@kortix/sdk 0.14.2 → 0.14.3
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 +16 -5
- package/dist/browser/session-sync/session-sync-registry.d.ts +6 -5
- package/dist/browser/session-sync/session-sync-registry.d.ts.map +1 -1
- package/dist/browser/session-sync/session-sync-registry.js +37 -5
- package/dist/browser/session-sync/session-sync-registry.js.map +1 -1
- package/dist/browser/stores/sync-store.d.ts +2 -2
- package/dist/browser/stores/sync-store.d.ts.map +1 -1
- package/dist/browser/stores/sync-store.js +2 -2
- package/dist/browser/stores/sync-store.js.map +1 -1
- package/dist/core/capture/rules.d.ts +6 -4
- package/dist/core/capture/rules.d.ts.map +1 -1
- package/dist/core/capture/rules.js +7 -5
- package/dist/core/capture/rules.js.map +1 -1
- package/dist/core/client/capture.d.ts +2 -0
- package/dist/core/client/capture.d.ts.map +1 -1
- package/dist/core/client/capture.js.map +1 -1
- package/dist/core/client/kortix.d.ts +8 -1
- package/dist/core/client/kortix.d.ts.map +1 -1
- package/dist/core/client/kortix.js +2 -0
- package/dist/core/client/kortix.js.map +1 -1
- package/dist/core/client/project-core.d.ts.map +1 -1
- package/dist/core/client/project-operations.d.ts +6 -0
- package/dist/core/client/project-operations.d.ts.map +1 -1
- package/dist/core/client/project-operations.js +4 -0
- package/dist/core/client/project-operations.js.map +1 -1
- package/dist/core/client/project-platform-security.d.ts +1 -1
- package/dist/core/client/project-platform-settings.d.ts +1 -1
- package/dist/core/models/composer-model.d.ts +3 -3
- package/dist/core/models/composer-model.js +4 -4
- package/dist/core/models/composer-model.js.map +1 -1
- package/dist/core/models/model-visibility.d.ts +2 -2
- package/dist/core/models/model-visibility.d.ts.map +1 -1
- package/dist/core/models/model-visibility.js +8 -8
- package/dist/core/models/model-visibility.js.map +1 -1
- package/dist/core/rest/platform-client/capture.d.ts +6 -1
- package/dist/core/rest/platform-client/capture.d.ts.map +1 -1
- package/dist/core/rest/platform-client/capture.js +6 -3
- package/dist/core/rest/platform-client/capture.js.map +1 -1
- package/dist/core/rest/platform-client/instance-admin.d.ts +1 -1
- package/dist/core/rest/platform-client/instance-admin.js +2 -2
- package/dist/core/rest/platform-client/instance-admin.js.map +1 -1
- package/dist/core/rest/platform-client/shared.js +1 -1
- package/dist/core/rest/platform-client/shared.js.map +1 -1
- package/dist/core/rest/platform-client/types.d.ts +5 -1
- package/dist/core/rest/platform-client/types.d.ts.map +1 -1
- package/dist/core/rest/platform-client/urls.d.ts +1 -1
- package/dist/core/rest/platform-client/urls.js +1 -1
- package/dist/core/rest/projects-client/apps.d.ts +2 -1
- package/dist/core/rest/projects-client/apps.d.ts.map +1 -1
- package/dist/core/rest/projects-client/apps.js.map +1 -1
- package/dist/core/rest/projects-client/channels.d.ts +19 -0
- package/dist/core/rest/projects-client/channels.d.ts.map +1 -1
- package/dist/core/rest/projects-client/channels.js +22 -0
- package/dist/core/rest/projects-client/channels.js.map +1 -1
- package/dist/core/rest/projects-client/connectors.d.ts +53 -1
- package/dist/core/rest/projects-client/connectors.d.ts.map +1 -1
- package/dist/core/rest/projects-client/connectors.js +12 -0
- package/dist/core/rest/projects-client/connectors.js.map +1 -1
- package/dist/core/rest/projects-client/drives.d.ts +18 -6
- package/dist/core/rest/projects-client/drives.d.ts.map +1 -1
- package/dist/core/rest/projects-client/drives.js +71 -3
- package/dist/core/rest/projects-client/drives.js.map +1 -1
- package/dist/core/rest/projects-client/notifications.d.ts +15 -0
- package/dist/core/rest/projects-client/notifications.d.ts.map +1 -1
- package/dist/core/rest/projects-client/notifications.js +27 -0
- package/dist/core/rest/projects-client/notifications.js.map +1 -1
- package/dist/core/rest/projects-client/projects.d.ts +1 -1
- package/dist/core/rest/projects-client/projects.d.ts.map +1 -1
- package/dist/core/rest/projects-client/projects.js +1 -0
- package/dist/core/rest/projects-client/projects.js.map +1 -1
- package/dist/core/rest/projects-client/sandbox.d.ts +8 -8
- package/dist/core/rest/projects-client/sandbox.d.ts.map +1 -1
- package/dist/core/rest/projects-client/session-sandbox.d.ts +1 -1
- package/dist/core/rest/projects-client/session-sandbox.d.ts.map +1 -1
- package/dist/core/rest/projects-client/sessions.d.ts +10 -5
- package/dist/core/rest/projects-client/sessions.d.ts.map +1 -1
- package/dist/core/rest/projects-client/sessions.js.map +1 -1
- package/dist/core/rest/projects-client/triggers.d.ts +76 -11
- package/dist/core/rest/projects-client/triggers.d.ts.map +1 -1
- package/dist/core/rest/projects-client/triggers.js +9 -1
- package/dist/core/rest/projects-client/triggers.js.map +1 -1
- package/dist/core/session/current-runtime.d.ts +1 -1
- package/dist/core/session/current-runtime.d.ts.map +1 -1
- package/dist/core/session/session-runtime-registry.d.ts +1 -1
- package/dist/core/session/session-runtime-registry.d.ts.map +1 -1
- package/dist/core/session/url.d.ts +1 -1
- package/dist/core/session/url.d.ts.map +1 -1
- package/dist/core/session-log/source.d.ts +4 -1
- package/dist/core/session-log/source.d.ts.map +1 -1
- package/dist/core/session-log/source.js +15 -10
- package/dist/core/session-log/source.js.map +1 -1
- package/dist/core/session-log/store.d.ts +7 -1
- package/dist/core/session-log/store.d.ts.map +1 -1
- package/dist/core/session-log/store.js +27 -8
- package/dist/core/session-log/store.js.map +1 -1
- package/dist/core/session-log/v1-view.d.ts +12 -0
- package/dist/core/session-log/v1-view.d.ts.map +1 -1
- package/dist/core/session-log/v1-view.js +14 -0
- package/dist/core/session-log/v1-view.js.map +1 -1
- package/dist/core/session-sync/saved-transcript.d.ts +16 -0
- package/dist/core/session-sync/saved-transcript.d.ts.map +1 -1
- package/dist/core/session-sync/saved-transcript.js +29 -13
- package/dist/core/session-sync/saved-transcript.js.map +1 -1
- package/dist/core/turns/segments/narration.js +1 -1
- package/dist/kortix.esm.min.js +34 -34
- package/dist/kortix.global.js +33 -33
- package/dist/react/opencode.d.ts +1 -1
- package/dist/react/opencode.d.ts.map +1 -1
- package/dist/react/opencode.js +1 -1
- package/dist/react/opencode.js.map +1 -1
- package/dist/react/query-keys.d.ts +1 -1
- package/dist/react/session-cache-write.d.ts.map +1 -1
- package/dist/react/session-cache-write.js +3 -0
- package/dist/react/session-cache-write.js.map +1 -1
- package/dist/react/sign-in-with-kortix.d.ts +1 -1
- package/dist/react/use-capture.d.ts +1 -0
- package/dist/react/use-capture.d.ts.map +1 -1
- package/dist/react/use-capture.js +5 -1
- package/dist/react/use-capture.js.map +1 -1
- package/dist/react/use-opencode-sessions/providers.d.ts.map +1 -1
- package/dist/react/use-opencode-sessions/providers.js +9 -11
- package/dist/react/use-opencode-sessions/providers.js.map +1 -1
- package/dist/react/use-session-log.d.ts +27 -5
- package/dist/react/use-session-log.d.ts.map +1 -1
- package/dist/react/use-session-log.js +114 -20
- package/dist/react/use-session-log.js.map +1 -1
- package/dist/react/use-session-sync.d.ts +7 -0
- package/dist/react/use-session-sync.d.ts.map +1 -1
- package/dist/react/use-session-sync.js +6 -6
- 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 +41 -20
- package/dist/react/use-session.js.map +1 -1
- package/dist/react/use-tunnel.d.ts +3 -0
- package/dist/react/use-tunnel.d.ts.map +1 -1
- package/dist/react/use-tunnel.js.map +1 -1
- package/package.json +2 -2
package/dist/kortix.esm.min.js
CHANGED
|
@@ -1,24 +1,24 @@
|
|
|
1
|
-
var DS={backendUrl:"",getToken:async()=>null},Vs=null,tr=null;function AM(e){tr=e}function RM(){return tr}function Hs(e,t){t?.global!==!1&&(Vs=e)}function I(){return tr?.()??Vs??DS}function zs(){return Vs!==null||tr?.()!==void 0}function jS(e){return new Promise(t=>setTimeout(t,e))}async function nr(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 jS(s)),i=await e(),i)return i;return i}var Ys=12e4;function LS(e){return(e instanceof Request?e.url:String(e)).includes("/global/event")}function $a(e,t,n=Ys){let r=e instanceof Request?e.signal:t?.signal;if(LS(e))return r??void 0;let s=AbortSignal.timeout(n);return r?typeof AbortSignal.any=="function"?AbortSignal.any([r,s]):r:s}function rr(){return new Response(JSON.stringify({error:"Not authenticated"}),{status:401,headers:{"Content-Type":"application/json"}})}var x=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 x{constructor(t="Not authenticated"){super(t,{code:"NO_SESSION"}),this.name="AuthError"}},ct=class extends x{constructor(t,n,r,s={}){super(r||n.message||`Billing Error: ${t}`,{...s,status:t,detail:n}),this.name="BillingError"}},kt=class extends x{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"}},$S="ENDPOINT_RETIRED";function U(e,t){let n=t?` ${t}`:"";return new x(`${e}() is retired: the Kortix API no longer serves this endpoint.${n}`,{code:$S})}var Js="feature_disabled";function Ua(e){if(!(e instanceof x)||e.status!==403||e.code!==Js)return null;let t=e.details??e.data;return t&&typeof t=="object"?t:{}}function Fa(e){let t=Ua(e);return t?(typeof t.feature=="string"&&!e.feature&&(e.feature=t.feature),!0):!1}function Na(e){let t=Ua(e);if(!t)return null;let n=e.feature;return typeof n=="string"?n:typeof t.feature=="string"?t.feature:null}function sr(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 ct(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 Ka(e){return e instanceof ct}function Xt(e){if(e instanceof ie)return!0;let t=e?.status;return t===401||t===403}function Ba(e){if(!(e instanceof ct))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 or(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 qa="request_deadline",US=/^Request exceeded the \d+s server processing deadline$/,Ga=(e,t,n)=>e!==503?!1:(typeof t=="object"&&t!==null&&"code"in t?t.code:void 0)===qa||US.test(n),FS="git_mirror_unavailable",NS=/^git mirror is temporarily unavailable$/,KS=(e,t,n)=>e!==503?!1:(typeof t=="object"&&t!==null&&"code"in t?t.code:void 0)===FS||NS.test(n),BS="connectors_provider_unavailable",qS=(e,t)=>e!==503?!1:(typeof t=="object"&&t!==null&&"code"in t?t.code:void 0)===BS;async function GS(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 WS(e,t,n){return Ga(e,t,n)||KS(e,t,n)||qS(e,t)||e===501&&t?.code===Va||e===409&&(t?.code===Ha||t?.code===za||t?.code===Ya)||e===503&&(t?.code===Ja||t?.code===Qa)}async function Wa(e,t,n,r){let{message:s,data:o}=await GS(e,t),i=new x(s,{status:e.status,response:e,details:o||void 0,data:o,detail:o?.detail,code:Ga(e.status,o,s)?qa:o?.code||o?.error_code||o?.detail?.error_code||e.status.toString()});e.status===402&&(i=sr(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&&!WS(e.status,o,s)&&I().onError?.(i,r),{error:i,success:!1}}var VS="X-Kortix-Impersonate",Xs="kortix.impersonation",lt=null,ir=!1,Qs=new Set;function Zs(){try{return typeof sessionStorage>"u"?null:sessionStorage}catch{return null}}function HS(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 zS(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 Xa(){for(let e of Qs)try{e()}catch{}}function YS(){return ir||(ir=!0,lt=zS(Zs()?.getItem(Xs)??null)),lt&&!HS(lt)?(Za(),null):lt}function $M(e){if(ir=!0,!e){Za();return}lt=e;try{Zs()?.setItem(Xs,JSON.stringify(e))}catch{}Xa()}function Za(){ir=!0;let e=lt!==null;lt=null;try{Zs()?.removeItem(Xs)}catch{}e&&Xa()}function UM(e){return Qs.add(e),()=>{Qs.delete(e)}}var JS=/(^|\/)admin\/(api|analytics)(\/|$)/;function QS(e){let t=e;if(/^https?:\/\//.test(e))try{t=new URL(e).pathname}catch{t=e}return!JS.test(t)}function ec(e){if(e!==void 0&&!QS(e))return{};let t=YS();return t?{[VS]:t.grantId}:{}}function XS(e){}function ZS(){return!1}function ex(e){return e?e instanceof Headers||Array.isArray(e)?[...new Headers(e).entries()]:Object.entries(e):[]}function ar(e,t){let n=t.toLowerCase();return Object.keys(e).some(r=>r.toLowerCase()===n)}function Zt(e,t,n){let r=t.toLowerCase();for(let s of Object.keys(e))s.toLowerCase()===r&&delete e[s];e[t]=n}function cr(e,t){let n={},r=[e instanceof Request?e.headers:void 0,t.headers];for(let[s,o]of r.flatMap(ex))Zt(n,s,o);return n}function to(e,t,n){let r={...t},s=I().clientVersion?.trim();s&&!ar(r,"x-kortix-client-version")&&Zt(r,"X-Kortix-Client-Version",s);for(let[i,a]of Object.entries(ec(e)))Zt(r,i,a);let o=I().credentialHeader?.trim();return o?ar(r,o)||Zt(r,o,n):ar(r,"authorization")||Zt(r,"Authorization",`Bearer ${n}`),r}async function ur(e,t){let n=await lr();if(!n)throw new ie;return{headers:new Headers(to(e,cr(e,{headers:t}),n)),rejected:()=>en(n)}}function tx(e){return typeof ReadableStream<"u"&&e.body instanceof ReadableStream}function tc(e,t,n,r,s){if(t instanceof Request){let c=new Headers(to(t.url,cr(t,n),r));return e(new Request(t,{headers:c,...s?{signal:s}:{}}))}let o=String(t),i=to(o,cr(t,n),r),a=o.startsWith("/")&&!o.startsWith("//");return e(o,{...n,headers:i,...a?{credentials:"same-origin"}:{},...s?{signal:s}:{}})}var nc=null;async function no(e){let t=await nr(()=>I().getToken(),e);return t&&(nc=t),t}var lr=no;function en(e=nc){e&&I().getToken.invalidate?.(e)}var eo=new Map;function nx(e){let t=eo.get(e);if(t)return t;let n=(async()=>(en(e),lr({attempts:2,baseDelayMs:200})))().finally(()=>eo.delete(e));return eo.set(e,n),n}async function ut(e,t={},n={}){let{retryOnAuthError:r=!0,timeoutMs:s=Ys}=n,o=n.fetch??I().fetch??fetch,i=s===null?(e instanceof Request?e.signal:t.signal)??void 0:$a(e,t,s);if(i?.aborted)throw ke();let a=await(i?ve(lr(),i):lr());if(!a)throw new ie;let c=r&&!tx(t)&&!ar(cr(e,t),"authorization"),p=c&&e instanceof Request?e.clone():e,d=await tc(o,e,t,a,i);if(d.status!==401||!c)return d;let g=await nx(a);return!g||g===a?d:tc(o,p,t,g,i)}async function Oe(e,t,n,r){let s=await ut(e,t,n);if(s.ok)return s;let o=await s.text().catch(()=>"");throw new x(o||`${r} (HTTP ${s.status})`,{status:s.status,response:s})}var rc=()=>I().backendUrl||"",rx=new Set([502,503,504]),sx=e=>rx.has(e),sc=e=>{let t=(e??"GET").toUpperCase();return t==="GET"||t==="HEAD"},ox=e=>sc(e)||(e??"GET").toUpperCase()==="DELETE",ix=2,pr=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,c={activeController:a,timeoutId:null,isAborted:!1,didTimeout:!1},p=()=>c.activeController.abort();i.signal?.addEventListener("abort",p,{once:!0});try{return await ax(e,i,n,r,s,o,a,c)}finally{i.signal?.removeEventListener("abort",p)}}async function ax(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 c={...t.body instanceof FormData?{}:{"Content-Type":"application/json"},...t.headers},p=await lx(e,t,c,s,o,i,a);if(p instanceof ie)return{error:p,success:!1};if(!p.ok)return await Wa(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(c){return ux(c,e,t.method,n,r,s,a)}finally{dr(a)}}function dr(e){e.timeoutId&&clearTimeout(e.timeoutId),e.timeoutId=null}async function cx(e,t,n){try{await ve(e.arrayBuffer(),t)}catch(r){if(pr(r))throw r}finally{dr(n)}}async function lx(e,t,n,r,s,o,i){let a=sc(t.method),c=ox(t.method),p=c?ix+1:1,d;for(let g=0;g<p;g++){g>0&&await or(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(ut(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&&pr(f)&&!t.signal?.aborted&&c&&g<p-1){i.didTimeout=!1;continue}if(pr(f)||g===p-1)throw f;continue}if(!a||!sx(d.status)||g===p-1)return s||dr(i),d;await cx(d,m.signal,i)}return d}function ux(e,t,n,r,s,o,i){dr(i);let a=pr(e);a&&(i.isAborted=!0);let c;if(a){if(!i.didTimeout)return{error:new x("Request aborted",{name:"AbortError",code:"ABORTED"}),success:!1};let p=t.replace(rc(),"")||t;c=new x(`Request timed out after ${Math.round(o/1e3)}s: ${p}`,{code:"TIMEOUT",url:t,endpoint:p,timeout:o})}else e instanceof Error?(c=new x(n==="POST"&&e instanceof TypeError&&e.message==="Failed to fetch"?`Failed to fetch: POST ${t.replace(rc(),"")||t}`:e.message,{name:e.name||"ApiError",stack:e.stack}),r&&I().onError?.(c,s)):(c=new x(String(e)),r&&I().onError?.(c,s));return{error:c,success:!1}}var je=()=>I().backendUrl||"",Va="feature_not_supported",Ha="model_not_servable",za="provision_in_flight",Ya="sandbox_state_change_in_progress",Ja="analytics_unavailable",Qa="accounts_list_unavailable",rO={async execute(e,t){try{let{data:n,error:r}=await e();if(r){let s=new x(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 x(n.message,{name:n.name||"ApiError",stack:n.stack}):new x(String(n));return I().onError?.(r,t),{error:r,success:!1}}}};async function px(e,t,n={}){let{timeout:r=3e4,fetch:s}=n,o=new AbortController,i=setTimeout(()=>o.abort(),r);try{return await ut(`${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 rr();throw a}finally{clearTimeout(i)}}var l={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:px};function u(e,t="Project request failed"){if(!e.success||e.data===void 0)throw e.error??new Error(t);return e.data}function ro(e){return e.replace(/\/v1\/?$/,"")}async function vt(e,t){if(!e.backendUrl||!e.accessToken)return null;let n=ro(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 oc(){return u(await l.get("/accounts"))}async function ic(e){return u(await l.post("/accounts",e))}async function ac(e){return u(await l.get(`/accounts/${e}`))}async function cc(e,t){return u(await l.patch(`/accounts/${e}`,{name:t}))}async function lc(e){return u(await l.get(`/accounts/${e}/branding`))}async function uc(e,t){return u(await l.put(`/accounts/${e}/branding`,t))}async function pc(e,t,n,r){let s=new FormData;return s.append("file",n,r??(n instanceof File?n.name:t)),u(await l.upload(`/accounts/${e}/branding/assets/${t}`,s))}async function dc(e,t){return u(await l.delete(`/accounts/${e}/branding/assets/${t}`))}async function gc(e){return u(await l.delete(`/accounts/${e}/branding`))}async function mc(e){return u(await l.get(`/accounts/${e}/members`))}async function fc(e,t){return u(await l.post(`/accounts/${e}/members`,t,{showErrors:!1}))}async function yc(e){return u(await l.get(`/accounts/${e}/invites`))}async function hc(e,t){return u(await l.delete(`/accounts/${e}/invites/${t}`))}async function _c(e,t){return u(await l.post(`/accounts/${e}/invites/${t}/resend`,{}))}async function bc(){return u(await l.get("/account-invites",{showErrors:!1})).invites}async function Pc(e){return u(await l.get(`/account-invites/${e}`,{showErrors:!1}))}async function so(e){return u(await l.post(`/account-invites/${e}/accept`,{}))}function dx(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 Sc(e,t){let n=await so(e);return{accepted:n,landing:dx(n,t)}}async function xc(e){return u(await l.post(`/account-invites/${e}/decline`,{}))}async function wc(e,t){return u(await l.delete(`/accounts/${e}/members/${t}`))}async function kc(e,t,n){return u(await l.patch(`/accounts/${e}/members/${t}`,{role:n}))}async function vc(e){return u(await l.post(`/accounts/${e}/leave`,{}))}async function uO(e){return vt(e,"/v1/accounts")}async function Ac(){let e=await l.get("/accounts/me",{showErrors:!1});return!e.success||!e.data?{valid:!1,error:e.error}:{valid:!0,identity:e.data}}var fO=["marketplace","connectors_api_discover","agentmail_email","llm_gateway","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"];async function At(){return u(await l.get("/projects"))}async function Cc(e){let t=e?`?account_id=${encodeURIComponent(e)}`:"";return u(await l.get(`/projects${t}`))}async function Rt(e,t){return u(await l.get(`/projects/${e}`,t))}async function Tc(e,t,n="write"){return u(await l.post(`/projects/${e}/git/collaborators`,{github_username:t,permission:n}))}async function Ic(e,t){return u(await l.post(`/projects/${e}/manifest/validate`,{raw:t}),"Failed to validate manifest")}async function Ec(e){return u(await l.post(`/projects/${e}/git-token`,{}),"Failed to mint git token")}function yO(e){let t=e.metadata?.git;return t?.provider==="github"&&t?.managed===!0}async function gr(e,t){let n=u(await l.get(`/projects/${e}/detail`,{showErrors:!1,...t}));return{...n,config:{...n.config,default_agent:n.config.default_agent??n.config.open_code_default_agent??null}}}async function mr(e,t){return u(await l.get(`/projects/${e}/llm-catalog`,{showErrors:!1,...t}))}async function fr(e,t){return u(await l.get(`/projects/${e}/model-picker`,{showErrors:!1,...t}))}async function hO(e,t){return u(await l.get(`/projects/${e}/llm-catalog/providers`,{showErrors:!1,...t}))}async function Mc(e){return u(await l.post("/projects",e))}async function Oc(e){return u(await l.post("/projects/create-repo",e,{showErrors:!1}))}async function Dc(e,t={}){return u(await l.post("/projects/provision",{seed_starter:!0,...e},{timeout:12e4,...t}))}var gx="provision_stream_unterminated",Rc=200;function mx(e){let t=e.split(`
|
|
1
|
+
var GP={backendUrl:"",getToken:async()=>null},Hs=null,sr=null;function $M(e){sr=e}function UM(){return sr}function zs(e,t){t?.global!==!1&&(Hs=e)}function T(){return sr?.()??Hs??GP}function Ys(){return Hs!==null||sr?.()!==void 0}function WP(e){return new Promise(t=>setTimeout(t,e))}async function or(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 WP(s)),i=await e(),i)return i;return i}var Js=12e4;function VP(e){return(e instanceof Request?e.url:String(e)).includes("/global/event")}function Fa(e,t,n=Js){let r=e instanceof Request?e.signal:t?.signal;if(VP(e))return r??void 0;let s=AbortSignal.timeout(n);return r?typeof AbortSignal.any=="function"?AbortSignal.any([r,s]):r:s}function ir(){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"}},lt=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"}},HP="ENDPOINT_RETIRED";function U(e,t){let n=t?` ${t}`:"";return new P(`${e}() is retired: the Kortix API no longer serves this endpoint.${n}`,{code:HP})}var Qs="feature_disabled";function Na(e){if(!(e instanceof P)||e.status!==403||e.code!==Qs)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}function ar(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 lt(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 lt}function en(e){if(e instanceof ie)return!0;let t=e?.status;return t===401||t===403}function Ga(e){if(!(e instanceof lt))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 cr(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",zP=/^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)===Wa||zP.test(n),YP="git_mirror_unavailable",JP=/^git mirror is temporarily unavailable$/,QP=(e,t,n)=>e!==503?!1:(typeof t=="object"&&t!==null&&"code"in t?t.code:void 0)===YP||JP.test(n),XP="connectors_provider_unavailable",ZP=(e,t)=>e!==503?!1:(typeof t=="object"&&t!==null&&"code"in t?t.code:void 0)===XP;async function ex(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 tx(e,t,n){return Va(e,t,n)||QP(e,t,n)||ZP(e,t)||e===501&&t?.code===za||e===409&&(t?.code===Ya||t?.code===Ja||t?.code===Qa)||e===503&&(t?.code===Xa||t?.code===Za)}async function Ha(e,t,n,r){let{message:s,data:o}=await ex(e,t),i=new P(s,{status:e.status,response:e,details:o||void 0,data:o,detail:o?.detail,code:Va(e.status,o,s)?Wa:o?.code||o?.error_code||o?.detail?.error_code||e.status.toString()});e.status===402&&(i=ar(i));let a=e.status===403&&(o?.code==="account_mfa_required"||o?.code==="sso_required")?o.code:null;if(a){try{T().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&&!tx(e.status,o,s)&&T().onError?.(i,r),{error:i,success:!1}}var nx="X-Kortix-Impersonate",Zs="kortix.impersonation",ut=null,lr=!1,Xs=new Set;function eo(){try{return typeof sessionStorage>"u"?null:sessionStorage}catch{return null}}function rx(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 sx(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 Xs)try{e()}catch{}}function ox(){return lr||(lr=!0,ut=sx(eo()?.getItem(Zs)??null)),ut&&!rx(ut)?(tc(),null):ut}function zM(e){if(lr=!0,!e){tc();return}ut=e;try{eo()?.setItem(Zs,JSON.stringify(e))}catch{}ec()}function tc(){lr=!0;let e=ut!==null;ut=null;try{eo()?.removeItem(Zs)}catch{}e&&ec()}function YM(e){return Xs.add(e),()=>{Xs.delete(e)}}var ix=/(^|\/)admin\/(api|analytics)(\/|$)/;function ax(e){let t=e;if(/^https?:\/\//.test(e))try{t=new URL(e).pathname}catch{t=e}return!ix.test(t)}function nc(e){if(e!==void 0&&!ax(e))return{};let t=ox();return t?{[nx]:t.grantId}:{}}function cx(e){}function lx(){return!1}function ux(e){return e?e instanceof Headers||Array.isArray(e)?[...new Headers(e).entries()]:Object.entries(e):[]}function ur(e,t){let n=t.toLowerCase();return Object.keys(e).some(r=>r.toLowerCase()===n)}function tn(e,t,n){let r=t.toLowerCase();for(let s of Object.keys(e))s.toLowerCase()===r&&delete e[s];e[t]=n}function pr(e,t){let n={},r=[e instanceof Request?e.headers:void 0,t.headers];for(let[s,o]of r.flatMap(ux))tn(n,s,o);return n}function no(e,t,n){let r={...t},s=T().clientVersion?.trim();s&&!ur(r,"x-kortix-client-version")&&tn(r,"X-Kortix-Client-Version",s);for(let[i,a]of Object.entries(nc(e)))tn(r,i,a);let o=T().credentialHeader?.trim();return o?ur(r,o)||tn(r,o,n):ur(r,"authorization")||tn(r,"Authorization",`Bearer ${n}`),r}async function vt(e,t){let n=await dr();if(!n)throw new ie;return{headers:new Headers(no(e,pr(e,{headers:t}),n)),rejected:()=>nn(n)}}function px(e){return typeof ReadableStream<"u"&&e.body instanceof ReadableStream}function rc(e,t,n,r,s){if(t instanceof Request){let c=new Headers(no(t.url,pr(t,n),r));return e(new Request(t,{headers:c,...s?{signal:s}:{}}))}let o=String(t),i=no(o,pr(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 ro(e){let t=await or(()=>T().getToken(),e);return t&&(sc=t),t}var dr=ro;function nn(e=sc){e&&T().getToken.invalidate?.(e)}var to=new Map;function dx(e){let t=to.get(e);if(t)return t;let n=(async()=>(nn(e),dr({attempts:2,baseDelayMs:200})))().finally(()=>to.delete(e));return to.set(e,n),n}async function pt(e,t={},n={}){let{retryOnAuthError:r=!0,timeoutMs:s=Js}=n,o=n.fetch??T().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(dr(),i):dr());if(!a)throw new ie;let c=r&&!px(t)&&!ur(pr(e,t),"authorization"),p=c&&e instanceof Request?e.clone():e,d=await rc(o,e,t,a,i);if(d.status!==401||!c)return d;let g=await dx(a);return!g||g===a?d:rc(o,p,t,g,i)}async function Oe(e,t,n,r){let s=await pt(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=()=>T().backendUrl||"",gx=new Set([502,503,504]),mx=e=>gx.has(e),ic=e=>{let t=(e??"GET").toUpperCase();return t==="GET"||t==="HEAD"},fx=e=>ic(e)||(e??"GET").toUpperCase()==="DELETE",yx=2,gr=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,c={activeController:a,timeoutId:null,isAborted:!1,didTimeout:!1},p=()=>c.activeController.abort();i.signal?.addEventListener("abort",p,{once:!0});try{return await hx(e,i,n,r,s,o,a,c)}finally{i.signal?.removeEventListener("abort",p)}}async function hx(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 c={...t.body instanceof FormData?{}:{"Content-Type":"application/json"},...t.headers},p=await bx(e,t,c,s,o,i,a);if(p instanceof ie)return{error:p,success:!1};if(!p.ok)return await Ha(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(c){return Sx(c,e,t.method,n,r,s,a)}finally{mr(a)}}function mr(e){e.timeoutId&&clearTimeout(e.timeoutId),e.timeoutId=null}async function _x(e,t,n){try{await ve(e.arrayBuffer(),t)}catch(r){if(gr(r))throw r}finally{mr(n)}}async function bx(e,t,n,r,s,o,i){let a=ic(t.method),c=fx(t.method),p=c?yx+1:1,d;for(let g=0;g<p;g++){g>0&&await cr(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(pt(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&&gr(f)&&!t.signal?.aborted&&c&&g<p-1){i.didTimeout=!1;continue}if(gr(f)||g===p-1)throw f;continue}if(!a||!mx(d.status)||g===p-1)return s||mr(i),d;await _x(d,m.signal,i)}return d}function Sx(e,t,n,r,s,o,i){mr(i);let a=gr(e);a&&(i.isAborted=!0);let c;if(a){if(!i.didTimeout)return{error:new P("Request aborted",{name:"AbortError",code:"ABORTED"}),success:!1};let p=t.replace(oc(),"")||t;c=new P(`Request timed out after ${Math.round(o/1e3)}s: ${p}`,{code:"TIMEOUT",url:t,endpoint:p,timeout:o})}else e instanceof Error?(c=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&&T().onError?.(c,s)):(c=new P(String(e)),r&&T().onError?.(c,s));return{error:c,success:!1}}var je=()=>T().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",mO={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 T().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 T().onError?.(r,t),{error:r,success:!1}}}};async function Px(e,t,n={}){let{timeout:r=3e4,fetch:s}=n,o=new AbortController,i=setTimeout(()=>o.abort(),r);try{return await pt(`${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 ir();throw a}finally{clearTimeout(i)}}var l={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:Px};function u(e,t="Project request failed"){if(!e.success||e.data===void 0)throw e.error??new Error(t);return e.data}function so(e){return e.replace(/\/v1\/?$/,"")}async function At(e,t){if(!e.backendUrl||!e.accessToken)return null;let n=so(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 l.get("/accounts"))}async function cc(e){return u(await l.post("/accounts",e))}async function lc(e){return u(await l.get(`/accounts/${e}`))}async function uc(e,t){return u(await l.patch(`/accounts/${e}`,{name:t}))}async function pc(e){return u(await l.get(`/accounts/${e}/branding`))}async function dc(e,t){return u(await l.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 l.upload(`/accounts/${e}/branding/assets/${t}`,s))}async function mc(e,t){return u(await l.delete(`/accounts/${e}/branding/assets/${t}`))}async function fc(e){return u(await l.delete(`/accounts/${e}/branding`))}async function yc(e){return u(await l.get(`/accounts/${e}/members`))}async function hc(e,t){return u(await l.post(`/accounts/${e}/members`,t,{showErrors:!1}))}async function _c(e){return u(await l.get(`/accounts/${e}/invites`))}async function bc(e,t){return u(await l.delete(`/accounts/${e}/invites/${t}`))}async function Sc(e,t){return u(await l.post(`/accounts/${e}/invites/${t}/resend`,{}))}async function Pc(){return u(await l.get("/account-invites",{showErrors:!1})).invites}async function xc(e){return u(await l.get(`/account-invites/${e}`,{showErrors:!1}))}async function oo(e){return u(await l.post(`/account-invites/${e}/accept`,{}))}function xx(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 oo(e);return{accepted:n,landing:xx(n,t)}}async function kc(e){return u(await l.post(`/account-invites/${e}/decline`,{}))}async function vc(e,t){return u(await l.delete(`/accounts/${e}/members/${t}`))}async function Ac(e,t,n){return u(await l.patch(`/accounts/${e}/members/${t}`,{role:n}))}async function Rc(e){return u(await l.post(`/accounts/${e}/leave`,{}))}async function PO(e){return At(e,"/v1/accounts")}async function Tc(){let e=await l.get("/accounts/me",{showErrors:!1});return!e.success||!e.data?{valid:!1,error:e.error}:{valid:!0,identity:e.data}}var AO=["marketplace","connectors_api_discover","agentmail_email","llm_gateway","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"];async function Rt(){return u(await l.get("/projects"))}async function Ic(e){let t=e?`?account_id=${encodeURIComponent(e)}`:"";return u(await l.get(`/projects${t}`))}async function Tt(e,t){return u(await l.get(`/projects/${e}`,t))}async function Ec(e,t,n="write"){return u(await l.post(`/projects/${e}/git/collaborators`,{github_username:t,permission:n}))}async function Mc(e,t){return u(await l.post(`/projects/${e}/manifest/validate`,{raw:t}),"Failed to validate manifest")}async function Oc(e){return u(await l.post(`/projects/${e}/git-token`,{}),"Failed to mint git token")}function RO(e){let t=e.metadata?.git;return t?.provider==="github"&&t?.managed===!0}async function fr(e,t){let n=u(await l.get(`/projects/${e}/detail`,{showErrors:!1,...t}));return{...n,config:{...n.config,default_agent:n.config.default_agent??n.config.open_code_default_agent??null}}}async function yr(e,t){return u(await l.get(`/projects/${e}/llm-catalog`,{showErrors:!1,...t}))}async function hr(e,t){return u(await l.get(`/projects/${e}/model-picker`,{showErrors:!1,...t}))}async function TO(e,t){return u(await l.get(`/projects/${e}/llm-catalog/providers`,{showErrors:!1,...t}))}async function Dc(e){return u(await l.post("/projects",e))}async function jc(e){return u(await l.post("/projects/create-repo",e,{showErrors:!1}))}async function Lc(e,t={}){return u(await l.post("/projects/provision",{seed_starter:!0,...e},{timeout:12e4,...t}))}var wx="provision_stream_unterminated",Cc=200;function kx(e){let t=e.split(`
|
|
2
2
|
`).filter(r=>r.startsWith("data:")).map(r=>r.slice(5).replace(/^ /,""));if(t.length===0)return null;let n=t.join(`
|
|
3
|
-
`);try{return JSON.parse(n)}catch(r){let s=n.length>
|
|
3
|
+
`);try{return JSON.parse(n)}catch(r){let s=n.length>Cc?`${n.slice(0,Cc)}\u2026`:n;throw new Error(`provisionProjectStream: received an unparseable SSE frame (${s})`,{cause:r})}}async function CO(e,t,n={}){let r=await l.postStream("/projects/provision-stream",{seed_starter:!0,...e},n);if(!r.ok){let c=await r.json().catch(()=>null);throw new P(c?.error||`Provision failed: HTTP ${r.status}`,{status:r.status,code:c?.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:c,value:p}=await s.read();if(c)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=mx(g);if(m){if(t(m),m.type==="error")throw new x(m.error,{status:m.status,code:m.code});m.type==="done"&&(a=m.project)}}}}finally{s.cancel().catch(()=>{})}if(!a)throw new x("Provision stream ended without a result",{code:gx});return a}async function bO(e){let t=e?.accountId?`?account_id=${encodeURIComponent(e.accountId)}`:"";return u(await l.get(`/projects/quota${t}`))}async function PO(){try{return u(await l.get("/projects/managed-git/status",{showErrors:!1}))}catch{return{configured:!1,provider:"github"}}}async function yr(e,t){return u(await l.patch(`/projects/${e}`,t))}async function jc(e,t,n){return u(await l.patch(`/projects/${e}/features`,{feature:t,enabled:n}))}async function Lc(e,t,n){return u(await l.patch(`/projects/${e}/experimental`,{feature:t,enabled:n}))}async function $c(e,t){return u(await l.patch(`/projects/${e}/sandbox-provider`,{provider:t}))}async function SO(e,t){return u(await l.get(`/projects/${e}/sandbox-provider/transition`,{showErrors:!1,...t}))}async function xO(e,t){throw U("updateTemplateWarmPool")}async function Uc(e,t){return u(await l.patch(`/projects/${e}/onboarding`,{completed:t}))}async function wO(e,t){return u(await l.patch(`/projects/${e}/onboarding`,{profile:t}))}async function hr(e){return u(await l.delete(`/projects/${e}`))}async function kO(e,t){return vt(e,`/v1/projects?account_id=${encodeURIComponent(t)}`)}async function vO(e,t){if(!e.backendUrl||!e.accessToken)return{ok:!1,limitReached:!1};let n=ro(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 Fc(e,t,n){return u(await l.post(`/projects/${e}/skills`,t,{showErrors:!1,...n}))}async function Nc(e){return u(await l.post("/projects/link-repository",e,{showErrors:!1}))}async function Kc(e){let{project_id:t,...n}=e;return u(await l.put(`/projects/${encodeURIComponent(t)}/git/repository`,n,{showErrors:!1}))}async function Bc(e){return u(await l.get(`/projects/github/installation?account_id=${encodeURIComponent(e)}`,{showErrors:!1}))}async function qc(e){return u(await l.get(`/projects/github/installations?account_id=${encodeURIComponent(e)}`,{showErrors:!1}))}async function Gc(e){return u(await l.post("/projects/github/installations/linkable",e,{showErrors:!1}))}async function Wc(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 l.get(`/projects/github/repositories?${r.toString()}`,{showErrors:!1}))}async function Vc(e,t,n){let r=new URLSearchParams({account_id:e,installation_id:t,repo_full_name:n});return u(await l.get(`/projects/github/repository-branches?${r.toString()}`,{showErrors:!1}))}async function Hc(e){return u(await l.post("/projects/github/installation",e,{showErrors:!1}))}async function zc(e){return u(await l.post("/projects/github/installations/link",e,{showErrors:!1}))}async function Yc(e){return u(await l.post("/projects/github/user-token",e,{showErrors:!1}))}async function Jc(e,t){let n=new URLSearchParams({account_id:e});return t&&n.set("installation_id",t),u(await l.delete(`/projects/github/installation?${n.toString()}`))}async function Qc(){return u(await l.get("/projects/git/backend",{showErrors:!1}))}async function Xc(e){let t=new URLSearchParams,n=e?.search?.trim();n&&t.set("search",n),e?.limit!==void 0&&t.set("limit",String(e.limit));let r=t.toString();return u(await l.get(`/projects/git/backend/repositories${r?`?${r}`:""}`,{showErrors:!1}))}async function UO(e,t){return u(await l.post(`/projects/${e}/access-requests`,{message:t?.trim()||void 0},{showErrors:!1}))}async function Zc(e,t){return u(await l.get(`/projects/${e}/access-requests`,t))}async function el(e,t,n="member"){return u(await l.post(`/projects/${e}/access-requests/${t}/approve`,{role:n}))}async function tl(e,t){return u(await l.post(`/projects/${e}/access-requests/${t}/reject`,{}))}async function nl(e){return u(await l.get(`/projects/${e}/access`))}async function rl(e,t,n){return u(await l.put(`/projects/${e}/access/${t}`,{role:n}))}async function sl(e,t){return u(await l.delete(`/projects/${e}/access/${t}`))}function FO(e){return"status"in e&&e.status==="invited"}async function ol(e,t,n,r){return u(await l.post(`/projects/${e}/access/invite`,{email:t,role:n,...r!==void 0?{expires_at:r}:{}}))}async function il(e){return u(await l.get(`/projects/${e}/access/pending-invites`))}async function al(e,t){return u(await l.delete(`/projects/${e}/access/pending-invites/${t}`))}async function cl(e,t){return u(await l.post(`/projects/${e}/access/pending-invites/${t}/resend`))}async function ll(e){return u(await l.get(`/projects/${e}/group-grants`))}async function ul(e,t,n,r){return u(await l.post(`/projects/${e}/group-grants`,r===void 0?{group_id:t,role:n}:{group_id:t,role:n,expires_at:r}))}async function pl(e,t,n,r){return u(await l.patch(`/projects/${e}/group-grants/${t}`,r===void 0?{role:n}:{role:n,expires_at:r}))}async function dl(e,t){return u(await l.delete(`/projects/${e}/group-grants/${t}`))}async function gl(e){return u(await l.get(`/projects/${e}/resource-grants`))}async function ml(e,t){return u(await l.post(`/projects/${e}/resource-grants`,{resource_type:t.resourceType,resource_id:t.resourceId,principal_type:t.principalType,principal_id:t.principalId,...t.expiresAt!==void 0?{expires_at:t.expiresAt}:{}}))}async function fl(e,t){return u(await l.delete(`/projects/${e}/resource-grants/${t}`))}async function yl(e,t){return u(await l.get(`/projects/${e}/approvals`,{showErrors:t?.showErrors}))}async function hl(e,t){return u(await l.get(`/projects/${e}/approvals/needs-input`,{showErrors:t?.showErrors}))}async function _l(e,t,n,r={}){let s=r.note?.trim();return u(await l.post(`/projects/${e}/approvals/${t}`,{decision:n,...s?{note:s}:{}}))}async function bl(e){return u(await l.get(`/projects/${e}/secrets`,{showErrors:!1}))}async function Pl(e,t){return u(await l.post(`/projects/${e}/secrets`,t))}async function Sl(e,t,n,r={}){return u(await l.put(`/projects/${e}/secrets/${encodeURIComponent(t)}/strategy`,{strategy:n,...r}))}async function xl(e,t,n){return u(await l.post(`/projects/${e}/secrets/${encodeURIComponent(t)}/broker`,n))}async function wl(e){return u(await l.get(`/projects/${e}/oauth`)).items??[]}async function oo(e,t,n){return u(await l.post(`/projects/${e}/oauth/${t}/start`,{sharing:n?.sharing,...n?.resourceLabel===void 0?{}:{resource_label:n.resourceLabel},...n?.resourceId===void 0?{}:{resource_id:n.resourceId}}))}async function io(e,t,n){return u(await l.post(`/projects/${e}/oauth/${t}/poll`,{flow_id:n}))}async function kl(e,t){return u(await l.delete(`/projects/${e}/oauth/${encodeURIComponent(t)}`))}var fx=2e3,yx=3e3,hx=10*6e4;async function qO(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,c=()=>o?.()??!1,p=await oo(t,n,r);if(c())return{status:"cancelled"};s?.({verification_url:p.verification_url,user_code:p.user_code});let d=Math.max(fx,p.interval_ms||yx),g=p.expires_at||a()+hx;for(;!c()&&a()<g;){if(await i(d),c())return{status:"cancelled"};let m;try{m=await io(t,n,p.flow_id)}catch{continue}if(c())return{status:"cancelled"};if(m.status==="success")return{status:"success",credential:m.credential};if(m.status==="failed")return{status:"failed",error:m.error};if(m.status==="expired")return{status:"expired"}}return c()?{status:"cancelled"}:{status:"expired"}}async function vl(e,t){return u(await l.put(`/projects/${e}/git-credential`,t))}async function Al(e,t){return u(await l.delete(`/projects/${e}/secrets/${encodeURIComponent(t)}`))}async function Rl(e,t,n){return u(await l.put(`/projects/${e}/secrets/${encodeURIComponent(t)}/personal`,n))}async function Cl(e,t){return u(await l.delete(`/projects/${e}/secrets/${encodeURIComponent(t)}/personal`))}var ao=e=>`/accounts/${encodeURIComponent(e)}/secret-resources`,Ct=(e,t)=>`${ao(e)}/${encodeURIComponent(t)}`,Tl=(e,t,n)=>`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/provider-secret-pools/${encodeURIComponent(n)}`;async function Il(e,t){let n=t?`?project_id=${encodeURIComponent(t)}`:"";return u(await l.get(`${ao(e)}${n}`))}async function El(e,t){return u(await l.post(ao(e),t))}async function Ml(e,t,n){return u(await l.put(`${Ct(e,t)}/value`,{value:n}))}async function Ol(e,t){return u(await l.post(`${Ct(e,t)}/retry`))}async function Dl(e,t){return u(await l.delete(Ct(e,t)))}async function jl(e,t,n,r){return u(await l.put(`${Ct(e,t)}/grants/${encodeURIComponent(n)}`,{},r))}async function Ll(e,t,n,r){return u(await l.delete(`${Ct(e,t)}/grants/${encodeURIComponent(n)}`,r))}async function $l(e,t,n,r){return u(await l.put(`${Ct(e,t)}/access`,{mode:n,user_ids:r}))}async function Ul(e,t,n){return u(await l.get(Tl(e,t,n)))}async function Fl(e,t){let n=`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/provider-secret-pools`;return u(await l.get(n))}async function Nl(e,t,n,r){return u(await l.put(Tl(e,t,n),{secret_ids:r}))}async function co(){return no()}async function _x(e){return nr(()=>I().getToken(),e,lo)}function lo(){en()}function XO(e){e===null&&en()}function ZO(e){}async function tn(){return co()}async function eD(e){return _x(e)}async function L(e,t,n){try{return await ut(e,t,{retryOnAuthError:n?.retryOnAuthError,timeoutMs:n?.timeoutMs})}catch(r){if(r instanceof ie)return rr();throw r}}function _r(e,t){return e?`/connectors/projects/${encodeURIComponent(e)}/${t}`:`/connectors/${t}`}async function nn(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 l.get(`${_r(e,"catalog")}${r}`)).connectors??[]}async function uo(e){let t=[];for(let n of await nn(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 Kl(e,t="",n={}){let r=t.trim().toLowerCase(),s=r.split(/\s+/).filter(Boolean),o=[],i=[];for(let a of await uo(e)){let c=`${a.tool} ${a.description}`.toLowerCase();!r||c.includes(r)?o.push(a):s.every(p=>c.includes(p))&&i.push(a)}return[...o,...i].slice(0,n.limit??20)}async function po(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 nn(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 bx(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 Px=9e4;async function Tt(e,t,n={},r={}){let{connector:s,action:o}=bx(t),i=r.account?.trim(),a=r.approvalContext?.trim(),c=u(await l.post(_r(e,"call"),{connector:s,action:o,args:n,...i?{account:i}:{},...a?{approval_context:a}:{}},{timeout:r.timeoutMs??Px,signal:r.signal}));return c.ok&&c.binding!==void 0&&!("output"in c)&&(c.output=c.data),c}async function go(e,t){let n=await l.get(_r(e,`connectors/${encodeURIComponent(t)}/accounts`));return u(n).accounts??[]}function Sx(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 xx(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 mo(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=xx(I().backendUrl),a=_r(e,"attachments"),c=await L(`${i}${a}`,{method:"POST",headers:o,body:t},{timeoutMs:6e4}),p=await c.text(),d=null;if(p)try{d=JSON.parse(p)}catch{d=p}if(!c.ok)throw new x(Sx(d,c.status),{status:c.status,code:String(d&&typeof d=="object"?d.code??c.status:c.status),details:d,response:c,endpoint:a});return d}function aD(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 Bl(e){return u(await l.get(`/projects/${e}/connections`))}async function ql(e){return u(await l.get(`/projects/${e}/connections/all`))}async function Gl(e,t){return u(await l.post(`/projects/${e}/connections`,t))}async function Wl(e,t){return u(await l.post(`/projects/${e}/connections/me`,t))}async function Vl(e,t,n){return u(await l.put(`/projects/${e}/connections/${t}/credential`,n))}function Le(e,t,n){return`/projects/${e}/connections/${t}/oauth2/${n}`}async function cD(e,t){return u(await l.post(`/projects/${e}/connectors/${encodeURIComponent(t)}/oauth2/connection`,{}))}async function lD(e,t,n){return u(await l.put(Le(e,t,"application"),n))}async function uD(e,t){return u(await l.get(Le(e,t,"application")))}async function pD(e,t,n){return u(await l.post(Le(e,t,"discover"),n))}async function dD(e,t,n={}){return u(await l.post(Le(e,t,"discover-resource"),n))}async function gD(e,t,n){return u(await l.post(Le(e,t,"register"),n))}async function mD(e,t,n){return u(await l.post(Le(e,t,"authorize"),n))}async function fD(e,t,n){return u(await l.post(Le(e,t,"device"),n))}async function yD(e,t,n){return u(await l.post(Le(e,t,`device/${encodeURIComponent(n)}`),{}))}async function hD(e,t){return u(await l.get(Le(e,t,"status")))}async function Hl(e,t){return u(await l.put(`/projects/${e}/connections/${t}/revoke`,{}))}async function zl(e,t){return u(await l.put(`/projects/${e}/connections/${t}/activate`,{}))}async function Yl(e,t){return u(await l.put(`/projects/${e}/connections/${t}/default`,{}))}async function Jl(e,t,n){return u(await l.put(`/projects/${e}/connections/${t}/label`,{label:n}))}async function Ql(e,t){return u(await l.post(`/projects/${e}/computers`,{tunnel_id:t.tunnelId,...t.share?{share:t.share}:{}}))}async function Xl(e,t,n=[]){return u(await l.post(`/projects/${e}/connections/${t}/share`,{principals:n}))}async function Zl(e,t,n={}){return u(await l.post(`/projects/${e}/connections/${t}/connect`,n))}async function eu(e,t){return u(await l.post(`/projects/${e}/connections/${t}/connect/finalize`,{}))}async function tu(e,t){let n=t?.includeSchemas===void 0?"":`?include_schemas=${t.includeSchemas}`;return u(await l.get(`/connectors/projects/${e}/connectors${n}`,{showErrors:!1}))}async function nu(e){return u(await l.post(`/connectors/projects/${e}/connectors/sync`,{}))}async function ru(e,t,n){return u(await l.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/credential-mode`,{mode:n}))}async function su(e,t,n){return u(await l.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/authorization-strategy`,{authorization_strategy:n}))}async function ou(e,t,n){return u(await l.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/sensitive`,{sensitive:n}))}async function iu(e,t){return u(await l.get(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/policies`))}async function au(e,t,n){return u(await l.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/policies`,{policies:n}))}async function _D(e,t){throw new Error("Connection-specific policies were removed. Use getConnectorPolicies(projectId, slug).")}async function bD(e,t,n){throw new Error("Connection-specific policies were removed. Use setConnectorPolicies(projectId, slug, policies).")}async function cu(e,t){return u(await l.get(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/config`))}async function lu(e,t,n){return u(await l.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/name`,{name:n}))}async function wx(e,t,n={}){return u(await l.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 uu=wx;async function PD(e,t){return u(await l.get(`/connectors/projects/${e}/sessions/${encodeURIComponent(t)}/connect-requests`)).connectors??[]}async function pu(e,t){return u(await l.post(`/connectors/projects/${e}/connectors`,t))}async function du(e,t){return u(await l.post(`/connectors/projects/${e}/connectors/auth-discovery`,t))}async function SD(e,t){return u(await l.post(`/connectors/projects/${e}/connectors/mcp-sign-in-check`,{url:t}))}async function gu(e,t){return u(await l.delete(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}`))}async function mu(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 l.get(`/connectors/projects/${e}/pipedream/apps${o?`?${o}`:""}`))}async function fu(e,t){let n=new URLSearchParams;t?.perCategory&&n.set("perCategory",String(t.perCategory)),t?.maxCategories&&n.set("maxCategories",String(t.maxCategories));let r=n.toString();return u(await l.get(`/connectors/projects/${e}/pipedream/sections${r?`?${r}`:""}`))}async function xD(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 l.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 wD(e,t){let n=new URLSearchParams;t?.perCategory&&n.set("perCategory",String(t.perCategory)),t?.maxCategories&&n.set("maxCategories",String(t.maxCategories));let r=n.toString();return u(await l.get(`/connectors/projects/${e}/connect/sections${r?`?${r}`:""}`))}async function fo(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 l.get(`/connectors/projects/${e}/discover/connectors${o?`?${o}`:""}`))}async function yu(e,t){let n=new URLSearchParams;t?.perCategory&&n.set("perCategory",String(t.perCategory)),t?.maxCategories&&n.set("maxCategories",String(t.maxCategories));let r=n.toString();return u(await l.get(`/connectors/projects/${e}/discover/sections${r?`?${r}`:""}`))}async function yo(e,t){let n=new URLSearchParams({id:t});return u(await l.get(`/connectors/projects/${e}/discover/connectors/detail?${n.toString()}`))}var kD=fo,vD=yo;async function hu(){return u(await l.get("/connectors/connect-status"))}async function _u(e,t,n){let r=typeof n=="string"?{value:n}:n;return u(await l.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/credential`,r))}async function bu(e,t){return u(await l.delete(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/credential`))}async function AD(e,t,n){return u(await l.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/secret-binding`,{secret_identifier:n}))}async function kx(e,t,n={}){let r={};return n.owner&&(r.owner=n.owner),n.connectionId&&(r.connection_id=n.connectionId),u(await l.post(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/connect/finalize`,r))}var Pu=kx;var br=class extends x{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:c,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=c??null,this.connectUrl=p??null,this.hint=d??null,this.availableAccounts=g??[],this.requestedAccount=m??null}},ho=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)}},_o=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 Su(e){return/^([a-z][a-z0-9_]*)(?::|$)/.exec(e)?.[1]??"connector_error"}function vx(e){let t=e?.headers?.get("retry-after");return t&&/^\d+$/.test(t.trim())?Number(t):null}function Ax(e,t,n){if(!(e instanceof x)||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 br(Ae(r.message)??Ae(r.hint)??s,{status:e.status,code:i===null?Su(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:vx(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 Rx(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 bo(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 Tt(e,`${o}.${i}`,r,s)}catch(c){throw Ax(c,o,i)}if(a.status==="pending_approval")throw new ho(o,i,a);if(!a.ok||a.upstream_error){let c=a.upstream_error??a.reason??"connector_error";throw new br(c,{status:200,code:a.upstream_error?"upstream_error":Su(c),details:a,data:a,reason:c,connector:o,action:i,binding:a.binding??null,upstreamStatus:a.upstream_status??null})}return Rx(a)}async function*xu(e,t,n,r,s){let{next:o,maxPages:i=100,...a}=s,c=r;for(let p=0;c;p++){if(p>=i)throw new _o(t,n,i,c);let d=await bo(e,t,n,c,a);yield d,c=o(d,c)}}async function wu(e){return u(await l.get(`/connectors/projects/${e}/policies`))}async function ku(e,t,n){return u(await l.put(`/connectors/projects/${e}/policies`,{policies:t,defaultMode:n}))}async function vu(e){return u(await l.get(`/projects/${e}/sandboxes`))}async function Au(e){return u(await l.get(`/projects/${e}/snapshots`))}async function Pr(e){return u(await l.get(`/projects/${e}/sandbox-health`,{showErrors:!1,timeout:15e3}))}async function Ru(e,t){return u(await l.post(`/projects/${e}/snapshots/rebuild`,t?{slug:t}:{}))}async function Cu(e){return u(await l.post(`/projects/${e}/snapshots/fix-with-agent`,{}))}async function Tu(e,t){return u(await l.post(`/projects/${e}/sandbox-templates`,t))}async function Iu(e,t,n){return u(await l.patch(`/projects/${e}/sandbox-templates/${t}`,n))}async function Eu(e,t){return u(await l.delete(`/projects/${e}/sandbox-templates/${t}`))}async function Mu(e,t){return u(await l.post(`/projects/${e}/sandbox-templates/${t}/build`,{}))}async function Ou(e){return u(await l.get(`/projects/${e}/sandboxes`))}async function Sr(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 ur(e);return{url:e,headers:Object.fromEntries(r.entries())}}async function Du(e,t){let n=new URLSearchParams;t?.ref&&n.set("ref",t.ref),t?.path&&n.set("path",t.path);let r=n.toString()?`?${n.toString()}`:"";return u(await l.get(`/projects/${e}/files${r}`,{showErrors:!1}))}async function ju(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 l.get(`/projects/${e}/files?${n.toString()}`,{showErrors:!1}))}async function Lu(e,t,n){let r=new URLSearchParams({q:t});return n?.content&&r.set("content","1"),n?.ref&&r.set("ref",n.ref),n?.limit&&r.set("limit",String(n.limit)),u(await l.get(`/projects/${e}/files/search?${r.toString()}`))}async function $u(e,t,n){let r=new URLSearchParams({path:t});return n&&r.set("ref",n),u(await l.get(`/projects/${e}/files/content?${r.toString()}`,{showErrors:!1}))}var Cx=10*6e4;async function Uu(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:Cx},"Failed to download")).blob()}async function Fu(e,t,n){let r=new URLSearchParams;t&&r.set("ref",t),n&&r.set("path",n);let s=r.toString()?`?${r.toString()}`:"";return Sr(`${I().backendUrl}/projects/${encodeURIComponent(e)}/files/archive${s}`)}async function WD(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 Po=52428800,Tx=104857600,Nu=20;var wr=e=>`/projects/${encodeURIComponent(e)}/attachments`,kr={showErrors:!1,deadlineCoversBody:!0},Ku=3e4,Ix=12e4,Ex=6e4,Mx=5*6e4,Ox=6e4,Dx=6e4;function xr(){return new x("Request aborted",{name:"AbortError",code:"ABORTED"})}function rn(e){if(e?.aborted)throw xr()}function jx(e){return!(e instanceof x)||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 sn(e,t,n=!1){let r;for(let s=0;;s++){rn(t);try{return await e()}catch(o){let i=n&&o instanceof x&&o.status===409&&o.code==="attachment_processing";if(t?.aborted||!(jx(o)||i))throw o;r??=Date.now()+(n?Mx:Ex);let a=Math.min(8e3,500*2**s)*(.5+Math.random()/2);if(Date.now()+a>=r)throw o;try{await or(a,t)}catch{throw rn(t),o}}}}function Lx(e){return!!e&&typeof e=="object"&&!Array.isArray(e)&&Object.values(e).every(t=>typeof t=="string")}function So(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"&&Lx(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 Bu(e,t,n,r){return u(await l.post(wr(e),{...r?{attachment_id:r}:{},filename:t.name,mime:t.type||"application/octet-stream",size:t.size},{...kr,signal:n,timeout:Ku}),"Failed to start attachment upload")}async function qu(e,t,n,r){let s=So({...await sn(()=>Bu(e,t,r.signal,n.attachment_id),r.signal),received_bytes:0},t,n.attachment_id);return r.onUpload?.(s),s}function Gu(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 x(r,{status:e,details:n,code:String(n?.statusCode??e)})}function $x(e){if(!(e instanceof x))return;let t=Number(e.details?.statusCode);return Number.isInteger(t)&&t>=400?t:e.status}function Ux(e,t,n,r){return new Promise((s,o)=>{let i=new e,a=0,c=!1,p,d=f=>{c||(c=!0,p&&clearTimeout(p),r.signal?.removeEventListener("abort",m),f?o(f):s())},g=()=>{p&&clearTimeout(p),p=setTimeout(()=>{d(new x("Attachment upload stalled",{code:"TIMEOUT"})),i.abort()},Ox)},m=()=>{d(xr()),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(Gu(i.status,i.responseText))},i.onerror=()=>d(new x("Network error during attachment upload",{name:"TypeError"})),i.onabort=()=>d(xr()),r.signal?.addEventListener("abort",m,{once:!0}),g(),i.send(n)})}async function Fx(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"?xr():new x(o instanceof Error?o.message:String(o),{name:o instanceof Error?o.name:"TypeError"})}if(!s.ok)throw Gu(s.status,await s.text().catch(()=>""));n.onProgress?.(t.size,t.size)}function Nx(e,t,n){rn(n.signal);let r=globalThis.XMLHttpRequest;return typeof r=="function"?Ux(r,e,t,n):Fx(e,t,n)}async function Kx(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 sn(()=>Nx(i,t,r),r.signal)}catch(a){let c=$x(a);if(c!==409){if(o||!(c===400||c===401||c===403))throw a;o=!0,s=await qu(e,t,s,r);continue}}return s={...s,received_bytes:t.size},r.onUpload?.(s),s}return Wu(e,t,s,r)}async function Wu(e,t,n,r){if(n.upload.kind!=="chunked")throw new Error("Invalid attachment upload handle");let s=n.upload.chunk_size,o=`${wr(e)}/${encodeURIComponent(n.attachment_id)}`,i=n;for(;i.received_bytes<t.size;){rn(r.signal);let a=i.received_bytes,c=Math.min(a+s,t.size),p=t.slice(a,c),d=await sn(async()=>u(await l.putRaw(`${o}/chunks/${a/s}`,p,{...kr,signal:r.signal,timeout:Ku}),"Failed to upload attachment chunk"),r.signal);if(d.size!==t.size||d.received_bytes!==c)throw new Error("Invalid attachment chunk acknowledgment");i={...i,received_bytes:c},r.onUpload?.(i),r.onProgress?.(c,t.size)}return i}async function vr(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");rn(n.signal);let r=n.resume?So({...n.resume},t):So({...await sn(()=>Bu(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()<Dx&&(r=await qu(e,t,r,n)),r=r.upload.kind==="direct"?await Kx(e,t,r,n):await Wu(e,t,r,n)),n.onProcessing?.();let s=`${wr(e)}/${encodeURIComponent(r.attachment_id)}`;try{return await sn(async()=>u(await l.post(`${s}/complete`,{},{...kr,signal:n.signal,timeout:Ix}),"Failed to complete attachment upload"),n.signal,!0)}catch(o){throw r.upload.kind==="direct"&&o instanceof x&&o.code==="attachment_not_uploaded"&&n.onUpload?.({...r,received_bytes:0}),o}}async function on(e,t,n={}){if(!e)throw new Error("A project is required to remove attachments");let r=await l.delete(`${wr(e)}/${encodeURIComponent(t)}`,{...kr,signal:n.signal});if(!r.success)throw r.error??new Error("Failed to remove attachment")}async function Vu(e,t){let n=new URLSearchParams;t?.q&&n.set("q",t.q),t?.limit!=null&&n.set("limit",String(t.limit)),t?.includeSessionBranches!==void 0&&n.set("include_session_branches",String(t.includeSessionBranches));let r=n.toString()?`?${n.toString()}`:"";return u(await l.get(`/projects/${e}/branches${r}`))}async function Hu(e,t){let n=new URLSearchParams;t?.ref&&n.set("ref",t.ref),t?.path&&n.set("path",t.path),t?.limit!=null&&n.set("limit",String(t.limit)),t?.skip!=null&&n.set("skip",String(t.skip));let r=n.toString()?`?${n.toString()}`:"";return u(await l.get(`/projects/${e}/commits${r}`))}async function zu(e,t){return u(await l.get(`/projects/${e}/commits/${encodeURIComponent(t)}`))}async function Yu(e,t,n){let r=new URLSearchParams;n?.path&&r.set("path",n.path);let s=r.toString()?`?${r.toString()}`:"";return u(await l.get(`/projects/${e}/commits/${encodeURIComponent(t)}/diff${s}`))}async function Ju(e,t,n){let r=new URLSearchParams({path:t});return n?.ref&&r.set("ref",n.ref),n?.limit!=null&&r.set("limit",String(n.limit)),n?.skip!=null&&r.set("skip",String(n.skip)),u(await l.get(`/projects/${e}/files/history?${r.toString()}`))}async function Qu(e,t){let n=new URLSearchParams({from:t.from,into:t.into});return u(await l.get(`/projects/${e}/version-diff?${n.toString()}`))}async function Xu(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 l.get(`/projects/${e}/change-requests${s}`,{showErrors:!1,timeout:15e3}))}async function Zu(e,t){return u(await l.get(`/projects/${e}/change-requests/${t}`))}async function ep(e,t){return u(await l.get(`/projects/${e}/change-requests/${t}/diff`))}async function tp(e,t){return u(await l.get(`/projects/${e}/change-requests/${t}/merge-preview`))}async function np(e,t){return u(await l.post(`/projects/${e}/change-requests`,t))}async function rp(e,t,n){return u(await l.post(`/projects/${e}/change-requests/${t}/merge`,n??{},{showErrors:!1}))}async function sp(e,t){return u(await l.post(`/projects/${e}/change-requests/${t}/close`,{}))}async function op(e,t){return u(await l.post(`/projects/${e}/change-requests/${t}/reopen`,{}))}async function ip(e,t,n){return u(await l.post(`/projects/${e}/change-requests/${t}/request-changes`,{feedback:n}))}async function ap(e,t,n){return u(await l.post(`/projects/${e}/sessions/${t}/commit-push`,n??{}))}async function cp(e,t,n){return u(await l.patch(`/projects/${e}/change-requests/${t}`,n))}var It=new Set,Bx=500;function Ar(e){e&&(It.add(e),It.size>Bx&&It.delete(It.values().next().value))}function lp(e){return!!e&&It.has(e)}function oj(e){e&&It.delete(e)}var le="kortix.session/2",Se=1,qx=["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),H=e=>typeof e=="string",Re=e=>H(e)&&e.length>0,Ue=e=>e===null||H(e),Y=(e,t)=>e===void 0||t(e),$e=(...e)=>t=>e.includes(t),an=e=>Number.isInteger(e)&&e>=0,Et=e=>typeof e=="number",dp=e=>e.schema===le&&an(e.v),pt=e=>Y(e,H),xo=e=>e===void 0||re(e)&&Object.values(e).every(t=>re(t)&&H(t.version)),gp=e=>e===null||re(e)&&H(e.provider)&&H(e.model)&&pt(e.variant),Gx=e=>e===null||re(e)&&Et(e.input)&&Et(e.output)&&Et(e.cache_read)&&Et(e.cache_write)&&Y(e.reasoning,Et)&&Y(e.cost,Et),up=e=>re(e)&&(e.type==="text"&&H(e.text)||e.type==="attachment"&&H(e.mime)),Wx=e=>re(e)&&Array.isArray(e.content)&&e.content.every(up)&&Y(e.model_content,t=>Array.isArray(t)&&t.every(up))&&typeof e.is_error=="boolean",pp={text:e=>H(e.text)&&Y(e.bytes,an)&&pt(e.ref)&&(e.ref===void 0||e.bytes!==void 0),reasoning:e=>H(e.text),attachment:e=>H(e.mime)&&pt(e.ref)&&Y(e.bytes,an)&&e.ref===void 0==(e.bytes===void 0),tool_call:e=>H(e.call_id)&&H(e.name)&&Re(e.kind)&&$e("pending","running","complete","error")(e.status)&&Y(e.result,Wx),compaction:e=>Ue(e.summary)&&Ue(e.first_kept_message_id),subtask:e=>H(e.thread_id)&&H(e.agent)&&H(e.description),step:e=>$e("start","finish")(e.phase),harness:e=>Re(e.harness)&&Re(e.kind)&&typeof e.model_visible=="boolean"};function Vx(e,t){if(!Array.isArray(e))return!1;let n=new Set;for(let r of e){if(!re(r)||!Re(r.id)||n.has(r.id)||!Object.hasOwn(pp,r.type)||!pp[r.type](r)||!xo(r.ext)||t&&r.type==="tool_call"&&(r.status==="pending"||r.status==="running"||!r.result))return!1;n.add(r.id)}return!0}function Hx(e){return re(e)&&dp(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)&&pt(e.native_agent_id)&&pt(e.context_ref)&&gp(e.model)&&Gx(e.usage)&&$e("stop","tool_calls","length","error","aborted",null)(e.finish)&&(e.error===null||re(e.error)&&Re(e.error.code)&&H(e.error.message))&&H(e.created_at)&&Ue(e.completed_at)&&re(e.producer)&&Re(e.producer.harness)&&H(e.producer.harness_version)&&H(e.producer.adapter_version)&&xo(e.ext)&&Vx(e.blocks,e.status!=="streaming"&&e.in_context===!0)}function zx(e){return re(e)&&dp(e)&&Re(e.thread_id)&&Ue(e.parent_thread_id)&&(e.spawned_by===null||re(e.spawned_by))&&H(e.created_at)}function Yx(e){return re(e)&&Y(e.schema,t=>t===le)&&Y(e.v,an)&&pt(e.session_id)&&Y(e.title,Ue)&&pt(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)&&gp(t.model??null))&&Y(e.harness,t=>re(t)&&H(t.current)&&Array.isArray(t.history))&&xo(e.ext)}function Rr(e){return re(e)&&an(e.generation)&&typeof e.has_more=="boolean"&&Yx(e.session)&&Array.isArray(e.threads)&&e.threads.every(zx)&&(e.thread_id===null||Re(e.thread_id))&&Array.isArray(e.messages)&&e.messages.every(t=>Hx(t)&&t.thread_id===e.thread_id)}var Jx=e=>Rr(e)&&e.messages.length>0;function Qx(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 mp={paintable:Jx,fit:Qx,capturedAt:()=>0},Xx=new WeakMap;function fp(e,t,n){Xx.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 Cr(e){return!!e&&typeof e.then=="function"}function yp(e,t){return Cr(e)?e.then(t):t(e)}function hp(e){let{storage:t,prefix:n,maxSessions:r,maxBytes:s,now:o}=e,i=`${n}index`,a=R=>{try{let T=t.getItem(R);return Cr(T)?T.catch(()=>null):T}catch{return null}},c=async R=>{try{await t.removeItem(R)}catch{}},p=R=>{if(!R)return[];try{let T=JSON.parse(R);return T?.v===1&&Array.isArray(T.entries)?T.entries:[]}catch{return[]}},d=Promise.resolve(),g=R=>{let T=d.then(R,R);return d=T.catch(()=>{}),T},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:c,enqueue:g,loadIndex:f,saveIndex:m,evict:async(R,T)=>{let b=[...R].sort((h,S)=>h.u-S.u),M=b.reduce((h,S)=>h+S.b,0);for(;b.length>r||M>s;){let h=b.findIndex(P=>P.s!==T);if(h===-1)break;let[S]=b.splice(h,1);M-=S.b,await c(`${n}${S.s}`)}return b},touch:R=>{g(async()=>{let T=await f(),b=T.find(M=>M.s===R);b&&(b.u=o(),await m(T))})},forgetScope:R=>g(async()=>{await c(`${n}${R}`);let T=await f(),b=T.filter(M=>M.s!==R);b.length!==T.length&&await m(b)})}}function Zx(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 ew=12,tw=15e5,nw=3e5,rw=336*60*60*1e3,Pp="kortix.saved-copy";function sw(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 c=r.slice(r.length-a);return JSON.stringify({...e,e:{...e.e,messages:c,message_count:c.length,complete:!1,next_cursor:String(c[0].info.id)}})},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 ow(e){let t=e.captured_at?Date.parse(e.captured_at):Number.NaN;return Number.isFinite(t)?t:0}var iw={paintable:Zx,fit:sw,capturedAt:ow};function fj(e){let t=bp(e,iw),n=bp({...e,namespace:`${e.namespace??Pp}.log`},mp),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 fp(r,n,t.remove),r}function bp(e,t){let{storage:n,userId:r,maxSessions:s=ew,maxBytes:o=tw,maxEnvelopeBytes:i=nw,maxAgeMs:a=rw,namespace:c=Pp,now:p=()=>Date.now()}=e,d=`${c}:${r}:`,g=hp({storage:n,prefix:d,maxSessions:s,maxBytes:o,now:p}),{indexKey:m,safeGet:f,safeRemove:_,enqueue:y,loadIndex:v,saveIndex:R,evict:T,touch:b,forgetScope:M}=g,h=(P,k)=>`${d}${P}/${k}`,S=P=>{try{let k=n.removeItem(P);Cr(k)&&k.catch(()=>{})}catch{}};return{keyFor:h,read(P,k){let C=`${P}/${k}`;return yp(f(h(P,k)),j=>{if(!j)return null;let w;try{w=JSON.parse(j)}catch{return S(h(P,k)),M(C),null}return!w||w.v!==1||w.user!==r||p()-w.at>a||!t.paintable(w.e)?(S(h(P,k)),M(C),null):(b(C),w.e)})},write(P,k,C){let j=`${P}/${k}`;if(!t.paintable(C))return M(j);let w={v:1,user:r,at:p(),e:C},D=t.fit(w,i);if(D===null)return M(j);let Pe=t.capturedAt(C);return y(async()=>{let N=await v(),z=N.find(it=>it.s===j);if(z&&Pe>0&&z.c>Pe)return;let G=N.filter(it=>it.s!==j),B={s:j,b:D.length,u:p(),c:Pe},Me=await T([...G,B],j),Ws=h(P,k);try{await n.setItem(Ws,D)}catch{let it=Me.filter(at=>at.s!==j).sort((at,OS)=>at.u-OS.u)[0];it&&(await _(`${d}${it.s}`),Me=Me.filter(at=>at.s!==it.s));try{await n.setItem(Ws,D)}catch{await _(Ws),Me=Me.filter(at=>at.s!==j)}}await R(Me)})},remove(P,k){return M(`${P}/${k}`)},clear(){return y(async()=>{let P=await v();for(let k of P)await _(`${d}${k.s}`);await _(m)})}}}var Sp=null;function yj(e){Sp=e}function xp(){return Sp}var aw=new Set;function wp(e){for(let t of aw)try{t(e)}catch{}}var kp=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 l.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};function Cj(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 Tj=50,cw=200,Ij=cw;function vp(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 Ap(e,t){let n=await l.get(`/projects/${e}/sessions${vp(t)}`,{showErrors:!1});return{items:u(n),next_cursor:n.headers?.get("x-next-cursor")??null}}async function Mt(e,t){return u(await l.get(`/projects/${e}/sessions${vp(t)}`))}async function Rp(e,t,n){return u(await l.put(`/projects/${e}/sessions/${t}/sharing`,n))}async function Cp(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/participants`,{showErrors:!1}))}async function Tp(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/watch`,{showErrors:!1}))}async function Ip(e,t,n){return u(await l.put(`/projects/${e}/sessions/${t}/watch`,{watching:n}))}async function Ep(e,t,n){return u(await l.put(`/projects/${e}/sessions/${t}/pin`,{pinned:n}))}async function Mp(e,t,n){return u(await l.put(`/projects/${e}/sessions/${t}/archive`,{archived:n}))}function Ej(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 Mj(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 Op(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/previews`))}async function Dp(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/public-shares`,{showErrors:!1}))}async function jp(e,t,n){return u(await l.post(`/projects/${e}/sessions/${t}/public-shares`,n))}async function Lp(e,t,n){return u(await l.delete(`/projects/${e}/sessions/${t}/public-shares/${n}`))}async function Ot(e,t){let n=u(await l.post(`/projects/${e}/sessions`,t??{}));return t?.initial_prompt||Ar(n?.session_id),n}async function $p(e,t){let n=t?.excludeSessionId?{exclude_session_id:t.excludeSessionId}:{},r=u(await l.post(`/projects/${e}/sessions/warm`,n,{showErrors:!1}));return r.reused||Ar(r.session.session_id),r}async function Up(e,t){let n=u(await l.post(`/projects/${e}/sessions/warm/claim`,t,{showErrors:!1}));return Ar(n.session_id),n}async function Tr(e,t,n){return u(await l.get(`/projects/${e}/sessions/${t}`,{showErrors:n?.showErrors}))}async function Fp(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 l.get(`/projects/${e}/sessions/${t}/audit${o?`?${o}`:""}`,{showErrors:r?.showErrors}))}async function Np(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 l.get(`/projects/${e}/sessions/${t}/transcript${s?`?${s}`:""}`))}async function Ir(e,t,n){let r=new URLSearchParams({shape:"sync"});return n?.limit!=null&&r.set("limit",String(n.limit)),n?.history&&r.set("history","true"),n?.before&&r.set("before",n.before),n?.child&&r.set("child",n.child),u(await l.get(`/projects/${e}/sessions/${t}/transcript?${r.toString()}`,{showErrors:!1,signal:n?.signal}))}async function Kp(e,t,n={},r){let s;try{s=await kp(e,t,n,r?.signal)}catch(o){if(o?.status===404)return null;throw o}if(!Rr(s))throw new Error("The response is not a session log page");return s}async function Er(e,t,n){return u(await l.get(`/projects/${e}/sessions/${t}/turn`,n?.showErrors===!1?{showErrors:!1}:void 0))}async function Oj(e,t,n){let r=new URLSearchParams;n?.transcript!=null&&r.set("transcript",String(n.transcript));let s=r.toString();return u(await l.get(`/projects/${e}/sessions/${t}/snapshot${s?`?${s}`:""}`,{signal:n?.signal,showErrors:!1}))}function lw(e){if(e)return e==="interrupt"?"transcript":"composer"}async function Mr(e,t,n){let r=n.placement??lw(n.delivery);return u(await l.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 Bp(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/prompts`,{showErrors:!1}))}async function qp(e,t,n){return u(await l.delete(`/projects/${e}/sessions/${t}/prompts/${n}`,{showErrors:!1})).removed}async function Gp(e,t,n,r){return u(await l.patch(`/projects/${e}/sessions/${t}/prompts/${n}`,{text:r},{showErrors:!1}))}async function Wp(e,t,n){return u(await l.patch(`/projects/${e}/sessions/${t}/prompts/${n}`,{delivery:"interrupt"},{showErrors:!1}))}async function Vp(e,t,n){return u(await l.post(`/projects/${e}/sessions/${t}/prompts/${n}/retry`,{},{showErrors:!1}))}async function Hp(e,t,n){return u(await l.post(`/projects/${e}/sessions/${t}/prompts/hold`,{held:n},{showErrors:!1}))}async function zp(e,t,n){return u(await l.patch(`/projects/${e}/sessions/${t}`,n))}async function Yp(e,t){let n=u(await l.delete(`/projects/${e}/sessions/${t}`));return xp()?.remove(e,t),n}async function Jp(e,t){return u(await l.post(`/projects/${e}/sessions/${t}/recover`,{},{showErrors:!1}))}async function Qp(e,t){return u(await l.post(`/projects/${e}/sessions/${t}/restore`,{},{showErrors:!1}))}async function Or(e,t,n={}){return u(await l.post(`/projects/${e}/sessions/${t}/restart`,{}))}async function Dr(e,t){let n=u(await l.post(`/projects/${e}/sessions/${t}/stop`,{}));return wp(t),n}async function Xp(e,t){return u(await l.get(`/projects/${e}/sessions/${encodeURIComponent(t)}/config`,{showErrors:!1}))}function uw(e){let t=e.split(`
|
|
7
|
+
`);let m=kx(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:wx});return a}async function IO(e){let t=e?.accountId?`?account_id=${encodeURIComponent(e.accountId)}`:"";return u(await l.get(`/projects/quota${t}`))}async function EO(){try{return u(await l.get("/projects/managed-git/status",{showErrors:!1}))}catch{return{configured:!1,provider:"github"}}}async function _r(e,t){return u(await l.patch(`/projects/${e}`,t))}async function $c(e,t,n){return u(await l.patch(`/projects/${e}/features`,{feature:t,enabled:n}))}async function Uc(e,t,n){return u(await l.patch(`/projects/${e}/experimental`,{feature:t,enabled:n}))}async function Fc(e,t){return u(await l.patch(`/projects/${e}/sandbox-provider`,{provider:t}))}async function MO(e,t){return u(await l.get(`/projects/${e}/sandbox-provider/transition`,{showErrors:!1,...t}))}async function OO(e,t){throw U("updateTemplateWarmPool")}async function Nc(e,t){return u(await l.patch(`/projects/${e}/onboarding`,{completed:t}))}async function DO(e,t){return u(await l.patch(`/projects/${e}/onboarding`,{profile:t}))}async function br(e){return u(await l.delete(`/projects/${e}`))}async function jO(e,t){return At(e,`/v1/projects?account_id=${encodeURIComponent(t)}`)}async function LO(e,t){if(!e.backendUrl||!e.accessToken)return{ok:!1,limitReached:!1};let n=so(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 l.post(`/projects/${e}/skills`,t,{showErrors:!1,...n}))}async function Kc(e){return u(await l.post("/projects/link-repository",e,{showErrors:!1}))}async function qc(e){let{project_id:t,...n}=e;return u(await l.put(`/projects/${encodeURIComponent(t)}/git/repository`,n,{showErrors:!1}))}async function Gc(e){return u(await l.get(`/projects/github/installation?account_id=${encodeURIComponent(e)}`,{showErrors:!1}))}async function Wc(e){return u(await l.get(`/projects/github/installations?account_id=${encodeURIComponent(e)}`,{showErrors:!1}))}async function Vc(e){return u(await l.post("/projects/github/installations/linkable",e,{showErrors:!1}))}async function Hc(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 l.get(`/projects/github/repositories?${r.toString()}`,{showErrors:!1}))}async function zc(e,t,n){let r=new URLSearchParams({account_id:e,installation_id:t,repo_full_name:n});return u(await l.get(`/projects/github/repository-branches?${r.toString()}`,{showErrors:!1}))}async function Yc(e){return u(await l.post("/projects/github/installation",e,{showErrors:!1}))}async function Jc(e){return u(await l.post("/projects/github/installations/link",e,{showErrors:!1}))}async function Qc(e){return u(await l.post("/projects/github/user-token",e,{showErrors:!1}))}async function Xc(e,t){let n=new URLSearchParams({account_id:e});return t&&n.set("installation_id",t),u(await l.delete(`/projects/github/installation?${n.toString()}`))}async function Zc(){return u(await l.get("/projects/git/backend",{showErrors:!1}))}async function el(e){let t=new URLSearchParams,n=e?.search?.trim();n&&t.set("search",n),e?.limit!==void 0&&t.set("limit",String(e.limit));let r=t.toString();return u(await l.get(`/projects/git/backend/repositories${r?`?${r}`:""}`,{showErrors:!1}))}async function YO(e,t){return u(await l.post(`/projects/${e}/access-requests`,{message:t?.trim()||void 0},{showErrors:!1}))}async function tl(e,t){return u(await l.get(`/projects/${e}/access-requests`,t))}async function nl(e,t,n="member"){return u(await l.post(`/projects/${e}/access-requests/${t}/approve`,{role:n}))}async function rl(e,t){return u(await l.post(`/projects/${e}/access-requests/${t}/reject`,{}))}async function sl(e){return u(await l.get(`/projects/${e}/access`))}async function ol(e,t,n){return u(await l.put(`/projects/${e}/access/${t}`,{role:n}))}async function il(e,t){return u(await l.delete(`/projects/${e}/access/${t}`))}function JO(e){return"status"in e&&e.status==="invited"}async function al(e,t,n,r){return u(await l.post(`/projects/${e}/access/invite`,{email:t,role:n,...r!==void 0?{expires_at:r}:{}}))}async function cl(e){return u(await l.get(`/projects/${e}/access/pending-invites`))}async function ll(e,t){return u(await l.delete(`/projects/${e}/access/pending-invites/${t}`))}async function ul(e,t){return u(await l.post(`/projects/${e}/access/pending-invites/${t}/resend`))}async function pl(e){return u(await l.get(`/projects/${e}/group-grants`))}async function dl(e,t,n,r){return u(await l.post(`/projects/${e}/group-grants`,r===void 0?{group_id:t,role:n}:{group_id:t,role:n,expires_at:r}))}async function gl(e,t,n,r){return u(await l.patch(`/projects/${e}/group-grants/${t}`,r===void 0?{role:n}:{role:n,expires_at:r}))}async function ml(e,t){return u(await l.delete(`/projects/${e}/group-grants/${t}`))}async function fl(e){return u(await l.get(`/projects/${e}/resource-grants`))}async function yl(e,t){return u(await l.post(`/projects/${e}/resource-grants`,{resource_type:t.resourceType,resource_id:t.resourceId,principal_type:t.principalType,principal_id:t.principalId,...t.expiresAt!==void 0?{expires_at:t.expiresAt}:{}}))}async function hl(e,t){return u(await l.delete(`/projects/${e}/resource-grants/${t}`))}async function _l(e,t){return u(await l.get(`/projects/${e}/approvals`,{showErrors:t?.showErrors}))}async function bl(e,t){return u(await l.get(`/projects/${e}/approvals/needs-input`,{showErrors:t?.showErrors}))}async function Sl(e,t,n,r={}){let s=r.note?.trim();return u(await l.post(`/projects/${e}/approvals/${t}`,{decision:n,...s?{note:s}:{}}))}async function Pl(e){return u(await l.get(`/projects/${e}/secrets`,{showErrors:!1}))}async function xl(e,t){return u(await l.post(`/projects/${e}/secrets`,t))}async function wl(e,t,n,r={}){return u(await l.put(`/projects/${e}/secrets/${encodeURIComponent(t)}/strategy`,{strategy:n,...r}))}async function kl(e,t,n){return u(await l.post(`/projects/${e}/secrets/${encodeURIComponent(t)}/broker`,n))}async function vl(e){return u(await l.get(`/projects/${e}/oauth`)).items??[]}async function io(e,t,n){return u(await l.post(`/projects/${e}/oauth/${t}/start`,{sharing:n?.sharing,...n?.resourceLabel===void 0?{}:{resource_label:n.resourceLabel},...n?.resourceId===void 0?{}:{resource_id:n.resourceId}}))}async function ao(e,t,n){return u(await l.post(`/projects/${e}/oauth/${t}/poll`,{flow_id:n}))}async function Al(e,t){return u(await l.delete(`/projects/${e}/oauth/${encodeURIComponent(t)}`))}var vx=2e3,Ax=3e3,Rx=10*6e4;async function eD(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,c=()=>o?.()??!1,p=await io(t,n,r);if(c())return{status:"cancelled"};s?.({verification_url:p.verification_url,user_code:p.user_code});let d=Math.max(vx,p.interval_ms||Ax),g=p.expires_at||a()+Rx;for(;!c()&&a()<g;){if(await i(d),c())return{status:"cancelled"};let m;try{m=await ao(t,n,p.flow_id)}catch{continue}if(c())return{status:"cancelled"};if(m.status==="success")return{status:"success",credential:m.credential};if(m.status==="failed")return{status:"failed",error:m.error};if(m.status==="expired")return{status:"expired"}}return c()?{status:"cancelled"}:{status:"expired"}}async function Rl(e,t){return u(await l.put(`/projects/${e}/git-credential`,t))}async function Tl(e,t){return u(await l.delete(`/projects/${e}/secrets/${encodeURIComponent(t)}`))}async function Cl(e,t,n){return u(await l.put(`/projects/${e}/secrets/${encodeURIComponent(t)}/personal`,n))}async function Il(e,t){return u(await l.delete(`/projects/${e}/secrets/${encodeURIComponent(t)}/personal`))}var co=e=>`/accounts/${encodeURIComponent(e)}/secret-resources`,Ct=(e,t)=>`${co(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 l.get(`${co(e)}${n}`))}async function Ol(e,t){return u(await l.post(co(e),t))}async function Dl(e,t,n){return u(await l.put(`${Ct(e,t)}/value`,{value:n}))}async function jl(e,t){return u(await l.post(`${Ct(e,t)}/retry`))}async function Ll(e,t){return u(await l.delete(Ct(e,t)))}async function $l(e,t,n,r){return u(await l.put(`${Ct(e,t)}/grants/${encodeURIComponent(n)}`,{},r))}async function Ul(e,t,n,r){return u(await l.delete(`${Ct(e,t)}/grants/${encodeURIComponent(n)}`,r))}async function Fl(e,t,n,r){return u(await l.put(`${Ct(e,t)}/access`,{mode:n,user_ids:r}))}async function Nl(e,t,n){return u(await l.get(El(e,t,n)))}async function Bl(e,t){let n=`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/provider-secret-pools`;return u(await l.get(n))}async function Kl(e,t,n,r){return u(await l.put(El(e,t,n),{secret_ids:r}))}async function lo(){return ro()}async function Tx(e){return or(()=>T().getToken(),e,uo)}function uo(){nn()}function lD(e){e===null&&nn()}function uD(e){}async function rn(){return lo()}async function pD(e){return Tx(e)}async function L(e,t,n){try{return await pt(e,t,{retryOnAuthError:n?.retryOnAuthError,timeoutMs:n?.timeoutMs})}catch(r){if(r instanceof ie)return ir();throw r}}function Sr(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 l.get(`${Sr(e,"catalog")}${r}`)).connectors??[]}async function po(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 ql(e,t="",n={}){let r=t.trim().toLowerCase(),s=r.split(/\s+/).filter(Boolean),o=[],i=[];for(let a of await po(e)){let c=`${a.tool} ${a.description}`.toLowerCase();!r||c.includes(r)?o.push(a):s.every(p=>c.includes(p))&&i.push(a)}return[...o,...i].slice(0,n.limit??20)}async function go(e,t){let n=t.indexOf(".");if(n<0)return null;let r=t.slice(0,n).trim();if(!r)return null;let s=(await sn(e,{slug:r,includeSchemas:!0,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 Cx(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 Ix=9e4;async function It(e,t,n={},r={}){let{connector:s,action:o}=Cx(t),i=r.account?.trim(),a=r.approvalContext?.trim(),c=u(await l.post(Sr(e,"call"),{connector:s,action:o,args:n,...i?{account:i}:{},...a?{approval_context:a}:{}},{timeout:r.timeoutMs??Ix,signal:r.signal}));return c.ok&&c.binding!==void 0&&!("output"in c)&&(c.output=c.data),c}async function mo(e,t){let n=await l.get(Sr(e,`connectors/${encodeURIComponent(t)}/accounts`));return u(n).accounts??[]}function Ex(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 Mx(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 fo(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=Mx(T().backendUrl),a=Sr(e,"attachments"),c=await L(`${i}${a}`,{method:"POST",headers:o,body:t},{timeoutMs:6e4}),p=await c.text(),d=null;if(p)try{d=JSON.parse(p)}catch{d=p}if(!c.ok)throw new P(Ex(d,c.status),{status:c.status,code:String(d&&typeof d=="object"?d.code??c.status:c.status),details:d,response:c,endpoint:a});return d}function _D(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 l.get(`/projects/${e}/connections`))}async function Wl(e){return u(await l.get(`/projects/${e}/connections/all`))}async function Vl(e,t){return u(await l.post(`/projects/${e}/connections`,t))}async function Hl(e,t){return u(await l.post(`/projects/${e}/connections/me`,t))}async function zl(e,t,n){return u(await l.put(`/projects/${e}/connections/${t}/credential`,n))}function Le(e,t,n){return`/projects/${e}/connections/${t}/oauth2/${n}`}async function bD(e,t){return u(await l.post(`/projects/${e}/connectors/${encodeURIComponent(t)}/oauth2/connection`,{}))}async function SD(e,t,n){return u(await l.put(Le(e,t,"application"),n))}async function PD(e,t){return u(await l.get(Le(e,t,"application")))}async function xD(e,t,n){return u(await l.post(Le(e,t,"discover"),n))}async function wD(e,t,n={}){return u(await l.post(Le(e,t,"discover-resource"),n))}async function kD(e,t,n){return u(await l.post(Le(e,t,"register"),n))}async function vD(e,t,n){return u(await l.post(Le(e,t,"authorize"),n))}async function AD(e,t,n){return u(await l.post(Le(e,t,"device"),n))}async function RD(e,t,n){return u(await l.post(Le(e,t,`device/${encodeURIComponent(n)}`),{}))}async function TD(e,t){return u(await l.get(Le(e,t,"status")))}async function Yl(e,t){return u(await l.put(`/projects/${e}/connections/${t}/revoke`,{}))}async function Jl(e,t){return u(await l.put(`/projects/${e}/connections/${t}/activate`,{}))}async function Ql(e,t){return u(await l.put(`/projects/${e}/connections/${t}/default`,{}))}async function Xl(e,t,n){return u(await l.put(`/projects/${e}/connections/${t}/label`,{label:n}))}async function Zl(e,t){return u(await l.post(`/projects/${e}/computers`,{tunnel_id:t.tunnelId,...t.share?{share:t.share}:{}}))}async function eu(e,t,n=[]){return u(await l.post(`/projects/${e}/connections/${t}/share`,{principals:n}))}async function tu(e,t,n={}){return u(await l.post(`/projects/${e}/connections/${t}/connect`,n))}async function nu(e,t){return u(await l.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 l.get(`/connectors/projects/${e}/connectors${n}`,{showErrors:!1}))}async function su(e){return u(await l.post(`/connectors/projects/${e}/connectors/sync`,{}))}async function ou(e,t,n){return u(await l.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/credential-mode`,{mode:n}))}async function iu(e,t,n){return u(await l.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/authorization-strategy`,{authorization_strategy:n}))}async function au(e,t,n){return u(await l.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/sensitive`,{sensitive:n}))}async function cu(e,t){return u(await l.get(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/policies`))}async function lu(e,t,n){return u(await l.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/policies`,{policies:n}))}async function CD(e,t){throw new Error("Connection-specific policies were removed. Use getConnectorPolicies(projectId, slug).")}async function ID(e,t,n){throw new Error("Connection-specific policies were removed. Use setConnectorPolicies(projectId, slug, policies).")}async function uu(e,t){return u(await l.get(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/config`))}async function pu(e,t,n){return u(await l.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/name`,{name:n}))}async function Ox(e,t,n={}){return u(await l.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=Ox;async function ED(e,t){return u(await l.get(`/connectors/projects/${e}/sessions/${encodeURIComponent(t)}/connect-requests`)).connectors??[]}async function gu(e,t){return u(await l.post(`/connectors/projects/${e}/connectors`,t))}async function mu(e,t){return u(await l.post(`/connectors/projects/${e}/connectors/auth-discovery`,t))}async function MD(e,t){return u(await l.post(`/connectors/projects/${e}/connectors/mcp-sign-in-check`,{url:t}))}async function fu(e){return u(await l.get(`/projects/${e}/connector-moves`)).moves}async function yu(e,t,n={}){return u(await l.post(`/projects/${e}/connectors/${encodeURIComponent(t)}/move`,n.connectionId?{connection_id:n.connectionId}:{}))}async function hu(e,t){return u(await l.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 l.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 l.get(`/connectors/projects/${e}/pipedream/sections${r?`?${r}`:""}`))}async function OD(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 l.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 DD(e,t){let n=new URLSearchParams;t?.perCategory&&n.set("perCategory",String(t.perCategory)),t?.maxCategories&&n.set("maxCategories",String(t.maxCategories));let r=n.toString();return u(await l.get(`/connectors/projects/${e}/connect/sections${r?`?${r}`:""}`))}async function yo(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 l.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 l.get(`/connectors/projects/${e}/discover/sections${r?`?${r}`:""}`))}async function ho(e,t){let n=new URLSearchParams({id:t});return u(await l.get(`/connectors/projects/${e}/discover/connectors/detail?${n.toString()}`))}var jD=yo,LD=ho;async function Pu(){return u(await l.get("/connectors/connect-status"))}async function xu(e,t,n){let r=typeof n=="string"?{value:n}:n;return u(await l.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/credential`,r))}async function wu(e,t){return u(await l.delete(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/credential`))}async function $D(e,t,n){return u(await l.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/secret-binding`,{secret_identifier:n}))}async function Dx(e,t,n={}){let r={};return n.owner&&(r.owner=n.owner),n.connectionId&&(r.connection_id=n.connectionId),u(await l.post(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/connect/finalize`,r))}var ku=Dx;var Pr=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:c,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=c??null,this.connectUrl=p??null,this.hint=d??null,this.availableAccounts=g??[],this.requestedAccount=m??null}},_o=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)}},bo=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 jx(e){let t=e?.headers?.get("retry-after");return t&&/^\d+$/.test(t.trim())?Number(t):null}function Lx(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 Pr(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: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 $x(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 So(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(c){throw Lx(c,o,i)}if(a.status==="pending_approval")throw new _o(o,i,a);if(!a.ok||a.upstream_error){let c=a.upstream_error??a.reason??"connector_error";throw new Pr(c,{status:200,code:a.upstream_error?"upstream_error":vu(c),details:a,data:a,reason:c,connector:o,action:i,binding:a.binding??null,upstreamStatus:a.upstream_status??null})}return $x(a)}async function*Au(e,t,n,r,s){let{next:o,maxPages:i=100,...a}=s,c=r;for(let p=0;c;p++){if(p>=i)throw new bo(t,n,i,c);let d=await So(e,t,n,c,a);yield d,c=o(d,c)}}async function Ru(e){return u(await l.get(`/connectors/projects/${e}/policies`))}async function Tu(e,t,n){return u(await l.put(`/connectors/projects/${e}/policies`,{policies:t,defaultMode:n}))}async function Cu(e){return u(await l.get(`/projects/${e}/sandboxes`))}async function Iu(e){return u(await l.get(`/projects/${e}/snapshots`))}async function xr(e){return u(await l.get(`/projects/${e}/sandbox-health`,{showErrors:!1,timeout:15e3}))}async function Eu(e,t){return u(await l.post(`/projects/${e}/snapshots/rebuild`,t?{slug:t}:{}))}async function Mu(e){return u(await l.post(`/projects/${e}/snapshots/fix-with-agent`,{}))}async function Ou(e,t){return u(await l.post(`/projects/${e}/sandbox-templates`,t))}async function Du(e,t,n){return u(await l.patch(`/projects/${e}/sandbox-templates/${t}`,n))}async function ju(e,t){return u(await l.delete(`/projects/${e}/sandbox-templates/${t}`))}async function Lu(e,t){return u(await l.post(`/projects/${e}/sandbox-templates/${t}/build`,{}))}async function $u(e){return u(await l.get(`/projects/${e}/sandboxes`))}async function wr(e){let t=new URL(T().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 l.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 l.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 l.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 l.get(`/projects/${e}/files/content?${r.toString()}`,{showErrors:!1}))}var Ux=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=`${T().backendUrl||""}/projects/${e}/files/archive${s}`;return await(await Oe(o,{method:"GET"},{timeoutMs:Ux},"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 wr(`${T().backendUrl}/projects/${encodeURIComponent(e)}/files/archive${s}`)}async function nj(e,t,n,r){let s=new URLSearchParams({path:t});n&&s.set("ref",n);let o=s.toString()?`?${s.toString()}`:"",i=`${T().backendUrl||""}/projects/${e}/files/raw${o}`;return await(await Oe(i,{method:"GET",...r?.signal?{signal:r.signal}:{}},{},"Failed to read file")).blob()}var Po=52428800,Fx=104857600,Gu=20;var vr=e=>`/projects/${encodeURIComponent(e)}/attachments`,Ar={showErrors:!1,deadlineCoversBody:!0},Wu=3e4,Nx=12e4,Bx=6e4,Kx=5*6e4,qx=6e4,Gx=6e4;function kr(){return new P("Request aborted",{name:"AbortError",code:"ABORTED"})}function on(e){if(e?.aborted)throw kr()}function Wx(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 an(e,t,n=!1){let r;for(let s=0;;s++){on(t);try{return await e()}catch(o){let i=n&&o instanceof P&&o.status===409&&o.code==="attachment_processing";if(t?.aborted||!(Wx(o)||i))throw o;r??=Date.now()+(n?Kx:Bx);let a=Math.min(8e3,500*2**s)*(.5+Math.random()/2);if(Date.now()+a>=r)throw o;try{await cr(a,t)}catch{throw on(t),o}}}}function Vx(e){return!!e&&typeof e=="object"&&!Array.isArray(e)&&Object.values(e).every(t=>typeof t=="string")}function xo(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"&&Vx(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 Vu(e,t,n,r){return u(await l.post(vr(e),{...r?{attachment_id:r}:{},filename:t.name,mime:t.type||"application/octet-stream",size:t.size},{...Ar,signal:n,timeout:Wu}),"Failed to start attachment upload")}async function Hu(e,t,n,r){let s=xo({...await an(()=>Vu(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 Hx(e){if(!(e instanceof P))return;let t=Number(e.details?.statusCode);return Number.isInteger(t)&&t>=400?t:e.status}function zx(e,t,n,r){return new Promise((s,o)=>{let i=new e,a=0,c=!1,p,d=f=>{c||(c=!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()},qx)},m=()=>{d(kr()),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(zu(i.status,i.responseText))},i.onerror=()=>d(new P("Network error during attachment upload",{name:"TypeError"})),i.onabort=()=>d(kr()),r.signal?.addEventListener("abort",m,{once:!0}),g(),i.send(n)})}async function Yx(e,t,n){let r=T().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"?kr():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 Jx(e,t,n){on(n.signal);let r=globalThis.XMLHttpRequest;return typeof r=="function"?zx(r,e,t,n):Yx(e,t,n)}async function Qx(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 an(()=>Jx(i,t,r),r.signal)}catch(a){let c=Hx(a);if(c!==409){if(o||!(c===400||c===401||c===403))throw a;o=!0,s=await Hu(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=`${vr(e)}/${encodeURIComponent(n.attachment_id)}`,i=n;for(;i.received_bytes<t.size;){on(r.signal);let a=i.received_bytes,c=Math.min(a+s,t.size),p=t.slice(a,c),d=await an(async()=>u(await l.putRaw(`${o}/chunks/${a/s}`,p,{...Ar,signal:r.signal,timeout:Wu}),"Failed to upload attachment chunk"),r.signal);if(d.size!==t.size||d.received_bytes!==c)throw new Error("Invalid attachment chunk acknowledgment");i={...i,received_bytes:c},r.onUpload?.(i),r.onProgress?.(c,t.size)}return i}async function Rr(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");on(n.signal);let r=n.resume?xo({...n.resume},t):xo({...await an(()=>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()<Gx&&(r=await Hu(e,t,r,n)),r=r.upload.kind==="direct"?await Qx(e,t,r,n):await Yu(e,t,r,n)),n.onProcessing?.();let s=`${vr(e)}/${encodeURIComponent(r.attachment_id)}`;try{return await an(async()=>u(await l.post(`${s}/complete`,{},{...Ar,signal:n.signal,timeout:Nx}),"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 cn(e,t,n={}){if(!e)throw new Error("A project is required to remove attachments");let r=await l.delete(`${vr(e)}/${encodeURIComponent(t)}`,{...Ar,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 l.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 l.get(`/projects/${e}/commits${r}`))}async function Xu(e,t){return u(await l.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 l.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 l.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 l.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 l.get(`/projects/${e}/change-requests${s}`,{showErrors:!1,timeout:15e3}))}async function rp(e,t){return u(await l.get(`/projects/${e}/change-requests/${t}`))}async function sp(e,t){return u(await l.get(`/projects/${e}/change-requests/${t}/diff`))}async function op(e,t){return u(await l.get(`/projects/${e}/change-requests/${t}/merge-preview`))}async function ip(e,t){return u(await l.post(`/projects/${e}/change-requests`,t))}async function ap(e,t,n){return u(await l.post(`/projects/${e}/change-requests/${t}/merge`,n??{},{showErrors:!1}))}async function cp(e,t){return u(await l.post(`/projects/${e}/change-requests/${t}/close`,{}))}async function lp(e,t){return u(await l.post(`/projects/${e}/change-requests/${t}/reopen`,{}))}async function up(e,t,n){return u(await l.post(`/projects/${e}/change-requests/${t}/request-changes`,{feedback:n}))}async function pp(e,t,n){return u(await l.post(`/projects/${e}/sessions/${t}/commit-push`,n??{}))}async function dp(e,t,n){return u(await l.patch(`/projects/${e}/change-requests/${t}`,n))}var Et=new Set,Xx=500;function Tr(e){e&&(Et.add(e),Et.size>Xx&&Et.delete(Et.values().next().value))}function gp(e){return!!e&&Et.has(e)}function yj(e){e&&Et.delete(e)}var le="kortix.session/2",Pe=1,Zx=["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),H=e=>typeof e=="string",Re=e=>H(e)&&e.length>0,Ue=e=>e===null||H(e),Y=(e,t)=>e===void 0||t(e),$e=(...e)=>t=>e.includes(t),ln=e=>Number.isInteger(e)&&e>=0,Mt=e=>typeof e=="number",yp=e=>e.schema===le&&ln(e.v),dt=e=>Y(e,H),wo=e=>e===void 0||re(e)&&Object.values(e).every(t=>re(t)&&H(t.version)),hp=e=>e===null||re(e)&&H(e.provider)&&H(e.model)&&dt(e.variant),ew=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),mp=e=>re(e)&&(e.type==="text"&&H(e.text)||e.type==="attachment"&&H(e.mime)),tw=e=>re(e)&&Array.isArray(e.content)&&e.content.every(mp)&&Y(e.model_content,t=>Array.isArray(t)&&t.every(mp))&&typeof e.is_error=="boolean",fp={text:e=>H(e.text)&&Y(e.bytes,ln)&&dt(e.ref)&&(e.ref===void 0||e.bytes!==void 0),reasoning:e=>H(e.text),attachment:e=>H(e.mime)&&dt(e.ref)&&Y(e.bytes,ln)&&e.ref===void 0==(e.bytes===void 0),tool_call:e=>H(e.call_id)&&H(e.name)&&Re(e.kind)&&$e("pending","running","complete","error")(e.status)&&Y(e.result,tw),compaction:e=>Ue(e.summary)&&Ue(e.first_kept_message_id),subtask:e=>H(e.thread_id)&&H(e.agent)&&H(e.description),step:e=>$e("start","finish")(e.phase),harness:e=>Re(e.harness)&&Re(e.kind)&&typeof e.model_visible=="boolean"};function nw(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)||!wo(r.ext)||t&&r.type==="tool_call"&&(r.status==="pending"||r.status==="running"||!r.result))return!1;n.add(r.id)}return!0}function ko(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"&&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)&&dt(e.native_agent_id)&&dt(e.context_ref)&&hp(e.model)&&ew(e.usage)&&$e("stop","tool_calls","length","error","aborted",null)(e.finish)&&(e.error===null||re(e.error)&&Re(e.error.code)&&H(e.error.message))&&H(e.created_at)&&Ue(e.completed_at)&&re(e.producer)&&Re(e.producer.harness)&&H(e.producer.harness_version)&&H(e.producer.adapter_version)&&wo(e.ext)&&nw(e.blocks,e.status!=="streaming"&&e.in_context===!0)}function vo(e){return re(e)&&yp(e)&&Re(e.thread_id)&&Ue(e.parent_thread_id)&&(e.spawned_by===null||re(e.spawned_by))&&H(e.created_at)}function rw(e){return re(e)&&Y(e.schema,t=>t===le)&&Y(e.v,ln)&&dt(e.session_id)&&Y(e.title,Ue)&&dt(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)&&hp(t.model??null))&&Y(e.harness,t=>re(t)&&H(t.current)&&Array.isArray(t.history))&&wo(e.ext)}function Ot(e){return re(e)&&ln(e.generation)&&typeof e.has_more=="boolean"&&rw(e.session)&&Array.isArray(e.threads)&&e.threads.every(vo)&&(e.thread_id===null||Re(e.thread_id))&&Array.isArray(e.messages)&&e.messages.every(t=>ko(t)&&t.thread_id===e.thread_id)}var sw=e=>Ot(e)&&e.messages.length>0;function ow(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:sw,fit:ow,capturedAt:()=>0},iw=new WeakMap;function bp(e,t,n){iw.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 Cr(e){return!!e&&typeof e.then=="function"}function Sp(e,t){return Cr(e)?e.then(t):t(e)}function Pp(e){let{storage:t,prefix:n,maxSessions:r,maxBytes:s,now:o}=e,i=`${n}index`,a=R=>{try{let I=t.getItem(R);return Cr(I)?I.catch(()=>null):I}catch{return null}},c=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:c,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>s;){let h=b.findIndex(S=>S.s!==I);if(h===-1)break;let[x]=b.splice(h,1);M-=x.b,await c(`${n}${x.s}`)}return b},touch:R=>{g(async()=>{let I=await f(),b=I.find(M=>M.s===R);b&&(b.u=o(),await m(I))})},forgetScope:R=>g(async()=>{await c(`${n}${R}`);let I=await f(),b=I.filter(M=>M.s!==R);b.length!==I.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 cw=12,lw=15e5,uw=3e5,pw=336*60*60*1e3,kp="kortix.saved-copy";function dw(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 c=r.slice(r.length-a);return JSON.stringify({...e,e:{...e.e,messages:c,message_count:c.length,complete:!1,next_cursor:String(c[0].info.id)}})},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 gw(e){let t=e.captured_at?Date.parse(e.captured_at):Number.NaN;return Number.isFinite(t)?t:0}var mw={paintable:aw,fit:dw,capturedAt:gw};function Aj(e){let t=wp(e,mw),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=cw,maxBytes:o=lw,maxEnvelopeBytes:i=uw,maxAgeMs:a=pw,namespace:c=kp,now:p=()=>Date.now()}=e,d=`${c}:${r}:`,g=Pp({storage:n,prefix:d,maxSessions:s,maxBytes:o,now:p}),{indexKey:m,safeGet:f,safeRemove:_,enqueue:y,loadIndex:k,saveIndex:R,evict:I,touch:b,forgetScope:M}=g,h=(S,v)=>`${d}${S}/${v}`,x=S=>{try{let v=n.removeItem(S);Cr(v)&&v.catch(()=>{})}catch{}};return{keyFor:h,read(S,v){let C=`${S}/${v}`;return Sp(f(h(S,v)),j=>{if(!j)return null;let w;try{w=JSON.parse(j)}catch{return x(h(S,v)),M(C),null}return!w||w.v!==1||w.user!==r||p()-w.at>a||!t.paintable(w.e)?(x(h(S,v)),M(C),null):(b(C),w.e)})},write(S,v,C){let j=`${S}/${v}`;if(!t.paintable(C))return M(j);let w={v:1,user:r,at:p(),e:C},D=t.fit(w,i);if(D===null)return M(j);let Se=t.capturedAt(C);return y(async()=>{let N=await k(),z=N.find(at=>at.s===j);if(z&&Se>0&&z.c>Se)return;let G=N.filter(at=>at.s!==j),K={s:j,b:D.length,u:p(),c:Se},Me=await I([...G,K],j),Vs=h(S,v);try{await n.setItem(Vs,D)}catch{let at=Me.filter(ct=>ct.s!==j).sort((ct,qP)=>ct.u-qP.u)[0];at&&(await _(`${d}${at.s}`),Me=Me.filter(ct=>ct.s!==at.s));try{await n.setItem(Vs,D)}catch{await _(Vs),Me=Me.filter(ct=>ct.s!==j)}}await R(Me)})},remove(S,v){return M(`${S}/${v}`)},clear(){return y(async()=>{let S=await k();for(let v of S)await _(`${d}${v.s}`);await _(m)})}}}var vp=null;function Rj(e){vp=e}function Ap(){return vp}var fw=new Set;function Rp(e){for(let t of fw)try{t(e)}catch{}}var un=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 l.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},yw=40;async function hw(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 hw(e,t,n,{limit:yw},r)}function Nj(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 Bj=50,_w=200,Kj=_w;function Cp(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 Ip(e,t){let n=await l.get(`/projects/${e}/sessions${Cp(t)}`,{showErrors:!1});return{items:u(n),next_cursor:n.headers?.get("x-next-cursor")??null}}async function Dt(e,t){return u(await l.get(`/projects/${e}/sessions${Cp(t)}`))}async function Ep(e,t,n){return u(await l.put(`/projects/${e}/sessions/${t}/sharing`,n))}async function Mp(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/participants`,{showErrors:!1}))}async function Op(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/watch`,{showErrors:!1}))}async function Dp(e,t,n){return u(await l.put(`/projects/${e}/sessions/${t}/watch`,{watching:n}))}async function jp(e,t,n){return u(await l.put(`/projects/${e}/sessions/${t}/pin`,{pinned:n}))}async function Lp(e,t,n){return u(await l.put(`/projects/${e}/sessions/${t}/archive`,{archived:n}))}function qj(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 Gj(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 $p(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/previews`))}async function Up(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/public-shares`,{showErrors:!1}))}async function Fp(e,t,n){return u(await l.post(`/projects/${e}/sessions/${t}/public-shares`,n))}async function Np(e,t,n){return u(await l.delete(`/projects/${e}/sessions/${t}/public-shares/${n}`))}async function jt(e,t){let n=u(await l.post(`/projects/${e}/sessions`,t??{}));return t?.initial_prompt||Tr(n?.session_id),n}async function Bp(e,t){let n=t?.excludeSessionId?{exclude_session_id:t.excludeSessionId}:{},r=u(await l.post(`/projects/${e}/sessions/warm`,n,{showErrors:!1}));return r.reused||Tr(r.session.session_id),r}async function Kp(e,t){let n=u(await l.post(`/projects/${e}/sessions/warm/claim`,t,{showErrors:!1}));return Tr(n.session_id),n}async function Ir(e,t,n){return u(await l.get(`/projects/${e}/sessions/${t}`,{showErrors:n?.showErrors}))}async function qp(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 l.get(`/projects/${e}/sessions/${t}/audit${o?`?${o}`:""}`,{showErrors:r?.showErrors}))}async function Gp(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 l.get(`/projects/${e}/sessions/${t}/transcript${s?`?${s}`:""}`))}async function Er(e,t,n){let r=new URLSearchParams({shape:"sync"});return n?.limit!=null&&r.set("limit",String(n.limit)),n?.history&&r.set("history","true"),n?.before&&r.set("before",n.before),n?.child&&r.set("child",n.child),u(await l.get(`/projects/${e}/sessions/${t}/transcript?${r.toString()}`,{showErrors:!1,signal:n?.signal}))}async function Wp(e,t,n={},r){let s;try{s=await un(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 Mr(e,t,n){return u(await l.get(`/projects/${e}/sessions/${t}/turn`,n?.showErrors===!1?{showErrors:!1}:void 0))}async function Wj(e,t,n){let r=new URLSearchParams;n?.transcript!=null&&r.set("transcript",String(n.transcript));let s=r.toString();return u(await l.get(`/projects/${e}/sessions/${t}/snapshot${s?`?${s}`:""}`,{signal:n?.signal,showErrors:!1}))}function bw(e){if(e)return e==="interrupt"?"transcript":"composer"}async function Or(e,t,n){let r=n.placement??bw(n.delivery);return u(await l.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 l.get(`/projects/${e}/sessions/${t}/prompts`,{showErrors:!1}))}async function Hp(e,t,n){return u(await l.delete(`/projects/${e}/sessions/${t}/prompts/${n}`,{showErrors:!1})).removed}async function zp(e,t,n,r){return u(await l.patch(`/projects/${e}/sessions/${t}/prompts/${n}`,{text:r},{showErrors:!1}))}async function Yp(e,t,n){return u(await l.patch(`/projects/${e}/sessions/${t}/prompts/${n}`,{delivery:"interrupt"},{showErrors:!1}))}async function Jp(e,t,n){return u(await l.post(`/projects/${e}/sessions/${t}/prompts/${n}/retry`,{},{showErrors:!1}))}async function Qp(e,t,n){return u(await l.post(`/projects/${e}/sessions/${t}/prompts/hold`,{held:n},{showErrors:!1}))}async function Xp(e,t,n){return u(await l.patch(`/projects/${e}/sessions/${t}`,n))}async function Zp(e,t){let n=u(await l.delete(`/projects/${e}/sessions/${t}`));return Ap()?.remove(e,t),n}async function ed(e,t){return u(await l.post(`/projects/${e}/sessions/${t}/recover`,{},{showErrors:!1}))}async function td(e,t){return u(await l.post(`/projects/${e}/sessions/${t}/restore`,{},{showErrors:!1}))}async function Dr(e,t,n={}){return u(await l.post(`/projects/${e}/sessions/${t}/restart`,{}))}async function jr(e,t){let n=u(await l.post(`/projects/${e}/sessions/${t}/stop`,{}));return Rp(t),n}async function nd(e,t){return u(await l.get(`/projects/${e}/sessions/${encodeURIComponent(t)}/config`,{showErrors:!1}))}function Sw(e){let t=e.split(`
|
|
8
8
|
`).filter(n=>n.startsWith("data:")).map(n=>n.slice(5).replace(/^ /,""));if(t.length===0)return null;try{return JSON.parse(t.join(`
|
|
9
|
-
`))}catch(n){throw new Error("reloadProjectSessionConfigStream received an invalid SSE frame",{cause:n})}}async function
|
|
9
|
+
`))}catch(n){throw new Error("reloadProjectSessionConfigStream received an invalid SSE frame",{cause:n})}}async function rd(e,t,n={}){return u(await l.post(`/projects/${e}/sessions/${encodeURIComponent(t)}/reload`,n,{showErrors:!1}))}async function sd(e,t,n,r,s={}){let o=await l.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,c="",p=null;try{for(;;){let{done:d,value:g}=await i.read();if(d)break;c+=a.decode(g,{stream:!0});let m=c.indexOf(`
|
|
10
10
|
|
|
11
11
|
`);for(;m!==-1;){let f=c.slice(0,m);c=c.slice(m+2),m=c.indexOf(`
|
|
12
12
|
|
|
13
|
-
`);let _=uw(f);if(_){if(r(_),_.type==="error")throw new x(_.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 td(e,t){return u(await l.get(`/projects/${e}/sessions/${encodeURIComponent(t)}/scope`))}async function nd(e,t,n){return u(await l.put(`/projects/${e}/sessions/${encodeURIComponent(t)}/scope`,n))}async function rd(e,t,n){return u(await l.put(`/projects/${e}/sessions/${encodeURIComponent(t)}/model`,{model:n,opencode_model:n}))}function jr(e){let t=e.metadata?.opencode_model;return typeof t=="string"&&t.trim()?t.trim():null}async function sd(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/message-authors`,{showErrors:!1}))}async function od(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/model-usage`,{showErrors:!1}))}function jj(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 id(e){return u(await l.get(`/projects/${e}/triggers`))}async function ad(e,t){return u(await l.post(`/projects/${e}/triggers`,t))}async function cd(e,t,n){return u(await l.patch(`/projects/${e}/triggers/${t}`,n))}async function ld(e,t){return u(await l.delete(`/projects/${e}/triggers/${t}`))}async function ud(e,t){return u(await l.patch(`/projects/${e}/triggers/activation`,{paused:t}))}function pd(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 dd(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 l.post(`/projects/${e}/triggers/${t}/fire`,r))}async function gd(e,t,n){return u(await l.get(`/projects/${e}/triggers/${t}/runs${pd(n)}`))}async function md(e,t){return u(await l.get(`/projects/${e}/trigger-runs${pd(t)}`))}async function fd(e,t,n,r){return u(await l.post(`/projects/${e}/triggers/${t}/runs/${n}/replay`,r?.confirmUnverified?{confirm_unverified:!0}:{}))}async function yd(e,t){let n="connector"in t?`connector=${encodeURIComponent(t.connector)}`:`app=${encodeURIComponent(t.app)}${t.source?`&source=${encodeURIComponent(t.source)}`:""}`;return u(await l.get(`/projects/${e}/triggers/event-types?${n}`))}async function hd(e){return u(await l.get(`/projects/${e}/triggers/event-apps`))}var Qe=new Map;function wo(e,t){return`${e}::${t}`}function _d(e,t){Qe.delete(e),Qe.set(e,t)}function bd(e,t){let n=wo(e,t),r=Qe.get(n);return r&&_d(n,r),r}function Lr(e,t,n){let r=wo(e,t);if(!Qe.has(r)&&Qe.size>=512){let s=Qe.keys().next().value;s!==void 0&&Qe.delete(s)}_d(r,n)}function Pd(e,t){Qe.delete(wo(e,t))}function pw(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function cn(){return pw(I().backendUrl||"http://localhost:8008/v1")}function Sd(){let e=I().sandboxId;return e?`${cn()}/p/${e}/8000`:""}function dw(e,t=8e3){return`${cn()}/p/${e}/${t}`}function Fe(e,t=8e3){return dw(e,t)}function xd(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 ko=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 Hj(e){return e instanceof Error&&e.name==="SessionStartError"}function gw(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 ko(s,{status:n,code:r,terminal:!0}):null}function wd(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 l.post(`/projects/${e}/sessions/${t}/start${i}`,{},{showErrors:!1})}async function dt(e,t,n){let r=await wd(e,t,n);if(!r.success||!r.data){let s=gw(r.error);if(s&&!(s.status===404&&lp(t)))throw s;return null}return vd(e,t,r.data)}async function kd(e,t,n){let r=await wd(e,t,n);if(!r.success||!r.data)throw r.error??new Error("Unable to start this session");return vd(e,t,r.data)}function vd(e,t,n){let r=n.sandbox?.external_id,s=n.runtime_session_id??n.opencode_session_id;return n.stage==="ready"&&r&&s&&Lr(e,t,{runtimeSessionId:s,opencodeSessionId:s,runtimeUrl:Fe(r),sandboxId:r}),n}function zj(e,t){return["session-start",e,t]}async function Ad(e){return u(await l.get(`/projects/${e}/model-defaults`))}async function Rd(e,t){return u(await l.put(`/projects/${e}/model-defaults`,t))}async function Cd(e,t){let n=new URLSearchParams({scope:t.scope,...t.agentName?{agentName:t.agentName}:{}}).toString();return u(await l.delete(`/projects/${e}/model-defaults?${n}`))}async function tL(e,t){return u(await l.put(`/projects/${e}/model-enablement`,{modelOverrides:t}))}function Td(e){let t=[];for(let n of e){let r=n.trim();r&&!t.includes(r)&&t.push(r)}return t}function mw(e,t){if(e.length!==t.length)return!1;let n=new Set(t);return e.every(r=>n.has(r))}function $r(e){let t=e.connectors_required?Td(e.connectors_required):void 0,n=e.connectors_personal?Td(e.connectors_personal):void 0;if(t&&n&&!mw(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 Id(e,t,n){let r=$r(n);return u(await l.put(`/projects/${e}/agents/${encodeURIComponent(t)}/scope`,r))}async function pL(e,t){let n=u(await l.get(`/projects/${e}/agents/${encodeURIComponent(t)}/config`));return{...n,block:n.block?vo(n.block):null}}async function dL(e,t,n){let r=vo(n,!0),s=u(await l.put(`/projects/${e}/agents/${encodeURIComponent(t)}/config`,r));return{...s,block:s.block?vo(s.block):null}}function vo(e,t=!1){let n=$r(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 gL(e,t,n){return u(await l.post(`/projects/${e}/secrets/${encodeURIComponent(t)}/grant`,{agent:n}))}async function Ed(e,t){return u(await l.put(`/projects/${e}/default-agent`,{agent:t}))}var Ur="Use setBillingPlan().",Md="Change the plan with setBillingPlan(); manage the card in the Stripe customer portal (createPortalSession()).";function Od(){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 fw(e){let t=e.trim().toLowerCase();return t===""||t==="free"||t==="none"?"free":t==="enterprise"?"enterprise":"credits"}function _L(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??Od(),r=(n.subscription?.tier_key||n.tier?.name||"none").toString(),s=(n.tier?.display_name||"").trim()||r;return{family:fw(r),label:s,sublabel:null,monthlyUsd:null}}function yw(e){return!!e&&e.can_manage_billing!==!1}function bL(e){return e?.subscription?.can_purchase_credits===!0&&yw(e)}async function Dd(e){let t=await l.get(e,{showErrors:!1}),n=t.error?.status===404&&/billing is not enabled/i.test(t.error.message||"");if(t.error&&t.error.status!==401&&!n)throw t.error;return t.error?Od():t.data}function jd(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 Ld(e){return Dd(`/billing/account-state${jd(e)}`)}async function $d(e){return Dd(`/billing/account-state/minimal${jd(e)}`)}async function Ud(e){let t=new URLSearchParams;e?.accountId&&t.set("account_id",e.accountId),e?.limit!=null&&t.set("limit",String(e.limit)),e?.offset!=null&&t.set("offset",String(e.offset)),e?.typeFilter&&t.set("type_filter",Array.isArray(e.typeFilter)?e.typeFilter.join(","):e.typeFilter);let n=t.toString();return u(await l.get(`/billing/transactions${n?`?${n}`:""}`))}async function Fd(e){let t=new URLSearchParams;e?.accountId&&t.set("account_id",e.accountId),e?.days!=null&&t.set("days",String(e.days));let n=t.toString();return u(await l.get(`/billing/transactions/summary${n?`?${n}`:""}`))}async function Nd(){return u(await l.get("/billing/credit-breakdown"))}async function Kd(e){let t=e!=null?`?days=${e}`:"";return u(await l.get(`/billing/usage-history${t}`))}async function Bd(){return u(await l.get("/billing/tier-configurations"))}async function PL(e){let t=e.accountId?`?account_id=${encodeURIComponent(e.accountId)}`:"";return vt(e,`/v1/billing/account-state${t}`)}async function qd(e){throw U("createCheckoutSession",Ur)}async function Gd(e,t){throw U("confirmCheckoutSession",Ur)}async function Wd(e,t){return u(await l.post("/billing/create-portal-session",{account_id:t,return_url:e}),"Failed to create portal session")}async function Vd(e,t){return u(await l.post("/billing/cancel-subscription",{account_id:t,feedback:e}),"Failed to cancel subscription")}async function Hd(e){return u(await l.post("/billing/reactivate-subscription",{account_id:e}),"Failed to reactivate subscription")}async function zd(e,t,n){throw U("scheduleDowngrade","Change the plan in the Stripe customer portal (createPortalSession()).")}async function Yd(e){throw U("cancelScheduledChange",Md)}async function Jd(e,t){throw U("getProrationPreview",Md)}async function Qd(e){return u(await l.post("/billing/purchase-credits",{amount:e.amount,account_id:e.accountId,success_url:e.successUrl,cancel_url:e.cancelUrl}),"Failed to purchase credits")}async function Xd(e){let t=e?`?account_id=${encodeURIComponent(e)}`:"";return u(await l.get(`/billing/auto-topup/settings${t}`),"Failed to load auto-topup settings")}async function SL(e){return u(await l.post(`/accounts/${encodeURIComponent(e)}/top-up-requests`,{}),"Failed to ask the owners for credits")}async function Zd(e){return u(await l.post("/billing/auto-topup/configure",{account_id:e.accountId,enabled:e.enabled,threshold:e.threshold,amount:e.amount},{showErrors:!1}),"Failed to configure auto-topup")}async function xL(e){let t=e?`?account_id=${encodeURIComponent(e)}`:"";return u(await l.get(`/billing/auto-topup/setup-status${t}`,{timeout:8e3,showErrors:!1}),"Failed to load auto-topup setup status")}async function eg(e){return u(await l.post("/billing/plan/preview",{monthly_usd:e.monthlyUsd,account_id:e.accountId}),"Failed to preview the plan change")}async function tg(e){return u(await l.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 ng(e){return u(await l.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 rg(e={}){return u(await l.post("/billing/enterprise/contact",{account_id:e.accountId,...e.note?{note:e.note}:{}}),"Failed to reach Kortix sales")}async function wL(e){throw U("createPerSeatCheckout",Ur)}async function kL(e){throw U("claimPerSeatBilling",Ur)}async function vL(e){return u(await l.post("/billing/sync-subscription",{account_id:e}),"Failed to sync subscription")}async function sg(e={}){let t=new URLSearchParams;e.start&&t.set("start",e.start),e.end&&t.set("end",e.end),(e.groupBy==="model"||e.groupBy==="provider"||e.groupBy==="day")&&t.set("group_by",e.groupBy),e.accountId&&t.set("account_id",e.accountId);let n=t.toString();return u(await l.get(`/usage${n?`?${n}`:""}`))}function Ao(e,t){t.accountId&&e.set("account_id",t.accountId),t.projectId&&e.set("project_id",t.projectId)}function Fr(e,t){t.from&&e.set("from",t.from),t.to&&e.set("to",t.to)}function Nr(e){return e.size>0?`?${e}`:""}async function ig(e={}){let t=new URLSearchParams;return Ao(t,e),e.ownerId&&t.set("owner_id",e.ownerId),Fr(t,e),e.sort&&t.set("sort",e.sort),e.limit!=null&&t.set("limit",String(e.limit)),e.offset!=null&&t.set("offset",String(e.offset)),u(await l.get(`/usage/session-costs${Nr(t)}`))}async function Kr(e,t={}){let n=new URLSearchParams;return Ao(n,t),u(await l.get(`/usage/session-costs/${encodeURIComponent(e)}${Nr(n)}`))}async function EL(e={}){let t=new URLSearchParams;return e.accountId&&t.set("account_id",e.accountId),Fr(t,e),e.sort&&t.set("sort",e.sort),e.limit!=null&&t.set("limit",String(e.limit)),e.offset!=null&&t.set("offset",String(e.offset)),u(await l.get(`/usage/cost-by-project${Nr(t)}`))}async function ML(e={}){let t=new URLSearchParams;return Ao(t,e),e.sessionId&&t.set("session_id",e.sessionId),Fr(t,e),u(await l.get(`/usage/cost-summary${Nr(t)}`))}function og(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)}Fr(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 OL(e,t={}){let n=og(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 ag(e,t){return u(await l.post(`/channels/${e}/identity/bind`,{token:t}),"Failed to connect your account")}function $L(e){return ag("slack",e)}function UL(e){return ag("teams",e)}async function cg(e,t){return u(await l.post(`/channels/${e}/identity/preview`,{token:t},{showErrors:!1}),"This link is invalid or has expired")}function FL(e){return cg("slack",e)}function NL(e){return cg("teams",e)}async function lg(e){let t=await l.get(`/projects/${encodeURIComponent(e)}/channels/slack/installation`,{showErrors:!1});return t.success?t.data??null:null}async function ug(e,t){return u(await l.post(`/projects/${encodeURIComponent(e)}/channels/slack/connect`,t,{showErrors:!1}),"Failed to connect")}var hw={oauth_available:!1,install_url:null};async function pg(e){let t=await l.get(`/projects/${encodeURIComponent(e)}/channels/slack/mode`,{showErrors:!1});return!t.success||!t.data?hw:t.data}async function dg(e,t,n){return u(await l.post(`/projects/${encodeURIComponent(t)}/channels/${e}/oauth/complete`,{code:n.code,state:n.state},{showErrors:!1}),"Failed to finish the install")}function gg(e,t){return dg("slack",e,t)}function mg(e,t){return dg("teams",e,t)}async function fg(e){return u(await l.get(`/webhooks/slack/${encodeURIComponent(e)}/manifest`,{showErrors:!1}),"Failed to load Slack manifest")}async function yg(e){let t=await l.delete(`/projects/${encodeURIComponent(e)}/channels/slack/installation`,{showErrors:!1});if(!t.success)throw new Error(t.error?.message??"Failed to disconnect")}async function hg(e,t){return u(await l.get(`/projects/${encodeURIComponent(e)}/channels/slack/file?url=${encodeURIComponent(t)}`,{showErrors:!1}),"Failed to download Slack file")}async function _g(e,t){return u(await l.post(`/projects/${encodeURIComponent(e)}/channels/slack/file/upload`,{channel:t.channel,filename:t.filename,content_base64:t.contentBase64,comment:t.comment,thread_ts:t.threadTs},{showErrors:!1}),"Failed to upload Slack file")}function Ro(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 _w={provider:"agentmail",managed_available:!1};async function bg(e,t){let n=t?`?connector_slug=${encodeURIComponent(t)}`:"",r=await l.get(`/projects/${encodeURIComponent(e)}/channels/email/installation${n}`,{showErrors:!1});return r.success&&r.data?Ro(r.data):null}async function Pg(e){let t=await l.get(`/projects/${encodeURIComponent(e)}/channels/email/mode`,{showErrors:!1});return!t.success||!t.data?_w:t.data}async function Sg(e,t){let n=u(await l.post(`/projects/${encodeURIComponent(e)}/channels/email/connect`,t,{showErrors:!1}),"Failed to connect email");return Ro(n)}async function xg(e,t){let n=t?`?connector_slug=${encodeURIComponent(t)}`:"",r=await l.delete(`/projects/${encodeURIComponent(e)}/channels/email/installation${n}`,{showErrors:!1});if(!r.success)throw new Error(r.error?.message??"Failed to disconnect email")}async function wg(e,t,n){let r=u(await l.patch(`/projects/${encodeURIComponent(e)}/channels/email/installation`,{connector_slug:t??"kortix_email",sender_policy:n},{showErrors:!1}),"Failed to update email policy");return Ro(r)}async function KL(e){return u(await l.get(`/projects/${encodeURIComponent(e)}/channels/bindings`,{showErrors:!1}),"Failed to load channel bindings")}async function BL(e,t,n){return u(await l.patch(`/projects/${encodeURIComponent(e)}/channels/bindings/${encodeURIComponent(t)}`,n,{showErrors:!1}),"Failed to update channel binding")}async function kg(e){return u(await l.get(`/projects/${e}/gateway/routing-policy`),"Gateway routing policy request failed")}async function vg(e,t){return u(await l.put(`/projects/${e}/gateway/routing-policy`,t),"Gateway routing policy request failed")}async function Ag(e){return u(await l.delete(`/projects/${e}/gateway/routing-policy`),"Gateway routing policy request failed")}async function Rg(e,t){return u(await l.post(`/projects/${e}/gateway/routing-policy/preview`,t),"Gateway route preview failed")}async function Cg(e,t){let n=new URLSearchParams;t?.limit&&n.set("limit",String(t.limit)),t?.offset&&n.set("offset",String(t.offset)),t?.ok!==void 0&&n.set("ok",String(t.ok));let r=n.toString();return u(await l.get(`/projects/${e}/gateway/logs${r?`?${r}`:""}`),"Gateway request failed")}async function Tg(e,t){return u(await l.get(`/projects/${e}/gateway/logs/${t}`),"Gateway request failed")}async function Ig(e,t){return u(await l.get(`/projects/${e}/gateway/overview${t?`?days=${t}`:""}`),"Gateway request failed")}async function Eg(e,t){return u(await l.get(`/projects/${e}/gateway/series${t?`?days=${t}`:""}`),"Gateway request failed")}async function Mg(e,t){return u(await l.get(`/projects/${e}/gateway/breakdown${t?`?days=${t}`:""}`),"Gateway request failed")}async function Og(e,t){return u(await l.get(`/projects/${e}/gateway/sessions${t?`?days=${t}`:""}`),"Gateway request failed")}async function Dg(e,t){return u(await l.get(`/projects/${e}/gateway/errors${t?`?days=${t}`:""}`),"Gateway request failed")}async function jg(e){return u(await l.get(`/projects/${e}/gateway/budgets`),"Gateway request failed")}async function Lg(e,t){return u(await l.put(`/projects/${e}/gateway/budgets`,t),"Gateway request failed")}async function $g(e,t){return u(await l.delete(`/projects/${e}/gateway/budgets/${t}`),"Gateway request failed")}async function Ug(e){return u(await l.get(`/projects/${e}/gateway/keys`),"Gateway request failed")}async function Fg(e,t){return u(await l.post(`/projects/${e}/gateway/keys`,{name:t}),"Gateway request failed")}async function Ng(e,t){return u(await l.delete(`/projects/${e}/gateway/keys/${t}`),"Gateway request failed")}async function Kg(e,t,n,r,s){return u(await l.post(`/projects/${e}/gateway/playground`,{prompt:t,models:n,...r?{system:r}:{},...s&&Object.keys(s).length?{generationConfig:s}:{}}),"Gateway request failed")}async function VL(e,t){return u(await l.post(`/projects/${e}/gateway/providers/${encodeURIComponent(t)}/verify`,{}),"Gateway provider verification failed")}async function YL(){throw U("getReferralCode")}async function JL(){throw U("refreshReferralCode")}async function QL(e){throw U("validateReferralCode")}async function XL(){throw U("getReferralStats")}async function ZL(e={}){throw U("listReferrals")}async function e$(e){throw U("sendReferralEmails")}var Co="call:";function qg(e){return e.startsWith("cr:")&&e.length>3?{type:"change_request",changeRequestId:e.slice(3)}:e.startsWith(Co)&&e.length>Co.length?{type:"connector_call",executionId:e.slice(Co.length)}:{type:"review_item",reviewItemId:e}}function bw(e){return e==="needs_you"?"needs_you":e==="waiting"?"waiting":"done"}function n$(e){let t={needs_you:0,waiting:0,done:0};for(let n of e)t[bw(n.status)]+=1;return t}function r$(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 To(e){return e.split(/[._-]/).filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function Gg(e){let t=e.indexOf(".");return t<=0?To(e):`(${To(e.slice(0,t))}) ${To(e.slice(t+1))}`}function Pw(e){let t=e.indexOf(".");return t>0?{connector:e.slice(0,t),action:e.slice(t+1)}:{connector:e,action:""}}var Br=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{},F=e=>typeof e=="string"&&e?e:void 0,Ce=e=>Array.isArray(e)?e:void 0,Bg=e=>typeof e=="number"?e:0,Sw=e=>e.split(`
|
|
14
|
-
`).map(t=>t.trim()).filter(Boolean);function xw(e,t){let n=Br(e.advanced),r=F(e.description),s=Ce(e.whatChanged)??(r?Sw(r):t.summary?[t.summary]:[]);return{crId:F(e.cr_id),number:typeof e.number=="number"?e.number:void 0,whatChanged:s,impact:F(e.impact)??"",verification:Ce(e.verification)??[],previewUrl:F(e.previewUrl)??F(e.preview_url),conflicts:Ce(e.conflicts),requestedChanges:Ce(e.requested_changes)??[],advanced:{headRef:F(n.headRef)??F(e.head_ref)??"",baseRef:F(n.baseRef)??F(e.base_ref)??"",headSha:F(n.headSha)??F(e.head_sha)??F(e.head_commit_sha)??"",baseSha:F(n.baseSha)??F(e.base_sha)??"",additions:Bg(n.additions),deletions:Bg(n.deletions),files:Ce(n.files)??[],mergeMode:F(n.mergeMode)??"merge"}}}function ww(e,t){let n=Ce(e.actions);if(n)return{actions:n.map((c,p)=>({id:F(c.id)??`${t.review_item_id}-${p}`,title:F(c.title)??"Action",connector:F(c.connector)??"",action:F(c.action)??"",consequence:F(c.consequence)??"",risk:F(c.risk)??t.risk,icon:F(c.icon)??"generic",argsPreview:Ce(c.argsPreview)??[],policySource:F(c.policySource)??"Requires approval",decided:c.decided==="approved"||c.decided==="denied"?c.decided:void 0}))};let r=F(e.action_path)??"",{connector:s,action:o}=Pw(r),i=Br(e.args_preview),a=Object.keys(i).length>0;return{actions:[{id:F(e.execution_id)??t.review_item_id,title:r?Gg(r):t.title||"Run action",connector:s,action:o,consequence:"Runs against the real connector once you approve",risk:t.risk,icon:"generic",argsPreview:Object.entries(i).map(([c,p])=>({key:c,value:p==="[redacted]"?"Hidden credential":typeof p=="string"?p:JSON.stringify(p,null,2)})),actionPath:r,rawArgsPreview:a?i:void 0,reviewComplete:e.args_preview_complete===!0,previewAuthorized:e.args_preview_authorized!==!1,canResolve:typeof t.can_resolve=="boolean"?t.can_resolve:e.args_preview_authorized!==!1,...t.resolvers?{resolvers:t.resolvers}:{},approvalContext:F(e.approval_context),connectorRisk:F(e.risk)??null,policySource:"Requires approval"}]}}function kw(e,t){return{artifactKind:F(e.artifactKind)??"document",artifactLabel:F(e.artifactLabel)??"Output",previewUrl:F(e.previewUrl)??F(e.preview_url),preview:F(e.preview),files:Ce(e.files),note:F(e.note)??t.summary??""}}function vw(e,t){return{question:F(e.question)??t.title??"",context:F(e.context),options:Ce(e.options)??[]}}function Aw(e,t){return{note:F(e.note)??t.summary??"",children:Ce(e.children)??[]}}function Rw(e){let t=Br(e.detail);switch(e.kind){case"change":return xw(t,e);case"approval":return ww(t,e);case"output":return kw(t,e);case"decision":return vw(t,e);case"batch":return Aw(t,e)}}function Cw(e,t){let n=typeof e.number=="number"?e.number:void 0,r=F(e.base_ref);return n!=null&&r?`#${n} \u2192 ${r}`:t}function s$(e,t={}){let n=Br(e.detail),r=e.origin_session_id??void 0,s=r?t.sessionLabels?.[r]:void 0,o=e.kind==="approval"?F(n.action_path):void 0,i=e.kind==="change"?Cw(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?Gg(o):e.title,summary:i,risk:e.risk,status:e.status,source:e.source,agent:e.agent||"Agent",createdAt:e.created_at,sessionId:r,detail:Rw(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_CREDENTIALS_ISSUE:"project.credentials.issue"},a$=[Z.PROJECT_WRITE,Z.PROJECT_TRIGGER_CREATE,Z.PROJECT_TRIGGER_FIRE,Z.PROJECT_TRIGGER_UPDATE,Z.PROJECT_TRIGGER_DELETE];function c$(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 l$=[Z.PROJECT_WRITE,Z.PROJECT_GITOPS_PUSH,Z.PROJECT_GITOPS_MERGE,Z.PROJECT_REVIEW_ACT];function Tw(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 u$(e,t,n){let r=qg(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 Tw(n).canMerge}return n[Z.PROJECT_WRITE]?.allowed===!0&&n[Z.PROJECT_REVIEW_ACT]?.allowed===!0}function $(e){return l.get(e,{showErrors:!1})}function A(e){return u(e,"Unexpected empty response")}async function Wg(e){return A(await $(`/accounts/${e}/iam/groups`)).groups}async function Vg(e,t){return A(await $(`/accounts/${e}/iam/groups/${t}`))}async function Hg(e,t){return A(await l.post(`/accounts/${e}/iam/groups`,t,{showErrors:!1}))}async function zg(e,t,n){return A(await l.patch(`/accounts/${e}/iam/groups/${t}`,n))}async function Yg(e,t){return A(await l.delete(`/accounts/${e}/iam/groups/${t}`))}async function Jg(e,t){return A(await $(`/accounts/${e}/iam/groups/${t}/members`)).members}async function Qg(e,t,n){return A(await l.post(`/accounts/${e}/iam/groups/${t}/members`,{userIds:n}))}async function h$(e,t){return A(await $(`/accounts/${e}/iam/groups/${t}/project-grants`)).grants}async function Xg(e,t,n){return A(await l.delete(`/accounts/${e}/iam/groups/${t}/members/${n}`))}async function _$(e,t){return A(await $(`/accounts/${e}/iam/members/${t}/groups`)).groups}async function b$(e,t){let n=A(await $(`/accounts/${e}/iam/members/${t}/project-access`));return{projects:n.projects,account_wide_policies:n.account_wide_policies??[]}}function Xe(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 k$(e,t={}){let n=Xe({resourceType:t.resourceType,principalType:t.principalType,principalId:t.principalId,projectId:t.projectId});return A(await $(`/accounts/${e}/iam/resource-grants${n}`)).grants}async function T$(e,t={}){let n=Xe({principalType:t.principalType,principalId:t.principalId,scopeType:t.scopeType,scopeId:t.scopeId===null?"null":t.scopeId});return A(await $(`/accounts/${e}/iam/policies${n}`)).policies}async function I$(e,t){return A(await l.post(`/accounts/${e}/iam/policies`,t,{showErrors:!1}))}async function E$(e,t,n){return A(await l.patch(`/accounts/${e}/iam/policies/${t}`,n,{showErrors:!1}))}async function M$(e,t){return A(await l.delete(`/accounts/${e}/iam/policies/${t}`))}async function O$(e,t){return A(await l.post(`/accounts/${e}/iam/policies:bulk-delete`,{policy_ids:t},{showErrors:!1}))}async function D$(e,t){return A(await l.post(`/accounts/${e}/iam/policies:bulk-import`,{policies:t},{showErrors:!1}))}async function Zg(e){return A(await $(`/accounts/${e}/iam/roles`)).roles}async function em(e){return A(await $(`/accounts/${e}/iam/agent-identities`)).agents}async function tm(e){return A(await l.get(`/projects/${e}/agent-identities`,{showErrors:!1})).agents}async function nm(e,t){return A(await $(`/accounts/${e}/iam/roles/${t}/permissions`))}async function U$(e){return A(await $(`/accounts/${e}/iam/actions`)).actions}async function rm(e,t){return A(await $(`/accounts/${e}/iam/roles/${t}/usage`))}async function sm(e,t){return A(await l.post(`/accounts/${e}/iam/roles`,t,{showErrors:!1}))}async function om(e,t,n){return A(await l.patch(`/accounts/${e}/iam/roles/${t}`,n,{showErrors:!1}))}async function im(e,t,n){return A(await l.put(`/accounts/${e}/iam/roles/${t}/permissions`,{actions:n},{showErrors:!1}))}async function am(e,t){return A(await l.delete(`/accounts/${e}/iam/roles/${t}`,{showErrors:!1}))}async function F$(e,t,n){return A(await l.patch(`/accounts/${e}/iam/members/${t}/super-admin`,{isSuperAdmin:n}))}async function q$(e){return A(await $(`/accounts/${e}/iam/scim/tokens`)).tokens}async function G$(e,t){return A(await l.post(`/accounts/${e}/iam/scim/tokens`,t,{showErrors:!1}))}async function W$(e,t){return A(await l.delete(`/accounts/${e}/iam/scim/tokens/${t}`))}async function Y$(e){return A(await $(`/accounts/${e}/iam/mfa-required`))}async function J$(e){return A(await $(`/accounts/${e}/iam/mfa-required/preview`))}async function Q$(e,t){return A(await l.patch(`/accounts/${e}/iam/mfa-required`,{enabled:t},{showErrors:!1}))}async function X$(e){return A(await $(`/accounts/${e}/iam/session-oversight`))}async function Z$(e,t){return A(await l.patch(`/accounts/${e}/iam/session-oversight`,{enabled:t},{showErrors:!1}))}async function r0(e){return A(await $(`/accounts/${e}/iam/sso/provider`)).provider}async function s0(e,t){return A(await l.put(`/accounts/${e}/iam/sso/provider`,t,{showErrors:!1})).provider}async function o0(e,t){return A(await l.post(`/accounts/${e}/iam/sso/provider/from-metadata`,t,{showErrors:!1})).provider}async function i0(e){return A(await l.post(`/accounts/${e}/iam/sso/provider/verify-domain`,{},{showErrors:!1})).provider}async function a0(e){return A(await l.delete(`/accounts/${e}/iam/sso/provider`))}async function c0(e){return A(await $(`/accounts/${e}/iam/sso/mappings`)).mappings}async function l0(e,t){return A(await l.post(`/accounts/${e}/iam/sso/mappings`,t,{showErrors:!1}))}async function u0(e,t){return A(await l.delete(`/accounts/${e}/iam/sso/mappings/${t}`))}async function m0(e){return A(await $(`/accounts/${e}/iam/session-policy`))}async function f0(e,t){return A(await l.patch(`/accounts/${e}/iam/session-policy`,t,{showErrors:!1}))}async function y0(e){return A(await $(`/accounts/${e}/iam/sessions`)).sessions}async function h0(e,t){return A(await l.post(`/accounts/${e}/iam/sessions/${t}/revoke`,{},{showErrors:!1}))}async function _0(e){return A(await $(`/accounts/${e}/iam/pat-policy`))}async function b0(e,t){return A(await l.patch(`/accounts/${e}/iam/pat-policy`,t,{showErrors:!1}))}async function w0(e){return A(await $(`/accounts/${e}/iam/service-accounts`)).service_accounts}async function k0(e,t){return A(await l.post(`/accounts/${e}/iam/service-accounts`,t,{showErrors:!1}))}async function v0(e,t){return A(await l.post(`/accounts/${e}/iam/service-accounts/${t}/disable`,{},{showErrors:!1}))}async function A0(e,t){return A(await l.delete(`/accounts/${e}/iam/service-accounts/${t}`))}async function E0(e){return A(await $(`/accounts/${e}/audit/webhooks`)).webhooks}async function M0(e,t){return A(await l.post(`/accounts/${e}/audit/webhooks`,t,{showErrors:!1}))}async function O0(e,t,n){return A(await l.patch(`/accounts/${e}/audit/webhooks/${t}`,n))}async function D0(e,t){return A(await l.delete(`/accounts/${e}/audit/webhooks/${t}`))}async function j0(e,t={}){let n=Xe({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 $(`/accounts/${e}/audit${n}`))}async function cm(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 $(`/accounts/${e}/iam/members/${t}/effective?${r.toString()}`))}async function lm(e,t,n){return n.length===0?[]:A(await l.post(`/accounts/${e}/iam/members/${t}/effective:batch`,{probes:n})).results}async function B0(e){return A(await $(`/accounts/${e}/iam/enterprise-demo`)).enabled}async function q0(e,t){return A(await l.put(`/accounts/${e}/iam/enterprise-demo`,{enabled:t})).enabled}async function um(e){return u(await l.get(`/accounts/${e}/iam/oauth-clients`,{showErrors:!1}))}async function pm(e,t){return u(await l.get(`/accounts/${e}/iam/oauth-clients/${t}`,{showErrors:!1}))}async function dm(e,t){return u(await l.post(`/accounts/${e}/iam/oauth-clients`,t,{showErrors:!1}))}async function gm(e,t,n){return u(await l.patch(`/accounts/${e}/iam/oauth-clients/${t}`,n,{showErrors:!1}))}async function mm(e,t){return u(await l.post(`/accounts/${e}/iam/oauth-clients/${t}/rotate-secret`,{},{showErrors:!1}))}async function fm(e,t){return u(await l.delete(`/accounts/${e}/iam/oauth-clients/${t}`,{showErrors:!1}))}function Iw(e){return Xe({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 ym(e,t){return u(await $(`/accounts/${e}/iam/assignments${Iw(t)}`)).assignments}async function hm(e,t){let n={principal_type:t.principal.type,principal_id:t.principal.id,scope_type:t.scope.type,scope_id:t.scope.type==="project"?t.scope.id:null};return t.roleId?n.role_id=t.roleId:n.role_key=t.roleKey,t.object&&(n.object_type=t.object.type,n.object_id=t.object.id),t.expiresAt!==void 0&&(n.expires_at=t.expiresAt),u(await l.post(`/accounts/${e}/iam/assignments`,n))}async function _m(e,t){return u(await l.delete(`/accounts/${e}/iam/assignments/${t}`)).assignment}async function bm(e,t){let n=t?.scopeType?`?scope_type=${t.scopeType}`:"";return u(await $(`/accounts/${e}/iam/permissions${n}`)).permissions}async function tU(){let e=await l.get("/account/deletion-status",{showErrors:!1});return e.error?.status===404?null:u(e,"Failed to load account deletion status")}async function nU(e="User requested deletion"){return u(await l.post("/account/request-deletion",{reason:e},{showErrors:!1}),"Failed to request account deletion")}async function rU(){return u(await l.post("/account/cancel-deletion",void 0,{showErrors:!1}),"Failed to cancel account deletion")}async function sU(){return u(await l.delete("/account/delete-immediately",{showErrors:!1}),"Failed to delete account immediately")}async function oU(){return(await l.get("/user-roles",{showErrors:!1})).data??{isAdmin:!1,role:null}}function lU(){return l.get("/admin/api/provider-distribution").then(e=>u(e))}function uU(e=300){return l.get(`/admin/api/sandboxes?limit=${e}`).then(t=>u(t))}function pU(e){return l.put("/admin/api/provider-distribution",e).then(t=>u(t))}function dU(e){return l.get(`/admin/api/provider-analytics?days=${e}`).then(t=>u(t))}function gU(e,t){return l.post(`/admin/api/sandboxes/${encodeURIComponent(e)}/migrate`,{targetProvider:t}).then(n=>u(n))}function mU(){return l.get("/admin/api/provider-fallback").then(e=>u(e))}function fU(e){return l.put("/admin/api/provider-fallback",{enabled:e}).then(t=>u(t))}var Pm="Export the deck as PDF or PPTX with convertRuntimePresentation().";async function _U(e){throw U("getGoogleAuthUrl",Pm)}async function bU(e,t){throw U("convertPresentationToGoogleSlides",Pm)}async function Sm(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 l.get(`/projects/${e}/review/items${r?`?${r}`:""}`,{showErrors:!1}))}async function xm(e){return u(await l.get(`/projects/${e}/review/summary`,{showErrors:!1}))}async function wm(e,t){return u(await l.get(`/projects/${e}/review/items/${t}`))}async function km(e,t){return u(await l.post(`/projects/${e}/review/items`,t))}async function vm(e,t,n){return u(await l.post(`/projects/${e}/review/items/${t}/act`,n))}async function Am(e,t){return u(await l.post(`/projects/${e}/review/bulk`,t))}async function Rm(e){return u(await l.get(`/p/share?sandbox_id=${encodeURIComponent(e)}`),"Failed to load public links").shares??[]}async function Cm(e){return u(await l.post("/p/share",{sandbox_id:e.sandboxId,port:e.port,ttl:e.ttl,label:e.label}),"Failed to generate public URL")}async function Tm(e,t){let n=await l.delete(`/p/share/${encodeURIComponent(t)}?sandbox_id=${encodeURIComponent(e)}`);if(!n.success)throw new Error(n.error?.message??"Failed to revoke public link")}var Io=class extends Error{constructor(n,r){super(n);this.status=r;this.name="PublicSessionShareError"}status};function Im(e,t=""){return`${cn()}/public/session-shares/${encodeURIComponent(e)}${t}`}async function Em(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 Io(s,t.status)}return r}async function CU(e){return Em(Im(e))}async function TU(e){return Em(Im(e,"/messages"))}async function Mm(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/reminders`))}async function Om(e,t,n){return u(await l.post(`/projects/${e}/sessions/${t}/reminders`,n))}async function Eo(e,t,n,r){return u(await l.patch(`/projects/${e}/sessions/${t}/reminders/${n}`,r))}async function Mo(e,t,n){return u(await l.delete(`/projects/${e}/sessions/${t}/reminders/${n}`))}var Ew=4;async function Dm(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(Ew,e.length)},s));let o={done:[],failed:[]};return e.forEach((i,a)=>{let c=n[a];c.ok?o.done.push(i):o.failed.push({reminder:i,error:c.error})}),o}function jm(e,t,n){return Dm(t,r=>Eo(e,r.sessionId,r.reminderId,n))}function Lm(e,t){return Dm(t,n=>Mo(e,n.sessionId,n.reminderId))}async function $m(e){return u(await l.get(`/projects/${e}/reminders`))}async function Um(e,t){let n=new URLSearchParams;e&&n.set("account_id",e),t?.mine&&n.set("mine","true");let r=n.size>0?`?${n.toString()}`:"";return u(await l.get(`/accounts/tokens${r}`))}async function Fm(e){let{accountId:t,expiresAt:n,projectId:r,name:s}=e;return u(await l.post("/accounts/tokens",{name:s,...t?{account_id:t}:{},...n?{expires_at:n}:{},...r?{project_id:r}:{}}))}async function Nm(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 l.delete(`/accounts/tokens/${encodeURIComponent(e)}${s}`))}async function Km(){return u(await l.get("/oauth/grants")).grants}async function Bm(e){return u(await l.delete(`/oauth/grants/${encodeURIComponent(e)}`))}async function LU(){return u(await l.get("/accounts/me/devices")).devices}async function $U(e){return u(await l.delete(`/accounts/me/devices/${encodeURIComponent(e)}`))}async function qm(e){return u(await l.get(`/projects/${e}/cli-token`))}async function Gm(e,t){return u(await l.post(`/projects/${e}/cli-token`,t??{}))}async function Wm(e,t){return u(await l.delete(`/projects/${e}/cli-token/${t}`))}function Dt(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 Oo(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 Vm(e,t){let n=Dt(Oo(t)).toString();return u(await l.get(`/accounts/${e}/audit${n?`?${n}`:""}`))}async function Hm(e,t){let n=Dt(Oo({...t,projectId:void 0})).toString();return u(await l.get(`/projects/${e}/audit${n?`?${n}`:""}`))}async function zm(e,t){let n=Dt(Oo(t)).toString();return u(await l.get(`/accounts/${e}/audit/export${n?`?${n}`:""}`))}async function Ym(e){return u(await l.get(`/accounts/${e}/audit/webhooks`))}async function Jm(e,t){return u(await l.post(`/accounts/${e}/audit/webhooks`,t))}async function Qm(e,t,n){return u(await l.patch(`/accounts/${e}/audit/webhooks/${t}`,n))}async function Xm(e,t){return u(await l.delete(`/accounts/${e}/audit/webhooks/${t}`))}async function Zm(e,t){return u(await l.post(`/projects/${e}/secret-requests`,{names:t.names,labels:t.labels,descriptions:t.descriptions,scope:t.scope,expires_in_minutes:t.expiresInMinutes}),"Failed to mint secret-entry link")}async function ef(e,t){return u(await l.post(`/projects/${e}/connect-requests`,{slug:t.slug,...t.owner?{owner:t.owner}:{},...t.label?{label:t.label}:{},expires_in_minutes:t.expiresInMinutes}),"Failed to mint connect link")}async function VU(e){return u(await l.get(`/approval-links/${e}`),"Failed to load approval")}async function tf(e){let t=new URLSearchParams;e?.query&&t.set("query",e.query),e?.type&&t.set("type",e.type),e?.source&&t.set("source",e.source),e?.limit!==void 0&&t.set("limit",String(e.limit)),e?.offset!==void 0&&t.set("offset",String(e.offset));let n=t.toString()?`?${t.toString()}`:"";return u(await l.get(`/marketplace/items${n}`))}async function nf(){return u(await l.get("/marketplace/marketplaces"))}async function rf(){return u(await l.get("/marketplace/marketplaces/featured"))}async function sf(e){return u(await l.get(`/marketplace/items/${encodeURIComponent(e)}`),"Item not found")}async function of(e,t){return u(await l.get(`/marketplace/items/${encodeURIComponent(e)}/file?path=${encodeURIComponent(t)}`),"File not found")}async function af(){return u(await l.get("/marketplace/sources"))}async function cf(e){return u(await l.post("/marketplace/sources",e),"Failed to add marketplace source")}async function lf(e){return u(await l.delete(`/marketplace/sources/${encodeURIComponent(e)}`),"Failed to remove marketplace source")}async function JU(e,t){return u(await l.post(`/projects/${encodeURIComponent(e)}/marketplace/install-session`,{id:t}),"Failed to start marketplace install session")}async function ZU(e){throw U("getTemplate")}async function eF(e,t){throw U("installTemplate")}async function uf(e){return u(await l.get(`/projects/${e}/apps`),"Failed to list Apps").apps}async function pf(e,t){return u(await l.post(`/projects/${e}/apps`,t),"Failed to create App")}async function Do(e,t){return u(await l.get(`/projects/${e}/apps/${t}`),"Failed to load App")}async function df(e,t,n){return u(await l.patch(`/projects/${e}/apps/${t}`,n),"Failed to update App")}async function gf(e,t){return u(await l.delete(`/projects/${e}/apps/${t}`),"Failed to delete App")}async function mf(e,t){return u(await l.post(`/projects/${e}/apps/${t}/token`,{}),"Failed to mint an App token")}async function ff(e,t){let n=await Do(e,t);if(!n.auth)throw new Error("This server does not report sign-in values for Apps.");let r=u(await l.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 yf(e,t){return u(await l.get(`/projects/${e}/apps/${t}/access`),"Failed to load App access policy")}async function hf(e,t){return u(await l.get(`/projects/${e}/apps/${t}/agents`),"Failed to load the agents with access to this App").agents}async function _f(e,t,n){return u(await l.patch(`/projects/${e}/apps/${t}/access`,n),"Failed to update App access policy")}async function bf(e,t){return u(await l.post(`/projects/${e}/apps/${t}/access-session`,{}),"Failed to create App access session")}async function jo(e,t){return u(await l.post(`/projects/${e}/apps/artifacts`,t),"Failed to register App artifact")}async function Lo(e,t,n){return u(await l.post(`/projects/${e}/apps/artifacts/${t}/finalize`,n),"Failed to finalize App artifact")}async function Mw(e){return e instanceof Uint8Array?e:new Uint8Array(await e.arrayBuffer())}async function Ow(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 Pf(e,t,n={}){let r=await Mw(t),s=n.mediaType??"application/gzip",o=await jo(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),Lo(e,o.artifact.artifact_id,{sha256:await Ow(r),size_bytes:r.byteLength})}async function Sf(e,t,n){return u(await l.post(`/projects/${e}/apps/${t}/deployments`,n),"Failed to create App deployment")}async function xf(e,t){return u(await l.get(`/projects/${e}/apps/${t}/deployments`),"Failed to list App deployments").deployments}async function wf(e,t,n){return u(await l.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 l.get(`/projects/${e}/apps/${t}/deployments/${n}/logs${o}`),"Failed to load App logs")}async function vf(e,t){return u(await l.post(`/projects/${e}/apps/${t}/start`,{}),"Failed to start App")}async function Af(e,t){return u(await l.post(`/projects/${e}/apps/${t}/stop`,{}),"Failed to stop App")}async function Rf(e,t,n){return u(await l.delete(`/projects/${e}/apps/${t}/deployments/${n}`),"Failed to delete App deployment")}async function Cf(e,t,n){return u(await l.post(`/projects/${e}/apps/${t}/rollback`,{deployment_id:n}),"Failed to roll back App")}var ye=(e,t)=>`/projects/${e}/apps/${t}`;async function Tf(e,t){return u(await l.get(`${ye(e,t)}/machines`),"Failed to list machines").machines}async function $o(e,t,n,r){return u(await l.post(`${ye(e,t)}/machines/${n}/${r}`,{}),`Failed to ${r} the machine`).machines}var If=(e,t,n)=>$o(e,t,n,"start"),Ef=(e,t,n)=>$o(e,t,n,"stop"),Mf=(e,t,n)=>$o(e,t,n,"restart");async function Of(e,t,n){return u(await l.delete(`${ye(e,t)}/machines/${n}`),"Failed to destroy the machine").machines}async function Df(e,t,n,r={}){return u(await l.put(`${ye(e,t)}/scale`,{count:n,...r.newVolumes?{new_volumes:!0}:{}}),"Failed to scale the App")}async function jf(e,t,n){return u(await l.post(`${ye(e,t)}/exec`,n),"Failed to run the command")}async function Lf(e,t){return u(await l.get(`${ye(e,t)}/volumes`),"Failed to list volumes").volumes}async function $f(e,t,n){return u(await l.post(`${ye(e,t)}/volumes`,n),"Failed to create the volume")}async function Uf(e,t,n,r){return u(await l.patch(`${ye(e,t)}/volumes/${n}`,r),"Failed to update the volume")}async function Ff(e,t,n,r){u(await l.delete(`${ye(e,t)}/volumes/${n}?confirm=${encodeURIComponent(r)}`),"Failed to destroy the volume")}async function Nf(e,t,n){return u(await l.get(`${ye(e,t)}/volumes/${n}/snapshots`),"Failed to list snapshots").snapshots}async function Kf(e,t,n){return u(await l.post(`${ye(e,t)}/volumes/${n}/snapshots`,{}),"Failed to take the snapshot")}async function Bf(e,t,n,r){return u(await l.post(`${ye(e,t)}/volumes/${n}/restore`,{snapshot_id:r}),"Failed to restore the volume")}async function qf(e,t,n,r){return u(await l.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 de=e=>`/drives/${encodeURIComponent(e)}`;async function mF(e){let t=u(await l.get(`/drives?${new URLSearchParams({projectId:e})}`),"Failed to load files").drives;if(!t[0])throw new x("Files not found",{status:404});return t[0]}async function fF(e,t){return u(await l.get(`${de(e)}/access?${new URLSearchParams({path:t})}`),"Failed to load sharing")}async function yF(e,t){return u(await l.put(`${de(e)}/access`,t),"Failed to share folder")}async function hF(e,t){let n=u(await l.delete(`${de(e)}/access/${encodeURIComponent(t)}`),"Failed to stop sharing");return{pendingSessions:typeof n?.pendingSessions=="number"?n.pendingSessions:0}}async function _F(e){return u(await l.get(`${de(e)}/principals`),"Failed to load people")}async function bF(e){return u(await l.get(`${de(e)}/conflicts`),"Failed to load conflicts").conflicts}async function PF(e,t){u(await l.post(`${de(e)}/conflicts/${encodeURIComponent(t)}/dismiss`,{}),"Failed to dismiss conflict")}async function SF(e,t="/"){return(await Dw(e,t)).entries}async function Dw(e,t="/"){return u(await l.get(`${de(e)}/files?${new URLSearchParams({path:t})}`),"Failed to load files")}function Gf(e,t,n){let r=pe(I().backendUrl),s={path:t};return n?.download&&(s.download="1"),`${r}${de(e)}/files/content?${new URLSearchParams(s)}`}async function xF(e,t,n){let r=await L(Gf(e,t),{signal:n});if(!r.ok){let s=await r.json().catch(()=>null);throw new x(s?.message||"Could not download file",{status:r.status})}return r.blob()}async function wF(e,t,n){let r=await L(Gf(e,t),{signal:n});if(!r.ok){let s=await r.json().catch(()=>null);throw new x(s?.message||"Could not download file",{status:r.status})}return{blob:await r.blob(),version:r.headers.get("etag")}}async function kF(e,t,n,r){return u(await l.putRaw(`${de(e)}/files/content?${new URLSearchParams({path:t})}`,n,{signal:r?.signal,...r?.ifMatch?{headers:{"If-Match":r.ifMatch}}:{}}),"Failed to upload file")}async function vF(e,t){return u(await l.post(`${de(e)}/files/mkdir`,{path:t}),"Failed to create folder")}async function AF(e,t,n){return u(await l.post(`${de(e)}/files/move`,{from:t,to:n}),"Failed to move")}async function RF(e,t,n){let r={path:t};n?.recursive&&(r.recursive="true"),u(await l.delete(`${de(e)}/files?${new URLSearchParams(r)}`),"Failed to delete")}async function CF(e){return u(await l.get(`${de(e)}/versions`),"Failed to load versions").versions}async function TF(e,t){u(await l.post(`${de(e)}/restore`,{versionId:t}),"Failed to restore version")}var jw=(e,t)=>`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/drives`;async function IF(e,t){return(await Lw(e,t)).drives}async function Lw(e,t){return u(await l.get(jw(e,t)),"Failed to load session files")}async function Wf(e){return u(await l.post("/notifications/device-token",e))}async function Vf(e,t){return u(await l.delete(`/notifications/device-token/${encodeURIComponent(e)}`,{signal:t?.signal}))}var DF=["turn_done","turn_error","question","permission","shared","automation_failed","automation_recovered","capture_device_down","capture_device_recovered"];async function Hf(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 l.get(`/notifications${r?`?${r}`:""}`,{showErrors:!1,signal:t?.signal}))}async function zf(e){let t="ids"in e?{ids:e.ids}:"all"in e?{all:!0}:{session_id:e.sessionId};return u(await l.post("/notifications/read",t))}var jF={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}};async function Yf(){return u(await l.get("/notifications/preferences",{showErrors:!1}))}async function Jf(e){return u(await l.put("/notifications/preferences",e))}async function Qf(){return u(await l.get("/notifications/web-push/key",{showErrors:!1}))}async function Xf(e){let t={endpoint:e.endpoint,keys:{p256dh:e.keys.p256dh,auth:e.keys.auth}};return u(await l.post("/notifications/web-push/subscriptions",t,{showErrors:!1}))}async function Zf(e,t){return u(await l.delete(`/notifications/web-push/subscriptions?endpoint=${encodeURIComponent(e)}`,{signal:t?.signal,showErrors:!1}))}async function qr(e){return u(await l.get(`/projects/${e}/model-access`))}async function Gr(e,t){return u(await l.put(`/projects/${e}/model-access`,t))}function NF(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 Uo(e){return typeof e=="string"&&e.trim().length>0}function ey(e){if(!e||typeof e!="object")return!1;let{path:t,url:n,content:r}=e;return Uo(t)||Uo(n)||Uo(r)}function $w(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 Wr(e){if(!e)return!0;let t=$w(e.items);return t?!t.some(ey):!ey(e)}var Te="kortix.transcript.v1",Uw=["auth","rate_limit","credits","context_length","output_length","aborted","unknown"];function ty(e){return typeof e=="string"&&Uw.includes(e)}var BF=["once","always","reject"],qF=["read","edit","glob","grep","list","bash","task","external_directory","todowrite","question","webfetch","websearch","lsp","doom_loop","skill"];var sy="kortix-v1-import",Fw={harness:sy,harness_version:Te,adapter_version:"1"},Fo={schema:le,v:1},Nw={opencode:"[Tool execution was interrupted]",pi:"No result provided"},Kw="[Old tool result content cleared]",Bw="The following tool was executed by the user",qw=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"})),Gw=e=>qw.get(e)??(e.includes("_")?"mcp":"other"),Ww=new Map([["stop","stop"],["tool-calls","tool_calls"],["length","length"],["error","error"]]),Vw=new Map([["stop","stop"],["tool_calls","tool-calls"],["length","length"],["error","error"]]),K=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),J=e=>typeof e=="string"?e:void 0,Ne=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,Yr=(e,t)=>Object.hasOwn(e,t)?e[t]:void 0,oy=(e,t,n)=>Object.defineProperty(e,t,{value:n,enumerable:!0,writable:!0,configurable:!0}),jt=e=>Ne(e)!==void 0&&Math.abs(e)<=864e13?new Date(e).toISOString():null,Lt=e=>{let t=e?Date.parse(e):NaN;return Number.isNaN(t)?void 0:t};function No(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)=>No(r,t[s]));if(!K(e)||!K(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=>No(e[r],Yr(t,r)))}function Hr(e,t){if(No(e,t))return;if(e===void 0)return{del:!0};if(!K(e)||!K(t))return{set:e};let n={};for(let r of new Set([...Object.keys(e),...Object.keys(t)])){let s=Hr(Yr(e,r),Yr(t,r));s&&oy(n,r,s)}return{sub:n}}function zr(e,t){if(!t)return e;if("set"in t)return t.set;if("del"in t)return;let n=K(e)?{...e}:{};for(let[r,s]of Object.entries(t.sub)){let o=zr(Yr(n,r),s);o===void 0?delete n[r]:oy(n,r,o)}return n}var ln=e=>Object.values(e??{}).find(t=>t.version===Te),Jr=(e,t)=>({[e]:{version:Te,...t}}),iy=(e,t)=>e.url!==void 0?{url:e.url}:e.ref!==void 0&&!t.fromV1?{url:e.ref}:{},ny=e=>(e??[]).flatMap(t=>t.type==="text"?[t.text]:[]).join(""),Hw=(e,t)=>({id:e.id,...t.sessionID!==null&&{sessionID:t.sessionID},messageID:t.messageID}),zw=e=>{if(K(e.result?.details))return e.result.details;let t=Object.values(e.ext??{}).find(n=>n.version!==Te&&K(n.data?.details));return t?t.data.details:{}};function Yw(e,t,n){let r=e.result,s=e.input===null||e.input===void 0?{}:{input:e.input},o=Lt(e.started_at)??t.created,i=Lt(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:ny(r?.content),...r?.exit_code!==void 0&&{metadata:a},time:{start:o,end:i}};let c=(r?.content??[]).flatMap((d,g)=>d.type==="attachment"?[{...n,id:`${e.id}-a${g}`,type:"file",mime:d.mime,...iy(d,t)}]:[]),p=Lt(r?.cleared_at);return{status:"completed",...s,output:ny(r?.content),title:e.title??"",metadata:{...zw(e),...a},time:{start:o,end:i,...p!==void 0&&{compacted:p}},...c.length&&{attachments:c}}}function ay(e,t){let n=Hw(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},...iy(e,t)};case"tool_call":return{...n,type:"tool",callID:e.call_id,tool:e.name,state:Yw(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 Jw(e){return ty(e.code)?{name:e.code==="aborted"?"MessageAbortedError":"UnknownError",code:e.code,data:{message:e.message}}:{name:e.code,data:{message:e.message}}}function cy(e,t,n={}){let r=e.usage,s=e.finish===null?void 0:Vw.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:Lt(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:Jw(e.error)},...n}}function ly(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 uy(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 Qw(e,t,n){let r=n||e.producer.harness===sy;if(!r&&(e.role==="system"||e.kind==="context"))return[];let s=ln(e.ext)?.data,o=s&&"runtime_session_id"in s?s.runtime_session_id??null:t,i={sessionID:o,messageID:e.message_id,created:Lt(e.created_at),fromV1:r},a=s&&"parts"in s?s.parts:e.blocks.flatMap(d=>{let g=ay(d,i);return g===void 0?[]:[zr(g,ln(d.ext)?.data)]}),c=[{runtime_session_id:o,info:zr(ly(e,i),s?.info),parts:a}],p=e.blocks.find(d=>d.type==="compaction");if(e.kind==="compaction"&&p&&p.summary!==null){let d=zr(uy(e,p,i),s?.summary);c.push({runtime_session_id:o,info:d.info,parts:d.parts})}return c}var Ko=e=>Ne(K(e.info)&&K(e.info.time)?e.info.time.created:void 0)??-1/0,Vr=e=>String(K(e.info)?e.info.id:""),py=(e,t)=>Ko(e)-Ko(t)||(Vr(e)<Vr(t)?-1:Vr(e)>Vr(t)?1:0),ry=e=>{let t=ln(e.ext);return t?t.native_id??null:e.thread_id};function Qr(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=>Qw(a,ry(i),ln(i.ext)!==void 0))),s=ln(t.ext)?.data,o=s&&"root_id"in s?s.root_id??null:n?ry(n):null;return{session_id:t.session_id,root_id:o,rows:r.sort(py)}}function Xw(e){let t=e.role==="assistant"?{p:e.providerID,m:e.modelID,v:e.variant}:K(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 Zw(e){if(!K(e.tokens))return null;let t=e.tokens,n=K(t.cache)?t.cache:{};return{input:Ne(t.input)??0,output:Ne(t.output)??0,cache_read:Ne(n.read)??0,cache_write:Ne(n.write)??0,...Ne(t.reasoning)!==void 0&&{reasoning:t.reasoning},...Ne(e.cost)!==void 0&&{cost:e.cost}}}var ek=e=>({code:J(e.code)||J(e.name)||"UnknownError",message:J(K(e.data)?e.data.message:void 0)??""});function dy(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 s=e.state,o=K(s.time)?s.time:{};K(s.input)||r.tool_input++;let i=K(s.metadata)&&Ne(s.metadata.exit)!==void 0?{exit_code:s.metadata.exit}:{},a,c,p=s.input??null;if(s.status==="completed"){let m=(Array.isArray(s.attachments)?s.attachments:[]).filter(K).map(_=>{let{bytes:y,...v}=dy(_,n,r);return{type:"attachment",...v}}),f=jt(o.compacted);a="complete",c={content:[...J(s.output)!==void 0?[{type:"text",text:s.output}]:[],...m],is_error:!1,...i,...f&&{model_content:[{type:"text",text:Kw}],cleared_at:f}}}else if(s.status==="error"){let m=J(s.error);a="error",c={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"&&J(s.raw)&&!(K(s.input)&&Object.keys(s.input).length)&&(p=s.raw);else{let m=Nw[n.h];a="error",c={content:[{type:"text",text:m}],is_error:!0,synthetic:!0,error:{code:"interrupted",message:m}}}let d=jt(o.start),g=jt(o.end);return{type:"tool_call",id:t,call_id:e.callID,name:e.tool,kind:Gw(e.tool),input:p,status:a,...c&&{result:c},...J(s.title)&&{title:s.title},...d&&{started_at:d},...g&&{ended_at:g}}}function nk(e,t,n,r,s,o){let i=(a,c=!1)=>({type:"harness",id:t,harness:s.h,kind:a,data:e,model_visible:c,...c&&{fallback_text:Bw}});if(!K(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,...dy(e,s,o),...J(e.filename)!==void 0&&{name:e.filename}};case"tool":return typeof e.callID=="string"&&typeof e.tool=="string"&&K(e.state)?tk(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:J(e.tail_start_id)??null,trigger:a}}case"subtask":return i("subtask",!0);default:return i(J(e.type)||"unknown")}}function rk(e){let t=e.map((s,o)=>K(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 sk(e,t,n,r,s,o){let i=K(e.info)?e.info:{},a=Array.isArray(e.parts)?e.parts:[],c=i.role==="user"?a.find(w=>K(w)&&w.type==="compaction"):void 0,p=t&&K(t.info)?t.info:void 0,d=i.role==="assistant"||i.role==="user"?i.role:"system",g=c?p:d==="assistant"?i:void 0,m=g&&K(g.error)?g.error:void 0,f=m?.name==="MessageAbortedError",_=g&&K(g.time)?jt(g.time.completed):null,y=o.live?"streaming":"interrupted",v=g?m?f?"aborted":"error":_?"complete":y:c?y:"complete",R=jt(K(i.time)?i.time.created:void 0)??"",T=t?(Array.isArray(t.parts)?t.parts:[]).flatMap(w=>K(w)&&w.type==="text"&&typeof w.text=="string"?[w.text]:[]).join(""):null,b={tool_input:0,cut_point:0,attachment:0},M=rk(a),h=a.map((w,D)=>nk(w,M[D],c,T,o,b)),S=h.some(w=>w.type==="text"||w.type==="attachment"||w.type==="tool_call"||w.type==="harness"&&w.model_visible),P=!s&&d!=="system"&&(c?v==="complete":!m||f&&S),k=o.live&&P&&v!=="streaming"&&h.some(w=>w.type==="tool_call"&&(w.status==="pending"||w.status==="running"))?"streaming":v,C=s?"superseded":P||!m?void 0:f?"aborted":"failed_attempt";return c&&K(c)&&J(c.tail_start_id)===void 0&&b.cut_point++,{m:{...Fo,message_id:J(i.id)??"",thread_id:n,seq:r,role:d,kind:c?"compaction":"turn",status:k,in_context:P,...C&&{hidden_reason:C},agent:J(i.agent)??null,...d==="assistant"&&{reply_to:J(i.parentID)??null},model:Xw(i),usage:g?Zw(g):null,finish:!g||c?null:f?"aborted":m?"error":Ww.get(i.finish)??null,error:m?ek(m):null,created_at:R,completed_at:g||c?_:R||null,producer:Fw,blocks:h},lost:b}}function ok(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:Lt(e.created_at),fromV1:!0};Array.isArray(t.parts)?e.blocks.forEach((p,d)=>{if(p.type==="harness"||p.type==="subtask")return;let g=Hr(t.parts[d],ay(p,i));g&&(p.ext=Jr(s,{data:g}))}):o.parts=t.parts;let a=Hr(t.info,ly(e,i));a&&(o.info=a);let c=e.blocks.find(p=>p.type==="compaction");if(n&&c){let p=Hr({info:n.info,parts:n.parts},uy(e,c,i));p&&(o.summary=p)}Object.keys(o).length&&(e.ext=Jr(s,{data:o}))}function ik(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(!(!K(o)||o.type!=="tool"||!K(o.state))&&(r?K(o.state.metadata)&&o.state.metadata.sessionId===t:n(o.state).includes(t)))return{row:s,part:o}}}}function Xr(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(py),s=new Map;for(let b of r){let M=s.get(b.runtime_session_id);M?M.push(b):s.set(b.runtime_session_id,[b])}let o=e.root_id,i=s.has(o),a=new Map,c=b=>a.get(b)??(a.set(b,JSON.stringify(b)),a.get(b)),p=new Map;for(let b of s.keys()){let M=i&&b===o?void 0:ik(r,b,c);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?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,_=jt(r.map(Ko).find(Number.isFinite))??"",y=[];for(let[b,M]of s){if(b!==g&&(b===null||!p.has(b)))continue;let h=b===g,S=h?r.filter(N=>N.runtime_session_id!==g&&f(N.runtime_session_id)===m):[],P=[...S,...M],k=new Set(S),C=new Map,j=new Set;for(let N of P){let z=K(N.info)?N.info:{};if(z.role!=="user"||!Array.isArray(N.parts)||!N.parts.some(B=>K(B)&&B.type==="compaction"))continue;let G=P.find(B=>!j.has(B)&&B.runtime_session_id===N.runtime_session_id&&K(B.info)&&B.info.role==="assistant"&&B.info.summary===!0&&B.info.parentID===z.id);G&&(C.set(N,G),j.add(G))}let w=[];for(let N of P){if(j.has(N))continue;let z=C.get(N),{m:G,lost:B}=sk(N,z,h?m:b,w.length+1,k.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]+=B[Me];w.push(G)}let D=b===null?void 0:p.get(b),Pe=w.find(N=>N.role==="user"&&N.kind==="turn");y.push({...Fo,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:Pe?.agent??null,title:null,created_at:w[0]?.created_at||_,messages:w,ext:Jr(n.h,b===null?{}:{native_id:b})})}y.sort((b,M)=>b.parent_thread_id===null?-1:M.parent_thread_id===null?1:T(b)-T(M));let v=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{...Fo,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:v?.agent??null,model:v?.model??null},todos:[],pending:{questions:[],permissions:[]},threads:y,...g!==o&&{ext:Jr(n.h,{data:{root_id:o}})}};function T(b){return r.findIndex(M=>M.runtime_session_id===b.thread_id)}}var Bo={schema:le,v:1},ak=Object.freeze({}),gy=new WeakMap;function Zr(e){let t=gy.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=Xr({session_id:"",root_id:n,rows:[{runtime_session_id:n,info:r,parts:[e]}]},{live:!0}).threads[0].messages[0].blocks[0];return gy.set(e,{state:e.state,block:o}),o}var qo=new WeakMap;function Go(e){if(qo.has(e))return qo.get(e);let t={...Bo,thread_id:"",parent_thread_id:null,spawned_by:null,agent:null,title:null,created_at:"",ext:{opencode:{version:Te}},messages:[{...Bo,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}=Qr({...Bo,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 qo.set(e,r),r}function se(e){return Go(e)}var ge=e=>typeof e=="object"&&e!==null&&e.type==="tool_call",Ke=e=>ge(e)?se(e):e;function ck(e){let t=se(e).state.metadata;return typeof t=="object"&&t!==null&&!Array.isArray(t)&&Object.keys(t).length?t:ak}var fy=e=>(e.result?.content??[]).flatMap(t=>t.type==="text"?[t.text]:[]).join("");function lk(e){return e.status==="complete"?"completed":e.status}var my=new WeakMap;function uk(e){if(e.status!=="complete")return"";let t=my.get(e);return t===void 0&&my.set(e,t=fy(e)),t}function pk(e){return e.status==="error"?e.result?.error?.message||fy(e):void 0}function he(e){return(e??"").replace(/^oc-/,"").replace(/-/g,"_")}function eN(e){return he(e)==="bash"}function yy(e){let t=he(e);return t==="question"||t==="ask"}function tN(e,t){let n=Math.max(0,e);return`${t?"Running":"Ran"} ${n} command${n===1?"":"s"}`}var dk=new Set(["show","show_user"]);function hy(e){return dk.has(he(e))}function nN(e,t){let n=Math.max(0,e);return`${t?"Writing":"Wrote"} ${n} file${n===1?"":"s"}`}function _y(e){return!!(e.type==="snapshot"||e.type==="patch"||e.type==="step-start"||e.type==="step-finish"||e.type==="text"&&!e.text?.trim()||Wo(e))}function Wo(e){let t=ge(e)?se(e):e,n=he(t.tool);return n!=="show"&&n!=="show_user"||t.state?.status!=="completed"?!1:Wr(t.state?.input)}var gk=new Set(["show","show_user","agent_spawn","agent_status","agent_message","agent_task_update","agent_stop"]);function by(e){return gk.has(he(e))}var mk=50*1024*1024,Vo="[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",fk=new RegExp(`^kortix-attachment://(${Vo})/(${Vo})/(${Vo})$`);function zo(e){if(typeof e!="string")return null;let t=fk.exec(e);return t?{projectId:t[1],sessionId:t[2],attachmentId:t[3]}:null}function lN(e){return zo(e)!==null}var Ho=new WeakMap;async function Py(e,t,n,r={}){if(n.size>mk)throw new Error("Attachments must be 50 MiB or smaller.");let s=`${e}/${t}`,o=r.attachmentId?void 0:Ho.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 c=Ho.get(n)??new Map;c.set(s,i),Ho.set(n,c)}let a=new FormData;return a.append("attachment_id",i.id),a.append("file",n,n.name),i.promise=l.upload(`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/attachments`,a,{signal:r.signal,timeout:12e4,showErrors:!1}).then(u).catch(c=>{throw i.promise=void 0,c}),i.promise}async function Sy(e,t){let n=zo(e);if(!n)throw new Error("Invalid attachment reference");let r=I().backendUrl.replace(/\/$/,""),s=await L(`${r}/projects/${n.projectId}/sessions/${n.sessionId}/attachments/${n.attachmentId}`,{signal:t});if(!s.ok)throw new x("Could not load attachment",{status:s.status});return s.blob()}var yk=new Set(["show","show_user"]);function hk(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 Be=e=>!!e&&typeof e=="object"&&!Array.isArray(e),un=e=>typeof e=="string"&&e.length>0?e:null,xy=e=>typeof e=="string"?un(e.split("/").pop()):null;function es(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 _k(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 bk(e){let t=e.blocks.filter(Be).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"&&Be(n.data)?n.data:n);return{info:{id:e.message_id,role:e.role},parts:t}}function Pk(e,t){for(let n of hk(e))t(es(n,"attachment"),es(n,"filename")??xy(es(n,"path")),es(n,"mime"))}function Sk(e,t){for(let n of[e,..._k(e.items)])Be(n)&&t(n.attachment,xy(n.path),null)}function uN(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let r of e){let s=Be(r)&&Array.isArray(r.blocks)?bk(r):r;if(!Be(s)||!Be(s.info)||!Array.isArray(s.parts))continue;let o=un(s.info.id);if(!o)continue;let i=un(s.info.role)??"unknown",a=(c,p,d)=>{let g=zo(c);!g||n.has(c)||(n.add(c),t.push({url:c,attachment_id:g.attachmentId,filename:p,mime:d,message_id:o,role:i}))};for(let c of s.parts)Be(c)&&(c.type==="file"?a(c.url,un(c.filename),un(c.mime)):c.type==="text"&&typeof c.text=="string"?Pk(c.text,a):c.type==="tool"&&typeof c.tool=="string"&&yk.has(he(c.tool))&&Be(c.state)&&Be(c.state.input)&&Sk(c.state.input,a))}return t}function Ze(e){try{return typeof process<"u"?process.env?.[e]:void 0}catch{return}}function xk(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 fN(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 Yo(e,t,n){return e!==void 0?e:xk(Ze(t),n)}var wy={get disableMobileAdvertising(){return Yo(I().featureFlags?.disableMobileAdvertising,"NEXT_PUBLIC_DISABLE_MOBILE_ADVERTISING",!1)},get enableDinoGame(){return Yo(I().featureFlags?.enableDinoGame,"NEXT_PUBLIC_ENABLE_DINO_GAME",!1)},get enableProjects(){return Yo(I().featureFlags?.enableProjects,"NEXT_PUBLIC_ENABLE_PROJECTS",!1)},get enableAutoModel(){return!1}};var wk=new Set(["project-manager"]);function Jo(e){return e.native===!0||e.mode==="subagent"||e.hidden||e.enabled===!1?!1:wy.enableProjects||!wk.has(e.name)}function _N(e){let t=e.agents.filter(Jo),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 ky(){return{projects:{list:At,listForAccount:Cc,get:Rt,detail:gr,create:Mc,createRepo:Oc,provision:Dc,update:yr,archive:hr,llmCatalog:mr,modelPicker:fr,modelAccess:qr,setModelAccess:Gr,sandboxHealth:Pr,sandboxTemplates:vu,sessions:Mt,createSession:Ot},github:{linkRepository:Nc,replaceProjectRepository:Kc,getInstallation:Bc,listInstallations:qc,listLinkableInstallations:Gc,listRepositories:Wc,listRepositoryBranches:Vc,linkInstallation:zc,saveInstallation:Hc,deleteInstallation:Jc,storeUserToken:Yc},gitBackend:{get:Qc,repositories:Xc},connectStatus:hu,marketplace:{items:o=>tf(o),item:o=>sf(o),itemFile:(o,i)=>of(o,i),marketplaces:()=>nf(),featured:()=>rf(),sources:{list:()=>af(),add:o=>cf(o),remove:o=>lf(o)}}}}function vy(){return{billing:{accountState:Ld,accountStateMinimal:$d,transactions:Ud,transactionsSummary:Fd,creditBreakdown:Nd,usageHistory:Kd,usageRollup:sg,sessionCosts:{list:ig,get:Kr},tierConfigurations:Bd,setPlan:tg,previewPlan:eg,acceptEnterpriseOffer:ng,contactSales:rg,checkout:{createSession:n=>qd(n),confirmSession:(n,r)=>Gd(n,r)},subscription:{createPortalSession:(n,r)=>Wd(n,r),cancel:(n,r)=>Vd(n,r),reactivate:n=>Hd(n),scheduleDowngrade:(n,r,s)=>zd(n,r,s),cancelScheduledChange:n=>Yd(n),prorationPreview:(n,r)=>Jd(n,r)},credits:{purchase:n=>Qd(n),autoTopupSettings:n=>Xd(n),configureAutoTopup:n=>Zd(n)}},sandboxShares:{list:Rm,create:Cm,revoke:Tm}}}var et={DESKTOP:"6080",DESKTOP_HTTPS:"6081",PRESENTATION_VIEWER:"3210",STATIC_FILE_SERVER:"3211",KORTIX_MASTER:"8000",BROWSER_STREAM:"9223",BROWSER_VIEWER:"9224",SSH:"22"};function tt(){let e=Ze("BACKEND_URL")||I().backendUrl;return e||"http://localhost:8008/v1"}function gt(e){let t=pe(e);return t.endsWith("/v1")?t:`${t}/v1`}function pn(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=pn(t);if(n)return n}return}if(e&&typeof e=="object"){let t=e;return pn(t.sandboxId??t.id??t.slug??Object.values(t)[0])}}function kk(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 ts(e,t,n){let r=n?.external_id||t.sandbox_url?.match(/\/p\/([^/]+)\//)?.[1]||t.sandbox_id||"";return{sandbox_id:n?.sandbox_id||t.sandbox_id||t.session_id,external_id:r,name:t.name||`${e.name} session`,provider:n?.provider||t.sandbox_provider||"daytona",base_url:n?.base_url||t.sandbox_url||(n?.external_id?`${tt()}/p/${n.external_id}/${et.KORTIX_MASTER}`:""),status:kk(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 Qo(){let e=await At(),t=[];for(let n of e){let r=await Mt(n.project_id).catch(()=>[]);for(let s of r)t.push({project:n,session:s,runtime:null,sandbox:ts(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 Xo(e){let t=await l.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 ns(e){let t=await Xo(e);if(t)return{projectId:t.project_id,sessionId:t.session_id};let n=await dn(e);return n?{projectId:n.project.project_id,sessionId:n.session.session_id}:null}async function dn(e){let t=await Qo();return e?t.find(n=>n.sandbox.sandbox_id===e||n.sandbox.external_id===e||n.session.session_id===e||n.runtime?.external_id===e)??null:t[0]??null}var gn=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 gn("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(`${gt(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(()=>""),c=null;try{c=a?JSON.parse(a):null}catch{c=a}if(!i.ok){let p=c&&typeof c=="object"?c:{};throw new gn(typeof p.error=="string"?p.error:"auth_error",typeof p.error_description=="string"&&p.error_description?p.error_description:typeof p.error=="string"?p.error:i.statusText||`HTTP ${i.status}`,i.status)}return c}function Zo(e,t){return oe("/auth/signup",{body:e},t)}function ei(e,t){return oe("/auth/sign-in/password",{body:e},t)}function ti(e,t){return oe("/auth/sign-in/magic-link",{body:e},t)}function ni(e,t){return oe("/auth/verify-otp",{body:e},t)}function ri(e,t){return oe("/auth/sign-in/oauth",{body:e},t)}function si(e,t){return oe("/auth/oauth/exchange",{body:e},t)}function mn(e,t){return oe("/auth/refresh",{body:e},t)}function oi(e,t){return oe("/auth/password/reset",{body:e},t)}function ii(e,t,n){return oe("/auth/password/update",{body:e,bearer:t},n)}function ai(e,t){return oe("/auth/user",{bearer:e},t)}function ci(e,t,n){return oe("/auth/user",{method:"PATCH",body:e,bearer:t},n)}function li(e,t){return oe("/auth/sign-in/sso",{body:e},t)}var ui={enroll:(e,t,n)=>oe("/auth/mfa/factors",{body:e,bearer:t},n),challenge:(e,t={},n,r)=>oe(`/auth/mfa/factors/${encodeURIComponent(e)}/challenge`,{body:t,bearer:n},r),verify:(e,t,n,r)=>oe(`/auth/mfa/factors/${encodeURIComponent(e)}/verify`,{body:t,bearer:n},r),unenroll:(e,t,n)=>oe(`/auth/mfa/factors/${encodeURIComponent(e)}`,{method:"DELETE",bearer:t},n)};function pi(e,t={},n){return oe("/auth/sign-out",{body:t,bearer:e},n)}function di(e={}){let t=e.refreshSkewSeconds??60,n=e.now??(()=>Date.now()),r=null,s=null,o=!e.storage,i=null,a=null,c=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:s})):await e.storage.remove());for(let y of[...p])try{y(r)}catch{}try{e.onChange?.(r)}catch{}}async function f(){if(o)return r;if(!i){let y=c,v=(async()=>{let R=await e.storage.get();if(y===c&&R)try{let T=JSON.parse(R);T.session?.access_token&&T.session?.refresh_token&&(r=T.session,s=T.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 _(){if(await f(),!r)return null;if(!a){let y=r.refresh_token,v=c,R=mn({refresh_token:y},e.request).then(async T=>(v!==c||(r=T.session,T.user&&(s=T.user),await m()),r)).catch(async T=>{if(v!==c)return r;let b=T&&typeof T=="object"&&"status"in T?T.status:0;if(b>=400&&b<500)return r=null,s=null,await m(),null;throw T}).finally(()=>{a===R&&(a=null)});a=R}return a}return{subscribe(y){return p.add(y),()=>{p.delete(y)}},current:()=>r,user:()=>s,load:f,async set(y,v){await f(),c+=1,a=null,r=y,v!==void 0&&(s=v),y||(s=null),await m()},async getToken(){return await f(),r?g(r)?(await _().catch(()=>r))?.access_token??null:r.access_token:null},refresh:_,async clear(){c+=1,a=null,r=null,s=null,o=!0,await m()}}}function Ay(){return{list:oc,get:ac,create:ic,secretResources:{list:Il,create:El,rotate:Ml,retry:Ol,remove:Dl,grant:jl,revoke:Ll,setAccess:$l},updateName:cc,branding:{get:lc,update:uc,uploadAsset:pc,removeAsset:dc,reset:gc},leave:vc,members:mc,invite:fc,removeMember:wc,updateMemberRole:kc,invites:yc,cancelInvite:hc,resendInvite:_c,tokens:{list:Um,create:Fm,revoke:Nm},connectedApps:{list:Km,revoke:Bm},audit:{log:Vm,export:zm,webhooks:{list:Ym,create:Jm,update:Qm,remove:Xm}}}}function Ry(){return{assignments:{list:ym,create:hm,revoke:_m},permissions:{list:bm,forRole:nm},roles:{list:Zg,create:sm,update:om,setPermissions:im,remove:am,usage:rm},groups:{list:Wg,get:Vg,create:Hg,update:zg,remove:Yg,members:{list:Jg,add:Qg,remove:Xg}},agentIdentities:em,oauthClients:{list:um,get:pm,create:dm,update:gm,rotateSecret:mm,remove:fm},can:cm,canBatch:lm}}function Cy(){let e={signUp:Zo,signInWithPassword:ei,sendMagicLink:ti,verifyOtp:ni,signInWithProvider:ri,exchangeCode:si,refresh:mn,resetPassword:oi,updatePassword:ii,updateUserMetadata:ci,signInWithSso:li,mfa:ui,user:ai,signOut:pi,session:di},t=Ay(),n=Ry();return{auth:e,accounts:t,iam:n,accountInvites:{listMine:bc,describe:Pc,accept:so,acceptAndLand:Sc,decline:xc}}}var fn=new Map,gi=new Map;function mi(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function Ty(e){return fn.get(mi(e))??null}function Iy(){return[...fn.values()].filter(e=>typeof e=="string")}function Ey(e){return fn.has(mi(e))}async function mt(e){let t=mi(e),n=fn.get(t);if(n!==void 0)return n;let r=gi.get(t);if(r)return r;let s=(async()=>{try{let o=await l.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 fn.set(t,i),i}catch{return null}finally{gi.delete(t)}})();return gi.set(t,s),s}function My(e){let{apiBaseUrl:t}=e;return Ey(t)||mt(t).catch(()=>{}),{sandboxId:e.sandboxId,backendPort:e.backendPort,apiBaseUrl:t,previewUrlTemplate:Ty(t)}}function Oy(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 x(`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),My({sandboxId:r,apiBaseUrl:s,backendPort:o})}}function Dy(e,t){let n=null;async function r(){n||(n=Tr(e,t,{showErrors:!1}).then(s=>{let o=jr(s)??"",i=o.indexOf("/"),a=i>0&&i<o.length-1?{providerID:o.slice(0,i),modelID:o.slice(i+1)}:void 0,c=s.agent_name?.trim()||void 0;return{model:a,agent:c}}));try{return await n}catch(s){throw n=null,s}}return{persistedPromptDefaults:r,clearPersistedDefaults:()=>{n=null}}}var $t={url:null,sandboxId:null,dbSandboxId:null,version:0},Ak=new Set;function rs(e,t=null,n=null){if(!($t.url===e&&$t.sandboxId===t&&$t.dbSandboxId===n)){$t={url:e,sandboxId:t,dbSandboxId:n,version:$t.version+1};for(let r of Ak)r()}}function jy(){return $t.url}var yn=new Map;function Ly(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 Ut=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 $y(e,t){async function n(r){let s=Date.now()+r,o=()=>Math.max(0,s-Date.now()),i=await dt(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 dt(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 x(Ly(i),{code:"RUNTIME_UNAVAILABLE"});let c=i.sandbox.external_id;if(!c)throw new x("Session sandbox has no external_id \u2014 cannot resolve its runtime URL",{code:"RUNTIME_UNAVAILABLE"});let p=Fe(c);return rs(p,c),{runtimeSessionId:a,opencodeSessionId:a,runtimeUrl:p,sandboxId:c}}return n}function Uy(e,t,n){let r=null;function s(){if(r)return r;let p=bd(e,t);return p&&(r=p),r}let o=$y(e,t);async function i(p){let d=s();if(d)return d;let g=p?.readyTimeoutMs??18e4,m=mt(I().backendUrl??n.backendUrl).catch(()=>null),f=p?.session?.session_id===t?xd(p.session):null,_=f?.sandbox?.external_id,y=f?.runtime_session_id;if(_&&y){let b=Fe(_);return rs(b,_),r={runtimeSessionId:y,opencodeSessionId:y,runtimeUrl:b,sandboxId:_},Lr(e,t,r),await m,r}let v=`${e}
|
|
15
|
-
${t}`,R=
|
|
13
|
+
`);let _=Sw(f);if(_){if(r(_),_.type==="error")throw new P(_.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 od(e,t){return u(await l.get(`/projects/${e}/sessions/${encodeURIComponent(t)}/scope`))}async function id(e,t,n){return u(await l.put(`/projects/${e}/sessions/${encodeURIComponent(t)}/scope`,n))}async function ad(e,t,n){return u(await l.put(`/projects/${e}/sessions/${encodeURIComponent(t)}/model`,{model:n,opencode_model:n}))}function Lr(e){let t=e.metadata?.opencode_model;return typeof t=="string"&&t.trim()?t.trim():null}async function cd(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/message-authors`,{showErrors:!1}))}async function ld(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/model-usage`,{showErrors:!1}))}function Hj(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 ud(e){return u(await l.get(`/projects/${e}/triggers`))}async function pd(e,t){return u(await l.post(`/projects/${e}/triggers`,t))}async function dd(e,t,n){return u(await l.patch(`/projects/${e}/triggers/${t}`,n))}async function gd(e,t){return u(await l.delete(`/projects/${e}/triggers/${t}`))}async function Qj(e){return u(await l.get(`/accounts/${e}/automations`))}async function Xj(e,t){return u(await l.patch(`/accounts/${e}/automations`,{paused:t},{showErrors:!1}))}async function md(e,t){return u(await l.patch(`/projects/${e}/triggers/activation`,{paused:t}))}function fd(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 yd(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 l.post(`/projects/${e}/triggers/${t}/fire`,r))}async function hd(e,t,n){return u(await l.get(`/projects/${e}/triggers/${t}/runs${fd(n)}`))}async function _d(e,t){return u(await l.get(`/projects/${e}/trigger-runs${fd(t)}`))}async function bd(e,t,n,r){return u(await l.post(`/projects/${e}/triggers/${t}/runs/${n}/replay`,r?.confirmUnverified?{confirm_unverified:!0}:{}))}async function Sd(e,t){let n="connector"in t?`connector=${encodeURIComponent(t.connector)}`:`app=${encodeURIComponent(t.app)}${t.source?`&source=${encodeURIComponent(t.source)}`:""}`;return u(await l.get(`/projects/${e}/triggers/event-types?${n}`))}async function Pd(e){return u(await l.get(`/projects/${e}/triggers/event-apps`))}var Xe=new Map;function Ao(e,t){return`${e}::${t}`}function xd(e,t){Xe.delete(e),Xe.set(e,t)}function wd(e,t){let n=Ao(e,t),r=Xe.get(n);return r&&xd(n,r),r}function $r(e,t,n){let r=Ao(e,t);if(!Xe.has(r)&&Xe.size>=512){let s=Xe.keys().next().value;s!==void 0&&Xe.delete(s)}xd(r,n)}function kd(e,t){Xe.delete(Ao(e,t))}function Pw(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function pn(){return Pw(T().backendUrl||"http://localhost:8008/v1")}function vd(){let e=T().sandboxId;return e?`${pn()}/p/${e}/8000`:""}function xw(e,t=8e3){return`${pn()}/p/${e}/${t}`}function Fe(e,t=8e3){return xw(e,t)}function Ad(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 Ro=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 aL(e){return e instanceof Error&&e.name==="SessionStartError"}function ww(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 Ro(s,{status:n,code:r,terminal:!0}):null}function Rd(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 l.post(`/projects/${e}/sessions/${t}/start${i}`,{},{showErrors:!1})}async function gt(e,t,n){let r=await Rd(e,t,n);if(!r.success||!r.data){let s=ww(r.error);if(s&&!(s.status===404&&gp(t)))throw s;return null}return Cd(e,t,r.data)}async function Td(e,t,n){let r=await Rd(e,t,n);if(!r.success||!r.data)throw r.error??new Error("Unable to start this session");return Cd(e,t,r.data)}function Cd(e,t,n){let r=n.sandbox?.external_id,s=n.runtime_session_id??n.opencode_session_id;return n.stage==="ready"&&r&&s&&$r(e,t,{runtimeSessionId:s,opencodeSessionId:s,runtimeUrl:Fe(r),sandboxId:r}),n}function cL(e,t){return["session-start",e,t]}async function Id(e){return u(await l.get(`/projects/${e}/model-defaults`))}async function Ed(e,t){return u(await l.put(`/projects/${e}/model-defaults`,t))}async function Md(e,t){let n=new URLSearchParams({scope:t.scope,...t.agentName?{agentName:t.agentName}:{}}).toString();return u(await l.delete(`/projects/${e}/model-defaults?${n}`))}async function fL(e,t){return u(await l.put(`/projects/${e}/model-enablement`,{modelOverrides:t}))}function Od(e){let t=[];for(let n of e){let r=n.trim();r&&!t.includes(r)&&t.push(r)}return t}function kw(e,t){if(e.length!==t.length)return!1;let n=new Set(t);return e.every(r=>n.has(r))}function Ur(e){let t=e.connectors_required?Od(e.connectors_required):void 0,n=e.connectors_personal?Od(e.connectors_personal):void 0;if(t&&n&&!kw(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 Dd(e,t,n){let r=Ur(n);return u(await l.put(`/projects/${e}/agents/${encodeURIComponent(t)}/scope`,r))}async function vL(e,t){let n=u(await l.get(`/projects/${e}/agents/${encodeURIComponent(t)}/config`));return{...n,block:n.block?To(n.block):null}}async function AL(e,t,n){let r=To(n,!0),s=u(await l.put(`/projects/${e}/agents/${encodeURIComponent(t)}/config`,r));return{...s,block:s.block?To(s.block):null}}function To(e,t=!1){let n=Ur(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 RL(e,t,n){return u(await l.post(`/projects/${e}/secrets/${encodeURIComponent(t)}/grant`,{agent:n}))}async function jd(e,t){return u(await l.put(`/projects/${e}/default-agent`,{agent:t}))}var Fr="Use setBillingPlan().",Ld="Change the plan with setBillingPlan(); manage the card in the Stripe customer portal (createPortalSession()).";function $d(){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 vw(e){let t=e.trim().toLowerCase();return t===""||t==="free"||t==="none"?"free":t==="enterprise"?"enterprise":"credits"}function ML(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??$d(),r=(n.subscription?.tier_key||n.tier?.name||"none").toString(),s=(n.tier?.display_name||"").trim()||r;return{family:vw(r),label:s,sublabel:null,monthlyUsd:null}}function Aw(e){return!!e&&e.can_manage_billing!==!1}function OL(e){return e?.subscription?.can_purchase_credits===!0&&Aw(e)}async function Ud(e){let t=await l.get(e,{showErrors:!1}),n=t.error?.status===404&&/billing is not enabled/i.test(t.error.message||"");if(t.error&&t.error.status!==401&&!n)throw t.error;return t.error?$d():t.data}function Fd(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 Nd(e){return Ud(`/billing/account-state${Fd(e)}`)}async function Bd(e){return Ud(`/billing/account-state/minimal${Fd(e)}`)}async function Kd(e){let t=new URLSearchParams;e?.accountId&&t.set("account_id",e.accountId),e?.limit!=null&&t.set("limit",String(e.limit)),e?.offset!=null&&t.set("offset",String(e.offset)),e?.typeFilter&&t.set("type_filter",Array.isArray(e.typeFilter)?e.typeFilter.join(","):e.typeFilter);let n=t.toString();return u(await l.get(`/billing/transactions${n?`?${n}`:""}`))}async function qd(e){let t=new URLSearchParams;e?.accountId&&t.set("account_id",e.accountId),e?.days!=null&&t.set("days",String(e.days));let n=t.toString();return u(await l.get(`/billing/transactions/summary${n?`?${n}`:""}`))}async function Gd(){return u(await l.get("/billing/credit-breakdown"))}async function Wd(e){let t=e!=null?`?days=${e}`:"";return u(await l.get(`/billing/usage-history${t}`))}async function Vd(){return u(await l.get("/billing/tier-configurations"))}async function DL(e){let t=e.accountId?`?account_id=${encodeURIComponent(e.accountId)}`:"";return At(e,`/v1/billing/account-state${t}`)}async function Hd(e){throw U("createCheckoutSession",Fr)}async function zd(e,t){throw U("confirmCheckoutSession",Fr)}async function Yd(e,t){return u(await l.post("/billing/create-portal-session",{account_id:t,return_url:e}),"Failed to create portal session")}async function Jd(e,t){return u(await l.post("/billing/cancel-subscription",{account_id:t,feedback:e}),"Failed to cancel subscription")}async function Qd(e){return u(await l.post("/billing/reactivate-subscription",{account_id:e}),"Failed to reactivate subscription")}async function Xd(e,t,n){throw U("scheduleDowngrade","Change the plan in the Stripe customer portal (createPortalSession()).")}async function Zd(e){throw U("cancelScheduledChange",Ld)}async function eg(e,t){throw U("getProrationPreview",Ld)}async function tg(e){return u(await l.post("/billing/purchase-credits",{amount:e.amount,account_id:e.accountId,success_url:e.successUrl,cancel_url:e.cancelUrl}),"Failed to purchase credits")}async function ng(e){let t=e?`?account_id=${encodeURIComponent(e)}`:"";return u(await l.get(`/billing/auto-topup/settings${t}`),"Failed to load auto-topup settings")}async function jL(e){return u(await l.post(`/accounts/${encodeURIComponent(e)}/top-up-requests`,{}),"Failed to ask the owners for credits")}async function rg(e){return u(await l.post("/billing/auto-topup/configure",{account_id:e.accountId,enabled:e.enabled,threshold:e.threshold,amount:e.amount},{showErrors:!1}),"Failed to configure auto-topup")}async function LL(e){let t=e?`?account_id=${encodeURIComponent(e)}`:"";return u(await l.get(`/billing/auto-topup/setup-status${t}`,{timeout:8e3,showErrors:!1}),"Failed to load auto-topup setup status")}async function sg(e){return u(await l.post("/billing/plan/preview",{monthly_usd:e.monthlyUsd,account_id:e.accountId}),"Failed to preview the plan change")}async function og(e){return u(await l.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 ig(e){return u(await l.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 ag(e={}){return u(await l.post("/billing/enterprise/contact",{account_id:e.accountId,...e.note?{note:e.note}:{}}),"Failed to reach Kortix sales")}async function $L(e){throw U("createPerSeatCheckout",Fr)}async function UL(e){throw U("claimPerSeatBilling",Fr)}async function FL(e){return u(await l.post("/billing/sync-subscription",{account_id:e}),"Failed to sync subscription")}async function cg(e={}){let t=new URLSearchParams;e.start&&t.set("start",e.start),e.end&&t.set("end",e.end),(e.groupBy==="model"||e.groupBy==="provider"||e.groupBy==="day")&&t.set("group_by",e.groupBy),e.accountId&&t.set("account_id",e.accountId);let n=t.toString();return u(await l.get(`/usage${n?`?${n}`:""}`))}function Co(e,t){t.accountId&&e.set("account_id",t.accountId),t.projectId&&e.set("project_id",t.projectId)}function Nr(e,t){t.from&&e.set("from",t.from),t.to&&e.set("to",t.to)}function Br(e){return e.size>0?`?${e}`:""}async function ug(e={}){let t=new URLSearchParams;return Co(t,e),e.ownerId&&t.set("owner_id",e.ownerId),Nr(t,e),e.sort&&t.set("sort",e.sort),e.limit!=null&&t.set("limit",String(e.limit)),e.offset!=null&&t.set("offset",String(e.offset)),u(await l.get(`/usage/session-costs${Br(t)}`))}async function Kr(e,t={}){let n=new URLSearchParams;return Co(n,t),u(await l.get(`/usage/session-costs/${encodeURIComponent(e)}${Br(n)}`))}async function WL(e={}){let t=new URLSearchParams;return e.accountId&&t.set("account_id",e.accountId),Nr(t,e),e.sort&&t.set("sort",e.sort),e.limit!=null&&t.set("limit",String(e.limit)),e.offset!=null&&t.set("offset",String(e.offset)),u(await l.get(`/usage/cost-by-project${Br(t)}`))}async function VL(e={}){let t=new URLSearchParams;return Co(t,e),e.sessionId&&t.set("session_id",e.sessionId),Nr(t,e),u(await l.get(`/usage/cost-summary${Br(t)}`))}function lg(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)}Nr(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`${T().backendUrl||""}${r}?${n}`}async function HL(e,t={}){let n=lg(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 pg(e,t){return u(await l.post(`/channels/${e}/identity/bind`,{token:t}),"Failed to connect your account")}function QL(e){return pg("slack",e)}function XL(e){return pg("teams",e)}async function dg(e,t){return u(await l.post(`/channels/${e}/identity/preview`,{token:t},{showErrors:!1}),"This link is invalid or has expired")}function ZL(e){return dg("slack",e)}function e$(e){return dg("teams",e)}async function gg(e){let t=await l.get(`/projects/${encodeURIComponent(e)}/channels/slack/installation`,{showErrors:!1});return t.success?t.data??null:null}async function mg(e,t){return u(await l.post(`/projects/${encodeURIComponent(e)}/channels/slack/connect`,t,{showErrors:!1}),"Failed to connect")}var Rw={oauth_available:!1,install_url:null};async function fg(e){let t=await l.get(`/projects/${encodeURIComponent(e)}/channels/slack/mode`,{showErrors:!1});return!t.success||!t.data?Rw:t.data}async function yg(e,t,n){return u(await l.post(`/projects/${encodeURIComponent(t)}/channels/${e}/oauth/complete`,{code:n.code,state:n.state},{showErrors:!1}),"Failed to finish the install")}function hg(e,t){return yg("slack",e,t)}function _g(e,t){return yg("teams",e,t)}async function bg(e){return u(await l.get(`/webhooks/slack/${encodeURIComponent(e)}/manifest`,{showErrors:!1}),"Failed to load Slack manifest")}async function Sg(e){let t=await l.delete(`/projects/${encodeURIComponent(e)}/channels/slack/installation`,{showErrors:!1});if(!t.success)throw new Error(t.error?.message??"Failed to disconnect")}async function t$(e){let t=await l.get(`/projects/${encodeURIComponent(e)}/channels/telegram/installation`,{showErrors:!1});return t.success?t.data??null:null}async function n$(e,t){return u(await l.post(`/projects/${encodeURIComponent(e)}/channels/telegram/connect`,t,{showErrors:!1}),"Failed to connect Telegram")}async function r$(e,t){return u(await l.put(`/projects/${encodeURIComponent(e)}/channels/telegram/allowed-users`,{user_ids:t},{showErrors:!1}),"Failed to update allowed Telegram users")}async function s$(e){let t=await l.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 l.get(`/projects/${encodeURIComponent(e)}/channels/slack/file?url=${encodeURIComponent(t)}`,{showErrors:!1}),"Failed to download Slack file")}async function xg(e,t){return u(await l.post(`/projects/${encodeURIComponent(e)}/channels/slack/file/upload`,{channel:t.channel,filename:t.filename,content_base64:t.contentBase64,comment:t.comment,thread_ts:t.threadTs},{showErrors:!1}),"Failed to upload Slack file")}function Io(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 Tw={provider:"agentmail",managed_available:!1};async function wg(e,t){let n=t?`?connector_slug=${encodeURIComponent(t)}`:"",r=await l.get(`/projects/${encodeURIComponent(e)}/channels/email/installation${n}`,{showErrors:!1});return r.success&&r.data?Io(r.data):null}async function kg(e){let t=await l.get(`/projects/${encodeURIComponent(e)}/channels/email/mode`,{showErrors:!1});return!t.success||!t.data?Tw:t.data}async function vg(e,t){let n=u(await l.post(`/projects/${encodeURIComponent(e)}/channels/email/connect`,t,{showErrors:!1}),"Failed to connect email");return Io(n)}async function Ag(e,t){let n=t?`?connector_slug=${encodeURIComponent(t)}`:"",r=await l.delete(`/projects/${encodeURIComponent(e)}/channels/email/installation${n}`,{showErrors:!1});if(!r.success)throw new Error(r.error?.message??"Failed to disconnect email")}async function Rg(e,t,n){let r=u(await l.patch(`/projects/${encodeURIComponent(e)}/channels/email/installation`,{connector_slug:t??"kortix_email",sender_policy:n},{showErrors:!1}),"Failed to update email policy");return Io(r)}async function o$(e){return u(await l.get(`/projects/${encodeURIComponent(e)}/channels/bindings`,{showErrors:!1}),"Failed to load channel bindings")}async function i$(e,t,n){return u(await l.patch(`/projects/${encodeURIComponent(e)}/channels/bindings/${encodeURIComponent(t)}`,n,{showErrors:!1}),"Failed to update channel binding")}async function Tg(e){return u(await l.get(`/projects/${e}/gateway/routing-policy`),"Gateway routing policy request failed")}async function Cg(e,t){return u(await l.put(`/projects/${e}/gateway/routing-policy`,t),"Gateway routing policy request failed")}async function Ig(e){return u(await l.delete(`/projects/${e}/gateway/routing-policy`),"Gateway routing policy request failed")}async function Eg(e,t){return u(await l.post(`/projects/${e}/gateway/routing-policy/preview`,t),"Gateway route preview failed")}async function Mg(e,t){let n=new URLSearchParams;t?.limit&&n.set("limit",String(t.limit)),t?.offset&&n.set("offset",String(t.offset)),t?.ok!==void 0&&n.set("ok",String(t.ok));let r=n.toString();return u(await l.get(`/projects/${e}/gateway/logs${r?`?${r}`:""}`),"Gateway request failed")}async function Og(e,t){return u(await l.get(`/projects/${e}/gateway/logs/${t}`),"Gateway request failed")}async function Dg(e,t){return u(await l.get(`/projects/${e}/gateway/overview${t?`?days=${t}`:""}`),"Gateway request failed")}async function jg(e,t){return u(await l.get(`/projects/${e}/gateway/series${t?`?days=${t}`:""}`),"Gateway request failed")}async function Lg(e,t){return u(await l.get(`/projects/${e}/gateway/breakdown${t?`?days=${t}`:""}`),"Gateway request failed")}async function $g(e,t){return u(await l.get(`/projects/${e}/gateway/sessions${t?`?days=${t}`:""}`),"Gateway request failed")}async function Ug(e,t){return u(await l.get(`/projects/${e}/gateway/errors${t?`?days=${t}`:""}`),"Gateway request failed")}async function Fg(e){return u(await l.get(`/projects/${e}/gateway/budgets`),"Gateway request failed")}async function Ng(e,t){return u(await l.put(`/projects/${e}/gateway/budgets`,t),"Gateway request failed")}async function Bg(e,t){return u(await l.delete(`/projects/${e}/gateway/budgets/${t}`),"Gateway request failed")}async function Kg(e){return u(await l.get(`/projects/${e}/gateway/keys`),"Gateway request failed")}async function qg(e,t){return u(await l.post(`/projects/${e}/gateway/keys`,{name:t}),"Gateway request failed")}async function Gg(e,t){return u(await l.delete(`/projects/${e}/gateway/keys/${t}`),"Gateway request failed")}async function Wg(e,t,n,r,s){return u(await l.post(`/projects/${e}/gateway/playground`,{prompt:t,models:n,...r?{system:r}:{},...s&&Object.keys(s).length?{generationConfig:s}:{}}),"Gateway request failed")}async function u$(e,t){return u(await l.post(`/projects/${e}/gateway/providers/${encodeURIComponent(t)}/verify`,{}),"Gateway provider verification failed")}async function g$(){throw U("getReferralCode")}async function m$(){throw U("refreshReferralCode")}async function f$(e){throw U("validateReferralCode")}async function y$(){throw U("getReferralStats")}async function h$(e={}){throw U("listReferrals")}async function _$(e){throw U("sendReferralEmails")}var Eo="call:";function Hg(e){return e.startsWith("cr:")&&e.length>3?{type:"change_request",changeRequestId:e.slice(3)}:e.startsWith(Eo)&&e.length>Eo.length?{type:"connector_call",executionId:e.slice(Eo.length)}:{type:"review_item",reviewItemId:e}}function Cw(e){return e==="needs_you"?"needs_you":e==="waiting"?"waiting":"done"}function S$(e){let t={needs_you:0,waiting:0,done:0};for(let n of e)t[Cw(n.status)]+=1;return t}function P$(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 Mo(e){return e.split(/[._-]/).filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function zg(e){let t=e.indexOf(".");return t<=0?Mo(e):`(${Mo(e.slice(0,t))}) ${Mo(e.slice(t+1))}`}function Iw(e){let t=e.indexOf(".");return t>0?{connector:e.slice(0,t),action:e.slice(t+1)}:{connector:e,action:""}}var qr=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{},F=e=>typeof e=="string"&&e?e:void 0,Te=e=>Array.isArray(e)?e:void 0,Vg=e=>typeof e=="number"?e:0,Ew=e=>e.split(`
|
|
14
|
+
`).map(t=>t.trim()).filter(Boolean);function Mw(e,t){let n=qr(e.advanced),r=F(e.description),s=Te(e.whatChanged)??(r?Ew(r):t.summary?[t.summary]:[]);return{crId:F(e.cr_id),number:typeof e.number=="number"?e.number:void 0,whatChanged:s,impact:F(e.impact)??"",verification:Te(e.verification)??[],previewUrl:F(e.previewUrl)??F(e.preview_url),conflicts:Te(e.conflicts),requestedChanges:Te(e.requested_changes)??[],advanced:{headRef:F(n.headRef)??F(e.head_ref)??"",baseRef:F(n.baseRef)??F(e.base_ref)??"",headSha:F(n.headSha)??F(e.head_sha)??F(e.head_commit_sha)??"",baseSha:F(n.baseSha)??F(e.base_sha)??"",additions:Vg(n.additions),deletions:Vg(n.deletions),files:Te(n.files)??[],mergeMode:F(n.mergeMode)??"merge"}}}function Ow(e,t){let n=Te(e.actions);if(n)return{actions:n.map((c,p)=>({id:F(c.id)??`${t.review_item_id}-${p}`,title:F(c.title)??"Action",connector:F(c.connector)??"",action:F(c.action)??"",consequence:F(c.consequence)??"",risk:F(c.risk)??t.risk,icon:F(c.icon)??"generic",argsPreview:Te(c.argsPreview)??[],policySource:F(c.policySource)??"Requires approval",decided:c.decided==="approved"||c.decided==="denied"?c.decided:void 0}))};let r=F(e.action_path)??"",{connector:s,action:o}=Iw(r),i=qr(e.args_preview),a=Object.keys(i).length>0;return{actions:[{id:F(e.execution_id)??t.review_item_id,title:r?zg(r):t.title||"Run action",connector:s,action:o,consequence:"Runs against the real connector once you approve",risk:t.risk,icon:"generic",argsPreview:Object.entries(i).map(([c,p])=>({key:c,value:p==="[redacted]"?"Hidden credential":typeof p=="string"?p:JSON.stringify(p,null,2)})),actionPath:r,rawArgsPreview:a?i:void 0,reviewComplete:e.args_preview_complete===!0,previewAuthorized:e.args_preview_authorized!==!1,canResolve:typeof t.can_resolve=="boolean"?t.can_resolve:e.args_preview_authorized!==!1,...t.resolvers?{resolvers:t.resolvers}:{},approvalContext:F(e.approval_context),connectorRisk:F(e.risk)??null,policySource:"Requires approval"}]}}function Dw(e,t){return{artifactKind:F(e.artifactKind)??"document",artifactLabel:F(e.artifactLabel)??"Output",previewUrl:F(e.previewUrl)??F(e.preview_url),preview:F(e.preview),files:Te(e.files),note:F(e.note)??t.summary??""}}function jw(e,t){return{question:F(e.question)??t.title??"",context:F(e.context),options:Te(e.options)??[]}}function Lw(e,t){return{note:F(e.note)??t.summary??"",children:Te(e.children)??[]}}function $w(e){let t=qr(e.detail);switch(e.kind){case"change":return Mw(t,e);case"approval":return Ow(t,e);case"output":return Dw(t,e);case"decision":return jw(t,e);case"batch":return Lw(t,e)}}function Uw(e,t){let n=typeof e.number=="number"?e.number:void 0,r=F(e.base_ref);return n!=null&&r?`#${n} \u2192 ${r}`:t}function x$(e,t={}){let n=qr(e.detail),r=e.origin_session_id??void 0,s=r?t.sessionLabels?.[r]:void 0,o=e.kind==="approval"?F(n.action_path):void 0,i=e.kind==="change"?Uw(n,e.summary):e.kind==="approval"?s??(r?"From a running session":e.summary):e.summary;return{id:e.review_item_id,kind:e.kind,title:o?zg(o):e.title,summary:i,risk:e.risk,status:e.status,source:e.source,agent:e.agent||"Agent",createdAt:e.created_at,sessionId:r,detail:$w(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_CREDENTIALS_ISSUE:"project.credentials.issue"},v$=[Z.PROJECT_WRITE,Z.PROJECT_TRIGGER_CREATE,Z.PROJECT_TRIGGER_FIRE,Z.PROJECT_TRIGGER_UPDATE,Z.PROJECT_TRIGGER_DELETE];function A$(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 R$=[Z.PROJECT_WRITE,Z.PROJECT_GITOPS_PUSH,Z.PROJECT_GITOPS_MERGE,Z.PROJECT_REVIEW_ACT];function Fw(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 T$(e,t,n){let r=Hg(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 Fw(n).canMerge}return n[Z.PROJECT_WRITE]?.allowed===!0&&n[Z.PROJECT_REVIEW_ACT]?.allowed===!0}function $(e){return l.get(e,{showErrors:!1})}function A(e){return u(e,"Unexpected empty response")}async function Yg(e){return A(await $(`/accounts/${e}/iam/groups`)).groups}async function Jg(e,t){return A(await $(`/accounts/${e}/iam/groups/${t}`))}async function Qg(e,t){return A(await l.post(`/accounts/${e}/iam/groups`,t,{showErrors:!1}))}async function Xg(e,t,n){return A(await l.patch(`/accounts/${e}/iam/groups/${t}`,n))}async function Zg(e,t){return A(await l.delete(`/accounts/${e}/iam/groups/${t}`))}async function em(e,t){return A(await $(`/accounts/${e}/iam/groups/${t}/members`)).members}async function tm(e,t,n){return A(await l.post(`/accounts/${e}/iam/groups/${t}/members`,{userIds:n}))}async function j$(e,t){return A(await $(`/accounts/${e}/iam/groups/${t}/project-grants`)).grants}async function nm(e,t,n){return A(await l.delete(`/accounts/${e}/iam/groups/${t}/members/${n}`))}async function L$(e,t){return A(await $(`/accounts/${e}/iam/members/${t}/groups`)).groups}async function $$(e,t){let n=A(await $(`/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 K$(e,t={}){let n=Ze({resourceType:t.resourceType,principalType:t.principalType,principalId:t.principalId,projectId:t.projectId});return A(await $(`/accounts/${e}/iam/resource-grants${n}`)).grants}async function H$(e,t={}){let n=Ze({principalType:t.principalType,principalId:t.principalId,scopeType:t.scopeType,scopeId:t.scopeId===null?"null":t.scopeId});return A(await $(`/accounts/${e}/iam/policies${n}`)).policies}async function z$(e,t){return A(await l.post(`/accounts/${e}/iam/policies`,t,{showErrors:!1}))}async function Y$(e,t,n){return A(await l.patch(`/accounts/${e}/iam/policies/${t}`,n,{showErrors:!1}))}async function J$(e,t){return A(await l.delete(`/accounts/${e}/iam/policies/${t}`))}async function Q$(e,t){return A(await l.post(`/accounts/${e}/iam/policies:bulk-delete`,{policy_ids:t},{showErrors:!1}))}async function X$(e,t){return A(await l.post(`/accounts/${e}/iam/policies:bulk-import`,{policies:t},{showErrors:!1}))}async function rm(e){return A(await $(`/accounts/${e}/iam/roles`)).roles}async function sm(e){return A(await $(`/accounts/${e}/iam/agent-identities`)).agents}async function om(e){return A(await l.get(`/projects/${e}/agent-identities`,{showErrors:!1})).agents}async function im(e,t){return A(await $(`/accounts/${e}/iam/roles/${t}/permissions`))}async function n0(e){return A(await $(`/accounts/${e}/iam/actions`)).actions}async function am(e,t){return A(await $(`/accounts/${e}/iam/roles/${t}/usage`))}async function cm(e,t){return A(await l.post(`/accounts/${e}/iam/roles`,t,{showErrors:!1}))}async function lm(e,t,n){return A(await l.patch(`/accounts/${e}/iam/roles/${t}`,n,{showErrors:!1}))}async function um(e,t,n){return A(await l.put(`/accounts/${e}/iam/roles/${t}/permissions`,{actions:n},{showErrors:!1}))}async function pm(e,t){return A(await l.delete(`/accounts/${e}/iam/roles/${t}`,{showErrors:!1}))}async function r0(e,t,n){return A(await l.patch(`/accounts/${e}/iam/members/${t}/super-admin`,{isSuperAdmin:n}))}async function a0(e){return A(await $(`/accounts/${e}/iam/scim/tokens`)).tokens}async function c0(e,t){return A(await l.post(`/accounts/${e}/iam/scim/tokens`,t,{showErrors:!1}))}async function l0(e,t){return A(await l.delete(`/accounts/${e}/iam/scim/tokens/${t}`))}async function g0(e){return A(await $(`/accounts/${e}/iam/mfa-required`))}async function m0(e){return A(await $(`/accounts/${e}/iam/mfa-required/preview`))}async function f0(e,t){return A(await l.patch(`/accounts/${e}/iam/mfa-required`,{enabled:t},{showErrors:!1}))}async function y0(e){return A(await $(`/accounts/${e}/iam/session-oversight`))}async function h0(e,t){return A(await l.patch(`/accounts/${e}/iam/session-oversight`,{enabled:t},{showErrors:!1}))}async function P0(e){return A(await $(`/accounts/${e}/iam/sso/provider`)).provider}async function x0(e,t){return A(await l.put(`/accounts/${e}/iam/sso/provider`,t,{showErrors:!1})).provider}async function w0(e,t){return A(await l.post(`/accounts/${e}/iam/sso/provider/from-metadata`,t,{showErrors:!1})).provider}async function k0(e){return A(await l.post(`/accounts/${e}/iam/sso/provider/verify-domain`,{},{showErrors:!1})).provider}async function v0(e){return A(await l.delete(`/accounts/${e}/iam/sso/provider`))}async function A0(e){return A(await $(`/accounts/${e}/iam/sso/mappings`)).mappings}async function R0(e,t){return A(await l.post(`/accounts/${e}/iam/sso/mappings`,t,{showErrors:!1}))}async function T0(e,t){return A(await l.delete(`/accounts/${e}/iam/sso/mappings/${t}`))}async function M0(e){return A(await $(`/accounts/${e}/iam/session-policy`))}async function O0(e,t){return A(await l.patch(`/accounts/${e}/iam/session-policy`,t,{showErrors:!1}))}async function D0(e){return A(await $(`/accounts/${e}/iam/sessions`)).sessions}async function j0(e,t){return A(await l.post(`/accounts/${e}/iam/sessions/${t}/revoke`,{},{showErrors:!1}))}async function L0(e){return A(await $(`/accounts/${e}/iam/pat-policy`))}async function $0(e,t){return A(await l.patch(`/accounts/${e}/iam/pat-policy`,t,{showErrors:!1}))}async function B0(e){return A(await $(`/accounts/${e}/iam/service-accounts`)).service_accounts}async function K0(e,t){return A(await l.post(`/accounts/${e}/iam/service-accounts`,t,{showErrors:!1}))}async function q0(e,t){return A(await l.post(`/accounts/${e}/iam/service-accounts/${t}/disable`,{},{showErrors:!1}))}async function G0(e,t){return A(await l.delete(`/accounts/${e}/iam/service-accounts/${t}`))}async function Y0(e){return A(await $(`/accounts/${e}/audit/webhooks`)).webhooks}async function J0(e,t){return A(await l.post(`/accounts/${e}/audit/webhooks`,t,{showErrors:!1}))}async function Q0(e,t,n){return A(await l.patch(`/accounts/${e}/audit/webhooks/${t}`,n))}async function X0(e,t){return A(await l.delete(`/accounts/${e}/audit/webhooks/${t}`))}async function Z0(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 $(`/accounts/${e}/audit${n}`))}async function dm(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 $(`/accounts/${e}/iam/members/${t}/effective?${r.toString()}`))}async function gm(e,t,n){return n.length===0?[]:A(await l.post(`/accounts/${e}/iam/members/${t}/effective:batch`,{probes:n})).results}async function iU(e){return A(await $(`/accounts/${e}/iam/enterprise-demo`)).enabled}async function aU(e,t){return A(await l.put(`/accounts/${e}/iam/enterprise-demo`,{enabled:t})).enabled}async function mm(e){return u(await l.get(`/accounts/${e}/iam/oauth-clients`,{showErrors:!1}))}async function fm(e,t){return u(await l.get(`/accounts/${e}/iam/oauth-clients/${t}`,{showErrors:!1}))}async function ym(e,t){return u(await l.post(`/accounts/${e}/iam/oauth-clients`,t,{showErrors:!1}))}async function hm(e,t,n){return u(await l.patch(`/accounts/${e}/iam/oauth-clients/${t}`,n,{showErrors:!1}))}async function _m(e,t){return u(await l.post(`/accounts/${e}/iam/oauth-clients/${t}/rotate-secret`,{},{showErrors:!1}))}async function bm(e,t){return u(await l.delete(`/accounts/${e}/iam/oauth-clients/${t}`,{showErrors:!1}))}function Nw(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 Sm(e,t){return u(await $(`/accounts/${e}/iam/assignments${Nw(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 l.post(`/accounts/${e}/iam/assignments`,n))}async function xm(e,t){return u(await l.delete(`/accounts/${e}/iam/assignments/${t}`)).assignment}async function wm(e,t){let n=t?.scopeType?`?scope_type=${t.scopeType}`:"";return u(await $(`/accounts/${e}/iam/permissions${n}`)).permissions}async function bU(){let e=await l.get("/account/deletion-status",{showErrors:!1});return e.error?.status===404?null:u(e,"Failed to load account deletion status")}async function SU(e="User requested deletion"){return u(await l.post("/account/request-deletion",{reason:e},{showErrors:!1}),"Failed to request account deletion")}async function PU(){return u(await l.post("/account/cancel-deletion",void 0,{showErrors:!1}),"Failed to cancel account deletion")}async function xU(){return u(await l.delete("/account/delete-immediately",{showErrors:!1}),"Failed to delete account immediately")}async function wU(){return(await l.get("/user-roles",{showErrors:!1})).data??{isAdmin:!1,role:null}}function RU(){return l.get("/admin/api/provider-distribution").then(e=>u(e))}function TU(e=300){return l.get(`/admin/api/sandboxes?limit=${e}`).then(t=>u(t))}function CU(e){return l.put("/admin/api/provider-distribution",e).then(t=>u(t))}function IU(e){return l.get(`/admin/api/provider-analytics?days=${e}`).then(t=>u(t))}function EU(e,t){return l.post(`/admin/api/sandboxes/${encodeURIComponent(e)}/migrate`,{targetProvider:t}).then(n=>u(n))}function MU(){return l.get("/admin/api/provider-fallback").then(e=>u(e))}function OU(e){return l.put("/admin/api/provider-fallback",{enabled:e}).then(t=>u(t))}var km="Export the deck as PDF or PPTX with convertRuntimePresentation().";async function LU(e){throw U("getGoogleAuthUrl",km)}async function $U(e,t){throw U("convertPresentationToGoogleSlides",km)}async function vm(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 l.get(`/projects/${e}/review/items${r?`?${r}`:""}`,{showErrors:!1}))}async function Am(e){return u(await l.get(`/projects/${e}/review/summary`,{showErrors:!1}))}async function Rm(e,t){return u(await l.get(`/projects/${e}/review/items/${t}`))}async function Tm(e,t){return u(await l.post(`/projects/${e}/review/items`,t))}async function Cm(e,t,n){return u(await l.post(`/projects/${e}/review/items/${t}/act`,n))}async function Im(e,t){return u(await l.post(`/projects/${e}/review/bulk`,t))}async function Em(e){return u(await l.get(`/p/share?sandbox_id=${encodeURIComponent(e)}`),"Failed to load public links").shares??[]}async function Mm(e){return u(await l.post("/p/share",{sandbox_id:e.sandboxId,port:e.port,ttl:e.ttl,label:e.label}),"Failed to generate public URL")}async function Om(e,t){let n=await l.delete(`/p/share/${encodeURIComponent(t)}?sandbox_id=${encodeURIComponent(e)}`);if(!n.success)throw new Error(n.error?.message??"Failed to revoke public link")}var Oo=class extends Error{constructor(n,r){super(n);this.status=r;this.name="PublicSessionShareError"}status};function Dm(e,t=""){return`${pn()}/public/session-shares/${encodeURIComponent(e)}${t}`}async function jm(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 Oo(s,t.status)}return r}async function VU(e){return jm(Dm(e))}async function HU(e){return jm(Dm(e,"/messages"))}async function Lm(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/reminders`))}async function $m(e,t,n){return u(await l.post(`/projects/${e}/sessions/${t}/reminders`,n))}async function Do(e,t,n,r){return u(await l.patch(`/projects/${e}/sessions/${t}/reminders/${n}`,r))}async function jo(e,t,n){return u(await l.delete(`/projects/${e}/sessions/${t}/reminders/${n}`))}var Bw=4;async function Um(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(Bw,e.length)},s));let o={done:[],failed:[]};return e.forEach((i,a)=>{let c=n[a];c.ok?o.done.push(i):o.failed.push({reminder:i,error:c.error})}),o}function Fm(e,t,n){return Um(t,r=>Do(e,r.sessionId,r.reminderId,n))}function Nm(e,t){return Um(t,n=>jo(e,n.sessionId,n.reminderId))}async function Bm(e){return u(await l.get(`/projects/${e}/reminders`))}async function Km(e,t){let n=new URLSearchParams;e&&n.set("account_id",e),t?.mine&&n.set("mine","true");let r=n.size>0?`?${n.toString()}`:"";return u(await l.get(`/accounts/tokens${r}`))}async function qm(e){let{accountId:t,expiresAt:n,projectId:r,name:s}=e;return u(await l.post("/accounts/tokens",{name:s,...t?{account_id:t}:{},...n?{expires_at:n}:{},...r?{project_id:r}:{}}))}async function Gm(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 l.delete(`/accounts/tokens/${encodeURIComponent(e)}${s}`))}async function Wm(){return u(await l.get("/oauth/grants")).grants}async function Vm(e){return u(await l.delete(`/oauth/grants/${encodeURIComponent(e)}`))}async function eF(){return u(await l.get("/accounts/me/devices")).devices}async function tF(e){return u(await l.delete(`/accounts/me/devices/${encodeURIComponent(e)}`))}async function Hm(e){return u(await l.get(`/projects/${e}/cli-token`))}async function zm(e,t){return u(await l.post(`/projects/${e}/cli-token`,t??{}))}async function Ym(e,t){return u(await l.delete(`/projects/${e}/cli-token/${t}`))}function Lt(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 Lo(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 Jm(e,t){let n=Lt(Lo(t)).toString();return u(await l.get(`/accounts/${e}/audit${n?`?${n}`:""}`))}async function Qm(e,t){let n=Lt(Lo({...t,projectId:void 0})).toString();return u(await l.get(`/projects/${e}/audit${n?`?${n}`:""}`))}async function Xm(e,t){let n=Lt(Lo(t)).toString();return u(await l.get(`/accounts/${e}/audit/export${n?`?${n}`:""}`))}async function Zm(e){return u(await l.get(`/accounts/${e}/audit/webhooks`))}async function ef(e,t){return u(await l.post(`/accounts/${e}/audit/webhooks`,t))}async function tf(e,t,n){return u(await l.patch(`/accounts/${e}/audit/webhooks/${t}`,n))}async function nf(e,t){return u(await l.delete(`/accounts/${e}/audit/webhooks/${t}`))}async function rf(e,t){return u(await l.post(`/projects/${e}/secret-requests`,{names:t.names,labels:t.labels,descriptions:t.descriptions,scope:t.scope,expires_in_minutes:t.expiresInMinutes}),"Failed to mint secret-entry link")}async function sf(e,t){return u(await l.post(`/projects/${e}/connect-requests`,{slug:t.slug,...t.owner?{owner:t.owner}:{},...t.label?{label:t.label}:{},expires_in_minutes:t.expiresInMinutes}),"Failed to mint connect link")}async function uF(e){return u(await l.get(`/approval-links/${e}`),"Failed to load approval")}async function of(e){let t=new URLSearchParams;e?.query&&t.set("query",e.query),e?.type&&t.set("type",e.type),e?.source&&t.set("source",e.source),e?.limit!==void 0&&t.set("limit",String(e.limit)),e?.offset!==void 0&&t.set("offset",String(e.offset));let n=t.toString()?`?${t.toString()}`:"";return u(await l.get(`/marketplace/items${n}`))}async function af(){return u(await l.get("/marketplace/marketplaces"))}async function cf(){return u(await l.get("/marketplace/marketplaces/featured"))}async function lf(e){return u(await l.get(`/marketplace/items/${encodeURIComponent(e)}`),"Item not found")}async function uf(e,t){return u(await l.get(`/marketplace/items/${encodeURIComponent(e)}/file?path=${encodeURIComponent(t)}`),"File not found")}async function pf(){return u(await l.get("/marketplace/sources"))}async function df(e){return u(await l.post("/marketplace/sources",e),"Failed to add marketplace source")}async function gf(e){return u(await l.delete(`/marketplace/sources/${encodeURIComponent(e)}`),"Failed to remove marketplace source")}async function mF(e,t){return u(await l.post(`/projects/${encodeURIComponent(e)}/marketplace/install-session`,{id:t}),"Failed to start marketplace install session")}async function hF(e){throw U("getTemplate")}async function _F(e,t){throw U("installTemplate")}async function mf(e){return u(await l.get(`/projects/${e}/apps`),"Failed to list Apps").apps}async function ff(e,t){return u(await l.post(`/projects/${e}/apps`,t),"Failed to create App")}async function $o(e,t){return u(await l.get(`/projects/${e}/apps/${t}`),"Failed to load App")}async function yf(e,t,n){return u(await l.patch(`/projects/${e}/apps/${t}`,n),"Failed to update App")}async function hf(e,t){return u(await l.delete(`/projects/${e}/apps/${t}`),"Failed to delete App")}async function _f(e,t){return u(await l.post(`/projects/${e}/apps/${t}/token`,{}),"Failed to mint an App token")}async function bf(e,t){let n=await $o(e,t);if(!n.auth)throw new Error("This server does not report sign-in values for Apps.");let r=u(await l.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 Sf(e,t){return u(await l.get(`/projects/${e}/apps/${t}/access`),"Failed to load App access policy")}async function Pf(e,t){return u(await l.get(`/projects/${e}/apps/${t}/agents`),"Failed to load the agents with access to this App").agents}async function xf(e,t,n){return u(await l.patch(`/projects/${e}/apps/${t}/access`,n),"Failed to update App access policy")}async function wf(e,t){return u(await l.post(`/projects/${e}/apps/${t}/access-session`,{}),"Failed to create App access session")}async function Uo(e,t){return u(await l.post(`/projects/${e}/apps/artifacts`,t),"Failed to register App artifact")}async function Fo(e,t,n){return u(await l.post(`/projects/${e}/apps/artifacts/${t}/finalize`,n),"Failed to finalize App artifact")}async function Kw(e){return e instanceof Uint8Array?e:new Uint8Array(await e.arrayBuffer())}async function qw(e){let t=Uint8Array.from(e),n=await globalThis.crypto.subtle.digest("SHA-256",t.buffer);return Array.from(new Uint8Array(n),r=>r.toString(16).padStart(2,"0")).join("")}async function kf(e,t,n={}){let r=await Kw(t),s=n.mediaType??"application/gzip",o=await Uo(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),Fo(e,o.artifact.artifact_id,{sha256:await qw(r),size_bytes:r.byteLength})}async function vf(e,t,n){return u(await l.post(`/projects/${e}/apps/${t}/deployments`,n),"Failed to create App deployment")}async function Af(e,t){return u(await l.get(`/projects/${e}/apps/${t}/deployments`),"Failed to list App deployments").deployments}async function Rf(e,t,n){return u(await l.get(`/projects/${e}/apps/${t}/deployments/${n}`),"Failed to load App deployment")}async function Tf(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 l.get(`/projects/${e}/apps/${t}/deployments/${n}/logs${o}`),"Failed to load App logs")}async function Cf(e,t){return u(await l.post(`/projects/${e}/apps/${t}/start`,{}),"Failed to start App")}async function If(e,t){return u(await l.post(`/projects/${e}/apps/${t}/stop`,{}),"Failed to stop App")}async function Ef(e,t,n){return u(await l.delete(`/projects/${e}/apps/${t}/deployments/${n}`),"Failed to delete App deployment")}async function Mf(e,t,n){return u(await l.post(`/projects/${e}/apps/${t}/rollback`,{deployment_id:n}),"Failed to roll back App")}var ye=(e,t)=>`/projects/${e}/apps/${t}`;async function Of(e,t){return u(await l.get(`${ye(e,t)}/machines`),"Failed to list machines").machines}async function No(e,t,n,r){return u(await l.post(`${ye(e,t)}/machines/${n}/${r}`,{}),`Failed to ${r} the machine`).machines}var Df=(e,t,n)=>No(e,t,n,"start"),jf=(e,t,n)=>No(e,t,n,"stop"),Lf=(e,t,n)=>No(e,t,n,"restart");async function $f(e,t,n){return u(await l.delete(`${ye(e,t)}/machines/${n}`),"Failed to destroy the machine").machines}async function Uf(e,t,n,r={}){return u(await l.put(`${ye(e,t)}/scale`,{count:n,...r.newVolumes?{new_volumes:!0}:{}}),"Failed to scale the App")}async function Ff(e,t,n){return u(await l.post(`${ye(e,t)}/exec`,n),"Failed to run the command")}async function Nf(e,t){return u(await l.get(`${ye(e,t)}/volumes`),"Failed to list volumes").volumes}async function Bf(e,t,n){return u(await l.post(`${ye(e,t)}/volumes`,n),"Failed to create the volume")}async function Kf(e,t,n,r){return u(await l.patch(`${ye(e,t)}/volumes/${n}`,r),"Failed to update the volume")}async function qf(e,t,n,r){u(await l.delete(`${ye(e,t)}/volumes/${n}?confirm=${encodeURIComponent(r)}`),"Failed to destroy the volume")}async function Gf(e,t,n){return u(await l.get(`${ye(e,t)}/volumes/${n}/snapshots`),"Failed to list snapshots").snapshots}async function Wf(e,t,n){return u(await l.post(`${ye(e,t)}/volumes/${n}/snapshots`,{}),"Failed to take the snapshot")}async function Vf(e,t,n,r){return u(await l.post(`${ye(e,t)}/volumes/${n}/restore`,{snapshot_id:r}),"Failed to restore the volume")}async function Hf(e,t,n,r){return u(await l.post(`${ye(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 OF(e){let t=u(await l.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 DF(e,t){return u(await l.get(`${de(e)}/access?${new URLSearchParams({path:t})}`),"Failed to load sharing")}async function jF(e,t){return u(await l.put(`${de(e)}/access`,t),"Failed to share folder")}async function LF(e,t){let n=u(await l.delete(`${de(e)}/access/${encodeURIComponent(t)}`),"Failed to stop sharing");return{pendingSessions:typeof n?.pendingSessions=="number"?n.pendingSessions:0}}async function $F(e){return u(await l.get(`${de(e)}/principals`),"Failed to load people")}async function UF(e){return u(await l.get(`${de(e)}/conflicts`),"Failed to load conflicts").conflicts}async function FF(e,t){u(await l.post(`${de(e)}/conflicts/${encodeURIComponent(t)}/dismiss`,{}),"Failed to dismiss conflict")}async function NF(e,t="/"){return(await Gw(e,t)).entries}async function Gw(e,t="/"){return u(await l.get(`${de(e)}/files?${new URLSearchParams({path:t})}`,{showErrors:!1}),"Failed to load files")}function zf(e,t,n){let r=ue(T().backendUrl),s={path:t};return n?.download&&(s.download="1"),`${r}${de(e)}/files/content?${new URLSearchParams(s)}`}async function BF(e,t,n){let r=await L(zf(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 KF(e,t,n){let r=await L(zf(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 qF(e,t,n,r){let s=`${de(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 Ww(a,s,d,o,i,r?.signal)}let c=u(await l.putRaw(s,n,{signal:r?.signal,headers:o}),"Failed to upload file"),p=n instanceof Blob?n.size:n.byteLength;return i?.(p,p),c}async function Ww(e,t,n,r,s,o){let i=`${ue(T().backendUrl)}${t}`,{headers:a,rejected:c}=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 _=()=>o?.removeEventListener("abort",f);g.open("PUT",i),a.forEach((y,k)=>g.setRequestHeader(k,y)),g.upload.onprogress=y=>s(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&&c(),d(new P(y?.message||"Failed to upload file",{status:g.status,code:y?.code,url:i}))},g.onerror=()=>{_(),d(new P("Network error while uploading",{name:"TypeError",url:i}))},g.onabort=()=>{_(),d(m())},g.send(n)})}async function GF(e,t){return u(await l.post(`${de(e)}/files/mkdir`,{path:t}),"Failed to create folder")}async function WF(e,t,n){return u(await l.post(`${de(e)}/files/move`,{from:t,to:n}),"Failed to move")}async function VF(e,t,n){let r={path:t};n?.recursive&&(r.recursive="true"),u(await l.delete(`${de(e)}/files?${new URLSearchParams(r)}`),"Failed to delete")}async function HF(e){return u(await l.get(`${de(e)}/versions`),"Failed to load versions").versions}async function zF(e,t){u(await l.post(`${de(e)}/restore`,{versionId:t}),"Failed to restore version")}var Vw=(e,t)=>`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/drives`;async function YF(e,t){return(await Hw(e,t)).drives}async function Hw(e,t){return u(await l.get(Vw(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")||T().backendUrl;return e||"http://localhost:8008/v1"}function Ne(e){let t=ue(e);return t.endsWith("/v1")?t:`${t}/v1`}function dn(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=dn(t);if(n)return n}return}if(e&&typeof e=="object"){let t=e;return dn(t.sandboxId??t.id??t.slug??Object.values(t)[0])}}function zw(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 Gr(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:zw(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 Bo(){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:Gr(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 Ko(e){let t=await l.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 Wr(e){let t=await Ko(e);if(t)return{projectId:t.project_id,sessionId:t.session_id};let n=await gn(e);return n?{projectId:n.project.project_id,sessionId:n.session.session_id}:null}async function gn(e){let t=await Bo();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 Yf(e){return u(await l.post("/notifications/device-token",e))}async function Jf(e,t){return u(await l.delete(`/notifications/device-token/${encodeURIComponent(e)}`,{signal:t?.signal}))}async function Qf(e,t){let n=T().fetch??((o,i)=>fetch(o,i)),r=Ne(t?.backendUrl??T().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 pN=["turn_done","turn_error","question","permission","shared","automation_failed","automation_recovered","capture_device_down","capture_device_recovered"];async function Xf(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 l.get(`/notifications${r?`?${r}`:""}`,{showErrors:!1,signal:t?.signal}))}async function Zf(e){let t="ids"in e?{ids:e.ids}:"all"in e?{all:!0}:{session_id:e.sessionId};return u(await l.post("/notifications/read",t))}var dN={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}};async function ey(){return u(await l.get("/notifications/preferences",{showErrors:!1}))}async function ty(e){return u(await l.put("/notifications/preferences",e))}async function ny(){return u(await l.get("/notifications/web-push/key",{showErrors:!1}))}async function ry(e){let t={endpoint:e.endpoint,keys:{p256dh:e.keys.p256dh,auth:e.keys.auth}};return u(await l.post("/notifications/web-push/subscriptions",t,{showErrors:!1}))}async function sy(e,t){return u(await l.delete(`/notifications/web-push/subscriptions?endpoint=${encodeURIComponent(e)}`,{signal:t?.signal,showErrors:!1}))}async function Vr(e){return u(await l.get(`/projects/${e}/model-access`))}async function Hr(e,t){return u(await l.put(`/projects/${e}/model-access`,t))}function hN(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 qo(e){return typeof e=="string"&&e.trim().length>0}function oy(e){if(!e||typeof e!="object")return!1;let{path:t,url:n,content:r}=e;return qo(t)||qo(n)||qo(r)}function Yw(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=Yw(e.items);return t?!t.some(oy):!oy(e)}var Ce="kortix.transcript.v1",Jw=["auth","rate_limit","credits","context_length","output_length","aborted","unknown"];function iy(e){return typeof e=="string"&&Jw.includes(e)}var bN=["once","always","reject"],SN=["read","edit","glob","grep","list","bash","task","external_directory","todowrite","question","webfetch","websearch","lsp","doom_loop","skill"];var ly="kortix-v1-import",Qw={harness:ly,harness_version:Ce,adapter_version:"1"},Go={schema:le,v:1},Xw={opencode:"[Tool execution was interrupted]",pi:"No result provided"},Zw="[Old tool result content cleared]",ek="The following tool was executed by the user",tk=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"})),nk=e=>tk.get(e)??(e.includes("_")?"mcp":"other"),rk=new Map([["stop","stop"],["tool-calls","tool_calls"],["length","length"],["error","error"]]),sk=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,Xr=(e,t)=>Object.hasOwn(e,t)?e[t]:void 0,uy=(e,t,n)=>Object.defineProperty(e,t,{value:n,enumerable:!0,writable:!0,configurable:!0}),$t=e=>Be(e)!==void 0&&Math.abs(e)<=864e13?new Date(e).toISOString():null,Ut=e=>{let t=e?Date.parse(e):NaN;return Number.isNaN(t)?void 0:t};function Wo(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)=>Wo(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=>Wo(e[r],Xr(t,r)))}function Jr(e,t){if(Wo(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=Jr(Xr(e,r),Xr(t,r));s&&uy(n,r,s)}return{sub:n}}function Qr(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=Qr(Xr(n,r),s);o===void 0?delete n[r]:uy(n,r,o)}return n}var mn=e=>Object.values(e??{}).find(t=>t.version===Ce),Zr=(e,t)=>({[e]:{version:Ce,...t}}),py=(e,t)=>e.url!==void 0?{url:e.url}:e.ref!==void 0&&!t.fromV1?{url:e.ref}:{},ay=e=>(e??[]).flatMap(t=>t.type==="text"?[t.text]:[]).join(""),ok=(e,t)=>({id:e.id,...t.sessionID!==null&&{sessionID:t.sessionID},messageID:t.messageID}),ik=e=>{if(B(e.result?.details))return e.result.details;let t=Object.values(e.ext??{}).find(n=>n.version!==Ce&&B(n.data?.details));return t?t.data.details:{}};function ak(e,t,n){let r=e.result,s=e.input===null||e.input===void 0?{}:{input:e.input},o=Ut(e.started_at)??t.created,i=Ut(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:ay(r?.content),...r?.exit_code!==void 0&&{metadata:a},time:{start:o,end:i}};let c=(r?.content??[]).flatMap((d,g)=>d.type==="attachment"?[{...n,id:`${e.id}-a${g}`,type:"file",mime:d.mime,...py(d,t)}]:[]),p=Ut(r?.cleared_at);return{status:"completed",...s,output:ay(r?.content),title:e.title??"",metadata:{...ik(e),...a},time:{start:o,end:i,...p!==void 0&&{compacted:p}},...c.length&&{attachments:c}}}function dy(e,t){let n=ok(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},...py(e,t)};case"tool_call":return{...n,type:"tool",callID:e.call_id,tool:e.name,state:ak(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 iy(e.code)?{name:e.code==="aborted"?"MessageAbortedError":"UnknownError",code:e.code,data:{message:e.message}}:{name:e.code,data:{message:e.message}}}function gy(e,t,n={}){let r=e.usage,s=e.finish===null?void 0:sk.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:Ut(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 my(e,t){return e.role==="assistant"?gy(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 fy(e,t,n){let r=`${e.message_id}-summary`;return{info:gy({...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 lk(e,t,n){let r=n||e.producer.harness===ly;if(!r&&(e.role==="system"||e.kind==="context"))return[];let s=mn(e.ext)?.data,o=s&&"runtime_session_id"in s?s.runtime_session_id??null:t,i={sessionID:o,messageID:e.message_id,created:Ut(e.created_at),fromV1:r},a=s&&"parts"in s?s.parts:e.blocks.flatMap(d=>{let g=dy(d,i);return g===void 0?[]:[Qr(g,mn(d.ext)?.data)]}),c=[{runtime_session_id:o,info:Qr(my(e,i),s?.info),parts:a}],p=e.blocks.find(d=>d.type==="compaction");if(e.kind==="compaction"&&p&&p.summary!==null){let d=Qr(fy(e,p,i),s?.summary);c.push({runtime_session_id:o,info:d.info,parts:d.parts})}return c}var Vo=e=>Be(B(e.info)&&B(e.info.time)?e.info.time.created:void 0)??-1/0,Yr=e=>String(B(e.info)?e.info.id:""),yy=(e,t)=>Vo(e)-Vo(t)||(Yr(e)<Yr(t)?-1:Yr(e)>Yr(t)?1:0),cy=e=>{let t=mn(e.ext);return t?t.native_id??null:e.thread_id};function es(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=>lk(a,cy(i),mn(i.ext)!==void 0))),s=mn(t.ext)?.data,o=s&&"root_id"in s?s.root_id??null:n?cy(n):null;return{session_id:t.session_id,root_id:o,rows:r.sort(yy)}}function uk(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 pk(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 dk=e=>({code:J(e.code)||J(e.name)||"UnknownError",message:J(B(e.data)?e.data.message:void 0)??""});function hy(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 gk(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,c,p=s.input??null;if(s.status==="completed"){let m=(Array.isArray(s.attachments)?s.attachments:[]).filter(B).map(_=>{let{bytes:y,...k}=hy(_,n,r);return{type:"attachment",...k}}),f=$t(o.compacted);a="complete",c={content:[...J(s.output)!==void 0?[{type:"text",text:s.output}]:[],...m],is_error:!1,...i,...f&&{model_content:[{type:"text",text:Zw}],cleared_at:f}}}else if(s.status==="error"){let m=J(s.error);a="error",c={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"&&J(s.raw)&&!(B(s.input)&&Object.keys(s.input).length)&&(p=s.raw);else{let m=Xw[n.h];a="error",c={content:[{type:"text",text:m}],is_error:!0,synthetic:!0,error:{code:"interrupted",message:m}}}let d=$t(o.start),g=$t(o.end);return{type:"tool_call",id:t,call_id:e.callID,name:e.tool,kind:nk(e.tool),input:p,status:a,...c&&{result:c},...J(s.title)&&{title:s.title},...d&&{started_at:d},...g&&{ended_at:g}}}function mk(e,t,n,r,s,o){let i=(a,c=!1)=>({type:"harness",id:t,harness:s.h,kind:a,data:e,model_visible:c,...c&&{fallback_text:ek}});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,...hy(e,s,o),...J(e.filename)!==void 0&&{name:e.filename}};case"tool":return typeof e.callID=="string"&&typeof e.tool=="string"&&B(e.state)?gk(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:J(e.tail_start_id)??null,trigger:a}}case"subtask":return i("subtask",!0);default:return i(J(e.type)||"unknown")}}function fk(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 yk(e,t,n,r,s,o){let i=B(e.info)?e.info:{},a=Array.isArray(e.parts)?e.parts:[],c=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=c?p:d==="assistant"?i:void 0,m=g&&B(g.error)?g.error:void 0,f=m?.name==="MessageAbortedError",_=g&&B(g.time)?$t(g.time.completed):null,y=o.live?"streaming":"interrupted",k=g?m?f?"aborted":"error":_?"complete":y:c?y:"complete",R=$t(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=fk(a),h=a.map((w,D)=>mk(w,M[D],c,I,o,b)),x=h.some(w=>w.type==="text"||w.type==="attachment"||w.type==="tool_call"||w.type==="harness"&&w.model_visible),S=!s&&d!=="system"&&(c?k==="complete":!m||f&&x),v=o.live&&S&&k!=="streaming"&&h.some(w=>w.type==="tool_call"&&(w.status==="pending"||w.status==="running"))?"streaming":k,C=s?"superseded":S||!m?void 0:f?"aborted":"failed_attempt";return c&&B(c)&&J(c.tail_start_id)===void 0&&b.cut_point++,{m:{...Go,message_id:J(i.id)??"",thread_id:n,seq:r,role:d,kind:c?"compaction":"turn",status:v,in_context:S,...C&&{hidden_reason:C},agent:J(i.agent)??null,...d==="assistant"&&{reply_to:J(i.parentID)??null},model:uk(i),usage:g?pk(g):null,finish:!g||c?null:f?"aborted":m?"error":rk.get(i.finish)??null,error:m?dk(m):null,created_at:R,completed_at:g||c?_:R||null,producer:Qw,blocks:h},lost:b}}function hk(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:Ut(e.created_at),fromV1:!0};Array.isArray(t.parts)?e.blocks.forEach((p,d)=>{if(p.type==="harness"||p.type==="subtask")return;let g=Jr(t.parts[d],dy(p,i));g&&(p.ext=Zr(s,{data:g}))}):o.parts=t.parts;let a=Jr(t.info,my(e,i));a&&(o.info=a);let c=e.blocks.find(p=>p.type==="compaction");if(n&&c){let p=Jr({info:n.info,parts:n.parts},fy(e,c,i));p&&(o.summary=p)}Object.keys(o).length&&(e.ext=Zr(s,{data:o}))}function _k(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 ts(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(yy),s=new Map;for(let b of r){let M=s.get(b.runtime_session_id);M?M.push(b):s.set(b.runtime_session_id,[b])}let o=e.root_id,i=s.has(o),a=new Map,c=b=>a.get(b)??(a.set(b,JSON.stringify(b)),a.get(b)),p=new Map;for(let b of s.keys()){let M=i&&b===o?void 0:_k(r,b,c);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?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,_=$t(r.map(Vo).find(Number.isFinite))??"",y=[];for(let[b,M]of s){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):[],S=[...x,...M],v=new Set(x),C=new Map,j=new Set;for(let N of S){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=S.find(K=>!j.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&&(C.set(N,G),j.add(G))}let w=[];for(let N of S){if(j.has(N))continue;let z=C.get(N),{m:G,lost:K}=yk(N,z,h?m:b,w.length+1,v.has(N),n);if(hk(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),Se=w.find(N=>N.role==="user"&&N.kind==="turn");y.push({...Go,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:Se?.agent??null,title:null,created_at:w[0]?.created_at||_,messages:w,ext:Zr(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{...Go,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!==o&&{ext:Zr(n.h,{data:{root_id:o}})}};function I(b){return r.findIndex(M=>M.runtime_session_id===b.thread_id)}}var Ho={schema:le,v:1},bk=Object.freeze({}),_y=new WeakMap;function ns(e){let t=_y.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=ts({session_id:"",root_id:n,rows:[{runtime_session_id:n,info:r,parts:[e]}]},{live:!0}).threads[0].messages[0].blocks[0];return _y.set(e,{state:e.state,block:o}),o}var zo=new WeakMap;function Yo(e){if(zo.has(e))return zo.get(e);let t={...Ho,thread_id:"",parent_thread_id:null,spawned_by:null,agent:null,title:null,created_at:"",ext:{opencode:{version:Ce}},messages:[{...Ho,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}=es({...Ho,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 zo.set(e,r),r}function se(e){return Yo(e)}var ge=e=>typeof e=="object"&&e!==null&&e.type==="tool_call",Ke=e=>ge(e)?se(e):e;function Sk(e){let t=se(e).state.metadata;return typeof t=="object"&&t!==null&&!Array.isArray(t)&&Object.keys(t).length?t:bk}var Sy=e=>(e.result?.content??[]).flatMap(t=>t.type==="text"?[t.text]:[]).join("");function Pk(e){return e.status==="complete"?"completed":e.status}var by=new WeakMap;function xk(e){if(e.status!=="complete")return"";let t=by.get(e);return t===void 0&&by.set(e,t=Sy(e)),t}function wk(e){return e.status==="error"?e.result?.error?.message||Sy(e):void 0}function he(e){return(e??"").replace(/^oc-/,"").replace(/-/g,"_")}function EN(e){return he(e)==="bash"}function Py(e){let t=he(e);return t==="question"||t==="ask"}function MN(e,t){let n=Math.max(0,e);return`${t?"Running":"Ran"} ${n} command${n===1?"":"s"}`}var kk=new Set(["show","show_user"]);function xy(e){return kk.has(he(e))}function ON(e,t){let n=Math.max(0,e);return`${t?"Writing":"Wrote"} ${n} file${n===1?"":"s"}`}function wy(e){return!!(e.type==="snapshot"||e.type==="patch"||e.type==="step-start"||e.type==="step-finish"||e.type==="text"&&!e.text?.trim()||Jo(e))}function Jo(e){let t=ge(e)?se(e):e,n=he(t.tool);return n!=="show"&&n!=="show_user"||t.state?.status!=="completed"?!1:zr(t.state?.input)}var vk=new Set(["show","show_user","agent_spawn","agent_status","agent_message","agent_task_update","agent_stop"]);function ky(e){return vk.has(he(e))}var Ak=50*1024*1024,Qo="[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",Rk=new RegExp(`^kortix-attachment://(${Qo})/(${Qo})/(${Qo})$`);function Zo(e){if(typeof e!="string")return null;let t=Rk.exec(e);return t?{projectId:t[1],sessionId:t[2],attachmentId:t[3]}:null}function NN(e){return Zo(e)!==null}var Xo=new WeakMap;async function vy(e,t,n,r={}){if(n.size>Ak)throw new Error("Attachments must be 50 MiB or smaller.");let s=`${e}/${t}`,o=r.attachmentId?void 0:Xo.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 c=Xo.get(n)??new Map;c.set(s,i),Xo.set(n,c)}let a=new FormData;return a.append("attachment_id",i.id),a.append("file",n,n.name),i.promise=l.upload(`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/attachments`,a,{signal:r.signal,timeout:12e4,showErrors:!1}).then(u).catch(c=>{throw i.promise=void 0,c}),i.promise}async function Ay(e,t){let n=Zo(e);if(!n)throw new Error("Invalid attachment reference");let r=T().backendUrl.replace(/\/$/,""),s=await L(`${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 Tk=new Set(["show","show_user"]);function Ck(e){let t=[],n=0;for(;;){let r=e.indexOf("<file",n);if(r===-1)return t;let s=r+5;if(s>=e.length||!/\s/.test(e[s])){n=s;continue}let o=e.indexOf(">",s);if(o===-1)return t;let i=e.indexOf("</file>",o+1);if(i===-1)return t;t.push(e.slice(s,o).trimStart()),n=i+7}}var qe=e=>!!e&&typeof e=="object"&&!Array.isArray(e),fn=e=>typeof e=="string"&&e.length>0?e:null,Ry=e=>typeof e=="string"?fn(e.split("/").pop()):null;function rs(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 Ik(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 Ek(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 Mk(e,t){for(let n of Ck(e))t(rs(n,"attachment"),rs(n,"filename")??Ry(rs(n,"path")),rs(n,"mime"))}function Ok(e,t){for(let n of[e,...Ik(e.items)])qe(n)&&t(n.attachment,Ry(n.path),null)}function BN(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let r of e){let s=qe(r)&&Array.isArray(r.blocks)?Ek(r):r;if(!qe(s)||!qe(s.info)||!Array.isArray(s.parts))continue;let o=fn(s.info.id);if(!o)continue;let i=fn(s.info.role)??"unknown",a=(c,p,d)=>{let g=Zo(c);!g||n.has(c)||(n.add(c),t.push({url:c,attachment_id:g.attachmentId,filename:p,mime:d,message_id:o,role:i}))};for(let c of s.parts)qe(c)&&(c.type==="file"?a(c.url,fn(c.filename),fn(c.mime)):c.type==="text"&&typeof c.text=="string"?Mk(c.text,a):c.type==="tool"&&typeof c.tool=="string"&&Tk.has(he(c.tool))&&qe(c.state)&&qe(c.state.input)&&Ok(c.state.input,a))}return t}function Dk(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 WN(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 ei(e,t,n){return e!==void 0?e:Dk(et(t),n)}var Ty={get disableMobileAdvertising(){return ei(T().featureFlags?.disableMobileAdvertising,"NEXT_PUBLIC_DISABLE_MOBILE_ADVERTISING",!1)},get enableDinoGame(){return ei(T().featureFlags?.enableDinoGame,"NEXT_PUBLIC_ENABLE_DINO_GAME",!1)},get enableProjects(){return ei(T().featureFlags?.enableProjects,"NEXT_PUBLIC_ENABLE_PROJECTS",!1)},get enableAutoModel(){return!1}};var jk=new Set(["project-manager"]);function ti(e){return e.native===!0||e.mode==="subagent"||e.hidden||e.enabled===!1?!1:Ty.enableProjects||!jk.has(e.name)}function zN(e){let t=e.agents.filter(ti),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 Cy(){return{projects:{list:Rt,listForAccount:Ic,get:Tt,detail:fr,create:Dc,createRepo:jc,provision:Lc,update:_r,archive:br,llmCatalog:yr,modelPicker:hr,modelAccess:Vr,setModelAccess:Hr,sandboxHealth:xr,sandboxTemplates:Cu,sessions:Dt,createSession:jt},github:{linkRepository:Kc,replaceProjectRepository:qc,getInstallation:Gc,listInstallations:Wc,listLinkableInstallations:Vc,listRepositories:Hc,listRepositoryBranches:zc,linkInstallation:Jc,saveInstallation:Yc,deleteInstallation:Xc,storeUserToken:Qc},gitBackend:{get:Zc,repositories:el},connectStatus:Pu,marketplace:{items:o=>of(o),item:o=>lf(o),itemFile:(o,i)=>uf(o,i),marketplaces:()=>af(),featured:()=>cf(),sources:{list:()=>pf(),add:o=>df(o),remove:o=>gf(o)}}}}function Iy(){return{billing:{accountState:Nd,accountStateMinimal:Bd,transactions:Kd,transactionsSummary:qd,creditBreakdown:Gd,usageHistory:Wd,usageRollup:cg,sessionCosts:{list:ug,get:Kr},tierConfigurations:Vd,setPlan:og,previewPlan:sg,acceptEnterpriseOffer:ig,contactSales:ag,checkout:{createSession:n=>Hd(n),confirmSession:(n,r)=>zd(n,r)},subscription:{createPortalSession:(n,r)=>Yd(n,r),cancel:(n,r)=>Jd(n,r),reactivate:n=>Qd(n),scheduleDowngrade:(n,r,s)=>Xd(n,r,s),cancelScheduledChange:n=>Zd(n),prorationPreview:(n,r)=>eg(n,r)},credits:{purchase:n=>tg(n),autoTopupSettings:n=>ng(n),configureAutoTopup:n=>rg(n)}},sandboxShares:{list:Em,create:Mm,revoke:Om}}}var yn=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??T().fetch??((p,d)=>fetch(p,d)),s=ue(n?.backendUrl??T().backendUrl??"");if(!s)throw new yn("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(()=>""),c=null;try{c=a?JSON.parse(a):null}catch{c=a}if(!i.ok){let p=c&&typeof c=="object"?c:{};throw new yn(typeof p.error=="string"?p.error:"auth_error",typeof p.error_description=="string"&&p.error_description?p.error_description:typeof p.error=="string"?p.error:i.statusText||`HTTP ${i.status}`,i.status)}return c}function ni(e,t){return oe("/auth/signup",{body:e},t)}function ri(e,t){return oe("/auth/sign-in/password",{body:e},t)}function si(e,t){return oe("/auth/sign-in/magic-link",{body:e},t)}function oi(e,t){return oe("/auth/verify-otp",{body:e},t)}function ii(e,t){return oe("/auth/sign-in/oauth",{body:e},t)}function ai(e,t){return oe("/auth/oauth/exchange",{body:e},t)}function hn(e,t){return oe("/auth/refresh",{body:e},t)}function ci(e,t){return oe("/auth/password/reset",{body:e},t)}function li(e,t,n){return oe("/auth/password/update",{body:e,bearer:t},n)}function ui(e,t){return oe("/auth/user",{bearer:e},t)}function pi(e,t,n){return oe("/auth/user",{method:"PATCH",body:e,bearer:t},n)}function di(e,t){return oe("/auth/sign-in/sso",{body:e},t)}var gi={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 mi(e,t={},n){return oe("/auth/sign-out",{body:t,bearer:e},n)}function fi(e={}){let t=e.refreshSkewSeconds??60,n=e.now??(()=>Date.now()),r=null,s=null,o=!e.storage,i=null,a=null,c=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:s})):await e.storage.remove());for(let y of[...p])try{y(r)}catch{}try{e.onChange?.(r)}catch{}}async function f(){if(o)return r;if(!i){let y=c,k=(async()=>{let R=await e.storage.get();if(y===c&&R)try{let I=JSON.parse(R);I.session?.access_token&&I.session?.refresh_token&&(r=I.session,s=I.user??null)}catch{r=null}return o=!0,r})();i=k,k.then(()=>{i===k&&(i=null)},()=>{i===k&&(i=null)})}return i}async function _(){if(await f(),!r)return null;if(!a){let y=r.refresh_token,k=c,R=hn({refresh_token:y},e.request).then(async I=>(k!==c||(r=I.session,I.user&&(s=I.user),await m()),r)).catch(async I=>{if(k!==c)return r;let b=I&&typeof I=="object"&&"status"in I?I.status:0;if(b>=400&&b<500)return r=null,s=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:()=>s,load:f,async set(y,k){await f(),c+=1,a=null,r=y,k!==void 0&&(s=k),y||(s=null),await m()},async getToken(){return await f(),r?g(r)?(await _().catch(()=>r))?.access_token??null:r.access_token:null},refresh:_,async clear(){c+=1,a=null,r=null,s=null,o=!0,await m()}}}function Ey(){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:Km,create:qm,revoke:Gm},connectedApps:{list:Wm,revoke:Vm},audit:{log:Jm,export:Xm,webhooks:{list:Zm,create:ef,update:tf,remove:nf}}}}function My(){return{assignments:{list:Sm,create:Pm,revoke:xm},permissions:{list:wm,forRole:im},roles:{list:rm,create:cm,update:lm,setPermissions:um,remove:pm,usage:am},groups:{list:Yg,get:Jg,create:Qg,update:Xg,remove:Zg,members:{list:em,add:tm,remove:nm}},agentIdentities:sm,oauthClients:{list:mm,get:fm,create:ym,update:hm,rotateSecret:_m,remove:bm},can:dm,canBatch:gm}}function Oy(){let e={signUp:ni,signInWithPassword:ri,sendMagicLink:si,verifyOtp:oi,signInWithProvider:ii,exchangeCode:ai,refresh:hn,resetPassword:ci,updatePassword:li,updateUserMetadata:pi,signInWithSso:di,mfa:gi,user:ui,signOut:mi,session:fi},t=Ey(),n=My();return{auth:e,accounts:t,iam:n,accountInvites:{listMine:Pc,describe:xc,accept:oo,acceptAndLand:wc,decline:kc}}}var _n=new Map,yi=new Map;function hi(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function Dy(e){return _n.get(hi(e))??null}function jy(){return[..._n.values()].filter(e=>typeof e=="string")}function Ly(e){return _n.has(hi(e))}async function mt(e){let t=hi(e),n=_n.get(t);if(n!==void 0)return n;let r=yi.get(t);if(r)return r;let s=(async()=>{try{let o=await l.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 _n.set(t,i),i}catch{return null}finally{yi.delete(t)}})();return yi.set(t,s),s}function $y(e){let{apiBaseUrl:t}=e;return Ly(t)||mt(t).catch(()=>{}),{sandboxId:e.sandboxId,backendPort:e.backendPort,apiBaseUrl:t,previewUrlTemplate:Dy(t)}}function Uy(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=T().backendUrl??e.backendUrl,o=80,i=t(s);return i&&(o=i.port?Number(i.port):i.protocol==="https:"?443:80),$y({sandboxId:r,apiBaseUrl:s,backendPort:o})}}function Fy(e,t){let n=null;async function r(){n||(n=Ir(e,t,{showErrors:!1}).then(s=>{let o=Lr(s)??"",i=o.indexOf("/"),a=i>0&&i<o.length-1?{providerID:o.slice(0,i),modelID:o.slice(i+1)}:void 0,c=s.agent_name?.trim()||void 0;return{model:a,agent:c}}));try{return await n}catch(s){throw n=null,s}}return{persistedPromptDefaults:r,clearPersistedDefaults:()=>{n=null}}}var Ft={url:null,sandboxId:null,dbSandboxId:null,version:0},$k=new Set;function ss(e,t=null,n=null){if(!(Ft.url===e&&Ft.sandboxId===t&&Ft.dbSandboxId===n)){Ft={url:e,sandboxId:t,dbSandboxId:n,version:Ft.version+1};for(let r of $k)r()}}function Ny(){return Ft.url}var bn=new Map;function By(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 Nt=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 Ky(e,t){async function n(r){let s=Date.now()+r,o=()=>Math.max(0,s-Date.now()),i=await gt(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 gt(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(By(i),{code:"RUNTIME_UNAVAILABLE"});let c=i.sandbox.external_id;if(!c)throw new P("Session sandbox has no external_id \u2014 cannot resolve its runtime URL",{code:"RUNTIME_UNAVAILABLE"});let p=Fe(c);return ss(p,c),{runtimeSessionId:a,opencodeSessionId:a,runtimeUrl:p,sandboxId:c}}return n}function qy(e,t,n){let r=null;function s(){if(r)return r;let p=wd(e,t);return p&&(r=p),r}let o=Ky(e,t);async function i(p){let d=s();if(d)return d;let g=p?.readyTimeoutMs??18e4,m=mt(T().backendUrl??n.backendUrl).catch(()=>null),f=p?.session?.session_id===t?Ad(p.session):null,_=f?.sandbox?.external_id,y=f?.runtime_session_id;if(_&&y){let b=Fe(_);return ss(b,_),r={runtimeSessionId:y,opencodeSessionId:y,runtimeUrl:b,sandboxId:_},$r(e,t,r),await m,r}let k=`${e}
|
|
15
|
+
${t}`,R=bn.get(k);if(R)return r=await R,await m,r;let I=o(g);bn.set(k,I);try{return r=await I,await m,r}finally{bn.get(k)===I&&bn.delete(k)}}function a(p){let d=s();if(!d)throw new Nt(p);return d}function c(){r=null,kd(e,t)}return{ensureReady:i,tryResolveReady:s,requireReady:a,forgetReady:c}}var q=["directory","workspace"],Gy=["messageID","model","agent","noReply","tools","format","system","variant","parts"],E=(e,t,n=q,r=[],s)=>({method:e,path:t,query:n,body:r,bodyParam:s}),Uk={"session.list":E("GET","/session",[...q,"scope","path","roots","start","search","limit"]),"session.get":E("GET","/session/{sessionID}"),"session.create":E("POST","/session",q,["parentID","title","agent","model","metadata","permission","workspaceID"]),"session.delete":E("DELETE","/session/{sessionID}"),"session.update":E("PATCH","/session/{sessionID}",q,["title","metadata","permission","time"]),"session.status":E("GET","/session/status"),"session.messages":E("GET","/session/{sessionID}/message",[...q,"limit","before"]),"session.prompt":E("POST","/session/{sessionID}/message",q,Gy),"session.promptAsync":E("POST","/session/{sessionID}/prompt_async",q,Gy),"session.abort":E("POST","/session/{sessionID}/abort"),"session.revert":E("POST","/session/{sessionID}/revert",q,["messageID","partID"]),"session.unrevert":E("POST","/session/{sessionID}/unrevert"),"session.summarize":E("POST","/session/{sessionID}/summarize",q,["providerID","modelID","auto"]),"session.command":E("POST","/session/{sessionID}/command",q,["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",q,["messageID"]),"session.diff":E("GET","/session/{sessionID}/diff",[...q,"messageID"]),"session.todo":E("GET","/session/{sessionID}/todo"),"permission.list":E("GET","/permission"),"permission.reply":E("POST","/permission/{requestID}/reply",q,["reply","message"]),"question.list":E("GET","/question"),"question.reply":E("POST","/question/{requestID}/reply",q,["answers"]),"question.reject":E("POST","/question/{requestID}/reject"),"part.update":E("PATCH","/session/{sessionID}/message/{messageID}/part/{partID}",q,[],"part"),"part.delete":E("DELETE","/session/{sessionID}/message/{messageID}/part/{partID}"),"file.list":E("GET","/file",[...q,"path"]),"file.read":E("GET","/file/content",[...q,"path"]),"find.files":E("GET","/find/file",[...q,"query","dirs","type","limit"]),"vcs.diff":E("GET","/vcs/diff",[...q,"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",q,["method","inputs"]),"provider.oauth.callback":E("POST","/provider/{providerID}/oauth/callback",q,["method","code"]),"auth.set":E("PUT","/auth/{providerID}",[],[],"auth"),"app.agents":E("GET","/agent"),"app.skills":E("GET","/skill"),"app.log":E("POST","/log",q,["service","level","message","extra"]),"command.list":E("GET","/command"),"tool.ids":E("GET","/experimental/tool/ids"),"tool.list":E("GET","/experimental/tool",[...q,"provider","model"]),"mcp.status":E("GET","/mcp"),"mcp.add":E("POST","/mcp",q,["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",q,["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 Fk(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 Nk(e,t,n={},r={}){let s=Uk[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 c=new Headers(r.headers);return a&&c.set("Content-Type","application/json"),new Request(`${e.replace(/\/$/,"")}${o}${Fk(s,n)}`,{method:s.method,headers:c,redirect:"follow",...a?{body:JSON.stringify(i)}:{},...r.signal?{signal:r.signal}:{}})}function Bk(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 Kk(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=Bk(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 _i(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:c,value:p}=await o.read();if(c)break;a=(a+p).replace(/\r\n/g,`
|
|
16
16
|
`).replace(/\r/g,`
|
|
17
17
|
`);let d=a.split(`
|
|
18
18
|
|
|
19
19
|
`);a=d.pop()??"";for(let g of d){let m={},f=[];for(let _ of g.split(`
|
|
20
20
|
`))if(_.startsWith("data:"))f.push(_.replace(/^data:\s*/,""));else if(_.startsWith("id:"))m.id=_.replace(/^id:\s*/,"");else if(_.startsWith("retry:")){let y=Number.parseInt(_.replace(/^retry:\s*/,""),10);Number.isNaN(y)||(m.retry=y)}f.length&&(m.data=f.join(`
|
|
21
|
-
`)),yield m}}}finally{r.removeEventListener("abort",i),o.releaseLock()}}}async function*Mk(e,t,n){let r=e.eventTransport??fi(e.fetch??globalThis.fetch),s=n.signal??new AbortController().signal,o=n.sseDefaultRetryDelay??3e3,i;for(let a=1;!s.aborted;a++)try{let c=new Headers(n.headers);i!==void 0&&c.set("Last-Event-ID",i);for await(let p of r({url:new URL(t).href,headers:c,signal: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(c){if(n.onSseError?.(c),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 hn(e){let t=s=>(o,i)=>Ek(e,Tk(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:Mk(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 Ny=200;async function Ok(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 ft(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 x(`${t}: ${r}`,{...e.response?{status:e.response.status,response:e.response}:{}})}function Ky(e){let t=e.runtimeUrl.replace(/\/$/,""),n=hn({baseUrl:t,fetch:e.fetch});return{messages:async(r={})=>{let s=encodeURIComponent(r.conversationId??e.rootId),o=async(c,p)=>{let d=new URLSearchParams;c!==void 0&&d.set("limit",String(c)),p&&d.set("before",p);let g=`/messages/${s}${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 x(`Reading the session transcript failed: ${await Ok(f)}`,{status:f.status,response:f});let _=await f.json();return{messages:_.messages??[],hasMore:_.has_more===!0}},i=await o(r.limit===void 0?void 0:Math.min(r.limit,Ny),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,Ny),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=>ft(i,"Reading the session status failed")),n.permission.list().then(i=>ft(i,"Reading permission requests failed")),n.question.list().then(i=>ft(i,"Reading questions failed"))]);return{statuses:r??{},permissions:s??[],questions:o??[]}},answerPermission:async(r,s,o)=>{ft(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){ft(await n.question.reject({requestID:r}),"Dismissing the question failed");return}ft(await n.question.reply({requestID:r,answers:s}),"Answering the question failed")},compact:async r=>{let s=r;if(!s){let o=await n.global.config.get().then(c=>c.error===void 0?c.data:null),i=typeof o?.model=="string"?o.model:"",a=i.indexOf("/");a>0&&a<i.length-1&&(s={providerID:i.slice(0,a),modelID:i.slice(a+1)})}if(!s)throw new x("Cannot compact: no model is set for this session",{code:"MODEL_REQUIRED"});return ft(await n.session.summarize({sessionID:e.rootId,providerID:s.providerID,modelID:s.modelID}),"Compacting the session failed"),s}}}function By(e){async function t(){let{runtimeSessionId:n,runtimeUrl:r}=await e.ensureReady();return Ky({runtimeUrl:r,rootId:n,fetch:L})}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 qy(e){return{setModel:t=>{e.model=t},changeModel:async t=>{let n=await rd(e.projectId,e.sessionId,t);return e.clearPersistedDefaults(),n}}}var _n=BigInt(4096),nt=BigInt(0xffffffffffff),Gy=nt+BigInt(1),Dk=Gy/BigInt(2),yt=BigInt(3600*1e3)*_n,yi=120*1e3,jk=/^msg_[0-9a-f]{12}[A-Za-z0-9]{14}$/,Lk=/^msg_([0-9a-f]{12})/,Wy="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";function Ft(e){let t=Lk.exec(e??"");return t?BigInt(`0x${t[1]}`):null}function bn(e){return BigInt(Math.trunc(e))*_n&nt}function Nt(e,t){let n=e-t&nt;return n>=Dk&&(n-=Gy),n}function Vy(e){let t=null;for(let n of e)n!=null&&(t===null||Nt(n,t)>BigInt(0))&&(t=n);return t}function $k(e,t){let n=Ft(e);return n===null?!1:Nt(n,bn(t))>yt}function Uk(e,t){let n=t===void 0?null:bn(t);return Hy(e,r=>n===null||Nt(r,n)<=yt)}function Hy(e,t){let n=[];for(let r of e){let s=Ft(r);s!==null&&t(s)&&n.push(s)}return Vy(n)}function Fk(){let e="",t=new Uint8Array(32);for(;e.length<14;){crypto.getRandomValues(t);for(let n of t)n<248&&e.length<14&&(e+=Wy[n%62])}return e}function zy(e){let t=e.random,n=bn(e.nowMs-(e.backdateMs??yi)),r=e.newestKnownTime??null;if(r!==null){let o=Nt(r,n);o>=BigInt(0)&&o<=yt&&(n=r+BigInt(1)&nt)}let s="";if(t)for(let o=0;o<14;o++)s+=Wy[Math.min(61,Math.floor(t()*62))];else s=Fk();return{id:`msg_${n.toString(16).padStart(12,"0")}${s}`,time:n}}function hi(e={}){let t=e.nowMs??Date.now(),n=bn(t-yi),r=Hy(e.after??[],s=>{let o=Nt(s,n);return o>=BigInt(0)&&o<=yt});return zy({nowMs:t,newestKnownTime:r}).id}function Yy(e){return{scope:()=>td(e.projectId,e.sessionId),providerSecretPool:{list:()=>Fl(e.projectId,e.sessionId),get:t=>Ul(e.projectId,e.sessionId,t),set:(t,n)=>Nl(e.projectId,e.sessionId,t,n)},rescope:t=>nd(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,c=hi(),p=await Mr(e.projectId,e.sessionId,{clientMessageId:c,messageId:c,remintOnDelivery:!0,parts:[{type:"text",text:t}],clientSentAtMs:Date.now(),...i||a?{overrides:{...i?{model:i}:{},...a?{agent:a}:{}}}:{}});if(p.state==="failed")throw new x("This prompt was refused: its earlier delivery already failed.",{code:"PROMPT_FAILED"});return p}}}var Jy=async function*(e){let t=I().eventStreamTransport;if(!t){yield*fi(((s,o)=>L(s,o,{timeoutMs:null})))(e);return}let{headers:n,rejected:r}=await ur(e.url,e.headers);try{yield*t({...e,headers:n})}catch(s){throw s?.status===401&&r(),s}};function qe(){let e=jy();return e||(I().billingEnabled??!1?"":Sd())}async function _i(e,t){return(await e.json().catch(()=>({})))?.error||e.statusText||t}function bi(e){if(!e)throw new Error("[kortix-runtime] Server URL not ready \u2014 sandbox is still loading");return e}async function Qy(e){let t=bi(e),n=await L(`${t}/env`);if(!n.ok)throw new Error(await _i(n,"Failed to load secrets"));return(await n.json()).secrets??{}}async function Xy(e,t,n){let r=bi(e),s=await L(`${r}/env/${encodeURIComponent(t)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({value:n})});if(!s.ok)throw new Error(await _i(s,"Failed to save secret"))}async function Zy(e,t){let n=bi(e),r=await L(`${n}/env/${encodeURIComponent(t)}`,{method:"DELETE"});if(!r.ok)throw new Error(await _i(r,"Failed to delete secret"))}var Nk={list:Qy,set:Xy,delete:Zy};async function Kk(e,t,n){let r=e;for(;r.endsWith("/");)r=r.slice(0,-1);let s=await L(`${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 ss(e,t){let n=await e.json().catch(()=>({}));return n?.error||n?.message||e.statusText||t}function Pn(e){if(!e)throw new Error("[kortix-pty] Server URL not ready \u2014 sandbox is still loading");return pe(e)}async function eh(e){let t=Pn(e),n=await L(`${t}/kortix/pty`);if(!n.ok)throw new Error(await ss(n,"Failed to list terminals"));return n.json()}async function th(e,t){let n=Pn(e),r=await L(`${n}/kortix/pty`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t??{})});if(!r.ok)throw new Error(await ss(r,"Failed to create terminal"));return r.json()}async function nh(e,t,n){let r=Pn(e),s=await L(`${r}/kortix/pty/${encodeURIComponent(t)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!s.ok)throw new Error(await ss(s,"Failed to update terminal"));return s.json()}async function rh(e,t){let n=Pn(e),r=await L(`${n}/kortix/pty/${encodeURIComponent(t)}`,{method:"DELETE"});if(!r.ok)throw new Error(await ss(r,"Failed to remove terminal"))}async function sh(e,t,n){let r=Pn(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 tn();a&&i.set("token",a),n?.wake&&i.set("wake","1");let c=i.toString();return c?`${o}${o.includes("?")?"&":"?"}${c}`:o}function Bk(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 rt="\x1B",oh="\x07",qk="\0",Pi=`(?:${oh}|${rt}\\\\)`,Gk=[new RegExp(`${rt}\\]697;[^${oh}${rt}]*${Pi}`,"g"),new RegExp(`${qk}?\\{"cursor":\\d+\\}`,"g"),new RegExp(`${rt}\\][0-9]+;rgb:[0-9a-fA-F/]+${Pi}`,"g"),new RegExp(`${rt}\\]4;[0-9]+;rgb:[0-9a-fA-F/]+${Pi}`,"g"),new RegExp(`${rt}\\[\\??[0-9;]*\\$y`,"g"),new RegExp(`${rt}\\[\\d+;\\d+R`,"g"),new RegExp(`${rt}\\[\\?[0-9;]*c`,"g")];function Wk(e){let t=e;for(let n of Gk)t=t.replace(n,"");return t}var Vk={list:eh,create:th,update:nh,remove:rh,webSocketUrl:sh};async function O(e,t,n,r){let s=e;for(;s.endsWith("/");)s=s.slice(0,-1);let o=await L(`${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 qK(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 GK(e,t){return O(e,`/kortix/tasks/${encodeURIComponent(t)}`)}async function WK(e,t){return O(e,`/kortix/tasks/${encodeURIComponent(t)}/events`)}async function VK(e,t){return O(e,`/kortix/tasks/${encodeURIComponent(t)}/status`)}async function HK(e,t){return O(e,"/kortix/tasks",{method:"POST",body:JSON.stringify(t)})}async function zK(e,t,n){return O(e,`/kortix/tasks/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}async function YK(e,t){return O(e,`/kortix/tasks/${encodeURIComponent(t)}/start`,{method:"POST"})}async function JK(e,t){return O(e,`/kortix/tasks/${encodeURIComponent(t)}/approve`,{method:"POST"})}async function QK(e,t){return O(e,`/kortix/tasks/${encodeURIComponent(t)}`,{method:"DELETE"})}async function XK(e,t){let n=t?`?project_id=${encodeURIComponent(t)}`:"";return O(e,`/kortix/tickets${n}`)}async function ZK(e,t){return O(e,`/kortix/tickets/${encodeURIComponent(t)}`)}async function eB(e,t){return O(e,`/kortix/tickets/${encodeURIComponent(t)}/events`)}async function tB(e,t){return O(e,"/kortix/tickets",{method:"POST",body:JSON.stringify(t)})}async function nB(e,t,n){return O(e,`/kortix/tickets/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}async function rB(e,t,n){return O(e,`/kortix/tickets/${encodeURIComponent(t)}/status`,{method:"POST",body:JSON.stringify(n)})}async function sB(e,t,n){return O(e,`/kortix/tickets/${encodeURIComponent(t)}/assign`,{method:"POST",body:JSON.stringify(n)})}async function oB(e,t,n){return O(e,`/kortix/tickets/${encodeURIComponent(t)}/unassign`,{method:"POST",body:JSON.stringify(n)})}async function iB(e,t,n){return O(e,`/kortix/tickets/${encodeURIComponent(t)}/comments`,{method:"POST",body:JSON.stringify(n)})}async function aB(e,t){return O(e,`/kortix/tickets/${encodeURIComponent(t)}`,{method:"DELETE"})}async function cB(e,t){return O(e,`/kortix/projects/${encodeURIComponent(t)}/columns`)}async function lB(e,t,n){return O(e,`/kortix/projects/${encodeURIComponent(t)}/columns`,{method:"PUT",body:JSON.stringify({columns:n})})}async function uB(e,t){return O(e,`/kortix/projects/${encodeURIComponent(t)}/fields`)}async function pB(e,t,n){return O(e,`/kortix/projects/${encodeURIComponent(t)}/fields`,{method:"PUT",body:JSON.stringify({fields:n})})}async function dB(e,t){return O(e,`/kortix/projects/${encodeURIComponent(t)}/templates`)}async function gB(e,t,n){return O(e,`/kortix/projects/${encodeURIComponent(t)}/templates`,{method:"PUT",body:JSON.stringify({templates:n})})}async function mB(e,t){return O(e,`/kortix/projects/${encodeURIComponent(t)}/pm-session`,{method:"POST"})}async function fB(e,t){return O(e,`/kortix/projects/${encodeURIComponent(t)}/agents`)}async function yB(e,t,n){return O(e,`/kortix/projects/${encodeURIComponent(t)}/agents`,{method:"POST",body:JSON.stringify(n)})}async function hB(e,t,n,r){return O(e,`/kortix/projects/${encodeURIComponent(t)}/agents/${encodeURIComponent(n)}`,{method:"PATCH",body:JSON.stringify(r)})}async function _B(e,t,n){return O(e,`/kortix/projects/${encodeURIComponent(t)}/agents/${encodeURIComponent(n)}`,{method:"DELETE"})}async function bB(e,t,n){return O(e,`/kortix/projects/${encodeURIComponent(t)}/agents/${encodeURIComponent(n)}/persona`)}async function PB(e,t,n=200){return O(e,`/kortix/projects/${encodeURIComponent(t)}/activity?limit=${n}`)}async function SB(e){return O(e,"/kortix/projects")}async function xB(e,t){return O(e,`/kortix/projects/${encodeURIComponent(t)}`)}async function wB(e,t){return O(e,`/kortix/projects/by-session/${encodeURIComponent(t)}`)}async function kB(e,t){return O(e,`/kortix/projects/${encodeURIComponent(t)}/sessions`)}async function vB(e,t){return O(e,`/kortix/projects/${encodeURIComponent(t)}`,{method:"DELETE"})}async function AB(e,t,n){return O(e,`/kortix/projects/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}async function RB(e,t,n="all"){return O(e,`/kortix/projects/${encodeURIComponent(t)}/milestones?status=${n}`)}async function CB(e,t,n){return O(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}`)}async function TB(e,t,n){return O(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}/events`)}async function IB(e,t,n){return O(e,`/kortix/projects/${encodeURIComponent(t)}/milestones`,{method:"POST",body:JSON.stringify(n)})}async function EB(e,t,n,r){return O(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}`,{method:"PATCH",body:JSON.stringify(r)})}async function MB(e,t,n,r){return O(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}/close`,{method:"POST",body:JSON.stringify(r)})}async function OB(e,t,n){return O(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}/reopen`,{method:"POST"})}async function DB(e,t,n){return O(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}`,{method:"DELETE"})}async function jB(e,t){return O(e,`/kortix/projects/${encodeURIComponent(t)}/credentials`)}async function LB(e,t,n){return O(e,`/kortix/projects/${encodeURIComponent(t)}/credentials/${encodeURIComponent(n)}/events`)}async function $B(e,t,n){return O(e,`/kortix/projects/${encodeURIComponent(t)}/credentials`,{method:"POST",body:JSON.stringify(n)})}async function UB(e,t,n){return O(e,`/kortix/projects/${encodeURIComponent(t)}/credentials/${encodeURIComponent(n)}`)}async function FB(e,t,n){return O(e,`/kortix/projects/${encodeURIComponent(t)}/credentials/${encodeURIComponent(n)}`,{method:"DELETE"})}var Hk=1e4,zk={retryOnAuthError:!1};function Kt(e,t,n){return O(e,t,{signal:AbortSignal.timeout(Hk),...n},zk)}async function NB(e,t=!1){return(await Kt(e,`/kortix/services${t?"?all=true":""}`)).services??[]}async function KB(e){return(await Kt(e,"/kortix/services/templates")).templates??[]}async function BB(e,t){return(await Kt(e,`/kortix/services/${encodeURIComponent(t)}/logs`)).logs??[]}async function qB(e,t,n){let r=n==="delete",s=r?`/kortix/services/${encodeURIComponent(t)}`:`/kortix/services/${encodeURIComponent(t)}/${n}`;return Kt(e,s,{method:r?"DELETE":"POST"})}async function GB(e,t){return Kt(e,`/kortix/services/reconcile${t?"?reload=true":""}`,{method:"POST"})}async function WB(e,t){return Kt(e,"/kortix/services/register",{method:"POST",body:JSON.stringify(t)})}var Ge=new Map,Yk=256,Sn=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=qe();if(!e)throw new Sn;return We(e)}function We(e){if(!e)throw new Error("[kortix-runtime] getClientForUrl called without a url");let t=Ge.get(e);if(t)return Ge.delete(e),Ge.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=hn({baseUrl:e,fetch:L,eventTransport:Jy});return Ge.set(e,n),Ge.size>Yk&&Ge.delete(Ge.keys().next().value),n}function ZB(e){Ge.delete(e)}function eq(){Ge.clear()}var os=new Map;function tq(e){if(!e)throw new Error("[kortix-runtime] getPublicClientForUrl called without a url");let t=os.get(e);if(t)return t;let n=hn({baseUrl:e,fetch});return os.set(e,n),n}function nq(e){os.delete(e)}function rq(){os.clear()}async function Jk(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 sq(e){let t=qe();if(!t)throw new x("[kortix-runtime] Server URL not ready \u2014 sandbox is still loading",{code:"RUNTIME_UNAVAILABLE"});let n=e==="full"?"/kortix/refresh":"/global/dispose",r=await L(`${t}${n}`,{method:"POST"}),s=r.headers.get("content-type")??"",o=/^application\/([\w.+-]+\+)?json\b/i.test(s.trim());if(!r.ok)throw new x(`System reload failed (${r.status}): ${await Jk(r)}`,{status:r.status,response:r,code:"RUNTIME_UNAVAILABLE"});if(!o)throw new x(`System reload endpoint is unavailable on this sandbox (${n})`,{status:r.status,response:r,code:"RUNTIME_UNAVAILABLE"});let i;try{i=await r.json()}catch(c){throw new x(`System reload returned malformed JSON from ${n}: ${c instanceof Error?c.message:String(c)}`,{status:r.status,response:r,code:"RUNTIME_UNAVAILABLE"})}let a=i===!0||typeof i=="object"&&i!==null&&i.ok===!0;return{success:a,mode:e,steps:a?[e==="full"?"refreshed workspace and restarted runtime":"reloaded config in place"]:[],errors:a?[]:[`the sandbox did not confirm the reload (${n})`]}}var ih="frontend";function is(e,t,n){(e==="error"?console.error:e==="warn"?console.warn:e==="debug"?console.debug:console.log)(`[${ih}] ${t}`,...n?[n]:[]);try{ht().app.log({service:ih,level:e,message:t,extra:n})}catch{}}var Ve={debug:(e,t)=>is("debug",e,t),info:(e,t)=>is("info",e,t),warn:(e,t)=>is("warn",e,t),error:(e,t)=>is("error",e,t)};var Qk=16,Xk=8,ah=6e4,Zk=250,ev=1e3,tv=3e4,nv=5,rv=.5,sv=3e3,ov=3e4,ch=2e4,iv=2e3,lh=8;function av(e){if(e.type==="session.status")return`session.status:${e.properties.sessionID}`;if(e.type==="lsp.updated")return"lsp.updated"}function cv(e,t){if(e?.type!=="message.part.delta"||t.type!=="message.part.delta")return;let n=e.properties,r=t.properties;if(n.partID!==r.partID||n.field!==r.field||n.messageID!==r.messageID||n.sessionID!==r.sessionID)return;let s=e.coalesced??[e];return s.push(t),{...t,properties:{...r,delta:n.delta+r.delta},coalesced:s}}function uh(e,t){let n=[],r,s=0,o=new Map,i=()=>{if(r&&e.clearTimeout(r),r=void 0,n.length===0)return;let c=n;n=[],o.clear(),s=e.now();for(let p of c)p&&t(p.event)},a=()=>{if(r)return;let c=e.now()-s;r=e.setTimeout(i,Math.max(0,Qk-c))};return{push(c){let p=cv(n[n.length-1]?.event,c);if(p)n[n.length-1]={type:p.type,event:p};else{let d=av(c);if(d){let g=o.get(d);g!==void 0&&(n[g]=void 0),o.set(d,n.length)}n.push({type:c.type,event:c})}a()},flush:i,clearTimer:()=>{r&&e.clearTimeout(r)}}}function ph(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 Si(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 lv(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:sv,sseMaxRetryDelay:ov,sseMaxRetryAttempts:1}).then(c=>{i||(i=!0,t.clearTimeout(a),s(c))},c=>{i||(i=!0,t.clearTimeout(a),o(c))})})}async function uv(e,t,n,r,s){let o=!1,i=t.now(),a=e[Symbol.asyncIterator]();for(;!n.aborted;){let c=a.next().then(f=>({kind:"next",result:f}),f=>({kind:"error",error:f})),p=ph(n),d=await Promise.race([c,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<Xk)&&(await new Promise(f=>t.setTimeout(f,0)),i=t.now()))}return o}function dh(e,t,n){let r=t?.cause?.status;return!e&&(typeof r=="number"&&r>=400||n<iv)}function gh(e,t,n){Ve.error("SSE event stream parked \u2014 giving up after consecutive hard failures",{consecutiveFailures:t,lastError:String(n)}),Si(e,r=>r.onParked,{consecutiveFailures:t,lastError:n})}function mh(e,t,n){let r=t?Zk:Math.min(ev*2**Math.min(e-1,nv),tv);return Math.round(r*(1+rv*(n.random?.()??0)))}function fh(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 yh(e){let{client:t,t:n,connectTimeoutMs:r,heartbeatTimeoutMs:s,outerSignal:o,retryCount:i,setConnectionState:a,onConnected:c,coalescer:p}=e,d=!1,g=!1,m,f=null,_=new AbortController;a("connecting");let y=ph(o);y.promise.then(()=>_.abort());try{let{stream:v}=await lv(t,n,r,_);c();let R=()=>{n.clearTimeout(m),m=n.setTimeout(()=>{Ve.warn("SSE heartbeat timeout, forcing reconnect"),_.abort()},s)};R(),d=await uv(v,n,_.signal,p,()=>{a("open"),R()}),g=d}catch(v){if(f=v,o.aborted)return{streamHadWork:d,stableConnection:g,error:f};let R=String(v),T=Xt(v)||Xt(v?.cause);if(Ve.error("SSE event stream error",{error:R,retryCount:i,isAuthError:T}),T)try{lo(),await co(),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 pv(e){return{type:"heartbeat-gap",gapMs:e}}function dv(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()},mv=5e3,fv=1e4,yv=4,xn=new WeakMap;function hv(e,t,n){let r=t.timers??gv,s=t.connectTimeoutMs??ch,o=t.heartbeatTimeoutMs??ah,i=t.maxConsecutiveHardFailures??lh,a=new AbortController,c=(v,...R)=>Si(n,v,...R),p=null,d=!1,g=v=>{p!==v&&(p=v,v&&c(R=>R.onConnectionChange,v))},m=r.now(),f=null,_=uh(r,v=>{m=r.now(),c(R=>R.onEvent,v)}),y={client:e,t:r,connectTimeoutMs:s,heartbeatTimeoutMs:o,outerSignal:a.signal,setConnectionState:g,onConnected:()=>{if(f){let v=r.now()-f.lastActivityAt,R=f.eventful;f=null,(R||v>mv)&&c(T=>T.onGapRehydrate,v)}m=r.now()},coalescer:_};return(async()=>{let v=0,R=0,T=0;for(;!a.signal.aborted;){let b=r.now(),M=await yh({...y,retryCount:v});if(a.signal.aborted)break;let h=M.error,{streamHadWork:S,stableConnection:P}=M,k=r.now()-b;if(R=dh(S,h,k)?R+1:0,R>=i){gh(n,R,h),p=null,d=!0;break}g("lost"),f={lastActivityAt:m,eventful:(f?.eventful??!1)||S},T=P&&k<fv?T+1:0;let w=P&&T<=yv;w?v=0:(v++,v>1&&Ve.warn("SSE event stream reconnecting",{retryCount:v})),await fh(r,a.signal,mh(v,w,r))}})(),{subscribers:n,connectionState:()=>p,isParked:()=>d,teardown:()=>{p=null,a.abort(),_.clearTimer()}}}function xi(e){let{onEvent:t,onGapRehydrate:n,onParked:r,onConnectionChange:s,signal:o}=e,i=e.client??(e.url?We(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},c=xn.get(i);if(c?.isParked()&&(xn.delete(i),c=void 0),!c)c=hv(i,e,new Set([a])),xn.set(i,c);else{c.subscribers.add(a);let f=c.connectionState();f&&s?.(f)}let p=c,d=!1,g=()=>{d||(d=!0,o&&o.removeEventListener("abort",m),p.subscribers.delete(a),p.subscribers.size===0&&(p.teardown(),xn.get(i)===p&&xn.delete(i)))},m=()=>g();return o&&(o.aborted?g():o.addEventListener("abort",m,{once:!0})),{close:g}}function hh(e){return{abort:async()=>{let{runtimeSessionId:t,runtimeUrl:n}=await e.ensureReady();return We(n).session.abort({sessionID:t})},rewind:async t=>{let{runtimeSessionId:n,runtimeUrl:r}=await e.ensureReady();return We(r).session.revert({sessionID:n,messageID:t})},restoreRewind:async()=>{let{runtimeSessionId:t,runtimeUrl:n}=await e.ensureReady();return We(n).session.unrevert({sessionID:t})},stream:async t=>{let{runtimeUrl:n}=await e.ensureReady();return xi({url:n,onEvent:t.onEvent,onGapRehydrate:t.onGapRehydrate,signal:t.signal})}}}function bh(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 x(n,{status:t?.response?.status??t?.status,response:t?.response,details:t})}return e.data}async function vi(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??qe()).trim();if(!t)throw new Sn;return t}async function Rn(e,t){let n=await L(`${ae(t)}${e}`);if(!n.ok)throw new x(await vi(n),{status:n.status,response:n});return n.json()}async function Ai(e,t,n,r,s){let o=await L(`${ae(s)}${e}`,{method:t,headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!o.ok)throw new x(`${r} failed (${o.status}): ${await vi(o)}`,{status:o.status,response:o});return o.json()}var Ri=["/workspace","/tmp","/home","/opt"],_v=Ri.filter(e=>e!=="/workspace");function Ph(e){return Ri.some(t=>e===t||e.startsWith(`${t}/`))}function Cn(e){return Ph(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(_v.some(n=>t===n||t.startsWith(`${n}/`)))return t;for(;t.startsWith("/");)t=t.slice(1);return t}var Sh=_t;async function Tn(e,t){let n=ae(t),r=_t(e)||".";return(await Rn(`/file?path=${encodeURIComponent(r)}`,n)).map(o=>({...o,path:o.absolute||`/workspace/${o.path}`}))}async function In(e,t){let n=_t(e);return Rn(`/file/content?path=${encodeURIComponent(n)}`,t)}async function bv(e,t,n){let r=ae(n),s=_t(e),o=await L(`${r}/file/raw?path=${encodeURIComponent(s)}`);if(!o.ok)throw new x(await vi(o),{status:o.status,response:o});if((o.headers.get("content-type")||"").includes("text/html"))throw new x("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 Pv=8,as=0,xh=[];async function Sv(){if(as<Pv){as++;return}await new Promise(e=>xh.push(e)),as++}function xv(){as--,xh.shift()?.()}function wv(e,t){let n=ae(t);return Sr(`${n}/file/raw?path=${encodeURIComponent(_t(e))}`)}async function En(e,t){await Sv();try{let n=ae(t);try{return await bv(e,void 0,n)}catch{}let r=await In(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{xv()}}async function cs(e){return Rn("/file/status",ae(e))}async function ls(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)),Rn(`/find/file?${s.toString()}`,r)}async function us(e,t){let n=ae(t);return(await Rn(`/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 wn=[400,1200],kv=e=>e===408||e===429||e===502||e===503||e===504,_h=e=>new Promise(t=>setTimeout(t,e));function vv(e){let t=e?.name;return t==="TimeoutError"||t==="AbortError"}var wi=3e4,wh=15*6e4,Av=256;function kn(e){if(typeof e!="number"||!Number.isFinite(e)||e<=0)return wi;let t=wi+e/Av;return Math.min(wh,Math.max(wi,Math.round(t)))}async function Rv(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 vn(e,t){let n;for(let s=0;s<=wn.length;s++){let o;try{o=await t(e())}catch(a){if(n=a,vv(a)||s===wn.length)break;await _h(wn[s]);continue}if(o.ok)return o.json();let i=await Rv(o);if(n=new x(`Upload failed (${o.status}): ${i}`,{status:o.status,response:o}),!kv(o.status)||s===wn.length)throw n;await _h(wn[s])}if(n instanceof x)throw n;let r=n instanceof Error?n.message:String(n||"request failed");throw new x(`Upload failed: ${r}`)}var ki=8*1024*1024;function Cv(e,t){if(!(typeof e?.size!="number"||!Number.isFinite(t))&&!(e.size>=t))throw new x(`Upload verification failed for ${e.path}: expected ${t} bytes, received ${e.size}`,{code:"UPLOAD_SIZE_MISMATCH"})}function kh(e,t){try{e?.onProgress?.(t)}catch{}}function vh(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 Tv(e){let t=e.lastIndexOf("/");return t<0?{parent:"",name:e}:{parent:e.slice(0,t)||"/",name:e.slice(t+1)}}async function Mn(e,t,n,r,s){let o=typeof r=="string"?r:void 0,i=typeof r=="string"?s:r,a=ae(o),c=kn(e.size),p=n||(e instanceof File?e.name:"")||"";if(e.size<=ki){let d=await vn(()=>vh(e,t,p),g=>L(`${a}/file/upload`,{method:"POST",body:g},{timeoutMs:c}));return Cv(d[0],e.size),kh(i,{loadedBytes:e.size,totalBytes:e.size}),d}return Iv(e,t,p,a,i)}async function Iv(e,t,n,r,s){let i=(await vn(()=>vh(new Blob([],{type:e.type}),t,n),c=>L(`${r}/file/upload`,{method:"POST",body:c},{timeoutMs:kn(0)})))[0]?.path;if(!i)throw new x("Upload reservation returned no file path",{code:"UPLOAD_NO_RESULT"});let a=Tv(i);if(!a.name)throw new x(`Upload reservation returned an invalid file path: ${i}`,{code:"UPLOAD_INVALID_PATH"});try{for(let c=0;c<e.size;c+=ki){let p=Math.min(e.size,c+ki),d=e.slice(c,p,e.type),g=await vn(()=>{let m=new FormData;return a.parent&&m.append("path",a.parent),m.append("filename",a.name),m.append("first",c===0?"true":"false"),m.append("offset",String(c)),m.append("file",d,a.name),m},m=>L(`${r}/file/append`,{method:"POST",body:m},{timeoutMs:kn(d.size)}));if(g.path!==i||g.size!==p)throw new x(`Upload verification failed for ${i}: expected ${p} bytes, received ${g.size}`,{code:"UPLOAD_SIZE_MISMATCH"});kh(s,{loadedBytes:p,totalBytes:e.size})}}catch(c){throw await Bt(i,r).catch(()=>{}),c}return[{path:i,size:e.size}]}function Ev(e,t,n){let r=ae(n);return vn(()=>{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=>L(`${r}/file/upload`,{method:"POST",body:s},{timeoutMs:Mv}))}var Mv=wh;function Ov(e,t,n){let r=ae(n),s=kn(t.size);return vn(()=>{let o=new FormData;return o.append(e,t,e.split("/").pop()||"file"),o},o=>L(`${r}/file/upload`,{method:"POST",body:o},{timeoutMs:s}))}var An=class extends x{path;constructor(t){super(`A file or folder already exists at ${t}`,{status:409,code:"FILE_EXISTS"}),this.name="FileExistsError",this.path=t}};async function ps(e,t){let n=ae(t),r=e.trim(),o=(r.startsWith("/")?r:`/${r}`).split("/"),i=o.pop()||"untitled",a=o.join("/")||"/workspace",c=Cn(`${a}/${i}`),p=[];try{p=await Tn(Ah(c),n)}catch(g){if(!(g instanceof x&&g.status===404))throw g}if(p.some(g=>g.name===Rh(c)))throw new An(c);let d=await Ch(c,new Blob([],{type:"application/octet-stream"}),n,{overwrite:!1});return[{path:d.path,size:d.bytes}]}async function ds(e,t,n){let r=ae(n);return Ov(t,await En(e,r),r)}function Dv(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function Ah(e){let t=e.lastIndexOf("/");return t<=0?"/":e.slice(0,t)}function Rh(e){return e.slice(e.lastIndexOf("/")+1)}function jv(){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 gs(e,t,n){let r=ae(n),s=Cn(Dv(e.trim()));return Ch(s,t,r,{overwrite:!0})}async function Ch(e,t,n,r){let s=Rh(e);if(!s)throw new x(`writeFile needs a file path, got "${e}"`,{code:"INVALID_PATH"});let o=Ah(e);await On(o,n).catch(()=>{});let i=jv(),a=await Mn(t,o,`.${s}.kortix-write-${i}`,n),c=a[0]?.path;if(!c)throw new x(`Upload returned no file for ${e}`,{code:"UPLOAD_NO_RESULT"});let p=Cn(c);try{await Th(p,e,n,r.overwrite)}catch(g){throw await Bt(p,n).catch(()=>{}),!r.overwrite&&g instanceof x&&g.status===409?new An(e):g}let d=a[0]?.size;return{path:e,bytes:typeof d=="number"?d:t.size}}async function Bt(e,t){return Ai("/file","DELETE",{path:e},"Delete",t)}async function On(e,t){return Ai("/file/mkdir","POST",{path:e},"Mkdir",t)}async function ms(e,t,n){return Th(e,t,ae(n),!0)}async function Th(e,t,n,r){return Ai("/file/rename","POST",r?{from:e,to:t}:{from:e,to:t,overwrite:!1},"Rename",n)}async function Ih(){return bh(await ht().project.current())}async function Ci(){return bh(await ht().global.health())}async function Eh(){try{return(await Ci()).healthy===!0}catch{return!1}}var Lv={list:Tn,read:In,readBlob:En,status:cs,findFiles:ls,findText:us,upload:Mn,write:gs,create:ps,copy:ds,remove:Bt,mkdir:On,rename:ms,currentProject:Ih,health:Ci,isReachable:Eh,toDaemonPath:_t,toSandboxAbsolutePath:Cn,toWorkspaceRelative:Sh};function Mh(e){return{list:async t=>Tn(t,(await e()).runtimeUrl),read:async t=>In(t,(await e()).runtimeUrl),readBlob:async t=>En(t,(await e()).runtimeUrl),status:async()=>cs((await e()).runtimeUrl),findFiles:async(t,n)=>ls(t,n,(await e()).runtimeUrl),findText:async t=>us(t,(await e()).runtimeUrl),upload:async(t,n,r,s)=>Mn(t,n,r,(await e()).runtimeUrl,s),write:async(t,n)=>gs(t,n,(await e()).runtimeUrl),create:async t=>ps(t,(await e()).runtimeUrl),copy:async(t,n)=>ds(t,n,(await e()).runtimeUrl),remove:async t=>Bt(t,(await e()).runtimeUrl),mkdir:async t=>On(t,(await e()).runtimeUrl),rename:async(t,n)=>ms(t,n,(await e()).runtimeUrl)}}function Oh(e){return{get:t=>Tr(e.projectId,e.sessionId,t),presence:(t,n)=>l.put(`/projects/${e.projectId}/sessions/${e.sessionId}/presence`,t,{showErrors:!1,keepalive:n?.keepalive??!t.active}),cost:()=>Kr(e.sessionId,{projectId:e.projectId}),update:t=>zp(e.projectId,e.sessionId,t),delete:()=>(e.forgetReady(),Yp(e.projectId,e.sessionId)),restore:()=>Qp(e.projectId,e.sessionId),recover:()=>Jp(e.projectId,e.sessionId),start:(...t)=>dt(e.projectId,e.sessionId,...t),startOrThrow:(...t)=>kd(e.projectId,e.sessionId,...t),restart:()=>(e.forgetReady(),Or(e.projectId,e.sessionId)),stop:()=>(e.forgetReady(),Dr(e.projectId,e.sessionId)),configState:()=>Xp(e.projectId,e.sessionId),reloadConfig:t=>(e.forgetReady(),Zp(e.projectId,e.sessionId,t)),reloadConfigStream:(...t)=>(e.forgetReady(),ed(e.projectId,e.sessionId,...t)),setSharing:t=>Rp(e.projectId,e.sessionId,t),previews:()=>Op(e.projectId,e.sessionId),participants:()=>Cp(e.projectId,e.sessionId),watch:()=>Tp(e.projectId,e.sessionId),setWatch:t=>Ip(e.projectId,e.sessionId,t),setPinned:t=>Ep(e.projectId,e.sessionId,t),setArchived:t=>Mp(e.projectId,e.sessionId,t),commit:t=>ap(e.projectId,e.sessionId,t),publicShares:{list:()=>Dp(e.projectId,e.sessionId),create:(...t)=>jp(e.projectId,e.sessionId,...t),revoke:(...t)=>Lp(e.projectId,e.sessionId,...t)}}}function Dh(e){return{reminders:{list:()=>Mm(e.projectId,e.sessionId),create:t=>Om(e.projectId,e.sessionId,t),update:(t,n)=>Eo(e.projectId,e.sessionId,t,n),remove:t=>Mo(e.projectId,e.sessionId,t)},audit:(t,n)=>Fp(e.projectId,e.sessionId,t,n),attachments:{upload:(t,n)=>Py(e.projectId,e.sessionId,t,n),read:(t,n)=>Sy(`kortix-attachment://${e.projectId}/${e.sessionId}/${t}`,n)},transcript:t=>Np(e.projectId,e.sessionId,t),messageAuthors:()=>sd(e.projectId,e.sessionId),modelUsage:()=>od(e.projectId,e.sessionId),transcriptSync:t=>Ir(e.projectId,e.sessionId,t),log:t=>Kp(e.projectId,e.sessionId,t),turn:()=>Er(e.projectId,e.sessionId),prompts:{create:t=>Mr(e.projectId,e.sessionId,t),list:()=>Bp(e.projectId,e.sessionId),remove:t=>qp(e.projectId,e.sessionId,t),retry:t=>Vp(e.projectId,e.sessionId,t),edit:(t,n)=>Gp(e.projectId,e.sessionId,t,n),interrupt:t=>Wp(e.projectId,e.sessionId,t),hold:t=>Hp(e.projectId,e.sessionId,t)},ensureReady:e.ensureReady}}function Uv(e,t){return e?.some(n=>n.startsWith("session."))?e.includes(t):!0}var Fv=["control_plane","provider_ingress","daemon","upstream_port"];function jh(e){return typeof e=="string"&&Fv.includes(e)?e:null}function Lh(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 $h(e,t){let n=(e===void 0?qe():e)||null;if(!n)return{status:0,ok:!1,health:null,body:"",hop:null,upstreamStatus:null};let r=await L(`${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=jh(r.headers.get("X-Kortix-Proxy-Hop"))??jh(o?.hop),c=Number(r.headers.get("X-Kortix-Upstream-Status")),p=o?.upstream_status,d=Number.isFinite(c)&&c>0?c:typeof p=="number"?p:null;return{status:r.status,ok:r.ok,health:i,body:s,hop:a,upstreamStatus:d}}var Uh=/https?:\/\/(?:localhost|127\.0\.0\.1):\d{1,5}[^\s)"'<>]*/g,Fh=/^https?:\/\/p(\d+)-([^.]+)\.localhost(?::(\d+))?(\/.*)?$/,Nh=/^https?:\/\/(?:dev|staging|prod|preview)-p(\d+)-([a-z0-9-]+)\.[^/]+?(?::(\d+))?(\/.*)?$/i,Kh=new Set([22,4096,parseInt(et.KORTIX_MASTER,10)]);function Nv(e){return Fh.test(e)}function fs(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 Kv(e){let t=e.indexOf("](");return t===-1?e:e.slice(0,t)}var Bv=new Set(["'",'"',"`","<","(","["]),qv=new Set([">","'",'"',"`",")","]",",",";",".","!","?"]);function Gv(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&&Bv.has(e[t]);)t++;for(;n>t&&qv.has(e[n-1]);)n--;return e.slice(t,n)}function Wv(e){return e.match(/https?:\/\/(?:localhost|127\.0\.0\.1):\d{1,5}[^\s"'<>)]*/i)?.[0]??null}var Vv=/^\/proxy\/(\d{1,5})(\/.*)?$/,Hv=/^\/(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 zv(e){if(!e)return!1;try{let t=new URL(e);return t.hostname!=="localhost"&&t.hostname!=="127.0.0.1"?!1:Hv.test(t.pathname)}catch{return!1}}function ys(e){if(!e)return null;let t=Gv(Kv(e.trim())),n=Vh(t);if(n){let r=fs(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(et.KORTIX_MASTER,10);if(s===i){let c=r.pathname.match(Vv);if(c){let p=parseInt(c[1],10);if(p>=1&&p<=65535)return s=p,o=fs(`${c[2]||"/"}${r.search}${r.hash}`),{originalUrl:`http://localhost:${s}${o}`,port:s,path:o}}}let a=fs(o);return{originalUrl:`${r.protocol}//${r.hostname}:${s}${a}`,port:s,path:a}}catch{let r=Wv(e);return r&&r!==e?ys(r):null}}function Yv(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(([c,p])=>o>=c&&i<=p)||t.push([o,i])}return t}function Jv(e,t){return t.some(([n,r])=>e>=n&&e<r)}function Qv(e){let t=[],n=new Set,r=Yv(e);Uh.lastIndex=0;let s;for(;(s=Uh.exec(e))!==null;){let o=ys(s[0]);if(!o)continue;let{originalUrl:i,port:a,path:c}=o;a<1||a>65535||Kh.has(a)||n.has(i)||(n.add(i),t.push({originalUrl:i,port:a,path:c,startIndex:s.index,endIndex:s.index+i.length,inCodeBlock:Jv(s.index,r)}))}return t}function Uq(e){return Qv(e).length>0}function Xv(e){try{let{hostname:t}=new URL(e);return t==="localhost"||t==="127.0.0.1"}catch{return!1}}function Bh(e){return e.trim().toLowerCase().split("_").join("-")}function qh(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function Zv(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(Bh(n.sandboxId));return`${qh(s)}${t}`}function eA(e){return e.sandboxId.trim().length>0}function bt(e,t,n){let r=fs(t);if(!eA(n))return sA(e,r);let s=Zv(e,r,n);return s||(Xv(n.apiBaseUrl)?`http://p${e}-${Bh(n.sandboxId)}.localhost:${n.backendPort}${r}`:`${qh(n.apiBaseUrl)}/p/${n.sandboxId}/${e}${r}`)}function Fq(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 tA(e){return`/open?path=/${(e.startsWith("/workspace")?e:`/workspace/${e.replace(/^\/+/,"")}`).split("/").filter(Boolean).map(r=>encodeURIComponent(r)).join("/")}`}function Nq(e){return`http://localhost:3211${tA(e)}`}function nA(){return"/health"}function Kq(e){return bt(3211,nA(),e)}function Bq(e,t){return bt(e,"/",t)}function rA(e){let t=ys(e);return!(!t||Kh.has(t.port)||zv(e))}function Gh(e,t){if(!e)return e;let n=ys(e);return n?rA(n.originalUrl)?bt(n.port,n.path,t):n.originalUrl:e}function sA(e,t="/"){return`http://localhost:${e}${t}`}var Wh=/^https?:\/\/[^/]+\/v1\/p\/([^/]+)\/(\d+)(\/.*)?$/;function Vh(e){let t=e.match(Fh);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(Nh);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(Wh);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 qq(e){try{let t=Vh(e);return t?`http://localhost:${t.port}${t.path}`:null}catch{return null}}function Gq(e){return Nv(e)||Nh.test(e)||Wh.test(e)}function Wq(e){try{let{hostname:t,port:n}=new URL(e);return(t==="localhost"||t==="127.0.0.1")&&n!==""}catch{return!1}}var Dn="/web-proxy/";function Vq(e,t){try{let n=new URL(e);if(n.protocol!=="http:"&&n.protocol!=="https:")return null;let r=n.protocol.replace(":",""),s=`${Dn}${r}/${n.host}${n.pathname}${n.search}${n.hash}`,o=parseInt(et.KORTIX_MASTER,10);return`${bt(o,"/",t).replace(/\/$/,"")}${s}`}catch{return null}}function Hq(e){try{let t=new URL(e),n=t.pathname.indexOf(Dn);if(n===-1)return null;let s=t.pathname.slice(n+Dn.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 zq(e){try{return new URL(e).pathname.includes(Dn)}catch{return e.includes(Dn)}}function Yq(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 Jq(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 Hh(e){return{health:t=>$h(e.tryResolveReady()?.runtimeUrl??null,t),previewUrl:(t,n="/")=>bt(t,n,e.resolvePreviewOptsForSandbox(e.requireReady("previewUrl").sandboxId)),proxyUrl:t=>Gh(t,e.resolvePreviewOptsForSandbox(e.requireReady("proxyUrl").sandboxId)),sandboxPortUrl:t=>Fe(e.requireReady("sandboxPortUrl").sandboxId,t)}}function Ti(e,t,n,r){let s,o,{persistedPromptDefaults:i,clearPersistedDefaults:a}=Dy(e,t),{ensureReady:c,tryResolveReady:p,requireReady:d,forgetReady:g}=Uy(e,t,n),m={projectId:e,sessionId:t,ensureReady:c,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{...Oh(m),...Dh(m),...Hh(m),...qy(m),...Yy(m),...hh(m),files:Mh(c),...By(m),get runtime(){return We(d("runtime").runtimeUrl)}}}function zh(e){return{apps:{list:()=>uf(e),create:t=>pf(e,t),get:t=>Do(e,t),update:(...t)=>df(e,...t),access:{get:(...t)=>yf(e,...t),update:(...t)=>_f(e,...t),session:(...t)=>bf(e,...t),agents:t=>hf(e,t)},remove:t=>gf(e,t),token:t=>mf(e,t),authEnv:t=>ff(e,t),artifacts:{register:t=>jo(e,t),uploadArchive:(...t)=>Pf(e,...t),finalize:(...t)=>Lo(e,...t)},deployments:{create:(...t)=>Sf(e,...t),list:t=>xf(e,t),get:(...t)=>wf(e,...t),logs:(...t)=>kf(e,...t),remove:(...t)=>Rf(e,...t)},start:t=>vf(e,t),stop:t=>Af(e,t),rollback:(...t)=>Cf(e,...t),machines:{list:t=>Tf(e,t),start:(t,n)=>If(e,t,n),stop:(t,n)=>Ef(e,t,n),restart:(t,n)=>Mf(e,t,n),destroy:(t,n)=>Of(e,t,n)},scale:(...t)=>Df(e,...t),exec:(...t)=>jf(e,...t),volumes:{list:t=>Lf(e,t),create:(...t)=>$f(e,...t),update:(...t)=>Uf(e,...t),destroy:(...t)=>Ff(e,...t),snapshots:(...t)=>Nf(e,...t),snapshot:(...t)=>Kf(e,...t),restore:(...t)=>Bf(e,...t),fork:(...t)=>qf(e,...t)}}}}function Yh(e){return{list:()=>nl(e),invite:(...t)=>ol(e,...t),update:(...t)=>rl(e,...t),revoke:t=>sl(e,t),pendingInvites:()=>il(e),resendInvite:(...t)=>cl(e,...t),revokeInvite:(...t)=>al(e,...t),requests:()=>Zc(e),approveRequest:(...t)=>el(e,...t),rejectRequest:(...t)=>tl(e,...t),groupGrants:()=>ll(e),attachGroupGrant:(...t)=>ul(e,...t),updateGroupGrant:(...t)=>pl(e,...t),detachGroupGrant:t=>dl(e,t),resourceGrants:{list:()=>gl(e),create:t=>ml(e,t),remove:t=>fl(e,t)}}}function Jh(e){return{tokens:{list:()=>qm(e),create:t=>Gm(e,t),revoke:t=>Wm(e,t)},setupLinks:{requestSecret:t=>Zm(e,t),requestConnector:t=>ef(e,t)},validateManifest:t=>Ic(e,t),gitToken:()=>Ec(e),agentIdentities:()=>tm(e),secrets:{list:()=>bl(e),upsert:t=>Pl(e,t),setStrategy:(...t)=>Sl(e,...t),broker:(...t)=>xl(e,...t),remove:t=>Al(e,t),setPersonal:(...t)=>Rl(e,...t),removePersonal:t=>Cl(e,t),setGitCredential:t=>vl(e,t),listProviderOAuth:()=>wl(e),startProviderOAuth:(...t)=>oo(e,...t),pollProviderOAuth:(...t)=>io(e,...t),removeProviderOAuth:t=>kl(e,t)},access:Yh(e)}}function Qh(e){return{list:()=>Bl(e),listAll:()=>ql(e),reconcile:(...t)=>Gl(e,...t),reconcileMember:(...t)=>Wl(e,...t),updateCredential:(...t)=>Vl(e,...t),revoke:(...t)=>Hl(e,...t),activate:(...t)=>zl(e,...t),setDefault:(...t)=>Yl(e,...t),rename:(...t)=>Jl(e,...t),share:(...t)=>Xl(e,...t),addComputer:(...t)=>Ql(e,...t),pipedreamConnect:(...t)=>Zl(e,...t),pipedreamFinalize:(...t)=>eu(e,...t)}}function hs(e){return{catalog:t=>nn(e,t),tools:()=>uo(e),search:(...t)=>Kl(e,...t),describe:(...t)=>po(e,...t),call:(...t)=>Tt(e,...t),callAction:(t,n,r,s)=>Tt(e,`${t}.${n}`,r,s),accounts:(...t)=>go(e,...t),uploadAttachment:(...t)=>mo(e,...t)}}function Ii(e,t){return{slug:t,run:(r,s,o)=>bo(e,t,r,s,o),call:(r,s,o)=>Tt(e,`${t}.${r}`,s,o),describe:async r=>r!==void 0?po(e,`${t}.${r}`):(await nn(e,{slug:t,includeSchemas:!0,includeOutputSchemas:!0})).find(o=>o.slug===t)??null,accounts:()=>go(e,t),paginate:(r,s,o)=>xu(e,t,r,s,o),uploadAttachment:(r,s)=>mo(e,r,{...s,connector:t})}}var oA=100,Xh=0,iA=new Set(["attachment_size_mismatch","attachment_failed"]),Zh=()=>new x("Attachment expired. Attach the file again.",{code:"attachment_expired"});function Ei(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 aA(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),c=()=>{o&&clearTimeout(o),o=void 0};return{onProgress:p=>{if(!t()||a(p)===a(e.item.receivedBytes)||(r=p,o))return;let d=s+oA-Date.now();if(d<=0)return i();o=setTimeout(i,d),typeof o=="object"&&"unref"in o&&o.unref()},onProcessing:()=>{c(),r=void 0,t()&&(e.item={...e.item,status:"processing",receivedBytes:e.item.size},n())},clear:c}}function e_(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,c,p={attachments:[]},d=()=>[...r.values()].filter(h=>!h.handedOff);function g(h,S){h.removalDeleted||(h.removalDeleted=!0,on(e,S).catch(()=>{}))}function m(){c&&clearTimeout(c);let h=d().map(({item:P})=>P);(h.length!==p.attachments.length||h.some((P,k)=>P!==p.attachments[k]))&&(p={attachments:h});let S=Math.min(...h.filter(P=>P.status==="ready").map(P=>Date.parse(P.attachment.expires_at)));Number.isFinite(S)&&!a&&(c=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:Zh()});m()},Math.min(2147483647,Math.max(0,S-Date.now()))),typeof c=="object"&&"unref"in c&&c.unref());for(let P of s)P();for(let P of[...o])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 S=d();if(S.length+h.length>20)throw new Error("A message can contain up to 20 attachments");if(h.some(k=>!Number.isSafeInteger(k)||k<=0||k>52428800))throw new Error("Each attachment must contain 1 byte to 50 MiB");if(S.reduce((k,C)=>k+C.item.size,0)+h.reduce((k,C)=>k+C,0)>104857600)throw new Error("Message attachments exceed 100 MiB")}function y(h,S,P){let k=++h.generation,C=new AbortController;h.abort=C,h.item={...h.item,status:"uploading",error:void 0};let j=()=>(!a||h.handedOff===!0)&&r.get(h.item.id)===h&&h.generation===k,w=aA(h,j,m);vr(e,S,{resume:h.upload,signal:C.signal,onUpload:D=>{h.upload=D,h.removed&&(C.abort(),g(h,D.attachment_id))},...w}).then(D=>{j()&&(h.item={...h.item,status:"ready",attachment:Ei(D),receivedBytes:D.size})}).catch(D=>{D instanceof x&&iA.has(D.code??"")&&(h.upload=void 0),j()&&(h.item={...h.item,status:D instanceof x&&D.code==="ABORTED"?"aborted":"error",error:D instanceof Error?D:new Error(String(D))})}).finally(()=>{w.clear(),h.abort===C&&(h.abort=void 0),P()})}function v(){for(let h of r.values()){if(i>=n)break;if(h.item.status!=="pending"||!h.item.file||a&&!h.handedOff)continue;let S=h.item.file;i++,y(h,S,()=>{i--,m(),v()})}m()}function R(h){_(h.map(P=>P.size));let S=h.map(P=>{let k=`attachment-${++Xh}`;return r.set(k,{generation:0,item:{id:k,file:P,filename:P.name,mime:P.type||"application/octet-stream",size:P.size,status:"pending",receivedBytes:0}}),k});return m(),v(),S}function T(h){let S=h.map(({attachment:k,file:C})=>{try{return{attachment:Ei(k),file:C}}catch{return}});_(S.flatMap(k=>k?[k.attachment.size]:[]));let P=S.map(k=>{if(!k)return;let C=`attachment-${++Xh}`,{attachment:j,file:w}=k;return r.set(C,{generation:0,item:{id:C,...w?{file:w}:{},filename:j.filename,mime:j.mime,size:j.size,status:"ready",receivedBytes:j.size,attachment:j}}),C});return m(),P}function b(h){let S=r.get(h);!S||S.item.status==="ready"||(S.generation++,S.abort?.abort(),S.item={...S.item,status:"aborted",error:new Error("Attachment upload cancelled")},m())}function M(h,{signal:S}={}){let P=[...h];return new Promise((k,C)=>{let j=()=>{o.delete(Pe),S?.removeEventListener("abort",D)},w=N=>{j(),C(N)},D=()=>w(ke()),Pe=()=>{let N=!1;for(let G of P){let B=r.get(G);if(!B)return w(new Error("Attachment was removed before it was sent"));if(a&&!B.handedOff)return w(new Error("Attachment controller is disposed"));if(B.item.status==="error"||B.item.status==="aborted")return w(B.item.error??new Error("Attachment upload failed"));B.item.status!=="ready"&&(N=!0)}if(N)return;let z;try{z=P.map(G=>{let B=Ei(r.get(G).item.attachment);return{type:"file",attachment_id:B.attachment_id,filename:B.filename,mime:B.mime}})}catch(G){return w(G instanceof Error?G:new Error(String(G)))}j(),k(z)};if(S?.aborted)return D();o.add(Pe),S?.addEventListener("abort",D,{once:!0}),Pe()})}return{add:h=>R([h])[0],addMany:R,restore:T,retry(h){let S=r.get(h);if(S?.handedOff||f(),!(!S||S.item.status==="ready"||S.item.status==="uploading"||S.item.status==="processing"||S.item.status==="pending")){if(!S.item.file||S.upload&&Date.parse(S.upload.expires_at)<=Date.now())throw Zh();S.item={...S.item,status:"pending",error:void 0},v()}},async remove(h){let S=r.get(h);if(!S)return;S.removed=!0,S.generation++,r.delete(h);let P=S.upload?.attachment_id??S.item.attachment?.attachment_id;P&&S.abort?.abort(),m(),v(),P&&g(S,P)},abort:b,submit(h){if(!a){for(let S of h){let P=r.get(S);P&&(P.handedOff=!0)}m()}},reclaim(h){if(!a){for(let S of h){let P=r.get(S);P&&(P.handedOff=!1)}m()}},whenReady:M,forget(h=d().map(S=>S.item.id)){for(let S of h){let P=r.get(S);P&&(P.generation++,P.abort?.abort(),r.delete(S))}m(),v()},dispose(){if(!a){a=!0,c&&clearTimeout(c);for(let h of r.values()){if(h.handedOff)continue;h.generation++,h.abort?.abort();let S=h.upload?.attachment_id??h.item.attachment?.attachment_id;S&&e&&on(e,S).catch(()=>{})}s.clear(),m()}},getSnapshot:()=>p,subscribe(h){return s.add(h),()=>{s.delete(h)}}}}function t_(e){return{attachments:{upload:(...t)=>vr(e,...t),delete:(...t)=>on(e,...t),createController:t=>e_(e,t)},get:t=>Rt(e,t),detail:()=>gr(e),skills:{create:(...t)=>Fc(e,...t)},audit:t=>Hm(e,t),update:t=>yr(e,t),archive:()=>hr(e),llmCatalog:()=>mr(e),modelPicker:()=>fr(e),modelAccess:()=>qr(e),setModelAccess:t=>Gr(e,t),sandboxHealth:()=>Pr(e),onboardingComplete:(...t)=>Uc(e,...t)}}function n_(e){return{sessions:{list:t=>Mt(e,t),listPage:t=>Ap(e,t),create:t=>Ot(e,t),ensureWarm:()=>$p(e),claimWarm:t=>Up(e,t)},review:{list:t=>Sm(e,t),summary:()=>xm(e),get:t=>wm(e,t),submit:t=>km(e,t),act:(...t)=>vm(e,...t),bulkAct:t=>Am(e,t)},approvals:{list:t=>yl(e,t),resolve:(...t)=>_l(e,...t),sessionsNeedingInput:t=>hl(e,t)}}}function r_(e){return{files:{list:t=>Du(e,t),listDirectory:t=>ju(e,t),read:(t,n)=>$u(e,t,n),search:(...t)=>Lu(e,...t),archive:(...t)=>Uu(e,...t),archiveRequest:(...t)=>Fu(e,...t),history:(...t)=>Ju(e,...t)},git:{commits:()=>Hu(e),commit:t=>zu(e,t),commitDiff:t=>Yu(e,t),branches:()=>Vu(e),versionDiff:(...t)=>Qu(e,...t),inviteCollaborator:(...t)=>Tc(e,...t)},changeRequests:{list:(...t)=>Xu(e,...t),get:t=>Zu(e,t),update:(...t)=>cp(e,...t),diff:t=>ep(e,t),mergePreview:t=>tp(e,t),open:(...t)=>np(e,...t),merge:(...t)=>rp(e,...t),close:(...t)=>sp(e,...t),reopen:(...t)=>op(e,...t),requestChanges:(...t)=>ip(e,...t)},...n_(e)}}function s_(e){return{policies:{list:()=>wu(e),set:(...t)=>ku(e,...t)},reminders:{list:()=>$m(e),updateMany:(...t)=>jm(e,...t),removeMany:(...t)=>Lm(e,...t)},triggers:{list:()=>id(e),eventApps:()=>hd(e),eventTypes:(...t)=>yd(e,...t),create:(...t)=>ad(e,...t),update:(...t)=>cd(e,...t),remove:(...t)=>ld(e,...t),fire:((t,n)=>dd(e,t,n)),runs:(...t)=>gd(e,...t),projectRuns:(...t)=>md(e,...t),replay:(...t)=>fd(e,...t),setActivation:(...t)=>ud(e,...t)},...r_(e)}}function o_(e,t){return{connectors:{...hs(e),list:()=>tu(e),config:(...n)=>cu(e,...n),create:(...n)=>pu(e,...n),remove:(...n)=>gu(e,...n),sync:()=>nu(e),auth:{discover:(...n)=>du(e,...n)},setName:(...n)=>lu(e,...n),setCredentialMode:(...n)=>ru(e,...n),setAuthorizationStrategy:(...n)=>su(e,...n),setCredential:(...n)=>_u(e,...n),deleteCredential:(...n)=>bu(e,...n),setSensitive:(...n)=>ou(e,...n),connections:t,policies:{get:(...n)=>iu(e,...n),set:(...n)=>au(e,...n)},pipedream:{listApps:(...n)=>mu(e,...n),listSections:(...n)=>fu(e,...n),connect:(...n)=>uu(e,...n),finalize:(...n)=>Pu(e,...n)},discover:{list:(...n)=>fo(e,...n),sections:(...n)=>yu(e,...n),detail:(...n)=>yo(e,...n)}},...s_(e)}}function i_(e){return{gateway:{logs:t=>Cg(e,t),log:t=>Tg(e,t),overview:t=>Ig(e,t),series:t=>Eg(e,t),breakdown:t=>Mg(e,t),sessions:t=>Og(e,t),errors:t=>Dg(e,t),budgets:()=>jg(e),setBudget:t=>Lg(e,t),deleteBudget:t=>$g(e,t),keys:()=>Ug(e),createKey:t=>Fg(e,t),revokeKey:t=>Ng(e,t),routing:{get:()=>kg(e),set:t=>vg(e,t),reset:()=>Ag(e),preview:t=>Rg(e,t)},playground:(t,n,r)=>Kg(e,t,n,r)}}}function a_(e){return{modelDefaults:{get:()=>Ad(e),set:t=>Rd(e,t),clear:t=>Cd(e,t)},setDefaultAgent:t=>Ed(e,t),sandbox:{list:()=>Ou(e),snapshots:()=>Au(e),rebuildSnapshot:t=>Ru(e,t),fixWithAgent:()=>Cu(e),createTemplate:t=>Tu(e,t),updateTemplate:(...t)=>Iu(e,...t),removeTemplate:t=>Eu(e,t),buildTemplate:t=>Mu(e,t),setProvider:t=>$c(e,t)},setAgentScope:(...t)=>Id(e,...t)}}function c_(e){return{channels:{slack:{installation:()=>lg(e),connect:t=>ug(e,t),mode:()=>pg(e),completeInstall:t=>gg(e,t),manifest:()=>fg(e),disconnect:()=>yg(e),getFile:t=>hg(e,t),uploadFile:t=>_g(e,t)},teams:{completeInstall:t=>mg(e,t)},email:{installation:t=>bg(e,t),mode:()=>Pg(e),connect:t=>Sg(e,t),disconnect:t=>xg(e,t),updatePolicy:(...t)=>wg(e,...t)}},updateFeatureFlag:(...t)=>jc(e,...t),updateExperimentalFeature:(...t)=>Lc(e,...t),...a_(e)}}var UG=["screen","actions","audio"],FG=["password_managers","messaging","banking"],NG={localHours:8760,remoteDays:3650},KG=[500,1e3,2e3,5e3,1e4],BG=[720,1080,1440,2160],qG={intervalMs:2e3,maxHeight:1440},cA=/^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/;function GG(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(/\.$/,""),cA.test(n)?n:null}function WG(e){let t=e.trim();return!t||t.length>255||t.startsWith("-")||/[\u0000-\u001f\u007f]/.test(t)||/\s/.test(t)&&!t.toLowerCase().endsWith(".exe")?null:t}function YG(e){let{state:t,idle:n}=e.health;return t==="healthy"?n?"idle":"recording":t}var Q=e=>`/accounts/${e}/capture`;function He(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 l_=e=>He({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}),Mi=(e={})=>({day:e.day,from:e.from,to:e.to,user_id:e.userId,device_id:e.deviceId,display_id:e.displayId});async function u_(e,t={}){return u(await l.get(`${Q(e)}/devices${He({user_id:t.userId,scope:t.scope})}`))}async function p_(e,t){return u(await l.delete(`${Q(e)}/devices/${t}`))}async function d_(e,t,n){return u(await l.put(`${Q(e)}/devices/${t}/link`,{user_id:n}))}async function g_(e){return u(await l.get(`${Q(e)}/enrollment-tokens`))}async function m_(e,t){return u(await l.post(`${Q(e)}/enrollment-tokens`,t))}async function f_(e,t){return u(await l.delete(`${Q(e)}/enrollment-tokens/${t}`))}async function y_(e,t={}){return u(await l.get(`${Q(e)}/enrollments${He({status:t.status})}`))}async function h_(e,t,n){return u(await l.post(`${Q(e)}/enrollments/${t}/approve`,n?{user_id:n}:{}))}async function __(e,t){return u(await l.post(`${Q(e)}/enrollments/${t}/deny`,{}))}async function b_(e){return u(await l.get(`${Q(e)}/policy`))}async function P_(e,t){return u(await l.put(`${Q(e)}/policy`,{policy:t}))}async function S_(e,t={}){return u(await l.get(`${Q(e)}/timeline${He(Mi(t))}`))}async function x_(e,t={}){return u(await l.get(`${Q(e)}/timeline/items${He(Mi(t))}`))}async function w_(e,t={}){return u(await l.get(`${Q(e)}/days${He({tz:t.tz,user_id:t.userId,device_id:t.deviceId})}`))}async function k_(e,t){return u(await l.get(`${Q(e)}/search${l_(t)}`))}async function v_(e,t,n={}){return u(await l.get(`${Q(e)}/frames/${t}${He({user_id:n.userId})}`))}async function A_(e,t,n={}){return u(await l.get(`${Q(e)}/chunks/${t}/media${He({user_id:n.userId})}`))}async function R_(e,t,n){return u(await l.get(`${Q(e)}/devices/${t}/assets/${encodeURIComponent(n)}`))}async function C_(e){return u(await l.get(`/capture/device/grants/${encodeURIComponent(e)}`))}async function T_(e,t){return u(await l.post(`/capture/device/grants/${encodeURIComponent(e)}/approve`,t?{account_id:t}:{}))}async function I_(e){return u(await l.post(`/capture/device/grants/${encodeURIComponent(e)}/deny`,{}))}async function E_(e){return u(await l.get(Q(e)))}async function M_(e,t){return u(await l.patch(Q(e),{enabled:t}))}async function O_(e){return u(await l.get(`/capture/me/search${l_(e)}`))}async function D_(e={}){return u(await l.get(`/capture/me/timeline${He(Mi(e))}`))}async function j_(e){return u(await l.get(`/capture/me/frames/${e}`))}function uA(e){return{workspace:{get:()=>E_(e),setEnabled:t=>M_(e,t)},devices:{list:t=>u_(e,t),revoke:t=>p_(e,t),link:(t,n)=>d_(e,t,n),assetUrl:(t,n)=>R_(e,t,n)},enrollment:{tokens:{list:()=>g_(e),create:t=>m_(e,t),revoke:t=>f_(e,t)},list:t=>y_(e,t),approve:(t,n)=>h_(e,t,n),deny:t=>__(e,t)},policy:{get:()=>b_(e),set:t=>P_(e,t)},timeline:{get:t=>S_(e,t),items:t=>x_(e,t),days:t=>w_(e,t)},search:t=>k_(e,t),frame:(t,n)=>v_(e,t,n),media:(t,n)=>A_(e,t,n)}}var L_={account:e=>uA(e),deviceGrant:C_,approveDevice:T_,denyDevice:I_,me:{search:O_,timeline:D_,frame:j_}};async function $_(e){let t=e?.fetch??I().fetch??((s,o)=>fetch(s,o)),n=e?.backendUrl??I().backendUrl,r=await t(`${gt(n)}/clients/mobile`,{headers:{accept:"application/json"},...e?.signal?{signal:e.signal}:{}});if(!r.ok)throw new x(`Mobile client policy request failed (HTTP ${r.status})`,{status:r.status,response:r});return await r.json()}var pA=/^v?(\d+)(?:\.(\d+))?(?:\.(\d+))?(?:[-+].*)?$/i;function t1(e,t){let n=o=>{let i=pA.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 dA(){return ht()}var U_=null,F_=!1;function gA(e){let t=U_;U_=e,!(F_||!t)&&(t.backendUrl===e.backendUrl&&t.getToken===e.getToken||(F_=!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 mA(e,t){t?.global!==!1&&gA(e),Hs(e,t);let n=Oy(e),{auth:r,accounts:s,iam:o,accountInvites:i}=Cy(),{billing:a,sandboxShares:c}=vy(),{projects:p,github:d,gitBackend:g,connectStatus:m,marketplace:f}=ky();function _(y){let v=Qh(y);return{...t_(y),...zh(y),...Jh(y),...o_(y,v),...i_(y),...c_(y),connector:R=>Ii(y,R),session:R=>Ti(y,R,e,n)}}return{config:e,auth:r,accounts:s,iam:o,accountInvites:i,projects:p,connectors:hs(),connector:y=>Ii(void 0,y),project:_,session:(y,v)=>Ti(y,v,e,n),github:d,gitBackend:g,billing:a,sandboxShares:c,connectStatus:m,marketplace:f,capture:L_,notifications:{registerDeviceToken:Wf,unregisterDeviceToken:Vf,list:Hf,markRead:zf,preferences:Yf,updatePreferences:Jf,webPushPublicKey:Qf,registerWebPushSubscription:Xf,unregisterWebPushSubscription:Zf},mobileClientPolicy:$_,validateToken:Ac,runtime:dA}}function fA(){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 yA(){return{pending:[],failed:[],inFlightId:null,inFlightIds:[]}}function qt(e){return e.inFlightIds?.length?e.inFlightIds:e.inFlightId?[e.inFlightId]:[]}function hA(e,t){return{...e,pending:[...e.pending,{...t,attempts:0}]}}function _A(e){if(qt(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 bA(e){let t=qt(e);return t.length===0?e:{...e,pending:e.pending.filter(n=>!t.includes(n.id)),inFlightId:null,inFlightIds:[]}}function PA(e,t){let n=qt(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 SA(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 xA(e,t){return qt(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 wA(e,t,n){return qt(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 kA(e,t,n){let r=qt(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],[c]=a.splice(s,1);return a.splice(i,0,c),{...e,pending:a}}var N_={thinking:!1,toolDetails:!0,assistantMetadata:!0};function vA(e){return e&&e.charAt(0).toUpperCase()+e.slice(1)}function AA(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 RA(e,t){if(e.type==="text"&&!e.synthetic)return`${e.text??""}
|
|
21
|
+
`)),yield m}}}finally{r.removeEventListener("abort",i),o.releaseLock()}}}async function*qk(e,t,n){let r=e.eventTransport??_i(e.fetch??globalThis.fetch),s=n.signal??new AbortController().signal,o=n.sseDefaultRetryDelay??3e3,i;for(let a=1;!s.aborted;a++)try{let c=new Headers(n.headers);i!==void 0&&c.set("Last-Event-ID",i);for await(let p of r({url:new URL(t).href,headers:c,signal: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(c){if(n.onSseError?.(c),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 Sn(e){let t=s=>(o,i)=>Kk(e,Nk(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:qk(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 Wy=200;async function Gk(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 ft(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 Vy(e){let t=e.runtimeUrl.replace(/\/$/,""),n=Sn({baseUrl:t,fetch:e.fetch});return{messages:async(r={})=>{let s=encodeURIComponent(r.conversationId??e.rootId),o=async(c,p)=>{let d=new URLSearchParams;c!==void 0&&d.set("limit",String(c)),p&&d.set("before",p);let g=`/messages/${s}${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 P(`Reading the session transcript failed: ${await Gk(f)}`,{status:f.status,response:f});let _=await f.json();return{messages:_.messages??[],hasMore:_.has_more===!0}},i=await o(r.limit===void 0?void 0:Math.min(r.limit,Wy),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,Wy),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=>ft(i,"Reading the session status failed")),n.permission.list().then(i=>ft(i,"Reading permission requests failed")),n.question.list().then(i=>ft(i,"Reading questions failed"))]);return{statuses:r??{},permissions:s??[],questions:o??[]}},answerPermission:async(r,s,o)=>{ft(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){ft(await n.question.reject({requestID:r}),"Dismissing the question failed");return}ft(await n.question.reply({requestID:r,answers:s}),"Answering the question failed")},compact:async r=>{let s=r;if(!s){let o=await n.global.config.get().then(c=>c.error===void 0?c.data:null),i=typeof o?.model=="string"?o.model:"",a=i.indexOf("/");a>0&&a<i.length-1&&(s={providerID:i.slice(0,a),modelID:i.slice(a+1)})}if(!s)throw new P("Cannot compact: no model is set for this session",{code:"MODEL_REQUIRED"});return ft(await n.session.summarize({sessionID:e.rootId,providerID:s.providerID,modelID:s.modelID}),"Compacting the session failed"),s}}}function Hy(e){async function t(){let{runtimeSessionId:n,runtimeUrl:r}=await e.ensureReady();return Vy({runtimeUrl:r,rootId:n,fetch:L})}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 zy(e){return{setModel:t=>{e.model=t},changeModel:async t=>{let n=await ad(e.projectId,e.sessionId,t);return e.clearPersistedDefaults(),n}}}var Pn=BigInt(4096),rt=BigInt(0xffffffffffff),Yy=rt+BigInt(1),Wk=Yy/BigInt(2),yt=BigInt(3600*1e3)*Pn,bi=120*1e3,Vk=/^msg_[0-9a-f]{12}[A-Za-z0-9]{14}$/,Hk=/^msg_([0-9a-f]{12})/,Jy="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";function Bt(e){let t=Hk.exec(e??"");return t?BigInt(`0x${t[1]}`):null}function xn(e){return BigInt(Math.trunc(e))*Pn&rt}function Kt(e,t){let n=e-t&rt;return n>=Wk&&(n-=Yy),n}function Qy(e){let t=null;for(let n of e)n!=null&&(t===null||Kt(n,t)>BigInt(0))&&(t=n);return t}function zk(e,t){let n=Bt(e);return n===null?!1:Kt(n,xn(t))>yt}function Yk(e,t){let n=t===void 0?null:xn(t);return Xy(e,r=>n===null||Kt(r,n)<=yt)}function Xy(e,t){let n=[];for(let r of e){let s=Bt(r);s!==null&&t(s)&&n.push(s)}return Qy(n)}function Jk(){let e="",t=new Uint8Array(32);for(;e.length<14;){crypto.getRandomValues(t);for(let n of t)n<248&&e.length<14&&(e+=Jy[n%62])}return e}function Zy(e){let t=e.random,n=xn(e.nowMs-(e.backdateMs??bi)),r=e.newestKnownTime??null;if(r!==null){let o=Kt(r,n);o>=BigInt(0)&&o<=yt&&(n=r+BigInt(1)&rt)}let s="";if(t)for(let o=0;o<14;o++)s+=Jy[Math.min(61,Math.floor(t()*62))];else s=Jk();return{id:`msg_${n.toString(16).padStart(12,"0")}${s}`,time:n}}function Si(e={}){let t=e.nowMs??Date.now(),n=xn(t-bi),r=Xy(e.after??[],s=>{let o=Kt(s,n);return o>=BigInt(0)&&o<=yt});return Zy({nowMs:t,newestKnownTime:r}).id}function eh(e){return{scope:()=>od(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=>id(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,c=Si(),p=await Or(e.projectId,e.sessionId,{clientMessageId:c,messageId:c,remintOnDelivery:!0,parts:[{type:"text",text:t}],clientSentAtMs:Date.now(),...i||a?{overrides:{...i?{model:i}:{},...a?{agent:a}:{}}}:{}});if(p.state==="failed")throw new P("This prompt was refused: its earlier delivery already failed.",{code:"PROMPT_FAILED"});return p}}}var th=async function*(e){let t=T().eventStreamTransport;if(!t){yield*_i(((s,o)=>L(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=Ny();return e||(T().billingEnabled??!1?"":vd())}async function Pi(e,t){return(await e.json().catch(()=>({})))?.error||e.statusText||t}function xi(e){if(!e)throw new Error("[kortix-runtime] Server URL not ready \u2014 sandbox is still loading");return e}async function nh(e){let t=xi(e),n=await L(`${t}/env`);if(!n.ok)throw new Error(await Pi(n,"Failed to load secrets"));return(await n.json()).secrets??{}}async function rh(e,t,n){let r=xi(e),s=await L(`${r}/env/${encodeURIComponent(t)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({value:n})});if(!s.ok)throw new Error(await Pi(s,"Failed to save secret"))}async function sh(e,t){let n=xi(e),r=await L(`${n}/env/${encodeURIComponent(t)}`,{method:"DELETE"});if(!r.ok)throw new Error(await Pi(r,"Failed to delete secret"))}var Qk={list:nh,set:rh,delete:sh};async function Xk(e,t,n){let r=e;for(;r.endsWith("/");)r=r.slice(0,-1);let s=await L(`${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 os(e,t){let n=await e.json().catch(()=>({}));return n?.error||n?.message||e.statusText||t}function wn(e){if(!e)throw new Error("[kortix-pty] Server URL not ready \u2014 sandbox is still loading");return ue(e)}async function oh(e){let t=wn(e),n=await L(`${t}/kortix/pty`);if(!n.ok)throw new Error(await os(n,"Failed to list terminals"));return n.json()}async function ih(e,t){let n=wn(e),r=await L(`${n}/kortix/pty`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t??{})});if(!r.ok)throw new Error(await os(r,"Failed to create terminal"));return r.json()}async function ah(e,t,n){let r=wn(e),s=await L(`${r}/kortix/pty/${encodeURIComponent(t)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!s.ok)throw new Error(await os(s,"Failed to update terminal"));return s.json()}async function ch(e,t){let n=wn(e),r=await L(`${n}/kortix/pty/${encodeURIComponent(t)}`,{method:"DELETE"});if(!r.ok)throw new Error(await os(r,"Failed to remove terminal"))}async function lh(e,t,n){let r=wn(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:"),ue(p.toString())}catch{return r.replace("https://","wss://").replace("http://","ws://")}})()}/kortix/pty/${encodeURIComponent(e)}/connect`,i=new URLSearchParams,a=await rn();a&&i.set("token",a),n?.wake&&i.set("wake","1");let c=i.toString();return c?`${o}${o.includes("?")?"&":"?"}${c}`:o}function Zk(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",uh="\x07",ev="\0",wi=`(?:${uh}|${st}\\\\)`,tv=[new RegExp(`${st}\\]697;[^${uh}${st}]*${wi}`,"g"),new RegExp(`${ev}?\\{"cursor":\\d+\\}`,"g"),new RegExp(`${st}\\][0-9]+;rgb:[0-9a-fA-F/]+${wi}`,"g"),new RegExp(`${st}\\]4;[0-9]+;rgb:[0-9a-fA-F/]+${wi}`,"g"),new RegExp(`${st}\\[\\??[0-9;]*\\$y`,"g"),new RegExp(`${st}\\[\\d+;\\d+R`,"g"),new RegExp(`${st}\\[\\?[0-9;]*c`,"g")];function nv(e){let t=e;for(let n of tv)t=t.replace(n,"");return t}var rv={list:oh,create:ih,update:ah,remove:ch,webSocketUrl:lh};async function O(e,t,n,r){let s=e;for(;s.endsWith("/");)s=s.slice(0,-1);let o=await L(`${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 pK(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 dK(e,t){return O(e,`/kortix/tasks/${encodeURIComponent(t)}`)}async function gK(e,t){return O(e,`/kortix/tasks/${encodeURIComponent(t)}/events`)}async function mK(e,t){return O(e,`/kortix/tasks/${encodeURIComponent(t)}/status`)}async function fK(e,t){return O(e,"/kortix/tasks",{method:"POST",body:JSON.stringify(t)})}async function yK(e,t,n){return O(e,`/kortix/tasks/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}async function hK(e,t){return O(e,`/kortix/tasks/${encodeURIComponent(t)}/start`,{method:"POST"})}async function _K(e,t){return O(e,`/kortix/tasks/${encodeURIComponent(t)}/approve`,{method:"POST"})}async function bK(e,t){return O(e,`/kortix/tasks/${encodeURIComponent(t)}`,{method:"DELETE"})}async function SK(e,t){let n=t?`?project_id=${encodeURIComponent(t)}`:"";return O(e,`/kortix/tickets${n}`)}async function PK(e,t){return O(e,`/kortix/tickets/${encodeURIComponent(t)}`)}async function xK(e,t){return O(e,`/kortix/tickets/${encodeURIComponent(t)}/events`)}async function wK(e,t){return O(e,"/kortix/tickets",{method:"POST",body:JSON.stringify(t)})}async function kK(e,t,n){return O(e,`/kortix/tickets/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}async function vK(e,t,n){return O(e,`/kortix/tickets/${encodeURIComponent(t)}/status`,{method:"POST",body:JSON.stringify(n)})}async function AK(e,t,n){return O(e,`/kortix/tickets/${encodeURIComponent(t)}/assign`,{method:"POST",body:JSON.stringify(n)})}async function RK(e,t,n){return O(e,`/kortix/tickets/${encodeURIComponent(t)}/unassign`,{method:"POST",body:JSON.stringify(n)})}async function TK(e,t,n){return O(e,`/kortix/tickets/${encodeURIComponent(t)}/comments`,{method:"POST",body:JSON.stringify(n)})}async function CK(e,t){return O(e,`/kortix/tickets/${encodeURIComponent(t)}`,{method:"DELETE"})}async function IK(e,t){return O(e,`/kortix/projects/${encodeURIComponent(t)}/columns`)}async function EK(e,t,n){return O(e,`/kortix/projects/${encodeURIComponent(t)}/columns`,{method:"PUT",body:JSON.stringify({columns:n})})}async function MK(e,t){return O(e,`/kortix/projects/${encodeURIComponent(t)}/fields`)}async function OK(e,t,n){return O(e,`/kortix/projects/${encodeURIComponent(t)}/fields`,{method:"PUT",body:JSON.stringify({fields:n})})}async function DK(e,t){return O(e,`/kortix/projects/${encodeURIComponent(t)}/templates`)}async function jK(e,t,n){return O(e,`/kortix/projects/${encodeURIComponent(t)}/templates`,{method:"PUT",body:JSON.stringify({templates:n})})}async function LK(e,t){return O(e,`/kortix/projects/${encodeURIComponent(t)}/pm-session`,{method:"POST"})}async function $K(e,t){return O(e,`/kortix/projects/${encodeURIComponent(t)}/agents`)}async function UK(e,t,n){return O(e,`/kortix/projects/${encodeURIComponent(t)}/agents`,{method:"POST",body:JSON.stringify(n)})}async function FK(e,t,n,r){return O(e,`/kortix/projects/${encodeURIComponent(t)}/agents/${encodeURIComponent(n)}`,{method:"PATCH",body:JSON.stringify(r)})}async function NK(e,t,n){return O(e,`/kortix/projects/${encodeURIComponent(t)}/agents/${encodeURIComponent(n)}`,{method:"DELETE"})}async function BK(e,t,n){return O(e,`/kortix/projects/${encodeURIComponent(t)}/agents/${encodeURIComponent(n)}/persona`)}async function KK(e,t,n=200){return O(e,`/kortix/projects/${encodeURIComponent(t)}/activity?limit=${n}`)}async function qK(e){return O(e,"/kortix/projects")}async function GK(e,t){return O(e,`/kortix/projects/${encodeURIComponent(t)}`)}async function WK(e,t){return O(e,`/kortix/projects/by-session/${encodeURIComponent(t)}`)}async function VK(e,t){return O(e,`/kortix/projects/${encodeURIComponent(t)}/sessions`)}async function HK(e,t){return O(e,`/kortix/projects/${encodeURIComponent(t)}`,{method:"DELETE"})}async function zK(e,t,n){return O(e,`/kortix/projects/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}async function YK(e,t,n="all"){return O(e,`/kortix/projects/${encodeURIComponent(t)}/milestones?status=${n}`)}async function JK(e,t,n){return O(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}`)}async function QK(e,t,n){return O(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}/events`)}async function XK(e,t,n){return O(e,`/kortix/projects/${encodeURIComponent(t)}/milestones`,{method:"POST",body:JSON.stringify(n)})}async function ZK(e,t,n,r){return O(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}`,{method:"PATCH",body:JSON.stringify(r)})}async function eq(e,t,n,r){return O(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}/close`,{method:"POST",body:JSON.stringify(r)})}async function tq(e,t,n){return O(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}/reopen`,{method:"POST"})}async function nq(e,t,n){return O(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}`,{method:"DELETE"})}async function rq(e,t){return O(e,`/kortix/projects/${encodeURIComponent(t)}/credentials`)}async function sq(e,t,n){return O(e,`/kortix/projects/${encodeURIComponent(t)}/credentials/${encodeURIComponent(n)}/events`)}async function oq(e,t,n){return O(e,`/kortix/projects/${encodeURIComponent(t)}/credentials`,{method:"POST",body:JSON.stringify(n)})}async function iq(e,t,n){return O(e,`/kortix/projects/${encodeURIComponent(t)}/credentials/${encodeURIComponent(n)}`)}async function aq(e,t,n){return O(e,`/kortix/projects/${encodeURIComponent(t)}/credentials/${encodeURIComponent(n)}`,{method:"DELETE"})}var sv=1e4,ov={retryOnAuthError:!1};function qt(e,t,n){return O(e,t,{signal:AbortSignal.timeout(sv),...n},ov)}async function cq(e,t=!1){return(await qt(e,`/kortix/services${t?"?all=true":""}`)).services??[]}async function lq(e){return(await qt(e,"/kortix/services/templates")).templates??[]}async function uq(e,t){return(await qt(e,`/kortix/services/${encodeURIComponent(t)}/logs`)).logs??[]}async function pq(e,t,n){let r=n==="delete",s=r?`/kortix/services/${encodeURIComponent(t)}`:`/kortix/services/${encodeURIComponent(t)}/${n}`;return qt(e,s,{method:r?"DELETE":"POST"})}async function dq(e,t){return qt(e,`/kortix/services/reconcile${t?"?reload=true":""}`,{method:"POST"})}async function gq(e,t){return qt(e,"/kortix/services/register",{method:"POST",body:JSON.stringify(t)})}var We=new Map,iv=256,kn=class extends Error{constructor(t="[kortix-runtime] Server URL not ready \u2014 sandbox is still loading"){super(t),this.name="RuntimeNotReadyError"}};function ht(){let e=Ge();if(!e)throw new kn;return Ve(e)}function Ve(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(!Ys())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:L,eventTransport:th});return We.set(e,n),We.size>iv&&We.delete(We.keys().next().value),n}function Pq(e){We.delete(e)}function xq(){We.clear()}var is=new Map;function wq(e){if(!e)throw new Error("[kortix-runtime] getPublicClientForUrl called without a url");let t=is.get(e);if(t)return t;let n=Sn({baseUrl:e,fetch});return is.set(e,n),n}function kq(e){is.delete(e)}function vq(){is.clear()}async function av(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 Aq(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 L(`${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 av(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(c){throw new P(`System reload returned malformed JSON from ${n}: ${c instanceof Error?c.message:String(c)}`,{status:r.status,response:r,code:"RUNTIME_UNAVAILABLE"})}let a=i===!0||typeof i=="object"&&i!==null&&i.ok===!0;return{success:a,mode:e,steps:a?[e==="full"?"refreshed workspace and restarted runtime":"reloaded config in place"]:[],errors:a?[]:[`the sandbox did not confirm the reload (${n})`]}}var ph="frontend";function as(e,t,n){(e==="error"?console.error:e==="warn"?console.warn:e==="debug"?console.debug:console.log)(`[${ph}] ${t}`,...n?[n]:[]);try{ht().app.log({service:ph,level:e,message:t,extra:n})}catch{}}var He={debug:(e,t)=>as("debug",e,t),info:(e,t)=>as("info",e,t),warn:(e,t)=>as("warn",e,t),error:(e,t)=>as("error",e,t)};var cv=16,lv=8,dh=6e4,uv=250,pv=1e3,dv=3e4,gv=5,mv=.5,fv=3e3,yv=3e4,gh=2e4,hv=2e3,mh=8;function _v(e){if(e.type==="session.status")return`session.status:${e.properties.sessionID}`;if(e.type==="lsp.updated")return"lsp.updated"}function bv(e,t){if(e?.type!=="message.part.delta"||t.type!=="message.part.delta")return;let n=e.properties,r=t.properties;if(n.partID!==r.partID||n.field!==r.field||n.messageID!==r.messageID||n.sessionID!==r.sessionID)return;let s=e.coalesced??[e];return s.push(t),{...t,properties:{...r,delta:n.delta+r.delta},coalesced:s}}function fh(e,t){let n=[],r,s=0,o=new Map,i=()=>{if(r&&e.clearTimeout(r),r=void 0,n.length===0)return;let c=n;n=[],o.clear(),s=e.now();for(let p of c)p&&t(p.event)},a=()=>{if(r)return;let c=e.now()-s;r=e.setTimeout(i,Math.max(0,cv-c))};return{push(c){let p=bv(n[n.length-1]?.event,c);if(p)n[n.length-1]={type:p.type,event:p};else{let d=_v(c);if(d){let g=o.get(d);g!==void 0&&(n[g]=void 0),o.set(d,n.length)}n.push({type:c.type,event:c})}a()},flush:i,clearTimer:()=>{r&&e.clearTimeout(r)}}}function yh(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 ki(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 Sv(e,t,n,r){return new Promise((s,o)=>{let i=!1,a=t.setTimeout(()=>{i||(i=!0,He.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:fv,sseMaxRetryDelay:yv,sseMaxRetryAttempts:1}).then(c=>{i||(i=!0,t.clearTimeout(a),s(c))},c=>{i||(i=!0,t.clearTimeout(a),o(c))})})}async function Pv(e,t,n,r,s){let o=!1,i=t.now(),a=e[Symbol.asyncIterator]();for(;!n.aborted;){let c=a.next().then(f=>({kind:"next",result:f}),f=>({kind:"error",error:f})),p=yh(n),d=await Promise.race([c,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<lv)&&(await new Promise(f=>t.setTimeout(f,0)),i=t.now()))}return o}function hh(e,t,n){let r=t?.cause?.status;return!e&&(typeof r=="number"&&r>=400||n<hv)}function _h(e,t,n){He.error("SSE event stream parked \u2014 giving up after consecutive hard failures",{consecutiveFailures:t,lastError:String(n)}),ki(e,r=>r.onParked,{consecutiveFailures:t,lastError:n})}function bh(e,t,n){let r=t?uv:Math.min(pv*2**Math.min(e-1,gv),dv);return Math.round(r*(1+mv*(n.random?.()??0)))}function Sh(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 Ph(e){let{client:t,t:n,connectTimeoutMs:r,heartbeatTimeoutMs:s,outerSignal:o,retryCount:i,setConnectionState:a,onConnected:c,coalescer:p}=e,d=!1,g=!1,m,f=null,_=new AbortController;a("connecting");let y=yh(o);y.promise.then(()=>_.abort());try{let{stream:k}=await Sv(t,n,r,_);c();let R=()=>{n.clearTimeout(m),m=n.setTimeout(()=>{He.warn("SSE heartbeat timeout, forcing reconnect"),_.abort()},s)};R(),d=await Pv(k,n,_.signal,p,()=>{a("open"),R()}),g=d}catch(k){if(f=k,o.aborted)return{streamHadWork:d,stableConnection:g,error:f};let R=String(k),I=en(k)||en(k?.cause);if(He.error("SSE event stream error",{error:R,retryCount:i,isAuthError:I}),I)try{uo(),await lo(),He.info("SSE: refreshed auth token after auth error")}catch(b){He.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 xv(e){return{type:"heartbeat-gap",gapMs:e}}function wv(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 kv={now:()=>Date.now(),setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),random:()=>Math.random()},vv=5e3,Av=1e4,Rv=4,vn=new WeakMap;function Tv(e,t,n){let r=t.timers??kv,s=t.connectTimeoutMs??gh,o=t.heartbeatTimeoutMs??dh,i=t.maxConsecutiveHardFailures??mh,a=new AbortController,c=(k,...R)=>ki(n,k,...R),p=null,d=!1,g=k=>{p!==k&&(p=k,k&&c(R=>R.onConnectionChange,k))},m=r.now(),f=null,_=fh(r,k=>{m=r.now(),c(R=>R.onEvent,k)}),y={client:e,t:r,connectTimeoutMs:s,heartbeatTimeoutMs:o,outerSignal:a.signal,setConnectionState:g,onConnected:()=>{if(f){let k=r.now()-f.lastActivityAt,R=f.eventful;f=null,(R||k>vv)&&c(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 Ph({...y,retryCount:k});if(a.signal.aborted)break;let h=M.error,{streamHadWork:x,stableConnection:S}=M,v=r.now()-b;if(R=hh(x,h,v)?R+1:0,R>=i){_h(n,R,h),p=null,d=!0;break}g("lost"),f={lastActivityAt:m,eventful:(f?.eventful??!1)||x},I=S&&v<Av?I+1:0;let w=S&&I<=Rv;w?k=0:(k++,k>1&&He.warn("SSE event stream reconnecting",{retryCount:k})),await Sh(r,a.signal,bh(k,w,r))}})(),{subscribers:n,connectionState:()=>p,isParked:()=>d,teardown:()=>{p=null,a.abort(),_.clearTimer()}}}function vi(e){let{onEvent:t,onGapRehydrate:n,onParked:r,onConnectionChange:s,signal:o}=e,i=e.client??(e.url?Ve(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},c=vn.get(i);if(c?.isParked()&&(vn.delete(i),c=void 0),!c)c=Tv(i,e,new Set([a])),vn.set(i,c);else{c.subscribers.add(a);let f=c.connectionState();f&&s?.(f)}let p=c,d=!1,g=()=>{d||(d=!0,o&&o.removeEventListener("abort",m),p.subscribers.delete(a),p.subscribers.size===0&&(p.teardown(),vn.get(i)===p&&vn.delete(i)))},m=()=>g();return o&&(o.aborted?g():o.addEventListener("abort",m,{once:!0})),{close:g}}function xh(e){return{abort:async()=>{let{runtimeSessionId:t,runtimeUrl:n}=await e.ensureReady();return Ve(n).session.abort({sessionID:t})},rewind:async t=>{let{runtimeSessionId:n,runtimeUrl:r}=await e.ensureReady();return Ve(r).session.revert({sessionID:n,messageID:t})},restoreRewind:async()=>{let{runtimeSessionId:t,runtimeUrl:n}=await e.ensureReady();return Ve(n).session.unrevert({sessionID:t})},stream:async t=>{let{runtimeUrl:n}=await e.ensureReady();return vi({url:n,onEvent:t.onEvent,onGapRehydrate:t.onGapRehydrate,signal:t.signal})}}}function kh(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 Ti(e){let t=await e.text().catch(()=>""),n=null;try{n=JSON.parse(t)}catch{}return n?.error||t||e.statusText||`HTTP ${e.status}`}function ae(e){let t=(e??Ge()).trim();if(!t)throw new kn;return t}async function In(e,t){let n=await L(`${ae(t)}${e}`);if(!n.ok)throw new P(await Ti(n),{status:n.status,response:n});return n.json()}async function Ci(e,t,n,r,s){let o=await L(`${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 Ti(o)}`,{status:o.status,response:o});return o.json()}var Ii=["/workspace","/tmp","/home","/opt"],Cv=Ii.filter(e=>e!=="/workspace");function vh(e){return Ii.some(t=>e===t||e.startsWith(`${t}/`))}function En(e){return vh(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(Cv.some(n=>t===n||t.startsWith(`${n}/`)))return t;for(;t.startsWith("/");)t=t.slice(1);return t}var Ah=_t;async function Mn(e,t){let n=ae(t),r=_t(e)||".";return(await In(`/file?path=${encodeURIComponent(r)}`,n)).map(o=>({...o,path:o.absolute||`/workspace/${o.path}`}))}async function On(e,t){let n=_t(e);return In(`/file/content?path=${encodeURIComponent(n)}`,t)}async function Iv(e,t,n){let r=ae(n),s=_t(e),o=await L(`${r}/file/raw?path=${encodeURIComponent(s)}`);if(!o.ok)throw new P(await Ti(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 Ev=8,cs=0,Rh=[];async function Mv(){if(cs<Ev){cs++;return}await new Promise(e=>Rh.push(e)),cs++}function Ov(){cs--,Rh.shift()?.()}function Dv(e,t){let n=ae(t);return wr(`${n}/file/raw?path=${encodeURIComponent(_t(e))}`)}async function Dn(e,t){await Mv();try{let n=ae(t);try{return await Iv(e,void 0,n)}catch{}let r=await On(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{Ov()}}async function ls(e){return In("/file/status",ae(e))}async function us(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)),In(`/find/file?${s.toString()}`,r)}async function ps(e,t){let n=ae(t);return(await In(`/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 An=[400,1200],jv=e=>e===408||e===429||e===502||e===503||e===504,wh=e=>new Promise(t=>setTimeout(t,e));function Lv(e){let t=e?.name;return t==="TimeoutError"||t==="AbortError"}var Ai=3e4,Th=15*6e4,$v=256;function Rn(e){if(typeof e!="number"||!Number.isFinite(e)||e<=0)return Ai;let t=Ai+e/$v;return Math.min(Th,Math.max(Ai,Math.round(t)))}async function Uv(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<=An.length;s++){let o;try{o=await t(e())}catch(a){if(n=a,Lv(a)||s===An.length)break;await wh(An[s]);continue}if(o.ok)return o.json();let i=await Uv(o);if(n=new P(`Upload failed (${o.status}): ${i}`,{status:o.status,response:o}),!jv(o.status)||s===An.length)throw n;await wh(An[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 Ri=8*1024*1024;function Fv(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 Ch(e,t){try{e?.onProgress?.(t)}catch{}}function Ih(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 Nv(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,s){let o=typeof r=="string"?r:void 0,i=typeof r=="string"?s:r,a=ae(o),c=Rn(e.size),p=n||(e instanceof File?e.name:"")||"";if(e.size<=Ri){let d=await Tn(()=>Ih(e,t,p),g=>L(`${a}/file/upload`,{method:"POST",body:g},{timeoutMs:c}));return Fv(d[0],e.size),Ch(i,{loadedBytes:e.size,totalBytes:e.size}),d}return Bv(e,t,p,a,i)}async function Bv(e,t,n,r,s){let i=(await Tn(()=>Ih(new Blob([],{type:e.type}),t,n),c=>L(`${r}/file/upload`,{method:"POST",body:c},{timeoutMs:Rn(0)})))[0]?.path;if(!i)throw new P("Upload reservation returned no file path",{code:"UPLOAD_NO_RESULT"});let a=Nv(i);if(!a.name)throw new P(`Upload reservation returned an invalid file path: ${i}`,{code:"UPLOAD_INVALID_PATH"});try{for(let c=0;c<e.size;c+=Ri){let p=Math.min(e.size,c+Ri),d=e.slice(c,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",c===0?"true":"false"),m.append("offset",String(c)),m.append("file",d,a.name),m},m=>L(`${r}/file/append`,{method:"POST",body:m},{timeoutMs:Rn(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"});Ch(s,{loadedBytes:p,totalBytes:e.size})}}catch(c){throw await Gt(i,r).catch(()=>{}),c}return[{path:i,size:e.size}]}function Kv(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=>L(`${r}/file/upload`,{method:"POST",body:s},{timeoutMs:qv}))}var qv=Th;function Gv(e,t,n){let r=ae(n),s=Rn(t.size);return Tn(()=>{let o=new FormData;return o.append(e,t,e.split("/").pop()||"file"),o},o=>L(`${r}/file/upload`,{method:"POST",body:o},{timeoutMs:s}))}var Cn=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 ds(e,t){let n=ae(t),r=e.trim(),o=(r.startsWith("/")?r:`/${r}`).split("/"),i=o.pop()||"untitled",a=o.join("/")||"/workspace",c=En(`${a}/${i}`),p=[];try{p=await Mn(Eh(c),n)}catch(g){if(!(g instanceof P&&g.status===404))throw g}if(p.some(g=>g.name===Mh(c)))throw new Cn(c);let d=await Oh(c,new Blob([],{type:"application/octet-stream"}),n,{overwrite:!1});return[{path:d.path,size:d.bytes}]}async function gs(e,t,n){let r=ae(n);return Gv(t,await Dn(e,r),r)}function Wv(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function Eh(e){let t=e.lastIndexOf("/");return t<=0?"/":e.slice(0,t)}function Mh(e){return e.slice(e.lastIndexOf("/")+1)}function Vv(){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 ms(e,t,n){let r=ae(n),s=En(Wv(e.trim()));return Oh(s,t,r,{overwrite:!0})}async function Oh(e,t,n,r){let s=Mh(e);if(!s)throw new P(`writeFile needs a file path, got "${e}"`,{code:"INVALID_PATH"});let o=Eh(e);await Ln(o,n).catch(()=>{});let i=Vv(),a=await jn(t,o,`.${s}.kortix-write-${i}`,n),c=a[0]?.path;if(!c)throw new P(`Upload returned no file for ${e}`,{code:"UPLOAD_NO_RESULT"});let p=En(c);try{await Dh(p,e,n,r.overwrite)}catch(g){throw await Gt(p,n).catch(()=>{}),!r.overwrite&&g instanceof P&&g.status===409?new Cn(e):g}let d=a[0]?.size;return{path:e,bytes:typeof d=="number"?d:t.size}}async function Gt(e,t){return Ci("/file","DELETE",{path:e},"Delete",t)}async function Ln(e,t){return Ci("/file/mkdir","POST",{path:e},"Mkdir",t)}async function fs(e,t,n){return Dh(e,t,ae(n),!0)}async function Dh(e,t,n,r){return Ci("/file/rename","POST",r?{from:e,to:t}:{from:e,to:t,overwrite:!1},"Rename",n)}async function jh(){return kh(await ht().project.current())}async function Ei(){return kh(await ht().global.health())}async function Lh(){try{return(await Ei()).healthy===!0}catch{return!1}}var Hv={list:Mn,read:On,readBlob:Dn,status:ls,findFiles:us,findText:ps,upload:jn,write:ms,create:ds,copy:gs,remove:Gt,mkdir:Ln,rename:fs,currentProject:jh,health:Ei,isReachable:Lh,toDaemonPath:_t,toSandboxAbsolutePath:En,toWorkspaceRelative:Ah};function $h(e){return{list:async t=>Mn(t,(await e()).runtimeUrl),read:async t=>On(t,(await e()).runtimeUrl),readBlob:async t=>Dn(t,(await e()).runtimeUrl),status:async()=>ls((await e()).runtimeUrl),findFiles:async(t,n)=>us(t,n,(await e()).runtimeUrl),findText:async t=>ps(t,(await e()).runtimeUrl),upload:async(t,n,r,s)=>jn(t,n,r,(await e()).runtimeUrl,s),write:async(t,n)=>ms(t,n,(await e()).runtimeUrl),create:async t=>ds(t,(await e()).runtimeUrl),copy:async(t,n)=>gs(t,n,(await e()).runtimeUrl),remove:async t=>Gt(t,(await e()).runtimeUrl),mkdir:async t=>Ln(t,(await e()).runtimeUrl),rename:async(t,n)=>fs(t,n,(await e()).runtimeUrl)}}function Uh(e){return{get:t=>Ir(e.projectId,e.sessionId,t),presence:(t,n)=>l.put(`/projects/${e.projectId}/sessions/${e.sessionId}/presence`,t,{showErrors:!1,keepalive:n?.keepalive??!t.active}),cost:()=>Kr(e.sessionId,{projectId:e.projectId}),update:t=>Xp(e.projectId,e.sessionId,t),delete:()=>(e.forgetReady(),Zp(e.projectId,e.sessionId)),restore:()=>td(e.projectId,e.sessionId),recover:()=>ed(e.projectId,e.sessionId),start:(...t)=>gt(e.projectId,e.sessionId,...t),startOrThrow:(...t)=>Td(e.projectId,e.sessionId,...t),restart:()=>(e.forgetReady(),Dr(e.projectId,e.sessionId)),stop:()=>(e.forgetReady(),jr(e.projectId,e.sessionId)),configState:()=>nd(e.projectId,e.sessionId),reloadConfig:t=>(e.forgetReady(),rd(e.projectId,e.sessionId,t)),reloadConfigStream:(...t)=>(e.forgetReady(),sd(e.projectId,e.sessionId,...t)),setSharing:t=>Ep(e.projectId,e.sessionId,t),previews:()=>$p(e.projectId,e.sessionId),participants:()=>Mp(e.projectId,e.sessionId),watch:()=>Op(e.projectId,e.sessionId),setWatch:t=>Dp(e.projectId,e.sessionId,t),setPinned:t=>jp(e.projectId,e.sessionId,t),setArchived:t=>Lp(e.projectId,e.sessionId,t),commit:t=>pp(e.projectId,e.sessionId,t),publicShares:{list:()=>Up(e.projectId,e.sessionId),create:(...t)=>Fp(e.projectId,e.sessionId,...t),revoke:(...t)=>Np(e.projectId,e.sessionId,...t)}}}function Fh(e){return{reminders:{list:()=>Lm(e.projectId,e.sessionId),create:t=>$m(e.projectId,e.sessionId,t),update:(t,n)=>Do(e.projectId,e.sessionId,t,n),remove:t=>jo(e.projectId,e.sessionId,t)},audit:(t,n)=>qp(e.projectId,e.sessionId,t,n),attachments:{upload:(t,n)=>vy(e.projectId,e.sessionId,t,n),read:(t,n)=>Ay(`kortix-attachment://${e.projectId}/${e.sessionId}/${t}`,n)},transcript:t=>Gp(e.projectId,e.sessionId,t),messageAuthors:()=>cd(e.projectId,e.sessionId),modelUsage:()=>ld(e.projectId,e.sessionId),transcriptSync:t=>Er(e.projectId,e.sessionId,t),log:t=>Wp(e.projectId,e.sessionId,t),turn:()=>Mr(e.projectId,e.sessionId),prompts:{create:t=>Or(e.projectId,e.sessionId,t),list:()=>Vp(e.projectId,e.sessionId),remove:t=>Hp(e.projectId,e.sessionId,t),retry:t=>Jp(e.projectId,e.sessionId,t),edit:(t,n)=>zp(e.projectId,e.sessionId,t,n),interrupt:t=>Yp(e.projectId,e.sessionId,t),hold:t=>Qp(e.projectId,e.sessionId,t)},ensureReady:e.ensureReady}}function Yv(e,t){return e?.some(n=>n.startsWith("session."))?e.includes(t):!0}var Jv=["control_plane","provider_ingress","daemon","upstream_port"];function Nh(e){return typeof e=="string"&&Jv.includes(e)?e:null}function Bh(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 Kh(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 L(`${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=Nh(r.headers.get("X-Kortix-Proxy-Hop"))??Nh(o?.hop),c=Number(r.headers.get("X-Kortix-Upstream-Status")),p=o?.upstream_status,d=Number.isFinite(c)&&c>0?c:typeof p=="number"?p:null;return{status:r.status,ok:r.ok,health:i,body:s,hop:a,upstreamStatus:d}}var qh=/https?:\/\/(?:localhost|127\.0\.0\.1):\d{1,5}[^\s)"'<>]*/g,Gh=/^https?:\/\/p(\d+)-([^.]+)\.localhost(?::(\d+))?(\/.*)?$/,Wh=/^https?:\/\/(?:dev|staging|prod|preview)-p(\d+)-([a-z0-9-]+)\.[^/]+?(?::(\d+))?(\/.*)?$/i,Vh=new Set([22,4096,parseInt(tt.KORTIX_MASTER,10)]);function Qv(e){return Gh.test(e)}function ys(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 Xv(e){let t=e.indexOf("](");return t===-1?e:e.slice(0,t)}var Zv=new Set(["'",'"',"`","<","(","["]),eA=new Set([">","'",'"',"`",")","]",",",";",".","!","?"]);function tA(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&&Zv.has(e[t]);)t++;for(;n>t&&eA.has(e[n-1]);)n--;return e.slice(t,n)}function nA(e){return e.match(/https?:\/\/(?:localhost|127\.0\.0\.1):\d{1,5}[^\s"'<>)]*/i)?.[0]??null}var rA=/^\/proxy\/(\d{1,5})(\/.*)?$/,sA=/^\/(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 oA(e){if(!e)return!1;try{let t=new URL(e);return t.hostname!=="localhost"&&t.hostname!=="127.0.0.1"?!1:sA.test(t.pathname)}catch{return!1}}function hs(e){if(!e)return null;let t=tA(Xv(e.trim())),n=Qh(t);if(n){let r=ys(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 c=r.pathname.match(rA);if(c){let p=parseInt(c[1],10);if(p>=1&&p<=65535)return s=p,o=ys(`${c[2]||"/"}${r.search}${r.hash}`),{originalUrl:`http://localhost:${s}${o}`,port:s,path:o}}}let a=ys(o);return{originalUrl:`${r.protocol}//${r.hostname}:${s}${a}`,port:s,path:a}}catch{let r=nA(e);return r&&r!==e?hs(r):null}}function iA(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(([c,p])=>o>=c&&i<=p)||t.push([o,i])}return t}function aA(e,t){return t.some(([n,r])=>e>=n&&e<r)}function cA(e){let t=[],n=new Set,r=iA(e);qh.lastIndex=0;let s;for(;(s=qh.exec(e))!==null;){let o=hs(s[0]);if(!o)continue;let{originalUrl:i,port:a,path:c}=o;a<1||a>65535||Vh.has(a)||n.has(i)||(n.add(i),t.push({originalUrl:i,port:a,path:c,startIndex:s.index,endIndex:s.index+i.length,inCodeBlock:aA(s.index,r)}))}return t}function iG(e){return cA(e).length>0}function lA(e){try{let{hostname:t}=new URL(e);return t==="localhost"||t==="127.0.0.1"}catch{return!1}}function Hh(e){return e.trim().toLowerCase().split("_").join("-")}function zh(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function uA(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(Hh(n.sandboxId));return`${zh(s)}${t}`}function pA(e){return e.sandboxId.trim().length>0}function bt(e,t,n){let r=ys(t);if(!pA(n))return fA(e,r);let s=uA(e,r,n);return s||(lA(n.apiBaseUrl)?`http://p${e}-${Hh(n.sandboxId)}.localhost:${n.backendPort}${r}`:`${zh(n.apiBaseUrl)}/p/${n.sandboxId}/${e}${r}`)}function aG(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 dA(e){return`/open?path=/${(e.startsWith("/workspace")?e:`/workspace/${e.replace(/^\/+/,"")}`).split("/").filter(Boolean).map(r=>encodeURIComponent(r)).join("/")}`}function cG(e){return`http://localhost:3211${dA(e)}`}function gA(){return"/health"}function lG(e){return bt(3211,gA(),e)}function uG(e,t){return bt(e,"/",t)}function mA(e){let t=hs(e);return!(!t||Vh.has(t.port)||oA(e))}function Yh(e,t){if(!e)return e;let n=hs(e);return n?mA(n.originalUrl)?bt(n.port,n.path,t):n.originalUrl:e}function fA(e,t="/"){return`http://localhost:${e}${t}`}var Jh=/^https?:\/\/[^/]+\/v1\/p\/([^/]+)\/(\d+)(\/.*)?$/;function Qh(e){let t=e.match(Gh);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(Wh);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(Jh);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 pG(e){try{let t=Qh(e);return t?`http://localhost:${t.port}${t.path}`:null}catch{return null}}function dG(e){return Qv(e)||Wh.test(e)||Jh.test(e)}function gG(e){try{let{hostname:t,port:n}=new URL(e);return(t==="localhost"||t==="127.0.0.1")&&n!==""}catch{return!1}}var $n="/web-proxy/";function mG(e,t){try{let n=new URL(e);if(n.protocol!=="http:"&&n.protocol!=="https:")return null;let r=n.protocol.replace(":",""),s=`${$n}${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 fG(e){try{let t=new URL(e),n=t.pathname.indexOf($n);if(n===-1)return null;let s=t.pathname.slice(n+$n.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 yG(e){try{return new URL(e).pathname.includes($n)}catch{return e.includes($n)}}function hG(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 _G(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 Xh(e){return{health:t=>Kh(e.tryResolveReady()?.runtimeUrl??null,t),previewUrl:(t,n="/")=>bt(t,n,e.resolvePreviewOptsForSandbox(e.requireReady("previewUrl").sandboxId)),proxyUrl:t=>Yh(t,e.resolvePreviewOptsForSandbox(e.requireReady("proxyUrl").sandboxId)),sandboxPortUrl:t=>Fe(e.requireReady("sandboxPortUrl").sandboxId,t)}}function Mi(e,t,n,r){let s,o,{persistedPromptDefaults:i,clearPersistedDefaults:a}=Fy(e,t),{ensureReady:c,tryResolveReady:p,requireReady:d,forgetReady:g}=qy(e,t,n),m={projectId:e,sessionId:t,ensureReady:c,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{...Uh(m),...Fh(m),...Xh(m),...zy(m),...eh(m),...xh(m),files:$h(c),...Hy(m),get runtime(){return Ve(d("runtime").runtimeUrl)}}}function Zh(e){return{apps:{list:()=>mf(e),create:t=>ff(e,t),get:t=>$o(e,t),update:(...t)=>yf(e,...t),access:{get:(...t)=>Sf(e,...t),update:(...t)=>xf(e,...t),session:(...t)=>wf(e,...t),agents:t=>Pf(e,t)},remove:t=>hf(e,t),token:t=>_f(e,t),authEnv:t=>bf(e,t),artifacts:{register:t=>Uo(e,t),uploadArchive:(...t)=>kf(e,...t),finalize:(...t)=>Fo(e,...t)},deployments:{create:(...t)=>vf(e,...t),list:t=>Af(e,t),get:(...t)=>Rf(e,...t),logs:(...t)=>Tf(e,...t),remove:(...t)=>Ef(e,...t)},start:t=>Cf(e,t),stop:t=>If(e,t),rollback:(...t)=>Mf(e,...t),machines:{list:t=>Of(e,t),start:(t,n)=>Df(e,t,n),stop:(t,n)=>jf(e,t,n),restart:(t,n)=>Lf(e,t,n),destroy:(t,n)=>$f(e,t,n)},scale:(...t)=>Uf(e,...t),exec:(...t)=>Ff(e,...t),volumes:{list:t=>Nf(e,t),create:(...t)=>Bf(e,...t),update:(...t)=>Kf(e,...t),destroy:(...t)=>qf(e,...t),snapshots:(...t)=>Gf(e,...t),snapshot:(...t)=>Wf(e,...t),restore:(...t)=>Vf(e,...t),fork:(...t)=>Hf(e,...t)}}}}function e_(e){return{list:()=>sl(e),invite:(...t)=>al(e,...t),update:(...t)=>ol(e,...t),revoke:t=>il(e,t),pendingInvites:()=>cl(e),resendInvite:(...t)=>ul(e,...t),revokeInvite:(...t)=>ll(e,...t),requests:()=>tl(e),approveRequest:(...t)=>nl(e,...t),rejectRequest:(...t)=>rl(e,...t),groupGrants:()=>pl(e),attachGroupGrant:(...t)=>dl(e,...t),updateGroupGrant:(...t)=>gl(e,...t),detachGroupGrant:t=>ml(e,t),resourceGrants:{list:()=>fl(e),create:t=>yl(e,t),remove:t=>hl(e,t)}}}function t_(e){return{tokens:{list:()=>Hm(e),create:t=>zm(e,t),revoke:t=>Ym(e,t)},setupLinks:{requestSecret:t=>rf(e,t),requestConnector:t=>sf(e,t)},validateManifest:t=>Mc(e,t),gitToken:()=>Oc(e),agentIdentities:()=>om(e),secrets:{list:()=>Pl(e),upsert:t=>xl(e,t),setStrategy:(...t)=>wl(e,...t),broker:(...t)=>kl(e,...t),remove:t=>Tl(e,t),setPersonal:(...t)=>Cl(e,...t),removePersonal:t=>Il(e,t),setGitCredential:t=>Rl(e,t),listProviderOAuth:()=>vl(e),startProviderOAuth:(...t)=>io(e,...t),pollProviderOAuth:(...t)=>ao(e,...t),removeProviderOAuth:t=>Al(e,t)},access:e_(e)}}function n_(e){return{list:()=>Gl(e),listAll:()=>Wl(e),reconcile:(...t)=>Vl(e,...t),reconcileMember:(...t)=>Hl(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 _s(e){return{catalog:t=>sn(e,t),tools:()=>po(e),search:(...t)=>ql(e,...t),describe:(...t)=>go(e,...t),call:(...t)=>It(e,...t),callAction:(t,n,r,s)=>It(e,`${t}.${n}`,r,s),accounts:(...t)=>mo(e,...t),uploadAttachment:(...t)=>fo(e,...t)}}function Oi(e,t){return{slug:t,run:(r,s,o)=>So(e,t,r,s,o),call:(r,s,o)=>It(e,`${t}.${r}`,s,o),describe:async r=>r!==void 0?go(e,`${t}.${r}`):(await sn(e,{slug:t,includeSchemas:!0,includeOutputSchemas:!0})).find(o=>o.slug===t)??null,accounts:()=>mo(e,t),paginate:(r,s,o)=>Au(e,t,r,s,o),uploadAttachment:(r,s)=>fo(e,r,{...s,connector:t})}}var yA=100,r_=0,hA=new Set(["attachment_size_mismatch","attachment_failed"]),s_=()=>new P("Attachment expired. Attach the file again.",{code:"attachment_expired"});function Di(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 _A(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),c=()=>{o&&clearTimeout(o),o=void 0};return{onProgress:p=>{if(!t()||a(p)===a(e.item.receivedBytes)||(r=p,o))return;let d=s+yA-Date.now();if(d<=0)return i();o=setTimeout(i,d),typeof o=="object"&&"unref"in o&&o.unref()},onProcessing:()=>{c(),r=void 0,t()&&(e.item={...e.item,status:"processing",receivedBytes:e.item.size},n())},clear:c}}function o_(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,c,p={attachments:[]},d=()=>[...r.values()].filter(h=>!h.handedOff);function g(h,x){h.removalDeleted||(h.removalDeleted=!0,cn(e,x).catch(()=>{}))}function m(){c&&clearTimeout(c);let h=d().map(({item:S})=>S);(h.length!==p.attachments.length||h.some((S,v)=>S!==p.attachments[v]))&&(p={attachments:h});let x=Math.min(...h.filter(S=>S.status==="ready").map(S=>Date.parse(S.attachment.expires_at)));Number.isFinite(x)&&!a&&(c=setTimeout(()=>{for(let S of d())S.item.status==="ready"&&Date.parse(S.item.attachment.expires_at)<=Date.now()&&(S.item={...S.item,status:"error",error:s_()});m()},Math.min(2147483647,Math.max(0,x-Date.now()))),typeof c=="object"&&"unref"in c&&c.unref());for(let S of s)S();for(let S of[...o])S()}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,C)=>v+C.item.size,0)+h.reduce((v,C)=>v+C,0)>104857600)throw new Error("Message attachments exceed 100 MiB")}function y(h,x,S){let v=++h.generation,C=new AbortController;h.abort=C,h.item={...h.item,status:"uploading",error:void 0};let j=()=>(!a||h.handedOff===!0)&&r.get(h.item.id)===h&&h.generation===v,w=_A(h,j,m);Rr(e,x,{resume:h.upload,signal:C.signal,onUpload:D=>{h.upload=D,h.removed&&(C.abort(),g(h,D.attachment_id))},...w}).then(D=>{j()&&(h.item={...h.item,status:"ready",attachment:Di(D),receivedBytes:D.size})}).catch(D=>{D instanceof P&&hA.has(D.code??"")&&(h.upload=void 0),j()&&(h.item={...h.item,status:D instanceof P&&D.code==="ABORTED"?"aborted":"error",error:D instanceof Error?D:new Error(String(D))})}).finally(()=>{w.clear(),h.abort===C&&(h.abort=void 0),S()})}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(S=>S.size));let x=h.map(S=>{let v=`attachment-${++r_}`;return r.set(v,{generation:0,item:{id:v,file:S,filename:S.name,mime:S.type||"application/octet-stream",size:S.size,status:"pending",receivedBytes:0}}),v});return m(),k(),x}function I(h){let x=h.map(({attachment:v,file:C})=>{try{return{attachment:Di(v),file:C}}catch{return}});_(x.flatMap(v=>v?[v.attachment.size]:[]));let S=x.map(v=>{if(!v)return;let C=`attachment-${++r_}`,{attachment:j,file:w}=v;return r.set(C,{generation:0,item:{id:C,...w?{file:w}:{},filename:j.filename,mime:j.mime,size:j.size,status:"ready",receivedBytes:j.size,attachment:j}}),C});return m(),S}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 S=[...h];return new Promise((v,C)=>{let j=()=>{o.delete(Se),x?.removeEventListener("abort",D)},w=N=>{j(),C(N)},D=()=>w(ke()),Se=()=>{let N=!1;for(let G of S){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=S.map(G=>{let K=Di(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)))}j(),v(z)};if(x?.aborted)return D();o.add(Se),x?.addEventListener("abort",D,{once:!0}),Se()})}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 s_();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 S=x.upload?.attachment_id??x.item.attachment?.attachment_id;S&&x.abort?.abort(),m(),k(),S&&g(x,S)},abort:b,submit(h){if(!a){for(let x of h){let S=r.get(x);S&&(S.handedOff=!0)}m()}},reclaim(h){if(!a){for(let x of h){let S=r.get(x);S&&(S.handedOff=!1)}m()}},whenReady:M,forget(h=d().map(x=>x.item.id)){for(let x of h){let S=r.get(x);S&&(S.generation++,S.abort?.abort(),r.delete(x))}m(),k()},dispose(){if(!a){a=!0,c&&clearTimeout(c);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&&cn(e,x).catch(()=>{})}s.clear(),m()}},getSnapshot:()=>p,subscribe(h){return s.add(h),()=>{s.delete(h)}}}}function i_(e){return{attachments:{upload:(...t)=>Rr(e,...t),delete:(...t)=>cn(e,...t),createController:t=>o_(e,t)},get:t=>Tt(e,t),detail:()=>fr(e),skills:{create:(...t)=>Bc(e,...t)},audit:t=>Qm(e,t),update:t=>_r(e,t),archive:()=>br(e),llmCatalog:()=>yr(e),modelPicker:()=>hr(e),modelAccess:()=>Vr(e),setModelAccess:t=>Hr(e,t),sandboxHealth:()=>xr(e),onboardingComplete:(...t)=>Nc(e,...t)}}function a_(e){return{sessions:{list:t=>Dt(e,t),listPage:t=>Ip(e,t),create:t=>jt(e,t),ensureWarm:()=>Bp(e),claimWarm:t=>Kp(e,t)},review:{list:t=>vm(e,t),summary:()=>Am(e),get:t=>Rm(e,t),submit:t=>Tm(e,t),act:(...t)=>Cm(e,...t),bulkAct:t=>Im(e,t)},approvals:{list:t=>_l(e,t),resolve:(...t)=>Sl(e,...t),sessionsNeedingInput:t=>bl(e,t)}}}function c_(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)},...a_(e)}}function l_(e){return{policies:{list:()=>Ru(e),set:(...t)=>Tu(e,...t)},reminders:{list:()=>Bm(e),updateMany:(...t)=>Fm(e,...t),removeMany:(...t)=>Nm(e,...t)},triggers:{list:()=>ud(e),eventApps:()=>Pd(e),eventTypes:(...t)=>Sd(e,...t),create:(...t)=>pd(e,...t),update:(...t)=>dd(e,...t),remove:(...t)=>gd(e,...t),fire:((t,n)=>yd(e,t,n)),runs:(...t)=>hd(e,...t),projectRuns:(...t)=>_d(e,...t),replay:(...t)=>bd(e,...t),setActivation:(...t)=>md(e,...t)},...c_(e)}}function u_(e,t){return{connectors:{..._s(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)=>xu(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)=>yo(e,...n),sections:(...n)=>Su(e,...n),detail:(...n)=>ho(e,...n)}},...l_(e)}}function p_(e){return{gateway:{logs:t=>Mg(e,t),log:t=>Og(e,t),overview:t=>Dg(e,t),series:t=>jg(e,t),breakdown:t=>Lg(e,t),sessions:t=>$g(e,t),errors:t=>Ug(e,t),budgets:()=>Fg(e),setBudget:t=>Ng(e,t),deleteBudget:t=>Bg(e,t),keys:()=>Kg(e),createKey:t=>qg(e,t),revokeKey:t=>Gg(e,t),routing:{get:()=>Tg(e),set:t=>Cg(e,t),reset:()=>Ig(e),preview:t=>Eg(e,t)},playground:(t,n,r)=>Wg(e,t,n,r)}}}function d_(e){return{modelDefaults:{get:()=>Id(e),set:t=>Ed(e,t),clear:t=>Md(e,t)},setDefaultAgent:t=>jd(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)=>Dd(e,...t)}}function g_(e){return{channels:{slack:{installation:()=>gg(e),connect:t=>mg(e,t),mode:()=>fg(e),completeInstall:t=>hg(e,t),manifest:()=>bg(e),disconnect:()=>Sg(e),getFile:t=>Pg(e,t),uploadFile:t=>xg(e,t)},teams:{completeInstall:t=>_g(e,t)},email:{installation:t=>wg(e,t),mode:()=>kg(e),connect:t=>vg(e,t),disconnect:t=>Ag(e,t),updatePolicy:(...t)=>Rg(e,...t)}},updateFeatureFlag:(...t)=>$c(e,...t),updateExperimentalFeature:(...t)=>Uc(e,...t),...d_(e)}}var i1=["screen","actions","audio"],a1=["password_managers","messaging","banking"],c1={localHours:8760,remoteDays:3650},l1=[500,1e3,2e3,5e3,1e4],u1=[720,1080,1440,2160],p1={intervalMs:2e3,maxHeight:1440},bA=/^(?=.{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(/\.$/,""),bA.test(n)?n:null}function g1(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 h1(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,s]of Object.entries(e))s!==void 0&&s!==""&&t.set(r,String(s));let n=t.toString();return n?`?${n}`:""}var m_=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}),ji=(e={})=>({day:e.day,from:e.from,to:e.to,user_id:e.userId,device_id:e.deviceId,display_id:e.displayId});async function f_(e,t={}){return u(await l.get(`${Q(e)}/devices${ze({user_id:t.userId,scope:t.scope})}`))}async function y_(e,t){return u(await l.delete(`${Q(e)}/devices/${t}`))}async function h_(e,t,n){return u(await l.put(`${Q(e)}/devices/${t}/link`,{user_id:n}))}async function __(e){return u(await l.get(`${Q(e)}/enrollment-tokens`))}async function b_(e,t){return u(await l.post(`${Q(e)}/enrollment-tokens`,t))}async function S_(e,t){return u(await l.delete(`${Q(e)}/enrollment-tokens/${t}`))}async function P_(e,t={}){return u(await l.get(`${Q(e)}/enrollments${ze({status:t.status})}`))}async function x_(e,t,n){return u(await l.post(`${Q(e)}/enrollments/${t}/approve`,n?{user_id:n}:{}))}async function w_(e,t){return u(await l.post(`${Q(e)}/enrollments/${t}/deny`,{}))}async function k_(e){return u(await l.get(`${Q(e)}/policy`))}async function v_(e,t){return u(await l.put(`${Q(e)}/policy`,{policy:t}))}async function A_(e,t={}){return u(await l.get(`${Q(e)}/timeline${ze(ji(t))}`))}async function R_(e,t={}){return u(await l.get(`${Q(e)}/timeline/items${ze(ji(t))}`))}async function T_(e,t={}){return u(await l.get(`${Q(e)}/days${ze({tz:t.tz,user_id:t.userId,device_id:t.deviceId})}`))}async function C_(e,t){return u(await l.get(`${Q(e)}/search${m_(t)}`))}async function I_(e,t,n={}){return u(await l.get(`${Q(e)}/frames/${t}${ze({user_id:n.userId,device_id:n.deviceId})}`))}async function E_(e,t,n={}){return u(await l.get(`${Q(e)}/chunks/${t}/media${ze({user_id:n.userId,device_id:n.deviceId})}`))}async function M_(e,t,n){return u(await l.get(`${Q(e)}/devices/${t}/assets/${encodeURIComponent(n)}`))}async function O_(e){return u(await l.get(`/capture/device/grants/${encodeURIComponent(e)}`))}async function D_(e,t){return u(await l.post(`/capture/device/grants/${encodeURIComponent(e)}/approve`,t?{account_id:t}:{}))}async function j_(e){return u(await l.post(`/capture/device/grants/${encodeURIComponent(e)}/deny`,{}))}async function L_(e){return u(await l.get(Q(e)))}async function $_(e,t){return u(await l.patch(Q(e),{enabled:t}))}async function U_(e){return u(await l.get(`/capture/me/search${m_(e)}`))}async function F_(e={}){return u(await l.get(`/capture/me/timeline${ze(ji(e))}`))}async function N_(e){return u(await l.get(`/capture/me/frames/${e}`))}function PA(e){return{workspace:{get:()=>L_(e),setEnabled:t=>$_(e,t)},devices:{list:t=>f_(e,t),revoke:t=>y_(e,t),link:(t,n)=>h_(e,t,n),assetUrl:(t,n)=>M_(e,t,n)},enrollment:{tokens:{list:()=>__(e),create:t=>b_(e,t),revoke:t=>S_(e,t)},list:t=>P_(e,t),approve:(t,n)=>x_(e,t,n),deny:t=>w_(e,t)},policy:{get:()=>k_(e),set:t=>v_(e,t)},timeline:{get:t=>A_(e,t),items:t=>R_(e,t),days:t=>T_(e,t)},search:t=>C_(e,t),frame:(t,n)=>I_(e,t,n),media:(t,n)=>E_(e,t,n)}}var B_={account:e=>PA(e),deviceGrant:O_,approveDevice:D_,denyDevice:j_,me:{search:U_,timeline:F_,frame:N_}};async function K_(e){let t=e?.fetch??T().fetch??((s,o)=>fetch(s,o)),n=e?.backendUrl??T().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 xA=/^v?(\d+)(?:\.(\d+))?(?:\.(\d+))?(?:[-+].*)?$/i;function w1(e,t){let n=o=>{let i=xA.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 wA(){return ht()}var q_=null,G_=!1;function kA(e){let t=q_;q_=e,!(G_||!t)&&(t.backendUrl===e.backendUrl&&t.getToken===e.getToken||(G_=!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 vA(e,t){t?.global!==!1&&kA(e),zs(e,t);let n=Uy(e),{auth:r,accounts:s,iam:o,accountInvites:i}=Oy(),{billing:a,sandboxShares:c}=Iy(),{projects:p,github:d,gitBackend:g,connectStatus:m,marketplace:f}=Cy();function _(y){let k=n_(y);return{...i_(y),...Zh(y),...t_(y),...u_(y,k),...p_(y),...g_(y),connector:R=>Oi(y,R),session:R=>Mi(y,R,e,n)}}return{config:e,auth:r,accounts:s,iam:o,accountInvites:i,projects:p,connectors:_s(),connector:y=>Oi(void 0,y),project:_,session:(y,k)=>Mi(y,k,e,n),github:d,gitBackend:g,billing:a,sandboxShares:c,connectStatus:m,marketplace:f,capture:B_,notifications:{registerDeviceToken:Yf,unregisterDeviceToken:Jf,releaseDeviceToken:Qf,list:Xf,markRead:Zf,preferences:ey,updatePreferences:ty,webPushPublicKey:ny,registerWebPushSubscription:ry,unregisterWebPushSubscription:sy},mobileClientPolicy:K_,validateToken:Tc,runtime:wA}}function AA(){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 RA(){return{pending:[],failed:[],inFlightId:null,inFlightIds:[]}}function Wt(e){return e.inFlightIds?.length?e.inFlightIds:e.inFlightId?[e.inFlightId]:[]}function TA(e,t){return{...e,pending:[...e.pending,{...t,attempts:0}]}}function CA(e){if(Wt(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 IA(e){let t=Wt(e);return t.length===0?e:{...e,pending:e.pending.filter(n=>!t.includes(n.id)),inFlightId:null,inFlightIds:[]}}function EA(e,t){let n=Wt(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 MA(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 OA(e,t){return Wt(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 DA(e,t,n){return Wt(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 jA(e,t,n){let r=Wt(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],[c]=a.splice(s,1);return a.splice(i,0,c),{...e,pending:a}}var W_={thinking:!1,toolDetails:!0,assistantMetadata:!0};function LA(e){return e&&e.charAt(0).toUpperCase()+e.slice(1)}function $A(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 UA(e,t){if(e.type==="text"&&!e.synthetic)return`${e.text??""}
|
|
22
22
|
|
|
23
23
|
`;if(e.type==="reasoning")return t.thinking?`> _Thinking:_
|
|
24
24
|
>
|
|
@@ -51,15 +51,15 @@ ${s}
|
|
|
51
51
|
${e.state.error}
|
|
52
52
|
\`\`\`
|
|
53
53
|
`),n+=`
|
|
54
|
-
`,n}return""}function
|
|
54
|
+
`,n}return""}function FA(e,t){if(!t)return`## Assistant
|
|
55
55
|
|
|
56
|
-
`;let n=e.agent?
|
|
56
|
+
`;let n=e.agent?LA(e.agent):"Assistant",r=e.modelID||"",s="";e.time?.completed&&e.time?.created&&(s=$A(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 NA(e,t,n){let r="";e.role==="user"?r+=`## User
|
|
61
61
|
|
|
62
|
-
`:r+=
|
|
62
|
+
`:r+=FA(e,n.assistantMetadata);for(let s of t)r+=UA(s,n);return r}function BA(e,t,n=W_){let r=`# ${e.title||"Untitled Session"}
|
|
63
63
|
|
|
64
64
|
`;r+=`**Session ID:** \`${e.id}\`
|
|
65
65
|
`,r+=`**Created:** ${new Date(e.time.created).toLocaleString()}
|
|
@@ -67,32 +67,32 @@ ${e.state.error}
|
|
|
67
67
|
|
|
68
68
|
`,r+=`---
|
|
69
69
|
|
|
70
|
-
`;for(let s of t)r+=
|
|
70
|
+
`;for(let s of t)r+=NA(s.info,s.parts,n),r+=`---
|
|
71
71
|
|
|
72
|
-
`;return r}function
|
|
72
|
+
`;return r}function KA(e,t){return`session-${e}.md`}var Li="An error occurred";var qA=["message","error","detail","error_description","msg","errors","data"];function $i(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 GA(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 WA(e){if(!/^\s*<(?:!doctype|html|head|body)\b/i.test(e))return;let t=e.toLowerCase(),n=VA(e,t);if(n)return n;let r=zA(e,t);return r?r.slice(0,200):void 0}function Y_(e){return Number.isNaN(e)?!0:!(e>=48&&e<=57||e>=65&&e<=90||e>=97&&e<=122)}function V_(e,t){let n=e.indexOf(">",t);return n===-1?e.length:n+1}function VA(e,t){let n=0;for(;;){let r=t.indexOf("<title",n);if(r===-1)return;let s=r+6;if(!Y_(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 HA=["script","style"];function zA(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=HA.find(i=>t.startsWith(`<${i}`,s)&&Y_(t.charCodeAt(s+i.length+1)));if(o){let i=t.indexOf(`</${o}`,s);r=i===-1?e.length:V_(e,i);continue}r=V_(e,s)}return n.join(" ").replace(/\s+/g," ").trim()}function YA(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 JA(e){let t=e.replace(/[_-]+/g," ").trim();return t&&t.charAt(0).toUpperCase()+t.slice(1)}function H_(e,t,n){if(typeof e=="string")return bs(e,t,n);if(e&&typeof e=="object")return Ss(e,t,n)}function bs(e,t,n=new WeakSet){let r=$i(e);if(!r)return;if(t>=4)return r;let s=YA(r);if(s)return s;let o=Vt(r);if(o!==void 0)return typeof o=="string"?bs(o,t+1,n):o&&typeof o=="object"?Ss(o,t+1,n):String(o);let i=J_(r);if(i){let a=Vt(i);if(a&&typeof a=="object"){let c=Ss(a,t+1,n);if(c)return c}}if(r.includes("{")){let a=GA(r);if(a)return bs(a,t+1,n)??a}return WA(r)??r}function Ss(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=H_(i,t,n);if(a)return a}return}let r=e;for(let i of qA){let a=H_(r[i],t,n);if(a)return a}let s=r.type??r.code;if(typeof s=="string"&&s.trim())return JA(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"?bs(e,0)??Li:typeof e=="object"?Ss(e,0)??Li:String(e):Li}function Ps(e){let t=QA(e)?.trim();if(!t)return;let n=_e(e);if(!(t===n||$i(t)===n))return t}function QA(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,c)=>typeof i=="string"&&i.trim()!==""&&c.indexOf(i)===a);if(o.length>0)return o.join(`
|
|
73
73
|
|
|
74
|
-
`)}if(typeof t.message=="string"&&t.message)return t.message;try{return JSON.stringify(e)}catch{return}}function
|
|
75
|
-
`||e==="\r"||e==="\u2028"||e==="\u2029"}function
|
|
74
|
+
`)}if(typeof t.message=="string"&&t.message)return t.message;try{return JSON.stringify(e)}catch{return}}function J_(e){let t=e.indexOf("{"),n=e.lastIndexOf("}");if(!(t===-1||n===-1||n<=t))return e.slice(t,n+1)}function XA(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 ZA(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 z_(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=ZA(e.attempt_failures),a=typeof e.requested_model=="string"&&e.requested_model?e.requested_model:void 0,c=typeof e.resolved_model=="string"&&e.resolved_model?e.resolved_model:void 0;return!t&&!n&&!r&&s===void 0&&!o&&!i?void 0:{message:typeof e.message=="string"&&e.message||XA(e)||"",provider:t,code:n,suggestion:r,upstreamStatus:s,requestId:o,attemptFailures:i,...a?{requestedModel:a}:{},...c?{resolvedModel:c}:{}}}function xe(e){if(e==null)return;if(typeof e=="string"){let a=$i(e),c=Vt(a)??Vt(J_(a));return c!==void 0?xe(c):void 0}if(typeof e!="object")return;let t=e,n=z_(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=z_(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 c=xe(a);if(c)return c}}if(o&&typeof o.message=="string"){let a=xe(o.message);if(a)return a}let i=t.cause;if(i&&typeof i=="object"){let a=i.body;if(a!==void 0){let c=xe(a);if(c)return c}}return n}var Q_={};function V(e,t){for(let n of t)Q_[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 eR=[["pty_","pty"],["agent_","delegate"],["task_","delegate"],["session_","sessions"],["trigger_","automations"],["project_","projects"]];function ce(e){let t=e.replace(/^oc[-_]/,"").replace(/-/g,"_"),n=Q_[t];if(n)return n;for(let[r,s]of eR)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 tR=["site","filetype","ext","inurl","allinurl","intitle","allintitle","intext","allintext","inanchor","inbody","before","after","daterange","related","cache","define","link","source","lang","loc","location","imagesize"];function nR(){return new RegExp(`(^|\\s)([-+]?)(${tR.join("|")}):("[^"]*"|\\S+)`,"gi")}function rR(){return/(^|\s)-(?:"[^"]*"|\S+)/g}function sR(){return/(^|\s)(?:OR|AND)(?=\s|$)/g}function oR(e){return e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1):e}function iR(e){return oR(e).replace(/^[a-z]+:\/\//i,"").replace(/^www\./i,"").replace(/\/.*$/,"").trim()}function X_(e){return e.length<=1?e[0]??"":`${e.slice(0,-1).join(", ")} or ${e[e.length-1]}`}function xs(e){let t=typeof e=="string"?e.trim():"";if(!t)return"";let n=[],r=t.replace(nR(),(s,o,i,a,c)=>{if(!i&&a.toLowerCase()==="site"){let p=iR(c);p&&!n.includes(p)&&n.push(p)}return o});return r=r.replace(rR(),"$1").replace(sR(),"$1").replace(/[()]/g," ").replace(/\s+/g," ").trim(),r?n.length>0?`${r} on ${X_(n)}`:r:n.length>0?X_(n):t}var aR=/\s/,cR=/\w/;function me(e){return e!==void 0&&aR.test(e)}function Un(e){return e===`
|
|
75
|
+
`||e==="\r"||e==="\u2028"||e==="\u2029"}function Ui(e){return e!==void 0&&cR.test(e)}function St(e){let t="";for(let n of e)t+=n.length===1?String.fromCharCode(lR(n.charCodeAt(0))):n;return t}function lR(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 Z_(e){let t=0;for(;t<e.length&&e[t]==="/";)t++;return Ye(e.slice(t))}function Fn(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 Fi(e,t){let n=Fn(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 $i(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 Y_(e,t){let n=$i(e,t);return n?e.slice(n.open+1+t.length,n.end):null}function J_(e,t){let n=$i(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 Q_(e,t){let n=`</${t}>`,r="",s=0;for(;;){let o=$i(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 X_(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 xs(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 Z_(e,t,n){let r=Pt(t),s=Pt(n);for(let o of Pt(e).split(/[\n\r\u2028\u2029]/)){let i=o.indexOf(r);if(i!==-1&&o.lastIndexOf(s)>=i+r.length)return!0}return!1}function eb(e,t){let n=Pt(e),r=t.map(Pt),s=e.length,o=c=>{let p=c;for(;p<s&&me(e[p]);)p++;return p},i=c=>{for(let p=c;p<s;p++)if(jn(e[p]))return p+1;return-1},a=0;for(;a!==-1&&a<=s;){let c=o(a);if(c>=s)return null;let p=r.find(d=>n.startsWith(d,c));if(p!==void 0){let d=o(c+p.length);if(e[d]===":"){let g=o(d+1);if(g<s){let m=g;for(;m<s&&!jn(e[m]);)m++;for(;m>g+1&&me(e[m-1]);)m--;return e.slice(g,m)}for(let m=s-1;m>d;m--)if(!jn(e[m]))return e[m];return null}}a=i(c)}return null}function tb(e){let t=e.length,n=new Array(t+1);n[0]=0;for(let a=1;a<=t;a++)n[a]=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 c=a+1;if(me(e[c])){for(;c<t&&me(e[c]);)c++;ji(e[c])&&(r[a]=a)}}let s=new Array(t+1);s[0]=0;for(let a=0;a<t;a++)s[a+1]=s[a]+(jn(e[a])?1:0);let o=(a,c)=>s[c]===s[a],i=a=>{let c=a+1;for(;me(e[c]);)c++;let p=c;for(;p<t&&ji(e[p]);)p++;return e.slice(c,p)};for(let a=e.indexOf("**task-");a!==-1;a=e.indexOf("**task-",a+1)){let c=a+7;for(;c<t&&/[a-z0-9]/.test(e[c]);)c++;if(c===a+7||e[c]!=="*"||e[c+1]!=="*")continue;let p=c+2,d=p;for(;d<t&&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(o(d,m))return{id:e.slice(a+2,c),title:e.slice(d,m),status:i(g)}}}if(d<t&&r[d]===d){for(let g=d-2;g>=p+1;g--)if(!jn(e[g]))return{id:e.slice(a+2,c),title:e[g],status:i(d)}}}}return null}function nb(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),s="",o=0;for(;o<r.length;){if(t(r,o)&&(o===0||!ji(r[o-1]))){let i=o,a=0;for(;t(r,i);){for(i+=6;i<r.length&&me(r[i]);)i++;a++}if(a>=2){o=i;continue}}s+=r[o],o++}return s}function rb(e,t){let n=t?"![":"[",r="",s=0,o=-2,i=-2;for(let a=e.indexOf(n);a!==-1;){let c=a+n.length;if(o<c&&(o=e.indexOf("]",c)),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(c,p)),s=i+1,a=e.indexOf(n,s)}return r+e.slice(s)}function sb(e){return rb(e,!0)}function ob(e){return rb(e,!1)}function ZA(e,t){let n=e.slice(t,t+8).toLowerCase();return n.startsWith("http://")||n.startsWith("https://")}function ib(e,t){let n=Pt(e),r=Pt(t),s=e.length,o=i=>{let a=i;for(;a<s&&me(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 c=o(a+1);for(let p=c;p<s;){if(!me(e[p])){p++;continue}let d=o(p);if(ZA(e,d))return e.slice(c,p);p=d}return e.slice(c)}return null}var eR=new Set(["read","glob","grep","list"]);function ee(e){return e.replace(/^oc-/,"").replace(/-/g,"_")}function O1(e){return eR.has(ce(e))}function D1(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 Ui(e){if(!e)return"";let t=ze(e.replace(/\\/g,"/")),n=t.lastIndexOf("/");return n>=0?t.slice(n+1):t}function ws(e,t=60){if(!e)return"";let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t)}\u2026`:n}function Fi(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?Ui(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?`"${ws(String(i),40)}" in ${Ui(String(a))}`:i?`"${ws(String(i),60)}"`:""}case"list":return r.path?Ui(String(r.path)):"";case"bash":return ws(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 ws(i==="query"&&Ss(a)||a,60)}return""}var tR={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 j1(e,t={}){let n=ge(e)?se(e):e,r={...tR,...t},s=ee(n.tool),o=Fi(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 Ye(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 K1(e){return e.type==="agent"}function B1(e){return e.type==="compaction"}function q1(e){return e.type==="snapshot"}function G1(e){return e.type==="patch"}function W1(e){return e.type==="step-start"||e.type==="step-finish"}function V1(e){if(Ye(e)||we(e))return e.text}function H1(e){if(!cb(e))return!1;let t=e.mime;return t.startsWith("image/")||t==="application/pdf"}function z1(e){let t=[],n=[];for(let r of e)cb(r)?t.push(r):n.push(r);return{attachments:t,stickyParts:n}}function Y1(e,t){let n=[];return e?.tool&&n.push(e.tool),t?.tool&&n.push(t.tool),n}function J1(e,t,n){return n.some(r=>r.messageID===t&&r.callID===e.callID)}var nR=new Set(["todoread","context_info"]);function Un(e){return!nR.has(ge(e)?e.name:e.tool)}var rR=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 ks(e){let t=ge(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 sR(n,t.state)}function sR(e,t){let n=ee(e);if(rR.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 Q1(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 X1(e){let t=[];for(let n of e)if(n.info.role==="assistant")for(let r of n.parts)te(r)&&Un(r)&&t.push(r);return t}var oR={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=>lR(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 Z1(e,t={}){let n=oR[ee(e)];if(!n)return iR(e,t);let r=typeof n.title=="string"?n.title:n.title(t);return{icon:n.icon,title:r,subtitle:n.subtitle?.(t)}}function iR(e,t){switch(ce(e)){case"read":return{icon:"glasses",title:"Read",subtitle:aR(Ie(t))};case"list":return{icon:"list",title:"List",subtitle:cR(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:ab(Ie(t))};case"write":return{icon:"file-pen",title:"Write",subtitle:ab(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 aR(e){if(!e)return;let t=e.split("/");return t[t.length-1]||e}function ab(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 cR(e){if(!e)return;let t=e.lastIndexOf("/");if(!(t<0))return e.slice(0,t)||"/"}function eW(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 $n(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 FW(e){let t=(e??"").trimStart();return t.startsWith("{")||t.startsWith("[")}function NW(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 KW(e,t=200){let n=e??"";return n=n.replace(/\\n/g," "),n=sb(n),n=ob(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 BW(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=xs(s);if(a===null)break;let c;try{c=JSON.parse(a)}catch{break}if(typeof c.status=="number"&&(o=c.status),typeof c.message=="string"&&c.message.trim())s=c.message.trim();else if(typeof c.error=="string"&&c.error.trim())s=c.error.trim();else break}return{message:s,status:o}}function Nn(e){try{return JSON.parse(`"${e}"`)}catch{return e}}function zi(e,t=30){if(!e)return[];let n=[],r=new Set,s=(a,c,p)=>{!/^https?:\/\//i.test(c)||r.has(c)||n.length>=t||(r.add(c),n.push({title:a.trim()||c,url:c,snippet:p?.trim()||void 0}))},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(Nn(i[1]),Nn(i[2]),i[3]?Nn(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(Nn(i[2]),Nn(i[1])),n.length>=t)return n}return n}function st(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function vb(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 Ts(e){return e.filter(t=>st(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 Ab(e){if(!e)return[];let t=vb(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(st(s)&&typeof s.query=="string"){let o=[];for(let i of r)!st(i)||typeof i.query!="string"||o.push({query:i.query,answer:i.answer||void 0,sources:Array.isArray(i.results)?Ts(i.results):[]});if(o.length>0)return o}else if(st(s)&&(s.title||s.url)){let o=Ts(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?Ts(r):[]}];if(Array.isArray(t)&&t.length>0){let s=t[0];if(st(s)&&(s.title||s.url)){let o=Ts(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),c=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&&c&&o.push({title:a[1].trim(),url:c[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=zi(e);if(s.length>0)return[{query:"",sources:s.map(o=>({title:o.title,url:o.url,snippet:o.snippet}))}]}return[]}function Yi(e){try{return new URL(e).hostname.replace("www.","")}catch{return e}}function VW(e){try{let t=new URL(e).hostname.replace(/^www\./,""),n=t.split(".");return n.length<=2?t:n.slice(-2).join(".")}catch{return Yi(e)}}function HW(e){try{return`https://www.google.com/s2/favicons?domain=${new URL(e).hostname.replace(/^www\./,"")}&sz=128`}catch{return null}}function zW(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 GR(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 WR(e,t){if(t.length===0)return[];let n=e.replace(/^Error:\s*/i,"").trim();return t.map(r=>{let s=ib(n,r)?.trim()||n;return{url:r,success:!1,error:s}})}function YW(e,t){let n=VR(e);if(n?.results?.length)return n.results;let r=typeof e=="string"?e:"";return r.trim()?WR(r,GR(t)):[]}function VR(e){if(!e)return null;let t=vb(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=>st(s)&&s.success!==!1).length,failed:n.failed??r.filter(s=>st(s)&&s.success===!1).length,results:r.map(s=>{let o=st(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=zi(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 HR(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 zR={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 Bn(e){return zR[ce(e)]}function Is(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 YR={run:"Terminal",memory:"Memory"};function nV(e){let t=Bn(e);return(t==="hidden"?void 0:YR[t])??Is(e)}function Kn(e,t,n){return e===1?t:n}function Ji(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 Tb(e){return e.length?Fi(e[0]):""}function Ee(e){return(e.state??{}).input??{}}var JR={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 QR(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 JR[t]??"message"}function Rb(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 XR(e){let t=ee(e.tool);if(t==="triggers"){let r=Ee(e).action||"list";return Rb(r)}let n=t.match(/^trigger_(.+)$/);return Rb(n?n[1]:"list")}var ZR={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 eC(e){return ZR[ee(e.tool)]??"read"}var tC={project_get:"open",project_list:"open",project_select:"open",project_update:"update",project_create:"create",project_delete:"delete"};function nC(e){return tC[ee(e.tool)]??"open"}function Wt(e){return e.every(t=>t===e[0])}var rC={view:"read",create:"write",str_replace:"write",insert:"write",rename:"write",delete:"delete"};function sC(e){if(ee(e.tool)!=="memory")return"read";let n=Ee(e).command;return n&&rC[n]||"unknown"}var oC={generate:"Made an image",edit:"Edited an image",upscale:"Upscaled an image",remove_bg:"Removed an image background"},iC={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 aC(e){let t=ze(e.replace(/\\/g,"/")),n=t.lastIndexOf("/");return n>=0?t.slice(n+1):t}function cC(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 lC(r,60);let s=typeof t.path=="string"?t.path:"";if(s)return aC(s);let o=typeof t.url=="string"?t.url:"";if(o){let i=HR(o);return i?Yi(i):"a link"}return""}function lC(e,t=60){let n=e.replace(/\s+/g," ").trim();return n.length>t?n.slice(0,t-1)+"\u2026":n}function uC(e){let t=Ee(e).action;return t&&oC[t]||"Worked on an image"}function pC(e){let t=Ee(e).action;return t&&iC[t]||"Worked on a presentation"}function dC(e){return e.slice(0,e.indexOf(":"))}var gC={generate:"image:generate",edit:"image:edit",upscale:"image:upscale",remove_bg:"image:remove_bg"},mC={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 fC(e){let t=ee(e.tool);if(t==="image_gen"){let n=Ee(e).action;return n&&gC[n]||"image:unknown"}if(t==="video_gen")return"video:create";if(t==="presentation_gen"){let n=Ee(e).action;return n&&mC[n]||"presentation:unknown"}return"shown:result"}var yC=new Set(["create_slide","export_pdf","export_pptx"]);function rV(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 hC={"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`},Cb={image:"image",video:"video",presentation:"presentation",shown:"result"};function _C(e){let t={image:0,video:0,presentation:0,shown:0};for(let r of e)t[dC(r)]++;let n=[];return Object.keys(t).forEach(r=>{let s=t[r];s&&n.push(`${s} ${Kn(s,Cb[r],`${Cb[r]}s`)}`)}),`Worked on ${Ji(n)}`}function Es(e,t){let n=t.map(Ke),r=n.length,s=Tb(n);switch(e){case"explore":{let o=n.filter(i=>ee(i.tool)==="read").length;return o===r?`Read ${r} ${Kn(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} ${Kn(r,"query","queries")}`;if(i===0)return`Read ${r} ${Kn(r,"page","pages")}`;let a=new Set;for(let p of n)if(o(p)){let d=p.state?.output;for(let g of Ab(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 c=a.size||r;return`Searched and read ${c} ${Kn(c,"source","sources")}`}case"create":{if(r===1){let i=n[0],a=ee(i.tool);if(a==="image_gen")return uC(i);if(a==="video_gen")return"Made a video";if(a==="presentation_gen")return pC(i);let c=cC(i);return c?`Showed you ${c}`:"Showed you the result"}let o=n.map(fC);return Wt(o)?hC[o[0]](r):_C(o)}case"plan":return r===1?"Planned the work":`Planned the work \xB7 ${r} steps`;case"delegate":{let o=n.map(QR);if(Wt(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(sC);if(Wt(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(eC);if(Wt(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(XR);if(Wt(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(nC);if(Wt(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 ${Is(n[0].tool)}`;let o=Array.from(new Set(n.map(i=>Is(i.tool))));return o.length===1?`Used ${o[0]} \xB7 ${r} times`:`Used ${Ji(o)}`}}}function Ib(e,t){let n=t.map(Ke),r=Tb(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=>Is(a.tool))));return`Couldn't finish using ${Ji(i)}`}}}var bC=new Set(["get_mem","memory_search","mem_search","ltm_search","dcp_compress","dcp_distill","dcp_prune","prune","distill","compress","context_info"]),PC={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 SC(e,t){if(e==="filePath"||e==="path"||e==="file"){let n=t.split("/");return n[n.length-1]||t}return e==="query"&&Ss(t)||t}function xC(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 SC(r,s.trim())}}function qn(e){let t=ge(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=PC[n],s=t.state?.input;return r?{verb:r.verb,running:r.running,object:xC(s,r.objectKeys),tier:bC.has(n)?"plumbing":"primary"}:{verb:"Used",running:"Using",object:n,tier:"primary"}}function Xi(e){let t=0,n=0,r=!1,s=!1;for(let o of e){if(qn(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)&&Hi(o)!=="ok"&&(n+=1)}return{total:t,failed:n,completed:t-n,hasPlumbing:r}}function Qi(e){return`${e} ${e===1?"step":"steps"}`}function wC(e,t){let{total:n,failed:r,completed:s,hasPlumbing:o}=e;return t?n===0?"Working":`Working \xB7 ${Qi(n)}`:n===0?o?"Housekeeping":"Worked":r===0?`Completed ${Qi(n)}`:s===0?`${Qi(n)} failed`:`Completed ${s} of ${n} steps \xB7 ${r} failed`}function Eb(e){let t=new Map,n=0;for(let s of e){if(!te(s)||qn(s).tier==="plumbing")continue;let o=Bn(s.tool);o!=="hidden"&&(t.set(o,[...t.get(o)??[],s]),Hi(s)!=="ok"&&(n+=1))}if(t.size===0)return wC(Xi(e),!1);let r=[...t].map(([s,o],i)=>{let a=Es(s,o);return i===0?a:a.charAt(0).toLowerCase()+a.slice(1)}).join(", ");return n>0?`${r} \xB7 ${n} failed`:r}function fV(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)},c=(e.userMessage?.parts??[]).some(p=>p.type==="compaction");c&&(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 c&&e.assistantMessages.length===0&&(r=!0),{isCompaction:t,hasContent:n,inFlight:r,error:s}}function kC(e){return e.some(t=>t.state?.status==="running"||t.state?.status==="pending")?"running":e.some(t=>t.state?.status==="error")?"error":"done"}function vC(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 Mb(e,t){let n=t.map(Ke),r=kC(n);return{id:n[0].callID,family:e,label:r==="error"?Ib(e,n):Es(e,n),parts:t,status:r,durationMs:r==="running"?void 0:vC(n)}}function Ob(e){let t=[],n=null,r=[],s=()=>{n&&r.length&&t.push(Mb(n,r)),n=null,r=[]};for(let o of e){let i=Ke(o),a=Bn(i.tool);if(a!=="hidden"&&!Wo(i)){if(hy(i.tool)){s(),t.push(Mb(a,[o]));continue}a!==n&&(s(),n=a),r.push(o)}}return s(),t}function Zi(e){let t=e.time?.end;return!(typeof t=="number"&&t>0)}function Db(e,t){let n=[],r=null,s=[],o=()=>{if(r&&r.texts.length>0){let{startedAt:a,endedAt:c}=r,p=typeof a=="number"&&typeof c=="number"&&c>a?c-a:void 0;n.push({kind:"thought",key:r.key,texts:r.texts,running:r.running,durationMs:p})}r=null},i=()=>{if(s.length!==0){for(let a of Ob(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 c=a.text?.trim();if(!c)continue;i(),r||(r={key:`thought-${a.id}`,texts:[],running:!1}),r.texts.push(c);let p=a.time;r.startedAt===void 0&&typeof p?.start=="number"&&(r.startedAt=p.start),r.endedAt=typeof p?.end=="number"&&p.end>0?p.end:void 0,r.running=Zi(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 c=n[a];c.kind==="thought"&&(c.running=!1)}return n}var AC=/^(thinking|thought|considering|planning|deciding|weighing|exploring|analy[sz]ing|reasoning|working out|figuring)/i;function RC(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 wV(e){let t=e.flatMap(s=>{let o=RC(s);return o?[o]:[]}).join(" ").trim();return t?AC.test(t)?t:`Thinking about ${/^[A-Z][a-z]/.test(t)?t[0].toLowerCase()+t.slice(1):t}`:"Thinking"}function CC(e){return e?.info?.time??{}}function vV(e){let t=CC(e).created;return typeof t!="number"||!Number.isFinite(t)||t<=0?null:t}var Ms=6e4,TC=10080*Ms,jb=1440;function Lb(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 IC(e,t){let n=t.getTime()-e.getTime(),r=n/Ms,s=(i,a)=>`${i} ${a}${i===1?"":"s"} ago`;if(r<60)return s(Math.round(r),"minute");if(r<jb)return s(Math.round(r/60),"hour");let o=(n-(Lb(t)-Lb(e)))/Ms;return s(Math.round(o/jb),"day")}function Fb(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 $b=new Map;function EC(e,t){let n={...e,...t.timeZone?{timeZone:t.timeZone}:{}},r=`${t.locale??""}|${JSON.stringify(n)}`,s=$b.get(r);return s||(s=new Intl.DateTimeFormat(t.locale,n),$b.set(r,s)),s}function Os(e,t,n){return EC(t,n).formatToParts(e).map(r=>r.type==="dayPeriod"?MC(r.value,n):r.value).join("")}function MC(e,t){let n=/^([ap])\.?\s?m\.?$/i.exec(e.trim());return n?`${n[1].toUpperCase()}M`:e.toLocaleUpperCase(t.locale)}function Ub(e,t){return Os(e,{year:"numeric"},t)}function AV(e,t,n={}){let r=Fb(e);if(!r)return"";let s=i=>Os(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<Ms?"just now":o<TC?IC(r,new Date(t)):s(Ub(r,n)!==Ub(new Date(t),n))}function RV(e,t={}){let n=Fb(e);if(!n)return"";let r=Os(n,{month:"long",day:"numeric",year:"numeric"},t),s=Os(n,{hour:"numeric",minute:"2-digit"},t);return`${r} ${s}`}function Nb(e,t={}){let n=[],r=[],s=()=>{r.length>0&&(n.push({kind:"burst",parts:r}),r=[])};for(let o of e)if(!_y(o)){if(Ye(o)){s(),n.push({kind:"text",part:o});continue}if(te(o)&&(by(o.tool)||!!t.standaloneCallIds?.has(o.callID))){s(),n.push({kind:"standalone",part:o});continue}r.push(o)}return s(),n}function OC(e){let t=he(e);return t==="show"||t==="show_user"}function Bb(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"&&OC(o.part.tool)&&!t.standaloneCallIds?.has(o.part.callID)){r.push(o);continue}s(),n.push(o)}return s(),n}var DC=["title","description","path","url","content","language","aspect_ratio","attachment"];function Kb(e,t){if(!t||typeof t!="object")return null;let n=t;if(Wr(n))return null;let r={callID:e,status:"ready",type:typeof n.type=="string"?n.type:""};for(let s of DC){let o=n[s];typeof o=="string"&&o&&(r[s]=o)}return r}function jC(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 qb(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=jC(s.items),i=o?o.map(a=>Kb(n.callID,a)).filter(a=>!!a):[Kb(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 Gb(e){return!e.working||e.awaitingUser?!1:e.isRetrying?!0:!e.hasError}var Gn=e=>"id"in e?e.id:e.userMessage.info.id,Wb=e=>"assistant"in e?e.assistant.length:e.assistantMessages.length,LC=e=>e.time?.completed;function $V(e){return!e.hasPendingTurns||!e.newestAssistantCompleted?!1:e.pendingDelivery||!!e.deliveringBelow||e.activeTurnId!==null&&e.activeTurnId!==e.workingTurnId}function $C(e,t){let n=Gn(e);return t.pendingTurnIds.has(n)||Wb(e)===0&&t.pendingPromptIds.has(n)}function UV(e){let t=e.turns.find(r=>e.deliveringPromptIds.has(Gn(r)));if(t)return Gn(t);let n=e.turns.findIndex(r=>$C(r,e));return n<=0?null:Gn(e.turns[n-1])}function FV(e){return e.isTurnWorking&&!e.pendingDelivery&&e.activeTurnId===e.turnId}function NV(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 KV(e){return!e.lastTurnWorking||e.workingTurnId===null||e.suppressed?!1:Gb({working:!0,hasError:e.workingTurnHasError,isRetrying:e.isRetrying,awaitingUser:e.awaitingUser})}function BV(e,t){for(let n=e.length-1;n>=0;n--){let r=Gn(e[n]);if(t(r))return Wb(e[n])===0?r:null}return null}function Vb(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(c=>c.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],c=a.assistantMessages[a.assistantMessages.length-1];if(!LC(c.info)&&!c.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 VV(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 HV(e,t){return!t||!e?!1:e.type!=="idle"}function zV(e,t){return!e&&!!t}function YV(e){for(let t of e.assistantMessages){let n=t.info;if(n.error)return xe(n.error)?.message||_e(n.error)}}function JV(e){for(let t of e.assistantMessages){let n=t.info;if(n.error)return Ps(n.error)}}function QV(e){for(let t of e.assistantMessages){let n=t.info;if(n.error)return xe(n.error)}}function Hb(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(Ye(e))return"Gathering thoughts..."}}var UC=new Set(["task","agent_task","agent-task","task_create","task-create","task_start","task-start"]);function FC(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=Hb(n.parts[r]);if(s)return s}}}function NC(e,t){let n=te(e)?e:void 0;if(n&&UC.has(n.tool)&&n.state.status==="running"){let r=FC(t);return r||(t?.length?"Handing off to an agent...":void 0)}return Hb(e)}function zb(e,t){for(let n=e.length-1;n>=0;n--){let r=NC(e[n].part,t);if(r)return r}return"Figuring out what\u2019s next..."}function Yb(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 Jb=1.055;function Qb(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),c=[...t.tiers??[],...t.contextOver200k?[t.contextOver200k]:[]].filter(d=>n>d.contextThreshold).sort((d,g)=>g.contextThreshold-d.contextThreshold)[0]??t,p=i/1e6*c.inputPer1M;return p+=r/1e6*c.outputPer1M,s>0&&(p+=s/1e6*(c.cacheReadPer1M??c.inputPer1M)),o>0&&(p+=o/1e6*(c.cacheWritePer1M??c.inputPer1M)),p}function ea(e,t){return e==="codex"||e==="openai-codex"||e==="kortix"&&!!t?.startsWith("codex/")}function Xb(e,t,n,r){if(ea(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?Qb(e.tokens,o):0}function Zb(e){if(e.role!=="assistant")return{};let t=e;return{providerID:t.providerID,modelID:t.modelID}}function ta(e,t){let n=0,r=0,s=0,o=0,i=0,a=0,c=!1;for(let{part:p,message:d}of e)if(p.type==="step-finish"){c=!0;let g=p,{providerID:m,modelID:f}=Zb(d.info);n+=Xb(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(!c){let p=new Set;for(let{message:d}of e){if(d.info.role!=="assistant")continue;let g=d.info;if(p.has(g.id))continue;p.add(g.id);let m=eP(g,t),f=g.tokens&&ea(g.providerID,g.modelID);if(m<=0&&!f)continue;c=!0,n+=m;let _=g.tokens;_&&(r+=_.input??0,s+=_.output??0,o+=_.reasoning??0,i+=_.cache?.read??0,a+=_.cache?.write??0)}}if(c)return{cost:n*Jb,tokens:{input:r,output:s,reasoning:o,cacheRead:i,cacheWrite:a}}}function eP(e,t){if(ea(e.providerID,e.modelID)||!t||!e.providerID||!e.modelID||!e.tokens)return 0;let n=t(e.providerID,e.modelID);return n?Qb({input:e.tokens.input,output:e.tokens.output,reasoning:e.tokens.reasoning,cache:e.tokens.cache},n):0}function XV(e,t){let n=0;for(let r of e){if(r.info?.role!=="assistant")continue;let s=r.info,{providerID:o,modelID:i}=Zb(s),a=0,c=!1;for(let p of r.parts)p.type==="step-finish"&&(c=!0,a+=Xb(p,o,i,t));c||(a+=eP(s,t)),n+=a}return n*Jb}function ZV(e){return e===0?"$0.00":e<.001?`$${e.toFixed(4)}`:e<.01?`$${e.toFixed(3)}`:`$${e.toFixed(2)}`}function eH(e){return e<1e3?String(e):e<1e4?`${(e/1e3).toFixed(1)}k`:`${Math.round(e/1e3)}k`}function tH(e){if(!e||e.type!=="retry")return;let t=e,n=_e(t.message);return{attempt:t.attempt,message:n.length>60?`${n.slice(0,60)}...`:n,next:t.next,details:xe(t.message)}}function nH(e){if(!(!e||e.type!=="retry"))return _e(e.message)}function rH(e){return(e.info.summary?.diffs?.length??0)>0}function tP(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 KC(e){return e.kind==="text"&&!e.part.text?.trim()}function nP(e,t){if(t.working)return null;let n=-1;for(let s=e.length-1;s>=0;s--){let o=e[s];if(!(tP(o)||KC(o))){o.kind==="text"&&(n=s);break}}let r={work:[],hoisted:[],final:[]};return e.forEach((s,o)=>{o===n?r.final.push(s):tP(s)?r.hoisted.push(s):r.work.push(s)}),r.work.length>0?r:null}function aH(e){let t=e==null?"":Yb(e);return t?`Worked for ${t}`:"Worked"}function BC(e){let t=e.userMessage.parts;if(t.length===0||!t.every(o=>Ye(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 uH(e){if(BC(e))return e.assistantMessages[0].parts[0]}function gH(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=Q_(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 mH(e){return e?e.split(`
|
|
84
|
-
`).filter(n=>n.trim()).length<=3:!1}function
|
|
85
|
-
`).filter(r=>r.trim()&&!r.startsWith("#"))[0]?.replace(/^\*\*.*?\*\*\s*/,"").trim();return n?n.length>120?n.slice(0,120).trim()+"\u2026":n:null}function
|
|
86
|
-
`).filter(r=>r.trim());for(let r of n){let s=
|
|
87
|
-
`),r=n===-1?e:e.slice(0,n),s=n===-1?"":e.slice(n+1);if(
|
|
77
|
+
`)&&(n=n.slice(0,-1)),n)}function Ni(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 eb(e,t){let n=Ni(e,t);return n?e.slice(n.open+1+t.length,n.end):null}function tb(e,t){let n=Ni(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 nb(e,t){let n=`</${t}>`,r="",s=0;for(;;){let o=Ni(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 rb(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 ws(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 sb(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 ob(e,t){let n=St(e),r=t.map(St),s=e.length,o=c=>{let p=c;for(;p<s&&me(e[p]);)p++;return p},i=c=>{for(let p=c;p<s;p++)if(Un(e[p]))return p+1;return-1},a=0;for(;a!==-1&&a<=s;){let c=o(a);if(c>=s)return null;let p=r.find(d=>n.startsWith(d,c));if(p!==void 0){let d=o(c+p.length);if(e[d]===":"){let g=o(d+1);if(g<s){let m=g;for(;m<s&&!Un(e[m]);)m++;for(;m>g+1&&me(e[m-1]);)m--;return e.slice(g,m)}for(let m=s-1;m>d;m--)if(!Un(e[m]))return e[m];return null}}a=i(c)}return null}function ib(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 c=a+1;if(me(e[c])){for(;c<t&&me(e[c]);)c++;Ui(e[c])&&(r[a]=a)}}let s=new Array(t+1);s[0]=0;for(let a=0;a<t;a++)s[a+1]=s[a]+(Un(e[a])?1:0);let o=(a,c)=>s[c]===s[a],i=a=>{let c=a+1;for(;me(e[c]);)c++;let p=c;for(;p<t&&Ui(e[p]);)p++;return e.slice(c,p)};for(let a=e.indexOf("**task-");a!==-1;a=e.indexOf("**task-",a+1)){let c=a+7;for(;c<t&&/[a-z0-9]/.test(e[c]);)c++;if(c===a+7||e[c]!=="*"||e[c+1]!=="*")continue;let p=c+2,d=p;for(;d<t&&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(o(d,m))return{id:e.slice(a+2,c),title:e.slice(d,m),status:i(g)}}}if(d<t&&r[d]===d){for(let g=d-2;g>=p+1;g--)if(!Un(e[g]))return{id:e.slice(a+2,c),title:e[g],status:i(d)}}}}return null}function ab(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),s="",o=0;for(;o<r.length;){if(t(r,o)&&(o===0||!Ui(r[o-1]))){let i=o,a=0;for(;t(r,i);){for(i+=6;i<r.length&&me(r[i]);)i++;a++}if(a>=2){o=i;continue}}s+=r[o],o++}return s}function cb(e,t){let n=t?"![":"[",r="",s=0,o=-2,i=-2;for(let a=e.indexOf(n);a!==-1;){let c=a+n.length;if(o<c&&(o=e.indexOf("]",c)),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(c,p)),s=i+1,a=e.indexOf(n,s)}return r+e.slice(s)}function lb(e){return cb(e,!0)}function ub(e){return cb(e,!1)}function uR(e,t){let n=e.slice(t,t+8).toLowerCase();return n.startsWith("http://")||n.startsWith("https://")}function pb(e,t){let n=St(e),r=St(t),s=e.length,o=i=>{let a=i;for(;a<s&&me(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 c=o(a+1);for(let p=c;p<s;){if(!me(e[p])){p++;continue}let d=o(p);if(uR(e,d))return e.slice(c,p);p=d}return e.slice(c)}return null}var pR=new Set(["read","glob","grep","list"]);function ee(e){return e.replace(/^oc-/,"").replace(/-/g,"_")}function tW(e){return pR.has(ce(e))}function nW(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 Bi(e){if(!e)return"";let t=Ye(e.replace(/\\/g,"/")),n=t.lastIndexOf("/");return n>=0?t.slice(n+1):t}function ks(e,t=60){if(!e)return"";let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t)}\u2026`:n}function Ki(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?Bi(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?`"${ks(String(i),40)}" in ${Bi(String(a))}`:i?`"${ks(String(i),60)}"`:""}case"list":return r.path?Bi(String(r.path)):"";case"bash":return ks(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 ks(i==="query"&&xs(a)||a,60)}return""}var dR={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 rW(e,t={}){let n=ge(e)?se(e):e,r={...dR,...t},s=ee(n.tool),o=Ki(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 gb(e){return e.type==="file"}function lW(e){return e.type==="agent"}function uW(e){return e.type==="compaction"}function pW(e){return e.type==="snapshot"}function dW(e){return e.type==="patch"}function gW(e){return e.type==="step-start"||e.type==="step-finish"}function mW(e){if(Je(e)||we(e))return e.text}function fW(e){if(!gb(e))return!1;let t=e.mime;return t.startsWith("image/")||t==="application/pdf"}function yW(e){let t=[],n=[];for(let r of e)gb(r)?t.push(r):n.push(r);return{attachments:t,stickyParts:n}}function hW(e,t){let n=[];return e?.tool&&n.push(e.tool),t?.tool&&n.push(t.tool),n}function _W(e,t,n){return n.some(r=>r.messageID===t&&r.callID===e.callID)}var gR=new Set(["todoread","context_info"]);function Bn(e){return!gR.has(ge(e)?e.name:e.tool)}var mR=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 vs(e){let t=ge(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 fR(n,t.state)}function fR(e,t){let n=ee(e);if(mR.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 SW(e){let t=[];for(let n of e)if(n.info.role==="assistant")for(let r of n.parts)te(r)&&Bn(r)&&t.push(r);return t}var yR={webfetch:{icon:"globe",title:"Web Fetch",subtitle:e=>e.url},websearch:{icon:"search",title:"Web Search",subtitle:e=>e.query},web_search:{icon:"search",title:"Web Search",subtitle:e=>e.query},scrape_webpage:{icon:"globe",title:"Scrape",subtitle:e=>e.urls?.split?.(",")[0]},image_search:{icon:"image",title:"Image Search",subtitle:e=>e.query},image_gen:{icon:"image",title:"Image Gen",subtitle:e=>e.prompt?.slice?.(0,40)},video_gen:{icon:"cpu",title:"Video Gen",subtitle:e=>e.prompt?.slice?.(0,40)},presentation_gen:{icon:"presentation",title:e=>{let t=e.action||"";return{create_slide:"Create Slide",list_slides:"List Slides",preview:"Preview",export_pdf:"Export PDF",export_pptx:"Export PPTX"}[t]||"Presentation"},subtitle:e=>e.slide_title||e.presentation_name},show:{icon:"globe",title:"Output",subtitle:e=>e.title||e.description},show_user:{icon:"globe",title:"Output",subtitle:e=>e.title||e.description},task:{icon:"square-kanban",title:e=>`Agent (${e.subagent_type||"task"})`,subtitle:e=>SR(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 PW(e,t={}){let n=yR[ee(e)];if(!n)return hR(e,t);let r=typeof n.title=="string"?n.title:n.title(t);return{icon:n.icon,title:r,subtitle:n.subtitle?.(t)}}function hR(e,t){switch(ce(e)){case"read":return{icon:"glasses",title:"Read",subtitle:_R(Ie(t))};case"list":return{icon:"list",title:"List",subtitle:bR(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:db(Ie(t))};case"write":return{icon:"file-pen",title:"Write",subtitle:db(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 _R(e){if(!e)return;let t=e.split("/");return t[t.length-1]||e}function db(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 bR(e){if(!e)return;let t=e.lastIndexOf("/");if(!(t<0))return e.slice(0,t)||"/"}function xW(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 Nn(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 SR(e){let t=Nn(e.description);if(t)return t;let n=Nn(e.title,80);if(n)return n;let r=Nn(e.message);if(r)return r;let s=Nn(e.prompt);if(s)return s;let o=Nn(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 kW(e,t){return e.find(n=>n.tool?.callID===t)}function vW(e,t){return e.find(n=>n.tool?.callID===t)}var PR=/\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 mb(e){return e?e.replace(PR,""):""}function As(e){let t=fb(e);return t?[t]:(Array.isArray(e?.edits)?e.edits:[]).flatMap(r=>{let s=r&&typeof r=="object"?fb(r):void 0;return s?[s]:[]})}function fb(e){let t=e?.oldString??e?.old_string??e?.oldText,n=e?.newString??e?.new_string??e?.newText;return typeof t=="string"&&typeof n=="string"?[t,n]:void 0}var xR={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"},wR={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 kR(e){return e.replace(/^oc[-_]/,"")}function yb(e){return kR(e).replace(/-/g,"_")}function hb(e){return yb(e).split(/[_\s]+/).filter(Boolean).map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" ")}function qi(e){return{label:xR[yb(e)]??hb(e),category:wR[ce(e)]}}var vR=256*1024;function AR(e){switch(e.status){case"pending":return"pending";case"running":return"running";case"completed":return"done";case"error":return"error";default:return e}}function RR(e){if(e===void 0)return{};if(e.length>vR)return{outputText:e};try{return{outputParsed:JSON.parse(e),outputText:e}}catch{return{outputText:e}}}function TR(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 pe=e=>typeof e=="string"?e:void 0,Rs=e=>typeof e=="number"?e:void 0,Ts=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:void 0;function Gi(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}var CR=new Set(["add","update","delete","move"]);function IR(e,t,n){if(e==="apply_patch"){let p=(Array.isArray(n.files)?n.files:[]).flatMap(d=>{let g=Ts(d),m=g&&(pe(g.relativePath)||pe(g.filePath));if(!g||!m)return[];let f=pe(g.type);return[Gi({path:m,type:f&&CR.has(f)?f:void 0,before:pe(g.before),after:pe(g.after),patch:pe(g.patch)??pe(g.diff),additions:Rs(g.additions),deletions:Rs(g.deletions),movePath:pe(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[Gi({path:r,after:pe(t.content)})];if(e!=="edit")return;let s=Ts(n.filediff),o=s?void 0:pe(n.patch),i=o?ER(o):void 0,a=s||o?[]:As(t);return[Gi({path:r,before:pe(s?.before)??(a.length?a.map(([c])=>c).join(`
|
|
79
|
+
`):void 0),after:pe(s?.after)??(a.length?a.map(([,c])=>c).join(`
|
|
80
|
+
`):pe(t.new_source)),patch:o,additions:Rs(s?.additions)??i?.additions,deletions:Rs(s?.deletions)??i?.deletions})]}function ER(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 MR(e){let t=e.answers;if(Array.isArray(t))return t.map(n=>Array.isArray(n)?n.filter(r=>typeof r=="string"):[])}function _b(e,t){let n="title"in t?t.title:void 0,r=t.status==="completed"?t.output:void 0,{outputParsed:s,outputText:o}=RR(r),i=AR(t),a=t.status==="error"?t.error:void 0;if(i==="done"){let m=TR(s);m&&(i="error",a=m)}let c=ce(e),p=t.input??{},d="metadata"in t&&Ts(t.metadata)||{},g=Ts(d.diagnostics);return{name:e,kind:c,title:n||qi(e).label,status:i,input:t.input,output:r,outputParsed:s,outputText:o,error:a,files:IR(c,p,d),diff:pe(d.patch)??pe(d.diff),diagnostics:g,answers:c==="question"?MR(d):void 0,childSessionId:vs({tool:e,state:t})}}function bb(e){let t=ge(e)?se(e):e;return _b(t.tool,t.state)}function OR(e){return{kind:"text",id:e.id,text:e.text,synthetic:!!e.synthetic}}function DR(e){return{kind:"reasoning",id:e.id,text:e.text}}function jR(e){return{kind:"tool",id:e.id,tool:_b(e.tool,e.state)}}function LR(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 $R(e){return{kind:"subtask",id:e.id,description:e.description,agent:e.agent,prompt:e.prompt,model:e.model}}function UR(e){return{kind:"patch",id:e.id,hash:e.hash,files:e.files,fileCount:e.files.length}}function FR(e){return{kind:"snapshot",id:e.id,snapshot:e.snapshot}}function NR(e){return{kind:"agent",id:e.id,name:e.name}}function BR(e){return{kind:"retry",id:e.id,attempt:e.attempt,message:_e(e.error),createdAt:e.time.created}}function KR(e){return{kind:"compaction",id:e.id,auto:e.auto,overflow:!!e.overflow,tailStartId:e.tail_start_id}}function qR(e){return{kind:"step",id:e.id,phase:"start",snapshot:e.snapshot}}function GR(e){return{kind:"step",id:e.id,phase:"finish",snapshot:e.snapshot,reason:e.reason,cost:e.cost,tokens:e.tokens}}function Sb(e){switch(e.type){case"text":return OR(e);case"reasoning":return DR(e);case"tool":return jR(e);case"file":return LR(e);case"subtask":return $R(e);case"patch":return UR(e);case"snapshot":return FR(e);case"agent":return NR(e);case"retry":return BR(e);case"compaction":return KR(e);case"step-start":return qR(e);case"step-finish":return GR(e);default:return{kind:"unknown",raw:e}}}function WR(e){if(!e)return;let t=typeof e=="object"&&"name"in e&&typeof e.name=="string"?e.name:"Error",n=xe(e);return{name:t,message:n?.message||_e(e),provider:n?.provider,code:n?.code,suggestion:n?.suggestion,upstreamStatus:n?.upstreamStatus,requestId:n?.requestId,attemptFailures:n?.attemptFailures}}function VR(e){switch(e.kind){case"text":case"reasoning":return e.text.trim().length>0;case"step":return!1;default:return!0}}function Wi(e){let t=e.parts.map(Sb),n=e.info.role==="assistant"?e.info.error:void 0,r=WR(n),s=!r&&!t.some(VR);return{parts:t,error:r,isEmpty:s}}var Vi=rt+BigInt(1),Pb=Vi/BigInt(2);function Cs(e){return BigInt(Math.trunc(e))*Pn}function Hi(e,t){let r=t-(t&rt)+e;return r-t>Pb?r-=Vi:t-r>Pb&&(r+=Vi),r}function xb(e,t){let n=Bt(e.info.id)??BigInt(0),r=e.info.time?.created;if(typeof r!="number")return Hi(n,t);let s=Cs(r),o=Hi(n,s);return(o>s?o-s:s-o)<=yt?o:s}function wb(e){return Bt(e)===null?1:0}function kb(e,t){return e<t?-1:e>t?1:0}function BW(e,t){return zi(e,t,Cs(Date.now()))}function vb(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 Cs(t??Date.now())}function zi(e,t,n){let r=wb(e.info.id),s=wb(t.info.id);if(r!==s)return r-s;if(r===0){let a=xb(e,n),c=xb(t,n);return a!==c?a<c?-1:1:kb(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:kb(e.info.id,t.info.id)}function KW(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 qW(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 HR(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(...HR(e,s));return r}function HW(e,t){let n=new Map([...t?.pendingMessageIds??[]].map((d,g)=>[d,g])),r=vb(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,c=[],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=c[c.length-1];f&&f.userMessage.info.id===g.parentID?f.assistantMessages.push(d):c.push({userMessage:YR(g.parentID,d),assistantMessages:[d],partial:!0});continue}p.push(d)}}if(p.length>0){let d=o[0]??c[0];if(d)d.assistantMessages.unshift(...p);else{let[g,...m]=p;o.push({userMessage:g,assistantMessages:m})}}return c.length>0?[...c,...o]:o}var Kn=new Map,zR=256;function YR(e,t){let n=t.info,r=n.time?.created,s=`${n.sessionID??""}|${e}|${r??""}`,o=Kn.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(Kn.size>=zR){let a=Kn.keys().next().value;a!==void 0&&Kn.delete(a)}return Kn.set(s,i),i}function zW(e){let t=[];for(let n of e.assistantMessages)for(let r of n.parts)t.push({part:r,message:n});return t}function YW(e){for(let t=e.length-1;t>=0;t--){let n=e[t].part;if(Je(n)&&n.text?.trim())return n}}function JW(e){return e.some(({part:t})=>t.type==="tool"||t.type==="compaction"||t.type==="snapshot"||t.type==="patch")}function QW(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 JR(e){if(!e||typeof e!="object")return!1;let t=e.data;return!!t&&typeof t=="object"&&t.isRetryable===!0}function Ab(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&&JR(n.error)}return!1}function Yi(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Tb(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 nV(e){return!!e&&(Tb(e)||Cb(e)!==null)}function Ji(e){let t=ge(e)?se(e):e,n=Rb.get(t);if(n&&n.state===t.state)return n.outcome;let r=QR(t);return Rb.set(t,{state:t.state,outcome:r}),r}var Rb=new WeakMap;function QR(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(Tb(n))return"failed";let r=XR(n);return r===void 0?"ok":ZR(r)?"failed":eT(r)}function XR(e){try{return JSON.parse(e)}catch{return}}function ZR(e){return Yi(e)&&e.success===!1&&typeof e.error=="string"}function eT(e){let t=Yi(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 Cb(e){let t=e.trim();if(!t)return null;let n;try{n=JSON.parse(t)}catch{return null}if(!Yi(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=ws(r.errorSummary);if(s===null)return r;try{let o=JSON.parse(s);typeof o.message=="string"&&o.message.trim()&&(r.nestedMessage=o.message.trim()),typeof o.status=="number"&&(r.status=o.status),typeof o.error=="boolean"&&(r.nestedError=o.error)}catch{}return r}function rV(e){return ab(e).replace(/\s+/g," ").trim()||e.trim()}function sV(e){let t=Cb(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 aV(e){let t=(e??"").trimStart();return t.startsWith("{")||t.startsWith("[")}function cV(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 lV(e,t=200){let n=e??"";return n=n.replace(/\\n/g," "),n=lb(n),n=ub(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 uV(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=ws(s);if(a===null)break;let c;try{c=JSON.parse(a)}catch{break}if(typeof c.status=="number"&&(o=c.status),typeof c.message=="string"&&c.message.trim())s=c.message.trim();else if(typeof c.error=="string"&&c.error.trim())s=c.error.trim();else break}return{message:s,status:o}}function qn(e){try{return JSON.parse(`"${e}"`)}catch{return e}}function Qi(e,t=30){if(!e)return[];let n=[],r=new Set,s=(a,c,p)=>{!/^https?:\/\//i.test(c)||r.has(c)||n.length>=t||(r.add(c),n.push({title:a.trim()||c,url:c,snippet:p?.trim()||void 0}))},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(qn(i[1]),qn(i[2]),i[3]?qn(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(qn(i[2]),qn(i[1])),n.length>=t)return n}return n}function ot(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ib(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 Is(e){return e.filter(t=>ot(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 Eb(e){if(!e)return[];let t=Ib(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(ot(s)&&typeof s.query=="string"){let o=[];for(let i of r)!ot(i)||typeof i.query!="string"||o.push({query:i.query,answer:i.answer||void 0,sources:Array.isArray(i.results)?Is(i.results):[]});if(o.length>0)return o}else if(ot(s)&&(s.title||s.url)){let o=Is(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?Is(r):[]}];if(Array.isArray(t)&&t.length>0){let s=t[0];if(ot(s)&&(s.title||s.url)){let o=Is(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),c=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&&c&&o.push({title:a[1].trim(),url:c[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=Qi(e);if(s.length>0)return[{query:"",sources:s.map(o=>({title:o.title,url:o.url,snippet:o.snippet}))}]}return[]}function Xi(e){try{return new URL(e).hostname.replace("www.","")}catch{return e}}function mV(e){try{let t=new URL(e).hostname.replace(/^www\./,""),n=t.split(".");return n.length<=2?t:n.slice(-2).join(".")}catch{return Xi(e)}}function fV(e){try{return`https://www.google.com/s2/favicons?domain=${new URL(e).hostname.replace(/^www\./,"")}&sz=128`}catch{return null}}function yV(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 tT(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 nT(e,t){if(t.length===0)return[];let n=e.replace(/^Error:\s*/i,"").trim();return t.map(r=>{let s=pb(n,r)?.trim()||n;return{url:r,success:!1,error:s}})}function hV(e,t){let n=rT(e);if(n?.results?.length)return n.results;let r=typeof e=="string"?e:"";return r.trim()?nT(r,tT(t)):[]}function rT(e){if(!e)return null;let t=Ib(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=>ot(s)&&s.success!==!1).length,failed:n.failed??r.filter(s=>ot(s)&&s.success===!1).length,results:r.map(s=>{let o=ot(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=Qi(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 sT(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 oT={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 Wn(e){return oT[ce(e)]}function Es(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 iT={run:"Terminal",memory:"Memory"};function kV(e){let t=Wn(e);return(t==="hidden"?void 0:iT[t])??Es(e)}function Gn(e,t,n){return e===1?t:n}function Zi(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 Db(e){return e.length?Ki(e[0]):""}function Ee(e){return(e.state??{}).input??{}}var aT={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 cT(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 aT[t]??"message"}function Mb(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 lT(e){let t=ee(e.tool);if(t==="triggers"){let r=Ee(e).action||"list";return Mb(r)}let n=t.match(/^trigger_(.+)$/);return Mb(n?n[1]:"list")}var uT={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 pT(e){return uT[ee(e.tool)]??"read"}var dT={project_get:"open",project_list:"open",project_select:"open",project_update:"update",project_create:"create",project_delete:"delete"};function gT(e){return dT[ee(e.tool)]??"open"}function Ht(e){return e.every(t=>t===e[0])}var mT={view:"read",create:"write",str_replace:"write",insert:"write",rename:"write",delete:"delete"};function fT(e){if(ee(e.tool)!=="memory")return"read";let n=Ee(e).command;return n&&mT[n]||"unknown"}var yT={generate:"Made an image",edit:"Edited an image",upscale:"Upscaled an image",remove_bg:"Removed an image background"},hT={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 _T(e){let t=Ye(e.replace(/\\/g,"/")),n=t.lastIndexOf("/");return n>=0?t.slice(n+1):t}function bT(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 ST(r,60);let s=typeof t.path=="string"?t.path:"";if(s)return _T(s);let o=typeof t.url=="string"?t.url:"";if(o){let i=sT(o);return i?Xi(i):"a link"}return""}function ST(e,t=60){let n=e.replace(/\s+/g," ").trim();return n.length>t?n.slice(0,t-1)+"\u2026":n}function PT(e){let t=Ee(e).action;return t&&yT[t]||"Worked on an image"}function xT(e){let t=Ee(e).action;return t&&hT[t]||"Worked on a presentation"}function wT(e){return e.slice(0,e.indexOf(":"))}var kT={generate:"image:generate",edit:"image:edit",upscale:"image:upscale",remove_bg:"image:remove_bg"},vT={create_slide:"presentation:create_slide",list_slides:"presentation:list_slides",list_presentations:"presentation:list_presentations",delete_slide:"presentation:delete_slide",delete_presentation:"presentation:delete_presentation",validate_slide:"presentation:validate_slide",export_pdf:"presentation:export_pdf",export_pptx:"presentation:export_pptx",preview:"presentation:preview",serve:"presentation:preview"};function AT(e){let t=ee(e.tool);if(t==="image_gen"){let n=Ee(e).action;return n&&kT[n]||"image:unknown"}if(t==="video_gen")return"video:create";if(t==="presentation_gen"){let n=Ee(e).action;return n&&vT[n]||"presentation:unknown"}return"shown:result"}var RT=new Set(["create_slide","export_pdf","export_pptx"]);function vV(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?RT.has(r)?"presentation":null:"presentation"}return null}var TT={"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`},Ob={image:"image",video:"video",presentation:"presentation",shown:"result"};function CT(e){let t={image:0,video:0,presentation:0,shown:0};for(let r of e)t[wT(r)]++;let n=[];return Object.keys(t).forEach(r=>{let s=t[r];s&&n.push(`${s} ${Gn(s,Ob[r],`${Ob[r]}s`)}`)}),`Worked on ${Zi(n)}`}function Ms(e,t){let n=t.map(Ke),r=n.length,s=Db(n);switch(e){case"explore":{let o=n.filter(i=>ee(i.tool)==="read").length;return o===r?`Read ${r} ${Gn(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} ${Gn(r,"query","queries")}`;if(i===0)return`Read ${r} ${Gn(r,"page","pages")}`;let a=new Set;for(let p of n)if(o(p)){let d=p.state?.output;for(let g of Eb(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 c=a.size||r;return`Searched and read ${c} ${Gn(c,"source","sources")}`}case"create":{if(r===1){let i=n[0],a=ee(i.tool);if(a==="image_gen")return PT(i);if(a==="video_gen")return"Made a video";if(a==="presentation_gen")return xT(i);let c=bT(i);return c?`Showed you ${c}`:"Showed you the result"}let o=n.map(AT);return Ht(o)?TT[o[0]](r):CT(o)}case"plan":return r===1?"Planned the work":`Planned the work \xB7 ${r} steps`;case"delegate":{let o=n.map(cT);if(Ht(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(fT);if(Ht(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(pT);if(Ht(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(lT);if(Ht(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(gT);if(Ht(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 ${Es(n[0].tool)}`;let o=Array.from(new Set(n.map(i=>Es(i.tool))));return o.length===1?`Used ${o[0]} \xB7 ${r} times`:`Used ${Zi(o)}`}}}function jb(e,t){let n=t.map(Ke),r=Db(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=>Es(a.tool))));return`Couldn't finish using ${Zi(i)}`}}}var IT=new Set(["get_mem","memory_search","mem_search","ltm_search","dcp_compress","dcp_distill","dcp_prune","prune","distill","compress","context_info"]),ET={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 MT(e,t){if(e==="filePath"||e==="path"||e==="file"){let n=t.split("/");return n[n.length-1]||t}return e==="query"&&xs(t)||t}function OT(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 MT(r,s.trim())}}function Vn(e){let t=ge(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=ET[n],s=t.state?.input;return r?{verb:r.verb,running:r.running,object:OT(s,r.objectKeys),tier:IT.has(n)?"plumbing":"primary"}:{verb:"Used",running:"Using",object:n,tier:"primary"}}function ta(e){let t=0,n=0,r=!1,s=!1;for(let o of e){if(Vn(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)&&Ji(o)!=="ok"&&(n+=1)}return{total:t,failed:n,completed:t-n,hasPlumbing:r}}function ea(e){return`${e} ${e===1?"step":"steps"}`}function DT(e,t){let{total:n,failed:r,completed:s,hasPlumbing:o}=e;return t?n===0?"Working":`Working \xB7 ${ea(n)}`:n===0?o?"Housekeeping":"Worked":r===0?`Completed ${ea(n)}`:s===0?`${ea(n)} failed`:`Completed ${s} of ${n} steps \xB7 ${r} failed`}function Lb(e){let t=new Map,n=0;for(let s of e){if(!te(s)||Vn(s).tier==="plumbing")continue;let o=Wn(s.tool);o!=="hidden"&&(t.set(o,[...t.get(o)??[],s]),Ji(s)!=="ok"&&(n+=1))}if(t.size===0)return DT(ta(e),!1);let r=[...t].map(([s,o],i)=>{let a=Ms(s,o);return i===0?a:a.charAt(0).toLowerCase()+a.slice(1)}).join(", ");return n>0?`${r} \xB7 ${n} failed`:r}function $V(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)},c=(e.userMessage?.parts??[]).some(p=>p.type==="compaction");c&&(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 c&&e.assistantMessages.length===0&&(r=!0),{isCompaction:t,hasContent:n,inFlight:r,error:s}}function jT(e){return e.some(t=>t.state?.status==="running"||t.state?.status==="pending")?"running":e.some(t=>t.state?.status==="error")?"error":"done"}function LT(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 $b(e,t){let n=t.map(Ke),r=jT(n);return{id:n[0].callID,family:e,label:r==="error"?jb(e,n):Ms(e,n),parts:t,status:r,durationMs:r==="running"?void 0:LT(n)}}function Ub(e){let t=[],n=null,r=[],s=()=>{n&&r.length&&t.push($b(n,r)),n=null,r=[]};for(let o of e){let i=Ke(o),a=Wn(i.tool);if(a!=="hidden"&&!Jo(i)){if(xy(i.tool)){s(),t.push($b(a,[o]));continue}a!==n&&(s(),n=a),r.push(o)}}return s(),t}function na(e){let t=e.time?.end;return!(typeof t=="number"&&t>0)}function Fb(e,t){let n=[],r=null,s=[],o=()=>{if(r&&r.texts.length>0){let{startedAt:a,endedAt:c}=r,p=typeof a=="number"&&typeof c=="number"&&c>a?c-a:void 0;n.push({kind:"thought",key:r.key,texts:r.texts,running:r.running,durationMs:p})}r=null},i=()=>{if(s.length!==0){for(let a of Ub(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 c=a.text?.trim();if(!c)continue;i(),r||(r={key:`thought-${a.id}`,texts:[],running:!1}),r.texts.push(c);let p=a.time;r.startedAt===void 0&&typeof p?.start=="number"&&(r.startedAt=p.start),r.endedAt=typeof p?.end=="number"&&p.end>0?p.end:void 0,r.running=na(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 c=n[a];c.kind==="thought"&&(c.running=!1)}return n}var $T=/^(thinking|thought|considering|planning|deciding|weighing|exploring|analy[sz]ing|reasoning|working out|figuring)/i;function UT(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 WV(e){let t=e.flatMap(s=>{let o=UT(s);return o?[o]:[]}).join(" ").trim();return t?$T.test(t)?t:`Thinking about ${/^[A-Z][a-z]/.test(t)?t[0].toLowerCase()+t.slice(1):t}`:"Thinking"}function FT(e){return e?.info?.time??{}}function HV(e){let t=FT(e).created;return typeof t!="number"||!Number.isFinite(t)||t<=0?null:t}var Os=6e4,NT=10080*Os,Nb=1440;function Bb(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 BT(e,t){let n=t.getTime()-e.getTime(),r=n/Os,s=(i,a)=>`${i} ${a}${i===1?"":"s"} ago`;if(r<60)return s(Math.round(r),"minute");if(r<Nb)return s(Math.round(r/60),"hour");let o=(n-(Bb(t)-Bb(e)))/Os;return s(Math.round(o/Nb),"day")}function Gb(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 Kb=new Map;function KT(e,t){let n={...e,...t.timeZone?{timeZone:t.timeZone}:{}},r=`${t.locale??""}|${JSON.stringify(n)}`,s=Kb.get(r);return s||(s=new Intl.DateTimeFormat(t.locale,n),Kb.set(r,s)),s}function Ds(e,t,n){return KT(t,n).formatToParts(e).map(r=>r.type==="dayPeriod"?qT(r.value,n):r.value).join("")}function qT(e,t){let n=/^([ap])\.?\s?m\.?$/i.exec(e.trim());return n?`${n[1].toUpperCase()}M`:e.toLocaleUpperCase(t.locale)}function qb(e,t){return Ds(e,{year:"numeric"},t)}function zV(e,t,n={}){let r=Gb(e);if(!r)return"";let s=i=>Ds(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<Os?"just now":o<NT?BT(r,new Date(t)):s(qb(r,n)!==qb(new Date(t),n))}function YV(e,t={}){let n=Gb(e);if(!n)return"";let r=Ds(n,{month:"long",day:"numeric",year:"numeric"},t),s=Ds(n,{hour:"numeric",minute:"2-digit"},t);return`${r} ${s}`}function Wb(e,t={}){let n=[],r=[],s=()=>{r.length>0&&(n.push({kind:"burst",parts:r}),r=[])};for(let o of e)if(!wy(o)){if(Je(o)){s(),n.push({kind:"text",part:o});continue}if(te(o)&&(ky(o.tool)||!!t.standaloneCallIds?.has(o.callID))){s(),n.push({kind:"standalone",part:o});continue}r.push(o)}return s(),n}function GT(e){let t=he(e);return t==="show"||t==="show_user"}function Hb(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"&>(o.part.tool)&&!t.standaloneCallIds?.has(o.part.callID)){r.push(o);continue}s(),n.push(o)}return s(),n}var WT=["title","description","path","url","content","language","aspect_ratio","attachment"];function Vb(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 s of WT){let o=n[s];typeof o=="string"&&o&&(r[s]=o)}return r}function VT(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 zb(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=VT(s.items),i=o?o.map(a=>Vb(n.callID,a)).filter(a=>!!a):[Vb(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 Yb(e){return!e.working||e.awaitingUser?!1:e.isRetrying?!0:!e.hasError}var Hn=e=>"id"in e?e.id:e.userMessage.info.id,Jb=e=>"assistant"in e?e.assistant.length:e.assistantMessages.length,HT=e=>e.time?.completed;function oH(e){return!e.hasPendingTurns||!e.newestAssistantCompleted?!1:e.pendingDelivery||!!e.deliveringBelow||e.activeTurnId!==null&&e.activeTurnId!==e.workingTurnId}function zT(e,t){let n=Hn(e);return t.pendingTurnIds.has(n)||Jb(e)===0&&t.pendingPromptIds.has(n)}function iH(e){let t=e.turns.find(r=>e.deliveringPromptIds.has(Hn(r)));if(t)return Hn(t);let n=e.turns.findIndex(r=>zT(r,e));return n<=0?null:Hn(e.turns[n-1])}function aH(e){return e.isTurnWorking&&!e.pendingDelivery&&e.activeTurnId===e.turnId}function cH(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 lH(e){return!e.lastTurnWorking||e.workingTurnId===null||e.suppressed?!1:Yb({working:!0,hasError:e.workingTurnHasError,isRetrying:e.isRetrying,awaitingUser:e.awaitingUser})}function uH(e,t){for(let n=e.length-1;n>=0;n--){let r=Hn(e[n]);if(t(r))return Jb(e[n])===0?r:null}return null}function Qb(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(c=>c.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],c=a.assistantMessages[a.assistantMessages.length-1];if(!HT(c.info)&&!c.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 mH(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 fH(e,t){return!t||!e?!1:e.type!=="idle"}function yH(e,t){return!e&&!!t}function hH(e){for(let t of e.assistantMessages){let n=t.info;if(n.error)return xe(n.error)?.message||_e(n.error)}}function _H(e){for(let t of e.assistantMessages){let n=t.info;if(n.error)return Ps(n.error)}}function bH(e){for(let t of e.assistantMessages){let n=t.info;if(n.error)return xe(n.error)}}function Xb(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 YT=new Set(["task","agent_task","agent-task","task_create","task-create","task_start","task-start"]);function JT(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=Xb(n.parts[r]);if(s)return s}}}function QT(e,t){let n=te(e)?e:void 0;if(n&&YT.has(n.tool)&&n.state.status==="running"){let r=JT(t);return r||(t?.length?"Handing off to an agent...":void 0)}return Xb(e)}function Zb(e,t){for(let n=e.length-1;n>=0;n--){let r=QT(e[n].part,t);if(r)return r}return"Figuring out what\u2019s next..."}function eS(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 tS=1.055;function nS(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),c=[...t.tiers??[],...t.contextOver200k?[t.contextOver200k]:[]].filter(d=>n>d.contextThreshold).sort((d,g)=>g.contextThreshold-d.contextThreshold)[0]??t,p=i/1e6*c.inputPer1M;return p+=r/1e6*c.outputPer1M,s>0&&(p+=s/1e6*(c.cacheReadPer1M??c.inputPer1M)),o>0&&(p+=o/1e6*(c.cacheWritePer1M??c.inputPer1M)),p}function ra(e,t){return e==="codex"||e==="openai-codex"||e==="kortix"&&!!t?.startsWith("codex/")}function rS(e,t,n,r){if(ra(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?nS(e.tokens,o):0}function sS(e){if(e.role!=="assistant")return{};let t=e;return{providerID:t.providerID,modelID:t.modelID}}function sa(e,t){let n=0,r=0,s=0,o=0,i=0,a=0,c=!1;for(let{part:p,message:d}of e)if(p.type==="step-finish"){c=!0;let g=p,{providerID:m,modelID:f}=sS(d.info);n+=rS(g,m,f,t),r+=g.tokens?.input||0,s+=g.tokens?.output||0,o+=g.tokens?.reasoning||0,i+=g.tokens?.cache?.read||0,a+=g.tokens?.cache?.write||0}if(!c){let p=new Set;for(let{message:d}of e){if(d.info.role!=="assistant")continue;let g=d.info;if(p.has(g.id))continue;p.add(g.id);let m=oS(g,t),f=g.tokens&&ra(g.providerID,g.modelID);if(m<=0&&!f)continue;c=!0,n+=m;let _=g.tokens;_&&(r+=_.input??0,s+=_.output??0,o+=_.reasoning??0,i+=_.cache?.read??0,a+=_.cache?.write??0)}}if(c)return{cost:n*tS,tokens:{input:r,output:s,reasoning:o,cacheRead:i,cacheWrite:a}}}function oS(e,t){if(ra(e.providerID,e.modelID)||!t||!e.providerID||!e.modelID||!e.tokens)return 0;let n=t(e.providerID,e.modelID);return n?nS({input:e.tokens.input,output:e.tokens.output,reasoning:e.tokens.reasoning,cache:e.tokens.cache},n):0}function SH(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,c=!1;for(let p of r.parts)p.type==="step-finish"&&(c=!0,a+=rS(p,o,i,t));c||(a+=oS(s,t)),n+=a}return n*tS}function PH(e){return e===0?"$0.00":e<.001?`$${e.toFixed(4)}`:e<.01?`$${e.toFixed(3)}`:`$${e.toFixed(2)}`}function xH(e){return e<1e3?String(e):e<1e4?`${(e/1e3).toFixed(1)}k`:`${Math.round(e/1e3)}k`}function wH(e){if(!e||e.type!=="retry")return;let t=e,n=_e(t.message);return{attempt:t.attempt,message:n.length>60?`${n.slice(0,60)}...`:n,next:t.next,details:xe(t.message)}}function kH(e){if(!(!e||e.type!=="retry"))return _e(e.message)}function vH(e){return(e.info.summary?.diffs?.length??0)>0}function iS(e){if(e.kind==="show-group")return!0;if(e.kind!=="standalone")return!1;let t=he(e.part.tool);return t==="show"||t==="show_user"}function XT(e){return e.kind==="text"&&!e.part.text?.trim()}function aS(e,t){if(t.working)return null;let n=-1;for(let s=e.length-1;s>=0;s--){let o=e[s];if(!(iS(o)||XT(o))){o.kind==="text"&&(n=s);break}}let r={work:[],hoisted:[],final:[]};return e.forEach((s,o)=>{o===n?r.final.push(s):iS(s)?r.hoisted.push(s):r.work.push(s)}),r.work.length>0?r:null}function CH(e){let t=e==null?"":eS(e);return t?`Worked for ${t}`:"Worked"}function ZT(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 MH(e){if(ZT(e))return e.assistantMessages[0].parts[0]}function jH(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=nb(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 LH(e){return e?e.split(`
|
|
84
|
+
`).filter(n=>n.trim()).length<=3:!1}function $H(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 UH(e){if(!e)return[];let t=[],n=e.split(`
|
|
86
|
+
`).filter(r=>r.trim());for(let r of n){let s=ib(r);if(s){let o=r.match(/\bses_[a-zA-Z0-9]+/);t.push({...s,sessionId:o?.[0]})}}return t}var Pt={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 NH(e,t){let n=Pt[e];return t==="running"?n.running:t==="failed"?n.failed:n.verb}function BH(e,t){return t?"failed":e?"running":"done"}var GH={view:"View",create:"Create",str_replace:"Edit",insert:"Insert",delete:"Delete",rename:"Rename"};function WH(e){return e?e.replace(/^\.\//,"").replace(/^(?:\.kortix\/)?memory(?:\/|$)/,"").replace(/\/$/,"")||"memory":""}function VH(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(sb(r,"content of "," with line numbers"))return{type:"file",content:s.split(`
|
|
88
88
|
`).map(i=>i.replace(/^\s*\d+(\t|$)/,"")).join(`
|
|
89
89
|
`)};if(/files and directories/i.test(r)){let o=t.replace(/\/$/,""),i=[];for(let a of s.split(`
|
|
90
|
-
`)){if(!a.trim())continue;let c=a.indexOf(" ");if(c===-1)continue;let p=a.slice(0,c).trim(),d=a.slice(c+1).trim();d!==o&&i.push({size:p,path:d,isDir:!/\.\w+$/.test(d)})}return{type:"dir",entries:i}}return null}var
|
|
90
|
+
`)){if(!a.trim())continue;let c=a.indexOf(" ");if(c===-1)continue;let p=a.slice(0,c).trim(),d=a.slice(c+1).trim();d!==o&&i.push({size:p,path:d,isDir:!/\.\w+$/.test(d)})}return{type:"dir",entries:i}}return null}var eC={add:{...Pt.write,icon:"create"},delete:{...Pt.delete,icon:"delete"},move:{...Pt.rename,icon:"edit"},update:{...Pt.edit,icon:"edit"}},cS={...Pt.change,icon:"edit"};function YH(e){if(e.length===0)return cS;let t=lS(e[0]);for(let n=1;n<e.length;n++)if(lS(e[n])!==t)return cS;return eC[t]}function lS(e){return e==="add"||e==="delete"||e==="move"?e:"update"}function QH(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 uS(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 tz(e){if(!e)return null;let t=Fn(e,"<path>","</path>"),n=t!==null?t.trim():void 0,r=Fi(e,"content");if(r!==null){let o=r.split(`
|
|
91
91
|
`).map(i=>i.replace(/^\s*\d+:\s?/,"")).join(`
|
|
92
|
-
`);return{path:n,type:"file",content:o}}let s=
|
|
93
|
-
`).map(i=>i.trim()).filter(i=>i&&!/^\(\d+\s+entr/i.test(i));return{path:n,type:"directory",entries:o}}return null}function
|
|
94
|
-
\u2026`:e}function
|
|
92
|
+
`);return{path:n,type:"file",content:o}}let s=Fi(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 sz(e){let t=tb(e,"skill_content");return t!==null?t.trim():e}function tC(e){let t=Fn(e,"<skill_files>","</skill_files>");return t===null?[]:rb(t,"<file>","</file>").map(n=>n.trim())}function nC(e){let t=eb(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 rC(e){return ob(e,["Base directory","Directory","Skill directory"])?.trim()??""}function sC(e){return Ye(nC(e)||rC(e))}function oz(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 oC="skills";function iC(e){let t=Z_(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?`${oC}/${r}`:""}function iz(e,t,n){let s=Ye(t?.trim()??"")||sC(e)||iC(n),o=tC(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 aC=4e3;function zn(e,t=aC){return e.length>t?`${e.slice(0,t)}
|
|
94
|
+
\u2026`:e}function pS(e){if(e!==void 0)try{return zn(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 zt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}function cC(e){let t=ne(e.input?.query)??"";if(e.status==="error")return{kind:"web-search",query:t,error:e.error??"Search failed"};let n=zt(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=zt(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 lC=/<exit_code>\s*(-?\d+)\s*<\/exit_code>/;function gS(e){let t=e.match(lC);return t?Number(t[1]):void 0}function uC(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 pC=["<system_info>","</system_info>","<exit_code>","</exit_code>","<stderr_note>","</stderr_note>"];function dC(e){let t=-1;for(let n of pC){let r=e.indexOf(n);r!==-1&&(t===-1||r<t)&&(t=r)}return t===-1?e:e.slice(0,t)}function gC(e){let t=ne(e.input?.command)??"",n=e.output??"",r=gS(n),o=mb(dC(uC(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 ia(e){return ne(e.input?.filePath,e.input?.file_path,e.input?.path)??""}function mC(e){let t=e.status==="error"?e.error:e.output&&zn(e.output)||void 0;return{kind:"file-read",path:ia(e),preview:t}}function fC(e){let t=ne(e.input?.content),n=e.status==="error"?e.error:zn(t??e.output??"")||void 0;return{kind:"file-write",path:ia(e),preview:n}}var yC=256*1024;function hC(e,t){if(e.length+t.length>yC)return;let n=e.split(`
|
|
95
95
|
`),r=t.split(`
|
|
96
|
-
`),s=0;for(;s<n.length&&s<r.length&&n[s]===r[s];)s++;let o=n.length,i=r.length;for(;o>s&&i>s&&n[o-1]===r[i-1];)o--,i--;let a=[];for(let c=0;c<s;c++)a.push({type:"unchanged",text:n[c]});for(let c=s;c<o;c++)a.push({type:"removed",text:n[c]});for(let c=s;c<i;c++)a.push({type:"added",text:r[c]});for(let c=o;c<n.length;c++)a.push({type:"unchanged",text:n[c]});return a}function
|
|
97
|
-
`).map(t=>t.trim()).filter(t=>t.startsWith("/")||t.startsWith("./")||t.startsWith("~")).map(t=>({path:t}))}function pT(e){let t=ne(e.input?.pattern,e.input?.query)??"";if(e.status==="error"||!e.output)return{kind:"search",pattern:t};let n=lP.test(e.output.trim())?lT(e.output):uT(e.output);return{kind:"search",pattern:t,matches:n.length>0?n.slice(0,200):void 0}}function dT(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 na(e){let t=Vt(e)??{};return{content:ne(t.content)??"",status:ne(t.status)??"pending",priority:ne(t.priority)}}function gT(e){let t=e.input?.todos;if(Array.isArray(t))return{kind:"todo",items:t.map(na)};if(Array.isArray(e.outputParsed))return{kind:"todo",items:e.outputParsed.map(na)};let n=Vt(e.outputParsed);return n&&Array.isArray(n.todos)?{kind:"todo",items:n.todos.map(na)}:{kind:"todo",items:[]}}function mT(e){return{kind:"question",questions:(Array.isArray(e.input?.questions)?e.input.questions:[]).map(r=>{let s=Vt(r)??{},i=(Array.isArray(s.options)?s.options:[]).flatMap(a=>{let c=Vt(a),p=c&&ne(c.label);return p?[{label:p,description:c?ne(c.description):void 0}]:[]});return{question:ne(s.question)??"",header:ne(s.header),options:i}})}}function fT(e){let n=e.input&&Object.keys(e.input).length>0?iP(e.input):void 0,r;return e.outputParsed!==void 0?r=typeof e.outputParsed=="string"?Wn(e.outputParsed):iP(e.outputParsed):e.outputText!==void 0?r=Wn(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 QC(e);case"bash":return nT(e);case"read":return rT(e);case"write":return sT(e);case"edit":return aT(e);case"grep":case"glob":return pT(e);case"task":return dT(e);case"todowrite":return gT(e);case"question":return mT(e);default:return fT(e)}}var hT=new Set(["AbortError","MessageAbortedError"]),_T=["operation was aborted","aborted by user","interrupted by user","cancelled by user","canceled by user","request was cancelled","request was canceled","aborterror"],bT=["unreachable","upstream","econnreset","econnrefused","socket hang up","network","fetch failed","timed out","timeout","gateway","502","503","504"];function uP(e){let t=e.toLowerCase();return bT.some(n=>t.includes(n))?!1:_T.some(n=>t.includes(n))}function PT(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 Ds(e){if(typeof e=="string")return uP(e);if(!e||typeof e!="object")return!1;let t=e,n=t.name;if(typeof n=="string"&&hT.has(n))return!0;let r=PT(t);return typeof r=="string"?uP(r):!1}var ST=["user","runtime-disposed","orphan-finalized","wake"],GH=["orphan-finalized","wake"];function WH(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 ST.includes(n)?n:void 0}var js="kortix-active-instance",xT=["/dashboard","/agents","/p","/workspace","/settings","/browser","/desktop","/services","/sessions","/terminal","/files","/scheduled-tasks","/commands","/tools","/configuration","/changelog","/legacy","/credits-explained"];function wT(e){return xT.some(t=>e===t||e.startsWith(`${t}/`))}function Vn(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 HH(e){let t=Vn(e);return!!t&&t.innerPath===""}function zH(e){let t=Vn(e);return!t||!t.innerPath?e:t.innerPath}function kT(e,t){if(!e)return t;if(t.startsWith("/")||(t=`/${t}`),t.startsWith("/instances/")){let n=Vn(t);return n?`/instances/${encodeURIComponent(e)}${n.innerPath}`:t}return wT(t)?`/instances/${encodeURIComponent(e)}${t}`:t}function vT(e){return e?Vn(e)?.instanceId??null:null}function YH(){return typeof window>"u"?null:vT(window.location.pathname)||AT()}function AT(){if(typeof document>"u")return null;let e=document.cookie.match(new RegExp(`(?:^|; )${js}=([^;]+)`));return e?decodeURIComponent(e[1]):null}function JH(e){if(typeof document>"u")return;let t=n=>{document.cookie=n};if(typeof window<"u"&&window.location.pathname.startsWith("/projects")){t(`${js}=; Max-Age=0; Path=/; SameSite=Lax`);return}if(!e){t(`${js}=; Max-Age=0; Path=/; SameSite=Lax`);return}t(`${js}=${encodeURIComponent(e)}; Path=/; SameSite=Lax`)}function QH(e,t){return t?kT(t,e):e}function XH(e){let t=Vn(e);return t?t.innerPath||"/dashboard":e}function Hn(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 pP(e){let t=Hn(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 ez=pP;function sa(e){let t=pP(e);if(!t||typeof t!="object")return null;let n=t;return n.name==="ConfigInvalidError"?n:null}var tz=sa;function RT(e){return sa(e)!==null}var nz=RT,CT=[/sandbox not ready/i,/sandbox is not (?:ready|running)/i,/opencode (?:session )?(?:is )?not ready/i,/\bsandbox_not_ready\b/,/\bsandbox_lifecycle_unavailable\b/],rz=["runtime_not_ready","sandbox runtime not ready","opencode not ready"],TT=/\bruntime_not_ready\b|sandbox runtime not ready|opencode not ready/i;function IT(e){return TT.test(Hn(e))}function zn(e){let t=Hn(e);return t?IT(t)||CT.some(n=>n.test(t)):!1}var ET=/server url not ready|sandbox is still loading/i;function sz(e){return ET.test(Hn(e))||zn(e)}var Ls=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 MT(e){let t=sa(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=Hn(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 oz=MT;function dP(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`${tt()}/p/${e.external_id}/${et.KORTIX_MASTER}`}function lz(e,t){return e.external_id?`${tt()}/p/${e.external_id}/${t}`:null}async function mz(){let e=await l.get("/setup/sandbox-providers");if(e.error)throw e.error;return e.data}async function OT(e){let t=await dn();if(t)return{sandbox:t.sandbox,created:!1};let r=(await At())[0];if(!r)throw new Error("Create a project before starting a sandbox");let s=await Ot(r.project_id,{...e?.provider?{provider:e.provider}:{}}),o=(await dt(r.project_id,s.session_id))?.sandbox??null;return{sandbox:ts(r,s,o),created:!0}}async function fz(){return(await dn().catch(()=>null))?.sandbox??null}async function yz(e){return{sandbox:(await OT(e)).sandbox}}async function hz(e){let t=pn(e);if(!t)return null;try{let n=await Xo(t);return n?ts(await Rt(n.project_id),n,null):(await dn(t))?.sandbox??null}catch{return null}}async function _z(e,t){throw await ns(e)?new Error("Renaming project-session sandboxes is not exposed by the current API"):new Error("Project session sandbox not found")}async function bz(e){let t=pn(e);return(await Qo().catch(()=>[])).map(r=>r.sandbox).filter(r=>!t||r.sandbox_id===t||r.external_id===t)}async function Pz(){return null}async function Sz(e){if(!e)throw new Error("No sandbox selected for workload restart");let t=await ns(e);if(!t)throw new Error("Project session sandbox not found");await Or(t.projectId,t.sessionId)}async function xz(e){if(!e)throw new Error("No sandbox selected to stop");let t=await ns(e);if(!t)throw new Error("Project session sandbox not found");await Dr(t.projectId,t.sessionId)}async function wz(e){throw new Error("Cancellation is not exposed for project-session sandboxes")}async function kz(e){throw new Error("Reactivation is not exposed for project-session sandboxes")}async function oa(e,t,n){let r=dP(e),s=await L(`${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 Tz(e,t){return oa(e,`/kortix/projects/${encodeURIComponent(t)}/members`,{method:"GET"})}async function Iz(e,t,n,r="member"){await oa(e,`/kortix/projects/${encodeURIComponent(t)}/members`,{method:"POST",body:JSON.stringify({user_id:n,role:r})})}async function Ez(e,t,n){await oa(e,`/kortix/projects/${encodeURIComponent(t)}/members/${encodeURIComponent(n)}`,{method:"DELETE"})}var ia="Use the account invite functions (acceptAccountInvite, declineAccountInvite).";async function Dz(e){throw U("getInvite",ia)}async function jz(e){throw U("acceptInvite",ia)}async function Lz(e){throw U("declineInvite",ia)}async function Uz(e){throw new Error("Backups are not exposed for project-session sandboxes")}async function Fz(e,t){throw new Error("Backups are not exposed for project-session sandboxes")}async function Nz(e,t){throw new Error("Backups are not exposed for project-session sandboxes")}async function Kz(e,t){throw new Error("Backups are not exposed for project-session sandboxes")}async function qz(e){throw new Error("SSH setup is not exposed for project-session sandboxes")}async function Gz(e){throw new Error("SSH connection details are not exposed for project-session sandboxes")}var DT=["pulling","patching","stopping","removing","recreating","restarting","verifying","starting","health_check"];function zz(e){return DT.includes(e)}async function Yz(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 Jz(e){let t=e?`?channel=${e}`:"",r=await(await Oe(`${tt()}/platform/sandbox/version/latest${t}`,{headers:{Accept:"application/json"}},{},"Version check failed")).json();try{let s=await jT(e||"stable");r.changelog=s.find(o=>o.version===r.version)??s[0]??null}catch{r.changelog=null}return r}async function jT(e){let t=e?`?channel=${e}`:"";return(await(await Oe(`${tt()}/platform/sandbox/version/changelog${t}`,{headers:{Accept:"application/json"}},{},"Changelog fetch failed")).json()).changelog}async function Qz(){return(await Oe(`${tt()}/platform/sandbox/version/all`,{headers:{Accept:"application/json"}},{},"All versions fetch failed")).json()}async function Xz(e,t){throw new Error("Sandbox image updates are managed by project-session provisioning")}async function Zz(e){}async function eY(e){}async function rY(e){return{serverTypes:[],location:e||"hel1"}}async function sY(e){throw new Error("Retired instance provisioning is unavailable. Create a project session with daytona, platinum, or e2b.")}async function oY(e){throw U("deleteInstance")}async function iY(e,t){}async function aY(){throw U("claimComputer")}async function cY(e){return null}function lY(e,t){throw U("getSandboxProvisionStreamUrl")}var $s=class extends Error{constructor(n,r,s){super(n);this.status=r;this.body=s;this.name="HostBoundaryError"}status;body};function gP(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 mP(e){let t=await e.text().catch(()=>"");if(!t)return null;try{return JSON.parse(t)}catch{return t}}function fP(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(`${gt(t.backendUrl)}${e}`,{method:n?.method??"GET",headers:gP(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 mP(s);if(!s.ok)throw new $s(fP(s,o),s.status,o);return o}function LT(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 mY(e,t){return X(`/marketplace/items${LT(t)}`,e)}function fY(e){return X("/marketplace/marketplaces",e)}function yY(e,t){return X(`/marketplace/items/${encodeURIComponent(e)}`,t)}function hY(e,t,n){return X(`/marketplace/items/${encodeURIComponent(e)}/file?path=${encodeURIComponent(t)}`,n)}function _Y(e,t){return X("/access/check-email",t,{method:"POST",body:{email:e}})}function bY(e,t){return X("/access/request-access",t,{method:"POST",body:e})}function PY(e){return X("/auth/logout",e,{method:"POST",body:{}})}function SY(e,t){return X(`/oauth/authorize/consent/${encodeURIComponent(e)}`,t)}function xY(e,t){return X("/oauth/authorize/consent",t,{method:"POST",body:{request_id:e.requestId,approved:e.approved}})}function wY(e,t){return X(`/setup-links/connectors/${encodeURIComponent(e)}`,t)}function kY(e,t){return X(`/setup-links/connectors/${encodeURIComponent(e)}/start`,t,{method:"POST",body:{}})}function vY(e,t,n={}){return X(`/setup-links/connectors/${encodeURIComponent(e)}/finalize`,t,{method:"POST",body:n.connectionId?{connection_id:n.connectionId}:{}})}function AY(e,t){return X(`/setup-links/secret/${encodeURIComponent(e)}`,t)}function RY(e,t,n,r){return X(`/setup-links/secret/${encodeURIComponent(e)}`,n,{method:"POST",body:{values:t,...r?.only_requester?{only_requester:!0}:{}}})}function CY(e,t){return X(`/p/public-share/${encodeURIComponent(e)}`,t)}function TY(e,t,n){return X(`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/start`,n,{method:"POST",body:{}})}function IY(e){return X("/system/maintenance",e)}function EY(e,t){return X("/system/maintenance",t,{method:"PUT",body:e})}function MY(e){return X("/user-roles",e)}function OY(e,t){return X("/system/demo-request",t,{method:"POST",body:e})}async function DY(e,t,n){let r=await fetch(`${gt(n.backendUrl)}/accounts/${encodeURIComponent(e)}/audit/export?${Dt(t)}`,{headers:gP(n,!1),...n.signal?{signal:n.signal}:{}});if(!r.ok){let s=await mP(r);throw new $s(fP(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 jY(e,t){throw U("openStressTestStream")}function LY(e,t){throw U("buildPublicTemplateUrl")}async function $Y(e,t,n){throw U("getPublicTemplate")}var $T="kortix:connect-link:";function aa(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`${$T}${t.toString(36)}${n.toString(36)}`}function FY(e,{storage:t}={}){let n=new Map,r=new Map,s=i=>{if(t)try{let a=t.getItem(aa(i));if(!a)return;let c=JSON.parse(a);if(Date.parse(c.expires_at)<=Date.now()){t.removeItem(aa(i));return}return c}catch{return}},o=(i,a)=>{if(t)try{t.setItem(aa(i),JSON.stringify(a))}catch{}};return{peek(i){let a=r.get(i);if(a)return a;let c=s(i);return c&&r.set(i,c),c},load(i){let a=n.get(i);if(a)return a;let c=e(i).then(p=>(r.set(i,p),o(i,p),p),p=>{throw n.delete(i),p});return n.set(i,c),c}}}var yP="Could not start the connect flow.";async function NY(e){let t;try{t=await e.start()}catch(r){return{kind:"error",message:r instanceof Error?r.message:yP}}if(t.connect_url)return{kind:"popup",url:t.connect_url};if(!t.connected)return{kind:"error",message:yP};let n=null;try{n=(await e.finalize()).connected_as??null}catch{}return{kind:"connected",alreadyConnected:t.already_connected===!0,connectedAs:n}}var UT=3e3,FT=5e3,NT=5*6e4;function KY(e,t){let n=e===0?UT:FT;return t+n>NT?null:n}function BY(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 WY(){let e=await l.get("/platform/github-app/status",{showErrors:!1});if(e.error)throw e.error;if(!e.data)throw new Error("GitHub App status request failed");return e.data}async function VY(e={}){let t=await l.post("/platform/github-app/manifest-start",e,{showErrors:!1});if(t.error)throw t.error;if(!t.data)throw new Error("GitHub App manifest-start request failed");return t.data}async function HY(e){let t=await l.post("/platform/github-app/app",{app_id:e.appId,private_key:e.privateKey,installation_id:e.installationId,slug:e.slug,client_id:e.clientId,client_secret:e.clientSecret},{showErrors:!1});if(t.error)throw t.error;if(!t.data)throw new Error("GitHub App configuration request failed");return t.data}async function zY(e){let t=await l.post("/platform/github-app/pat",e,{showErrors:!1});if(t.error)throw t.error;if(!t.data)throw new Error("GitHub token configuration request failed");return t.data}async function YY(){let e=await l.delete("/platform/github-app",{showErrors:!1});if(e.error)throw e.error;if(!e.data)throw new Error("GitHub App disconnect request failed");return e.data}var QY="1";var KT="kortix.query-cache";function _P(e){return!!e&&typeof e.then=="function"}function hP(e){return _P(e)?e:Promise.resolve()}function XY(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 ZY(e){let{storage:t,userId:n,shouldPersist:r,version:s="1",maxAgeMs:o=6048e5,maxBytes:i=1e6,throttleMs:a=1e3,namespace:c=KT,now:p=()=>Date.now()}=e,d=`${c}:${n}`,g=null,m=!1,f=null,_=Promise.resolve(),y=()=>{try{return hP(t.removeItem(d)).catch(()=>{})}catch{return Promise.resolve()}},v=(P,k)=>{if(!k)return 0;let C;try{C=JSON.parse(k)}catch{return y(),0}if(!C||C.v!==s||C.user!==n||!Array.isArray(C.queries)||p()-C.at>o)return y(),0;let j=0;for(let w of C.queries){if(!w||!Array.isArray(w.k)||w.d===void 0||typeof w.t!="number"||p()-w.t>o||!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"}),j+=1)}return j},R=P=>P.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),T=(P,k)=>{let C=[],j=0;for(let w of P){let D=JSON.stringify(w).length+1;j+D>k||(C.push(w),j+=D)}return C},b=async P=>{let k=T(R(P),i);for(;;){let C={v:s,user:n,at:p(),queries:k};try{await hP(t.setItem(d,JSON.stringify(C)));return}catch{if(k.length===0)return;k=k.slice(0,Math.floor(k.length/2))}}},M=()=>{f!==null&&(clearTimeout(f),f=null)},h=()=>{M();let P=g;return!P||!m||(m=!1,_=_.then(()=>b(P)).catch(()=>{})),_},S=()=>{m=!0,f===null&&(f=setTimeout(()=>{f=null,h()},a))};return{storageKey:d,restore(P){let k;try{k=t.getItem(d)}catch{return 0}return _P(k)?k.then(C=>v(P,C)).catch(()=>0):v(P,k)},persist(P){g=P,m=!0;let k=P.getQueryCache().subscribe(C=>{C.type!=="updated"&&C.type!=="removed"&&C.type!=="added"||r(C.query.queryKey)&&S()});return()=>{k(),g===P&&(g=null,M())}},flush(){return h()},async clear(){M(),g=null,m=!1,await _,await y()}}}function e2(){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 BT="/kortix/part/";function qT(e){return typeof e=="string"&&e.startsWith(BT)}async function s2(e){if(!qT(e))throw new Error(`not an attachment part reference: ${e}`);let t=qe();if(!t)throw new Error("runtime url not bound");let n=await L(`${t}${e}`);if(!n.ok)throw new Error(`attachment part fetch failed: ${n.status}`);return n.blob()}function bP(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 GT(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 PP(e,t){return GT(e,t)?(t?bP(t):null)??bP(e):null}function Us(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 SP(e,t){try{let n=new URL(e);return n.searchParams.set("token",t),n.toString()}catch{return e}}var WT=/^p\d{1,5}-[a-z0-9-]+\.localhost$/;function VT(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function HT(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(VT).join("[a-z0-9-]+")).join("\\d{1,5}");return new RegExp(`^${o}$`).test(e)}function zT(e){try{let t=new URL(e);return t.hostname==="localhost"||t.hostname==="127.0.0.1"?t:null}catch{return null}}function xP(e){return e.port?e.port:e.protocol==="https:"?"443":"80"}function YT(e,t){let n;try{n=new URL(e)}catch{return!1}return n.protocol!=="https:"&&n.protocol!=="http:"?!1:WT.test(n.hostname)?t.backendUrls.some(r=>{let s=zT(r);return s!==null&&xP(s)===xP(n)}):t.templates.some(r=>HT(n.origin,r))}async function wP(e,t={}){if(!Us(e))return!1;let n=I().backendUrl;n&&await mt(n).catch(()=>null);let r=[n,t.serverUrl].filter(s=>typeof s=="string"&&s.length>0);return YT(e,{templates:Iy(),backendUrls:r})}async function JT(e,t={}){let n=PP(e,t.serverUrl||I().backendUrl||void 0);if(!n)return!1;let r=await tn();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 f2(e,t={}){if(Us(e)){if(!await wP(e,t))return e;let n=await tn();return n?SP(e,n):e}return await JT(e,t),e}var h2=3e3;function QT(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 _2(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 QT(o.status)}catch{return"unknown"}finally{clearTimeout(s),t?.signal?.removeEventListener("abort",r)}}function XT(e){let t=e;for(;t.endsWith("/");)t=t.slice(0,-1);return t}function S2(e,t){throw U("buildPresentationTemplatePdfUrl")}function x2(e,t){throw U("buildPresentationTemplateImageUrl")}function ZT(e,t){return`${XT(e)}/presentation/convert-to-${t}`}async function w2(e,t,n,r){let s=ZT(t,e),o=r?.pollIntervalMs??2500,i=r?.timeoutMs??4*6e4,a=Date.now(),c=!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 _=await p.blob();if(_.size===0)throw new Error("Downloaded file is empty");return _}if(p.status===202){if(c||(c=!0,r?.onGenerating?.()),Date.now()-a>i)throw new Error(`Timed out waiting for the ${e.toUpperCase()} to generate`);await new Promise((_,y)=>{let v=setTimeout(_,o);r?.signal?.addEventListener("abort",()=>{clearTimeout(v),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 A2(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 R2(e){return e==="unreachable"}function C2(e){return!e||e.status===0?"unknown":e.ok&&Lh(e.health)?"live":e.hop==="control_plane"?"waking":e.ok||e.health?.status==="starting"?"connecting":"unreachable"}var eI=1e4,T2={connection:"unknown",faultSinceMs:null};function I2(e,t,n,r=eI){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 kP({optimistic:e,abort:t,inbox:n,server:r,stream:s,activity:o,nowMs:i}){let a=!!e&&i-e.atMs<ca,c=!!t&&i-t.atMs<pa;return{receiptLive:a,receiptTurnId:e?e.turnId===void 0?e.messageId:e.turnId:null,serverFloor:a?e?.acceptedAtMs??Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY,streamFloor:a?e?.atMs:Number.NEGATIVE_INFINITY,abortLive:c,abortFloor:c?t?.settledAtMs??Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY,serverFresh:!!r&&i-r.atMs<=la,streamFresh:!!s&&i-s.atMs<=Yn,inboxFresh:!!n&&i-n.atMs<=ua,activityFresh:!!o&&i-o.atMs<=Yn}}function Ht(e){if(!e)return null;let t=Date.parse(e);return Number.isNaN(t)?null:t}function da(e,t,n){if(!t)return!1;let r=Ht(e.started_at);if(r===null||r>=t.atMs)return!1;let s=n?.lastEnded,o=Ht(s?.ended_at);return!(s&&o!==null&&Math.abs(o-t.atMs)<=1e3&&s.turn_token!==e.turn_token)}function tI(e,t,n,r){let{activity:s,server:o}=e,{serverFresh:i,abortFloor:a,activityFresh:c}=t;return c&&(!n||s.atMs>n.atMs)&&s.atMs>=a?{state:"working",source:"stream",turnId:i?o.turns.find(d=>d.state==="active"&&!da(d,n,o))?.message_id??null:null,since:s.atMs,serverOpenTurnToken:r}:null}function nI(e,t,n,r){let{server:s,stream:o}=e,{serverFresh:i,abortFloor:a}=t,c=i?s.turns.filter(g=>!da(g,n,s)):[],p=c.find(g=>g.state==="active")??c[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:Ht(p.started_at)??s.atMs,serverOpenTurnToken:r},openTurn:p}:{result:null,openTurn:p}}function rI(e,t,n){let{inbox:r,server:s,stream:o}=e,{inboxFresh:i,abortFloor:a,streamFresh:c,serverFresh:p,receiptLive:d,receiptTurnId:g,abortLive:m}=t;if(i&&r.pending>0&&r.atMs>=a)return{...c&&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 sI(e,t,n,r){let{server:s,stream:o,optimistic:i,nowMs:a}=e,{serverFresh:c,serverFloor:p,streamFresh:d,streamFloor:g,abortFloor:m,receiptLive:f,receiptTurnId:_}=t,y=c&&!n&&s.atMs>=p,v=d&&o.atMs>=g&&(o.type==="idle"||o.atMs>=m);if(y&&(!o||s.atMs>=o.atMs))return{state:"idle",source:"server",turnId:null,since:Ht(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:_,since:i.atMs,serverOpenTurnToken:r};let R=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:R.source,turnId:null,since:R.atMs,serverOpenTurnToken:r}}function vP(e){let t=kP(e),{server:n,stream:r}=e,s=r&&r.type==="idle"&&r.origin!=="local"?r:null,o=n?.turns[0]?.turn_token??null,i=tI(e,t,s,o);if(i)return i;let{result:a,openTurn:c}=nI(e,t,s,o);return a??rI(e,t,o)??sI(e,t,c,o)}var ca=6e4,la=45e3,Yn=45e3,ua=1e4,K2=3e3,pa=15e3;function B2(e,t){return t?t.serverAtMs!=null&&e.serverAtMs!=null?e.serverAtMs>=t.serverAtMs:e.atMs>=t.atMs:!0}function q2(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 W2(e){return vP(e)}function V2(e){let{optimistic:t,abort:n,inbox:r,server:s,stream:o,activity:i,nowMs:a}=e,c=[null,t?t.atMs+ca:null,n?n.atMs+pa:null,r?r.atMs+ua:null,s?s.atMs+la:null,o?o.atMs+Yn:null,i?i.atMs+Yn:null],p=null;for(let d of c)d===null||d<=a||(p===null||d<p)&&(p=d);return p}function oI(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||Ds({name:s.name??void 0,message:s.message})?null:s}var iI="SandboxMemoryGuard";function J2(e,t,n){if(!e||!t||n.hasError&&!n.isAbort)return null;let r=oI(e,t);if(r?.message){if(r.name!==iI)return{kind:"cause",name:r.name,message:r.message};let a=r.message.match(/(\d{1,3})%/)?.[1],c=r.message.split(":")[0]?.trim()||null;return{kind:"sandbox-memory",usedPct:a?Number(a):null,detail:c}}let 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 X2=6e4;function Z2(e){return e.serverCompactingAtMs!==null?!0:e.optimisticAtMs===null?!1:e.nowMs-e.optimisticAtMs<6e4}function eJ(e){if(e.serverCompactingAtMs!==null||e.optimisticAtMs===null)return null;let t=e.optimisticAtMs+6e4;return t>e.nowMs?t:null}var aI=9e4;function tJ(e){return e.serverCompactingAtMs===null?null:e.serverCompactingAtMs+aI}var rJ=75e3,sJ=2,oJ=2e4;function AP(){return{status:"idle",dispatch:"none",fingerprint:null,lastProgressAtMs:null,lastDispatchAtMs:null,attempts:[],msSinceProgress:0,settled:!1}}function iJ(e){return e.filter(t=>t!=null).join("|")}function cI(e,t){return e.length===0?"retry-start":e.filter(r=>r.step==="restart").length<t?"restart":null}function aJ(e,t,n={}){let r=n.noProgressMs??75e3,s=n.maxRestarts??2,o=n.cooldownMs??2e4;if(t.runtimeReachable)return{...AP(),settled:!0};if(!t.waking)return{...e,dispatch:"none",fingerprint:null,lastProgressAtMs:null,msSinceProgress:0};if(e.settled)return{...AP(),settled:!0};let i=e.lastProgressAtMs,a=i===null,c=t.progress!==e.fingerprint,p=i===null||c?t.nowMs:i,d=Math.max(0,t.nowMs-p),g={...e,dispatch:"none",fingerprint:t.progress,lastProgressAtMs:p,msSinceProgress:d,status:e.attempts.length>0?"escalating":"waking"};if(e.status==="exhausted")return{...g,status:"exhausted"};let m=!a&&!c&&d>=r;if(!t.serverGaveUp&&!m||e.lastDispatchAtMs!==null&&t.nowMs-e.lastDispatchAtMs<o)return g;let f=cI(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 lI={"retry-start":"retrying",restart:"restarting"};function cJ(e){if(e.status!=="escalating")return null;let t=e.attempts[e.attempts.length-1];return t?`Still waking \u2014 ${lI[t.step]} the runtime (attempt ${e.attempts.length+1})`:null}function uI(e){return e===1?"once":e===2?"twice":`${e} times`}function lJ(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 ${uI(t)}`),`Tried: ${r.join(", then ")}.`}var pJ={"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 pI(e){return!!(e.metadata??{}).legacy_migration}function dJ(e,t=0){if(t>0)return"needs-you";switch(e.status){case"queued":case"branching":case"provisioning":return"starting";case"running":return"running";case"completed":case"stopped":return pI(e)?"legacy":e.status==="completed"?"done":"stopped";case"failed":return"failed";default:return"stopped"}}function gJ(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 mJ={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 fJ(e){return e===null?"Waiting to retry":e>0?`Retrying in ${e}s`:"Retrying now"}function ga(e){return e.runtime_sessions??e.opencode_sessions??[]}function dI(e){let t=ga(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 hJ(e){let t=dI(e);return t?ga(e).filter(n=>n.parent_id===t.id&&!n.archived_at).sort((n,r)=>(r.updated_at??0)-(n.updated_at??0)||n.id.localeCompare(r.id)):[]}function _J(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=>ga(r).some(s=>s.id===t))??null)}var gI=new Set;function mI(e){for(let t of[...gI])try{t(e)}catch{}}var EP={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 MP=e=>Object.values(e.ext??{}).find(t=>t.version===Te),OP=e=>!!e&&MP(e)!==void 0,fI=e=>{let t=MP(e);return t?t.native_id??null:e.thread_id},RP=new WeakMap;function DP(e,t){let n=fI(e),r=RP.get(t);if(r&&r.native===n)return r.rows;let{rows:s}=Qr({...EP,threads:[{...e,messages:[t]}]}),o=s.map(i=>({info:i.info,parts:i.parts}));return RP.set(t,{native:n,rows:o}),o}var ma=e=>e.info.time?.created;var yI=(e,t)=>(ma(e)??-1/0)-(ma(t)??-1/0)||(e.info.id<t.info.id?-1:e.info.id>t.info.id?1:0);var CP=new WeakMap,TP=new WeakMap,jP=e=>typeof e=="object"&&e!==null,hI=e=>e!==void 0&&Number.isFinite(e)&&Math.abs(e)<=864e13?new Date(e).toISOString():null,_I=e=>e.info.role==="user"&&e.parts.some(t=>jP(t)&&t.type==="compaction"),bI=(e,t)=>{let n=e.info;return n.role==="assistant"&&n.summary===!0&&n.parentID===t.info.id},IP=new WeakMap;function PI(e,t,n){let r=t.info,s=`${e}|${String(r.id)}|${String(r.time?.created)}`,o=!1,i=n.blocks.map((a,c)=>{let p=t.parts[c];if(!jP(p)||a.type==="compaction")return a;let d=`${s}|${c}|${a.id}`,g=IP.get(p);return g&&g.key===d?(o=!0,g.block):(IP.set(p,{key:d,block:a}),a)});return o?{...n,blocks:i}:n}function SI(e){let t=new Map,n=new Set;for(let r of e){if(!_I(r))continue;let s=e.find(o=>!n.has(o)&&bI(o,r));s&&(t.set(r,s),n.add(s))}return{paired:t,used:n}}function xI(e,t,n,r,s){let o=CP.get(n);if(o&&o.sessionId===e&&o.native===t&&o.sum===r&&o.seq===s)return o;let a=Xr({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}),c=PI(t,n,a.threads[0].messages[0]),p={sessionId:e,native:t,sum:r,seq:s,message:{...c,seq:s},lost:a.grade_counts};return CP.set(n,p),p}function wI(e,t,n){let r=TP.get(n);if(r&&r.sessionId===e&&r.native===t)return r.log;let s=[...n].sort(yI),{paired:o,used:i}=SI(s),a={tool_input:0,cut_point:0,attachment:0},c=[];for(let m of s){if(i.has(m))continue;let f=xI(e,t,m,o.get(m),c.length+1);for(let _ of["tool_input","cut_point","attachment"])a[_]+=f.lost[_];c.push(f.message)}let p=hI(s.map(ma).find(m=>typeof m=="number"&&Number.isFinite(m)))??"",d=c.filter(m=>m.role==="user"&&m.kind==="turn"),g={...EP,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:c[0]?.created_at||p,messages:c,ext:{opencode:{version:Te,native_id:t}}}]};return TP.set(n,{sessionId:e,native:t,log:g}),g}var fa=new WeakMap,zt=new WeakMap,LP=new WeakMap;function Fs(e){let t,n=zt.get(e);return n&&(t=kI(n).get(e.id)),t?(fa.set(t,e),t):(e.type!=="harness"?t=Go(e):typeof e.data?.type=="string"?t=e.data:e.model_visible&&e.fallback_text!==void 0&&(t=LP.get(e)??{id:e.id,type:"text",text:e.fallback_text,synthetic:!0},LP.set(e,t)),t&&fa.set(t,e),t)}var Jn=e=>fa.get(e),xt=e=>e.flatMap(t=>Fs(t)??[]),$P=new WeakMap;function kI(e){let t=$P.get(e);return t||$P.set(e,t=new Map(ot(e)[0]?.parts.map(n=>[n.id,n]))),t}var UP=new Map;function ot(e){let t=UP.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:""},UP.set(e.thread_id,t)),DP(t,e)}var vI="kortix-v1-import",ya={schema:le,v:1};function Ns(e,t){for(let n=e.length-1;n>=0;n--)if(t(e[n]))return e[n]}var ha=e=>e.type==="tool_call",AI=e=>e.status==="pending"||e.status==="running",_a=e=>e.status==="error"&&(e.result?.synthetic===!0||e.result?.error?.code==="interrupted");function RI(e,t){let n=_a(e);return!AI(e)&&!n?e.status:t?e.status==="running"||n&&e.started_at?"running":"pending":"interrupted"}var FP=new WeakMap;function CI(e,t){let n=FP.get(e);if(n)return n;let r=typeof e.client_sent_at_ms=="number"?e.client_sent_at_ms:Date.parse(e.created_at),s={...ya,message_id:e.message_id||`queued-${e.prompt_id}`,thread_id:t,seq:Number.MAX_SAFE_INTEGER,role:"user",kind:"turn",status:"complete",in_context:!0,origin:"prompt",model:null,usage:null,finish:null,error:null,created_at:Number.isFinite(r)?new Date(r).toISOString():"",completed_at:null,producer:{harness:"kortix-inbox",harness_version:"",adapter_version:"1"},blocks:[{type:"text",id:`syn-${e.prompt_id}`,text:e.full_text??e.text}]};return FP.set(e,s),s}var NP=new WeakMap;function TI(e){let t=NP.get(e);return t||(t={...ya,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:[]},NP.set(e,t)),t}var KP=new WeakMap;function II(e){let t=KP.get(e);return t||(t={...ya,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:[]},KP.set(e,t)),t}var EI=e=>!e.error&&e.blocks.length===0&&!(e.usage&&(e.usage.input||e.usage.output||e.usage.reasoning));function MI(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,c=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)&&(c=y,i.has(y)||i.set(y,i.size),y.user.kind==="compaction"&&(p=y));continue}if(g.role!=="assistant"||EI(g))continue;let f=(g.reply_to?r.get(g.reply_to):void 0)??c;if(p&&f&&(f===p||(i.get(f)??1/0)<i.get(p))){let y=a.get(p);y||(y={user:II(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){o.push(g);continue}let _=s[s.length-1];_&&_.user.message_id===g.reply_to?_.assistant.push(g):s.push({user:TI(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 OI(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 GP(e){let n=(e.user.kind==="compaction"?[e.user,...e.assistant]:e.assistant).find(i=>i.error);if(!n?.error)return null;let r=ot(n)[0]?.info?.error??n.error.message,s=xe(r),o=Ps(r);return{code:n.error.code,message:s?.message||_e(r),...s&&{details:s},...o!==void 0&&{raw:o}}}function DI(e,t,n){return e.length&&e.every(t)?ta(e.flatMap(r=>ot(r).flatMap(s=>s.parts.map(o=>({part:o,message:s})))),n)??null:ba(e,n)}function ba(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 ta(n,t)??null}function jI(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 LI(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&&ha(n)&&n.name==="bash"?n:null}function $I(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:ha(i)?ks(i):void 0;a&&r.has(a)&&o.add(a)}return[...o]}var UI=e=>e.assistant.some(t=>t.blocks.some(n=>ha(n)&&ce(n.name)==="todowrite"&&Un(n))),FI=e=>e.blocks.length>0&&e.blocks.every(t=>t.type==="text"&&t.synthetic===!0);function NI(e,t){let n=e.map(s=>GP(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 BP=new WeakMap,KI=[];function WP(e){let t=Ns(e.messages,n=>n.role==="assistant");return!!t&&Sb(ot(t))}var qP=new WeakMap;function BI(e){let t=qP.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},qP.set(e,t)}return t}function Pa(e,t={}){let n=t.hideOutOfContext?BI(e):e,r=new Set(t.held??KI),s=MI(n.messages,r),o=Ns(n.messages,y=>y.role==="assistant"),i=WP(n),a=Vb({turns:s.map(y=>({userMessage:{info:{id:y.user.message_id}},assistantMessages:y.assistant.map(v=>({info:{time:v.status==="streaming"?{}:{completed:1},error:v.error??void 0}}))})),hintMessageId:OI(s,t.liveMessageId),unrunTurnIds:r}),c=Ns(s,UI)??s[s.length-1],p=s.map(y=>!y.partial&&FI(y.user)),d=NI(s,p),g=OP(n),m=y=>g||y.producer.harness===vI,f=t.threads??[],_=new Set(f.map(y=>y.thread_id));return s.map((y,v)=>{let R=t.busy===!0&&a.workingTurnId===y.user.message_id,T=a.pendingTurnIds.includes(y.user.message_id),b=i&&y.assistant.includes(o),M=d[v],h=`${y.partial}|${R}|${T}|${y===c}|${b}|${M?(M.continued?"c":"")+M.retries:"-"}`,S=BP.get(y.user);if(S&&S.key===h&&S.pricing===t.pricing&&S.heads===t.threads&&S.assistant.length===y.assistant.length&&S.assistant.every((w,D)=>w===y.assistant[D]))return S.turn;let P=y.assistant.flatMap(w=>w.blocks);for(let w of y.assistant)for(let D of w.blocks)zt.set(D,w);let k=$I(y,P,f,_),C=y.assistant[y.assistant.length-1],j={internal:p[v],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":C?C.status:y.user.kind==="compaction"?y.user.status:"pending",error:GP(y),cost:DI([y.user,...y.assistant],m,t.pricing),compaction:jI(y.user),threads:k,plan:y===c,shell:LI(y),response:Ns(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:T,retrying:b};return BP.set(y.user,{assistant:y.assistant,key:h,pricing:t.pricing,heads:t.threads,turn:j}),j})}var Sa=e=>Jn(e);function qI(e,t={}){return Bb(Nb(xt(e),t),t).map(n=>n.kind==="burst"?{kind:n.kind,blocks:n.parts.map(Jn)}:n.kind==="show-group"?{kind:n.kind,blocks:n.parts.map(Sa)}:n.kind==="text"?{kind:n.kind,block:Jn(n.part)}:{kind:n.kind,block:Sa(n.part)})}var GI=e=>e.kind==="burst"||e.kind==="show-group"?{kind:e.kind,parts:xt(e.blocks)}:{kind:e.kind,part:Fs(e.block)};function WI(e,t){let n=new Map(e.map(o=>[GI(o),o])),r=nP([...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 VI(e){if(!te(e)||!yy(e.tool))return!1;let t=e.state.input?.questions;if(!Array.isArray(t)||!t.length)return!1;let n=mb(e);return(n.answers??oP(n.outputText??"",t.length)??[]).length>0}function HI(e){return Db(xt(e),n=>qn(n).tier).flatMap(n=>n.kind==="group"&&n.step.parts.some(VI)?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:Jn(n.part)};if(n.kind==="group")return{kind:"group",key:n.key,blocks:n.step.parts.map(Sa),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&&zt.get(r);return{kind:"thought",key:n.key,texts:n.texts,running:n.running&&(!s||s.status==="streaming"),durationMs:n.durationMs}})}function zI(e,t){return zb(xt(e.blocks).map(n=>({part:n})),t?.flatMap(ot))}function YI(e){return Xi(xt(e))}function JI(e){return Eb(xt(e))}function QI(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=Fs(n),s=zt.get(n);return!!r&&we(r)&&Zi(r)&&(!s||s.status==="streaming")}):!1}var VP=new WeakMap;function XI(e){if(!_a(e))return e;let t=VP.get(e);if(!t){let{result:n,...r}=e;t={...r,status:e.started_at?"running":"pending"},VP.set(e,t)}return t}function ZI(e){let{callID:t,error:n,...r}=e;return e.status==="error"?{...r,type:"error",content:n||"This output failed to load."}:r}function eE(e){let t=e.map(se),n=t[0],r=t.some(o=>o.state.status==="running"||o.state.status==="pending"),s=qb(t).map(ZI);return Zr({...n,state:{...n.state,status:r?"running":"completed",input:{items:s}}})}function tE(e,t,n){let r=se(e),s=r.state;return Zr({...r,state:{...s,status:"completed",...n!==void 0&&{input:n},metadata:{...s.metadata??{},answers:t}}})}function nE(e){let t=ot(e).map(r=>Bi(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 HP=Object.freeze([]),zP=new WeakMap;function rE(e){if(!e)return HP;let t=zP.get(e);if(!t){let n=e.messages.flatMap(r=>r.role==="assistant"?r.blocks.filter(s=>s.type==="tool_call"&&Un(s)):[]);t=n.length?n:HP,zP.set(e,t)}return t}function sE(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 Pa(e)){let s=ba([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 oE="prt_kortix_restore_g";function iE(e){return e.role==="user"&&e.blocks.some(t=>t.type==="text"&&t.id.startsWith(oE))}function aE(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(c=>c.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 xa=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Je=e=>typeof e=="number"&&Number.isFinite(e)&&e>0?e:0,cE=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=xa(t)?t.restore:void 0;if(!xa(n))return null;let r=xa(n.dropped)?n.dropped:{},s=e.grade_counts,o=[{kind:"message",count:Je(r.message)},{kind:"attachment",count:Je(s?.attachment)},{kind:"text",count:Je(r.text)+Je(n.truncated)},{kind:"tool_input",count:Je(s?.tool_input)},{kind:"tool_result",count:Je(r.tool_result)},{kind:"cut_point",count:Je(s?.cut_point)},{kind:"other",count:Object.entries(r).reduce((i,[a,c])=>cE.has(a)?i:i+Je(c),0)}];return{generation:Je(n.generation),missing:o.filter(i=>i.count>0)}}var JP=e=>e.type==="text"?[e]:e.type==="tool_call"?(e.result?.content??[]).filter(t=>t.type==="text"):[];function uE(e){let t=new Map;for(let n of e)for(let r of n.blocks)for(let s of JP(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 QP=(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}},pE=(e,t)=>e.map(n=>n.type==="text"?QP(n,t):n),YP=new WeakMap;function dE(e,t){let n=YP.get(e);if(n?.texts===t)return n.out;let r=e.blocks.some(s=>JP(s).some(o=>o.ref!==void 0&&t.has(o.ref)))?{...e,blocks:e.blocks.map(s=>s.type==="text"?QP(s,t):s.type==="tool_call"&&s.result?{...s,result:{...s.result,content:pE(s.result.content,t)}}:s)}:e;return YP.set(e,{texts:t,out:r}),r}var wa=1024*1024;function gE(e){return e.reduce((t,n)=>t+n.bytes,0)>wa?"download":"inline"}function mE(e){let t=new Set,n=0;for(let r of[...e].sort((s,o)=>s.bytes-o.bytes)){if(n+r.bytes>wa)break;n+=r.bytes,t.add(r)}return{inline:e.filter(r=>t.has(r)),download:e.filter(r=>!t.has(r))}}function fE(e,t){if(t.size===0)return e;let n=e.messages.map(r=>dE(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 hE(e){let t=ZP(e)?e.code:void 0;return typeof t=="string"?t:void 0}var ZP=e=>typeof e=="object"&&e!==null;function XP(e){let t=e?.metadata;return!!ZP(t)&&t.warm===!0}var _E=5,bE=2e3,PE=e=>new Promise(t=>setTimeout(t,e));async function SE(e,{attempts:t=_E,delayMs:n=bE,sleep:r=PE}={}){for(let s=0;s<t;s++){s>0&&await r(n);try{if(await e())return!0}catch{}}return!1}function TQ(e,t){let n=new Map,r=new Set,s=new Set,o=new Set,i=0,a=(c,p,d)=>{if(r.has(c)||n.has(c))return Promise.resolve();r.add(c);let g=i,m=(async()=>{let f=null;try{let _=await e.ensure(c,p);if(g!==i)return;s.has(_.sessionId)?f=_.sessionId:n.set(c,_)}catch{}finally{g===i&&r.delete(c)}f&&d>0&&await a(c,f,d-1)})();return o.add(m),m.finally(()=>o.delete(m)),m};return{ensure:(c,p)=>a(c,p?.excludeSessionId,1),take:(c,p,{replenish:d})=>{let g=n.get(c);return g?(n.delete(c),s.add(g.sessionId),d&&a(c,g.sessionId,1),t.fits(g,p)?g:null):null},prime:async(c,p,d)=>{try{return await e.claim(c,d),!0}catch(g){return yE(hE(g))?SE(async()=>!XP(await e.read(c,p.sessionId)),t.sleep?{sleep:t.sleep}:{}):!1}},dropBySessionId:c=>{for(let[p,d]of n)if(d.sessionId===c)return n.delete(p),s.add(c),p;return null},revalidate:async c=>{let p=n.get(c);if(!p)return!1;try{if(XP(await e.read(c,p.sessionId)))return!1}catch{return!1}return n.get(c)?.sessionId!==p.sessionId?!1:(n.delete(c),s.add(p.sessionId),!0)},held:c=>n.get(c)??null,reset:()=>{i+=1,n.clear(),r.clear(),s.clear()},settled:async()=>{for(;o.size>0;)await Promise.all([...o])}}}var xE=12e4,Ks=class extends Error{constructor(t){super(`Session history read did not settle within ${t}ms`),this.name="SessionSyncReadTimeoutError"}},wE=1e3,kE=15e3,eS=100,vE=50,AE=10;function tS(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?.(),c=await t(`${n}/session/${encodeURIComponent(e.sessionId)}/message?${i}`,{headers:a?{Authorization:`Bearer ${a}`}:void 0,...o?{signal:o}:{}});if(!c.ok)throw c.status===503?new Ls(`session ${c.status}`):new x(`Session synchronization failed: ${c.status}`,{status:c.status});return{messages:await c.json(),nextCursor:c.headers.get("x-next-cursor")||void 0}}}function RE(e){return TE(tS(e))}function CE(e){return new ka({...e,loadPage:tS(e)})}async function TE(e){let t=[],n=new Set,r;do{let i=await e({limit:eS,...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 IE={now:Date.now,setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e),setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e)},ka=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??IE,this.livenessIntervalMs=t.livenessIntervalMs??1e4,this.verifyIntervalMs=t.verifyIntervalMs??3e4,this.readTimeoutMs=t.readTimeoutMs??xE,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 Ks;if(!r&&Ds(n))return;if(r||this.update({freshness:zn(n)?"loading":"error"}),n instanceof x&&(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(wE*2**this.retryAttempt,kE);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"?vE:eS,...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((c,p)=>{o=this.startTimer(()=>{let d=new Ks(this.readTimeoutMs);p(d),r.abort(d)},this.readTimeoutMs)}),a;try{a=t(r.signal)}catch(c){a=Promise.reject(c)}return Promise.race([a,i]).finally(()=>{this.cancelTimer(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),c=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<AE&&i.some(g=>g.info.role==="assistant"&&!!g.info.parentID&&!a.has(g.info.parentID));){if(c.has(p))throw new Error(`Session history cursor repeated: ${p}`);c.add(p);let g;try{g=await this.loadPage(n,r,p)}catch(m){throw 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 EE=5e3,rS=40,jQ=5*6e4,ME=16,Qn=new Map;function sS(e,t,n,r=Date.now()){let s=oS(e,t);for(Qn.delete(s),Qn.set(s,{envelope:n,atMs:r});Qn.size>ME;){let o=Qn.keys().next().value;if(o===void 0)break;Qn.delete(o)}}var nS=new Map;function oS(e,t){return`${e}/${t}`}function OE(e,t){return e.settledAtMs===null?!0:t-e.settledAtMs<=EE}function iS(e,t,n=Date.now()){if(!e||!t)return null;let r=oS(e,t),s=nS.get(r);return s?OE(s,n)?s.promise:(nS.delete(r),null):null}function aS(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 DE=2e3;async function jE(e,t,n){let r=iS(e,t),s,o=r?await Promise.race([r,new Promise(i=>{s=setTimeout(i,n.snapshotWaitMs??DE,null)})]).finally(()=>clearTimeout(s)):null;return(o&&aS(o))??Ir(e,t,{limit:rS,history:!0,signal:n.signal})}async function LE(e){let{projectId:t,sessionId:n,runtimeSessionId:r}=e;if(!t||!n||!r)return{envelope:null,empty:!1};let s;try{s=await jE(t,n,{})}catch{return{envelope:null,empty:!1}}if(sS(t,n,s),cS(s)!==r)return{envelope:s,empty:!1};try{let o=await Er(t,n);return{envelope:s,empty:lS({savedEmptyRoot:r,rootSessionId:r,turnRead:!0,hasEndedTurn:o.last_ended!=null,hasOpenOrQueuedTurn:o.turns.length>0})}}catch{return{envelope:s,empty:!1}}}function cS(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 lS(e){return e.savedEmptyRoot!==null&&e.savedEmptyRoot===e.rootSessionId&&e.turnRead&&!e.hasEndedTurn&&!e.hasOpenOrQueuedTurn}function BQ(e){throw U("buildTunnelEventStreamUrl")}function qQ(e){let{url:t,token:n,method:r="GET",body:s,onEvent:o,onOpen:i,onError:a,onClose:c,signal:p}=e,d=new Map,g=null,m=!1,f="";function _(b,M){o?.(b,M);let h=d.get(b);if(h)for(let S of h)try{S(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"&&s!==void 0&&(h["Content-Type"]="application/json"),f&&(h["Last-Event-ID"]=f);let S=await fetch(t,{method:r,headers:h,body:r!=="GET"&&s!==void 0?JSON.stringify(s):void 0,signal:M,credentials:"include"});if(!S.ok)throw new Error(`SSE connection failed: ${S.status} ${S.statusText}`);if(!S.body)throw new Error("SSE response has no body");i?.();let P=S.body.getReader(),k=new TextDecoder,C="",j="message",w=[],D=N=>{if(N===""){w.length>0&&_(j,w.join(`
|
|
98
|
-
`)),j="message",w=[];return}if(N.startsWith(":"))return;let z=N.indexOf(":"),G=z===-1?N:N.slice(0,z),B=z===-1?"":N.slice(z+1);B.startsWith(" ")&&(B=B.slice(1)),G==="event"?j=B.trim()||"message":G==="data"?w.push(B):G==="id"&&!B.includes("\0")&&(f=B)},Pe=N=>{let z="";!N&&C.endsWith("\r")&&(z="\r",C=C.slice(0,-1));let G=C.split(/\r\n|\n|\r/);C=(G.pop()??"")+z;for(let B of G)D(B)};for(;!m;){let{done:N,value:z}=await P.read();if(N)break;C+=k.decode(z,{stream:!0}),Pe(!1)}m||(C+=k.decode(),Pe(!0),c?.())}catch(h){if(m||h instanceof DOMException&&h.name==="AbortError")return;a?.(h instanceof Error?h:new Error(String(h)))}}function v(){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 T(b,M){d.get(b)?.delete(M)}return{connect:y,close:v,addEventListener:R,removeEventListener:T}}function GQ(e,t){throw U("createTunnelEventStream")}var uS="/_kortix/viewer",Bs=6e4,Yt=new Map;function $E(){Yt.clear(),Xn.clear()}async function UE(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 pS(e={}){let t=e.path??uS,n=e.fetch??((o,i)=>fetch(o,i)),r=Yt.get(t);if(r&&!r.inflight&&r.expiresAt>Date.now())return r.session;if(r?.inflight)return r.inflight;let s=UE(t,n).then(o=>{let i=o?.expires_at?Date.parse(o.expires_at):Number.NaN,a=Number.isFinite(i)?i-Bs:Date.now()+Bs;return Yt.set(t,{session:o,expiresAt:a}),o});return Yt.set(t,{session:r?.session??null,expiresAt:0,inflight:s}),s}function FE(e={}){let t=e.path??uS;return Object.assign(async()=>(await pS(e))?.access_token??null,{invalidate:n=>{let r=Yt.get(t);r&&!r.inflight&&r.session?.access_token===n&&Yt.delete(t)}})}var Xn=new Map;async function NE(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 Xn.set(e,{token:r.token,refreshAt:Number.isFinite(s)?s-Bs:Date.now()+Bs}),r.token}catch{return null}}function dS(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=Xn.get(n);if(o instanceof Promise)return o;if(o&&!s.forceRefreshToken&&o.refreshAt>Date.now())return o.token;let i=NE(n,r).then(a=>(a===null&&Xn.delete(n),a));return Xn.set(n,i),i}}function KE(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:dS({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 gS(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 Aa(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:gS(t.groups),groupIds:gS(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 BE(e,t={}){let n=Aa(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 qE=60,va=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 mS(e){return JSON.parse(new TextDecoder().decode(fS(e)))}async function GE(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=va.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(()=>va.delete(e)),va.set(e,n)),n}return JSON.parse(e)}async function WE(e,t={}){let n=b=>{throw new wt("unauthenticated",`Kortix sign-in token refused: ${b}.`)},r=t.jwks??Ze("KORTIX_AUTH_JWKS"),s=t.issuer??Ze("KORTIX_AUTH_ISSUER"),o=t.audience??Ze("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,c,p]=i,d,g;try{d=mS(a),g=mS(c)}catch{return n("malformed")}if(d.alg!=="ES256")return n("unsupported algorithm");let m;try{m=await GE(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}.${c}`),y;try{y=fS(p)}catch{return n("malformed")}let v=!1;for(let b of f)try{let{kid:M,alg:h,use:S,key_ops:P,...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,y,_)){v=!0;break}}catch{}if(!v)return n("bad signature");let R=Math.floor(Date.now()/1e3);if(typeof g.exp!="number"||g.exp+qE<R)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 T=Aa(g);return T||n("no subject")}function yS(e){let t=e.agents.map(VE),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 VE(e){return{name:e.name,description:e.description??void 0,mode:e.mode??void 0,source:e.source,hidden:e.enabled===!1}}function hS(e,t){if(!Array.isArray(e))return[];let n=t?.includeSubagents===!0;return e.filter(r=>Jo(n?{...r,mode:null}:r))}function HE(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=hS(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 zE=yS;function _S(e){return e.providerID==="kortix"||e.providerID==="opencode"?e.modelID:`${e.providerID}/${e.modelID}`}function Ra(e){return{providerID:"kortix",modelID:e}}function Ca(e,t){let n=e.startsWith("kortix/")?e.slice(7):e;if(!t){let r=n.indexOf("/");if(r>0&&r<n.length-1)return{providerID:n.slice(0,r),modelID:n.slice(r+1)}}return Ra(n)}var Ta=[{id:"deepinfra",env:["DEEPINFRA_API_KEY"]},{id:"perplexity-agent",env:["PERPLEXITY_API_KEY"]},{id:"bailing",env:["BAILING_API_TOKEN"]},{id:"poe",env:["POE_API_KEY"]},{id:"cerebras",env:["CEREBRAS_API_KEY"]},{id:"groq",env:["GROQ_API_KEY"]},{id:"blueclaw",env:["BLUECLAW_API_KEY"]},{id:"zai",env:["ZHIPU_API_KEY"]},{id:"empiriolabs",env:["EMPIRIOLABS_API_KEY"]},{id:"sensenova",env:["SENSENOVA_API_KEY"]},{id:"alibaba-token-plan",env:["ALIBABA_TOKEN_PLAN_API_KEY"]},{id:"cloudflare-workers-ai",env:["CLOUDFLARE_ACCOUNT_ID","CLOUDFLARE_API_KEY"]},{id:"engy",env:["ENGY_API_KEY"]},{id:"poolside",env:["POOLSIDE_API_KEY"]},{id:"nano-gpt",env:["NANO_GPT_API_KEY"]},{id:"abliteration-ai",env:["ABLIT_KEY"]},{id:"crof",env:["CROF_API_KEY"]},{id:"standardcompute",env:["STANDARDCOMPUTE_API_KEY"]},{id:"cloudferro-sherlock",env:["CLOUDFERRO_SHERLOCK_API_KEY"]},{id:"anthropic",env:["ANTHROPIC_API_KEY"]},{id:"tinfoil",env:["TINFOIL_API_KEY"]},{id:"llama",env:["LLAMA_API_KEY"]},{id:"cohere",env:["COHERE_API_KEY"]},{id:"deepseek",env:["DEEPSEEK_API_KEY"]},{id:"baseten",env:["BASETEN_API_KEY"]},{id:"nan",env:["NAN_API_KEY"]},{id:"stepfun-ai-step-plan",env:["STEPFUN_API_KEY"]},{id:"nearai",env:["NEARAI_API_KEY"]},{id:"wandb",env:["WANDB_API_KEY"]},{id:"subconscious",env:["SUBCONSCIOUS_API_KEY"]},{id:"zeldoc",env:["ZELDOC_API_KEY"]},{id:"databricks",env:["DATABRICKS_HOST","DATABRICKS_TOKEN"]},{id:"umans-ai-coding-plan",env:["UMANS_AI_CODING_PLAN_API_KEY"]},{id:"kuae-cloud-coding-plan",env:["KUAE_API_KEY"]},{id:"umans-ai",env:["UMANS_AI_API_KEY"]},{id:"siliconflow",env:["SILICONFLOW_API_KEY"]},{id:"minimax-coding-plan",env:["MINIMAX_API_KEY"]},{id:"alibaba-coding-plan",env:["ALIBABA_CODING_PLAN_API_KEY"]},{id:"lilac",env:["LILAC_API_KEY"]},{id:"moonshotai-cn",env:["MOONSHOT_API_KEY"]},{id:"bothub",env:["BOTHUB_API_KEY"]},{id:"xiaomi-token-plan-cn",env:["XIAOMI_API_KEY"]},{id:"privatemode-ai",env:["PRIVATEMODE_API_KEY","PRIVATEMODE_ENDPOINT"]},{id:"llmgateway-providers",env:["LLMGATEWAY_API_KEY"]},{id:"above",env:["ABOVE_API_KEY"]},{id:"kilo",env:["KILO_API_KEY"]},{id:"venice",env:["VENICE_API_KEY"]},{id:"alibaba-token-plan-cn",env:["ALIBABA_TOKEN_PLAN_API_KEY"]},{id:"ai21",env:["AI21_API_KEY"]},{id:"commandcode",env:["CMD_API_KEY"]},{id:"lowrouter",env:["LOWROUTER_API_KEY"]},{id:"reflection",env:["REFLECTION_API_KEY"]},{id:"inference",env:["INFERENCE_API_KEY"]},{id:"iflowcn",env:["IFLOW_API_KEY"]},{id:"minimax-cn-coding-plan",env:["MINIMAX_API_KEY"]},{id:"thinkingmachines",env:["TINKER_API_KEY"]},{id:"stepfun-step-plan",env:["STEPFUN_API_KEY"]},{id:"melious",env:["MELIOUS_API_KEY"]},{id:"berget",env:["BERGET_API_KEY"]},{id:"snowflake-cortex",env:["SNOWFLAKE_ACCOUNT","SNOWFLAKE_CORTEX_PAT"]},{id:"sarvam",env:["SARVAM_API_KEY"]},{id:"nova",env:["NOVA_API_KEY"]},{id:"abacus",env:["ABACUS_API_KEY"]},{id:"novita-ai",env:["NOVITA_API_KEY"]},{id:"302ai",env:["302AI_API_KEY"]},{id:"openrouter",env:["OPENROUTER_API_KEY"]},{id:"perplexity",env:["PERPLEXITY_API_KEY"]},{id:"iteracompute",env:["ITERACOMPUTE_API_KEY"]},{id:"the-grid-ai",env:["THEGRID_API_KEY"]},{id:"meta",env:["META_MODEL_API_KEY"]},{id:"cline-pass",env:["CLINE_API_KEY"]},{id:"modal",env:["MODAL_PROXY_TOKEN"]},{id:"coralbricks",env:["CORAL_API_KEY"]},{id:"routing-run",env:["ROUTING_RUN_API_KEY"]},{id:"echo",env:["ECHO_API_KEY"]},{id:"neuralwatt",env:["NEURALWATT_API_KEY"]},{id:"gitlab",env:["GITLAB_TOKEN"]},{id:"infer",env:["INFER_API_KEY"]},{id:"azure",env:["AZURE_RESOURCE_NAME","AZURE_API_KEY"]},{id:"freemodel",env:["FREEMODEL_API_KEY"]},{id:"azure-cognitive-services",env:["AZURE_COGNITIVE_SERVICES_RESOURCE_NAME","AZURE_COGNITIVE_SERVICES_API_KEY"]},{id:"pendra",env:["PENDRA_API_KEY"]},{id:"moark",env:["MOARK_API_KEY"]},{id:"atomic-chat",env:["ATOMIC_CHAT_API_KEY"]},{id:"qihang-ai",env:["QIHANG_API_KEY"]},{id:"ai-router",env:["AI_ROUTER_API_KEY"]},{id:"llmtr",env:["LLMTR_API_KEY"]},{id:"alibaba",env:["DASHSCOPE_API_KEY"]},{id:"auriko",env:["AURIKO_API_KEY"]},{id:"zenmux",env:["ZENMUX_API_KEY"]},{id:"unorouter",env:["UNOROUTER_API_KEY"]},{id:"salad-cloud",env:["SALAD_CLOUD_API_KEY"]},{id:"vispark",env:["VISPARK_LAB_API_KEY"]},{id:"siliconflow-cn",env:["SILICONFLOW_CN_API_KEY"]},{id:"regolo-ai",env:["REGOLO_API_KEY"]},{id:"xiaomi-token-plan-ams",env:["XIAOMI_API_KEY"]},{id:"inceptron",env:["INCEPTRON_API_KEY"]},{id:"aimlapi",env:["AIMLAPI_API_KEY"]},{id:"upstage",env:["UPSTAGE_API_KEY"]},{id:"vultr",env:["VULTR_API_KEY"]},{id:"huggingface",env:["HF_TOKEN"]},{id:"volcengine",env:["ARK_API_KEY"]},{id:"impossibl",env:["IMPOSSIBL_API_KEY"]},{id:"xpersona",env:["XPERSONA_API_KEY"]},{id:"qiniu-ai",env:["QINIU_API_KEY"]},{id:"modelscope",env:["MODELSCOPE_API_KEY"]},{id:"google",env:["GOOGLE_API_KEY","GOOGLE_GENERATIVE_AI_API_KEY","GEMINI_API_KEY"]},{id:"vancine",env:["VANCINE_API_KEY"]},{id:"zhipuai-coding-plan",env:["ZHIPU_API_KEY"]},{id:"lucidquery",env:["LUCIDQUERY_API_KEY"]},{id:"gmicloud",env:["GMICLOUD_API_KEY"]},{id:"oci",env:["OCI_GENAI_API_KEY"]},{id:"cloudflare-ai-gateway",env:["CLOUDFLARE_API_TOKEN","CLOUDFLARE_ACCOUNT_ID","CLOUDFLARE_GATEWAY_ID"]},{id:"clarifai",env:["CLARIFAI_PAT"]},{id:"aiand",env:["AIAND_API_KEY"]},{id:"frogbot",env:["FROGBOT_API_KEY"]},{id:"stackit",env:["STACKIT_API_KEY"]},{id:"anyapi",env:["ANYAPI_API_KEY"]},{id:"crusoe",env:["CRUSOE_API_KEY"]},{id:"volcengine-coding-plan",env:["ARK_CODING_PLAN_API_KEY"]},{id:"jiekou",env:["JIEKOU_API_KEY"]},{id:"ollama-cloud",env:["OLLAMA_API_KEY"]},{id:"agentrouter",env:["AGENTROUTER_API_KEY"]},{id:"tencent-tokenhub",env:["TENCENT_TOKENHUB_API_KEY"]},{id:"watsonx",env:["WATSONX_AI_APIKEY","WATSONX_AI_PROJECT_ID"]},{id:"ambient",env:["AMBIENT_API_KEY"]},{id:"model-oracle-ai",env:["MODEL_ORACLE_API_KEY"]},{id:"xai",env:["XAI_API_KEY"]},{id:"nebius",env:["NEBIUS_API_KEY"]},{id:"minimax-cn",env:["MINIMAX_API_KEY"]},{id:"scaleway",env:["SCALEWAY_API_KEY"]},{id:"vercel",env:["AI_GATEWAY_API_KEY"]},{id:"zai-coding-plan",env:["ZHIPU_API_KEY"]},{id:"ebcloud",env:["EBCLOUD_API_KEY"]},{id:"greenpt",env:["GREENPT_API_KEY"]},{id:"mixlayer",env:["MIXLAYER_API_KEY"]},{id:"hyper",env:["HYPER_API_KEY"]},{id:"jalapeno",env:["JALAPENO_API_KEY"]},{id:"dinference",env:["DINFERENCE_API_KEY"]},{id:"neosmith",env:["NEOSMITH_API_KEY"]},{id:"fireworks-ai",env:["FIREWORKS_API_KEY"]},{id:"stepfun-ai",env:["STEPFUN_API_KEY"]},{id:"fastrouter",env:["FASTROUTER_API_KEY"]},{id:"orcarouter",env:["ORCAROUTER_API_KEY"]},{id:"friendli",env:["FRIENDLI_TOKEN"]},{id:"kimi-code-plan-cn",env:["KIMI_API_KEY"]},{id:"inco",env:["INCO_API_KEY"]},{id:"sakana",env:["SAKANA_API_KEY"]},{id:"scx-ai",env:["SCX_API_KEY"]},{id:"zenifra",env:["ZENIFRA_AI_KEY"]},{id:"tokenrouter",env:["TOKENROUTER_API_KEY"]},{id:"google-vertex-anthropic",env:["GOOGLE_VERTEX_PROJECT","GOOGLE_VERTEX_LOCATION","GOOGLE_APPLICATION_CREDENTIALS"]},{id:"moonshotai",env:["MOONSHOT_API_KEY"]},{id:"ainetcafe",env:["AINETCAFE_API_KEY"]},{id:"wallaby",env:["WALLABY_API_KEY"]},{id:"bee",env:["BEE_API_KEY"]},{id:"scnet-token-plan",env:["SCNET_API_KEY"]},{id:"ofox",env:["OFOX_API_KEY"]},{id:"neon",env:["NEON_AI_GATEWAY_BASE_URL","NEON_AI_GATEWAY_TOKEN"]},{id:"aihubmix",env:["AIHUBMIX_API_KEY"]},{id:"merge-gateway",env:["MERGE_GATEWAY_API_KEY"]},{id:"opper",env:["OPPER_API_KEY"]},{id:"nvidia",env:["NVIDIA_API_KEY"]},{id:"pioneer",env:["PIONEER_API_KEY"]},{id:"xiaomi",env:["XIAOMI_API_KEY"]},{id:"xiaomi-token-plan-sgp",env:["XIAOMI_API_KEY"]},{id:"minimax",env:["MINIMAX_API_KEY"]},{id:"github-copilot",env:["GITHUB_TOKEN"]},{id:"inferx",env:["INFERX_API_KEY"]},{id:"opencode-go",env:["OPENCODE_API_KEY"]},{id:"openreason",env:["OPENREASON_API_KEY"]},{id:"lmstudio",env:["LMSTUDIO_API_KEY"]},{id:"aki-io",env:["AKI_IO_API_KEY"]},{id:"tensorx",env:["TENSORX_API_KEY"]},{id:"longcat",env:["LONGCAT_API_KEY"]},{id:"pareto",env:["PARETO_API_KEY"]},{id:"chutes",env:["CHUTES_API_KEY"]},{id:"edenai",env:["EDENAI_API_KEY"]},{id:"stepfun",env:["STEPFUN_API_KEY"]},{id:"hpc-ai",env:["HPC_AI_API_KEY"]},{id:"tencent-coding-plan",env:["TENCENT_CODING_PLAN_API_KEY"]},{id:"sambanova",env:["SAMBANOVA_API_KEY"]},{id:"tempr",env:["TEMPR_API_KEY"]},{id:"inception",env:["INCEPTION_API_KEY"]},{id:"modelis",env:["MODELIS_API_KEY"]},{id:"opencode",env:["OPENCODE_API_KEY"]},{id:"kenari",env:["KENARI_API_KEY"]},{id:"kimi-code-plan-global",env:["KIMI_API_KEY"]},{id:"trustedrouter",env:["TRUSTEDROUTER_API_KEY"]},{id:"wafer.ai",env:["WAFER_API_KEY"]},{id:"zhipuai",env:["ZHIPU_API_KEY"]},{id:"lynkr",env:["LYNKR_API_KEY"]},{id:"meganova",env:["MEGANOVA_API_KEY"]},{id:"ovhcloud",env:["OVHCLOUD_API_KEY"]},{id:"requesty",env:["REQUESTY_API_KEY"]},{id:"mistral",env:["MISTRAL_API_KEY"]},{id:"amazon-bedrock",env:["AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_REGION","AWS_BEARER_TOKEN_BEDROCK"]},{id:"synthetic",env:["SYNTHETIC_API_KEY"]},{id:"llmgateway",env:["LLMGATEWAY_API_KEY"]},{id:"sap-ai-core",env:["AICORE_SERVICE_KEY"]},{id:"vivgrid",env:["VIVGRID_API_KEY"]},{id:"prime",env:["PRIME_API_KEY"]},{id:"klokintegration",env:["KLOKINTEGRATION_API_KEY"]},{id:"google-vertex",env:["GOOGLE_VERTEX_PROJECT","GOOGLE_VERTEX_LOCATION","GOOGLE_APPLICATION_CREDENTIALS"]},{id:"evroc",env:["EVROC_API_KEY"]},{id:"tokengo",env:["TOKENGO_API_KEY"]},{id:"submodel",env:["SUBMODEL_INSTAGEN_ACCESS_KEY"]},{id:"kosmik",env:["KOSMIK_API_KEY"]},{id:"tencent-token-plan",env:["TENCENT_TOKEN_PLAN_API_KEY"]},{id:"togetherai",env:["TOGETHER_API_KEY"]},{id:"helicone",env:["HELICONE_API_KEY"]},{id:"cortecs",env:["CORTECS_API_KEY"]},{id:"agnes",env:["AGNES_API_KEY"]},{id:"daoxe",env:["DAOXE_API_KEY"]},{id:"morph",env:["MORPH_API_KEY"]},{id:"openai",env:["OPENAI_API_KEY"]},{id:"alibaba-coding-plan-cn",env:["ALIBABA_CODING_PLAN_API_KEY"]},{id:"io-net",env:["IOINTELLIGENCE_API_KEY"]},{id:"infomaniak",env:["INFOMANIAK_API_KEY","INFOMANIAK_PRODUCT_ID"]},{id:"llmtech",env:["LLMTECH_API_KEY"]},{id:"crossmodel",env:["CROSSMODEL_API_KEY"]},{id:"arcee",env:["ARCEE_API_KEY"]},{id:"drun",env:["DRUN_API_KEY"]},{id:"amd",env:["AMD_API_KEY"]},{id:"qvac",env:["QVAC_API_KEY"]},{id:"claudinio",env:["CLAUDINIO_API_KEY"]},{id:"runinfra",env:["RUNINFRA_GATEWAY_KEY"]},{id:"hetzner",env:["HETZNER_API_KEY"]},{id:"digitalocean",env:["DIGITALOCEAN_ACCESS_TOKEN"]},{id:"boundless",env:["BOUNDLESS_API_KEY"]},{id:"aixy",env:["AIXY_API_KEY"]},{id:"alibaba-cn",env:["DASHSCOPE_API_KEY"]}];function Ia(e){if(!e.released)return null;let t=new Date(e.released).getTime();return Number.isNaN(t)?null:t}function JE(e){if(e.provider)return e.provider;let t=e.id.indexOf("/");return t===-1?"kortix":e.id.slice(0,t)}function bS(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 fe(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 PS(e){return e.reduce((t,n)=>{let r=Ia(n)??0,s=Ia(t)??0;return r!==s?r>s?n:t:fe(n.id)>fe(t.id)?n:t})}function Ea(e,t){let n=(t?.now??new Date).getTime(),r=(t?.windowMonths??6)*2630016e3,s=new Set;for(let[,o]of bS(e,JE)){let a=[...bS(o,p=>p.family||p.id).values()].map(PS),c=a.filter(p=>{let d=Ia(p);return d!==null&&Math.abs(n-d)<r});for(let p of c.length>0?c:[PS(a)])s.add(p.id)}return s}function qs(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=>fe(r.id)>0)?n.filter(r=>fe(r.id)>0):n}function Zn(e){let t;for(let n of qs(e)){if(!t){t=n;continue}let r=(n.released??"").localeCompare(t.released??"");(r>0||r===0&&fe(n.id)>fe(t.id))&&(t=n)}return t}var QE={"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 SS(e){return`${e.toUpperCase().replace(/[^A-Z0-9]+/g,"_")}_API_KEY`}var XE=(()=>{let e=new Map;for(let{id:n,env:r}of Ta)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=>SS(o)===n)??s[0])}return t})();function xS(e){let t=QE[e.id];if(t)return t;let n=e.env??[],r=n.length===1?XE.get(n[0]):void 0;return r&&r!==e.id?{methods:[{envVars:[SS(e.id)]}]}:{methods:n.length>0?[{envVars:n}]:[]}}function Oa(e,t){return e.methods.some(n=>n.envVars.length>0&&n.envVars.every(t))}var ZE=["low","medium","high"];function wS(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:[...ZE]}: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 kS=Ta;var Ma={allow_fallbacks:!0,zdr:!0,data_collection:"deny"};var Gs=[{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:{"morph/fp8":{inputPerMillion:.09,cachedInputPerMillion:.008,outputPerMillion:.55}},tier:"balanced",vision:!0,limit:{context:1e6,output:65536},reasoningOptions:[{type:"effort",values:["none","low","high","max"]}],openrouterProvider:{only:["morph/fp8"],...Ma,max_price:{prompt:.3,completion:1.2}}},{id:"glm-5.3-flash",name:"GLM 5.3 Flash",upstreamModelId:"z-ai/glm-5.3-flash",transport:"openrouter",morphModelId:"morph-glm53flash",morphPricing:{inputPerMillion:.1,cachedInputPerMillion:.02,outputPerMillion:.35},pricingRef:"openrouter/z-ai/glm-5.3-flash",pricing:{inputPerMillion:.15,cachedInputPerMillion:.05,outputPerMillion:.5},openrouterEndpointPricing:{"decart/fp4":{inputPerMillion:.1275,cachedInputPerMillion:.0255,outputPerMillion:.425},"coreweave/nvfp4":{inputPerMillion:.15,cachedInputPerMillion:.05,outputPerMillion:.5}},tier:"fast",vision:!0,limit:{context:1e6,output:65536},reasoningOptions:[{type:"effort",values:["low","high","max"]}],openrouterProvider:{only:["decart/fp4","coreweave/nvfp4"],...Ma,max_price:{prompt:.15,completion:.5}}},{id:"kimi-k3",name:"Kimi K3 2.8T",upstreamModelId:"moonshotai/kimi-k3",transport:"openrouter",morphModelId:"morph-kimik3",morphPricing:{inputPerMillion:2.5,cachedInputPerMillion:.29,outputPerMillion:14},pricingRef:"openrouter/moonshotai/kimi-k3",pricing:{inputPerMillion:3.3,cachedInputPerMillion:.33,outputPerMillion:16.5},openrouterEndpointPricing:{"fireworks/us":{inputPerMillion:3.3,cachedInputPerMillion:.33,outputPerMillion:16.5}},tier:"flagship",vision:!0,limit:{context:1e6,output:65536},openrouterProvider:{only:["fireworks/us"],...Ma,max_price:{prompt:3.3,completion:16.5}}}],rX=new Map(Gs.map(e=>[e.id,e]));var vS=Gs.map(e=>e.id),AS=(Gs.find(e=>e.tier==="flagship")??Gs[0]).id,RS="deepseek-v4.1-flash";var TS=kS.map(e=>({id:e.id,authRequirement:xS(e)})),er=new Set(["kortix"]),Da=new Set(["kortix"]);function Jt(e){let t=Array.isArray(e.all)?e.all:[],n=Array.isArray(e.connected)?e.connected:[];if(t.length>0||n.length>0)return{...e,all:t,connected:n};let r=e.providers,s=Array.isArray(r)?r:[];return s.length===0?{...e,all:[],connected:[]}:{...e,all:s,connected:s.map(o=>o.id)}}function eM(e){if(!e)return!1;let t=Jt(e),n=Array.isArray(t.all)?t.all:[],r=Array.isArray(t.connected)?t.connected:[];return r.length===0?!1:n.some(s=>r.includes(s.id)&&s.models&&Object.keys(s.models).length>0)}function tM(e){let t=Jt(e),n=Array.isArray(t.all)?t.all:[],r=Array.isArray(t.connected)?t.connected:[];return{...t,all:n.filter(s=>!Da.has(s.id)),connected:r.filter(s=>!Da.has(s))}}function nM(e,t,n){let r=Jt(e),s=Array.isArray(r.all)?r.all:[],o=new Set(s.map(a=>a.id)),i=new Set(Array.isArray(r.connected)?r.connected:[]);for(let a of n)o.has(a.id)&&Oa(a.authRequirement,c=>t.has(c))&&i.add(a.id);return o.has("codex")&&(t.has("CODEX_AUTH_JSON")||t.has("OPENCODE_AUTH_JSON"))&&i.add("codex"),{...r,connected:[...i]}}var rM=new Map(["anthropic","openai","google","x-ai","xai","deepseek","mistral","groq","perplexity","openrouter"].map((e,t)=>[e,t]));function sM(e){let t=e.reasoning_options??[],n=t.find(r=>r.type==="effort");return n?(n.values??[]).flatMap(r=>r===null?["none"]:typeof r=="string"?[r]:[]):t.some(r=>r.type==="budget_tokens")?["high","max"]:[]}var ja="opencode";function oM(e){return e.cost?.input===0&&e.cost?.output===0}function CS(e){return e===ja?Number.MAX_SAFE_INTEGER:rM.get(e)??Number.MAX_SAFE_INTEGER-1}function iM(e,t){let n=cM(t),r={},s=(e.providers??[]).map(o=>{let i=(o.models??[]).filter(a=>a.status!=="deprecated");return o.id===ja&&!n.has(ja)?{...o,models:i.filter(oM),keyless:!0}:{...o,models:i,keyless:!1}}).filter(o=>(o.keyless||n.has(o.id))&&!Da.has(o.id)&&(o.models?.length??0)>0).sort((o,i)=>CS(o.id)-CS(i.id)).map(o=>{let i=[...o.models].sort((c,p)=>(p.released??"").localeCompare(c.released??"")||fe(p.id)-fe(c.id)),a=Zn(i)?.id??i[0]?.id;return a&&(r[o.id]=a),{id:o.id,name:o.name,source:o.keyless?"api":"env",models:Object.fromEntries(i.map(c=>{let p=sM(c);return[c.id,{id:c.id,name:c.name,...c.released?{release_date:c.released}:{},...c.family?{family:c.family}:{},...c.reasoning!==void 0?{reasoning:c.reasoning}:{},...c.reasoning_options?{reasoning_options:c.reasoning_options}:{},...c.tool_call!==void 0?{tool_call:c.tool_call}:{},...c.attachment!==void 0?{attachment:c.attachment}:{},...c.modalities?{modalities:c.modalities}:{},...c.limit?{limit:c.limit}:{},...c.cost?{cost:c.cost}:{},...c.description?{description:c.description}:{},...c.open_weights!==void 0?{open_weights:c.open_weights}:{},...c.last_updated?{last_updated:c.last_updated}:{},...p.length>0?{variants:Object.fromEntries(p.map(d=>[d,{}]))}:{}}]}))}});return{all:s,connected:s.map(o=>o.id),default:r}}function aM(e,t){if(!e)return t;if(!t)return e;let n=Jt(e),r=Jt(t),s=new Map;for(let d of Array.isArray(r.all)?r.all:[])s.set(d.id,d);let o=[],i=new Set;for(let d of Array.isArray(n.all)?n.all:[])o.push(s.get(d.id)??d),i.add(d.id);for(let d of Array.isArray(r.all)?r.all:[])i.has(d.id)||(o.push(d),i.add(d.id));let a=[],c=new Set;for(let d of[...Array.isArray(n.connected)?n.connected:[],...Array.isArray(r.connected)?r.connected:[]])c.has(d)||(a.push(d),c.add(d));let p={...r.default??{}};for(let[d,g]of Object.entries(n.default??{})){let m=s.get(d);(!m||m.models&&g in m.models)&&(p[d]=g)}return{...r,all:o,connected:a,default:p}}function cM(e){let t=new Set;for(let n of TS)Oa(n.authRequirement,r=>e.has(r))&&t.add(n.id);return(e.has("CODEX_AUTH_JSON")||e.has("OPENCODE_AUTH_JSON"))&&t.add("codex"),t}function 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=wS({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 uM(e,t){return tM(nM(Jt(e),t,TS))}function pM(e){if(e.gatewayEnabled)return e.modelPicker?lM(e.modelPicker):void 0;let t=e.secretNames??new Set,n=e.runtimeProviders?uM(e.runtimeProviders,t):void 0;return aM(e.llmCatalogProviders?iM(e.llmCatalogProviders,t):void 0,eM(n)?n:void 0)}function dM(e){return"capabilities"in e&&e.capabilities!=null}function La(e,t){let n=e.find(r=>r.providerID===t.providerID&&r.modelID===t.modelID);return!!n&&n.enabled!==!1}function gM(e,t){if(!e)return[];let n=t?.providerMode??"gateway",r=Array.isArray(e.all)?e.all:[],s=Array.isArray(e.connected)?e.connected:[],o=[];for(let i of r)if(s.includes(i.id)&&!(n==="gateway"?!er.has(i.id):er.has(i.id)))for(let[a,c]of Object.entries(i.models)){if(a==="auto"||a==="kortix/auto")continue;let p;if(dM(c)){let d=c.capabilities;p={reasoning:d.reasoning??!1,vision:d.input?d.input.image??!1:void 0,toolcall:d.toolcall??!1}}else{let d=c.modalities?.input;p={reasoning:c.reasoning??!1,vision:d?d.includes("image"):c.attachment,toolcall:c.tool_call??!1}}o.push({id:_S({providerID:i.id,modelID:a}),providerID:i.id,providerName:c.provider_name??i.name,modelID:a,modelName:(c.name||a).replace("(latest)","").trim(),variants:c.variants,capabilities:p,contextWindow:c.limit?.context,releaseDate:c.release_date,family:c.family,cost:c.cost?{input:c.cost.input??0,output:c.cost.output??0}:void 0,providerSource:i.source,provider:c.provider,reasoningOptions:c.reasoning_options,description:c.description,openWeights:c.open_weights,lastUpdated:c.last_updated,enabled:c.enabled,free:c.free===!0})}return o}function IS(e){return new Map(e.map(t=>[`${t.providerID}:${t.modelID}`,t]))}var mM=new Set([AS]),fM="kortix",ES="codex",yM=new Set(vS);function hM(e,t){if(t)return t;let n=e.indexOf("/");return n===-1?e:e.slice(0,n)}function Qt(e){return mM.has(e.modelID)}function _M(e){return Ea(e.map(t=>({id:`${t.providerID}:${t.modelID}`,released:t.releaseDate,family:t.family,provider:t.provider??t.providerID})))}function bM(e){let{connectedProviderIds:t}=e,n=e.freeTier??!1,r=_M(e.catalogModels),s=IS(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}`,c=o.get(a);if(c==="hide")return!1;if(i.providerID===fM){let d=hM(i.modelID,i.provider),g=d===ES?t?.has(ES)??!1:t?.has(d)??!1;if(yM.has(i.modelID))return!n||i.modelID===RS;if(!g)return!1;if(c==="show"||r.has(a))return!0;let m=s.get(a);if(!m?.releaseDate)return Qt(i);try{let f=new Date(m.releaseDate);if(Number.isNaN(f.getTime()))return Qt(i)}catch{return Qt(i)}return!1}if(c==="show"||r.has(a))return!0;let p=s.get(a);if(!p?.releaseDate)return Qt(i);try{let d=new Date(p.releaseDate);if(Number.isNaN(d.getTime()))return Qt(i)}catch{return Qt(i)}return!1}}function PM(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 MS(e,t){if(!e||er.has(e.providerID)||fe(e.modelID)>0)return e;let n=t.filter(i=>i.providerID===e.providerID&&i.enabled!==!1);if(!n.some(i=>fe(i.modelID)>0))return e;let r=i=>fe(i)===1&&i.slice(i.indexOf(".")+1)===e.modelID,o=(n.find(i=>i.modelID===`global.${e.modelID}`)??n.find(i=>r(i.modelID)))?.modelID??Zn(n.map(i=>({id:i.modelID,released:i.releaseDate})))?.id;return!o||o===e.modelID?e:{...e,modelID:o}}function SM(e,t){let n=(t?e?.agentDefaults?.[t]:void 0)??e?.projectDefault??e?.accountDefault??e?.platformDefault;return n?Ra(n):void 0}function xM(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 wM=new Set(["explicit","repointed"]);function kM(e){let t=e.session?jr(e.session):null,n=t?Ca(t,e.gatewayEnabled):void 0;return(wM.has(String(e.session?.metadata?.opencode_model_source))?[n,e.lastPromptModel]:[e.lastPromptModel,n]).filter(o=>!!o)}function vM(e){let{models:t,providers:n}=e,r=c=>La(t,c),s=c=>c.find(p=>!!p&&r(p)),o=(()=>{if(e.configModel){let c=e.configModel.split("/");if(c.length>=2){let[p,...d]=c,g=d.join("/");if(r({providerID:p,modelID:g}))return{providerID:p,modelID:g}}}for(let c of e.recent??[])if(r(c))return c;if(n){let c=n.default||{},p=Array.isArray(n.all)?n.all:[],d=Array.isArray(n.connected)?n.connected:[],g=p.filter(m=>d.includes(m.id));for(let m of g){let f=c[m.id];if(f){let _={providerID:m.id,modelID:f};if(r(_))return _}for(let _ of qs(Object.keys(m.models).map(y=>({id:y})))){let y={providerID:m.id,modelID:_.id};if(r(y))return y}}}})(),i=s(e.picks??[]),a=i??s([e.serverDefault,e.globalDefault,e.agentModel,o]);return{model:MS(a,t),explicit:i,fallback:o}}export{ST as ABORT_REASONS,GH as ABORT_REASONS_NOT_YET_EMITTED,Qa as ACCOUNTS_LIST_UNAVAILABLE_CODE,js as ACTIVE_INSTANCE_COOKIE,Ja as ANALYTICS_UNAVAILABLE_CODE,BT as ATTACHMENT_PART_REF_PREFIX,x as ApiError,ie as AuthError,ct as BillingError,qG as CAPTURE_DEVICE_DEFAULTS,FG as CAPTURE_EXCLUSION_GROUPS,KG as CAPTURE_FRAME_INTERVALS_MS,UG as CAPTURE_LAYERS,BG as CAPTURE_MAX_HEIGHTS,NG as CAPTURE_RETENTION_LIMITS,eI as CONNECTION_FAULT_GRACE_MS,UT as CONNECTOR_POLL_FIRST_DELAY_MS,FT as CONNECTOR_POLL_INTERVAL_MS,NT as CONNECTOR_POLL_WINDOW_MS,eR as CONTEXT_TOOLS,Jb as COST_MARKUP,ho as ConnectorApprovalPendingError,br as ConnectorCallError,_o as ConnectorPageLimitError,tR as DEFAULT_CONTEXT_TOOL_TRIGGER_LABELS,jF as DEFAULT_NOTIFICATION_PREFERENCES,N_ as DEFAULT_TRANSCRIPT_OPTIONS,DT as DESTRUCTIVE_PHASES,Js as FEATURE_DISABLED_CODE,fO as FEATURE_FLAG_KEYS,Va as FEATURE_NOT_SUPPORTED_CODE,St as FILE_VERBS,An as FileExistsError,gn as HeadlessAuthError,$s as HostBoundaryError,VS as IMPERSONATION_HEADER,DF as INBOX_NOTIFICATION_KINDS,ua as INBOX_OBSERVATION_MAX_MS,T2 as INITIAL_SETTLED_CONNECTION,xT as INSTANCE_SCOPED_ROUTES,qx as KNOWN_TOOL_KINDS,Te as KORTIX_TRANSCRIPT_SCHEMA,wt as KortixMemberError,Tx as MAX_PROMPT_ATTACHMENTS_BYTES,Po as MAX_PROMPT_ATTACHMENT_BYTES,Nu as MAX_PROMPT_ATTACHMENT_FILES,xH as MEMORY_VERBS,Ha as MODEL_NOT_SERVABLE_CODE,dk as NO_GROUP_ACTIVITY_TOOLS,pa as OPTIMISTIC_ABORT_MAX_MS,X2 as OPTIMISTIC_COMPACTION_MAX_MS,ca as OPTIMISTIC_RECEIPT_MAX_MS,QY as PERSISTED_QUERY_CACHE_VERSION,bC as PLUMBING_TOOLS,h2 as PREVIEW_PROBE_TIMEOUT_MS,Z as PROJECT_ACTIONS,Ij as PROJECT_SESSION_NAME_LOOKUP_LIMIT,Tj as PROJECT_SESSION_PAGE_DEFAULT_LIMIT,cw as PROJECT_SESSION_PAGE_MAX_LIMIT,za as PROVISION_IN_FLIGHT_CODE,gx as PROVISION_STREAM_UNTERMINATED_CODE,Io as PublicSessionShareError,l$ as REVIEW_CONTROL_ACTIONS,rz as RUNTIME_NOT_READY_MARKERS,qF as RUNTIME_PERMISSION_CAPABILITIES,BF as RUNTIME_PERMISSION_REPLIES,kt as RequestTooLargeError,Sn as RuntimeNotReadyError,Ri as SANDBOX_FS_ROOTS,et as SANDBOX_PORTS,Ya as SANDBOX_STATE_CHANGE_IN_PROGRESS_CODE,aI as SERVER_COMPACTION_REVALIDATE_MS,la as SERVER_OBSERVATION_MAX_MS,pJ as SESSION_LIST_STATUS,wa as SESSION_LOG_FULL_TEXT_INLINE_MAX_BYTES,Se as SESSION_LOG_MINOR,le as SESSION_LOG_SCHEMA,mJ as SESSION_NOTICE,gk as STANDALONE_TOOLS,Yn as STREAM_OBSERVATION_MAX_MS,Ls as SandboxNotReadyError,Ut as SessionNotReadyError,ko as SessionStartError,a$ as TRIGGER_CONTROL_ACTIONS,K2 as TURN_END_LEDGER_LAG_MS,Uw as TURN_ERROR_CODES,oJ as WAKE_ESCALATION_COOLDOWN_MS,sJ as WAKE_MAX_RESTARTS,rJ as WAKE_NO_PROGRESS_MS,yi as WIRE_ID_BACKDATE_MS,yt as WIRE_ID_CLOCK_TOLERANCE,nt as WIRE_ID_TIME_MASK,_n as WIRE_ID_TIME_SCALE,jk as WIRE_MESSAGE_ID,RM as __getConfigResolver,AM as __setConfigResolver,WH as abortErrorReason,so as acceptAccountInvite,Sc as acceptAccountInviteAndLand,ng as acceptEnterpriseOffer,jz as acceptInvite,dx as accountInviteLanding,vm as actReviewItem,zl as activateConnection,Ql as addComputerToProject,Qg as addGroupMembers,cf as addMarketplaceSource,aJ as advanceWakeEscalation,LR as allDescendantIds,SP as appendPreviewToken,T_ as approveCaptureDeviceGrant,h_ as approveCaptureEnrollment,el as approveProjectAccessRequest,JK as approveTask,hr as archiveProject,sB as assignTicket,ul as attachGroupToProject,ui as authMfa,ai as authUser,L as authenticatedFetch,Sr as authenticatedRequest,f2 as authorizePreviewUrl,l as backendApi,$L as bindSlackIdentity,UL as bindTeamsIdentity,xl as brokerProjectSecretRequest,e2 as browserKeyValueStorage,kT as buildInstancePath,x2 as buildPresentationTemplateImageUrl,S2 as buildPresentationTemplatePdfUrl,PP as buildPreviewAuthEndpoint,LY as buildPublicTemplateUrl,ZT as buildRuntimePresentationConversionUrl,Mu as buildSandboxTemplate,WR as buildScrapeFailureResults,Kq as buildStaticFileHealthPreviewUrl,Nq as buildStaticFileLocalUrl,Fq as buildStaticFilePreviewUrl,tA as buildStaticFileServicePath,BQ as buildTunnelEventStreamUrl,Vq as buildWebProxyUrl,Am as bulkActReviewItems,O$ as bulkDeletePolicies,D$ as bulkImportPolicies,Xi as burstSummary,wC as burstSummaryLabel,Eb as burstWorkLabel,Tt as callConnector,yw as canManageBilling,bL as canOfferTopup,rU as cancelAccountDeletion,hc as cancelAccountInvite,wz as cancelSandbox,eY as cancelSandboxUpdate,Yd as cancelScheduledChange,Vd as cancelSubscription,YG as captureHealthBucket,Tw as changeRequestControlsFrom,_Y as checkAccessEmail,SD as checkMcpServerSignIn,PW as childMapByParent,aY as claimComputer,_A as claimNext,kL as claimPerSeatBilling,Up as claimWarmProjectSession,fb as classifyPart,QT as classifyPreviewProbeStatus,Bk as classifyPtyClose,nE as classifySessionLogMessage,Bi as classifyTurn,jW as cleanErrorMessage,KW as cleanResultSnippet,gH as cleanWorkerOutput,Za as clearImpersonationSession,$E as clearKortixAppViewerCache,Cd as clearModelDefault,oj as clearSessionFresh,sp as closeChangeRequest,MB as closeMilestone,AW as collectTurnParts,iB as commentTicket,ap as commitSessionChanges,eJ as compactionExpiryAtMs,fV as compactionTurnInfo,Wi as compareForDisplayAt,bW as compareMessagesForDisplay,t1 as compareSemver,bA as completeInFlight,gg as completeSlackInstall,mg as completeTeamsInstall,hS as composerSelectableAgents,Hb as computeStatusFromPart,Zd as configureAutoTopup,Hs as configureKortix,Gd as confirmCheckoutSession,Sg as connectEmail,ug as connectSlack,C2 as connectionFromHealth,R2 as connectionIsFaulted,aD as connectionSharedWithEveryone,wx as connectorConnect,kx as connectorFinalize,BY as connectorHeadline,rg as contactEnterpriseSales,nV as contextLabelForTool,D1 as contextToolSummary,j1 as contextToolTrigger,bU as convertPresentationToGoogleSlides,w2 as convertRuntimePresentation,ds as copyFile,og as costExportUrl,q2 as countLiveInboxPrompts,n$ as countReviewItemsBySegment,ic as createAccount,Jm as createAccountAuditWebhook,El as createAccountSecretResource,Fm as createAccountToken,pf as createApp,bf as createAppAccessSession,Sf as createAppDeployment,mf as createAppToken,$f as createAppVolume,Kf as createAppVolumeSnapshot,rV as createArtifactKind,hm as createAssignment,M0 as createAuditWebhook,Fz as createBackup,m_ as createCaptureEnrollmentToken,qd as createCheckoutSession,pu as createConnector,FY as createConnectorLinkInfoCache,ps as createFile,Fg as createGatewayKey,Hg as createGroup,CE as createHttpSessionSyncController,sY as createInstance,mA as createKortix,th as createKortixPty,di as createKortixSession,JU as createMarketplaceInstallSession,IB as createMilestone,bM as createModelVisibility,dm as createOAuthClient,wL as createPerSeatCheckout,ZY as createPersistedQueryCache,I$ as createPolicy,Wd as createPortalSession,Mc as createProject,yB as createProjectAgent,Gm as createProjectCliToken,Oc as createProjectRepo,ml as createProjectResourceGrant,Ot as createProjectSession,Fc as createProjectSkill,ad as createProjectTrigger,e_ as createPromptAttachmentController,sm as createRole,qQ as createSSEStream,yz as createSandbox,Cm as createSandboxShare,Tu as createSandboxTemplate,fj as createSavedCopyStore,G$ as createScimToken,k0 as createServiceAccountApi,Mr as createSessionPrompt,jp as createSessionPublicShare,yA as createSessionQueue,Om as createSessionReminder,l0 as createSsoGroupMapping,HK as createTask,tB as createTicket,GQ as createTunnelEventStream,TQ as createWarmSessionPool,xp as currentSavedCopyStore,xc as declineAccountInvite,Lz as declineInvite,sU as deleteAccountImmediately,Dl as deleteAccountSecretResource,gf as deleteApp,Rf as deleteAppDeployment,D0 as deleteAuditWebhook,Kz as deleteBackup,gu as deleteConnector,bu as deleteConnectorCredential,FB as deleteCredential,RF as deleteDriveFile,Zy as deleteEnv,Bt as deleteFile,$g as deleteGatewayBudget,Jc as deleteGitHubInstallation,Yg as deleteGroup,oY as deleteInstance,vB as deleteKortixProject,DB as deleteMilestone,fm as deleteOAuthClient,Cl as deletePersonalProjectSecret,M$ as deletePolicy,_B as deleteProjectAgent,kl as deleteProjectProviderOAuth,fl as deleteProjectResourceGrant,Al as deleteProjectSecret,Yp as deleteProjectSession,ld as deleteProjectTrigger,on as deletePromptAttachment,am as deleteRole,Eu as deleteSandboxTemplate,A0 as deleteServiceAccountApi,qp as deleteSessionPrompt,Mo as deleteSessionReminder,Lm as deleteSessionReminders,u0 as deleteSsoGroupMapping,a0 as deleteSsoProvider,QK as deleteTask,aB as deleteTicket,I_ as denyCaptureDeviceGrant,__ as denyCaptureEnrollment,Pc as describeAccountInvite,po as describeConnectorTool,Of as destroyAppMachine,Ff as destroyAppVolume,dl as detachGroupFromProject,Qv as detectLocalhostUrls,hJ as directSubsessions,v0 as disableServiceAccountApi,xg as disconnectEmail,YY as disconnectGitHubApp,yg as disconnectSlack,pD as discoverConnectionOAuth2,dD as discoverConnectionOAuth2Resource,du as discoverConnectorAuth,Pz as discoverLocalSandbox,PF as dismissDriveConflict,DY as downloadAccountAudit,xF as downloadDriveFile,ZB as dropClientForUrl,nq as dropPublicClientForUrl,wA as editQueued,Gp as editSessionPrompt,hA as enqueue,mB as ensurePmSession,JT as ensurePreviewSessionCookie,cD as ensureProjectConnectorConnection,OT as ensureSandbox,$p as ensureWarmProjectSession,Nk as env,si as exchangeCode,jf as execInApp,zm as exportAccountAudit,xe as extractGatewayErrorDetails,Vn as extractInstanceRoute,HC as extractSkillBaseDir,LH as extractSkillContent,GC as extractSkillFiles,fH as extractWorkerPreview,PA as failInFlight,UV as fallbackBusyRowAfterTurnId,Bn as familyForTool,Na as featureDisabledKey,wy as featureFlags,PL as fetchAccountStateWithToken,uO as fetchAccountsWithToken,s2 as fetchAttachmentPart,OL as fetchCostExportCsv,pS as fetchKortixAppViewer,Uu as fetchProjectArchive,WD as fetchProjectFileRaw,kO as fetchProjectsForAccountWithToken,Sy as fetchSessionAttachment,wv as fileDownloadRequest,bH as filePhase,_H as fileVerb,Lv as files,Lo as finalizeAppArtifact,vY as finalizeConnectorSetupLink,Mj as findActiveTranscriptShare,ls as findFiles,RW as findLastTextPart,uN as findSessionAttachments,us as findText,dd as fireProjectTrigger,Cu as fixSandboxWithAgent,gM as flattenModels,wV as flattenThought,qf as forkAppVolume,Ba as formatBillingErrorForUI,ZV as formatCost,Yb as formatDuration,LW as formatJsonFailureOutput,AV as formatMessageDay,RV as formatMessageExact,oz as formatOpenCodeRuntimeError,NW as formatRawOutput,MT as formatRuntimeError,eH as formatTokens,IA as formatTranscript,BV as freshSendHint,fA as generateSessionId,ac as getAccount,lc as getAccountBranding,tU as getAccountDeletionStatus,Ld as getAccountState,$d as getAccountStateMinimal,AT as getActiveInstanceIdFromCookie,dU as getAdminProviderAnalytics,lU as getAdminProviderDistribution,mU as getAdminProviderFallback,oU as getAdminRole,lR as getAgentCardLabel,pL as getAgentConfig,bB as getAgentPersona,Qz as getAllVersions,TW as getAnsweredQuestionParts,Do as getApp,yf as getAppAccess,ff as getAppAuthEnv,wf as getAppDeployment,kf as getAppDeploymentLogs,VU as getApprovalLink,tn as getAuthToken,eD as getAuthTokenWithRetry,Xd as getAutoTopupSettings,xL as getAutoTopupSetupStatus,Nd as getBillingCreditBreakdown,Bd as getBillingTierConfigurations,Fd as getBillingTransactionsSummary,Kd as getBillingUsageHistory,R_ as getCaptureAssetUrl,A_ as getCaptureChunkMedia,w_ as getCaptureDays,C_ as getCaptureDeviceGrant,v_ as getCaptureFrame,b_ as getCapturePolicy,S_ as getCaptureTimeline,x_ as getCaptureTimelineItems,E_ as getCaptureWorkspace,Zu as getChangeRequest,ep as getChangeRequestDiff,tp as getChangeRequestMergePreview,Q1 as getChildSessionError,ks as getChildSessionId,X1 as getChildSessionToolParts,ht as getClient,We as getClientForUrl,hu as getConnectStatus,uD as getConnectionOAuth2Application,hD as getConnectionOAuth2Status,_D as getConnectionPolicies,nn as getConnectorCatalog,cu as getConnectorConfig,iu as getConnectorPolicies,wY as getConnectorSetupLink,ML as getCostSummary,vT as getCurrentInstanceIdFromPathname,YH as getCurrentInstanceIdFromWindow,Ih as getCurrentProject,Od as getDefaultAccountState,tW as getDiagnostics,cR as getDirectory,yo as getDiscoverConnector,vD as getDiscoverIntegration,Gf as getDriveFileUrl,bg as getEmailInstallation,Pg as getEmailMode,B0 as getEnterpriseDemo,cs as getFileStatus,ab as getFileWithDir,aR as getFilename,fF as getFolderAccess,jT as getFullChangelog,Mg as getGatewayBreakdown,jg as getGatewayBudgets,Dg as getGatewayErrors,Ug as getGatewayKeys,Tg as getGatewayLog,Ig as getGatewayOverview,kg as getGatewayRoutingPolicy,Eg as getGatewaySeries,Og as getGatewaySessions,WY as getGitHubAppStatus,Bc as getGitHubInstallation,_U as getGoogleAuthUrl,Vg as getGroup,Y1 as getHiddenToolParts,YS as getImpersonationSession,Dz as getInvite,rY as getJustavpsServerTypes,xB as getKortixProject,wB as getKortixProjectBySession,sh as getKortixPtyWebSocketUrl,Jz as getLatestSandboxVersion,IY as getMaintenanceConfig,Qc as getManagedGitBackend,PO as getManagedGitStatus,sf as getMarketplaceCatalogItem,of as getMarketplaceCatalogItemFile,Y$ as getMfaRequired,CB as getMilestone,$_ as getMobileClientPolicy,Ad as getModelDefaults,j_ as getMyCaptureFrame,D_ as getMyCaptureTimeline,Yf as getNotificationPreferences,pm as getOAuthClient,SY as getOAuthConsentRequest,tz as getOpenCodeConfigInvalidError,V1 as getPartText,_0 as getPatPolicy,nW as getPermissionForTool,Rt as getProject,PB as getProjectActivity,zu as getProjectCommit,Yu as getProjectCommitDiff,gr as getProjectDetail,mF as getProjectDrive,Ju as getProjectFileHistory,Ec as getProjectGitToken,mr as getProjectLlmCatalog,hO as getProjectLlmCatalogProviders,qr as getProjectModelAccess,fr as getProjectModelPicker,bO as getProjectQuota,Pr as getProjectSandboxHealth,SO as getProjectSandboxProviderTransition,Tr as getProjectSession,Xp as getProjectSessionConfigState,td as getProjectSessionScope,Jd as getProrationPreview,mz as getProviders,Bq as getProxyBaseUrl,tq as getPublicClientForUrl,yY as getPublicMarketplaceItem,hY as getPublicMarketplaceItemFile,CU as getPublicSessionShare,TU as getPublicSessionShareMessages,CY as getPublicShareByToken,$Y as getPublicTemplate,rW as getQuestionForTool,YL as getReferralCode,XL as getReferralStats,tH as getRetryInfo,nH as getRetryMessage,wm as getReviewItem,xm as getReviewSummary,nm as getRolePermissions,rm as getRoleUsage,sa as getRuntimeConfigInvalidError,Gz as getSSHConnection,fz as getSandbox,hz as getSandboxById,lz as getSandboxPortUrl,cY as getSandboxProvisionStatus,lY as getSandboxProvisionStreamUrl,Yz as getSandboxUpdateStatus,dP as getSandboxUrl,Fe as getSandboxUrlForExternalId,AY as getSecretSetupLink,Ci as getServerHealth,BB as getServiceLogs,Fp as getSessionAudit,XV as getSessionCost,Kr as getSessionCostRecord,Lw as getSessionDrives,$h as getSessionHealth,Kp as getSessionLogPage,sd as getSessionMessageAuthors,od as getSessionModelUsage,Oj as getSessionOpenBundle,X$ as getSessionOversight,Cp as getSessionParticipants,m0 as getSessionPolicy,Op as getSessionPreviewCandidates,Ul as getSessionProviderSecretPool,Np as getSessionTranscript,Ir as getSessionTranscriptSync,Er as getSessionTurn,Tp as getSessionWatch,uH as getShellModePart,hg as getSlackChannelFile,lg as getSlackInstallation,fg as getSlackManifest,pg as getSlackMode,r0 as getSsoProvider,nA as getStaticFileHealthPath,co as getSupabaseAccessToken,_x as getSupabaseAccessTokenWithRetry,GK as getTask,VK as getTaskStatus,ZU as getTemplate,ZK as getTicket,Z1 as getToolInfo,Fi as getToolPrimaryArg,EA as getTranscriptFilename,ta as getTurnCost,YV as getTurnError,QV as getTurnErrorDetails,JV as getTurnErrorRawText,zb as getTurnStatus,sg as getUsageRollup,MY as getUserRolesWithToken,Qu as getVersionDiff,Qf as getWebPushPublicKey,HV as getWorkingState,jl as grantAccountSecretResource,Iz as grantSandboxProjectAccess,gL as grantSecretToAgent,vW as groupMessagesIntoTurns,Bb as groupShowSegments,Ob as groupSteps,rH as hasDiffs,Uq as hasLocalhostUrls,eA as hasPreviewTarget,Sb as hasRetryingAssistantTurn,pv as heartbeatGapEvent,Hp as holdSessionPrompts,Gg as humanizeReviewActionPath,Ss as humanizeSearchQuery,db as humanizeToolName,ec as impersonationHeaders,o0 as importSsoProviderFromMetadata,B2 as inboxObservationSupersedes,AP as initialWakeEscalationState,Ie as inputPath,eF as installTemplate,Wp as interruptSessionPrompt,lo as invalidateTokenCache,fc as inviteAccountMember,ol as inviteProjectMember,Tc as inviteRepoCollaborator,Ds as isAbortError,ZS as isAdminBypassEnabled,K1 as isAgentPart,zv as isAppRouteUrl,H1 as isAttachment,qT as isAttachmentPartRef,Xt as isAuthFailure,Ka as isBillingError,B1 as isCompactionPart,zs as isConfigured,O1 as isContextTool,zz as isDestructivePhase,lS as isEmptyConversation,Wo as isEmptyShowPart,DW as isErrorOutput,Yq as isExternalUrl,Fa as isFeatureDisabledError,cb as isFilePart,HS as isImpersonationSessionLive,HH as isInstanceDetailPath,wT as isInstanceScopedAppPath,Wq as isInternalLocalhostUrl,_y as isInvisibleActivityPart,FO as isInviteSent,VV as isLastUserMessage,pI as isLegacyMigratedSession,yO as isManagedGithubProject,hy as isNoGroupActivityTool,La as isOfferedModel,nz as isOpenCodeConfigInvalidError,Zx as isPaintableSavedCopy,G1 as isPatchPart,XY as isPersistableQueryKey,Gq as isPreviewUrl,rA as isProxiableLocalhostUrl,yy as isQuestionTool,we as isReasoningPart,FR as isRetryableTurnError,RT as isRuntimeConfigInvalidError,IT as isRuntimeNotReadyResponse,Lh as isRuntimeReady,sz as isRuntimeStartingError,zn as isSandboxNotReadyError,Jo as isSelectableAgent,Eh as isServerReachable,lN as isSessionAttachmentRef,lp as isSessionFresh,iE as isSessionLogRestoreNote,Hj as isSessionStartError,eN as isShellActivityTool,BC as isShellMode,mH as isShortOutput,NF as isShowContentUnavailable,Wr as isShowPayloadEmpty,q1 as isSnapshotPart,by as isStandaloneActivityTool,W1 as isStepPart,Us as isSubdomainPreviewUrl,Ye as isTextPart,te as isToolPart,J1 as isToolPartHidden,ty as isTurnErrorCode,Ph as isUnderSandboxRoot,zq as isWebProxyUrl,$k as isWireIdAheadOf,FE as kortixAppViewerToken,KE as kortixBinding,Vk as kortixPty,dS as kortixToken,xM as latestPromptModel,vc as leaveAccount,d_ as linkCaptureDevice,zc as linkGitHubInstallation,Nc as linkRepository,Vm as listAccountAudit,Ym as listAccountAuditWebhooks,yc as listAccountInvites,mc as listAccountMembers,k$ as listAccountResourceGrants,Il as listAccountSecretResources,y0 as listAccountSessions,Um as listAccountTokens,oc as listAccounts,U$ as listActions,uU as listAdminSandboxes,em as listAgentIdentities,ql as listAllConnections,hf as listAppAgents,xf as listAppDeployments,Tf as listAppMachines,Nf as listAppVolumeSnapshots,Lf as listAppVolumes,uf as listApps,ym as listAssignments,j0 as listAuditEvents,E0 as listAuditWebhooks,Uz as listBackups,Ud as listBillingTransactions,u_ as listCaptureDevices,g_ as listCaptureEnrollmentTokens,y_ as listCaptureEnrollments,Xu as listChangeRequests,KL as listChannelBindings,cB as listColumns,wD as listConnectSections,xD as listConnectToolkits,Bl as listConnections,go as listConnectorAccounts,uo as listConnectorTools,tu as listConnectors,EL as listCostByProject,LB as listCredentialEvents,jB as listCredentials,fo as listDiscoverConnectors,kD as listDiscoverIntegrations,yu as listDiscoverSections,bF as listDriveConflicts,SF as listDriveFiles,Dw as listDriveFolder,CF as listDriveVersions,Qy as listEnv,rf as listFeaturedMarketplaces,uB as listFields,Tn as listFiles,_F as listFolderPrincipals,Cg as listGatewayLogs,qc as listGitHubInstallations,Wc as listGitHubRepositories,Vc as listGitHubRepositoryBranches,Jg as listGroupMembers,h$ as listGroupProjectGrants,Wg as listGroups,kB as listKortixProjectSessions,SB as listKortixProjects,eh as listKortixPty,Gc as listLinkableGitHubInstallations,Xc as listManagedGitRepositories,tf as listMarketplaceCatalogItems,af as listMarketplaceSources,nf as listMarketplaces,_$ as listMemberGroups,b$ as listMemberProjectAccess,TB as listMilestoneEvents,RB as listMilestones,bc as listMyAccountInvites,Hf as listNotifications,um as listOAuthClients,Km as listOAuthGrants,yl as listPendingApprovals,il as listPendingProjectInvites,bm as listPermissions,mu as listPipedreamApps,fu as listPipedreamSections,T$ as listPolicies,nl as listProjectAccess,Zc as listProjectAccessRequests,tm as listProjectAgentIdentities,fB as listProjectAgents,Hm as listProjectAudit,Vu as listProjectBranches,qm as listProjectCliTokens,Hu as listProjectCommits,ju as listProjectDirectory,Du as listProjectFiles,ll as listProjectGroupGrants,wu as listProjectPolicies,wl as listProjectProviderOAuth,$m as listProjectReminders,gl as listProjectResourceGrants,vu as listProjectSandboxTemplates,Ou as listProjectSandboxes,bl as listProjectSecrets,Mt as listProjectSessions,Ap as listProjectSessionsPage,Au as listProjectSnapshots,hd as listProjectTriggerEventApps,yd as listProjectTriggerEventTypes,md as listProjectTriggerRuns,id as listProjectTriggers,At as listProjects,Cc as listProjectsForAccount,mY as listPublicMarketplaceItems,fY as listPublicMarketplaces,ZL as listReferrals,Sm as listReviewItems,Zg as listRoles,Tz as listSandboxProjectMembers,Rm as listSandboxShares,bz as listSandboxes,q$ as listScimTokens,w0 as listServiceAccountsApi,KB as listServiceTemplates,NB as listServices,PD as listSessionConnectRequests,ig as listSessionCosts,IF as listSessionDrives,Bp as listSessionPrompts,Fl as listSessionProviderSecretPools,Dp as listSessionPublicShares,Mm as listSessionReminders,hl as listSessionsNeedingInput,LU as listSignedInDevices,c0 as listSsoGroupMappings,WK as listTaskEvents,qK as listTasks,dB as listTemplates,eB as listTicketEvents,XK as listTickets,gd as listTriggerRuns,RE as loadHttpSessionHistory,mt as loadPreviewUrlTemplate,wb as looksLikeError,zW as looksLikeHtml,FW as looksLikeJsonPayload,vF as makeDriveFolder,s$ as mapApiReviewItem,iY as markInstanceError,zf as markNotificationsRead,Ar as markSessionFresh,Vy as maxWireIdClock,wH as memoryRelPath,Db as mergeBurstSteps,rp as mergeChangeRequest,vV as messageCreatedAt,CC as messageTime,gU as migrateAdminSandboxProvider,hi as mintWireMessageId,zy as mintWireMessageIdAbove,On as mkdir,PM as modelInDefaultView,Ca as modelRefToKey,AF as moveDriveFile,Ib as narrateFailedStep,Es as narrateStep,Is as narrationToolName,dv as narrowChatEvent,Uk as newestWireIdClock,KY as nextConnectorPollDelay,he as normalizeActivityToolName,XH as normalizeAppPathname,WG as normalizeCaptureAppId,GG as normalizeCaptureDomain,Jq as normalizeExternalInput,ee as normalizeName,pb as normalizeToolName,mI as notifyHostSignal,np as openChangeRequest,xi as openEventStream,jY as openStressTestStream,xu as paginateConnector,sr as parseBillingError,BW as parseEmbeddedFailure,fN as parseFlagOverride,kb as parseJsonFailure,ys as parseLocalhostUrl,kH as parseMemoryView,ez as parseOpenCodeErrorPayload,TH as parsePresentationOutput,jh as parseProxyHop,oP as parseQuestionAnswersFromOutput,OH as parseReadOutput,pP as parseRuntimeErrorPayload,GR as parseScrapeInputUrls,VR as parseScrapeOutput,Vh as parseSubdomainUrl,yH as parseTaskRows,Hq as parseWebProxyUrl,Ab as parseWebSearchOutput,Hi as partOutcome,AB as patchKortixProject,RH as patchVerb,pM as pickerProviderList,uu as pipedreamConnect,Zl as pipedreamConnectConnection,Pu as pipedreamFinalize,eu as pipedreamFinalizeConnection,I as platformConfig,yD as pollConnectionOAuth2DeviceAuthorization,io as pollProjectProviderOAuth,eg as previewBillingPlan,Rg as previewGatewayRoute,J$ as previewMfaRequired,FL as previewSlackIdentity,NL as previewTeamsIdentity,cm as probeEffectivePermission,lm as probeEffectivePermissions,_2 as probePreviewPort,Fu as projectArchiveRequest,Z2 as projectCompacting,zE as projectConfigAgentsToOpenCodeAgents,yS as projectConfigAgentsToRuntimeAgents,A2 as projectSessionConnection,_J as projectSessionForRuntimeId,xd as projectSessionStartSeed,W2 as projectWorking,Dc as provisionProject,_O as provisionProjectStream,vO as provisionProjectWithToken,Gh as proxyLocalhostUrl,qq as proxyUrlToInternal,Qd as purchaseCredits,lD as putConnectionOAuth2Application,Ps as rawErrorText,kz as reactivateSandbox,Hd as reactivateSubscription,En as readBlob,wF as readDriveFile,In as readFile,Aa as readKortixMember,$u as readProjectFile,LE as readSavedSessionCopy,Zi as reasoningIsRunning,Ru as rebuildProjectSnapshot,Gl as reconcileConnection,Wl as reconcileMemberConnection,GB as reconcileServices,PY as recordPlatformLogout,zi as recoverLinkResults,Jp as recoverProjectSession,JL as refreshReferralCode,mn as refreshSession,jo as registerAppArtifact,gD as registerConnectionOAuth2Client,Wf as registerDeviceToken,WB as registerService,Xf as registerWebPushSubscription,tl as rejectProjectAccessRequest,eW as relativizePath,Zp as reloadProjectSessionConfig,ed as reloadProjectSessionConfigStream,Xm as removeAccountAuditWebhook,dc as removeAccountBrandingAsset,wc as removeAccountMember,Xg as removeGroupMember,rh as removeKortixPty,lf as removeMarketplaceSource,xA as removeQueued,Jl as renameConnection,ms as renameFile,_z as renameSandbox,op as reopenChangeRequest,OB as reopenMilestone,kA as reorderQueued,lB as replaceColumns,pB as replaceFields,Kc as replaceProjectRepository,gB as replaceTemplates,fd as replayTriggerRun,nU as requestAccountDeletion,ip as requestChangesOnChangeRequest,UO as requestProjectAccess,ef as requestProjectConnector,Zm as requestProjectSecret,SL as requestTopUp,BE as requireKortixMember,_c as resendAccountInvite,cl as resendPendingProjectInvite,gc as resetAccountBranding,eq as resetClient,Ag as resetGatewayRoutingPolicy,oi as resetPassword,rq as resetPublicClient,Zz as resetSandboxUpdateStatus,_l as resolveApproval,HE as resolveComposerAgent,vM as resolveComposerModel,NY as resolveConnectorStart,SM as resolveModelDefault,Ej as resolvePublicShareUrl,YW as resolveScrapeResults,Vb as resolveWorkingTurn,_L as resolvedPlan,Mf as restartAppMachine,Or as restartProjectSession,Sz as restartSandbox,Bf as restoreAppVolume,Nz as restoreBackup,TF as restoreDriveVersion,Qp as restoreProjectSession,Ol as retryAccountSecretResource,SA as retryFailed,Vp as retrySessionPrompt,UB as revealCredential,qg as reviewItemTarget,bw as reviewSegmentForStatus,u$ as reviewVerdictAllowed,r$ as reviewVerdictForStatus,Ll as revokeAccountSecretResourceGrant,h0 as revokeAccountSession,Nm as revokeAccountToken,_m as revokeAssignment,p_ as revokeCaptureDevice,f_ as revokeCaptureEnrollmentToken,Hl as revokeConnection,Ng as revokeGatewayKey,Bm as revokeOAuthGrant,al as revokePendingProjectInvite,sl as revokeProjectAccess,Wm as revokeProjectCliToken,Ez as revokeSandboxProjectAccess,Tm as revokeSandboxShare,W$ as revokeScimToken,Lp as revokeSessionPublicShare,bt as rewriteLocalhostUrl,Cf as rollbackApp,dI as rootRuntimeSession,Ml as rotateAccountSecretResource,mm as rotateOAuthClientSecret,bo as runConnector,Kg as runGatewayPlayground,qO as runProjectProviderOAuthFlow,ga as runtimeSessionsOf,Uv as runtimeSupports,Wk as sanitizePtyChunk,Hc as saveGitHubInstallation,cS as savedCopyEmptyRoot,Df as scaleApp,zd as scheduleDowngrade,k_ as searchCapture,Kl as searchConnectorTools,O_ as searchMyCapture,Lu as searchProjectFiles,Nb as segmentTurn,_N as selectableProjectAgents,ti as sendMagicLink,e$ as sendReferralEmails,tJ as serverCompactionRevalidateAtMs,qB as serviceAction,gJ as sessionConnectionLabel,dJ as sessionListStatus,zI as sessionLogActivityText,tE as sessionLogAnsweredQuestionCall,QI as sessionLogBurstRunning,HI as sessionLogBurstSteps,YI as sessionLogBurstSummary,JI as sessionLogBurstWorkLabel,RI as sessionLogCallStatus,gE as sessionLogFullTextAction,mE as sessionLogFullTextPlan,aE as sessionLogHarnessSwitches,wI as sessionLogOfV1Rows,XI as sessionLogOpenCall,CI as sessionLogPromptMessage,uE as sessionLogReferencedTexts,lE as sessionLogRestoreNotice,WP as sessionLogRetrying,eE as sessionLogShowGroupCall,sE as sessionLogThreadMetrics,qI as sessionLogTurnSegments,Pa as sessionLogTurns,fE as sessionLogWithFullTexts,kM as sessionModelCandidates,jr as sessionModelPin,Cj as sessionParentId,jj as sessionPromptActions,zj as sessionStartKey,$l as setAccountSecretResourceAccess,JH as setActiveInstanceCookie,XS as setAdminBypass,pU as setAdminProviderDistribution,fU as setAdminProviderFallback,Id as setAgentScope,tg as setBillingPlan,ZO as setBootstrapAuthToken,XO as setCachedAuthToken,M_ as setCaptureEnabled,P_ as setCapturePolicy,bD as setConnectionPolicies,su as setConnectorAuthorizationStrategy,_u as setConnectorCredential,ru as setConnectorCredentialMode,lu as setConnectorName,au as setConnectorPolicies,AD as setConnectorSecretBinding,ou as setConnectorSensitive,Yl as setDefaultConnection,q0 as setEnterpriseDemo,Xy as setEnv,Lg as setGatewayBudget,vg as setGatewayRoutingPolicy,HY as setGitHubAppFromExisting,zY as setGitHubAppPat,$M as setImpersonationSession,EY as setMaintenanceConfig,F$ as setMemberSuperAdmin,Q$ as setMfaRequired,Rd as setModelDefault,Rl as setPersonalProjectSecret,Gr as setProjectModelAccess,tL as setProjectModelEnablement,Uc as setProjectOnboardingComplete,wO as setProjectOnboardingProfile,ku as setProjectPolicies,Sl as setProjectSecretStrategy,rd as setProjectSessionModel,nd as setProjectSessionScope,Rp as setProjectSessionSharing,ud as setProjectTriggersActivation,yj as setSavedCopyStore,Mp as setSessionArchived,Z$ as setSessionOversight,Ep as setSessionPinned,Nl as setSessionProviderSecretPool,Ip as setSessionWatch,I2 as settleSessionConnection,qz as setupSSH,Xl as shareConnection,yF as shareFolder,tN as shellActivityGroupLabel,cP as shellExitCode,QS as shouldAttachImpersonation,zV as shouldHideResponsePart,Un as shouldShowToolPart,$V as shouldSuppressWorkingTurnBusy,qb as showGroupItems,Gb as showTurnBusyIndicator,ei as signInWithPassword,ri as signInWithProvider,li as signInWithSso,pi as signOut,$U as signOutDevice,Zo as signUp,UH as skillDocumentPath,$H as skillInputDir,SW as sortSessions,WI as splitSessionLogTurnWork,nP as splitTurnWork,z1 as splitUserParts,vf as startApp,If as startAppMachine,mD as startConnectionOAuth2Authorization,fD as startConnectionOAuth2DeviceAuthorization,kY as startConnectorSetupLink,VY as startGitHubAppManifest,oo as startProjectProviderOAuth,dt as startProjectSession,kd as startProjectSessionOrThrow,TY as startSessionWithToken,YK as startTask,qn as stepLabel,Af as stopApp,Ef as stopAppMachine,Dr as stopProjectSession,xz as stopSandbox,Yc as storeGitHubUserToken,lb as stripAnsi,zH as stripInstancePrefix,pe as stripTrailingSlashes,rE as subAgentCalls,bY as submitAccessRequest,OY as submitDemoRequest,xY as submitOAuthConsent,km as submitReviewItem,RY as submitSecretSetupLink,UM as subscribeToImpersonation,rO as supabaseClient,nu as syncConnectors,vL as syncSubscription,sq as systemReload,_t as toDaemonPath,QH as toInstanceAwarePath,sA as toInternalUrl,Cn as toSandboxAbsolutePath,mb as toToolView,Sh as toWorkspaceRelative,Zr as toolCallBlock,pk as toolCallError,ck as toolCallMetadata,uk as toolCallRawOutput,lk as toolCallStatus,Ni as toolInfo,ce as toolKind,yT as toolViewModel,c$ as triggerControlsFrom,Xz as triggerSandboxUpdate,Kk as triggersRequest,oI as turnEndCause,J2 as turnEndNotice,CW as turnHasSteps,FV as turnIsConfirmedActive,NV as turnRendersQueued,fJ as turnRetryLabel,oB as unassignTicket,Vf as unregisterDeviceToken,Zf as unregisterWebPushSubscription,hF as unshareFolder,Pb as untimedAnchorOf,_e as unwrapError,Qm as updateAccountAuditWebhook,uc as updateAccountBranding,kc as updateAccountMemberRole,cc as updateAccountName,dL as updateAgentConfig,df as updateApp,_f as updateAppAccess,Uf as updateAppVolume,O0 as updateAuditWebhook,cp as updateChangeRequest,BL as updateChannelBinding,Vl as updateConnectionCredential,wg as updateEmailPolicy,Lc as updateExperimentalFeature,jc as updateFeatureFlag,zg as updateGroup,nh as updateKortixPty,EB as updateMilestone,Jf as updateNotificationPreferences,gm as updateOAuthClient,ii as updatePassword,b0 as updatePatPolicy,E$ as updatePolicy,yr as updateProject,rl as updateProjectAccess,hB as updateProjectAgent,Ed as updateProjectDefaultAgent,pl as updateProjectGroupGrant,$c as updateProjectSandboxProvider,zp as updateProjectSession,cd as updateProjectTrigger,om as updateRole,im as updateRolePermissions,Iu as updateSandboxTemplate,f0 as updateSessionPolicy,Eo as updateSessionReminder,jm as updateSessionReminders,zK as updateTask,xO as updateTemplateWarmPool,nB as updateTicket,rB as updateTicketStatus,ci as updateUserMetadata,pc as uploadAccountBrandingAsset,Pf as uploadAppArtifactArchive,mo as uploadConnectorAttachment,kF as uploadDriveFile,Mn as uploadFile,Ev as uploadNativeFile,vr as uploadPromptAttachment,Py as uploadSessionAttachment,_g as uploadSlackChannelFile,kn as uploadTimeoutMsForBytes,$B as upsertCredential,vl as upsertProjectGitCredential,Pl as upsertProjectSecret,s0 as upsertSsoProvider,Ic as validateProjectManifest,QL as validateReferralCode,Ac as validateToken,VL as verifyGatewayProvider,WE as verifyKortixToken,ni as verifyOtp,i0 as verifySsoDomain,lJ as wakeEscalationAttemptSummary,cJ as wakeEscalationNote,iJ as wakeProgressFingerprint,Ft as wireIdClock,bn as wireIdClockAt,Nt as wireIdClockDelta,aH as workedForLabel,V2 as workingExpiryAtMs,KV as workingTurnDrawsBusyRow,nN as writeActivityGroupLabel,gs as writeFile,Yi as wsDomain,HW as wsFavicon,VW 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 c=0;c<s;c++)a.push({type:"unchanged",text:n[c]});for(let c=s;c<o;c++)a.push({type:"removed",text:n[c]});for(let c=s;c<i;c++)a.push({type:"added",text:r[c]});for(let c=o;c<n.length;c++)a.push({type:"unchanged",text:n[c]});return a}function _C(e){let t=As(e.input),n=t.map(([s,o])=>hC(s,o)),r=t.length&&n.every(Boolean)?n.flatMap(s=>s??[]):void 0;return{kind:"file-edit",path:ia(e),diff:r}}var mS=/^Found\s+(\d+)\s+match/i,bC=/^(\/[^:]+?):\s*/,dS=/Line\s+(\d+):/g;function SC(e){let t=e.trim(),n=t.match(mS),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(bC);if(!a)continue;let c=a[1],p=i.slice(a[0].length),d=[],g;for(dS.lastIndex=0;(g=dS.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,_=p.slice(d[m].contentStart,f).trim();s.push({path:c,line:d[m].line,content:_.endsWith(";")?_.slice(0,-1):_})}}return s}function PC(e){return e.trim().split(`
|
|
97
|
+
`).map(t=>t.trim()).filter(t=>t.startsWith("/")||t.startsWith("./")||t.startsWith("~")).map(t=>({path:t}))}function xC(e){let t=ne(e.input?.pattern,e.input?.query)??"";if(e.status==="error"||!e.output)return{kind:"search",pattern:t};let n=mS.test(e.output.trim())?SC(e.output):PC(e.output);return{kind:"search",pattern:t,matches:n.length>0?n.slice(0,200):void 0}}function wC(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 oa(e){let t=zt(e)??{};return{content:ne(t.content)??"",status:ne(t.status)??"pending",priority:ne(t.priority)}}function kC(e){let t=e.input?.todos;if(Array.isArray(t))return{kind:"todo",items:t.map(oa)};if(Array.isArray(e.outputParsed))return{kind:"todo",items:e.outputParsed.map(oa)};let n=zt(e.outputParsed);return n&&Array.isArray(n.todos)?{kind:"todo",items:n.todos.map(oa)}:{kind:"todo",items:[]}}function vC(e){return{kind:"question",questions:(Array.isArray(e.input?.questions)?e.input.questions:[]).map(r=>{let s=zt(r)??{},i=(Array.isArray(s.options)?s.options:[]).flatMap(a=>{let c=zt(a),p=c&&ne(c.label);return p?[{label:p,description:c?ne(c.description):void 0}]:[]});return{question:ne(s.question)??"",header:ne(s.header),options:i}})}}function AC(e){let n=e.input&&Object.keys(e.input).length>0?pS(e.input):void 0,r;return e.outputParsed!==void 0?r=typeof e.outputParsed=="string"?zn(e.outputParsed):pS(e.outputParsed):e.outputText!==void 0?r=zn(e.outputText):r=e.error,{kind:"generic",label:e.title,inputPretty:n,outputPretty:r}}function RC(e){switch(ce(e.name)){case"web_search":return cC(e);case"bash":return gC(e);case"read":return mC(e);case"write":return fC(e);case"edit":return _C(e);case"grep":case"glob":return xC(e);case"task":return wC(e);case"todowrite":return kC(e);case"question":return vC(e);default:return AC(e)}}var TC=new Set(["AbortError","MessageAbortedError"]),CC=["operation was aborted","aborted by user","interrupted by user","cancelled by user","canceled by user","request was cancelled","request was canceled","aborterror"],IC=["unreachable","upstream","econnreset","econnrefused","socket hang up","network","fetch failed","timed out","timeout","gateway","502","503","504"];function fS(e){let t=e.toLowerCase();return IC.some(n=>t.includes(n))?!1:CC.some(n=>t.includes(n))}function EC(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 js(e){if(typeof e=="string")return fS(e);if(!e||typeof e!="object")return!1;let t=e,n=t.name;if(typeof n=="string"&&TC.has(n))return!0;let r=EC(t);return typeof r=="string"?fS(r):!1}var MC=["user","runtime-disposed","orphan-finalized","wake"],dz=["orphan-finalized","wake"];function gz(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 MC.includes(n)?n:void 0}var Ls="kortix-active-instance",OC=["/dashboard","/agents","/p","/workspace","/settings","/browser","/desktop","/services","/sessions","/terminal","/files","/scheduled-tasks","/commands","/tools","/configuration","/changelog","/legacy","/credits-explained"];function DC(e){return OC.some(t=>e===t||e.startsWith(`${t}/`))}function Yn(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 fz(e){let t=Yn(e);return!!t&&t.innerPath===""}function yz(e){let t=Yn(e);return!t||!t.innerPath?e:t.innerPath}function jC(e,t){if(!e)return t;if(t.startsWith("/")||(t=`/${t}`),t.startsWith("/instances/")){let n=Yn(t);return n?`/instances/${encodeURIComponent(e)}${n.innerPath}`:t}return DC(t)?`/instances/${encodeURIComponent(e)}${t}`:t}function LC(e){return e?Yn(e)?.instanceId??null:null}function hz(){return typeof window>"u"?null:LC(window.location.pathname)||$C()}function $C(){if(typeof document>"u")return null;let e=document.cookie.match(new RegExp(`(?:^|; )${Ls}=([^;]+)`));return e?decodeURIComponent(e[1]):null}function _z(e){if(typeof document>"u")return;let t=n=>{document.cookie=n};if(typeof window<"u"&&window.location.pathname.startsWith("/projects")){t(`${Ls}=; Max-Age=0; Path=/; SameSite=Lax`);return}if(!e){t(`${Ls}=; Max-Age=0; Path=/; SameSite=Lax`);return}t(`${Ls}=${encodeURIComponent(e)}; Path=/; SameSite=Lax`)}function bz(e,t){return t?jC(t,e):e}function Sz(e){let t=Yn(e);return t?t.innerPath||"/dashboard":e}function Jn(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 yS(e){let t=Jn(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 xz=yS;function aa(e){let t=yS(e);if(!t||typeof t!="object")return null;let n=t;return n.name==="ConfigInvalidError"?n:null}var wz=aa;function UC(e){return aa(e)!==null}var kz=UC,FC=[/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"],NC=/\bruntime_not_ready\b|sandbox runtime not ready|opencode not ready/i;function BC(e){return NC.test(Jn(e))}function Qn(e){let t=Jn(e);return t?BC(t)||FC.some(n=>n.test(t)):!1}var KC=/server url not ready|sandbox is still loading/i;function Az(e){return KC.test(Jn(e))||Qn(e)}var $s=class extends Error{constructor(t){let n=t?.trim();super(n&&Qn(n)?n:n?`sandbox not ready: ${n}`:"sandbox not ready"),this.name="SandboxNotReadyError"}};function qC(e){let t=aa(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=Jn(e);return Qn(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 Rz=qC;function hS(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 Ez(e,t){return e.external_id?`${nt()}/p/${e.external_id}/${t}`:null}async function Lz(){let e=await l.get("/setup/sandbox-providers");if(e.error)throw e.error;return e.data}async function GC(e){let t=await gn();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 gt(r.project_id,s.session_id))?.sandbox??null;return{sandbox:Gr(r,s,o),created:!0}}async function $z(){return(await gn().catch(()=>null))?.sandbox??null}async function Uz(e){return{sandbox:(await GC(e)).sandbox}}async function Fz(e){let t=dn(e);if(!t)return null;try{let n=await Ko(t);return n?Gr(await Tt(n.project_id),n,null):(await gn(t))?.sandbox??null}catch{return null}}async function Nz(e,t){throw await Wr(e)?new Error("Renaming project-session sandboxes is not exposed by the current API"):new Error("Project session sandbox not found")}async function Bz(e){let t=dn(e);return(await Bo().catch(()=>[])).map(r=>r.sandbox).filter(r=>!t||r.sandbox_id===t||r.external_id===t)}async function Kz(){return null}async function qz(e){if(!e)throw new Error("No sandbox selected for workload restart");let t=await Wr(e);if(!t)throw new Error("Project session sandbox not found");await Dr(t.projectId,t.sessionId)}async function Gz(e){if(!e)throw new Error("No sandbox selected to stop");let t=await Wr(e);if(!t)throw new Error("Project session sandbox not found");await jr(t.projectId,t.sessionId)}async function Wz(e){throw new Error("Cancellation is not exposed for project-session sandboxes")}async function Vz(e){throw new Error("Reactivation is not exposed for project-session sandboxes")}async function ca(e,t,n){let r=hS(e),s=await L(`${ue(r)}${t}`,{signal:AbortSignal.timeout(8e3),headers:{"Content-Type":"application/json"},...n});if(!s.ok){let o=await s.text().catch(()=>"");throw new Error(o||`Request failed (${s.status})`)}return await s.json()}async function Qz(e,t){return ca(e,`/kortix/projects/${encodeURIComponent(t)}/members`,{method:"GET"})}async function Xz(e,t,n,r="member"){await ca(e,`/kortix/projects/${encodeURIComponent(t)}/members`,{method:"POST",body:JSON.stringify({user_id:n,role:r})})}async function Zz(e,t,n){await ca(e,`/kortix/projects/${encodeURIComponent(t)}/members/${encodeURIComponent(n)}`,{method:"DELETE"})}var la="Use the account invite functions (acceptAccountInvite, declineAccountInvite).";async function nY(e){throw U("getInvite",la)}async function rY(e){throw U("acceptInvite",la)}async function sY(e){throw U("declineInvite",la)}async function iY(e){throw new Error("Backups are not exposed for project-session sandboxes")}async function aY(e,t){throw new Error("Backups are not exposed for project-session sandboxes")}async function cY(e,t){throw new Error("Backups are not exposed for project-session sandboxes")}async function lY(e,t){throw new Error("Backups are not exposed for project-session sandboxes")}async function pY(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 WC=["pulling","patching","stopping","removing","recreating","restarting","verifying","starting","health_check"];function yY(e){return WC.includes(e)}async function hY(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 _Y(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 VC(e||"stable");r.changelog=s.find(o=>o.version===r.version)??s[0]??null}catch{r.changelog=null}return r}async function VC(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 SY(e,t){throw new Error("Sandbox image updates are managed by project-session provisioning")}async function PY(e){}async function xY(e){}async function vY(e){return{serverTypes:[],location:e||"hel1"}}async function AY(e){throw new Error("Retired instance provisioning is unavailable. Create a project session on platinum (or the legacy daytona fallback).")}async function RY(e){throw U("deleteInstance")}async function TY(e,t){}async function CY(){throw U("claimComputer")}async function IY(e){return null}function EY(e,t){throw U("getSandboxProvisionStreamUrl")}var Us=class extends Error{constructor(n,r,s){super(n);this.status=r;this.body=s;this.name="HostBoundaryError"}status;body};function _S(e,t){let n=new Headers(e.headers);return n.set("Accept","application/json"),t&&n.set("Content-Type","application/json"),e.accessToken&&n.set("Authorization",`Bearer ${e.accessToken}`),n}async function bS(e){let t=await e.text().catch(()=>"");if(!t)return null;try{return JSON.parse(t)}catch{return t}}function SS(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:_S(t,r),...r?{body:JSON.stringify(n.body)}:{},...t.signal?{signal:t.signal}:{},...t.cache?{cache:t.cache}:{},...t.next?{next:t.next}:{}}),o=await bS(s);if(!s.ok)throw new Us(SS(s,o),s.status,o);return o}function HC(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 LY(e,t){return X(`/marketplace/items${HC(t)}`,e)}function $Y(e){return X("/marketplace/marketplaces",e)}function UY(e,t){return X(`/marketplace/items/${encodeURIComponent(e)}`,t)}function FY(e,t,n){return X(`/marketplace/items/${encodeURIComponent(e)}/file?path=${encodeURIComponent(t)}`,n)}function NY(e,t){return X("/access/check-email",t,{method:"POST",body:{email:e}})}function BY(e,t){return X("/access/request-access",t,{method:"POST",body:e})}function KY(e){return X("/auth/logout",e,{method:"POST",body:{}})}function qY(e,t){return X(`/oauth/authorize/consent/${encodeURIComponent(e)}`,t)}function GY(e,t){return X("/oauth/authorize/consent",t,{method:"POST",body:{request_id:e.requestId,approved:e.approved}})}function WY(e,t){return X(`/setup-links/connectors/${encodeURIComponent(e)}`,t)}function VY(e,t){return X(`/setup-links/connectors/${encodeURIComponent(e)}/start`,t,{method:"POST",body:{}})}function HY(e,t,n={}){return X(`/setup-links/connectors/${encodeURIComponent(e)}/finalize`,t,{method:"POST",body:n.connectionId?{connection_id:n.connectionId}:{}})}function zY(e,t){return X(`/setup-links/secret/${encodeURIComponent(e)}`,t)}function YY(e,t,n,r){return X(`/setup-links/secret/${encodeURIComponent(e)}`,n,{method:"POST",body:{values:t,...r?.only_requester?{only_requester:!0}:{}}})}function JY(e,t){return X(`/p/public-share/${encodeURIComponent(e)}`,t)}function QY(e,t,n){return X(`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/start`,n,{method:"POST",body:{}})}function XY(e){return X("/system/maintenance",e)}function ZY(e,t){return X("/system/maintenance",t,{method:"PUT",body:e})}function e2(e){return X("/user-roles",e)}function t2(e,t){return X("/system/demo-request",t,{method:"POST",body:e})}async function n2(e,t,n){let r=await fetch(`${Ne(n.backendUrl)}/accounts/${encodeURIComponent(e)}/audit/export?${Lt(t)}`,{headers:_S(n,!1),...n.signal?{signal:n.signal}:{}});if(!r.ok){let s=await bS(r);throw new Us(SS(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 r2(e,t){throw U("openStressTestStream")}function s2(e,t){throw U("buildPublicTemplateUrl")}async function o2(e,t,n){throw U("getPublicTemplate")}var zC="kortix:connect-link:";function ua(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`${zC}${t.toString(36)}${n.toString(36)}`}function a2(e,{storage:t}={}){let n=new Map,r=new Map,s=i=>{if(t)try{let a=t.getItem(ua(i));if(!a)return;let c=JSON.parse(a);if(Date.parse(c.expires_at)<=Date.now()){t.removeItem(ua(i));return}return c}catch{return}},o=(i,a)=>{if(t)try{t.setItem(ua(i),JSON.stringify(a))}catch{}};return{peek(i){let a=r.get(i);if(a)return a;let c=s(i);return c&&r.set(i,c),c},load(i){let a=n.get(i);if(a)return a;let c=e(i).then(p=>(r.set(i,p),o(i,p),p),p=>{throw n.delete(i),p});return n.set(i,c),c}}}var PS="Could not start the connect flow.";async function c2(e){let t;try{t=await e.start()}catch(r){return{kind:"error",message:r instanceof Error?r.message:PS}}if(t.connect_url)return{kind:"popup",url:t.connect_url};if(!t.connected)return{kind:"error",message:PS};let n=null;try{n=(await e.finalize()).connected_as??null}catch{}return{kind:"connected",alreadyConnected:t.already_connected===!0,connectedAs:n}}var YC=3e3,JC=5e3,QC=5*6e4;function l2(e,t){let n=e===0?YC:JC;return t+n>QC?null:n}function u2(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 g2(){let e=await l.get("/platform/github-app/status",{showErrors:!1});if(e.error)throw e.error;if(!e.data)throw new Error("GitHub App status request failed");return e.data}async function m2(e={}){let t=await l.post("/platform/github-app/manifest-start",e,{showErrors:!1});if(t.error)throw t.error;if(!t.data)throw new Error("GitHub App manifest-start request failed");return t.data}async function f2(e){let t=await l.post("/platform/github-app/app",{app_id:e.appId,private_key:e.privateKey,installation_id:e.installationId,slug:e.slug,client_id:e.clientId,client_secret:e.clientSecret},{showErrors:!1});if(t.error)throw t.error;if(!t.data)throw new Error("GitHub App configuration request failed");return t.data}async function y2(e){let t=await l.post("/platform/github-app/pat",e,{showErrors:!1});if(t.error)throw t.error;if(!t.data)throw new Error("GitHub token configuration request failed");return t.data}async function h2(){let e=await l.delete("/platform/github-app",{showErrors:!1});if(e.error)throw e.error;if(!e.data)throw new Error("GitHub App disconnect request failed");return e.data}var b2="1";var XC="kortix.query-cache";function wS(e){return!!e&&typeof e.then=="function"}function xS(e){return wS(e)?e:Promise.resolve()}function S2(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 P2(e){let{storage:t,userId:n,shouldPersist:r,version:s="1",maxAgeMs:o=6048e5,maxBytes:i=1e6,throttleMs:a=1e3,namespace:c=XC,now:p=()=>Date.now()}=e,d=`${c}:${n}`,g=null,m=!1,f=null,_=Promise.resolve(),y=()=>{try{return xS(t.removeItem(d)).catch(()=>{})}catch{return Promise.resolve()}},k=(S,v)=>{if(!v)return 0;let C;try{C=JSON.parse(v)}catch{return y(),0}if(!C||C.v!==s||C.user!==n||!Array.isArray(C.queries)||p()-C.at>o)return y(),0;let j=0;for(let w of C.queries){if(!w||!Array.isArray(w.k)||w.d===void 0||typeof w.t!="number"||p()-w.t>o||!r(w.k))continue;let D=S.getQueryState(w.k);D&&D.data!==void 0&&D.dataUpdatedAt>=w.t||(S.setQueryData(w.k,w.d,{updatedAt:w.t}),S.invalidateQueries?.({queryKey:w.k,exact:!0,refetchType:"none"}),j+=1)}return j},R=S=>S.getQueryCache().getAll().filter(v=>v.state.data!==void 0&&r(v.queryKey)).map(v=>({k:v.queryKey,d:v.state.data,t:v.state.dataUpdatedAt})).sort((v,C)=>C.t-v.t),I=(S,v)=>{let C=[],j=0;for(let w of S){let D=JSON.stringify(w).length+1;j+D>v||(C.push(w),j+=D)}return C},b=async S=>{let v=I(R(S),i);for(;;){let C={v:s,user:n,at:p(),queries:v};try{await xS(t.setItem(d,JSON.stringify(C)));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 S=g;return!S||!m||(m=!1,_=_.then(()=>b(S)).catch(()=>{})),_},x=()=>{m=!0,f===null&&(f=setTimeout(()=>{f=null,h()},a))};return{storageKey:d,restore(S){let v;try{v=t.getItem(d)}catch{return 0}return wS(v)?v.then(C=>k(S,C)).catch(()=>0):k(S,v)},persist(S){g=S,m=!0;let v=S.getQueryCache().subscribe(C=>{C.type!=="updated"&&C.type!=="removed"&&C.type!=="added"||r(C.query.queryKey)&&x()});return()=>{v(),g===S&&(g=null,M())}},flush(){return h()},async clear(){M(),g=null,m=!1,await _,await y()}}}function x2(){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 ZC="/kortix/part/";function eI(e){return typeof e=="string"&&e.startsWith(ZC)}async function A2(e){if(!eI(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 L(`${t}${e}`);if(!n.ok)throw new Error(`attachment part fetch failed: ${n.status}`);return n.blob()}function kS(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 tI(e,t){try{let n=new URL(e),r=n.pathname;if(!(/^\/v1\/p\/[^/]+\/\d+(?:\/|$)/.test(r)||/^\/proxy\/\d+(?:\/|$)/.test(r)))return!1;let o=new Set;if(t)try{o.add(new URL(t).origin)}catch{}return typeof window<"u"&&o.add(window.location.origin),o.has(n.origin)}catch{return!1}}function vS(e,t){return tI(e,t)?(t?kS(t):null)??kS(e):null}function Fs(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 AS(e,t){try{let n=new URL(e);return n.searchParams.set("token",t),n.toString()}catch{return e}}var nI=/^p\d{1,5}-[a-z0-9-]+\.localhost$/;function rI(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function sI(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(rI).join("[a-z0-9-]+")).join("\\d{1,5}");return new RegExp(`^${o}$`).test(e)}function oI(e){try{let t=new URL(e);return t.hostname==="localhost"||t.hostname==="127.0.0.1"?t:null}catch{return null}}function RS(e){return e.port?e.port:e.protocol==="https:"?"443":"80"}function iI(e,t){let n;try{n=new URL(e)}catch{return!1}return n.protocol!=="https:"&&n.protocol!=="http:"?!1:nI.test(n.hostname)?t.backendUrls.some(r=>{let s=oI(r);return s!==null&&RS(s)===RS(n)}):t.templates.some(r=>sI(n.origin,r))}async function TS(e,t={}){if(!Fs(e))return!1;let n=T().backendUrl;n&&await mt(n).catch(()=>null);let r=[n,t.serverUrl].filter(s=>typeof s=="string"&&s.length>0);return iI(e,{templates:jy(),backendUrls:r})}async function aI(e,t={}){let n=vS(e,t.serverUrl||T().backendUrl||void 0);if(!n)return!1;let r=await rn();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 $2(e,t={}){if(Fs(e)){if(!await TS(e,t))return e;let n=await rn();return n?AS(e,n):e}return await aI(e,t),e}var F2=3e3;function cI(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 N2(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 cI(o.status)}catch{return"unknown"}finally{clearTimeout(s),t?.signal?.removeEventListener("abort",r)}}function lI(e){let t=e;for(;t.endsWith("/");)t=t.slice(0,-1);return t}function q2(e,t){throw U("buildPresentationTemplatePdfUrl")}function G2(e,t){throw U("buildPresentationTemplateImageUrl")}function uI(e,t){return`${lI(e)}/presentation/convert-to-${t}`}async function W2(e,t,n,r){let s=uI(t,e),o=r?.pollIntervalMs??2500,i=r?.timeoutMs??4*6e4,a=Date.now(),c=!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 _=await p.blob();if(_.size===0)throw new Error("Downloaded file is empty");return _}if(p.status===202){if(c||(c=!0,r?.onGenerating?.()),Date.now()-a>i)throw new Error(`Timed out waiting for the ${e.toUpperCase()} to generate`);await new Promise((_,y)=>{let k=setTimeout(_,o);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 z2(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 Y2(e){return e==="unreachable"}function J2(e){return!e||e.status===0?"unknown":e.ok&&Bh(e.health)?"live":e.hop==="control_plane"?"waking":e.ok||e.health?.status==="starting"?"connecting":"unreachable"}var pI=1e4,Q2={connection:"unknown",faultSinceMs:null};function X2(e,t,n,r=pI){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 CS({optimistic:e,abort:t,inbox:n,server:r,stream:s,activity:o,nowMs:i}){let a=!!e&&i-e.atMs<pa,c=!!t&&i-t.atMs<ma;return{receiptLive:a,receiptTurnId:e?e.turnId===void 0?e.messageId:e.turnId:null,serverFloor:a?e?.acceptedAtMs??Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY,streamFloor:a?e?.atMs:Number.NEGATIVE_INFINITY,abortLive:c,abortFloor:c?t?.settledAtMs??Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY,serverFresh:!!r&&i-r.atMs<=da,streamFresh:!!s&&i-s.atMs<=Xn,inboxFresh:!!n&&i-n.atMs<=ga,activityFresh:!!o&&i-o.atMs<=Xn}}function Yt(e){if(!e)return null;let t=Date.parse(e);return Number.isNaN(t)?null:t}function fa(e,t,n){if(!t)return!1;let r=Yt(e.started_at);if(r===null||r>=t.atMs)return!1;let s=n?.lastEnded,o=Yt(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:c}=t;return c&&(!n||s.atMs>n.atMs)&&s.atMs>=a?{state:"working",source:"stream",turnId:i?o.turns.find(d=>d.state==="active"&&!fa(d,n,o))?.message_id??null:null,since:s.atMs,serverOpenTurnToken:r}:null}function gI(e,t,n,r){let{server:s,stream:o}=e,{serverFresh:i,abortFloor:a}=t,c=i?s.turns.filter(g=>!fa(g,n,s)):[],p=c.find(g=>g.state==="active")??c[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:Yt(p.started_at)??s.atMs,serverOpenTurnToken:r},openTurn:p}:{result:null,openTurn:p}}function mI(e,t,n){let{inbox:r,server:s,stream:o}=e,{inboxFresh:i,abortFloor:a,streamFresh:c,serverFresh:p,receiptLive:d,receiptTurnId:g,abortLive:m}=t;if(i&&r.pending>0&&r.atMs>=a)return{...c&&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 fI(e,t,n,r){let{server:s,stream:o,optimistic:i,nowMs:a}=e,{serverFresh:c,serverFloor:p,streamFresh:d,streamFloor:g,abortFloor:m,receiptLive:f,receiptTurnId:_}=t,y=c&&!n&&s.atMs>=p,k=d&&o.atMs>=g&&(o.type==="idle"||o.atMs>=m);if(y&&(!o||s.atMs>=o.atMs))return{state:"idle",source:"server",turnId:null,since:Yt(s.lastEnded?.ended_at)??s.atMs,serverOpenTurnToken:r};if(k)return{state:o.type==="idle"?"idle":"working",source:"stream",turnId:null,since:o.atMs,serverOpenTurnToken:r};if(f)return{pendingDelivery:!0,state:"working",source:"optimistic",turnId:_,since:i.atMs,serverOpenTurnToken:r};let R=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:R.source,turnId:null,since:R.atMs,serverOpenTurnToken:r}}function IS(e){let t=CS(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:c}=gI(e,t,s,o);return a??mI(e,t,o)??fI(e,t,c,o)}var pa=6e4,da=45e3,Xn=45e3,ga=1e4,lJ=3e3,ma=15e3;function uJ(e,t){return t?t.serverAtMs!=null&&e.serverAtMs!=null?e.serverAtMs>=t.serverAtMs:e.atMs>=t.atMs:!0}function pJ(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 gJ(e){return IS(e)}function mJ(e){let{optimistic:t,abort:n,inbox:r,server:s,stream:o,activity:i,nowMs:a}=e,c=[null,t?t.atMs+pa:null,n?n.atMs+ma:null,r?r.atMs+ga:null,s?s.atMs+da:null,o?o.atMs+Xn:null,i?i.atMs+Xn:null],p=null;for(let d of c)d===null||d<=a||(p===null||d<p)&&(p=d);return p}function yI(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||js({name:s.name??void 0,message:s.message})?null:s}var hI="SandboxMemoryGuard";function _J(e,t,n){if(!e||!t||n.hasError&&!n.isAbort)return null;let r=yI(e,t);if(r?.message){if(r.name!==hI)return{kind:"cause",name:r.name,message:r.message};let a=r.message.match(/(\d{1,3})%/)?.[1],c=r.message.split(":")[0]?.trim()||null;return{kind:"sandbox-memory",usedPct:a?Number(a):null,detail:c}}let 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 SJ=6e4;function PJ(e){return e.serverCompactingAtMs!==null?!0:e.optimisticAtMs===null?!1:e.nowMs-e.optimisticAtMs<6e4}function xJ(e){if(e.serverCompactingAtMs!==null||e.optimisticAtMs===null)return null;let t=e.optimisticAtMs+6e4;return t>e.nowMs?t:null}var _I=9e4;function wJ(e){return e.serverCompactingAtMs===null?null:e.serverCompactingAtMs+_I}var vJ=75e3,AJ=2,RJ=2e4;function ES(){return{status:"idle",dispatch:"none",fingerprint:null,lastProgressAtMs:null,lastDispatchAtMs:null,attempts:[],msSinceProgress:0,settled:!1}}function TJ(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 CJ(e,t,n={}){let r=n.noProgressMs??75e3,s=n.maxRestarts??2,o=n.cooldownMs??2e4;if(t.runtimeReachable)return{...ES(),settled:!0};if(!t.waking)return{...e,dispatch:"none",fingerprint:null,lastProgressAtMs:null,msSinceProgress:0};if(e.settled)return{...ES(),settled:!0};let i=e.lastProgressAtMs,a=i===null,c=t.progress!==e.fingerprint,p=i===null||c?t.nowMs:i,d=Math.max(0,t.nowMs-p),g={...e,dispatch:"none",fingerprint:t.progress,lastProgressAtMs:p,msSinceProgress:d,status:e.attempts.length>0?"escalating":"waking"};if(e.status==="exhausted")return{...g,status:"exhausted"};let m=!a&&!c&&d>=r;if(!t.serverGaveUp&&!m||e.lastDispatchAtMs!==null&&t.nowMs-e.lastDispatchAtMs<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 SI={"retry-start":"retrying",restart:"restarting"};function IJ(e){if(e.status!=="escalating")return null;let t=e.attempts[e.attempts.length-1];return t?`Still waking \u2014 ${SI[t.step]} the runtime (attempt ${e.attempts.length+1})`:null}function PI(e){return e===1?"once":e===2?"twice":`${e} times`}function EJ(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 ${PI(t)}`),`Tried: ${r.join(", then ")}.`}var OJ={"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 xI(e){return!!(e.metadata??{}).legacy_migration}function DJ(e,t=0){if(t>0)return"needs-you";switch(e.status){case"queued":case"branching":case"provisioning":return"starting";case"running":return"running";case"completed":case"stopped":return xI(e)?"legacy":e.status==="completed"?"done":"stopped";case"failed":return"failed";default:return"stopped"}}function jJ(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 LJ={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 $J(e){return e===null?"Waiting to retry":e>0?`Retrying in ${e}s`:"Retrying now"}function ya(e){return e.runtime_sessions??e.opencode_sessions??[]}function wI(e){let t=ya(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 FJ(e){let t=wI(e);return t?ya(e).filter(n=>n.parent_id===t.id&&!n.archived_at).sort((n,r)=>(r.updated_at??0)-(n.updated_at??0)||n.id.localeCompare(r.id)):[]}function NJ(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=>ya(r).some(s=>s.id===t))??null)}var kI=new Set;function vI(e){for(let t of[...kI])try{t(e)}catch{}}var LS={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 $S=e=>Object.values(e.ext??{}).find(t=>t.version===Ce),US=e=>!!e&&$S(e)!==void 0,FS=e=>{let t=$S(e);return t?t.native_id??null:e.thread_id};function NS(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:FS(t),hasMessages:n,empty:!n&&e.older[t.thread_id]===!1}}var MS=new WeakMap;function BS(e,t){let n=FS(e),r=MS.get(t);if(r&&r.native===n)return r.rows;let{rows:s}=es({...LS,threads:[{...e,messages:[t]}]}),o=s.map(i=>({info:i.info,parts:i.parts}));return MS.set(t,{native:n,rows:o}),o}var ha=e=>e.info.time?.created;var AI=(e,t)=>(ha(e)??-1/0)-(ha(t)??-1/0)||(e.info.id<t.info.id?-1:e.info.id>t.info.id?1:0);var OS=new WeakMap,DS=new WeakMap,KS=e=>typeof e=="object"&&e!==null,RI=e=>e!==void 0&&Number.isFinite(e)&&Math.abs(e)<=864e13?new Date(e).toISOString():null,TI=e=>e.info.role==="user"&&e.parts.some(t=>KS(t)&&t.type==="compaction"),CI=(e,t)=>{let n=e.info;return n.role==="assistant"&&n.summary===!0&&n.parentID===t.info.id},jS=new WeakMap;function II(e,t,n){let r=t.info,s=`${e}|${String(r.id)}|${String(r.time?.created)}`,o=!1,i=n.blocks.map((a,c)=>{let p=t.parts[c];if(!KS(p)||a.type==="compaction")return a;let d=`${s}|${c}|${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 EI(e){let t=new Map,n=new Set;for(let r of e){if(!TI(r))continue;let s=e.find(o=>!n.has(o)&&CI(o,r));s&&(t.set(r,s),n.add(s))}return{paired:t,used:n}}function MI(e,t,n,r,s){let o=OS.get(n);if(o&&o.sessionId===e&&o.native===t&&o.sum===r&&o.seq===s)return o;let a=ts({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}),c=II(t,n,a.threads[0].messages[0]),p={sessionId:e,native:t,sum:r,seq:s,message:{...c,seq:s},lost:a.grade_counts};return OS.set(n,p),p}function OI(e,t,n){let r=DS.get(n);if(r&&r.sessionId===e&&r.native===t)return r.log;let s=[...n].sort(AI),{paired:o,used:i}=EI(s),a={tool_input:0,cut_point:0,attachment:0},c=[];for(let m of s){if(i.has(m))continue;let f=MI(e,t,m,o.get(m),c.length+1);for(let _ of["tool_input","cut_point","attachment"])a[_]+=f.lost[_];c.push(f.message)}let p=RI(s.map(ha).find(m=>typeof m=="number"&&Number.isFinite(m)))??"",d=c.filter(m=>m.role==="user"&&m.kind==="turn"),g={...LS,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:c[0]?.created_at||p,messages:c,ext:{opencode:{version:Ce,native_id:t}}}]};return DS.set(n,{sessionId:e,native:t,log:g}),g}var _a=new WeakMap,Jt=new WeakMap,qS=new WeakMap;function Ns(e){let t,n=Jt.get(e);return n&&(t=DI(n).get(e.id)),t?(_a.set(t,e),t):(e.type!=="harness"?t=Yo(e):typeof e.data?.type=="string"?t=e.data:e.model_visible&&e.fallback_text!==void 0&&(t=qS.get(e)??{id:e.id,type:"text",text:e.fallback_text,synthetic:!0},qS.set(e,t)),t&&_a.set(t,e),t)}var Zn=e=>_a.get(e),xt=e=>e.flatMap(t=>Ns(t)??[]),GS=new WeakMap;function DI(e){let t=GS.get(e);return t||GS.set(e,t=new Map(it(e)[0]?.parts.map(n=>[n.id,n]))),t}var WS=new Map;function it(e){let t=WS.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:""},WS.set(e.thread_id,t)),BS(t,e)}var jI="kortix-v1-import",ba={schema:le,v:1};function Bs(e,t){for(let n=e.length-1;n>=0;n--)if(t(e[n]))return e[n]}var Sa=e=>e.type==="tool_call",LI=e=>e.status==="pending"||e.status==="running",Pa=e=>e.status==="error"&&(e.result?.synthetic===!0||e.result?.error?.code==="interrupted");function $I(e,t){let n=Pa(e);return!LI(e)&&!n?e.status:t?e.status==="running"||n&&e.started_at?"running":"pending":"interrupted"}var VS=new WeakMap;function UI(e,t){let n=VS.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={...ba,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 VS.set(e,s),s}var HS=new WeakMap;function FI(e){let t=HS.get(e);return t||(t={...ba,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:[]},HS.set(e,t)),t}var zS=new WeakMap;function NI(e){let t=zS.get(e);return t||(t={...ba,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:[]},zS.set(e,t)),t}var BI=e=>!e.error&&e.blocks.length===0&&!(e.usage&&(e.usage.input||e.usage.output||e.usage.reasoning));function KI(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,c=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)&&(c=y,i.has(y)||i.set(y,i.size),y.user.kind==="compaction"&&(p=y));continue}if(g.role!=="assistant"||BI(g))continue;let f=(g.reply_to?r.get(g.reply_to):void 0)??c;if(p&&f&&(f===p||(i.get(f)??1/0)<i.get(p))){let y=a.get(p);y||(y={user:NI(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){o.push(g);continue}let _=s[s.length-1];_&&_.user.message_id===g.reply_to?_.assistant.push(g):s.push({user:FI(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 qI(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 QS(e){let n=(e.user.kind==="compaction"?[e.user,...e.assistant]:e.assistant).find(i=>i.error);if(!n?.error)return null;let r=it(n)[0]?.info?.error??n.error.message,s=xe(r),o=Ps(r);return{code:n.error.code,message:s?.message||_e(r),...s&&{details:s},...o!==void 0&&{raw:o}}}function GI(e,t,n){return e.length&&e.every(t)?sa(e.flatMap(r=>it(r).flatMap(s=>s.parts.map(o=>({part:o,message:s})))),n)??null:xa(e,n)}function xa(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 sa(n,t)??null}function WI(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 VI(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&&Sa(n)&&n.name==="bash"?n:null}function HI(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:Sa(i)?vs(i):void 0;a&&r.has(a)&&o.add(a)}return[...o]}var zI=e=>e.assistant.some(t=>t.blocks.some(n=>Sa(n)&&ce(n.name)==="todowrite"&&Bn(n))),YI=e=>e.blocks.length>0&&e.blocks.every(t=>t.type==="text"&&t.synthetic===!0);function JI(e,t){let n=e.map(s=>QS(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 YS=new WeakMap,QI=[];function XS(e){let t=Bs(e.messages,n=>n.role==="assistant");return!!t&&Ab(it(t))}var JS=new WeakMap;function XI(e){let t=JS.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},JS.set(e,t)}return t}function wa(e,t={}){let n=t.hideOutOfContext?XI(e):e,r=new Set(t.held??QI),s=KI(n.messages,r),o=Bs(n.messages,y=>y.role==="assistant"),i=XS(n),a=Qb({turns:s.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:qI(s,t.liveMessageId),unrunTurnIds:r}),c=Bs(s,zI)??s[s.length-1],p=s.map(y=>!y.partial&&YI(y.user)),d=JI(s,p),g=US(n),m=y=>g||y.producer.harness===jI,f=t.threads??[],_=new Set(f.map(y=>y.thread_id));return s.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(o),M=d[k],h=`${y.partial}|${R}|${I}|${y===c}|${b}|${M?(M.continued?"c":"")+M.retries:"-"}`,x=YS.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 S=y.assistant.flatMap(w=>w.blocks);for(let w of y.assistant)for(let D of w.blocks)Jt.set(D,w);let v=HI(y,S,f,_),C=y.assistant[y.assistant.length-1],j={internal:p[k],autoRetry:M,id:y.user.message_id,user:y.user,assistant:y.assistant,partial:y.partial,continues:y.continues??null,blocks:S,status:b?"streaming":C?C.status:y.user.kind==="compaction"?y.user.status:"pending",error:QS(y),cost:GI([y.user,...y.assistant],m,t.pricing),compaction:WI(y.user),threads:v,plan:y===c,shell:VI(y),response:Bs(S,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 YS.set(y.user,{assistant:y.assistant,key:h,pricing:t.pricing,heads:t.threads,turn:j}),j})}var ka=e=>Zn(e);function ZI(e,t={}){return Hb(Wb(xt(e),t),t).map(n=>n.kind==="burst"?{kind:n.kind,blocks:n.parts.map(Zn)}:n.kind==="show-group"?{kind:n.kind,blocks:n.parts.map(ka)}:n.kind==="text"?{kind:n.kind,block:Zn(n.part)}:{kind:n.kind,block:ka(n.part)})}var eE=e=>e.kind==="burst"||e.kind==="show-group"?{kind:e.kind,parts:xt(e.blocks)}:{kind:e.kind,part:Ns(e.block)};function tE(e,t){let n=new Map(e.map(o=>[eE(o),o])),r=aS([...n.keys()],t);if(!r)return null;let s=o=>o.map(i=>n.get(i));return{work:s(r.work),hoisted:s(r.hoisted),final:s(r.final)}}function nE(e){if(!te(e)||!Py(e.tool))return!1;let t=e.state.input?.questions;if(!Array.isArray(t)||!t.length)return!1;let n=bb(e);return(n.answers??uS(n.outputText??"",t.length)??[]).length>0}function rE(e){return Fb(xt(e),n=>Vn(n).tier).flatMap(n=>n.kind==="group"&&n.step.parts.some(nE)?n.step.parts.map(r=>({kind:"part",key:r.id,part:r})):[n]).map(n=>{if(n.kind==="part")return{kind:"block",key:n.key,block:Zn(n.part)};if(n.kind==="group")return{kind:"group",key:n.key,blocks:n.step.parts.map(ka),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&&Jt.get(r);return{kind:"thought",key:n.key,texts:n.texts,running:n.running&&(!s||s.status==="streaming"),durationMs:n.durationMs}})}function sE(e,t){return Zb(xt(e.blocks).map(n=>({part:n})),t?.flatMap(it))}function oE(e){return ta(xt(e))}function iE(e){return Lb(xt(e))}function aE(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=Ns(n),s=Jt.get(n);return!!r&&we(r)&&na(r)&&(!s||s.status==="streaming")}):!1}var ZS=new WeakMap;function cE(e){if(!Pa(e))return e;let t=ZS.get(e);if(!t){let{result:n,...r}=e;t={...r,status:e.started_at?"running":"pending"},ZS.set(e,t)}return t}function lE(e){let{callID:t,error:n,...r}=e;return e.status==="error"?{...r,type:"error",content:n||"This output failed to load."}:r}function uE(e){let t=e.map(se),n=t[0],r=t.some(o=>o.state.status==="running"||o.state.status==="pending"),s=zb(t).map(lE);return ns({...n,state:{...n.state,status:r?"running":"completed",input:{items:s}}})}function pE(e,t,n){let r=se(e),s=r.state;return ns({...r,state:{...s,status:"completed",...n!==void 0&&{input:n},metadata:{...s.metadata??{},answers:t}}})}function dE(e){let t=it(e).map(r=>Wi(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 eP=Object.freeze([]),tP=new WeakMap;function gE(e){if(!e)return eP;let t=tP.get(e);if(!t){let n=e.messages.flatMap(r=>r.role==="assistant"?r.blocks.filter(s=>s.type==="tool_call"&&Bn(s)):[]);t=n.length?n:eP,tP.set(e,t)}return t}function mE(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 wa(e)){let s=xa([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 fE="prt_kortix_restore_g";function yE(e){return e.role==="user"&&e.blocks.some(t=>t.type==="text"&&t.id.startsWith(fE))}function hE(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(c=>c.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 va=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Qe=e=>typeof e=="number"&&Number.isFinite(e)&&e>0?e:0,_E=new Set(["message","attachment","tool_input","cut_point","layout","text","tool_result"]);function bE(e){if(e?.restore_grade!=="partial")return null;let t=e.ext?.kortix?.data,n=va(t)?t.restore:void 0;if(!va(n))return null;let r=va(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,c])=>_E.has(a)?i:i+Qe(c),0)}];return{generation:Qe(n.generation),missing:o.filter(i=>i.count>0)}}var rP=e=>e.type==="text"?[e]:e.type==="tool_call"?(e.result?.content??[]).filter(t=>t.type==="text"):[];function SE(e){let t=new Map;for(let n of e)for(let r of n.blocks)for(let s of rP(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 sP=(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}},PE=(e,t)=>e.map(n=>n.type==="text"?sP(n,t):n),nP=new WeakMap;function xE(e,t){let n=nP.get(e);if(n?.texts===t)return n.out;let r=e.blocks.some(s=>rP(s).some(o=>o.ref!==void 0&&t.has(o.ref)))?{...e,blocks:e.blocks.map(s=>s.type==="text"?sP(s,t):s.type==="tool_call"&&s.result?{...s,result:{...s.result,content:PE(s.result.content,t)}}:s)}:e;return nP.set(e,{texts:t,out:r}),r}var Aa=1024*1024;function wE(e){return e.reduce((t,n)=>t+n.bytes,0)>Aa?"download":"inline"}function kE(e){let t=new Set,n=0;for(let r of[...e].sort((s,o)=>s.bytes-o.bytes)){if(n+r.bytes>Aa)break;n+=r.bytes,t.add(r)}return{inline:e.filter(r=>t.has(r)),download:e.filter(r=>!t.has(r))}}function vE(e,t){if(t.size===0)return e;let n=e.messages.map(r=>xE(r,t));return n.every((r,s)=>r===e.messages[s])?e:{...e,messages:n}}function AE(e){return e==="TIMEOUT"||e==="request_deadline"}function RE(e){let t=iP(e)?e.code:void 0;return typeof t=="string"?t:void 0}var iP=e=>typeof e=="object"&&e!==null;function oP(e){let t=e?.metadata;return!!iP(t)&&t.warm===!0}var TE=5,CE=2e3,IE=e=>new Promise(t=>setTimeout(t,e));async function EE(e,{attempts:t=TE,delayMs:n=CE,sleep:r=IE}={}){for(let s=0;s<t;s++){s>0&&await r(n);try{if(await e())return!0}catch{}}return!1}function Q4(e,t){let n=new Map,r=new Set,s=new Set,o=new Set,i=0,a=(c,p,d)=>{if(r.has(c)||n.has(c))return Promise.resolve();r.add(c);let g=i,m=(async()=>{let f=null;try{let _=await e.ensure(c,p);if(g!==i)return;s.has(_.sessionId)?f=_.sessionId:n.set(c,_)}catch{}finally{g===i&&r.delete(c)}f&&d>0&&await a(c,f,d-1)})();return o.add(m),m.finally(()=>o.delete(m)),m};return{ensure:(c,p)=>a(c,p?.excludeSessionId,1),take:(c,p,{replenish:d})=>{let g=n.get(c);return g?(n.delete(c),s.add(g.sessionId),d&&a(c,g.sessionId,1),t.fits(g,p)?g:null):null},prime:async(c,p,d)=>{try{return await e.claim(c,d),!0}catch(g){return AE(RE(g))?EE(async()=>!oP(await e.read(c,p.sessionId)),t.sleep?{sleep:t.sleep}:{}):!1}},dropBySessionId:c=>{for(let[p,d]of n)if(d.sessionId===c)return n.delete(p),s.add(c),p;return null},revalidate:async c=>{let p=n.get(c);if(!p)return!1;try{if(oP(await e.read(c,p.sessionId)))return!1}catch{return!1}return n.get(c)?.sessionId!==p.sessionId?!1:(n.delete(c),s.add(p.sessionId),!0)},held:c=>n.get(c)??null,reset:()=>{i+=1,n.clear(),r.clear(),s.clear()},settled:async()=>{for(;o.size>0;)await Promise.all([...o])}}}var ME=12e4,Ks=class extends Error{constructor(t){super(`Session history read did not settle within ${t}ms`),this.name="SessionSyncReadTimeoutError"}},OE=1e3,DE=15e3,aP=100,jE=50,LE=10;function cP(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?.(),c=await t(`${n}/session/${encodeURIComponent(e.sessionId)}/message?${i}`,{headers:a?{Authorization:`Bearer ${a}`}:void 0,...o?{signal:o}:{}});if(!c.ok)throw c.status===503?new $s(`session ${c.status}`):new P(`Session synchronization failed: ${c.status}`,{status:c.status});return{messages:await c.json(),nextCursor:c.headers.get("x-next-cursor")||void 0}}}function $E(e){return FE(cP(e))}function UE(e){return new Ra({...e,loadPage:cP(e)})}async function FE(e){let t=[],n=new Set,r;do{let i=await e({limit:aP,...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 NE={now:Date.now,setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e),setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e)},Ra=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??NE,this.livenessIntervalMs=t.livenessIntervalMs??1e4,this.verifyIntervalMs=t.verifyIntervalMs??3e4,this.readTimeoutMs=t.readTimeoutMs??ME,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 Ks;if(!r&&js(n))return;if(r||this.update({freshness:Qn(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(OE*2**this.retryAttempt,DE);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"?jE:aP,...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((c,p)=>{o=this.startTimer(()=>{let d=new Ks(this.readTimeoutMs);p(d),r.abort(d)},this.readTimeoutMs)}),a;try{a=t(r.signal)}catch(c){a=Promise.reject(c)}return Promise.race([a,i]).finally(()=>{this.cancelTimer(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),c=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<LE&&i.some(g=>g.info.role==="assistant"&&!!g.info.parentID&&!a.has(g.info.parentID));){if(c.has(p))throw new Error(`Session history cursor repeated: ${p}`);c.add(p);let g;try{g=await this.loadPage(n,r,p)}catch(m){throw 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 BE=5e3,uP=40,rQ=5*6e4,KE=16,er=new Map;function pP(e,t,n,r=Date.now()){let s=dP(e,t);for(er.delete(s),er.set(s,{envelope:n,atMs:r});er.size>KE;){let o=er.keys().next().value;if(o===void 0)break;er.delete(o)}}var lP=new Map;function dP(e,t){return`${e}/${t}`}function qE(e,t){return e.settledAtMs===null?!0:t-e.settledAtMs<=BE}function gP(e,t,n=Date.now()){if(!e||!t)return null;let r=dP(e,t),s=lP.get(r);return s?qE(s,n)?s.promise:(lP.delete(r),null):null}function mP(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 fP=Object.freeze({generation:0,session:{},threads:{},messages:{},revs:{},older:{}});function GE(e,t){let n=(e[t.thread_id]??[]).filter(s=>s.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 yP(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)!ko(p)||e.revs[p.message_id]!==void 0||(r=GE(r,p));let a={...e.threads};for(let p of t.threads)vo(p)&&(a[p.thread_id]=p);let c=t.generation>e.generation;return{...e,generation:Math.max(t.generation,e.generation),session:c?{...e.session,...t.session}:{...t.session,...e.session},threads:a,messages:r,older:s}}var WE=2e3;async function VE(e,t,n){let r=gP(e,t),s,o=r?await Promise.race([r,new Promise(i=>{s=setTimeout(i,n.snapshotWaitMs??WE,null)})]).finally(()=>clearTimeout(s)):null;return(o&&mP(o))??Er(e,t,{limit:uP,history:!0,signal:n.signal})}async function HE(e){let{projectId:t,sessionId:n,runtimeSessionId:r}=e;if(!t||!n||!r)return{envelope:null,empty:!1};if(e.sessionLog){let o=un?await Tp(un,t,n):null,i=o&&NS(yP(fP,o));return{envelope:null,empty:!!i?.empty&&i.runtimeSessionId===r&&await hP(t,n,r),log:o}}let s;try{s=await VE(t,n,{})}catch{return{envelope:null,empty:!1}}return pP(t,n,s),_P(s)!==r?{envelope:s,empty:!1}:{envelope:s,empty:await hP(t,n,r)}}async function hP(e,t,n){try{let r=await Mr(e,t);return bP({savedEmptyRoot:n,rootSessionId:n,turnRead:!0,hasEndedTurn:r.last_ended!=null,hasOpenOrQueuedTurn:r.turns.length>0})}catch{return!1}}function _P(e){return e?.available&&e.source==="mirror"&&e.complete&&e.total===0&&e.messages.length===0?e.runtime_session_id??e.opencode_session_id??null:null}function bP(e){return e.savedEmptyRoot!==null&&e.savedEmptyRoot===e.rootSessionId&&e.turnRead&&!e.hasEndedTurn&&!e.hasOpenOrQueuedTurn}function fQ(e){throw U("buildTunnelEventStreamUrl")}function yQ(e){let{url:t,token:n,method:r="GET",body:s,onEvent:o,onOpen:i,onError:a,onClose:c,signal:p}=e,d=new Map,g=null,m=!1,f="";function _(b,M){o?.(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"&&s!==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"&&s!==void 0?JSON.stringify(s):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 S=x.body.getReader(),v=new TextDecoder,C="",j="message",w=[],D=N=>{if(N===""){w.length>0&&_(j,w.join(`
|
|
98
|
+
`)),j="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"?j=K.trim()||"message":G==="data"?w.push(K):G==="id"&&!K.includes("\0")&&(f=K)},Se=N=>{let z="";!N&&C.endsWith("\r")&&(z="\r",C=C.slice(0,-1));let G=C.split(/\r\n|\n|\r/);C=(G.pop()??"")+z;for(let K of G)D(K)};for(;!m;){let{done:N,value:z}=await S.read();if(N)break;C+=v.decode(z,{stream:!0}),Se(!1)}m||(C+=v.decode(),Se(!0),c?.())}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 hQ(e,t){throw U("createTunnelEventStream")}var SP="/_kortix/viewer",qs=6e4,Qt=new Map;function zE(){Qt.clear(),tr.clear()}async function YE(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 PP(e={}){let t=e.path??SP,n=e.fetch??((o,i)=>fetch(o,i)),r=Qt.get(t);if(r&&!r.inflight&&r.expiresAt>Date.now())return r.session;if(r?.inflight)return r.inflight;let s=YE(t,n).then(o=>{let i=o?.expires_at?Date.parse(o.expires_at):Number.NaN,a=Number.isFinite(i)?i-qs:Date.now()+qs;return Qt.set(t,{session:o,expiresAt:a}),o});return Qt.set(t,{session:r?.session??null,expiresAt:0,inflight:s}),s}function JE(e={}){let t=e.path??SP;return Object.assign(async()=>(await PP(e))?.access_token??null,{invalidate:n=>{let r=Qt.get(t);r&&!r.inflight&&r.session?.access_token===n&&Qt.delete(t)}})}var tr=new Map;async function QE(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 tr.set(e,{token:r.token,refreshAt:Number.isFinite(s)?s-qs:Date.now()+qs}),r.token}catch{return null}}function xP(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=tr.get(n);if(o instanceof Promise)return o;if(o&&!s.forceRefreshToken&&o.refreshAt>Date.now())return o.token;let i=QE(n,r).then(a=>(a===null&&tr.delete(n),a));return tr.set(n,i),i}}function XE(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:xP({audience:e,fetch:t.fetch})}}var wt=class extends Error{code;constructor(t,n){super(n),this.name="KortixMemberError",this.code=t}},be=e=>typeof e=="string"&&e.length>0?e:null;function wP(e){let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch{return[]}return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}function Ca(e){if(!e||typeof e!="object")return null;let t=e,n=be(t.sub)??be(t.subject)??be(t.user_id)??be(t.userId);return n?{userId:n,email:be(t.email),name:be(t.name),picture:be(t.picture)??be(t.pictureUrl),groups:wP(t.groups),groupIds:wP(t.group_ids??t.groupIds),role:be(t.role),accountId:be(t.account_id)??be(t.accountId),projectId:be(t.project_id)??be(t.projectId)}:null}function ZE(e,t={}){let n=Ca(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 eM=60,Ta=new Map;function vP(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),n=atob(t+"=".repeat((4-t.length%4)%4));return Uint8Array.from(n,r=>r.charCodeAt(0))}function kP(e){return JSON.parse(new TextDecoder().decode(vP(e)))}async function tM(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=Ta.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(()=>Ta.delete(e)),Ta.set(e,n)),n}return JSON.parse(e)}async function nM(e,t={}){let n=b=>{throw new wt("unauthenticated",`Kortix sign-in token refused: ${b}.`)},r=t.jwks??et("KORTIX_AUTH_JWKS"),s=t.issuer??et("KORTIX_AUTH_ISSUER"),o=t.audience??et("KORTIX_AUTH_AUDIENCE");if(!r)return n("no key set configured (KORTIX_AUTH_JWKS)");if(o!==!1&&!o)return n("no audience configured (KORTIX_AUTH_AUDIENCE, or `audience: false` to accept any App)");let i=typeof e=="string"?e.split("."):[];if(i.length!==3)return n("malformed");let[a,c,p]=i,d,g;try{d=kP(a),g=kP(c)}catch{return n("malformed")}if(d.alg!=="ES256")return n("unsupported algorithm");let m;try{m=await tM(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}.${c}`),y;try{y=vP(p)}catch{return n("malformed")}let k=!1;for(let b of f)try{let{kid:M,alg:h,use:x,key_ops:S,...v}=b,C=await crypto.subtle.importKey("jwk",v,{name:"ECDSA",namedCurve:"P-256"},!1,["verify"]);if(await crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},C,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+eM<R)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 I=Ca(g);return I||n("no subject")}function AP(e){let t=e.agents.map(rM),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 rM(e){return{name:e.name,description:e.description??void 0,mode:e.mode??void 0,source:e.source,hidden:e.enabled===!1}}function RP(e,t){if(!Array.isArray(e))return[];let n=t?.includeSubagents===!0;return e.filter(r=>ti(n?{...r,mode:null}:r))}function sM(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=RP(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 oM=AP;function TP(e){return e.providerID==="kortix"||e.providerID==="opencode"?e.modelID:`${e.providerID}/${e.modelID}`}function Ia(e){return{providerID:"kortix",modelID:e}}function Ea(e,t){let n=e.startsWith("kortix/")?e.slice(7):e;if(!t){let r=n.indexOf("/");if(r>0&&r<n.length-1)return{providerID:n.slice(0,r),modelID:n.slice(r+1)}}return Ia(n)}var Ma=[{id:"poolside",env:["POOLSIDE_API_KEY"]},{id:"klokintegration",env:["KLOKINTEGRATION_API_KEY"]},{id:"pioneer",env:["PIONEER_API_KEY"]},{id:"above",env:["ABOVE_API_KEY"]},{id:"ambient",env:["AMBIENT_API_KEY"]},{id:"xiaomi-token-plan-cn",env:["XIAOMI_API_KEY"]},{id:"alibaba-token-plan-cn",env:["ALIBABA_TOKEN_PLAN_API_KEY"]},{id:"standardcompute",env:["STANDARDCOMPUTE_API_KEY"]},{id:"zai-coding-plan",env:["ZHIPU_API_KEY"]},{id:"aki-io",env:["AKI_IO_API_KEY"]},{id:"opper",env:["OPPER_API_KEY"]},{id:"evroc",env:["EVROC_API_KEY"]},{id:"amazon-bedrock",env:["AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_REGION","AWS_BEARER_TOKEN_BEDROCK"]},{id:"modal",env:["MODAL_PROXY_TOKEN"]},{id:"stepfun-ai-step-plan",env:["STEPFUN_API_KEY"]},{id:"aiand",env:["AIAND_API_KEY"]},{id:"greenpt",env:["GREENPT_API_KEY"]},{id:"digitalocean",env:["DIGITALOCEAN_ACCESS_TOKEN"]},{id:"google",env:["GOOGLE_API_KEY","GOOGLE_GENERATIVE_AI_API_KEY","GEMINI_API_KEY"]},{id:"llmgateway-providers",env:["LLMGATEWAY_API_KEY"]},{id:"nvidia",env:["NVIDIA_API_KEY"]},{id:"tencent-tokenhub",env:["TENCENT_TOKENHUB_API_KEY"]},{id:"tensorx",env:["TENSORX_API_KEY"]},{id:"prime",env:["PRIME_API_KEY"]},{id:"moonshotai-cn",env:["MOONSHOT_API_KEY"]},{id:"inferx",env:["INFERX_API_KEY"]},{id:"fireworks-ai",env:["FIREWORKS_API_KEY"]},{id:"ofox",env:["OFOX_API_KEY"]},{id:"modelscope",env:["MODELSCOPE_API_KEY"]},{id:"mistral",env:["MISTRAL_API_KEY"]},{id:"nebius",env:["NEBIUS_API_KEY"]},{id:"helicone",env:["HELICONE_API_KEY"]},{id:"longcat",env:["LONGCAT_API_KEY"]},{id:"deepinfra",env:["DEEPINFRA_API_KEY"]},{id:"watsonx",env:["WATSONX_AI_APIKEY","WATSONX_AI_PROJECT_ID"]},{id:"kenari",env:["KENARI_API_KEY"]},{id:"stepfun-ai",env:["STEPFUN_API_KEY"]},{id:"nova",env:["NOVA_API_KEY"]},{id:"minimax-cn-coding-plan",env:["MINIMAX_API_KEY"]},{id:"ai21",env:["AI21_API_KEY"]},{id:"dinference",env:["DINFERENCE_API_KEY"]},{id:"pendra",env:["PENDRA_API_KEY"]},{id:"lowrouter",env:["LOWROUTER_API_KEY"]},{id:"unorouter",env:["UNOROUTER_API_KEY"]},{id:"auriko",env:["AURIKO_API_KEY"]},{id:"opencode",env:["OPENCODE_API_KEY"]},{id:"huggingface",env:["HF_TOKEN"]},{id:"togetherai",env:["TOGETHER_API_KEY"]},{id:"volcengine",env:["ARK_API_KEY"]},{id:"azure",env:["AZURE_RESOURCE_NAME","AZURE_API_KEY"]},{id:"engy",env:["ENGY_API_KEY"]},{id:"llmtr",env:["LLMTR_API_KEY"]},{id:"daoxe",env:["DAOXE_API_KEY"]},{id:"poe",env:["POE_API_KEY"]},{id:"perplexity",env:["PERPLEXITY_API_KEY"]},{id:"kimi-code-plan-cn",env:["KIMI_API_KEY"]},{id:"kosmik",env:["KOSMIK_API_KEY"]},{id:"claudinio",env:["CLAUDINIO_API_KEY"]},{id:"qvac",env:["QVAC_API_KEY"]},{id:"ainetcafe",env:["AINETCAFE_API_KEY"]},{id:"alibaba-token-plan",env:["ALIBABA_TOKEN_PLAN_API_KEY"]},{id:"vancine",env:["VANCINE_API_KEY"]},{id:"ebcloud",env:["EBCLOUD_API_KEY"]},{id:"neon",env:["NEON_AI_GATEWAY_BASE_URL","NEON_AI_GATEWAY_TOKEN"]},{id:"boundless",env:["BOUNDLESS_API_KEY"]},{id:"hpc-ai",env:["HPC_AI_API_KEY"]},{id:"zhipuai",env:["ZHIPU_API_KEY"]},{id:"wafer.ai",env:["WAFER_API_KEY"]},{id:"cloudflare-workers-ai",env:["CLOUDFLARE_ACCOUNT_ID","CLOUDFLARE_API_KEY"]},{id:"friendli",env:["FRIENDLI_TOKEN"]},{id:"minimax",env:["MINIMAX_API_KEY"]},{id:"siliconflow-cn",env:["SILICONFLOW_CN_API_KEY"]},{id:"jiekou",env:["JIEKOU_API_KEY"]},{id:"lynkr",env:["LYNKR_API_KEY"]},{id:"trustedrouter",env:["TRUSTEDROUTER_API_KEY"]},{id:"wandb",env:["WANDB_API_KEY"]},{id:"kilo",env:["KILO_API_KEY"]},{id:"drun",env:["DRUN_API_KEY"]},{id:"crusoe",env:["CRUSOE_API_KEY"]},{id:"inceptron",env:["INCEPTRON_API_KEY"]},{id:"kimi-code-plan-global",env:["KIMI_API_KEY"]},{id:"jalapeno",env:["JALAPENO_API_KEY"]},{id:"clarifai",env:["CLARIFAI_PAT"]},{id:"openrouter",env:["OPENROUTER_API_KEY"]},{id:"scaleway",env:["SCALEWAY_API_KEY"]},{id:"llmtech",env:["LLMTECH_API_KEY"]},{id:"routing-run",env:["ROUTING_RUN_API_KEY"]},{id:"salad-cloud",env:["SALAD_CLOUD_API_KEY"]},{id:"hyper",env:["HYPER_API_KEY"]},{id:"model-oracle-ai",env:["MODEL_ORACLE_API_KEY"]},{id:"nan",env:["NAN_API_KEY"]},{id:"alibaba",env:["DASHSCOPE_API_KEY"]},{id:"xai",env:["XAI_API_KEY"]},{id:"moark",env:["MOARK_API_KEY"]},{id:"minimax-cn",env:["MINIMAX_API_KEY"]},{id:"zenmux",env:["ZENMUX_API_KEY"]},{id:"tokenrouter",env:["TOKENROUTER_API_KEY"]},{id:"modelis",env:["MODELIS_API_KEY"]},{id:"regolo-ai",env:["REGOLO_API_KEY"]},{id:"vivgrid",env:["VIVGRID_API_KEY"]},{id:"vispark",env:["VISPARK_LAB_API_KEY"]},{id:"crof",env:["CROF_API_KEY"]},{id:"bothub",env:["BOTHUB_API_KEY"]},{id:"reflection",env:["REFLECTION_API_KEY"]},{id:"arcee",env:["ARCEE_API_KEY"]},{id:"cloudflare-ai-gateway",env:["CLOUDFLARE_API_TOKEN","CLOUDFLARE_ACCOUNT_ID","CLOUDFLARE_GATEWAY_ID"]},{id:"cortecs",env:["CORTECS_API_KEY"]},{id:"github-copilot",env:["GITHUB_TOKEN"]},{id:"kuae-cloud-coding-plan",env:["KUAE_API_KEY"]},{id:"xiaomi-token-plan-ams",env:["XIAOMI_API_KEY"]},{id:"vultr",env:["VULTR_API_KEY"]},{id:"aixy",env:["AIXY_API_KEY"]},{id:"sensenova",env:["SENSENOVA_API_KEY"]},{id:"tencent-token-plan",env:["TENCENT_TOKEN_PLAN_API_KEY"]},{id:"lucidquery",env:["LUCIDQUERY_API_KEY"]},{id:"scx-ai",env:["SCX_API_KEY"]},{id:"commandcode",env:["CMD_API_KEY"]},{id:"amd",env:["AMD_API_KEY"]},{id:"submodel",env:["SUBMODEL_INSTAGEN_ACCESS_KEY"]},{id:"merge-gateway",env:["MERGE_GATEWAY_API_KEY"]},{id:"google-vertex-anthropic",env:["GOOGLE_VERTEX_PROJECT","GOOGLE_VERTEX_LOCATION","GOOGLE_APPLICATION_CREDENTIALS"]},{id:"agnes",env:["AGNES_API_KEY"]},{id:"upstage",env:["UPSTAGE_API_KEY"]},{id:"inference",env:["INFERENCE_API_KEY"]},{id:"crossmodel",env:["CROSSMODEL_API_KEY"]},{id:"zeldoc",env:["ZELDOC_API_KEY"]},{id:"requesty",env:["REQUESTY_API_KEY"]},{id:"stackit",env:["STACKIT_API_KEY"]},{id:"tempr",env:["TEMPR_API_KEY"]},{id:"xiaomi",env:["XIAOMI_API_KEY"]},{id:"302ai",env:["302AI_API_KEY"]},{id:"oci",env:["OCI_GENAI_API_KEY"]},{id:"volcengine-coding-plan",env:["ARK_CODING_PLAN_API_KEY"]},{id:"zenifra",env:["ZENIFRA_AI_KEY"]},{id:"abliteration-ai",env:["ABLIT_KEY"]},{id:"tencent-coding-plan",env:["TENCENT_CODING_PLAN_API_KEY"]},{id:"freemodel",env:["FREEMODEL_API_KEY"]},{id:"tinfoil",env:["TINFOIL_API_KEY"]},{id:"berget",env:["BERGET_API_KEY"]},{id:"synthetic",env:["SYNTHETIC_API_KEY"]},{id:"ai-router",env:["AI_ROUTER_API_KEY"]},{id:"tokengo",env:["TOKENGO_API_KEY"]},{id:"novita-ai",env:["NOVITA_API_KEY"]},{id:"impossibl",env:["IMPOSSIBL_API_KEY"]},{id:"meganova",env:["MEGANOVA_API_KEY"]},{id:"moonshotai",env:["MOONSHOT_API_KEY"]},{id:"empiriolabs",env:["EMPIRIOLABS_API_KEY"]},{id:"blueclaw",env:["BLUECLAW_API_KEY"]},{id:"fastrouter",env:["FASTROUTER_API_KEY"]},{id:"deepseek",env:["DEEPSEEK_API_KEY"]},{id:"perplexity-agent",env:["PERPLEXITY_API_KEY"]},{id:"ollama-cloud",env:["OLLAMA_API_KEY"]},{id:"infer",env:["INFER_API_KEY"]},{id:"databricks",env:["DATABRICKS_HOST","DATABRICKS_TOKEN"]},{id:"iflowcn",env:["IFLOW_API_KEY"]},{id:"anyapi",env:["ANYAPI_API_KEY"]},{id:"groq",env:["GROQ_API_KEY"]},{id:"gitlab",env:["GITLAB_TOKEN"]},{id:"sakana",env:["SAKANA_API_KEY"]},{id:"hetzner",env:["HETZNER_API_KEY"]},{id:"qihang-ai",env:["QIHANG_API_KEY"]},{id:"frogbot",env:["FROGBOT_API_KEY"]},{id:"alibaba-cn",env:["DASHSCOPE_API_KEY"]},{id:"azure-cognitive-services",env:["AZURE_COGNITIVE_SERVICES_RESOURCE_NAME","AZURE_COGNITIVE_SERVICES_API_KEY"]},{id:"sambanova",env:["SAMBANOVA_API_KEY"]},{id:"subconscious",env:["SUBCONSCIOUS_API_KEY"]},{id:"io-net",env:["IOINTELLIGENCE_API_KEY"]},{id:"melious",env:["MELIOUS_API_KEY"]},{id:"sarvam",env:["SARVAM_API_KEY"]},{id:"minimax-coding-plan",env:["MINIMAX_API_KEY"]},{id:"aimlapi",env:["AIMLAPI_API_KEY"]},{id:"echo",env:["ECHO_API_KEY"]},{id:"edenai",env:["EDENAI_API_KEY"]},{id:"inception",env:["INCEPTION_API_KEY"]},{id:"meta",env:["META_MODEL_API_KEY"]},{id:"bailing",env:["BAILING_API_TOKEN"]},{id:"runinfra",env:["RUNINFRA_GATEWAY_KEY"]},{id:"umans-ai-coding-plan",env:["UMANS_AI_CODING_PLAN_API_KEY"]},{id:"agentrouter",env:["AGENTROUTER_API_KEY"]},{id:"anthropic",env:["ANTHROPIC_API_KEY"]},{id:"privatemode-ai",env:["PRIVATEMODE_API_KEY","PRIVATEMODE_ENDPOINT"]},{id:"mixlayer",env:["MIXLAYER_API_KEY"]},{id:"opencode-go",env:["OPENCODE_API_KEY"]},{id:"nano-gpt",env:["NANO_GPT_API_KEY"]},{id:"neuralwatt",env:["NEURALWATT_API_KEY"]},{id:"alibaba-coding-plan",env:["ALIBABA_CODING_PLAN_API_KEY"]},{id:"xpersona",env:["XPERSONA_API_KEY"]},{id:"wallaby",env:["WALLABY_API_KEY"]},{id:"aihubmix",env:["AIHUBMIX_API_KEY"]},{id:"zai",env:["ZHIPU_API_KEY"]},{id:"cerebras",env:["CEREBRAS_API_KEY"]},{id:"coralbricks",env:["CORAL_API_KEY"]},{id:"sap-ai-core",env:["AICORE_SERVICE_KEY"]},{id:"stepfun",env:["STEPFUN_API_KEY"]},{id:"zhipuai-coding-plan",env:["ZHIPU_API_KEY"]},{id:"lmstudio",env:["LMSTUDIO_API_KEY"]},{id:"google-vertex",env:["GOOGLE_VERTEX_PROJECT","GOOGLE_VERTEX_LOCATION","GOOGLE_APPLICATION_CREDENTIALS"]},{id:"bee",env:["BEE_API_KEY"]},{id:"gmicloud",env:["GMICLOUD_API_KEY"]},{id:"qiniu-ai",env:["QINIU_API_KEY"]},{id:"siliconflow",env:["SILICONFLOW_API_KEY"]},{id:"llmgateway",env:["LLMGATEWAY_API_KEY"]},{id:"xiaomi-token-plan-sgp",env:["XIAOMI_API_KEY"]},{id:"alibaba-coding-plan-cn",env:["ALIBABA_CODING_PLAN_API_KEY"]},{id:"abacus",env:["ABACUS_API_KEY"]},{id:"cloudferro-sherlock",env:["CLOUDFERRO_SHERLOCK_API_KEY"]},{id:"cline-pass",env:["CLINE_API_KEY"]},{id:"stepfun-step-plan",env:["STEPFUN_API_KEY"]},{id:"venice",env:["VENICE_API_KEY"]},{id:"thinkingmachines",env:["TINKER_API_KEY"]},{id:"infomaniak",env:["INFOMANIAK_API_KEY","INFOMANIAK_PRODUCT_ID"]},{id:"iteracompute",env:["ITERACOMPUTE_API_KEY"]},{id:"openai",env:["OPENAI_API_KEY"]},{id:"scnet-token-plan",env:["SCNET_API_KEY"]},{id:"the-grid-ai",env:["THEGRID_API_KEY"]},{id:"orcarouter",env:["ORCAROUTER_API_KEY"]},{id:"llama",env:["LLAMA_API_KEY"]},{id:"chutes",env:["CHUTES_API_KEY"]},{id:"pareto",env:["PARETO_API_KEY"]},{id:"inco",env:["INCO_API_KEY"]},{id:"neosmith",env:["NEOSMITH_API_KEY"]},{id:"morph",env:["MORPH_API_KEY"]},{id:"lilac",env:["LILAC_API_KEY"]},{id:"atomic-chat",env:["ATOMIC_CHAT_API_KEY"]},{id:"baseten",env:["BASETEN_API_KEY"]},{id:"nearai",env:["NEARAI_API_KEY"]},{id:"umans-ai",env:["UMANS_AI_API_KEY"]},{id:"cohere",env:["COHERE_API_KEY"]},{id:"vercel",env:["AI_GATEWAY_API_KEY"]},{id:"snowflake-cortex",env:["SNOWFLAKE_ACCOUNT","SNOWFLAKE_CORTEX_PAT"]},{id:"openreason",env:["OPENREASON_API_KEY"]},{id:"ovhcloud",env:["OVHCLOUD_API_KEY"]}];function Oa(e){if(!e.released)return null;let t=new Date(e.released).getTime();return Number.isNaN(t)?null:t}function aM(e){if(e.provider)return e.provider;let t=e.id.indexOf("/");return t===-1?"kortix":e.id.slice(0,t)}function CP(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 fe(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 IP(e){return e.reduce((t,n)=>{let r=Oa(n)??0,s=Oa(t)??0;return r!==s?r>s?n:t:fe(n.id)>fe(t.id)?n:t})}function Da(e,t){let n=(t?.now??new Date).getTime(),r=(t?.windowMonths??6)*2630016e3,s=new Set;for(let[,o]of CP(e,aM)){let a=[...CP(o,p=>p.family||p.id).values()].map(IP),c=a.filter(p=>{let d=Oa(p);return d!==null&&Math.abs(n-d)<r});for(let p of c.length>0?c:[IP(a)])s.add(p.id)}return s}function Gs(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=>fe(r.id)>0)?n.filter(r=>fe(r.id)>0):n}function nr(e){let t;for(let n of Gs(e)){if(!t){t=n;continue}let r=(n.released??"").localeCompare(t.released??"");(r>0||r===0&&fe(n.id)>fe(t.id))&&(t=n)}return t}var cM={"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 MP(e){return`${e.toUpperCase().replace(/[^A-Z0-9]+/g,"_")}_API_KEY`}var lM=(()=>{let e=new Map;for(let{id:n,env:r}of Ma)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=>MP(o)===n)??s[0])}return t})();function OP(e){let t=cM[e.id];if(t)return t;let n=e.env??[],r=n.length===1?lM.get(n[0]):void 0;return r&&r!==e.id?{methods:[{envVars:[MP(e.id)]}]}:{methods:n.length>0?[{envVars:n}]:[]}}function ja(e,t){return e.methods.some(n=>n.envVars.length>0&&n.envVars.every(t))}var uM=["low","medium","high"];function DP(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:[...uM]}: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 jP=Ma;var EP={allow_fallbacks:!0,zdr:!0,data_collection:"deny"};var Ws=[{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"],...EP,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"],...EP,max_price:{prompt:.15,completion:.5}}}],IQ=new Map(Ws.map(e=>[e.id,e]));var LP=Ws.map(e=>e.id),$P=(Ws.find(e=>e.tier==="flagship")??Ws[0]).id;var FP=jP.map(e=>({id:e.id,authRequirement:OP(e)})),rr=new Set(["kortix"]),La=new Set(["kortix"]);function Xt(e){let t=Array.isArray(e.all)?e.all:[],n=Array.isArray(e.connected)?e.connected:[];if(t.length>0||n.length>0)return{...e,all:t,connected:n};let r=e.providers,s=Array.isArray(r)?r:[];return s.length===0?{...e,all:[],connected:[]}:{...e,all:s,connected:s.map(o=>o.id)}}function pM(e){if(!e)return!1;let t=Xt(e),n=Array.isArray(t.all)?t.all:[],r=Array.isArray(t.connected)?t.connected:[];return r.length===0?!1:n.some(s=>r.includes(s.id)&&s.models&&Object.keys(s.models).length>0)}function dM(e){let t=Xt(e),n=Array.isArray(t.all)?t.all:[],r=Array.isArray(t.connected)?t.connected:[];return{...t,all:n.filter(s=>!La.has(s.id)),connected:r.filter(s=>!La.has(s))}}function gM(e,t,n){let r=Xt(e),s=Array.isArray(r.all)?r.all:[],o=new Set(s.map(a=>a.id)),i=new Set(Array.isArray(r.connected)?r.connected:[]);for(let a of n)o.has(a.id)&&ja(a.authRequirement,c=>t.has(c))&&i.add(a.id);return o.has("codex")&&(t.has("CODEX_AUTH_JSON")||t.has("OPENCODE_AUTH_JSON"))&&i.add("codex"),{...r,connected:[...i]}}var mM=new Map(["anthropic","openai","google","x-ai","xai","deepseek","mistral","groq","perplexity","openrouter"].map((e,t)=>[e,t]));function fM(e){let t=e.reasoning_options??[],n=t.find(r=>r.type==="effort");return n?(n.values??[]).flatMap(r=>r===null?["none"]:typeof r=="string"?[r]:[]):t.some(r=>r.type==="budget_tokens")?["high","max"]:[]}var $a="opencode";function yM(e){return e.cost?.input===0&&e.cost?.output===0}function UP(e){return e===$a?Number.MAX_SAFE_INTEGER:mM.get(e)??Number.MAX_SAFE_INTEGER-1}function hM(e,t){let n=bM(t),r={},s=(e.providers??[]).map(o=>{let i=(o.models??[]).filter(a=>a.status!=="deprecated");return o.id===$a&&!n.has($a)?{...o,models:i.filter(yM),keyless:!0}:{...o,models:i,keyless:!1}}).filter(o=>(o.keyless||n.has(o.id))&&!La.has(o.id)&&(o.models?.length??0)>0).sort((o,i)=>UP(o.id)-UP(i.id)).map(o=>{let i=[...o.models].sort((c,p)=>(p.released??"").localeCompare(c.released??"")||fe(p.id)-fe(c.id)),a=nr(i)?.id??i[0]?.id;return a&&(r[o.id]=a),{id:o.id,name:o.name,source:o.keyless?"api":"env",models:Object.fromEntries(i.map(c=>{let p=fM(c);return[c.id,{id:c.id,name:c.name,...c.released?{release_date:c.released}:{},...c.family?{family:c.family}:{},...c.reasoning!==void 0?{reasoning:c.reasoning}:{},...c.reasoning_options?{reasoning_options:c.reasoning_options}:{},...c.tool_call!==void 0?{tool_call:c.tool_call}:{},...c.attachment!==void 0?{attachment:c.attachment}:{},...c.modalities?{modalities:c.modalities}:{},...c.limit?{limit:c.limit}:{},...c.cost?{cost:c.cost}:{},...c.description?{description:c.description}:{},...c.open_weights!==void 0?{open_weights:c.open_weights}:{},...c.last_updated?{last_updated:c.last_updated}:{},...p.length>0?{variants:Object.fromEntries(p.map(d=>[d,{}]))}:{}}]}))}});return{all:s,connected:s.map(o=>o.id),default:r}}function _M(e,t){if(!e)return t;if(!t)return e;let n=Xt(e),r=Xt(t),s=new Map;for(let d of Array.isArray(r.all)?r.all:[])s.set(d.id,d);let o=[],i=new Set;for(let d of Array.isArray(n.all)?n.all:[])o.push(s.get(d.id)??d),i.add(d.id);for(let d of Array.isArray(r.all)?r.all:[])i.has(d.id)||(o.push(d),i.add(d.id));let a=[],c=new Set;for(let d of[...Array.isArray(n.connected)?n.connected:[],...Array.isArray(r.connected)?r.connected:[]])c.has(d)||(a.push(d),c.add(d));let p={...r.default??{}};for(let[d,g]of Object.entries(n.default??{})){let m=s.get(d);(!m||m.models&&g in m.models)&&(p[d]=g)}return{...r,all:o,connected:a,default:p}}function bM(e){let t=new Set;for(let n of FP)ja(n.authRequirement,r=>e.has(r))&&t.add(n.id);return(e.has("CODEX_AUTH_JSON")||e.has("OPENCODE_AUTH_JSON"))&&t.add("codex"),t}function SM(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=DP({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 PM(e,t){return dM(gM(Xt(e),t,FP))}function xM(e){if(e.gatewayEnabled)return e.modelPicker?SM(e.modelPicker):void 0;let t=e.secretNames??new Set,n=e.runtimeProviders?PM(e.runtimeProviders,t):void 0;return _M(e.llmCatalogProviders?hM(e.llmCatalogProviders,t):void 0,pM(n)?n:void 0)}function wM(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}function kM(e,t){if(!e)return[];let n=t?.providerMode??"gateway",r=Array.isArray(e.all)?e.all:[],s=Array.isArray(e.connected)?e.connected:[],o=[];for(let i of r)if(s.includes(i.id)&&!(n==="gateway"?!rr.has(i.id):rr.has(i.id)))for(let[a,c]of Object.entries(i.models)){if(a==="auto"||a==="kortix/auto")continue;let p;if(wM(c)){let d=c.capabilities;p={reasoning:d.reasoning??!1,vision:d.input?d.input.image??!1:void 0,toolcall:d.toolcall??!1}}else{let d=c.modalities?.input;p={reasoning:c.reasoning??!1,vision:d?d.includes("image"):c.attachment,toolcall:c.tool_call??!1}}o.push({id:TP({providerID:i.id,modelID:a}),providerID:i.id,providerName:c.provider_name??i.name,modelID:a,modelName:(c.name||a).replace("(latest)","").trim(),variants:c.variants,capabilities:p,contextWindow:c.limit?.context,releaseDate:c.release_date,family:c.family,cost:c.cost?{input:c.cost.input??0,output:c.cost.output??0}:void 0,providerSource:i.source,provider:c.provider,reasoningOptions:c.reasoning_options,description:c.description,openWeights:c.open_weights,lastUpdated:c.last_updated,enabled:c.enabled,free:c.free===!0})}return o}function NP(e){return new Map(e.map(t=>[`${t.providerID}:${t.modelID}`,t]))}var vM=new Set([$P]),AM="kortix",BP="codex",RM=new Set(LP);function TM(e,t){if(t)return t;let n=e.indexOf("/");return n===-1?e:e.slice(0,n)}function Zt(e){return vM.has(e.modelID)}function CM(e){return Da(e.map(t=>({id:`${t.providerID}:${t.modelID}`,released:t.releaseDate,family:t.family,provider:t.provider??t.providerID})))}function IM(e){let{connectedProviderIds:t}=e,n=e.freeTier??!1,r=CM(e.catalogModels),s=NP(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}`,c=o.get(a);if(c==="hide")return!1;if(i.providerID===AM){let d=TM(i.modelID,i.provider),g=d===BP?t?.has(BP)??!1:t?.has(d)??!1;if(RM.has(i.modelID))return!n;if(!g)return!1;if(c==="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(c==="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 EM(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 KP(e,t){if(!e||rr.has(e.providerID)||fe(e.modelID)>0)return e;let n=t.filter(i=>i.providerID===e.providerID&&i.enabled!==!1);if(!n.some(i=>fe(i.modelID)>0))return e;let r=i=>fe(i)===1&&i.slice(i.indexOf(".")+1)===e.modelID,o=(n.find(i=>i.modelID===`global.${e.modelID}`)??n.find(i=>r(i.modelID)))?.modelID??nr(n.map(i=>({id:i.modelID,released:i.releaseDate})))?.id;return!o||o===e.modelID?e:{...e,modelID:o}}function MM(e,t){let n=(t?e?.agentDefaults?.[t]:void 0)??e?.projectDefault??e?.accountDefault??(e?.freeTier?void 0:e?.platformDefault);return n?Ia(n):void 0}function OM(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 DM=new Set(["explicit","repointed"]);function jM(e){let t=e.session?Lr(e.session):null,n=t?Ea(t,e.gatewayEnabled):void 0;return(DM.has(String(e.session?.metadata?.opencode_model_source))?[n,e.lastPromptModel]:[e.lastPromptModel,n]).filter(o=>!!o)}function LM(e){let{models:t,providers:n}=e,r=c=>Ua(t,c),s=c=>c.find(p=>!!p&&r(p)),o=(()=>{if(e.configModel){let c=e.configModel.split("/");if(c.length>=2){let[p,...d]=c,g=d.join("/");if(r({providerID:p,modelID:g}))return{providerID:p,modelID:g}}}for(let c of e.recent??[])if(r(c))return c;if(n){let c=n.default||{},p=Array.isArray(n.all)?n.all:[],d=Array.isArray(n.connected)?n.connected:[],g=p.filter(m=>d.includes(m.id));for(let m of g){let f=c[m.id];if(f){let _={providerID:m.id,modelID:f};if(r(_))return _}for(let _ of Gs(Object.keys(m.models).map(y=>({id:y})))){let y={providerID:m.id,modelID:_.id};if(r(y))return y}}}})(),i=s(e.picks??[]),a=i??s([e.serverDefault,e.globalDefault,e.agentModel,o]);return{model:KP(a,t),explicit:i,fallback:o}}export{MC as ABORT_REASONS,dz as ABORT_REASONS_NOT_YET_EMITTED,Za as ACCOUNTS_LIST_UNAVAILABLE_CODE,Ls as ACTIVE_INSTANCE_COOKIE,Xa as ANALYTICS_UNAVAILABLE_CODE,ZC as ATTACHMENT_PART_REF_PREFIX,P as ApiError,ie as AuthError,lt as BillingError,p1 as CAPTURE_DEVICE_DEFAULTS,a1 as CAPTURE_EXCLUSION_GROUPS,l1 as CAPTURE_FRAME_INTERVALS_MS,i1 as CAPTURE_LAYERS,u1 as CAPTURE_MAX_HEIGHTS,c1 as CAPTURE_RETENTION_LIMITS,pI as CONNECTION_FAULT_GRACE_MS,YC as CONNECTOR_POLL_FIRST_DELAY_MS,JC as CONNECTOR_POLL_INTERVAL_MS,QC as CONNECTOR_POLL_WINDOW_MS,pR as CONTEXT_TOOLS,tS as COST_MARKUP,_o as ConnectorApprovalPendingError,Pr as ConnectorCallError,bo as ConnectorPageLimitError,dR as DEFAULT_CONTEXT_TOOL_TRIGGER_LABELS,dN as DEFAULT_NOTIFICATION_PREFERENCES,W_ as DEFAULT_TRANSCRIPT_OPTIONS,WC as DESTRUCTIVE_PHASES,Qs as FEATURE_DISABLED_CODE,AO as FEATURE_FLAG_KEYS,za as FEATURE_NOT_SUPPORTED_CODE,Pt as FILE_VERBS,Cn as FileExistsError,yn as HeadlessAuthError,Us as HostBoundaryError,nx as IMPERSONATION_HEADER,pN as INBOX_NOTIFICATION_KINDS,ga as INBOX_OBSERVATION_MAX_MS,Q2 as INITIAL_SETTLED_CONNECTION,OC as INSTANCE_SCOPED_ROUTES,Zx as KNOWN_TOOL_KINDS,Ce as KORTIX_TRANSCRIPT_SCHEMA,wt as KortixMemberError,Fx as MAX_PROMPT_ATTACHMENTS_BYTES,Po as MAX_PROMPT_ATTACHMENT_BYTES,Gu as MAX_PROMPT_ATTACHMENT_FILES,GH as MEMORY_VERBS,Ya as MODEL_NOT_SERVABLE_CODE,kk as NO_GROUP_ACTIVITY_TOOLS,ma as OPTIMISTIC_ABORT_MAX_MS,SJ as OPTIMISTIC_COMPACTION_MAX_MS,pa as OPTIMISTIC_RECEIPT_MAX_MS,b2 as PERSISTED_QUERY_CACHE_VERSION,IT as PLUMBING_TOOLS,F2 as PREVIEW_PROBE_TIMEOUT_MS,Z as PROJECT_ACTIONS,Kj as PROJECT_SESSION_NAME_LOOKUP_LIMIT,Bj as PROJECT_SESSION_PAGE_DEFAULT_LIMIT,_w as PROJECT_SESSION_PAGE_MAX_LIMIT,Ja as PROVISION_IN_FLIGHT_CODE,wx as PROVISION_STREAM_UNTERMINATED_CODE,Oo as PublicSessionShareError,R$ as REVIEW_CONTROL_ACTIONS,vz as RUNTIME_NOT_READY_MARKERS,SN as RUNTIME_PERMISSION_CAPABILITIES,bN as RUNTIME_PERMISSION_REPLIES,kt as RequestTooLargeError,kn as RuntimeNotReadyError,Ii as SANDBOX_FS_ROOTS,tt as SANDBOX_PORTS,Qa as SANDBOX_STATE_CHANGE_IN_PROGRESS_CODE,_I as SERVER_COMPACTION_REVALIDATE_MS,da as SERVER_OBSERVATION_MAX_MS,OJ as SESSION_LIST_STATUS,Aa as SESSION_LOG_FULL_TEXT_INLINE_MAX_BYTES,Pe as SESSION_LOG_MINOR,le as SESSION_LOG_SCHEMA,LJ as SESSION_NOTICE,vk as STANDALONE_TOOLS,Xn as STREAM_OBSERVATION_MAX_MS,$s as SandboxNotReadyError,Nt as SessionNotReadyError,Ro as SessionStartError,v$ as TRIGGER_CONTROL_ACTIONS,lJ as TURN_END_LEDGER_LAG_MS,Jw as TURN_ERROR_CODES,RJ as WAKE_ESCALATION_COOLDOWN_MS,AJ as WAKE_MAX_RESTARTS,vJ as WAKE_NO_PROGRESS_MS,bi as WIRE_ID_BACKDATE_MS,yt as WIRE_ID_CLOCK_TOLERANCE,rt as WIRE_ID_TIME_MASK,Pn as WIRE_ID_TIME_SCALE,Vk as WIRE_MESSAGE_ID,UM as __getConfigResolver,$M as __setConfigResolver,gz as abortErrorReason,oo as acceptAccountInvite,wc as acceptAccountInviteAndLand,ig as acceptEnterpriseOffer,rY as acceptInvite,xx as accountInviteLanding,Cm as actReviewItem,Jl as activateConnection,Zl as addComputerToProject,tm as addGroupMembers,df as addMarketplaceSource,CJ as advanceWakeEscalation,HR as allDescendantIds,AS as appendPreviewToken,D_ as approveCaptureDeviceGrant,x_ as approveCaptureEnrollment,nl as approveProjectAccessRequest,_K as approveTask,br as archiveProject,AK as assignTicket,dl as attachGroupToProject,gi as authMfa,ui as authUser,L as authenticatedFetch,wr as authenticatedRequest,$2 as authorizePreviewUrl,l as backendApi,QL as bindSlackIdentity,XL as bindTeamsIdentity,kl as brokerProjectSecretRequest,x2 as browserKeyValueStorage,jC as buildInstancePath,G2 as buildPresentationTemplateImageUrl,q2 as buildPresentationTemplatePdfUrl,vS as buildPreviewAuthEndpoint,s2 as buildPublicTemplateUrl,uI as buildRuntimePresentationConversionUrl,Lu as buildSandboxTemplate,nT as buildScrapeFailureResults,lG as buildStaticFileHealthPreviewUrl,cG as buildStaticFileLocalUrl,aG as buildStaticFilePreviewUrl,dA as buildStaticFileServicePath,fQ as buildTunnelEventStreamUrl,mG as buildWebProxyUrl,Im as bulkActReviewItems,Q$ as bulkDeletePolicies,X$ as bulkImportPolicies,ta as burstSummary,DT as burstSummaryLabel,Lb as burstWorkLabel,It as callConnector,Aw as canManageBilling,OL as canOfferTopup,PU as cancelAccountDeletion,bc as cancelAccountInvite,Wz as cancelSandbox,xY as cancelSandboxUpdate,Zd as cancelScheduledChange,Jd as cancelSubscription,h1 as captureHealthBucket,Fw as changeRequestControlsFrom,NY as checkAccessEmail,MD as checkMcpServerSignIn,KW as childMapByParent,CY as claimComputer,CA as claimNext,UL as claimPerSeatBilling,Kp as claimWarmProjectSession,Sb as classifyPart,cI as classifyPreviewProbeStatus,Zk as classifyPtyClose,dE as classifySessionLogMessage,Wi as classifyTurn,rV as cleanErrorMessage,lV as cleanResultSnippet,jH as cleanWorkerOutput,tc as clearImpersonationSession,zE as clearKortixAppViewerCache,Md as clearModelDefault,yj as clearSessionFresh,cp as closeChangeRequest,eq as closeMilestone,zW as collectTurnParts,TK as commentTicket,pp as commitSessionChanges,xJ as compactionExpiryAtMs,$V as compactionTurnInfo,zi as compareForDisplayAt,BW as compareMessagesForDisplay,w1 as compareSemver,IA as completeInFlight,hg as completeSlackInstall,_g as completeTeamsInstall,RP as composerSelectableAgents,Xb as computeStatusFromPart,rg as configureAutoTopup,zs as configureKortix,zd as confirmCheckoutSession,vg as connectEmail,mg as connectSlack,n$ as connectTelegram,J2 as connectionFromHealth,Y2 as connectionIsFaulted,_D as connectionSharedWithEveryone,Ox as connectorConnect,Dx as connectorFinalize,u2 as connectorHeadline,ag as contactEnterpriseSales,kV as contextLabelForTool,nW as contextToolSummary,rW as contextToolTrigger,$U as convertPresentationToGoogleSlides,W2 as convertRuntimePresentation,gs as copyFile,lg as costExportUrl,pJ as countLiveInboxPrompts,S$ as countReviewItemsBySegment,cc as createAccount,ef as createAccountAuditWebhook,Ol as createAccountSecretResource,qm as createAccountToken,ff as createApp,wf as createAppAccessSession,vf as createAppDeployment,_f as createAppToken,Bf as createAppVolume,Wf as createAppVolumeSnapshot,vV as createArtifactKind,Pm as createAssignment,J0 as createAuditWebhook,aY as createBackup,b_ as createCaptureEnrollmentToken,Hd as createCheckoutSession,gu as createConnector,a2 as createConnectorLinkInfoCache,ds as createFile,qg as createGatewayKey,Qg as createGroup,UE as createHttpSessionSyncController,AY as createInstance,vA as createKortix,ih as createKortixPty,fi as createKortixSession,mF as createMarketplaceInstallSession,XK as createMilestone,IM as createModelVisibility,ym as createOAuthClient,$L as createPerSeatCheckout,P2 as createPersistedQueryCache,z$ as createPolicy,Yd as createPortalSession,Dc as createProject,UK as createProjectAgent,zm as createProjectCliToken,jc as createProjectRepo,yl as createProjectResourceGrant,jt as createProjectSession,Bc as createProjectSkill,pd as createProjectTrigger,o_ as createPromptAttachmentController,cm as createRole,yQ as createSSEStream,Uz as createSandbox,Mm as createSandboxShare,Ou as createSandboxTemplate,Aj as createSavedCopyStore,c0 as createScimToken,K0 as createServiceAccountApi,Or as createSessionPrompt,Fp as createSessionPublicShare,RA as createSessionQueue,$m as createSessionReminder,R0 as createSsoGroupMapping,fK as createTask,wK as createTicket,hQ as createTunnelEventStream,Q4 as createWarmSessionPool,Ap as currentSavedCopyStore,kc as declineAccountInvite,sY as declineInvite,xU as deleteAccountImmediately,Ll as deleteAccountSecretResource,hf as deleteApp,Ef as deleteAppDeployment,X0 as deleteAuditWebhook,lY as deleteBackup,hu as deleteConnector,wu as deleteConnectorCredential,aq as deleteCredential,VF as deleteDriveFile,sh as deleteEnv,Gt as deleteFile,Bg as deleteGatewayBudget,Xc as deleteGitHubInstallation,Zg as deleteGroup,RY as deleteInstance,HK as deleteKortixProject,nq as deleteMilestone,bm as deleteOAuthClient,Il as deletePersonalProjectSecret,J$ as deletePolicy,NK as deleteProjectAgent,Al as deleteProjectProviderOAuth,hl as deleteProjectResourceGrant,Tl as deleteProjectSecret,Zp as deleteProjectSession,gd as deleteProjectTrigger,cn as deletePromptAttachment,pm as deleteRole,ju as deleteSandboxTemplate,G0 as deleteServiceAccountApi,Hp as deleteSessionPrompt,jo as deleteSessionReminder,Nm as deleteSessionReminders,T0 as deleteSsoGroupMapping,v0 as deleteSsoProvider,bK as deleteTask,CK as deleteTicket,j_ as denyCaptureDeviceGrant,w_ as denyCaptureEnrollment,xc as describeAccountInvite,go as describeConnectorTool,$f as destroyAppMachine,qf as destroyAppVolume,ml as detachGroupFromProject,cA as detectLocalhostUrls,FJ as directSubsessions,q0 as disableServiceAccountApi,Ag as disconnectEmail,h2 as disconnectGitHubApp,Sg as disconnectSlack,s$ as disconnectTelegram,xD as discoverConnectionOAuth2,wD as discoverConnectionOAuth2Resource,mu as discoverConnectorAuth,Kz as discoverLocalSandbox,FF as dismissDriveConflict,n2 as downloadAccountAudit,BF as downloadDriveFile,Pq as dropClientForUrl,kq as dropPublicClientForUrl,DA as editQueued,zp as editSessionPrompt,TA as enqueue,LK as ensurePmSession,aI as ensurePreviewSessionCookie,bD as ensureProjectConnectorConnection,GC as ensureSandbox,Bp as ensureWarmProjectSession,Qk as env,ai as exchangeCode,Ff as execInApp,Xm as exportAccountAudit,xe as extractGatewayErrorDetails,Yn as extractInstanceRoute,sC as extractSkillBaseDir,sz as extractSkillContent,tC as extractSkillFiles,$H as extractWorkerPreview,EA as failInFlight,iH as fallbackBusyRowAfterTurnId,Wn as familyForTool,Ka as featureDisabledKey,Ty as featureFlags,DL as fetchAccountStateWithToken,PO as fetchAccountsWithToken,A2 as fetchAttachmentPart,HL as fetchCostExportCsv,PP as fetchKortixAppViewer,Ku as fetchProjectArchive,nj as fetchProjectFileRaw,jO as fetchProjectsForAccountWithToken,Ay as fetchSessionAttachment,Dv as fileDownloadRequest,BH as filePhase,NH as fileVerb,Hv as files,Fo as finalizeAppArtifact,HY as finalizeConnectorSetupLink,Gj as findActiveTranscriptShare,us as findFiles,YW as findLastTextPart,BN as findSessionAttachments,ps as findText,yd as fireProjectTrigger,Mu as fixSandboxWithAgent,kM as flattenModels,WV as flattenThought,Hf as forkAppVolume,Ga as formatBillingErrorForUI,PH as formatCost,eS as formatDuration,sV as formatJsonFailureOutput,zV as formatMessageDay,YV as formatMessageExact,Rz as formatOpenCodeRuntimeError,cV as formatRawOutput,qC as formatRuntimeError,xH as formatTokens,BA as formatTranscript,uH as freshSendHint,AA as generateSessionId,lc as getAccount,Qj as getAccountAutomations,pc as getAccountBranding,bU as getAccountDeletionStatus,Nd as getAccountState,Bd as getAccountStateMinimal,$C as getActiveInstanceIdFromCookie,IU as getAdminProviderAnalytics,RU as getAdminProviderDistribution,MU as getAdminProviderFallback,wU as getAdminRole,SR as getAgentCardLabel,vL as getAgentConfig,BK as getAgentPersona,bY as getAllVersions,QW as getAnsweredQuestionParts,$o as getApp,Sf as getAppAccess,bf as getAppAuthEnv,Rf as getAppDeployment,Tf as getAppDeploymentLogs,uF as getApprovalLink,rn as getAuthToken,pD as getAuthTokenWithRetry,ng as getAutoTopupSettings,LL as getAutoTopupSetupStatus,Gd as getBillingCreditBreakdown,Vd as getBillingTierConfigurations,qd as getBillingTransactionsSummary,Wd as getBillingUsageHistory,M_ as getCaptureAssetUrl,E_ as getCaptureChunkMedia,T_ as getCaptureDays,O_ as getCaptureDeviceGrant,I_ as getCaptureFrame,k_ as getCapturePolicy,A_ as getCaptureTimeline,R_ as getCaptureTimelineItems,L_ as getCaptureWorkspace,rp as getChangeRequest,sp as getChangeRequestDiff,op as getChangeRequestMergePreview,bW as getChildSessionError,vs as getChildSessionId,SW as getChildSessionToolParts,ht as getClient,Ve as getClientForUrl,Pu as getConnectStatus,PD as getConnectionOAuth2Application,TD as getConnectionOAuth2Status,CD as getConnectionPolicies,sn as getConnectorCatalog,uu as getConnectorConfig,cu as getConnectorPolicies,WY as getConnectorSetupLink,VL as getCostSummary,LC as getCurrentInstanceIdFromPathname,hz as getCurrentInstanceIdFromWindow,jh as getCurrentProject,$d as getDefaultAccountState,wW as getDiagnostics,bR as getDirectory,ho as getDiscoverConnector,LD as getDiscoverIntegration,zf as getDriveFileUrl,wg as getEmailInstallation,kg as getEmailMode,iU as getEnterpriseDemo,ls as getFileStatus,db as getFileWithDir,_R as getFilename,DF as getFolderAccess,VC as getFullChangelog,Lg as getGatewayBreakdown,Fg as getGatewayBudgets,Ug as getGatewayErrors,Kg as getGatewayKeys,Og as getGatewayLog,Dg as getGatewayOverview,Tg as getGatewayRoutingPolicy,jg as getGatewaySeries,$g as getGatewaySessions,g2 as getGitHubAppStatus,Gc as getGitHubInstallation,LU as getGoogleAuthUrl,Jg as getGroup,hW as getHiddenToolParts,ox as getImpersonationSession,nY as getInvite,vY as getJustavpsServerTypes,GK as getKortixProject,WK as getKortixProjectBySession,lh as getKortixPtyWebSocketUrl,_Y as getLatestSandboxVersion,XY as getMaintenanceConfig,Zc as getManagedGitBackend,EO as getManagedGitStatus,lf as getMarketplaceCatalogItem,uf as getMarketplaceCatalogItemFile,g0 as getMfaRequired,JK as getMilestone,K_ as getMobileClientPolicy,Id as getModelDefaults,N_ as getMyCaptureFrame,F_ as getMyCaptureTimeline,ey as getNotificationPreferences,fm as getOAuthClient,qY as getOAuthConsentRequest,wz as getOpenCodeConfigInvalidError,mW as getPartText,L0 as getPatPolicy,kW as getPermissionForTool,Tt as getProject,KK as getProjectActivity,Xu as getProjectCommit,Zu as getProjectCommitDiff,fr as getProjectDetail,OF as getProjectDrive,ep as getProjectFileHistory,Oc as getProjectGitToken,yr as getProjectLlmCatalog,TO as getProjectLlmCatalogProviders,Vr as getProjectModelAccess,hr as getProjectModelPicker,IO as getProjectQuota,xr as getProjectSandboxHealth,MO as getProjectSandboxProviderTransition,Ir as getProjectSession,nd as getProjectSessionConfigState,od as getProjectSessionScope,eg as getProrationPreview,Lz as getProviders,uG as getProxyBaseUrl,wq as getPublicClientForUrl,UY as getPublicMarketplaceItem,FY as getPublicMarketplaceItemFile,VU as getPublicSessionShare,HU as getPublicSessionShareMessages,JY as getPublicShareByToken,o2 as getPublicTemplate,vW as getQuestionForTool,g$ as getReferralCode,y$ as getReferralStats,wH as getRetryInfo,kH as getRetryMessage,Rm as getReviewItem,Am as getReviewSummary,im as getRolePermissions,am as getRoleUsage,aa as getRuntimeConfigInvalidError,dY as getSSHConnection,$z as getSandbox,Fz as getSandboxById,Ez as getSandboxPortUrl,IY as getSandboxProvisionStatus,EY as getSandboxProvisionStreamUrl,hY as getSandboxUpdateStatus,hS as getSandboxUrl,Fe as getSandboxUrlForExternalId,zY as getSecretSetupLink,Ei as getServerHealth,uq as getServiceLogs,qp as getSessionAudit,SH as getSessionCost,Kr as getSessionCostRecord,Hw as getSessionDrives,Kh as getSessionHealth,Wp as getSessionLogPage,cd as getSessionMessageAuthors,ld as getSessionModelUsage,Wj as getSessionOpenBundle,y0 as getSessionOversight,Mp as getSessionParticipants,M0 as getSessionPolicy,$p as getSessionPreviewCandidates,Nl as getSessionProviderSecretPool,Gp as getSessionTranscript,Er as getSessionTranscriptSync,Mr as getSessionTurn,Op as getSessionWatch,MH as getShellModePart,Pg as getSlackChannelFile,gg as getSlackInstallation,bg as getSlackManifest,fg as getSlackMode,P0 as getSsoProvider,gA as getStaticFileHealthPath,lo as getSupabaseAccessToken,Tx as getSupabaseAccessTokenWithRetry,dK as getTask,mK as getTaskStatus,t$ as getTelegramInstallation,hF as getTemplate,PK as getTicket,PW as getToolInfo,Ki as getToolPrimaryArg,KA as getTranscriptFilename,sa as getTurnCost,hH as getTurnError,bH as getTurnErrorDetails,_H as getTurnErrorRawText,Zb as getTurnStatus,cg as getUsageRollup,e2 as getUserRolesWithToken,tp as getVersionDiff,ny as getWebPushPublicKey,fH as getWorkingState,$l as grantAccountSecretResource,Xz as grantSandboxProjectAccess,RL as grantSecretToAgent,HW as groupMessagesIntoTurns,Hb as groupShowSegments,Ub as groupSteps,vH as hasDiffs,iG as hasLocalhostUrls,pA as hasPreviewTarget,Ab as hasRetryingAssistantTurn,xv as heartbeatGapEvent,Qp as holdSessionPrompts,zg as humanizeReviewActionPath,xs as humanizeSearchQuery,hb as humanizeToolName,nc as impersonationHeaders,w0 as importSsoProviderFromMetadata,uJ as inboxObservationSupersedes,ES as initialWakeEscalationState,Ie as inputPath,_F as installTemplate,Yp as interruptSessionPrompt,uo as invalidateTokenCache,hc as inviteAccountMember,al as inviteProjectMember,Ec as inviteRepoCollaborator,js as isAbortError,lx as isAdminBypassEnabled,lW as isAgentPart,oA as isAppRouteUrl,fW as isAttachment,eI as isAttachmentPartRef,en as isAuthFailure,qa as isBillingError,uW as isCompactionPart,Ys as isConfigured,tW as isContextTool,yY as isDestructivePhase,bP as isEmptyConversation,Jo as isEmptyShowPart,nV as isErrorOutput,hG as isExternalUrl,Ba as isFeatureDisabledError,gb as isFilePart,rx as isImpersonationSessionLive,fz as isInstanceDetailPath,DC as isInstanceScopedAppPath,gG as isInternalLocalhostUrl,wy as isInvisibleActivityPart,JO as isInviteSent,mH as isLastUserMessage,xI as isLegacyMigratedSession,RO as isManagedGithubProject,xy as isNoGroupActivityTool,Ua as isOfferedModel,kz as isOpenCodeConfigInvalidError,aw as isPaintableSavedCopy,dW as isPatchPart,S2 as isPersistableQueryKey,dG as isPreviewUrl,mA as isProxiableLocalhostUrl,Py as isQuestionTool,we as isReasoningPart,JR as isRetryableTurnError,UC as isRuntimeConfigInvalidError,BC as isRuntimeNotReadyResponse,Bh as isRuntimeReady,Az as isRuntimeStartingError,Qn as isSandboxNotReadyError,ti as isSelectableAgent,Lh as isServerReachable,NN as isSessionAttachmentRef,gp as isSessionFresh,yE as isSessionLogRestoreNote,aL as isSessionStartError,EN as isShellActivityTool,ZT as isShellMode,LH as isShortOutput,hN as isShowContentUnavailable,zr as isShowPayloadEmpty,pW as isSnapshotPart,ky as isStandaloneActivityTool,gW as isStepPart,Fs as isSubdomainPreviewUrl,Je as isTextPart,te as isToolPart,_W as isToolPartHidden,iy as isTurnErrorCode,vh as isUnderSandboxRoot,yG as isWebProxyUrl,zk as isWireIdAheadOf,JE as kortixAppViewerToken,XE as kortixBinding,rv as kortixPty,xP as kortixToken,OM as latestPromptModel,Rc as leaveAccount,h_ as linkCaptureDevice,Jc as linkGitHubInstallation,Kc as linkRepository,Jm as listAccountAudit,Zm as listAccountAuditWebhooks,_c as listAccountInvites,yc as listAccountMembers,K$ as listAccountResourceGrants,Ml as listAccountSecretResources,D0 as listAccountSessions,Km as listAccountTokens,ac as listAccounts,n0 as listActions,TU as listAdminSandboxes,sm as listAgentIdentities,Wl as listAllConnections,Pf as listAppAgents,Af as listAppDeployments,Of as listAppMachines,Gf as listAppVolumeSnapshots,Nf as listAppVolumes,mf as listApps,Sm as listAssignments,Z0 as listAuditEvents,Y0 as listAuditWebhooks,iY as listBackups,Kd as listBillingTransactions,f_ as listCaptureDevices,__ as listCaptureEnrollmentTokens,P_ as listCaptureEnrollments,np as listChangeRequests,o$ as listChannelBindings,IK as listColumns,DD as listConnectSections,OD as listConnectToolkits,Gl as listConnections,mo as listConnectorAccounts,fu as listConnectorMoves,po as listConnectorTools,ru as listConnectors,WL as listCostByProject,sq as listCredentialEvents,rq as listCredentials,yo as listDiscoverConnectors,jD as listDiscoverIntegrations,Su as listDiscoverSections,UF as listDriveConflicts,NF as listDriveFiles,Gw as listDriveFolder,HF as listDriveVersions,nh as listEnv,cf as listFeaturedMarketplaces,MK as listFields,Mn as listFiles,$F as listFolderPrincipals,Mg as listGatewayLogs,Wc as listGitHubInstallations,Hc as listGitHubRepositories,zc as listGitHubRepositoryBranches,em as listGroupMembers,j$ as listGroupProjectGrants,Yg as listGroups,VK as listKortixProjectSessions,qK as listKortixProjects,oh as listKortixPty,Vc as listLinkableGitHubInstallations,el as listManagedGitRepositories,of as listMarketplaceCatalogItems,pf as listMarketplaceSources,af as listMarketplaces,L$ as listMemberGroups,$$ as listMemberProjectAccess,QK as listMilestoneEvents,YK as listMilestones,Pc as listMyAccountInvites,Xf as listNotifications,mm as listOAuthClients,Wm as listOAuthGrants,_l as listPendingApprovals,cl as listPendingProjectInvites,wm as listPermissions,_u as listPipedreamApps,bu as listPipedreamSections,H$ as listPolicies,sl as listProjectAccess,tl as listProjectAccessRequests,om as listProjectAgentIdentities,$K as listProjectAgents,Qm as listProjectAudit,Ju as listProjectBranches,Hm as listProjectCliTokens,Qu as listProjectCommits,Fu as listProjectDirectory,Uu as listProjectFiles,pl as listProjectGroupGrants,Ru as listProjectPolicies,vl as listProjectProviderOAuth,Bm as listProjectReminders,fl as listProjectResourceGrants,Cu as listProjectSandboxTemplates,$u as listProjectSandboxes,Pl as listProjectSecrets,Dt as listProjectSessions,Ip as listProjectSessionsPage,Iu as listProjectSnapshots,Pd as listProjectTriggerEventApps,Sd as listProjectTriggerEventTypes,_d as listProjectTriggerRuns,ud as listProjectTriggers,Rt as listProjects,Ic as listProjectsForAccount,LY as listPublicMarketplaceItems,$Y as listPublicMarketplaces,h$ as listReferrals,vm as listReviewItems,rm as listRoles,Qz as listSandboxProjectMembers,Em as listSandboxShares,Bz as listSandboxes,a0 as listScimTokens,B0 as listServiceAccountsApi,lq as listServiceTemplates,cq as listServices,ED as listSessionConnectRequests,ug as listSessionCosts,YF as listSessionDrives,Vp as listSessionPrompts,Bl as listSessionProviderSecretPools,Up as listSessionPublicShares,Lm as listSessionReminders,bl as listSessionsNeedingInput,eF as listSignedInDevices,A0 as listSsoGroupMappings,gK as listTaskEvents,pK as listTasks,DK as listTemplates,xK as listTicketEvents,SK as listTickets,hd as listTriggerRuns,$E as loadHttpSessionHistory,mt as loadPreviewUrlTemplate,Tb as looksLikeError,yV as looksLikeHtml,aV as looksLikeJsonPayload,GF as makeDriveFolder,x$ as mapApiReviewItem,TY as markInstanceError,Zf as markNotificationsRead,Tr as markSessionFresh,Qy as maxWireIdClock,WH as memoryRelPath,Fb as mergeBurstSteps,ap as mergeChangeRequest,HV as messageCreatedAt,FT as messageTime,EU as migrateAdminSandboxProvider,Si as mintWireMessageId,Zy as mintWireMessageIdAbove,Ln as mkdir,EM as modelInDefaultView,Ea as modelRefToKey,yu as moveConnector,WF as moveDriveFile,jb as narrateFailedStep,Ms as narrateStep,Es as narrationToolName,wv as narrowChatEvent,Yk as newestWireIdClock,l2 as nextConnectorPollDelay,he as normalizeActivityToolName,Sz as normalizeAppPathname,g1 as normalizeCaptureAppId,d1 as normalizeCaptureDomain,_G as normalizeExternalInput,ee as normalizeName,yb as normalizeToolName,vI as notifyHostSignal,ip as openChangeRequest,vi as openEventStream,r2 as openStressTestStream,Au as paginateConnector,ar as parseBillingError,uV as parseEmbeddedFailure,WN as parseFlagOverride,Cb as parseJsonFailure,hs as parseLocalhostUrl,VH as parseMemoryView,xz as parseOpenCodeErrorPayload,QH as parsePresentationOutput,Nh as parseProxyHop,uS as parseQuestionAnswersFromOutput,tz as parseReadOutput,yS as parseRuntimeErrorPayload,tT as parseScrapeInputUrls,rT as parseScrapeOutput,Qh as parseSubdomainUrl,UH as parseTaskRows,fG as parseWebProxyUrl,Eb as parseWebSearchOutput,Ji as partOutcome,zK as patchKortixProject,YH as patchVerb,xM as pickerProviderList,du as pipedreamConnect,tu as pipedreamConnectConnection,ku as pipedreamFinalize,nu as pipedreamFinalizeConnection,T as platformConfig,RD as pollConnectionOAuth2DeviceAuthorization,ao as pollProjectProviderOAuth,sg as previewBillingPlan,Eg as previewGatewayRoute,m0 as previewMfaRequired,ZL as previewSlackIdentity,e$ as previewTeamsIdentity,dm as probeEffectivePermission,gm as probeEffectivePermissions,N2 as probePreviewPort,qu as projectArchiveRequest,PJ as projectCompacting,oM as projectConfigAgentsToOpenCodeAgents,AP as projectConfigAgentsToRuntimeAgents,z2 as projectSessionConnection,NJ as projectSessionForRuntimeId,Ad as projectSessionStartSeed,gJ as projectWorking,Lc as provisionProject,CO as provisionProjectStream,LO as provisionProjectWithToken,Yh as proxyLocalhostUrl,pG as proxyUrlToInternal,tg as purchaseCredits,SD as putConnectionOAuth2Application,Ps as rawErrorText,Vz as reactivateSandbox,Qd as reactivateSubscription,Dn as readBlob,KF as readDriveFile,On as readFile,Ca as readKortixMember,Bu as readProjectFile,HE as readSavedSessionCopy,na as reasoningIsRunning,Eu as rebuildProjectSnapshot,Vl as reconcileConnection,Hl as reconcileMemberConnection,dq as reconcileServices,KY as recordPlatformLogout,Qi as recoverLinkResults,ed as recoverProjectSession,m$ as refreshReferralCode,hn as refreshSession,Uo as registerAppArtifact,kD as registerConnectionOAuth2Client,Yf as registerDeviceToken,gq as registerService,ry as registerWebPushSubscription,rl as rejectProjectAccessRequest,xW as relativizePath,Qf as releaseDeviceToken,rd as reloadProjectSessionConfig,sd as reloadProjectSessionConfigStream,nf as removeAccountAuditWebhook,mc as removeAccountBrandingAsset,vc as removeAccountMember,nm as removeGroupMember,ch as removeKortixPty,gf as removeMarketplaceSource,OA as removeQueued,Xl as renameConnection,fs as renameFile,Nz as renameSandbox,lp as reopenChangeRequest,tq as reopenMilestone,jA as reorderQueued,EK as replaceColumns,OK as replaceFields,qc as replaceProjectRepository,jK as replaceTemplates,bd as replayTriggerRun,SU as requestAccountDeletion,up as requestChangesOnChangeRequest,YO as requestProjectAccess,sf as requestProjectConnector,rf as requestProjectSecret,jL as requestTopUp,ZE as requireKortixMember,Sc as resendAccountInvite,ul as resendPendingProjectInvite,fc as resetAccountBranding,xq as resetClient,Ig as resetGatewayRoutingPolicy,ci as resetPassword,vq as resetPublicClient,PY as resetSandboxUpdateStatus,Sl as resolveApproval,sM as resolveComposerAgent,LM as resolveComposerModel,c2 as resolveConnectorStart,MM as resolveModelDefault,qj as resolvePublicShareUrl,hV as resolveScrapeResults,Qb as resolveWorkingTurn,ML as resolvedPlan,Lf as restartAppMachine,Dr as restartProjectSession,qz as restartSandbox,Vf as restoreAppVolume,cY as restoreBackup,zF as restoreDriveVersion,td as restoreProjectSession,jl as retryAccountSecretResource,MA as retryFailed,Jp as retrySessionPrompt,iq as revealCredential,Hg as reviewItemTarget,Cw as reviewSegmentForStatus,T$ as reviewVerdictAllowed,P$ as reviewVerdictForStatus,Ul as revokeAccountSecretResourceGrant,j0 as revokeAccountSession,Gm as revokeAccountToken,xm as revokeAssignment,y_ as revokeCaptureDevice,S_ as revokeCaptureEnrollmentToken,Yl as revokeConnection,Gg as revokeGatewayKey,Vm as revokeOAuthGrant,ll as revokePendingProjectInvite,il as revokeProjectAccess,Ym as revokeProjectCliToken,Zz as revokeSandboxProjectAccess,Om as revokeSandboxShare,l0 as revokeScimToken,Np as revokeSessionPublicShare,bt as rewriteLocalhostUrl,Mf as rollbackApp,wI as rootRuntimeSession,Dl as rotateAccountSecretResource,_m as rotateOAuthClientSecret,So as runConnector,Wg as runGatewayPlayground,eD as runProjectProviderOAuthFlow,ya as runtimeSessionsOf,Yv as runtimeSupports,nv as sanitizePtyChunk,Yc as saveGitHubInstallation,_P as savedCopyEmptyRoot,Uf as scaleApp,Xd as scheduleDowngrade,C_ as searchCapture,ql as searchConnectorTools,U_ as searchMyCapture,Nu as searchProjectFiles,Wb as segmentTurn,zN as selectableProjectAgents,si as sendMagicLink,_$ as sendReferralEmails,wJ as serverCompactionRevalidateAtMs,pq as serviceAction,jJ as sessionConnectionLabel,DJ as sessionListStatus,sE as sessionLogActivityText,pE as sessionLogAnsweredQuestionCall,aE as sessionLogBurstRunning,rE as sessionLogBurstSteps,oE as sessionLogBurstSummary,iE as sessionLogBurstWorkLabel,$I as sessionLogCallStatus,wE as sessionLogFullTextAction,kE as sessionLogFullTextPlan,hE as sessionLogHarnessSwitches,OI as sessionLogOfV1Rows,cE as sessionLogOpenCall,UI as sessionLogPromptMessage,SE as sessionLogReferencedTexts,bE as sessionLogRestoreNotice,XS as sessionLogRetrying,uE as sessionLogShowGroupCall,mE as sessionLogThreadMetrics,ZI as sessionLogTurnSegments,wa as sessionLogTurns,vE as sessionLogWithFullTexts,jM as sessionModelCandidates,Lr as sessionModelPin,Nj as sessionParentId,Hj as sessionPromptActions,cL as sessionStartKey,Xj as setAccountAutomationsPaused,Fl as setAccountSecretResourceAccess,_z as setActiveInstanceCookie,cx as setAdminBypass,CU as setAdminProviderDistribution,OU as setAdminProviderFallback,Dd as setAgentScope,og as setBillingPlan,uD as setBootstrapAuthToken,lD as setCachedAuthToken,$_ as setCaptureEnabled,v_ as setCapturePolicy,ID as setConnectionPolicies,iu as setConnectorAuthorizationStrategy,xu as setConnectorCredential,ou as setConnectorCredentialMode,pu as setConnectorName,lu as setConnectorPolicies,$D as setConnectorSecretBinding,au as setConnectorSensitive,Ql as setDefaultConnection,aU as setEnterpriseDemo,rh as setEnv,Ng as setGatewayBudget,Cg as setGatewayRoutingPolicy,f2 as setGitHubAppFromExisting,y2 as setGitHubAppPat,zM as setImpersonationSession,ZY as setMaintenanceConfig,r0 as setMemberSuperAdmin,f0 as setMfaRequired,Ed as setModelDefault,Cl as setPersonalProjectSecret,Hr as setProjectModelAccess,fL as setProjectModelEnablement,Nc as setProjectOnboardingComplete,DO as setProjectOnboardingProfile,Tu as setProjectPolicies,wl as setProjectSecretStrategy,ad as setProjectSessionModel,id as setProjectSessionScope,Ep as setProjectSessionSharing,md as setProjectTriggersActivation,Rj as setSavedCopyStore,Lp as setSessionArchived,h0 as setSessionOversight,jp as setSessionPinned,Kl as setSessionProviderSecretPool,Dp as setSessionWatch,r$ as setTelegramAllowedUsers,X2 as settleSessionConnection,pY as setupSSH,eu as shareConnection,jF as shareFolder,MN as shellActivityGroupLabel,gS as shellExitCode,ax as shouldAttachImpersonation,yH as shouldHideResponsePart,Bn as shouldShowToolPart,oH as shouldSuppressWorkingTurnBusy,zb as showGroupItems,Yb as showTurnBusyIndicator,ri as signInWithPassword,ii as signInWithProvider,di as signInWithSso,mi as signOut,tF as signOutDevice,ni as signUp,iz as skillDocumentPath,oz as skillInputDir,qW as sortSessions,tE as splitSessionLogTurnWork,aS as splitTurnWork,yW as splitUserParts,Cf as startApp,Df as startAppMachine,vD as startConnectionOAuth2Authorization,AD as startConnectionOAuth2DeviceAuthorization,VY as startConnectorSetupLink,m2 as startGitHubAppManifest,io as startProjectProviderOAuth,gt as startProjectSession,Td as startProjectSessionOrThrow,QY as startSessionWithToken,hK as startTask,Vn as stepLabel,If as stopApp,jf as stopAppMachine,jr as stopProjectSession,Gz as stopSandbox,Qc as storeGitHubUserToken,mb as stripAnsi,yz as stripInstancePrefix,ue as stripTrailingSlashes,gE as subAgentCalls,BY as submitAccessRequest,t2 as submitDemoRequest,GY as submitOAuthConsent,Tm as submitReviewItem,YY as submitSecretSetupLink,YM as subscribeToImpersonation,mO as supabaseClient,su as syncConnectors,FL as syncSubscription,Aq as systemReload,_t as toDaemonPath,bz as toInstanceAwarePath,fA as toInternalUrl,En as toSandboxAbsolutePath,bb as toToolView,Ah as toWorkspaceRelative,ns as toolCallBlock,wk as toolCallError,Sk as toolCallMetadata,xk as toolCallRawOutput,Pk as toolCallStatus,qi as toolInfo,ce as toolKind,RC as toolViewModel,A$ as triggerControlsFrom,SY as triggerSandboxUpdate,Xk as triggersRequest,yI as turnEndCause,_J as turnEndNotice,JW as turnHasSteps,aH as turnIsConfirmedActive,cH as turnRendersQueued,$J as turnRetryLabel,RK as unassignTicket,Jf as unregisterDeviceToken,sy as unregisterWebPushSubscription,LF as unshareFolder,vb as untimedAnchorOf,_e as unwrapError,tf as updateAccountAuditWebhook,dc as updateAccountBranding,Ac as updateAccountMemberRole,uc as updateAccountName,AL as updateAgentConfig,yf as updateApp,xf as updateAppAccess,Kf as updateAppVolume,Q0 as updateAuditWebhook,dp as updateChangeRequest,i$ as updateChannelBinding,zl as updateConnectionCredential,Rg as updateEmailPolicy,Uc as updateExperimentalFeature,$c as updateFeatureFlag,Xg as updateGroup,ah as updateKortixPty,ZK as updateMilestone,ty as updateNotificationPreferences,hm as updateOAuthClient,li as updatePassword,$0 as updatePatPolicy,Y$ as updatePolicy,_r as updateProject,ol as updateProjectAccess,FK as updateProjectAgent,jd as updateProjectDefaultAgent,gl as updateProjectGroupGrant,Fc as updateProjectSandboxProvider,Xp as updateProjectSession,dd as updateProjectTrigger,lm as updateRole,um as updateRolePermissions,Du as updateSandboxTemplate,O0 as updateSessionPolicy,Do as updateSessionReminder,Fm as updateSessionReminders,yK as updateTask,OO as updateTemplateWarmPool,kK as updateTicket,vK as updateTicketStatus,pi as updateUserMetadata,gc as uploadAccountBrandingAsset,kf as uploadAppArtifactArchive,fo as uploadConnectorAttachment,qF as uploadDriveFile,jn as uploadFile,Kv as uploadNativeFile,Rr as uploadPromptAttachment,vy as uploadSessionAttachment,xg as uploadSlackChannelFile,Rn as uploadTimeoutMsForBytes,oq as upsertCredential,Rl as upsertProjectGitCredential,xl as upsertProjectSecret,x0 as upsertSsoProvider,Mc as validateProjectManifest,f$ as validateReferralCode,Tc as validateToken,u$ as verifyGatewayProvider,nM as verifyKortixToken,oi as verifyOtp,k0 as verifySsoDomain,EJ as wakeEscalationAttemptSummary,IJ as wakeEscalationNote,TJ as wakeProgressFingerprint,Bt as wireIdClock,xn as wireIdClockAt,Kt as wireIdClockDelta,CH as workedForLabel,mJ as workingExpiryAtMs,lH as workingTurnDrawsBusyRow,ON as writeActivityGroupLabel,ms as writeFile,Xi as wsDomain,fV as wsFavicon,mV as wsRootDomain};
|