@kortix/sdk 0.13.54 → 0.13.56

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (114) hide show
  1. package/README.md +34 -9
  2. package/dist/browser/stores/sync-store.d.ts +20 -0
  3. package/dist/browser/stores/sync-store.d.ts.map +1 -1
  4. package/dist/browser/stores/sync-store.js +65 -23
  5. package/dist/browser/stores/sync-store.js.map +1 -1
  6. package/dist/core/auth/app-viewer.d.ts +1 -1
  7. package/dist/core/auth/app-viewer.js +1 -1
  8. package/dist/core/client/kortix.d.ts +3 -0
  9. package/dist/core/client/kortix.d.ts.map +1 -1
  10. package/dist/core/client/kortix.js +3 -0
  11. package/dist/core/client/kortix.js.map +1 -1
  12. package/dist/core/client/project-access-resources.d.ts +1 -1
  13. package/dist/core/client/project-access-resources.d.ts.map +1 -1
  14. package/dist/core/client/project-access-resources.js +1 -1
  15. package/dist/core/client/project-access-resources.js.map +1 -1
  16. package/dist/core/client/project-core.d.ts.map +1 -1
  17. package/dist/core/rest/platform-client/client-policy.d.ts +21 -0
  18. package/dist/core/rest/platform-client/client-policy.d.ts.map +1 -0
  19. package/dist/core/rest/platform-client/client-policy.js +49 -0
  20. package/dist/core/rest/platform-client/client-policy.js.map +1 -0
  21. package/dist/core/rest/platform-client/index.d.ts +1 -0
  22. package/dist/core/rest/platform-client/index.d.ts.map +1 -1
  23. package/dist/core/rest/platform-client/index.js +1 -0
  24. package/dist/core/rest/platform-client/index.js.map +1 -1
  25. package/dist/core/rest/projects-client/apps-fleet.js +1 -1
  26. package/dist/core/rest/projects-client/apps.d.ts +18 -2
  27. package/dist/core/rest/projects-client/apps.d.ts.map +1 -1
  28. package/dist/core/rest/projects-client/apps.js.map +1 -1
  29. package/dist/core/rest/projects-client/projects.d.ts +6 -1
  30. package/dist/core/rest/projects-client/projects.d.ts.map +1 -1
  31. package/dist/core/rest/projects-client/projects.js +3 -0
  32. package/dist/core/rest/projects-client/projects.js.map +1 -1
  33. package/dist/core/session/control-stream.d.ts +12 -0
  34. package/dist/core/session/control-stream.d.ts.map +1 -1
  35. package/dist/core/session/control-stream.js +22 -1
  36. package/dist/core/session/control-stream.js.map +1 -1
  37. package/dist/core/session-log/guard.d.ts +18 -0
  38. package/dist/core/session-log/guard.d.ts.map +1 -0
  39. package/dist/core/session-log/guard.js +114 -0
  40. package/dist/core/session-log/guard.js.map +1 -0
  41. package/dist/core/session-log/index.d.ts +16 -0
  42. package/dist/core/session-log/index.d.ts.map +1 -0
  43. package/dist/core/session-log/index.js +15 -0
  44. package/dist/core/session-log/index.js.map +1 -0
  45. package/dist/core/session-log/saved-log.d.ts +23 -0
  46. package/dist/core/session-log/saved-log.d.ts.map +1 -0
  47. package/dist/core/session-log/saved-log.js +34 -0
  48. package/dist/core/session-log/saved-log.js.map +1 -0
  49. package/dist/core/session-log/source.d.ts +36 -0
  50. package/dist/core/session-log/source.d.ts.map +1 -0
  51. package/dist/core/session-log/source.js +52 -0
  52. package/dist/core/session-log/source.js.map +1 -0
  53. package/dist/core/session-log/store.d.ts +25 -0
  54. package/dist/core/session-log/store.d.ts.map +1 -0
  55. package/dist/core/session-log/store.js +170 -0
  56. package/dist/core/session-log/store.js.map +1 -0
  57. package/dist/core/session-log/types.d.ts +371 -0
  58. package/dist/core/session-log/types.d.ts.map +1 -0
  59. package/dist/core/session-log/types.js +24 -0
  60. package/dist/core/session-log/types.js.map +1 -0
  61. package/dist/core/session-log/v1-view.d.ts +30 -0
  62. package/dist/core/session-log/v1-view.d.ts.map +1 -0
  63. package/dist/core/session-log/v1-view.js +106 -0
  64. package/dist/core/session-log/v1-view.js.map +1 -0
  65. package/dist/core/session-log/v1.d.ts +107 -0
  66. package/dist/core/session-log/v1.d.ts.map +1 -0
  67. package/dist/core/session-log/v1.js +495 -0
  68. package/dist/core/session-log/v1.js.map +1 -0
  69. package/dist/core/session-sync/copy-store-types.d.ts +29 -0
  70. package/dist/core/session-sync/copy-store-types.d.ts.map +1 -0
  71. package/dist/core/session-sync/copy-store-types.js +2 -0
  72. package/dist/core/session-sync/copy-store-types.js.map +1 -0
  73. package/dist/core/session-sync/saved-copy-store.d.ts +5 -0
  74. package/dist/core/session-sync/saved-copy-store.d.ts.map +1 -1
  75. package/dist/core/session-sync/saved-copy-store.js +30 -4
  76. package/dist/core/session-sync/saved-copy-store.js.map +1 -1
  77. package/dist/core/turns/segments/index.d.ts +1 -0
  78. package/dist/core/turns/segments/index.d.ts.map +1 -1
  79. package/dist/core/turns/segments/index.js +1 -0
  80. package/dist/core/turns/segments/index.js.map +1 -1
  81. package/dist/core/turns/segments/work-split.d.ts +16 -0
  82. package/dist/core/turns/segments/work-split.d.ts.map +1 -0
  83. package/dist/core/turns/segments/work-split.js +59 -0
  84. package/dist/core/turns/segments/work-split.js.map +1 -0
  85. package/dist/index.d.ts +1 -0
  86. package/dist/index.d.ts.map +1 -1
  87. package/dist/index.js +1 -0
  88. package/dist/index.js.map +1 -1
  89. package/dist/kortix.esm.min.js +33 -33
  90. package/dist/kortix.global.js +34 -34
  91. package/dist/react/opencode.d.ts +1 -0
  92. package/dist/react/opencode.d.ts.map +1 -1
  93. package/dist/react/opencode.js +2 -0
  94. package/dist/react/opencode.js.map +1 -1
  95. package/dist/react/session-transcript-subscription.d.ts +5 -1
  96. package/dist/react/session-transcript-subscription.d.ts.map +1 -1
  97. package/dist/react/session-transcript-subscription.js +8 -2
  98. package/dist/react/session-transcript-subscription.js.map +1 -1
  99. package/dist/react/sign-in-with-kortix.d.ts +1 -1
  100. package/dist/react/use-opencode-events/handle-event.d.ts +6 -0
  101. package/dist/react/use-opencode-events/handle-event.d.ts.map +1 -1
  102. package/dist/react/use-opencode-events/handle-event.js +5 -0
  103. package/dist/react/use-opencode-events/handle-event.js.map +1 -1
  104. package/dist/react/use-opencode-events/index.d.ts.map +1 -1
  105. package/dist/react/use-opencode-events/index.js +1 -0
  106. package/dist/react/use-opencode-events/index.js.map +1 -1
  107. package/dist/react/use-session-log.d.ts +52 -0
  108. package/dist/react/use-session-log.d.ts.map +1 -0
  109. package/dist/react/use-session-log.js +166 -0
  110. package/dist/react/use-session-log.js.map +1 -0
  111. package/dist/react/use-session.d.ts.map +1 -1
  112. package/dist/react/use-session.js +4 -0
  113. package/dist/react/use-session.js.map +1 -1
  114. package/package.json +2 -2
@@ -1,24 +1,24 @@
1
- var nb={backendUrl:"",getToken:async()=>null},eo=null,En=null;function Yk(e){En=e}function Qk(){return En}function to(e,t){t?.global!==!1&&(eo=e)}function k(){return En?.()??eo??nb}function no(){return eo!==null||En?.()!==void 0}function rb(e){return new Promise(t=>setTimeout(t,e))}async function Mn(e,t,n){let r=Math.max(1,t?.attempts??1),o=t?.baseDelayMs??0,s=t?.invalidateBetweenAttempts??!1,i=null;for(let a=0;a<r;a++)if(a>0&&(s&&n?.(),o>0&&await rb(o)),i=await e(),i)return i;return i}var ro=12e4;function ob(e){return(e instanceof Request?e.url:String(e)).includes("/global/event")}function _i(e,t,n=ro){let r=e instanceof Request?e.signal:t?.signal;if(ob(e))return r??void 0;let o=AbortSignal.timeout(n);return r?typeof AbortSignal.any=="function"?AbortSignal.any([r,o]):r:o}function On(){return new Response(JSON.stringify({error:"Not authenticated"}),{status:401,headers:{"Content-Type":"application/json"}})}var b=class extends Error{status;code;details;data;detail;response;url;endpoint;timeout;constructor(t,n={}){super(t),this.name="ApiError";let{name:r,stack:o,...s}=n;Object.assign(this,s),r&&(this.name=r),o&&(this.stack=o);let i=typeof t=="string"?t:t==null?"":String(t);Object.defineProperty(this,"message",{value:i,enumerable:!0,writable:!0,configurable:!0}),Object.setPrototypeOf(this,new.target.prototype)}},X=class extends b{constructor(t="Not authenticated"){super(t,{code:"NO_SESSION"}),this.name="AuthError"}},We=class extends b{constructor(t,n,r,o={}){super(r||n.message||`Billing Error: ${t}`,{...o,status:t,detail:n}),this.name="BillingError"}},ut=class extends b{constructor(t=431,n,r){let o="Request headers are too large";super(r||n?.message||o,{status:t,detail:{message:n?.message||o,suggestion:n?.suggestion||"Try uploading files one at a time, or reduce the number of files in a single request."}}),this.name="RequestTooLargeError"}},sb="ENDPOINT_RETIRED";function F(e,t){let n=t?` ${t}`:"";return new b(`${e}() is retired: the Kortix API no longer serves this endpoint.${n}`,{code:sb})}var oo="feature_disabled";function Pi(e){if(!(e instanceof b)||e.status!==403||e.code!==oo)return null;let t=e.details??e.data;return t&&typeof t=="object"?t:{}}function xi(e){let t=Pi(e);return t?(typeof t.feature=="string"&&!e.feature&&(e.feature=t.feature),!0):!1}function Si(e){let t=Pi(e);if(!t)return null;let n=e.feature;return typeof n=="string"?n:typeof t.feature=="string"?t.feature:null}function Dn(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 We(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 wi(e){return e instanceof We}function jt(e){if(e instanceof X)return!0;let t=e?.status;return t===401||t===403}function vi(e){if(!(e instanceof We))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 ge(){return typeof DOMException=="function"?new DOMException("Aborted","AbortError"):Object.assign(new Error("Aborted"),{name:"AbortError"})}function me(e,t){return new Promise((n,r)=>{let o=()=>{t.removeEventListener("abort",o),r(ge())};t.addEventListener("abort",o,{once:!0}),e.then(n,r).finally(()=>t.removeEventListener("abort",o)),t.aborted&&o()})}function jn(e,t){return new Promise((n,r)=>{let o=()=>{clearTimeout(s),t?.removeEventListener("abort",o),r(ge())},s=setTimeout(()=>{t?.removeEventListener("abort",o),n()},e);t?.aborted?o():t?.addEventListener("abort",o,{once:!0})})}var Ai="request_deadline",ib=/^Request exceeded the \d+s server processing deadline$/,ki=(e,t,n)=>e!==503?!1:(typeof t=="object"&&t!==null&&"code"in t?t.code:void 0)===Ai||ib.test(n),ab="git_mirror_unavailable",cb=/^git mirror is temporarily unavailable$/,lb=(e,t,n)=>e!==503?!1:(typeof t=="object"&&t!==null&&"code"in t?t.code:void 0)===ab||cb.test(n);async function ub(e,t){let n=`HTTP ${e.status}: ${e.statusText}`,r=null;try{r=await me(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 ge();return{message:n,data:r}}function pb(e,t,n){return ki(e,t,n)||lb(e,t,n)||e===501&&t?.code===Ii||e===409&&(t?.code===Ci||t?.code===Ti)||e===503&&(t?.code===Ei||t?.code===Mi)}async function Ri(e,t,n,r){let{message:o,data:s}=await ub(e,t),i=new b(o,{status:e.status,response:e,details:s||void 0,data:s,detail:s?.detail,code:ki(e.status,s,o)?Ai:s?.code||s?.error_code||s?.detail?.error_code||e.status.toString()});e.status===402&&(i=Dn(i));let a=e.status!==403?null:s?.code==="account_mfa_required"?"kortix:mfa-required":s?.code==="sso_required"?"kortix:sso-required":null;if(a&&typeof window<"u"&&typeof window.dispatchEvent=="function")try{window.dispatchEvent(new CustomEvent(a))}catch{}return e.status===431&&(i=new ut(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&&!pb(e.status,s,o)&&k().onError?.(i,r),{error:i,success:!1}}var db="X-Kortix-Impersonate",io="kortix.impersonation",He=null,$n=!1,so=new Set;function ao(){try{return typeof sessionStorage>"u"?null:sessionStorage}catch{return null}}function gb(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 mb(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 Oi(){for(let e of so)try{e()}catch{}}function fb(){return $n||($n=!0,He=mb(ao()?.getItem(io)??null)),He&&!gb(He)?(Di(),null):He}function iR(e){if($n=!0,!e){Di();return}He=e;try{ao()?.setItem(io,JSON.stringify(e))}catch{}Oi()}function Di(){$n=!0;let e=He!==null;He=null;try{ao()?.removeItem(io)}catch{}e&&Oi()}function aR(e){return so.add(e),()=>{so.delete(e)}}var yb=/(^|\/)admin\/(api|analytics)(\/|$)/;function hb(e){let t=e;if(/^https?:\/\//.test(e))try{t=new URL(e).pathname}catch{t=e}return!yb.test(t)}function ji(e){if(e!==void 0&&!hb(e))return{};let t=fb();return t?{[db]:t.grantId}:{}}var po=!1;function bb(e){po=e}function _b(){return po}function Pb(e){return e?e instanceof Headers||Array.isArray(e)?[...new Headers(e).entries()]:Object.entries(e):[]}function lo(e,t){let n=t.toLowerCase();return Object.keys(e).some(r=>r.toLowerCase()===n)}function $t(e,t,n){let r=t.toLowerCase();for(let o of Object.keys(e))o.toLowerCase()===r&&delete e[o];e[t]=n}function Un(e,t){let n={},r=[e instanceof Request?e.headers:void 0,t.headers];for(let[o,s]of r.flatMap(Pb))$t(n,o,s);return n}function uo(e,t,n){let r={...t},o=k().clientVersion?.trim();o&&!lo(r,"x-kortix-client-version")&&$t(r,"X-Kortix-Client-Version",o),po&&$t(r,"x-kortix-admin-bypass","1");for(let[s,i]of Object.entries(ji(e)))$t(r,s,i);return lo(r,"authorization")||$t(r,"Authorization",`Bearer ${n}`),r}async function Ln(e,t){let n=await Fn();if(!n)throw new X;return{headers:new Headers(uo(e,Un(e,{headers:t}),n)),rejected:()=>Ut(n)}}function xb(e){return typeof ReadableStream<"u"&&e.body instanceof ReadableStream}function $i(e,t,n,r,o){if(t instanceof Request){let c=new Headers(uo(t.url,Un(t,n),r));return e(new Request(t,{headers:c,...o?{signal:o}:{}}))}let s=String(t),i=uo(s,Un(t,n),r),a=s.startsWith("/")&&!s.startsWith("//");return e(s,{...n,headers:i,...a?{credentials:"same-origin"}:{},...o?{signal:o}:{}})}var Ui=null;async function go(e){let t=await Mn(()=>k().getToken(),e);return t&&(Ui=t),t}var Fn=go;function Ut(e=Ui){e&&k().getToken.invalidate?.(e)}var co=new Map;function Sb(e){let t=co.get(e);if(t)return t;let n=(async()=>(Ut(e),Fn({attempts:2,baseDelayMs:200})))().finally(()=>co.delete(e));return co.set(e,n),n}async function Ve(e,t={},n={}){let{retryOnAuthError:r=!0,timeoutMs:o=ro}=n,s=n.fetch??k().fetch??fetch,i=o===null?(e instanceof Request?e.signal:t.signal)??void 0:_i(e,t,o);if(i?.aborted)throw ge();let a=await(i?me(Fn(),i):Fn());if(!a)throw new X;let c=r&&!xb(t)&&!lo(Un(e,t),"authorization"),p=c&&e instanceof Request?e.clone():e,d=await $i(s,e,t,a,i);if(d.status!==401||!c)return d;let g=await Sb(a);return!g||g===a?d:$i(s,p,t,g,i)}async function we(e,t,n,r){let o=await Ve(e,t,n);if(o.ok)return o;let s=await o.text().catch(()=>"");throw new b(s||`${r} (HTTP ${o.status})`,{status:o.status,response:o})}var Fi=()=>k().backendUrl||"",wb=new Set([502,503,504]),vb=e=>wb.has(e),Li=e=>{let t=(e??"GET").toUpperCase();return t==="GET"||t==="HEAD"},Ab=e=>Li(e)||(e??"GET").toUpperCase()==="DELETE",kb=2,Nn=e=>e?.name==="AbortError"||e?.name==="AbortSignal"||e instanceof Error&&e.message.includes("aborted");async function ve(e,t={}){let{showErrors:n=!0,errorContext:r,timeout:o=3e4,deadlineCoversBody:s=!1,...i}=t,a=new AbortController,c={activeController:a,timeoutId:null,isAborted:!1,didTimeout:!1},p=()=>c.activeController.abort();i.signal?.addEventListener("abort",p,{once:!0});try{return await Rb(e,i,n,r,o,s,a,c)}finally{i.signal?.removeEventListener("abort",p)}}async function Rb(e,t,n,r,o,s,i,a){try{if(t.signal?.aborted)throw ge();a.timeoutId=setTimeout(()=>{!a.isAborted&&!i.signal.aborted&&(a.isAborted=!0,a.didTimeout=!0,i.abort())},o);let c={...t.body instanceof FormData?{}:{"Content-Type":"application/json"},...t.headers},p=await Cb(e,t,c,o,s,i,a);if(p instanceof X)return{error:p,success:!1};if(!p.ok)return await Ri(p,a.activeController.signal,n,r);let d,g=p.headers.get("content-type");return g?.includes("application/json")?d=await me(p.json(),a.activeController.signal):g?.includes("text/")?d=await me(p.text(),a.activeController.signal):d=await me(p.blob(),a.activeController.signal),{data:d,success:!0,headers:p.headers}}catch(c){return Tb(c,e,t.method,n,r,o,a)}finally{Kn(a)}}function Kn(e){e.timeoutId&&clearTimeout(e.timeoutId),e.timeoutId=null}async function Ib(e,t,n){try{await me(e.arrayBuffer(),t)}catch(r){if(Nn(r))throw r}finally{Kn(n)}}async function Cb(e,t,n,r,o,s,i){let a=Li(t.method),c=Ab(t.method),p=c?kb+1:1,d;for(let g=0;g<p;g++){g>0&&await jn(250*2**(g-1),t.signal??void 0);let m=g===0?s:new AbortController;i.activeController=m,t.signal?.aborted&&m.abort(),g>0&&(i.timeoutId=setTimeout(()=>{i.didTimeout=!0,m.abort()},r));try{d=await me(Ve(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 X)return new X;if(i.didTimeout&&Nn(f)&&!t.signal?.aborted&&c&&g<p-1){i.didTimeout=!1;continue}if(Nn(f)||g===p-1)throw f;continue}if(!a||!vb(d.status)||g===p-1)return o||Kn(i),d;await Ib(d,m.signal,i)}return d}function Tb(e,t,n,r,o,s,i){Kn(i);let a=Nn(e);a&&(i.isAborted=!0);let c;if(a){if(!i.didTimeout)return{error:new b("Request aborted",{name:"AbortError",code:"ABORTED"}),success:!1};let p=t.replace(Fi(),"")||t;c=new b(`Request timed out after ${Math.round(s/1e3)}s: ${p}`,{code:"TIMEOUT",url:t,endpoint:p,timeout:s})}else e instanceof Error?(c=new b(n==="POST"&&e instanceof TypeError&&e.message==="Failed to fetch"?`Failed to fetch: POST ${t.replace(Fi(),"")||t}`:e.message,{name:e.name||"ApiError",stack:e.stack}),r&&k().onError?.(c,o)):(c=new b(String(e)),r&&k().onError?.(c,o));return{error:c,success:!1}}var Ae=()=>k().backendUrl||"",Ii="feature_not_supported",Ci="model_not_servable",Ti="provision_in_flight",Ei="analytics_unavailable",Mi="accounts_list_unavailable",kR={async execute(e,t){try{let{data:n,error:r}=await e();if(r){let o=new b(r.message||"Database error",{code:r.code,details:r});return k().onError?.(o,t),{error:o,success:!1}}return{data:n,success:!0}}catch(n){let r=n instanceof Error?new b(n.message,{name:n.name||"ApiError",stack:n.stack}):new b(String(n));return k().onError?.(r,t),{error:r,success:!1}}}};async function Eb(e,t,n={}){let{timeout:r=3e4,fetch:o}=n,s=new AbortController,i=setTimeout(()=>s.abort(),r);try{return await Ve(`${Ae()}${e}`,{method:"POST",headers:{Accept:"text/event-stream","Content-Type":"application/json"},body:JSON.stringify(t),signal:s.signal,credentials:"omit"},{timeoutMs:null,fetch:o})}catch(a){if(a instanceof X)return On();throw a}finally{clearTimeout(i)}}var l={putRaw:(e,t,n)=>ve(`${Ae()}${e}`,{...n,method:"PUT",body:t,headers:{"Content-Type":"application/octet-stream",...n?.headers}}),get:(e,t)=>ve(`${Ae()}${e}`,{...t,method:"GET"}),post:(e,t,n)=>ve(`${Ae()}${e}`,{...n,method:"POST",body:t?JSON.stringify(t):void 0}),put:(e,t,n)=>ve(`${Ae()}${e}`,{...n,method:"PUT",body:t?JSON.stringify(t):void 0}),patch:(e,t,n)=>ve(`${Ae()}${e}`,{...n,method:"PATCH",body:t?JSON.stringify(t):void 0}),delete:(e,t)=>ve(`${Ae()}${e}`,{...t,method:"DELETE"}),upload:(e,t,n)=>{let{headers:r,...o}=n||{},s={...r};return delete s["Content-Type"],ve(`${Ae()}${e}`,{...o,method:"POST",body:t,headers:s})},uploadPut:(e,t,n)=>{let{headers:r,...o}=n||{},s={...r};return delete s["Content-Type"],ve(`${Ae()}${e}`,{...o,method:"PUT",body:t,headers:s})},postStream:Eb};function u(e,t="Project request failed"){if(!e.success||e.data===void 0)throw e.error??new Error(t);return e.data}function mo(e){return e.replace(/\/v1\/?$/,"")}async function pt(e,t){if(!e.backendUrl||!e.accessToken)return null;let n=mo(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 Ni(){return u(await l.get("/accounts"))}async function Ki(e){return u(await l.post("/accounts",e))}async function qi(e){return u(await l.get(`/accounts/${e}`))}async function Gi(e,t){return u(await l.patch(`/accounts/${e}`,{name:t}))}async function Bi(e){return u(await l.get(`/accounts/${e}/branding`))}async function Wi(e,t){return u(await l.put(`/accounts/${e}/branding`,t))}async function Hi(e,t,n,r){let o=new FormData;return o.append("file",n,r??(n instanceof File?n.name:t)),u(await l.upload(`/accounts/${e}/branding/assets/${t}`,o))}async function Vi(e,t){return u(await l.delete(`/accounts/${e}/branding/assets/${t}`))}async function zi(e){return u(await l.delete(`/accounts/${e}/branding`))}async function Yi(e){return u(await l.get(`/accounts/${e}/members`))}async function Qi(e,t){return u(await l.post(`/accounts/${e}/members`,t,{showErrors:!1}))}async function Xi(e){return u(await l.get(`/accounts/${e}/invites`))}async function Ji(e,t){return u(await l.delete(`/accounts/${e}/invites/${t}`))}async function Zi(e,t){return u(await l.post(`/accounts/${e}/invites/${t}/resend`,{}))}async function ea(){return u(await l.get("/account-invites",{showErrors:!1})).invites}async function ta(e){return u(await l.get(`/account-invites/${e}`,{showErrors:!1}))}async function na(e){return u(await l.post(`/account-invites/${e}/accept`,{}))}async function ra(e){return u(await l.post(`/account-invites/${e}/decline`,{}))}async function oa(e,t){return u(await l.delete(`/accounts/${e}/members/${t}`))}async function sa(e,t,n){return u(await l.patch(`/accounts/${e}/members/${t}`,{role:n}))}async function ia(e){return u(await l.post(`/accounts/${e}/leave`,{}))}async function OR(e){return pt(e,"/v1/accounts")}async function aa(){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 FR=["marketplace","connectors_api_discover","agentmail_email","llm_gateway","meta_agent","apps","monitors","reminders","warm_sessions","secrets_egress","pooled_provider_secrets","pi_harness","us_region","event_triggers","notification_center","drives","ephemeral_sandboxes"];async function dt(){return u(await l.get("/projects"))}async function la(e){let t=e?`?account_id=${encodeURIComponent(e)}`:"";return u(await l.get(`/projects${t}`))}async function qn(e,t){return u(await l.get(`/projects/${e}`,t))}async function ua(e,t,n="write"){return u(await l.post(`/projects/${e}/git/collaborators`,{github_username:t,permission:n}))}async function pa(e,t){return u(await l.post(`/projects/${e}/manifest/validate`,{raw:t}),"Failed to validate manifest")}async function da(e){return u(await l.post(`/projects/${e}/git-token`,{}),"Failed to mint git token")}function LR(e){let t=e.metadata?.git;return t?.provider==="github"&&t?.managed===!0}async function Gn(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 Bn(e,t){return u(await l.get(`/projects/${e}/llm-catalog`,{showErrors:!1,...t}))}async function Wn(e,t){return u(await l.get(`/projects/${e}/model-picker`,{showErrors:!1,...t}))}async function NR(e,t){return u(await l.get(`/projects/${e}/llm-catalog/providers`,{showErrors:!1,...t}))}async function ga(e){return u(await l.post("/projects",e))}async function ma(e){return u(await l.post("/projects/create-repo",e,{showErrors:!1}))}async function fa(e,t={}){return u(await l.post("/projects/provision",{seed_starter:!0,...e},{timeout:12e4,...t}))}var ca=200;function Mb(e){let t=e.split(`
1
+ var Ab={backendUrl:"",getToken:async()=>null},lo=null,Fn=null;function ER(e){Fn=e}function MR(){return Fn}function uo(e,t){t?.global!==!1&&(lo=e)}function v(){return Fn?.()??lo??Ab}function po(){return lo!==null||Fn?.()!==void 0}function vb(e){return new Promise(t=>setTimeout(t,e))}async function Nn(e,t,n){let r=Math.max(1,t?.attempts??1),o=t?.baseDelayMs??0,s=t?.invalidateBetweenAttempts??!1,i=null;for(let a=0;a<r;a++)if(a>0&&(s&&n?.(),o>0&&await vb(o)),i=await e(),i)return i;return i}var go=12e4;function kb(e){return(e instanceof Request?e.url:String(e)).includes("/global/event")}function Ti(e,t,n=go){let r=e instanceof Request?e.signal:t?.signal;if(kb(e))return r??void 0;let o=AbortSignal.timeout(n);return r?typeof AbortSignal.any=="function"?AbortSignal.any([r,o]):r:o}function Kn(){return new Response(JSON.stringify({error:"Not authenticated"}),{status:401,headers:{"Content-Type":"application/json"}})}var b=class extends Error{status;code;details;data;detail;response;url;endpoint;timeout;constructor(t,n={}){super(t),this.name="ApiError";let{name:r,stack:o,...s}=n;Object.assign(this,s),r&&(this.name=r),o&&(this.stack=o);let i=typeof t=="string"?t:t==null?"":String(t);Object.defineProperty(this,"message",{value:i,enumerable:!0,writable:!0,configurable:!0}),Object.setPrototypeOf(this,new.target.prototype)}},te=class extends b{constructor(t="Not authenticated"){super(t,{code:"NO_SESSION"}),this.name="AuthError"}},Xe=class extends b{constructor(t,n,r,o={}){super(r||n.message||`Billing Error: ${t}`,{...o,status:t,detail:n}),this.name="BillingError"}},ht=class extends b{constructor(t=431,n,r){let o="Request headers are too large";super(r||n?.message||o,{status:t,detail:{message:n?.message||o,suggestion:n?.suggestion||"Try uploading files one at a time, or reduce the number of files in a single request."}}),this.name="RequestTooLargeError"}},Rb="ENDPOINT_RETIRED";function U(e,t){let n=t?` ${t}`:"";return new b(`${e}() is retired: the Kortix API no longer serves this endpoint.${n}`,{code:Rb})}var mo="feature_disabled";function Ei(e){if(!(e instanceof b)||e.status!==403||e.code!==mo)return null;let t=e.details??e.data;return t&&typeof t=="object"?t:{}}function Mi(e){let t=Ei(e);return t?(typeof t.feature=="string"&&!e.feature&&(e.feature=t.feature),!0):!1}function Oi(e){let t=Ei(e);if(!t)return null;let n=e.feature;return typeof n=="string"?n:typeof t.feature=="string"?t.feature:null}function qn(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 Xe(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 Di(e){return e instanceof Xe}function Bt(e){if(e instanceof te)return!0;let t=e?.status;return t===401||t===403}function ji(e){if(!(e instanceof Xe))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 ye(){return typeof DOMException=="function"?new DOMException("Aborted","AbortError"):Object.assign(new Error("Aborted"),{name:"AbortError"})}function he(e,t){return new Promise((n,r)=>{let o=()=>{t.removeEventListener("abort",o),r(ye())};t.addEventListener("abort",o,{once:!0}),e.then(n,r).finally(()=>t.removeEventListener("abort",o)),t.aborted&&o()})}function Bn(e,t){return new Promise((n,r)=>{let o=()=>{clearTimeout(s),t?.removeEventListener("abort",o),r(ye())},s=setTimeout(()=>{t?.removeEventListener("abort",o),n()},e);t?.aborted?o():t?.addEventListener("abort",o,{once:!0})})}var $i="request_deadline",Cb=/^Request exceeded the \d+s server processing deadline$/,Ui=(e,t,n)=>e!==503?!1:(typeof t=="object"&&t!==null&&"code"in t?t.code:void 0)===$i||Cb.test(n),Ib="git_mirror_unavailable",Tb=/^git mirror is temporarily unavailable$/,Eb=(e,t,n)=>e!==503?!1:(typeof t=="object"&&t!==null&&"code"in t?t.code:void 0)===Ib||Tb.test(n);async function Mb(e,t){let n=`HTTP ${e.status}: ${e.statusText}`,r=null;try{r=await he(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 ye();return{message:n,data:r}}function Ob(e,t,n){return Ui(e,t,n)||Eb(e,t,n)||e===501&&t?.code===Fi||e===409&&(t?.code===Ni||t?.code===Ki)||e===503&&(t?.code===qi||t?.code===Bi)}async function Li(e,t,n,r){let{message:o,data:s}=await Mb(e,t),i=new b(o,{status:e.status,response:e,details:s||void 0,data:s,detail:s?.detail,code:Ui(e.status,s,o)?$i:s?.code||s?.error_code||s?.detail?.error_code||e.status.toString()});e.status===402&&(i=qn(i));let a=e.status!==403?null:s?.code==="account_mfa_required"?"kortix:mfa-required":s?.code==="sso_required"?"kortix:sso-required":null;if(a&&typeof window<"u"&&typeof window.dispatchEvent=="function")try{window.dispatchEvent(new CustomEvent(a))}catch{}return e.status===431&&(i=new ht(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&&!Ob(e.status,s,o)&&v().onError?.(i,r),{error:i,success:!1}}var Db="X-Kortix-Impersonate",yo="kortix.impersonation",Je=null,Gn=!1,fo=new Set;function ho(){try{return typeof sessionStorage>"u"?null:sessionStorage}catch{return null}}function jb(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 $b(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 Gi(){for(let e of fo)try{e()}catch{}}function Ub(){return Gn||(Gn=!0,Je=$b(ho()?.getItem(yo)??null)),Je&&!jb(Je)?(Wi(),null):Je}function qR(e){if(Gn=!0,!e){Wi();return}Je=e;try{ho()?.setItem(yo,JSON.stringify(e))}catch{}Gi()}function Wi(){Gn=!0;let e=Je!==null;Je=null;try{ho()?.removeItem(yo)}catch{}e&&Gi()}function BR(e){return fo.add(e),()=>{fo.delete(e)}}var Lb=/(^|\/)admin\/(api|analytics)(\/|$)/;function Fb(e){let t=e;if(/^https?:\/\//.test(e))try{t=new URL(e).pathname}catch{t=e}return!Lb.test(t)}function Hi(e){if(e!==void 0&&!Fb(e))return{};let t=Ub();return t?{[Db]:t.grantId}:{}}var xo=!1;function Nb(e){xo=e}function Kb(){return xo}function qb(e){return e?e instanceof Headers||Array.isArray(e)?[...new Headers(e).entries()]:Object.entries(e):[]}function _o(e,t){let n=t.toLowerCase();return Object.keys(e).some(r=>r.toLowerCase()===n)}function Gt(e,t,n){let r=t.toLowerCase();for(let o of Object.keys(e))o.toLowerCase()===r&&delete e[o];e[t]=n}function Wn(e,t){let n={},r=[e instanceof Request?e.headers:void 0,t.headers];for(let[o,s]of r.flatMap(qb))Gt(n,o,s);return n}function Po(e,t,n){let r={...t},o=v().clientVersion?.trim();o&&!_o(r,"x-kortix-client-version")&&Gt(r,"X-Kortix-Client-Version",o),xo&&Gt(r,"x-kortix-admin-bypass","1");for(let[s,i]of Object.entries(Hi(e)))Gt(r,s,i);return _o(r,"authorization")||Gt(r,"Authorization",`Bearer ${n}`),r}async function Vn(e,t){let n=await Hn();if(!n)throw new te;return{headers:new Headers(Po(e,Wn(e,{headers:t}),n)),rejected:()=>Wt(n)}}function Bb(e){return typeof ReadableStream<"u"&&e.body instanceof ReadableStream}function Vi(e,t,n,r,o){if(t instanceof Request){let c=new Headers(Po(t.url,Wn(t,n),r));return e(new Request(t,{headers:c,...o?{signal:o}:{}}))}let s=String(t),i=Po(s,Wn(t,n),r),a=s.startsWith("/")&&!s.startsWith("//");return e(s,{...n,headers:i,...a?{credentials:"same-origin"}:{},...o?{signal:o}:{}})}var zi=null;async function So(e){let t=await Nn(()=>v().getToken(),e);return t&&(zi=t),t}var Hn=So;function Wt(e=zi){e&&v().getToken.invalidate?.(e)}var bo=new Map;function Gb(e){let t=bo.get(e);if(t)return t;let n=(async()=>(Wt(e),Hn({attempts:2,baseDelayMs:200})))().finally(()=>bo.delete(e));return bo.set(e,n),n}async function Ze(e,t={},n={}){let{retryOnAuthError:r=!0,timeoutMs:o=go}=n,s=n.fetch??v().fetch??fetch,i=o===null?(e instanceof Request?e.signal:t.signal)??void 0:Ti(e,t,o);if(i?.aborted)throw ye();let a=await(i?he(Hn(),i):Hn());if(!a)throw new te;let c=r&&!Bb(t)&&!_o(Wn(e,t),"authorization"),p=c&&e instanceof Request?e.clone():e,d=await Vi(s,e,t,a,i);if(d.status!==401||!c)return d;let g=await Gb(a);return!g||g===a?d:Vi(s,p,t,g,i)}async function Re(e,t,n,r){let o=await Ze(e,t,n);if(o.ok)return o;let s=await o.text().catch(()=>"");throw new b(s||`${r} (HTTP ${o.status})`,{status:o.status,response:o})}var Yi=()=>v().backendUrl||"",Wb=new Set([502,503,504]),Hb=e=>Wb.has(e),Qi=e=>{let t=(e??"GET").toUpperCase();return t==="GET"||t==="HEAD"},Vb=e=>Qi(e)||(e??"GET").toUpperCase()==="DELETE",zb=2,zn=e=>e?.name==="AbortError"||e?.name==="AbortSignal"||e instanceof Error&&e.message.includes("aborted");async function Ce(e,t={}){let{showErrors:n=!0,errorContext:r,timeout:o=3e4,deadlineCoversBody:s=!1,...i}=t,a=new AbortController,c={activeController:a,timeoutId:null,isAborted:!1,didTimeout:!1},p=()=>c.activeController.abort();i.signal?.addEventListener("abort",p,{once:!0});try{return await Yb(e,i,n,r,o,s,a,c)}finally{i.signal?.removeEventListener("abort",p)}}async function Yb(e,t,n,r,o,s,i,a){try{if(t.signal?.aborted)throw ye();a.timeoutId=setTimeout(()=>{!a.isAborted&&!i.signal.aborted&&(a.isAborted=!0,a.didTimeout=!0,i.abort())},o);let c={...t.body instanceof FormData?{}:{"Content-Type":"application/json"},...t.headers},p=await Xb(e,t,c,o,s,i,a);if(p instanceof te)return{error:p,success:!1};if(!p.ok)return await Li(p,a.activeController.signal,n,r);let d,g=p.headers.get("content-type");return g?.includes("application/json")?d=await he(p.json(),a.activeController.signal):g?.includes("text/")?d=await he(p.text(),a.activeController.signal):d=await he(p.blob(),a.activeController.signal),{data:d,success:!0,headers:p.headers}}catch(c){return Jb(c,e,t.method,n,r,o,a)}finally{Yn(a)}}function Yn(e){e.timeoutId&&clearTimeout(e.timeoutId),e.timeoutId=null}async function Qb(e,t,n){try{await he(e.arrayBuffer(),t)}catch(r){if(zn(r))throw r}finally{Yn(n)}}async function Xb(e,t,n,r,o,s,i){let a=Qi(t.method),c=Vb(t.method),p=c?zb+1:1,d;for(let g=0;g<p;g++){g>0&&await Bn(250*2**(g-1),t.signal??void 0);let m=g===0?s:new AbortController;i.activeController=m,t.signal?.aborted&&m.abort(),g>0&&(i.timeoutId=setTimeout(()=>{i.didTimeout=!0,m.abort()},r));try{d=await he(Ze(e,{...t,headers:n,signal:m.signal,credentials:t.credentials??"omit"},{timeoutMs:null}),m.signal)}catch(f){if(i.timeoutId&&(clearTimeout(i.timeoutId),i.timeoutId=null),f instanceof te)return new te;if(i.didTimeout&&zn(f)&&!t.signal?.aborted&&c&&g<p-1){i.didTimeout=!1;continue}if(zn(f)||g===p-1)throw f;continue}if(!a||!Hb(d.status)||g===p-1)return o||Yn(i),d;await Qb(d,m.signal,i)}return d}function Jb(e,t,n,r,o,s,i){Yn(i);let a=zn(e);a&&(i.isAborted=!0);let c;if(a){if(!i.didTimeout)return{error:new b("Request aborted",{name:"AbortError",code:"ABORTED"}),success:!1};let p=t.replace(Yi(),"")||t;c=new b(`Request timed out after ${Math.round(s/1e3)}s: ${p}`,{code:"TIMEOUT",url:t,endpoint:p,timeout:s})}else e instanceof Error?(c=new b(n==="POST"&&e instanceof TypeError&&e.message==="Failed to fetch"?`Failed to fetch: POST ${t.replace(Yi(),"")||t}`:e.message,{name:e.name||"ApiError",stack:e.stack}),r&&v().onError?.(c,o)):(c=new b(String(e)),r&&v().onError?.(c,o));return{error:c,success:!1}}var Ie=()=>v().backendUrl||"",Fi="feature_not_supported",Ni="model_not_servable",Ki="provision_in_flight",qi="analytics_unavailable",Bi="accounts_list_unavailable",cC={async execute(e,t){try{let{data:n,error:r}=await e();if(r){let o=new b(r.message||"Database error",{code:r.code,details:r});return v().onError?.(o,t),{error:o,success:!1}}return{data:n,success:!0}}catch(n){let r=n instanceof Error?new b(n.message,{name:n.name||"ApiError",stack:n.stack}):new b(String(n));return v().onError?.(r,t),{error:r,success:!1}}}};async function Zb(e,t,n={}){let{timeout:r=3e4,fetch:o}=n,s=new AbortController,i=setTimeout(()=>s.abort(),r);try{return await Ze(`${Ie()}${e}`,{method:"POST",headers:{Accept:"text/event-stream","Content-Type":"application/json"},body:JSON.stringify(t),signal:s.signal,credentials:"omit"},{timeoutMs:null,fetch:o})}catch(a){if(a instanceof te)return Kn();throw a}finally{clearTimeout(i)}}var l={putRaw:(e,t,n)=>Ce(`${Ie()}${e}`,{...n,method:"PUT",body:t,headers:{"Content-Type":"application/octet-stream",...n?.headers}}),get:(e,t)=>Ce(`${Ie()}${e}`,{...t,method:"GET"}),post:(e,t,n)=>Ce(`${Ie()}${e}`,{...n,method:"POST",body:t?JSON.stringify(t):void 0}),put:(e,t,n)=>Ce(`${Ie()}${e}`,{...n,method:"PUT",body:t?JSON.stringify(t):void 0}),patch:(e,t,n)=>Ce(`${Ie()}${e}`,{...n,method:"PATCH",body:t?JSON.stringify(t):void 0}),delete:(e,t)=>Ce(`${Ie()}${e}`,{...t,method:"DELETE"}),upload:(e,t,n)=>{let{headers:r,...o}=n||{},s={...r};return delete s["Content-Type"],Ce(`${Ie()}${e}`,{...o,method:"POST",body:t,headers:s})},uploadPut:(e,t,n)=>{let{headers:r,...o}=n||{},s={...r};return delete s["Content-Type"],Ce(`${Ie()}${e}`,{...o,method:"PUT",body:t,headers:s})},postStream:Zb};function u(e,t="Project request failed"){if(!e.success||e.data===void 0)throw e.error??new Error(t);return e.data}function wo(e){return e.replace(/\/v1\/?$/,"")}async function bt(e,t){if(!e.backendUrl||!e.accessToken)return null;let n=wo(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 Xi(){return u(await l.get("/accounts"))}async function Ji(e){return u(await l.post("/accounts",e))}async function Zi(e){return u(await l.get(`/accounts/${e}`))}async function ea(e,t){return u(await l.patch(`/accounts/${e}`,{name:t}))}async function ta(e){return u(await l.get(`/accounts/${e}/branding`))}async function na(e,t){return u(await l.put(`/accounts/${e}/branding`,t))}async function ra(e,t,n,r){let o=new FormData;return o.append("file",n,r??(n instanceof File?n.name:t)),u(await l.upload(`/accounts/${e}/branding/assets/${t}`,o))}async function oa(e,t){return u(await l.delete(`/accounts/${e}/branding/assets/${t}`))}async function sa(e){return u(await l.delete(`/accounts/${e}/branding`))}async function ia(e){return u(await l.get(`/accounts/${e}/members`))}async function aa(e,t){return u(await l.post(`/accounts/${e}/members`,t,{showErrors:!1}))}async function ca(e){return u(await l.get(`/accounts/${e}/invites`))}async function la(e,t){return u(await l.delete(`/accounts/${e}/invites/${t}`))}async function ua(e,t){return u(await l.post(`/accounts/${e}/invites/${t}/resend`,{}))}async function pa(){return u(await l.get("/account-invites",{showErrors:!1})).invites}async function da(e){return u(await l.get(`/account-invites/${e}`,{showErrors:!1}))}async function ga(e){return u(await l.post(`/account-invites/${e}/accept`,{}))}async function ma(e){return u(await l.post(`/account-invites/${e}/decline`,{}))}async function fa(e,t){return u(await l.delete(`/accounts/${e}/members/${t}`))}async function ya(e,t,n){return u(await l.patch(`/accounts/${e}/members/${t}`,{role:n}))}async function ha(e){return u(await l.post(`/accounts/${e}/leave`,{}))}async function fC(e){return bt(e,"/v1/accounts")}async function ba(){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 PC=["marketplace","connectors_api_discover","agentmail_email","llm_gateway","meta_agent","apps","monitors","reminders","warm_sessions","secrets_egress","pooled_provider_secrets","pi_harness","us_region","event_triggers","notification_center","volumes","stateless_sessions","drives","ephemeral_sandboxes","session_log"];async function _t(){return u(await l.get("/projects"))}async function Pa(e){let t=e?`?account_id=${encodeURIComponent(e)}`:"";return u(await l.get(`/projects${t}`))}async function Qn(e,t){return u(await l.get(`/projects/${e}`,t))}async function xa(e,t,n="write"){return u(await l.post(`/projects/${e}/git/collaborators`,{github_username:t,permission:n}))}async function Sa(e,t){return u(await l.post(`/projects/${e}/manifest/validate`,{raw:t}),"Failed to validate manifest")}async function wa(e){return u(await l.post(`/projects/${e}/git-token`,{}),"Failed to mint git token")}function xC(e){let t=e.metadata?.git;return t?.provider==="github"&&t?.managed===!0}async function Xn(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 Jn(e,t){return u(await l.get(`/projects/${e}/llm-catalog`,{showErrors:!1,...t}))}async function Zn(e,t){return u(await l.get(`/projects/${e}/model-picker`,{showErrors:!1,...t}))}async function SC(e,t){return u(await l.get(`/projects/${e}/llm-catalog/providers`,{showErrors:!1,...t}))}async function Aa(e){return u(await l.post("/projects",e))}async function va(e){return u(await l.post("/projects/create-repo",e,{showErrors:!1}))}async function ka(e,t={}){return u(await l.post("/projects/provision",{seed_starter:!0,...e},{timeout:12e4,...t}))}var _a=200;function e_(e){let t=e.split(`
2
2
  `).filter(r=>r.startsWith("data:")).map(r=>r.slice(5).replace(/^ /,""));if(t.length===0)return null;let n=t.join(`
3
- `);try{return JSON.parse(n)}catch(r){let o=n.length>ca?`${n.slice(0,ca)}\u2026`:n;throw new Error(`provisionProjectStream: received an unparseable SSE frame (${o})`,{cause:r})}}async function KR(e,t,n={}){let r=await l.postStream("/projects/provision-stream",{seed_starter:!0,...e},n);if(!r.ok){let c=await r.json().catch(()=>null);throw new b(c?.error||`Provision failed: HTTP ${r.status}`,{status:r.status,code:c?.code})}let o=r.body?.getReader();if(!o)throw new Error("Provision stream is unavailable on this runtime (no response body)");let s=new TextDecoder,i="",a=null;try{for(;;){let{done:c,value:p}=await o.read();if(c)break;i+=s.decode(p,{stream:!0});let d=i.indexOf(`
3
+ `);try{return JSON.parse(n)}catch(r){let o=n.length>_a?`${n.slice(0,_a)}\u2026`:n;throw new Error(`provisionProjectStream: received an unparseable SSE frame (${o})`,{cause:r})}}async function wC(e,t,n={}){let r=await l.postStream("/projects/provision-stream",{seed_starter:!0,...e},n);if(!r.ok){let c=await r.json().catch(()=>null);throw new b(c?.error||`Provision failed: HTTP ${r.status}`,{status:r.status,code:c?.code})}let o=r.body?.getReader();if(!o)throw new Error("Provision stream is unavailable on this runtime (no response body)");let s=new TextDecoder,i="",a=null;try{for(;;){let{done:c,value:p}=await o.read();if(c)break;i+=s.decode(p,{stream:!0});let d=i.indexOf(`
4
4
 
5
5
  `);for(;d!==-1;){let g=i.slice(0,d);i=i.slice(d+2),d=i.indexOf(`
6
6
 
7
- `);let m=Mb(g);if(m){if(t(m),m.type==="error")throw new b(m.error,{status:m.status,code:m.code});m.type==="done"&&(a=m.project)}}}}finally{o.cancel().catch(()=>{})}if(!a)throw new Error("Provision stream ended without a result");return a}async function qR(){try{return u(await l.get("/projects/managed-git/status",{showErrors:!1}))}catch{return{configured:!1,provider:"github"}}}async function Hn(e,t){return u(await l.patch(`/projects/${e}`,t))}async function ya(e,t,n){return u(await l.patch(`/projects/${e}/features`,{feature:t,enabled:n}))}async function ha(e,t,n){return u(await l.patch(`/projects/${e}/experimental`,{feature:t,enabled:n}))}async function ba(e,t){return u(await l.patch(`/projects/${e}/sandbox-provider`,{provider:t}))}async function GR(e,t){return u(await l.get(`/projects/${e}/sandbox-provider/transition`,{showErrors:!1,...t}))}async function BR(e,t){throw F("updateTemplateWarmPool")}async function _a(e,t){return u(await l.patch(`/projects/${e}/onboarding`,{completed:t}))}async function WR(e,t){return u(await l.patch(`/projects/${e}/onboarding`,{profile:t}))}async function Vn(e){return u(await l.delete(`/projects/${e}`))}async function HR(e,t){return pt(e,`/v1/projects?account_id=${encodeURIComponent(t)}`)}async function VR(e,t){if(!e.backendUrl||!e.accessToken)return{ok:!1,limitReached:!1};let n=mo(e.backendUrl);try{let r=await fetch(`${n}/v1/projects/provision`,{method:"POST",headers:{Authorization:`Bearer ${e.accessToken}`,"Content-Type":"application/json"},body:JSON.stringify({seed_starter:!0,...t}),signal:AbortSignal.timeout(e.timeoutMs??9e4)});if(r.ok){let o=await r.json().catch(()=>null);return o?.project_id?{ok:!0,project:o}:{ok:!1,limitReached:!1}}return r.status===403?{ok:!1,limitReached:(await r.json().catch(()=>null))?.code==="project_limit_reached"}:{ok:!1,limitReached:!1}}catch{return{ok:!1,limitReached:!1}}}async function Pa(e,t,n){return u(await l.post(`/projects/${e}/skills`,t,{showErrors:!1,...n}))}async function xa(e){return u(await l.post("/projects/link-repository",e,{showErrors:!1}))}async function Sa(e){let{project_id:t,...n}=e;return u(await l.put(`/projects/${encodeURIComponent(t)}/git/repository`,n,{showErrors:!1}))}async function wa(e){return u(await l.get(`/projects/github/installation?account_id=${encodeURIComponent(e)}`,{showErrors:!1}))}async function va(e){return u(await l.get(`/projects/github/installations?account_id=${encodeURIComponent(e)}`,{showErrors:!1}))}async function Aa(e){return u(await l.post("/projects/github/installations/linkable",e,{showErrors:!1}))}async function ka(e,t,n){let r=new URLSearchParams({account_id:e});t&&r.set("installation_id",t);let o=n?.search?.trim();return o&&r.set("search",o),n?.limit!==void 0&&r.set("limit",String(n.limit)),u(await l.get(`/projects/github/repositories?${r.toString()}`,{showErrors:!1}))}async function Ra(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 Ia(e){return u(await l.post("/projects/github/installation",e,{showErrors:!1}))}async function Ca(e){return u(await l.post("/projects/github/installations/link",e,{showErrors:!1}))}async function Ta(e){return u(await l.post("/projects/github/user-token",e,{showErrors:!1}))}async function Ea(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 Ma(){return u(await l.get("/projects/git/backend",{showErrors:!1}))}async function Oa(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 iI(e,t){return u(await l.post(`/projects/${e}/access-requests`,{message:t?.trim()||void 0},{showErrors:!1}))}async function Da(e,t){return u(await l.get(`/projects/${e}/access-requests`,t))}async function ja(e,t,n="member"){return u(await l.post(`/projects/${e}/access-requests/${t}/approve`,{role:n}))}async function $a(e,t){return u(await l.post(`/projects/${e}/access-requests/${t}/reject`,{}))}async function Ua(e){return u(await l.get(`/projects/${e}/access`))}async function Fa(e,t,n){return u(await l.put(`/projects/${e}/access/${t}`,{role:n}))}async function La(e,t){return u(await l.delete(`/projects/${e}/access/${t}`))}function aI(e){return"status"in e&&e.status==="invited"}async function Na(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 Ka(e){return u(await l.get(`/projects/${e}/access/pending-invites`))}async function qa(e,t){return u(await l.delete(`/projects/${e}/access/pending-invites/${t}`))}async function Ga(e,t){return u(await l.post(`/projects/${e}/access/pending-invites/${t}/resend`))}async function Ba(e){return u(await l.get(`/projects/${e}/group-grants`))}async function Wa(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 Ha(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 Va(e,t){return u(await l.delete(`/projects/${e}/group-grants/${t}`))}async function za(e){return u(await l.get(`/projects/${e}/resource-grants`))}async function Ya(e,t){return u(await l.post(`/projects/${e}/resource-grants`,{resource_type:t.resourceType,resource_id:t.resourceId,principal_type:t.principalType,principal_id:t.principalId,...t.expiresAt!==void 0?{expires_at:t.expiresAt}:{}}))}async function Qa(e,t){return u(await l.delete(`/projects/${e}/resource-grants/${t}`))}async function Xa(e,t){return u(await l.get(`/projects/${e}/approvals`,{showErrors:t?.showErrors}))}async function Ja(e,t){return u(await l.get(`/projects/${e}/approvals/needs-input`,{showErrors:t?.showErrors}))}async function Za(e,t,n,r={}){let o=r.note?.trim();return u(await l.post(`/projects/${e}/approvals/${t}`,{decision:n,...o?{note:o}:{}}))}async function ec(e){return u(await l.get(`/projects/${e}/secrets`,{showErrors:!1}))}async function tc(e,t){return u(await l.post(`/projects/${e}/secrets`,t))}async function nc(e,t,n,r={}){return u(await l.put(`/projects/${e}/secrets/${encodeURIComponent(t)}/strategy`,{strategy:n,...r}))}async function rc(e,t,n){return u(await l.post(`/projects/${e}/secrets/${encodeURIComponent(t)}/broker`,n))}async function oc(e){return u(await l.get(`/projects/${e}/oauth`)).items??[]}async function fo(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 yo(e,t,n){return u(await l.post(`/projects/${e}/oauth/${t}/poll`,{flow_id:n}))}async function sc(e,t){return u(await l.delete(`/projects/${e}/oauth/${encodeURIComponent(t)}`))}var Ob=2e3,Db=3e3,jb=10*6e4;async function pI(e){let{projectId:t,provider:n,input:r,onChallenge:o,isCancelled:s,sleep:i=m=>new Promise(f=>setTimeout(f,m)),now:a=()=>Date.now()}=e,c=()=>s?.()??!1,p=await fo(t,n,r);if(c())return{status:"cancelled"};o?.({verification_url:p.verification_url,user_code:p.user_code});let d=Math.max(Ob,p.interval_ms||Db),g=p.expires_at||a()+jb;for(;!c()&&a()<g;){if(await i(d),c())return{status:"cancelled"};let m;try{m=await yo(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 ic(e,t){return u(await l.put(`/projects/${e}/git-credential`,t))}async function ac(e,t){return u(await l.delete(`/projects/${e}/secrets/${encodeURIComponent(t)}`))}async function cc(e,t,n){return u(await l.put(`/projects/${e}/secrets/${encodeURIComponent(t)}/personal`,n))}async function lc(e,t){return u(await l.delete(`/projects/${e}/secrets/${encodeURIComponent(t)}/personal`))}var ho=e=>`/accounts/${encodeURIComponent(e)}/secret-resources`,gt=(e,t)=>`${ho(e)}/${encodeURIComponent(t)}`,uc=(e,t,n)=>`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/provider-secret-pools/${encodeURIComponent(n)}`;async function pc(e,t){let n=t?`?project_id=${encodeURIComponent(t)}`:"";return u(await l.get(`${ho(e)}${n}`))}async function dc(e,t){return u(await l.post(ho(e),t))}async function gc(e,t,n){return u(await l.put(`${gt(e,t)}/value`,{value:n}))}async function mc(e,t){return u(await l.post(`${gt(e,t)}/retry`))}async function fc(e,t){return u(await l.delete(gt(e,t)))}async function yc(e,t,n,r){return u(await l.put(`${gt(e,t)}/grants/${encodeURIComponent(n)}`,{},r))}async function hc(e,t,n,r){return u(await l.delete(`${gt(e,t)}/grants/${encodeURIComponent(n)}`,r))}async function bc(e,t,n,r){return u(await l.put(`${gt(e,t)}/access`,{mode:n,user_ids:r}))}async function _c(e,t,n){return u(await l.get(uc(e,t,n)))}async function Pc(e,t){let n=`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/provider-secret-pools`;return u(await l.get(n))}async function xc(e,t,n,r){return u(await l.put(uc(e,t,n),{secret_ids:r}))}async function bo(){return go()}async function $b(e){return Mn(()=>k().getToken(),e,_o)}function _o(){Ut()}function PI(e){e===null&&Ut()}function xI(e){}async function Ft(){return bo()}async function SI(e){return $b(e)}async function M(e,t,n){try{return await Ve(e,t,{retryOnAuthError:n?.retryOnAuthError,timeoutMs:n?.timeoutMs})}catch(r){if(r instanceof X)return On();throw r}}function zn(e,t){return e?`/connectors/projects/${encodeURIComponent(e)}/${t}`:`/connectors/${t}`}async function Lt(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(`${zn(e,"catalog")}${r}`)).connectors??[]}async function Po(e){let t=[];for(let n of await Lt(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 Sc(e,t="",n={}){let r=t.trim().toLowerCase(),o=r.split(/\s+/).filter(Boolean),s=[],i=[];for(let a of await Po(e)){let c=`${a.tool} ${a.description}`.toLowerCase();!r||c.includes(r)?s.push(a):o.every(p=>c.includes(p))&&i.push(a)}return[...s,...i].slice(0,n.limit??20)}async function xo(e,t){let n=t.indexOf(".");if(n<0)return null;let r=t.slice(0,n).trim();if(!r)return null;let o=(await Lt(e,{slug:r,includeSchemas:!0,includeOutputSchemas:!0})).find(s=>s.slug===r);if(!o)return null;for(let s of o.actions){let i=`${o.slug}.${s.path}`;if(i===t)return{tool:i,connector:o.slug,action:s.path,risk:s.risk,description:s.description||s.name,inputSchema:s.inputSchema,outputSchema:s.outputSchema??null}}return null}function Ub(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 Fb=9e4;async function mt(e,t,n={},r={}){let{connector:o,action:s}=Ub(t),i=r.account?.trim(),a=r.approvalContext?.trim(),c=u(await l.post(zn(e,"call"),{connector:o,action:s,args:n,...i?{account:i}:{},...a?{approval_context:a}:{}},{timeout:r.timeoutMs??Fb,signal:r.signal}));return c.ok&&c.binding!==void 0&&!("output"in c)&&(c.output=c.data),c}async function So(e,t){let n=await l.get(zn(e,`connectors/${encodeURIComponent(t)}/accounts`));return u(n).accounts??[]}function Lb(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 Nb(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 wo(e,t,n){let r=n.filename.trim(),o=n.contentType.trim();if(!r)throw new Error("filename is required");if(!o)throw new Error("contentType is required");let s={"Content-Type":o,"X-Kortix-Attachment-Filename":encodeURIComponent(r),"X-Kortix-Attachment-Disposition":n.contentDisposition??"attachment"};n.contentId?.trim()&&(s["X-Kortix-Attachment-Content-Id"]=encodeURIComponent(n.contentId.trim())),n.connector?.trim()&&(s["X-Kortix-Attachment-Connector"]=encodeURIComponent(n.connector.trim()));let i=Nb(k().backendUrl),a=zn(e,"attachments"),c=await M(`${i}${a}`,{method:"POST",headers:s,body:t},{timeoutMs:6e4}),p=await c.text(),d=null;if(p)try{d=JSON.parse(p)}catch{d=p}if(!c.ok)throw new b(Lb(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 CI(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 wc(e){return u(await l.get(`/projects/${e}/connections`))}async function vc(e){return u(await l.get(`/projects/${e}/connections/all`))}async function Ac(e,t){return u(await l.post(`/projects/${e}/connections`,t))}async function kc(e,t){return u(await l.post(`/projects/${e}/connections/me`,t))}async function Rc(e,t,n){return u(await l.put(`/projects/${e}/connections/${t}/credential`,n))}function ke(e,t,n){return`/projects/${e}/connections/${t}/oauth2/${n}`}async function TI(e,t){return u(await l.post(`/projects/${e}/connectors/${encodeURIComponent(t)}/oauth2/connection`,{}))}async function EI(e,t,n){return u(await l.put(ke(e,t,"application"),n))}async function MI(e,t){return u(await l.get(ke(e,t,"application")))}async function OI(e,t,n){return u(await l.post(ke(e,t,"discover"),n))}async function DI(e,t,n={}){return u(await l.post(ke(e,t,"discover-resource"),n))}async function jI(e,t,n){return u(await l.post(ke(e,t,"register"),n))}async function $I(e,t,n){return u(await l.post(ke(e,t,"authorize"),n))}async function UI(e,t,n){return u(await l.post(ke(e,t,"device"),n))}async function FI(e,t,n){return u(await l.post(ke(e,t,`device/${encodeURIComponent(n)}`),{}))}async function LI(e,t){return u(await l.get(ke(e,t,"status")))}async function Ic(e,t){return u(await l.put(`/projects/${e}/connections/${t}/revoke`,{}))}async function Cc(e,t){return u(await l.put(`/projects/${e}/connections/${t}/activate`,{}))}async function Tc(e,t){return u(await l.put(`/projects/${e}/connections/${t}/default`,{}))}async function Ec(e,t,n){return u(await l.put(`/projects/${e}/connections/${t}/label`,{label:n}))}async function Mc(e,t){return u(await l.post(`/projects/${e}/computers`,{tunnel_id:t.tunnelId,...t.share?{share:t.share}:{}}))}async function Oc(e,t,n=[]){return u(await l.post(`/projects/${e}/connections/${t}/share`,{principals:n}))}async function Dc(e,t,n={}){return u(await l.post(`/projects/${e}/connections/${t}/connect`,n))}async function jc(e,t){return u(await l.post(`/projects/${e}/connections/${t}/connect/finalize`,{}))}async function $c(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 Uc(e){return u(await l.post(`/connectors/projects/${e}/connectors/sync`,{}))}async function Fc(e,t,n){return u(await l.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/credential-mode`,{mode:n}))}async function Lc(e,t,n){return u(await l.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/authorization-strategy`,{authorization_strategy:n}))}async function Nc(e,t,n){return u(await l.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/sensitive`,{sensitive:n}))}async function Kc(e,t){return u(await l.get(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/policies`))}async function qc(e,t,n){return u(await l.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/policies`,{policies:n}))}async function NI(e,t){throw new Error("Connection-specific policies were removed. Use getConnectorPolicies(projectId, slug).")}async function KI(e,t,n){throw new Error("Connection-specific policies were removed. Use setConnectorPolicies(projectId, slug, policies).")}async function Gc(e,t){return u(await l.get(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/config`))}async function Bc(e,t,n){return u(await l.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/name`,{name:n}))}async function Kb(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 Wc=Kb;async function qI(e,t){return u(await l.get(`/connectors/projects/${e}/sessions/${encodeURIComponent(t)}/connect-requests`)).connectors??[]}async function Hc(e,t){return u(await l.post(`/connectors/projects/${e}/connectors`,t))}async function Vc(e,t){return u(await l.post(`/connectors/projects/${e}/connectors/auth-discovery`,t))}async function zc(e,t){return u(await l.delete(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}`))}async function Yc(e,t,n){let r=typeof t=="string"||t===void 0?{...t?{q:t}:{},...n?{cursor:n}:{}}:t,o=new URLSearchParams;r.q&&o.set("q",r.q),r.category&&o.set("category",r.category),r.cursor&&o.set("cursor",r.cursor),r.limit&&o.set("limit",String(r.limit));let s=o.toString();return u(await l.get(`/connectors/projects/${e}/pipedream/apps${s?`?${s}`:""}`))}async function Qc(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 GI(e,t={}){let n=new URLSearchParams;t.q&&n.set("q",t.q),t.category&&n.set("category",t.category),t.cursor&&n.set("cursor",t.cursor),t.limit&&n.set("limit",String(t.limit));let r=n.toString(),o=u(await l.get(`/connectors/projects/${e}/connect/toolkits${r?`?${r}`:""}`));if("toolkits"in o)return o;let s=o.cursor?.trim()||void 0;return{provider:"composio",toolkits:o.items,nextCursor:s,hasMore:!!s}}async function BI(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 vo(e,t,n){let r=typeof t=="string"||t===void 0?{...t?{q:t}:{},...n?{cursor:n}:{}}:t,o=new URLSearchParams;r.q&&o.set("q",r.q),r.category&&o.set("category",r.category),r.cursor&&o.set("cursor",r.cursor),r.limit&&o.set("limit",String(r.limit));let s=o.toString();return u(await l.get(`/connectors/projects/${e}/discover/connectors${s?`?${s}`:""}`))}async function Xc(e,t){let n=new URLSearchParams;t?.perCategory&&n.set("perCategory",String(t.perCategory)),t?.maxCategories&&n.set("maxCategories",String(t.maxCategories));let r=n.toString();return u(await l.get(`/connectors/projects/${e}/discover/sections${r?`?${r}`:""}`))}async function Ao(e,t){let n=new URLSearchParams({id:t});return u(await l.get(`/connectors/projects/${e}/discover/connectors/detail?${n.toString()}`))}var WI=vo,HI=Ao;async function Jc(){return u(await l.get("/connectors/connect-status"))}async function Zc(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 el(e,t){return u(await l.delete(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/credential`))}async function VI(e,t,n){return u(await l.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/secret-binding`,{secret_identifier:n}))}async function qb(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 tl=qb;var Yn=class extends b{reason;connector;action;binding;upstreamStatus;retryAfterSeconds;connectUrl;hint;availableAccounts;requestedAccount;constructor(t,n){let{reason:r,connector:o,action:s,binding:i,upstreamStatus:a,retryAfterSeconds:c,connectUrl:p,hint:d,availableAccounts:g,requestedAccount:m,...f}=n;super(t,{...f,name:"ConnectorCallError"}),this.reason=r,this.connector=o,this.action=s,this.binding=i??null,this.upstreamStatus=a??null,this.retryAfterSeconds=c??null,this.connectUrl=p??null,this.hint=d??null,this.availableAccounts=g??[],this.requestedAccount=m??null}},ko=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)}},Ro=class extends Error{code="max_pages_exceeded";connector;action;maxPages;nextArgs;constructor(t,n,r,o){super(`${t}.${n} has more than ${r} pages; resume with nextArgs`),this.name="ConnectorPageLimitError",this.connector=t,this.action=n,this.maxPages=r,this.nextArgs=o,Object.setPrototypeOf(this,new.target.prototype)}},fe=e=>typeof e=="string"&&e?e:null;function nl(e){return/^([a-z][a-z0-9_]*)(?::|$)/.exec(e)?.[1]??"connector_error"}function Gb(e){let t=e?.headers?.get("retry-after");return t&&/^\d+$/.test(t.trim())?Number(t):null}function Bb(e,t,n){if(!(e instanceof b)||typeof e.status!="number")return e;let r=e.details&&typeof e.details=="object"?e.details:{},o=fe(r.reason)??fe(r.error)??e.message,s=/^upstream_(\d{3})\b/.exec(o),i=typeof r.upstream_status=="number"?r.upstream_status:s?Number(s[1]):null;return new Yn(fe(r.message)??fe(r.hint)??o,{status:e.status,code:i===null?nl(o):`upstream_${i}`,details:e.details,data:e.details,response:e.response,reason:o,connector:fe(r.connector)??t,action:fe(r.action)??n,binding:fe(r.binding),upstreamStatus:i,retryAfterSeconds:typeof r.retry_after_seconds=="number"?r.retry_after_seconds:Gb(e.response),connectUrl:fe(r.connect_url),hint:fe(r.hint),availableAccounts:Array.isArray(r.available_accounts)?r.available_accounts:[],requestedAccount:fe(r.requested_account)})}function Wb(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 Io(e,t,n,r={},o={}){let s=t.trim(),i=n.trim();if(!s||!i)throw new Error("connector slug and action are required");let a;try{a=await mt(e,`${s}.${i}`,r,o)}catch(c){throw Bb(c,s,i)}if(a.status==="pending_approval")throw new ko(s,i,a);if(!a.ok||a.upstream_error){let c=a.upstream_error??a.reason??"connector_error";throw new Yn(c,{status:200,code:a.upstream_error?"upstream_error":nl(c),details:a,data:a,reason:c,connector:s,action:i,binding:a.binding??null,upstreamStatus:a.upstream_status??null})}return Wb(a)}async function*rl(e,t,n,r,o){let{next:s,maxPages:i=100,...a}=o,c=r;for(let p=0;c;p++){if(p>=i)throw new Ro(t,n,i,c);let d=await Io(e,t,n,c,a);yield d,c=s(d,c)}}async function ol(e){return u(await l.get(`/connectors/projects/${e}/policies`))}async function sl(e,t,n){return u(await l.put(`/connectors/projects/${e}/policies`,{policies:t,defaultMode:n}))}async function il(e){return u(await l.get(`/projects/${e}/sandboxes`))}async function al(e){return u(await l.get(`/projects/${e}/snapshots`))}async function Qn(e){return u(await l.get(`/projects/${e}/sandbox-health`,{showErrors:!1,timeout:15e3}))}async function cl(e,t){return u(await l.post(`/projects/${e}/snapshots/rebuild`,t?{slug:t}:{}))}async function ll(e){return u(await l.post(`/projects/${e}/snapshots/fix-with-agent`,{}))}async function ul(e,t){return u(await l.post(`/projects/${e}/sandbox-templates`,t))}async function pl(e,t,n){return u(await l.patch(`/projects/${e}/sandbox-templates/${t}`,n))}async function dl(e,t){return u(await l.delete(`/projects/${e}/sandbox-templates/${t}`))}async function gl(e,t){return u(await l.post(`/projects/${e}/sandbox-templates/${t}/build`,{}))}async function ml(e){return u(await l.get(`/projects/${e}/sandboxes`))}async function Xn(e){let t=new URL(k().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 Ln(e);return{url:e,headers:Object.fromEntries(r.entries())}}async function fl(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 yl(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"),u(await l.get(`/projects/${e}/files?${n.toString()}`,{showErrors:!1}))}async function hl(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 bl(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 Hb=10*6e4;async function _l(e,t,n){let r=new URLSearchParams;t&&r.set("ref",t),n&&r.set("path",n);let o=r.toString()?`?${r.toString()}`:"",s=`${k().backendUrl||""}/projects/${e}/files/archive${o}`;return await(await we(s,{method:"GET"},{timeoutMs:Hb},"Failed to download")).blob()}async function Pl(e,t,n){let r=new URLSearchParams;t&&r.set("ref",t),n&&r.set("path",n);let o=r.toString()?`?${r.toString()}`:"";return Xn(`${k().backendUrl}/projects/${encodeURIComponent(e)}/files/archive${o}`)}async function dC(e,t,n,r){let o=new URLSearchParams({path:t});n&&o.set("ref",n);let s=o.toString()?`?${o.toString()}`:"",i=`${k().backendUrl||""}/projects/${e}/files/raw${s}`;return await(await we(i,{method:"GET",...r?.signal?{signal:r.signal}:{}},{},"Failed to read file")).blob()}var Co=52428800,Vb=104857600,xl=20;var Zn=e=>`/projects/${encodeURIComponent(e)}/attachments`,er={showErrors:!1,deadlineCoversBody:!0},Sl=3e4,zb=12e4,Yb=6e4,Qb=5*6e4,Xb=6e4,Jb=6e4;function Jn(){return new b("Request aborted",{name:"AbortError",code:"ABORTED"})}function Nt(e){if(e?.aborted)throw Jn()}function Zb(e){return!(e instanceof b)||e.code==="ABORTED"||e.code==="attachment_budget_exceeded"?!1:e.code==="TIMEOUT"||e.name==="TypeError"||e.status===429||e.status!==void 0&&e.status>=500}async function Kt(e,t,n=!1){let r;for(let o=0;;o++){Nt(t);try{return await e()}catch(s){let i=n&&s instanceof b&&s.status===409&&s.code==="attachment_processing";if(t?.aborted||!(Zb(s)||i))throw s;r??=Date.now()+(n?Qb:Yb);let a=Math.min(8e3,500*2**o)*(.5+Math.random()/2);if(Date.now()+a>=r)throw s;try{await jn(a,t)}catch{throw Nt(t),s}}}}function e_(e){return!!e&&typeof e=="object"&&!Array.isArray(e)&&Object.values(e).every(t=>typeof t=="string")}function To(e,t,n){let r=e?.upload,o=e?.received_bytes,s=Number.isSafeInteger(o)&&o>=0&&o<=t.size,i=r?.kind==="direct"?typeof r.url=="string"&&/^https?:\/\//i.test(r.url)&&r.method==="PUT"&&e_(r.headers)&&Number.isFinite(Date.parse(r.expires_at))&&(o===0||o===t.size):r?.kind==="chunked"&&Number.isSafeInteger(r.chunk_size)&&r.chunk_size>0&&(o===t.size||o%r.chunk_size===0);if(!e?.attachment_id||n!==void 0&&e.attachment_id!==n||e.size!==t.size||!s||!i)throw new Error("Invalid attachment upload handle");return e}async function wl(e,t,n,r){return u(await l.post(Zn(e),{...r?{attachment_id:r}:{},filename:t.name,mime:t.type||"application/octet-stream",size:t.size},{...er,signal:n,timeout:Sl}),"Failed to start attachment upload")}async function vl(e,t,n,r){let o=To({...await Kt(()=>wl(e,t,r.signal,n.attachment_id),r.signal),received_bytes:0},t,n.attachment_id);return r.onUpload?.(o),o}function Al(e,t){let n;try{n=JSON.parse(t)}catch{}let r=typeof n?.message=="string"?n.message:typeof n?.error=="string"?n.error:`HTTP ${e}`;return new b(r,{status:e,details:n,code:String(n?.statusCode??e)})}function t_(e){if(!(e instanceof b))return;let t=Number(e.details?.statusCode);return Number.isInteger(t)&&t>=400?t:e.status}function n_(e,t,n,r){return new Promise((o,s)=>{let i=new e,a=0,c=!1,p,d=f=>{c||(c=!0,p&&clearTimeout(p),r.signal?.removeEventListener("abort",m),f?s(f):o())},g=()=>{p&&clearTimeout(p),p=setTimeout(()=>{d(new b("Attachment upload stalled",{code:"TIMEOUT"})),i.abort()},Xb)},m=()=>{d(Jn()),i.abort()};i.open(t.method,t.url);for(let[f,h]of Object.entries(t.headers))i.setRequestHeader(f,h);i.upload.onprogress=f=>{g(),a=Math.min(f.loaded,n.size),r.onProgress?.(a,n.size)},i.onload=()=>{i.status>=200&&i.status<300?(a<n.size&&r.onProgress?.(n.size,n.size),d()):d(Al(i.status,i.responseText))},i.onerror=()=>d(new b("Network error during attachment upload",{name:"TypeError"})),i.onabort=()=>d(Jn()),r.signal?.addEventListener("abort",m,{once:!0}),g(),i.send(n)})}async function r_(e,t,n){let r=k().fetch??fetch,o;try{o=await r(e.url,{method:e.method,headers:e.headers,body:t,signal:n.signal,credentials:"omit"})}catch(s){throw n.signal?.aborted||s instanceof Error&&s.name==="AbortError"?Jn():new b(s instanceof Error?s.message:String(s),{name:s instanceof Error?s.name:"TypeError"})}if(!o.ok)throw Al(o.status,await o.text().catch(()=>""));n.onProgress?.(t.size,t.size)}function o_(e,t,n){Nt(n.signal);let r=globalThis.XMLHttpRequest;return typeof r=="function"?n_(r,e,t,n):r_(e,t,n)}async function s_(e,t,n,r){let o=n,s=!1;for(r.onProgress?.(0,t.size);o.upload.kind==="direct";){let i=o.upload;try{await Kt(()=>o_(i,t,r),r.signal)}catch(a){let c=t_(a);if(c!==409){if(s||!(c===400||c===401||c===403))throw a;s=!0,o=await vl(e,t,o,r);continue}}return o={...o,received_bytes:t.size},r.onUpload?.(o),o}return kl(e,t,o,r)}async function kl(e,t,n,r){if(n.upload.kind!=="chunked")throw new Error("Invalid attachment upload handle");let o=n.upload.chunk_size,s=`${Zn(e)}/${encodeURIComponent(n.attachment_id)}`,i=n;for(;i.received_bytes<t.size;){Nt(r.signal);let a=i.received_bytes,c=Math.min(a+o,t.size),p=t.slice(a,c),d=await Kt(async()=>u(await l.putRaw(`${s}/chunks/${a/o}`,p,{...er,signal:r.signal,timeout:Sl}),"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 tr(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");Nt(n.signal);let r=n.resume?To({...n.resume},t):To({...await Kt(()=>wl(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()<Jb&&(r=await vl(e,t,r,n)),r=r.upload.kind==="direct"?await s_(e,t,r,n):await kl(e,t,r,n)),n.onProcessing?.();let o=`${Zn(e)}/${encodeURIComponent(r.attachment_id)}`;try{return await Kt(async()=>u(await l.post(`${o}/complete`,{},{...er,signal:n.signal,timeout:zb}),"Failed to complete attachment upload"),n.signal,!0)}catch(s){throw r.upload.kind==="direct"&&s instanceof b&&s.code==="attachment_not_uploaded"&&n.onUpload?.({...r,received_bytes:0}),s}}async function qt(e,t,n={}){if(!e)throw new Error("A project is required to remove attachments");let r=await l.delete(`${Zn(e)}/${encodeURIComponent(t)}`,{...er,signal:n.signal});if(!r.success)throw r.error??new Error("Failed to remove attachment")}async function Rl(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 Il(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 Cl(e,t){return u(await l.get(`/projects/${e}/commits/${encodeURIComponent(t)}`))}async function Tl(e,t,n){let r=new URLSearchParams;n?.path&&r.set("path",n.path);let o=r.toString()?`?${r.toString()}`:"";return u(await l.get(`/projects/${e}/commits/${encodeURIComponent(t)}/diff${o}`))}async function El(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 Ml(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 Ol(e,t,n){let r=new URLSearchParams;t&&r.set("status",t),n?.originSessionId&&r.set("origin_session_id",n.originSessionId),n?.limit!=null&&r.set("limit",String(n.limit));let o=r.toString()?`?${r.toString()}`:"";return u(await l.get(`/projects/${e}/change-requests${o}`,{showErrors:!1,timeout:15e3}))}async function Dl(e,t){return u(await l.get(`/projects/${e}/change-requests/${t}`))}async function jl(e,t){return u(await l.get(`/projects/${e}/change-requests/${t}/diff`))}async function $l(e,t){return u(await l.get(`/projects/${e}/change-requests/${t}/merge-preview`))}async function Ul(e,t){return u(await l.post(`/projects/${e}/change-requests`,t))}async function Fl(e,t,n){return u(await l.post(`/projects/${e}/change-requests/${t}/merge`,n??{},{showErrors:!1}))}async function Ll(e,t){return u(await l.post(`/projects/${e}/change-requests/${t}/close`,{}))}async function Nl(e,t){return u(await l.post(`/projects/${e}/change-requests/${t}/reopen`,{}))}async function Kl(e,t,n){return u(await l.post(`/projects/${e}/change-requests/${t}/request-changes`,{feedback:n}))}async function ql(e,t,n){return u(await l.post(`/projects/${e}/sessions/${t}/commit-push`,n??{}))}async function Gl(e,t,n){return u(await l.patch(`/projects/${e}/change-requests/${t}`,n))}var ft=new Set,i_=500;function nr(e){e&&(ft.add(e),ft.size>i_&&ft.delete(ft.values().next().value))}function Bl(e){return!!e&&ft.has(e)}function kC(e){e&&ft.delete(e)}function Wl(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 rr=1,a_=12,c_=15e5,l_=3e5,u_=336*60*60*1e3,p_="kortix.saved-copy";function Eo(e){return!!e&&typeof e.then=="function"}function d_(e,t){return Eo(e)?e.then(t):t(e)}function g_(e,t){let n=JSON.stringify(e);if(n.length<=t)return n;let{messages:r}=e.e;if(r.length===0)return null;let o=a=>{let c=r.slice(r.length-a);return JSON.stringify({...e,e:{...e.e,messages:c,message_count:c.length,complete:!1,next_cursor:String(c[0].info.id)}})},s=o(1).length-JSON.stringify(r[r.length-1]).length,i=0;for(;i<r.length;){let a=JSON.stringify(r[r.length-1-i]).length+(i>0?1:0);if(s+a>t)break;s+=a,i+=1}for(;i>0;i-=1){let a=o(i);if(a.length<=t)return a}return null}function m_(e){let t=e.captured_at?Date.parse(e.captured_at):Number.NaN;return Number.isFinite(t)?t:0}function IC(e){let{storage:t,userId:n,maxSessions:r=a_,maxBytes:o=c_,maxEnvelopeBytes:s=l_,maxAgeMs:i=u_,namespace:a=p_,now:c=()=>Date.now()}=e,p=`${a}:${n}:`,d=`${p}index`,g=(w,P)=>`${p}${w}/${P}`,m=w=>{try{let P=t.getItem(w);return Eo(P)?P.catch(()=>null):P}catch{return null}},f=w=>{try{let P=t.removeItem(w);Eo(P)&&P.catch(()=>{})}catch{}},h=async w=>{try{await t.removeItem(w)}catch{}},S=w=>{if(!w)return[];try{let P=JSON.parse(w);return P?.v===rr&&Array.isArray(P.entries)?P.entries:[]}catch{return[]}},D=Promise.resolve(),j=w=>{let P=D.then(w,w);return D=P.catch(()=>{}),P},L=async w=>{try{await t.setItem(d,JSON.stringify({v:rr,entries:w}))}catch{}},y=async()=>S(await m(d)),_=async(w,P)=>{let A=[...w].sort((T,N)=>T.u-N.u),C=A.reduce((T,N)=>T+N.b,0);for(;A.length>r||C>o;){let T=A.findIndex($=>$.s!==P);if(T===-1)break;let[N]=A.splice(T,1);C-=N.b,await h(`${p}${N.s}`)}return A},x=w=>{j(async()=>{let P=await y(),A=P.find(C=>C.s===w);A&&(A.u=c(),await L(P))})},E=w=>j(async()=>{await h(`${p}${w}`);let P=await y(),A=P.filter(C=>C.s!==w);A.length!==P.length&&await L(A)});return{keyFor:g,read(w,P){let A=`${w}/${P}`;return d_(m(g(w,P)),C=>{if(!C)return null;let T;try{T=JSON.parse(C)}catch{return f(g(w,P)),E(A),null}return!T||T.v!==rr||T.user!==n||c()-T.at>i||!Wl(T.e)?(f(g(w,P)),E(A),null):(x(A),T.e)})},write(w,P,A){let C=`${w}/${P}`;if(!Wl(A))return E(C);let T={v:rr,user:n,at:c(),e:A},N=g_(T,s);if(N===null)return E(C);let $=m_(A);return j(async()=>{let K=await y(),q=K.find(_e=>_e.s===C);if(q&&$>0&&q.c>$)return;let ue=K.filter(_e=>_e.s!==C),le={s:C,b:N.length,u:c(),c:$},qe=await _([...ue,le],C),at=g(w,P);try{await t.setItem(at,N)}catch{let _e=qe.filter(Pe=>Pe.s!==C).sort((Pe,ie)=>Pe.u-ie.u)[0];_e&&(await h(`${p}${_e.s}`),qe=qe.filter(Pe=>Pe.s!==_e.s));try{await t.setItem(at,N)}catch{await h(at),qe=qe.filter(Pe=>Pe.s!==C)}}await L(qe)})},remove(w,P){return E(`${w}/${P}`)},clear(){return j(async()=>{let w=await y();for(let P of w)await h(`${p}${P.s}`);await h(d)})}}}var Hl=null;function CC(e){Hl=e}function Vl(){return Hl}var f_=new Set;function zl(e){for(let t of f_)try{t(e)}catch{}}function UC(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 FC=50,y_=200,LC=y_;function Yl(e){let t=new URLSearchParams;e?.scope&&e.scope!=="visible"&&t.set("scope",e.scope),e?.limit!==void 0&&t.set("limit",String(e.limit)),e?.cursor&&t.set("cursor",e.cursor),e?.parent&&t.set("parent",e.parent),e?.startedBy&&t.set("started_by",e.startedBy);let n=e?.q?.trim();n&&t.set("q",n);for(let r of e?.labels??[])t.append("label",r);return t.size>0?`?${t}`:""}async function Ql(e,t){let n=await l.get(`/projects/${e}/sessions${Yl(t)}`);return{items:u(n),next_cursor:n.headers?.get("x-next-cursor")??null}}async function yt(e,t){return u(await l.get(`/projects/${e}/sessions${Yl(t)}`))}async function Xl(e,t,n){return u(await l.put(`/projects/${e}/sessions/${t}/sharing`,n))}async function Jl(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/participants`,{showErrors:!1}))}async function Zl(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/watch`,{showErrors:!1}))}async function eu(e,t,n){return u(await l.put(`/projects/${e}/sessions/${t}/watch`,{watching:n}))}function NC(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 KC(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 tu(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/previews`))}async function nu(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/public-shares`,{showErrors:!1}))}async function ru(e,t,n){return u(await l.post(`/projects/${e}/sessions/${t}/public-shares`,n))}async function ou(e,t,n){return u(await l.delete(`/projects/${e}/sessions/${t}/public-shares/${n}`))}async function ht(e,t){let n=u(await l.post(`/projects/${e}/sessions`,t??{}));return t?.initial_prompt||nr(n?.session_id),n}async function su(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||nr(r.session.session_id),r}async function iu(e,t){let n=u(await l.post(`/projects/${e}/sessions/warm/claim`,t,{showErrors:!1}));return nr(n.session_id),n}async function or(e,t,n){return u(await l.get(`/projects/${e}/sessions/${t}`,{showErrors:n?.showErrors}))}async function au(e,t,n,r){let o=new URLSearchParams;n&&o.set("limit",String(n)),r?.cursor&&o.set("cursor",r.cursor),r?.includeEvents!=null&&o.set("include_events",String(r.includeEvents));let s=o.toString();return u(await l.get(`/projects/${e}/sessions/${t}/audit${s?`?${s}`:""}`,{showErrors:r?.showErrors}))}async function cu(e,t,n){let r=new URLSearchParams;n?.limit!=null&&r.set("limit",String(n.limit)),n?.chars!=null&&r.set("chars",String(n.chars));let o=r.toString();return u(await l.get(`/projects/${e}/sessions/${t}/transcript${o?`?${o}`:""}`))}async function lu(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 uu(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/turn`))}async function qC(e,t,n){let r=new URLSearchParams;n?.transcript!=null&&r.set("transcript",String(n.transcript));let o=r.toString();return u(await l.get(`/projects/${e}/sessions/${t}/snapshot${o?`?${o}`:""}`,{signal:n?.signal,showErrors:!1}))}function h_(e){if(e)return e==="interrupt"?"transcript":"composer"}async function sr(e,t,n){let r=n.placement??h_(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 pu(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/prompts`,{showErrors:!1}))}async function du(e,t,n){return u(await l.delete(`/projects/${e}/sessions/${t}/prompts/${n}`,{showErrors:!1})).removed}async function gu(e,t,n,r){return u(await l.patch(`/projects/${e}/sessions/${t}/prompts/${n}`,{text:r},{showErrors:!1}))}async function mu(e,t,n){return u(await l.patch(`/projects/${e}/sessions/${t}/prompts/${n}`,{delivery:"interrupt"},{showErrors:!1}))}async function fu(e,t,n){return u(await l.post(`/projects/${e}/sessions/${t}/prompts/${n}/retry`,{},{showErrors:!1}))}async function yu(e,t,n){return u(await l.post(`/projects/${e}/sessions/${t}/prompts/hold`,{held:n},{showErrors:!1}))}async function hu(e,t,n){return u(await l.patch(`/projects/${e}/sessions/${t}`,n))}async function bu(e,t){let n=u(await l.delete(`/projects/${e}/sessions/${t}`));return Vl()?.remove(e,t),n}async function ir(e,t,n={}){return u(await l.post(`/projects/${e}/sessions/${t}/restart`,n.reset_machine?{reset_machine:!0,...n.discard_state?{discard_state:!0}:{}}:{}))}async function ar(e,t){let n=u(await l.post(`/projects/${e}/sessions/${t}/stop`,{}));return zl(t),n}async function _u(e,t){return u(await l.get(`/projects/${e}/sessions/${encodeURIComponent(t)}/config`,{showErrors:!1}))}function b_(e){let t=e.split(`
7
+ `);let m=e_(g);if(m){if(t(m),m.type==="error")throw new b(m.error,{status:m.status,code:m.code});m.type==="done"&&(a=m.project)}}}}finally{o.cancel().catch(()=>{})}if(!a)throw new Error("Provision stream ended without a result");return a}async function AC(){try{return u(await l.get("/projects/managed-git/status",{showErrors:!1}))}catch{return{configured:!1,provider:"github"}}}async function er(e,t){return u(await l.patch(`/projects/${e}`,t))}async function Ra(e,t,n){return u(await l.patch(`/projects/${e}/features`,{feature:t,enabled:n}))}async function Ca(e,t,n){return u(await l.patch(`/projects/${e}/experimental`,{feature:t,enabled:n}))}async function Ia(e,t){return u(await l.patch(`/projects/${e}/sandbox-provider`,{provider:t}))}async function vC(e,t){return u(await l.get(`/projects/${e}/sandbox-provider/transition`,{showErrors:!1,...t}))}async function kC(e,t){throw U("updateTemplateWarmPool")}async function Ta(e,t){return u(await l.patch(`/projects/${e}/onboarding`,{completed:t}))}async function RC(e,t){return u(await l.patch(`/projects/${e}/onboarding`,{profile:t}))}async function tr(e){return u(await l.delete(`/projects/${e}`))}async function CC(e,t){return bt(e,`/v1/projects?account_id=${encodeURIComponent(t)}`)}async function IC(e,t){if(!e.backendUrl||!e.accessToken)return{ok:!1,limitReached:!1};let n=wo(e.backendUrl);try{let r=await fetch(`${n}/v1/projects/provision`,{method:"POST",headers:{Authorization:`Bearer ${e.accessToken}`,"Content-Type":"application/json"},body:JSON.stringify({seed_starter:!0,...t}),signal:AbortSignal.timeout(e.timeoutMs??9e4)});if(r.ok){let o=await r.json().catch(()=>null);return o?.project_id?{ok:!0,project:o}:{ok:!1,limitReached:!1}}return r.status===403?{ok:!1,limitReached:(await r.json().catch(()=>null))?.code==="project_limit_reached"}:{ok:!1,limitReached:!1}}catch{return{ok:!1,limitReached:!1}}}async function Ea(e,t,n){return u(await l.post(`/projects/${e}/skills`,t,{showErrors:!1,...n}))}async function Ma(e){return u(await l.post("/projects/link-repository",e,{showErrors:!1}))}async function Oa(e){let{project_id:t,...n}=e;return u(await l.put(`/projects/${encodeURIComponent(t)}/git/repository`,n,{showErrors:!1}))}async function Da(e){return u(await l.get(`/projects/github/installation?account_id=${encodeURIComponent(e)}`,{showErrors:!1}))}async function ja(e){return u(await l.get(`/projects/github/installations?account_id=${encodeURIComponent(e)}`,{showErrors:!1}))}async function $a(e){return u(await l.post("/projects/github/installations/linkable",e,{showErrors:!1}))}async function Ua(e,t,n){let r=new URLSearchParams({account_id:e});t&&r.set("installation_id",t);let o=n?.search?.trim();return o&&r.set("search",o),n?.limit!==void 0&&r.set("limit",String(n.limit)),u(await l.get(`/projects/github/repositories?${r.toString()}`,{showErrors:!1}))}async function La(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 Fa(e){return u(await l.post("/projects/github/installation",e,{showErrors:!1}))}async function Na(e){return u(await l.post("/projects/github/installations/link",e,{showErrors:!1}))}async function Ka(e){return u(await l.post("/projects/github/user-token",e,{showErrors:!1}))}async function qa(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 Ba(){return u(await l.get("/projects/git/backend",{showErrors:!1}))}async function Ga(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 qC(e,t){return u(await l.post(`/projects/${e}/access-requests`,{message:t?.trim()||void 0},{showErrors:!1}))}async function Wa(e,t){return u(await l.get(`/projects/${e}/access-requests`,t))}async function Ha(e,t,n="member"){return u(await l.post(`/projects/${e}/access-requests/${t}/approve`,{role:n}))}async function Va(e,t){return u(await l.post(`/projects/${e}/access-requests/${t}/reject`,{}))}async function za(e){return u(await l.get(`/projects/${e}/access`))}async function Ya(e,t,n){return u(await l.put(`/projects/${e}/access/${t}`,{role:n}))}async function Qa(e,t){return u(await l.delete(`/projects/${e}/access/${t}`))}function BC(e){return"status"in e&&e.status==="invited"}async function Xa(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 Ja(e){return u(await l.get(`/projects/${e}/access/pending-invites`))}async function Za(e,t){return u(await l.delete(`/projects/${e}/access/pending-invites/${t}`))}async function ec(e,t){return u(await l.post(`/projects/${e}/access/pending-invites/${t}/resend`))}async function tc(e){return u(await l.get(`/projects/${e}/group-grants`))}async function nc(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 rc(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 oc(e,t){return u(await l.delete(`/projects/${e}/group-grants/${t}`))}async function sc(e){return u(await l.get(`/projects/${e}/resource-grants`))}async function ic(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 ac(e,t){return u(await l.delete(`/projects/${e}/resource-grants/${t}`))}async function cc(e,t){return u(await l.get(`/projects/${e}/approvals`,{showErrors:t?.showErrors}))}async function lc(e,t){return u(await l.get(`/projects/${e}/approvals/needs-input`,{showErrors:t?.showErrors}))}async function uc(e,t,n,r={}){let o=r.note?.trim();return u(await l.post(`/projects/${e}/approvals/${t}`,{decision:n,...o?{note:o}:{}}))}async function pc(e){return u(await l.get(`/projects/${e}/secrets`,{showErrors:!1}))}async function dc(e,t){return u(await l.post(`/projects/${e}/secrets`,t))}async function gc(e,t,n,r={}){return u(await l.put(`/projects/${e}/secrets/${encodeURIComponent(t)}/strategy`,{strategy:n,...r}))}async function mc(e,t,n){return u(await l.post(`/projects/${e}/secrets/${encodeURIComponent(t)}/broker`,n))}async function fc(e){return u(await l.get(`/projects/${e}/oauth`)).items??[]}async function Ao(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 vo(e,t,n){return u(await l.post(`/projects/${e}/oauth/${t}/poll`,{flow_id:n}))}async function yc(e,t){return u(await l.delete(`/projects/${e}/oauth/${encodeURIComponent(t)}`))}var t_=2e3,n_=3e3,r_=10*6e4;async function VC(e){let{projectId:t,provider:n,input:r,onChallenge:o,isCancelled:s,sleep:i=m=>new Promise(f=>setTimeout(f,m)),now:a=()=>Date.now()}=e,c=()=>s?.()??!1,p=await Ao(t,n,r);if(c())return{status:"cancelled"};o?.({verification_url:p.verification_url,user_code:p.user_code});let d=Math.max(t_,p.interval_ms||n_),g=p.expires_at||a()+r_;for(;!c()&&a()<g;){if(await i(d),c())return{status:"cancelled"};let m;try{m=await vo(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 hc(e,t){return u(await l.put(`/projects/${e}/git-credential`,t))}async function bc(e,t){return u(await l.delete(`/projects/${e}/secrets/${encodeURIComponent(t)}`))}async function _c(e,t,n){return u(await l.put(`/projects/${e}/secrets/${encodeURIComponent(t)}/personal`,n))}async function Pc(e,t){return u(await l.delete(`/projects/${e}/secrets/${encodeURIComponent(t)}/personal`))}var ko=e=>`/accounts/${encodeURIComponent(e)}/secret-resources`,Pt=(e,t)=>`${ko(e)}/${encodeURIComponent(t)}`,xc=(e,t,n)=>`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/provider-secret-pools/${encodeURIComponent(n)}`;async function Sc(e,t){let n=t?`?project_id=${encodeURIComponent(t)}`:"";return u(await l.get(`${ko(e)}${n}`))}async function wc(e,t){return u(await l.post(ko(e),t))}async function Ac(e,t,n){return u(await l.put(`${Pt(e,t)}/value`,{value:n}))}async function vc(e,t){return u(await l.post(`${Pt(e,t)}/retry`))}async function kc(e,t){return u(await l.delete(Pt(e,t)))}async function Rc(e,t,n,r){return u(await l.put(`${Pt(e,t)}/grants/${encodeURIComponent(n)}`,{},r))}async function Cc(e,t,n,r){return u(await l.delete(`${Pt(e,t)}/grants/${encodeURIComponent(n)}`,r))}async function Ic(e,t,n,r){return u(await l.put(`${Pt(e,t)}/access`,{mode:n,user_ids:r}))}async function Tc(e,t,n){return u(await l.get(xc(e,t,n)))}async function Ec(e,t){let n=`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/provider-secret-pools`;return u(await l.get(n))}async function Mc(e,t,n,r){return u(await l.put(xc(e,t,n),{secret_ids:r}))}async function Ro(){return So()}async function o_(e){return Nn(()=>v().getToken(),e,Co)}function Co(){Wt()}function nI(e){e===null&&Wt()}function rI(e){}async function Ht(){return Ro()}async function oI(e){return o_(e)}async function E(e,t,n){try{return await Ze(e,t,{retryOnAuthError:n?.retryOnAuthError,timeoutMs:n?.timeoutMs})}catch(r){if(r instanceof te)return Kn();throw r}}function nr(e,t){return e?`/connectors/projects/${encodeURIComponent(e)}/${t}`:`/connectors/${t}`}async function Vt(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(`${nr(e,"catalog")}${r}`)).connectors??[]}async function Io(e){let t=[];for(let n of await Vt(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 Oc(e,t="",n={}){let r=t.trim().toLowerCase(),o=r.split(/\s+/).filter(Boolean),s=[],i=[];for(let a of await Io(e)){let c=`${a.tool} ${a.description}`.toLowerCase();!r||c.includes(r)?s.push(a):o.every(p=>c.includes(p))&&i.push(a)}return[...s,...i].slice(0,n.limit??20)}async function To(e,t){let n=t.indexOf(".");if(n<0)return null;let r=t.slice(0,n).trim();if(!r)return null;let o=(await Vt(e,{slug:r,includeSchemas:!0,includeOutputSchemas:!0})).find(s=>s.slug===r);if(!o)return null;for(let s of o.actions){let i=`${o.slug}.${s.path}`;if(i===t)return{tool:i,connector:o.slug,action:s.path,risk:s.risk,description:s.description||s.name,inputSchema:s.inputSchema,outputSchema:s.outputSchema??null}}return null}function s_(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 i_=9e4;async function xt(e,t,n={},r={}){let{connector:o,action:s}=s_(t),i=r.account?.trim(),a=r.approvalContext?.trim(),c=u(await l.post(nr(e,"call"),{connector:o,action:s,args:n,...i?{account:i}:{},...a?{approval_context:a}:{}},{timeout:r.timeoutMs??i_,signal:r.signal}));return c.ok&&c.binding!==void 0&&!("output"in c)&&(c.output=c.data),c}async function Eo(e,t){let n=await l.get(nr(e,`connectors/${encodeURIComponent(t)}/accounts`));return u(n).accounts??[]}function a_(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 c_(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(),o=n.contentType.trim();if(!r)throw new Error("filename is required");if(!o)throw new Error("contentType is required");let s={"Content-Type":o,"X-Kortix-Attachment-Filename":encodeURIComponent(r),"X-Kortix-Attachment-Disposition":n.contentDisposition??"attachment"};n.contentId?.trim()&&(s["X-Kortix-Attachment-Content-Id"]=encodeURIComponent(n.contentId.trim())),n.connector?.trim()&&(s["X-Kortix-Attachment-Connector"]=encodeURIComponent(n.connector.trim()));let i=c_(v().backendUrl),a=nr(e,"attachments"),c=await E(`${i}${a}`,{method:"POST",headers:s,body:t},{timeoutMs:6e4}),p=await c.text(),d=null;if(p)try{d=JSON.parse(p)}catch{d=p}if(!c.ok)throw new b(a_(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 pI(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 Dc(e){return u(await l.get(`/projects/${e}/connections`))}async function jc(e){return u(await l.get(`/projects/${e}/connections/all`))}async function $c(e,t){return u(await l.post(`/projects/${e}/connections`,t))}async function Uc(e,t){return u(await l.post(`/projects/${e}/connections/me`,t))}async function Lc(e,t,n){return u(await l.put(`/projects/${e}/connections/${t}/credential`,n))}function Te(e,t,n){return`/projects/${e}/connections/${t}/oauth2/${n}`}async function dI(e,t){return u(await l.post(`/projects/${e}/connectors/${encodeURIComponent(t)}/oauth2/connection`,{}))}async function gI(e,t,n){return u(await l.put(Te(e,t,"application"),n))}async function mI(e,t){return u(await l.get(Te(e,t,"application")))}async function fI(e,t,n){return u(await l.post(Te(e,t,"discover"),n))}async function yI(e,t,n={}){return u(await l.post(Te(e,t,"discover-resource"),n))}async function hI(e,t,n){return u(await l.post(Te(e,t,"register"),n))}async function bI(e,t,n){return u(await l.post(Te(e,t,"authorize"),n))}async function _I(e,t,n){return u(await l.post(Te(e,t,"device"),n))}async function PI(e,t,n){return u(await l.post(Te(e,t,`device/${encodeURIComponent(n)}`),{}))}async function xI(e,t){return u(await l.get(Te(e,t,"status")))}async function Fc(e,t){return u(await l.put(`/projects/${e}/connections/${t}/revoke`,{}))}async function Nc(e,t){return u(await l.put(`/projects/${e}/connections/${t}/activate`,{}))}async function Kc(e,t){return u(await l.put(`/projects/${e}/connections/${t}/default`,{}))}async function qc(e,t,n){return u(await l.put(`/projects/${e}/connections/${t}/label`,{label:n}))}async function Bc(e,t){return u(await l.post(`/projects/${e}/computers`,{tunnel_id:t.tunnelId,...t.share?{share:t.share}:{}}))}async function Gc(e,t,n=[]){return u(await l.post(`/projects/${e}/connections/${t}/share`,{principals:n}))}async function Wc(e,t,n={}){return u(await l.post(`/projects/${e}/connections/${t}/connect`,n))}async function Hc(e,t){return u(await l.post(`/projects/${e}/connections/${t}/connect/finalize`,{}))}async function Vc(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 zc(e){return u(await l.post(`/connectors/projects/${e}/connectors/sync`,{}))}async function Yc(e,t,n){return u(await l.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/credential-mode`,{mode:n}))}async function Qc(e,t,n){return u(await l.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/authorization-strategy`,{authorization_strategy:n}))}async function Xc(e,t,n){return u(await l.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/sensitive`,{sensitive:n}))}async function Jc(e,t){return u(await l.get(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/policies`))}async function Zc(e,t,n){return u(await l.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/policies`,{policies:n}))}async function SI(e,t){throw new Error("Connection-specific policies were removed. Use getConnectorPolicies(projectId, slug).")}async function wI(e,t,n){throw new Error("Connection-specific policies were removed. Use setConnectorPolicies(projectId, slug, policies).")}async function el(e,t){return u(await l.get(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/config`))}async function tl(e,t,n){return u(await l.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/name`,{name:n}))}async function l_(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 nl=l_;async function AI(e,t){return u(await l.get(`/connectors/projects/${e}/sessions/${encodeURIComponent(t)}/connect-requests`)).connectors??[]}async function rl(e,t){return u(await l.post(`/connectors/projects/${e}/connectors`,t))}async function ol(e,t){return u(await l.post(`/connectors/projects/${e}/connectors/auth-discovery`,t))}async function sl(e,t){return u(await l.delete(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}`))}async function il(e,t,n){let r=typeof t=="string"||t===void 0?{...t?{q:t}:{},...n?{cursor:n}:{}}:t,o=new URLSearchParams;r.q&&o.set("q",r.q),r.category&&o.set("category",r.category),r.cursor&&o.set("cursor",r.cursor),r.limit&&o.set("limit",String(r.limit));let s=o.toString();return u(await l.get(`/connectors/projects/${e}/pipedream/apps${s?`?${s}`:""}`))}async function al(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 vI(e,t={}){let n=new URLSearchParams;t.q&&n.set("q",t.q),t.category&&n.set("category",t.category),t.cursor&&n.set("cursor",t.cursor),t.limit&&n.set("limit",String(t.limit));let r=n.toString(),o=u(await l.get(`/connectors/projects/${e}/connect/toolkits${r?`?${r}`:""}`));if("toolkits"in o)return o;let s=o.cursor?.trim()||void 0;return{provider:"composio",toolkits:o.items,nextCursor:s,hasMore:!!s}}async function kI(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 Oo(e,t,n){let r=typeof t=="string"||t===void 0?{...t?{q:t}:{},...n?{cursor:n}:{}}:t,o=new URLSearchParams;r.q&&o.set("q",r.q),r.category&&o.set("category",r.category),r.cursor&&o.set("cursor",r.cursor),r.limit&&o.set("limit",String(r.limit));let s=o.toString();return u(await l.get(`/connectors/projects/${e}/discover/connectors${s?`?${s}`:""}`))}async function cl(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 Do(e,t){let n=new URLSearchParams({id:t});return u(await l.get(`/connectors/projects/${e}/discover/connectors/detail?${n.toString()}`))}var RI=Oo,CI=Do;async function ll(){return u(await l.get("/connectors/connect-status"))}async function ul(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 pl(e,t){return u(await l.delete(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/credential`))}async function II(e,t,n){return u(await l.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/secret-binding`,{secret_identifier:n}))}async function u_(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 dl=u_;var rr=class extends b{reason;connector;action;binding;upstreamStatus;retryAfterSeconds;connectUrl;hint;availableAccounts;requestedAccount;constructor(t,n){let{reason:r,connector:o,action:s,binding:i,upstreamStatus:a,retryAfterSeconds:c,connectUrl:p,hint:d,availableAccounts:g,requestedAccount:m,...f}=n;super(t,{...f,name:"ConnectorCallError"}),this.reason=r,this.connector=o,this.action=s,this.binding=i??null,this.upstreamStatus=a??null,this.retryAfterSeconds=c??null,this.connectUrl=p??null,this.hint=d??null,this.availableAccounts=g??[],this.requestedAccount=m??null}},jo=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,o){super(`${t}.${n} has more than ${r} pages; resume with nextArgs`),this.name="ConnectorPageLimitError",this.connector=t,this.action=n,this.maxPages=r,this.nextArgs=o,Object.setPrototypeOf(this,new.target.prototype)}},be=e=>typeof e=="string"&&e?e:null;function gl(e){return/^([a-z][a-z0-9_]*)(?::|$)/.exec(e)?.[1]??"connector_error"}function p_(e){let t=e?.headers?.get("retry-after");return t&&/^\d+$/.test(t.trim())?Number(t):null}function d_(e,t,n){if(!(e instanceof b)||typeof e.status!="number")return e;let r=e.details&&typeof e.details=="object"?e.details:{},o=be(r.reason)??be(r.error)??e.message,s=/^upstream_(\d{3})\b/.exec(o),i=typeof r.upstream_status=="number"?r.upstream_status:s?Number(s[1]):null;return new rr(be(r.message)??be(r.hint)??o,{status:e.status,code:i===null?gl(o):`upstream_${i}`,details:e.details,data:e.details,response:e.response,reason:o,connector:be(r.connector)??t,action:be(r.action)??n,binding:be(r.binding),upstreamStatus:i,retryAfterSeconds:typeof r.retry_after_seconds=="number"?r.retry_after_seconds:p_(e.response),connectUrl:be(r.connect_url),hint:be(r.hint),availableAccounts:Array.isArray(r.available_accounts)?r.available_accounts:[],requestedAccount:be(r.requested_account)})}function g_(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 Uo(e,t,n,r={},o={}){let s=t.trim(),i=n.trim();if(!s||!i)throw new Error("connector slug and action are required");let a;try{a=await xt(e,`${s}.${i}`,r,o)}catch(c){throw d_(c,s,i)}if(a.status==="pending_approval")throw new jo(s,i,a);if(!a.ok||a.upstream_error){let c=a.upstream_error??a.reason??"connector_error";throw new rr(c,{status:200,code:a.upstream_error?"upstream_error":gl(c),details:a,data:a,reason:c,connector:s,action:i,binding:a.binding??null,upstreamStatus:a.upstream_status??null})}return g_(a)}async function*ml(e,t,n,r,o){let{next:s,maxPages:i=100,...a}=o,c=r;for(let p=0;c;p++){if(p>=i)throw new $o(t,n,i,c);let d=await Uo(e,t,n,c,a);yield d,c=s(d,c)}}async function fl(e){return u(await l.get(`/connectors/projects/${e}/policies`))}async function yl(e,t,n){return u(await l.put(`/connectors/projects/${e}/policies`,{policies:t,defaultMode:n}))}async function hl(e){return u(await l.get(`/projects/${e}/sandboxes`))}async function bl(e){return u(await l.get(`/projects/${e}/snapshots`))}async function or(e){return u(await l.get(`/projects/${e}/sandbox-health`,{showErrors:!1,timeout:15e3}))}async function _l(e,t){return u(await l.post(`/projects/${e}/snapshots/rebuild`,t?{slug:t}:{}))}async function Pl(e){return u(await l.post(`/projects/${e}/snapshots/fix-with-agent`,{}))}async function xl(e,t){return u(await l.post(`/projects/${e}/sandbox-templates`,t))}async function Sl(e,t,n){return u(await l.patch(`/projects/${e}/sandbox-templates/${t}`,n))}async function wl(e,t){return u(await l.delete(`/projects/${e}/sandbox-templates/${t}`))}async function Al(e,t){return u(await l.post(`/projects/${e}/sandbox-templates/${t}/build`,{}))}async function vl(e){return u(await l.get(`/projects/${e}/sandboxes`))}async function sr(e){let t=new URL(v().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 Vn(e);return{url:e,headers:Object.fromEntries(r.entries())}}async function kl(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 Rl(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"),u(await l.get(`/projects/${e}/files?${n.toString()}`,{showErrors:!1}))}async function Cl(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 Il(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 m_=10*6e4;async function Tl(e,t,n){let r=new URLSearchParams;t&&r.set("ref",t),n&&r.set("path",n);let o=r.toString()?`?${r.toString()}`:"",s=`${v().backendUrl||""}/projects/${e}/files/archive${o}`;return await(await Re(s,{method:"GET"},{timeoutMs:m_},"Failed to download")).blob()}async function El(e,t,n){let r=new URLSearchParams;t&&r.set("ref",t),n&&r.set("path",n);let o=r.toString()?`?${r.toString()}`:"";return sr(`${v().backendUrl}/projects/${encodeURIComponent(e)}/files/archive${o}`)}async function zI(e,t,n,r){let o=new URLSearchParams({path:t});n&&o.set("ref",n);let s=o.toString()?`?${o.toString()}`:"",i=`${v().backendUrl||""}/projects/${e}/files/raw${s}`;return await(await Re(i,{method:"GET",...r?.signal?{signal:r.signal}:{}},{},"Failed to read file")).blob()}var Lo=52428800,f_=104857600,Ml=20;var ar=e=>`/projects/${encodeURIComponent(e)}/attachments`,cr={showErrors:!1,deadlineCoversBody:!0},Ol=3e4,y_=12e4,h_=6e4,b_=5*6e4,__=6e4,P_=6e4;function ir(){return new b("Request aborted",{name:"AbortError",code:"ABORTED"})}function zt(e){if(e?.aborted)throw ir()}function x_(e){return!(e instanceof b)||e.code==="ABORTED"||e.code==="attachment_budget_exceeded"?!1:e.code==="TIMEOUT"||e.name==="TypeError"||e.status===429||e.status!==void 0&&e.status>=500}async function Yt(e,t,n=!1){let r;for(let o=0;;o++){zt(t);try{return await e()}catch(s){let i=n&&s instanceof b&&s.status===409&&s.code==="attachment_processing";if(t?.aborted||!(x_(s)||i))throw s;r??=Date.now()+(n?b_:h_);let a=Math.min(8e3,500*2**o)*(.5+Math.random()/2);if(Date.now()+a>=r)throw s;try{await Bn(a,t)}catch{throw zt(t),s}}}}function S_(e){return!!e&&typeof e=="object"&&!Array.isArray(e)&&Object.values(e).every(t=>typeof t=="string")}function Fo(e,t,n){let r=e?.upload,o=e?.received_bytes,s=Number.isSafeInteger(o)&&o>=0&&o<=t.size,i=r?.kind==="direct"?typeof r.url=="string"&&/^https?:\/\//i.test(r.url)&&r.method==="PUT"&&S_(r.headers)&&Number.isFinite(Date.parse(r.expires_at))&&(o===0||o===t.size):r?.kind==="chunked"&&Number.isSafeInteger(r.chunk_size)&&r.chunk_size>0&&(o===t.size||o%r.chunk_size===0);if(!e?.attachment_id||n!==void 0&&e.attachment_id!==n||e.size!==t.size||!s||!i)throw new Error("Invalid attachment upload handle");return e}async function Dl(e,t,n,r){return u(await l.post(ar(e),{...r?{attachment_id:r}:{},filename:t.name,mime:t.type||"application/octet-stream",size:t.size},{...cr,signal:n,timeout:Ol}),"Failed to start attachment upload")}async function jl(e,t,n,r){let o=Fo({...await Yt(()=>Dl(e,t,r.signal,n.attachment_id),r.signal),received_bytes:0},t,n.attachment_id);return r.onUpload?.(o),o}function $l(e,t){let n;try{n=JSON.parse(t)}catch{}let r=typeof n?.message=="string"?n.message:typeof n?.error=="string"?n.error:`HTTP ${e}`;return new b(r,{status:e,details:n,code:String(n?.statusCode??e)})}function w_(e){if(!(e instanceof b))return;let t=Number(e.details?.statusCode);return Number.isInteger(t)&&t>=400?t:e.status}function A_(e,t,n,r){return new Promise((o,s)=>{let i=new e,a=0,c=!1,p,d=f=>{c||(c=!0,p&&clearTimeout(p),r.signal?.removeEventListener("abort",m),f?s(f):o())},g=()=>{p&&clearTimeout(p),p=setTimeout(()=>{d(new b("Attachment upload stalled",{code:"TIMEOUT"})),i.abort()},__)},m=()=>{d(ir()),i.abort()};i.open(t.method,t.url);for(let[f,h]of Object.entries(t.headers))i.setRequestHeader(f,h);i.upload.onprogress=f=>{g(),a=Math.min(f.loaded,n.size),r.onProgress?.(a,n.size)},i.onload=()=>{i.status>=200&&i.status<300?(a<n.size&&r.onProgress?.(n.size,n.size),d()):d($l(i.status,i.responseText))},i.onerror=()=>d(new b("Network error during attachment upload",{name:"TypeError"})),i.onabort=()=>d(ir()),r.signal?.addEventListener("abort",m,{once:!0}),g(),i.send(n)})}async function v_(e,t,n){let r=v().fetch??fetch,o;try{o=await r(e.url,{method:e.method,headers:e.headers,body:t,signal:n.signal,credentials:"omit"})}catch(s){throw n.signal?.aborted||s instanceof Error&&s.name==="AbortError"?ir():new b(s instanceof Error?s.message:String(s),{name:s instanceof Error?s.name:"TypeError"})}if(!o.ok)throw $l(o.status,await o.text().catch(()=>""));n.onProgress?.(t.size,t.size)}function k_(e,t,n){zt(n.signal);let r=globalThis.XMLHttpRequest;return typeof r=="function"?A_(r,e,t,n):v_(e,t,n)}async function R_(e,t,n,r){let o=n,s=!1;for(r.onProgress?.(0,t.size);o.upload.kind==="direct";){let i=o.upload;try{await Yt(()=>k_(i,t,r),r.signal)}catch(a){let c=w_(a);if(c!==409){if(s||!(c===400||c===401||c===403))throw a;s=!0,o=await jl(e,t,o,r);continue}}return o={...o,received_bytes:t.size},r.onUpload?.(o),o}return Ul(e,t,o,r)}async function Ul(e,t,n,r){if(n.upload.kind!=="chunked")throw new Error("Invalid attachment upload handle");let o=n.upload.chunk_size,s=`${ar(e)}/${encodeURIComponent(n.attachment_id)}`,i=n;for(;i.received_bytes<t.size;){zt(r.signal);let a=i.received_bytes,c=Math.min(a+o,t.size),p=t.slice(a,c),d=await Yt(async()=>u(await l.putRaw(`${s}/chunks/${a/o}`,p,{...cr,signal:r.signal,timeout:Ol}),"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 lr(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");zt(n.signal);let r=n.resume?Fo({...n.resume},t):Fo({...await Yt(()=>Dl(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()<P_&&(r=await jl(e,t,r,n)),r=r.upload.kind==="direct"?await R_(e,t,r,n):await Ul(e,t,r,n)),n.onProcessing?.();let o=`${ar(e)}/${encodeURIComponent(r.attachment_id)}`;try{return await Yt(async()=>u(await l.post(`${o}/complete`,{},{...cr,signal:n.signal,timeout:y_}),"Failed to complete attachment upload"),n.signal,!0)}catch(s){throw r.upload.kind==="direct"&&s instanceof b&&s.code==="attachment_not_uploaded"&&n.onUpload?.({...r,received_bytes:0}),s}}async function Qt(e,t,n={}){if(!e)throw new Error("A project is required to remove attachments");let r=await l.delete(`${ar(e)}/${encodeURIComponent(t)}`,{...cr,signal:n.signal});if(!r.success)throw r.error??new Error("Failed to remove attachment")}async function Ll(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 Fl(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 Nl(e,t){return u(await l.get(`/projects/${e}/commits/${encodeURIComponent(t)}`))}async function Kl(e,t,n){let r=new URLSearchParams;n?.path&&r.set("path",n.path);let o=r.toString()?`?${r.toString()}`:"";return u(await l.get(`/projects/${e}/commits/${encodeURIComponent(t)}/diff${o}`))}async function ql(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 Bl(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 Gl(e,t,n){let r=new URLSearchParams;t&&r.set("status",t),n?.originSessionId&&r.set("origin_session_id",n.originSessionId),n?.limit!=null&&r.set("limit",String(n.limit));let o=r.toString()?`?${r.toString()}`:"";return u(await l.get(`/projects/${e}/change-requests${o}`,{showErrors:!1,timeout:15e3}))}async function Wl(e,t){return u(await l.get(`/projects/${e}/change-requests/${t}`))}async function Hl(e,t){return u(await l.get(`/projects/${e}/change-requests/${t}/diff`))}async function Vl(e,t){return u(await l.get(`/projects/${e}/change-requests/${t}/merge-preview`))}async function zl(e,t){return u(await l.post(`/projects/${e}/change-requests`,t))}async function Yl(e,t,n){return u(await l.post(`/projects/${e}/change-requests/${t}/merge`,n??{},{showErrors:!1}))}async function Ql(e,t){return u(await l.post(`/projects/${e}/change-requests/${t}/close`,{}))}async function Xl(e,t){return u(await l.post(`/projects/${e}/change-requests/${t}/reopen`,{}))}async function Jl(e,t,n){return u(await l.post(`/projects/${e}/change-requests/${t}/request-changes`,{feedback:n}))}async function Zl(e,t,n){return u(await l.post(`/projects/${e}/sessions/${t}/commit-push`,n??{}))}async function eu(e,t,n){return u(await l.patch(`/projects/${e}/change-requests/${t}`,n))}var St=new Set,C_=500;function ur(e){e&&(St.add(e),St.size>C_&&St.delete(St.values().next().value))}function tu(e){return!!e&&St.has(e)}function cT(e){e&&St.delete(e)}var pr="kortix.session/2",I_=1,T_=["shell","read","write","edit","patch","list","glob","grep","web_fetch","web_search","todo","task","question","plan","mcp","other"];var Z=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),H=e=>typeof e=="string",_e=e=>H(e)&&e.length>0,Me=e=>e===null||H(e),z=(e,t)=>e===void 0||t(e),Ee=(...e)=>t=>e.includes(t),Xt=e=>Number.isInteger(e)&&e>=0,wt=e=>typeof e=="number",ou=e=>e.schema===pr&&Xt(e.v),et=e=>z(e,H),No=e=>e===void 0||Z(e)&&Object.values(e).every(t=>Z(t)&&H(t.version)),su=e=>e===null||Z(e)&&H(e.provider)&&H(e.model)&&et(e.variant),E_=e=>e===null||Z(e)&&wt(e.input)&&wt(e.output)&&wt(e.cache_read)&&wt(e.cache_write)&&z(e.reasoning,wt)&&z(e.cost,wt),nu=e=>Z(e)&&(e.type==="text"&&H(e.text)||e.type==="attachment"&&H(e.mime)),M_=e=>Z(e)&&Array.isArray(e.content)&&e.content.every(nu)&&z(e.model_content,t=>Array.isArray(t)&&t.every(nu))&&typeof e.is_error=="boolean",ru={text:e=>H(e.text)&&z(e.bytes,Xt)&&et(e.ref)&&(e.ref===void 0||e.bytes!==void 0),reasoning:e=>H(e.text),attachment:e=>H(e.mime)&&et(e.ref)&&z(e.bytes,Xt)&&e.ref===void 0==(e.bytes===void 0),tool_call:e=>H(e.call_id)&&H(e.name)&&_e(e.kind)&&Ee("pending","running","complete","error")(e.status)&&z(e.result,M_),compaction:e=>Me(e.summary)&&Me(e.first_kept_message_id),subtask:e=>H(e.thread_id)&&H(e.agent)&&H(e.description),step:e=>Ee("start","finish")(e.phase),harness:e=>_e(e.harness)&&_e(e.kind)&&typeof e.model_visible=="boolean"};function O_(e,t){if(!Array.isArray(e))return!1;let n=new Set;for(let r of e){if(!Z(r)||!_e(r.id)||n.has(r.id)||!Object.hasOwn(ru,r.type)||!ru[r.type](r)||!No(r.ext)||t&&r.type==="tool_call"&&(r.status==="pending"||r.status==="running"||!r.result))return!1;n.add(r.id)}return!0}function D_(e){return Z(e)&&ou(e)&&_e(e.message_id)&&_e(e.thread_id)&&Number.isInteger(e.seq)&&Ee("user","assistant","system")(e.role)&&Ee("turn","compaction","context")(e.kind)&&Ee("streaming","complete","error","aborted","interrupted")(e.status)&&typeof e.in_context=="boolean"&&z(e.hidden_reason,Ee("failed_attempt","aborted","retracted","reverted","superseded"))&&z(e.origin,Ee("prompt","steer","command","automation","subagent","notification"))&&z(e.agent,Me)&&z(e.reply_to,Me)&&z(e.parent_message_id,Me)&&et(e.native_agent_id)&&et(e.context_ref)&&su(e.model)&&E_(e.usage)&&Ee("stop","tool_calls","length","error","aborted",null)(e.finish)&&(e.error===null||Z(e.error)&&_e(e.error.code)&&H(e.error.message))&&H(e.created_at)&&Me(e.completed_at)&&Z(e.producer)&&_e(e.producer.harness)&&H(e.producer.harness_version)&&H(e.producer.adapter_version)&&No(e.ext)&&O_(e.blocks,e.status!=="streaming"&&e.in_context===!0)}function j_(e){return Z(e)&&ou(e)&&_e(e.thread_id)&&Me(e.parent_thread_id)&&(e.spawned_by===null||Z(e.spawned_by))&&H(e.created_at)}function $_(e){return Z(e)&&z(e.schema,t=>t===pr)&&z(e.v,Xt)&&et(e.session_id)&&z(e.title,Me)&&et(e.created_at)&&z(e.restore_grade,Ee("native","converted","partial"))&&z(e.todos,Array.isArray)&&z(e.pending,t=>Z(t)&&Array.isArray(t.questions)&&Array.isArray(t.permissions))&&z(e.selection,t=>Z(t)&&z(t.agent,Me)&&su(t.model??null))&&z(e.harness,t=>Z(t)&&H(t.current)&&Array.isArray(t.history))&&No(e.ext)}function iu(e){return Z(e)&&Xt(e.generation)&&typeof e.has_more=="boolean"&&$_(e.session)&&Array.isArray(e.threads)&&e.threads.every(j_)&&(e.thread_id===null||_e(e.thread_id))&&Array.isArray(e.messages)&&e.messages.every(t=>D_(t)&&t.thread_id===e.thread_id)}var U_=e=>iu(e)&&e.messages.length>0;function L_(e,t){let{messages:n}=e.e;for(let r=0;r<n.length;r++){let o=JSON.stringify(r===0?e:{...e,e:{...e.e,messages:n.slice(r),has_more:!0}});if(o.length<=t)return o}return null}var au={paintable:U_,fit:L_,capturedAt:()=>0},F_=new WeakMap;function cu(e,t,n){F_.set(e,{read:(r,o)=>t.read(r,o),write:async(r,o,s)=>{await t.write(r,o,s),await n(r,o)}})}function N_(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 dr=1,K_=12,q_=15e5,B_=3e5,G_=336*60*60*1e3,uu="kortix.saved-copy";function Ko(e){return!!e&&typeof e.then=="function"}function W_(e,t){return Ko(e)?e.then(t):t(e)}function H_(e,t){let n=JSON.stringify(e);if(n.length<=t)return n;let{messages:r}=e.e;if(r.length===0)return null;let o=a=>{let c=r.slice(r.length-a);return JSON.stringify({...e,e:{...e.e,messages:c,message_count:c.length,complete:!1,next_cursor:String(c[0].info.id)}})},s=o(1).length-JSON.stringify(r[r.length-1]).length,i=0;for(;i<r.length;){let a=JSON.stringify(r[r.length-1-i]).length+(i>0?1:0);if(s+a>t)break;s+=a,i+=1}for(;i>0;i-=1){let a=o(i);if(a.length<=t)return a}return null}function V_(e){let t=e.captured_at?Date.parse(e.captured_at):Number.NaN;return Number.isFinite(t)?t:0}var z_={paintable:N_,fit:H_,capturedAt:V_};function yT(e){let t=lu(e,z_),n=lu({...e,namespace:`${e.namespace??uu}.log`},au),r={...t,remove:async(o,s)=>{await Promise.all([t.remove(o,s),n.remove(o,s)])},clear:async()=>{await Promise.all([t.clear(),n.clear()])}};return cu(r,n,t.remove),r}function lu(e,t){let{storage:n,userId:r,maxSessions:o=K_,maxBytes:s=q_,maxEnvelopeBytes:i=B_,maxAgeMs:a=G_,namespace:c=uu,now:p=()=>Date.now()}=e,d=`${c}:${r}:`,g=`${d}index`,m=(x,S)=>`${d}${x}/${S}`,f=x=>{try{let S=n.getItem(x);return Ko(S)?S.catch(()=>null):S}catch{return null}},h=x=>{try{let S=n.removeItem(x);Ko(S)&&S.catch(()=>{})}catch{}},P=async x=>{try{await n.removeItem(x)}catch{}},j=x=>{if(!x)return[];try{let S=JSON.parse(x);return S?.v===dr&&Array.isArray(S.entries)?S.entries:[]}catch{return[]}},L=Promise.resolve(),N=x=>{let S=L.then(x,x);return L=S.catch(()=>{}),S},y=async x=>{try{await n.setItem(g,JSON.stringify({v:dr,entries:x}))}catch{}},_=async()=>j(await f(g)),w=async(x,S)=>{let I=[...x].sort((F,M)=>F.u-M.u),C=I.reduce((F,M)=>F+M.b,0);for(;I.length>o||C>s;){let F=I.findIndex(K=>K.s!==S);if(F===-1)break;let[M]=I.splice(F,1);C-=M.b,await P(`${d}${M.s}`)}return I},D=x=>{N(async()=>{let S=await _(),I=S.find(C=>C.s===x);I&&(I.u=p(),await y(S))})},T=x=>N(async()=>{await P(`${d}${x}`);let S=await _(),I=S.filter(C=>C.s!==x);I.length!==S.length&&await y(I)});return{keyFor:m,read(x,S){let I=`${x}/${S}`;return W_(f(m(x,S)),C=>{if(!C)return null;let F;try{F=JSON.parse(C)}catch{return h(m(x,S)),T(I),null}return!F||F.v!==dr||F.user!==r||p()-F.at>a||!t.paintable(F.e)?(h(m(x,S)),T(I),null):(D(I),F.e)})},write(x,S,I){let C=`${x}/${S}`;if(!t.paintable(I))return T(C);let F={v:dr,user:r,at:p(),e:I},M=t.fit(F,i);if(M===null)return T(C);let K=t.capturedAt(I);return N(async()=>{let q=await _(),ge=q.find(Ae=>Ae.s===C);if(ge&&K>0&&ge.c>K)return;let me=q.filter(Ae=>Ae.s!==C),Ci={s:C,b:M.length,u:p(),c:K},we=await w([...me,Ci],C),qt=m(x,S);try{await n.setItem(qt,M)}catch{let Ae=we.filter(Q=>Q.s!==C).sort((Q,ze)=>Q.u-ze.u)[0];Ae&&(await P(`${d}${Ae.s}`),we=we.filter(Q=>Q.s!==Ae.s));try{await n.setItem(qt,M)}catch{await P(qt),we=we.filter(Q=>Q.s!==C)}}await y(we)})},remove(x,S){return T(`${x}/${S}`)},clear(){return N(async()=>{let x=await _();for(let S of x)await P(`${d}${S.s}`);await P(g)})}}}var pu=null;function hT(e){pu=e}function du(){return pu}var Y_=new Set;function gu(e){for(let t of Y_)try{t(e)}catch{}}function vT(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 kT=50,Q_=200,RT=Q_;function mu(e){let t=new URLSearchParams;e?.scope&&e.scope!=="visible"&&t.set("scope",e.scope),e?.limit!==void 0&&t.set("limit",String(e.limit)),e?.cursor&&t.set("cursor",e.cursor),e?.parent&&t.set("parent",e.parent),e?.startedBy&&t.set("started_by",e.startedBy);let n=e?.q?.trim();n&&t.set("q",n);for(let r of e?.labels??[])t.append("label",r);return t.size>0?`?${t}`:""}async function fu(e,t){let n=await l.get(`/projects/${e}/sessions${mu(t)}`);return{items:u(n),next_cursor:n.headers?.get("x-next-cursor")??null}}async function At(e,t){return u(await l.get(`/projects/${e}/sessions${mu(t)}`))}async function yu(e,t,n){return u(await l.put(`/projects/${e}/sessions/${t}/sharing`,n))}async function hu(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/participants`,{showErrors:!1}))}async function bu(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/watch`,{showErrors:!1}))}async function _u(e,t,n){return u(await l.put(`/projects/${e}/sessions/${t}/watch`,{watching:n}))}function CT(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 IT(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 Pu(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/previews`))}async function xu(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/public-shares`,{showErrors:!1}))}async function Su(e,t,n){return u(await l.post(`/projects/${e}/sessions/${t}/public-shares`,n))}async function wu(e,t,n){return u(await l.delete(`/projects/${e}/sessions/${t}/public-shares/${n}`))}async function vt(e,t){let n=u(await l.post(`/projects/${e}/sessions`,t??{}));return t?.initial_prompt||ur(n?.session_id),n}async function Au(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||ur(r.session.session_id),r}async function vu(e,t){let n=u(await l.post(`/projects/${e}/sessions/warm/claim`,t,{showErrors:!1}));return ur(n.session_id),n}async function gr(e,t,n){return u(await l.get(`/projects/${e}/sessions/${t}`,{showErrors:n?.showErrors}))}async function ku(e,t,n,r){let o=new URLSearchParams;n&&o.set("limit",String(n)),r?.cursor&&o.set("cursor",r.cursor),r?.includeEvents!=null&&o.set("include_events",String(r.includeEvents));let s=o.toString();return u(await l.get(`/projects/${e}/sessions/${t}/audit${s?`?${s}`:""}`,{showErrors:r?.showErrors}))}async function Ru(e,t,n){let r=new URLSearchParams;n?.limit!=null&&r.set("limit",String(n.limit)),n?.chars!=null&&r.set("chars",String(n.chars));let o=r.toString();return u(await l.get(`/projects/${e}/sessions/${t}/transcript${o?`?${o}`:""}`))}async function Cu(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 Iu(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/turn`))}async function TT(e,t,n){let r=new URLSearchParams;n?.transcript!=null&&r.set("transcript",String(n.transcript));let o=r.toString();return u(await l.get(`/projects/${e}/sessions/${t}/snapshot${o?`?${o}`:""}`,{signal:n?.signal,showErrors:!1}))}function X_(e){if(e)return e==="interrupt"?"transcript":"composer"}async function mr(e,t,n){let r=n.placement??X_(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 Tu(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/prompts`,{showErrors:!1}))}async function Eu(e,t,n){return u(await l.delete(`/projects/${e}/sessions/${t}/prompts/${n}`,{showErrors:!1})).removed}async function Mu(e,t,n,r){return u(await l.patch(`/projects/${e}/sessions/${t}/prompts/${n}`,{text:r},{showErrors:!1}))}async function Ou(e,t,n){return u(await l.patch(`/projects/${e}/sessions/${t}/prompts/${n}`,{delivery:"interrupt"},{showErrors:!1}))}async function Du(e,t,n){return u(await l.post(`/projects/${e}/sessions/${t}/prompts/${n}/retry`,{},{showErrors:!1}))}async function ju(e,t,n){return u(await l.post(`/projects/${e}/sessions/${t}/prompts/hold`,{held:n},{showErrors:!1}))}async function $u(e,t,n){return u(await l.patch(`/projects/${e}/sessions/${t}`,n))}async function Uu(e,t){let n=u(await l.delete(`/projects/${e}/sessions/${t}`));return du()?.remove(e,t),n}async function fr(e,t,n={}){return u(await l.post(`/projects/${e}/sessions/${t}/restart`,n.reset_machine?{reset_machine:!0,...n.discard_state?{discard_state:!0}:{}}:{}))}async function yr(e,t){let n=u(await l.post(`/projects/${e}/sessions/${t}/stop`,{}));return gu(t),n}async function Lu(e,t){return u(await l.get(`/projects/${e}/sessions/${encodeURIComponent(t)}/config`,{showErrors:!1}))}function J_(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 Pu(e,t,n={}){return u(await l.post(`/projects/${e}/sessions/${encodeURIComponent(t)}/reload`,n,{showErrors:!1}))}async function xu(e,t,n,r,o={}){let s=await l.postStream(`/projects/${e}/sessions/${encodeURIComponent(t)}/reload-stream`,n,o);if(!s.ok){let d=await s.json().catch(()=>null);throw new b(d?.error||`Reload failed: HTTP ${s.status}`,{status:s.status,code:d?.code,data:d})}let i=s.body?.getReader();if(!i)throw new Error("Reload stream is unavailable on this runtime (no response body)");let a=new TextDecoder,c="",p=null;try{for(;;){let{done:d,value:g}=await i.read();if(d)break;c+=a.decode(g,{stream:!0});let m=c.indexOf(`
9
+ `))}catch(n){throw new Error("reloadProjectSessionConfigStream received an invalid SSE frame",{cause:n})}}async function Fu(e,t,n={}){return u(await l.post(`/projects/${e}/sessions/${encodeURIComponent(t)}/reload`,n,{showErrors:!1}))}async function Nu(e,t,n,r,o={}){let s=await l.postStream(`/projects/${e}/sessions/${encodeURIComponent(t)}/reload-stream`,n,o);if(!s.ok){let d=await s.json().catch(()=>null);throw new b(d?.error||`Reload failed: HTTP ${s.status}`,{status:s.status,code:d?.code,data:d})}let i=s.body?.getReader();if(!i)throw new Error("Reload stream is unavailable on this runtime (no response body)");let a=new TextDecoder,c="",p=null;try{for(;;){let{done:d,value:g}=await i.read();if(d)break;c+=a.decode(g,{stream:!0});let m=c.indexOf(`
10
10
 
11
11
  `);for(;m!==-1;){let f=c.slice(0,m);c=c.slice(m+2),m=c.indexOf(`
12
12
 
13
- `);let h=b_(f);if(h){if(r(h),h.type==="error")throw new b(h.error,{status:h.status,code:h.code,data:{reason:h.reason}});h.type==="done"&&(p=h.result)}}}}finally{i.cancel().catch(()=>{})}if(!p)throw new Error("Reload stream ended without a result");return p}async function Su(e,t){return u(await l.get(`/projects/${e}/sessions/${encodeURIComponent(t)}/scope`))}async function wu(e,t,n){return u(await l.put(`/projects/${e}/sessions/${encodeURIComponent(t)}/scope`,n))}async function vu(e,t,n){return u(await l.put(`/projects/${e}/sessions/${encodeURIComponent(t)}/model`,{model:n,opencode_model:n}))}function Au(e){let t=e.metadata?.opencode_model;return typeof t=="string"&&t.trim()?t.trim():null}async function ku(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/message-authors`,{showErrors:!1}))}async function Ru(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/model-usage`,{showErrors:!1}))}function BC(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 Iu(e){return u(await l.get(`/projects/${e}/triggers`))}async function Cu(e,t){return u(await l.post(`/projects/${e}/triggers`,t))}async function Tu(e,t,n){return u(await l.patch(`/projects/${e}/triggers/${t}`,n))}async function Eu(e,t){return u(await l.delete(`/projects/${e}/triggers/${t}`))}async function Mu(e,t){return u(await l.patch(`/projects/${e}/triggers/activation`,{paused:t}))}async function Ou(e,t){return u(await l.post(`/projects/${e}/triggers/${t}/fire`,{}))}async function Du(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 ju(e){return u(await l.get(`/projects/${e}/triggers/event-apps`))}var Oe=new Map;function Mo(e,t){return`${e}::${t}`}function $u(e,t){Oe.delete(e),Oe.set(e,t)}function Uu(e,t){let n=Mo(e,t),r=Oe.get(n);return r&&$u(n,r),r}function Fu(e,t,n){let r=Mo(e,t);if(!Oe.has(r)&&Oe.size>=512){let o=Oe.keys().next().value;o!==void 0&&Oe.delete(o)}$u(r,n)}function Lu(e,t){Oe.delete(Mo(e,t))}function __(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function Gt(){return __(k().backendUrl||"http://localhost:8008/v1")}function Nu(){let e=k().sandboxId;return e?`${Gt()}/p/${e}/8000`:""}function P_(e,t=8e3){return`${Gt()}/p/${e}/${t}`}function ze(e,t=8e3){return P_(e,t)}function nT(e){if(e.status!=="running"||!e.sandbox_id||!e.sandbox_provider||!e.sandbox_url||!(e.runtime_session_id??e.opencode_session_id))return null;let t=e.runtime_session_id??e.opencode_session_id,n=e.sandbox_url.match(/\/p\/([^/]+)\//)?.[1];return n?{stage:"ready",agent_name:e.agent_name??"default",retriable:!0,sandbox:{sandbox_id:e.sandbox_id,session_id:e.session_id,project_id:e.project_id,account_id:e.account_id,provider:e.sandbox_provider,external_id:n,base_url:e.sandbox_url,status:"active",config:{},metadata:e.metadata,last_used_at:e.updated_at,created_at:e.created_at,updated_at:e.updated_at},runtime_session_id:t,opencode_session_id:t,runtime_url:e.sandbox_url}:null}var Oo=class extends Error{status;code;terminal;constructor(t,n){super(t),this.name="SessionStartError",this.status=n.status,this.code=n.code,this.terminal=n.terminal}};function rT(e){return e instanceof Error&&e.name==="SessionStartError"}function x_(e){let t=e,n=t?.status,r=t?.code??t?.details?.code??t?.details?.error,o=t?.message||"Unable to start this session";return n&&n>=400&&n<500&&n!==408&&n!==429?new Oo(o,{status:n,code:r,terminal:!0}):null}function Ku(e,t,n){let r=typeof n=="number"?n:n?.waitMs,o=typeof n=="number"?void 0:n?.repositoryMode,s=new URLSearchParams;r&&r>0&&s.set("wait_ms",String(Math.floor(r))),o&&s.set("repository_mode",o),typeof n=="object"&&n?.keepStopped&&s.set("keep_stopped","1"),typeof n=="object"&&n?.intentAgeMs&&n.intentAgeMs>0&&s.set("intent_age_ms",String(Math.floor(n.intentAgeMs)));let i=s.size>0?`?${s.toString()}`:"";return l.post(`/projects/${e}/sessions/${t}/start${i}`,{},{showErrors:!1})}async function Ye(e,t,n){let r=await Ku(e,t,n);if(!r.success||!r.data){let o=x_(r.error);if(o&&!(o.status===404&&Bl(t)))throw o;return null}return Gu(e,t,r.data)}async function qu(e,t,n){let r=await Ku(e,t,n);if(!r.success||!r.data)throw r.error??new Error("Unable to start this session");return Gu(e,t,r.data)}function Gu(e,t,n){let r=n.sandbox?.external_id,o=n.runtime_session_id??n.opencode_session_id;return n.stage==="ready"&&r&&o&&Fu(e,t,{runtimeSessionId:o,opencodeSessionId:o,runtimeUrl:ze(r),sandboxId:r}),n}function oT(e,t){return["session-start",e,t]}async function Bu(e){return u(await l.get(`/projects/${e}/model-defaults`))}async function Wu(e,t){return u(await l.put(`/projects/${e}/model-defaults`,t))}async function Hu(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 pT(e,t){return u(await l.put(`/projects/${e}/model-enablement`,{modelOverrides:t}))}function Vu(e){let t=[];for(let n of e){let r=n.trim();r&&!t.includes(r)&&t.push(r)}return t}function S_(e,t){if(e.length!==t.length)return!1;let n=new Set(t);return e.every(r=>n.has(r))}function cr(e){let t=e.connectors_required?Vu(e.connectors_required):void 0,n=e.connectors_personal?Vu(e.connectors_personal):void 0;if(t&&n&&!S_(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 zu(e,t,n){let r=cr(n);return u(await l.put(`/projects/${e}/agents/${encodeURIComponent(t)}/scope`,r))}async function xT(e,t){let n=u(await l.get(`/projects/${e}/agents/${encodeURIComponent(t)}/config`));return{...n,block:n.block?Do(n.block):null}}async function ST(e,t,n){let r=Do(n,!0),o=u(await l.put(`/projects/${e}/agents/${encodeURIComponent(t)}/config`,r));return{...o,block:o.block?Do(o.block):null}}function Do(e,t=!1){let n=cr(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 wT(e,t,n){return u(await l.post(`/projects/${e}/secrets/${encodeURIComponent(t)}/grant`,{agent:n}))}async function Yu(e,t){return u(await l.put(`/projects/${e}/default-agent`,{agent:t}))}var Qu="Use createPerSeatCheckout().";function Xu(){return{credits:{total:0,daily:0,monthly:0,extra:0,can_run:!1,daily_refresh:null},subscription:{tier_key:"none",tier_display_name:"No Plan",status:"no_subscription",billing_period:null,provider:"stripe",subscription_id:null,current_period_end:null,cancel_at_period_end:!1,is_cancelled:!1,cancellation_effective_date:null,has_scheduled_change:!1,scheduled_change:null,commitment:{has_commitment:!1,can_cancel:!0,commitment_type:null,months_remaining:null,commitment_end_date:null},can_purchase_credits:!1},models:[],limits:{concurrent_runs:{running_count:0,limit:0,can_start:!1,tier_name:"none"},ai_worker_count:{current_count:0,limit:0,can_create:!1,tier_name:"none"},custom_mcp_count:{current_count:0,limit:0,can_create:!1,tier_name:"none"}},tier:{name:"none",display_name:"No Plan",monthly_credits:0,can_purchase_credits:!1}}}function w_(e){let t=e.trim().toLowerCase();return t===""||t==="free"||t==="none"?"free":t==="enterprise"?"enterprise":"team"}function IT(e){let t=e?.plan;if(t)return{family:t.family,label:t.label,sublabel:t.sublabel??null,isGrandfathered:t.is_grandfathered===!0};let n=e??Xu(),r=(n.subscription?.tier_key||n.tier?.name||"none").toString(),o=(n.tier?.display_name||"").trim()||r;return{family:w_(r),label:o,sublabel:null,isGrandfathered:!1}}async function Ju(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?Xu():t.data}function Zu(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 ep(e){return Ju(`/billing/account-state${Zu(e)}`)}async function tp(e){return Ju(`/billing/account-state/minimal${Zu(e)}`)}async function np(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 rp(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 op(){return u(await l.get("/billing/credit-breakdown"))}async function sp(e){let t=e!=null?`?days=${e}`:"";return u(await l.get(`/billing/usage-history${t}`))}async function ip(){return u(await l.get("/billing/tier-configurations"))}async function CT(e){let t=e.accountId?`?account_id=${encodeURIComponent(e.accountId)}`:"";return pt(e,`/v1/billing/account-state${t}`)}async function ap(e){throw F("createCheckoutSession",Qu)}async function cp(e,t){throw F("confirmCheckoutSession",Qu)}async function lp(e,t){return u(await l.post("/billing/create-portal-session",{account_id:t,return_url:e}),"Failed to create portal session")}async function up(e,t){return u(await l.post("/billing/cancel-subscription",{account_id:t,feedback:e}),"Failed to cancel subscription")}async function pp(e){return u(await l.post("/billing/reactivate-subscription",{account_id:e}),"Failed to reactivate subscription")}async function dp(e,t,n){throw F("scheduleDowngrade","Change the plan in the Stripe customer portal (createPortalSession()).")}async function gp(e){return u(await l.post("/billing/cancel-scheduled-change",{account_id:e}),"Failed to cancel scheduled change")}async function mp(e,t){let n=new URLSearchParams({new_price_id:e});return t&&n.set("account_id",t),u(await l.get(`/billing/proration-preview?${n.toString()}`),"Failed to load proration preview")}async function fp(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 yp(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 TT(e){return u(await l.post(`/accounts/${encodeURIComponent(e)}/top-up-requests`,{}),"Failed to ask the owners for credits")}async function hp(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 ET(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 MT(e){return u(await l.post("/billing/create-per-seat-checkout",{account_id:e.accountId,success_url:e.successUrl,cancel_url:e.cancelUrl,locale:e.locale}),"Failed to create per-seat checkout")}async function OT(e){return u(await l.post("/billing/claim-per-seat",{account_id:e}),"Failed to switch to per-seat billing")}async function DT(e){return u(await l.post("/billing/sync-subscription",{account_id:e}),"Failed to sync subscription")}async function bp(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 jo(e,t){t.accountId&&e.set("account_id",t.accountId),t.projectId&&e.set("project_id",t.projectId)}function lr(e,t){t.from&&e.set("from",t.from),t.to&&e.set("to",t.to)}function ur(e){return e.size>0?`?${e}`:""}async function Pp(e={}){let t=new URLSearchParams;return jo(t,e),e.ownerId&&t.set("owner_id",e.ownerId),lr(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${ur(t)}`))}async function pr(e,t={}){let n=new URLSearchParams;return jo(n,t),u(await l.get(`/usage/session-costs/${encodeURIComponent(e)}${ur(n)}`))}async function NT(e={}){let t=new URLSearchParams;return e.accountId&&t.set("account_id",e.accountId),lr(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${ur(t)}`))}async function KT(e={}){let t=new URLSearchParams;return jo(t,e),e.sessionId&&t.set("session_id",e.sessionId),lr(t,e),u(await l.get(`/usage/cost-summary${ur(t)}`))}function _p(e,t={}){let n=new URLSearchParams;if(t.accountId&&n.set("account_id",t.accountId),t.projectId&&n.set("project_id",t.projectId),e==="sessions"){let o=t;o.ownerId&&n.set("owner_id",o.ownerId)}lr(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`${k().backendUrl||""}${r}?${n}`}async function qT(e,t={}){let n=_p(e==="projects"?"projects":"sessions",t),r=await we(n,{method:"GET"},{timeoutMs:10*6e4},"Failed to export CSV"),o=r.headers.get("x-kortix-row-cap"),s=o!=null?Number(o):NaN;return{blob:await r.blob(),rowCap:Number.isFinite(s)?s:null}}async function xp(e,t){return u(await l.post(`/channels/${e}/identity/bind`,{token:t}),"Failed to connect your account")}function HT(e){return xp("slack",e)}function VT(e){return xp("teams",e)}async function Sp(e,t){return u(await l.post(`/channels/${e}/identity/preview`,{token:t},{showErrors:!1}),"This link is invalid or has expired")}function zT(e){return Sp("slack",e)}function YT(e){return Sp("teams",e)}async function wp(e){let t=await l.get(`/projects/${encodeURIComponent(e)}/channels/slack/installation`,{showErrors:!1});return t.success?t.data??null:null}async function vp(e,t){return u(await l.post(`/projects/${encodeURIComponent(e)}/channels/slack/connect`,t,{showErrors:!1}),"Failed to connect")}var v_={oauth_available:!1,install_url:null};async function Ap(e){let t=await l.get(`/projects/${encodeURIComponent(e)}/channels/slack/mode`,{showErrors:!1});return!t.success||!t.data?v_:t.data}async function kp(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 Rp(e,t){return kp("slack",e,t)}function Ip(e,t){return kp("teams",e,t)}async function Cp(e){return u(await l.get(`/webhooks/slack/${encodeURIComponent(e)}/manifest`,{showErrors:!1}),"Failed to load Slack manifest")}async function Tp(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 Ep(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 Mp(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 $o(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 A_={provider:"agentmail",managed_available:!1};async function Op(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?$o(r.data):null}async function Dp(e){let t=await l.get(`/projects/${encodeURIComponent(e)}/channels/email/mode`,{showErrors:!1});return!t.success||!t.data?A_:t.data}async function jp(e,t){let n=u(await l.post(`/projects/${encodeURIComponent(e)}/channels/email/connect`,t,{showErrors:!1}),"Failed to connect email");return $o(n)}async function $p(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 Up(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 $o(r)}async function QT(e){return u(await l.get(`/projects/${encodeURIComponent(e)}/channels/bindings`,{showErrors:!1}),"Failed to load channel bindings")}async function XT(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 Fp(e){return u(await l.get(`/projects/${e}/gateway/routing-policy`),"Gateway routing policy request failed")}async function Lp(e,t){return u(await l.put(`/projects/${e}/gateway/routing-policy`,t),"Gateway routing policy request failed")}async function Np(e){return u(await l.delete(`/projects/${e}/gateway/routing-policy`),"Gateway routing policy request failed")}async function Kp(e,t){return u(await l.post(`/projects/${e}/gateway/routing-policy/preview`,t),"Gateway route preview failed")}async function qp(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 Gp(e,t){return u(await l.get(`/projects/${e}/gateway/logs/${t}`),"Gateway request failed")}async function Bp(e,t){return u(await l.get(`/projects/${e}/gateway/overview${t?`?days=${t}`:""}`),"Gateway request failed")}async function Wp(e,t){return u(await l.get(`/projects/${e}/gateway/series${t?`?days=${t}`:""}`),"Gateway request failed")}async function Hp(e,t){return u(await l.get(`/projects/${e}/gateway/breakdown${t?`?days=${t}`:""}`),"Gateway request failed")}async function Vp(e,t){return u(await l.get(`/projects/${e}/gateway/sessions${t?`?days=${t}`:""}`),"Gateway request failed")}async function zp(e,t){return u(await l.get(`/projects/${e}/gateway/errors${t?`?days=${t}`:""}`),"Gateway request failed")}async function Yp(e){return u(await l.get(`/projects/${e}/gateway/budgets`),"Gateway request failed")}async function Qp(e,t){return u(await l.put(`/projects/${e}/gateway/budgets`,t),"Gateway request failed")}async function Xp(e,t){return u(await l.delete(`/projects/${e}/gateway/budgets/${t}`),"Gateway request failed")}async function Jp(e){return u(await l.get(`/projects/${e}/gateway/keys`),"Gateway request failed")}async function Zp(e,t){return u(await l.post(`/projects/${e}/gateway/keys`,{name:t}),"Gateway request failed")}async function ed(e,t){return u(await l.delete(`/projects/${e}/gateway/keys/${t}`),"Gateway request failed")}async function td(e,t,n,r,o){return u(await l.post(`/projects/${e}/gateway/playground`,{prompt:t,models:n,...r?{system:r}:{},...o&&Object.keys(o).length?{generationConfig:o}:{}}),"Gateway request failed")}async function tE(e,t){return u(await l.post(`/projects/${e}/gateway/providers/${encodeURIComponent(t)}/verify`,{}),"Gateway provider verification failed")}async function oE(){throw F("getReferralCode")}async function sE(){throw F("refreshReferralCode")}async function iE(e){throw F("validateReferralCode")}async function aE(){throw F("getReferralStats")}async function cE(e={}){throw F("listReferrals")}async function lE(e){throw F("sendReferralEmails")}function O(e){return l.get(e,{showErrors:!1})}function v(e){return u(e,"Unexpected empty response")}async function nd(e){return v(await O(`/accounts/${e}/iam/groups`)).groups}async function rd(e,t){return v(await O(`/accounts/${e}/iam/groups/${t}`))}async function od(e,t){return v(await l.post(`/accounts/${e}/iam/groups`,t,{showErrors:!1}))}async function sd(e,t,n){return v(await l.patch(`/accounts/${e}/iam/groups/${t}`,n))}async function id(e,t){return v(await l.delete(`/accounts/${e}/iam/groups/${t}`))}async function ad(e,t){return v(await O(`/accounts/${e}/iam/groups/${t}/members`)).members}async function cd(e,t,n){return v(await l.post(`/accounts/${e}/iam/groups/${t}/members`,{userIds:n}))}async function yE(e,t){return v(await O(`/accounts/${e}/iam/groups/${t}/project-grants`)).grants}async function ld(e,t,n){return v(await l.delete(`/accounts/${e}/iam/groups/${t}/members/${n}`))}async function hE(e,t){return v(await O(`/accounts/${e}/iam/members/${t}/groups`)).groups}async function bE(e,t){let n=v(await O(`/accounts/${e}/iam/members/${t}/project-access`));return{projects:n.projects,account_wide_policies:n.account_wide_policies??[]}}function De(e){let t=new URLSearchParams;for(let[r,o]of Object.entries(e))o&&t.set(r,String(o));let n=t.toString();return n?`?${n}`:""}async function wE(e,t={}){let n=De({resourceType:t.resourceType,principalType:t.principalType,principalId:t.principalId,projectId:t.projectId});return v(await O(`/accounts/${e}/iam/resource-grants${n}`)).grants}async function IE(e,t={}){let n=De({principalType:t.principalType,principalId:t.principalId,scopeType:t.scopeType,scopeId:t.scopeId===null?"null":t.scopeId});return v(await O(`/accounts/${e}/iam/policies${n}`)).policies}async function CE(e,t){return v(await l.post(`/accounts/${e}/iam/policies`,t,{showErrors:!1}))}async function TE(e,t,n){return v(await l.patch(`/accounts/${e}/iam/policies/${t}`,n,{showErrors:!1}))}async function EE(e,t){return v(await l.delete(`/accounts/${e}/iam/policies/${t}`))}async function ME(e,t){return v(await l.post(`/accounts/${e}/iam/policies:bulk-delete`,{policy_ids:t},{showErrors:!1}))}async function OE(e,t){return v(await l.post(`/accounts/${e}/iam/policies:bulk-import`,{policies:t},{showErrors:!1}))}async function ud(e){return v(await O(`/accounts/${e}/iam/roles`)).roles}async function pd(e){return v(await O(`/accounts/${e}/iam/agent-identities`)).agents}async function dd(e){return v(await l.get(`/projects/${e}/agent-identities`,{showErrors:!1})).agents}async function gd(e,t){return v(await O(`/accounts/${e}/iam/roles/${t}/permissions`))}async function UE(e){return v(await O(`/accounts/${e}/iam/actions`)).actions}async function md(e,t){return v(await O(`/accounts/${e}/iam/roles/${t}/usage`))}async function fd(e,t){return v(await l.post(`/accounts/${e}/iam/roles`,t,{showErrors:!1}))}async function yd(e,t,n){return v(await l.patch(`/accounts/${e}/iam/roles/${t}`,n,{showErrors:!1}))}async function hd(e,t,n){return v(await l.put(`/accounts/${e}/iam/roles/${t}/permissions`,{actions:n},{showErrors:!1}))}async function bd(e,t){return v(await l.delete(`/accounts/${e}/iam/roles/${t}`,{showErrors:!1}))}async function FE(e,t,n){return v(await l.patch(`/accounts/${e}/iam/members/${t}/super-admin`,{isSuperAdmin:n}))}async function qE(e){return v(await O(`/accounts/${e}/iam/scim/tokens`)).tokens}async function GE(e,t){return v(await l.post(`/accounts/${e}/iam/scim/tokens`,t,{showErrors:!1}))}async function BE(e,t){return v(await l.delete(`/accounts/${e}/iam/scim/tokens/${t}`))}async function zE(e){return v(await O(`/accounts/${e}/iam/mfa-required`))}async function YE(e){return v(await O(`/accounts/${e}/iam/mfa-required/preview`))}async function QE(e,t){return v(await l.patch(`/accounts/${e}/iam/mfa-required`,{enabled:t},{showErrors:!1}))}async function XE(e){return v(await O(`/accounts/${e}/iam/session-oversight`))}async function JE(e,t){return v(await l.patch(`/accounts/${e}/iam/session-oversight`,{enabled:t},{showErrors:!1}))}async function nM(e){return v(await O(`/accounts/${e}/iam/sso/provider`)).provider}async function rM(e,t){return v(await l.put(`/accounts/${e}/iam/sso/provider`,t,{showErrors:!1})).provider}async function oM(e,t){return v(await l.post(`/accounts/${e}/iam/sso/provider/from-metadata`,t,{showErrors:!1})).provider}async function sM(e){return v(await l.post(`/accounts/${e}/iam/sso/provider/verify-domain`,{},{showErrors:!1})).provider}async function iM(e){return v(await l.delete(`/accounts/${e}/iam/sso/provider`))}async function aM(e){return v(await O(`/accounts/${e}/iam/sso/mappings`)).mappings}async function cM(e,t){return v(await l.post(`/accounts/${e}/iam/sso/mappings`,t,{showErrors:!1}))}async function lM(e,t){return v(await l.delete(`/accounts/${e}/iam/sso/mappings/${t}`))}async function gM(e){return v(await O(`/accounts/${e}/iam/session-policy`))}async function mM(e,t){return v(await l.patch(`/accounts/${e}/iam/session-policy`,t,{showErrors:!1}))}async function fM(e){return v(await O(`/accounts/${e}/iam/sessions`)).sessions}async function yM(e,t){return v(await l.post(`/accounts/${e}/iam/sessions/${t}/revoke`,{},{showErrors:!1}))}async function hM(e){return v(await O(`/accounts/${e}/iam/pat-policy`))}async function bM(e,t){return v(await l.patch(`/accounts/${e}/iam/pat-policy`,t,{showErrors:!1}))}async function SM(e){return v(await O(`/accounts/${e}/iam/service-accounts`)).service_accounts}async function wM(e,t){return v(await l.post(`/accounts/${e}/iam/service-accounts`,t,{showErrors:!1}))}async function vM(e,t){return v(await l.post(`/accounts/${e}/iam/service-accounts/${t}/disable`,{},{showErrors:!1}))}async function AM(e,t){return v(await l.delete(`/accounts/${e}/iam/service-accounts/${t}`))}async function TM(e){return v(await O(`/accounts/${e}/audit/webhooks`)).webhooks}async function EM(e,t){return v(await l.post(`/accounts/${e}/audit/webhooks`,t,{showErrors:!1}))}async function MM(e,t,n){return v(await l.patch(`/accounts/${e}/audit/webhooks/${t}`,n))}async function OM(e,t){return v(await l.delete(`/accounts/${e}/audit/webhooks/${t}`))}async function DM(e,t={}){let n=De({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 v(await O(`/accounts/${e}/audit${n}`))}async function _d(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),v(await O(`/accounts/${e}/iam/members/${t}/effective?${r.toString()}`))}async function Pd(e,t,n){return n.length===0?[]:v(await l.post(`/accounts/${e}/iam/members/${t}/effective:batch`,{probes:n})).results}async function KM(e){return v(await O(`/accounts/${e}/iam/enterprise-demo`)).enabled}async function qM(e,t){return v(await l.put(`/accounts/${e}/iam/enterprise-demo`,{enabled:t})).enabled}async function xd(e){return u(await l.get(`/accounts/${e}/iam/oauth-clients`,{showErrors:!1}))}async function Sd(e,t){return u(await l.get(`/accounts/${e}/iam/oauth-clients/${t}`,{showErrors:!1}))}async function wd(e,t){return u(await l.post(`/accounts/${e}/iam/oauth-clients`,t,{showErrors:!1}))}async function vd(e,t,n){return u(await l.patch(`/accounts/${e}/iam/oauth-clients/${t}`,n,{showErrors:!1}))}async function Ad(e,t){return u(await l.post(`/accounts/${e}/iam/oauth-clients/${t}/rotate-secret`,{},{showErrors:!1}))}async function kd(e,t){return u(await l.delete(`/accounts/${e}/iam/oauth-clients/${t}`,{showErrors:!1}))}function k_(e){return De({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 Rd(e,t){return u(await O(`/accounts/${e}/iam/assignments${k_(t)}`)).assignments}async function Id(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 Cd(e,t){return u(await l.delete(`/accounts/${e}/iam/assignments/${t}`)).assignment}async function Td(e,t){let n=t?.scopeType?`?scope_type=${t.scopeType}`:"";return u(await O(`/accounts/${e}/iam/permissions${n}`)).permissions}async function eO(){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 tO(e="User requested deletion"){return u(await l.post("/account/request-deletion",{reason:e},{showErrors:!1}),"Failed to request account deletion")}async function nO(){return u(await l.post("/account/cancel-deletion",void 0,{showErrors:!1}),"Failed to cancel account deletion")}async function rO(){return u(await l.delete("/account/delete-immediately",{showErrors:!1}),"Failed to delete account immediately")}async function oO(){return(await l.get("/user-roles",{showErrors:!1})).data??{isAdmin:!1,role:null}}function cO(){return l.get("/admin/api/provider-distribution").then(e=>u(e))}function lO(e=300){return l.get(`/admin/api/sandboxes?limit=${e}`).then(t=>u(t))}function uO(e){return l.put("/admin/api/provider-distribution",e).then(t=>u(t))}function pO(e){return l.get(`/admin/api/provider-analytics?days=${e}`).then(t=>u(t))}function dO(e,t){return l.post(`/admin/api/sandboxes/${encodeURIComponent(e)}/migrate`,{targetProvider:t}).then(n=>u(n))}function gO(){return l.get("/admin/api/provider-fallback").then(e=>u(e))}function mO(e){return l.put("/admin/api/provider-fallback",{enabled:e}).then(t=>u(t))}function fO(){return l.get("/admin/api/boot-modes").then(e=>u(e))}function yO(e){return l.put("/admin/api/boot-modes",e).then(t=>u(t))}var Ed="Export the deck as PDF or PPTX with convertRuntimePresentation().";async function _O(e){throw F("getGoogleAuthUrl",Ed)}async function PO(e,t){throw F("convertPresentationToGoogleSlides",Ed)}async function Md(e,t){let n=new URLSearchParams;t?.segment&&n.set("segment",t.segment),t?.kind&&n.set("kind",t.kind);let r=n.toString();return u(await l.get(`/projects/${e}/review/items${r?`?${r}`:""}`,{showErrors:!1}))}async function Od(e,t){return u(await l.get(`/projects/${e}/review/items/${t}`))}async function Dd(e,t){return u(await l.post(`/projects/${e}/review/items`,t))}async function jd(e,t,n){return u(await l.post(`/projects/${e}/review/items/${t}/act`,n))}async function $d(e,t){return u(await l.post(`/projects/${e}/review/bulk`,t))}var Uo="call:";function AO(e){return e.startsWith("cr:")&&e.length>3?{type:"change_request",changeRequestId:e.slice(3)}:e.startsWith(Uo)&&e.length>Uo.length?{type:"connector_call",executionId:e.slice(Uo.length)}:{type:"review_item",reviewItemId:e}}function R_(e){return e==="needs_you"?"needs_you":e==="waiting"?"waiting":"done"}function kO(e){let t={needs_you:0,waiting:0,done:0};for(let n of e)t[R_(n.status)]+=1;return t}function RO(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 Fo(e){return e.split(/[._-]/).filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function Fd(e){let t=e.indexOf(".");return t<=0?Fo(e):`(${Fo(e.slice(0,t))}) ${Fo(e.slice(t+1))}`}function I_(e){let t=e.indexOf(".");return t>0?{connector:e.slice(0,t),action:e.slice(t+1)}:{connector:e,action:""}}var dr=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{},U=e=>typeof e=="string"&&e?e:void 0,ye=e=>Array.isArray(e)?e:void 0,Ud=e=>typeof e=="number"?e:0,C_=e=>e.split(`
14
- `).map(t=>t.trim()).filter(Boolean);function T_(e,t){let n=dr(e.advanced),r=U(e.description),o=ye(e.whatChanged)??(r?C_(r):t.summary?[t.summary]:[]);return{crId:U(e.cr_id),number:typeof e.number=="number"?e.number:void 0,whatChanged:o,impact:U(e.impact)??"",verification:ye(e.verification)??[],previewUrl:U(e.previewUrl)??U(e.preview_url),conflicts:ye(e.conflicts),requestedChanges:ye(e.requested_changes)??[],advanced:{headRef:U(n.headRef)??U(e.head_ref)??"",baseRef:U(n.baseRef)??U(e.base_ref)??"",headSha:U(n.headSha)??U(e.head_sha)??U(e.head_commit_sha)??"",baseSha:U(n.baseSha)??U(e.base_sha)??"",additions:Ud(n.additions),deletions:Ud(n.deletions),files:ye(n.files)??[],mergeMode:U(n.mergeMode)??"merge"}}}function E_(e,t){let n=ye(e.actions);if(n)return{actions:n.map((c,p)=>({id:U(c.id)??`${t.review_item_id}-${p}`,title:U(c.title)??"Action",connector:U(c.connector)??"",action:U(c.action)??"",consequence:U(c.consequence)??"",risk:U(c.risk)??t.risk,icon:U(c.icon)??"generic",argsPreview:ye(c.argsPreview)??[],policySource:U(c.policySource)??"Requires approval",decided:c.decided==="approved"||c.decided==="denied"?c.decided:void 0}))};let r=U(e.action_path)??"",{connector:o,action:s}=I_(r),i=dr(e.args_preview),a=Object.keys(i).length>0;return{actions:[{id:U(e.execution_id)??t.review_item_id,title:r?Fd(r):t.title||"Run action",connector:o,action:s,consequence:"Runs against the real connector once you approve",risk:t.risk,icon:"generic",argsPreview:Object.entries(i).map(([c,p])=>({key:c,value:p==="[redacted]"?"Hidden credential":typeof p=="string"?p:JSON.stringify(p,null,2)})),actionPath:r,rawArgsPreview:a?i:void 0,reviewComplete:e.args_preview_complete===!0,previewAuthorized:e.args_preview_authorized!==!1,approvalContext:U(e.approval_context),connectorRisk:U(e.risk)??null,policySource:"Requires approval"}]}}function M_(e,t){return{artifactKind:U(e.artifactKind)??"document",artifactLabel:U(e.artifactLabel)??"Output",previewUrl:U(e.previewUrl)??U(e.preview_url),preview:U(e.preview),files:ye(e.files),note:U(e.note)??t.summary??""}}function O_(e,t){return{question:U(e.question)??t.title??"",context:U(e.context),options:ye(e.options)??[]}}function D_(e,t){return{note:U(e.note)??t.summary??"",children:ye(e.children)??[]}}function j_(e){let t=dr(e.detail);switch(e.kind){case"change":return T_(t,e);case"approval":return E_(t,e);case"output":return M_(t,e);case"decision":return O_(t,e);case"batch":return D_(t,e)}}function $_(e,t){let n=typeof e.number=="number"?e.number:void 0,r=U(e.base_ref);return n!=null&&r?`#${n} \u2192 ${r}`:t}function IO(e,t={}){let n=dr(e.detail),r=e.origin_session_id??void 0,o=r?t.sessionLabels?.[r]:void 0,s=e.kind==="approval"?U(n.action_path):void 0,i=e.kind==="change"?$_(n,e.summary):e.kind==="approval"?o??(r?"From a running session":e.summary):e.summary;return{id:e.review_item_id,kind:e.kind,title:s?Fd(s):e.title,summary:i,risk:e.risk,status:e.status,source:e.source,agent:e.agent||"Agent",createdAt:e.created_at,sessionId:r,detail:j_(e)}}async function Ld(e){return u(await l.get(`/p/share?sandbox_id=${encodeURIComponent(e)}`),"Failed to load public links").shares??[]}async function Nd(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 Kd(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 Lo=class extends Error{constructor(n,r){super(n);this.status=r;this.name="PublicSessionShareError"}status};function qd(e,t=""){return`${Gt()}/public/session-shares/${encodeURIComponent(e)}${t}`}async function Gd(e){let t=await fetch(e,{method:"GET",headers:{Accept:"application/json"}}),n=await t.text().catch(()=>""),r=null;try{r=n?JSON.parse(n):null}catch{}if(!t.ok){let o=(r&&typeof r=="object"&&"error"in r&&typeof r.error=="string"?r.error:null)||t.statusText||`HTTP ${t.status}`;throw new Lo(o,t.status)}return r}async function DO(e){return Gd(qd(e))}async function jO(e){return Gd(qd(e,"/messages"))}async function Bd(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/reminders`))}async function Wd(e,t,n){return u(await l.post(`/projects/${e}/sessions/${t}/reminders`,n))}async function No(e,t,n,r){return u(await l.patch(`/projects/${e}/sessions/${t}/reminders/${n}`,r))}async function Ko(e,t,n){return u(await l.delete(`/projects/${e}/sessions/${t}/reminders/${n}`))}var U_=4;async function Hd(e,t){let n=new Array(e.length),r=0,o=async()=>{for(;r<e.length;){let i=r++;try{await t(e[i]),n[i]={ok:!0}}catch(a){n[i]={ok:!1,error:a}}}};await Promise.all(Array.from({length:Math.min(U_,e.length)},o));let s={done:[],failed:[]};return e.forEach((i,a)=>{let c=n[a];c.ok?s.done.push(i):s.failed.push({reminder:i,error:c.error})}),s}function Vd(e,t,n){return Hd(t,r=>No(e,r.sessionId,r.reminderId,n))}function zd(e,t){return Hd(t,n=>Ko(e,n.sessionId,n.reminderId))}async function Yd(e){return u(await l.get(`/projects/${e}/reminders`))}async function Qd(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 Xd(e){let{accountId:t,expiresAt:n,projectId:r,name:o}=e;return u(await l.post("/accounts/tokens",{name:o,...t?{account_id:t}:{},...n?{expires_at:n}:{},...r?{project_id:r}:{}}))}async function Jd(e,t){let n=t?`?account_id=${encodeURIComponent(t)}`:"";return u(await l.delete(`/accounts/tokens/${e}${n}`))}async function Zd(){return u(await l.get("/oauth/grants")).grants}async function eg(e){return u(await l.delete(`/oauth/grants/${encodeURIComponent(e)}`))}async function qO(){return u(await l.get("/accounts/me/devices")).devices}async function GO(e){return u(await l.delete(`/accounts/me/devices/${encodeURIComponent(e)}`))}async function tg(e){return u(await l.get(`/projects/${e}/cli-token`))}async function ng(e,t){return u(await l.post(`/projects/${e}/cli-token`,t??{}))}async function rg(e,t){return u(await l.delete(`/projects/${e}/cli-token/${t}`))}function bt(e){let t=new URLSearchParams,n=" format action actor actor_type project_id session_id source credential_kind phase outcome resource_type request_id correlation_id since until q cursor limit ";for(let[r,o]of Object.entries(e))n.includes(` ${r} `)&&o!=null&&o!==""&&t.set(r,String(o));return t}function qo(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 og(e,t){let n=bt(qo(t)).toString();return u(await l.get(`/accounts/${e}/audit${n?`?${n}`:""}`))}async function sg(e,t){let n=bt(qo({...t,projectId:void 0})).toString();return u(await l.get(`/projects/${e}/audit${n?`?${n}`:""}`))}async function ig(e,t){let n=bt(qo(t)).toString();return u(await l.get(`/accounts/${e}/audit/export${n?`?${n}`:""}`))}async function ag(e){return u(await l.get(`/accounts/${e}/audit/webhooks`))}async function cg(e,t){return u(await l.post(`/accounts/${e}/audit/webhooks`,t))}async function lg(e,t,n){return u(await l.patch(`/accounts/${e}/audit/webhooks/${t}`,n))}async function ug(e,t){return u(await l.delete(`/accounts/${e}/audit/webhooks/${t}`))}async function pg(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 dg(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 JO(e){return u(await l.get(`/approval-links/${e}`),"Failed to load approval")}async function gg(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 mg(){return u(await l.get("/marketplace/marketplaces"))}async function fg(){return u(await l.get("/marketplace/marketplaces/featured"))}async function yg(e){return u(await l.get(`/marketplace/items/${encodeURIComponent(e)}`),"Item not found")}async function hg(e,t){return u(await l.get(`/marketplace/items/${encodeURIComponent(e)}/file?path=${encodeURIComponent(t)}`),"File not found")}async function bg(){return u(await l.get("/marketplace/sources"))}async function _g(e){return u(await l.post("/marketplace/sources",e),"Failed to add marketplace source")}async function Pg(e){return u(await l.delete(`/marketplace/sources/${encodeURIComponent(e)}`),"Failed to remove marketplace source")}async function nD(e,t){return u(await l.post(`/projects/${encodeURIComponent(e)}/marketplace/install-session`,{id:t}),"Failed to start marketplace install session")}async function sD(e){throw F("getTemplate")}async function iD(e,t){throw F("installTemplate")}async function xg(e){return u(await l.get(`/projects/${e}/apps`),"Failed to list Apps").apps}async function Sg(e,t){return u(await l.post(`/projects/${e}/apps`,t),"Failed to create App")}async function Go(e,t){return u(await l.get(`/projects/${e}/apps/${t}`),"Failed to load App")}async function wg(e,t,n){return u(await l.patch(`/projects/${e}/apps/${t}`,n),"Failed to update App")}async function vg(e,t){return u(await l.delete(`/projects/${e}/apps/${t}`),"Failed to delete App")}async function Ag(e,t){return u(await l.post(`/projects/${e}/apps/${t}/token`,{}),"Failed to mint an App token")}async function kg(e,t){let n=await Go(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"),o=new TextEncoder().encode(JSON.stringify(r)),s="";for(let i of o)s+=String.fromCharCode(i);return{KORTIX_AUTH_ISSUER:n.auth.issuer,KORTIX_AUTH_AUDIENCE:n.auth.audience,KORTIX_AUTH_JWKS:`data:application/json;base64,${btoa(s)}`}}async function Rg(e,t){return u(await l.get(`/projects/${e}/apps/${t}/access`),"Failed to load App access policy")}async function Ig(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 Cg(e,t,n){return u(await l.patch(`/projects/${e}/apps/${t}/access`,n),"Failed to update App access policy")}async function Tg(e,t){return u(await l.post(`/projects/${e}/apps/${t}/access-session`,{}),"Failed to create App access session")}async function Bo(e,t){return u(await l.post(`/projects/${e}/apps/artifacts`,t),"Failed to register App artifact")}async function Wo(e,t,n){return u(await l.post(`/projects/${e}/apps/artifacts/${t}/finalize`,n),"Failed to finalize App artifact")}async function F_(e){return e instanceof Uint8Array?e:new Uint8Array(await e.arrayBuffer())}async function L_(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 Eg(e,t,n={}){let r=await F_(t),o=n.mediaType??"application/gzip",s=await Bo(e,{kind:"archive",media_type:o});if(!s.upload)throw new Error("App artifact registration did not return an upload URL");if(r.byteLength>s.upload.max_bytes)throw new Error(`App artifact exceeds ${s.upload.max_bytes} bytes`);n.onProgress?.(0,r.byteLength);let i=await fetch(s.upload.url,{method:"PUT",body:new Blob([Uint8Array.from(r).buffer],{type:o}),signal:n.signal,headers:{"content-type":o,"x-upsert":"false"}});if(!i.ok){let a=await i.text().catch(()=>"");throw new Error(`App artifact upload failed with HTTP ${i.status}${a?`: ${a}`:""}`)}return n.onProgress?.(r.byteLength,r.byteLength),Wo(e,s.artifact.artifact_id,{sha256:await L_(r),size_bytes:r.byteLength})}async function Mg(e,t,n){return u(await l.post(`/projects/${e}/apps/${t}/deployments`,n),"Failed to create App deployment")}async function Og(e,t){return u(await l.get(`/projects/${e}/apps/${t}/deployments`),"Failed to list App deployments").deployments}async function Dg(e,t,n){return u(await l.get(`/projects/${e}/apps/${t}/deployments/${n}`),"Failed to load App deployment")}async function jg(e,t,n,r={}){let o=new URLSearchParams;r.after!==void 0&&o.set("after",String(r.after)),r.limit!==void 0&&o.set("limit",String(r.limit));let s=o.size?`?${o.toString()}`:"";return u(await l.get(`/projects/${e}/apps/${t}/deployments/${n}/logs${s}`),"Failed to load App logs")}async function $g(e,t){return u(await l.post(`/projects/${e}/apps/${t}/start`,{}),"Failed to start App")}async function Ug(e,t){return u(await l.post(`/projects/${e}/apps/${t}/stop`,{}),"Failed to stop App")}async function Fg(e,t,n){return u(await l.delete(`/projects/${e}/apps/${t}/deployments/${n}`),"Failed to delete App deployment")}async function Lg(e,t,n){return u(await l.post(`/projects/${e}/apps/${t}/rollback`,{deployment_id:n}),"Failed to roll back App")}var ae=(e,t)=>`/projects/${e}/apps/${t}`;async function Ng(e,t){return u(await l.get(`${ae(e,t)}/machines`),"Failed to list machines").machines}async function Ho(e,t,n,r){return u(await l.post(`${ae(e,t)}/machines/${n}/${r}`,{}),`Failed to ${r} the machine`).machines}var Kg=(e,t,n)=>Ho(e,t,n,"start"),qg=(e,t,n)=>Ho(e,t,n,"stop"),Gg=(e,t,n)=>Ho(e,t,n,"restart");async function Bg(e,t,n){return u(await l.delete(`${ae(e,t)}/machines/${n}`),"Failed to destroy the machine").machines}async function Wg(e,t,n){return u(await l.put(`${ae(e,t)}/scale`,{count:n}),"Failed to scale the App")}async function Hg(e,t,n){return u(await l.post(`${ae(e,t)}/exec`,n),"Failed to run the command")}async function Vg(e,t){return u(await l.get(`${ae(e,t)}/volumes`),"Failed to list volumes").volumes}async function zg(e,t,n){return u(await l.post(`${ae(e,t)}/volumes`,n),"Failed to create the volume")}async function Yg(e,t,n,r){return u(await l.patch(`${ae(e,t)}/volumes/${n}`,r),"Failed to update the volume")}async function Qg(e,t,n,r){u(await l.delete(`${ae(e,t)}/volumes/${n}?confirm=${encodeURIComponent(r)}`),"Failed to destroy the volume")}async function Xg(e,t,n){return u(await l.get(`${ae(e,t)}/volumes/${n}/snapshots`),"Failed to list snapshots").snapshots}async function Jg(e,t,n){return u(await l.post(`${ae(e,t)}/volumes/${n}/snapshots`,{}),"Failed to take the snapshot")}async function Zg(e,t,n,r){return u(await l.post(`${ae(e,t)}/volumes/${n}/restore`,{snapshot_id:r}),"Failed to restore the volume")}async function em(e,t,n,r){return u(await l.post(`${ae(e,t)}/volumes/${n}/fork`,r),"Failed to fork the volume")}function te(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return t===e.length?e:e.slice(0,t)}var ne=e=>`/drives/${encodeURIComponent(e)}`;async function PD(e){let t=u(await l.get(`/drives?${new URLSearchParams({projectId:e})}`),"Failed to load files").drives;if(!t[0])throw new b("Files not found",{status:404});return t[0]}async function xD(e,t){return u(await l.get(`${ne(e)}/access?${new URLSearchParams({path:t})}`),"Failed to load sharing")}async function SD(e,t){return u(await l.put(`${ne(e)}/access`,t),"Failed to share folder")}async function wD(e,t){let n=u(await l.delete(`${ne(e)}/access/${encodeURIComponent(t)}`),"Failed to stop sharing");return{pendingSessions:typeof n?.pendingSessions=="number"?n.pendingSessions:0}}async function vD(e){return u(await l.get(`${ne(e)}/principals`),"Failed to load people")}async function AD(e){return u(await l.get(`${ne(e)}/conflicts`),"Failed to load conflicts").conflicts}async function kD(e,t){u(await l.post(`${ne(e)}/conflicts/${encodeURIComponent(t)}/dismiss`,{}),"Failed to dismiss conflict")}async function RD(e,t="/"){return(await N_(e,t)).entries}async function N_(e,t="/"){return u(await l.get(`${ne(e)}/files?${new URLSearchParams({path:t})}`),"Failed to load files")}function tm(e,t,n){let r=te(k().backendUrl),o={path:t};return n?.download&&(o.download="1"),`${r}${ne(e)}/files/content?${new URLSearchParams(o)}`}async function ID(e,t,n){let r=await M(tm(e,t),{signal:n});if(!r.ok){let o=await r.json().catch(()=>null);throw new b(o?.message||"Could not download file",{status:r.status})}return r.blob()}async function CD(e,t,n){let r=await M(tm(e,t),{signal:n});if(!r.ok){let o=await r.json().catch(()=>null);throw new b(o?.message||"Could not download file",{status:r.status})}return{blob:await r.blob(),version:r.headers.get("etag")}}async function TD(e,t,n,r){return u(await l.putRaw(`${ne(e)}/files/content?${new URLSearchParams({path:t})}`,n,{signal:r?.signal,...r?.ifMatch?{headers:{"If-Match":r.ifMatch}}:{}}),"Failed to upload file")}async function ED(e,t){return u(await l.post(`${ne(e)}/files/mkdir`,{path:t}),"Failed to create folder")}async function MD(e,t,n){return u(await l.post(`${ne(e)}/files/move`,{from:t,to:n}),"Failed to move")}async function OD(e,t,n){let r={path:t};n?.recursive&&(r.recursive="true"),u(await l.delete(`${ne(e)}/files?${new URLSearchParams(r)}`),"Failed to delete")}async function DD(e){return u(await l.get(`${ne(e)}/versions`),"Failed to load versions").versions}async function jD(e,t){u(await l.post(`${ne(e)}/restore`,{versionId:t}),"Failed to restore version")}var K_=(e,t)=>`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/drives`;async function $D(e,t){return(await q_(e,t)).drives}async function q_(e,t){return u(await l.get(K_(e,t)),"Failed to load session files")}async function nm(e){return u(await l.post("/notifications/device-token",e))}async function rm(e,t){return u(await l.delete(`/notifications/device-token/${encodeURIComponent(e)}`,{signal:t?.signal}))}var ND=["turn_done","turn_error","question","permission","shared","automation_failed","automation_recovered"];async function om(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 sm(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 KD={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}};async function im(){return u(await l.get("/notifications/preferences",{showErrors:!1}))}async function am(e){return u(await l.put("/notifications/preferences",e))}async function cm(){return u(await l.get("/notifications/web-push/key",{showErrors:!1}))}async function lm(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 um(e,t){return u(await l.delete(`/notifications/web-push/subscriptions?endpoint=${encodeURIComponent(e)}`,{signal:t?.signal,showErrors:!1}))}async function gr(e){return u(await l.get(`/projects/${e}/model-access`))}async function mr(e,t){return u(await l.put(`/projects/${e}/model-access`,t))}function HD(e){let{running:t,isCarousel:n,contentStatus:r,isWebsitePreview:o,previewHasError:s,previewIsLinkOnly:i}=e;return t||n?!1:o?s&&!i:r==="error"}function Vo(e){return typeof e=="string"&&e.trim().length>0}function pm(e){if(!e||typeof e!="object")return!1;let{path:t,url:n,content:r}=e;return Vo(t)||Vo(n)||Vo(r)}function G_(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 fr(e){if(!e)return!0;let t=G_(e.items);return t?!t.some(pm):!pm(e)}function pe(e){return(e??"").replace(/^oc-/,"").replace(/-/g,"_")}function YD(e){return pe(e)==="bash"}function QD(e){let t=pe(e);return t==="question"||t==="ask"}function XD(e,t){let n=Math.max(0,e);return`${t?"Running":"Ran"} ${n} command${n===1?"":"s"}`}var B_=new Set(["show","show_user"]);function dm(e){return B_.has(pe(e))}function JD(e,t){let n=Math.max(0,e);return`${t?"Writing":"Wrote"} ${n} file${n===1?"":"s"}`}function gm(e){return!!(e.type==="snapshot"||e.type==="patch"||e.type==="step-start"||e.type==="step-finish"||e.type==="text"&&!e.text?.trim()||zo(e))}function zo(e){let t=pe(e.tool);return t!=="show"&&t!=="show_user"||e.state?.status!=="completed"?!1:fr(e.state?.input)}var W_=new Set(["show","show_user","agent_spawn","agent_status","agent_message","agent_task_update","agent_stop"]);function mm(e){return W_.has(pe(e))}var H_=50*1024*1024,Yo="[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",V_=new RegExp(`^kortix-attachment://(${Yo})/(${Yo})/(${Yo})$`);function Xo(e){if(typeof e!="string")return null;let t=V_.exec(e);return t?{projectId:t[1],sessionId:t[2],attachmentId:t[3]}:null}function sj(e){return Xo(e)!==null}var Qo=new WeakMap;async function fm(e,t,n,r={}){if(n.size>H_)throw new Error("Attachments must be 50 MiB or smaller.");let o=`${e}/${t}`,s=r.attachmentId?void 0:Qo.get(n)?.get(o);if(s?.promise)return s.promise;let i=s??{id:r.attachmentId??crypto.randomUUID(),promise:void 0};if(!r.attachmentId){let c=Qo.get(n)??new Map;c.set(o,i),Qo.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 ym(e,t){let n=Xo(e);if(!n)throw new Error("Invalid attachment reference");let r=k().backendUrl.replace(/\/$/,""),o=await M(`${r}/projects/${n.projectId}/sessions/${n.sessionId}/attachments/${n.attachmentId}`,{signal:t});if(!o.ok)throw new b("Could not load attachment",{status:o.status});return o.blob()}var z_=new Set(["show","show_user"]);function Y_(e){let t=[],n=0;for(;;){let r=e.indexOf("<file",n);if(r===-1)return t;let o=r+5;if(o>=e.length||!/\s/.test(e[o])){n=o;continue}let s=e.indexOf(">",o);if(s===-1)return t;let i=e.indexOf("</file>",s+1);if(i===-1)return t;t.push(e.slice(o,s).trimStart()),n=i+7}}var _t=e=>!!e&&typeof e=="object"&&!Array.isArray(e),Bt=e=>typeof e=="string"&&e.length>0?e:null,hm=e=>typeof e=="string"?Bt(e.split("/").pop()):null;function yr(e,t){let n=e.match(new RegExp(`(?:^|\\s)${t}="([^"]*)"`))?.[1];return n===void 0?null:n.replace(/&quot;/g,'"').replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&")}function Q_(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 X_(e,t){for(let n of Y_(e))t(yr(n,"attachment"),yr(n,"filename")??hm(yr(n,"path")),yr(n,"mime"))}function J_(e,t){for(let n of[e,...Q_(e.items)])_t(n)&&t(n.attachment,hm(n.path),null)}function ij(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let r of e){if(!_t(r)||!_t(r.info)||!Array.isArray(r.parts))continue;let o=Bt(r.info.id);if(!o)continue;let s=Bt(r.info.role)??"unknown",i=(a,c,p)=>{let d=Xo(a);!d||n.has(a)||(n.add(a),t.push({url:a,attachment_id:d.attachmentId,filename:c,mime:p,message_id:o,role:s}))};for(let a of r.parts)_t(a)&&(a.type==="file"?i(a.url,Bt(a.filename),Bt(a.mime)):a.type==="text"&&typeof a.text=="string"?X_(a.text,i):a.type==="tool"&&typeof a.tool=="string"&&z_.has(pe(a.tool))&&_t(a.state)&&_t(a.state.input)&&J_(a.state.input,i))}return t}function je(e){try{return typeof process<"u"?process.env?.[e]:void 0}catch{return}}function Z_(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 pj(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 Jo(e,t,n){return e!==void 0?e:Z_(je(t),n)}var bm={get disableMobileAdvertising(){return Jo(k().featureFlags?.disableMobileAdvertising,"NEXT_PUBLIC_DISABLE_MOBILE_ADVERTISING",!1)},get enableDinoGame(){return Jo(k().featureFlags?.enableDinoGame,"NEXT_PUBLIC_ENABLE_DINO_GAME",!1)},get enableProjects(){return Jo(k().featureFlags?.enableProjects,"NEXT_PUBLIC_ENABLE_PROJECTS",!1)},get enableAutoModel(){return!1}};var eP=new Set(["project-manager"]);function Zo(e){return e.native===!0||e.mode==="subagent"||e.hidden||e.enabled===!1?!1:bm.enableProjects||!eP.has(e.name)}function mj(e){let t=e.agents.filter(Zo),n=e.default_agent??e.open_code_default_agent;return n?t.sort((r,o)=>r.name===n?-1:o.name===n?1:0):t}function _m(){return{projects:{list:dt,listForAccount:la,get:qn,detail:Gn,create:ga,createRepo:ma,provision:fa,update:Hn,archive:Vn,llmCatalog:Bn,modelPicker:Wn,modelAccess:gr,setModelAccess:mr,sandboxHealth:Qn,sandboxTemplates:il,sessions:yt,createSession:ht},github:{linkRepository:xa,replaceProjectRepository:Sa,getInstallation:wa,listInstallations:va,listLinkableInstallations:Aa,listRepositories:ka,listRepositoryBranches:Ra,linkInstallation:Ca,saveInstallation:Ia,deleteInstallation:Ea,storeUserToken:Ta},gitBackend:{get:Ma,repositories:Oa},connectStatus:Jc,marketplace:{items:s=>gg(s),item:s=>yg(s),itemFile:(s,i)=>hg(s,i),marketplaces:()=>mg(),featured:()=>fg(),sources:{list:()=>bg(),add:s=>_g(s),remove:s=>Pg(s)}}}}function Pm(){return{billing:{accountState:ep,accountStateMinimal:tp,transactions:np,transactionsSummary:rp,creditBreakdown:op,usageHistory:sp,usageRollup:bp,sessionCosts:{list:Pp,get:pr},tierConfigurations:ip,checkout:{createSession:n=>ap(n),confirmSession:(n,r)=>cp(n,r)},subscription:{createPortalSession:(n,r)=>lp(n,r),cancel:(n,r)=>up(n,r),reactivate:n=>pp(n),scheduleDowngrade:(n,r,o)=>dp(n,r,o),cancelScheduledChange:n=>gp(n),prorationPreview:(n,r)=>mp(n,r)},credits:{purchase:n=>fp(n),autoTopupSettings:n=>yp(n),configureAutoTopup:n=>hp(n)}},sandboxShares:{list:Ld,create:Nd,revoke:Kd}}}var $e={DESKTOP:"6080",DESKTOP_HTTPS:"6081",PRESENTATION_VIEWER:"3210",STATIC_FILE_SERVER:"3211",KORTIX_MASTER:"8000",BROWSER_STREAM:"9223",BROWSER_VIEWER:"9224",SSH:"22"};function Ue(){let e=je("BACKEND_URL")||k().backendUrl;return e||"http://localhost:8008/v1"}function Ht(e){let t=te(e);return t.endsWith("/v1")?t:`${t}/v1`}function Wt(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=Wt(t);if(n)return n}return}if(e&&typeof e=="object"){let t=e;return Wt(t.sandboxId??t.id??t.slug??Object.values(t)[0])}}function tP(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 es(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?`${Ue()}/p/${n.external_id}/${$e.KORTIX_MASTER}`:""),status:tP(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 ts(){let e=await dt(),t=[];for(let n of e){let r=await yt(n.project_id).catch(()=>[]);for(let o of r)t.push({project:n,session:o,runtime:null,sandbox:es(n,o,null)})}return t.sort((n,r)=>{let o={active:0,provisioning:1,stopped:2,error:3},s=(o[n.sandbox.status]??99)-(o[r.sandbox.status]??99);return s!==0?s:Date.parse(r.sandbox.updated_at)-Date.parse(n.sandbox.updated_at)})}async function Qe(e){let t=await ts();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 Vt=class extends Error{constructor(n,r,o){super(r);this.code=n;this.status=o;this.name="HeadlessAuthError"}code;status};async function Q(e,t,n){let r=n?.fetch??k().fetch??((p,d)=>fetch(p,d)),o=te(n?.backendUrl??k().backendUrl??"");if(!o)throw new Vt("not_configured","backendUrl is not configured (configureKortix / createKortix first)",0);let s={accept:"application/json"};t.body!==void 0&&(s["content-type"]="application/json"),t.bearer&&(s.authorization=`Bearer ${t.bearer}`);let i=await r(`${Ht(o)}${e}`,{method:t.method??(t.body!==void 0?"POST":"GET"),headers:s,...t.body!==void 0?{body:JSON.stringify(t.body)}:{},...n?.signal?{signal:n.signal}:{}}),a=await i.text().catch(()=>""),c=null;try{c=a?JSON.parse(a):null}catch{c=a}if(!i.ok){let p=c&&typeof c=="object"?c:{};throw new Vt(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 ns(e,t){return Q("/auth/signup",{body:e},t)}function rs(e,t){return Q("/auth/sign-in/password",{body:e},t)}function os(e,t){return Q("/auth/sign-in/magic-link",{body:e},t)}function ss(e,t){return Q("/auth/verify-otp",{body:e},t)}function is(e,t){return Q("/auth/sign-in/oauth",{body:e},t)}function as(e,t){return Q("/auth/oauth/exchange",{body:e},t)}function zt(e,t){return Q("/auth/refresh",{body:e},t)}function cs(e,t){return Q("/auth/password/reset",{body:e},t)}function ls(e,t,n){return Q("/auth/password/update",{body:e,bearer:t},n)}function us(e,t){return Q("/auth/user",{bearer:e},t)}function ps(e,t,n){return Q("/auth/user",{method:"PATCH",body:e,bearer:t},n)}function ds(e,t){return Q("/auth/sign-in/sso",{body:e},t)}var gs={enroll:(e,t,n)=>Q("/auth/mfa/factors",{body:e,bearer:t},n),challenge:(e,t={},n,r)=>Q(`/auth/mfa/factors/${encodeURIComponent(e)}/challenge`,{body:t,bearer:n},r),verify:(e,t,n,r)=>Q(`/auth/mfa/factors/${encodeURIComponent(e)}/verify`,{body:t,bearer:n},r),unenroll:(e,t,n)=>Q(`/auth/mfa/factors/${encodeURIComponent(e)}`,{method:"DELETE",bearer:t},n)};function ms(e,t={},n){return Q("/auth/sign-out",{body:t,bearer:e},n)}function fs(e={}){let t=e.refreshSkewSeconds??60,n=e.now??(()=>Date.now()),r=null,o=null,s=!e.storage,i=null,a=null,c=0,p=new Set,d=S=>(S.expires_at??0)*1e3,g=S=>d(S)-t*1e3<=n();async function m(){e.storage&&(r?await e.storage.set(JSON.stringify({session:r,user:o})):await e.storage.remove());for(let S of[...p])try{S(r)}catch{}try{e.onChange?.(r)}catch{}}async function f(){if(s)return r;if(!i){let S=c,D=(async()=>{let j=await e.storage.get();if(S===c&&j)try{let L=JSON.parse(j);L.session?.access_token&&L.session?.refresh_token&&(r=L.session,o=L.user??null)}catch{r=null}return s=!0,r})();i=D,D.then(()=>{i===D&&(i=null)},()=>{i===D&&(i=null)})}return i}async function h(){if(await f(),!r)return null;if(!a){let S=r.refresh_token,D=c,j=zt({refresh_token:S},e.request).then(async L=>(D!==c||(r=L.session,L.user&&(o=L.user),await m()),r)).catch(async L=>{if(D!==c)return r;let y=L&&typeof L=="object"&&"status"in L?L.status:0;if(y>=400&&y<500)return r=null,o=null,await m(),null;throw L}).finally(()=>{a===j&&(a=null)});a=j}return a}return{subscribe(S){return p.add(S),()=>{p.delete(S)}},current:()=>r,user:()=>o,load:f,async set(S,D){await f(),c+=1,a=null,r=S,D!==void 0&&(o=D),S||(o=null),await m()},async getToken(){return await f(),r?g(r)?(await h().catch(()=>r))?.access_token??null:r.access_token:null},refresh:h,async clear(){c+=1,a=null,r=null,o=null,s=!0,await m()}}}function xm(){return{list:Ni,get:qi,create:Ki,secretResources:{list:pc,create:dc,rotate:gc,retry:mc,remove:fc,grant:yc,revoke:hc,setAccess:bc},updateName:Gi,branding:{get:Bi,update:Wi,uploadAsset:Hi,removeAsset:Vi,reset:zi},leave:ia,members:Yi,invite:Qi,removeMember:oa,updateMemberRole:sa,invites:Xi,cancelInvite:Ji,resendInvite:Zi,tokens:{list:Qd,create:Xd,revoke:Jd},connectedApps:{list:Zd,revoke:eg},audit:{log:og,export:ig,webhooks:{list:ag,create:cg,update:lg,remove:ug}}}}function Sm(){return{assignments:{list:Rd,create:Id,revoke:Cd},permissions:{list:Td,forRole:gd},roles:{list:ud,create:fd,update:yd,setPermissions:hd,remove:bd,usage:md},groups:{list:nd,get:rd,create:od,update:sd,remove:id,members:{list:ad,add:cd,remove:ld}},agentIdentities:pd,oauthClients:{list:xd,get:Sd,create:wd,update:vd,rotateSecret:Ad,remove:kd},can:_d,canBatch:Pd}}function wm(){let e={signUp:ns,signInWithPassword:rs,sendMagicLink:os,verifyOtp:ss,signInWithProvider:is,exchangeCode:as,refresh:zt,resetPassword:cs,updatePassword:ls,updateUserMetadata:ps,signInWithSso:ds,mfa:gs,user:us,signOut:ms,session:fs},t=xm(),n=Sm();return{auth:e,accounts:t,iam:n,accountInvites:{listMine:ea,describe:ta,accept:na,decline:ra}}}var Yt=new Map,ys=new Map;function hs(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function vm(e){return Yt.get(hs(e))??null}function Am(){return[...Yt.values()].filter(e=>typeof e=="string")}function km(e){return Yt.has(hs(e))}async function Xe(e){let t=hs(e),n=Yt.get(t);if(n!==void 0)return n;let r=ys.get(t);if(r)return r;let o=(async()=>{try{let s=await l.get("/p/config",{showErrors:!1,errorContext:{operation:"load preview config",silent:!0}});if(!s.success)return null;let i=typeof s.data?.preview_url_template=="string"?s.data.preview_url_template:null;return Yt.set(t,i),i}catch{return null}finally{ys.delete(t)}})();return ys.set(t,o),o}function Rm(e){let{apiBaseUrl:t}=e;return km(t)||Xe(t).catch(()=>{}),{sandboxId:e.sandboxId,backendPort:e.backendPort,apiBaseUrl:t,previewUrlTemplate:vm(t)}}function Im(e){function t(n){try{return new URL(n)}catch{if(typeof window<"u"&&window.location?.origin)try{return new URL(n,window.location.origin)}catch{return null}throw new b(`Kortix SDK: backendUrl must be an absolute URL outside the browser (got ${JSON.stringify(n)}). Relative paths like "/api/kortix" only resolve against a page origin \u2014 configure an absolute backendUrl for server-side hosts.`,{code:"INVALID_BACKEND_URL"})}}return function(r){let o=k().backendUrl??e.backendUrl,s=80,i=t(o);return i&&(s=i.port?Number(i.port):i.protocol==="https:"?443:80),Rm({sandboxId:r,apiBaseUrl:o,backendPort:s})}}function Cm(e,t){let n=null;async function r(){n||(n=or(e,t,{showErrors:!1}).then(o=>{let s=Au(o)??"",i=s.indexOf("/"),a=i>0&&i<s.length-1?{providerID:s.slice(0,i),modelID:s.slice(i+1)}:void 0,c=o.agent_name?.trim()||void 0;return{model:a,agent:c}}));try{return await n}catch(o){throw n=null,o}}return{persistedPromptDefaults:r,clearPersistedDefaults:()=>{n=null}}}var Qt=new Map;function Tm(e){let t=`Session runtime not ready (stage: ${e?.stage??"unknown"})`,n=e?.failure,r=[];n?.category&&r.push(n.category),n?.message&&r.push(n.message);let o=n?.evidence?.error;return o&&o!==n?.message&&r.push(o),r.length===0&&e?.reason&&r.push(e.reason),r.length>0?`${t}: ${r.join(" \u2014 ")}`:t}var Pt=class extends Error{constructor(t){super(`Session runtime not ready \u2014 call \`await session.ensureReady()\` (it drives \`start()\` to completion and resolves this session's own sandbox runtime) before calling \`${t}\`.`),this.name="SessionNotReadyError"}};var xt={url:null,sandboxId:null,dbSandboxId:null,version:0},rP=new Set;function Em(e,t=null,n=null){if(!(xt.url===e&&xt.sandboxId===t&&xt.dbSandboxId===n)){xt={url:e,sandboxId:t,dbSandboxId:n,version:xt.version+1};for(let r of rP)r()}}function Mm(){return xt.url}function Om(e,t){async function n(r){let o=Date.now()+r,s=()=>Math.max(0,o-Date.now()),i=await Ye(e,t,Math.min(3e4,s()));for(;Date.now()<o&&(i==null||(i.stage==="provisioning"||i.stage==="starting")&&i.retriable);)await new Promise(d=>setTimeout(d,Math.min(1e3,s()))),i=await Ye(e,t,Math.min(3e4,s()));let a=i?.runtime_session_id??i?.opencode_session_id;if(!i||i.stage!=="ready"||!i.sandbox||!a)throw new b(Tm(i),{code:"RUNTIME_UNAVAILABLE"});let c=i.sandbox.external_id;if(!c)throw new b("Session sandbox has no external_id \u2014 cannot resolve its runtime URL",{code:"RUNTIME_UNAVAILABLE"});let p=ze(c);return Em(p,c),{runtimeSessionId:a,opencodeSessionId:a,runtimeUrl:p,sandboxId:c}}return n}function Dm(e,t,n){let r=null;function o(){if(r)return r;let p=Uu(e,t);return p&&(r=p),r}let s=Om(e,t);async function i(p){let d=o();if(d)return d;let g=p?.readyTimeoutMs??18e4,m=Xe(k().backendUrl??n.backendUrl).catch(()=>null),f=`${e}
15
- ${t}`,h=Qt.get(f);if(h)return r=await h,await m,r;let S=s(g);Qt.set(f,S);try{return r=await S,await m,r}finally{Qt.get(f)===S&&Qt.delete(f)}}function a(p){let d=o();if(!d)throw new Pt(p);return d}function c(){r=null,Lu(e,t)}return{ensureReady:i,tryResolveReady:o,requireReady:a,forgetReady:c}}var G=["directory","workspace"],jm=["messageID","model","agent","noReply","tools","format","system","variant","parts"],R=(e,t,n=G,r=[],o)=>({method:e,path:t,query:n,body:r,bodyParam:o}),oP={"session.list":R("GET","/session",[...G,"scope","path","roots","start","search","limit"]),"session.get":R("GET","/session/{sessionID}"),"session.create":R("POST","/session",G,["parentID","title","agent","model","metadata","permission","workspaceID"]),"session.delete":R("DELETE","/session/{sessionID}"),"session.update":R("PATCH","/session/{sessionID}",G,["title","metadata","permission","time"]),"session.status":R("GET","/session/status"),"session.messages":R("GET","/session/{sessionID}/message",[...G,"limit","before"]),"session.prompt":R("POST","/session/{sessionID}/message",G,jm),"session.promptAsync":R("POST","/session/{sessionID}/prompt_async",G,jm),"session.abort":R("POST","/session/{sessionID}/abort"),"session.revert":R("POST","/session/{sessionID}/revert",G,["messageID","partID"]),"session.unrevert":R("POST","/session/{sessionID}/unrevert"),"session.summarize":R("POST","/session/{sessionID}/summarize",G,["providerID","modelID","auto"]),"session.command":R("POST","/session/{sessionID}/command",G,["messageID","agent","model","arguments","command","variant","parts"]),"session.share":R("POST","/session/{sessionID}/share"),"session.unshare":R("DELETE","/session/{sessionID}/share"),"session.fork":R("POST","/session/{sessionID}/fork",G,["messageID"]),"session.diff":R("GET","/session/{sessionID}/diff",[...G,"messageID"]),"session.todo":R("GET","/session/{sessionID}/todo"),"permission.list":R("GET","/permission"),"permission.reply":R("POST","/permission/{requestID}/reply",G,["reply","message"]),"question.list":R("GET","/question"),"question.reply":R("POST","/question/{requestID}/reply",G,["answers"]),"question.reject":R("POST","/question/{requestID}/reject"),"part.update":R("PATCH","/session/{sessionID}/message/{messageID}/part/{partID}",G,[],"part"),"part.delete":R("DELETE","/session/{sessionID}/message/{messageID}/part/{partID}"),"file.list":R("GET","/file",[...G,"path"]),"file.read":R("GET","/file/content",[...G,"path"]),"find.files":R("GET","/find/file",[...G,"query","dirs","type","limit"]),"vcs.diff":R("GET","/vcs/diff",[...G,"mode","context"]),"global.health":R("GET","/global/health",[]),"global.dispose":R("POST","/global/dispose",[]),"global.config.get":R("GET","/global/config",[]),"global.config.update":R("PATCH","/global/config",[],[],"config"),"provider.list":R("GET","/provider"),"provider.auth":R("GET","/provider/auth"),"provider.oauth.authorize":R("POST","/provider/{providerID}/oauth/authorize",G,["method","inputs"]),"provider.oauth.callback":R("POST","/provider/{providerID}/oauth/callback",G,["method","code"]),"auth.set":R("PUT","/auth/{providerID}",[],[],"auth"),"app.agents":R("GET","/agent"),"app.skills":R("GET","/skill"),"app.log":R("POST","/log",G,["service","level","message","extra"]),"command.list":R("GET","/command"),"tool.ids":R("GET","/experimental/tool/ids"),"tool.list":R("GET","/experimental/tool",[...G,"provider","model"]),"mcp.status":R("GET","/mcp"),"mcp.add":R("POST","/mcp",G,["name","config"]),"mcp.connect":R("POST","/mcp/{name}/connect"),"mcp.disconnect":R("POST","/mcp/{name}/disconnect"),"mcp.auth.start":R("POST","/mcp/{name}/auth"),"mcp.auth.callback":R("POST","/mcp/{name}/auth/callback",G,["code"]),"mcp.auth.remove":R("DELETE","/mcp/{name}/auth"),"project.list":R("GET","/project"),"project.current":R("GET","/project/current"),"path.get":R("GET","/path")};function sP(e,t){let n=[];for(let r of e.query){let o=t[r];o!=null&&n.push(`${r}=${encodeURIComponent(String(o))}`)}return n.length?`?${n.join("&")}`:""}function iP(e,t,n={},r={}){let o=oP[t],s=o.path.replace(/\{(\w+)\}/g,(p,d)=>encodeURIComponent(String(n[d]))),i,a=!1;if(o.bodyParam)i=n[o.bodyParam],a=i!==void 0;else for(let p of o.body)p in n&&(i={...i,[p]:n[p]},a=!0);let c=new Headers(r.headers);return a&&c.set("Content-Type","application/json"),new Request(`${e.replace(/\/$/,"")}${s}${sP(o,n)}`,{method:o.method,headers:c,redirect:"follow",...a?{body:JSON.stringify(i)}:{},...r.signal?{signal:r.signal}:{}})}function aP(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 cP(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=aP(r.headers.get("Content-Type"));if(r.status===204||r.headers.get("Content-Length")==="0")return{data:i==="json"?{}:i==="formData"?new FormData:i==="stream"?r.body:await r[i](),request:t,response:r};if(i==="stream")return{data:r.body,request:t,response:r};if(i==="json"){let a=await r.text();return{data:a?JSON.parse(a):{},request:t,response:r}}return{data:await r[i](),request:t,response:r}}let o=await r.text(),s=o;try{s=JSON.parse(o)}catch{}return{error:s||{},request:t,response:r}}function bs(e=globalThis.fetch){return async function*({url:t,headers:n,signal:r}){let o=await e(new Request(t,{method:"GET",headers:n,signal:r,redirect:"follow"}));if(!o.ok)throw Object.assign(new Error(`SSE failed: ${o.status} ${o.statusText}`),{status:o.status});if(!o.body)throw new Error("No body in SSE response");let s=o.body.pipeThrough(new TextDecoderStream).getReader(),i=()=>{try{s.cancel()}catch{}};r.addEventListener("abort",i);try{let a="";for(;;){let{done:c,value:p}=await s.read();if(c)break;a=(a+p).replace(/\r\n/g,`
13
+ `);let h=J_(f);if(h){if(r(h),h.type==="error")throw new b(h.error,{status:h.status,code:h.code,data:{reason:h.reason}});h.type==="done"&&(p=h.result)}}}}finally{i.cancel().catch(()=>{})}if(!p)throw new Error("Reload stream ended without a result");return p}async function Ku(e,t){return u(await l.get(`/projects/${e}/sessions/${encodeURIComponent(t)}/scope`))}async function qu(e,t,n){return u(await l.put(`/projects/${e}/sessions/${encodeURIComponent(t)}/scope`,n))}async function Bu(e,t,n){return u(await l.put(`/projects/${e}/sessions/${encodeURIComponent(t)}/model`,{model:n,opencode_model:n}))}function Gu(e){let t=e.metadata?.opencode_model;return typeof t=="string"&&t.trim()?t.trim():null}async function Wu(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/message-authors`,{showErrors:!1}))}async function Hu(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/model-usage`,{showErrors:!1}))}function MT(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 Vu(e){return u(await l.get(`/projects/${e}/triggers`))}async function zu(e,t){return u(await l.post(`/projects/${e}/triggers`,t))}async function Yu(e,t,n){return u(await l.patch(`/projects/${e}/triggers/${t}`,n))}async function Qu(e,t){return u(await l.delete(`/projects/${e}/triggers/${t}`))}async function Xu(e,t){return u(await l.patch(`/projects/${e}/triggers/activation`,{paused:t}))}async function Ju(e,t){return u(await l.post(`/projects/${e}/triggers/${t}/fire`,{}))}async function Zu(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 ep(e){return u(await l.get(`/projects/${e}/triggers/event-apps`))}var Fe=new Map;function qo(e,t){return`${e}::${t}`}function tp(e,t){Fe.delete(e),Fe.set(e,t)}function np(e,t){let n=qo(e,t),r=Fe.get(n);return r&&tp(n,r),r}function rp(e,t,n){let r=qo(e,t);if(!Fe.has(r)&&Fe.size>=512){let o=Fe.keys().next().value;o!==void 0&&Fe.delete(o)}tp(r,n)}function op(e,t){Fe.delete(qo(e,t))}function Z_(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function Jt(){return Z_(v().backendUrl||"http://localhost:8008/v1")}function sp(){let e=v().sandboxId;return e?`${Jt()}/p/${e}/8000`:""}function eP(e,t=8e3){return`${Jt()}/p/${e}/${t}`}function tt(e,t=8e3){return eP(e,t)}function GT(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 Bo=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 WT(e){return e instanceof Error&&e.name==="SessionStartError"}function tP(e){let t=e,n=t?.status,r=t?.code??t?.details?.code??t?.details?.error,o=t?.message||"Unable to start this session";return n&&n>=400&&n<500&&n!==408&&n!==429?new Bo(o,{status:n,code:r,terminal:!0}):null}function ip(e,t,n){let r=typeof n=="number"?n:n?.waitMs,o=typeof n=="number"?void 0:n?.repositoryMode,s=new URLSearchParams;r&&r>0&&s.set("wait_ms",String(Math.floor(r))),o&&s.set("repository_mode",o),typeof n=="object"&&n?.keepStopped&&s.set("keep_stopped","1"),typeof n=="object"&&n?.intentAgeMs&&n.intentAgeMs>0&&s.set("intent_age_ms",String(Math.floor(n.intentAgeMs)));let i=s.size>0?`?${s.toString()}`:"";return l.post(`/projects/${e}/sessions/${t}/start${i}`,{},{showErrors:!1})}async function nt(e,t,n){let r=await ip(e,t,n);if(!r.success||!r.data){let o=tP(r.error);if(o&&!(o.status===404&&tu(t)))throw o;return null}return cp(e,t,r.data)}async function ap(e,t,n){let r=await ip(e,t,n);if(!r.success||!r.data)throw r.error??new Error("Unable to start this session");return cp(e,t,r.data)}function cp(e,t,n){let r=n.sandbox?.external_id,o=n.runtime_session_id??n.opencode_session_id;return n.stage==="ready"&&r&&o&&rp(e,t,{runtimeSessionId:o,opencodeSessionId:o,runtimeUrl:tt(r),sandboxId:r}),n}function HT(e,t){return["session-start",e,t]}async function lp(e){return u(await l.get(`/projects/${e}/model-defaults`))}async function up(e,t){return u(await l.put(`/projects/${e}/model-defaults`,t))}async function pp(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 ZT(e,t){return u(await l.put(`/projects/${e}/model-enablement`,{modelOverrides:t}))}function dp(e){let t=[];for(let n of e){let r=n.trim();r&&!t.includes(r)&&t.push(r)}return t}function nP(e,t){if(e.length!==t.length)return!1;let n=new Set(t);return e.every(r=>n.has(r))}function hr(e){let t=e.connectors_required?dp(e.connectors_required):void 0,n=e.connectors_personal?dp(e.connectors_personal):void 0;if(t&&n&&!nP(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 gp(e,t,n){let r=hr(n);return u(await l.put(`/projects/${e}/agents/${encodeURIComponent(t)}/scope`,r))}async function lE(e,t){let n=u(await l.get(`/projects/${e}/agents/${encodeURIComponent(t)}/config`));return{...n,block:n.block?Go(n.block):null}}async function uE(e,t,n){let r=Go(n,!0),o=u(await l.put(`/projects/${e}/agents/${encodeURIComponent(t)}/config`,r));return{...o,block:o.block?Go(o.block):null}}function Go(e,t=!1){let n=hr(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 pE(e,t,n){return u(await l.post(`/projects/${e}/secrets/${encodeURIComponent(t)}/grant`,{agent:n}))}async function mp(e,t){return u(await l.put(`/projects/${e}/default-agent`,{agent:t}))}var fp="Use createPerSeatCheckout().";function yp(){return{credits:{total:0,daily:0,monthly:0,extra:0,can_run:!1,daily_refresh:null},subscription:{tier_key:"none",tier_display_name:"No Plan",status:"no_subscription",billing_period:null,provider:"stripe",subscription_id:null,current_period_end:null,cancel_at_period_end:!1,is_cancelled:!1,cancellation_effective_date:null,has_scheduled_change:!1,scheduled_change:null,commitment:{has_commitment:!1,can_cancel:!0,commitment_type:null,months_remaining:null,commitment_end_date:null},can_purchase_credits:!1},models:[],limits:{concurrent_runs:{running_count:0,limit:0,can_start:!1,tier_name:"none"},ai_worker_count:{current_count:0,limit:0,can_create:!1,tier_name:"none"},custom_mcp_count:{current_count:0,limit:0,can_create:!1,tier_name:"none"}},tier:{name:"none",display_name:"No Plan",monthly_credits:0,can_purchase_credits:!1}}}function rP(e){let t=e.trim().toLowerCase();return t===""||t==="free"||t==="none"?"free":t==="enterprise"?"enterprise":"team"}function yE(e){let t=e?.plan;if(t)return{family:t.family,label:t.label,sublabel:t.sublabel??null,isGrandfathered:t.is_grandfathered===!0};let n=e??yp(),r=(n.subscription?.tier_key||n.tier?.name||"none").toString(),o=(n.tier?.display_name||"").trim()||r;return{family:rP(r),label:o,sublabel:null,isGrandfathered:!1}}async function hp(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?yp():t.data}function bp(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 _p(e){return hp(`/billing/account-state${bp(e)}`)}async function Pp(e){return hp(`/billing/account-state/minimal${bp(e)}`)}async function xp(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 Sp(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 wp(){return u(await l.get("/billing/credit-breakdown"))}async function Ap(e){let t=e!=null?`?days=${e}`:"";return u(await l.get(`/billing/usage-history${t}`))}async function vp(){return u(await l.get("/billing/tier-configurations"))}async function hE(e){let t=e.accountId?`?account_id=${encodeURIComponent(e.accountId)}`:"";return bt(e,`/v1/billing/account-state${t}`)}async function kp(e){throw U("createCheckoutSession",fp)}async function Rp(e,t){throw U("confirmCheckoutSession",fp)}async function Cp(e,t){return u(await l.post("/billing/create-portal-session",{account_id:t,return_url:e}),"Failed to create portal session")}async function Ip(e,t){return u(await l.post("/billing/cancel-subscription",{account_id:t,feedback:e}),"Failed to cancel subscription")}async function Tp(e){return u(await l.post("/billing/reactivate-subscription",{account_id:e}),"Failed to reactivate subscription")}async function Ep(e,t,n){throw U("scheduleDowngrade","Change the plan in the Stripe customer portal (createPortalSession()).")}async function Mp(e){return u(await l.post("/billing/cancel-scheduled-change",{account_id:e}),"Failed to cancel scheduled change")}async function Op(e,t){let n=new URLSearchParams({new_price_id:e});return t&&n.set("account_id",t),u(await l.get(`/billing/proration-preview?${n.toString()}`),"Failed to load proration preview")}async function Dp(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 jp(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 bE(e){return u(await l.post(`/accounts/${encodeURIComponent(e)}/top-up-requests`,{}),"Failed to ask the owners for credits")}async function $p(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 _E(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 PE(e){return u(await l.post("/billing/create-per-seat-checkout",{account_id:e.accountId,success_url:e.successUrl,cancel_url:e.cancelUrl,locale:e.locale}),"Failed to create per-seat checkout")}async function xE(e){return u(await l.post("/billing/claim-per-seat",{account_id:e}),"Failed to switch to per-seat billing")}async function SE(e){return u(await l.post("/billing/sync-subscription",{account_id:e}),"Failed to sync subscription")}async function Up(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 Wo(e,t){t.accountId&&e.set("account_id",t.accountId),t.projectId&&e.set("project_id",t.projectId)}function br(e,t){t.from&&e.set("from",t.from),t.to&&e.set("to",t.to)}function _r(e){return e.size>0?`?${e}`:""}async function Fp(e={}){let t=new URLSearchParams;return Wo(t,e),e.ownerId&&t.set("owner_id",e.ownerId),br(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${_r(t)}`))}async function Pr(e,t={}){let n=new URLSearchParams;return Wo(n,t),u(await l.get(`/usage/session-costs/${encodeURIComponent(e)}${_r(n)}`))}async function CE(e={}){let t=new URLSearchParams;return e.accountId&&t.set("account_id",e.accountId),br(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${_r(t)}`))}async function IE(e={}){let t=new URLSearchParams;return Wo(t,e),e.sessionId&&t.set("session_id",e.sessionId),br(t,e),u(await l.get(`/usage/cost-summary${_r(t)}`))}function Lp(e,t={}){let n=new URLSearchParams;if(t.accountId&&n.set("account_id",t.accountId),t.projectId&&n.set("project_id",t.projectId),e==="sessions"){let o=t;o.ownerId&&n.set("owner_id",o.ownerId)}br(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`${v().backendUrl||""}${r}?${n}`}async function TE(e,t={}){let n=Lp(e==="projects"?"projects":"sessions",t),r=await Re(n,{method:"GET"},{timeoutMs:10*6e4},"Failed to export CSV"),o=r.headers.get("x-kortix-row-cap"),s=o!=null?Number(o):NaN;return{blob:await r.blob(),rowCap:Number.isFinite(s)?s:null}}async function Np(e,t){return u(await l.post(`/channels/${e}/identity/bind`,{token:t}),"Failed to connect your account")}function DE(e){return Np("slack",e)}function jE(e){return Np("teams",e)}async function Kp(e,t){return u(await l.post(`/channels/${e}/identity/preview`,{token:t},{showErrors:!1}),"This link is invalid or has expired")}function $E(e){return Kp("slack",e)}function UE(e){return Kp("teams",e)}async function qp(e){let t=await l.get(`/projects/${encodeURIComponent(e)}/channels/slack/installation`,{showErrors:!1});return t.success?t.data??null:null}async function Bp(e,t){return u(await l.post(`/projects/${encodeURIComponent(e)}/channels/slack/connect`,t,{showErrors:!1}),"Failed to connect")}var oP={oauth_available:!1,install_url:null};async function Gp(e){let t=await l.get(`/projects/${encodeURIComponent(e)}/channels/slack/mode`,{showErrors:!1});return!t.success||!t.data?oP:t.data}async function Wp(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 Hp(e,t){return Wp("slack",e,t)}function Vp(e,t){return Wp("teams",e,t)}async function zp(e){return u(await l.get(`/webhooks/slack/${encodeURIComponent(e)}/manifest`,{showErrors:!1}),"Failed to load Slack manifest")}async function Yp(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 Qp(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 Xp(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 Ho(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 sP={provider:"agentmail",managed_available:!1};async function Jp(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?Ho(r.data):null}async function Zp(e){let t=await l.get(`/projects/${encodeURIComponent(e)}/channels/email/mode`,{showErrors:!1});return!t.success||!t.data?sP:t.data}async function ed(e,t){let n=u(await l.post(`/projects/${encodeURIComponent(e)}/channels/email/connect`,t,{showErrors:!1}),"Failed to connect email");return Ho(n)}async function td(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 nd(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 Ho(r)}async function LE(e){return u(await l.get(`/projects/${encodeURIComponent(e)}/channels/bindings`,{showErrors:!1}),"Failed to load channel bindings")}async function FE(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 rd(e){return u(await l.get(`/projects/${e}/gateway/routing-policy`),"Gateway routing policy request failed")}async function od(e,t){return u(await l.put(`/projects/${e}/gateway/routing-policy`,t),"Gateway routing policy request failed")}async function sd(e){return u(await l.delete(`/projects/${e}/gateway/routing-policy`),"Gateway routing policy request failed")}async function id(e,t){return u(await l.post(`/projects/${e}/gateway/routing-policy/preview`,t),"Gateway route preview failed")}async function ad(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 cd(e,t){return u(await l.get(`/projects/${e}/gateway/logs/${t}`),"Gateway request failed")}async function ld(e,t){return u(await l.get(`/projects/${e}/gateway/overview${t?`?days=${t}`:""}`),"Gateway request failed")}async function ud(e,t){return u(await l.get(`/projects/${e}/gateway/series${t?`?days=${t}`:""}`),"Gateway request failed")}async function pd(e,t){return u(await l.get(`/projects/${e}/gateway/breakdown${t?`?days=${t}`:""}`),"Gateway request failed")}async function dd(e,t){return u(await l.get(`/projects/${e}/gateway/sessions${t?`?days=${t}`:""}`),"Gateway request failed")}async function gd(e,t){return u(await l.get(`/projects/${e}/gateway/errors${t?`?days=${t}`:""}`),"Gateway request failed")}async function md(e){return u(await l.get(`/projects/${e}/gateway/budgets`),"Gateway request failed")}async function fd(e,t){return u(await l.put(`/projects/${e}/gateway/budgets`,t),"Gateway request failed")}async function yd(e,t){return u(await l.delete(`/projects/${e}/gateway/budgets/${t}`),"Gateway request failed")}async function hd(e){return u(await l.get(`/projects/${e}/gateway/keys`),"Gateway request failed")}async function bd(e,t){return u(await l.post(`/projects/${e}/gateway/keys`,{name:t}),"Gateway request failed")}async function _d(e,t){return u(await l.delete(`/projects/${e}/gateway/keys/${t}`),"Gateway request failed")}async function Pd(e,t,n,r,o){return u(await l.post(`/projects/${e}/gateway/playground`,{prompt:t,models:n,...r?{system:r}:{},...o&&Object.keys(o).length?{generationConfig:o}:{}}),"Gateway request failed")}async function BE(e,t){return u(await l.post(`/projects/${e}/gateway/providers/${encodeURIComponent(t)}/verify`,{}),"Gateway provider verification failed")}async function HE(){throw U("getReferralCode")}async function VE(){throw U("refreshReferralCode")}async function zE(e){throw U("validateReferralCode")}async function YE(){throw U("getReferralStats")}async function QE(e={}){throw U("listReferrals")}async function XE(e){throw U("sendReferralEmails")}function O(e){return l.get(e,{showErrors:!1})}function A(e){return u(e,"Unexpected empty response")}async function xd(e){return A(await O(`/accounts/${e}/iam/groups`)).groups}async function Sd(e,t){return A(await O(`/accounts/${e}/iam/groups/${t}`))}async function wd(e,t){return A(await l.post(`/accounts/${e}/iam/groups`,t,{showErrors:!1}))}async function Ad(e,t,n){return A(await l.patch(`/accounts/${e}/iam/groups/${t}`,n))}async function vd(e,t){return A(await l.delete(`/accounts/${e}/iam/groups/${t}`))}async function kd(e,t){return A(await O(`/accounts/${e}/iam/groups/${t}/members`)).members}async function Rd(e,t,n){return A(await l.post(`/accounts/${e}/iam/groups/${t}/members`,{userIds:n}))}async function oM(e,t){return A(await O(`/accounts/${e}/iam/groups/${t}/project-grants`)).grants}async function Cd(e,t,n){return A(await l.delete(`/accounts/${e}/iam/groups/${t}/members/${n}`))}async function sM(e,t){return A(await O(`/accounts/${e}/iam/members/${t}/groups`)).groups}async function iM(e,t){let n=A(await O(`/accounts/${e}/iam/members/${t}/project-access`));return{projects:n.projects,account_wide_policies:n.account_wide_policies??[]}}function Ne(e){let t=new URLSearchParams;for(let[r,o]of Object.entries(e))o&&t.set(r,String(o));let n=t.toString();return n?`?${n}`:""}async function pM(e,t={}){let n=Ne({resourceType:t.resourceType,principalType:t.principalType,principalId:t.principalId,projectId:t.projectId});return A(await O(`/accounts/${e}/iam/resource-grants${n}`)).grants}async function yM(e,t={}){let n=Ne({principalType:t.principalType,principalId:t.principalId,scopeType:t.scopeType,scopeId:t.scopeId===null?"null":t.scopeId});return A(await O(`/accounts/${e}/iam/policies${n}`)).policies}async function hM(e,t){return A(await l.post(`/accounts/${e}/iam/policies`,t,{showErrors:!1}))}async function bM(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 PM(e,t){return A(await l.post(`/accounts/${e}/iam/policies:bulk-delete`,{policy_ids:t},{showErrors:!1}))}async function xM(e,t){return A(await l.post(`/accounts/${e}/iam/policies:bulk-import`,{policies:t},{showErrors:!1}))}async function Id(e){return A(await O(`/accounts/${e}/iam/roles`)).roles}async function Td(e){return A(await O(`/accounts/${e}/iam/agent-identities`)).agents}async function Ed(e){return A(await l.get(`/projects/${e}/agent-identities`,{showErrors:!1})).agents}async function Md(e,t){return A(await O(`/accounts/${e}/iam/roles/${t}/permissions`))}async function vM(e){return A(await O(`/accounts/${e}/iam/actions`)).actions}async function Od(e,t){return A(await O(`/accounts/${e}/iam/roles/${t}/usage`))}async function Dd(e,t){return A(await l.post(`/accounts/${e}/iam/roles`,t,{showErrors:!1}))}async function jd(e,t,n){return A(await l.patch(`/accounts/${e}/iam/roles/${t}`,n,{showErrors:!1}))}async function $d(e,t,n){return A(await l.put(`/accounts/${e}/iam/roles/${t}/permissions`,{actions:n},{showErrors:!1}))}async function Ud(e,t){return A(await l.delete(`/accounts/${e}/iam/roles/${t}`,{showErrors:!1}))}async function kM(e,t,n){return A(await l.patch(`/accounts/${e}/iam/members/${t}/super-admin`,{isSuperAdmin:n}))}async function TM(e){return A(await O(`/accounts/${e}/iam/scim/tokens`)).tokens}async function EM(e,t){return A(await l.post(`/accounts/${e}/iam/scim/tokens`,t,{showErrors:!1}))}async function MM(e,t){return A(await l.delete(`/accounts/${e}/iam/scim/tokens/${t}`))}async function $M(e){return A(await O(`/accounts/${e}/iam/mfa-required`))}async function UM(e){return A(await O(`/accounts/${e}/iam/mfa-required/preview`))}async function LM(e,t){return A(await l.patch(`/accounts/${e}/iam/mfa-required`,{enabled:t},{showErrors:!1}))}async function FM(e){return A(await O(`/accounts/${e}/iam/session-oversight`))}async function NM(e,t){return A(await l.patch(`/accounts/${e}/iam/session-oversight`,{enabled:t},{showErrors:!1}))}async function GM(e){return A(await O(`/accounts/${e}/iam/sso/provider`)).provider}async function WM(e,t){return A(await l.put(`/accounts/${e}/iam/sso/provider`,t,{showErrors:!1})).provider}async function HM(e,t){return A(await l.post(`/accounts/${e}/iam/sso/provider/from-metadata`,t,{showErrors:!1})).provider}async function VM(e){return A(await l.post(`/accounts/${e}/iam/sso/provider/verify-domain`,{},{showErrors:!1})).provider}async function zM(e){return A(await l.delete(`/accounts/${e}/iam/sso/provider`))}async function YM(e){return A(await O(`/accounts/${e}/iam/sso/mappings`)).mappings}async function QM(e,t){return A(await l.post(`/accounts/${e}/iam/sso/mappings`,t,{showErrors:!1}))}async function XM(e,t){return A(await l.delete(`/accounts/${e}/iam/sso/mappings/${t}`))}async function tO(e){return A(await O(`/accounts/${e}/iam/session-policy`))}async function nO(e,t){return A(await l.patch(`/accounts/${e}/iam/session-policy`,t,{showErrors:!1}))}async function rO(e){return A(await O(`/accounts/${e}/iam/sessions`)).sessions}async function oO(e,t){return A(await l.post(`/accounts/${e}/iam/sessions/${t}/revoke`,{},{showErrors:!1}))}async function sO(e){return A(await O(`/accounts/${e}/iam/pat-policy`))}async function iO(e,t){return A(await l.patch(`/accounts/${e}/iam/pat-policy`,t,{showErrors:!1}))}async function uO(e){return A(await O(`/accounts/${e}/iam/service-accounts`)).service_accounts}async function pO(e,t){return A(await l.post(`/accounts/${e}/iam/service-accounts`,t,{showErrors:!1}))}async function dO(e,t){return A(await l.post(`/accounts/${e}/iam/service-accounts/${t}/disable`,{},{showErrors:!1}))}async function gO(e,t){return A(await l.delete(`/accounts/${e}/iam/service-accounts/${t}`))}async function bO(e){return A(await O(`/accounts/${e}/audit/webhooks`)).webhooks}async function _O(e,t){return A(await l.post(`/accounts/${e}/audit/webhooks`,t,{showErrors:!1}))}async function PO(e,t,n){return A(await l.patch(`/accounts/${e}/audit/webhooks/${t}`,n))}async function xO(e,t){return A(await l.delete(`/accounts/${e}/audit/webhooks/${t}`))}async function SO(e,t={}){let n=Ne({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 O(`/accounts/${e}/audit${n}`))}async function Ld(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 O(`/accounts/${e}/iam/members/${t}/effective?${r.toString()}`))}async function Fd(e,t,n){return n.length===0?[]:A(await l.post(`/accounts/${e}/iam/members/${t}/effective:batch`,{probes:n})).results}async function IO(e){return A(await O(`/accounts/${e}/iam/enterprise-demo`)).enabled}async function TO(e,t){return A(await l.put(`/accounts/${e}/iam/enterprise-demo`,{enabled:t})).enabled}async function Nd(e){return u(await l.get(`/accounts/${e}/iam/oauth-clients`,{showErrors:!1}))}async function Kd(e,t){return u(await l.get(`/accounts/${e}/iam/oauth-clients/${t}`,{showErrors:!1}))}async function qd(e,t){return u(await l.post(`/accounts/${e}/iam/oauth-clients`,t,{showErrors:!1}))}async function Bd(e,t,n){return u(await l.patch(`/accounts/${e}/iam/oauth-clients/${t}`,n,{showErrors:!1}))}async function Gd(e,t){return u(await l.post(`/accounts/${e}/iam/oauth-clients/${t}/rotate-secret`,{},{showErrors:!1}))}async function Wd(e,t){return u(await l.delete(`/accounts/${e}/iam/oauth-clients/${t}`,{showErrors:!1}))}function iP(e){return Ne({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 Hd(e,t){return u(await O(`/accounts/${e}/iam/assignments${iP(t)}`)).assignments}async function Vd(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 zd(e,t){return u(await l.delete(`/accounts/${e}/iam/assignments/${t}`)).assignment}async function Yd(e,t){let n=t?.scopeType?`?scope_type=${t.scopeType}`:"";return u(await O(`/accounts/${e}/iam/permissions${n}`)).permissions}async function qO(){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 BO(e="User requested deletion"){return u(await l.post("/account/request-deletion",{reason:e},{showErrors:!1}),"Failed to request account deletion")}async function GO(){return u(await l.post("/account/cancel-deletion",void 0,{showErrors:!1}),"Failed to cancel account deletion")}async function WO(){return u(await l.delete("/account/delete-immediately",{showErrors:!1}),"Failed to delete account immediately")}async function HO(){return(await l.get("/user-roles",{showErrors:!1})).data??{isAdmin:!1,role:null}}function QO(){return l.get("/admin/api/provider-distribution").then(e=>u(e))}function XO(e=300){return l.get(`/admin/api/sandboxes?limit=${e}`).then(t=>u(t))}function JO(e){return l.put("/admin/api/provider-distribution",e).then(t=>u(t))}function ZO(e){return l.get(`/admin/api/provider-analytics?days=${e}`).then(t=>u(t))}function eD(e,t){return l.post(`/admin/api/sandboxes/${encodeURIComponent(e)}/migrate`,{targetProvider:t}).then(n=>u(n))}function tD(){return l.get("/admin/api/provider-fallback").then(e=>u(e))}function nD(e){return l.put("/admin/api/provider-fallback",{enabled:e}).then(t=>u(t))}function rD(){return l.get("/admin/api/boot-modes").then(e=>u(e))}function oD(e){return l.put("/admin/api/boot-modes",e).then(t=>u(t))}var Qd="Export the deck as PDF or PPTX with convertRuntimePresentation().";async function aD(e){throw U("getGoogleAuthUrl",Qd)}async function cD(e,t){throw U("convertPresentationToGoogleSlides",Qd)}async function Xd(e,t){let n=new URLSearchParams;t?.segment&&n.set("segment",t.segment),t?.kind&&n.set("kind",t.kind);let r=n.toString();return u(await l.get(`/projects/${e}/review/items${r?`?${r}`:""}`,{showErrors:!1}))}async function Jd(e,t){return u(await l.get(`/projects/${e}/review/items/${t}`))}async function Zd(e,t){return u(await l.post(`/projects/${e}/review/items`,t))}async function eg(e,t,n){return u(await l.post(`/projects/${e}/review/items/${t}/act`,n))}async function tg(e,t){return u(await l.post(`/projects/${e}/review/bulk`,t))}var Vo="call:";function gD(e){return e.startsWith("cr:")&&e.length>3?{type:"change_request",changeRequestId:e.slice(3)}:e.startsWith(Vo)&&e.length>Vo.length?{type:"connector_call",executionId:e.slice(Vo.length)}:{type:"review_item",reviewItemId:e}}function aP(e){return e==="needs_you"?"needs_you":e==="waiting"?"waiting":"done"}function mD(e){let t={needs_you:0,waiting:0,done:0};for(let n of e)t[aP(n.status)]+=1;return t}function fD(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 zo(e){return e.split(/[._-]/).filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function rg(e){let t=e.indexOf(".");return t<=0?zo(e):`(${zo(e.slice(0,t))}) ${zo(e.slice(t+1))}`}function cP(e){let t=e.indexOf(".");return t>0?{connector:e.slice(0,t),action:e.slice(t+1)}:{connector:e,action:""}}var xr=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{},$=e=>typeof e=="string"&&e?e:void 0,Pe=e=>Array.isArray(e)?e:void 0,ng=e=>typeof e=="number"?e:0,lP=e=>e.split(`
14
+ `).map(t=>t.trim()).filter(Boolean);function uP(e,t){let n=xr(e.advanced),r=$(e.description),o=Pe(e.whatChanged)??(r?lP(r):t.summary?[t.summary]:[]);return{crId:$(e.cr_id),number:typeof e.number=="number"?e.number:void 0,whatChanged:o,impact:$(e.impact)??"",verification:Pe(e.verification)??[],previewUrl:$(e.previewUrl)??$(e.preview_url),conflicts:Pe(e.conflicts),requestedChanges:Pe(e.requested_changes)??[],advanced:{headRef:$(n.headRef)??$(e.head_ref)??"",baseRef:$(n.baseRef)??$(e.base_ref)??"",headSha:$(n.headSha)??$(e.head_sha)??$(e.head_commit_sha)??"",baseSha:$(n.baseSha)??$(e.base_sha)??"",additions:ng(n.additions),deletions:ng(n.deletions),files:Pe(n.files)??[],mergeMode:$(n.mergeMode)??"merge"}}}function pP(e,t){let n=Pe(e.actions);if(n)return{actions:n.map((c,p)=>({id:$(c.id)??`${t.review_item_id}-${p}`,title:$(c.title)??"Action",connector:$(c.connector)??"",action:$(c.action)??"",consequence:$(c.consequence)??"",risk:$(c.risk)??t.risk,icon:$(c.icon)??"generic",argsPreview:Pe(c.argsPreview)??[],policySource:$(c.policySource)??"Requires approval",decided:c.decided==="approved"||c.decided==="denied"?c.decided:void 0}))};let r=$(e.action_path)??"",{connector:o,action:s}=cP(r),i=xr(e.args_preview),a=Object.keys(i).length>0;return{actions:[{id:$(e.execution_id)??t.review_item_id,title:r?rg(r):t.title||"Run action",connector:o,action:s,consequence:"Runs against the real connector once you approve",risk:t.risk,icon:"generic",argsPreview:Object.entries(i).map(([c,p])=>({key:c,value:p==="[redacted]"?"Hidden credential":typeof p=="string"?p:JSON.stringify(p,null,2)})),actionPath:r,rawArgsPreview:a?i:void 0,reviewComplete:e.args_preview_complete===!0,previewAuthorized:e.args_preview_authorized!==!1,approvalContext:$(e.approval_context),connectorRisk:$(e.risk)??null,policySource:"Requires approval"}]}}function dP(e,t){return{artifactKind:$(e.artifactKind)??"document",artifactLabel:$(e.artifactLabel)??"Output",previewUrl:$(e.previewUrl)??$(e.preview_url),preview:$(e.preview),files:Pe(e.files),note:$(e.note)??t.summary??""}}function gP(e,t){return{question:$(e.question)??t.title??"",context:$(e.context),options:Pe(e.options)??[]}}function mP(e,t){return{note:$(e.note)??t.summary??"",children:Pe(e.children)??[]}}function fP(e){let t=xr(e.detail);switch(e.kind){case"change":return uP(t,e);case"approval":return pP(t,e);case"output":return dP(t,e);case"decision":return gP(t,e);case"batch":return mP(t,e)}}function yP(e,t){let n=typeof e.number=="number"?e.number:void 0,r=$(e.base_ref);return n!=null&&r?`#${n} \u2192 ${r}`:t}function yD(e,t={}){let n=xr(e.detail),r=e.origin_session_id??void 0,o=r?t.sessionLabels?.[r]:void 0,s=e.kind==="approval"?$(n.action_path):void 0,i=e.kind==="change"?yP(n,e.summary):e.kind==="approval"?o??(r?"From a running session":e.summary):e.summary;return{id:e.review_item_id,kind:e.kind,title:s?rg(s):e.title,summary:i,risk:e.risk,status:e.status,source:e.source,agent:e.agent||"Agent",createdAt:e.created_at,sessionId:r,detail:fP(e)}}async function og(e){return u(await l.get(`/p/share?sandbox_id=${encodeURIComponent(e)}`),"Failed to load public links").shares??[]}async function sg(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 ig(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 Yo=class extends Error{constructor(n,r){super(n);this.status=r;this.name="PublicSessionShareError"}status};function ag(e,t=""){return`${Jt()}/public/session-shares/${encodeURIComponent(e)}${t}`}async function cg(e){let t=await fetch(e,{method:"GET",headers:{Accept:"application/json"}}),n=await t.text().catch(()=>""),r=null;try{r=n?JSON.parse(n):null}catch{}if(!t.ok){let o=(r&&typeof r=="object"&&"error"in r&&typeof r.error=="string"?r.error:null)||t.statusText||`HTTP ${t.status}`;throw new Yo(o,t.status)}return r}async function SD(e){return cg(ag(e))}async function wD(e){return cg(ag(e,"/messages"))}async function lg(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/reminders`))}async function ug(e,t,n){return u(await l.post(`/projects/${e}/sessions/${t}/reminders`,n))}async function Qo(e,t,n,r){return u(await l.patch(`/projects/${e}/sessions/${t}/reminders/${n}`,r))}async function Xo(e,t,n){return u(await l.delete(`/projects/${e}/sessions/${t}/reminders/${n}`))}var hP=4;async function pg(e,t){let n=new Array(e.length),r=0,o=async()=>{for(;r<e.length;){let i=r++;try{await t(e[i]),n[i]={ok:!0}}catch(a){n[i]={ok:!1,error:a}}}};await Promise.all(Array.from({length:Math.min(hP,e.length)},o));let s={done:[],failed:[]};return e.forEach((i,a)=>{let c=n[a];c.ok?s.done.push(i):s.failed.push({reminder:i,error:c.error})}),s}function dg(e,t,n){return pg(t,r=>Qo(e,r.sessionId,r.reminderId,n))}function gg(e,t){return pg(t,n=>Xo(e,n.sessionId,n.reminderId))}async function mg(e){return u(await l.get(`/projects/${e}/reminders`))}async function fg(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 yg(e){let{accountId:t,expiresAt:n,projectId:r,name:o}=e;return u(await l.post("/accounts/tokens",{name:o,...t?{account_id:t}:{},...n?{expires_at:n}:{},...r?{project_id:r}:{}}))}async function hg(e,t){let n=t?`?account_id=${encodeURIComponent(t)}`:"";return u(await l.delete(`/accounts/tokens/${e}${n}`))}async function bg(){return u(await l.get("/oauth/grants")).grants}async function _g(e){return u(await l.delete(`/oauth/grants/${encodeURIComponent(e)}`))}async function TD(){return u(await l.get("/accounts/me/devices")).devices}async function ED(e){return u(await l.delete(`/accounts/me/devices/${encodeURIComponent(e)}`))}async function Pg(e){return u(await l.get(`/projects/${e}/cli-token`))}async function xg(e,t){return u(await l.post(`/projects/${e}/cli-token`,t??{}))}async function Sg(e,t){return u(await l.delete(`/projects/${e}/cli-token/${t}`))}function kt(e){let t=new URLSearchParams,n=" format action actor actor_type project_id session_id source credential_kind phase outcome resource_type request_id correlation_id since until q cursor limit ";for(let[r,o]of Object.entries(e))n.includes(` ${r} `)&&o!=null&&o!==""&&t.set(r,String(o));return t}function Jo(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 wg(e,t){let n=kt(Jo(t)).toString();return u(await l.get(`/accounts/${e}/audit${n?`?${n}`:""}`))}async function Ag(e,t){let n=kt(Jo({...t,projectId:void 0})).toString();return u(await l.get(`/projects/${e}/audit${n?`?${n}`:""}`))}async function vg(e,t){let n=kt(Jo(t)).toString();return u(await l.get(`/accounts/${e}/audit/export${n?`?${n}`:""}`))}async function kg(e){return u(await l.get(`/accounts/${e}/audit/webhooks`))}async function Rg(e,t){return u(await l.post(`/accounts/${e}/audit/webhooks`,t))}async function Cg(e,t,n){return u(await l.patch(`/accounts/${e}/audit/webhooks/${t}`,n))}async function Ig(e,t){return u(await l.delete(`/accounts/${e}/audit/webhooks/${t}`))}async function Tg(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 Eg(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 ND(e){return u(await l.get(`/approval-links/${e}`),"Failed to load approval")}async function Mg(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 Og(){return u(await l.get("/marketplace/marketplaces"))}async function Dg(){return u(await l.get("/marketplace/marketplaces/featured"))}async function jg(e){return u(await l.get(`/marketplace/items/${encodeURIComponent(e)}`),"Item not found")}async function $g(e,t){return u(await l.get(`/marketplace/items/${encodeURIComponent(e)}/file?path=${encodeURIComponent(t)}`),"File not found")}async function Ug(){return u(await l.get("/marketplace/sources"))}async function Lg(e){return u(await l.post("/marketplace/sources",e),"Failed to add marketplace source")}async function Fg(e){return u(await l.delete(`/marketplace/sources/${encodeURIComponent(e)}`),"Failed to remove marketplace source")}async function GD(e,t){return u(await l.post(`/projects/${encodeURIComponent(e)}/marketplace/install-session`,{id:t}),"Failed to start marketplace install session")}async function VD(e){throw U("getTemplate")}async function zD(e,t){throw U("installTemplate")}async function Ng(e){return u(await l.get(`/projects/${e}/apps`),"Failed to list Apps").apps}async function Kg(e,t){return u(await l.post(`/projects/${e}/apps`,t),"Failed to create App")}async function Zo(e,t){return u(await l.get(`/projects/${e}/apps/${t}`),"Failed to load App")}async function qg(e,t,n){return u(await l.patch(`/projects/${e}/apps/${t}`,n),"Failed to update App")}async function Bg(e,t){return u(await l.delete(`/projects/${e}/apps/${t}`),"Failed to delete App")}async function Gg(e,t){return u(await l.post(`/projects/${e}/apps/${t}/token`,{}),"Failed to mint an App token")}async function Wg(e,t){let n=await Zo(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"),o=new TextEncoder().encode(JSON.stringify(r)),s="";for(let i of o)s+=String.fromCharCode(i);return{KORTIX_AUTH_ISSUER:n.auth.issuer,KORTIX_AUTH_AUDIENCE:n.auth.audience,KORTIX_AUTH_JWKS:`data:application/json;base64,${btoa(s)}`}}async function Hg(e,t){return u(await l.get(`/projects/${e}/apps/${t}/access`),"Failed to load App access policy")}async function Vg(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 zg(e,t,n){return u(await l.patch(`/projects/${e}/apps/${t}/access`,n),"Failed to update App access policy")}async function Yg(e,t){return u(await l.post(`/projects/${e}/apps/${t}/access-session`,{}),"Failed to create App access session")}async function es(e,t){return u(await l.post(`/projects/${e}/apps/artifacts`,t),"Failed to register App artifact")}async function ts(e,t,n){return u(await l.post(`/projects/${e}/apps/artifacts/${t}/finalize`,n),"Failed to finalize App artifact")}async function bP(e){return e instanceof Uint8Array?e:new Uint8Array(await e.arrayBuffer())}async function _P(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 Qg(e,t,n={}){let r=await bP(t),o=n.mediaType??"application/gzip",s=await es(e,{kind:"archive",media_type:o});if(!s.upload)throw new Error("App artifact registration did not return an upload URL");if(r.byteLength>s.upload.max_bytes)throw new Error(`App artifact exceeds ${s.upload.max_bytes} bytes`);n.onProgress?.(0,r.byteLength);let i=await fetch(s.upload.url,{method:"PUT",body:new Blob([Uint8Array.from(r).buffer],{type:o}),signal:n.signal,headers:{"content-type":o,"x-upsert":"false"}});if(!i.ok){let a=await i.text().catch(()=>"");throw new Error(`App artifact upload failed with HTTP ${i.status}${a?`: ${a}`:""}`)}return n.onProgress?.(r.byteLength,r.byteLength),ts(e,s.artifact.artifact_id,{sha256:await _P(r),size_bytes:r.byteLength})}async function Xg(e,t,n){return u(await l.post(`/projects/${e}/apps/${t}/deployments`,n),"Failed to create App deployment")}async function Jg(e,t){return u(await l.get(`/projects/${e}/apps/${t}/deployments`),"Failed to list App deployments").deployments}async function Zg(e,t,n){return u(await l.get(`/projects/${e}/apps/${t}/deployments/${n}`),"Failed to load App deployment")}async function em(e,t,n,r={}){let o=new URLSearchParams;r.after!==void 0&&o.set("after",String(r.after)),r.limit!==void 0&&o.set("limit",String(r.limit));let s=o.size?`?${o.toString()}`:"";return u(await l.get(`/projects/${e}/apps/${t}/deployments/${n}/logs${s}`),"Failed to load App logs")}async function tm(e,t){return u(await l.post(`/projects/${e}/apps/${t}/start`,{}),"Failed to start App")}async function nm(e,t){return u(await l.post(`/projects/${e}/apps/${t}/stop`,{}),"Failed to stop App")}async function rm(e,t,n){return u(await l.delete(`/projects/${e}/apps/${t}/deployments/${n}`),"Failed to delete App deployment")}async function om(e,t,n){return u(await l.post(`/projects/${e}/apps/${t}/rollback`,{deployment_id:n}),"Failed to roll back App")}var ue=(e,t)=>`/projects/${e}/apps/${t}`;async function sm(e,t){return u(await l.get(`${ue(e,t)}/machines`),"Failed to list machines").machines}async function ns(e,t,n,r){return u(await l.post(`${ue(e,t)}/machines/${n}/${r}`,{}),`Failed to ${r} the machine`).machines}var im=(e,t,n)=>ns(e,t,n,"start"),am=(e,t,n)=>ns(e,t,n,"stop"),cm=(e,t,n)=>ns(e,t,n,"restart");async function lm(e,t,n){return u(await l.delete(`${ue(e,t)}/machines/${n}`),"Failed to destroy the machine").machines}async function um(e,t,n){return u(await l.put(`${ue(e,t)}/scale`,{count:n}),"Failed to scale the App")}async function pm(e,t,n){return u(await l.post(`${ue(e,t)}/exec`,n),"Failed to run the command")}async function dm(e,t){return u(await l.get(`${ue(e,t)}/volumes`),"Failed to list volumes").volumes}async function gm(e,t,n){return u(await l.post(`${ue(e,t)}/volumes`,n),"Failed to create the volume")}async function mm(e,t,n,r){return u(await l.patch(`${ue(e,t)}/volumes/${n}`,r),"Failed to update the volume")}async function fm(e,t,n,r){u(await l.delete(`${ue(e,t)}/volumes/${n}?confirm=${encodeURIComponent(r)}`),"Failed to destroy the volume")}async function ym(e,t,n){return u(await l.get(`${ue(e,t)}/volumes/${n}/snapshots`),"Failed to list snapshots").snapshots}async function hm(e,t,n){return u(await l.post(`${ue(e,t)}/volumes/${n}/snapshots`,{}),"Failed to take the snapshot")}async function bm(e,t,n,r){return u(await l.post(`${ue(e,t)}/volumes/${n}/restore`,{snapshot_id:r}),"Failed to restore the volume")}async function _m(e,t,n,r){return u(await l.post(`${ue(e,t)}/volumes/${n}/fork`,r),"Failed to fork the volume")}function se(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return t===e.length?e:e.slice(0,t)}var ie=e=>`/drives/${encodeURIComponent(e)}`;async function cj(e){let t=u(await l.get(`/drives?${new URLSearchParams({projectId:e})}`),"Failed to load files").drives;if(!t[0])throw new b("Files not found",{status:404});return t[0]}async function lj(e,t){return u(await l.get(`${ie(e)}/access?${new URLSearchParams({path:t})}`),"Failed to load sharing")}async function uj(e,t){return u(await l.put(`${ie(e)}/access`,t),"Failed to share folder")}async function pj(e,t){let n=u(await l.delete(`${ie(e)}/access/${encodeURIComponent(t)}`),"Failed to stop sharing");return{pendingSessions:typeof n?.pendingSessions=="number"?n.pendingSessions:0}}async function dj(e){return u(await l.get(`${ie(e)}/principals`),"Failed to load people")}async function gj(e){return u(await l.get(`${ie(e)}/conflicts`),"Failed to load conflicts").conflicts}async function mj(e,t){u(await l.post(`${ie(e)}/conflicts/${encodeURIComponent(t)}/dismiss`,{}),"Failed to dismiss conflict")}async function fj(e,t="/"){return(await PP(e,t)).entries}async function PP(e,t="/"){return u(await l.get(`${ie(e)}/files?${new URLSearchParams({path:t})}`),"Failed to load files")}function Pm(e,t,n){let r=se(v().backendUrl),o={path:t};return n?.download&&(o.download="1"),`${r}${ie(e)}/files/content?${new URLSearchParams(o)}`}async function yj(e,t,n){let r=await E(Pm(e,t),{signal:n});if(!r.ok){let o=await r.json().catch(()=>null);throw new b(o?.message||"Could not download file",{status:r.status})}return r.blob()}async function hj(e,t,n){let r=await E(Pm(e,t),{signal:n});if(!r.ok){let o=await r.json().catch(()=>null);throw new b(o?.message||"Could not download file",{status:r.status})}return{blob:await r.blob(),version:r.headers.get("etag")}}async function bj(e,t,n,r){return u(await l.putRaw(`${ie(e)}/files/content?${new URLSearchParams({path:t})}`,n,{signal:r?.signal,...r?.ifMatch?{headers:{"If-Match":r.ifMatch}}:{}}),"Failed to upload file")}async function _j(e,t){return u(await l.post(`${ie(e)}/files/mkdir`,{path:t}),"Failed to create folder")}async function Pj(e,t,n){return u(await l.post(`${ie(e)}/files/move`,{from:t,to:n}),"Failed to move")}async function xj(e,t,n){let r={path:t};n?.recursive&&(r.recursive="true"),u(await l.delete(`${ie(e)}/files?${new URLSearchParams(r)}`),"Failed to delete")}async function Sj(e){return u(await l.get(`${ie(e)}/versions`),"Failed to load versions").versions}async function wj(e,t){u(await l.post(`${ie(e)}/restore`,{versionId:t}),"Failed to restore version")}var xP=(e,t)=>`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/drives`;async function Aj(e,t){return(await SP(e,t)).drives}async function SP(e,t){return u(await l.get(xP(e,t)),"Failed to load session files")}async function xm(e){return u(await l.post("/notifications/device-token",e))}async function Sm(e,t){return u(await l.delete(`/notifications/device-token/${encodeURIComponent(e)}`,{signal:t?.signal}))}var Cj=["turn_done","turn_error","question","permission","shared","automation_failed","automation_recovered"];async function wm(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 Am(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 Ij={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}};async function vm(){return u(await l.get("/notifications/preferences",{showErrors:!1}))}async function km(e){return u(await l.put("/notifications/preferences",e))}async function Rm(){return u(await l.get("/notifications/web-push/key",{showErrors:!1}))}async function Cm(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 Im(e,t){return u(await l.delete(`/notifications/web-push/subscriptions?endpoint=${encodeURIComponent(e)}`,{signal:t?.signal,showErrors:!1}))}async function Sr(e){return u(await l.get(`/projects/${e}/model-access`))}async function wr(e,t){return u(await l.put(`/projects/${e}/model-access`,t))}function Dj(e){let{running:t,isCarousel:n,contentStatus:r,isWebsitePreview:o,previewHasError:s,previewIsLinkOnly:i}=e;return t||n?!1:o?s&&!i:r==="error"}function rs(e){return typeof e=="string"&&e.trim().length>0}function Tm(e){if(!e||typeof e!="object")return!1;let{path:t,url:n,content:r}=e;return rs(t)||rs(n)||rs(r)}function wP(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 Ar(e){if(!e)return!0;let t=wP(e.items);return t?!t.some(Tm):!Tm(e)}function pe(e){return(e??"").replace(/^oc-/,"").replace(/-/g,"_")}function Uj(e){return pe(e)==="bash"}function Lj(e){let t=pe(e);return t==="question"||t==="ask"}function Fj(e,t){let n=Math.max(0,e);return`${t?"Running":"Ran"} ${n} command${n===1?"":"s"}`}var AP=new Set(["show","show_user"]);function Em(e){return AP.has(pe(e))}function Nj(e,t){let n=Math.max(0,e);return`${t?"Writing":"Wrote"} ${n} file${n===1?"":"s"}`}function Mm(e){return!!(e.type==="snapshot"||e.type==="patch"||e.type==="step-start"||e.type==="step-finish"||e.type==="text"&&!e.text?.trim()||os(e))}function os(e){let t=pe(e.tool);return t!=="show"&&t!=="show_user"||e.state?.status!=="completed"?!1:Ar(e.state?.input)}var vP=new Set(["show","show_user","agent_spawn","agent_status","agent_message","agent_task_update","agent_stop"]);function Om(e){return vP.has(pe(e))}var kP=50*1024*1024,ss="[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",RP=new RegExp(`^kortix-attachment://(${ss})/(${ss})/(${ss})$`);function as(e){if(typeof e!="string")return null;let t=RP.exec(e);return t?{projectId:t[1],sessionId:t[2],attachmentId:t[3]}:null}function Vj(e){return as(e)!==null}var is=new WeakMap;async function Dm(e,t,n,r={}){if(n.size>kP)throw new Error("Attachments must be 50 MiB or smaller.");let o=`${e}/${t}`,s=r.attachmentId?void 0:is.get(n)?.get(o);if(s?.promise)return s.promise;let i=s??{id:r.attachmentId??crypto.randomUUID(),promise:void 0};if(!r.attachmentId){let c=is.get(n)??new Map;c.set(o,i),is.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 jm(e,t){let n=as(e);if(!n)throw new Error("Invalid attachment reference");let r=v().backendUrl.replace(/\/$/,""),o=await E(`${r}/projects/${n.projectId}/sessions/${n.sessionId}/attachments/${n.attachmentId}`,{signal:t});if(!o.ok)throw new b("Could not load attachment",{status:o.status});return o.blob()}var CP=new Set(["show","show_user"]);function IP(e){let t=[],n=0;for(;;){let r=e.indexOf("<file",n);if(r===-1)return t;let o=r+5;if(o>=e.length||!/\s/.test(e[o])){n=o;continue}let s=e.indexOf(">",o);if(s===-1)return t;let i=e.indexOf("</file>",s+1);if(i===-1)return t;t.push(e.slice(o,s).trimStart()),n=i+7}}var Rt=e=>!!e&&typeof e=="object"&&!Array.isArray(e),Zt=e=>typeof e=="string"&&e.length>0?e:null,$m=e=>typeof e=="string"?Zt(e.split("/").pop()):null;function vr(e,t){let n=e.match(new RegExp(`(?:^|\\s)${t}="([^"]*)"`))?.[1];return n===void 0?null:n.replace(/&quot;/g,'"').replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&")}function TP(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 EP(e,t){for(let n of IP(e))t(vr(n,"attachment"),vr(n,"filename")??$m(vr(n,"path")),vr(n,"mime"))}function MP(e,t){for(let n of[e,...TP(e.items)])Rt(n)&&t(n.attachment,$m(n.path),null)}function zj(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let r of e){if(!Rt(r)||!Rt(r.info)||!Array.isArray(r.parts))continue;let o=Zt(r.info.id);if(!o)continue;let s=Zt(r.info.role)??"unknown",i=(a,c,p)=>{let d=as(a);!d||n.has(a)||(n.add(a),t.push({url:a,attachment_id:d.attachmentId,filename:c,mime:p,message_id:o,role:s}))};for(let a of r.parts)Rt(a)&&(a.type==="file"?i(a.url,Zt(a.filename),Zt(a.mime)):a.type==="text"&&typeof a.text=="string"?EP(a.text,i):a.type==="tool"&&typeof a.tool=="string"&&CP.has(pe(a.tool))&&Rt(a.state)&&Rt(a.state.input)&&MP(a.state.input,i))}return t}function Ke(e){try{return typeof process<"u"?process.env?.[e]:void 0}catch{return}}function OP(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 Zj(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 cs(e,t,n){return e!==void 0?e:OP(Ke(t),n)}var Um={get disableMobileAdvertising(){return cs(v().featureFlags?.disableMobileAdvertising,"NEXT_PUBLIC_DISABLE_MOBILE_ADVERTISING",!1)},get enableDinoGame(){return cs(v().featureFlags?.enableDinoGame,"NEXT_PUBLIC_ENABLE_DINO_GAME",!1)},get enableProjects(){return cs(v().featureFlags?.enableProjects,"NEXT_PUBLIC_ENABLE_PROJECTS",!1)},get enableAutoModel(){return!1}};var DP=new Set(["project-manager"]);function ls(e){return e.native===!0||e.mode==="subagent"||e.hidden||e.enabled===!1?!1:Um.enableProjects||!DP.has(e.name)}function n$(e){let t=e.agents.filter(ls),n=e.default_agent??e.open_code_default_agent;return n?t.sort((r,o)=>r.name===n?-1:o.name===n?1:0):t}function Lm(){return{projects:{list:_t,listForAccount:Pa,get:Qn,detail:Xn,create:Aa,createRepo:va,provision:ka,update:er,archive:tr,llmCatalog:Jn,modelPicker:Zn,modelAccess:Sr,setModelAccess:wr,sandboxHealth:or,sandboxTemplates:hl,sessions:At,createSession:vt},github:{linkRepository:Ma,replaceProjectRepository:Oa,getInstallation:Da,listInstallations:ja,listLinkableInstallations:$a,listRepositories:Ua,listRepositoryBranches:La,linkInstallation:Na,saveInstallation:Fa,deleteInstallation:qa,storeUserToken:Ka},gitBackend:{get:Ba,repositories:Ga},connectStatus:ll,marketplace:{items:s=>Mg(s),item:s=>jg(s),itemFile:(s,i)=>$g(s,i),marketplaces:()=>Og(),featured:()=>Dg(),sources:{list:()=>Ug(),add:s=>Lg(s),remove:s=>Fg(s)}}}}function Fm(){return{billing:{accountState:_p,accountStateMinimal:Pp,transactions:xp,transactionsSummary:Sp,creditBreakdown:wp,usageHistory:Ap,usageRollup:Up,sessionCosts:{list:Fp,get:Pr},tierConfigurations:vp,checkout:{createSession:n=>kp(n),confirmSession:(n,r)=>Rp(n,r)},subscription:{createPortalSession:(n,r)=>Cp(n,r),cancel:(n,r)=>Ip(n,r),reactivate:n=>Tp(n),scheduleDowngrade:(n,r,o)=>Ep(n,r,o),cancelScheduledChange:n=>Mp(n),prorationPreview:(n,r)=>Op(n,r)},credits:{purchase:n=>Dp(n),autoTopupSettings:n=>jp(n),configureAutoTopup:n=>$p(n)}},sandboxShares:{list:og,create:sg,revoke:ig}}}var qe={DESKTOP:"6080",DESKTOP_HTTPS:"6081",PRESENTATION_VIEWER:"3210",STATIC_FILE_SERVER:"3211",KORTIX_MASTER:"8000",BROWSER_STREAM:"9223",BROWSER_VIEWER:"9224",SSH:"22"};function Be(){let e=Ke("BACKEND_URL")||v().backendUrl;return e||"http://localhost:8008/v1"}function rt(e){let t=se(e);return t.endsWith("/v1")?t:`${t}/v1`}function en(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=en(t);if(n)return n}return}if(e&&typeof e=="object"){let t=e;return en(t.sandboxId??t.id??t.slug??Object.values(t)[0])}}function jP(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 us(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?`${Be()}/p/${n.external_id}/${qe.KORTIX_MASTER}`:""),status:jP(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 ps(){let e=await _t(),t=[];for(let n of e){let r=await At(n.project_id).catch(()=>[]);for(let o of r)t.push({project:n,session:o,runtime:null,sandbox:us(n,o,null)})}return t.sort((n,r)=>{let o={active:0,provisioning:1,stopped:2,error:3},s=(o[n.sandbox.status]??99)-(o[r.sandbox.status]??99);return s!==0?s:Date.parse(r.sandbox.updated_at)-Date.parse(n.sandbox.updated_at)})}async function ot(e){let t=await ps();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 tn=class extends Error{constructor(n,r,o){super(r);this.code=n;this.status=o;this.name="HeadlessAuthError"}code;status};async function ee(e,t,n){let r=n?.fetch??v().fetch??((p,d)=>fetch(p,d)),o=se(n?.backendUrl??v().backendUrl??"");if(!o)throw new tn("not_configured","backendUrl is not configured (configureKortix / createKortix first)",0);let s={accept:"application/json"};t.body!==void 0&&(s["content-type"]="application/json"),t.bearer&&(s.authorization=`Bearer ${t.bearer}`);let i=await r(`${rt(o)}${e}`,{method:t.method??(t.body!==void 0?"POST":"GET"),headers:s,...t.body!==void 0?{body:JSON.stringify(t.body)}:{},...n?.signal?{signal:n.signal}:{}}),a=await i.text().catch(()=>""),c=null;try{c=a?JSON.parse(a):null}catch{c=a}if(!i.ok){let p=c&&typeof c=="object"?c:{};throw new tn(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 ds(e,t){return ee("/auth/signup",{body:e},t)}function gs(e,t){return ee("/auth/sign-in/password",{body:e},t)}function ms(e,t){return ee("/auth/sign-in/magic-link",{body:e},t)}function fs(e,t){return ee("/auth/verify-otp",{body:e},t)}function ys(e,t){return ee("/auth/sign-in/oauth",{body:e},t)}function hs(e,t){return ee("/auth/oauth/exchange",{body:e},t)}function nn(e,t){return ee("/auth/refresh",{body:e},t)}function bs(e,t){return ee("/auth/password/reset",{body:e},t)}function _s(e,t,n){return ee("/auth/password/update",{body:e,bearer:t},n)}function Ps(e,t){return ee("/auth/user",{bearer:e},t)}function xs(e,t,n){return ee("/auth/user",{method:"PATCH",body:e,bearer:t},n)}function Ss(e,t){return ee("/auth/sign-in/sso",{body:e},t)}var ws={enroll:(e,t,n)=>ee("/auth/mfa/factors",{body:e,bearer:t},n),challenge:(e,t={},n,r)=>ee(`/auth/mfa/factors/${encodeURIComponent(e)}/challenge`,{body:t,bearer:n},r),verify:(e,t,n,r)=>ee(`/auth/mfa/factors/${encodeURIComponent(e)}/verify`,{body:t,bearer:n},r),unenroll:(e,t,n)=>ee(`/auth/mfa/factors/${encodeURIComponent(e)}`,{method:"DELETE",bearer:t},n)};function As(e,t={},n){return ee("/auth/sign-out",{body:t,bearer:e},n)}function vs(e={}){let t=e.refreshSkewSeconds??60,n=e.now??(()=>Date.now()),r=null,o=null,s=!e.storage,i=null,a=null,c=0,p=new Set,d=P=>(P.expires_at??0)*1e3,g=P=>d(P)-t*1e3<=n();async function m(){e.storage&&(r?await e.storage.set(JSON.stringify({session:r,user:o})):await e.storage.remove());for(let P of[...p])try{P(r)}catch{}try{e.onChange?.(r)}catch{}}async function f(){if(s)return r;if(!i){let P=c,j=(async()=>{let L=await e.storage.get();if(P===c&&L)try{let N=JSON.parse(L);N.session?.access_token&&N.session?.refresh_token&&(r=N.session,o=N.user??null)}catch{r=null}return s=!0,r})();i=j,j.then(()=>{i===j&&(i=null)},()=>{i===j&&(i=null)})}return i}async function h(){if(await f(),!r)return null;if(!a){let P=r.refresh_token,j=c,L=nn({refresh_token:P},e.request).then(async N=>(j!==c||(r=N.session,N.user&&(o=N.user),await m()),r)).catch(async N=>{if(j!==c)return r;let y=N&&typeof N=="object"&&"status"in N?N.status:0;if(y>=400&&y<500)return r=null,o=null,await m(),null;throw N}).finally(()=>{a===L&&(a=null)});a=L}return a}return{subscribe(P){return p.add(P),()=>{p.delete(P)}},current:()=>r,user:()=>o,load:f,async set(P,j){await f(),c+=1,a=null,r=P,j!==void 0&&(o=j),P||(o=null),await m()},async getToken(){return await f(),r?g(r)?(await h().catch(()=>r))?.access_token??null:r.access_token:null},refresh:h,async clear(){c+=1,a=null,r=null,o=null,s=!0,await m()}}}function Nm(){return{list:Xi,get:Zi,create:Ji,secretResources:{list:Sc,create:wc,rotate:Ac,retry:vc,remove:kc,grant:Rc,revoke:Cc,setAccess:Ic},updateName:ea,branding:{get:ta,update:na,uploadAsset:ra,removeAsset:oa,reset:sa},leave:ha,members:ia,invite:aa,removeMember:fa,updateMemberRole:ya,invites:ca,cancelInvite:la,resendInvite:ua,tokens:{list:fg,create:yg,revoke:hg},connectedApps:{list:bg,revoke:_g},audit:{log:wg,export:vg,webhooks:{list:kg,create:Rg,update:Cg,remove:Ig}}}}function Km(){return{assignments:{list:Hd,create:Vd,revoke:zd},permissions:{list:Yd,forRole:Md},roles:{list:Id,create:Dd,update:jd,setPermissions:$d,remove:Ud,usage:Od},groups:{list:xd,get:Sd,create:wd,update:Ad,remove:vd,members:{list:kd,add:Rd,remove:Cd}},agentIdentities:Td,oauthClients:{list:Nd,get:Kd,create:qd,update:Bd,rotateSecret:Gd,remove:Wd},can:Ld,canBatch:Fd}}function qm(){let e={signUp:ds,signInWithPassword:gs,sendMagicLink:ms,verifyOtp:fs,signInWithProvider:ys,exchangeCode:hs,refresh:nn,resetPassword:bs,updatePassword:_s,updateUserMetadata:xs,signInWithSso:Ss,mfa:ws,user:Ps,signOut:As,session:vs},t=Nm(),n=Km();return{auth:e,accounts:t,iam:n,accountInvites:{listMine:pa,describe:da,accept:ga,decline:ma}}}var rn=new Map,ks=new Map;function Rs(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function Bm(e){return rn.get(Rs(e))??null}function Gm(){return[...rn.values()].filter(e=>typeof e=="string")}function Wm(e){return rn.has(Rs(e))}async function st(e){let t=Rs(e),n=rn.get(t);if(n!==void 0)return n;let r=ks.get(t);if(r)return r;let o=(async()=>{try{let s=await l.get("/p/config",{showErrors:!1,errorContext:{operation:"load preview config",silent:!0}});if(!s.success)return null;let i=typeof s.data?.preview_url_template=="string"?s.data.preview_url_template:null;return rn.set(t,i),i}catch{return null}finally{ks.delete(t)}})();return ks.set(t,o),o}function Hm(e){let{apiBaseUrl:t}=e;return Wm(t)||st(t).catch(()=>{}),{sandboxId:e.sandboxId,backendPort:e.backendPort,apiBaseUrl:t,previewUrlTemplate:Bm(t)}}function Vm(e){function t(n){try{return new URL(n)}catch{if(typeof window<"u"&&window.location?.origin)try{return new URL(n,window.location.origin)}catch{return null}throw new b(`Kortix SDK: backendUrl must be an absolute URL outside the browser (got ${JSON.stringify(n)}). Relative paths like "/api/kortix" only resolve against a page origin \u2014 configure an absolute backendUrl for server-side hosts.`,{code:"INVALID_BACKEND_URL"})}}return function(r){let o=v().backendUrl??e.backendUrl,s=80,i=t(o);return i&&(s=i.port?Number(i.port):i.protocol==="https:"?443:80),Hm({sandboxId:r,apiBaseUrl:o,backendPort:s})}}function zm(e,t){let n=null;async function r(){n||(n=gr(e,t,{showErrors:!1}).then(o=>{let s=Gu(o)??"",i=s.indexOf("/"),a=i>0&&i<s.length-1?{providerID:s.slice(0,i),modelID:s.slice(i+1)}:void 0,c=o.agent_name?.trim()||void 0;return{model:a,agent:c}}));try{return await n}catch(o){throw n=null,o}}return{persistedPromptDefaults:r,clearPersistedDefaults:()=>{n=null}}}var on=new Map;function Ym(e){let t=`Session runtime not ready (stage: ${e?.stage??"unknown"})`,n=e?.failure,r=[];n?.category&&r.push(n.category),n?.message&&r.push(n.message);let o=n?.evidence?.error;return o&&o!==n?.message&&r.push(o),r.length===0&&e?.reason&&r.push(e.reason),r.length>0?`${t}: ${r.join(" \u2014 ")}`:t}var Ct=class extends Error{constructor(t){super(`Session runtime not ready \u2014 call \`await session.ensureReady()\` (it drives \`start()\` to completion and resolves this session's own sandbox runtime) before calling \`${t}\`.`),this.name="SessionNotReadyError"}};var It={url:null,sandboxId:null,dbSandboxId:null,version:0},UP=new Set;function Qm(e,t=null,n=null){if(!(It.url===e&&It.sandboxId===t&&It.dbSandboxId===n)){It={url:e,sandboxId:t,dbSandboxId:n,version:It.version+1};for(let r of UP)r()}}function Xm(){return It.url}function Jm(e,t){async function n(r){let o=Date.now()+r,s=()=>Math.max(0,o-Date.now()),i=await nt(e,t,Math.min(3e4,s()));for(;Date.now()<o&&(i==null||(i.stage==="provisioning"||i.stage==="starting")&&i.retriable);)await new Promise(d=>setTimeout(d,Math.min(1e3,s()))),i=await nt(e,t,Math.min(3e4,s()));let a=i?.runtime_session_id??i?.opencode_session_id;if(!i||i.stage!=="ready"||!i.sandbox||!a)throw new b(Ym(i),{code:"RUNTIME_UNAVAILABLE"});let c=i.sandbox.external_id;if(!c)throw new b("Session sandbox has no external_id \u2014 cannot resolve its runtime URL",{code:"RUNTIME_UNAVAILABLE"});let p=tt(c);return Qm(p,c),{runtimeSessionId:a,opencodeSessionId:a,runtimeUrl:p,sandboxId:c}}return n}function Zm(e,t,n){let r=null;function o(){if(r)return r;let p=np(e,t);return p&&(r=p),r}let s=Jm(e,t);async function i(p){let d=o();if(d)return d;let g=p?.readyTimeoutMs??18e4,m=st(v().backendUrl??n.backendUrl).catch(()=>null),f=`${e}
15
+ ${t}`,h=on.get(f);if(h)return r=await h,await m,r;let P=s(g);on.set(f,P);try{return r=await P,await m,r}finally{on.get(f)===P&&on.delete(f)}}function a(p){let d=o();if(!d)throw new Ct(p);return d}function c(){r=null,op(e,t)}return{ensureReady:i,tryResolveReady:o,requireReady:a,forgetReady:c}}var B=["directory","workspace"],ef=["messageID","model","agent","noReply","tools","format","system","variant","parts"],k=(e,t,n=B,r=[],o)=>({method:e,path:t,query:n,body:r,bodyParam:o}),LP={"session.list":k("GET","/session",[...B,"scope","path","roots","start","search","limit"]),"session.get":k("GET","/session/{sessionID}"),"session.create":k("POST","/session",B,["parentID","title","agent","model","metadata","permission","workspaceID"]),"session.delete":k("DELETE","/session/{sessionID}"),"session.update":k("PATCH","/session/{sessionID}",B,["title","metadata","permission","time"]),"session.status":k("GET","/session/status"),"session.messages":k("GET","/session/{sessionID}/message",[...B,"limit","before"]),"session.prompt":k("POST","/session/{sessionID}/message",B,ef),"session.promptAsync":k("POST","/session/{sessionID}/prompt_async",B,ef),"session.abort":k("POST","/session/{sessionID}/abort"),"session.revert":k("POST","/session/{sessionID}/revert",B,["messageID","partID"]),"session.unrevert":k("POST","/session/{sessionID}/unrevert"),"session.summarize":k("POST","/session/{sessionID}/summarize",B,["providerID","modelID","auto"]),"session.command":k("POST","/session/{sessionID}/command",B,["messageID","agent","model","arguments","command","variant","parts"]),"session.share":k("POST","/session/{sessionID}/share"),"session.unshare":k("DELETE","/session/{sessionID}/share"),"session.fork":k("POST","/session/{sessionID}/fork",B,["messageID"]),"session.diff":k("GET","/session/{sessionID}/diff",[...B,"messageID"]),"session.todo":k("GET","/session/{sessionID}/todo"),"permission.list":k("GET","/permission"),"permission.reply":k("POST","/permission/{requestID}/reply",B,["reply","message"]),"question.list":k("GET","/question"),"question.reply":k("POST","/question/{requestID}/reply",B,["answers"]),"question.reject":k("POST","/question/{requestID}/reject"),"part.update":k("PATCH","/session/{sessionID}/message/{messageID}/part/{partID}",B,[],"part"),"part.delete":k("DELETE","/session/{sessionID}/message/{messageID}/part/{partID}"),"file.list":k("GET","/file",[...B,"path"]),"file.read":k("GET","/file/content",[...B,"path"]),"find.files":k("GET","/find/file",[...B,"query","dirs","type","limit"]),"vcs.diff":k("GET","/vcs/diff",[...B,"mode","context"]),"global.health":k("GET","/global/health",[]),"global.dispose":k("POST","/global/dispose",[]),"global.config.get":k("GET","/global/config",[]),"global.config.update":k("PATCH","/global/config",[],[],"config"),"provider.list":k("GET","/provider"),"provider.auth":k("GET","/provider/auth"),"provider.oauth.authorize":k("POST","/provider/{providerID}/oauth/authorize",B,["method","inputs"]),"provider.oauth.callback":k("POST","/provider/{providerID}/oauth/callback",B,["method","code"]),"auth.set":k("PUT","/auth/{providerID}",[],[],"auth"),"app.agents":k("GET","/agent"),"app.skills":k("GET","/skill"),"app.log":k("POST","/log",B,["service","level","message","extra"]),"command.list":k("GET","/command"),"tool.ids":k("GET","/experimental/tool/ids"),"tool.list":k("GET","/experimental/tool",[...B,"provider","model"]),"mcp.status":k("GET","/mcp"),"mcp.add":k("POST","/mcp",B,["name","config"]),"mcp.connect":k("POST","/mcp/{name}/connect"),"mcp.disconnect":k("POST","/mcp/{name}/disconnect"),"mcp.auth.start":k("POST","/mcp/{name}/auth"),"mcp.auth.callback":k("POST","/mcp/{name}/auth/callback",B,["code"]),"mcp.auth.remove":k("DELETE","/mcp/{name}/auth"),"project.list":k("GET","/project"),"project.current":k("GET","/project/current"),"path.get":k("GET","/path")};function FP(e,t){let n=[];for(let r of e.query){let o=t[r];o!=null&&n.push(`${r}=${encodeURIComponent(String(o))}`)}return n.length?`?${n.join("&")}`:""}function NP(e,t,n={},r={}){let o=LP[t],s=o.path.replace(/\{(\w+)\}/g,(p,d)=>encodeURIComponent(String(n[d]))),i,a=!1;if(o.bodyParam)i=n[o.bodyParam],a=i!==void 0;else for(let p of o.body)p in n&&(i={...i,[p]:n[p]},a=!0);let c=new Headers(r.headers);return a&&c.set("Content-Type","application/json"),new Request(`${e.replace(/\/$/,"")}${s}${FP(o,n)}`,{method:o.method,headers:c,redirect:"follow",...a?{body:JSON.stringify(i)}:{},...r.signal?{signal:r.signal}:{}})}function KP(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 qP(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=KP(r.headers.get("Content-Type"));if(r.status===204||r.headers.get("Content-Length")==="0")return{data:i==="json"?{}:i==="formData"?new FormData:i==="stream"?r.body:await r[i](),request:t,response:r};if(i==="stream")return{data:r.body,request:t,response:r};if(i==="json"){let a=await r.text();return{data:a?JSON.parse(a):{},request:t,response:r}}return{data:await r[i](),request:t,response:r}}let o=await r.text(),s=o;try{s=JSON.parse(o)}catch{}return{error:s||{},request:t,response:r}}function Cs(e=globalThis.fetch){return async function*({url:t,headers:n,signal:r}){let o=await e(new Request(t,{method:"GET",headers:n,signal:r,redirect:"follow"}));if(!o.ok)throw Object.assign(new Error(`SSE failed: ${o.status} ${o.statusText}`),{status:o.status});if(!o.body)throw new Error("No body in SSE response");let s=o.body.pipeThrough(new TextDecoderStream).getReader(),i=()=>{try{s.cancel()}catch{}};r.addEventListener("abort",i);try{let a="";for(;;){let{done:c,value:p}=await s.read();if(c)break;a=(a+p).replace(/\r\n/g,`
16
16
  `).replace(/\r/g,`
17
17
  `);let d=a.split(`
18
18
 
19
19
  `);a=d.pop()??"";for(let g of d){let m={},f=[];for(let h of g.split(`
20
- `))if(h.startsWith("data:"))f.push(h.replace(/^data:\s*/,""));else if(h.startsWith("id:"))m.id=h.replace(/^id:\s*/,"");else if(h.startsWith("retry:")){let S=Number.parseInt(h.replace(/^retry:\s*/,""),10);Number.isNaN(S)||(m.retry=S)}f.length&&(m.data=f.join(`
21
- `)),yield m}}}finally{r.removeEventListener("abort",i),s.releaseLock()}}}async function*lP(e,t,n){let r=e.eventTransport??bs(e.fetch??globalThis.fetch),o=n.signal??new AbortController().signal,s=n.sseDefaultRetryDelay??3e3,i;for(let a=1;!o.aborted;a++)try{let c=new Headers(n.headers);i!==void 0&&c.set("Last-Event-ID",i);for await(let p of r({url:new URL(t).href,headers:c,signal:o}))if(p.id!==void 0&&(i=p.id),p.retry!==void 0&&(s=p.retry),p.data!==void 0)try{yield JSON.parse(p.data)}catch{yield p.data}return}catch(c){if(n.onSseError?.(c),n.sseMaxRetryAttempts!==void 0&&a>=n.sseMaxRetryAttempts)return;let p=Math.min(s*2**(a-1),n.sseMaxRetryDelay??3e4);await new Promise(d=>setTimeout(d,p))}}function Xt(e){let t=o=>(s,i)=>cP(e,iP(e.baseUrl,o,s,i)),n=o=>s=>t(o)(void 0,s);return{session:{list:t("session.list"),get:t("session.get"),create:t("session.create"),delete:t("session.delete"),update:t("session.update"),status:t("session.status"),messages:t("session.messages"),prompt:t("session.prompt"),promptAsync:t("session.promptAsync"),abort:t("session.abort"),revert:t("session.revert"),unrevert:t("session.unrevert"),summarize:t("session.summarize"),command:t("session.command"),share:t("session.share"),unshare:t("session.unshare"),fork:t("session.fork"),diff:t("session.diff"),todo:t("session.todo")},permission:{list:t("permission.list"),reply:t("permission.reply")},question:{list:t("question.list"),reply:t("question.reply"),reject:t("question.reject")},part:{update:t("part.update"),delete:t("part.delete")},file:{list:t("file.list"),read:t("file.read")},find:{files:t("find.files")},vcs:{diff:t("vcs.diff")},global:{event:async(o={})=>({stream:lP(e,`${e.baseUrl.replace(/\/$/,"")}/global/event`,o)}),health:n("global.health"),dispose:n("global.dispose"),config:{get:n("global.config.get"),update:t("global.config.update")}},provider:{list:t("provider.list"),auth:t("provider.auth"),oauth:{authorize:t("provider.oauth.authorize"),callback:t("provider.oauth.callback")}},auth:{set:t("auth.set")},app:{agents:t("app.agents"),skills:t("app.skills"),log:t("app.log")},command:{list:t("command.list")},tool:{ids:t("tool.ids"),list:t("tool.list")},mcp:{status:t("mcp.status"),add:t("mcp.add"),connect:t("mcp.connect"),disconnect:t("mcp.disconnect"),auth:{start:t("mcp.auth.start"),callback:t("mcp.auth.callback"),remove:t("mcp.auth.remove")}},project:{list:t("project.list"),current:t("project.current")},path:{get:t("path.get")}}}var $m=200;async function uP(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 Je(e,t){if(e.error===void 0)return e.data;let n=e.error,r=typeof n=="string"?n:n?.data?.message||n?.message||n?.error||"request failed";throw new b(`${t}: ${r}`,{...e.response?{status:e.response.status,response:e.response}:{}})}function Um(e){let t=e.runtimeUrl.replace(/\/$/,""),n=Xt({baseUrl:t,fetch:e.fetch});return{messages:async(r={})=>{let o=encodeURIComponent(r.conversationId??e.rootId),s=async(c,p)=>{let d=new URLSearchParams;c!==void 0&&d.set("limit",String(c)),p&&d.set("before",p);let g=`/messages/${o}${d.size?`?${d}`:""}`,m=S=>e.fetch(new Request(`${t}${S}${g}`,{method:"GET",...r.signal?{signal:r.signal}:{}})),f=await m("/kortix/runtime");if((f.status===404||(f.headers.get("content-type")??"").startsWith("text/html"))&&(f=await m("/kortix/opencode")),!f.ok)throw new b(`Reading the session transcript failed: ${await uP(f)}`,{status:f.status,response:f});let h=await f.json();return{messages:h.messages??[],hasMore:h.has_more===!0}},i=await s(r.limit===void 0?void 0:Math.min(r.limit,$m),r.before),a=[...i.messages];for(;r.limit!==void 0&&a.length<r.limit&&i.hasMore&&a.length>0&&(i=await s(Math.min(r.limit-a.length,$m),a[0].info.id),!!i.messages.length);)a.unshift(...i.messages);return{messages:a,hasMore:i.hasMore}},pending:async()=>{let[r,o,s]=await Promise.all([n.session.status().then(i=>Je(i,"Reading the session status failed")),n.permission.list().then(i=>Je(i,"Reading permission requests failed")),n.question.list().then(i=>Je(i,"Reading questions failed"))]);return{statuses:r??{},permissions:o??[],questions:s??[]}},answerPermission:async(r,o,s)=>{Je(await n.permission.reply({requestID:r,reply:o,...s!==void 0?{message:s}:{}}),"Answering the permission request failed")},answerQuestion:async(r,o)=>{if(o===null){Je(await n.question.reject({requestID:r}),"Dismissing the question failed");return}Je(await n.question.reply({requestID:r,answers:o}),"Answering the question failed")},compact:async r=>{let o=r;if(!o){let s=await n.global.config.get().then(c=>c.error===void 0?c.data:null),i=typeof s?.model=="string"?s.model:"",a=i.indexOf("/");a>0&&a<i.length-1&&(o={providerID:i.slice(0,a),modelID:i.slice(a+1)})}if(!o)throw new b("Cannot compact: no model is set for this session",{code:"MODEL_REQUIRED"});return Je(await n.session.summarize({sessionID:e.rootId,providerID:o.providerID,modelID:o.modelID}),"Compacting the session failed"),o}}}function Fm(e){async function t(){let{runtimeSessionId:n,runtimeUrl:r}=await e.ensureReady();return Um({runtimeUrl:r,rootId:n,fetch:M})}return{messages:async n=>(await t()).messages(n),pending:async()=>(await t()).pending(),answerPermission:async(n,r,o)=>(await t()).answerPermission(n,r,o),answerQuestion:async(n,r)=>(await t()).answerQuestion(n,r),compact:async n=>(await t()).compact(n)}}function Lm(e){return{setModel:t=>{e.model=t},changeModel:async t=>{let n=await vu(e.projectId,e.sessionId,t);return e.clearPersistedDefaults(),n}}}var Jt=BigInt(4096),Fe=BigInt(0xffffffffffff),Nm=Fe+BigInt(1),pP=Nm/BigInt(2),Ze=BigInt(3600*1e3)*Jt,_s=120*1e3,dP=/^msg_[0-9a-f]{12}[A-Za-z0-9]{14}$/,gP=/^msg_([0-9a-f]{12})/,Km="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";function St(e){let t=gP.exec(e??"");return t?BigInt(`0x${t[1]}`):null}function Zt(e){return BigInt(Math.trunc(e))*Jt&Fe}function wt(e,t){let n=e-t&Fe;return n>=pP&&(n-=Nm),n}function qm(e){let t=null;for(let n of e)n!=null&&(t===null||wt(n,t)>BigInt(0))&&(t=n);return t}function mP(e,t){let n=St(e);return n===null?!1:wt(n,Zt(t))>Ze}function fP(e,t){let n=t===void 0?null:Zt(t);return Gm(e,r=>n===null||wt(r,n)<=Ze)}function Gm(e,t){let n=[];for(let r of e){let o=St(r);o!==null&&t(o)&&n.push(o)}return qm(n)}function yP(){let e="",t=new Uint8Array(32);for(;e.length<14;){crypto.getRandomValues(t);for(let n of t)n<248&&e.length<14&&(e+=Km[n%62])}return e}function Bm(e){let t=e.random,n=Zt(e.nowMs-(e.backdateMs??_s)),r=e.newestKnownTime??null;if(r!==null){let s=wt(r,n);s>=BigInt(0)&&s<=Ze&&(n=r+BigInt(1)&Fe)}let o="";if(t)for(let s=0;s<14;s++)o+=Km[Math.min(61,Math.floor(t()*62))];else o=yP();return{id:`msg_${n.toString(16).padStart(12,"0")}${o}`,time:n}}function Ps(e={}){let t=e.nowMs??Date.now(),n=Zt(t-_s),r=Gm(e.after??[],o=>{let s=wt(o,n);return s>=BigInt(0)&&s<=Ze});return Bm({nowMs:t,newestKnownTime:r}).id}function Wm(e){return{scope:()=>Su(e.projectId,e.sessionId),providerSecretPool:{list:()=>Pc(e.projectId,e.sessionId),get:t=>_c(e.projectId,e.sessionId,t),set:(t,n)=>xc(e.projectId,e.sessionId,t,n)},rescope:t=>wu(e.projectId,e.sessionId,t),setAgent:t=>{e.agent=t},send:async(t,n)=>{await e.ensureReady();let r=n?.model??e.model,o=n?.agent??e.agent,s=r&&o?{}:await e.persistedPromptDefaults(),i=r??s.model,a=o??s.agent,c=Ps(),p=await sr(e.projectId,e.sessionId,{clientMessageId:c,messageId:c,remintOnDelivery:!0,parts:[{type:"text",text:t}],clientSentAtMs:Date.now(),...i||a?{overrides:{...i?{model:i}:{},...a?{agent:a}:{}}}:{}});if(p.state==="failed")throw new b("This prompt was refused: its earlier delivery already failed.",{code:"PROMPT_FAILED"});return p}}}var y$="kortix.transcript.v1",hP=["auth","rate_limit","credits","context_length","output_length","aborted","unknown"];function h$(e){return typeof e=="string"&&hP.includes(e)}var b$=["once","always","reject"],_$=["read","edit","glob","grep","list","bash","task","external_directory","todowrite","question","webfetch","websearch","lsp","doom_loop","skill"];var Hm=async function*(e){let t=k().eventStreamTransport;if(!t){yield*bs(((o,s)=>M(o,s,{timeoutMs:null})))(e);return}let{headers:n,rejected:r}=await Ln(e.url,e.headers);try{yield*t({...e,headers:n})}catch(o){throw o?.status===401&&r(),o}};function Re(){let e=Mm();return e||(k().billingEnabled??!1?"":Nu())}async function xs(e,t){return(await e.json().catch(()=>({})))?.error||e.statusText||t}function Ss(e){if(!e)throw new Error("[opencode-sdk] Server URL not ready \u2014 sandbox is still loading");return e}async function Vm(e){let t=Ss(e),n=await M(`${t}/env`);if(!n.ok)throw new Error(await xs(n,"Failed to load secrets"));return(await n.json()).secrets??{}}async function zm(e,t,n){let r=Ss(e),o=await M(`${r}/env/${encodeURIComponent(t)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({value:n})});if(!o.ok)throw new Error(await xs(o,"Failed to save secret"))}async function Ym(e,t){let n=Ss(e),r=await M(`${n}/env/${encodeURIComponent(t)}`,{method:"DELETE"});if(!r.ok)throw new Error(await xs(r,"Failed to delete secret"))}var bP={list:Vm,set:zm,delete:Ym};async function _P(e,t,n){let r=e;for(;r.endsWith("/");)r=r.slice(0,-1);let o=await M(`${r}/kortix/triggers${t}`,{...n,headers:{"Content-Type":"application/json",...n?.headers}}),s=await o.json();if(!o.ok)throw new Error(s?.error||s?.message||`Request failed with ${o.status}`);return s}async function hr(e,t){let n=await e.json().catch(()=>({}));return n?.error||n?.message||e.statusText||t}function en(e){if(!e)throw new Error("[kortix-pty] Server URL not ready \u2014 sandbox is still loading");return te(e)}async function Qm(e){let t=en(e),n=await M(`${t}/kortix/pty`);if(!n.ok)throw new Error(await hr(n,"Failed to list terminals"));return n.json()}async function Xm(e,t){let n=en(e),r=await M(`${n}/kortix/pty`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t??{})});if(!r.ok)throw new Error(await hr(r,"Failed to create terminal"));return r.json()}async function Jm(e,t,n){let r=en(e),o=await M(`${r}/kortix/pty/${encodeURIComponent(t)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!o.ok)throw new Error(await hr(o,"Failed to update terminal"));return o.json()}async function Zm(e,t){let n=en(e),r=await M(`${n}/kortix/pty/${encodeURIComponent(t)}`,{method:"DELETE"});if(!r.ok)throw new Error(await hr(r,"Failed to remove terminal"))}async function ef(e,t,n){let r=en(t),s=`${(()=>{try{let p=new URL(r);return p.protocol==="https:"?p.protocol="wss:":p.protocol==="http:"&&(p.protocol="ws:"),typeof window<"u"&&window.location.protocol==="https:"&&p.protocol==="ws:"&&(p.protocol="wss:"),te(p.toString())}catch{return r.replace("https://","wss://").replace("http://","ws://")}})()}/kortix/pty/${encodeURIComponent(e)}/connect`,i=new URLSearchParams,a=await Ft();a&&i.set("token",a),n?.wake&&i.set("wake","1");let c=i.toString();return c?`${s}${s.includes("?")?"&":"?"}${c}`:s}function PP(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 Le="\x1B",tf="\x07",xP="\0",ws=`(?:${tf}|${Le}\\\\)`,SP=[new RegExp(`${Le}\\]697;[^${tf}${Le}]*${ws}`,"g"),new RegExp(`${xP}?\\{"cursor":\\d+\\}`,"g"),new RegExp(`${Le}\\][0-9]+;rgb:[0-9a-fA-F/]+${ws}`,"g"),new RegExp(`${Le}\\]4;[0-9]+;rgb:[0-9a-fA-F/]+${ws}`,"g"),new RegExp(`${Le}\\[\\??[0-9;]*\\$y`,"g"),new RegExp(`${Le}\\[\\d+;\\d+R`,"g"),new RegExp(`${Le}\\[\\?[0-9;]*c`,"g")];function wP(e){let t=e;for(let n of SP)t=t.replace(n,"");return t}var vP={list:Qm,create:Xm,update:Jm,remove:Zm,webSocketUrl:ef};async function I(e,t,n,r){let o=e;for(;o.endsWith("/");)o=o.slice(0,-1);let s=await M(`${o}${t}`,{...n,headers:{"Content-Type":"application/json",...n?.headers}},r),i=await s.text(),a={};try{a=i?JSON.parse(i):{}}catch{a={}}if(!s.ok)throw new Error(a?.error||a?.message||a?.details||i.slice(0,200)||`Request failed with ${s.status}`);return a}async function N$(e,t={}){let n=new URLSearchParams;t.projectId&&n.set("project_id",t.projectId),t.status&&n.set("status",t.status);let r=n.toString()?`?${n}`:"";return I(e,`/kortix/tasks${r}`)}async function K$(e,t){return I(e,`/kortix/tasks/${encodeURIComponent(t)}`)}async function q$(e,t){return I(e,`/kortix/tasks/${encodeURIComponent(t)}/events`)}async function G$(e,t){return I(e,`/kortix/tasks/${encodeURIComponent(t)}/status`)}async function B$(e,t){return I(e,"/kortix/tasks",{method:"POST",body:JSON.stringify(t)})}async function W$(e,t,n){return I(e,`/kortix/tasks/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}async function H$(e,t){return I(e,`/kortix/tasks/${encodeURIComponent(t)}/start`,{method:"POST"})}async function V$(e,t){return I(e,`/kortix/tasks/${encodeURIComponent(t)}/approve`,{method:"POST"})}async function z$(e,t){return I(e,`/kortix/tasks/${encodeURIComponent(t)}`,{method:"DELETE"})}async function Y$(e,t){let n=t?`?project_id=${encodeURIComponent(t)}`:"";return I(e,`/kortix/tickets${n}`)}async function Q$(e,t){return I(e,`/kortix/tickets/${encodeURIComponent(t)}`)}async function X$(e,t){return I(e,`/kortix/tickets/${encodeURIComponent(t)}/events`)}async function J$(e,t){return I(e,"/kortix/tickets",{method:"POST",body:JSON.stringify(t)})}async function Z$(e,t,n){return I(e,`/kortix/tickets/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}async function e0(e,t,n){return I(e,`/kortix/tickets/${encodeURIComponent(t)}/status`,{method:"POST",body:JSON.stringify(n)})}async function t0(e,t,n){return I(e,`/kortix/tickets/${encodeURIComponent(t)}/assign`,{method:"POST",body:JSON.stringify(n)})}async function n0(e,t,n){return I(e,`/kortix/tickets/${encodeURIComponent(t)}/unassign`,{method:"POST",body:JSON.stringify(n)})}async function r0(e,t,n){return I(e,`/kortix/tickets/${encodeURIComponent(t)}/comments`,{method:"POST",body:JSON.stringify(n)})}async function o0(e,t){return I(e,`/kortix/tickets/${encodeURIComponent(t)}`,{method:"DELETE"})}async function s0(e,t){return I(e,`/kortix/projects/${encodeURIComponent(t)}/columns`)}async function i0(e,t,n){return I(e,`/kortix/projects/${encodeURIComponent(t)}/columns`,{method:"PUT",body:JSON.stringify({columns:n})})}async function a0(e,t){return I(e,`/kortix/projects/${encodeURIComponent(t)}/fields`)}async function c0(e,t,n){return I(e,`/kortix/projects/${encodeURIComponent(t)}/fields`,{method:"PUT",body:JSON.stringify({fields:n})})}async function l0(e,t){return I(e,`/kortix/projects/${encodeURIComponent(t)}/templates`)}async function u0(e,t,n){return I(e,`/kortix/projects/${encodeURIComponent(t)}/templates`,{method:"PUT",body:JSON.stringify({templates:n})})}async function p0(e,t){return I(e,`/kortix/projects/${encodeURIComponent(t)}/pm-session`,{method:"POST"})}async function d0(e,t){return I(e,`/kortix/projects/${encodeURIComponent(t)}/agents`)}async function g0(e,t,n){return I(e,`/kortix/projects/${encodeURIComponent(t)}/agents`,{method:"POST",body:JSON.stringify(n)})}async function m0(e,t,n,r){return I(e,`/kortix/projects/${encodeURIComponent(t)}/agents/${encodeURIComponent(n)}`,{method:"PATCH",body:JSON.stringify(r)})}async function f0(e,t,n){return I(e,`/kortix/projects/${encodeURIComponent(t)}/agents/${encodeURIComponent(n)}`,{method:"DELETE"})}async function y0(e,t,n){return I(e,`/kortix/projects/${encodeURIComponent(t)}/agents/${encodeURIComponent(n)}/persona`)}async function h0(e,t,n=200){return I(e,`/kortix/projects/${encodeURIComponent(t)}/activity?limit=${n}`)}async function b0(e){return I(e,"/kortix/projects")}async function _0(e,t){return I(e,`/kortix/projects/${encodeURIComponent(t)}`)}async function P0(e,t){return I(e,`/kortix/projects/by-session/${encodeURIComponent(t)}`)}async function x0(e,t){return I(e,`/kortix/projects/${encodeURIComponent(t)}/sessions`)}async function S0(e,t){return I(e,`/kortix/projects/${encodeURIComponent(t)}`,{method:"DELETE"})}async function w0(e,t,n){return I(e,`/kortix/projects/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}async function v0(e,t,n="all"){return I(e,`/kortix/projects/${encodeURIComponent(t)}/milestones?status=${n}`)}async function A0(e,t,n){return I(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}`)}async function k0(e,t,n){return I(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}/events`)}async function R0(e,t,n){return I(e,`/kortix/projects/${encodeURIComponent(t)}/milestones`,{method:"POST",body:JSON.stringify(n)})}async function I0(e,t,n,r){return I(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}`,{method:"PATCH",body:JSON.stringify(r)})}async function C0(e,t,n,r){return I(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}/close`,{method:"POST",body:JSON.stringify(r)})}async function T0(e,t,n){return I(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}/reopen`,{method:"POST"})}async function E0(e,t,n){return I(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}`,{method:"DELETE"})}async function M0(e,t){return I(e,`/kortix/projects/${encodeURIComponent(t)}/credentials`)}async function O0(e,t,n){return I(e,`/kortix/projects/${encodeURIComponent(t)}/credentials/${encodeURIComponent(n)}/events`)}async function D0(e,t,n){return I(e,`/kortix/projects/${encodeURIComponent(t)}/credentials`,{method:"POST",body:JSON.stringify(n)})}async function j0(e,t,n){return I(e,`/kortix/projects/${encodeURIComponent(t)}/credentials/${encodeURIComponent(n)}`)}async function $0(e,t,n){return I(e,`/kortix/projects/${encodeURIComponent(t)}/credentials/${encodeURIComponent(n)}`,{method:"DELETE"})}var AP=1e4,kP={retryOnAuthError:!1};function vt(e,t,n){return I(e,t,{signal:AbortSignal.timeout(AP),...n},kP)}async function U0(e,t=!1){return(await vt(e,`/kortix/services${t?"?all=true":""}`)).services??[]}async function F0(e){return(await vt(e,"/kortix/services/templates")).templates??[]}async function L0(e,t){return(await vt(e,`/kortix/services/${encodeURIComponent(t)}/logs`)).logs??[]}async function N0(e,t,n){let r=n==="delete",o=r?`/kortix/services/${encodeURIComponent(t)}`:`/kortix/services/${encodeURIComponent(t)}/${n}`;return vt(e,o,{method:r?"DELETE":"POST"})}async function K0(e,t){return vt(e,`/kortix/services/reconcile${t?"?reload=true":""}`,{method:"POST"})}async function q0(e,t){return vt(e,"/kortix/services/register",{method:"POST",body:JSON.stringify(t)})}var Ie=new Map,RP=256,tn=class extends Error{constructor(t="[opencode-sdk] Server URL not ready \u2014 sandbox is still loading"){super(t),this.name="RuntimeNotReadyError"}};function et(){let e=Re();if(!e)throw new tn;return Ce(e)}function Ce(e){if(!e)throw new Error("[opencode-sdk] getClientForUrl called without a url");let t=Ie.get(e);if(t)return Ie.delete(e),Ie.set(e,t),t;if(!no())throw new Error("[opencode-sdk] No auth token provider configured \u2014 call configureKortix()/createKortix() before talking to a sandbox runtime.");let n=Xt({baseUrl:e,fetch:M,eventTransport:Hm});return Ie.set(e,n),Ie.size>RP&&Ie.delete(Ie.keys().next().value),n}function Q0(e){Ie.delete(e)}function X0(){Ie.clear()}var br=new Map;function J0(e){if(!e)throw new Error("[opencode-sdk] getPublicClientForUrl called without a url");let t=br.get(e);if(t)return t;let n=Xt({baseUrl:e,fetch});return br.set(e,n),n}function Z0(e){br.delete(e)}function eU(){br.clear()}async function IP(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 tU(e){let t=Re();if(!t)throw new b("[opencode-sdk] Server URL not ready \u2014 sandbox is still loading",{code:"RUNTIME_UNAVAILABLE"});let n=e==="full"?"/kortix/refresh":"/global/dispose",r=await M(`${t}${n}`,{method:"POST"}),o=r.headers.get("content-type")??"",s=/^application\/([\w.+-]+\+)?json\b/i.test(o.trim());if(!r.ok)throw new b(`System reload failed (${r.status}): ${await IP(r)}`,{status:r.status,response:r,code:"RUNTIME_UNAVAILABLE"});if(!s)throw new b(`System reload endpoint is unavailable on this sandbox (${n})`,{status:r.status,response:r,code:"RUNTIME_UNAVAILABLE"});let i;try{i=await r.json()}catch(c){throw new b(`System reload returned malformed JSON from ${n}: ${c instanceof Error?c.message:String(c)}`,{status:r.status,response:r,code:"RUNTIME_UNAVAILABLE"})}let a=i===!0||typeof i=="object"&&i!==null&&i.ok===!0;return{success:a,mode:e,steps:a?[e==="full"?"refreshed workspace and restarted runtime":"reloaded config in place"]:[],errors:a?[]:[`the sandbox did not confirm the reload (${n})`]}}var nf="frontend";function _r(e,t,n){(e==="error"?console.error:e==="warn"?console.warn:e==="debug"?console.debug:console.log)(`[${nf}] ${t}`,...n?[n]:[]);try{et().app.log({service:nf,level:e,message:t,extra:n})}catch{}}var Ne={debug:(e,t)=>_r("debug",e,t),info:(e,t)=>_r("info",e,t),warn:(e,t)=>_r("warn",e,t),error:(e,t)=>_r("error",e,t)};function CP(e){return{type:"heartbeat-gap",gapMs:e}}function TP(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 EP={now:()=>Date.now(),setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),random:()=>Math.random()},MP=16,OP=8,DP=6e4,jP=5e3,$P=250,UP=1e3,FP=3e4,LP=5,NP=1e4,KP=4,qP=.5,GP=3e3,BP=3e4,WP=2e4,HP=2e3,VP=8;function zP(e){if(e.type==="session.status")return`session.status:${e.properties.sessionID}`;if(e.type==="lsp.updated")return"lsp.updated"}function YP(e,t){if(e?.type!=="message.part.delta"||t.type!=="message.part.delta")return;let n=e.properties,r=t.properties;if(n.partID!==r.partID||n.field!==r.field||n.messageID!==r.messageID||n.sessionID!==r.sessionID)return;let o=e.coalesced??[e];return o.push(t),{...t,properties:{...r,delta:n.delta+r.delta},coalesced:o}}function rf(e){if(e.aborted)return{promise:Promise.resolve(),cleanup:()=>{}};let t=()=>{};return{promise:new Promise(r=>{t=()=>r(),e.addEventListener("abort",t,{once:!0})}),cleanup:()=>e.removeEventListener("abort",t)}}var nn=new WeakMap;function QP(e,t,n){let r=t.timers??EP,o=t.connectTimeoutMs??WP,s=t.heartbeatTimeoutMs??DP,i=t.maxConsecutiveHardFailures??VP,a=new AbortController;function c(_,...x){for(let E of n){let w=_(E);if(w)try{w(...x)}catch(P){console.warn("[opencode-events] subscriber handler threw, skipping",P)}}}let p=null,d=!1,g=_=>{p!==_&&(p=_,_&&c(x=>x.onConnectionChange,_))},m=r.now(),f=null,h=[],S,D=0,j=new Map,L=()=>{if(S&&r.clearTimeout(S),S=void 0,h.length===0)return;let _=h;h=[],j.clear(),D=r.now(),m=r.now();for(let x of _)x&&c(E=>E.onEvent,x.event)},y=()=>{if(S)return;let _=r.now()-D;S=r.setTimeout(L,Math.max(0,MP-_))};return(async()=>{let _=0,x=0,E=0;for(;!a.signal.aborted;){let w=!1,P=!1,A,C,T=null,N=r.now(),$=new AbortController;g("connecting");let K=rf(a.signal);K.promise.then(()=>$.abort());try{let ie=await new Promise((ct,Be)=>{let ee=!1;C=r.setTimeout(()=>{ee||(ee=!0,Ne.warn("SSE connect timed out, forcing reconnect",{connectTimeoutMs:o}),$.abort(),Be(new Error(`SSE connect timed out after ${o}ms`)))},o),e.global.event({signal:$.signal,sseDefaultRetryDelay:GP,sseMaxRetryDelay:BP,sseMaxRetryAttempts:1}).then(xe=>{ee||(ee=!0,r.clearTimeout(C),ct(xe))},xe=>{ee||(ee=!0,r.clearTimeout(C),Be(xe))})}),{stream:Dt}=ie;if(f){let ct=r.now()-f.lastActivityAt,Be=f.eventful;f=null,(Be||ct>jP)&&c(ee=>ee.onGapRehydrate,ct)}m=r.now();let Ge=()=>{r.clearTimeout(A),A=r.setTimeout(()=>{Ne.warn("SSE heartbeat timeout, forcing reconnect"),$.abort()},s)};Ge();let Tn=r.now(),tb=Dt[Symbol.asyncIterator]();for(;!$.signal.aborted;){let ct=tb.next().then(Se=>({kind:"next",result:Se}),Se=>({kind:"error",error:Se})),Be=rf($.signal),ee=await Promise.race([ct,Be.promise.then(()=>({kind:"aborted"}))]);if(Be.cleanup(),ee.kind==="aborted")break;if(ee.kind==="error")throw ee.error;if(ee.result.done)break;g("open"),Ge();let xe=ee.result.value,lt=xe&&typeof xe=="object"&&"payload"in xe?xe.payload:xe;if(!lt?.type)continue;lt.type!=="server.connected"&&(w=!0);let Zr=YP(h[h.length-1]?.event,lt);if(Zr)h[h.length-1]={type:Zr.type,event:Zr};else{let Se=zP(lt);if(Se){let bi=j.get(Se);bi!==void 0&&(h[bi]=void 0),j.set(Se,h.length)}h.push({type:lt.type,event:lt})}y(),!(r.now()-Tn<OP)&&(Tn=r.now(),await new Promise(Se=>r.setTimeout(Se,0)))}P=w}catch(ie){if(a.signal.aborted)break;T=ie;let Dt=String(ie),Ge=jt(ie)||jt(ie?.cause);if(Ne.error("SSE event stream error",{error:Dt,retryCount:_,isAuthError:Ge}),Ge)try{_o(),await bo(),Ne.info("SSE: refreshed auth token after auth error")}catch(Tn){Ne.error("SSE: failed to refresh auth token",{error:String(Tn)})}}finally{r.clearTimeout(A),r.clearTimeout(C),$.abort(),K.cleanup(),L()}if(a.signal.aborted)break;let q=r.now()-N,ue=T?.cause?.status;if(x=!w&&(typeof ue=="number"&&ue>=400||q<HP)?x+1:0,x>=i){Ne.error("SSE event stream parked \u2014 giving up after consecutive hard failures",{consecutiveFailures:x,lastError:String(T)}),p=null,d=!0,c(ie=>ie.onParked,{consecutiveFailures:x,lastError:T});break}g("lost"),f={lastActivityAt:m,eventful:(f?.eventful??!1)||w},E=P&&q<NP?E+1:0;let at=P&&E<=KP;at?_=0:(_++,_>1&&Ne.warn("SSE event stream reconnecting",{retryCount:_}));let _e=at?$P:Math.min(UP*2**Math.min(_-1,LP),FP),Pe=Math.round(_e*(1+qP*(r.random?.()??0)));await new Promise(ie=>{let Dt=r.setTimeout(ie,Pe),Ge=()=>{r.clearTimeout(Dt),ie()};a.signal.addEventListener("abort",Ge,{once:!0})})}})(),{subscribers:n,connectionState:()=>p,isParked:()=>d,teardown:()=>{p=null,a.abort(),S&&r.clearTimeout(S)}}}function vs(e){let{onEvent:t,onGapRehydrate:n,onParked:r,onConnectionChange:o,signal:s}=e,i=e.client??(e.url?Ce(e.url):void 0);if(!i)throw new Error("openEventStream needs the session runtime `url`");let a={onEvent:t,onGapRehydrate:n,onParked:r,onConnectionChange:o},c=nn.get(i);if(c?.isParked()&&(nn.delete(i),c=void 0),!c)c=QP(i,e,new Set([a])),nn.set(i,c);else{c.subscribers.add(a);let f=c.connectionState();f&&o?.(f)}let p=c,d=!1,g=()=>{d||(d=!0,s&&s.removeEventListener("abort",m),p.subscribers.delete(a),p.subscribers.size===0&&(p.teardown(),nn.get(i)===p&&nn.delete(i)))},m=()=>g();return s&&(s.aborted?g():s.addEventListener("abort",m,{once:!0})),{close:g}}function of(e){return{abort:async()=>{let{runtimeSessionId:t,runtimeUrl:n}=await e.ensureReady();return Ce(n).session.abort({sessionID:t})},rewind:async t=>{let{runtimeSessionId:n,runtimeUrl:r}=await e.ensureReady();return Ce(r).session.revert({sessionID:n,messageID:t})},restoreRewind:async()=>{let{runtimeSessionId:t,runtimeUrl:n}=await e.ensureReady();return Ce(n).session.unrevert({sessionID:t})},stream:async t=>{let{runtimeUrl:n}=await e.ensureReady();return vs({url:n,onEvent:t.onEvent,onGapRehydrate:t.onGapRehydrate,signal:t.signal})}}}function lf(e){if(e.error){let t=e.error,n=t?.data?.message||t?.message||(typeof t?.error=="string"?t.error:null)||"SDK request failed";throw new b(n,{status:t?.response?.status??t?.status,response:t?.response,details:t})}return e.data}async function At(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 Y(e){let t=(e??Re()).trim();if(!t)throw new tn;return t}async function xr(e,t){let n=await M(`${Y(t)}${e}`);if(!n.ok)throw new b(await At(n),{status:n.status,response:n});return n.json()}var Rs=["/workspace","/tmp","/home","/opt"],XP=Rs.filter(e=>e!=="/workspace");function uf(e){return Rs.some(t=>e===t||e.startsWith(`${t}/`))}function cn(e){return uf(e)?e:`/workspace/${e.replace(/^\/+/,"")}`}function tt(e){let t=e||"";if(t==="/workspace"||t==="/workspace/")return"";if(t.startsWith("/workspace/"))t=t.slice(11);else if(XP.some(n=>t===n||t.startsWith(`${n}/`)))return t;for(;t.startsWith("/");)t=t.slice(1);return t}var pf=tt;async function ln(e,t){let n=Y(t),r=tt(e)||".";return(await xr(`/file?path=${encodeURIComponent(r)}`,n)).map(s=>({...s,path:s.absolute||`/workspace/${s.path}`}))}async function un(e,t){let n=Y(t),r=tt(e),o=await M(`${n}/file/content?path=${encodeURIComponent(r)}`);if(!o.ok)throw new b(await At(o),{status:o.status,response:o});return o.json()}async function JP(e,t,n){let r=Y(n),o=tt(e),s=await M(`${r}/file/raw?path=${encodeURIComponent(o)}`);if(!s.ok)throw new b(await At(s),{status:s.status,response:s});if((s.headers.get("content-type")||"").includes("text/html"))throw new b("File could not be loaded (raw byte route unavailable)",{status:s.status,response:s,code:"INVALID_CONTENT_TYPE"});let i=await s.blob();return t&&(!i.type||i.type==="application/octet-stream")?new Blob([i],{type:t}):i}var ZP=8,Pr=0,df=[];async function ex(){if(Pr<ZP){Pr++;return}await new Promise(e=>df.push(e)),Pr++}function tx(){Pr--,df.shift()?.()}function nx(e,t){let n=Y(t);return Xn(`${n}/file/raw?path=${encodeURIComponent(tt(e))}`)}async function pn(e,t){await ex();try{let n=Y(t);try{return await JP(e,void 0,n)}catch{}let r=await un(e,n);if(r.encoding==="base64"&&r.content){let o=Uint8Array.from(atob(r.content),s=>s.charCodeAt(0));return new Blob([o],{type:r.mimeType||"application/octet-stream"})}return new Blob([r.content??""],{type:r.mimeType||"text/plain;charset=utf-8"})}finally{tx()}}async function Sr(e){return xr("/file/status",Y(e))}async function wr(e,t,n){let r=Y(n),o=new URLSearchParams({query:e});return t?.type&&o.set("type",t.type),t?.limit&&o.set("limit",String(t.limit)),xr(`/find/file?${o.toString()}`,r)}async function vr(e,t){let n=Y(t);return(await xr(`/find?pattern=${encodeURIComponent(e)}`,n)).map(o=>({path:typeof o.path=="string"?o.path:o.path?.text??"",lines:typeof o.lines=="string"?o.lines:o.lines?.text??"",line_number:o.line_number,absolute_offset:o.absolute_offset,submatches:(o.submatches??[]).map(s=>({start:s.start,end:s.end}))}))}var rn=[400,1200],rx=e=>e===408||e===429||e===502||e===503||e===504,sf=e=>new Promise(t=>setTimeout(t,e));function ox(e){let t=e?.name;return t==="TimeoutError"||t==="AbortError"}var As=3e4,gf=15*6e4,sx=256;function on(e){if(typeof e!="number"||!Number.isFinite(e)||e<=0)return As;let t=As+e/sx;return Math.min(gf,Math.max(As,Math.round(t)))}async function ix(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 sn(e,t){let n;for(let o=0;o<=rn.length;o++){let s;try{s=await t(e())}catch(a){if(n=a,ox(a)||o===rn.length)break;await sf(rn[o]);continue}if(s.ok)return s.json();let i=await ix(s);if(n=new b(`Upload failed (${s.status}): ${i}`,{status:s.status,response:s}),!rx(s.status)||o===rn.length)throw n;await sf(rn[o])}if(n instanceof b)throw n;let r=n instanceof Error?n.message:String(n||"request failed");throw new b(`Upload failed: ${r}`)}var ks=8*1024*1024;function ax(e,t){if(!(typeof e?.size!="number"||!Number.isFinite(t))&&!(e.size>=t))throw new b(`Upload verification failed for ${e.path}: expected ${t} bytes, received ${e.size}`,{code:"UPLOAD_SIZE_MISMATCH"})}function af(e,t){try{e?.onProgress?.(t)}catch{}}function cf(e,t,n){let r=new FormData,o=(t??"").trim();return o&&r.append("path",o.startsWith("/")?o:`/${o}`),n&&r.append("filename",n),n?r.append("file",e,n):r.append("file",e),r}function cx(e){let t=e.lastIndexOf("/");return t<0?{parent:"",name:e}:{parent:e.slice(0,t)||"/",name:e.slice(t+1)}}async function dn(e,t,n,r,o){let s=typeof r=="string"?r:void 0,i=typeof r=="string"?o:r,a=Y(s),c=on(e.size),p=n||(e instanceof File?e.name:"")||"";if(e.size<=ks){let f=await sn(()=>cf(e,t,p),h=>M(`${a}/file/upload`,{method:"POST",body:h},{timeoutMs:c}));return ax(f[0],e.size),af(i,{loadedBytes:e.size,totalBytes:e.size}),f}let g=(await sn(()=>cf(new Blob([],{type:e.type}),t,p),f=>M(`${a}/file/upload`,{method:"POST",body:f},{timeoutMs:on(0)})))[0]?.path;if(!g)throw new b("Upload reservation returned no file path",{code:"UPLOAD_NO_RESULT"});let m=cx(g);if(!m.name)throw new b(`Upload reservation returned an invalid file path: ${g}`,{code:"UPLOAD_INVALID_PATH"});try{for(let f=0;f<e.size;f+=ks){let h=Math.min(e.size,f+ks),S=e.slice(f,h,e.type),D=await sn(()=>{let j=new FormData;return m.parent&&j.append("path",m.parent),j.append("filename",m.name),j.append("first",f===0?"true":"false"),j.append("offset",String(f)),j.append("file",S,m.name),j},j=>M(`${a}/file/append`,{method:"POST",body:j},{timeoutMs:on(S.size)}));if(D.path!==g||D.size!==h)throw new b(`Upload verification failed for ${g}: expected ${h} bytes, received ${D.size}`,{code:"UPLOAD_SIZE_MISMATCH"});af(i,{loadedBytes:h,totalBytes:e.size})}}catch(f){throw await kt(g,a).catch(()=>{}),f}return[{path:g,size:e.size}]}function lx(e,t,n){let r=Y(n);return sn(()=>{let o=new FormData;return t&&o.append("path",t),o.append("file",{uri:e.uri,name:e.name,type:e.type||"application/octet-stream"}),o},o=>M(`${r}/file/upload`,{method:"POST",body:o},{timeoutMs:ux}))}var ux=gf;function px(e,t,n){let r=Y(n),o=on(t.size);return sn(()=>{let s=new FormData;return s.append(e,t,e.split("/").pop()||"file"),s},s=>M(`${r}/file/upload`,{method:"POST",body:s},{timeoutMs:o}))}var an=class extends b{path;constructor(t){super(`A file or folder already exists at ${t}`,{status:409,code:"FILE_EXISTS"}),this.name="FileExistsError",this.path=t}};async function Ar(e,t){let n=Y(t),r=e.trim(),s=(r.startsWith("/")?r:`/${r}`).split("/"),i=s.pop()||"untitled",a=s.join("/")||"/workspace",c=cn(`${a}/${i}`),p=[];try{p=await ln(mf(c),n)}catch(g){if(!(g instanceof b&&g.status===404))throw g}if(p.some(g=>g.name===ff(c)))throw new an(c);let d=await yf(c,new Blob([],{type:"application/octet-stream"}),n,{overwrite:!1});return[{path:d.path,size:d.bytes}]}async function kr(e,t,n){let r=Y(n);return px(t,await pn(e,r),r)}function dx(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function mf(e){let t=e.lastIndexOf("/");return t<=0?"/":e.slice(0,t)}function ff(e){return e.slice(e.lastIndexOf("/")+1)}function gx(){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 Rr(e,t,n){let r=Y(n),o=cn(dx(e.trim()));return yf(o,t,r,{overwrite:!0})}async function yf(e,t,n,r){let o=ff(e);if(!o)throw new b(`writeFile needs a file path, got "${e}"`,{code:"INVALID_PATH"});let s=mf(e);await gn(s,n).catch(()=>{});let i=gx(),a=await dn(t,s,`.${o}.kortix-write-${i}`,n),c=a[0]?.path;if(!c)throw new b(`Upload returned no file for ${e}`,{code:"UPLOAD_NO_RESULT"});let p=cn(c);try{await hf(p,e,n,r.overwrite)}catch(g){throw await kt(p,n).catch(()=>{}),!r.overwrite&&g instanceof b&&g.status===409?new an(e):g}let d=a[0]?.size;return{path:e,bytes:typeof d=="number"?d:t.size}}async function kt(e,t){let n=await M(`${Y(t)}/file`,{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:e})});if(!n.ok)throw new b(`Delete failed (${n.status}): ${await At(n)}`,{status:n.status,response:n});return n.json()}async function gn(e,t){let n=await M(`${Y(t)}/file/mkdir`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:e})});if(!n.ok)throw new b(`Mkdir failed (${n.status}): ${await At(n)}`,{status:n.status,response:n});return n.json()}async function Ir(e,t,n){return hf(e,t,Y(n),!0)}async function hf(e,t,n,r){let o=await M(`${n}/file/rename`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r?{from:e,to:t}:{from:e,to:t,overwrite:!1})});if(!o.ok)throw new b(`Rename failed (${o.status}): ${await At(o)}`,{status:o.status,response:o});return o.json()}async function bf(){return lf(await et().project.current())}async function Is(){return lf(await et().global.health())}async function _f(){try{return(await Is()).healthy===!0}catch{return!1}}var mx={list:ln,read:un,readBlob:pn,status:Sr,findFiles:wr,findText:vr,upload:dn,write:Rr,create:Ar,copy:kr,remove:kt,mkdir:gn,rename:Ir,currentProject:bf,health:Is,isReachable:_f,toDaemonPath:tt,toSandboxAbsolutePath:cn,toWorkspaceRelative:pf};function Pf(e){return{list:async t=>ln(t,(await e()).runtimeUrl),read:async t=>un(t,(await e()).runtimeUrl),readBlob:async t=>pn(t,(await e()).runtimeUrl),status:async()=>Sr((await e()).runtimeUrl),findFiles:async(t,n)=>wr(t,n,(await e()).runtimeUrl),findText:async t=>vr(t,(await e()).runtimeUrl),upload:async(t,n,r,o)=>dn(t,n,r,(await e()).runtimeUrl,o),write:async(t,n)=>Rr(t,n,(await e()).runtimeUrl),create:async t=>Ar(t,(await e()).runtimeUrl),copy:async(t,n)=>kr(t,n,(await e()).runtimeUrl),remove:async t=>kt(t,(await e()).runtimeUrl),mkdir:async t=>gn(t,(await e()).runtimeUrl),rename:async(t,n)=>Ir(t,n,(await e()).runtimeUrl)}}function xf(e){return{get:t=>or(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:()=>pr(e.sessionId,{projectId:e.projectId}),update:t=>hu(e.projectId,e.sessionId,t),delete:()=>(e.forgetReady(),bu(e.projectId,e.sessionId)),start:(...t)=>Ye(e.projectId,e.sessionId,...t),startOrThrow:(...t)=>qu(e.projectId,e.sessionId,...t),restart:()=>(e.forgetReady(),ir(e.projectId,e.sessionId)),stop:()=>(e.forgetReady(),ar(e.projectId,e.sessionId)),configState:()=>_u(e.projectId,e.sessionId),reloadConfig:t=>(e.forgetReady(),Pu(e.projectId,e.sessionId,t)),reloadConfigStream:(...t)=>(e.forgetReady(),xu(e.projectId,e.sessionId,...t)),setSharing:t=>Xl(e.projectId,e.sessionId,t),previews:()=>tu(e.projectId,e.sessionId),participants:()=>Jl(e.projectId,e.sessionId),watch:()=>Zl(e.projectId,e.sessionId),setWatch:t=>eu(e.projectId,e.sessionId,t),commit:t=>ql(e.projectId,e.sessionId,t),publicShares:{list:()=>nu(e.projectId,e.sessionId),create:(...t)=>ru(e.projectId,e.sessionId,...t),revoke:(...t)=>ou(e.projectId,e.sessionId,...t)}}}function Sf(e){return{reminders:{list:()=>Bd(e.projectId,e.sessionId),create:t=>Wd(e.projectId,e.sessionId,t),update:(t,n)=>No(e.projectId,e.sessionId,t,n),remove:t=>Ko(e.projectId,e.sessionId,t)},audit:(t,n)=>au(e.projectId,e.sessionId,t,n),attachments:{upload:(t,n)=>fm(e.projectId,e.sessionId,t,n),read:(t,n)=>ym(`kortix-attachment://${e.projectId}/${e.sessionId}/${t}`,n)},transcript:t=>cu(e.projectId,e.sessionId,t),messageAuthors:()=>ku(e.projectId,e.sessionId),modelUsage:()=>Ru(e.projectId,e.sessionId),transcriptSync:t=>lu(e.projectId,e.sessionId,t),turn:()=>uu(e.projectId,e.sessionId),prompts:{create:t=>sr(e.projectId,e.sessionId,t),list:()=>pu(e.projectId,e.sessionId),remove:t=>du(e.projectId,e.sessionId,t),retry:t=>fu(e.projectId,e.sessionId,t),edit:(t,n)=>gu(e.projectId,e.sessionId,t,n),interrupt:t=>mu(e.projectId,e.sessionId,t),hold:t=>yu(e.projectId,e.sessionId,t)},ensureReady:e.ensureReady}}function yx(e,t){return e?.some(n=>n.startsWith("session."))?e.includes(t):!0}var hx=["control_plane","provider_ingress","daemon","upstream_port"];function wf(e){return typeof e=="string"&&hx.includes(e)?e:null}function vf(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 Af(e,t){let n=(e===void 0?Re():e)||null;if(!n)return{status:0,ok:!1,health:null,body:"",hop:null,upstreamStatus:null};let r=await M(`${n}/kortix/health`,{method:"GET",...t},{retryOnAuthError:!1}),o=await r.text().catch(()=>""),s=null;try{s=o?JSON.parse(o):null}catch{s=null}let i=s,a=wf(r.headers.get("X-Kortix-Proxy-Hop"))??wf(s?.hop),c=Number(r.headers.get("X-Kortix-Upstream-Status")),p=s?.upstream_status,d=Number.isFinite(c)&&c>0?c:typeof p=="number"?p:null;return{status:r.status,ok:r.ok,health:i,body:o,hop:a,upstreamStatus:d}}var kf=/https?:\/\/(?:localhost|127\.0\.0\.1):\d{1,5}[^\s)"'<>]*/g,Rf=/^https?:\/\/p(\d+)-([^.]+)\.localhost(?::(\d+))?(\/.*)?$/,If=/^https?:\/\/(?:dev|staging|prod|preview)-p(\d+)-([a-z0-9-]+)\.[^/]+?(?::(\d+))?(\/.*)?$/i,Cf=new Set([22,4096,parseInt($e.KORTIX_MASTER,10)]);function bx(e){return Rf.test(e)}function Cr(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 _x(e){let t=e.indexOf("](");return t===-1?e:e.slice(0,t)}var Px=new Set(["'",'"',"`","<","(","["]),xx=new Set([">","'",'"',"`",")","]",",",";",".","!","?"]);function Sx(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&&Px.has(e[t]);)t++;for(;n>t&&xx.has(e[n-1]);)n--;return e.slice(t,n)}function wx(e){return e.match(/https?:\/\/(?:localhost|127\.0\.0\.1):\d{1,5}[^\s"'<>)]*/i)?.[0]??null}var vx=/^\/proxy\/(\d{1,5})(\/.*)?$/,Ax=/^\/(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 kx(e){if(!e)return!1;try{let t=new URL(e);return t.hostname!=="localhost"&&t.hostname!=="127.0.0.1"?!1:Ax.test(t.pathname)}catch{return!1}}function Tr(e){if(!e)return null;let t=Sx(_x(e.trim())),n=Df(t);if(n){let r=Cr(n.path||"/");return{originalUrl:`http://localhost:${n.port}${r}`,port:n.port,path:r}}try{let r=new URL(t);if(r.protocol!=="http:"&&r.protocol!=="https:"||r.hostname!=="localhost"&&r.hostname!=="127.0.0.1"||!r.port)return null;let o=parseInt(r.port,10);if(!Number.isInteger(o)||o<1||o>65535)return null;let s=`${r.pathname||"/"}${r.search}${r.hash}`,i=parseInt($e.KORTIX_MASTER,10);if(o===i){let c=r.pathname.match(vx);if(c){let p=parseInt(c[1],10);if(p>=1&&p<=65535)return o=p,s=Cr(`${c[2]||"/"}${r.search}${r.hash}`),{originalUrl:`http://localhost:${o}${s}`,port:o,path:s}}}let a=Cr(s);return{originalUrl:`${r.protocol}//${r.hostname}:${o}${a}`,port:o,path:a}}catch{let r=wx(e);return r&&r!==e?Tr(r):null}}function Rx(e){let t=[],n=/```[\s\S]*?```/g,r;for(;(r=n.exec(e))!==null;)t.push([r.index,r.index+r[0].length]);let o=/`[^`\n]+`/g;for(;(r=o.exec(e))!==null;){let s=r.index,i=s+r[0].length;t.some(([c,p])=>s>=c&&i<=p)||t.push([s,i])}return t}function Ix(e,t){return t.some(([n,r])=>e>=n&&e<r)}function Cx(e){let t=[],n=new Set,r=Rx(e);kf.lastIndex=0;let o;for(;(o=kf.exec(e))!==null;){let s=Tr(o[0]);if(!s)continue;let{originalUrl:i,port:a,path:c}=s;a<1||a>65535||Cf.has(a)||n.has(i)||(n.add(i),t.push({originalUrl:i,port:a,path:c,startIndex:o.index,endIndex:o.index+i.length,inCodeBlock:Ix(o.index,r)}))}return t}function MU(e){return Cx(e).length>0}function Tx(e){try{let{hostname:t}=new URL(e);return t==="localhost"||t==="127.0.0.1"}catch{return!1}}function Tf(e){return e.trim().toLowerCase().split("_").join("-")}function Ef(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function Ex(e,t,n){let r=n.previewUrlTemplate;if(!r||!r.includes("{port}")||!r.includes("{sandbox}"))return null;let o=r.split("{port}").join(String(e)).split("{sandbox}").join(Tf(n.sandboxId));return`${Ef(o)}${t}`}function Mx(e){return e.sandboxId.trim().length>0}function nt(e,t,n){let r=Cr(t);if(!Mx(n))return $x(e,r);let o=Ex(e,r,n);return o||(Tx(n.apiBaseUrl)?`http://p${e}-${Tf(n.sandboxId)}.localhost:${n.backendPort}${r}`:`${Ef(n.apiBaseUrl)}/p/${n.sandboxId}/${e}${r}`)}function OU(e,t){if(!e)return;let r=e.replace(/^\/workspace\//,"").replace(/^\/+/,"").split("/").filter(Boolean).map(o=>encodeURIComponent(o)).join("/");return nt(3211,`/open?path=/workspace/${r}`,t)}function Ox(e){return`/open?path=/${(e.startsWith("/workspace")?e:`/workspace/${e.replace(/^\/+/,"")}`).split("/").filter(Boolean).map(r=>encodeURIComponent(r)).join("/")}`}function DU(e){return`http://localhost:3211${Ox(e)}`}function Dx(){return"/health"}function jU(e){return nt(3211,Dx(),e)}function $U(e,t){return nt(e,"/",t)}function jx(e){let t=Tr(e);return!(!t||Cf.has(t.port)||kx(e))}function Mf(e,t){if(!e)return e;let n=Tr(e);return n?jx(n.originalUrl)?nt(n.port,n.path,t):n.originalUrl:e}function $x(e,t="/"){return`http://localhost:${e}${t}`}var Of=/^https?:\/\/[^/]+\/v1\/p\/([^/]+)\/(\d+)(\/.*)?$/;function Df(e){let t=e.match(Rf);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(If);if(n){let o=443;try{let s=new URL(e);o=s.port?parseInt(s.port,10):s.protocol==="https:"?443:80}catch{return null}return{port:parseInt(n[1],10),sandboxId:n[2],backendPort:o,path:n[4]||"/"}}let r=e.match(Of);if(r)try{let o=new URL(e);return{port:parseInt(r[2],10),sandboxId:r[1],backendPort:parseInt(o.port,10)||(o.protocol==="https:"?443:80),path:r[3]||"/"}}catch{return null}return null}function UU(e){try{let t=Df(e);return t?`http://localhost:${t.port}${t.path}`:null}catch{return null}}function FU(e){return bx(e)||If.test(e)||Of.test(e)}function LU(e){try{let{hostname:t,port:n}=new URL(e);return(t==="localhost"||t==="127.0.0.1")&&n!==""}catch{return!1}}var mn="/web-proxy/";function NU(e,t){try{let n=new URL(e);if(n.protocol!=="http:"&&n.protocol!=="https:")return null;let r=n.protocol.replace(":",""),o=`${mn}${r}/${n.host}${n.pathname}${n.search}${n.hash}`,s=parseInt($e.KORTIX_MASTER,10);return`${nt(s,"/",t).replace(/\/$/,"")}${o}`}catch{return null}}function KU(e){try{let t=new URL(e),n=t.pathname.indexOf(mn);if(n===-1)return null;let o=t.pathname.slice(n+mn.length).match(/^(https?)\/([\w.\-]+(?::\d+)?)(\/.*)?$/);if(!o)return null;let s=o[1],i=o[2],a=o[3]||"/";return`${s}://${i}${a}${t.search}${t.hash}`}catch{return null}}function qU(e){try{return new URL(e).pathname.includes(mn)}catch{return e.includes(mn)}}function GU(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 BU(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 jf(e){return{health:t=>Af(e.tryResolveReady()?.runtimeUrl??null,t),previewUrl:(t,n="/")=>nt(t,n,e.resolvePreviewOptsForSandbox(e.requireReady("previewUrl").sandboxId)),proxyUrl:t=>Mf(t,e.resolvePreviewOptsForSandbox(e.requireReady("proxyUrl").sandboxId)),sandboxPortUrl:t=>ze(e.requireReady("sandboxPortUrl").sandboxId,t)}}function Cs(e,t,n,r){let o,s,{persistedPromptDefaults:i,clearPersistedDefaults:a}=Cm(e,t),{ensureReady:c,tryResolveReady:p,requireReady:d,forgetReady:g}=Dm(e,t,n),m={projectId:e,sessionId:t,ensureReady:c,tryResolveReady:p,requireReady:d,forgetReady:g,resolvePreviewOptsForSandbox:r,get model(){return o},set model(f){o=f},get agent(){return s},set agent(f){s=f},clearPersistedDefaults:a,persistedPromptDefaults:i};return{...xf(m),...Sf(m),...jf(m),...Lm(m),...Wm(m),...of(m),files:Pf(c),...Fm(m),get runtime(){return Ce(d("runtime").runtimeUrl)}}}function $f(e){return{apps:{list:()=>xg(e),create:t=>Sg(e,t),get:t=>Go(e,t),update:(...t)=>wg(e,...t),access:{get:(...t)=>Rg(e,...t),update:(...t)=>Cg(e,...t),session:(...t)=>Tg(e,...t),agents:t=>Ig(e,t)},remove:t=>vg(e,t),token:t=>Ag(e,t),authEnv:t=>kg(e,t),artifacts:{register:t=>Bo(e,t),uploadArchive:(...t)=>Eg(e,...t),finalize:(...t)=>Wo(e,...t)},deployments:{create:(...t)=>Mg(e,...t),list:t=>Og(e,t),get:(...t)=>Dg(e,...t),logs:(...t)=>jg(e,...t),remove:(...t)=>Fg(e,...t)},start:t=>$g(e,t),stop:t=>Ug(e,t),rollback:(...t)=>Lg(e,...t),machines:{list:t=>Ng(e,t),start:(t,n)=>Kg(e,t,n),stop:(t,n)=>qg(e,t,n),restart:(t,n)=>Gg(e,t,n),destroy:(t,n)=>Bg(e,t,n)},scale:(t,n)=>Wg(e,t,n),exec:(...t)=>Hg(e,...t),volumes:{list:t=>Vg(e,t),create:(...t)=>zg(e,...t),update:(...t)=>Yg(e,...t),destroy:(...t)=>Qg(e,...t),snapshots:(...t)=>Xg(e,...t),snapshot:(...t)=>Jg(e,...t),restore:(...t)=>Zg(e,...t),fork:(...t)=>em(e,...t)}}}}function Uf(e){return{list:()=>Ua(e),invite:(...t)=>Na(e,...t),update:(...t)=>Fa(e,...t),revoke:t=>La(e,t),pendingInvites:()=>Ka(e),resendInvite:(...t)=>Ga(e,...t),revokeInvite:(...t)=>qa(e,...t),requests:()=>Da(e),approveRequest:(...t)=>ja(e,...t),rejectRequest:(...t)=>$a(e,...t),groupGrants:()=>Ba(e),attachGroupGrant:(...t)=>Wa(e,...t),updateGroupGrant:(...t)=>Ha(e,...t),detachGroupGrant:t=>Va(e,t),resourceGrants:{list:()=>za(e),create:t=>Ya(e,t),remove:t=>Qa(e,t)}}}function Ff(e){return{tokens:{list:()=>tg(e),create:t=>ng(e,t),revoke:t=>rg(e,t)},setupLinks:{requestSecret:t=>pg(e,t),requestConnector:t=>dg(e,t)},validateManifest:t=>pa(e,t),gitToken:()=>da(e),agentIdentities:()=>dd(e),secrets:{list:()=>ec(e),upsert:t=>tc(e,t),setStrategy:(...t)=>nc(e,...t),broker:(...t)=>rc(e,...t),remove:t=>ac(e,t),setPersonal:(...t)=>cc(e,...t),removePersonal:t=>lc(e,t),setGitCredential:t=>ic(e,t),listProviderOAuth:()=>oc(e),startProviderOAuth:(...t)=>fo(e,...t),pollProviderOAuth:(...t)=>yo(e,...t),removeProviderOAuth:t=>sc(e,t)},access:Uf(e)}}function Lf(e){return{list:()=>wc(e),listAll:()=>vc(e),reconcile:(...t)=>Ac(e,...t),reconcileMember:(...t)=>kc(e,...t),updateCredential:(...t)=>Rc(e,...t),revoke:(...t)=>Ic(e,...t),activate:(...t)=>Cc(e,...t),setDefault:(...t)=>Tc(e,...t),rename:(...t)=>Ec(e,...t),share:(...t)=>Oc(e,...t),addComputer:(...t)=>Mc(e,...t),pipedreamConnect:(...t)=>Dc(e,...t),pipedreamFinalize:(...t)=>jc(e,...t)}}function Er(e){return{catalog:t=>Lt(e,t),tools:()=>Po(e),search:(...t)=>Sc(e,...t),describe:(...t)=>xo(e,...t),call:(...t)=>mt(e,...t),callAction:(t,n,r,o)=>mt(e,`${t}.${n}`,r,o),accounts:(...t)=>So(e,...t),uploadAttachment:(...t)=>wo(e,...t)}}function Ts(e,t){return{slug:t,run:(r,o,s)=>Io(e,t,r,o,s),call:(r,o,s)=>mt(e,`${t}.${r}`,o,s),describe:async r=>r!==void 0?xo(e,`${t}.${r}`):(await Lt(e,{slug:t,includeSchemas:!0,includeOutputSchemas:!0})).find(s=>s.slug===t)??null,accounts:()=>So(e,t),paginate:(r,o,s)=>rl(e,t,r,o,s),uploadAttachment:(r,o)=>wo(e,r,{...o,connector:t})}}var Ux=100,Fx=0,Lx=new Set(["attachment_size_mismatch","attachment_failed"]),Nf=()=>new b("Attachment expired. Attach the file again.",{code:"attachment_expired"});function Kf(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 qf(e,t={}){let n=t.concurrency??2;if(!Number.isInteger(n)||n<1||n>20)throw new Error("Attachment concurrency must be between 1 and 20");let r=new Map,o=new Set,s=new Set,i=0,a=!1,c,p={attachments:[]},d=()=>[...r.values()].filter(y=>!y.handedOff);function g(y,_){y.removalDeleted||(y.removalDeleted=!0,qt(e,_).catch(()=>{}))}function m(){c&&clearTimeout(c);let y=d().map(({item:x})=>x);(y.length!==p.attachments.length||y.some((x,E)=>x!==p.attachments[E]))&&(p={attachments:y});let _=Math.min(...y.filter(x=>x.status==="ready").map(x=>Date.parse(x.attachment.expires_at)));Number.isFinite(_)&&!a&&(c=setTimeout(()=>{for(let x of d())x.item.status==="ready"&&Date.parse(x.item.attachment.expires_at)<=Date.now()&&(x.item={...x.item,status:"error",error:Nf()});m()},Math.min(2147483647,Math.max(0,_-Date.now()))),typeof c=="object"&&"unref"in c&&c.unref());for(let x of o)x();for(let x of[...s])x()}function f(){if(a)throw new Error("Attachment controller is disposed");if(!e)throw new Error("A project is required to attach files");return e}function h(y){f();let _=d();if(_.length+y.length>20)throw new Error("A message can contain up to 20 attachments");if(y.some(E=>!Number.isSafeInteger(E)||E<=0||E>52428800))throw new Error("Each attachment must contain 1 byte to 50 MiB");if(_.reduce((E,w)=>E+w.item.size,0)+y.reduce((E,w)=>E+w,0)>104857600)throw new Error("Message attachments exceed 100 MiB")}function S(){for(let y of r.values()){if(i>=n)break;if(y.item.status!=="pending"||!y.item.file||a&&!y.handedOff)continue;let _=y.item.file;i++;let x=++y.generation,E=new AbortController;y.abort=E,y.item={...y.item,status:"uploading",error:void 0};let w=()=>(!a||y.handedOff===!0)&&r.get(y.item.id)===y&&y.generation===x,P,A=0,C,T=()=>{C=void 0,!(!w()||y.item.status!=="uploading"||P===void 0)&&(y.item={...y.item,receivedBytes:P},P=void 0,A=Date.now(),m())},N=$=>Math.floor($*100/y.item.size);tr(e,_,{resume:y.upload,signal:E.signal,onUpload:$=>{y.upload=$,y.removed&&(E.abort(),g(y,$.attachment_id))},onProgress:$=>{if(!w()||N($)===N(y.item.receivedBytes)||(P=$,C))return;let K=A+Ux-Date.now();if(K<=0)return T();C=setTimeout(T,K),typeof C=="object"&&"unref"in C&&C.unref()},onProcessing:()=>{C&&clearTimeout(C),C=void 0,P=void 0,w()&&(y.item={...y.item,status:"processing",receivedBytes:y.item.size},m())}}).then($=>{w()&&(y.item={...y.item,status:"ready",attachment:Kf($),receivedBytes:$.size})}).catch($=>{$ instanceof b&&Lx.has($.code??"")&&(y.upload=void 0),w()&&(y.item={...y.item,status:$ instanceof b&&$.code==="ABORTED"?"aborted":"error",error:$ instanceof Error?$:new Error(String($))})}).finally(()=>{i--,C&&clearTimeout(C),y.abort===E&&(y.abort=void 0),m(),S()})}m()}function D(y){h(y.map(x=>x.size));let _=y.map(x=>{let E=`attachment-${++Fx}`;return r.set(E,{generation:0,item:{id:E,file:x,filename:x.name,mime:x.type||"application/octet-stream",size:x.size,status:"pending",receivedBytes:0}}),E});return m(),S(),_}function j(y){let _=r.get(y);!_||_.item.status==="ready"||(_.generation++,_.abort?.abort(),_.item={..._.item,status:"aborted",error:new Error("Attachment upload cancelled")},m())}function L(y,{signal:_}={}){let x=[...y];return new Promise((E,w)=>{let P=()=>{s.delete(T),_?.removeEventListener("abort",C)},A=N=>{P(),w(N)},C=()=>A(ge()),T=()=>{let N=!1;for(let K of x){let q=r.get(K);if(!q)return A(new Error("Attachment was removed before it was sent"));if(a&&!q.handedOff)return A(new Error("Attachment controller is disposed"));if(q.item.status==="error"||q.item.status==="aborted")return A(q.item.error??new Error("Attachment upload failed"));q.item.status!=="ready"&&(N=!0)}if(N)return;let $;try{$=x.map(K=>{let q=Kf(r.get(K).item.attachment);return{type:"file",attachment_id:q.attachment_id,filename:q.filename,mime:q.mime}})}catch(K){return A(K instanceof Error?K:new Error(String(K)))}P(),E($)};if(_?.aborted)return C();s.add(T),_?.addEventListener("abort",C,{once:!0}),T()})}return{add:y=>D([y])[0],addMany:D,retry(y){let _=r.get(y);if(_?.handedOff||f(),!(!_||_.item.status==="ready"||_.item.status==="uploading"||_.item.status==="processing"||_.item.status==="pending")){if(!_.item.file||_.upload&&Date.parse(_.upload.expires_at)<=Date.now())throw Nf();_.item={..._.item,status:"pending",error:void 0},S()}},async remove(y){let _=r.get(y);if(!_)return;_.removed=!0,_.generation++,r.delete(y);let x=_.upload?.attachment_id??_.item.attachment?.attachment_id;x&&_.abort?.abort(),m(),S(),x&&g(_,x)},abort:j,submit(y){if(!a){for(let _ of y){let x=r.get(_);x&&(x.handedOff=!0)}m()}},reclaim(y){if(!a){for(let _ of y){let x=r.get(_);x&&(x.handedOff=!1)}m()}},whenReady:L,forget(y=d().map(_=>_.item.id)){for(let _ of y){let x=r.get(_);x&&(x.generation++,x.abort?.abort(),r.delete(_))}m(),S()},dispose(){if(!a){a=!0,c&&clearTimeout(c);for(let y of r.values()){if(y.handedOff)continue;y.generation++,y.abort?.abort();let _=y.upload?.attachment_id??y.item.attachment?.attachment_id;_&&e&&qt(e,_).catch(()=>{})}o.clear(),m()}},getSnapshot:()=>p,subscribe(y){return o.add(y),()=>{o.delete(y)}}}}function Gf(e){return{attachments:{upload:(...t)=>tr(e,...t),delete:(...t)=>qt(e,...t),createController:t=>qf(e,t)},get:t=>qn(e,t),detail:()=>Gn(e),skills:{create:(...t)=>Pa(e,...t)},audit:t=>sg(e,t),update:t=>Hn(e,t),archive:()=>Vn(e),llmCatalog:()=>Bn(e),modelPicker:()=>Wn(e),modelAccess:()=>gr(e),setModelAccess:t=>mr(e,t),sandboxHealth:()=>Qn(e),onboardingComplete:(...t)=>_a(e,...t)}}function Bf(e){return{sessions:{list:t=>yt(e,t),listPage:t=>Ql(e,t),create:t=>ht(e,t),ensureWarm:()=>su(e),claimWarm:t=>iu(e,t)},review:{list:t=>Md(e,t),get:t=>Od(e,t),submit:t=>Dd(e,t),act:(...t)=>jd(e,...t),bulkAct:t=>$d(e,t)},approvals:{list:t=>Xa(e,t),resolve:(...t)=>Za(e,...t),sessionsNeedingInput:t=>Ja(e,t)}}}function Wf(e){return{files:{list:t=>fl(e,t),listDirectory:t=>yl(e,t),read:(t,n)=>bl(e,t,n),search:(...t)=>hl(e,...t),archive:(...t)=>_l(e,...t),archiveRequest:(...t)=>Pl(e,...t),history:(...t)=>El(e,...t)},git:{commits:()=>Il(e),commit:t=>Cl(e,t),commitDiff:t=>Tl(e,t),branches:()=>Rl(e),versionDiff:(...t)=>Ml(e,...t),inviteCollaborator:(...t)=>ua(e,...t)},changeRequests:{list:()=>Ol(e),get:t=>Dl(e,t),update:(...t)=>Gl(e,...t),diff:t=>jl(e,t),mergePreview:t=>$l(e,t),open:(...t)=>Ul(e,...t),merge:(...t)=>Fl(e,...t),close:(...t)=>Ll(e,...t),reopen:(...t)=>Nl(e,...t),requestChanges:(...t)=>Kl(e,...t)},...Bf(e)}}function Hf(e){return{policies:{list:()=>ol(e),set:(...t)=>sl(e,...t)},reminders:{list:()=>Yd(e),updateMany:(...t)=>Vd(e,...t),removeMany:(...t)=>zd(e,...t)},triggers:{list:()=>Iu(e),eventApps:()=>ju(e),eventTypes:(...t)=>Du(e,...t),create:(...t)=>Cu(e,...t),update:(...t)=>Tu(e,...t),remove:(...t)=>Eu(e,...t),fire:(...t)=>Ou(e,...t),setActivation:(...t)=>Mu(e,...t)},...Wf(e)}}function Vf(e,t){return{connectors:{...Er(e),list:()=>$c(e),config:(...n)=>Gc(e,...n),create:(...n)=>Hc(e,...n),remove:(...n)=>zc(e,...n),sync:()=>Uc(e),auth:{discover:(...n)=>Vc(e,...n)},setName:(...n)=>Bc(e,...n),setCredentialMode:(...n)=>Fc(e,...n),setAuthorizationStrategy:(...n)=>Lc(e,...n),setCredential:(...n)=>Zc(e,...n),deleteCredential:(...n)=>el(e,...n),setSensitive:(...n)=>Nc(e,...n),connections:t,policies:{get:(...n)=>Kc(e,...n),set:(...n)=>qc(e,...n)},pipedream:{listApps:(...n)=>Yc(e,...n),listSections:(...n)=>Qc(e,...n),connect:(...n)=>Wc(e,...n),finalize:(...n)=>tl(e,...n)},discover:{list:(...n)=>vo(e,...n),sections:(...n)=>Xc(e,...n),detail:(...n)=>Ao(e,...n)}},...Hf(e)}}function zf(e){return{gateway:{logs:t=>qp(e,t),log:t=>Gp(e,t),overview:t=>Bp(e,t),series:t=>Wp(e,t),breakdown:t=>Hp(e,t),sessions:t=>Vp(e,t),errors:t=>zp(e,t),budgets:()=>Yp(e),setBudget:t=>Qp(e,t),deleteBudget:t=>Xp(e,t),keys:()=>Jp(e),createKey:t=>Zp(e,t),revokeKey:t=>ed(e,t),routing:{get:()=>Fp(e),set:t=>Lp(e,t),reset:()=>Np(e),preview:t=>Kp(e,t)},playground:(t,n,r)=>td(e,t,n,r)}}}function Yf(e){return{modelDefaults:{get:()=>Bu(e),set:t=>Wu(e,t),clear:t=>Hu(e,t)},setDefaultAgent:t=>Yu(e,t),sandbox:{list:()=>ml(e),snapshots:()=>al(e),rebuildSnapshot:t=>cl(e,t),fixWithAgent:()=>ll(e),createTemplate:t=>ul(e,t),updateTemplate:(...t)=>pl(e,...t),removeTemplate:t=>dl(e,t),buildTemplate:t=>gl(e,t),setProvider:t=>ba(e,t)},setAgentScope:(...t)=>zu(e,...t)}}function Qf(e){return{channels:{slack:{installation:()=>wp(e),connect:t=>vp(e,t),mode:()=>Ap(e),completeInstall:t=>Rp(e,t),manifest:()=>Cp(e),disconnect:()=>Tp(e),getFile:t=>Ep(e,t),uploadFile:t=>Mp(e,t)},teams:{completeInstall:t=>Ip(e,t)},email:{installation:t=>Op(e,t),mode:()=>Dp(e),connect:t=>jp(e,t),disconnect:t=>$p(e,t),updatePolicy:(...t)=>Up(e,...t)}},updateFeatureFlag:(...t)=>ya(e,...t),updateExperimentalFeature:(...t)=>ha(e,...t),...Yf(e)}}function Nx(){return et()}var Xf=null,Jf=!1;function Kx(e){let t=Xf;Xf=e,!(Jf||!t)&&(t.backendUrl===e.backendUrl&&t.getToken===e.getToken||(Jf=!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 qx(e,t){t?.global!==!1&&Kx(e),to(e,t);let n=Im(e),{auth:r,accounts:o,iam:s,accountInvites:i}=wm(),{billing:a,sandboxShares:c}=Pm(),{projects:p,github:d,gitBackend:g,connectStatus:m,marketplace:f}=_m();function h(S){let D=Lf(S);return{...Gf(S),...$f(S),...Ff(S),...Vf(S,D),...zf(S),...Qf(S),connector:j=>Ts(S,j),session:j=>Cs(S,j,e,n)}}return{config:e,auth:r,accounts:o,iam:s,accountInvites:i,projects:p,connectors:Er(),connector:S=>Ts(void 0,S),project:h,session:(S,D)=>Cs(S,D,e,n),github:d,gitBackend:g,billing:a,sandboxShares:c,connectStatus:m,marketplace:f,notifications:{registerDeviceToken:nm,unregisterDeviceToken:rm,list:om,markRead:sm,preferences:im,updatePreferences:am,webPushPublicKey:cm,registerWebPushSubscription:lm,unregisterWebPushSubscription:um},validateToken:aa,runtime:Nx}}function Gx(){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 Bx(){return{pending:[],failed:[],inFlightId:null,inFlightIds:[]}}function Rt(e){return e.inFlightIds?.length?e.inFlightIds:e.inFlightId?[e.inFlightId]:[]}function Wx(e,t){return{...e,pending:[...e.pending,{...t,attempts:0}]}}function Hx(e){if(Rt(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 Vx(e){let t=Rt(e);return t.length===0?e:{...e,pending:e.pending.filter(n=>!t.includes(n.id)),inFlightId:null,inFlightIds:[]}}function zx(e,t){let n=Rt(e);if(n.length===0)return e;let r=e.pending.filter(o=>n.includes(o.id));return r.length===0?{...e,inFlightId:null,inFlightIds:[]}:{pending:e.pending.filter(o=>!n.includes(o.id)),failed:[...e.failed,...r.map(o=>({...o,lastError:t}))],inFlightId:null,inFlightIds:[]}}function Yx(e,t){let n=e.failed.find(s=>s.id===t);if(!n)return e;let{lastError:r,...o}=n;return{...e,pending:[...e.pending,o],failed:e.failed.filter(s=>s.id!==t)}}function Qx(e,t){return Rt(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 Xx(e,t,n){return Rt(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 Jx(e,t,n){let r=Rt(e);if(r.includes(t))return e;let o=e.pending.findIndex(p=>p.id===t);if(o===-1)return e;let s=r.length,i=Math.min(Math.max(n,s),e.pending.length-1);if(i===o)return e;let a=[...e.pending],[c]=a.splice(o,1);return a.splice(i,0,c),{...e,pending:a}}var Zf={thinking:!1,toolDetails:!0,assistantMetadata:!0};function Zx(e){return e&&e.charAt(0).toUpperCase()+e.slice(1)}function eS(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 tS(e,t){if(e.type==="text"&&!e.synthetic)return`${e.text??""}
20
+ `))if(h.startsWith("data:"))f.push(h.replace(/^data:\s*/,""));else if(h.startsWith("id:"))m.id=h.replace(/^id:\s*/,"");else if(h.startsWith("retry:")){let P=Number.parseInt(h.replace(/^retry:\s*/,""),10);Number.isNaN(P)||(m.retry=P)}f.length&&(m.data=f.join(`
21
+ `)),yield m}}}finally{r.removeEventListener("abort",i),s.releaseLock()}}}async function*BP(e,t,n){let r=e.eventTransport??Cs(e.fetch??globalThis.fetch),o=n.signal??new AbortController().signal,s=n.sseDefaultRetryDelay??3e3,i;for(let a=1;!o.aborted;a++)try{let c=new Headers(n.headers);i!==void 0&&c.set("Last-Event-ID",i);for await(let p of r({url:new URL(t).href,headers:c,signal:o}))if(p.id!==void 0&&(i=p.id),p.retry!==void 0&&(s=p.retry),p.data!==void 0)try{yield JSON.parse(p.data)}catch{yield p.data}return}catch(c){if(n.onSseError?.(c),n.sseMaxRetryAttempts!==void 0&&a>=n.sseMaxRetryAttempts)return;let p=Math.min(s*2**(a-1),n.sseMaxRetryDelay??3e4);await new Promise(d=>setTimeout(d,p))}}function sn(e){let t=o=>(s,i)=>qP(e,NP(e.baseUrl,o,s,i)),n=o=>s=>t(o)(void 0,s);return{session:{list:t("session.list"),get:t("session.get"),create:t("session.create"),delete:t("session.delete"),update:t("session.update"),status:t("session.status"),messages:t("session.messages"),prompt:t("session.prompt"),promptAsync:t("session.promptAsync"),abort:t("session.abort"),revert:t("session.revert"),unrevert:t("session.unrevert"),summarize:t("session.summarize"),command:t("session.command"),share:t("session.share"),unshare:t("session.unshare"),fork:t("session.fork"),diff:t("session.diff"),todo:t("session.todo")},permission:{list:t("permission.list"),reply:t("permission.reply")},question:{list:t("question.list"),reply:t("question.reply"),reject:t("question.reject")},part:{update:t("part.update"),delete:t("part.delete")},file:{list:t("file.list"),read:t("file.read")},find:{files:t("find.files")},vcs:{diff:t("vcs.diff")},global:{event:async(o={})=>({stream:BP(e,`${e.baseUrl.replace(/\/$/,"")}/global/event`,o)}),health:n("global.health"),dispose:n("global.dispose"),config:{get:n("global.config.get"),update:t("global.config.update")}},provider:{list:t("provider.list"),auth:t("provider.auth"),oauth:{authorize:t("provider.oauth.authorize"),callback:t("provider.oauth.callback")}},auth:{set:t("auth.set")},app:{agents:t("app.agents"),skills:t("app.skills"),log:t("app.log")},command:{list:t("command.list")},tool:{ids:t("tool.ids"),list:t("tool.list")},mcp:{status:t("mcp.status"),add:t("mcp.add"),connect:t("mcp.connect"),disconnect:t("mcp.disconnect"),auth:{start:t("mcp.auth.start"),callback:t("mcp.auth.callback"),remove:t("mcp.auth.remove")}},project:{list:t("project.list"),current:t("project.current")},path:{get:t("path.get")}}}var tf=200;async function GP(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 it(e,t){if(e.error===void 0)return e.data;let n=e.error,r=typeof n=="string"?n:n?.data?.message||n?.message||n?.error||"request failed";throw new b(`${t}: ${r}`,{...e.response?{status:e.response.status,response:e.response}:{}})}function nf(e){let t=e.runtimeUrl.replace(/\/$/,""),n=sn({baseUrl:t,fetch:e.fetch});return{messages:async(r={})=>{let o=encodeURIComponent(r.conversationId??e.rootId),s=async(c,p)=>{let d=new URLSearchParams;c!==void 0&&d.set("limit",String(c)),p&&d.set("before",p);let g=`/messages/${o}${d.size?`?${d}`:""}`,m=P=>e.fetch(new Request(`${t}${P}${g}`,{method:"GET",...r.signal?{signal:r.signal}:{}})),f=await m("/kortix/runtime");if((f.status===404||(f.headers.get("content-type")??"").startsWith("text/html"))&&(f=await m("/kortix/opencode")),!f.ok)throw new b(`Reading the session transcript failed: ${await GP(f)}`,{status:f.status,response:f});let h=await f.json();return{messages:h.messages??[],hasMore:h.has_more===!0}},i=await s(r.limit===void 0?void 0:Math.min(r.limit,tf),r.before),a=[...i.messages];for(;r.limit!==void 0&&a.length<r.limit&&i.hasMore&&a.length>0&&(i=await s(Math.min(r.limit-a.length,tf),a[0].info.id),!!i.messages.length);)a.unshift(...i.messages);return{messages:a,hasMore:i.hasMore}},pending:async()=>{let[r,o,s]=await Promise.all([n.session.status().then(i=>it(i,"Reading the session status failed")),n.permission.list().then(i=>it(i,"Reading permission requests failed")),n.question.list().then(i=>it(i,"Reading questions failed"))]);return{statuses:r??{},permissions:o??[],questions:s??[]}},answerPermission:async(r,o,s)=>{it(await n.permission.reply({requestID:r,reply:o,...s!==void 0?{message:s}:{}}),"Answering the permission request failed")},answerQuestion:async(r,o)=>{if(o===null){it(await n.question.reject({requestID:r}),"Dismissing the question failed");return}it(await n.question.reply({requestID:r,answers:o}),"Answering the question failed")},compact:async r=>{let o=r;if(!o){let s=await n.global.config.get().then(c=>c.error===void 0?c.data:null),i=typeof s?.model=="string"?s.model:"",a=i.indexOf("/");a>0&&a<i.length-1&&(o={providerID:i.slice(0,a),modelID:i.slice(a+1)})}if(!o)throw new b("Cannot compact: no model is set for this session",{code:"MODEL_REQUIRED"});return it(await n.session.summarize({sessionID:e.rootId,providerID:o.providerID,modelID:o.modelID}),"Compacting the session failed"),o}}}function rf(e){async function t(){let{runtimeSessionId:n,runtimeUrl:r}=await e.ensureReady();return nf({runtimeUrl:r,rootId:n,fetch:E})}return{messages:async n=>(await t()).messages(n),pending:async()=>(await t()).pending(),answerPermission:async(n,r,o)=>(await t()).answerPermission(n,r,o),answerQuestion:async(n,r)=>(await t()).answerQuestion(n,r),compact:async n=>(await t()).compact(n)}}function of(e){return{setModel:t=>{e.model=t},changeModel:async t=>{let n=await Bu(e.projectId,e.sessionId,t);return e.clearPersistedDefaults(),n}}}var an=BigInt(4096),Ge=BigInt(0xffffffffffff),sf=Ge+BigInt(1),WP=sf/BigInt(2),at=BigInt(3600*1e3)*an,Is=120*1e3,HP=/^msg_[0-9a-f]{12}[A-Za-z0-9]{14}$/,VP=/^msg_([0-9a-f]{12})/,af="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";function Tt(e){let t=VP.exec(e??"");return t?BigInt(`0x${t[1]}`):null}function cn(e){return BigInt(Math.trunc(e))*an&Ge}function Et(e,t){let n=e-t&Ge;return n>=WP&&(n-=sf),n}function cf(e){let t=null;for(let n of e)n!=null&&(t===null||Et(n,t)>BigInt(0))&&(t=n);return t}function zP(e,t){let n=Tt(e);return n===null?!1:Et(n,cn(t))>at}function YP(e,t){let n=t===void 0?null:cn(t);return lf(e,r=>n===null||Et(r,n)<=at)}function lf(e,t){let n=[];for(let r of e){let o=Tt(r);o!==null&&t(o)&&n.push(o)}return cf(n)}function QP(){let e="",t=new Uint8Array(32);for(;e.length<14;){crypto.getRandomValues(t);for(let n of t)n<248&&e.length<14&&(e+=af[n%62])}return e}function uf(e){let t=e.random,n=cn(e.nowMs-(e.backdateMs??Is)),r=e.newestKnownTime??null;if(r!==null){let s=Et(r,n);s>=BigInt(0)&&s<=at&&(n=r+BigInt(1)&Ge)}let o="";if(t)for(let s=0;s<14;s++)o+=af[Math.min(61,Math.floor(t()*62))];else o=QP();return{id:`msg_${n.toString(16).padStart(12,"0")}${o}`,time:n}}function Ts(e={}){let t=e.nowMs??Date.now(),n=cn(t-Is),r=lf(e.after??[],o=>{let s=Et(o,n);return s>=BigInt(0)&&s<=at});return uf({nowMs:t,newestKnownTime:r}).id}function pf(e){return{scope:()=>Ku(e.projectId,e.sessionId),providerSecretPool:{list:()=>Ec(e.projectId,e.sessionId),get:t=>Tc(e.projectId,e.sessionId,t),set:(t,n)=>Mc(e.projectId,e.sessionId,t,n)},rescope:t=>qu(e.projectId,e.sessionId,t),setAgent:t=>{e.agent=t},send:async(t,n)=>{await e.ensureReady();let r=n?.model??e.model,o=n?.agent??e.agent,s=r&&o?{}:await e.persistedPromptDefaults(),i=r??s.model,a=o??s.agent,c=Ts(),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 b("This prompt was refused: its earlier delivery already failed.",{code:"PROMPT_FAILED"});return p}}}var o0="kortix.transcript.v1",XP=["auth","rate_limit","credits","context_length","output_length","aborted","unknown"];function s0(e){return typeof e=="string"&&XP.includes(e)}var i0=["once","always","reject"],a0=["read","edit","glob","grep","list","bash","task","external_directory","todowrite","question","webfetch","websearch","lsp","doom_loop","skill"];var df=async function*(e){let t=v().eventStreamTransport;if(!t){yield*Cs(((o,s)=>E(o,s,{timeoutMs:null})))(e);return}let{headers:n,rejected:r}=await Vn(e.url,e.headers);try{yield*t({...e,headers:n})}catch(o){throw o?.status===401&&r(),o}};function Oe(){let e=Xm();return e||(v().billingEnabled??!1?"":sp())}async function Es(e,t){return(await e.json().catch(()=>({})))?.error||e.statusText||t}function Ms(e){if(!e)throw new Error("[opencode-sdk] Server URL not ready \u2014 sandbox is still loading");return e}async function gf(e){let t=Ms(e),n=await E(`${t}/env`);if(!n.ok)throw new Error(await Es(n,"Failed to load secrets"));return(await n.json()).secrets??{}}async function mf(e,t,n){let r=Ms(e),o=await E(`${r}/env/${encodeURIComponent(t)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({value:n})});if(!o.ok)throw new Error(await Es(o,"Failed to save secret"))}async function ff(e,t){let n=Ms(e),r=await E(`${n}/env/${encodeURIComponent(t)}`,{method:"DELETE"});if(!r.ok)throw new Error(await Es(r,"Failed to delete secret"))}var JP={list:gf,set:mf,delete:ff};async function ZP(e,t,n){let r=e;for(;r.endsWith("/");)r=r.slice(0,-1);let o=await E(`${r}/kortix/triggers${t}`,{...n,headers:{"Content-Type":"application/json",...n?.headers}}),s=await o.json();if(!o.ok)throw new Error(s?.error||s?.message||`Request failed with ${o.status}`);return s}async function kr(e,t){let n=await e.json().catch(()=>({}));return n?.error||n?.message||e.statusText||t}function ln(e){if(!e)throw new Error("[kortix-pty] Server URL not ready \u2014 sandbox is still loading");return se(e)}async function yf(e){let t=ln(e),n=await E(`${t}/kortix/pty`);if(!n.ok)throw new Error(await kr(n,"Failed to list terminals"));return n.json()}async function hf(e,t){let n=ln(e),r=await E(`${n}/kortix/pty`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t??{})});if(!r.ok)throw new Error(await kr(r,"Failed to create terminal"));return r.json()}async function bf(e,t,n){let r=ln(e),o=await E(`${r}/kortix/pty/${encodeURIComponent(t)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!o.ok)throw new Error(await kr(o,"Failed to update terminal"));return o.json()}async function _f(e,t){let n=ln(e),r=await E(`${n}/kortix/pty/${encodeURIComponent(t)}`,{method:"DELETE"});if(!r.ok)throw new Error(await kr(r,"Failed to remove terminal"))}async function Pf(e,t,n){let r=ln(t),s=`${(()=>{try{let p=new URL(r);return p.protocol==="https:"?p.protocol="wss:":p.protocol==="http:"&&(p.protocol="ws:"),typeof window<"u"&&window.location.protocol==="https:"&&p.protocol==="ws:"&&(p.protocol="wss:"),se(p.toString())}catch{return r.replace("https://","wss://").replace("http://","ws://")}})()}/kortix/pty/${encodeURIComponent(e)}/connect`,i=new URLSearchParams,a=await Ht();a&&i.set("token",a),n?.wake&&i.set("wake","1");let c=i.toString();return c?`${s}${s.includes("?")?"&":"?"}${c}`:s}function ex(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 We="\x1B",xf="\x07",tx="\0",Os=`(?:${xf}|${We}\\\\)`,nx=[new RegExp(`${We}\\]697;[^${xf}${We}]*${Os}`,"g"),new RegExp(`${tx}?\\{"cursor":\\d+\\}`,"g"),new RegExp(`${We}\\][0-9]+;rgb:[0-9a-fA-F/]+${Os}`,"g"),new RegExp(`${We}\\]4;[0-9]+;rgb:[0-9a-fA-F/]+${Os}`,"g"),new RegExp(`${We}\\[\\??[0-9;]*\\$y`,"g"),new RegExp(`${We}\\[\\d+;\\d+R`,"g"),new RegExp(`${We}\\[\\?[0-9;]*c`,"g")];function rx(e){let t=e;for(let n of nx)t=t.replace(n,"");return t}var ox={list:yf,create:hf,update:bf,remove:_f,webSocketUrl:Pf};async function R(e,t,n,r){let o=e;for(;o.endsWith("/");)o=o.slice(0,-1);let s=await E(`${o}${t}`,{...n,headers:{"Content-Type":"application/json",...n?.headers}},r),i=await s.text(),a={};try{a=i?JSON.parse(i):{}}catch{a={}}if(!s.ok)throw new Error(a?.error||a?.message||a?.details||i.slice(0,200)||`Request failed with ${s.status}`);return a}async function C0(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 R(e,`/kortix/tasks${r}`)}async function I0(e,t){return R(e,`/kortix/tasks/${encodeURIComponent(t)}`)}async function T0(e,t){return R(e,`/kortix/tasks/${encodeURIComponent(t)}/events`)}async function E0(e,t){return R(e,`/kortix/tasks/${encodeURIComponent(t)}/status`)}async function M0(e,t){return R(e,"/kortix/tasks",{method:"POST",body:JSON.stringify(t)})}async function O0(e,t,n){return R(e,`/kortix/tasks/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}async function D0(e,t){return R(e,`/kortix/tasks/${encodeURIComponent(t)}/start`,{method:"POST"})}async function j0(e,t){return R(e,`/kortix/tasks/${encodeURIComponent(t)}/approve`,{method:"POST"})}async function $0(e,t){return R(e,`/kortix/tasks/${encodeURIComponent(t)}`,{method:"DELETE"})}async function U0(e,t){let n=t?`?project_id=${encodeURIComponent(t)}`:"";return R(e,`/kortix/tickets${n}`)}async function L0(e,t){return R(e,`/kortix/tickets/${encodeURIComponent(t)}`)}async function F0(e,t){return R(e,`/kortix/tickets/${encodeURIComponent(t)}/events`)}async function N0(e,t){return R(e,"/kortix/tickets",{method:"POST",body:JSON.stringify(t)})}async function K0(e,t,n){return R(e,`/kortix/tickets/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}async function q0(e,t,n){return R(e,`/kortix/tickets/${encodeURIComponent(t)}/status`,{method:"POST",body:JSON.stringify(n)})}async function B0(e,t,n){return R(e,`/kortix/tickets/${encodeURIComponent(t)}/assign`,{method:"POST",body:JSON.stringify(n)})}async function G0(e,t,n){return R(e,`/kortix/tickets/${encodeURIComponent(t)}/unassign`,{method:"POST",body:JSON.stringify(n)})}async function W0(e,t,n){return R(e,`/kortix/tickets/${encodeURIComponent(t)}/comments`,{method:"POST",body:JSON.stringify(n)})}async function H0(e,t){return R(e,`/kortix/tickets/${encodeURIComponent(t)}`,{method:"DELETE"})}async function V0(e,t){return R(e,`/kortix/projects/${encodeURIComponent(t)}/columns`)}async function z0(e,t,n){return R(e,`/kortix/projects/${encodeURIComponent(t)}/columns`,{method:"PUT",body:JSON.stringify({columns:n})})}async function Y0(e,t){return R(e,`/kortix/projects/${encodeURIComponent(t)}/fields`)}async function Q0(e,t,n){return R(e,`/kortix/projects/${encodeURIComponent(t)}/fields`,{method:"PUT",body:JSON.stringify({fields:n})})}async function X0(e,t){return R(e,`/kortix/projects/${encodeURIComponent(t)}/templates`)}async function J0(e,t,n){return R(e,`/kortix/projects/${encodeURIComponent(t)}/templates`,{method:"PUT",body:JSON.stringify({templates:n})})}async function Z0(e,t){return R(e,`/kortix/projects/${encodeURIComponent(t)}/pm-session`,{method:"POST"})}async function eU(e,t){return R(e,`/kortix/projects/${encodeURIComponent(t)}/agents`)}async function tU(e,t,n){return R(e,`/kortix/projects/${encodeURIComponent(t)}/agents`,{method:"POST",body:JSON.stringify(n)})}async function nU(e,t,n,r){return R(e,`/kortix/projects/${encodeURIComponent(t)}/agents/${encodeURIComponent(n)}`,{method:"PATCH",body:JSON.stringify(r)})}async function rU(e,t,n){return R(e,`/kortix/projects/${encodeURIComponent(t)}/agents/${encodeURIComponent(n)}`,{method:"DELETE"})}async function oU(e,t,n){return R(e,`/kortix/projects/${encodeURIComponent(t)}/agents/${encodeURIComponent(n)}/persona`)}async function sU(e,t,n=200){return R(e,`/kortix/projects/${encodeURIComponent(t)}/activity?limit=${n}`)}async function iU(e){return R(e,"/kortix/projects")}async function aU(e,t){return R(e,`/kortix/projects/${encodeURIComponent(t)}`)}async function cU(e,t){return R(e,`/kortix/projects/by-session/${encodeURIComponent(t)}`)}async function lU(e,t){return R(e,`/kortix/projects/${encodeURIComponent(t)}/sessions`)}async function uU(e,t){return R(e,`/kortix/projects/${encodeURIComponent(t)}`,{method:"DELETE"})}async function pU(e,t,n){return R(e,`/kortix/projects/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}async function dU(e,t,n="all"){return R(e,`/kortix/projects/${encodeURIComponent(t)}/milestones?status=${n}`)}async function gU(e,t,n){return R(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}`)}async function mU(e,t,n){return R(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}/events`)}async function fU(e,t,n){return R(e,`/kortix/projects/${encodeURIComponent(t)}/milestones`,{method:"POST",body:JSON.stringify(n)})}async function yU(e,t,n,r){return R(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}`,{method:"PATCH",body:JSON.stringify(r)})}async function hU(e,t,n,r){return R(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}/close`,{method:"POST",body:JSON.stringify(r)})}async function bU(e,t,n){return R(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}/reopen`,{method:"POST"})}async function _U(e,t,n){return R(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}`,{method:"DELETE"})}async function PU(e,t){return R(e,`/kortix/projects/${encodeURIComponent(t)}/credentials`)}async function xU(e,t,n){return R(e,`/kortix/projects/${encodeURIComponent(t)}/credentials/${encodeURIComponent(n)}/events`)}async function SU(e,t,n){return R(e,`/kortix/projects/${encodeURIComponent(t)}/credentials`,{method:"POST",body:JSON.stringify(n)})}async function wU(e,t,n){return R(e,`/kortix/projects/${encodeURIComponent(t)}/credentials/${encodeURIComponent(n)}`)}async function AU(e,t,n){return R(e,`/kortix/projects/${encodeURIComponent(t)}/credentials/${encodeURIComponent(n)}`,{method:"DELETE"})}var sx=1e4,ix={retryOnAuthError:!1};function Mt(e,t,n){return R(e,t,{signal:AbortSignal.timeout(sx),...n},ix)}async function vU(e,t=!1){return(await Mt(e,`/kortix/services${t?"?all=true":""}`)).services??[]}async function kU(e){return(await Mt(e,"/kortix/services/templates")).templates??[]}async function RU(e,t){return(await Mt(e,`/kortix/services/${encodeURIComponent(t)}/logs`)).logs??[]}async function CU(e,t,n){let r=n==="delete",o=r?`/kortix/services/${encodeURIComponent(t)}`:`/kortix/services/${encodeURIComponent(t)}/${n}`;return Mt(e,o,{method:r?"DELETE":"POST"})}async function IU(e,t){return Mt(e,`/kortix/services/reconcile${t?"?reload=true":""}`,{method:"POST"})}async function TU(e,t){return Mt(e,"/kortix/services/register",{method:"POST",body:JSON.stringify(t)})}var De=new Map,ax=256,un=class extends Error{constructor(t="[opencode-sdk] Server URL not ready \u2014 sandbox is still loading"){super(t),this.name="RuntimeNotReadyError"}};function ct(){let e=Oe();if(!e)throw new un;return je(e)}function je(e){if(!e)throw new Error("[opencode-sdk] getClientForUrl called without a url");let t=De.get(e);if(t)return De.delete(e),De.set(e,t),t;if(!po())throw new Error("[opencode-sdk] No auth token provider configured \u2014 call configureKortix()/createKortix() before talking to a sandbox runtime.");let n=sn({baseUrl:e,fetch:E,eventTransport:df});return De.set(e,n),De.size>ax&&De.delete(De.keys().next().value),n}function LU(e){De.delete(e)}function FU(){De.clear()}var Rr=new Map;function NU(e){if(!e)throw new Error("[opencode-sdk] getPublicClientForUrl called without a url");let t=Rr.get(e);if(t)return t;let n=sn({baseUrl:e,fetch});return Rr.set(e,n),n}function KU(e){Rr.delete(e)}function qU(){Rr.clear()}async function cx(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 BU(e){let t=Oe();if(!t)throw new b("[opencode-sdk] Server URL not ready \u2014 sandbox is still loading",{code:"RUNTIME_UNAVAILABLE"});let n=e==="full"?"/kortix/refresh":"/global/dispose",r=await E(`${t}${n}`,{method:"POST"}),o=r.headers.get("content-type")??"",s=/^application\/([\w.+-]+\+)?json\b/i.test(o.trim());if(!r.ok)throw new b(`System reload failed (${r.status}): ${await cx(r)}`,{status:r.status,response:r,code:"RUNTIME_UNAVAILABLE"});if(!s)throw new b(`System reload endpoint is unavailable on this sandbox (${n})`,{status:r.status,response:r,code:"RUNTIME_UNAVAILABLE"});let i;try{i=await r.json()}catch(c){throw new b(`System reload returned malformed JSON from ${n}: ${c instanceof Error?c.message:String(c)}`,{status:r.status,response:r,code:"RUNTIME_UNAVAILABLE"})}let a=i===!0||typeof i=="object"&&i!==null&&i.ok===!0;return{success:a,mode:e,steps:a?[e==="full"?"refreshed workspace and restarted runtime":"reloaded config in place"]:[],errors:a?[]:[`the sandbox did not confirm the reload (${n})`]}}var Sf="frontend";function Cr(e,t,n){(e==="error"?console.error:e==="warn"?console.warn:e==="debug"?console.debug:console.log)(`[${Sf}] ${t}`,...n?[n]:[]);try{ct().app.log({service:Sf,level:e,message:t,extra:n})}catch{}}var He={debug:(e,t)=>Cr("debug",e,t),info:(e,t)=>Cr("info",e,t),warn:(e,t)=>Cr("warn",e,t),error:(e,t)=>Cr("error",e,t)};function lx(e){return{type:"heartbeat-gap",gapMs:e}}function ux(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 px={now:()=>Date.now(),setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),random:()=>Math.random()},dx=16,gx=8,mx=6e4,fx=5e3,yx=250,hx=1e3,bx=3e4,_x=5,Px=1e4,xx=4,Sx=.5,wx=3e3,Ax=3e4,vx=2e4,kx=2e3,Rx=8;function Cx(e){if(e.type==="session.status")return`session.status:${e.properties.sessionID}`;if(e.type==="lsp.updated")return"lsp.updated"}function Ix(e,t){if(e?.type!=="message.part.delta"||t.type!=="message.part.delta")return;let n=e.properties,r=t.properties;if(n.partID!==r.partID||n.field!==r.field||n.messageID!==r.messageID||n.sessionID!==r.sessionID)return;let o=e.coalesced??[e];return o.push(t),{...t,properties:{...r,delta:n.delta+r.delta},coalesced:o}}function wf(e){if(e.aborted)return{promise:Promise.resolve(),cleanup:()=>{}};let t=()=>{};return{promise:new Promise(r=>{t=()=>r(),e.addEventListener("abort",t,{once:!0})}),cleanup:()=>e.removeEventListener("abort",t)}}var pn=new WeakMap;function Tx(e,t,n){let r=t.timers??px,o=t.connectTimeoutMs??vx,s=t.heartbeatTimeoutMs??mx,i=t.maxConsecutiveHardFailures??Rx,a=new AbortController;function c(_,...w){for(let D of n){let T=_(D);if(T)try{T(...w)}catch(x){console.warn("[opencode-events] subscriber handler threw, skipping",x)}}}let p=null,d=!1,g=_=>{p!==_&&(p=_,_&&c(w=>w.onConnectionChange,_))},m=r.now(),f=null,h=[],P,j=0,L=new Map,N=()=>{if(P&&r.clearTimeout(P),P=void 0,h.length===0)return;let _=h;h=[],L.clear(),j=r.now(),m=r.now();for(let w of _)w&&c(D=>D.onEvent,w.event)},y=()=>{if(P)return;let _=r.now()-j;P=r.setTimeout(N,Math.max(0,dx-_))};return(async()=>{let _=0,w=0,D=0;for(;!a.signal.aborted;){let T=!1,x=!1,S,I,C=null,F=r.now(),M=new AbortController;g("connecting");let K=wf(a.signal);K.promise.then(()=>M.abort());try{let Q=await new Promise((ft,Qe)=>{let oe=!1;I=r.setTimeout(()=>{oe||(oe=!0,He.warn("SSE connect timed out, forcing reconnect",{connectTimeoutMs:o}),M.abort(),Qe(new Error(`SSE connect timed out after ${o}ms`)))},o),e.global.event({signal:M.signal,sseDefaultRetryDelay:wx,sseMaxRetryDelay:Ax,sseMaxRetryAttempts:1}).then(ve=>{oe||(oe=!0,r.clearTimeout(I),ft(ve))},ve=>{oe||(oe=!0,r.clearTimeout(I),Qe(ve))})}),{stream:ze}=Q;if(f){let ft=r.now()-f.lastActivityAt,Qe=f.eventful;f=null,(Qe||ft>fx)&&c(oe=>oe.onGapRehydrate,ft)}m=r.now();let Ye=()=>{r.clearTimeout(S),S=r.setTimeout(()=>{He.warn("SSE heartbeat timeout, forcing reconnect"),M.abort()},s)};Ye();let Ln=r.now(),wb=ze[Symbol.asyncIterator]();for(;!M.signal.aborted;){let ft=wb.next().then(ke=>({kind:"next",result:ke}),ke=>({kind:"error",error:ke})),Qe=wf(M.signal),oe=await Promise.race([ft,Qe.promise.then(()=>({kind:"aborted"}))]);if(Qe.cleanup(),oe.kind==="aborted")break;if(oe.kind==="error")throw oe.error;if(oe.result.done)break;g("open"),Ye();let ve=oe.result.value,yt=ve&&typeof ve=="object"&&"payload"in ve?ve.payload:ve;if(!yt?.type)continue;yt.type!=="server.connected"&&(T=!0);let co=Ix(h[h.length-1]?.event,yt);if(co)h[h.length-1]={type:co.type,event:co};else{let ke=Cx(yt);if(ke){let Ii=L.get(ke);Ii!==void 0&&(h[Ii]=void 0),L.set(ke,h.length)}h.push({type:yt.type,event:yt})}y(),!(r.now()-Ln<gx)&&(Ln=r.now(),await new Promise(ke=>r.setTimeout(ke,0)))}x=T}catch(Q){if(a.signal.aborted)break;C=Q;let ze=String(Q),Ye=Bt(Q)||Bt(Q?.cause);if(He.error("SSE event stream error",{error:ze,retryCount:_,isAuthError:Ye}),Ye)try{Co(),await Ro(),He.info("SSE: refreshed auth token after auth error")}catch(Ln){He.error("SSE: failed to refresh auth token",{error:String(Ln)})}}finally{r.clearTimeout(S),r.clearTimeout(I),M.abort(),K.cleanup(),N()}if(a.signal.aborted)break;let q=r.now()-F,ge=C?.cause?.status;if(w=!T&&(typeof ge=="number"&&ge>=400||q<kx)?w+1:0,w>=i){He.error("SSE event stream parked \u2014 giving up after consecutive hard failures",{consecutiveFailures:w,lastError:String(C)}),p=null,d=!0,c(Q=>Q.onParked,{consecutiveFailures:w,lastError:C});break}g("lost"),f={lastActivityAt:m,eventful:(f?.eventful??!1)||T},D=x&&q<Px?D+1:0;let we=x&&D<=xx;we?_=0:(_++,_>1&&He.warn("SSE event stream reconnecting",{retryCount:_}));let qt=we?yx:Math.min(hx*2**Math.min(_-1,_x),bx),Ae=Math.round(qt*(1+Sx*(r.random?.()??0)));await new Promise(Q=>{let ze=r.setTimeout(Q,Ae),Ye=()=>{r.clearTimeout(ze),Q()};a.signal.addEventListener("abort",Ye,{once:!0})})}})(),{subscribers:n,connectionState:()=>p,isParked:()=>d,teardown:()=>{p=null,a.abort(),P&&r.clearTimeout(P)}}}function Ds(e){let{onEvent:t,onGapRehydrate:n,onParked:r,onConnectionChange:o,signal:s}=e,i=e.client??(e.url?je(e.url):void 0);if(!i)throw new Error("openEventStream needs the session runtime `url`");let a={onEvent:t,onGapRehydrate:n,onParked:r,onConnectionChange:o},c=pn.get(i);if(c?.isParked()&&(pn.delete(i),c=void 0),!c)c=Tx(i,e,new Set([a])),pn.set(i,c);else{c.subscribers.add(a);let f=c.connectionState();f&&o?.(f)}let p=c,d=!1,g=()=>{d||(d=!0,s&&s.removeEventListener("abort",m),p.subscribers.delete(a),p.subscribers.size===0&&(p.teardown(),pn.get(i)===p&&pn.delete(i)))},m=()=>g();return s&&(s.aborted?g():s.addEventListener("abort",m,{once:!0})),{close:g}}function Af(e){return{abort:async()=>{let{runtimeSessionId:t,runtimeUrl:n}=await e.ensureReady();return je(n).session.abort({sessionID:t})},rewind:async t=>{let{runtimeSessionId:n,runtimeUrl:r}=await e.ensureReady();return je(r).session.revert({sessionID:n,messageID:t})},restoreRewind:async()=>{let{runtimeSessionId:t,runtimeUrl:n}=await e.ensureReady();return je(n).session.unrevert({sessionID:t})},stream:async t=>{let{runtimeUrl:n}=await e.ensureReady();return Ds({url:n,onEvent:t.onEvent,onGapRehydrate:t.onGapRehydrate,signal:t.signal})}}}function Cf(e){if(e.error){let t=e.error,n=t?.data?.message||t?.message||(typeof t?.error=="string"?t.error:null)||"SDK request failed";throw new b(n,{status:t?.response?.status??t?.status,response:t?.response,details:t})}return e.data}async function Ot(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 J(e){let t=(e??Oe()).trim();if(!t)throw new un;return t}async function Tr(e,t){let n=await E(`${J(t)}${e}`);if(!n.ok)throw new b(await Ot(n),{status:n.status,response:n});return n.json()}var Us=["/workspace","/tmp","/home","/opt"],Ex=Us.filter(e=>e!=="/workspace");function If(e){return Us.some(t=>e===t||e.startsWith(`${t}/`))}function yn(e){return If(e)?e:`/workspace/${e.replace(/^\/+/,"")}`}function lt(e){let t=e||"";if(t==="/workspace"||t==="/workspace/")return"";if(t.startsWith("/workspace/"))t=t.slice(11);else if(Ex.some(n=>t===n||t.startsWith(`${n}/`)))return t;for(;t.startsWith("/");)t=t.slice(1);return t}var Tf=lt;async function hn(e,t){let n=J(t),r=lt(e)||".";return(await Tr(`/file?path=${encodeURIComponent(r)}`,n)).map(s=>({...s,path:s.absolute||`/workspace/${s.path}`}))}async function bn(e,t){let n=J(t),r=lt(e),o=await E(`${n}/file/content?path=${encodeURIComponent(r)}`);if(!o.ok)throw new b(await Ot(o),{status:o.status,response:o});return o.json()}async function Mx(e,t,n){let r=J(n),o=lt(e),s=await E(`${r}/file/raw?path=${encodeURIComponent(o)}`);if(!s.ok)throw new b(await Ot(s),{status:s.status,response:s});if((s.headers.get("content-type")||"").includes("text/html"))throw new b("File could not be loaded (raw byte route unavailable)",{status:s.status,response:s,code:"INVALID_CONTENT_TYPE"});let i=await s.blob();return t&&(!i.type||i.type==="application/octet-stream")?new Blob([i],{type:t}):i}var Ox=8,Ir=0,Ef=[];async function Dx(){if(Ir<Ox){Ir++;return}await new Promise(e=>Ef.push(e)),Ir++}function jx(){Ir--,Ef.shift()?.()}function $x(e,t){let n=J(t);return sr(`${n}/file/raw?path=${encodeURIComponent(lt(e))}`)}async function _n(e,t){await Dx();try{let n=J(t);try{return await Mx(e,void 0,n)}catch{}let r=await bn(e,n);if(r.encoding==="base64"&&r.content){let o=Uint8Array.from(atob(r.content),s=>s.charCodeAt(0));return new Blob([o],{type:r.mimeType||"application/octet-stream"})}return new Blob([r.content??""],{type:r.mimeType||"text/plain;charset=utf-8"})}finally{jx()}}async function Er(e){return Tr("/file/status",J(e))}async function Mr(e,t,n){let r=J(n),o=new URLSearchParams({query:e});return t?.type&&o.set("type",t.type),t?.limit&&o.set("limit",String(t.limit)),Tr(`/find/file?${o.toString()}`,r)}async function Or(e,t){let n=J(t);return(await Tr(`/find?pattern=${encodeURIComponent(e)}`,n)).map(o=>({path:typeof o.path=="string"?o.path:o.path?.text??"",lines:typeof o.lines=="string"?o.lines:o.lines?.text??"",line_number:o.line_number,absolute_offset:o.absolute_offset,submatches:(o.submatches??[]).map(s=>({start:s.start,end:s.end}))}))}var dn=[400,1200],Ux=e=>e===408||e===429||e===502||e===503||e===504,vf=e=>new Promise(t=>setTimeout(t,e));function Lx(e){let t=e?.name;return t==="TimeoutError"||t==="AbortError"}var js=3e4,Mf=15*6e4,Fx=256;function gn(e){if(typeof e!="number"||!Number.isFinite(e)||e<=0)return js;let t=js+e/Fx;return Math.min(Mf,Math.max(js,Math.round(t)))}async function Nx(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 mn(e,t){let n;for(let o=0;o<=dn.length;o++){let s;try{s=await t(e())}catch(a){if(n=a,Lx(a)||o===dn.length)break;await vf(dn[o]);continue}if(s.ok)return s.json();let i=await Nx(s);if(n=new b(`Upload failed (${s.status}): ${i}`,{status:s.status,response:s}),!Ux(s.status)||o===dn.length)throw n;await vf(dn[o])}if(n instanceof b)throw n;let r=n instanceof Error?n.message:String(n||"request failed");throw new b(`Upload failed: ${r}`)}var $s=8*1024*1024;function Kx(e,t){if(!(typeof e?.size!="number"||!Number.isFinite(t))&&!(e.size>=t))throw new b(`Upload verification failed for ${e.path}: expected ${t} bytes, received ${e.size}`,{code:"UPLOAD_SIZE_MISMATCH"})}function kf(e,t){try{e?.onProgress?.(t)}catch{}}function Rf(e,t,n){let r=new FormData,o=(t??"").trim();return o&&r.append("path",o.startsWith("/")?o:`/${o}`),n&&r.append("filename",n),n?r.append("file",e,n):r.append("file",e),r}function qx(e){let t=e.lastIndexOf("/");return t<0?{parent:"",name:e}:{parent:e.slice(0,t)||"/",name:e.slice(t+1)}}async function Pn(e,t,n,r,o){let s=typeof r=="string"?r:void 0,i=typeof r=="string"?o:r,a=J(s),c=gn(e.size),p=n||(e instanceof File?e.name:"")||"";if(e.size<=$s){let f=await mn(()=>Rf(e,t,p),h=>E(`${a}/file/upload`,{method:"POST",body:h},{timeoutMs:c}));return Kx(f[0],e.size),kf(i,{loadedBytes:e.size,totalBytes:e.size}),f}let g=(await mn(()=>Rf(new Blob([],{type:e.type}),t,p),f=>E(`${a}/file/upload`,{method:"POST",body:f},{timeoutMs:gn(0)})))[0]?.path;if(!g)throw new b("Upload reservation returned no file path",{code:"UPLOAD_NO_RESULT"});let m=qx(g);if(!m.name)throw new b(`Upload reservation returned an invalid file path: ${g}`,{code:"UPLOAD_INVALID_PATH"});try{for(let f=0;f<e.size;f+=$s){let h=Math.min(e.size,f+$s),P=e.slice(f,h,e.type),j=await mn(()=>{let L=new FormData;return m.parent&&L.append("path",m.parent),L.append("filename",m.name),L.append("first",f===0?"true":"false"),L.append("offset",String(f)),L.append("file",P,m.name),L},L=>E(`${a}/file/append`,{method:"POST",body:L},{timeoutMs:gn(P.size)}));if(j.path!==g||j.size!==h)throw new b(`Upload verification failed for ${g}: expected ${h} bytes, received ${j.size}`,{code:"UPLOAD_SIZE_MISMATCH"});kf(i,{loadedBytes:h,totalBytes:e.size})}}catch(f){throw await Dt(g,a).catch(()=>{}),f}return[{path:g,size:e.size}]}function Bx(e,t,n){let r=J(n);return mn(()=>{let o=new FormData;return t&&o.append("path",t),o.append("file",{uri:e.uri,name:e.name,type:e.type||"application/octet-stream"}),o},o=>E(`${r}/file/upload`,{method:"POST",body:o},{timeoutMs:Gx}))}var Gx=Mf;function Wx(e,t,n){let r=J(n),o=gn(t.size);return mn(()=>{let s=new FormData;return s.append(e,t,e.split("/").pop()||"file"),s},s=>E(`${r}/file/upload`,{method:"POST",body:s},{timeoutMs:o}))}var fn=class extends b{path;constructor(t){super(`A file or folder already exists at ${t}`,{status:409,code:"FILE_EXISTS"}),this.name="FileExistsError",this.path=t}};async function Dr(e,t){let n=J(t),r=e.trim(),s=(r.startsWith("/")?r:`/${r}`).split("/"),i=s.pop()||"untitled",a=s.join("/")||"/workspace",c=yn(`${a}/${i}`),p=[];try{p=await hn(Of(c),n)}catch(g){if(!(g instanceof b&&g.status===404))throw g}if(p.some(g=>g.name===Df(c)))throw new fn(c);let d=await jf(c,new Blob([],{type:"application/octet-stream"}),n,{overwrite:!1});return[{path:d.path,size:d.bytes}]}async function jr(e,t,n){let r=J(n);return Wx(t,await _n(e,r),r)}function Hx(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function Of(e){let t=e.lastIndexOf("/");return t<=0?"/":e.slice(0,t)}function Df(e){return e.slice(e.lastIndexOf("/")+1)}function Vx(){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 $r(e,t,n){let r=J(n),o=yn(Hx(e.trim()));return jf(o,t,r,{overwrite:!0})}async function jf(e,t,n,r){let o=Df(e);if(!o)throw new b(`writeFile needs a file path, got "${e}"`,{code:"INVALID_PATH"});let s=Of(e);await xn(s,n).catch(()=>{});let i=Vx(),a=await Pn(t,s,`.${o}.kortix-write-${i}`,n),c=a[0]?.path;if(!c)throw new b(`Upload returned no file for ${e}`,{code:"UPLOAD_NO_RESULT"});let p=yn(c);try{await $f(p,e,n,r.overwrite)}catch(g){throw await Dt(p,n).catch(()=>{}),!r.overwrite&&g instanceof b&&g.status===409?new fn(e):g}let d=a[0]?.size;return{path:e,bytes:typeof d=="number"?d:t.size}}async function Dt(e,t){let n=await E(`${J(t)}/file`,{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:e})});if(!n.ok)throw new b(`Delete failed (${n.status}): ${await Ot(n)}`,{status:n.status,response:n});return n.json()}async function xn(e,t){let n=await E(`${J(t)}/file/mkdir`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:e})});if(!n.ok)throw new b(`Mkdir failed (${n.status}): ${await Ot(n)}`,{status:n.status,response:n});return n.json()}async function Ur(e,t,n){return $f(e,t,J(n),!0)}async function $f(e,t,n,r){let o=await E(`${n}/file/rename`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r?{from:e,to:t}:{from:e,to:t,overwrite:!1})});if(!o.ok)throw new b(`Rename failed (${o.status}): ${await Ot(o)}`,{status:o.status,response:o});return o.json()}async function Uf(){return Cf(await ct().project.current())}async function Ls(){return Cf(await ct().global.health())}async function Lf(){try{return(await Ls()).healthy===!0}catch{return!1}}var zx={list:hn,read:bn,readBlob:_n,status:Er,findFiles:Mr,findText:Or,upload:Pn,write:$r,create:Dr,copy:jr,remove:Dt,mkdir:xn,rename:Ur,currentProject:Uf,health:Ls,isReachable:Lf,toDaemonPath:lt,toSandboxAbsolutePath:yn,toWorkspaceRelative:Tf};function Ff(e){return{list:async t=>hn(t,(await e()).runtimeUrl),read:async t=>bn(t,(await e()).runtimeUrl),readBlob:async t=>_n(t,(await e()).runtimeUrl),status:async()=>Er((await e()).runtimeUrl),findFiles:async(t,n)=>Mr(t,n,(await e()).runtimeUrl),findText:async t=>Or(t,(await e()).runtimeUrl),upload:async(t,n,r,o)=>Pn(t,n,r,(await e()).runtimeUrl,o),write:async(t,n)=>$r(t,n,(await e()).runtimeUrl),create:async t=>Dr(t,(await e()).runtimeUrl),copy:async(t,n)=>jr(t,n,(await e()).runtimeUrl),remove:async t=>Dt(t,(await e()).runtimeUrl),mkdir:async t=>xn(t,(await e()).runtimeUrl),rename:async(t,n)=>Ur(t,n,(await e()).runtimeUrl)}}function Nf(e){return{get:t=>gr(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:()=>Pr(e.sessionId,{projectId:e.projectId}),update:t=>$u(e.projectId,e.sessionId,t),delete:()=>(e.forgetReady(),Uu(e.projectId,e.sessionId)),start:(...t)=>nt(e.projectId,e.sessionId,...t),startOrThrow:(...t)=>ap(e.projectId,e.sessionId,...t),restart:()=>(e.forgetReady(),fr(e.projectId,e.sessionId)),stop:()=>(e.forgetReady(),yr(e.projectId,e.sessionId)),configState:()=>Lu(e.projectId,e.sessionId),reloadConfig:t=>(e.forgetReady(),Fu(e.projectId,e.sessionId,t)),reloadConfigStream:(...t)=>(e.forgetReady(),Nu(e.projectId,e.sessionId,...t)),setSharing:t=>yu(e.projectId,e.sessionId,t),previews:()=>Pu(e.projectId,e.sessionId),participants:()=>hu(e.projectId,e.sessionId),watch:()=>bu(e.projectId,e.sessionId),setWatch:t=>_u(e.projectId,e.sessionId,t),commit:t=>Zl(e.projectId,e.sessionId,t),publicShares:{list:()=>xu(e.projectId,e.sessionId),create:(...t)=>Su(e.projectId,e.sessionId,...t),revoke:(...t)=>wu(e.projectId,e.sessionId,...t)}}}function Kf(e){return{reminders:{list:()=>lg(e.projectId,e.sessionId),create:t=>ug(e.projectId,e.sessionId,t),update:(t,n)=>Qo(e.projectId,e.sessionId,t,n),remove:t=>Xo(e.projectId,e.sessionId,t)},audit:(t,n)=>ku(e.projectId,e.sessionId,t,n),attachments:{upload:(t,n)=>Dm(e.projectId,e.sessionId,t,n),read:(t,n)=>jm(`kortix-attachment://${e.projectId}/${e.sessionId}/${t}`,n)},transcript:t=>Ru(e.projectId,e.sessionId,t),messageAuthors:()=>Wu(e.projectId,e.sessionId),modelUsage:()=>Hu(e.projectId,e.sessionId),transcriptSync:t=>Cu(e.projectId,e.sessionId,t),turn:()=>Iu(e.projectId,e.sessionId),prompts:{create:t=>mr(e.projectId,e.sessionId,t),list:()=>Tu(e.projectId,e.sessionId),remove:t=>Eu(e.projectId,e.sessionId,t),retry:t=>Du(e.projectId,e.sessionId,t),edit:(t,n)=>Mu(e.projectId,e.sessionId,t,n),interrupt:t=>Ou(e.projectId,e.sessionId,t),hold:t=>ju(e.projectId,e.sessionId,t)},ensureReady:e.ensureReady}}function Qx(e,t){return e?.some(n=>n.startsWith("session."))?e.includes(t):!0}var Xx=["control_plane","provider_ingress","daemon","upstream_port"];function qf(e){return typeof e=="string"&&Xx.includes(e)?e:null}function Bf(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 Gf(e,t){let n=(e===void 0?Oe():e)||null;if(!n)return{status:0,ok:!1,health:null,body:"",hop:null,upstreamStatus:null};let r=await E(`${n}/kortix/health`,{method:"GET",...t},{retryOnAuthError:!1}),o=await r.text().catch(()=>""),s=null;try{s=o?JSON.parse(o):null}catch{s=null}let i=s,a=qf(r.headers.get("X-Kortix-Proxy-Hop"))??qf(s?.hop),c=Number(r.headers.get("X-Kortix-Upstream-Status")),p=s?.upstream_status,d=Number.isFinite(c)&&c>0?c:typeof p=="number"?p:null;return{status:r.status,ok:r.ok,health:i,body:o,hop:a,upstreamStatus:d}}var Wf=/https?:\/\/(?:localhost|127\.0\.0\.1):\d{1,5}[^\s)"'<>]*/g,Hf=/^https?:\/\/p(\d+)-([^.]+)\.localhost(?::(\d+))?(\/.*)?$/,Vf=/^https?:\/\/(?:dev|staging|prod|preview)-p(\d+)-([a-z0-9-]+)\.[^/]+?(?::(\d+))?(\/.*)?$/i,zf=new Set([22,4096,parseInt(qe.KORTIX_MASTER,10)]);function Jx(e){return Hf.test(e)}function Lr(e){if(!e)return"/";let t=e,n=t.indexOf("](");n!==-1&&(t=t.slice(0,n));let r=t.toLowerCase().indexOf("%5d(");return r!==-1&&(t=t.slice(0,r)),t?t.startsWith("/")?t:`/${t}`:"/"}function Zx(e){let t=e.indexOf("](");return t===-1?e:e.slice(0,t)}var eS=new Set(["'",'"',"`","<","(","["]),tS=new Set([">","'",'"',"`",")","]",",",";",".","!","?"]);function nS(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&&eS.has(e[t]);)t++;for(;n>t&&tS.has(e[n-1]);)n--;return e.slice(t,n)}function rS(e){return e.match(/https?:\/\/(?:localhost|127\.0\.0\.1):\d{1,5}[^\s"'<>)]*/i)?.[0]??null}var oS=/^\/proxy\/(\d{1,5})(\/.*)?$/,sS=/^\/(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 iS(e){if(!e)return!1;try{let t=new URL(e);return t.hostname!=="localhost"&&t.hostname!=="127.0.0.1"?!1:sS.test(t.pathname)}catch{return!1}}function Fr(e){if(!e)return null;let t=nS(Zx(e.trim())),n=Zf(t);if(n){let r=Lr(n.path||"/");return{originalUrl:`http://localhost:${n.port}${r}`,port:n.port,path:r}}try{let r=new URL(t);if(r.protocol!=="http:"&&r.protocol!=="https:"||r.hostname!=="localhost"&&r.hostname!=="127.0.0.1"||!r.port)return null;let o=parseInt(r.port,10);if(!Number.isInteger(o)||o<1||o>65535)return null;let s=`${r.pathname||"/"}${r.search}${r.hash}`,i=parseInt(qe.KORTIX_MASTER,10);if(o===i){let c=r.pathname.match(oS);if(c){let p=parseInt(c[1],10);if(p>=1&&p<=65535)return o=p,s=Lr(`${c[2]||"/"}${r.search}${r.hash}`),{originalUrl:`http://localhost:${o}${s}`,port:o,path:s}}}let a=Lr(s);return{originalUrl:`${r.protocol}//${r.hostname}:${o}${a}`,port:o,path:a}}catch{let r=rS(e);return r&&r!==e?Fr(r):null}}function aS(e){let t=[],n=/```[\s\S]*?```/g,r;for(;(r=n.exec(e))!==null;)t.push([r.index,r.index+r[0].length]);let o=/`[^`\n]+`/g;for(;(r=o.exec(e))!==null;){let s=r.index,i=s+r[0].length;t.some(([c,p])=>s>=c&&i<=p)||t.push([s,i])}return t}function cS(e,t){return t.some(([n,r])=>e>=n&&e<r)}function lS(e){let t=[],n=new Set,r=aS(e);Wf.lastIndex=0;let o;for(;(o=Wf.exec(e))!==null;){let s=Fr(o[0]);if(!s)continue;let{originalUrl:i,port:a,path:c}=s;a<1||a>65535||zf.has(a)||n.has(i)||(n.add(i),t.push({originalUrl:i,port:a,path:c,startIndex:o.index,endIndex:o.index+i.length,inCodeBlock:cS(o.index,r)}))}return t}function PL(e){return lS(e).length>0}function uS(e){try{let{hostname:t}=new URL(e);return t==="localhost"||t==="127.0.0.1"}catch{return!1}}function Yf(e){return e.trim().toLowerCase().split("_").join("-")}function Qf(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function pS(e,t,n){let r=n.previewUrlTemplate;if(!r||!r.includes("{port}")||!r.includes("{sandbox}"))return null;let o=r.split("{port}").join(String(e)).split("{sandbox}").join(Yf(n.sandboxId));return`${Qf(o)}${t}`}function dS(e){return e.sandboxId.trim().length>0}function ut(e,t,n){let r=Lr(t);if(!dS(n))return yS(e,r);let o=pS(e,r,n);return o||(uS(n.apiBaseUrl)?`http://p${e}-${Yf(n.sandboxId)}.localhost:${n.backendPort}${r}`:`${Qf(n.apiBaseUrl)}/p/${n.sandboxId}/${e}${r}`)}function xL(e,t){if(!e)return;let r=e.replace(/^\/workspace\//,"").replace(/^\/+/,"").split("/").filter(Boolean).map(o=>encodeURIComponent(o)).join("/");return ut(3211,`/open?path=/workspace/${r}`,t)}function gS(e){return`/open?path=/${(e.startsWith("/workspace")?e:`/workspace/${e.replace(/^\/+/,"")}`).split("/").filter(Boolean).map(r=>encodeURIComponent(r)).join("/")}`}function SL(e){return`http://localhost:3211${gS(e)}`}function mS(){return"/health"}function wL(e){return ut(3211,mS(),e)}function AL(e,t){return ut(e,"/",t)}function fS(e){let t=Fr(e);return!(!t||zf.has(t.port)||iS(e))}function Xf(e,t){if(!e)return e;let n=Fr(e);return n?fS(n.originalUrl)?ut(n.port,n.path,t):n.originalUrl:e}function yS(e,t="/"){return`http://localhost:${e}${t}`}var Jf=/^https?:\/\/[^/]+\/v1\/p\/([^/]+)\/(\d+)(\/.*)?$/;function Zf(e){let t=e.match(Hf);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(Vf);if(n){let o=443;try{let s=new URL(e);o=s.port?parseInt(s.port,10):s.protocol==="https:"?443:80}catch{return null}return{port:parseInt(n[1],10),sandboxId:n[2],backendPort:o,path:n[4]||"/"}}let r=e.match(Jf);if(r)try{let o=new URL(e);return{port:parseInt(r[2],10),sandboxId:r[1],backendPort:parseInt(o.port,10)||(o.protocol==="https:"?443:80),path:r[3]||"/"}}catch{return null}return null}function vL(e){try{let t=Zf(e);return t?`http://localhost:${t.port}${t.path}`:null}catch{return null}}function kL(e){return Jx(e)||Vf.test(e)||Jf.test(e)}function RL(e){try{let{hostname:t,port:n}=new URL(e);return(t==="localhost"||t==="127.0.0.1")&&n!==""}catch{return!1}}var Sn="/web-proxy/";function CL(e,t){try{let n=new URL(e);if(n.protocol!=="http:"&&n.protocol!=="https:")return null;let r=n.protocol.replace(":",""),o=`${Sn}${r}/${n.host}${n.pathname}${n.search}${n.hash}`,s=parseInt(qe.KORTIX_MASTER,10);return`${ut(s,"/",t).replace(/\/$/,"")}${o}`}catch{return null}}function IL(e){try{let t=new URL(e),n=t.pathname.indexOf(Sn);if(n===-1)return null;let o=t.pathname.slice(n+Sn.length).match(/^(https?)\/([\w.\-]+(?::\d+)?)(\/.*)?$/);if(!o)return null;let s=o[1],i=o[2],a=o[3]||"/";return`${s}://${i}${a}${t.search}${t.hash}`}catch{return null}}function TL(e){try{return new URL(e).pathname.includes(Sn)}catch{return e.includes(Sn)}}function EL(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 ML(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 ey(e){return{health:t=>Gf(e.tryResolveReady()?.runtimeUrl??null,t),previewUrl:(t,n="/")=>ut(t,n,e.resolvePreviewOptsForSandbox(e.requireReady("previewUrl").sandboxId)),proxyUrl:t=>Xf(t,e.resolvePreviewOptsForSandbox(e.requireReady("proxyUrl").sandboxId)),sandboxPortUrl:t=>tt(e.requireReady("sandboxPortUrl").sandboxId,t)}}function Fs(e,t,n,r){let o,s,{persistedPromptDefaults:i,clearPersistedDefaults:a}=zm(e,t),{ensureReady:c,tryResolveReady:p,requireReady:d,forgetReady:g}=Zm(e,t,n),m={projectId:e,sessionId:t,ensureReady:c,tryResolveReady:p,requireReady:d,forgetReady:g,resolvePreviewOptsForSandbox:r,get model(){return o},set model(f){o=f},get agent(){return s},set agent(f){s=f},clearPersistedDefaults:a,persistedPromptDefaults:i};return{...Nf(m),...Kf(m),...ey(m),...of(m),...pf(m),...Af(m),files:Ff(c),...rf(m),get runtime(){return je(d("runtime").runtimeUrl)}}}function ty(e){return{apps:{list:()=>Ng(e),create:t=>Kg(e,t),get:t=>Zo(e,t),update:(...t)=>qg(e,...t),access:{get:(...t)=>Hg(e,...t),update:(...t)=>zg(e,...t),session:(...t)=>Yg(e,...t),agents:t=>Vg(e,t)},remove:t=>Bg(e,t),token:t=>Gg(e,t),authEnv:t=>Wg(e,t),artifacts:{register:t=>es(e,t),uploadArchive:(...t)=>Qg(e,...t),finalize:(...t)=>ts(e,...t)},deployments:{create:(...t)=>Xg(e,...t),list:t=>Jg(e,t),get:(...t)=>Zg(e,...t),logs:(...t)=>em(e,...t),remove:(...t)=>rm(e,...t)},start:t=>tm(e,t),stop:t=>nm(e,t),rollback:(...t)=>om(e,...t),machines:{list:t=>sm(e,t),start:(t,n)=>im(e,t,n),stop:(t,n)=>am(e,t,n),restart:(t,n)=>cm(e,t,n),destroy:(t,n)=>lm(e,t,n)},scale:(t,n)=>um(e,t,n),exec:(...t)=>pm(e,...t),volumes:{list:t=>dm(e,t),create:(...t)=>gm(e,...t),update:(...t)=>mm(e,...t),destroy:(...t)=>fm(e,...t),snapshots:(...t)=>ym(e,...t),snapshot:(...t)=>hm(e,...t),restore:(...t)=>bm(e,...t),fork:(...t)=>_m(e,...t)}}}}function ny(e){return{list:()=>za(e),invite:(...t)=>Xa(e,...t),update:(...t)=>Ya(e,...t),revoke:t=>Qa(e,t),pendingInvites:()=>Ja(e),resendInvite:(...t)=>ec(e,...t),revokeInvite:(...t)=>Za(e,...t),requests:()=>Wa(e),approveRequest:(...t)=>Ha(e,...t),rejectRequest:(...t)=>Va(e,...t),groupGrants:()=>tc(e),attachGroupGrant:(...t)=>nc(e,...t),updateGroupGrant:(...t)=>rc(e,...t),detachGroupGrant:t=>oc(e,t),resourceGrants:{list:()=>sc(e),create:t=>ic(e,t),remove:t=>ac(e,t)}}}function ry(e){return{tokens:{list:()=>Pg(e),create:t=>xg(e,t),revoke:t=>Sg(e,t)},setupLinks:{requestSecret:t=>Tg(e,t),requestConnector:t=>Eg(e,t)},validateManifest:t=>Sa(e,t),gitToken:()=>wa(e),agentIdentities:()=>Ed(e),secrets:{list:()=>pc(e),upsert:t=>dc(e,t),setStrategy:(...t)=>gc(e,...t),broker:(...t)=>mc(e,...t),remove:t=>bc(e,t),setPersonal:(...t)=>_c(e,...t),removePersonal:t=>Pc(e,t),setGitCredential:t=>hc(e,t),listProviderOAuth:()=>fc(e),startProviderOAuth:(...t)=>Ao(e,...t),pollProviderOAuth:(...t)=>vo(e,...t),removeProviderOAuth:t=>yc(e,t)},access:ny(e)}}function oy(e){return{list:()=>Dc(e),listAll:()=>jc(e),reconcile:(...t)=>$c(e,...t),reconcileMember:(...t)=>Uc(e,...t),updateCredential:(...t)=>Lc(e,...t),revoke:(...t)=>Fc(e,...t),activate:(...t)=>Nc(e,...t),setDefault:(...t)=>Kc(e,...t),rename:(...t)=>qc(e,...t),share:(...t)=>Gc(e,...t),addComputer:(...t)=>Bc(e,...t),pipedreamConnect:(...t)=>Wc(e,...t),pipedreamFinalize:(...t)=>Hc(e,...t)}}function Nr(e){return{catalog:t=>Vt(e,t),tools:()=>Io(e),search:(...t)=>Oc(e,...t),describe:(...t)=>To(e,...t),call:(...t)=>xt(e,...t),callAction:(t,n,r,o)=>xt(e,`${t}.${n}`,r,o),accounts:(...t)=>Eo(e,...t),uploadAttachment:(...t)=>Mo(e,...t)}}function Ns(e,t){return{slug:t,run:(r,o,s)=>Uo(e,t,r,o,s),call:(r,o,s)=>xt(e,`${t}.${r}`,o,s),describe:async r=>r!==void 0?To(e,`${t}.${r}`):(await Vt(e,{slug:t,includeSchemas:!0,includeOutputSchemas:!0})).find(s=>s.slug===t)??null,accounts:()=>Eo(e,t),paginate:(r,o,s)=>ml(e,t,r,o,s),uploadAttachment:(r,o)=>Mo(e,r,{...o,connector:t})}}var hS=100,bS=0,_S=new Set(["attachment_size_mismatch","attachment_failed"]),sy=()=>new b("Attachment expired. Attach the file again.",{code:"attachment_expired"});function iy(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 ay(e,t={}){let n=t.concurrency??2;if(!Number.isInteger(n)||n<1||n>20)throw new Error("Attachment concurrency must be between 1 and 20");let r=new Map,o=new Set,s=new Set,i=0,a=!1,c,p={attachments:[]},d=()=>[...r.values()].filter(y=>!y.handedOff);function g(y,_){y.removalDeleted||(y.removalDeleted=!0,Qt(e,_).catch(()=>{}))}function m(){c&&clearTimeout(c);let y=d().map(({item:w})=>w);(y.length!==p.attachments.length||y.some((w,D)=>w!==p.attachments[D]))&&(p={attachments:y});let _=Math.min(...y.filter(w=>w.status==="ready").map(w=>Date.parse(w.attachment.expires_at)));Number.isFinite(_)&&!a&&(c=setTimeout(()=>{for(let w of d())w.item.status==="ready"&&Date.parse(w.item.attachment.expires_at)<=Date.now()&&(w.item={...w.item,status:"error",error:sy()});m()},Math.min(2147483647,Math.max(0,_-Date.now()))),typeof c=="object"&&"unref"in c&&c.unref());for(let w of o)w();for(let w of[...s])w()}function f(){if(a)throw new Error("Attachment controller is disposed");if(!e)throw new Error("A project is required to attach files");return e}function h(y){f();let _=d();if(_.length+y.length>20)throw new Error("A message can contain up to 20 attachments");if(y.some(D=>!Number.isSafeInteger(D)||D<=0||D>52428800))throw new Error("Each attachment must contain 1 byte to 50 MiB");if(_.reduce((D,T)=>D+T.item.size,0)+y.reduce((D,T)=>D+T,0)>104857600)throw new Error("Message attachments exceed 100 MiB")}function P(){for(let y of r.values()){if(i>=n)break;if(y.item.status!=="pending"||!y.item.file||a&&!y.handedOff)continue;let _=y.item.file;i++;let w=++y.generation,D=new AbortController;y.abort=D,y.item={...y.item,status:"uploading",error:void 0};let T=()=>(!a||y.handedOff===!0)&&r.get(y.item.id)===y&&y.generation===w,x,S=0,I,C=()=>{I=void 0,!(!T()||y.item.status!=="uploading"||x===void 0)&&(y.item={...y.item,receivedBytes:x},x=void 0,S=Date.now(),m())},F=M=>Math.floor(M*100/y.item.size);lr(e,_,{resume:y.upload,signal:D.signal,onUpload:M=>{y.upload=M,y.removed&&(D.abort(),g(y,M.attachment_id))},onProgress:M=>{if(!T()||F(M)===F(y.item.receivedBytes)||(x=M,I))return;let K=S+hS-Date.now();if(K<=0)return C();I=setTimeout(C,K),typeof I=="object"&&"unref"in I&&I.unref()},onProcessing:()=>{I&&clearTimeout(I),I=void 0,x=void 0,T()&&(y.item={...y.item,status:"processing",receivedBytes:y.item.size},m())}}).then(M=>{T()&&(y.item={...y.item,status:"ready",attachment:iy(M),receivedBytes:M.size})}).catch(M=>{M instanceof b&&_S.has(M.code??"")&&(y.upload=void 0),T()&&(y.item={...y.item,status:M instanceof b&&M.code==="ABORTED"?"aborted":"error",error:M instanceof Error?M:new Error(String(M))})}).finally(()=>{i--,I&&clearTimeout(I),y.abort===D&&(y.abort=void 0),m(),P()})}m()}function j(y){h(y.map(w=>w.size));let _=y.map(w=>{let D=`attachment-${++bS}`;return r.set(D,{generation:0,item:{id:D,file:w,filename:w.name,mime:w.type||"application/octet-stream",size:w.size,status:"pending",receivedBytes:0}}),D});return m(),P(),_}function L(y){let _=r.get(y);!_||_.item.status==="ready"||(_.generation++,_.abort?.abort(),_.item={..._.item,status:"aborted",error:new Error("Attachment upload cancelled")},m())}function N(y,{signal:_}={}){let w=[...y];return new Promise((D,T)=>{let x=()=>{s.delete(C),_?.removeEventListener("abort",I)},S=F=>{x(),T(F)},I=()=>S(ye()),C=()=>{let F=!1;for(let K of w){let q=r.get(K);if(!q)return S(new Error("Attachment was removed before it was sent"));if(a&&!q.handedOff)return S(new Error("Attachment controller is disposed"));if(q.item.status==="error"||q.item.status==="aborted")return S(q.item.error??new Error("Attachment upload failed"));q.item.status!=="ready"&&(F=!0)}if(F)return;let M;try{M=w.map(K=>{let q=iy(r.get(K).item.attachment);return{type:"file",attachment_id:q.attachment_id,filename:q.filename,mime:q.mime}})}catch(K){return S(K instanceof Error?K:new Error(String(K)))}x(),D(M)};if(_?.aborted)return I();s.add(C),_?.addEventListener("abort",I,{once:!0}),C()})}return{add:y=>j([y])[0],addMany:j,retry(y){let _=r.get(y);if(_?.handedOff||f(),!(!_||_.item.status==="ready"||_.item.status==="uploading"||_.item.status==="processing"||_.item.status==="pending")){if(!_.item.file||_.upload&&Date.parse(_.upload.expires_at)<=Date.now())throw sy();_.item={..._.item,status:"pending",error:void 0},P()}},async remove(y){let _=r.get(y);if(!_)return;_.removed=!0,_.generation++,r.delete(y);let w=_.upload?.attachment_id??_.item.attachment?.attachment_id;w&&_.abort?.abort(),m(),P(),w&&g(_,w)},abort:L,submit(y){if(!a){for(let _ of y){let w=r.get(_);w&&(w.handedOff=!0)}m()}},reclaim(y){if(!a){for(let _ of y){let w=r.get(_);w&&(w.handedOff=!1)}m()}},whenReady:N,forget(y=d().map(_=>_.item.id)){for(let _ of y){let w=r.get(_);w&&(w.generation++,w.abort?.abort(),r.delete(_))}m(),P()},dispose(){if(!a){a=!0,c&&clearTimeout(c);for(let y of r.values()){if(y.handedOff)continue;y.generation++,y.abort?.abort();let _=y.upload?.attachment_id??y.item.attachment?.attachment_id;_&&e&&Qt(e,_).catch(()=>{})}o.clear(),m()}},getSnapshot:()=>p,subscribe(y){return o.add(y),()=>{o.delete(y)}}}}function cy(e){return{attachments:{upload:(...t)=>lr(e,...t),delete:(...t)=>Qt(e,...t),createController:t=>ay(e,t)},get:t=>Qn(e,t),detail:()=>Xn(e),skills:{create:(...t)=>Ea(e,...t)},audit:t=>Ag(e,t),update:t=>er(e,t),archive:()=>tr(e),llmCatalog:()=>Jn(e),modelPicker:()=>Zn(e),modelAccess:()=>Sr(e),setModelAccess:t=>wr(e,t),sandboxHealth:()=>or(e),onboardingComplete:(...t)=>Ta(e,...t)}}function ly(e){return{sessions:{list:t=>At(e,t),listPage:t=>fu(e,t),create:t=>vt(e,t),ensureWarm:()=>Au(e),claimWarm:t=>vu(e,t)},review:{list:t=>Xd(e,t),get:t=>Jd(e,t),submit:t=>Zd(e,t),act:(...t)=>eg(e,...t),bulkAct:t=>tg(e,t)},approvals:{list:t=>cc(e,t),resolve:(...t)=>uc(e,...t),sessionsNeedingInput:t=>lc(e,t)}}}function uy(e){return{files:{list:t=>kl(e,t),listDirectory:t=>Rl(e,t),read:(t,n)=>Il(e,t,n),search:(...t)=>Cl(e,...t),archive:(...t)=>Tl(e,...t),archiveRequest:(...t)=>El(e,...t),history:(...t)=>ql(e,...t)},git:{commits:()=>Fl(e),commit:t=>Nl(e,t),commitDiff:t=>Kl(e,t),branches:()=>Ll(e),versionDiff:(...t)=>Bl(e,...t),inviteCollaborator:(...t)=>xa(e,...t)},changeRequests:{list:()=>Gl(e),get:t=>Wl(e,t),update:(...t)=>eu(e,...t),diff:t=>Hl(e,t),mergePreview:t=>Vl(e,t),open:(...t)=>zl(e,...t),merge:(...t)=>Yl(e,...t),close:(...t)=>Ql(e,...t),reopen:(...t)=>Xl(e,...t),requestChanges:(...t)=>Jl(e,...t)},...ly(e)}}function py(e){return{policies:{list:()=>fl(e),set:(...t)=>yl(e,...t)},reminders:{list:()=>mg(e),updateMany:(...t)=>dg(e,...t),removeMany:(...t)=>gg(e,...t)},triggers:{list:()=>Vu(e),eventApps:()=>ep(e),eventTypes:(...t)=>Zu(e,...t),create:(...t)=>zu(e,...t),update:(...t)=>Yu(e,...t),remove:(...t)=>Qu(e,...t),fire:(...t)=>Ju(e,...t),setActivation:(...t)=>Xu(e,...t)},...uy(e)}}function dy(e,t){return{connectors:{...Nr(e),list:()=>Vc(e),config:(...n)=>el(e,...n),create:(...n)=>rl(e,...n),remove:(...n)=>sl(e,...n),sync:()=>zc(e),auth:{discover:(...n)=>ol(e,...n)},setName:(...n)=>tl(e,...n),setCredentialMode:(...n)=>Yc(e,...n),setAuthorizationStrategy:(...n)=>Qc(e,...n),setCredential:(...n)=>ul(e,...n),deleteCredential:(...n)=>pl(e,...n),setSensitive:(...n)=>Xc(e,...n),connections:t,policies:{get:(...n)=>Jc(e,...n),set:(...n)=>Zc(e,...n)},pipedream:{listApps:(...n)=>il(e,...n),listSections:(...n)=>al(e,...n),connect:(...n)=>nl(e,...n),finalize:(...n)=>dl(e,...n)},discover:{list:(...n)=>Oo(e,...n),sections:(...n)=>cl(e,...n),detail:(...n)=>Do(e,...n)}},...py(e)}}function gy(e){return{gateway:{logs:t=>ad(e,t),log:t=>cd(e,t),overview:t=>ld(e,t),series:t=>ud(e,t),breakdown:t=>pd(e,t),sessions:t=>dd(e,t),errors:t=>gd(e,t),budgets:()=>md(e),setBudget:t=>fd(e,t),deleteBudget:t=>yd(e,t),keys:()=>hd(e),createKey:t=>bd(e,t),revokeKey:t=>_d(e,t),routing:{get:()=>rd(e),set:t=>od(e,t),reset:()=>sd(e),preview:t=>id(e,t)},playground:(t,n,r)=>Pd(e,t,n,r)}}}function my(e){return{modelDefaults:{get:()=>lp(e),set:t=>up(e,t),clear:t=>pp(e,t)},setDefaultAgent:t=>mp(e,t),sandbox:{list:()=>vl(e),snapshots:()=>bl(e),rebuildSnapshot:t=>_l(e,t),fixWithAgent:()=>Pl(e),createTemplate:t=>xl(e,t),updateTemplate:(...t)=>Sl(e,...t),removeTemplate:t=>wl(e,t),buildTemplate:t=>Al(e,t),setProvider:t=>Ia(e,t)},setAgentScope:(...t)=>gp(e,...t)}}function fy(e){return{channels:{slack:{installation:()=>qp(e),connect:t=>Bp(e,t),mode:()=>Gp(e),completeInstall:t=>Hp(e,t),manifest:()=>zp(e),disconnect:()=>Yp(e),getFile:t=>Qp(e,t),uploadFile:t=>Xp(e,t)},teams:{completeInstall:t=>Vp(e,t)},email:{installation:t=>Jp(e,t),mode:()=>Zp(e),connect:t=>ed(e,t),disconnect:t=>td(e,t),updatePolicy:(...t)=>nd(e,...t)}},updateFeatureFlag:(...t)=>Ra(e,...t),updateExperimentalFeature:(...t)=>Ca(e,...t),...my(e)}}async function yy(e){let t=e?.fetch??v().fetch??((o,s)=>fetch(o,s)),n=e?.backendUrl??v().backendUrl,r=await t(`${rt(n)}/clients/mobile`,{headers:{accept:"application/json"},...e?.signal?{signal:e.signal}:{}});if(!r.ok)throw new b(`Mobile client policy request failed (HTTP ${r.status})`,{status:r.status,response:r});return await r.json()}var PS=/^v?(\d+)(?:\.(\d+))?(?:\.(\d+))?(?:[-+].*)?$/i;function wF(e,t){let n=s=>{let i=PS.exec(s.trim());return i?[Number(i[1]),Number(i[2]??0),Number(i[3]??0)]:null},r=n(e),o=n(t);if(!r||!o)return null;for(let s=0;s<3;s++)if(r[s]!==o[s])return r[s]<o[s]?-1:1;return 0}function xS(){return ct()}var hy=null,by=!1;function SS(e){let t=hy;hy=e,!(by||!t)&&(t.backendUrl===e.backendUrl&&t.getToken===e.getToken||(by=!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 wS(e,t){t?.global!==!1&&SS(e),uo(e,t);let n=Vm(e),{auth:r,accounts:o,iam:s,accountInvites:i}=qm(),{billing:a,sandboxShares:c}=Fm(),{projects:p,github:d,gitBackend:g,connectStatus:m,marketplace:f}=Lm();function h(P){let j=oy(P);return{...cy(P),...ty(P),...ry(P),...dy(P,j),...gy(P),...fy(P),connector:L=>Ns(P,L),session:L=>Fs(P,L,e,n)}}return{config:e,auth:r,accounts:o,iam:s,accountInvites:i,projects:p,connectors:Nr(),connector:P=>Ns(void 0,P),project:h,session:(P,j)=>Fs(P,j,e,n),github:d,gitBackend:g,billing:a,sandboxShares:c,connectStatus:m,marketplace:f,notifications:{registerDeviceToken:xm,unregisterDeviceToken:Sm,list:wm,markRead:Am,preferences:vm,updatePreferences:km,webPushPublicKey:Rm,registerWebPushSubscription:Cm,unregisterWebPushSubscription:Im},mobileClientPolicy:yy,validateToken:ba,runtime:xS}}function AS(){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 vS(){return{pending:[],failed:[],inFlightId:null,inFlightIds:[]}}function jt(e){return e.inFlightIds?.length?e.inFlightIds:e.inFlightId?[e.inFlightId]:[]}function kS(e,t){return{...e,pending:[...e.pending,{...t,attempts:0}]}}function RS(e){if(jt(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 CS(e){let t=jt(e);return t.length===0?e:{...e,pending:e.pending.filter(n=>!t.includes(n.id)),inFlightId:null,inFlightIds:[]}}function IS(e,t){let n=jt(e);if(n.length===0)return e;let r=e.pending.filter(o=>n.includes(o.id));return r.length===0?{...e,inFlightId:null,inFlightIds:[]}:{pending:e.pending.filter(o=>!n.includes(o.id)),failed:[...e.failed,...r.map(o=>({...o,lastError:t}))],inFlightId:null,inFlightIds:[]}}function TS(e,t){let n=e.failed.find(s=>s.id===t);if(!n)return e;let{lastError:r,...o}=n;return{...e,pending:[...e.pending,o],failed:e.failed.filter(s=>s.id!==t)}}function ES(e,t){return jt(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 MS(e,t,n){return jt(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 OS(e,t,n){let r=jt(e);if(r.includes(t))return e;let o=e.pending.findIndex(p=>p.id===t);if(o===-1)return e;let s=r.length,i=Math.min(Math.max(n,s),e.pending.length-1);if(i===o)return e;let a=[...e.pending],[c]=a.splice(o,1);return a.splice(i,0,c),{...e,pending:a}}var _y={thinking:!1,toolDetails:!0,assistantMetadata:!0};function DS(e){return e&&e.charAt(0).toUpperCase()+e.slice(1)}function jS(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 $S(e,t){if(e.type==="text"&&!e.synthetic)return`${e.text??""}
22
22
 
23
23
  `;if(e.type==="reasoning")return t.thinking?`> _Thinking:_
24
24
  >
@@ -51,15 +51,15 @@ ${o}
51
51
  ${e.state.error}
52
52
  \`\`\`
53
53
  `),n+=`
54
- `,n}return""}function nS(e,t){if(!t)return`## Assistant
54
+ `,n}return""}function US(e,t){if(!t)return`## Assistant
55
55
 
56
- `;let n=e.agent?Zx(e.agent):"Assistant",r=e.modelID||"",o="";e.time?.completed&&e.time?.created&&(o=eS(e.time.completed-e.time.created));let s=[r,o].filter(Boolean).join(" \xB7 ");return s?`## ${n} (${s})
56
+ `;let n=e.agent?DS(e.agent):"Assistant",r=e.modelID||"",o="";e.time?.completed&&e.time?.created&&(o=jS(e.time.completed-e.time.created));let s=[r,o].filter(Boolean).join(" \xB7 ");return s?`## ${n} (${s})
57
57
 
58
58
  `:`## ${n}
59
59
 
60
- `}function rS(e,t,n){let r="";e.role==="user"?r+=`## User
60
+ `}function LS(e,t,n){let r="";e.role==="user"?r+=`## User
61
61
 
62
- `:r+=nS(e,n.assistantMetadata);for(let o of t)r+=tS(o,n);return r}function oS(e,t,n=Zf){let r=`# ${e.title||"Untitled Session"}
62
+ `:r+=US(e,n.assistantMetadata);for(let o of t)r+=$S(o,n);return r}function FS(e,t,n=_y){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,30 +67,30 @@ ${e.state.error}
67
67
 
68
68
  `,r+=`---
69
69
 
70
- `;for(let o of t)r+=rS(o.info,o.parts,n),r+=`---
70
+ `;for(let o of t)r+=LS(o.info,o.parts,n),r+=`---
71
71
 
72
- `;return r}function sS(e,t){return`session-${e}.md`}var Es="An error occurred";var iS=["message","error","detail","error_description","msg","errors","data"];function Ms(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 It(e){if(!(typeof e!="string"||!e))try{return JSON.parse(e)}catch{return}}function aS(e){let t=e.match(/"(?:message|detail|error_description|msg)"\s*:\s*"((?:[^"\\]|\\.)*)"/);if(!t)return;let n=It(`"${t[1]}"`);return typeof n=="string"&&n.trim()?n.trim():void 0}function cS(e){if(!/^\s*<(?:!doctype|html|head|body)\b/i.test(e))return;let t=e.toLowerCase(),n=lS(e,t);if(n)return n;let r=pS(e,t);return r?r.slice(0,200):void 0}function ry(e){return Number.isNaN(e)?!0:!(e>=48&&e<=57||e>=65&&e<=90||e>=97&&e<=122)}function ey(e,t){let n=e.indexOf(">",t);return n===-1?e.length:n+1}function lS(e,t){let n=0;for(;;){let r=t.indexOf("<title",n);if(r===-1)return;let o=r+6;if(!ry(t.charCodeAt(o))){n=o;continue}let s=e.indexOf(">",o);if(s===-1)return;let i=e.indexOf("<",s+1);if(i!==-1&&t.startsWith("</title",i)){let a=e.slice(s+1,i).trim();if(a)return a}n=s+1}}var uS=["script","style"];function pS(e,t){let n=[],r=0;for(;r<e.length;){let o=e.indexOf("<",r);if(o===-1){n.push(e.slice(r));break}n.push(e.slice(r,o));let s=uS.find(i=>t.startsWith(`<${i}`,o)&&ry(t.charCodeAt(o+i.length+1)));if(s){let i=t.indexOf(`</${s}`,o);r=i===-1?e.length:ey(e,i);continue}r=ey(e,o)}return n.join(" ").replace(/\s+/g," ").trim()}function dS(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 gS(e){let t=e.replace(/[_-]+/g," ").trim();return t&&t.charAt(0).toUpperCase()+t.slice(1)}function ty(e,t,n){if(typeof e=="string")return Mr(e,t,n);if(e&&typeof e=="object")return Or(e,t,n)}function Mr(e,t,n=new WeakSet){let r=Ms(e);if(!r)return;if(t>=4)return r;let o=dS(r);if(o)return o;let s=It(r);if(s!==void 0)return typeof s=="string"?Mr(s,t+1,n):s&&typeof s=="object"?Or(s,t+1,n):String(s);let i=sy(r);if(i){let a=It(i);if(a&&typeof a=="object"){let c=Or(a,t+1,n);if(c)return c}}if(r.includes("{")){let a=aS(r);if(a)return Mr(a,t+1,n)??a}return cS(r)??r}function Or(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=ty(i,t,n);if(a)return a}return}let r=e;for(let i of iS){let a=ty(r[i],t,n);if(a)return a}let o=r.type??r.code;if(typeof o=="string"&&o.trim())return gS(o);let s=r.status??r.statusCode??r.upstream_status;if(typeof s=="number"&&Number.isFinite(s))return`Request failed with status ${s}`}function de(e){return e?typeof e=="string"?Mr(e,0)??Es:typeof e=="object"?Or(e,0)??Es:String(e):Es}function oy(e){let t=mS(e)?.trim();if(!t)return;let n=de(e);if(!(t===n||Ms(t)===n))return t}function mS(e){if(typeof e=="string")return e;if(!e||typeof e!="object")return;let t=e,n=t.data;if(n&&typeof n=="object"&&!Array.isArray(n)){let{message:r,responseBody:o}=n,s=[r,o].filter((i,a,c)=>typeof i=="string"&&i.trim()!==""&&c.indexOf(i)===a);if(s.length>0)return s.join(`
72
+ `;return r}function NS(e,t){return`session-${e}.md`}var Ks="An error occurred";var KS=["message","error","detail","error_description","msg","errors","data"];function qs(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 $t(e){if(!(typeof e!="string"||!e))try{return JSON.parse(e)}catch{return}}function qS(e){let t=e.match(/"(?:message|detail|error_description|msg)"\s*:\s*"((?:[^"\\]|\\.)*)"/);if(!t)return;let n=$t(`"${t[1]}"`);return typeof n=="string"&&n.trim()?n.trim():void 0}function BS(e){if(!/^\s*<(?:!doctype|html|head|body)\b/i.test(e))return;let t=e.toLowerCase(),n=GS(e,t);if(n)return n;let r=HS(e,t);return r?r.slice(0,200):void 0}function wy(e){return Number.isNaN(e)?!0:!(e>=48&&e<=57||e>=65&&e<=90||e>=97&&e<=122)}function Py(e,t){let n=e.indexOf(">",t);return n===-1?e.length:n+1}function GS(e,t){let n=0;for(;;){let r=t.indexOf("<title",n);if(r===-1)return;let o=r+6;if(!wy(t.charCodeAt(o))){n=o;continue}let s=e.indexOf(">",o);if(s===-1)return;let i=e.indexOf("<",s+1);if(i!==-1&&t.startsWith("</title",i)){let a=e.slice(s+1,i).trim();if(a)return a}n=s+1}}var WS=["script","style"];function HS(e,t){let n=[],r=0;for(;r<e.length;){let o=e.indexOf("<",r);if(o===-1){n.push(e.slice(r));break}n.push(e.slice(r,o));let s=WS.find(i=>t.startsWith(`<${i}`,o)&&wy(t.charCodeAt(o+i.length+1)));if(s){let i=t.indexOf(`</${s}`,o);r=i===-1?e.length:Py(e,i);continue}r=Py(e,o)}return n.join(" ").replace(/\s+/g," ").trim()}function VS(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 zS(e){let t=e.replace(/[_-]+/g," ").trim();return t&&t.charAt(0).toUpperCase()+t.slice(1)}function xy(e,t,n){if(typeof e=="string")return Kr(e,t,n);if(e&&typeof e=="object")return qr(e,t,n)}function Kr(e,t,n=new WeakSet){let r=qs(e);if(!r)return;if(t>=4)return r;let o=VS(r);if(o)return o;let s=$t(r);if(s!==void 0)return typeof s=="string"?Kr(s,t+1,n):s&&typeof s=="object"?qr(s,t+1,n):String(s);let i=vy(r);if(i){let a=$t(i);if(a&&typeof a=="object"){let c=qr(a,t+1,n);if(c)return c}}if(r.includes("{")){let a=qS(r);if(a)return Kr(a,t+1,n)??a}return BS(r)??r}function qr(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=xy(i,t,n);if(a)return a}return}let r=e;for(let i of KS){let a=xy(r[i],t,n);if(a)return a}let o=r.type??r.code;if(typeof o=="string"&&o.trim())return zS(o);let s=r.status??r.statusCode??r.upstream_status;if(typeof s=="number"&&Number.isFinite(s))return`Request failed with status ${s}`}function fe(e){return e?typeof e=="string"?Kr(e,0)??Ks:typeof e=="object"?qr(e,0)??Ks:String(e):Ks}function Ay(e){let t=YS(e)?.trim();if(!t)return;let n=fe(e);if(!(t===n||qs(t)===n))return t}function YS(e){if(typeof e=="string")return e;if(!e||typeof e!="object")return;let t=e,n=t.data;if(n&&typeof n=="object"&&!Array.isArray(n)){let{message:r,responseBody:o}=n,s=[r,o].filter((i,a,c)=>typeof i=="string"&&i.trim()!==""&&c.indexOf(i)===a);if(s.length>0)return s.join(`
73
73
 
74
- `)}if(typeof t.message=="string"&&t.message)return t.message;try{return JSON.stringify(e)}catch{return}}function sy(e){let t=e.indexOf("{"),n=e.lastIndexOf("}");if(!(t===-1||n===-1||n<=t))return e.slice(t,n+1)}function fS(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 yS(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 ny(e){let t=typeof e.provider=="string"&&e.provider?e.provider:void 0,n=typeof e.code=="string"&&e.code?e.code:void 0,r=typeof e.suggestion=="string"&&e.suggestion?e.suggestion:void 0,o=typeof e.upstream_status=="number"?e.upstream_status:void 0,s=typeof e.request_id=="string"&&e.request_id?e.request_id:void 0,i=yS(e.attempt_failures),a=typeof e.requested_model=="string"&&e.requested_model?e.requested_model:void 0,c=typeof e.resolved_model=="string"&&e.resolved_model?e.resolved_model:void 0;return!t&&!n&&!r&&o===void 0&&!s&&!i?void 0:{message:typeof e.message=="string"&&e.message||fS(e)||"",provider:t,code:n,suggestion:r,upstreamStatus:o,requestId:s,attemptFailures:i,...a?{requestedModel:a}:{},...c?{resolvedModel:c}:{}}}function he(e){if(e==null)return;if(typeof e=="string"){let a=Ms(e),c=It(a)??It(sy(a));return c!==void 0?he(c):void 0}if(typeof e!="object")return;let t=e,n=ny(t),r=typeof t.name=="string"&&typeof t.data=="object";if(n&&!r)return n;let o=t.error;if(o&&typeof o=="object"&&!Array.isArray(o)){let a=ny(o);if(a)return a}let s=t.data;if(s&&typeof s.responseBody=="string"){let a=It(s.responseBody);if(a!==void 0){let c=he(a);if(c)return c}}if(s&&typeof s.message=="string"){let a=he(s.message);if(a)return a}let i=t.cause;if(i&&typeof i=="object"){let a=i.body;if(a!==void 0){let c=he(a);if(c)return c}}return n}var iy={};function H(e,t){for(let n of t)iy[n]=e}H("read",["read"]);H("list",["list","ls"]);H("glob",["glob"]);H("grep",["grep"]);H("write",["write"]);H("edit",["edit","multiedit","morph_edit"]);H("apply_patch",["apply_patch","patch"]);H("bash",["bash"]);H("web_search",["web_search","websearch","image_search"]);H("webfetch",["webfetch","web_fetch","scrape_webpage","scrapewebpage"]);H("media",["image_gen","video_gen"]);H("show",["show","show_user","presentation_gen"]);H("task",["task"]);H("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"]);H("todowrite",["todowrite","todo_write","todoread"]);H("question",["question","ask"]);H("memory",["memory","memory_search","mem_search","ltm_search","get_mem"]);H("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"]);H("automations",["triggers"]);H("skill",["skill"]);H("context",["prune","distill","compress","context_info"]);H("retired",["integration_list","integration_connect","integration_search","integration_actions","integration_run","integration_request","integration_exec"]);var hS=[["pty_","pty"],["agent_","delegate"],["task_","delegate"],["session_","sessions"],["trigger_","automations"],["project_","projects"]];function re(e){let t=e.replace(/^oc[-_]/,"").replace(/-/g,"_"),n=iy[t];if(n)return n;for(let[r,o]of hS)if(t.startsWith(r))return o;return"other"}function Ke(e){for(let t of[e?.filePath,e?.file_path,e?.path])if(typeof t=="string"&&t)return t}var bS=["site","filetype","ext","inurl","allinurl","intitle","allintitle","intext","allintext","inanchor","inbody","before","after","daterange","related","cache","define","link","source","lang","loc","location","imagesize"];function _S(){return new RegExp(`(^|\\s)([-+]?)(${bS.join("|")}):("[^"]*"|\\S+)`,"gi")}function PS(){return/(^|\s)-(?:"[^"]*"|\S+)/g}function xS(){return/(^|\s)(?:OR|AND)(?=\s|$)/g}function SS(e){return e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1):e}function wS(e){return SS(e).replace(/^[a-z]+:\/\//i,"").replace(/^www\./i,"").replace(/\/.*$/,"").trim()}function ay(e){return e.length<=1?e[0]??"":`${e.slice(0,-1).join(", ")} or ${e[e.length-1]}`}function Dr(e){let t=typeof e=="string"?e.trim():"";if(!t)return"";let n=[],r=t.replace(_S(),(o,s,i,a,c)=>{if(!i&&a.toLowerCase()==="site"){let p=wS(c);p&&!n.includes(p)&&n.push(p)}return s});return r=r.replace(PS(),"$1").replace(xS(),"$1").replace(/[()]/g," ").replace(/\s+/g," ").trim(),r?n.length>0?`${r} on ${ay(n)}`:r:n.length>0?ay(n):t}var vS=/\s/,AS=/\w/;function oe(e){return e!==void 0&&vS.test(e)}function fn(e){return e===`
75
- `||e==="\r"||e==="\u2028"||e==="\u2029"}function Os(e){return e!==void 0&&AS.test(e)}function rt(e){let t="";for(let n of e)t+=n.length===1?String.fromCharCode(kS(n.charCodeAt(0))):n;return t}function kS(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 Te(e){let t=e.length;for(;t>0&&e[t-1]==="/";)t--;return e.slice(0,t)}function cy(e){let t=0;for(;t<e.length&&e[t]==="/";)t++;return Te(e.slice(t))}function yn(e,t,n){let r=e.indexOf(t);if(r===-1)return null;let o=e.indexOf(n,r+t.length);return o===-1?null:e.slice(r+t.length,o)}function Ds(e,t){let n=yn(e,`<${t}>`,`</${t}>`);return n===null?null:(n.startsWith(`
74
+ `)}if(typeof t.message=="string"&&t.message)return t.message;try{return JSON.stringify(e)}catch{return}}function vy(e){let t=e.indexOf("{"),n=e.lastIndexOf("}");if(!(t===-1||n===-1||n<=t))return e.slice(t,n+1)}function QS(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 XS(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 Sy(e){let t=typeof e.provider=="string"&&e.provider?e.provider:void 0,n=typeof e.code=="string"&&e.code?e.code:void 0,r=typeof e.suggestion=="string"&&e.suggestion?e.suggestion:void 0,o=typeof e.upstream_status=="number"?e.upstream_status:void 0,s=typeof e.request_id=="string"&&e.request_id?e.request_id:void 0,i=XS(e.attempt_failures),a=typeof e.requested_model=="string"&&e.requested_model?e.requested_model:void 0,c=typeof e.resolved_model=="string"&&e.resolved_model?e.resolved_model:void 0;return!t&&!n&&!r&&o===void 0&&!s&&!i?void 0:{message:typeof e.message=="string"&&e.message||QS(e)||"",provider:t,code:n,suggestion:r,upstreamStatus:o,requestId:s,attemptFailures:i,...a?{requestedModel:a}:{},...c?{resolvedModel:c}:{}}}function xe(e){if(e==null)return;if(typeof e=="string"){let a=qs(e),c=$t(a)??$t(vy(a));return c!==void 0?xe(c):void 0}if(typeof e!="object")return;let t=e,n=Sy(t),r=typeof t.name=="string"&&typeof t.data=="object";if(n&&!r)return n;let o=t.error;if(o&&typeof o=="object"&&!Array.isArray(o)){let a=Sy(o);if(a)return a}let s=t.data;if(s&&typeof s.responseBody=="string"){let a=$t(s.responseBody);if(a!==void 0){let c=xe(a);if(c)return c}}if(s&&typeof s.message=="string"){let a=xe(s.message);if(a)return a}let i=t.cause;if(i&&typeof i=="object"){let a=i.body;if(a!==void 0){let c=xe(a);if(c)return c}}return n}var ky={};function V(e,t){for(let n of t)ky[n]=e}V("read",["read"]);V("list",["list","ls"]);V("glob",["glob"]);V("grep",["grep"]);V("write",["write"]);V("edit",["edit","multiedit","morph_edit"]);V("apply_patch",["apply_patch","patch"]);V("bash",["bash"]);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 JS=[["pty_","pty"],["agent_","delegate"],["task_","delegate"],["session_","sessions"],["trigger_","automations"],["project_","projects"]];function ae(e){let t=e.replace(/^oc[-_]/,"").replace(/-/g,"_"),n=ky[t];if(n)return n;for(let[r,o]of JS)if(t.startsWith(r))return o;return"other"}function Ve(e){for(let t of[e?.filePath,e?.file_path,e?.path])if(typeof t=="string"&&t)return t}var ZS=["site","filetype","ext","inurl","allinurl","intitle","allintitle","intext","allintext","inanchor","inbody","before","after","daterange","related","cache","define","link","source","lang","loc","location","imagesize"];function ew(){return new RegExp(`(^|\\s)([-+]?)(${ZS.join("|")}):("[^"]*"|\\S+)`,"gi")}function tw(){return/(^|\s)-(?:"[^"]*"|\S+)/g}function nw(){return/(^|\s)(?:OR|AND)(?=\s|$)/g}function rw(e){return e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1):e}function ow(e){return rw(e).replace(/^[a-z]+:\/\//i,"").replace(/^www\./i,"").replace(/\/.*$/,"").trim()}function Ry(e){return e.length<=1?e[0]??"":`${e.slice(0,-1).join(", ")} or ${e[e.length-1]}`}function Br(e){let t=typeof e=="string"?e.trim():"";if(!t)return"";let n=[],r=t.replace(ew(),(o,s,i,a,c)=>{if(!i&&a.toLowerCase()==="site"){let p=ow(c);p&&!n.includes(p)&&n.push(p)}return s});return r=r.replace(tw(),"$1").replace(nw(),"$1").replace(/[()]/g," ").replace(/\s+/g," ").trim(),r?n.length>0?`${r} on ${Ry(n)}`:r:n.length>0?Ry(n):t}var sw=/\s/,iw=/\w/;function ce(e){return e!==void 0&&sw.test(e)}function wn(e){return e===`
75
+ `||e==="\r"||e==="\u2028"||e==="\u2029"}function Bs(e){return e!==void 0&&iw.test(e)}function pt(e){let t="";for(let n of e)t+=n.length===1?String.fromCharCode(aw(n.charCodeAt(0))):n;return t}function aw(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 $e(e){let t=e.length;for(;t>0&&e[t-1]==="/";)t--;return e.slice(0,t)}function Cy(e){let t=0;for(;t<e.length&&e[t]==="/";)t++;return $e(e.slice(t))}function An(e,t,n){let r=e.indexOf(t);if(r===-1)return null;let o=e.indexOf(n,r+t.length);return o===-1?null:e.slice(r+t.length,o)}function Gs(e,t){let n=An(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 js(e,t,n=0){let r=e.indexOf(`<${t}`,n);if(r===-1)return null;let o=e.indexOf(">",r+1+t.length);return o===-1?null:{open:r,end:o}}function ly(e,t){let n=js(e,t);return n?e.slice(n.open+1+t.length,n.end):null}function uy(e,t){let n=js(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 py(e,t){let n=`</${t}>`,r="",o=0;for(;;){let s=js(e,t,o);if(!s)break;let i=e.indexOf(n,s.end+1);if(i===-1)break;r+=e.slice(o,s.open),o=i+n.length}return r+e.slice(o)}function dy(e,t,n){let r=[];for(let o of e.split(/[\n\r\u2028\u2029]/)){let s=0;for(;;){let i=o.indexOf(t,s);if(i===-1)break;let a=o.indexOf(n,i+t.length);if(a===-1)break;r.push(o.slice(i+t.length,a)),s=a+n.length}}return r}function hn(e){let t=e.trimEnd();if(!t.endsWith("}"))return null;let n=t.indexOf(":");for(;n!==-1;){let r=n+1;for(;r<t.length&&oe(t[r]);)r++;if(t[r]==="{")return t.slice(r);n=t.indexOf(":",n+1)}return null}function gy(e,t,n){let r=rt(t),o=rt(n);for(let s of rt(e).split(/[\n\r\u2028\u2029]/)){let i=s.indexOf(r);if(i!==-1&&s.lastIndexOf(o)>=i+r.length)return!0}return!1}function my(e,t){let n=rt(e),r=t.map(rt),o=e.length,s=c=>{let p=c;for(;p<o&&oe(e[p]);)p++;return p},i=c=>{for(let p=c;p<o;p++)if(fn(e[p]))return p+1;return-1},a=0;for(;a!==-1&&a<=o;){let c=s(a);if(c>=o)return null;let p=r.find(d=>n.startsWith(d,c));if(p!==void 0){let d=s(c+p.length);if(e[d]===":"){let g=s(d+1);if(g<o){let m=g;for(;m<o&&!fn(e[m]);)m++;for(;m>g+1&&oe(e[m-1]);)m--;return e.slice(g,m)}for(let m=o-1;m>d;m--)if(!fn(e[m]))return e[m];return null}}a=i(c)}return null}function fy(e){let t=e.length,n=new Array(t+1);n[0]=0;for(let a=1;a<=t;a++)n[a]=oe(e[a-1])?n[a-1]:a;let r=new Array(t+1).fill(-1);for(let a=t-1;a>=0;a--){if(r[a]=r[a+1],e[a]!=="\u2014"||!oe(e[a-1]))continue;let c=a+1;if(oe(e[c])){for(;c<t&&oe(e[c]);)c++;Os(e[c])&&(r[a]=a)}}let o=new Array(t+1);o[0]=0;for(let a=0;a<t;a++)o[a+1]=o[a]+(fn(e[a])?1:0);let s=(a,c)=>o[c]===o[a],i=a=>{let c=a+1;for(;oe(e[c]);)c++;let p=c;for(;p<t&&Os(e[p]);)p++;return e.slice(c,p)};for(let a=e.indexOf("**task-");a!==-1;a=e.indexOf("**task-",a+1)){let c=a+7;for(;c<t&&/[a-z0-9]/.test(e[c]);)c++;if(c===a+7||e[c]!=="*"||e[c+1]!=="*")continue;let p=c+2,d=p;for(;d<t&&oe(e[d]);)d++;if(d!==p){if(d<t&&d+2<=t){let g=r[d+2]??-1;if(g!==-1){let m=Math.max(d+1,n[g]);if(s(d,m))return{id:e.slice(a+2,c),title:e.slice(d,m),status:i(g)}}}if(d<t&&r[d]===d){for(let g=d-2;g>=p+1;g--)if(!fn(e[g]))return{id:e.slice(a+2,c),title:e[g],status:i(d)}}}}return null}function yy(e){let t=(i,a)=>i.slice(a,a+6).toLowerCase()==="error:",n=0;for(;;){let i=n;for(;i<e.length&&oe(e[i]);)i++;if(!t(e,i))break;for(i+=6;i<e.length&&oe(e[i]);)i++;n=i}let r=e.slice(n),o="",s=0;for(;s<r.length;){if(t(r,s)&&(s===0||!Os(r[s-1]))){let i=s,a=0;for(;t(r,i);){for(i+=6;i<r.length&&oe(r[i]);)i++;a++}if(a>=2){s=i;continue}}o+=r[s],s++}return o}function hy(e,t){let n=t?"![":"[",r="",o=0,s=-2,i=-2;for(let a=e.indexOf(n);a!==-1;){let c=a+n.length;if(s<c&&(s=e.indexOf("]",c)),s===-1)break;let p=s;if(e[p+1]!=="("){a=e.indexOf(n,p+1);continue}if(i<p+2&&(i=e.indexOf(")",p+2)),i===-1)break;r+=e.slice(o,a)+(t?" ":e.slice(c,p)),o=i+1,a=e.indexOf(n,o)}return r+e.slice(o)}function by(e){return hy(e,!0)}function _y(e){return hy(e,!1)}function RS(e,t){let n=e.slice(t,t+8).toLowerCase();return n.startsWith("http://")||n.startsWith("https://")}function Py(e,t){let n=rt(e),r=rt(t),o=e.length,s=i=>{let a=i;for(;a<o&&oe(e[a]);)a++;return a};for(let i=n.indexOf(r);i!==-1;i=n.indexOf(r,i+1)){let a=s(i+r.length);if(e[a]!==":")continue;let c=s(a+1);for(let p=c;p<o;){if(!oe(e[p])){p++;continue}let d=s(p);if(RS(e,d))return e.slice(c,p);p=d}return e.slice(c)}return null}var IS=new Set(["read","glob","grep","list"]);function z(e){return e.replace(/^oc-/,"").replace(/-/g,"_")}function sL(e){return IS.has(re(e))}function iL(e){let t=0,n=0,r=0;for(let o of e){let s=re(o.tool);s==="read"?t++:s==="glob"||s==="grep"?n++:s==="list"&&r++}return{read:t,search:n,list:r}}function $s(e){if(!e)return"";let t=Te(e.replace(/\\/g,"/")),n=t.lastIndexOf("/");return n>=0?t.slice(n+1):t}function jr(e,t=60){if(!e)return"";let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t)}\u2026`:n}function Us(e){let n=(e.state??{}).input??{};switch(z(e.tool)){case"read":case"edit":case"write":case"morph_edit":{let s=n.filePath??n.file_path??n.path;return s?$s(String(s)):""}case"glob":return n.pattern?String(n.pattern):"";case"grep":{let s=n.pattern??n.query,i=n.path??n.include;return s&&i?`"${jr(String(s),40)}" in ${$s(String(i))}`:s?`"${jr(String(s),60)}"`:""}case"list":return n.path?$s(String(n.path)):"";case"bash":return jr(String(n.command??""),80);default:break}let o=["description","query","url","filePath","file_path","path","pattern","name","prompt"];for(let s of o){let i=n[s];if(typeof i=="string"&&i.length>0)return jr(s==="query"&&Dr(i)||i,60)}return""}var CS={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 aL(e,t={}){let n={...CS,...t},r=z(e.tool),o=Us(e);switch(r){case"read":return{title:n.read,subtitle:o};case"glob":case"grep":return{title:n.search,subtitle:o};case"list":return{title:n.list,subtitle:o};case"bash":return{title:n.shell,subtitle:o};case"edit":case"morph_edit":return{title:n.edit,subtitle:o};case"write":return{title:n.write,subtitle:o};case"webfetch":case"web_fetch":return{title:n.fetch,subtitle:o};case"websearch":case"web_search":return{title:n.webSearch,subtitle:o};case"scrape":case"scrape_webpage":return{title:n.scrape,subtitle:o};case"apply_patch":return{title:n.applyPatch,subtitle:o};case"task":return{title:n.task,subtitle:o};case"session_spawn":case"session_start_background":return{title:n.worker,subtitle:o};case"project_select":case"project_list":return{title:n.workspace,subtitle:o};default:return{title:r.replace(/_/g," ").replace(/\b\w/g,i=>i.toUpperCase()),subtitle:o}}}function Ee(e){return e.type==="text"}function Me(e){return e.type==="reasoning"}function J(e){return e.type==="tool"}function Sy(e){return e.type==="file"}function dL(e){return e.type==="agent"}function gL(e){return e.type==="compaction"}function mL(e){return e.type==="snapshot"}function fL(e){return e.type==="patch"}function yL(e){return e.type==="step-start"||e.type==="step-finish"}function hL(e){if(Ee(e)||Me(e))return e.text}function bL(e){if(!Sy(e))return!1;let t=e.mime;return t.startsWith("image/")||t==="application/pdf"}function _L(e){let t=[],n=[];for(let r of e)Sy(r)?t.push(r):n.push(r);return{attachments:t,stickyParts:n}}function PL(e,t){let n=[];return e?.tool&&n.push(e.tool),t?.tool&&n.push(t.tool),n}function xL(e,t,n){return n.some(r=>r.messageID===t&&r.callID===e.callID)}var TS=new Set(["todoread","context_info"]);function ES(e){return!TS.has(e.tool)}var MS=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 wy(e){let t=e.tool||"";if(t.startsWith("oc-"))return;let n=re(t);if(n==="task"||n==="delegate"){let r=e.state?.metadata?.sessionId;if(typeof r=="string"&&r)return r;if(n==="task"&&e.state?.status==="error")return e.state.error?.match(/\btask_id:\s*(ses_[A-Za-z0-9]+)/)?.[1]}return OS(t,e.state)}function OS(e,t){let n=z(e);if(MS.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 SL(e){if(e)for(let t=e.length-1;t>=0;t--){let n=e[t]?.info;if(n?.role==="assistant"&&n.error)return de(n.error)}}function wL(e){let t=[];for(let n of e)if(n.info.role==="assistant")for(let r of n.parts)J(r)&&ES(r)&&t.push(r);return t}function vL(e,t={}){switch(z(e)){case"webfetch":return{icon:"globe",title:"Web Fetch",subtitle:t.url};case"websearch":case"web_search":return{icon:"search",title:"Web Search",subtitle:t.query};case"scrape_webpage":return{icon:"globe",title:"Scrape",subtitle:t.urls?.split?.(",")[0]};case"image_search":return{icon:"image",title:"Image Search",subtitle:t.query};case"image_gen":return{icon:"image",title:"Image Gen",subtitle:t.prompt?.slice?.(0,40)};case"video_gen":return{icon:"cpu",title:"Video Gen",subtitle:t.prompt?.slice?.(0,40)};case"presentation_gen":{let n=t.action||"";return{icon:"presentation",title:{create_slide:"Create Slide",list_slides:"List Slides",preview:"Preview",export_pdf:"Export PDF",export_pptx:"Export PPTX"}[n]||"Presentation",subtitle:t.slide_title||t.presentation_name}}case"show":case"show_user":return{icon:"globe",title:"Output",subtitle:t.title||t.description};case"task":return{icon:"square-kanban",title:`Agent (${t.subagent_type||"task"})`,subtitle:US(t)};case"session_spawn":case"session_start_background":return{icon:"square-kanban",title:`Worker (${t.agent||"KortixWorker"})`,subtitle:t.description||t.prompt?.slice(0,60)};case"apply_patch":return{icon:"file-pen",title:"Patch",subtitle:t.files?.length?`${t.files.length} file${t.files.length>1?"s":""}`:void 0};case"todoread":return{icon:"check-square",title:"Todos (read)"};case"prune":return{icon:"scissors",title:"DCP Prune",subtitle:t.reason};case"distill":return{icon:"scissors",title:"DCP Distill"};case"compress":return{icon:"scissors",title:"DCP Compress",subtitle:t.topic};case"context_info":return{icon:"scissors",title:"Context Info"};case"session_read":return{icon:"glasses",title:`Session Read (${t.mode||"summary"})`,subtitle:t.session_id?.slice(-12)};case"session_search":return{icon:"search",title:"Session Search",subtitle:t.query};case"session_message":return{icon:"message-circle",title:"Message \u2192 Session",subtitle:t.session_id?.slice(-12)};case"session_lineage":return{icon:"list-tree",title:"Session Lineage",subtitle:t.session_id?.slice(-12)};case"session_list_background":case"session_list_spawned":return{icon:"layers",title:"Background Sessions",subtitle:t.project||"all"};case"session_stats":return{icon:"layers",title:"Session Stats",subtitle:t.session_id?.slice(-12)||"current"};case"session_list":return{icon:"list",title:"Session List",subtitle:t.search};case"session_get":return{icon:"book-open",title:"Session Get",subtitle:t.session_id?.slice(-12)};case"session_context":return{icon:"book-open",title:"Session Context",subtitle:t.session_id?.slice(-12)};case"project_delete":return{icon:"trash-2",title:"Workspace Delete Disabled",subtitle:t.project};case"project_list":return{icon:"folder",title:"Projects"};case"project_get":case"project_update":return{icon:"folder",title:"Project",subtitle:t.name||t.project};case"project_select":return{icon:"folder",title:"Project Select",subtitle:t.project};case"project_create":return{icon:"folder-plus",title:"Project Create",subtitle:t.name};case"triggers":case"trigger_create":return{icon:"clock",title:"Create Trigger",subtitle:t.name};case"trigger_list":return{icon:"clock",title:"List Triggers"};case"trigger_get":return{icon:"clock",title:"Trigger Details",subtitle:t.name||t.id};case"trigger_delete":return{icon:"clock",title:"Delete Trigger",subtitle:t.name||t.id};case"trigger_update":return{icon:"clock",title:"Update Trigger",subtitle:t.name||t.id};case"trigger_test":return{icon:"clock",title:"Test Trigger",subtitle:t.name||t.id};case"trigger_pause":return{icon:"clock",title:"Pause Trigger",subtitle:t.name||t.id};case"trigger_resume":return{icon:"clock",title:"Resume Trigger",subtitle:t.name||t.id};case"agent_spawn":return{icon:"cpu",title:`Agent (${t.agent_type||"worker"})`,subtitle:t.description};case"agent_message":return{icon:"message-circle",title:"Agent Message",subtitle:t.agent_id};case"agent_stop":return{icon:"ban",title:"Agent Stop",subtitle:t.agent_id};case"agent_status":return{icon:"layers",title:"Agent Status"};case"agent_task":return{icon:"check-square",title:"Create Task",subtitle:t.title};case"agent_task_update":return{icon:"check-square",title:"Update Task",subtitle:t.task_id};case"agent_task_list":return{icon:"check-square",title:"List Tasks"};case"agent_task_get":return{icon:"check-square",title:"Task Details",subtitle:t.task_id};case"task_create":return{icon:"plus",title:"Create Task",subtitle:t.title};case"task_list":return{icon:"list",title:"Tasks",subtitle:t.status||"all"};case"task_update":return{icon:"refresh-cw",title:"Update Task",subtitle:t.id};case"task_done":return{icon:"check-circle",title:"Task Done",subtitle:t.id};case"task_delete":return{icon:"trash-2",title:"Delete Task",subtitle:t.id};case"pty_spawn":return{icon:"terminal",title:"Spawn",subtitle:t.title||t.command};case"pty_read":return{icon:"terminal",title:"Terminal Output",subtitle:t.id};case"pty_write":case"pty_input":return{icon:"terminal",title:"Terminal Input",subtitle:t.id};case"pty_kill":return{icon:"terminal",title:"Kill Process",subtitle:t.id};default:return DS(e,t)}}function DS(e,t){switch(re(e)){case"read":return{icon:"glasses",title:"Read",subtitle:jS(Ke(t))};case"list":return{icon:"list",title:"List",subtitle:$S(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:xy(Ke(t))};case"write":return{icon:"file-pen",title:"Write",subtitle:xy(Ke(t))};case"todowrite":return{icon:"check-square",title:"Todos"};case"question":return{icon:"message-circle",title:"Questions"};default:return{icon:"cpu",title:e}}}function jS(e){if(!e)return;let t=e.split("/");return t[t.length-1]||e}function xy(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 $S(e){if(!e)return;let t=e.lastIndexOf("/");if(!(t<0))return e.slice(0,t)||"/"}function AL(e,t){if(!t)return e;if(e.startsWith(t)){let n=e.slice(t.length);return n.startsWith("/")?n.slice(1):n}return e}function bn(e,t=120){if(typeof e!="string")return"";let n=e.split(`
78
- `).map(r=>r.trim()).find(Boolean);return n?n.length>t?`${n.slice(0,t).trim()}\u2026`:n:""}function US(e){let t=bn(e.description);if(t)return t;let n=bn(e.title,80);if(n)return n;let r=bn(e.message);if(r)return r;let o=bn(e.prompt);if(o)return o;let s=bn(e.agent_id,40);return s?`Agent ${s}`:"Worker task"}function kL(e,t){return!e||!t?[]:(e[t]??[]).filter(r=>r.severity===1).slice(0,3)}function RL(e,t){return e.find(n=>n.tool?.callID===t)}function IL(e,t){return e.find(n=>n.tool?.callID===t)}var FS=/\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 CL(e){return e?e.replace(FS,""):""}var LS={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"},NS={read:"files",list:"files",glob:"search",grep:"search",write:"edit",edit:"edit",apply_patch:"edit",bash:"shell",pty:"shell",web_search:"web",webfetch:"web",media:"web",show:"task",task:"task",delegate:"task",sessions:"task",todowrite:"task",question:"task",automations:"task",projects:"task",memory:"other",connectors:"other",skill:"other",context:"other",retired:"other",other:"other"};function KS(e){return e.replace(/^oc[-_]/,"")}function vy(e){return KS(e).replace(/-/g,"_")}function Ay(e){return vy(e).split(/[_\s]+/).filter(Boolean).map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" ")}function Fs(e){return{label:LS[vy(e)]??Ay(e),category:NS[re(e)]}}var qS=256*1024;function GS(e){switch(e.status){case"pending":return"pending";case"running":return"running";case"completed":return"done";case"error":return"error";default:return e}}function BS(e){if(e===void 0)return{};if(e.length>qS)return{outputText:e};try{return{outputParsed:JSON.parse(e),outputText:e}}catch{return{outputText:e}}}function WS(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e,n=t.success===!1,r=t.error,o=typeof r=="string"&&r.length>0||typeof r=="object"&&r!==null;if(!(!n&&!o))return o?de(r):typeof t.message=="string"&&t.message?t.message:"Tool reported failure"}var Z=e=>typeof e=="string"?e:void 0,$r=e=>typeof e=="number"?e:void 0,Ur=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:void 0;function Ls(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}var HS=new Set(["add","update","delete","move"]);function VS(e,t,n){if(e==="apply_patch"){let c=(Array.isArray(n.files)?n.files:[]).flatMap(p=>{let d=Ur(p),g=d&&(Z(d.relativePath)||Z(d.filePath));if(!d||!g)return[];let m=Z(d.type);return[Ls({path:g,type:m&&HS.has(m)?m:void 0,before:Z(d.before),after:Z(d.after),patch:Z(d.patch)??Z(d.diff),additions:$r(d.additions),deletions:$r(d.deletions),movePath:Z(d.movePath)})]});return c.length?c:void 0}let r=Ke(t);if(!r)return;if(e==="read")return[{path:r}];if(e==="write")return[Ls({path:r,after:Z(t.content)})];if(e!=="edit")return;let o=Ur(n.filediff),s=o?void 0:Z(n.patch),i=s?zS(s):void 0;return[Ls({path:r,before:Z(o?.before)??Z(t.oldString),after:Z(o?.after)??Z(t.newString),patch:s,additions:$r(o?.additions)??i?.additions,deletions:$r(o?.deletions)??i?.deletions})]}function zS(e){let t=0,n=0;for(let r of e.split(`
79
- `))r.startsWith("+")&&!r.startsWith("+++")?t++:r.startsWith("-")&&!r.startsWith("---")&&n++;return{additions:t,deletions:n}}function YS(e){let t=e.answers;if(Array.isArray(t))return t.map(n=>Array.isArray(n)?n.filter(r=>typeof r=="string"):[])}function ky(e,t){let n="title"in t?t.title:void 0,r=t.status==="completed"?t.output:void 0,{outputParsed:o,outputText:s}=BS(r),i=GS(t),a=t.status==="error"?t.error:void 0;if(i==="done"){let m=WS(o);m&&(i="error",a=m)}let c=re(e),p=t.input??{},d="metadata"in t&&Ur(t.metadata)||{},g=Ur(d.diagnostics);return{name:e,kind:c,title:n||Fs(e).label,status:i,input:t.input,output:r,outputParsed:o,outputText:s,error:a,files:VS(c,p,d),diff:Z(d.patch)??Z(d.diff),diagnostics:g,answers:c==="question"?YS(d):void 0,childSessionId:wy({tool:e,state:t})}}function UL(e){return ky(e.tool,e.state)}function QS(e){return{kind:"text",id:e.id,text:e.text,synthetic:!!e.synthetic}}function XS(e){return{kind:"reasoning",id:e.id,text:e.text}}function JS(e){return{kind:"tool",id:e.id,tool:ky(e.tool,e.state)}}function ZS(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 ew(e){return{kind:"subtask",id:e.id,description:e.description,agent:e.agent,prompt:e.prompt,model:e.model}}function tw(e){return{kind:"patch",id:e.id,hash:e.hash,files:e.files,fileCount:e.files.length}}function nw(e){return{kind:"snapshot",id:e.id,snapshot:e.snapshot}}function rw(e){return{kind:"agent",id:e.id,name:e.name}}function ow(e){return{kind:"retry",id:e.id,attempt:e.attempt,message:de(e.error),createdAt:e.time.created}}function sw(e){return{kind:"compaction",id:e.id,auto:e.auto,overflow:!!e.overflow,tailStartId:e.tail_start_id}}function iw(e){return{kind:"step",id:e.id,phase:"start",snapshot:e.snapshot}}function aw(e){return{kind:"step",id:e.id,phase:"finish",snapshot:e.snapshot,reason:e.reason,cost:e.cost,tokens:e.tokens}}function Ry(e){switch(e.type){case"text":return QS(e);case"reasoning":return XS(e);case"tool":return JS(e);case"file":return ZS(e);case"subtask":return ew(e);case"patch":return tw(e);case"snapshot":return nw(e);case"agent":return rw(e);case"retry":return ow(e);case"compaction":return sw(e);case"step-start":return iw(e);case"step-finish":return aw(e);default:return{kind:"unknown",raw:e}}}function cw(e){if(!e)return;let t=typeof e=="object"&&"name"in e&&typeof e.name=="string"?e.name:"Error",n=he(e);return{name:t,message:n?.message||de(e),provider:n?.provider,code:n?.code,suggestion:n?.suggestion,upstreamStatus:n?.upstreamStatus,requestId:n?.requestId,attemptFailures:n?.attemptFailures}}function lw(e){switch(e.kind){case"text":case"reasoning":return e.text.trim().length>0;case"step":return!1;default:return!0}}function uw(e){let t=e.parts.map(Ry),n=e.info.role==="assistant"?e.info.error:void 0,r=cw(n),o=!r&&!t.some(lw);return{parts:t,error:r,isEmpty:o}}var Ns=Fe+BigInt(1),Iy=Ns/BigInt(2);function Fr(e){return BigInt(Math.trunc(e))*Jt}function Ks(e,t){let r=t-(t&Fe)+e;return r-t>Iy?r-=Ns:t-r>Iy&&(r+=Ns),r}function Cy(e,t){let n=St(e.info.id)??BigInt(0),r=e.info.time?.created;if(typeof r!="number")return Ks(n,t);let o=Fr(r),s=Ks(n,o);return(s>o?s-o:o-s)<=Ze?s:o}function Ty(e){return St(e)===null?1:0}function Ey(e,t){return e<t?-1:e>t?1:0}function BL(e,t){return My(e,t,Fr(Date.now()))}function pw(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 Fr(t??Date.now())}function My(e,t,n){let r=Ty(e.info.id),o=Ty(t.info.id);if(r!==o)return r-o;if(r===0){let a=Cy(e,n),c=Cy(t,n);return a!==c?a<c?-1:1:Ey(e.info.id,t.info.id)}let s=typeof e.info.time?.created=="number"?e.info.time.created:null,i=typeof t.info.time?.created=="number"?t.info.time.created:null;return s===null&&i===null?0:s===null?1:i===null?-1:s!==i?s<i?-1:1:Ey(e.info.id,t.info.id)}function WL(e,t){let n=new Map([...t?.pendingMessageIds??[]].map((d,g)=>[d,g])),r=pw(e),o=[...e].sort((d,g)=>{let m=n.get(d.info.id),f=n.get(g.info.id);return m!==void 0&&f!==void 0?m-f:m!==void 0?1:f!==void 0?-1:My(d,g,r)}),s=[],i=new Map;for(let d of o)if(d.info.role==="user"){if(i.has(d.info.id))continue;let g={userMessage:d,assistantMessages:[]};s.push(g),i.set(d.info.id,g)}let a=null,c=[],p=[];for(let d of o){if(d.info.role==="user"){a=i.get(d.info.id)??null;continue}if(d.info.role!=="assistant")continue;let g=d.info,m=g.tokens;if(!(!g.error&&d.parts.length===0&&m?.input===0&&m.output===0&&m.reasoning===0)){if(g.parentID){let f=i.get(g.parentID);if(f){f.assistantMessages.push(d);continue}}if(a){a.assistantMessages.push(d);continue}if(g.parentID){let f=c[c.length-1];f&&f.userMessage.info.id===g.parentID?f.assistantMessages.push(d):c.push({userMessage:gw(g.parentID,d),assistantMessages:[d],partial:!0});continue}p.push(d)}}if(p.length>0){let d=s[0]??c[0];if(d)d.assistantMessages.unshift(...p);else{let[g,...m]=p;s.push({userMessage:g,assistantMessages:m})}}return c.length>0?[...c,...s]:s}var _n=new Map,dw=256;function gw(e,t){let n=t.info,r=n.time?.created,o=`${n.sessionID??""}|${e}|${r??""}`,s=_n.get(o);if(s)return s;let i={info:{id:e,role:"user",...n.sessionID?{sessionID:n.sessionID}:{},...typeof r=="number"?{time:{created:r}}:{}},parts:[]};if(_n.size>=dw){let a=_n.keys().next().value;a!==void 0&&_n.delete(a)}return _n.set(o,i),i}function HL(e){let t=[];for(let n of e.assistantMessages)for(let r of n.parts)t.push({part:r,message:n});return t}function VL(e){for(let t=e.length-1;t>=0;t--){let n=e[t].part;if(Ee(n)&&n.text?.trim())return n}}function zL(e){return e.some(({part:t})=>t.type==="tool"||t.type==="compaction"||t.type==="snapshot"||t.type==="patch")}function YL(e,t,n){if(n)return[];let r=[];for(let o of e.assistantMessages)for(let s of o.parts){if(!J(s))continue;let i=s,a=i.state?.metadata?.answers;i.tool==="question"&&(a?.length??0)>0&&r.push({part:s,message:o})}return r}function QL(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 XL(e){let t=e-6e4;return(n,r)=>{let o=n.time.updated??n.time.created,s=r.time.updated??r.time.created,i=o>t,a=s>t;return i&&a?n.id<r.id?-1:n.id>r.id?1:0:i&&!a?-1:!i&&a?1:s-o}}function mw(e,t){let n=e.get(t);if(!n||n.length===0)return[];let r=[];for(let o of n)r.push(o),r.push(...mw(e,o));return r}function fw(e){if(!e||typeof e!="object")return!1;let t=e.data;return!!t&&typeof t=="object"&&t.isRetryable===!0}function ZL(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&&fw(n.error)}return!1}function Lr(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Dy(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 nN(e){return!!e&&(Dy(e)||Pw(e)!==null)}function jy(e){let t=Oy.get(e);if(t&&t.state===e.state)return t.outcome;let n=yw(e);return Oy.set(e,{state:e.state,outcome:n}),n}var Oy=new WeakMap;function yw(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(Dy(n))return"failed";let r=hw(n);return r===void 0?"ok":bw(r)?"failed":_w(r)}function hw(e){try{return JSON.parse(e)}catch{return}}function bw(e){return Lr(e)&&e.success===!1&&typeof e.error=="string"}function _w(e){let t=Lr(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 Pw(e){let t=e.trim();if(!t)return null;let n;try{n=JSON.parse(t)}catch{return null}if(!Lr(n)||n.success!==!1||typeof n.error!="string")return null;let r={errorSummary:n.error.trim(),hint:typeof n.hint=="string"?n.hint.trim():void 0},o=hn(r.errorSummary);if(o===null)return r;try{let s=JSON.parse(o);typeof s.message=="string"&&s.message.trim()&&(r.nestedMessage=s.message.trim()),typeof s.status=="number"&&(r.status=s.status),typeof s.error=="boolean"&&(r.nestedError=s.error)}catch{}return r}function rN(e){return yy(e).replace(/\s+/g," ").trim()||e.trim()}function oN(e){let t=e.trim();if(!t)return null;let n;try{n=JSON.parse(t)}catch{return null}if(!Lr(n))return null;let r=n.success,o=n.error,s=n.hint;if(r!==!1||typeof o!="string")return null;let i=[];i.push(o.trim());let a=hn(o);if(a!==null)try{let p=JSON.parse(a).message;typeof p=="string"&&p.trim()&&i.push(`Details: ${p.trim()}`)}catch{}return typeof s=="string"&&s.trim()&&i.push(`Hint: ${s.trim()}`),i.join(`
80
-
81
- `)}var xw=new Set(["get_mem","memory_search","mem_search","ltm_search","dcp_compress","dcp_distill","dcp_prune","prune","distill","compress","context_info"]),Sw={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 ww(e,t){if(e==="filePath"||e==="path"||e==="file"){let n=t.split("/");return n[n.length-1]||t}return e==="query"&&Dr(t)||t}function vw(e,t){if(!t||typeof e!="object"||e===null)return;let n=e;for(let r of t){let o=n[r];if(typeof o=="string"&&o.trim())return ww(r,o.trim())}}function $y(e){if(Me(e))return{verb:"Thought",running:"Thinking",object:void 0,tier:"reasoning"};if(!J(e))return{verb:"Used",running:"Using",object:void 0,tier:"primary"};let t=pe(e.tool),n=Sw[t],r=e.state?.input;return n?{verb:n.verb,running:n.running,object:vw(r,n.objectKeys),tier:xw.has(t)?"plumbing":"primary"}:{verb:"Used",running:"Using",object:t,tier:"primary"}}function gN(e){let t=0,n=0,r=!1,o=!1;for(let s of e){if($y(s).tier==="plumbing"){r=!0;continue}if(Me(s)){if(!s.text?.trim())continue;o||(o=!0,t+=1);continue}o=!1,t+=1,J(s)&&jy(s)!=="ok"&&(n+=1)}return{total:t,failed:n,completed:t-n,hasPlumbing:r}}function qs(e){return`${e} ${e===1?"step":"steps"}`}function mN(e,t){let{total:n,failed:r,completed:o,hasPlumbing:s}=e;return t?n===0?"Working":`Working \xB7 ${qs(n)}`:n===0?s?"Housekeeping":"Worked":r===0?`Completed ${qs(n)}`:o===0?`${qs(n)} failed`:`Completed ${o} of ${n} steps \xB7 ${r} failed`}function yN(e){let t=!1,n=!1,r=!1,o=null,s=p=>{let d=p;return d?.summary!==!0?!1:(t=!0,!d.time?.completed&&!d.error&&(r=!0),o==null&&d.error!=null&&(o=d.error),!0)},i=p=>{for(let d of p??[])d.type==="compaction"?(t=!0,n=!0):d.type==="text"&&d.text?.trim()&&(n=!0)},c=(e.userMessage?.parts??[]).some(p=>p.type==="compaction");c&&(t=!0),e.userMessage&&s(e.userMessage.info)&&i(e.userMessage.parts);for(let p of e.assistantMessages)s(p.info),i(p.parts);return c&&e.assistantMessages.length===0&&(r=!0),{isCompaction:t,hasContent:n,inFlight:r,error:o}}function _N(e){let t=(e??"").trimStart();return t.startsWith("{")||t.startsWith("[")}function PN(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 xN(e,t=200){let n=e??"";return n=n.replace(/\\n/g," "),n=by(n),n=_y(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 SN(e){let t=(e??"").trim();if(!t)return null;let n;try{if(n=JSON.parse(t),typeof n=="string")try{n=JSON.parse(n)}catch{return null}}catch{return null}if(!n||typeof n!="object"||Array.isArray(n))return null;let r=n;if(r.success!==!1||typeof r.error!="string"||!r.error.trim())return null;let o=r.error.trim(),s;for(let i=0;i<3;i++){let a=hn(o);if(a===null)break;let c;try{c=JSON.parse(a)}catch{break}if(typeof c.status=="number"&&(s=c.status),typeof c.message=="string"&&c.message.trim())o=c.message.trim();else if(typeof c.error=="string"&&c.error.trim())o=c.error.trim();else break}return{message:o,status:s}}function Pn(e){try{return JSON.parse(`"${e}"`)}catch{return e}}function Gs(e,t=30){if(!e)return[];let n=[],r=new Set,o=(a,c,p)=>{!/^https?:\/\//i.test(c)||r.has(c)||n.length>=t||(r.add(c),n.push({title:a.trim()||c,url:c,snippet:p?.trim()||void 0}))},s=/"title"\s*:\s*"((?:\\.|[^"\\])*)"\s*,\s*"url"\s*:\s*"((?:\\.|[^"\\])*)"(?:\s*,\s*"(?:snippet|content|text)"\s*:\s*"((?:\\.|[^"\\])*)")?/g,i;for(;(i=s.exec(e))!==null;)if(o(Pn(i[1]),Pn(i[2]),i[3]?Pn(i[3]):void 0),n.length>=t)return n;if(n.length===0){let a=/"url"\s*:\s*"((?:\\.|[^"\\])*)"[^{}]{0,400}?"title"\s*:\s*"((?:\\.|[^"\\])*)"/g;for(;(i=a.exec(e))!==null;)if(o(Pn(i[2]),Pn(i[1])),n.length>=t)return n}return n}function Uy(e,t=!1){if(typeof e=="object"&&e!==null)return e;if(typeof e!="string")return null;try{let n=JSON.parse(e);if(typeof n=="string")try{n=JSON.parse(n)}catch{}return typeof n=="object"?n:null}catch{let n=t&&e.trim().replace(/^\uFEFF/,"");if(n&&n!==e)try{return JSON.parse(n)}catch{}return null}}function Nr(e){return e.filter(t=>t.title&&t.url).map(t=>({title:t.title,url:t.url,snippet:t.snippet||t.content||t.text||void 0,author:t.author||void 0,publishedDate:t.publishedDate||t.published_date||void 0}))}function Fy(e){if(!e)return[];let t=Uy(e,!0);if(t?.success===!1)return[];if(Array.isArray(t?.results)&&t.results.length>0){let n=t.results[0];if(n&&typeof n.query=="string"){let r=[];for(let o of t.results)typeof o.query=="string"&&r.push({query:o.query,answer:o.answer||void 0,sources:Array.isArray(o.results)?Nr(o.results):[]});if(r.length>0)return r}else if(n&&(n.title||n.url)){let r=Nr(t.results);if(r.length>0)return[{query:t.query||"",answer:t.answer||void 0,sources:r}]}}if(t?.query&&typeof t.query=="string")return[{query:t.query,answer:t.answer||void 0,sources:Array.isArray(t.results)?Nr(t.results):[]}];if(Array.isArray(t)&&t.length>0&&t[0]&&(t[0].title||t[0].url)){let n=Nr(t);if(n.length>0)return[{query:"",sources:n}]}if(typeof e=="string"){let n=e.split(/(?=^Title: )/m).filter(Boolean),r=[];for(let o of n){let s=o.match(/^Title:\s*(.+)/m),i=o.match(/^URL:\s*(.+)/m),a=o.match(/^Author:\s*(.+)/m),c=o.match(/^Published Date:\s*(.+)/m),p=o.match(/^Text:\s*([\s\S]*?)$/m);s&&i&&r.push({title:s[1].trim(),url:i[1].trim(),snippet:p?.[1]?.trim()||void 0,author:a?.[1]?.trim()||void 0,publishedDate:c?.[1]?.trim()||void 0})}if(r.length>0)return[{query:"",sources:r}]}if(typeof e=="string"){let n=Gs(e);if(n.length>0)return[{query:"",sources:n.map(r=>({title:r.title,url:r.url,snippet:r.snippet}))}]}return[]}function Bs(e){try{return new URL(e).hostname.replace("www.","")}catch{return e}}function kN(e){try{let t=new URL(e).hostname.replace(/^www\./,""),n=t.split(".");return n.length<=2?t:n.slice(-2).join(".")}catch{return Bs(e)}}function RN(e){try{return`https://www.google.com/s2/favicons?domain=${new URL(e).hostname.replace(/^www\./,"")}&sz=128`}catch{return null}}function IN(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 Aw(e){let t=e.urls??e.url;if(typeof t=="string")return t.split(/[\s,]+/).map(n=>n.trim()).filter(n=>/^https?:\/\//i.test(n));if(Array.isArray(t)){let n=[];for(let r of t){if(typeof r!="string")continue;let o=r.trim();/^https?:\/\//i.test(o)&&n.push(o)}return n}return[]}function kw(e,t){if(t.length===0)return[];let n=e.replace(/^Error:\s*/i,"").trim();return t.map(r=>{let o=Py(n,r)?.trim()||n;return{url:r,success:!1,error:o}})}function CN(e,t){let n=Rw(e);if(n?.results?.length)return n.results;let r=typeof e=="string"?e:"";return r.trim()?kw(r,Aw(t)):[]}function Rw(e){if(!e)return null;let t=Uy(e);if(!t)return null;if(t.results&&Array.isArray(t.results))return{total:t.total||t.results.length,successful:t.successful??t.results.filter(n=>n.success!==!1).length,failed:t.failed??t.results.filter(n=>n.success===!1).length,results:t.results.map(n=>({url:n.url||"",success:n.success!==!1,title:n.title||void 0,content:n.content||n.text||n.snippet||void 0,error:n.error||void 0}))};if(typeof e=="string"){let n=Gs(e);if(n.length>0)return{total:n.length,successful:n.length,failed:0,results:n.map(r=>({url:r.url,success:!0,title:r.title||void 0,content:r.snippet||void 0}))}}return null}function Iw(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 Cw={read:"explore",list:"explore",glob:"explore",grep:"explore",write:"edit",edit:"edit",apply_patch:"edit",bash:"run",pty:"run",web_search:"web",webfetch:"web",media:"create",show:"create",task:"delegate",delegate:"delegate",sessions:"sessions",todowrite:"plan",question:"ask",memory:"memory",connectors:"connectors",automations:"automations",projects:"projects",skill:"skills",context:"hidden",retired:"retired",other:"other"};function Ws(e){return Cw[re(e)]}function Kr(e){let t=z(e).replace(/__+/g,"/");return(t.includes("/")?t.slice(t.lastIndexOf("/")+1):t).replace(/_/g," ").trim().replace(/\b\w/g,r=>r.toUpperCase())}var Tw={run:"Terminal",memory:"Memory"};function jN(e){let t=Ws(e);return(t==="hidden"?void 0:Tw[t])??Kr(e)}function xn(e,t,n){return e===1?t:n}function Hs(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 Ky(e){return e.length?Us(e[0]):""}function be(e){return(e.state??{}).input??{}}var Ew={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 Mw(e){let t=z(e.tool);if(t==="agent_task_update"||t==="task_update")switch(be(e).action||""){case"start":return"spawn";case"cancel":return"stop";case"approve":return"done";default:return"message"}return Ew[t]??"message"}function Ly(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 Ow(e){let t=z(e.tool);if(t==="triggers"){let r=be(e).action||"list";return Ly(r)}let n=t.match(/^trigger_(.+)$/);return Ly(n?n[1]:"list")}var Dw={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 jw(e){return Dw[z(e.tool)]??"read"}var $w={project_get:"open",project_list:"open",project_select:"open",project_update:"update",project_create:"create",project_delete:"delete"};function Uw(e){return $w[z(e.tool)]??"open"}function Ct(e){return e.every(t=>t===e[0])}var Fw={view:"read",create:"write",str_replace:"write",insert:"write",rename:"write",delete:"delete"};function Lw(e){if(z(e.tool)!=="memory")return"read";let n=be(e).command;return n&&Fw[n]||"unknown"}var Nw={generate:"Made an image",edit:"Edited an image",upscale:"Upscaled an image",remove_bg:"Removed an image background"},Kw={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 qw(e){let t=Te(e.replace(/\\/g,"/")),n=t.lastIndexOf("/");return n>=0?t.slice(n+1):t}function Gw(e){let t=be(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 Bw(r,60);let o=typeof t.path=="string"?t.path:"";if(o)return qw(o);let s=typeof t.url=="string"?t.url:"";if(s){let i=Iw(s);return i?Bs(i):"a link"}return""}function Bw(e,t=60){let n=e.replace(/\s+/g," ").trim();return n.length>t?n.slice(0,t-1)+"\u2026":n}function Ww(e){let t=be(e).action;return t&&Nw[t]||"Worked on an image"}function Hw(e){let t=be(e).action;return t&&Kw[t]||"Worked on a presentation"}function Vw(e){return e.slice(0,e.indexOf(":"))}var zw={generate:"image:generate",edit:"image:edit",upscale:"image:upscale",remove_bg:"image:remove_bg"},Yw={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 Qw(e){let t=z(e.tool);if(t==="image_gen"){let n=be(e).action;return n&&zw[n]||"image:unknown"}if(t==="video_gen")return"video:create";if(t==="presentation_gen"){let n=be(e).action;return n&&Yw[n]||"presentation:unknown"}return"shown:result"}var Xw=new Set(["create_slide","export_pdf","export_pptx"]);function $N(e){let t=z(e.tool);if(t==="image_gen")return"image";if(t==="video_gen")return"video";if(t==="presentation_gen"){let n=be(e).action;return n?Xw.has(n)?"presentation":null:"presentation"}return null}var Jw={"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`},Ny={image:"image",video:"video",presentation:"presentation",shown:"result"};function Zw(e){let t={image:0,video:0,presentation:0,shown:0};for(let r of e)t[Vw(r)]++;let n=[];return Object.keys(t).forEach(r=>{let o=t[r];o&&n.push(`${o} ${xn(o,Ny[r],`${Ny[r]}s`)}`)}),`Worked on ${Hs(n)}`}function qy(e,t){let n=t.length,r=Ky(t);switch(e){case"explore":{let o=t.filter(s=>z(s.tool)==="read").length;return o===n?`Read ${n} ${xn(n,"file","files")}`:o===0?"Looked through your files":`Looked through your files \xB7 ${o} read`}case"edit":{let o=new Set(t.map(i=>Ke(be(i))).filter(Boolean)).size||n,s=t.every(i=>z(i.tool)==="write")?"Wrote":"Updated";return o===1?r?`${s} ${r}`:`${s} a file`:`${s} ${o} files`}case"run":return n===1?"Ran a command":`Ran ${n} commands`;case"web":{let o=c=>{let p=z(c.tool);return p==="web_search"||p==="websearch"||p==="image_search"},s=t.filter(o).length;if(s===n)return`Searched the web \xB7 ${n} ${xn(n,"query","queries")}`;if(s===0)return`Read ${n} ${xn(n,"page","pages")}`;let i=new Set;for(let c of t)if(o(c)){let p=c.state?.output;for(let d of Fy(p).flatMap(g=>g.sources))d.url&&i.add(d.url)}else{let p=c.state?.input?.url;typeof p=="string"&&p&&i.add(p)}let a=i.size||n;return`Searched and read ${a} ${xn(a,"source","sources")}`}case"create":{if(n===1){let s=t[0],i=z(s.tool);if(i==="image_gen")return Ww(s);if(i==="video_gen")return"Made a video";if(i==="presentation_gen")return Hw(s);let a=Gw(s);return a?`Showed you ${a}`:"Showed you the result"}let o=t.map(Qw);return Ct(o)?Jw[o[0]](n):Zw(o)}case"plan":return n===1?"Planned the work":`Planned the work \xB7 ${n} steps`;case"delegate":{let o=t.map(Mw);if(Ct(o))switch(o[0]){case"spawn":return n===1?"Asked a helper agent":`Worked with ${n} helper agents`;case"message":return n===1?"Sent instructions to a helper agent":`Sent instructions to ${n} helper agents`;case"status":return"Checked on a helper agent";case"stop":return n===1?"Stopped a helper agent":`Stopped ${n} helper agents`;case"done":return n===1?"A helper agent finished a task":`Helper agents finished ${n} tasks`;case"delete":return n===1?"Removed a task":`Removed ${n} tasks`}return n===1?"Worked with a helper agent":`Worked with helper agents \xB7 ${n} steps`}case"sessions":return"Checked earlier work";case"memory":{let o=t.map(Lw);if(Ct(o))switch(o[0]){case"write":return n===1?"Wrote to its memory":`Wrote to its memory \xB7 ${n} updates`;case"delete":return n===1?"Deleted from its memory":`Deleted ${n} things from its memory`;case"read":return"Recalled what you told it before"}return"Worked with its memory"}case"connectors":{let o=t.map(jw);if(Ct(o))switch(o[0]){case"connect":return n===1?r?`Connected to ${r}`:"Connected a connector":`Connected ${n} connectors`;case"call":return n===1?"Used a connector":`Made ${n} connector calls`;case"read":return"Checked your connectors"}return"Worked with your connectors"}case"automations":{let o=t.map(Ow);if(Ct(o))switch(o[0]){case"create":return n===1?"Set up an automation":`Set up ${n} automations`;case"update":return n===1?"Updated an automation":`Updated ${n} automations`;case"delete":return n===1?"Deleted an automation":`Deleted ${n} automations`;case"control":return n===1?"Adjusted an automation":`Adjusted ${n} automations`;case"test":return n===1?"Tested an automation":`Tested ${n} automations`;case"read":return"Checked your automations";case"unknown":return"Worked with your automations"}return"Worked with your automations"}case"projects":{let o=t.map(Uw);if(Ct(o))switch(o[0]){case"delete":return n===1?"Tried to delete a project \u2014 deletion isn't allowed":`Tried to delete ${n} projects \u2014 deletion isn't allowed`;case"create":return n===1?r?`Created ${r}`:"Created a project":`Created ${n} projects`;case"update":return n===1?r?`Updated ${r}`:"Updated your project":`Updated ${n} projects`;case"open":return n===1?r?`Opened ${r}`:"Opened your project":`Opened ${n} projects`}return r?`Worked in ${r}`:"Worked in your project"}case"skills":return n===1?r?`Used the ${r} skill`:"Used a skill":`Used ${n} skills`;case"ask":return"Asked you a question";case"retired":return"Used a connector that has since been removed";case"other":{if(n===1)return`Used ${Kr(t[0].tool)}`;let o=Array.from(new Set(t.map(s=>Kr(s.tool))));return o.length===1?`Used ${o[0]} \xB7 ${n} times`:`Used ${Hs(o)}`}}}function Gy(e,t){let n=Ky(t);switch(e){case"explore":return"Couldn't read your files";case"edit":{if(t.length===1){let r=z(t[0].tool)==="write"?"write":"update";return n?`Couldn't ${r} ${n}`:`Couldn't ${r} a file`}return"Couldn't update some files"}case"run":return"A command failed";case"web":return"Couldn't finish searching the web";case"create":return"Couldn't finish making that";case"plan":return"Couldn't update the plan";case"delegate":return"A helper agent hit a problem";case"sessions":return"Couldn't check earlier work";case"memory":return"Couldn't reach its memory";case"connectors":return"Couldn't reach a connector";case"automations":return"Hit a problem with your automations";case"projects":return"Hit a problem with your project";case"skills":return"Couldn't use a skill";case"ask":return"Couldn't ask you a question";case"retired":return"Used a connector that has since been removed";case"other":{let r=t.filter(i=>i.state?.status==="error"),o=r.length?r:t,s=Array.from(new Set(o.map(i=>Kr(i.tool))));return`Couldn't finish using ${Hs(s)}`}}}function ev(e){return e.some(t=>t.state?.status==="running"||t.state?.status==="pending")?"running":e.some(t=>t.state?.status==="error")?"error":"done"}function tv(e){let t=Number.POSITIVE_INFINITY,n=0;for(let r of e){let o=r.state.time;typeof o?.start=="number"&&(t=Math.min(t,o.start)),typeof o?.end=="number"&&(n=Math.max(n,o.end))}if(!(!Number.isFinite(t)||n<=t))return n-t}function By(e,t){let n=ev(t);return{id:t[0].callID,family:e,label:n==="error"?Gy(e,t):qy(e,t),parts:t,status:n,durationMs:n==="running"?void 0:tv(t)}}function Wy(e){let t=[],n=null,r=[],o=()=>{n&&r.length&&t.push(By(n,r)),n=null,r=[]};for(let s of e){let i=Ws(s.tool);if(i!=="hidden"&&!zo(s)){if(dm(s.tool)){o(),t.push(By(i,[s]));continue}i!==n&&(o(),n=i),r.push(s)}}return o(),t}function nv(e){let t=e.time?.end;return!(typeof t=="number"&&t>0)}function GN(e,t){let n=[],r=null,o=[],s=()=>{if(r&&r.texts.length>0){let{startedAt:a,endedAt:c}=r,p=typeof a=="number"&&typeof c=="number"&&c>a?c-a:void 0;n.push({kind:"thought",key:r.key,texts:r.texts,running:r.running,durationMs:p})}r=null},i=()=>{if(o.length!==0){for(let a of Wy(o))n.push(a.parts.length===1?{kind:"part",key:a.parts[0].id,part:a.parts[0]}:{kind:"group",key:`group-${a.parts[0].id}`,step:a});o=[]}};for(let a of e)if(t(a)!=="plumbing"){if(Me(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=nv(a);continue}if(s(),J(a)){o.push(a);continue}i(),n.push({kind:"part",key:a.id,part:a})}s(),i();for(let a=0;a<n.length-1;a++){let c=n[a];c.kind==="thought"&&(c.running=!1)}return n}var rv=/^(thinking|thought|considering|planning|deciding|weighing|exploring|analy[sz]ing|reasoning|working out|figuring)/i;function ov(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 BN(e){let t=e.flatMap(o=>{let s=ov(o);return s?[s]:[]}).join(" ").trim();return t?rv.test(t)?t:`Thinking about ${/^[A-Z][a-z]/.test(t)?t[0].toLowerCase()+t.slice(1):t}`:"Thinking"}function sv(e){return e?.info?.time??{}}function HN(e){let t=sv(e).created;return typeof t!="number"||!Number.isFinite(t)||t<=0?null:t}var qr=6e4,iv=10080*qr,Hy=1440;function Vy(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 av(e,t){let n=t.getTime()-e.getTime(),r=n/qr,o=(i,a)=>`${i} ${a}${i===1?"":"s"} ago`;if(r<60)return o(Math.round(r),"minute");if(r<Hy)return o(Math.round(r/60),"hour");let s=(n-(Vy(t)-Vy(e)))/qr;return o(Math.round(s/Hy),"day")}function Qy(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 zy=new Map;function cv(e,t){let n={...e,...t.timeZone?{timeZone:t.timeZone}:{}},r=`${t.locale??""}|${JSON.stringify(n)}`,o=zy.get(r);return o||(o=new Intl.DateTimeFormat(t.locale,n),zy.set(r,o)),o}function Gr(e,t,n){return cv(t,n).formatToParts(e).map(r=>r.type==="dayPeriod"?lv(r.value,n):r.value).join("")}function lv(e,t){let n=/^([ap])\.?\s?m\.?$/i.exec(e.trim());return n?`${n[1].toUpperCase()}M`:e.toLocaleUpperCase(t.locale)}function Yy(e,t){return Gr(e,{year:"numeric"},t)}function VN(e,t,n={}){let r=Qy(e);if(!r)return"";let o=i=>Gr(r,{month:"long",day:"numeric",...i?{year:"numeric"}:{}},n);if(t===null)return o(!0);let s=Math.max(0,t-r.getTime());return s<qr?"just now":s<iv?av(r,new Date(t)):o(Yy(r,n)!==Yy(new Date(t),n))}function zN(e,t={}){let n=Qy(e);if(!n)return"";let r=Gr(n,{month:"long",day:"numeric",year:"numeric"},t),o=Gr(n,{hour:"numeric",minute:"2-digit"},t);return`${r} ${o}`}function JN(e,t={}){let n=[],r=[],o=()=>{r.length>0&&(n.push({kind:"burst",parts:r}),r=[])};for(let s of e)if(!gm(s)){if(Ee(s)){o(),n.push({kind:"text",part:s});continue}if(J(s)&&(mm(s.tool)||!!t.standaloneCallIds?.has(s.callID))){o(),n.push({kind:"standalone",part:s});continue}r.push(s)}return o(),n}function uv(e){let t=pe(e);return t==="show"||t==="show_user"}function nK(e,t={}){let n=[],r=[],o=()=>{r.length===1?n.push(r[0]):r.length>1&&n.push({kind:"show-group",parts:r.map(s=>s.part)}),r=[]};for(let s of e){if(s.kind==="standalone"&&uv(s.part.tool)&&!t.standaloneCallIds?.has(s.part.callID)){r.push(s);continue}o(),n.push(s)}return o(),n}var pv=["title","description","path","url","content","language","aspect_ratio","attachment"];function Xy(e,t){if(!t||typeof t!="object")return null;let n=t;if(fr(n))return null;let r={callID:e,status:"ready",type:typeof n.type=="string"?n.type:""};for(let o of pv){let s=n[o];typeof s=="string"&&s&&(r[o]=s)}return r}function dv(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 rK(e){let t=[];for(let n of e){let r=n.state,o=r.input??{};if(r.status==="error"){let a=typeof o.title=="string"&&o.title?o.title:void 0;t.push({callID:n.callID,status:"error",type:"error",...a?{title:a}:{},error:typeof r.error=="string"?r.error:""});continue}let s=dv(o.items),i=s?s.map(a=>Xy(n.callID,a)).filter(a=>!!a):[Xy(n.callID,o)].filter(a=>!!a);if(i.length>0){t.push(...i);continue}(r.status==="running"||r.status==="pending")&&t.push({callID:n.callID,status:"pending",type:""})}return t}function Jy(e){return!e.working||e.awaitingUser?!1:e.isRetrying?!0:!e.hasError}var gv=e=>e.time?.completed;function aK(e){return!e.hasPendingTurns||!e.newestAssistantCompleted?!1:e.pendingDelivery||!!e.deliveringBelow||e.activeTurnId!==null&&e.activeTurnId!==e.workingTurnId}function mv(e,t){let n=e.userMessage.info.id;return t.pendingTurnIds.has(n)||e.assistantMessages.length===0&&t.pendingPromptIds.has(n)}function cK(e){let t=e.turns.find(r=>e.deliveringPromptIds.has(r.userMessage.info.id));if(t)return t.userMessage.info.id;let n=e.turns.findIndex(r=>mv(r,e));return n<=0?null:e.turns[n-1].userMessage.info.id}function lK(e){return e.isTurnWorking&&!e.pendingDelivery&&e.activeTurnId===e.turnId}function uK(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 pK(e){return!e.lastTurnWorking||e.workingTurnId===null||e.suppressed?!1:Jy({working:!0,hasError:e.workingTurnHasError,isRetrying:e.isRetrying,awaitingUser:e.awaitingUser})}function dK(e,t){for(let n=e.length-1;n>=0;n--){let r=e[n].userMessage.info.id;if(t(r))return e[n].assistantMessages.length===0?r:null}return null}function gK(e){let{turns:t}=e;if(t.length===0)return{workingTurnId:null,pendingTurnIds:[]};let n=-1;for(let a=t.length-1;a>=0;a--)if(t[a].assistantMessages.length>0){n=a;break}let r=t.slice(n+1).map(a=>a.userMessage.info.id),o=a=>({workingTurnId:t[a].userMessage.info.id,pendingTurnIds:t.slice(a+1).map(c=>c.userMessage.info.id)}),s=e.hintMessageId??null;if(s){if(n>=0&&t[n].userMessage.info.id===s)return o(n);let a=r.indexOf(s);if(a>=0)return o(n+1+a)}if(n>=0){let a=t[n],c=a.assistantMessages[a.assistantMessages.length-1];if(!gv(c.info)&&!c.info.error)return o(n)}let i=e.unrunTurnIds;if(r.length>0){for(let a=t.length-1;a>n;a--)if(!i?.has(t[a].userMessage.info.id))return o(a)}return n<0?{workingTurnId:null,pendingTurnIds:r}:o(n)}function fv(e){let t=e.userMessage.parts;if(t.length===0||!t.every(s=>Ee(s)&&s.synthetic)||e.assistantMessages.length!==1)return!1;let r=e.assistantMessages[0].parts;if(r.length!==1)return!1;let o=r[0];return J(o)&&o.tool==="bash"}function yK(e){if(fv(e))return e.assistantMessages[0].parts[0]}function PK(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 xK(e,t){return!t||!e?!1:e.type!=="idle"}function SK(e,t){return!e&&!!t}function wK(e){for(let t of e.assistantMessages){let n=t.info;if(n.error)return he(n.error)?.message||de(n.error)}}function vK(e){for(let t of e.assistantMessages){let n=t.info;if(n.error)return oy(n.error)}}function AK(e){for(let t of e.assistantMessages){let n=t.info;if(n.error)return he(n.error)}}function Zy(e){if(e){if(J(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(Me(e)){let t=e.text?.trimStart();if(t){let n=t.match(/^\*\*(.+?)\*\*/);if(n)return`Thinking about ${n[1].trim()}...`}return"Thinking..."}if(Ee(e))return"Gathering thoughts..."}}function kK(e,t){for(let n=e.length-1;n>=0;n--){let r=e[n].part,o=J(r)?r:void 0;if(o&&(o.tool==="task"||o.tool==="agent_task"||o.tool==="agent-task"||o.tool==="task_create"||o.tool==="task-create"||o.tool==="task_start"||o.tool==="task-start")&&o.state.status==="running"&&t&&t.length>0){for(let i=t.length-1;i>=0;i--){let a=t[i];if(a.info.role==="assistant")for(let c=a.parts.length-1;c>=0;c--){let p=Zy(a.parts[c]);if(p)return p}}return"Handing off to an agent..."}let s=Zy(r);if(s)return s}return"Figuring out what\u2019s next..."}function RK(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 eh=1.2;function th(e,t){if(!e)return 0;let n=e.input??0,r=(e.output??0)+(e.reasoning??0),o=e.cache?.read??0,s=e.cache?.write??0,i=Math.max(0,n-o-s),c=[...t.tiers??[],...t.contextOver200k?[t.contextOver200k]:[]].filter(d=>n>d.contextThreshold).sort((d,g)=>g.contextThreshold-d.contextThreshold)[0]??t,p=i/1e6*c.inputPer1M;return p+=r/1e6*c.outputPer1M,o>0&&(p+=o/1e6*(c.cacheReadPer1M??c.inputPer1M)),s>0&&(p+=s/1e6*(c.cacheWritePer1M??c.inputPer1M)),p}function Vs(e,t){return e==="codex"||e==="openai-codex"||e==="kortix"&&!!t?.startsWith("codex/")}function nh(e,t,n,r){if(Vs(t,n))return 0;let o=e.cost||0;if(o>0)return o;if(!r||!t||!n)return 0;let s=r(t,n);return s?th(e.tokens,s):0}function rh(e){if(e.role!=="assistant")return{};let t=e;return{providerID:t.providerID,modelID:t.modelID}}function IK(e,t){let n=0,r=0,o=0,s=0,i=0,a=0,c=!1;for(let{part:p,message:d}of e)if(p.type==="step-finish"){c=!0;let g=p,{providerID:m,modelID:f}=rh(d.info);n+=nh(g,m,f,t),r+=g.tokens?.input||0,o+=g.tokens?.output||0,s+=g.tokens?.reasoning||0,i+=g.tokens?.cache?.read||0,a+=g.tokens?.cache?.write||0}if(!c){let p=new Set;for(let{message:d}of e){if(d.info.role!=="assistant")continue;let g=d.info;if(p.has(g.id))continue;p.add(g.id);let m=oh(g,t),f=g.tokens&&Vs(g.providerID,g.modelID);if(m<=0&&!f)continue;c=!0,n+=m;let h=g.tokens;h&&(r+=h.input??0,o+=h.output??0,s+=h.reasoning??0,i+=h.cache?.read??0,a+=h.cache?.write??0)}}if(c)return{cost:n*eh,tokens:{input:r,output:o,reasoning:s,cacheRead:i,cacheWrite:a}}}function oh(e,t){if(Vs(e.providerID,e.modelID)||!t||!e.providerID||!e.modelID||!e.tokens)return 0;let n=t(e.providerID,e.modelID);return n?th({input:e.tokens.input,output:e.tokens.output,reasoning:e.tokens.reasoning,cache:e.tokens.cache},n):0}function CK(e,t){let n=0;for(let r of e){if(r.info?.role!=="assistant")continue;let o=r.info,{providerID:s,modelID:i}=rh(o),a=0,c=!1;for(let p of r.parts)p.type==="step-finish"&&(c=!0,a+=nh(p,s,i,t));c||(a+=oh(o,t)),n+=a}return n*eh}function TK(e){return e===0?"$0.00":e<.001?`$${e.toFixed(4)}`:e<.01?`$${e.toFixed(3)}`:`$${e.toFixed(2)}`}function EK(e){return e<1e3?String(e):e<1e4?`${(e/1e3).toFixed(1)}k`:`${Math.round(e/1e3)}k`}function MK(e){if(!e||e.type!=="retry")return;let t=e,n=de(t.message);return{attempt:t.attempt,message:n.length>60?`${n.slice(0,60)}...`:n,next:t.next,details:he(t.message)}}function OK(e){if(!(!e||e.type!=="retry"))return de(e.message)}function DK(e){return(e.info.summary?.diffs?.length??0)>0}function UK(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=py(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 FK(e){return e?e.split(`
82
- `).filter(n=>n.trim()).length<=3:!1}function LK(e){if(!e)return null;let n=e.split(`
83
- `).filter(r=>r.trim()&&!r.startsWith("#"))[0]?.replace(/^\*\*.*?\*\*\s*/,"").trim();return n?n.length>120?n.slice(0,120).trim()+"\u2026":n:null}function NK(e){if(!e)return[];let t=[],n=e.split(`
84
- `).filter(r=>r.trim());for(let r of n){let o=fy(r);if(o){let s=r.match(/\bses_[a-zA-Z0-9]+/);t.push({...o,sessionId:s?.[0]})}}return t}var ot={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 qK(e,t){let n=ot[e];return t==="running"?n.running:t==="failed"?n.failed:n.verb}function GK(e,t){return t?"failed":e?"running":"done"}var HK={view:"View",create:"Create",str_replace:"Edit",insert:"Insert",delete:"Delete",rename:"Rename"};function VK(e){return e?e.replace(/^\.\//,"").replace(/^(?:\.kortix\/)?memory(?:\/|$)/,"").replace(/\/$/,"")||"memory":""}function zK(e,t){if(!e)return null;let n=e.indexOf(`
85
- `),r=n===-1?e:e.slice(0,n),o=n===-1?"":e.slice(n+1);if(gy(r,"content of "," with line numbers"))return{type:"file",content:o.split(`
77
+ `)&&(n=n.slice(0,-1)),n)}function Ws(e,t,n=0){let r=e.indexOf(`<${t}`,n);if(r===-1)return null;let o=e.indexOf(">",r+1+t.length);return o===-1?null:{open:r,end:o}}function Iy(e,t){let n=Ws(e,t);return n?e.slice(n.open+1+t.length,n.end):null}function Ty(e,t){let n=Ws(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 Ey(e,t){let n=`</${t}>`,r="",o=0;for(;;){let s=Ws(e,t,o);if(!s)break;let i=e.indexOf(n,s.end+1);if(i===-1)break;r+=e.slice(o,s.open),o=i+n.length}return r+e.slice(o)}function My(e,t,n){let r=[];for(let o of e.split(/[\n\r\u2028\u2029]/)){let s=0;for(;;){let i=o.indexOf(t,s);if(i===-1)break;let a=o.indexOf(n,i+t.length);if(a===-1)break;r.push(o.slice(i+t.length,a)),s=a+n.length}}return r}function vn(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&&ce(t[r]);)r++;if(t[r]==="{")return t.slice(r);n=t.indexOf(":",n+1)}return null}function Oy(e,t,n){let r=pt(t),o=pt(n);for(let s of pt(e).split(/[\n\r\u2028\u2029]/)){let i=s.indexOf(r);if(i!==-1&&s.lastIndexOf(o)>=i+r.length)return!0}return!1}function Dy(e,t){let n=pt(e),r=t.map(pt),o=e.length,s=c=>{let p=c;for(;p<o&&ce(e[p]);)p++;return p},i=c=>{for(let p=c;p<o;p++)if(wn(e[p]))return p+1;return-1},a=0;for(;a!==-1&&a<=o;){let c=s(a);if(c>=o)return null;let p=r.find(d=>n.startsWith(d,c));if(p!==void 0){let d=s(c+p.length);if(e[d]===":"){let g=s(d+1);if(g<o){let m=g;for(;m<o&&!wn(e[m]);)m++;for(;m>g+1&&ce(e[m-1]);)m--;return e.slice(g,m)}for(let m=o-1;m>d;m--)if(!wn(e[m]))return e[m];return null}}a=i(c)}return null}function jy(e){let t=e.length,n=new Array(t+1);n[0]=0;for(let a=1;a<=t;a++)n[a]=ce(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"||!ce(e[a-1]))continue;let c=a+1;if(ce(e[c])){for(;c<t&&ce(e[c]);)c++;Bs(e[c])&&(r[a]=a)}}let o=new Array(t+1);o[0]=0;for(let a=0;a<t;a++)o[a+1]=o[a]+(wn(e[a])?1:0);let s=(a,c)=>o[c]===o[a],i=a=>{let c=a+1;for(;ce(e[c]);)c++;let p=c;for(;p<t&&Bs(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&&ce(e[d]);)d++;if(d!==p){if(d<t&&d+2<=t){let g=r[d+2]??-1;if(g!==-1){let m=Math.max(d+1,n[g]);if(s(d,m))return{id:e.slice(a+2,c),title:e.slice(d,m),status:i(g)}}}if(d<t&&r[d]===d){for(let g=d-2;g>=p+1;g--)if(!wn(e[g]))return{id:e.slice(a+2,c),title:e[g],status:i(d)}}}}return null}function $y(e){let t=(i,a)=>i.slice(a,a+6).toLowerCase()==="error:",n=0;for(;;){let i=n;for(;i<e.length&&ce(e[i]);)i++;if(!t(e,i))break;for(i+=6;i<e.length&&ce(e[i]);)i++;n=i}let r=e.slice(n),o="",s=0;for(;s<r.length;){if(t(r,s)&&(s===0||!Bs(r[s-1]))){let i=s,a=0;for(;t(r,i);){for(i+=6;i<r.length&&ce(r[i]);)i++;a++}if(a>=2){s=i;continue}}o+=r[s],s++}return o}function Uy(e,t){let n=t?"![":"[",r="",o=0,s=-2,i=-2;for(let a=e.indexOf(n);a!==-1;){let c=a+n.length;if(s<c&&(s=e.indexOf("]",c)),s===-1)break;let p=s;if(e[p+1]!=="("){a=e.indexOf(n,p+1);continue}if(i<p+2&&(i=e.indexOf(")",p+2)),i===-1)break;r+=e.slice(o,a)+(t?" ":e.slice(c,p)),o=i+1,a=e.indexOf(n,o)}return r+e.slice(o)}function Ly(e){return Uy(e,!0)}function Fy(e){return Uy(e,!1)}function cw(e,t){let n=e.slice(t,t+8).toLowerCase();return n.startsWith("http://")||n.startsWith("https://")}function Ny(e,t){let n=pt(e),r=pt(t),o=e.length,s=i=>{let a=i;for(;a<o&&ce(e[a]);)a++;return a};for(let i=n.indexOf(r);i!==-1;i=n.indexOf(r,i+1)){let a=s(i+r.length);if(e[a]!==":")continue;let c=s(a+1);for(let p=c;p<o;){if(!ce(e[p])){p++;continue}let d=s(p);if(cw(e,d))return e.slice(c,p);p=d}return e.slice(c)}return null}var lw=new Set(["read","glob","grep","list"]);function X(e){return e.replace(/^oc-/,"").replace(/-/g,"_")}function ZF(e){return lw.has(ae(e))}function eN(e){let t=0,n=0,r=0;for(let o of e){let s=ae(o.tool);s==="read"?t++:s==="glob"||s==="grep"?n++:s==="list"&&r++}return{read:t,search:n,list:r}}function Hs(e){if(!e)return"";let t=$e(e.replace(/\\/g,"/")),n=t.lastIndexOf("/");return n>=0?t.slice(n+1):t}function Gr(e,t=60){if(!e)return"";let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t)}\u2026`:n}function Vs(e){let n=(e.state??{}).input??{};switch(X(e.tool)){case"read":case"edit":case"write":case"morph_edit":{let s=n.filePath??n.file_path??n.path;return s?Hs(String(s)):""}case"glob":return n.pattern?String(n.pattern):"";case"grep":{let s=n.pattern??n.query,i=n.path??n.include;return s&&i?`"${Gr(String(s),40)}" in ${Hs(String(i))}`:s?`"${Gr(String(s),60)}"`:""}case"list":return n.path?Hs(String(n.path)):"";case"bash":return Gr(String(n.command??""),80);default:break}let o=["description","query","url","filePath","file_path","path","pattern","name","prompt"];for(let s of o){let i=n[s];if(typeof i=="string"&&i.length>0)return Gr(s==="query"&&Br(i)||i,60)}return""}var uw={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 tN(e,t={}){let n={...uw,...t},r=X(e.tool),o=Vs(e);switch(r){case"read":return{title:n.read,subtitle:o};case"glob":case"grep":return{title:n.search,subtitle:o};case"list":return{title:n.list,subtitle:o};case"bash":return{title:n.shell,subtitle:o};case"edit":case"morph_edit":return{title:n.edit,subtitle:o};case"write":return{title:n.write,subtitle:o};case"webfetch":case"web_fetch":return{title:n.fetch,subtitle:o};case"websearch":case"web_search":return{title:n.webSearch,subtitle:o};case"scrape":case"scrape_webpage":return{title:n.scrape,subtitle:o};case"apply_patch":return{title:n.applyPatch,subtitle:o};case"task":return{title:n.task,subtitle:o};case"session_spawn":case"session_start_background":return{title:n.worker,subtitle:o};case"project_select":case"project_list":return{title:n.workspace,subtitle:o};default:return{title:r.replace(/_/g," ").replace(/\b\w/g,i=>i.toUpperCase()),subtitle:o}}}function Ue(e){return e.type==="text"}function Le(e){return e.type==="reasoning"}function ne(e){return e.type==="tool"}function qy(e){return e.type==="file"}function iN(e){return e.type==="agent"}function aN(e){return e.type==="compaction"}function cN(e){return e.type==="snapshot"}function lN(e){return e.type==="patch"}function uN(e){return e.type==="step-start"||e.type==="step-finish"}function pN(e){if(Ue(e)||Le(e))return e.text}function dN(e){if(!qy(e))return!1;let t=e.mime;return t.startsWith("image/")||t==="application/pdf"}function gN(e){let t=[],n=[];for(let r of e)qy(r)?t.push(r):n.push(r);return{attachments:t,stickyParts:n}}function mN(e,t){let n=[];return e?.tool&&n.push(e.tool),t?.tool&&n.push(t.tool),n}function fN(e,t,n){return n.some(r=>r.messageID===t&&r.callID===e.callID)}var pw=new Set(["todoread","context_info"]);function dw(e){return!pw.has(e.tool)}var gw=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 By(e){let t=e.tool||"";if(t.startsWith("oc-"))return;let n=ae(t);if(n==="task"||n==="delegate"){let r=e.state?.metadata?.sessionId;if(typeof r=="string"&&r)return r;if(n==="task"&&e.state?.status==="error")return e.state.error?.match(/\btask_id:\s*(ses_[A-Za-z0-9]+)/)?.[1]}return mw(t,e.state)}function mw(e,t){let n=X(e);if(gw.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 yN(e){if(e)for(let t=e.length-1;t>=0;t--){let n=e[t]?.info;if(n?.role==="assistant"&&n.error)return fe(n.error)}}function hN(e){let t=[];for(let n of e)if(n.info.role==="assistant")for(let r of n.parts)ne(r)&&dw(r)&&t.push(r);return t}function bN(e,t={}){switch(X(e)){case"webfetch":return{icon:"globe",title:"Web Fetch",subtitle:t.url};case"websearch":case"web_search":return{icon:"search",title:"Web Search",subtitle:t.query};case"scrape_webpage":return{icon:"globe",title:"Scrape",subtitle:t.urls?.split?.(",")[0]};case"image_search":return{icon:"image",title:"Image Search",subtitle:t.query};case"image_gen":return{icon:"image",title:"Image Gen",subtitle:t.prompt?.slice?.(0,40)};case"video_gen":return{icon:"cpu",title:"Video Gen",subtitle:t.prompt?.slice?.(0,40)};case"presentation_gen":{let n=t.action||"";return{icon:"presentation",title:{create_slide:"Create Slide",list_slides:"List Slides",preview:"Preview",export_pdf:"Export PDF",export_pptx:"Export PPTX"}[n]||"Presentation",subtitle:t.slide_title||t.presentation_name}}case"show":case"show_user":return{icon:"globe",title:"Output",subtitle:t.title||t.description};case"task":return{icon:"square-kanban",title:`Agent (${t.subagent_type||"task"})`,subtitle:bw(t)};case"session_spawn":case"session_start_background":return{icon:"square-kanban",title:`Worker (${t.agent||"KortixWorker"})`,subtitle:t.description||t.prompt?.slice(0,60)};case"apply_patch":return{icon:"file-pen",title:"Patch",subtitle:t.files?.length?`${t.files.length} file${t.files.length>1?"s":""}`:void 0};case"todoread":return{icon:"check-square",title:"Todos (read)"};case"prune":return{icon:"scissors",title:"DCP Prune",subtitle:t.reason};case"distill":return{icon:"scissors",title:"DCP Distill"};case"compress":return{icon:"scissors",title:"DCP Compress",subtitle:t.topic};case"context_info":return{icon:"scissors",title:"Context Info"};case"session_read":return{icon:"glasses",title:`Session Read (${t.mode||"summary"})`,subtitle:t.session_id?.slice(-12)};case"session_search":return{icon:"search",title:"Session Search",subtitle:t.query};case"session_message":return{icon:"message-circle",title:"Message \u2192 Session",subtitle:t.session_id?.slice(-12)};case"session_lineage":return{icon:"list-tree",title:"Session Lineage",subtitle:t.session_id?.slice(-12)};case"session_list_background":case"session_list_spawned":return{icon:"layers",title:"Background Sessions",subtitle:t.project||"all"};case"session_stats":return{icon:"layers",title:"Session Stats",subtitle:t.session_id?.slice(-12)||"current"};case"session_list":return{icon:"list",title:"Session List",subtitle:t.search};case"session_get":return{icon:"book-open",title:"Session Get",subtitle:t.session_id?.slice(-12)};case"session_context":return{icon:"book-open",title:"Session Context",subtitle:t.session_id?.slice(-12)};case"project_delete":return{icon:"trash-2",title:"Workspace Delete Disabled",subtitle:t.project};case"project_list":return{icon:"folder",title:"Projects"};case"project_get":case"project_update":return{icon:"folder",title:"Project",subtitle:t.name||t.project};case"project_select":return{icon:"folder",title:"Project Select",subtitle:t.project};case"project_create":return{icon:"folder-plus",title:"Project Create",subtitle:t.name};case"triggers":case"trigger_create":return{icon:"clock",title:"Create Trigger",subtitle:t.name};case"trigger_list":return{icon:"clock",title:"List Triggers"};case"trigger_get":return{icon:"clock",title:"Trigger Details",subtitle:t.name||t.id};case"trigger_delete":return{icon:"clock",title:"Delete Trigger",subtitle:t.name||t.id};case"trigger_update":return{icon:"clock",title:"Update Trigger",subtitle:t.name||t.id};case"trigger_test":return{icon:"clock",title:"Test Trigger",subtitle:t.name||t.id};case"trigger_pause":return{icon:"clock",title:"Pause Trigger",subtitle:t.name||t.id};case"trigger_resume":return{icon:"clock",title:"Resume Trigger",subtitle:t.name||t.id};case"agent_spawn":return{icon:"cpu",title:`Agent (${t.agent_type||"worker"})`,subtitle:t.description};case"agent_message":return{icon:"message-circle",title:"Agent Message",subtitle:t.agent_id};case"agent_stop":return{icon:"ban",title:"Agent Stop",subtitle:t.agent_id};case"agent_status":return{icon:"layers",title:"Agent Status"};case"agent_task":return{icon:"check-square",title:"Create Task",subtitle:t.title};case"agent_task_update":return{icon:"check-square",title:"Update Task",subtitle:t.task_id};case"agent_task_list":return{icon:"check-square",title:"List Tasks"};case"agent_task_get":return{icon:"check-square",title:"Task Details",subtitle:t.task_id};case"task_create":return{icon:"plus",title:"Create Task",subtitle:t.title};case"task_list":return{icon:"list",title:"Tasks",subtitle:t.status||"all"};case"task_update":return{icon:"refresh-cw",title:"Update Task",subtitle:t.id};case"task_done":return{icon:"check-circle",title:"Task Done",subtitle:t.id};case"task_delete":return{icon:"trash-2",title:"Delete Task",subtitle:t.id};case"pty_spawn":return{icon:"terminal",title:"Spawn",subtitle:t.title||t.command};case"pty_read":return{icon:"terminal",title:"Terminal Output",subtitle:t.id};case"pty_write":case"pty_input":return{icon:"terminal",title:"Terminal Input",subtitle:t.id};case"pty_kill":return{icon:"terminal",title:"Kill Process",subtitle:t.id};default:return fw(e,t)}}function fw(e,t){switch(ae(e)){case"read":return{icon:"glasses",title:"Read",subtitle:yw(Ve(t))};case"list":return{icon:"list",title:"List",subtitle:hw(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:Ky(Ve(t))};case"write":return{icon:"file-pen",title:"Write",subtitle:Ky(Ve(t))};case"todowrite":return{icon:"check-square",title:"Todos"};case"question":return{icon:"message-circle",title:"Questions"};default:return{icon:"cpu",title:e}}}function yw(e){if(!e)return;let t=e.split("/");return t[t.length-1]||e}function Ky(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 hw(e){if(!e)return;let t=e.lastIndexOf("/");if(!(t<0))return e.slice(0,t)||"/"}function _N(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 kn(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 bw(e){let t=kn(e.description);if(t)return t;let n=kn(e.title,80);if(n)return n;let r=kn(e.message);if(r)return r;let o=kn(e.prompt);if(o)return o;let s=kn(e.agent_id,40);return s?`Agent ${s}`:"Worker task"}function PN(e,t){return!e||!t?[]:(e[t]??[]).filter(r=>r.severity===1).slice(0,3)}function xN(e,t){return e.find(n=>n.tool?.callID===t)}function SN(e,t){return e.find(n=>n.tool?.callID===t)}var _w=/\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 wN(e){return e?e.replace(_w,""):""}var Pw={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"},xw={read:"files",list:"files",glob:"search",grep:"search",write:"edit",edit:"edit",apply_patch:"edit",bash:"shell",pty:"shell",web_search:"web",webfetch:"web",media:"web",show:"task",task:"task",delegate:"task",sessions:"task",todowrite:"task",question:"task",automations:"task",projects:"task",memory:"other",connectors:"other",skill:"other",context:"other",retired:"other",other:"other"};function Sw(e){return e.replace(/^oc[-_]/,"")}function Gy(e){return Sw(e).replace(/-/g,"_")}function Wy(e){return Gy(e).split(/[_\s]+/).filter(Boolean).map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" ")}function zs(e){return{label:Pw[Gy(e)]??Wy(e),category:xw[ae(e)]}}var ww=256*1024;function Aw(e){switch(e.status){case"pending":return"pending";case"running":return"running";case"completed":return"done";case"error":return"error";default:return e}}function vw(e){if(e===void 0)return{};if(e.length>ww)return{outputText:e};try{return{outputParsed:JSON.parse(e),outputText:e}}catch{return{outputText:e}}}function kw(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e,n=t.success===!1,r=t.error,o=typeof r=="string"&&r.length>0||typeof r=="object"&&r!==null;if(!(!n&&!o))return o?fe(r):typeof t.message=="string"&&t.message?t.message:"Tool reported failure"}var re=e=>typeof e=="string"?e:void 0,Wr=e=>typeof e=="number"?e:void 0,Hr=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:void 0;function Ys(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}var Rw=new Set(["add","update","delete","move"]);function Cw(e,t,n){if(e==="apply_patch"){let c=(Array.isArray(n.files)?n.files:[]).flatMap(p=>{let d=Hr(p),g=d&&(re(d.relativePath)||re(d.filePath));if(!d||!g)return[];let m=re(d.type);return[Ys({path:g,type:m&&Rw.has(m)?m:void 0,before:re(d.before),after:re(d.after),patch:re(d.patch)??re(d.diff),additions:Wr(d.additions),deletions:Wr(d.deletions),movePath:re(d.movePath)})]});return c.length?c:void 0}let r=Ve(t);if(!r)return;if(e==="read")return[{path:r}];if(e==="write")return[Ys({path:r,after:re(t.content)})];if(e!=="edit")return;let o=Hr(n.filediff),s=o?void 0:re(n.patch),i=s?Iw(s):void 0;return[Ys({path:r,before:re(o?.before)??re(t.oldString),after:re(o?.after)??re(t.newString),patch:s,additions:Wr(o?.additions)??i?.additions,deletions:Wr(o?.deletions)??i?.deletions})]}function Iw(e){let t=0,n=0;for(let r of e.split(`
79
+ `))r.startsWith("+")&&!r.startsWith("+++")?t++:r.startsWith("-")&&!r.startsWith("---")&&n++;return{additions:t,deletions:n}}function Tw(e){let t=e.answers;if(Array.isArray(t))return t.map(n=>Array.isArray(n)?n.filter(r=>typeof r=="string"):[])}function Hy(e,t){let n="title"in t?t.title:void 0,r=t.status==="completed"?t.output:void 0,{outputParsed:o,outputText:s}=vw(r),i=Aw(t),a=t.status==="error"?t.error:void 0;if(i==="done"){let m=kw(o);m&&(i="error",a=m)}let c=ae(e),p=t.input??{},d="metadata"in t&&Hr(t.metadata)||{},g=Hr(d.diagnostics);return{name:e,kind:c,title:n||zs(e).label,status:i,input:t.input,output:r,outputParsed:o,outputText:s,error:a,files:Cw(c,p,d),diff:re(d.patch)??re(d.diff),diagnostics:g,answers:c==="question"?Tw(d):void 0,childSessionId:By({tool:e,state:t})}}function EN(e){return Hy(e.tool,e.state)}function Ew(e){return{kind:"text",id:e.id,text:e.text,synthetic:!!e.synthetic}}function Mw(e){return{kind:"reasoning",id:e.id,text:e.text}}function Ow(e){return{kind:"tool",id:e.id,tool:Hy(e.tool,e.state)}}function Dw(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 jw(e){return{kind:"subtask",id:e.id,description:e.description,agent:e.agent,prompt:e.prompt,model:e.model}}function $w(e){return{kind:"patch",id:e.id,hash:e.hash,files:e.files,fileCount:e.files.length}}function Uw(e){return{kind:"snapshot",id:e.id,snapshot:e.snapshot}}function Lw(e){return{kind:"agent",id:e.id,name:e.name}}function Fw(e){return{kind:"retry",id:e.id,attempt:e.attempt,message:fe(e.error),createdAt:e.time.created}}function Nw(e){return{kind:"compaction",id:e.id,auto:e.auto,overflow:!!e.overflow,tailStartId:e.tail_start_id}}function Kw(e){return{kind:"step",id:e.id,phase:"start",snapshot:e.snapshot}}function qw(e){return{kind:"step",id:e.id,phase:"finish",snapshot:e.snapshot,reason:e.reason,cost:e.cost,tokens:e.tokens}}function Vy(e){switch(e.type){case"text":return Ew(e);case"reasoning":return Mw(e);case"tool":return Ow(e);case"file":return Dw(e);case"subtask":return jw(e);case"patch":return $w(e);case"snapshot":return Uw(e);case"agent":return Lw(e);case"retry":return Fw(e);case"compaction":return Nw(e);case"step-start":return Kw(e);case"step-finish":return qw(e);default:return{kind:"unknown",raw:e}}}function Bw(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||fe(e),provider:n?.provider,code:n?.code,suggestion:n?.suggestion,upstreamStatus:n?.upstreamStatus,requestId:n?.requestId,attemptFailures:n?.attemptFailures}}function Gw(e){switch(e.kind){case"text":case"reasoning":return e.text.trim().length>0;case"step":return!1;default:return!0}}function Ww(e){let t=e.parts.map(Vy),n=e.info.role==="assistant"?e.info.error:void 0,r=Bw(n),o=!r&&!t.some(Gw);return{parts:t,error:r,isEmpty:o}}var Qs=Ge+BigInt(1),zy=Qs/BigInt(2);function Vr(e){return BigInt(Math.trunc(e))*an}function Xs(e,t){let r=t-(t&Ge)+e;return r-t>zy?r-=Qs:t-r>zy&&(r+=Qs),r}function Yy(e,t){let n=Tt(e.info.id)??BigInt(0),r=e.info.time?.created;if(typeof r!="number")return Xs(n,t);let o=Vr(r),s=Xs(n,o);return(s>o?s-o:o-s)<=at?s:o}function Qy(e){return Tt(e)===null?1:0}function Xy(e,t){return e<t?-1:e>t?1:0}function LN(e,t){return Jy(e,t,Vr(Date.now()))}function Hw(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 Vr(t??Date.now())}function Jy(e,t,n){let r=Qy(e.info.id),o=Qy(t.info.id);if(r!==o)return r-o;if(r===0){let a=Yy(e,n),c=Yy(t,n);return a!==c?a<c?-1:1:Xy(e.info.id,t.info.id)}let s=typeof e.info.time?.created=="number"?e.info.time.created:null,i=typeof t.info.time?.created=="number"?t.info.time.created:null;return s===null&&i===null?0:s===null?1:i===null?-1:s!==i?s<i?-1:1:Xy(e.info.id,t.info.id)}function FN(e,t){let n=new Map([...t?.pendingMessageIds??[]].map((d,g)=>[d,g])),r=Hw(e),o=[...e].sort((d,g)=>{let m=n.get(d.info.id),f=n.get(g.info.id);return m!==void 0&&f!==void 0?m-f:m!==void 0?1:f!==void 0?-1:Jy(d,g,r)}),s=[],i=new Map;for(let d of o)if(d.info.role==="user"){if(i.has(d.info.id))continue;let g={userMessage:d,assistantMessages:[]};s.push(g),i.set(d.info.id,g)}let a=null,c=[],p=[];for(let d of o){if(d.info.role==="user"){a=i.get(d.info.id)??null;continue}if(d.info.role!=="assistant")continue;let g=d.info,m=g.tokens;if(!(!g.error&&d.parts.length===0&&m?.input===0&&m.output===0&&m.reasoning===0)){if(g.parentID){let f=i.get(g.parentID);if(f){f.assistantMessages.push(d);continue}}if(a){a.assistantMessages.push(d);continue}if(g.parentID){let f=c[c.length-1];f&&f.userMessage.info.id===g.parentID?f.assistantMessages.push(d):c.push({userMessage:zw(g.parentID,d),assistantMessages:[d],partial:!0});continue}p.push(d)}}if(p.length>0){let d=s[0]??c[0];if(d)d.assistantMessages.unshift(...p);else{let[g,...m]=p;s.push({userMessage:g,assistantMessages:m})}}return c.length>0?[...c,...s]:s}var Rn=new Map,Vw=256;function zw(e,t){let n=t.info,r=n.time?.created,o=`${n.sessionID??""}|${e}|${r??""}`,s=Rn.get(o);if(s)return s;let i={info:{id:e,role:"user",...n.sessionID?{sessionID:n.sessionID}:{},...typeof r=="number"?{time:{created:r}}:{}},parts:[]};if(Rn.size>=Vw){let a=Rn.keys().next().value;a!==void 0&&Rn.delete(a)}return Rn.set(o,i),i}function NN(e){let t=[];for(let n of e.assistantMessages)for(let r of n.parts)t.push({part:r,message:n});return t}function KN(e){for(let t=e.length-1;t>=0;t--){let n=e[t].part;if(Ue(n)&&n.text?.trim())return n}}function qN(e){return e.some(({part:t})=>t.type==="tool"||t.type==="compaction"||t.type==="snapshot"||t.type==="patch")}function BN(e,t,n){if(n)return[];let r=[];for(let o of e.assistantMessages)for(let s of o.parts){if(!ne(s))continue;let i=s,a=i.state?.metadata?.answers;i.tool==="question"&&(a?.length??0)>0&&r.push({part:s,message:o})}return r}function GN(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 WN(e){let t=e-6e4;return(n,r)=>{let o=n.time.updated??n.time.created,s=r.time.updated??r.time.created,i=o>t,a=s>t;return i&&a?n.id<r.id?-1:n.id>r.id?1:0:i&&!a?-1:!i&&a?1:s-o}}function Yw(e,t){let n=e.get(t);if(!n||n.length===0)return[];let r=[];for(let o of n)r.push(o),r.push(...Yw(e,o));return r}function Qw(e){if(!e||typeof e!="object")return!1;let t=e.data;return!!t&&typeof t=="object"&&t.isRetryable===!0}function VN(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&&Qw(n.error)}return!1}function zr(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function eh(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 QN(e){return!!e&&(eh(e)||tA(e)!==null)}function th(e){let t=Zy.get(e);if(t&&t.state===e.state)return t.outcome;let n=Xw(e);return Zy.set(e,{state:e.state,outcome:n}),n}var Zy=new WeakMap;function Xw(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(eh(n))return"failed";let r=Jw(n);return r===void 0?"ok":Zw(r)?"failed":eA(r)}function Jw(e){try{return JSON.parse(e)}catch{return}}function Zw(e){return zr(e)&&e.success===!1&&typeof e.error=="string"}function eA(e){let t=zr(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 tA(e){let t=e.trim();if(!t)return null;let n;try{n=JSON.parse(t)}catch{return null}if(!zr(n)||n.success!==!1||typeof n.error!="string")return null;let r={errorSummary:n.error.trim(),hint:typeof n.hint=="string"?n.hint.trim():void 0},o=vn(r.errorSummary);if(o===null)return r;try{let s=JSON.parse(o);typeof s.message=="string"&&s.message.trim()&&(r.nestedMessage=s.message.trim()),typeof s.status=="number"&&(r.status=s.status),typeof s.error=="boolean"&&(r.nestedError=s.error)}catch{}return r}function XN(e){return $y(e).replace(/\s+/g," ").trim()||e.trim()}function JN(e){let t=e.trim();if(!t)return null;let n;try{n=JSON.parse(t)}catch{return null}if(!zr(n))return null;let r=n.success,o=n.error,s=n.hint;if(r!==!1||typeof o!="string")return null;let i=[];i.push(o.trim());let a=vn(o);if(a!==null)try{let p=JSON.parse(a).message;typeof p=="string"&&p.trim()&&i.push(`Details: ${p.trim()}`)}catch{}return typeof s=="string"&&s.trim()&&i.push(`Hint: ${s.trim()}`),i.join(`
80
+
81
+ `)}var nA=new Set(["get_mem","memory_search","mem_search","ltm_search","dcp_compress","dcp_distill","dcp_prune","prune","distill","compress","context_info"]),rA={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 oA(e,t){if(e==="filePath"||e==="path"||e==="file"){let n=t.split("/");return n[n.length-1]||t}return e==="query"&&Br(t)||t}function sA(e,t){if(!t||typeof e!="object"||e===null)return;let n=e;for(let r of t){let o=n[r];if(typeof o=="string"&&o.trim())return oA(r,o.trim())}}function nh(e){if(Le(e))return{verb:"Thought",running:"Thinking",object:void 0,tier:"reasoning"};if(!ne(e))return{verb:"Used",running:"Using",object:void 0,tier:"primary"};let t=pe(e.tool),n=rA[t],r=e.state?.input;return n?{verb:n.verb,running:n.running,object:sA(r,n.objectKeys),tier:nA.has(t)?"plumbing":"primary"}:{verb:"Used",running:"Using",object:t,tier:"primary"}}function aK(e){let t=0,n=0,r=!1,o=!1;for(let s of e){if(nh(s).tier==="plumbing"){r=!0;continue}if(Le(s)){if(!s.text?.trim())continue;o||(o=!0,t+=1);continue}o=!1,t+=1,ne(s)&&th(s)!=="ok"&&(n+=1)}return{total:t,failed:n,completed:t-n,hasPlumbing:r}}function Js(e){return`${e} ${e===1?"step":"steps"}`}function cK(e,t){let{total:n,failed:r,completed:o,hasPlumbing:s}=e;return t?n===0?"Working":`Working \xB7 ${Js(n)}`:n===0?s?"Housekeeping":"Worked":r===0?`Completed ${Js(n)}`:o===0?`${Js(n)} failed`:`Completed ${o} of ${n} steps \xB7 ${r} failed`}function uK(e){let t=!1,n=!1,r=!1,o=null,s=p=>{let d=p;return d?.summary!==!0?!1:(t=!0,!d.time?.completed&&!d.error&&(r=!0),o==null&&d.error!=null&&(o=d.error),!0)},i=p=>{for(let d of p??[])d.type==="compaction"?(t=!0,n=!0):d.type==="text"&&d.text?.trim()&&(n=!0)},c=(e.userMessage?.parts??[]).some(p=>p.type==="compaction");c&&(t=!0),e.userMessage&&s(e.userMessage.info)&&i(e.userMessage.parts);for(let p of e.assistantMessages)s(p.info),i(p.parts);return c&&e.assistantMessages.length===0&&(r=!0),{isCompaction:t,hasContent:n,inFlight:r,error:o}}function gK(e){let t=(e??"").trimStart();return t.startsWith("{")||t.startsWith("[")}function mK(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 fK(e,t=200){let n=e??"";return n=n.replace(/\\n/g," "),n=Ly(n),n=Fy(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 yK(e){let t=(e??"").trim();if(!t)return null;let n;try{if(n=JSON.parse(t),typeof n=="string")try{n=JSON.parse(n)}catch{return null}}catch{return null}if(!n||typeof n!="object"||Array.isArray(n))return null;let r=n;if(r.success!==!1||typeof r.error!="string"||!r.error.trim())return null;let o=r.error.trim(),s;for(let i=0;i<3;i++){let a=vn(o);if(a===null)break;let c;try{c=JSON.parse(a)}catch{break}if(typeof c.status=="number"&&(s=c.status),typeof c.message=="string"&&c.message.trim())o=c.message.trim();else if(typeof c.error=="string"&&c.error.trim())o=c.error.trim();else break}return{message:o,status:s}}function Cn(e){try{return JSON.parse(`"${e}"`)}catch{return e}}function Zs(e,t=30){if(!e)return[];let n=[],r=new Set,o=(a,c,p)=>{!/^https?:\/\//i.test(c)||r.has(c)||n.length>=t||(r.add(c),n.push({title:a.trim()||c,url:c,snippet:p?.trim()||void 0}))},s=/"title"\s*:\s*"((?:\\.|[^"\\])*)"\s*,\s*"url"\s*:\s*"((?:\\.|[^"\\])*)"(?:\s*,\s*"(?:snippet|content|text)"\s*:\s*"((?:\\.|[^"\\])*)")?/g,i;for(;(i=s.exec(e))!==null;)if(o(Cn(i[1]),Cn(i[2]),i[3]?Cn(i[3]):void 0),n.length>=t)return n;if(n.length===0){let a=/"url"\s*:\s*"((?:\\.|[^"\\])*)"[^{}]{0,400}?"title"\s*:\s*"((?:\\.|[^"\\])*)"/g;for(;(i=a.exec(e))!==null;)if(o(Cn(i[2]),Cn(i[1])),n.length>=t)return n}return n}function rh(e,t=!1){if(typeof e=="object"&&e!==null)return e;if(typeof e!="string")return null;try{let n=JSON.parse(e);if(typeof n=="string")try{n=JSON.parse(n)}catch{}return typeof n=="object"?n:null}catch{let n=t&&e.trim().replace(/^\uFEFF/,"");if(n&&n!==e)try{return JSON.parse(n)}catch{}return null}}function Yr(e){return e.filter(t=>t.title&&t.url).map(t=>({title:t.title,url:t.url,snippet:t.snippet||t.content||t.text||void 0,author:t.author||void 0,publishedDate:t.publishedDate||t.published_date||void 0}))}function oh(e){if(!e)return[];let t=rh(e,!0);if(t?.success===!1)return[];if(Array.isArray(t?.results)&&t.results.length>0){let n=t.results[0];if(n&&typeof n.query=="string"){let r=[];for(let o of t.results)typeof o.query=="string"&&r.push({query:o.query,answer:o.answer||void 0,sources:Array.isArray(o.results)?Yr(o.results):[]});if(r.length>0)return r}else if(n&&(n.title||n.url)){let r=Yr(t.results);if(r.length>0)return[{query:t.query||"",answer:t.answer||void 0,sources:r}]}}if(t?.query&&typeof t.query=="string")return[{query:t.query,answer:t.answer||void 0,sources:Array.isArray(t.results)?Yr(t.results):[]}];if(Array.isArray(t)&&t.length>0&&t[0]&&(t[0].title||t[0].url)){let n=Yr(t);if(n.length>0)return[{query:"",sources:n}]}if(typeof e=="string"){let n=e.split(/(?=^Title: )/m).filter(Boolean),r=[];for(let o of n){let s=o.match(/^Title:\s*(.+)/m),i=o.match(/^URL:\s*(.+)/m),a=o.match(/^Author:\s*(.+)/m),c=o.match(/^Published Date:\s*(.+)/m),p=o.match(/^Text:\s*([\s\S]*?)$/m);s&&i&&r.push({title:s[1].trim(),url:i[1].trim(),snippet:p?.[1]?.trim()||void 0,author:a?.[1]?.trim()||void 0,publishedDate:c?.[1]?.trim()||void 0})}if(r.length>0)return[{query:"",sources:r}]}if(typeof e=="string"){let n=Zs(e);if(n.length>0)return[{query:"",sources:n.map(r=>({title:r.title,url:r.url,snippet:r.snippet}))}]}return[]}function ei(e){try{return new URL(e).hostname.replace("www.","")}catch{return e}}function PK(e){try{let t=new URL(e).hostname.replace(/^www\./,""),n=t.split(".");return n.length<=2?t:n.slice(-2).join(".")}catch{return ei(e)}}function xK(e){try{return`https://www.google.com/s2/favicons?domain=${new URL(e).hostname.replace(/^www\./,"")}&sz=128`}catch{return null}}function SK(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 iA(e){let t=e.urls??e.url;if(typeof t=="string")return t.split(/[\s,]+/).map(n=>n.trim()).filter(n=>/^https?:\/\//i.test(n));if(Array.isArray(t)){let n=[];for(let r of t){if(typeof r!="string")continue;let o=r.trim();/^https?:\/\//i.test(o)&&n.push(o)}return n}return[]}function aA(e,t){if(t.length===0)return[];let n=e.replace(/^Error:\s*/i,"").trim();return t.map(r=>{let o=Ny(n,r)?.trim()||n;return{url:r,success:!1,error:o}})}function wK(e,t){let n=cA(e);if(n?.results?.length)return n.results;let r=typeof e=="string"?e:"";return r.trim()?aA(r,iA(t)):[]}function cA(e){if(!e)return null;let t=rh(e);if(!t)return null;if(t.results&&Array.isArray(t.results))return{total:t.total||t.results.length,successful:t.successful??t.results.filter(n=>n.success!==!1).length,failed:t.failed??t.results.filter(n=>n.success===!1).length,results:t.results.map(n=>({url:n.url||"",success:n.success!==!1,title:n.title||void 0,content:n.content||n.text||n.snippet||void 0,error:n.error||void 0}))};if(typeof e=="string"){let n=Zs(e);if(n.length>0)return{total:n.length,successful:n.length,failed:0,results:n.map(r=>({url:r.url,success:!0,title:r.title||void 0,content:r.snippet||void 0}))}}return null}function lA(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 uA={read:"explore",list:"explore",glob:"explore",grep:"explore",write:"edit",edit:"edit",apply_patch:"edit",bash:"run",pty:"run",web_search:"web",webfetch:"web",media:"create",show:"create",task:"delegate",delegate:"delegate",sessions:"sessions",todowrite:"plan",question:"ask",memory:"memory",connectors:"connectors",automations:"automations",projects:"projects",skill:"skills",context:"hidden",retired:"retired",other:"other"};function ti(e){return uA[ae(e)]}function Qr(e){let t=X(e).replace(/__+/g,"/");return(t.includes("/")?t.slice(t.lastIndexOf("/")+1):t).replace(/_/g," ").trim().replace(/\b\w/g,r=>r.toUpperCase())}var pA={run:"Terminal",memory:"Memory"};function IK(e){let t=ti(e);return(t==="hidden"?void 0:pA[t])??Qr(e)}function In(e,t,n){return e===1?t:n}function ni(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 ah(e){return e.length?Vs(e[0]):""}function Se(e){return(e.state??{}).input??{}}var dA={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 gA(e){let t=X(e.tool);if(t==="agent_task_update"||t==="task_update")switch(Se(e).action||""){case"start":return"spawn";case"cancel":return"stop";case"approve":return"done";default:return"message"}return dA[t]??"message"}function sh(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 mA(e){let t=X(e.tool);if(t==="triggers"){let r=Se(e).action||"list";return sh(r)}let n=t.match(/^trigger_(.+)$/);return sh(n?n[1]:"list")}var fA={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 yA(e){return fA[X(e.tool)]??"read"}var hA={project_get:"open",project_list:"open",project_select:"open",project_update:"update",project_create:"create",project_delete:"delete"};function bA(e){return hA[X(e.tool)]??"open"}function Ut(e){return e.every(t=>t===e[0])}var _A={view:"read",create:"write",str_replace:"write",insert:"write",rename:"write",delete:"delete"};function PA(e){if(X(e.tool)!=="memory")return"read";let n=Se(e).command;return n&&_A[n]||"unknown"}var xA={generate:"Made an image",edit:"Edited an image",upscale:"Upscaled an image",remove_bg:"Removed an image background"},SA={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 wA(e){let t=$e(e.replace(/\\/g,"/")),n=t.lastIndexOf("/");return n>=0?t.slice(n+1):t}function AA(e){let t=Se(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 vA(r,60);let o=typeof t.path=="string"?t.path:"";if(o)return wA(o);let s=typeof t.url=="string"?t.url:"";if(s){let i=lA(s);return i?ei(i):"a link"}return""}function vA(e,t=60){let n=e.replace(/\s+/g," ").trim();return n.length>t?n.slice(0,t-1)+"\u2026":n}function kA(e){let t=Se(e).action;return t&&xA[t]||"Worked on an image"}function RA(e){let t=Se(e).action;return t&&SA[t]||"Worked on a presentation"}function CA(e){return e.slice(0,e.indexOf(":"))}var IA={generate:"image:generate",edit:"image:edit",upscale:"image:upscale",remove_bg:"image:remove_bg"},TA={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 EA(e){let t=X(e.tool);if(t==="image_gen"){let n=Se(e).action;return n&&IA[n]||"image:unknown"}if(t==="video_gen")return"video:create";if(t==="presentation_gen"){let n=Se(e).action;return n&&TA[n]||"presentation:unknown"}return"shown:result"}var MA=new Set(["create_slide","export_pdf","export_pptx"]);function TK(e){let t=X(e.tool);if(t==="image_gen")return"image";if(t==="video_gen")return"video";if(t==="presentation_gen"){let n=Se(e).action;return n?MA.has(n)?"presentation":null:"presentation"}return null}var OA={"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`},ih={image:"image",video:"video",presentation:"presentation",shown:"result"};function DA(e){let t={image:0,video:0,presentation:0,shown:0};for(let r of e)t[CA(r)]++;let n=[];return Object.keys(t).forEach(r=>{let o=t[r];o&&n.push(`${o} ${In(o,ih[r],`${ih[r]}s`)}`)}),`Worked on ${ni(n)}`}function ch(e,t){let n=t.length,r=ah(t);switch(e){case"explore":{let o=t.filter(s=>X(s.tool)==="read").length;return o===n?`Read ${n} ${In(n,"file","files")}`:o===0?"Looked through your files":`Looked through your files \xB7 ${o} read`}case"edit":{let o=new Set(t.map(i=>Ve(Se(i))).filter(Boolean)).size||n,s=t.every(i=>X(i.tool)==="write")?"Wrote":"Updated";return o===1?r?`${s} ${r}`:`${s} a file`:`${s} ${o} files`}case"run":return n===1?"Ran a command":`Ran ${n} commands`;case"web":{let o=c=>{let p=X(c.tool);return p==="web_search"||p==="websearch"||p==="image_search"},s=t.filter(o).length;if(s===n)return`Searched the web \xB7 ${n} ${In(n,"query","queries")}`;if(s===0)return`Read ${n} ${In(n,"page","pages")}`;let i=new Set;for(let c of t)if(o(c)){let p=c.state?.output;for(let d of oh(p).flatMap(g=>g.sources))d.url&&i.add(d.url)}else{let p=c.state?.input?.url;typeof p=="string"&&p&&i.add(p)}let a=i.size||n;return`Searched and read ${a} ${In(a,"source","sources")}`}case"create":{if(n===1){let s=t[0],i=X(s.tool);if(i==="image_gen")return kA(s);if(i==="video_gen")return"Made a video";if(i==="presentation_gen")return RA(s);let a=AA(s);return a?`Showed you ${a}`:"Showed you the result"}let o=t.map(EA);return Ut(o)?OA[o[0]](n):DA(o)}case"plan":return n===1?"Planned the work":`Planned the work \xB7 ${n} steps`;case"delegate":{let o=t.map(gA);if(Ut(o))switch(o[0]){case"spawn":return n===1?"Asked a helper agent":`Worked with ${n} helper agents`;case"message":return n===1?"Sent instructions to a helper agent":`Sent instructions to ${n} helper agents`;case"status":return"Checked on a helper agent";case"stop":return n===1?"Stopped a helper agent":`Stopped ${n} helper agents`;case"done":return n===1?"A helper agent finished a task":`Helper agents finished ${n} tasks`;case"delete":return n===1?"Removed a task":`Removed ${n} tasks`}return n===1?"Worked with a helper agent":`Worked with helper agents \xB7 ${n} steps`}case"sessions":return"Checked earlier work";case"memory":{let o=t.map(PA);if(Ut(o))switch(o[0]){case"write":return n===1?"Wrote to its memory":`Wrote to its memory \xB7 ${n} updates`;case"delete":return n===1?"Deleted from its memory":`Deleted ${n} things from its memory`;case"read":return"Recalled what you told it before"}return"Worked with its memory"}case"connectors":{let o=t.map(yA);if(Ut(o))switch(o[0]){case"connect":return n===1?r?`Connected to ${r}`:"Connected a connector":`Connected ${n} connectors`;case"call":return n===1?"Used a connector":`Made ${n} connector calls`;case"read":return"Checked your connectors"}return"Worked with your connectors"}case"automations":{let o=t.map(mA);if(Ut(o))switch(o[0]){case"create":return n===1?"Set up an automation":`Set up ${n} automations`;case"update":return n===1?"Updated an automation":`Updated ${n} automations`;case"delete":return n===1?"Deleted an automation":`Deleted ${n} automations`;case"control":return n===1?"Adjusted an automation":`Adjusted ${n} automations`;case"test":return n===1?"Tested an automation":`Tested ${n} automations`;case"read":return"Checked your automations";case"unknown":return"Worked with your automations"}return"Worked with your automations"}case"projects":{let o=t.map(bA);if(Ut(o))switch(o[0]){case"delete":return n===1?"Tried to delete a project \u2014 deletion isn't allowed":`Tried to delete ${n} projects \u2014 deletion isn't allowed`;case"create":return n===1?r?`Created ${r}`:"Created a project":`Created ${n} projects`;case"update":return n===1?r?`Updated ${r}`:"Updated your project":`Updated ${n} projects`;case"open":return n===1?r?`Opened ${r}`:"Opened your project":`Opened ${n} projects`}return r?`Worked in ${r}`:"Worked in your project"}case"skills":return n===1?r?`Used the ${r} skill`:"Used a skill":`Used ${n} skills`;case"ask":return"Asked you a question";case"retired":return"Used a connector that has since been removed";case"other":{if(n===1)return`Used ${Qr(t[0].tool)}`;let o=Array.from(new Set(t.map(s=>Qr(s.tool))));return o.length===1?`Used ${o[0]} \xB7 ${n} times`:`Used ${ni(o)}`}}}function lh(e,t){let n=ah(t);switch(e){case"explore":return"Couldn't read your files";case"edit":{if(t.length===1){let r=X(t[0].tool)==="write"?"write":"update";return n?`Couldn't ${r} ${n}`:`Couldn't ${r} a file`}return"Couldn't update some files"}case"run":return"A command failed";case"web":return"Couldn't finish searching the web";case"create":return"Couldn't finish making that";case"plan":return"Couldn't update the plan";case"delegate":return"A helper agent hit a problem";case"sessions":return"Couldn't check earlier work";case"memory":return"Couldn't reach its memory";case"connectors":return"Couldn't reach a connector";case"automations":return"Hit a problem with your automations";case"projects":return"Hit a problem with your project";case"skills":return"Couldn't use a skill";case"ask":return"Couldn't ask you a question";case"retired":return"Used a connector that has since been removed";case"other":{let r=t.filter(i=>i.state?.status==="error"),o=r.length?r:t,s=Array.from(new Set(o.map(i=>Qr(i.tool))));return`Couldn't finish using ${ni(s)}`}}}function jA(e){return e.some(t=>t.state?.status==="running"||t.state?.status==="pending")?"running":e.some(t=>t.state?.status==="error")?"error":"done"}function $A(e){let t=Number.POSITIVE_INFINITY,n=0;for(let r of e){let o=r.state.time;typeof o?.start=="number"&&(t=Math.min(t,o.start)),typeof o?.end=="number"&&(n=Math.max(n,o.end))}if(!(!Number.isFinite(t)||n<=t))return n-t}function uh(e,t){let n=jA(t);return{id:t[0].callID,family:e,label:n==="error"?lh(e,t):ch(e,t),parts:t,status:n,durationMs:n==="running"?void 0:$A(t)}}function ph(e){let t=[],n=null,r=[],o=()=>{n&&r.length&&t.push(uh(n,r)),n=null,r=[]};for(let s of e){let i=ti(s.tool);if(i!=="hidden"&&!os(s)){if(Em(s.tool)){o(),t.push(uh(i,[s]));continue}i!==n&&(o(),n=i),r.push(s)}}return o(),t}function UA(e){let t=e.time?.end;return!(typeof t=="number"&&t>0)}function UK(e,t){let n=[],r=null,o=[],s=()=>{if(r&&r.texts.length>0){let{startedAt:a,endedAt:c}=r,p=typeof a=="number"&&typeof c=="number"&&c>a?c-a:void 0;n.push({kind:"thought",key:r.key,texts:r.texts,running:r.running,durationMs:p})}r=null},i=()=>{if(o.length!==0){for(let a of ph(o))n.push(a.parts.length===1?{kind:"part",key:a.parts[0].id,part:a.parts[0]}:{kind:"group",key:`group-${a.parts[0].id}`,step:a});o=[]}};for(let a of e)if(t(a)!=="plumbing"){if(Le(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=UA(a);continue}if(s(),ne(a)){o.push(a);continue}i(),n.push({kind:"part",key:a.id,part:a})}s(),i();for(let a=0;a<n.length-1;a++){let c=n[a];c.kind==="thought"&&(c.running=!1)}return n}var LA=/^(thinking|thought|considering|planning|deciding|weighing|exploring|analy[sz]ing|reasoning|working out|figuring)/i;function FA(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 LK(e){let t=e.flatMap(o=>{let s=FA(o);return s?[s]:[]}).join(" ").trim();return t?LA.test(t)?t:`Thinking about ${/^[A-Z][a-z]/.test(t)?t[0].toLowerCase()+t.slice(1):t}`:"Thinking"}function NA(e){return e?.info?.time??{}}function NK(e){let t=NA(e).created;return typeof t!="number"||!Number.isFinite(t)||t<=0?null:t}var Xr=6e4,KA=10080*Xr,dh=1440;function gh(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 qA(e,t){let n=t.getTime()-e.getTime(),r=n/Xr,o=(i,a)=>`${i} ${a}${i===1?"":"s"} ago`;if(r<60)return o(Math.round(r),"minute");if(r<dh)return o(Math.round(r/60),"hour");let s=(n-(gh(t)-gh(e)))/Xr;return o(Math.round(s/dh),"day")}function yh(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 mh=new Map;function BA(e,t){let n={...e,...t.timeZone?{timeZone:t.timeZone}:{}},r=`${t.locale??""}|${JSON.stringify(n)}`,o=mh.get(r);return o||(o=new Intl.DateTimeFormat(t.locale,n),mh.set(r,o)),o}function Jr(e,t,n){return BA(t,n).formatToParts(e).map(r=>r.type==="dayPeriod"?GA(r.value,n):r.value).join("")}function GA(e,t){let n=/^([ap])\.?\s?m\.?$/i.exec(e.trim());return n?`${n[1].toUpperCase()}M`:e.toLocaleUpperCase(t.locale)}function fh(e,t){return Jr(e,{year:"numeric"},t)}function KK(e,t,n={}){let r=yh(e);if(!r)return"";let o=i=>Jr(r,{month:"long",day:"numeric",...i?{year:"numeric"}:{}},n);if(t===null)return o(!0);let s=Math.max(0,t-r.getTime());return s<Xr?"just now":s<KA?qA(r,new Date(t)):o(fh(r,n)!==fh(new Date(t),n))}function qK(e,t={}){let n=yh(e);if(!n)return"";let r=Jr(n,{month:"long",day:"numeric",year:"numeric"},t),o=Jr(n,{hour:"numeric",minute:"2-digit"},t);return`${r} ${o}`}function HK(e,t={}){let n=[],r=[],o=()=>{r.length>0&&(n.push({kind:"burst",parts:r}),r=[])};for(let s of e)if(!Mm(s)){if(Ue(s)){o(),n.push({kind:"text",part:s});continue}if(ne(s)&&(Om(s.tool)||!!t.standaloneCallIds?.has(s.callID))){o(),n.push({kind:"standalone",part:s});continue}r.push(s)}return o(),n}function WA(e){let t=pe(e);return t==="show"||t==="show_user"}function QK(e,t={}){let n=[],r=[],o=()=>{r.length===1?n.push(r[0]):r.length>1&&n.push({kind:"show-group",parts:r.map(s=>s.part)}),r=[]};for(let s of e){if(s.kind==="standalone"&&WA(s.part.tool)&&!t.standaloneCallIds?.has(s.part.callID)){r.push(s);continue}o(),n.push(s)}return o(),n}var HA=["title","description","path","url","content","language","aspect_ratio","attachment"];function hh(e,t){if(!t||typeof t!="object")return null;let n=t;if(Ar(n))return null;let r={callID:e,status:"ready",type:typeof n.type=="string"?n.type:""};for(let o of HA){let s=n[o];typeof s=="string"&&s&&(r[o]=s)}return r}function VA(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 XK(e){let t=[];for(let n of e){let r=n.state,o=r.input??{};if(r.status==="error"){let a=typeof o.title=="string"&&o.title?o.title:void 0;t.push({callID:n.callID,status:"error",type:"error",...a?{title:a}:{},error:typeof r.error=="string"?r.error:""});continue}let s=VA(o.items),i=s?s.map(a=>hh(n.callID,a)).filter(a=>!!a):[hh(n.callID,o)].filter(a=>!!a);if(i.length>0){t.push(...i);continue}(r.status==="running"||r.status==="pending")&&t.push({callID:n.callID,status:"pending",type:""})}return t}function bh(e){return!e.working||e.awaitingUser?!1:e.isRetrying?!0:!e.hasError}var zA=e=>e.time?.completed;function tq(e){return!e.hasPendingTurns||!e.newestAssistantCompleted?!1:e.pendingDelivery||!!e.deliveringBelow||e.activeTurnId!==null&&e.activeTurnId!==e.workingTurnId}function YA(e,t){let n=e.userMessage.info.id;return t.pendingTurnIds.has(n)||e.assistantMessages.length===0&&t.pendingPromptIds.has(n)}function nq(e){let t=e.turns.find(r=>e.deliveringPromptIds.has(r.userMessage.info.id));if(t)return t.userMessage.info.id;let n=e.turns.findIndex(r=>YA(r,e));return n<=0?null:e.turns[n-1].userMessage.info.id}function rq(e){return e.isTurnWorking&&!e.pendingDelivery&&e.activeTurnId===e.turnId}function oq(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 sq(e){return!e.lastTurnWorking||e.workingTurnId===null||e.suppressed?!1:bh({working:!0,hasError:e.workingTurnHasError,isRetrying:e.isRetrying,awaitingUser:e.awaitingUser})}function iq(e,t){for(let n=e.length-1;n>=0;n--){let r=e[n].userMessage.info.id;if(t(r))return e[n].assistantMessages.length===0?r:null}return null}function aq(e){let{turns:t}=e;if(t.length===0)return{workingTurnId:null,pendingTurnIds:[]};let n=-1;for(let a=t.length-1;a>=0;a--)if(t[a].assistantMessages.length>0){n=a;break}let r=t.slice(n+1).map(a=>a.userMessage.info.id),o=a=>({workingTurnId:t[a].userMessage.info.id,pendingTurnIds:t.slice(a+1).map(c=>c.userMessage.info.id)}),s=e.hintMessageId??null;if(s){if(n>=0&&t[n].userMessage.info.id===s)return o(n);let a=r.indexOf(s);if(a>=0)return o(n+1+a)}if(n>=0){let a=t[n],c=a.assistantMessages[a.assistantMessages.length-1];if(!zA(c.info)&&!c.info.error)return o(n)}let i=e.unrunTurnIds;if(r.length>0){for(let a=t.length-1;a>n;a--)if(!i?.has(t[a].userMessage.info.id))return o(a)}return n<0?{workingTurnId:null,pendingTurnIds:r}:o(n)}function pq(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 dq(e,t){return!t||!e?!1:e.type!=="idle"}function gq(e,t){return!e&&!!t}function mq(e){for(let t of e.assistantMessages){let n=t.info;if(n.error)return xe(n.error)?.message||fe(n.error)}}function fq(e){for(let t of e.assistantMessages){let n=t.info;if(n.error)return Ay(n.error)}}function yq(e){for(let t of e.assistantMessages){let n=t.info;if(n.error)return xe(n.error)}}function _h(e){if(e){if(ne(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(Le(e)){let t=e.text?.trimStart();if(t){let n=t.match(/^\*\*(.+?)\*\*/);if(n)return`Thinking about ${n[1].trim()}...`}return"Thinking..."}if(Ue(e))return"Gathering thoughts..."}}function hq(e,t){for(let n=e.length-1;n>=0;n--){let r=e[n].part,o=ne(r)?r:void 0;if(o&&(o.tool==="task"||o.tool==="agent_task"||o.tool==="agent-task"||o.tool==="task_create"||o.tool==="task-create"||o.tool==="task_start"||o.tool==="task-start")&&o.state.status==="running"&&t&&t.length>0){for(let i=t.length-1;i>=0;i--){let a=t[i];if(a.info.role==="assistant")for(let c=a.parts.length-1;c>=0;c--){let p=_h(a.parts[c]);if(p)return p}}return"Handing off to an agent..."}let s=_h(r);if(s)return s}return"Figuring out what\u2019s next..."}function Ph(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 xh=1.2;function Sh(e,t){if(!e)return 0;let n=e.input??0,r=(e.output??0)+(e.reasoning??0),o=e.cache?.read??0,s=e.cache?.write??0,i=Math.max(0,n-o-s),c=[...t.tiers??[],...t.contextOver200k?[t.contextOver200k]:[]].filter(d=>n>d.contextThreshold).sort((d,g)=>g.contextThreshold-d.contextThreshold)[0]??t,p=i/1e6*c.inputPer1M;return p+=r/1e6*c.outputPer1M,o>0&&(p+=o/1e6*(c.cacheReadPer1M??c.inputPer1M)),s>0&&(p+=s/1e6*(c.cacheWritePer1M??c.inputPer1M)),p}function ri(e,t){return e==="codex"||e==="openai-codex"||e==="kortix"&&!!t?.startsWith("codex/")}function wh(e,t,n,r){if(ri(t,n))return 0;let o=e.cost||0;if(o>0)return o;if(!r||!t||!n)return 0;let s=r(t,n);return s?Sh(e.tokens,s):0}function Ah(e){if(e.role!=="assistant")return{};let t=e;return{providerID:t.providerID,modelID:t.modelID}}function bq(e,t){let n=0,r=0,o=0,s=0,i=0,a=0,c=!1;for(let{part:p,message:d}of e)if(p.type==="step-finish"){c=!0;let g=p,{providerID:m,modelID:f}=Ah(d.info);n+=wh(g,m,f,t),r+=g.tokens?.input||0,o+=g.tokens?.output||0,s+=g.tokens?.reasoning||0,i+=g.tokens?.cache?.read||0,a+=g.tokens?.cache?.write||0}if(!c){let p=new Set;for(let{message:d}of e){if(d.info.role!=="assistant")continue;let g=d.info;if(p.has(g.id))continue;p.add(g.id);let m=vh(g,t),f=g.tokens&&ri(g.providerID,g.modelID);if(m<=0&&!f)continue;c=!0,n+=m;let h=g.tokens;h&&(r+=h.input??0,o+=h.output??0,s+=h.reasoning??0,i+=h.cache?.read??0,a+=h.cache?.write??0)}}if(c)return{cost:n*xh,tokens:{input:r,output:o,reasoning:s,cacheRead:i,cacheWrite:a}}}function vh(e,t){if(ri(e.providerID,e.modelID)||!t||!e.providerID||!e.modelID||!e.tokens)return 0;let n=t(e.providerID,e.modelID);return n?Sh({input:e.tokens.input,output:e.tokens.output,reasoning:e.tokens.reasoning,cache:e.tokens.cache},n):0}function _q(e,t){let n=0;for(let r of e){if(r.info?.role!=="assistant")continue;let o=r.info,{providerID:s,modelID:i}=Ah(o),a=0,c=!1;for(let p of r.parts)p.type==="step-finish"&&(c=!0,a+=wh(p,s,i,t));c||(a+=vh(o,t)),n+=a}return n*xh}function Pq(e){return e===0?"$0.00":e<.001?`$${e.toFixed(4)}`:e<.01?`$${e.toFixed(3)}`:`$${e.toFixed(2)}`}function xq(e){return e<1e3?String(e):e<1e4?`${(e/1e3).toFixed(1)}k`:`${Math.round(e/1e3)}k`}function Sq(e){if(!e||e.type!=="retry")return;let t=e,n=fe(t.message);return{attempt:t.attempt,message:n.length>60?`${n.slice(0,60)}...`:n,next:t.next,details:xe(t.message)}}function wq(e){if(!(!e||e.type!=="retry"))return fe(e.message)}function Aq(e){return(e.info.summary?.diffs?.length??0)>0}function kh(e){if(e.kind==="show-group")return!0;if(e.kind!=="standalone")return!1;let t=pe(e.part.tool);return t==="show"||t==="show_user"}function QA(e){return e.kind==="text"&&!e.part.text?.trim()}function Cq(e,t){if(t.working)return null;let n=-1;for(let o=e.length-1;o>=0;o--){let s=e[o];if(!(kh(s)||QA(s))){s.kind==="text"&&(n=o);break}}let r={work:[],hoisted:[],final:[]};return e.forEach((o,s)=>{s===n?r.final.push(o):kh(o)?r.hoisted.push(o):r.work.push(o)}),r.work.length>0?r:null}function Iq(e){let t=e==null?"":Ph(e);return t?`Worked for ${t}`:"Worked"}function XA(e){let t=e.userMessage.parts;if(t.length===0||!t.every(s=>Ue(s)&&s.synthetic)||e.assistantMessages.length!==1)return!1;let r=e.assistantMessages[0].parts;if(r.length!==1)return!1;let o=r[0];return ne(o)&&o.tool==="bash"}function Mq(e){if(XA(e))return e.assistantMessages[0].parts[0]}function jq(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=Ey(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 $q(e){return e?e.split(`
82
+ `).filter(n=>n.trim()).length<=3:!1}function Uq(e){if(!e)return null;let n=e.split(`
83
+ `).filter(r=>r.trim()&&!r.startsWith("#"))[0]?.replace(/^\*\*.*?\*\*\s*/,"").trim();return n?n.length>120?n.slice(0,120).trim()+"\u2026":n:null}function Lq(e){if(!e)return[];let t=[],n=e.split(`
84
+ `).filter(r=>r.trim());for(let r of n){let o=jy(r);if(o){let s=r.match(/\bses_[a-zA-Z0-9]+/);t.push({...o,sessionId:s?.[0]})}}return t}var dt={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 Nq(e,t){let n=dt[e];return t==="running"?n.running:t==="failed"?n.failed:n.verb}function Kq(e,t){return t?"failed":e?"running":"done"}var Gq={view:"View",create:"Create",str_replace:"Edit",insert:"Insert",delete:"Delete",rename:"Rename"};function Wq(e){return e?e.replace(/^\.\//,"").replace(/^(?:\.kortix\/)?memory(?:\/|$)/,"").replace(/\/$/,"")||"memory":""}function Hq(e,t){if(!e)return null;let n=e.indexOf(`
85
+ `),r=n===-1?e:e.slice(0,n),o=n===-1?"":e.slice(n+1);if(Oy(r,"content of "," with line numbers"))return{type:"file",content:o.split(`
86
86
  `).map(i=>i.replace(/^\s*\d+(\t|$)/,"")).join(`
87
87
  `)};if(/files and directories/i.test(r)){let s=t.replace(/\/$/,""),i=[];for(let a of o.split(`
88
- `)){if(!a.trim())continue;let c=a.indexOf(" ");if(c===-1)continue;let p=a.slice(0,c).trim(),d=a.slice(c+1).trim();d!==s&&i.push({size:p,path:d,isDir:!/\.\w+$/.test(d)})}return{type:"dir",entries:i}}return null}var yv={add:{...ot.write,icon:"create"},delete:{...ot.delete,icon:"delete"},move:{...ot.rename,icon:"edit"},update:{...ot.edit,icon:"edit"}},sh={...ot.change,icon:"edit"};function XK(e){if(e.length===0)return sh;let t=ih(e[0]);for(let n=1;n<e.length;n++)if(ih(e[n])!==t)return sh;return yv[t]}function ih(e){return e==="add"||e==="delete"||e==="move"?e:"update"}function ZK(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 tq(e,t){if(!e)return null;let n=/"([^"]*)"="([^"]*)"/g,r=[],o;for(;(o=n.exec(e))!==null;)r.push(o[2]);return r.length===0?null:Array.from({length:Math.max(t,r.length)},(s,i)=>r[i]?[r[i]]:[])}function oq(e){if(!e)return null;let t=yn(e,"<path>","</path>"),n=t!==null?t.trim():void 0,r=Ds(e,"content");if(r!==null){let s=r.split(`
88
+ `)){if(!a.trim())continue;let c=a.indexOf(" ");if(c===-1)continue;let p=a.slice(0,c).trim(),d=a.slice(c+1).trim();d!==s&&i.push({size:p,path:d,isDir:!/\.\w+$/.test(d)})}return{type:"dir",entries:i}}return null}var JA={add:{...dt.write,icon:"create"},delete:{...dt.delete,icon:"delete"},move:{...dt.rename,icon:"edit"},update:{...dt.edit,icon:"edit"}},Rh={...dt.change,icon:"edit"};function Yq(e){if(e.length===0)return Rh;let t=Ch(e[0]);for(let n=1;n<e.length;n++)if(Ch(e[n])!==t)return Rh;return JA[t]}function Ch(e){return e==="add"||e==="delete"||e==="move"?e:"update"}function Xq(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 Zq(e,t){if(!e)return null;let n=/"([^"]*)"="([^"]*)"/g,r=[],o;for(;(o=n.exec(e))!==null;)r.push(o[2]);return r.length===0?null:Array.from({length:Math.max(t,r.length)},(s,i)=>r[i]?[r[i]]:[])}function nB(e){if(!e)return null;let t=An(e,"<path>","</path>"),n=t!==null?t.trim():void 0,r=Gs(e,"content");if(r!==null){let s=r.split(`
89
89
  `).map(i=>i.replace(/^\s*\d+:\s?/,"")).join(`
90
- `);return{path:n,type:"file",content:s}}let o=Ds(e,"entries");if(o!==null){let s=o.split(`
91
- `).map(i=>i.trim()).filter(i=>i&&!/^\(\d+\s+entr/i.test(i));return{path:n,type:"directory",entries:s}}return null}function aq(e){let t=uy(e,"skill_content");return t!==null?t.trim():e}function hv(e){let t=yn(e,"<skill_files>","</skill_files>");return t===null?[]:dy(t,"<file>","</file>").map(n=>n.trim())}function bv(e){let t=ly(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 _v(e){return my(e,["Base directory","Directory","Skill directory"])?.trim()??""}function Pv(e){return Te(bv(e)||_v(e))}function cq(e){for(let t of["dir","directory","path","skillPath","location"]){let n=e[t];if(typeof n=="string"&&n.trim())return Te(n.trim())}return""}var xv="skills";function Sv(e){let t=cy(e?.trim()??"");if(!t||t.toLowerCase()==="skill")return"";let n=t.split("/").map(o=>o.trim());if(n.some(o=>o===".."||o==="."))return"";let r=n.at(-1)??"";return r?`${xv}/${r}`:""}function lq(e,t,n){let o=Te(t?.trim()??"")||Pv(e)||Sv(n),s=hv(e).find(i=>/(^|\/)SKILL\.md$/i.test(i));if(s){if(s.startsWith("/"))return s;if(o)return`${o}/${s}`}return o?`${o}/SKILL.md`:null}var wv=4e3;function Sn(e,t=wv){return e.length>t?`${e.slice(0,t)}
92
- \u2026`:e}function ah(e){if(e!==void 0)try{return Sn(JSON.stringify(e,null,2))}catch{return}}function W(...e){for(let t of e)if(typeof t=="string"&&t.length>0)return t}function st(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}function vv(e){let t=W(e.input?.query)??"";if(e.status==="error")return{kind:"web-search",query:t,error:e.error??"Search failed"};let n=st(e.outputParsed);if(!n)return{kind:"web-search",query:t};let o=(Array.isArray(n.results)?n.results:Array.isArray(n.images)?n.images:[]).slice(0,50).map(s=>{let i=st(s)??{};return{title:W(i.title)??"",url:W(i.url,i.link)??"",snippet:W(i.snippet,i.description,i.source)}});return{kind:"web-search",query:W(n.query)??t,results:o.length>0?o:void 0,answer:W(n.answer)}}var Av=/<exit_code>\s*(-?\d+)\s*<\/exit_code>/;function lh(e){let t=e.match(Av);return t?Number(t[1]):void 0}function kv(e,t,n){let r="",o=0;for(;;){let s=e.indexOf(t,o);if(s===-1)return r+e.slice(o);let i=e.indexOf(n,s+t.length);if(i===-1)return r+e.slice(o);r+=e.slice(o,s),o=i+n.length}}var Rv=["<system_info>","</system_info>","<exit_code>","</exit_code>","<stderr_note>","</stderr_note>"];function Iv(e){let t=-1;for(let n of Rv){let r=e.indexOf(n);r!==-1&&(t===-1||r<t)&&(t=r)}return t===-1?e:e.slice(0,t)}var Cv=/\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 Tv(e){return e.replace(Cv,"")}function Ev(e){let t=W(e.input?.command)??"",n=e.output??"",r=lh(n),s=Tv(Iv(kv(n,"<bash_metadata>","</bash_metadata>"))).trim()||(e.status==="error"?e.error:void 0);return{kind:"shell",command:t,stdout:s||void 0,exitCode:r}}function Ys(e){return W(e.input?.filePath,e.input?.file_path,e.input?.path)??""}function Mv(e){let t=e.status==="error"?e.error:e.output&&Sn(e.output)||void 0;return{kind:"file-read",path:Ys(e),preview:t}}function Ov(e){let t=W(e.input?.content),n=e.status==="error"?e.error:Sn(t??e.output??"")||void 0;return{kind:"file-write",path:Ys(e),preview:n}}var Dv=256*1024;function jv(e,t){if(e.length+t.length>Dv)return;let n=e.split(`
90
+ `);return{path:n,type:"file",content:s}}let o=Gs(e,"entries");if(o!==null){let s=o.split(`
91
+ `).map(i=>i.trim()).filter(i=>i&&!/^\(\d+\s+entr/i.test(i));return{path:n,type:"directory",entries:s}}return null}function sB(e){let t=Ty(e,"skill_content");return t!==null?t.trim():e}function ZA(e){let t=An(e,"<skill_files>","</skill_files>");return t===null?[]:My(t,"<file>","</file>").map(n=>n.trim())}function ev(e){let t=Iy(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 tv(e){return Dy(e,["Base directory","Directory","Skill directory"])?.trim()??""}function nv(e){return $e(ev(e)||tv(e))}function iB(e){for(let t of["dir","directory","path","skillPath","location"]){let n=e[t];if(typeof n=="string"&&n.trim())return $e(n.trim())}return""}var rv="skills";function ov(e){let t=Cy(e?.trim()??"");if(!t||t.toLowerCase()==="skill")return"";let n=t.split("/").map(o=>o.trim());if(n.some(o=>o===".."||o==="."))return"";let r=n.at(-1)??"";return r?`${rv}/${r}`:""}function aB(e,t,n){let o=$e(t?.trim()??"")||nv(e)||ov(n),s=ZA(e).find(i=>/(^|\/)SKILL\.md$/i.test(i));if(s){if(s.startsWith("/"))return s;if(o)return`${o}/${s}`}return o?`${o}/SKILL.md`:null}var sv=4e3;function Tn(e,t=sv){return e.length>t?`${e.slice(0,t)}
92
+ \u2026`:e}function Ih(e){if(e!==void 0)try{return Tn(JSON.stringify(e,null,2))}catch{return}}function W(...e){for(let t of e)if(typeof t=="string"&&t.length>0)return t}function gt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}function iv(e){let t=W(e.input?.query)??"";if(e.status==="error")return{kind:"web-search",query:t,error:e.error??"Search failed"};let n=gt(e.outputParsed);if(!n)return{kind:"web-search",query:t};let o=(Array.isArray(n.results)?n.results:Array.isArray(n.images)?n.images:[]).slice(0,50).map(s=>{let i=gt(s)??{};return{title:W(i.title)??"",url:W(i.url,i.link)??"",snippet:W(i.snippet,i.description,i.source)}});return{kind:"web-search",query:W(n.query)??t,results:o.length>0?o:void 0,answer:W(n.answer)}}var av=/<exit_code>\s*(-?\d+)\s*<\/exit_code>/;function Eh(e){let t=e.match(av);return t?Number(t[1]):void 0}function cv(e,t,n){let r="",o=0;for(;;){let s=e.indexOf(t,o);if(s===-1)return r+e.slice(o);let i=e.indexOf(n,s+t.length);if(i===-1)return r+e.slice(o);r+=e.slice(o,s),o=i+n.length}}var lv=["<system_info>","</system_info>","<exit_code>","</exit_code>","<stderr_note>","</stderr_note>"];function uv(e){let t=-1;for(let n of lv){let r=e.indexOf(n);r!==-1&&(t===-1||r<t)&&(t=r)}return t===-1?e:e.slice(0,t)}var pv=/\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 dv(e){return e.replace(pv,"")}function gv(e){let t=W(e.input?.command)??"",n=e.output??"",r=Eh(n),s=dv(uv(cv(n,"<bash_metadata>","</bash_metadata>"))).trim()||(e.status==="error"?e.error:void 0);return{kind:"shell",command:t,stdout:s||void 0,exitCode:r}}function si(e){return W(e.input?.filePath,e.input?.file_path,e.input?.path)??""}function mv(e){let t=e.status==="error"?e.error:e.output&&Tn(e.output)||void 0;return{kind:"file-read",path:si(e),preview:t}}function fv(e){let t=W(e.input?.content),n=e.status==="error"?e.error:Tn(t??e.output??"")||void 0;return{kind:"file-write",path:si(e),preview:n}}var yv=256*1024;function hv(e,t){if(e.length+t.length>yv)return;let n=e.split(`
93
93
  `),r=t.split(`
94
- `),o=0;for(;o<n.length&&o<r.length&&n[o]===r[o];)o++;let s=n.length,i=r.length;for(;s>o&&i>o&&n[s-1]===r[i-1];)s--,i--;let a=[];for(let c=0;c<o;c++)a.push({type:"unchanged",text:n[c]});for(let c=o;c<s;c++)a.push({type:"removed",text:n[c]});for(let c=o;c<i;c++)a.push({type:"added",text:r[c]});for(let c=s;c<n.length;c++)a.push({type:"unchanged",text:n[c]});return a}function $v(e){let t=W(e?.oldString),n=W(e?.newString);return t!==void 0&&n!==void 0?[[t,n]]:(Array.isArray(e?.edits)?e.edits:[]).flatMap(o=>{let s=st(o),i=s&&W(s.oldText),a=s&&W(s.newText);return i!==void 0&&a!==void 0?[[i,a]]:[]})}function Uv(e){let t=$v(e.input),n=t.map(([o,s])=>jv(o,s)),r=t.length&&n.every(Boolean)?n.flatMap(o=>o??[]):void 0;return{kind:"file-edit",path:Ys(e),diff:r}}var uh=/^Found\s+(\d+)\s+match/i,Fv=/^(\/[^:]+?):\s*/,ch=/Line\s+(\d+):/g;function Lv(e){let t=e.trim(),n=t.match(uh),r=n?t.slice(n[0].length).trim():t;if(!r)return[];let o=[];for(let s of r.split(/\n\n+/)){let i=s.trim();if(!i)continue;let a=i.match(Fv);if(!a)continue;let c=a[1],p=i.slice(a[0].length),d=[],g;for(ch.lastIndex=0;(g=ch.exec(p))!==null;)d.push({line:Number(g[1]),contentStart:g.index+g[0].length,headerStart:g.index});for(let m=0;m<d.length;m++){let f=m+1<d.length?d[m+1].headerStart:p.length,h=p.slice(d[m].contentStart,f).trim();o.push({path:c,line:d[m].line,content:h.endsWith(";")?h.slice(0,-1):h})}}return o}function Nv(e){return e.trim().split(`
95
- `).map(t=>t.trim()).filter(t=>t.startsWith("/")||t.startsWith("./")||t.startsWith("~")).map(t=>({path:t}))}function Kv(e){let t=W(e.input?.pattern,e.input?.query)??"";if(e.status==="error"||!e.output)return{kind:"search",pattern:t};let n=uh.test(e.output.trim())?Lv(e.output):Nv(e.output);return{kind:"search",pattern:t,matches:n.length>0?n.slice(0,200):void 0}}function qv(e){let t=W(e.input?.description,e.input?.title,e.input?.prompt)??e.title,n=W(e.input?.subagent_type,e.input?.agent);return{kind:"task",description:t,agent:n}}function zs(e){let t=st(e)??{};return{content:W(t.content)??"",status:W(t.status)??"pending",priority:W(t.priority)}}function Gv(e){let t=e.input?.todos;if(Array.isArray(t))return{kind:"todo",items:t.map(zs)};if(Array.isArray(e.outputParsed))return{kind:"todo",items:e.outputParsed.map(zs)};let n=st(e.outputParsed);return n&&Array.isArray(n.todos)?{kind:"todo",items:n.todos.map(zs)}:{kind:"todo",items:[]}}function Bv(e){return{kind:"question",questions:(Array.isArray(e.input?.questions)?e.input.questions:[]).map(r=>{let o=st(r)??{},i=(Array.isArray(o.options)?o.options:[]).flatMap(a=>{let c=st(a),p=c&&W(c.label);return p?[{label:p,description:c?W(c.description):void 0}]:[]});return{question:W(o.question)??"",header:W(o.header),options:i}})}}function Wv(e){let n=e.input&&Object.keys(e.input).length>0?ah(e.input):void 0,r;return e.outputParsed!==void 0?r=typeof e.outputParsed=="string"?Sn(e.outputParsed):ah(e.outputParsed):e.outputText!==void 0?r=Sn(e.outputText):r=e.error,{kind:"generic",label:e.title,inputPretty:n,outputPretty:r}}function Hv(e){switch(re(e.name)){case"web_search":return vv(e);case"bash":return Ev(e);case"read":return Mv(e);case"write":return Ov(e);case"edit":return Uv(e);case"grep":case"glob":return Kv(e);case"task":return qv(e);case"todowrite":return Gv(e);case"question":return Bv(e);default:return Wv(e)}}var Vv=new Set(["AbortError","MessageAbortedError"]),zv=["operation was aborted","aborted by user","interrupted by user","cancelled by user","canceled by user","request was cancelled","request was canceled","aborterror"],Yv=["unreachable","upstream","econnreset","econnrefused","socket hang up","network","fetch failed","timed out","timeout","gateway","502","503","504"];function ph(e){let t=e.toLowerCase();return Yv.some(n=>t.includes(n))?!1:zv.some(n=>t.includes(n))}function Qv(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 Br(e){if(typeof e=="string")return ph(e);if(!e||typeof e!="object")return!1;let t=e,n=t.name;if(typeof n=="string"&&Vv.has(n))return!0;let r=Qv(t);return typeof r=="string"?ph(r):!1}var Xv=["user","runtime-disposed","orphan-finalized","wake"],gq=["orphan-finalized","wake"];function mq(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 Xv.includes(n)?n:void 0}var Wr="kortix-active-instance",Jv=["/dashboard","/agents","/p","/workspace","/settings","/browser","/desktop","/services","/sessions","/terminal","/files","/scheduled-tasks","/commands","/tools","/configuration","/changelog","/legacy","/credits-explained"];function Zv(e){return Jv.some(t=>e===t||e.startsWith(`${t}/`))}function wn(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 yq(e){let t=wn(e);return!!t&&t.innerPath===""}function hq(e){let t=wn(e);return!t||!t.innerPath?e:t.innerPath}function eA(e,t){if(!e)return t;if(t.startsWith("/")||(t=`/${t}`),t.startsWith("/instances/")){let n=wn(t);return n?`/instances/${encodeURIComponent(e)}${n.innerPath}`:t}return Zv(t)?`/instances/${encodeURIComponent(e)}${t}`:t}function tA(e){return e?wn(e)?.instanceId??null:null}function bq(){return typeof window>"u"?null:tA(window.location.pathname)||nA()}function nA(){if(typeof document>"u")return null;let e=document.cookie.match(new RegExp(`(?:^|; )${Wr}=([^;]+)`));return e?decodeURIComponent(e[1]):null}function _q(e){if(typeof document>"u")return;let t=n=>{document.cookie=n};if(typeof window<"u"&&window.location.pathname.startsWith("/projects")){t(`${Wr}=; Max-Age=0; Path=/; SameSite=Lax`);return}if(!e){t(`${Wr}=; Max-Age=0; Path=/; SameSite=Lax`);return}t(`${Wr}=${encodeURIComponent(e)}; Path=/; SameSite=Lax`)}function Pq(e,t){return t?eA(t,e):e}function xq(e){let t=wn(e);return t?t.innerPath||"/dashboard":e}function vn(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 dh(e){let t=vn(e).trim();if(!t)return null;let n=[t,t.replace(/^Failed to perform action:\s*/i,"").trim()],r=t.indexOf("{");r>=0&&n.push(t.slice(r));for(let o of n)if(o)try{return JSON.parse(o)}catch{}return null}var wq=dh;function Qs(e){let t=dh(e);if(!t||typeof t!="object")return null;let n=t;return n.name==="ConfigInvalidError"?n:null}var vq=Qs;function rA(e){return Qs(e)!==null}var Aq=rA,oA=[/sandbox not ready/i,/sandbox is not (?:ready|running)/i,/opencode (?:session )?(?:is )?not ready/i,/\bsandbox_not_ready\b/,/\bsandbox_lifecycle_unavailable\b/],kq=["runtime_not_ready","sandbox runtime not ready","opencode not ready"],sA=/\bruntime_not_ready\b|sandbox runtime not ready|opencode not ready/i;function iA(e){return sA.test(vn(e))}function An(e){let t=vn(e);return t?iA(t)||oA.some(n=>n.test(t)):!1}var aA=/server url not ready|sandbox is still loading/i;function Rq(e){return aA.test(vn(e))||An(e)}var Hr=class extends Error{constructor(t){let n=t?.trim();super(n&&An(n)?n:n?`sandbox not ready: ${n}`:"sandbox not ready"),this.name="SandboxNotReadyError"}};function cA(e){let t=Qs(e);if(t){let o=(t.data?.path??"OpenCode config").replace(/^\/workspace\//,""),s=t.data?.issues?.[0]?.message,i=t.data?.issues?.[0]?.path?.join("."),a=i?.startsWith("permission")?"Remove the invalid permission frontmatter entry or replace it with valid OpenCode permission config.":"Fix the invalid config entry, then restart this session.";return{title:"OpenCode config is invalid",message:`${o} is preventing OpenCode from loading. ${a}`,detail:s?`${i?`${i}: `:""}${s}`:void 0}}let n=vn(e);return An(n)?{title:"Session is waking up",message:"This session slept to save compute. Your conversation is safe \u2014 sending a message wakes it back up."}:{title:"The session runtime failed to load",message:n||"The sandbox is running, but its runtime returned an error."}}var Iq=cA;function gh(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`${Ue()}/p/${e.external_id}/${$e.KORTIX_MASTER}`}function Mq(e,t){return e.external_id?`${Ue()}/p/${e.external_id}/${t}`:null}async function Uq(){let e=await l.get("/setup/sandbox-providers");if(e.error)throw e.error;return e.data}async function lA(e){let t=await Qe();if(t)return{sandbox:t.sandbox,created:!1};let r=(await dt())[0];if(!r)throw new Error("Create a project before starting a sandbox");let o=await ht(r.project_id,{...e?.provider?{provider:e.provider}:{}}),s=(await Ye(r.project_id,o.session_id))?.sandbox??null;return{sandbox:es(r,o,s),created:!0}}async function Fq(){return(await Qe().catch(()=>null))?.sandbox??null}async function Lq(e){return{sandbox:(await lA(e)).sandbox}}async function Nq(e){let t=Wt(e);return t?(await Qe(t).catch(()=>null))?.sandbox??null:null}async function Kq(e,t){throw await Qe(e)?new Error("Renaming project-session sandboxes is not exposed by the current API"):new Error("Project session sandbox not found")}async function qq(e){let t=Wt(e);return(await ts().catch(()=>[])).map(r=>r.sandbox).filter(r=>!t||r.sandbox_id===t||r.external_id===t)}async function Gq(){return null}async function Bq(e){if(!e)throw new Error("No sandbox selected for workload restart");let t=await Qe(e);if(!t)throw new Error("Project session sandbox not found");await ir(t.project.project_id,t.session.session_id)}async function Wq(e){if(!e)throw new Error("No sandbox selected to stop");let t=await Qe(e);if(!t)throw new Error("Project session sandbox not found");await ar(t.project.project_id,t.session.session_id)}async function Hq(e){throw new Error("Cancellation is not exposed for project-session sandboxes")}async function Vq(e){throw new Error("Reactivation is not exposed for project-session sandboxes")}async function Xs(e,t,n){let r=gh(e),o=await M(`${te(r)}${t}`,{signal:AbortSignal.timeout(8e3),headers:{"Content-Type":"application/json"},...n});if(!o.ok){let s=await o.text().catch(()=>"");throw new Error(s||`Request failed (${o.status})`)}return await o.json()}async function Jq(e,t){return Xs(e,`/kortix/projects/${encodeURIComponent(t)}/members`,{method:"GET"})}async function Zq(e,t,n,r="member"){await Xs(e,`/kortix/projects/${encodeURIComponent(t)}/members`,{method:"POST",body:JSON.stringify({user_id:n,role:r})})}async function eG(e,t,n){await Xs(e,`/kortix/projects/${encodeURIComponent(t)}/members/${encodeURIComponent(n)}`,{method:"DELETE"})}var Js="Use the account invite functions (acceptAccountInvite, declineAccountInvite).";async function rG(e){throw F("getInvite",Js)}async function oG(e){throw F("acceptInvite",Js)}async function sG(e){throw F("declineInvite",Js)}async function aG(e){throw new Error("Backups are not exposed for project-session sandboxes")}async function cG(e,t){throw new Error("Backups are not exposed for project-session sandboxes")}async function lG(e,t){throw new Error("Backups are not exposed for project-session sandboxes")}async function uG(e,t){throw new Error("Backups are not exposed for project-session sandboxes")}async function dG(e){throw new Error("SSH setup is not exposed for project-session sandboxes")}async function gG(e){throw new Error("SSH connection details are not exposed for project-session sandboxes")}var uA=["pulling","patching","stopping","removing","recreating","restarting","verifying","starting","health_check"];function hG(e){return uA.includes(e)}async function bG(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 _G(e){let t=e?`?channel=${e}`:"",r=await(await we(`${Ue()}/platform/sandbox/version/latest${t}`,{headers:{Accept:"application/json"}},{},"Version check failed")).json();try{let o=await pA(e||"stable");r.changelog=o.find(s=>s.version===r.version)??o[0]??null}catch{r.changelog=null}return r}async function pA(e){let t=e?`?channel=${e}`:"";return(await(await we(`${Ue()}/platform/sandbox/version/changelog${t}`,{headers:{Accept:"application/json"}},{},"Changelog fetch failed")).json()).changelog}async function PG(){return(await we(`${Ue()}/platform/sandbox/version/all`,{headers:{Accept:"application/json"}},{},"All versions fetch failed")).json()}async function xG(e,t){throw new Error("Sandbox image updates are managed by project-session provisioning")}async function SG(e){}async function wG(e){}async function kG(e){return{serverTypes:[],location:e||"hel1"}}async function RG(e){throw new Error("Retired instance provisioning is unavailable. Create a project session with daytona, platinum, or e2b.")}async function IG(e){throw F("deleteInstance")}async function CG(e,t){}async function TG(){throw F("claimComputer")}async function EG(e){return null}function MG(e,t){throw F("getSandboxProvisionStreamUrl")}var Vr=class extends Error{constructor(n,r,o){super(n);this.status=r;this.body=o;this.name="HostBoundaryError"}status;body};function mh(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 fh(e){let t=await e.text().catch(()=>"");if(!t)return null;try{return JSON.parse(t)}catch{return t}}function yh(e,t){if(t&&typeof t=="object"){let n=t;for(let r of["error_description","error","message"])if(typeof n[r]=="string"&&n[r])return n[r]}return typeof t=="string"&&t?t:e.statusText||`HTTP ${e.status}`}async function V(e,t,n){let r=n?.body!==void 0,o=await fetch(`${Ht(t.backendUrl)}${e}`,{method:n?.method??"GET",headers:mh(t,r),...r?{body:JSON.stringify(n.body)}:{},...t.signal?{signal:t.signal}:{},...t.cache?{cache:t.cache}:{},...t.next?{next:t.next}:{}}),s=await fh(o);if(!o.ok)throw new Vr(yh(o,s),o.status,s);return s}function dA(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 UG(e,t){return V(`/marketplace/items${dA(t)}`,e)}function FG(e){return V("/marketplace/marketplaces",e)}function LG(e,t){return V(`/marketplace/items/${encodeURIComponent(e)}`,t)}function NG(e,t,n){return V(`/marketplace/items/${encodeURIComponent(e)}/file?path=${encodeURIComponent(t)}`,n)}function KG(e,t){return V("/access/check-email",t,{method:"POST",body:{email:e}})}function qG(e,t){return V("/access/request-access",t,{method:"POST",body:e})}function GG(e){return V("/auth/logout",e,{method:"POST",body:{}})}function BG(e,t){return V(`/oauth/authorize/consent/${encodeURIComponent(e)}`,t)}function WG(e,t){return V("/oauth/authorize/consent",t,{method:"POST",body:{request_id:e.requestId,approved:e.approved}})}function HG(e,t){return V(`/setup-links/connectors/${encodeURIComponent(e)}`,t)}function VG(e,t){return V(`/setup-links/connectors/${encodeURIComponent(e)}/start`,t,{method:"POST",body:{}})}function zG(e,t,n={}){return V(`/setup-links/connectors/${encodeURIComponent(e)}/finalize`,t,{method:"POST",body:n.connectionId?{connection_id:n.connectionId}:{}})}function YG(e,t){return V(`/setup-links/secret/${encodeURIComponent(e)}`,t)}function QG(e,t,n,r){return V(`/setup-links/secret/${encodeURIComponent(e)}`,n,{method:"POST",body:{values:t,...r?.only_requester?{only_requester:!0}:{}}})}function XG(e,t){return V(`/p/public-share/${encodeURIComponent(e)}`,t)}function JG(e,t,n){return V(`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/start`,n,{method:"POST",body:{}})}function ZG(e){return V("/system/maintenance",e)}function eB(e,t){return V("/system/maintenance",t,{method:"PUT",body:e})}function tB(e){return V("/user-roles",e)}function nB(e,t){return V("/system/demo-request",t,{method:"POST",body:e})}async function rB(e,t,n){let r=await fetch(`${Ht(n.backendUrl)}/accounts/${encodeURIComponent(e)}/audit/export?${bt(t)}`,{headers:mh(n,!1),...n.signal?{signal:n.signal}:{}});if(!r.ok){let o=await fh(r);throw new Vr(yh(r,o),r.status,o)}return{blob:await r.blob(),filename:r.headers.get("content-disposition")?.match(/filename="([^"]+)"/)?.[1]??null,capped:r.headers.get("x-audit-capped")==="true",rowCount:r.headers.get("x-audit-row-count"),complete:r.headers.get("x-audit-complete")!=="false",nextCursor:r.headers.get("x-audit-next-cursor")||null}}async function oB(e,t){throw F("openStressTestStream")}function sB(e,t){throw F("buildPublicTemplateUrl")}async function iB(e,t,n){throw F("getPublicTemplate")}var gA="kortix:connect-link:";function Zs(e){let t=2166136261,n=16777619^e.length;for(let r=0;r<e.length;r+=1){let o=e.charCodeAt(r);t=Math.imul(t^o,16777619)>>>0,n=Math.imul(n^o,1540483477)>>>0}return`${gA}${t.toString(36)}${n.toString(36)}`}function cB(e,{storage:t}={}){let n=new Map,r=new Map,o=i=>{if(t)try{let a=t.getItem(Zs(i));if(!a)return;let c=JSON.parse(a);if(Date.parse(c.expires_at)<=Date.now()){t.removeItem(Zs(i));return}return c}catch{return}},s=(i,a)=>{if(t)try{t.setItem(Zs(i),JSON.stringify(a))}catch{}};return{peek(i){let a=r.get(i);if(a)return a;let c=o(i);return c&&r.set(i,c),c},load(i){let a=n.get(i);if(a)return a;let c=e(i).then(p=>(r.set(i,p),s(i,p),p),p=>{throw n.delete(i),p});return n.set(i,c),c}}}var hh="Could not start the connect flow.";async function lB(e){let t;try{t=await e.start()}catch(r){return{kind:"error",message:r instanceof Error?r.message:hh}}if(t.connect_url)return{kind:"popup",url:t.connect_url};if(!t.connected)return{kind:"error",message:hh};let n=null;try{n=(await e.finalize()).connected_as??null}catch{}return{kind:"connected",alreadyConnected:t.already_connected===!0,connectedAs:n}}var mA=3e3,fA=5e3,yA=5*6e4;function uB(e,t){let n=e===0?mA:fA;return t+n>yA?null:n}function pB(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 mB(){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 fB(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 yB(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 hB(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 bB(){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 PB="1";var hA="kortix.query-cache";function _h(e){return!!e&&typeof e.then=="function"}function bh(e){return _h(e)?e:Promise.resolve()}function xB(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 SB(e){let{storage:t,userId:n,shouldPersist:r,version:o="1",maxAgeMs:s=6048e5,maxBytes:i=1e6,throttleMs:a=1e3,namespace:c=hA,now:p=()=>Date.now()}=e,d=`${c}:${n}`,g=null,m=!1,f=null,h=Promise.resolve(),S=()=>{try{return bh(t.removeItem(d)).catch(()=>{})}catch{return Promise.resolve()}},D=(w,P)=>{if(!P)return 0;let A;try{A=JSON.parse(P)}catch{return S(),0}if(!A||A.v!==o||A.user!==n||!Array.isArray(A.queries)||p()-A.at>s)return S(),0;let C=0;for(let T of A.queries){if(!T||!Array.isArray(T.k)||T.d===void 0||typeof T.t!="number"||p()-T.t>s||!r(T.k))continue;let N=w.getQueryState(T.k);N&&N.data!==void 0&&N.dataUpdatedAt>=T.t||(w.setQueryData(T.k,T.d,{updatedAt:T.t}),w.invalidateQueries?.({queryKey:T.k,exact:!0,refetchType:"none"}),C+=1)}return C},j=w=>w.getQueryCache().getAll().filter(P=>P.state.data!==void 0&&r(P.queryKey)).map(P=>({k:P.queryKey,d:P.state.data,t:P.state.dataUpdatedAt})).sort((P,A)=>A.t-P.t),L=(w,P)=>{let A=[],C=0;for(let T of w){let N=JSON.stringify(T).length+1;C+N>P||(A.push(T),C+=N)}return A},y=async w=>{let P=L(j(w),i);for(;;){let A={v:o,user:n,at:p(),queries:P};try{await bh(t.setItem(d,JSON.stringify(A)));return}catch{if(P.length===0)return;P=P.slice(0,Math.floor(P.length/2))}}},_=()=>{f!==null&&(clearTimeout(f),f=null)},x=()=>{_();let w=g;return!w||!m||(m=!1,h=h.then(()=>y(w)).catch(()=>{})),h},E=()=>{m=!0,f===null&&(f=setTimeout(()=>{f=null,x()},a))};return{storageKey:d,restore(w){let P;try{P=t.getItem(d)}catch{return 0}return _h(P)?P.then(A=>D(w,A)).catch(()=>0):D(w,P)},persist(w){g=w,m=!0;let P=w.getQueryCache().subscribe(A=>{A.type!=="updated"&&A.type!=="removed"&&A.type!=="added"||r(A.query.queryKey)&&E()});return()=>{P(),g===w&&(g=null,_())}},flush(){return x()},async clear(){_(),g=null,m=!1,await h,await S()}}}function wB(){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 bA="/kortix/part/";function _A(e){return typeof e=="string"&&e.startsWith(bA)}async function RB(e){if(!_A(e))throw new Error(`not an attachment part reference: ${e}`);let t=Re();if(!t)throw new Error("runtime url not bound");let n=await M(`${t}${e}`);if(!n.ok)throw new Error(`attachment part fetch failed: ${n.status}`);return n.blob()}function Ph(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 PA(e,t){try{let n=new URL(e),r=n.pathname;if(!(/^\/v1\/p\/[^/]+\/\d+(?:\/|$)/.test(r)||/^\/proxy\/\d+(?:\/|$)/.test(r)))return!1;let s=new Set;if(t)try{s.add(new URL(t).origin)}catch{}return typeof window<"u"&&s.add(window.location.origin),s.has(n.origin)}catch{return!1}}function xh(e,t){return PA(e,t)?(t?Ph(t):null)??Ph(e):null}function zr(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 Sh(e,t){try{let n=new URL(e);return n.searchParams.set("token",t),n.toString()}catch{return e}}var xA=/^p\d{1,5}-[a-z0-9-]+\.localhost$/;function SA(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function wA(e,t){if(!t.includes("{port}")||!t.includes("{sandbox}"))return!1;let n=t.indexOf("://");if(n<=0)return!1;let r=t.slice(0,n).toLowerCase();if(r!=="https"&&r!=="http")return!1;let o=(t.slice(n+3).split("/")[0]??"").toLowerCase(),s=`${r}://${o}`.split("{port}").map(i=>i.split("{sandbox}").map(SA).join("[a-z0-9-]+")).join("\\d{1,5}");return new RegExp(`^${s}$`).test(e)}function vA(e){try{let t=new URL(e);return t.hostname==="localhost"||t.hostname==="127.0.0.1"?t:null}catch{return null}}function wh(e){return e.port?e.port:e.protocol==="https:"?"443":"80"}function AA(e,t){let n;try{n=new URL(e)}catch{return!1}return n.protocol!=="https:"&&n.protocol!=="http:"?!1:xA.test(n.hostname)?t.backendUrls.some(r=>{let o=vA(r);return o!==null&&wh(o)===wh(n)}):t.templates.some(r=>wA(n.origin,r))}async function vh(e,t={}){if(!zr(e))return!1;let n=k().backendUrl;n&&await Xe(n).catch(()=>null);let r=[n,t.serverUrl].filter(o=>typeof o=="string"&&o.length>0);return AA(e,{templates:Am(),backendUrls:r})}async function kA(e,t={}){let n=xh(e,t.serverUrl||k().backendUrl||void 0);if(!n)return!1;let r=await Ft();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 FB(e,t={}){if(zr(e)){if(!await vh(e,t))return e;let n=await Ft();return n?Sh(e,n):e}return await kA(e,t),e}var NB=3e3;function RA(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 KB(e,t){if(!e||t?.signal?.aborted)return"unknown";let n=new AbortController,r=()=>n.abort();t?.signal?.addEventListener("abort",r);let o=setTimeout(r,t?.timeoutMs??3e3);try{let s=await fetch(e,{method:"HEAD",credentials:"include",cache:"no-store",signal:n.signal});return RA(s.status)}catch{return"unknown"}finally{clearTimeout(o),t?.signal?.removeEventListener("abort",r)}}function IA(e){let t=e;for(;t.endsWith("/");)t=t.slice(0,-1);return t}function BB(e,t){throw F("buildPresentationTemplatePdfUrl")}function WB(e,t){throw F("buildPresentationTemplateImageUrl")}function CA(e,t){return`${IA(e)}/presentation/convert-to-${t}`}async function HB(e,t,n,r){let o=CA(t,e),s=r?.pollIntervalMs??2500,i=r?.timeoutMs??4*6e4,a=Date.now(),c=!1;for(;;){let p=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({presentation_path:n,download:!0}),...r?.signal?{signal:r.signal}:{}}),d=p.headers.get("content-type")||"";if(p.ok&&(d.includes("pdf")||d.includes("presentation")||d.includes("octet-stream"))){let h=await p.blob();if(h.size===0)throw new Error("Downloaded file is empty");return h}if(p.status===202){if(c||(c=!0,r?.onGenerating?.()),Date.now()-a>i)throw new Error(`Timed out waiting for the ${e.toUpperCase()} to generate`);await new Promise((h,S)=>{let D=setTimeout(h,s);r?.signal?.addEventListener("abort",()=>{clearTimeout(D),S(r.signal?.reason??new DOMException("Aborted","AbortError"))},{once:!0})});continue}let m=await p.text().catch(()=>""),f=p.statusText;try{let h=JSON.parse(m);f=String(h.error||h.detail||h.message||f)}catch{m&&(f=m)}throw new Error(`Failed to download ${e.toUpperCase()}: ${f} (HTTP ${p.status})`)}}function YB(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 QB(e){return e==="unreachable"}function XB(e){return!e||e.status===0?"unknown":e.ok&&vf(e.health)?"live":e.hop==="control_plane"?"waking":e.ok||e.health?.status==="starting"?"connecting":"unreachable"}var TA=1e4,JB={connection:"unknown",faultSinceMs:null};function ZB(e,t,n,r=TA){if(t==="unknown")return e;if(t==="live"||t==="waking")return{connection:t,faultSinceMs:null};let o=e.faultSinceMs??n;return n-o>=r?{connection:t,faultSinceMs:o}:{connection:e.connection==="unknown"?"connecting":e.connection,faultSinceMs:o}}function Ah({optimistic:e,abort:t,inbox:n,server:r,stream:o,activity:s,nowMs:i}){let a=!!e&&i-e.atMs<ei,c=!!t&&i-t.atMs<ri;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<=ti,streamFresh:!!o&&i-o.atMs<=kn,inboxFresh:!!n&&i-n.atMs<=ni,activityFresh:!!s&&i-s.atMs<=kn}}function Tt(e){if(!e)return null;let t=Date.parse(e);return Number.isNaN(t)?null:t}function oi(e,t,n){if(!t)return!1;let r=Tt(e.started_at);if(r===null||r>=t.atMs)return!1;let o=n?.lastEnded,s=Tt(o?.ended_at);return!(o&&s!==null&&Math.abs(s-t.atMs)<=1e3&&o.turn_token!==e.turn_token)}function EA(e,t,n,r){let{activity:o,server:s}=e,{serverFresh:i,abortFloor:a,activityFresh:c}=t;return c&&(!n||o.atMs>n.atMs)&&o.atMs>=a?{state:"working",source:"stream",turnId:i?s.turns.find(d=>d.state==="active"&&!oi(d,n,s))?.message_id??null:null,since:o.atMs,serverOpenTurnToken:r}:null}function MA(e,t,n,r){let{server:o,stream:s}=e,{serverFresh:i,abortFloor:a}=t,c=i?o.turns.filter(g=>!oi(g,n,o)):[],p=c.find(g=>g.state==="active")??c[0],d=!!s&&!(s.type==="idle"&&s.origin==="local");return p&&o.atMs>=a&&(!d||o.atMs>=s.atMs)?{result:{...p.state==="delivering"?{pendingDelivery:!0}:{},state:"working",source:"server",turnId:p.message_id,since:Tt(p.started_at)??o.atMs,serverOpenTurnToken:r},openTurn:p}:{result:null,openTurn:p}}function OA(e,t,n){let{inbox:r,server:o,stream:s}=e,{inboxFresh:i,abortFloor:a,streamFresh:c,serverFresh:p,receiptLive:d,receiptTurnId:g,abortLive:m}=t;if(i&&r.pending>0&&r.atMs>=a)return{...c&&s.type!=="idle"&&(!p||s.atMs>o.atMs)&&s.atMs>=a?{}:{pendingDelivery:!0},state:"working",source:"server",turnId:d?g:null,since:r.atMs,serverOpenTurnToken:n};let f=r?.drainedAtMs;return i&&r.pending===0&&f!=null&&!m&&!(p&&o.atMs>=f)?{pendingDelivery:!0,state:"working",source:"server",turnId:null,since:f,serverOpenTurnToken:n}:null}function DA(e,t,n,r){let{server:o,stream:s,optimistic:i,nowMs:a}=e,{serverFresh:c,serverFloor:p,streamFresh:d,streamFloor:g,abortFloor:m,receiptLive:f,receiptTurnId:h}=t,S=c&&!n&&o.atMs>=p,D=d&&s.atMs>=g&&(s.type==="idle"||s.atMs>=m);if(S&&(!s||o.atMs>=s.atMs))return{state:"idle",source:"server",turnId:null,since:Tt(o.lastEnded?.ended_at)??o.atMs,serverOpenTurnToken:r};if(D)return{state:s.type==="idle"?"idle":"working",source:"stream",turnId:null,since:s.atMs,serverOpenTurnToken:r};if(f)return{pendingDelivery:!0,state:"working",source:"optimistic",turnId:h,since:i.atMs,serverOpenTurnToken:r};let j=o&&s?o.atMs>=s.atMs?{source:"server",atMs:o.atMs}:{source:"stream",atMs:s.atMs}:o?{source:"server",atMs:o.atMs}:s?{source:"stream",atMs:s.atMs}:{source:"server",atMs:a};return{state:"idle",source:j.source,turnId:null,since:j.atMs,serverOpenTurnToken:r}}function kh(e){let t=Ah(e),{server:n,stream:r}=e,o=r&&r.type==="idle"&&r.origin!=="local"?r:null,s=n?.turns[0]?.turn_token??null,i=EA(e,t,o,s);if(i)return i;let{result:a,openTurn:c}=MA(e,t,o,s);return a??OA(e,t,s)??DA(e,t,c,s)}var ei=6e4,ti=45e3,kn=45e3,ni=1e4,u1=3e3,ri=15e3;function p1(e,t){return t?t.serverAtMs!=null&&e.serverAtMs!=null?e.serverAtMs>=t.serverAtMs:e.atMs>=t.atMs:!0}function d1(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 m1(e){return kh(e)}function f1(e){let{optimistic:t,abort:n,inbox:r,server:o,stream:s,activity:i,nowMs:a}=e,c=[null,t?t.atMs+ei:null,n?n.atMs+ri:null,r?r.atMs+ni:null,o?o.atMs+ti:null,s?s.atMs+kn:null,i?i.atMs+kn:null],p=null;for(let d of c)d===null||d<=a||(p===null||d<p)&&(p=d);return p}function jA(e,t){if(!e||!t)return null;let n=e.recent_failures?.find(s=>s.message_id===t),r=e.last_ended,o=n?.error??(r?.message_id===t&&r.end_reason==="failed"?r.error:void 0);return!o?.message||Br({name:o.name??void 0,message:o.message})?null:o}var $A="SandboxMemoryGuard";function _1(e,t,n){if(!e||!t||n.hasError&&!n.isAbort)return null;let r=jA(e,t);if(r?.message){if(r.name!==$A)return{kind:"cause",name:r.name,message:r.message};let a=r.message.match(/(\d{1,3})%/)?.[1],c=r.message.split(":")[0]?.trim()||null;return{kind:"sandbox-memory",usedPct:a?Number(a):null,detail:c}}let o=e.recent_failures?.find(a=>a.message_id===t);if(!o)return null;let s=o.ended_at?Date.parse(o.ended_at):Number.NaN;return Number.isFinite(s)&&typeof e.atMs=="number"&&e.atMs-s<2500?null:{kind:"unexplained"}}var x1=6e4;function S1(e){return e.serverCompactingAtMs!==null?!0:e.optimisticAtMs===null?!1:e.nowMs-e.optimisticAtMs<6e4}function w1(e){if(e.serverCompactingAtMs!==null||e.optimisticAtMs===null)return null;let t=e.optimisticAtMs+6e4;return t>e.nowMs?t:null}var UA=9e4;function v1(e){return e.serverCompactingAtMs===null?null:e.serverCompactingAtMs+UA}var k1=75e3,R1=2,I1=2e4;function Rh(){return{status:"idle",dispatch:"none",fingerprint:null,lastProgressAtMs:null,lastDispatchAtMs:null,attempts:[],msSinceProgress:0,settled:!1}}function C1(e){return e.filter(t=>t!=null).join("|")}function FA(e,t){return e.length===0?"retry-start":e.filter(r=>r.step==="restart").length<t?"restart":null}function T1(e,t,n={}){let r=n.noProgressMs??75e3,o=n.maxRestarts??2,s=n.cooldownMs??2e4;if(t.runtimeReachable)return{...Rh(),settled:!0};if(!t.waking)return{...e,dispatch:"none",fingerprint:null,lastProgressAtMs:null,msSinceProgress:0};if(e.settled)return{...Rh(),settled:!0};let i=e.lastProgressAtMs,a=i===null,c=t.progress!==e.fingerprint,p=i===null||c?t.nowMs:i,d=Math.max(0,t.nowMs-p),g={...e,dispatch:"none",fingerprint:t.progress,lastProgressAtMs:p,msSinceProgress:d,status:e.attempts.length>0?"escalating":"waking"};if(e.status==="exhausted")return{...g,status:"exhausted"};let m=!a&&!c&&d>=r;if(!t.serverGaveUp&&!m||e.lastDispatchAtMs!==null&&t.nowMs-e.lastDispatchAtMs<s)return g;let f=FA(e.attempts,o);return f?{...g,status:"escalating",dispatch:f,attempts:[...e.attempts,{step:f,atMs:t.nowMs}],lastDispatchAtMs:t.nowMs,lastProgressAtMs:t.nowMs,msSinceProgress:0}:{...g,status:"exhausted"}}var LA={"retry-start":"retrying",restart:"restarting"};function E1(e){if(e.status!=="escalating")return null;let t=e.attempts[e.attempts.length-1];return t?`Still waking \u2014 ${LA[t.step]} the runtime (attempt ${e.attempts.length+1})`:null}function NA(e){return e===1?"once":e===2?"twice":`${e} times`}function M1(e){if(e.status!=="exhausted")return null;let t=e.attempts.filter(o=>o.step==="restart").length,n=e.attempts.some(o=>o.step==="retry-start");if(!n&&t===0)return null;let r=[];return n&&r.push("re-issuing the wake"),t>0&&r.push(`restarting the session ${NA(t)}`),`Tried: ${r.join(", then ")}.`}var D1={"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 KA(e){return!!(e.metadata??{}).legacy_migration}function j1(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 KA(e)?"legacy":e.status==="completed"?"done":"stopped";case"failed":return"failed";default:return"stopped"}}function $1(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 U1={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 F1(e){return e===null?"Waiting to retry":e>0?`Retrying in ${e}s`:"Retrying now"}function si(e){return e.runtime_sessions??e.opencode_sessions??[]}function qA(e){let t=si(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 N1(e){let t=qA(e);return t?si(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 K1(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=>si(r).some(o=>o.id===t))??null)}var GA=new Set;function BA(e){for(let t of[...GA])try{t(e)}catch{}}function WA(e){return e==="TIMEOUT"||e==="request_deadline"}function HA(e){let t=Ch(e)?e.code:void 0;return typeof t=="string"?t:void 0}var Ch=e=>typeof e=="object"&&e!==null;function Ih(e){let t=e?.metadata;return!!Ch(t)&&t.warm===!0}var VA=5,zA=2e3,YA=e=>new Promise(t=>setTimeout(t,e));async function QA(e,{attempts:t=VA,delayMs:n=zA,sleep:r=YA}={}){for(let o=0;o<t;o++){o>0&&await r(n);try{if(await e())return!0}catch{}}return!1}function sW(e,t){let n=new Map,r=new Set,o=new Set,s=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 h=await e.ensure(c,p);if(g!==i)return;o.has(h.sessionId)?f=h.sessionId:n.set(c,h)}catch{}finally{g===i&&r.delete(c)}f&&d>0&&await a(c,f,d-1)})();return s.add(m),m.finally(()=>s.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),o.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 WA(HA(g))?QA(async()=>!Ih(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),o.add(c),p;return null},revalidate:async c=>{let p=n.get(c);if(!p)return!1;try{if(Ih(await e.read(c,p.sessionId)))return!1}catch{return!1}return n.get(c)?.sessionId!==p.sessionId?!1:(n.delete(c),o.add(p.sessionId),!0)},held:c=>n.get(c)??null,reset:()=>{i+=1,n.clear(),r.clear(),o.clear()},settled:async()=>{for(;s.size>0;)await Promise.all([...s])}}}var XA=12e4,Yr=class extends Error{constructor(t){super(`Session history read did not settle within ${t}ms`),this.name="SessionSyncReadTimeoutError"}},JA=1e3,ZA=15e3,Th=100,ek=50,tk=10;function Eh(e){let t=e.fetch??globalThis.fetch,n=e.baseUrl.replace(/\/$/,"");return async({limit:r,before:o},s)=>{let i=new URLSearchParams({limit:String(r)});o&&i.set("before",o);let a=await e.getToken?.(),c=await t(`${n}/session/${encodeURIComponent(e.sessionId)}/message?${i}`,{headers:a?{Authorization:`Bearer ${a}`}:void 0,...s?{signal:s}:{}});if(!c.ok)throw c.status===503?new Hr(`session ${c.status}`):new b(`Session synchronization failed: ${c.status}`,{status:c.status});return{messages:await c.json(),nextCursor:c.headers.get("x-next-cursor")||void 0}}}function nk(e){return ok(Eh(e))}function rk(e){return new ii({...e,loadPage:Eh(e)})}async function ok(e){let t=[],n=new Set,r;do{let i=await e({limit:Th,...r?{before:r}:{}});if(t.push(i.messages),r=i.nextCursor,r&&n.has(r))throw new Error(`Session history cursor repeated: ${r}`);r&&n.add(r)}while(r);let o=[],s=new Set;for(let i=t.length-1;i>=0;i--)for(let a of t[i])s.has(a.info.id)||(s.add(a.info.id),o.push(a));return o}var sk={now:Date.now,setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e),setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e)},ii=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??sk,this.livenessIntervalMs=t.livenessIntervalMs??1e4,this.verifyIntervalMs=t.verifyIntervalMs??3e4,this.readTimeoutMs=t.readTimeoutMs??XA,this.lastActivityAt=this.scheduler.now(),this.lastTailReadAt=this.scheduler.now()}getSnapshot=()=>this.snapshot;subscribe=t=>(this.listeners.add(t),()=>this.listeners.delete(t));start(){return this.snapshot.freshness==="fresh"?Promise.resolve():this.reconcile("initial")}reconcile(t="manual"){return this.destroyed?Promise.resolve():this.tailRequest?this.tailRequest:(this.update({freshness:this.snapshot.freshness==="idle"||this.snapshot.freshness==="loading"?"loading":"stale"}),this.tailRequest=this.loadTail(t).finally(()=>{this.tailRequest=void 0}),this.tailRequest)}loadOlder=()=>{if(this.destroyed||!this.nextCursor)return Promise.resolve();if(this.olderRequest)return this.olderRequest;let t=this.nextCursor;return this.update({isLoadingOlder:!0}),this.olderRequest=this.loadCompleteOlderTurn(t).then(n=>{this.destroyed||(this.rememberUserMessages(n.messages),this.options.hydrate(n.messages),this.olderHistoryStarted=!0,this.setCursor(n.nextCursor))}).finally(()=>{this.olderRequest=void 0,this.update({isLoadingOlder:!1})}),this.olderRequest};noteActivity(){this.lastActivityAt=this.scheduler.now(),this.snapshot.freshness!=="fresh"&&this.update({freshness:"fresh"})}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 Yr;if(!r&&Br(n))return;if(r||this.update({freshness:An(n)?"loading":"error"}),n instanceof b&&(n.status===404||n.status===410)){this.tailUnavailable=!0,this.cancelTimer(this.tailRetryTimer),this.tailRetryTimer=void 0;return}this.scheduleTailRetry(t)}}scheduleTailRetry(t){if(this.destroyed||this.tailRetryTimer!==void 0)return;let n=Math.min(JA*2**this.retryAttempt,ZA);this.retryAttempt+=1,this.tailRetryTimer=this.startTimer(()=>{this.tailRetryTimer=void 0,!this.destroyed&&this.reconcile(t)},n)}async loadPage(t,n,r){let o=this.scheduler.now();try{let s=await this.boundedRead(i=>this.options.loadPage({limit:t==="tail"?ek:Th,...r?{before:r}:{}},i));return this.options.onTelemetry?.({operation:t,reason:n,durationMs:this.scheduler.now()-o,messageCount:s.messages.length,succeeded:!0}),s}catch(s){throw this.options.onTelemetry?.({operation:t,reason:n,durationMs:this.scheduler.now()-o,messageCount:0,succeeded:!1}),s}}boundedRead(t){let n=this.abortController.signal,r=new AbortController,o=()=>r.abort(n.reason);n.aborted?r.abort(n.reason):n.addEventListener("abort",o,{once:!0});let s,i=new Promise((c,p)=>{s=this.startTimer(()=>{let d=new Yr(this.readTimeoutMs);p(d),r.abort(d)},this.readTimeoutMs)}),a;try{a=t(r.signal)}catch(c){a=Promise.reject(c)}return Promise.race([a,i]).finally(()=>{this.cancelTimer(s),n.removeEventListener("abort",o)})}async loadCompleteOlderTurn(t){let n=await this.loadPage("older","manual",t);return this.loadCompleteTurn(n,"older","manual",t,r=>{this.rememberUserMessages(r.messages),this.options.hydrate(r.messages),this.setCursor(r.nextCursor)})}async loadCompleteTurn(t,n,r,o,s){let i=[...t.messages],a=new Set(this.knownUserMessageIds),c=new Set(o?[o]:[]),p=t.nextCursor,d=0;for(let g of t.messages)g.info.role==="user"&&a.add(g.info.id);for(;p&&d<tk&&i.some(g=>g.info.role==="assistant"&&!!g.info.parentID&&!a.has(g.info.parentID));){if(c.has(p))throw new Error(`Session history cursor repeated: ${p}`);c.add(p);let g;try{g=await this.loadPage(n,r,p)}catch(m){throw s?.({messages:[...i],nextCursor:p}),m}if(this.destroyed)return{messages:i,nextCursor:p};d+=1,i.unshift(...g.messages);for(let m of g.messages)m.info.role==="user"&&a.add(m.info.id);p=g.nextCursor,s?.({messages:[...i],nextCursor:p})}return{messages:i,nextCursor:p}}rememberUserMessages(t){for(let n of t)n.info.role==="user"&&this.knownUserMessageIds.add(n.info.id)}async checkLiveness(){if(this.destroyed||this.tailUnavailable||this.streamReliable)return;let t=this.scheduler.now(),n=t-this.lastActivityAt>this.livenessIntervalMs,r=t-this.lastTailReadAt>=this.verifyIntervalMs;!(this.livenessBusy&&n)&&!r||(await this.raceDeadline(this.reconcile("poll"),this.livenessIntervalMs),this.lastActivityAt=this.scheduler.now())}raceDeadline(t,n){return new Promise(r=>{let o,s=!1,i=()=>{s||(s=!0,this.cancelTimer(o),r())};o=this.startTimer(i,n),t.then(i,i)})}setCursor(t){this.nextCursor=t,this.update({hasOlder:!!t})}stopLivenessTimer(){this.livenessTimer!==void 0&&(this.scheduler.clearInterval(this.livenessTimer),this.livenessTimer=void 0)}startTimer(t,n){return this.scheduler.setTimeout?this.scheduler.setTimeout(t,n):setTimeout(t,n)}cancelTimer(t){t!==void 0&&(this.scheduler.clearTimeout?this.scheduler.clearTimeout(t):clearTimeout(t))}update(t){let n={...this.snapshot,...t};if(!(n.freshness===this.snapshot.freshness&&n.hasOlder===this.snapshot.hasOlder&&n.isLoadingOlder===this.snapshot.isLoadingOlder)){this.snapshot=n;for(let r of this.listeners)r()}}};function ik(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 ak(e){return e.savedEmptyRoot!==null&&e.savedEmptyRoot===e.rootSessionId&&e.turnRead&&!e.hasEndedTurn&&!e.hasOpenOrQueuedTurn}function gW(e){throw F("buildTunnelEventStreamUrl")}function mW(e){let{url:t,token:n,method:r="GET",body:o,onEvent:s,onOpen:i,onError:a,onClose:c,signal:p}=e,d=new Map,g=null,m=!1,f="";function h(y,_){s?.(y,_);let x=d.get(y);if(x)for(let E of x)try{E(_)}catch{}}async function S(){if(m)return;let y=new AbortController;g=y,p&&(p.aborted?y.abort():p.addEventListener("abort",()=>y.abort(),{once:!0}));let _=y.signal;try{let x={Accept:"text/event-stream",Authorization:`Bearer ${n}`};r!=="GET"&&o!==void 0&&(x["Content-Type"]="application/json"),f&&(x["Last-Event-ID"]=f);let E=await fetch(t,{method:r,headers:x,body:r!=="GET"&&o!==void 0?JSON.stringify(o):void 0,signal:_,credentials:"include"});if(!E.ok)throw new Error(`SSE connection failed: ${E.status} ${E.statusText}`);if(!E.body)throw new Error("SSE response has no body");i?.();let w=E.body.getReader(),P=new TextDecoder,A="",C="message",T=[],N=K=>{if(K===""){T.length>0&&h(C,T.join(`
96
- `)),C="message",T=[];return}if(K.startsWith(":"))return;let q=K.indexOf(":"),ue=q===-1?K:K.slice(0,q),le=q===-1?"":K.slice(q+1);le.startsWith(" ")&&(le=le.slice(1)),ue==="event"?C=le.trim()||"message":ue==="data"?T.push(le):ue==="id"&&!le.includes("\0")&&(f=le)},$=K=>{let q="";!K&&A.endsWith("\r")&&(q="\r",A=A.slice(0,-1));let ue=A.split(/\r\n|\n|\r/);A=(ue.pop()??"")+q;for(let le of ue)N(le)};for(;!m;){let{done:K,value:q}=await w.read();if(K)break;A+=P.decode(q,{stream:!0}),$(!1)}m||(A+=P.decode(),$(!0),c?.())}catch(x){if(m||x instanceof DOMException&&x.name==="AbortError")return;a?.(x instanceof Error?x:new Error(String(x)))}}function D(){m=!0,g?.abort(),g=null,d.clear()}function j(y,_){let x=d.get(y)??new Set;x.add(_),d.set(y,x)}function L(y,_){d.get(y)?.delete(_)}return{connect:S,close:D,addEventListener:j,removeEventListener:L}}function fW(e,t){throw F("createTunnelEventStream")}var Mh="/_kortix/viewer",Qr=6e4,Et=new Map;function ck(){Et.clear(),Rn.clear()}async function lk(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 Oh(e={}){let t=e.path??Mh,n=e.fetch??((s,i)=>fetch(s,i)),r=Et.get(t);if(r&&!r.inflight&&r.expiresAt>Date.now())return r.session;if(r?.inflight)return r.inflight;let o=lk(t,n).then(s=>{let i=s?.expires_at?Date.parse(s.expires_at):Number.NaN,a=Number.isFinite(i)?i-Qr:Date.now()+Qr;return Et.set(t,{session:s,expiresAt:a}),s});return Et.set(t,{session:r?.session??null,expiresAt:0,inflight:o}),o}function uk(e={}){let t=e.path??Mh;return Object.assign(async()=>(await Oh(e))?.access_token??null,{invalidate:n=>{let r=Et.get(t);r&&!r.inflight&&r.session?.access_token===n&&Et.delete(t)}})}var Rn=new Map;async function pk(e,t){try{let n=await t(e,{credentials:"same-origin",headers:{accept:"application/json"}});if(!n.ok){if(n.status===403){let s=await n.json().catch(()=>null);s?.error==="app_not_linked"&&console.warn(`[kortix] ${String(s.error_description)}`)}return null}let r=await n.json().catch(()=>null);if(!r||typeof r.token!="string")return null;let o=typeof r.expires_at=="string"?Date.parse(r.expires_at):Number.NaN;return Rn.set(e,{token:r.token,refreshAt:Number.isFinite(o)?o-Qr:Date.now()+Qr}),r.token}catch{return null}}function Dh(e={}){let t=e.path??"/_kortix/token",n=e.audience===void 0?t:`${t}?audience=${encodeURIComponent(e.audience)}`,r=e.fetch??((o,s)=>fetch(o,s));return async(o={})=>{let s=Rn.get(n);if(s instanceof Promise)return s;if(s&&!o.forceRefreshToken&&s.refreshAt>Date.now())return s.token;let i=pk(n,r).then(a=>(a===null&&Rn.delete(n),a));return Rn.set(n,i),i}}function dk(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:`${te(n)}/_kortix/apps/${encodeURIComponent(e)}`,token:Dh({audience:e,fetch:t.fetch})}}var it=class extends Error{code;constructor(t,n){super(n),this.name="KortixMemberError",this.code=t}},ce=e=>typeof e=="string"&&e.length>0?e:null;function jh(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 ci(e){if(!e||typeof e!="object")return null;let t=e,n=ce(t.sub)??ce(t.subject)??ce(t.user_id)??ce(t.userId);return n?{userId:n,email:ce(t.email),name:ce(t.name),picture:ce(t.picture)??ce(t.pictureUrl),groups:jh(t.groups),groupIds:jh(t.group_ids??t.groupIds),role:ce(t.role),accountId:ce(t.account_id)??ce(t.accountId),projectId:ce(t.project_id)??ce(t.projectId)}:null}function gk(e,t={}){let n=ci(e);if(!n)throw new it("unauthenticated","Sign in with Kortix to continue.");let{groups:r,roles:o}=t;if(r&&!r.some(s=>n.groups.includes(s)||n.groupIds.includes(s)))throw new it("forbidden",`Only members of ${r.join(" or ")||"no group"} may do this.`);if(o&&!o.some(s=>n.role===s))throw new it("forbidden",`Only ${o.join(" or ")||"no role"} members may do this.`);return n}var mk=60,ai=new Map;function Uh(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 $h(e){return JSON.parse(new TextDecoder().decode(Uh(e)))}async function fk(e,t){if(typeof e!="string")return e;if(e.startsWith("data:")){let n=e.indexOf(","),r=e.slice(5,n),o=e.slice(n+1),s=r.endsWith(";base64")?new TextDecoder().decode(Uint8Array.from(atob(o),i=>i.charCodeAt(0))):decodeURIComponent(o);return JSON.parse(s)}if(/^https?:\/\//.test(e)){let n=ai.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(()=>ai.delete(e)),ai.set(e,n)),n}return JSON.parse(e)}async function yk(e,t={}){let n=y=>{throw new it("unauthenticated",`Kortix sign-in token refused: ${y}.`)},r=t.jwks??je("KORTIX_AUTH_JWKS"),o=t.issuer??je("KORTIX_AUTH_ISSUER"),s=t.audience??je("KORTIX_AUTH_AUDIENCE");if(!r)return n("no key set configured (KORTIX_AUTH_JWKS)");if(s!==!1&&!s)return n("no audience configured (KORTIX_AUTH_AUDIENCE, or `audience: false` to accept any App)");let i=typeof e=="string"?e.split("."):[];if(i.length!==3)return n("malformed");let[a,c,p]=i,d,g;try{d=$h(a),g=$h(c)}catch{return n("malformed")}if(d.alg!=="ES256")return n("unsupported algorithm");let m;try{m=await fk(r,t.fetch??((y,_)=>fetch(y,_)))}catch{return n("key set unavailable")}let f=(m.keys??[]).filter(y=>y.kty==="EC"&&(d.kid===void 0||y.kid===d.kid));if(f.length===0)return n("unknown key");let h=new TextEncoder().encode(`${a}.${c}`),S;try{S=Uh(p)}catch{return n("malformed")}let D=!1;for(let y of f)try{let{kid:_,alg:x,use:E,key_ops:w,...P}=y,A=await crypto.subtle.importKey("jwk",P,{name:"ECDSA",namedCurve:"P-256"},!1,["verify"]);if(await crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},A,S,h)){D=!0;break}}catch{}if(!D)return n("bad signature");let j=Math.floor(Date.now()/1e3);if(typeof g.exp!="number"||g.exp+mk<j)return n("expired");if(o&&g.iss!==o)return n("wrong issuer");if(s){let y=g.aud;if(!(y===s||Array.isArray(y)&&y.includes(s)))return n("wrong audience")}let L=ci(g);return L||n("no subject")}function Fh(e){let t=e.agents.map(hk),n=e.default_agent??e.open_code_default_agent;return n?t.sort((r,o)=>r.name===n?-1:o.name===n?1:0):t}function hk(e){return{name:e.name,description:e.description??void 0,mode:e.mode??void 0,source:e.source,hidden:e.enabled===!1}}function Lh(e,t){if(!Array.isArray(e))return[];let n=t?.includeSubagents===!0;return e.filter(r=>Zo(n?{...r,mode:null}:r))}function bk(e){let t=e.boundAgent?.trim()||null;if(!Array.isArray(e.agents)){let s=e.selectedAgent?.trim();return s?{selected:s,disabled:!1,reason:"loading"}:{selected:t,disabled:!1,reason:"loading"}}let n=Lh(e.agents);if(n.length===0)return t?{selected:t,disabled:!1,reason:"bound"}:{selected:null,disabled:!0,reason:"no_access"};let r=e.selectedAgent?.trim();if(r&&n.some(s=>s.name===r))return{selected:r,disabled:!1,reason:"selected"};if(t)return{selected:t,disabled:!1,reason:"bound"};let o=e.defaultAgent?.trim();return o&&n.some(s=>s.name===o)?{selected:o,disabled:!1,reason:"default"}:{selected:n[0].name,disabled:!1,reason:"first_accessible"}}var _k=Fh;function Nh(e){return e.providerID==="kortix"||e.providerID==="opencode"?e.modelID:`${e.providerID}/${e.modelID}`}function li(e){return{providerID:"kortix",modelID:e}}function Pk(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 li(n)}var ui=[{id:"hpc-ai",env:["HPC_AI_API_KEY"]},{id:"ai-router",env:["AI_ROUTER_API_KEY"]},{id:"mixlayer",env:["MIXLAYER_API_KEY"]},{id:"qiniu-ai",env:["QINIU_API_KEY"]},{id:"neuralwatt",env:["NEURALWATT_API_KEY"]},{id:"umans-ai-coding-plan",env:["UMANS_AI_CODING_PLAN_API_KEY"]},{id:"iteracompute",env:["ITERACOMPUTE_API_KEY"]},{id:"cloudflare-workers-ai",env:["CLOUDFLARE_ACCOUNT_ID","CLOUDFLARE_API_KEY"]},{id:"meganova",env:["MEGANOVA_API_KEY"]},{id:"infomaniak",env:["INFOMANIAK_API_KEY","INFOMANIAK_PRODUCT_ID"]},{id:"orcarouter",env:["ORCAROUTER_API_KEY"]},{id:"zenifra",env:["ZENIFRA_AI_KEY"]},{id:"nvidia",env:["NVIDIA_API_KEY"]},{id:"qvac",env:["QVAC_API_KEY"]},{id:"iflowcn",env:["IFLOW_API_KEY"]},{id:"claudinio",env:["CLAUDINIO_API_KEY"]},{id:"cortecs",env:["CORTECS_API_KEY"]},{id:"nano-gpt",env:["NANO_GPT_API_KEY"]},{id:"modelscope",env:["MODELSCOPE_API_KEY"]},{id:"synthetic",env:["SYNTHETIC_API_KEY"]},{id:"jalapeno",env:["JALAPENO_API_KEY"]},{id:"abliteration-ai",env:["ABLIT_KEY"]},{id:"deepseek",env:["DEEPSEEK_API_KEY"]},{id:"greenpt",env:["GREENPT_API_KEY"]},{id:"xpersona",env:["XPERSONA_API_KEY"]},{id:"tencent-tokenhub",env:["TENCENT_TOKENHUB_API_KEY"]},{id:"stepfun-step-plan",env:["STEPFUN_API_KEY"]},{id:"xiaomi-token-plan-sgp",env:["XIAOMI_API_KEY"]},{id:"the-grid-ai",env:["THEGRID_API_KEY"]},{id:"google-vertex",env:["GOOGLE_VERTEX_PROJECT","GOOGLE_VERTEX_LOCATION","GOOGLE_APPLICATION_CREDENTIALS"]},{id:"alibaba-token-plan",env:["ALIBABA_TOKEN_PLAN_API_KEY"]},{id:"agentrouter",env:["AGENTROUTER_API_KEY"]},{id:"google",env:["GOOGLE_API_KEY","GOOGLE_GENERATIVE_AI_API_KEY","GEMINI_API_KEY"]},{id:"model-oracle-ai",env:["MODEL_ORACLE_API_KEY"]},{id:"deepinfra",env:["DEEPINFRA_API_KEY"]},{id:"meta",env:["META_MODEL_API_KEY"]},{id:"huggingface",env:["HF_TOKEN"]},{id:"impossibl",env:["IMPOSSIBL_API_KEY"]},{id:"jiekou",env:["JIEKOU_API_KEY"]},{id:"longcat",env:["LONGCAT_API_KEY"]},{id:"inception",env:["INCEPTION_API_KEY"]},{id:"openrouter",env:["OPENROUTER_API_KEY"]},{id:"google-vertex-anthropic",env:["GOOGLE_VERTEX_PROJECT","GOOGLE_VERTEX_LOCATION","GOOGLE_APPLICATION_CREDENTIALS"]},{id:"poolside",env:["POOLSIDE_API_KEY"]},{id:"hetzner",env:["HETZNER_API_KEY"]},{id:"regolo-ai",env:["REGOLO_API_KEY"]},{id:"lynkr",env:["LYNKR_API_KEY"]},{id:"lucidquery",env:["LUCIDQUERY_API_KEY"]},{id:"blueclaw",env:["BLUECLAW_API_KEY"]},{id:"standardcompute",env:["STANDARDCOMPUTE_API_KEY"]},{id:"auriko",env:["AURIKO_API_KEY"]},{id:"daoxe",env:["DAOXE_API_KEY"]},{id:"moonshotai",env:["MOONSHOT_API_KEY"]},{id:"crossmodel",env:["CROSSMODEL_API_KEY"]},{id:"kenari",env:["KENARI_API_KEY"]},{id:"clarifai",env:["CLARIFAI_PAT"]},{id:"snowflake-cortex",env:["SNOWFLAKE_ACCOUNT","SNOWFLAKE_CORTEX_PAT"]},{id:"anthropic",env:["ANTHROPIC_API_KEY"]},{id:"cohere",env:["COHERE_API_KEY"]},{id:"zai",env:["ZHIPU_API_KEY"]},{id:"routing-run",env:["ROUTING_RUN_API_KEY"]},{id:"stackit",env:["STACKIT_API_KEY"]},{id:"databricks",env:["DATABRICKS_HOST","DATABRICKS_TOKEN"]},{id:"moark",env:["MOARK_API_KEY"]},{id:"salad-cloud",env:["SALAD_CLOUD_API_KEY"]},{id:"alibaba-cn",env:["DASHSCOPE_API_KEY"]},{id:"kosmik",env:["KOSMIK_API_KEY"]},{id:"minimax-cn-coding-plan",env:["MINIMAX_API_KEY"]},{id:"amazon-bedrock",env:["AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_REGION","AWS_BEARER_TOKEN_BEDROCK"]},{id:"unorouter",env:["UNOROUTER_API_KEY"]},{id:"crusoe",env:["CRUSOE_API_KEY"]},{id:"dinference",env:["DINFERENCE_API_KEY"]},{id:"openai",env:["OPENAI_API_KEY"]},{id:"opencode-go",env:["OPENCODE_API_KEY"]},{id:"opper",env:["OPPER_API_KEY"]},{id:"xai",env:["XAI_API_KEY"]},{id:"stepfun-ai",env:["STEPFUN_API_KEY"]},{id:"lmstudio",env:["LMSTUDIO_API_KEY"]},{id:"ambient",env:["AMBIENT_API_KEY"]},{id:"llmgateway-providers",env:["LLMGATEWAY_API_KEY"]},{id:"vivgrid",env:["VIVGRID_API_KEY"]},{id:"nebius",env:["NEBIUS_API_KEY"]},{id:"echo",env:["ECHO_API_KEY"]},{id:"cloudferro-sherlock",env:["CLOUDFERRO_SHERLOCK_API_KEY"]},{id:"nearai",env:["NEARAI_API_KEY"]},{id:"xiaomi-token-plan-cn",env:["XIAOMI_API_KEY"]},{id:"tinfoil",env:["TINFOIL_API_KEY"]},{id:"zhipuai-coding-plan",env:["ZHIPU_API_KEY"]},{id:"llmtr",env:["LLMTR_API_KEY"]},{id:"merge-gateway",env:["MERGE_GATEWAY_API_KEY"]},{id:"inceptron",env:["INCEPTRON_API_KEY"]},{id:"ovhcloud",env:["OVHCLOUD_API_KEY"]},{id:"aki-io",env:["AKI_IO_API_KEY"]},{id:"stepfun",env:["STEPFUN_API_KEY"]},{id:"llama",env:["LLAMA_API_KEY"]},{id:"cloudflare-ai-gateway",env:["CLOUDFLARE_API_TOKEN","CLOUDFLARE_ACCOUNT_ID","CLOUDFLARE_GATEWAY_ID"]},{id:"drun",env:["DRUN_API_KEY"]},{id:"sarvam",env:["SARVAM_API_KEY"]},{id:"digitalocean",env:["DIGITALOCEAN_ACCESS_TOKEN"]},{id:"alibaba-coding-plan-cn",env:["ALIBABA_CODING_PLAN_API_KEY"]},{id:"neosmith",env:["NEOSMITH_API_KEY"]},{id:"stepfun-ai-step-plan",env:["STEPFUN_API_KEY"]},{id:"fastrouter",env:["FASTROUTER_API_KEY"]},{id:"privatemode-ai",env:["PRIVATEMODE_API_KEY","PRIVATEMODE_ENDPOINT"]},{id:"zeldoc",env:["ZELDOC_API_KEY"]},{id:"lilac",env:["LILAC_API_KEY"]},{id:"io-net",env:["IOINTELLIGENCE_API_KEY"]},{id:"berget",env:["BERGET_API_KEY"]},{id:"xiaomi",env:["XIAOMI_API_KEY"]},{id:"minimax-coding-plan",env:["MINIMAX_API_KEY"]},{id:"zai-coding-plan",env:["ZHIPU_API_KEY"]},{id:"alibaba",env:["DASHSCOPE_API_KEY"]},{id:"sakana",env:["SAKANA_API_KEY"]},{id:"zenmux",env:["ZENMUX_API_KEY"]},{id:"perplexity-agent",env:["PERPLEXITY_API_KEY"]},{id:"alibaba-coding-plan",env:["ALIBABA_CODING_PLAN_API_KEY"]},{id:"ollama-cloud",env:["OLLAMA_API_KEY"]},{id:"perplexity",env:["PERPLEXITY_API_KEY"]},{id:"gmicloud",env:["GMICLOUD_API_KEY"]},{id:"umans-ai",env:["UMANS_AI_API_KEY"]},{id:"sap-ai-core",env:["AICORE_SERVICE_KEY"]},{id:"inference",env:["INFERENCE_API_KEY"]},{id:"arcee",env:["ARCEE_API_KEY"]},{id:"qihang-ai",env:["QIHANG_API_KEY"]},{id:"kuae-cloud-coding-plan",env:["KUAE_API_KEY"]},{id:"submodel",env:["SUBMODEL_INSTAGEN_ACCESS_KEY"]},{id:"scx-ai",env:["SCX_API_KEY"]},{id:"freemodel",env:["FREEMODEL_API_KEY"]},{id:"nova",env:["NOVA_API_KEY"]},{id:"togetherai",env:["TOGETHER_API_KEY"]},{id:"ofox",env:["OFOX_API_KEY"]},{id:"friendli",env:["FRIENDLI_TOKEN"]},{id:"inferx",env:["INFERX_API_KEY"]},{id:"helicone",env:["HELICONE_API_KEY"]},{id:"zhipuai",env:["ZHIPU_API_KEY"]},{id:"neon",env:["NEON_AI_GATEWAY_BASE_URL","NEON_AI_GATEWAY_TOKEN"]},{id:"evroc",env:["EVROC_API_KEY"]},{id:"azure-cognitive-services",env:["AZURE_COGNITIVE_SERVICES_RESOURCE_NAME","AZURE_COGNITIVE_SERVICES_API_KEY"]},{id:"pendra",env:["PENDRA_API_KEY"]},{id:"302ai",env:["302AI_API_KEY"]},{id:"opencode",env:["OPENCODE_API_KEY"]},{id:"requesty",env:["REQUESTY_API_KEY"]},{id:"siliconflow",env:["SILICONFLOW_API_KEY"]},{id:"atomic-chat",env:["ATOMIC_CHAT_API_KEY"]},{id:"hyper",env:["HYPER_API_KEY"]},{id:"subconscious",env:["SUBCONSCIOUS_API_KEY"]},{id:"azure",env:["AZURE_RESOURCE_NAME","AZURE_API_KEY"]},{id:"trustedrouter",env:["TRUSTEDROUTER_API_KEY"]},{id:"scaleway",env:["SCALEWAY_API_KEY"]},{id:"frogbot",env:["FROGBOT_API_KEY"]},{id:"thinkingmachines",env:["TINKER_API_KEY"]},{id:"baseten",env:["BASETEN_API_KEY"]},{id:"siliconflow-cn",env:["SILICONFLOW_CN_API_KEY"]},{id:"minimax-cn",env:["MINIMAX_API_KEY"]},{id:"poe",env:["POE_API_KEY"]},{id:"mistral",env:["MISTRAL_API_KEY"]},{id:"modal",env:["MODAL_PROXY_TOKEN"]},{id:"aihubmix",env:["AIHUBMIX_API_KEY"]},{id:"cline-pass",env:["CLINE_API_KEY"]},{id:"empiriolabs",env:["EMPIRIOLABS_API_KEY"]},{id:"morph",env:["MORPH_API_KEY"]},{id:"tencent-coding-plan",env:["TENCENT_CODING_PLAN_API_KEY"]},{id:"xiaomi-token-plan-ams",env:["XIAOMI_API_KEY"]},{id:"scnet-token-plan",env:["SCNET_API_KEY"]},{id:"anyapi",env:["ANYAPI_API_KEY"]},{id:"cerebras",env:["CEREBRAS_API_KEY"]},{id:"amd",env:["AMD_API_KEY"]},{id:"bailing",env:["BAILING_API_TOKEN"]},{id:"watsonx",env:["WATSONX_AI_APIKEY","WATSONX_AI_PROJECT_ID"]},{id:"vercel",env:["AI_GATEWAY_API_KEY"]},{id:"edenai",env:["EDENAI_API_KEY"]},{id:"novita-ai",env:["NOVITA_API_KEY"]},{id:"upstage",env:["UPSTAGE_API_KEY"]},{id:"llmgateway",env:["LLMGATEWAY_API_KEY"]},{id:"chutes",env:["CHUTES_API_KEY"]},{id:"crof",env:["CROF_API_KEY"]},{id:"v0",env:["V0_API_KEY"]},{id:"groq",env:["GROQ_API_KEY"]},{id:"runinfra",env:["RUNINFRA_GATEWAY_KEY"]},{id:"agnes",env:["AGNES_API_KEY"]},{id:"gitlab",env:["GITLAB_TOKEN"]},{id:"alibaba-token-plan-cn",env:["ALIBABA_TOKEN_PLAN_API_KEY"]},{id:"coralbricks",env:["CORAL_API_KEY"]},{id:"aiand",env:["AIAND_API_KEY"]},{id:"github-copilot",env:["GITHUB_TOKEN"]},{id:"wafer.ai",env:["WAFER_API_KEY"]},{id:"modelis",env:["MODELIS_API_KEY"]},{id:"ebcloud",env:["EBCLOUD_API_KEY"]},{id:"tensorx",env:["TENSORX_API_KEY"]},{id:"tencent-token-plan",env:["TENCENT_TOKEN_PLAN_API_KEY"]},{id:"kilo",env:["KILO_API_KEY"]},{id:"pioneer",env:["PIONEER_API_KEY"]},{id:"venice",env:["VENICE_API_KEY"]},{id:"fireworks-ai",env:["FIREWORKS_API_KEY"]},{id:"moonshotai-cn",env:["MOONSHOT_API_KEY"]},{id:"wandb",env:["WANDB_API_KEY"]},{id:"kimi-for-coding",env:["KIMI_API_KEY"]},{id:"abacus",env:["ABACUS_API_KEY"]},{id:"minimax",env:["MINIMAX_API_KEY"]},{id:"vultr",env:["VULTR_API_KEY"]}];function pi(e){if(!e.released)return null;let t=new Date(e.released).getTime();return Number.isNaN(t)?null:t}function Sk(e){if(e.provider)return e.provider;let t=e.id.indexOf("/");return t===-1?"kortix":e.id.slice(0,t)}function Kh(e,t){let n=new Map;for(let r of e){let o=t(r),s=n.get(o);s?s.push(r):n.set(o,[r])}return n}function se(e){let t=e.includes("/")?e.slice(e.indexOf("/")+1):e;return t.startsWith("global.")?2:/^(us|eu|jp|apac|au|ca|sa|us-gov)\./.test(t)?1:0}function qh(e){return e.reduce((t,n)=>{let r=pi(n)??0,o=pi(t)??0;return r!==o?r>o?n:t:se(n.id)>se(t.id)?n:t})}function di(e,t){let n=(t?.now??new Date).getTime(),r=(t?.windowMonths??6)*2630016e3,o=new Set;for(let[,s]of Kh(e,Sk)){let a=[...Kh(s,p=>p.family||p.id).values()].map(qh),c=a.filter(p=>{let d=pi(p);return d!==null&&Math.abs(n-d)<r});for(let p of c.length>0?c:[qh(a)])o.add(p.id)}return o}function Xr(e){let t=e.filter(r=>r.status!=="deprecated"&&r.status!=="beta"&&r.tool_call!==!1),n=t.length>0?t:e;return n.some(r=>se(r.id)>0)?n.filter(r=>se(r.id)>0):n}function In(e){let t;for(let n of Xr(e)){if(!t){t=n;continue}let r=(n.released??"").localeCompare(t.released??"");(r>0||r===0&&se(n.id)>se(t.id))&&(t=n)}return t}var wk={"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 Gh(e){return`${e.toUpperCase().replace(/[^A-Z0-9]+/g,"_")}_API_KEY`}var vk=(()=>{let e=new Map;for(let{id:n,env:r}of ui)r.length===1&&e.set(r[0],[...e.get(r[0])??[],n]);let t=new Map;for(let[n,r]of e){if(r.length<2)continue;let o=[...r].sort((s,i)=>s.length-i.length||s.localeCompare(i));t.set(n,r.find(s=>Gh(s)===n)??o[0])}return t})();function Bh(e){let t=wk[e.id];if(t)return t;let n=e.env??[],r=n.length===1?vk.get(n[0]):void 0;return r&&r!==e.id?{methods:[{envVars:[Gh(e.id)]}]}:{methods:n.length>0?[{envVars:n}]:[]}}function mi(e,t){return e.methods.some(n=>n.envVars.length>0&&n.envVars.every(t))}var Ak=["low","medium","high"];function Wh(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:[...Ak]}:void 0,o=e.temperature===!0,s=e.limit?.output,i=typeof s=="number"&&s>0?{ceiling:s}:void 0;return{reasoningEffort:r,temperature:o,topP:o,maxOutputTokens:i}}var Hh=ui;var gi={allow_fallbacks:!0,zdr:!0,data_collection:"deny"};var Jr=[{id:"deepseek-v4.1-flash",name:"DeepSeek V4.1 Flash",upstreamModelId:"deepseek/deepseek-v4.1-flash",transport:"openrouter",morphModelId:"morph-dsv41flash",morphPricing:{inputPerMillion:.15,cachedInputPerMillion:.003,outputPerMillion:.6},pricingRef:"openrouter/deepseek/deepseek-v4.1-flash",pricing:{inputPerMillion:.2,cachedInputPerMillion:.03,outputPerMillion:.65},openrouterEndpointPricing:{"coreweave/fp8":{inputPerMillion:.2,cachedInputPerMillion:.03,outputPerMillion:.65}},tier:"balanced",vision:!0,limit:{context:1e6,output:65536},reasoningOptions:[{type:"effort",values:["none","low","high","max"]}],openrouterProvider:{only:["coreweave/fp8"],...gi,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"],...gi,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"],...gi,max_price:{prompt:3.3,completion:16.5}}}],IW=new Map(Jr.map(e=>[e.id,e]));var Vh=Jr.map(e=>e.id),zh=(Jr.find(e=>e.tier==="flagship")??Jr[0]).id,Yh="deepseek-v4.1-flash";var Xh=Hh.map(e=>({id:e.id,authRequirement:Bh(e)})),Cn=new Set(["kortix"]),fi=new Set(["kortix"]);function Mt(e){let t=Array.isArray(e.all)?e.all:[],n=Array.isArray(e.connected)?e.connected:[];if(t.length>0||n.length>0)return{...e,all:t,connected:n};let r=e.providers,o=Array.isArray(r)?r:[];return o.length===0?{...e,all:[],connected:[]}:{...e,all:o,connected:o.map(s=>s.id)}}function kk(e){if(!e)return!1;let t=Mt(e),n=Array.isArray(t.all)?t.all:[],r=Array.isArray(t.connected)?t.connected:[];return r.length===0?!1:n.some(o=>r.includes(o.id)&&o.models&&Object.keys(o.models).length>0)}function Rk(e){let t=Mt(e),n=Array.isArray(t.all)?t.all:[],r=Array.isArray(t.connected)?t.connected:[];return{...t,all:n.filter(o=>!fi.has(o.id)),connected:r.filter(o=>!fi.has(o))}}function Ik(e,t,n){let r=Mt(e),o=Array.isArray(r.all)?r.all:[],s=new Set(o.map(a=>a.id)),i=new Set(Array.isArray(r.connected)?r.connected:[]);for(let a of n)s.has(a.id)&&mi(a.authRequirement,c=>t.has(c))&&i.add(a.id);return s.has("codex")&&(t.has("CODEX_AUTH_JSON")||t.has("OPENCODE_AUTH_JSON"))&&i.add("codex"),{...r,connected:[...i]}}var Ck=new Map(["anthropic","openai","google","x-ai","xai","deepseek","mistral","groq","perplexity","openrouter"].map((e,t)=>[e,t]));function Tk(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 yi="opencode";function Ek(e){return e.cost?.input===0&&e.cost?.output===0}function Qh(e){return e===yi?Number.MAX_SAFE_INTEGER:Ck.get(e)??Number.MAX_SAFE_INTEGER-1}function Mk(e,t){let n=Dk(t),r={},o=(e.providers??[]).map(s=>{let i=(s.models??[]).filter(a=>a.status!=="deprecated");return s.id===yi&&!n.has(yi)?{...s,models:i.filter(Ek),keyless:!0}:{...s,models:i,keyless:!1}}).filter(s=>(s.keyless||n.has(s.id))&&!fi.has(s.id)&&(s.models?.length??0)>0).sort((s,i)=>Qh(s.id)-Qh(i.id)).map(s=>{let i=[...s.models].sort((c,p)=>(p.released??"").localeCompare(c.released??"")||se(p.id)-se(c.id)),a=In(i)?.id??i[0]?.id;return a&&(r[s.id]=a),{id:s.id,name:s.name,source:s.keyless?"api":"env",models:Object.fromEntries(i.map(c=>{let p=Tk(c);return[c.id,{id:c.id,name:c.name,...c.released?{release_date:c.released}:{},...c.family?{family:c.family}:{},...c.reasoning!==void 0?{reasoning:c.reasoning}:{},...c.reasoning_options?{reasoning_options:c.reasoning_options}:{},...c.tool_call!==void 0?{tool_call:c.tool_call}:{},...c.attachment!==void 0?{attachment:c.attachment}:{},...c.modalities?{modalities:c.modalities}:{},...c.limit?{limit:c.limit}:{},...c.cost?{cost:c.cost}:{},...c.description?{description:c.description}:{},...c.open_weights!==void 0?{open_weights:c.open_weights}:{},...c.last_updated?{last_updated:c.last_updated}:{},...p.length>0?{variants:Object.fromEntries(p.map(d=>[d,{}]))}:{}}]}))}});return{all:o,connected:o.map(s=>s.id),default:r}}function Ok(e,t){if(!e)return t;if(!t)return e;let n=Mt(e),r=Mt(t),o=new Map;for(let d of Array.isArray(r.all)?r.all:[])o.set(d.id,d);let s=[],i=new Set;for(let d of Array.isArray(n.all)?n.all:[])s.push(o.get(d.id)??d),i.add(d.id);for(let d of Array.isArray(r.all)?r.all:[])i.has(d.id)||(s.push(d),i.add(d.id));let a=[],c=new Set;for(let d of[...Array.isArray(n.connected)?n.connected:[],...Array.isArray(r.connected)?r.connected:[]])c.has(d)||(a.push(d),c.add(d));let p={...r.default??{}};for(let[d,g]of Object.entries(n.default??{})){let m=o.get(d);(!m||m.models&&g in m.models)&&(p[d]=g)}return{...r,all:s,connected:a,default:p}}function Dk(e){let t=new Set;for(let n of Xh)mi(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 jk(e){let t=Object.fromEntries(Object.entries(e.models??{}).filter(([r])=>r!=="auto"&&r!=="kortix/auto").map(([r,o])=>{if(o.variants&&Object.keys(o.variants).length>0)return[r,o];let s=Wh({id:r,name:o.name,reasoning:o.reasoning,reasoning_options:o.reasoning_options}).reasoningEffort?.values;return s?.length?[r,{...o,variants:Object.fromEntries(s.map(i=>[i,{}]))}]:[r,o]})),n=Object.keys(t)[0];return{default:n?{kortix:n}:{},connected:["kortix"],all:[{id:"kortix",name:"Kortix",source:"gateway",models:t}]}}function $k(e,t){return Rk(Ik(Mt(e),t,Xh))}function Uk(e){if(e.gatewayEnabled)return e.modelPicker?jk(e.modelPicker):void 0;let t=e.secretNames??new Set,n=e.runtimeProviders?$k(e.runtimeProviders,t):void 0;return Ok(e.llmCatalogProviders?Mk(e.llmCatalogProviders,t):void 0,kk(n)?n:void 0)}function Fk(e){return"capabilities"in e&&e.capabilities!=null}function hi(e,t){let n=e.find(r=>r.providerID===t.providerID&&r.modelID===t.modelID);return!!n&&n.enabled!==!1}function Lk(e,t){if(!e)return[];let n=t?.providerMode??"gateway",r=Array.isArray(e.all)?e.all:[],o=Array.isArray(e.connected)?e.connected:[],s=[];for(let i of r)if(o.includes(i.id)&&!(n==="gateway"?!Cn.has(i.id):Cn.has(i.id)))for(let[a,c]of Object.entries(i.models)){if(a==="auto"||a==="kortix/auto")continue;let p;if(Fk(c)){let d=c.capabilities;p={reasoning:d.reasoning??!1,vision:d.input?d.input.image??!1:void 0,toolcall:d.toolcall??!1}}else{let d=c.modalities?.input;p={reasoning:c.reasoning??!1,vision:d?d.includes("image"):c.attachment,toolcall:c.tool_call??!1}}s.push({id:Nh({providerID:i.id,modelID:a}),providerID:i.id,providerName:c.provider_name??i.name,modelID:a,modelName:(c.name||a).replace("(latest)","").trim(),variants:c.variants,capabilities:p,contextWindow:c.limit?.context,releaseDate:c.release_date,family:c.family,cost:c.cost?{input:c.cost.input??0,output:c.cost.output??0}:void 0,providerSource:i.source,provider:c.provider,reasoningOptions:c.reasoning_options,description:c.description,openWeights:c.open_weights,lastUpdated:c.last_updated,enabled:c.enabled,free:c.free===!0})}return s}function Jh(e){return new Map(e.map(t=>[`${t.providerID}:${t.modelID}`,t]))}var Nk=new Set([zh]),Kk="kortix",Zh="codex",qk=new Set(Vh);function Gk(e,t){if(t)return t;let n=e.indexOf("/");return n===-1?e:e.slice(0,n)}function Ot(e){return Nk.has(e.modelID)}function Bk(e){return di(e.map(t=>({id:`${t.providerID}:${t.modelID}`,released:t.releaseDate,family:t.family,provider:t.provider??t.providerID})))}function Wk(e){let{connectedProviderIds:t}=e,n=e.freeTier??!1,r=Bk(e.catalogModels),o=Jh(e.catalogModels),s=new Map;for(let i of e.pins??[])s.set(`${i.providerID}:${i.modelID}`,i.visibility);return i=>{let a=`${i.providerID}:${i.modelID}`,c=s.get(a);if(c==="hide")return!1;if(i.providerID===Kk){let d=Gk(i.modelID,i.provider),g=d===Zh?t?.has(Zh)??!1:t?.has(d)??!1;if(qk.has(i.modelID))return!n||i.modelID===Yh;if(!g)return!1;if(c==="show"||r.has(a))return!0;let m=o.get(a);if(!m?.releaseDate)return Ot(i);try{let f=new Date(m.releaseDate);if(Number.isNaN(f.getTime()))return Ot(i)}catch{return Ot(i)}return!1}if(c==="show"||r.has(a))return!0;let p=o.get(a);if(!p?.releaseDate)return Ot(i);try{let d=new Date(p.releaseDate);if(Number.isNaN(d.getTime()))return Ot(i)}catch{return Ot(i)}return!1}}function Hk(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 eb(e,t){if(!e||Cn.has(e.providerID)||se(e.modelID)>0)return e;let n=t.filter(i=>i.providerID===e.providerID&&i.enabled!==!1);if(!n.some(i=>se(i.modelID)>0))return e;let r=i=>se(i)===1&&i.slice(i.indexOf(".")+1)===e.modelID,s=(n.find(i=>i.modelID===`global.${e.modelID}`)??n.find(i=>r(i.modelID)))?.modelID??In(n.map(i=>({id:i.modelID,released:i.releaseDate})))?.id;return!s||s===e.modelID?e:{...e,modelID:s}}function Vk(e,t){let n=(t?e?.agentDefaults?.[t]:void 0)??e?.projectDefault??e?.accountDefault??e?.platformDefault;return n?li(n):void 0}function zk(e){let{models:t,providers:n}=e,r=c=>hi(t,c),o=c=>c.find(p=>!!p&&r(p)),s=(()=>{if(e.configModel){let c=e.configModel.split("/");if(c.length>=2){let[p,...d]=c,g=d.join("/");if(r({providerID:p,modelID:g}))return{providerID:p,modelID:g}}}for(let c of e.recent??[])if(r(c))return c;if(n){let c=n.default||{},p=Array.isArray(n.all)?n.all:[],d=Array.isArray(n.connected)?n.connected:[],g=p.filter(m=>d.includes(m.id));for(let m of g){let f=c[m.id];if(f){let h={providerID:m.id,modelID:f};if(r(h))return h}for(let h of Xr(Object.keys(m.models).map(S=>({id:S})))){let S={providerID:m.id,modelID:h.id};if(r(S))return S}}}})(),i=o(e.picks??[]),a=i??o([e.serverDefault,e.globalDefault,e.agentModel,s]);return{model:eb(a,t),explicit:i,fallback:s}}export{Xv as ABORT_REASONS,gq as ABORT_REASONS_NOT_YET_EMITTED,Mi as ACCOUNTS_LIST_UNAVAILABLE_CODE,Wr as ACTIVE_INSTANCE_COOKIE,Ei as ANALYTICS_UNAVAILABLE_CODE,bA as ATTACHMENT_PART_REF_PREFIX,b as ApiError,X as AuthError,We as BillingError,TA as CONNECTION_FAULT_GRACE_MS,mA as CONNECTOR_POLL_FIRST_DELAY_MS,fA as CONNECTOR_POLL_INTERVAL_MS,yA as CONNECTOR_POLL_WINDOW_MS,IS as CONTEXT_TOOLS,eh as COST_MARKUP,ko as ConnectorApprovalPendingError,Yn as ConnectorCallError,Ro as ConnectorPageLimitError,CS as DEFAULT_CONTEXT_TOOL_TRIGGER_LABELS,KD as DEFAULT_NOTIFICATION_PREFERENCES,Zf as DEFAULT_TRANSCRIPT_OPTIONS,uA as DESTRUCTIVE_PHASES,oo as FEATURE_DISABLED_CODE,FR as FEATURE_FLAG_KEYS,Ii as FEATURE_NOT_SUPPORTED_CODE,ot as FILE_VERBS,an as FileExistsError,Vt as HeadlessAuthError,Vr as HostBoundaryError,db as IMPERSONATION_HEADER,ND as INBOX_NOTIFICATION_KINDS,ni as INBOX_OBSERVATION_MAX_MS,JB as INITIAL_SETTLED_CONNECTION,Jv as INSTANCE_SCOPED_ROUTES,y$ as KORTIX_TRANSCRIPT_SCHEMA,it as KortixMemberError,Vb as MAX_PROMPT_ATTACHMENTS_BYTES,Co as MAX_PROMPT_ATTACHMENT_BYTES,xl as MAX_PROMPT_ATTACHMENT_FILES,HK as MEMORY_VERBS,Ci as MODEL_NOT_SERVABLE_CODE,B_ as NO_GROUP_ACTIVITY_TOOLS,ri as OPTIMISTIC_ABORT_MAX_MS,x1 as OPTIMISTIC_COMPACTION_MAX_MS,ei as OPTIMISTIC_RECEIPT_MAX_MS,PB as PERSISTED_QUERY_CACHE_VERSION,xw as PLUMBING_TOOLS,NB as PREVIEW_PROBE_TIMEOUT_MS,LC as PROJECT_SESSION_NAME_LOOKUP_LIMIT,FC as PROJECT_SESSION_PAGE_DEFAULT_LIMIT,y_ as PROJECT_SESSION_PAGE_MAX_LIMIT,Ti as PROVISION_IN_FLIGHT_CODE,Lo as PublicSessionShareError,kq as RUNTIME_NOT_READY_MARKERS,_$ as RUNTIME_PERMISSION_CAPABILITIES,b$ as RUNTIME_PERMISSION_REPLIES,ut as RequestTooLargeError,tn as RuntimeNotReadyError,Rs as SANDBOX_FS_ROOTS,$e as SANDBOX_PORTS,UA as SERVER_COMPACTION_REVALIDATE_MS,ti as SERVER_OBSERVATION_MAX_MS,D1 as SESSION_LIST_STATUS,U1 as SESSION_NOTICE,W_ as STANDALONE_TOOLS,kn as STREAM_OBSERVATION_MAX_MS,Hr as SandboxNotReadyError,Pt as SessionNotReadyError,Oo as SessionStartError,u1 as TURN_END_LEDGER_LAG_MS,hP as TURN_ERROR_CODES,I1 as WAKE_ESCALATION_COOLDOWN_MS,R1 as WAKE_MAX_RESTARTS,k1 as WAKE_NO_PROGRESS_MS,_s as WIRE_ID_BACKDATE_MS,Ze as WIRE_ID_CLOCK_TOLERANCE,Fe as WIRE_ID_TIME_MASK,Jt as WIRE_ID_TIME_SCALE,dP as WIRE_MESSAGE_ID,Qk as __getConfigResolver,Yk as __setConfigResolver,mq as abortErrorReason,na as acceptAccountInvite,oG as acceptInvite,jd as actReviewItem,Cc as activateConnection,Mc as addComputerToProject,cd as addGroupMembers,_g as addMarketplaceSource,T1 as advanceWakeEscalation,mw as allDescendantIds,Sh as appendPreviewToken,ja as approveProjectAccessRequest,V$ as approveTask,Vn as archiveProject,t0 as assignTicket,Wa as attachGroupToProject,gs as authMfa,us as authUser,M as authenticatedFetch,Xn as authenticatedRequest,FB as authorizePreviewUrl,l as backendApi,HT as bindSlackIdentity,VT as bindTeamsIdentity,rc as brokerProjectSecretRequest,wB as browserKeyValueStorage,eA as buildInstancePath,WB as buildPresentationTemplateImageUrl,BB as buildPresentationTemplatePdfUrl,xh as buildPreviewAuthEndpoint,sB as buildPublicTemplateUrl,CA as buildRuntimePresentationConversionUrl,gl as buildSandboxTemplate,kw as buildScrapeFailureResults,jU as buildStaticFileHealthPreviewUrl,DU as buildStaticFileLocalUrl,OU as buildStaticFilePreviewUrl,Ox as buildStaticFileServicePath,gW as buildTunnelEventStreamUrl,NU as buildWebProxyUrl,$d as bulkActReviewItems,ME as bulkDeletePolicies,OE as bulkImportPolicies,gN as burstSummary,mN as burstSummaryLabel,mt as callConnector,nO as cancelAccountDeletion,Ji as cancelAccountInvite,Hq as cancelSandbox,wG as cancelSandboxUpdate,gp as cancelScheduledChange,up as cancelSubscription,KG as checkAccessEmail,QL as childMapByParent,TG as claimComputer,Hx as claimNext,OT as claimPerSeatBilling,iu as claimWarmProjectSession,Ry as classifyPart,RA as classifyPreviewProbeStatus,PP as classifyPtyClose,uw as classifyTurn,rN as cleanErrorMessage,xN as cleanResultSnippet,UK as cleanWorkerOutput,Di as clearImpersonationSession,ck as clearKortixAppViewerCache,Hu as clearModelDefault,kC as clearSessionFresh,Ll as closeChangeRequest,C0 as closeMilestone,HL as collectTurnParts,r0 as commentTicket,ql as commitSessionChanges,w1 as compactionExpiryAtMs,yN as compactionTurnInfo,BL as compareMessagesForDisplay,Vx as completeInFlight,Rp as completeSlackInstall,Ip as completeTeamsInstall,Lh as composerSelectableAgents,Zy as computeStatusFromPart,hp as configureAutoTopup,to as configureKortix,cp as confirmCheckoutSession,jp as connectEmail,vp as connectSlack,XB as connectionFromHealth,QB as connectionIsFaulted,CI as connectionSharedWithEveryone,Kb as connectorConnect,qb as connectorFinalize,pB as connectorHeadline,jN as contextLabelForTool,iL as contextToolSummary,aL as contextToolTrigger,PO as convertPresentationToGoogleSlides,HB as convertRuntimePresentation,kr as copyFile,_p as costExportUrl,d1 as countLiveInboxPrompts,kO as countReviewItemsBySegment,Ki as createAccount,cg as createAccountAuditWebhook,dc as createAccountSecretResource,Xd as createAccountToken,Sg as createApp,Tg as createAppAccessSession,Mg as createAppDeployment,Ag as createAppToken,zg as createAppVolume,Jg as createAppVolumeSnapshot,$N as createArtifactKind,Id as createAssignment,EM as createAuditWebhook,cG as createBackup,ap as createCheckoutSession,Hc as createConnector,cB as createConnectorLinkInfoCache,Ar as createFile,Zp as createGatewayKey,od as createGroup,rk as createHttpSessionSyncController,RG as createInstance,qx as createKortix,Xm as createKortixPty,fs as createKortixSession,nD as createMarketplaceInstallSession,R0 as createMilestone,Wk as createModelVisibility,wd as createOAuthClient,MT as createPerSeatCheckout,SB as createPersistedQueryCache,CE as createPolicy,lp as createPortalSession,ga as createProject,g0 as createProjectAgent,ng as createProjectCliToken,ma as createProjectRepo,Ya as createProjectResourceGrant,ht as createProjectSession,Pa as createProjectSkill,Cu as createProjectTrigger,qf as createPromptAttachmentController,fd as createRole,mW as createSSEStream,Lq as createSandbox,Nd as createSandboxShare,ul as createSandboxTemplate,IC as createSavedCopyStore,GE as createScimToken,wM as createServiceAccountApi,sr as createSessionPrompt,ru as createSessionPublicShare,Bx as createSessionQueue,Wd as createSessionReminder,cM as createSsoGroupMapping,B$ as createTask,J$ as createTicket,fW as createTunnelEventStream,sW as createWarmSessionPool,Vl as currentSavedCopyStore,ra as declineAccountInvite,sG as declineInvite,rO as deleteAccountImmediately,fc as deleteAccountSecretResource,vg as deleteApp,Fg as deleteAppDeployment,OM as deleteAuditWebhook,uG as deleteBackup,zc as deleteConnector,el as deleteConnectorCredential,$0 as deleteCredential,OD as deleteDriveFile,Ym as deleteEnv,kt as deleteFile,Xp as deleteGatewayBudget,Ea as deleteGitHubInstallation,id as deleteGroup,IG as deleteInstance,S0 as deleteKortixProject,E0 as deleteMilestone,kd as deleteOAuthClient,lc as deletePersonalProjectSecret,EE as deletePolicy,f0 as deleteProjectAgent,sc as deleteProjectProviderOAuth,Qa as deleteProjectResourceGrant,ac as deleteProjectSecret,bu as deleteProjectSession,Eu as deleteProjectTrigger,qt as deletePromptAttachment,bd as deleteRole,dl as deleteSandboxTemplate,AM as deleteServiceAccountApi,du as deleteSessionPrompt,Ko as deleteSessionReminder,zd as deleteSessionReminders,lM as deleteSsoGroupMapping,iM as deleteSsoProvider,z$ as deleteTask,o0 as deleteTicket,ta as describeAccountInvite,xo as describeConnectorTool,Bg as destroyAppMachine,Qg as destroyAppVolume,Va as detachGroupFromProject,Cx as detectLocalhostUrls,N1 as directSubsessions,vM as disableServiceAccountApi,$p as disconnectEmail,bB as disconnectGitHubApp,Tp as disconnectSlack,OI as discoverConnectionOAuth2,DI as discoverConnectionOAuth2Resource,Vc as discoverConnectorAuth,Gq as discoverLocalSandbox,kD as dismissDriveConflict,rB as downloadAccountAudit,ID as downloadDriveFile,Q0 as dropClientForUrl,Z0 as dropPublicClientForUrl,Xx as editQueued,gu as editSessionPrompt,Wx as enqueue,p0 as ensurePmSession,kA as ensurePreviewSessionCookie,TI as ensureProjectConnectorConnection,lA as ensureSandbox,su as ensureWarmProjectSession,bP as env,as as exchangeCode,Hg as execInApp,ig as exportAccountAudit,he as extractGatewayErrorDetails,wn as extractInstanceRoute,Pv as extractSkillBaseDir,aq as extractSkillContent,hv as extractSkillFiles,LK as extractWorkerPreview,zx as failInFlight,cK as fallbackBusyRowAfterTurnId,Ws as familyForTool,Si as featureDisabledKey,bm as featureFlags,CT as fetchAccountStateWithToken,OR as fetchAccountsWithToken,RB as fetchAttachmentPart,qT as fetchCostExportCsv,Oh as fetchKortixAppViewer,_l as fetchProjectArchive,dC as fetchProjectFileRaw,HR as fetchProjectsForAccountWithToken,ym as fetchSessionAttachment,nx as fileDownloadRequest,GK as filePhase,qK as fileVerb,mx as files,Wo as finalizeAppArtifact,zG as finalizeConnectorSetupLink,KC as findActiveTranscriptShare,wr as findFiles,VL as findLastTextPart,ij as findSessionAttachments,vr as findText,Ou as fireProjectTrigger,ll as fixSandboxWithAgent,Lk as flattenModels,BN as flattenThought,em as forkAppVolume,vi as formatBillingErrorForUI,TK as formatCost,RK as formatDuration,oN as formatJsonFailureOutput,VN as formatMessageDay,zN as formatMessageExact,Iq as formatOpenCodeRuntimeError,PN as formatRawOutput,cA as formatRuntimeError,EK as formatTokens,oS as formatTranscript,dK as freshSendHint,Gx as generateSessionId,qi as getAccount,Bi as getAccountBranding,eO as getAccountDeletionStatus,ep as getAccountState,tp as getAccountStateMinimal,nA as getActiveInstanceIdFromCookie,fO as getAdminBootModes,pO as getAdminProviderAnalytics,cO as getAdminProviderDistribution,gO as getAdminProviderFallback,oO as getAdminRole,US as getAgentCardLabel,xT as getAgentConfig,y0 as getAgentPersona,PG as getAllVersions,YL as getAnsweredQuestionParts,Go as getApp,Rg as getAppAccess,kg as getAppAuthEnv,Dg as getAppDeployment,jg as getAppDeploymentLogs,JO as getApprovalLink,Ft as getAuthToken,SI as getAuthTokenWithRetry,yp as getAutoTopupSettings,ET as getAutoTopupSetupStatus,op as getBillingCreditBreakdown,ip as getBillingTierConfigurations,rp as getBillingTransactionsSummary,sp as getBillingUsageHistory,Dl as getChangeRequest,jl as getChangeRequestDiff,$l as getChangeRequestMergePreview,SL as getChildSessionError,wy as getChildSessionId,wL as getChildSessionToolParts,et as getClient,Ce as getClientForUrl,Jc as getConnectStatus,MI as getConnectionOAuth2Application,LI as getConnectionOAuth2Status,NI as getConnectionPolicies,Lt as getConnectorCatalog,Gc as getConnectorConfig,Kc as getConnectorPolicies,HG as getConnectorSetupLink,KT as getCostSummary,tA as getCurrentInstanceIdFromPathname,bq as getCurrentInstanceIdFromWindow,bf as getCurrentProject,Xu as getDefaultAccountState,kL as getDiagnostics,$S as getDirectory,Ao as getDiscoverConnector,HI as getDiscoverIntegration,tm as getDriveFileUrl,Op as getEmailInstallation,Dp as getEmailMode,KM as getEnterpriseDemo,Sr as getFileStatus,xy as getFileWithDir,jS as getFilename,xD as getFolderAccess,pA as getFullChangelog,Hp as getGatewayBreakdown,Yp as getGatewayBudgets,zp as getGatewayErrors,Jp as getGatewayKeys,Gp as getGatewayLog,Bp as getGatewayOverview,Fp as getGatewayRoutingPolicy,Wp as getGatewaySeries,Vp as getGatewaySessions,mB as getGitHubAppStatus,wa as getGitHubInstallation,_O as getGoogleAuthUrl,rd as getGroup,PL as getHiddenToolParts,fb as getImpersonationSession,rG as getInvite,kG as getJustavpsServerTypes,_0 as getKortixProject,P0 as getKortixProjectBySession,ef as getKortixPtyWebSocketUrl,_G as getLatestSandboxVersion,ZG as getMaintenanceConfig,Ma as getManagedGitBackend,qR as getManagedGitStatus,yg as getMarketplaceCatalogItem,hg as getMarketplaceCatalogItemFile,zE as getMfaRequired,A0 as getMilestone,Bu as getModelDefaults,im as getNotificationPreferences,Sd as getOAuthClient,BG as getOAuthConsentRequest,vq as getOpenCodeConfigInvalidError,hL as getPartText,hM as getPatPolicy,RL as getPermissionForTool,qn as getProject,h0 as getProjectActivity,Cl as getProjectCommit,Tl as getProjectCommitDiff,Gn as getProjectDetail,PD as getProjectDrive,El as getProjectFileHistory,da as getProjectGitToken,Bn as getProjectLlmCatalog,NR as getProjectLlmCatalogProviders,gr as getProjectModelAccess,Wn as getProjectModelPicker,Qn as getProjectSandboxHealth,GR as getProjectSandboxProviderTransition,or as getProjectSession,_u as getProjectSessionConfigState,Su as getProjectSessionScope,mp as getProrationPreview,Uq as getProviders,$U as getProxyBaseUrl,J0 as getPublicClientForUrl,LG as getPublicMarketplaceItem,NG as getPublicMarketplaceItemFile,DO as getPublicSessionShare,jO as getPublicSessionShareMessages,XG as getPublicShareByToken,iB as getPublicTemplate,IL as getQuestionForTool,oE as getReferralCode,aE as getReferralStats,MK as getRetryInfo,OK as getRetryMessage,Od as getReviewItem,gd as getRolePermissions,md as getRoleUsage,Qs as getRuntimeConfigInvalidError,gG as getSSHConnection,Fq as getSandbox,Nq as getSandboxById,Mq as getSandboxPortUrl,EG as getSandboxProvisionStatus,MG as getSandboxProvisionStreamUrl,bG as getSandboxUpdateStatus,gh as getSandboxUrl,ze as getSandboxUrlForExternalId,YG as getSecretSetupLink,Is as getServerHealth,L0 as getServiceLogs,au as getSessionAudit,CK as getSessionCost,pr as getSessionCostRecord,q_ as getSessionDrives,Af as getSessionHealth,ku as getSessionMessageAuthors,Ru as getSessionModelUsage,qC as getSessionOpenBundle,XE as getSessionOversight,Jl as getSessionParticipants,gM as getSessionPolicy,tu as getSessionPreviewCandidates,_c as getSessionProviderSecretPool,cu as getSessionTranscript,lu as getSessionTranscriptSync,uu as getSessionTurn,Zl as getSessionWatch,yK as getShellModePart,Ep as getSlackChannelFile,wp as getSlackInstallation,Cp as getSlackManifest,Ap as getSlackMode,nM as getSsoProvider,Dx as getStaticFileHealthPath,bo as getSupabaseAccessToken,$b as getSupabaseAccessTokenWithRetry,K$ as getTask,G$ as getTaskStatus,sD as getTemplate,Q$ as getTicket,vL as getToolInfo,Us as getToolPrimaryArg,sS as getTranscriptFilename,IK as getTurnCost,wK as getTurnError,AK as getTurnErrorDetails,vK as getTurnErrorRawText,kK as getTurnStatus,bp as getUsageRollup,tB as getUserRolesWithToken,Ml as getVersionDiff,cm as getWebPushPublicKey,xK as getWorkingState,yc as grantAccountSecretResource,Zq as grantSandboxProjectAccess,wT as grantSecretToAgent,WL as groupMessagesIntoTurns,nK as groupShowSegments,Wy as groupSteps,DK as hasDiffs,MU as hasLocalhostUrls,Mx as hasPreviewTarget,ZL as hasRetryingAssistantTurn,CP as heartbeatGapEvent,yu as holdSessionPrompts,Fd as humanizeReviewActionPath,Dr as humanizeSearchQuery,Ay as humanizeToolName,ji as impersonationHeaders,oM as importSsoProviderFromMetadata,p1 as inboxObservationSupersedes,Rh as initialWakeEscalationState,Ke as inputPath,iD as installTemplate,mu as interruptSessionPrompt,_o as invalidateTokenCache,Qi as inviteAccountMember,Na as inviteProjectMember,ua as inviteRepoCollaborator,Br as isAbortError,_b as isAdminBypassEnabled,dL as isAgentPart,kx as isAppRouteUrl,bL as isAttachment,_A as isAttachmentPartRef,jt as isAuthFailure,wi as isBillingError,gL as isCompactionPart,no as isConfigured,sL as isContextTool,hG as isDestructivePhase,ak as isEmptyConversation,zo as isEmptyShowPart,nN as isErrorOutput,GU as isExternalUrl,xi as isFeatureDisabledError,Sy as isFilePart,gb as isImpersonationSessionLive,yq as isInstanceDetailPath,Zv as isInstanceScopedAppPath,LU as isInternalLocalhostUrl,gm as isInvisibleActivityPart,aI as isInviteSent,PK as isLastUserMessage,KA as isLegacyMigratedSession,LR as isManagedGithubProject,dm as isNoGroupActivityTool,hi as isOfferedModel,Aq as isOpenCodeConfigInvalidError,Wl as isPaintableSavedCopy,fL as isPatchPart,xB as isPersistableQueryKey,FU as isPreviewUrl,jx as isProxiableLocalhostUrl,QD as isQuestionTool,Me as isReasoningPart,fw as isRetryableTurnError,rA as isRuntimeConfigInvalidError,iA as isRuntimeNotReadyResponse,vf as isRuntimeReady,Rq as isRuntimeStartingError,An as isSandboxNotReadyError,Zo as isSelectableAgent,_f as isServerReachable,sj as isSessionAttachmentRef,Bl as isSessionFresh,rT as isSessionStartError,YD as isShellActivityTool,fv as isShellMode,FK as isShortOutput,HD as isShowContentUnavailable,fr as isShowPayloadEmpty,mL as isSnapshotPart,mm as isStandaloneActivityTool,yL as isStepPart,zr as isSubdomainPreviewUrl,Ee as isTextPart,J as isToolPart,xL as isToolPartHidden,h$ as isTurnErrorCode,uf as isUnderSandboxRoot,qU as isWebProxyUrl,mP as isWireIdAheadOf,uk as kortixAppViewerToken,dk as kortixBinding,vP as kortixPty,Dh as kortixToken,ia as leaveAccount,Ca as linkGitHubInstallation,xa as linkRepository,og as listAccountAudit,ag as listAccountAuditWebhooks,Xi as listAccountInvites,Yi as listAccountMembers,wE as listAccountResourceGrants,pc as listAccountSecretResources,fM as listAccountSessions,Qd as listAccountTokens,Ni as listAccounts,UE as listActions,lO as listAdminSandboxes,pd as listAgentIdentities,vc as listAllConnections,Ig as listAppAgents,Og as listAppDeployments,Ng as listAppMachines,Xg as listAppVolumeSnapshots,Vg as listAppVolumes,xg as listApps,Rd as listAssignments,DM as listAuditEvents,TM as listAuditWebhooks,aG as listBackups,np as listBillingTransactions,Ol as listChangeRequests,QT as listChannelBindings,s0 as listColumns,BI as listConnectSections,GI as listConnectToolkits,wc as listConnections,So as listConnectorAccounts,Po as listConnectorTools,$c as listConnectors,NT as listCostByProject,O0 as listCredentialEvents,M0 as listCredentials,vo as listDiscoverConnectors,WI as listDiscoverIntegrations,Xc as listDiscoverSections,AD as listDriveConflicts,RD as listDriveFiles,N_ as listDriveFolder,DD as listDriveVersions,Vm as listEnv,fg as listFeaturedMarketplaces,a0 as listFields,ln as listFiles,vD as listFolderPrincipals,qp as listGatewayLogs,va as listGitHubInstallations,ka as listGitHubRepositories,Ra as listGitHubRepositoryBranches,ad as listGroupMembers,yE as listGroupProjectGrants,nd as listGroups,x0 as listKortixProjectSessions,b0 as listKortixProjects,Qm as listKortixPty,Aa as listLinkableGitHubInstallations,Oa as listManagedGitRepositories,gg as listMarketplaceCatalogItems,bg as listMarketplaceSources,mg as listMarketplaces,hE as listMemberGroups,bE as listMemberProjectAccess,k0 as listMilestoneEvents,v0 as listMilestones,ea as listMyAccountInvites,om as listNotifications,xd as listOAuthClients,Zd as listOAuthGrants,Xa as listPendingApprovals,Ka as listPendingProjectInvites,Td as listPermissions,Yc as listPipedreamApps,Qc as listPipedreamSections,IE as listPolicies,Ua as listProjectAccess,Da as listProjectAccessRequests,dd as listProjectAgentIdentities,d0 as listProjectAgents,sg as listProjectAudit,Rl as listProjectBranches,tg as listProjectCliTokens,Il as listProjectCommits,yl as listProjectDirectory,fl as listProjectFiles,Ba as listProjectGroupGrants,ol as listProjectPolicies,oc as listProjectProviderOAuth,Yd as listProjectReminders,za as listProjectResourceGrants,il as listProjectSandboxTemplates,ml as listProjectSandboxes,ec as listProjectSecrets,yt as listProjectSessions,Ql as listProjectSessionsPage,al as listProjectSnapshots,ju as listProjectTriggerEventApps,Du as listProjectTriggerEventTypes,Iu as listProjectTriggers,dt as listProjects,la as listProjectsForAccount,UG as listPublicMarketplaceItems,FG as listPublicMarketplaces,cE as listReferrals,Md as listReviewItems,ud as listRoles,Jq as listSandboxProjectMembers,Ld as listSandboxShares,qq as listSandboxes,qE as listScimTokens,SM as listServiceAccountsApi,F0 as listServiceTemplates,U0 as listServices,qI as listSessionConnectRequests,Pp as listSessionCosts,$D as listSessionDrives,pu as listSessionPrompts,Pc as listSessionProviderSecretPools,nu as listSessionPublicShares,Bd as listSessionReminders,Ja as listSessionsNeedingInput,qO as listSignedInDevices,aM as listSsoGroupMappings,q$ as listTaskEvents,N$ as listTasks,l0 as listTemplates,X$ as listTicketEvents,Y$ as listTickets,nk as loadHttpSessionHistory,Xe as loadPreviewUrlTemplate,Dy as looksLikeError,IN as looksLikeHtml,_N as looksLikeJsonPayload,ED as makeDriveFolder,IO as mapApiReviewItem,CG as markInstanceError,sm as markNotificationsRead,nr as markSessionFresh,qm as maxWireIdClock,VK as memoryRelPath,GN as mergeBurstSteps,Fl as mergeChangeRequest,HN as messageCreatedAt,sv as messageTime,dO as migrateAdminSandboxProvider,Ps as mintWireMessageId,Bm as mintWireMessageIdAbove,gn as mkdir,Hk as modelInDefaultView,Pk as modelRefToKey,MD as moveDriveFile,Gy as narrateFailedStep,qy as narrateStep,Kr as narrationToolName,TP as narrowChatEvent,fP as newestWireIdClock,uB as nextConnectorPollDelay,pe as normalizeActivityToolName,xq as normalizeAppPathname,BU as normalizeExternalInput,z as normalizeName,vy as normalizeToolName,BA as notifyHostSignal,Ul as openChangeRequest,vs as openEventStream,oB as openStressTestStream,rl as paginateConnector,Dn as parseBillingError,SN as parseEmbeddedFailure,pj as parseFlagOverride,Pw as parseJsonFailure,Tr as parseLocalhostUrl,zK as parseMemoryView,wq as parseOpenCodeErrorPayload,ZK as parsePresentationOutput,wf as parseProxyHop,tq as parseQuestionAnswersFromOutput,oq as parseReadOutput,dh as parseRuntimeErrorPayload,Aw as parseScrapeInputUrls,Rw as parseScrapeOutput,Df as parseSubdomainUrl,NK as parseTaskRows,KU as parseWebProxyUrl,Fy as parseWebSearchOutput,jy as partOutcome,w0 as patchKortixProject,XK as patchVerb,Uk as pickerProviderList,Wc as pipedreamConnect,Dc as pipedreamConnectConnection,tl as pipedreamFinalize,jc as pipedreamFinalizeConnection,k as platformConfig,FI as pollConnectionOAuth2DeviceAuthorization,yo as pollProjectProviderOAuth,Kp as previewGatewayRoute,YE as previewMfaRequired,zT as previewSlackIdentity,YT as previewTeamsIdentity,_d as probeEffectivePermission,Pd as probeEffectivePermissions,KB as probePreviewPort,Pl as projectArchiveRequest,S1 as projectCompacting,_k as projectConfigAgentsToOpenCodeAgents,Fh as projectConfigAgentsToRuntimeAgents,YB as projectSessionConnection,K1 as projectSessionForRuntimeId,nT as projectSessionStartSeed,m1 as projectWorking,fa as provisionProject,KR as provisionProjectStream,VR as provisionProjectWithToken,Mf as proxyLocalhostUrl,UU as proxyUrlToInternal,fp as purchaseCredits,EI as putConnectionOAuth2Application,oy as rawErrorText,Vq as reactivateSandbox,pp as reactivateSubscription,pn as readBlob,CD as readDriveFile,un as readFile,ci as readKortixMember,bl as readProjectFile,nv as reasoningIsRunning,cl as rebuildProjectSnapshot,Ac as reconcileConnection,kc as reconcileMemberConnection,K0 as reconcileServices,GG as recordPlatformLogout,Gs as recoverLinkResults,sE as refreshReferralCode,zt as refreshSession,Bo as registerAppArtifact,jI as registerConnectionOAuth2Client,nm as registerDeviceToken,q0 as registerService,lm as registerWebPushSubscription,$a as rejectProjectAccessRequest,AL as relativizePath,Pu as reloadProjectSessionConfig,xu as reloadProjectSessionConfigStream,ug as removeAccountAuditWebhook,Vi as removeAccountBrandingAsset,oa as removeAccountMember,ld as removeGroupMember,Zm as removeKortixPty,Pg as removeMarketplaceSource,Qx as removeQueued,Ec as renameConnection,Ir as renameFile,Kq as renameSandbox,Nl as reopenChangeRequest,T0 as reopenMilestone,Jx as reorderQueued,i0 as replaceColumns,c0 as replaceFields,Sa as replaceProjectRepository,u0 as replaceTemplates,tO as requestAccountDeletion,Kl as requestChangesOnChangeRequest,iI as requestProjectAccess,dg as requestProjectConnector,pg as requestProjectSecret,TT as requestTopUp,gk as requireKortixMember,Zi as resendAccountInvite,Ga as resendPendingProjectInvite,zi as resetAccountBranding,X0 as resetClient,Np as resetGatewayRoutingPolicy,cs as resetPassword,eU as resetPublicClient,SG as resetSandboxUpdateStatus,Za as resolveApproval,bk as resolveComposerAgent,zk as resolveComposerModel,lB as resolveConnectorStart,Vk as resolveModelDefault,NC as resolvePublicShareUrl,CN as resolveScrapeResults,gK as resolveWorkingTurn,IT as resolvedPlan,Gg as restartAppMachine,ir as restartProjectSession,Bq as restartSandbox,Zg as restoreAppVolume,lG as restoreBackup,jD as restoreDriveVersion,mc as retryAccountSecretResource,Yx as retryFailed,fu as retrySessionPrompt,j0 as revealCredential,AO as reviewItemTarget,R_ as reviewSegmentForStatus,RO as reviewVerdictForStatus,hc as revokeAccountSecretResourceGrant,yM as revokeAccountSession,Jd as revokeAccountToken,Cd as revokeAssignment,Ic as revokeConnection,ed as revokeGatewayKey,eg as revokeOAuthGrant,qa as revokePendingProjectInvite,La as revokeProjectAccess,rg as revokeProjectCliToken,eG as revokeSandboxProjectAccess,Kd as revokeSandboxShare,BE as revokeScimToken,ou as revokeSessionPublicShare,nt as rewriteLocalhostUrl,Lg as rollbackApp,qA as rootRuntimeSession,gc as rotateAccountSecretResource,Ad as rotateOAuthClientSecret,Io as runConnector,td as runGatewayPlayground,pI as runProjectProviderOAuthFlow,si as runtimeSessionsOf,yx as runtimeSupports,wP as sanitizePtyChunk,Ia as saveGitHubInstallation,ik as savedCopyEmptyRoot,Wg as scaleApp,dp as scheduleDowngrade,Sc as searchConnectorTools,hl as searchProjectFiles,JN as segmentTurn,mj as selectableProjectAgents,os as sendMagicLink,lE as sendReferralEmails,v1 as serverCompactionRevalidateAtMs,N0 as serviceAction,$1 as sessionConnectionLabel,j1 as sessionListStatus,Au as sessionModelPin,UC as sessionParentId,BC as sessionPromptActions,oT as sessionStartKey,bc as setAccountSecretResourceAccess,_q as setActiveInstanceCookie,yO as setAdminBootModes,bb as setAdminBypass,uO as setAdminProviderDistribution,mO as setAdminProviderFallback,zu as setAgentScope,xI as setBootstrapAuthToken,PI as setCachedAuthToken,KI as setConnectionPolicies,Lc as setConnectorAuthorizationStrategy,Zc as setConnectorCredential,Fc as setConnectorCredentialMode,Bc as setConnectorName,qc as setConnectorPolicies,VI as setConnectorSecretBinding,Nc as setConnectorSensitive,Tc as setDefaultConnection,qM as setEnterpriseDemo,zm as setEnv,Qp as setGatewayBudget,Lp as setGatewayRoutingPolicy,yB as setGitHubAppFromExisting,hB as setGitHubAppPat,iR as setImpersonationSession,eB as setMaintenanceConfig,FE as setMemberSuperAdmin,QE as setMfaRequired,Wu as setModelDefault,cc as setPersonalProjectSecret,mr as setProjectModelAccess,pT as setProjectModelEnablement,_a as setProjectOnboardingComplete,WR as setProjectOnboardingProfile,sl as setProjectPolicies,nc as setProjectSecretStrategy,vu as setProjectSessionModel,wu as setProjectSessionScope,Xl as setProjectSessionSharing,Mu as setProjectTriggersActivation,CC as setSavedCopyStore,JE as setSessionOversight,xc as setSessionProviderSecretPool,eu as setSessionWatch,ZB as settleSessionConnection,dG as setupSSH,Oc as shareConnection,SD as shareFolder,XD as shellActivityGroupLabel,lh as shellExitCode,hb as shouldAttachImpersonation,SK as shouldHideResponsePart,ES as shouldShowToolPart,aK as shouldSuppressWorkingTurnBusy,rK as showGroupItems,Jy as showTurnBusyIndicator,rs as signInWithPassword,is as signInWithProvider,ds as signInWithSso,ms as signOut,GO as signOutDevice,ns as signUp,lq as skillDocumentPath,cq as skillInputDir,XL as sortSessions,_L as splitUserParts,$g as startApp,Kg as startAppMachine,$I as startConnectionOAuth2Authorization,UI as startConnectionOAuth2DeviceAuthorization,VG as startConnectorSetupLink,fB as startGitHubAppManifest,fo as startProjectProviderOAuth,Ye as startProjectSession,qu as startProjectSessionOrThrow,JG as startSessionWithToken,H$ as startTask,$y as stepLabel,Ug as stopApp,qg as stopAppMachine,ar as stopProjectSession,Wq as stopSandbox,Ta as storeGitHubUserToken,CL as stripAnsi,hq as stripInstancePrefix,te as stripTrailingSlashes,qG as submitAccessRequest,nB as submitDemoRequest,WG as submitOAuthConsent,Dd as submitReviewItem,QG as submitSecretSetupLink,aR as subscribeToImpersonation,kR as supabaseClient,Uc as syncConnectors,DT as syncSubscription,tU as systemReload,tt as toDaemonPath,Pq as toInstanceAwarePath,$x as toInternalUrl,cn as toSandboxAbsolutePath,UL as toToolView,pf as toWorkspaceRelative,Fs as toolInfo,re as toolKind,Hv as toolViewModel,xG as triggerSandboxUpdate,_P as triggersRequest,jA as turnEndCause,_1 as turnEndNotice,zL as turnHasSteps,lK as turnIsConfirmedActive,uK as turnRendersQueued,F1 as turnRetryLabel,n0 as unassignTicket,rm as unregisterDeviceToken,um as unregisterWebPushSubscription,wD as unshareFolder,de as unwrapError,lg as updateAccountAuditWebhook,Wi as updateAccountBranding,sa as updateAccountMemberRole,Gi as updateAccountName,ST as updateAgentConfig,wg as updateApp,Cg as updateAppAccess,Yg as updateAppVolume,MM as updateAuditWebhook,Gl as updateChangeRequest,XT as updateChannelBinding,Rc as updateConnectionCredential,Up as updateEmailPolicy,ha as updateExperimentalFeature,ya as updateFeatureFlag,sd as updateGroup,Jm as updateKortixPty,I0 as updateMilestone,am as updateNotificationPreferences,vd as updateOAuthClient,ls as updatePassword,bM as updatePatPolicy,TE as updatePolicy,Hn as updateProject,Fa as updateProjectAccess,m0 as updateProjectAgent,Yu as updateProjectDefaultAgent,Ha as updateProjectGroupGrant,ba as updateProjectSandboxProvider,hu as updateProjectSession,Tu as updateProjectTrigger,yd as updateRole,hd as updateRolePermissions,pl as updateSandboxTemplate,mM as updateSessionPolicy,No as updateSessionReminder,Vd as updateSessionReminders,W$ as updateTask,BR as updateTemplateWarmPool,Z$ as updateTicket,e0 as updateTicketStatus,ps as updateUserMetadata,Hi as uploadAccountBrandingAsset,Eg as uploadAppArtifactArchive,wo as uploadConnectorAttachment,TD as uploadDriveFile,dn as uploadFile,lx as uploadNativeFile,tr as uploadPromptAttachment,fm as uploadSessionAttachment,Mp as uploadSlackChannelFile,on as uploadTimeoutMsForBytes,D0 as upsertCredential,ic as upsertProjectGitCredential,tc as upsertProjectSecret,rM as upsertSsoProvider,pa as validateProjectManifest,iE as validateReferralCode,aa as validateToken,tE as verifyGatewayProvider,yk as verifyKortixToken,ss as verifyOtp,sM as verifySsoDomain,M1 as wakeEscalationAttemptSummary,E1 as wakeEscalationNote,C1 as wakeProgressFingerprint,St as wireIdClock,Zt as wireIdClockAt,wt as wireIdClockDelta,f1 as workingExpiryAtMs,pK as workingTurnDrawsBusyRow,JD as writeActivityGroupLabel,Rr as writeFile,Bs as wsDomain,RN as wsFavicon,kN as wsRootDomain};
94
+ `),o=0;for(;o<n.length&&o<r.length&&n[o]===r[o];)o++;let s=n.length,i=r.length;for(;s>o&&i>o&&n[s-1]===r[i-1];)s--,i--;let a=[];for(let c=0;c<o;c++)a.push({type:"unchanged",text:n[c]});for(let c=o;c<s;c++)a.push({type:"removed",text:n[c]});for(let c=o;c<i;c++)a.push({type:"added",text:r[c]});for(let c=s;c<n.length;c++)a.push({type:"unchanged",text:n[c]});return a}function bv(e){let t=W(e?.oldString),n=W(e?.newString);return t!==void 0&&n!==void 0?[[t,n]]:(Array.isArray(e?.edits)?e.edits:[]).flatMap(o=>{let s=gt(o),i=s&&W(s.oldText),a=s&&W(s.newText);return i!==void 0&&a!==void 0?[[i,a]]:[]})}function _v(e){let t=bv(e.input),n=t.map(([o,s])=>hv(o,s)),r=t.length&&n.every(Boolean)?n.flatMap(o=>o??[]):void 0;return{kind:"file-edit",path:si(e),diff:r}}var Mh=/^Found\s+(\d+)\s+match/i,Pv=/^(\/[^:]+?):\s*/,Th=/Line\s+(\d+):/g;function xv(e){let t=e.trim(),n=t.match(Mh),r=n?t.slice(n[0].length).trim():t;if(!r)return[];let o=[];for(let s of r.split(/\n\n+/)){let i=s.trim();if(!i)continue;let a=i.match(Pv);if(!a)continue;let c=a[1],p=i.slice(a[0].length),d=[],g;for(Th.lastIndex=0;(g=Th.exec(p))!==null;)d.push({line:Number(g[1]),contentStart:g.index+g[0].length,headerStart:g.index});for(let m=0;m<d.length;m++){let f=m+1<d.length?d[m+1].headerStart:p.length,h=p.slice(d[m].contentStart,f).trim();o.push({path:c,line:d[m].line,content:h.endsWith(";")?h.slice(0,-1):h})}}return o}function Sv(e){return e.trim().split(`
95
+ `).map(t=>t.trim()).filter(t=>t.startsWith("/")||t.startsWith("./")||t.startsWith("~")).map(t=>({path:t}))}function wv(e){let t=W(e.input?.pattern,e.input?.query)??"";if(e.status==="error"||!e.output)return{kind:"search",pattern:t};let n=Mh.test(e.output.trim())?xv(e.output):Sv(e.output);return{kind:"search",pattern:t,matches:n.length>0?n.slice(0,200):void 0}}function Av(e){let t=W(e.input?.description,e.input?.title,e.input?.prompt)??e.title,n=W(e.input?.subagent_type,e.input?.agent);return{kind:"task",description:t,agent:n}}function oi(e){let t=gt(e)??{};return{content:W(t.content)??"",status:W(t.status)??"pending",priority:W(t.priority)}}function vv(e){let t=e.input?.todos;if(Array.isArray(t))return{kind:"todo",items:t.map(oi)};if(Array.isArray(e.outputParsed))return{kind:"todo",items:e.outputParsed.map(oi)};let n=gt(e.outputParsed);return n&&Array.isArray(n.todos)?{kind:"todo",items:n.todos.map(oi)}:{kind:"todo",items:[]}}function kv(e){return{kind:"question",questions:(Array.isArray(e.input?.questions)?e.input.questions:[]).map(r=>{let o=gt(r)??{},i=(Array.isArray(o.options)?o.options:[]).flatMap(a=>{let c=gt(a),p=c&&W(c.label);return p?[{label:p,description:c?W(c.description):void 0}]:[]});return{question:W(o.question)??"",header:W(o.header),options:i}})}}function Rv(e){let n=e.input&&Object.keys(e.input).length>0?Ih(e.input):void 0,r;return e.outputParsed!==void 0?r=typeof e.outputParsed=="string"?Tn(e.outputParsed):Ih(e.outputParsed):e.outputText!==void 0?r=Tn(e.outputText):r=e.error,{kind:"generic",label:e.title,inputPretty:n,outputPretty:r}}function Cv(e){switch(ae(e.name)){case"web_search":return iv(e);case"bash":return gv(e);case"read":return mv(e);case"write":return fv(e);case"edit":return _v(e);case"grep":case"glob":return wv(e);case"task":return Av(e);case"todowrite":return vv(e);case"question":return kv(e);default:return Rv(e)}}var Iv=new Set(["AbortError","MessageAbortedError"]),Tv=["operation was aborted","aborted by user","interrupted by user","cancelled by user","canceled by user","request was cancelled","request was canceled","aborterror"],Ev=["unreachable","upstream","econnreset","econnrefused","socket hang up","network","fetch failed","timed out","timeout","gateway","502","503","504"];function Oh(e){let t=e.toLowerCase();return Ev.some(n=>t.includes(n))?!1:Tv.some(n=>t.includes(n))}function Mv(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 Zr(e){if(typeof e=="string")return Oh(e);if(!e||typeof e!="object")return!1;let t=e,n=t.name;if(typeof n=="string"&&Iv.has(n))return!0;let r=Mv(t);return typeof r=="string"?Oh(r):!1}var Ov=["user","runtime-disposed","orphan-finalized","wake"],pB=["orphan-finalized","wake"];function dB(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 Ov.includes(n)?n:void 0}var eo="kortix-active-instance",Dv=["/dashboard","/agents","/p","/workspace","/settings","/browser","/desktop","/services","/sessions","/terminal","/files","/scheduled-tasks","/commands","/tools","/configuration","/changelog","/legacy","/credits-explained"];function jv(e){return Dv.some(t=>e===t||e.startsWith(`${t}/`))}function En(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 mB(e){let t=En(e);return!!t&&t.innerPath===""}function fB(e){let t=En(e);return!t||!t.innerPath?e:t.innerPath}function $v(e,t){if(!e)return t;if(t.startsWith("/")||(t=`/${t}`),t.startsWith("/instances/")){let n=En(t);return n?`/instances/${encodeURIComponent(e)}${n.innerPath}`:t}return jv(t)?`/instances/${encodeURIComponent(e)}${t}`:t}function Uv(e){return e?En(e)?.instanceId??null:null}function yB(){return typeof window>"u"?null:Uv(window.location.pathname)||Lv()}function Lv(){if(typeof document>"u")return null;let e=document.cookie.match(new RegExp(`(?:^|; )${eo}=([^;]+)`));return e?decodeURIComponent(e[1]):null}function hB(e){if(typeof document>"u")return;let t=n=>{document.cookie=n};if(typeof window<"u"&&window.location.pathname.startsWith("/projects")){t(`${eo}=; Max-Age=0; Path=/; SameSite=Lax`);return}if(!e){t(`${eo}=; Max-Age=0; Path=/; SameSite=Lax`);return}t(`${eo}=${encodeURIComponent(e)}; Path=/; SameSite=Lax`)}function bB(e,t){return t?$v(t,e):e}function _B(e){let t=En(e);return t?t.innerPath||"/dashboard":e}function Mn(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 Dh(e){let t=Mn(e).trim();if(!t)return null;let n=[t,t.replace(/^Failed to perform action:\s*/i,"").trim()],r=t.indexOf("{");r>=0&&n.push(t.slice(r));for(let o of n)if(o)try{return JSON.parse(o)}catch{}return null}var xB=Dh;function ii(e){let t=Dh(e);if(!t||typeof t!="object")return null;let n=t;return n.name==="ConfigInvalidError"?n:null}var SB=ii;function Fv(e){return ii(e)!==null}var wB=Fv,Nv=[/sandbox not ready/i,/sandbox is not (?:ready|running)/i,/opencode (?:session )?(?:is )?not ready/i,/\bsandbox_not_ready\b/,/\bsandbox_lifecycle_unavailable\b/],AB=["runtime_not_ready","sandbox runtime not ready","opencode not ready"],Kv=/\bruntime_not_ready\b|sandbox runtime not ready|opencode not ready/i;function qv(e){return Kv.test(Mn(e))}function On(e){let t=Mn(e);return t?qv(t)||Nv.some(n=>n.test(t)):!1}var Bv=/server url not ready|sandbox is still loading/i;function vB(e){return Bv.test(Mn(e))||On(e)}var to=class extends Error{constructor(t){let n=t?.trim();super(n&&On(n)?n:n?`sandbox not ready: ${n}`:"sandbox not ready"),this.name="SandboxNotReadyError"}};function Gv(e){let t=ii(e);if(t){let o=(t.data?.path??"OpenCode config").replace(/^\/workspace\//,""),s=t.data?.issues?.[0]?.message,i=t.data?.issues?.[0]?.path?.join("."),a=i?.startsWith("permission")?"Remove the invalid permission frontmatter entry or replace it with valid OpenCode permission config.":"Fix the invalid config entry, then restart this session.";return{title:"OpenCode config is invalid",message:`${o} is preventing OpenCode from loading. ${a}`,detail:s?`${i?`${i}: `:""}${s}`:void 0}}let n=Mn(e);return On(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 kB=Gv;function jh(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`${Be()}/p/${e.external_id}/${qe.KORTIX_MASTER}`}function TB(e,t){return e.external_id?`${Be()}/p/${e.external_id}/${t}`:null}async function jB(){let e=await l.get("/setup/sandbox-providers");if(e.error)throw e.error;return e.data}async function Wv(e){let t=await ot();if(t)return{sandbox:t.sandbox,created:!1};let r=(await _t())[0];if(!r)throw new Error("Create a project before starting a sandbox");let o=await vt(r.project_id,{...e?.provider?{provider:e.provider}:{}}),s=(await nt(r.project_id,o.session_id))?.sandbox??null;return{sandbox:us(r,o,s),created:!0}}async function $B(){return(await ot().catch(()=>null))?.sandbox??null}async function UB(e){return{sandbox:(await Wv(e)).sandbox}}async function LB(e){let t=en(e);return t?(await ot(t).catch(()=>null))?.sandbox??null:null}async function FB(e,t){throw await ot(e)?new Error("Renaming project-session sandboxes is not exposed by the current API"):new Error("Project session sandbox not found")}async function NB(e){let t=en(e);return(await ps().catch(()=>[])).map(r=>r.sandbox).filter(r=>!t||r.sandbox_id===t||r.external_id===t)}async function KB(){return null}async function qB(e){if(!e)throw new Error("No sandbox selected for workload restart");let t=await ot(e);if(!t)throw new Error("Project session sandbox not found");await fr(t.project.project_id,t.session.session_id)}async function BB(e){if(!e)throw new Error("No sandbox selected to stop");let t=await ot(e);if(!t)throw new Error("Project session sandbox not found");await yr(t.project.project_id,t.session.session_id)}async function GB(e){throw new Error("Cancellation is not exposed for project-session sandboxes")}async function WB(e){throw new Error("Reactivation is not exposed for project-session sandboxes")}async function ai(e,t,n){let r=jh(e),o=await E(`${se(r)}${t}`,{signal:AbortSignal.timeout(8e3),headers:{"Content-Type":"application/json"},...n});if(!o.ok){let s=await o.text().catch(()=>"");throw new Error(s||`Request failed (${o.status})`)}return await o.json()}async function QB(e,t){return ai(e,`/kortix/projects/${encodeURIComponent(t)}/members`,{method:"GET"})}async function XB(e,t,n,r="member"){await ai(e,`/kortix/projects/${encodeURIComponent(t)}/members`,{method:"POST",body:JSON.stringify({user_id:n,role:r})})}async function JB(e,t,n){await ai(e,`/kortix/projects/${encodeURIComponent(t)}/members/${encodeURIComponent(n)}`,{method:"DELETE"})}var ci="Use the account invite functions (acceptAccountInvite, declineAccountInvite).";async function tG(e){throw U("getInvite",ci)}async function nG(e){throw U("acceptInvite",ci)}async function rG(e){throw U("declineInvite",ci)}async function sG(e){throw new Error("Backups are not exposed for project-session sandboxes")}async function iG(e,t){throw new Error("Backups are not exposed for project-session sandboxes")}async function aG(e,t){throw new Error("Backups are not exposed for project-session sandboxes")}async function cG(e,t){throw new Error("Backups are not exposed for project-session sandboxes")}async function uG(e){throw new Error("SSH setup is not exposed for project-session sandboxes")}async function pG(e){throw new Error("SSH connection details are not exposed for project-session sandboxes")}var Hv=["pulling","patching","stopping","removing","recreating","restarting","verifying","starting","health_check"];function fG(e){return Hv.includes(e)}async function yG(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 hG(e){let t=e?`?channel=${e}`:"",r=await(await Re(`${Be()}/platform/sandbox/version/latest${t}`,{headers:{Accept:"application/json"}},{},"Version check failed")).json();try{let o=await Vv(e||"stable");r.changelog=o.find(s=>s.version===r.version)??o[0]??null}catch{r.changelog=null}return r}async function Vv(e){let t=e?`?channel=${e}`:"";return(await(await Re(`${Be()}/platform/sandbox/version/changelog${t}`,{headers:{Accept:"application/json"}},{},"Changelog fetch failed")).json()).changelog}async function bG(){return(await Re(`${Be()}/platform/sandbox/version/all`,{headers:{Accept:"application/json"}},{},"All versions fetch failed")).json()}async function _G(e,t){throw new Error("Sandbox image updates are managed by project-session provisioning")}async function PG(e){}async function xG(e){}async function AG(e){return{serverTypes:[],location:e||"hel1"}}async function vG(e){throw new Error("Retired instance provisioning is unavailable. Create a project session with daytona, platinum, or e2b.")}async function kG(e){throw U("deleteInstance")}async function RG(e,t){}async function CG(){throw U("claimComputer")}async function IG(e){return null}function TG(e,t){throw U("getSandboxProvisionStreamUrl")}var no=class extends Error{constructor(n,r,o){super(n);this.status=r;this.body=o;this.name="HostBoundaryError"}status;body};function $h(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 Uh(e){let t=await e.text().catch(()=>"");if(!t)return null;try{return JSON.parse(t)}catch{return t}}function Lh(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 Y(e,t,n){let r=n?.body!==void 0,o=await fetch(`${rt(t.backendUrl)}${e}`,{method:n?.method??"GET",headers:$h(t,r),...r?{body:JSON.stringify(n.body)}:{},...t.signal?{signal:t.signal}:{},...t.cache?{cache:t.cache}:{},...t.next?{next:t.next}:{}}),s=await Uh(o);if(!o.ok)throw new no(Lh(o,s),o.status,s);return s}function zv(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 jG(e,t){return Y(`/marketplace/items${zv(t)}`,e)}function $G(e){return Y("/marketplace/marketplaces",e)}function UG(e,t){return Y(`/marketplace/items/${encodeURIComponent(e)}`,t)}function LG(e,t,n){return Y(`/marketplace/items/${encodeURIComponent(e)}/file?path=${encodeURIComponent(t)}`,n)}function FG(e,t){return Y("/access/check-email",t,{method:"POST",body:{email:e}})}function NG(e,t){return Y("/access/request-access",t,{method:"POST",body:e})}function KG(e){return Y("/auth/logout",e,{method:"POST",body:{}})}function qG(e,t){return Y(`/oauth/authorize/consent/${encodeURIComponent(e)}`,t)}function BG(e,t){return Y("/oauth/authorize/consent",t,{method:"POST",body:{request_id:e.requestId,approved:e.approved}})}function GG(e,t){return Y(`/setup-links/connectors/${encodeURIComponent(e)}`,t)}function WG(e,t){return Y(`/setup-links/connectors/${encodeURIComponent(e)}/start`,t,{method:"POST",body:{}})}function HG(e,t,n={}){return Y(`/setup-links/connectors/${encodeURIComponent(e)}/finalize`,t,{method:"POST",body:n.connectionId?{connection_id:n.connectionId}:{}})}function VG(e,t){return Y(`/setup-links/secret/${encodeURIComponent(e)}`,t)}function zG(e,t,n,r){return Y(`/setup-links/secret/${encodeURIComponent(e)}`,n,{method:"POST",body:{values:t,...r?.only_requester?{only_requester:!0}:{}}})}function YG(e,t){return Y(`/p/public-share/${encodeURIComponent(e)}`,t)}function QG(e,t,n){return Y(`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/start`,n,{method:"POST",body:{}})}function XG(e){return Y("/system/maintenance",e)}function JG(e,t){return Y("/system/maintenance",t,{method:"PUT",body:e})}function ZG(e){return Y("/user-roles",e)}function e1(e,t){return Y("/system/demo-request",t,{method:"POST",body:e})}async function t1(e,t,n){let r=await fetch(`${rt(n.backendUrl)}/accounts/${encodeURIComponent(e)}/audit/export?${kt(t)}`,{headers:$h(n,!1),...n.signal?{signal:n.signal}:{}});if(!r.ok){let o=await Uh(r);throw new no(Lh(r,o),r.status,o)}return{blob:await r.blob(),filename:r.headers.get("content-disposition")?.match(/filename="([^"]+)"/)?.[1]??null,capped:r.headers.get("x-audit-capped")==="true",rowCount:r.headers.get("x-audit-row-count"),complete:r.headers.get("x-audit-complete")!=="false",nextCursor:r.headers.get("x-audit-next-cursor")||null}}async function n1(e,t){throw U("openStressTestStream")}function r1(e,t){throw U("buildPublicTemplateUrl")}async function o1(e,t,n){throw U("getPublicTemplate")}var Yv="kortix:connect-link:";function li(e){let t=2166136261,n=16777619^e.length;for(let r=0;r<e.length;r+=1){let o=e.charCodeAt(r);t=Math.imul(t^o,16777619)>>>0,n=Math.imul(n^o,1540483477)>>>0}return`${Yv}${t.toString(36)}${n.toString(36)}`}function i1(e,{storage:t}={}){let n=new Map,r=new Map,o=i=>{if(t)try{let a=t.getItem(li(i));if(!a)return;let c=JSON.parse(a);if(Date.parse(c.expires_at)<=Date.now()){t.removeItem(li(i));return}return c}catch{return}},s=(i,a)=>{if(t)try{t.setItem(li(i),JSON.stringify(a))}catch{}};return{peek(i){let a=r.get(i);if(a)return a;let c=o(i);return c&&r.set(i,c),c},load(i){let a=n.get(i);if(a)return a;let c=e(i).then(p=>(r.set(i,p),s(i,p),p),p=>{throw n.delete(i),p});return n.set(i,c),c}}}var Fh="Could not start the connect flow.";async function a1(e){let t;try{t=await e.start()}catch(r){return{kind:"error",message:r instanceof Error?r.message:Fh}}if(t.connect_url)return{kind:"popup",url:t.connect_url};if(!t.connected)return{kind:"error",message:Fh};let n=null;try{n=(await e.finalize()).connected_as??null}catch{}return{kind:"connected",alreadyConnected:t.already_connected===!0,connectedAs:n}}var Qv=3e3,Xv=5e3,Jv=5*6e4;function c1(e,t){let n=e===0?Qv:Xv;return t+n>Jv?null:n}function l1(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 d1(){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 g1(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 m1(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 f1(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 y1(){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 b1="1";var Zv="kortix.query-cache";function Kh(e){return!!e&&typeof e.then=="function"}function Nh(e){return Kh(e)?e:Promise.resolve()}function _1(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 P1(e){let{storage:t,userId:n,shouldPersist:r,version:o="1",maxAgeMs:s=6048e5,maxBytes:i=1e6,throttleMs:a=1e3,namespace:c=Zv,now:p=()=>Date.now()}=e,d=`${c}:${n}`,g=null,m=!1,f=null,h=Promise.resolve(),P=()=>{try{return Nh(t.removeItem(d)).catch(()=>{})}catch{return Promise.resolve()}},j=(T,x)=>{if(!x)return 0;let S;try{S=JSON.parse(x)}catch{return P(),0}if(!S||S.v!==o||S.user!==n||!Array.isArray(S.queries)||p()-S.at>s)return P(),0;let I=0;for(let C of S.queries){if(!C||!Array.isArray(C.k)||C.d===void 0||typeof C.t!="number"||p()-C.t>s||!r(C.k))continue;let F=T.getQueryState(C.k);F&&F.data!==void 0&&F.dataUpdatedAt>=C.t||(T.setQueryData(C.k,C.d,{updatedAt:C.t}),T.invalidateQueries?.({queryKey:C.k,exact:!0,refetchType:"none"}),I+=1)}return I},L=T=>T.getQueryCache().getAll().filter(x=>x.state.data!==void 0&&r(x.queryKey)).map(x=>({k:x.queryKey,d:x.state.data,t:x.state.dataUpdatedAt})).sort((x,S)=>S.t-x.t),N=(T,x)=>{let S=[],I=0;for(let C of T){let F=JSON.stringify(C).length+1;I+F>x||(S.push(C),I+=F)}return S},y=async T=>{let x=N(L(T),i);for(;;){let S={v:o,user:n,at:p(),queries:x};try{await Nh(t.setItem(d,JSON.stringify(S)));return}catch{if(x.length===0)return;x=x.slice(0,Math.floor(x.length/2))}}},_=()=>{f!==null&&(clearTimeout(f),f=null)},w=()=>{_();let T=g;return!T||!m||(m=!1,h=h.then(()=>y(T)).catch(()=>{})),h},D=()=>{m=!0,f===null&&(f=setTimeout(()=>{f=null,w()},a))};return{storageKey:d,restore(T){let x;try{x=t.getItem(d)}catch{return 0}return Kh(x)?x.then(S=>j(T,S)).catch(()=>0):j(T,x)},persist(T){g=T,m=!0;let x=T.getQueryCache().subscribe(S=>{S.type!=="updated"&&S.type!=="removed"&&S.type!=="added"||r(S.query.queryKey)&&D()});return()=>{x(),g===T&&(g=null,_())}},flush(){return w()},async clear(){_(),g=null,m=!1,await h,await P()}}}function x1(){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 ek="/kortix/part/";function tk(e){return typeof e=="string"&&e.startsWith(ek)}async function v1(e){if(!tk(e))throw new Error(`not an attachment part reference: ${e}`);let t=Oe();if(!t)throw new Error("runtime url not bound");let n=await E(`${t}${e}`);if(!n.ok)throw new Error(`attachment part fetch failed: ${n.status}`);return n.blob()}function qh(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 nk(e,t){try{let n=new URL(e),r=n.pathname;if(!(/^\/v1\/p\/[^/]+\/\d+(?:\/|$)/.test(r)||/^\/proxy\/\d+(?:\/|$)/.test(r)))return!1;let s=new Set;if(t)try{s.add(new URL(t).origin)}catch{}return typeof window<"u"&&s.add(window.location.origin),s.has(n.origin)}catch{return!1}}function Bh(e,t){return nk(e,t)?(t?qh(t):null)??qh(e):null}function ro(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 Gh(e,t){try{let n=new URL(e);return n.searchParams.set("token",t),n.toString()}catch{return e}}var rk=/^p\d{1,5}-[a-z0-9-]+\.localhost$/;function ok(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function sk(e,t){if(!t.includes("{port}")||!t.includes("{sandbox}"))return!1;let n=t.indexOf("://");if(n<=0)return!1;let r=t.slice(0,n).toLowerCase();if(r!=="https"&&r!=="http")return!1;let o=(t.slice(n+3).split("/")[0]??"").toLowerCase(),s=`${r}://${o}`.split("{port}").map(i=>i.split("{sandbox}").map(ok).join("[a-z0-9-]+")).join("\\d{1,5}");return new RegExp(`^${s}$`).test(e)}function ik(e){try{let t=new URL(e);return t.hostname==="localhost"||t.hostname==="127.0.0.1"?t:null}catch{return null}}function Wh(e){return e.port?e.port:e.protocol==="https:"?"443":"80"}function ak(e,t){let n;try{n=new URL(e)}catch{return!1}return n.protocol!=="https:"&&n.protocol!=="http:"?!1:rk.test(n.hostname)?t.backendUrls.some(r=>{let o=ik(r);return o!==null&&Wh(o)===Wh(n)}):t.templates.some(r=>sk(n.origin,r))}async function Hh(e,t={}){if(!ro(e))return!1;let n=v().backendUrl;n&&await st(n).catch(()=>null);let r=[n,t.serverUrl].filter(o=>typeof o=="string"&&o.length>0);return ak(e,{templates:Gm(),backendUrls:r})}async function ck(e,t={}){let n=Bh(e,t.serverUrl||v().backendUrl||void 0);if(!n)return!1;let r=await Ht();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 $1(e,t={}){if(ro(e)){if(!await Hh(e,t))return e;let n=await Ht();return n?Gh(e,n):e}return await ck(e,t),e}var L1=3e3;function lk(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 F1(e,t){if(!e||t?.signal?.aborted)return"unknown";let n=new AbortController,r=()=>n.abort();t?.signal?.addEventListener("abort",r);let o=setTimeout(r,t?.timeoutMs??3e3);try{let s=await fetch(e,{method:"HEAD",credentials:"include",cache:"no-store",signal:n.signal});return lk(s.status)}catch{return"unknown"}finally{clearTimeout(o),t?.signal?.removeEventListener("abort",r)}}function uk(e){let t=e;for(;t.endsWith("/");)t=t.slice(0,-1);return t}function q1(e,t){throw U("buildPresentationTemplatePdfUrl")}function B1(e,t){throw U("buildPresentationTemplateImageUrl")}function pk(e,t){return`${uk(e)}/presentation/convert-to-${t}`}async function G1(e,t,n,r){let o=pk(t,e),s=r?.pollIntervalMs??2500,i=r?.timeoutMs??4*6e4,a=Date.now(),c=!1;for(;;){let p=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({presentation_path:n,download:!0}),...r?.signal?{signal:r.signal}:{}}),d=p.headers.get("content-type")||"";if(p.ok&&(d.includes("pdf")||d.includes("presentation")||d.includes("octet-stream"))){let h=await p.blob();if(h.size===0)throw new Error("Downloaded file is empty");return h}if(p.status===202){if(c||(c=!0,r?.onGenerating?.()),Date.now()-a>i)throw new Error(`Timed out waiting for the ${e.toUpperCase()} to generate`);await new Promise((h,P)=>{let j=setTimeout(h,s);r?.signal?.addEventListener("abort",()=>{clearTimeout(j),P(r.signal?.reason??new DOMException("Aborted","AbortError"))},{once:!0})});continue}let m=await p.text().catch(()=>""),f=p.statusText;try{let h=JSON.parse(m);f=String(h.error||h.detail||h.message||f)}catch{m&&(f=m)}throw new Error(`Failed to download ${e.toUpperCase()}: ${f} (HTTP ${p.status})`)}}function V1(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 z1(e){return e==="unreachable"}function Y1(e){return!e||e.status===0?"unknown":e.ok&&Bf(e.health)?"live":e.hop==="control_plane"?"waking":e.ok||e.health?.status==="starting"?"connecting":"unreachable"}var dk=1e4,Q1={connection:"unknown",faultSinceMs:null};function X1(e,t,n,r=dk){if(t==="unknown")return e;if(t==="live"||t==="waking")return{connection:t,faultSinceMs:null};let o=e.faultSinceMs??n;return n-o>=r?{connection:t,faultSinceMs:o}:{connection:e.connection==="unknown"?"connecting":e.connection,faultSinceMs:o}}function Vh({optimistic:e,abort:t,inbox:n,server:r,stream:o,activity:s,nowMs:i}){let a=!!e&&i-e.atMs<ui,c=!!t&&i-t.atMs<gi;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<=pi,streamFresh:!!o&&i-o.atMs<=Dn,inboxFresh:!!n&&i-n.atMs<=di,activityFresh:!!s&&i-s.atMs<=Dn}}function Lt(e){if(!e)return null;let t=Date.parse(e);return Number.isNaN(t)?null:t}function mi(e,t,n){if(!t)return!1;let r=Lt(e.started_at);if(r===null||r>=t.atMs)return!1;let o=n?.lastEnded,s=Lt(o?.ended_at);return!(o&&s!==null&&Math.abs(s-t.atMs)<=1e3&&o.turn_token!==e.turn_token)}function gk(e,t,n,r){let{activity:o,server:s}=e,{serverFresh:i,abortFloor:a,activityFresh:c}=t;return c&&(!n||o.atMs>n.atMs)&&o.atMs>=a?{state:"working",source:"stream",turnId:i?s.turns.find(d=>d.state==="active"&&!mi(d,n,s))?.message_id??null:null,since:o.atMs,serverOpenTurnToken:r}:null}function mk(e,t,n,r){let{server:o,stream:s}=e,{serverFresh:i,abortFloor:a}=t,c=i?o.turns.filter(g=>!mi(g,n,o)):[],p=c.find(g=>g.state==="active")??c[0],d=!!s&&!(s.type==="idle"&&s.origin==="local");return p&&o.atMs>=a&&(!d||o.atMs>=s.atMs)?{result:{...p.state==="delivering"?{pendingDelivery:!0}:{},state:"working",source:"server",turnId:p.message_id,since:Lt(p.started_at)??o.atMs,serverOpenTurnToken:r},openTurn:p}:{result:null,openTurn:p}}function fk(e,t,n){let{inbox:r,server:o,stream:s}=e,{inboxFresh:i,abortFloor:a,streamFresh:c,serverFresh:p,receiptLive:d,receiptTurnId:g,abortLive:m}=t;if(i&&r.pending>0&&r.atMs>=a)return{...c&&s.type!=="idle"&&(!p||s.atMs>o.atMs)&&s.atMs>=a?{}:{pendingDelivery:!0},state:"working",source:"server",turnId:d?g:null,since:r.atMs,serverOpenTurnToken:n};let f=r?.drainedAtMs;return i&&r.pending===0&&f!=null&&!m&&!(p&&o.atMs>=f)?{pendingDelivery:!0,state:"working",source:"server",turnId:null,since:f,serverOpenTurnToken:n}:null}function yk(e,t,n,r){let{server:o,stream:s,optimistic:i,nowMs:a}=e,{serverFresh:c,serverFloor:p,streamFresh:d,streamFloor:g,abortFloor:m,receiptLive:f,receiptTurnId:h}=t,P=c&&!n&&o.atMs>=p,j=d&&s.atMs>=g&&(s.type==="idle"||s.atMs>=m);if(P&&(!s||o.atMs>=s.atMs))return{state:"idle",source:"server",turnId:null,since:Lt(o.lastEnded?.ended_at)??o.atMs,serverOpenTurnToken:r};if(j)return{state:s.type==="idle"?"idle":"working",source:"stream",turnId:null,since:s.atMs,serverOpenTurnToken:r};if(f)return{pendingDelivery:!0,state:"working",source:"optimistic",turnId:h,since:i.atMs,serverOpenTurnToken:r};let L=o&&s?o.atMs>=s.atMs?{source:"server",atMs:o.atMs}:{source:"stream",atMs:s.atMs}:o?{source:"server",atMs:o.atMs}:s?{source:"stream",atMs:s.atMs}:{source:"server",atMs:a};return{state:"idle",source:L.source,turnId:null,since:L.atMs,serverOpenTurnToken:r}}function zh(e){let t=Vh(e),{server:n,stream:r}=e,o=r&&r.type==="idle"&&r.origin!=="local"?r:null,s=n?.turns[0]?.turn_token??null,i=gk(e,t,o,s);if(i)return i;let{result:a,openTurn:c}=mk(e,t,o,s);return a??fk(e,t,s)??yk(e,t,c,s)}var ui=6e4,pi=45e3,Dn=45e3,di=1e4,cW=3e3,gi=15e3;function lW(e,t){return t?t.serverAtMs!=null&&e.serverAtMs!=null?e.serverAtMs>=t.serverAtMs:e.atMs>=t.atMs:!0}function uW(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 dW(e){return zh(e)}function gW(e){let{optimistic:t,abort:n,inbox:r,server:o,stream:s,activity:i,nowMs:a}=e,c=[null,t?t.atMs+ui:null,n?n.atMs+gi:null,r?r.atMs+di:null,o?o.atMs+pi:null,s?s.atMs+Dn:null,i?i.atMs+Dn:null],p=null;for(let d of c)d===null||d<=a||(p===null||d<p)&&(p=d);return p}function hk(e,t){if(!e||!t)return null;let n=e.recent_failures?.find(s=>s.message_id===t),r=e.last_ended,o=n?.error??(r?.message_id===t&&r.end_reason==="failed"?r.error:void 0);return!o?.message||Zr({name:o.name??void 0,message:o.message})?null:o}var bk="SandboxMemoryGuard";function hW(e,t,n){if(!e||!t||n.hasError&&!n.isAbort)return null;let r=hk(e,t);if(r?.message){if(r.name!==bk)return{kind:"cause",name:r.name,message:r.message};let a=r.message.match(/(\d{1,3})%/)?.[1],c=r.message.split(":")[0]?.trim()||null;return{kind:"sandbox-memory",usedPct:a?Number(a):null,detail:c}}let o=e.recent_failures?.find(a=>a.message_id===t);if(!o)return null;let s=o.ended_at?Date.parse(o.ended_at):Number.NaN;return Number.isFinite(s)&&typeof e.atMs=="number"&&e.atMs-s<2500?null:{kind:"unexplained"}}var _W=6e4;function PW(e){return e.serverCompactingAtMs!==null?!0:e.optimisticAtMs===null?!1:e.nowMs-e.optimisticAtMs<6e4}function xW(e){if(e.serverCompactingAtMs!==null||e.optimisticAtMs===null)return null;let t=e.optimisticAtMs+6e4;return t>e.nowMs?t:null}var _k=9e4;function SW(e){return e.serverCompactingAtMs===null?null:e.serverCompactingAtMs+_k}var AW=75e3,vW=2,kW=2e4;function Yh(){return{status:"idle",dispatch:"none",fingerprint:null,lastProgressAtMs:null,lastDispatchAtMs:null,attempts:[],msSinceProgress:0,settled:!1}}function RW(e){return e.filter(t=>t!=null).join("|")}function Pk(e,t){return e.length===0?"retry-start":e.filter(r=>r.step==="restart").length<t?"restart":null}function CW(e,t,n={}){let r=n.noProgressMs??75e3,o=n.maxRestarts??2,s=n.cooldownMs??2e4;if(t.runtimeReachable)return{...Yh(),settled:!0};if(!t.waking)return{...e,dispatch:"none",fingerprint:null,lastProgressAtMs:null,msSinceProgress:0};if(e.settled)return{...Yh(),settled:!0};let i=e.lastProgressAtMs,a=i===null,c=t.progress!==e.fingerprint,p=i===null||c?t.nowMs:i,d=Math.max(0,t.nowMs-p),g={...e,dispatch:"none",fingerprint:t.progress,lastProgressAtMs:p,msSinceProgress:d,status:e.attempts.length>0?"escalating":"waking"};if(e.status==="exhausted")return{...g,status:"exhausted"};let m=!a&&!c&&d>=r;if(!t.serverGaveUp&&!m||e.lastDispatchAtMs!==null&&t.nowMs-e.lastDispatchAtMs<s)return g;let f=Pk(e.attempts,o);return f?{...g,status:"escalating",dispatch:f,attempts:[...e.attempts,{step:f,atMs:t.nowMs}],lastDispatchAtMs:t.nowMs,lastProgressAtMs:t.nowMs,msSinceProgress:0}:{...g,status:"exhausted"}}var xk={"retry-start":"retrying",restart:"restarting"};function IW(e){if(e.status!=="escalating")return null;let t=e.attempts[e.attempts.length-1];return t?`Still waking \u2014 ${xk[t.step]} the runtime (attempt ${e.attempts.length+1})`:null}function Sk(e){return e===1?"once":e===2?"twice":`${e} times`}function TW(e){if(e.status!=="exhausted")return null;let t=e.attempts.filter(o=>o.step==="restart").length,n=e.attempts.some(o=>o.step==="retry-start");if(!n&&t===0)return null;let r=[];return n&&r.push("re-issuing the wake"),t>0&&r.push(`restarting the session ${Sk(t)}`),`Tried: ${r.join(", then ")}.`}var MW={"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 wk(e){return!!(e.metadata??{}).legacy_migration}function OW(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 wk(e)?"legacy":e.status==="completed"?"done":"stopped";case"failed":return"failed";default:return"stopped"}}function DW(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 jW={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 $W(e){return e===null?"Waiting to retry":e>0?`Retrying in ${e}s`:"Retrying now"}function fi(e){return e.runtime_sessions??e.opencode_sessions??[]}function Ak(e){let t=fi(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 LW(e){let t=Ak(e);return t?fi(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 FW(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=>fi(r).some(o=>o.id===t))??null)}var vk=new Set;function kk(e){for(let t of[...vk])try{t(e)}catch{}}function Rk(e){return e==="TIMEOUT"||e==="request_deadline"}function Ck(e){let t=Xh(e)?e.code:void 0;return typeof t=="string"?t:void 0}var Xh=e=>typeof e=="object"&&e!==null;function Qh(e){let t=e?.metadata;return!!Xh(t)&&t.warm===!0}var Ik=5,Tk=2e3,Ek=e=>new Promise(t=>setTimeout(t,e));async function Mk(e,{attempts:t=Ik,delayMs:n=Tk,sleep:r=Ek}={}){for(let o=0;o<t;o++){o>0&&await r(n);try{if(await e())return!0}catch{}}return!1}function sH(e,t){let n=new Map,r=new Set,o=new Set,s=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 h=await e.ensure(c,p);if(g!==i)return;o.has(h.sessionId)?f=h.sessionId:n.set(c,h)}catch{}finally{g===i&&r.delete(c)}f&&d>0&&await a(c,f,d-1)})();return s.add(m),m.finally(()=>s.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),o.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 Rk(Ck(g))?Mk(async()=>!Qh(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),o.add(c),p;return null},revalidate:async c=>{let p=n.get(c);if(!p)return!1;try{if(Qh(await e.read(c,p.sessionId)))return!1}catch{return!1}return n.get(c)?.sessionId!==p.sessionId?!1:(n.delete(c),o.add(p.sessionId),!0)},held:c=>n.get(c)??null,reset:()=>{i+=1,n.clear(),r.clear(),o.clear()},settled:async()=>{for(;s.size>0;)await Promise.all([...s])}}}var Ok=12e4,oo=class extends Error{constructor(t){super(`Session history read did not settle within ${t}ms`),this.name="SessionSyncReadTimeoutError"}},Dk=1e3,jk=15e3,Jh=100,$k=50,Uk=10;function Zh(e){let t=e.fetch??globalThis.fetch,n=e.baseUrl.replace(/\/$/,"");return async({limit:r,before:o},s)=>{let i=new URLSearchParams({limit:String(r)});o&&i.set("before",o);let a=await e.getToken?.(),c=await t(`${n}/session/${encodeURIComponent(e.sessionId)}/message?${i}`,{headers:a?{Authorization:`Bearer ${a}`}:void 0,...s?{signal:s}:{}});if(!c.ok)throw c.status===503?new to(`session ${c.status}`):new b(`Session synchronization failed: ${c.status}`,{status:c.status});return{messages:await c.json(),nextCursor:c.headers.get("x-next-cursor")||void 0}}}function Lk(e){return Nk(Zh(e))}function Fk(e){return new yi({...e,loadPage:Zh(e)})}async function Nk(e){let t=[],n=new Set,r;do{let i=await e({limit:Jh,...r?{before:r}:{}});if(t.push(i.messages),r=i.nextCursor,r&&n.has(r))throw new Error(`Session history cursor repeated: ${r}`);r&&n.add(r)}while(r);let o=[],s=new Set;for(let i=t.length-1;i>=0;i--)for(let a of t[i])s.has(a.info.id)||(s.add(a.info.id),o.push(a));return o}var Kk={now:Date.now,setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e),setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e)},yi=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??Kk,this.livenessIntervalMs=t.livenessIntervalMs??1e4,this.verifyIntervalMs=t.verifyIntervalMs??3e4,this.readTimeoutMs=t.readTimeoutMs??Ok,this.lastActivityAt=this.scheduler.now(),this.lastTailReadAt=this.scheduler.now()}getSnapshot=()=>this.snapshot;subscribe=t=>(this.listeners.add(t),()=>this.listeners.delete(t));start(){return this.snapshot.freshness==="fresh"?Promise.resolve():this.reconcile("initial")}reconcile(t="manual"){return this.destroyed?Promise.resolve():this.tailRequest?this.tailRequest:(this.update({freshness:this.snapshot.freshness==="idle"||this.snapshot.freshness==="loading"?"loading":"stale"}),this.tailRequest=this.loadTail(t).finally(()=>{this.tailRequest=void 0}),this.tailRequest)}loadOlder=()=>{if(this.destroyed||!this.nextCursor)return Promise.resolve();if(this.olderRequest)return this.olderRequest;let t=this.nextCursor;return this.update({isLoadingOlder:!0}),this.olderRequest=this.loadCompleteOlderTurn(t).then(n=>{this.destroyed||(this.rememberUserMessages(n.messages),this.options.hydrate(n.messages),this.olderHistoryStarted=!0,this.setCursor(n.nextCursor))}).finally(()=>{this.olderRequest=void 0,this.update({isLoadingOlder:!1})}),this.olderRequest};noteActivity(){this.lastActivityAt=this.scheduler.now(),this.snapshot.freshness!=="fresh"&&this.update({freshness:"fresh"})}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 oo;if(!r&&Zr(n))return;if(r||this.update({freshness:On(n)?"loading":"error"}),n instanceof b&&(n.status===404||n.status===410)){this.tailUnavailable=!0,this.cancelTimer(this.tailRetryTimer),this.tailRetryTimer=void 0;return}this.scheduleTailRetry(t)}}scheduleTailRetry(t){if(this.destroyed||this.tailRetryTimer!==void 0)return;let n=Math.min(Dk*2**this.retryAttempt,jk);this.retryAttempt+=1,this.tailRetryTimer=this.startTimer(()=>{this.tailRetryTimer=void 0,!this.destroyed&&this.reconcile(t)},n)}async loadPage(t,n,r){let o=this.scheduler.now();try{let s=await this.boundedRead(i=>this.options.loadPage({limit:t==="tail"?$k:Jh,...r?{before:r}:{}},i));return this.options.onTelemetry?.({operation:t,reason:n,durationMs:this.scheduler.now()-o,messageCount:s.messages.length,succeeded:!0}),s}catch(s){throw this.options.onTelemetry?.({operation:t,reason:n,durationMs:this.scheduler.now()-o,messageCount:0,succeeded:!1}),s}}boundedRead(t){let n=this.abortController.signal,r=new AbortController,o=()=>r.abort(n.reason);n.aborted?r.abort(n.reason):n.addEventListener("abort",o,{once:!0});let s,i=new Promise((c,p)=>{s=this.startTimer(()=>{let d=new oo(this.readTimeoutMs);p(d),r.abort(d)},this.readTimeoutMs)}),a;try{a=t(r.signal)}catch(c){a=Promise.reject(c)}return Promise.race([a,i]).finally(()=>{this.cancelTimer(s),n.removeEventListener("abort",o)})}async loadCompleteOlderTurn(t){let n=await this.loadPage("older","manual",t);return this.loadCompleteTurn(n,"older","manual",t,r=>{this.rememberUserMessages(r.messages),this.options.hydrate(r.messages),this.setCursor(r.nextCursor)})}async loadCompleteTurn(t,n,r,o,s){let i=[...t.messages],a=new Set(this.knownUserMessageIds),c=new Set(o?[o]:[]),p=t.nextCursor,d=0;for(let g of t.messages)g.info.role==="user"&&a.add(g.info.id);for(;p&&d<Uk&&i.some(g=>g.info.role==="assistant"&&!!g.info.parentID&&!a.has(g.info.parentID));){if(c.has(p))throw new Error(`Session history cursor repeated: ${p}`);c.add(p);let g;try{g=await this.loadPage(n,r,p)}catch(m){throw s?.({messages:[...i],nextCursor:p}),m}if(this.destroyed)return{messages:i,nextCursor:p};d+=1,i.unshift(...g.messages);for(let m of g.messages)m.info.role==="user"&&a.add(m.info.id);p=g.nextCursor,s?.({messages:[...i],nextCursor:p})}return{messages:i,nextCursor:p}}rememberUserMessages(t){for(let n of t)n.info.role==="user"&&this.knownUserMessageIds.add(n.info.id)}async checkLiveness(){if(this.destroyed||this.tailUnavailable||this.streamReliable)return;let t=this.scheduler.now(),n=t-this.lastActivityAt>this.livenessIntervalMs,r=t-this.lastTailReadAt>=this.verifyIntervalMs;!(this.livenessBusy&&n)&&!r||(await this.raceDeadline(this.reconcile("poll"),this.livenessIntervalMs),this.lastActivityAt=this.scheduler.now())}raceDeadline(t,n){return new Promise(r=>{let o,s=!1,i=()=>{s||(s=!0,this.cancelTimer(o),r())};o=this.startTimer(i,n),t.then(i,i)})}setCursor(t){this.nextCursor=t,this.update({hasOlder:!!t})}stopLivenessTimer(){this.livenessTimer!==void 0&&(this.scheduler.clearInterval(this.livenessTimer),this.livenessTimer=void 0)}startTimer(t,n){return this.scheduler.setTimeout?this.scheduler.setTimeout(t,n):setTimeout(t,n)}cancelTimer(t){t!==void 0&&(this.scheduler.clearTimeout?this.scheduler.clearTimeout(t):clearTimeout(t))}update(t){let n={...this.snapshot,...t};if(!(n.freshness===this.snapshot.freshness&&n.hasOlder===this.snapshot.hasOlder&&n.isLoadingOlder===this.snapshot.isLoadingOlder)){this.snapshot=n;for(let r of this.listeners)r()}}};function qk(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 Bk(e){return e.savedEmptyRoot!==null&&e.savedEmptyRoot===e.rootSessionId&&e.turnRead&&!e.hasEndedTurn&&!e.hasOpenOrQueuedTurn}function gH(e){throw U("buildTunnelEventStreamUrl")}function mH(e){let{url:t,token:n,method:r="GET",body:o,onEvent:s,onOpen:i,onError:a,onClose:c,signal:p}=e,d=new Map,g=null,m=!1,f="";function h(y,_){s?.(y,_);let w=d.get(y);if(w)for(let D of w)try{D(_)}catch{}}async function P(){if(m)return;let y=new AbortController;g=y,p&&(p.aborted?y.abort():p.addEventListener("abort",()=>y.abort(),{once:!0}));let _=y.signal;try{let w={Accept:"text/event-stream",Authorization:`Bearer ${n}`};r!=="GET"&&o!==void 0&&(w["Content-Type"]="application/json"),f&&(w["Last-Event-ID"]=f);let D=await fetch(t,{method:r,headers:w,body:r!=="GET"&&o!==void 0?JSON.stringify(o):void 0,signal:_,credentials:"include"});if(!D.ok)throw new Error(`SSE connection failed: ${D.status} ${D.statusText}`);if(!D.body)throw new Error("SSE response has no body");i?.();let T=D.body.getReader(),x=new TextDecoder,S="",I="message",C=[],F=K=>{if(K===""){C.length>0&&h(I,C.join(`
96
+ `)),I="message",C=[];return}if(K.startsWith(":"))return;let q=K.indexOf(":"),ge=q===-1?K:K.slice(0,q),me=q===-1?"":K.slice(q+1);me.startsWith(" ")&&(me=me.slice(1)),ge==="event"?I=me.trim()||"message":ge==="data"?C.push(me):ge==="id"&&!me.includes("\0")&&(f=me)},M=K=>{let q="";!K&&S.endsWith("\r")&&(q="\r",S=S.slice(0,-1));let ge=S.split(/\r\n|\n|\r/);S=(ge.pop()??"")+q;for(let me of ge)F(me)};for(;!m;){let{done:K,value:q}=await T.read();if(K)break;S+=x.decode(q,{stream:!0}),M(!1)}m||(S+=x.decode(),M(!0),c?.())}catch(w){if(m||w instanceof DOMException&&w.name==="AbortError")return;a?.(w instanceof Error?w:new Error(String(w)))}}function j(){m=!0,g?.abort(),g=null,d.clear()}function L(y,_){let w=d.get(y)??new Set;w.add(_),d.set(y,w)}function N(y,_){d.get(y)?.delete(_)}return{connect:P,close:j,addEventListener:L,removeEventListener:N}}function fH(e,t){throw U("createTunnelEventStream")}var eb="/_kortix/viewer",so=6e4,Ft=new Map;function Gk(){Ft.clear(),jn.clear()}async function Wk(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 tb(e={}){let t=e.path??eb,n=e.fetch??((s,i)=>fetch(s,i)),r=Ft.get(t);if(r&&!r.inflight&&r.expiresAt>Date.now())return r.session;if(r?.inflight)return r.inflight;let o=Wk(t,n).then(s=>{let i=s?.expires_at?Date.parse(s.expires_at):Number.NaN,a=Number.isFinite(i)?i-so:Date.now()+so;return Ft.set(t,{session:s,expiresAt:a}),s});return Ft.set(t,{session:r?.session??null,expiresAt:0,inflight:o}),o}function Hk(e={}){let t=e.path??eb;return Object.assign(async()=>(await tb(e))?.access_token??null,{invalidate:n=>{let r=Ft.get(t);r&&!r.inflight&&r.session?.access_token===n&&Ft.delete(t)}})}var jn=new Map;async function Vk(e,t){try{let n=await t(e,{credentials:"same-origin",headers:{accept:"application/json"}});if(!n.ok){if(n.status===403){let s=await n.json().catch(()=>null);s?.error==="app_not_linked"&&console.warn(`[kortix] ${String(s.error_description)}`)}return null}let r=await n.json().catch(()=>null);if(!r||typeof r.token!="string")return null;let o=typeof r.expires_at=="string"?Date.parse(r.expires_at):Number.NaN;return jn.set(e,{token:r.token,refreshAt:Number.isFinite(o)?o-so:Date.now()+so}),r.token}catch{return null}}function nb(e={}){let t=e.path??"/_kortix/token",n=e.audience===void 0?t:`${t}?audience=${encodeURIComponent(e.audience)}`,r=e.fetch??((o,s)=>fetch(o,s));return async(o={})=>{let s=jn.get(n);if(s instanceof Promise)return s;if(s&&!o.forceRefreshToken&&s.refreshAt>Date.now())return s.token;let i=Vk(n,r).then(a=>(a===null&&jn.delete(n),a));return jn.set(n,i),i}}function zk(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:`${se(n)}/_kortix/apps/${encodeURIComponent(e)}`,token:nb({audience:e,fetch:t.fetch})}}var mt=class extends Error{code;constructor(t,n){super(n),this.name="KortixMemberError",this.code=t}},de=e=>typeof e=="string"&&e.length>0?e:null;function rb(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 bi(e){if(!e||typeof e!="object")return null;let t=e,n=de(t.sub)??de(t.subject)??de(t.user_id)??de(t.userId);return n?{userId:n,email:de(t.email),name:de(t.name),picture:de(t.picture)??de(t.pictureUrl),groups:rb(t.groups),groupIds:rb(t.group_ids??t.groupIds),role:de(t.role),accountId:de(t.account_id)??de(t.accountId),projectId:de(t.project_id)??de(t.projectId)}:null}function Yk(e,t={}){let n=bi(e);if(!n)throw new mt("unauthenticated","Sign in with Kortix to continue.");let{groups:r,roles:o}=t;if(r&&!r.some(s=>n.groups.includes(s)||n.groupIds.includes(s)))throw new mt("forbidden",`Only members of ${r.join(" or ")||"no group"} may do this.`);if(o&&!o.some(s=>n.role===s))throw new mt("forbidden",`Only ${o.join(" or ")||"no role"} members may do this.`);return n}var Qk=60,hi=new Map;function sb(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 ob(e){return JSON.parse(new TextDecoder().decode(sb(e)))}async function Xk(e,t){if(typeof e!="string")return e;if(e.startsWith("data:")){let n=e.indexOf(","),r=e.slice(5,n),o=e.slice(n+1),s=r.endsWith(";base64")?new TextDecoder().decode(Uint8Array.from(atob(o),i=>i.charCodeAt(0))):decodeURIComponent(o);return JSON.parse(s)}if(/^https?:\/\//.test(e)){let n=hi.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(()=>hi.delete(e)),hi.set(e,n)),n}return JSON.parse(e)}async function Jk(e,t={}){let n=y=>{throw new mt("unauthenticated",`Kortix sign-in token refused: ${y}.`)},r=t.jwks??Ke("KORTIX_AUTH_JWKS"),o=t.issuer??Ke("KORTIX_AUTH_ISSUER"),s=t.audience??Ke("KORTIX_AUTH_AUDIENCE");if(!r)return n("no key set configured (KORTIX_AUTH_JWKS)");if(s!==!1&&!s)return n("no audience configured (KORTIX_AUTH_AUDIENCE, or `audience: false` to accept any App)");let i=typeof e=="string"?e.split("."):[];if(i.length!==3)return n("malformed");let[a,c,p]=i,d,g;try{d=ob(a),g=ob(c)}catch{return n("malformed")}if(d.alg!=="ES256")return n("unsupported algorithm");let m;try{m=await Xk(r,t.fetch??((y,_)=>fetch(y,_)))}catch{return n("key set unavailable")}let f=(m.keys??[]).filter(y=>y.kty==="EC"&&(d.kid===void 0||y.kid===d.kid));if(f.length===0)return n("unknown key");let h=new TextEncoder().encode(`${a}.${c}`),P;try{P=sb(p)}catch{return n("malformed")}let j=!1;for(let y of f)try{let{kid:_,alg:w,use:D,key_ops:T,...x}=y,S=await crypto.subtle.importKey("jwk",x,{name:"ECDSA",namedCurve:"P-256"},!1,["verify"]);if(await crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},S,P,h)){j=!0;break}}catch{}if(!j)return n("bad signature");let L=Math.floor(Date.now()/1e3);if(typeof g.exp!="number"||g.exp+Qk<L)return n("expired");if(o&&g.iss!==o)return n("wrong issuer");if(s){let y=g.aud;if(!(y===s||Array.isArray(y)&&y.includes(s)))return n("wrong audience")}let N=bi(g);return N||n("no subject")}function ib(e){let t=e.agents.map(Zk),n=e.default_agent??e.open_code_default_agent;return n?t.sort((r,o)=>r.name===n?-1:o.name===n?1:0):t}function Zk(e){return{name:e.name,description:e.description??void 0,mode:e.mode??void 0,source:e.source,hidden:e.enabled===!1}}function ab(e,t){if(!Array.isArray(e))return[];let n=t?.includeSubagents===!0;return e.filter(r=>ls(n?{...r,mode:null}:r))}function eR(e){let t=e.boundAgent?.trim()||null;if(!Array.isArray(e.agents)){let s=e.selectedAgent?.trim();return s?{selected:s,disabled:!1,reason:"loading"}:{selected:t,disabled:!1,reason:"loading"}}let n=ab(e.agents);if(n.length===0)return t?{selected:t,disabled:!1,reason:"bound"}:{selected:null,disabled:!0,reason:"no_access"};let r=e.selectedAgent?.trim();if(r&&n.some(s=>s.name===r))return{selected:r,disabled:!1,reason:"selected"};if(t)return{selected:t,disabled:!1,reason:"bound"};let o=e.defaultAgent?.trim();return o&&n.some(s=>s.name===o)?{selected:o,disabled:!1,reason:"default"}:{selected:n[0].name,disabled:!1,reason:"first_accessible"}}var tR=ib;function cb(e){return e.providerID==="kortix"||e.providerID==="opencode"?e.modelID:`${e.providerID}/${e.modelID}`}function _i(e){return{providerID:"kortix",modelID:e}}function nR(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 _i(n)}var Pi=[{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:"lowrouter",env:["LOWROUTER_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:"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:"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:"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:"aixy",env:["AIXY_API_KEY"]},{id:"alibaba-cn",env:["DASHSCOPE_API_KEY"]}];function xi(e){if(!e.released)return null;let t=new Date(e.released).getTime();return Number.isNaN(t)?null:t}function oR(e){if(e.provider)return e.provider;let t=e.id.indexOf("/");return t===-1?"kortix":e.id.slice(0,t)}function lb(e,t){let n=new Map;for(let r of e){let o=t(r),s=n.get(o);s?s.push(r):n.set(o,[r])}return n}function le(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 ub(e){return e.reduce((t,n)=>{let r=xi(n)??0,o=xi(t)??0;return r!==o?r>o?n:t:le(n.id)>le(t.id)?n:t})}function Si(e,t){let n=(t?.now??new Date).getTime(),r=(t?.windowMonths??6)*2630016e3,o=new Set;for(let[,s]of lb(e,oR)){let a=[...lb(s,p=>p.family||p.id).values()].map(ub),c=a.filter(p=>{let d=xi(p);return d!==null&&Math.abs(n-d)<r});for(let p of c.length>0?c:[ub(a)])o.add(p.id)}return o}function io(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=>le(r.id)>0)?n.filter(r=>le(r.id)>0):n}function $n(e){let t;for(let n of io(e)){if(!t){t=n;continue}let r=(n.released??"").localeCompare(t.released??"");(r>0||r===0&&le(n.id)>le(t.id))&&(t=n)}return t}var sR={"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 pb(e){return`${e.toUpperCase().replace(/[^A-Z0-9]+/g,"_")}_API_KEY`}var iR=(()=>{let e=new Map;for(let{id:n,env:r}of Pi)r.length===1&&e.set(r[0],[...e.get(r[0])??[],n]);let t=new Map;for(let[n,r]of e){if(r.length<2)continue;let o=[...r].sort((s,i)=>s.length-i.length||s.localeCompare(i));t.set(n,r.find(s=>pb(s)===n)??o[0])}return t})();function db(e){let t=sR[e.id];if(t)return t;let n=e.env??[],r=n.length===1?iR.get(n[0]):void 0;return r&&r!==e.id?{methods:[{envVars:[pb(e.id)]}]}:{methods:n.length>0?[{envVars:n}]:[]}}function Ai(e,t){return e.methods.some(n=>n.envVars.length>0&&n.envVars.every(t))}var aR=["low","medium","high"];function gb(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:[...aR]}:void 0,o=e.temperature===!0,s=e.limit?.output,i=typeof s=="number"&&s>0?{ceiling:s}:void 0;return{reasoningEffort:r,temperature:o,topP:o,maxOutputTokens:i}}var mb=Pi;var wi={allow_fallbacks:!0,zdr:!0,data_collection:"deny"};var ao=[{id:"deepseek-v4.1-flash",name:"DeepSeek V4.1 Flash",upstreamModelId:"deepseek/deepseek-v4.1-flash",transport:"openrouter",morphModelId:"morph-dsv41flash",morphPricing:{inputPerMillion:.15,cachedInputPerMillion:.003,outputPerMillion:.6},pricingRef:"openrouter/deepseek/deepseek-v4.1-flash",pricing:{inputPerMillion:.2,cachedInputPerMillion:.03,outputPerMillion:.65},openrouterEndpointPricing:{"coreweave/fp8":{inputPerMillion:.2,cachedInputPerMillion:.03,outputPerMillion:.65}},tier:"balanced",vision:!0,limit:{context:1e6,output:65536},reasoningOptions:[{type:"effort",values:["none","low","high","max"]}],openrouterProvider:{only:["coreweave/fp8"],...wi,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"],...wi,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"],...wi,max_price:{prompt:3.3,completion:16.5}}}],CH=new Map(ao.map(e=>[e.id,e]));var fb=ao.map(e=>e.id),yb=(ao.find(e=>e.tier==="flagship")??ao[0]).id,hb="deepseek-v4.1-flash";var _b=mb.map(e=>({id:e.id,authRequirement:db(e)})),Un=new Set(["kortix"]),vi=new Set(["kortix"]);function Nt(e){let t=Array.isArray(e.all)?e.all:[],n=Array.isArray(e.connected)?e.connected:[];if(t.length>0||n.length>0)return{...e,all:t,connected:n};let r=e.providers,o=Array.isArray(r)?r:[];return o.length===0?{...e,all:[],connected:[]}:{...e,all:o,connected:o.map(s=>s.id)}}function cR(e){if(!e)return!1;let t=Nt(e),n=Array.isArray(t.all)?t.all:[],r=Array.isArray(t.connected)?t.connected:[];return r.length===0?!1:n.some(o=>r.includes(o.id)&&o.models&&Object.keys(o.models).length>0)}function lR(e){let t=Nt(e),n=Array.isArray(t.all)?t.all:[],r=Array.isArray(t.connected)?t.connected:[];return{...t,all:n.filter(o=>!vi.has(o.id)),connected:r.filter(o=>!vi.has(o))}}function uR(e,t,n){let r=Nt(e),o=Array.isArray(r.all)?r.all:[],s=new Set(o.map(a=>a.id)),i=new Set(Array.isArray(r.connected)?r.connected:[]);for(let a of n)s.has(a.id)&&Ai(a.authRequirement,c=>t.has(c))&&i.add(a.id);return s.has("codex")&&(t.has("CODEX_AUTH_JSON")||t.has("OPENCODE_AUTH_JSON"))&&i.add("codex"),{...r,connected:[...i]}}var pR=new Map(["anthropic","openai","google","x-ai","xai","deepseek","mistral","groq","perplexity","openrouter"].map((e,t)=>[e,t]));function dR(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 ki="opencode";function gR(e){return e.cost?.input===0&&e.cost?.output===0}function bb(e){return e===ki?Number.MAX_SAFE_INTEGER:pR.get(e)??Number.MAX_SAFE_INTEGER-1}function mR(e,t){let n=yR(t),r={},o=(e.providers??[]).map(s=>{let i=(s.models??[]).filter(a=>a.status!=="deprecated");return s.id===ki&&!n.has(ki)?{...s,models:i.filter(gR),keyless:!0}:{...s,models:i,keyless:!1}}).filter(s=>(s.keyless||n.has(s.id))&&!vi.has(s.id)&&(s.models?.length??0)>0).sort((s,i)=>bb(s.id)-bb(i.id)).map(s=>{let i=[...s.models].sort((c,p)=>(p.released??"").localeCompare(c.released??"")||le(p.id)-le(c.id)),a=$n(i)?.id??i[0]?.id;return a&&(r[s.id]=a),{id:s.id,name:s.name,source:s.keyless?"api":"env",models:Object.fromEntries(i.map(c=>{let p=dR(c);return[c.id,{id:c.id,name:c.name,...c.released?{release_date:c.released}:{},...c.family?{family:c.family}:{},...c.reasoning!==void 0?{reasoning:c.reasoning}:{},...c.reasoning_options?{reasoning_options:c.reasoning_options}:{},...c.tool_call!==void 0?{tool_call:c.tool_call}:{},...c.attachment!==void 0?{attachment:c.attachment}:{},...c.modalities?{modalities:c.modalities}:{},...c.limit?{limit:c.limit}:{},...c.cost?{cost:c.cost}:{},...c.description?{description:c.description}:{},...c.open_weights!==void 0?{open_weights:c.open_weights}:{},...c.last_updated?{last_updated:c.last_updated}:{},...p.length>0?{variants:Object.fromEntries(p.map(d=>[d,{}]))}:{}}]}))}});return{all:o,connected:o.map(s=>s.id),default:r}}function fR(e,t){if(!e)return t;if(!t)return e;let n=Nt(e),r=Nt(t),o=new Map;for(let d of Array.isArray(r.all)?r.all:[])o.set(d.id,d);let s=[],i=new Set;for(let d of Array.isArray(n.all)?n.all:[])s.push(o.get(d.id)??d),i.add(d.id);for(let d of Array.isArray(r.all)?r.all:[])i.has(d.id)||(s.push(d),i.add(d.id));let a=[],c=new Set;for(let d of[...Array.isArray(n.connected)?n.connected:[],...Array.isArray(r.connected)?r.connected:[]])c.has(d)||(a.push(d),c.add(d));let p={...r.default??{}};for(let[d,g]of Object.entries(n.default??{})){let m=o.get(d);(!m||m.models&&g in m.models)&&(p[d]=g)}return{...r,all:s,connected:a,default:p}}function yR(e){let t=new Set;for(let n of _b)Ai(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 hR(e){let t=Object.fromEntries(Object.entries(e.models??{}).filter(([r])=>r!=="auto"&&r!=="kortix/auto").map(([r,o])=>{if(o.variants&&Object.keys(o.variants).length>0)return[r,o];let s=gb({id:r,name:o.name,reasoning:o.reasoning,reasoning_options:o.reasoning_options}).reasoningEffort?.values;return s?.length?[r,{...o,variants:Object.fromEntries(s.map(i=>[i,{}]))}]:[r,o]})),n=Object.keys(t)[0];return{default:n?{kortix:n}:{},connected:["kortix"],all:[{id:"kortix",name:"Kortix",source:"gateway",models:t}]}}function bR(e,t){return lR(uR(Nt(e),t,_b))}function _R(e){if(e.gatewayEnabled)return e.modelPicker?hR(e.modelPicker):void 0;let t=e.secretNames??new Set,n=e.runtimeProviders?bR(e.runtimeProviders,t):void 0;return fR(e.llmCatalogProviders?mR(e.llmCatalogProviders,t):void 0,cR(n)?n:void 0)}function PR(e){return"capabilities"in e&&e.capabilities!=null}function Ri(e,t){let n=e.find(r=>r.providerID===t.providerID&&r.modelID===t.modelID);return!!n&&n.enabled!==!1}function xR(e,t){if(!e)return[];let n=t?.providerMode??"gateway",r=Array.isArray(e.all)?e.all:[],o=Array.isArray(e.connected)?e.connected:[],s=[];for(let i of r)if(o.includes(i.id)&&!(n==="gateway"?!Un.has(i.id):Un.has(i.id)))for(let[a,c]of Object.entries(i.models)){if(a==="auto"||a==="kortix/auto")continue;let p;if(PR(c)){let d=c.capabilities;p={reasoning:d.reasoning??!1,vision:d.input?d.input.image??!1:void 0,toolcall:d.toolcall??!1}}else{let d=c.modalities?.input;p={reasoning:c.reasoning??!1,vision:d?d.includes("image"):c.attachment,toolcall:c.tool_call??!1}}s.push({id:cb({providerID:i.id,modelID:a}),providerID:i.id,providerName:c.provider_name??i.name,modelID:a,modelName:(c.name||a).replace("(latest)","").trim(),variants:c.variants,capabilities:p,contextWindow:c.limit?.context,releaseDate:c.release_date,family:c.family,cost:c.cost?{input:c.cost.input??0,output:c.cost.output??0}:void 0,providerSource:i.source,provider:c.provider,reasoningOptions:c.reasoning_options,description:c.description,openWeights:c.open_weights,lastUpdated:c.last_updated,enabled:c.enabled,free:c.free===!0})}return s}function Pb(e){return new Map(e.map(t=>[`${t.providerID}:${t.modelID}`,t]))}var SR=new Set([yb]),wR="kortix",xb="codex",AR=new Set(fb);function vR(e,t){if(t)return t;let n=e.indexOf("/");return n===-1?e:e.slice(0,n)}function Kt(e){return SR.has(e.modelID)}function kR(e){return Si(e.map(t=>({id:`${t.providerID}:${t.modelID}`,released:t.releaseDate,family:t.family,provider:t.provider??t.providerID})))}function RR(e){let{connectedProviderIds:t}=e,n=e.freeTier??!1,r=kR(e.catalogModels),o=Pb(e.catalogModels),s=new Map;for(let i of e.pins??[])s.set(`${i.providerID}:${i.modelID}`,i.visibility);return i=>{let a=`${i.providerID}:${i.modelID}`,c=s.get(a);if(c==="hide")return!1;if(i.providerID===wR){let d=vR(i.modelID,i.provider),g=d===xb?t?.has(xb)??!1:t?.has(d)??!1;if(AR.has(i.modelID))return!n||i.modelID===hb;if(!g)return!1;if(c==="show"||r.has(a))return!0;let m=o.get(a);if(!m?.releaseDate)return Kt(i);try{let f=new Date(m.releaseDate);if(Number.isNaN(f.getTime()))return Kt(i)}catch{return Kt(i)}return!1}if(c==="show"||r.has(a))return!0;let p=o.get(a);if(!p?.releaseDate)return Kt(i);try{let d=new Date(p.releaseDate);if(Number.isNaN(d.getTime()))return Kt(i)}catch{return Kt(i)}return!1}}function CR(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 Sb(e,t){if(!e||Un.has(e.providerID)||le(e.modelID)>0)return e;let n=t.filter(i=>i.providerID===e.providerID&&i.enabled!==!1);if(!n.some(i=>le(i.modelID)>0))return e;let r=i=>le(i)===1&&i.slice(i.indexOf(".")+1)===e.modelID,s=(n.find(i=>i.modelID===`global.${e.modelID}`)??n.find(i=>r(i.modelID)))?.modelID??$n(n.map(i=>({id:i.modelID,released:i.releaseDate})))?.id;return!s||s===e.modelID?e:{...e,modelID:s}}function IR(e,t){let n=(t?e?.agentDefaults?.[t]:void 0)??e?.projectDefault??e?.accountDefault??e?.platformDefault;return n?_i(n):void 0}function TR(e){let{models:t,providers:n}=e,r=c=>Ri(t,c),o=c=>c.find(p=>!!p&&r(p)),s=(()=>{if(e.configModel){let c=e.configModel.split("/");if(c.length>=2){let[p,...d]=c,g=d.join("/");if(r({providerID:p,modelID:g}))return{providerID:p,modelID:g}}}for(let c of e.recent??[])if(r(c))return c;if(n){let c=n.default||{},p=Array.isArray(n.all)?n.all:[],d=Array.isArray(n.connected)?n.connected:[],g=p.filter(m=>d.includes(m.id));for(let m of g){let f=c[m.id];if(f){let h={providerID:m.id,modelID:f};if(r(h))return h}for(let h of io(Object.keys(m.models).map(P=>({id:P})))){let P={providerID:m.id,modelID:h.id};if(r(P))return P}}}})(),i=o(e.picks??[]),a=i??o([e.serverDefault,e.globalDefault,e.agentModel,s]);return{model:Sb(a,t),explicit:i,fallback:s}}export{Ov as ABORT_REASONS,pB as ABORT_REASONS_NOT_YET_EMITTED,Bi as ACCOUNTS_LIST_UNAVAILABLE_CODE,eo as ACTIVE_INSTANCE_COOKIE,qi as ANALYTICS_UNAVAILABLE_CODE,ek as ATTACHMENT_PART_REF_PREFIX,b as ApiError,te as AuthError,Xe as BillingError,dk as CONNECTION_FAULT_GRACE_MS,Qv as CONNECTOR_POLL_FIRST_DELAY_MS,Xv as CONNECTOR_POLL_INTERVAL_MS,Jv as CONNECTOR_POLL_WINDOW_MS,lw as CONTEXT_TOOLS,xh as COST_MARKUP,jo as ConnectorApprovalPendingError,rr as ConnectorCallError,$o as ConnectorPageLimitError,uw as DEFAULT_CONTEXT_TOOL_TRIGGER_LABELS,Ij as DEFAULT_NOTIFICATION_PREFERENCES,_y as DEFAULT_TRANSCRIPT_OPTIONS,Hv as DESTRUCTIVE_PHASES,mo as FEATURE_DISABLED_CODE,PC as FEATURE_FLAG_KEYS,Fi as FEATURE_NOT_SUPPORTED_CODE,dt as FILE_VERBS,fn as FileExistsError,tn as HeadlessAuthError,no as HostBoundaryError,Db as IMPERSONATION_HEADER,Cj as INBOX_NOTIFICATION_KINDS,di as INBOX_OBSERVATION_MAX_MS,Q1 as INITIAL_SETTLED_CONNECTION,Dv as INSTANCE_SCOPED_ROUTES,T_ as KNOWN_TOOL_KINDS,o0 as KORTIX_TRANSCRIPT_SCHEMA,mt as KortixMemberError,f_ as MAX_PROMPT_ATTACHMENTS_BYTES,Lo as MAX_PROMPT_ATTACHMENT_BYTES,Ml as MAX_PROMPT_ATTACHMENT_FILES,Gq as MEMORY_VERBS,Ni as MODEL_NOT_SERVABLE_CODE,AP as NO_GROUP_ACTIVITY_TOOLS,gi as OPTIMISTIC_ABORT_MAX_MS,_W as OPTIMISTIC_COMPACTION_MAX_MS,ui as OPTIMISTIC_RECEIPT_MAX_MS,b1 as PERSISTED_QUERY_CACHE_VERSION,nA as PLUMBING_TOOLS,L1 as PREVIEW_PROBE_TIMEOUT_MS,RT as PROJECT_SESSION_NAME_LOOKUP_LIMIT,kT as PROJECT_SESSION_PAGE_DEFAULT_LIMIT,Q_ as PROJECT_SESSION_PAGE_MAX_LIMIT,Ki as PROVISION_IN_FLIGHT_CODE,Yo as PublicSessionShareError,AB as RUNTIME_NOT_READY_MARKERS,a0 as RUNTIME_PERMISSION_CAPABILITIES,i0 as RUNTIME_PERMISSION_REPLIES,ht as RequestTooLargeError,un as RuntimeNotReadyError,Us as SANDBOX_FS_ROOTS,qe as SANDBOX_PORTS,_k as SERVER_COMPACTION_REVALIDATE_MS,pi as SERVER_OBSERVATION_MAX_MS,MW as SESSION_LIST_STATUS,I_ as SESSION_LOG_MINOR,pr as SESSION_LOG_SCHEMA,jW as SESSION_NOTICE,vP as STANDALONE_TOOLS,Dn as STREAM_OBSERVATION_MAX_MS,to as SandboxNotReadyError,Ct as SessionNotReadyError,Bo as SessionStartError,cW as TURN_END_LEDGER_LAG_MS,XP as TURN_ERROR_CODES,kW as WAKE_ESCALATION_COOLDOWN_MS,vW as WAKE_MAX_RESTARTS,AW as WAKE_NO_PROGRESS_MS,Is as WIRE_ID_BACKDATE_MS,at as WIRE_ID_CLOCK_TOLERANCE,Ge as WIRE_ID_TIME_MASK,an as WIRE_ID_TIME_SCALE,HP as WIRE_MESSAGE_ID,MR as __getConfigResolver,ER as __setConfigResolver,dB as abortErrorReason,ga as acceptAccountInvite,nG as acceptInvite,eg as actReviewItem,Nc as activateConnection,Bc as addComputerToProject,Rd as addGroupMembers,Lg as addMarketplaceSource,CW as advanceWakeEscalation,Yw as allDescendantIds,Gh as appendPreviewToken,Ha as approveProjectAccessRequest,j0 as approveTask,tr as archiveProject,B0 as assignTicket,nc as attachGroupToProject,ws as authMfa,Ps as authUser,E as authenticatedFetch,sr as authenticatedRequest,$1 as authorizePreviewUrl,l as backendApi,DE as bindSlackIdentity,jE as bindTeamsIdentity,mc as brokerProjectSecretRequest,x1 as browserKeyValueStorage,$v as buildInstancePath,B1 as buildPresentationTemplateImageUrl,q1 as buildPresentationTemplatePdfUrl,Bh as buildPreviewAuthEndpoint,r1 as buildPublicTemplateUrl,pk as buildRuntimePresentationConversionUrl,Al as buildSandboxTemplate,aA as buildScrapeFailureResults,wL as buildStaticFileHealthPreviewUrl,SL as buildStaticFileLocalUrl,xL as buildStaticFilePreviewUrl,gS as buildStaticFileServicePath,gH as buildTunnelEventStreamUrl,CL as buildWebProxyUrl,tg as bulkActReviewItems,PM as bulkDeletePolicies,xM as bulkImportPolicies,aK as burstSummary,cK as burstSummaryLabel,xt as callConnector,GO as cancelAccountDeletion,la as cancelAccountInvite,GB as cancelSandbox,xG as cancelSandboxUpdate,Mp as cancelScheduledChange,Ip as cancelSubscription,FG as checkAccessEmail,GN as childMapByParent,CG as claimComputer,RS as claimNext,xE as claimPerSeatBilling,vu as claimWarmProjectSession,Vy as classifyPart,lk as classifyPreviewProbeStatus,ex as classifyPtyClose,Ww as classifyTurn,XN as cleanErrorMessage,fK as cleanResultSnippet,jq as cleanWorkerOutput,Wi as clearImpersonationSession,Gk as clearKortixAppViewerCache,pp as clearModelDefault,cT as clearSessionFresh,Ql as closeChangeRequest,hU as closeMilestone,NN as collectTurnParts,W0 as commentTicket,Zl as commitSessionChanges,xW as compactionExpiryAtMs,uK as compactionTurnInfo,LN as compareMessagesForDisplay,wF as compareSemver,CS as completeInFlight,Hp as completeSlackInstall,Vp as completeTeamsInstall,ab as composerSelectableAgents,_h as computeStatusFromPart,$p as configureAutoTopup,uo as configureKortix,Rp as confirmCheckoutSession,ed as connectEmail,Bp as connectSlack,Y1 as connectionFromHealth,z1 as connectionIsFaulted,pI as connectionSharedWithEveryone,l_ as connectorConnect,u_ as connectorFinalize,l1 as connectorHeadline,IK as contextLabelForTool,eN as contextToolSummary,tN as contextToolTrigger,cD as convertPresentationToGoogleSlides,G1 as convertRuntimePresentation,jr as copyFile,Lp as costExportUrl,uW as countLiveInboxPrompts,mD as countReviewItemsBySegment,Ji as createAccount,Rg as createAccountAuditWebhook,wc as createAccountSecretResource,yg as createAccountToken,Kg as createApp,Yg as createAppAccessSession,Xg as createAppDeployment,Gg as createAppToken,gm as createAppVolume,hm as createAppVolumeSnapshot,TK as createArtifactKind,Vd as createAssignment,_O as createAuditWebhook,iG as createBackup,kp as createCheckoutSession,rl as createConnector,i1 as createConnectorLinkInfoCache,Dr as createFile,bd as createGatewayKey,wd as createGroup,Fk as createHttpSessionSyncController,vG as createInstance,wS as createKortix,hf as createKortixPty,vs as createKortixSession,GD as createMarketplaceInstallSession,fU as createMilestone,RR as createModelVisibility,qd as createOAuthClient,PE as createPerSeatCheckout,P1 as createPersistedQueryCache,hM as createPolicy,Cp as createPortalSession,Aa as createProject,tU as createProjectAgent,xg as createProjectCliToken,va as createProjectRepo,ic as createProjectResourceGrant,vt as createProjectSession,Ea as createProjectSkill,zu as createProjectTrigger,ay as createPromptAttachmentController,Dd as createRole,mH as createSSEStream,UB as createSandbox,sg as createSandboxShare,xl as createSandboxTemplate,yT as createSavedCopyStore,EM as createScimToken,pO as createServiceAccountApi,mr as createSessionPrompt,Su as createSessionPublicShare,vS as createSessionQueue,ug as createSessionReminder,QM as createSsoGroupMapping,M0 as createTask,N0 as createTicket,fH as createTunnelEventStream,sH as createWarmSessionPool,du as currentSavedCopyStore,ma as declineAccountInvite,rG as declineInvite,WO as deleteAccountImmediately,kc as deleteAccountSecretResource,Bg as deleteApp,rm as deleteAppDeployment,xO as deleteAuditWebhook,cG as deleteBackup,sl as deleteConnector,pl as deleteConnectorCredential,AU as deleteCredential,xj as deleteDriveFile,ff as deleteEnv,Dt as deleteFile,yd as deleteGatewayBudget,qa as deleteGitHubInstallation,vd as deleteGroup,kG as deleteInstance,uU as deleteKortixProject,_U as deleteMilestone,Wd as deleteOAuthClient,Pc as deletePersonalProjectSecret,_M as deletePolicy,rU as deleteProjectAgent,yc as deleteProjectProviderOAuth,ac as deleteProjectResourceGrant,bc as deleteProjectSecret,Uu as deleteProjectSession,Qu as deleteProjectTrigger,Qt as deletePromptAttachment,Ud as deleteRole,wl as deleteSandboxTemplate,gO as deleteServiceAccountApi,Eu as deleteSessionPrompt,Xo as deleteSessionReminder,gg as deleteSessionReminders,XM as deleteSsoGroupMapping,zM as deleteSsoProvider,$0 as deleteTask,H0 as deleteTicket,da as describeAccountInvite,To as describeConnectorTool,lm as destroyAppMachine,fm as destroyAppVolume,oc as detachGroupFromProject,lS as detectLocalhostUrls,LW as directSubsessions,dO as disableServiceAccountApi,td as disconnectEmail,y1 as disconnectGitHubApp,Yp as disconnectSlack,fI as discoverConnectionOAuth2,yI as discoverConnectionOAuth2Resource,ol as discoverConnectorAuth,KB as discoverLocalSandbox,mj as dismissDriveConflict,t1 as downloadAccountAudit,yj as downloadDriveFile,LU as dropClientForUrl,KU as dropPublicClientForUrl,MS as editQueued,Mu as editSessionPrompt,kS as enqueue,Z0 as ensurePmSession,ck as ensurePreviewSessionCookie,dI as ensureProjectConnectorConnection,Wv as ensureSandbox,Au as ensureWarmProjectSession,JP as env,hs as exchangeCode,pm as execInApp,vg as exportAccountAudit,xe as extractGatewayErrorDetails,En as extractInstanceRoute,nv as extractSkillBaseDir,sB as extractSkillContent,ZA as extractSkillFiles,Uq as extractWorkerPreview,IS as failInFlight,nq as fallbackBusyRowAfterTurnId,ti as familyForTool,Oi as featureDisabledKey,Um as featureFlags,hE as fetchAccountStateWithToken,fC as fetchAccountsWithToken,v1 as fetchAttachmentPart,TE as fetchCostExportCsv,tb as fetchKortixAppViewer,Tl as fetchProjectArchive,zI as fetchProjectFileRaw,CC as fetchProjectsForAccountWithToken,jm as fetchSessionAttachment,$x as fileDownloadRequest,Kq as filePhase,Nq as fileVerb,zx as files,ts as finalizeAppArtifact,HG as finalizeConnectorSetupLink,IT as findActiveTranscriptShare,Mr as findFiles,KN as findLastTextPart,zj as findSessionAttachments,Or as findText,Ju as fireProjectTrigger,Pl as fixSandboxWithAgent,xR as flattenModels,LK as flattenThought,_m as forkAppVolume,ji as formatBillingErrorForUI,Pq as formatCost,Ph as formatDuration,JN as formatJsonFailureOutput,KK as formatMessageDay,qK as formatMessageExact,kB as formatOpenCodeRuntimeError,mK as formatRawOutput,Gv as formatRuntimeError,xq as formatTokens,FS as formatTranscript,iq as freshSendHint,AS as generateSessionId,Zi as getAccount,ta as getAccountBranding,qO as getAccountDeletionStatus,_p as getAccountState,Pp as getAccountStateMinimal,Lv as getActiveInstanceIdFromCookie,rD as getAdminBootModes,ZO as getAdminProviderAnalytics,QO as getAdminProviderDistribution,tD as getAdminProviderFallback,HO as getAdminRole,bw as getAgentCardLabel,lE as getAgentConfig,oU as getAgentPersona,bG as getAllVersions,BN as getAnsweredQuestionParts,Zo as getApp,Hg as getAppAccess,Wg as getAppAuthEnv,Zg as getAppDeployment,em as getAppDeploymentLogs,ND as getApprovalLink,Ht as getAuthToken,oI as getAuthTokenWithRetry,jp as getAutoTopupSettings,_E as getAutoTopupSetupStatus,wp as getBillingCreditBreakdown,vp as getBillingTierConfigurations,Sp as getBillingTransactionsSummary,Ap as getBillingUsageHistory,Wl as getChangeRequest,Hl as getChangeRequestDiff,Vl as getChangeRequestMergePreview,yN as getChildSessionError,By as getChildSessionId,hN as getChildSessionToolParts,ct as getClient,je as getClientForUrl,ll as getConnectStatus,mI as getConnectionOAuth2Application,xI as getConnectionOAuth2Status,SI as getConnectionPolicies,Vt as getConnectorCatalog,el as getConnectorConfig,Jc as getConnectorPolicies,GG as getConnectorSetupLink,IE as getCostSummary,Uv as getCurrentInstanceIdFromPathname,yB as getCurrentInstanceIdFromWindow,Uf as getCurrentProject,yp as getDefaultAccountState,PN as getDiagnostics,hw as getDirectory,Do as getDiscoverConnector,CI as getDiscoverIntegration,Pm as getDriveFileUrl,Jp as getEmailInstallation,Zp as getEmailMode,IO as getEnterpriseDemo,Er as getFileStatus,Ky as getFileWithDir,yw as getFilename,lj as getFolderAccess,Vv as getFullChangelog,pd as getGatewayBreakdown,md as getGatewayBudgets,gd as getGatewayErrors,hd as getGatewayKeys,cd as getGatewayLog,ld as getGatewayOverview,rd as getGatewayRoutingPolicy,ud as getGatewaySeries,dd as getGatewaySessions,d1 as getGitHubAppStatus,Da as getGitHubInstallation,aD as getGoogleAuthUrl,Sd as getGroup,mN as getHiddenToolParts,Ub as getImpersonationSession,tG as getInvite,AG as getJustavpsServerTypes,aU as getKortixProject,cU as getKortixProjectBySession,Pf as getKortixPtyWebSocketUrl,hG as getLatestSandboxVersion,XG as getMaintenanceConfig,Ba as getManagedGitBackend,AC as getManagedGitStatus,jg as getMarketplaceCatalogItem,$g as getMarketplaceCatalogItemFile,$M as getMfaRequired,gU as getMilestone,yy as getMobileClientPolicy,lp as getModelDefaults,vm as getNotificationPreferences,Kd as getOAuthClient,qG as getOAuthConsentRequest,SB as getOpenCodeConfigInvalidError,pN as getPartText,sO as getPatPolicy,xN as getPermissionForTool,Qn as getProject,sU as getProjectActivity,Nl as getProjectCommit,Kl as getProjectCommitDiff,Xn as getProjectDetail,cj as getProjectDrive,ql as getProjectFileHistory,wa as getProjectGitToken,Jn as getProjectLlmCatalog,SC as getProjectLlmCatalogProviders,Sr as getProjectModelAccess,Zn as getProjectModelPicker,or as getProjectSandboxHealth,vC as getProjectSandboxProviderTransition,gr as getProjectSession,Lu as getProjectSessionConfigState,Ku as getProjectSessionScope,Op as getProrationPreview,jB as getProviders,AL as getProxyBaseUrl,NU as getPublicClientForUrl,UG as getPublicMarketplaceItem,LG as getPublicMarketplaceItemFile,SD as getPublicSessionShare,wD as getPublicSessionShareMessages,YG as getPublicShareByToken,o1 as getPublicTemplate,SN as getQuestionForTool,HE as getReferralCode,YE as getReferralStats,Sq as getRetryInfo,wq as getRetryMessage,Jd as getReviewItem,Md as getRolePermissions,Od as getRoleUsage,ii as getRuntimeConfigInvalidError,pG as getSSHConnection,$B as getSandbox,LB as getSandboxById,TB as getSandboxPortUrl,IG as getSandboxProvisionStatus,TG as getSandboxProvisionStreamUrl,yG as getSandboxUpdateStatus,jh as getSandboxUrl,tt as getSandboxUrlForExternalId,VG as getSecretSetupLink,Ls as getServerHealth,RU as getServiceLogs,ku as getSessionAudit,_q as getSessionCost,Pr as getSessionCostRecord,SP as getSessionDrives,Gf as getSessionHealth,Wu as getSessionMessageAuthors,Hu as getSessionModelUsage,TT as getSessionOpenBundle,FM as getSessionOversight,hu as getSessionParticipants,tO as getSessionPolicy,Pu as getSessionPreviewCandidates,Tc as getSessionProviderSecretPool,Ru as getSessionTranscript,Cu as getSessionTranscriptSync,Iu as getSessionTurn,bu as getSessionWatch,Mq as getShellModePart,Qp as getSlackChannelFile,qp as getSlackInstallation,zp as getSlackManifest,Gp as getSlackMode,GM as getSsoProvider,mS as getStaticFileHealthPath,Ro as getSupabaseAccessToken,o_ as getSupabaseAccessTokenWithRetry,I0 as getTask,E0 as getTaskStatus,VD as getTemplate,L0 as getTicket,bN as getToolInfo,Vs as getToolPrimaryArg,NS as getTranscriptFilename,bq as getTurnCost,mq as getTurnError,yq as getTurnErrorDetails,fq as getTurnErrorRawText,hq as getTurnStatus,Up as getUsageRollup,ZG as getUserRolesWithToken,Bl as getVersionDiff,Rm as getWebPushPublicKey,dq as getWorkingState,Rc as grantAccountSecretResource,XB as grantSandboxProjectAccess,pE as grantSecretToAgent,FN as groupMessagesIntoTurns,QK as groupShowSegments,ph as groupSteps,Aq as hasDiffs,PL as hasLocalhostUrls,dS as hasPreviewTarget,VN as hasRetryingAssistantTurn,lx as heartbeatGapEvent,ju as holdSessionPrompts,rg as humanizeReviewActionPath,Br as humanizeSearchQuery,Wy as humanizeToolName,Hi as impersonationHeaders,HM as importSsoProviderFromMetadata,lW as inboxObservationSupersedes,Yh as initialWakeEscalationState,Ve as inputPath,zD as installTemplate,Ou as interruptSessionPrompt,Co as invalidateTokenCache,aa as inviteAccountMember,Xa as inviteProjectMember,xa as inviteRepoCollaborator,Zr as isAbortError,Kb as isAdminBypassEnabled,iN as isAgentPart,iS as isAppRouteUrl,dN as isAttachment,tk as isAttachmentPartRef,Bt as isAuthFailure,Di as isBillingError,aN as isCompactionPart,po as isConfigured,ZF as isContextTool,fG as isDestructivePhase,Bk as isEmptyConversation,os as isEmptyShowPart,QN as isErrorOutput,EL as isExternalUrl,Mi as isFeatureDisabledError,qy as isFilePart,jb as isImpersonationSessionLive,mB as isInstanceDetailPath,jv as isInstanceScopedAppPath,RL as isInternalLocalhostUrl,Mm as isInvisibleActivityPart,BC as isInviteSent,pq as isLastUserMessage,wk as isLegacyMigratedSession,xC as isManagedGithubProject,Em as isNoGroupActivityTool,Ri as isOfferedModel,wB as isOpenCodeConfigInvalidError,N_ as isPaintableSavedCopy,lN as isPatchPart,_1 as isPersistableQueryKey,kL as isPreviewUrl,fS as isProxiableLocalhostUrl,Lj as isQuestionTool,Le as isReasoningPart,Qw as isRetryableTurnError,Fv as isRuntimeConfigInvalidError,qv as isRuntimeNotReadyResponse,Bf as isRuntimeReady,vB as isRuntimeStartingError,On as isSandboxNotReadyError,ls as isSelectableAgent,Lf as isServerReachable,Vj as isSessionAttachmentRef,tu as isSessionFresh,WT as isSessionStartError,Uj as isShellActivityTool,XA as isShellMode,$q as isShortOutput,Dj as isShowContentUnavailable,Ar as isShowPayloadEmpty,cN as isSnapshotPart,Om as isStandaloneActivityTool,uN as isStepPart,ro as isSubdomainPreviewUrl,Ue as isTextPart,ne as isToolPart,fN as isToolPartHidden,s0 as isTurnErrorCode,If as isUnderSandboxRoot,TL as isWebProxyUrl,zP as isWireIdAheadOf,Hk as kortixAppViewerToken,zk as kortixBinding,ox as kortixPty,nb as kortixToken,ha as leaveAccount,Na as linkGitHubInstallation,Ma as linkRepository,wg as listAccountAudit,kg as listAccountAuditWebhooks,ca as listAccountInvites,ia as listAccountMembers,pM as listAccountResourceGrants,Sc as listAccountSecretResources,rO as listAccountSessions,fg as listAccountTokens,Xi as listAccounts,vM as listActions,XO as listAdminSandboxes,Td as listAgentIdentities,jc as listAllConnections,Vg as listAppAgents,Jg as listAppDeployments,sm as listAppMachines,ym as listAppVolumeSnapshots,dm as listAppVolumes,Ng as listApps,Hd as listAssignments,SO as listAuditEvents,bO as listAuditWebhooks,sG as listBackups,xp as listBillingTransactions,Gl as listChangeRequests,LE as listChannelBindings,V0 as listColumns,kI as listConnectSections,vI as listConnectToolkits,Dc as listConnections,Eo as listConnectorAccounts,Io as listConnectorTools,Vc as listConnectors,CE as listCostByProject,xU as listCredentialEvents,PU as listCredentials,Oo as listDiscoverConnectors,RI as listDiscoverIntegrations,cl as listDiscoverSections,gj as listDriveConflicts,fj as listDriveFiles,PP as listDriveFolder,Sj as listDriveVersions,gf as listEnv,Dg as listFeaturedMarketplaces,Y0 as listFields,hn as listFiles,dj as listFolderPrincipals,ad as listGatewayLogs,ja as listGitHubInstallations,Ua as listGitHubRepositories,La as listGitHubRepositoryBranches,kd as listGroupMembers,oM as listGroupProjectGrants,xd as listGroups,lU as listKortixProjectSessions,iU as listKortixProjects,yf as listKortixPty,$a as listLinkableGitHubInstallations,Ga as listManagedGitRepositories,Mg as listMarketplaceCatalogItems,Ug as listMarketplaceSources,Og as listMarketplaces,sM as listMemberGroups,iM as listMemberProjectAccess,mU as listMilestoneEvents,dU as listMilestones,pa as listMyAccountInvites,wm as listNotifications,Nd as listOAuthClients,bg as listOAuthGrants,cc as listPendingApprovals,Ja as listPendingProjectInvites,Yd as listPermissions,il as listPipedreamApps,al as listPipedreamSections,yM as listPolicies,za as listProjectAccess,Wa as listProjectAccessRequests,Ed as listProjectAgentIdentities,eU as listProjectAgents,Ag as listProjectAudit,Ll as listProjectBranches,Pg as listProjectCliTokens,Fl as listProjectCommits,Rl as listProjectDirectory,kl as listProjectFiles,tc as listProjectGroupGrants,fl as listProjectPolicies,fc as listProjectProviderOAuth,mg as listProjectReminders,sc as listProjectResourceGrants,hl as listProjectSandboxTemplates,vl as listProjectSandboxes,pc as listProjectSecrets,At as listProjectSessions,fu as listProjectSessionsPage,bl as listProjectSnapshots,ep as listProjectTriggerEventApps,Zu as listProjectTriggerEventTypes,Vu as listProjectTriggers,_t as listProjects,Pa as listProjectsForAccount,jG as listPublicMarketplaceItems,$G as listPublicMarketplaces,QE as listReferrals,Xd as listReviewItems,Id as listRoles,QB as listSandboxProjectMembers,og as listSandboxShares,NB as listSandboxes,TM as listScimTokens,uO as listServiceAccountsApi,kU as listServiceTemplates,vU as listServices,AI as listSessionConnectRequests,Fp as listSessionCosts,Aj as listSessionDrives,Tu as listSessionPrompts,Ec as listSessionProviderSecretPools,xu as listSessionPublicShares,lg as listSessionReminders,lc as listSessionsNeedingInput,TD as listSignedInDevices,YM as listSsoGroupMappings,T0 as listTaskEvents,C0 as listTasks,X0 as listTemplates,F0 as listTicketEvents,U0 as listTickets,Lk as loadHttpSessionHistory,st as loadPreviewUrlTemplate,eh as looksLikeError,SK as looksLikeHtml,gK as looksLikeJsonPayload,_j as makeDriveFolder,yD as mapApiReviewItem,RG as markInstanceError,Am as markNotificationsRead,ur as markSessionFresh,cf as maxWireIdClock,Wq as memoryRelPath,UK as mergeBurstSteps,Yl as mergeChangeRequest,NK as messageCreatedAt,NA as messageTime,eD as migrateAdminSandboxProvider,Ts as mintWireMessageId,uf as mintWireMessageIdAbove,xn as mkdir,CR as modelInDefaultView,nR as modelRefToKey,Pj as moveDriveFile,lh as narrateFailedStep,ch as narrateStep,Qr as narrationToolName,ux as narrowChatEvent,YP as newestWireIdClock,c1 as nextConnectorPollDelay,pe as normalizeActivityToolName,_B as normalizeAppPathname,ML as normalizeExternalInput,X as normalizeName,Gy as normalizeToolName,kk as notifyHostSignal,zl as openChangeRequest,Ds as openEventStream,n1 as openStressTestStream,ml as paginateConnector,qn as parseBillingError,yK as parseEmbeddedFailure,Zj as parseFlagOverride,tA as parseJsonFailure,Fr as parseLocalhostUrl,Hq as parseMemoryView,xB as parseOpenCodeErrorPayload,Xq as parsePresentationOutput,qf as parseProxyHop,Zq as parseQuestionAnswersFromOutput,nB as parseReadOutput,Dh as parseRuntimeErrorPayload,iA as parseScrapeInputUrls,cA as parseScrapeOutput,Zf as parseSubdomainUrl,Lq as parseTaskRows,IL as parseWebProxyUrl,oh as parseWebSearchOutput,th as partOutcome,pU as patchKortixProject,Yq as patchVerb,_R as pickerProviderList,nl as pipedreamConnect,Wc as pipedreamConnectConnection,dl as pipedreamFinalize,Hc as pipedreamFinalizeConnection,v as platformConfig,PI as pollConnectionOAuth2DeviceAuthorization,vo as pollProjectProviderOAuth,id as previewGatewayRoute,UM as previewMfaRequired,$E as previewSlackIdentity,UE as previewTeamsIdentity,Ld as probeEffectivePermission,Fd as probeEffectivePermissions,F1 as probePreviewPort,El as projectArchiveRequest,PW as projectCompacting,tR as projectConfigAgentsToOpenCodeAgents,ib as projectConfigAgentsToRuntimeAgents,V1 as projectSessionConnection,FW as projectSessionForRuntimeId,GT as projectSessionStartSeed,dW as projectWorking,ka as provisionProject,wC as provisionProjectStream,IC as provisionProjectWithToken,Xf as proxyLocalhostUrl,vL as proxyUrlToInternal,Dp as purchaseCredits,gI as putConnectionOAuth2Application,Ay as rawErrorText,WB as reactivateSandbox,Tp as reactivateSubscription,_n as readBlob,hj as readDriveFile,bn as readFile,bi as readKortixMember,Il as readProjectFile,UA as reasoningIsRunning,_l as rebuildProjectSnapshot,$c as reconcileConnection,Uc as reconcileMemberConnection,IU as reconcileServices,KG as recordPlatformLogout,Zs as recoverLinkResults,VE as refreshReferralCode,nn as refreshSession,es as registerAppArtifact,hI as registerConnectionOAuth2Client,xm as registerDeviceToken,TU as registerService,Cm as registerWebPushSubscription,Va as rejectProjectAccessRequest,_N as relativizePath,Fu as reloadProjectSessionConfig,Nu as reloadProjectSessionConfigStream,Ig as removeAccountAuditWebhook,oa as removeAccountBrandingAsset,fa as removeAccountMember,Cd as removeGroupMember,_f as removeKortixPty,Fg as removeMarketplaceSource,ES as removeQueued,qc as renameConnection,Ur as renameFile,FB as renameSandbox,Xl as reopenChangeRequest,bU as reopenMilestone,OS as reorderQueued,z0 as replaceColumns,Q0 as replaceFields,Oa as replaceProjectRepository,J0 as replaceTemplates,BO as requestAccountDeletion,Jl as requestChangesOnChangeRequest,qC as requestProjectAccess,Eg as requestProjectConnector,Tg as requestProjectSecret,bE as requestTopUp,Yk as requireKortixMember,ua as resendAccountInvite,ec as resendPendingProjectInvite,sa as resetAccountBranding,FU as resetClient,sd as resetGatewayRoutingPolicy,bs as resetPassword,qU as resetPublicClient,PG as resetSandboxUpdateStatus,uc as resolveApproval,eR as resolveComposerAgent,TR as resolveComposerModel,a1 as resolveConnectorStart,IR as resolveModelDefault,CT as resolvePublicShareUrl,wK as resolveScrapeResults,aq as resolveWorkingTurn,yE as resolvedPlan,cm as restartAppMachine,fr as restartProjectSession,qB as restartSandbox,bm as restoreAppVolume,aG as restoreBackup,wj as restoreDriveVersion,vc as retryAccountSecretResource,TS as retryFailed,Du as retrySessionPrompt,wU as revealCredential,gD as reviewItemTarget,aP as reviewSegmentForStatus,fD as reviewVerdictForStatus,Cc as revokeAccountSecretResourceGrant,oO as revokeAccountSession,hg as revokeAccountToken,zd as revokeAssignment,Fc as revokeConnection,_d as revokeGatewayKey,_g as revokeOAuthGrant,Za as revokePendingProjectInvite,Qa as revokeProjectAccess,Sg as revokeProjectCliToken,JB as revokeSandboxProjectAccess,ig as revokeSandboxShare,MM as revokeScimToken,wu as revokeSessionPublicShare,ut as rewriteLocalhostUrl,om as rollbackApp,Ak as rootRuntimeSession,Ac as rotateAccountSecretResource,Gd as rotateOAuthClientSecret,Uo as runConnector,Pd as runGatewayPlayground,VC as runProjectProviderOAuthFlow,fi as runtimeSessionsOf,Qx as runtimeSupports,rx as sanitizePtyChunk,Fa as saveGitHubInstallation,qk as savedCopyEmptyRoot,um as scaleApp,Ep as scheduleDowngrade,Oc as searchConnectorTools,Cl as searchProjectFiles,HK as segmentTurn,n$ as selectableProjectAgents,ms as sendMagicLink,XE as sendReferralEmails,SW as serverCompactionRevalidateAtMs,CU as serviceAction,DW as sessionConnectionLabel,OW as sessionListStatus,Gu as sessionModelPin,vT as sessionParentId,MT as sessionPromptActions,HT as sessionStartKey,Ic as setAccountSecretResourceAccess,hB as setActiveInstanceCookie,oD as setAdminBootModes,Nb as setAdminBypass,JO as setAdminProviderDistribution,nD as setAdminProviderFallback,gp as setAgentScope,rI as setBootstrapAuthToken,nI as setCachedAuthToken,wI as setConnectionPolicies,Qc as setConnectorAuthorizationStrategy,ul as setConnectorCredential,Yc as setConnectorCredentialMode,tl as setConnectorName,Zc as setConnectorPolicies,II as setConnectorSecretBinding,Xc as setConnectorSensitive,Kc as setDefaultConnection,TO as setEnterpriseDemo,mf as setEnv,fd as setGatewayBudget,od as setGatewayRoutingPolicy,m1 as setGitHubAppFromExisting,f1 as setGitHubAppPat,qR as setImpersonationSession,JG as setMaintenanceConfig,kM as setMemberSuperAdmin,LM as setMfaRequired,up as setModelDefault,_c as setPersonalProjectSecret,wr as setProjectModelAccess,ZT as setProjectModelEnablement,Ta as setProjectOnboardingComplete,RC as setProjectOnboardingProfile,yl as setProjectPolicies,gc as setProjectSecretStrategy,Bu as setProjectSessionModel,qu as setProjectSessionScope,yu as setProjectSessionSharing,Xu as setProjectTriggersActivation,hT as setSavedCopyStore,NM as setSessionOversight,Mc as setSessionProviderSecretPool,_u as setSessionWatch,X1 as settleSessionConnection,uG as setupSSH,Gc as shareConnection,uj as shareFolder,Fj as shellActivityGroupLabel,Eh as shellExitCode,Fb as shouldAttachImpersonation,gq as shouldHideResponsePart,dw as shouldShowToolPart,tq as shouldSuppressWorkingTurnBusy,XK as showGroupItems,bh as showTurnBusyIndicator,gs as signInWithPassword,ys as signInWithProvider,Ss as signInWithSso,As as signOut,ED as signOutDevice,ds as signUp,aB as skillDocumentPath,iB as skillInputDir,WN as sortSessions,Cq as splitTurnWork,gN as splitUserParts,tm as startApp,im as startAppMachine,bI as startConnectionOAuth2Authorization,_I as startConnectionOAuth2DeviceAuthorization,WG as startConnectorSetupLink,g1 as startGitHubAppManifest,Ao as startProjectProviderOAuth,nt as startProjectSession,ap as startProjectSessionOrThrow,QG as startSessionWithToken,D0 as startTask,nh as stepLabel,nm as stopApp,am as stopAppMachine,yr as stopProjectSession,BB as stopSandbox,Ka as storeGitHubUserToken,wN as stripAnsi,fB as stripInstancePrefix,se as stripTrailingSlashes,NG as submitAccessRequest,e1 as submitDemoRequest,BG as submitOAuthConsent,Zd as submitReviewItem,zG as submitSecretSetupLink,BR as subscribeToImpersonation,cC as supabaseClient,zc as syncConnectors,SE as syncSubscription,BU as systemReload,lt as toDaemonPath,bB as toInstanceAwarePath,yS as toInternalUrl,yn as toSandboxAbsolutePath,EN as toToolView,Tf as toWorkspaceRelative,zs as toolInfo,ae as toolKind,Cv as toolViewModel,_G as triggerSandboxUpdate,ZP as triggersRequest,hk as turnEndCause,hW as turnEndNotice,qN as turnHasSteps,rq as turnIsConfirmedActive,oq as turnRendersQueued,$W as turnRetryLabel,G0 as unassignTicket,Sm as unregisterDeviceToken,Im as unregisterWebPushSubscription,pj as unshareFolder,fe as unwrapError,Cg as updateAccountAuditWebhook,na as updateAccountBranding,ya as updateAccountMemberRole,ea as updateAccountName,uE as updateAgentConfig,qg as updateApp,zg as updateAppAccess,mm as updateAppVolume,PO as updateAuditWebhook,eu as updateChangeRequest,FE as updateChannelBinding,Lc as updateConnectionCredential,nd as updateEmailPolicy,Ca as updateExperimentalFeature,Ra as updateFeatureFlag,Ad as updateGroup,bf as updateKortixPty,yU as updateMilestone,km as updateNotificationPreferences,Bd as updateOAuthClient,_s as updatePassword,iO as updatePatPolicy,bM as updatePolicy,er as updateProject,Ya as updateProjectAccess,nU as updateProjectAgent,mp as updateProjectDefaultAgent,rc as updateProjectGroupGrant,Ia as updateProjectSandboxProvider,$u as updateProjectSession,Yu as updateProjectTrigger,jd as updateRole,$d as updateRolePermissions,Sl as updateSandboxTemplate,nO as updateSessionPolicy,Qo as updateSessionReminder,dg as updateSessionReminders,O0 as updateTask,kC as updateTemplateWarmPool,K0 as updateTicket,q0 as updateTicketStatus,xs as updateUserMetadata,ra as uploadAccountBrandingAsset,Qg as uploadAppArtifactArchive,Mo as uploadConnectorAttachment,bj as uploadDriveFile,Pn as uploadFile,Bx as uploadNativeFile,lr as uploadPromptAttachment,Dm as uploadSessionAttachment,Xp as uploadSlackChannelFile,gn as uploadTimeoutMsForBytes,SU as upsertCredential,hc as upsertProjectGitCredential,dc as upsertProjectSecret,WM as upsertSsoProvider,Sa as validateProjectManifest,zE as validateReferralCode,ba as validateToken,BE as verifyGatewayProvider,Jk as verifyKortixToken,fs as verifyOtp,VM as verifySsoDomain,TW as wakeEscalationAttemptSummary,IW as wakeEscalationNote,RW as wakeProgressFingerprint,Tt as wireIdClock,cn as wireIdClockAt,Et as wireIdClockDelta,Iq as workedForLabel,gW as workingExpiryAtMs,sq as workingTurnDrawsBusyRow,Nj as writeActivityGroupLabel,$r as writeFile,ei as wsDomain,xK as wsFavicon,PK as wsRootDomain};