@abacus-ai/cli 2.4.9-canary.2 → 2.4.9-canary.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.mjs +6 -6
  2. package/package.json +1 -1
package/dist/index.mjs CHANGED
@@ -2,7 +2,7 @@
2
2
  import{createRequire as e}from"node:module";import*as t from"node:util";import n,{isDeepStrictEqual as r,parseArgs as i,promisify as a,stripVTControlCharacters as o}from"node:util";import*as s from"node:fs";import c,{copyFileSync as l,createReadStream as u,createWriteStream as d,existsSync as f,mkdirSync as p,promises as m,readFile as h,readFileSync as g,readdir as _,readdirSync as v,realpathSync as y,statSync as b,unlinkSync as x,writeFileSync as S}from"node:fs";import{PassThrough as C,Readable as w,Transform as T,Writable as E}from"node:stream";import*as D from"node:path";import O,{dirname as k,join as A,posix as j,resolve as M,sep as N}from"node:path";import*as P from"node:os";import ee,{arch as F,homedir as te,hostname as I,platform as L}from"node:os";import{Worker as R,isMainThread as z,threadId as ne}from"node:worker_threads";import*as re from"node:diagnostics_channel";import{subscribe as ie}from"node:diagnostics_channel";import ae,{exec as oe,execFile as se,execFileSync as ce,execSync as le,spawn as ue,spawnSync as de}from"node:child_process";import*as fe from"node:readline";import B,{createInterface as pe}from"node:readline";import*as me from"node:http";import{createServer as he}from"node:http";import*as ge from"node:https";import{constants as _e,createGzip as ve,gunzipSync as ye,gzipSync as be}from"node:zlib";import*as V from"node:net";import*as xe from"node:tls";import{AsyncLocalStorage as Se}from"node:async_hooks";import{fileURLToPath as Ce}from"node:url";import*as we from"node:fs/promises";import Te,{mkdir as Ee,open as De,readFile as Oe,writeFile as ke}from"node:fs/promises";import*as Ae from"node:assert";import je from"node:assert";import{EventEmitter as Me}from"node:events";import{pipeline as Ne}from"node:stream/promises";import Pe,{createCipheriv as Fe,createDecipheriv as Ie,createHash as Le,pbkdf2Sync as Re,randomBytes as ze}from"node:crypto";import Be from"trash";import{rgPath as Ve}from"@vscode/ripgrep";import H,{stdin as He,stdout as Ue}from"node:process";import U from"node:tty";var We=Object.create,Ge=Object.defineProperty,Ke=Object.getOwnPropertyDescriptor,qe=Object.getOwnPropertyNames,Je=Object.getPrototypeOf,Ye=Object.prototype.hasOwnProperty,W=(e,t)=>()=>(e&&(t=e(e=0)),t),G=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Xe=(e,t)=>{let n={};for(var r in e)Ge(n,r,{get:e[r],enumerable:!0});return t||Ge(n,Symbol.toStringTag,{value:`Module`}),n},Ze=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=qe(t),a=0,o=i.length,s;a<o;a++)s=i[a],!Ye.call(e,s)&&s!==n&&Ge(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=Ke(t,s))||r.enumerable});return e},Qe=(e,t,n)=>(n=e==null?{}:We(Je(e)),Ze(t||!e||!e.__esModule?Ge(n,`default`,{value:e,enumerable:!0}):n,e)),$e=e=>Ye.call(e,`module.exports`)?e[`module.exports`]:Ze(Ge({},`__esModule`,{value:!0}),e),et=e(import.meta.url);const tt=Object.freeze({CLI:`CLI`,EXTENSION:`EXTENSION`,COWORK:`COWORK`});function nt(e){switch(e.trim().replaceAll(/[_\s-]+/g,``).toUpperCase()){case`CLI`:return tt.CLI;case`EXTENSION`:return tt.EXTENSION;case`COWORK`:return tt.COWORK;default:throw Error(`Invalid client type: ${e}. Expected one of ${Object.values(tt).join(`, `)}.`)}}const rt=Object.freeze({CHATLLM:`CHATLLM`,CODE_LLM:`CODE_LLM`,CODE_LLM_AGENT:`CODE_LLM_AGENT`,CODE_LLM_NON_INTERACTIVE:`CODE_LLM_NON_INTERACTIVE`});function it(e){return typeof e==`function`?e:at(e)}function at(e){if(e==null)return()=>!1;if(e===`fatal`)return e=>e.level===`fatal`;if(e===`error`)return e=>e.level===`fatal`||e.level===`error`;if(e===`warning`)return e=>e.level===`fatal`||e.level===`error`||e.level===`warning`;if(e===`info`)return e=>e.level===`fatal`||e.level===`error`||e.level===`warning`||e.level===`info`;if(e===`debug`)return e=>e.level===`fatal`||e.level===`error`||e.level===`warning`||e.level===`info`||e.level===`debug`;if(e===`trace`)return()=>!0;throw TypeError(`Invalid log level: ${e}.`)}const ot=[`trace`,`debug`,`info`,`warning`,`error`,`fatal`];function st(e,t){let n=ot.indexOf(e);if(n<0)throw TypeError(`Invalid log level: ${JSON.stringify(e)}.`);let r=ot.indexOf(t);if(r<0)throw TypeError(`Invalid log level: ${JSON.stringify(t)}.`);return n-r}const ct=Symbol.for(`logtape.lazy`);function lt(e){return typeof e==`object`&&!!e&&ct in e&&e[ct]===!0}function ut(e){let t={};for(let n in e){let r=e[n];t[n]=lt(r)?r.getter():r}return t}function dt(e=[]){return pt.getLogger(e)}const ft=Symbol.for(`logtape.rootLogger`);var pt=class e{parent;children;category;sinks;parentSinks=`inherit`;filters;lowestLevel=`trace`;contextLocalStorage;static getLogger(t=[]){let n=ft in globalThis?globalThis[ft]??null:null;return n??(n=new e(null,[]),globalThis[ft]=n),typeof t==`string`?n.getChild(t):t.length===0?n:n.getChild(t)}constructor(e,t){this.parent=e,this.children={},this.category=t,this.sinks=[],this.filters=[]}getChild(t){let n=typeof t==`string`?t:t[0],r=this.children[n],i=r instanceof e?r:r?.deref();return i??(i=new e(this,[...this.category,n]),this.children[n]=`WeakRef`in globalThis?new WeakRef(i):i),typeof t==`string`||t.length===1?i:i.getChild(t.slice(1))}reset(){for(;this.sinks.length>0;)this.sinks.shift();for(this.parentSinks=`inherit`;this.filters.length>0;)this.filters.shift();this.lowestLevel=`trace`}resetDescendants(){for(let t of Object.values(this.children))(t instanceof e?t:t.deref())?.resetDescendants();this.reset()}with(e){return new mt(this,{...e})}filter(e){for(let t of this.filters)if(!t(e))return!1;return this.filters.length<1?this.parent?.filter(e)??!0:!0}*getSinks(e){if(!(this.lowestLevel===null||st(e,this.lowestLevel)<0)){if(this.parent!=null&&this.parentSinks===`inherit`)for(let t of this.parent.getSinks(e))yield t;for(let e of this.sinks)yield e}}isEnabledFor(e){if(this.lowestLevel===null||st(e,this.lowestLevel)<0)return!1;for(let t of this.getSinks(e))return!0;return!1}emit(e,t){let n=wt(),r=`category`in e?e.category:this.category,i=n.length>0?[...n,...r]:r,a=Object.getOwnPropertyDescriptors(e);a.category={value:i,enumerable:!0,configurable:!0};let o=Object.defineProperties({},a);if(!(this.lowestLevel===null||st(o.level,this.lowestLevel)<0||!this.filter(o))){for(let e of this.getSinks(o.level))if(!t?.has(e))try{e(o)}catch(n){let r=new Set(t);r.add(e),ht.log(`fatal`,`Failed to emit a log record to sink {sink}: {error}`,{sink:e,error:n,record:o},r)}}}log(e,t,n,r){let i=Tt(),a,o=typeof n==`function`?{category:this.category,level:e,timestamp:Date.now(),get message(){return xt(t,this.properties)},rawMessage:t,get properties(){return a??={...i,...n()},a}}:{category:this.category,level:e,timestamp:Date.now(),message:xt(t,{...i,...n}),rawMessage:t,properties:{...i,...n}};this.emit(o,r)}logLazily(e,t,n={}){let r=Tt(),i,a;function o(){if((a==null||i==null)&&(a=t((e,...t)=>(i=e,St(e,t))),i==null))throw TypeError(`No log record was made.`);return[a,i]}this.emit({category:this.category,level:e,get message(){return o()[0]},get rawMessage(){return o()[1]},timestamp:Date.now(),properties:{...r,...n}})}logTemplate(e,t,n,r={}){let i=Tt();this.emit({category:this.category,level:e,message:St(t,n),rawMessage:t,timestamp:Date.now(),properties:{...i,...r}})}trace(e,...t){if(typeof e==`string`){let n=t[0];if(typeof n==`function`){if(n.constructor.name===`AsyncFunction`)return this.isEnabledFor(`trace`)?n().then(t=>{this.log(`trace`,e,t)}):Promise.resolve();let t=n();if(t instanceof Promise)return this.isEnabledFor(`trace`)?t.then(t=>{this.log(`trace`,e,t)}):Promise.resolve();this.log(`trace`,e,t);return}this.log(`trace`,e,n??{})}else typeof e==`function`?this.logLazily(`trace`,e):Array.isArray(e)?this.logTemplate(`trace`,e,t):this.log(`trace`,`{*}`,e)}debug(e,...t){if(typeof e==`string`){let n=t[0];if(typeof n==`function`){if(n.constructor.name===`AsyncFunction`)return this.isEnabledFor(`debug`)?n().then(t=>{this.log(`debug`,e,t)}):Promise.resolve();let t=n();if(t instanceof Promise)return this.isEnabledFor(`debug`)?t.then(t=>{this.log(`debug`,e,t)}):Promise.resolve();this.log(`debug`,e,t);return}this.log(`debug`,e,n??{})}else typeof e==`function`?this.logLazily(`debug`,e):Array.isArray(e)?this.logTemplate(`debug`,e,t):this.log(`debug`,`{*}`,e)}info(e,...t){if(typeof e==`string`){let n=t[0];if(typeof n==`function`){if(n.constructor.name===`AsyncFunction`)return this.isEnabledFor(`info`)?n().then(t=>{this.log(`info`,e,t)}):Promise.resolve();let t=n();if(t instanceof Promise)return this.isEnabledFor(`info`)?t.then(t=>{this.log(`info`,e,t)}):Promise.resolve();this.log(`info`,e,t);return}this.log(`info`,e,n??{})}else typeof e==`function`?this.logLazily(`info`,e):Array.isArray(e)?this.logTemplate(`info`,e,t):this.log(`info`,`{*}`,e)}warn(e,...t){if(e instanceof Error)this.log(`warning`,`{error.message}`,{error:e});else if(typeof e==`string`&&t[0]instanceof Error)this.log(`warning`,e,{error:t[0]});else if(typeof e==`string`){let n=t[0];if(typeof n==`function`){if(n.constructor.name===`AsyncFunction`)return this.isEnabledFor(`warning`)?n().then(t=>{this.log(`warning`,e,t)}):Promise.resolve();let t=n();if(t instanceof Promise)return this.isEnabledFor(`warning`)?t.then(t=>{this.log(`warning`,e,t)}):Promise.resolve();this.log(`warning`,e,t);return}this.log(`warning`,e,n??{})}else typeof e==`function`?this.logLazily(`warning`,e):Array.isArray(e)?this.logTemplate(`warning`,e,t):this.log(`warning`,`{*}`,e)}warning(e,...t){if(e instanceof Error)this.log(`warning`,`{error.message}`,{error:e});else if(typeof e==`string`&&t[0]instanceof Error)this.log(`warning`,e,{error:t[0]});else if(typeof e==`string`){let n=t[0];if(typeof n==`function`){if(n.constructor.name===`AsyncFunction`)return this.isEnabledFor(`warning`)?n().then(t=>{this.log(`warning`,e,t)}):Promise.resolve();let t=n();if(t instanceof Promise)return this.isEnabledFor(`warning`)?t.then(t=>{this.log(`warning`,e,t)}):Promise.resolve();this.log(`warning`,e,t);return}this.log(`warning`,e,n??{})}else typeof e==`function`?this.logLazily(`warning`,e):Array.isArray(e)?this.logTemplate(`warning`,e,t):this.log(`warning`,`{*}`,e)}error(e,...t){if(e instanceof Error)this.log(`error`,`{error.message}`,{error:e});else if(typeof e==`string`&&t[0]instanceof Error)this.log(`error`,e,{error:t[0]});else if(typeof e==`string`){let n=t[0];if(typeof n==`function`){if(n.constructor.name===`AsyncFunction`)return this.isEnabledFor(`error`)?n().then(t=>{this.log(`error`,e,t)}):Promise.resolve();let t=n();if(t instanceof Promise)return this.isEnabledFor(`error`)?t.then(t=>{this.log(`error`,e,t)}):Promise.resolve();this.log(`error`,e,t);return}this.log(`error`,e,n??{})}else typeof e==`function`?this.logLazily(`error`,e):Array.isArray(e)?this.logTemplate(`error`,e,t):this.log(`error`,`{*}`,e)}fatal(e,...t){if(e instanceof Error)this.log(`fatal`,`{error.message}`,{error:e});else if(typeof e==`string`&&t[0]instanceof Error)this.log(`fatal`,e,{error:t[0]});else if(typeof e==`string`){let n=t[0];if(typeof n==`function`){if(n.constructor.name===`AsyncFunction`)return this.isEnabledFor(`fatal`)?n().then(t=>{this.log(`fatal`,e,t)}):Promise.resolve();let t=n();if(t instanceof Promise)return this.isEnabledFor(`fatal`)?t.then(t=>{this.log(`fatal`,e,t)}):Promise.resolve();this.log(`fatal`,e,t);return}this.log(`fatal`,e,n??{})}else typeof e==`function`?this.logLazily(`fatal`,e):Array.isArray(e)?this.logTemplate(`fatal`,e,t):this.log(`fatal`,`{*}`,e)}},mt=class e{logger;properties;constructor(e,t){this.logger=e,this.properties=t}get category(){return this.logger.category}get parent(){return this.logger.parent}getChild(e){return this.logger.getChild(e).with(this.properties)}with(t){return new e(this.logger,{...this.properties,...t})}log(e,t,n,r){let i=this.properties;this.logger.log(e,t,typeof n==`function`?()=>ut({...i,...n()}):()=>ut({...i,...n}),r)}logLazily(e,t){this.logger.logLazily(e,t,ut(this.properties))}logTemplate(e,t,n){this.logger.logTemplate(e,t,n,ut(this.properties))}emit(e){let t={...e,properties:ut({...this.properties,...e.properties})};this.logger.emit(t)}isEnabledFor(e){return this.logger.isEnabledFor(e)}trace(e,...t){if(typeof e==`string`){let n=t[0];if(typeof n==`function`){if(n.constructor.name===`AsyncFunction`)return this.isEnabledFor(`trace`)?n().then(t=>{this.log(`trace`,e,t)}):Promise.resolve();let t=n();if(t instanceof Promise)return this.isEnabledFor(`trace`)?t.then(t=>{this.log(`trace`,e,t)}):Promise.resolve();this.log(`trace`,e,t);return}this.log(`trace`,e,n??{})}else typeof e==`function`?this.logLazily(`trace`,e):Array.isArray(e)?this.logTemplate(`trace`,e,t):this.log(`trace`,`{*}`,e)}debug(e,...t){if(typeof e==`string`){let n=t[0];if(typeof n==`function`){if(n.constructor.name===`AsyncFunction`)return this.isEnabledFor(`debug`)?n().then(t=>{this.log(`debug`,e,t)}):Promise.resolve();let t=n();if(t instanceof Promise)return this.isEnabledFor(`debug`)?t.then(t=>{this.log(`debug`,e,t)}):Promise.resolve();this.log(`debug`,e,t);return}this.log(`debug`,e,n??{})}else typeof e==`function`?this.logLazily(`debug`,e):Array.isArray(e)?this.logTemplate(`debug`,e,t):this.log(`debug`,`{*}`,e)}info(e,...t){if(typeof e==`string`){let n=t[0];if(typeof n==`function`){if(n.constructor.name===`AsyncFunction`)return this.isEnabledFor(`info`)?n().then(t=>{this.log(`info`,e,t)}):Promise.resolve();let t=n();if(t instanceof Promise)return this.isEnabledFor(`info`)?t.then(t=>{this.log(`info`,e,t)}):Promise.resolve();this.log(`info`,e,t);return}this.log(`info`,e,n??{})}else typeof e==`function`?this.logLazily(`info`,e):Array.isArray(e)?this.logTemplate(`info`,e,t):this.log(`info`,`{*}`,e)}warn(e,...t){if(e instanceof Error)this.log(`warning`,`{error.message}`,{error:e});else if(typeof e==`string`&&t[0]instanceof Error)this.log(`warning`,e,{error:t[0]});else if(typeof e==`string`){let n=t[0];if(typeof n==`function`){if(n.constructor.name===`AsyncFunction`)return this.isEnabledFor(`warning`)?n().then(t=>{this.log(`warning`,e,t)}):Promise.resolve();let t=n();if(t instanceof Promise)return this.isEnabledFor(`warning`)?t.then(t=>{this.log(`warning`,e,t)}):Promise.resolve();this.log(`warning`,e,t);return}this.log(`warning`,e,n??{})}else typeof e==`function`?this.logLazily(`warning`,e):Array.isArray(e)?this.logTemplate(`warning`,e,t):this.log(`warning`,`{*}`,e)}warning(e,...t){if(e instanceof Error)this.log(`warning`,`{error.message}`,{error:e});else if(typeof e==`string`&&t[0]instanceof Error)this.log(`warning`,e,{error:t[0]});else if(typeof e==`string`){let n=t[0];if(typeof n==`function`){if(n.constructor.name===`AsyncFunction`)return this.isEnabledFor(`warning`)?n().then(t=>{this.log(`warning`,e,t)}):Promise.resolve();let t=n();if(t instanceof Promise)return this.isEnabledFor(`warning`)?t.then(t=>{this.log(`warning`,e,t)}):Promise.resolve();this.log(`warning`,e,t);return}this.log(`warning`,e,n??{})}else typeof e==`function`?this.logLazily(`warning`,e):Array.isArray(e)?this.logTemplate(`warning`,e,t):this.log(`warning`,`{*}`,e)}error(e,...t){if(e instanceof Error)this.log(`error`,`{error.message}`,{error:e});else if(typeof e==`string`&&t[0]instanceof Error)this.log(`error`,e,{error:t[0]});else if(typeof e==`string`){let n=t[0];if(typeof n==`function`){if(n.constructor.name===`AsyncFunction`)return this.isEnabledFor(`error`)?n().then(t=>{this.log(`error`,e,t)}):Promise.resolve();let t=n();if(t instanceof Promise)return this.isEnabledFor(`error`)?t.then(t=>{this.log(`error`,e,t)}):Promise.resolve();this.log(`error`,e,t);return}this.log(`error`,e,n??{})}else typeof e==`function`?this.logLazily(`error`,e):Array.isArray(e)?this.logTemplate(`error`,e,t):this.log(`error`,`{*}`,e)}fatal(e,...t){if(e instanceof Error)this.log(`fatal`,`{error.message}`,{error:e});else if(typeof e==`string`&&t[0]instanceof Error)this.log(`fatal`,e,{error:t[0]});else if(typeof e==`string`){let n=t[0];if(typeof n==`function`){if(n.constructor.name===`AsyncFunction`)return this.isEnabledFor(`fatal`)?n().then(t=>{this.log(`fatal`,e,t)}):Promise.resolve();let t=n();if(t instanceof Promise)return this.isEnabledFor(`fatal`)?t.then(t=>{this.log(`fatal`,e,t)}):Promise.resolve();this.log(`fatal`,e,t);return}this.log(`fatal`,e,n??{})}else typeof e==`function`?this.logLazily(`fatal`,e):Array.isArray(e)?this.logTemplate(`fatal`,e,t):this.log(`fatal`,`{*}`,e)}};const ht=pt.getLogger([`logtape`,`meta`]);function gt(e){return e.includes(`.`)||e.includes(`[`)||e.includes(`?.`)}function _t(e,t){if(!(t===`__proto__`||t===`prototype`||t===`constructor`)&&(typeof e==`object`||typeof e==`function`)&&e!==null)return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function vt(e,t){let n=e.length,r=t;if(r>=n)return null;let i;if(e[r]===`[`){if(r++,r>=n)return null;if(e[r]===`"`||e[r]===`'`){let t=e[r];r++;let a=``;for(;r<n&&e[r]!==t;)if(e[r]===`\\`){if(r++,r<n){let t=e[r];switch(t){case`n`:a+=`
3
3
  `;break;case`t`:a+=` `;break;case`r`:a+=`\r`;break;case`b`:a+=`\b`;break;case`f`:a+=`\f`;break;case`v`:a+=`\v`;break;case`0`:a+=`\0`;break;case`\\`:a+=`\\`;break;case`"`:a+=`"`;break;case`'`:a+=`'`;break;case`u`:if(r+4<n){let n=e.slice(r+1,r+5),i=Number.parseInt(n,16);Number.isNaN(i)?a+=t:(a+=String.fromCharCode(i),r+=4)}else a+=t;break;default:a+=t}r++}}else a+=e[r],r++;if(r>=n)return null;i=a,r++}else{let t=r;for(;r<n&&e[r]!==`]`&&e[r]!==`'`&&e[r]!==`"`;)r++;if(r>=n)return null;let a=e.slice(t,r);if(a.length===0)return null;let o=Number(a);i=Number.isNaN(o)?a:o}for(;r<n&&e[r]!==`]`;)r++;r<n&&r++}else{let t=r;for(;r<n&&e[r]!==`.`&&e[r]!==`[`&&e[r]!==`?`&&e[r]!==`]`;)r++;if(i=e.slice(t,r),i.length===0)return null}return r<n&&e[r]===`.`&&r++,{segment:i,nextIndex:r}}function yt(e,t){if(typeof t==`string`)return _t(e,t);if(Array.isArray(e)&&t>=0&&t<e.length)return e[t]}function bt(e,t){if(e==null||t.length===0||t.endsWith(`.`))return;let n=e,r=0,i=t.length;for(;r<i;){if(t.slice(r,r+2)===`?.`){if(r+=2,n==null)return}else if(n==null)return;let e=vt(t,r);if(e===null)return;let{segment:i,nextIndex:a}=e;if(r=a,n=yt(n,i),n===void 0)return}return n}function xt(e,t){let n=e.length;if(n===0)return[``];if(!e.includes(`{`))return[e];let r=[],i=0;for(let a=0;a<n;a++){let o=e[a];if(o===`{`){if((a+1<n?e[a+1]:``)===`{`){a++;continue}let o=e.indexOf(`}`,a+1);if(o===-1)continue;let s=e.slice(i,a);r.push(s.replace(/{{/g,`{`).replace(/}}/g,`}`));let c=e.slice(a+1,o),l,u=c.trim();u===`*`?l=c in t?t[c]:`*`in t?t[`*`]:t:(l=c===u||c in t?t[c]:t[u],l===void 0&&gt(u)&&(l=bt(t,u))),r.push(l),a=o,i=a+1}else o===`}`&&a+1<n&&e[a+1]===`}`&&a++}let a=e.slice(i);return r.push(a.replace(/{{/g,`{`).replace(/}}/g,`}`)),r}function St(e,t){let n=[];for(let r=0;r<e.length;r++)n.push(e[r]),r<t.length&&n.push(t[r]);return n}const Ct=Symbol.for(`logtape.categoryPrefix`);function wt(){let e=pt.getLogger().contextLocalStorage?.getStore();if(e==null)return[];let t=e[Ct];return Array.isArray(t)?t:[]}function Tt(){let e=pt.getLogger().contextLocalStorage?.getStore();if(e==null)return{};let t={};for(let n of Object.keys(e))t[n]=e[n];return t}var Et=Xe({inspect:()=>Dt});function Dt(e,t){return n.inspect(e,t)}const Ot={trace:`TRC`,debug:`DBG`,info:`INF`,warning:`WRN`,error:`ERR`,fatal:`FTL`},kt=typeof document<`u`||typeof navigator<`u`&&navigator.product===`ReactNative`?e=>JSON.stringify(e):`Deno`in globalThis&&`inspect`in globalThis.Deno&&typeof globalThis.Deno.inspect==`function`?(e,t)=>globalThis.Deno.inspect(e,{strAbbreviateSize:1/0,iterableLimit:1/0,...t}):Et!=null&&`inspect`in Et&&typeof Dt==`function`?(e,t)=>Dt(e,{maxArrayLength:1/0,maxStringLength:1/0,...t}):e=>JSON.stringify(e);function At(e){return e<10?`0${e}`:`${e}`}function jt(e){return e<10?`00${e}`:e<100?`0${e}`:`${e}`}const Mt={"date-time-timezone":e=>{let t=new Date(e);return`${t.getUTCFullYear()}-${At(t.getUTCMonth()+1)}-${At(t.getUTCDate())} ${At(t.getUTCHours())}:${At(t.getUTCMinutes())}:${At(t.getUTCSeconds())}.${jt(t.getUTCMilliseconds())} +00:00`},"date-time-tz":e=>{let t=new Date(e);return`${t.getUTCFullYear()}-${At(t.getUTCMonth()+1)}-${At(t.getUTCDate())} ${At(t.getUTCHours())}:${At(t.getUTCMinutes())}:${At(t.getUTCSeconds())}.${jt(t.getUTCMilliseconds())} +00`},"date-time":e=>{let t=new Date(e);return`${t.getUTCFullYear()}-${At(t.getUTCMonth()+1)}-${At(t.getUTCDate())} ${At(t.getUTCHours())}:${At(t.getUTCMinutes())}:${At(t.getUTCSeconds())}.${jt(t.getUTCMilliseconds())}`},"time-timezone":e=>{let t=new Date(e);return`${At(t.getUTCHours())}:${At(t.getUTCMinutes())}:${At(t.getUTCSeconds())}.${jt(t.getUTCMilliseconds())} +00:00`},"time-tz":e=>{let t=new Date(e);return`${At(t.getUTCHours())}:${At(t.getUTCMinutes())}:${At(t.getUTCSeconds())}.${jt(t.getUTCMilliseconds())} +00`},time:e=>{let t=new Date(e);return`${At(t.getUTCHours())}:${At(t.getUTCMinutes())}:${At(t.getUTCSeconds())}.${jt(t.getUTCMilliseconds())}`},date:e=>{let t=new Date(e);return`${t.getUTCFullYear()}-${At(t.getUTCMonth()+1)}-${At(t.getUTCDate())}`},rfc3339:e=>new Date(e).toISOString(),none:()=>null},Nt={ABBR:Ot,abbr:{trace:`trc`,debug:`dbg`,info:`inf`,warning:`wrn`,error:`err`,fatal:`ftl`},FULL:{trace:`TRACE`,debug:`DEBUG`,info:`INFO`,warning:`WARNING`,error:`ERROR`,fatal:`FATAL`},full:{trace:`trace`,debug:`debug`,info:`info`,warning:`warning`,error:`error`,fatal:`fatal`},L:{trace:`T`,debug:`D`,info:`I`,warning:`W`,error:`E`,fatal:`F`},l:{trace:`t`,debug:`d`,info:`i`,warning:`w`,error:`e`,fatal:`f`}};function Pt(e){return e===`crlf`?`\r
4
4
  `:`
5
- `}function Ft(e,t){if(!(t instanceof Error))return t;let n={name:t.name,message:t.message};typeof t.stack==`string`&&(n.stack=t.stack);let r=t.cause;r!==void 0&&(n.cause=r),typeof AggregateError<`u`&&t instanceof AggregateError&&(n.errors=t.errors);for(let e of Object.keys(t))e in n||(n[e]=t[e]);return n}function It(e={}){let t=(()=>{let t=e.timestamp;return t==null?Mt[`date-time-timezone`]:t===`disabled`?Mt.none:typeof t==`string`&&t in Mt?Mt[t]:t})(),n=e.category??`·`,r=e.value?t=>e.value(t,kt):kt,i=(()=>{let t=e.level;return t==null||t===`ABBR`?e=>Nt.ABBR[e]:t===`abbr`?e=>Nt.abbr[e]:t===`FULL`?e=>Nt.FULL[e]:t===`full`?e=>Nt.full[e]:t===`L`?e=>Nt.L[e]:t===`l`?e=>Nt.l[e]:t})(),a=Pt(e.lineEnding),o=e.format??(({timestamp:e,level:t,category:n,message:r})=>`${e?`${e} `:``}[${t}] ${n}: ${r}`);return e=>{let s=e.message,c=s.length,l;if(c===1)l=s[0];else if(c<=6){l=``;for(let e=0;e<c;e++)l+=e%2==0?s[e]:r(s[e])}else{let e=Array(c);for(let t=0;t<c;t++)e[t]=t%2==0?s[t]:r(s[t]);l=e.join(``)}return`${o({timestamp:t(e.timestamp),level:i(e.level),category:typeof n==`function`?n(e.category):e.category.join(n),message:l,record:e})}${a}`}}const Lt=It(),Rt=`\x1B[0m`,zt={black:`\x1B[30m`,red:`\x1B[31m`,green:`\x1B[32m`,yellow:`\x1B[33m`,blue:`\x1B[34m`,magenta:`\x1B[35m`,cyan:`\x1B[36m`,white:`\x1B[37m`},Bt={bold:`\x1B[1m`,dim:`\x1B[2m`,italic:`\x1B[3m`,underline:`\x1B[4m`,strikethrough:`\x1B[9m`},Vt={trace:null,debug:`blue`,info:`green`,warning:`yellow`,error:`red`,fatal:`magenta`};function Ht(e={}){let t=e.format,n=e.timestampStyle===void 0?`dim`:e.timestampStyle,r=e.timestampColor??null,i=`${n==null?``:Bt[n]}${r==null?``:zt[r]}`,a=n==null&&r==null?``:Rt,o=e.levelStyle===void 0?`bold`:e.levelStyle,s=e.levelColors??Vt,c=e.categoryStyle===void 0?`dim`:e.categoryStyle,l=e.categoryColor??null,u=`${c==null?``:Bt[c]}${l==null?``:zt[l]}`,d=c==null&&l==null?``:Rt;return It({timestamp:`date-time-tz`,value(e,t){return t(e,{colors:!0})},...e,format({timestamp:e,level:n,category:r,message:c,record:l}){let f=s[l.level];return e=e==null?null:`${i}${e}${a}`,n=`${o==null?``:Bt[o]}${f==null?``:zt[f]}${n}${o==null&&f==null?``:Rt}`,t==null?`${e==null?``:`${e} `}${n} ${u}${r}:${d} ${c}`:t({timestamp:e,level:n,category:`${u}${r}${d}`,message:c,record:l})}})}Ht();function Ut(e={}){let t=Pt(e.lineEnding);if(!e.categorySeparator&&!e.message&&!e.properties)return e=>{if(e.message.length===3)return JSON.stringify({"@timestamp":new Date(e.timestamp).toISOString(),level:e.level===`warning`?`WARN`:e.level.toUpperCase(),message:e.message[0]+JSON.stringify(e.message[1])+e.message[2],logger:e.category.join(`.`),properties:e.properties},Ft)+t;if(e.message.length===1)return JSON.stringify({"@timestamp":new Date(e.timestamp).toISOString(),level:e.level===`warning`?`WARN`:e.level.toUpperCase(),message:e.message[0],logger:e.category.join(`.`),properties:e.properties},Ft)+t;let n=e.message[0];for(let t=1;t<e.message.length;t++)n+=t&1?JSON.stringify(e.message[t]):e.message[t];return JSON.stringify({"@timestamp":new Date(e.timestamp).toISOString(),level:e.level===`warning`?`WARN`:e.level.toUpperCase(),message:n,logger:e.category.join(`.`),properties:e.properties},Ft)+t};let n=e.message===`template`,r=e.properties??`nest:properties`,i;if(typeof e.categorySeparator==`function`)i=e.categorySeparator;else{let t=e.categorySeparator??`.`;i=e=>e.join(t)}let a;if(r===`flatten`)a=e=>e;else if(r.startsWith(`prepend:`)){let e=r.substring(8);if(e===``)throw TypeError(`Invalid properties option: ${JSON.stringify(r)}. It must be of the form "prepend:<prefix>" where <prefix> is a non-empty string.`);a=t=>{let n={};for(let r in t)n[`${e}${r}`]=t[r];return n}}else if(r.startsWith(`nest:`)){let e=r.substring(5);a=t=>({[e]:t})}else throw TypeError(`Invalid properties option: ${JSON.stringify(r)}. It must be "flatten", "prepend:<prefix>", or "nest:<key>".`);let o;return o=n?e=>{if(typeof e.rawMessage==`string`)return e.rawMessage;let t=``;for(let n=0;n<e.rawMessage.length;n++)t+=n%2<1?e.rawMessage[n]:`{}`;return t}:e=>{let t=e.message.length;if(t===1)return e.message[0];let n=``;for(let r=0;r<t;r++)n+=r%2<1?e.message[r]:JSON.stringify(e.message[r]);return n},e=>JSON.stringify({"@timestamp":new Date(e.timestamp).toISOString(),level:e.level===`warning`?`WARN`:e.level.toUpperCase(),message:o(e),logger:i(e.category),...a(e.properties)},Ft)+t}Ut();const Wt={trace:`background-color: gray; color: white;`,debug:`background-color: gray; color: white;`,info:`background-color: white; color: black;`,warning:`background-color: orange; color: black;`,error:`background-color: red; color: white;`,fatal:`background-color: maroon; color: white;`};function Gt(e){let t=``,n=[];for(let r=0;r<e.message.length;r++)r%2==0?t+=e.message[r]:(t+=`%o`,n.push(e.message[r]));let r=new Date(e.timestamp);return[`%c${`${r.getUTCHours().toString().padStart(2,`0`)}:${r.getUTCMinutes().toString().padStart(2,`0`)}:${r.getUTCSeconds().toString().padStart(2,`0`)}.${r.getUTCMilliseconds().toString().padStart(3,`0`)}`} %c${Ot[e.level]}%c %c${e.category.join(`·`)} %c${t}`,`color: gray;`,Wt[e.level],`background-color: default;`,`color: gray;`,`color: default;`,...n]}function Kt(e={}){let t=e.formatter??Gt,n={trace:`debug`,debug:`debug`,info:`info`,warning:`warn`,error:`error`,fatal:`error`,...e.levelMap??{}},r=e.console??globalThis.console,i=e=>{let i=t(e),a=n[e.level];if(a===void 0)throw TypeError(`Invalid log level: ${e.level}.`);if(typeof i==`string`){let e=i.replace(/\r?\n$/,``);r[a](e)}else r[a](...i)};if(!e.nonBlocking)return i;let a=e.nonBlocking===!0?{}:e.nonBlocking,o=a.bufferSize??100,s=a.flushInterval??100,c=[],l=null,u=!1,d=!1,f=o*2;function p(){if(c.length===0)return;let e=c.splice(0);for(let t of e)try{i(t)}catch{}}function m(){d||(d=!0,setTimeout(()=>{d=!1,p()},0))}function h(){l!==null||u||(l=setInterval(()=>{p()},s))}let g=e=>{u||(c.length>=f&&c.shift(),c.push(e),c.length>=o?m():l===null&&h())};return g[Symbol.dispose]=()=>{u=!0,l!==null&&(clearInterval(l),l=null),p()},g}let qt=null;const Jt=new Set,Yt=new Set,Xt=new Set;function Zt(e){return e.category.length===0||e.category.length===1&&e.category[0]===`logtape`||e.category.length===2&&e.category[0]===`logtape`&&e.category[1]===`meta`}function Qt(e){let t=e?rn:an;if(typeof globalThis.EdgeRuntime!=`string`&&`process`in globalThis&&!(`Deno`in globalThis)){let e=globalThis.process,n=e?.on;if(typeof n==`function`){n.call(e,`exit`,t);return}}let n=globalThis.addEventListener;typeof n==`function`&&(`Deno`in globalThis?n.call(globalThis,`unload`,t):n.call(globalThis,`pagehide`,t))}async function $t(e){if(qt!=null&&!e.reset)throw new on(`Already configured; if you want to reset, turn on the reset flag.`);await tn();try{en(e,!0)}catch(e){throw e instanceof on&&await tn(),e}}function en(e,t){qt=e;let n=!1,r=new Set;for(let t of e.loggers){Zt(t)&&(n=!0);let i=Array.isArray(t.category)?JSON.stringify(t.category):JSON.stringify([t.category]);if(r.has(i))throw new on(`Duplicate logger configuration for category: ${i}. Each category can only be configured once.`);r.add(i);let a=pt.getLogger(t.category);for(let n of t.sinks??[]){let t=e.sinks[n];if(!t)throw new on(`Sink not found: ${n}.`);a.sinks.push(t)}a.parentSinks=t.parentSinks??`inherit`,t.lowestLevel!==void 0&&(a.lowestLevel=t.lowestLevel);for(let n of t.filters??[]){let t=e.filters?.[n];if(t===void 0)throw new on(`Filter not found: ${n}.`);a.filters.push(it(t))}Jt.add(a)}pt.getLogger().contextLocalStorage=e.contextLocalStorage;for(let n of Object.values(e.sinks)){if(Symbol.asyncDispose in n)if(t)Xt.add(n);else throw new on(`Async disposables cannot be used with configureSync().`);Symbol.dispose in n&&Yt.add(n)}for(let n of Object.values(e.filters??{}))if(!(n==null||typeof n==`string`)){if(Symbol.asyncDispose in n)if(t)Xt.add(n);else throw new on(`Async disposables cannot be used with configureSync().`);Symbol.dispose in n&&Yt.add(n)}Qt(t);let i=pt.getLogger([`logtape`,`meta`]);n||i.sinks.push(Kt()),i.info(`LogTape loggers are configured. Note that LogTape itself uses the meta logger, which has category {metaLoggerCategory}. The meta logger is used to log internal diagnostics such as sink exceptions. It's recommended to configure the meta logger with a separate sink so that you can easily notice if logging itself fails or is misconfigured. To turn off this message, configure the meta logger with higher log levels than {dismissLevel}. See also <https://logtape.org/manual/categories#meta-logger>.`,{metaLoggerCategory:[`logtape`,`meta`],dismissLevel:`info`})}async function tn(){await rn(),nn()}function nn(){let e=pt.getLogger([]);e.resetDescendants(),delete e.contextLocalStorage,Jt.clear(),qt=null}async function rn(){an();let e=[];for(let t of Xt)e.push(t[Symbol.asyncDispose]()),Xt.delete(t);await Promise.all(e)}function an(){for(let e of Yt)e[Symbol.dispose]();Yt.clear()}var on=class extends Error{constructor(e){super(e),this.name=`ConfigureError`}};let sn=``;function cn(){let e=new Date,t=(e,t=2)=>String(e).padStart(t,`0`);return`${[e.getFullYear(),t(e.getMonth()+1),t(e.getDate()),`T`,t(e.getHours()),t(e.getMinutes()),t(e.getSeconds())].join(``)}-${Math.random().toString(36).substring(2,8)}`}function ln(){return sn||=cn(),sn}function un(e){sn=e}function dn(e,t){let n=t.formatter??Lt,r=t.encoder??new TextEncoder,i=t.maxSize??1024*1024,a=t.maxFiles??5,o=t.bufferSize??1024*8,s=t.flushInterval??5e3,c=0;try{c=t.statSync(e).size}catch{}let l=t.openSync(e),u=Date.now(),d=``;function f(e){return c+e.length>i}function p(){t.closeSync(l);for(let n=a-1;n>0;n--){let r=`${e}.${n}`,i=`${e}.${n+1}`;try{t.renameSync(r,i)}catch{}}t.renameSync(e,`${e}.1`),c=0,l=t.openSync(e)}if(!t.nonBlocking){function e(){if(d.length>0){let e=r.encode(d);d=``,f(e)&&p(),t.writeSync(l,e),t.flushSync(l),c+=e.length,u=Date.now()}}let i=t=>{d+=n(t);let r=d.length>=o,i=s>0&&t.timestamp-u>=s;(r||i)&&e()};return i[Symbol.dispose]=()=>{e(),t.closeSync(l)},i}let m=t,h=!1,g=null,_=null;async function v(){if(d.length===0)return;let e=d;d=``;try{let t=r.encode(e);f(t)&&p(),m.writeSync(l,t),await m.flush(l),c+=t.length,u=Date.now()}catch{}}function y(){g||h||(g=v().finally(()=>{g=null}))}function b(){_!==null||h||(_=setInterval(()=>{y()},s))}let x=e=>{if(h)return;d+=n(e);let t=d.length>=o,r=s>0&&e.timestamp-u>=s;t||r?y():_===null&&s>0&&b()};return x[Symbol.asyncDispose]=async()=>{h=!0,_!==null&&(clearInterval(_),_=null),await v();try{await m.close(l)}catch{}},x}const fn={openSync(e){return c.openSync(e,`a`)},writeSync:c.writeSync,writeManySync(e,t){if(t.length!==0){if(t.length===1){c.writeSync(e,t[0]);return}c.writevSync(e,t)}},flushSync:c.fsyncSync,closeSync:c.closeSync,statSync:c.statSync,renameSync:c.renameSync},pn={...fn,async writeMany(e,t){if(t.length!==0){if(t.length===1){await a(c.write)(e,t[0]);return}await a(c.writev)(e,t)}},flush:a(c.fsync),close:a(c.close)};({...fn}),c.readdirSync,c.unlinkSync,c.mkdirSync,{...pn},c.readdirSync,c.unlinkSync,c.mkdirSync;function mn(e,t={}){return t.nonBlocking?dn(e,{...t,...pn}):dn(e,{...t,...fn})}const hn={name:`abacusai`,fullName:`Abacus.AI`,longName:`Abacus.AI CLI`,description:`AI coding assistant`,binName:`abacusai`,binAliases:[`abacus`],configDirName:`.abacusai`,logsDirName:`logs`,configFileName:`config.json`,localConfigDirName:`.abacusai`,ideDirName:`ide`,envPrefix:`ABACUS_`,internalEnvPrefix:`CODELLM_`,socketEnvVar:`CODELLM_SOCKET_PATH`,keychainService:`abacusai`,mcpClientName:`abacusai-agent`,mcpOAuthClientName:`Abacus.AI Agent`,mcpConfigSourceType:`abacusai-user`,reactIdentifierPrefix:`abacusai-`,agentType:`CODE_LLM_AGENT`,sentryDsn:`https://bd1c87d300ab740912022757ddda4ad2@o270508.ingest.us.sentry.io/4511013419024384`},gn={publishName:`@abacus-ai/cli`,userAgentNames:{cli:`codellm-cli`,desktop:`codellm-desktop`,print:`codellm-non-interactive`},runtimeDeps:[`koffi`,`@vscode/ripgrep`,`trash`]};function _n(){return O.join(te(),hn.configDirName,hn.logsDirName)}function vn(e,t=20){try{let n=v(e).filter(e=>e.endsWith(`.log`)).map(t=>({name:t,mtime:b(O.join(e,t)).mtimeMs})).sort((e,t)=>t.mtime-e.mtime);for(let r of n.slice(t))try{x(O.join(e,r.name))}catch{}}catch{}}function yn(e){try{p(e,{recursive:!0})}catch{}}function bn(e,t){return yn(e),vn(e),mn(O.join(e,`${t}.log`),{maxSize:5*1024*1024,maxFiles:20})}async function xn(e={}){let t=e.sessionId??ln(),n=e.logDir??_n(),r=e.logLevel??(e.dev?`debug`:`info`),i={file:bn(n,t)};e.dev&&(i.console=Kt()),await $t({sinks:i,loggers:[{category:[`codellm`],lowestLevel:r,sinks:Object.keys(i)},{category:[`logtape`,`meta`],lowestLevel:`warning`,sinks:[]}]})}function Sn(){let e=dt([`codellm`,`api`]);return{error(t,...n){t instanceof Error?e.error(t):e.error`${t} ${n}`},warn(t,...n){e.warn`${t} ${n}`},debug(...t){e.debug`${t}`}}}const Cn=typeof __SENTRY_DEBUG__>`u`||__SENTRY_DEBUG__,wn=globalThis,Tn=`10.46.0`;function En(){return Dn(wn),wn}function Dn(e){let t=e.__SENTRY__=e.__SENTRY__||{};return t.version=t.version||`10.46.0`,t[Tn]=t[`10.46.0`]||{}}function On(e,t,n=wn){let r=n.__SENTRY__=n.__SENTRY__||{},i=r[Tn]=r[`10.46.0`]||{};return i[e]||(i[e]=t())}const kn=[`debug`,`info`,`warn`,`error`,`log`,`assert`,`trace`],An={};function jn(e){if(!(`console`in wn))return e();let t=wn.console,n={},r=Object.keys(An);r.forEach(e=>{let r=An[e];n[e]=t[e],t[e]=r});try{return e()}finally{r.forEach(e=>{t[e]=n[e]})}}function Mn(){zn().enabled=!0}function Nn(){zn().enabled=!1}function Pn(){return zn().enabled}function Fn(...e){Rn(`log`,...e)}function In(...e){Rn(`warn`,...e)}function Ln(...e){Rn(`error`,...e)}function Rn(e,...t){Cn&&Pn()&&jn(()=>{wn.console[e](`Sentry Logger [${e}]:`,...t)})}function zn(){return Cn?On(`loggerSettings`,()=>({enabled:!1})):{enabled:!1}}const Bn={enable:Mn,disable:Nn,isEnabled:Pn,log:Fn,warn:In,error:Ln},Vn=/\(error: (.*)\)/,Hn=/captureMessage|captureException/;function Un(...e){let t=e.sort((e,t)=>e[0]-t[0]).map(e=>e[1]);return(e,n=0,r=0)=>{let i=[],a=e.split(`
5
+ `}function Ft(e,t){if(!(t instanceof Error))return t;let n={name:t.name,message:t.message};typeof t.stack==`string`&&(n.stack=t.stack);let r=t.cause;r!==void 0&&(n.cause=r),typeof AggregateError<`u`&&t instanceof AggregateError&&(n.errors=t.errors);for(let e of Object.keys(t))e in n||(n[e]=t[e]);return n}function It(e={}){let t=(()=>{let t=e.timestamp;return t==null?Mt[`date-time-timezone`]:t===`disabled`?Mt.none:typeof t==`string`&&t in Mt?Mt[t]:t})(),n=e.category??`·`,r=e.value?t=>e.value(t,kt):kt,i=(()=>{let t=e.level;return t==null||t===`ABBR`?e=>Nt.ABBR[e]:t===`abbr`?e=>Nt.abbr[e]:t===`FULL`?e=>Nt.FULL[e]:t===`full`?e=>Nt.full[e]:t===`L`?e=>Nt.L[e]:t===`l`?e=>Nt.l[e]:t})(),a=Pt(e.lineEnding),o=e.format??(({timestamp:e,level:t,category:n,message:r})=>`${e?`${e} `:``}[${t}] ${n}: ${r}`);return e=>{let s=e.message,c=s.length,l;if(c===1)l=s[0];else if(c<=6){l=``;for(let e=0;e<c;e++)l+=e%2==0?s[e]:r(s[e])}else{let e=Array(c);for(let t=0;t<c;t++)e[t]=t%2==0?s[t]:r(s[t]);l=e.join(``)}return`${o({timestamp:t(e.timestamp),level:i(e.level),category:typeof n==`function`?n(e.category):e.category.join(n),message:l,record:e})}${a}`}}const Lt=It(),Rt=`\x1B[0m`,zt={black:`\x1B[30m`,red:`\x1B[31m`,green:`\x1B[32m`,yellow:`\x1B[33m`,blue:`\x1B[34m`,magenta:`\x1B[35m`,cyan:`\x1B[36m`,white:`\x1B[37m`},Bt={bold:`\x1B[1m`,dim:`\x1B[2m`,italic:`\x1B[3m`,underline:`\x1B[4m`,strikethrough:`\x1B[9m`},Vt={trace:null,debug:`blue`,info:`green`,warning:`yellow`,error:`red`,fatal:`magenta`};function Ht(e={}){let t=e.format,n=e.timestampStyle===void 0?`dim`:e.timestampStyle,r=e.timestampColor??null,i=`${n==null?``:Bt[n]}${r==null?``:zt[r]}`,a=n==null&&r==null?``:Rt,o=e.levelStyle===void 0?`bold`:e.levelStyle,s=e.levelColors??Vt,c=e.categoryStyle===void 0?`dim`:e.categoryStyle,l=e.categoryColor??null,u=`${c==null?``:Bt[c]}${l==null?``:zt[l]}`,d=c==null&&l==null?``:Rt;return It({timestamp:`date-time-tz`,value(e,t){return t(e,{colors:!0})},...e,format({timestamp:e,level:n,category:r,message:c,record:l}){let f=s[l.level];return e=e==null?null:`${i}${e}${a}`,n=`${o==null?``:Bt[o]}${f==null?``:zt[f]}${n}${o==null&&f==null?``:Rt}`,t==null?`${e==null?``:`${e} `}${n} ${u}${r}:${d} ${c}`:t({timestamp:e,level:n,category:`${u}${r}${d}`,message:c,record:l})}})}Ht();function Ut(e={}){let t=Pt(e.lineEnding);if(!e.categorySeparator&&!e.message&&!e.properties)return e=>{if(e.message.length===3)return JSON.stringify({"@timestamp":new Date(e.timestamp).toISOString(),level:e.level===`warning`?`WARN`:e.level.toUpperCase(),message:e.message[0]+JSON.stringify(e.message[1])+e.message[2],logger:e.category.join(`.`),properties:e.properties},Ft)+t;if(e.message.length===1)return JSON.stringify({"@timestamp":new Date(e.timestamp).toISOString(),level:e.level===`warning`?`WARN`:e.level.toUpperCase(),message:e.message[0],logger:e.category.join(`.`),properties:e.properties},Ft)+t;let n=e.message[0];for(let t=1;t<e.message.length;t++)n+=t&1?JSON.stringify(e.message[t]):e.message[t];return JSON.stringify({"@timestamp":new Date(e.timestamp).toISOString(),level:e.level===`warning`?`WARN`:e.level.toUpperCase(),message:n,logger:e.category.join(`.`),properties:e.properties},Ft)+t};let n=e.message===`template`,r=e.properties??`nest:properties`,i;if(typeof e.categorySeparator==`function`)i=e.categorySeparator;else{let t=e.categorySeparator??`.`;i=e=>e.join(t)}let a;if(r===`flatten`)a=e=>e;else if(r.startsWith(`prepend:`)){let e=r.substring(8);if(e===``)throw TypeError(`Invalid properties option: ${JSON.stringify(r)}. It must be of the form "prepend:<prefix>" where <prefix> is a non-empty string.`);a=t=>{let n={};for(let r in t)n[`${e}${r}`]=t[r];return n}}else if(r.startsWith(`nest:`)){let e=r.substring(5);a=t=>({[e]:t})}else throw TypeError(`Invalid properties option: ${JSON.stringify(r)}. It must be "flatten", "prepend:<prefix>", or "nest:<key>".`);let o;return o=n?e=>{if(typeof e.rawMessage==`string`)return e.rawMessage;let t=``;for(let n=0;n<e.rawMessage.length;n++)t+=n%2<1?e.rawMessage[n]:`{}`;return t}:e=>{let t=e.message.length;if(t===1)return e.message[0];let n=``;for(let r=0;r<t;r++)n+=r%2<1?e.message[r]:JSON.stringify(e.message[r]);return n},e=>JSON.stringify({"@timestamp":new Date(e.timestamp).toISOString(),level:e.level===`warning`?`WARN`:e.level.toUpperCase(),message:o(e),logger:i(e.category),...a(e.properties)},Ft)+t}Ut();const Wt={trace:`background-color: gray; color: white;`,debug:`background-color: gray; color: white;`,info:`background-color: white; color: black;`,warning:`background-color: orange; color: black;`,error:`background-color: red; color: white;`,fatal:`background-color: maroon; color: white;`};function Gt(e){let t=``,n=[];for(let r=0;r<e.message.length;r++)r%2==0?t+=e.message[r]:(t+=`%o`,n.push(e.message[r]));let r=new Date(e.timestamp);return[`%c${`${r.getUTCHours().toString().padStart(2,`0`)}:${r.getUTCMinutes().toString().padStart(2,`0`)}:${r.getUTCSeconds().toString().padStart(2,`0`)}.${r.getUTCMilliseconds().toString().padStart(3,`0`)}`} %c${Ot[e.level]}%c %c${e.category.join(`·`)} %c${t}`,`color: gray;`,Wt[e.level],`background-color: default;`,`color: gray;`,`color: default;`,...n]}function Kt(e={}){let t=e.formatter??Gt,n={trace:`debug`,debug:`debug`,info:`info`,warning:`warn`,error:`error`,fatal:`error`,...e.levelMap??{}},r=e.console??globalThis.console,i=e=>{let i=t(e),a=n[e.level];if(a===void 0)throw TypeError(`Invalid log level: ${e.level}.`);if(typeof i==`string`){let e=i.replace(/\r?\n$/,``);r[a](e)}else r[a](...i)};if(!e.nonBlocking)return i;let a=e.nonBlocking===!0?{}:e.nonBlocking,o=a.bufferSize??100,s=a.flushInterval??100,c=[],l=null,u=!1,d=!1,f=o*2;function p(){if(c.length===0)return;let e=c.splice(0);for(let t of e)try{i(t)}catch{}}function m(){d||(d=!0,setTimeout(()=>{d=!1,p()},0))}function h(){l!==null||u||(l=setInterval(()=>{p()},s))}let g=e=>{u||(c.length>=f&&c.shift(),c.push(e),c.length>=o?m():l===null&&h())};return g[Symbol.dispose]=()=>{u=!0,l!==null&&(clearInterval(l),l=null),p()},g}let qt=null;const Jt=new Set,Yt=new Set,Xt=new Set;function Zt(e){return e.category.length===0||e.category.length===1&&e.category[0]===`logtape`||e.category.length===2&&e.category[0]===`logtape`&&e.category[1]===`meta`}function Qt(e){let t=e?rn:an;if(typeof globalThis.EdgeRuntime!=`string`&&`process`in globalThis&&!(`Deno`in globalThis)){let e=globalThis.process,n=e?.on;if(typeof n==`function`){n.call(e,`exit`,t);return}}let n=globalThis.addEventListener;typeof n==`function`&&(`Deno`in globalThis?n.call(globalThis,`unload`,t):n.call(globalThis,`pagehide`,t))}async function $t(e){if(qt!=null&&!e.reset)throw new on(`Already configured; if you want to reset, turn on the reset flag.`);await tn();try{en(e,!0)}catch(e){throw e instanceof on&&await tn(),e}}function en(e,t){qt=e;let n=!1,r=new Set;for(let t of e.loggers){Zt(t)&&(n=!0);let i=Array.isArray(t.category)?JSON.stringify(t.category):JSON.stringify([t.category]);if(r.has(i))throw new on(`Duplicate logger configuration for category: ${i}. Each category can only be configured once.`);r.add(i);let a=pt.getLogger(t.category);for(let n of t.sinks??[]){let t=e.sinks[n];if(!t)throw new on(`Sink not found: ${n}.`);a.sinks.push(t)}a.parentSinks=t.parentSinks??`inherit`,t.lowestLevel!==void 0&&(a.lowestLevel=t.lowestLevel);for(let n of t.filters??[]){let t=e.filters?.[n];if(t===void 0)throw new on(`Filter not found: ${n}.`);a.filters.push(it(t))}Jt.add(a)}pt.getLogger().contextLocalStorage=e.contextLocalStorage;for(let n of Object.values(e.sinks)){if(Symbol.asyncDispose in n)if(t)Xt.add(n);else throw new on(`Async disposables cannot be used with configureSync().`);Symbol.dispose in n&&Yt.add(n)}for(let n of Object.values(e.filters??{}))if(!(n==null||typeof n==`string`)){if(Symbol.asyncDispose in n)if(t)Xt.add(n);else throw new on(`Async disposables cannot be used with configureSync().`);Symbol.dispose in n&&Yt.add(n)}Qt(t);let i=pt.getLogger([`logtape`,`meta`]);n||i.sinks.push(Kt()),i.info(`LogTape loggers are configured. Note that LogTape itself uses the meta logger, which has category {metaLoggerCategory}. The meta logger is used to log internal diagnostics such as sink exceptions. It's recommended to configure the meta logger with a separate sink so that you can easily notice if logging itself fails or is misconfigured. To turn off this message, configure the meta logger with higher log levels than {dismissLevel}. See also <https://logtape.org/manual/categories#meta-logger>.`,{metaLoggerCategory:[`logtape`,`meta`],dismissLevel:`info`})}async function tn(){await rn(),nn()}function nn(){let e=pt.getLogger([]);e.resetDescendants(),delete e.contextLocalStorage,Jt.clear(),qt=null}async function rn(){an();let e=[];for(let t of Xt)e.push(t[Symbol.asyncDispose]()),Xt.delete(t);await Promise.all(e)}function an(){for(let e of Yt)e[Symbol.dispose]();Yt.clear()}var on=class extends Error{constructor(e){super(e),this.name=`ConfigureError`}};let sn=``;function cn(){let e=new Date,t=(e,t=2)=>String(e).padStart(t,`0`);return`${[e.getFullYear(),t(e.getMonth()+1),t(e.getDate()),`T`,t(e.getHours()),t(e.getMinutes()),t(e.getSeconds())].join(``)}-${Math.random().toString(36).substring(2,8)}`}function ln(){return sn||=cn(),sn}function un(e){sn=e}function dn(e,t){let n=t.formatter??Lt,r=t.encoder??new TextEncoder,i=t.maxSize??1024*1024,a=t.maxFiles??5,o=t.bufferSize??1024*8,s=t.flushInterval??5e3,c=0;try{c=t.statSync(e).size}catch{}let l=t.openSync(e),u=Date.now(),d=``;function f(e){return c+e.length>i}function p(){t.closeSync(l);for(let n=a-1;n>0;n--){let r=`${e}.${n}`,i=`${e}.${n+1}`;try{t.renameSync(r,i)}catch{}}t.renameSync(e,`${e}.1`),c=0,l=t.openSync(e)}if(!t.nonBlocking){function e(){if(d.length>0){let e=r.encode(d);d=``,f(e)&&p(),t.writeSync(l,e),t.flushSync(l),c+=e.length,u=Date.now()}}let i=t=>{d+=n(t);let r=d.length>=o,i=s>0&&t.timestamp-u>=s;(r||i)&&e()};return i[Symbol.dispose]=()=>{e(),t.closeSync(l)},i}let m=t,h=!1,g=null,_=null;async function v(){if(d.length===0)return;let e=d;d=``;try{let t=r.encode(e);f(t)&&p(),m.writeSync(l,t),await m.flush(l),c+=t.length,u=Date.now()}catch{}}function y(){g||h||(g=v().finally(()=>{g=null}))}function b(){_!==null||h||(_=setInterval(()=>{y()},s))}let x=e=>{if(h)return;d+=n(e);let t=d.length>=o,r=s>0&&e.timestamp-u>=s;t||r?y():_===null&&s>0&&b()};return x[Symbol.asyncDispose]=async()=>{h=!0,_!==null&&(clearInterval(_),_=null),await v();try{await m.close(l)}catch{}},x}const fn={openSync(e){return c.openSync(e,`a`)},writeSync:c.writeSync,writeManySync(e,t){if(t.length!==0){if(t.length===1){c.writeSync(e,t[0]);return}c.writevSync(e,t)}},flushSync:c.fsyncSync,closeSync:c.closeSync,statSync:c.statSync,renameSync:c.renameSync},pn={...fn,async writeMany(e,t){if(t.length!==0){if(t.length===1){await a(c.write)(e,t[0]);return}await a(c.writev)(e,t)}},flush:a(c.fsync),close:a(c.close)};({...fn}),c.readdirSync,c.unlinkSync,c.mkdirSync,{...pn},c.readdirSync,c.unlinkSync,c.mkdirSync;function mn(e,t={}){return t.nonBlocking?dn(e,{...t,...pn}):dn(e,{...t,...fn})}const hn={name:`abacusai`,fullName:`Abacus.AI`,longName:`Abacus.AI CLI`,description:`AI coding assistant`,binName:`abacusai`,binAliases:[`abacus`],configDirName:`.abacusai`,logsDirName:`logs`,configFileName:`config.json`,localConfigDirName:`.abacusai`,ideDirName:`ide`,envPrefix:`ABACUS_`,internalEnvPrefix:`CODELLM_`,socketEnvVar:`CODELLM_SOCKET_PATH`,keychainService:`abacusai`,mcpClientName:`abacusai-agent`,mcpOAuthClientName:`Abacus.AI Agent`,mcpConfigSourceType:`abacusai-user`,reactIdentifierPrefix:`abacusai-`,agentType:`CODE_LLM_AGENT`,nonInteractiveAgentType:`CODE_LLM_NON_INTERACTIVE`,sentryDsn:`https://bd1c87d300ab740912022757ddda4ad2@o270508.ingest.us.sentry.io/4511013419024384`},gn={publishName:`@abacus-ai/cli`,userAgentNames:{cli:`codellm-cli`,desktop:`codellm-desktop`,print:`codellm-non-interactive`},runtimeDeps:[`koffi`,`@vscode/ripgrep`,`trash`]};function _n(){return O.join(te(),hn.configDirName,hn.logsDirName)}function vn(e,t=20){try{let n=v(e).filter(e=>e.endsWith(`.log`)).map(t=>({name:t,mtime:b(O.join(e,t)).mtimeMs})).sort((e,t)=>t.mtime-e.mtime);for(let r of n.slice(t))try{x(O.join(e,r.name))}catch{}}catch{}}function yn(e){try{p(e,{recursive:!0})}catch{}}function bn(e,t){return yn(e),vn(e),mn(O.join(e,`${t}.log`),{maxSize:5*1024*1024,maxFiles:20})}async function xn(e={}){let t=e.sessionId??ln(),n=e.logDir??_n(),r=e.logLevel??(e.dev?`debug`:`info`),i={file:bn(n,t)};e.dev&&(i.console=Kt()),await $t({sinks:i,loggers:[{category:[`codellm`],lowestLevel:r,sinks:Object.keys(i)},{category:[`logtape`,`meta`],lowestLevel:`warning`,sinks:[]}]})}function Sn(){let e=dt([`codellm`,`api`]);return{error(t,...n){t instanceof Error?e.error(t):e.error`${t} ${n}`},warn(t,...n){e.warn`${t} ${n}`},debug(...t){e.debug`${t}`}}}const Cn=typeof __SENTRY_DEBUG__>`u`||__SENTRY_DEBUG__,wn=globalThis,Tn=`10.46.0`;function En(){return Dn(wn),wn}function Dn(e){let t=e.__SENTRY__=e.__SENTRY__||{};return t.version=t.version||`10.46.0`,t[Tn]=t[`10.46.0`]||{}}function On(e,t,n=wn){let r=n.__SENTRY__=n.__SENTRY__||{},i=r[Tn]=r[`10.46.0`]||{};return i[e]||(i[e]=t())}const kn=[`debug`,`info`,`warn`,`error`,`log`,`assert`,`trace`],An={};function jn(e){if(!(`console`in wn))return e();let t=wn.console,n={},r=Object.keys(An);r.forEach(e=>{let r=An[e];n[e]=t[e],t[e]=r});try{return e()}finally{r.forEach(e=>{t[e]=n[e]})}}function Mn(){zn().enabled=!0}function Nn(){zn().enabled=!1}function Pn(){return zn().enabled}function Fn(...e){Rn(`log`,...e)}function In(...e){Rn(`warn`,...e)}function Ln(...e){Rn(`error`,...e)}function Rn(e,...t){Cn&&Pn()&&jn(()=>{wn.console[e](`Sentry Logger [${e}]:`,...t)})}function zn(){return Cn?On(`loggerSettings`,()=>({enabled:!1})):{enabled:!1}}const Bn={enable:Mn,disable:Nn,isEnabled:Pn,log:Fn,warn:In,error:Ln},Vn=/\(error: (.*)\)/,Hn=/captureMessage|captureException/;function Un(...e){let t=e.sort((e,t)=>e[0]-t[0]).map(e=>e[1]);return(e,n=0,r=0)=>{let i=[],a=e.split(`
6
6
  `);for(let e=n;e<a.length;e++){let n=a[e];n.length>1024&&(n=n.slice(0,1024));let o=Vn.test(n)?n.replace(Vn,`$1`):n;if(!o.match(/\S*Error: /)){for(let e of t){let t=e(o);if(t){i.push(t);break}}if(i.length>=50+r)break}}return Gn(i.slice(r))}}function Wn(e){return Array.isArray(e)?Un(...e):e}function Gn(e){if(!e.length)return[];let t=Array.from(e);return/sentryWrapped/.test(Kn(t).function||``)&&t.pop(),t.reverse(),Hn.test(Kn(t).function||``)&&(t.pop(),Hn.test(Kn(t).function||``)&&t.pop()),t.slice(0,50).map(e=>({...e,filename:e.filename||Kn(t).filename,function:e.function||`?`}))}function Kn(e){return e[e.length-1]||{}}const qn=`<anonymous>`;function Jn(e){try{return!e||typeof e!=`function`?qn:e.name||qn}catch{return qn}}function Yn(e){return`__v_isVNode`in e&&e.__v_isVNode?`[VueVNode]`:`[VueViewModel]`}function Xn(e){let t=e?.startsWith(`file://`)?e.slice(7):e;return t?.match(/\/[A-Z]:/)&&(t=t.slice(1)),t}const Zn={},Qn={};function $n(e,t){Zn[e]=Zn[e]||[],Zn[e].push(t)}function er(e,t){if(!Qn[e]){Qn[e]=!0;try{t()}catch(t){Cn&&Bn.error(`Error while instrumenting ${e}`,t)}}}function tr(e,t){let n=e&&Zn[e];if(n)for(let r of n)try{r(t)}catch(t){Cn&&Bn.error(`Error while triggering instrumentation handler.\nType: ${e}\nName: ${Jn(r)}\nError:`,t)}}let nr=null;function rr(e){let t=`error`;$n(t,e),er(t,ir)}function ir(){nr=wn.onerror,wn.onerror=function(e,t,n,r,i){return tr(`error`,{column:r,error:i,line:n,msg:e,url:t}),nr?nr.apply(this,arguments):!1},wn.onerror.__SENTRY_INSTRUMENTED__=!0}let ar=null;function or(e){let t=`unhandledrejection`;$n(t,e),er(t,sr)}function sr(){ar=wn.onunhandledrejection,wn.onunhandledrejection=function(e){return tr(`unhandledrejection`,e),ar?ar.apply(this,arguments):!0},wn.onunhandledrejection.__SENTRY_INSTRUMENTED__=!0}const cr=Object.prototype.toString;function lr(e){switch(cr.call(e)){case`[object Error]`:case`[object Exception]`:case`[object DOMException]`:case`[object WebAssembly.Exception]`:return!0;default:return xr(e,Error)}}function ur(e,t){return cr.call(e)===`[object ${t}]`}function dr(e){return ur(e,`ErrorEvent`)}function fr(e){return ur(e,`String`)}function pr(e){return typeof e==`object`&&!!e&&`__sentry_template_string__`in e&&`__sentry_template_values__`in e}function mr(e){return e===null||pr(e)||typeof e!=`object`&&typeof e!=`function`}function hr(e){return ur(e,`Object`)}function gr(e){return typeof Event<`u`&&xr(e,Event)}function _r(e){return typeof Element<`u`&&xr(e,Element)}function vr(e){return ur(e,`RegExp`)}function yr(e){return!!(e?.then&&typeof e.then==`function`)}function br(e){return hr(e)&&`nativeEvent`in e&&`preventDefault`in e&&`stopPropagation`in e}function xr(e,t){try{return e instanceof t}catch{return!1}}function Sr(e){return!!(typeof e==`object`&&e&&(e.__isVue||e._isVue||e.__v_isVNode))}const Cr=wn;function wr(e,t={}){if(!e)return`<unknown>`;try{let n=e,r=[],i=0,a=0,o,s=Array.isArray(t)?t:t.keyAttrs,c=!Array.isArray(t)&&t.maxStringLength||80;for(;n&&i++<5&&(o=Tr(n,s),!(o===`html`||i>1&&a+r.length*3+o.length>=c));)r.push(o),a+=o.length,n=n.parentNode;return r.reverse().join(` > `)}catch{return`<unknown>`}}function Tr(e,t){let n=e,r=[];if(!n?.tagName)return``;if(Cr.HTMLElement&&n instanceof HTMLElement&&n.dataset){if(n.dataset.sentryComponent)return n.dataset.sentryComponent;if(n.dataset.sentryElement)return n.dataset.sentryElement}r.push(n.tagName.toLowerCase());let i=t?.length?t.filter(e=>n.getAttribute(e)).map(e=>[e,n.getAttribute(e)]):null;if(i?.length)i.forEach(e=>{r.push(`[${e[0]}="${e[1]}"]`)});else{n.id&&r.push(`#${n.id}`);let e=n.className;if(e&&fr(e)){let t=e.split(/\s+/);for(let e of t)r.push(`.${e}`)}}for(let e of[`aria-label`,`type`,`name`,`title`,`alt`]){let t=n.getAttribute(e);t&&r.push(`[${e}="${t}"]`)}return r.join(``)}function Er(e,t,n){if(!(t in e))return;let r=e[t];if(typeof r!=`function`)return;let i=n(r);typeof i==`function`&&Or(i,r);try{e[t]=i}catch{Cn&&Bn.log(`Failed to replace method "${t}" in object`,e)}}function Dr(e,t,n){try{Object.defineProperty(e,t,{value:n,writable:!0,configurable:!0})}catch{Cn&&Bn.log(`Failed to add non-enumerable property "${t}" to object`,e)}}function Or(e,t){try{e.prototype=t.prototype=t.prototype||{},Dr(e,`__sentry_original__`,t)}catch{}}function kr(e){return e.__sentry_original__}function Ar(e){if(lr(e))return{message:e.message,name:e.name,stack:e.stack,...Mr(e)};if(gr(e)){let t={type:e.type,target:jr(e.target),currentTarget:jr(e.currentTarget),...Mr(e)};return typeof CustomEvent<`u`&&xr(e,CustomEvent)&&(t.detail=e.detail),t}else return e}function jr(e){try{return _r(e)?wr(e):Object.prototype.toString.call(e)}catch{return`<unknown>`}}function Mr(e){return typeof e==`object`&&e?Object.fromEntries(Object.entries(e)):{}}function Nr(e){let t=Object.keys(Ar(e));return t.sort(),t[0]?t.join(`, `):`[object has no keys]`}let Pr;function Fr(e){if(Pr!==void 0)return Pr?Pr(e):e();let t=Symbol.for(`__SENTRY_SAFE_RANDOM_ID_WRAPPER__`),n=wn;return t in n&&typeof n[t]==`function`?(Pr=n[t],Pr(e)):(Pr=null,e())}function Ir(){return Fr(()=>Math.random())}function Lr(){return Fr(()=>Date.now())}function Rr(e,t=0){return typeof e!=`string`||t===0||e.length<=t?e:`${e.slice(0,t)}...`}function zr(e,t){let n=e,r=n.length;if(r<=150)return n;t>r&&(t=r);let i=Math.max(t-60,0);i<5&&(i=0);let a=Math.min(i+140,r);return a>r-5&&(a=r),a===r&&(i=Math.max(a-140,0)),n=n.slice(i,a),i>0&&(n=`'{snip} ${n}`),a<r&&(n+=` {snip}`),n}function Br(e,t){if(!Array.isArray(e))return``;let n=[];for(let t=0;t<e.length;t++){let r=e[t];try{Sr(r)?n.push(Yn(r)):n.push(String(r))}catch{n.push(`[value cannot be serialized]`)}}return n.join(t)}function Vr(e,t,n=!1){return fr(e)?vr(t)?t.test(e):fr(t)?n?e===t:e.includes(t):!1:!1}function Hr(e,t=[],n=!1){return t.some(t=>Vr(e,t,n))}function Ur(){let e=wn;return e.crypto||e.msCrypto}let Wr;function Gr(){return Ir()*16}function Kr(e=Ur()){try{if(e?.randomUUID)return Fr(()=>e.randomUUID()).replace(/-/g,``)}catch{}return Wr||=`10000000100040008000100000000000`,Wr.replace(/[018]/g,e=>(e^(Gr()&15)>>e/4).toString(16))}function qr(e){return e.exception?.values?.[0]}function Jr(e){let{message:t,event_id:n}=e;if(t)return t;let r=qr(e);return r?r.type&&r.value?`${r.type}: ${r.value}`:r.type||r.value||n||`<unknown>`:n||`<unknown>`}function Yr(e,t,n){let r=e.exception=e.exception||{},i=r.values=r.values||[],a=i[0]=i[0]||{};a.value||=t||``,a.type||=n||`Error`}function Xr(e,t){let n=qr(e);if(!n)return;let r={type:`generic`,handled:!0},i=n.mechanism;if(n.mechanism={...r,...i,...t},t&&`data`in t){let e={...i?.data,...t.data};n.mechanism.data=e}}const Zr=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/;function Qr(e){return parseInt(e||``,10)}function $r(e){let t=e.match(Zr)||[],n=Qr(t[1]),r=Qr(t[2]),i=Qr(t[3]);return{buildmetadata:t[5],major:isNaN(n)?void 0:n,minor:isNaN(r)?void 0:r,patch:isNaN(i)?void 0:i,prerelease:t[4]}}function ei(e){if(ti(e))return!0;try{Dr(e,`__sentry_captured__`,!0)}catch{}return!1}function ti(e){try{return e.__sentry_captured__}catch{}}const ni=1e3;function ri(){return Lr()/ni}function ii(){let{performance:e}=wn;if(!e?.now||!e.timeOrigin)return ri;let t=e.timeOrigin;return()=>(t+Fr(()=>e.now()))/ni}let ai;function oi(){return(ai??=ii())()}function si(e){let t=oi(),n={sid:Kr(),init:!0,timestamp:t,started:t,duration:0,status:`ok`,errors:0,ignoreDuration:!1,toJSON:()=>ui(n)};return e&&ci(n,e),n}function ci(e,t={}){if(t.user&&(!e.ipAddress&&t.user.ip_address&&(e.ipAddress=t.user.ip_address),!e.did&&!t.did&&(e.did=t.user.id||t.user.email||t.user.username)),e.timestamp=t.timestamp||oi(),t.abnormal_mechanism&&(e.abnormal_mechanism=t.abnormal_mechanism),t.ignoreDuration&&(e.ignoreDuration=t.ignoreDuration),t.sid&&(e.sid=t.sid.length===32?t.sid:Kr()),t.init!==void 0&&(e.init=t.init),!e.did&&t.did&&(e.did=`${t.did}`),typeof t.started==`number`&&(e.started=t.started),e.ignoreDuration)e.duration=void 0;else if(typeof t.duration==`number`)e.duration=t.duration;else{let t=e.timestamp-e.started;e.duration=t>=0?t:0}t.release&&(e.release=t.release),t.environment&&(e.environment=t.environment),!e.ipAddress&&t.ipAddress&&(e.ipAddress=t.ipAddress),!e.userAgent&&t.userAgent&&(e.userAgent=t.userAgent),typeof t.errors==`number`&&(e.errors=t.errors),t.status&&(e.status=t.status)}function li(e,t){let n={};t?n={status:t}:e.status===`ok`&&(n={status:`exited`}),ci(e,n)}function ui(e){return{sid:`${e.sid}`,init:e.init,started:new Date(e.started*1e3).toISOString(),timestamp:new Date(e.timestamp*1e3).toISOString(),status:e.status,errors:e.errors,did:typeof e.did==`number`||typeof e.did==`string`?`${e.did}`:void 0,duration:e.duration,abnormal_mechanism:e.abnormal_mechanism,attrs:{release:e.release,environment:e.environment,ip_address:e.ipAddress,user_agent:e.userAgent}}}function di(e,t,n=2){if(!t||typeof t!=`object`||n<=0)return t;if(e&&Object.keys(t).length===0)return e;let r={...e};for(let e in t)Object.prototype.hasOwnProperty.call(t,e)&&(r[e]=di(r[e],t[e],n-1));return r}function fi(){return Kr()}function pi(){return Kr().substring(16)}const mi=`_sentrySpan`;function hi(e,t){t?Dr(e,mi,t):delete e[mi]}function gi(e){return e[mi]}var _i=class e{constructor(){this._notifyingListeners=!1,this._scopeListeners=[],this._eventProcessors=[],this._breadcrumbs=[],this._attachments=[],this._user={},this._tags={},this._attributes={},this._extra={},this._contexts={},this._sdkProcessingMetadata={},this._propagationContext={traceId:fi(),sampleRand:Ir()}}clone(){let t=new e;return t._breadcrumbs=[...this._breadcrumbs],t._tags={...this._tags},t._attributes={...this._attributes},t._extra={...this._extra},t._contexts={...this._contexts},this._contexts.flags&&(t._contexts.flags={values:[...this._contexts.flags.values]}),t._user=this._user,t._level=this._level,t._session=this._session,t._transactionName=this._transactionName,t._fingerprint=this._fingerprint,t._eventProcessors=[...this._eventProcessors],t._attachments=[...this._attachments],t._sdkProcessingMetadata={...this._sdkProcessingMetadata},t._propagationContext={...this._propagationContext},t._client=this._client,t._lastEventId=this._lastEventId,t._conversationId=this._conversationId,hi(t,gi(this)),t}setClient(e){this._client=e}setLastEventId(e){this._lastEventId=e}getClient(){return this._client}lastEventId(){return this._lastEventId}addScopeListener(e){this._scopeListeners.push(e)}addEventProcessor(e){return this._eventProcessors.push(e),this}setUser(e){return this._user=e||{email:void 0,id:void 0,ip_address:void 0,username:void 0},this._session&&ci(this._session,{user:e}),this._notifyScopeListeners(),this}getUser(){return this._user}setConversationId(e){return this._conversationId=e||void 0,this._notifyScopeListeners(),this}setTags(e){return this._tags={...this._tags,...e},this._notifyScopeListeners(),this}setTag(e,t){return this.setTags({[e]:t})}setAttributes(e){return this._attributes={...this._attributes,...e},this._notifyScopeListeners(),this}setAttribute(e,t){return this.setAttributes({[e]:t})}removeAttribute(e){return e in this._attributes&&(delete this._attributes[e],this._notifyScopeListeners()),this}setExtras(e){return this._extra={...this._extra,...e},this._notifyScopeListeners(),this}setExtra(e,t){return this._extra={...this._extra,[e]:t},this._notifyScopeListeners(),this}setFingerprint(e){return this._fingerprint=e,this._notifyScopeListeners(),this}setLevel(e){return this._level=e,this._notifyScopeListeners(),this}setTransactionName(e){return this._transactionName=e,this._notifyScopeListeners(),this}setContext(e,t){return t===null?delete this._contexts[e]:this._contexts[e]=t,this._notifyScopeListeners(),this}setSession(e){return e?this._session=e:delete this._session,this._notifyScopeListeners(),this}getSession(){return this._session}update(t){if(!t)return this;let n=typeof t==`function`?t(this):t,{tags:r,attributes:i,extra:a,user:o,contexts:s,level:c,fingerprint:l=[],propagationContext:u,conversationId:d}=(n instanceof e?n.getScopeData():hr(n)?t:void 0)||{};return this._tags={...this._tags,...r},this._attributes={...this._attributes,...i},this._extra={...this._extra,...a},this._contexts={...this._contexts,...s},o&&Object.keys(o).length&&(this._user=o),c&&(this._level=c),l.length&&(this._fingerprint=l),u&&(this._propagationContext=u),d&&(this._conversationId=d),this}clear(){return this._breadcrumbs=[],this._tags={},this._attributes={},this._extra={},this._user={},this._contexts={},this._level=void 0,this._transactionName=void 0,this._fingerprint=void 0,this._session=void 0,this._conversationId=void 0,hi(this,void 0),this._attachments=[],this.setPropagationContext({traceId:fi(),sampleRand:Ir()}),this._notifyScopeListeners(),this}addBreadcrumb(e,t){let n=typeof t==`number`?t:100;if(n<=0)return this;let r={timestamp:ri(),...e,message:e.message?Rr(e.message,2048):e.message};return this._breadcrumbs.push(r),this._breadcrumbs.length>n&&(this._breadcrumbs=this._breadcrumbs.slice(-n),this._client?.recordDroppedEvent(`buffer_overflow`,`log_item`)),this._notifyScopeListeners(),this}getLastBreadcrumb(){return this._breadcrumbs[this._breadcrumbs.length-1]}clearBreadcrumbs(){return this._breadcrumbs=[],this._notifyScopeListeners(),this}addAttachment(e){return this._attachments.push(e),this}clearAttachments(){return this._attachments=[],this}getScopeData(){return{breadcrumbs:this._breadcrumbs,attachments:this._attachments,contexts:this._contexts,tags:this._tags,attributes:this._attributes,extra:this._extra,user:this._user,level:this._level,fingerprint:this._fingerprint||[],eventProcessors:this._eventProcessors,propagationContext:this._propagationContext,sdkProcessingMetadata:this._sdkProcessingMetadata,transactionName:this._transactionName,span:gi(this),conversationId:this._conversationId}}setSDKProcessingMetadata(e){return this._sdkProcessingMetadata=di(this._sdkProcessingMetadata,e,2),this}setPropagationContext(e){return this._propagationContext=e,this}getPropagationContext(){return this._propagationContext}captureException(e,t){let n=t?.event_id||Kr();if(!this._client)return Cn&&Bn.warn(`No client configured on scope - will not capture exception!`),n;let r=Error(`Sentry syntheticException`);return this._client.captureException(e,{originalException:e,syntheticException:r,...t,event_id:n},this),n}captureMessage(e,t,n){let r=n?.event_id||Kr();if(!this._client)return Cn&&Bn.warn(`No client configured on scope - will not capture message!`),r;let i=n?.syntheticException??Error(e);return this._client.captureMessage(e,t,{originalException:e,syntheticException:i,...n,event_id:r},this),r}captureEvent(e,t){let n=e.event_id||t?.event_id||Kr();return this._client?(this._client.captureEvent(e,{...t,event_id:n},this),n):(Cn&&Bn.warn(`No client configured on scope - will not capture event!`),n)}_notifyScopeListeners(){this._notifyingListeners||=(this._notifyingListeners=!0,this._scopeListeners.forEach(e=>{e(this)}),!1)}};function vi(){return On(`defaultCurrentScope`,()=>new _i)}function yi(){return On(`defaultIsolationScope`,()=>new _i)}const bi=e=>e instanceof Promise&&!e[xi],xi=Symbol(`chained PromiseLike`),Si=(e,t,n)=>{let r=e.then(e=>(t(e),e),e=>{throw n(e),e});return bi(r)&&bi(e)?r:Ci(e,r)},Ci=(e,t)=>{let n=!1;for(let r in e){if(r in t)continue;n=!0;let i=e[r];typeof i==`function`?Object.defineProperty(t,r,{value:(...t)=>i.apply(e,t),enumerable:!0,configurable:!0,writable:!0}):t[r]=i}return n&&Object.assign(t,{[xi]:!0}),t};var wi=class{constructor(e,t){let n;n=e||new _i;let r;r=t||new _i,this._stack=[{scope:n}],this._isolationScope=r}withScope(e){let t=this._pushScope(),n;try{n=e(t)}catch(e){throw this._popScope(),e}return yr(n)?Si(n,()=>this._popScope(),()=>this._popScope()):(this._popScope(),n)}getClient(){return this.getStackTop().client}getScope(){return this.getStackTop().scope}getIsolationScope(){return this._isolationScope}getStackTop(){return this._stack[this._stack.length-1]}_pushScope(){let e=this.getScope().clone();return this._stack.push({client:this.getClient(),scope:e}),e}_popScope(){return this._stack.length<=1?!1:!!this._stack.pop()}};function Ti(){let e=Dn(En());return e.stack=e.stack||new wi(vi(),yi())}function Ei(e){return Ti().withScope(e)}function Di(e,t){let n=Ti();return n.withScope(()=>(n.getStackTop().scope=e,t(e)))}function Oi(e){return Ti().withScope(()=>e(Ti().getIsolationScope()))}function ki(){return{withIsolationScope:Oi,withScope:Ei,withSetScope:Di,withSetIsolationScope:(e,t)=>Oi(t),getCurrentScope:()=>Ti().getScope(),getIsolationScope:()=>Ti().getIsolationScope()}}function Ai(e){let t=Dn(En());t.acs=e}function ji(e){let t=Dn(e);return t.acs?t.acs:ki()}function Mi(){return ji(En()).getCurrentScope()}function Ni(){return ji(En()).getIsolationScope()}function Pi(){return On(`globalScope`,()=>new _i)}function Fi(...e){let t=ji(En());if(e.length===2){let[n,r]=e;return n?t.withSetScope(n,r):t.withScope(r)}return t.withScope(e[0])}function Ii(...e){let t=ji(En());if(e.length===2){let[n,r]=e;return n?t.withSetIsolationScope(n,r):t.withIsolationScope(r)}return t.withIsolationScope(e[0])}function Li(){return Mi().getClient()}function Ri(e){let{traceId:t,parentSpanId:n,propagationSpanId:r}=e.getPropagationContext(),i={trace_id:t,span_id:r||pi()};return n&&(i.parent_span_id=n),i}function zi(e){if(e){if(typeof e==`object`&&`deref`in e&&typeof e.deref==`function`)try{return e.deref()}catch{return}return e}}function Bi(e){let t=e;return{scope:t._sentryScope,isolationScope:zi(t._sentryIsolationScope)}}function Vi(e){let t=Ui(e);if(!t)return;let n=Object.entries(t).reduce((e,[t,n])=>{if(t.startsWith(`sentry-`)){let r=t.slice(7);e[r]=n}return e},{});if(Object.keys(n).length>0)return n}function Hi(e){if(e)return Gi(Object.entries(e).reduce((e,[t,n])=>(n&&(e[`sentry-${t}`]=n),e),{}))}function Ui(e){if(!(!e||!fr(e)&&!Array.isArray(e)))return Array.isArray(e)?e.reduce((e,t)=>{let n=Wi(t);return Object.entries(n).forEach(([t,n])=>{e[t]=n}),e},{}):Wi(e)}function Wi(e){return e.split(`,`).map(e=>{let t=e.indexOf(`=`);return t===-1?[]:[e.slice(0,t),e.slice(t+1)].map(e=>{try{return decodeURIComponent(e.trim())}catch{return}})}).reduce((e,[t,n])=>(t&&n&&(e[t]=n),e),{})}function Gi(e){if(Object.keys(e).length!==0)return Object.entries(e).reduce((e,[t,n],r)=>{let i=`${encodeURIComponent(t)}=${encodeURIComponent(n)}`,a=r===0?i:`${e},${i}`;return a.length>8192?(Cn&&Bn.warn(`Not adding key: ${t} with val: ${n} to baggage header due to exceeding baggage size limits.`),e):a},``)}const Ki=/^o(\d+)\./,qi=/^(?:(\w+):)\/\/(?:(\w+)(?::(\w+)?)?@)((?:\[[:.%\w]+\]|[\w.-]+))(?::(\d+))?\/(.+)/;function Ji(e){return e===`http`||e===`https`}function Yi(e,t=!1){let{host:n,path:r,pass:i,port:a,projectId:o,protocol:s,publicKey:c}=e;return`${s}://${c}${t&&i?`:${i}`:``}@${n}${a?`:${a}`:``}/${r&&`${r}/`}${o}`}function Xi(e){let t=qi.exec(e);if(!t){jn(()=>{console.error(`Invalid Sentry Dsn: ${e}`)});return}let[n,r,i=``,a=``,o=``,s=``]=t.slice(1),c=``,l=s,u=l.split(`/`);if(u.length>1&&(c=u.slice(0,-1).join(`/`),l=u.pop()),l){let e=l.match(/^\d+/);e&&(l=e[0])}return Zi({host:a,pass:i,path:c,projectId:l,port:o,protocol:n,publicKey:r})}function Zi(e){return{protocol:e.protocol,publicKey:e.publicKey||``,pass:e.pass||``,host:e.host,port:e.port||``,path:e.path||``,projectId:e.projectId}}function Qi(e){if(!Cn)return!0;let{port:t,projectId:n,protocol:r}=e;return[`protocol`,`publicKey`,`host`,`projectId`].find(t=>e[t]?!1:(Bn.error(`Invalid Sentry Dsn: ${t} missing`),!0))?!1:n.match(/^\d+$/)?Ji(r)?t&&isNaN(parseInt(t,10))?(Bn.error(`Invalid Sentry Dsn: Invalid port ${t}`),!1):!0:(Bn.error(`Invalid Sentry Dsn: Invalid protocol ${r}`),!1):(Bn.error(`Invalid Sentry Dsn: Invalid projectId ${n}`),!1)}function $i(e){return e.match(Ki)?.[1]}function ea(e){let t=e.getOptions(),{host:n}=e.getDsn()||{},r;return t.orgId?r=String(t.orgId):n&&(r=$i(n)),r}function ta(e){let t=typeof e==`string`?Xi(e):Zi(e);if(!(!t||!Qi(t)))return t}function na(e){if(typeof e==`boolean`)return Number(e);let t=typeof e==`string`?parseFloat(e):e;if(!(typeof t!=`number`||isNaN(t)||t<0||t>1))return t}const ra=RegExp(`^[ \\t]*([0-9a-f]{32})?-?([0-9a-f]{16})?-?([01])?[ \\t]*$`);function ia(e){if(!e)return;let t=e.match(ra);if(!t)return;let n;return t[3]===`1`?n=!0:t[3]===`0`&&(n=!1),{traceId:t[1],parentSampled:n,parentSpanId:t[2]}}function aa(e,t){let n=ia(e),r=Vi(t);if(!n?.traceId)return{traceId:fi(),sampleRand:Ir()};let i=ca(n,r);r&&(r.sample_rand=i.toString());let{traceId:a,parentSpanId:o,parentSampled:s}=n;return{traceId:a,parentSpanId:o,sampled:s,dsc:r||{},sampleRand:i}}function oa(e=fi(),t=pi(),n){let r=``;return n!==void 0&&(r=n?`-1`:`-0`),`${e}-${t}${r}`}function sa(e=fi(),t=pi(),n){return`00-${e}-${t}-${n?`01`:`00`}`}function ca(e,t){let n=na(t?.sample_rand);if(n!==void 0)return n;let r=na(t?.sample_rate);return r&&e?.parentSampled!==void 0?e.parentSampled?Ir()*r:r+Ir()*(1-r):Ir()}function la(e,t){let n=ea(e);return t&&n&&t!==n?(Bn.log(`Won't continue trace because org IDs don't match (incoming baggage: ${t}, SDK options: ${n})`),!1):e.getOptions().strictTraceContinuation&&(t&&!n||!t&&n)?(Bn.log(`Starting a new trace because strict trace continuation is enabled but one org ID is missing (incoming baggage: ${t}, Sentry client: ${n})`),!1):!0}let ua=!1;function da(e){let{spanId:t,traceId:n,isRemote:r}=e.spanContext(),i=r?t:_a(e).parent_span_id,a=Bi(e).scope;return{parent_span_id:i,span_id:r?a?.getPropagationContext().propagationSpanId||pi():t,trace_id:n}}function fa(e){let{traceId:t,spanId:n}=e.spanContext();return oa(t,n,ba(e))}function pa(e){let{traceId:t,spanId:n}=e.spanContext();return sa(t,n,ba(e))}function ma(e){if(e&&e.length>0)return e.map(({context:{spanId:e,traceId:t,traceFlags:n,...r},attributes:i})=>({span_id:e,trace_id:t,sampled:n===1,attributes:i,...r}))}function ha(e){return typeof e==`number`?ga(e):Array.isArray(e)?e[0]+e[1]/1e9:e instanceof Date?ga(e.getTime()):oi()}function ga(e){return e>9999999999?e/1e3:e}function _a(e){if(ya(e))return e.getSpanJSON();let{spanId:t,traceId:n}=e.spanContext();if(va(e)){let{attributes:r,startTime:i,name:a,endTime:o,status:s,links:c}=e;return{span_id:t,trace_id:n,data:r,description:a,parent_span_id:`parentSpanId`in e?e.parentSpanId:`parentSpanContext`in e?e.parentSpanContext?.spanId:void 0,start_timestamp:ha(i),timestamp:ha(o)||void 0,status:xa(s),op:r[`sentry.op`],origin:r[`sentry.origin`],links:ma(c)}}return{span_id:t,trace_id:n,start_timestamp:0,data:{}}}function va(e){let t=e;return!!t.attributes&&!!t.startTime&&!!t.name&&!!t.endTime&&!!t.status}function ya(e){return typeof e.getSpanJSON==`function`}function ba(e){let{traceFlags:t}=e.spanContext();return t===1}function xa(e){if(!(!e||e.code===0))return e.code===1?`ok`:e.message||`internal_error`}function Sa(e){return e._sentryRootSpan||e}function Ca(){let e=ji(En());return e.getActiveSpan?e.getActiveSpan():gi(Mi())}function wa(){ua||=(jn(()=>{console.warn("[Sentry] Returning null from `beforeSendSpan` is disallowed. To drop certain spans, configure the respective integrations directly or use `ignoreSpans`.")}),!0)}let Ta=!1;function Ea(){if(Ta)return;function e(){let e=Ca(),t=e&&Sa(e);if(t){let e=`internal_error`;Cn&&Bn.log(`[Tracing] Root span: ${e} -> Global error occurred`),t.setStatus({code:2,message:e})}}e.tag=`sentry_tracingErrorCallback`,Ta=!0,rr(e),or(e)}function Da(e){if(typeof __SENTRY_TRACING__==`boolean`&&!__SENTRY_TRACING__)return!1;let t=e||Li()?.getOptions();return!!t&&(t.tracesSampleRate!=null||!!t.tracesSampler)}function Oa(e){Bn.log(`Ignoring span ${e.op} - ${e.description} because it matches \`ignoreSpans\`.`)}function ka(e,t){if(!t?.length||!e.description)return!1;for(let n of t){if(ja(n)){if(Vr(e.description,n))return Cn&&Oa(e),!0;continue}if(!n.name&&!n.op)continue;let t=n.name?Vr(e.description,n.name):!0,r=n.op?e.op&&Vr(e.op,n.op):!0;if(t&&r)return Cn&&Oa(e),!0}return!1}function Aa(e,t){let n=t.parent_span_id,r=t.span_id;if(n)for(let t of e)t.parent_span_id===r&&(t.parent_span_id=n)}function ja(e){return typeof e==`string`||e instanceof RegExp}function Ma(e,t){let n=t.getOptions(),{publicKey:r}=t.getDsn()||{},i={environment:n.environment||`production`,release:n.release,public_key:r,trace_id:e,org_id:ea(t)};return t.emit(`createDsc`,i),i}function Na(e,t){let n=t.getPropagationContext();return n.dsc||Ma(n.traceId,e)}function Pa(e){let t=Li();if(!t)return{};let n=Sa(e),r=_a(n),i=r.data,a=n.spanContext().traceState,o=a?.get(`sentry.sample_rate`)??i[`sentry.sample_rate`]??i[`sentry.previous_trace_sample_rate`];function s(e){return(typeof o==`number`||typeof o==`string`)&&(e.sample_rate=`${o}`),e}let c=n._frozenDsc;if(c)return s(c);let l=a?.get(`sentry.dsc`),u=l&&Vi(l);if(u)return s(u);let d=Ma(e.spanContext().traceId,t),f=i[`sentry.source`],p=r.description;return f!==`url`&&p&&(d.transaction=p),Da()&&(d.sampled=String(ba(n)),d.sample_rand=a?.get(`sentry.sample_rand`)??Bi(n).scope?.getPropagationContext().sampleRand.toString()),s(d),t.emit(`createDsc`,d,n),d}function Fa(e,t=100,n=1/0){try{return La(``,e,t,n)}catch(e){return{ERROR:`**non-serializable** (${e})`}}}function Ia(e,t=3,n=100*1024){let r=Fa(e,t);return Va(r)>n?Ia(e,t-1,n):r}function La(e,t,n=1/0,r=1/0,i=Ha()){let[a,o]=i;if(t==null||[`boolean`,`string`].includes(typeof t)||typeof t==`number`&&Number.isFinite(t))return t;let s=Ra(e,t);if(!s.startsWith(`[object `))return s;if(t.__sentry_skip_normalization__)return t;let c=typeof t.__sentry_override_normalization_depth__==`number`?t.__sentry_override_normalization_depth__:n;if(c===0)return s.replace(`object `,``);if(a(t))return`[Circular ~]`;let l=t;if(l&&typeof l.toJSON==`function`)try{return La(``,l.toJSON(),c-1,r,i)}catch{}let u=Array.isArray(t)?[]:{},d=0,f=Ar(t);for(let e in f){if(!Object.prototype.hasOwnProperty.call(f,e))continue;if(d>=r){u[e]=`[MaxProperties ~]`;break}let t=f[e];u[e]=La(e,t,c-1,r,i),d++}return o(t),u}function Ra(e,t){try{if(e===`domain`&&t&&typeof t==`object`&&t._events)return`[Domain]`;if(e===`domainEmitter`)return`[DomainEmitter]`;if(typeof global<`u`&&t===global)return`[Global]`;if(typeof window<`u`&&t===window)return`[Window]`;if(typeof document<`u`&&t===document)return`[Document]`;if(Sr(t))return Yn(t);if(br(t))return`[SyntheticEvent]`;if(typeof t==`number`&&!Number.isFinite(t))return`[${t}]`;if(typeof t==`function`)return`[Function: ${Jn(t)}]`;if(typeof t==`symbol`)return`[${String(t)}]`;if(typeof t==`bigint`)return`[BigInt: ${String(t)}]`;let n=za(t);return/^HTML(\w*)Element$/.test(n)?`[HTMLElement: ${n}]`:`[object ${n}]`}catch(e){return`**non-serializable** (${e})`}}function za(e){let t=Object.getPrototypeOf(e);return t?.constructor?t.constructor.name:`null prototype`}function Ba(e){return~-encodeURI(e).split(/%..|./).length}function Va(e){return Ba(JSON.stringify(e))}function Ha(){let e=new WeakSet;function t(t){return e.has(t)?!0:(e.add(t),!1)}function n(t){e.delete(t)}return[t,n]}function Ua(e,t=[]){return[e,t]}function Wa(e,t){let[n,r]=e;return[n,[...r,t]]}function Ga(e,t){let n=e[1];for(let e of n){let n=e[0].type;if(t(e,n))return!0}return!1}function Ka(e,t){return Ga(e,(e,n)=>t.includes(n))}function qa(e){let t=Dn(wn);return t.encodePolyfill?t.encodePolyfill(e):new TextEncoder().encode(e)}function Ja(e){let[t,n]=e,r=JSON.stringify(t);function i(e){typeof r==`string`?r=typeof e==`string`?r+e:[qa(r),e]:r.push(typeof e==`string`?qa(e):e)}for(let e of n){let[t,n]=e;if(i(`\n${JSON.stringify(t)}\n`),typeof n==`string`||n instanceof Uint8Array)i(n);else{let e;try{e=JSON.stringify(n)}catch{e=JSON.stringify(Fa(n))}i(e)}}return typeof r==`string`?r:Ya(r)}function Ya(e){let t=e.reduce((e,t)=>e+t.length,0),n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}function Xa(e){let t=typeof e.data==`string`?qa(e.data):e.data;return[{type:`attachment`,length:t.length,filename:e.filename,content_type:e.contentType,attachment_type:e.attachmentType},t]}const Za={sessions:`session`,event:`error`,client_report:`internal`,user_report:`default`,profile_chunk:`profile`,replay_event:`replay`,replay_recording:`replay`,check_in:`monitor`,raw_security:`security`,log:`log_item`,trace_metric:`metric`};function Qa(e){return e in Za}function $a(e){return Qa(e)?Za[e]:e}function eo(e){if(!e?.sdk)return;let{name:t,version:n}=e.sdk;return{name:t,version:n}}function to(e,t,n,r){let i=e.sdkProcessingMetadata?.dynamicSamplingContext;return{event_id:e.event_id,sent_at:new Date().toISOString(),...t&&{sdk:t},...!!n&&r&&{dsn:Yi(r)},...i&&{trace:i}}}function no(e,t){if(!t)return e;let n=e.sdk||{};return e.sdk={...n,name:n.name||t.name,version:n.version||t.version,integrations:[...e.sdk?.integrations||[],...t.integrations||[]],packages:[...e.sdk?.packages||[],...t.packages||[]],settings:e.sdk?.settings||t.settings?{...e.sdk?.settings,...t.settings}:void 0},e}function ro(e,t,n,r){let i=eo(n);return Ua({sent_at:new Date().toISOString(),...i&&{sdk:i},...!!r&&t&&{dsn:Yi(t)}},[`aggregates`in e?[{type:`sessions`},e]:[{type:`session`},e.toJSON()]])}function io(e,t,n,r){let i=eo(n),a=e.type&&e.type!==`replay_event`?e.type:`event`;no(e,n?.sdk);let o=to(e,i,r,t);return delete e.sdkProcessingMetadata,Ua(o,[[{type:a},e]])}const ao=`__SENTRY_SUPPRESS_TRACING__`,oo=(e,t)=>{let n=ji(En());if(n.continueTrace)return n.continueTrace(e,t);let{sentryTrace:r,baggage:i}=e,a=Li(),o=Vi(i);return a&&!la(a,o?.org_id)?lo(t):Fi(e=>{let n=aa(r,i);return e.setPropagationContext(n),hi(e,void 0),t()})};function so(e,t){let n=uo();return n.withActiveSpan?n.withActiveSpan(e,t):Fi(n=>(hi(n,e||void 0),t(n)))}function co(e){let t=uo();return t.suppressTracing?t.suppressTracing(e):Fi(t=>{t.setSDKProcessingMetadata({[ao]:!0});let n=e();return t.setSDKProcessingMetadata({[ao]:void 0}),n})}function lo(e){return Fi(t=>(t.setPropagationContext({traceId:fi(),sampleRand:Ir()}),Cn&&Bn.log(`Starting a new trace with id ${t.getPropagationContext().traceId}`),so(null,e)))}function uo(){return ji(En())}function fo(e){return new mo(t=>{t(e)})}function po(e){return new mo((t,n)=>{n(e)})}var mo=class e{constructor(e){this._state=0,this._handlers=[],this._runExecutor(e)}then(t,n){return new e((e,r)=>{this._handlers.push([!1,n=>{if(!t)e(n);else try{e(t(n))}catch(e){r(e)}},t=>{if(!n)r(t);else try{e(n(t))}catch(e){r(e)}}]),this._executeHandlers()})}catch(e){return this.then(e=>e,e)}finally(t){return new e((e,n)=>{let r,i;return this.then(e=>{i=!1,r=e,t&&t()},e=>{i=!0,r=e,t&&t()}).then(()=>{if(i){n(r);return}e(r)})})}_executeHandlers(){if(this._state===0)return;let e=this._handlers.slice();this._handlers=[],e.forEach(e=>{e[0]||=(this._state===1&&e[1](this._value),this._state===2&&e[2](this._value),!0)})}_runExecutor(e){let t=(e,t)=>{if(this._state===0){if(yr(t)){t.then(n,r);return}this._state=e,this._value=t,this._executeHandlers()}},n=e=>{t(1,e)},r=e=>{t(2,e)};try{e(n,r)}catch(e){r(e)}}};function ho(e,t,n,r=0){try{let i=go(t,n,e,r);return yr(i)?i:fo(i)}catch(e){return po(e)}}function go(e,t,n,r){let i=n[r];if(!e||!i)return e;let a=i({...e},t);return Cn&&a===null&&Bn.log(`Event processor "${i.id||`?`}" dropped event`),yr(a)?a.then(e=>go(e,t,n,r+1)):go(a,t,n,r+1)}let _o,vo,yo,bo;function xo(e){let t=wn._sentryDebugIds,n=wn._debugIds;if(!t&&!n)return{};let r=t?Object.keys(t):[],i=n?Object.keys(n):[];if(bo&&r.length===vo&&i.length===yo)return bo;vo=r.length,yo=i.length,bo={},_o||={};let a=(t,n)=>{for(let r of t){let t=n[r],i=_o?.[r];if(i&&bo&&t)bo[i[0]]=t,_o&&(_o[r]=[i[0],t]);else if(t){let n=e(r);for(let e=n.length-1;e>=0;e--){let i=n[e]?.filename;if(i&&bo&&_o){bo[i]=t,_o[r]=[i,t];break}}}}};return t&&a(r,t),n&&a(i,n),bo}function So(e,t){let{fingerprint:n,span:r,breadcrumbs:i,sdkProcessingMetadata:a}=t;Eo(e,t),r&&ko(e,r),Ao(e,n),Do(e,i),Oo(e,a)}function Co(e,t){let{extra:n,tags:r,attributes:i,user:a,contexts:o,level:s,sdkProcessingMetadata:c,breadcrumbs:l,fingerprint:u,eventProcessors:d,attachments:f,propagationContext:p,transactionName:m,span:h}=t;wo(e,`extra`,n),wo(e,`tags`,r),wo(e,`attributes`,i),wo(e,`user`,a),wo(e,`contexts`,o),e.sdkProcessingMetadata=di(e.sdkProcessingMetadata,c,2),s&&(e.level=s),m&&(e.transactionName=m),h&&(e.span=h),l.length&&(e.breadcrumbs=[...e.breadcrumbs,...l]),u.length&&(e.fingerprint=[...e.fingerprint,...u]),d.length&&(e.eventProcessors=[...e.eventProcessors,...d]),f.length&&(e.attachments=[...e.attachments,...f]),e.propagationContext={...e.propagationContext,...p}}function wo(e,t,n){e[t]=di(e[t],n,1)}function To(e,t){let n=Pi().getScopeData();return e&&Co(n,e.getScopeData()),t&&Co(n,t.getScopeData()),n}function Eo(e,t){let{extra:n,tags:r,user:i,contexts:a,level:o,transactionName:s}=t;Object.keys(n).length&&(e.extra={...n,...e.extra}),Object.keys(r).length&&(e.tags={...r,...e.tags}),Object.keys(i).length&&(e.user={...i,...e.user}),Object.keys(a).length&&(e.contexts={...a,...e.contexts}),o&&(e.level=o),s&&e.type!==`transaction`&&(e.transaction=s)}function Do(e,t){let n=[...e.breadcrumbs||[],...t];e.breadcrumbs=n.length?n:void 0}function Oo(e,t){e.sdkProcessingMetadata={...e.sdkProcessingMetadata,...t}}function ko(e,t){e.contexts={trace:da(t),...e.contexts},e.sdkProcessingMetadata={dynamicSamplingContext:Pa(t),...e.sdkProcessingMetadata};let n=_a(Sa(t)).description;n&&!e.transaction&&e.type===`transaction`&&(e.transaction=n)}function Ao(e,t){e.fingerprint=e.fingerprint?Array.isArray(e.fingerprint)?e.fingerprint:[e.fingerprint]:[],t&&(e.fingerprint=e.fingerprint.concat(t)),e.fingerprint.length||delete e.fingerprint}function jo(e,t,n,r,i,a){let{normalizeDepth:o=3,normalizeMaxBreadth:s=1e3}=e,c={...t,event_id:t.event_id||n.event_id||Kr(),timestamp:t.timestamp||ri()},l=n.integrations||e.integrations.map(e=>e.name);Mo(c,e),Fo(c,l),i&&i.emit(`applyFrameMetadata`,t),t.type===void 0&&No(c,e.stackParser);let u=Lo(r,n.captureContext);n.mechanism&&Xr(c,n.mechanism);let d=i?i.getEventProcessors():[],f=To(a,u),p=[...n.attachments||[],...f.attachments];p.length&&(n.attachments=p),So(c,f);let m=[...d,...f.eventProcessors];return(n.data&&n.data.__sentry__===!0?fo(c):ho(m,c,n)).then(e=>(e&&Po(e),typeof o==`number`&&o>0?Io(e,o,s):e))}function Mo(e,t){let{environment:n,release:r,dist:i,maxValueLength:a}=t;e.environment=e.environment||n||`production`,!e.release&&r&&(e.release=r),!e.dist&&i&&(e.dist=i);let o=e.request;o?.url&&a&&(o.url=Rr(o.url,a)),a&&e.exception?.values?.forEach(e=>{e.value&&=Rr(e.value,a)})}function No(e,t){let n=xo(t);e.exception?.values?.forEach(e=>{e.stacktrace?.frames?.forEach(e=>{e.filename&&(e.debug_id=n[e.filename])})})}function Po(e){let t={};if(e.exception?.values?.forEach(e=>{e.stacktrace?.frames?.forEach(e=>{e.debug_id&&(e.abs_path?t[e.abs_path]=e.debug_id:e.filename&&(t[e.filename]=e.debug_id),delete e.debug_id)})}),Object.keys(t).length===0)return;e.debug_meta=e.debug_meta||{},e.debug_meta.images=e.debug_meta.images||[];let n=e.debug_meta.images;Object.entries(t).forEach(([e,t])=>{n.push({type:`sourcemap`,code_file:e,debug_id:t})})}function Fo(e,t){t.length>0&&(e.sdk=e.sdk||{},e.sdk.integrations=[...e.sdk.integrations||[],...t])}function Io(e,t,n){if(!e)return null;let r={...e,...e.breadcrumbs&&{breadcrumbs:e.breadcrumbs.map(e=>({...e,...e.data&&{data:Fa(e.data,t,n)}}))},...e.user&&{user:Fa(e.user,t,n)},...e.contexts&&{contexts:Fa(e.contexts,t,n)},...e.extra&&{extra:Fa(e.extra,t,n)}};return e.contexts?.trace&&r.contexts&&(r.contexts.trace=e.contexts.trace,e.contexts.trace.data&&(r.contexts.trace.data=Fa(e.contexts.trace.data,t,n))),e.spans&&(r.spans=e.spans.map(e=>({...e,...e.data&&{data:Fa(e.data,t,n)}}))),e.contexts?.flags&&r.contexts&&(r.contexts.flags=Fa(e.contexts.flags,3,n)),r}function Lo(e,t){if(!t)return e;let n=e?e.clone():new _i;return n.update(t),n}function Ro(e){if(e)return zo(e)||Vo(e)?{captureContext:e}:e}function zo(e){return e instanceof _i||typeof e==`function`}const Bo=[`user`,`level`,`extra`,`contexts`,`tags`,`fingerprint`,`propagationContext`];function Vo(e){return Object.keys(e).some(e=>Bo.includes(e))}function Ho(e,t){return Mi().captureException(e,Ro(t))}function Uo(e,t){let n=typeof t==`string`?t:void 0,r=typeof t==`string`?void 0:{captureContext:t};return Mi().captureMessage(e,n,r)}function Wo(e,t){Ni().setTag(e,t)}function Go(){let e=Li();return e?.getOptions().enabled!==!1&&!!e?.getTransport()}function Ko(e){let t=Ni(),{user:n}=To(t,Mi()),{userAgent:r}=wn.navigator||{},i=si({user:n,...r&&{userAgent:r},...e}),a=t.getSession();return a?.status===`ok`&&ci(a,{status:`exited`}),qo(),t.setSession(i),i}function qo(){let e=Ni(),t=Mi().getSession()||e.getSession();t&&li(t),Jo(),e.setSession()}function Jo(){let e=Ni(),t=Li(),n=e.getSession();n&&t&&t.captureSession(n)}function Yo(e){let t=e.protocol?`${e.protocol}:`:``,n=e.port?`:${e.port}`:``;return`${t}//${e.host}${n}${e.path?`/${e.path}`:``}/api/`}function Xo(e){return`${Yo(e)}${e.projectId}/envelope/`}function Zo(e,t){let n={sentry_version:`7`};return e.publicKey&&(n.sentry_key=e.publicKey),t&&(n.sentry_client=`${t.name}/${t.version}`),new URLSearchParams(n).toString()}function Qo(e,t,n){return t||`${Xo(e)}?${Zo(e,n)}`}const $o=[];function es(e){let t={};return e.forEach(e=>{let{name:n}=e,r=t[n];r&&!r.isDefaultInstance&&e.isDefaultInstance||(t[n]=e)}),Object.values(t)}function ts(e){let t=e.defaultIntegrations||[],n=e.integrations;t.forEach(e=>{e.isDefaultInstance=!0});let r;if(Array.isArray(n))r=[...t,...n];else if(typeof n==`function`){let e=n(t);r=Array.isArray(e)?e:[e]}else r=t;return es(r)}function ns(e,t){let n={};return t.forEach(t=>{t&&is(e,t,n)}),n}function rs(e,t){for(let n of t)n?.afterAllSetup&&n.afterAllSetup(e)}function is(e,t,n){if(n[t.name]){Cn&&Bn.log(`Integration skipped because it was already installed: ${t.name}`);return}if(n[t.name]=t,!$o.includes(t.name)&&typeof t.setupOnce==`function`&&(t.setupOnce(),$o.push(t.name)),t.setup&&typeof t.setup==`function`&&t.setup(e),typeof t.preprocessEvent==`function`){let n=t.preprocessEvent.bind(t);e.on(`preprocessEvent`,(t,r)=>n(t,r,e))}if(typeof t.processEvent==`function`){let n=t.processEvent.bind(t),r=Object.assign((t,r)=>n(t,r,e),{id:t.name});e.addEventProcessor(r)}Cn&&Bn.log(`Integration installed: ${t.name}`)}function as(e){return e}function os(e,t){return t?Fi(t,()=>{let n=Ca(),r=n?da(n):Ri(t);return[n?Pa(n):Na(e,t),r]}):[void 0,void 0]}function ss(e){return[{type:`log`,item_count:e.length,content_type:`application/vnd.sentry.items.log+json`},{items:e}]}function cs(e,t,n,r){let i={};return t?.sdk&&(i.sdk={name:t.sdk.name,version:t.sdk.version}),n&&r&&(i.dsn=Yi(r)),Ua(i,[ss(e)])}function ls(e,t){let n=t??us(e)??[];if(n.length===0)return;let r=e.getOptions(),i=cs(n,r._metadata,r.tunnel,e.getDsn());ds().set(e,[]),e.emit(`flushLogs`),e.sendEnvelope(i)}function us(e){return ds().get(e)}function ds(){return On(`clientToLogBufferMap`,()=>new WeakMap)}function fs(e){return[{type:`trace_metric`,item_count:e.length,content_type:`application/vnd.sentry.items.trace-metric+json`},{items:e}]}function ps(e,t,n,r){let i={};return t?.sdk&&(i.sdk={name:t.sdk.name,version:t.sdk.version}),n&&r&&(i.dsn=Yi(r)),Ua(i,[fs(e)])}function ms(e,t){let n=t??hs(e)??[];if(n.length===0)return;let r=e.getOptions(),i=ps(n,r._metadata,r.tunnel,e.getDsn());gs().set(e,[]),e.emit(`flushMetrics`),e.sendEnvelope(i)}function hs(e){return gs().get(e)}function gs(){return On(`clientToMetricBufferMap`,()=>new WeakMap)}function _s(e){return typeof e==`object`&&typeof e.unref==`function`&&e.unref(),e}const vs=Symbol.for(`SentryBufferFullError`);function ys(e=100){let t=new Set;function n(){return t.size<e}function r(e){t.delete(e)}function i(e){if(!n())return po(vs);let i=e();return t.add(i),i.then(()=>r(i),()=>r(i)),i}function a(e){if(!t.size)return fo(!0);let n=Promise.allSettled(Array.from(t)).then(()=>!0);if(!e)return n;let r=[n,new Promise(t=>_s(setTimeout(()=>t(!1),e)))];return Promise.race(r)}return{get $(){return Array.from(t)},add:i,drain:a}}function bs(e,t=Lr()){let n=parseInt(`${e}`,10);if(!isNaN(n))return n*1e3;let r=Date.parse(`${e}`);return isNaN(r)?6e4:r-t}function xs(e,t){return e[t]||e.all||0}function Ss(e,t,n=Lr()){return xs(e,t)>n}function Cs(e,{statusCode:t,headers:n},r=Lr()){let i={...e},a=n?.[`x-sentry-rate-limits`],o=n?.[`retry-after`];if(a)for(let e of a.trim().split(`,`)){let[t,n,,,a]=e.split(`:`,5),o=parseInt(t,10),s=(isNaN(o)?60:o)*1e3;if(!n)i.all=r+s;else for(let e of n.split(`;`))e===`metric_bucket`?(!a||a.split(`;`).includes(`custom`))&&(i[e]=r+s):i[e]=r+s}else o?i.all=r+bs(o,r):t===429&&(i.all=r+60*1e3);return i}function ws(e,t,n=ys(e.bufferSize||64)){let r={},i=e=>n.drain(e);function a(i){let a=[];if(Ga(i,(t,n)=>{let i=$a(n);Ss(r,i)?e.recordDroppedEvent(`ratelimit_backoff`,i):a.push(t)}),a.length===0)return Promise.resolve({});let o=Ua(i[0],a),s=t=>{if(Ka(o,[`client_report`])){Cn&&Bn.warn(`Dropping client report. Will not send outcomes (reason: ${t}).`);return}Ga(o,(n,r)=>{e.recordDroppedEvent(t,$a(r))})};return n.add(()=>t({body:Ja(o)}).then(e=>e.statusCode===413?(Cn&&Bn.error(`Sentry responded with status code 413. Envelope was discarded due to exceeding size limits.`),s(`send_error`),e):(Cn&&e.statusCode!==void 0&&(e.statusCode<200||e.statusCode>=300)&&Bn.warn(`Sentry responded with status code ${e.statusCode} to sent event.`),r=Cs(r,e),e),e=>{throw s(`network_error`),Cn&&Bn.error(`Encountered error running transport request:`,e),e})).then(e=>e,e=>{if(e===vs)return Cn&&Bn.error(`Skipped sending event because buffer is full.`),s(`queue_overflow`),Promise.resolve({});throw e})}return{send:a,flush:i}}function Ts(e,t,n){let r=[{type:`client_report`},{timestamp:n||ri(),discarded_events:e}];return Ua(t?{dsn:t}:{},[r])}function Es(e){let t=[];e.message&&t.push(e.message);try{let n=e.exception.values[e.exception.values.length-1];n?.value&&(t.push(n.value),n.type&&t.push(`${n.type}: ${n.value}`))}catch{}return t}function Ds(e){let{trace_id:t,parent_span_id:n,span_id:r,status:i,origin:a,data:o,op:s}=e.contexts?.trace??{};return{data:o??{},description:e.transaction,op:s,parent_span_id:n,span_id:r??``,start_timestamp:e.start_timestamp??0,status:i,timestamp:e.timestamp,trace_id:t??``,origin:a,profile_id:o?.[`sentry.profile_id`],exclusive_time:o?.[`sentry.exclusive_time`],measurements:e.measurements,is_segment:!0}}function Os(e){return{type:`transaction`,timestamp:e.timestamp,start_timestamp:e.start_timestamp,transaction:e.description,contexts:{trace:{trace_id:e.trace_id,span_id:e.span_id,parent_span_id:e.parent_span_id,op:e.op,status:e.status,origin:e.origin,data:{...e.data,...e.profile_id&&{"sentry.profile_id":e.profile_id},...e.exclusive_time&&{"sentry.exclusive_time":e.exclusive_time}}}},measurements:e.measurements}}const ks=`Not capturing exception because it's already been captured.`,As=`Discarded session because of missing or non-string release`,js=Symbol.for(`SentryInternalError`),Ms=Symbol.for(`SentryDoNotSendEventError`);function Ns(e){return{message:e,[js]:!0}}function Ps(e){return{message:e,[Ms]:!0}}function Fs(e){return!!e&&typeof e==`object`&&js in e}function Is(e){return!!e&&typeof e==`object`&&Ms in e}function Ls(e,t,n,r,i){let a=0,o,s=!1;e.on(n,()=>{a=0,clearTimeout(o),s=!1}),e.on(t,t=>{a+=r(t),a>=8e5?i(e):s||(s=!0,o=_s(setTimeout(()=>{i(e)},5e3)))}),e.on(`flush`,()=>{i(e)})}var Rs=class{constructor(e){if(this._options=e,this._integrations={},this._numProcessing=0,this._outcomes={},this._hooks={},this._eventProcessors=[],this._promiseBuffer=ys(e.transportOptions?.bufferSize??64),e.dsn?this._dsn=ta(e.dsn):Cn&&Bn.warn(`No DSN provided, client will not send events.`),this._dsn){let t=Qo(this._dsn,e.tunnel,e._metadata?e._metadata.sdk:void 0);this._transport=e.transport({tunnel:this._options.tunnel,recordDroppedEvent:this.recordDroppedEvent.bind(this),...e.transportOptions,url:t})}this._options.enableLogs=this._options.enableLogs??this._options._experiments?.enableLogs,this._options.enableLogs&&Ls(this,`afterCaptureLog`,`flushLogs`,Gs,ls),(this._options.enableMetrics??this._options._experiments?.enableMetrics??!0)&&Ls(this,`afterCaptureMetric`,`flushMetrics`,Ws,ms)}captureException(e,t,n){let r=Kr();if(ei(e))return Cn&&Bn.log(ks),r;let i={event_id:r,...t};return this._process(()=>this.eventFromException(e,i).then(e=>this._captureEvent(e,i,n)).then(e=>e),`error`),i.event_id}captureMessage(e,t,n,r){let i={event_id:Kr(),...n},a=pr(e)?e:String(e),o=mr(e),s=o?this.eventFromMessage(a,t,i):this.eventFromException(e,i);return this._process(()=>s.then(e=>this._captureEvent(e,i,r)),o?`unknown`:`error`),i.event_id}captureEvent(e,t,n){let r=Kr();if(t?.originalException&&ei(t.originalException))return Cn&&Bn.log(ks),r;let i={event_id:r,...t},a=e.sdkProcessingMetadata||{},o=a.capturedSpanScope,s=a.capturedSpanIsolationScope,c=zs(e.type);return this._process(()=>this._captureEvent(e,i,o||n,s),c),i.event_id}captureSession(e){this.sendSession(e),ci(e,{init:!1})}getDsn(){return this._dsn}getOptions(){return this._options}getSdkMetadata(){return this._options._metadata}getTransport(){return this._transport}async flush(e){let t=this._transport;if(!t)return!0;this.emit(`flush`);let n=await this._isClientDoneProcessing(e),r=await t.flush(e);return n&&r}async close(e){ls(this);let t=await this.flush(e);return this.getOptions().enabled=!1,this.emit(`close`),t}getEventProcessors(){return this._eventProcessors}addEventProcessor(e){this._eventProcessors.push(e)}init(){(this._isEnabled()||this._options.integrations.some(({name:e})=>e.startsWith(`Spotlight`)))&&this._setupIntegrations()}getIntegrationByName(e){return this._integrations[e]}addIntegration(e){let t=this._integrations[e.name];is(this,e,this._integrations),t||rs(this,[e])}sendEvent(e,t={}){this.emit(`beforeSendEvent`,e,t);let n=io(e,this._dsn,this._options._metadata,this._options.tunnel);for(let e of t.attachments||[])n=Wa(n,Xa(e));this.sendEnvelope(n).then(t=>this.emit(`afterSendEvent`,e,t))}sendSession(e){let{release:t,environment:n=`production`}=this._options;if(`aggregates`in e){let r=e.attrs||{};if(!r.release&&!t){Cn&&Bn.warn(As);return}r.release=r.release||t,r.environment=r.environment||n,e.attrs=r}else{if(!e.release&&!t){Cn&&Bn.warn(As);return}e.release=e.release||t,e.environment=e.environment||n}this.emit(`beforeSendSession`,e);let r=ro(e,this._dsn,this._options._metadata,this._options.tunnel);this.sendEnvelope(r)}recordDroppedEvent(e,t,n=1){if(this._options.sendClientReports){let r=`${e}:${t}`;Cn&&Bn.log(`Recording outcome: "${r}"${n>1?` (${n} times)`:``}`),this._outcomes[r]=(this._outcomes[r]||0)+n}}on(e,t){let n=this._hooks[e]=this._hooks[e]||new Set,r=(...e)=>t(...e);return n.add(r),()=>{n.delete(r)}}emit(e,...t){let n=this._hooks[e];n&&n.forEach(e=>e(...t))}async sendEnvelope(e){if(this.emit(`beforeEnvelope`,e),this._isEnabled()&&this._transport)try{return await this._transport.send(e)}catch(e){return Cn&&Bn.error(`Error while sending envelope:`,e),{}}return Cn&&Bn.error(`Transport disabled`),{}}dispose(){}_setupIntegrations(){let{integrations:e}=this._options;this._integrations=ns(this,e),rs(this,e)}_updateSessionFromEvent(e,t){let n=t.level===`fatal`,r=!1,i=t.exception?.values;if(i){r=!0,n=!1;for(let e of i)if(e.mechanism?.handled===!1){n=!0;break}}let a=e.status===`ok`;(a&&e.errors===0||a&&n)&&(ci(e,{...n&&{status:`crashed`},errors:e.errors||Number(r||n)}),this.captureSession(e))}async _isClientDoneProcessing(e){let t=0;for(;!e||t<e;){if(await new Promise(e=>setTimeout(e,1)),!this._numProcessing)return!0;t++}return!1}_isEnabled(){return this.getOptions().enabled!==!1&&this._transport!==void 0}_prepareEvent(e,t,n,r){let i=this.getOptions(),a=Object.keys(this._integrations);return!t.integrations&&a?.length&&(t.integrations=a),this.emit(`preprocessEvent`,e,t),e.type||r.setLastEventId(e.event_id||t.event_id),jo(i,e,t,n,this,r).then(e=>e===null?e:(this.emit(`postprocessEvent`,e,t),e.contexts={trace:{...e.contexts?.trace,...Ri(n)},...e.contexts},e.sdkProcessingMetadata={dynamicSamplingContext:Na(this,n),...e.sdkProcessingMetadata},e))}_captureEvent(e,t={},n=Mi(),r=Ni()){return Cn&&Hs(e)&&Bn.log(`Captured error event \`${Es(e)[0]||`<unknown>`}\``),this._processEvent(e,t,n,r).then(e=>e.event_id,e=>{Cn&&(Is(e)?Bn.log(e.message):Fs(e)?Bn.warn(e.message):Bn.warn(e))})}_processEvent(e,t,n,r){let i=this.getOptions(),{sampleRate:a}=i,o=Us(e),s=Hs(e),c=`before send for type \`${e.type||`error`}\``,l=a===void 0?void 0:na(a);if(s&&typeof l==`number`&&Ir()>l)return this.recordDroppedEvent(`sample_rate`,`error`),po(Ps(`Discarding event because it's not included in the random sample (sampling rate = ${a})`));let u=zs(e.type);return this._prepareEvent(e,t,n,r).then(e=>{if(e===null)throw this.recordDroppedEvent(`event_processor`,u),Ps("An event processor returned `null`, will not send event.");return t.data?.__sentry__===!0?e:Bs(Vs(this,i,e,t),c)}).then(i=>{if(i===null){if(this.recordDroppedEvent(`before_send`,u),o){let t=1+(e.spans||[]).length;this.recordDroppedEvent(`before_send`,`span`,t)}throw Ps(`${c} returned \`null\`, will not send event.`)}let a=n.getSession()||r.getSession();if(s&&a&&this._updateSessionFromEvent(a,i),o){let e=(i.sdkProcessingMetadata?.spanCountBeforeProcessing||0)-(i.spans?i.spans.length:0);e>0&&this.recordDroppedEvent(`before_send`,`span`,e)}let l=i.transaction_info;return o&&l&&i.transaction!==e.transaction&&(i.transaction_info={...l,source:`custom`}),this.sendEvent(i,t),i}).then(null,e=>{throw Is(e)||Fs(e)?e:(this.captureException(e,{mechanism:{handled:!1,type:`internal`},data:{__sentry__:!0},originalException:e}),Ns(`Event processing pipeline threw an error, original event will not be sent. Details have been sent as a new event.\nReason: ${e}`))})}_process(e,t){this._numProcessing++,this._promiseBuffer.add(e).then(e=>(this._numProcessing--,e),e=>(this._numProcessing--,e===vs&&this.recordDroppedEvent(`queue_overflow`,t),e))}_clearOutcomes(){let e=this._outcomes;return this._outcomes={},Object.entries(e).map(([e,t])=>{let[n,r]=e.split(`:`);return{reason:n,category:r,quantity:t}})}_flushOutcomes(){Cn&&Bn.log(`Flushing outcomes...`);let e=this._clearOutcomes();if(e.length===0){Cn&&Bn.log(`No outcomes to send`);return}if(!this._dsn){Cn&&Bn.log(`No dsn provided, will not send outcomes`);return}Cn&&Bn.log(`Sending outcomes:`,e);let t=Ts(e,this._options.tunnel&&Yi(this._dsn));this.sendEnvelope(t)}};function zs(e){return e===`replay_event`?`replay`:e||`error`}function Bs(e,t){let n=`${t} must return \`null\` or a valid event.`;if(yr(e))return e.then(e=>{if(!hr(e)&&e!==null)throw Ns(n);return e},e=>{throw Ns(`${t} rejected with ${e}`)});if(!hr(e)&&e!==null)throw Ns(n);return e}function Vs(e,t,n,r){let{beforeSend:i,beforeSendTransaction:a,beforeSendSpan:o,ignoreSpans:s}=t,c=n;if(Hs(c)&&i)return i(c,r);if(Us(c)){if(o||s){let t=Ds(c);if(s?.length&&ka(t,s))return null;if(o){let e=o(t);e?c=di(n,Os(e)):wa()}if(c.spans){let t=[],n=c.spans;for(let e of n){if(s?.length&&ka(e,s)){Aa(n,e);continue}if(o){let n=o(e);n?t.push(n):(wa(),t.push(e))}else t.push(e)}let r=c.spans.length-t.length;r&&e.recordDroppedEvent(`before_send`,`span`,r),c.spans=t}}if(a){if(c.spans){let e=c.spans.length;c.sdkProcessingMetadata={...n.sdkProcessingMetadata,spanCountBeforeProcessing:e}}return a(c,r)}}return c}function Hs(e){return e.type===void 0}function Us(e){return e.type===`transaction`}function Ws(e){let t=0;return e.name&&(t+=e.name.length*2),t+=8,t+Ks(e.attributes)}function Gs(e){let t=0;return e.message&&(t+=e.message.length*2),t+Ks(e.attributes)}function Ks(e){if(!e)return 0;let t=0;return Object.values(e).forEach(e=>{Array.isArray(e)?t+=e.length*qs(e[0]):mr(e)?t+=qs(e):t+=100}),t}function qs(e){return typeof e==`string`?e.length*2:typeof e==`number`?8:typeof e==`boolean`?4:0}function Js(e,t,n,r,i){let a={sent_at:new Date().toISOString()};return n?.sdk&&(a.sdk={name:n.sdk.name,version:n.sdk.version}),r&&i&&(a.dsn=Yi(i)),t&&(a.trace=t),Ua(a,[Ys(e)])}function Ys(e){return[{type:`check_in`},e]}function Xs(e){let t=e._metadata?.sdk,n=t?.name&&t?.version?`${t?.name}/${t?.version}`:void 0;e.transportOptions={...e.transportOptions,headers:{...n&&{"user-agent":n},...e.transportOptions?.headers}}}function Zs(e,t){return e(t.stack||``,1)}function Qs(e){return lr(e)&&`__sentry_fetch_url_host__`in e&&typeof e.__sentry_fetch_url_host__==`string`}function $s(e){return Qs(e)?`${e.message} (${e.__sentry_fetch_url_host__})`:e.message}function ec(e,t){let n={type:t.name||t.constructor.name,value:$s(t)},r=Zs(e,t);return r.length&&(n.stacktrace={frames:r}),n}function tc(e){for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t)){let n=e[t];if(n instanceof Error)return n}}function nc(e){if(`name`in e&&typeof e.name==`string`){let t=`'${e.name}' captured as exception`;return`message`in e&&typeof e.message==`string`&&(t+=` with message '${e.message}'`),t}else if(`message`in e&&typeof e.message==`string`)return e.message;let t=Nr(e);if(dr(e))return`Event \`ErrorEvent\` captured as exception with message \`${e.message}\``;let n=rc(e);return`${n&&n!==`Object`?`'${n}'`:`Object`} captured as exception with keys: ${t}`}function rc(e){try{let t=Object.getPrototypeOf(e);return t?t.constructor.name:void 0}catch{}}function ic(e,t,n,r){if(lr(n))return[n,void 0];if(t.synthetic=!0,hr(n)){let t=e?.getOptions().normalizeDepth,i={__serialized__:Ia(n,t)},a=tc(n);if(a)return[a,i];let o=nc(n),s=r?.syntheticException||Error(o);return s.message=o,[s,i]}let i=r?.syntheticException||Error(n);return i.message=`${n}`,[i,void 0]}function ac(e,t,n,r){let i=r?.data&&r.data.mechanism||{handled:!0,type:`generic`},[a,o]=ic(e,i,n,r),s={exception:{values:[ec(t,a)]}};return o&&(s.extra=o),Yr(s,void 0,void 0),Xr(s,i),{...s,event_id:r?.event_id}}function oc(e,t,n=`info`,r,i){let a={event_id:r?.event_id,level:n};if(i&&r?.syntheticException){let n=Zs(e,r.syntheticException);n.length&&(a.exception={values:[{value:t,stacktrace:{frames:n}}]},Xr(a,{synthetic:!0}))}if(pr(t)){let{__sentry_template_string__:e,__sentry_template_values__:n}=t;return a.logentry={message:e,params:n},a}return a.message=t,a}var sc=class extends Rs{constructor(e){Ea(),Xs(e),super(e),this._setUpMetricsProcessing()}eventFromException(e,t){let n=ac(this,this._options.stackParser,e,t);return n.level=`error`,fo(n)}eventFromMessage(e,t=`info`,n){return fo(oc(this._options.stackParser,e,t,n,this._options.attachStacktrace))}captureException(e,t,n){return cc(t),super.captureException(e,t,n)}captureEvent(e,t,n){return!e.type&&e.exception?.values&&e.exception.values.length>0&&cc(t),super.captureEvent(e,t,n)}captureCheckIn(e,t,n){let r=`checkInId`in e&&e.checkInId?e.checkInId:Kr();if(!this._isEnabled())return Cn&&Bn.warn(`SDK not enabled, will not capture check-in.`),r;let{release:i,environment:a,tunnel:o}=this.getOptions(),s={check_in_id:r,monitor_slug:e.monitorSlug,status:e.status,release:i,environment:a};`duration`in e&&(s.duration=e.duration),t&&(s.monitor_config={schedule:t.schedule,checkin_margin:t.checkinMargin,max_runtime:t.maxRuntime,timezone:t.timezone,failure_issue_threshold:t.failureIssueThreshold,recovery_threshold:t.recoveryThreshold});let[c,l]=os(this,n);l&&(s.contexts={trace:l});let u=Js(s,c,this.getSdkMetadata(),o,this.getDsn());return Cn&&Bn.log(`Sending checkin:`,e.monitorSlug,e.status),this.sendEnvelope(u),r}dispose(){Cn&&Bn.log(`Disposing client...`);for(let e of Object.keys(this._hooks))this._hooks[e]?.clear();this._hooks={},this._eventProcessors.length=0,this._integrations={},this._outcomes={},this._transport=void 0,this._promiseBuffer=ys(64)}_prepareEvent(e,t,n,r){return this._options.platform&&(e.platform=e.platform||this._options.platform),this._options.runtime&&(e.contexts={...e.contexts,runtime:e.contexts?.runtime||this._options.runtime}),this._options.serverName&&(e.server_name=e.server_name||this._options.serverName),super._prepareEvent(e,t,n,r)}_setUpMetricsProcessing(){this.on(`processMetric`,e=>{this._options.serverName&&(e.attributes={"server.address":this._options.serverName,...e.attributes})})}};function cc(e){let t=Ni().getScopeData().sdkProcessingMetadata.requestSession;if(t){let n=e?.mechanism?.handled??!0;n&&t.status!==`crashed`?t.status=`errored`:n||(t.status=`crashed`)}}const lc=new Set([`false`,`f`,`n`,`no`,`off`,`0`]),uc=new Set([`true`,`t`,`y`,`yes`,`on`,`1`]);function dc(e,t){let n=String(e).toLowerCase();return lc.has(n)?!1:uc.has(n)?!0:t?.strict?null:!!e}function fc(e){if(!e)return{};let t=e.match(/^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/);if(!t)return{};let n=t[6]||``,r=t[8]||``;return{host:t[4],path:t[5],protocol:t[2],search:n,hash:r,relative:t[5]+n+r}}function pc(e){return e.split(/[?#]/,1)[0]}function mc(e){let{protocol:t,host:n,path:r}=e,i=n?.replace(/^.*@/,`[filtered]:[filtered]@`).replace(/(:80)$/,``).replace(/(:443)$/,``)||``;return`${t?`${t}://`:``}${i}${r}`}function hc(e,t,n=[t],r=`npm`){let i=(e._metadata=e._metadata||{}).sdk=e._metadata.sdk||{};i.name||(i.name=`sentry.javascript.${t}`,i.packages=n.map(e=>({name:`${r}:@sentry/${e}`,version:Tn})),i.version=Tn)}function gc(e={}){let t=e.client||Li();if(!Go()||!t)return{};let n=ji(En());if(n.getTraceData)return n.getTraceData(e);let r=e.scope||Mi(),i=e.span||Ca(),a=i?fa(i):_c(r),o=Hi(i?Pa(i):Na(t,r));if(!ra.test(a))return Bn.warn(`Invalid sentry-trace data. Cannot generate trace data`),{};let s={"sentry-trace":a,baggage:o};return e.propagateTraceparent&&(s.traceparent=i?pa(i):vc(r)),s}function _c(e){let{traceId:t,sampled:n,propagationSpanId:r}=e.getPropagationContext();return oa(t,r,n)}function vc(e){let{traceId:t,sampled:n,propagationSpanId:r}=e.getPropagationContext();return sa(t,r,n)}const yc=`[Tracing] Not injecting trace data for url because it does not match tracePropagationTargets:`;function bc(e,t,n){if(typeof e!=`string`||!t)return!0;let r=n?.get(e);if(r!==void 0)return Cn&&!r&&Bn.log(yc,e),r;let i=Hr(e,t);return n?.set(e,i),Cn&&!i&&Bn.log(yc,e),i}function xc(e){let t=Object.create(null);try{Object.entries(e).forEach(([e,n])=>{typeof n==`string`&&(t[e]=n)})}catch{}return t}function Sc(e){let t=e.headers||{},n=(typeof t[`x-forwarded-host`]==`string`?t[`x-forwarded-host`]:void 0)||(typeof t.host==`string`?t.host:void 0),r=(typeof t[`x-forwarded-proto`]==`string`?t[`x-forwarded-proto`]:void 0)||e.protocol||(e.socket?.encrypted?`https`:`http`),i=e.url||``,a=Cc({url:i,host:n,protocol:r}),o=e.body||void 0,s=e.cookies;return{url:a,method:e.method,query_string:wc(i),headers:xc(t),cookies:s,data:o}}function Cc({url:e,protocol:t,host:n}){if(e?.startsWith(`http`))return e;if(e&&n)return`${t}://${n}${e}`}function wc(e){if(e)try{let t=new URL(e,`http://s.io`).search.slice(1);return t.length?t:void 0}catch{return}}function Tc(e,t){let n=Li(),r=Ni();if(!n)return;let{beforeBreadcrumb:i=null,maxBreadcrumbs:a=100}=n.getOptions();if(a<=0)return;let o={timestamp:ri(),...e},s=i?jn(()=>i(o,t)):o;s!==null&&(n.emit&&n.emit(`beforeAddBreadcrumb`,s,t),r.addBreadcrumb(s,a))}let Ec;const Dc=new WeakMap,Oc=as((()=>({name:`FunctionToString`,setupOnce(){Ec=Function.prototype.toString;try{Function.prototype.toString=function(...e){let t=kr(this),n=Dc.has(Li())&&t!==void 0?t:this;return Ec.apply(n,e)}}catch{}},setup(e){Dc.set(e,!0)}}))),kc=[/^Script error\.?$/,/^Javascript error: Script error\.? on line 0$/,/^ResizeObserver loop completed with undelivered notifications.$/,/^Cannot redefine property: googletag$/,/^Can't find variable: gmo$/,/^undefined is not an object \(evaluating 'a\.[A-Z]'\)$/,/can't redefine non-configurable property "solana"/,/vv\(\)\.getRestrictions is not a function/,/Can't find variable: _AutofillCallbackHandler/,/Object Not Found Matching Id:\d+, MethodName:simulateEvent/,/^Java exception was raised during method invocation$/],Ac=as((e={})=>{let t;return{name:`EventFilters`,setup(n){t=jc(e,n.getOptions())},processEvent(n,r,i){return t||=jc(e,i.getOptions()),Mc(n,t)?null:n}}});function jc(e={},t={}){return{allowUrls:[...e.allowUrls||[],...t.allowUrls||[]],denyUrls:[...e.denyUrls||[],...t.denyUrls||[]],ignoreErrors:[...e.ignoreErrors||[],...t.ignoreErrors||[],...e.disableErrorDefaults?[]:kc],ignoreTransactions:[...e.ignoreTransactions||[],...t.ignoreTransactions||[]]}}function Mc(e,t){if(!e.type){if(Nc(e,t.ignoreErrors))return Cn&&Bn.warn(`Event dropped due to being matched by \`ignoreErrors\` option.\nEvent: ${Jr(e)}`),!0;if(zc(e))return Cn&&Bn.warn(`Event dropped due to not having an error message, error type or stacktrace.\nEvent: ${Jr(e)}`),!0;if(Fc(e,t.denyUrls))return Cn&&Bn.warn(`Event dropped due to being matched by \`denyUrls\` option.\nEvent: ${Jr(e)}.\nUrl: ${Rc(e)}`),!0;if(!Ic(e,t.allowUrls))return Cn&&Bn.warn(`Event dropped due to not being matched by \`allowUrls\` option.\nEvent: ${Jr(e)}.\nUrl: ${Rc(e)}`),!0}else if(e.type===`transaction`&&Pc(e,t.ignoreTransactions))return Cn&&Bn.warn(`Event dropped due to being matched by \`ignoreTransactions\` option.\nEvent: ${Jr(e)}`),!0;return!1}function Nc(e,t){return t?.length?Es(e).some(e=>Hr(e,t)):!1}function Pc(e,t){if(!t?.length)return!1;let n=e.transaction;return n?Hr(n,t):!1}function Fc(e,t){if(!t?.length)return!1;let n=Rc(e);return n?Hr(n,t):!1}function Ic(e,t){if(!t?.length)return!0;let n=Rc(e);return n?Hr(n,t):!0}function Lc(e=[]){for(let t=e.length-1;t>=0;t--){let n=e[t];if(n&&n.filename!==`<anonymous>`&&n.filename!==`[native code]`)return n.filename||null}return null}function Rc(e){try{let t=[...e.exception?.values??[]].reverse().find(e=>e.mechanism?.parent_id===void 0&&e.stacktrace?.frames?.length)?.stacktrace?.frames;return t?Lc(t):null}catch{return Cn&&Bn.error(`Cannot extract url for event ${Jr(e)}`),null}}function zc(e){return e.exception?.values?.length?!e.message&&!e.exception.values.some(e=>e.stacktrace||e.type&&e.type!==`Error`||e.value):!1}function Bc(e,t,n,r,i,a){if(!i.exception?.values||!a||!xr(a.originalException,Error))return;let o=i.exception.values.length>0?i.exception.values[i.exception.values.length-1]:void 0;o&&(i.exception.values=Vc(e,t,r,a.originalException,n,i.exception.values,o,0))}function Vc(e,t,n,r,i,a,o,s){if(a.length>=n+1)return a;let c=[...a];if(xr(r[i],Error)){Uc(o,s,r);let a=e(t,r[i]),l=c.length;Wc(a,i,l,s),c=Vc(e,t,n,r[i],i,[a,...c],a,l)}return Hc(r)&&r.errors.forEach((a,l)=>{if(xr(a,Error)){Uc(o,s,r);let u=e(t,a),d=c.length;Wc(u,`errors[${l}]`,d,s),c=Vc(e,t,n,a,i,[u,...c],u,d)}}),c}function Hc(e){return Array.isArray(e.errors)}function Uc(e,t,n){e.mechanism={handled:!0,type:`auto.core.linked_errors`,...Hc(n)&&{is_exception_group:!0},...e.mechanism,exception_id:t}}function Wc(e,t,n,r){e.mechanism={handled:!0,...e.mechanism,type:`chained`,source:t,exception_id:n,parent_id:r}}const Gc=as(((e={})=>{let t=e.limit||5,n=e.key||`cause`;return{name:`LinkedErrors`,preprocessEvent(e,r,i){Bc(ec,i.getOptions().stackParser,n,t,e,r)}}}));function Kc(e){let t={},n=0;for(;n<e.length;){let r=e.indexOf(`=`,n);if(r===-1)break;let i=e.indexOf(`;`,n);if(i===-1)i=e.length;else if(i<r){n=e.lastIndexOf(`;`,r-1)+1;continue}let a=e.slice(n,r).trim();if(t[a]===void 0){let n=e.slice(r+1,i).trim();n.charCodeAt(0)===34&&(n=n.slice(1,-1));try{t[a]=n.indexOf(`%`)===-1?n:decodeURIComponent(n)}catch{t[a]=n}}n=i+1}return t}const qc=[`X-Client-IP`,`X-Forwarded-For`,`Fly-Client-IP`,`CF-Connecting-IP`,`Fastly-Client-Ip`,`True-Client-Ip`,`X-Real-IP`,`X-Cluster-Client-IP`,`X-Forwarded`,`Forwarded-For`,`Forwarded`,`X-Vercel-Forwarded-For`];function Jc(e){let t={};for(let n of Object.keys(e))t[n.toLowerCase()]=e[n];return qc.map(e=>{let n=t[e.toLowerCase()],r=Array.isArray(n)?n.join(`;`):n;return e===`Forwarded`?Yc(r):r?.split(`,`).map(e=>e.trim())}).reduce((e,t)=>t?e.concat(t):e,[]).find(e=>e!==null&&Xc(e))||null}function Yc(e){if(!e)return null;for(let t of e.split(`;`))if(t.startsWith(`for=`))return t.slice(4);return null}function Xc(e){return/(?:^(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}$)|(?:^(?:(?:[a-fA-F\d]{1,4}:){7}(?:[a-fA-F\d]{1,4}|:)|(?:[a-fA-F\d]{1,4}:){6}(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|:[a-fA-F\d]{1,4}|:)|(?:[a-fA-F\d]{1,4}:){5}(?::(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|(?::[a-fA-F\d]{1,4}){1,2}|:)|(?:[a-fA-F\d]{1,4}:){4}(?:(?::[a-fA-F\d]{1,4}){0,1}:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|(?::[a-fA-F\d]{1,4}){1,3}|:)|(?:[a-fA-F\d]{1,4}:){3}(?:(?::[a-fA-F\d]{1,4}){0,2}:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|(?::[a-fA-F\d]{1,4}){1,4}|:)|(?:[a-fA-F\d]{1,4}:){2}(?:(?::[a-fA-F\d]{1,4}){0,3}:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|(?::[a-fA-F\d]{1,4}){1,5}|:)|(?:[a-fA-F\d]{1,4}:){1}(?:(?::[a-fA-F\d]{1,4}){0,4}:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|(?::[a-fA-F\d]{1,4}){1,6}|:)|(?::(?:(?::[a-fA-F\d]{1,4}){0,5}:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|(?::[a-fA-F\d]{1,4}){1,7}|:)))(?:%[0-9a-zA-Z]{1,})?$)/.test(e)}const Zc={cookies:!0,data:!0,headers:!0,query_string:!0,url:!0},Qc=as(((e={})=>{let t={...Zc,...e.include};return{name:`RequestData`,processEvent(e,n,r){let{sdkProcessingMetadata:i={}}=e,{normalizedRequest:a,ipAddress:o}=i,s={...t,ip:t.ip??r.getOptions().sendDefaultPii};return a&&$c(e,a,{ipAddress:o},s),e}}}));function $c(e,t,n,r){if(e.request={...e.request,...el(t,r)},r.ip){let r=t.headers&&Jc(t.headers)||n.ipAddress;r&&(e.user={...e.user,ip_address:r})}}function el(e,t){let n={},r={...e.headers};return t.headers&&(n.headers=r,t.cookies||delete r.cookie,t.ip||qc.forEach(e=>{delete r[e]})),n.method=e.method,t.url&&(n.url=e.url),t.cookies&&(n.cookies=e.cookies||(r?.cookie?Kc(r.cookie):void 0)||{}),t.query_string&&(n.query_string=e.query_string),t.data&&(n.data=e.data),n}function tl(e){let t=`console`;$n(t,e),er(t,nl)}function nl(){`console`in wn&&kn.forEach(function(e){e in wn.console&&Er(wn.console,e,function(t){return An[e]=t,function(...t){tr(`console`,{args:t,level:e}),An[e]?.apply(wn.console,t)}})})}function rl(e){return e===`warn`?`warning`:[`fatal`,`error`,`warning`,`log`,`info`,`debug`].includes(e)?e:`log`}const il=/^(\S+:\\|\/?)([\s\S]*?)((?:\.{1,2}|[^/\\]+?|)(\.[^./\\]*|))(?:[/\\]*)$/;function al(e){let t=e.length>1024?`<truncated>${e.slice(-1024)}`:e,n=il.exec(t);return n?n.slice(1):[]}function ol(e){let t=al(e),n=t[0]||``,r=t[1];return!n&&!r?`.`:(r&&=r.slice(0,r.length-1),n+r)}const sl=as((e={})=>{let t=new Set(e.levels||kn);return{name:`Console`,setup(e){tl(({args:n,level:r})=>{Li()!==e||!t.has(r)||cl(r,n)})}}});function cl(e,t){let n={category:`console`,data:{arguments:t,logger:`console`},level:rl(e),message:ll(t)};if(e===`assert`)if(t[0]===!1){let e=t.slice(1);n.message=e.length>0?`Assertion failed: ${ll(e)}`:`Assertion failed`,n.data.arguments=e}else return;Tc(n,{input:t,level:e})}function ll(e){return`util`in wn&&typeof wn.util.format==`function`?wn.util.format(...e):Br(e,` `)}function ul(e){if(e!==void 0){if(e>=400&&e<500)return`warning`;if(e>=500)return`error`}}function dl(e,t=!1){return!(t||e&&!e.startsWith(`/`)&&!e.match(/^[A-Z]:/)&&!e.startsWith(`.`)&&!e.match(/^[a-zA-Z]([a-zA-Z0-9.\-+])*:\/\//))&&e!==void 0&&!e.includes(`node_modules/`)}function fl(e){let t=/^\s*[-]{4,}$/,n=/at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/,r=/at (?:async )?(.+?) \(data:(.*?),/;return i=>{let a=i.match(r);if(a)return{filename:`<data:${a[2]}>`,function:a[1]};let o=i.match(n);if(o){let t,n,r,i,a;if(o[1]){r=o[1];let e=r.lastIndexOf(`.`);if(r[e-1]===`.`&&e--,e>0){t=r.slice(0,e),n=r.slice(e+1);let i=t.indexOf(`.Module`);i>0&&(r=r.slice(i+1),t=t.slice(0,i))}i=void 0}n&&(i=t,a=n),n===`<anonymous>`&&(a=void 0,r=void 0),r===void 0&&(a||=`?`,r=i?`${i}.${a}`:a);let s=Xn(o[2]),c=o[5]===`native`;!s&&o[5]&&!c&&(s=o[5]);let l=s?hl(s):void 0;return{filename:l??s,module:l&&e?.(l),function:r,lineno:ml(o[3]),colno:ml(o[4]),in_app:dl(s||``,c)}}if(i.match(t))return{filename:i}}}function pl(e){return[90,fl(e)]}function ml(e){return parseInt(e||``,10)||void 0}function hl(e){try{return decodeURI(e)}catch{return}}var gl=class{constructor(e){this._maxSize=e,this._cache=new Map}get size(){return this._cache.size}get(e){let t=this._cache.get(e);if(t!==void 0)return this._cache.delete(e),this._cache.set(e,t),t}set(e,t){if(this._cache.size>=this._maxSize){let e=this._cache.keys().next().value;this._cache.delete(e)}this._cache.set(e,t)}remove(e){let t=this._cache.get(e);return t&&this._cache.delete(e),t}clear(){this._cache.clear()}keys(){return Array.from(this._cache.keys())}values(){let e=[];return this._cache.forEach(t=>e.push(t)),e}};let _l=!1,vl=``,yl=0,bl=0;const xl=6e4,Sl=new Map,Cl=new Set([`OnUncaughtException`,`OnUnhandledRejection`]);function wl(e,t){_l=!0,vl=e,Wo(`session_id`,ln()),Wo(`runtime`,e),t&&Wo(`client_kind`,t)}function Tl(e){return vl=e.runtime,{dsn:hn.sentryDsn,environment:e.environment??(typeof process<`u`?`production`:void 0)??`production`,release:e.version,tracesSampleRate:0,sampleRate:1,maxBreadcrumbs:30,sendDefaultPii:!1,...e.disableGlobalUnhandledErrors?{integrations(e){return e.filter(e=>!Cl.has(e.name))}}:{},beforeSend(e){return jl(e)||Nl(e)||!Pl()||Il(Fl(e))?null:El(e)}}}function El(e){return e}function Dl(e,t){_l&&(t?Fi(n=>{n.setExtras(t),Ho(e)}):Ho(e))}function Ol(e,t,n){_l&&(n?Fi(r=>{r.setExtras(n),Uo(e,t)}):Uo(e,t))}function kl(e,t){_l&&Wo(e,t)}function Al(e,t,n=`info`){_l&&Tc({message:e,category:t,level:n})}function jl(e){for(let t of e.exception?.values??[]){let e=t.type??``,n=t.value??``;if(e===`AbortError`||e===`CreditLimitError`||n===`interrupted`||n===`This operation was aborted`||vl===`cli`&&/\bE(?:IO|PIPE|NOTCONN)\b/.test(n))return!0}return(e.message??e.logentry?.message??``)===`Credit limit reached`}const Ml=/codellm|abacusai/;function Nl(e){if(vl!==`extension-host`)return!1;let t=e.exception?.values;if(!t||t.length===0)return!1;let n=t.flatMap(e=>e.stacktrace?.frames??[]);return n.length===0?!1:!n.some(e=>{let t=e.filename??e.abs_path??e.module??``;return Ml.test(t)})}function Pl(){let e=Date.now();return e-bl>xl&&(yl=0,bl=e),yl++,yl<=10}function Fl(e){let t=e.exception?.values?.[0];if(t)return`${t.type??``}:${t.value??``}`;let n=e.message??e.logentry?.message;return n?`msg:${n}`:Math.random().toString()}function Il(e){let t=Date.now(),n=Sl.get(e);if(n&&t-n<xl)return!0;if(Sl.set(e,t),Sl.size>100){let e=Sl.keys().next().value;e&&Sl.delete(e)}return!1}var Ll=class extends Error{code=`AUTH_EXPIRED`;constructor(){super(`Session expired — please log in again.`),this.name=`AuthExpiredError`}},Rl=class extends Error{cause;code=`NETWORK_ERROR`;constructor(e,t){super(e??`Network unavailable — check your connection.`),this.cause=t,this.name=`NetworkError`}};const zl=[`User not logged in`,`Invalid API Key`,`Invalid session token`];function Bl(e){return zl.includes(e)}function Vl(e){if(!(e instanceof Error))return!1;if(e instanceof Rl)return!0;let t=e.message.toLowerCase();return e.name===`TypeError`&&t.includes(`fetch failed`)||t.includes(`econnrefused`)||t.includes(`econnreset`)||t.includes(`etimedout`)||t.includes(`enotfound`)||t.includes(`enetunreach`)||t.includes(`ehostunreach`)||t.includes(`epipe`)||t.includes(`socket hang up`)}const Hl=`codellm.endpoints`;var Ul=class e{headers;logger;clientName;clientVersion;static apiPrefixUrl=`https://apps.abacus.ai`;static abacusDomain=`https://abacus.ai`;chatWebDomainOverride=null;cache=new Map;userAgentHeaders;constructor(e,t,n,r){this.headers=e,this.logger=t,this.clientName=n,this.clientVersion=r,this.userAgentHeaders=n&&r?{"User-Agent":`${n}/${r}`}:{};let i=this.cache.get(`codellm.endpoints`)??null;if(i)try{this.endpoints=JSON.parse(i)}catch(e){this.logger?.error(`Failed to parse stored endpoints:`,e)}}throwAuthExpired(){throw Ol(`Auth expired mid-session`,`warning`,{context:`api-client`}),new Ll}setUrl(t){e.apiPrefixUrl=t,e.abacusDomain=t.includes(`-apps.abacus.ai`)?t.replace(`-apps.abacus.ai`,`.abacus.ai`):t.replace(`apps.`,``)}setChatWebDomain(e){this.chatWebDomainOverride=e,e?this.cache.set(`codellm.chatWebDomain`,e):this.cache.delete(`codellm.chatWebDomain`)}getChatWebDomain(){return this.chatWebDomainOverride}endpoints=null;getAbacusDomain(){return this.isDevpodEnvironment()?e.apiPrefixUrl:e.abacusDomain}async getConversationsList(e,t){return this._customCall(`/api/listDeploymentConversations`,{conversationType:e,...t&&{chatllmProjectId:t}},{isClusterProxy:!0,method:`GET`})}async searchConversations(e,t){return this._customCall(`/api/_searchConversations`,{query:e,...t&&{conversationType:t}},{isClusterProxy:!0,method:`POST`})}getDeploymentConversation(e){return this._customCall(`/api/getDeploymentConversation`,{...e,skipDocumentBoundingBoxes:!0,filterIntermediateConversationEvents:!0,getUnusedDocumentUploads:!1},{isClusterProxy:!0,method:`POST`})}clearDeploymentConversation(e){return this._customCall(`/api/clearDeploymentConversation`,e,{isClusterProxy:!0,method:`POST`})}getCodeEdit({fileContents:e,fileSelection:t,rules:n,...r}){return this._customCall(`/api/_getCodeEdit`,{...r,fileContents:e===void 0?void 0:JSON.stringify(e),fileSelection:t===void 0?void 0:JSON.stringify(t),rules:n===void 0?void 0:JSON.stringify(n)},{isClusterProxy:!0,method:`POST`})}listLLMModels(){return this._customCall(`/api/_listCodeBots`,{supportsThoughtStreaming:!0},{isClusterProxy:!0,method:`POST`})}getConstantsAutocomplete(){return this._customCall(`/api/_getConstantsAutocomplete`,{},{isClusterProxy:!0,method:`POST`,suppressNotifications:!0})}getCodeAutocompleteResponse({signal:e,...t}){return this._customCall(`/api/_getCodeAutocompleteResponse`,t,{isClusterProxy:!0,method:`POST`,signal:e})}getAutocompleteEditPrediction({signal:e,...t}){return this._customCall(`/api/_getAutocompleteEditPrediction`,t,{isClusterProxy:!0,method:`POST`,signal:e})}async getUserInfo(){return!this.endpoints&&!this.chatWebDomainOverride&&await this.getApiEndpoint(),await this._customCall(`/api/_getUserInfo`,{},{method:`POST`,useDirect:!0,suppressNotifications:!0})}async getApiEndpoint(){let e=await this._customCall(`/api/v0/getApiEndpoint`,{reqScheme:`https`},{method:`POST`,useDirect:!0});return e?.success&&e?.result&&(this.endpoints=e,this.cache.set(Hl,JSON.stringify(e))),e}resetEndpoints(){this.endpoints=null,this.cache.delete(Hl),this.chatWebDomainOverride=null}async*streamChatMessage({deploymentConversationId:e,requestId:t,fileContents:n,filePositions:r,terminalSelections:i,rules:a,signal:o,...s}){yield*this.fetchSSE(`/api/_codeLLMSendMessageSSE`,{...s,deploymentConversationId:e,fileContents:n===null?void 0:JSON.stringify(n),filePositions:r===null?void 0:JSON.stringify(r),terminalSelections:i===null?void 0:JSON.stringify(i),rules:a===void 0?void 0:JSON.stringify(a),requestId:t},{isClusterProxy:!0,signal:o})}async*streamAgentMessage({deploymentConversationId:e,requestId:t,folderPaths:n,terminalSelections:r,mcpTools:i,availableSkills:a,activeSkills:o,supportedSubAgents:s,reconnect:c,signal:l,...u}){if(!e)throw Error(`streamAgentMessage: deploymentConversationId is required but was not provided`);yield*this.fetchSSE(`/api/_codeLLMSendAgentMessageSSE`,{...u,deploymentConversationId:e,folderPaths:n===void 0?void 0:JSON.stringify(n),terminalSelections:r===null?void 0:JSON.stringify(r),mcpTools:i===void 0?void 0:JSON.stringify(i),requestId:t,availableSkills:a===void 0?void 0:JSON.stringify(a),activeSkills:o===void 0?void 0:JSON.stringify(o),supportedSubAgents:s===void 0?void 0:JSON.stringify(s),supportsParallelToolUse:!0,...c&&{reconnect:!0}},{isClusterProxy:!0,signal:l})}stopResponseSSE(e){return this._customCall(`/api/_stopResponseSSE`,{requestId:e},{isClusterProxy:!0,method:`POST`})}getPendingRequestIdForConversation(e){return this._customCall(`/api/_getPendingRequestIdForConversation`,{deploymentConversationId:e},{isClusterProxy:!0,method:`GET`})}async _customCall(t,n,r={method:`POST`}){try{let i,a=this.isDevpodEnvironment();a&&!t?.includes(`/api/v0/`)&&!t?.includes(`_codeLLMSendMessageSSE`)&&!t?.includes(`_getCodeAutocompleteResponse`)&&!t?.includes(`_getAutocompleteEditPrediction`)&&!t?.includes(`_codeLLMSendAgentMessageSSE`)&&!t?.includes(`createUploadDataToChatllmRequest`)&&!t?.includes(`getUploadDataToChatllmStatus`)&&!t?.includes(`_stopResponseSSE`)&&!t?.includes(`_getPendingRequestIdForConversation`)&&!t?.includes(`_getCodeSummary`)&&!t?.includes(`_getIndividualSummary`)&&!t?.includes(`_getCodeEdit`)&&!t?.includes(`_getCodeChatEdits`)&&!t?.includes(`_getCodeLLMCodeEmbeddings`)&&!t?.includes(`_getCodeLLMChangedFiles`)&&!t?.includes(`_updateCodeLLMWorkspaceState`)&&(t=t?.replace(`/api/`,`/api/v0/`)),i=r.useDirect?t?.includes(`_getUserInfo`)?this.getAbacusDomain():this.chatWebDomainOverride?`https://${this.chatWebDomainOverride}`:this.getAbacusDomain():r.isClusterProxy?this.chatWebDomainOverride?`https://${this.chatWebDomainOverride}`:this.endpoints?.result?a&&this.endpoints.result.proxyEndpoint?this.endpoints.result.proxyEndpoint:this.endpoints.result.externalChatEndpoint?this.endpoints.result.externalChatEndpoint:e.apiPrefixUrl:e.apiPrefixUrl:t?.includes(`listExternalApplications`)||t?.includes(`_authenticateDeviceForCodeLlm`)||t?.includes(`_pollDeviceCode`)?this.getAbacusDomain():e.apiPrefixUrl;let o=i.indexOf(`/chatllm`);i=o===-1?i:i.substring(0,o);let s=new URL(`${i}${t}`),c=t?.includes(`_authenticateDeviceForCodeLlm`)||t?.includes(`_pollDeviceCode`)?{}:await this.headers.getHeaders(),l,u={"REAI-UI":`1`,...this.userAgentHeaders,...c};if(r.method===`GET`){if(n!==void 0)for(let e of Object.keys(n))s.searchParams.append(e,String(n[e]))}else if(r.formData)l=r.formData;else if(l=JSON.stringify(n),u[`Content-Type`]=`application/json`,r.gzip){u[`Content-Encoding`]=`gzip`;let e=new Blob([l]).stream().pipeThrough(new CompressionStream(`gzip`)),t=await new Response(e).arrayBuffer();l=btoa(String.fromCharCode.apply(null,Array.from(new Uint8Array(t))))}let d=await fetch(s,{method:r.method,body:l,headers:u,signal:r.signal});if(!d.ok){let e=await d.text(),t=`API request failed with status ${d.status}`;try{let n=JSON.parse(e);if(n&&typeof n==`object`&&`error`in n){let e=String(n.error);Bl(e)&&this.throwAuthExpired(),t=e}}catch(n){if(n instanceof Ll)throw n;t+=`: ${e}`}throw Error(t)}let f=await d.json();if(f&&typeof f==`object`&&`success`in f&&`error`in f){let e=f;e.success===!1&&e.error&&Bl(e.error)&&this.throwAuthExpired()}return f}catch(e){if(e instanceof Ll)throw e;if(e instanceof Error&&e.name===`AbortError`)return null;throw e instanceof Error&&Vl(e)?new Rl(e.message,e):(Dl(e,{context:`api-client`}),e)}}async createCodellmDeploymentConversation(e=rt.CODE_LLM,t){return await this._customCall(`/api/_createCodellmDeploymentConversation`,{conversationType:e.toString(),...t&&{clientType:t},codeAgentV2:!0},{isClusterProxy:!0,method:`POST`})}_createChatLLMProject(e){return this._customCall(`/api/_createChatLLMProject`,e,{isClusterProxy:!0,method:`POST`})}_attachConverstationToChatLLMProject(e){return this._customCall(`/api/_attachConverstationToChatLLMProject`,e,{isClusterProxy:!0,method:`POST`})}async createUploadDataToChatllmRequest({deploymentConversationId:e,deploymentId:t,files:n,startPage:r,endPage:i}){let a=new globalThis.FormData;for(let e of n){let t=e.name.lastIndexOf(`.`),n=e.name.substring(0,t===-1?e.name.length:t);a.append(n,e)}a.append(`deploymentConversationId`,e),a.append(`deploymentId`,t),r!==void 0&&a.append(`startPage`,String(r)),i!==void 0&&a.append(`endPage`,String(i));let o=await this._customCall(`/api/createUploadDataToChatllmRequest`,{},{isClusterProxy:!0,method:`POST`,formData:a});if(!o)throw Error(`Upload failed`);return o}getUploadStatus(e){return this._customCall(`/api/getUploadDataToChatllmStatus?request_id=${e}`,void 0,{isClusterProxy:!0,method:`GET`})}deleteDeploymentConversation(e){return this._customCall(`/api/deleteDeploymentConversation`,e,{isClusterProxy:!0,method:`POST`})}setDeploymentConversationFeedback(e){return this._customCall(`/api/v0/setDeploymentConversationFeedback`,e,{method:`POST`})}getCodeChatEdits(e){return this._customCall(`/api/_getCodeChatEdits`,e,{isClusterProxy:!0,method:`POST`})}listExternalApplications(){return this._customCall(`/api/listExternalApplications`,{includeSearchLlm:!1},{isClusterProxy:!1,method:`POST`})}detachDocumentsFromDeploymentConversation(e){return this._customCall(`/api/_detachDocumentsFromDeploymentConversation`,e,{isClusterProxy:!0,method:`POST`})}authenticateDeviceForCodeLlm(e,t){return this._customCall(`/api/_authenticateDeviceForCodeLlm`,{email:e,deviceId:t},{isClusterProxy:!1,method:`POST`})}pollDeviceCode(e){return this._customCall(`/api/_pollDeviceCode`,{userCode:e},{isClusterProxy:!1,method:`POST`})}recordUserAction(e){return this._customCall(`/api/_recordUserAction`,{actionType:e},{isClusterProxy:!0,method:`POST`})}listOrganizations(){return this._customCall(`/api/v0/_listOrganizations`,{},{method:`GET`,useDirect:!0})}updateApiKeyOrganization(e){return this._customCall(`/api/v0/_updateApiKeyOrganization`,{organizationId:e},{method:`POST`,useDirect:!0})}selectActiveOrganization(e){return this._customCall(`/api/v0/_selectActiveOrganization`,{organizationId:e},{method:`POST`,useDirect:!0})}async switchOrganization(e){if(!(await this.updateApiKeyOrganization(e))?.success||!(await this.selectActiveOrganization(e))?.success)return!1;this.resetEndpoints();let t=(await this.getUserInfo())?.result?.organization,n=null;if(t){let e=t.externalChatOrgHost;if(typeof e==`string`&&e.trim()!==``)n=e.trim();else if(typeof t.externalChatEndpoint==`string`&&t.externalChatEndpoint.trim()!==``){let e=t.externalChatEndpoint.trim(),r=null;try{r=new URL(e)}catch{try{/^[a-zA-Z][a-zA-Z0-9+\-.]*:\/\//.test(e)||(r=new URL(`https://${e}`))}catch{r=null}}r?.host&&(n=r.host)}}return this.setChatWebDomain(n),!0}isDevpodEnvironment(){let e=this.endpoints?.result?.apiEndpoint||``;return e.includes(`-dev.internalreai.com`)||e.includes(`-dev.mumbai.internalreai.com`)}async*fetchSSE(e,t,n={}){let r=(await this._fetchRaw(e,t,{...n,isSSE:!0,method:`POST`})).body?.getReader();if(!r)return;let i=new TextDecoder,a=``;try{for(;;){let e,{value:t,done:n}=await Promise.race([r.read(),new Promise((t,n)=>{e=setTimeout(()=>n(Error(`SSE read timeout — connection may be lost`)),3e4)})]).finally(()=>clearTimeout(e));if(n){if(a.trim()){let e=this.parseNDJSON(a);for(let t of e.parsed){if(t.end||t.cancelled)return;yield t}}return}a+=i.decode(t,{stream:!0});let{parsed:o,remainder:s}=this.parseNDJSON(a);a=s;for(let e of o){if(e.error){yield e;return}if(e.end||e.cancelled)return;e.ping||(yield e)}}}catch(e){if(this.logger?.error(`Streaming error`,e),e instanceof Ll)throw e;if(e instanceof Error&&e.name===`AbortError`)return;throw e instanceof Error&&(Vl(e)||e.message.includes(`SSE read timeout`))?new Rl(e.message,e):e}finally{r.releaseLock()}}async _fetchRaw(t,n,r){let i,a=this.isDevpodEnvironment();i=r.useDirect?t?.includes(`_getUserInfo`)?this.getAbacusDomain():this.chatWebDomainOverride?`https://${this.chatWebDomainOverride}`:this.getAbacusDomain():r.isClusterProxy?this.chatWebDomainOverride?`https://${this.chatWebDomainOverride}`:this.endpoints?.result?a&&this.endpoints.result.proxyEndpoint?this.endpoints.result.proxyEndpoint:this.endpoints.result.externalChatEndpoint?this.endpoints.result.externalChatEndpoint:e.apiPrefixUrl:e.apiPrefixUrl:t?.includes(`listExternalApplications`)||t?.includes(`_authenticateDeviceForCodeLlm`)||t?.includes(`_pollDeviceCode`)?this.getAbacusDomain():e.apiPrefixUrl,a&&!t?.includes(`/api/v0/`)&&!t?.includes(`_codeLLMSendMessageSSE`)&&!t?.includes(`_getCodeAutocompleteResponse`)&&!t?.includes(`_getAutocompleteEditPrediction`)&&!t?.includes(`_codeLLMSendAgentMessageSSE`)&&!t?.includes(`createUploadDataToChatllmRequest`)&&!t?.includes(`getUploadDataToChatllmStatus`)&&!t?.includes(`_stopResponseSSE`)&&!t?.includes(`_getPendingRequestIdForConversation`)&&!t?.includes(`_getCodeSummary`)&&!t?.includes(`_getIndividualSummary`)&&!t?.includes(`_getCodeEdit`)&&!t?.includes(`_getCodeChatEdits`)&&!t?.includes(`_getCodeLLMCodeEmbeddings`)&&!t?.includes(`_getCodeLLMChangedFiles`)&&!t?.includes(`_updateCodeLLMWorkspaceState`)&&(t=t?.replace(`/api/`,`/api/v0/`));let o=i.indexOf(`/chatllm`);i=o===-1?i:i.substring(0,o);let s=new URL(`${i}${t}`),c=await this.headers.getHeaders(),l={"REAI-UI":`1`,...this.userAgentHeaders,...c,...r.isSSE?{Accept:`text/event-stream`,Connection:`keep-alive`}:{}},u;if(r.method===`GET`){if(n)for(let e of Object.keys(n))s.searchParams.append(e,String(n[e]))}else if(r.formData)u=r.formData;else if(u=JSON.stringify(n),l[`Content-Type`]=`application/json`,r.gzip){l[`Content-Encoding`]=`gzip`;let e=new Blob([u]).stream().pipeThrough(new CompressionStream(`gzip`)),t=await new Response(e).arrayBuffer();u=btoa(String.fromCharCode.apply(null,Array.from(new Uint8Array(t))))}let d=await fetch(s,{method:r.method,body:u,headers:l,signal:r.signal});if(!d.ok){let e=await d.text(),t=`API request failed with status ${d.status}`;try{let n=JSON.parse(e);if(n&&typeof n==`object`&&`error`in n){let e=String(n.error);Bl(e)&&this.throwAuthExpired(),t=e}}catch(n){if(n instanceof Ll)throw n;t+=`: ${e}`}throw Error(t)}return d}parseNDJSON(e){let t=[],n=0,r=e.indexOf(`
7
7
  `,n);for(;r!==-1;){let i=e.substring(n,r).trim();if(n=r+1,r=e.indexOf(`
8
8
  `,n),i!==``)try{t.push(JSON.parse(i))}catch(r){if(r instanceof SyntaxError)return{parsed:t,remainder:e.substring(n-i.length-1)}}}return{parsed:t,remainder:e.substring(n)}}getCodeSummary(e){return this._customCall(`/api/_getCodeSummary`,e,{isClusterProxy:!0,method:`POST`,suppressNotifications:!0})}getIndividualSummary(e){return this._customCall(`/api/_getIndividualSummary`,e,{isClusterProxy:!0,method:`POST`,suppressNotifications:!0})}getCodeEmbedding(e){return this._customCall(`/api/_getCodeLLMCodeEmbeddings`,e,{isClusterProxy:!0,method:`POST`})}getCodeLLMChangedFiles(e){return this._customCall(`/api/_getCodeLLMChangedFiles`,e,{isClusterProxy:!0,method:`POST`,gzip:!1})}updateWorkspaceState(e){return this._customCall(`/api/_updateCodeLLMWorkspaceState`,e,{isClusterProxy:!0,method:`POST`,gzip:!1})}};const Wl=typeof __SENTRY_DEBUG__>`u`||__SENTRY_DEBUG__;var Gl=class extends sc{constructor(e){let t=e.includeServerName===!1?void 0:e.serverName||global.process.env.SENTRY_NAME||P.hostname(),n={...e,platform:`node`,runtime:{name:`node`,version:global.process.version},serverName:t};hc(n,`node-light`,[`node-core`]),Bn.log(`Initializing Sentry: process: ${process.pid}, thread: ${z?`main`:`worker-${ne}`}.`),super(n),this.getOptions().enableLogs&&(this._logOnExitFlushListener=()=>{ls(this)},t&&this.on(`beforeCaptureLog`,e=>{e.attributes={...e.attributes,"server.address":t}}),process.on(`beforeExit`,this._logOnExitFlushListener))}async flush(e){return this.getOptions().sendClientReports&&this._flushOutcomes(),super.flush(e)}async close(e){return this._clientReportInterval&&clearInterval(this._clientReportInterval),this._clientReportOnExitFlushListener&&process.off(`beforeExit`,this._clientReportOnExitFlushListener),this._logOnExitFlushListener&&process.off(`beforeExit`,this._logOnExitFlushListener),super.close(e)}startClientReportTracking(){let e=this.getOptions();e.sendClientReports&&(this._clientReportOnExitFlushListener=()=>{this._flushOutcomes()},this._clientReportInterval=setInterval(()=>{Wl&&Bn.log(`Flushing client reports based on interval.`),this._flushOutcomes()},e.clientReportFlushInterval??6e4).unref(),process.on(`beforeExit`,this._clientReportOnExitFlushListener))}};const Kl=as((e={})=>({name:`ChildProcess`,setup(){re.channel(`child_process`).subscribe(t=>{t&&typeof t==`object`&&`process`in t&&ql(t.process,e)}),re.channel(`worker_threads`).subscribe(t=>{t&&typeof t==`object`&&`worker`in t&&Jl(t.worker,e)})}}));function ql(e,t){let n=!1,r;e.on(`spawn`,()=>{if(e.spawnfile===`/usr/bin/sw_vers`){n=!0;return}r={spawnfile:e.spawnfile},t.includeChildProcessArgs&&(r.spawnargs=e.spawnargs)}).on(`exit`,e=>{n||(n=!0,e!==null&&e!==0&&Tc({category:`child_process`,message:`Child process exited with code '${e}'`,level:e===0?`info`:`warning`,data:r}))}).on(`error`,e=>{n||(n=!0,Tc({category:`child_process`,message:`Child process errored with '${e.message}'`,level:`error`,data:r}))})}function Jl(e,t){let n;e.on(`online`,()=>{n=e.threadId}).on(`error`,e=>{t.captureWorkerErrors===!1?Tc({category:`worker_thread`,message:`Worker thread errored with '${e.message}'`,level:`error`,data:{threadId:n}}):Ho(e,{mechanism:{type:`auto.child_process.worker_thread`,handled:!1,data:{threadId:String(n)}}})})}const Yl=a(h),Xl=a(_),Zl=as(((e={})=>{let t,n={app:!0,os:!0,device:!0,culture:!0,cloudResource:!0,...e};async function r(e){t===void 0&&(t=i());let n=Ql(await t);return e.contexts={...e.contexts,app:{...n.app,...e.contexts?.app},os:{...n.os,...e.contexts?.os},device:{...n.device,...e.contexts?.device},culture:{...n.culture,...e.contexts?.culture},cloud_resource:{...n.cloud_resource,...e.contexts?.cloud_resource}},e}async function i(){let e={};if(n.os&&(e.os=await $l()),n.app&&(e.app=tu()),n.device&&(e.device=nu(n.device)),n.culture){let t=eu();t&&(e.culture=t)}return n.cloudResource&&(e.cloud_resource=uu()),e}return{name:`Context`,processEvent(e){return r(e)}}}));function Ql(e){if(e.app?.app_memory&&(e.app.app_memory=process.memoryUsage().rss),e.app?.free_memory&&typeof process.availableMemory==`function`){let t=process.availableMemory?.();t!=null&&(e.app.free_memory=t)}return e.device?.free_memory&&(e.device.free_memory=P.freemem()),e}async function $l(){let e=P.platform();switch(e){case`darwin`:return su();case`linux`:return lu();default:return{name:ru[e]||e,version:P.release()}}}function eu(){try{if(typeof process.versions.icu!=`string`)return;let e=new Date(9e8);if(new Intl.DateTimeFormat(`es`,{month:`long`}).format(e)===`enero`){let e=Intl.DateTimeFormat().resolvedOptions();return{locale:e.locale,timezone:e.timeZone}}}catch{}}function tu(){let e=process.memoryUsage().rss,t={app_start_time:new Date(Date.now()-process.uptime()*1e3).toISOString(),app_memory:e};if(typeof process.availableMemory==`function`){let e=process.availableMemory?.();e!=null&&(t.free_memory=e)}return t}function nu(e){let t={},n;try{n=P.uptime()}catch{}if(typeof n==`number`&&(t.boot_time=new Date(Date.now()-n*1e3).toISOString()),t.arch=P.arch(),(e===!0||e.memory)&&(t.memory_size=P.totalmem(),t.free_memory=P.freemem()),e===!0||e.cpu){let e=P.cpus(),n=e?.[0];n&&(t.processor_count=e.length,t.cpu_description=n.model,t.processor_frequency=n.speed)}return t}const ru={aix:`IBM AIX`,freebsd:`FreeBSD`,openbsd:`OpenBSD`,sunos:`SunOS`,win32:`Windows`,ohos:`OpenHarmony`,android:`Android`},iu=[{name:`fedora-release`,distros:[`Fedora`]},{name:`redhat-release`,distros:[`Red Hat Linux`,`Centos`]},{name:`redhat_version`,distros:[`Red Hat Linux`]},{name:`SuSE-release`,distros:[`SUSE Linux`]},{name:`lsb-release`,distros:[`Ubuntu Linux`,`Arch Linux`]},{name:`debian_version`,distros:[`Debian`]},{name:`debian_release`,distros:[`Debian`]},{name:`arch-release`,distros:[`Arch Linux`]},{name:`gentoo-release`,distros:[`Gentoo Linux`]},{name:`novell-release`,distros:[`SUSE Linux`]},{name:`alpine-release`,distros:[`Alpine Linux`]}],au={alpine:e=>e,arch:e=>ou(/distrib_release=(.*)/,e),centos:e=>ou(/release ([^ ]+)/,e),debian:e=>e,fedora:e=>ou(/release (..)/,e),mint:e=>ou(/distrib_release=(.*)/,e),red:e=>ou(/release ([^ ]+)/,e),suse:e=>ou(/VERSION = (.*)\n/,e),ubuntu:e=>ou(/distrib_release=(.*)/,e)};function ou(e,t){let n=e.exec(t);return n?n[1]:void 0}async function su(){let e={kernel_version:P.release(),name:`Mac OS X`,version:`10.${Number(P.release().split(`.`)[0])-4}`};try{let t=await new Promise((e,t)=>{se(`/usr/bin/sw_vers`,(n,r)=>{if(n){t(n);return}e(r)})});e.name=ou(/^ProductName:\s+(.*)$/m,t),e.version=ou(/^ProductVersion:\s+(.*)$/m,t),e.build=ou(/^BuildVersion:\s+(.*)$/m,t)}catch{}return e}function cu(e){return e.split(` `)[0].toLowerCase()}async function lu(){let e={kernel_version:P.release(),name:`Linux`};try{let t=await Xl(`/etc`),n=iu.find(e=>t.includes(e.name));if(!n)return e;let r=(await Yl(A(`/etc`,n.name),{encoding:`utf-8`})).toLowerCase(),{distros:i}=n;e.name=i.find(e=>r.indexOf(cu(e))>=0)||i[0],e.version=au[cu(e.name)]?.(r)}catch{}return e}function uu(){if(process.env.VERCEL)return{"cloud.provider":`vercel`,"cloud.region":process.env.VERCEL_REGION};if(process.env.AWS_REGION)return{"cloud.provider":`aws`,"cloud.region":process.env.AWS_REGION,"cloud.platform":process.env.AWS_EXECUTION_ENV};if(process.env.GCP_PROJECT)return{"cloud.provider":`gcp`};if(process.env.ALIYUN_REGION_ID)return{"cloud.provider":`alibaba_cloud`,"cloud.region":process.env.ALIYUN_REGION_ID};if(process.env.WEBSITE_SITE_NAME&&process.env.REGION_NAME)return{"cloud.provider":`azure`,"cloud.region":process.env.REGION_NAME};if(process.env.IBM_CLOUD_REGION)return{"cloud.provider":`ibm_cloud`,"cloud.region":process.env.IBM_CLOUD_REGION};if(process.env.TENCENTCLOUD_REGION)return{"cloud.provider":`tencent_cloud`,"cloud.region":process.env.TENCENTCLOUD_REGION,"cloud.account.id":process.env.TENCENTCLOUD_APPID,"cloud.availability_zone":process.env.TENCENTCLOUD_ZONE};if(process.env.NETLIFY)return{"cloud.provider":`netlify`};if(process.env.FLY_REGION)return{"cloud.provider":`fly.io`,"cloud.region":process.env.FLY_REGION};if(process.env.DYNO)return{"cloud.provider":`heroku`}}const du=new gl(10),fu=new gl(20);function pu(e,t,n){let r=e.get(t);return r===void 0?(e.set(t,n),n):r}function mu(e){return!!(e.startsWith(`node:`)||e.endsWith(`.min.js`)||e.endsWith(`.min.cjs`)||e.endsWith(`.min.mjs`)||e.startsWith(`data:`))}function hu(e){return e.lineno!==void 0&&e.lineno>1e4||e.colno!==void 0&&e.colno>1e3}function gu(e,t){let n=du.get(e);if(n===void 0)return!1;for(let e=t[0];e<=t[1];e++)if(n[e]===void 0)return!1;return!0}function _u(e,t){if(!e.length)return[];let n=0,r=e[0];if(typeof r!=`number`)return[];let i=Tu(r,t),a=[];for(;;){if(n===e.length-1){a.push(i);break}let r=e[n+1];if(typeof r!=`number`)break;r<=i[1]?i[1]=r+t:(a.push(i),i=Tu(r,t)),n++}return a}function vu(e,t,n){return new Promise((r,i)=>{let a=u(e),o=pe({input:a});function s(){a.destroy(),r()}let c=0,l=0,d=t[l];if(d===void 0){s();return}let f=d[0],p=d[1];function m(t){fu.set(e,1),Wl&&Bn.error(`Failed to read file: ${e}. Error: ${t}`),o.close(),o.removeAllListeners(),s()}a.on(`error`,m),o.on(`error`,m),o.on(`close`,s),o.on(`line`,e=>{if(c++,!(c<f)&&(n[c]=zr(e,0),c>=p)){if(l===t.length-1){o.close(),o.removeAllListeners();return}l++;let e=t[l];if(e===void 0){o.close(),o.removeAllListeners();return}f=e[0],p=e[1]}})})}async function yu(e,t){let n={};if(t>0&&e.exception?.values){for(let t of e.exception.values)if(t.stacktrace?.frames?.length)for(let e=t.stacktrace.frames.length-1;e>=0;e--){let r=t.stacktrace.frames[e],i=r?.filename;!r||typeof i!=`string`||typeof r.lineno!=`number`||mu(i)||hu(r)||(n[i]||(n[i]=[]),n[i].push(r.lineno))}}let r=Object.keys(n);if(r.length==0)return e;let i=[];for(let e of r){if(fu.get(e))continue;let r=n[e];if(!r)continue;r.sort((e,t)=>e-t);let a=_u(r,t);if(a.every(t=>gu(e,t)))continue;let o=pu(du,e,{});i.push(vu(e,a,o))}if(await Promise.all(i).catch(()=>{Wl&&Bn.log(`Failed to read one or more source files and resolve context lines`)}),t>0&&e.exception?.values)for(let n of e.exception.values)n.stacktrace?.frames&&n.stacktrace.frames.length>0&&bu(n.stacktrace.frames,t,du);return e}function bu(e,t,n){for(let r of e)if(r.filename&&r.context_line===void 0&&typeof r.lineno==`number`){let e=n.get(r.filename);if(e===void 0)continue;Su(r.lineno,r,t,e)}}function xu(e){delete e.pre_context,delete e.context_line,delete e.post_context}function Su(e,t,n,r){if(t.lineno===void 0||r===void 0){Wl&&Bn.error(`Cannot resolve context for frame with no lineno or file contents`);return}t.pre_context=[];for(let i=Cu(e,n);i<e;i++){let e=r[i];if(e===void 0){xu(t),Wl&&Bn.error(`Could not find line ${i} in file ${t.filename}`);return}t.pre_context.push(e)}if(r[e]===void 0){xu(t),Wl&&Bn.error(`Could not find line ${e} in file ${t.filename}`);return}t.context_line=r[e];let i=wu(e,n);t.post_context=[];for(let n=e+1;n<=i;n++){let e=r[n];if(e===void 0)break;t.post_context.push(e)}}function Cu(e,t){return Math.max(1,e-t)}function wu(e,t){return e+t}function Tu(e,t){return[Cu(e,t),wu(e,t)]}const Eu=as(((e={})=>{let t=e.frameContextLines===void 0?7:e.frameContextLines;return{name:`ContextLines`,processEvent(e){return yu(e,t)}}})),Du=$r(process.versions.node),Ou=Du.major;Du.minor;let ku;async function Au(){if(ku===void 0)try{ku=!!(await import(`node:inspector`)).url()}catch{ku=!1}return ku}const ju=`__SENTRY_ERROR_LOCAL_VARIABLES__`;function Mu(e,t,n){let r=0,i=5,a=0;return setInterval(()=>{a===0?r>e&&(i*=2,n(i),i>86400&&(i=86400),a=i):(--a,a===0&&t()),r=0},1e3).unref(),()=>{r+=1}}function Nu(e){return e!==void 0&&(e.length===0||e===`?`||e===`<anonymous>`)}function Pu(e,t){return e===t||`Object.${e}`===t||e===`Object.${t}`||Nu(e)&&Nu(t)}function Fu(...e){Bn.log(`[LocalVariables]`,...e)}const Iu=as(((e={})=>{function t(t,n){let r=(t.stacktrace?.frames||[]).filter(e=>e.function!==`new Promise`);for(let t=0;t<r.length;t++){let i=r.length-t-1,a=n[t],o=r[i];if(!o||!a)break;a.vars===void 0||o.in_app===!1&&e.includeOutOfAppFrames!==!0||!Pu(o.function,a.function)||(o.vars=a.vars)}}function n(e,n){if(n.originalException&&typeof n.originalException==`object`&&`__SENTRY_ERROR_LOCAL_VARIABLES__`in n.originalException&&Array.isArray(n.originalException.__SENTRY_ERROR_LOCAL_VARIABLES__)){for(let r of e.exception?.values||[])t(r,n.originalException[ju]);n.originalException[ju]=void 0}return e}async function r(){let e=await import(`node:inspector`);e.url()||e.open(0)}function i(e){let t=new R(new URL(`data:application/javascript;base64,LyohIEBzZW50cnkvbm9kZS1jb3JlIDEwLjQ2LjAgKGU1ZmRjOWQpIHwgaHR0cHM6Ly9naXRodWIuY29tL2dldHNlbnRyeS9zZW50cnktamF2YXNjcmlwdCAqLwppbXBvcnR7U2Vzc2lvbiBhcyBlfWZyb20ibm9kZTppbnNwZWN0b3IvcHJvbWlzZXMiO2ltcG9ydHt3b3JrZXJEYXRhIGFzIHR9ZnJvbSJub2RlOndvcmtlcl90aHJlYWRzIjtjb25zdCBuPWdsb2JhbFRoaXMsaT17fTtjb25zdCBvPSJfX1NFTlRSWV9FUlJPUl9MT0NBTF9WQVJJQUJMRVNfXyI7Y29uc3QgYT10O2Z1bmN0aW9uIHMoLi4uZSl7YS5kZWJ1ZyYmZnVuY3Rpb24oZSl7aWYoISgiY29uc29sZSJpbiBuKSlyZXR1cm4gZSgpO2NvbnN0IHQ9bi5jb25zb2xlLG89e30sYT1PYmplY3Qua2V5cyhpKTthLmZvckVhY2goZT0+e2NvbnN0IG49aVtlXTtvW2VdPXRbZV0sdFtlXT1ufSk7dHJ5e3JldHVybiBlKCl9ZmluYWxseXthLmZvckVhY2goZT0+e3RbZV09b1tlXX0pfX0oKCk9PmNvbnNvbGUubG9nKCJbTG9jYWxWYXJpYWJsZXMgV29ya2VyXSIsLi4uZSkpfWFzeW5jIGZ1bmN0aW9uIGMoZSx0LG4saSl7Y29uc3Qgbz1hd2FpdCBlLnBvc3QoIlJ1bnRpbWUuZ2V0UHJvcGVydGllcyIse29iamVjdElkOnQsb3duUHJvcGVydGllczohMH0pO2lbbl09by5yZXN1bHQuZmlsdGVyKGU9PiJsZW5ndGgiIT09ZS5uYW1lJiYhaXNOYU4ocGFyc2VJbnQoZS5uYW1lLDEwKSkpLnNvcnQoKGUsdCk9PnBhcnNlSW50KGUubmFtZSwxMCktcGFyc2VJbnQodC5uYW1lLDEwKSkubWFwKGU9PmUudmFsdWU/LnZhbHVlKX1hc3luYyBmdW5jdGlvbiByKGUsdCxuLGkpe2NvbnN0IG89YXdhaXQgZS5wb3N0KCJSdW50aW1lLmdldFByb3BlcnRpZXMiLHtvYmplY3RJZDp0LG93blByb3BlcnRpZXM6ITB9KTtpW25dPW8ucmVzdWx0Lm1hcChlPT5bZS5uYW1lLGUudmFsdWU/LnZhbHVlXSkucmVkdWNlKChlLFt0LG5dKT0+KGVbdF09bixlKSx7fSl9ZnVuY3Rpb24gdShlLHQpe2UudmFsdWUmJigidmFsdWUiaW4gZS52YWx1ZT92b2lkIDA9PT1lLnZhbHVlLnZhbHVlfHxudWxsPT09ZS52YWx1ZS52YWx1ZT90W2UubmFtZV09YDwke2UudmFsdWUudmFsdWV9PmA6dFtlLm5hbWVdPWUudmFsdWUudmFsdWU6ImRlc2NyaXB0aW9uImluIGUudmFsdWUmJiJmdW5jdGlvbiIhPT1lLnZhbHVlLnR5cGU/dFtlLm5hbWVdPWA8JHtlLnZhbHVlLmRlc2NyaXB0aW9ufT5gOiJ1bmRlZmluZWQiPT09ZS52YWx1ZS50eXBlJiYodFtlLm5hbWVdPSI8dW5kZWZpbmVkPiIpKX1hc3luYyBmdW5jdGlvbiBsKGUsdCl7Y29uc3Qgbj1hd2FpdCBlLnBvc3QoIlJ1bnRpbWUuZ2V0UHJvcGVydGllcyIse29iamVjdElkOnQsb3duUHJvcGVydGllczohMH0pLGk9e307Zm9yKGNvbnN0IHQgb2Ygbi5yZXN1bHQpaWYodC52YWx1ZT8ub2JqZWN0SWQmJiJBcnJheSI9PT10LnZhbHVlLmNsYXNzTmFtZSl7Y29uc3Qgbj10LnZhbHVlLm9iamVjdElkO2F3YWl0IGMoZSxuLHQubmFtZSxpKX1lbHNlIGlmKHQudmFsdWU/Lm9iamVjdElkJiYiT2JqZWN0Ij09PXQudmFsdWUuY2xhc3NOYW1lKXtjb25zdCBuPXQudmFsdWUub2JqZWN0SWQ7YXdhaXQgcihlLG4sdC5uYW1lLGkpfWVsc2UgdC52YWx1ZSYmdSh0LGkpO3JldHVybiBpfWxldCBmOyhhc3luYyBmdW5jdGlvbigpe2NvbnN0IHQ9bmV3IGU7dC5jb25uZWN0VG9NYWluVGhyZWFkKCkscygiQ29ubmVjdGVkIHRvIG1haW4gdGhyZWFkIik7bGV0IG49ITE7dC5vbigiRGVidWdnZXIucmVzdW1lZCIsKCk9PntuPSExfSksdC5vbigiRGVidWdnZXIucGF1c2VkIixlPT57bj0hMCxhc3luYyBmdW5jdGlvbihlLHtyZWFzb246dCxkYXRhOntvYmplY3RJZDpufSxjYWxsRnJhbWVzOml9KXtpZigiZXhjZXB0aW9uIiE9PXQmJiJwcm9taXNlUmVqZWN0aW9uIiE9PXQpcmV0dXJuO2lmKGY/LigpLG51bGw9PW4pcmV0dXJuO2NvbnN0IGE9W107Zm9yKGxldCB0PTA7dDxpLmxlbmd0aDt0Kyspe2NvbnN0e3Njb3BlQ2hhaW46bixmdW5jdGlvbk5hbWU6byx0aGlzOnN9PWlbdF0sYz1uLmZpbmQoZT0+ImxvY2FsIj09PWUudHlwZSkscj0iZ2xvYmFsIiE9PXMuY2xhc3NOYW1lJiZzLmNsYXNzTmFtZT9gJHtzLmNsYXNzTmFtZX0uJHtvfWA6bztpZih2b2lkIDA9PT1jPy5vYmplY3Qub2JqZWN0SWQpYVt0XT17ZnVuY3Rpb246cn07ZWxzZXtjb25zdCBuPWF3YWl0IGwoZSxjLm9iamVjdC5vYmplY3RJZCk7YVt0XT17ZnVuY3Rpb246cix2YXJzOm59fX1hd2FpdCBlLnBvc3QoIlJ1bnRpbWUuY2FsbEZ1bmN0aW9uT24iLHtmdW5jdGlvbkRlY2xhcmF0aW9uOmBmdW5jdGlvbigpIHsgdGhpcy4ke299ID0gdGhpcy4ke299IHx8ICR7SlNPTi5zdHJpbmdpZnkoYSl9OyB9YCxzaWxlbnQ6ITAsb2JqZWN0SWQ6bn0pLGF3YWl0IGUucG9zdCgiUnVudGltZS5yZWxlYXNlT2JqZWN0Iix7b2JqZWN0SWQ6bn0pfSh0LGUucGFyYW1zKS50aGVuKGFzeW5jKCk9PntuJiZhd2FpdCB0LnBvc3QoIkRlYnVnZ2VyLnJlc3VtZSIpfSxhc3luYyBlPT57biYmYXdhaXQgdC5wb3N0KCJEZWJ1Z2dlci5yZXN1bWUiKX0pfSksYXdhaXQgdC5wb3N0KCJEZWJ1Z2dlci5lbmFibGUiKTtjb25zdCBpPSExIT09YS5jYXB0dXJlQWxsRXhjZXB0aW9ucztpZihhd2FpdCB0LnBvc3QoIkRlYnVnZ2VyLnNldFBhdXNlT25FeGNlcHRpb25zIix7c3RhdGU6aT8iYWxsIjoidW5jYXVnaHQifSksaSl7Y29uc3QgZT1hLm1heEV4Y2VwdGlvbnNQZXJTZWNvbmR8fDUwO2Y9ZnVuY3Rpb24oZSx0LG4pe2xldCBpPTAsbz01LGE9MDtyZXR1cm4gc2V0SW50ZXJ2YWwoKCk9PnswPT09YT9pPmUmJihvKj0yLG4obyksbz44NjQwMCYmKG89ODY0MDApLGE9byk6KGEtPTEsMD09PWEmJnQoKSksaT0wfSwxZTMpLnVucmVmKCksKCk9PntpKz0xfX0oZSxhc3luYygpPT57cygiUmF0ZS1saW1pdCBsaWZ0ZWQuIiksYXdhaXQgdC5wb3N0KCJEZWJ1Z2dlci5zZXRQYXVzZU9uRXhjZXB0aW9ucyIse3N0YXRlOiJhbGwifSl9LGFzeW5jIGU9PntzKGBSYXRlLWxpbWl0IGV4Y2VlZGVkLiBEaXNhYmxpbmcgY2FwdHVyaW5nIG9mIGNhdWdodCBleGNlcHRpb25zIGZvciAke2V9IHNlY29uZHMuYCksYXdhaXQgdC5wb3N0KCJEZWJ1Z2dlci5zZXRQYXVzZU9uRXhjZXB0aW9ucyIse3N0YXRlOiJ1bmNhdWdodCJ9KX0pfX0pKCkuY2F0Y2goZT0+e3MoIkZhaWxlZCB0byBzdGFydCBkZWJ1Z2dlciIsZSl9KSxzZXRJbnRlcnZhbCgoKT0+e30sMWU0KTs=`),{workerData:e,execArgv:[],env:{...process.env,NODE_OPTIONS:void 0}});process.on(`exit`,()=>{t.terminate()}),t.once(`error`,e=>{Fu(`Worker error`,e)}),t.once(`exit`,e=>{Fu(`Worker exit`,e)}),t.unref()}return{name:`LocalVariablesAsync`,async setup(t){if(!t.getOptions().includeLocalVariables)return;if(await Au()){Bn.warn(`Local variables capture has been disabled because the debugger was already enabled`);return}let n={...e,debug:Bn.isEnabled()};r().then(()=>{try{i(n)}catch(e){Bn.error(`Failed to start worker`,e)}},e=>{Bn.error(`Failed to start inspector`,e)})},processEvent(e,t){return n(e,t)}}}));function Lu(e){if(e!==void 0)return e.slice(-10).reduce((e,t)=>`${e},${t.function},${t.lineno},${t.colno}`,``)}function Ru(e,t){if(t!==void 0)return Lu(e(t,1))}function zu(e){let t=[],n=!1;function r(r){t=[],!n&&(n=!0,e(r))}t.push(r);function i(e){t.push(e)}function a(e){let n=t.pop()||r;try{n(e)}catch{r(e)}}return{add:i,next:a}}var Bu=class e{constructor(e){this._session=e}static async create(t){return t||new e(new(await(import(`node:inspector`))).Session)}configureAndConnect(e,t){this._session.connect(),this._session.on(`Debugger.paused`,t=>{e(t,()=>{this._session.post(`Debugger.resume`)})}),this._session.post(`Debugger.enable`),this._session.post(`Debugger.setPauseOnExceptions`,{state:t?`all`:`uncaught`})}setPauseOnExceptions(e){this._session.post(`Debugger.setPauseOnExceptions`,{state:e?`all`:`uncaught`})}getLocalVariables(e,t){this._getProperties(e,e=>{let{add:n,next:r}=zu(t);for(let t of e)if(t.value?.objectId&&t.value.className===`Array`){let e=t.value.objectId;n(n=>this._unrollArray(e,t.name,n,r))}else if(t.value?.objectId&&t.value.className===`Object`){let e=t.value.objectId;n(n=>this._unrollObject(e,t.name,n,r))}else t.value&&n(e=>this._unrollOther(t,e,r));r({})})}_getProperties(e,t){this._session.post(`Runtime.getProperties`,{objectId:e,ownProperties:!0},(e,n)=>{t(e?[]:n.result)})}_unrollArray(e,t,n,r){this._getProperties(e,e=>{n[t]=e.filter(e=>e.name!==`length`&&!isNaN(parseInt(e.name,10))).sort((e,t)=>parseInt(e.name,10)-parseInt(t.name,10)).map(e=>e.value?.value),r(n)})}_unrollObject(e,t,n,r){this._getProperties(e,e=>{n[t]=e.map(e=>[e.name,e.value?.value]).reduce((e,[t,n])=>(e[t]=n,e),{}),r(n)})}_unrollOther(e,t,n){e.value&&(`value`in e.value?e.value.value===void 0||e.value.value===null?t[e.name]=`<${e.value.value}>`:t[e.name]=e.value.value:`description`in e.value&&e.value.type!==`function`?t[e.name]=`<${e.value.description}>`:e.value.type===`undefined`&&(t[e.name]=`<undefined>`)),n(t)}};const Vu=as(((e={},t)=>{let n=new gl(20),r,i=!1;function a(t){let r=Lu(t.stacktrace?.frames);if(r===void 0)return;let i=n.remove(r);if(i===void 0)return;let a=(t.stacktrace?.frames||[]).filter(e=>e.function!==`new Promise`);for(let t=0;t<a.length;t++){let n=a.length-t-1,r=i[t],o=a[n];if(!o||!r)break;r.vars===void 0||o.in_app===!1&&e.includeOutOfAppFrames!==!0||!Pu(o.function,r.function)||(o.vars=r.vars)}}function o(e){for(let t of e.exception?.values||[])a(t);return e}let s;async function c(){let a=Li()?.getOptions();if(a?.includeLocalVariables){if(Ou<18){Bn.log("The `LocalVariables` integration is only supported on Node >= v18.");return}if(await Au()){Bn.warn(`Local variables capture has been disabled because the debugger was already enabled`);return}try{let o=await Bu.create(t),s=(e,{params:{reason:t,data:i,callFrames:a}},s)=>{if(t!==`exception`&&t!==`promiseRejection`){s();return}r?.();let c=Ru(e,i.description);if(c==null){s();return}let{add:l,next:u}=zu(e=>{n.set(c,e),s()});for(let e=0;e<Math.min(a.length,5);e++){let{scopeChain:t,functionName:n,this:r}=a[e],i=t.find(e=>e.type===`local`),s=r.className===`global`||!r.className?n:`${r.className}.${n}`;if(i?.object.objectId===void 0)l(t=>{t[e]={function:s},u(t)});else{let t=i.object.objectId;l(n=>o.getLocalVariables(t,t=>{n[e]={function:s,vars:t},u(n)}))}}u([])},c=e.captureAllExceptions!==!1;o.configureAndConnect((e,t)=>s(a.stackParser,e,t),c),c&&(r=Mu(e.maxExceptionsPerSecond||50,()=>{Bn.log(`Local variables rate-limit lifted.`),o.setPauseOnExceptions(!0)},e=>{Bn.log(`Local variables rate-limit exceeded. Disabling capturing of caught exceptions for ${e} seconds.`),o.setPauseOnExceptions(!1)})),i=!0}catch(e){Bn.log("The `LocalVariables` integration failed to start.",e)}}}return{name:`LocalVariables`,setupOnce(){s=c()},async processEvent(e){return await s,i?o(e):e},_getCachedFramesCount(){return n.size},_getFirstCachedFrame(){return n.values()[0]}}})),Hu=(e={})=>Du.major<19?Vu(e):Iu(e);function Uu(){try{return typeof module<`u`&&module.exports!==void 0}catch{return!1}}let Wu;const Gu=typeof __SENTRY_SERVER_MODULES__>`u`?{}:__SENTRY_SERVER_MODULES__,Ku=(()=>({name:`Modules`,processEvent(e){return e.modules={...e.modules,...Xu()},e},getModules:Xu}));function qu(){try{return et.cache?Object.keys(et.cache):[]}catch{return[]}}function Ju(){return{...Gu,...Qu(),...Uu()?Yu():{}}}function Yu(){let e=et.main?.paths||[],t=qu(),n={},r=new Set;return t.forEach(t=>{let i=t,a=()=>{let t=i;if(i=k(t),!i||t===i||r.has(t))return;if(e.indexOf(i)<0)return a();let o=A(t,`package.json`);if(r.add(t),!f(o))return a();try{let e=JSON.parse(g(o,`utf8`));n[e.name]=e.version}catch{}};a()}),n}function Xu(){return Wu||=Ju(),Wu}function Zu(){try{let e=A(process.cwd(),`package.json`);return JSON.parse(g(e,`utf8`))}catch{return{}}}function Qu(){let e=Zu();return{...e.dependencies,...e.devDependencies}}function $u(e){jn(()=>{console.error(e)});let t=Li();if(t===void 0){Wl&&Bn.warn(`No NodeClient was defined, we are exiting the process now.`),global.process.exit(1);return}let n=t.getOptions(),r=n?.shutdownTimeout&&n.shutdownTimeout>0?n.shutdownTimeout:2e3;t.close(r).then(e=>{e||Wl&&Bn.warn(`We reached the timeout for emptying the request buffer, still exiting now!`),global.process.exit(1)},e=>{Wl&&Bn.error(e)})}const ed=as((e={})=>{let t={exitEvenIfOtherHandlersAreRegistered:!1,...e};return{name:`OnUncaughtException`,setup(e){z&&global.process.on(`uncaughtException`,td(e,t))}}});function td(e,t){let n=!1,r=!1,i=!1,a,o=e.getOptions();return Object.assign(s=>{let c=$u;t.onFatalError?c=t.onFatalError:o.onFatalError&&(c=o.onFatalError);let l=global.process.listeners(`uncaughtException`).filter(e=>e.name!==`domainUncaughtExceptionClear`&&e.tag!==`sentry_tracingErrorCallback`&&e._errorHandler!==!0).length===0,u=t.exitEvenIfOtherHandlersAreRegistered||l;n?u&&(i?(Wl&&Bn.warn(`uncaught exception after calling fatal error shutdown callback - this is bad! forcing shutdown`),$u(s)):r||(r=!0,setTimeout(()=>{i||(i=!0,c(a,s))},2e3))):(a=s,n=!0,Li()===e&&Ho(s,{originalException:s,captureContext:{level:`fatal`},mechanism:{handled:!1,type:`auto.node.onuncaughtexception`}}),!i&&u&&(i=!0,c(s)))},{_errorHandler:!0})}const nd=[{name:`AI_NoOutputGeneratedError`},{name:`AbortError`}],rd=as(((e={})=>{let t={mode:e.mode??`warn`,ignore:[...nd,...e.ignore??[]]};return{name:`OnUnhandledRejection`,setup(e){global.process.on(`unhandledRejection`,ree(e,t))}}}));function eee(e){if(typeof e!=`object`||!e)return{name:``,message:String(e??``)};let t=e;return{name:typeof t.name==`string`?t.name:``,message:typeof t.message==`string`?t.message:String(e)}}function tee(e,t){let n=e.name===void 0||Vr(t.name,e.name,!0),r=e.message===void 0||Vr(t.message,e.message);return n&&r}function nee(e,t){let n=eee(t);return e.some(e=>tee(e,n))}function ree(e,t){return function(n,r){if(Li()!==e||nee(t.ignore??[],n))return;let i=t.mode===`strict`?`fatal`:`error`,a=n&&typeof n==`object`?n._sentry_active_span:void 0;(a?e=>so(a,e):e=>e())(()=>{Ho(n,{originalException:r,captureContext:{extra:{unhandledPromiseRejection:!0},level:i},mechanism:{handled:!1,type:`auto.node.onunhandledrejection`}})}),iee(n,t.mode)}}function iee(e,t){let n=`This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason:`;t===`warn`?jn(()=>{console.warn(n),console.error(e&&typeof e==`object`&&`stack`in e?e.stack:e)}):t===`strict`&&(jn(()=>{console.warn(n)}),$u(e))}const aee=as(()=>({name:`ProcessSession`,setupOnce(){Ko(),process.on(`beforeExit`,()=>{Ni().getSession()?.status!==`ok`&&qo()})}})),oee=as(((e={})=>{let t={sidecarUrl:e.sidecarUrl||`http://localhost:8969/stream`};return{name:`Spotlight`,setup(e){try{Bn.warn(`[Spotlight] It seems you're not in dev mode. Do you really want to have Spotlight enabled?`)}catch{}see(e,t)}}}));function see(e,t){let n=cee(t.sidecarUrl);if(!n)return;let r=0;e.on(`beforeEnvelope`,e=>{if(r>3){Bn.warn(`[Spotlight] Disabled Sentry -> Spotlight integration due to too many failed requests`);return}let t=Ja(e);co(()=>{let e=me.request({method:`POST`,path:n.pathname,hostname:n.hostname,port:n.port,headers:{"Content-Type":`application/x-sentry-envelope`}},e=>{e.statusCode&&e.statusCode>=200&&e.statusCode<400&&(r=0),e.on(`data`,()=>{}),e.on(`end`,()=>{}),e.setEncoding(`utf8`)});e.on(`error`,()=>{r++,Bn.warn(`[Spotlight] Failed to send envelope to Spotlight Sidecar`)}),e.write(t),e.end()})})}function cee(e){try{return new URL(`${e}`)}catch{Bn.warn(`[Spotlight] Invalid sidecar URL: ${e}`);return}}function lee(e){return!(e instanceof Error)||!(`errno`in e)||typeof e.errno!=`number`?!1:t.getSystemErrorMap().has(e.errno)}const uee=as((e={})=>({name:`NodeSystemError`,processEvent:(t,n,r)=>{if(!lee(n.originalException))return t;let i=n.originalException,a={...i};!r.getOptions().sendDefaultPii&&e.includePaths!==!0&&(delete a.path,delete a.dest),t.contexts={...t.contexts,node_system_error:a};for(let e of t.exception?.values||[])e.value&&(i.path&&e.value.includes(i.path)&&(e.value=e.value.replace(`'${i.path}'`,``).trim()),i.dest&&e.value.includes(i.dest)&&(e.value=e.value.replace(`'${i.dest}'`,``).trim()));return t}}));function id(e){return e.replace(/^[A-Z]:/,``).replace(/\\/g,`/`)}function dee(e=process.argv[1]?ol(process.argv[1]):process.cwd(),t=N===`\\`){let n=t?id(e):e;return e=>{if(!e)return;let r=t?id(e):e,{dir:i,base:a,ext:o}=j.parse(r);(o===`.js`||o===`.mjs`||o===`.cjs`)&&(a=a.slice(0,o.length*-1));let s=decodeURIComponent(a);i||=`.`;let c=i.lastIndexOf(`/node_modules`);if(c>-1)return`${i.slice(c+14).replace(/\//g,`.`)}:${s}`;if(i.startsWith(n)){let e=i.slice(n.length+1).replace(/\//g,`.`);return e?`${e}:${s}`:s}return s}}function fee(e){if(process.env.SENTRY_RELEASE)return process.env.SENTRY_RELEASE;if(wn.SENTRY_RELEASE?.id)return wn.SENTRY_RELEASE.id;let t=process.env.GITHUB_SHA||process.env.CI_MERGE_REQUEST_SOURCE_BRANCH_SHA||process.env.CI_BUILD_REF||process.env.CI_COMMIT_SHA||process.env.BITBUCKET_COMMIT,n=process.env.APPVEYOR_PULL_REQUEST_HEAD_COMMIT||process.env.APPVEYOR_REPO_COMMIT||process.env.CODEBUILD_RESOLVED_SOURCE_VERSION||process.env.AWS_COMMIT_ID||process.env.BUILD_SOURCEVERSION||process.env.GIT_CLONE_COMMIT_HASH||process.env.BUDDY_EXECUTION_REVISION||process.env.BUILDKITE_COMMIT||process.env.CIRCLE_SHA1||process.env.CIRRUS_CHANGE_IN_REPO||process.env.CF_REVISION||process.env.CM_COMMIT||process.env.CF_PAGES_COMMIT_SHA||process.env.DRONE_COMMIT_SHA||process.env.FC_GIT_COMMIT_SHA||process.env.HEROKU_TEST_RUN_COMMIT_VERSION||process.env.HEROKU_BUILD_COMMIT||process.env.HEROKU_SLUG_COMMIT||process.env.RAILWAY_GIT_COMMIT_SHA||process.env.RENDER_GIT_COMMIT||process.env.SEMAPHORE_GIT_SHA||process.env.TRAVIS_PULL_REQUEST_SHA||process.env.VERCEL_GIT_COMMIT_SHA||process.env.VERCEL_GITHUB_COMMIT_SHA||process.env.VERCEL_GITLAB_COMMIT_SHA||process.env.VERCEL_BITBUCKET_COMMIT_SHA||process.env.ZEIT_GITHUB_COMMIT_SHA||process.env.ZEIT_GITLAB_COMMIT_SHA||process.env.ZEIT_BITBUCKET_COMMIT_SHA,r=process.env.CI_COMMIT_ID||process.env.SOURCE_COMMIT||process.env.SOURCE_VERSION||process.env.GIT_COMMIT||process.env.COMMIT_REF||process.env.BUILD_VCS_NUMBER||process.env.CI_COMMIT_SHA;return t||n||r||e}const pee=Un(pl(dee())),ad=Symbol(`AgentBaseInternalState`);var mee=class extends me.Agent{constructor(e){super(e),this[ad]={}}isSecureEndpoint(e){if(e){if(typeof e.secureEndpoint==`boolean`)return e.secureEndpoint;if(typeof e.protocol==`string`)return e.protocol===`https:`}let{stack:t}=Error();return typeof t==`string`?t.split(`
@@ -75076,7 +75076,7 @@ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,`$1$2`).replace(/\
75076
75076
  `)+1;for(;e!==0;)this.onNewLine(this.offset+e),e=this.source.indexOf(`
75077
75077
  `,e)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){let t=e.items[e.items.length-1];switch(this.type){case`newline`:if(this.onKeyLine=!1,t.value){let n=`end`in t.value?t.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type===`comment`?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case`space`:case`comment`:if(t.value)e.items.push({start:[this.sourceToken]});else if(t.sep)t.sep.push(this.sourceToken);else{if(this.atIndentedComment(t.start,e.indent)){let n=e.items[e.items.length-2]?.value?.end;if(Array.isArray(n)){Array.prototype.push.apply(n,t.start),n.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return}if(this.indent>=e.indent){let n=!this.onKeyLine&&this.indent===e.indent,r=n&&(t.sep||t.explicitKey)&&this.type!==`seq-item-ind`,a=[];if(r&&t.sep&&!t.value){let n=[];for(let r=0;r<t.sep.length;++r){let i=t.sep[r];switch(i.type){case`newline`:n.push(r);break;case`space`:break;case`comment`:i.indent>e.indent&&(n.length=0);break;default:n.length=0}}n.length>=2&&(a=t.sep.splice(n[1]))}switch(this.type){case`anchor`:case`tag`:r||t.value?(a.push(this.sourceToken),e.items.push({start:a}),this.onKeyLine=!0):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case`explicit-key-ind`:!t.sep&&!t.explicitKey?(t.start.push(this.sourceToken),t.explicitKey=!0):r||t.value?(a.push(this.sourceToken),e.items.push({start:a,explicitKey:!0})):this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case`map-value-ind`:if(t.explicitKey)if(!t.sep)if(i(t.start,`newline`))Object.assign(t,{key:null,sep:[this.sourceToken]});else{let e=c(t.start);this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:e,key:null,sep:[this.sourceToken]}]})}else if(t.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(i(t.sep,`map-value-ind`))this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:a,key:null,sep:[this.sourceToken]}]});else if(o(t.key)&&!i(t.sep,`newline`)){let e=c(t.start),n=t.key,r=t.sep;r.push(this.sourceToken),delete t.key,delete t.sep,this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:e,key:n,sep:r}]})}else a.length>0?t.sep=t.sep.concat(a,this.sourceToken):t.sep.push(this.sourceToken);else t.sep?t.value||r?e.items.push({start:a,key:null,sep:[this.sourceToken]}):i(t.sep,`map-value-ind`)?this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:{let n=this.flowScalar(this.type);r||t.value?(e.items.push({start:a,key:n,sep:[]}),this.onKeyLine=!0):t.sep?this.stack.push(n):(Object.assign(t,{key:n,sep:[]}),this.onKeyLine=!0);return}default:{let r=this.startBlockValue(e);if(r){if(r.type===`block-seq`){if(!t.explicitKey&&t.sep&&!i(t.sep,`newline`)){yield*this.pop({type:`error`,offset:this.offset,message:`Unexpected block-seq-ind on same line with key`,source:this.source});return}}else n&&e.items.push({start:a});this.stack.push(r);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){let t=e.items[e.items.length-1];switch(this.type){case`newline`:if(t.value){let n=`end`in t.value?t.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type===`comment`?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.start.push(this.sourceToken);return;case`space`:case`comment`:if(t.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(t.start,e.indent)){let n=e.items[e.items.length-2]?.value?.end;if(Array.isArray(n)){Array.prototype.push.apply(n,t.start),n.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return;case`anchor`:case`tag`:if(t.value||this.indent<=e.indent)break;t.start.push(this.sourceToken);return;case`seq-item-ind`:if(this.indent!==e.indent)break;t.value||i(t.start,`seq-item-ind`)?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return}if(this.indent>e.indent){let t=this.startBlockValue(e);if(t){this.stack.push(t);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){let t=e.items[e.items.length-1];if(this.type===`flow-error-end`){let e;do yield*this.pop(),e=this.peek(1);while(e?.type===`flow-collection`)}else if(e.end.length===0){switch(this.type){case`comma`:case`explicit-key-ind`:!t||t.sep?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return;case`map-value-ind`:!t||t.value?e.items.push({start:[],key:null,sep:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});return;case`space`:case`comment`:case`newline`:case`anchor`:case`tag`:!t||t.value?e.items.push({start:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:{let n=this.flowScalar(this.type);!t||t.value?e.items.push({start:[],key:n,sep:[]}):t.sep?this.stack.push(n):Object.assign(t,{key:n,sep:[]});return}case`flow-map-end`:case`flow-seq-end`:e.end.push(this.sourceToken);return}let n=this.startBlockValue(e);n?this.stack.push(n):(yield*this.pop(),yield*this.step())}else{let t=this.peek(2);if(t.type===`block-map`&&(this.type===`map-value-ind`&&t.indent===e.indent||this.type===`newline`&&!t.items[t.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type===`map-value-ind`&&t.type!==`flow-collection`){let n=c(s(t));l(e);let r=e.end.splice(1,e.end.length);r.push(this.sourceToken);let i={type:`block-map`,offset:e.offset,indent:e.indent,items:[{start:n,key:e,sep:r}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=i}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let e=this.source.indexOf(`
75078
75078
  `)+1;for(;e!==0;)this.onNewLine(this.offset+e),e=this.source.indexOf(`
75079
- `,e)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:return this.flowScalar(this.type);case`block-scalar-header`:return{type:`block-scalar`,offset:this.offset,indent:this.indent,props:[this.sourceToken],source:``};case`flow-map-start`:case`flow-seq-start`:return{type:`flow-collection`,offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case`seq-item-ind`:return{type:`block-seq`,offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case`explicit-key-ind`:{this.onKeyLine=!0;let t=c(s(e));return t.push(this.sourceToken),{type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:t,explicitKey:!0}]}}case`map-value-ind`:{this.onKeyLine=!0;let t=c(s(e));return{type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:t,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){return this.type!==`comment`||this.indent<=t?!1:e.every(e=>e.type===`newline`||e.type===`space`)}*documentEnd(e){this.type!==`doc-mode`&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type===`newline`&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case`comma`:case`doc-start`:case`doc-end`:case`flow-seq-end`:case`flow-map-end`:case`map-value-ind`:yield*this.pop(),yield*this.step();break;case`newline`:this.onKeyLine=!1;default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type===`newline`&&(yield*this.pop())}}}})),xOe=G((e=>{var t=nq(),n=qK(),r=JK(),i=EK(),a=fK(),o=aq(),s=oq();function c(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new o.LineCounter||null,prettyErrors:t}}function l(e,n={}){let{lineCounter:i,prettyErrors:a}=c(n),o=new s.Parser(i?.addNewLine),l=new t.Composer(n),u=Array.from(l.compose(o.parse(e)));if(a&&i)for(let t of u)t.errors.forEach(r.prettifyError(e,i)),t.warnings.forEach(r.prettifyError(e,i));return u.length>0?u:Object.assign([],{empty:!0},l.streamInfo())}function u(e,n={}){let{lineCounter:i,prettyErrors:a}=c(n),o=new s.Parser(i?.addNewLine),l=new t.Composer(n),u=null;for(let t of l.compose(o.parse(e),!0,e.length))if(!u)u=t;else if(u.options.logLevel!==`silent`){u.errors.push(new r.YAMLParseError(t.range.slice(0,2),`MULTIPLE_DOCS`,`Source contains multiple documents; please use YAML.parseAllDocuments()`));break}return a&&i&&(u.errors.forEach(r.prettifyError(e,i)),u.warnings.forEach(r.prettifyError(e,i))),u}function d(e,t,n){let r;typeof t==`function`?r=t:n===void 0&&t&&typeof t==`object`&&(n=t);let a=u(e,n);if(!a)return null;if(a.warnings.forEach(e=>i.warn(a.options.logLevel,e)),a.errors.length>0){if(a.options.logLevel!==`silent`)throw a.errors[0];a.errors=[]}return a.toJS(Object.assign({reviver:r},n))}function f(e,t,r){let i=null;if(typeof t==`function`||Array.isArray(t)?i=t:r===void 0&&t&&(r=t),typeof r==`string`&&(r=r.length),typeof r==`number`){let e=Math.round(r);r=e<1?void 0:e>8?{indent:8}:{indent:e}}if(e===void 0){let{keepUndefined:e}=r??t??{};if(!e)return}return a.isDocument(e)&&!i?e.toString(r):new n.Document(e,i,r).toString(r)}e.parse=d,e.parseAllDocuments=l,e.parseDocument=u,e.stringify=f})),SOe=G((e=>{var t=nq(),n=qK(),r=KK(),i=JK(),a=yK(),o=fK(),s=kK(),c=bK(),l=jK(),u=NK();rq();var d=iq(),f=aq(),p=oq(),m=xOe(),h=pK();e.Composer=t.Composer,e.Document=n.Document,e.Schema=r.Schema,e.YAMLError=i.YAMLError,e.YAMLParseError=i.YAMLParseError,e.YAMLWarning=i.YAMLWarning,e.Alias=a.Alias,e.isAlias=o.isAlias,e.isCollection=o.isCollection,e.isDocument=o.isDocument,e.isMap=o.isMap,e.isNode=o.isNode,e.isPair=o.isPair,e.isScalar=o.isScalar,e.isSeq=o.isSeq,e.Pair=s.Pair,e.Scalar=c.Scalar,e.YAMLMap=l.YAMLMap,e.YAMLSeq=u.YAMLSeq,e.Lexer=d.Lexer,e.LineCounter=f.LineCounter,e.Parser=p.Parser,e.parse=m.parse,e.parseAllDocuments=m.parseAllDocuments,e.parseDocument=m.parseDocument,e.stringify=m.stringify,e.visit=h.visit,e.visitAsync=h.visitAsync}))();function COe(e){let t=e.trimStart();if(!t.startsWith(`---`))return{data:{},body:e};let n=t.match(/\r?\n---\s*(?:\r?\n|$)/);if(!n||n.index===void 0)return{data:{},body:e};let r=n.index,i=t.slice(3,r).trim(),a=t.slice(r+n[0].length).trim();try{let e=(0,SOe.parse)(i);return e&&typeof e==`object`&&!Array.isArray(e)?{data:e,body:a}:{data:{},body:a}}catch{return{data:{},body:e}}}function wOe(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``)}const TOe=dt([`codellm`,`agent`,`skills`]),sq=new class{skills=new Map;async loadSkills(e){let t=await mCe(),n=O.join(ee.homedir(),hn.configDirName,`skills`),r=e?O.join(e,hn.localConfigDirName,`skills`):void 0,i=await this.discoverSkills(t,`builtin`),a=await this.discoverSkills(n,`global`),o=r?await this.discoverSkills(r,`project`):[];this.skills.clear();for(let e of i)this.skills.set(e.id,e);for(let e of a)this.skills.set(e.id,e);for(let e of o)this.skills.set(e.id,e);TOe.info`skills loaded: builtin=${i.length} global=${a.length} project=${o.length}`}async discoverSkills(e,t){let n=[],r;try{r=await Te.readdir(e,{withFileTypes:!0})}catch{return n}r.sort((e,t)=>e.name.localeCompare(t.name));for(let i of r)if(i.isFile()&&i.name.endsWith(`.md`)){let r=O.join(e,i.name),a=await this.parseSkillFile(r,!1,t);a&&n.push(a)}else if(i.isDirectory()){let r=O.join(e,i.name,`SKILL.md`);try{await Te.access(r);let e=await this.parseSkillFile(r,!0,t);e&&n.push(e)}catch{}}return n}async parseSkillFile(e,t,n){try{let{data:r}=COe(await Te.readFile(e,`utf-8`)),i=wOe(t?O.basename(O.dirname(e)):O.basename(e,`.md`));return i?this.buildSkill(i,r,e,t,n):null}catch{return null}}buildSkill(e,t,n,r,i){let a=t.name,o=t.description,s=typeof a==`string`&&a.trim()?a.trim():e,c=typeof o==`string`&&o.trim()?o.trim():void 0;if(!c)return null;let l={name:s,description:c};typeof t[`argument-hint`]==`string`&&(l[`argument-hint`]=t[`argument-hint`]),typeof t[`disable-model-invocation`]==`boolean`&&(l[`disable-model-invocation`]=t[`disable-model-invocation`]),typeof t[`user-invocable`]==`boolean`&&(l[`user-invocable`]=t[`user-invocable`]),Array.isArray(t[`allowed-tools`])&&(l[`allowed-tools`]=t[`allowed-tools`].filter(e=>typeof e==`string`)),typeof t.license==`string`&&(l.license=t.license),typeof t.compatibility==`string`&&(l.compatibility=t.compatibility);let u=t.metadata;if(u&&typeof u==`object`&&!Array.isArray(u)){let e={};for(let[t,n]of Object.entries(u))typeof n==`string`&&(e[t]=n);Object.keys(e).length>0&&(l.metadata=e)}return{id:e,frontmatter:l,path:n,isDirectory:r,source:i}}get(e){return this.skills.get(e)}getAll(){return Array.from(this.skills.values()).filter(e=>e.frontmatter[`user-invocable`]!==!1)}getAllMetadata(){return this.getAll().map(e=>({id:e.id,name:e.frontmatter.name,description:e.frontmatter.description,location:e.path}))}search(e){let t=e.toLowerCase();return this.getAll().filter(e=>e.id.toLowerCase().includes(t)||e.frontmatter.name.toLowerCase().includes(t)||e.frontmatter.description.toLowerCase().includes(t))}matchSkill(e){if(!e.startsWith(`/`))return null;let t=e.slice(1).split(/\s+/);if(t.length===0)return null;let[n,...r]=t;if(!n)return null;let i=this.skills.get(n);return!i||i.frontmatter[`user-invocable`]===!1?null:{skill:i,args:r.join(` `)}}},cq=dt([`codellm`,`agent`,`tools`,`diagnostics`]);var EOe=class e extends fV{name=`get_diagnostics`;displayName=`GetDiagnostics`;description=`Get IDE diagnostics (errors, warnings, info) for a file or all open files.`;_provider;static Parameters=ZL({uri:Y().optional().describe(`Optional file URI to get diagnostics for. If not provided, gets diagnostics for all files.`)});parameters=e.Parameters;constructor(e){super(),this._provider=e}needsPermission(){return!1}async execute(e,t){let n=e.uri?[e.uri]:void 0;cq.debug`Getting diagnostics${e.uri?` for ${e.uri}`:` for all files`}`;let r=await this._provider.getDiagnostics(n);return cq.debug`Found ${r.length} diagnostics`,{type:`get_diagnostics`,diagnostics:r,total:r.length}}format(e,t){return JSON.stringify({...e,status:`success`})}parse(e){let t=bR(e);if(t.rejected)return{phase:`rejected`,toolType:`get_diagnostics`,data:{},summary:t.userNote?`Rejected \u00b7 "${t.userNote}"`:`Rejected`,...t.userNote!==void 0&&{userNote:t.userNote}};try{let t=JSON.parse(e),n=t.status===`error`?`error`:`success`,r=t.diagnostics?.filter(e=>e.severity===`error`).length??0,i=t.diagnostics?.filter(e=>e.severity===`warning`).length??0,a=[];return r>0&&a.push(`${r} error${r===1?``:`s`}`),i>0&&a.push(`${i} warning${i===1?``:`s`}`),{phase:n,toolType:`get_diagnostics`,data:t,summary:a.length>0?a.join(`, `):`${t.total??0} diagnostics`}}catch{return{phase:`success`,toolType:`get_diagnostics`,data:{},summary:`Completed`}}}},DOe=class extends CR{includeInApiDefinitions=!1};const lq=dt([`codellm`,`agent`,`tools`,`mcp`]);var OOe=class extends DOe{name;displayName;description;parameters;isReadonly=!1;mcpToolDefinition;constructor(e){super(),this.mcpToolDefinition=e,this.name=e.name,this.displayName=e.name,this.description=e.description||`MCP tool: ${e.name}`,this.parameters=this.createZodSchemaFromMCPSchema(e.inputSchema)}createZodSchemaFromMCPSchema(e){let t=e?.properties||{},n=e?.required||[],r={};for(let[e,i]of Object.entries(t)){let t=i,a=n.includes(e),o=this.jsonSchemaToZod(t);a||(o=o.optional()),r[e]=o}return ZL(r)}jsonSchemaToZod(e){switch(e.type){case`string`:return e.enum?oR(e.enum):Y();case`number`:case`integer`:return rxe;case`boolean`:return AR;case`array`:return e.items?YL(this.jsonSchemaToZod(e.items)):YL(qL());case`object`:if(e.properties){let t={},n=e.required||[];for(let[r,i]of Object.entries(e.properties)){let e=this.jsonSchemaToZod(i);n.includes(r)||(e=e.optional()),t[r]=e}return ZL(t)}return iR(Y(),qL());case`null`:return KL();default:return e.oneOf?this.jsonSchemaToZod(e.oneOf[0]):qL()}}async execute(e,t){if(lq.debug`Executing MCP tool: ${this.name} (server=${this.mcpToolDefinition.serverId})`,!t.mcpService)return lq.warn`MCP service not available for tool: ${this.name}`,{type:`mcp`,serverId:this.mcpToolDefinition.serverId,toolName:this.name,content:`MCP service not available`,isError:!0};try{let n=(await t.mcpService.listAllToolDefinitions()).find(e=>e.name===this.name);if(!n)throw Error(`MCP tool '${this.name}' not found`);let r=await t.mcpService.callTool(n.serverId,n.originalName||this.name,e);return{type:`mcp`,serverId:n.serverId,toolName:this.name,content:r.content||r,isError:r.isError||!1}}catch(e){return Dl(e instanceof Error?e:Error(String(e)),{context:`mcp-tool-execution`}),lq.error`MCP tool execution failed: ${this.name}: ${e instanceof Error?e.message:String(e)}`,{type:`mcp`,serverId:this.mcpToolDefinition.serverId,toolName:this.name,content:`MCP tool execution failed: ${e instanceof Error?e.message:String(e)}`,isError:!0}}}format(e,t){return JSON.stringify({type:`mcp`,status:e.isError?`error`:`success`,serverId:e.serverId,toolName:e.toolName,content:e.content})}parse(e){let t=bR(e);if(t.rejected)return{phase:`rejected`,toolType:`mcp`,data:{},summary:t.userNote?`Rejected \u00b7 "${t.userNote}"`:`Rejected`,...t.userNote!==void 0&&{userNote:t.userNote}};try{let t=JSON.parse(e);return t.status===`error`||t.isError?{phase:`error`,toolType:`mcp`,data:t,summary:`Error`,errorMessage:typeof t.content==`string`?t.content:`MCP error`}:{phase:`success`,toolType:`mcp`,data:t,summary:`Executed successfully`}}catch{}return e.startsWith(`Error:`)?{phase:`error`,toolType:`mcp`,data:{},summary:e,errorMessage:e}:{phase:`success`,toolType:`mcp`,data:{},summary:`Executed successfully`}}};const kOe=new Set([`read`,`ls`,`grep`,`codebase_search`,`web_search`,`web_fetch`,`bash_output`,`kill_shell`,`get_diagnostics`]);function AOe(e){if(e.type!==`tool_call`)return null;let t=e.toolUseRequest.name;return kOe.has(t)?`read_search`:e.parsedResult?.data&&e.parsedResult.data.serverId?`mcp`:null}function jOe(e){if(e.type!==`tool_call`)return null;let t=e.parsedResult?.data;return t?.serverId?`${t.serverId}:${e.toolUseRequest.name}`:null}function MOe(e,t){if(t===`mcp`){let t=e[0];if(t?.type===`tool_call`){let n=t.toolUseRequest.name,r=t.parsedResult?.data?.serverId??`mcp`;return`${n} \u00d7 ${e.length} (${r})`}}let n=new Map;for(let t of e){if(t.type!==`tool_call`)continue;let e=t.toolUseRequest.name;n.set(e,(n.get(e)??0)+1)}let r=[];for(let[e,t]of n){let n=NOe(e);r.push(t>1?`${n} ${t} ${uq(e,t)}`:`${n} 1 ${uq(e,1)}`)}return r.join(`, `)}function NOe(e){switch(e){case`read`:return`read`;case`ls`:return`listed`;case`grep`:return`searched`;case`codebase_search`:return`searched`;case`web_search`:return`web searched`;case`web_fetch`:return`fetched`;case`bash_output`:return`got output from`;case`kill_shell`:return`killed`;case`get_diagnostics`:return`got diagnostics from`;default:return e}}function uq(e,t){let n=t===1?``:`s`;switch(e){case`read`:return`file${n}`;case`ls`:return`director${t===1?`y`:`ies`}`;case`grep`:return`pattern${n}`;case`codebase_search`:return`quer${t===1?`y`:`ies`}`;case`web_search`:return`quer${t===1?`y`:`ies`}`;case`web_fetch`:return`URL${n}`;case`kill_shell`:return`shell${n}`;default:return`call${n}`}}function POe(e){let t=[],n=[],r=null,i=null;function a(){n.length!==0&&(n.length===1?t.push(n[0]):t.push({type:`tool_group`,id:crypto.randomUUID(),tools:n,category:r,summary:MOe(n,r)}),n=[],r=null,i=null)}for(let o of e){let e=AOe(o);if(e===null){a(),t.push(o);continue}let s=e===`mcp`?jOe(o):null,c=o.type===`tool_call`&&o.toolPhase===`error`;(e!==r||e===`mcp`&&s!==i)&&(a(),r=e,i=s),n.push(o),c&&a()}return a(),t}function FOe(e){return e.length>1e4?!0:e.split(/\r\n|\r|\n/).length>5e3}var IOe=class{_tmpDir=null;_counter=0;_ensureDir(){if(!this._tmpDir){let e=O.join(ee.homedir(),hn.configDirName,`tmp`);c.mkdirSync(e,{recursive:!0}),this._tmpDir=c.mkdtempSync(O.join(e,`codellm-prompt-`))}return this._tmpDir}savePrompt(e){let t=this._ensureDir();this._counter++;let n=O.join(t,`prompt-${this._counter}.txt`);return c.writeFileSync(n,e,`utf-8`),n}cleanup(){if(this._tmpDir){try{c.rmSync(this._tmpDir,{recursive:!0,force:!0})}catch{}this._tmpDir=null,this._counter=0}}};const LOe={run_in_terminal:`bash`,get_terminal_output:`bash_output`,fetch_url:`web_fetch`},ROe={bash:{id:`shellId`,isBackground:`runInBackground`},bash_output:{id:`shellId`}};function dq(e){let t=LOe[e.name];t&&(e.name=t);let n=ROe[e.name];if(n&&e.input&&typeof e.input==`object`){let t=e.input;for(let[e,r]of Object.entries(n))e in t&&!(r in t)&&(t[r]=t[e],delete t[e])}}function fq(e){if(e.type===`code_llm_agent_tool_request`&&e.toolUseRequest){let t=Array.isArray(e.toolUseRequest)?e.toolUseRequest:[e.toolUseRequest];for(let e of t)dq(e)}if(Array.isArray(e.segments))for(let t of e.segments)fq(t)}function zOe(e){for(let t of e){if(t.toolUseRequest){let e=Array.isArray(t.toolUseRequest)?t.toolUseRequest:[t.toolUseRequest];for(let t of e)dq(t)}if(Array.isArray(t.segments))for(let e of t.segments)fq(e)}}var pq=class{sessionId;_logger=dt([`codellm`,`agent`,`session`]);_workspace;_terminalService;_registry;_mcpService;_config;_conversationId=null;_mode;_model;_running=!1;_abortController=null;_initialized=!1;_uploadedDocs=new Set;_rules=[];_markdownContext=``;_rulesEngine;_toolEventBuffer=[];_messageQueue=[];_promptFileManager=new IOe;_swapFolder=null;_setFolder=null;onAutoRestart=null;mcp;rules;constructor(e){let t=sF(aF(e.primaryWorkspace)),n=Array.from(new Set([t,...e.allowedDirectories.map(e=>sF(aF(e)))]));this._config={...e,primaryWorkspace:t,allowedDirectories:n},this.sessionId=crypto.randomUUID(),this._mode=e.mode??xd.Normal,this._model=e.model??``,this._logger.info(`Creating AgentSession (workspace={workspace}, mode={mode})`,{workspace:t,mode:this._mode}),this._workspace=new Swe(t),this._terminalService=new $De(t),this._terminalService.onBackgroundComplete=(e,t,n)=>{let r=`Background process (id=${e}) running \`${t}\` has ${n===0?`completed successfully`:`exited with code ${n}`}.`;this.nq(r,{hidden:!0}),!this._running&&this.onAutoRestart&&this.onAutoRestart(r)},this._registry=MV(),e.disabledBuiltinTools?.length&&this._registry.setDisabledTools(e.disabledBuiltinTools),e.diagnosticsProvider&&this._registry.register(new EOe(e.diagnosticsProvider)),this._mcpService=new uK;let r=e.config?.get(`permissions`)??{};this._rulesEngine=new VCe({rules:{allow:[...r.allow??[],...e.permissionRules?.allow??[]],deny:[...r.deny??[],...e.permissionRules?.deny??[]],ask:[...r.ask??[],...e.permissionRules?.ask??[]]},cliAllowed:e.cliAllowedTools,cliDenied:e.cliDisallowedTools}),this.mcp=this._buildMcpManager(),this.rules=this._buildRulesManager()}async _ensureInitialized(){if(!this._initialized){if(this._initialized=!0,this._logger.debug(`Initializing session`),this._config.config){await this._config.config.load();let e=this._config.config.get(`baseUrl`);e&&(this._config.apiClient.setUrl(e),this._config.apiClient.resetEndpoints(),await this._config.apiClient.getApiEndpoint());let t=this._config.config.get(`permissions`);if(t){for(let e of t.allow??[])this._rulesEngine.addAllowRule(e);for(let e of t.deny??[])this._rulesEngine.addDenyRule(e);for(let e of t.ask??[])this._rulesEngine.addAskRule(e)}let n=this._config.config.get(`additionalDirectories`);if(n)for(let e of n){let t=sF(aF(e));if(!this._config.allowedDirectories.includes(t)){this._config.allowedDirectories.push(t);let e=t.endsWith(`/`)?t:t+`/`;this._rulesEngine.addAllowRule(`Bash(cd ${e}*)`),this._rulesEngine.addAllowRule(`Bash(cd ${t})`)}}}await Promise.all([this._mcpService.initialize(this._config.primaryWorkspace,this._config.mcpServers,this._config.onMcpAuthRequired),this._config.enableSkills?sq.loadSkills(this._config.primaryWorkspace):Promise.resolve()])}}_buildMcpManager(){return{listServers:()=>this._mcpService.getConnectedServers(),addServer:async e=>{let t=this._mcpService.getConnectedServers().map(e=>e.config);return this._mcpService.initialize(this._config.primaryWorkspace,[...t,e],this._config.onMcpAuthRequired)},removeServer:async e=>{let t=this._mcpService.getConnectedServers().map(e=>e.config).filter(t=>t.id!==e);await this._mcpService.initialize(this._config.primaryWorkspace,t,this._config.onMcpAuthRequired)},callTool:(e,t,n)=>this._mcpService.callTool(e,t,n),getTools:()=>this._mcpService.getAbacusMcpTools(),refresh:async e=>{await this._mcpService.initialize(e??this._config.primaryWorkspace,this._config.mcpServers,this._config.onMcpAuthRequired)},authenticateServer:(e,t)=>this._mcpService.authenticateServer(e,t)}}_buildRulesManager(){return{getAll:()=>this._rules,getMarkdownContext:()=>this._markdownContext,reload:async()=>{this._rules=[],this._markdownContext=``}}}_buildBrowserActionDescription(e){switch(e.name){case`perform_interactive_element_action`:{let{action:t,id:n,text:r}=e.input,i=t??`interact with`,a={click:`Click`,type:`Type`,hover:`Hover`,scroll:`Scroll`,focus:`Focus`,select:`Select`}[i]??i;return i===`type`&&r&&n?`Type "${r}" into element ${n}`:i===`select`&&r&&n?`Select "${r}" in element ${n}`:n?`${a} element ${n}`:a}case`computer`:{let{action:t,coordinate:n,text:r}=e.input,i=t??``;return i===`screenshot`?`Screenshot`:i===`key`&&r?`Key: ${r}`:i===`type`&&r?`Type "${r}"`:n?`${i} at (${String(n[0])}, ${String(n[1])})`:i||`Computer action`}case`navigate_to`:return`Navigate to ${e.input.url??``}`;case`new_tab`:return`Open new tab${e.input.url?`: ${e.input.url}`:``}`;case`switch_active_tab`:return`Switch to tab ${String(e.input.id??``)}`;case`close_tab`:return`Close tab ${String(e.input.id??``)}`;case`refresh_tab`:return`Refresh tab`;case`get_tab_content`:return`Get tab content`;case`get_interactive_elements`:return`Get interactive elements`;default:return e.name}}_buildPermissionRequest(e,t){let n=this._registry.get(e.name)?.displayName??e.name;if(!jV.isBuiltinRequest(e))return{type:`generic`,tool:e,displayName:n,toolName:n,inputSummary:JSON.stringify(e.input).slice(0,200)};switch(e.name){case`read`:{let t=aF(e.input.filePath??``),r=sF(O.isAbsolute(t)?t:O.resolve(this._config.primaryWorkspace,t));return{type:`read_outside_directory`,tool:e,displayName:n,filePath:r,resolvedPath:r,deducedDirectory:O.dirname(r)}}case`edit`:{let r=t._prepareResult;if(r?.outsideWorkspace){let t=sF(r.resolvedPath??e.input.filePath??``);return{type:`edit_outside_directory`,tool:e,displayName:n,filePath:t,resolvedPath:t,deducedDirectory:O.dirname(t)}}if(r?.error)return{type:`edit_file`,tool:e,displayName:n,filePath:e.input.filePath??``,originalContent:``,newContent:``};let i=r?.currentContent??``,a=r?.newContent??``;return{type:`edit_file`,tool:e,displayName:n,filePath:e.input.filePath??``,originalContent:i,newContent:a}}case`write`:{let r=t._prepareResult;if(r?.outsideWorkspace){let t=sF(r.resolvedPath??e.input.filePath??``);return{type:`write_outside_directory`,tool:e,displayName:n,filePath:t,resolvedPath:t,deducedDirectory:O.dirname(t),isNewFile:!r?.fileExists}}return{type:`write_file`,tool:e,displayName:n,filePath:e.input.filePath??``,originalContent:r?.currentContent??``,content:e.input.content??``,isNewFile:!r?.fileExists}}case`bash`:{let t=e.input.command??``;return{type:`run_terminal`,tool:e,displayName:n,command:t,cwd:this._config.primaryWorkspace,background:!!(e.input.runInBackground??!1),unmatchedPatterns:this._rulesEngine.getUnmatchedBashSegments(t,this._config.primaryWorkspace)}}case`exit_plan_mode`:{let r=t._prepareResult;return{type:`exit_plan_mode`,tool:e,displayName:n,planFilePath:e.input.planFilePath??``,planContent:String(r?.planContent??``)}}case`ask_user_question`:return{type:`ask_user_question`,tool:e,displayName:n,questions:Array.isArray(e.input.questions)?e.input.questions:[]};case`navigate_to`:return{type:`browser_action`,tool:e,displayName:n,action:e.name,url:e.input.url,description:this._buildBrowserActionDescription(e)};case`computer`:case`perform_interactive_element_action`:case`switch_active_tab`:case`close_tab`:case`refresh_tab`:case`get_tab_content`:case`get_interactive_elements`:case`new_tab`:return{type:`browser_action`,tool:e,displayName:n,action:e.name,description:this._buildBrowserActionDescription(e)};case`notebook_edit`:{let r=t._prepareResult;if(r?.outsideWorkspace){let t=sF(r.resolvedPath??e.input.notebookPath??``);return{type:`notebook_edit_outside_directory`,tool:e,displayName:n,filePath:t,resolvedPath:t,deducedDirectory:O.dirname(t)}}let i=r?.notebook,a=e.input.cellId,o=e.input.editMode??`replace`,s=``;if(a&&i?.cells){let e=i.cells.find(e=>e.id===a||e.metadata?.id===a);e&&(s=Array.isArray(e.source)?e.source.join(``):String(e.source??``))}return{type:`notebook_edit`,tool:e,displayName:n,notebookPath:e.input.notebookPath??``,cellId:a,editMode:o,cellType:e.input.cellType,originalContent:s,newContent:e.input.newSource??``}}default:return{type:`generic`,tool:e,displayName:n,toolName:n,inputSummary:JSON.stringify(e.input).slice(0,200)}}}_buildExecuteTools(e){return async(t,n,r)=>{let i=new AbortController,a=()=>i.abort(`interrupted`);n&&(n.aborted?i.abort(`interrupted`):n.addEventListener(`abort`,a,{once:!0}));let o=[],s=(e,t,n)=>{let r=n?.storageContent??t;return{id:e.id,content:t,...n?.rejected&&{rejected:!0},parsedResult:r.startsWith(`Error:`)?{phase:`error`,toolType:e.name,data:{},summary:r,errorMessage:r}:this._registry.parse(e.name,r)}};try{let a=async t=>{if(i.signal.aborted)return{resolved:!0,result:s(t,JSON.stringify({reason:yR.INTERRUPTED}),{rejected:!0})};let a={workspace:this._workspace,terminalService:this._terminalService,apiClient:this._config.apiClient,workspacePath:this._config.primaryWorkspace,conversationId:e,agentMode:this._mode,toolCallId:t.id,status:`executing`,uploadedDocs:this._uploadedDocs,allowEditingPaths:this._config.allowedDirectories,abortController:i,permissionProvider:this._config.permissionProvider,rulesEngine:this._rulesEngine,getAgentMode:()=>this._mode,setAgentMode:e=>{this._mode=e},mcpService:{listAllToolDefinitions:async()=>this._mcpService.getAbacusMcpTools(),callTool:(e,t,n)=>this._mcpService.callTool(e,t,n),reloadConnections:async()=>{await this._mcpService.initialize(this._config.primaryWorkspace,this._config.mcpServers,this._config.onMcpAuthRequired)},getServerStatus:e=>{let t=this._mcpService.getConnectedServers().find(t=>t.config.id===e);return t?t.status===`connected`?`running`:`error`:`stopped`}},...this._rules.length>0&&{rules:this._rules},...this._config.planDirectory!==void 0&&{plansDir:this._config.planDirectory},...this._config.clientType&&{clientType:this._config.clientType},...r&&{emitEvent:r},...r&&{onOutputUpdate:(e,t)=>{r({type:`tool_output_update`,toolCallId:e,output:t})}}};try{if(this._registry.isDisabled(t.name))return{resolved:!0,result:s(t,`Error: tool '${t.name}' is disabled in this environment`)};r?.({type:`tool_execution_start`,tool:t});let e=this._registry.createToolInstance(t.name,t.input??{},a);if(await e.prepare(),t.name===`edit`&&jV.isBuiltinRequest(t)&&!e._prepareResult?.error){let n=e._prepareResult,i=a.workspacePath,o=a.plansDir??O.join(te(),hn.configDirName,`plans`),s=lF(O.resolve(i,t.input.filePath??``),O.resolve(i,o)),c={originalContent:n?.currentContent??``,newContent:n?.newContent??``,isPlanFile:s,isNewFile:!(n?.fileExists??!0)},l={type:`tool_display_data`,toolCallId:t.id,data:c};r?.(l),this._toolEventBuffer.push(l)}if(t.name===`notebook_edit`&&jV.isBuiltinRequest(t)&&!e._prepareResult?.error){let n=e._prepareResult?.notebook,i=t.input.cellId,a=``;if(i&&n?.cells){let e=n.cells.find(e=>e.id===i||e.metadata?.id===i);e&&(a=Array.isArray(e.source)?e.source.join(``):String(e.source??``))}let o={originalContent:a,newContent:t.input.newSource??``},s={type:`tool_display_data`,toolCallId:t.id,data:o};r?.(s),this._toolEventBuffer.push(s)}if(t.name===`write`&&jV.isBuiltinRequest(t)&&!e._prepareResult?.error){let n=e._prepareResult,i={originalContent:n?.currentContent??``,newContent:t.input.content??``,isNewFile:!(n?.fileExists??!0)},a={type:`tool_display_data`,toolCallId:t.id,data:i};r?.(a),this._toolEventBuffer.push(a)}let i=this._mode===xd.Yolo&&t.name!==`ask_user_question`;if(!i&&e.needsPermission()){let i=this._registry.get(t.name)?.displayName??t.name,o=BV(t),c=this._rulesEngine.evaluate(i,o);if(c===`deny`)return{resolved:!0,result:s(t,JSON.stringify({reason:yR.REJECTED}),{rejected:!0})};if(c!==`allow`){let i=this._buildPermissionRequest(t,e);if(this._config.permissionProvider.needsPermission(i)){let o={type:`status_changed`,status:Sd.WaitingForToolPermission};r?.(o),this._toolEventBuffer.push(o);let c;try{let e=this._config.permissionProvider.requestPermission(i);if(n){let t,r=new Promise((e,r)=>{n.aborted?r(Error(`interrupted`)):(t=()=>r(Error(`interrupted`)),n.addEventListener(`abort`,t,{once:!0}))});try{c=await Promise.race([e,r])}finally{t&&n.removeEventListener(`abort`,t)}}else c=await e}catch{return{resolved:!0,result:s(t,JSON.stringify({reason:yR.INTERRUPTED}),{rejected:!0})}}if(r?.({type:`status_changed`,status:Sd.ExecutingTool}),this._toolEventBuffer.push({type:`status_changed`,status:Sd.ExecutingTool}),c===`reject`)return{resolved:!0,result:s(t,JSON.stringify({reason:yR.REJECTED}),{rejected:!0})};if(typeof c==`object`&&c.type===`reject_with_message`)return{resolved:!0,result:s(t,JSON.stringify({reason:yR.USER_MESSAGE,message:c.message}),{rejected:!0})};if(c===`allowAlways`||c===`allowYolo`||c===`accept`){if(c===`allowAlways`&&(i.type===`read_outside_directory`||i.type===`write_outside_directory`||i.type===`edit_outside_directory`||i.type===`notebook_edit_outside_directory`)){if(this.addAllowedDirectory(i.deducedDirectory),this._config.config){let e=this._config.config.get(`additionalDirectories`)??[];e.includes(i.deducedDirectory)||this._config.config.set(`additionalDirectories`,[...e,i.deducedDirectory],`local`)}}else if(t.name===`exit_plan_mode`){let e=c===`allowYolo`?xd.Yolo:c===`allowAlways`?xd.AcceptEdits:xd.Normal;this._mode=e,a.agentMode=e,r?.({type:`mode_changed`,mode:e}),this._toolEventBuffer.push({type:`mode_changed`,mode:e})}else if(c===`allowAlways`){let e=Dd(i.type);this._mode=e,a.agentMode=e,r?.({type:`mode_changed`,mode:e}),this._toolEventBuffer.push({type:`mode_changed`,mode:e})}}if(typeof c==`object`&&c.type===`accept_with_message`&&this.nq(c.message),typeof c==`object`&&c.type===`question_answers`&&e.mergeParams({answers:c.answers}),typeof c==`object`&&c.type===`allow_always_with_rule`&&(this._rulesEngine.addAllowRule(c.rule),this._config.config)){let e=this._config.config.get(`permissions`)??{},t=[...e.allow??[],c.rule];this._config.config.set(`permissions`,{...e,allow:t},`local`)}if(typeof c==`object`&&c.type===`allow_always_with_rules`){for(let e of c.rules)this._rulesEngine.addAllowRule(e);if(this._config.config){let e=this._config.config.get(`permissions`)??{},t=[...e.allow??[],...c.rules];this._config.config.set(`permissions`,{...e,allow:t},`local`)}}}}}return t.name===`enter_plan_mode`&&(this._mode=xd.PlanMode,a.agentMode=xd.PlanMode,r?.({type:`mode_changed`,mode:xd.PlanMode}),this._toolEventBuffer.push({type:`mode_changed`,mode:xd.PlanMode})),t.name===`exit_plan_mode`&&i&&(this._mode=xd.Normal,a.agentMode=xd.Normal,r?.({type:`mode_changed`,mode:xd.Normal}),this._toolEventBuffer.push({type:`mode_changed`,mode:xd.Normal})),{resolved:!1,call:t,instance:e,ctx:a}}catch(e){return i.signal.aborted?{resolved:!0,result:s(t,JSON.stringify({reason:yR.INTERRUPTED}),{rejected:!0})}:{resolved:!0,result:s(t,`Error: ${e instanceof Error?e.message:String(e)}`)}}},c=async e=>{try{if(await e.instance.execute(),i.signal.aborted)return s(e.call,JSON.stringify({reason:yR.INTERRUPTED}),{rejected:!0});let t=e.instance.formatResultForLLM(),n=e.instance.formatResult(),r=typeof t==`string`?t:JSON.stringify(t);return s(e.call,r,{storageContent:n===r?void 0:n})}catch(t){if(i.signal.aborted)return s(e.call,JSON.stringify({reason:yR.INTERRUPTED}),{rejected:!0});let n=t instanceof Error?t.message:String(t);return s(e.call,`Error: ${n}`)}},l=0,u=!1;for(;l<t.length;){let e=e=>this._registry.get(e.name)?.concurrency(e.input,this._config.primaryWorkspace)??!1;if(u){let n=t[l],i=!!e(n),a=this._registry.get(n.name),c=a?!a.isReadonly:!1;if(i||c){let e=s(n,SR);o.push(e),r?.({type:`tool_execution_complete`,tool:n,result:e}),l++;continue}}if(e(t[l])){let n=l+1;for(;n<t.length&&e(t[n]);)n++;if(n-l>1){let i=t.slice(l,n),d=i.map(e);l=n;let f=[[]],p=[new Set];for(let e=0;e<i.length;e++){let t=d[e],n=f[f.length-1],r=p[p.length-1];typeof t==`string`&&r.has(t)&&(f.push([]),p.push(new Set),n=f[f.length-1],r=p[p.length-1]),typeof t==`string`&&r.add(t),n.push(e)}let m=new Map,h=new Map,g=!1;for(let e of f){if(g){for(let t of e){let e=s(i[t],SR);o.push(e),r?.({type:`tool_execution_complete`,tool:i[t],result:e})}continue}for(let t of e)m.set(t,await a(i[t]));for(let t of e){let e=m.get(t);e.resolved&&r?.({type:`tool_execution_complete`,tool:i[t],result:e.result})}let t=e.filter(e=>!m.get(e).resolved).map(async e=>{let t=m.get(e);if(!t.resolved){let n=await c(t);h.set(e,n),r?.({type:`tool_execution_complete`,tool:i[e],result:n})}});for(let e=0;e<t.length;e+=10)await Promise.all(t.slice(e,e+10));for(let t of e){let e=m.get(t),n=e.resolved?e.result:h.get(t);o.push(n),!g&&!n.rejected&&n.content.startsWith(`Error:`)&&(g=!0)}}g&&(u=!0);continue}}let n=t[l];l++;let i=await a(n);if(i.resolved){o.push(i.result),r?.({type:`tool_execution_complete`,tool:n,result:i.result});continue}let d=await c(i);o.push(d),r?.({type:`tool_execution_complete`,tool:n,result:d})}return o}finally{n&&n.removeEventListener(`abort`,a)}}}async createConversation(){let e=await this._config.apiClient.createCodellmDeploymentConversation(`CODE_LLM_AGENT`,this._config.clientType);if(e?.success===!1&&e.error)throw Error(e.error);let t=e?.result?.deploymentConversationId;if(!t)throw Error(`Failed to create conversation: no deployment conversation ID returned`);return this._conversationId=t,t}async loadConversation(e){this._conversationId=e;let t=await this._config.apiClient.getDeploymentConversation({deploymentConversationId:e}),n=t?.result?.history??[],r=t?.result?.name??void 0;zOe(n);let i=POe(this._hydrateHistory(n)),a;for(let e=n.length-1;e>=0;e--){let t=n[e]?.inputParams?.llmName;if(t){a=t;break}}return{...r!==void 0&&{title:r},...a!==void 0&&{llmName:a},segments:i}}switchConversation(e){return this._conversationId=e,this._uploadedDocs.clear(),Promise.resolve()}resetConversation(){this._conversationId=null,this._uploadedDocs.clear()}async deleteConversation(e){await this._config.apiClient.deleteDeploymentConversation?.({deploymentConversationId:e}),this._conversationId===e&&(this._conversationId=null)}async listConversations(){return((await this._config.apiClient.getConversationsList(`CODE_LLM_AGENT`))?.result??[]).map(e=>({id:e.deploymentConversationId??``,createdAt:new Date(e.createdAt??Date.now()),updatedAt:new Date(e.lastEventCreatedAt??e.createdAt??Date.now()),...e.name!==void 0&&{title:e.name}}))}_hydrateHistory(e){let t=[],n=[];for(let r of e){if(r.role===`USER`){let e=this._extractParallelToolResponses(r);e.length>0&&this._attachToolResults(n,e),n=[];let i=(r.prompt??r.text??``).trim();i&&t.push({type:`text`,id:crypto.randomUUID(),source:`user`,content:i});continue}n=[];for(let e of r.segments??[]){if(e.isThoughts){let n=typeof e.segment==`string`?e.segment:e.segment?.segment??``;t.push({type:`thinking`,id:crypto.randomUUID(),content:n,isSpinny:!1});continue}if(e.type===`code_llm_agent_tool_request`&&e.toolUseRequest){let r=Array.isArray(e.toolUseRequest)?e.toolUseRequest:[e.toolUseRequest];for(let e of r){let r={type:`tool_call`,id:crypto.randomUUID(),toolUseRequest:e,toolPhase:`unknown`};t.push(r),n.push(r)}continue}if(e.type===`code_llm_notification`){t.push({type:`notification`,id:crypto.randomUUID(),message:e.message??(typeof e.segment==`string`?e.segment:``)??``,severity:e.severity??`info`,...e.actions!==void 0&&{actions:e.actions}});continue}let r=typeof e.segment==`string`?e.segment:e.segment?.segment;r&&t.push({type:`text`,id:crypto.randomUUID(),source:`bot`,content:r})}}return this._detectAbandonedTools(t),t}_extractParallelToolResponses(e){if(Array.isArray(e.parallelToolResponses))return e.parallelToolResponses;for(let t of e.segments??[])if(Array.isArray(t.parallelToolResponses)&&t.parallelToolResponses.length>0)return t.parallelToolResponses;return[]}_attachToolResults(e,t){for(let n=0;n<Math.min(e.length,t.length);n++){let r=e[n],i=t[n],a=r.toolUseRequest.name,o=bR(i);r.toolUseResult={id:r.toolUseRequest.id,content:i,...o.rejected&&{rejected:!0}};let s=this._registry.parse(a,i);o.rejected&&(s.phase=`rejected`,o.userNote!==void 0&&(s.userNote=o.userNote)),r.parsedResult=s,r.toolPhase=s.phase}}_detectAbandonedTools(e){let t=new Set([`todo_write`]);for(let n=0;n<e.length;n++){let r=e[n];if(r.type===`tool_call`&&!r.toolUseResult&&!t.has(r.toolUseRequest.name)){let t=e.slice(n+1).some(e=>e.type===`text`||e.type===`tool_call`),i=t?`abandoned`:`abandoned_last`;r.toolPhase=i,r.parsedResult={phase:i,toolType:r.toolUseRequest.name,data:{},summary:t?`Abandoned`:`Abandoned · What should I do next?`}}}}_rewriteIfLargePrompt(e){return FOe(e)?`The large prompt is saved in ${this._promptFileManager.savePrompt(e)} file. Follow the instructions in it.`:e}async*send(e,t){if(await this._ensureInitialized(),this._logger.info(`Sending message (conversationId={conversationId}, mode={mode}, model={model})`,{conversationId:this._conversationId,mode:this._mode,model:this._model}),!this._conversationId)for(let e=0;e<8;e++)try{await this.createConversation();break}catch(t){if(!Vl(t)||e>=7)throw t;let n=Math.min((e+1)*2e3,1e4);yield{type:`retry`,attempt:e+1,maxAttempts:8,delayMs:n,isNetworkError:!0},await BR(n)}this._running=!0,this._abortController=new AbortController;let n=this._buildExecuteTools(this._conversationId);try{yield{type:`status_changed`,status:Sd.Submitted};let r=this._rewriteIfLargePrompt(e),i=!0;for(;;){let e=this._mcpService.getAbacusMcpTools();e.length>0&&this._registry.registerMCPTools(e.map(e=>new OOe(e)));let a=this._registry.getApiToolDefinitions(),o=this._config.isPrintMode?a.filter(e=>e.name!==`ask_user_question`):a,s={apiClient:this._config.apiClient,conversationId:this._conversationId,model:this._model,workspacePath:this._config.primaryWorkspace,...this._swapFolder&&{swapFolder:this._swapFolder},...this._setFolder&&{setFolder:this._setFolder},uploadedDocs:this._uploadedDocs,supportedTools:o,supportedSubAgents:RR().map(e=>({name:e})),...e.length>0&&{mcpTools:e},...this._rules.length>0&&{rules:this._rules},...this._config.enableSkills&&(()=>{let e=sq.getAllMetadata();return e.length>0?{availableSkills:e}:{}})(),...this._config.enableSkills&&t?.activeSkills&&t.activeSkills.length>0&&{activeSkills:t.activeSkills},...this._config.isPrintMode!==void 0&&{isPrintMode:this._config.isPrintMode},...this._config.enablePromptRewrite!==void 0&&{enablePromptRewrite:this._config.enablePromptRewrite},...this._config.supportsThoughtStreaming!==void 0&&{supportsThoughtStreaming:this._config.supportsThoughtStreaming},agentMode:this._mode,...this._config.config?.get(`client`)&&{client:this._config.config.get(`client`)},...this._config.maxTurns!==void 0&&{maxTurns:this._config.maxTurns},...i&&t?.diagnosticIssues!==void 0&&{diagnosticIssues:t.diagnosticIssues},...i&&t?.currentFile!==void 0&&{currentFile:O.isAbsolute(t.currentFile)?t.currentFile:O.resolve(this._config.primaryWorkspace,t.currentFile)},...i&&t?.selectionStartLine!==void 0&&{selectionStartLine:t.selectionStartLine},...i&&t?.selectionEndLine!==void 0&&{selectionEndLine:t.selectionEndLine},executeTools:n,getConcurrency:e=>this._registry.get(e.name)?.concurrency(e.input,this._config.primaryWorkspace)??!1,drainEvents:()=>{let e=this._toolEventBuffer.slice();return this._toolEventBuffer.length=0,e},dequeueAllQueuedMessage:e=>{let t=this.dq(e);return t.length===0?null:{message:this._rewriteIfLargePrompt(t.map(e=>e.message).join(`
75079
+ `,e)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:return this.flowScalar(this.type);case`block-scalar-header`:return{type:`block-scalar`,offset:this.offset,indent:this.indent,props:[this.sourceToken],source:``};case`flow-map-start`:case`flow-seq-start`:return{type:`flow-collection`,offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case`seq-item-ind`:return{type:`block-seq`,offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case`explicit-key-ind`:{this.onKeyLine=!0;let t=c(s(e));return t.push(this.sourceToken),{type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:t,explicitKey:!0}]}}case`map-value-ind`:{this.onKeyLine=!0;let t=c(s(e));return{type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:t,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){return this.type!==`comment`||this.indent<=t?!1:e.every(e=>e.type===`newline`||e.type===`space`)}*documentEnd(e){this.type!==`doc-mode`&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type===`newline`&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case`comma`:case`doc-start`:case`doc-end`:case`flow-seq-end`:case`flow-map-end`:case`map-value-ind`:yield*this.pop(),yield*this.step();break;case`newline`:this.onKeyLine=!1;default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type===`newline`&&(yield*this.pop())}}}})),xOe=G((e=>{var t=nq(),n=qK(),r=JK(),i=EK(),a=fK(),o=aq(),s=oq();function c(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new o.LineCounter||null,prettyErrors:t}}function l(e,n={}){let{lineCounter:i,prettyErrors:a}=c(n),o=new s.Parser(i?.addNewLine),l=new t.Composer(n),u=Array.from(l.compose(o.parse(e)));if(a&&i)for(let t of u)t.errors.forEach(r.prettifyError(e,i)),t.warnings.forEach(r.prettifyError(e,i));return u.length>0?u:Object.assign([],{empty:!0},l.streamInfo())}function u(e,n={}){let{lineCounter:i,prettyErrors:a}=c(n),o=new s.Parser(i?.addNewLine),l=new t.Composer(n),u=null;for(let t of l.compose(o.parse(e),!0,e.length))if(!u)u=t;else if(u.options.logLevel!==`silent`){u.errors.push(new r.YAMLParseError(t.range.slice(0,2),`MULTIPLE_DOCS`,`Source contains multiple documents; please use YAML.parseAllDocuments()`));break}return a&&i&&(u.errors.forEach(r.prettifyError(e,i)),u.warnings.forEach(r.prettifyError(e,i))),u}function d(e,t,n){let r;typeof t==`function`?r=t:n===void 0&&t&&typeof t==`object`&&(n=t);let a=u(e,n);if(!a)return null;if(a.warnings.forEach(e=>i.warn(a.options.logLevel,e)),a.errors.length>0){if(a.options.logLevel!==`silent`)throw a.errors[0];a.errors=[]}return a.toJS(Object.assign({reviver:r},n))}function f(e,t,r){let i=null;if(typeof t==`function`||Array.isArray(t)?i=t:r===void 0&&t&&(r=t),typeof r==`string`&&(r=r.length),typeof r==`number`){let e=Math.round(r);r=e<1?void 0:e>8?{indent:8}:{indent:e}}if(e===void 0){let{keepUndefined:e}=r??t??{};if(!e)return}return a.isDocument(e)&&!i?e.toString(r):new n.Document(e,i,r).toString(r)}e.parse=d,e.parseAllDocuments=l,e.parseDocument=u,e.stringify=f})),SOe=G((e=>{var t=nq(),n=qK(),r=KK(),i=JK(),a=yK(),o=fK(),s=kK(),c=bK(),l=jK(),u=NK();rq();var d=iq(),f=aq(),p=oq(),m=xOe(),h=pK();e.Composer=t.Composer,e.Document=n.Document,e.Schema=r.Schema,e.YAMLError=i.YAMLError,e.YAMLParseError=i.YAMLParseError,e.YAMLWarning=i.YAMLWarning,e.Alias=a.Alias,e.isAlias=o.isAlias,e.isCollection=o.isCollection,e.isDocument=o.isDocument,e.isMap=o.isMap,e.isNode=o.isNode,e.isPair=o.isPair,e.isScalar=o.isScalar,e.isSeq=o.isSeq,e.Pair=s.Pair,e.Scalar=c.Scalar,e.YAMLMap=l.YAMLMap,e.YAMLSeq=u.YAMLSeq,e.Lexer=d.Lexer,e.LineCounter=f.LineCounter,e.Parser=p.Parser,e.parse=m.parse,e.parseAllDocuments=m.parseAllDocuments,e.parseDocument=m.parseDocument,e.stringify=m.stringify,e.visit=h.visit,e.visitAsync=h.visitAsync}))();function COe(e){let t=e.trimStart();if(!t.startsWith(`---`))return{data:{},body:e};let n=t.match(/\r?\n---\s*(?:\r?\n|$)/);if(!n||n.index===void 0)return{data:{},body:e};let r=n.index,i=t.slice(3,r).trim(),a=t.slice(r+n[0].length).trim();try{let e=(0,SOe.parse)(i);return e&&typeof e==`object`&&!Array.isArray(e)?{data:e,body:a}:{data:{},body:a}}catch{return{data:{},body:e}}}function wOe(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``)}const TOe=dt([`codellm`,`agent`,`skills`]),sq=new class{skills=new Map;async loadSkills(e){let t=await mCe(),n=O.join(ee.homedir(),hn.configDirName,`skills`),r=e?O.join(e,hn.localConfigDirName,`skills`):void 0,i=await this.discoverSkills(t,`builtin`),a=await this.discoverSkills(n,`global`),o=r?await this.discoverSkills(r,`project`):[];this.skills.clear();for(let e of i)this.skills.set(e.id,e);for(let e of a)this.skills.set(e.id,e);for(let e of o)this.skills.set(e.id,e);TOe.info`skills loaded: builtin=${i.length} global=${a.length} project=${o.length}`}async discoverSkills(e,t){let n=[],r;try{r=await Te.readdir(e,{withFileTypes:!0})}catch{return n}r.sort((e,t)=>e.name.localeCompare(t.name));for(let i of r)if(i.isFile()&&i.name.endsWith(`.md`)){let r=O.join(e,i.name),a=await this.parseSkillFile(r,!1,t);a&&n.push(a)}else if(i.isDirectory()){let r=O.join(e,i.name,`SKILL.md`);try{await Te.access(r);let e=await this.parseSkillFile(r,!0,t);e&&n.push(e)}catch{}}return n}async parseSkillFile(e,t,n){try{let{data:r}=COe(await Te.readFile(e,`utf-8`)),i=wOe(t?O.basename(O.dirname(e)):O.basename(e,`.md`));return i?this.buildSkill(i,r,e,t,n):null}catch{return null}}buildSkill(e,t,n,r,i){let a=t.name,o=t.description,s=typeof a==`string`&&a.trim()?a.trim():e,c=typeof o==`string`&&o.trim()?o.trim():void 0;if(!c)return null;let l={name:s,description:c};typeof t[`argument-hint`]==`string`&&(l[`argument-hint`]=t[`argument-hint`]),typeof t[`disable-model-invocation`]==`boolean`&&(l[`disable-model-invocation`]=t[`disable-model-invocation`]),typeof t[`user-invocable`]==`boolean`&&(l[`user-invocable`]=t[`user-invocable`]),Array.isArray(t[`allowed-tools`])&&(l[`allowed-tools`]=t[`allowed-tools`].filter(e=>typeof e==`string`)),typeof t.license==`string`&&(l.license=t.license),typeof t.compatibility==`string`&&(l.compatibility=t.compatibility);let u=t.metadata;if(u&&typeof u==`object`&&!Array.isArray(u)){let e={};for(let[t,n]of Object.entries(u))typeof n==`string`&&(e[t]=n);Object.keys(e).length>0&&(l.metadata=e)}return{id:e,frontmatter:l,path:n,isDirectory:r,source:i}}get(e){return this.skills.get(e)}getAll(){return Array.from(this.skills.values()).filter(e=>e.frontmatter[`user-invocable`]!==!1)}getAllMetadata(){return this.getAll().map(e=>({id:e.id,name:e.frontmatter.name,description:e.frontmatter.description,location:e.path}))}search(e){let t=e.toLowerCase();return this.getAll().filter(e=>e.id.toLowerCase().includes(t)||e.frontmatter.name.toLowerCase().includes(t)||e.frontmatter.description.toLowerCase().includes(t))}matchSkill(e){if(!e.startsWith(`/`))return null;let t=e.slice(1).split(/\s+/);if(t.length===0)return null;let[n,...r]=t;if(!n)return null;let i=this.skills.get(n);return!i||i.frontmatter[`user-invocable`]===!1?null:{skill:i,args:r.join(` `)}}},cq=dt([`codellm`,`agent`,`tools`,`diagnostics`]);var EOe=class e extends fV{name=`get_diagnostics`;displayName=`GetDiagnostics`;description=`Get IDE diagnostics (errors, warnings, info) for a file or all open files.`;_provider;static Parameters=ZL({uri:Y().optional().describe(`Optional file URI to get diagnostics for. If not provided, gets diagnostics for all files.`)});parameters=e.Parameters;constructor(e){super(),this._provider=e}needsPermission(){return!1}async execute(e,t){let n=e.uri?[e.uri]:void 0;cq.debug`Getting diagnostics${e.uri?` for ${e.uri}`:` for all files`}`;let r=await this._provider.getDiagnostics(n);return cq.debug`Found ${r.length} diagnostics`,{type:`get_diagnostics`,diagnostics:r,total:r.length}}format(e,t){return JSON.stringify({...e,status:`success`})}parse(e){let t=bR(e);if(t.rejected)return{phase:`rejected`,toolType:`get_diagnostics`,data:{},summary:t.userNote?`Rejected \u00b7 "${t.userNote}"`:`Rejected`,...t.userNote!==void 0&&{userNote:t.userNote}};try{let t=JSON.parse(e),n=t.status===`error`?`error`:`success`,r=t.diagnostics?.filter(e=>e.severity===`error`).length??0,i=t.diagnostics?.filter(e=>e.severity===`warning`).length??0,a=[];return r>0&&a.push(`${r} error${r===1?``:`s`}`),i>0&&a.push(`${i} warning${i===1?``:`s`}`),{phase:n,toolType:`get_diagnostics`,data:t,summary:a.length>0?a.join(`, `):`${t.total??0} diagnostics`}}catch{return{phase:`success`,toolType:`get_diagnostics`,data:{},summary:`Completed`}}}},DOe=class extends CR{includeInApiDefinitions=!1};const lq=dt([`codellm`,`agent`,`tools`,`mcp`]);var OOe=class extends DOe{name;displayName;description;parameters;isReadonly=!1;mcpToolDefinition;constructor(e){super(),this.mcpToolDefinition=e,this.name=e.name,this.displayName=e.name,this.description=e.description||`MCP tool: ${e.name}`,this.parameters=this.createZodSchemaFromMCPSchema(e.inputSchema)}createZodSchemaFromMCPSchema(e){let t=e?.properties||{},n=e?.required||[],r={};for(let[e,i]of Object.entries(t)){let t=i,a=n.includes(e),o=this.jsonSchemaToZod(t);a||(o=o.optional()),r[e]=o}return ZL(r)}jsonSchemaToZod(e){switch(e.type){case`string`:return e.enum?oR(e.enum):Y();case`number`:case`integer`:return rxe;case`boolean`:return AR;case`array`:return e.items?YL(this.jsonSchemaToZod(e.items)):YL(qL());case`object`:if(e.properties){let t={},n=e.required||[];for(let[r,i]of Object.entries(e.properties)){let e=this.jsonSchemaToZod(i);n.includes(r)||(e=e.optional()),t[r]=e}return ZL(t)}return iR(Y(),qL());case`null`:return KL();default:return e.oneOf?this.jsonSchemaToZod(e.oneOf[0]):qL()}}async execute(e,t){if(lq.debug`Executing MCP tool: ${this.name} (server=${this.mcpToolDefinition.serverId})`,!t.mcpService)return lq.warn`MCP service not available for tool: ${this.name}`,{type:`mcp`,serverId:this.mcpToolDefinition.serverId,toolName:this.name,content:`MCP service not available`,isError:!0};try{let n=(await t.mcpService.listAllToolDefinitions()).find(e=>e.name===this.name);if(!n)throw Error(`MCP tool '${this.name}' not found`);let r=await t.mcpService.callTool(n.serverId,n.originalName||this.name,e);return{type:`mcp`,serverId:n.serverId,toolName:this.name,content:r.content||r,isError:r.isError||!1}}catch(e){return Dl(e instanceof Error?e:Error(String(e)),{context:`mcp-tool-execution`}),lq.error`MCP tool execution failed: ${this.name}: ${e instanceof Error?e.message:String(e)}`,{type:`mcp`,serverId:this.mcpToolDefinition.serverId,toolName:this.name,content:`MCP tool execution failed: ${e instanceof Error?e.message:String(e)}`,isError:!0}}}format(e,t){return JSON.stringify({type:`mcp`,status:e.isError?`error`:`success`,serverId:e.serverId,toolName:e.toolName,content:e.content})}parse(e){let t=bR(e);if(t.rejected)return{phase:`rejected`,toolType:`mcp`,data:{},summary:t.userNote?`Rejected \u00b7 "${t.userNote}"`:`Rejected`,...t.userNote!==void 0&&{userNote:t.userNote}};try{let t=JSON.parse(e);return t.status===`error`||t.isError?{phase:`error`,toolType:`mcp`,data:t,summary:`Error`,errorMessage:typeof t.content==`string`?t.content:`MCP error`}:{phase:`success`,toolType:`mcp`,data:t,summary:`Executed successfully`}}catch{}return e.startsWith(`Error:`)?{phase:`error`,toolType:`mcp`,data:{},summary:e,errorMessage:e}:{phase:`success`,toolType:`mcp`,data:{},summary:`Executed successfully`}}};const kOe=new Set([`read`,`ls`,`grep`,`codebase_search`,`web_search`,`web_fetch`,`bash_output`,`kill_shell`,`get_diagnostics`]);function AOe(e){if(e.type!==`tool_call`)return null;let t=e.toolUseRequest.name;return kOe.has(t)?`read_search`:e.parsedResult?.data&&e.parsedResult.data.serverId?`mcp`:null}function jOe(e){if(e.type!==`tool_call`)return null;let t=e.parsedResult?.data;return t?.serverId?`${t.serverId}:${e.toolUseRequest.name}`:null}function MOe(e,t){if(t===`mcp`){let t=e[0];if(t?.type===`tool_call`){let n=t.toolUseRequest.name,r=t.parsedResult?.data?.serverId??`mcp`;return`${n} \u00d7 ${e.length} (${r})`}}let n=new Map;for(let t of e){if(t.type!==`tool_call`)continue;let e=t.toolUseRequest.name;n.set(e,(n.get(e)??0)+1)}let r=[];for(let[e,t]of n){let n=NOe(e);r.push(t>1?`${n} ${t} ${uq(e,t)}`:`${n} 1 ${uq(e,1)}`)}return r.join(`, `)}function NOe(e){switch(e){case`read`:return`read`;case`ls`:return`listed`;case`grep`:return`searched`;case`codebase_search`:return`searched`;case`web_search`:return`web searched`;case`web_fetch`:return`fetched`;case`bash_output`:return`got output from`;case`kill_shell`:return`killed`;case`get_diagnostics`:return`got diagnostics from`;default:return e}}function uq(e,t){let n=t===1?``:`s`;switch(e){case`read`:return`file${n}`;case`ls`:return`director${t===1?`y`:`ies`}`;case`grep`:return`pattern${n}`;case`codebase_search`:return`quer${t===1?`y`:`ies`}`;case`web_search`:return`quer${t===1?`y`:`ies`}`;case`web_fetch`:return`URL${n}`;case`kill_shell`:return`shell${n}`;default:return`call${n}`}}function POe(e){let t=[],n=[],r=null,i=null;function a(){n.length!==0&&(n.length===1?t.push(n[0]):t.push({type:`tool_group`,id:crypto.randomUUID(),tools:n,category:r,summary:MOe(n,r)}),n=[],r=null,i=null)}for(let o of e){let e=AOe(o);if(e===null){a(),t.push(o);continue}let s=e===`mcp`?jOe(o):null,c=o.type===`tool_call`&&o.toolPhase===`error`;(e!==r||e===`mcp`&&s!==i)&&(a(),r=e,i=s),n.push(o),c&&a()}return a(),t}function FOe(e){return e.length>1e4?!0:e.split(/\r\n|\r|\n/).length>5e3}var IOe=class{_tmpDir=null;_counter=0;_ensureDir(){if(!this._tmpDir){let e=O.join(ee.homedir(),hn.configDirName,`tmp`);c.mkdirSync(e,{recursive:!0}),this._tmpDir=c.mkdtempSync(O.join(e,`codellm-prompt-`))}return this._tmpDir}savePrompt(e){let t=this._ensureDir();this._counter++;let n=O.join(t,`prompt-${this._counter}.txt`);return c.writeFileSync(n,e,`utf-8`),n}cleanup(){if(this._tmpDir){try{c.rmSync(this._tmpDir,{recursive:!0,force:!0})}catch{}this._tmpDir=null,this._counter=0}}};const LOe={run_in_terminal:`bash`,get_terminal_output:`bash_output`,fetch_url:`web_fetch`},ROe={bash:{id:`shellId`,isBackground:`runInBackground`},bash_output:{id:`shellId`}};function dq(e){let t=LOe[e.name];t&&(e.name=t);let n=ROe[e.name];if(n&&e.input&&typeof e.input==`object`){let t=e.input;for(let[e,r]of Object.entries(n))e in t&&!(r in t)&&(t[r]=t[e],delete t[e])}}function fq(e){if(e.type===`code_llm_agent_tool_request`&&e.toolUseRequest){let t=Array.isArray(e.toolUseRequest)?e.toolUseRequest:[e.toolUseRequest];for(let e of t)dq(e)}if(Array.isArray(e.segments))for(let t of e.segments)fq(t)}function zOe(e){for(let t of e){if(t.toolUseRequest){let e=Array.isArray(t.toolUseRequest)?t.toolUseRequest:[t.toolUseRequest];for(let t of e)dq(t)}if(Array.isArray(t.segments))for(let e of t.segments)fq(e)}}var pq=class{sessionId;_logger=dt([`codellm`,`agent`,`session`]);_workspace;_terminalService;_registry;_mcpService;_config;_conversationId=null;_mode;_model;_running=!1;_abortController=null;_initialized=!1;_uploadedDocs=new Set;_rules=[];_markdownContext=``;_rulesEngine;_toolEventBuffer=[];_messageQueue=[];_promptFileManager=new IOe;_swapFolder=null;_setFolder=null;onAutoRestart=null;mcp;rules;constructor(e){let t=sF(aF(e.primaryWorkspace)),n=Array.from(new Set([t,...e.allowedDirectories.map(e=>sF(aF(e)))]));this._config={...e,primaryWorkspace:t,allowedDirectories:n},this.sessionId=crypto.randomUUID(),this._mode=e.mode??xd.Normal,this._model=e.model??``,this._logger.info(`Creating AgentSession (workspace={workspace}, mode={mode})`,{workspace:t,mode:this._mode}),this._workspace=new Swe(t),this._terminalService=new $De(t),this._terminalService.onBackgroundComplete=(e,t,n)=>{let r=`Background process (id=${e}) running \`${t}\` has ${n===0?`completed successfully`:`exited with code ${n}`}.`;this.nq(r,{hidden:!0}),!this._running&&this.onAutoRestart&&this.onAutoRestart(r)},this._registry=MV(),e.disabledBuiltinTools?.length&&this._registry.setDisabledTools(e.disabledBuiltinTools),e.diagnosticsProvider&&this._registry.register(new EOe(e.diagnosticsProvider)),this._mcpService=new uK;let r=e.config?.get(`permissions`)??{};this._rulesEngine=new VCe({rules:{allow:[...r.allow??[],...e.permissionRules?.allow??[]],deny:[...r.deny??[],...e.permissionRules?.deny??[]],ask:[...r.ask??[],...e.permissionRules?.ask??[]]},cliAllowed:e.cliAllowedTools,cliDenied:e.cliDisallowedTools}),this.mcp=this._buildMcpManager(),this.rules=this._buildRulesManager()}async _ensureInitialized(){if(!this._initialized){if(this._initialized=!0,this._logger.debug(`Initializing session`),this._config.config){await this._config.config.load();let e=this._config.config.get(`baseUrl`);e&&(this._config.apiClient.setUrl(e),this._config.apiClient.resetEndpoints(),await this._config.apiClient.getApiEndpoint());let t=this._config.config.get(`permissions`);if(t){for(let e of t.allow??[])this._rulesEngine.addAllowRule(e);for(let e of t.deny??[])this._rulesEngine.addDenyRule(e);for(let e of t.ask??[])this._rulesEngine.addAskRule(e)}let n=this._config.config.get(`additionalDirectories`);if(n)for(let e of n){let t=sF(aF(e));if(!this._config.allowedDirectories.includes(t)){this._config.allowedDirectories.push(t);let e=t.endsWith(`/`)?t:t+`/`;this._rulesEngine.addAllowRule(`Bash(cd ${e}*)`),this._rulesEngine.addAllowRule(`Bash(cd ${t})`)}}}await Promise.all([this._mcpService.initialize(this._config.primaryWorkspace,this._config.mcpServers,this._config.onMcpAuthRequired),this._config.enableSkills?sq.loadSkills(this._config.primaryWorkspace):Promise.resolve()])}}_buildMcpManager(){return{listServers:()=>this._mcpService.getConnectedServers(),addServer:async e=>{let t=this._mcpService.getConnectedServers().map(e=>e.config);return this._mcpService.initialize(this._config.primaryWorkspace,[...t,e],this._config.onMcpAuthRequired)},removeServer:async e=>{let t=this._mcpService.getConnectedServers().map(e=>e.config).filter(t=>t.id!==e);await this._mcpService.initialize(this._config.primaryWorkspace,t,this._config.onMcpAuthRequired)},callTool:(e,t,n)=>this._mcpService.callTool(e,t,n),getTools:()=>this._mcpService.getAbacusMcpTools(),refresh:async e=>{await this._mcpService.initialize(e??this._config.primaryWorkspace,this._config.mcpServers,this._config.onMcpAuthRequired)},authenticateServer:(e,t)=>this._mcpService.authenticateServer(e,t)}}_buildRulesManager(){return{getAll:()=>this._rules,getMarkdownContext:()=>this._markdownContext,reload:async()=>{this._rules=[],this._markdownContext=``}}}_buildBrowserActionDescription(e){switch(e.name){case`perform_interactive_element_action`:{let{action:t,id:n,text:r}=e.input,i=t??`interact with`,a={click:`Click`,type:`Type`,hover:`Hover`,scroll:`Scroll`,focus:`Focus`,select:`Select`}[i]??i;return i===`type`&&r&&n?`Type "${r}" into element ${n}`:i===`select`&&r&&n?`Select "${r}" in element ${n}`:n?`${a} element ${n}`:a}case`computer`:{let{action:t,coordinate:n,text:r}=e.input,i=t??``;return i===`screenshot`?`Screenshot`:i===`key`&&r?`Key: ${r}`:i===`type`&&r?`Type "${r}"`:n?`${i} at (${String(n[0])}, ${String(n[1])})`:i||`Computer action`}case`navigate_to`:return`Navigate to ${e.input.url??``}`;case`new_tab`:return`Open new tab${e.input.url?`: ${e.input.url}`:``}`;case`switch_active_tab`:return`Switch to tab ${String(e.input.id??``)}`;case`close_tab`:return`Close tab ${String(e.input.id??``)}`;case`refresh_tab`:return`Refresh tab`;case`get_tab_content`:return`Get tab content`;case`get_interactive_elements`:return`Get interactive elements`;default:return e.name}}_buildPermissionRequest(e,t){let n=this._registry.get(e.name)?.displayName??e.name;if(!jV.isBuiltinRequest(e))return{type:`generic`,tool:e,displayName:n,toolName:n,inputSummary:JSON.stringify(e.input).slice(0,200)};switch(e.name){case`read`:{let t=aF(e.input.filePath??``),r=sF(O.isAbsolute(t)?t:O.resolve(this._config.primaryWorkspace,t));return{type:`read_outside_directory`,tool:e,displayName:n,filePath:r,resolvedPath:r,deducedDirectory:O.dirname(r)}}case`edit`:{let r=t._prepareResult;if(r?.outsideWorkspace){let t=sF(r.resolvedPath??e.input.filePath??``);return{type:`edit_outside_directory`,tool:e,displayName:n,filePath:t,resolvedPath:t,deducedDirectory:O.dirname(t)}}if(r?.error)return{type:`edit_file`,tool:e,displayName:n,filePath:e.input.filePath??``,originalContent:``,newContent:``};let i=r?.currentContent??``,a=r?.newContent??``;return{type:`edit_file`,tool:e,displayName:n,filePath:e.input.filePath??``,originalContent:i,newContent:a}}case`write`:{let r=t._prepareResult;if(r?.outsideWorkspace){let t=sF(r.resolvedPath??e.input.filePath??``);return{type:`write_outside_directory`,tool:e,displayName:n,filePath:t,resolvedPath:t,deducedDirectory:O.dirname(t),isNewFile:!r?.fileExists}}return{type:`write_file`,tool:e,displayName:n,filePath:e.input.filePath??``,originalContent:r?.currentContent??``,content:e.input.content??``,isNewFile:!r?.fileExists}}case`bash`:{let t=e.input.command??``;return{type:`run_terminal`,tool:e,displayName:n,command:t,cwd:this._config.primaryWorkspace,background:!!(e.input.runInBackground??!1),unmatchedPatterns:this._rulesEngine.getUnmatchedBashSegments(t,this._config.primaryWorkspace)}}case`exit_plan_mode`:{let r=t._prepareResult;return{type:`exit_plan_mode`,tool:e,displayName:n,planFilePath:e.input.planFilePath??``,planContent:String(r?.planContent??``)}}case`ask_user_question`:return{type:`ask_user_question`,tool:e,displayName:n,questions:Array.isArray(e.input.questions)?e.input.questions:[]};case`navigate_to`:return{type:`browser_action`,tool:e,displayName:n,action:e.name,url:e.input.url,description:this._buildBrowserActionDescription(e)};case`computer`:case`perform_interactive_element_action`:case`switch_active_tab`:case`close_tab`:case`refresh_tab`:case`get_tab_content`:case`get_interactive_elements`:case`new_tab`:return{type:`browser_action`,tool:e,displayName:n,action:e.name,description:this._buildBrowserActionDescription(e)};case`notebook_edit`:{let r=t._prepareResult;if(r?.outsideWorkspace){let t=sF(r.resolvedPath??e.input.notebookPath??``);return{type:`notebook_edit_outside_directory`,tool:e,displayName:n,filePath:t,resolvedPath:t,deducedDirectory:O.dirname(t)}}let i=r?.notebook,a=e.input.cellId,o=e.input.editMode??`replace`,s=``;if(a&&i?.cells){let e=i.cells.find(e=>e.id===a||e.metadata?.id===a);e&&(s=Array.isArray(e.source)?e.source.join(``):String(e.source??``))}return{type:`notebook_edit`,tool:e,displayName:n,notebookPath:e.input.notebookPath??``,cellId:a,editMode:o,cellType:e.input.cellType,originalContent:s,newContent:e.input.newSource??``}}default:return{type:`generic`,tool:e,displayName:n,toolName:n,inputSummary:JSON.stringify(e.input).slice(0,200)}}}_buildExecuteTools(e){return async(t,n,r)=>{let i=new AbortController,a=()=>i.abort(`interrupted`);n&&(n.aborted?i.abort(`interrupted`):n.addEventListener(`abort`,a,{once:!0}));let o=[],s=(e,t,n)=>{let r=n?.storageContent??t;return{id:e.id,content:t,...n?.rejected&&{rejected:!0},parsedResult:r.startsWith(`Error:`)?{phase:`error`,toolType:e.name,data:{},summary:r,errorMessage:r}:this._registry.parse(e.name,r)}};try{let a=async t=>{if(i.signal.aborted)return{resolved:!0,result:s(t,JSON.stringify({reason:yR.INTERRUPTED}),{rejected:!0})};let a={workspace:this._workspace,terminalService:this._terminalService,apiClient:this._config.apiClient,workspacePath:this._config.primaryWorkspace,conversationId:e,agentMode:this._mode,toolCallId:t.id,status:`executing`,uploadedDocs:this._uploadedDocs,allowEditingPaths:this._config.allowedDirectories,abortController:i,permissionProvider:this._config.permissionProvider,rulesEngine:this._rulesEngine,getAgentMode:()=>this._mode,setAgentMode:e=>{this._mode=e},mcpService:{listAllToolDefinitions:async()=>this._mcpService.getAbacusMcpTools(),callTool:(e,t,n)=>this._mcpService.callTool(e,t,n),reloadConnections:async()=>{await this._mcpService.initialize(this._config.primaryWorkspace,this._config.mcpServers,this._config.onMcpAuthRequired)},getServerStatus:e=>{let t=this._mcpService.getConnectedServers().find(t=>t.config.id===e);return t?t.status===`connected`?`running`:`error`:`stopped`}},...this._rules.length>0&&{rules:this._rules},...this._config.planDirectory!==void 0&&{plansDir:this._config.planDirectory},...this._config.clientType&&{clientType:this._config.clientType},...r&&{emitEvent:r},...r&&{onOutputUpdate:(e,t)=>{r({type:`tool_output_update`,toolCallId:e,output:t})}}};try{if(this._registry.isDisabled(t.name))return{resolved:!0,result:s(t,`Error: tool '${t.name}' is disabled in this environment`)};r?.({type:`tool_execution_start`,tool:t});let e=this._registry.createToolInstance(t.name,t.input??{},a);if(await e.prepare(),t.name===`edit`&&jV.isBuiltinRequest(t)&&!e._prepareResult?.error){let n=e._prepareResult,i=a.workspacePath,o=a.plansDir??O.join(te(),hn.configDirName,`plans`),s=lF(O.resolve(i,t.input.filePath??``),O.resolve(i,o)),c={originalContent:n?.currentContent??``,newContent:n?.newContent??``,isPlanFile:s,isNewFile:!(n?.fileExists??!0)},l={type:`tool_display_data`,toolCallId:t.id,data:c};r?.(l),this._toolEventBuffer.push(l)}if(t.name===`notebook_edit`&&jV.isBuiltinRequest(t)&&!e._prepareResult?.error){let n=e._prepareResult?.notebook,i=t.input.cellId,a=``;if(i&&n?.cells){let e=n.cells.find(e=>e.id===i||e.metadata?.id===i);e&&(a=Array.isArray(e.source)?e.source.join(``):String(e.source??``))}let o={originalContent:a,newContent:t.input.newSource??``},s={type:`tool_display_data`,toolCallId:t.id,data:o};r?.(s),this._toolEventBuffer.push(s)}if(t.name===`write`&&jV.isBuiltinRequest(t)&&!e._prepareResult?.error){let n=e._prepareResult,i={originalContent:n?.currentContent??``,newContent:t.input.content??``,isNewFile:!(n?.fileExists??!0)},a={type:`tool_display_data`,toolCallId:t.id,data:i};r?.(a),this._toolEventBuffer.push(a)}let i=this._mode===xd.Yolo&&t.name!==`ask_user_question`;if(!i&&e.needsPermission()){let i=this._registry.get(t.name)?.displayName??t.name,o=BV(t),c=this._rulesEngine.evaluate(i,o);if(c===`deny`)return{resolved:!0,result:s(t,JSON.stringify({reason:yR.REJECTED}),{rejected:!0})};if(c!==`allow`){let i=this._buildPermissionRequest(t,e);if(this._config.permissionProvider.needsPermission(i)){let o={type:`status_changed`,status:Sd.WaitingForToolPermission};r?.(o),this._toolEventBuffer.push(o);let c;try{let e=this._config.permissionProvider.requestPermission(i);if(n){let t,r=new Promise((e,r)=>{n.aborted?r(Error(`interrupted`)):(t=()=>r(Error(`interrupted`)),n.addEventListener(`abort`,t,{once:!0}))});try{c=await Promise.race([e,r])}finally{t&&n.removeEventListener(`abort`,t)}}else c=await e}catch{return{resolved:!0,result:s(t,JSON.stringify({reason:yR.INTERRUPTED}),{rejected:!0})}}if(r?.({type:`status_changed`,status:Sd.ExecutingTool}),this._toolEventBuffer.push({type:`status_changed`,status:Sd.ExecutingTool}),c===`reject`)return{resolved:!0,result:s(t,JSON.stringify({reason:yR.REJECTED}),{rejected:!0})};if(typeof c==`object`&&c.type===`reject_with_message`)return{resolved:!0,result:s(t,JSON.stringify({reason:yR.USER_MESSAGE,message:c.message}),{rejected:!0})};if(c===`allowAlways`||c===`allowYolo`||c===`accept`){if(c===`allowAlways`&&(i.type===`read_outside_directory`||i.type===`write_outside_directory`||i.type===`edit_outside_directory`||i.type===`notebook_edit_outside_directory`)){if(this.addAllowedDirectory(i.deducedDirectory),this._config.config){let e=this._config.config.get(`additionalDirectories`)??[];e.includes(i.deducedDirectory)||this._config.config.set(`additionalDirectories`,[...e,i.deducedDirectory],`local`)}}else if(t.name===`exit_plan_mode`){let e=c===`allowYolo`?xd.Yolo:c===`allowAlways`?xd.AcceptEdits:xd.Normal;this._mode=e,a.agentMode=e,r?.({type:`mode_changed`,mode:e}),this._toolEventBuffer.push({type:`mode_changed`,mode:e})}else if(c===`allowAlways`){let e=Dd(i.type);this._mode=e,a.agentMode=e,r?.({type:`mode_changed`,mode:e}),this._toolEventBuffer.push({type:`mode_changed`,mode:e})}}if(typeof c==`object`&&c.type===`accept_with_message`&&this.nq(c.message),typeof c==`object`&&c.type===`question_answers`&&e.mergeParams({answers:c.answers}),typeof c==`object`&&c.type===`allow_always_with_rule`&&(this._rulesEngine.addAllowRule(c.rule),this._config.config)){let e=this._config.config.get(`permissions`)??{},t=[...e.allow??[],c.rule];this._config.config.set(`permissions`,{...e,allow:t},`local`)}if(typeof c==`object`&&c.type===`allow_always_with_rules`){for(let e of c.rules)this._rulesEngine.addAllowRule(e);if(this._config.config){let e=this._config.config.get(`permissions`)??{},t=[...e.allow??[],...c.rules];this._config.config.set(`permissions`,{...e,allow:t},`local`)}}}}}return t.name===`enter_plan_mode`&&(this._mode=xd.PlanMode,a.agentMode=xd.PlanMode,r?.({type:`mode_changed`,mode:xd.PlanMode}),this._toolEventBuffer.push({type:`mode_changed`,mode:xd.PlanMode})),t.name===`exit_plan_mode`&&i&&(this._mode=xd.Normal,a.agentMode=xd.Normal,r?.({type:`mode_changed`,mode:xd.Normal}),this._toolEventBuffer.push({type:`mode_changed`,mode:xd.Normal})),{resolved:!1,call:t,instance:e,ctx:a}}catch(e){return i.signal.aborted?{resolved:!0,result:s(t,JSON.stringify({reason:yR.INTERRUPTED}),{rejected:!0})}:{resolved:!0,result:s(t,`Error: ${e instanceof Error?e.message:String(e)}`)}}},c=async e=>{try{if(await e.instance.execute(),i.signal.aborted)return s(e.call,JSON.stringify({reason:yR.INTERRUPTED}),{rejected:!0});let t=e.instance.formatResultForLLM(),n=e.instance.formatResult(),r=typeof t==`string`?t:JSON.stringify(t);return s(e.call,r,{storageContent:n===r?void 0:n})}catch(t){if(i.signal.aborted)return s(e.call,JSON.stringify({reason:yR.INTERRUPTED}),{rejected:!0});let n=t instanceof Error?t.message:String(t);return s(e.call,`Error: ${n}`)}},l=0,u=!1;for(;l<t.length;){let e=e=>this._registry.get(e.name)?.concurrency(e.input,this._config.primaryWorkspace)??!1;if(u){let n=t[l],i=!!e(n),a=this._registry.get(n.name),c=a?!a.isReadonly:!1;if(i||c){let e=s(n,SR);o.push(e),r?.({type:`tool_execution_complete`,tool:n,result:e}),l++;continue}}if(e(t[l])){let n=l+1;for(;n<t.length&&e(t[n]);)n++;if(n-l>1){let i=t.slice(l,n),d=i.map(e);l=n;let f=[[]],p=[new Set];for(let e=0;e<i.length;e++){let t=d[e],n=f[f.length-1],r=p[p.length-1];typeof t==`string`&&r.has(t)&&(f.push([]),p.push(new Set),n=f[f.length-1],r=p[p.length-1]),typeof t==`string`&&r.add(t),n.push(e)}let m=new Map,h=new Map,g=!1;for(let e of f){if(g){for(let t of e){let e=s(i[t],SR);o.push(e),r?.({type:`tool_execution_complete`,tool:i[t],result:e})}continue}for(let t of e)m.set(t,await a(i[t]));for(let t of e){let e=m.get(t);e.resolved&&r?.({type:`tool_execution_complete`,tool:i[t],result:e.result})}let t=e.filter(e=>!m.get(e).resolved).map(async e=>{let t=m.get(e);if(!t.resolved){let n=await c(t);h.set(e,n),r?.({type:`tool_execution_complete`,tool:i[e],result:n})}});for(let e=0;e<t.length;e+=10)await Promise.all(t.slice(e,e+10));for(let t of e){let e=m.get(t),n=e.resolved?e.result:h.get(t);o.push(n),!g&&!n.rejected&&n.content.startsWith(`Error:`)&&(g=!0)}}g&&(u=!0);continue}}let n=t[l];l++;let i=await a(n);if(i.resolved){o.push(i.result),r?.({type:`tool_execution_complete`,tool:n,result:i.result});continue}let d=await c(i);o.push(d),r?.({type:`tool_execution_complete`,tool:n,result:d})}return o}finally{n&&n.removeEventListener(`abort`,a)}}}async createConversation(){let e=await this._config.apiClient.createCodellmDeploymentConversation(this._config.isPrintMode?hn.nonInteractiveAgentType:hn.agentType,this._config.clientType);if(e?.success===!1&&e.error)throw Error(e.error);let t=e?.result?.deploymentConversationId;if(!t)throw Error(`Failed to create conversation: no deployment conversation ID returned`);return this._conversationId=t,t}async loadConversation(e){this._conversationId=e;let t=await this._config.apiClient.getDeploymentConversation({deploymentConversationId:e}),n=t?.result?.history??[],r=t?.result?.name??void 0;zOe(n);let i=POe(this._hydrateHistory(n)),a;for(let e=n.length-1;e>=0;e--){let t=n[e]?.inputParams?.llmName;if(t){a=t;break}}return{...r!==void 0&&{title:r},...a!==void 0&&{llmName:a},segments:i}}switchConversation(e){return this._conversationId=e,this._uploadedDocs.clear(),Promise.resolve()}resetConversation(){this._conversationId=null,this._uploadedDocs.clear()}async deleteConversation(e){await this._config.apiClient.deleteDeploymentConversation?.({deploymentConversationId:e}),this._conversationId===e&&(this._conversationId=null)}async listConversations(){return((await this._config.apiClient.getConversationsList(this._config.isPrintMode?hn.nonInteractiveAgentType:hn.agentType))?.result??[]).map(e=>({id:e.deploymentConversationId??``,createdAt:new Date(e.createdAt??Date.now()),updatedAt:new Date(e.lastEventCreatedAt??e.createdAt??Date.now()),...e.name!==void 0&&{title:e.name}}))}_hydrateHistory(e){let t=[],n=[];for(let r of e){if(r.role===`USER`){let e=this._extractParallelToolResponses(r);e.length>0&&this._attachToolResults(n,e),n=[];let i=(r.prompt??r.text??``).trim();i&&t.push({type:`text`,id:crypto.randomUUID(),source:`user`,content:i});continue}n=[];for(let e of r.segments??[]){if(e.isThoughts){let n=typeof e.segment==`string`?e.segment:e.segment?.segment??``;t.push({type:`thinking`,id:crypto.randomUUID(),content:n,isSpinny:!1});continue}if(e.type===`code_llm_agent_tool_request`&&e.toolUseRequest){let r=Array.isArray(e.toolUseRequest)?e.toolUseRequest:[e.toolUseRequest];for(let e of r){let r={type:`tool_call`,id:crypto.randomUUID(),toolUseRequest:e,toolPhase:`unknown`};t.push(r),n.push(r)}continue}if(e.type===`code_llm_notification`){t.push({type:`notification`,id:crypto.randomUUID(),message:e.message??(typeof e.segment==`string`?e.segment:``)??``,severity:e.severity??`info`,...e.actions!==void 0&&{actions:e.actions}});continue}let r=typeof e.segment==`string`?e.segment:e.segment?.segment;r&&t.push({type:`text`,id:crypto.randomUUID(),source:`bot`,content:r})}}return this._detectAbandonedTools(t),t}_extractParallelToolResponses(e){if(Array.isArray(e.parallelToolResponses))return e.parallelToolResponses;for(let t of e.segments??[])if(Array.isArray(t.parallelToolResponses)&&t.parallelToolResponses.length>0)return t.parallelToolResponses;return[]}_attachToolResults(e,t){for(let n=0;n<Math.min(e.length,t.length);n++){let r=e[n],i=t[n],a=r.toolUseRequest.name,o=bR(i);r.toolUseResult={id:r.toolUseRequest.id,content:i,...o.rejected&&{rejected:!0}};let s=this._registry.parse(a,i);o.rejected&&(s.phase=`rejected`,o.userNote!==void 0&&(s.userNote=o.userNote)),r.parsedResult=s,r.toolPhase=s.phase}}_detectAbandonedTools(e){let t=new Set([`todo_write`]);for(let n=0;n<e.length;n++){let r=e[n];if(r.type===`tool_call`&&!r.toolUseResult&&!t.has(r.toolUseRequest.name)){let t=e.slice(n+1).some(e=>e.type===`text`||e.type===`tool_call`),i=t?`abandoned`:`abandoned_last`;r.toolPhase=i,r.parsedResult={phase:i,toolType:r.toolUseRequest.name,data:{},summary:t?`Abandoned`:`Abandoned · What should I do next?`}}}}_rewriteIfLargePrompt(e){return FOe(e)?`The large prompt is saved in ${this._promptFileManager.savePrompt(e)} file. Follow the instructions in it.`:e}async*send(e,t){if(await this._ensureInitialized(),this._logger.info(`Sending message (conversationId={conversationId}, mode={mode}, model={model})`,{conversationId:this._conversationId,mode:this._mode,model:this._model}),!this._conversationId)for(let e=0;e<8;e++)try{await this.createConversation();break}catch(t){if(!Vl(t)||e>=7)throw t;let n=Math.min((e+1)*2e3,1e4);yield{type:`retry`,attempt:e+1,maxAttempts:8,delayMs:n,isNetworkError:!0},await BR(n)}this._running=!0,this._abortController=new AbortController;let n=this._buildExecuteTools(this._conversationId);try{yield{type:`status_changed`,status:Sd.Submitted};let r=this._rewriteIfLargePrompt(e),i=!0;for(;;){let e=this._mcpService.getAbacusMcpTools();e.length>0&&this._registry.registerMCPTools(e.map(e=>new OOe(e)));let a=this._registry.getApiToolDefinitions(),o=this._config.isPrintMode?a.filter(e=>e.name!==`ask_user_question`):a,s={apiClient:this._config.apiClient,conversationId:this._conversationId,model:this._model,workspacePath:this._config.primaryWorkspace,...this._swapFolder&&{swapFolder:this._swapFolder},...this._setFolder&&{setFolder:this._setFolder},uploadedDocs:this._uploadedDocs,supportedTools:o,supportedSubAgents:RR().map(e=>({name:e})),...e.length>0&&{mcpTools:e},...this._rules.length>0&&{rules:this._rules},...this._config.enableSkills&&(()=>{let e=sq.getAllMetadata();return e.length>0?{availableSkills:e}:{}})(),...this._config.enableSkills&&t?.activeSkills&&t.activeSkills.length>0&&{activeSkills:t.activeSkills},...this._config.isPrintMode!==void 0&&{isPrintMode:this._config.isPrintMode},...this._config.enablePromptRewrite!==void 0&&{enablePromptRewrite:this._config.enablePromptRewrite},...this._config.supportsThoughtStreaming!==void 0&&{supportsThoughtStreaming:this._config.supportsThoughtStreaming},agentMode:this._mode,...this._config.config?.get(`client`)&&{client:this._config.config.get(`client`)},...this._config.maxTurns!==void 0&&{maxTurns:this._config.maxTurns},...i&&t?.diagnosticIssues!==void 0&&{diagnosticIssues:t.diagnosticIssues},...i&&t?.currentFile!==void 0&&{currentFile:O.isAbsolute(t.currentFile)?t.currentFile:O.resolve(this._config.primaryWorkspace,t.currentFile)},...i&&t?.selectionStartLine!==void 0&&{selectionStartLine:t.selectionStartLine},...i&&t?.selectionEndLine!==void 0&&{selectionEndLine:t.selectionEndLine},executeTools:n,getConcurrency:e=>this._registry.get(e.name)?.concurrency(e.input,this._config.primaryWorkspace)??!1,drainEvents:()=>{let e=this._toolEventBuffer.slice();return this._toolEventBuffer.length=0,e},dequeueAllQueuedMessage:e=>{let t=this.dq(e);return t.length===0?null:{message:this._rewriteIfLargePrompt(t.map(e=>e.message).join(`
75080
75080
  `)),allHidden:t.every(e=>e.hidden)}}};this._swapFolder=null,this._setFolder=null;let c=GR(s,r,this._abortController.signal),l=!1,u;for(;!(u=await c.next()).done;){let e=u.value;e.type===`text_delta`&&!l?(l=!0,yield{type:`status_changed`,status:Sd.Streaming}):e.type===`tool_requested`&&(yield{type:`status_changed`,status:Sd.ExecutingTool}),yield e,e.type===`mode_changed`&&(this._mode=e.mode)}if(i=!1,this._messageQueue.length===0||this._abortController.signal.aborted)break;let d=this.dq({includeHidden:!0});if(d.length===0)break;let f=d.every(e=>e.hidden);r=this._rewriteIfLargePrompt(d.map(e=>e.message).join(`
75081
75081
  `)),f||(yield{type:`user_message_dequeued`,content:r})}}finally{this._running=!1,this._abortController=null,this._toolEventBuffer.length=0,this._uploadedDocs.clear(),this._promptFileManager.cleanup(),this._logger.debug(`Send completed, session idle`),yield{type:`status_changed`,status:Sd.Idle}}}stop(){this._abortController?.abort()}dispose(){this._abortController?.abort(),this._promptFileManager.cleanup(),this._terminalService.dispose()}nq(e,t){let n={id:crypto.randomUUID(),message:e,...t?.hidden?{hidden:!0}:{}};return this._messageQueue.push(n),{...n}}getQueue(e){return this.getQueueEntries(e).map(e=>e.message)}getQueueEntries(e){return e?.includeHidden??!1?this._messageQueue.map(e=>({...e})):this._messageQueue.filter(e=>e.hidden!==!0).map(e=>({...e}))}dq(e){let t=e?.includeHidden??!1,n=e?.id;if(n!==void 0){let e=this._messageQueue.findIndex(e=>e.id===n?t||e.hidden!==!0:!1);if(e===-1)return[];let[r]=this._messageQueue.splice(e,1);return r?[{...r}]:[]}if(t){let e=this._messageQueue.map(e=>({...e}));return this._messageQueue.length=0,e}let r=[],i=[];for(let e of this._messageQueue)e.hidden===!0?i.push(e):r.push({...e});return this._messageQueue=i,r}setContent(e,t){let n=typeof e==`string`?e:e.id,r=this._messageQueue.find(e=>e.id===n);return r?(r.message=t,{...r}):null}setText(e,t){return this.setContent(e,t)}remove(e,t){let n=typeof e==`string`?e:e.id,r=t?.includeHidden??!1,i=this._messageQueue.findIndex(e=>e.id===n&&(r||e.hidden!==!0));i!==-1&&this._messageQueue.splice(i,1)}clearQueue(e){if(e?.includeHidden===!0){this._messageQueue.length=0;return}this._messageQueue=this._messageQueue.filter(e=>e.hidden===!0)}addUploadedDoc(e){this._uploadedDocs.add(e)}clearUploadedDocs(){this._uploadedDocs.clear()}isDirectoryAllowed(e){let t=sF(aF(e));for(let e of this._config.allowedDirectories)if(lF(t,e))return{allowed:!0,coveredBy:e};return{allowed:!1}}addAllowedDirectory(e,t){let n=sF(aF(e));for(let e of this._config.allowedDirectories)if(lF(n,e))return{status:`already-allowed`,coveredBy:e};this._config.allowedDirectories.push(n);let r=n.endsWith(`/`)?n:n+`/`;if(this._rulesEngine.addAllowRule(`Bash(cd ${r}*)`),this._rulesEngine.addAllowRule(`Bash(cd ${n})`),t?.persist&&this._config.config){let e=this._config.config.get(`additionalDirectories`)??[];e.includes(n)||this._config.config.set(`additionalDirectories`,[...e,n],`local`)}return{status:`added`}}setMode(e){this._mode=e}refreshPermissionRequest(e){return e.type===`run_terminal`?{...e,cwd:this._config.primaryWorkspace,unmatchedPatterns:this._rulesEngine.getUnmatchedBashSegments(e.command,this._config.primaryWorkspace)}:e}setModel(e){this._model=e}setWorkspace(e){let t=sF(aF(e));if(this._config.primaryWorkspace=t,!this._config.allowedDirectories.includes(t)){this._config.allowedDirectories.push(t);let e=t.endsWith(`/`)?t:t+`/`;this._rulesEngine.addAllowRule(`Bash(cd ${e}*)`),this._rulesEngine.addAllowRule(`Bash(cd ${t})`)}this._swapFolder=t,this._setFolder=t,this._workspace.setCwd(t),this._terminalService.setCwd(t)}getMode(){return this._mode}getConversationId(){return this._conversationId}isRunning(){return this._running}listTerminalSessions(){return this._terminalService.listSessions()}getTerminalSessionOutput(e){let t=this._terminalService.getLiveOutput(e);if(t)return t.output;let n=this._terminalService.getOutput(e);return n.length>0?n[n.length-1].output:``}async stopTerminalSession(e){return this._terminalService.stopCommand(e)}},BOe=class{needsPermission(e){return!1}async requestPermission(e){return`accept`}},mq=class{handler;_needsPermission;constructor(e,t){this.handler=e,this._needsPermission=t}needsPermission(e){return this._needsPermission?this._needsPermission(e):!0}async requestPermission(e){return this.handler(e)}},VOe=class{async read(){let e={},t=hn.envPrefix,n=hn.internalEnvPrefix,r=process.env[`${t}BASE_URL`],i=process.env[`${t}MODEL`],a=process.env[`${n}LOG_LEVEL`],o=process.env[`${t}MAX_TURNS`],s=process.env[`${t}AUTO_UPDATE`],c=process.env[`${n}CHANNEL`];if(r&&(e.baseUrl=r),i&&(e.model=i),a&&(e.logLevel=a),o&&(e.maxTurns=parseInt(o,10)),c&&(e.updateChannel=c),s!==void 0){let t=jR.safeParse(s);t.success&&t.data!==void 0&&(e.autoUpdate=t.data)}return e}},HOe=class{configPath;constructor(){this.configPath=O.join(te(),hn.configDirName,hn.configFileName)}async read(){try{let e=await m.readFile(this.configPath,`utf-8`);return JSON.parse(e)}catch{return{}}}async write(e){let t=O.dirname(this.configPath);await m.mkdir(t,{recursive:!0}),await m.writeFile(this.configPath,JSON.stringify(e,null,2),`utf-8`)}},UOe=class{configPath;constructor(e){this.configPath=O.join(e,hn.localConfigDirName,hn.configFileName)}async read(){try{let e=await m.readFile(this.configPath,`utf-8`);return JSON.parse(e)}catch{return{}}}async write(e){let t=O.dirname(this.configPath);await m.mkdir(t,{recursive:!0}),await m.writeFile(this.configPath,JSON.stringify(e,null,2),`utf-8`)}};const WOe=dt([`codellm`,`agent`,`config`]);function hq(e,...t){let n={...e};for(let e of t)for(let t of Object.keys(e)){let r=e[t];r!==void 0&&(typeof r==`object`&&r&&!Array.isArray(r)&&typeof n[t]==`object`&&n[t]!==null?n[t]=hq(n[t],r):n[t]=r)}return n}const gq={allowedDirectories:[],primaryWorkspace:``,logLevel:`info`};var _q=class{sources;cache=null;constructor(e){this.sources=[new HOe,new UOe(e.cwd),...e.extraSources??[],new VOe]}async load(){let e={...gq};for(let t of this.sources){let n=await t.read();e=hq(e,n)}this.cache=e,WOe.info`config loaded from ${this.sources.length} sources`}get(e){return this.cache?this.cache[e]??gq[e]:gq[e]}getAll(){return this.cache??gq}async set(e,t,n=`global`){let r=n===`global`?this.sources[0]:this.sources[1];if(r?.write){let n=await r.read();await r.write({...n,[e]:t})}this.cache&&(this.cache[e]=t)}};dt([`codellm`,`agent`,`history`]);var vq=class{source;maxEntries;filePath;entries=[];navIndex=-1;loaded=!1;writeQueue=Promise.resolve();constructor(e,t){this.source=e,this.maxEntries=t?.maxEntries??1e4,this.filePath=t?.filePath??A(te(),hn.configDirName,`history.jsonl`)}async load(){if(!this.loaded){this.loaded=!0;try{let e=this.maxEntries*2048,t=await De(this.filePath,`r`);try{let{size:n}=await t.stat(),r=Math.max(0,n-e),i=Buffer.allocUnsafe(n-r);await t.read(i,0,i.length,r);let a=i.toString(`utf-8`),o=r===0?0:a.indexOf(`
75082
75082
  `)+1,s=a.slice(o).split(`
@@ -75140,12 +75140,12 @@ No matching component was found for:
75140
75140
  `).map(e=>eMe(e,i)).join(`
75141
75141
  `):t===`truncate-start`&&(r=r.split(`
75142
75142
  `).map(e=>$je(e,i)).join(`
75143
- `))}}r=wMe(e,r),e.renderCache={lines:[r],width:n,height:0,left:l,top:u},t.write(l,u,r,d)}else e.renderCache=void 0;e.renderDirty=!1;return}let f=!1;if(e.nodeName===`jar-view`){e.style.backgroundColor&&TMe(l,u,e,t),e.style.borderStyle&&bMe(l,u,e,t);let n=e.style.overflowX===`hidden`||e.style.overflow===`hidden`,r=e.style.overflowY===`hidden`||e.style.overflow===`hidden`;if(n||r){let i=n?l+dZ(e.style,`Left`):void 0,a=n?l+c.getComputedWidth()-dZ(e.style,`Right`):void 0,o=r?u+dZ(e.style,`Top`):void 0,s=r?u+c.getComputedHeight()-dZ(e.style,`Bottom`):void 0;t.clip({x1:i,x2:a,y1:o,y2:s}),f=!0}}if(e.nodeName===`jar-root`||e.nodeName===`jar-view`){let n=f?u+dZ(e.style,`Top`):o,r=f?u+c.getComputedHeight()-dZ(e.style,`Bottom`):s;for(let i of e.childNodes)fZ(i,t,{offsetX:l,offsetY:u,transformers:d,clipY1:n,clipY2:r});f&&t.unclip()}e.renderDirty=!1};var EMe=class{rootNode;lastWidth=0;cachedLines=null;output=new tMe(0,0);constructor(e){this.rootNode=e}notifyCommit(){this.cachedLines=null}render(e){let t=e!==this.lastWidth;if(t&&(this.clearAllRenderCaches(this.rootNode),this.lastWidth=e),this.cachedLines&&!this.rootNode.renderDirty&&!t)return this.cachedLines;this.rootNode.yogaNode.setWidth(e),this.rootNode.yogaNode.calculateLayout(void 0,void 0,1);let n=Math.ceil(this.rootNode.yogaNode.getComputedHeight());if(n<=0)return this.cachedLines=[],this.cachedLines;this.output.reset(e,n),fZ(this.rootNode,this.output,{});let r=this.output.get(),i=!1;for(let t of r)if(JJ(t)>e){i=!0;break}return this.cachedLines=i?r.map(t=>JJ(t)>e?$J(t,e):t):r,this.cachedLines}invalidate(){this.cachedLines=null,this.clearAllRenderCaches(this.rootNode)}clearAllRenderCaches(e){e.renderDirty=!0,e.renderCache=void 0;for(let t of e.childNodes)t.nodeName!==`#text`&&this.clearAllRenderCaches(t)}},DMe;(function(e){e[e.BlinkingBlock=0]=`BlinkingBlock`,e[e.BlinkingBlockDefault=1]=`BlinkingBlockDefault`,e[e.SteadyBlock=2]=`SteadyBlock`,e[e.BlinkingUnderline=3]=`BlinkingUnderline`,e[e.SteadyUnderline=4]=`SteadyUnderline`,e[e.BlinkingBar=5]=`BlinkingBar`,e[e.SteadyBar=6]=`SteadyBar`})(DMe||={});const pZ=`\x1B[?25h`,mZ=`\x1B[?25l`;function OMe(e,t){let n=``;return t!==``&&(n=typeof Buffer<`u`?Buffer.from(t).toString(`base64`):btoa(t)),`\x1B]52;`+String.fromCharCode(e)+`;`+n+`\x07`}function kMe(e){return OMe(99,e)}function hZ(e,...t){return`\x1B]8;`+(t.length>0?t.join(`:`):``)+`;`+e+`\x07`}function gZ(...e){return hZ(``,...e)}function _Z(e){return e.replace(/[\x07\x1b\x9c]/g,``)}function AMe(e){return`\x1B]9;`+_Z(e)+`\x07`}function vZ(e,...t){return`\x1B]99;`+t.map(_Z).join(`:`)+`;`+_Z(e)+`\x07`}function jMe(e){return`\x1B]777;notify;;`+_Z(e)+`\x07`}const yZ=`\x1B]9;4;0\x07`;function MMe(e){return`\x1B]9;4;1;`+Math.min(Math.max(0,e),100)+`\x07`}function NMe(e){return`\x1B]9;4;2;`+Math.min(Math.max(0,e),100)+`\x07`}function PMe(e){return`\x1B]9;4;4;`+Math.min(Math.max(0,e),100)+`\x07`}var FMe=class{env;profile;terminalType;_isDark;_writer;_progressHideTimer=null;constructor(e){this.env=e?.env??DY(),this.profile=nZ(this.env),gMe(this.profile),this.terminalType=OY(this.env),this._isDark=e?.isDark??WX(),this._writer=e?.writer??null,e?.isDark!==void 0&&GX(e.isDark)}get isDark(){return this._isDark}setDark(e){this._isDark=e,GX(e)}resolveAdaptiveColor(e){if(typeof e==`string`)return eZ.parse(e);let t=this._isDark?e.dark:e.light;return eZ.parse(t)}colorize(e,t,n){if(!t)return e;let r=this.resolveAdaptiveColor(t);if(!r)return e;let i=aZ(r,this.profile);return i?`\x1B[`+(n===`foreground`?i.fgSequence():i.bgSequence())+`m`+e+`\x1B[0m`:e}styledText(){return cZ(this.profile)}write(e){this._writer?this._writer(e):typeof process<`u`&&process.stdout?.isTTY&&process.stdout.write(e)}notify(e){if(!cje(this.env))return;let t=this.terminalType,{title:n,body:r}=e,i=n?`${n}:\n${r}`:r;t===`kitty`&&(n?this.write(vZ(r,`d=0:p=title`,n)):this.write(vZ(r))),this.write(jMe(i)),this.write(AMe(i))}showProgress(e){if(!kY(this.env))return;this.clearProgressTimer();let t=e.state??`normal`,n=Math.min(Math.max(0,e.percentage??0),100);switch(t){case`indeterminate`:this.write(`\x1B]9;4;3\x07`);break;case`error`:this.write(NMe(n));break;case`warning`:this.write(PMe(n));break;default:this.write(MMe(n));break}(t===`error`||n>=100)&&this.scheduleProgressHide()}hideProgress(){this.clearProgressTimer(),kY(this.env)&&this.write(yZ)}async trackProgress(e){this.showProgress({state:`indeterminate`});try{let t=await e;return this.showProgress({percentage:100}),this.scheduleProgressHide(),t}catch(e){throw this.showProgress({percentage:100,state:`error`}),this.scheduleProgressHide(),e}}copyToClipboard(e){AY(this.env)&&this.write(kMe(e))}clearClipboard(){AY(this.env)&&this.write(`\x1B]52;c;\x07`)}hyperlink(e,t){return lje(this.env)?hZ(e)+t+gZ():t}clearProgressTimer(){this._progressHideTimer&&=(clearTimeout(this._progressHideTimer),null)}scheduleProgressHide(){this.clearProgressTimer(),this._progressHideTimer=setTimeout(()=>{this.write(yZ),this._progressHideTimer=null},500)}},IMe=class{tui;terminal;terminalOutput;rootNode;bridge;container;exitCallbacks=[];exitPromise;resolveExit;exitOnCtrlC;ownsTui;suspendable;onSuspended;cleanupSuspend;originalWarningListeners;warningInterceptor;requestFullRedrawOnNextCommit=!1;constructor(e={}){this.exitOnCtrlC=e.exitOnCtrlC??!0,this.suspendable=e.suspendable??!1,this.onSuspended=e.onSuspended,e.tui?(this.tui=e.tui,this.terminal=e.tui.terminal,this.ownsTui=!1):e.terminal?(this.terminal=e.terminal,this.tui=new wY(this.terminal),this.ownsTui=!0):(this.terminal=new sje,this.tui=new wY(this.terminal),this.ownsTui=!0),this.terminalOutput=new FMe({writer:e=>this.terminal.write(e)}),this.rootNode=yX(`jar-root`),this.rootNode.yogaNode.setFlexDirection(0),this.rootNode.yogaNode.setFlexGrow(1),this.rootNode.onRender=()=>{this.bridge.notifyCommit(),this.requestFullRedrawOnNextCommit?(this.requestFullRedrawOnNextCommit=!1,this.tui.requestRender(!0)):this.tui.requestRender(),performance.clearMeasures()},this.bridge=new EMe(this.rootNode),this.tui.addChild(this.bridge),this.container=MX.createContainer(this.rootNode,0,null,!1,null,`jar`,()=>{},()=>{},()=>{},()=>{}),this.exitPromise=new Promise(e=>{this.resolveExit=e}),this.exitOnCtrlC&&this.tui.addInputListener(e=>{if(!pY(e)&&vY(e,`ctrl+c`))return this.exit(),{consume:!0}})}render(e){MX.updateContainerSync(e,this.container,null),MX.flushSyncWork()}requestFullRedraw(){this.requestFullRedrawOnNextCommit=!0,this.bridge.invalidate(),this.tui.requestRender(!0)}start(){this.ownsTui&&this.tui.start(),this.setupWarningInterceptor(),this.suspendable&&(this.cleanupSuspend=this.setupSuspendHandler())}exit(e){for(let t of this.exitCallbacks)t(e);this.ownsTui&&this.terminal.kittyProtocolActive?this.terminal.drainInput(200,50).catch(()=>{}).then(()=>this.unmount()):this.unmount()}onExit(e){this.exitCallbacks.push(e)}unmount(){if(this.warningInterceptor&&=(H.removeListener(`warning`,this.warningInterceptor),void 0),this.originalWarningListeners){let e=H.listeners(`warning`);for(let t of this.originalWarningListeners)e.includes(t)||H.on(`warning`,t);this.originalWarningListeners=void 0}this.cleanupSuspend?.(),this.ownsTui&&this.disableInputProtocols(),MX.updateContainerSync(null,this.container,null),MX.flushSyncWork(),this.tui.removeChild(this.bridge),this.ownsTui&&this.tui.stop(),this.rootNode.yogaNode?.unsetMeasureFunc(),this.rootNode.yogaNode?.free(),this.rootNode.yogaNode=void 0,this.resolveExit()}cleanupTerminal(){this.ownsTui&&(this.cleanupSuspend?.(),this.disableInputProtocols(),this.tui.stop(),H.stdout.write(pZ))}disableInputProtocols(){this.terminal.write(MY),this.terminal.write(`\x1B[?2004l`),this.terminal.kittyProtocolActive&&this.terminal.write(`\x1B[<u`)}setupWarningInterceptor(){this.originalWarningListeners||(this.originalWarningListeners=H.rawListeners(`warning`),H.removeAllListeners(`warning`),this.warningInterceptor=()=>{},H.on(`warning`,this.warningInterceptor))}setupSuspendHandler(){if(H.platform===`win32`||!this.ownsTui)return()=>{};let e=!1,t=()=>{e=this.terminal.kittyProtocolActive,H.stdout.isTTY&&(this.disableInputProtocols(),H.stdout.write(pZ)),H.stdin.isTTY&&H.stdin.isRaw&&H.stdin.setRawMode(!1),this.onSuspended?.(),H.removeListener(`SIGTSTP`,t),H.kill(H.pid,`SIGTSTP`)},n=()=>{H.stdin.isTTY&&H.stdin.setRawMode(!0),H.stdout.isTTY&&(H.stdout.write(mZ),this.terminal.write(`\x1B[?2004h`),this.terminal.write(jY),e&&this.terminal.write(`\x1B[>7u`)),H.on(`SIGTSTP`,t),this.tui.requestRender(!0)};return H.on(`SIGTSTP`,t),H.on(`SIGCONT`,n),()=>{H.removeListener(`SIGTSTP`,t),H.removeListener(`SIGCONT`,n)}}waitUntilExit(){return this.exitPromise}getRootNode(){return this.rootNode}};function LMe(e,t){let n=new IMe(t),r=Z.createElement(RX,{tui:n.tui,terminal:n.terminal,terminalOutput:n.terminalOutput,exit:e=>n.exit(e),requestFullRedraw:()=>n.requestFullRedraw(),children:e});return n.render(r),n.start(),{rerender(e){let t=Z.createElement(RX,{tui:n.tui,terminal:n.terminal,terminalOutput:n.terminalOutput,exit:e=>n.exit(e),requestFullRedraw:()=>n.requestFullRedraw(),children:e});n.render(t)},unmount(){n.unmount()},waitUntilExit(){return n.waitUntilExit()},requestFullRedraw(){n.requestFullRedraw()},cleanupTerminal(){n.cleanupTerminal()}}}function Q({children:e,...t}){return(0,X.jsx)(`jar-view`,{style:{flexWrap:`nowrap`,flexDirection:`row`,flexGrow:0,flexShrink:1,...t,overflowX:t.overflowX??t.overflow??`visible`,overflowY:t.overflowY??t.overflow??`visible`},children:e})}function $({color:e,backgroundColor:t,dimColor:n=!1,bold:r=!1,italic:i=!1,underline:a=!1,strikethrough:o=!1,inverse:s=!1,wrap:c=`wrap`,transform:l,children:u}){if(u==null)return null;let d=(0,Z.useCallback)(c=>(n&&(c=cZ().dim().render(c)),e&&(c=sZ(c,e,`foreground`)),t&&(c=sZ(c,t,`background`)),r&&(c=cZ().bold().render(c)),i&&(c=cZ().italic().render(c)),a&&(c=cZ().underline().render(c)),o&&(c=cZ().strikethrough().render(c)),s&&(c=cZ().reverse().render(c)),l&&(c=l(c)),c),[e,t,n,r,i,a,o,s,l]);return(0,X.jsx)(`jar-text`,{style:{flexGrow:0,flexShrink:0,flexDirection:`row`,textWrap:c},internal_transform:d,children:u})}const RMe=/\x1b\[[\d:]*;(\d+)/;function zMe(e){let t=RMe.exec(e);return t?(parseInt(t[1],10)-1&8)!=0:!1}const bZ={upArrow:!1,downArrow:!1,leftArrow:!1,rightArrow:!1,pageDown:!1,pageUp:!1,home:!1,end:!1,return:!1,escape:!1,ctrl:!1,shift:!1,tab:!1,backspace:!1,delete:!1,meta:!1,super:!1,paste:!1,raw:``},xZ=(e,t={})=>{let{addInputListener:n}=(0,Z.use)(FX),r=(0,Z.useRef)(e);r.current=e,(0,Z.useEffect)(()=>{if(t.isActive!==!1)return n(e=>{if(pY(e))return;if(e.startsWith(`\x1B[200~`)){let t=e.indexOf(`\x1B[201~`),n=t===-1?e.slice(6):e.slice(6,t);bZ.upArrow=!1,bZ.downArrow=!1,bZ.leftArrow=!1,bZ.rightArrow=!1,bZ.pageDown=!1,bZ.pageUp=!1,bZ.home=!1,bZ.end=!1,bZ.return=!1,bZ.escape=!1,bZ.ctrl=!1,bZ.shift=!1,bZ.tab=!1,bZ.backspace=!1,bZ.delete=!1,bZ.meta=!1,bZ.super=!1,bZ.paste=!0,bZ.raw=e,r.current(n,{...bZ});return}let t=qAe(e),n=t?t.split(`+`):[],i=n[n.length-1]??``,a=n.includes(`ctrl`),o=n.includes(`shift`),s=n.includes(`alt`);bZ.upArrow=i===`up`,bZ.downArrow=i===`down`,bZ.leftArrow=i===`left`,bZ.rightArrow=i===`right`,bZ.pageDown=i===`pagedown`,bZ.pageUp=i===`pageup`,bZ.home=i===`home`,bZ.end=i===`end`,bZ.return=i===`return`||i===`enter`,bZ.escape=i===`escape`,bZ.ctrl=a,bZ.shift=o,bZ.tab=i===`tab`,bZ.backspace=i===`backspace`,bZ.delete=i===`delete`,bZ.meta=s,bZ.super=zMe(e),bZ.paste=!1,bZ.raw=e;let c=bZ,l=``;if(a&&i)l=i;else if(!c.upArrow&&!c.downArrow&&!c.leftArrow&&!c.rightArrow&&!c.pageDown&&!c.pageUp&&!c.home&&!c.end&&!c.return&&!c.escape&&!c.tab&&!c.backspace&&!c.delete){let t=XAe(e);t===void 0?e.length===1?l=e:i.length===1&&(l=i):l=t}r.current(l,{...c})})},[t.isActive,n])},BMe=()=>{let e=(0,Z.use)(IX);if(!e)throw Error(`useApp must be used within a jar render context`);return{exit:e.exit,requestFullRedraw:e.requestFullRedraw}},SZ=({isActive:e=!0,autoFocus:t=!1,id:n}={})=>{let{activeId:r,add:i,remove:a,activate:o,deactivate:s,focus:c}=(0,Z.use)(NX),l=(0,Z.useMemo)(()=>n??Math.random().toString().slice(2,7),[n]);return(0,Z.useEffect)(()=>(i(l,{autoFocus:t}),()=>{a(l)}),[l,t]),(0,Z.useEffect)(()=>{e?o(l):s(l)},[e,l]),{isFocused:!!l&&r===l,focus:c}};function CZ(){return(0,Z.use)(PX)}const wZ=()=>{let e=(0,Z.use)(LX);if(!e)throw Error(`useTerminal must be used within a jar render context`);return e.output},TZ=RegExp(`[\\x1b\\x9b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><~]|\\x1b\\][\\s\\S]*?(?:\\x07|\\x1b\\\\)`,`g`);function VMe(){return new RegExp(TZ.source,`g`)}function HMe(e){return e.replace(TZ,``)}function UMe(e){return e.replace(/[\x07\x1b\x9c]/g,``)}function EZ(e){return`\x1B]2;`+UMe(e)+`\x07`}var DZ=G(((e,t)=>{t.exports={name:`@codellm/cli`,version:`2.4.9-canary.2`,private:!0,bin:{abacusai:`dist/index.mjs`},files:[`dist`,`LICENSE.txt`],type:`module`,scripts:{"prepare-publish":`bun ./scripts/prepare-publish.ts`,build:`tsdown`,"check-types":`tsgo -b --noEmit`,test:`FORCE_COLOR=1 vitest run`,"test:watch":`FORCE_COLOR=1 vitest`,"test:ui":`FORCE_COLOR=1 vitest --ui`,"test:coverage":`FORCE_COLOR=1 vitest run --coverage`},dependencies:{"@clack/prompts":`^0.11.0`,"@codellm/agent":`workspace:*`,"@codellm/api":`workspace:*`,"@codellm/auth":`workspace:*`,"@codellm/comms":`workspace:*`,"@codellm/jar":`workspace:*`,"@codellm/logging":`workspace:*`,"@codellm/product":`workspace:*`,"@logtape/logtape":`^2.0.5`,"@orpc/client":`catalog:`,"@orpc/contract":`catalog:`,"@orpc/server":`catalog:`,"@sentry/node-core":`10.46.0`,"@slack/web-api":`^7.0.0`,"@tanstack/react-query":`^5.90.19`,"@vscode/ripgrep":`1.17.0`,"ansi-styles":`^6.2.3`,"beautiful-mermaid":`^1.1.3`,"cli-boxes":`^4.0.1`,"cli-highlight":`^2.1.11`,conf:`^15.0.2`,diff:`^8.0.3`,fzf:`^0.5.2`,"gradient-string":`^3.0.0`,immer:`^11.1.4`,"isomorphic-git":`^1.36.1`,marked:`^17.0.4`,"patchright-core":`^1.58.2`,react:`^19.2.3`,"react-compiler-runtime":`^1.0.0`,remend:`^1.2.2`,semver:`^7.7.4`,"shell-history":`^2.0.1`,"string-width":`^8.1.0`,"strip-ansi":`^7.2.0`,trash:`^9.0.0`,zod:`catalog:`},devDependencies:{"@codellm/configs":`workspace:*`,"@playwright/mcp":`^0.0.68`,"@types/diff":`^8.0.0`,"@types/node":`catalog:`,"@types/react":`^19.2.9`,"@types/semver":`^7.7.1`,"@typescript/native-preview":`catalog:`,"@vitejs/plugin-react":`^5.1.2`,"@vitest/coverage-v8":`^4.0.18`,"@vitest/ui":`^4.0.18`,"@xterm/addon-serialize":`^0.14.0`,"@xterm/headless":`^6.0.0`,"babel-plugin-react-compiler":`^1.0.0`,"cli-testing-library":`^3.0.1`,jsdom:`^27.4.0`,"node-pty":`^1.1.0`,"react-devtools-core":`^6.1.5`,"svg-term-cli":`^2.1.1`,tsdown:`^0.21.0`,vite:`catalog:`,vitest:`^4.0.18`},engines:{node:`>=18`}}})),OZ=Qe(DZ(),1);let kZ=null;function AZ(e){let t=(0,xJ.prerelease)(e);return t&&t.length>0&&typeof t[0]==`string`?t[0]:`latest`}function jZ(e){if(!e)return``;try{return y(e)}catch{return e}}function MZ(){return{invokedPath:jZ(process.argv[1]??``),execPath:jZ(process.execPath??process.argv[0]??``)}}function NZ(e){let t=hn.configDirName.replace(/^\./,``).replace(/[.*+?^${}()|[\]\\]/g,`\\$&`);return RegExp(`[/\\\\]\\.?${t}[/\\\\]bin[/\\\\]`,`i`).test(e)}function PZ(e){return/[/\\]node_modules[/\\]/.test(e)||/[/\\]\._npx[/\\]/.test(e)||/[/\\]_npx[/\\]/.test(e)||/[/\\]\.?npm[/\\]/.test(e)||/[/\\]\.?pnpm[/\\]/.test(e)||/[/\\]\.?yarn[/\\]/.test(e)||/[/\\]\.bun[/\\]/.test(e)}function FZ(){let e=(process.env.npm_command??``).toLowerCase();if(e===`exec`||e===`dlx`)return!0;let{invokedPath:t,execPath:n}=MZ();return/[/\\]_npx[/\\]|[/\\]dlx[/\\]|[/\\]\.cache[/\\]/.test(t+`|`+n)}function IZ(){let e=process.env.npm_config_user_agent;if(e){let t=e.split(`/`)[0];if(t===`yarn`||t===`pnpm`||t===`bun`||t===`npm`)return t}let{invokedPath:t,execPath:n}=MZ(),r=`${t}|${n}`;return/[/\\]\.?yarn[/\\]/.test(r)?`yarn`:/[/\\]\.?pnpm[/\\]/.test(r)?`pnpm`:/[/\\]\.bun[/\\]/.test(r)||process.versions.bun!==void 0&&!NZ(n)?`bun`:`npm`}function WMe(){let{execPath:e,invokedPath:t}=MZ();return PZ(t)||PZ(e)?!1:NZ(e)||NZ(t)}function LZ(){let e=`${hn.internalEnvPrefix}DEV`,t=process.env[e];if(t===`1`||t===`true`)return!0;let{invokedPath:n,execPath:r}=MZ();return!(NZ(r)||NZ(n)||PZ(n)||PZ(r)||process.env.npm_config_user_agent)}function GMe(){let{execPath:e}=MZ(),t=IZ(),n=FZ();return LZ()?{installationType:`development`,packageManager:t,isEphemeral:n,execPath:e}:WMe()?{installationType:`native`,packageManager:t,isEphemeral:n,execPath:e}:{installationType:`package-manager`,packageManager:t,isEphemeral:n,execPath:e}}function KMe(){return`${process.platform===`win32`?`win32`:process.platform===`darwin`?`darwin`:`linux`}-${process.arch===`arm64`?`arm64`:`x64`}`}async function qMe(e){let t=Date.now();if(kZ&&t-kZ.timestamp<6e4)return kZ.tags;let n=await fetch(`https://registry.npmjs.org/${e}`,{signal:AbortSignal.timeout(1e4),headers:{accept:`application/json`}});if(!n.ok)throw Error(`Registry returned ${n.status}`);let r=(await n.json())[`dist-tags`]??{};return kZ={tags:r,timestamp:t},r}async function JMe(e,t,n,r){let i=t??AZ(e),a=(r??`https://apps.abacus.ai`).replace(/\/$/,``),o=new URL(`${a}/api/v0/_getCodellmCliVersion`);o.searchParams.set(`channel`,i),n&&o.searchParams.set(`platform`,n),o.searchParams.set(`cli_version`,e);let s=await fetch(o.toString(),{signal:AbortSignal.timeout(1e4)});if(s.status===204)return null;if(!s.ok)throw Error(`API returned ${s.status}`);let c=await s.json(),l=c&&`result`in c&&c.result?c.result:c??{};if(!l.version||!l.channel)throw Error(`API returned invalid payload`);return{currentVersion:e,latestVersion:l.version,tag:l.channel,packageManager:IZ(),isEphemeral:FZ(),installationType:`native`,downloadUrl:l.url}}async function YMe(e,t){let n=t??AZ(e),r=IZ(),i=FZ(),a=(await qMe(gn.publishName))[n];return!a&&n!==`latest`||!a||a===e?null:{currentVersion:e,latestVersion:a,tag:n,packageManager:r,isEphemeral:i,installationType:`package-manager`}}async function RZ(e,t,n,r){let i=GMe();if(i.installationType===`native`)try{return await JMe(e,t,KMe(),n)}catch{return null}return i.installationType===`development`&&!r?.includeDev?null:await YMe(e,t)}function zZ(e){if(e.installationType===`native`)return`${hn.binName} upgrade`;let t=`${gn.publishName}@${e.tag}`;switch(e.packageManager){case`yarn`:return`yarn global add ${t}`;case`pnpm`:return`pnpm add -g ${t}`;case`bun`:return`bun add -g ${t}`;default:return`npm install -g ${t}`}}function BZ(e){try{return{ok:!0,output:le(zZ(e),{stdio:`pipe`,encoding:`utf-8`}).trim()}}catch(e){return{ok:!1,output:e instanceof Error&&`stderr`in e?String(e.stderr).trim():e instanceof Error?e.message:`Unknown error`}}}async function VZ(e){if(!e.downloadUrl)return{ok:!1,output:`No download URL`};let t=D.join(P.tmpdir(),`abacusai-update-${Date.now()}`),n=D.join(P.homedir(),hn.configDirName,`bin`),r=process.platform===`win32`,i=r?`${hn.binName}.exe`:hn.binName;try{await we.mkdir(t,{recursive:!0}),await we.mkdir(n,{recursive:!0});let a=D.join(t,r?`update.zip`:`update.tar.gz`),o=await fetch(e.downloadUrl);if(!o.ok)throw Error(`Download failed: ${o.status}`);let s=Buffer.from(await o.arrayBuffer());await we.writeFile(a,s),le(r?`powershell -Command "Expand-Archive -Path '${a}' -DestinationPath '${t}' -Force"`:`tar -xzf "${a}" -C "${t}"`,{stdio:`pipe`});let c=D.join(t,i),l=D.join(n,i);return await we.copyFile(c,l),r||await we.chmod(l,493),{ok:!0,output:`Updated to ${e.latestVersion}`}}catch(e){return{ok:!1,output:e instanceof Error?e.message:`Unknown error`}}finally{await we.rm(t,{recursive:!0,force:!0}).catch(()=>{})}}function XMe(e,t){let n=e=>{let n=e.toLowerCase();if(n===t)return 1e3;if(n.startsWith(t))return 900;let r=0,i=-1;for(let e of t){let t=n.indexOf(e,i+1);if(t===-1)return 0;r+=100-(t-i),i=t}return r+=Math.max(0,50-n.length),r},r=null,i=0;for(let t of e){let e=Math.max(n(t.name??``),n(t.llmName));e>i&&(i=e,r=t.llmName)}return i>=100?r:null}async function HZ(e,t){let n=(await e.listLLMModels())?.result??[];return n.length||(process.stderr.write(`Error: No models available.
75143
+ `))}}r=wMe(e,r),e.renderCache={lines:[r],width:n,height:0,left:l,top:u},t.write(l,u,r,d)}else e.renderCache=void 0;e.renderDirty=!1;return}let f=!1;if(e.nodeName===`jar-view`){e.style.backgroundColor&&TMe(l,u,e,t),e.style.borderStyle&&bMe(l,u,e,t);let n=e.style.overflowX===`hidden`||e.style.overflow===`hidden`,r=e.style.overflowY===`hidden`||e.style.overflow===`hidden`;if(n||r){let i=n?l+dZ(e.style,`Left`):void 0,a=n?l+c.getComputedWidth()-dZ(e.style,`Right`):void 0,o=r?u+dZ(e.style,`Top`):void 0,s=r?u+c.getComputedHeight()-dZ(e.style,`Bottom`):void 0;t.clip({x1:i,x2:a,y1:o,y2:s}),f=!0}}if(e.nodeName===`jar-root`||e.nodeName===`jar-view`){let n=f?u+dZ(e.style,`Top`):o,r=f?u+c.getComputedHeight()-dZ(e.style,`Bottom`):s;for(let i of e.childNodes)fZ(i,t,{offsetX:l,offsetY:u,transformers:d,clipY1:n,clipY2:r});f&&t.unclip()}e.renderDirty=!1};var EMe=class{rootNode;lastWidth=0;cachedLines=null;output=new tMe(0,0);constructor(e){this.rootNode=e}notifyCommit(){this.cachedLines=null}render(e){let t=e!==this.lastWidth;if(t&&(this.clearAllRenderCaches(this.rootNode),this.lastWidth=e),this.cachedLines&&!this.rootNode.renderDirty&&!t)return this.cachedLines;this.rootNode.yogaNode.setWidth(e),this.rootNode.yogaNode.calculateLayout(void 0,void 0,1);let n=Math.ceil(this.rootNode.yogaNode.getComputedHeight());if(n<=0)return this.cachedLines=[],this.cachedLines;this.output.reset(e,n),fZ(this.rootNode,this.output,{});let r=this.output.get(),i=!1;for(let t of r)if(JJ(t)>e){i=!0;break}return this.cachedLines=i?r.map(t=>JJ(t)>e?$J(t,e):t):r,this.cachedLines}invalidate(){this.cachedLines=null,this.clearAllRenderCaches(this.rootNode)}clearAllRenderCaches(e){e.renderDirty=!0,e.renderCache=void 0;for(let t of e.childNodes)t.nodeName!==`#text`&&this.clearAllRenderCaches(t)}},DMe;(function(e){e[e.BlinkingBlock=0]=`BlinkingBlock`,e[e.BlinkingBlockDefault=1]=`BlinkingBlockDefault`,e[e.SteadyBlock=2]=`SteadyBlock`,e[e.BlinkingUnderline=3]=`BlinkingUnderline`,e[e.SteadyUnderline=4]=`SteadyUnderline`,e[e.BlinkingBar=5]=`BlinkingBar`,e[e.SteadyBar=6]=`SteadyBar`})(DMe||={});const pZ=`\x1B[?25h`,mZ=`\x1B[?25l`;function OMe(e,t){let n=``;return t!==``&&(n=typeof Buffer<`u`?Buffer.from(t).toString(`base64`):btoa(t)),`\x1B]52;`+String.fromCharCode(e)+`;`+n+`\x07`}function kMe(e){return OMe(99,e)}function hZ(e,...t){return`\x1B]8;`+(t.length>0?t.join(`:`):``)+`;`+e+`\x07`}function gZ(...e){return hZ(``,...e)}function _Z(e){return e.replace(/[\x07\x1b\x9c]/g,``)}function AMe(e){return`\x1B]9;`+_Z(e)+`\x07`}function vZ(e,...t){return`\x1B]99;`+t.map(_Z).join(`:`)+`;`+_Z(e)+`\x07`}function jMe(e){return`\x1B]777;notify;;`+_Z(e)+`\x07`}const yZ=`\x1B]9;4;0\x07`;function MMe(e){return`\x1B]9;4;1;`+Math.min(Math.max(0,e),100)+`\x07`}function NMe(e){return`\x1B]9;4;2;`+Math.min(Math.max(0,e),100)+`\x07`}function PMe(e){return`\x1B]9;4;4;`+Math.min(Math.max(0,e),100)+`\x07`}var FMe=class{env;profile;terminalType;_isDark;_writer;_progressHideTimer=null;constructor(e){this.env=e?.env??DY(),this.profile=nZ(this.env),gMe(this.profile),this.terminalType=OY(this.env),this._isDark=e?.isDark??WX(),this._writer=e?.writer??null,e?.isDark!==void 0&&GX(e.isDark)}get isDark(){return this._isDark}setDark(e){this._isDark=e,GX(e)}resolveAdaptiveColor(e){if(typeof e==`string`)return eZ.parse(e);let t=this._isDark?e.dark:e.light;return eZ.parse(t)}colorize(e,t,n){if(!t)return e;let r=this.resolveAdaptiveColor(t);if(!r)return e;let i=aZ(r,this.profile);return i?`\x1B[`+(n===`foreground`?i.fgSequence():i.bgSequence())+`m`+e+`\x1B[0m`:e}styledText(){return cZ(this.profile)}write(e){this._writer?this._writer(e):typeof process<`u`&&process.stdout?.isTTY&&process.stdout.write(e)}notify(e){if(!cje(this.env))return;let t=this.terminalType,{title:n,body:r}=e,i=n?`${n}:\n${r}`:r;t===`kitty`&&(n?this.write(vZ(r,`d=0:p=title`,n)):this.write(vZ(r))),this.write(jMe(i)),this.write(AMe(i))}showProgress(e){if(!kY(this.env))return;this.clearProgressTimer();let t=e.state??`normal`,n=Math.min(Math.max(0,e.percentage??0),100);switch(t){case`indeterminate`:this.write(`\x1B]9;4;3\x07`);break;case`error`:this.write(NMe(n));break;case`warning`:this.write(PMe(n));break;default:this.write(MMe(n));break}(t===`error`||n>=100)&&this.scheduleProgressHide()}hideProgress(){this.clearProgressTimer(),kY(this.env)&&this.write(yZ)}async trackProgress(e){this.showProgress({state:`indeterminate`});try{let t=await e;return this.showProgress({percentage:100}),this.scheduleProgressHide(),t}catch(e){throw this.showProgress({percentage:100,state:`error`}),this.scheduleProgressHide(),e}}copyToClipboard(e){AY(this.env)&&this.write(kMe(e))}clearClipboard(){AY(this.env)&&this.write(`\x1B]52;c;\x07`)}hyperlink(e,t){return lje(this.env)?hZ(e)+t+gZ():t}clearProgressTimer(){this._progressHideTimer&&=(clearTimeout(this._progressHideTimer),null)}scheduleProgressHide(){this.clearProgressTimer(),this._progressHideTimer=setTimeout(()=>{this.write(yZ),this._progressHideTimer=null},500)}},IMe=class{tui;terminal;terminalOutput;rootNode;bridge;container;exitCallbacks=[];exitPromise;resolveExit;exitOnCtrlC;ownsTui;suspendable;onSuspended;cleanupSuspend;originalWarningListeners;warningInterceptor;requestFullRedrawOnNextCommit=!1;constructor(e={}){this.exitOnCtrlC=e.exitOnCtrlC??!0,this.suspendable=e.suspendable??!1,this.onSuspended=e.onSuspended,e.tui?(this.tui=e.tui,this.terminal=e.tui.terminal,this.ownsTui=!1):e.terminal?(this.terminal=e.terminal,this.tui=new wY(this.terminal),this.ownsTui=!0):(this.terminal=new sje,this.tui=new wY(this.terminal),this.ownsTui=!0),this.terminalOutput=new FMe({writer:e=>this.terminal.write(e)}),this.rootNode=yX(`jar-root`),this.rootNode.yogaNode.setFlexDirection(0),this.rootNode.yogaNode.setFlexGrow(1),this.rootNode.onRender=()=>{this.bridge.notifyCommit(),this.requestFullRedrawOnNextCommit?(this.requestFullRedrawOnNextCommit=!1,this.tui.requestRender(!0)):this.tui.requestRender(),performance.clearMeasures()},this.bridge=new EMe(this.rootNode),this.tui.addChild(this.bridge),this.container=MX.createContainer(this.rootNode,0,null,!1,null,`jar`,()=>{},()=>{},()=>{},()=>{}),this.exitPromise=new Promise(e=>{this.resolveExit=e}),this.exitOnCtrlC&&this.tui.addInputListener(e=>{if(!pY(e)&&vY(e,`ctrl+c`))return this.exit(),{consume:!0}})}render(e){MX.updateContainerSync(e,this.container,null),MX.flushSyncWork()}requestFullRedraw(){this.requestFullRedrawOnNextCommit=!0,this.bridge.invalidate(),this.tui.requestRender(!0)}start(){this.ownsTui&&this.tui.start(),this.setupWarningInterceptor(),this.suspendable&&(this.cleanupSuspend=this.setupSuspendHandler())}exit(e){for(let t of this.exitCallbacks)t(e);this.ownsTui&&this.terminal.kittyProtocolActive?this.terminal.drainInput(200,50).catch(()=>{}).then(()=>this.unmount()):this.unmount()}onExit(e){this.exitCallbacks.push(e)}unmount(){if(this.warningInterceptor&&=(H.removeListener(`warning`,this.warningInterceptor),void 0),this.originalWarningListeners){let e=H.listeners(`warning`);for(let t of this.originalWarningListeners)e.includes(t)||H.on(`warning`,t);this.originalWarningListeners=void 0}this.cleanupSuspend?.(),this.ownsTui&&this.disableInputProtocols(),MX.updateContainerSync(null,this.container,null),MX.flushSyncWork(),this.tui.removeChild(this.bridge),this.ownsTui&&this.tui.stop(),this.rootNode.yogaNode?.unsetMeasureFunc(),this.rootNode.yogaNode?.free(),this.rootNode.yogaNode=void 0,this.resolveExit()}cleanupTerminal(){this.ownsTui&&(this.cleanupSuspend?.(),this.disableInputProtocols(),this.tui.stop(),H.stdout.write(pZ))}disableInputProtocols(){this.terminal.write(MY),this.terminal.write(`\x1B[?2004l`),this.terminal.kittyProtocolActive&&this.terminal.write(`\x1B[<u`)}setupWarningInterceptor(){this.originalWarningListeners||(this.originalWarningListeners=H.rawListeners(`warning`),H.removeAllListeners(`warning`),this.warningInterceptor=()=>{},H.on(`warning`,this.warningInterceptor))}setupSuspendHandler(){if(H.platform===`win32`||!this.ownsTui)return()=>{};let e=!1,t=()=>{e=this.terminal.kittyProtocolActive,H.stdout.isTTY&&(this.disableInputProtocols(),H.stdout.write(pZ)),H.stdin.isTTY&&H.stdin.isRaw&&H.stdin.setRawMode(!1),this.onSuspended?.(),H.removeListener(`SIGTSTP`,t),H.kill(H.pid,`SIGTSTP`)},n=()=>{H.stdin.isTTY&&H.stdin.setRawMode(!0),H.stdout.isTTY&&(H.stdout.write(mZ),this.terminal.write(`\x1B[?2004h`),this.terminal.write(jY),e&&this.terminal.write(`\x1B[>7u`)),H.on(`SIGTSTP`,t),this.tui.requestRender(!0)};return H.on(`SIGTSTP`,t),H.on(`SIGCONT`,n),()=>{H.removeListener(`SIGTSTP`,t),H.removeListener(`SIGCONT`,n)}}waitUntilExit(){return this.exitPromise}getRootNode(){return this.rootNode}};function LMe(e,t){let n=new IMe(t),r=Z.createElement(RX,{tui:n.tui,terminal:n.terminal,terminalOutput:n.terminalOutput,exit:e=>n.exit(e),requestFullRedraw:()=>n.requestFullRedraw(),children:e});return n.render(r),n.start(),{rerender(e){let t=Z.createElement(RX,{tui:n.tui,terminal:n.terminal,terminalOutput:n.terminalOutput,exit:e=>n.exit(e),requestFullRedraw:()=>n.requestFullRedraw(),children:e});n.render(t)},unmount(){n.unmount()},waitUntilExit(){return n.waitUntilExit()},requestFullRedraw(){n.requestFullRedraw()},cleanupTerminal(){n.cleanupTerminal()}}}function Q({children:e,...t}){return(0,X.jsx)(`jar-view`,{style:{flexWrap:`nowrap`,flexDirection:`row`,flexGrow:0,flexShrink:1,...t,overflowX:t.overflowX??t.overflow??`visible`,overflowY:t.overflowY??t.overflow??`visible`},children:e})}function $({color:e,backgroundColor:t,dimColor:n=!1,bold:r=!1,italic:i=!1,underline:a=!1,strikethrough:o=!1,inverse:s=!1,wrap:c=`wrap`,transform:l,children:u}){if(u==null)return null;let d=(0,Z.useCallback)(c=>(n&&(c=cZ().dim().render(c)),e&&(c=sZ(c,e,`foreground`)),t&&(c=sZ(c,t,`background`)),r&&(c=cZ().bold().render(c)),i&&(c=cZ().italic().render(c)),a&&(c=cZ().underline().render(c)),o&&(c=cZ().strikethrough().render(c)),s&&(c=cZ().reverse().render(c)),l&&(c=l(c)),c),[e,t,n,r,i,a,o,s,l]);return(0,X.jsx)(`jar-text`,{style:{flexGrow:0,flexShrink:0,flexDirection:`row`,textWrap:c},internal_transform:d,children:u})}const RMe=/\x1b\[[\d:]*;(\d+)/;function zMe(e){let t=RMe.exec(e);return t?(parseInt(t[1],10)-1&8)!=0:!1}const bZ={upArrow:!1,downArrow:!1,leftArrow:!1,rightArrow:!1,pageDown:!1,pageUp:!1,home:!1,end:!1,return:!1,escape:!1,ctrl:!1,shift:!1,tab:!1,backspace:!1,delete:!1,meta:!1,super:!1,paste:!1,raw:``},xZ=(e,t={})=>{let{addInputListener:n}=(0,Z.use)(FX),r=(0,Z.useRef)(e);r.current=e,(0,Z.useEffect)(()=>{if(t.isActive!==!1)return n(e=>{if(pY(e))return;if(e.startsWith(`\x1B[200~`)){let t=e.indexOf(`\x1B[201~`),n=t===-1?e.slice(6):e.slice(6,t);bZ.upArrow=!1,bZ.downArrow=!1,bZ.leftArrow=!1,bZ.rightArrow=!1,bZ.pageDown=!1,bZ.pageUp=!1,bZ.home=!1,bZ.end=!1,bZ.return=!1,bZ.escape=!1,bZ.ctrl=!1,bZ.shift=!1,bZ.tab=!1,bZ.backspace=!1,bZ.delete=!1,bZ.meta=!1,bZ.super=!1,bZ.paste=!0,bZ.raw=e,r.current(n,{...bZ});return}let t=qAe(e),n=t?t.split(`+`):[],i=n[n.length-1]??``,a=n.includes(`ctrl`),o=n.includes(`shift`),s=n.includes(`alt`);bZ.upArrow=i===`up`,bZ.downArrow=i===`down`,bZ.leftArrow=i===`left`,bZ.rightArrow=i===`right`,bZ.pageDown=i===`pagedown`,bZ.pageUp=i===`pageup`,bZ.home=i===`home`,bZ.end=i===`end`,bZ.return=i===`return`||i===`enter`,bZ.escape=i===`escape`,bZ.ctrl=a,bZ.shift=o,bZ.tab=i===`tab`,bZ.backspace=i===`backspace`,bZ.delete=i===`delete`,bZ.meta=s,bZ.super=zMe(e),bZ.paste=!1,bZ.raw=e;let c=bZ,l=``;if(a&&i)l=i;else if(!c.upArrow&&!c.downArrow&&!c.leftArrow&&!c.rightArrow&&!c.pageDown&&!c.pageUp&&!c.home&&!c.end&&!c.return&&!c.escape&&!c.tab&&!c.backspace&&!c.delete){let t=XAe(e);t===void 0?e.length===1?l=e:i.length===1&&(l=i):l=t}r.current(l,{...c})})},[t.isActive,n])},BMe=()=>{let e=(0,Z.use)(IX);if(!e)throw Error(`useApp must be used within a jar render context`);return{exit:e.exit,requestFullRedraw:e.requestFullRedraw}},SZ=({isActive:e=!0,autoFocus:t=!1,id:n}={})=>{let{activeId:r,add:i,remove:a,activate:o,deactivate:s,focus:c}=(0,Z.use)(NX),l=(0,Z.useMemo)(()=>n??Math.random().toString().slice(2,7),[n]);return(0,Z.useEffect)(()=>(i(l,{autoFocus:t}),()=>{a(l)}),[l,t]),(0,Z.useEffect)(()=>{e?o(l):s(l)},[e,l]),{isFocused:!!l&&r===l,focus:c}};function CZ(){return(0,Z.use)(PX)}const wZ=()=>{let e=(0,Z.use)(LX);if(!e)throw Error(`useTerminal must be used within a jar render context`);return e.output},TZ=RegExp(`[\\x1b\\x9b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><~]|\\x1b\\][\\s\\S]*?(?:\\x07|\\x1b\\\\)`,`g`);function VMe(){return new RegExp(TZ.source,`g`)}function HMe(e){return e.replace(TZ,``)}function UMe(e){return e.replace(/[\x07\x1b\x9c]/g,``)}function EZ(e){return`\x1B]2;`+UMe(e)+`\x07`}var DZ=G(((e,t)=>{t.exports={name:`@codellm/cli`,version:`2.4.9-canary.3`,private:!0,bin:{abacusai:`dist/index.mjs`},files:[`dist`,`LICENSE.txt`],type:`module`,scripts:{"prepare-publish":`bun ./scripts/prepare-publish.ts`,build:`tsdown`,"check-types":`tsgo -b --noEmit`,test:`FORCE_COLOR=1 vitest run`,"test:watch":`FORCE_COLOR=1 vitest`,"test:ui":`FORCE_COLOR=1 vitest --ui`,"test:coverage":`FORCE_COLOR=1 vitest run --coverage`},dependencies:{"@clack/prompts":`^0.11.0`,"@codellm/agent":`workspace:*`,"@codellm/api":`workspace:*`,"@codellm/auth":`workspace:*`,"@codellm/comms":`workspace:*`,"@codellm/jar":`workspace:*`,"@codellm/logging":`workspace:*`,"@codellm/product":`workspace:*`,"@logtape/logtape":`^2.0.5`,"@orpc/client":`catalog:`,"@orpc/contract":`catalog:`,"@orpc/server":`catalog:`,"@sentry/node-core":`10.46.0`,"@slack/web-api":`^7.0.0`,"@tanstack/react-query":`^5.90.19`,"@vscode/ripgrep":`1.17.0`,"ansi-styles":`^6.2.3`,"beautiful-mermaid":`^1.1.3`,"cli-boxes":`^4.0.1`,"cli-highlight":`^2.1.11`,conf:`^15.0.2`,diff:`^8.0.3`,fzf:`^0.5.2`,"gradient-string":`^3.0.0`,immer:`^11.1.4`,"isomorphic-git":`^1.36.1`,marked:`^17.0.4`,"patchright-core":`^1.58.2`,react:`^19.2.3`,"react-compiler-runtime":`^1.0.0`,remend:`^1.2.2`,semver:`^7.7.4`,"shell-history":`^2.0.1`,"string-width":`^8.1.0`,"strip-ansi":`^7.2.0`,trash:`^9.0.0`,zod:`catalog:`},devDependencies:{"@codellm/configs":`workspace:*`,"@playwright/mcp":`^0.0.68`,"@types/diff":`^8.0.0`,"@types/node":`catalog:`,"@types/react":`^19.2.9`,"@types/semver":`^7.7.1`,"@typescript/native-preview":`catalog:`,"@vitejs/plugin-react":`^5.1.2`,"@vitest/coverage-v8":`^4.0.18`,"@vitest/ui":`^4.0.18`,"@xterm/addon-serialize":`^0.14.0`,"@xterm/headless":`^6.0.0`,"babel-plugin-react-compiler":`^1.0.0`,"cli-testing-library":`^3.0.1`,jsdom:`^27.4.0`,"node-pty":`^1.1.0`,"react-devtools-core":`^6.1.5`,"svg-term-cli":`^2.1.1`,tsdown:`^0.21.0`,vite:`catalog:`,vitest:`^4.0.18`},engines:{node:`>=18`}}})),OZ=Qe(DZ(),1);let kZ=null;function AZ(e){let t=(0,xJ.prerelease)(e);return t&&t.length>0&&typeof t[0]==`string`?t[0]:`latest`}function jZ(e){if(!e)return``;try{return y(e)}catch{return e}}function MZ(){return{invokedPath:jZ(process.argv[1]??``),execPath:jZ(process.execPath??process.argv[0]??``)}}function NZ(e){let t=hn.configDirName.replace(/^\./,``).replace(/[.*+?^${}()|[\]\\]/g,`\\$&`);return RegExp(`[/\\\\]\\.?${t}[/\\\\]bin[/\\\\]`,`i`).test(e)}function PZ(e){return/[/\\]node_modules[/\\]/.test(e)||/[/\\]\._npx[/\\]/.test(e)||/[/\\]_npx[/\\]/.test(e)||/[/\\]\.?npm[/\\]/.test(e)||/[/\\]\.?pnpm[/\\]/.test(e)||/[/\\]\.?yarn[/\\]/.test(e)||/[/\\]\.bun[/\\]/.test(e)}function FZ(){let e=(process.env.npm_command??``).toLowerCase();if(e===`exec`||e===`dlx`)return!0;let{invokedPath:t,execPath:n}=MZ();return/[/\\]_npx[/\\]|[/\\]dlx[/\\]|[/\\]\.cache[/\\]/.test(t+`|`+n)}function IZ(){let e=process.env.npm_config_user_agent;if(e){let t=e.split(`/`)[0];if(t===`yarn`||t===`pnpm`||t===`bun`||t===`npm`)return t}let{invokedPath:t,execPath:n}=MZ(),r=`${t}|${n}`;return/[/\\]\.?yarn[/\\]/.test(r)?`yarn`:/[/\\]\.?pnpm[/\\]/.test(r)?`pnpm`:/[/\\]\.bun[/\\]/.test(r)||process.versions.bun!==void 0&&!NZ(n)?`bun`:`npm`}function WMe(){let{execPath:e,invokedPath:t}=MZ();return PZ(t)||PZ(e)?!1:NZ(e)||NZ(t)}function LZ(){let e=`${hn.internalEnvPrefix}DEV`,t=process.env[e];if(t===`1`||t===`true`)return!0;let{invokedPath:n,execPath:r}=MZ();return!(NZ(r)||NZ(n)||PZ(n)||PZ(r)||process.env.npm_config_user_agent)}function GMe(){let{execPath:e}=MZ(),t=IZ(),n=FZ();return LZ()?{installationType:`development`,packageManager:t,isEphemeral:n,execPath:e}:WMe()?{installationType:`native`,packageManager:t,isEphemeral:n,execPath:e}:{installationType:`package-manager`,packageManager:t,isEphemeral:n,execPath:e}}function KMe(){return`${process.platform===`win32`?`win32`:process.platform===`darwin`?`darwin`:`linux`}-${process.arch===`arm64`?`arm64`:`x64`}`}async function qMe(e){let t=Date.now();if(kZ&&t-kZ.timestamp<6e4)return kZ.tags;let n=await fetch(`https://registry.npmjs.org/${e}`,{signal:AbortSignal.timeout(1e4),headers:{accept:`application/json`}});if(!n.ok)throw Error(`Registry returned ${n.status}`);let r=(await n.json())[`dist-tags`]??{};return kZ={tags:r,timestamp:t},r}async function JMe(e,t,n,r){let i=t??AZ(e),a=(r??`https://apps.abacus.ai`).replace(/\/$/,``),o=new URL(`${a}/api/v0/_getCodellmCliVersion`);o.searchParams.set(`channel`,i),n&&o.searchParams.set(`platform`,n),o.searchParams.set(`cli_version`,e);let s=await fetch(o.toString(),{signal:AbortSignal.timeout(1e4)});if(s.status===204)return null;if(!s.ok)throw Error(`API returned ${s.status}`);let c=await s.json(),l=c&&`result`in c&&c.result?c.result:c??{};if(!l.version||!l.channel)throw Error(`API returned invalid payload`);return{currentVersion:e,latestVersion:l.version,tag:l.channel,packageManager:IZ(),isEphemeral:FZ(),installationType:`native`,downloadUrl:l.url}}async function YMe(e,t){let n=t??AZ(e),r=IZ(),i=FZ(),a=(await qMe(gn.publishName))[n];return!a&&n!==`latest`||!a||a===e?null:{currentVersion:e,latestVersion:a,tag:n,packageManager:r,isEphemeral:i,installationType:`package-manager`}}async function RZ(e,t,n,r){let i=GMe();if(i.installationType===`native`)try{return await JMe(e,t,KMe(),n)}catch{return null}return i.installationType===`development`&&!r?.includeDev?null:await YMe(e,t)}function zZ(e){if(e.installationType===`native`)return`${hn.binName} upgrade`;let t=`${gn.publishName}@${e.tag}`;switch(e.packageManager){case`yarn`:return`yarn global add ${t}`;case`pnpm`:return`pnpm add -g ${t}`;case`bun`:return`bun add -g ${t}`;default:return`npm install -g ${t}`}}function BZ(e){try{return{ok:!0,output:le(zZ(e),{stdio:`pipe`,encoding:`utf-8`}).trim()}}catch(e){return{ok:!1,output:e instanceof Error&&`stderr`in e?String(e.stderr).trim():e instanceof Error?e.message:`Unknown error`}}}async function VZ(e){if(!e.downloadUrl)return{ok:!1,output:`No download URL`};let t=D.join(P.tmpdir(),`abacusai-update-${Date.now()}`),n=D.join(P.homedir(),hn.configDirName,`bin`),r=process.platform===`win32`,i=r?`${hn.binName}.exe`:hn.binName;try{await we.mkdir(t,{recursive:!0}),await we.mkdir(n,{recursive:!0});let a=D.join(t,r?`update.zip`:`update.tar.gz`),o=await fetch(e.downloadUrl);if(!o.ok)throw Error(`Download failed: ${o.status}`);let s=Buffer.from(await o.arrayBuffer());await we.writeFile(a,s),le(r?`powershell -Command "Expand-Archive -Path '${a}' -DestinationPath '${t}' -Force"`:`tar -xzf "${a}" -C "${t}"`,{stdio:`pipe`});let c=D.join(t,i),l=D.join(n,i);return await we.copyFile(c,l),r||await we.chmod(l,493),{ok:!0,output:`Updated to ${e.latestVersion}`}}catch(e){return{ok:!1,output:e instanceof Error?e.message:`Unknown error`}}finally{await we.rm(t,{recursive:!0,force:!0}).catch(()=>{})}}function XMe(e,t){let n=e=>{let n=e.toLowerCase();if(n===t)return 1e3;if(n.startsWith(t))return 900;let r=0,i=-1;for(let e of t){let t=n.indexOf(e,i+1);if(t===-1)return 0;r+=100-(t-i),i=t}return r+=Math.max(0,50-n.length),r},r=null,i=0;for(let t of e){let e=Math.max(n(t.name??``),n(t.llmName));e>i&&(i=e,r=t.llmName)}return i>=100?r:null}async function HZ(e,t){let n=(await e.listLLMModels())?.result??[];return n.length||(process.stderr.write(`Error: No models available.
75144
75144
  `),process.exit(1)),t?XMe(n,t.toLowerCase())||(process.stderr.write(`Warning: Model "${t}" not found. Using default: ${n[0].llmName}\n`),n[0].llmName):n[0].llmName}const UZ=dt([`codellm`,`cli`,`exit`]),WZ=new Set,GZ=new Set,KZ=new Set;let qZ=!1,JZ=!1,YZ=null,XZ;async function ZMe(e){let t=e.map(e=>new Promise(t=>{let n=`writableLength`in e?e.writableLength:0;if((`bufferSize`in e?e.bufferSize:n)===0){t();return}let r=e.write.bind(e),i=!1,a=()=>{let n=`writableLength`in e?e.writableLength:0;(`bufferSize`in e?e.bufferSize:n)===0&&!i&&(i=!0,e.write=r,t())};e.once(`drain`,a),e.write(``,`utf-8`,()=>{a()}),e.write=function(){return!1}}));await Promise.all(t)}async function ZZ(e,t,n,r){if(qZ)return;r?.debug?.(`Executing exit handlers`,{shouldManuallyExit:e,isSynchronous:t,signal:n,asyncCallbacks:WZ.size,syncCallbacks:GZ.size}),qZ=!0,WZ.size>0&&t&&UZ.error`SYNCHRONOUS TERMINATION NOTICE: When explicitly exiting the process via process.exit or via a parent process, asynchronous tasks in your exitHooks will not run. Either remove these tasks, use gracefulExit() instead of process.exit(), or ensure your parent process sends a SIGINT to the process running this code.`;let i=0;n>0?i=128+n:XZ===void 0?(typeof H.exitCode==`number`||typeof H.exitCode==`string`)&&(i=Number(H.exitCode)):i=XZ;let a=(t=!1)=>{(t||e)&&(YZ?YZ.call(H,i):H.exit(i))};for(let e of GZ)try{e(i)}catch(e){UZ.error`Error in synchronous exit hook: ${e}`}if(t){a();return}let o=[],s=0;for(let[e,t]of WZ)s=Math.max(s,t),o.push(Promise.resolve(e(i)).catch(e=>{UZ.error`Error in asynchronous exit hook: ${e}`}));let c=Array.from(KZ);c.length>0&&o.push(ZMe(c));let l=setTimeout(()=>{a(!0)},s);try{await Promise.all(o),clearTimeout(l),a()}catch(e){clearTimeout(l),UZ.error`Error during exit cleanup: ${e}`,a(!0)}}function QMe(){JZ||(JZ=!0,H.once(`beforeExit`,()=>{ZZ(!0,!1,-128)}),H.once(`SIGINT`,()=>{ZZ(!0,!1,2)}),H.once(`SIGTERM`,()=>{ZZ(!0,!1,15)}),H.once(`exit`,()=>{ZZ(!1,!0,0)}),H.on(`message`,e=>{e===`shutdown`&&ZZ(!0,!0,-128)}),YZ||(YZ=H.exit.bind(H),H.exit=function(e){if(XZ===void 0&&(XZ=e??0),WZ.size===0&&KZ.size===0){if(YZ){YZ(e??0);return}H.exit(e??0)}ZZ(!0,!1,-128).catch(e=>{UZ.error`Error during exit: ${e}`,YZ?YZ(1):H.exit(1)})}))}function QZ(e,t){if(typeof e!=`function`)throw TypeError(`callback must be a function`);if(qZ)throw Error(`Cannot install exit hook while exit handlers are running`);t?.logger?.debug?.(`Registering exit hook`,{wait:t?.wait,hasStreams:t?.streams!==void 0}),QMe();let n=t?.wait??0,r=t?.streams??[H.stdout,H.stderr];if(n>0){let t=[e,n];WZ.add(t);for(let e of r)KZ.add(e);return()=>{WZ.delete(t);for(let e of r)KZ.delete(e)}}return GZ.add(e),()=>{GZ.delete(e)}}function $Z(e){e!==void 0&&(H.exitCode=e),ZZ(!0,!1,-128)}const eQ=`${hn.internalEnvPrefix}CLIENT_KIND`;function $Me(){let e=process.env[eQ]?.trim();if(!e)return tt.CLI;try{return nt(e)}catch{throw Error(`Invalid ${eQ} value: ${e}. Expected one of ${Object.values(tt).join(`, `)}.`)}}function tQ(e){process.stdout.write(JSON.stringify(e)+`
75145
75145
  `)}function eNe(e){try{return JSON.parse(e)}catch{return null}}async function tNe({agentArgs:e}){Al(`ndjson IPC host started`,`cli`);let t=$Me(),n=await PJ.create(),r=new Ul(n,Sn(),gn.userAgentNames.desktop,OZ.default.version);if(!n.isAuthenticated())try{(await r.getUserInfo())?.result?.email||(process.stderr.write(`Error: Not authenticated. Set ABACUS_DEVICE_CODE environment variable.
75146
75146
  `),process.exit(1))}catch{process.stderr.write(`Error: Not authenticated. Set ABACUS_DEVICE_CODE environment variable.
75147
75147
  `),process.exit(1)}let i=process.cwd(),a=t===tt.COWORK?`desktop`:`cli`,o=new _q({cwd:i,extraSources:[{read:async()=>({client:a})}]});await o.load();let s=o.get(`baseUrl`);if(s){try{new URL(s)}catch{process.stderr.write(`Invalid baseUrl: ${s}\n`),process.exit(1)}r.setUrl(s),r.resetEndpoints(),await r.getApiEndpoint()}let c=await HZ(r,e?.model),l=new Map,u=0,d=new mq(async e=>{let t=`perm-${++u}`;return tQ({type:`permission_needed`,permissionId:t,request:e}),new Promise(e=>{l.set(t,{resolve:e})})}),f=xd.Normal,p=e?.[`permission-mode`];if(p)switch(p){case`normal`:f=xd.Normal;break;case`accept-edits`:f=xd.AcceptEdits;break;case`plan`:f=xd.PlanMode;break;case`yolo`:f=xd.Yolo;break}let m=new pq({allowedDirectories:[i,...e?.[`add-dir`]?.map(e=>O.isAbsolute(e)?e:O.resolve(i,e))??[]],primaryWorkspace:i,apiClient:r,mode:f,model:c,permissionProvider:d,config:o,isPrintMode:!1,enablePromptRewrite:!1,supportsThoughtStreaming:!0,enableSkills:!0,cliAllowedTools:e?.[`allowed-tools`],cliDisallowedTools:e?.[`disallowed-tools`],clientType:t});m.onAutoRestart=e=>{nQ(m,e)},QZ(async()=>{m.stop(),await new Promise(e=>setTimeout(e,200))},{wait:1e3}),tQ({type:`ready`,model:c,mode:f});let h=sq.loadSkills(i).then(()=>{tQ({type:`skills_loaded`,skills:sq.getAllMetadata()})}).catch(e=>{Dl(e),process.stderr.write(`Failed to load skills: ${e}\n`)}),g=o.get(`autoUpdate`)!==!1;LZ()||RZ(OZ.default.version,o.get(`updateChannel`),o.get(`baseUrl`)).then(async e=>{if(!e||(tQ({type:`update_available`,currentVersion:e.currentVersion,latestVersion:e.latestVersion}),!g))return;tQ({type:`update_downloading`,latestVersion:e.latestVersion});let t=e.installationType===`native`?await VZ(e):BZ(e);t.ok?tQ({type:`update_complete`,latestVersion:e.latestVersion}):tQ({type:`update_failed`,latestVersion:e.latestVersion,error:t.output||`Update failed`})}).catch(e=>{Dl(e)});let _=B.createInterface({input:process.stdin});_.on(`line`,async e=>{let t=e.trim();if(!t)return;let n=eNe(t);if(n)switch(n.type){case`send`:{let e=n.message??``,t=n.conversationId,r=Array.isArray(n.activeSkills)?n.activeSkills:void 0;t&&m.getConversationId()!==t&&await m.switchConversation(t),nQ(m,e,r);break}case`stop`:m.stop();break;case`list_skills`:h.then(()=>{tQ({type:`skills_loaded`,skills:sq.getAllMetadata()})});break;case`switch_conversation`:{let e=n.conversationId;e&&(m.switchConversation(e),tQ({type:`event`,event:{type:`status_changed`,status:`idle`}}));break}case`reset_conversation`:m.resetConversation(),tQ({type:`event`,event:{type:`status_changed`,status:`idle`}});break;case`set_mode`:{let e=nNe(n.mode??`DEFAULT`);m.setMode(e);break}case`set_model`:{let e=n.model;e&&(m.setModel(e),tQ({type:`event`,event:{type:`model_changed`,model:e}}));break}case`set_folder`:{let e=n.folder;e&&m.setWorkspace(e);break}case`enqueue`:{let e=n.message??``,t=n.hidden??!1;m.nq(e,{hidden:t}),tQ({type:`queue_updated`,messages:m.getQueueEntries()});break}case`dequeue`:{let e=n.includeHidden??!1,t=n.id,r=m.dq({includeHidden:e,...t?{id:t}:{}});tQ({type:`queue_updated`,messages:m.getQueueEntries(),dequeued:r.map(e=>e.message)});break}case`get_queue`:{let e=n.includeHidden??!1;tQ({type:`queue_updated`,messages:m.getQueueEntries({includeHidden:e})});break}case`clear_queue`:{let e=n.includeHidden??!1;m.clearQueue({includeHidden:e}),tQ({type:`queue_updated`,messages:m.getQueueEntries()});break}case`remove_from_queue`:{let e=n.id,t=n.index;if(e)m.remove(e,{includeHidden:!0});else if(typeof t==`number`){let e=m.getQueueEntries()[t];e&&m.remove(e.id)}tQ({type:`queue_updated`,messages:m.getQueueEntries()});break}case`permission_response`:{let e=n.permissionId,t=n.decision,r=l.get(e);r&&(r.resolve(t),l.delete(e));break}}}),_.on(`close`,()=>{process.exit(0)})}async function nQ(e,t,n){try{for await(let r of e.send(t,{activeSkills:n}))tQ({type:`event`,event:r})}catch(e){Dl(e),tQ({type:`event`,event:{type:`error`,error:{message:e instanceof Error?e.message:String(e)}}})}}function nNe(e){switch(e){case`DEFAULT`:return xd.Normal;case`ACCEPTEDITS`:return xd.AcceptEdits;case`PLAN`:return xd.PlanMode;case`YOLO`:return xd.Yolo;default:return xd.Normal}}const rNe=dt([`codellm`,`cli`,`print-mode`]);async function iNe(){let e=await PJ.create();return{apiClient:new Ul(e,Sn(),gn.userAgentNames.print,OZ.default.version),authManager:e}}function rQ(e){process.stdout.write(JSON.stringify(e)+`
75148
- `)}async function aNe(e,t){if(e?.resume)return e.resume;if(e?.continue)try{return((await t.getConversationsList(`CODE_LLM_AGENT`))?.result??[]).sort((e,t)=>{let n=e.lastEventCreatedAt?new Date(e.lastEventCreatedAt).getTime():0;return(t.lastEventCreatedAt?new Date(t.lastEventCreatedAt).getTime():0)-n})[0]?.deploymentConversationId}catch{}return e?.conversationId}async function oNe({agentArgs:e}){Al(`print-mode started`,`cli`);let{apiClient:t,authManager:n}=await iNe(),r=process.cwd(),i=new _q({cwd:r,extraSources:[{read:async()=>({client:`cli`})}]});await i.load(),LZ()||RZ(OZ.default.version,i.get(`updateChannel`),i.get(`baseUrl`)).then(e=>{if(e){let t=e.isEphemeral?`\nUpdate available: ${e.currentVersion} → ${e.latestVersion} (${e.tag})\n`:e.installationType===`native`&&i.get(`autoUpdate`)!==!1?`\nUpdate available: ${e.currentVersion} → ${e.latestVersion} (${e.tag}). Restart to auto-update.\n`:`\nUpdate available: ${e.currentVersion} → ${e.latestVersion} (${e.tag}). Run: ${zZ(e)}\n`;process.stderr.write(t)}}).catch(e=>{Dl(e)});let a=i.get(`baseUrl`);if(a){try{new URL(a)}catch{rNe.error`Invalid baseUrl: ${a}`,process.exit(1)}t.setUrl(a),t.resetEndpoints(),await t.getApiEndpoint()}!n.isAuthenticated()&&!n.isEnvAuth()&&(process.stderr.write(`Not authenticated. Set ${hn.envPrefix}API_KEY environment variable or run interactively to log in.\n`),process.exit(1));let o=e?.[`output-format`]??`text`,s=await HZ(t,e?.model),c=xd.Yolo,l=e?.[`permission-mode`];if(l)switch(l){case`normal`:c=xd.Normal;break;case`accept-edits`:c=xd.AcceptEdits;break;case`plan`:c=xd.PlanMode;break;default:c=xd.Yolo;break}let u=new pq({allowedDirectories:[r,...e?.[`add-dir`]?.map(e=>O.isAbsolute(e)?e:O.resolve(r,e))??[]],primaryWorkspace:r,apiClient:t,mode:c,model:s,permissionProvider:new BOe,config:i,isPrintMode:!0,enablePromptRewrite:!1,supportsThoughtStreaming:!0,cliAllowedTools:e?.[`allowed-tools`],cliDisallowedTools:e?.[`disallowed-tools`],clientType:tt.CLI});QZ(async()=>{u.stop(),await new Promise(e=>setTimeout(e,200))},{wait:1e3});let d=await aNe(e,t);if(d)try{let e=await u.loadConversation(d);e.llmName&&(s=e.llmName,u.setModel(e.llmName))}catch(e){throw Dl(e),e}let f=e?.prompt??``;process.env.DEEPAGENT_HIGH_QUALITY===`true`&&(f=`
75148
+ `)}async function aNe(e,t){if(e?.resume)return e.resume;if(e?.continue)try{return((await t.getConversationsList(hn.nonInteractiveAgentType))?.result??[]).sort((e,t)=>{let n=e.lastEventCreatedAt?new Date(e.lastEventCreatedAt).getTime():0;return(t.lastEventCreatedAt?new Date(t.lastEventCreatedAt).getTime():0)-n})[0]?.deploymentConversationId}catch{}return e?.conversationId}async function oNe({agentArgs:e}){Al(`print-mode started`,`cli`);let{apiClient:t,authManager:n}=await iNe(),r=process.cwd(),i=new _q({cwd:r,extraSources:[{read:async()=>({client:`cli`})}]});await i.load(),LZ()||RZ(OZ.default.version,i.get(`updateChannel`),i.get(`baseUrl`)).then(e=>{if(e){let t=e.isEphemeral?`\nUpdate available: ${e.currentVersion} → ${e.latestVersion} (${e.tag})\n`:e.installationType===`native`&&i.get(`autoUpdate`)!==!1?`\nUpdate available: ${e.currentVersion} → ${e.latestVersion} (${e.tag}). Restart to auto-update.\n`:`\nUpdate available: ${e.currentVersion} → ${e.latestVersion} (${e.tag}). Run: ${zZ(e)}\n`;process.stderr.write(t)}}).catch(e=>{Dl(e)});let a=i.get(`baseUrl`);if(a){try{new URL(a)}catch{rNe.error`Invalid baseUrl: ${a}`,process.exit(1)}t.setUrl(a),t.resetEndpoints(),await t.getApiEndpoint()}!n.isAuthenticated()&&!n.isEnvAuth()&&(process.stderr.write(`Not authenticated. Set ${hn.envPrefix}API_KEY environment variable or run interactively to log in.\n`),process.exit(1));let o=e?.[`output-format`]??`text`,s=await HZ(t,e?.model),c=xd.Yolo,l=e?.[`permission-mode`];if(l)switch(l){case`normal`:c=xd.Normal;break;case`accept-edits`:c=xd.AcceptEdits;break;case`plan`:c=xd.PlanMode;break;default:c=xd.Yolo;break}let u=new pq({allowedDirectories:[r,...e?.[`add-dir`]?.map(e=>O.isAbsolute(e)?e:O.resolve(r,e))??[]],primaryWorkspace:r,apiClient:t,mode:c,model:s,permissionProvider:new BOe,config:i,isPrintMode:!0,enablePromptRewrite:!1,supportsThoughtStreaming:!0,cliAllowedTools:e?.[`allowed-tools`],cliDisallowedTools:e?.[`disallowed-tools`],clientType:tt.CLI});QZ(async()=>{u.stop(),await new Promise(e=>setTimeout(e,200))},{wait:1e3});let d=await aNe(e,t);if(d)try{let e=await u.loadConversation(d);e.llmName&&(s=e.llmName,u.setModel(e.llmName))}catch(e){throw Dl(e),e}let f=e?.prompt??``;process.env.DEEPAGENT_HIGH_QUALITY===`true`&&(f=`
75149
75149
  IMPORTANT INSTRUCTIONS: Your task is to follow the <task_description> EXACTLY and verify the solution within the FIXED TIME LIMIT.
75150
75150
  A few things to keep in mind (Add Relevant ONES BELOW AS TODOS):
75151
75151
  1. You are in a docker container without user interaction and fixed time limit. Assume HIGHEST permissions are available to the user.
@@ -75244,7 +75244,7 @@ https://github.com/highlightjs/highlight.js/issues/2277`),a=e,i=t);let o={code:i
75244
75244
  [Contract-First] Missing or invalid implementation for procedure at path: ${h4(n.path)}.
75245
75245
  Ensure that the procedure is correctly defined and matches the expected contract.
75246
75246
  `);n.procedure=kHe(e,n.contract)}return{path:n.path,procedure:n.procedure}}}},LHe=class extends PHe{constructor(e,t={}){let n=new g4(new m4(t)),r=new IHe(t),i=new FHe(n);super(e,r,i,t)}},RHe=class{socketServer;socketPath;editorState={file:void 0,startLine:void 0,endLine:void 0};onEditorStateCallback=null;pendingDecisions=new Map;constructor(){let e=D.join(P.homedir(),hn.configDirName,`cli`);this.socketPath=D.join(e,`${process.pid}.sock`)}getEditorState(){return{...this.editorState}}onEditorChange(e){this.onEditorStateCallback=e}waitForDecision(e,t){return new Promise((n,r)=>{if(t?.aborted){r(Error(`Aborted`));return}let i=()=>{t?.removeEventListener(`abort`,a),this.pendingDecisions.delete(e)},a=()=>{i(),r(Error(`Aborted`))};t?.addEventListener(`abort`,a,{once:!0}),this.pendingDecisions.set(e,{resolve:e=>{i(),n(e)},cleanup:i})})}async start(){let e=D.dirname(this.socketPath);s.existsSync(e)||s.mkdirSync(e,{recursive:!0});let t=e3(nHe),n=t.router({editorStateChanged:t.editorStateChanged.handler(async({input:e})=>(this.editorState={file:e.file??void 0,startLine:e.startLine,endLine:e.endLine},this.onEditorStateCallback?.(this.editorState),{ok:!0})),toolDecision:t.toolDecision.handler(async({input:e})=>{let t=this.pendingDecisions.get(e.toolId);return t&&t.resolve(e.decision),{ok:!0}})});this.socketServer=await gHe(this.socketPath,new LHe(n))}dispose(){for(let[,e]of this.pendingDecisions)e.cleanup();this.pendingDecisions.clear(),this.socketServer?.dispose(),this.socketServer=void 0}},zHe=class{client=null;disposeSocket=null;currentFile=void 0;selectionStartLine=void 0;selectionEndLine=void 0;onFileChangeCallback=null;constructor(e){this.pushServer=e}findSocketPath(){let e=process.env[hn.socketEnvVar];if(e&&c.existsSync(e))return e;try{let e=O.join(ee.homedir(),hn.configDirName,hn.ideDirName),t=c.readdirSync(e).filter(e=>e.endsWith(`.sock`));if(t.length===0)return null;let n=null;for(let r of t){let t=O.join(e,r);try{let e=c.statSync(t);(!n||e.mtimeMs>n.mtime)&&(n={path:t,mtime:e.mtimeMs})}catch{}}if(n&&c.existsSync(n.path))return n.path}catch{}return null}async connect(){try{let e=this.findSocketPath();if(!e)return!1;let t=await yHe(e,{timeoutMs:2e3});this.client=c4(t.link),this.disposeSocket=()=>t.dispose(),await this.client.register({cliSocketPath:this.pushServer.socketPath,pid:process.pid});let n=this.pushServer.getEditorState();return this.currentFile=n.file,this.selectionStartLine=n.startLine,this.selectionEndLine=n.endLine,this.pushServer.onEditorChange(e=>{this.currentFile=e.file,this.selectionStartLine=e.startLine,this.selectionEndLine=e.endLine,this.onFileChangeCallback?.(e.file,e.startLine,e.endLine)}),!0}catch{return!1}}getCurrentFile(){return this.currentFile}getSelectionRange(){return{startLine:this.selectionStartLine,endLine:this.selectionEndLine}}isConnected(){return this.client!==null}onFileChange(e){this.onFileChangeCallback=e}async showDiff(e){if(!this.client)return!1;try{return(await this.client.showDiff({...e,cliSocketPath:this.pushServer.socketPath})).success}catch{return!1}}async showToolView(e){if(!this.client)return!1;try{return(await this.client.showToolView({...e,cliSocketPath:this.pushServer.socketPath})).success}catch{return!1}}async notifyDiffDecision(e){if(!this.client)throw Error(`Not connected to extension`);await this.client.notifyDiffDecision(e)}async openPlanFile(e){if(!this.client)throw Error(`Not connected to extension`);return{opened:(await this.client.openFile({file:e})).success}}async getDiagnostics(e){if(!this.client)throw Error(`Not connected to extension`);return this.client.getDiagnostics({...e&&{files:e}})}dispose(){this.disposeSocket?.(),this.disposeSocket=null,this.client=null,this.currentFile=void 0,this.selectionStartLine=void 0,this.selectionEndLine=void 0,this.onFileChangeCallback=null}};const t3=(0,Z.createContext)(null);function n3(){let e=(0,Z.use)(t3);if(!e)throw Error(`useExtensionFile must be used within ExtensionFileProvider`);return e}function BHe({children:e,initialFile:t}){let[n,r]=(0,Z.useState)(t),[i,a]=(0,Z.useState)(void 0),[o,s]=(0,Z.useState)(void 0),[c,l]=(0,Z.useState)(null),[u,d]=(0,Z.useState)(null),f=(0,Z.useRef)(null),p=(0,Z.useRef)(null);return(0,Z.useEffect)(()=>{let e=!1;return(async()=>{let t=new RHe;try{await t.start()}catch{}if(e){t.dispose();return}p.current=t,d(t),t.onEditorChange(e=>{r(e.file),a(e.startLine),s(e.endLine)});for(let n of[0,...[500,1e3,2e3,3e3,4e3]]){if(e||(n>0&&await new Promise(e=>setTimeout(e,n)),e))return;try{let n=new zHe(t);if(await n.connect()){if(e){n.dispose();return}let i=t.getEditorState();r(i.file),a(i.startLine),s(i.endLine),n.onFileChange((e,t,n)=>{r(e),a(t),s(n)}),f.current=n,l(n);return}}catch{}}})(),()=>{e=!0,f.current&&(f.current.dispose(),f.current=null,l(null)),p.current&&(p.current.dispose(),p.current=null,d(null))}},[]),(0,X.jsx)(t3.Provider,{value:{currentFile:n,selectionStartLine:i,selectionEndLine:o,connection:c,pushServer:u},children:e})}const r3=(0,Z.createContext)(null);function VHe({children:e}){let[t,n]=(0,Z.useState)(`idle`),r=(0,Z.useCallback)(()=>n(`upload`),[]),i=(0,Z.useCallback)(()=>n(`download`),[]),a=(0,Z.useCallback)(()=>n(`idle`),[]),o=(0,Z.useMemo)(()=>({activity:t,setActivity:n,startUpload:r,startDownload:i,stopActivity:a}),[t,r,i,a]);return(0,X.jsx)(r3.Provider,{value:o,children:e})}function i3(){let e=(0,Z.use)(r3);if(!e)throw Error(`useNetworkActivity must be used within NetworkActivityProvider`);return e}const a3=(0,Z.createContext)(null),HHe=()=>{let e=(0,Z.use)(a3);if(!e)throw Error(`useNotification must be used within NotificationProvider`);return e},UHe=({children:e})=>{let{isFocused:t}=CZ(),n=wZ(),r=(0,Z.useRef)(t);r.current=t;let i=(0,Z.useCallback)((e,t)=>{r.current||n.notify({body:e,title:t})},[n]),a=(0,Z.useCallback)(e=>{r.current||n.notify({body:e,title:`Action Required`})},[n]),o=(0,Z.useCallback)(e=>{r.current||n.notify({body:e,title:`Task Complete`})},[n]),s=(0,Z.useMemo)(()=>({notifyIfUnfocused:i,notifyActionRequired:a,notifyTaskComplete:o}),[i,a,o]);return(0,X.jsx)(a3.Provider,{value:s,children:e})},o3=(0,Z.createContext)(null),s3=()=>{let e=(0,Z.use)(o3);if(!e)throw Error(`useApiClient must be used within ApiClientProvider`);return e},c3=(0,Z.memo)(({children:e,client:t,authManager:n,onAuthExpired:r})=>{let[i,a]=(0,Z.useState)(!1),o=(0,Z.useCallback)(()=>a(!1),[]),s=(0,Z.useMemo)(()=>({apiClient:t,authManager:n,authExpired:i,setAuthExpired:a,clearAuthExpired:o,onAuthExpired:r}),[i,t,n,o,r]);return(0,X.jsx)(o3.Provider,{value:s,children:e})});c3.displayName=`ApiClientProvider`;const l3=(0,Z.createContext)(null);function u3(e,t){let n=t?new Set(t):null;return e.map(e=>{if(e.type!==`code_llm_tool_call`||e.status!==`transient`||e.toolUseResult||n&&!n.has(e.id))return e;let t=Array.isArray(e.toolUseRequest)?e.toolUseRequest[0]?.id??e.id:e.toolUseRequest?.id??e.id;return{...e,status:`completed`,isStreamingArgs:!1,toolUseResult:{id:t,content:JSON.stringify({reason:yR.INTERRUPTED}),rejected:!0}}})}function WHe(e,t){switch(t.type){case`INIT_SEND`:return[...u3(e.filter(e=>e.temp!==!0)),t.userSeg,t.spinnySeg];case`TEXT_DELTA`:{let{segId:n,content:r}=t,i=u3(e).filter(e=>!e.isSpinny);return i.find(e=>e.id===n)?i.map(e=>e.id===n?{...e,segment:(e.segment||``)+r}:e):[...i,{id:n,status:`transient`,source:`bot`,type:`text`,segment:r}]}case`THINKING_DELTA`:{let{segId:n,content:r,startTime:i}=t;return e.find(e=>e.id===n)?e.map(e=>e.id===n?{...e,segment:(e.segment||``)+r}:e):[...e,{id:n,status:`transient`,source:`bot`,type:`thinking`,isSpinny:!0,segment:r,thinkingStartTime:i}]}case`THINKING_COMPLETE`:return e.map(e=>e.id===t.segId?{...e,status:`completed`,isSpinny:!1,thinkingEndTime:t.endTime}:e);case`TOOL_DISPLAY_DATA`:return e.map(e=>e.id===t.toolCallId?{...e,toolDisplayData:{...e.toolDisplayData,...t.data}}:e);case`TOOL_REQUESTED`:{let{textSegId:n,toolSeg:r}=t,i;return i=n?e.filter(e=>!e.isSpinny).map(e=>e.id===n?{...e,status:`completed`}:e):e.filter(e=>!e.isSpinny),[...i,r]}case`TOOL_EXECUTION_COMPLETE`:{let{toolCallId:n,rawResult:r,parsedResult:i,spinnySeg:a}=t;return[...e.map(e=>e.id===n?{...e,status:`completed`,toolUseResult:r,...i!==void 0&&{parsedResult:i}}:e),a]}case`TOOL_USER_MESSAGE`:return[...e,t.seg];case`TEXT_COMPLETED`:return e.map(e=>e.id===t.segId?{...e,status:`completed`}:e);case`TURN_COMPLETE`:{let n=u3(e,t.toolCallIds);return t.textSegId&&(n=n.map(e=>e.id===t.textSegId?{...e,status:`completed`}:e)),n}case`FINALIZE`:{let n=u3(e);return t.textSegId&&(n=n.map(e=>e.id===t.textSegId?{...e,status:`completed`}:e)),n.filter(e=>!e.isSpinny)}case`ADD_NOTIFICATION`:{let n=t.seg,r=e[e.length-1];if(r&&r.type===`code_llm_notification`&&r.message===n.message&&r.severity===n.severity){let t=[...e];return t[t.length-1]={...r,flashKey:(r.flashKey??0)+1},t}return[...e,n]}case`ERROR`:return[...u3(e).filter(e=>!e.isSpinny),t.errorSeg];case`REMOVE_USER_SEG`:return e.filter(e=>e.id!==t.userSegId);case`CLEAR`:return[];case`LOAD`:return t.segments;case`REMOVE_TEMP`:return e.some(e=>e.temp===!0)?e.filter(e=>e.temp!==!0):e;case`ADD_CREDITS`:return[...e,t.seg];case`TOOL_CALL_START`:{let{toolCallId:n,toolName:r,textSegId:i}=t,a;return a=i?e.filter(e=>!e.isSpinny).map(e=>e.id===i?{...e,status:`completed`}:e):e.filter(e=>!e.isSpinny),[...a,{id:n,status:`transient`,source:`bot`,type:`code_llm_tool_call`,toolUseRequest:{id:n,name:r,input:{}},isStreamingArgs:!0,streamingArguments:``}]}case`TOOL_CALL_DELTA`:{let{toolCallId:n,argumentsDelta:r}=t;return e.map(e=>e.id===n?{...e,streamingArguments:(e.streamingArguments??``)+r}:e)}case`TOOL_CALL_STOP`:{let{toolCallId:n,toolName:r,arguments:i}=t,a={};try{a=JSON.parse(i)}catch{}return e.map(e=>e.id===n?{...e,isStreamingArgs:!1,streamingArguments:i,toolUseRequest:{id:n,name:r,input:a}}:e)}default:return e}}function GHe(e){switch(e.type){case`text`:return{id:e.id,status:`completed`,source:e.source,type:`text`,segment:e.content};case`thinking`:return{id:e.id,status:`completed`,source:`bot`,type:`thinking`,segment:e.content,isSpinny:e.isSpinny,...e.title!==void 0&&{title:e.title}};case`tool_call`:return{id:e.id,status:`completed`,source:`bot`,type:`code_llm_tool_call`,toolUseRequest:e.toolUseRequest,toolUseResult:e.toolUseResult??{id:e.toolUseRequest.id,content:` `},...e.parsedResult!==void 0&&{parsedResult:e.parsedResult},...e.toolDisplayData!==void 0&&{toolDisplayData:e.toolDisplayData}};case`notification`:return{id:e.id,status:`completed`,source:`bot`,type:`code_llm_notification`,message:e.message,severity:e.severity,...e.actions!==void 0&&{actions:e.actions}};case`tool_group`:return{id:e.id,status:`completed`,source:`bot`,type:`text`,segment:e.summary}}}const d3=(0,Z.memo)(({children:e,apiClient:t,configService:n,agentArgs:r})=>{let{agentMode:i,setAgentMode:a}=U0(),o=(0,Z.useRef)(i),s=(0,Z.useRef)(i),c=(0,Z.useRef)(null),{notifyActionRequired:l,notifyTaskComplete:u}=HHe(),{startUpload:d,startDownload:f,stopActivity:p}=i3(),{authManager:m,setAuthExpired:h,onAuthExpired:g}=s3(),_=wZ(),{connection:v,pushServer:y}=n3(),b=(0,Z.useRef)(v),x=(0,Z.useRef)(y);(0,Z.useEffect)(()=>{b.current=v},[v]),(0,Z.useEffect)(()=>{x.current=y},[y]);let[S,C]=(0,Z.useState)(Sd.Idle),[w,T]=(0,Z.useReducer)(WHe,[]),E=(0,Z.useRef)(new Map),[D,k]=(0,Z.useState)(null),[A,j]=(0,Z.useState)(null),M=(0,Z.useRef)(null),N=(0,Z.useRef)([]),[P,ee]=(0,Z.useState)([]),[F,te]=(0,Z.useState)(null),[I,L]=(0,Z.useState)(null),[R,z]=(0,Z.useState)(!0),[ne,re]=(0,Z.useState)(!0),[ie,ae]=(0,Z.useState)(0),[oe,se]=(0,Z.useState)(null),[ce,le]=(0,Z.useState)(null),[ue,de]=(0,Z.useState)(null),[fe,B]=(0,Z.useState)(null),pe=(0,Z.useRef)(0),me=(0,Z.useRef)(!0),he=(0,Z.useRef)(null),ge=(0,Z.useRef)(Sd.Idle),_e=(0,Z.useCallback)(e=>{ge.current=e,C(e)},[]);(0,Z.useEffect)(()=>()=>{he.current&&clearTimeout(he.current),c.current&&clearTimeout(c.current)},[]);let[ve,ye]=(0,Z.useState)(null),be=sF(process.cwd()),V=(0,Z.useCallback)(e=>{M.current=e,j(e)},[]),xe=(0,Z.useCallback)(()=>{let e=N.current.shift();if(!e){V(null);return}e.request=Ce.current?.refreshPermissionRequest(e.request)??e.request;let t=!1;(e.editorDiffFilePath||e.editorToolViewShown)&&x.current&&x.current.waitForDecision(e.request.tool.id).then(n=>{t||(t=!0,_e(n===`accept`||n===`allowAlways`||n===`allowYolo`?Sd.ExecutingTool:Sd.Submitted),e.resolve(n),xe())}).catch(()=>{}),V({request:e.request,resolve:n=>{t||(t=!0,_e(n===`accept`||n===`allowAlways`||n===`allowYolo`||typeof n==`object`&&n.type===`accept_with_message`||typeof n==`object`&&n.type===`question_answers`?Sd.ExecutingTool:Sd.Submitted),setTimeout(()=>{e.resolve(n),xe()},0).unref())}}),_e(Sd.WaitingForToolPermission),l(`Abacus.AI is waiting for your input`)},[l,_e,V]),Se=(0,Z.useMemo)(()=>new mq(async e=>{let t=b.current,n=e,r=null;if(t&&x.current&&e.type===`edit_file`){let i=e.tool.id,a=E.current.get(i),o=(e.tool.input??{}).filePath??e.filePath??``,s=a?.originalContent??e.originalContent??``,c=a?.newContent??e.newContent??``;o&&(s||c)&&await t.showDiff({filePath:o,originalContent:s,modifiedContent:c,toolId:i})&&(n={...e,diffShownInEditor:!0},r=o)}if(t&&x.current&&e.type===`write_file`&&!e.isNewFile){let i=e.tool.id,a=e.filePath??``,o=e.originalContent??``,s=e.content??``;a&&(o||s)&&await t.showDiff({filePath:a,originalContent:o,modifiedContent:s,toolId:i})&&(n={...e,diffShownInEditor:!0},r=a)}let i=!1;t&&e.type===`exit_plan_mode`&&e.planFilePath&&(x.current&&await t.showToolView({filePath:e.planFilePath,toolKey:e.tool.id}).catch(()=>!1)&&(i=!0),i||await t.openPlanFile(e.planFilePath).catch(()=>{}));let a=await new Promise(e=>{let t={request:n,editorDiffFilePath:r,editorToolViewShown:i,resolve:e},a=N.current.length===0&&!M.current;N.current.push(t),a&&xe()});if(r&&t){let e=a===`reject`||typeof a==`object`&&a.type===`reject_with_message`;t.notifyDiffDecision({targetFile:r,decision:e?`reject`:`accept`}).catch(()=>{})}return a}),[xe]),Ce=(0,Z.useRef)(null);function we(){return new pq({allowedDirectories:[be,...r?.[`add-dir`]?.map(e=>{let t=aF(e);return sF(O.isAbsolute(t)?t:O.resolve(be,t))})??[]],primaryWorkspace:be,apiClient:t,mode:s.current,permissionProvider:Se,config:n,diagnosticsProvider:{getDiagnostics:async e=>{let t=b.current;return t?t.getDiagnostics(e):[]}},onMcpAuthRequired:void 0,cliAllowedTools:r?.[`allowed-tools`],cliDisallowedTools:r?.[`disallowed-tools`],clientType:tt.CLI})}Ce.current||=(s.current=o.current,we());let Te=Ce.current,Ee=(0,Z.useCallback)(()=>{ee(Te.getQueueEntries().map(e=>({...e})))},[Te]),De=(0,Z.useCallback)(e=>{s.current=e,Te.setMode(e),N.current=N.current.filter(t=>Ed(t.request.type,e)?(t.resolve(`accept`),!1):!0);let t=M.current;t&&Ed(t.request.type,e)&&t.resolve(`accept`)},[Te]);(0,Z.useEffect)(()=>(o.current=i,c.current&&clearTimeout(c.current),c.current=setTimeout(()=>{De(i),c.current=null},500),c.current.unref(),()=>{c.current&&=(clearTimeout(c.current),null)}),[i,De]),(0,Z.useEffect)(()=>{(async()=>{let e=!0;if(r?.conversationId)try{await Pe(r.conversationId)}catch{e=!1}e&&r?.prompt&&await Ie({message:r.prompt})})()},[]),(0,Z.useEffect)(()=>{let e=!1,t=0,n=1e3,r=()=>{if(e)return;t+=n;let i=Te.mcp.listServers(),a=i.filter(e=>e.status===`auth-required`);if(a.length>0){let e=a.map(e=>e.config.name??e.config.id).join(`, `);Oe(`${a.length} MCP server(s) require auth (${e}). Use /mcp auth <name> to authenticate.`,`warning`,!0);return}t<1e4&&i.some(e=>e.status!==`connected`&&e.status!==`error`)&&setTimeout(r,n)},i=setTimeout(r,n);return()=>{e=!0,clearTimeout(i)}},[]),(0,Z.useEffect)(()=>{switch(S){case Sd.Submitted:case Sd.Streaming:_.showProgress({state:`indeterminate`});break;case Sd.ExecutingTool:_.showProgress({state:`indeterminate`});break;case Sd.WaitingForToolPermission:_.hideProgress();break;case Sd.Idle:_.hideProgress();break}},[S,_]);let Oe=(0,Z.useCallback)((e,t=`info`,n=!1)=>{T({type:`ADD_NOTIFICATION`,seg:{id:crypto.randomUUID(),status:`completed`,source:`bot`,type:`code_llm_notification`,severity:t,message:e,temp:n}})},[]),ke=(0,Z.useCallback)(()=>{T({type:`CLEAR`}),k(null),_e(Sd.Idle),ye(null),B(null),E.current.clear(),c.current&&=(clearTimeout(c.current),null),s.current=o.current,Ce.current=we()},[t,be,Se]),Ae=(0,Z.useCallback)(()=>{T({type:`CLEAR`})},[]),je=(0,Z.useCallback)(()=>{T({type:`REMOVE_TEMP`})},[]),Me=(0,Z.useCallback)(()=>{let e=Te.dq();Ee(),e.length>0&&te(e.map(e=>e.message).join(`
75247
- `)),Te.stop();let t=M.current;t&&t.resolve(`reject`);for(let e of N.current)e.resolve(`reject`);N.current.length=0,V(null),_e(Sd.Idle)},[Te,Ee,_e,V]),Ne=(0,Z.useCallback)(()=>{A&&A.resolve(`reject`)},[A]),Pe=(0,Z.useCallback)(async e=>{_e(Sd.LoadingConversation),T({type:`CLEAR`}),k(null),ye(e);try{let t=await Te.loadConversation(e);return t.title&&k(t.title),t.segments.length>0&&T({type:`LOAD`,segments:t.segments.map(e=>GHe(e))}),t.llmName&&B(t.llmName),{llmName:t.llmName}}catch{return Oe(`Failed to load conversation`,`error`),{}}finally{_e(Sd.Idle)}},[Te,Oe,_e]),Fe=(0,Z.useCallback)(async(e,t)=>{await Te.mcp.refresh(),t&&Oe(`MCP tools refreshed`,`info`,!0)},[Te,Oe]),Ie=(0,Z.useCallback)(async({message:e,selectedModel:t,fileAttachments:n,activeSkills:r})=>{if(!e||S===Sd.LoadingConversation)return;t&&Te.setModel(t);let i=e;if(n&&n.length>0){let e=n.filter(e=>!e.mimeType.startsWith(`image/`));for(let t of e){let e=typeof t.content==`string`?t.content:t.content.toString(`utf-8`);i+=`\n\n<file path="${t.filePath}">\n${e}\n</file>`}}let o=crypto.randomUUID();T({type:`INIT_SEND`,userSeg:{id:o,status:`completed`,source:`user`,type:`text`,segment:e},spinnySeg:{id:crypto.randomUUID(),status:`transient`,source:`bot`,type:`collapsible_component`,title:`Processing request`,temp:!0,isSpinny:!0}}),_e(Sd.Submitted),d();let s=null,c=null,l=[],_=new Set,v,y=b.current,x=y?.getCurrentFile(),C=y?.getSelectionRange();if(y&&x)try{let e=(await y.getDiagnostics([x])).filter(e=>e.severity===`error`||e.severity===`warning`);e.length>0&&(v=e.map(e=>`${e.file}:${e.line}:${e.column} [${e.severity}] ${e.message}`).join(`
75247
+ `)),Te.stop();let t=M.current;t&&t.resolve(`reject`);for(let e of N.current)e.resolve(`reject`);N.current.length=0,V(null),_e(Sd.Idle)},[Te,Ee,_e,V]),Ne=(0,Z.useCallback)(()=>{A&&A.resolve(`reject`)},[A]),Pe=(0,Z.useCallback)(async e=>{_e(Sd.LoadingConversation),T({type:`CLEAR`}),k(null),ye(e);try{let t=await Te.loadConversation(e);return t.title&&k(t.title),t.segments.length>0&&T({type:`LOAD`,segments:t.segments.map(e=>GHe(e))}),B(t.llmName??null),t.llmName&&Te.setModel(t.llmName),{llmName:t.llmName}}catch{return B(null),Oe(`Failed to load conversation`,`error`),{}}finally{_e(Sd.Idle)}},[Te,Oe,_e]),Fe=(0,Z.useCallback)(async(e,t)=>{await Te.mcp.refresh(),t&&Oe(`MCP tools refreshed`,`info`,!0)},[Te,Oe]),Ie=(0,Z.useCallback)(async({message:e,selectedModel:t,fileAttachments:n,activeSkills:r})=>{if(!e||S===Sd.LoadingConversation)return;t&&Te.setModel(t);let i=e;if(n&&n.length>0){let e=n.filter(e=>!e.mimeType.startsWith(`image/`));for(let t of e){let e=typeof t.content==`string`?t.content:t.content.toString(`utf-8`);i+=`\n\n<file path="${t.filePath}">\n${e}\n</file>`}}let o=crypto.randomUUID();T({type:`INIT_SEND`,userSeg:{id:o,status:`completed`,source:`user`,type:`text`,segment:e},spinnySeg:{id:crypto.randomUUID(),status:`transient`,source:`bot`,type:`collapsible_component`,title:`Processing request`,temp:!0,isSpinny:!0}}),_e(Sd.Submitted),d();let s=null,c=null,l=[],_=new Set,v,y=b.current,x=y?.getCurrentFile(),C=y?.getSelectionRange();if(y&&x)try{let e=(await y.getDiagnostics([x])).filter(e=>e.severity===`error`||e.severity===`warning`);e.length>0&&(v=e.map(e=>`${e.file}:${e.line}:${e.column} [${e.severity}] ${e.message}`).join(`
75248
75248
  `))}catch{}try{for await(let e of Te.send(i,{diagnosticIssues:v,currentFile:x??void 0,selectionStartLine:C?.startLine,selectionEndLine:C?.endLine,activeSkills:r})){let t=()=>{c&&=(T({type:`THINKING_COMPLETE`,segId:c,endTime:Date.now()}),null)};switch(e.type){case`text_delta`:{_e(Sd.Streaming),p(),f(),t();let n=e.content;s||=crypto.randomUUID(),T({type:`TEXT_DELTA`,segId:s,content:n});break}case`thinking_delta`:{let t=e.content;c||=crypto.randomUUID(),T({type:`THINKING_DELTA`,segId:c,content:t,startTime:Date.now()});break}case`thinking_complete`:t();break;case`tool_display_data`:{let{toolCallId:t,data:n}=e,r=E.current.get(t)??{};E.current.set(t,{...r,...n}),T({type:`TOOL_DISPLAY_DATA`,toolCallId:t,data:n});break}case`tool_call_start`:t(),_.add(e.toolCallId),T({type:`TOOL_CALL_START`,toolCallId:e.toolCallId,toolName:e.toolName,textSegId:s}),s=null;break;case`tool_call_delta`:T({type:`TOOL_CALL_DELTA`,toolCallId:e.toolCallId,argumentsDelta:e.argumentsDelta});break;case`tool_call_stop`:T({type:`TOOL_CALL_STOP`,toolCallId:e.toolCallId,toolName:e.toolName,arguments:e.arguments});break;case`tool_requested`:{ge.current!==Sd.WaitingForToolPermission&&_e(Sd.ExecutingTool),p(),d(),t();let n=e.tool.id;if(l.push(n),_.has(n)){T({type:`TOOL_CALL_STOP`,toolCallId:n,toolName:e.tool.name,arguments:JSON.stringify(e.tool.input??{})}),s=null;break}let r={id:n,status:`transient`,source:`bot`,type:`code_llm_tool_call`,toolUseRequest:{id:n,name:e.tool.name,input:e.tool.input},toolDisplayData:E.current.get(n)};T({type:`TOOL_REQUESTED`,toolCallId:n,textSegId:s,toolSeg:r}),s=null;break}case`tool_execution_complete`:{p(),f();let t=e.tool.id,{parsedResult:n,...r}=e.result,i={id:crypto.randomUUID(),status:`transient`,source:`bot`,type:`collapsible_component`,title:`Analyzing result`,temp:!0,isSpinny:!0};T({type:`TOOL_EXECUTION_COMPLETE`,toolCallId:t,rawResult:r,...n!==void 0&&{parsedResult:n},spinnySeg:i}),s=null;break}case`notification`:T({type:`ADD_NOTIFICATION`,seg:{id:crypto.randomUUID(),status:`completed`,source:`bot`,type:`code_llm_notification`,severity:e.severity,message:e.message,...e.actions!==void 0&&{actions:e.actions}}});break;case`error`:T({type:`ERROR`,errorSeg:{id:crypto.randomUUID(),status:`completed`,source:`bot`,type:`code_llm_notification`,severity:`error`,message:e.error.message}});break;case`mode_changed`:a(e.mode);break;case`tool_user_message`:T({type:`TOOL_USER_MESSAGE`,seg:{id:crypto.randomUUID(),status:`completed`,source:`user`,type:`text`,segment:e.message}});break;case`retry`:L({attempt:e.attempt,maxAttempts:e.maxAttempts,delayMs:e.delayMs,isNetworkError:e.isNetworkError});break;case`network_status`:e.online?(he.current&&=(clearTimeout(he.current),null),me.current=!0,z(!0),re(!0),L(null),setTimeout(()=>{if(ge.current===Sd.Idle&&Te.getQueueEntries().length>0){let e=Te.dq();if(e.length>0){Ee();let t=e.map(e=>e.message).join(`
75249
75249
  `),n=sq.matchSkill(t.trim());Ie(n?{message:t,activeSkills:[n.skill.id]}:{message:t})}}},0).unref?.()):(me.current=!1,z(!1),he.current||=setTimeout(()=>{he.current=null,me.current||re(!1)},3e4));break;case`user_message_dequeued`:T({type:`INIT_SEND`,userSeg:{id:crypto.randomUUID(),status:`completed`,source:`user`,type:`text`,segment:e.content},spinnySeg:{id:crypto.randomUUID(),status:`transient`,source:`bot`,type:`collapsible_component`,title:`Processing request`,temp:!0,isSpinny:!0}}),Ee(),s=null,c=null,l.length=0;break;case`credits`:pe.current+=e.creditsUsed,ae(t=>t+e.creditsUsed);break;case`session_info`:se(e.contextPercent),le(e.contextTokensUsed),de(e.contextWindowMax);break;case`turn_complete`:T({type:`TURN_COMPLETE`,textSegId:s,toolCallIds:[...l]}),s=null,l.length=0,Ee();break}}}catch(e){if(e instanceof Ll)m.isEnvAuth()||(h(!0),g?.()),T({type:`REMOVE_USER_SEG`,userSegId:o}),Oe(`Session expired — use /login to authenticate again.`,`error`,!0);else{let t=Vl(e)?`Unable to connect to API`:e instanceof Error?e.message:`An error occurred`;T({type:`REMOVE_USER_SEG`,userSegId:o}),Oe(t,`error`,!0)}te(i),Te.dq(),Ee()}finally{p(),L(null);let e=Te.getConversationId();e&&ye(e),T({type:`FINALIZE`,textSegId:s}),pe.current>0&&(T({type:`ADD_CREDITS`,seg:{id:`credits-${Date.now()}`,status:`completed`,source:`bot`,type:`code_llm_credits`,creditsUsed:pe.current}}),pe.current=0),_e(Sd.Idle),u(`Abacus.AI completed the task`)}},[Te,S,Oe,u,d,f,p,a,m,h]);(0,Z.useEffect)(()=>(Te.onAutoRestart=e=>{ge.current===Sd.Idle&&Ie({message:e})},()=>{Te.onAutoRestart=null}),[Te,Ie]);let Le=(0,Z.useCallback)((e,t)=>{let n=Te.nq(e,t);return Ee(),n},[Te,Ee]),Re=(0,Z.useCallback)(e=>{let t=Te.dq(e);return Ee(),t},[Te,Ee]),ze=(0,Z.useCallback)((e,t)=>{Te.remove(e,t),Ee()},[Te,Ee]),Be=(0,Z.useCallback)((e,t)=>{let n=Te.setContent(e,t);return Ee(),n},[Te,Ee]),Ve=(0,Z.useCallback)(e=>{Te.clearQueue(e),Ee()},[Te,Ee]),H=(0,Z.useCallback)(()=>{te(null)},[]),He=(0,Z.useCallback)(e=>Te.isDirectoryAllowed(e),[Te]),Ue=(0,Z.useCallback)((e,t)=>Te.addAllowedDirectory(e,t),[Te]),U=(0,Z.useCallback)(()=>Te.listTerminalSessions(),[Te]),We=(0,Z.useCallback)(e=>Te.getTerminalSessionOutput(e),[Te]),Ge=(0,Z.useCallback)(e=>Te.stopTerminalSession(e),[Te]),Ke=(0,Z.useMemo)(()=>({conversationId:ve,conversationTitle:D,segments:w,segmentsLength:w.length,sendMessage:Ie,stop:Me,rejectPendingPermission:Ne,agentStatus:S,clearSegments:ke,clearSegmentsOnly:Ae,clearTempSegments:je,loadConversation:Pe,addNotification:Oe,mcp:Te.mcp,isDirectoryAllowed:He,addAllowedDirectory:Ue,pendingToolPermission:A,refreshMcpTools:Fe,queuedMessages:P,nq:Le,dq:Re,removeFromQueue:ze,setQueuedMessageContent:Be,clearQueue:Ve,dequeuedOnStop:F,clearDequeuedOnStop:H,retryState:I,networkOnline:R,debouncedNetworkOnline:ne,listTerminalSessions:U,getTerminalSessionOutput:We,stopTerminalSession:Ge,totalCredits:ie,contextPercent:oe,contextTokensUsed:ce,contextWindowMax:ue,resolvedConversationLlmName:fe}),[ve,D,w,Ie,Me,Ne,S,ke,Ae,je,Pe,Oe,Te,He,Ue,A,Fe,P,Le,Re,ze,Be,Ve,F,H,I,R,ne,U,We,Ge,ie,oe,ce,ue,fe]);return(0,X.jsx)(l3.Provider,{value:Ke,children:e})});d3.displayName=`AgentProvider`;function f3(){let e=(0,Z.use)(l3);if(!e)throw Error(`Agent context not found. Did you forget to wrap your component in <${d3.name}>?`);return e}function p3(e){return e.split(`_`).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(``)}function KHe({toolName:e,status:t,parsedResult:n}){let{agentStatus:r}=f3(),i=p3(e);if(t===`interrupted`)return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(E0,{name:i,status:`interrupted`}),(0,X.jsx)(D0,{color:`yellow`,children:`Interrupted · What should I do instead?`})]});if(t===`rejected`)return n?.userNote?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(E0,{name:i,status:`rejected`}),(0,X.jsxs)(D0,{color:`yellow`,children:[`Rejected · `,(0,X.jsxs)($,{italic:!0,children:[`"`,n.userNote,`"`]})]})]}):(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(E0,{name:i,status:`rejected`}),(0,X.jsx)(D0,{color:`yellow`,children:`Rejected`})]});if(t===`error`)return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(E0,{name:i,status:`error`}),(0,X.jsx)(D0,{color:`red`,children:n?.errorMessage??n?.summary??`MCP tool execution failed`})]});let a=r===Sd.WaitingForToolPermission&&!n,o=!n&&(r===Sd.Streaming||r===Sd.ExecutingTool),s=n?.phase===`error`;return a?(0,X.jsxs)(Q,{flexDirection:`row`,gap:1,children:[(0,X.jsx)($,{color:`yellow`,children:`●`}),(0,X.jsx)($,{color:`cyan`,children:i})]}):o?(0,X.jsx)(E0,{name:i,status:`pending`,showSpinner:!0}):n?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(E0,{name:i,status:s?`error`:`success`}),(0,X.jsx)(D0,{color:s?`red`:`brightblack`,children:s?`Error: ${n.errorMessage??n.summary??`Tool execution failed`}`:n.summary??`Executed successfully`})]}):(0,X.jsx)(Q,{flexDirection:`column`,children:(0,X.jsx)(E0,{name:i,status:`pending`})})}function qHe(e){return{displayName:p3(e),getHeaderParams(e){return``},renderUI(t,n,r){return(0,X.jsx)(KHe,{toolName:e,rawInput:t,status:n,parsedResult:r})}}}function m3(e){let t=[];return e.pattern&&t.push(`pattern: "${e.pattern}"`),e.path&&t.push(`path: "${e.path}"`),t.length>0?t.join(`, `):`[no pattern]`}const JHe={displayName:`Search`,getHeaderParams(e){try{return m3(e)}catch{return`[unknown]`}},renderUI(e,t,n){let r=m3(e);return t===`error`?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(E0,{name:`Search`,params:r,status:`error`}),(0,X.jsx)(D0,{color:`red`,children:`Error matching files`})]}):t===`executing`?(0,X.jsx)(E0,{name:`Search`,params:r,status:`executing`,showSpinner:!0}):n?(0,X.jsx)(YHe,{searchParams:r,parsedResult:n}):(0,X.jsx)(Q,{flexDirection:`column`,children:(0,X.jsx)(E0,{name:`Search`,params:r,status:`pending`})})}};function YHe({searchParams:e,parsedResult:t}){let n=(0,Z.useContext)(K0),r=t.data.files??[],i=n?30:10,a=r.slice(0,i),o=r.length-a.length;return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(E0,{name:`Search`,params:e,status:`success`}),(0,X.jsx)(D0,{children:t.summary}),r.length>0&&(0,X.jsxs)(O0,{children:[a.map((e,t)=>(0,X.jsx)($,{dimColor:!0,children:e},t)),o>0&&(0,X.jsxs)($,{dimColor:!0,children:[`… +`,o,` more file`,o===1?``:`s`]})]})]})}function h3(e){let t=e,n=[];t.pattern&&n.push(`pattern: "${t.pattern}"`),t.path&&n.push(`path: "${t.path}"`);let r=t.outputMode||e.output_mode;return r&&n.push(`outputMode: "${r}"`),t.glob&&n.push(`glob: "${t.glob}"`),t[`-i`]&&n.push(`case-insensitive`),n.length>0?n.join(`, `):`[no pattern]`}const XHe={displayName:`Search`,getHeaderParams(e){try{return h3(e)}catch{return`[unknown]`}},renderUI(e,t,n){let r=h3(e);return t===`error`?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(E0,{name:`Search`,params:r,status:`error`}),(0,X.jsx)(D0,{color:`red`,children:`Error searching content`})]}):t===`executing`?(0,X.jsx)(E0,{name:`Search`,params:r,status:`executing`,showSpinner:!0}):n?(0,X.jsx)(ZHe,{searchParams:r,parsedResult:n}):(0,X.jsx)(Q,{flexDirection:`column`,children:(0,X.jsx)(E0,{name:`Search`,params:r,status:`pending`})})}};function ZHe({searchParams:e,parsedResult:t}){let n=(0,Z.useContext)(K0),r=t.data.matches??[],i=n?30:10,a=r.slice(0,i),o=r.length-a.length;return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(E0,{name:`Search`,params:e,status:`success`}),(0,X.jsx)(D0,{children:t.summary}),r.length>0&&(0,X.jsxs)(O0,{children:[a.map((e,t)=>(0,X.jsx)($,{dimColor:!0,children:e},t)),o>0&&(0,X.jsxs)($,{dimColor:!0,children:[`… +`,o,` more match`,o===1?``:`es`]})]})]})}const QHe=ZL({url:Y()}),$He={displayName:`Web Fetch`,getHeaderParams(e){try{let t=e?.url||``;return t.length>50?t.substring(0,47)+`...`:t}catch{return`[unknown]`}},renderUI(e,t,n){let r=QHe.safeParse(F0(e));if(!r.success)return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(E0,{name:`Fetch`,params:``,status:`error`}),(0,X.jsx)(D0,{color:`red`,children:`Invalid params`})]});let i=r.data.url||``,a=i.length>50?i.substring(0,47)+`...`:i;return t===`error`?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(E0,{name:`Fetch`,params:a,status:`error`}),(0,X.jsx)(D0,{color:`red`,children:`Error fetching URL`})]}):t===`executing`?(0,X.jsx)(E0,{name:`Fetch`,params:a,status:`executing`,showSpinner:!0}):n?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(E0,{name:`Fetch`,params:a,status:`success`}),(0,X.jsx)(D0,{children:n.summary??`Fetched content`})]}):(0,X.jsx)(Q,{flexDirection:`column`,children:(0,X.jsx)(E0,{name:`Fetch`,params:a,status:`pending`})})}},eUe=ZL({searchTerm:Y(),query:Y().optional(),explanation:Y().optional(),allowedDomains:YL(Y()).optional(),blockedDomains:YL(Y()).optional()}),tUe={displayName:`WebSearch`,getHeaderParams(e){try{return`"${e?.searchTerm||e?.search_term||e?.query||`[no query]`}"`}catch{return`[unknown]`}},renderUI(e,t,n){let r=eUe.safeParse(F0(e));if(!r.success)return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(E0,{name:`WebSearch`,params:``,status:`error`}),(0,X.jsx)(D0,{color:`red`,children:`Invalid params`})]});let i=r.data,a=i.searchTerm||i.query||``,o=`"${a.length>40?a.substring(0,37)+`...`:a}"`;return t===`error`?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(E0,{name:`WebSearch`,params:o,status:`error`}),(0,X.jsx)(D0,{color:`red`,children:`Error performing web search`})]}):t===`executing`?(0,X.jsx)(E0,{name:`WebSearch`,params:o,status:`executing`,showSpinner:!0}):(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(E0,{name:`WebSearch`,params:o,status:`success`}),(0,X.jsx)(D0,{children:`Found results`})]})}},nUe=ZL({shellId:Y(),filter:Y().optional()}),rUe={displayName:`BashOutput`,getHeaderParams(e){try{let t=e,n=[`id: ${t.shellId||``}`];return t.filter&&n.push(`filter: ${t.filter}`),n.join(`, `)}catch{return`[unknown]`}},renderUI(e,t,n){let r=nUe.safeParse(F0(e));if(!r.success)return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(E0,{name:`BashOutput`,params:``,status:`error`}),(0,X.jsx)(D0,{color:`red`,children:`Invalid params`})]});let i=`id: ${r.data.shellId}`;return t===`interrupted`?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(E0,{name:`BashOutput`,params:i,status:`interrupted`}),(0,X.jsx)(D0,{color:`yellow`,children:`Interrupted · What should I do instead?`})]}):t===`rejected`?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(E0,{name:`BashOutput`,params:i,status:`rejected`}),n?.userNote?(0,X.jsxs)(D0,{color:`yellow`,children:[`Rejected · `,(0,X.jsxs)($,{italic:!0,children:[`"`,n.userNote,`"`]})]}):(0,X.jsx)(D0,{color:`yellow`,children:`Rejected`})]}):!n&&(t===`executing`||t===`pending`)?(0,X.jsx)(E0,{name:`BashOutput`,params:i,status:`pending`,showSpinner:!0}):n?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(E0,{name:`BashOutput`,params:i,status:`success`}),(0,X.jsx)(D0,{children:n.summary})]}):(0,X.jsx)(Q,{flexDirection:`column`,children:(0,X.jsx)(E0,{name:`BashOutput`,params:i,status:`pending`})})}};var iUe=class{startTime;constructor(){this.startTime=performance.now()}getElapsedSeconds(){return(performance.now()-this.startTime)/1e3}getElapsedMs(){return performance.now()-this.startTime}getFormattedDuration(){return g3(this.getElapsedMs())}reset(){this.startTime=performance.now()}};function g3(e){let t=Math.floor(e/1e3),n=Math.floor(t/3600),r=Math.floor(t%3600/60),i=t%60,a=[];return n>0&&a.push(`${n}h`),r>0&&a.push(`${r}m`),(i>0||a.length===0)&&a.push(`${i}s`),a.join(` `)}function aUe(e,t,n){let r=n?50:t,i=e.split(`
75250
75250
  `).filter(Boolean);return i.length<=r?{lines:i,isTruncated:!1,hiddenCount:0}:{lines:i.slice(0,r),isTruncated:!0,hiddenCount:i.length-r}}function oUe(e){let[t]=(0,Z.useState)(Date.now()),[n,r]=(0,Z.useState)(0);return(0,Z.useEffect)(()=>{if(!e)return;let n=setInterval(()=>{r(Date.now()-t)},1e3);return()=>clearInterval(n)},[e,t]),n}function sUe({command:e,toolCallId:t,executionResult:n}){let{agentStatus:r}=f3(),i=(0,Z.useContext)(K0),[a,o]=(0,Z.useState)(!1),s=a||i,c=!n&&(r===Sd.Streaming||r===Sd.ExecutingTool),l=oUe(c),u=l>=5e3,d=(0,Z.useDeferredValue)(n?.output||``),{lines:f,isTruncated:p,hiddenCount:m}=(0,Z.useMemo)(()=>aUe(d,7,s),[d,s]),h=!i&&!c&&n!==void 0&&(p||a),{isFocused:g}=SZ({id:`bash-tool-${t}`,isActive:h});xZ((e,t)=>{g&&t.ctrl&&e===`o`&&o(e=>!e)},{isActive:g&&h});let _=e.length>500?e.slice(0,500)+`…`:e,v=n?.exitCode??0,y=n?.status===`error`||v!==0,b=c?`pending`:y?`error`:`success`;if(c){let e=u?g3(l):null;return(0,X.jsxs)(Q,{flexDirection:`column`,gap:0,children:[(0,X.jsx)(E0,{name:`Bash`,params:_,paramsLanguage:`bash`,status:b,showSpinner:!0}),(0,X.jsxs)(D0,{color:`brightblack`,children:[`Running…`,e?` ${e}`:null]})]})}if(n){let e=f.length>0,t=`exit ${v} (${lBe(n.duration??0)})`;return(0,X.jsxs)(Q,{flexDirection:`column`,gap:0,children:[(0,X.jsx)(E0,{name:`Bash`,params:_,paramsLanguage:`bash`,status:b}),(0,X.jsx)(O0,{children:e?(0,X.jsxs)(X.Fragment,{children:[y&&(0,X.jsx)($,{color:`red`,dimColor:!0,children:`Error:`}),f.map((e,t)=>(0,X.jsx)($,{color:y?`red`:void 0,dimColor:!0,children:e},t)),p&&(0,X.jsxs)($,{dimColor:!0,children:[`… +`,m,` `,s?`more `:``,`line`,m===1?``:`s`,s?``:` (ctrl+o to expand)`]})]}):(0,X.jsx)($,{dimColor:!0,children:`(no content)`})}),(0,X.jsx)(D0,{color:y?`red`:`brightblack`,children:t})]})}return(0,X.jsx)(Q,{flexDirection:`column`,children:(0,X.jsx)(E0,{name:`Bash`,params:_,paramsLanguage:`bash`,status:`pending`})})}const cUe=ZL({command:Y(),explanation:Y().optional(),runInBackground:B0,shellId:Y().optional(),interactiveMode:B0,timeout:vR().optional()});function lUe({rawInput:e,status:t,parsedResult:n}){let r=cUe.safeParse(F0(e));if(!r.success)return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(E0,{name:`Bash`,params:``,paramsLanguage:`bash`,status:`error`}),(0,X.jsx)(D0,{color:`red`,children:`Invalid params`})]});let i=r.data,a=i.command||``,o=a.length>500?a.slice(0,500)+`…`:a,s=i.timeout?` (timeout: ${(i.timeout/1e3).toFixed(0)}s)`:``;if(t===`interrupted`)return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(E0,{name:`Bash`,params:o,paramsLanguage:`bash`,status:`interrupted`}),(0,X.jsx)(D0,{color:`yellow`,children:`Interrupted · What should I do instead?`})]});if(t===`rejected`)return n?.userNote?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(E0,{name:`Bash`,params:o,paramsLanguage:`bash`,status:`rejected`}),(0,X.jsxs)(D0,{color:`yellow`,children:[`Rejected · `,(0,X.jsxs)($,{italic:!0,children:[`"`,n.userNote,`"`]})]})]}):(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(E0,{name:`Bash`,params:o,paramsLanguage:`bash`,status:`rejected`}),(0,X.jsx)(D0,{color:`yellow`,children:`Rejected`})]});if(n?.data?.timedOut)return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(E0,{name:`Bash`,params:`${o}${s}`,paramsLanguage:`bash`,status:`success`}),(0,X.jsx)(D0,{children:`Running in the background`})]});if(n?.runInBackground)return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(E0,{name:`Bash`,params:`${o}${s}`,paramsLanguage:`bash`,status:`success`}),(0,X.jsx)(D0,{children:n.summary})]});let c=e?.id||`unknown`,l=n?.data;return(0,X.jsx)(sUe,{command:`${o}${s}`,toolCallId:c,executionResult:l})}const uUe={displayName:`Bash`,getHeaderParams(e){try{return e?.command||`[no command]`}catch{return`[unknown]`}},renderUI(e,t,n){return(0,X.jsx)(lUe,{rawInput:e,status:t,parsedResult:n})}},dUe=ZL({shellId:Y()}),_3={read:_Ve,delete:JBe,write:xVe,edit:nVe,notebook_edit:oVe,grep:XHe,glob:JHe,web_search:tUe,web_fetch:$He,bash:uUe,bash_output:rUe,kill_shell:{displayName:`KillShell`,getHeaderParams(e){try{return`id: ${e.shellId||``}`}catch{return`[unknown]`}},renderUI(e,t,n){let r=dUe.safeParse(F0(e));if(!r.success)return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(E0,{name:`KillShell`,params:``,status:`error`}),(0,X.jsx)(D0,{color:`red`,children:`Invalid params`})]});let i=`id: ${r.data.shellId}`;return t===`interrupted`?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(E0,{name:`KillShell`,params:i,status:`interrupted`}),(0,X.jsx)(D0,{color:`yellow`,children:`Interrupted · What should I do instead?`})]}):t===`rejected`?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(E0,{name:`KillShell`,params:i,status:`rejected`}),n?.userNote?(0,X.jsxs)(D0,{color:`yellow`,children:[`Rejected · `,(0,X.jsxs)($,{italic:!0,children:[`"`,n.userNote,`"`]})]}):(0,X.jsx)(D0,{color:`yellow`,children:`Rejected`})]}):!n&&(t===`executing`||t===`pending`)?(0,X.jsx)(E0,{name:`KillShell`,params:i,status:`pending`,showSpinner:!0}):n?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(E0,{name:`KillShell`,params:i,status:`success`}),(0,X.jsx)(D0,{children:n.summary})]}):(0,X.jsx)(Q,{flexDirection:`column`,children:(0,X.jsx)(E0,{name:`KillShell`,params:i,status:`pending`})})}},navigate_to:BBe,new_tab:HBe,close_tab:MBe,switch_active_tab:qBe,refresh_tab:GBe,get_tab_content:RBe,computer:PBe,get_interactive_elements:IBe,perform_interactive_element_action:WBe,ask_user_question:vBe,enter_plan_mode:yBe,exit_plan_mode:CBe,subagent:TBe,task:DBe,todo_write:ABe,get_diagnostics:CVe};function fUe(e,t){_3[e]=t??qHe(e)}function pUe(e){let t=e.toolUseRequest;return t?(Array.isArray(t)?t:[t]).map(e=>{let t=e;return{name:t.name??``,input:t.input??{}}}).filter(e=>e.name):[]}function mUe(e,t=4){let n=[];for(let r of e){if(n.length>=t)break;for(let e of pUe(r)){if(n.length>=t)break;let r=_3[e.name];if(!r)continue;let i=``;try{i=r.getHeaderParams(e.input)}catch{}if(!i)continue;let a=r.displayName??e.name;n.push({label:a,detail:i})}}return n}const v3=(0,Z.memo)(({counts:e,segments:t})=>{let n=(0,Z.useMemo)(()=>{let t=[];return e.toolUses>0&&t.push(`${e.toolUses} tool ${e.toolUses===1?`use`:`uses`}`),e.responses>0&&t.push(`${e.responses} ${e.responses===1?`response`:`responses`}`),t.length===0?`Conversation compacted`:t.join(`, `)+` compacted`},[e]),r=(0,Z.useMemo)(()=>mUe(t),[t]);return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsxs)(Q,{flexDirection:`row`,gap:1,children:[(0,X.jsx)($,{color:ZQ,children:`⟐`}),(0,X.jsx)($,{color:ZQ,dimColor:!0,children:n}),(0,X.jsx)($,{color:ZQ,dimColor:!0,children:`(ctrl+o to expand)`})]}),r.map((e,t)=>(0,X.jsx)(Q,{flexDirection:`row`,paddingLeft:2,children:(0,X.jsxs)($,{color:ZQ,dimColor:!0,children:[`⎿ `,e.label,` `,e.detail]})},t))]})});v3.displayName=`CompactedPlaceholder`;const y3=(0,Z.createContext)(null);function hUe(){let e=(0,Z.use)(y3);if(!e)throw Error(`useUpdate must be used within UpdateProvider`);return e}function gUe({children:e,configService:t}){let[n,r]=(0,Z.useState)(null),{autoUpdate:i,updateChannel:a,baseUrl:o}=(0,Z.useMemo)(()=>({autoUpdate:t.get(`autoUpdate`)!==!1,updateChannel:t.get(`updateChannel`),baseUrl:t.get(`baseUrl`)}),[t]);(0,Z.useEffect)(()=>{if(LZ())return;let e=!0,t=()=>{RZ(OZ.default.version,a,o).then(t=>{e&&r(e=>e?.latestVersion===t?.latestVersion?e:t)}).catch(()=>{})};t();let n=setInterval(t,6e4);return()=>{e=!1,clearInterval(n)}},[a,o]);let s=(0,Z.useMemo)(()=>({updateInfo:n,autoUpdate:i}),[n,i]);return(0,X.jsx)(y3.Provider,{value:s,children:e})}const b3=(0,Z.createContext)(null),x3=()=>{let e=(0,Z.use)(b3);if(!e)throw Error(`${x3.name} must be used within a ${S3.name}`);return e};function S3({children:e}){let[t,n]=(0,Z.useState)({columns:process.stdout.columns-8,rows:process.stdout.rows}),r=(0,Z.useCallback)(()=>{n({columns:process.stdout.columns-8,rows:process.stdout.rows})},[]);(0,Z.useLayoutEffect)(()=>(process.stdout.on(`resize`,r),()=>{process.stdout.off(`resize`,r)}),[r]);let i=(0,Z.useMemo)(()=>({width:t.columns,height:t.rows}),[t.columns,t.rows]);return(0,X.jsx)(b3.Provider,{value:i,children:e})}function _Ue(){let{height:e}=x3();return Math.max(0,e-3)}let C3=function(e){return e.Models=`models`,e.UserInfo=`userInfo`,e.CreateConversation=`create-conversation`,e.GetConversation=`get-conversation`,e.Grep=`grep`,e.ReadFile=`read-file`,e.EditFile=`edit-file`,e.Bash=`bash`,e.BashOutput=`bash-output`,e.MCPTool=`mcp-tool`,e.PrInfo=`pr-info`,e}({});function vUe(e){return JQ({queryKey:[C3.Models],queryFn:async()=>{try{return(await e.listLLMModels())?.result??[]}catch{return[]}},initialData:[],staleTime:300*1e3,retry:1,refetchOnMount:`always`,refetchOnWindowFocus:!1})}function w3(e){return typeof e==`string`?e:typeof e==`object`&&e&&`segment`in e?e.segment:null}function yUe(){return process.platform===`win32`}async function bUe(e){return new Promise(t=>setTimeout(t,e))}function xUe({onlyFirst:e=!1}={}){return RegExp(`(?:\\u001B\\][\\s\\S]*?(?:\\u0007|\\u001B\\u005C|\\u009C))|[\\u001B\\u009B][[\\]()#;?]*(?:\\d{1,4}(?:[;:]\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]`,e?void 0:`g`)}const SUe=xUe();function T3(e){if(typeof e!=`string`)throw TypeError(`Expected a \`string\`, got \`${typeof e}\``);return!e.includes(`\x1B`)&&!e.includes(`›`)?e:e.replace(SUe,``)}const CUe=new Intl.Segmenter,wUe=RegExp(`^(?:\\p{Default_Ignorable_Code_Point}|\\p{Control}|\\p{Format}|\\p{Mark}|\\p{Surrogate})+$`,`v`),TUe=RegExp(`^[\\p{Default_Ignorable_Code_Point}\\p{Control}\\p{Format}\\p{Mark}\\p{Surrogate}]+`,`v`),EUe=RegExp(`^\\p{RGI_Emoji}$`,`v`),DUe=/^[\d#*]\u20E3$/,OUe=/\p{Extended_Pictographic}/gu;function kUe(e){if(e.length>50)return!1;if(DUe.test(e))return!0;if(e.includes(`‍`)){let t=e.match(OUe);return t!==null&&t.length>=2}return!1}function AUe(e){return e.replace(TUe,``)}function jUe(e){return wUe.test(e)}function MUe(e,t){let n=0;if(e.length>1)for(let r of e.slice(1))r>=`＀`&&r<=`￯`&&(n+=WJ(r.codePointAt(0),t));return n}function NUe(e,t={}){if(typeof e!=`string`||e.length===0)return 0;let{ambiguousIsNarrow:n=!0,countAnsiEscapeCodes:r=!1}=t,i=e;if(!r&&(i.includes(`\x1B`)||i.includes(`›`))&&(i=T3(i)),i.length===0)return 0;if(/^[\u0020-\u007E]*$/.test(i))return i.length;let a=0,o={ambiguousAsWide:!n};for(let{segment:e}of CUe.segment(i)){if(jUe(e))continue;if(EUe.test(e)||kUe(e)){a+=2;continue}let t=AUe(e).codePointAt(0);a+=WJ(t,o),a+=MUe(e,o)}return a}const PUe=[RegExp(`\x1B\\[2J`,`g`),RegExp(`\x1B\\[H`,`g`),RegExp(`\x1B\\[\\d+(;\\d+)?H`,`g`),RegExp(`\x1Bc`,`g`),RegExp(`\x1B\\[!p`,`g`),RegExp(`\x1B\\[\\?1049[hl]`,`g`),RegExp(`\x1B\\[\\d*[ABCD]`,`g`),RegExp(`\x1B\\[s`,`g`),RegExp(`\x1B\\[u`,`g`),RegExp(`\x1B\\[\\d*J`,`g`),RegExp(`\x1B\\[\\d*K`,`g`),RegExp(`\x1B\\[\\?25[hl]`,`g`),RegExp(`\x07`,`g`)];function FUe(e){let t=e;for(let e of PUe)t=t.replace(e,``);return t}const E3=new Map,D3=1e3;function O3(e){let t=!0;for(let n=0;n<e.length;n++)if(e.charCodeAt(n)>127){t=!1;break}if(t)return e.split(``);if(e.length<=D3){let t=E3.get(e);if(t)return t}let n=Array.from(e);return e.length<=D3&&E3.set(e,n),n}function k3(e){return O3(e).length}function A3(e,t,n){return O3(e).slice(t,n).join(``)}function j3(e){return O3(o(HMe(e))).filter(e=>{let t=e.codePointAt(0);return t===void 0?!1:t===10||t===13||t===9?!0:!(t>=0&&t<=31||t>=128&&t<=159)}).join(``)}const M3=new Map,N3=e=>{if(/^[\u0020-\u007E]*$/.test(e))return e.length;if(M3.has(e))return M3.get(e);let t=NUe(e);return M3.set(e,t),t};VMe();function IUe(e,t){if(!L3(e[t]))return!1;let n=t+1;for(;n<e.length&&z3(e[n]);)n++;return n>=e.length||!L3(e[n])}function LUe(e,t){let{lines:n,cursorRow:r,cursorCol:i}=e;switch(t.type){case`vim_delete_word_forward`:case`vim_change_word_forward`:{let{count:a}=t.payload,o=r,s=i;for(let e=0;e<a;e++){let e=K3(n,o,s,!0);if(e)o=e.row,s=e.col;else{let e=n[o]||``,t=G3(e,s);s=t===null?k3(e):t+1;break}}return o!==r||s!==i?X3(t6(e),r,i,o,s,``):e}case`vim_delete_word_backward`:case`vim_change_word_backward`:{let{count:a}=t.payload,o=r,s=i;for(let e=0;e<a;e++){let e=q3(n,o,s);if(e)o=e.row,s=e.col;else break}return o!==r||s!==i?X3(t6(e),o,s,r,i,``):e}case`vim_delete_word_end`:case`vim_change_word_end`:{let{count:a}=t.payload,o=r,s=i,c=r,l=i;for(let e=0;e<a;e++){let t=K3(n,o,s,!1);if(t){if(c=t.row,l=t.col+1,e<a-1){let e=K3(n,t.row,t.col+1,!0);if(e)o=e.row,s=e.col;else break}}else break}if(c<n.length){let e=k3(n[c]||``);l=Math.min(l,e)}return c!==r||l!==i?X3(t6(e),r,i,c,l,``):e}case`vim_delete_line`:{let{count:i}=t.payload;if(n.length===0)return e;let a=Math.min(i,n.length-r),o=n.length;if(o===1||a>=o)return{...t6(e),lines:[``],cursorRow:0,cursorCol:0,preferredCol:null};let s=t6(e),c=[...s.lines];c.splice(r,a);let l=Math.min(r,c.length-1);return{...s,lines:c,cursorRow:l,cursorCol:0,preferredCol:null}}case`vim_change_line`:{let{count:i}=t.payload;if(n.length===0)return e;let a=Math.min(i,n.length-r),o=t6(e),{startOffset:s,endOffset:c}=Y3(r,a,o.lines),{startRow:l,startCol:u,endRow:d,endCol:f}=J3(s,c,o.lines);return X3(o,l,u,d,f,``)}case`vim_delete_to_end_of_line`:case`vim_change_to_end_of_line`:{let t=n[r]||``;return i<k3(t)?X3(t6(e),r,i,r,k3(t),``):e}case`vim_change_movement`:{let{movement:a,count:o}=t.payload,s=n.length;switch(a){case`h`:{let t=Math.max(0,i-o);return X3(t6(e),r,t,r,i,``)}case`j`:{let t=Math.min(o,s-r);if(t>0)if(s===1){let t=e.lines[0]||``;return X3(t6(e),0,0,0,k3(t),``)}else{let n=t6(e),{startOffset:i,endOffset:a}=Y3(r,t,n.lines),{startRow:o,startCol:s,endRow:c,endCol:l}=J3(i,a,n.lines);return X3(n,o,s,c,l,``)}return e}case`k`:if(Math.min(o,r+1)>0)if(e.lines.length===1){let t=e.lines[0]||``;return X3(t6(e),0,0,0,k3(t),``)}else{let t=Math.max(0,r-o+1),n=r-t+1,i=t6(e),{startOffset:a,endOffset:s}=Y3(t,n,i.lines),{startRow:c,startCol:l,endRow:u,endCol:d}=J3(a,s,i.lines);return{...X3(i,c,l,u,d,``),cursorRow:t,cursorCol:0}}return e;case`l`:return X3(t6(e),r,i,r,Math.min(k3(n[r]||``),i+o),``);default:return e}}case`vim_move_left`:{let{count:n}=t.payload,{cursorRow:r,cursorCol:i,lines:a}=e,o=r,s=i;for(let e=0;e<n;e++)if(s>0)s--;else if(o>0){o--;let e=k3(a[o]||``);s=e===0?0:e-1}return{...e,cursorRow:o,cursorCol:s,preferredCol:null}}case`vim_move_right`:{let{count:n}=t.payload,{cursorRow:r,cursorCol:i,lines:a}=e,o=r,s=i;for(let e=0;e<n;e++){let e=a[o]||``,t=k3(e);if(t===0)o<a.length-1&&(o++,s=0);else if(s<t-1){s++;let n=O3(e);for(;s<n.length&&z3(n[s])&&s<t-1;)s++}else o<a.length-1&&(o++,s=0)}return{...e,cursorRow:o,cursorCol:s,preferredCol:null}}case`vim_move_up`:{let{count:n}=t.payload,{cursorRow:r,cursorCol:i,lines:a}=e,o=Math.max(0,r-n),s=k3(a[o]||``),c=Math.min(i,s>0?s-1:0);return{...e,cursorRow:o,cursorCol:c,preferredCol:null}}case`vim_move_down`:{let{count:n}=t.payload,{cursorRow:r,cursorCol:i,lines:a}=e,o=Math.min(a.length-1,r+n),s=k3(a[o]||``),c=Math.min(i,s>0?s-1:0);return{...e,cursorRow:o,cursorCol:c,preferredCol:null}}case`vim_move_word_forward`:{let{count:a}=t.payload,o=r,s=i;for(let e=0;e<a;e++){let e=K3(n,o,s,!0);if(e)o=e.row,s=e.col;else break}return{...e,cursorRow:o,cursorCol:s,preferredCol:null}}case`vim_move_word_backward`:{let{count:a}=t.payload,o=r,s=i;for(let e=0;e<a;e++){let e=q3(n,o,s);if(e)o=e.row,s=e.col;else break}return{...e,cursorRow:o,cursorCol:s,preferredCol:null}}case`vim_move_word_end`:{let{count:a}=t.payload,o=r,s=i;for(let e=0;e<a;e++){if(e===0){let e=O3(n[o]||``);if(s<e.length&&L3(e[s])&&(s+1>=e.length||!B3(e[s+1])||L3(e[s])&&IUe(e,s))){let e=K3(n,o,s+1,!1);if(e){o=e.row,s=e.col;continue}}}let t=K3(n,o,s,!1);if(t)o=t.row,s=t.col;else break}return{...e,cursorRow:o,cursorCol:s,preferredCol:null}}case`vim_delete_char`:{let{count:n}=t.payload,{cursorRow:r,cursorCol:i,lines:a}=e,o=k3(a[r]||``);if(i<o){let t=Math.min(n,o-i);return X3(t6(e),r,i,r,i+t,``)}return e}case`vim_insert_at_cursor`:return e;case`vim_append_at_cursor`:{let{cursorRow:t,cursorCol:n,lines:r}=e,i=n<k3(r[t]||``)?n+1:n;return{...e,cursorCol:i,preferredCol:null}}case`vim_open_line_below`:{let{cursorRow:t,lines:n}=e,r=t6(e),i=k3(n[t]||``);return X3(r,t,i,t,i,`
@@ -75858,7 +75858,7 @@ Register-ArgumentCompleter -Native -CommandName @('${e}') -ScriptBlock {
75858
75858
 
75859
75859
  `),process.stdout.write(` ${Q9}\n`),process.stdout.write(` ${s}\n\n`),e.dryRun){process.stdout.write(`Dry run — no changes written.
75860
75860
  `);return}if(process.stdin.isTTY&&process.stdout.isTTY){let e=await HJe(`Proceed? [Y/n] `);if(e!==``&&e.toLowerCase()!==`y`){process.stdout.write(`Aborted.
75861
- `);return}}GJe(o,s),process.stdout.write(`\nInstalled to ${o}\n\n`),process.stdout.write(`Restart your shell, or activate now:\n\n ${s}\n\n`),process.stdout.write(`Once active, unrecognized commands will be routed through \`${t} --print\`.\n`)}const qJe=`${hn.internalEnvPrefix}IPC`;function JJe(){return process.env[qJe]?.trim().toLowerCase()===`ndjson`}const YJe=cn();un(YJe),await xn({sessionId:YJe}),LZ()||(zee(Tl({runtime:`cli`,version:OZ.default.version})),wl(`cli`,`cli`)),process.on(`uncaughtException`,e=>{Dl(e,{handler:`uncaughtException`})}),process.on(`unhandledRejection`,e=>{Dl(e instanceof Error?e:Error(String(e)),{handler:`unhandledRejection`})});for(let e of[process.stdout,process.stderr,process.stdin])e.on?.(`error`,t=>{if(t.code===`EIO`||t.code===`EPIPE`||t.code===`ENOTCONN`)return;let n=e===process.stdin?`stdin`:e===process.stdout?`stdout`:`stderr`;Dl(t,{handler:`streamError`,stream:n});try{console.error(lZ(`red`)(`Fatal ${n} stream error: ${t.message??t.code??String(t)}`))}catch{}$Z(1)});function $9(e,t=1){throw console.error(lZ(`red`)(e)),$Z(t),Error(e)}function XJe(e){try{return new URL(e)}catch{$9(`Invalid ${hn.envPrefix}BASE_URL: ${e}`)}}function ZJe(e){(e?.[`output-format`]||e?.[`input-format`])&&!e?.print&&$9(`--output-format and --input-format flags can only be used with --print mode`)}async function QJe(){let e=process.stdin;e.isTTY&&$9(`No prompt provided and no piped input detected. Either provide a prompt or pipe input.`);let t=``;for await(let n of e)t+=n;let n=t.trim();return n||$9(`No input provided`),n}async function $Je(e){return e?.prompt?e.prompt:QJe()}async function eYe(e,t){let n=t.get(`baseUrl`);n&&(XJe(n),e.setUrl(n),e.resetEndpoints(),await e.getApiEndpoint())}async function tYe(e,t){if(e?.resume)return e.resume;if(e?.continue)try{return((await t.getConversationsList(hn.agentType))?.result??[]).sort((e,t)=>{let n=e.lastEventCreatedAt?new Date(e.lastEventCreatedAt).getTime():0;return(t.lastEventCreatedAt?new Date(t.lastEventCreatedAt).getTime():0)-n})[0]?.deploymentConversationId}catch{}}async function nYe(e,t){if(t?.version){console.log(`Abacus.AI CLI version ${OZ.default.version}`),$Z(0);return}if(ZJe(t),JJe()){kl(`client_kind`,`ndjson-ipc`),await tNe({agentArgs:t});return}else if(t?.print){kl(`client_kind`,`print`);let e=await $Je(t);await oNe({agentArgs:{...t,prompt:e}})}else{kl(`client_kind`,`cli`);let n=await PJ.create(),r=new Ul(n,Sn(),gn.userAgentNames.cli,OZ.default.version);if(await eYe(r,e),!n.isAuthenticated()&&!n.isEnvAuth()&&((!process.stdin.isTTY||!process.stdout.isTTY)&&$9(`Not authenticated. Set ${hn.envPrefix}API_KEY environment variable or run interactively to log in.`),!(await q9({authManager:n,apiClient:r,reason:`welcome`,version:OZ.default.version})).success)){$Z(0);return}let i=await tYe(t,r);await EJe({apiClient:r,authManager:n,configService:e,agentArgs:{...t,...i&&{conversationId:i}}})}}const rYe=`
75861
+ `);return}}GJe(o,s),process.stdout.write(`\nInstalled to ${o}\n\n`),process.stdout.write(`Restart your shell, or activate now:\n\n ${s}\n\n`),process.stdout.write(`Once active, unrecognized commands will be routed through \`${t} --print\`.\n`)}const qJe=`${hn.internalEnvPrefix}IPC`;function JJe(){return process.env[qJe]?.trim().toLowerCase()===`ndjson`}const YJe=cn();un(YJe),await xn({sessionId:YJe}),LZ()||(zee(Tl({runtime:`cli`,version:OZ.default.version})),wl(`cli`,`cli`)),process.on(`uncaughtException`,e=>{Dl(e,{handler:`uncaughtException`})}),process.on(`unhandledRejection`,e=>{Dl(e instanceof Error?e:Error(String(e)),{handler:`unhandledRejection`})});for(let e of[process.stdout,process.stderr,process.stdin])e.on?.(`error`,t=>{if(t.code===`EIO`||t.code===`EPIPE`||t.code===`ENOTCONN`)return;let n=e===process.stdin?`stdin`:e===process.stdout?`stdout`:`stderr`;Dl(t,{handler:`streamError`,stream:n});try{console.error(lZ(`red`)(`Fatal ${n} stream error: ${t.message??t.code??String(t)}`))}catch{}$Z(1)});function $9(e,t=1){throw console.error(lZ(`red`)(e)),$Z(t),Error(e)}function XJe(e){try{return new URL(e)}catch{$9(`Invalid ${hn.envPrefix}BASE_URL: ${e}`)}}function ZJe(e){(e?.[`output-format`]||e?.[`input-format`])&&!e?.print&&$9(`--output-format and --input-format flags can only be used with --print mode`)}async function QJe(){let e=process.stdin;e.isTTY&&$9(`No prompt provided and no piped input detected. Either provide a prompt or pipe input.`);let t=``;for await(let n of e)t+=n;let n=t.trim();return n||$9(`No input provided`),n}async function $Je(e){return e?.prompt?e.prompt:QJe()}async function eYe(e,t){let n=t.get(`baseUrl`);n&&(XJe(n),e.setUrl(n),e.resetEndpoints(),await e.getApiEndpoint())}async function tYe(e,t){if(e?.resume)return e.resume;if(e?.continue)try{let n=e.print?hn.nonInteractiveAgentType:hn.agentType;return((await t.getConversationsList(n))?.result??[]).sort((e,t)=>{let n=e.lastEventCreatedAt?new Date(e.lastEventCreatedAt).getTime():0;return(t.lastEventCreatedAt?new Date(t.lastEventCreatedAt).getTime():0)-n})[0]?.deploymentConversationId}catch{}}async function nYe(e,t){if(t?.version){console.log(`Abacus.AI CLI version ${OZ.default.version}`),$Z(0);return}if(ZJe(t),JJe()){kl(`client_kind`,`ndjson-ipc`),await tNe({agentArgs:t});return}else if(t?.print){kl(`client_kind`,`print`);let e=await $Je(t);await oNe({agentArgs:{...t,prompt:e}})}else{kl(`client_kind`,`cli`);let n=await PJ.create(),r=new Ul(n,Sn(),gn.userAgentNames.cli,OZ.default.version);if(await eYe(r,e),!n.isAuthenticated()&&!n.isEnvAuth()&&((!process.stdin.isTTY||!process.stdout.isTTY)&&$9(`Not authenticated. Set ${hn.envPrefix}API_KEY environment variable or run interactively to log in.`),!(await q9({authManager:n,apiClient:r,reason:`welcome`,version:OZ.default.version})).success)){$Z(0);return}let i=await tYe(t,r);await EJe({apiClient:r,authManager:n,configService:e,agentArgs:{...t,...i&&{conversationId:i}}})}}const rYe=`
75862
75862
  Usage: ${hn.binName} [options] [prompt]
75863
75863
 
75864
75864
  Examples:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@abacus-ai/cli",
3
- "version": "2.4.9-canary.2",
3
+ "version": "2.4.9-canary.3",
4
4
  "type": "module",
5
5
  "bin": {
6
6
  "abacusai": "dist/index.mjs"