@abacus-ai/cli 2.5.0-canary.1 → 2.5.0-canary.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.mjs +6 -6
- package/package.json +1 -1
package/dist/index.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{createRequire as e}from"node:module";import*as t from"node:os";import n,{arch as r,homedir as i,hostname as a,platform as o}from"node:os";import*as s from"node:util";import c,{isDeepStrictEqual as l,parseArgs as u,promisify as d,stripVTControlCharacters as f}from"node:util";import*as p from"node:fs";import m,{copyFileSync as h,createReadStream as g,createWriteStream as _,existsSync as v,mkdirSync as y,promises as b,readFile as x,readFileSync as S,readdir as C,readdirSync as w,realpathSync as T,statSync as E,unlinkSync as D,writeFileSync as O}from"node:fs";import{PassThrough as k,Readable as A,Transform as j,Writable as M}from"node:stream";import*as N from"node:path";import P,{dirname as ee,join as te,posix as F,resolve as I,sep as L}from"node:path";import{Worker as ne,isMainThread as R,threadId as z}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-notifier";import We from"node:tty";var Ge=Object.create,Ke=Object.defineProperty,qe=Object.getOwnPropertyDescriptor,Je=Object.getOwnPropertyNames,Ye=Object.getPrototypeOf,Xe=Object.prototype.hasOwnProperty,W=(e,t)=>()=>(e&&(t=e(e=0)),t),G=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),Ze=(e,t)=>{let n={};for(var r in e)Ke(n,r,{get:e[r],enumerable:!0});return t||Ke(n,Symbol.toStringTag,{value:`Module`}),n},Qe=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=Je(t),a=0,o=i.length,s;a<o;a++)s=i[a],!Xe.call(e,s)&&s!==n&&Ke(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=qe(t,s))||r.enumerable});return e},$e=(e,t,n)=>(n=e==null?{}:Ge(Ye(e)),Qe(t||!e||!e.__esModule?Ke(n,`default`,{value:e,enumerable:!0}):n,e)),et=e=>Xe.call(e,`module.exports`)?e[`module.exports`]:Qe(Ke({},`__esModule`,{value:!0}),e),tt=e(import.meta.url);const nt=Object.freeze({CLI:`CLI`,EXTENSION:`EXTENSION`,COWORK:`COWORK`});function rt(e){switch(e.trim().replaceAll(/[_\s-]+/g,``).toUpperCase()){case`CLI`:return nt.CLI;case`EXTENSION`:return nt.EXTENSION;case`COWORK`:return nt.COWORK;default:throw Error(`Invalid client type: ${e}. Expected one of ${Object.values(nt).join(`, `)}.`)}}const it=Object.freeze({CHATLLM:`CHATLLM`,CODE_LLM:`CODE_LLM`,CODE_LLM_AGENT:`CODE_LLM_AGENT`,CODE_LLM_NON_INTERACTIVE:`CODE_LLM_NON_INTERACTIVE`});function at(e){return typeof e==`function`?e:ot(e)}function ot(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 st=[`trace`,`debug`,`info`,`warning`,`error`,`fatal`];function ct(e,t){let n=st.indexOf(e);if(n<0)throw TypeError(`Invalid log level: ${JSON.stringify(e)}.`);let r=st.indexOf(t);if(r<0)throw TypeError(`Invalid log level: ${JSON.stringify(t)}.`);return n-r}const lt=Symbol.for(`logtape.lazy`);function ut(e){return typeof e==`object`&&!!e&< in e&&e[lt]===!0}function dt(e){let t={};for(let n in e){let r=e[n];t[n]=ut(r)?r.getter():r}return t}function ft(e=[]){return mt.getLogger(e)}const pt=Symbol.for(`logtape.rootLogger`);var mt=class e{parent;children;category;sinks;parentSinks=`inherit`;filters;lowestLevel=`trace`;contextLocalStorage;static getLogger(t=[]){let n=pt in globalThis?globalThis[pt]??null:null;return n??(n=new e(null,[]),globalThis[pt]=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 ht(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||ct(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||ct(e,this.lowestLevel)<0)return!1;for(let t of this.getSinks(e))return!0;return!1}emit(e,t){let n=Tt(),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||ct(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),gt.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=Et(),a,o=typeof n==`function`?{category:this.category,level:e,timestamp:Date.now(),get message(){return St(t,this.properties)},rawMessage:t,get properties(){return a??={...i,...n()},a}}:{category:this.category,level:e,timestamp:Date.now(),message:St(t,{...i,...n}),rawMessage:t,properties:{...i,...n}};this.emit(o,r)}logLazily(e,t,n={}){let r=Et(),i,a;function o(){if((a==null||i==null)&&(a=t((e,...t)=>(i=e,Ct(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=Et();this.emit({category:this.category,level:e,message:Ct(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)}},ht=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`?()=>dt({...i,...n()}):()=>dt({...i,...n}),r)}logLazily(e,t){this.logger.logLazily(e,t,dt(this.properties))}logTemplate(e,t,n){this.logger.logTemplate(e,t,n,dt(this.properties))}emit(e){let t={...e,properties:dt({...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 gt=mt.getLogger([`logtape`,`meta`]);function _t(e){return e.includes(`.`)||e.includes(`[`)||e.includes(`?.`)}function vt(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 yt(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+=`
|
|
2
|
+
import{createRequire as e}from"node:module";import*as t from"node:os";import n,{arch as r,homedir as i,hostname as a,platform as o}from"node:os";import*as s from"node:util";import c,{isDeepStrictEqual as l,parseArgs as u,promisify as d,stripVTControlCharacters as f}from"node:util";import*as p from"node:fs";import m,{copyFileSync as h,createReadStream as g,createWriteStream as _,existsSync as v,mkdirSync as y,promises as b,readFile as x,readFileSync as S,readdir as C,readdirSync as w,realpathSync as T,statSync as E,unlinkSync as D,writeFileSync as O}from"node:fs";import{PassThrough as k,Readable as A,Transform as j,Writable as M}from"node:stream";import*as N from"node:path";import P,{dirname as ee,join as te,posix as F,resolve as I,sep as L}from"node:path";import{Worker as ne,isMainThread as R,threadId as z}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-notifier";import We from"node:tty";var Ge=Object.create,Ke=Object.defineProperty,qe=Object.getOwnPropertyDescriptor,Je=Object.getOwnPropertyNames,Ye=Object.getPrototypeOf,Xe=Object.prototype.hasOwnProperty,W=(e,t)=>()=>(e&&(t=e(e=0)),t),G=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),Ze=(e,t)=>{let n={};for(var r in e)Ke(n,r,{get:e[r],enumerable:!0});return t||Ke(n,Symbol.toStringTag,{value:`Module`}),n},Qe=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=Je(t),a=0,o=i.length,s;a<o;a++)s=i[a],!Xe.call(e,s)&&s!==n&&Ke(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=qe(t,s))||r.enumerable});return e},$e=(e,t,n)=>(n=e==null?{}:Ge(Ye(e)),Qe(t||!e||!e.__esModule?Ke(n,`default`,{value:e,enumerable:!0}):n,e)),et=e=>Xe.call(e,`module.exports`)?e[`module.exports`]:Qe(Ke({},`__esModule`,{value:!0}),e),tt=e(import.meta.url);const nt=Object.freeze({CLI:`CLI`,EXTENSION:`EXTENSION`,COWORK:`COWORK`,CLOUD:`CLOUD`});function rt(e){switch(e.trim().replaceAll(/[_\s-]+/g,``).toUpperCase()){case`CLI`:return nt.CLI;case`EXTENSION`:return nt.EXTENSION;case`COWORK`:return nt.COWORK;case`CLOUD`:return nt.CLOUD;default:throw Error(`Invalid client type: ${e}. Expected one of ${Object.values(nt).join(`, `)}.`)}}const it=Object.freeze({CHATLLM:`CHATLLM`,CODE_LLM:`CODE_LLM`,CODE_LLM_AGENT:`CODE_LLM_AGENT`,CODE_LLM_NON_INTERACTIVE:`CODE_LLM_NON_INTERACTIVE`});function at(e){return typeof e==`function`?e:ot(e)}function ot(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 st=[`trace`,`debug`,`info`,`warning`,`error`,`fatal`];function ct(e,t){let n=st.indexOf(e);if(n<0)throw TypeError(`Invalid log level: ${JSON.stringify(e)}.`);let r=st.indexOf(t);if(r<0)throw TypeError(`Invalid log level: ${JSON.stringify(t)}.`);return n-r}const lt=Symbol.for(`logtape.lazy`);function ut(e){return typeof e==`object`&&!!e&< in e&&e[lt]===!0}function dt(e){let t={};for(let n in e){let r=e[n];t[n]=ut(r)?r.getter():r}return t}function ft(e=[]){return mt.getLogger(e)}const pt=Symbol.for(`logtape.rootLogger`);var mt=class e{parent;children;category;sinks;parentSinks=`inherit`;filters;lowestLevel=`trace`;contextLocalStorage;static getLogger(t=[]){let n=pt in globalThis?globalThis[pt]??null:null;return n??(n=new e(null,[]),globalThis[pt]=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 ht(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||ct(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||ct(e,this.lowestLevel)<0)return!1;for(let t of this.getSinks(e))return!0;return!1}emit(e,t){let n=Tt(),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||ct(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),gt.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=Et(),a,o=typeof n==`function`?{category:this.category,level:e,timestamp:Date.now(),get message(){return St(t,this.properties)},rawMessage:t,get properties(){return a??={...i,...n()},a}}:{category:this.category,level:e,timestamp:Date.now(),message:St(t,{...i,...n}),rawMessage:t,properties:{...i,...n}};this.emit(o,r)}logLazily(e,t,n={}){let r=Et(),i,a;function o(){if((a==null||i==null)&&(a=t((e,...t)=>(i=e,Ct(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=Et();this.emit({category:this.category,level:e,message:Ct(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)}},ht=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`?()=>dt({...i,...n()}):()=>dt({...i,...n}),r)}logLazily(e,t){this.logger.logLazily(e,t,dt(this.properties))}logTemplate(e,t,n){this.logger.logTemplate(e,t,n,dt(this.properties))}emit(e){let t={...e,properties:dt({...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 gt=mt.getLogger([`logtape`,`meta`]);function _t(e){return e.includes(`.`)||e.includes(`[`)||e.includes(`?.`)}function vt(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 yt(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 bt(e,t){if(typeof t==`string`)return vt(e,t);if(Array.isArray(e)&&t>=0&&t<e.length)return e[t]}function xt(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=yt(t,r);if(e===null)return;let{segment:i,nextIndex:a}=e;if(r=a,n=bt(n,i),n===void 0)return}return n}function St(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&&_t(u)&&(l=xt(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 Ct(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 wt=Symbol.for(`logtape.categoryPrefix`);function Tt(){let e=mt.getLogger().contextLocalStorage?.getStore();if(e==null)return[];let t=e[wt];return Array.isArray(t)?t:[]}function Et(){let e=mt.getLogger().contextLocalStorage?.getStore();if(e==null)return{};let t={};for(let n of Object.keys(e))t[n]=e[n];return t}var Dt=Ze({inspect:()=>Ot});function Ot(e,t){return c.inspect(e,t)}const kt={trace:`TRC`,debug:`DBG`,info:`INF`,warning:`WRN`,error:`ERR`,fatal:`FTL`},At=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}):Dt!=null&&`inspect`in Dt&&typeof Ot==`function`?(e,t)=>Ot(e,{maxArrayLength:1/0,maxStringLength:1/0,...t}):e=>JSON.stringify(e);function jt(e){return e<10?`0${e}`:`${e}`}function Mt(e){return e<10?`00${e}`:e<100?`0${e}`:`${e}`}const Nt={"date-time-timezone":e=>{let t=new Date(e);return`${t.getUTCFullYear()}-${jt(t.getUTCMonth()+1)}-${jt(t.getUTCDate())} ${jt(t.getUTCHours())}:${jt(t.getUTCMinutes())}:${jt(t.getUTCSeconds())}.${Mt(t.getUTCMilliseconds())} +00:00`},"date-time-tz":e=>{let t=new Date(e);return`${t.getUTCFullYear()}-${jt(t.getUTCMonth()+1)}-${jt(t.getUTCDate())} ${jt(t.getUTCHours())}:${jt(t.getUTCMinutes())}:${jt(t.getUTCSeconds())}.${Mt(t.getUTCMilliseconds())} +00`},"date-time":e=>{let t=new Date(e);return`${t.getUTCFullYear()}-${jt(t.getUTCMonth()+1)}-${jt(t.getUTCDate())} ${jt(t.getUTCHours())}:${jt(t.getUTCMinutes())}:${jt(t.getUTCSeconds())}.${Mt(t.getUTCMilliseconds())}`},"time-timezone":e=>{let t=new Date(e);return`${jt(t.getUTCHours())}:${jt(t.getUTCMinutes())}:${jt(t.getUTCSeconds())}.${Mt(t.getUTCMilliseconds())} +00:00`},"time-tz":e=>{let t=new Date(e);return`${jt(t.getUTCHours())}:${jt(t.getUTCMinutes())}:${jt(t.getUTCSeconds())}.${Mt(t.getUTCMilliseconds())} +00`},time:e=>{let t=new Date(e);return`${jt(t.getUTCHours())}:${jt(t.getUTCMinutes())}:${jt(t.getUTCSeconds())}.${Mt(t.getUTCMilliseconds())}`},date:e=>{let t=new Date(e);return`${t.getUTCFullYear()}-${jt(t.getUTCMonth()+1)}-${jt(t.getUTCDate())}`},rfc3339:e=>new Date(e).toISOString(),none:()=>null},Pt={ABBR:kt,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 Ft(e){return e===`crlf`?`\r
|
|
4
4
|
`:`
|
|
5
5
|
`}function It(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 Lt(e={}){let t=(()=>{let t=e.timestamp;return t==null?Nt[`date-time-timezone`]:t===`disabled`?Nt.none:typeof t==`string`&&t in Nt?Nt[t]:t})(),n=e.category??`·`,r=e.value?t=>e.value(t,At):At,i=(()=>{let t=e.level;return t==null||t===`ABBR`?e=>Pt.ABBR[e]:t===`abbr`?e=>Pt.abbr[e]:t===`FULL`?e=>Pt.FULL[e]:t===`full`?e=>Pt.full[e]:t===`L`?e=>Pt.L[e]:t===`l`?e=>Pt.l[e]:t})(),a=Ft(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 Rt=Lt(),zt=`\x1B[0m`,Bt={black:`\x1B[30m`,red:`\x1B[31m`,green:`\x1B[32m`,yellow:`\x1B[33m`,blue:`\x1B[34m`,magenta:`\x1B[35m`,cyan:`\x1B[36m`,white:`\x1B[37m`},Vt={bold:`\x1B[1m`,dim:`\x1B[2m`,italic:`\x1B[3m`,underline:`\x1B[4m`,strikethrough:`\x1B[9m`},Ht={trace:null,debug:`blue`,info:`green`,warning:`yellow`,error:`red`,fatal:`magenta`};function Ut(e={}){let t=e.format,n=e.timestampStyle===void 0?`dim`:e.timestampStyle,r=e.timestampColor??null,i=`${n==null?``:Vt[n]}${r==null?``:Bt[r]}`,a=n==null&&r==null?``:zt,o=e.levelStyle===void 0?`bold`:e.levelStyle,s=e.levelColors??Ht,c=e.categoryStyle===void 0?`dim`:e.categoryStyle,l=e.categoryColor??null,u=`${c==null?``:Vt[c]}${l==null?``:Bt[l]}`,d=c==null&&l==null?``:zt;return Lt({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?``:Vt[o]}${f==null?``:Bt[f]}${n}${o==null&&f==null?``:zt}`,t==null?`${e==null?``:`${e} `}${n} ${u}${r}:${d} ${c}`:t({timestamp:e,level:n,category:`${u}${r}${d}`,message:c,record:l})}})}Ut();function Wt(e={}){let t=Ft(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},It)+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},It)+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},It)+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)},It)+t}Wt();const Gt={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 Kt(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${kt[e.level]}%c %c${e.category.join(`·`)} %c${t}`,`color: gray;`,Gt[e.level],`background-color: default;`,`color: gray;`,`color: default;`,...n]}function qt(e={}){let t=e.formatter??Kt,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 Jt=null;const Yt=new Set,Xt=new Set,Zt=new Set;function Qt(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 $t(e){let t=e?an:on;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 en(e){if(Jt!=null&&!e.reset)throw new sn(`Already configured; if you want to reset, turn on the reset flag.`);await nn();try{tn(e,!0)}catch(e){throw e instanceof sn&&await nn(),e}}function tn(e,t){Jt=e;let n=!1,r=new Set;for(let t of e.loggers){Qt(t)&&(n=!0);let i=Array.isArray(t.category)?JSON.stringify(t.category):JSON.stringify([t.category]);if(r.has(i))throw new sn(`Duplicate logger configuration for category: ${i}. Each category can only be configured once.`);r.add(i);let a=mt.getLogger(t.category);for(let n of t.sinks??[]){let t=e.sinks[n];if(!t)throw new sn(`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 sn(`Filter not found: ${n}.`);a.filters.push(at(t))}Yt.add(a)}mt.getLogger().contextLocalStorage=e.contextLocalStorage;for(let n of Object.values(e.sinks)){if(Symbol.asyncDispose in n)if(t)Zt.add(n);else throw new sn(`Async disposables cannot be used with configureSync().`);Symbol.dispose in n&&Xt.add(n)}for(let n of Object.values(e.filters??{}))if(!(n==null||typeof n==`string`)){if(Symbol.asyncDispose in n)if(t)Zt.add(n);else throw new sn(`Async disposables cannot be used with configureSync().`);Symbol.dispose in n&&Xt.add(n)}$t(t);let i=mt.getLogger([`logtape`,`meta`]);n||i.sinks.push(qt()),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 nn(){await an(),rn()}function rn(){let e=mt.getLogger([]);e.resetDescendants(),delete e.contextLocalStorage,Yt.clear(),Jt=null}async function an(){on();let e=[];for(let t of Zt)e.push(t[Symbol.asyncDispose]()),Zt.delete(t);await Promise.all(e)}function on(){for(let e of Xt)e[Symbol.dispose]();Xt.clear()}var sn=class extends Error{constructor(e){super(e),this.name=`ConfigureError`}};let cn=``;function ln(){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 un(){return cn||=ln(),cn}function dn(e){cn=e}function fn(e,t){let n=t.formatter??Rt,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 pn={openSync(e){return m.openSync(e,`a`)},writeSync:m.writeSync,writeManySync(e,t){if(t.length!==0){if(t.length===1){m.writeSync(e,t[0]);return}m.writevSync(e,t)}},flushSync:m.fsyncSync,closeSync:m.closeSync,statSync:m.statSync,renameSync:m.renameSync},mn={...pn,async writeMany(e,t){if(t.length!==0){if(t.length===1){await d(m.write)(e,t[0]);return}await d(m.writev)(e,t)}},flush:d(m.fsync),close:d(m.close)};({...pn}),m.readdirSync,m.unlinkSync,m.mkdirSync,{...mn},m.readdirSync,m.unlinkSync,m.mkdirSync;function hn(e,t={}){return t.nonBlocking?fn(e,{...t,...mn}):fn(e,{...t,...pn})}const gn={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`},_n={publishName:`@abacus-ai/cli`,userAgentNames:{cli:`codellm-cli`,desktop:`codellm-desktop`,print:`codellm-non-interactive`},runtimeDeps:[`koffi`,`@vscode/ripgrep`,`trash`,`node-notifier`]};function vn(){return P.join(i(),gn.configDirName,gn.logsDirName)}function yn(e,t=20){try{let n=w(e).filter(e=>e.endsWith(`.log`)).map(t=>({name:t,mtime:E(P.join(e,t)).mtimeMs})).sort((e,t)=>t.mtime-e.mtime);for(let r of n.slice(t))try{D(P.join(e,r.name))}catch{}}catch{}}function bn(e){try{y(e,{recursive:!0})}catch{}}function xn(e,t){return bn(e),yn(e),hn(P.join(e,`${t}.log`),{maxSize:5*1024*1024,maxFiles:20})}async function Sn(e={}){let t=e.sessionId??un(),n=e.logDir??vn(),r=e.logLevel??(e.dev?`debug`:`info`),i={file:xn(n,t)};e.dev&&(i.console=qt()),await en({sinks:i,loggers:[{category:[`codellm`],lowestLevel:r,sinks:Object.keys(i)},{category:[`logtape`,`meta`],lowestLevel:`warning`,sinks:[]}]})}function Cn(){let e=ft([`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 wn=typeof __SENTRY_DEBUG__>`u`||__SENTRY_DEBUG__,Tn=globalThis,En=`10.51.0`;function Dn(){return On(Tn),Tn}function On(e){let t=e.__SENTRY__=e.__SENTRY__||{};return t.version=t.version||`10.51.0`,t[En]=t[`10.51.0`]||{}}function kn(e,t,n=Tn){let r=n.__SENTRY__=n.__SENTRY__||{},i=r[En]=r[`10.51.0`]||{};return i[e]||(i[e]=t())}const An=[`debug`,`info`,`warn`,`error`,`log`,`assert`,`trace`],jn={};function Mn(e){if(!(`console`in Tn))return e();let t=Tn.console,n={},r=Object.keys(jn);r.forEach(e=>{let r=jn[e];n[e]=t[e],t[e]=r});try{return e()}finally{r.forEach(e=>{t[e]=n[e]})}}function Nn(){Bn().enabled=!0}function Pn(){Bn().enabled=!1}function Fn(){return Bn().enabled}function In(...e){zn(`log`,...e)}function Ln(...e){zn(`warn`,...e)}function Rn(...e){zn(`error`,...e)}function zn(e,...t){wn&&Fn()&&Mn(()=>{Tn.console[e](`Sentry Logger [${e}]:`,...t)})}function Bn(){return wn?kn(`loggerSettings`,()=>({enabled:!1})):{enabled:!1}}const Vn={enable:Nn,disable:Pn,isEnabled:Fn,log:In,warn:Ln,error:Rn},Hn=/\(error: (.*)\)/,Un=/captureMessage|captureException/;function Wn(...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(`
|
|
@@ -1896,7 +1896,7 @@ ${e.terminator}`}function Uhe(e){return`(${vF(e.body)})${_F(e.redirections)}`}fu
|
|
|
1896
1896
|
|
|
1897
1897
|
`)}t.write(`payload.value = newResult;`),t.write(`return payload;`);let s=t.compile();return(t,n)=>s(e,t,n)},a,o=AI,s=!bI.jitless,c=s&&p_e.value,l=t.catchall,u;e._zod.parse=(d,f)=>{u??=r.value;let p=d.value;return o(p)?s&&c&&f?.async===!1&&f.jitless!==!0?(a||=i(t.shape),d=a(d,f),l?SL([],p,d,f,u,e):d):n(d,f):(d.issues.push({expected:`object`,code:`invalid_type`,input:p,inst:e}),d)}});function CL(e,t,n,r){for(let n of e)if(n.issues.length===0)return t.value=n.value,t;let i=e.filter(e=>!LI(e));return i.length===1?(t.value=i[0].value,i[0]):(t.issues.push({code:`invalid_union`,input:t.value,inst:n,errors:e.map(e=>e.issues.map(e=>BI(e,r,xI())))}),t)}const wL=_I(`$ZodUnion`,(e,t)=>{pL.init(e,t),EI(e._zod,`optin`,()=>t.options.some(e=>e._zod.optin===`optional`)?`optional`:void 0),EI(e._zod,`optout`,()=>t.options.some(e=>e._zod.optout===`optional`)?`optional`:void 0),EI(e._zod,`values`,()=>{if(t.options.every(e=>e._zod.values))return new Set(t.options.flatMap(e=>Array.from(e._zod.values)))}),EI(e._zod,`pattern`,()=>{if(t.options.every(e=>e._zod.pattern)){let e=t.options.map(e=>e._zod.pattern);return RegExp(`^(${e.map(e=>TI(e.source)).join(`|`)})$`)}});let n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(r,i)=>{if(n)return n(r,i);let a=!1,o=[];for(let e of t.options){let t=e._zod.run({value:r.value,issues:[]},i);if(t instanceof Promise)o.push(t),a=!0;else{if(t.issues.length===0)return t;o.push(t)}}return a?Promise.all(o).then(t=>CL(t,r,e,i)):CL(o,r,e,i)}});function TL(e,t,n,r){let i=e.filter(e=>e.issues.length===0);return i.length===1?(t.value=i[0].value,t):(i.length===0?t.issues.push({code:`invalid_union`,input:t.value,inst:n,errors:e.map(e=>e.issues.map(e=>BI(e,r,xI())))}):t.issues.push({code:`invalid_union`,input:t.value,inst:n,errors:[],inclusive:!1}),t)}const vye=_I(`$ZodXor`,(e,t)=>{wL.init(e,t),t.inclusive=!1;let n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(r,i)=>{if(n)return n(r,i);let a=!1,o=[];for(let e of t.options){let t=e._zod.run({value:r.value,issues:[]},i);t instanceof Promise?(o.push(t),a=!0):o.push(t)}return a?Promise.all(o).then(t=>TL(t,r,e,i)):TL(o,r,e,i)}}),yye=_I(`$ZodDiscriminatedUnion`,(e,t)=>{t.inclusive=!1,wL.init(e,t);let n=e._zod.parse;EI(e._zod,`propValues`,()=>{let e={};for(let n of t.options){let r=n._zod.propValues;if(!r||Object.keys(r).length===0)throw Error(`Invalid discriminated union option at index "${t.options.indexOf(n)}"`);for(let[t,n]of Object.entries(r)){e[t]||(e[t]=new Set);for(let r of n)e[t].add(r)}}return e});let r=CI(()=>{let e=t.options,n=new Map;for(let r of e){let e=r._zod.propValues?.[t.discriminator];if(!e||e.size===0)throw Error(`Invalid discriminated union option at index "${t.options.indexOf(r)}"`);for(let t of e){if(n.has(t))throw Error(`Duplicate discriminator value "${String(t)}"`);n.set(t,r)}}return n});e._zod.parse=(i,a)=>{let o=i.value;if(!AI(o))return i.issues.push({code:`invalid_type`,expected:`object`,input:o,inst:e}),i;let s=r.value.get(o?.[t.discriminator]);return s?s._zod.run(i,a):t.unionFallback||a.direction===`backward`?n(i,a):(i.issues.push({code:`invalid_union`,errors:[],note:`No matching discriminator`,discriminator:t.discriminator,options:Array.from(r.value.keys()),input:o,path:[t.discriminator],inst:e}),i)}}),bye=_I(`$ZodIntersection`,(e,t)=>{pL.init(e,t),e._zod.parse=(e,n)=>{let r=e.value,i=t.left._zod.run({value:r,issues:[]},n),a=t.right._zod.run({value:r,issues:[]},n);return i instanceof Promise||a instanceof Promise?Promise.all([i,a]).then(([t,n])=>DL(e,t,n)):DL(e,i,a)}});function EL(e,t){if(e===t||e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(jI(e)&&jI(t)){let n=Object.keys(t),r=Object.keys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=EL(e[n],t[n]);if(!r.valid)return{valid:!1,mergeErrorPath:[n,...r.mergeErrorPath]};i[n]=r.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let r=0;r<e.length;r++){let i=e[r],a=t[r],o=EL(i,a);if(!o.valid)return{valid:!1,mergeErrorPath:[r,...o.mergeErrorPath]};n.push(o.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function DL(e,t,n){let r=new Map,i;for(let n of t.issues)if(n.code===`unrecognized_keys`){i??=n;for(let e of n.keys)r.has(e)||r.set(e,{}),r.get(e).l=!0}else e.issues.push(n);for(let t of n.issues)if(t.code===`unrecognized_keys`)for(let e of t.keys)r.has(e)||r.set(e,{}),r.get(e).r=!0;else e.issues.push(t);let a=[...r].filter(([,e])=>e.l&&e.r).map(([e])=>e);if(a.length&&i&&e.issues.push({...i,keys:a}),LI(e))return e;let o=EL(t.value,n.value);if(!o.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(o.mergeErrorPath)}`);return e.value=o.data,e}const OL=_I(`$ZodTuple`,(e,t)=>{pL.init(e,t);let n=t.items;e._zod.parse=(r,i)=>{let a=r.value;if(!Array.isArray(a))return r.issues.push({input:a,inst:e,expected:`tuple`,code:`invalid_type`}),r;r.value=[];let o=[],s=kL(n,`optin`),c=kL(n,`optout`);if(!t.rest){if(a.length<s)return r.issues.push({code:`too_small`,minimum:s,inclusive:!0,input:a,inst:e,origin:`array`}),r;a.length>n.length&&r.issues.push({code:`too_big`,maximum:n.length,inclusive:!0,input:a,inst:e,origin:`array`})}let l=Array(n.length);for(let e=0;e<n.length;e++){let t=n[e]._zod.run({value:a[e],issues:[]},i);t instanceof Promise?o.push(t.then(t=>{l[e]=t})):l[e]=t}if(t.rest){let e=n.length-1,s=a.slice(n.length);for(let n of s){e++;let a=t.rest._zod.run({value:n,issues:[]},i);a instanceof Promise?o.push(a.then(t=>AL(t,r,e))):AL(a,r,e)}}return o.length?Promise.all(o).then(()=>jL(l,r,n,a,c)):jL(l,r,n,a,c)}});function kL(e,t){for(let n=e.length-1;n>=0;n--)if(e[n]._zod[t]!==`optional`)return n+1;return 0}function AL(e,t,n){e.issues.length&&t.issues.push(...RI(n,e.issues)),t.value[n]=e.value}function jL(e,t,n,r,i){for(let a=0;a<n.length;a++){let n=e[a],o=a<r.length;if(n.issues.length){if(!o&&a>=i){t.value.length=a;break}t.issues.push(...RI(a,n.issues))}t.value[a]=n.value}for(let e=t.value.length-1;e>=r.length&&n[e]._zod.optout===`optional`&&t.value[e]===void 0;e--)t.value.length=e;return t}const xye=_I(`$ZodRecord`,(e,t)=>{pL.init(e,t),e._zod.parse=(n,r)=>{let i=n.value;if(!jI(i))return n.issues.push({expected:`record`,code:`invalid_type`,input:i,inst:e}),n;let a=[],o=t.keyType._zod.values;if(o){n.value={};let s=new Set;for(let c of o)if(typeof c==`string`||typeof c==`number`||typeof c==`symbol`){s.add(typeof c==`number`?c.toString():c);let o=t.keyType._zod.run({value:c,issues:[]},r);if(o instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(o.issues.length){n.issues.push({code:`invalid_key`,origin:`record`,issues:o.issues.map(e=>BI(e,r,xI())),input:c,path:[c],inst:e});continue}let l=o.value,u=t.valueType._zod.run({value:i[c],issues:[]},r);u instanceof Promise?a.push(u.then(e=>{e.issues.length&&n.issues.push(...RI(c,e.issues)),n.value[l]=e.value})):(u.issues.length&&n.issues.push(...RI(c,u.issues)),n.value[l]=u.value)}let c;for(let e in i)s.has(e)||(c??=[],c.push(e));c&&c.length>0&&n.issues.push({code:`unrecognized_keys`,input:i,inst:e,keys:c})}else{n.value={};for(let o of Reflect.ownKeys(i)){if(o===`__proto__`||!Object.prototype.propertyIsEnumerable.call(i,o))continue;let s=t.keyType._zod.run({value:o,issues:[]},r);if(s instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(typeof o==`string`&&iL.test(o)&&s.issues.length){let e=t.keyType._zod.run({value:Number(o),issues:[]},r);if(e instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);e.issues.length===0&&(s=e)}if(s.issues.length){t.mode===`loose`?n.value[o]=i[o]:n.issues.push({code:`invalid_key`,origin:`record`,issues:s.issues.map(e=>BI(e,r,xI())),input:o,path:[o],inst:e});continue}let c=t.valueType._zod.run({value:i[o],issues:[]},r);c instanceof Promise?a.push(c.then(e=>{e.issues.length&&n.issues.push(...RI(o,e.issues)),n.value[s.value]=e.value})):(c.issues.length&&n.issues.push(...RI(o,c.issues)),n.value[s.value]=c.value)}}return a.length?Promise.all(a).then(()=>n):n}}),Sye=_I(`$ZodMap`,(e,t)=>{pL.init(e,t),e._zod.parse=(n,r)=>{let i=n.value;if(!(i instanceof Map))return n.issues.push({expected:`map`,code:`invalid_type`,input:i,inst:e}),n;let a=[];n.value=new Map;for(let[o,s]of i){let c=t.keyType._zod.run({value:o,issues:[]},r),l=t.valueType._zod.run({value:s,issues:[]},r);c instanceof Promise||l instanceof Promise?a.push(Promise.all([c,l]).then(([t,a])=>{ML(t,a,n,o,i,e,r)})):ML(c,l,n,o,i,e,r)}return a.length?Promise.all(a).then(()=>n):n}});function ML(e,t,n,r,i,a,o){e.issues.length&&(NI.has(typeof r)?n.issues.push(...RI(r,e.issues)):n.issues.push({code:`invalid_key`,origin:`map`,input:i,inst:a,issues:e.issues.map(e=>BI(e,o,xI()))})),t.issues.length&&(NI.has(typeof r)?n.issues.push(...RI(r,t.issues)):n.issues.push({origin:`map`,code:`invalid_element`,input:i,inst:a,key:r,issues:t.issues.map(e=>BI(e,o,xI()))})),n.value.set(e.value,t.value)}const Cye=_I(`$ZodSet`,(e,t)=>{pL.init(e,t),e._zod.parse=(n,r)=>{let i=n.value;if(!(i instanceof Set))return n.issues.push({input:i,inst:e,expected:`set`,code:`invalid_type`}),n;let a=[];n.value=new Set;for(let e of i){let i=t.valueType._zod.run({value:e,issues:[]},r);i instanceof Promise?a.push(i.then(e=>NL(e,n))):NL(i,n)}return a.length?Promise.all(a).then(()=>n):n}});function NL(e,t){e.issues.length&&t.issues.push(...e.issues),t.value.add(e.value)}const wye=_I(`$ZodEnum`,(e,t)=>{pL.init(e,t);let n=c_e(t.entries),r=new Set(n);e._zod.values=r,e._zod.pattern=RegExp(`^(${n.filter(e=>NI.has(typeof e)).map(e=>typeof e==`string`?PI(e):e.toString()).join(`|`)})$`),e._zod.parse=(t,i)=>{let a=t.value;return r.has(a)||t.issues.push({code:`invalid_value`,values:n,input:a,inst:e}),t}}),Tye=_I(`$ZodLiteral`,(e,t)=>{if(pL.init(e,t),t.values.length===0)throw Error(`Cannot create literal schema with no valid values`);let n=new Set(t.values);e._zod.values=n,e._zod.pattern=RegExp(`^(${t.values.map(e=>typeof e==`string`?PI(e):e?PI(e.toString()):String(e)).join(`|`)})$`),e._zod.parse=(r,i)=>{let a=r.value;return n.has(a)||r.issues.push({code:`invalid_value`,values:t.values,input:a,inst:e}),r}}),Eye=_I(`$ZodFile`,(e,t)=>{pL.init(e,t),e._zod.parse=(t,n)=>{let r=t.value;return r instanceof File||t.issues.push({expected:`file`,code:`invalid_type`,input:r,inst:e}),t}}),Dye=_I(`$ZodTransform`,(e,t)=>{pL.init(e,t),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new yI(e.constructor.name);let i=t.transform(n.value,n);if(r.async)return(i instanceof Promise?i:Promise.resolve(i)).then(e=>(n.value=e,n));if(i instanceof Promise)throw new vI;return n.value=i,n}});function PL(e,t){return e.issues.length&&t===void 0?{issues:[],value:void 0}:e}const FL=_I(`$ZodOptional`,(e,t)=>{pL.init(e,t),e._zod.optin=`optional`,e._zod.optout=`optional`,EI(e._zod,`values`,()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),EI(e._zod,`pattern`,()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${TI(e.source)})?$`):void 0}),e._zod.parse=(e,n)=>{if(t.innerType._zod.optin===`optional`){let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(t=>PL(t,e.value)):PL(r,e.value)}return e.value===void 0?e:t.innerType._zod.run(e,n)}}),Oye=_I(`$ZodExactOptional`,(e,t)=>{FL.init(e,t),EI(e._zod,`values`,()=>t.innerType._zod.values),EI(e._zod,`pattern`,()=>t.innerType._zod.pattern),e._zod.parse=(e,n)=>t.innerType._zod.run(e,n)}),kye=_I(`$ZodNullable`,(e,t)=>{pL.init(e,t),EI(e._zod,`optin`,()=>t.innerType._zod.optin),EI(e._zod,`optout`,()=>t.innerType._zod.optout),EI(e._zod,`pattern`,()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${TI(e.source)}|null)$`):void 0}),EI(e._zod,`values`,()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(e,n)=>e.value===null?e:t.innerType._zod.run(e,n)}),Aye=_I(`$ZodDefault`,(e,t)=>{pL.init(e,t),e._zod.optin=`optional`,EI(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);if(e.value===void 0)return e.value=t.defaultValue,e;let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(e=>IL(e,t)):IL(r,t)}});function IL(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const jye=_I(`$ZodPrefault`,(e,t)=>{pL.init(e,t),e._zod.optin=`optional`,EI(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>(n.direction===`backward`||e.value===void 0&&(e.value=t.defaultValue),t.innerType._zod.run(e,n))}),Mye=_I(`$ZodNonOptional`,(e,t)=>{pL.init(e,t),EI(e._zod,`values`,()=>{let e=t.innerType._zod.values;return e?new Set([...e].filter(e=>e!==void 0)):void 0}),e._zod.parse=(n,r)=>{let i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(t=>LL(t,e)):LL(i,e)}});function LL(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:`invalid_type`,expected:`nonoptional`,input:e.value,inst:t}),e}const Nye=_I(`$ZodSuccess`,(e,t)=>{pL.init(e,t),e._zod.parse=(e,n)=>{if(n.direction===`backward`)throw new yI(`ZodSuccess`);let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(t=>(e.value=t.issues.length===0,e)):(e.value=r.issues.length===0,e)}}),Pye=_I(`$ZodCatch`,(e,t)=>{pL.init(e,t),EI(e._zod,`optin`,()=>t.innerType._zod.optin),EI(e._zod,`optout`,()=>t.innerType._zod.optout),EI(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(r=>(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>BI(e,n,xI()))},input:e.value}),e.issues=[]),e)):(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>BI(e,n,xI()))},input:e.value}),e.issues=[]),e)}}),Fye=_I(`$ZodNaN`,(e,t)=>{pL.init(e,t),e._zod.parse=(t,n)=>((typeof t.value!=`number`||!Number.isNaN(t.value))&&t.issues.push({input:t.value,inst:e,expected:`nan`,code:`invalid_type`}),t)}),Iye=_I(`$ZodPipe`,(e,t)=>{pL.init(e,t),EI(e._zod,`values`,()=>t.in._zod.values),EI(e._zod,`optin`,()=>t.in._zod.optin),EI(e._zod,`optout`,()=>t.out._zod.optout),EI(e._zod,`propValues`,()=>t.in._zod.propValues),e._zod.parse=(e,n)=>{if(n.direction===`backward`){let r=t.out._zod.run(e,n);return r instanceof Promise?r.then(e=>RL(e,t.in,n)):RL(r,t.in,n)}let r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>RL(e,t.out,n)):RL(r,t.out,n)}});function RL(e,t,n){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},n)}const Lye=_I(`$ZodCodec`,(e,t)=>{pL.init(e,t),EI(e._zod,`values`,()=>t.in._zod.values),EI(e._zod,`optin`,()=>t.in._zod.optin),EI(e._zod,`optout`,()=>t.out._zod.optout),EI(e._zod,`propValues`,()=>t.in._zod.propValues),e._zod.parse=(e,n)=>{if((n.direction||`forward`)===`forward`){let r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>zL(e,t,n)):zL(r,t,n)}else{let r=t.out._zod.run(e,n);return r instanceof Promise?r.then(e=>zL(e,t,n)):zL(r,t,n)}}});function zL(e,t,n){if(e.issues.length)return e.aborted=!0,e;if((n.direction||`forward`)===`forward`){let r=t.transform(e.value,e);return r instanceof Promise?r.then(r=>BL(e,r,t.out,n)):BL(e,r,t.out,n)}else{let r=t.reverseTransform(e.value,e);return r instanceof Promise?r.then(r=>BL(e,r,t.in,n)):BL(e,r,t.in,n)}}function BL(e,t,n,r){return e.issues.length?(e.aborted=!0,e):n._zod.run({value:t,issues:e.issues},r)}const Rye=_I(`$ZodReadonly`,(e,t)=>{pL.init(e,t),EI(e._zod,`propValues`,()=>t.innerType._zod.propValues),EI(e._zod,`values`,()=>t.innerType._zod.values),EI(e._zod,`optin`,()=>t.innerType?._zod?.optin),EI(e._zod,`optout`,()=>t.innerType?._zod?.optout),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(VL):VL(r)}});function VL(e){return e.value=Object.freeze(e.value),e}const zye=_I(`$ZodTemplateLiteral`,(e,t)=>{pL.init(e,t);let n=[];for(let e of t.parts)if(typeof e==`object`&&e){if(!e._zod.pattern)throw Error(`Invalid template literal part, no pattern found: ${[...e._zod.traits].shift()}`);let t=e._zod.pattern instanceof RegExp?e._zod.pattern.source:e._zod.pattern;if(!t)throw Error(`Invalid template literal part: ${e._zod.traits}`);let r=+!!t.startsWith(`^`),i=t.endsWith(`$`)?t.length-1:t.length;n.push(t.slice(r,i))}else if(e===null||m_e.has(typeof e))n.push(PI(`${e}`));else throw Error(`Invalid template literal part: ${e}`);e._zod.pattern=RegExp(`^${n.join(``)}$`),e._zod.parse=(n,r)=>typeof n.value==`string`?(e._zod.pattern.lastIndex=0,e._zod.pattern.test(n.value)||n.issues.push({input:n.value,inst:e,code:`invalid_format`,format:t.format??`template_literal`,pattern:e._zod.pattern.source}),n):(n.issues.push({input:n.value,inst:e,expected:`string`,code:`invalid_type`}),n)}),Bye=_I(`$ZodFunction`,(e,t)=>(pL.init(e,t),e._def=t,e._zod.def=t,e.implement=t=>{if(typeof t!=`function`)throw Error(`implement() must be called with a function`);return function(...n){let r=e._def.input?JI(e._def.input,n):n,i=Reflect.apply(t,this,r);return e._def.output?JI(e._def.output,i):i}},e.implementAsync=t=>{if(typeof t!=`function`)throw Error(`implementAsync() must be called with a function`);return async function(...n){let r=e._def.input?await XI(e._def.input,n):n,i=await Reflect.apply(t,this,r);return e._def.output?await XI(e._def.output,i):i}},e._zod.parse=(t,n)=>typeof t.value==`function`?(e._def.output&&e._def.output._zod.def.type===`promise`?t.value=e.implementAsync(t.value):t.value=e.implement(t.value),t):(t.issues.push({code:`invalid_type`,expected:`function`,input:t.value,inst:e}),t),e.input=(...t)=>{let n=e.constructor;return Array.isArray(t[0])?new n({type:`function`,input:new OL({type:`tuple`,items:t[0],rest:t[1]}),output:e._def.output}):new n({type:`function`,input:t[0],output:e._def.output})},e.output=t=>{let n=e.constructor;return new n({type:`function`,input:e._def.input,output:t})},e)),Vye=_I(`$ZodPromise`,(e,t)=>{pL.init(e,t),e._zod.parse=(e,n)=>Promise.resolve(e.value).then(e=>t.innerType._zod.run({value:e,issues:[]},n))}),Hye=_I(`$ZodLazy`,(e,t)=>{pL.init(e,t),EI(e._zod,`innerType`,()=>{let e=t;return e._cachedInner||=t.getter(),e._cachedInner}),EI(e._zod,`pattern`,()=>e._zod.innerType?._zod?.pattern),EI(e._zod,`propValues`,()=>e._zod.innerType?._zod?.propValues),EI(e._zod,`optin`,()=>e._zod.innerType?._zod?.optin??void 0),EI(e._zod,`optout`,()=>e._zod.innerType?._zod?.optout??void 0),e._zod.parse=(t,n)=>e._zod.innerType._zod.run(t,n)}),Uye=_I(`$ZodCustom`,(e,t)=>{sL.init(e,t),pL.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=n=>{let r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then(t=>HL(t,n,r,e));HL(i,n,r,e)}});function HL(e,t,n,r){if(!e){let e={code:`custom`,input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(e.params=r._zod.def.params),t.issues.push(UI(e))}}var UL,Wye=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){let n=t[0];return this._map.set(e,n),n&&typeof n==`object`&&`id`in n&&this._idmap.set(n.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let t=this._map.get(e);return t&&typeof t==`object`&&`id`in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let n={...this.get(t)??{}};delete n.id;let r={...n,...this._map.get(e)};return Object.keys(r).length?r:void 0}return this._map.get(e)}has(e){return this._map.has(e)}};function Gye(){return new Wye}(UL=globalThis).__zod_globalRegistry??(UL.__zod_globalRegistry=Gye());const WL=globalThis.__zod_globalRegistry;function Kye(e,t){return new e({type:`string`,...II(t)})}function qye(e,t){return new e({type:`string`,coerce:!0,...II(t)})}function Jye(e,t){return new e({type:`string`,format:`email`,check:`string_format`,abort:!1,...II(t)})}function GL(e,t){return new e({type:`string`,format:`guid`,check:`string_format`,abort:!1,...II(t)})}function Yye(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,...II(t)})}function Xye(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v4`,...II(t)})}function Zye(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v6`,...II(t)})}function Qye(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v7`,...II(t)})}function KL(e,t){return new e({type:`string`,format:`url`,check:`string_format`,abort:!1,...II(t)})}function $ye(e,t){return new e({type:`string`,format:`emoji`,check:`string_format`,abort:!1,...II(t)})}function ebe(e,t){return new e({type:`string`,format:`nanoid`,check:`string_format`,abort:!1,...II(t)})}function tbe(e,t){return new e({type:`string`,format:`cuid`,check:`string_format`,abort:!1,...II(t)})}function nbe(e,t){return new e({type:`string`,format:`cuid2`,check:`string_format`,abort:!1,...II(t)})}function rbe(e,t){return new e({type:`string`,format:`ulid`,check:`string_format`,abort:!1,...II(t)})}function ibe(e,t){return new e({type:`string`,format:`xid`,check:`string_format`,abort:!1,...II(t)})}function abe(e,t){return new e({type:`string`,format:`ksuid`,check:`string_format`,abort:!1,...II(t)})}function obe(e,t){return new e({type:`string`,format:`ipv4`,check:`string_format`,abort:!1,...II(t)})}function sbe(e,t){return new e({type:`string`,format:`ipv6`,check:`string_format`,abort:!1,...II(t)})}function cbe(e,t){return new e({type:`string`,format:`cidrv4`,check:`string_format`,abort:!1,...II(t)})}function lbe(e,t){return new e({type:`string`,format:`cidrv6`,check:`string_format`,abort:!1,...II(t)})}function ube(e,t){return new e({type:`string`,format:`base64`,check:`string_format`,abort:!1,...II(t)})}function dbe(e,t){return new e({type:`string`,format:`base64url`,check:`string_format`,abort:!1,...II(t)})}function fbe(e,t){return new e({type:`string`,format:`e164`,check:`string_format`,abort:!1,...II(t)})}function pbe(e,t){return new e({type:`string`,format:`jwt`,check:`string_format`,abort:!1,...II(t)})}function mbe(e,t){return new e({type:`string`,format:`datetime`,check:`string_format`,offset:!1,local:!1,precision:null,...II(t)})}function hbe(e,t){return new e({type:`string`,format:`date`,check:`string_format`,...II(t)})}function gbe(e,t){return new e({type:`string`,format:`time`,check:`string_format`,precision:null,...II(t)})}function _be(e,t){return new e({type:`string`,format:`duration`,check:`string_format`,...II(t)})}function vbe(e,t){return new e({type:`number`,checks:[],...II(t)})}function ybe(e,t){return new e({type:`number`,coerce:!0,checks:[],...II(t)})}function bbe(e,t){return new e({type:`number`,check:`number_format`,abort:!1,format:`safeint`,...II(t)})}function xbe(e,t){return new e({type:`boolean`,...II(t)})}function Sbe(e,t){return new e({type:`null`,...II(t)})}function Cbe(e){return new e({type:`any`})}function wbe(e){return new e({type:`unknown`})}function Tbe(e,t){return new e({type:`never`,...II(t)})}function qL(e,t){return new lL({check:`less_than`,...II(t),value:e,inclusive:!1})}function JL(e,t){return new lL({check:`less_than`,...II(t),value:e,inclusive:!0})}function YL(e,t){return new uL({check:`greater_than`,...II(t),value:e,inclusive:!1})}function XL(e,t){return new uL({check:`greater_than`,...II(t),value:e,inclusive:!0})}function ZL(e,t){return new fve({check:`multiple_of`,...II(t),value:e})}function QL(e,t){return new hve({check:`max_size`,...II(t),maximum:e})}function $L(e,t){return new gve({check:`min_size`,...II(t),minimum:e})}function eR(e,t){return new _ve({check:`size_equals`,...II(t),size:e})}function tR(e,t){return new vve({check:`max_length`,...II(t),maximum:e})}function nR(e,t){return new yve({check:`min_length`,...II(t),minimum:e})}function rR(e,t){return new bve({check:`length_equals`,...II(t),length:e})}function Ebe(e,t){return new xve({check:`string_format`,format:`regex`,...II(t),pattern:e})}function Dbe(e){return new Sve({check:`string_format`,format:`lowercase`,...II(e)})}function Obe(e){return new Cve({check:`string_format`,format:`uppercase`,...II(e)})}function kbe(e,t){return new wve({check:`string_format`,format:`includes`,...II(t),includes:e})}function Abe(e,t){return new Tve({check:`string_format`,format:`starts_with`,...II(t),prefix:e})}function jbe(e,t){return new Eve({check:`string_format`,format:`ends_with`,...II(t),suffix:e})}function Mbe(e,t){return new Dve({check:`mime_type`,mime:e,...II(t)})}function iR(e){return new Ove({check:`overwrite`,tx:e})}function Nbe(e){return iR(t=>t.normalize(e))}function Pbe(){return iR(e=>e.trim())}function Fbe(){return iR(e=>e.toLowerCase())}function Ibe(){return iR(e=>e.toUpperCase())}function Lbe(){return iR(e=>f_e(e))}function Rbe(e,t,n){return new e({type:`array`,element:t,...II(n)})}function zbe(e,t,n){let r=II(n);return r.abort??=!0,new e({type:`custom`,check:`custom`,fn:t,...r})}function Bbe(e,t,n){return new e({type:`custom`,check:`custom`,fn:t,...II(n)})}function Vbe(e,t){let n=Hbe(t=>(t.addIssue=e=>{if(typeof e==`string`)t.issues.push(UI(e,t.value,n._zod.def));else{let r=e;r.fatal&&(r.continue=!1),r.code??=`custom`,r.input??=t.value,r.inst??=n,r.continue??=!n._zod.def.abort,t.issues.push(UI(r))}},e(t.value,t)),t);return n}function Hbe(e,t){let n=new sL({check:`custom`,...II(t)});return n._zod.check=e,n}function aR(e){let t=e?.target??`draft-2020-12`;return t===`draft-4`&&(t=`draft-04`),t===`draft-7`&&(t=`draft-07`),{processors:e.processors??{},metadataRegistry:e?.metadata??WL,target:t,unrepresentable:e?.unrepresentable??`throw`,override:e?.override??(()=>{}),io:e?.io??`output`,counter:0,seen:new Map,cycles:e?.cycles??`ref`,reused:e?.reused??`inline`,external:e?.external??void 0}}function oR(e,t,n={path:[],schemaPath:[]}){var r;let i=e._zod.def,a=t.seen.get(e);if(a)return a.count++,n.schemaPath.includes(e)&&(a.cycle=n.path),a.schema;let o={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,o);let s=e._zod.toJSONSchema?.();if(s)o.schema=s;else{let r={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,o.schema,r);else{let n=o.schema,a=t.processors[i.type];if(!a)throw Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);a(e,t,n,r)}let a=e._zod.parent;a&&(o.ref||=a,oR(a,t,r),t.seen.get(a).isParent=!0)}let c=t.metadataRegistry.get(e);return c&&Object.assign(o.schema,c),t.io===`input`&&lR(e)&&(delete o.schema.examples,delete o.schema.default),t.io===`input`&&`_prefault`in o.schema&&((r=o.schema).default??(r.default=o.schema._prefault)),delete o.schema._prefault,t.seen.get(e).schema}function sR(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);let r=new Map;for(let t of e.seen.entries()){let n=e.metadataRegistry.get(t[0])?.id;if(n){let e=r.get(n);if(e&&e!==t[0])throw Error(`Duplicate schema id "${n}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(n,t[0])}}let i=t=>{let r=e.target===`draft-2020-12`?`$defs`:`definitions`;if(e.external){let n=e.external.registry.get(t[0])?.id,i=e.external.uri??(e=>e);if(n)return{ref:i(n)};let a=t[1].defId??t[1].schema.id??`schema${e.counter++}`;return t[1].defId=a,{defId:a,ref:`${i(`__shared`)}#/${r}/${a}`}}if(t[1]===n)return{ref:`#`};let i=`#/${r}/`,a=t[1].schema.id??`__schema${e.counter++}`;return{defId:a,ref:i+a}},a=e=>{if(e[1].schema.$ref)return;let t=e[1],{ref:n,defId:r}=i(e);t.def={...t.schema},r&&(t.defId=r);let a=t.schema;for(let e in a)delete a[e];a.$ref=n};if(e.cycles===`throw`)for(let t of e.seen.entries()){let e=t[1];if(e.cycle)throw Error(`Cycle detected: #/${e.cycle?.join(`/`)}/<root>
|
|
1898
1898
|
|
|
1899
|
-
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let n of e.seen.entries()){let r=n[1];if(t===n[0]){a(n);continue}if(e.external){let r=e.external.registry.get(n[0])?.id;if(t!==n[0]&&r){a(n);continue}}if(e.metadataRegistry.get(n[0])?.id){a(n);continue}if(r.cycle){a(n);continue}if(r.count>1&&e.reused===`ref`){a(n);continue}}}function cR(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);let r=t=>{let n=e.seen.get(t);if(n.ref===null)return;let i=n.def??n.schema,a={...i},o=n.ref;if(n.ref=null,o){r(o);let n=e.seen.get(o),s=n.schema;if(s.$ref&&(e.target===`draft-07`||e.target===`draft-04`||e.target===`openapi-3.0`)?(i.allOf=i.allOf??[],i.allOf.push(s)):Object.assign(i,s),Object.assign(i,a),t._zod.parent===o)for(let e in i)e===`$ref`||e===`allOf`||e in a||delete i[e];if(s.$ref&&n.def)for(let e in i)e===`$ref`||e===`allOf`||e in n.def&&JSON.stringify(i[e])===JSON.stringify(n.def[e])&&delete i[e]}let s=t._zod.parent;if(s&&s!==o){r(s);let t=e.seen.get(s);if(t?.schema.$ref&&(i.$ref=t.schema.$ref,t.def))for(let e in i)e===`$ref`||e===`allOf`||e in t.def&&JSON.stringify(i[e])===JSON.stringify(t.def[e])&&delete i[e]}e.override({zodSchema:t,jsonSchema:i,path:n.path??[]})};for(let t of[...e.seen.entries()].reverse())r(t[0]);let i={};if(e.target===`draft-2020-12`?i.$schema=`https://json-schema.org/draft/2020-12/schema`:e.target===`draft-07`?i.$schema=`http://json-schema.org/draft-07/schema#`:e.target===`draft-04`?i.$schema=`http://json-schema.org/draft-04/schema#`:e.target,e.external?.uri){let n=e.external.registry.get(t)?.id;if(!n)throw Error("Schema is missing an `id` property");i.$id=e.external.uri(n)}Object.assign(i,n.def??n.schema);let a=e.metadataRegistry.get(t)?.id;a!==void 0&&i.id===a&&delete i.id;let o=e.external?.defs??{};for(let t of e.seen.entries()){let e=t[1];e.def&&e.defId&&(e.def.id===e.defId&&delete e.def.id,o[e.defId]=e.def)}e.external||Object.keys(o).length>0&&(e.target===`draft-2020-12`?i.$defs=o:i.definitions=o);try{let n=JSON.parse(JSON.stringify(i));return Object.defineProperty(n,`~standard`,{value:{...t[`~standard`],jsonSchema:{input:uR(t,`input`,e.processors),output:uR(t,`output`,e.processors)}},enumerable:!1,writable:!1}),n}catch{throw Error(`Error converting schema to JSON.`)}}function lR(e,t){let n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);let r=e._zod.def;if(r.type===`transform`)return!0;if(r.type===`array`)return lR(r.element,n);if(r.type===`set`)return lR(r.valueType,n);if(r.type===`lazy`)return lR(r.getter(),n);if(r.type===`promise`||r.type===`optional`||r.type===`nonoptional`||r.type===`nullable`||r.type===`readonly`||r.type===`default`||r.type===`prefault`)return lR(r.innerType,n);if(r.type===`intersection`)return lR(r.left,n)||lR(r.right,n);if(r.type===`record`||r.type===`map`)return lR(r.keyType,n)||lR(r.valueType,n);if(r.type===`pipe`)return lR(r.in,n)||lR(r.out,n);if(r.type===`object`){for(let e in r.shape)if(lR(r.shape[e],n))return!0;return!1}if(r.type===`union`){for(let e of r.options)if(lR(e,n))return!0;return!1}if(r.type===`tuple`){for(let e of r.items)if(lR(e,n))return!0;return!!(r.rest&&lR(r.rest,n))}return!1}const Ube=(e,t={})=>n=>{let r=aR({...n,processors:t});return oR(e,r),sR(r,e),cR(r,e)},uR=(e,t,n={})=>r=>{let{libraryOptions:i,target:a}=r??{},o=aR({...i??{},target:a,io:t,processors:n});return oR(e,o),sR(o,e),cR(o,e)},Wbe={guid:`uuid`,url:`uri`,datetime:`date-time`,json_string:`json-string`,regex:``},Gbe=(e,t,n,r)=>{let i=n;i.type=`string`;let{minimum:a,maximum:o,format:s,patterns:c,contentEncoding:l}=e._zod.bag;if(typeof a==`number`&&(i.minLength=a),typeof o==`number`&&(i.maxLength=o),s&&(i.format=Wbe[s]??s,i.format===``&&delete i.format,s===`time`&&delete i.format),l&&(i.contentEncoding=l),c&&c.size>0){let e=[...c];e.length===1?i.pattern=e[0].source:e.length>1&&(i.allOf=[...e.map(e=>({...t.target===`draft-07`||t.target===`draft-04`||t.target===`openapi-3.0`?{type:`string`}:{},pattern:e.source}))])}},Kbe=(e,t,n,r)=>{let i=n,{minimum:a,maximum:o,format:s,multipleOf:c,exclusiveMaximum:l,exclusiveMinimum:u}=e._zod.bag;typeof s==`string`&&s.includes(`int`)?i.type=`integer`:i.type=`number`;let d=typeof u==`number`&&u>=(a??-1/0),f=typeof l==`number`&&l<=(o??1/0),p=t.target===`draft-04`||t.target===`openapi-3.0`;d?p?(i.minimum=u,i.exclusiveMinimum=!0):i.exclusiveMinimum=u:typeof a==`number`&&(i.minimum=a),f?p?(i.maximum=l,i.exclusiveMaximum=!0):i.exclusiveMaximum=l:typeof o==`number`&&(i.maximum=o),typeof c==`number`&&(i.multipleOf=c)},qbe=(e,t,n,r)=>{n.type=`boolean`},Jbe=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`BigInt cannot be represented in JSON Schema`)},Ybe=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Symbols cannot be represented in JSON Schema`)},Xbe=(e,t,n,r)=>{t.target===`openapi-3.0`?(n.type=`string`,n.nullable=!0,n.enum=[null]):n.type=`null`},Zbe=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Undefined cannot be represented in JSON Schema`)},Qbe=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Void cannot be represented in JSON Schema`)},$be=(e,t,n,r)=>{n.not={}},exe=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Date cannot be represented in JSON Schema`)},txe=(e,t,n,r)=>{let i=e._zod.def,a=c_e(i.entries);a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),n.enum=a},nxe=(e,t,n,r)=>{let i=e._zod.def,a=[];for(let e of i.values)if(e===void 0){if(t.unrepresentable===`throw`)throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof e==`bigint`){if(t.unrepresentable===`throw`)throw Error(`BigInt literals cannot be represented in JSON Schema`);a.push(Number(e))}else a.push(e);if(a.length!==0)if(a.length===1){let e=a[0];n.type=e===null?`null`:typeof e,t.target===`draft-04`||t.target===`openapi-3.0`?n.enum=[e]:n.const=e}else a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),a.every(e=>typeof e==`boolean`)&&(n.type=`boolean`),a.every(e=>e===null)&&(n.type=`null`),n.enum=a},rxe=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`NaN cannot be represented in JSON Schema`)},ixe=(e,t,n,r)=>{let i=n,a=e._zod.pattern;if(!a)throw Error(`Pattern not found in template literal`);i.type=`string`,i.pattern=a.source},axe=(e,t,n,r)=>{let i=n,a={type:`string`,format:`binary`,contentEncoding:`binary`},{minimum:o,maximum:s,mime:c}=e._zod.bag;o!==void 0&&(a.minLength=o),s!==void 0&&(a.maxLength=s),c?c.length===1?(a.contentMediaType=c[0],Object.assign(i,a)):(Object.assign(i,a),i.anyOf=c.map(e=>({contentMediaType:e}))):Object.assign(i,a)},oxe=(e,t,n,r)=>{n.type=`boolean`},sxe=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Custom types cannot be represented in JSON Schema`)},cxe=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Function types cannot be represented in JSON Schema`)},lxe=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Transforms cannot be represented in JSON Schema`)},uxe=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Map cannot be represented in JSON Schema`)},dxe=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Set cannot be represented in JSON Schema`)},fxe=(e,t,n,r)=>{let i=n,a=e._zod.def,{minimum:o,maximum:s}=e._zod.bag;typeof o==`number`&&(i.minItems=o),typeof s==`number`&&(i.maxItems=s),i.type=`array`,i.items=oR(a.element,t,{...r,path:[...r.path,`items`]})},pxe=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`,i.properties={};let o=a.shape;for(let e in o)i.properties[e]=oR(o[e],t,{...r,path:[...r.path,`properties`,e]});let s=new Set(Object.keys(o)),c=new Set([...s].filter(e=>{let n=a.shape[e]._zod;return t.io===`input`?n.optin===void 0:n.optout===void 0}));c.size>0&&(i.required=Array.from(c)),a.catchall?._zod.def.type===`never`?i.additionalProperties=!1:a.catchall?a.catchall&&(i.additionalProperties=oR(a.catchall,t,{...r,path:[...r.path,`additionalProperties`]})):t.io===`output`&&(i.additionalProperties=!1)},dR=(e,t,n,r)=>{let i=e._zod.def,a=i.inclusive===!1,o=i.options.map((e,n)=>oR(e,t,{...r,path:[...r.path,a?`oneOf`:`anyOf`,n]}));a?n.oneOf=o:n.anyOf=o},mxe=(e,t,n,r)=>{let i=e._zod.def,a=oR(i.left,t,{...r,path:[...r.path,`allOf`,0]}),o=oR(i.right,t,{...r,path:[...r.path,`allOf`,1]}),s=e=>`allOf`in e&&Object.keys(e).length===1;n.allOf=[...s(a)?a.allOf:[a],...s(o)?o.allOf:[o]]},hxe=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`array`;let o=t.target===`draft-2020-12`?`prefixItems`:`items`,s=t.target===`draft-2020-12`||t.target===`openapi-3.0`?`items`:`additionalItems`,c=a.items.map((e,n)=>oR(e,t,{...r,path:[...r.path,o,n]})),l=a.rest?oR(a.rest,t,{...r,path:[...r.path,s,...t.target===`openapi-3.0`?[a.items.length]:[]]}):null;t.target===`draft-2020-12`?(i.prefixItems=c,l&&(i.items=l)):t.target===`openapi-3.0`?(i.items={anyOf:c},l&&i.items.anyOf.push(l),i.minItems=c.length,l||(i.maxItems=c.length)):(i.items=c,l&&(i.additionalItems=l));let{minimum:u,maximum:d}=e._zod.bag;typeof u==`number`&&(i.minItems=u),typeof d==`number`&&(i.maxItems=d)},gxe=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`;let o=a.keyType,s=o._zod.bag?.patterns;if(a.mode===`loose`&&s&&s.size>0){let e=oR(a.valueType,t,{...r,path:[...r.path,`patternProperties`,`*`]});i.patternProperties={};for(let t of s)i.patternProperties[t.source]=e}else (t.target===`draft-07`||t.target===`draft-2020-12`)&&(i.propertyNames=oR(a.keyType,t,{...r,path:[...r.path,`propertyNames`]})),i.additionalProperties=oR(a.valueType,t,{...r,path:[...r.path,`additionalProperties`]});let c=o._zod.values;if(c){let e=[...c].filter(e=>typeof e==`string`||typeof e==`number`);e.length>0&&(i.required=e)}},_xe=(e,t,n,r)=>{let i=e._zod.def,a=oR(i.innerType,t,r),o=t.seen.get(e);t.target===`openapi-3.0`?(o.ref=i.innerType,n.nullable=!0):n.anyOf=[a,{type:`null`}]},vxe=(e,t,n,r)=>{let i=e._zod.def;oR(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},yxe=(e,t,n,r)=>{let i=e._zod.def;oR(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.default=JSON.parse(JSON.stringify(i.defaultValue))},bxe=(e,t,n,r)=>{let i=e._zod.def;oR(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,t.io===`input`&&(n._prefault=JSON.parse(JSON.stringify(i.defaultValue)))},xxe=(e,t,n,r)=>{let i=e._zod.def;oR(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o;try{o=i.catchValue(void 0)}catch{throw Error(`Dynamic catch values are not supported in JSON Schema`)}n.default=o},Sxe=(e,t,n,r)=>{let i=e._zod.def,a=t.io===`input`?i.in._zod.def.type===`transform`?i.out:i.in:i.out;oR(a,t,r);let o=t.seen.get(e);o.ref=a},Cxe=(e,t,n,r)=>{let i=e._zod.def;oR(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.readOnly=!0},wxe=(e,t,n,r)=>{let i=e._zod.def;oR(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},fR=(e,t,n,r)=>{let i=e._zod.def;oR(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},Txe=(e,t,n,r)=>{let i=e._zod.innerType;oR(i,t,r);let a=t.seen.get(e);a.ref=i},Exe=_I(`ZodISODateTime`,(e,t)=>{Hve.init(e,t),xR.init(e,t)});function pR(e){return mbe(Exe,e)}const Dxe=_I(`ZodISODate`,(e,t)=>{Uve.init(e,t),xR.init(e,t)});function Oxe(e){return hbe(Dxe,e)}const kxe=_I(`ZodISOTime`,(e,t)=>{Wve.init(e,t),xR.init(e,t)});function Axe(e){return gbe(kxe,e)}const jxe=_I(`ZodISODuration`,(e,t)=>{Gve.init(e,t),xR.init(e,t)});function Mxe(e){return _be(jxe,e)}const mR=(e,t)=>{GI.init(e,t),e.name=`ZodError`,Object.defineProperties(e,{format:{value:t=>D_e(e,t)},flatten:{value:t=>E_e(e,t)},addIssue:{value:t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,SI,2)}},addIssues:{value:t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,SI,2)}},isEmpty:{get(){return e.issues.length===0}}})};_I(`ZodError`,mR);const hR=_I(`ZodError`,mR,{Parent:Error}),Nxe=qI(hR),Pxe=YI(hR),Fxe=ZI(hR),Ixe=$I(hR),Lxe=k_e(hR),Rxe=A_e(hR),zxe=j_e(hR),Bxe=M_e(hR),Vxe=N_e(hR),Hxe=P_e(hR),Uxe=F_e(hR),Wxe=I_e(hR),gR=new WeakMap;function _R(e,t,n){let r=Object.getPrototypeOf(e),i=gR.get(r);if(i||(i=new Set,gR.set(r,i)),!i.has(t)){i.add(t);for(let e in n){let t=n[e];Object.defineProperty(r,e,{configurable:!0,enumerable:!1,get(){let n=t.bind(this);return Object.defineProperty(this,e,{configurable:!0,writable:!0,enumerable:!0,value:n}),n},set(t){Object.defineProperty(this,e,{configurable:!0,writable:!0,enumerable:!0,value:t})}})}}}const vR=_I(`ZodType`,(e,t)=>(pL.init(e,t),Object.assign(e[`~standard`],{jsonSchema:{input:uR(e,`input`),output:uR(e,`output`)}}),e.toJSONSchema=Ube(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,`_def`,{value:t}),e.parse=(t,n)=>Nxe(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>Fxe(e,t,n),e.parseAsync=async(t,n)=>Pxe(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>Ixe(e,t,n),e.spa=e.safeParseAsync,e.encode=(t,n)=>Lxe(e,t,n),e.decode=(t,n)=>Rxe(e,t,n),e.encodeAsync=async(t,n)=>zxe(e,t,n),e.decodeAsync=async(t,n)=>Bxe(e,t,n),e.safeEncode=(t,n)=>Vxe(e,t,n),e.safeDecode=(t,n)=>Hxe(e,t,n),e.safeEncodeAsync=async(t,n)=>Uxe(e,t,n),e.safeDecodeAsync=async(t,n)=>Wxe(e,t,n),_R(e,`ZodType`,{check(...e){let t=this.def;return this.clone(OI(t,{checks:[...t.checks??[],...e.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return FI(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(FSe(e,t))},superRefine(e,t){return this.check(ISe(e,t))},overwrite(e){return this.check(iR(e))},optional(){return JR(this)},exactOptional(){return CSe(this)},nullable(){return YR(this)},nullish(){return JR(YR(this))},nonoptional(e){return kSe(this,e)},array(){return MR(this)},or(e){return LR([this,e])},and(e){return zR(this,e)},transform(e){return QR(this,KR(e))},default(e){return ESe(this,e)},prefault(e){return OSe(this,e)},catch(e){return jSe(this,e)},pipe(e){return QR(this,e)},readonly(){return NSe(this)},describe(e){let t=this.clone();return WL.add(t,{description:e}),t},meta(...e){if(e.length===0)return WL.get(this);let t=this.clone();return WL.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e){return e(this)}}),Object.defineProperty(e,`description`,{get(){return WL.get(e)?.description},configurable:!0}),e)),yR=_I(`_ZodString`,(e,t)=>{mL.init(e,t),vR.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Gbe(e,t,n,r);let n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,_R(e,`_ZodString`,{regex(...e){return this.check(Ebe(...e))},includes(...e){return this.check(kbe(...e))},startsWith(...e){return this.check(Abe(...e))},endsWith(...e){return this.check(jbe(...e))},min(...e){return this.check(nR(...e))},max(...e){return this.check(tR(...e))},length(...e){return this.check(rR(...e))},nonempty(...e){return this.check(nR(1,...e))},lowercase(e){return this.check(Dbe(e))},uppercase(e){return this.check(Obe(e))},trim(){return this.check(Pbe())},normalize(...e){return this.check(Nbe(...e))},toLowerCase(){return this.check(Fbe())},toUpperCase(){return this.check(Ibe())},slugify(){return this.check(Lbe())}})}),bR=_I(`ZodString`,(e,t)=>{mL.init(e,t),yR.init(e,t),e.email=t=>e.check(Jye(Gxe,t)),e.url=t=>e.check(KL(wR,t)),e.jwt=t=>e.check(pbe(sSe,t)),e.emoji=t=>e.check($ye(qxe,t)),e.guid=t=>e.check(GL(SR,t)),e.uuid=t=>e.check(Yye(CR,t)),e.uuidv4=t=>e.check(Xye(CR,t)),e.uuidv6=t=>e.check(Zye(CR,t)),e.uuidv7=t=>e.check(Qye(CR,t)),e.nanoid=t=>e.check(ebe(Jxe,t)),e.guid=t=>e.check(GL(SR,t)),e.cuid=t=>e.check(tbe(Yxe,t)),e.cuid2=t=>e.check(nbe(Xxe,t)),e.ulid=t=>e.check(rbe(Zxe,t)),e.base64=t=>e.check(ube(iSe,t)),e.base64url=t=>e.check(dbe(aSe,t)),e.xid=t=>e.check(ibe(Qxe,t)),e.ksuid=t=>e.check(abe($xe,t)),e.ipv4=t=>e.check(obe(eSe,t)),e.ipv6=t=>e.check(sbe(tSe,t)),e.cidrv4=t=>e.check(cbe(nSe,t)),e.cidrv6=t=>e.check(lbe(rSe,t)),e.e164=t=>e.check(fbe(oSe,t)),e.datetime=t=>e.check(pR(t)),e.date=t=>e.check(Oxe(t)),e.time=t=>e.check(Axe(t)),e.duration=t=>e.check(Mxe(t))});function Y(e){return Kye(bR,e)}const xR=_I(`ZodStringFormat`,(e,t)=>{hL.init(e,t),yR.init(e,t)}),Gxe=_I(`ZodEmail`,(e,t)=>{Nve.init(e,t),xR.init(e,t)}),SR=_I(`ZodGUID`,(e,t)=>{jve.init(e,t),xR.init(e,t)}),CR=_I(`ZodUUID`,(e,t)=>{Mve.init(e,t),xR.init(e,t)}),wR=_I(`ZodURL`,(e,t)=>{Pve.init(e,t),xR.init(e,t)});function Kxe(e){return KL(wR,e)}const qxe=_I(`ZodEmoji`,(e,t)=>{Fve.init(e,t),xR.init(e,t)}),Jxe=_I(`ZodNanoID`,(e,t)=>{Ive.init(e,t),xR.init(e,t)}),Yxe=_I(`ZodCUID`,(e,t)=>{Lve.init(e,t),xR.init(e,t)}),Xxe=_I(`ZodCUID2`,(e,t)=>{Rve.init(e,t),xR.init(e,t)}),Zxe=_I(`ZodULID`,(e,t)=>{zve.init(e,t),xR.init(e,t)}),Qxe=_I(`ZodXID`,(e,t)=>{Bve.init(e,t),xR.init(e,t)}),$xe=_I(`ZodKSUID`,(e,t)=>{Vve.init(e,t),xR.init(e,t)}),eSe=_I(`ZodIPv4`,(e,t)=>{Kve.init(e,t),xR.init(e,t)});_I(`ZodMAC`,(e,t)=>{Jve.init(e,t),xR.init(e,t)});const tSe=_I(`ZodIPv6`,(e,t)=>{qve.init(e,t),xR.init(e,t)}),nSe=_I(`ZodCIDRv4`,(e,t)=>{Yve.init(e,t),xR.init(e,t)}),rSe=_I(`ZodCIDRv6`,(e,t)=>{Xve.init(e,t),xR.init(e,t)}),iSe=_I(`ZodBase64`,(e,t)=>{Zve.init(e,t),xR.init(e,t)}),aSe=_I(`ZodBase64URL`,(e,t)=>{$ve.init(e,t),xR.init(e,t)}),oSe=_I(`ZodE164`,(e,t)=>{eye.init(e,t),xR.init(e,t)}),sSe=_I(`ZodJWT`,(e,t)=>{nye.init(e,t),xR.init(e,t)});_I(`ZodCustomStringFormat`,(e,t)=>{rye.init(e,t),xR.init(e,t)});const TR=_I(`ZodNumber`,(e,t)=>{_L.init(e,t),vR.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Kbe(e,t,n,r),_R(e,`ZodNumber`,{gt(e,t){return this.check(YL(e,t))},gte(e,t){return this.check(XL(e,t))},min(e,t){return this.check(XL(e,t))},lt(e,t){return this.check(qL(e,t))},lte(e,t){return this.check(JL(e,t))},max(e,t){return this.check(JL(e,t))},int(e){return this.check(DR(e))},safe(e){return this.check(DR(e))},positive(e){return this.check(YL(0,e))},nonnegative(e){return this.check(XL(0,e))},negative(e){return this.check(qL(0,e))},nonpositive(e){return this.check(JL(0,e))},multipleOf(e,t){return this.check(ZL(e,t))},step(e,t){return this.check(ZL(e,t))},finite(){return this}});let n=e._zod.bag;e.minValue=Math.max(n.minimum??-1/0,n.exclusiveMinimum??-1/0)??null,e.maxValue=Math.min(n.maximum??1/0,n.exclusiveMaximum??1/0)??null,e.isInt=(n.format??``).includes(`int`)||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null});function ER(e){return vbe(TR,e)}const cSe=_I(`ZodNumberFormat`,(e,t)=>{iye.init(e,t),TR.init(e,t)});function DR(e){return bbe(cSe,e)}const lSe=_I(`ZodBoolean`,(e,t)=>{aye.init(e,t),vR.init(e,t),e._zod.processJSONSchema=(t,n,r)=>qbe(e,t,n,r)});function OR(e){return xbe(lSe,e)}const uSe=_I(`ZodBigInt`,(e,t)=>{vL.init(e,t),vR.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Jbe(e,t,n,r),e.gte=(t,n)=>e.check(XL(t,n)),e.min=(t,n)=>e.check(XL(t,n)),e.gt=(t,n)=>e.check(YL(t,n)),e.gte=(t,n)=>e.check(XL(t,n)),e.min=(t,n)=>e.check(XL(t,n)),e.lt=(t,n)=>e.check(qL(t,n)),e.lte=(t,n)=>e.check(JL(t,n)),e.max=(t,n)=>e.check(JL(t,n)),e.positive=t=>e.check(YL(BigInt(0),t)),e.negative=t=>e.check(qL(BigInt(0),t)),e.nonpositive=t=>e.check(JL(BigInt(0),t)),e.nonnegative=t=>e.check(XL(BigInt(0),t)),e.multipleOf=(t,n)=>e.check(ZL(t,n));let n=e._zod.bag;e.minValue=n.minimum??null,e.maxValue=n.maximum??null,e.format=n.format??null});_I(`ZodBigIntFormat`,(e,t)=>{oye.init(e,t),uSe.init(e,t)}),_I(`ZodSymbol`,(e,t)=>{sye.init(e,t),vR.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ybe(e,t,n,r)}),_I(`ZodUndefined`,(e,t)=>{cye.init(e,t),vR.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Zbe(e,t,n,r)});const dSe=_I(`ZodNull`,(e,t)=>{lye.init(e,t),vR.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Xbe(e,t,n,r)});function kR(e){return Sbe(dSe,e)}const fSe=_I(`ZodAny`,(e,t)=>{uye.init(e,t),vR.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function AR(){return Cbe(fSe)}const pSe=_I(`ZodUnknown`,(e,t)=>{dye.init(e,t),vR.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function jR(){return wbe(pSe)}const mSe=_I(`ZodNever`,(e,t)=>{fye.init(e,t),vR.init(e,t),e._zod.processJSONSchema=(t,n,r)=>$be(e,t,n,r)});function hSe(e){return Tbe(mSe,e)}_I(`ZodVoid`,(e,t)=>{pye.init(e,t),vR.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Qbe(e,t,n,r)}),_I(`ZodDate`,(e,t)=>{mye.init(e,t),vR.init(e,t),e._zod.processJSONSchema=(t,n,r)=>exe(e,t,n,r),e.min=(t,n)=>e.check(XL(t,n)),e.max=(t,n)=>e.check(JL(t,n));let n=e._zod.bag;e.minDate=n.minimum?new Date(n.minimum):null,e.maxDate=n.maximum?new Date(n.maximum):null});const gSe=_I(`ZodArray`,(e,t)=>{hye.init(e,t),vR.init(e,t),e._zod.processJSONSchema=(t,n,r)=>fxe(e,t,n,r),e.element=t.element,_R(e,`ZodArray`,{min(e,t){return this.check(nR(e,t))},nonempty(e){return this.check(nR(1,e))},max(e,t){return this.check(tR(e,t))},length(e,t){return this.check(rR(e,t))},unwrap(){return this.element}})});function MR(e,t){return Rbe(gSe,e,t)}const NR=_I(`ZodObject`,(e,t)=>{_ye.init(e,t),vR.init(e,t),e._zod.processJSONSchema=(t,n,r)=>pxe(e,t,n,r),EI(e,`shape`,()=>t.shape),_R(e,`ZodObject`,{keyof(){return WR(Object.keys(this._zod.def.shape))},catchall(e){return this.clone({...this._zod.def,catchall:e})},passthrough(){return this.clone({...this._zod.def,catchall:jR()})},loose(){return this.clone({...this._zod.def,catchall:jR()})},strict(){return this.clone({...this._zod.def,catchall:hSe()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(e){return b_e(this,e)},safeExtend(e){return x_e(this,e)},merge(e){return S_e(this,e)},pick(e){return v_e(this,e)},omit(e){return y_e(this,e)},partial(...e){return C_e(qR,this,e[0])},required(...e){return w_e(XR,this,e[0])}})});function PR(e,t){return new NR({type:`object`,shape:e??{},...II(t)})}function FR(e,t){return new NR({type:`object`,shape:e,catchall:jR(),...II(t)})}const IR=_I(`ZodUnion`,(e,t)=>{wL.init(e,t),vR.init(e,t),e._zod.processJSONSchema=(t,n,r)=>dR(e,t,n,r),e.options=t.options});function LR(e,t){return new IR({type:`union`,options:e,...II(t)})}_I(`ZodXor`,(e,t)=>{IR.init(e,t),vye.init(e,t),e._zod.processJSONSchema=(t,n,r)=>dR(e,t,n,r),e.options=t.options});const _Se=_I(`ZodDiscriminatedUnion`,(e,t)=>{IR.init(e,t),yye.init(e,t)});function RR(e,t,n){return new _Se({type:`union`,options:t,discriminator:e,...II(n)})}const vSe=_I(`ZodIntersection`,(e,t)=>{bye.init(e,t),vR.init(e,t),e._zod.processJSONSchema=(t,n,r)=>mxe(e,t,n,r)});function zR(e,t){return new vSe({type:`intersection`,left:e,right:t})}const ySe=_I(`ZodTuple`,(e,t)=>{OL.init(e,t),vR.init(e,t),e._zod.processJSONSchema=(t,n,r)=>hxe(e,t,n,r),e.rest=t=>e.clone({...e._zod.def,rest:t})});function BR(e,t,n){let r=t instanceof pL;return new ySe({type:`tuple`,items:e,rest:r?t:null,...II(r?n:t)})}const VR=_I(`ZodRecord`,(e,t)=>{xye.init(e,t),vR.init(e,t),e._zod.processJSONSchema=(t,n,r)=>gxe(e,t,n,r),e.keyType=t.keyType,e.valueType=t.valueType});function HR(e,t,n){return!t||!t._zod?new VR({type:`record`,keyType:Y(),valueType:e,...II(t)}):new VR({type:`record`,keyType:e,valueType:t,...II(n)})}_I(`ZodMap`,(e,t)=>{Sye.init(e,t),vR.init(e,t),e._zod.processJSONSchema=(t,n,r)=>uxe(e,t,n,r),e.keyType=t.keyType,e.valueType=t.valueType,e.min=(...t)=>e.check($L(...t)),e.nonempty=t=>e.check($L(1,t)),e.max=(...t)=>e.check(QL(...t)),e.size=(...t)=>e.check(eR(...t))}),_I(`ZodSet`,(e,t)=>{Cye.init(e,t),vR.init(e,t),e._zod.processJSONSchema=(t,n,r)=>dxe(e,t,n,r),e.min=(...t)=>e.check($L(...t)),e.nonempty=t=>e.check($L(1,t)),e.max=(...t)=>e.check(QL(...t)),e.size=(...t)=>e.check(eR(...t))});const UR=_I(`ZodEnum`,(e,t)=>{wye.init(e,t),vR.init(e,t),e._zod.processJSONSchema=(t,n,r)=>txe(e,t,n,r),e.enum=t.entries,e.options=Object.values(t.entries);let n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{let i={};for(let r of e)if(n.has(r))i[r]=t.entries[r];else throw Error(`Key ${r} not found in enum`);return new UR({...t,checks:[],...II(r),entries:i})},e.exclude=(e,r)=>{let i={...t.entries};for(let t of e)if(n.has(t))delete i[t];else throw Error(`Key ${t} not found in enum`);return new UR({...t,checks:[],...II(r),entries:i})}});function WR(e,t){return new UR({type:`enum`,entries:Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e,...II(t)})}const bSe=_I(`ZodLiteral`,(e,t)=>{Tye.init(e,t),vR.init(e,t),e._zod.processJSONSchema=(t,n,r)=>nxe(e,t,n,r),e.values=new Set(t.values),Object.defineProperty(e,`value`,{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function GR(e,t){return new bSe({type:`literal`,values:Array.isArray(e)?e:[e],...II(t)})}_I(`ZodFile`,(e,t)=>{Eye.init(e,t),vR.init(e,t),e._zod.processJSONSchema=(t,n,r)=>axe(e,t,n,r),e.min=(t,n)=>e.check($L(t,n)),e.max=(t,n)=>e.check(QL(t,n)),e.mime=(t,n)=>e.check(Mbe(Array.isArray(t)?t:[t],n))});const xSe=_I(`ZodTransform`,(e,t)=>{Dye.init(e,t),vR.init(e,t),e._zod.processJSONSchema=(t,n,r)=>lxe(e,t,n,r),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new yI(e.constructor.name);n.addIssue=r=>{if(typeof r==`string`)n.issues.push(UI(r,n.value,t));else{let t=r;t.fatal&&(t.continue=!1),t.code??=`custom`,t.input??=n.value,t.inst??=e,n.issues.push(UI(t))}};let i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n)):(n.value=i,n)}});function KR(e){return new xSe({type:`transform`,transform:e})}const qR=_I(`ZodOptional`,(e,t)=>{FL.init(e,t),vR.init(e,t),e._zod.processJSONSchema=(t,n,r)=>fR(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function JR(e){return new qR({type:`optional`,innerType:e})}const SSe=_I(`ZodExactOptional`,(e,t)=>{Oye.init(e,t),vR.init(e,t),e._zod.processJSONSchema=(t,n,r)=>fR(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function CSe(e){return new SSe({type:`optional`,innerType:e})}const wSe=_I(`ZodNullable`,(e,t)=>{kye.init(e,t),vR.init(e,t),e._zod.processJSONSchema=(t,n,r)=>_xe(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function YR(e){return new wSe({type:`nullable`,innerType:e})}const TSe=_I(`ZodDefault`,(e,t)=>{Aye.init(e,t),vR.init(e,t),e._zod.processJSONSchema=(t,n,r)=>yxe(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function ESe(e,t){return new TSe({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():MI(t)}})}const DSe=_I(`ZodPrefault`,(e,t)=>{jye.init(e,t),vR.init(e,t),e._zod.processJSONSchema=(t,n,r)=>bxe(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function OSe(e,t){return new DSe({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():MI(t)}})}const XR=_I(`ZodNonOptional`,(e,t)=>{Mye.init(e,t),vR.init(e,t),e._zod.processJSONSchema=(t,n,r)=>vxe(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function kSe(e,t){return new XR({type:`nonoptional`,innerType:e,...II(t)})}_I(`ZodSuccess`,(e,t)=>{Nye.init(e,t),vR.init(e,t),e._zod.processJSONSchema=(t,n,r)=>oxe(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});const ASe=_I(`ZodCatch`,(e,t)=>{Pye.init(e,t),vR.init(e,t),e._zod.processJSONSchema=(t,n,r)=>xxe(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function jSe(e,t){return new ASe({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:()=>t})}_I(`ZodNaN`,(e,t)=>{Fye.init(e,t),vR.init(e,t),e._zod.processJSONSchema=(t,n,r)=>rxe(e,t,n,r)});const ZR=_I(`ZodPipe`,(e,t)=>{Iye.init(e,t),vR.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Sxe(e,t,n,r),e.in=t.in,e.out=t.out});function QR(e,t){return new ZR({type:`pipe`,in:e,out:t})}_I(`ZodCodec`,(e,t)=>{ZR.init(e,t),Lye.init(e,t)});const MSe=_I(`ZodReadonly`,(e,t)=>{Rye.init(e,t),vR.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Cxe(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function NSe(e){return new MSe({type:`readonly`,innerType:e})}_I(`ZodTemplateLiteral`,(e,t)=>{zye.init(e,t),vR.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ixe(e,t,n,r)}),_I(`ZodLazy`,(e,t)=>{Hye.init(e,t),vR.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Txe(e,t,n,r),e.unwrap=()=>e._zod.def.getter()}),_I(`ZodPromise`,(e,t)=>{Vye.init(e,t),vR.init(e,t),e._zod.processJSONSchema=(t,n,r)=>wxe(e,t,n,r),e.unwrap=()=>e._zod.def.innerType}),_I(`ZodFunction`,(e,t)=>{Bye.init(e,t),vR.init(e,t),e._zod.processJSONSchema=(t,n,r)=>cxe(e,t,n,r)});const $R=_I(`ZodCustom`,(e,t)=>{Uye.init(e,t),vR.init(e,t),e._zod.processJSONSchema=(t,n,r)=>sxe(e,t,n,r)});function PSe(e,t){return zbe($R,e??(()=>!0),t)}function FSe(e,t={}){return Bbe($R,e,t)}function ISe(e,t){return Vbe(e,t)}function ez(e,t){return QR(KR(e),t)}const LSe={invalid_type:`invalid_type`,too_big:`too_big`,too_small:`too_small`,invalid_format:`invalid_format`,not_multiple_of:`not_multiple_of`,unrecognized_keys:`unrecognized_keys`,invalid_union:`invalid_union`,invalid_key:`invalid_key`,invalid_element:`invalid_element`,invalid_value:`invalid_value`,custom:`custom`};var RSe;(function(e){})(RSe||={});function tz(e){return qye(bR,e)}function nz(e){return ybe(TR,e)}const rz={USER_MESSAGE:`user_message`,REJECTED:`rejected`,INTERRUPTED:`interrupted`},zSe={REJECTED:`rejected`};function iz(e){if(e===`Tool was rejected by user`)return{rejected:!0};try{let t=JSON.parse(e);if(t.reason===rz.USER_MESSAGE)return{rejected:!0,userNote:t.message};if(t.reason===rz.REJECTED||t.reason===rz.INTERRUPTED)return{rejected:!0};if(t.status===zSe.REJECTED)return{rejected:!0,userNote:t.userNote}}catch{}return{rejected:!1}}const az=`sibling_tool_failed`,oz=JSON.stringify({type:az,message:`Not executed: a tool call in a preceding parallel batch failed`});function BSe(e){try{return JSON.parse(e)?.type===az}catch{return!1}}var sz=class{concurrency(e,t){return!1}includeInApiDefinitions=!0;isEnabled(e){return!0}async prepare(e,t){return null}needsPermission(e,t,n){return!this.isReadonly}timeout(e,t){return 12e4}async onTimeout(e,t,n){throw Error(`${this.displayName} tool timed out after ${n}ms`)}format(e,t){return typeof e==`string`?e:JSON.stringify(e)}formatForLLM(e,t){return this.format(e,t)}parse(e){let t=iz(e);if(t.rejected)return{phase:`rejected`,toolType:this.name,data:{},summary:t.userNote?`Rejected \u00b7 "${t.userNote}"`:`Rejected`,...t.userNote!==void 0&&{userNote:t.userNote}};try{let t=JSON.parse(e),n=`success`;return t.status===`error`?n=`error`:t.status===`skipped`&&(n=`skipped`),{phase:n,toolType:t.type??this.name,data:t,summary:t.message??t.summary??`Completed`,...t.errorMessage!==void 0&&{errorMessage:t.errorMessage}}}catch{}return e.startsWith(`Error:`)?{phase:`error`,toolType:this.name,data:{},summary:e,errorMessage:e}:{phase:`success`,toolType:this.name,data:{},summary:`Completed`}}validateParams(e){return this.parameters.parse(e)}getToolDefinition(){let e=this.getParameterNames();return{name:this.name,description:this.description,arguments:e}}getParameterNames(){return Object.keys(this.parameters.shape)}};const VSe=Symbol.for(`server-executed`);var cz=class extends sz{isReadonly=!0;async execute(e,t,n){return VSe}format(e,t){return JSON.stringify({type:this.name,status:`server-executed`})}};ft([`codellm`,`agent`,`tools`,`subagent`]);var lz=class e extends cz{name=`subagent`;displayName=`Subagent`;description=`Switch to a different subagent for a task`;static parametersSchema=PR({agent:Y().describe(`The name of the subagent to switch to`),task:Y().describe(`The task description for the subagent`)});parameters=e.parametersSchema;needsPermission(){return!1}timeout(){return 6e5}format(e,t){return JSON.stringify({type:`subagent`,status:`success`,agent:t.agent,task:t.task})}parse(e){let t=iz(e);if(t.rejected)return{phase:`rejected`,toolType:`subagent`,data:{},summary:t.userNote?`Rejected \u00b7 "${t.userNote}"`:`Rejected`,...t.userNote!==void 0&&{userNote:t.userNote}};try{let t=JSON.parse(e);return{phase:`success`,toolType:`subagent`,data:t,summary:`Delegated to ${t.agent??`explore`} agent`}}catch{}return{phase:`success`,toolType:`subagent`,data:{},summary:`Delegated`}}};ft([`codellm`,`agent`,`tools`,`todo-write`]);var uz=class e extends cz{name=`todo_write`;displayName=`TodoWrite`;description=`Create and manage a structured task list`;static parametersSchema=PR({todos:ez(e=>{if(e==null)return[];if(typeof e==`string`)try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}return Array.isArray(e)?e:[]},MR(PR({content:Y().describe(`The task content`),status:WR([`pending`,`in_progress`,`completed`,`cancelled`]).describe(`The status of the task`),id:Y().optional().describe(`Optional task ID`)}))).describe(`Array of todo items`)});parameters=e.parametersSchema;needsPermission(){return!1}format(e,t){return`Updated`}parse(e){let t=iz(e);if(t.rejected)return{phase:`rejected`,toolType:`todo_write`,data:{},summary:`Rejected`,...t.userNote!==void 0&&{userNote:t.userNote}};try{let t=JSON.parse(e);if(t.todos){let e=t.todos;return{phase:`success`,toolType:`todo_write`,data:t,summary:`${e.filter(e=>e.status===`pending`).length} pending, ${e.filter(e=>e.status===`in_progress`).length} in progress, ${e.filter(e=>e.status===`completed`).length} completed`}}}catch{}return{phase:`success`,toolType:`todo_write`,data:{},summary:`Updated`}}};function dz(e){if(typeof e!=`string`)return e;let t=e.trim();return t?Number(t):NaN}function fz(e){if(typeof e!=`string`)return e;let t=e.trim().toLowerCase();return[`true`,`1`,`yes`,`y`].includes(t)?!0:[`false`,`0`,`no`,`n`].includes(t)?!1:e}const HSe=ez(dz,ER()),pz=ez(dz,ER()).optional(),mz=ez(fz,OR()),hz=ez(fz,OR()).optional(),USe=ft([`codellm`,`agent`,`tools`,`ask-user`]);var gz=class e extends sz{isReadonly=!0;name=`ask_user_question`;displayName=`AskUserQuestion`;description=`Ask the user questions during execution to gather preferences, clarify instructions, or get decisions on implementation choices`;static parametersSchema=PR({questions:MR(PR({question:Y().describe(`The question to ask the user`),header:Y().describe(`A header/title for the question`),options:MR(PR({label:Y().describe(`The option label`),description:Y().describe(`A description of the option`)})).describe(`Array of options for the user to select from`),multiSelect:mz.describe(`Whether the user can select multiple options`)})).describe(`Array of questions to ask the user`),answers:HR(Y(),Y()).optional().describe(`User-provided answers to the questions`)});parameters=e.parametersSchema;needsPermission(){return!0}async execute(e){return USe.debug`Asking user ${e.questions.length} question(s)`,{answers:e.answers||{}}}format(e,t){return JSON.stringify({type:`ask_user_question`,status:`success`,answers:e.answers})}parse(e){let t=iz(e);if(t.rejected)return{phase:`rejected`,toolType:`ask_user_question`,data:{},summary:`Cancelled`,...t.userNote!==void 0&&{userNote:t.userNote}};try{let t=JSON.parse(e),n=t.answers,r=n?Object.keys(n).length:0;return{phase:`success`,toolType:`ask_user_question`,data:t,summary:`Answered ${r} question${r===1?``:`s`}`}}catch{}return{phase:`success`,toolType:`ask_user_question`,data:{},summary:`Answered`}}};const WSe=ft([`codellm`,`agent`,`tools`,`plan-mode`]);var _z=class e extends sz{name=`enter_plan_mode`;displayName=`EnterPlanMode`;description=`Enter plan mode to create a plan before implementing changes`;static parametersSchema=PR({});parameters=e.parametersSchema;isReadonly=!0;needsPermission(e,t,n){return!1}async execute(e,t){return WSe.info`Entering plan mode`,{success:!0}}format(e,t){return`Entered plan mode`}parse(e){let t=iz(e);return t.rejected?{phase:`rejected`,toolType:`enter_plan_mode`,data:{},summary:`Rejected`,...t.userNote!==void 0&&{userNote:t.userNote}}:{phase:`success`,toolType:`enter_plan_mode`,data:{},summary:`Entered plan mode`}}};const GSe=ft([`codellm`,`agent`,`tools`,`plan-mode`]);var vz=class e extends sz{name=`exit_plan_mode`;displayName=`ExitPlanMode`;description=`Exit plan mode and return to normal agent operation`;static parametersSchema=PR({planFilePath:Y().describe(`Path to the plan file`)});parameters=e.parametersSchema;isReadonly=!0;async prepare(e,t){if(!e.planFilePath)return{error:`Plan not found`,skipPermission:!0};try{let n=await t.workspace.readRawFile(e.planFilePath);return n?{planContent:n}:{error:`Plan not found`,skipPermission:!0}}catch{return{error:`Plan not found`,skipPermission:!0}}}needsPermission(e,t,n){return!n?.skipPermission}async execute(e,t,n){if(n?.error)throw Error(n.error);return GSe.info`Exiting plan mode with plan: ${e.planFilePath}`,{planFilePath:e.planFilePath}}format(e,t){return JSON.stringify({type:`exit_plan_mode`,status:`success`,...e.planFilePath&&{planFilePath:e.planFilePath}})}parse(e){let t=iz(e);if(t.rejected)return{phase:`rejected`,toolType:`exit_plan_mode`,data:{},summary:`Rejected`,...t.userNote!==void 0&&{userNote:t.userNote}};try{return{phase:`success`,toolType:`exit_plan_mode`,data:JSON.parse(e),summary:`Plan approved`}}catch{}return e.includes(`implement the plan`),{phase:`success`,toolType:`exit_plan_mode`,data:{},summary:`Plan approved`}}},yz;(function(e){e.GeneralPurpose=`GENERAL_PURPOSE`,e.Explore=`EXPLORE`,e.Plan=`PLAN`})(yz||={});const KSe={[yz.GeneralPurpose]:{name:yz.GeneralPurpose,displayName:`Agent`,description:`General-purpose agent for researching complex questions, searching for code, and executing multi-step tasks`,allowedTools:[`*`],defaultModel:`CLAUDE_V4_5_SONNET`},[yz.Explore]:{name:yz.Explore,displayName:`Explore`,description:`Fast agent specialized for exploring codebases. Use for finding files by patterns, searching code for keywords, or answering questions about the codebase.`,allowedTools:[`read`,`glob`,`grep`,`bash`,`web_fetch`,`web_search`],defaultModel:`CLAUDE_V4_5_HAIKU`},[yz.Plan]:{name:yz.Plan,displayName:`Plan`,description:`Fast agent for creating implementation plans. Explores codebase to understand architecture before planning.`,allowedTools:[`read`,`glob`,`grep`,`bash`,`web_fetch`,`web_search`],defaultModel:`CLAUDE_V4_5_HAIKU`}},qSe=new Set(Object.values(yz));function JSe(e){return qSe.has(e)}function bz(e){if(JSe(e))return e}function xz(e){return KSe[e]}function Sz(){return Object.values(yz)}function Cz(e){let t=bz(e);return t?xz(t).displayName:e}function YSe(e,t){let n=bz(e);if(!n)return!1;let r=xz(n);return r.allowedTools.includes(`*`)?!0:r.allowedTools.includes(t)}async function wz(e){return new Promise(t=>setTimeout(t,e))}const Tz=ft([`codellm`,`agent`,`loop`]);function Ez(e){if(!e)return null;if(typeof e==`string`)return e;if(typeof e==`object`&&e){let t=e;if(t.text)return t.text;if(t.segment)return Ez(t.segment)}return null}function XSe(e){return Math.min((e+1)*2e3,1e4)}function Dz(e){return 2**(e+1)*1e3}function*ZSe(e,t,n){if(e.error){let t=e.error,r=typeof t==`string`?t:JSON.stringify(t);r.includes(`Credit limit`)||r.includes(`no_usage_points`)||r.includes(`compute_point_budgeting`)||r.includes(`limit_exceeded`)||r.includes(`exhausted`)||r.includes(`purchase more credits`)?yield{__error:new Ld({...n.pendingCreditLimitSegment??void 0,message:r})}:Su(r)?yield{__error:new yu}:yield{__error:new Id(r)};return}if(e.type===`no_usage_points`||e.type===`compute_point_budgeting`||e.type===`limit_exceeded`){n.pendingCreditLimitSegment=e;return}if(e.type===`code_llm_credits`){yield{type:`credits`,creditsUsed:e.creditsUsed};return}if(e.type===`code_llm_session_info`){yield{type:`session_info`,contextPercent:e.contextPercent??0,contextTokensUsed:e.contextTokensUsed??0,contextWindowMax:e.contextWindowMax??0};return}if(e.type===`collapsible_component`&&e.isThoughts===!0){let t=e.title||`Thinking`,n=Ez(e.segment)??``;n&&(yield{type:`thinking_delta`,content:n,title:t}),e.isSpinny===!1&&(yield{type:`thinking_complete`});return}if(e.type===`code_llm_notification`){let t=e.message||Ez(e.segment)||`Notification`;yield{...e,type:`notification`,message:t,severity:e.severity??`info`};return}if(e.type===`code_llm_agent_tool_call_start`){yield{type:`tool_call_start`,toolCallId:e.toolCallId,toolName:e.toolName};return}if(e.type===`code_llm_agent_tool_call_delta`){yield{type:`tool_call_delta`,toolCallId:e.toolCallId,argumentsDelta:e.argumentsDelta};return}if(e.type===`code_llm_agent_tool_call_stop`){yield{type:`tool_call_stop`,toolCallId:e.toolCallId,toolName:e.toolName,arguments:e.arguments};let n=e.toolUseRequest;if(n){let e=n;if(e.name===`edit`){let t=e.input;(`startLineOneIndexed`in t||`endLineOneIndexed`in t)&&(e={...e,input:{...t,startLine:t.startLineOneIndexed??t.startLine,endLine:t.endLineOneIndexed??t.endLine}})}t.push(e),yield{type:`tool_requested`,tool:e}}return}if(e.toolUseRequest){let n=(Array.isArray(e.toolUseRequest)?e.toolUseRequest:[e.toolUseRequest]).map(e=>{if(e.name===`edit`){let t=e.input;if(`startLineOneIndexed`in t||`endLineOneIndexed`in t)return{...e,input:{...t,startLine:t.startLineOneIndexed??t.startLine,endLine:t.endLineOneIndexed??t.endLine}}}return e}),r=new Set(t.map(e=>e.id)),i=n.filter(e=>!r.has(e.id));t.push(...i);for(let e of i)yield{type:`tool_requested`,tool:e};return}if(e.segment){let t=Ez(e.segment);t&&(yield{type:`text_delta`,content:t})}}async function*QSe(e,t){let n=t?.generateRequestId?.()??crypto.randomUUID(),r=!1;Tz.debug(`Starting agent loop (conversationId={conversationId}, model={model})`,{conversationId:e.conversationId,model:e.model});for(let t=0;t<8;t++){fu(`turn started`,`agent`);let i=n,a=!1;if(t>0){Tz.debug(`Retry attempt {attempt}: checking for pending request ID`,{attempt:t});try{let t=await e.apiClient.getPendingRequestIdForConversation(e.conversationId);t?.success&&t.result?.requestId&&(i=t.result.requestId,a=!0)}catch{}}let o=[],s={pendingCreditLimitSegment:null},c=!1;try{Tz.debug(`Sending SSE request (attempt={attempt}, conversationId={conversationId}, requestId={requestId}, reconnect={reconnect})`,{attempt:t,conversationId:e.conversationId,requestId:i,reconnect:a});let n=e.apiClient.streamAgentMessage({deploymentConversationId:e.conversationId,message:e.message,supportedTools:e.supportedTools,supportedSubAgents:e.supportedSubAgents,mcpTools:e.isPrintMode?[]:e.mcpTools??[],workspacePath:e.workspacePath,...e.swapFolder&&{swapFolder:e.swapFolder},llmName:e.model,requestId:i,docInfos:e.uploadedDocs?Array.from(e.uploadedDocs):[],toolUseResult:e.toolResult,supportsV2:!0,supportsThoughtStreaming:e.supportsThoughtStreaming??!0,supportsParallelToolUse:!0,isPrintMode:e.isPrintMode??!1,...e.subagent&&{subagent:e.subagent},agentMode:e.agentMode,currentFile:e.currentFile,selectionStartLine:e.selectionStartLine,selectionEndLine:e.selectionEndLine,gitBranch:e.gitBranch,gitMain:e.gitMain,gitStatus:e.gitStatus,gitCommits:e.gitCommits,diagnosticIssues:e.diagnosticIssues,availableSkills:e.availableSkills,activeSkills:e.activeSkills,client:e.client,setFolder:e.setFolder,reconnect:a,signal:e.signal});for await(let t of n){if(e.signal?.aborted)break;for(let e of ZSe(t,o,s)){if(`__error`in e)throw e.__error;yield e}c=!0}if(e.signal?.aborted){e.apiClient.stopResponseSSE(i).catch(()=>{}),yield{type:`turn_complete_with_tools`,toolCalls:o};return}r&&=(yield{type:`network_status`,online:!0},!1),yield{type:`turn_complete_with_tools`,toolCalls:o},Tz.debug(`Agent loop completed with {count} tool calls`,{count:o.length});return}catch(n){let i=n instanceof Error?n:Error(String(n));if(i instanceof yu){if(c&&t<4&&!e.signal?.aborted){let e=Dz(t);Tz.warn(`Auth error mid-stream (attempt={attempt}, delay={delayMs}ms) — retrying (server may have re-validated against a stale replica)`,{attempt:t+1,delayMs:e}),uu(`Mid-stream auth error, retrying`,`warning`,{context:`agent-loop`,attempt:t+1}),yield{type:`retry`,attempt:t+1,maxAttempts:5,delayMs:e,isNetworkError:!1},await wz(e);continue}throw Tz.warn(`Auth expired, aborting loop`),i}if(i instanceof Ld)throw Tz.warn(`Credit limit reached, aborting loop`),uu(`Credit limit reached`,`warning`,{context:`agent-loop`}),i;let a=Cu(i),o=a?8:5;if(t<o-1&&!e.signal?.aborted){let e=a?XSe(t):Dz(t);Tz.warn(`Retrying after error (attempt={attempt}, network={isNetErr}, delay={delayMs}ms): {error}`,{attempt:t+1,isNetErr:a,delayMs:e,error:i.message}),a&&!r&&(r=!0,yield{type:`network_status`,online:!1}),yield{type:`retry`,attempt:t+1,maxAttempts:o,delayMs:e,isNetworkError:a},await wz(e);continue}throw Tz.error(`All retry attempts exhausted: {error}`,{error:i.message}),lu(i,{context:`agent-loop-retry-exhausted`}),Cu(i)?i instanceof bu?i:new bu(i.message,i):i}}}const Oz=ft([`codellm`,`agent`,`runner`]);var $Se=class{queue=[];resolvers=[];closed=!1;push(e){this.closed||(this.resolvers.length>0?this.resolvers.shift()(e):this.queue.push(e))}async next(){return this.queue.length>0?this.queue.shift():this.closed?null:new Promise(e=>{this.resolvers.push(e)})}close(){this.closed=!0;for(let e of this.resolvers)e(null);this.resolvers=[]}drain(){let e=[...this.queue];return this.queue=[],e}};function eCe(e){return e.toUpperCase().includes(`CLAUDE`)}async function*kz(e,t,n){let r=e.maxTurns??2**53-1,i=t,a,o=0,s=0,c=[],l=e.agentMode;Oz.info(`Starting agent conversation (model={model}, maxTurns={maxTurns})`,{model:e.model,maxTurns:r});try{for(;o<r;){if(n?.aborted)return Oz.info(`Conversation aborted after {numTurns} turns`,{numTurns:o}),{content:c.join(``),numTurns:o,toolCallsExecuted:s,success:!1,error:Error(`Execution cancelled`)};o++;let t={...e,swapFolder:a===void 0?e.swapFolder:void 0,setFolder:a===void 0?e.setFolder:void 0,agentMode:l,message:i,...a!==void 0&&{toolResult:a},...n!==void 0&&{signal:n}},r=[],u=new Map,d=new Map,f=new Map,p=[],m=new $Se,h=new AbortController,g=()=>h.abort(`interrupted`);n&&(n.aborted?h.abort(`interrupted`):n.addEventListener(`abort`,g,{once:!0}));let _=async(t,n,r)=>(await e.executeTools([t],n,r))[0],v=e.getConcurrency??(()=>!1),y=e=>{let t=_(e,h.signal,e=>m.push(e)).then(t=>{d.set(e.id,t);for(let[t,n]of f)if(n===e.id){f.delete(t);break}return t}).catch(e=>{throw h.abort(`sibling_tool_failed`),e});u.set(e.id,t)},b=e=>{let t=v(e);typeof t==`string`&&f.has(t)?p.push(e):(typeof t==`string`&&f.set(t,e.id),y(e))},x=!1;for await(let e of QSe(t)){for(let e of m.drain())e.type===`mode_changed`&&(l=e.mode),yield e;if(e.type===`turn_complete_with_tools`){r=e.toolCalls,x=!0;continue}if(e.type===`text_delta`&&c.push(e.content),e.type===`tool_requested`){yield e,b(e.tool);continue}yield e}for(let e of m.drain())e.type===`mode_changed`&&(l=e.mode),yield e;if(x||Oz.warn(`Agent loop exited without turn_complete_with_tools (collected {count} tool calls)`,{count:r.length}),r.length===0){Oz.debug(`Turn {numTurns} complete with no tool calls`,{numTurns:o}),n?.removeEventListener(`abort`,g),yield{type:`turn_complete`};break}for(let e of p){let t=v(e);if(typeof t==`string`&&f.has(t)){let e=f.get(t),n=u.get(e);if(n)try{await n}catch{}}h.signal.aborted||b(e)}let S=r.filter(e=>!u.has(e.id));if(S.length>0)if(u.size===0){let t,n=e.executeTools(r,h.signal,e=>m.push(e)).then(e=>{t=e;for(let t=0;t<e.length;t++){let n=r[t];n&&d.set(n.id,e[t])}return m.close(),e}),i=new Set;for(;t===void 0;){let e=await Promise.race([m.next(),n.then(()=>null)]);if(e!==null)e.type===`mode_changed`&&(l=e.mode),e.type===`tool_execution_complete`&&i.add(e.tool.id),yield e;else if(t!==void 0)break}t||=await n;for(let e of m.drain())e.type===`mode_changed`&&(l=e.mode),e.type===`tool_execution_complete`&&i.add(e.tool.id),yield e;for(let e=0;e<t.length;e++){let n=r[e],a=t[e];n&&a&&!i.has(n.id)&&(yield{type:`tool_execution_complete`,tool:n,result:a})}}else for(let e of S)h.signal.aborted||y(e);if(u.size>0){let e=Promise.allSettled(u.values()).then(()=>{m.close()}),t=new Set,n=await m.next();for(;n!==null;)n.type===`mode_changed`&&(l=n.mode),n.type===`tool_execution_complete`&&t.add(n.tool.id),yield n,n=await m.next();await e;for(let e of r){let n=d.get(e.id);n&&!t.has(e.id)&&(yield{type:`tool_execution_complete`,tool:e,result:n})}}s+=r.length;let C=r.map(e=>d.get(e.id)??{id:e.id,content:`Error: tool execution did not complete`});n?.removeEventListener(`abort`,g);for(let t of e.drainEvents?.()??[])t.type===`mode_changed`&&(l=t.mode),yield t;let w=new Set([`task`]),T=(e,t)=>!(!e.rejected||w.has(r[t]?.name??``)),E=C.some((e,t)=>{if(!T(e,t))return!1;try{return JSON.parse(e.content).reason===rz.REJECTED}catch{return!1}}),D=C.some((e,t)=>{if(!T(e,t))return!1;try{return JSON.parse(e.content).reason===rz.INTERRUPTED}catch{return!1}}),O=C.some(e=>{if(!e.rejected)return!1;try{return JSON.parse(e.content).reason===rz.USER_MESSAGE}catch{return!1}});if((E||D)&&!O){yield{type:`turn_complete`};break}let k=C.map(({parsedResult:e,...t})=>t);a=k.length===1?k[0]:k;let A=r.some(e=>e.name===`exit_plan_mode`)&&C.some(e=>{if(e.rejected)return!1;try{return JSON.parse(e.content).type===`exit_plan_mode`}catch{return!1}}),j=`I want you to start implementing the plan now as you have outlined in your plan.`;if(eCe(e.model)){let t=e.dequeueAllQueuedMessage?.({includeHidden:!0});t?(i=A?`${j} ${t.message}`:t.message,t.allHidden||(yield{type:`user_message_dequeued`,content:t.message})):i=A?j:``}else i=A?j:``;yield{type:`turn_complete`}}if(o>=r){Oz.warn(`Maximum turns ({maxTurns}) exceeded`,{maxTurns:r});let e=Error(`Maximum turns (${r}) exceeded`);return yield{type:`error`,error:e},{content:c.join(``),numTurns:o,toolCallsExecuted:s,success:!1,error:e}}return Oz.info(`Conversation completed (turns={numTurns}, toolCalls={toolCallsExecuted})`,{numTurns:o,toolCallsExecuted:s}),{content:c.join(``),numTurns:o,toolCallsExecuted:s,success:!0}}catch(e){let t=e instanceof Error?e:Error(String(e));return lu(t,{context:`agent-runner`}),Oz.error(`Conversation failed after {numTurns} turns: {error}`,{numTurns:o,toolCallsExecuted:s,error:t}),yield{type:`error`,error:t},{content:c.join(``),numTurns:o,toolCallsExecuted:s,success:!1,error:t}}}const Az=ft([`codellm`,`agent`,`subagent`]);function tCe(e,t){let n=xz(t);return!n||n.allowedTools.includes(`*`)?e:e.filter(e=>YSe(t,e.name))}function nCe(e,t,n,r,i){let a=n.get(e.name)?.displayName??e.name;if(!n.isBuiltinRequest(e))return{type:`generic`,tool:e,displayName:a,toolName:a,inputSummary:JSON.stringify(e.input??{}).slice(0,200)};switch(e.name){case`read`:{let n=t._prepareResult;if(n?.resolvedPath){let t=UF(n.resolvedPath);return{type:`read_outside_directory`,tool:e,displayName:a,filePath:t,resolvedPath:t,deducedDirectory:P.dirname(t)}}return{type:`generic`,tool:e,displayName:a,toolName:a,inputSummary:JSON.stringify(e.input??{}).slice(0,200)}}case`edit`:{let n=t._prepareResult;if(n?.outsideWorkspace){let t=UF(n.resolvedPath??e.input.filePath??``);return{type:`edit_outside_directory`,tool:e,displayName:a,filePath:t,resolvedPath:t,deducedDirectory:P.dirname(t)}}return{type:`edit_file`,tool:e,displayName:a,filePath:e.input.filePath??``,originalContent:n?.currentContent??``,newContent:n?.newContent??``}}case`write`:{let n=t._prepareResult;if(n?.outsideWorkspace){let t=UF(n.resolvedPath??e.input.filePath??``);return{type:`write_outside_directory`,tool:e,displayName:a,filePath:t,resolvedPath:t,deducedDirectory:P.dirname(t),isNewFile:!n?.fileExists}}return{type:`write_file`,tool:e,displayName:a,filePath:e.input.filePath??``,originalContent:n?.currentContent??``,content:e.input.content??``,isNewFile:!n?.fileExists}}case`bash`:return{type:`run_terminal`,tool:e,displayName:a,command:e.input.command??``,cwd:r,background:!!(e.input.runInBackground??!1),unmatchedPatterns:i?.getUnmatchedBashSegments(e.input.command??``,r)??[]};case`notebook_edit`:{let n=t._prepareResult;if(n?.outsideWorkspace){let t=UF(n.resolvedPath??e.input.notebookPath??``);return{type:`notebook_edit_outside_directory`,tool:e,displayName:a,filePath:t,resolvedPath:t,deducedDirectory:P.dirname(t)}}let r=n?.notebook,i=e.input.cellId,o=``;if(i&&r?.cells){let e=r.cells.find(e=>e.id===i||e.metadata?.id===i);e&&(o=Array.isArray(e.source)?e.source.join(``):String(e.source??``))}return{type:`notebook_edit`,tool:e,displayName:a,notebookPath:e.input.notebookPath??``,cellId:i,editMode:e.input.editMode??`replace`,cellType:e.input.cellType,originalContent:o,newContent:e.input.newSource??``}}case`ask_user_question`:return{type:`ask_user_question`,tool:e,displayName:a,questions:Array.isArray(e.input.questions)?e.input.questions:[]};case`exit_plan_mode`:{let n=t._prepareResult;return{type:`exit_plan_mode`,tool:e,displayName:a,planFilePath:e.input.planFilePath??``,planContent:n?.planContent??``}}default:return{type:`generic`,tool:e,displayName:a,toolName:a,inputSummary:JSON.stringify(e.input??{}).slice(0,200)}}}async function rCe(e){let{prompt:t,subagentType:n,model:r,resume:i,parentContext:a,onProgress:o,signal:s}=e;Az.info(`Starting subagent (type={subagentType}, model={model})`,{subagentType:n,model:r??`default`});let c=xz(n);if(!c)return Az.error(`Unknown subagent type: {subagentType}`,{subagentType:n}),{success:!1,output:``,toolsExecuted:[],toolCalls:[],numTurns:0,error:`Unknown subagent type: ${n}`};let l=_H(),u=tCe(l.getApiToolDefinitions(),n),d=r??c.defaultModel??`CLAUDE_V4_5_SONNET`,f;if(i&&c.supportsResume)f=i;else try{let e=await a.apiClient.createCodellmDeploymentConversation(`CODE_LLM_NON_INTERACTIVE`,a.clientType);if(!e?.result?.deploymentConversationId)return{success:!1,output:``,toolsExecuted:[],toolCalls:[],numTurns:0,error:`Failed to create subagent conversation: no conversation ID returned`};f=e.result.deploymentConversationId}catch(e){return{success:!1,output:``,toolsExecuted:[],toolCalls:[],numTurns:0,error:`Failed to create subagent conversation: ${e instanceof Error?e.message:String(e)}`}}let p=[],m=[],h=[],g=a.permissionProvider&&a.rulesEngine&&a.getAgentMode,_=()=>a.getAgentMode?.()??Pd.Yolo,v=c?.name,y={apiClient:a.apiClient,conversationId:f,model:d,workspacePath:a.workspacePath,supportedTools:u,mcpTools:[],uploadedDocs:a.uploadedDocs,isPrintMode:!g,...v&&{subagent:v},supportsThoughtStreaming:!0,agentMode:_(),executeTools:async(e,t,n)=>{let r=[];for(let i of e){if(t?.aborted||s?.aborted)break;m.push(i.name);let e={name:i.name,input:i.input??{}};o?.({type:`tool_requested`,content:`${i.name}`,toolName:i.name,toolInput:e.input,toolId:i.id}),n?.({type:`tool_execution_start`,tool:i});let c=_(),u={...a,toolCallId:i.id,conversationId:f,agentMode:c,status:`executing`};try{let d=l.createToolInstance(i.name,i.input??{},u);await d.prepare();let f=c===Pd.Yolo&&i.name!==`ask_user_question`;if(g&&!f&&d.needsPermission()){let c=l.get(i.name)?.displayName??i.name,f=TH(i),p=a.rulesEngine.evaluate(c,f,a.workspacePath);if(p===`deny`){r.push({id:i.id,content:JSON.stringify({reason:rz.REJECTED}),rejected:!0}),e.result=`denied by rule`,h.push(e),o?.({type:`tool_complete`,content:`${i.name}`,toolName:i.name,toolId:i.id});continue}if(p!==`allow`){let c=nCe(i,d,l,a.workspacePath,a.rulesEngine);if(a.permissionProvider.needsPermission(c)){n?.({type:`status_changed`,status:Fd.WaitingForToolPermission}),a.emitEvent?.({type:`status_changed`,status:Fd.WaitingForToolPermission});let l;try{let e=a.permissionProvider.requestPermission(c),n=t||s;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{l=await Promise.race([e,r])}finally{t&&n.removeEventListener(`abort`,t)}}else l=await e}catch{r.push({id:i.id,content:JSON.stringify({reason:rz.INTERRUPTED}),rejected:!0}),e.result=`interrupted`,h.push(e),o?.({type:`tool_complete`,content:`${i.name}`,toolName:i.name,toolId:i.id});continue}if(n?.({type:`status_changed`,status:Fd.ExecutingTool}),a.emitEvent?.({type:`status_changed`,status:Fd.ExecutingTool}),l===`reject`){r.push({id:i.id,content:JSON.stringify({reason:rz.REJECTED}),rejected:!0}),e.result=`rejected`,h.push(e),o?.({type:`tool_complete`,content:`${i.name}`,toolName:i.name,toolId:i.id});continue}if(typeof l==`object`&&l.type===`reject_with_message`){r.push({id:i.id,content:JSON.stringify({reason:rz.USER_MESSAGE,message:l.message}),rejected:!0}),e.result=`rejected`,h.push(e),o?.({type:`tool_complete`,content:`${i.name}`,toolName:i.name,toolId:i.id});continue}if(l===`allowAlways`||l===`allowYolo`||l===`accept`){if(l===`allowAlways`&&(c.type===`read_outside_directory`||c.type===`write_outside_directory`||c.type===`edit_outside_directory`||c.type===`notebook_edit_outside_directory`)&&`deducedDirectory`in c){let e=a.allowEditingPaths??[],t=c.deducedDirectory;e.includes(t)||e.push(t)}else if(i.name===`exit_plan_mode`){let e=l===`allowYolo`?Pd.Yolo:l===`allowAlways`?Pd.AcceptEdits:Pd.Normal;a.setAgentMode?.(e),u.agentMode=e,n?.({type:`mode_changed`,mode:e})}else if(l===`allowAlways`){let e=Bd(c.type);a.setAgentMode?.(e),u.agentMode=e,n?.({type:`mode_changed`,mode:e})}}if(typeof l==`object`&&l.type===`accept_with_message`){r.push({id:i.id,content:JSON.stringify({reason:rz.USER_MESSAGE,message:l.message}),rejected:!0}),e.result=`accepted with message`,h.push(e),o?.({type:`tool_complete`,content:`${i.name}`,toolName:i.name,toolId:i.id});continue}if(typeof l==`object`&&l.type===`question_answers`&&d.mergeParams({answers:l.answers}),typeof l==`object`&&l.type===`allow_always_with_rule`&&a.rulesEngine.addAllowRule(l.rule),typeof l==`object`&&l.type===`allow_always_with_rules`)for(let e of l.rules)a.rulesEngine.addAllowRule(e)}}}i.name===`enter_plan_mode`&&(a.setAgentMode?.(Pd.PlanMode),u.agentMode=Pd.PlanMode,n?.({type:`mode_changed`,mode:Pd.PlanMode})),i.name===`exit_plan_mode`&&f&&(a.setAgentMode?.(Pd.Normal),u.agentMode=Pd.Normal,n?.({type:`mode_changed`,mode:Pd.Normal})),await d.execute();let p=d.formatResultForLLM(),m=d.formatResult(),_=typeof p==`string`?p:JSON.stringify(p),v=l.parse(i.name,m);r.push({id:i.id,content:_,parsedResult:v}),e.result=_}catch(t){let n=t instanceof Error?t.message:String(t);r.push({id:i.id,content:`Error: ${n}`}),e.result=`Error: ${n}`}h.push(e),o?.({type:`tool_complete`,content:`${i.name}`,toolName:i.name,toolId:i.id})}for(let t of e)r.some(e=>e.id===t.id)||r.push({id:t.id,content:JSON.stringify({reason:rz.INTERRUPTED}),rejected:!0});return r}};try{o?.({type:`status`,content:`Starting ${n} agent...`});let e=kz(y,t,s),r=await e.next();for(;!r.done;){let t=r.value;switch(t.type){case`text_delta`:p.push(t.content),o?.({type:`text`,content:t.content});break;case`thinking_delta`:o?.({type:`thinking`,content:t.content});break;case`tool_requested`:case`turn_complete`:break;case`tool_execution_complete`:p.length=0;break;case`error`:return{success:!1,output:p.join(``),toolsExecuted:m,toolCalls:h,numTurns:0,error:t.error?.message??`Unknown error`};case`credits`:a.emitEvent?.(t);break;case`mode_changed`:a.emitEvent?.(t);break;case`session_info`:break;case`status_changed`:case`notification`:break}r=await e.next()}let i=r.value;return Az.info(`Subagent completed (type={subagentType}, turns={numTurns}, tools={toolCount})`,{subagentType:n,numTurns:i.numTurns,toolCount:m.length}),{success:i.success,output:p.join(``),toolsExecuted:m,toolCalls:h,numTurns:i.numTurns,...i.error&&{error:i.error.message}}}catch(e){let t=e instanceof Error?e.message:String(e);return lu(e instanceof Error?e:Error(t),{context:`subagent-runner`}),Az.error(`Subagent failed (type={subagentType}): {error}`,{subagentType:n,error:t}),{success:!1,output:p.join(``),toolsExecuted:m,toolCalls:h,numTurns:0,error:t}}}const jz=ft([`codellm`,`agent`,`tools`,`task`]);var Mz=class e extends sz{name=`task`;displayName=`Task`;description=`Launch a new agent to handle complex, multi-step tasks autonomously.
|
|
1899
|
+
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let n of e.seen.entries()){let r=n[1];if(t===n[0]){a(n);continue}if(e.external){let r=e.external.registry.get(n[0])?.id;if(t!==n[0]&&r){a(n);continue}}if(e.metadataRegistry.get(n[0])?.id){a(n);continue}if(r.cycle){a(n);continue}if(r.count>1&&e.reused===`ref`){a(n);continue}}}function cR(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);let r=t=>{let n=e.seen.get(t);if(n.ref===null)return;let i=n.def??n.schema,a={...i},o=n.ref;if(n.ref=null,o){r(o);let n=e.seen.get(o),s=n.schema;if(s.$ref&&(e.target===`draft-07`||e.target===`draft-04`||e.target===`openapi-3.0`)?(i.allOf=i.allOf??[],i.allOf.push(s)):Object.assign(i,s),Object.assign(i,a),t._zod.parent===o)for(let e in i)e===`$ref`||e===`allOf`||e in a||delete i[e];if(s.$ref&&n.def)for(let e in i)e===`$ref`||e===`allOf`||e in n.def&&JSON.stringify(i[e])===JSON.stringify(n.def[e])&&delete i[e]}let s=t._zod.parent;if(s&&s!==o){r(s);let t=e.seen.get(s);if(t?.schema.$ref&&(i.$ref=t.schema.$ref,t.def))for(let e in i)e===`$ref`||e===`allOf`||e in t.def&&JSON.stringify(i[e])===JSON.stringify(t.def[e])&&delete i[e]}e.override({zodSchema:t,jsonSchema:i,path:n.path??[]})};for(let t of[...e.seen.entries()].reverse())r(t[0]);let i={};if(e.target===`draft-2020-12`?i.$schema=`https://json-schema.org/draft/2020-12/schema`:e.target===`draft-07`?i.$schema=`http://json-schema.org/draft-07/schema#`:e.target===`draft-04`?i.$schema=`http://json-schema.org/draft-04/schema#`:e.target,e.external?.uri){let n=e.external.registry.get(t)?.id;if(!n)throw Error("Schema is missing an `id` property");i.$id=e.external.uri(n)}Object.assign(i,n.def??n.schema);let a=e.metadataRegistry.get(t)?.id;a!==void 0&&i.id===a&&delete i.id;let o=e.external?.defs??{};for(let t of e.seen.entries()){let e=t[1];e.def&&e.defId&&(e.def.id===e.defId&&delete e.def.id,o[e.defId]=e.def)}e.external||Object.keys(o).length>0&&(e.target===`draft-2020-12`?i.$defs=o:i.definitions=o);try{let n=JSON.parse(JSON.stringify(i));return Object.defineProperty(n,`~standard`,{value:{...t[`~standard`],jsonSchema:{input:uR(t,`input`,e.processors),output:uR(t,`output`,e.processors)}},enumerable:!1,writable:!1}),n}catch{throw Error(`Error converting schema to JSON.`)}}function lR(e,t){let n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);let r=e._zod.def;if(r.type===`transform`)return!0;if(r.type===`array`)return lR(r.element,n);if(r.type===`set`)return lR(r.valueType,n);if(r.type===`lazy`)return lR(r.getter(),n);if(r.type===`promise`||r.type===`optional`||r.type===`nonoptional`||r.type===`nullable`||r.type===`readonly`||r.type===`default`||r.type===`prefault`)return lR(r.innerType,n);if(r.type===`intersection`)return lR(r.left,n)||lR(r.right,n);if(r.type===`record`||r.type===`map`)return lR(r.keyType,n)||lR(r.valueType,n);if(r.type===`pipe`)return lR(r.in,n)||lR(r.out,n);if(r.type===`object`){for(let e in r.shape)if(lR(r.shape[e],n))return!0;return!1}if(r.type===`union`){for(let e of r.options)if(lR(e,n))return!0;return!1}if(r.type===`tuple`){for(let e of r.items)if(lR(e,n))return!0;return!!(r.rest&&lR(r.rest,n))}return!1}const Ube=(e,t={})=>n=>{let r=aR({...n,processors:t});return oR(e,r),sR(r,e),cR(r,e)},uR=(e,t,n={})=>r=>{let{libraryOptions:i,target:a}=r??{},o=aR({...i??{},target:a,io:t,processors:n});return oR(e,o),sR(o,e),cR(o,e)},Wbe={guid:`uuid`,url:`uri`,datetime:`date-time`,json_string:`json-string`,regex:``},Gbe=(e,t,n,r)=>{let i=n;i.type=`string`;let{minimum:a,maximum:o,format:s,patterns:c,contentEncoding:l}=e._zod.bag;if(typeof a==`number`&&(i.minLength=a),typeof o==`number`&&(i.maxLength=o),s&&(i.format=Wbe[s]??s,i.format===``&&delete i.format,s===`time`&&delete i.format),l&&(i.contentEncoding=l),c&&c.size>0){let e=[...c];e.length===1?i.pattern=e[0].source:e.length>1&&(i.allOf=[...e.map(e=>({...t.target===`draft-07`||t.target===`draft-04`||t.target===`openapi-3.0`?{type:`string`}:{},pattern:e.source}))])}},Kbe=(e,t,n,r)=>{let i=n,{minimum:a,maximum:o,format:s,multipleOf:c,exclusiveMaximum:l,exclusiveMinimum:u}=e._zod.bag;typeof s==`string`&&s.includes(`int`)?i.type=`integer`:i.type=`number`;let d=typeof u==`number`&&u>=(a??-1/0),f=typeof l==`number`&&l<=(o??1/0),p=t.target===`draft-04`||t.target===`openapi-3.0`;d?p?(i.minimum=u,i.exclusiveMinimum=!0):i.exclusiveMinimum=u:typeof a==`number`&&(i.minimum=a),f?p?(i.maximum=l,i.exclusiveMaximum=!0):i.exclusiveMaximum=l:typeof o==`number`&&(i.maximum=o),typeof c==`number`&&(i.multipleOf=c)},qbe=(e,t,n,r)=>{n.type=`boolean`},Jbe=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`BigInt cannot be represented in JSON Schema`)},Ybe=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Symbols cannot be represented in JSON Schema`)},Xbe=(e,t,n,r)=>{t.target===`openapi-3.0`?(n.type=`string`,n.nullable=!0,n.enum=[null]):n.type=`null`},Zbe=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Undefined cannot be represented in JSON Schema`)},Qbe=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Void cannot be represented in JSON Schema`)},$be=(e,t,n,r)=>{n.not={}},exe=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Date cannot be represented in JSON Schema`)},txe=(e,t,n,r)=>{let i=e._zod.def,a=c_e(i.entries);a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),n.enum=a},nxe=(e,t,n,r)=>{let i=e._zod.def,a=[];for(let e of i.values)if(e===void 0){if(t.unrepresentable===`throw`)throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof e==`bigint`){if(t.unrepresentable===`throw`)throw Error(`BigInt literals cannot be represented in JSON Schema`);a.push(Number(e))}else a.push(e);if(a.length!==0)if(a.length===1){let e=a[0];n.type=e===null?`null`:typeof e,t.target===`draft-04`||t.target===`openapi-3.0`?n.enum=[e]:n.const=e}else a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),a.every(e=>typeof e==`boolean`)&&(n.type=`boolean`),a.every(e=>e===null)&&(n.type=`null`),n.enum=a},rxe=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`NaN cannot be represented in JSON Schema`)},ixe=(e,t,n,r)=>{let i=n,a=e._zod.pattern;if(!a)throw Error(`Pattern not found in template literal`);i.type=`string`,i.pattern=a.source},axe=(e,t,n,r)=>{let i=n,a={type:`string`,format:`binary`,contentEncoding:`binary`},{minimum:o,maximum:s,mime:c}=e._zod.bag;o!==void 0&&(a.minLength=o),s!==void 0&&(a.maxLength=s),c?c.length===1?(a.contentMediaType=c[0],Object.assign(i,a)):(Object.assign(i,a),i.anyOf=c.map(e=>({contentMediaType:e}))):Object.assign(i,a)},oxe=(e,t,n,r)=>{n.type=`boolean`},sxe=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Custom types cannot be represented in JSON Schema`)},cxe=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Function types cannot be represented in JSON Schema`)},lxe=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Transforms cannot be represented in JSON Schema`)},uxe=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Map cannot be represented in JSON Schema`)},dxe=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Set cannot be represented in JSON Schema`)},fxe=(e,t,n,r)=>{let i=n,a=e._zod.def,{minimum:o,maximum:s}=e._zod.bag;typeof o==`number`&&(i.minItems=o),typeof s==`number`&&(i.maxItems=s),i.type=`array`,i.items=oR(a.element,t,{...r,path:[...r.path,`items`]})},pxe=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`,i.properties={};let o=a.shape;for(let e in o)i.properties[e]=oR(o[e],t,{...r,path:[...r.path,`properties`,e]});let s=new Set(Object.keys(o)),c=new Set([...s].filter(e=>{let n=a.shape[e]._zod;return t.io===`input`?n.optin===void 0:n.optout===void 0}));c.size>0&&(i.required=Array.from(c)),a.catchall?._zod.def.type===`never`?i.additionalProperties=!1:a.catchall?a.catchall&&(i.additionalProperties=oR(a.catchall,t,{...r,path:[...r.path,`additionalProperties`]})):t.io===`output`&&(i.additionalProperties=!1)},dR=(e,t,n,r)=>{let i=e._zod.def,a=i.inclusive===!1,o=i.options.map((e,n)=>oR(e,t,{...r,path:[...r.path,a?`oneOf`:`anyOf`,n]}));a?n.oneOf=o:n.anyOf=o},mxe=(e,t,n,r)=>{let i=e._zod.def,a=oR(i.left,t,{...r,path:[...r.path,`allOf`,0]}),o=oR(i.right,t,{...r,path:[...r.path,`allOf`,1]}),s=e=>`allOf`in e&&Object.keys(e).length===1;n.allOf=[...s(a)?a.allOf:[a],...s(o)?o.allOf:[o]]},hxe=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`array`;let o=t.target===`draft-2020-12`?`prefixItems`:`items`,s=t.target===`draft-2020-12`||t.target===`openapi-3.0`?`items`:`additionalItems`,c=a.items.map((e,n)=>oR(e,t,{...r,path:[...r.path,o,n]})),l=a.rest?oR(a.rest,t,{...r,path:[...r.path,s,...t.target===`openapi-3.0`?[a.items.length]:[]]}):null;t.target===`draft-2020-12`?(i.prefixItems=c,l&&(i.items=l)):t.target===`openapi-3.0`?(i.items={anyOf:c},l&&i.items.anyOf.push(l),i.minItems=c.length,l||(i.maxItems=c.length)):(i.items=c,l&&(i.additionalItems=l));let{minimum:u,maximum:d}=e._zod.bag;typeof u==`number`&&(i.minItems=u),typeof d==`number`&&(i.maxItems=d)},gxe=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`;let o=a.keyType,s=o._zod.bag?.patterns;if(a.mode===`loose`&&s&&s.size>0){let e=oR(a.valueType,t,{...r,path:[...r.path,`patternProperties`,`*`]});i.patternProperties={};for(let t of s)i.patternProperties[t.source]=e}else (t.target===`draft-07`||t.target===`draft-2020-12`)&&(i.propertyNames=oR(a.keyType,t,{...r,path:[...r.path,`propertyNames`]})),i.additionalProperties=oR(a.valueType,t,{...r,path:[...r.path,`additionalProperties`]});let c=o._zod.values;if(c){let e=[...c].filter(e=>typeof e==`string`||typeof e==`number`);e.length>0&&(i.required=e)}},_xe=(e,t,n,r)=>{let i=e._zod.def,a=oR(i.innerType,t,r),o=t.seen.get(e);t.target===`openapi-3.0`?(o.ref=i.innerType,n.nullable=!0):n.anyOf=[a,{type:`null`}]},vxe=(e,t,n,r)=>{let i=e._zod.def;oR(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},yxe=(e,t,n,r)=>{let i=e._zod.def;oR(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.default=JSON.parse(JSON.stringify(i.defaultValue))},bxe=(e,t,n,r)=>{let i=e._zod.def;oR(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,t.io===`input`&&(n._prefault=JSON.parse(JSON.stringify(i.defaultValue)))},xxe=(e,t,n,r)=>{let i=e._zod.def;oR(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o;try{o=i.catchValue(void 0)}catch{throw Error(`Dynamic catch values are not supported in JSON Schema`)}n.default=o},Sxe=(e,t,n,r)=>{let i=e._zod.def,a=t.io===`input`?i.in._zod.def.type===`transform`?i.out:i.in:i.out;oR(a,t,r);let o=t.seen.get(e);o.ref=a},Cxe=(e,t,n,r)=>{let i=e._zod.def;oR(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.readOnly=!0},wxe=(e,t,n,r)=>{let i=e._zod.def;oR(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},fR=(e,t,n,r)=>{let i=e._zod.def;oR(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},Txe=(e,t,n,r)=>{let i=e._zod.innerType;oR(i,t,r);let a=t.seen.get(e);a.ref=i},Exe=_I(`ZodISODateTime`,(e,t)=>{Hve.init(e,t),xR.init(e,t)});function pR(e){return mbe(Exe,e)}const Dxe=_I(`ZodISODate`,(e,t)=>{Uve.init(e,t),xR.init(e,t)});function Oxe(e){return hbe(Dxe,e)}const kxe=_I(`ZodISOTime`,(e,t)=>{Wve.init(e,t),xR.init(e,t)});function Axe(e){return gbe(kxe,e)}const jxe=_I(`ZodISODuration`,(e,t)=>{Gve.init(e,t),xR.init(e,t)});function Mxe(e){return _be(jxe,e)}const mR=(e,t)=>{GI.init(e,t),e.name=`ZodError`,Object.defineProperties(e,{format:{value:t=>D_e(e,t)},flatten:{value:t=>E_e(e,t)},addIssue:{value:t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,SI,2)}},addIssues:{value:t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,SI,2)}},isEmpty:{get(){return e.issues.length===0}}})};_I(`ZodError`,mR);const hR=_I(`ZodError`,mR,{Parent:Error}),Nxe=qI(hR),Pxe=YI(hR),Fxe=ZI(hR),Ixe=$I(hR),Lxe=k_e(hR),Rxe=A_e(hR),zxe=j_e(hR),Bxe=M_e(hR),Vxe=N_e(hR),Hxe=P_e(hR),Uxe=F_e(hR),Wxe=I_e(hR),gR=new WeakMap;function _R(e,t,n){let r=Object.getPrototypeOf(e),i=gR.get(r);if(i||(i=new Set,gR.set(r,i)),!i.has(t)){i.add(t);for(let e in n){let t=n[e];Object.defineProperty(r,e,{configurable:!0,enumerable:!1,get(){let n=t.bind(this);return Object.defineProperty(this,e,{configurable:!0,writable:!0,enumerable:!0,value:n}),n},set(t){Object.defineProperty(this,e,{configurable:!0,writable:!0,enumerable:!0,value:t})}})}}}const vR=_I(`ZodType`,(e,t)=>(pL.init(e,t),Object.assign(e[`~standard`],{jsonSchema:{input:uR(e,`input`),output:uR(e,`output`)}}),e.toJSONSchema=Ube(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,`_def`,{value:t}),e.parse=(t,n)=>Nxe(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>Fxe(e,t,n),e.parseAsync=async(t,n)=>Pxe(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>Ixe(e,t,n),e.spa=e.safeParseAsync,e.encode=(t,n)=>Lxe(e,t,n),e.decode=(t,n)=>Rxe(e,t,n),e.encodeAsync=async(t,n)=>zxe(e,t,n),e.decodeAsync=async(t,n)=>Bxe(e,t,n),e.safeEncode=(t,n)=>Vxe(e,t,n),e.safeDecode=(t,n)=>Hxe(e,t,n),e.safeEncodeAsync=async(t,n)=>Uxe(e,t,n),e.safeDecodeAsync=async(t,n)=>Wxe(e,t,n),_R(e,`ZodType`,{check(...e){let t=this.def;return this.clone(OI(t,{checks:[...t.checks??[],...e.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return FI(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(FSe(e,t))},superRefine(e,t){return this.check(ISe(e,t))},overwrite(e){return this.check(iR(e))},optional(){return JR(this)},exactOptional(){return CSe(this)},nullable(){return YR(this)},nullish(){return JR(YR(this))},nonoptional(e){return kSe(this,e)},array(){return MR(this)},or(e){return LR([this,e])},and(e){return zR(this,e)},transform(e){return QR(this,KR(e))},default(e){return ESe(this,e)},prefault(e){return OSe(this,e)},catch(e){return jSe(this,e)},pipe(e){return QR(this,e)},readonly(){return NSe(this)},describe(e){let t=this.clone();return WL.add(t,{description:e}),t},meta(...e){if(e.length===0)return WL.get(this);let t=this.clone();return WL.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e){return e(this)}}),Object.defineProperty(e,`description`,{get(){return WL.get(e)?.description},configurable:!0}),e)),yR=_I(`_ZodString`,(e,t)=>{mL.init(e,t),vR.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Gbe(e,t,n,r);let n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,_R(e,`_ZodString`,{regex(...e){return this.check(Ebe(...e))},includes(...e){return this.check(kbe(...e))},startsWith(...e){return this.check(Abe(...e))},endsWith(...e){return this.check(jbe(...e))},min(...e){return this.check(nR(...e))},max(...e){return this.check(tR(...e))},length(...e){return this.check(rR(...e))},nonempty(...e){return this.check(nR(1,...e))},lowercase(e){return this.check(Dbe(e))},uppercase(e){return this.check(Obe(e))},trim(){return this.check(Pbe())},normalize(...e){return this.check(Nbe(...e))},toLowerCase(){return this.check(Fbe())},toUpperCase(){return this.check(Ibe())},slugify(){return this.check(Lbe())}})}),bR=_I(`ZodString`,(e,t)=>{mL.init(e,t),yR.init(e,t),e.email=t=>e.check(Jye(Gxe,t)),e.url=t=>e.check(KL(wR,t)),e.jwt=t=>e.check(pbe(sSe,t)),e.emoji=t=>e.check($ye(qxe,t)),e.guid=t=>e.check(GL(SR,t)),e.uuid=t=>e.check(Yye(CR,t)),e.uuidv4=t=>e.check(Xye(CR,t)),e.uuidv6=t=>e.check(Zye(CR,t)),e.uuidv7=t=>e.check(Qye(CR,t)),e.nanoid=t=>e.check(ebe(Jxe,t)),e.guid=t=>e.check(GL(SR,t)),e.cuid=t=>e.check(tbe(Yxe,t)),e.cuid2=t=>e.check(nbe(Xxe,t)),e.ulid=t=>e.check(rbe(Zxe,t)),e.base64=t=>e.check(ube(iSe,t)),e.base64url=t=>e.check(dbe(aSe,t)),e.xid=t=>e.check(ibe(Qxe,t)),e.ksuid=t=>e.check(abe($xe,t)),e.ipv4=t=>e.check(obe(eSe,t)),e.ipv6=t=>e.check(sbe(tSe,t)),e.cidrv4=t=>e.check(cbe(nSe,t)),e.cidrv6=t=>e.check(lbe(rSe,t)),e.e164=t=>e.check(fbe(oSe,t)),e.datetime=t=>e.check(pR(t)),e.date=t=>e.check(Oxe(t)),e.time=t=>e.check(Axe(t)),e.duration=t=>e.check(Mxe(t))});function Y(e){return Kye(bR,e)}const xR=_I(`ZodStringFormat`,(e,t)=>{hL.init(e,t),yR.init(e,t)}),Gxe=_I(`ZodEmail`,(e,t)=>{Nve.init(e,t),xR.init(e,t)}),SR=_I(`ZodGUID`,(e,t)=>{jve.init(e,t),xR.init(e,t)}),CR=_I(`ZodUUID`,(e,t)=>{Mve.init(e,t),xR.init(e,t)}),wR=_I(`ZodURL`,(e,t)=>{Pve.init(e,t),xR.init(e,t)});function Kxe(e){return KL(wR,e)}const qxe=_I(`ZodEmoji`,(e,t)=>{Fve.init(e,t),xR.init(e,t)}),Jxe=_I(`ZodNanoID`,(e,t)=>{Ive.init(e,t),xR.init(e,t)}),Yxe=_I(`ZodCUID`,(e,t)=>{Lve.init(e,t),xR.init(e,t)}),Xxe=_I(`ZodCUID2`,(e,t)=>{Rve.init(e,t),xR.init(e,t)}),Zxe=_I(`ZodULID`,(e,t)=>{zve.init(e,t),xR.init(e,t)}),Qxe=_I(`ZodXID`,(e,t)=>{Bve.init(e,t),xR.init(e,t)}),$xe=_I(`ZodKSUID`,(e,t)=>{Vve.init(e,t),xR.init(e,t)}),eSe=_I(`ZodIPv4`,(e,t)=>{Kve.init(e,t),xR.init(e,t)});_I(`ZodMAC`,(e,t)=>{Jve.init(e,t),xR.init(e,t)});const tSe=_I(`ZodIPv6`,(e,t)=>{qve.init(e,t),xR.init(e,t)}),nSe=_I(`ZodCIDRv4`,(e,t)=>{Yve.init(e,t),xR.init(e,t)}),rSe=_I(`ZodCIDRv6`,(e,t)=>{Xve.init(e,t),xR.init(e,t)}),iSe=_I(`ZodBase64`,(e,t)=>{Zve.init(e,t),xR.init(e,t)}),aSe=_I(`ZodBase64URL`,(e,t)=>{$ve.init(e,t),xR.init(e,t)}),oSe=_I(`ZodE164`,(e,t)=>{eye.init(e,t),xR.init(e,t)}),sSe=_I(`ZodJWT`,(e,t)=>{nye.init(e,t),xR.init(e,t)});_I(`ZodCustomStringFormat`,(e,t)=>{rye.init(e,t),xR.init(e,t)});const TR=_I(`ZodNumber`,(e,t)=>{_L.init(e,t),vR.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Kbe(e,t,n,r),_R(e,`ZodNumber`,{gt(e,t){return this.check(YL(e,t))},gte(e,t){return this.check(XL(e,t))},min(e,t){return this.check(XL(e,t))},lt(e,t){return this.check(qL(e,t))},lte(e,t){return this.check(JL(e,t))},max(e,t){return this.check(JL(e,t))},int(e){return this.check(DR(e))},safe(e){return this.check(DR(e))},positive(e){return this.check(YL(0,e))},nonnegative(e){return this.check(XL(0,e))},negative(e){return this.check(qL(0,e))},nonpositive(e){return this.check(JL(0,e))},multipleOf(e,t){return this.check(ZL(e,t))},step(e,t){return this.check(ZL(e,t))},finite(){return this}});let n=e._zod.bag;e.minValue=Math.max(n.minimum??-1/0,n.exclusiveMinimum??-1/0)??null,e.maxValue=Math.min(n.maximum??1/0,n.exclusiveMaximum??1/0)??null,e.isInt=(n.format??``).includes(`int`)||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null});function ER(e){return vbe(TR,e)}const cSe=_I(`ZodNumberFormat`,(e,t)=>{iye.init(e,t),TR.init(e,t)});function DR(e){return bbe(cSe,e)}const lSe=_I(`ZodBoolean`,(e,t)=>{aye.init(e,t),vR.init(e,t),e._zod.processJSONSchema=(t,n,r)=>qbe(e,t,n,r)});function OR(e){return xbe(lSe,e)}const uSe=_I(`ZodBigInt`,(e,t)=>{vL.init(e,t),vR.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Jbe(e,t,n,r),e.gte=(t,n)=>e.check(XL(t,n)),e.min=(t,n)=>e.check(XL(t,n)),e.gt=(t,n)=>e.check(YL(t,n)),e.gte=(t,n)=>e.check(XL(t,n)),e.min=(t,n)=>e.check(XL(t,n)),e.lt=(t,n)=>e.check(qL(t,n)),e.lte=(t,n)=>e.check(JL(t,n)),e.max=(t,n)=>e.check(JL(t,n)),e.positive=t=>e.check(YL(BigInt(0),t)),e.negative=t=>e.check(qL(BigInt(0),t)),e.nonpositive=t=>e.check(JL(BigInt(0),t)),e.nonnegative=t=>e.check(XL(BigInt(0),t)),e.multipleOf=(t,n)=>e.check(ZL(t,n));let n=e._zod.bag;e.minValue=n.minimum??null,e.maxValue=n.maximum??null,e.format=n.format??null});_I(`ZodBigIntFormat`,(e,t)=>{oye.init(e,t),uSe.init(e,t)}),_I(`ZodSymbol`,(e,t)=>{sye.init(e,t),vR.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ybe(e,t,n,r)}),_I(`ZodUndefined`,(e,t)=>{cye.init(e,t),vR.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Zbe(e,t,n,r)});const dSe=_I(`ZodNull`,(e,t)=>{lye.init(e,t),vR.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Xbe(e,t,n,r)});function kR(e){return Sbe(dSe,e)}const fSe=_I(`ZodAny`,(e,t)=>{uye.init(e,t),vR.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function AR(){return Cbe(fSe)}const pSe=_I(`ZodUnknown`,(e,t)=>{dye.init(e,t),vR.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function jR(){return wbe(pSe)}const mSe=_I(`ZodNever`,(e,t)=>{fye.init(e,t),vR.init(e,t),e._zod.processJSONSchema=(t,n,r)=>$be(e,t,n,r)});function hSe(e){return Tbe(mSe,e)}_I(`ZodVoid`,(e,t)=>{pye.init(e,t),vR.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Qbe(e,t,n,r)}),_I(`ZodDate`,(e,t)=>{mye.init(e,t),vR.init(e,t),e._zod.processJSONSchema=(t,n,r)=>exe(e,t,n,r),e.min=(t,n)=>e.check(XL(t,n)),e.max=(t,n)=>e.check(JL(t,n));let n=e._zod.bag;e.minDate=n.minimum?new Date(n.minimum):null,e.maxDate=n.maximum?new Date(n.maximum):null});const gSe=_I(`ZodArray`,(e,t)=>{hye.init(e,t),vR.init(e,t),e._zod.processJSONSchema=(t,n,r)=>fxe(e,t,n,r),e.element=t.element,_R(e,`ZodArray`,{min(e,t){return this.check(nR(e,t))},nonempty(e){return this.check(nR(1,e))},max(e,t){return this.check(tR(e,t))},length(e,t){return this.check(rR(e,t))},unwrap(){return this.element}})});function MR(e,t){return Rbe(gSe,e,t)}const NR=_I(`ZodObject`,(e,t)=>{_ye.init(e,t),vR.init(e,t),e._zod.processJSONSchema=(t,n,r)=>pxe(e,t,n,r),EI(e,`shape`,()=>t.shape),_R(e,`ZodObject`,{keyof(){return WR(Object.keys(this._zod.def.shape))},catchall(e){return this.clone({...this._zod.def,catchall:e})},passthrough(){return this.clone({...this._zod.def,catchall:jR()})},loose(){return this.clone({...this._zod.def,catchall:jR()})},strict(){return this.clone({...this._zod.def,catchall:hSe()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(e){return b_e(this,e)},safeExtend(e){return x_e(this,e)},merge(e){return S_e(this,e)},pick(e){return v_e(this,e)},omit(e){return y_e(this,e)},partial(...e){return C_e(qR,this,e[0])},required(...e){return w_e(XR,this,e[0])}})});function PR(e,t){return new NR({type:`object`,shape:e??{},...II(t)})}function FR(e,t){return new NR({type:`object`,shape:e,catchall:jR(),...II(t)})}const IR=_I(`ZodUnion`,(e,t)=>{wL.init(e,t),vR.init(e,t),e._zod.processJSONSchema=(t,n,r)=>dR(e,t,n,r),e.options=t.options});function LR(e,t){return new IR({type:`union`,options:e,...II(t)})}_I(`ZodXor`,(e,t)=>{IR.init(e,t),vye.init(e,t),e._zod.processJSONSchema=(t,n,r)=>dR(e,t,n,r),e.options=t.options});const _Se=_I(`ZodDiscriminatedUnion`,(e,t)=>{IR.init(e,t),yye.init(e,t)});function RR(e,t,n){return new _Se({type:`union`,options:t,discriminator:e,...II(n)})}const vSe=_I(`ZodIntersection`,(e,t)=>{bye.init(e,t),vR.init(e,t),e._zod.processJSONSchema=(t,n,r)=>mxe(e,t,n,r)});function zR(e,t){return new vSe({type:`intersection`,left:e,right:t})}const ySe=_I(`ZodTuple`,(e,t)=>{OL.init(e,t),vR.init(e,t),e._zod.processJSONSchema=(t,n,r)=>hxe(e,t,n,r),e.rest=t=>e.clone({...e._zod.def,rest:t})});function BR(e,t,n){let r=t instanceof pL;return new ySe({type:`tuple`,items:e,rest:r?t:null,...II(r?n:t)})}const VR=_I(`ZodRecord`,(e,t)=>{xye.init(e,t),vR.init(e,t),e._zod.processJSONSchema=(t,n,r)=>gxe(e,t,n,r),e.keyType=t.keyType,e.valueType=t.valueType});function HR(e,t,n){return!t||!t._zod?new VR({type:`record`,keyType:Y(),valueType:e,...II(t)}):new VR({type:`record`,keyType:e,valueType:t,...II(n)})}_I(`ZodMap`,(e,t)=>{Sye.init(e,t),vR.init(e,t),e._zod.processJSONSchema=(t,n,r)=>uxe(e,t,n,r),e.keyType=t.keyType,e.valueType=t.valueType,e.min=(...t)=>e.check($L(...t)),e.nonempty=t=>e.check($L(1,t)),e.max=(...t)=>e.check(QL(...t)),e.size=(...t)=>e.check(eR(...t))}),_I(`ZodSet`,(e,t)=>{Cye.init(e,t),vR.init(e,t),e._zod.processJSONSchema=(t,n,r)=>dxe(e,t,n,r),e.min=(...t)=>e.check($L(...t)),e.nonempty=t=>e.check($L(1,t)),e.max=(...t)=>e.check(QL(...t)),e.size=(...t)=>e.check(eR(...t))});const UR=_I(`ZodEnum`,(e,t)=>{wye.init(e,t),vR.init(e,t),e._zod.processJSONSchema=(t,n,r)=>txe(e,t,n,r),e.enum=t.entries,e.options=Object.values(t.entries);let n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{let i={};for(let r of e)if(n.has(r))i[r]=t.entries[r];else throw Error(`Key ${r} not found in enum`);return new UR({...t,checks:[],...II(r),entries:i})},e.exclude=(e,r)=>{let i={...t.entries};for(let t of e)if(n.has(t))delete i[t];else throw Error(`Key ${t} not found in enum`);return new UR({...t,checks:[],...II(r),entries:i})}});function WR(e,t){return new UR({type:`enum`,entries:Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e,...II(t)})}const bSe=_I(`ZodLiteral`,(e,t)=>{Tye.init(e,t),vR.init(e,t),e._zod.processJSONSchema=(t,n,r)=>nxe(e,t,n,r),e.values=new Set(t.values),Object.defineProperty(e,`value`,{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function GR(e,t){return new bSe({type:`literal`,values:Array.isArray(e)?e:[e],...II(t)})}_I(`ZodFile`,(e,t)=>{Eye.init(e,t),vR.init(e,t),e._zod.processJSONSchema=(t,n,r)=>axe(e,t,n,r),e.min=(t,n)=>e.check($L(t,n)),e.max=(t,n)=>e.check(QL(t,n)),e.mime=(t,n)=>e.check(Mbe(Array.isArray(t)?t:[t],n))});const xSe=_I(`ZodTransform`,(e,t)=>{Dye.init(e,t),vR.init(e,t),e._zod.processJSONSchema=(t,n,r)=>lxe(e,t,n,r),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new yI(e.constructor.name);n.addIssue=r=>{if(typeof r==`string`)n.issues.push(UI(r,n.value,t));else{let t=r;t.fatal&&(t.continue=!1),t.code??=`custom`,t.input??=n.value,t.inst??=e,n.issues.push(UI(t))}};let i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n)):(n.value=i,n)}});function KR(e){return new xSe({type:`transform`,transform:e})}const qR=_I(`ZodOptional`,(e,t)=>{FL.init(e,t),vR.init(e,t),e._zod.processJSONSchema=(t,n,r)=>fR(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function JR(e){return new qR({type:`optional`,innerType:e})}const SSe=_I(`ZodExactOptional`,(e,t)=>{Oye.init(e,t),vR.init(e,t),e._zod.processJSONSchema=(t,n,r)=>fR(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function CSe(e){return new SSe({type:`optional`,innerType:e})}const wSe=_I(`ZodNullable`,(e,t)=>{kye.init(e,t),vR.init(e,t),e._zod.processJSONSchema=(t,n,r)=>_xe(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function YR(e){return new wSe({type:`nullable`,innerType:e})}const TSe=_I(`ZodDefault`,(e,t)=>{Aye.init(e,t),vR.init(e,t),e._zod.processJSONSchema=(t,n,r)=>yxe(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function ESe(e,t){return new TSe({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():MI(t)}})}const DSe=_I(`ZodPrefault`,(e,t)=>{jye.init(e,t),vR.init(e,t),e._zod.processJSONSchema=(t,n,r)=>bxe(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function OSe(e,t){return new DSe({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():MI(t)}})}const XR=_I(`ZodNonOptional`,(e,t)=>{Mye.init(e,t),vR.init(e,t),e._zod.processJSONSchema=(t,n,r)=>vxe(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function kSe(e,t){return new XR({type:`nonoptional`,innerType:e,...II(t)})}_I(`ZodSuccess`,(e,t)=>{Nye.init(e,t),vR.init(e,t),e._zod.processJSONSchema=(t,n,r)=>oxe(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});const ASe=_I(`ZodCatch`,(e,t)=>{Pye.init(e,t),vR.init(e,t),e._zod.processJSONSchema=(t,n,r)=>xxe(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function jSe(e,t){return new ASe({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:()=>t})}_I(`ZodNaN`,(e,t)=>{Fye.init(e,t),vR.init(e,t),e._zod.processJSONSchema=(t,n,r)=>rxe(e,t,n,r)});const ZR=_I(`ZodPipe`,(e,t)=>{Iye.init(e,t),vR.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Sxe(e,t,n,r),e.in=t.in,e.out=t.out});function QR(e,t){return new ZR({type:`pipe`,in:e,out:t})}_I(`ZodCodec`,(e,t)=>{ZR.init(e,t),Lye.init(e,t)});const MSe=_I(`ZodReadonly`,(e,t)=>{Rye.init(e,t),vR.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Cxe(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function NSe(e){return new MSe({type:`readonly`,innerType:e})}_I(`ZodTemplateLiteral`,(e,t)=>{zye.init(e,t),vR.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ixe(e,t,n,r)}),_I(`ZodLazy`,(e,t)=>{Hye.init(e,t),vR.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Txe(e,t,n,r),e.unwrap=()=>e._zod.def.getter()}),_I(`ZodPromise`,(e,t)=>{Vye.init(e,t),vR.init(e,t),e._zod.processJSONSchema=(t,n,r)=>wxe(e,t,n,r),e.unwrap=()=>e._zod.def.innerType}),_I(`ZodFunction`,(e,t)=>{Bye.init(e,t),vR.init(e,t),e._zod.processJSONSchema=(t,n,r)=>cxe(e,t,n,r)});const $R=_I(`ZodCustom`,(e,t)=>{Uye.init(e,t),vR.init(e,t),e._zod.processJSONSchema=(t,n,r)=>sxe(e,t,n,r)});function PSe(e,t){return zbe($R,e??(()=>!0),t)}function FSe(e,t={}){return Bbe($R,e,t)}function ISe(e,t){return Vbe(e,t)}function ez(e,t){return QR(KR(e),t)}const LSe={invalid_type:`invalid_type`,too_big:`too_big`,too_small:`too_small`,invalid_format:`invalid_format`,not_multiple_of:`not_multiple_of`,unrecognized_keys:`unrecognized_keys`,invalid_union:`invalid_union`,invalid_key:`invalid_key`,invalid_element:`invalid_element`,invalid_value:`invalid_value`,custom:`custom`};var RSe;(function(e){})(RSe||={});function tz(e){return qye(bR,e)}function nz(e){return ybe(TR,e)}const rz={USER_MESSAGE:`user_message`,REJECTED:`rejected`,INTERRUPTED:`interrupted`},zSe={REJECTED:`rejected`};function iz(e){if(e===`Tool was rejected by user`)return{rejected:!0};try{let t=JSON.parse(e);if(t.reason===rz.USER_MESSAGE)return{rejected:!0,userNote:t.message};if(t.reason===rz.REJECTED||t.reason===rz.INTERRUPTED)return{rejected:!0};if(t.status===zSe.REJECTED)return{rejected:!0,userNote:t.userNote}}catch{}return{rejected:!1}}const az=`sibling_tool_failed`,oz=JSON.stringify({type:az,message:`Not executed: a tool call in a preceding parallel batch failed`});function BSe(e){try{return JSON.parse(e)?.type===az}catch{return!1}}var sz=class{concurrency(e,t){return!1}includeInApiDefinitions=!0;isEnabled(e){return!0}async prepare(e,t){return null}needsPermission(e,t,n){return!this.isReadonly}timeout(e,t){return 12e4}async onTimeout(e,t,n){throw Error(`${this.displayName} tool timed out after ${n}ms`)}format(e,t){return typeof e==`string`?e:JSON.stringify(e)}formatForLLM(e,t){return this.format(e,t)}parse(e){let t=iz(e);if(t.rejected)return{phase:`rejected`,toolType:this.name,data:{},summary:t.userNote?`Rejected \u00b7 "${t.userNote}"`:`Rejected`,...t.userNote!==void 0&&{userNote:t.userNote}};try{let t=JSON.parse(e),n=`success`;return t.status===`error`?n=`error`:t.status===`skipped`&&(n=`skipped`),{phase:n,toolType:t.type??this.name,data:t,summary:t.message??t.summary??`Completed`,...t.errorMessage!==void 0&&{errorMessage:t.errorMessage}}}catch{}return e.startsWith(`Error:`)?{phase:`error`,toolType:this.name,data:{},summary:e,errorMessage:e}:{phase:`success`,toolType:this.name,data:{},summary:`Completed`}}validateParams(e){return this.parameters.parse(e)}getToolDefinition(){let e=this.getParameterNames();return{name:this.name,description:this.description,arguments:e}}getParameterNames(){return Object.keys(this.parameters.shape)}};const VSe=Symbol.for(`server-executed`);var cz=class extends sz{isReadonly=!0;async execute(e,t,n){return VSe}format(e,t){return JSON.stringify({type:this.name,status:`server-executed`})}};ft([`codellm`,`agent`,`tools`,`subagent`]);var lz=class e extends cz{name=`subagent`;displayName=`Subagent`;description=`Switch to a different subagent for a task`;static parametersSchema=PR({agent:Y().describe(`The name of the subagent to switch to`),task:Y().describe(`The task description for the subagent`)});parameters=e.parametersSchema;needsPermission(){return!1}timeout(){return 6e5}format(e,t){return JSON.stringify({type:`subagent`,status:`success`,agent:t.agent,task:t.task})}parse(e){let t=iz(e);if(t.rejected)return{phase:`rejected`,toolType:`subagent`,data:{},summary:t.userNote?`Rejected \u00b7 "${t.userNote}"`:`Rejected`,...t.userNote!==void 0&&{userNote:t.userNote}};try{let t=JSON.parse(e);return{phase:`success`,toolType:`subagent`,data:t,summary:`Delegated to ${t.agent??`explore`} agent`}}catch{}return{phase:`success`,toolType:`subagent`,data:{},summary:`Delegated`}}};ft([`codellm`,`agent`,`tools`,`todo-write`]);var uz=class e extends cz{name=`todo_write`;displayName=`TodoWrite`;description=`Create and manage a structured task list`;static parametersSchema=PR({todos:ez(e=>{if(e==null)return[];if(typeof e==`string`)try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}return Array.isArray(e)?e:[]},MR(PR({content:Y().describe(`The task content`),status:WR([`pending`,`in_progress`,`completed`,`cancelled`]).describe(`The status of the task`),id:Y().optional().describe(`Optional task ID`)}))).describe(`Array of todo items`)});parameters=e.parametersSchema;needsPermission(){return!1}format(e,t){return`Updated`}parse(e){let t=iz(e);if(t.rejected)return{phase:`rejected`,toolType:`todo_write`,data:{},summary:`Rejected`,...t.userNote!==void 0&&{userNote:t.userNote}};try{let t=JSON.parse(e);if(t.todos){let e=t.todos;return{phase:`success`,toolType:`todo_write`,data:t,summary:`${e.filter(e=>e.status===`pending`).length} pending, ${e.filter(e=>e.status===`in_progress`).length} in progress, ${e.filter(e=>e.status===`completed`).length} completed`}}}catch{}return{phase:`success`,toolType:`todo_write`,data:{},summary:`Updated`}}};function dz(e){if(typeof e!=`string`)return e;let t=e.trim();return t?Number(t):NaN}function fz(e){if(typeof e!=`string`)return e;let t=e.trim().toLowerCase();return[`true`,`1`,`yes`,`y`].includes(t)?!0:[`false`,`0`,`no`,`n`].includes(t)?!1:e}const HSe=ez(dz,ER()),pz=ez(dz,ER()).optional(),mz=ez(fz,OR()),hz=ez(fz,OR()).optional(),USe=ft([`codellm`,`agent`,`tools`,`ask-user`]);var gz=class e extends sz{isReadonly=!0;name=`ask_user_question`;displayName=`AskUserQuestion`;description=`Ask the user questions during execution to gather preferences, clarify instructions, or get decisions on implementation choices`;static parametersSchema=PR({questions:MR(PR({question:Y().describe(`The question to ask the user`),header:Y().describe(`A header/title for the question`),options:MR(PR({label:Y().describe(`The option label`),description:Y().describe(`A description of the option`)})).describe(`Array of options for the user to select from`),multiSelect:mz.describe(`Whether the user can select multiple options`)})).describe(`Array of questions to ask the user`),answers:HR(Y(),Y()).optional().describe(`User-provided answers to the questions`)});parameters=e.parametersSchema;needsPermission(){return!0}async execute(e){return USe.debug`Asking user ${e.questions.length} question(s)`,{answers:e.answers||{}}}format(e,t){return JSON.stringify({type:`ask_user_question`,status:`success`,answers:e.answers})}parse(e){let t=iz(e);if(t.rejected)return{phase:`rejected`,toolType:`ask_user_question`,data:{},summary:`Cancelled`,...t.userNote!==void 0&&{userNote:t.userNote}};try{let t=JSON.parse(e),n=t.answers,r=n?Object.keys(n).length:0;return{phase:`success`,toolType:`ask_user_question`,data:t,summary:`Answered ${r} question${r===1?``:`s`}`}}catch{}return{phase:`success`,toolType:`ask_user_question`,data:{},summary:`Answered`}}};const WSe=ft([`codellm`,`agent`,`tools`,`plan-mode`]);var _z=class e extends sz{name=`enter_plan_mode`;displayName=`EnterPlanMode`;description=`Enter plan mode to create a plan before implementing changes`;static parametersSchema=PR({});parameters=e.parametersSchema;isReadonly=!0;needsPermission(e,t,n){return!1}async execute(e,t){return WSe.info`Entering plan mode`,{success:!0}}format(e,t){return`Entered plan mode`}parse(e){let t=iz(e);return t.rejected?{phase:`rejected`,toolType:`enter_plan_mode`,data:{},summary:`Rejected`,...t.userNote!==void 0&&{userNote:t.userNote}}:{phase:`success`,toolType:`enter_plan_mode`,data:{},summary:`Entered plan mode`}}};const GSe=ft([`codellm`,`agent`,`tools`,`plan-mode`]);var vz=class e extends sz{name=`exit_plan_mode`;displayName=`ExitPlanMode`;description=`Exit plan mode and return to normal agent operation`;static parametersSchema=PR({planFilePath:Y().describe(`Path to the plan file`)});parameters=e.parametersSchema;isReadonly=!0;async prepare(e,t){if(!e.planFilePath)return{error:`Plan not found`,skipPermission:!0};try{let n=await t.workspace.readRawFile(e.planFilePath);return n?{planContent:n}:{error:`Plan not found`,skipPermission:!0}}catch{return{error:`Plan not found`,skipPermission:!0}}}needsPermission(e,t,n){return!n?.skipPermission}async execute(e,t,n){if(n?.error)throw Error(n.error);return GSe.info`Exiting plan mode with plan: ${e.planFilePath}`,{planFilePath:e.planFilePath}}format(e,t){return JSON.stringify({type:`exit_plan_mode`,status:`success`,...e.planFilePath&&{planFilePath:e.planFilePath}})}parse(e){let t=iz(e);if(t.rejected)return{phase:`rejected`,toolType:`exit_plan_mode`,data:{},summary:`Rejected`,...t.userNote!==void 0&&{userNote:t.userNote}};try{return{phase:`success`,toolType:`exit_plan_mode`,data:JSON.parse(e),summary:`Plan approved`}}catch{}return e.includes(`implement the plan`),{phase:`success`,toolType:`exit_plan_mode`,data:{},summary:`Plan approved`}}},yz;(function(e){e.GeneralPurpose=`GENERAL_PURPOSE`,e.Explore=`EXPLORE`,e.Plan=`PLAN`})(yz||={});const KSe={[yz.GeneralPurpose]:{name:yz.GeneralPurpose,displayName:`Agent`,description:`General-purpose agent for researching complex questions, searching for code, and executing multi-step tasks`,allowedTools:[`*`],defaultModel:`CLAUDE_V4_5_SONNET`},[yz.Explore]:{name:yz.Explore,displayName:`Explore`,description:`Fast agent specialized for exploring codebases. Use for finding files by patterns, searching code for keywords, or answering questions about the codebase.`,allowedTools:[`read`,`glob`,`grep`,`bash`,`web_fetch`,`web_search`],defaultModel:`CLAUDE_V4_5_HAIKU`},[yz.Plan]:{name:yz.Plan,displayName:`Plan`,description:`Fast agent for creating implementation plans. Explores codebase to understand architecture before planning.`,allowedTools:[`read`,`glob`,`grep`,`bash`,`web_fetch`,`web_search`],defaultModel:`CLAUDE_V4_5_HAIKU`}},qSe=new Set(Object.values(yz));function JSe(e){return qSe.has(e)}function bz(e){if(JSe(e))return e}function xz(e){return KSe[e]}function Sz(){return Object.values(yz)}function Cz(e){let t=bz(e);return t?xz(t).displayName:e}function YSe(e,t){let n=bz(e);if(!n)return!1;let r=xz(n);return r.allowedTools.includes(`*`)?!0:r.allowedTools.includes(t)}async function wz(e){return new Promise(t=>setTimeout(t,e))}const Tz=ft([`codellm`,`agent`,`loop`]);function Ez(e){if(!e)return null;if(typeof e==`string`)return e;if(typeof e==`object`&&e){let t=e;if(t.text)return t.text;if(t.segment)return Ez(t.segment)}return null}function XSe(e){return Math.min((e+1)*2e3,1e4)}function Dz(e){return 2**(e+1)*1e3}function*ZSe(e,t,n){if(e.error){let t=e.error,r=typeof t==`string`?t:JSON.stringify(t);r.includes(`Credit limit`)||r.includes(`no_usage_points`)||r.includes(`compute_point_budgeting`)||r.includes(`limit_exceeded`)||r.includes(`exhausted`)||r.includes(`purchase more credits`)?yield{__error:new Ld({...n.pendingCreditLimitSegment??void 0,message:r})}:Su(r)?yield{__error:new yu}:yield{__error:new Id(r)};return}if(e.type===`no_usage_points`||e.type===`compute_point_budgeting`||e.type===`limit_exceeded`){n.pendingCreditLimitSegment=e;return}if(e.type===`code_llm_credits`){yield{type:`credits`,creditsUsed:e.creditsUsed};return}if(e.type===`code_llm_session_info`){yield{type:`session_info`,contextPercent:e.contextPercent??0,contextTokensUsed:e.contextTokensUsed??0,contextWindowMax:e.contextWindowMax??0};return}if(e.type===`collapsible_component`&&e.isThoughts===!0){let t=e.title||`Thinking`,n=Ez(e.segment)??``;n&&(yield{type:`thinking_delta`,content:n,title:t}),e.isSpinny===!1&&(yield{type:`thinking_complete`});return}if(e.type===`code_llm_notification`){let t=e.message||Ez(e.segment)||`Notification`;yield{...e,type:`notification`,message:t,severity:e.severity??`info`};return}if(e.type===`code_llm_agent_tool_call_start`){yield{type:`tool_call_start`,toolCallId:e.toolCallId,toolName:e.toolName};return}if(e.type===`code_llm_agent_tool_call_delta`){yield{type:`tool_call_delta`,toolCallId:e.toolCallId,argumentsDelta:e.argumentsDelta};return}if(e.type===`code_llm_agent_tool_call_stop`){yield{type:`tool_call_stop`,toolCallId:e.toolCallId,toolName:e.toolName,arguments:e.arguments};let n=e.toolUseRequest;if(n){let e=n;if(e.name===`edit`){let t=e.input;(`startLineOneIndexed`in t||`endLineOneIndexed`in t)&&(e={...e,input:{...t,startLine:t.startLineOneIndexed??t.startLine,endLine:t.endLineOneIndexed??t.endLine}})}t.push(e),yield{type:`tool_requested`,tool:e}}return}if(e.toolUseRequest){let n=(Array.isArray(e.toolUseRequest)?e.toolUseRequest:[e.toolUseRequest]).map(e=>{if(e.name===`edit`){let t=e.input;if(`startLineOneIndexed`in t||`endLineOneIndexed`in t)return{...e,input:{...t,startLine:t.startLineOneIndexed??t.startLine,endLine:t.endLineOneIndexed??t.endLine}}}return e}),r=new Set(t.map(e=>e.id)),i=n.filter(e=>!r.has(e.id));t.push(...i);for(let e of i)yield{type:`tool_requested`,tool:e};return}if(e.segment){let t=Ez(e.segment);t&&(yield{type:`text_delta`,content:t})}}async function*QSe(e,t){let n=t?.generateRequestId?.()??crypto.randomUUID(),r=!1;Tz.debug(`Starting agent loop (conversationId={conversationId}, model={model})`,{conversationId:e.conversationId,model:e.model});for(let t=0;t<8;t++){fu(`turn started`,`agent`);let i=n,a=!1;if(t>0){Tz.debug(`Retry attempt {attempt}: checking for pending request ID`,{attempt:t});try{let t=await e.apiClient.getPendingRequestIdForConversation(e.conversationId);t?.success&&t.result?.requestId&&(i=t.result.requestId,a=!0)}catch{}}let o=[],s={pendingCreditLimitSegment:null},c=!1;try{Tz.debug(`Sending SSE request (attempt={attempt}, conversationId={conversationId}, requestId={requestId}, reconnect={reconnect})`,{attempt:t,conversationId:e.conversationId,requestId:i,reconnect:a});let n=e.apiClient.streamAgentMessage({deploymentConversationId:e.conversationId,message:e.message,supportedTools:e.supportedTools,supportedSubAgents:e.supportedSubAgents,mcpTools:e.isPrintMode?[]:e.mcpTools??[],workspacePath:e.workspacePath,...e.swapFolder&&{swapFolder:e.swapFolder},llmName:e.model,requestId:i,docInfos:e.uploadedDocs?Array.from(e.uploadedDocs):[],toolUseResult:e.toolResult,supportsV2:!0,supportsThoughtStreaming:e.supportsThoughtStreaming??!0,supportsParallelToolUse:!0,isPrintMode:e.isPrintMode??!1,...e.subagent&&{subagent:e.subagent},agentMode:e.agentMode,currentFile:e.currentFile,selectionStartLine:e.selectionStartLine,selectionEndLine:e.selectionEndLine,gitBranch:e.gitBranch,gitMain:e.gitMain,gitStatus:e.gitStatus,gitCommits:e.gitCommits,diagnosticIssues:e.diagnosticIssues,agentsMd:e.agentsMd,availableSkills:e.availableSkills,activeSkills:e.activeSkills,client:e.client,setFolder:e.setFolder,reconnect:a,signal:e.signal});for await(let t of n){if(e.signal?.aborted)break;for(let e of ZSe(t,o,s)){if(`__error`in e)throw e.__error;yield e}c=!0}if(e.signal?.aborted){e.apiClient.stopResponseSSE(i).catch(()=>{}),yield{type:`turn_complete_with_tools`,toolCalls:o};return}r&&=(yield{type:`network_status`,online:!0},!1),yield{type:`turn_complete_with_tools`,toolCalls:o},Tz.debug(`Agent loop completed with {count} tool calls`,{count:o.length});return}catch(n){let i=n instanceof Error?n:Error(String(n));if(i instanceof yu){if(c&&t<4&&!e.signal?.aborted){let e=Dz(t);Tz.warn(`Auth error mid-stream (attempt={attempt}, delay={delayMs}ms) — retrying (server may have re-validated against a stale replica)`,{attempt:t+1,delayMs:e}),uu(`Mid-stream auth error, retrying`,`warning`,{context:`agent-loop`,attempt:t+1}),yield{type:`retry`,attempt:t+1,maxAttempts:5,delayMs:e,isNetworkError:!1},await wz(e);continue}throw Tz.warn(`Auth expired, aborting loop`),i}if(i instanceof Ld)throw Tz.warn(`Credit limit reached, aborting loop`),uu(`Credit limit reached`,`warning`,{context:`agent-loop`}),i;let a=Cu(i),o=a?8:5;if(t<o-1&&!e.signal?.aborted){let e=a?XSe(t):Dz(t);Tz.warn(`Retrying after error (attempt={attempt}, network={isNetErr}, delay={delayMs}ms): {error}`,{attempt:t+1,isNetErr:a,delayMs:e,error:i.message}),a&&!r&&(r=!0,yield{type:`network_status`,online:!1}),yield{type:`retry`,attempt:t+1,maxAttempts:o,delayMs:e,isNetworkError:a},await wz(e);continue}throw Tz.error(`All retry attempts exhausted: {error}`,{error:i.message}),lu(i,{context:`agent-loop-retry-exhausted`}),Cu(i)?i instanceof bu?i:new bu(i.message,i):i}}}const Oz=ft([`codellm`,`agent`,`runner`]);var $Se=class{queue=[];resolvers=[];closed=!1;push(e){this.closed||(this.resolvers.length>0?this.resolvers.shift()(e):this.queue.push(e))}async next(){return this.queue.length>0?this.queue.shift():this.closed?null:new Promise(e=>{this.resolvers.push(e)})}close(){this.closed=!0;for(let e of this.resolvers)e(null);this.resolvers=[]}drain(){let e=[...this.queue];return this.queue=[],e}};function eCe(e){return e.toUpperCase().includes(`CLAUDE`)}async function*kz(e,t,n){let r=e.maxTurns??2**53-1,i=t,a,o=0,s=0,c=[],l=e.agentMode;Oz.info(`Starting agent conversation (model={model}, maxTurns={maxTurns})`,{model:e.model,maxTurns:r});try{for(;o<r;){if(n?.aborted)return Oz.info(`Conversation aborted after {numTurns} turns`,{numTurns:o}),{content:c.join(``),numTurns:o,toolCallsExecuted:s,success:!1,error:Error(`Execution cancelled`)};o++;let t={...e,swapFolder:a===void 0?e.swapFolder:void 0,setFolder:a===void 0?e.setFolder:void 0,agentMode:l,message:i,...a!==void 0&&{toolResult:a},...n!==void 0&&{signal:n},...o>1&&{agentsMd:void 0}},r=[],u=new Map,d=new Map,f=new Map,p=[],m=new $Se,h=new AbortController,g=()=>h.abort(`interrupted`);n&&(n.aborted?h.abort(`interrupted`):n.addEventListener(`abort`,g,{once:!0}));let _=async(t,n,r)=>(await e.executeTools([t],n,r))[0],v=e.getConcurrency??(()=>!1),y=e=>{let t=_(e,h.signal,e=>m.push(e)).then(t=>{d.set(e.id,t);for(let[t,n]of f)if(n===e.id){f.delete(t);break}return t}).catch(e=>{throw h.abort(`sibling_tool_failed`),e});u.set(e.id,t)},b=e=>{let t=v(e);typeof t==`string`&&f.has(t)?p.push(e):(typeof t==`string`&&f.set(t,e.id),y(e))},x=!1;for await(let e of QSe(t)){for(let e of m.drain())e.type===`mode_changed`&&(l=e.mode),yield e;if(e.type===`turn_complete_with_tools`){r=e.toolCalls,x=!0;continue}if(e.type===`text_delta`&&c.push(e.content),e.type===`tool_requested`){yield e,b(e.tool);continue}yield e}for(let e of m.drain())e.type===`mode_changed`&&(l=e.mode),yield e;if(x||Oz.warn(`Agent loop exited without turn_complete_with_tools (collected {count} tool calls)`,{count:r.length}),r.length===0){Oz.debug(`Turn {numTurns} complete with no tool calls`,{numTurns:o}),n?.removeEventListener(`abort`,g),yield{type:`turn_complete`};break}for(let e of p){let t=v(e);if(typeof t==`string`&&f.has(t)){let e=f.get(t),n=u.get(e);if(n)try{await n}catch{}}h.signal.aborted||b(e)}let S=r.filter(e=>!u.has(e.id));if(S.length>0)if(u.size===0){let t,n=e.executeTools(r,h.signal,e=>m.push(e)).then(e=>{t=e;for(let t=0;t<e.length;t++){let n=r[t];n&&d.set(n.id,e[t])}return m.close(),e}),i=new Set;for(;t===void 0;){let e=await Promise.race([m.next(),n.then(()=>null)]);if(e!==null)e.type===`mode_changed`&&(l=e.mode),e.type===`tool_execution_complete`&&i.add(e.tool.id),yield e;else if(t!==void 0)break}t||=await n;for(let e of m.drain())e.type===`mode_changed`&&(l=e.mode),e.type===`tool_execution_complete`&&i.add(e.tool.id),yield e;for(let e=0;e<t.length;e++){let n=r[e],a=t[e];n&&a&&!i.has(n.id)&&(yield{type:`tool_execution_complete`,tool:n,result:a})}}else for(let e of S)h.signal.aborted||y(e);if(u.size>0){let e=Promise.allSettled(u.values()).then(()=>{m.close()}),t=new Set,n=await m.next();for(;n!==null;)n.type===`mode_changed`&&(l=n.mode),n.type===`tool_execution_complete`&&t.add(n.tool.id),yield n,n=await m.next();await e;for(let e of r){let n=d.get(e.id);n&&!t.has(e.id)&&(yield{type:`tool_execution_complete`,tool:e,result:n})}}s+=r.length;let C=r.map(e=>d.get(e.id)??{id:e.id,content:`Error: tool execution did not complete`});n?.removeEventListener(`abort`,g);for(let t of e.drainEvents?.()??[])t.type===`mode_changed`&&(l=t.mode),yield t;let w=new Set([`task`]),T=(e,t)=>!(!e.rejected||w.has(r[t]?.name??``)),E=C.some((e,t)=>{if(!T(e,t))return!1;try{return JSON.parse(e.content).reason===rz.REJECTED}catch{return!1}}),D=C.some((e,t)=>{if(!T(e,t))return!1;try{return JSON.parse(e.content).reason===rz.INTERRUPTED}catch{return!1}}),O=C.some(e=>{if(!e.rejected)return!1;try{return JSON.parse(e.content).reason===rz.USER_MESSAGE}catch{return!1}});if((E||D)&&!O){yield{type:`turn_complete`};break}let k=C.map(({parsedResult:e,...t})=>t);a=k.length===1?k[0]:k;let A=r.some(e=>e.name===`exit_plan_mode`)&&C.some(e=>{if(e.rejected)return!1;try{return JSON.parse(e.content).type===`exit_plan_mode`}catch{return!1}}),j=`I want you to start implementing the plan now as you have outlined in your plan.`;if(eCe(e.model)){let t=e.dequeueAllQueuedMessage?.({includeHidden:!0});t?(i=A?`${j} ${t.message}`:t.message,t.allHidden||(yield{type:`user_message_dequeued`,content:t.message})):i=A?j:``}else i=A?j:``;yield{type:`turn_complete`}}if(o>=r){Oz.warn(`Maximum turns ({maxTurns}) exceeded`,{maxTurns:r});let e=Error(`Maximum turns (${r}) exceeded`);return yield{type:`error`,error:e},{content:c.join(``),numTurns:o,toolCallsExecuted:s,success:!1,error:e}}return Oz.info(`Conversation completed (turns={numTurns}, toolCalls={toolCallsExecuted})`,{numTurns:o,toolCallsExecuted:s}),{content:c.join(``),numTurns:o,toolCallsExecuted:s,success:!0}}catch(e){let t=e instanceof Error?e:Error(String(e));return lu(t,{context:`agent-runner`}),Oz.error(`Conversation failed after {numTurns} turns: {error}`,{numTurns:o,toolCallsExecuted:s,error:t}),yield{type:`error`,error:t},{content:c.join(``),numTurns:o,toolCallsExecuted:s,success:!1,error:t}}}const Az=ft([`codellm`,`agent`,`subagent`]);function tCe(e,t){let n=xz(t);return!n||n.allowedTools.includes(`*`)?e:e.filter(e=>YSe(t,e.name))}function nCe(e,t,n,r,i){let a=n.get(e.name)?.displayName??e.name;if(!n.isBuiltinRequest(e))return{type:`generic`,tool:e,displayName:a,toolName:a,inputSummary:JSON.stringify(e.input??{}).slice(0,200)};switch(e.name){case`read`:{let n=t._prepareResult;if(n?.resolvedPath){let t=UF(n.resolvedPath);return{type:`read_outside_directory`,tool:e,displayName:a,filePath:t,resolvedPath:t,deducedDirectory:P.dirname(t)}}return{type:`generic`,tool:e,displayName:a,toolName:a,inputSummary:JSON.stringify(e.input??{}).slice(0,200)}}case`edit`:{let n=t._prepareResult;if(n?.outsideWorkspace){let t=UF(n.resolvedPath??e.input.filePath??``);return{type:`edit_outside_directory`,tool:e,displayName:a,filePath:t,resolvedPath:t,deducedDirectory:P.dirname(t)}}return{type:`edit_file`,tool:e,displayName:a,filePath:e.input.filePath??``,originalContent:n?.currentContent??``,newContent:n?.newContent??``}}case`write`:{let n=t._prepareResult;if(n?.outsideWorkspace){let t=UF(n.resolvedPath??e.input.filePath??``);return{type:`write_outside_directory`,tool:e,displayName:a,filePath:t,resolvedPath:t,deducedDirectory:P.dirname(t),isNewFile:!n?.fileExists}}return{type:`write_file`,tool:e,displayName:a,filePath:e.input.filePath??``,originalContent:n?.currentContent??``,content:e.input.content??``,isNewFile:!n?.fileExists}}case`bash`:return{type:`run_terminal`,tool:e,displayName:a,command:e.input.command??``,cwd:r,background:!!(e.input.runInBackground??!1),unmatchedPatterns:i?.getUnmatchedBashSegments(e.input.command??``,r)??[]};case`notebook_edit`:{let n=t._prepareResult;if(n?.outsideWorkspace){let t=UF(n.resolvedPath??e.input.notebookPath??``);return{type:`notebook_edit_outside_directory`,tool:e,displayName:a,filePath:t,resolvedPath:t,deducedDirectory:P.dirname(t)}}let r=n?.notebook,i=e.input.cellId,o=``;if(i&&r?.cells){let e=r.cells.find(e=>e.id===i||e.metadata?.id===i);e&&(o=Array.isArray(e.source)?e.source.join(``):String(e.source??``))}return{type:`notebook_edit`,tool:e,displayName:a,notebookPath:e.input.notebookPath??``,cellId:i,editMode:e.input.editMode??`replace`,cellType:e.input.cellType,originalContent:o,newContent:e.input.newSource??``}}case`ask_user_question`:return{type:`ask_user_question`,tool:e,displayName:a,questions:Array.isArray(e.input.questions)?e.input.questions:[]};case`exit_plan_mode`:{let n=t._prepareResult;return{type:`exit_plan_mode`,tool:e,displayName:a,planFilePath:e.input.planFilePath??``,planContent:n?.planContent??``}}default:return{type:`generic`,tool:e,displayName:a,toolName:a,inputSummary:JSON.stringify(e.input??{}).slice(0,200)}}}async function rCe(e){let{prompt:t,subagentType:n,model:r,resume:i,parentContext:a,onProgress:o,signal:s}=e;Az.info(`Starting subagent (type={subagentType}, model={model})`,{subagentType:n,model:r??`default`});let c=xz(n);if(!c)return Az.error(`Unknown subagent type: {subagentType}`,{subagentType:n}),{success:!1,output:``,toolsExecuted:[],toolCalls:[],numTurns:0,error:`Unknown subagent type: ${n}`};let l=_H(),u=tCe(l.getApiToolDefinitions(),n),d=r??c.defaultModel??`CLAUDE_V4_5_SONNET`,f;if(i&&c.supportsResume)f=i;else try{let e=await a.apiClient.createCodellmDeploymentConversation(`CODE_LLM_NON_INTERACTIVE`,a.clientType);if(!e?.result?.deploymentConversationId)return{success:!1,output:``,toolsExecuted:[],toolCalls:[],numTurns:0,error:`Failed to create subagent conversation: no conversation ID returned`};f=e.result.deploymentConversationId}catch(e){return{success:!1,output:``,toolsExecuted:[],toolCalls:[],numTurns:0,error:`Failed to create subagent conversation: ${e instanceof Error?e.message:String(e)}`}}let p=[],m=[],h=[],g=a.permissionProvider&&a.rulesEngine&&a.getAgentMode,_=()=>a.getAgentMode?.()??Pd.Yolo,v=c?.name,y={apiClient:a.apiClient,conversationId:f,model:d,workspacePath:a.workspacePath,supportedTools:u,mcpTools:[],uploadedDocs:a.uploadedDocs,isPrintMode:!g,...v&&{subagent:v},supportsThoughtStreaming:!0,agentMode:_(),executeTools:async(e,t,n)=>{let r=[];for(let i of e){if(t?.aborted||s?.aborted)break;m.push(i.name);let e={name:i.name,input:i.input??{}};o?.({type:`tool_requested`,content:`${i.name}`,toolName:i.name,toolInput:e.input,toolId:i.id}),n?.({type:`tool_execution_start`,tool:i});let c=_(),u={...a,toolCallId:i.id,conversationId:f,agentMode:c,status:`executing`};try{let d=l.createToolInstance(i.name,i.input??{},u);await d.prepare();let f=c===Pd.Yolo&&i.name!==`ask_user_question`;if(g&&!f&&d.needsPermission()){let c=l.get(i.name)?.displayName??i.name,f=TH(i),p=a.rulesEngine.evaluate(c,f,a.workspacePath);if(p===`deny`){r.push({id:i.id,content:JSON.stringify({reason:rz.REJECTED}),rejected:!0}),e.result=`denied by rule`,h.push(e),o?.({type:`tool_complete`,content:`${i.name}`,toolName:i.name,toolId:i.id});continue}if(p!==`allow`){let c=nCe(i,d,l,a.workspacePath,a.rulesEngine);if(a.permissionProvider.needsPermission(c)){n?.({type:`status_changed`,status:Fd.WaitingForToolPermission}),a.emitEvent?.({type:`status_changed`,status:Fd.WaitingForToolPermission});let l;try{let e=a.permissionProvider.requestPermission(c),n=t||s;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{l=await Promise.race([e,r])}finally{t&&n.removeEventListener(`abort`,t)}}else l=await e}catch{r.push({id:i.id,content:JSON.stringify({reason:rz.INTERRUPTED}),rejected:!0}),e.result=`interrupted`,h.push(e),o?.({type:`tool_complete`,content:`${i.name}`,toolName:i.name,toolId:i.id});continue}if(n?.({type:`status_changed`,status:Fd.ExecutingTool}),a.emitEvent?.({type:`status_changed`,status:Fd.ExecutingTool}),l===`reject`){r.push({id:i.id,content:JSON.stringify({reason:rz.REJECTED}),rejected:!0}),e.result=`rejected`,h.push(e),o?.({type:`tool_complete`,content:`${i.name}`,toolName:i.name,toolId:i.id});continue}if(typeof l==`object`&&l.type===`reject_with_message`){r.push({id:i.id,content:JSON.stringify({reason:rz.USER_MESSAGE,message:l.message}),rejected:!0}),e.result=`rejected`,h.push(e),o?.({type:`tool_complete`,content:`${i.name}`,toolName:i.name,toolId:i.id});continue}if(l===`allowAlways`||l===`allowYolo`||l===`accept`){if(l===`allowAlways`&&(c.type===`read_outside_directory`||c.type===`write_outside_directory`||c.type===`edit_outside_directory`||c.type===`notebook_edit_outside_directory`)&&`deducedDirectory`in c){let e=a.allowEditingPaths??[],t=c.deducedDirectory;e.includes(t)||e.push(t)}else if(i.name===`exit_plan_mode`){let e=l===`allowYolo`?Pd.Yolo:l===`allowAlways`?Pd.AcceptEdits:Pd.Normal;a.setAgentMode?.(e),u.agentMode=e,n?.({type:`mode_changed`,mode:e})}else if(l===`allowAlways`){let e=Bd(c.type);a.setAgentMode?.(e),u.agentMode=e,n?.({type:`mode_changed`,mode:e})}}if(typeof l==`object`&&l.type===`accept_with_message`){r.push({id:i.id,content:JSON.stringify({reason:rz.USER_MESSAGE,message:l.message}),rejected:!0}),e.result=`accepted with message`,h.push(e),o?.({type:`tool_complete`,content:`${i.name}`,toolName:i.name,toolId:i.id});continue}if(typeof l==`object`&&l.type===`question_answers`&&d.mergeParams({answers:l.answers}),typeof l==`object`&&l.type===`allow_always_with_rule`&&a.rulesEngine.addAllowRule(l.rule),typeof l==`object`&&l.type===`allow_always_with_rules`)for(let e of l.rules)a.rulesEngine.addAllowRule(e)}}}i.name===`enter_plan_mode`&&(a.setAgentMode?.(Pd.PlanMode),u.agentMode=Pd.PlanMode,n?.({type:`mode_changed`,mode:Pd.PlanMode})),i.name===`exit_plan_mode`&&f&&(a.setAgentMode?.(Pd.Normal),u.agentMode=Pd.Normal,n?.({type:`mode_changed`,mode:Pd.Normal})),await d.execute();let p=d.formatResultForLLM(),m=d.formatResult(),_=typeof p==`string`?p:JSON.stringify(p),v=l.parse(i.name,m);r.push({id:i.id,content:_,parsedResult:v}),e.result=_}catch(t){let n=t instanceof Error?t.message:String(t);r.push({id:i.id,content:`Error: ${n}`}),e.result=`Error: ${n}`}h.push(e),o?.({type:`tool_complete`,content:`${i.name}`,toolName:i.name,toolId:i.id})}for(let t of e)r.some(e=>e.id===t.id)||r.push({id:t.id,content:JSON.stringify({reason:rz.INTERRUPTED}),rejected:!0});return r}};try{o?.({type:`status`,content:`Starting ${n} agent...`});let e=kz(y,t,s),r=await e.next();for(;!r.done;){let t=r.value;switch(t.type){case`text_delta`:p.push(t.content),o?.({type:`text`,content:t.content});break;case`thinking_delta`:o?.({type:`thinking`,content:t.content});break;case`tool_requested`:case`turn_complete`:break;case`tool_execution_complete`:p.length=0;break;case`error`:return{success:!1,output:p.join(``),toolsExecuted:m,toolCalls:h,numTurns:0,error:t.error?.message??`Unknown error`};case`credits`:a.emitEvent?.(t);break;case`mode_changed`:a.emitEvent?.(t);break;case`session_info`:break;case`status_changed`:case`notification`:break}r=await e.next()}let i=r.value;return Az.info(`Subagent completed (type={subagentType}, turns={numTurns}, tools={toolCount})`,{subagentType:n,numTurns:i.numTurns,toolCount:m.length}),{success:i.success,output:p.join(``),toolsExecuted:m,toolCalls:h,numTurns:i.numTurns,...i.error&&{error:i.error.message}}}catch(e){let t=e instanceof Error?e.message:String(e);return lu(e instanceof Error?e:Error(t),{context:`subagent-runner`}),Az.error(`Subagent failed (type={subagentType}): {error}`,{subagentType:n,error:t}),{success:!1,output:p.join(``),toolsExecuted:m,toolCalls:h,numTurns:0,error:t}}}const jz=ft([`codellm`,`agent`,`tools`,`task`]);var Mz=class e extends sz{name=`task`;displayName=`Task`;description=`Launch a new agent to handle complex, multi-step tasks autonomously.
|
|
1900
1900
|
|
|
1901
1901
|
The Task tool launches specialized agents (subprocesses) that autonomously handle complex tasks. Each agent type has specific capabilities and tools available to it.
|
|
1902
1902
|
|
|
@@ -75104,8 +75104,8 @@ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,`$1$2`).replace(/\
|
|
|
75104
75104
|
`)+1;for(;e!==0;)this.onNewLine(this.offset+e),e=this.source.indexOf(`
|
|
75105
75105
|
`,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(`
|
|
75106
75106
|
`)+1;for(;e!==0;)this.onNewLine(this.offset+e),e=this.source.indexOf(`
|
|
75107
|
-
`,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())}}}})),iAe=G((e=>{var t=Vq(),n=Mq(),r=Nq(),i=dq(),a=ZK(),o=Wq(),s=Gq();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})),aAe=G((e=>{var t=Vq(),n=Mq(),r=jq(),i=Nq(),a=iq(),o=ZK(),s=mq(),c=aq(),l=gq(),u=vq();Hq();var d=Uq(),f=Wq(),p=Gq(),m=iAe(),h=QK();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 oAe(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,aAe.parse)(i);return e&&typeof e==`object`&&!Array.isArray(e)?{data:e,body:a}:{data:{},body:a}}catch{return{data:{},body:e}}}function sAe(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``)}const cAe=ft([`codellm`,`agent`,`skills`]),Kq=new class{skills=new Map;async loadSkills(e,t){let r=await Qwe(t??`cli`),i=P.join(n.homedir(),gn.configDirName,`skills`),a=e?P.join(e,gn.localConfigDirName,`skills`):void 0,o=await this.discoverSkills(r,`builtin`),s=await this.discoverSkills(i,`global`),c=a?await this.discoverSkills(a,`project`):[];this.skills.clear();for(let e of o)this.skills.set(e.id,e);for(let e of s)this.skills.set(e.id,e);for(let e of c)this.skills.set(e.id,e);cAe.info`skills loaded: builtin=${o.length} global=${s.length} project=${c.length} clientKind=${t??`cli`}`}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=P.join(e,i.name),a=await this.parseSkillFile(r,!1,t);a&&n.push(a)}else if(i.isDirectory()){let r=P.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}=oAe(await Te.readFile(e,`utf-8`)),i=sAe(t?P.basename(P.dirname(e)):P.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(` `)}}},qq=ft([`codellm`,`agent`,`tools`,`diagnostics`]);var lAe=class e extends ZV{name=`get_diagnostics`;displayName=`GetDiagnostics`;description=`Get IDE diagnostics (errors, warnings, info) for a file or all open files.`;_provider;static Parameters=PR({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;qq.debug`Getting diagnostics${e.uri?` for ${e.uri}`:` for all files`}`;let r=await this._provider.getDiagnostics(n);return qq.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=iz(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`}}}},uAe=class extends sz{includeInApiDefinitions=!1};const Jq=ft([`codellm`,`agent`,`tools`,`mcp`]);var dAe=class extends uAe{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 PR(r)}jsonSchemaToZod(e){switch(e.type){case`string`:return e.enum?WR(e.enum):Y();case`number`:case`integer`:return HSe;case`boolean`:return mz;case`array`:return e.items?MR(this.jsonSchemaToZod(e.items)):MR(AR());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 PR(t)}return HR(Y(),AR());case`null`:return kR();default:return e.oneOf?this.jsonSchemaToZod(e.oneOf[0]):AR()}}async execute(e,t){if(Jq.debug`Executing MCP tool: ${this.name} (server=${this.mcpToolDefinition.serverId})`,!t.mcpService)return Jq.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 lu(e instanceof Error?e:Error(String(e)),{context:`mcp-tool-execution`}),Jq.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=iz(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`}}};function fAe(e){return e.length>1e4?!0:e.split(/\r\n|\r|\n/).length>5e3}var pAe=class{_tmpDir=null;_counter=0;_ensureDir(){if(!this._tmpDir){let e=P.join(n.homedir(),gn.configDirName,`tmp`);m.mkdirSync(e,{recursive:!0}),this._tmpDir=m.mkdtempSync(P.join(e,`codellm-prompt-`))}return this._tmpDir}savePrompt(e){let t=this._ensureDir();this._counter++;let n=P.join(t,`prompt-${this._counter}.txt`);return m.writeFileSync(n,e,`utf-8`),n}cleanup(){if(this._tmpDir){try{m.rmSync(this._tmpDir,{recursive:!0,force:!0})}catch{}this._tmpDir=null,this._counter=0}}};const mAe={run_in_terminal:`bash`,get_terminal_output:`bash_output`,fetch_url:`web_fetch`},hAe={bash:{id:`shellId`,isBackground:`runInBackground`},bash_output:{id:`shellId`}};function Yq(e){let t=mAe[e.name];t&&(e.name=t);let n=hAe[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 Xq(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)Yq(e)}if(Array.isArray(e.segments))for(let t of e.segments)Xq(t)}function gAe(e){for(let t of e){if(t.toolUseRequest){let e=Array.isArray(t.toolUseRequest)?t.toolUseRequest:[t.toolUseRequest];for(let t of e)Yq(t)}if(Array.isArray(t.segments))for(let e of t.segments)Xq(e)}}var Zq=class{sessionId;_logger=ft([`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 pAe;_swapFolder=null;_setFolder=null;onAutoRestart=null;mcp;rules;constructor(e){let t=UF(VF(e.primaryWorkspace)),n=Array.from(new Set([t,...e.allowedDirectories.map(e=>UF(VF(e)))]));this._config={...e,primaryWorkspace:t,allowedDirectories:n},this.sessionId=crypto.randomUUID(),this._mode=e.mode??Pd.Normal,this._model=e.model??``,this._logger.info(`Creating AgentSession (workspace={workspace}, mode={mode})`,{workspace:t,mode:this._mode}),this._workspace=new oEe(t),this._terminalService=new Ike(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=_H(),e.disabledBuiltinTools?.length&&this._registry.setDisabledTools(e.disabledBuiltinTools),e.diagnosticsProvider&&this._registry.register(new lAe(e.diagnosticsProvider)),this._mcpService=new YK;let r=e.config?.get(`permissions`)??{},i={allow:[...r.allow??[],...e.permissionRules?.allow??[]],deny:[...r.deny??[],...e.permissionRules?.deny??[]],ask:[...r.ask??[],...e.permissionRules?.ask??[]]};this._rulesEngine=new TTe({rules:i,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=UF(VF(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?Kq.loadSkills(this._config.primaryWorkspace,this._config.clientType?.toLowerCase()):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(!gH.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=VF(e.input.filePath??``),r=UF(P.isAbsolute(t)?t:P.resolve(this._config.primaryWorkspace,t));return{type:`read_outside_directory`,tool:e,displayName:n,filePath:r,resolvedPath:r,deducedDirectory:P.dirname(r)}}case`edit`:{let r=t._prepareResult;if(r?.outsideWorkspace){let t=UF(r.resolvedPath??e.input.filePath??``);return{type:`edit_outside_directory`,tool:e,displayName:n,filePath:t,resolvedPath:t,deducedDirectory:P.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=UF(r.resolvedPath??e.input.filePath??``);return{type:`write_outside_directory`,tool:e,displayName:n,filePath:t,resolvedPath:t,deducedDirectory:P.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=UF(r.resolvedPath??e.input.notebookPath??``);return{type:`notebook_edit_outside_directory`,tool:e,displayName:n,filePath:t,resolvedPath:t,deducedDirectory:P.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 a=new AbortController,o=()=>a.abort(`interrupted`);n&&(n.aborted?a.abort(`interrupted`):n.addEventListener(`abort`,o,{once:!0}));let s=[],c=(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 o=async t=>{if(a.signal.aborted)return{resolved:!0,result:c(t,JSON.stringify({reason:rz.INTERRUPTED}),{rejected:!0})};let o={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:a,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:c(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??{},o);if(await e.prepare(),t.name===`edit`&&gH.isBuiltinRequest(t)&&!e._prepareResult?.error){let n=e._prepareResult,a=o.workspacePath,s=o.plansDir??P.join(i(),gn.configDirName,`plans`),c=GF(P.resolve(a,t.input.filePath??``),P.resolve(a,s)),l={originalContent:n?.currentContent??``,newContent:n?.newContent??``,isPlanFile:c,isNewFile:!(n?.fileExists??!0)},u={type:`tool_display_data`,toolCallId:t.id,data:l};r?.(u),this._toolEventBuffer.push(u)}if(t.name===`notebook_edit`&&gH.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`&&gH.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 a=this._mode===Pd.Yolo&&t.name!==`ask_user_question`;if(!a&&e.needsPermission()){let i=this._registry.get(t.name)?.displayName??t.name,a=TH(t),s=this._rulesEngine.evaluate(i,a,this._config.primaryWorkspace);if(s===`deny`)return{resolved:!0,result:c(t,JSON.stringify({reason:rz.REJECTED}),{rejected:!0})};if(s!==`allow`){let i=this._buildPermissionRequest(t,e);if(this._config.permissionProvider.needsPermission(i)){let a={type:`status_changed`,status:Fd.WaitingForToolPermission};r?.(a),this._toolEventBuffer.push(a);let s;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{s=await Promise.race([e,r])}finally{t&&n.removeEventListener(`abort`,t)}}else s=await e}catch{return{resolved:!0,result:c(t,JSON.stringify({reason:rz.INTERRUPTED}),{rejected:!0})}}if(r?.({type:`status_changed`,status:Fd.ExecutingTool}),this._toolEventBuffer.push({type:`status_changed`,status:Fd.ExecutingTool}),s===`reject`)return{resolved:!0,result:c(t,JSON.stringify({reason:rz.REJECTED}),{rejected:!0})};if(typeof s==`object`&&s.type===`reject_with_message`)return{resolved:!0,result:c(t,JSON.stringify({reason:rz.USER_MESSAGE,message:s.message}),{rejected:!0})};if(s===`allowAlways`||s===`allowYolo`||s===`accept`){if(s===`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=s===`allowYolo`?Pd.Yolo:s===`allowAlways`?Pd.AcceptEdits:Pd.Normal;this._mode=e,o.agentMode=e,r?.({type:`mode_changed`,mode:e}),this._toolEventBuffer.push({type:`mode_changed`,mode:e})}else if(s===`allowAlways`){let e=Bd(i.type);this._mode=e,o.agentMode=e,r?.({type:`mode_changed`,mode:e}),this._toolEventBuffer.push({type:`mode_changed`,mode:e})}}if(typeof s==`object`&&s.type===`accept_with_message`&&this.nq(s.message),typeof s==`object`&&s.type===`question_answers`&&e.mergeParams({answers:s.answers}),typeof s==`object`&&s.type===`allow_always_with_rule`&&(this._rulesEngine.addAllowRule(s.rule),this._config.config)){let e=this._config.config.get(`permissions`)??{},t=[...e.allow??[],s.rule];this._config.config.set(`permissions`,{...e,allow:t},`local`)}if(typeof s==`object`&&s.type===`allow_always_with_rules`){for(let e of s.rules)this._rulesEngine.addAllowRule(e);if(this._config.config){let e=this._config.config.get(`permissions`)??{},t=[...e.allow??[],...s.rules];this._config.config.set(`permissions`,{...e,allow:t},`local`)}}}}}return t.name===`enter_plan_mode`&&(this._mode=Pd.PlanMode,o.agentMode=Pd.PlanMode,r?.({type:`mode_changed`,mode:Pd.PlanMode}),this._toolEventBuffer.push({type:`mode_changed`,mode:Pd.PlanMode})),t.name===`exit_plan_mode`&&a&&(this._mode=Pd.Normal,o.agentMode=Pd.Normal,r?.({type:`mode_changed`,mode:Pd.Normal}),this._toolEventBuffer.push({type:`mode_changed`,mode:Pd.Normal})),{resolved:!1,call:t,instance:e,ctx:o}}catch(e){return a.signal.aborted?{resolved:!0,result:c(t,JSON.stringify({reason:rz.INTERRUPTED}),{rejected:!0})}:{resolved:!0,result:c(t,`Error: ${e instanceof Error?e.message:String(e)}`)}}},l=async e=>{try{if(await e.instance.execute(),a.signal.aborted)return c(e.call,JSON.stringify({reason:rz.INTERRUPTED}),{rejected:!0});let t=e.instance.formatResultForLLM(),n=e.instance.formatResult(),r=typeof t==`string`?t:JSON.stringify(t);return c(e.call,r,{storageContent:n===r?void 0:n})}catch(t){if(a.signal.aborted)return c(e.call,JSON.stringify({reason:rz.INTERRUPTED}),{rejected:!0});let n=t instanceof Error?t.message:String(t);return c(e.call,`Error: ${n}`)}},u=0,d=!1;for(;u<t.length;){let e=e=>this._registry.get(e.name)?.concurrency(e.input,this._config.primaryWorkspace)??!1;if(d){let n=t[u],i=!!e(n),a=this._registry.get(n.name),o=a?!a.isReadonly:!1;if(i||o){let e=c(n,oz);s.push(e),r?.({type:`tool_execution_complete`,tool:n,result:e}),u++;continue}}if(e(t[u])){let n=u+1;for(;n<t.length&&e(t[n]);)n++;if(n-u>1){let i=t.slice(u,n),a=i.map(e);u=n;let f=[[]],p=[new Set];for(let e=0;e<i.length;e++){let t=a[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=c(i[t],oz);s.push(e),r?.({type:`tool_execution_complete`,tool:i[t],result:e})}continue}for(let t of e)m.set(t,await o(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 l(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);s.push(n),!g&&!n.rejected&&n.content.startsWith(`Error:`)&&(g=!0)}}g&&(d=!0);continue}}let n=t[u];u++;let i=await o(n);if(i.resolved){s.push(i.result),r?.({type:`tool_execution_complete`,tool:n,result:i.result});continue}let a=await l(i);s.push(a),r?.({type:`tool_execution_complete`,tool:n,result:a})}return s}finally{n&&n.removeEventListener(`abort`,o)}}}async createConversation(){let e=await this._config.apiClient.createCodellmDeploymentConversation(this._config.isPrintMode?gn.nonInteractiveAgentType:gn.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;gAe(n);let i=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?gn.nonInteractiveAgentType:gn.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=iz(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 fAe(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(!Cu(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 wz(n)}this._running=!0,this._abortController=new AbortController;let n=this._buildExecuteTools(this._conversationId);try{yield{type:`status_changed`,status:Fd.Submitted};let r=this._rewriteIfLargePrompt(e),i=!0;for(;;){let e=this._mcpService.getAbacusMcpTools();e.length>0&&this._registry.registerMCPTools(e.map(e=>new dAe(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:Sz().map(e=>({name:e})),...e.length>0&&{mcpTools:e},...this._rules.length>0&&{rules:this._rules},...this._config.enableSkills&&(()=>{let e=Kq.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:P.isAbsolute(t.currentFile)?t.currentFile:P.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(`
|
|
75108
|
-
`)),allHidden:t.every(e=>e.hidden)}}};this._swapFolder=null,this._setFolder=null;let c=kz(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:Fd.Streaming}):e.type===`tool_requested`&&(yield{type:`status_changed`,status:Fd.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(`
|
|
75107
|
+
`,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())}}}})),iAe=G((e=>{var t=Vq(),n=Mq(),r=Nq(),i=dq(),a=ZK(),o=Wq(),s=Gq();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})),aAe=G((e=>{var t=Vq(),n=Mq(),r=jq(),i=Nq(),a=iq(),o=ZK(),s=mq(),c=aq(),l=gq(),u=vq();Hq();var d=Uq(),f=Wq(),p=Gq(),m=iAe(),h=QK();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 oAe(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,aAe.parse)(i);return e&&typeof e==`object`&&!Array.isArray(e)?{data:e,body:a}:{data:{},body:a}}catch{return{data:{},body:e}}}function sAe(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``)}const cAe=ft([`codellm`,`agent`,`skills`]),Kq=new class{skills=new Map;async loadSkills(e,t){let r=await Qwe(t??`cli`),i=P.join(n.homedir(),gn.configDirName,`skills`),a=e?P.join(e,gn.localConfigDirName,`skills`):void 0,o=await this.discoverSkills(r,`builtin`),s=await this.discoverSkills(i,`global`),c=a?await this.discoverSkills(a,`project`):[];this.skills.clear();for(let e of o)this.skills.set(e.id,e);for(let e of s)this.skills.set(e.id,e);for(let e of c)this.skills.set(e.id,e);cAe.info`skills loaded: builtin=${o.length} global=${s.length} project=${c.length} clientKind=${t??`cli`}`}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=P.join(e,i.name),a=await this.parseSkillFile(r,!1,t);a&&n.push(a)}else if(i.isDirectory()){let r=P.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}=oAe(await Te.readFile(e,`utf-8`)),i=sAe(t?P.basename(P.dirname(e)):P.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(` `)}}},qq=ft([`codellm`,`agent`,`tools`,`diagnostics`]);var lAe=class e extends ZV{name=`get_diagnostics`;displayName=`GetDiagnostics`;description=`Get IDE diagnostics (errors, warnings, info) for a file or all open files.`;_provider;static Parameters=PR({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;qq.debug`Getting diagnostics${e.uri?` for ${e.uri}`:` for all files`}`;let r=await this._provider.getDiagnostics(n);return qq.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=iz(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`}}}},uAe=class extends sz{includeInApiDefinitions=!1};const Jq=ft([`codellm`,`agent`,`tools`,`mcp`]);var dAe=class extends uAe{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 PR(r)}jsonSchemaToZod(e){switch(e.type){case`string`:return e.enum?WR(e.enum):Y();case`number`:case`integer`:return HSe;case`boolean`:return mz;case`array`:return e.items?MR(this.jsonSchemaToZod(e.items)):MR(AR());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 PR(t)}return HR(Y(),AR());case`null`:return kR();default:return e.oneOf?this.jsonSchemaToZod(e.oneOf[0]):AR()}}async execute(e,t){if(Jq.debug`Executing MCP tool: ${this.name} (server=${this.mcpToolDefinition.serverId})`,!t.mcpService)return Jq.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 lu(e instanceof Error?e:Error(String(e)),{context:`mcp-tool-execution`}),Jq.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=iz(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`}}};function fAe(e){return e.length>1e4?!0:e.split(/\r\n|\r|\n/).length>5e3}var pAe=class{_tmpDir=null;_counter=0;_ensureDir(){if(!this._tmpDir){let e=P.join(n.homedir(),gn.configDirName,`tmp`);m.mkdirSync(e,{recursive:!0}),this._tmpDir=m.mkdtempSync(P.join(e,`codellm-prompt-`))}return this._tmpDir}savePrompt(e){let t=this._ensureDir();this._counter++;let n=P.join(t,`prompt-${this._counter}.txt`);return m.writeFileSync(n,e,`utf-8`),n}cleanup(){if(this._tmpDir){try{m.rmSync(this._tmpDir,{recursive:!0,force:!0})}catch{}this._tmpDir=null,this._counter=0}}};const mAe={run_in_terminal:`bash`,get_terminal_output:`bash_output`,fetch_url:`web_fetch`},hAe={bash:{id:`shellId`,isBackground:`runInBackground`},bash_output:{id:`shellId`}};function Yq(e){let t=mAe[e.name];t&&(e.name=t);let n=hAe[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 Xq(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)Yq(e)}if(Array.isArray(e.segments))for(let t of e.segments)Xq(t)}function gAe(e){for(let t of e){if(t.toolUseRequest){let e=Array.isArray(t.toolUseRequest)?t.toolUseRequest:[t.toolUseRequest];for(let t of e)Yq(t)}if(Array.isArray(t.segments))for(let e of t.segments)Xq(e)}}var Zq=class{sessionId;_logger=ft([`codellm`,`agent`,`session`]);_workspace;_terminalService;_registry;_mcpService;_config;_conversationId=null;_mode;_model;_running=!1;_abortController=null;_initialized=!1;_uploadedDocs=new Set;_rules=[];_markdownContext=``;_agentsMdContent=void 0;_agentsMdSentInConversation=!1;_rulesEngine;_toolEventBuffer=[];_messageQueue=[];_promptFileManager=new pAe;_swapFolder=null;_setFolder=null;onAutoRestart=null;mcp;rules;constructor(e){let t=UF(VF(e.primaryWorkspace)),n=Array.from(new Set([t,...e.allowedDirectories.map(e=>UF(VF(e)))]));this._config={...e,primaryWorkspace:t,allowedDirectories:n},this.sessionId=crypto.randomUUID(),this._mode=e.mode??Pd.Normal,this._model=e.model??``,this._logger.info(`Creating AgentSession (workspace={workspace}, mode={mode})`,{workspace:t,mode:this._mode}),this._workspace=new oEe(t),this._terminalService=new Ike(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=_H(),e.disabledBuiltinTools?.length&&this._registry.setDisabledTools(e.disabledBuiltinTools),e.diagnosticsProvider&&this._registry.register(new lAe(e.diagnosticsProvider)),this._mcpService=new YK;let r=e.config?.get(`permissions`)??{},i={allow:[...r.allow??[],...e.permissionRules?.allow??[]],deny:[...r.deny??[],...e.permissionRules?.deny??[]],ask:[...r.ask??[],...e.permissionRules?.ask??[]]};this._rulesEngine=new TTe({rules:i,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=UF(VF(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?Kq.loadSkills(this._config.primaryWorkspace,this._config.clientType?.toLowerCase()):Promise.resolve(),this._config.sendAgentMd?this._loadAgentMd():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=``}}}async _loadAgentMd(){let e=this._config.primaryWorkspace;try{let t=(await Te.readdir(e)).find(e=>e.toLowerCase()===`agents.md`);t&&(this._agentsMdContent=await Te.readFile(P.join(e,t),`utf-8`))}catch{}}_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(!gH.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=VF(e.input.filePath??``),r=UF(P.isAbsolute(t)?t:P.resolve(this._config.primaryWorkspace,t));return{type:`read_outside_directory`,tool:e,displayName:n,filePath:r,resolvedPath:r,deducedDirectory:P.dirname(r)}}case`edit`:{let r=t._prepareResult;if(r?.outsideWorkspace){let t=UF(r.resolvedPath??e.input.filePath??``);return{type:`edit_outside_directory`,tool:e,displayName:n,filePath:t,resolvedPath:t,deducedDirectory:P.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=UF(r.resolvedPath??e.input.filePath??``);return{type:`write_outside_directory`,tool:e,displayName:n,filePath:t,resolvedPath:t,deducedDirectory:P.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=UF(r.resolvedPath??e.input.notebookPath??``);return{type:`notebook_edit_outside_directory`,tool:e,displayName:n,filePath:t,resolvedPath:t,deducedDirectory:P.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 a=new AbortController,o=()=>a.abort(`interrupted`);n&&(n.aborted?a.abort(`interrupted`):n.addEventListener(`abort`,o,{once:!0}));let s=[],c=(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 o=async t=>{if(a.signal.aborted)return{resolved:!0,result:c(t,JSON.stringify({reason:rz.INTERRUPTED}),{rejected:!0})};let o={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:a,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:c(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??{},o);if(await e.prepare(),t.name===`edit`&&gH.isBuiltinRequest(t)&&!e._prepareResult?.error){let n=e._prepareResult,a=o.workspacePath,s=o.plansDir??P.join(i(),gn.configDirName,`plans`),c=GF(P.resolve(a,t.input.filePath??``),P.resolve(a,s)),l={originalContent:n?.currentContent??``,newContent:n?.newContent??``,isPlanFile:c,isNewFile:!(n?.fileExists??!0)},u={type:`tool_display_data`,toolCallId:t.id,data:l};r?.(u),this._toolEventBuffer.push(u)}if(t.name===`notebook_edit`&&gH.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`&&gH.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 a=this._mode===Pd.Yolo&&t.name!==`ask_user_question`;if(!a&&e.needsPermission()){let i=this._registry.get(t.name)?.displayName??t.name,a=TH(t),s=this._rulesEngine.evaluate(i,a,this._config.primaryWorkspace);if(s===`deny`)return{resolved:!0,result:c(t,JSON.stringify({reason:rz.REJECTED}),{rejected:!0})};if(s!==`allow`){let i=this._buildPermissionRequest(t,e);if(this._config.permissionProvider.needsPermission(i)){let a={type:`status_changed`,status:Fd.WaitingForToolPermission};r?.(a),this._toolEventBuffer.push(a);let s;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{s=await Promise.race([e,r])}finally{t&&n.removeEventListener(`abort`,t)}}else s=await e}catch{return{resolved:!0,result:c(t,JSON.stringify({reason:rz.INTERRUPTED}),{rejected:!0})}}if(r?.({type:`status_changed`,status:Fd.ExecutingTool}),this._toolEventBuffer.push({type:`status_changed`,status:Fd.ExecutingTool}),s===`reject`)return{resolved:!0,result:c(t,JSON.stringify({reason:rz.REJECTED}),{rejected:!0})};if(typeof s==`object`&&s.type===`reject_with_message`)return{resolved:!0,result:c(t,JSON.stringify({reason:rz.USER_MESSAGE,message:s.message}),{rejected:!0})};if(s===`allowAlways`||s===`allowYolo`||s===`accept`){if(s===`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=s===`allowYolo`?Pd.Yolo:s===`allowAlways`?Pd.AcceptEdits:Pd.Normal;this._mode=e,o.agentMode=e,r?.({type:`mode_changed`,mode:e}),this._toolEventBuffer.push({type:`mode_changed`,mode:e})}else if(s===`allowAlways`){let e=Bd(i.type);this._mode=e,o.agentMode=e,r?.({type:`mode_changed`,mode:e}),this._toolEventBuffer.push({type:`mode_changed`,mode:e})}}if(typeof s==`object`&&s.type===`accept_with_message`&&this.nq(s.message),typeof s==`object`&&s.type===`question_answers`&&e.mergeParams({answers:s.answers}),typeof s==`object`&&s.type===`allow_always_with_rule`&&(this._rulesEngine.addAllowRule(s.rule),this._config.config)){let e=this._config.config.get(`permissions`)??{},t=[...e.allow??[],s.rule];this._config.config.set(`permissions`,{...e,allow:t},`local`)}if(typeof s==`object`&&s.type===`allow_always_with_rules`){for(let e of s.rules)this._rulesEngine.addAllowRule(e);if(this._config.config){let e=this._config.config.get(`permissions`)??{},t=[...e.allow??[],...s.rules];this._config.config.set(`permissions`,{...e,allow:t},`local`)}}}}}return t.name===`enter_plan_mode`&&(this._mode=Pd.PlanMode,o.agentMode=Pd.PlanMode,r?.({type:`mode_changed`,mode:Pd.PlanMode}),this._toolEventBuffer.push({type:`mode_changed`,mode:Pd.PlanMode})),t.name===`exit_plan_mode`&&a&&(this._mode=Pd.Normal,o.agentMode=Pd.Normal,r?.({type:`mode_changed`,mode:Pd.Normal}),this._toolEventBuffer.push({type:`mode_changed`,mode:Pd.Normal})),{resolved:!1,call:t,instance:e,ctx:o}}catch(e){return a.signal.aborted?{resolved:!0,result:c(t,JSON.stringify({reason:rz.INTERRUPTED}),{rejected:!0})}:{resolved:!0,result:c(t,`Error: ${e instanceof Error?e.message:String(e)}`)}}},l=async e=>{try{if(await e.instance.execute(),a.signal.aborted)return c(e.call,JSON.stringify({reason:rz.INTERRUPTED}),{rejected:!0});let t=e.instance.formatResultForLLM(),n=e.instance.formatResult(),r=typeof t==`string`?t:JSON.stringify(t);return c(e.call,r,{storageContent:n===r?void 0:n})}catch(t){if(a.signal.aborted)return c(e.call,JSON.stringify({reason:rz.INTERRUPTED}),{rejected:!0});let n=t instanceof Error?t.message:String(t);return c(e.call,`Error: ${n}`)}},u=0,d=!1;for(;u<t.length;){let e=e=>this._registry.get(e.name)?.concurrency(e.input,this._config.primaryWorkspace)??!1;if(d){let n=t[u],i=!!e(n),a=this._registry.get(n.name),o=a?!a.isReadonly:!1;if(i||o){let e=c(n,oz);s.push(e),r?.({type:`tool_execution_complete`,tool:n,result:e}),u++;continue}}if(e(t[u])){let n=u+1;for(;n<t.length&&e(t[n]);)n++;if(n-u>1){let i=t.slice(u,n),a=i.map(e);u=n;let f=[[]],p=[new Set];for(let e=0;e<i.length;e++){let t=a[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=c(i[t],oz);s.push(e),r?.({type:`tool_execution_complete`,tool:i[t],result:e})}continue}for(let t of e)m.set(t,await o(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 l(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);s.push(n),!g&&!n.rejected&&n.content.startsWith(`Error:`)&&(g=!0)}}g&&(d=!0);continue}}let n=t[u];u++;let i=await o(n);if(i.resolved){s.push(i.result),r?.({type:`tool_execution_complete`,tool:n,result:i.result});continue}let a=await l(i);s.push(a),r?.({type:`tool_execution_complete`,tool:n,result:a})}return s}finally{n&&n.removeEventListener(`abort`,o)}}}async createConversation(){let e=await this._config.apiClient.createCodellmDeploymentConversation(this._config.isPrintMode?gn.nonInteractiveAgentType:gn.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;gAe(n);let i=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(),this._agentsMdSentInConversation=!1}async deleteConversation(e){await this._config.apiClient.deleteDeploymentConversation?.({deploymentConversationId:e}),this._conversationId===e&&(this._conversationId=null,this._uploadedDocs.clear(),this._agentsMdSentInConversation=!1)}async listConversations(){return((await this._config.apiClient.getConversationsList(this._config.isPrintMode?gn.nonInteractiveAgentType:gn.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=iz(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 fAe(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(!Cu(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 wz(n)}this._running=!0,this._abortController=new AbortController;let n=this._buildExecuteTools(this._conversationId);try{yield{type:`status_changed`,status:Fd.Submitted};let r=this._rewriteIfLargePrompt(e),i=!0;for(;;){let e=this._mcpService.getAbacusMcpTools();e.length>0&&this._registry.registerMCPTools(e.map(e=>new dAe(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:Sz().map(e=>({name:e})),...e.length>0&&{mcpTools:e},...this._rules.length>0&&{rules:this._rules},...this._config.sendAgentMd&&!this._agentsMdSentInConversation&&this._agentsMdContent!==void 0&&{agentsMd:this._agentsMdContent},...this._config.enableSkills&&(()=>{let e=Kq.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:P.isAbsolute(t.currentFile)?t.currentFile:P.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(`
|
|
75108
|
+
`)),allHidden:t.every(e=>e.hidden)}}};this._swapFolder=null,this._setFolder=null,s.agentsMd!==void 0&&(this._agentsMdSentInConversation=!0);let c=kz(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:Fd.Streaming}):e.type===`tool_requested`&&(yield{type:`status_changed`,status:Fd.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(`
|
|
75109
75109
|
`)),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:Fd.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=UF(VF(e));for(let e of this._config.allowedDirectories)if(GF(t,e))return{allowed:!0,coveredBy:e};return{allowed:!1}}addAllowedDirectory(e,t){let n=UF(VF(e));for(let e of this._config.allowedDirectories)if(GF(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=UF(VF(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)}},_Ae=class{needsPermission(e){return!1}async requestPermission(e){return`accept`}},Qq=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)}},vAe=class{async read(){let e={},t=gn.envPrefix,n=gn.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=hz.safeParse(s);t.success&&t.data!==void 0&&(e.autoUpdate=t.data)}return e}},yAe=class{configPath;constructor(){this.configPath=P.join(i(),gn.configDirName,gn.configFileName)}async read(){try{let e=await b.readFile(this.configPath,`utf-8`);return JSON.parse(e)}catch{return{}}}async write(e){let t=P.dirname(this.configPath);await b.mkdir(t,{recursive:!0}),await b.writeFile(this.configPath,JSON.stringify(e,null,2),`utf-8`)}},bAe=class{configPath;constructor(e){this.configPath=P.join(e,gn.localConfigDirName,gn.configFileName)}async read(){try{let e=await b.readFile(this.configPath,`utf-8`);return JSON.parse(e)}catch{return{}}}async write(e){let t=P.dirname(this.configPath);await b.mkdir(t,{recursive:!0}),await b.writeFile(this.configPath,JSON.stringify(e,null,2),`utf-8`)}};const xAe=ft([`codellm`,`agent`,`config`]);function $q(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]=$q(n[t],r):n[t]=r)}return n}const eJ={allowedDirectories:[],primaryWorkspace:``,logLevel:`info`};var tJ=class{sources;cache=null;constructor(e){this.sources=[new yAe,new bAe(e.cwd),...e.extraSources??[],new vAe]}async load(){let e={...eJ};for(let t of this.sources){let n=await t.read();e=$q(e,n)}this.cache=e,xAe.info`config loaded from ${this.sources.length} sources`}get(e){return this.cache?this.cache[e]??eJ[e]:eJ[e]}getAll(){return this.cache??eJ}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)}};const nJ=ft([`codellm`,`agent`,`native-notifier`]),SAe={complete:`Glass`,"action-required":`Ping`},CAe={complete:`complete`,"action-required":`dialog-warning`};function rJ(e){try{oe(e,{windowsHide:!0},e=>{e&&(nJ.warn`Notification sound command failed: ${e}`,lu(e,{context:`native-notifier`,phase:`play-sound`}))})}catch(e){nJ.warn`Notification sound exec threw synchronously: ${e}`,lu(e instanceof Error?e:Error(String(e)),{context:`native-notifier`,phase:`play-sound-sync`})}}function wAe(e){let t=process.platform;if(t===`darwin`)rJ(`afplay /System/Library/Sounds/${SAe[e]}.aiff`);else if(t===`win32`)rJ(`powershell -NoProfile -c "[console]::beep(${e===`complete`?880:440},400)"`);else{let t=CAe[e];rJ(`paplay /usr/share/sounds/freedesktop/stereo/${t}.oga 2>/dev/null || aplay /usr/share/sounds/freedesktop/stereo/${t}.oga 2>/dev/null || true`)}}function TAe(e,t,n,r){let i={title:e,message:t,sound:!1,...r?.iconPath&&{icon:r.iconPath},...r?.activateBundleId&&{activate:r.activateBundleId}},a=e=>{e&&(nJ.warn`OS notification failed: ${e}`,lu(e instanceof Error?e:Error(String(e)),{context:`native-notifier`,phase:`send-notification`,platform:process.platform,arch:process.arch}))};Promise.resolve().then(()=>{U.notify(i,e=>a(e))}).catch(a)}ft([`codellm`,`agent`,`history`]);var iJ=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??te(i(),gn.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(`
|
|
75110
75110
|
`)+1,s=a.slice(o).split(`
|
|
75111
75111
|
`).filter(Boolean);for(let e of s)try{let t=JSON.parse(e);t.message&&t.source&&this.entries.push(t)}catch{}this.entries.length>this.maxEntries&&(this.entries=this.entries.slice(-this.maxEntries))}finally{await t.close()}}catch{}}}append(e){let t=e.trimStart();if(!t)return;let n={ts:new Date().toISOString(),source:this.source,message:t,multiline:t.includes(`
|
|
@@ -75178,11 +75178,11 @@ No matching component was found for:
|
|
|
75178
75178
|
* This source code is licensed under the MIT license found in the
|
|
75179
75179
|
* LICENSE file in the root directory of this source tree.
|
|
75180
75180
|
*/
|
|
75181
|
-
var bPe=G((e=>{var t=SY().__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;e.c=function(e){return t.H.useMemoCache(e)}})),oQ=G(((e,t)=>{t.exports=bPe()}))();function $(e){let t=(0,oQ.c)(14),{color:n,backgroundColor:r,dimColor:i,bold:a,italic:o,underline:s,strikethrough:c,inverse:l,wrap:u,transform:d,children:f}=e,p=i===void 0?!1:i,m=a===void 0?!1:a,h=o===void 0?!1:o,g=s===void 0?!1:s,_=c===void 0?!1:c,v=l===void 0?!1:l,y=u===void 0?`wrap`:u;if(f==null)return null;let b;t[0]!==r||t[1]!==m||t[2]!==n||t[3]!==p||t[4]!==v||t[5]!==h||t[6]!==_||t[7]!==g||t[8]!==d?(b=e=>(p&&(e=JZ().dim().render(e)),n&&(e=qZ(e,n,`foreground`)),r&&(e=qZ(e,r,`background`)),m&&(e=JZ().bold().render(e)),h&&(e=JZ().italic().render(e)),g&&(e=JZ().underline().render(e)),_&&(e=JZ().strikethrough().render(e)),v&&(e=JZ().reverse().render(e)),d&&(e=d(e)),e),t[0]=r,t[1]=m,t[2]=n,t[3]=p,t[4]=v,t[5]=h,t[6]=_,t[7]=g,t[8]=d,t[9]=b):b=t[9];let x=b,S;return t[10]!==f||t[11]!==x||t[12]!==y?(S=(0,Z.jsx)(`jar-text`,{style:{flexGrow:0,flexShrink:0,flexDirection:`row`,textWrap:y},internal_transform:x,children:f}),t[10]=f,t[11]=x,t[12]=y,t[13]=S):S=t[13],S}const xPe=/\x1b\[[\d:]*;(\d+)/;function SPe(e){let t=xPe.exec(e);return t?(parseInt(t[1],10)-1&8)!=0:!1}const sQ={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:``},cQ=(e,t={})=>{let{addInputListener:n}=(0,X.use)(xZ),r=(0,X.useRef)(e);r.current=e,(0,X.useEffect)(()=>{if(t.isActive!==!1)return n(e=>{if($Y(e))return;if(e.startsWith(`\x1B[200~`)){let t=e.indexOf(`\x1B[201~`),n=t===-1?e.slice(6):e.slice(6,t);sQ.upArrow=!1,sQ.downArrow=!1,sQ.leftArrow=!1,sQ.rightArrow=!1,sQ.pageDown=!1,sQ.pageUp=!1,sQ.home=!1,sQ.end=!1,sQ.return=!1,sQ.escape=!1,sQ.ctrl=!1,sQ.shift=!1,sQ.tab=!1,sQ.backspace=!1,sQ.delete=!1,sQ.meta=!1,sQ.super=!1,sQ.paste=!0,sQ.raw=e,r.current(n,{...sQ});return}let t=kMe(e),n=t?t.split(`+`):[],i=n[n.length-1]??``,a=n.includes(`ctrl`),o=n.includes(`shift`),s=n.includes(`alt`);sQ.upArrow=i===`up`,sQ.downArrow=i===`down`,sQ.leftArrow=i===`left`,sQ.rightArrow=i===`right`,sQ.pageDown=i===`pagedown`,sQ.pageUp=i===`pageup`,sQ.home=i===`home`,sQ.end=i===`end`,sQ.return=i===`return`||i===`enter`,sQ.escape=i===`escape`,sQ.ctrl=a,sQ.shift=o,sQ.tab=i===`tab`,sQ.backspace=i===`backspace`,sQ.delete=i===`delete`,sQ.meta=s,sQ.super=SPe(e),sQ.paste=!1,sQ.raw=e;let c=sQ,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=MMe(e);t===void 0?e.length===1?l=e:i.length===1&&(l=i):l=t}r.current(l,{...c})})},[t.isActive,n])},CPe=()=>{let e=(0,X.use)(SZ);if(!e)throw Error(`useApp must be used within a jar render context`);return{exit:e.exit,requestFullRedraw:e.requestFullRedraw}},lQ=e=>{let t=(0,oQ.c)(23),n;t[0]===e?n=t[1]:(n=e===void 0?{}:e,t[0]=e,t[1]=n);let{isActive:r,autoFocus:i,id:a}=n,o=r===void 0?!0:r,s=i===void 0?!1:i,{activeId:c,add:l,remove:u,activate:d,deactivate:f,focus:p}=(0,X.use)(yZ),m;t[2]===a?m=t[3]:(m=a??Math.random().toString().slice(2,7),t[2]=a,t[3]=m);let h=m,g;t[4]!==l||t[5]!==s||t[6]!==h||t[7]!==u?(g=()=>(l(h,{autoFocus:s}),()=>{u(h)}),t[4]=l,t[5]=s,t[6]=h,t[7]=u,t[8]=g):g=t[8];let _;t[9]!==s||t[10]!==h?(_=[h,s],t[9]=s,t[10]=h,t[11]=_):_=t[11],(0,X.useEffect)(g,_);let v;t[12]!==d||t[13]!==f||t[14]!==h||t[15]!==o?(v=()=>{o?d(h):f(h)},t[12]=d,t[13]=f,t[14]=h,t[15]=o,t[16]=v):v=t[16];let y;t[17]!==h||t[18]!==o?(y=[o,h],t[17]=h,t[18]=o,t[19]=y):y=t[19],(0,X.useEffect)(v,y);let b=!!h&&c===h,x;return t[20]!==p||t[21]!==b?(x={isFocused:b,focus:p},t[20]=p,t[21]=b,t[22]=x):x=t[22],x};function uQ(){return(0,X.use)(bZ)}const dQ=()=>{let e=(0,X.use)(CZ);if(!e)throw Error(`useTerminal must be used within a jar render context`);return e.output},fQ=RegExp(`[\\x1b\\x9b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><~]|\\x1b\\][\\s\\S]*?(?:\\x07|\\x1b\\\\)`,`g`);function wPe(){return new RegExp(fQ.source,`g`)}function TPe(e){return e.replace(fQ,``)}function EPe(e){return e.replace(/[\x07\x1b\x9c]/g,``)}function pQ(e){return`\x1B]2;`+EPe(e)+`\x07`}var mQ=G(((e,t)=>{t.exports={name:`@codellm/cli`,version:`2.5.0-canary.1`,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":`catalog:`,"@orpc/client":`catalog:`,"@orpc/contract":`catalog:`,"@orpc/server":`catalog:`,"@sentry/node-core":`catalog:`,"@slack/web-api":`^7.0.0`,"@tanstack/react-query":`catalog:`,"@vscode/ripgrep":`catalog:`,"ansi-styles":`catalog:`,"beautiful-mermaid":`^1.1.3`,"cli-boxes":`catalog:`,"cli-highlight":`^2.1.11`,conf:`catalog:`,diff:`catalog:`,fzf:`catalog:`,"gradient-string":`^3.0.0`,immer:`catalog:`,"isomorphic-git":`catalog:`,marked:`^17.0.6`,"node-notifier":`catalog:`,"patchright-core":`catalog:`,react:`catalog:react`,"react-compiler-runtime":`^1.0.0`,remend:`^1.3.0`,semver:`catalog:`,"shell-history":`^2.0.1`,"string-width":`catalog:`,"strip-ansi":`catalog:`,trash:`catalog:`,zod:`catalog:`},devDependencies:{"@babel/core":`catalog:infra`,"@codellm/configs":`workspace:*`,"@playwright/mcp":`^0.0.68`,"@rolldown/plugin-babel":`catalog:infra`,"@types/diff":`^8.0.0`,"@types/node":`catalog:`,"@types/react":`catalog:react`,"@types/semver":`^7.7.1`,"@typescript/native-preview":`catalog:infra`,"@vitejs/plugin-react":`catalog:infra`,"@vitest/coverage-v8":`^4.1.5`,"@vitest/ui":`^4.1.5`,"@xterm/addon-serialize":`^0.14.0`,"@xterm/headless":`^6.0.0`,"babel-plugin-react-compiler":`catalog:infra`,"cli-testing-library":`^3.0.1`,jsdom:`^27.4.0`,"react-devtools-core":`^6.1.5`,"svg-term-cli":`^2.1.1`,tsdown:`catalog:infra`,vite:`catalog:infra`,vitest:`catalog:infra`,zigpty:`^0.1.6`},engines:{node:`>=18`}}})),hQ=$e(mQ(),1);let gQ=null;function _Q(e){let t=(0,sY.prerelease)(e);return t&&t.length>0&&typeof t[0]==`string`?t[0]:`latest`}function vQ(e){if(!e)return``;try{return T(e)}catch{return e}}function yQ(){return{invokedPath:vQ(process.argv[1]??``),execPath:vQ(process.execPath??process.argv[0]??``)}}function bQ(e){let t=gn.configDirName.replace(/^\./,``).replace(/[.*+?^${}()|[\]\\]/g,`\\$&`);return RegExp(`[/\\\\]\\.?${t}[/\\\\]bin[/\\\\]`,`i`).test(e)}function xQ(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 SQ(){let e=(process.env.npm_command??``).toLowerCase();if(e===`exec`||e===`dlx`)return!0;let{invokedPath:t,execPath:n}=yQ();return/[/\\]_npx[/\\]|[/\\]dlx[/\\]|[/\\]\.cache[/\\]/.test(t+`|`+n)}function CQ(){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}=yQ(),r=`${t}|${n}`;return/[/\\]\.?yarn[/\\]/.test(r)?`yarn`:/[/\\]\.?pnpm[/\\]/.test(r)?`pnpm`:/[/\\]\.bun[/\\]/.test(r)||process.versions.bun!==void 0&&!bQ(n)?`bun`:`npm`}function DPe(){let{execPath:e,invokedPath:t}=yQ();return xQ(t)||xQ(e)?!1:bQ(e)||bQ(t)}function wQ(){let e=`${gn.internalEnvPrefix}DEV`,t=process.env[e];if(t===`1`||t===`true`)return!0;let{invokedPath:n,execPath:r}=yQ();return!(bQ(r)||bQ(n)||xQ(n)||xQ(r)||process.env.npm_config_user_agent)}function OPe(){let{execPath:e}=yQ(),t=CQ(),n=SQ();return wQ()?{installationType:`development`,packageManager:t,isEphemeral:n,execPath:e}:DPe()?{installationType:`native`,packageManager:t,isEphemeral:n,execPath:e}:{installationType:`package-manager`,packageManager:t,isEphemeral:n,execPath:e}}function kPe(){return`${process.platform===`win32`?`win32`:process.platform===`darwin`?`darwin`:`linux`}-${process.arch===`arm64`?`arm64`:`x64`}`}async function APe(e){let t=Date.now();if(gQ&&t-gQ.timestamp<6e4)return gQ.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 gQ={tags:r,timestamp:t},r}async function jPe(e,t,n,r){let i=t??_Q(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:CQ(),isEphemeral:SQ(),installationType:`native`,downloadUrl:l.url}}async function MPe(e,t){let n=t??_Q(e),r=CQ(),i=SQ(),a=(await APe(_n.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 TQ(e,t,n,r){let i=OPe();if(i.installationType===`native`)try{return await jPe(e,t,kPe(),n)}catch{return null}return i.installationType===`development`&&!r?.includeDev?null:await MPe(e,t)}function EQ(e){if(e.installationType===`native`)return`${gn.binName} upgrade`;let t=`${_n.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 DQ(e){try{return{ok:!0,output:le(EQ(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`}}}function NPe(){let e=N.join(t.homedir(),gn.configDirName,`bin`);try{let n=N.dirname(vQ(process.execPath));return!n||n.toLowerCase().startsWith(t.tmpdir().toLowerCase())?e:n}catch{return e}}async function OQ(e){if(!e.downloadUrl)return{ok:!1,output:`No download URL`};let n=N.join(t.tmpdir(),`abacusai-update-${Date.now()}`),r=process.platform===`win32`,i=r?`${gn.binName}.exe`:gn.binName,a=NPe();try{await we.mkdir(n,{recursive:!0}),await we.mkdir(a,{recursive:!0});let t=N.join(n,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(t,s),le(r?`powershell -Command "Expand-Archive -Path '${t}' -DestinationPath '${n}' -Force"`:`tar -xzf "${t}" -C "${n}"`,{stdio:`pipe`});let c=N.join(n,i),l=N.join(a,i);if(r){let e=`${l}.old`;await we.rm(e,{force:!0}).catch(()=>{}),await we.rename(l,e).catch(()=>{}),await we.copyFile(c,l),await we.rm(e,{force:!0}).catch(()=>{})}else await we.copyFile(c,l),await we.chmod(l,493);return{ok:!0,output:`Updated to ${e.latestVersion}`}}catch(e){return{ok:!1,output:e instanceof Error?e.message:`Unknown error`}}finally{await we.rm(n,{recursive:!0,force:!0}).catch(()=>{})}}function PPe(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 kQ(e,t){let n=(await e.listLLMModels())?.result??[];return n.length||(process.stderr.write(`Error: No models available.
|
|
75181
|
+
var bPe=G((e=>{var t=SY().__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;e.c=function(e){return t.H.useMemoCache(e)}})),oQ=G(((e,t)=>{t.exports=bPe()}))();function $(e){let t=(0,oQ.c)(14),{color:n,backgroundColor:r,dimColor:i,bold:a,italic:o,underline:s,strikethrough:c,inverse:l,wrap:u,transform:d,children:f}=e,p=i===void 0?!1:i,m=a===void 0?!1:a,h=o===void 0?!1:o,g=s===void 0?!1:s,_=c===void 0?!1:c,v=l===void 0?!1:l,y=u===void 0?`wrap`:u;if(f==null)return null;let b;t[0]!==r||t[1]!==m||t[2]!==n||t[3]!==p||t[4]!==v||t[5]!==h||t[6]!==_||t[7]!==g||t[8]!==d?(b=e=>(p&&(e=JZ().dim().render(e)),n&&(e=qZ(e,n,`foreground`)),r&&(e=qZ(e,r,`background`)),m&&(e=JZ().bold().render(e)),h&&(e=JZ().italic().render(e)),g&&(e=JZ().underline().render(e)),_&&(e=JZ().strikethrough().render(e)),v&&(e=JZ().reverse().render(e)),d&&(e=d(e)),e),t[0]=r,t[1]=m,t[2]=n,t[3]=p,t[4]=v,t[5]=h,t[6]=_,t[7]=g,t[8]=d,t[9]=b):b=t[9];let x=b,S;return t[10]!==f||t[11]!==x||t[12]!==y?(S=(0,Z.jsx)(`jar-text`,{style:{flexGrow:0,flexShrink:0,flexDirection:`row`,textWrap:y},internal_transform:x,children:f}),t[10]=f,t[11]=x,t[12]=y,t[13]=S):S=t[13],S}const xPe=/\x1b\[[\d:]*;(\d+)/;function SPe(e){let t=xPe.exec(e);return t?(parseInt(t[1],10)-1&8)!=0:!1}const sQ={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:``},cQ=(e,t={})=>{let{addInputListener:n}=(0,X.use)(xZ),r=(0,X.useRef)(e);r.current=e,(0,X.useEffect)(()=>{if(t.isActive!==!1)return n(e=>{if($Y(e))return;if(e.startsWith(`\x1B[200~`)){let t=e.indexOf(`\x1B[201~`),n=t===-1?e.slice(6):e.slice(6,t);sQ.upArrow=!1,sQ.downArrow=!1,sQ.leftArrow=!1,sQ.rightArrow=!1,sQ.pageDown=!1,sQ.pageUp=!1,sQ.home=!1,sQ.end=!1,sQ.return=!1,sQ.escape=!1,sQ.ctrl=!1,sQ.shift=!1,sQ.tab=!1,sQ.backspace=!1,sQ.delete=!1,sQ.meta=!1,sQ.super=!1,sQ.paste=!0,sQ.raw=e,r.current(n,{...sQ});return}let t=kMe(e),n=t?t.split(`+`):[],i=n[n.length-1]??``,a=n.includes(`ctrl`),o=n.includes(`shift`),s=n.includes(`alt`);sQ.upArrow=i===`up`,sQ.downArrow=i===`down`,sQ.leftArrow=i===`left`,sQ.rightArrow=i===`right`,sQ.pageDown=i===`pagedown`,sQ.pageUp=i===`pageup`,sQ.home=i===`home`,sQ.end=i===`end`,sQ.return=i===`return`||i===`enter`,sQ.escape=i===`escape`,sQ.ctrl=a,sQ.shift=o,sQ.tab=i===`tab`,sQ.backspace=i===`backspace`,sQ.delete=i===`delete`,sQ.meta=s,sQ.super=SPe(e),sQ.paste=!1,sQ.raw=e;let c=sQ,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=MMe(e);t===void 0?e.length===1?l=e:i.length===1&&(l=i):l=t}r.current(l,{...c})})},[t.isActive,n])},CPe=()=>{let e=(0,X.use)(SZ);if(!e)throw Error(`useApp must be used within a jar render context`);return{exit:e.exit,requestFullRedraw:e.requestFullRedraw}},lQ=e=>{let t=(0,oQ.c)(23),n;t[0]===e?n=t[1]:(n=e===void 0?{}:e,t[0]=e,t[1]=n);let{isActive:r,autoFocus:i,id:a}=n,o=r===void 0?!0:r,s=i===void 0?!1:i,{activeId:c,add:l,remove:u,activate:d,deactivate:f,focus:p}=(0,X.use)(yZ),m;t[2]===a?m=t[3]:(m=a??Math.random().toString().slice(2,7),t[2]=a,t[3]=m);let h=m,g;t[4]!==l||t[5]!==s||t[6]!==h||t[7]!==u?(g=()=>(l(h,{autoFocus:s}),()=>{u(h)}),t[4]=l,t[5]=s,t[6]=h,t[7]=u,t[8]=g):g=t[8];let _;t[9]!==s||t[10]!==h?(_=[h,s],t[9]=s,t[10]=h,t[11]=_):_=t[11],(0,X.useEffect)(g,_);let v;t[12]!==d||t[13]!==f||t[14]!==h||t[15]!==o?(v=()=>{o?d(h):f(h)},t[12]=d,t[13]=f,t[14]=h,t[15]=o,t[16]=v):v=t[16];let y;t[17]!==h||t[18]!==o?(y=[o,h],t[17]=h,t[18]=o,t[19]=y):y=t[19],(0,X.useEffect)(v,y);let b=!!h&&c===h,x;return t[20]!==p||t[21]!==b?(x={isFocused:b,focus:p},t[20]=p,t[21]=b,t[22]=x):x=t[22],x};function uQ(){return(0,X.use)(bZ)}const dQ=()=>{let e=(0,X.use)(CZ);if(!e)throw Error(`useTerminal must be used within a jar render context`);return e.output},fQ=RegExp(`[\\x1b\\x9b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><~]|\\x1b\\][\\s\\S]*?(?:\\x07|\\x1b\\\\)`,`g`);function wPe(){return new RegExp(fQ.source,`g`)}function TPe(e){return e.replace(fQ,``)}function EPe(e){return e.replace(/[\x07\x1b\x9c]/g,``)}function pQ(e){return`\x1B]2;`+EPe(e)+`\x07`}var mQ=G(((e,t)=>{t.exports={name:`@codellm/cli`,version:`2.5.0-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":`catalog:`,"@orpc/client":`catalog:`,"@orpc/contract":`catalog:`,"@orpc/server":`catalog:`,"@sentry/node-core":`catalog:`,"@slack/web-api":`^7.0.0`,"@tanstack/react-query":`catalog:`,"@vscode/ripgrep":`catalog:`,"ansi-styles":`catalog:`,"beautiful-mermaid":`^1.1.3`,"cli-boxes":`catalog:`,"cli-highlight":`^2.1.11`,conf:`catalog:`,diff:`catalog:`,fzf:`catalog:`,"gradient-string":`^3.0.0`,immer:`catalog:`,"isomorphic-git":`catalog:`,marked:`^17.0.6`,"node-notifier":`catalog:`,"patchright-core":`catalog:`,react:`catalog:react`,"react-compiler-runtime":`^1.0.0`,remend:`^1.3.0`,semver:`catalog:`,"shell-history":`^2.0.1`,"string-width":`catalog:`,"strip-ansi":`catalog:`,trash:`catalog:`,zod:`catalog:`},devDependencies:{"@babel/core":`catalog:infra`,"@codellm/configs":`workspace:*`,"@playwright/mcp":`^0.0.68`,"@rolldown/plugin-babel":`catalog:infra`,"@types/diff":`^8.0.0`,"@types/node":`catalog:`,"@types/react":`catalog:react`,"@types/semver":`^7.7.1`,"@typescript/native-preview":`catalog:infra`,"@vitejs/plugin-react":`catalog:infra`,"@vitest/coverage-v8":`^4.1.5`,"@vitest/ui":`^4.1.5`,"@xterm/addon-serialize":`^0.14.0`,"@xterm/headless":`^6.0.0`,"babel-plugin-react-compiler":`catalog:infra`,"cli-testing-library":`^3.0.1`,jsdom:`^27.4.0`,"react-devtools-core":`^6.1.5`,"svg-term-cli":`^2.1.1`,tsdown:`catalog:infra`,vite:`catalog:infra`,vitest:`catalog:infra`,zigpty:`^0.1.6`},engines:{node:`>=18`}}})),hQ=$e(mQ(),1);let gQ=null;function _Q(e){let t=(0,sY.prerelease)(e);return t&&t.length>0&&typeof t[0]==`string`?t[0]:`latest`}function vQ(e){if(!e)return``;try{return T(e)}catch{return e}}function yQ(){return{invokedPath:vQ(process.argv[1]??``),execPath:vQ(process.execPath??process.argv[0]??``)}}function bQ(e){let t=gn.configDirName.replace(/^\./,``).replace(/[.*+?^${}()|[\]\\]/g,`\\$&`);return RegExp(`[/\\\\]\\.?${t}[/\\\\]bin[/\\\\]`,`i`).test(e)}function xQ(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 SQ(){let e=(process.env.npm_command??``).toLowerCase();if(e===`exec`||e===`dlx`)return!0;let{invokedPath:t,execPath:n}=yQ();return/[/\\]_npx[/\\]|[/\\]dlx[/\\]|[/\\]\.cache[/\\]/.test(t+`|`+n)}function CQ(){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}=yQ(),r=`${t}|${n}`;return/[/\\]\.?yarn[/\\]/.test(r)?`yarn`:/[/\\]\.?pnpm[/\\]/.test(r)?`pnpm`:/[/\\]\.bun[/\\]/.test(r)||process.versions.bun!==void 0&&!bQ(n)?`bun`:`npm`}function DPe(){let{execPath:e,invokedPath:t}=yQ();return xQ(t)||xQ(e)?!1:bQ(e)||bQ(t)}function wQ(){let e=`${gn.internalEnvPrefix}DEV`,t=process.env[e];if(t===`1`||t===`true`)return!0;let{invokedPath:n,execPath:r}=yQ();return!(bQ(r)||bQ(n)||xQ(n)||xQ(r)||process.env.npm_config_user_agent)}function OPe(){let{execPath:e}=yQ(),t=CQ(),n=SQ();return wQ()?{installationType:`development`,packageManager:t,isEphemeral:n,execPath:e}:DPe()?{installationType:`native`,packageManager:t,isEphemeral:n,execPath:e}:{installationType:`package-manager`,packageManager:t,isEphemeral:n,execPath:e}}function kPe(){return`${process.platform===`win32`?`win32`:process.platform===`darwin`?`darwin`:`linux`}-${process.arch===`arm64`?`arm64`:`x64`}`}async function APe(e){let t=Date.now();if(gQ&&t-gQ.timestamp<6e4)return gQ.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 gQ={tags:r,timestamp:t},r}async function jPe(e,t,n,r){let i=t??_Q(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:CQ(),isEphemeral:SQ(),installationType:`native`,downloadUrl:l.url}}async function MPe(e,t){let n=t??_Q(e),r=CQ(),i=SQ(),a=(await APe(_n.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 TQ(e,t,n,r){let i=OPe();if(i.installationType===`native`)try{return await jPe(e,t,kPe(),n)}catch{return null}return i.installationType===`development`&&!r?.includeDev?null:await MPe(e,t)}function EQ(e){if(e.installationType===`native`)return`${gn.binName} upgrade`;let t=`${_n.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 DQ(e){try{return{ok:!0,output:le(EQ(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`}}}function NPe(){let e=N.join(t.homedir(),gn.configDirName,`bin`);try{let n=N.dirname(vQ(process.execPath));return!n||n.toLowerCase().startsWith(t.tmpdir().toLowerCase())?e:n}catch{return e}}async function OQ(e){if(!e.downloadUrl)return{ok:!1,output:`No download URL`};let n=N.join(t.tmpdir(),`abacusai-update-${Date.now()}`),r=process.platform===`win32`,i=r?`${gn.binName}.exe`:gn.binName,a=NPe();try{await we.mkdir(n,{recursive:!0}),await we.mkdir(a,{recursive:!0});let t=N.join(n,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(t,s),le(r?`powershell -Command "Expand-Archive -Path '${t}' -DestinationPath '${n}' -Force"`:`tar -xzf "${t}" -C "${n}"`,{stdio:`pipe`});let c=N.join(n,i),l=N.join(a,i);if(r){let e=`${l}.old`;await we.rm(e,{force:!0}).catch(()=>{}),await we.rename(l,e).catch(()=>{}),await we.copyFile(c,l),await we.rm(e,{force:!0}).catch(()=>{})}else await we.copyFile(c,l),await we.chmod(l,493);return{ok:!0,output:`Updated to ${e.latestVersion}`}}catch(e){return{ok:!1,output:e instanceof Error?e.message:`Unknown error`}}finally{await we.rm(n,{recursive:!0,force:!0}).catch(()=>{})}}function PPe(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 kQ(e,t){let n=(await e.listLLMModels())?.result??[];return n.length||(process.stderr.write(`Error: No models available.
|
|
75182
75182
|
`),process.exit(1)),t?PPe(n,t.toLowerCase())||(process.stderr.write(`Warning: Model "${t}" not found. Using default: ${n[0].llmName}\n`),n[0].llmName):n[0].llmName}const AQ=ft([`codellm`,`cli`,`exit`]),jQ=new Set,MQ=new Set,NQ=new Set;let PQ=!1,FQ=!1,IQ=null,LQ;async function FPe(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 RQ(e,t,n,r){if(PQ)return;r?.debug?.(`Executing exit handlers`,{shouldManuallyExit:e,isSynchronous:t,signal:n,asyncCallbacks:jQ.size,syncCallbacks:MQ.size}),PQ=!0,jQ.size>0&&t&&AQ.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:LQ===void 0?(typeof H.exitCode==`number`||typeof H.exitCode==`string`)&&(i=Number(H.exitCode)):i=LQ;let a=(t=!1)=>{(t||e)&&(IQ?IQ.call(H,i):H.exit(i))};for(let e of MQ)try{e(i)}catch(e){AQ.error`Error in synchronous exit hook: ${e}`}if(t){a();return}let o=[],s=0;for(let[e,t]of jQ)s=Math.max(s,t),o.push(Promise.resolve(e(i)).catch(e=>{AQ.error`Error in asynchronous exit hook: ${e}`}));let c=Array.from(NQ);c.length>0&&o.push(FPe(c));let l=setTimeout(()=>{a(!0)},s);try{await Promise.all(o),clearTimeout(l),a()}catch(e){clearTimeout(l),AQ.error`Error during exit cleanup: ${e}`,a(!0)}}function IPe(){FQ||(FQ=!0,H.once(`beforeExit`,()=>{RQ(!0,!1,-128)}),H.once(`SIGINT`,()=>{RQ(!0,!1,2)}),H.once(`SIGTERM`,()=>{RQ(!0,!1,15)}),H.once(`exit`,()=>{RQ(!1,!0,0)}),H.on(`message`,e=>{e===`shutdown`&&RQ(!0,!0,-128)}),IQ||(IQ=H.exit.bind(H),H.exit=function(e){if(LQ===void 0&&(LQ=e??0),jQ.size===0&&NQ.size===0){if(IQ){IQ(e??0);return}H.exit(e??0)}RQ(!0,!1,-128).catch(e=>{AQ.error`Error during exit: ${e}`,IQ?IQ(1):H.exit(1)})}))}function zQ(e,t){if(typeof e!=`function`)throw TypeError(`callback must be a function`);if(PQ)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}),IPe();let n=t?.wait??0,r=t?.streams??[H.stdout,H.stderr];if(n>0){let t=[e,n];jQ.add(t);for(let e of r)NQ.add(e);return()=>{jQ.delete(t);for(let e of r)NQ.delete(e)}}return MQ.add(e),()=>{MQ.delete(e)}}function BQ(e){e!==void 0&&(H.exitCode=e),RQ(!0,!1,-128)}const VQ=`${gn.internalEnvPrefix}CLIENT_KIND`;function LPe(){let e=process.env[VQ]?.trim();if(!e)return nt.CLI;try{return rt(e)}catch{throw Error(`Invalid ${VQ} value: ${e}. Expected one of ${Object.values(nt).join(`, `)}.`)}}function HQ(e){process.stdout.write(JSON.stringify(e)+`
|
|
75183
75183
|
`)}function RPe(e){try{return JSON.parse(e)}catch{return null}}async function zPe({agentArgs:e}){fu(`ndjson IPC host started`,`cli`);let t=LPe(),n=await bY.create(),r=new Tu(n,Cn(),_n.userAgentNames.desktop,hQ.default.version);if(!n.isAuthenticated())try{(await r.getUserInfo())?.result?.email||(process.stderr.write(`Error: Not authenticated. Set ABACUS_DEVICE_CODE environment variable.
|
|
75184
75184
|
`),process.exit(1))}catch{process.stderr.write(`Error: Not authenticated. Set ABACUS_DEVICE_CODE environment variable.
|
|
75185
|
-
`),process.exit(1)}let i=process.cwd(),a=t===nt.COWORK?`desktop`:`cli`,o=new tJ({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 kQ(r,e?.model),l=new Map,u=0,d=new Qq(async e=>{let t=`perm-${++u}`;return HQ({type:`permission_needed`,permissionId:t,request:e}),new Promise(e=>{l.set(t,{resolve:e})})}),f=Pd.Normal,p=e?.[`permission-mode`];if(p)switch(p){case`normal`:f=Pd.Normal;break;case`accept-edits`:f=Pd.AcceptEdits;break;case`plan`:f=Pd.PlanMode;break;case`yolo`:f=Pd.Yolo;break}let m=new Zq({allowedDirectories:[i,...e?.[`add-dir`]?.map(e=>P.isAbsolute(e)?e:P.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=>{UQ(m,e)},zQ(async()=>{m.stop(),await new Promise(e=>setTimeout(e,200))},{wait:1e3}),HQ({type:`ready`,model:c,mode:f});let h=Kq.loadSkills(i).then(()=>{HQ({type:`skills_loaded`,skills:Kq.getAllMetadata()})}).catch(e=>{lu(e),process.stderr.write(`Failed to load skills: ${e}\n`)}),g=o.get(`autoUpdate`)!==!1;wQ()||TQ(hQ.default.version,o.get(`updateChannel`),o.get(`baseUrl`)).then(async e=>{if(!e||(HQ({type:`update_available`,currentVersion:e.currentVersion,latestVersion:e.latestVersion}),!g))return;HQ({type:`update_downloading`,latestVersion:e.latestVersion});let t=e.installationType===`native`?await OQ(e):DQ(e);t.ok?HQ({type:`update_complete`,latestVersion:e.latestVersion}):HQ({type:`update_failed`,latestVersion:e.latestVersion,error:t.output||`Update failed`})}).catch(e=>{lu(e)});let _=B.createInterface({input:process.stdin});_.on(`line`,async e=>{let t=e.trim();if(!t)return;let n=RPe(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),UQ(m,e,r);break}case`stop`:m.stop();break;case`list_skills`:h.then(()=>{HQ({type:`skills_loaded`,skills:Kq.getAllMetadata()})});break;case`switch_conversation`:{let e=n.conversationId;e&&(m.switchConversation(e),HQ({type:`event`,event:{type:`status_changed`,status:`idle`}}));break}case`reset_conversation`:m.resetConversation(),HQ({type:`event`,event:{type:`status_changed`,status:`idle`}});break;case`set_mode`:{let e=BPe(n.mode??`DEFAULT`);m.setMode(e);break}case`set_model`:{let e=n.model;if(e){let t=await kQ(r,e);m.setModel(t),HQ({type:`event`,event:{type:`model_changed`,model:t}})}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}),HQ({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}:{}});HQ({type:`queue_updated`,messages:m.getQueueEntries(),dequeued:r.map(e=>e.message)});break}case`get_queue`:{let e=n.includeHidden??!1;HQ({type:`queue_updated`,messages:m.getQueueEntries({includeHidden:e})});break}case`clear_queue`:{let e=n.includeHidden??!1;m.clearQueue({includeHidden:e}),HQ({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)}HQ({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 UQ(e,t,n){try{for await(let r of e.send(t,{activeSkills:n}))HQ({type:`event`,event:r})}catch(e){lu(e),HQ({type:`event`,event:{type:`error`,error:{message:e instanceof Error?e.message:String(e)}}})}}function BPe(e){switch(e){case`DEFAULT`:return Pd.Normal;case`ACCEPTEDITS`:return Pd.AcceptEdits;case`PLAN`:return Pd.PlanMode;case`YOLO`:return Pd.Yolo;default:return Pd.Normal}}const VPe=ft([`codellm`,`cli`,`print-mode`]);async function HPe(){let e=await bY.create();return{apiClient:new Tu(e,Cn(),_n.userAgentNames.print,hQ.default.version),authManager:e}}function WQ(e){process.stdout.write(JSON.stringify(e)+`
|
|
75185
|
+
`),process.exit(1)}let i=process.cwd(),a=t===nt.COWORK?`desktop`:t===nt.CLOUD?`cloud`:`cli`,o=new tJ({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 kQ(r,e?.model),l=new Map,u=0,d=new Qq(async e=>{let t=`perm-${++u}`;return HQ({type:`permission_needed`,permissionId:t,request:e}),new Promise(e=>{l.set(t,{resolve:e})})}),f=Pd.Normal,p=e?.[`permission-mode`];if(p)switch(p){case`normal`:f=Pd.Normal;break;case`accept-edits`:f=Pd.AcceptEdits;break;case`plan`:f=Pd.PlanMode;break;case`yolo`:f=Pd.Yolo;break}let m=new Zq({allowedDirectories:[i,...e?.[`add-dir`]?.map(e=>P.isAbsolute(e)?e:P.resolve(i,e))??[]],primaryWorkspace:i,apiClient:r,mode:f,model:c,permissionProvider:d,config:o,isPrintMode:!1,enablePromptRewrite:!1,supportsThoughtStreaming:!0,enableSkills:!0,sendAgentMd:t===nt.CLOUD,cliAllowedTools:e?.[`allowed-tools`],cliDisallowedTools:e?.[`disallowed-tools`],clientType:t});m.onAutoRestart=e=>{UQ(m,e)},zQ(async()=>{m.stop(),await new Promise(e=>setTimeout(e,200))},{wait:1e3}),HQ({type:`ready`,model:c,mode:f});let h=Kq.loadSkills(i).then(()=>{HQ({type:`skills_loaded`,skills:Kq.getAllMetadata()})}).catch(e=>{lu(e),process.stderr.write(`Failed to load skills: ${e}\n`)}),g=o.get(`autoUpdate`)!==!1;wQ()||TQ(hQ.default.version,o.get(`updateChannel`),o.get(`baseUrl`)).then(async e=>{if(!e||(HQ({type:`update_available`,currentVersion:e.currentVersion,latestVersion:e.latestVersion}),!g))return;HQ({type:`update_downloading`,latestVersion:e.latestVersion});let t=e.installationType===`native`?await OQ(e):DQ(e);t.ok?HQ({type:`update_complete`,latestVersion:e.latestVersion}):HQ({type:`update_failed`,latestVersion:e.latestVersion,error:t.output||`Update failed`})}).catch(e=>{lu(e)});let _=B.createInterface({input:process.stdin});_.on(`line`,async e=>{let t=e.trim();if(!t)return;let n=RPe(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),UQ(m,e,r);break}case`stop`:m.stop();break;case`list_skills`:h.then(()=>{HQ({type:`skills_loaded`,skills:Kq.getAllMetadata()})});break;case`switch_conversation`:{let e=n.conversationId;e&&(m.switchConversation(e),HQ({type:`event`,event:{type:`status_changed`,status:`idle`}}));break}case`reset_conversation`:m.resetConversation(),HQ({type:`event`,event:{type:`status_changed`,status:`idle`}});break;case`set_mode`:{let e=BPe(n.mode??`DEFAULT`);m.setMode(e);break}case`set_model`:{let e=n.model;if(e){let t=await kQ(r,e);m.setModel(t),HQ({type:`event`,event:{type:`model_changed`,model:t}})}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}),HQ({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}:{}});HQ({type:`queue_updated`,messages:m.getQueueEntries(),dequeued:r.map(e=>e.message)});break}case`get_queue`:{let e=n.includeHidden??!1;HQ({type:`queue_updated`,messages:m.getQueueEntries({includeHidden:e})});break}case`clear_queue`:{let e=n.includeHidden??!1;m.clearQueue({includeHidden:e}),HQ({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)}HQ({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 UQ(e,t,n){try{for await(let r of e.send(t,{activeSkills:n}))HQ({type:`event`,event:r})}catch(e){lu(e),HQ({type:`event`,event:{type:`error`,error:{message:e instanceof Error?e.message:String(e)}}})}}function BPe(e){switch(e){case`DEFAULT`:return Pd.Normal;case`ACCEPTEDITS`:return Pd.AcceptEdits;case`PLAN`:return Pd.PlanMode;case`YOLO`:return Pd.Yolo;default:return Pd.Normal}}const VPe=ft([`codellm`,`cli`,`print-mode`]);async function HPe(){let e=await bY.create();return{apiClient:new Tu(e,Cn(),_n.userAgentNames.print,hQ.default.version),authManager:e}}function WQ(e){process.stdout.write(JSON.stringify(e)+`
|
|
75186
75186
|
`)}async function UPe(e,t){if(e?.resume)return e.resume;if(e?.continue)try{return((await t.getConversationsList(gn.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 WPe({agentArgs:e}){fu(`print-mode started`,`cli`);let{apiClient:t,authManager:n}=await HPe(),r=process.cwd(),i=new tJ({cwd:r,extraSources:[{read:async()=>({client:`cli`})}]});await i.load(),wQ()||TQ(hQ.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: ${EQ(e)}\n`;process.stderr.write(t)}}).catch(e=>{lu(e)});let a=i.get(`baseUrl`);if(a){try{new URL(a)}catch{VPe.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 ${gn.envPrefix}API_KEY environment variable or run interactively to log in.\n`),process.exit(1));let o=e?.[`output-format`]??`text`,s=await kQ(t,e?.model),c=Pd.Yolo,l=e?.[`permission-mode`];if(l)switch(l){case`normal`:c=Pd.Normal;break;case`accept-edits`:c=Pd.AcceptEdits;break;case`plan`:c=Pd.PlanMode;break;default:c=Pd.Yolo;break}let u=new Zq({allowedDirectories:[r,...e?.[`add-dir`]?.map(e=>P.isAbsolute(e)?e:P.resolve(r,e))??[]],primaryWorkspace:r,apiClient:t,mode:c,model:s,permissionProvider:new _Ae,config:i,isPrintMode:!0,enablePromptRewrite:!1,supportsThoughtStreaming:!0,enableSkills:!0,cliAllowedTools:e?.[`allowed-tools`],cliDisallowedTools:e?.[`disallowed-tools`],clientType:nt.CLI});zQ(async()=>{u.stop(),await new Promise(e=>setTimeout(e,200))},{wait:1e3});let d=await UPe(e,t);if(d)try{let e=await u.loadConversation(d);e.llmName&&(s=e.llmName,u.setModel(e.llmName))}catch(e){throw lu(e),e}let f=e?.prompt??``;process.env.DEEPAGENT_HIGH_QUALITY===`true`&&(f=`
|
|
75187
75187
|
IMPORTANT INSTRUCTIONS: Your task is to follow the <task_description> EXACTLY and verify the solution within the FIXED TIME LIMIT.
|
|
75188
75188
|
A few things to keep in mind (Add Relevant ONES BELOW AS TODOS):
|