@abacus-ai/cli 2.4.8 → 2.4.9-canary.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.mjs +17 -17
  2. package/package.json +1 -1
package/dist/index.mjs CHANGED
@@ -1868,7 +1868,7 @@ ${e.terminator}`}function cme(e){return`(${LP(e.body)})${IP(e.redirections)}`}fu
1868
1868
 
1869
1869
  `)}t.write(`payload.value = newResult;`),t.write(`return payload;`);let s=t.compile();return(t,n)=>s(e,t,n)},a,o=QF,s=!zF.jitless,c=s&&Ohe.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?WI([],p,d,f,u,e):d):n(d,f):(d.issues.push({expected:`object`,code:`invalid_type`,input:p,inst:e}),d)}});function GI(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=>!aI(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=>cI(e,r,BF())))}),t)}const KI=IF(`$ZodUnion`,(e,t)=>{FI.init(e,t),qF(e._zod,`optin`,()=>t.options.some(e=>e._zod.optin===`optional`)?`optional`:void 0),qF(e._zod,`optout`,()=>t.options.some(e=>e._zod.optout===`optional`)?`optional`:void 0),qF(e._zod,`values`,()=>{if(t.options.every(e=>e._zod.values))return new Set(t.options.flatMap(e=>Array.from(e._zod.values)))}),qF(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=>GF(e.source)).join(`|`)})$`)}});let n=t.options.length===1,r=t.options[0]._zod.run;e._zod.parse=(i,a)=>{if(n)return r(i,a);let o=!1,s=[];for(let e of t.options){let t=e._zod.run({value:i.value,issues:[]},a);if(t instanceof Promise)s.push(t),o=!0;else{if(t.issues.length===0)return t;s.push(t)}}return o?Promise.all(s).then(t=>GI(t,i,e,a)):GI(s,i,e,a)}});function qI(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=>cI(e,r,BF())))}):t.issues.push({code:`invalid_union`,input:t.value,inst:n,errors:[],inclusive:!1}),t)}const j_e=IF(`$ZodXor`,(e,t)=>{KI.init(e,t),t.inclusive=!1;let n=t.options.length===1,r=t.options[0]._zod.run;e._zod.parse=(i,a)=>{if(n)return r(i,a);let o=!1,s=[];for(let e of t.options){let t=e._zod.run({value:i.value,issues:[]},a);t instanceof Promise?(s.push(t),o=!0):s.push(t)}return o?Promise.all(s).then(t=>qI(t,i,e,a)):qI(s,i,e,a)}}),M_e=IF(`$ZodDiscriminatedUnion`,(e,t)=>{t.inclusive=!1,KI.init(e,t);let n=e._zod.parse;qF(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=UF(()=>{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(!QF(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?n(i,a):(i.issues.push({code:`invalid_union`,errors:[],note:`No matching discriminator`,discriminator:t.discriminator,input:o,path:[t.discriminator],inst:e}),i)}}),N_e=IF(`$ZodIntersection`,(e,t)=>{FI.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])=>YI(e,t,n)):YI(e,i,a)}});function JI(e,t){if(e===t||e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if($F(e)&&$F(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=JI(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=JI(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 YI(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}),aI(e))return e;let o=JI(t.value,n.value);if(!o.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(o.mergeErrorPath)}`);return e.value=o.data,e}const XI=IF(`$ZodTuple`,(e,t)=>{FI.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=[...n].reverse().findIndex(e=>e._zod.optin!==`optional`),c=s===-1?0:n.length-s;if(!t.rest){let t=a.length>n.length,i=a.length<c-1;if(t||i)return r.issues.push({...t?{code:`too_big`,maximum:n.length,inclusive:!0}:{code:`too_small`,minimum:n.length},input:a,inst:e,origin:`array`}),r}let l=-1;for(let e of n){if(l++,l>=a.length&&l>=c)continue;let t=e._zod.run({value:a[l],issues:[]},i);t instanceof Promise?o.push(t.then(e=>ZI(e,r,l))):ZI(t,r,l)}if(t.rest){let e=a.slice(n.length);for(let n of e){l++;let e=t.rest._zod.run({value:n,issues:[]},i);e instanceof Promise?o.push(e.then(e=>ZI(e,r,l))):ZI(e,r,l)}}return o.length?Promise.all(o).then(()=>r):r}});function ZI(e,t,n){e.issues.length&&t.issues.push(...oI(n,e.issues)),t.value[n]=e.value}const P_e=IF(`$ZodRecord`,(e,t)=>{FI.init(e,t),e._zod.parse=(n,r)=>{let i=n.value;if(!$F(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 e of o)if(typeof e==`string`||typeof e==`number`||typeof e==`symbol`){s.add(typeof e==`number`?e.toString():e);let o=t.valueType._zod.run({value:i[e],issues:[]},r);o instanceof Promise?a.push(o.then(t=>{t.issues.length&&n.issues.push(...oI(e,t.issues)),n.value[e]=t.value})):(o.issues.length&&n.issues.push(...oI(e,o.issues)),n.value[e]=o.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__`)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`&&EI.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=>cI(e,r,BF())),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(...oI(o,e.issues)),n.value[s.value]=e.value})):(c.issues.length&&n.issues.push(...oI(o,c.issues)),n.value[s.value]=c.value)}}return a.length?Promise.all(a).then(()=>n):n}}),F_e=IF(`$ZodMap`,(e,t)=>{FI.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])=>{QI(t,a,n,o,i,e,r)})):QI(c,l,n,o,i,e,r)}return a.length?Promise.all(a).then(()=>n):n}});function QI(e,t,n,r,i,a,o){e.issues.length&&(tI.has(typeof r)?n.issues.push(...oI(r,e.issues)):n.issues.push({code:`invalid_key`,origin:`map`,input:i,inst:a,issues:e.issues.map(e=>cI(e,o,BF()))})),t.issues.length&&(tI.has(typeof r)?n.issues.push(...oI(r,t.issues)):n.issues.push({origin:`map`,code:`invalid_element`,input:i,inst:a,key:r,issues:t.issues.map(e=>cI(e,o,BF()))})),n.value.set(e.value,t.value)}const I_e=IF(`$ZodSet`,(e,t)=>{FI.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=>$I(e,n))):$I(i,n)}return a.length?Promise.all(a).then(()=>n):n}});function $I(e,t){e.issues.length&&t.issues.push(...e.issues),t.value.add(e.value)}const L_e=IF(`$ZodEnum`,(e,t)=>{FI.init(e,t);let n=VF(t.entries),r=new Set(n);e._zod.values=r,e._zod.pattern=RegExp(`^(${n.filter(e=>tI.has(typeof e)).map(e=>typeof e==`string`?nI(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}}),R_e=IF(`$ZodLiteral`,(e,t)=>{if(FI.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`?nI(e):e?nI(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}}),z_e=IF(`$ZodFile`,(e,t)=>{FI.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}}),B_e=IF(`$ZodTransform`,(e,t)=>{FI.init(e,t),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new RF(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 LF;return n.value=i,n}});function eL(e,t){return e.issues.length&&t===void 0?{issues:[],value:void 0}:e}const tL=IF(`$ZodOptional`,(e,t)=>{FI.init(e,t),e._zod.optin=`optional`,e._zod.optout=`optional`,qF(e._zod,`values`,()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),qF(e._zod,`pattern`,()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${GF(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=>eL(t,e.value)):eL(r,e.value)}return e.value===void 0?e:t.innerType._zod.run(e,n)}}),V_e=IF(`$ZodExactOptional`,(e,t)=>{tL.init(e,t),qF(e._zod,`values`,()=>t.innerType._zod.values),qF(e._zod,`pattern`,()=>t.innerType._zod.pattern),e._zod.parse=(e,n)=>t.innerType._zod.run(e,n)}),H_e=IF(`$ZodNullable`,(e,t)=>{FI.init(e,t),qF(e._zod,`optin`,()=>t.innerType._zod.optin),qF(e._zod,`optout`,()=>t.innerType._zod.optout),qF(e._zod,`pattern`,()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${GF(e.source)}|null)$`):void 0}),qF(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)}),U_e=IF(`$ZodDefault`,(e,t)=>{FI.init(e,t),e._zod.optin=`optional`,qF(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=>nL(e,t)):nL(r,t)}});function nL(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const W_e=IF(`$ZodPrefault`,(e,t)=>{FI.init(e,t),e._zod.optin=`optional`,qF(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))}),G_e=IF(`$ZodNonOptional`,(e,t)=>{FI.init(e,t),qF(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=>rL(t,e)):rL(i,e)}});function rL(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 K_e=IF(`$ZodSuccess`,(e,t)=>{FI.init(e,t),e._zod.parse=(e,n)=>{if(n.direction===`backward`)throw new RF(`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)}}),q_e=IF(`$ZodCatch`,(e,t)=>{FI.init(e,t),qF(e._zod,`optin`,()=>t.innerType._zod.optin),qF(e._zod,`optout`,()=>t.innerType._zod.optout),qF(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=>cI(e,n,BF()))},input:e.value}),e.issues=[]),e)):(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>cI(e,n,BF()))},input:e.value}),e.issues=[]),e)}}),J_e=IF(`$ZodNaN`,(e,t)=>{FI.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)}),Y_e=IF(`$ZodPipe`,(e,t)=>{FI.init(e,t),qF(e._zod,`values`,()=>t.in._zod.values),qF(e._zod,`optin`,()=>t.in._zod.optin),qF(e._zod,`optout`,()=>t.out._zod.optout),qF(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=>iL(e,t.in,n)):iL(r,t.in,n)}let r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>iL(e,t.out,n)):iL(r,t.out,n)}});function iL(e,t,n){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},n)}const X_e=IF(`$ZodCodec`,(e,t)=>{FI.init(e,t),qF(e._zod,`values`,()=>t.in._zod.values),qF(e._zod,`optin`,()=>t.in._zod.optin),qF(e._zod,`optout`,()=>t.out._zod.optout),qF(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=>aL(e,t,n)):aL(r,t,n)}else{let r=t.out._zod.run(e,n);return r instanceof Promise?r.then(e=>aL(e,t,n)):aL(r,t,n)}}});function aL(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=>oL(e,r,t.out,n)):oL(e,r,t.out,n)}else{let r=t.reverseTransform(e.value,e);return r instanceof Promise?r.then(r=>oL(e,r,t.in,n)):oL(e,r,t.in,n)}}function oL(e,t,n,r){return e.issues.length?(e.aborted=!0,e):n._zod.run({value:t,issues:e.issues},r)}const Z_e=IF(`$ZodReadonly`,(e,t)=>{FI.init(e,t),qF(e._zod,`propValues`,()=>t.innerType._zod.propValues),qF(e._zod,`values`,()=>t.innerType._zod.values),qF(e._zod,`optin`,()=>t.innerType?._zod?.optin),qF(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(sL):sL(r)}});function sL(e){return e.value=Object.freeze(e.value),e}const Q_e=IF(`$ZodTemplateLiteral`,(e,t)=>{FI.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(`^`)?1:0,i=t.endsWith(`$`)?t.length-1:t.length;n.push(t.slice(r,i))}else if(e===null||khe.has(typeof e))n.push(nI(`${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)}),$_e=IF(`$ZodFunction`,(e,t)=>(FI.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?gI(e._def.input,n):n,i=Reflect.apply(t,this,r);return e._def.output?gI(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 vI(e._def.input,n):n,i=await Reflect.apply(t,this,r);return e._def.output?await vI(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 XI({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)),eve=IF(`$ZodPromise`,(e,t)=>{FI.init(e,t),e._zod.parse=(e,n)=>Promise.resolve(e.value).then(e=>t.innerType._zod.run({value:e,issues:[]},n))}),tve=IF(`$ZodLazy`,(e,t)=>{FI.init(e,t),qF(e._zod,`innerType`,()=>t.getter()),qF(e._zod,`pattern`,()=>e._zod.innerType?._zod?.pattern),qF(e._zod,`propValues`,()=>e._zod.innerType?._zod?.propValues),qF(e._zod,`optin`,()=>e._zod.innerType?._zod?.optin??void 0),qF(e._zod,`optout`,()=>e._zod.innerType?._zod?.optout??void 0),e._zod.parse=(t,n)=>e._zod.innerType._zod.run(t,n)}),nve=IF(`$ZodCustom`,(e,t)=>{kI.init(e,t),FI.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=>cL(t,n,r,e));cL(i,n,r,e)}});function cL(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(dI(e))}}var lL,rve=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 ive(){return new rve}(lL=globalThis).__zod_globalRegistry??(lL.__zod_globalRegistry=ive());const uL=globalThis.__zod_globalRegistry;function ave(e,t){return new e({type:`string`,...iI(t)})}function ove(e,t){return new e({type:`string`,coerce:!0,...iI(t)})}function sve(e,t){return new e({type:`string`,format:`email`,check:`string_format`,abort:!1,...iI(t)})}function dL(e,t){return new e({type:`string`,format:`guid`,check:`string_format`,abort:!1,...iI(t)})}function cve(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,...iI(t)})}function lve(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v4`,...iI(t)})}function uve(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v6`,...iI(t)})}function dve(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v7`,...iI(t)})}function fL(e,t){return new e({type:`string`,format:`url`,check:`string_format`,abort:!1,...iI(t)})}function fve(e,t){return new e({type:`string`,format:`emoji`,check:`string_format`,abort:!1,...iI(t)})}function pve(e,t){return new e({type:`string`,format:`nanoid`,check:`string_format`,abort:!1,...iI(t)})}function mve(e,t){return new e({type:`string`,format:`cuid`,check:`string_format`,abort:!1,...iI(t)})}function hve(e,t){return new e({type:`string`,format:`cuid2`,check:`string_format`,abort:!1,...iI(t)})}function gve(e,t){return new e({type:`string`,format:`ulid`,check:`string_format`,abort:!1,...iI(t)})}function _ve(e,t){return new e({type:`string`,format:`xid`,check:`string_format`,abort:!1,...iI(t)})}function vve(e,t){return new e({type:`string`,format:`ksuid`,check:`string_format`,abort:!1,...iI(t)})}function yve(e,t){return new e({type:`string`,format:`ipv4`,check:`string_format`,abort:!1,...iI(t)})}function bve(e,t){return new e({type:`string`,format:`ipv6`,check:`string_format`,abort:!1,...iI(t)})}function xve(e,t){return new e({type:`string`,format:`cidrv4`,check:`string_format`,abort:!1,...iI(t)})}function Sve(e,t){return new e({type:`string`,format:`cidrv6`,check:`string_format`,abort:!1,...iI(t)})}function Cve(e,t){return new e({type:`string`,format:`base64`,check:`string_format`,abort:!1,...iI(t)})}function wve(e,t){return new e({type:`string`,format:`base64url`,check:`string_format`,abort:!1,...iI(t)})}function Tve(e,t){return new e({type:`string`,format:`e164`,check:`string_format`,abort:!1,...iI(t)})}function Eve(e,t){return new e({type:`string`,format:`jwt`,check:`string_format`,abort:!1,...iI(t)})}function Dve(e,t){return new e({type:`string`,format:`datetime`,check:`string_format`,offset:!1,local:!1,precision:null,...iI(t)})}function Ove(e,t){return new e({type:`string`,format:`date`,check:`string_format`,...iI(t)})}function kve(e,t){return new e({type:`string`,format:`time`,check:`string_format`,precision:null,...iI(t)})}function Ave(e,t){return new e({type:`string`,format:`duration`,check:`string_format`,...iI(t)})}function jve(e,t){return new e({type:`number`,checks:[],...iI(t)})}function Mve(e,t){return new e({type:`number`,coerce:!0,checks:[],...iI(t)})}function Nve(e,t){return new e({type:`number`,check:`number_format`,abort:!1,format:`safeint`,...iI(t)})}function Pve(e,t){return new e({type:`boolean`,...iI(t)})}function Fve(e,t){return new e({type:`null`,...iI(t)})}function Ive(e){return new e({type:`any`})}function Lve(e){return new e({type:`unknown`})}function Rve(e,t){return new e({type:`never`,...iI(t)})}function pL(e,t){return new jI({check:`less_than`,...iI(t),value:e,inclusive:!1})}function mL(e,t){return new jI({check:`less_than`,...iI(t),value:e,inclusive:!0})}function hL(e,t){return new MI({check:`greater_than`,...iI(t),value:e,inclusive:!1})}function gL(e,t){return new MI({check:`greater_than`,...iI(t),value:e,inclusive:!0})}function _L(e,t){return new Tge({check:`multiple_of`,...iI(t),value:e})}function vL(e,t){return new Oge({check:`max_size`,...iI(t),maximum:e})}function yL(e,t){return new kge({check:`min_size`,...iI(t),minimum:e})}function bL(e,t){return new Age({check:`size_equals`,...iI(t),size:e})}function xL(e,t){return new jge({check:`max_length`,...iI(t),maximum:e})}function SL(e,t){return new Mge({check:`min_length`,...iI(t),minimum:e})}function CL(e,t){return new Nge({check:`length_equals`,...iI(t),length:e})}function zve(e,t){return new Pge({check:`string_format`,format:`regex`,...iI(t),pattern:e})}function Bve(e){return new Fge({check:`string_format`,format:`lowercase`,...iI(e)})}function Vve(e){return new Ige({check:`string_format`,format:`uppercase`,...iI(e)})}function Hve(e,t){return new Lge({check:`string_format`,format:`includes`,...iI(t),includes:e})}function Uve(e,t){return new Rge({check:`string_format`,format:`starts_with`,...iI(t),prefix:e})}function Wve(e,t){return new zge({check:`string_format`,format:`ends_with`,...iI(t),suffix:e})}function Gve(e,t){return new Bge({check:`mime_type`,mime:e,...iI(t)})}function wL(e){return new Vge({check:`overwrite`,tx:e})}function Kve(e){return wL(t=>t.normalize(e))}function qve(){return wL(e=>e.trim())}function Jve(){return wL(e=>e.toLowerCase())}function Yve(){return wL(e=>e.toUpperCase())}function Xve(){return wL(e=>Dhe(e))}function Zve(e,t,n){return new e({type:`array`,element:t,...iI(n)})}function Qve(e,t,n){let r=iI(n);return r.abort??=!0,new e({type:`custom`,check:`custom`,fn:t,...r})}function $ve(e,t,n){return new e({type:`custom`,check:`custom`,fn:t,...iI(n)})}function eye(e){let t=tye(n=>(n.addIssue=e=>{if(typeof e==`string`)n.issues.push(dI(e,n.value,t._zod.def));else{let r=e;r.fatal&&(r.continue=!1),r.code??=`custom`,r.input??=n.value,r.inst??=t,r.continue??=!t._zod.def.abort,n.issues.push(dI(r))}},e(n.value,n)));return t}function tye(e,t){let n=new kI({check:`custom`,...iI(t)});return n._zod.check=e,n}function TL(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??uL,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 EL(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,EL(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`&&kL(e)&&(delete o.schema.examples,delete o.schema.default),t.io===`input`&&o.schema._prefault&&((r=o.schema).default??(r.default=o.schema._prefault)),delete o.schema._prefault,t.seen.get(e).schema}function DL(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>
1870
1870
 
1871
- 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 OL(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.external?.defs??{};for(let t of e.seen.entries()){let e=t[1];e.def&&e.defId&&(a[e.defId]=e.def)}e.external||Object.keys(a).length>0&&(e.target===`draft-2020-12`?i.$defs=a:i.definitions=a);try{let n=JSON.parse(JSON.stringify(i));return Object.defineProperty(n,`~standard`,{value:{...t[`~standard`],jsonSchema:{input:AL(t,`input`,e.processors),output:AL(t,`output`,e.processors)}},enumerable:!1,writable:!1}),n}catch{throw Error(`Error converting schema to JSON.`)}}function kL(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 kL(r.element,n);if(r.type===`set`)return kL(r.valueType,n);if(r.type===`lazy`)return kL(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 kL(r.innerType,n);if(r.type===`intersection`)return kL(r.left,n)||kL(r.right,n);if(r.type===`record`||r.type===`map`)return kL(r.keyType,n)||kL(r.valueType,n);if(r.type===`pipe`)return kL(r.in,n)||kL(r.out,n);if(r.type===`object`){for(let e in r.shape)if(kL(r.shape[e],n))return!0;return!1}if(r.type===`union`){for(let e of r.options)if(kL(e,n))return!0;return!1}if(r.type===`tuple`){for(let e of r.items)if(kL(e,n))return!0;return!!(r.rest&&kL(r.rest,n))}return!1}const nye=(e,t={})=>n=>{let r=TL({...n,processors:t});return EL(e,r),DL(r,e),OL(r,e)},AL=(e,t,n={})=>r=>{let{libraryOptions:i,target:a}=r??{},o=TL({...i??{},target:a,io:t,processors:n});return EL(e,o),DL(o,e),OL(o,e)},rye={guid:`uuid`,url:`uri`,datetime:`date-time`,json_string:`json-string`,regex:``},iye=(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=rye[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}))])}},aye=(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`,typeof u==`number`&&(t.target===`draft-04`||t.target===`openapi-3.0`?(i.minimum=u,i.exclusiveMinimum=!0):i.exclusiveMinimum=u),typeof a==`number`&&(i.minimum=a,typeof u==`number`&&t.target!==`draft-04`&&(u>=a?delete i.minimum:delete i.exclusiveMinimum)),typeof l==`number`&&(t.target===`draft-04`||t.target===`openapi-3.0`?(i.maximum=l,i.exclusiveMaximum=!0):i.exclusiveMaximum=l),typeof o==`number`&&(i.maximum=o,typeof l==`number`&&t.target!==`draft-04`&&(l<=o?delete i.maximum:delete i.exclusiveMaximum)),typeof c==`number`&&(i.multipleOf=c)},oye=(e,t,n,r)=>{n.type=`boolean`},sye=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`BigInt cannot be represented in JSON Schema`)},cye=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Symbols cannot be represented in JSON Schema`)},lye=(e,t,n,r)=>{t.target===`openapi-3.0`?(n.type=`string`,n.nullable=!0,n.enum=[null]):n.type=`null`},uye=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Undefined cannot be represented in JSON Schema`)},dye=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Void cannot be represented in JSON Schema`)},fye=(e,t,n,r)=>{n.not={}},pye=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Date cannot be represented in JSON Schema`)},mye=(e,t,n,r)=>{let i=e._zod.def,a=VF(i.entries);a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),n.enum=a},hye=(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},gye=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`NaN cannot be represented in JSON Schema`)},_ye=(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},vye=(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)},yye=(e,t,n,r)=>{n.type=`boolean`},bye=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Custom types cannot be represented in JSON Schema`)},xye=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Function types cannot be represented in JSON Schema`)},Sye=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Transforms cannot be represented in JSON Schema`)},Cye=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Map cannot be represented in JSON Schema`)},wye=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Set cannot be represented in JSON Schema`)},Tye=(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=EL(a.element,t,{...r,path:[...r.path,`items`]})},Eye=(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]=EL(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=EL(a.catchall,t,{...r,path:[...r.path,`additionalProperties`]})):t.io===`output`&&(i.additionalProperties=!1)},jL=(e,t,n,r)=>{let i=e._zod.def,a=i.inclusive===!1,o=i.options.map((e,n)=>EL(e,t,{...r,path:[...r.path,a?`oneOf`:`anyOf`,n]}));a?n.oneOf=o:n.anyOf=o},Dye=(e,t,n,r)=>{let i=e._zod.def,a=EL(i.left,t,{...r,path:[...r.path,`allOf`,0]}),o=EL(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]]},Oye=(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)=>EL(e,t,{...r,path:[...r.path,o,n]})),l=a.rest?EL(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)},kye=(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=EL(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=EL(a.keyType,t,{...r,path:[...r.path,`propertyNames`]})),i.additionalProperties=EL(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)}},Aye=(e,t,n,r)=>{let i=e._zod.def,a=EL(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`}]},jye=(e,t,n,r)=>{let i=e._zod.def;EL(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},Mye=(e,t,n,r)=>{let i=e._zod.def;EL(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.default=JSON.parse(JSON.stringify(i.defaultValue))},Nye=(e,t,n,r)=>{let i=e._zod.def;EL(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)))},Pye=(e,t,n,r)=>{let i=e._zod.def;EL(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},Fye=(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;EL(a,t,r);let o=t.seen.get(e);o.ref=a},Iye=(e,t,n,r)=>{let i=e._zod.def;EL(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.readOnly=!0},Lye=(e,t,n,r)=>{let i=e._zod.def;EL(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},ML=(e,t,n,r)=>{let i=e._zod.def;EL(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},Rye=(e,t,n,r)=>{let i=e._zod.innerType;EL(i,t,r);let a=t.seen.get(e);a.ref=i},zye=IF(`ZodISODateTime`,(e,t)=>{t_e.init(e,t),zL.init(e,t)});function NL(e){return Dve(zye,e)}const Bye=IF(`ZodISODate`,(e,t)=>{n_e.init(e,t),zL.init(e,t)});function Vye(e){return Ove(Bye,e)}const Hye=IF(`ZodISOTime`,(e,t)=>{r_e.init(e,t),zL.init(e,t)});function Uye(e){return kve(Hye,e)}const Wye=IF(`ZodISODuration`,(e,t)=>{i_e.init(e,t),zL.init(e,t)});function Gye(e){return Ave(Wye,e)}const PL=(e,t)=>{pI.init(e,t),e.name=`ZodError`,Object.defineProperties(e,{format:{value:t=>Vhe(e,t)},flatten:{value:t=>Bhe(e,t)},addIssue:{value:t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,HF,2)}},addIssues:{value:t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,HF,2)}},isEmpty:{get(){return e.issues.length===0}}})};IF(`ZodError`,PL);const FL=IF(`ZodError`,PL,{Parent:Error}),Kye=hI(FL),qye=_I(FL),Jye=yI(FL),Yye=xI(FL),Xye=Uhe(FL),Zye=Whe(FL),Qye=Ghe(FL),$ye=Khe(FL),ebe=qhe(FL),tbe=Jhe(FL),nbe=Yhe(FL),rbe=Xhe(FL),IL=IF(`ZodType`,(e,t)=>(FI.init(e,t),Object.assign(e[`~standard`],{jsonSchema:{input:AL(e,`input`),output:AL(e,`output`)}}),e.toJSONSchema=nye(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,`_def`,{value:t}),e.check=(...n)=>e.clone(YF(t,{checks:[...t.checks??[],...n.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]}),{parent:!0}),e.with=e.check,e.clone=(t,n)=>rI(e,t,n),e.brand=()=>e,e.register=((t,n)=>(t.add(e,n),e)),e.parse=(t,n)=>Kye(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>Jye(e,t,n),e.parseAsync=async(t,n)=>qye(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>Yye(e,t,n),e.spa=e.safeParseAsync,e.encode=(t,n)=>Xye(e,t,n),e.decode=(t,n)=>Zye(e,t,n),e.encodeAsync=async(t,n)=>Qye(e,t,n),e.decodeAsync=async(t,n)=>$ye(e,t,n),e.safeEncode=(t,n)=>ebe(e,t,n),e.safeDecode=(t,n)=>tbe(e,t,n),e.safeEncodeAsync=async(t,n)=>nbe(e,t,n),e.safeDecodeAsync=async(t,n)=>rbe(e,t,n),e.refine=(t,n)=>e.check(Ybe(t,n)),e.superRefine=t=>e.check(Xbe(t)),e.overwrite=t=>e.check(wL(t)),e.optional=()=>dR(e),e.exactOptional=()=>Lbe(e),e.nullable=()=>fR(e),e.nullish=()=>dR(fR(e)),e.nonoptional=t=>Ube(e,t),e.array=()=>XL(e),e.or=t=>tR([e,t]),e.and=t=>rR(e,t),e.transform=t=>hR(e,lR(t)),e.default=t=>Bbe(e,t),e.prefault=t=>Hbe(e,t),e.catch=t=>Gbe(e,t),e.pipe=t=>hR(e,t),e.readonly=()=>qbe(e),e.describe=t=>{let n=e.clone();return uL.add(n,{description:t}),n},Object.defineProperty(e,`description`,{get(){return uL.get(e)?.description},configurable:!0}),e.meta=(...t)=>{if(t.length===0)return uL.get(e);let n=e.clone();return uL.add(n,t[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e.apply=t=>t(e),e)),LL=IF(`_ZodString`,(e,t)=>{II.init(e,t),IL.init(e,t),e._zod.processJSONSchema=(t,n,r)=>iye(e,t,n,r);let n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,e.regex=(...t)=>e.check(zve(...t)),e.includes=(...t)=>e.check(Hve(...t)),e.startsWith=(...t)=>e.check(Uve(...t)),e.endsWith=(...t)=>e.check(Wve(...t)),e.min=(...t)=>e.check(SL(...t)),e.max=(...t)=>e.check(xL(...t)),e.length=(...t)=>e.check(CL(...t)),e.nonempty=(...t)=>e.check(SL(1,...t)),e.lowercase=t=>e.check(Bve(t)),e.uppercase=t=>e.check(Vve(t)),e.trim=()=>e.check(qve()),e.normalize=(...t)=>e.check(Kve(...t)),e.toLowerCase=()=>e.check(Jve()),e.toUpperCase=()=>e.check(Yve()),e.slugify=()=>e.check(Xve())}),RL=IF(`ZodString`,(e,t)=>{II.init(e,t),LL.init(e,t),e.email=t=>e.check(sve(ibe,t)),e.url=t=>e.check(fL(HL,t)),e.jwt=t=>e.check(Eve(bbe,t)),e.emoji=t=>e.check(fve(obe,t)),e.guid=t=>e.check(dL(BL,t)),e.uuid=t=>e.check(cve(VL,t)),e.uuidv4=t=>e.check(lve(VL,t)),e.uuidv6=t=>e.check(uve(VL,t)),e.uuidv7=t=>e.check(dve(VL,t)),e.nanoid=t=>e.check(pve(sbe,t)),e.guid=t=>e.check(dL(BL,t)),e.cuid=t=>e.check(mve(cbe,t)),e.cuid2=t=>e.check(hve(lbe,t)),e.ulid=t=>e.check(gve(ube,t)),e.base64=t=>e.check(Cve(_be,t)),e.base64url=t=>e.check(wve(vbe,t)),e.xid=t=>e.check(_ve(dbe,t)),e.ksuid=t=>e.check(vve(fbe,t)),e.ipv4=t=>e.check(yve(pbe,t)),e.ipv6=t=>e.check(bve(mbe,t)),e.cidrv4=t=>e.check(xve(hbe,t)),e.cidrv6=t=>e.check(Sve(gbe,t)),e.e164=t=>e.check(Tve(ybe,t)),e.datetime=t=>e.check(NL(t)),e.date=t=>e.check(Vye(t)),e.time=t=>e.check(Uye(t)),e.duration=t=>e.check(Gye(t))});function Y(e){return ave(RL,e)}const zL=IF(`ZodStringFormat`,(e,t)=>{LI.init(e,t),LL.init(e,t)}),ibe=IF(`ZodEmail`,(e,t)=>{Kge.init(e,t),zL.init(e,t)}),BL=IF(`ZodGUID`,(e,t)=>{Wge.init(e,t),zL.init(e,t)}),VL=IF(`ZodUUID`,(e,t)=>{Gge.init(e,t),zL.init(e,t)}),HL=IF(`ZodURL`,(e,t)=>{qge.init(e,t),zL.init(e,t)});function abe(e){return fL(HL,e)}const obe=IF(`ZodEmoji`,(e,t)=>{Jge.init(e,t),zL.init(e,t)}),sbe=IF(`ZodNanoID`,(e,t)=>{Yge.init(e,t),zL.init(e,t)}),cbe=IF(`ZodCUID`,(e,t)=>{Xge.init(e,t),zL.init(e,t)}),lbe=IF(`ZodCUID2`,(e,t)=>{Zge.init(e,t),zL.init(e,t)}),ube=IF(`ZodULID`,(e,t)=>{Qge.init(e,t),zL.init(e,t)}),dbe=IF(`ZodXID`,(e,t)=>{$ge.init(e,t),zL.init(e,t)}),fbe=IF(`ZodKSUID`,(e,t)=>{e_e.init(e,t),zL.init(e,t)}),pbe=IF(`ZodIPv4`,(e,t)=>{a_e.init(e,t),zL.init(e,t)});IF(`ZodMAC`,(e,t)=>{s_e.init(e,t),zL.init(e,t)});const mbe=IF(`ZodIPv6`,(e,t)=>{o_e.init(e,t),zL.init(e,t)}),hbe=IF(`ZodCIDRv4`,(e,t)=>{c_e.init(e,t),zL.init(e,t)}),gbe=IF(`ZodCIDRv6`,(e,t)=>{l_e.init(e,t),zL.init(e,t)}),_be=IF(`ZodBase64`,(e,t)=>{u_e.init(e,t),zL.init(e,t)}),vbe=IF(`ZodBase64URL`,(e,t)=>{f_e.init(e,t),zL.init(e,t)}),ybe=IF(`ZodE164`,(e,t)=>{p_e.init(e,t),zL.init(e,t)}),bbe=IF(`ZodJWT`,(e,t)=>{h_e.init(e,t),zL.init(e,t)});IF(`ZodCustomStringFormat`,(e,t)=>{g_e.init(e,t),zL.init(e,t)});const UL=IF(`ZodNumber`,(e,t)=>{zI.init(e,t),IL.init(e,t),e._zod.processJSONSchema=(t,n,r)=>aye(e,t,n,r),e.gt=(t,n)=>e.check(hL(t,n)),e.gte=(t,n)=>e.check(gL(t,n)),e.min=(t,n)=>e.check(gL(t,n)),e.lt=(t,n)=>e.check(pL(t,n)),e.lte=(t,n)=>e.check(mL(t,n)),e.max=(t,n)=>e.check(mL(t,n)),e.int=t=>e.check(GL(t)),e.safe=t=>e.check(GL(t)),e.positive=t=>e.check(hL(0,t)),e.nonnegative=t=>e.check(gL(0,t)),e.negative=t=>e.check(pL(0,t)),e.nonpositive=t=>e.check(mL(0,t)),e.multipleOf=(t,n)=>e.check(_L(t,n)),e.step=(t,n)=>e.check(_L(t,n)),e.finite=()=>e;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 WL(e){return jve(UL,e)}const xbe=IF(`ZodNumberFormat`,(e,t)=>{__e.init(e,t),UL.init(e,t)});function GL(e){return Nve(xbe,e)}const Sbe=IF(`ZodBoolean`,(e,t)=>{v_e.init(e,t),IL.init(e,t),e._zod.processJSONSchema=(t,n,r)=>oye(e,t,n,r)});function KL(e){return Pve(Sbe,e)}const Cbe=IF(`ZodBigInt`,(e,t)=>{BI.init(e,t),IL.init(e,t),e._zod.processJSONSchema=(t,n,r)=>sye(e,t,n,r),e.gte=(t,n)=>e.check(gL(t,n)),e.min=(t,n)=>e.check(gL(t,n)),e.gt=(t,n)=>e.check(hL(t,n)),e.gte=(t,n)=>e.check(gL(t,n)),e.min=(t,n)=>e.check(gL(t,n)),e.lt=(t,n)=>e.check(pL(t,n)),e.lte=(t,n)=>e.check(mL(t,n)),e.max=(t,n)=>e.check(mL(t,n)),e.positive=t=>e.check(hL(BigInt(0),t)),e.negative=t=>e.check(pL(BigInt(0),t)),e.nonpositive=t=>e.check(mL(BigInt(0),t)),e.nonnegative=t=>e.check(gL(BigInt(0),t)),e.multipleOf=(t,n)=>e.check(_L(t,n));let n=e._zod.bag;e.minValue=n.minimum??null,e.maxValue=n.maximum??null,e.format=n.format??null});IF(`ZodBigIntFormat`,(e,t)=>{y_e.init(e,t),Cbe.init(e,t)}),IF(`ZodSymbol`,(e,t)=>{b_e.init(e,t),IL.init(e,t),e._zod.processJSONSchema=(t,n,r)=>cye(e,t,n,r)}),IF(`ZodUndefined`,(e,t)=>{x_e.init(e,t),IL.init(e,t),e._zod.processJSONSchema=(t,n,r)=>uye(e,t,n,r)});const wbe=IF(`ZodNull`,(e,t)=>{S_e.init(e,t),IL.init(e,t),e._zod.processJSONSchema=(t,n,r)=>lye(e,t,n,r)});function qL(e){return Fve(wbe,e)}const Tbe=IF(`ZodAny`,(e,t)=>{C_e.init(e,t),IL.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function JL(){return Ive(Tbe)}const Ebe=IF(`ZodUnknown`,(e,t)=>{w_e.init(e,t),IL.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function YL(){return Lve(Ebe)}const Dbe=IF(`ZodNever`,(e,t)=>{T_e.init(e,t),IL.init(e,t),e._zod.processJSONSchema=(t,n,r)=>fye(e,t,n,r)});function Obe(e){return Rve(Dbe,e)}IF(`ZodVoid`,(e,t)=>{E_e.init(e,t),IL.init(e,t),e._zod.processJSONSchema=(t,n,r)=>dye(e,t,n,r)}),IF(`ZodDate`,(e,t)=>{D_e.init(e,t),IL.init(e,t),e._zod.processJSONSchema=(t,n,r)=>pye(e,t,n,r),e.min=(t,n)=>e.check(gL(t,n)),e.max=(t,n)=>e.check(mL(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 kbe=IF(`ZodArray`,(e,t)=>{O_e.init(e,t),IL.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Tye(e,t,n,r),e.element=t.element,e.min=(t,n)=>e.check(SL(t,n)),e.nonempty=t=>e.check(SL(1,t)),e.max=(t,n)=>e.check(xL(t,n)),e.length=(t,n)=>e.check(CL(t,n)),e.unwrap=()=>e.element});function XL(e,t){return Zve(kbe,e,t)}const ZL=IF(`ZodObject`,(e,t)=>{A_e.init(e,t),IL.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Eye(e,t,n,r),qF(e,`shape`,()=>t.shape),e.keyof=()=>sR(Object.keys(e._zod.def.shape)),e.catchall=t=>e.clone({...e._zod.def,catchall:t}),e.passthrough=()=>e.clone({...e._zod.def,catchall:YL()}),e.loose=()=>e.clone({...e._zod.def,catchall:YL()}),e.strict=()=>e.clone({...e._zod.def,catchall:Obe()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=t=>Fhe(e,t),e.safeExtend=t=>Ihe(e,t),e.merge=t=>Lhe(e,t),e.pick=t=>Nhe(e,t),e.omit=t=>Phe(e,t),e.partial=(...t)=>Rhe(uR,e,t[0]),e.required=(...t)=>zhe(pR,e,t[0])});function QL(e,t){return new ZL({type:`object`,shape:e??{},...iI(t)})}function $L(e,t){return new ZL({type:`object`,shape:e,catchall:YL(),...iI(t)})}const eR=IF(`ZodUnion`,(e,t)=>{KI.init(e,t),IL.init(e,t),e._zod.processJSONSchema=(t,n,r)=>jL(e,t,n,r),e.options=t.options});function tR(e,t){return new eR({type:`union`,options:e,...iI(t)})}IF(`ZodXor`,(e,t)=>{eR.init(e,t),j_e.init(e,t),e._zod.processJSONSchema=(t,n,r)=>jL(e,t,n,r),e.options=t.options});const Abe=IF(`ZodDiscriminatedUnion`,(e,t)=>{eR.init(e,t),M_e.init(e,t)});function nR(e,t,n){return new Abe({type:`union`,options:t,discriminator:e,...iI(n)})}const jbe=IF(`ZodIntersection`,(e,t)=>{N_e.init(e,t),IL.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Dye(e,t,n,r)});function rR(e,t){return new jbe({type:`intersection`,left:e,right:t})}const Mbe=IF(`ZodTuple`,(e,t)=>{XI.init(e,t),IL.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Oye(e,t,n,r),e.rest=t=>e.clone({...e._zod.def,rest:t})});function iR(e,t,n){let r=t instanceof FI;return new Mbe({type:`tuple`,items:e,rest:r?t:null,...iI(r?n:t)})}const Nbe=IF(`ZodRecord`,(e,t)=>{P_e.init(e,t),IL.init(e,t),e._zod.processJSONSchema=(t,n,r)=>kye(e,t,n,r),e.keyType=t.keyType,e.valueType=t.valueType});function aR(e,t,n){return new Nbe({type:`record`,keyType:e,valueType:t,...iI(n)})}IF(`ZodMap`,(e,t)=>{F_e.init(e,t),IL.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Cye(e,t,n,r),e.keyType=t.keyType,e.valueType=t.valueType,e.min=(...t)=>e.check(yL(...t)),e.nonempty=t=>e.check(yL(1,t)),e.max=(...t)=>e.check(vL(...t)),e.size=(...t)=>e.check(bL(...t))}),IF(`ZodSet`,(e,t)=>{I_e.init(e,t),IL.init(e,t),e._zod.processJSONSchema=(t,n,r)=>wye(e,t,n,r),e.min=(...t)=>e.check(yL(...t)),e.nonempty=t=>e.check(yL(1,t)),e.max=(...t)=>e.check(vL(...t)),e.size=(...t)=>e.check(bL(...t))});const oR=IF(`ZodEnum`,(e,t)=>{L_e.init(e,t),IL.init(e,t),e._zod.processJSONSchema=(t,n,r)=>mye(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 oR({...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 oR({...t,checks:[],...iI(r),entries:i})}});function sR(e,t){return new oR({type:`enum`,entries:Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e,...iI(t)})}const Pbe=IF(`ZodLiteral`,(e,t)=>{R_e.init(e,t),IL.init(e,t),e._zod.processJSONSchema=(t,n,r)=>hye(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 cR(e,t){return new Pbe({type:`literal`,values:Array.isArray(e)?e:[e],...iI(t)})}IF(`ZodFile`,(e,t)=>{z_e.init(e,t),IL.init(e,t),e._zod.processJSONSchema=(t,n,r)=>vye(e,t,n,r),e.min=(t,n)=>e.check(yL(t,n)),e.max=(t,n)=>e.check(vL(t,n)),e.mime=(t,n)=>e.check(Gve(Array.isArray(t)?t:[t],n))});const Fbe=IF(`ZodTransform`,(e,t)=>{B_e.init(e,t),IL.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Sye(e,t,n,r),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new RF(e.constructor.name);n.addIssue=r=>{if(typeof r==`string`)n.issues.push(dI(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(dI(t))}};let i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n)):(n.value=i,n)}});function lR(e){return new Fbe({type:`transform`,transform:e})}const uR=IF(`ZodOptional`,(e,t)=>{tL.init(e,t),IL.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ML(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function dR(e){return new uR({type:`optional`,innerType:e})}const Ibe=IF(`ZodExactOptional`,(e,t)=>{V_e.init(e,t),IL.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ML(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Lbe(e){return new Ibe({type:`optional`,innerType:e})}const Rbe=IF(`ZodNullable`,(e,t)=>{H_e.init(e,t),IL.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Aye(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function fR(e){return new Rbe({type:`nullable`,innerType:e})}const zbe=IF(`ZodDefault`,(e,t)=>{U_e.init(e,t),IL.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Mye(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Bbe(e,t){return new zbe({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():eI(t)}})}const Vbe=IF(`ZodPrefault`,(e,t)=>{W_e.init(e,t),IL.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Nye(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Hbe(e,t){return new Vbe({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():eI(t)}})}const pR=IF(`ZodNonOptional`,(e,t)=>{G_e.init(e,t),IL.init(e,t),e._zod.processJSONSchema=(t,n,r)=>jye(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Ube(e,t){return new pR({type:`nonoptional`,innerType:e,...iI(t)})}IF(`ZodSuccess`,(e,t)=>{K_e.init(e,t),IL.init(e,t),e._zod.processJSONSchema=(t,n,r)=>yye(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});const Wbe=IF(`ZodCatch`,(e,t)=>{q_e.init(e,t),IL.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Pye(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Gbe(e,t){return new Wbe({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:()=>t})}IF(`ZodNaN`,(e,t)=>{J_e.init(e,t),IL.init(e,t),e._zod.processJSONSchema=(t,n,r)=>gye(e,t,n,r)});const mR=IF(`ZodPipe`,(e,t)=>{Y_e.init(e,t),IL.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Fye(e,t,n,r),e.in=t.in,e.out=t.out});function hR(e,t){return new mR({type:`pipe`,in:e,out:t})}IF(`ZodCodec`,(e,t)=>{mR.init(e,t),X_e.init(e,t)});const Kbe=IF(`ZodReadonly`,(e,t)=>{Z_e.init(e,t),IL.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Iye(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function qbe(e){return new Kbe({type:`readonly`,innerType:e})}IF(`ZodTemplateLiteral`,(e,t)=>{Q_e.init(e,t),IL.init(e,t),e._zod.processJSONSchema=(t,n,r)=>_ye(e,t,n,r)}),IF(`ZodLazy`,(e,t)=>{tve.init(e,t),IL.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Rye(e,t,n,r),e.unwrap=()=>e._zod.def.getter()}),IF(`ZodPromise`,(e,t)=>{eve.init(e,t),IL.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Lye(e,t,n,r),e.unwrap=()=>e._zod.def.innerType}),IF(`ZodFunction`,(e,t)=>{$_e.init(e,t),IL.init(e,t),e._zod.processJSONSchema=(t,n,r)=>xye(e,t,n,r)});const gR=IF(`ZodCustom`,(e,t)=>{nve.init(e,t),IL.init(e,t),e._zod.processJSONSchema=(t,n,r)=>bye(e,t,n,r)});function Jbe(e,t){return Qve(gR,e??(()=>!0),t)}function Ybe(e,t={}){return $ve(gR,e,t)}function Xbe(e){return eye(e)}function _R(e,t){return hR(lR(e),t)}const Zbe={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 Qbe;(function(e){})(Qbe||={});function vR(e){return ove(RL,e)}function yR(e){return Mve(UL,e)}const bR={USER_MESSAGE:`user_message`,REJECTED:`rejected`,INTERRUPTED:`interrupted`},$be={REJECTED:`rejected`};function xR(e){if(e===`Tool was rejected by user`)return{rejected:!0};try{let t=JSON.parse(e);if(t.reason===bR.USER_MESSAGE)return{rejected:!0,userNote:t.message};if(t.reason===bR.REJECTED||t.reason===bR.INTERRUPTED)return{rejected:!0};if(t.status===$be.REJECTED)return{rejected:!0,userNote:t.userNote}}catch{}return{rejected:!1}}const SR=`sibling_tool_failed`,CR=JSON.stringify({type:SR,message:`Not executed: a tool call in a preceding parallel batch failed`});function exe(e){try{return JSON.parse(e)?.type===SR}catch{return!1}}var wR=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}format(e,t){return typeof e==`string`?e:JSON.stringify(e)}formatForLLM(e,t){return this.format(e,t)}parse(e){let t=xR(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 txe=Symbol.for(`server-executed`);var TR=class extends wR{isReadonly=!0;async execute(e,t,n){return txe}format(e,t){return JSON.stringify({type:this.name,status:`server-executed`})}};dt([`codellm`,`agent`,`tools`,`subagent`]);var ER=class e extends TR{name=`subagent`;displayName=`Subagent`;description=`Switch to a different subagent for a task`;static parametersSchema=QL({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}format(e,t){return JSON.stringify({type:`subagent`,status:`success`,agent:t.agent,task:t.task})}parse(e){let t=xR(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`}}};dt([`codellm`,`agent`,`tools`,`todo-write`]);var DR=class e extends TR{name=`todo_write`;displayName=`TodoWrite`;description=`Create and manage a structured task list`;static parametersSchema=QL({todos:_R(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:[]},XL(QL({content:Y().describe(`The task content`),status:sR([`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=xR(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 OR(e){if(typeof e!=`string`)return e;let t=e.trim();return t?Number(t):NaN}function kR(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 nxe=_R(OR,WL()),AR=_R(OR,WL().optional()),jR=_R(kR,KL()),MR=_R(kR,KL().optional()),rxe=dt([`codellm`,`agent`,`tools`,`ask-user`]);var NR=class e extends wR{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=QL({questions:XL(QL({question:Y().describe(`The question to ask the user`),header:Y().describe(`A header/title for the question`),options:XL(QL({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:jR.describe(`Whether the user can select multiple options`)})).describe(`Array of questions to ask the user`),answers:aR(Y(),Y()).optional().describe(`User-provided answers to the questions`)});parameters=e.parametersSchema;needsPermission(){return!0}async execute(e){return rxe.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=xR(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 ixe=dt([`codellm`,`agent`,`tools`,`plan-mode`]);var PR=class e extends wR{name=`enter_plan_mode`;displayName=`EnterPlanMode`;description=`Enter plan mode to create a plan before implementing changes`;static parametersSchema=QL({});parameters=e.parametersSchema;isReadonly=!0;needsPermission(e,t,n){return!1}async execute(e,t){return ixe.info`Entering plan mode`,{success:!0}}format(e,t){return`Entered plan mode`}parse(e){let t=xR(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 axe=dt([`codellm`,`agent`,`tools`,`plan-mode`]);var FR=class e extends wR{name=`exit_plan_mode`;displayName=`ExitPlanMode`;description=`Exit plan mode and return to normal agent operation`;static parametersSchema=QL({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 axe.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=xR(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`}}},IR;(function(e){e.GeneralPurpose=`GENERAL_PURPOSE`,e.Explore=`EXPLORE`,e.Plan=`PLAN`})(IR||={});const oxe={[IR.GeneralPurpose]:{name:IR.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`},[IR.Explore]:{name:IR.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`},[IR.Plan]:{name:IR.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`}},sxe=new Set(Object.values(IR));function cxe(e){return sxe.has(e)}function LR(e){if(cxe(e))return e}function RR(e){return oxe[e]}function zR(){return Object.values(IR)}function BR(e){let t=LR(e);return t?RR(t).displayName:e}function lxe(e,t){let n=LR(e);if(!n)return!1;let r=RR(n);return r.allowedTools.includes(`*`)?!0:r.allowedTools.includes(t)}async function VR(e){return new Promise(t=>setTimeout(t,e))}const HR=dt([`codellm`,`agent`,`loop`]);function UR(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 UR(t.segment)}return null}function uxe(e){return Math.min((e+1)*2e3,1e4)}function WR(e){return 2**(e+1)*1e3}function*dxe(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 wd({...n.pendingCreditLimitSegment??void 0,message:r})}:Bl(r)?yield{__error:new Ll}:yield{__error:new Cd(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===`collapsible_component`&&e.isThoughts===!0){let t=e.title||`Thinking`,n=UR(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||UR(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=UR(e.segment);t&&(yield{type:`text_delta`,content:t})}}async function*fxe(e,t){let n=t?.generateRequestId?.()??crypto.randomUUID(),r=!1;HR.debug(`Starting agent loop (conversationId={conversationId}, model={model})`,{conversationId:e.conversationId,model:e.model});for(let t=0;t<8;t++){Al(`turn started`,`agent`);let i=n,a=!1;if(t>0){HR.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{let t=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 n of t){if(e.signal?.aborted)break;for(let e of dxe(n,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},HR.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 Ll){if(c&&t<4&&!e.signal?.aborted){let e=WR(t);HR.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}),Ol(`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 VR(e);continue}throw HR.warn(`Auth expired, aborting loop`),i}if(i instanceof wd)throw HR.warn(`Credit limit reached, aborting loop`),Ol(`Credit limit reached`,`warning`,{context:`agent-loop`}),i;let a=Vl(i),o=a?8:5;if(t<o-1&&!e.signal?.aborted){let e=a?uxe(t):WR(t);HR.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 VR(e);continue}throw HR.error(`All retry attempts exhausted: {error}`,{error:i.message}),Dl(i,{context:`agent-loop-retry-exhausted`}),Vl(i)?i instanceof Rl?i:new Rl(i.message,i):i}}}const GR=dt([`codellm`,`agent`,`runner`]);var pxe=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 mxe(e){return e.toUpperCase().includes(`CLAUDE`)}async function*KR(e,t,n){let r=e.maxTurns??2**53-1,i=t,a,o=0,s=0,c=[],l=e.agentMode;GR.info(`Starting agent conversation (model={model}, maxTurns={maxTurns})`,{model:e.model,maxTurns:r});try{for(;o<r;){if(n?.aborted)return GR.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 pxe,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 fxe(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||GR.warn(`Agent loop exited without turn_complete_with_tools (collected {count} tool calls)`,{count:r.length}),r.length===0){GR.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===bR.REJECTED}catch{return!1}}),D=C.some((e,t)=>{if(!T(e,t))return!1;try{return JSON.parse(e.content).reason===bR.INTERRUPTED}catch{return!1}}),O=C.some(e=>{if(!e.rejected)return!1;try{return JSON.parse(e.content).reason===bR.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.`,M=e.getQueuedMessage?.();M&&mxe(e.model)?(i=A?`${j} ${M}`:M,e.clearQueuedMessage?.(),e.isQueuedMessageHidden?.()||(yield{type:`user_message_dequeued`,content:M})):i=A?j:``,yield{type:`turn_complete`}}if(o>=r){GR.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 GR.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 Dl(t,{context:`agent-runner`}),GR.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 qR=dt([`codellm`,`agent`,`subagent`]);function hxe(e,t){let n=RR(t);return!n||n.allowedTools.includes(`*`)?e:e.filter(e=>lxe(t,e.name))}function gxe(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=cF(n.resolvedPath);return{type:`read_outside_directory`,tool:e,displayName:a,filePath:t,resolvedPath:t,deducedDirectory:O.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=cF(n.resolvedPath??e.input.filePath??``);return{type:`edit_outside_directory`,tool:e,displayName:a,filePath:t,resolvedPath:t,deducedDirectory:O.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=cF(n.resolvedPath??e.input.filePath??``);return{type:`write_outside_directory`,tool:e,displayName:a,filePath:t,resolvedPath:t,deducedDirectory:O.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=cF(n.resolvedPath??e.input.notebookPath??``);return{type:`notebook_edit_outside_directory`,tool:e,displayName:a,filePath:t,resolvedPath:t,deducedDirectory:O.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 _xe(e){let{prompt:t,subagentType:n,model:r,resume:i,parentContext:a,onProgress:o,signal:s}=e;qR.info(`Starting subagent (type={subagentType}, model={model})`,{subagentType:n,model:r??`default`});let c=RR(n);if(!c)return qR.error(`Unknown subagent type: {subagentType}`,{subagentType:n}),{success:!1,output:``,toolsExecuted:[],toolCalls:[],numTurns:0,error:`Unknown subagent type: ${n}`};let l=NV(),u=hxe(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?.()??xd.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===xd.Yolo&&i.name!==`ask_user_question`;if(g&&!f&&d.needsPermission()){let c=l.get(i.name)?.displayName??i.name,f=VV(i),p=a.rulesEngine.evaluate(c,f);if(p===`deny`){r.push({id:i.id,content:JSON.stringify({reason:bR.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=gxe(i,d,l,a.workspacePath,a.rulesEngine);if(a.permissionProvider.needsPermission(c)){n?.({type:`status_changed`,status:Sd.WaitingForToolPermission}),a.emitEvent?.({type:`status_changed`,status:Sd.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:bR.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:Sd.ExecutingTool}),a.emitEvent?.({type:`status_changed`,status:Sd.ExecutingTool}),l===`reject`){r.push({id:i.id,content:JSON.stringify({reason:bR.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:bR.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`?xd.Yolo:l===`allowAlways`?xd.AcceptEdits:xd.Normal;a.setAgentMode?.(e),u.agentMode=e,n?.({type:`mode_changed`,mode:e})}else if(l===`allowAlways`){let e=Dd(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:bR.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?.(xd.PlanMode),u.agentMode=xd.PlanMode,n?.({type:`mode_changed`,mode:xd.PlanMode})),i.name===`exit_plan_mode`&&f&&(a.setAgentMode?.(xd.Normal),u.agentMode=xd.Normal,n?.({type:`mode_changed`,mode:xd.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:bR.INTERRUPTED}),rejected:!0});return r}};try{o?.({type:`status`,content:`Starting ${n} agent...`});let e=KR(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`status_changed`:case`notification`:break}r=await e.next()}let i=r.value;return qR.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 Dl(e instanceof Error?e:Error(t),{context:`subagent-runner`}),qR.error(`Subagent failed (type={subagentType}): {error}`,{subagentType:n,error:t}),{success:!1,output:p.join(``),toolsExecuted:m,toolCalls:h,numTurns:0,error:t}}}const JR=dt([`codellm`,`agent`,`tools`,`task`]);var YR=class e extends wR{name=`task`;displayName=`Task`;description=`Launch a new agent to handle complex, multi-step tasks autonomously.
1871
+ 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 OL(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.external?.defs??{};for(let t of e.seen.entries()){let e=t[1];e.def&&e.defId&&(a[e.defId]=e.def)}e.external||Object.keys(a).length>0&&(e.target===`draft-2020-12`?i.$defs=a:i.definitions=a);try{let n=JSON.parse(JSON.stringify(i));return Object.defineProperty(n,`~standard`,{value:{...t[`~standard`],jsonSchema:{input:AL(t,`input`,e.processors),output:AL(t,`output`,e.processors)}},enumerable:!1,writable:!1}),n}catch{throw Error(`Error converting schema to JSON.`)}}function kL(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 kL(r.element,n);if(r.type===`set`)return kL(r.valueType,n);if(r.type===`lazy`)return kL(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 kL(r.innerType,n);if(r.type===`intersection`)return kL(r.left,n)||kL(r.right,n);if(r.type===`record`||r.type===`map`)return kL(r.keyType,n)||kL(r.valueType,n);if(r.type===`pipe`)return kL(r.in,n)||kL(r.out,n);if(r.type===`object`){for(let e in r.shape)if(kL(r.shape[e],n))return!0;return!1}if(r.type===`union`){for(let e of r.options)if(kL(e,n))return!0;return!1}if(r.type===`tuple`){for(let e of r.items)if(kL(e,n))return!0;return!!(r.rest&&kL(r.rest,n))}return!1}const nye=(e,t={})=>n=>{let r=TL({...n,processors:t});return EL(e,r),DL(r,e),OL(r,e)},AL=(e,t,n={})=>r=>{let{libraryOptions:i,target:a}=r??{},o=TL({...i??{},target:a,io:t,processors:n});return EL(e,o),DL(o,e),OL(o,e)},rye={guid:`uuid`,url:`uri`,datetime:`date-time`,json_string:`json-string`,regex:``},iye=(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=rye[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}))])}},aye=(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`,typeof u==`number`&&(t.target===`draft-04`||t.target===`openapi-3.0`?(i.minimum=u,i.exclusiveMinimum=!0):i.exclusiveMinimum=u),typeof a==`number`&&(i.minimum=a,typeof u==`number`&&t.target!==`draft-04`&&(u>=a?delete i.minimum:delete i.exclusiveMinimum)),typeof l==`number`&&(t.target===`draft-04`||t.target===`openapi-3.0`?(i.maximum=l,i.exclusiveMaximum=!0):i.exclusiveMaximum=l),typeof o==`number`&&(i.maximum=o,typeof l==`number`&&t.target!==`draft-04`&&(l<=o?delete i.maximum:delete i.exclusiveMaximum)),typeof c==`number`&&(i.multipleOf=c)},oye=(e,t,n,r)=>{n.type=`boolean`},sye=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`BigInt cannot be represented in JSON Schema`)},cye=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Symbols cannot be represented in JSON Schema`)},lye=(e,t,n,r)=>{t.target===`openapi-3.0`?(n.type=`string`,n.nullable=!0,n.enum=[null]):n.type=`null`},uye=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Undefined cannot be represented in JSON Schema`)},dye=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Void cannot be represented in JSON Schema`)},fye=(e,t,n,r)=>{n.not={}},pye=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Date cannot be represented in JSON Schema`)},mye=(e,t,n,r)=>{let i=e._zod.def,a=VF(i.entries);a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),n.enum=a},hye=(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},gye=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`NaN cannot be represented in JSON Schema`)},_ye=(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},vye=(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)},yye=(e,t,n,r)=>{n.type=`boolean`},bye=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Custom types cannot be represented in JSON Schema`)},xye=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Function types cannot be represented in JSON Schema`)},Sye=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Transforms cannot be represented in JSON Schema`)},Cye=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Map cannot be represented in JSON Schema`)},wye=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Set cannot be represented in JSON Schema`)},Tye=(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=EL(a.element,t,{...r,path:[...r.path,`items`]})},Eye=(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]=EL(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=EL(a.catchall,t,{...r,path:[...r.path,`additionalProperties`]})):t.io===`output`&&(i.additionalProperties=!1)},jL=(e,t,n,r)=>{let i=e._zod.def,a=i.inclusive===!1,o=i.options.map((e,n)=>EL(e,t,{...r,path:[...r.path,a?`oneOf`:`anyOf`,n]}));a?n.oneOf=o:n.anyOf=o},Dye=(e,t,n,r)=>{let i=e._zod.def,a=EL(i.left,t,{...r,path:[...r.path,`allOf`,0]}),o=EL(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]]},Oye=(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)=>EL(e,t,{...r,path:[...r.path,o,n]})),l=a.rest?EL(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)},kye=(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=EL(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=EL(a.keyType,t,{...r,path:[...r.path,`propertyNames`]})),i.additionalProperties=EL(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)}},Aye=(e,t,n,r)=>{let i=e._zod.def,a=EL(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`}]},jye=(e,t,n,r)=>{let i=e._zod.def;EL(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},Mye=(e,t,n,r)=>{let i=e._zod.def;EL(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.default=JSON.parse(JSON.stringify(i.defaultValue))},Nye=(e,t,n,r)=>{let i=e._zod.def;EL(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)))},Pye=(e,t,n,r)=>{let i=e._zod.def;EL(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},Fye=(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;EL(a,t,r);let o=t.seen.get(e);o.ref=a},Iye=(e,t,n,r)=>{let i=e._zod.def;EL(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.readOnly=!0},Lye=(e,t,n,r)=>{let i=e._zod.def;EL(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},ML=(e,t,n,r)=>{let i=e._zod.def;EL(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},Rye=(e,t,n,r)=>{let i=e._zod.innerType;EL(i,t,r);let a=t.seen.get(e);a.ref=i},zye=IF(`ZodISODateTime`,(e,t)=>{t_e.init(e,t),zL.init(e,t)});function NL(e){return Dve(zye,e)}const Bye=IF(`ZodISODate`,(e,t)=>{n_e.init(e,t),zL.init(e,t)});function Vye(e){return Ove(Bye,e)}const Hye=IF(`ZodISOTime`,(e,t)=>{r_e.init(e,t),zL.init(e,t)});function Uye(e){return kve(Hye,e)}const Wye=IF(`ZodISODuration`,(e,t)=>{i_e.init(e,t),zL.init(e,t)});function Gye(e){return Ave(Wye,e)}const PL=(e,t)=>{pI.init(e,t),e.name=`ZodError`,Object.defineProperties(e,{format:{value:t=>Vhe(e,t)},flatten:{value:t=>Bhe(e,t)},addIssue:{value:t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,HF,2)}},addIssues:{value:t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,HF,2)}},isEmpty:{get(){return e.issues.length===0}}})};IF(`ZodError`,PL);const FL=IF(`ZodError`,PL,{Parent:Error}),Kye=hI(FL),qye=_I(FL),Jye=yI(FL),Yye=xI(FL),Xye=Uhe(FL),Zye=Whe(FL),Qye=Ghe(FL),$ye=Khe(FL),ebe=qhe(FL),tbe=Jhe(FL),nbe=Yhe(FL),rbe=Xhe(FL),IL=IF(`ZodType`,(e,t)=>(FI.init(e,t),Object.assign(e[`~standard`],{jsonSchema:{input:AL(e,`input`),output:AL(e,`output`)}}),e.toJSONSchema=nye(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,`_def`,{value:t}),e.check=(...n)=>e.clone(YF(t,{checks:[...t.checks??[],...n.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]}),{parent:!0}),e.with=e.check,e.clone=(t,n)=>rI(e,t,n),e.brand=()=>e,e.register=((t,n)=>(t.add(e,n),e)),e.parse=(t,n)=>Kye(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>Jye(e,t,n),e.parseAsync=async(t,n)=>qye(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>Yye(e,t,n),e.spa=e.safeParseAsync,e.encode=(t,n)=>Xye(e,t,n),e.decode=(t,n)=>Zye(e,t,n),e.encodeAsync=async(t,n)=>Qye(e,t,n),e.decodeAsync=async(t,n)=>$ye(e,t,n),e.safeEncode=(t,n)=>ebe(e,t,n),e.safeDecode=(t,n)=>tbe(e,t,n),e.safeEncodeAsync=async(t,n)=>nbe(e,t,n),e.safeDecodeAsync=async(t,n)=>rbe(e,t,n),e.refine=(t,n)=>e.check(Ybe(t,n)),e.superRefine=t=>e.check(Xbe(t)),e.overwrite=t=>e.check(wL(t)),e.optional=()=>dR(e),e.exactOptional=()=>Lbe(e),e.nullable=()=>fR(e),e.nullish=()=>dR(fR(e)),e.nonoptional=t=>Ube(e,t),e.array=()=>XL(e),e.or=t=>tR([e,t]),e.and=t=>rR(e,t),e.transform=t=>hR(e,lR(t)),e.default=t=>Bbe(e,t),e.prefault=t=>Hbe(e,t),e.catch=t=>Gbe(e,t),e.pipe=t=>hR(e,t),e.readonly=()=>qbe(e),e.describe=t=>{let n=e.clone();return uL.add(n,{description:t}),n},Object.defineProperty(e,`description`,{get(){return uL.get(e)?.description},configurable:!0}),e.meta=(...t)=>{if(t.length===0)return uL.get(e);let n=e.clone();return uL.add(n,t[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e.apply=t=>t(e),e)),LL=IF(`_ZodString`,(e,t)=>{II.init(e,t),IL.init(e,t),e._zod.processJSONSchema=(t,n,r)=>iye(e,t,n,r);let n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,e.regex=(...t)=>e.check(zve(...t)),e.includes=(...t)=>e.check(Hve(...t)),e.startsWith=(...t)=>e.check(Uve(...t)),e.endsWith=(...t)=>e.check(Wve(...t)),e.min=(...t)=>e.check(SL(...t)),e.max=(...t)=>e.check(xL(...t)),e.length=(...t)=>e.check(CL(...t)),e.nonempty=(...t)=>e.check(SL(1,...t)),e.lowercase=t=>e.check(Bve(t)),e.uppercase=t=>e.check(Vve(t)),e.trim=()=>e.check(qve()),e.normalize=(...t)=>e.check(Kve(...t)),e.toLowerCase=()=>e.check(Jve()),e.toUpperCase=()=>e.check(Yve()),e.slugify=()=>e.check(Xve())}),RL=IF(`ZodString`,(e,t)=>{II.init(e,t),LL.init(e,t),e.email=t=>e.check(sve(ibe,t)),e.url=t=>e.check(fL(HL,t)),e.jwt=t=>e.check(Eve(bbe,t)),e.emoji=t=>e.check(fve(obe,t)),e.guid=t=>e.check(dL(BL,t)),e.uuid=t=>e.check(cve(VL,t)),e.uuidv4=t=>e.check(lve(VL,t)),e.uuidv6=t=>e.check(uve(VL,t)),e.uuidv7=t=>e.check(dve(VL,t)),e.nanoid=t=>e.check(pve(sbe,t)),e.guid=t=>e.check(dL(BL,t)),e.cuid=t=>e.check(mve(cbe,t)),e.cuid2=t=>e.check(hve(lbe,t)),e.ulid=t=>e.check(gve(ube,t)),e.base64=t=>e.check(Cve(_be,t)),e.base64url=t=>e.check(wve(vbe,t)),e.xid=t=>e.check(_ve(dbe,t)),e.ksuid=t=>e.check(vve(fbe,t)),e.ipv4=t=>e.check(yve(pbe,t)),e.ipv6=t=>e.check(bve(mbe,t)),e.cidrv4=t=>e.check(xve(hbe,t)),e.cidrv6=t=>e.check(Sve(gbe,t)),e.e164=t=>e.check(Tve(ybe,t)),e.datetime=t=>e.check(NL(t)),e.date=t=>e.check(Vye(t)),e.time=t=>e.check(Uye(t)),e.duration=t=>e.check(Gye(t))});function Y(e){return ave(RL,e)}const zL=IF(`ZodStringFormat`,(e,t)=>{LI.init(e,t),LL.init(e,t)}),ibe=IF(`ZodEmail`,(e,t)=>{Kge.init(e,t),zL.init(e,t)}),BL=IF(`ZodGUID`,(e,t)=>{Wge.init(e,t),zL.init(e,t)}),VL=IF(`ZodUUID`,(e,t)=>{Gge.init(e,t),zL.init(e,t)}),HL=IF(`ZodURL`,(e,t)=>{qge.init(e,t),zL.init(e,t)});function abe(e){return fL(HL,e)}const obe=IF(`ZodEmoji`,(e,t)=>{Jge.init(e,t),zL.init(e,t)}),sbe=IF(`ZodNanoID`,(e,t)=>{Yge.init(e,t),zL.init(e,t)}),cbe=IF(`ZodCUID`,(e,t)=>{Xge.init(e,t),zL.init(e,t)}),lbe=IF(`ZodCUID2`,(e,t)=>{Zge.init(e,t),zL.init(e,t)}),ube=IF(`ZodULID`,(e,t)=>{Qge.init(e,t),zL.init(e,t)}),dbe=IF(`ZodXID`,(e,t)=>{$ge.init(e,t),zL.init(e,t)}),fbe=IF(`ZodKSUID`,(e,t)=>{e_e.init(e,t),zL.init(e,t)}),pbe=IF(`ZodIPv4`,(e,t)=>{a_e.init(e,t),zL.init(e,t)});IF(`ZodMAC`,(e,t)=>{s_e.init(e,t),zL.init(e,t)});const mbe=IF(`ZodIPv6`,(e,t)=>{o_e.init(e,t),zL.init(e,t)}),hbe=IF(`ZodCIDRv4`,(e,t)=>{c_e.init(e,t),zL.init(e,t)}),gbe=IF(`ZodCIDRv6`,(e,t)=>{l_e.init(e,t),zL.init(e,t)}),_be=IF(`ZodBase64`,(e,t)=>{u_e.init(e,t),zL.init(e,t)}),vbe=IF(`ZodBase64URL`,(e,t)=>{f_e.init(e,t),zL.init(e,t)}),ybe=IF(`ZodE164`,(e,t)=>{p_e.init(e,t),zL.init(e,t)}),bbe=IF(`ZodJWT`,(e,t)=>{h_e.init(e,t),zL.init(e,t)});IF(`ZodCustomStringFormat`,(e,t)=>{g_e.init(e,t),zL.init(e,t)});const UL=IF(`ZodNumber`,(e,t)=>{zI.init(e,t),IL.init(e,t),e._zod.processJSONSchema=(t,n,r)=>aye(e,t,n,r),e.gt=(t,n)=>e.check(hL(t,n)),e.gte=(t,n)=>e.check(gL(t,n)),e.min=(t,n)=>e.check(gL(t,n)),e.lt=(t,n)=>e.check(pL(t,n)),e.lte=(t,n)=>e.check(mL(t,n)),e.max=(t,n)=>e.check(mL(t,n)),e.int=t=>e.check(GL(t)),e.safe=t=>e.check(GL(t)),e.positive=t=>e.check(hL(0,t)),e.nonnegative=t=>e.check(gL(0,t)),e.negative=t=>e.check(pL(0,t)),e.nonpositive=t=>e.check(mL(0,t)),e.multipleOf=(t,n)=>e.check(_L(t,n)),e.step=(t,n)=>e.check(_L(t,n)),e.finite=()=>e;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 WL(e){return jve(UL,e)}const xbe=IF(`ZodNumberFormat`,(e,t)=>{__e.init(e,t),UL.init(e,t)});function GL(e){return Nve(xbe,e)}const Sbe=IF(`ZodBoolean`,(e,t)=>{v_e.init(e,t),IL.init(e,t),e._zod.processJSONSchema=(t,n,r)=>oye(e,t,n,r)});function KL(e){return Pve(Sbe,e)}const Cbe=IF(`ZodBigInt`,(e,t)=>{BI.init(e,t),IL.init(e,t),e._zod.processJSONSchema=(t,n,r)=>sye(e,t,n,r),e.gte=(t,n)=>e.check(gL(t,n)),e.min=(t,n)=>e.check(gL(t,n)),e.gt=(t,n)=>e.check(hL(t,n)),e.gte=(t,n)=>e.check(gL(t,n)),e.min=(t,n)=>e.check(gL(t,n)),e.lt=(t,n)=>e.check(pL(t,n)),e.lte=(t,n)=>e.check(mL(t,n)),e.max=(t,n)=>e.check(mL(t,n)),e.positive=t=>e.check(hL(BigInt(0),t)),e.negative=t=>e.check(pL(BigInt(0),t)),e.nonpositive=t=>e.check(mL(BigInt(0),t)),e.nonnegative=t=>e.check(gL(BigInt(0),t)),e.multipleOf=(t,n)=>e.check(_L(t,n));let n=e._zod.bag;e.minValue=n.minimum??null,e.maxValue=n.maximum??null,e.format=n.format??null});IF(`ZodBigIntFormat`,(e,t)=>{y_e.init(e,t),Cbe.init(e,t)}),IF(`ZodSymbol`,(e,t)=>{b_e.init(e,t),IL.init(e,t),e._zod.processJSONSchema=(t,n,r)=>cye(e,t,n,r)}),IF(`ZodUndefined`,(e,t)=>{x_e.init(e,t),IL.init(e,t),e._zod.processJSONSchema=(t,n,r)=>uye(e,t,n,r)});const wbe=IF(`ZodNull`,(e,t)=>{S_e.init(e,t),IL.init(e,t),e._zod.processJSONSchema=(t,n,r)=>lye(e,t,n,r)});function qL(e){return Fve(wbe,e)}const Tbe=IF(`ZodAny`,(e,t)=>{C_e.init(e,t),IL.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function JL(){return Ive(Tbe)}const Ebe=IF(`ZodUnknown`,(e,t)=>{w_e.init(e,t),IL.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function YL(){return Lve(Ebe)}const Dbe=IF(`ZodNever`,(e,t)=>{T_e.init(e,t),IL.init(e,t),e._zod.processJSONSchema=(t,n,r)=>fye(e,t,n,r)});function Obe(e){return Rve(Dbe,e)}IF(`ZodVoid`,(e,t)=>{E_e.init(e,t),IL.init(e,t),e._zod.processJSONSchema=(t,n,r)=>dye(e,t,n,r)}),IF(`ZodDate`,(e,t)=>{D_e.init(e,t),IL.init(e,t),e._zod.processJSONSchema=(t,n,r)=>pye(e,t,n,r),e.min=(t,n)=>e.check(gL(t,n)),e.max=(t,n)=>e.check(mL(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 kbe=IF(`ZodArray`,(e,t)=>{O_e.init(e,t),IL.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Tye(e,t,n,r),e.element=t.element,e.min=(t,n)=>e.check(SL(t,n)),e.nonempty=t=>e.check(SL(1,t)),e.max=(t,n)=>e.check(xL(t,n)),e.length=(t,n)=>e.check(CL(t,n)),e.unwrap=()=>e.element});function XL(e,t){return Zve(kbe,e,t)}const ZL=IF(`ZodObject`,(e,t)=>{A_e.init(e,t),IL.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Eye(e,t,n,r),qF(e,`shape`,()=>t.shape),e.keyof=()=>sR(Object.keys(e._zod.def.shape)),e.catchall=t=>e.clone({...e._zod.def,catchall:t}),e.passthrough=()=>e.clone({...e._zod.def,catchall:YL()}),e.loose=()=>e.clone({...e._zod.def,catchall:YL()}),e.strict=()=>e.clone({...e._zod.def,catchall:Obe()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=t=>Fhe(e,t),e.safeExtend=t=>Ihe(e,t),e.merge=t=>Lhe(e,t),e.pick=t=>Nhe(e,t),e.omit=t=>Phe(e,t),e.partial=(...t)=>Rhe(uR,e,t[0]),e.required=(...t)=>zhe(pR,e,t[0])});function QL(e,t){return new ZL({type:`object`,shape:e??{},...iI(t)})}function $L(e,t){return new ZL({type:`object`,shape:e,catchall:YL(),...iI(t)})}const eR=IF(`ZodUnion`,(e,t)=>{KI.init(e,t),IL.init(e,t),e._zod.processJSONSchema=(t,n,r)=>jL(e,t,n,r),e.options=t.options});function tR(e,t){return new eR({type:`union`,options:e,...iI(t)})}IF(`ZodXor`,(e,t)=>{eR.init(e,t),j_e.init(e,t),e._zod.processJSONSchema=(t,n,r)=>jL(e,t,n,r),e.options=t.options});const Abe=IF(`ZodDiscriminatedUnion`,(e,t)=>{eR.init(e,t),M_e.init(e,t)});function nR(e,t,n){return new Abe({type:`union`,options:t,discriminator:e,...iI(n)})}const jbe=IF(`ZodIntersection`,(e,t)=>{N_e.init(e,t),IL.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Dye(e,t,n,r)});function rR(e,t){return new jbe({type:`intersection`,left:e,right:t})}const Mbe=IF(`ZodTuple`,(e,t)=>{XI.init(e,t),IL.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Oye(e,t,n,r),e.rest=t=>e.clone({...e._zod.def,rest:t})});function iR(e,t,n){let r=t instanceof FI;return new Mbe({type:`tuple`,items:e,rest:r?t:null,...iI(r?n:t)})}const Nbe=IF(`ZodRecord`,(e,t)=>{P_e.init(e,t),IL.init(e,t),e._zod.processJSONSchema=(t,n,r)=>kye(e,t,n,r),e.keyType=t.keyType,e.valueType=t.valueType});function aR(e,t,n){return new Nbe({type:`record`,keyType:e,valueType:t,...iI(n)})}IF(`ZodMap`,(e,t)=>{F_e.init(e,t),IL.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Cye(e,t,n,r),e.keyType=t.keyType,e.valueType=t.valueType,e.min=(...t)=>e.check(yL(...t)),e.nonempty=t=>e.check(yL(1,t)),e.max=(...t)=>e.check(vL(...t)),e.size=(...t)=>e.check(bL(...t))}),IF(`ZodSet`,(e,t)=>{I_e.init(e,t),IL.init(e,t),e._zod.processJSONSchema=(t,n,r)=>wye(e,t,n,r),e.min=(...t)=>e.check(yL(...t)),e.nonempty=t=>e.check(yL(1,t)),e.max=(...t)=>e.check(vL(...t)),e.size=(...t)=>e.check(bL(...t))});const oR=IF(`ZodEnum`,(e,t)=>{L_e.init(e,t),IL.init(e,t),e._zod.processJSONSchema=(t,n,r)=>mye(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 oR({...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 oR({...t,checks:[],...iI(r),entries:i})}});function sR(e,t){return new oR({type:`enum`,entries:Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e,...iI(t)})}const Pbe=IF(`ZodLiteral`,(e,t)=>{R_e.init(e,t),IL.init(e,t),e._zod.processJSONSchema=(t,n,r)=>hye(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 cR(e,t){return new Pbe({type:`literal`,values:Array.isArray(e)?e:[e],...iI(t)})}IF(`ZodFile`,(e,t)=>{z_e.init(e,t),IL.init(e,t),e._zod.processJSONSchema=(t,n,r)=>vye(e,t,n,r),e.min=(t,n)=>e.check(yL(t,n)),e.max=(t,n)=>e.check(vL(t,n)),e.mime=(t,n)=>e.check(Gve(Array.isArray(t)?t:[t],n))});const Fbe=IF(`ZodTransform`,(e,t)=>{B_e.init(e,t),IL.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Sye(e,t,n,r),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new RF(e.constructor.name);n.addIssue=r=>{if(typeof r==`string`)n.issues.push(dI(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(dI(t))}};let i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n)):(n.value=i,n)}});function lR(e){return new Fbe({type:`transform`,transform:e})}const uR=IF(`ZodOptional`,(e,t)=>{tL.init(e,t),IL.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ML(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function dR(e){return new uR({type:`optional`,innerType:e})}const Ibe=IF(`ZodExactOptional`,(e,t)=>{V_e.init(e,t),IL.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ML(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Lbe(e){return new Ibe({type:`optional`,innerType:e})}const Rbe=IF(`ZodNullable`,(e,t)=>{H_e.init(e,t),IL.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Aye(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function fR(e){return new Rbe({type:`nullable`,innerType:e})}const zbe=IF(`ZodDefault`,(e,t)=>{U_e.init(e,t),IL.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Mye(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Bbe(e,t){return new zbe({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():eI(t)}})}const Vbe=IF(`ZodPrefault`,(e,t)=>{W_e.init(e,t),IL.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Nye(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Hbe(e,t){return new Vbe({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():eI(t)}})}const pR=IF(`ZodNonOptional`,(e,t)=>{G_e.init(e,t),IL.init(e,t),e._zod.processJSONSchema=(t,n,r)=>jye(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Ube(e,t){return new pR({type:`nonoptional`,innerType:e,...iI(t)})}IF(`ZodSuccess`,(e,t)=>{K_e.init(e,t),IL.init(e,t),e._zod.processJSONSchema=(t,n,r)=>yye(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});const Wbe=IF(`ZodCatch`,(e,t)=>{q_e.init(e,t),IL.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Pye(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Gbe(e,t){return new Wbe({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:()=>t})}IF(`ZodNaN`,(e,t)=>{J_e.init(e,t),IL.init(e,t),e._zod.processJSONSchema=(t,n,r)=>gye(e,t,n,r)});const mR=IF(`ZodPipe`,(e,t)=>{Y_e.init(e,t),IL.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Fye(e,t,n,r),e.in=t.in,e.out=t.out});function hR(e,t){return new mR({type:`pipe`,in:e,out:t})}IF(`ZodCodec`,(e,t)=>{mR.init(e,t),X_e.init(e,t)});const Kbe=IF(`ZodReadonly`,(e,t)=>{Z_e.init(e,t),IL.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Iye(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function qbe(e){return new Kbe({type:`readonly`,innerType:e})}IF(`ZodTemplateLiteral`,(e,t)=>{Q_e.init(e,t),IL.init(e,t),e._zod.processJSONSchema=(t,n,r)=>_ye(e,t,n,r)}),IF(`ZodLazy`,(e,t)=>{tve.init(e,t),IL.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Rye(e,t,n,r),e.unwrap=()=>e._zod.def.getter()}),IF(`ZodPromise`,(e,t)=>{eve.init(e,t),IL.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Lye(e,t,n,r),e.unwrap=()=>e._zod.def.innerType}),IF(`ZodFunction`,(e,t)=>{$_e.init(e,t),IL.init(e,t),e._zod.processJSONSchema=(t,n,r)=>xye(e,t,n,r)});const gR=IF(`ZodCustom`,(e,t)=>{nve.init(e,t),IL.init(e,t),e._zod.processJSONSchema=(t,n,r)=>bye(e,t,n,r)});function Jbe(e,t){return Qve(gR,e??(()=>!0),t)}function Ybe(e,t={}){return $ve(gR,e,t)}function Xbe(e){return eye(e)}function _R(e,t){return hR(lR(e),t)}const Zbe={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 Qbe;(function(e){})(Qbe||={});function vR(e){return ove(RL,e)}function yR(e){return Mve(UL,e)}const bR={USER_MESSAGE:`user_message`,REJECTED:`rejected`,INTERRUPTED:`interrupted`},$be={REJECTED:`rejected`};function xR(e){if(e===`Tool was rejected by user`)return{rejected:!0};try{let t=JSON.parse(e);if(t.reason===bR.USER_MESSAGE)return{rejected:!0,userNote:t.message};if(t.reason===bR.REJECTED||t.reason===bR.INTERRUPTED)return{rejected:!0};if(t.status===$be.REJECTED)return{rejected:!0,userNote:t.userNote}}catch{}return{rejected:!1}}const SR=`sibling_tool_failed`,CR=JSON.stringify({type:SR,message:`Not executed: a tool call in a preceding parallel batch failed`});function exe(e){try{return JSON.parse(e)?.type===SR}catch{return!1}}var wR=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}format(e,t){return typeof e==`string`?e:JSON.stringify(e)}formatForLLM(e,t){return this.format(e,t)}parse(e){let t=xR(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 txe=Symbol.for(`server-executed`);var TR=class extends wR{isReadonly=!0;async execute(e,t,n){return txe}format(e,t){return JSON.stringify({type:this.name,status:`server-executed`})}};dt([`codellm`,`agent`,`tools`,`subagent`]);var ER=class e extends TR{name=`subagent`;displayName=`Subagent`;description=`Switch to a different subagent for a task`;static parametersSchema=QL({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}format(e,t){return JSON.stringify({type:`subagent`,status:`success`,agent:t.agent,task:t.task})}parse(e){let t=xR(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`}}};dt([`codellm`,`agent`,`tools`,`todo-write`]);var DR=class e extends TR{name=`todo_write`;displayName=`TodoWrite`;description=`Create and manage a structured task list`;static parametersSchema=QL({todos:_R(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:[]},XL(QL({content:Y().describe(`The task content`),status:sR([`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=xR(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 OR(e){if(typeof e!=`string`)return e;let t=e.trim();return t?Number(t):NaN}function kR(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 nxe=_R(OR,WL()),AR=_R(OR,WL().optional()),jR=_R(kR,KL()),MR=_R(kR,KL().optional()),rxe=dt([`codellm`,`agent`,`tools`,`ask-user`]);var NR=class e extends wR{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=QL({questions:XL(QL({question:Y().describe(`The question to ask the user`),header:Y().describe(`A header/title for the question`),options:XL(QL({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:jR.describe(`Whether the user can select multiple options`)})).describe(`Array of questions to ask the user`),answers:aR(Y(),Y()).optional().describe(`User-provided answers to the questions`)});parameters=e.parametersSchema;needsPermission(){return!0}async execute(e){return rxe.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=xR(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 ixe=dt([`codellm`,`agent`,`tools`,`plan-mode`]);var PR=class e extends wR{name=`enter_plan_mode`;displayName=`EnterPlanMode`;description=`Enter plan mode to create a plan before implementing changes`;static parametersSchema=QL({});parameters=e.parametersSchema;isReadonly=!0;needsPermission(e,t,n){return!1}async execute(e,t){return ixe.info`Entering plan mode`,{success:!0}}format(e,t){return`Entered plan mode`}parse(e){let t=xR(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 axe=dt([`codellm`,`agent`,`tools`,`plan-mode`]);var FR=class e extends wR{name=`exit_plan_mode`;displayName=`ExitPlanMode`;description=`Exit plan mode and return to normal agent operation`;static parametersSchema=QL({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 axe.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=xR(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`}}},IR;(function(e){e.GeneralPurpose=`GENERAL_PURPOSE`,e.Explore=`EXPLORE`,e.Plan=`PLAN`})(IR||={});const oxe={[IR.GeneralPurpose]:{name:IR.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`},[IR.Explore]:{name:IR.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`},[IR.Plan]:{name:IR.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`}},sxe=new Set(Object.values(IR));function cxe(e){return sxe.has(e)}function LR(e){if(cxe(e))return e}function RR(e){return oxe[e]}function zR(){return Object.values(IR)}function BR(e){let t=LR(e);return t?RR(t).displayName:e}function lxe(e,t){let n=LR(e);if(!n)return!1;let r=RR(n);return r.allowedTools.includes(`*`)?!0:r.allowedTools.includes(t)}async function VR(e){return new Promise(t=>setTimeout(t,e))}const HR=dt([`codellm`,`agent`,`loop`]);function UR(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 UR(t.segment)}return null}function uxe(e){return Math.min((e+1)*2e3,1e4)}function WR(e){return 2**(e+1)*1e3}function*dxe(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 wd({...n.pendingCreditLimitSegment??void 0,message:r})}:Bl(r)?yield{__error:new Ll}:yield{__error:new Cd(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===`collapsible_component`&&e.isThoughts===!0){let t=e.title||`Thinking`,n=UR(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||UR(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=UR(e.segment);t&&(yield{type:`text_delta`,content:t})}}async function*fxe(e,t){let n=t?.generateRequestId?.()??crypto.randomUUID(),r=!1;HR.debug(`Starting agent loop (conversationId={conversationId}, model={model})`,{conversationId:e.conversationId,model:e.model});for(let t=0;t<8;t++){Al(`turn started`,`agent`);let i=n,a=!1;if(t>0){HR.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{let t=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 n of t){if(e.signal?.aborted)break;for(let e of dxe(n,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},HR.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 Ll){if(c&&t<4&&!e.signal?.aborted){let e=WR(t);HR.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}),Ol(`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 VR(e);continue}throw HR.warn(`Auth expired, aborting loop`),i}if(i instanceof wd)throw HR.warn(`Credit limit reached, aborting loop`),Ol(`Credit limit reached`,`warning`,{context:`agent-loop`}),i;let a=Vl(i),o=a?8:5;if(t<o-1&&!e.signal?.aborted){let e=a?uxe(t):WR(t);HR.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 VR(e);continue}throw HR.error(`All retry attempts exhausted: {error}`,{error:i.message}),Dl(i,{context:`agent-loop-retry-exhausted`}),Vl(i)?i instanceof Rl?i:new Rl(i.message,i):i}}}const GR=dt([`codellm`,`agent`,`runner`]);var pxe=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 mxe(e){return e.toUpperCase().includes(`CLAUDE`)}async function*KR(e,t,n){let r=e.maxTurns??2**53-1,i=t,a,o=0,s=0,c=[],l=e.agentMode;GR.info(`Starting agent conversation (model={model}, maxTurns={maxTurns})`,{model:e.model,maxTurns:r});try{for(;o<r;){if(n?.aborted)return GR.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 pxe,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 fxe(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||GR.warn(`Agent loop exited without turn_complete_with_tools (collected {count} tool calls)`,{count:r.length}),r.length===0){GR.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===bR.REJECTED}catch{return!1}}),D=C.some((e,t)=>{if(!T(e,t))return!1;try{return JSON.parse(e.content).reason===bR.INTERRUPTED}catch{return!1}}),O=C.some(e=>{if(!e.rejected)return!1;try{return JSON.parse(e.content).reason===bR.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(mxe(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){GR.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 GR.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 Dl(t,{context:`agent-runner`}),GR.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 qR=dt([`codellm`,`agent`,`subagent`]);function hxe(e,t){let n=RR(t);return!n||n.allowedTools.includes(`*`)?e:e.filter(e=>lxe(t,e.name))}function gxe(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=cF(n.resolvedPath);return{type:`read_outside_directory`,tool:e,displayName:a,filePath:t,resolvedPath:t,deducedDirectory:O.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=cF(n.resolvedPath??e.input.filePath??``);return{type:`edit_outside_directory`,tool:e,displayName:a,filePath:t,resolvedPath:t,deducedDirectory:O.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=cF(n.resolvedPath??e.input.filePath??``);return{type:`write_outside_directory`,tool:e,displayName:a,filePath:t,resolvedPath:t,deducedDirectory:O.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=cF(n.resolvedPath??e.input.notebookPath??``);return{type:`notebook_edit_outside_directory`,tool:e,displayName:a,filePath:t,resolvedPath:t,deducedDirectory:O.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 _xe(e){let{prompt:t,subagentType:n,model:r,resume:i,parentContext:a,onProgress:o,signal:s}=e;qR.info(`Starting subagent (type={subagentType}, model={model})`,{subagentType:n,model:r??`default`});let c=RR(n);if(!c)return qR.error(`Unknown subagent type: {subagentType}`,{subagentType:n}),{success:!1,output:``,toolsExecuted:[],toolCalls:[],numTurns:0,error:`Unknown subagent type: ${n}`};let l=NV(),u=hxe(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?.()??xd.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===xd.Yolo&&i.name!==`ask_user_question`;if(g&&!f&&d.needsPermission()){let c=l.get(i.name)?.displayName??i.name,f=VV(i),p=a.rulesEngine.evaluate(c,f);if(p===`deny`){r.push({id:i.id,content:JSON.stringify({reason:bR.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=gxe(i,d,l,a.workspacePath,a.rulesEngine);if(a.permissionProvider.needsPermission(c)){n?.({type:`status_changed`,status:Sd.WaitingForToolPermission}),a.emitEvent?.({type:`status_changed`,status:Sd.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:bR.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:Sd.ExecutingTool}),a.emitEvent?.({type:`status_changed`,status:Sd.ExecutingTool}),l===`reject`){r.push({id:i.id,content:JSON.stringify({reason:bR.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:bR.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`?xd.Yolo:l===`allowAlways`?xd.AcceptEdits:xd.Normal;a.setAgentMode?.(e),u.agentMode=e,n?.({type:`mode_changed`,mode:e})}else if(l===`allowAlways`){let e=Dd(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:bR.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?.(xd.PlanMode),u.agentMode=xd.PlanMode,n?.({type:`mode_changed`,mode:xd.PlanMode})),i.name===`exit_plan_mode`&&f&&(a.setAgentMode?.(xd.Normal),u.agentMode=xd.Normal,n?.({type:`mode_changed`,mode:xd.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:bR.INTERRUPTED}),rejected:!0});return r}};try{o?.({type:`status`,content:`Starting ${n} agent...`});let e=KR(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`status_changed`:case`notification`:break}r=await e.next()}let i=r.value;return qR.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 Dl(e instanceof Error?e:Error(t),{context:`subagent-runner`}),qR.error(`Subagent failed (type={subagentType}): {error}`,{subagentType:n,error:t}),{success:!1,output:p.join(``),toolsExecuted:m,toolCalls:h,numTurns:0,error:t}}}const JR=dt([`codellm`,`agent`,`tools`,`task`]);var YR=class e extends wR{name=`task`;displayName=`Task`;description=`Launch a new agent to handle complex, multi-step tasks autonomously.
1872
1872
 
1873
1873
  The Task tool launches specialized agents (subprocesses) that autonomously handle complex tasks. Each agent type has specific capabilities and tools available to it.
1874
1874
 
@@ -74912,7 +74912,7 @@ The script returns JSON with error details:
74912
74912
  `).filter(e=>e&&!e.startsWith(`(Results are truncated`)).filter(e=>e.trim()),r=n.length===0?`No files found`:`${n.length} files`;return{phase:`success`,toolType:`glob`,data:{files:n},summary:r}}};dt([`codellm`,`agent`,`tools`,`web-search`]);const CCe=QL({searchTerm:Y().describe(`Search query for web search`),query:Y().optional().describe(`Alternative query parameter`),explanation:Y().optional().describe(`Explanation of why this search is needed`),allowedDomains:XL(Y()).optional().describe(`Only include results from these domains`),blockedDomains:XL(Y()).optional().describe(`Exclude results from these domains`)});var wV=class extends TR{name=`web_search`;displayName=`WebSearch`;description=`Search on the web`;parameters=CCe;isReadonly=!0;concurrency(e){return!0}format(e,t){return JSON.stringify({type:`web_search`,status:`success`})}parse(e){let t=xR(e);return t.rejected?{phase:`rejected`,toolType:`web_search`,data:{},summary:t.userNote?`Rejected \u00b7 "${t.userNote}"`:`Rejected`,...t.userNote!==void 0&&{userNote:t.userNote}}:{phase:`success`,toolType:`web_search`,data:{},summary:`Found results`}}};dt([`codellm`,`agent`,`tools`,`web-fetch`]);const wCe=QL({url:Y().describe(`The URL to fetch content from`),prompt:Y().describe(`The prompt to run on the fetched content`)});var TV=class extends TR{name=`web_fetch`;displayName=`Fetch`;description=`Fetch content from a URL`;parameters=wCe;isReadonly=!0;concurrency(e){return!0}format(e,t){return JSON.stringify({type:`web_fetch`,status:`success`})}parse(e){let t=xR(e);if(t.rejected)return{phase:`rejected`,toolType:`web_fetch`,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.error?{phase:`error`,toolType:`web_fetch`,data:t,summary:t.error??`Error`,errorMessage:t.error}:{phase:`success`,toolType:`web_fetch`,data:t,summary:`Fetched`}}catch{}let n=(e.length/1024).toFixed(1);return{phase:`success`,toolType:`web_fetch`,data:{content:e},summary:`Fetched ${n} KB`}}};function TCe(e){return e.trim()}const EV=dt([`codellm`,`agent`,`tools`,`bash`]);function DV(e){let t=3e4,n=TCe(e);if(n.length<=t)return n;let r=1;for(let e=0;e<n.length;e++)n[e]===`
74913
74913
  `&&r++;let i=n.substring(0,1e4),a=n.substring(n.length-2e4),o=1;for(let e=0;e<i.length;e++)i[e]===`
74914
74914
  `&&o++;let s=1;for(let e=0;e<a.length;e++)a[e]===`
74915
- `&&s++;return`${i}\n\n... [${r-(o+s)} lines / ${n.length-t} chars truncated] ...\n\n${a}`}var OV=class e extends XR{name=`bash`;displayName=`Bash`;description=`Run a command in a minified terminal. Creates a new terminal by default, unless an id is provided to use an existing terminal.`;static DEFAULT_TIMEOUT_MS=12e4;static MAX_TIMEOUT_MS=6e5;concurrency(e,t){let n=e.command;if(!n)return!1;let r=e.shellId===`new`?void 0:e.shellId;if(e.interactiveMode||r)return!1;try{return PF(n,t).concurrencyKey}catch{return!1}}static getAllowedWritePaths(e){if(e.agentMode===xd.PlanMode)return[e.plansDir??O.join(te(),`.abacusai`,`plans`)]}async prepare(t,n){let{command:r}=t;if(!r)return{analysis:null};try{let t=e.getAllowedWritePaths(n),i=PF(r,n.workspacePath,t?{allowedWritePaths:t}:void 0),a=i.overallMutability===`readonly`,o=i.commands.length>0&&i.commands.every(e=>e.isKnown);return{analysis:i,skipPermission:a&&o&&!i.requiresPermission}}catch{return{analysis:null}}}needsPermission(e,t,n){return n?.analysis?n.analysis.requiresPermission:!0}static Parameters=QL({command:Y().describe(`The command to execute`),explanation:Y().optional().describe(`Explanation of what the command does`),runInBackground:MR.describe(`Whether to run the command in the background`),shellId:vR().optional().describe(`Terminal ID to use (creates new if not provided)`),interactiveMode:MR.describe(`Whether to run in interactive mode`),timeout:yR().optional().describe(`Timeout in milliseconds (default: 120000, max: 600000)`)});parameters=e.Parameters;async execute(t,n,r){let{command:i,runInBackground:a,interactiveMode:o,timeout:s}=t,c=t.shellId===`new`?void 0:t.shellId;EV.debug(`Executing bash command: {cmd}{bg}{interactive}`,{cmd:i.slice(0,200),bg:a?` (background)`:``,interactive:o?` (interactive)`:``});let l=n.terminalService,u=s??e.DEFAULT_TIMEOUT_MS,d=Math.min(u,e.MAX_TIMEOUT_MS),f=n.onOutputUpdate,p=n.abortController?.signal,m=c?parseInt(c):void 0;if(o&&i===`/exit`)return m?(await l.closeTerminal?.(m),{type:`bash`,id:m,command:i,exitCode:0,output:`Terminal closed`,isError:!1,duration:0,runInBackground:!1,interactiveMode:!0,terminated:!0}):{type:`bash`,id:0,command:i,exitCode:1,output:`No terminal ID provided for /exit command`,isError:!0,duration:0,runInBackground:!1,interactiveMode:!0};if(o&&i===`/wait`)if(m){await VR(3e3);let e=l.getOutput(m);return{type:`bash`,id:m,command:i,exitCode:0,output:(e.length>0?e[e.length-1]:null)?.output??`No output available`,isError:!1,duration:3e3,runInBackground:!1,interactiveMode:!0,message:`Terminal state checked - ready for next command`}}else return{type:`bash`,id:0,command:i,exitCode:1,output:`No terminal ID provided for /wait command`,isError:!0,duration:0,runInBackground:!1,interactiveMode:!0};if(o){let e=await l.executeCommand(i,{terminalId:m,alwaysCreateNew:!c,interactiveMode:!0});await VR(3e3);let t=e.result.get(),n=t.output||``;return n=DV(n),{type:`bash`,id:t.id,command:t.command,exitCode:t.exitCode||0,output:n,isError:t.exitCode!==void 0&&t.exitCode!==0,duration:t.duration||0,runInBackground:!1,interactiveMode:!0,message:`Interactive command executed - terminal ready for next command`}}let h=await l.executeCommand(i,{terminalId:m,alwaysCreateNew:!c});if(a){let e=h.result.get();l.markAsBackground?.(e.id);let t=e.output||``;return t=DV(t),{type:`bash`,id:e.id,command:e.command,exitCode:e.exitCode||0,output:t,isError:!1,duration:e.duration||0,runInBackground:!0,message:`Background command started`}}if(h.running){let e=h.result.get().id,t;f&&(t=setInterval(()=>{try{let e=h.result.get();e&&e.output&&f(n.toolCallId,e.output)}catch{}},100));let r=[h.running],i,a=p?new Promise((e,t)=>{p.aborted?t(Error(`interrupted`)):(i=()=>t(Error(`interrupted`)),p.addEventListener(`abort`,i,{once:!0}))}):null;a&&r.push(a);let o=new Promise((e,t)=>{setTimeout(()=>{t(Error(`Terminal command timed out after ${d}ms`))},d)});r.push(o);try{try{await Promise.race(r)}catch(t){if(t instanceof Error&&t.message===`interrupted`){await l.stopCommand(e);let t=h.result.get();return{type:`bash`,id:t.id,command:t.command,exitCode:130,output:(t.output||``)+`
74915
+ `&&s++;return`${i}\n\n... [${r-(o+s)} lines / ${n.length-t} chars truncated] ...\n\n${a}`}var OV=class e extends XR{name=`bash`;displayName=`Bash`;description=`Run a command in a minified terminal. Creates a new terminal by default, unless an id is provided to use an existing terminal.`;static DEFAULT_TIMEOUT_MS=12e4;static MAX_TIMEOUT_MS=6e5;concurrency(e,t){let n=e.command;if(!n)return!1;let r=e.shellId===`new`?void 0:e.shellId;if(e.interactiveMode||r)return!1;try{return PF(n,t).concurrencyKey}catch{return!1}}static getAllowedWritePaths(e){if(e.agentMode===xd.PlanMode)return[e.plansDir??O.join(te(),hn.configDirName,`plans`)]}async prepare(t,n){let{command:r}=t;if(!r)return{analysis:null};try{let t=e.getAllowedWritePaths(n),i=PF(r,n.workspacePath,t?{allowedWritePaths:t}:void 0),a=i.overallMutability===`readonly`,o=i.commands.length>0&&i.commands.every(e=>e.isKnown);return{analysis:i,skipPermission:a&&o&&!i.requiresPermission}}catch{return{analysis:null}}}needsPermission(e,t,n){return n?.analysis?n.analysis.requiresPermission:!0}static Parameters=QL({command:Y().describe(`The command to execute`),explanation:Y().optional().describe(`Explanation of what the command does`),runInBackground:MR.describe(`Whether to run the command in the background`),shellId:vR().optional().describe(`Terminal ID to use (creates new if not provided)`),interactiveMode:MR.describe(`Whether to run in interactive mode`),timeout:yR().optional().describe(`Timeout in milliseconds (default: 120000, max: 600000)`)});parameters=e.Parameters;async execute(t,n,r){let{command:i,runInBackground:a,interactiveMode:o,timeout:s}=t,c=t.shellId===`new`?void 0:t.shellId;EV.debug(`Executing bash command: {cmd}{bg}{interactive}`,{cmd:i.slice(0,200),bg:a?` (background)`:``,interactive:o?` (interactive)`:``});let l=n.terminalService,u=s??e.DEFAULT_TIMEOUT_MS,d=Math.min(u,e.MAX_TIMEOUT_MS),f=n.onOutputUpdate,p=n.abortController?.signal,m=c?parseInt(c):void 0;if(o&&i===`/exit`)return m?(await l.closeTerminal?.(m),{type:`bash`,id:m,command:i,exitCode:0,output:`Terminal closed`,isError:!1,duration:0,runInBackground:!1,interactiveMode:!0,terminated:!0}):{type:`bash`,id:0,command:i,exitCode:1,output:`No terminal ID provided for /exit command`,isError:!0,duration:0,runInBackground:!1,interactiveMode:!0};if(o&&i===`/wait`)if(m){await VR(3e3);let e=l.getOutput(m);return{type:`bash`,id:m,command:i,exitCode:0,output:(e.length>0?e[e.length-1]:null)?.output??`No output available`,isError:!1,duration:3e3,runInBackground:!1,interactiveMode:!0,message:`Terminal state checked - ready for next command`}}else return{type:`bash`,id:0,command:i,exitCode:1,output:`No terminal ID provided for /wait command`,isError:!0,duration:0,runInBackground:!1,interactiveMode:!0};if(o){let e=await l.executeCommand(i,{terminalId:m,alwaysCreateNew:!c,interactiveMode:!0});await VR(3e3);let t=e.result.get(),n=t.output||``;return n=DV(n),{type:`bash`,id:t.id,command:t.command,exitCode:t.exitCode||0,output:n,isError:t.exitCode!==void 0&&t.exitCode!==0,duration:t.duration||0,runInBackground:!1,interactiveMode:!0,message:`Interactive command executed - terminal ready for next command`}}let h=await l.executeCommand(i,{terminalId:m,alwaysCreateNew:!c});if(a){let e=h.result.get();l.markAsBackground?.(e.id);let t=e.output||``;return t=DV(t),{type:`bash`,id:e.id,command:e.command,exitCode:e.exitCode||0,output:t,isError:!1,duration:e.duration||0,runInBackground:!0,message:`Background command started`}}if(h.running){let e=h.result.get().id,t;f&&(t=setInterval(()=>{try{let e=h.result.get();e&&e.output&&f(n.toolCallId,e.output)}catch{}},100));let r=[h.running],i,a=p?new Promise((e,t)=>{p.aborted?t(Error(`interrupted`)):(i=()=>t(Error(`interrupted`)),p.addEventListener(`abort`,i,{once:!0}))}):null;a&&r.push(a);let o=new Promise((e,t)=>{setTimeout(()=>{t(Error(`Terminal command timed out after ${d}ms`))},d)});r.push(o);try{try{await Promise.race(r)}catch(t){if(t instanceof Error&&t.message===`interrupted`){await l.stopCommand(e);let t=h.result.get();return{type:`bash`,id:t.id,command:t.command,exitCode:130,output:(t.output||``)+`
74916
74916
  [Interrupted]`,isError:!0,duration:t.duration||0,runInBackground:!1,terminated:!0}}if(t instanceof Error&&t.message.includes(`timed out`)){let e=h.result.get();return l.markAsBackground?.(e.id),{type:`bash`,id:e.id,command:e.command,exitCode:0,output:`Command running in background with ID: ${e.id}`,isError:!1,duration:e.duration||0,runInBackground:!0,timedOut:!0}}throw t}}finally{t&&clearInterval(t),i&&p&&p.removeEventListener(`abort`,i)}}let g=h.result.get(),_=g.output||``;_=DV(_);let v=g.exitCode||0;return v===0?EV.debug(`Command completed successfully in {duration}ms`,{duration:g.duration||0}):EV.warn(`Command exited with code {exitCode}: {cmd}`,{exitCode:v,cmd:i.slice(0,100)}),{type:`bash`,id:g.id,command:g.command,exitCode:v,output:_,isError:g.exitCode!==void 0&&g.exitCode!==0,duration:g.duration||0,runInBackground:!1}}format(e,t){let n=e;return JSON.stringify({type:`bash`,status:n.isError?`error`:`success`,id:n.id,command:n.command,exitCode:n.exitCode,output:n.output,duration:n.duration,...n.runInBackground&&{runInBackground:!0},...n.terminated&&{terminated:!0},...n.timedOut&&{timedOut:!0},...n.interactiveMode&&{interactiveMode:!0}})}parse(e){let t=xR(e);if(t.rejected)return{phase:`rejected`,toolType:`bash`,data:{},summary:t.userNote?`Rejected \u00b7 "${t.userNote}"`:`Rejected`,...t.userNote!==void 0&&{userNote:t.userNote}};try{let t=JSON.parse(e);if(t.terminated)return{phase:`error`,toolType:`bash`,data:t,summary:`Terminated${t.duration==null?``:` \u00b7 ${(t.duration/1e3).toFixed(1)}s`}`,...t.exitCode!=null&&{exitCode:t.exitCode},...t.duration!=null&&{duration:t.duration}};if(t.timedOut)return{phase:`success`,toolType:`bash`,data:t,summary:`Running in background (id: ${t.id??`?`})`,runInBackground:!0};if(t.runInBackground)return{phase:`success`,toolType:`bash`,data:t,summary:`Started in background (id: ${t.id??`?`})`,runInBackground:!0};let n=t.exitCode??0,r=t.duration==null?``:` \u00b7 ${(t.duration/1e3).toFixed(1)}s`,i=n!==0||t.isError||t.status===`error`;return{phase:i?`error`:`success`,toolType:`bash`,data:t,summary:`exit ${n}${r}`,exitCode:n,...t.duration!=null&&{duration:t.duration},...i&&t.output&&{errorMessage:t.output.slice(-200)}}}catch{}return e.startsWith(`Error:`)?{phase:`error`,toolType:`bash`,data:{},summary:e,errorMessage:e}:{phase:`success`,toolType:`bash`,data:{},summary:`Completed`}}};const ECe=dt([`codellm`,`agent`,`tools`,`bash-output`]);var kV=class e extends pV{name=`bash_output`;displayName=`BashOutput`;description=`Get the output of a terminal command`;concurrency(e){return!0}static Parameters=QL({shellId:vR().describe(`Terminal ID to get output from`),filter:Y().optional().describe(`Optional regular expression to filter the output lines. Only lines matching this regex will be included in the result.`)});parameters=e.Parameters;needsPermission(){return!1}_applyFilter(e,t){let n=new RegExp(t);return e.map(e=>({...e,output:(e.output??``).split(`
74917
74917
  `).filter(e=>n.test(e)).join(`
74918
74918
  `)}))}async execute(e,t){let{shellId:n,filter:r}=e;if(ECe.debug`Getting output for shell ${n}${r?` with filter: ${r}`:``}`,!n)throw Error(`shellId parameter is required for bash_output`);let i=t.terminalService,a=parseInt(n),o=i.getLiveOutput?.(a);if(o){let e=[o];return r&&(e=this._applyFilter(e,r)),{type:`bash_output`,terminalId:n,outputs:e,totalOutputs:1}}let s=i.getOutput(a);return r&&(s=this._applyFilter(s,r)),{type:`bash_output`,terminalId:n,outputs:s,totalOutputs:s.length}}format(e,t){return JSON.stringify({...e,status:`success`})}parse(e){let t=xR(e);if(t.rejected)return{phase:`rejected`,toolType:`bash_output`,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:`bash_output`,data:t,summary:`Retrieved ${t.totalOutputs??t.outputs?.length??0} lines`}}catch{}return e.startsWith(`Error:`)?{phase:`error`,toolType:`bash_output`,data:{},summary:e,errorMessage:e}:{phase:`success`,toolType:`bash_output`,data:{},summary:`Retrieved`}}};const DCe=dt([`codellm`,`agent`,`tools`,`kill-shell`]);var AV=class e extends XR{name=`kill_shell`;displayName=`KillShell`;description=`Kills a running background bash shell by its ID. Use this tool when you need to terminate a long-running shell. Shell IDs can be found using the /tasks command.`;static Parameters=QL({shellId:vR().describe(`The ID of the background shell to kill`)});parameters=e.Parameters;async execute(e,t){let{shellId:n}=e;if(DCe.debug`Killing shell ${n}`,!n)throw Error(`shellId parameter is required for kill_shell`);let r=t.terminalService,i=parseInt(n),a=await r.stopCommand(i);return r.closeTerminal&&await r.closeTerminal(i),{type:`kill_shell`,shellId:n,success:a}}format(e,t){return JSON.stringify({...e,status:e.success?`success`:`failure`})}parse(e){let t=xR(e);if(t.rejected)return{phase:`rejected`,toolType:`kill_shell`,data:{},summary:t.userNote?`Rejected \u00b7 "${t.userNote}"`:`Rejected`,...t.userNote!==void 0&&{userNote:t.userNote}};try{let t=JSON.parse(e);return{phase:t.success?`success`:`error`,toolType:`kill_shell`,data:t,summary:t.success?`Killed shell ${t.shellId}`:`Failed to kill shell ${t.shellId}`}}catch{}return e.startsWith(`Error:`)?{phase:`error`,toolType:`kill_shell`,data:{},summary:e,errorMessage:e}:{phase:`success`,toolType:`kill_shell`,data:{},summary:`Shell killed`}}},OCe=class{tool;context;params;_prepareResult=null;_executionResult=null;constructor(e,t,n){this.tool=e,this.params=t,this.context=n}getTool(){return this.tool}getParams(){return this.params}mergeParams(e){this.params={...this.params,...e}}getContext(){return this.context}getPrepareResult(){return this._prepareResult}getExecutionResult(){return this._executionResult}async prepare(){return this._prepareResult=await this.tool.prepare(this.params,this.context),this._prepareResult}needsPermission(){return this._prepareResult?.skipPermission?!1:this.tool.needsPermission(this.params,this.context,this._prepareResult)}async execute(){return Al(`tool: ${this.tool.name}`,`tools`),this._executionResult=await this.tool.execute(this.params,this.context,this._prepareResult),this._executionResult}formatResult(){if(this._executionResult===null)throw Error(`Cannot format result before execution completes`);return this.tool.format(this._executionResult,this.params)}formatResultForLLM(){if(this._executionResult===null)throw Error(`Cannot format result before execution completes`);return this.tool.formatForLLM(this._executionResult,this.params)}async executeWithPermission(e){if(await this.prepare(),this.needsPermission()){if(!e)throw Error(`Permission check required but no permission callback provided`);if(!await e())throw Error(`Permission denied`)}return await this.execute(),this.formatResult()}},jV=class{tools;context;_disabledTools;constructor(){this.tools=new Map,this._disabledTools=new Set}setDisabledTools(e){this._disabledTools=new Set(e)}isDisabled(e){return this._disabledTools.has(e)}register(e){if(this.tools.has(e.name))throw Error(`Tool '${e.name}' is already registered`);this.tools.set(e.name,e)}registerAll(e){for(let t of e)this.register(t)}get(e){return this.tools.get(e)}has(e){return this.tools.has(e)}getToolNames(){return Array.from(this.tools.keys())}getAllTools(){return Array.from(this.tools.values())}setContext(e){this.context=e}getApiToolDefinitions(e){let t=e??this.context;return Array.from(this.tools.values()).filter(e=>e.includeInApiDefinitions).filter(e=>!this._disabledTools.has(e.name)).filter(e=>!t||e.isEnabled(t)).map(e=>e.getToolDefinition())}getMcpToolDefinitions(){return Array.from(this.tools.values()).filter(e=>!e.includeInApiDefinitions).map(e=>e.getToolDefinition())}getReadonlyToolDefinitions(e){return Array.from(this.tools.values()).filter(e=>e.isReadonly&&e.includeInApiDefinitions).filter(e=>!this._disabledTools.has(e.name)).filter(t=>!e||t.isEnabled(e)).map(e=>e.getToolDefinition())}registerMCPTools(e){let t=Array.from(this.tools.entries()).filter(([e,t])=>!t.includeInApiDefinitions).map(([e,t])=>e);for(let e of t)this.tools.delete(e);this.registerAll(e)}createToolInstance(e,t,n){let r=this.get(e);if(!r)throw Error(`Tool '${e}' is not registered`);return new OCe(r,r.validateParams(t),n)}isBuiltinTool(e){let t=this.get(e);return t?t.includeInApiDefinitions:!1}isBuiltinRequest(e){return this.isBuiltinTool(e.name)}unregister(e){return this.tools.delete(e)}parse(e,t){if(exe(t))return{phase:`sibling_failed`,toolType:e,data:{},summary:`Not executed — a sibling tool call in a preceding parallel batch failed`,errorMessage:`Sibling tool call failed`};let n=this.tools.get(e);return n?n.parse(t):this._genericParse(e,t)}_genericParse(e,t){let n=xR(t);if(n.rejected)return{phase:`rejected`,toolType:e,data:{},summary:n.userNote?`Rejected \u00b7 "${n.userNote}"`:`Rejected`,...n.userNote!==void 0&&{userNote:n.userNote}};try{let n=JSON.parse(t),r=`success`;return n.status===`error`?r=`error`:n.status===`skipped`&&(r=`skipped`),{phase:r,toolType:n.type??e,data:n,summary:n.message??n.summary??`Completed`,...n.errorMessage!==void 0&&{errorMessage:n.errorMessage}}}catch{}return t.startsWith(`Error:`)?{phase:`error`,toolType:e,data:{},summary:t,errorMessage:t}:{phase:`success`,toolType:e,data:{},summary:`Completed`}}clear(){this.tools.clear()}};const MV=new jV;MV.register(new $R),MV.register(new iz),MV.register(new gV),MV.register(new vV),MV.register(new yV),MV.register(new xV),MV.register(new CV),MV.register(new wV),MV.register(new TV),MV.register(new OV),MV.register(new kV),MV.register(new AV),MV.register(new ER),MV.register(new DR),MV.register(new NR),MV.register(new PR),MV.register(new FR),MV.register(new YR);function NV(){let e=new jV;return e.register(new $R),e.register(new iz),e.register(new gV),e.register(new vV),e.register(new yV),e.register(new xV),e.register(new CV),e.register(new wV),e.register(new TV),e.register(new OV),e.register(new kV),e.register(new AV),e.register(new ER),e.register(new DR),e.register(new NR),e.register(new PR),e.register(new FR),e.register(new YR),e}function PV(e){let t=e.indexOf(`(`);if(t===-1)return{displayName:e,pattern:null};let n=e.slice(0,t),r=e.lastIndexOf(`)`);if(r===-1||r<=t)return{displayName:e,pattern:``};let i=e.slice(t+1,r).trim();return i===``||i===`*`?{displayName:n,pattern:null}:{displayName:n,pattern:i}}function FV(e,t,n){return e.displayName===t?e.pattern===null?!0:t===`Bash`?ACe(e.pattern,n):e.pattern.startsWith(`domain:`)||e.pattern.startsWith(`//`)||e.pattern.startsWith(`~/`)||kCe(t)?RCe(e.pattern,n):BV(n,e.pattern):!1}function kCe(e){return[`Edit`,`Read`,`Delete`,`LS`,`Upload`].includes(e)}function ACe(e,t){let n=nF(t),r=n[0]?.trim();return r?n.length>1?n.every(t=>IV(e,t)):BV(r,e):!1}function IV(e,t){let n=t.trim();if(!n)return!1;let r=jCe(e,n);return r===null?BV(n,e):r}function jCe(e,t){let n=LV(e),r=LV(t);if(!n||!r)return null;if(n.command!==r.command)return!1;let i=PCe(n.target);if(!i&&FCe(n.target))return null;let a=RV(r.target);if(i){let e=RV(i);return a&&e?LCe(a,e):BV(r.target,n.target)}let o=RV(n.target);return o&&a?zV(o)===zV(a):BV(r.target,n.target)}function LV(e){let t=e.trim().match(/^(?:builtin\s+)?(cd|pushd)\b\s*(.*)$/i);if(!t)return null;let n=t[1].toLowerCase(),r=t[2]?.trim()??``;if(!r)return{command:n,target:`~`};let i=MCe(r);return!i||i===`-`?null:{command:n,target:i}}function MCe(e){let t=!1,n=!1,r=!1,i=``;for(let a=0;a<e.length;a++){let o=e[a];if(r){i+=o,r=!1;continue}if(!t&&o===`\\`){r=!0,i+=o;continue}if(!n&&o===`'`){t=!t,i+=o;continue}if(!t&&o===`"`){n=!n,i+=o;continue}if(!t&&!n&&/\s/.test(o))break;i+=o}return NCe(i.trim())}function NCe(e){return e&&((e.startsWith(`"`)&&e.endsWith(`"`)||e.startsWith(`'`)&&e.endsWith(`'`))&&(e=e.slice(1,-1)),e.replace(/\\([\\\s"'])/g,`$1`))}function PCe(e){return e===`*`||e===`**`?`.`:e.endsWith(`/**`)?e.slice(0,-3):e.endsWith(`/*`)?e.slice(0,-2):null}function FCe(e){return/[*?\[]/.test(e)}function RV(e){if(!e)return null;let t=oF(e);if(!O.isAbsolute(t))return null;let n=cF(t);return ICe(O.normalize(n))}function ICe(e){let t=O.normalize(e);return t===O.parse(t).root?t:t.replace(/[\\/]+$/g,``)}function zV(e){return process.platform===`win32`?e.toLowerCase():e}function LCe(e,t){if(zV(e)===zV(t))return!0;let n=O.relative(t,e);return!!n&&!n.startsWith(`..`)&&!O.isAbsolute(n)}function BV(e,t){let n=`^`,r=0;for(;r<t.length;){let e=t[r];e===`*`?t[r+1]===`*`?(n+=`.*`,r+=2):(n+=`.*`,r++):e===`?`?(n+=`.`,r++):(n+=e.replace(/[.+^${}()|\\[\]]/g,`\\$&`),r++)}n+=`$`;try{return new RegExp(n).test(e)}catch{return e===t}}function RCe(e,t){let n=e;n=n.replace(/\\/g,`/`);let r=t.replace(/\\/g,`/`);if(n.startsWith(`//`)){let e=n.slice(2);n=/^[A-Za-z]:/.test(e)?e:`/`+e}if(n.startsWith(`~/`)&&(n=oF(n).replace(/\\/g,`/`)),n.startsWith(`domain:`)){let e=n.slice(7);try{let t=new URL(r);return t.hostname===e||t.hostname.endsWith(`.`+e)}catch{return r.includes(e)}}return zCe(r,n)}function zCe(e,t){let n=`^`,r=0;for(;r<t.length;){let e=t[r];if(e===`*`)t[r+1]===`*`?t[r+2]===`/`?(n+=`(?:.*/)?`,r+=3):(n+=`.*`,r+=2):(n+=`[^/]*`,r++);else if(e===`?`)n+=`[^/]`,r++;else if(e===`[`){let e=t.indexOf(`]`,r);e===-1?(n+=`\\[`,r++):(n+=t.slice(r,e+1),r=e+1)}else n+=e.replace(/[.+^${}()|\\]/g,`\\$&`),r++}n+=`$`;try{return new RegExp(n).test(e)}catch{return e===t}}function VV(e,t){let n=typeof e==`string`?{id:``,type:``,name:e,input:t??{}}:e;if(!MV.isBuiltinRequest(n)){for(let e of Object.values(n.input))if(typeof e==`string`)return e;return``}switch(n.name){case`edit`:return n.input.filePath??``;case`read`:return n.input.filePath??``;case`write`:return n.input.filePath??``;case`bash`:return n.input.command??``;case`navigate_to`:case`new_tab`:case`web_fetch`:return n.input.url??``;case`web_search`:return n.input.searchTerm??``;case`grep`:return n.input.pattern??``;default:return``}}const HV=dt([`codellm`,`agent`,`permissions`]);var BCe=class{denyRules;askRules;allowRules;constructor(e){let{rules:t,cliAllowed:n,cliDenied:r}=e;this.denyRules=[...(t.deny??[]).map(PV),...(r??[]).map(PV)],this.askRules=(t.ask??[]).map(PV),this.allowRules=[...(t.allow??[]).map(PV),...(n??[]).map(PV)]}evaluate(e,t){if(e===`Bash`){let n=nF(t);if(n.length>1){let t=this.evaluateBashCompound(n);return HV.debug`permission: ${e} decision=${t}`,t}}for(let n of this.denyRules)if(FV(n,e,t))return HV.debug`permission: ${e} decision=deny`,`deny`;for(let n of this.askRules)if(FV(n,e,t))return HV.debug`permission: ${e} decision=ask`,`ask`;for(let n of this.allowRules)if(FV(n,e,t))return HV.debug`permission: ${e} decision=allow`,`allow`;return null}evaluateBashCompound(e){let t=`allow`;for(let n of e){let e=n.trim();if(!e)continue;let r=this.evaluateSingleBashSegment(e);if(r===`deny`)return`deny`;r===`ask`&&(t=`ask`),r===null&&t!==`ask`&&(t=null)}return t}evaluateSingleBashSegment(e){for(let t of this.denyRules)if(t.displayName===`Bash`&&(t.pattern===null||IV(t.pattern,e)))return`deny`;for(let t of this.askRules)if(t.displayName===`Bash`&&(t.pattern===null||IV(t.pattern,e)))return`ask`;for(let t of this.allowRules)if(t.displayName===`Bash`&&(t.pattern===null||IV(t.pattern,e)))return`allow`;return null}getUnmatchedBashSegments(e,t){let n=nF(e),r=[];for(let e of n){let n=e.trim();if(!n)continue;let i=this.evaluateSingleBashSegment(n);if(i!==`allow`){if(i===null){let e=EF(OF(n),t);if(e.isKnown&&!e.requiresPermission)continue}r.push(FF(n))}}return[...new Set(r)]}addAllowRule(e){this.allowRules.push(PV(e))}addDenyRule(e){this.denyRules.push(PV(e))}addAskRule(e){this.askRules.push(PV(e))}getAllowRules(){return this.allowRules.map(e=>e.pattern===null?e.displayName:`${e.displayName}(${e.pattern})`)}},UV=G(((e,t)=>{let n=`[^\\\\/]`,r=`[^/]`,i=`(?:\\/|$)`,a=`(?:^|\\/)`,o=`\\.{1,2}${i}`,s={DOT_LITERAL:`\\.`,PLUS_LITERAL:`\\+`,QMARK_LITERAL:`\\?`,SLASH_LITERAL:`\\/`,ONE_CHAR:`(?=.)`,QMARK:r,END_ANCHOR:i,DOTS_SLASH:o,NO_DOT:`(?!\\.)`,NO_DOTS:`(?!${a}${o})`,NO_DOT_SLASH:`(?!\\.{0,1}${i})`,NO_DOTS_SLASH:`(?!${o})`,QMARK_NO_DOT:`[^.\\/]`,STAR:`${r}*?`,START_ANCHOR:a,SEP:`/`},c={...s,SLASH_LITERAL:`[\\\\/]`,QMARK:n,STAR:`${n}*?`,DOTS_SLASH:`\\.{1,2}(?:[\\\\/]|$)`,NO_DOT:`(?!\\.)`,NO_DOTS:`(?!(?:^|[\\\\/])\\.{1,2}(?:[\\\\/]|$))`,NO_DOT_SLASH:`(?!\\.{0,1}(?:[\\\\/]|$))`,NO_DOTS_SLASH:`(?!\\.{1,2}(?:[\\\\/]|$))`,QMARK_NO_DOT:`[^.\\\\/]`,START_ANCHOR:`(?:^|[\\\\/])`,END_ANCHOR:`(?:[\\\\/]|$)`,SEP:`\\`};t.exports={MAX_LENGTH:1024*64,POSIX_REGEX_SOURCE:{alnum:`a-zA-Z0-9`,alpha:`a-zA-Z`,ascii:`\\x00-\\x7F`,blank:` \\t`,cntrl:`\\x00-\\x1F\\x7F`,digit:`0-9`,graph:`\\x21-\\x7E`,lower:`a-z`,print:`\\x20-\\x7E `,punct:`\\-!"#$%&'()\\*+,./:;<=>?@[\\]^_\`{|}~`,space:` \\t\\r\\n\\v\\f`,upper:`A-Z`,word:`A-Za-z0-9_`,xdigit:`A-Fa-f0-9`},REGEX_BACKSLASH:/\\(?![*+?^${}(|)[\]])/g,REGEX_NON_SPECIAL_CHARS:/^[^@![\].,$*+?^{}()|\\/]+/,REGEX_SPECIAL_CHARS:/[-*+?.^${}(|)[\]]/,REGEX_SPECIAL_CHARS_BACKREF:/(\\?)((\W)(\3*))/g,REGEX_SPECIAL_CHARS_GLOBAL:/([-*+?.^${}(|)[\]])/g,REGEX_REMOVE_BACKSLASH:/(?:\[.*?[^\\]\]|\\(?=.))/g,REPLACEMENTS:{__proto__:null,"***":`*`,"**/**":`**`,"**/**/**":`**`},CHAR_0:48,CHAR_9:57,CHAR_UPPERCASE_A:65,CHAR_LOWERCASE_A:97,CHAR_UPPERCASE_Z:90,CHAR_LOWERCASE_Z:122,CHAR_LEFT_PARENTHESES:40,CHAR_RIGHT_PARENTHESES:41,CHAR_ASTERISK:42,CHAR_AMPERSAND:38,CHAR_AT:64,CHAR_BACKWARD_SLASH:92,CHAR_CARRIAGE_RETURN:13,CHAR_CIRCUMFLEX_ACCENT:94,CHAR_COLON:58,CHAR_COMMA:44,CHAR_DOT:46,CHAR_DOUBLE_QUOTE:34,CHAR_EQUAL:61,CHAR_EXCLAMATION_MARK:33,CHAR_FORM_FEED:12,CHAR_FORWARD_SLASH:47,CHAR_GRAVE_ACCENT:96,CHAR_HASH:35,CHAR_HYPHEN_MINUS:45,CHAR_LEFT_ANGLE_BRACKET:60,CHAR_LEFT_CURLY_BRACE:123,CHAR_LEFT_SQUARE_BRACKET:91,CHAR_LINE_FEED:10,CHAR_NO_BREAK_SPACE:160,CHAR_PERCENT:37,CHAR_PLUS:43,CHAR_QUESTION_MARK:63,CHAR_RIGHT_ANGLE_BRACKET:62,CHAR_RIGHT_CURLY_BRACE:125,CHAR_RIGHT_SQUARE_BRACKET:93,CHAR_SEMICOLON:59,CHAR_SINGLE_QUOTE:39,CHAR_SPACE:32,CHAR_TAB:9,CHAR_UNDERSCORE:95,CHAR_VERTICAL_LINE:124,CHAR_ZERO_WIDTH_NOBREAK_SPACE:65279,extglobChars(e){return{"!":{type:`negate`,open:`(?:(?!(?:`,close:`))${e.STAR})`},"?":{type:`qmark`,open:`(?:`,close:`)?`},"+":{type:`plus`,open:`(?:`,close:`)+`},"*":{type:`star`,open:`(?:`,close:`)*`},"@":{type:`at`,open:`(?:`,close:`)`}}},globChars(e){return e===!0?c:s}}})),WV=G((e=>{let{REGEX_BACKSLASH:t,REGEX_REMOVE_BACKSLASH:n,REGEX_SPECIAL_CHARS:r,REGEX_SPECIAL_CHARS_GLOBAL:i}=UV();e.isObject=e=>typeof e==`object`&&!!e&&!Array.isArray(e),e.hasRegexChars=e=>r.test(e),e.isRegexChar=t=>t.length===1&&e.hasRegexChars(t),e.escapeRegex=e=>e.replace(i,`\\$1`),e.toPosixSlashes=e=>e.replace(t,`/`),e.isWindows=()=>{if(typeof navigator<`u`&&navigator.platform){let e=navigator.platform.toLowerCase();return e===`win32`||e===`windows`}return typeof process<`u`&&process.platform?process.platform===`win32`:!1},e.removeBackslashes=e=>e.replace(n,e=>e===`\\`?``:e),e.escapeLast=(t,n,r)=>{let i=t.lastIndexOf(n,r);return i===-1?t:t[i-1]===`\\`?e.escapeLast(t,n,i-1):`${t.slice(0,i)}\\${t.slice(i)}`},e.removePrefix=(e,t={})=>{let n=e;return n.startsWith(`./`)&&(n=n.slice(2),t.prefix=`./`),n},e.wrapOutput=(e,t={},n={})=>{let r=`${n.contains?``:`^`}(?:${e})${n.contains?``:`$`}`;return t.negated===!0&&(r=`(?:^(?!${r}).*$)`),r},e.basename=(e,{windows:t}={})=>{let n=e.split(t?/[\\/]/:`/`),r=n[n.length-1];return r===``?n[n.length-2]:r}})),VCe=G(((e,t)=>{let n=WV(),{CHAR_ASTERISK:r,CHAR_AT:i,CHAR_BACKWARD_SLASH:a,CHAR_COMMA:o,CHAR_DOT:s,CHAR_EXCLAMATION_MARK:c,CHAR_FORWARD_SLASH:l,CHAR_LEFT_CURLY_BRACE:u,CHAR_LEFT_PARENTHESES:d,CHAR_LEFT_SQUARE_BRACKET:f,CHAR_PLUS:p,CHAR_QUESTION_MARK:m,CHAR_RIGHT_CURLY_BRACE:h,CHAR_RIGHT_PARENTHESES:g,CHAR_RIGHT_SQUARE_BRACKET:_}=UV(),v=e=>e===l||e===a,y=e=>{e.isPrefix!==!0&&(e.depth=e.isGlobstar?1/0:1)};t.exports=(e,t)=>{let b=t||{},x=e.length-1,S=b.parts===!0||b.scanToEnd===!0,C=[],w=[],T=[],E=e,D=-1,O=0,k=0,A=!1,j=!1,M=!1,N=!1,P=!1,ee=!1,F=!1,te=!1,I=!1,L=!1,R=0,z,ne,re={value:``,depth:0,isGlob:!1},ie=()=>D>=x,ae=()=>E.charCodeAt(D+1),oe=()=>(z=ne,E.charCodeAt(++D));for(;D<x;){ne=oe();let e;if(ne===a){F=re.backslashes=!0,ne=oe(),ne===u&&(ee=!0);continue}if(ee===!0||ne===u){for(R++;ie()!==!0&&(ne=oe());){if(ne===a){F=re.backslashes=!0,oe();continue}if(ne===u){R++;continue}if(ee!==!0&&ne===s&&(ne=oe())===s){if(A=re.isBrace=!0,M=re.isGlob=!0,L=!0,S===!0)continue;break}if(ee!==!0&&ne===o){if(A=re.isBrace=!0,M=re.isGlob=!0,L=!0,S===!0)continue;break}if(ne===h&&(R--,R===0)){ee=!1,A=re.isBrace=!0,L=!0;break}}if(S===!0)continue;break}if(ne===l){if(C.push(D),w.push(re),re={value:``,depth:0,isGlob:!1},L===!0)continue;if(z===s&&D===O+1){O+=2;continue}k=D+1;continue}if(b.noext!==!0&&(ne===p||ne===i||ne===r||ne===m||ne===c)&&ae()===d){if(M=re.isGlob=!0,N=re.isExtglob=!0,L=!0,ne===c&&D===O&&(I=!0),S===!0){for(;ie()!==!0&&(ne=oe());){if(ne===a){F=re.backslashes=!0,ne=oe();continue}if(ne===g){M=re.isGlob=!0,L=!0;break}}continue}break}if(ne===r){if(z===r&&(P=re.isGlobstar=!0),M=re.isGlob=!0,L=!0,S===!0)continue;break}if(ne===m){if(M=re.isGlob=!0,L=!0,S===!0)continue;break}if(ne===f){for(;ie()!==!0&&(e=oe());){if(e===a){F=re.backslashes=!0,oe();continue}if(e===_){j=re.isBracket=!0,M=re.isGlob=!0,L=!0;break}}if(S===!0)continue;break}if(b.nonegate!==!0&&ne===c&&D===O){te=re.negated=!0,O++;continue}if(b.noparen!==!0&&ne===d){if(M=re.isGlob=!0,S===!0){for(;ie()!==!0&&(ne=oe());){if(ne===d){F=re.backslashes=!0,ne=oe();continue}if(ne===g){L=!0;break}}continue}break}if(M===!0){if(L=!0,S===!0)continue;break}}b.noext===!0&&(N=!1,M=!1);let se=E,ce=``,le=``;O>0&&(ce=E.slice(0,O),E=E.slice(O),k-=O),se&&M===!0&&k>0?(se=E.slice(0,k),le=E.slice(k)):M===!0?(se=``,le=E):se=E,se&&se!==``&&se!==`/`&&se!==E&&v(se.charCodeAt(se.length-1))&&(se=se.slice(0,-1)),b.unescape===!0&&(le&&=n.removeBackslashes(le),se&&F===!0&&(se=n.removeBackslashes(se)));let ue={prefix:ce,input:e,start:O,base:se,glob:le,isBrace:A,isBracket:j,isGlob:M,isExtglob:N,isGlobstar:P,negated:te,negatedExtglob:I};if(b.tokens===!0&&(ue.maxDepth=0,v(ne)||w.push(re),ue.tokens=w),b.parts===!0||b.tokens===!0){let t;for(let n=0;n<C.length;n++){let r=t?t+1:O,i=C[n],a=e.slice(r,i);b.tokens&&(n===0&&O!==0?(w[n].isPrefix=!0,w[n].value=ce):w[n].value=a,y(w[n]),ue.maxDepth+=w[n].depth),(n!==0||a!==``)&&T.push(a),t=i}if(t&&t+1<e.length){let n=e.slice(t+1);T.push(n),b.tokens&&(w[w.length-1].value=n,y(w[w.length-1]),ue.maxDepth+=w[w.length-1].depth)}ue.slashes=C,ue.parts=T}return ue}})),HCe=G(((e,t)=>{let n=UV(),r=WV(),{MAX_LENGTH:i,POSIX_REGEX_SOURCE:a,REGEX_NON_SPECIAL_CHARS:o,REGEX_SPECIAL_CHARS_BACKREF:s,REPLACEMENTS:c}=n,l=(e,t)=>{if(typeof t.expandRange==`function`)return t.expandRange(...e,t);e.sort();let n=`[${e.join(`-`)}]`;try{new RegExp(n)}catch{return e.map(e=>r.escapeRegex(e)).join(`..`)}return n},u=(e,t)=>`Missing ${e}: "${t}" - use "\\\\${t}" to match literal characters`,d=(e,t)=>{if(typeof e!=`string`)throw TypeError(`Expected a string`);e=c[e]||e;let f={...t},p=typeof f.maxLength==`number`?Math.min(i,f.maxLength):i,m=e.length;if(m>p)throw SyntaxError(`Input length: ${m}, exceeds maximum allowed length: ${p}`);let h={type:`bos`,value:``,output:f.prepend||``},g=[h],_=f.capture?``:`?:`,v=n.globChars(f.windows),y=n.extglobChars(v),{DOT_LITERAL:b,PLUS_LITERAL:x,SLASH_LITERAL:S,ONE_CHAR:C,DOTS_SLASH:w,NO_DOT:T,NO_DOT_SLASH:E,NO_DOTS_SLASH:D,QMARK:O,QMARK_NO_DOT:k,STAR:A,START_ANCHOR:j}=v,M=e=>`(${_}(?:(?!${j}${e.dot?w:b}).)*?)`,N=f.dot?``:T,P=f.dot?O:k,ee=f.bash===!0?M(f):A;f.capture&&(ee=`(${ee})`),typeof f.noext==`boolean`&&(f.noextglob=f.noext);let F={input:e,index:-1,start:0,dot:f.dot===!0,consumed:``,output:``,prefix:``,backtrack:!1,negated:!1,brackets:0,braces:0,parens:0,quotes:0,globstar:!1,tokens:g};e=r.removePrefix(e,F),m=e.length;let te=[],I=[],L=[],R=h,z,ne=()=>F.index===m-1,re=F.peek=(t=1)=>e[F.index+t],ie=F.advance=()=>e[++F.index]||``,ae=()=>e.slice(F.index+1),oe=(e=``,t=0)=>{F.consumed+=e,F.index+=t},se=e=>{F.output+=e.output==null?e.value:e.output,oe(e.value)},ce=()=>{let e=1;for(;re()===`!`&&(re(2)!==`(`||re(3)===`?`);)ie(),F.start++,e++;return e%2==0?!1:(F.negated=!0,F.start++,!0)},le=e=>{F[e]++,L.push(e)},ue=e=>{F[e]--,L.pop()},de=e=>{if(R.type===`globstar`){let t=F.braces>0&&(e.type===`comma`||e.type===`brace`),n=e.extglob===!0||te.length&&(e.type===`pipe`||e.type===`paren`);e.type!==`slash`&&e.type!==`paren`&&!t&&!n&&(F.output=F.output.slice(0,-R.output.length),R.type=`star`,R.value=`*`,R.output=ee,F.output+=R.output)}if(te.length&&e.type!==`paren`&&(te[te.length-1].inner+=e.value),(e.value||e.output)&&se(e),R&&R.type===`text`&&e.type===`text`){R.output=(R.output||R.value)+e.value,R.value+=e.value;return}e.prev=R,g.push(e),R=e},fe=(e,t)=>{let n={...y[t],conditions:1,inner:``};n.prev=R,n.parens=F.parens,n.output=F.output;let r=(f.capture?`(`:``)+n.open;le(`parens`),de({type:e,value:t,output:F.output?``:C}),de({type:`paren`,extglob:!0,value:ie(),output:r}),te.push(n)},B=e=>{let n=e.close+(f.capture?`)`:``),r;if(e.type===`negate`){let i=ee;e.inner&&e.inner.length>1&&e.inner.includes(`/`)&&(i=M(f)),(i!==ee||ne()||/^\)+$/.test(ae()))&&(n=e.close=`)$))${i}`),e.inner.includes(`*`)&&(r=ae())&&/^\.[^\\/.]+$/.test(r)&&(n=e.close=`)${d(r,{...t,fastpaths:!1}).output})${i})`),e.prev.type===`bos`&&(F.negatedExtglob=!0)}de({type:`paren`,extglob:!0,value:z,output:n}),ue(`parens`)};if(f.fastpaths!==!1&&!/(^[*!]|[/()[\]{}"])/.test(e)){let n=!1,i=e.replace(s,(e,t,r,i,a,o)=>i===`\\`?(n=!0,e):i===`?`?t?t+i+(a?O.repeat(a.length):``):o===0?P+(a?O.repeat(a.length):``):O.repeat(r.length):i===`.`?b.repeat(r.length):i===`*`?t?t+i+(a?ee:``):ee:t?e:`\\${e}`);return n===!0&&(i=f.unescape===!0?i.replace(/\\/g,``):i.replace(/\\+/g,e=>e.length%2==0?`\\\\`:e?`\\`:``)),i===e&&f.contains===!0?(F.output=e,F):(F.output=r.wrapOutput(i,F,t),F)}for(;!ne();){if(z=ie(),z===`\0`)continue;if(z===`\\`){let e=re();if(e===`/`&&f.bash!==!0||e===`.`||e===`;`)continue;if(!e){z+=`\\`,de({type:`text`,value:z});continue}let t=/^\\+/.exec(ae()),n=0;if(t&&t[0].length>2&&(n=t[0].length,F.index+=n,n%2!=0&&(z+=`\\`)),f.unescape===!0?z=ie():z+=ie(),F.brackets===0){de({type:`text`,value:z});continue}}if(F.brackets>0&&(z!==`]`||R.value===`[`||R.value===`[^`)){if(f.posix!==!1&&z===`:`){let e=R.value.slice(1);if(e.includes(`[`)&&(R.posix=!0,e.includes(`:`))){let e=R.value.lastIndexOf(`[`),t=R.value.slice(0,e),n=a[R.value.slice(e+2)];if(n){R.value=t+n,F.backtrack=!0,ie(),!h.output&&g.indexOf(R)===1&&(h.output=C);continue}}}(z===`[`&&re()!==`:`||z===`-`&&re()===`]`)&&(z=`\\${z}`),z===`]`&&(R.value===`[`||R.value===`[^`)&&(z=`\\${z}`),f.posix===!0&&z===`!`&&R.value===`[`&&(z=`^`),R.value+=z,se({value:z});continue}if(F.quotes===1&&z!==`"`){z=r.escapeRegex(z),R.value+=z,se({value:z});continue}if(z===`"`){F.quotes=F.quotes===1?0:1,f.keepQuotes===!0&&de({type:`text`,value:z});continue}if(z===`(`){le(`parens`),de({type:`paren`,value:z});continue}if(z===`)`){if(F.parens===0&&f.strictBrackets===!0)throw SyntaxError(u(`opening`,`(`));let e=te[te.length-1];if(e&&F.parens===e.parens+1){B(te.pop());continue}de({type:`paren`,value:z,output:F.parens?`)`:`\\)`}),ue(`parens`);continue}if(z===`[`){if(f.nobracket===!0||!ae().includes(`]`)){if(f.nobracket!==!0&&f.strictBrackets===!0)throw SyntaxError(u(`closing`,`]`));z=`\\${z}`}else le(`brackets`);de({type:`bracket`,value:z});continue}if(z===`]`){if(f.nobracket===!0||R&&R.type===`bracket`&&R.value.length===1){de({type:`text`,value:z,output:`\\${z}`});continue}if(F.brackets===0){if(f.strictBrackets===!0)throw SyntaxError(u(`opening`,`[`));de({type:`text`,value:z,output:`\\${z}`});continue}ue(`brackets`);let e=R.value.slice(1);if(R.posix!==!0&&e[0]===`^`&&!e.includes(`/`)&&(z=`/${z}`),R.value+=z,se({value:z}),f.literalBrackets===!1||r.hasRegexChars(e))continue;let t=r.escapeRegex(R.value);if(F.output=F.output.slice(0,-R.value.length),f.literalBrackets===!0){F.output+=t,R.value=t;continue}R.value=`(${_}${t}|${R.value})`,F.output+=R.value;continue}if(z===`{`&&f.nobrace!==!0){le(`braces`);let e={type:`brace`,value:z,output:`(`,outputIndex:F.output.length,tokensIndex:F.tokens.length};I.push(e),de(e);continue}if(z===`}`){let e=I[I.length-1];if(f.nobrace===!0||!e){de({type:`text`,value:z,output:z});continue}let t=`)`;if(e.dots===!0){let e=g.slice(),n=[];for(let t=e.length-1;t>=0&&(g.pop(),e[t].type!==`brace`);t--)e[t].type!==`dots`&&n.unshift(e[t].value);t=l(n,f),F.backtrack=!0}if(e.comma!==!0&&e.dots!==!0){let n=F.output.slice(0,e.outputIndex),r=F.tokens.slice(e.tokensIndex);e.value=e.output=`\\{`,z=t=`\\}`,F.output=n;for(let e of r)F.output+=e.output||e.value}de({type:`brace`,value:z,output:t}),ue(`braces`),I.pop();continue}if(z===`|`){te.length>0&&te[te.length-1].conditions++,de({type:`text`,value:z});continue}if(z===`,`){let e=z,t=I[I.length-1];t&&L[L.length-1]===`braces`&&(t.comma=!0,e=`|`),de({type:`comma`,value:z,output:e});continue}if(z===`/`){if(R.type===`dot`&&F.index===F.start+1){F.start=F.index+1,F.consumed=``,F.output=``,g.pop(),R=h;continue}de({type:`slash`,value:z,output:S});continue}if(z===`.`){if(F.braces>0&&R.type===`dot`){R.value===`.`&&(R.output=b);let e=I[I.length-1];R.type=`dots`,R.output+=z,R.value+=z,e.dots=!0;continue}if(F.braces+F.parens===0&&R.type!==`bos`&&R.type!==`slash`){de({type:`text`,value:z,output:b});continue}de({type:`dot`,value:z,output:b});continue}if(z===`?`){if(!(R&&R.value===`(`)&&f.noextglob!==!0&&re()===`(`&&re(2)!==`?`){fe(`qmark`,z);continue}if(R&&R.type===`paren`){let e=re(),t=z;(R.value===`(`&&!/[!=<:]/.test(e)||e===`<`&&!/<([!=]|\w+>)/.test(ae()))&&(t=`\\${z}`),de({type:`text`,value:z,output:t});continue}if(f.dot!==!0&&(R.type===`slash`||R.type===`bos`)){de({type:`qmark`,value:z,output:k});continue}de({type:`qmark`,value:z,output:O});continue}if(z===`!`){if(f.noextglob!==!0&&re()===`(`&&(re(2)!==`?`||!/[!=<:]/.test(re(3)))){fe(`negate`,z);continue}if(f.nonegate!==!0&&F.index===0){ce();continue}}if(z===`+`){if(f.noextglob!==!0&&re()===`(`&&re(2)!==`?`){fe(`plus`,z);continue}if(R&&R.value===`(`||f.regex===!1){de({type:`plus`,value:z,output:x});continue}if(R&&(R.type===`bracket`||R.type===`paren`||R.type===`brace`)||F.parens>0){de({type:`plus`,value:z});continue}de({type:`plus`,value:x});continue}if(z===`@`){if(f.noextglob!==!0&&re()===`(`&&re(2)!==`?`){de({type:`at`,extglob:!0,value:z,output:``});continue}de({type:`text`,value:z});continue}if(z!==`*`){(z===`$`||z===`^`)&&(z=`\\${z}`);let e=o.exec(ae());e&&(z+=e[0],F.index+=e[0].length),de({type:`text`,value:z});continue}if(R&&(R.type===`globstar`||R.star===!0)){R.type=`star`,R.star=!0,R.value+=z,R.output=ee,F.backtrack=!0,F.globstar=!0,oe(z);continue}let t=ae();if(f.noextglob!==!0&&/^\([^?]/.test(t)){fe(`star`,z);continue}if(R.type===`star`){if(f.noglobstar===!0){oe(z);continue}let n=R.prev,r=n.prev,i=n.type===`slash`||n.type===`bos`,a=r&&(r.type===`star`||r.type===`globstar`);if(f.bash===!0&&(!i||t[0]&&t[0]!==`/`)){de({type:`star`,value:z,output:``});continue}let o=F.braces>0&&(n.type===`comma`||n.type===`brace`),s=te.length&&(n.type===`pipe`||n.type===`paren`);if(!i&&n.type!==`paren`&&!o&&!s){de({type:`star`,value:z,output:``});continue}for(;t.slice(0,3)===`/**`;){let n=e[F.index+4];if(n&&n!==`/`)break;t=t.slice(3),oe(`/**`,3)}if(n.type===`bos`&&ne()){R.type=`globstar`,R.value+=z,R.output=M(f),F.output=R.output,F.globstar=!0,oe(z);continue}if(n.type===`slash`&&n.prev.type!==`bos`&&!a&&ne()){F.output=F.output.slice(0,-(n.output+R.output).length),n.output=`(?:${n.output}`,R.type=`globstar`,R.output=M(f)+(f.strictSlashes?`)`:`|$)`),R.value+=z,F.globstar=!0,F.output+=n.output+R.output,oe(z);continue}if(n.type===`slash`&&n.prev.type!==`bos`&&t[0]===`/`){let e=t[1]===void 0?``:`|$`;F.output=F.output.slice(0,-(n.output+R.output).length),n.output=`(?:${n.output}`,R.type=`globstar`,R.output=`${M(f)}${S}|${S}${e})`,R.value+=z,F.output+=n.output+R.output,F.globstar=!0,oe(z+ie()),de({type:`slash`,value:`/`,output:``});continue}if(n.type===`bos`&&t[0]===`/`){R.type=`globstar`,R.value+=z,R.output=`(?:^|${S}|${M(f)}${S})`,F.output=R.output,F.globstar=!0,oe(z+ie()),de({type:`slash`,value:`/`,output:``});continue}F.output=F.output.slice(0,-R.output.length),R.type=`globstar`,R.output=M(f),R.value+=z,F.output+=R.output,F.globstar=!0,oe(z);continue}let n={type:`star`,value:z,output:ee};if(f.bash===!0){n.output=`.*?`,(R.type===`bos`||R.type===`slash`)&&(n.output=N+n.output),de(n);continue}if(R&&(R.type===`bracket`||R.type===`paren`)&&f.regex===!0){n.output=z,de(n);continue}(F.index===F.start||R.type===`slash`||R.type===`dot`)&&(R.type===`dot`?(F.output+=E,R.output+=E):f.dot===!0?(F.output+=D,R.output+=D):(F.output+=N,R.output+=N),re()!==`*`&&(F.output+=C,R.output+=C)),de(n)}for(;F.brackets>0;){if(f.strictBrackets===!0)throw SyntaxError(u(`closing`,`]`));F.output=r.escapeLast(F.output,`[`),ue(`brackets`)}for(;F.parens>0;){if(f.strictBrackets===!0)throw SyntaxError(u(`closing`,`)`));F.output=r.escapeLast(F.output,`(`),ue(`parens`)}for(;F.braces>0;){if(f.strictBrackets===!0)throw SyntaxError(u(`closing`,`}`));F.output=r.escapeLast(F.output,`{`),ue(`braces`)}if(f.strictSlashes!==!0&&(R.type===`star`||R.type===`bracket`)&&de({type:`maybe_slash`,value:``,output:`${S}?`}),F.backtrack===!0){F.output=``;for(let e of F.tokens)F.output+=e.output==null?e.value:e.output,e.suffix&&(F.output+=e.suffix)}return F};d.fastpaths=(e,t)=>{let a={...t},o=typeof a.maxLength==`number`?Math.min(i,a.maxLength):i,s=e.length;if(s>o)throw SyntaxError(`Input length: ${s}, exceeds maximum allowed length: ${o}`);e=c[e]||e;let{DOT_LITERAL:l,SLASH_LITERAL:u,ONE_CHAR:d,DOTS_SLASH:f,NO_DOT:p,NO_DOTS:m,NO_DOTS_SLASH:h,STAR:g,START_ANCHOR:_}=n.globChars(a.windows),v=a.dot?m:p,y=a.dot?h:p,b=a.capture?``:`?:`,x={negated:!1,prefix:``},S=a.bash===!0?`.*?`:g;a.capture&&(S=`(${S})`);let C=e=>e.noglobstar===!0?S:`(${b}(?:(?!${_}${e.dot?f:l}).)*?)`,w=e=>{switch(e){case`*`:return`${v}${d}${S}`;case`.*`:return`${l}${d}${S}`;case`*.*`:return`${v}${S}${l}${d}${S}`;case`*/*`:return`${v}${S}${u}${d}${y}${S}`;case`**`:return v+C(a);case`**/*`:return`(?:${v}${C(a)}${u})?${y}${d}${S}`;case`**/*.*`:return`(?:${v}${C(a)}${u})?${y}${S}${l}${d}${S}`;case`**/.*`:return`(?:${v}${C(a)}${u})?${l}${d}${S}`;default:{let t=/^(.*?)\.(\w+)$/.exec(e);if(!t)return;let n=w(t[1]);return n?n+l+t[2]:void 0}}},T=w(r.removePrefix(e,x));return T&&a.strictSlashes!==!0&&(T+=`${u}?`),T},t.exports=d})),UCe=G(((e,t)=>{let n=VCe(),r=HCe(),i=WV(),a=UV(),o=e=>e&&typeof e==`object`&&!Array.isArray(e),s=(e,t,n=!1)=>{if(Array.isArray(e)){let r=e.map(e=>s(e,t,n));return e=>{for(let t of r){let n=t(e);if(n)return n}return!1}}let r=o(e)&&e.tokens&&e.input;if(e===``||typeof e!=`string`&&!r)throw TypeError(`Expected pattern to be a non-empty string`);let i=t||{},a=i.windows,c=r?s.compileRe(e,t):s.makeRe(e,t,!1,!0),l=c.state;delete c.state;let u=()=>!1;if(i.ignore){let e={...t,ignore:null,onMatch:null,onResult:null};u=s(i.ignore,e,n)}let d=(n,r=!1)=>{let{isMatch:o,match:d,output:f}=s.test(n,c,t,{glob:e,posix:a}),p={glob:e,state:l,regex:c,posix:a,input:n,output:f,match:d,isMatch:o};return typeof i.onResult==`function`&&i.onResult(p),o===!1?(p.isMatch=!1,r?p:!1):u(n)?(typeof i.onIgnore==`function`&&i.onIgnore(p),p.isMatch=!1,r?p:!1):(typeof i.onMatch==`function`&&i.onMatch(p),r?p:!0)};return n&&(d.state=l),d};s.test=(e,t,n,{glob:r,posix:a}={})=>{if(typeof e!=`string`)throw TypeError(`Expected input to be a string`);if(e===``)return{isMatch:!1,output:``};let o=n||{},c=o.format||(a?i.toPosixSlashes:null),l=e===r,u=l&&c?c(e):e;return l===!1&&(u=c?c(e):e,l=u===r),(l===!1||o.capture===!0)&&(l=o.matchBase===!0||o.basename===!0?s.matchBase(e,t,n,a):t.exec(u)),{isMatch:!!l,match:l,output:u}},s.matchBase=(e,t,n)=>(t instanceof RegExp?t:s.makeRe(t,n)).test(i.basename(e)),s.isMatch=(e,t,n)=>s(t,n)(e),s.parse=(e,t)=>Array.isArray(e)?e.map(e=>s.parse(e,t)):r(e,{...t,fastpaths:!1}),s.scan=(e,t)=>n(e,t),s.compileRe=(e,t,n=!1,r=!1)=>{if(n===!0)return e.output;let i=t||{},a=i.contains?``:`^`,o=i.contains?``:`$`,c=`${a}(?:${e.output})${o}`;e&&e.negated===!0&&(c=`^(?!${c}).*$`);let l=s.toRegex(c,t);return r===!0&&(l.state=e),l},s.makeRe=(e,t={},n=!1,i=!1)=>{if(!e||typeof e!=`string`)throw TypeError(`Expected a non-empty string`);let a={negated:!1,fastpaths:!0};return t.fastpaths!==!1&&(e[0]===`.`||e[0]===`*`)&&(a.output=r.fastpaths(e,t)),a.output||(a=r(e,t)),s.compileRe(a,t,n,i)},s.toRegex=(e,t)=>{try{let n=t||{};return new RegExp(e,n.flags||(n.nocase?`i`:``))}catch(e){if(t&&t.debug===!0)throw e;return/$^/}},s.constants=a,t.exports=s})),WCe=G(((e,t)=>{let n=UCe(),r=WV();function i(e,t,i=!1){return t&&(t.windows===null||t.windows===void 0)&&(t={...t,windows:r.isWindows()}),n(e,t,i)}Object.assign(i,n),t.exports=i}));const GV=8192;async function KV(e){let t=await m.open(e,`r`);try{let e=Buffer.alloc(GV),{bytesRead:n}=await t.read(e,0,GV,0);for(let t=0;t<n;t++)if(e[t]===0)return!0;return!1}finally{await t.close()}}
@@ -75076,9 +75076,9 @@ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,`$1$2`).replace(/\
75076
75076
  `)+1;for(;e!==0;)this.onNewLine(this.offset+e),e=this.source.indexOf(`
75077
75077
  `,e)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){let t=e.items[e.items.length-1];switch(this.type){case`newline`:if(this.onKeyLine=!1,t.value){let n=`end`in t.value?t.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type===`comment`?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case`space`:case`comment`:if(t.value)e.items.push({start:[this.sourceToken]});else if(t.sep)t.sep.push(this.sourceToken);else{if(this.atIndentedComment(t.start,e.indent)){let n=e.items[e.items.length-2]?.value?.end;if(Array.isArray(n)){Array.prototype.push.apply(n,t.start),n.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return}if(this.indent>=e.indent){let n=!this.onKeyLine&&this.indent===e.indent,r=n&&(t.sep||t.explicitKey)&&this.type!==`seq-item-ind`,a=[];if(r&&t.sep&&!t.value){let n=[];for(let r=0;r<t.sep.length;++r){let i=t.sep[r];switch(i.type){case`newline`:n.push(r);break;case`space`:break;case`comment`:i.indent>e.indent&&(n.length=0);break;default:n.length=0}}n.length>=2&&(a=t.sep.splice(n[1]))}switch(this.type){case`anchor`:case`tag`:r||t.value?(a.push(this.sourceToken),e.items.push({start:a}),this.onKeyLine=!0):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case`explicit-key-ind`:!t.sep&&!t.explicitKey?(t.start.push(this.sourceToken),t.explicitKey=!0):r||t.value?(a.push(this.sourceToken),e.items.push({start:a,explicitKey:!0})):this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case`map-value-ind`:if(t.explicitKey)if(!t.sep)if(i(t.start,`newline`))Object.assign(t,{key:null,sep:[this.sourceToken]});else{let e=c(t.start);this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:e,key:null,sep:[this.sourceToken]}]})}else if(t.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(i(t.sep,`map-value-ind`))this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:a,key:null,sep:[this.sourceToken]}]});else if(o(t.key)&&!i(t.sep,`newline`)){let e=c(t.start),n=t.key,r=t.sep;r.push(this.sourceToken),delete t.key,delete t.sep,this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:e,key:n,sep:r}]})}else a.length>0?t.sep=t.sep.concat(a,this.sourceToken):t.sep.push(this.sourceToken);else t.sep?t.value||r?e.items.push({start:a,key:null,sep:[this.sourceToken]}):i(t.sep,`map-value-ind`)?this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:{let n=this.flowScalar(this.type);r||t.value?(e.items.push({start:a,key:n,sep:[]}),this.onKeyLine=!0):t.sep?this.stack.push(n):(Object.assign(t,{key:n,sep:[]}),this.onKeyLine=!0);return}default:{let r=this.startBlockValue(e);if(r){if(r.type===`block-seq`){if(!t.explicitKey&&t.sep&&!i(t.sep,`newline`)){yield*this.pop({type:`error`,offset:this.offset,message:`Unexpected block-seq-ind on same line with key`,source:this.source});return}}else n&&e.items.push({start:a});this.stack.push(r);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){let t=e.items[e.items.length-1];switch(this.type){case`newline`:if(t.value){let n=`end`in t.value?t.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type===`comment`?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.start.push(this.sourceToken);return;case`space`:case`comment`:if(t.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(t.start,e.indent)){let n=e.items[e.items.length-2]?.value?.end;if(Array.isArray(n)){Array.prototype.push.apply(n,t.start),n.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return;case`anchor`:case`tag`:if(t.value||this.indent<=e.indent)break;t.start.push(this.sourceToken);return;case`seq-item-ind`:if(this.indent!==e.indent)break;t.value||i(t.start,`seq-item-ind`)?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return}if(this.indent>e.indent){let t=this.startBlockValue(e);if(t){this.stack.push(t);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){let t=e.items[e.items.length-1];if(this.type===`flow-error-end`){let e;do yield*this.pop(),e=this.peek(1);while(e?.type===`flow-collection`)}else if(e.end.length===0){switch(this.type){case`comma`:case`explicit-key-ind`:!t||t.sep?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return;case`map-value-ind`:!t||t.value?e.items.push({start:[],key:null,sep:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});return;case`space`:case`comment`:case`newline`:case`anchor`:case`tag`:!t||t.value?e.items.push({start:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:{let n=this.flowScalar(this.type);!t||t.value?e.items.push({start:[],key:n,sep:[]}):t.sep?this.stack.push(n):Object.assign(t,{key:n,sep:[]});return}case`flow-map-end`:case`flow-seq-end`:e.end.push(this.sourceToken);return}let n=this.startBlockValue(e);n?this.stack.push(n):(yield*this.pop(),yield*this.step())}else{let t=this.peek(2);if(t.type===`block-map`&&(this.type===`map-value-ind`&&t.indent===e.indent||this.type===`newline`&&!t.items[t.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type===`map-value-ind`&&t.type!==`flow-collection`){let n=c(s(t));l(e);let r=e.end.splice(1,e.end.length);r.push(this.sourceToken);let i={type:`block-map`,offset:e.offset,indent:e.indent,items:[{start:n,key:e,sep:r}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=i}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let e=this.source.indexOf(`
75078
75078
  `)+1;for(;e!==0;)this.onNewLine(this.offset+e),e=this.source.indexOf(`
75079
- `,e)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:return this.flowScalar(this.type);case`block-scalar-header`:return{type:`block-scalar`,offset:this.offset,indent:this.indent,props:[this.sourceToken],source:``};case`flow-map-start`:case`flow-seq-start`:return{type:`flow-collection`,offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case`seq-item-ind`:return{type:`block-seq`,offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case`explicit-key-ind`:{this.onKeyLine=!0;let t=c(s(e));return t.push(this.sourceToken),{type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:t,explicitKey:!0}]}}case`map-value-ind`:{this.onKeyLine=!0;let t=c(s(e));return{type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:t,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){return this.type!==`comment`||this.indent<=t?!1:e.every(e=>e.type===`newline`||e.type===`space`)}*documentEnd(e){this.type!==`doc-mode`&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type===`newline`&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case`comma`:case`doc-start`:case`doc-end`:case`flow-seq-end`:case`flow-map-end`:case`map-value-ind`:yield*this.pop(),yield*this.step();break;case`newline`:this.onKeyLine=!1;default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type===`newline`&&(yield*this.pop())}}}})),bOe=G((e=>{var t=rq(),n=JK(),r=YK(),i=DK(),a=pK(),o=oq(),s=sq();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})),xOe=G((e=>{var t=rq(),n=JK(),r=qK(),i=YK(),a=bK(),o=pK(),s=AK(),c=xK(),l=MK(),u=PK();iq();var d=aq(),f=oq(),p=sq(),m=bOe(),h=mK();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 SOe(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,xOe.parse)(i);return e&&typeof e==`object`&&!Array.isArray(e)?{data:e,body:a}:{data:{},body:a}}catch{return{data:{},body:e}}}function COe(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``)}const wOe=dt([`codellm`,`agent`,`skills`]),cq=new class{skills=new Map;async loadSkills(e){let t=await pCe(),n=O.join(ee.homedir(),hn.configDirName,`skills`),r=e?O.join(e,hn.localConfigDirName,`skills`):void 0,i=await this.discoverSkills(t,`builtin`),a=await this.discoverSkills(n,`global`),o=r?await this.discoverSkills(r,`project`):[];this.skills.clear();for(let e of i)this.skills.set(e.id,e);for(let e of a)this.skills.set(e.id,e);for(let e of o)this.skills.set(e.id,e);wOe.info`skills loaded: builtin=${i.length} global=${a.length} project=${o.length}`}async discoverSkills(e,t){let n=[],r;try{r=await Te.readdir(e,{withFileTypes:!0})}catch{return n}r.sort((e,t)=>e.name.localeCompare(t.name));for(let i of r)if(i.isFile()&&i.name.endsWith(`.md`)){let r=O.join(e,i.name),a=await this.parseSkillFile(r,!1,t);a&&n.push(a)}else if(i.isDirectory()){let r=O.join(e,i.name,`SKILL.md`);try{await Te.access(r);let e=await this.parseSkillFile(r,!0,t);e&&n.push(e)}catch{}}return n}async parseSkillFile(e,t,n){try{let{data:r}=SOe(await Te.readFile(e,`utf-8`)),i=COe(t?O.basename(O.dirname(e)):O.basename(e,`.md`));return i?this.buildSkill(i,r,e,t,n):null}catch{return null}}buildSkill(e,t,n,r,i){let a=t.name,o=t.description,s=typeof a==`string`&&a.trim()?a.trim():e,c=typeof o==`string`&&o.trim()?o.trim():void 0;if(!c)return null;let l={name:s,description:c};typeof t[`argument-hint`]==`string`&&(l[`argument-hint`]=t[`argument-hint`]),typeof t[`disable-model-invocation`]==`boolean`&&(l[`disable-model-invocation`]=t[`disable-model-invocation`]),typeof t[`user-invocable`]==`boolean`&&(l[`user-invocable`]=t[`user-invocable`]),Array.isArray(t[`allowed-tools`])&&(l[`allowed-tools`]=t[`allowed-tools`].filter(e=>typeof e==`string`)),typeof t.license==`string`&&(l.license=t.license),typeof t.compatibility==`string`&&(l.compatibility=t.compatibility);let u=t.metadata;if(u&&typeof u==`object`&&!Array.isArray(u)){let e={};for(let[t,n]of Object.entries(u))typeof n==`string`&&(e[t]=n);Object.keys(e).length>0&&(l.metadata=e)}return{id:e,frontmatter:l,path:n,isDirectory:r,source:i}}get(e){return this.skills.get(e)}getAll(){return Array.from(this.skills.values()).filter(e=>e.frontmatter[`user-invocable`]!==!1)}getAllMetadata(){return this.getAll().map(e=>({id:e.id,name:e.frontmatter.name,description:e.frontmatter.description,location:e.path}))}search(e){let t=e.toLowerCase();return this.getAll().filter(e=>e.id.toLowerCase().includes(t)||e.frontmatter.name.toLowerCase().includes(t)||e.frontmatter.description.toLowerCase().includes(t))}matchSkill(e){if(!e.startsWith(`/`))return null;let t=e.slice(1).split(/\s+/);if(t.length===0)return null;let[n,...r]=t;if(!n)return null;let i=this.skills.get(n);return!i||i.frontmatter[`user-invocable`]===!1?null:{skill:i,args:r.join(` `)}}},lq=dt([`codellm`,`agent`,`tools`,`diagnostics`]);var TOe=class e extends pV{name=`get_diagnostics`;displayName=`GetDiagnostics`;description=`Get IDE diagnostics (errors, warnings, info) for a file or all open files.`;_provider;static Parameters=QL({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;lq.debug`Getting diagnostics${e.uri?` for ${e.uri}`:` for all files`}`;let r=await this._provider.getDiagnostics(n);return lq.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=xR(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`}}}},EOe=class extends wR{includeInApiDefinitions=!1};const uq=dt([`codellm`,`agent`,`tools`,`mcp`]);var DOe=class extends EOe{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 QL(r)}jsonSchemaToZod(e){switch(e.type){case`string`:return e.enum?sR(e.enum):Y();case`number`:case`integer`:return nxe;case`boolean`:return jR;case`array`:return e.items?XL(this.jsonSchemaToZod(e.items)):XL(JL());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 QL(t)}return aR(Y(),JL());case`null`:return qL();default:return e.oneOf?this.jsonSchemaToZod(e.oneOf[0]):JL()}}async execute(e,t){if(uq.debug`Executing MCP tool: ${this.name} (server=${this.mcpToolDefinition.serverId})`,!t.mcpService)return uq.warn`MCP service not available for tool: ${this.name}`,{type:`mcp`,serverId:this.mcpToolDefinition.serverId,toolName:this.name,content:`MCP service not available`,isError:!0};try{let n=(await t.mcpService.listAllToolDefinitions()).find(e=>e.name===this.name);if(!n)throw Error(`MCP tool '${this.name}' not found`);let r=await t.mcpService.callTool(n.serverId,n.originalName||this.name,e);return{type:`mcp`,serverId:n.serverId,toolName:this.name,content:r.content||r,isError:r.isError||!1}}catch(e){return Dl(e instanceof Error?e:Error(String(e)),{context:`mcp-tool-execution`}),uq.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=xR(e);if(t.rejected)return{phase:`rejected`,toolType:`mcp`,data:{},summary:t.userNote?`Rejected \u00b7 "${t.userNote}"`:`Rejected`,...t.userNote!==void 0&&{userNote:t.userNote}};try{let t=JSON.parse(e);return t.status===`error`||t.isError?{phase:`error`,toolType:`mcp`,data:t,summary:`Error`,errorMessage:typeof t.content==`string`?t.content:`MCP error`}:{phase:`success`,toolType:`mcp`,data:t,summary:`Executed successfully`}}catch{}return e.startsWith(`Error:`)?{phase:`error`,toolType:`mcp`,data:{},summary:e,errorMessage:e}:{phase:`success`,toolType:`mcp`,data:{},summary:`Executed successfully`}}};const OOe=new Set([`read`,`ls`,`grep`,`codebase_search`,`web_search`,`web_fetch`,`bash_output`,`kill_shell`,`get_diagnostics`]);function kOe(e){if(e.type!==`tool_call`)return null;let t=e.toolUseRequest.name;return OOe.has(t)?`read_search`:e.parsedResult?.data&&e.parsedResult.data.serverId?`mcp`:null}function AOe(e){if(e.type!==`tool_call`)return null;let t=e.parsedResult?.data;return t?.serverId?`${t.serverId}:${e.toolUseRequest.name}`:null}function jOe(e,t){if(t===`mcp`){let t=e[0];if(t?.type===`tool_call`){let n=t.toolUseRequest.name,r=t.parsedResult?.data?.serverId??`mcp`;return`${n} \u00d7 ${e.length} (${r})`}}let n=new Map;for(let t of e){if(t.type!==`tool_call`)continue;let e=t.toolUseRequest.name;n.set(e,(n.get(e)??0)+1)}let r=[];for(let[e,t]of n){let n=MOe(e);r.push(t>1?`${n} ${t} ${dq(e,t)}`:`${n} 1 ${dq(e,1)}`)}return r.join(`, `)}function MOe(e){switch(e){case`read`:return`read`;case`ls`:return`listed`;case`grep`:return`searched`;case`codebase_search`:return`searched`;case`web_search`:return`web searched`;case`web_fetch`:return`fetched`;case`bash_output`:return`got output from`;case`kill_shell`:return`killed`;case`get_diagnostics`:return`got diagnostics from`;default:return e}}function dq(e,t){let n=t===1?``:`s`;switch(e){case`read`:return`file${n}`;case`ls`:return`director${t===1?`y`:`ies`}`;case`grep`:return`pattern${n}`;case`codebase_search`:return`quer${t===1?`y`:`ies`}`;case`web_search`:return`quer${t===1?`y`:`ies`}`;case`web_fetch`:return`URL${n}`;case`kill_shell`:return`shell${n}`;default:return`call${n}`}}function NOe(e){let t=[],n=[],r=null,i=null;function a(){n.length!==0&&(n.length===1?t.push(n[0]):t.push({type:`tool_group`,id:crypto.randomUUID(),tools:n,category:r,summary:jOe(n,r)}),n=[],r=null,i=null)}for(let o of e){let e=kOe(o);if(e===null){a(),t.push(o);continue}let s=e===`mcp`?AOe(o):null,c=o.type===`tool_call`&&o.toolPhase===`error`;(e!==r||e===`mcp`&&s!==i)&&(a(),r=e,i=s),n.push(o),c&&a()}return a(),t}function POe(e){return e.length>1e4?!0:e.split(/\r\n|\r|\n/).length>5e3}var FOe=class{_tmpDir=null;_counter=0;_ensureDir(){if(!this._tmpDir){let e=O.join(ee.homedir(),`.abacusai`,`tmp`);c.mkdirSync(e,{recursive:!0}),this._tmpDir=c.mkdtempSync(O.join(e,`codellm-paste-`))}return this._tmpDir}savePaste(e){let t=this._ensureDir();this._counter++;let n=O.join(t,`paste-${this._counter}.txt`);return c.writeFileSync(n,e,`utf-8`),n}cleanup(){if(this._tmpDir){try{c.rmSync(this._tmpDir,{recursive:!0,force:!0})}catch{}this._tmpDir=null,this._counter=0}}};const IOe={run_in_terminal:`bash`,get_terminal_output:`bash_output`,fetch_url:`web_fetch`},LOe={bash:{id:`shellId`,isBackground:`runInBackground`},bash_output:{id:`shellId`}};function fq(e){let t=IOe[e.name];t&&(e.name=t);let n=LOe[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 pq(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)fq(e)}if(Array.isArray(e.segments))for(let t of e.segments)pq(t)}function ROe(e){for(let t of e){if(t.toolUseRequest){let e=Array.isArray(t.toolUseRequest)?t.toolUseRequest:[t.toolUseRequest];for(let t of e)fq(t)}if(Array.isArray(t.segments))for(let e of t.segments)pq(e)}}var mq=class{sessionId;_logger=dt([`codellm`,`agent`,`session`]);_workspace;_terminalService;_registry;_mcpService;_config;_conversationId=null;_mode;_model;_running=!1;_abortController=null;_initialized=!1;_uploadedDocs=new Set;_rules=[];_markdownContext=``;_rulesEngine;_toolEventBuffer=[];_messageQueue=[];_hasHiddenQueued=!1;_pasteTempFileManager=new FOe;_swapFolder=null;_setFolder=null;onAutoRestart=null;mcp;rules;constructor(e){let t=cF(oF(e.primaryWorkspace)),n=Array.from(new Set([t,...e.allowedDirectories.map(e=>cF(oF(e)))]));this._config={...e,primaryWorkspace:t,allowedDirectories:n},this.sessionId=crypto.randomUUID(),this._mode=e.mode??xd.Normal,this._model=e.model??``,this._logger.info(`Creating AgentSession (workspace={workspace}, mode={mode})`,{workspace:t,mode:this._mode}),this._workspace=new xwe(t),this._terminalService=new QDe(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.enqueue(r,{hidden:!0}),!this._running&&this.onAutoRestart&&this.onAutoRestart(r)},this._registry=NV(),e.disabledBuiltinTools?.length&&this._registry.setDisabledTools(e.disabledBuiltinTools),e.diagnosticsProvider&&this._registry.register(new TOe(e.diagnosticsProvider)),this._mcpService=new dK;let r=e.config?.get(`permissions`)??{};this._rulesEngine=new BCe({rules:{allow:[...r.allow??[],...e.permissionRules?.allow??[]],deny:[...r.deny??[],...e.permissionRules?.deny??[]],ask:[...r.ask??[],...e.permissionRules?.ask??[]]},cliAllowed:e.cliAllowedTools,cliDenied:e.cliDisallowedTools}),this.mcp=this._buildMcpManager(),this.rules=this._buildRulesManager()}async _ensureInitialized(){if(!this._initialized){if(this._initialized=!0,this._logger.debug(`Initializing session`),this._config.config){await this._config.config.load();let e=this._config.config.get(`baseUrl`);e&&(this._config.apiClient.setUrl(e),this._config.apiClient.resetEndpoints(),await this._config.apiClient.getApiEndpoint());let t=this._config.config.get(`permissions`);if(t){for(let e of t.allow??[])this._rulesEngine.addAllowRule(e);for(let e of t.deny??[])this._rulesEngine.addDenyRule(e);for(let e of t.ask??[])this._rulesEngine.addAskRule(e)}let n=this._config.config.get(`additionalDirectories`);if(n)for(let e of n){let t=cF(oF(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?cq.loadSkills(this._config.primaryWorkspace):Promise.resolve()])}}_buildMcpManager(){return{listServers:()=>this._mcpService.getConnectedServers(),addServer:async e=>{let t=this._mcpService.getConnectedServers().map(e=>e.config);return this._mcpService.initialize(this._config.primaryWorkspace,[...t,e],this._config.onMcpAuthRequired)},removeServer:async e=>{let t=this._mcpService.getConnectedServers().map(e=>e.config).filter(t=>t.id!==e);await this._mcpService.initialize(this._config.primaryWorkspace,t,this._config.onMcpAuthRequired)},callTool:(e,t,n)=>this._mcpService.callTool(e,t,n),getTools:()=>this._mcpService.getAbacusMcpTools(),refresh:async e=>{await this._mcpService.initialize(e??this._config.primaryWorkspace,this._config.mcpServers,this._config.onMcpAuthRequired)},authenticateServer:(e,t)=>this._mcpService.authenticateServer(e,t)}}_buildRulesManager(){return{getAll:()=>this._rules,getMarkdownContext:()=>this._markdownContext,reload:async()=>{this._rules=[],this._markdownContext=``}}}_buildBrowserActionDescription(e){switch(e.name){case`perform_interactive_element_action`:{let{action:t,id:n,text:r}=e.input,i=t??`interact with`,a={click:`Click`,type:`Type`,hover:`Hover`,scroll:`Scroll`,focus:`Focus`,select:`Select`}[i]??i;return i===`type`&&r&&n?`Type "${r}" into element ${n}`:i===`select`&&r&&n?`Select "${r}" in element ${n}`:n?`${a} element ${n}`:a}case`computer`:{let{action:t,coordinate:n,text:r}=e.input,i=t??``;return i===`screenshot`?`Screenshot`:i===`key`&&r?`Key: ${r}`:i===`type`&&r?`Type "${r}"`:n?`${i} at (${String(n[0])}, ${String(n[1])})`:i||`Computer action`}case`navigate_to`:return`Navigate to ${e.input.url??``}`;case`new_tab`:return`Open new tab${e.input.url?`: ${e.input.url}`:``}`;case`switch_active_tab`:return`Switch to tab ${String(e.input.id??``)}`;case`close_tab`:return`Close tab ${String(e.input.id??``)}`;case`refresh_tab`:return`Refresh tab`;case`get_tab_content`:return`Get tab content`;case`get_interactive_elements`:return`Get interactive elements`;default:return e.name}}_buildPermissionRequest(e,t){let n=this._registry.get(e.name)?.displayName??e.name;if(!MV.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=oF(e.input.filePath??``),r=cF(O.isAbsolute(t)?t:O.resolve(this._config.primaryWorkspace,t));return{type:`read_outside_directory`,tool:e,displayName:n,filePath:r,resolvedPath:r,deducedDirectory:O.dirname(r)}}case`edit`:{let r=t._prepareResult;if(r?.outsideWorkspace){let t=cF(r.resolvedPath??e.input.filePath??``);return{type:`edit_outside_directory`,tool:e,displayName:n,filePath:t,resolvedPath:t,deducedDirectory:O.dirname(t)}}if(r?.error)return{type:`edit_file`,tool:e,displayName:n,filePath:e.input.filePath??``,originalContent:``,newContent:``};let i=r?.currentContent??``,a=r?.newContent??``;return{type:`edit_file`,tool:e,displayName:n,filePath:e.input.filePath??``,originalContent:i,newContent:a}}case`write`:{let r=t._prepareResult;if(r?.outsideWorkspace){let t=cF(r.resolvedPath??e.input.filePath??``);return{type:`write_outside_directory`,tool:e,displayName:n,filePath:t,resolvedPath:t,deducedDirectory:O.dirname(t),isNewFile:!r?.fileExists}}return{type:`write_file`,tool:e,displayName:n,filePath:e.input.filePath??``,originalContent:r?.currentContent??``,content:e.input.content??``,isNewFile:!r?.fileExists}}case`bash`:{let t=e.input.command??``;return{type:`run_terminal`,tool:e,displayName:n,command:t,cwd:this._config.primaryWorkspace,background:!!(e.input.runInBackground??!1),unmatchedPatterns:this._rulesEngine.getUnmatchedBashSegments(t,this._config.primaryWorkspace)}}case`exit_plan_mode`:{let r=t._prepareResult;return{type:`exit_plan_mode`,tool:e,displayName:n,planFilePath:e.input.planFilePath??``,planContent:String(r?.planContent??``)}}case`ask_user_question`:return{type:`ask_user_question`,tool:e,displayName:n,questions:Array.isArray(e.input.questions)?e.input.questions:[]};case`navigate_to`:return{type:`browser_action`,tool:e,displayName:n,action:e.name,url:e.input.url,description:this._buildBrowserActionDescription(e)};case`computer`:case`perform_interactive_element_action`:case`switch_active_tab`:case`close_tab`:case`refresh_tab`:case`get_tab_content`:case`get_interactive_elements`:case`new_tab`:return{type:`browser_action`,tool:e,displayName:n,action:e.name,description:this._buildBrowserActionDescription(e)};case`notebook_edit`:{let r=t._prepareResult;if(r?.outsideWorkspace){let t=cF(r.resolvedPath??e.input.notebookPath??``);return{type:`notebook_edit_outside_directory`,tool:e,displayName:n,filePath:t,resolvedPath:t,deducedDirectory:O.dirname(t)}}let i=r?.notebook,a=e.input.cellId,o=e.input.editMode??`replace`,s=``;if(a&&i?.cells){let e=i.cells.find(e=>e.id===a||e.metadata?.id===a);e&&(s=Array.isArray(e.source)?e.source.join(``):String(e.source??``))}return{type:`notebook_edit`,tool:e,displayName:n,notebookPath:e.input.notebookPath??``,cellId:a,editMode:o,cellType:e.input.cellType,originalContent:s,newContent:e.input.newSource??``}}default:return{type:`generic`,tool:e,displayName:n,toolName:n,inputSummary:JSON.stringify(e.input).slice(0,200)}}}_buildExecuteTools(e){return async(t,n,r)=>{let i=new AbortController,a=()=>i.abort(`interrupted`);n&&(n.aborted?i.abort(`interrupted`):n.addEventListener(`abort`,a,{once:!0}));let o=[],s=(e,t,n)=>{let r=n?.storageContent??t;return{id:e.id,content:t,...n?.rejected&&{rejected:!0},parsedResult:r.startsWith(`Error:`)?{phase:`error`,toolType:e.name,data:{},summary:r,errorMessage:r}:this._registry.parse(e.name,r)}};try{let a=async t=>{if(i.signal.aborted)return{resolved:!0,result:s(t,JSON.stringify({reason:bR.INTERRUPTED}),{rejected:!0})};let a={workspace:this._workspace,terminalService:this._terminalService,apiClient:this._config.apiClient,workspacePath:this._config.primaryWorkspace,conversationId:e,agentMode:this._mode,toolCallId:t.id,status:`executing`,uploadedDocs:this._uploadedDocs,allowEditingPaths:this._config.allowedDirectories,abortController:i,permissionProvider:this._config.permissionProvider,rulesEngine:this._rulesEngine,getAgentMode:()=>this._mode,setAgentMode:e=>{this._mode=e},mcpService:{listAllToolDefinitions:async()=>this._mcpService.getAbacusMcpTools(),callTool:(e,t,n)=>this._mcpService.callTool(e,t,n),reloadConnections:async()=>{await this._mcpService.initialize(this._config.primaryWorkspace,this._config.mcpServers,this._config.onMcpAuthRequired)},getServerStatus:e=>{let t=this._mcpService.getConnectedServers().find(t=>t.config.id===e);return t?t.status===`connected`?`running`:`error`:`stopped`}},...this._rules.length>0&&{rules:this._rules},...this._config.planDirectory!==void 0&&{plansDir:this._config.planDirectory},...this._config.clientType&&{clientType:this._config.clientType},...r&&{emitEvent:r},...r&&{onOutputUpdate:(e,t)=>{r({type:`tool_output_update`,toolCallId:e,output:t})}}};try{if(this._registry.isDisabled(t.name))return{resolved:!0,result:s(t,`Error: tool '${t.name}' is disabled in this environment`)};r?.({type:`tool_execution_start`,tool:t});let e=this._registry.createToolInstance(t.name,t.input??{},a);if(await e.prepare(),t.name===`edit`&&MV.isBuiltinRequest(t)&&!e._prepareResult?.error){let n=e._prepareResult,i=a.workspacePath,o=a.plansDir??O.join(te(),hn.configDirName,`plans`),s=uF(O.resolve(i,t.input.filePath??``),O.resolve(i,o)),c={originalContent:n?.currentContent??``,newContent:n?.newContent??``,isPlanFile:s,isNewFile:!(n?.fileExists??!0)},l={type:`tool_display_data`,toolCallId:t.id,data:c};r?.(l),this._toolEventBuffer.push(l)}if(t.name===`notebook_edit`&&MV.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`&&MV.isBuiltinRequest(t)&&!e._prepareResult?.error){let n=e._prepareResult,i={originalContent:n?.currentContent??``,newContent:t.input.content??``,isNewFile:!(n?.fileExists??!0)},a={type:`tool_display_data`,toolCallId:t.id,data:i};r?.(a),this._toolEventBuffer.push(a)}let i=this._mode===xd.Yolo&&t.name!==`ask_user_question`;if(!i&&e.needsPermission()){let i=this._registry.get(t.name)?.displayName??t.name,o=VV(t),c=this._rulesEngine.evaluate(i,o);if(c===`deny`)return{resolved:!0,result:s(t,JSON.stringify({reason:bR.REJECTED}),{rejected:!0})};if(c!==`allow`){let i=this._buildPermissionRequest(t,e);if(this._config.permissionProvider.needsPermission(i)){let o={type:`status_changed`,status:Sd.WaitingForToolPermission};r?.(o),this._toolEventBuffer.push(o);let c;try{let e=this._config.permissionProvider.requestPermission(i);if(n){let t,r=new Promise((e,r)=>{n.aborted?r(Error(`interrupted`)):(t=()=>r(Error(`interrupted`)),n.addEventListener(`abort`,t,{once:!0}))});try{c=await Promise.race([e,r])}finally{t&&n.removeEventListener(`abort`,t)}}else c=await e}catch{return{resolved:!0,result:s(t,JSON.stringify({reason:bR.INTERRUPTED}),{rejected:!0})}}if(r?.({type:`status_changed`,status:Sd.ExecutingTool}),this._toolEventBuffer.push({type:`status_changed`,status:Sd.ExecutingTool}),c===`reject`)return{resolved:!0,result:s(t,JSON.stringify({reason:bR.REJECTED}),{rejected:!0})};if(typeof c==`object`&&c.type===`reject_with_message`)return{resolved:!0,result:s(t,JSON.stringify({reason:bR.USER_MESSAGE,message:c.message}),{rejected:!0})};if(c===`allowAlways`||c===`allowYolo`||c===`accept`){if(c===`allowAlways`&&(i.type===`read_outside_directory`||i.type===`write_outside_directory`||i.type===`edit_outside_directory`||i.type===`notebook_edit_outside_directory`)){if(this.addAllowedDirectory(i.deducedDirectory),this._config.config){let e=this._config.config.get(`additionalDirectories`)??[];e.includes(i.deducedDirectory)||this._config.config.set(`additionalDirectories`,[...e,i.deducedDirectory],`local`)}}else if(t.name===`exit_plan_mode`){let e=c===`allowYolo`?xd.Yolo:c===`allowAlways`?xd.AcceptEdits:xd.Normal;this._mode=e,a.agentMode=e,r?.({type:`mode_changed`,mode:e}),this._toolEventBuffer.push({type:`mode_changed`,mode:e})}else if(c===`allowAlways`){let e=Dd(i.type);this._mode=e,a.agentMode=e,r?.({type:`mode_changed`,mode:e}),this._toolEventBuffer.push({type:`mode_changed`,mode:e})}}if(typeof c==`object`&&c.type===`accept_with_message`&&this._messageQueue.push({message:c.message,hidden:!1}),typeof c==`object`&&c.type===`question_answers`&&e.mergeParams({answers:c.answers}),typeof c==`object`&&c.type===`allow_always_with_rule`&&(this._rulesEngine.addAllowRule(c.rule),this._config.config)){let e=this._config.config.get(`permissions`)??{},t=[...e.allow??[],c.rule];this._config.config.set(`permissions`,{...e,allow:t},`local`)}if(typeof c==`object`&&c.type===`allow_always_with_rules`){for(let e of c.rules)this._rulesEngine.addAllowRule(e);if(this._config.config){let e=this._config.config.get(`permissions`)??{},t=[...e.allow??[],...c.rules];this._config.config.set(`permissions`,{...e,allow:t},`local`)}}}}}return t.name===`enter_plan_mode`&&(this._mode=xd.PlanMode,a.agentMode=xd.PlanMode,r?.({type:`mode_changed`,mode:xd.PlanMode}),this._toolEventBuffer.push({type:`mode_changed`,mode:xd.PlanMode})),t.name===`exit_plan_mode`&&i&&(this._mode=xd.Normal,a.agentMode=xd.Normal,r?.({type:`mode_changed`,mode:xd.Normal}),this._toolEventBuffer.push({type:`mode_changed`,mode:xd.Normal})),{resolved:!1,call:t,instance:e,ctx:a}}catch(e){return i.signal.aborted?{resolved:!0,result:s(t,JSON.stringify({reason:bR.INTERRUPTED}),{rejected:!0})}:{resolved:!0,result:s(t,`Error: ${e instanceof Error?e.message:String(e)}`)}}},c=async e=>{try{if(await e.instance.execute(),i.signal.aborted)return s(e.call,JSON.stringify({reason:bR.INTERRUPTED}),{rejected:!0});let t=e.instance.formatResultForLLM(),n=e.instance.formatResult(),r=typeof t==`string`?t:JSON.stringify(t);return s(e.call,r,{storageContent:n===r?void 0:n})}catch(t){if(i.signal.aborted)return s(e.call,JSON.stringify({reason:bR.INTERRUPTED}),{rejected:!0});let n=t instanceof Error?t.message:String(t);return s(e.call,`Error: ${n}`)}},l=0,u=!1;for(;l<t.length;){let e=e=>this._registry.get(e.name)?.concurrency(e.input,this._config.primaryWorkspace)??!1;if(u){let n=t[l],i=!!e(n),a=this._registry.get(n.name),c=a?!a.isReadonly:!1;if(i||c){let e=s(n,CR);o.push(e),r?.({type:`tool_execution_complete`,tool:n,result:e}),l++;continue}}if(e(t[l])){let n=l+1;for(;n<t.length&&e(t[n]);)n++;if(n-l>1){let i=t.slice(l,n),d=i.map(e);l=n;let f=[[]],p=[new Set];for(let e=0;e<i.length;e++){let t=d[e],n=f[f.length-1],r=p[p.length-1];typeof t==`string`&&r.has(t)&&(f.push([]),p.push(new Set),n=f[f.length-1],r=p[p.length-1]),typeof t==`string`&&r.add(t),n.push(e)}let m=new Map,h=new Map,g=!1;for(let e of f){if(g){for(let t of e){let e=s(i[t],CR);o.push(e),r?.({type:`tool_execution_complete`,tool:i[t],result:e})}continue}for(let t of e)m.set(t,await a(i[t]));for(let t of e){let e=m.get(t);e.resolved&&r?.({type:`tool_execution_complete`,tool:i[t],result:e.result})}let t=e.filter(e=>!m.get(e).resolved).map(async e=>{let t=m.get(e);if(!t.resolved){let n=await c(t);h.set(e,n),r?.({type:`tool_execution_complete`,tool:i[e],result:n})}});for(let e=0;e<t.length;e+=10)await Promise.all(t.slice(e,e+10));for(let t of e){let e=m.get(t),n=e.resolved?e.result:h.get(t);o.push(n),!g&&!n.rejected&&n.content.startsWith(`Error:`)&&(g=!0)}}g&&(u=!0);continue}}let n=t[l];l++;let i=await a(n);if(i.resolved){o.push(i.result),r?.({type:`tool_execution_complete`,tool:n,result:i.result});continue}let d=await c(i);o.push(d),r?.({type:`tool_execution_complete`,tool:n,result:d})}return o}finally{n&&n.removeEventListener(`abort`,a)}}}async createConversation(){let e=await this._config.apiClient.createCodellmDeploymentConversation(`CODE_LLM_AGENT`,this._config.clientType);if(e?.success===!1&&e.error)throw Error(e.error);let t=e?.result?.deploymentConversationId;if(!t)throw Error(`Failed to create conversation: no deployment conversation ID returned`);return this._conversationId=t,t}async loadConversation(e){this._conversationId=e;let t=await this._config.apiClient.getDeploymentConversation({deploymentConversationId:e}),n=t?.result?.history??[],r=t?.result?.name??void 0;ROe(n);let i=NOe(this._hydrateHistory(n));return{...r!==void 0&&{title:r},segments:i}}switchConversation(e){return this._conversationId=e,this._uploadedDocs.clear(),Promise.resolve()}resetConversation(){this._conversationId=null,this._uploadedDocs.clear()}async deleteConversation(e){await this._config.apiClient.deleteDeploymentConversation?.({deploymentConversationId:e}),this._conversationId===e&&(this._conversationId=null)}async listConversations(){return((await this._config.apiClient.getConversationsList(`CODE_LLM_AGENT`))?.result??[]).map(e=>({id:e.deploymentConversationId??``,createdAt:new Date(e.createdAt??Date.now()),updatedAt:new Date(e.lastEventCreatedAt??e.createdAt??Date.now()),...e.name!==void 0&&{title:e.name}}))}_hydrateHistory(e){let t=[],n=[];for(let r of e){if(r.role===`USER`){let e=this._extractParallelToolResponses(r);e.length>0&&this._attachToolResults(n,e),n=[];let i=(r.prompt??r.text??``).trim();i&&t.push({type:`text`,id:crypto.randomUUID(),source:`user`,content:i});continue}n=[];for(let e of r.segments??[]){if(e.isThoughts){let n=typeof e.segment==`string`?e.segment:e.segment?.segment??``;t.push({type:`thinking`,id:crypto.randomUUID(),content:n,isSpinny:!1});continue}if(e.type===`code_llm_agent_tool_request`&&e.toolUseRequest){let r=Array.isArray(e.toolUseRequest)?e.toolUseRequest:[e.toolUseRequest];for(let e of r){let r={type:`tool_call`,id:crypto.randomUUID(),toolUseRequest:e,toolPhase:`unknown`};t.push(r),n.push(r)}continue}if(e.type===`code_llm_notification`){t.push({type:`notification`,id:crypto.randomUUID(),message:e.message??(typeof e.segment==`string`?e.segment:``)??``,severity:e.severity??`info`,...e.actions!==void 0&&{actions:e.actions}});continue}let r=typeof e.segment==`string`?e.segment:e.segment?.segment;r&&t.push({type:`text`,id:crypto.randomUUID(),source:`bot`,content:r})}}return this._detectAbandonedTools(t),t}_extractParallelToolResponses(e){if(Array.isArray(e.parallelToolResponses))return e.parallelToolResponses;for(let t of e.segments??[])if(Array.isArray(t.parallelToolResponses)&&t.parallelToolResponses.length>0)return t.parallelToolResponses;return[]}_attachToolResults(e,t){for(let n=0;n<Math.min(e.length,t.length);n++){let r=e[n],i=t[n],a=r.toolUseRequest.name,o=xR(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?`}}}}_rewriteLargePastedContent(e){return POe(e)?`The large pasted content is in ${this._pasteTempFileManager.savePaste(e)} file.`:e}async*send(e,t){if(await this._ensureInitialized(),this._logger.info(`Sending message (conversationId={conversationId}, mode={mode}, model={model})`,{conversationId:this._conversationId,mode:this._mode,model:this._model}),!this._conversationId)for(let e=0;e<8;e++)try{await this.createConversation();break}catch(t){if(!Vl(t)||e>=7)throw t;let n=Math.min((e+1)*2e3,1e4);yield{type:`retry`,attempt:e+1,maxAttempts:8,delayMs:n,isNetworkError:!0},await VR(n)}this._running=!0,this._abortController=new AbortController;let n=this._buildExecuteTools(this._conversationId);try{yield{type:`status_changed`,status:Sd.Submitted};let r=this._rewriteLargePastedContent(e),i=!0;for(;;){let e=this._mcpService.getAbacusMcpTools();e.length>0&&this._registry.registerMCPTools(e.map(e=>new DOe(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:zR().map(e=>({name:e})),...e.length>0&&{mcpTools:e},...this._rules.length>0&&{rules:this._rules},...this._config.enableSkills&&(()=>{let e=cq.getAllMetadata();return e.length>0?{availableSkills:e}:{}})(),...this._config.enableSkills&&t?.activeSkills&&t.activeSkills.length>0&&{activeSkills:t.activeSkills},...this._config.isPrintMode!==void 0&&{isPrintMode:this._config.isPrintMode},...this._config.enablePromptRewrite!==void 0&&{enablePromptRewrite:this._config.enablePromptRewrite},...this._config.supportsThoughtStreaming!==void 0&&{supportsThoughtStreaming:this._config.supportsThoughtStreaming},agentMode:this._mode,...this._config.config?.get(`client`)&&{client:this._config.config.get(`client`)},...this._config.maxTurns!==void 0&&{maxTurns:this._config.maxTurns},...i&&t?.diagnosticIssues!==void 0&&{diagnosticIssues:t.diagnosticIssues},...i&&t?.currentFile!==void 0&&{currentFile:O.isAbsolute(t.currentFile)?t.currentFile:O.resolve(this._config.primaryWorkspace,t.currentFile)},...i&&t?.selectionStartLine!==void 0&&{selectionStartLine:t.selectionStartLine},...i&&t?.selectionEndLine!==void 0&&{selectionEndLine:t.selectionEndLine},executeTools:n,getConcurrency:e=>this._registry.get(e.name)?.concurrency(e.input,this._config.primaryWorkspace)??!1,drainEvents:()=>{let e=this._toolEventBuffer.slice();return this._toolEventBuffer.length=0,e},getQueuedMessage:()=>{if(this._messageQueue.length===0)return null;let e=this._messageQueue.map(e=>this._rewriteLargePastedContent(e.message)).join(`
75080
- `);return this._hasHiddenQueued=this._messageQueue.every(e=>e.hidden),e},isQueuedMessageHidden:()=>this._hasHiddenQueued,clearQueuedMessage:()=>{this._messageQueue.length=0}};this._swapFolder=null,this._setFolder=null;let c=KR(s,r,this._abortController.signal),l=!1,u;for(;!(u=await c.next()).done;){let e=u.value;e.type===`text_delta`&&!l?(l=!0,yield{type:`status_changed`,status:Sd.Streaming}):e.type===`tool_requested`&&(yield{type:`status_changed`,status:Sd.ExecutingTool}),yield e,e.type===`mode_changed`&&(this._mode=e.mode)}if(i=!1,this._messageQueue.length===0||this._abortController.signal.aborted)break;let d=this._messageQueue.every(e=>e.hidden);r=this._messageQueue.map(e=>this._rewriteLargePastedContent(e.message)).join(`
75081
- `),this._messageQueue.length=0,d||(yield{type:`user_message_dequeued`,content:r})}}finally{this._running=!1,this._abortController=null,this._toolEventBuffer.length=0,this._uploadedDocs.clear(),this._pasteTempFileManager.cleanup(),this._logger.debug(`Send completed, session idle`),yield{type:`status_changed`,status:Sd.Idle}}}stop(){this._abortController?.abort()}dispose(){this._abortController?.abort(),this._pasteTempFileManager.cleanup(),this._terminalService.dispose()}enqueue(e,t){this._messageQueue.push({message:e,hidden:t?.hidden??!1})}getQueue(){return this._messageQueue.map(e=>e.message)}dequeue(){let e=this._messageQueue.shift();return e?e.message:null}clearQueue(){this._messageQueue.length=0}removeAt(e){this._messageQueue.splice(e,1)}addUploadedDoc(e){this._uploadedDocs.add(e)}clearUploadedDocs(){this._uploadedDocs.clear()}isDirectoryAllowed(e){let t=cF(oF(e));for(let e of this._config.allowedDirectories)if(uF(t,e))return{allowed:!0,coveredBy:e};return{allowed:!1}}addAllowedDirectory(e,t){let n=cF(oF(e));for(let e of this._config.allowedDirectories)if(uF(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=cF(oF(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)}},zOe=class{needsPermission(e){return!1}async requestPermission(e){return`accept`}},hq=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)}},BOe=class{async read(){let e={},t=hn.envPrefix,n=hn.internalEnvPrefix,r=process.env[`${t}BASE_URL`],i=process.env[`${t}MODEL`],a=process.env[`${n}LOG_LEVEL`],o=process.env[`${t}MAX_TURNS`],s=process.env[`${t}AUTO_UPDATE`],c=process.env[`${n}CHANNEL`];if(r&&(e.baseUrl=r),i&&(e.model=i),a&&(e.logLevel=a),o&&(e.maxTurns=parseInt(o,10)),c&&(e.updateChannel=c),s!==void 0){let t=MR.safeParse(s);t.success&&t.data!==void 0&&(e.autoUpdate=t.data)}return e}},VOe=class{configPath;constructor(){this.configPath=O.join(te(),hn.configDirName,hn.configFileName)}async read(){try{let e=await m.readFile(this.configPath,`utf-8`);return JSON.parse(e)}catch{return{}}}async write(e){let t=O.dirname(this.configPath);await m.mkdir(t,{recursive:!0}),await m.writeFile(this.configPath,JSON.stringify(e,null,2),`utf-8`)}},HOe=class{configPath;constructor(e){this.configPath=O.join(e,hn.localConfigDirName,hn.configFileName)}async read(){try{let e=await m.readFile(this.configPath,`utf-8`);return JSON.parse(e)}catch{return{}}}async write(e){let t=O.dirname(this.configPath);await m.mkdir(t,{recursive:!0}),await m.writeFile(this.configPath,JSON.stringify(e,null,2),`utf-8`)}};const UOe=dt([`codellm`,`agent`,`config`]);function gq(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]=gq(n[t],r):n[t]=r)}return n}const _q={allowedDirectories:[],primaryWorkspace:``,logLevel:`info`};var vq=class{sources;cache=null;constructor(e){this.sources=[new VOe,new HOe(e.cwd),...e.extraSources??[],new BOe]}async load(){let e={..._q};for(let t of this.sources){let n=await t.read();e=gq(e,n)}this.cache=e,UOe.info`config loaded from ${this.sources.length} sources`}get(e){return this.cache?this.cache[e]??_q[e]:_q[e]}getAll(){return this.cache??_q}async set(e,t,n=`global`){let r=n===`global`?this.sources[0]:this.sources[1];if(r?.write){let n=await r.read();await r.write({...n,[e]:t})}this.cache&&(this.cache[e]=t)}};dt([`codellm`,`agent`,`history`]);var yq=class{source;maxEntries;filePath;entries=[];navIndex=-1;loaded=!1;writeQueue=Promise.resolve();constructor(e,t){this.source=e,this.maxEntries=t?.maxEntries??1e4,this.filePath=t?.filePath??A(te(),hn.configDirName,`history.jsonl`)}async load(){if(!this.loaded){this.loaded=!0;try{let e=this.maxEntries*2048,t=await De(this.filePath,`r`);try{let{size:n}=await t.stat(),r=Math.max(0,n-e),i=Buffer.allocUnsafe(n-r);await t.read(i,0,i.length,r);let a=i.toString(`utf-8`),o=r===0?0:a.indexOf(`
75079
+ `,e)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:return this.flowScalar(this.type);case`block-scalar-header`:return{type:`block-scalar`,offset:this.offset,indent:this.indent,props:[this.sourceToken],source:``};case`flow-map-start`:case`flow-seq-start`:return{type:`flow-collection`,offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case`seq-item-ind`:return{type:`block-seq`,offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case`explicit-key-ind`:{this.onKeyLine=!0;let t=c(s(e));return t.push(this.sourceToken),{type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:t,explicitKey:!0}]}}case`map-value-ind`:{this.onKeyLine=!0;let t=c(s(e));return{type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:t,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){return this.type!==`comment`||this.indent<=t?!1:e.every(e=>e.type===`newline`||e.type===`space`)}*documentEnd(e){this.type!==`doc-mode`&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type===`newline`&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case`comma`:case`doc-start`:case`doc-end`:case`flow-seq-end`:case`flow-map-end`:case`map-value-ind`:yield*this.pop(),yield*this.step();break;case`newline`:this.onKeyLine=!1;default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type===`newline`&&(yield*this.pop())}}}})),bOe=G((e=>{var t=rq(),n=JK(),r=YK(),i=DK(),a=pK(),o=oq(),s=sq();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})),xOe=G((e=>{var t=rq(),n=JK(),r=qK(),i=YK(),a=bK(),o=pK(),s=AK(),c=xK(),l=MK(),u=PK();iq();var d=aq(),f=oq(),p=sq(),m=bOe(),h=mK();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 SOe(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,xOe.parse)(i);return e&&typeof e==`object`&&!Array.isArray(e)?{data:e,body:a}:{data:{},body:a}}catch{return{data:{},body:e}}}function COe(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``)}const wOe=dt([`codellm`,`agent`,`skills`]),cq=new class{skills=new Map;async loadSkills(e){let t=await pCe(),n=O.join(ee.homedir(),hn.configDirName,`skills`),r=e?O.join(e,hn.localConfigDirName,`skills`):void 0,i=await this.discoverSkills(t,`builtin`),a=await this.discoverSkills(n,`global`),o=r?await this.discoverSkills(r,`project`):[];this.skills.clear();for(let e of i)this.skills.set(e.id,e);for(let e of a)this.skills.set(e.id,e);for(let e of o)this.skills.set(e.id,e);wOe.info`skills loaded: builtin=${i.length} global=${a.length} project=${o.length}`}async discoverSkills(e,t){let n=[],r;try{r=await Te.readdir(e,{withFileTypes:!0})}catch{return n}r.sort((e,t)=>e.name.localeCompare(t.name));for(let i of r)if(i.isFile()&&i.name.endsWith(`.md`)){let r=O.join(e,i.name),a=await this.parseSkillFile(r,!1,t);a&&n.push(a)}else if(i.isDirectory()){let r=O.join(e,i.name,`SKILL.md`);try{await Te.access(r);let e=await this.parseSkillFile(r,!0,t);e&&n.push(e)}catch{}}return n}async parseSkillFile(e,t,n){try{let{data:r}=SOe(await Te.readFile(e,`utf-8`)),i=COe(t?O.basename(O.dirname(e)):O.basename(e,`.md`));return i?this.buildSkill(i,r,e,t,n):null}catch{return null}}buildSkill(e,t,n,r,i){let a=t.name,o=t.description,s=typeof a==`string`&&a.trim()?a.trim():e,c=typeof o==`string`&&o.trim()?o.trim():void 0;if(!c)return null;let l={name:s,description:c};typeof t[`argument-hint`]==`string`&&(l[`argument-hint`]=t[`argument-hint`]),typeof t[`disable-model-invocation`]==`boolean`&&(l[`disable-model-invocation`]=t[`disable-model-invocation`]),typeof t[`user-invocable`]==`boolean`&&(l[`user-invocable`]=t[`user-invocable`]),Array.isArray(t[`allowed-tools`])&&(l[`allowed-tools`]=t[`allowed-tools`].filter(e=>typeof e==`string`)),typeof t.license==`string`&&(l.license=t.license),typeof t.compatibility==`string`&&(l.compatibility=t.compatibility);let u=t.metadata;if(u&&typeof u==`object`&&!Array.isArray(u)){let e={};for(let[t,n]of Object.entries(u))typeof n==`string`&&(e[t]=n);Object.keys(e).length>0&&(l.metadata=e)}return{id:e,frontmatter:l,path:n,isDirectory:r,source:i}}get(e){return this.skills.get(e)}getAll(){return Array.from(this.skills.values()).filter(e=>e.frontmatter[`user-invocable`]!==!1)}getAllMetadata(){return this.getAll().map(e=>({id:e.id,name:e.frontmatter.name,description:e.frontmatter.description,location:e.path}))}search(e){let t=e.toLowerCase();return this.getAll().filter(e=>e.id.toLowerCase().includes(t)||e.frontmatter.name.toLowerCase().includes(t)||e.frontmatter.description.toLowerCase().includes(t))}matchSkill(e){if(!e.startsWith(`/`))return null;let t=e.slice(1).split(/\s+/);if(t.length===0)return null;let[n,...r]=t;if(!n)return null;let i=this.skills.get(n);return!i||i.frontmatter[`user-invocable`]===!1?null:{skill:i,args:r.join(` `)}}},lq=dt([`codellm`,`agent`,`tools`,`diagnostics`]);var TOe=class e extends pV{name=`get_diagnostics`;displayName=`GetDiagnostics`;description=`Get IDE diagnostics (errors, warnings, info) for a file or all open files.`;_provider;static Parameters=QL({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;lq.debug`Getting diagnostics${e.uri?` for ${e.uri}`:` for all files`}`;let r=await this._provider.getDiagnostics(n);return lq.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=xR(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`}}}},EOe=class extends wR{includeInApiDefinitions=!1};const uq=dt([`codellm`,`agent`,`tools`,`mcp`]);var DOe=class extends EOe{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 QL(r)}jsonSchemaToZod(e){switch(e.type){case`string`:return e.enum?sR(e.enum):Y();case`number`:case`integer`:return nxe;case`boolean`:return jR;case`array`:return e.items?XL(this.jsonSchemaToZod(e.items)):XL(JL());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 QL(t)}return aR(Y(),JL());case`null`:return qL();default:return e.oneOf?this.jsonSchemaToZod(e.oneOf[0]):JL()}}async execute(e,t){if(uq.debug`Executing MCP tool: ${this.name} (server=${this.mcpToolDefinition.serverId})`,!t.mcpService)return uq.warn`MCP service not available for tool: ${this.name}`,{type:`mcp`,serverId:this.mcpToolDefinition.serverId,toolName:this.name,content:`MCP service not available`,isError:!0};try{let n=(await t.mcpService.listAllToolDefinitions()).find(e=>e.name===this.name);if(!n)throw Error(`MCP tool '${this.name}' not found`);let r=await t.mcpService.callTool(n.serverId,n.originalName||this.name,e);return{type:`mcp`,serverId:n.serverId,toolName:this.name,content:r.content||r,isError:r.isError||!1}}catch(e){return Dl(e instanceof Error?e:Error(String(e)),{context:`mcp-tool-execution`}),uq.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=xR(e);if(t.rejected)return{phase:`rejected`,toolType:`mcp`,data:{},summary:t.userNote?`Rejected \u00b7 "${t.userNote}"`:`Rejected`,...t.userNote!==void 0&&{userNote:t.userNote}};try{let t=JSON.parse(e);return t.status===`error`||t.isError?{phase:`error`,toolType:`mcp`,data:t,summary:`Error`,errorMessage:typeof t.content==`string`?t.content:`MCP error`}:{phase:`success`,toolType:`mcp`,data:t,summary:`Executed successfully`}}catch{}return e.startsWith(`Error:`)?{phase:`error`,toolType:`mcp`,data:{},summary:e,errorMessage:e}:{phase:`success`,toolType:`mcp`,data:{},summary:`Executed successfully`}}};const OOe=new Set([`read`,`ls`,`grep`,`codebase_search`,`web_search`,`web_fetch`,`bash_output`,`kill_shell`,`get_diagnostics`]);function kOe(e){if(e.type!==`tool_call`)return null;let t=e.toolUseRequest.name;return OOe.has(t)?`read_search`:e.parsedResult?.data&&e.parsedResult.data.serverId?`mcp`:null}function AOe(e){if(e.type!==`tool_call`)return null;let t=e.parsedResult?.data;return t?.serverId?`${t.serverId}:${e.toolUseRequest.name}`:null}function jOe(e,t){if(t===`mcp`){let t=e[0];if(t?.type===`tool_call`){let n=t.toolUseRequest.name,r=t.parsedResult?.data?.serverId??`mcp`;return`${n} \u00d7 ${e.length} (${r})`}}let n=new Map;for(let t of e){if(t.type!==`tool_call`)continue;let e=t.toolUseRequest.name;n.set(e,(n.get(e)??0)+1)}let r=[];for(let[e,t]of n){let n=MOe(e);r.push(t>1?`${n} ${t} ${dq(e,t)}`:`${n} 1 ${dq(e,1)}`)}return r.join(`, `)}function MOe(e){switch(e){case`read`:return`read`;case`ls`:return`listed`;case`grep`:return`searched`;case`codebase_search`:return`searched`;case`web_search`:return`web searched`;case`web_fetch`:return`fetched`;case`bash_output`:return`got output from`;case`kill_shell`:return`killed`;case`get_diagnostics`:return`got diagnostics from`;default:return e}}function dq(e,t){let n=t===1?``:`s`;switch(e){case`read`:return`file${n}`;case`ls`:return`director${t===1?`y`:`ies`}`;case`grep`:return`pattern${n}`;case`codebase_search`:return`quer${t===1?`y`:`ies`}`;case`web_search`:return`quer${t===1?`y`:`ies`}`;case`web_fetch`:return`URL${n}`;case`kill_shell`:return`shell${n}`;default:return`call${n}`}}function NOe(e){let t=[],n=[],r=null,i=null;function a(){n.length!==0&&(n.length===1?t.push(n[0]):t.push({type:`tool_group`,id:crypto.randomUUID(),tools:n,category:r,summary:jOe(n,r)}),n=[],r=null,i=null)}for(let o of e){let e=kOe(o);if(e===null){a(),t.push(o);continue}let s=e===`mcp`?AOe(o):null,c=o.type===`tool_call`&&o.toolPhase===`error`;(e!==r||e===`mcp`&&s!==i)&&(a(),r=e,i=s),n.push(o),c&&a()}return a(),t}function POe(e){return e.length>1e4?!0:e.split(/\r\n|\r|\n/).length>5e3}var FOe=class{_tmpDir=null;_counter=0;_ensureDir(){if(!this._tmpDir){let e=O.join(ee.homedir(),hn.configDirName,`tmp`);c.mkdirSync(e,{recursive:!0}),this._tmpDir=c.mkdtempSync(O.join(e,`codellm-prompt-`))}return this._tmpDir}savePrompt(e){let t=this._ensureDir();this._counter++;let n=O.join(t,`prompt-${this._counter}.txt`);return c.writeFileSync(n,e,`utf-8`),n}cleanup(){if(this._tmpDir){try{c.rmSync(this._tmpDir,{recursive:!0,force:!0})}catch{}this._tmpDir=null,this._counter=0}}};const IOe={run_in_terminal:`bash`,get_terminal_output:`bash_output`,fetch_url:`web_fetch`},LOe={bash:{id:`shellId`,isBackground:`runInBackground`},bash_output:{id:`shellId`}};function fq(e){let t=IOe[e.name];t&&(e.name=t);let n=LOe[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 pq(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)fq(e)}if(Array.isArray(e.segments))for(let t of e.segments)pq(t)}function ROe(e){for(let t of e){if(t.toolUseRequest){let e=Array.isArray(t.toolUseRequest)?t.toolUseRequest:[t.toolUseRequest];for(let t of e)fq(t)}if(Array.isArray(t.segments))for(let e of t.segments)pq(e)}}var mq=class{sessionId;_logger=dt([`codellm`,`agent`,`session`]);_workspace;_terminalService;_registry;_mcpService;_config;_conversationId=null;_mode;_model;_running=!1;_abortController=null;_initialized=!1;_uploadedDocs=new Set;_rules=[];_markdownContext=``;_rulesEngine;_toolEventBuffer=[];_messageQueue=[];_promptFileManager=new FOe;_swapFolder=null;_setFolder=null;onAutoRestart=null;mcp;rules;constructor(e){let t=cF(oF(e.primaryWorkspace)),n=Array.from(new Set([t,...e.allowedDirectories.map(e=>cF(oF(e)))]));this._config={...e,primaryWorkspace:t,allowedDirectories:n},this.sessionId=crypto.randomUUID(),this._mode=e.mode??xd.Normal,this._model=e.model??``,this._logger.info(`Creating AgentSession (workspace={workspace}, mode={mode})`,{workspace:t,mode:this._mode}),this._workspace=new xwe(t),this._terminalService=new QDe(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=NV(),e.disabledBuiltinTools?.length&&this._registry.setDisabledTools(e.disabledBuiltinTools),e.diagnosticsProvider&&this._registry.register(new TOe(e.diagnosticsProvider)),this._mcpService=new dK;let r=e.config?.get(`permissions`)??{};this._rulesEngine=new BCe({rules:{allow:[...r.allow??[],...e.permissionRules?.allow??[]],deny:[...r.deny??[],...e.permissionRules?.deny??[]],ask:[...r.ask??[],...e.permissionRules?.ask??[]]},cliAllowed:e.cliAllowedTools,cliDenied:e.cliDisallowedTools}),this.mcp=this._buildMcpManager(),this.rules=this._buildRulesManager()}async _ensureInitialized(){if(!this._initialized){if(this._initialized=!0,this._logger.debug(`Initializing session`),this._config.config){await this._config.config.load();let e=this._config.config.get(`baseUrl`);e&&(this._config.apiClient.setUrl(e),this._config.apiClient.resetEndpoints(),await this._config.apiClient.getApiEndpoint());let t=this._config.config.get(`permissions`);if(t){for(let e of t.allow??[])this._rulesEngine.addAllowRule(e);for(let e of t.deny??[])this._rulesEngine.addDenyRule(e);for(let e of t.ask??[])this._rulesEngine.addAskRule(e)}let n=this._config.config.get(`additionalDirectories`);if(n)for(let e of n){let t=cF(oF(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?cq.loadSkills(this._config.primaryWorkspace):Promise.resolve()])}}_buildMcpManager(){return{listServers:()=>this._mcpService.getConnectedServers(),addServer:async e=>{let t=this._mcpService.getConnectedServers().map(e=>e.config);return this._mcpService.initialize(this._config.primaryWorkspace,[...t,e],this._config.onMcpAuthRequired)},removeServer:async e=>{let t=this._mcpService.getConnectedServers().map(e=>e.config).filter(t=>t.id!==e);await this._mcpService.initialize(this._config.primaryWorkspace,t,this._config.onMcpAuthRequired)},callTool:(e,t,n)=>this._mcpService.callTool(e,t,n),getTools:()=>this._mcpService.getAbacusMcpTools(),refresh:async e=>{await this._mcpService.initialize(e??this._config.primaryWorkspace,this._config.mcpServers,this._config.onMcpAuthRequired)},authenticateServer:(e,t)=>this._mcpService.authenticateServer(e,t)}}_buildRulesManager(){return{getAll:()=>this._rules,getMarkdownContext:()=>this._markdownContext,reload:async()=>{this._rules=[],this._markdownContext=``}}}_buildBrowserActionDescription(e){switch(e.name){case`perform_interactive_element_action`:{let{action:t,id:n,text:r}=e.input,i=t??`interact with`,a={click:`Click`,type:`Type`,hover:`Hover`,scroll:`Scroll`,focus:`Focus`,select:`Select`}[i]??i;return i===`type`&&r&&n?`Type "${r}" into element ${n}`:i===`select`&&r&&n?`Select "${r}" in element ${n}`:n?`${a} element ${n}`:a}case`computer`:{let{action:t,coordinate:n,text:r}=e.input,i=t??``;return i===`screenshot`?`Screenshot`:i===`key`&&r?`Key: ${r}`:i===`type`&&r?`Type "${r}"`:n?`${i} at (${String(n[0])}, ${String(n[1])})`:i||`Computer action`}case`navigate_to`:return`Navigate to ${e.input.url??``}`;case`new_tab`:return`Open new tab${e.input.url?`: ${e.input.url}`:``}`;case`switch_active_tab`:return`Switch to tab ${String(e.input.id??``)}`;case`close_tab`:return`Close tab ${String(e.input.id??``)}`;case`refresh_tab`:return`Refresh tab`;case`get_tab_content`:return`Get tab content`;case`get_interactive_elements`:return`Get interactive elements`;default:return e.name}}_buildPermissionRequest(e,t){let n=this._registry.get(e.name)?.displayName??e.name;if(!MV.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=oF(e.input.filePath??``),r=cF(O.isAbsolute(t)?t:O.resolve(this._config.primaryWorkspace,t));return{type:`read_outside_directory`,tool:e,displayName:n,filePath:r,resolvedPath:r,deducedDirectory:O.dirname(r)}}case`edit`:{let r=t._prepareResult;if(r?.outsideWorkspace){let t=cF(r.resolvedPath??e.input.filePath??``);return{type:`edit_outside_directory`,tool:e,displayName:n,filePath:t,resolvedPath:t,deducedDirectory:O.dirname(t)}}if(r?.error)return{type:`edit_file`,tool:e,displayName:n,filePath:e.input.filePath??``,originalContent:``,newContent:``};let i=r?.currentContent??``,a=r?.newContent??``;return{type:`edit_file`,tool:e,displayName:n,filePath:e.input.filePath??``,originalContent:i,newContent:a}}case`write`:{let r=t._prepareResult;if(r?.outsideWorkspace){let t=cF(r.resolvedPath??e.input.filePath??``);return{type:`write_outside_directory`,tool:e,displayName:n,filePath:t,resolvedPath:t,deducedDirectory:O.dirname(t),isNewFile:!r?.fileExists}}return{type:`write_file`,tool:e,displayName:n,filePath:e.input.filePath??``,originalContent:r?.currentContent??``,content:e.input.content??``,isNewFile:!r?.fileExists}}case`bash`:{let t=e.input.command??``;return{type:`run_terminal`,tool:e,displayName:n,command:t,cwd:this._config.primaryWorkspace,background:!!(e.input.runInBackground??!1),unmatchedPatterns:this._rulesEngine.getUnmatchedBashSegments(t,this._config.primaryWorkspace)}}case`exit_plan_mode`:{let r=t._prepareResult;return{type:`exit_plan_mode`,tool:e,displayName:n,planFilePath:e.input.planFilePath??``,planContent:String(r?.planContent??``)}}case`ask_user_question`:return{type:`ask_user_question`,tool:e,displayName:n,questions:Array.isArray(e.input.questions)?e.input.questions:[]};case`navigate_to`:return{type:`browser_action`,tool:e,displayName:n,action:e.name,url:e.input.url,description:this._buildBrowserActionDescription(e)};case`computer`:case`perform_interactive_element_action`:case`switch_active_tab`:case`close_tab`:case`refresh_tab`:case`get_tab_content`:case`get_interactive_elements`:case`new_tab`:return{type:`browser_action`,tool:e,displayName:n,action:e.name,description:this._buildBrowserActionDescription(e)};case`notebook_edit`:{let r=t._prepareResult;if(r?.outsideWorkspace){let t=cF(r.resolvedPath??e.input.notebookPath??``);return{type:`notebook_edit_outside_directory`,tool:e,displayName:n,filePath:t,resolvedPath:t,deducedDirectory:O.dirname(t)}}let i=r?.notebook,a=e.input.cellId,o=e.input.editMode??`replace`,s=``;if(a&&i?.cells){let e=i.cells.find(e=>e.id===a||e.metadata?.id===a);e&&(s=Array.isArray(e.source)?e.source.join(``):String(e.source??``))}return{type:`notebook_edit`,tool:e,displayName:n,notebookPath:e.input.notebookPath??``,cellId:a,editMode:o,cellType:e.input.cellType,originalContent:s,newContent:e.input.newSource??``}}default:return{type:`generic`,tool:e,displayName:n,toolName:n,inputSummary:JSON.stringify(e.input).slice(0,200)}}}_buildExecuteTools(e){return async(t,n,r)=>{let i=new AbortController,a=()=>i.abort(`interrupted`);n&&(n.aborted?i.abort(`interrupted`):n.addEventListener(`abort`,a,{once:!0}));let o=[],s=(e,t,n)=>{let r=n?.storageContent??t;return{id:e.id,content:t,...n?.rejected&&{rejected:!0},parsedResult:r.startsWith(`Error:`)?{phase:`error`,toolType:e.name,data:{},summary:r,errorMessage:r}:this._registry.parse(e.name,r)}};try{let a=async t=>{if(i.signal.aborted)return{resolved:!0,result:s(t,JSON.stringify({reason:bR.INTERRUPTED}),{rejected:!0})};let a={workspace:this._workspace,terminalService:this._terminalService,apiClient:this._config.apiClient,workspacePath:this._config.primaryWorkspace,conversationId:e,agentMode:this._mode,toolCallId:t.id,status:`executing`,uploadedDocs:this._uploadedDocs,allowEditingPaths:this._config.allowedDirectories,abortController:i,permissionProvider:this._config.permissionProvider,rulesEngine:this._rulesEngine,getAgentMode:()=>this._mode,setAgentMode:e=>{this._mode=e},mcpService:{listAllToolDefinitions:async()=>this._mcpService.getAbacusMcpTools(),callTool:(e,t,n)=>this._mcpService.callTool(e,t,n),reloadConnections:async()=>{await this._mcpService.initialize(this._config.primaryWorkspace,this._config.mcpServers,this._config.onMcpAuthRequired)},getServerStatus:e=>{let t=this._mcpService.getConnectedServers().find(t=>t.config.id===e);return t?t.status===`connected`?`running`:`error`:`stopped`}},...this._rules.length>0&&{rules:this._rules},...this._config.planDirectory!==void 0&&{plansDir:this._config.planDirectory},...this._config.clientType&&{clientType:this._config.clientType},...r&&{emitEvent:r},...r&&{onOutputUpdate:(e,t)=>{r({type:`tool_output_update`,toolCallId:e,output:t})}}};try{if(this._registry.isDisabled(t.name))return{resolved:!0,result:s(t,`Error: tool '${t.name}' is disabled in this environment`)};r?.({type:`tool_execution_start`,tool:t});let e=this._registry.createToolInstance(t.name,t.input??{},a);if(await e.prepare(),t.name===`edit`&&MV.isBuiltinRequest(t)&&!e._prepareResult?.error){let n=e._prepareResult,i=a.workspacePath,o=a.plansDir??O.join(te(),hn.configDirName,`plans`),s=uF(O.resolve(i,t.input.filePath??``),O.resolve(i,o)),c={originalContent:n?.currentContent??``,newContent:n?.newContent??``,isPlanFile:s,isNewFile:!(n?.fileExists??!0)},l={type:`tool_display_data`,toolCallId:t.id,data:c};r?.(l),this._toolEventBuffer.push(l)}if(t.name===`notebook_edit`&&MV.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`&&MV.isBuiltinRequest(t)&&!e._prepareResult?.error){let n=e._prepareResult,i={originalContent:n?.currentContent??``,newContent:t.input.content??``,isNewFile:!(n?.fileExists??!0)},a={type:`tool_display_data`,toolCallId:t.id,data:i};r?.(a),this._toolEventBuffer.push(a)}let i=this._mode===xd.Yolo&&t.name!==`ask_user_question`;if(!i&&e.needsPermission()){let i=this._registry.get(t.name)?.displayName??t.name,o=VV(t),c=this._rulesEngine.evaluate(i,o);if(c===`deny`)return{resolved:!0,result:s(t,JSON.stringify({reason:bR.REJECTED}),{rejected:!0})};if(c!==`allow`){let i=this._buildPermissionRequest(t,e);if(this._config.permissionProvider.needsPermission(i)){let o={type:`status_changed`,status:Sd.WaitingForToolPermission};r?.(o),this._toolEventBuffer.push(o);let c;try{let e=this._config.permissionProvider.requestPermission(i);if(n){let t,r=new Promise((e,r)=>{n.aborted?r(Error(`interrupted`)):(t=()=>r(Error(`interrupted`)),n.addEventListener(`abort`,t,{once:!0}))});try{c=await Promise.race([e,r])}finally{t&&n.removeEventListener(`abort`,t)}}else c=await e}catch{return{resolved:!0,result:s(t,JSON.stringify({reason:bR.INTERRUPTED}),{rejected:!0})}}if(r?.({type:`status_changed`,status:Sd.ExecutingTool}),this._toolEventBuffer.push({type:`status_changed`,status:Sd.ExecutingTool}),c===`reject`)return{resolved:!0,result:s(t,JSON.stringify({reason:bR.REJECTED}),{rejected:!0})};if(typeof c==`object`&&c.type===`reject_with_message`)return{resolved:!0,result:s(t,JSON.stringify({reason:bR.USER_MESSAGE,message:c.message}),{rejected:!0})};if(c===`allowAlways`||c===`allowYolo`||c===`accept`){if(c===`allowAlways`&&(i.type===`read_outside_directory`||i.type===`write_outside_directory`||i.type===`edit_outside_directory`||i.type===`notebook_edit_outside_directory`)){if(this.addAllowedDirectory(i.deducedDirectory),this._config.config){let e=this._config.config.get(`additionalDirectories`)??[];e.includes(i.deducedDirectory)||this._config.config.set(`additionalDirectories`,[...e,i.deducedDirectory],`local`)}}else if(t.name===`exit_plan_mode`){let e=c===`allowYolo`?xd.Yolo:c===`allowAlways`?xd.AcceptEdits:xd.Normal;this._mode=e,a.agentMode=e,r?.({type:`mode_changed`,mode:e}),this._toolEventBuffer.push({type:`mode_changed`,mode:e})}else if(c===`allowAlways`){let e=Dd(i.type);this._mode=e,a.agentMode=e,r?.({type:`mode_changed`,mode:e}),this._toolEventBuffer.push({type:`mode_changed`,mode:e})}}if(typeof c==`object`&&c.type===`accept_with_message`&&this.nq(c.message),typeof c==`object`&&c.type===`question_answers`&&e.mergeParams({answers:c.answers}),typeof c==`object`&&c.type===`allow_always_with_rule`&&(this._rulesEngine.addAllowRule(c.rule),this._config.config)){let e=this._config.config.get(`permissions`)??{},t=[...e.allow??[],c.rule];this._config.config.set(`permissions`,{...e,allow:t},`local`)}if(typeof c==`object`&&c.type===`allow_always_with_rules`){for(let e of c.rules)this._rulesEngine.addAllowRule(e);if(this._config.config){let e=this._config.config.get(`permissions`)??{},t=[...e.allow??[],...c.rules];this._config.config.set(`permissions`,{...e,allow:t},`local`)}}}}}return t.name===`enter_plan_mode`&&(this._mode=xd.PlanMode,a.agentMode=xd.PlanMode,r?.({type:`mode_changed`,mode:xd.PlanMode}),this._toolEventBuffer.push({type:`mode_changed`,mode:xd.PlanMode})),t.name===`exit_plan_mode`&&i&&(this._mode=xd.Normal,a.agentMode=xd.Normal,r?.({type:`mode_changed`,mode:xd.Normal}),this._toolEventBuffer.push({type:`mode_changed`,mode:xd.Normal})),{resolved:!1,call:t,instance:e,ctx:a}}catch(e){return i.signal.aborted?{resolved:!0,result:s(t,JSON.stringify({reason:bR.INTERRUPTED}),{rejected:!0})}:{resolved:!0,result:s(t,`Error: ${e instanceof Error?e.message:String(e)}`)}}},c=async e=>{try{if(await e.instance.execute(),i.signal.aborted)return s(e.call,JSON.stringify({reason:bR.INTERRUPTED}),{rejected:!0});let t=e.instance.formatResultForLLM(),n=e.instance.formatResult(),r=typeof t==`string`?t:JSON.stringify(t);return s(e.call,r,{storageContent:n===r?void 0:n})}catch(t){if(i.signal.aborted)return s(e.call,JSON.stringify({reason:bR.INTERRUPTED}),{rejected:!0});let n=t instanceof Error?t.message:String(t);return s(e.call,`Error: ${n}`)}},l=0,u=!1;for(;l<t.length;){let e=e=>this._registry.get(e.name)?.concurrency(e.input,this._config.primaryWorkspace)??!1;if(u){let n=t[l],i=!!e(n),a=this._registry.get(n.name),c=a?!a.isReadonly:!1;if(i||c){let e=s(n,CR);o.push(e),r?.({type:`tool_execution_complete`,tool:n,result:e}),l++;continue}}if(e(t[l])){let n=l+1;for(;n<t.length&&e(t[n]);)n++;if(n-l>1){let i=t.slice(l,n),d=i.map(e);l=n;let f=[[]],p=[new Set];for(let e=0;e<i.length;e++){let t=d[e],n=f[f.length-1],r=p[p.length-1];typeof t==`string`&&r.has(t)&&(f.push([]),p.push(new Set),n=f[f.length-1],r=p[p.length-1]),typeof t==`string`&&r.add(t),n.push(e)}let m=new Map,h=new Map,g=!1;for(let e of f){if(g){for(let t of e){let e=s(i[t],CR);o.push(e),r?.({type:`tool_execution_complete`,tool:i[t],result:e})}continue}for(let t of e)m.set(t,await a(i[t]));for(let t of e){let e=m.get(t);e.resolved&&r?.({type:`tool_execution_complete`,tool:i[t],result:e.result})}let t=e.filter(e=>!m.get(e).resolved).map(async e=>{let t=m.get(e);if(!t.resolved){let n=await c(t);h.set(e,n),r?.({type:`tool_execution_complete`,tool:i[e],result:n})}});for(let e=0;e<t.length;e+=10)await Promise.all(t.slice(e,e+10));for(let t of e){let e=m.get(t),n=e.resolved?e.result:h.get(t);o.push(n),!g&&!n.rejected&&n.content.startsWith(`Error:`)&&(g=!0)}}g&&(u=!0);continue}}let n=t[l];l++;let i=await a(n);if(i.resolved){o.push(i.result),r?.({type:`tool_execution_complete`,tool:n,result:i.result});continue}let d=await c(i);o.push(d),r?.({type:`tool_execution_complete`,tool:n,result:d})}return o}finally{n&&n.removeEventListener(`abort`,a)}}}async createConversation(){let e=await this._config.apiClient.createCodellmDeploymentConversation(`CODE_LLM_AGENT`,this._config.clientType);if(e?.success===!1&&e.error)throw Error(e.error);let t=e?.result?.deploymentConversationId;if(!t)throw Error(`Failed to create conversation: no deployment conversation ID returned`);return this._conversationId=t,t}async loadConversation(e){this._conversationId=e;let t=await this._config.apiClient.getDeploymentConversation({deploymentConversationId:e}),n=t?.result?.history??[],r=t?.result?.name??void 0;ROe(n);let i=NOe(this._hydrateHistory(n));return{...r!==void 0&&{title:r},segments:i}}switchConversation(e){return this._conversationId=e,this._uploadedDocs.clear(),Promise.resolve()}resetConversation(){this._conversationId=null,this._uploadedDocs.clear()}async deleteConversation(e){await this._config.apiClient.deleteDeploymentConversation?.({deploymentConversationId:e}),this._conversationId===e&&(this._conversationId=null)}async listConversations(){return((await this._config.apiClient.getConversationsList(`CODE_LLM_AGENT`))?.result??[]).map(e=>({id:e.deploymentConversationId??``,createdAt:new Date(e.createdAt??Date.now()),updatedAt:new Date(e.lastEventCreatedAt??e.createdAt??Date.now()),...e.name!==void 0&&{title:e.name}}))}_hydrateHistory(e){let t=[],n=[];for(let r of e){if(r.role===`USER`){let e=this._extractParallelToolResponses(r);e.length>0&&this._attachToolResults(n,e),n=[];let i=(r.prompt??r.text??``).trim();i&&t.push({type:`text`,id:crypto.randomUUID(),source:`user`,content:i});continue}n=[];for(let e of r.segments??[]){if(e.isThoughts){let n=typeof e.segment==`string`?e.segment:e.segment?.segment??``;t.push({type:`thinking`,id:crypto.randomUUID(),content:n,isSpinny:!1});continue}if(e.type===`code_llm_agent_tool_request`&&e.toolUseRequest){let r=Array.isArray(e.toolUseRequest)?e.toolUseRequest:[e.toolUseRequest];for(let e of r){let r={type:`tool_call`,id:crypto.randomUUID(),toolUseRequest:e,toolPhase:`unknown`};t.push(r),n.push(r)}continue}if(e.type===`code_llm_notification`){t.push({type:`notification`,id:crypto.randomUUID(),message:e.message??(typeof e.segment==`string`?e.segment:``)??``,severity:e.severity??`info`,...e.actions!==void 0&&{actions:e.actions}});continue}let r=typeof e.segment==`string`?e.segment:e.segment?.segment;r&&t.push({type:`text`,id:crypto.randomUUID(),source:`bot`,content:r})}}return this._detectAbandonedTools(t),t}_extractParallelToolResponses(e){if(Array.isArray(e.parallelToolResponses))return e.parallelToolResponses;for(let t of e.segments??[])if(Array.isArray(t.parallelToolResponses)&&t.parallelToolResponses.length>0)return t.parallelToolResponses;return[]}_attachToolResults(e,t){for(let n=0;n<Math.min(e.length,t.length);n++){let r=e[n],i=t[n],a=r.toolUseRequest.name,o=xR(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 POe(e)?`The large prompt is saved in ${this._promptFileManager.savePrompt(e)} file. Follow the instructions in it.`:e}async*send(e,t){if(await this._ensureInitialized(),this._logger.info(`Sending message (conversationId={conversationId}, mode={mode}, model={model})`,{conversationId:this._conversationId,mode:this._mode,model:this._model}),!this._conversationId)for(let e=0;e<8;e++)try{await this.createConversation();break}catch(t){if(!Vl(t)||e>=7)throw t;let n=Math.min((e+1)*2e3,1e4);yield{type:`retry`,attempt:e+1,maxAttempts:8,delayMs:n,isNetworkError:!0},await VR(n)}this._running=!0,this._abortController=new AbortController;let n=this._buildExecuteTools(this._conversationId);try{yield{type:`status_changed`,status:Sd.Submitted};let r=this._rewriteIfLargePrompt(e),i=!0;for(;;){let e=this._mcpService.getAbacusMcpTools();e.length>0&&this._registry.registerMCPTools(e.map(e=>new DOe(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:zR().map(e=>({name:e})),...e.length>0&&{mcpTools:e},...this._rules.length>0&&{rules:this._rules},...this._config.enableSkills&&(()=>{let e=cq.getAllMetadata();return e.length>0?{availableSkills:e}:{}})(),...this._config.enableSkills&&t?.activeSkills&&t.activeSkills.length>0&&{activeSkills:t.activeSkills},...this._config.isPrintMode!==void 0&&{isPrintMode:this._config.isPrintMode},...this._config.enablePromptRewrite!==void 0&&{enablePromptRewrite:this._config.enablePromptRewrite},...this._config.supportsThoughtStreaming!==void 0&&{supportsThoughtStreaming:this._config.supportsThoughtStreaming},agentMode:this._mode,...this._config.config?.get(`client`)&&{client:this._config.config.get(`client`)},...this._config.maxTurns!==void 0&&{maxTurns:this._config.maxTurns},...i&&t?.diagnosticIssues!==void 0&&{diagnosticIssues:t.diagnosticIssues},...i&&t?.currentFile!==void 0&&{currentFile:O.isAbsolute(t.currentFile)?t.currentFile:O.resolve(this._config.primaryWorkspace,t.currentFile)},...i&&t?.selectionStartLine!==void 0&&{selectionStartLine:t.selectionStartLine},...i&&t?.selectionEndLine!==void 0&&{selectionEndLine:t.selectionEndLine},executeTools:n,getConcurrency:e=>this._registry.get(e.name)?.concurrency(e.input,this._config.primaryWorkspace)??!1,drainEvents:()=>{let e=this._toolEventBuffer.slice();return this._toolEventBuffer.length=0,e},dequeueAllQueuedMessage:e=>{let t=this.dq(e);return t.length===0?null:{message:this._rewriteIfLargePrompt(t.map(e=>e.message).join(`
75080
+ `)),allHidden:t.every(e=>e.hidden)}}};this._swapFolder=null,this._setFolder=null;let c=KR(s,r,this._abortController.signal),l=!1,u;for(;!(u=await c.next()).done;){let e=u.value;e.type===`text_delta`&&!l?(l=!0,yield{type:`status_changed`,status:Sd.Streaming}):e.type===`tool_requested`&&(yield{type:`status_changed`,status:Sd.ExecutingTool}),yield e,e.type===`mode_changed`&&(this._mode=e.mode)}if(i=!1,this._messageQueue.length===0||this._abortController.signal.aborted)break;let d=this.dq({includeHidden:!0});if(d.length===0)break;let f=d.every(e=>e.hidden);r=this._rewriteIfLargePrompt(d.map(e=>e.message).join(`
75081
+ `)),f||(yield{type:`user_message_dequeued`,content:r})}}finally{this._running=!1,this._abortController=null,this._toolEventBuffer.length=0,this._uploadedDocs.clear(),this._promptFileManager.cleanup(),this._logger.debug(`Send completed, session idle`),yield{type:`status_changed`,status:Sd.Idle}}}stop(){this._abortController?.abort()}dispose(){this._abortController?.abort(),this._promptFileManager.cleanup(),this._terminalService.dispose()}nq(e,t){let n={id:crypto.randomUUID(),message:e,...t?.hidden?{hidden:!0}:{}};return this._messageQueue.push(n),{...n}}getQueue(e){return this.getQueueEntries(e).map(e=>e.message)}getQueueEntries(e){return e?.includeHidden??!1?this._messageQueue.map(e=>({...e})):this._messageQueue.filter(e=>e.hidden!==!0).map(e=>({...e}))}dq(e){let t=e?.includeHidden??!1,n=e?.id;if(n!==void 0){let e=this._messageQueue.findIndex(e=>e.id===n?t||e.hidden!==!0:!1);if(e===-1)return[];let[r]=this._messageQueue.splice(e,1);return r?[{...r}]:[]}if(t){let e=this._messageQueue.map(e=>({...e}));return this._messageQueue.length=0,e}let r=[],i=[];for(let e of this._messageQueue)e.hidden===!0?i.push(e):r.push({...e});return this._messageQueue=i,r}setContent(e,t){let n=typeof e==`string`?e:e.id,r=this._messageQueue.find(e=>e.id===n);return r?(r.message=t,{...r}):null}setText(e,t){return this.setContent(e,t)}remove(e,t){let n=typeof e==`string`?e:e.id,r=t?.includeHidden??!1,i=this._messageQueue.findIndex(e=>e.id===n&&(r||e.hidden!==!0));i!==-1&&this._messageQueue.splice(i,1)}clearQueue(e){if(e?.includeHidden===!0){this._messageQueue.length=0;return}this._messageQueue=this._messageQueue.filter(e=>e.hidden===!0)}addUploadedDoc(e){this._uploadedDocs.add(e)}clearUploadedDocs(){this._uploadedDocs.clear()}isDirectoryAllowed(e){let t=cF(oF(e));for(let e of this._config.allowedDirectories)if(uF(t,e))return{allowed:!0,coveredBy:e};return{allowed:!1}}addAllowedDirectory(e,t){let n=cF(oF(e));for(let e of this._config.allowedDirectories)if(uF(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=cF(oF(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)}},zOe=class{needsPermission(e){return!1}async requestPermission(e){return`accept`}},hq=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)}},BOe=class{async read(){let e={},t=hn.envPrefix,n=hn.internalEnvPrefix,r=process.env[`${t}BASE_URL`],i=process.env[`${t}MODEL`],a=process.env[`${n}LOG_LEVEL`],o=process.env[`${t}MAX_TURNS`],s=process.env[`${t}AUTO_UPDATE`],c=process.env[`${n}CHANNEL`];if(r&&(e.baseUrl=r),i&&(e.model=i),a&&(e.logLevel=a),o&&(e.maxTurns=parseInt(o,10)),c&&(e.updateChannel=c),s!==void 0){let t=MR.safeParse(s);t.success&&t.data!==void 0&&(e.autoUpdate=t.data)}return e}},VOe=class{configPath;constructor(){this.configPath=O.join(te(),hn.configDirName,hn.configFileName)}async read(){try{let e=await m.readFile(this.configPath,`utf-8`);return JSON.parse(e)}catch{return{}}}async write(e){let t=O.dirname(this.configPath);await m.mkdir(t,{recursive:!0}),await m.writeFile(this.configPath,JSON.stringify(e,null,2),`utf-8`)}},HOe=class{configPath;constructor(e){this.configPath=O.join(e,hn.localConfigDirName,hn.configFileName)}async read(){try{let e=await m.readFile(this.configPath,`utf-8`);return JSON.parse(e)}catch{return{}}}async write(e){let t=O.dirname(this.configPath);await m.mkdir(t,{recursive:!0}),await m.writeFile(this.configPath,JSON.stringify(e,null,2),`utf-8`)}};const UOe=dt([`codellm`,`agent`,`config`]);function gq(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]=gq(n[t],r):n[t]=r)}return n}const _q={allowedDirectories:[],primaryWorkspace:``,logLevel:`info`};var vq=class{sources;cache=null;constructor(e){this.sources=[new VOe,new HOe(e.cwd),...e.extraSources??[],new BOe]}async load(){let e={..._q};for(let t of this.sources){let n=await t.read();e=gq(e,n)}this.cache=e,UOe.info`config loaded from ${this.sources.length} sources`}get(e){return this.cache?this.cache[e]??_q[e]:_q[e]}getAll(){return this.cache??_q}async set(e,t,n=`global`){let r=n===`global`?this.sources[0]:this.sources[1];if(r?.write){let n=await r.read();await r.write({...n,[e]:t})}this.cache&&(this.cache[e]=t)}};dt([`codellm`,`agent`,`history`]);var yq=class{source;maxEntries;filePath;entries=[];navIndex=-1;loaded=!1;writeQueue=Promise.resolve();constructor(e,t){this.source=e,this.maxEntries=t?.maxEntries??1e4,this.filePath=t?.filePath??A(te(),hn.configDirName,`history.jsonl`)}async load(){if(!this.loaded){this.loaded=!0;try{let e=this.maxEntries*2048,t=await De(this.filePath,`r`);try{let{size:n}=await t.stat(),r=Math.max(0,n-e),i=Buffer.allocUnsafe(n-r);await t.read(i,0,i.length,r);let a=i.toString(`utf-8`),o=r===0?0:a.indexOf(`
75082
75082
  `)+1,s=a.slice(o).split(`
75083
75083
  `).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(`
75084
75084
  `)};this.entries.push(n),this.entries.length>this.maxEntries?(this.entries=this.entries.slice(-this.maxEntries),this.enqueueWrite(()=>this.rewriteFile())):this.enqueueWrite(()=>this.appendLine(n))}isNavigating(){return this.navIndex!==-1}navigateUp(){if(this.entries.length===0)return null;if(this.navIndex===-1)this.navIndex=this.entries.length-1;else if(this.navIndex>0)this.navIndex--;else return null;return this.entries[this.navIndex]??null}navigateDown(){return this.navIndex===-1?null:(this.navIndex++,this.navIndex>=this.entries.length?(this.navIndex=-1,null):this.entries[this.navIndex]??null)}resetNavigation(){this.navIndex=-1}getEntries(){return this.entries}enqueueWrite(e){this.writeQueue=this.writeQueue.then(e).catch(()=>{})}async appendLine(e){try{await Ee(k(this.filePath),{recursive:!0});let t=await De(this.filePath,`a`);try{await t.write(JSON.stringify(e)+`
@@ -75140,11 +75140,11 @@ No matching component was found for:
75140
75140
  `).map(e=>Zje(e,i)).join(`
75141
75141
  `):t===`truncate-start`&&(r=r.split(`
75142
75142
  `).map(e=>Xje(e,i)).join(`
75143
- `))}}r=xMe(e,r),e.renderCache={lines:[r],width:n,height:0,left:l,top:u},t.write(l,u,r,d)}else e.renderCache=void 0;e.renderDirty=!1;return}let f=!1;if(e.nodeName===`jar-view`){e.style.backgroundColor&&SMe(l,u,e,t),e.style.borderStyle&&_Me(l,u,e,t);let n=e.style.overflowX===`hidden`||e.style.overflow===`hidden`,r=e.style.overflowY===`hidden`||e.style.overflow===`hidden`;if(n||r){let i=n?l+sZ(e.style,`Left`):void 0,a=n?l+c.getComputedWidth()-sZ(e.style,`Right`):void 0,o=r?u+sZ(e.style,`Top`):void 0,s=r?u+c.getComputedHeight()-sZ(e.style,`Bottom`):void 0;t.clip({x1:i,x2:a,y1:o,y2:s}),f=!0}}if(e.nodeName===`jar-root`||e.nodeName===`jar-view`){let n=f?u+sZ(e.style,`Top`):o,r=f?u+c.getComputedHeight()-sZ(e.style,`Bottom`):s;for(let i of e.childNodes)cZ(i,t,{offsetX:l,offsetY:u,transformers:d,clipY1:n,clipY2:r});f&&t.unclip()}e.renderDirty=!1};var CMe=class{rootNode;lastWidth=0;cachedLines=null;output=new Qje(0,0);constructor(e){this.rootNode=e}notifyCommit(){this.cachedLines=null}render(e){let t=e!==this.lastWidth;if(t&&(this.clearAllRenderCaches(this.rootNode),this.lastWidth=e),this.cachedLines&&!this.rootNode.renderDirty&&!t)return this.cachedLines;this.rootNode.yogaNode.setWidth(e),this.rootNode.yogaNode.calculateLayout(void 0,void 0,1);let n=Math.ceil(this.rootNode.yogaNode.getComputedHeight());if(n<=0)return this.cachedLines=[],this.cachedLines;this.output.reset(e,n),cZ(this.rootNode,this.output,{});let r=this.output.get(),i=!1;for(let t of r)if(JJ(t)>e){i=!0;break}return this.cachedLines=i?r.map(t=>JJ(t)>e?$J(t,e):t):r,this.cachedLines}invalidate(){this.cachedLines=null,this.clearAllRenderCaches(this.rootNode)}clearAllRenderCaches(e){e.renderDirty=!0,e.renderCache=void 0;for(let t of e.childNodes)t.nodeName!==`#text`&&this.clearAllRenderCaches(t)}},wMe;(function(e){e[e.BlinkingBlock=0]=`BlinkingBlock`,e[e.BlinkingBlockDefault=1]=`BlinkingBlockDefault`,e[e.SteadyBlock=2]=`SteadyBlock`,e[e.BlinkingUnderline=3]=`BlinkingUnderline`,e[e.SteadyUnderline=4]=`SteadyUnderline`,e[e.BlinkingBar=5]=`BlinkingBar`,e[e.SteadyBar=6]=`SteadyBar`})(wMe||={});const lZ=`\x1B[?25h`,uZ=`\x1B[?25l`;function TMe(e,t){let n=``;return t!==``&&(n=typeof Buffer<`u`?Buffer.from(t).toString(`base64`):btoa(t)),`\x1B]52;`+String.fromCharCode(e)+`;`+n+`\x07`}function EMe(e){return TMe(99,e)}function dZ(e){let t=e??ZX(),n=t.TERM_PROGRAM.toLowerCase(),r=t.TERM.toLowerCase(),i=(t.LC_TERMINAL??``).toLowerCase();if(n===`iterm.app`)return`iterm2`;if(n===`wezterm`)return`wezterm`;if(n===`ghostty`)return`ghostty`;if(n===`vscode`)return`vscode`;if(n===`tmux`)return`tmux`;if(t.WT_SESSION)return`windows-terminal`;if(r.includes(`kitty`))return`kitty`;if(r.includes(`alacritty`))return`alacritty`;if(r.includes(`foot`))return`foot`;if(r.includes(`contour`))return`contour`;if(r.includes(`rio`))return`rio`;if(r.includes(`ghostty`))return`ghostty`;if(r.includes(`wezterm`))return`wezterm`;if(r.startsWith(`tmux`))return`tmux`;if(r.startsWith(`screen`))return`screen`;if(r===`xterm`||r.startsWith(`xterm-`))return`xterm`;if(r===`linux`)return`linux`;if(!n&&i){if(i===`iterm2`)return`iterm2`;if(i===`wezterm`)return`wezterm`}return`unknown`}function DMe(e){return(e??ZX()).isTTY}function fZ(e){let t=dZ(e);return t===`windows-terminal`||t===`iterm2`||t===`wezterm`||t===`ghostty`}function pZ(e){let t=dZ(e);return t===`iterm2`||t===`kitty`||t===`wezterm`||t===`ghostty`||t===`alacritty`||t===`foot`||t===`xterm`||t===`tmux`||t===`windows-terminal`||t===`rio`||t===`contour`}function OMe(e){let t=dZ(e);return t===`iterm2`||t===`kitty`||t===`wezterm`||t===`ghostty`||t===`alacritty`||t===`foot`||t===`contour`||t===`rio`||t===`vscode`||t===`windows-terminal`}function mZ(e,...t){return`\x1B]8;`+(t.length>0?t.join(`:`):``)+`;`+e+`\x07`}function hZ(...e){return mZ(``,...e)}function gZ(e){return e.replace(/[\x07\x1b\x9c]/g,``)}function kMe(e){return`\x1B]9;`+gZ(e)+`\x07`}function _Z(e,...t){return`\x1B]99;`+t.map(gZ).join(`:`)+`;`+gZ(e)+`\x07`}function AMe(e){return`\x1B]777;notify;;`+gZ(e)+`\x07`}const vZ=`\x1B]9;4;0\x07`;function jMe(e){return`\x1B]9;4;1;`+Math.min(Math.max(0,e),100)+`\x07`}function MMe(e){return`\x1B]9;4;2;`+Math.min(Math.max(0,e),100)+`\x07`}function NMe(e){return`\x1B]9;4;4;`+Math.min(Math.max(0,e),100)+`\x07`}var PMe=class{env;profile;terminalType;_isDark;_writer;_progressHideTimer=null;constructor(e){this.env=e?.env??ZX(),this.profile=$X(this.env),pMe(this.profile),this.terminalType=dZ(this.env),this._isDark=e?.isDark??BX(),this._writer=e?.writer??null,e?.isDark!==void 0&&VX(e.isDark)}get isDark(){return this._isDark}setDark(e){this._isDark=e,VX(e)}resolveAdaptiveColor(e){if(typeof e==`string`)return XX.parse(e);let t=this._isDark?e.dark:e.light;return XX.parse(t)}colorize(e,t,n){if(!t)return e;let r=this.resolveAdaptiveColor(t);if(!r)return e;let i=nZ(r,this.profile);return i?`\x1B[`+(n===`foreground`?i.fgSequence():i.bgSequence())+`m`+e+`\x1B[0m`:e}styledText(){return iZ(this.profile)}write(e){this._writer?this._writer(e):typeof process<`u`&&process.stdout?.isTTY&&process.stdout.write(e)}notify(e){if(!DMe(this.env))return;let t=this.terminalType,{title:n,body:r}=e,i=n?`${n}:\n${r}`:r;t===`kitty`&&(n?this.write(_Z(r,`d=0:p=title`,n)):this.write(_Z(r))),this.write(AMe(i)),this.write(kMe(i))}showProgress(e){if(!fZ(this.env))return;this.clearProgressTimer();let t=e.state??`normal`,n=Math.min(Math.max(0,e.percentage??0),100);switch(t){case`indeterminate`:this.write(`\x1B]9;4;3\x07`);break;case`error`:this.write(MMe(n));break;case`warning`:this.write(NMe(n));break;default:this.write(jMe(n));break}(t===`error`||n>=100)&&this.scheduleProgressHide()}hideProgress(){this.clearProgressTimer(),fZ(this.env)&&this.write(vZ)}async trackProgress(e){this.showProgress({state:`indeterminate`});try{let t=await e;return this.showProgress({percentage:100}),this.scheduleProgressHide(),t}catch(e){throw this.showProgress({percentage:100,state:`error`}),this.scheduleProgressHide(),e}}copyToClipboard(e){pZ(this.env)&&this.write(EMe(e))}clearClipboard(){pZ(this.env)&&this.write(`\x1B]52;c;\x07`)}hyperlink(e,t){return OMe(this.env)?mZ(e)+t+hZ():t}clearProgressTimer(){this._progressHideTimer&&=(clearTimeout(this._progressHideTimer),null)}scheduleProgressHide(){this.clearProgressTimer(),this._progressHideTimer=setTimeout(()=>{this.write(vZ),this._progressHideTimer=null},500)}},FMe=class{tui;terminal;terminalOutput;rootNode;bridge;container;exitCallbacks=[];exitPromise;resolveExit;exitOnCtrlC;ownsTui;suspendable;onSuspended;cleanupSuspend;originalWarningListeners;warningInterceptor;requestFullRedrawOnNextCommit=!1;constructor(e={}){this.exitOnCtrlC=e.exitOnCtrlC??!0,this.suspendable=e.suspendable??!1,this.onSuspended=e.onSuspended,e.tui?(this.tui=e.tui,this.terminal=e.tui.terminal,this.ownsTui=!1):e.terminal?(this.terminal=e.terminal,this.tui=new wY(this.terminal),this.ownsTui=!0):(this.terminal=new sje,this.tui=new wY(this.terminal),this.ownsTui=!0),this.terminalOutput=new PMe({writer:e=>this.terminal.write(e)}),this.rootNode=hX(`jar-root`),this.rootNode.yogaNode.setFlexDirection(0),this.rootNode.yogaNode.setFlexGrow(1),this.rootNode.onRender=()=>{this.bridge.notifyCommit(),this.requestFullRedrawOnNextCommit?(this.requestFullRedrawOnNextCommit=!1,this.tui.requestRender(!0)):this.tui.requestRender(),performance.clearMeasures()},this.bridge=new CMe(this.rootNode),this.tui.addChild(this.bridge),this.container=OX.createContainer(this.rootNode,0,null,!1,null,`jar`,()=>{},()=>{},()=>{},()=>{}),this.exitPromise=new Promise(e=>{this.resolveExit=e}),this.exitOnCtrlC&&this.tui.addInputListener(e=>{if(!pY(e)&&vY(e,`ctrl+c`))return this.exit(),{consume:!0}})}render(e){OX.updateContainerSync(e,this.container,null),OX.flushSyncWork()}requestFullRedraw(){this.requestFullRedrawOnNextCommit=!0,this.bridge.invalidate(),this.tui.requestRender(!0)}start(){this.ownsTui&&this.tui.start(),this.setupWarningInterceptor(),this.suspendable&&(this.cleanupSuspend=this.setupSuspendHandler())}exit(e){for(let t of this.exitCallbacks)t(e);this.unmount()}onExit(e){this.exitCallbacks.push(e)}unmount(){if(this.warningInterceptor&&=(H.removeListener(`warning`,this.warningInterceptor),void 0),this.originalWarningListeners){let e=H.listeners(`warning`);for(let t of this.originalWarningListeners)e.includes(t)||H.on(`warning`,t);this.originalWarningListeners=void 0}this.cleanupSuspend?.(),this.ownsTui&&this.disableInputProtocols(),OX.updateContainerSync(null,this.container,null),OX.flushSyncWork(),this.tui.removeChild(this.bridge),this.ownsTui&&this.tui.stop(),this.rootNode.yogaNode?.unsetMeasureFunc(),this.rootNode.yogaNode?.free(),this.rootNode.yogaNode=void 0,this.resolveExit()}cleanupTerminal(){this.ownsTui&&(this.cleanupSuspend?.(),this.disableInputProtocols(),this.tui.stop(),H.stdout.write(lZ))}disableInputProtocols(){this.terminal.write(OY),this.terminal.write(`\x1B[?2004l`),this.terminal.kittyProtocolActive&&this.terminal.write(`\x1B[<u`)}setupWarningInterceptor(){this.originalWarningListeners||(this.originalWarningListeners=H.rawListeners(`warning`),H.removeAllListeners(`warning`),this.warningInterceptor=()=>{},H.on(`warning`,this.warningInterceptor))}setupSuspendHandler(){if(H.platform===`win32`||!this.ownsTui)return()=>{};let e=!1,t=()=>{e=this.terminal.kittyProtocolActive,H.stdout.isTTY&&(this.disableInputProtocols(),H.stdout.write(lZ)),H.stdin.isTTY&&H.stdin.isRaw&&H.stdin.setRawMode(!1),this.onSuspended?.(),H.removeListener(`SIGTSTP`,t),H.kill(H.pid,`SIGTSTP`)},n=()=>{H.stdin.isTTY&&H.stdin.setRawMode(!0),H.stdout.isTTY&&(H.stdout.write(uZ),this.terminal.write(`\x1B[?2004h`),this.terminal.write(DY),e&&this.terminal.write(`\x1B[>7u`)),H.on(`SIGTSTP`,t),this.tui.requestRender(!0)};return H.on(`SIGTSTP`,t),H.on(`SIGCONT`,n),()=>{H.removeListener(`SIGTSTP`,t),H.removeListener(`SIGCONT`,n)}}waitUntilExit(){return this.exitPromise}getRootNode(){return this.rootNode}};function IMe(e,t){let n=new FMe(t),r=Z.createElement(PX,{tui:n.tui,terminal:n.terminal,terminalOutput:n.terminalOutput,exit:e=>n.exit(e),requestFullRedraw:()=>n.requestFullRedraw(),children:e});return n.render(r),n.start(),{rerender(e){let t=Z.createElement(PX,{tui:n.tui,terminal:n.terminal,terminalOutput:n.terminalOutput,exit:e=>n.exit(e),requestFullRedraw:()=>n.requestFullRedraw(),children:e});n.render(t)},unmount(){n.unmount()},waitUntilExit(){return n.waitUntilExit()},requestFullRedraw(){n.requestFullRedraw()},cleanupTerminal(){n.cleanupTerminal()}}}function Q({children:e,...t}){return(0,X.jsx)(`jar-view`,{style:{flexWrap:`nowrap`,flexDirection:`row`,flexGrow:0,flexShrink:1,...t,overflowX:t.overflowX??t.overflow??`visible`,overflowY:t.overflowY??t.overflow??`visible`},children:e})}function $({color:e,backgroundColor:t,dimColor:n=!1,bold:r=!1,italic:i=!1,underline:a=!1,strikethrough:o=!1,inverse:s=!1,wrap:c=`wrap`,transform:l,children:u}){if(u==null)return null;let d=(0,Z.useCallback)(c=>(n&&(c=iZ().dim().render(c)),e&&(c=rZ(c,e,`foreground`)),t&&(c=rZ(c,t,`background`)),r&&(c=iZ().bold().render(c)),i&&(c=iZ().italic().render(c)),a&&(c=iZ().underline().render(c)),o&&(c=iZ().strikethrough().render(c)),s&&(c=iZ().reverse().render(c)),l&&(c=l(c)),c),[e,t,n,r,i,a,o,s,l]);return(0,X.jsx)(`jar-text`,{style:{flexGrow:0,flexShrink:0,flexDirection:`row`,textWrap:c},internal_transform:d,children:u})}const LMe=/\x1b\[[\d:]*;(\d+)/;function RMe(e){let t=LMe.exec(e);return t?(parseInt(t[1],10)-1&8)!=0:!1}const yZ={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:``},bZ=(e,t={})=>{let{addInputListener:n}=(0,Z.use)(jX),r=(0,Z.useRef)(e);r.current=e,(0,Z.useEffect)(()=>{if(t.isActive!==!1)return n(e=>{if(pY(e))return;if(e.startsWith(`\x1B[200~`)){let t=e.indexOf(`\x1B[201~`),n=t===-1?e.slice(6):e.slice(6,t);yZ.upArrow=!1,yZ.downArrow=!1,yZ.leftArrow=!1,yZ.rightArrow=!1,yZ.pageDown=!1,yZ.pageUp=!1,yZ.home=!1,yZ.end=!1,yZ.return=!1,yZ.escape=!1,yZ.ctrl=!1,yZ.shift=!1,yZ.tab=!1,yZ.backspace=!1,yZ.delete=!1,yZ.meta=!1,yZ.super=!1,yZ.paste=!0,yZ.raw=e,r.current(n,{...yZ});return}let t=qAe(e),n=t?t.split(`+`):[],i=n[n.length-1]??``,a=n.includes(`ctrl`),o=n.includes(`shift`),s=n.includes(`alt`);yZ.upArrow=i===`up`,yZ.downArrow=i===`down`,yZ.leftArrow=i===`left`,yZ.rightArrow=i===`right`,yZ.pageDown=i===`pagedown`,yZ.pageUp=i===`pageup`,yZ.home=i===`home`,yZ.end=i===`end`,yZ.return=i===`return`||i===`enter`,yZ.escape=i===`escape`,yZ.ctrl=a,yZ.shift=o,yZ.tab=i===`tab`,yZ.backspace=i===`backspace`,yZ.delete=i===`delete`,yZ.meta=s,yZ.super=RMe(e),yZ.paste=!1,yZ.raw=e;let c=yZ,l=``;if(a&&i)l=i;else if(!c.upArrow&&!c.downArrow&&!c.leftArrow&&!c.rightArrow&&!c.pageDown&&!c.pageUp&&!c.home&&!c.end&&!c.return&&!c.escape&&!c.tab&&!c.backspace&&!c.delete){let t=XAe(e);t===void 0?e.length===1?l=e:i.length===1&&(l=i):l=t}r.current(l,{...c})})},[t.isActive,n])},zMe=()=>{let e=(0,Z.use)(MX);if(!e)throw Error(`useApp must be used within a jar render context`);return{exit:e.exit,requestFullRedraw:e.requestFullRedraw}},xZ=({isActive:e=!0,autoFocus:t=!1,id:n}={})=>{let{activeId:r,add:i,remove:a,activate:o,deactivate:s,focus:c}=(0,Z.use)(kX),l=(0,Z.useMemo)(()=>n??Math.random().toString().slice(2,7),[n]);return(0,Z.useEffect)(()=>(i(l,{autoFocus:t}),()=>{a(l)}),[l,t]),(0,Z.useEffect)(()=>{e?o(l):s(l)},[e,l]),{isFocused:!!l&&r===l,focus:c}};function SZ(){return(0,Z.use)(AX)}const CZ=()=>{let e=(0,Z.use)(NX);if(!e)throw Error(`useTerminal must be used within a jar render context`);return e.output},wZ=RegExp(`[\\x1b\\x9b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><~]|\\x1b\\][\\s\\S]*?(?:\\x07|\\x1b\\\\)`,`g`);function BMe(){return new RegExp(wZ.source,`g`)}function VMe(e){return e.replace(wZ,``)}function HMe(e){return e.replace(/[\x07\x1b\x9c]/g,``)}function TZ(e){return`\x1B]2;`+HMe(e)+`\x07`}var EZ=G(((e,t)=>{t.exports={name:`@codellm/cli`,version:`2.4.8`,private:!0,bin:{abacusai:`dist/index.mjs`},files:[`dist`,`LICENSE.txt`],type:`module`,scripts:{"prepare-publish":`bun ./scripts/prepare-publish.ts`,build:`tsdown`,"check-types":`tsgo -b --noEmit`,test:`FORCE_COLOR=1 vitest run`,"test:watch":`FORCE_COLOR=1 vitest`,"test:ui":`FORCE_COLOR=1 vitest --ui`,"test:coverage":`FORCE_COLOR=1 vitest run --coverage`},dependencies:{"@clack/prompts":`^0.11.0`,"@codellm/agent":`workspace:*`,"@codellm/api":`workspace:*`,"@codellm/auth":`workspace:*`,"@codellm/comms":`workspace:*`,"@codellm/jar":`workspace:*`,"@codellm/logging":`workspace:*`,"@codellm/product":`workspace:*`,"@logtape/logtape":`^2.0.5`,"@orpc/client":`catalog:`,"@orpc/contract":`catalog:`,"@orpc/server":`catalog:`,"@sentry/node-core":`10.46.0`,"@slack/web-api":`^7.0.0`,"@tanstack/react-query":`^5.90.19`,"@vscode/ripgrep":`1.17.0`,"ansi-styles":`^6.2.3`,"beautiful-mermaid":`^1.1.3`,"cli-boxes":`^4.0.1`,"cli-highlight":`^2.1.11`,conf:`^15.0.2`,diff:`^8.0.3`,fzf:`^0.5.2`,"gradient-string":`^3.0.0`,immer:`^11.1.4`,"isomorphic-git":`^1.36.1`,marked:`^17.0.4`,"patchright-core":`^1.58.2`,react:`^19.2.3`,"react-compiler-runtime":`^1.0.0`,remend:`^1.2.2`,semver:`^7.7.4`,"shell-history":`^2.0.1`,"string-width":`^8.1.0`,"strip-ansi":`^7.2.0`,trash:`^9.0.0`,zod:`catalog:`},devDependencies:{"@codellm/configs":`workspace:*`,"@playwright/mcp":`^0.0.68`,"@types/diff":`^8.0.0`,"@types/node":`catalog:`,"@types/react":`^19.2.9`,"@types/semver":`^7.7.1`,"@typescript/native-preview":`catalog:`,"@vitejs/plugin-react":`^5.1.2`,"@vitest/coverage-v8":`^4.0.18`,"@vitest/ui":`^4.0.18`,"@xterm/addon-serialize":`^0.14.0`,"@xterm/headless":`^6.0.0`,"babel-plugin-react-compiler":`^1.0.0`,"cli-testing-library":`^3.0.1`,jsdom:`^27.4.0`,"node-pty":`^1.1.0`,"react-devtools-core":`^6.1.5`,"svg-term-cli":`^2.1.1`,tsdown:`^0.21.0`,vite:`catalog:`,vitest:`^4.0.18`},engines:{node:`>=18`}}})),DZ=Qe(EZ(),1);let OZ=null;function kZ(e){let t=(0,xJ.prerelease)(e);return t&&t.length>0&&typeof t[0]==`string`?t[0]:`latest`}function AZ(e){if(!e)return``;try{return y(e)}catch{return e}}function jZ(){return{invokedPath:AZ(process.argv[1]??``),execPath:AZ(process.execPath??process.argv[0]??``)}}function MZ(e){let t=hn.configDirName.replace(/^\./,``).replace(/[.*+?^${}()|[\]\\]/g,`\\$&`);return RegExp(`[/\\\\]\\.?${t}[/\\\\]bin[/\\\\]`,`i`).test(e)}function NZ(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 PZ(){let e=(process.env.npm_command??``).toLowerCase();if(e===`exec`||e===`dlx`)return!0;let{invokedPath:t,execPath:n}=jZ();return/[/\\]_npx[/\\]|[/\\]dlx[/\\]|[/\\]\.cache[/\\]/.test(t+`|`+n)}function FZ(){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}=jZ(),r=`${t}|${n}`;return/[/\\]\.?yarn[/\\]/.test(r)?`yarn`:/[/\\]\.?pnpm[/\\]/.test(r)?`pnpm`:/[/\\]\.bun[/\\]/.test(r)||process.versions.bun!==void 0&&!MZ(n)?`bun`:`npm`}function UMe(){let{execPath:e,invokedPath:t}=jZ();return NZ(t)||NZ(e)?!1:MZ(e)||MZ(t)}function IZ(){let e=`${hn.internalEnvPrefix}DEV`,t=process.env[e];if(t===`1`||t===`true`)return!0;let{invokedPath:n,execPath:r}=jZ();return!(MZ(r)||MZ(n)||NZ(n)||NZ(r)||process.env.npm_config_user_agent)}function WMe(){let{execPath:e}=jZ(),t=FZ(),n=PZ();return IZ()?{installationType:`development`,packageManager:t,isEphemeral:n,execPath:e}:UMe()?{installationType:`native`,packageManager:t,isEphemeral:n,execPath:e}:{installationType:`package-manager`,packageManager:t,isEphemeral:n,execPath:e}}function GMe(){return`${process.platform===`win32`?`win32`:process.platform===`darwin`?`darwin`:`linux`}-${process.arch===`arm64`?`arm64`:`x64`}`}async function KMe(e){let t=Date.now();if(OZ&&t-OZ.timestamp<6e4)return OZ.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 OZ={tags:r,timestamp:t},r}async function qMe(e,t,n,r){let i=t??kZ(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:FZ(),isEphemeral:PZ(),installationType:`native`,downloadUrl:l.url}}async function JMe(e,t){let n=t??kZ(e),r=FZ(),i=PZ(),a=(await KMe(gn.publishName))[n];return!a&&n!==`latest`||!a||a===e?null:{currentVersion:e,latestVersion:a,tag:n,packageManager:r,isEphemeral:i,installationType:`package-manager`}}async function LZ(e,t,n,r){let i=WMe();if(i.installationType===`native`)try{return await qMe(e,t,GMe(),n)}catch{return null}return i.installationType===`development`&&!r?.includeDev?null:await JMe(e,t)}function RZ(e){if(e.installationType===`native`)return`${hn.binName} upgrade`;let t=`${gn.publishName}@${e.tag}`;switch(e.packageManager){case`yarn`:return`yarn global add ${t}`;case`pnpm`:return`pnpm add -g ${t}`;case`bun`:return`bun add -g ${t}`;default:return`npm install -g ${t}`}}function zZ(e){try{return{ok:!0,output:le(RZ(e),{stdio:`pipe`,encoding:`utf-8`}).trim()}}catch(e){return{ok:!1,output:e instanceof Error&&`stderr`in e?String(e.stderr).trim():e instanceof Error?e.message:`Unknown error`}}}async function BZ(e){if(!e.downloadUrl)return{ok:!1,output:`No download URL`};let t=D.join(P.tmpdir(),`abacusai-update-${Date.now()}`),n=D.join(P.homedir(),hn.configDirName,`bin`),r=process.platform===`win32`,i=r?`${hn.binName}.exe`:hn.binName;try{await we.mkdir(t,{recursive:!0}),await we.mkdir(n,{recursive:!0});let a=D.join(t,r?`update.zip`:`update.tar.gz`),o=await fetch(e.downloadUrl);if(!o.ok)throw Error(`Download failed: ${o.status}`);let s=Buffer.from(await o.arrayBuffer());await we.writeFile(a,s),le(r?`powershell -Command "Expand-Archive -Path '${a}' -DestinationPath '${t}' -Force"`:`tar -xzf "${a}" -C "${t}"`,{stdio:`pipe`});let c=D.join(t,i),l=D.join(n,i);return await we.copyFile(c,l),r||await we.chmod(l,493),{ok:!0,output:`Updated to ${e.latestVersion}`}}catch(e){return{ok:!1,output:e instanceof Error?e.message:`Unknown error`}}finally{await we.rm(t,{recursive:!0,force:!0}).catch(()=>{})}}function YMe(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 VZ(e,t){let n=(await e.listLLMModels())?.result??[];return n.length||(process.stderr.write(`Error: No models available.
75143
+ `))}}r=xMe(e,r),e.renderCache={lines:[r],width:n,height:0,left:l,top:u},t.write(l,u,r,d)}else e.renderCache=void 0;e.renderDirty=!1;return}let f=!1;if(e.nodeName===`jar-view`){e.style.backgroundColor&&SMe(l,u,e,t),e.style.borderStyle&&_Me(l,u,e,t);let n=e.style.overflowX===`hidden`||e.style.overflow===`hidden`,r=e.style.overflowY===`hidden`||e.style.overflow===`hidden`;if(n||r){let i=n?l+sZ(e.style,`Left`):void 0,a=n?l+c.getComputedWidth()-sZ(e.style,`Right`):void 0,o=r?u+sZ(e.style,`Top`):void 0,s=r?u+c.getComputedHeight()-sZ(e.style,`Bottom`):void 0;t.clip({x1:i,x2:a,y1:o,y2:s}),f=!0}}if(e.nodeName===`jar-root`||e.nodeName===`jar-view`){let n=f?u+sZ(e.style,`Top`):o,r=f?u+c.getComputedHeight()-sZ(e.style,`Bottom`):s;for(let i of e.childNodes)cZ(i,t,{offsetX:l,offsetY:u,transformers:d,clipY1:n,clipY2:r});f&&t.unclip()}e.renderDirty=!1};var CMe=class{rootNode;lastWidth=0;cachedLines=null;output=new Qje(0,0);constructor(e){this.rootNode=e}notifyCommit(){this.cachedLines=null}render(e){let t=e!==this.lastWidth;if(t&&(this.clearAllRenderCaches(this.rootNode),this.lastWidth=e),this.cachedLines&&!this.rootNode.renderDirty&&!t)return this.cachedLines;this.rootNode.yogaNode.setWidth(e),this.rootNode.yogaNode.calculateLayout(void 0,void 0,1);let n=Math.ceil(this.rootNode.yogaNode.getComputedHeight());if(n<=0)return this.cachedLines=[],this.cachedLines;this.output.reset(e,n),cZ(this.rootNode,this.output,{});let r=this.output.get(),i=!1;for(let t of r)if(JJ(t)>e){i=!0;break}return this.cachedLines=i?r.map(t=>JJ(t)>e?$J(t,e):t):r,this.cachedLines}invalidate(){this.cachedLines=null,this.clearAllRenderCaches(this.rootNode)}clearAllRenderCaches(e){e.renderDirty=!0,e.renderCache=void 0;for(let t of e.childNodes)t.nodeName!==`#text`&&this.clearAllRenderCaches(t)}},wMe;(function(e){e[e.BlinkingBlock=0]=`BlinkingBlock`,e[e.BlinkingBlockDefault=1]=`BlinkingBlockDefault`,e[e.SteadyBlock=2]=`SteadyBlock`,e[e.BlinkingUnderline=3]=`BlinkingUnderline`,e[e.SteadyUnderline=4]=`SteadyUnderline`,e[e.BlinkingBar=5]=`BlinkingBar`,e[e.SteadyBar=6]=`SteadyBar`})(wMe||={});const lZ=`\x1B[?25h`,uZ=`\x1B[?25l`;function TMe(e,t){let n=``;return t!==``&&(n=typeof Buffer<`u`?Buffer.from(t).toString(`base64`):btoa(t)),`\x1B]52;`+String.fromCharCode(e)+`;`+n+`\x07`}function EMe(e){return TMe(99,e)}function dZ(e){let t=e??ZX(),n=t.TERM_PROGRAM.toLowerCase(),r=t.TERM.toLowerCase(),i=(t.LC_TERMINAL??``).toLowerCase();if(n===`iterm.app`)return`iterm2`;if(n===`wezterm`)return`wezterm`;if(n===`ghostty`)return`ghostty`;if(n===`vscode`)return`vscode`;if(n===`tmux`)return`tmux`;if(t.WT_SESSION)return`windows-terminal`;if(r.includes(`kitty`))return`kitty`;if(r.includes(`alacritty`))return`alacritty`;if(r.includes(`foot`))return`foot`;if(r.includes(`contour`))return`contour`;if(r.includes(`rio`))return`rio`;if(r.includes(`ghostty`))return`ghostty`;if(r.includes(`wezterm`))return`wezterm`;if(r.startsWith(`tmux`))return`tmux`;if(r.startsWith(`screen`))return`screen`;if(r===`xterm`||r.startsWith(`xterm-`))return`xterm`;if(r===`linux`)return`linux`;if(!n&&i){if(i===`iterm2`)return`iterm2`;if(i===`wezterm`)return`wezterm`}return`unknown`}function DMe(e){return(e??ZX()).isTTY}function fZ(e){let t=dZ(e);return t===`windows-terminal`||t===`iterm2`||t===`wezterm`||t===`ghostty`}function pZ(e){let t=dZ(e);return t===`iterm2`||t===`kitty`||t===`wezterm`||t===`ghostty`||t===`alacritty`||t===`foot`||t===`xterm`||t===`tmux`||t===`windows-terminal`||t===`rio`||t===`contour`}function OMe(e){let t=dZ(e);return t===`iterm2`||t===`kitty`||t===`wezterm`||t===`ghostty`||t===`alacritty`||t===`foot`||t===`contour`||t===`rio`||t===`vscode`||t===`windows-terminal`}function mZ(e,...t){return`\x1B]8;`+(t.length>0?t.join(`:`):``)+`;`+e+`\x07`}function hZ(...e){return mZ(``,...e)}function gZ(e){return e.replace(/[\x07\x1b\x9c]/g,``)}function kMe(e){return`\x1B]9;`+gZ(e)+`\x07`}function _Z(e,...t){return`\x1B]99;`+t.map(gZ).join(`:`)+`;`+gZ(e)+`\x07`}function AMe(e){return`\x1B]777;notify;;`+gZ(e)+`\x07`}const vZ=`\x1B]9;4;0\x07`;function jMe(e){return`\x1B]9;4;1;`+Math.min(Math.max(0,e),100)+`\x07`}function MMe(e){return`\x1B]9;4;2;`+Math.min(Math.max(0,e),100)+`\x07`}function NMe(e){return`\x1B]9;4;4;`+Math.min(Math.max(0,e),100)+`\x07`}var PMe=class{env;profile;terminalType;_isDark;_writer;_progressHideTimer=null;constructor(e){this.env=e?.env??ZX(),this.profile=$X(this.env),pMe(this.profile),this.terminalType=dZ(this.env),this._isDark=e?.isDark??BX(),this._writer=e?.writer??null,e?.isDark!==void 0&&VX(e.isDark)}get isDark(){return this._isDark}setDark(e){this._isDark=e,VX(e)}resolveAdaptiveColor(e){if(typeof e==`string`)return XX.parse(e);let t=this._isDark?e.dark:e.light;return XX.parse(t)}colorize(e,t,n){if(!t)return e;let r=this.resolveAdaptiveColor(t);if(!r)return e;let i=nZ(r,this.profile);return i?`\x1B[`+(n===`foreground`?i.fgSequence():i.bgSequence())+`m`+e+`\x1B[0m`:e}styledText(){return iZ(this.profile)}write(e){this._writer?this._writer(e):typeof process<`u`&&process.stdout?.isTTY&&process.stdout.write(e)}notify(e){if(!DMe(this.env))return;let t=this.terminalType,{title:n,body:r}=e,i=n?`${n}:\n${r}`:r;t===`kitty`&&(n?this.write(_Z(r,`d=0:p=title`,n)):this.write(_Z(r))),this.write(AMe(i)),this.write(kMe(i))}showProgress(e){if(!fZ(this.env))return;this.clearProgressTimer();let t=e.state??`normal`,n=Math.min(Math.max(0,e.percentage??0),100);switch(t){case`indeterminate`:this.write(`\x1B]9;4;3\x07`);break;case`error`:this.write(MMe(n));break;case`warning`:this.write(NMe(n));break;default:this.write(jMe(n));break}(t===`error`||n>=100)&&this.scheduleProgressHide()}hideProgress(){this.clearProgressTimer(),fZ(this.env)&&this.write(vZ)}async trackProgress(e){this.showProgress({state:`indeterminate`});try{let t=await e;return this.showProgress({percentage:100}),this.scheduleProgressHide(),t}catch(e){throw this.showProgress({percentage:100,state:`error`}),this.scheduleProgressHide(),e}}copyToClipboard(e){pZ(this.env)&&this.write(EMe(e))}clearClipboard(){pZ(this.env)&&this.write(`\x1B]52;c;\x07`)}hyperlink(e,t){return OMe(this.env)?mZ(e)+t+hZ():t}clearProgressTimer(){this._progressHideTimer&&=(clearTimeout(this._progressHideTimer),null)}scheduleProgressHide(){this.clearProgressTimer(),this._progressHideTimer=setTimeout(()=>{this.write(vZ),this._progressHideTimer=null},500)}},FMe=class{tui;terminal;terminalOutput;rootNode;bridge;container;exitCallbacks=[];exitPromise;resolveExit;exitOnCtrlC;ownsTui;suspendable;onSuspended;cleanupSuspend;originalWarningListeners;warningInterceptor;requestFullRedrawOnNextCommit=!1;constructor(e={}){this.exitOnCtrlC=e.exitOnCtrlC??!0,this.suspendable=e.suspendable??!1,this.onSuspended=e.onSuspended,e.tui?(this.tui=e.tui,this.terminal=e.tui.terminal,this.ownsTui=!1):e.terminal?(this.terminal=e.terminal,this.tui=new wY(this.terminal),this.ownsTui=!0):(this.terminal=new sje,this.tui=new wY(this.terminal),this.ownsTui=!0),this.terminalOutput=new PMe({writer:e=>this.terminal.write(e)}),this.rootNode=hX(`jar-root`),this.rootNode.yogaNode.setFlexDirection(0),this.rootNode.yogaNode.setFlexGrow(1),this.rootNode.onRender=()=>{this.bridge.notifyCommit(),this.requestFullRedrawOnNextCommit?(this.requestFullRedrawOnNextCommit=!1,this.tui.requestRender(!0)):this.tui.requestRender(),performance.clearMeasures()},this.bridge=new CMe(this.rootNode),this.tui.addChild(this.bridge),this.container=OX.createContainer(this.rootNode,0,null,!1,null,`jar`,()=>{},()=>{},()=>{},()=>{}),this.exitPromise=new Promise(e=>{this.resolveExit=e}),this.exitOnCtrlC&&this.tui.addInputListener(e=>{if(!pY(e)&&vY(e,`ctrl+c`))return this.exit(),{consume:!0}})}render(e){OX.updateContainerSync(e,this.container,null),OX.flushSyncWork()}requestFullRedraw(){this.requestFullRedrawOnNextCommit=!0,this.bridge.invalidate(),this.tui.requestRender(!0)}start(){this.ownsTui&&this.tui.start(),this.setupWarningInterceptor(),this.suspendable&&(this.cleanupSuspend=this.setupSuspendHandler())}exit(e){for(let t of this.exitCallbacks)t(e);this.unmount()}onExit(e){this.exitCallbacks.push(e)}unmount(){if(this.warningInterceptor&&=(H.removeListener(`warning`,this.warningInterceptor),void 0),this.originalWarningListeners){let e=H.listeners(`warning`);for(let t of this.originalWarningListeners)e.includes(t)||H.on(`warning`,t);this.originalWarningListeners=void 0}this.cleanupSuspend?.(),this.ownsTui&&this.disableInputProtocols(),OX.updateContainerSync(null,this.container,null),OX.flushSyncWork(),this.tui.removeChild(this.bridge),this.ownsTui&&this.tui.stop(),this.rootNode.yogaNode?.unsetMeasureFunc(),this.rootNode.yogaNode?.free(),this.rootNode.yogaNode=void 0,this.resolveExit()}cleanupTerminal(){this.ownsTui&&(this.cleanupSuspend?.(),this.disableInputProtocols(),this.tui.stop(),H.stdout.write(lZ))}disableInputProtocols(){this.terminal.write(OY),this.terminal.write(`\x1B[?2004l`),this.terminal.kittyProtocolActive&&this.terminal.write(`\x1B[<u`)}setupWarningInterceptor(){this.originalWarningListeners||(this.originalWarningListeners=H.rawListeners(`warning`),H.removeAllListeners(`warning`),this.warningInterceptor=()=>{},H.on(`warning`,this.warningInterceptor))}setupSuspendHandler(){if(H.platform===`win32`||!this.ownsTui)return()=>{};let e=!1,t=()=>{e=this.terminal.kittyProtocolActive,H.stdout.isTTY&&(this.disableInputProtocols(),H.stdout.write(lZ)),H.stdin.isTTY&&H.stdin.isRaw&&H.stdin.setRawMode(!1),this.onSuspended?.(),H.removeListener(`SIGTSTP`,t),H.kill(H.pid,`SIGTSTP`)},n=()=>{H.stdin.isTTY&&H.stdin.setRawMode(!0),H.stdout.isTTY&&(H.stdout.write(uZ),this.terminal.write(`\x1B[?2004h`),this.terminal.write(DY),e&&this.terminal.write(`\x1B[>7u`)),H.on(`SIGTSTP`,t),this.tui.requestRender(!0)};return H.on(`SIGTSTP`,t),H.on(`SIGCONT`,n),()=>{H.removeListener(`SIGTSTP`,t),H.removeListener(`SIGCONT`,n)}}waitUntilExit(){return this.exitPromise}getRootNode(){return this.rootNode}};function IMe(e,t){let n=new FMe(t),r=Z.createElement(PX,{tui:n.tui,terminal:n.terminal,terminalOutput:n.terminalOutput,exit:e=>n.exit(e),requestFullRedraw:()=>n.requestFullRedraw(),children:e});return n.render(r),n.start(),{rerender(e){let t=Z.createElement(PX,{tui:n.tui,terminal:n.terminal,terminalOutput:n.terminalOutput,exit:e=>n.exit(e),requestFullRedraw:()=>n.requestFullRedraw(),children:e});n.render(t)},unmount(){n.unmount()},waitUntilExit(){return n.waitUntilExit()},requestFullRedraw(){n.requestFullRedraw()},cleanupTerminal(){n.cleanupTerminal()}}}function Q({children:e,...t}){return(0,X.jsx)(`jar-view`,{style:{flexWrap:`nowrap`,flexDirection:`row`,flexGrow:0,flexShrink:1,...t,overflowX:t.overflowX??t.overflow??`visible`,overflowY:t.overflowY??t.overflow??`visible`},children:e})}function $({color:e,backgroundColor:t,dimColor:n=!1,bold:r=!1,italic:i=!1,underline:a=!1,strikethrough:o=!1,inverse:s=!1,wrap:c=`wrap`,transform:l,children:u}){if(u==null)return null;let d=(0,Z.useCallback)(c=>(n&&(c=iZ().dim().render(c)),e&&(c=rZ(c,e,`foreground`)),t&&(c=rZ(c,t,`background`)),r&&(c=iZ().bold().render(c)),i&&(c=iZ().italic().render(c)),a&&(c=iZ().underline().render(c)),o&&(c=iZ().strikethrough().render(c)),s&&(c=iZ().reverse().render(c)),l&&(c=l(c)),c),[e,t,n,r,i,a,o,s,l]);return(0,X.jsx)(`jar-text`,{style:{flexGrow:0,flexShrink:0,flexDirection:`row`,textWrap:c},internal_transform:d,children:u})}const LMe=/\x1b\[[\d:]*;(\d+)/;function RMe(e){let t=LMe.exec(e);return t?(parseInt(t[1],10)-1&8)!=0:!1}const yZ={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:``},bZ=(e,t={})=>{let{addInputListener:n}=(0,Z.use)(jX),r=(0,Z.useRef)(e);r.current=e,(0,Z.useEffect)(()=>{if(t.isActive!==!1)return n(e=>{if(pY(e))return;if(e.startsWith(`\x1B[200~`)){let t=e.indexOf(`\x1B[201~`),n=t===-1?e.slice(6):e.slice(6,t);yZ.upArrow=!1,yZ.downArrow=!1,yZ.leftArrow=!1,yZ.rightArrow=!1,yZ.pageDown=!1,yZ.pageUp=!1,yZ.home=!1,yZ.end=!1,yZ.return=!1,yZ.escape=!1,yZ.ctrl=!1,yZ.shift=!1,yZ.tab=!1,yZ.backspace=!1,yZ.delete=!1,yZ.meta=!1,yZ.super=!1,yZ.paste=!0,yZ.raw=e,r.current(n,{...yZ});return}let t=qAe(e),n=t?t.split(`+`):[],i=n[n.length-1]??``,a=n.includes(`ctrl`),o=n.includes(`shift`),s=n.includes(`alt`);yZ.upArrow=i===`up`,yZ.downArrow=i===`down`,yZ.leftArrow=i===`left`,yZ.rightArrow=i===`right`,yZ.pageDown=i===`pagedown`,yZ.pageUp=i===`pageup`,yZ.home=i===`home`,yZ.end=i===`end`,yZ.return=i===`return`||i===`enter`,yZ.escape=i===`escape`,yZ.ctrl=a,yZ.shift=o,yZ.tab=i===`tab`,yZ.backspace=i===`backspace`,yZ.delete=i===`delete`,yZ.meta=s,yZ.super=RMe(e),yZ.paste=!1,yZ.raw=e;let c=yZ,l=``;if(a&&i)l=i;else if(!c.upArrow&&!c.downArrow&&!c.leftArrow&&!c.rightArrow&&!c.pageDown&&!c.pageUp&&!c.home&&!c.end&&!c.return&&!c.escape&&!c.tab&&!c.backspace&&!c.delete){let t=XAe(e);t===void 0?e.length===1?l=e:i.length===1&&(l=i):l=t}r.current(l,{...c})})},[t.isActive,n])},zMe=()=>{let e=(0,Z.use)(MX);if(!e)throw Error(`useApp must be used within a jar render context`);return{exit:e.exit,requestFullRedraw:e.requestFullRedraw}},xZ=({isActive:e=!0,autoFocus:t=!1,id:n}={})=>{let{activeId:r,add:i,remove:a,activate:o,deactivate:s,focus:c}=(0,Z.use)(kX),l=(0,Z.useMemo)(()=>n??Math.random().toString().slice(2,7),[n]);return(0,Z.useEffect)(()=>(i(l,{autoFocus:t}),()=>{a(l)}),[l,t]),(0,Z.useEffect)(()=>{e?o(l):s(l)},[e,l]),{isFocused:!!l&&r===l,focus:c}};function SZ(){return(0,Z.use)(AX)}const CZ=()=>{let e=(0,Z.use)(NX);if(!e)throw Error(`useTerminal must be used within a jar render context`);return e.output},wZ=RegExp(`[\\x1b\\x9b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><~]|\\x1b\\][\\s\\S]*?(?:\\x07|\\x1b\\\\)`,`g`);function BMe(){return new RegExp(wZ.source,`g`)}function VMe(e){return e.replace(wZ,``)}function HMe(e){return e.replace(/[\x07\x1b\x9c]/g,``)}function TZ(e){return`\x1B]2;`+HMe(e)+`\x07`}var EZ=G(((e,t)=>{t.exports={name:`@codellm/cli`,version:`2.4.9-canary.0`,private:!0,bin:{abacusai:`dist/index.mjs`},files:[`dist`,`LICENSE.txt`],type:`module`,scripts:{"prepare-publish":`bun ./scripts/prepare-publish.ts`,build:`tsdown`,"check-types":`tsgo -b --noEmit`,test:`FORCE_COLOR=1 vitest run`,"test:watch":`FORCE_COLOR=1 vitest`,"test:ui":`FORCE_COLOR=1 vitest --ui`,"test:coverage":`FORCE_COLOR=1 vitest run --coverage`},dependencies:{"@clack/prompts":`^0.11.0`,"@codellm/agent":`workspace:*`,"@codellm/api":`workspace:*`,"@codellm/auth":`workspace:*`,"@codellm/comms":`workspace:*`,"@codellm/jar":`workspace:*`,"@codellm/logging":`workspace:*`,"@codellm/product":`workspace:*`,"@logtape/logtape":`^2.0.5`,"@orpc/client":`catalog:`,"@orpc/contract":`catalog:`,"@orpc/server":`catalog:`,"@sentry/node-core":`10.46.0`,"@slack/web-api":`^7.0.0`,"@tanstack/react-query":`^5.90.19`,"@vscode/ripgrep":`1.17.0`,"ansi-styles":`^6.2.3`,"beautiful-mermaid":`^1.1.3`,"cli-boxes":`^4.0.1`,"cli-highlight":`^2.1.11`,conf:`^15.0.2`,diff:`^8.0.3`,fzf:`^0.5.2`,"gradient-string":`^3.0.0`,immer:`^11.1.4`,"isomorphic-git":`^1.36.1`,marked:`^17.0.4`,"patchright-core":`^1.58.2`,react:`^19.2.3`,"react-compiler-runtime":`^1.0.0`,remend:`^1.2.2`,semver:`^7.7.4`,"shell-history":`^2.0.1`,"string-width":`^8.1.0`,"strip-ansi":`^7.2.0`,trash:`^9.0.0`,zod:`catalog:`},devDependencies:{"@codellm/configs":`workspace:*`,"@playwright/mcp":`^0.0.68`,"@types/diff":`^8.0.0`,"@types/node":`catalog:`,"@types/react":`^19.2.9`,"@types/semver":`^7.7.1`,"@typescript/native-preview":`catalog:`,"@vitejs/plugin-react":`^5.1.2`,"@vitest/coverage-v8":`^4.0.18`,"@vitest/ui":`^4.0.18`,"@xterm/addon-serialize":`^0.14.0`,"@xterm/headless":`^6.0.0`,"babel-plugin-react-compiler":`^1.0.0`,"cli-testing-library":`^3.0.1`,jsdom:`^27.4.0`,"node-pty":`^1.1.0`,"react-devtools-core":`^6.1.5`,"svg-term-cli":`^2.1.1`,tsdown:`^0.21.0`,vite:`catalog:`,vitest:`^4.0.18`},engines:{node:`>=18`}}})),DZ=Qe(EZ(),1);let OZ=null;function kZ(e){let t=(0,xJ.prerelease)(e);return t&&t.length>0&&typeof t[0]==`string`?t[0]:`latest`}function AZ(e){if(!e)return``;try{return y(e)}catch{return e}}function jZ(){return{invokedPath:AZ(process.argv[1]??``),execPath:AZ(process.execPath??process.argv[0]??``)}}function MZ(e){let t=hn.configDirName.replace(/^\./,``).replace(/[.*+?^${}()|[\]\\]/g,`\\$&`);return RegExp(`[/\\\\]\\.?${t}[/\\\\]bin[/\\\\]`,`i`).test(e)}function NZ(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 PZ(){let e=(process.env.npm_command??``).toLowerCase();if(e===`exec`||e===`dlx`)return!0;let{invokedPath:t,execPath:n}=jZ();return/[/\\]_npx[/\\]|[/\\]dlx[/\\]|[/\\]\.cache[/\\]/.test(t+`|`+n)}function FZ(){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}=jZ(),r=`${t}|${n}`;return/[/\\]\.?yarn[/\\]/.test(r)?`yarn`:/[/\\]\.?pnpm[/\\]/.test(r)?`pnpm`:/[/\\]\.bun[/\\]/.test(r)||process.versions.bun!==void 0&&!MZ(n)?`bun`:`npm`}function UMe(){let{execPath:e,invokedPath:t}=jZ();return NZ(t)||NZ(e)?!1:MZ(e)||MZ(t)}function IZ(){let e=`${hn.internalEnvPrefix}DEV`,t=process.env[e];if(t===`1`||t===`true`)return!0;let{invokedPath:n,execPath:r}=jZ();return!(MZ(r)||MZ(n)||NZ(n)||NZ(r)||process.env.npm_config_user_agent)}function WMe(){let{execPath:e}=jZ(),t=FZ(),n=PZ();return IZ()?{installationType:`development`,packageManager:t,isEphemeral:n,execPath:e}:UMe()?{installationType:`native`,packageManager:t,isEphemeral:n,execPath:e}:{installationType:`package-manager`,packageManager:t,isEphemeral:n,execPath:e}}function GMe(){return`${process.platform===`win32`?`win32`:process.platform===`darwin`?`darwin`:`linux`}-${process.arch===`arm64`?`arm64`:`x64`}`}async function KMe(e){let t=Date.now();if(OZ&&t-OZ.timestamp<6e4)return OZ.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 OZ={tags:r,timestamp:t},r}async function qMe(e,t,n,r){let i=t??kZ(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:FZ(),isEphemeral:PZ(),installationType:`native`,downloadUrl:l.url}}async function JMe(e,t){let n=t??kZ(e),r=FZ(),i=PZ(),a=(await KMe(gn.publishName))[n];return!a&&n!==`latest`||!a||a===e?null:{currentVersion:e,latestVersion:a,tag:n,packageManager:r,isEphemeral:i,installationType:`package-manager`}}async function LZ(e,t,n,r){let i=WMe();if(i.installationType===`native`)try{return await qMe(e,t,GMe(),n)}catch{return null}return i.installationType===`development`&&!r?.includeDev?null:await JMe(e,t)}function RZ(e){if(e.installationType===`native`)return`${hn.binName} upgrade`;let t=`${gn.publishName}@${e.tag}`;switch(e.packageManager){case`yarn`:return`yarn global add ${t}`;case`pnpm`:return`pnpm add -g ${t}`;case`bun`:return`bun add -g ${t}`;default:return`npm install -g ${t}`}}function zZ(e){try{return{ok:!0,output:le(RZ(e),{stdio:`pipe`,encoding:`utf-8`}).trim()}}catch(e){return{ok:!1,output:e instanceof Error&&`stderr`in e?String(e.stderr).trim():e instanceof Error?e.message:`Unknown error`}}}async function BZ(e){if(!e.downloadUrl)return{ok:!1,output:`No download URL`};let t=D.join(P.tmpdir(),`abacusai-update-${Date.now()}`),n=D.join(P.homedir(),hn.configDirName,`bin`),r=process.platform===`win32`,i=r?`${hn.binName}.exe`:hn.binName;try{await we.mkdir(t,{recursive:!0}),await we.mkdir(n,{recursive:!0});let a=D.join(t,r?`update.zip`:`update.tar.gz`),o=await fetch(e.downloadUrl);if(!o.ok)throw Error(`Download failed: ${o.status}`);let s=Buffer.from(await o.arrayBuffer());await we.writeFile(a,s),le(r?`powershell -Command "Expand-Archive -Path '${a}' -DestinationPath '${t}' -Force"`:`tar -xzf "${a}" -C "${t}"`,{stdio:`pipe`});let c=D.join(t,i),l=D.join(n,i);return await we.copyFile(c,l),r||await we.chmod(l,493),{ok:!0,output:`Updated to ${e.latestVersion}`}}catch(e){return{ok:!1,output:e instanceof Error?e.message:`Unknown error`}}finally{await we.rm(t,{recursive:!0,force:!0}).catch(()=>{})}}function YMe(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 VZ(e,t){let n=(await e.listLLMModels())?.result??[];return n.length||(process.stderr.write(`Error: No models available.
75144
75144
  `),process.exit(1)),t?YMe(n,t.toLowerCase())||(process.stderr.write(`Warning: Model "${t}" not found. Using default: ${n[0].llmName}\n`),n[0].llmName):n[0].llmName}const HZ=dt([`codellm`,`cli`,`exit`]),UZ=new Set,WZ=new Set,GZ=new Set;let KZ=!1,qZ=!1,JZ=null,YZ;async function XMe(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 XZ(e,t,n,r){if(KZ)return;r?.debug?.(`Executing exit handlers`,{shouldManuallyExit:e,isSynchronous:t,signal:n,asyncCallbacks:UZ.size,syncCallbacks:WZ.size}),KZ=!0,UZ.size>0&&t&&HZ.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:YZ===void 0?(typeof H.exitCode==`number`||typeof H.exitCode==`string`)&&(i=Number(H.exitCode)):i=YZ;let a=(t=!1)=>{(t||e)&&(JZ?JZ.call(H,i):H.exit(i))};for(let e of WZ)try{e(i)}catch(e){HZ.error`Error in synchronous exit hook: ${e}`}if(t){a();return}let o=[],s=0;for(let[e,t]of UZ)s=Math.max(s,t),o.push(Promise.resolve(e(i)).catch(e=>{HZ.error`Error in asynchronous exit hook: ${e}`}));let c=Array.from(GZ);c.length>0&&o.push(XMe(c));let l=setTimeout(()=>{a(!0)},s);try{await Promise.all(o),clearTimeout(l),a()}catch(e){clearTimeout(l),HZ.error`Error during exit cleanup: ${e}`,a(!0)}}function ZMe(){qZ||(qZ=!0,H.once(`beforeExit`,()=>{XZ(!0,!1,-128)}),H.once(`SIGINT`,()=>{XZ(!0,!1,2)}),H.once(`SIGTERM`,()=>{XZ(!0,!1,15)}),H.once(`exit`,()=>{XZ(!1,!0,0)}),H.on(`message`,e=>{e===`shutdown`&&XZ(!0,!0,-128)}),JZ||(JZ=H.exit.bind(H),H.exit=function(e){if(YZ===void 0&&(YZ=e??0),UZ.size===0&&GZ.size===0){if(JZ){JZ(e??0);return}H.exit(e??0)}XZ(!0,!1,-128).catch(e=>{HZ.error`Error during exit: ${e}`,JZ?JZ(1):H.exit(1)})}))}function ZZ(e,t){if(typeof e!=`function`)throw TypeError(`callback must be a function`);if(KZ)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}),ZMe();let n=t?.wait??0,r=t?.streams??[H.stdout,H.stderr];if(n>0){let t=[e,n];UZ.add(t);for(let e of r)GZ.add(e);return()=>{UZ.delete(t);for(let e of r)GZ.delete(e)}}return WZ.add(e),()=>{WZ.delete(e)}}function QZ(e){e!==void 0&&(H.exitCode=e),XZ(!0,!1,-128)}const $Z=`${hn.internalEnvPrefix}CLIENT_KIND`;function QMe(){let e=process.env[$Z]?.trim();if(!e)return tt.CLI;try{return nt(e)}catch{throw Error(`Invalid ${$Z} value: ${e}. Expected one of ${Object.values(tt).join(`, `)}.`)}}function eQ(e){process.stdout.write(JSON.stringify(e)+`
75145
75145
  `)}function $Me(e){try{return JSON.parse(e)}catch{return null}}async function eNe({agentArgs:e}){Al(`ndjson IPC host started`,`cli`);let t=QMe(),n=await PJ.create(),r=new Ul(n,Sn(),gn.userAgentNames.desktop,DZ.default.version);if(!n.isAuthenticated())try{(await r.getUserInfo())?.result?.email||(process.stderr.write(`Error: Not authenticated. Set ABACUS_DEVICE_CODE environment variable.
75146
75146
  `),process.exit(1))}catch{process.stderr.write(`Error: Not authenticated. Set ABACUS_DEVICE_CODE environment variable.
75147
- `),process.exit(1)}let i=process.cwd(),a=t===tt.COWORK?`desktop`:`cli`,o=new vq({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 VZ(r,e?.model),l=new Map,u=0,d=new hq(async e=>{let t=`perm-${++u}`;return eQ({type:`permission_needed`,permissionId:t,request:e}),new Promise(e=>{l.set(t,{resolve:e})})}),f=xd.Normal,p=e?.[`permission-mode`];if(p)switch(p){case`normal`:f=xd.Normal;break;case`accept-edits`:f=xd.AcceptEdits;break;case`plan`:f=xd.PlanMode;break;case`yolo`:f=xd.Yolo;break}let m=new mq({allowedDirectories:[i,...e?.[`add-dir`]?.map(e=>O.isAbsolute(e)?e:O.resolve(i,e))??[]],primaryWorkspace:i,apiClient:r,mode:f,model:c,permissionProvider:d,config:o,isPrintMode:!1,enablePromptRewrite:!1,supportsThoughtStreaming:!0,enableSkills:!0,cliAllowedTools:e?.[`allowed-tools`],cliDisallowedTools:e?.[`disallowed-tools`],clientType:t});m.onAutoRestart=e=>{tQ(m,e)},ZZ(async()=>{m.stop(),await new Promise(e=>setTimeout(e,200))},{wait:1e3}),eQ({type:`ready`,model:c,mode:f});let h=cq.loadSkills(i).then(()=>{eQ({type:`skills_loaded`,skills:cq.getAllMetadata()})}).catch(e=>{Dl(e),process.stderr.write(`Failed to load skills: ${e}\n`)}),g=o.get(`autoUpdate`)!==!1;IZ()||LZ(DZ.default.version,o.get(`updateChannel`),o.get(`baseUrl`)).then(async e=>{if(!e||(eQ({type:`update_available`,currentVersion:e.currentVersion,latestVersion:e.latestVersion}),!g))return;eQ({type:`update_downloading`,latestVersion:e.latestVersion});let t=e.installationType===`native`?await BZ(e):zZ(e);t.ok?eQ({type:`update_complete`,latestVersion:e.latestVersion}):eQ({type:`update_failed`,latestVersion:e.latestVersion,error:t.output||`Update failed`})}).catch(e=>{Dl(e)});let _=B.createInterface({input:process.stdin});_.on(`line`,async e=>{let t=e.trim();if(!t)return;let n=$Me(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),tQ(m,e,r);break}case`stop`:m.stop();break;case`list_skills`:h.then(()=>{eQ({type:`skills_loaded`,skills:cq.getAllMetadata()})});break;case`switch_conversation`:{let e=n.conversationId;e&&(m.switchConversation(e),eQ({type:`event`,event:{type:`status_changed`,status:`idle`}}));break}case`reset_conversation`:m.resetConversation(),eQ({type:`event`,event:{type:`status_changed`,status:`idle`}});break;case`set_mode`:{let e=tNe(n.mode??`DEFAULT`);m.setMode(e);break}case`set_model`:{let e=n.model;e&&(m.setModel(e),eQ({type:`event`,event:{type:`model_changed`,model:e}}));break}case`set_folder`:{let e=n.folder;e&&m.setWorkspace(e);break}case`enqueue`:{let e=n.message??``,t=n.hidden??!1;m.enqueue(e,{hidden:t}),eQ({type:`queue_updated`,messages:m.getQueue()});break}case`dequeue`:{let e=m.dequeue();eQ({type:`queue_updated`,messages:m.getQueue(),dequeued:e});break}case`get_queue`:eQ({type:`queue_updated`,messages:m.getQueue()});break;case`clear_queue`:m.clearQueue(),eQ({type:`queue_updated`,messages:[]});break;case`remove_from_queue`:{let e=n.index;typeof e==`number`&&m.removeAt(e),eQ({type:`queue_updated`,messages:m.getQueue()});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 tQ(e,t,n){try{for await(let r of e.send(t,{activeSkills:n}))eQ({type:`event`,event:r})}catch(e){Dl(e),eQ({type:`event`,event:{type:`error`,error:{message:e instanceof Error?e.message:String(e)}}})}}function tNe(e){switch(e){case`DEFAULT`:return xd.Normal;case`ACCEPTEDITS`:return xd.AcceptEdits;case`PLAN`:return xd.PlanMode;case`YOLO`:return xd.Yolo;default:return xd.Normal}}const nNe=dt([`codellm`,`cli`,`print-mode`]);async function rNe(){let e=await PJ.create();return{apiClient:new Ul(e,Sn(),gn.userAgentNames.print,DZ.default.version),authManager:e}}function nQ(e){process.stdout.write(JSON.stringify(e)+`
75147
+ `),process.exit(1)}let i=process.cwd(),a=t===tt.COWORK?`desktop`:`cli`,o=new vq({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 VZ(r,e?.model),l=new Map,u=0,d=new hq(async e=>{let t=`perm-${++u}`;return eQ({type:`permission_needed`,permissionId:t,request:e}),new Promise(e=>{l.set(t,{resolve:e})})}),f=xd.Normal,p=e?.[`permission-mode`];if(p)switch(p){case`normal`:f=xd.Normal;break;case`accept-edits`:f=xd.AcceptEdits;break;case`plan`:f=xd.PlanMode;break;case`yolo`:f=xd.Yolo;break}let m=new mq({allowedDirectories:[i,...e?.[`add-dir`]?.map(e=>O.isAbsolute(e)?e:O.resolve(i,e))??[]],primaryWorkspace:i,apiClient:r,mode:f,model:c,permissionProvider:d,config:o,isPrintMode:!1,enablePromptRewrite:!1,supportsThoughtStreaming:!0,enableSkills:!0,cliAllowedTools:e?.[`allowed-tools`],cliDisallowedTools:e?.[`disallowed-tools`],clientType:t});m.onAutoRestart=e=>{tQ(m,e)},ZZ(async()=>{m.stop(),await new Promise(e=>setTimeout(e,200))},{wait:1e3}),eQ({type:`ready`,model:c,mode:f});let h=cq.loadSkills(i).then(()=>{eQ({type:`skills_loaded`,skills:cq.getAllMetadata()})}).catch(e=>{Dl(e),process.stderr.write(`Failed to load skills: ${e}\n`)}),g=o.get(`autoUpdate`)!==!1;IZ()||LZ(DZ.default.version,o.get(`updateChannel`),o.get(`baseUrl`)).then(async e=>{if(!e||(eQ({type:`update_available`,currentVersion:e.currentVersion,latestVersion:e.latestVersion}),!g))return;eQ({type:`update_downloading`,latestVersion:e.latestVersion});let t=e.installationType===`native`?await BZ(e):zZ(e);t.ok?eQ({type:`update_complete`,latestVersion:e.latestVersion}):eQ({type:`update_failed`,latestVersion:e.latestVersion,error:t.output||`Update failed`})}).catch(e=>{Dl(e)});let _=B.createInterface({input:process.stdin});_.on(`line`,async e=>{let t=e.trim();if(!t)return;let n=$Me(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),tQ(m,e,r);break}case`stop`:m.stop();break;case`list_skills`:h.then(()=>{eQ({type:`skills_loaded`,skills:cq.getAllMetadata()})});break;case`switch_conversation`:{let e=n.conversationId;e&&(m.switchConversation(e),eQ({type:`event`,event:{type:`status_changed`,status:`idle`}}));break}case`reset_conversation`:m.resetConversation(),eQ({type:`event`,event:{type:`status_changed`,status:`idle`}});break;case`set_mode`:{let e=tNe(n.mode??`DEFAULT`);m.setMode(e);break}case`set_model`:{let e=n.model;e&&(m.setModel(e),eQ({type:`event`,event:{type:`model_changed`,model:e}}));break}case`set_folder`:{let e=n.folder;e&&m.setWorkspace(e);break}case`enqueue`:{let e=n.message??``,t=n.hidden??!1;m.nq(e,{hidden:t}),eQ({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}:{}});eQ({type:`queue_updated`,messages:m.getQueueEntries(),dequeued:r.map(e=>e.message)});break}case`get_queue`:{let e=n.includeHidden??!1;eQ({type:`queue_updated`,messages:m.getQueueEntries({includeHidden:e})});break}case`clear_queue`:{let e=n.includeHidden??!1;m.clearQueue({includeHidden:e}),eQ({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)}eQ({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 tQ(e,t,n){try{for await(let r of e.send(t,{activeSkills:n}))eQ({type:`event`,event:r})}catch(e){Dl(e),eQ({type:`event`,event:{type:`error`,error:{message:e instanceof Error?e.message:String(e)}}})}}function tNe(e){switch(e){case`DEFAULT`:return xd.Normal;case`ACCEPTEDITS`:return xd.AcceptEdits;case`PLAN`:return xd.PlanMode;case`YOLO`:return xd.Yolo;default:return xd.Normal}}const nNe=dt([`codellm`,`cli`,`print-mode`]);async function rNe(){let e=await PJ.create();return{apiClient:new Ul(e,Sn(),gn.userAgentNames.print,DZ.default.version),authManager:e}}function nQ(e){process.stdout.write(JSON.stringify(e)+`
75148
75148
  `)}async function iNe(e,t){if(e?.resume)return e.resume;if(e?.continue)try{return((await t.getConversationsList(`CODE_LLM_AGENT`))?.result??[]).sort((e,t)=>{let n=e.lastEventCreatedAt?new Date(e.lastEventCreatedAt).getTime():0;return(t.lastEventCreatedAt?new Date(t.lastEventCreatedAt).getTime():0)-n})[0]?.deploymentConversationId}catch{}return e?.conversationId}async function aNe({agentArgs:e}){Al(`print-mode started`,`cli`);let{apiClient:t,authManager:n}=await rNe(),r=process.cwd(),i=new vq({cwd:r,extraSources:[{read:async()=>({client:`cli`})}]});await i.load(),IZ()||LZ(DZ.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: ${RZ(e)}\n`;process.stderr.write(t)}}).catch(e=>{Dl(e)});let a=i.get(`baseUrl`);if(a){try{new URL(a)}catch{nNe.error`Invalid baseUrl: ${a}`,process.exit(1)}t.setUrl(a),t.resetEndpoints(),await t.getApiEndpoint()}!n.isAuthenticated()&&!n.isEnvAuth()&&(process.stderr.write(`Not authenticated. Set ${hn.envPrefix}API_KEY environment variable or run interactively to log in.\n`),process.exit(1));let o=e?.[`output-format`]??`text`,s=await VZ(t,e?.model),c=xd.Yolo,l=e?.[`permission-mode`];if(l)switch(l){case`normal`:c=xd.Normal;break;case`accept-edits`:c=xd.AcceptEdits;break;case`plan`:c=xd.PlanMode;break;default:c=xd.Yolo;break}let u=new mq({allowedDirectories:[r,...e?.[`add-dir`]?.map(e=>O.isAbsolute(e)?e:O.resolve(r,e))??[]],primaryWorkspace:r,apiClient:t,mode:c,model:s,permissionProvider:new zOe,config:i,isPrintMode:!0,enablePromptRewrite:!1,supportsThoughtStreaming:!0,cliAllowedTools:e?.[`allowed-tools`],cliDisallowedTools:e?.[`disallowed-tools`],clientType:tt.CLI});ZZ(async()=>{u.stop(),await new Promise(e=>setTimeout(e,200))},{wait:1e3});let d=await iNe(e,t);if(d)try{await u.loadConversation(d)}catch(e){throw Dl(e),e}let f=e?.prompt??``;process.env.DEEPAGENT_HIGH_QUALITY===`true`&&(f=`
75149
75149
  IMPORTANT INSTRUCTIONS: Your task is to follow the <task_description> EXACTLY and verify the solution within the FIXED TIME LIMIT.
75150
75150
  A few things to keep in mind (Add Relevant ONES BELOW AS TODOS):
@@ -75243,8 +75243,10 @@ https://github.com/highlightjs/highlight.js/issues/2277`),a=e,i=t);let o={code:i
75243
75243
  `,`utf8`)}function N4(e){let t=[],n=0;for(let r=0;r<e.length;r++)if(e[r]===10){let i=e.subarray(n,r).toString(`utf8`).trim();i&&t.push(i),n=r+1}return[t,e.subarray(n)]}function hHe(e,t){let n=rHe(t,{});try{s.existsSync(e)&&s.unlinkSync(e)}catch{}let r=V.createServer(e=>{let t=new pHe(t=>{!e.destroyed&&e.writable&&e.write(M4(t))}),r=Buffer.alloc(0);e.on(`data`,async e=>{r=Buffer.concat([r,e]);let[i,a]=N4(r);r=a;for(let e of i)try{await t.message(e,n)}catch(e){Dl(e,{context:`rpc-deserialization`})}}),e.on(`close`,()=>{t.close()}),e.on(`error`,n=>{Dl(n,{context:`socket-server`}),e.destroy(),t.close()})});return new Promise((t,n)=>{r.on(`error`,e=>{Dl(e,{context:`socket-server`}),n(e)}),r.listen(e,()=>{r.removeListener(`error`,n),r.on(`error`,e=>{Dl(e,{context:`socket-server`})});try{s.chmodSync(e,438)}catch{}t({getSocketPath:()=>e,dispose:()=>{r.close();try{s.existsSync(e)&&s.unlinkSync(e)}catch{}}})})})}var gHe=class{peer;constructor(e){this.peer=e}async call(e){let t=await this.peer.request(e);return{...t,body:()=>Promise.resolve(t.body)}}},_He=class extends ZVe{constructor(e){super(new gHe(e),{url:`orpc:/`})}};function vHe(e,t){let n=t?.timeoutMs??2e3;return new Promise((t,r)=>{let i=V.connect(e),a=setTimeout(()=>{i.destroy(),r(Error(`Connection to ${e} timed out after ${n}ms`))},n);i.on(`connect`,()=>{clearTimeout(a);let e=new dHe(e=>{!i.destroyed&&i.writable&&i.write(M4(e))}),n=Buffer.alloc(0);i.on(`data`,async t=>{n=Buffer.concat([n,t]);let[r,i]=N4(n);n=i;for(let t of r)try{await e.message(t)}catch(e){Dl(e,{context:`rpc-deserialization`})}}),i.on(`close`,()=>e.close()),i.on(`error`,t=>{Dl(t,{context:`socket-client`}),i.destroy(),e.close()}),t({link:new _He(e),dispose:()=>{e.close(),i.destroy()}})}),i.on(`error`,e=>{clearTimeout(a),Dl(e,{context:`socket-connect`}),r(e)})})}const P4=Symbol(`ORPC_LAZY_SYMBOL`);function F4(e,t={}){return{[P4]:{loader:e,meta:t}}}function I4(e){return(typeof e==`object`||typeof e==`function`)&&e!==null&&P4 in e}function L4(e){return e[P4].meta}function R4(e){return I4(e)?e[P4].loader():Promise.resolve({default:e})}function yHe(e,t){if(t.length>e.length)return!1;for(let n=0;n<e.length;n++){if(t[n]===void 0)return!0;if(e[n]!==t[n])return!1}return!0}function bHe(e,t,n){return n.dedupeLeading&&yHe(t,e)?t:[...e,...t]}function z4(e,t){return[...e,t]}var B4=class{"~orpc";constructor(e){this[`~orpc`]=e}};function V4(e){return e instanceof B4?!0:d4(e)&&`middlewares`in e[`~orpc`]&&`inputValidationIndex`in e[`~orpc`]&&`outputValidationIndex`in e[`~orpc`]&&`handler`in e[`~orpc`]}function xHe(e,t){return{...e,...t}}function SHe(e){return new Proxy(e,{get(t,n){return typeof n==`string`?(...t)=>{let r=C2(t),i=e[n];return new q2(n,{defined:!!i,status:i?.status,message:r.message??i?.message,data:r.data,cause:r.cause})}:Reflect.get(t,n)}})}function CHe(e){return{output:e,context:{}}}function H4(e,...t){let n=C2(t);return async(...[t,r])=>{let i=w2(n.path),{default:a}=await R4(e),o=r?.context??{},s=await V2(n.context??{},o),c=SHe(a[`~orpc`].errorMap),l=async e=>e instanceof q2?await WVe(a[`~orpc`].errorMap,e):e;try{let e=await A2({name:`call_procedure`,signal:r?.signal},e=>(e?.setAttribute(`procedure.path`,[...i]),I2(w2(n.interceptors),{context:s,input:t,errors:c,path:i,procedure:a,signal:r?.signal,lastEventId:r?.lastEventId},e=>EHe(e.procedure,e))));return N2(e)?e instanceof r4?e:PVe(e,o4(F2({name:`consume_event_iterator_output`,signal:r?.signal},e),{value:e=>e,error:e=>l(e)})):e}catch(e){throw await l(e)}}}async function wHe(e,t){let n=e[`~orpc`].inputSchema;return n?A2({name:`validate_input`},async()=>{let e=await n[`~standard`].validate(t);if(e.issues)throw new q2(`BAD_REQUEST`,{message:`Input validation failed`,data:{issues:e.issues},cause:new c4({message:`Input validation failed`,issues:e.issues,data:t})});return e.value}):t}async function THe(e,t){let n=e[`~orpc`].outputSchema;return n?A2({name:`validate_output`},async()=>{let e=await n[`~standard`].validate(t);if(e.issues)throw new q2(`INTERNAL_SERVER_ERROR`,{message:`Output validation failed`,cause:new c4({message:`Output validation failed`,issues:e.issues,data:t})});return e.value}):t}async function EHe(e,t){let n=e[`~orpc`].middlewares,r=Math.min(Math.max(0,e[`~orpc`].inputValidationIndex),n.length),i=Math.min(Math.max(0,e[`~orpc`].outputValidationIndex),n.length),a=async(o,s,c)=>{let l=c;o===r&&(l=await wHe(e,l));let u=n[o],d=u?await A2({name:`middleware.${u.name}`,signal:t.signal},async e=>(e?.setAttribute(`middleware.index`,o),e?.setAttribute(`middleware.name`,u.name),(await u({...t,context:s,next:async(...[e])=>{let t=e?.context??{};return{output:await a(o+1,xHe(s,t),l),context:t}}},l,CHe)).output)):await A2({name:`handler`,signal:t.signal},()=>e[`~orpc`].handler({...t,context:s,input:l}));return o===i?await THe(e,d):d};return a(0,t.context,t.input)}const U4=Symbol(`ORPC_HIDDEN_ROUTER_CONTRACT`);function W4(e,t){return new Proxy(e,{get(e,n){return n===U4?t:Reflect.get(e,n)}})}function DHe(e){return e[U4]}function G4(e,t){let n=e;for(let e=0;e<t.length;e++){let r=t[e];if(!n||V4(n))return;if(!I4(n)){n=n[r];continue}let i=n,a=t.slice(e);return F4(async()=>R4(G4((await R4(i)).default,a)),L4(i))}return n}function K4(e){return new Proxy(e,{get(t,n){return typeof n==`string`?K4(G4(e,[n])):Reflect.get(t,n)}})}function q4(e,t){if(I4(e)){let n=L4(e),r=n?.prefix?v4(t.prefix,n?.prefix):t.prefix;return K4(F4(async()=>{let{default:n}=await R4(e);return R4(q4(n,t))},{...n,prefix:r}))}if(V4(e)){let n=bHe(t.middlewares,e[`~orpc`].middlewares,{dedupeLeading:t.dedupeLeadingMiddlewares}),r=n.length-e[`~orpc`].middlewares.length;return new B4({...e[`~orpc`],route:b4(e[`~orpc`].route,t),errorMap:l4(t.errorMap,e[`~orpc`].errorMap),middlewares:n,inputValidationIndex:e[`~orpc`].inputValidationIndex+r,outputValidationIndex:e[`~orpc`].outputValidationIndex+r})}let n={};for(let r in e)n[r]=q4(e[r],t);return n}function J4(e,t,n=[]){let r=e.router,i=DHe(e.router);if(i!==void 0&&(r=i),I4(r))n.push({router:r,path:e.path});else if(d4(r))t({contract:r,path:e.path});else for(let i in r)J4({router:r[i],path:[...e.path,i]},t,n);return n}function OHe(e,t){return new B4({...e[`~orpc`],errorMap:t[`~orpc`].errorMap,route:t[`~orpc`].route,meta:t[`~orpc`].meta})}const kHe={initialInputValidationIndex:0,initialOutputValidationIndex:0,dedupeLeadingMiddlewares:!0};function Y4(e,t){return t===void 0?kHe[e]:t}function X4(e){let t=((...t)=>e(...t));return t.mapInput=t=>X4((n,r,...i)=>e(n,t(r),...i)),t.concat=(t,n)=>{let r=n?X4(t).mapInput(n):t;return X4((t,n,i,...a)=>e({...t,next:(...[e])=>r({...t,context:{...t.context,...e?.context},next:(...[n])=>t.next({context:{...e?.context,...n?.context}})},n,i,...a)},n,i,...a))},t}function AHe(e){return async t=>{try{return[null,await e(t)]}catch(e){if(e instanceof Error&&`digest`in e&&typeof e.digest==`string`&&e.digest.startsWith(`NEXT_`)||e instanceof Response&&`options`in e&&R2(e.options)||R2(e)&&e.isNotFound===!0)throw e;return[J2(e).toJSON(),void 0]}}}var jHe=class e extends B4{errors(t){return new e({...this[`~orpc`],errorMap:l4(this[`~orpc`].errorMap,t)})}meta(t){return new e({...this[`~orpc`],meta:g4(this[`~orpc`].meta,t)})}route(t){return new e({...this[`~orpc`],route:_4(this[`~orpc`].route,t)})}use(t,n){let r=n?X4(t).mapInput(n):t;return new e({...this[`~orpc`],middlewares:z4(this[`~orpc`].middlewares,r)})}callable(...e){let t=H4(this,...e);return new Proxy(t,{get:(e,t)=>Reflect.has(this,t)?Reflect.get(this,t):Reflect.get(e,t),has:(e,t)=>Reflect.has(this,t)||Reflect.has(e,t)})}actionable(...e){let t=AHe(H4(this,...e));return new Proxy(t,{get:(e,t)=>Reflect.has(this,t)?Reflect.get(this,t):Reflect.get(e,t),has:(e,t)=>Reflect.has(this,t)||Reflect.has(e,t)})}},Z4=class e{"~orpc";constructor(e){this[`~orpc`]=e}$config(t){let n=this[`~orpc`].inputValidationIndex-Y4(`initialInputValidationIndex`,this[`~orpc`].config.initialInputValidationIndex),r=this[`~orpc`].outputValidationIndex-Y4(`initialOutputValidationIndex`,this[`~orpc`].config.initialOutputValidationIndex);return new e({...this[`~orpc`],config:t,dedupeLeadingMiddlewares:Y4(`dedupeLeadingMiddlewares`,t.dedupeLeadingMiddlewares),inputValidationIndex:Y4(`initialInputValidationIndex`,t.initialInputValidationIndex)+n,outputValidationIndex:Y4(`initialOutputValidationIndex`,t.initialOutputValidationIndex)+r})}$context(){return new e({...this[`~orpc`],middlewares:[],inputValidationIndex:Y4(`initialInputValidationIndex`,this[`~orpc`].config.initialInputValidationIndex),outputValidationIndex:Y4(`initialOutputValidationIndex`,this[`~orpc`].config.initialOutputValidationIndex)})}$meta(t){return new e({...this[`~orpc`],meta:t})}$route(t){return new e({...this[`~orpc`],route:t})}$input(t){return new e({...this[`~orpc`],inputSchema:t})}middleware(e){return X4(e)}errors(t){return new e({...this[`~orpc`],errorMap:l4(this[`~orpc`].errorMap,t)})}use(t,n){let r=n?X4(t).mapInput(n):t;return new e({...this[`~orpc`],middlewares:z4(this[`~orpc`].middlewares,r)})}meta(t){return new e({...this[`~orpc`],meta:g4(this[`~orpc`].meta,t)})}route(t){return new e({...this[`~orpc`],route:_4(this[`~orpc`].route,t)})}input(t){return new e({...this[`~orpc`],inputSchema:t,inputValidationIndex:Y4(`initialInputValidationIndex`,this[`~orpc`].config.initialInputValidationIndex)+this[`~orpc`].middlewares.length})}output(t){return new e({...this[`~orpc`],outputSchema:t,outputValidationIndex:Y4(`initialOutputValidationIndex`,this[`~orpc`].config.initialOutputValidationIndex)+this[`~orpc`].middlewares.length})}handler(e){return new jHe({...this[`~orpc`],handler:e})}prefix(t){return new e({...this[`~orpc`],prefix:v4(this[`~orpc`].prefix,t)})}tag(...t){return new e({...this[`~orpc`],tags:y4(this[`~orpc`].tags,t)})}router(e){return q4(e,this[`~orpc`])}lazy(e){return q4(F4(e),this[`~orpc`])}};new Z4({config:{},route:{},meta:{},errorMap:{},inputValidationIndex:Y4(`initialInputValidationIndex`),outputValidationIndex:Y4(`initialOutputValidationIndex`),middlewares:[],dedupeLeadingMiddlewares:!0});function Q4(e,t,n){return d4(e)?new Z4({...e[`~orpc`],config:t,middlewares:n,inputValidationIndex:Y4(`initialInputValidationIndex`,t?.initialInputValidationIndex)+n.length,outputValidationIndex:Y4(`initialOutputValidationIndex`,t?.initialOutputValidationIndex)+n.length,dedupeLeadingMiddlewares:Y4(`dedupeLeadingMiddlewares`,t.dedupeLeadingMiddlewares)}):new Proxy(e,{get:(r,i)=>{if(typeof i!=`string`)return Reflect.get(r,i);let a;i===`middleware`?a=e=>X4(e):i===`use`?a=r=>Q4(e,t,z4(n,r)):i===`router`?a=r=>W4(q4(r,{middlewares:n,errorMap:{},prefix:void 0,tags:void 0,dedupeLeadingMiddlewares:Y4(`dedupeLeadingMiddlewares`,t.dedupeLeadingMiddlewares)}),e):i===`lazy`&&(a=r=>W4(q4(F4(r),{middlewares:n,errorMap:{},prefix:void 0,tags:void 0,dedupeLeadingMiddlewares:Y4(`dedupeLeadingMiddlewares`,t.dedupeLeadingMiddlewares)}),e));let o=eHe(r,[i]);if(!o)return a??o;let s=Q4(o,t,n);return a?new Proxy(a,{get(e,t){return Reflect.get(s,t)}}):s}})}function $4(e,t={}){let n=Q4(e,t,[]),r=new Proxy(n,{get:(t,n)=>{let i;n===`$context`?i=()=>r:n===`$config`&&(i=t=>$4(e,t));let a=Reflect.get(t,n);return!i||!a||typeof a!=`function`&&typeof a!=`object`?i||a:new Proxy(i,{get(e,t){return Reflect.get(a,t)}})}});return r}var MHe=class{plugins;constructor(e=[]){this.plugins=[...e].sort((e,t)=>(e.order??0)-(t.order??0))}init(e,t){for(let n of this.plugins)n.init?.(e,t)}},NHe=class{constructor(e,t,n,r){this.matcher=t,this.codec=n,new MHe(r.plugins).init(r,e),this.interceptors=w2(r.interceptors),this.clientInterceptors=w2(r.clientInterceptors),this.rootInterceptors=w2(r.rootInterceptors),this.matcher.init(e)}interceptors;clientInterceptors;rootInterceptors;async handle(e,t){let n=t.prefix?.replace(/\/$/,``)||void 0;return n&&!e.url.pathname.startsWith(`${n}/`)&&e.url.pathname!==n?{matched:!1,response:void 0}:I2(this.rootInterceptors,{...t,request:e,prefix:n},async t=>A2({name:`${e.method} ${e.url.pathname}`},async e=>{let n;try{return await I2(this.interceptors,t,async({request:t,context:r,prefix:i})=>{let a=t.method,o=t.url,s=i?o.pathname.replace(i,``):o.pathname,c=await A2({name:`find_procedure`},()=>this.matcher.match(a,`/${s.replace(/^\/|\/$/g,``)}`));if(!c)return{matched:!1,response:void 0};e?.updateName(`${T2}.${c.path.join(`/`)}`),e?.setAttribute(`rpc.system`,T2),e?.setAttribute(`rpc.method`,c.path.join(`.`)),n=`decode_input`;let l=await A2({name:`decode_input`},()=>this.codec.decode(t,c.params,c.procedure));n=void 0,N2(l)&&(l=F2({name:`consume_event_iterator_input`,signal:t.signal},l));let u=H4(c.procedure,{context:r,path:c.path,interceptors:this.clientInterceptors});n=`call_procedure`;let d=await u(l,{signal:t.signal,lastEventId:i4(t.headers[`last-event-id`])});return n=void 0,{matched:!0,response:this.codec.encode(d,c.procedure)}})}catch(t){n!==`call_procedure`&&k2(e,t);let r=n===`decode_input`&&!(t instanceof q2)?new q2(`BAD_REQUEST`,{message:`Malformed request. Ensure the request body is properly formatted and the 'Content-Type' header is set correctly.`,cause:t}):J2(t);return{matched:!0,response:this.codec.encodeError(r)}}}))}},PHe=class{constructor(e){this.serializer=e}async decode(e,t,n){let r=e.method===`GET`?kVe(e.url.searchParams.getAll(`data`).at(-1)):await e.body();return this.serializer.deserialize(r)}encode(e,t){return{status:200,headers:{},body:this.serializer.serialize(e)}}encodeError(e){return{status:e.status,headers:{},body:this.serializer.serialize(e.toJSON())}}},FHe=class{filter;tree=new jVe;pendingRouters=[];constructor(e={}){this.filter=e.filter??!0}init(e,t=[]){let n=J4({router:e,path:t},t=>{if(!V2(this.filter,t))return;let{path:n,contract:r}=t,i=m4(n);V4(r)?this.tree[i]={path:n,contract:r,procedure:r,router:e}:this.tree[i]={path:n,contract:r,procedure:void 0,router:e}});this.pendingRouters.push(...n.map(e=>({...e,httpPathPrefix:m4(e.path)})))}async match(e,t){if(this.pendingRouters.length){let e=[];for(let n of this.pendingRouters)if(t.startsWith(n.httpPathPrefix)){let{default:e}=await R4(n.router);this.init(e,n.path)}else e.push(n);this.pendingRouters=e}let n=this.tree[t];if(n){if(!n.procedure){let{default:e}=await R4(G4(n.router,n.path));if(!V4(e))throw Error(`
75244
75244
  [Contract-First] Missing or invalid implementation for procedure at path: ${m4(n.path)}.
75245
75245
  Ensure that the procedure is correctly defined and matches the expected contract.
75246
- `);n.procedure=OHe(e,n.contract)}return{path:n.path,procedure:n.procedure}}}},IHe=class extends NHe{constructor(e,t={}){let n=new h4(new p4(t)),r=new FHe(t),i=new PHe(n);super(e,r,i,t)}},LHe=class{socketServer;socketPath;editorState={file:void 0,startLine:void 0,endLine:void 0};onEditorStateCallback=null;pendingDecisions=new Map;constructor(){let e=D.join(P.homedir(),hn.configDirName,`cli`);this.socketPath=D.join(e,`${process.pid}.sock`)}getEditorState(){return{...this.editorState}}onEditorChange(e){this.onEditorStateCallback=e}waitForDecision(e,t){return new Promise((n,r)=>{if(t?.aborted){r(Error(`Aborted`));return}let i=()=>{t?.removeEventListener(`abort`,a),this.pendingDecisions.delete(e)},a=()=>{i(),r(Error(`Aborted`))};t?.addEventListener(`abort`,a,{once:!0}),this.pendingDecisions.set(e,{resolve:e=>{i(),n(e)},cleanup:i})})}async start(){let e=D.dirname(this.socketPath);s.existsSync(e)||s.mkdirSync(e,{recursive:!0});let t=$4(tHe),n=t.router({editorStateChanged:t.editorStateChanged.handler(async({input:e})=>(this.editorState={file:e.file??void 0,startLine:e.startLine,endLine:e.endLine},this.onEditorStateCallback?.(this.editorState),{ok:!0})),toolDecision:t.toolDecision.handler(async({input:e})=>{let t=this.pendingDecisions.get(e.toolId);return t&&t.resolve(e.decision),{ok:!0}})});this.socketServer=await hHe(this.socketPath,new IHe(n))}dispose(){for(let[,e]of this.pendingDecisions)e.cleanup();this.pendingDecisions.clear(),this.socketServer?.dispose(),this.socketServer=void 0}},RHe=class{client=null;disposeSocket=null;currentFile=void 0;selectionStartLine=void 0;selectionEndLine=void 0;onFileChangeCallback=null;constructor(e){this.pushServer=e}findSocketPath(){let e=process.env[hn.socketEnvVar];if(e&&c.existsSync(e))return e;try{let e=O.join(ee.homedir(),hn.configDirName,hn.ideDirName),t=c.readdirSync(e).filter(e=>e.endsWith(`.sock`));if(t.length===0)return null;let n=null;for(let r of t){let t=O.join(e,r);try{let e=c.statSync(t);(!n||e.mtimeMs>n.mtime)&&(n={path:t,mtime:e.mtimeMs})}catch{}}if(n&&c.existsSync(n.path))return n.path}catch{}return null}async connect(){try{let e=this.findSocketPath();if(!e)return!1;let t=await vHe(e,{timeoutMs:2e3});this.client=s4(t.link),this.disposeSocket=()=>t.dispose(),await this.client.register({cliSocketPath:this.pushServer.socketPath,pid:process.pid});let n=this.pushServer.getEditorState();return this.currentFile=n.file,this.selectionStartLine=n.startLine,this.selectionEndLine=n.endLine,this.pushServer.onEditorChange(e=>{this.currentFile=e.file,this.selectionStartLine=e.startLine,this.selectionEndLine=e.endLine,this.onFileChangeCallback?.(e.file,e.startLine,e.endLine)}),!0}catch{return!1}}getCurrentFile(){return this.currentFile}getSelectionRange(){return{startLine:this.selectionStartLine,endLine:this.selectionEndLine}}isConnected(){return this.client!==null}onFileChange(e){this.onFileChangeCallback=e}async showDiff(e){if(!this.client)return!1;try{return(await this.client.showDiff({...e,cliSocketPath:this.pushServer.socketPath})).success}catch{return!1}}async showToolView(e){if(!this.client)return!1;try{return(await this.client.showToolView({...e,cliSocketPath:this.pushServer.socketPath})).success}catch{return!1}}async notifyDiffDecision(e){if(!this.client)throw Error(`Not connected to extension`);await this.client.notifyDiffDecision(e)}async openPlanFile(e){if(!this.client)throw Error(`Not connected to extension`);return{opened:(await this.client.openFile({file:e})).success}}async getDiagnostics(e){if(!this.client)throw Error(`Not connected to extension`);return this.client.getDiagnostics({...e&&{files:e}})}dispose(){this.disposeSocket?.(),this.disposeSocket=null,this.client=null,this.currentFile=void 0,this.selectionStartLine=void 0,this.selectionEndLine=void 0,this.onFileChangeCallback=null}};const e3=(0,Z.createContext)(null);function t3(){let e=(0,Z.use)(e3);if(!e)throw Error(`useExtensionFile must be used within ExtensionFileProvider`);return e}function zHe({children:e,initialFile:t}){let[n,r]=(0,Z.useState)(t),[i,a]=(0,Z.useState)(void 0),[o,s]=(0,Z.useState)(void 0),[c,l]=(0,Z.useState)(null),[u,d]=(0,Z.useState)(null),f=(0,Z.useRef)(null),p=(0,Z.useRef)(null);return(0,Z.useEffect)(()=>{let e=!1;return(async()=>{let t=new LHe;try{await t.start()}catch{}if(e){t.dispose();return}p.current=t,d(t),t.onEditorChange(e=>{r(e.file),a(e.startLine),s(e.endLine)});for(let n of[0,...[500,1e3,2e3,3e3,4e3]]){if(e||(n>0&&await new Promise(e=>setTimeout(e,n)),e))return;try{let n=new RHe(t);if(await n.connect()){if(e){n.dispose();return}let i=t.getEditorState();r(i.file),a(i.startLine),s(i.endLine),n.onFileChange((e,t,n)=>{r(e),a(t),s(n)}),f.current=n,l(n);return}}catch{}}})(),()=>{e=!0,f.current&&(f.current.dispose(),f.current=null,l(null)),p.current&&(p.current.dispose(),p.current=null,d(null))}},[]),(0,X.jsx)(e3.Provider,{value:{currentFile:n,selectionStartLine:i,selectionEndLine:o,connection:c,pushServer:u},children:e})}const n3=(0,Z.createContext)(null);function BHe({children:e}){let[t,n]=(0,Z.useState)(`idle`),r=(0,Z.useCallback)(()=>n(`upload`),[]),i=(0,Z.useCallback)(()=>n(`download`),[]),a=(0,Z.useCallback)(()=>n(`idle`),[]),o=(0,Z.useMemo)(()=>({activity:t,setActivity:n,startUpload:r,startDownload:i,stopActivity:a}),[t,r,i,a]);return(0,X.jsx)(n3.Provider,{value:o,children:e})}function r3(){let e=(0,Z.use)(n3);if(!e)throw Error(`useNetworkActivity must be used within NetworkActivityProvider`);return e}const i3=(0,Z.createContext)(null),VHe=()=>{let e=(0,Z.use)(i3);if(!e)throw Error(`useNotification must be used within NotificationProvider`);return e},HHe=({children:e})=>{let{isFocused:t}=SZ(),n=CZ(),r=(0,Z.useRef)(t);r.current=t;let i=(0,Z.useCallback)((e,t)=>{r.current||n.notify({body:e,title:t})},[n]),a=(0,Z.useCallback)(e=>{r.current||n.notify({body:e,title:`Action Required`})},[n]),o=(0,Z.useCallback)(e=>{r.current||n.notify({body:e,title:`Task Complete`})},[n]),s=(0,Z.useMemo)(()=>({notifyIfUnfocused:i,notifyActionRequired:a,notifyTaskComplete:o}),[i,a,o]);return(0,X.jsx)(i3.Provider,{value:s,children:e})},a3=(0,Z.createContext)(null),o3=()=>{let e=(0,Z.use)(a3);if(!e)throw Error(`useApiClient must be used within ApiClientProvider`);return e},s3=(0,Z.memo)(({children:e,client:t,authManager:n,onAuthExpired:r})=>{let[i,a]=(0,Z.useState)(!1),o=(0,Z.useCallback)(()=>a(!1),[]),s=(0,Z.useMemo)(()=>({apiClient:t,authManager:n,authExpired:i,setAuthExpired:a,clearAuthExpired:o,onAuthExpired:r}),[i,t,n,o,r]);return(0,X.jsx)(a3.Provider,{value:s,children:e})});s3.displayName=`ApiClientProvider`;const c3=(0,Z.createContext)(null);function l3(e,t){let n=t?new Set(t):null;return e.map(e=>{if(e.type!==`code_llm_tool_call`||e.status!==`transient`||e.toolUseResult||n&&!n.has(e.id))return e;let t=Array.isArray(e.toolUseRequest)?e.toolUseRequest[0]?.name??``:e.toolUseRequest?.name??``,r=Array.isArray(e.toolUseRequest)?e.toolUseRequest[0]?.id??e.id:e.toolUseRequest?.id??e.id;return{...e,status:`completed`,toolUseResult:{id:r,content:`Error: tool execution orphaned`},parsedResult:{phase:`error`,toolType:t,data:{},summary:``}}})}function UHe(e,t){switch(t.type){case`INIT_SEND`:return[...l3(e.filter(e=>e.temp!==!0)),t.userSeg,t.spinnySeg];case`TEXT_DELTA`:{let{segId:n,content:r}=t,i=l3(e).filter(e=>!e.isSpinny);return i.find(e=>e.id===n)?i.map(e=>e.id===n?{...e,segment:(e.segment||``)+r}:e):[...i,{id:n,status:`transient`,source:`bot`,type:`text`,segment:r}]}case`THINKING_DELTA`:{let{segId:n,content:r,startTime:i}=t;return e.find(e=>e.id===n)?e.map(e=>e.id===n?{...e,segment:(e.segment||``)+r}:e):[...e,{id:n,status:`transient`,source:`bot`,type:`thinking`,isSpinny:!0,segment:r,thinkingStartTime:i}]}case`THINKING_COMPLETE`:return e.map(e=>e.id===t.segId?{...e,status:`completed`,isSpinny:!1,thinkingEndTime:t.endTime}:e);case`TOOL_DISPLAY_DATA`:return e.map(e=>e.id===t.toolCallId?{...e,toolDisplayData:{...e.toolDisplayData,...t.data}}:e);case`TOOL_REQUESTED`:{let{textSegId:n,toolSeg:r}=t,i;return i=n?e.filter(e=>!e.isSpinny).map(e=>e.id===n?{...e,status:`completed`}:e):e.filter(e=>!e.isSpinny),[...i,r]}case`TOOL_EXECUTION_COMPLETE`:{let{toolCallId:n,rawResult:r,parsedResult:i,spinnySeg:a}=t;return[...e.map(e=>e.id===n?{...e,status:`completed`,toolUseResult:r,...i!==void 0&&{parsedResult:i}}:e),a]}case`TOOL_USER_MESSAGE`:return[...e,t.seg];case`TEXT_COMPLETED`:return e.map(e=>e.id===t.segId?{...e,status:`completed`}:e);case`TURN_COMPLETE`:{let n=l3(e,t.toolCallIds);return t.textSegId&&(n=n.map(e=>e.id===t.textSegId?{...e,status:`completed`}:e)),n}case`FINALIZE`:{let n=l3(e);return t.textSegId&&(n=n.map(e=>e.id===t.textSegId?{...e,status:`completed`}:e)),n.filter(e=>!e.isSpinny)}case`ADD_NOTIFICATION`:{let n=t.seg,r=e[e.length-1];if(r&&r.type===`code_llm_notification`&&r.message===n.message&&r.severity===n.severity){let t=[...e];return t[t.length-1]={...r,flashKey:(r.flashKey??0)+1},t}return[...e,n]}case`ERROR`:return[...l3(e).filter(e=>!e.isSpinny),t.errorSeg];case`REMOVE_USER_SEG`:return e.filter(e=>e.id!==t.userSegId);case`CLEAR`:return[];case`LOAD`:return t.segments;case`REMOVE_TEMP`:return e.some(e=>e.temp===!0)?e.filter(e=>e.temp!==!0):e;case`ADD_CREDITS`:return[...e,t.seg];case`TOOL_CALL_START`:{let{toolCallId:n,toolName:r,textSegId:i}=t,a;return a=i?e.filter(e=>!e.isSpinny).map(e=>e.id===i?{...e,status:`completed`}:e):e.filter(e=>!e.isSpinny),[...a,{id:n,status:`transient`,source:`bot`,type:`code_llm_tool_call`,toolUseRequest:{id:n,name:r,input:{}},isStreamingArgs:!0,streamingArguments:``}]}case`TOOL_CALL_DELTA`:{let{toolCallId:n,argumentsDelta:r}=t;return e.map(e=>e.id===n?{...e,streamingArguments:(e.streamingArguments??``)+r}:e)}case`TOOL_CALL_STOP`:{let{toolCallId:n,toolName:r,arguments:i}=t,a={};try{a=JSON.parse(i)}catch{}return e.map(e=>e.id===n?{...e,isStreamingArgs:!1,streamingArguments:i,toolUseRequest:{id:n,name:r,input:a}}:e)}default:return e}}function WHe(e){switch(e.type){case`text`:return{id:e.id,status:`completed`,source:e.source,type:`text`,segment:e.content};case`thinking`:return{id:e.id,status:`completed`,source:`bot`,type:`thinking`,segment:e.content,isSpinny:e.isSpinny,...e.title!==void 0&&{title:e.title}};case`tool_call`:return{id:e.id,status:`completed`,source:`bot`,type:`code_llm_tool_call`,toolUseRequest:e.toolUseRequest,toolUseResult:e.toolUseResult??{id:e.toolUseRequest.id,content:` `},...e.parsedResult!==void 0&&{parsedResult:e.parsedResult},...e.toolDisplayData!==void 0&&{toolDisplayData:e.toolDisplayData}};case`notification`:return{id:e.id,status:`completed`,source:`bot`,type:`code_llm_notification`,message:e.message,severity:e.severity,...e.actions!==void 0&&{actions:e.actions}};case`tool_group`:return{id:e.id,status:`completed`,source:`bot`,type:`text`,segment:e.summary}}}const u3=(0,Z.memo)(({children:e,apiClient:t,configService:n,agentArgs:r})=>{let{agentMode:i,setAgentMode:a}=H0(),o=(0,Z.useRef)(i),s=(0,Z.useRef)(i),c=(0,Z.useRef)(null),{notifyActionRequired:l,notifyTaskComplete:u}=VHe(),{startUpload:d,startDownload:f,stopActivity:p}=r3(),{authManager:m,setAuthExpired:h,onAuthExpired:g}=o3(),_=CZ(),{connection:v,pushServer:y}=t3(),b=(0,Z.useRef)(v),x=(0,Z.useRef)(y);(0,Z.useEffect)(()=>{b.current=v},[v]),(0,Z.useEffect)(()=>{x.current=y},[y]);let[S,C]=(0,Z.useState)(Sd.Idle),[w,T]=(0,Z.useReducer)(UHe,[]),E=(0,Z.useRef)(new Map),[D,k]=(0,Z.useState)(null),[A,j]=(0,Z.useState)(null),M=(0,Z.useRef)(null),N=(0,Z.useRef)([]),[P,ee]=(0,Z.useState)([]),[F,te]=(0,Z.useState)(null),[I,L]=(0,Z.useState)(null),[R,z]=(0,Z.useState)(!0),[ne,re]=(0,Z.useState)(!0),[ie,ae]=(0,Z.useState)(0),oe=(0,Z.useRef)(0),se=(0,Z.useRef)(!0),ce=(0,Z.useRef)(null),le=(0,Z.useRef)(Sd.Idle),ue=(0,Z.useCallback)(e=>{le.current=e,C(e)},[]);(0,Z.useEffect)(()=>()=>{ce.current&&clearTimeout(ce.current),c.current&&clearTimeout(c.current)},[]);let[de,fe]=(0,Z.useState)(null),B=cF(process.cwd()),pe=(0,Z.useCallback)(e=>{M.current=e,j(e)},[]),me=(0,Z.useCallback)(()=>{let e=N.current.shift();if(!e){pe(null);return}e.request=ge.current?.refreshPermissionRequest(e.request)??e.request;let t=!1;(e.editorDiffFilePath||e.editorToolViewShown)&&x.current&&x.current.waitForDecision(e.request.tool.id).then(n=>{t||(t=!0,ue(n===`accept`||n===`allowAlways`||n===`allowYolo`?Sd.ExecutingTool:Sd.Submitted),e.resolve(n),me())}).catch(()=>{}),pe({request:e.request,resolve:n=>{t||(t=!0,ue(n===`accept`||n===`allowAlways`||n===`allowYolo`||typeof n==`object`&&n.type===`accept_with_message`||typeof n==`object`&&n.type===`question_answers`?Sd.ExecutingTool:Sd.Submitted),setTimeout(()=>{e.resolve(n),me()},0).unref())}}),ue(Sd.WaitingForToolPermission),l(`Abacus.AI is waiting for your input`)},[l,ue,pe]),he=(0,Z.useMemo)(()=>new hq(async e=>{let t=b.current,n=e,r=null;if(t&&x.current&&e.type===`edit_file`){let i=e.tool.id,a=E.current.get(i),o=(e.tool.input??{}).filePath??e.filePath??``,s=a?.originalContent??e.originalContent??``,c=a?.newContent??e.newContent??``;o&&(s||c)&&await t.showDiff({filePath:o,originalContent:s,modifiedContent:c,toolId:i})&&(n={...e,diffShownInEditor:!0},r=o)}if(t&&x.current&&e.type===`write_file`&&!e.isNewFile){let i=e.tool.id,a=e.filePath??``,o=e.originalContent??``,s=e.content??``;a&&(o||s)&&await t.showDiff({filePath:a,originalContent:o,modifiedContent:s,toolId:i})&&(n={...e,diffShownInEditor:!0},r=a)}let i=!1;t&&e.type===`exit_plan_mode`&&e.planFilePath&&(x.current&&await t.showToolView({filePath:e.planFilePath,toolKey:e.tool.id}).catch(()=>!1)&&(i=!0),i||await t.openPlanFile(e.planFilePath).catch(()=>{}));let a=await new Promise(e=>{let t={request:n,editorDiffFilePath:r,editorToolViewShown:i,resolve:e},a=N.current.length===0&&!M.current;N.current.push(t),a&&me()});if(r&&t){let e=a===`reject`||typeof a==`object`&&a.type===`reject_with_message`;t.notifyDiffDecision({targetFile:r,decision:e?`reject`:`accept`}).catch(()=>{})}return a}),[me]),ge=(0,Z.useRef)(null);function _e(){return new mq({allowedDirectories:[B,...r?.[`add-dir`]?.map(e=>{let t=oF(e);return cF(O.isAbsolute(t)?t:O.resolve(B,t))})??[]],primaryWorkspace:B,apiClient:t,mode:s.current,permissionProvider:he,config:n,diagnosticsProvider:{getDiagnostics:async e=>{let t=b.current;return t?t.getDiagnostics(e):[]}},onMcpAuthRequired:void 0,cliAllowedTools:r?.[`allowed-tools`],cliDisallowedTools:r?.[`disallowed-tools`],clientType:tt.CLI})}ge.current||=(s.current=o.current,_e());let ve=ge.current,ye=(0,Z.useCallback)(e=>{s.current=e,ve.setMode(e),N.current=N.current.filter(t=>Ed(t.request.type,e)?(t.resolve(`accept`),!1):!0);let t=M.current;t&&Ed(t.request.type,e)&&t.resolve(`accept`)},[ve]);(0,Z.useEffect)(()=>(o.current=i,c.current&&clearTimeout(c.current),c.current=setTimeout(()=>{ye(i),c.current=null},500),c.current.unref(),()=>{c.current&&=(clearTimeout(c.current),null)}),[i,ye]),(0,Z.useEffect)(()=>{(async()=>{let e=!0;if(r?.conversationId)try{await Te(r.conversationId)}catch{e=!1}e&&r?.prompt&&await De({message:r.prompt})})()},[]),(0,Z.useEffect)(()=>{let e=!1,t=0,n=1e3,r=()=>{if(e)return;t+=n;let i=ve.mcp.listServers(),a=i.filter(e=>e.status===`auth-required`);if(a.length>0){let e=a.map(e=>e.config.name??e.config.id).join(`, `);be(`${a.length} MCP server(s) require auth (${e}). Use /mcp auth <name> to authenticate.`,`warning`,!0);return}t<1e4&&i.some(e=>e.status!==`connected`&&e.status!==`error`)&&setTimeout(r,n)},i=setTimeout(r,n);return()=>{e=!0,clearTimeout(i)}},[]),(0,Z.useEffect)(()=>{switch(S){case Sd.Submitted:case Sd.Streaming:_.showProgress({state:`indeterminate`});break;case Sd.ExecutingTool:_.showProgress({state:`indeterminate`});break;case Sd.WaitingForToolPermission:_.hideProgress();break;case Sd.Idle:_.hideProgress();break}},[S,_]);let be=(0,Z.useCallback)((e,t=`info`,n=!1)=>{T({type:`ADD_NOTIFICATION`,seg:{id:crypto.randomUUID(),status:`completed`,source:`bot`,type:`code_llm_notification`,severity:t,message:e,temp:n}})},[]),V=(0,Z.useCallback)(()=>{T({type:`CLEAR`}),k(null),ue(Sd.Idle),fe(null),E.current.clear(),c.current&&=(clearTimeout(c.current),null),s.current=o.current,ge.current=_e()},[t,B,he]),xe=(0,Z.useCallback)(()=>{T({type:`CLEAR`})},[]),Se=(0,Z.useCallback)(()=>{T({type:`REMOVE_TEMP`})},[]),Ce=(0,Z.useCallback)(()=>{let e=ve.dequeue();ve.clearQueue(),ee([]),e!==null&&te(e),ve.stop();let t=M.current;t&&t.resolve(`reject`);for(let e of N.current)e.resolve(`reject`);N.current.length=0,pe(null),ue(Sd.Idle)},[ve,ue,pe]),we=(0,Z.useCallback)(()=>{A&&A.resolve(`reject`)},[A]),Te=(0,Z.useCallback)(async e=>{ue(Sd.LoadingConversation),T({type:`CLEAR`}),k(null),fe(e);try{let t=await ve.loadConversation(e);t.title&&k(t.title),t.segments.length>0&&T({type:`LOAD`,segments:t.segments.map(e=>WHe(e))})}catch{be(`Failed to load conversation`,`error`)}finally{ue(Sd.Idle)}},[ve,be,ue]),Ee=(0,Z.useCallback)(async(e,t)=>{await ve.mcp.refresh(),t&&be(`MCP tools refreshed`,`info`,!0)},[ve,be]),De=(0,Z.useCallback)(async({message:e,selectedModel:t,fileAttachments:n,activeSkills:r})=>{if(!e||S===Sd.LoadingConversation)return;t&&ve.setModel(t);let i=e;if(n&&n.length>0){let e=n.filter(e=>!e.mimeType.startsWith(`image/`));for(let t of e){let e=typeof t.content==`string`?t.content:t.content.toString(`utf-8`);i+=`\n\n<file path="${t.filePath}">\n${e}\n</file>`}}let o=crypto.randomUUID();T({type:`INIT_SEND`,userSeg:{id:o,status:`completed`,source:`user`,type:`text`,segment:e},spinnySeg:{id:crypto.randomUUID(),status:`transient`,source:`bot`,type:`collapsible_component`,title:`Processing request`,temp:!0,isSpinny:!0}}),ue(Sd.Submitted),d();let s=null,c=null,l=[],_=new Set,v,y=b.current,x=y?.getCurrentFile(),C=y?.getSelectionRange();if(y&&x)try{let e=(await y.getDiagnostics([x])).filter(e=>e.severity===`error`||e.severity===`warning`);e.length>0&&(v=e.map(e=>`${e.file}:${e.line}:${e.column} [${e.severity}] ${e.message}`).join(`
75247
- `))}catch{}try{for await(let e of ve.send(i,{diagnosticIssues:v,currentFile:x??void 0,selectionStartLine:C?.startLine,selectionEndLine:C?.endLine,activeSkills:r})){let t=()=>{c&&=(T({type:`THINKING_COMPLETE`,segId:c,endTime:Date.now()}),null)};switch(e.type){case`text_delta`:{ue(Sd.Streaming),p(),f(),t();let n=e.content;s||=crypto.randomUUID(),T({type:`TEXT_DELTA`,segId:s,content:n});break}case`thinking_delta`:{let t=e.content;c||=crypto.randomUUID(),T({type:`THINKING_DELTA`,segId:c,content:t,startTime:Date.now()});break}case`thinking_complete`:t();break;case`tool_display_data`:{let{toolCallId:t,data:n}=e,r=E.current.get(t)??{};E.current.set(t,{...r,...n}),T({type:`TOOL_DISPLAY_DATA`,toolCallId:t,data:n});break}case`tool_call_start`:t(),_.add(e.toolCallId),T({type:`TOOL_CALL_START`,toolCallId:e.toolCallId,toolName:e.toolName,textSegId:s}),s=null;break;case`tool_call_delta`:T({type:`TOOL_CALL_DELTA`,toolCallId:e.toolCallId,argumentsDelta:e.argumentsDelta});break;case`tool_call_stop`:T({type:`TOOL_CALL_STOP`,toolCallId:e.toolCallId,toolName:e.toolName,arguments:e.arguments});break;case`tool_requested`:{le.current!==Sd.WaitingForToolPermission&&ue(Sd.ExecutingTool),p(),d(),t();let n=e.tool.id;if(l.push(n),_.has(n)){T({type:`TOOL_CALL_STOP`,toolCallId:n,toolName:e.tool.name,arguments:JSON.stringify(e.tool.input??{})}),s=null;break}let r={id:n,status:`transient`,source:`bot`,type:`code_llm_tool_call`,toolUseRequest:{id:n,name:e.tool.name,input:e.tool.input},toolDisplayData:E.current.get(n)};T({type:`TOOL_REQUESTED`,toolCallId:n,textSegId:s,toolSeg:r}),s=null;break}case`tool_execution_complete`:{p(),f();let t=e.tool.id,{parsedResult:n,...r}=e.result,i={id:crypto.randomUUID(),status:`transient`,source:`bot`,type:`collapsible_component`,title:`Analyzing result`,temp:!0,isSpinny:!0};T({type:`TOOL_EXECUTION_COMPLETE`,toolCallId:t,rawResult:r,...n!==void 0&&{parsedResult:n},spinnySeg:i}),s=null;break}case`notification`:T({type:`ADD_NOTIFICATION`,seg:{id:crypto.randomUUID(),status:`completed`,source:`bot`,type:`code_llm_notification`,severity:e.severity,message:e.message,...e.actions!==void 0&&{actions:e.actions}}});break;case`error`:T({type:`ERROR`,errorSeg:{id:crypto.randomUUID(),status:`completed`,source:`bot`,type:`code_llm_notification`,severity:`error`,message:e.error.message}});break;case`mode_changed`:a(e.mode);break;case`tool_user_message`:T({type:`TOOL_USER_MESSAGE`,seg:{id:crypto.randomUUID(),status:`completed`,source:`user`,type:`text`,segment:e.message}});break;case`retry`:L({attempt:e.attempt,maxAttempts:e.maxAttempts,delayMs:e.delayMs,isNetworkError:e.isNetworkError});break;case`network_status`:e.online?(ce.current&&=(clearTimeout(ce.current),null),se.current=!0,z(!0),re(!0),L(null),setTimeout(()=>{if(le.current===Sd.Idle&&ve.getQueue().length>0){let e=ve.dequeue();if(e){ee(ve.getQueue());let t=cq.matchSkill(e.trim());De(t?{message:e,activeSkills:[t.skill.id]}:{message:e})}}},0).unref?.()):(se.current=!1,z(!1),ce.current||=setTimeout(()=>{ce.current=null,se.current||re(!1)},3e4));break;case`user_message_dequeued`:T({type:`INIT_SEND`,userSeg:{id:crypto.randomUUID(),status:`completed`,source:`user`,type:`text`,segment:e.content},spinnySeg:{id:crypto.randomUUID(),status:`transient`,source:`bot`,type:`collapsible_component`,title:`Processing request`,temp:!0,isSpinny:!0}}),ee(ve.getQueue()),s=null,c=null,l.length=0;break;case`credits`:oe.current+=e.creditsUsed,ae(t=>t+e.creditsUsed);break;case`turn_complete`:T({type:`TURN_COMPLETE`,textSegId:s,toolCallIds:[...l]}),s=null,l.length=0,ee(ve.getQueue());break}}}catch(e){if(e instanceof Ll)m.isEnvAuth()||(h(!0),g?.()),T({type:`REMOVE_USER_SEG`,userSegId:o}),be(`Session expired — use /login to authenticate again.`,`error`,!0);else{let t=Vl(e)?`Unable to connect to API`:e instanceof Error?e.message:`An error occurred`;T({type:`REMOVE_USER_SEG`,userSegId:o}),be(t,`error`,!0)}te(i),ve.clearQueue(),ee([])}finally{p(),L(null);let e=ve.getConversationId();e&&fe(e),T({type:`FINALIZE`,textSegId:s}),oe.current>0&&(T({type:`ADD_CREDITS`,seg:{id:`credits-${Date.now()}`,status:`completed`,source:`bot`,type:`code_llm_credits`,creditsUsed:oe.current}}),oe.current=0),ue(Sd.Idle),u(`Abacus.AI completed the task`)}},[ve,S,be,u,d,f,p,a,m,h]);(0,Z.useEffect)(()=>(ve.onAutoRestart=e=>{le.current===Sd.Idle&&De({message:e})},()=>{ve.onAutoRestart=null}),[ve,De]);let Oe=(0,Z.useCallback)(e=>{ve.enqueue(e),ee(ve.getQueue())},[ve]),ke=(0,Z.useCallback)(()=>{ve.dequeue(),ee(ve.getQueue())},[ve]),Ae=(0,Z.useCallback)(()=>{ve.clearQueue(),ee([])},[ve]),je=(0,Z.useCallback)(()=>{te(null)},[]),Me=(0,Z.useCallback)(e=>ve.isDirectoryAllowed(e),[ve]),Ne=(0,Z.useCallback)((e,t)=>ve.addAllowedDirectory(e,t),[ve]),Pe=(0,Z.useCallback)(()=>ve.listTerminalSessions(),[ve]),Fe=(0,Z.useCallback)(e=>ve.getTerminalSessionOutput(e),[ve]),Ie=(0,Z.useCallback)(e=>ve.stopTerminalSession(e),[ve]),Le=(0,Z.useMemo)(()=>({conversationId:de,conversationTitle:D,segments:w,segmentsLength:w.length,sendMessage:De,stop:Ce,rejectPendingPermission:we,agentStatus:S,clearSegments:V,clearSegmentsOnly:xe,clearTempSegments:Se,loadConversation:Te,addNotification:be,mcp:ve.mcp,isDirectoryAllowed:Me,addAllowedDirectory:Ne,pendingToolPermission:A,refreshMcpTools:Ee,queuedMessages:P,addToQueue:Oe,removeFirstFromQueue:ke,clearQueue:Ae,dequeuedOnStop:F,clearDequeuedOnStop:je,retryState:I,networkOnline:R,debouncedNetworkOnline:ne,listTerminalSessions:Pe,getTerminalSessionOutput:Fe,stopTerminalSession:Ie,totalCredits:ie}),[de,D,w,De,Ce,we,S,V,xe,Se,Te,be,ve,Me,Ne,A,Ee,P,Oe,ke,Ae,F,je,I,R,ne,Pe,Fe,Ie,ie]);return(0,X.jsx)(c3.Provider,{value:Le,children:e})});u3.displayName=`AgentProvider`;function d3(){let e=(0,Z.use)(c3);if(!e)throw Error(`Agent context not found. Did you forget to wrap your component in <${u3.name}>?`);return e}function f3(e){return e.split(`_`).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(``)}function GHe({toolName:e,status:t,parsedResult:n}){let{agentStatus:r}=d3(),i=f3(e);if(t===`interrupted`)return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(T0,{name:i,status:`interrupted`}),(0,X.jsx)(E0,{color:`yellow`,children:`Interrupted · What should I do instead?`})]});if(t===`rejected`)return n?.userNote?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(T0,{name:i,status:`rejected`}),(0,X.jsxs)(E0,{color:`yellow`,children:[`Rejected · `,(0,X.jsxs)($,{italic:!0,children:[`"`,n.userNote,`"`]})]})]}):(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(T0,{name:i,status:`rejected`}),(0,X.jsx)(E0,{color:`yellow`,children:`Rejected`})]});if(t===`error`)return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(T0,{name:i,status:`error`}),(0,X.jsx)(E0,{color:`red`,children:n?.errorMessage??n?.summary??`MCP tool execution failed`})]});let a=r===Sd.WaitingForToolPermission&&!n,o=!n&&(r===Sd.Streaming||r===Sd.ExecutingTool),s=n?.phase===`error`;return a?(0,X.jsxs)(Q,{flexDirection:`row`,gap:1,children:[(0,X.jsx)($,{color:`yellow`,children:`●`}),(0,X.jsx)($,{color:`cyan`,children:i})]}):o?(0,X.jsx)(T0,{name:i,status:`pending`,showSpinner:!0}):n?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(T0,{name:i,status:s?`error`:`success`}),(0,X.jsx)(E0,{color:s?`red`:`brightblack`,children:s?`Error: ${n.errorMessage??n.summary??`Tool execution failed`}`:n.summary??`Executed successfully`})]}):(0,X.jsx)(Q,{flexDirection:`column`,children:(0,X.jsx)(T0,{name:i,status:`pending`})})}function KHe(e){return{displayName:f3(e),getHeaderParams(e){return``},renderUI(t,n,r){return(0,X.jsx)(GHe,{toolName:e,rawInput:t,status:n,parsedResult:r})}}}function p3(e){let t=[];return e.pattern&&t.push(`pattern: "${e.pattern}"`),e.path&&t.push(`path: "${e.path}"`),t.length>0?t.join(`, `):`[no pattern]`}const qHe={displayName:`Search`,getHeaderParams(e){try{return p3(e)}catch{return`[unknown]`}},renderUI(e,t,n){let r=p3(e);return t===`error`?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(T0,{name:`Search`,params:r,status:`error`}),(0,X.jsx)(E0,{color:`red`,children:`Error matching files`})]}):t===`executing`?(0,X.jsx)(T0,{name:`Search`,params:r,status:`executing`,showSpinner:!0}):n?(0,X.jsx)(JHe,{searchParams:r,parsedResult:n}):(0,X.jsx)(Q,{flexDirection:`column`,children:(0,X.jsx)(T0,{name:`Search`,params:r,status:`pending`})})}};function JHe({searchParams:e,parsedResult:t}){let n=(0,Z.useContext)(G0),r=t.data.files??[],i=n?30:10,a=r.slice(0,i),o=r.length-a.length;return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(T0,{name:`Search`,params:e,status:`success`}),(0,X.jsx)(E0,{children:t.summary}),r.length>0&&(0,X.jsxs)(D0,{children:[a.map((e,t)=>(0,X.jsx)($,{dimColor:!0,children:e},t)),o>0&&(0,X.jsxs)($,{dimColor:!0,children:[`… +`,o,` more file`,o===1?``:`s`]})]})]})}function m3(e){let t=e,n=[];t.pattern&&n.push(`pattern: "${t.pattern}"`),t.path&&n.push(`path: "${t.path}"`);let r=t.outputMode||e.output_mode;return r&&n.push(`outputMode: "${r}"`),t.glob&&n.push(`glob: "${t.glob}"`),t[`-i`]&&n.push(`case-insensitive`),n.length>0?n.join(`, `):`[no pattern]`}const YHe={displayName:`Search`,getHeaderParams(e){try{return m3(e)}catch{return`[unknown]`}},renderUI(e,t,n){let r=m3(e);return t===`error`?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(T0,{name:`Search`,params:r,status:`error`}),(0,X.jsx)(E0,{color:`red`,children:`Error searching content`})]}):t===`executing`?(0,X.jsx)(T0,{name:`Search`,params:r,status:`executing`,showSpinner:!0}):n?(0,X.jsx)(XHe,{searchParams:r,parsedResult:n}):(0,X.jsx)(Q,{flexDirection:`column`,children:(0,X.jsx)(T0,{name:`Search`,params:r,status:`pending`})})}};function XHe({searchParams:e,parsedResult:t}){let n=(0,Z.useContext)(G0),r=t.data.matches??[],i=n?30:10,a=r.slice(0,i),o=r.length-a.length;return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(T0,{name:`Search`,params:e,status:`success`}),(0,X.jsx)(E0,{children:t.summary}),r.length>0&&(0,X.jsxs)(D0,{children:[a.map((e,t)=>(0,X.jsx)($,{dimColor:!0,children:e},t)),o>0&&(0,X.jsxs)($,{dimColor:!0,children:[`… +`,o,` more match`,o===1?``:`es`]})]})]})}const ZHe=QL({url:Y()}),QHe={displayName:`Web Fetch`,getHeaderParams(e){try{let t=e?.url||``;return t.length>50?t.substring(0,47)+`...`:t}catch{return`[unknown]`}},renderUI(e,t,n){let r=ZHe.safeParse(P0(e));if(!r.success)return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(T0,{name:`Fetch`,params:``,status:`error`}),(0,X.jsx)(E0,{color:`red`,children:`Invalid params`})]});let i=r.data.url||``,a=i.length>50?i.substring(0,47)+`...`:i;return t===`error`?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(T0,{name:`Fetch`,params:a,status:`error`}),(0,X.jsx)(E0,{color:`red`,children:`Error fetching URL`})]}):t===`executing`?(0,X.jsx)(T0,{name:`Fetch`,params:a,status:`executing`,showSpinner:!0}):n?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(T0,{name:`Fetch`,params:a,status:`success`}),(0,X.jsx)(E0,{children:n.summary??`Fetched content`})]}):(0,X.jsx)(Q,{flexDirection:`column`,children:(0,X.jsx)(T0,{name:`Fetch`,params:a,status:`pending`})})}},$He=QL({searchTerm:Y(),query:Y().optional(),explanation:Y().optional(),allowedDomains:XL(Y()).optional(),blockedDomains:XL(Y()).optional()}),eUe={displayName:`WebSearch`,getHeaderParams(e){try{return`"${e?.searchTerm||e?.search_term||e?.query||`[no query]`}"`}catch{return`[unknown]`}},renderUI(e,t,n){let r=$He.safeParse(P0(e));if(!r.success)return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(T0,{name:`WebSearch`,params:``,status:`error`}),(0,X.jsx)(E0,{color:`red`,children:`Invalid params`})]});let i=r.data,a=i.searchTerm||i.query||``,o=`"${a.length>40?a.substring(0,37)+`...`:a}"`;return t===`error`?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(T0,{name:`WebSearch`,params:o,status:`error`}),(0,X.jsx)(E0,{color:`red`,children:`Error performing web search`})]}):t===`executing`?(0,X.jsx)(T0,{name:`WebSearch`,params:o,status:`executing`,showSpinner:!0}):(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(T0,{name:`WebSearch`,params:o,status:`success`}),(0,X.jsx)(E0,{children:`Found results`})]})}},tUe=QL({shellId:Y(),filter:Y().optional()}),nUe={displayName:`BashOutput`,getHeaderParams(e){try{let t=e,n=[`id: ${t.shellId||``}`];return t.filter&&n.push(`filter: ${t.filter}`),n.join(`, `)}catch{return`[unknown]`}},renderUI(e,t,n){let r=tUe.safeParse(P0(e));if(!r.success)return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(T0,{name:`BashOutput`,params:``,status:`error`}),(0,X.jsx)(E0,{color:`red`,children:`Invalid params`})]});let i=`id: ${r.data.shellId}`;return t===`interrupted`?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(T0,{name:`BashOutput`,params:i,status:`interrupted`}),(0,X.jsx)(E0,{color:`yellow`,children:`Interrupted · What should I do instead?`})]}):t===`rejected`?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(T0,{name:`BashOutput`,params:i,status:`rejected`}),n?.userNote?(0,X.jsxs)(E0,{color:`yellow`,children:[`Rejected · `,(0,X.jsxs)($,{italic:!0,children:[`"`,n.userNote,`"`]})]}):(0,X.jsx)(E0,{color:`yellow`,children:`Rejected`})]}):!n&&(t===`executing`||t===`pending`)?(0,X.jsx)(T0,{name:`BashOutput`,params:i,status:`pending`,showSpinner:!0}):n?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(T0,{name:`BashOutput`,params:i,status:`success`}),(0,X.jsx)(E0,{children:n.summary})]}):(0,X.jsx)(Q,{flexDirection:`column`,children:(0,X.jsx)(T0,{name:`BashOutput`,params:i,status:`pending`})})}};var rUe=class{startTime;constructor(){this.startTime=performance.now()}getElapsedSeconds(){return(performance.now()-this.startTime)/1e3}getElapsedMs(){return performance.now()-this.startTime}getFormattedDuration(){return h3(this.getElapsedMs())}reset(){this.startTime=performance.now()}};function h3(e){let t=Math.floor(e/1e3),n=Math.floor(t/3600),r=Math.floor(t%3600/60),i=t%60,a=[];return n>0&&a.push(`${n}h`),r>0&&a.push(`${r}m`),(i>0||a.length===0)&&a.push(`${i}s`),a.join(` `)}function iUe(e,t,n){let r=n?50:t,i=e.split(`
75246
+ `);n.procedure=OHe(e,n.contract)}return{path:n.path,procedure:n.procedure}}}},IHe=class extends NHe{constructor(e,t={}){let n=new h4(new p4(t)),r=new FHe(t),i=new PHe(n);super(e,r,i,t)}},LHe=class{socketServer;socketPath;editorState={file:void 0,startLine:void 0,endLine:void 0};onEditorStateCallback=null;pendingDecisions=new Map;constructor(){let e=D.join(P.homedir(),hn.configDirName,`cli`);this.socketPath=D.join(e,`${process.pid}.sock`)}getEditorState(){return{...this.editorState}}onEditorChange(e){this.onEditorStateCallback=e}waitForDecision(e,t){return new Promise((n,r)=>{if(t?.aborted){r(Error(`Aborted`));return}let i=()=>{t?.removeEventListener(`abort`,a),this.pendingDecisions.delete(e)},a=()=>{i(),r(Error(`Aborted`))};t?.addEventListener(`abort`,a,{once:!0}),this.pendingDecisions.set(e,{resolve:e=>{i(),n(e)},cleanup:i})})}async start(){let e=D.dirname(this.socketPath);s.existsSync(e)||s.mkdirSync(e,{recursive:!0});let t=$4(tHe),n=t.router({editorStateChanged:t.editorStateChanged.handler(async({input:e})=>(this.editorState={file:e.file??void 0,startLine:e.startLine,endLine:e.endLine},this.onEditorStateCallback?.(this.editorState),{ok:!0})),toolDecision:t.toolDecision.handler(async({input:e})=>{let t=this.pendingDecisions.get(e.toolId);return t&&t.resolve(e.decision),{ok:!0}})});this.socketServer=await hHe(this.socketPath,new IHe(n))}dispose(){for(let[,e]of this.pendingDecisions)e.cleanup();this.pendingDecisions.clear(),this.socketServer?.dispose(),this.socketServer=void 0}},RHe=class{client=null;disposeSocket=null;currentFile=void 0;selectionStartLine=void 0;selectionEndLine=void 0;onFileChangeCallback=null;constructor(e){this.pushServer=e}findSocketPath(){let e=process.env[hn.socketEnvVar];if(e&&c.existsSync(e))return e;try{let e=O.join(ee.homedir(),hn.configDirName,hn.ideDirName),t=c.readdirSync(e).filter(e=>e.endsWith(`.sock`));if(t.length===0)return null;let n=null;for(let r of t){let t=O.join(e,r);try{let e=c.statSync(t);(!n||e.mtimeMs>n.mtime)&&(n={path:t,mtime:e.mtimeMs})}catch{}}if(n&&c.existsSync(n.path))return n.path}catch{}return null}async connect(){try{let e=this.findSocketPath();if(!e)return!1;let t=await vHe(e,{timeoutMs:2e3});this.client=s4(t.link),this.disposeSocket=()=>t.dispose(),await this.client.register({cliSocketPath:this.pushServer.socketPath,pid:process.pid});let n=this.pushServer.getEditorState();return this.currentFile=n.file,this.selectionStartLine=n.startLine,this.selectionEndLine=n.endLine,this.pushServer.onEditorChange(e=>{this.currentFile=e.file,this.selectionStartLine=e.startLine,this.selectionEndLine=e.endLine,this.onFileChangeCallback?.(e.file,e.startLine,e.endLine)}),!0}catch{return!1}}getCurrentFile(){return this.currentFile}getSelectionRange(){return{startLine:this.selectionStartLine,endLine:this.selectionEndLine}}isConnected(){return this.client!==null}onFileChange(e){this.onFileChangeCallback=e}async showDiff(e){if(!this.client)return!1;try{return(await this.client.showDiff({...e,cliSocketPath:this.pushServer.socketPath})).success}catch{return!1}}async showToolView(e){if(!this.client)return!1;try{return(await this.client.showToolView({...e,cliSocketPath:this.pushServer.socketPath})).success}catch{return!1}}async notifyDiffDecision(e){if(!this.client)throw Error(`Not connected to extension`);await this.client.notifyDiffDecision(e)}async openPlanFile(e){if(!this.client)throw Error(`Not connected to extension`);return{opened:(await this.client.openFile({file:e})).success}}async getDiagnostics(e){if(!this.client)throw Error(`Not connected to extension`);return this.client.getDiagnostics({...e&&{files:e}})}dispose(){this.disposeSocket?.(),this.disposeSocket=null,this.client=null,this.currentFile=void 0,this.selectionStartLine=void 0,this.selectionEndLine=void 0,this.onFileChangeCallback=null}};const e3=(0,Z.createContext)(null);function t3(){let e=(0,Z.use)(e3);if(!e)throw Error(`useExtensionFile must be used within ExtensionFileProvider`);return e}function zHe({children:e,initialFile:t}){let[n,r]=(0,Z.useState)(t),[i,a]=(0,Z.useState)(void 0),[o,s]=(0,Z.useState)(void 0),[c,l]=(0,Z.useState)(null),[u,d]=(0,Z.useState)(null),f=(0,Z.useRef)(null),p=(0,Z.useRef)(null);return(0,Z.useEffect)(()=>{let e=!1;return(async()=>{let t=new LHe;try{await t.start()}catch{}if(e){t.dispose();return}p.current=t,d(t),t.onEditorChange(e=>{r(e.file),a(e.startLine),s(e.endLine)});for(let n of[0,...[500,1e3,2e3,3e3,4e3]]){if(e||(n>0&&await new Promise(e=>setTimeout(e,n)),e))return;try{let n=new RHe(t);if(await n.connect()){if(e){n.dispose();return}let i=t.getEditorState();r(i.file),a(i.startLine),s(i.endLine),n.onFileChange((e,t,n)=>{r(e),a(t),s(n)}),f.current=n,l(n);return}}catch{}}})(),()=>{e=!0,f.current&&(f.current.dispose(),f.current=null,l(null)),p.current&&(p.current.dispose(),p.current=null,d(null))}},[]),(0,X.jsx)(e3.Provider,{value:{currentFile:n,selectionStartLine:i,selectionEndLine:o,connection:c,pushServer:u},children:e})}const n3=(0,Z.createContext)(null);function BHe({children:e}){let[t,n]=(0,Z.useState)(`idle`),r=(0,Z.useCallback)(()=>n(`upload`),[]),i=(0,Z.useCallback)(()=>n(`download`),[]),a=(0,Z.useCallback)(()=>n(`idle`),[]),o=(0,Z.useMemo)(()=>({activity:t,setActivity:n,startUpload:r,startDownload:i,stopActivity:a}),[t,r,i,a]);return(0,X.jsx)(n3.Provider,{value:o,children:e})}function r3(){let e=(0,Z.use)(n3);if(!e)throw Error(`useNetworkActivity must be used within NetworkActivityProvider`);return e}const i3=(0,Z.createContext)(null),VHe=()=>{let e=(0,Z.use)(i3);if(!e)throw Error(`useNotification must be used within NotificationProvider`);return e},HHe=({children:e})=>{let{isFocused:t}=SZ(),n=CZ(),r=(0,Z.useRef)(t);r.current=t;let i=(0,Z.useCallback)((e,t)=>{r.current||n.notify({body:e,title:t})},[n]),a=(0,Z.useCallback)(e=>{r.current||n.notify({body:e,title:`Action Required`})},[n]),o=(0,Z.useCallback)(e=>{r.current||n.notify({body:e,title:`Task Complete`})},[n]),s=(0,Z.useMemo)(()=>({notifyIfUnfocused:i,notifyActionRequired:a,notifyTaskComplete:o}),[i,a,o]);return(0,X.jsx)(i3.Provider,{value:s,children:e})},a3=(0,Z.createContext)(null),o3=()=>{let e=(0,Z.use)(a3);if(!e)throw Error(`useApiClient must be used within ApiClientProvider`);return e},s3=(0,Z.memo)(({children:e,client:t,authManager:n,onAuthExpired:r})=>{let[i,a]=(0,Z.useState)(!1),o=(0,Z.useCallback)(()=>a(!1),[]),s=(0,Z.useMemo)(()=>({apiClient:t,authManager:n,authExpired:i,setAuthExpired:a,clearAuthExpired:o,onAuthExpired:r}),[i,t,n,o,r]);return(0,X.jsx)(a3.Provider,{value:s,children:e})});s3.displayName=`ApiClientProvider`;const c3=(0,Z.createContext)(null);function l3(e,t){let n=t?new Set(t):null;return e.map(e=>{if(e.type!==`code_llm_tool_call`||e.status!==`transient`||e.toolUseResult||n&&!n.has(e.id))return e;let t=Array.isArray(e.toolUseRequest)?e.toolUseRequest[0]?.name??``:e.toolUseRequest?.name??``,r=Array.isArray(e.toolUseRequest)?e.toolUseRequest[0]?.id??e.id:e.toolUseRequest?.id??e.id;return{...e,status:`completed`,toolUseResult:{id:r,content:`Error: tool execution orphaned`},parsedResult:{phase:`error`,toolType:t,data:{},summary:``}}})}function UHe(e,t){switch(t.type){case`INIT_SEND`:return[...l3(e.filter(e=>e.temp!==!0)),t.userSeg,t.spinnySeg];case`TEXT_DELTA`:{let{segId:n,content:r}=t,i=l3(e).filter(e=>!e.isSpinny);return i.find(e=>e.id===n)?i.map(e=>e.id===n?{...e,segment:(e.segment||``)+r}:e):[...i,{id:n,status:`transient`,source:`bot`,type:`text`,segment:r}]}case`THINKING_DELTA`:{let{segId:n,content:r,startTime:i}=t;return e.find(e=>e.id===n)?e.map(e=>e.id===n?{...e,segment:(e.segment||``)+r}:e):[...e,{id:n,status:`transient`,source:`bot`,type:`thinking`,isSpinny:!0,segment:r,thinkingStartTime:i}]}case`THINKING_COMPLETE`:return e.map(e=>e.id===t.segId?{...e,status:`completed`,isSpinny:!1,thinkingEndTime:t.endTime}:e);case`TOOL_DISPLAY_DATA`:return e.map(e=>e.id===t.toolCallId?{...e,toolDisplayData:{...e.toolDisplayData,...t.data}}:e);case`TOOL_REQUESTED`:{let{textSegId:n,toolSeg:r}=t,i;return i=n?e.filter(e=>!e.isSpinny).map(e=>e.id===n?{...e,status:`completed`}:e):e.filter(e=>!e.isSpinny),[...i,r]}case`TOOL_EXECUTION_COMPLETE`:{let{toolCallId:n,rawResult:r,parsedResult:i,spinnySeg:a}=t;return[...e.map(e=>e.id===n?{...e,status:`completed`,toolUseResult:r,...i!==void 0&&{parsedResult:i}}:e),a]}case`TOOL_USER_MESSAGE`:return[...e,t.seg];case`TEXT_COMPLETED`:return e.map(e=>e.id===t.segId?{...e,status:`completed`}:e);case`TURN_COMPLETE`:{let n=l3(e,t.toolCallIds);return t.textSegId&&(n=n.map(e=>e.id===t.textSegId?{...e,status:`completed`}:e)),n}case`FINALIZE`:{let n=l3(e);return t.textSegId&&(n=n.map(e=>e.id===t.textSegId?{...e,status:`completed`}:e)),n.filter(e=>!e.isSpinny)}case`ADD_NOTIFICATION`:{let n=t.seg,r=e[e.length-1];if(r&&r.type===`code_llm_notification`&&r.message===n.message&&r.severity===n.severity){let t=[...e];return t[t.length-1]={...r,flashKey:(r.flashKey??0)+1},t}return[...e,n]}case`ERROR`:return[...l3(e).filter(e=>!e.isSpinny),t.errorSeg];case`REMOVE_USER_SEG`:return e.filter(e=>e.id!==t.userSegId);case`CLEAR`:return[];case`LOAD`:return t.segments;case`REMOVE_TEMP`:return e.some(e=>e.temp===!0)?e.filter(e=>e.temp!==!0):e;case`ADD_CREDITS`:return[...e,t.seg];case`TOOL_CALL_START`:{let{toolCallId:n,toolName:r,textSegId:i}=t,a;return a=i?e.filter(e=>!e.isSpinny).map(e=>e.id===i?{...e,status:`completed`}:e):e.filter(e=>!e.isSpinny),[...a,{id:n,status:`transient`,source:`bot`,type:`code_llm_tool_call`,toolUseRequest:{id:n,name:r,input:{}},isStreamingArgs:!0,streamingArguments:``}]}case`TOOL_CALL_DELTA`:{let{toolCallId:n,argumentsDelta:r}=t;return e.map(e=>e.id===n?{...e,streamingArguments:(e.streamingArguments??``)+r}:e)}case`TOOL_CALL_STOP`:{let{toolCallId:n,toolName:r,arguments:i}=t,a={};try{a=JSON.parse(i)}catch{}return e.map(e=>e.id===n?{...e,isStreamingArgs:!1,streamingArguments:i,toolUseRequest:{id:n,name:r,input:a}}:e)}default:return e}}function WHe(e){switch(e.type){case`text`:return{id:e.id,status:`completed`,source:e.source,type:`text`,segment:e.content};case`thinking`:return{id:e.id,status:`completed`,source:`bot`,type:`thinking`,segment:e.content,isSpinny:e.isSpinny,...e.title!==void 0&&{title:e.title}};case`tool_call`:return{id:e.id,status:`completed`,source:`bot`,type:`code_llm_tool_call`,toolUseRequest:e.toolUseRequest,toolUseResult:e.toolUseResult??{id:e.toolUseRequest.id,content:` `},...e.parsedResult!==void 0&&{parsedResult:e.parsedResult},...e.toolDisplayData!==void 0&&{toolDisplayData:e.toolDisplayData}};case`notification`:return{id:e.id,status:`completed`,source:`bot`,type:`code_llm_notification`,message:e.message,severity:e.severity,...e.actions!==void 0&&{actions:e.actions}};case`tool_group`:return{id:e.id,status:`completed`,source:`bot`,type:`text`,segment:e.summary}}}const u3=(0,Z.memo)(({children:e,apiClient:t,configService:n,agentArgs:r})=>{let{agentMode:i,setAgentMode:a}=H0(),o=(0,Z.useRef)(i),s=(0,Z.useRef)(i),c=(0,Z.useRef)(null),{notifyActionRequired:l,notifyTaskComplete:u}=VHe(),{startUpload:d,startDownload:f,stopActivity:p}=r3(),{authManager:m,setAuthExpired:h,onAuthExpired:g}=o3(),_=CZ(),{connection:v,pushServer:y}=t3(),b=(0,Z.useRef)(v),x=(0,Z.useRef)(y);(0,Z.useEffect)(()=>{b.current=v},[v]),(0,Z.useEffect)(()=>{x.current=y},[y]);let[S,C]=(0,Z.useState)(Sd.Idle),[w,T]=(0,Z.useReducer)(UHe,[]),E=(0,Z.useRef)(new Map),[D,k]=(0,Z.useState)(null),[A,j]=(0,Z.useState)(null),M=(0,Z.useRef)(null),N=(0,Z.useRef)([]),[P,ee]=(0,Z.useState)([]),[F,te]=(0,Z.useState)(null),[I,L]=(0,Z.useState)(null),[R,z]=(0,Z.useState)(!0),[ne,re]=(0,Z.useState)(!0),[ie,ae]=(0,Z.useState)(0),oe=(0,Z.useRef)(0),se=(0,Z.useRef)(!0),ce=(0,Z.useRef)(null),le=(0,Z.useRef)(Sd.Idle),ue=(0,Z.useCallback)(e=>{le.current=e,C(e)},[]);(0,Z.useEffect)(()=>()=>{ce.current&&clearTimeout(ce.current),c.current&&clearTimeout(c.current)},[]);let[de,fe]=(0,Z.useState)(null),B=cF(process.cwd()),pe=(0,Z.useCallback)(e=>{M.current=e,j(e)},[]),me=(0,Z.useCallback)(()=>{let e=N.current.shift();if(!e){pe(null);return}e.request=ge.current?.refreshPermissionRequest(e.request)??e.request;let t=!1;(e.editorDiffFilePath||e.editorToolViewShown)&&x.current&&x.current.waitForDecision(e.request.tool.id).then(n=>{t||(t=!0,ue(n===`accept`||n===`allowAlways`||n===`allowYolo`?Sd.ExecutingTool:Sd.Submitted),e.resolve(n),me())}).catch(()=>{}),pe({request:e.request,resolve:n=>{t||(t=!0,ue(n===`accept`||n===`allowAlways`||n===`allowYolo`||typeof n==`object`&&n.type===`accept_with_message`||typeof n==`object`&&n.type===`question_answers`?Sd.ExecutingTool:Sd.Submitted),setTimeout(()=>{e.resolve(n),me()},0).unref())}}),ue(Sd.WaitingForToolPermission),l(`Abacus.AI is waiting for your input`)},[l,ue,pe]),he=(0,Z.useMemo)(()=>new hq(async e=>{let t=b.current,n=e,r=null;if(t&&x.current&&e.type===`edit_file`){let i=e.tool.id,a=E.current.get(i),o=(e.tool.input??{}).filePath??e.filePath??``,s=a?.originalContent??e.originalContent??``,c=a?.newContent??e.newContent??``;o&&(s||c)&&await t.showDiff({filePath:o,originalContent:s,modifiedContent:c,toolId:i})&&(n={...e,diffShownInEditor:!0},r=o)}if(t&&x.current&&e.type===`write_file`&&!e.isNewFile){let i=e.tool.id,a=e.filePath??``,o=e.originalContent??``,s=e.content??``;a&&(o||s)&&await t.showDiff({filePath:a,originalContent:o,modifiedContent:s,toolId:i})&&(n={...e,diffShownInEditor:!0},r=a)}let i=!1;t&&e.type===`exit_plan_mode`&&e.planFilePath&&(x.current&&await t.showToolView({filePath:e.planFilePath,toolKey:e.tool.id}).catch(()=>!1)&&(i=!0),i||await t.openPlanFile(e.planFilePath).catch(()=>{}));let a=await new Promise(e=>{let t={request:n,editorDiffFilePath:r,editorToolViewShown:i,resolve:e},a=N.current.length===0&&!M.current;N.current.push(t),a&&me()});if(r&&t){let e=a===`reject`||typeof a==`object`&&a.type===`reject_with_message`;t.notifyDiffDecision({targetFile:r,decision:e?`reject`:`accept`}).catch(()=>{})}return a}),[me]),ge=(0,Z.useRef)(null);function _e(){return new mq({allowedDirectories:[B,...r?.[`add-dir`]?.map(e=>{let t=oF(e);return cF(O.isAbsolute(t)?t:O.resolve(B,t))})??[]],primaryWorkspace:B,apiClient:t,mode:s.current,permissionProvider:he,config:n,diagnosticsProvider:{getDiagnostics:async e=>{let t=b.current;return t?t.getDiagnostics(e):[]}},onMcpAuthRequired:void 0,cliAllowedTools:r?.[`allowed-tools`],cliDisallowedTools:r?.[`disallowed-tools`],clientType:tt.CLI})}ge.current||=(s.current=o.current,_e());let ve=ge.current,ye=(0,Z.useCallback)(()=>{ee(ve.getQueueEntries().map(e=>({...e})))},[ve]),be=(0,Z.useCallback)(e=>{s.current=e,ve.setMode(e),N.current=N.current.filter(t=>Ed(t.request.type,e)?(t.resolve(`accept`),!1):!0);let t=M.current;t&&Ed(t.request.type,e)&&t.resolve(`accept`)},[ve]);(0,Z.useEffect)(()=>(o.current=i,c.current&&clearTimeout(c.current),c.current=setTimeout(()=>{be(i),c.current=null},500),c.current.unref(),()=>{c.current&&=(clearTimeout(c.current),null)}),[i,be]),(0,Z.useEffect)(()=>{(async()=>{let e=!0;if(r?.conversationId)try{await Ee(r.conversationId)}catch{e=!1}e&&r?.prompt&&await Oe({message:r.prompt})})()},[]),(0,Z.useEffect)(()=>{let e=!1,t=0,n=1e3,r=()=>{if(e)return;t+=n;let i=ve.mcp.listServers(),a=i.filter(e=>e.status===`auth-required`);if(a.length>0){let e=a.map(e=>e.config.name??e.config.id).join(`, `);V(`${a.length} MCP server(s) require auth (${e}). Use /mcp auth <name> to authenticate.`,`warning`,!0);return}t<1e4&&i.some(e=>e.status!==`connected`&&e.status!==`error`)&&setTimeout(r,n)},i=setTimeout(r,n);return()=>{e=!0,clearTimeout(i)}},[]),(0,Z.useEffect)(()=>{switch(S){case Sd.Submitted:case Sd.Streaming:_.showProgress({state:`indeterminate`});break;case Sd.ExecutingTool:_.showProgress({state:`indeterminate`});break;case Sd.WaitingForToolPermission:_.hideProgress();break;case Sd.Idle:_.hideProgress();break}},[S,_]);let V=(0,Z.useCallback)((e,t=`info`,n=!1)=>{T({type:`ADD_NOTIFICATION`,seg:{id:crypto.randomUUID(),status:`completed`,source:`bot`,type:`code_llm_notification`,severity:t,message:e,temp:n}})},[]),xe=(0,Z.useCallback)(()=>{T({type:`CLEAR`}),k(null),ue(Sd.Idle),fe(null),E.current.clear(),c.current&&=(clearTimeout(c.current),null),s.current=o.current,ge.current=_e()},[t,B,he]),Se=(0,Z.useCallback)(()=>{T({type:`CLEAR`})},[]),Ce=(0,Z.useCallback)(()=>{T({type:`REMOVE_TEMP`})},[]),we=(0,Z.useCallback)(()=>{let e=ve.dq();ye(),e.length>0&&te(e.map(e=>e.message).join(`
75247
+ `)),ve.stop();let t=M.current;t&&t.resolve(`reject`);for(let e of N.current)e.resolve(`reject`);N.current.length=0,pe(null),ue(Sd.Idle)},[ve,ye,ue,pe]),Te=(0,Z.useCallback)(()=>{A&&A.resolve(`reject`)},[A]),Ee=(0,Z.useCallback)(async e=>{ue(Sd.LoadingConversation),T({type:`CLEAR`}),k(null),fe(e);try{let t=await ve.loadConversation(e);t.title&&k(t.title),t.segments.length>0&&T({type:`LOAD`,segments:t.segments.map(e=>WHe(e))})}catch{V(`Failed to load conversation`,`error`)}finally{ue(Sd.Idle)}},[ve,V,ue]),De=(0,Z.useCallback)(async(e,t)=>{await ve.mcp.refresh(),t&&V(`MCP tools refreshed`,`info`,!0)},[ve,V]),Oe=(0,Z.useCallback)(async({message:e,selectedModel:t,fileAttachments:n,activeSkills:r})=>{if(!e||S===Sd.LoadingConversation)return;t&&ve.setModel(t);let i=e;if(n&&n.length>0){let e=n.filter(e=>!e.mimeType.startsWith(`image/`));for(let t of e){let e=typeof t.content==`string`?t.content:t.content.toString(`utf-8`);i+=`\n\n<file path="${t.filePath}">\n${e}\n</file>`}}let o=crypto.randomUUID();T({type:`INIT_SEND`,userSeg:{id:o,status:`completed`,source:`user`,type:`text`,segment:e},spinnySeg:{id:crypto.randomUUID(),status:`transient`,source:`bot`,type:`collapsible_component`,title:`Processing request`,temp:!0,isSpinny:!0}}),ue(Sd.Submitted),d();let s=null,c=null,l=[],_=new Set,v,y=b.current,x=y?.getCurrentFile(),C=y?.getSelectionRange();if(y&&x)try{let e=(await y.getDiagnostics([x])).filter(e=>e.severity===`error`||e.severity===`warning`);e.length>0&&(v=e.map(e=>`${e.file}:${e.line}:${e.column} [${e.severity}] ${e.message}`).join(`
75248
+ `))}catch{}try{for await(let e of ve.send(i,{diagnosticIssues:v,currentFile:x??void 0,selectionStartLine:C?.startLine,selectionEndLine:C?.endLine,activeSkills:r})){let t=()=>{c&&=(T({type:`THINKING_COMPLETE`,segId:c,endTime:Date.now()}),null)};switch(e.type){case`text_delta`:{ue(Sd.Streaming),p(),f(),t();let n=e.content;s||=crypto.randomUUID(),T({type:`TEXT_DELTA`,segId:s,content:n});break}case`thinking_delta`:{let t=e.content;c||=crypto.randomUUID(),T({type:`THINKING_DELTA`,segId:c,content:t,startTime:Date.now()});break}case`thinking_complete`:t();break;case`tool_display_data`:{let{toolCallId:t,data:n}=e,r=E.current.get(t)??{};E.current.set(t,{...r,...n}),T({type:`TOOL_DISPLAY_DATA`,toolCallId:t,data:n});break}case`tool_call_start`:t(),_.add(e.toolCallId),T({type:`TOOL_CALL_START`,toolCallId:e.toolCallId,toolName:e.toolName,textSegId:s}),s=null;break;case`tool_call_delta`:T({type:`TOOL_CALL_DELTA`,toolCallId:e.toolCallId,argumentsDelta:e.argumentsDelta});break;case`tool_call_stop`:T({type:`TOOL_CALL_STOP`,toolCallId:e.toolCallId,toolName:e.toolName,arguments:e.arguments});break;case`tool_requested`:{le.current!==Sd.WaitingForToolPermission&&ue(Sd.ExecutingTool),p(),d(),t();let n=e.tool.id;if(l.push(n),_.has(n)){T({type:`TOOL_CALL_STOP`,toolCallId:n,toolName:e.tool.name,arguments:JSON.stringify(e.tool.input??{})}),s=null;break}let r={id:n,status:`transient`,source:`bot`,type:`code_llm_tool_call`,toolUseRequest:{id:n,name:e.tool.name,input:e.tool.input},toolDisplayData:E.current.get(n)};T({type:`TOOL_REQUESTED`,toolCallId:n,textSegId:s,toolSeg:r}),s=null;break}case`tool_execution_complete`:{p(),f();let t=e.tool.id,{parsedResult:n,...r}=e.result,i={id:crypto.randomUUID(),status:`transient`,source:`bot`,type:`collapsible_component`,title:`Analyzing result`,temp:!0,isSpinny:!0};T({type:`TOOL_EXECUTION_COMPLETE`,toolCallId:t,rawResult:r,...n!==void 0&&{parsedResult:n},spinnySeg:i}),s=null;break}case`notification`:T({type:`ADD_NOTIFICATION`,seg:{id:crypto.randomUUID(),status:`completed`,source:`bot`,type:`code_llm_notification`,severity:e.severity,message:e.message,...e.actions!==void 0&&{actions:e.actions}}});break;case`error`:T({type:`ERROR`,errorSeg:{id:crypto.randomUUID(),status:`completed`,source:`bot`,type:`code_llm_notification`,severity:`error`,message:e.error.message}});break;case`mode_changed`:a(e.mode);break;case`tool_user_message`:T({type:`TOOL_USER_MESSAGE`,seg:{id:crypto.randomUUID(),status:`completed`,source:`user`,type:`text`,segment:e.message}});break;case`retry`:L({attempt:e.attempt,maxAttempts:e.maxAttempts,delayMs:e.delayMs,isNetworkError:e.isNetworkError});break;case`network_status`:e.online?(ce.current&&=(clearTimeout(ce.current),null),se.current=!0,z(!0),re(!0),L(null),setTimeout(()=>{if(le.current===Sd.Idle&&ve.getQueueEntries().length>0){let e=ve.dq();if(e.length>0){ye();let t=e.map(e=>e.message).join(`
75249
+ `),n=cq.matchSkill(t.trim());Oe(n?{message:t,activeSkills:[n.skill.id]}:{message:t})}}},0).unref?.()):(se.current=!1,z(!1),ce.current||=setTimeout(()=>{ce.current=null,se.current||re(!1)},3e4));break;case`user_message_dequeued`:T({type:`INIT_SEND`,userSeg:{id:crypto.randomUUID(),status:`completed`,source:`user`,type:`text`,segment:e.content},spinnySeg:{id:crypto.randomUUID(),status:`transient`,source:`bot`,type:`collapsible_component`,title:`Processing request`,temp:!0,isSpinny:!0}}),ye(),s=null,c=null,l.length=0;break;case`credits`:oe.current+=e.creditsUsed,ae(t=>t+e.creditsUsed);break;case`turn_complete`:T({type:`TURN_COMPLETE`,textSegId:s,toolCallIds:[...l]}),s=null,l.length=0,ye();break}}}catch(e){if(e instanceof Ll)m.isEnvAuth()||(h(!0),g?.()),T({type:`REMOVE_USER_SEG`,userSegId:o}),V(`Session expired — use /login to authenticate again.`,`error`,!0);else{let t=Vl(e)?`Unable to connect to API`:e instanceof Error?e.message:`An error occurred`;T({type:`REMOVE_USER_SEG`,userSegId:o}),V(t,`error`,!0)}te(i),ve.dq(),ye()}finally{p(),L(null);let e=ve.getConversationId();e&&fe(e),T({type:`FINALIZE`,textSegId:s}),oe.current>0&&(T({type:`ADD_CREDITS`,seg:{id:`credits-${Date.now()}`,status:`completed`,source:`bot`,type:`code_llm_credits`,creditsUsed:oe.current}}),oe.current=0),ue(Sd.Idle),u(`Abacus.AI completed the task`)}},[ve,S,V,u,d,f,p,a,m,h]);(0,Z.useEffect)(()=>(ve.onAutoRestart=e=>{le.current===Sd.Idle&&Oe({message:e})},()=>{ve.onAutoRestart=null}),[ve,Oe]);let ke=(0,Z.useCallback)((e,t)=>{let n=ve.nq(e,t);return ye(),n},[ve,ye]),Ae=(0,Z.useCallback)(e=>{let t=ve.dq(e);return ye(),t},[ve,ye]),je=(0,Z.useCallback)((e,t)=>{ve.remove(e,t),ye()},[ve,ye]),Me=(0,Z.useCallback)((e,t)=>{let n=ve.setContent(e,t);return ye(),n},[ve,ye]),Ne=(0,Z.useCallback)(e=>{ve.clearQueue(e),ye()},[ve,ye]),Pe=(0,Z.useCallback)(()=>{te(null)},[]),Fe=(0,Z.useCallback)(e=>ve.isDirectoryAllowed(e),[ve]),Ie=(0,Z.useCallback)((e,t)=>ve.addAllowedDirectory(e,t),[ve]),Le=(0,Z.useCallback)(()=>ve.listTerminalSessions(),[ve]),Re=(0,Z.useCallback)(e=>ve.getTerminalSessionOutput(e),[ve]),ze=(0,Z.useCallback)(e=>ve.stopTerminalSession(e),[ve]),Be=(0,Z.useMemo)(()=>({conversationId:de,conversationTitle:D,segments:w,segmentsLength:w.length,sendMessage:Oe,stop:we,rejectPendingPermission:Te,agentStatus:S,clearSegments:xe,clearSegmentsOnly:Se,clearTempSegments:Ce,loadConversation:Ee,addNotification:V,mcp:ve.mcp,isDirectoryAllowed:Fe,addAllowedDirectory:Ie,pendingToolPermission:A,refreshMcpTools:De,queuedMessages:P,nq:ke,dq:Ae,removeFromQueue:je,setQueuedMessageContent:Me,clearQueue:Ne,dequeuedOnStop:F,clearDequeuedOnStop:Pe,retryState:I,networkOnline:R,debouncedNetworkOnline:ne,listTerminalSessions:Le,getTerminalSessionOutput:Re,stopTerminalSession:ze,totalCredits:ie}),[de,D,w,Oe,we,Te,S,xe,Se,Ce,Ee,V,ve,Fe,Ie,A,De,P,ke,Ae,je,Me,Ne,F,Pe,I,R,ne,Le,Re,ze,ie]);return(0,X.jsx)(c3.Provider,{value:Be,children:e})});u3.displayName=`AgentProvider`;function d3(){let e=(0,Z.use)(c3);if(!e)throw Error(`Agent context not found. Did you forget to wrap your component in <${u3.name}>?`);return e}function f3(e){return e.split(`_`).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(``)}function GHe({toolName:e,status:t,parsedResult:n}){let{agentStatus:r}=d3(),i=f3(e);if(t===`interrupted`)return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(T0,{name:i,status:`interrupted`}),(0,X.jsx)(E0,{color:`yellow`,children:`Interrupted · What should I do instead?`})]});if(t===`rejected`)return n?.userNote?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(T0,{name:i,status:`rejected`}),(0,X.jsxs)(E0,{color:`yellow`,children:[`Rejected · `,(0,X.jsxs)($,{italic:!0,children:[`"`,n.userNote,`"`]})]})]}):(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(T0,{name:i,status:`rejected`}),(0,X.jsx)(E0,{color:`yellow`,children:`Rejected`})]});if(t===`error`)return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(T0,{name:i,status:`error`}),(0,X.jsx)(E0,{color:`red`,children:n?.errorMessage??n?.summary??`MCP tool execution failed`})]});let a=r===Sd.WaitingForToolPermission&&!n,o=!n&&(r===Sd.Streaming||r===Sd.ExecutingTool),s=n?.phase===`error`;return a?(0,X.jsxs)(Q,{flexDirection:`row`,gap:1,children:[(0,X.jsx)($,{color:`yellow`,children:`●`}),(0,X.jsx)($,{color:`cyan`,children:i})]}):o?(0,X.jsx)(T0,{name:i,status:`pending`,showSpinner:!0}):n?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(T0,{name:i,status:s?`error`:`success`}),(0,X.jsx)(E0,{color:s?`red`:`brightblack`,children:s?`Error: ${n.errorMessage??n.summary??`Tool execution failed`}`:n.summary??`Executed successfully`})]}):(0,X.jsx)(Q,{flexDirection:`column`,children:(0,X.jsx)(T0,{name:i,status:`pending`})})}function KHe(e){return{displayName:f3(e),getHeaderParams(e){return``},renderUI(t,n,r){return(0,X.jsx)(GHe,{toolName:e,rawInput:t,status:n,parsedResult:r})}}}function p3(e){let t=[];return e.pattern&&t.push(`pattern: "${e.pattern}"`),e.path&&t.push(`path: "${e.path}"`),t.length>0?t.join(`, `):`[no pattern]`}const qHe={displayName:`Search`,getHeaderParams(e){try{return p3(e)}catch{return`[unknown]`}},renderUI(e,t,n){let r=p3(e);return t===`error`?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(T0,{name:`Search`,params:r,status:`error`}),(0,X.jsx)(E0,{color:`red`,children:`Error matching files`})]}):t===`executing`?(0,X.jsx)(T0,{name:`Search`,params:r,status:`executing`,showSpinner:!0}):n?(0,X.jsx)(JHe,{searchParams:r,parsedResult:n}):(0,X.jsx)(Q,{flexDirection:`column`,children:(0,X.jsx)(T0,{name:`Search`,params:r,status:`pending`})})}};function JHe({searchParams:e,parsedResult:t}){let n=(0,Z.useContext)(G0),r=t.data.files??[],i=n?30:10,a=r.slice(0,i),o=r.length-a.length;return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(T0,{name:`Search`,params:e,status:`success`}),(0,X.jsx)(E0,{children:t.summary}),r.length>0&&(0,X.jsxs)(D0,{children:[a.map((e,t)=>(0,X.jsx)($,{dimColor:!0,children:e},t)),o>0&&(0,X.jsxs)($,{dimColor:!0,children:[`… +`,o,` more file`,o===1?``:`s`]})]})]})}function m3(e){let t=e,n=[];t.pattern&&n.push(`pattern: "${t.pattern}"`),t.path&&n.push(`path: "${t.path}"`);let r=t.outputMode||e.output_mode;return r&&n.push(`outputMode: "${r}"`),t.glob&&n.push(`glob: "${t.glob}"`),t[`-i`]&&n.push(`case-insensitive`),n.length>0?n.join(`, `):`[no pattern]`}const YHe={displayName:`Search`,getHeaderParams(e){try{return m3(e)}catch{return`[unknown]`}},renderUI(e,t,n){let r=m3(e);return t===`error`?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(T0,{name:`Search`,params:r,status:`error`}),(0,X.jsx)(E0,{color:`red`,children:`Error searching content`})]}):t===`executing`?(0,X.jsx)(T0,{name:`Search`,params:r,status:`executing`,showSpinner:!0}):n?(0,X.jsx)(XHe,{searchParams:r,parsedResult:n}):(0,X.jsx)(Q,{flexDirection:`column`,children:(0,X.jsx)(T0,{name:`Search`,params:r,status:`pending`})})}};function XHe({searchParams:e,parsedResult:t}){let n=(0,Z.useContext)(G0),r=t.data.matches??[],i=n?30:10,a=r.slice(0,i),o=r.length-a.length;return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(T0,{name:`Search`,params:e,status:`success`}),(0,X.jsx)(E0,{children:t.summary}),r.length>0&&(0,X.jsxs)(D0,{children:[a.map((e,t)=>(0,X.jsx)($,{dimColor:!0,children:e},t)),o>0&&(0,X.jsxs)($,{dimColor:!0,children:[`… +`,o,` more match`,o===1?``:`es`]})]})]})}const ZHe=QL({url:Y()}),QHe={displayName:`Web Fetch`,getHeaderParams(e){try{let t=e?.url||``;return t.length>50?t.substring(0,47)+`...`:t}catch{return`[unknown]`}},renderUI(e,t,n){let r=ZHe.safeParse(P0(e));if(!r.success)return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(T0,{name:`Fetch`,params:``,status:`error`}),(0,X.jsx)(E0,{color:`red`,children:`Invalid params`})]});let i=r.data.url||``,a=i.length>50?i.substring(0,47)+`...`:i;return t===`error`?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(T0,{name:`Fetch`,params:a,status:`error`}),(0,X.jsx)(E0,{color:`red`,children:`Error fetching URL`})]}):t===`executing`?(0,X.jsx)(T0,{name:`Fetch`,params:a,status:`executing`,showSpinner:!0}):n?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(T0,{name:`Fetch`,params:a,status:`success`}),(0,X.jsx)(E0,{children:n.summary??`Fetched content`})]}):(0,X.jsx)(Q,{flexDirection:`column`,children:(0,X.jsx)(T0,{name:`Fetch`,params:a,status:`pending`})})}},$He=QL({searchTerm:Y(),query:Y().optional(),explanation:Y().optional(),allowedDomains:XL(Y()).optional(),blockedDomains:XL(Y()).optional()}),eUe={displayName:`WebSearch`,getHeaderParams(e){try{return`"${e?.searchTerm||e?.search_term||e?.query||`[no query]`}"`}catch{return`[unknown]`}},renderUI(e,t,n){let r=$He.safeParse(P0(e));if(!r.success)return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(T0,{name:`WebSearch`,params:``,status:`error`}),(0,X.jsx)(E0,{color:`red`,children:`Invalid params`})]});let i=r.data,a=i.searchTerm||i.query||``,o=`"${a.length>40?a.substring(0,37)+`...`:a}"`;return t===`error`?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(T0,{name:`WebSearch`,params:o,status:`error`}),(0,X.jsx)(E0,{color:`red`,children:`Error performing web search`})]}):t===`executing`?(0,X.jsx)(T0,{name:`WebSearch`,params:o,status:`executing`,showSpinner:!0}):(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(T0,{name:`WebSearch`,params:o,status:`success`}),(0,X.jsx)(E0,{children:`Found results`})]})}},tUe=QL({shellId:Y(),filter:Y().optional()}),nUe={displayName:`BashOutput`,getHeaderParams(e){try{let t=e,n=[`id: ${t.shellId||``}`];return t.filter&&n.push(`filter: ${t.filter}`),n.join(`, `)}catch{return`[unknown]`}},renderUI(e,t,n){let r=tUe.safeParse(P0(e));if(!r.success)return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(T0,{name:`BashOutput`,params:``,status:`error`}),(0,X.jsx)(E0,{color:`red`,children:`Invalid params`})]});let i=`id: ${r.data.shellId}`;return t===`interrupted`?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(T0,{name:`BashOutput`,params:i,status:`interrupted`}),(0,X.jsx)(E0,{color:`yellow`,children:`Interrupted · What should I do instead?`})]}):t===`rejected`?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(T0,{name:`BashOutput`,params:i,status:`rejected`}),n?.userNote?(0,X.jsxs)(E0,{color:`yellow`,children:[`Rejected · `,(0,X.jsxs)($,{italic:!0,children:[`"`,n.userNote,`"`]})]}):(0,X.jsx)(E0,{color:`yellow`,children:`Rejected`})]}):!n&&(t===`executing`||t===`pending`)?(0,X.jsx)(T0,{name:`BashOutput`,params:i,status:`pending`,showSpinner:!0}):n?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(T0,{name:`BashOutput`,params:i,status:`success`}),(0,X.jsx)(E0,{children:n.summary})]}):(0,X.jsx)(Q,{flexDirection:`column`,children:(0,X.jsx)(T0,{name:`BashOutput`,params:i,status:`pending`})})}};var rUe=class{startTime;constructor(){this.startTime=performance.now()}getElapsedSeconds(){return(performance.now()-this.startTime)/1e3}getElapsedMs(){return performance.now()-this.startTime}getFormattedDuration(){return h3(this.getElapsedMs())}reset(){this.startTime=performance.now()}};function h3(e){let t=Math.floor(e/1e3),n=Math.floor(t/3600),r=Math.floor(t%3600/60),i=t%60,a=[];return n>0&&a.push(`${n}h`),r>0&&a.push(`${r}m`),(i>0||a.length===0)&&a.push(`${i}s`),a.join(` `)}function iUe(e,t,n){let r=n?50:t,i=e.split(`
75248
75250
  `).filter(Boolean);return i.length<=r?{lines:i,isTruncated:!1,hiddenCount:0}:{lines:i.slice(0,r),isTruncated:!0,hiddenCount:i.length-r}}function aUe(e){let[t]=(0,Z.useState)(Date.now()),[n,r]=(0,Z.useState)(0);return(0,Z.useEffect)(()=>{if(!e)return;let n=setInterval(()=>{r(Date.now()-t)},1e3);return()=>clearInterval(n)},[e,t]),n}function oUe({command:e,toolCallId:t,executionResult:n}){let{agentStatus:r}=d3(),i=(0,Z.useContext)(G0),[a,o]=(0,Z.useState)(!1),s=a||i,c=!n&&(r===Sd.Streaming||r===Sd.ExecutingTool),l=aUe(c),u=l>=5e3,d=(0,Z.useDeferredValue)(n?.output||``),{lines:f,isTruncated:p,hiddenCount:m}=(0,Z.useMemo)(()=>iUe(d,7,s),[d,s]),h=!i&&!c&&n!==void 0&&(p||a),{isFocused:g}=xZ({id:`bash-tool-${t}`,isActive:h});bZ((e,t)=>{g&&t.ctrl&&e===`o`&&o(e=>!e)},{isActive:g&&h});let _=e.length>500?e.slice(0,500)+`…`:e,v=n?.exitCode??0,y=n?.status===`error`||v!==0,b=c?`pending`:y?`error`:`success`;if(c){let e=u?h3(l):null;return(0,X.jsxs)(Q,{flexDirection:`column`,gap:0,children:[(0,X.jsx)(T0,{name:`Bash`,params:_,paramsLanguage:`bash`,status:b,showSpinner:!0}),(0,X.jsxs)(E0,{color:`brightblack`,children:[`Running…`,e?` ${e}`:null]})]})}if(n){let e=f.length>0,t=`exit ${v} (${cBe(n.duration??0)})`;return(0,X.jsxs)(Q,{flexDirection:`column`,gap:0,children:[(0,X.jsx)(T0,{name:`Bash`,params:_,paramsLanguage:`bash`,status:b}),(0,X.jsx)(D0,{children:e?(0,X.jsxs)(X.Fragment,{children:[y&&(0,X.jsx)($,{color:`red`,dimColor:!0,children:`Error:`}),f.map((e,t)=>(0,X.jsx)($,{color:y?`red`:void 0,dimColor:!0,children:e},t)),p&&(0,X.jsxs)($,{dimColor:!0,children:[`… +`,m,` `,s?`more `:``,`line`,m===1?``:`s`,s?``:` (ctrl+o to expand)`]})]}):(0,X.jsx)($,{dimColor:!0,children:`(no content)`})}),(0,X.jsx)(E0,{color:y?`red`:`brightblack`,children:t})]})}return(0,X.jsx)(Q,{flexDirection:`column`,children:(0,X.jsx)(T0,{name:`Bash`,params:_,paramsLanguage:`bash`,status:`pending`})})}const sUe=QL({command:Y(),explanation:Y().optional(),runInBackground:z0,shellId:Y().optional(),interactiveMode:z0,timeout:yR().optional()});function cUe({rawInput:e,status:t,parsedResult:n}){let r=sUe.safeParse(P0(e));if(!r.success)return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(T0,{name:`Bash`,params:``,paramsLanguage:`bash`,status:`error`}),(0,X.jsx)(E0,{color:`red`,children:`Invalid params`})]});let i=r.data,a=i.command||``,o=a.length>500?a.slice(0,500)+`…`:a,s=i.timeout?` (timeout: ${(i.timeout/1e3).toFixed(0)}s)`:``;if(t===`interrupted`)return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(T0,{name:`Bash`,params:o,paramsLanguage:`bash`,status:`interrupted`}),(0,X.jsx)(E0,{color:`yellow`,children:`Interrupted · What should I do instead?`})]});if(t===`rejected`)return n?.userNote?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(T0,{name:`Bash`,params:o,paramsLanguage:`bash`,status:`rejected`}),(0,X.jsxs)(E0,{color:`yellow`,children:[`Rejected · `,(0,X.jsxs)($,{italic:!0,children:[`"`,n.userNote,`"`]})]})]}):(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(T0,{name:`Bash`,params:o,paramsLanguage:`bash`,status:`rejected`}),(0,X.jsx)(E0,{color:`yellow`,children:`Rejected`})]});if(n?.data?.timedOut)return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(T0,{name:`Bash`,params:`${o}${s}`,paramsLanguage:`bash`,status:`success`}),(0,X.jsx)(E0,{children:`Running in the background`})]});if(n?.runInBackground)return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(T0,{name:`Bash`,params:`${o}${s}`,paramsLanguage:`bash`,status:`success`}),(0,X.jsx)(E0,{children:n.summary})]});let c=e?.id||`unknown`,l=n?.data;return(0,X.jsx)(oUe,{command:`${o}${s}`,toolCallId:c,executionResult:l})}const lUe={displayName:`Bash`,getHeaderParams(e){try{return e?.command||`[no command]`}catch{return`[unknown]`}},renderUI(e,t,n){return(0,X.jsx)(cUe,{rawInput:e,status:t,parsedResult:n})}},uUe=QL({shellId:Y()}),g3={read:gVe,delete:qBe,write:bVe,edit:tVe,notebook_edit:aVe,grep:YHe,glob:qHe,web_search:eUe,web_fetch:QHe,bash:lUe,bash_output:nUe,kill_shell:{displayName:`KillShell`,getHeaderParams(e){try{return`id: ${e.shellId||``}`}catch{return`[unknown]`}},renderUI(e,t,n){let r=uUe.safeParse(P0(e));if(!r.success)return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(T0,{name:`KillShell`,params:``,status:`error`}),(0,X.jsx)(E0,{color:`red`,children:`Invalid params`})]});let i=`id: ${r.data.shellId}`;return t===`interrupted`?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(T0,{name:`KillShell`,params:i,status:`interrupted`}),(0,X.jsx)(E0,{color:`yellow`,children:`Interrupted · What should I do instead?`})]}):t===`rejected`?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(T0,{name:`KillShell`,params:i,status:`rejected`}),n?.userNote?(0,X.jsxs)(E0,{color:`yellow`,children:[`Rejected · `,(0,X.jsxs)($,{italic:!0,children:[`"`,n.userNote,`"`]})]}):(0,X.jsx)(E0,{color:`yellow`,children:`Rejected`})]}):!n&&(t===`executing`||t===`pending`)?(0,X.jsx)(T0,{name:`KillShell`,params:i,status:`pending`,showSpinner:!0}):n?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(T0,{name:`KillShell`,params:i,status:`success`}),(0,X.jsx)(E0,{children:n.summary})]}):(0,X.jsx)(Q,{flexDirection:`column`,children:(0,X.jsx)(T0,{name:`KillShell`,params:i,status:`pending`})})}},navigate_to:zBe,new_tab:VBe,close_tab:jBe,switch_active_tab:KBe,refresh_tab:WBe,get_tab_content:LBe,computer:NBe,get_interactive_elements:FBe,perform_interactive_element_action:UBe,ask_user_question:_Be,enter_plan_mode:vBe,exit_plan_mode:SBe,subagent:wBe,task:EBe,todo_write:kBe,get_diagnostics:SVe};function dUe(e,t){g3[e]=t??KHe(e)}function fUe(e){let t=e.toolUseRequest;return t?(Array.isArray(t)?t:[t]).map(e=>{let t=e;return{name:t.name??``,input:t.input??{}}}).filter(e=>e.name):[]}function pUe(e,t=4){let n=[];for(let r of e){if(n.length>=t)break;for(let e of fUe(r)){if(n.length>=t)break;let r=g3[e.name];if(!r)continue;let i=``;try{i=r.getHeaderParams(e.input)}catch{}if(!i)continue;let a=r.displayName??e.name;n.push({label:a,detail:i})}}return n}const _3=(0,Z.memo)(({counts:e,segments:t})=>{let n=(0,Z.useMemo)(()=>{let t=[];return e.toolUses>0&&t.push(`${e.toolUses} tool ${e.toolUses===1?`use`:`uses`}`),e.responses>0&&t.push(`${e.responses} ${e.responses===1?`response`:`responses`}`),t.length===0?`Conversation compacted`:t.join(`, `)+` compacted`},[e]),r=(0,Z.useMemo)(()=>pUe(t),[t]);return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsxs)(Q,{flexDirection:`row`,gap:1,children:[(0,X.jsx)($,{color:XQ,children:`⟐`}),(0,X.jsx)($,{color:XQ,dimColor:!0,children:n}),(0,X.jsx)($,{color:XQ,dimColor:!0,children:`(ctrl+o to expand)`})]}),r.map((e,t)=>(0,X.jsx)(Q,{flexDirection:`row`,paddingLeft:2,children:(0,X.jsxs)($,{color:XQ,dimColor:!0,children:[`⎿ `,e.label,` `,e.detail]})},t))]})});_3.displayName=`CompactedPlaceholder`;const v3=(0,Z.createContext)(null);function mUe(){let e=(0,Z.use)(v3);if(!e)throw Error(`useUpdate must be used within UpdateProvider`);return e}function hUe({children:e,configService:t}){let[n,r]=(0,Z.useState)(null),{autoUpdate:i,updateChannel:a,baseUrl:o}=(0,Z.useMemo)(()=>({autoUpdate:t.get(`autoUpdate`)!==!1,updateChannel:t.get(`updateChannel`),baseUrl:t.get(`baseUrl`)}),[t]);(0,Z.useEffect)(()=>{if(IZ())return;let e=!0,t=()=>{LZ(DZ.default.version,a,o).then(t=>{e&&r(e=>e?.latestVersion===t?.latestVersion?e:t)}).catch(()=>{})};t();let n=setInterval(t,6e4);return()=>{e=!1,clearInterval(n)}},[a,o]);let s=(0,Z.useMemo)(()=>({updateInfo:n,autoUpdate:i}),[n,i]);return(0,X.jsx)(v3.Provider,{value:s,children:e})}const y3=(0,Z.createContext)(null),b3=()=>{let e=(0,Z.use)(y3);if(!e)throw Error(`${b3.name} must be used within a ${x3.name}`);return e};function x3({children:e}){let[t,n]=(0,Z.useState)({columns:process.stdout.columns-8,rows:process.stdout.rows}),r=(0,Z.useCallback)(()=>{n({columns:process.stdout.columns-8,rows:process.stdout.rows})},[]);(0,Z.useLayoutEffect)(()=>(process.stdout.on(`resize`,r),()=>{process.stdout.off(`resize`,r)}),[r]);let i=(0,Z.useMemo)(()=>({width:t.columns,height:t.rows}),[t.columns,t.rows]);return(0,X.jsx)(y3.Provider,{value:i,children:e})}function gUe(){let{height:e}=b3();return Math.max(0,e-3)}let S3=function(e){return e.Models=`models`,e.UserInfo=`userInfo`,e.CreateConversation=`create-conversation`,e.GetConversation=`get-conversation`,e.Grep=`grep`,e.ReadFile=`read-file`,e.EditFile=`edit-file`,e.Bash=`bash`,e.BashOutput=`bash-output`,e.MCPTool=`mcp-tool`,e.PrInfo=`pr-info`,e}({});function _Ue(e){return qQ({queryKey:[S3.Models],queryFn:async()=>{try{return(await e.listLLMModels())?.result??[]}catch{return[]}},initialData:[],staleTime:300*1e3,retry:1,refetchOnMount:`always`,refetchOnWindowFocus:!1})}function C3(e){return typeof e==`string`?e:typeof e==`object`&&e&&`segment`in e?e.segment:null}function vUe(){return process.platform===`win32`}async function yUe(e){return new Promise(t=>setTimeout(t,e))}function bUe({onlyFirst:e=!1}={}){return RegExp(`(?:\\u001B\\][\\s\\S]*?(?:\\u0007|\\u001B\\u005C|\\u009C))|[\\u001B\\u009B][[\\]()#;?]*(?:\\d{1,4}(?:[;:]\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]`,e?void 0:`g`)}const xUe=bUe();function w3(e){if(typeof e!=`string`)throw TypeError(`Expected a \`string\`, got \`${typeof e}\``);return!e.includes(`\x1B`)&&!e.includes(`›`)?e:e.replace(xUe,``)}const SUe=new Intl.Segmenter,CUe=RegExp(`^(?:\\p{Default_Ignorable_Code_Point}|\\p{Control}|\\p{Format}|\\p{Mark}|\\p{Surrogate})+$`,`v`),wUe=RegExp(`^[\\p{Default_Ignorable_Code_Point}\\p{Control}\\p{Format}\\p{Mark}\\p{Surrogate}]+`,`v`),TUe=RegExp(`^\\p{RGI_Emoji}$`,`v`),EUe=/^[\d#*]\u20E3$/,DUe=/\p{Extended_Pictographic}/gu;function OUe(e){if(e.length>50)return!1;if(EUe.test(e))return!0;if(e.includes(`‍`)){let t=e.match(DUe);return t!==null&&t.length>=2}return!1}function kUe(e){return e.replace(wUe,``)}function AUe(e){return CUe.test(e)}function jUe(e,t){let n=0;if(e.length>1)for(let r of e.slice(1))r>=`＀`&&r<=`￯`&&(n+=WJ(r.codePointAt(0),t));return n}function MUe(e,t={}){if(typeof e!=`string`||e.length===0)return 0;let{ambiguousIsNarrow:n=!0,countAnsiEscapeCodes:r=!1}=t,i=e;if(!r&&(i.includes(`\x1B`)||i.includes(`›`))&&(i=w3(i)),i.length===0)return 0;if(/^[\u0020-\u007E]*$/.test(i))return i.length;let a=0,o={ambiguousAsWide:!n};for(let{segment:e}of SUe.segment(i)){if(AUe(e))continue;if(TUe.test(e)||OUe(e)){a+=2;continue}let t=kUe(e).codePointAt(0);a+=WJ(t,o),a+=jUe(e,o)}return a}const NUe=[RegExp(`\x1B\\[2J`,`g`),RegExp(`\x1B\\[H`,`g`),RegExp(`\x1B\\[\\d+(;\\d+)?H`,`g`),RegExp(`\x1Bc`,`g`),RegExp(`\x1B\\[!p`,`g`),RegExp(`\x1B\\[\\?1049[hl]`,`g`),RegExp(`\x1B\\[\\d*[ABCD]`,`g`),RegExp(`\x1B\\[s`,`g`),RegExp(`\x1B\\[u`,`g`),RegExp(`\x1B\\[\\d*J`,`g`),RegExp(`\x1B\\[\\d*K`,`g`),RegExp(`\x1B\\[\\?25[hl]`,`g`),RegExp(`\x07`,`g`)];function PUe(e){let t=e;for(let e of NUe)t=t.replace(e,``);return t}const T3=new Map,E3=1e3;function D3(e){let t=!0;for(let n=0;n<e.length;n++)if(e.charCodeAt(n)>127){t=!1;break}if(t)return e.split(``);if(e.length<=E3){let t=T3.get(e);if(t)return t}let n=Array.from(e);return e.length<=E3&&T3.set(e,n),n}function O3(e){return D3(e).length}function k3(e,t,n){return D3(e).slice(t,n).join(``)}function A3(e){return D3(o(VMe(e))).filter(e=>{let t=e.codePointAt(0);return t===void 0?!1:t===10||t===13||t===9?!0:!(t>=0&&t<=31||t>=128&&t<=159)}).join(``)}const j3=new Map,M3=e=>{if(/^[\u0020-\u007E]*$/.test(e))return e.length;if(j3.has(e))return j3.get(e);let t=MUe(e);return j3.set(e,t),t};BMe();function FUe(e,t){if(!I3(e[t]))return!1;let n=t+1;for(;n<e.length&&R3(e[n]);)n++;return n>=e.length||!I3(e[n])}function IUe(e,t){let{lines:n,cursorRow:r,cursorCol:i}=e;switch(t.type){case`vim_delete_word_forward`:case`vim_change_word_forward`:{let{count:a}=t.payload,o=r,s=i;for(let e=0;e<a;e++){let e=G3(n,o,s,!0);if(e)o=e.row,s=e.col;else{let e=n[o]||``,t=W3(e,s);s=t===null?O3(e):t+1;break}}return o!==r||s!==i?Y3(e6(e),r,i,o,s,``):e}case`vim_delete_word_backward`:case`vim_change_word_backward`:{let{count:a}=t.payload,o=r,s=i;for(let e=0;e<a;e++){let e=K3(n,o,s);if(e)o=e.row,s=e.col;else break}return o!==r||s!==i?Y3(e6(e),o,s,r,i,``):e}case`vim_delete_word_end`:case`vim_change_word_end`:{let{count:a}=t.payload,o=r,s=i,c=r,l=i;for(let e=0;e<a;e++){let t=G3(n,o,s,!1);if(t){if(c=t.row,l=t.col+1,e<a-1){let e=G3(n,t.row,t.col+1,!0);if(e)o=e.row,s=e.col;else break}}else break}if(c<n.length){let e=O3(n[c]||``);l=Math.min(l,e)}return c!==r||l!==i?Y3(e6(e),r,i,c,l,``):e}case`vim_delete_line`:{let{count:i}=t.payload;if(n.length===0)return e;let a=Math.min(i,n.length-r),o=n.length;if(o===1||a>=o)return{...e6(e),lines:[``],cursorRow:0,cursorCol:0,preferredCol:null};let s=e6(e),c=[...s.lines];c.splice(r,a);let l=Math.min(r,c.length-1);return{...s,lines:c,cursorRow:l,cursorCol:0,preferredCol:null}}case`vim_change_line`:{let{count:i}=t.payload;if(n.length===0)return e;let a=Math.min(i,n.length-r),o=e6(e),{startOffset:s,endOffset:c}=J3(r,a,o.lines),{startRow:l,startCol:u,endRow:d,endCol:f}=q3(s,c,o.lines);return Y3(o,l,u,d,f,``)}case`vim_delete_to_end_of_line`:case`vim_change_to_end_of_line`:{let t=n[r]||``;return i<O3(t)?Y3(e6(e),r,i,r,O3(t),``):e}case`vim_change_movement`:{let{movement:a,count:o}=t.payload,s=n.length;switch(a){case`h`:{let t=Math.max(0,i-o);return Y3(e6(e),r,t,r,i,``)}case`j`:{let t=Math.min(o,s-r);if(t>0)if(s===1){let t=e.lines[0]||``;return Y3(e6(e),0,0,0,O3(t),``)}else{let n=e6(e),{startOffset:i,endOffset:a}=J3(r,t,n.lines),{startRow:o,startCol:s,endRow:c,endCol:l}=q3(i,a,n.lines);return Y3(n,o,s,c,l,``)}return e}case`k`:if(Math.min(o,r+1)>0)if(e.lines.length===1){let t=e.lines[0]||``;return Y3(e6(e),0,0,0,O3(t),``)}else{let t=Math.max(0,r-o+1),n=r-t+1,i=e6(e),{startOffset:a,endOffset:s}=J3(t,n,i.lines),{startRow:c,startCol:l,endRow:u,endCol:d}=q3(a,s,i.lines);return{...Y3(i,c,l,u,d,``),cursorRow:t,cursorCol:0}}return e;case`l`:return Y3(e6(e),r,i,r,Math.min(O3(n[r]||``),i+o),``);default:return e}}case`vim_move_left`:{let{count:n}=t.payload,{cursorRow:r,cursorCol:i,lines:a}=e,o=r,s=i;for(let e=0;e<n;e++)if(s>0)s--;else if(o>0){o--;let e=O3(a[o]||``);s=e===0?0:e-1}return{...e,cursorRow:o,cursorCol:s,preferredCol:null}}case`vim_move_right`:{let{count:n}=t.payload,{cursorRow:r,cursorCol:i,lines:a}=e,o=r,s=i;for(let e=0;e<n;e++){let e=a[o]||``,t=O3(e);if(t===0)o<a.length-1&&(o++,s=0);else if(s<t-1){s++;let n=D3(e);for(;s<n.length&&R3(n[s])&&s<t-1;)s++}else o<a.length-1&&(o++,s=0)}return{...e,cursorRow:o,cursorCol:s,preferredCol:null}}case`vim_move_up`:{let{count:n}=t.payload,{cursorRow:r,cursorCol:i,lines:a}=e,o=Math.max(0,r-n),s=O3(a[o]||``),c=Math.min(i,s>0?s-1:0);return{...e,cursorRow:o,cursorCol:c,preferredCol:null}}case`vim_move_down`:{let{count:n}=t.payload,{cursorRow:r,cursorCol:i,lines:a}=e,o=Math.min(a.length-1,r+n),s=O3(a[o]||``),c=Math.min(i,s>0?s-1:0);return{...e,cursorRow:o,cursorCol:c,preferredCol:null}}case`vim_move_word_forward`:{let{count:a}=t.payload,o=r,s=i;for(let e=0;e<a;e++){let e=G3(n,o,s,!0);if(e)o=e.row,s=e.col;else break}return{...e,cursorRow:o,cursorCol:s,preferredCol:null}}case`vim_move_word_backward`:{let{count:a}=t.payload,o=r,s=i;for(let e=0;e<a;e++){let e=K3(n,o,s);if(e)o=e.row,s=e.col;else break}return{...e,cursorRow:o,cursorCol:s,preferredCol:null}}case`vim_move_word_end`:{let{count:a}=t.payload,o=r,s=i;for(let e=0;e<a;e++){if(e===0){let e=D3(n[o]||``);if(s<e.length&&I3(e[s])&&(s+1>=e.length||!z3(e[s+1])||I3(e[s])&&FUe(e,s))){let e=G3(n,o,s+1,!1);if(e){o=e.row,s=e.col;continue}}}let t=G3(n,o,s,!1);if(t)o=t.row,s=t.col;else break}return{...e,cursorRow:o,cursorCol:s,preferredCol:null}}case`vim_delete_char`:{let{count:n}=t.payload,{cursorRow:r,cursorCol:i,lines:a}=e,o=O3(a[r]||``);if(i<o){let t=Math.min(n,o-i);return Y3(e6(e),r,i,r,i+t,``)}return e}case`vim_insert_at_cursor`:return e;case`vim_append_at_cursor`:{let{cursorRow:t,cursorCol:n,lines:r}=e,i=n<O3(r[t]||``)?n+1:n;return{...e,cursorCol:i,preferredCol:null}}case`vim_open_line_below`:{let{cursorRow:t,lines:n}=e,r=e6(e),i=O3(n[t]||``);return Y3(r,t,i,t,i,`
75249
75251
  `)}case`vim_open_line_above`:{let{cursorRow:t}=e;return{...Y3(e6(e),t,0,t,0,`
75250
75252
  `),cursorRow:t,cursorCol:0}}case`vim_append_at_line_end`:{let{cursorRow:t,lines:n}=e,r=O3(n[t]||``);return{...e,cursorCol:r,preferredCol:null}}case`vim_insert_at_line_start`:{let{cursorRow:t,lines:n}=e,r=n[t]||``,i=0,a=D3(r);for(;i<a.length&&/\s/.test(a[i]);)i++;return{...e,cursorCol:i,preferredCol:null}}case`vim_move_to_line_start`:return{...e,cursorCol:0,preferredCol:null};case`vim_move_to_line_end`:{let{cursorRow:t,lines:n}=e,r=O3(n[t]||``);return{...e,cursorCol:r>0?r-1:0,preferredCol:null}}case`vim_move_to_first_nonwhitespace`:{let{cursorRow:t,lines:n}=e,r=n[t]||``,i=0,a=D3(r);for(;i<a.length&&/\s/.test(a[i]);)i++;return{...e,cursorCol:i,preferredCol:null}}case`vim_move_to_first_line`:return{...e,cursorRow:0,cursorCol:0,preferredCol:null};case`vim_move_to_last_line`:{let{lines:t}=e,n=t.length-1;return{...e,cursorRow:n,cursorCol:0,preferredCol:null}}case`vim_move_to_line`:{let{lineNumber:n}=t.payload,{lines:r}=e,i=Math.min(Math.max(0,n-1),r.length-1);return{...e,cursorRow:i,cursorCol:0,preferredCol:null}}case`vim_escape_insert_mode`:{let{cursorCol:t}=e,n=t>0?t-1:0;return{...e,cursorCol:n,preferredCol:null}}default:return e}}const N3=dt([`codellm`,`cli`,`text-buffer`]);let P3=0;const LUe=/\[Pasted text (#\d+) \+\d+ lines\]/g;function RUe(e){return e.length>500?!0:e.split(/\r\n|\r|\n/).length>5}function zUe(e){P3++;let t=`#${P3}`;return{placeholder:`[Pasted text ${t} +${e.split(/\r\n|\r|\n/).length} lines]`,id:t}}function F3(e){return e===void 0?!1:!/[\s,.;!?]/.test(e)}const I3=e=>/[\w\p{L}\p{N}]/u.test(e),L3=e=>/\s/.test(e),R3=e=>/\p{M}/u.test(e),z3=e=>I3(e)||R3(e),B3=e=>/[\p{Script=Latin}]/u.test(e)?`latin`:/[\p{Script=Han}]/u.test(e)?`han`:/[\p{Script=Arabic}]/u.test(e)?`arabic`:/[\p{Script=Hiragana}]/u.test(e)?`hiragana`:/[\p{Script=Katakana}]/u.test(e)?`katakana`:/[\p{Script=Cyrillic}]/u.test(e)?`cyrillic`:`other`,V3=(e,t)=>!I3(e)||!I3(t)?!1:B3(e)!==B3(t),H3=(e,t)=>{let n=D3(e),r=t;if(r>=n.length)return null;let i=n[r];if(I3(i))for(;r<n.length&&z3(n[r]);){if(r+1<n.length&&I3(n[r+1])&&V3(n[r],n[r+1])){r++;break}r++}else if(!L3(i))for(;r<n.length&&!I3(n[r])&&!L3(n[r]);)r++;for(;r<n.length&&L3(n[r]);)r++;return r<n.length?r:null},U3=(e,t)=>{let n=D3(e),r=t;if(r<=0)return null;for(r--;r>=0&&L3(n[r]);)r--;if(r<0)return null;if(I3(n[r])){for(;r>=0&&I3(n[r]);){if(r-1>=0&&I3(n[r-1])&&V3(n[r],n[r-1]))return r;r--}return r+1}else{for(;r>=0&&!I3(n[r])&&!L3(n[r]);)r--;return r+1}},W3=(e,t)=>{let n=D3(e),r=t,i=r<n.length&&z3(n[r])&&(r+1>=n.length||!z3(n[r+1])||I3(n[r])&&r+1<n.length&&I3(n[r+1])&&V3(n[r],n[r+1])),a=r<n.length&&!z3(n[r])&&!L3(n[r])&&(r+1>=n.length||L3(n[r+1])||z3(n[r+1]));if(i||a)for(r++;r<n.length&&L3(n[r]);)r++;if(r<n.length&&!z3(n[r]))for(;r<n.length&&L3(n[r]);)r++;let o=!1,s=-1;if(r<n.length&&z3(n[r]))for(;r<n.length&&z3(n[r]);){if(o=!0,I3(n[r])&&(s=r),r+1<n.length&&I3(n[r+1])&&V3(n[r],n[r+1])){r++,I3(n[r-1])&&(s=r-1);break}r++}else if(r<n.length&&!L3(n[r]))for(;r<n.length&&!I3(n[r])&&!L3(n[r]);)o=!0,s=r,r++;return o&&s>=t?s:null},G3=(e,t,n,r)=>{let i=e[t]||``,a=r?H3(i,n):W3(i,n);if(a!==null)return{row:t,col:a};for(let n=t+1;n<e.length;n++){let t=e[n]||``,i=D3(t);if(i.length===0){let t=!1;for(let r=n+1;r<e.length;r++){let n=D3(e[r]||``),i=0;for(;i<n.length&&L3(n[i]);)i++;if(i<n.length){t=!0;break}}if(!t)return{row:n,col:0};continue}let a=0;for(;a<i.length&&L3(i[a]);)a++;if(a<i.length){if(r)return{row:n,col:a};{let e=W3(t,a);if(e!==null)return{row:n,col:e}}}}return null},K3=(e,t,n)=>{let r=U3(e[t]||``,n);if(r!==null)return{row:t,col:r};for(let n=t-1;n>=0;n--){let t=e[n]||``,r=D3(t);if(r.length===0)continue;let i=r.length;for(;i>0&&L3(r[i-1]);)i--;if(i>0){let e=U3(t,i);if(e!==null)return{row:n,col:e}}}return null},q3=(e,t,n)=>{let r=0,i=0,a=0,o=0,s=0;for(let t=0;t<n.length;t++){let o=n[t].length+1;if(r+o>e){i=t,a=e-r;break}r+=o}r=0;for(let e=0;e<n.length;e++){let i=n[e].length+(e<n.length-1?1:0);if(r+i>=t){o=e,s=t-r;break}r+=i}return{startRow:i,startCol:a,endRow:o,endCol:s}},J3=(e,t,n)=>{let r=0;for(let t=0;t<e;t++)r+=n[t].length+1;let i=r;for(let r=0;r<t;r++){let t=e+r;t<n.length&&(i+=n[t].length,t<n.length-1&&(i+=1))}return{startOffset:r,endOffset:i}},Y3=(e,t,n,r,i,a)=>{let o=t=>e.lines[t]||``,s=e=>O3(o(e)),c=(e,t,n)=>Math.min(Math.max(e,t),n);if(t>r||t===r&&n>i||t<0||n<0||r>=e.lines.length||r<e.lines.length&&i>s(r))return e;let l=[...e.lines],u=c(n,0,s(t)),d=c(i,0,s(r)),f=k3(o(t),0,u),p=k3(o(r),d),m=a.replace(/\r\n/g,`
@@ -75325,12 +75327,12 @@ Please restart your terminal for changes to take effect.`),n(t,`info`)}else n(e.
75325
75327
  `).slice(-20).join(`
75326
75328
  `)}`,`info`)}}],uiProvider:(t,n)=>(0,X.jsx)(C6,{listTerminalSessions:e.listTerminalSessions,getTerminalSessionOutput:e.getTerminalSessionOutput,stopTerminalSession:e.stopTerminalSession,onDismiss:n.onDismiss}),execute:()=>{if(!e.listTerminalSessions){n(`Terminal sessions not available`,`error`);return}let t=e.listTerminalSessions();if(t.length===0){n(`No background tasks found`,`info`);return}let r=t.filter(e=>e.isRunning),i=t.filter(e=>!e.isRunning&&(e.exitCode??0)===0),a=t.filter(e=>!e.isRunning&&(e.exitCode??0)!==0),o=[];if(o.push(`Tasks:`),o.push(``),r.length>0){o.push(`In progress (${r.length}):`);for(let e of r){let t=h3(Date.now()-e.startTime),n=e.command.length>50?e.command.substring(0,47)+`...`:e.command;o.push(` [${e.id}] ${n} (${t})`)}o.push(``)}if(i.length>0){o.push(`Completed (${i.length}):`);for(let e of i.slice(-5)){let t=e.command.length>50?e.command.substring(0,47)+`...`:e.command;o.push(` [${e.id}] ${t} (ok)`)}i.length>5&&o.push(` ... and ${i.length-5} more`),o.push(``)}if(a.length>0){o.push(`Failed (${a.length}):`);for(let e of a.slice(-5)){let t=e.command.length>50?e.command.substring(0,47)+`...`:e.command;o.push(` [${e.id}] ${t} (exit ${e.exitCode})`)}a.length>5&&o.push(` ... and ${a.length-5} more`),o.push(``)}o.push(`Use /tasks output <id> to inspect logs`),o.push(`Use /tasks stop <id> to terminate`),n(o.join(`
75327
75329
  `),`info`)}},{id:`diff`,description:`Show git diff of all changes in an interactive viewer`,usage:`/diff`,uiProvider:(t,n)=>(0,X.jsx)(S6,{cwd:e.getCwd?.()??process.cwd(),onDismiss:n.onDismiss}),execute:async()=>{n(`Use /diff in interactive mode to view changes`,`info`)}},{id:`copy`,description:`Copy the last assistant response to clipboard`,usage:`/copy`,isAvailable:e=>e.segmentsLength>0,execute:()=>{let t=e.getLastAssistantMessage?.();if(!t){n(`No assistant response to copy`,`warning`);return}v2(t)?n(`Copied to clipboard`,`info`,!0):n(`Failed to copy to clipboard`,`error`)}},{id:`export`,description:`Export the current conversation to a file or clipboard`,usage:`/export`,uiProvider:(t,r)=>{let i=e=>{let t=[];for(let n of e)if(n.type===`text`&&n.segment){let e=n.source===`user`?`Human`:`Assistant`,r=typeof n.segment==`string`?n.segment:``;r&&t.push(`## ${e}\n\n${r}\n`)}return t.join(`
75328
- `)};return(0,X.jsx)(f6,{title:`Export Conversation`,subtitle:`Select export method:`,options:[{label:`Copy to clipboard`,description:`Copy the conversation to your system clipboard`,action:async()=>{let t=e.getSegmentsForExport?.()??[];if(t.length===0){n(`No conversation to export`,`warning`);return}let r=i(t);if(!r.trim()){n(`No text content to export`,`warning`);return}v2(r)?n(`Conversation copied to clipboard`,`info`):n(`Failed to copy to clipboard`,`error`)}},{label:`Save to file`,description:`Save the conversation to a file in the current directory`,action:async()=>{let t=e.getSegmentsForExport?.()??[];if(t.length===0){n(`No conversation to export`,`warning`);return}let r=i(t);if(!r.trim()){n(`No text content to export`,`warning`);return}let a=e.getCwd?.()??process.cwd(),o=O.join(a,`conversation.txt`);try{await Te.writeFile(o,r,`utf-8`),n(`Conversation saved to ${o}`,`info`)}catch(e){n(`Failed to save file: ${e instanceof Error?e.message:`Unknown error`}`,`error`)}}}],onDismiss:r.onDismiss})},execute:async()=>{n(`Use /export in interactive mode to export conversation`,`info`)}},{id:`feedback`,description:`Submit feedback about Abacus.AI CLI`,usage:`/feedback`,uiProvider:(t,n)=>{let r=e.getCwd?.()??process.cwd();return(0,X.jsx)(h6,{version:DZ.default.version,cwd:r,onDismiss:n.onDismiss})},execute:async()=>{n(`Use /feedback in interactive mode to submit feedback`,`info`)}}),x6.clear(),(async()=>{let t=r;if(e.checkEnvAuth){let{shouldHide:n}=e.checkEnvAuth();n&&(t=r.filter(e=>e.id!==`login`&&e.id!==`logout`))}t.forEach(e=>x6.register(e))})()}const w6=(0,Z.createContext)(null);function T6(){let e=(0,Z.use)(w6);if(!e)throw Error(`${T6.name} must be used within ${E6.name}`);return e}function E6({children:e}){let[t,n]=(0,Z.useState)(``),[r,i]=(0,Z.useState)(B0.Prompt),a=(0,Z.useRef)(null),[o,s]=(0,Z.useState)(`idle`),[c,l]=(0,Z.useState)(null),[u,d]=(0,Z.useState)(null),{queuedMessages:f,addToQueue:p,removeFirstFromQueue:m,clearQueue:h}=d3(),[g,_]=(0,Z.useState)([]),v=(0,Z.useCallback)(e=>{_(t=>[...t,e])},[]),y=(0,Z.useCallback)(()=>{_([])},[]),b=(0,Z.useMemo)(()=>({prompt:t,setPrompt:n,mode:r,setMode:i,bufferRef:a,activity:o,setActivity:s,queuedMessages:f,addToQueue:p,removeFirstFromQueue:m,clearQueue:h,attachments:g,setAttachments:_,addAttachment:v,clearAttachments:y,ghostText:c,setGhostText:l,commandOverlay:u,setCommandOverlay:d}),[t,r,o,f,p,m,h,g,v,y,c,u]);return(0,X.jsx)(w6.Provider,{value:b,children:e})}const D6=/[A-Za-z0-9_.~/\\-]/;function O6(e,t){let[n,r]=t,i=e.split(`
75329
- `)[n]||``,a=-1;for(let e=Math.min(r,i.length)-1;e>=0;e--){let t=i[e];if(t===`@`){a=e;break}if(!D6.test(t))break}if(a===-1)return null;if(a>0){let e=i[a-1];if(e&&!/\s/.test(e))return null}let o=a+1;for(;o<i.length&&D6.test(i[o]);)o++;let s=Math.min(r,o);return{query:i.slice(a+1,s),startRow:n,startCol:a,endRow:n,endCol:o}}function _We(){return[{regex:RegExp(`(?:^|\\s)@(?:'[^']*'|(?:[A-Za-z0-9_.~/-]|\\\\ )+)`,`gm`),color:`brightcyan`},{regex:RegExp(`^/[A-Za-z0-9_./\\-]+`,`gm`),color:`brightmagenta`},{regex:RegExp(`\\[Pasted text #\\d+ \\+\\d+ lines\\]`,`g`),color:`brightyellow`}]}const k6=(0,Z.memo)(()=>{let{queuedMessages:e}=T6();return e.length===0?null:(0,X.jsx)(Q,{flexDirection:`column`,children:e.map((e,t)=>(0,X.jsxs)(Q,{flexDirection:`row`,gap:1,children:[(0,X.jsx)($,{color:XQ,children:`❯`}),(0,X.jsx)($,{color:XQ,italic:!0,children:e.trim()})]},t))})});k6.displayName=`MessageQueue`;const A6=(0,Z.memo)(({mode:e,prompt:t,handler:n,onExitFilesMode:r,onSubmitPrompt:i,hints:a,availableHeight:o,onLoadingChange:s,commandContext:c})=>n?(0,X.jsx)(X.Fragment,{children:n.render({prompt:t,onExit:r,onSubmitPrompt:i,hints:a,availableHeight:o,onLoadingChange:s,commandContext:c})}):null);A6.displayName=`ModePanel`;function vWe(e){return typeof e==`string`?{label:e}:e}const j6=(0,Z.memo)(({items:e,limit:t=10,maxHeight:n,initialIndex:r=0,isActive:i=!0,showIndex:a=!0,showIndicators:o=!1,onHighlight:s,onSubmit:c,onTab:l,onCancel:u,onEscape:d,renderItem:f})=>{let p=e.length,[m,h]=(0,Z.useState)(Math.max(0,Math.min(r,Math.max(0,p-1)))),[g,_]=(0,Z.useState)(0),v=(0,Z.useMemo)(()=>e.map(vWe),[e]),y=(0,Z.useMemo)(()=>{if(n!==void 0&&n>0){let e=(o?2:0)+(a?1:0);return Math.max(1,Math.min(t,n-e))}return t},[n,t,o,a]),b=Math.max(1,Math.min(y,p||y)),x=Math.floor(b/2);(0,Z.useEffect)(()=>{m>=p&&(h(p===0?0:p-1),_(0))},[p,m]);let S=(0,Z.useEffectEvent)(e=>{typeof s==`function`&&p>0&&s(v[e].label,e)});(0,Z.useEffect)(()=>{S(m)},[m]);let C=(0,Z.useCallback)(e=>{let t=Math.max(0,p-b);return Math.max(0,Math.min(e,t))},[p,b]),w=(0,Z.useCallback)(()=>{if(p===0||m<=0)return;let e=m-1;h(e),e<g+x&&_(C(e-x)),e>g+b-1&&_(C(e-b+1))},[p,m,g,x,b,C]),T=(0,Z.useCallback)(()=>{if(p===0||m>=p-1)return;let e=m+1;h(e),e>g+x&&_(C(e-x)),e<g&&_(C(e))},[p,m,g,x,C]);bZ((e,t)=>{if(i){if(t.upArrow){w();return}if(t.downArrow){T();return}if(t.escape){d?.(),u?.();return}if(t.tab&&!t.ctrl&&!t.meta&&!t.shift){p>0&&l?.(v[m].label,m);return}t.return&&!t.ctrl&&!t.meta&&!t.shift&&(p>0?c?.(v[m].label,m):(d?.(),u?.()))}},{isActive:i});let E=(0,Z.useMemo)(()=>{if(p===0)return[];let e=Math.min(p,g+b);return v.slice(g,e)},[v,p,g,b]),D=n===void 0||n>=3,O=o&&D,k=a&&D;return(0,X.jsxs)(Q,{flexDirection:`column`,children:[O&&p>0&&g>0&&(0,X.jsxs)($,{dimColor:!0,children:[`▲ `,k&&p>1&&`(${m+1}/${p})`]}),p===0?(0,X.jsx)($,{dimColor:!0,children:`No matches`}):E.map((e,t)=>{let n=g+t,r=n===m;return f?(0,X.jsxs)(Q,{flexDirection:`row`,children:[(0,X.jsx)($,{color:r?`brightcyan`:void 0,children:r?`> `:` `}),f(e,r)]},`${e.label}-${n}`):(0,X.jsxs)($,{color:r?`brightcyan`:void 0,wrap:`truncate-end`,children:[r?`> `:` `,e.label,e.description?(0,X.jsxs)($,{dimColor:!0,children:[` `,e.description]}):null,e.badge?(0,X.jsxs)($,{color:`yellow`,children:[` [`,e.badge,`]`]}):null]},`${e.label}-${n}`)}),O&&p>0&&g+b<p&&(0,X.jsxs)($,{dimColor:!0,children:[`▼ `,k&&p>1&&`(${m+1}/${p})`]}),!O&&k&&p>1&&(0,X.jsx)($,{dimColor:!0,children:`(${m+1}/${p})`})]})});j6.displayName=`Select`;const M6=(0,Z.memo)(({prompt:e,onAccept:t,onCancel:n,availableHeight:r,onLoadingChange:i,commandContext:a,onSubmitPrompt:o})=>{let{bufferRef:s,setGhostText:c,setCommandOverlay:l}=T6(),[u,d]=(0,Z.useState)(null),[f,p]=(0,Z.useState)([]),[m,h]=(0,Z.useState)(!1),g=(0,Z.useCallback)(()=>{s.current?.setText(``)},[s]),_=(0,Z.useDeferredValue)((0,Z.useMemo)(()=>{let t=e.trim();return t.startsWith(`/`)?t.slice(1):``},[e])),v=(0,Z.useMemo)(()=>u?u.exactMatch?{type:`commands`,query:u.command.id}:u.needsSubcommand?{type:`subcommands`,query:u.query}:u.subcommand?.completionProvider||u.command.completionProvider?{type:`completions`,query:u.query}:null:{type:`commands`,query:_},[u,_]);(0,Z.useEffect)(()=>{let t=e.trimStart();if(!t.startsWith(`/`)){d(null);return}d(x6.match(t))},[e]),(0,Z.useEffect)(()=>{if(!u||u.needsSubcommand||u.exactMatch){c(null);return}let e=u.subcommand?.ghostProvider||u.command.ghostProvider;if(!e){c(null);return}return c(e(u.query||``)),()=>c(null)},[u,u?.query,c]),(0,Z.useEffect)(()=>{if(u)return;let t=e.trimStart();if(!t.startsWith(`/`))return;let n=cq.matchSkill(t);if(!n){c(null);return}let r=n.skill.frontmatter[`argument-hint`];if(!r){c(null);return}return c(n.args?null:r),()=>c(null)},[u,e,c]),(0,Z.useEffect)(()=>(i?.(m),()=>{i?.(!1)}),[m,i]),(0,Z.useEffect)(()=>{let e=u?.subcommand?.completionProvider||u?.command.completionProvider;if(!e||u?.needsSubcommand){p([]),h(!1);return}h(!0);let t=e(u.query||``);if(t instanceof Promise)t.then(e=>{p(e.map(e=>typeof e==`string`?e:e.label)),h(!1)}).catch(()=>{p([]),h(!1)});else if(Symbol.asyncIterator in Object(t)){let e=t;(async()=>{for await(let t of e)p(t.map(e=>typeof e==`string`?e:e.label));h(!1)})().catch(()=>{p([]),h(!1)})}else Array.isArray(t)&&(p(t.map(e=>typeof e==`string`?e:e.label)),h(!1))},[u,u?.query]);let y=(0,Z.useMemo)(()=>{if(!v)return[];if(v.type===`subcommands`&&u?.command.subcommands)return x6.searchSubcommands(u.command,v.query).map((e,t)=>({type:`subcommand`,display:`${e.id} - ${e.description}`,subcommandIdx:t}));if(v.type===`completions`)return m||f.length===0?[]:f.map(e=>({type:`completion`,display:e,value:e}));let e=x6.search(_,a).map((e,t)=>({type:`command`,display:`${e.id} - ${e.description}`,commandIdx:t})),t=cq.search(_).map(e=>({type:`skill`,display:`${e.id} - ${e.frontmatter.description} [skill]`,skill:e}));return[...e,...t]},[v,u,f,m,_,a]),b=(0,Z.useMemo)(()=>y.map(e=>e.display),[y]),x=(0,Z.useCallback)((e,t)=>{if(!v)return null;let n=y[t];if(!n)return null;if(n.type===`subcommand`&&u?.command.subcommands){let e=x6.searchSubcommands(u.command,v.query)[n.subcommandIdx];return e?`/${u.command.id} ${e.id} `:null}if(n.type===`completion`&&u)return m?null:`${u.subcommand?`/${u.command.id} ${u.subcommand.id}`:`/${u.command.id}`} ${n.value}`;if(n.type===`command`){let e=x6.search(_,a)[n.commandIdx];return e?`/${e.id} `:null}return n.type===`skill`?`/${n.skill.id} `:null},[v,u,_,m,a,y]),S=(0,Z.useCallback)((e,t)=>{let n=s.current;if(!n)return;let r=x(e,t);r&&n.setText(r)},[s,x]),C=(0,Z.useCallback)(async(e,n)=>{let r=s.current;if(!r){t();return}if(!v)return;let i=y[n];if(i){if(i.type===`subcommand`&&u?.command.subcommands){let e=x6.searchSubcommands(u.command,v.query)[i.subcommandIdx];e&&(e.requiresArgument||e.completionProvider?r.setText(`/${u.command.id} ${e.id} `):(await e.execute([]),r.setText(``),t()));return}if(i.type===`completion`&&u){if(m)return;let e=u.command;if(e.uiProvider){let t={onDismiss:()=>{l(null),g()},clearBuffer:g},n=u.subcommand?[u.subcommand.id,i.value]:[i.value],r=e.uiProvider(n,t);if(r){l(r);return}}let n=u.subcommand||u.command;n.execute&&(await n.execute([i.value]),r.setText(``),t());return}if(i.type===`skill`){r.setText(`/${i.skill.id} `);return}if(i.type===`command`){let e=x6.search(_,a)[i.commandIdx];if(!e)return;if(e.subcommands&&e.subcommands.length>0){r.setText(`/${e.id} `);return}if(e.requiresArgument||e.completionProvider){r.setText(`/${e.id} `);return}if(e.uiProvider){let t={onDismiss:()=>{l(null),g()},clearBuffer:g},n=e.uiProvider([],t);if(n){l(n);return}}e.execute&&(await e.execute([]),r.setText(``),t())}}},[s,u,_,t,v,m,a,g,l,y]),w=!!v&&b.length>0;return bZ((e,n)=>{if(!n.return||n.ctrl||n.meta||n.shift)return;let r=s.current;if(!r)return;let i=r.text.trimStart();if(!i.startsWith(`/`))return;let a=x6.match(i);if(!a||a.needsSubcommand){o&&o(i);return}let c=a.subcommand||a.command;if(!(c.completionProvider&&c.requiresArgument)){if(a.command.uiProvider){let e=a.args?a.args.split(/\s+/).filter(Boolean):[],t=a.subcommand?[a.subcommand.id,...e]:e,n={onDismiss:()=>{l(null),g()},clearBuffer:g},r=a.command.uiProvider(t,n);if(r){l(r);return}}(async()=>{await x6.execute(a)&&(r.setText(``),t())})()}},{isActive:!w}),w?(0,X.jsx)(Q,{flexDirection:`column`,children:(0,X.jsx)(j6,{items:b,limit:Math.max(1,Math.min(10,r-2)),maxHeight:r,isActive:!0,showIndex:!0,showIndicators:!0,onSubmit:C,onTab:S,onCancel:n})}):null});M6.displayName=`CommandPicker`;function yWe(e){let{setCommandOverlay:t}=T6(),n=(0,Z.useCallback)((n,r)=>{if(!n.uiProvider)return!1;let i={onDismiss:()=>{t(null),e()},clearBuffer:e},a=n.uiProvider(r,i);return a?(t(a),!0):!1},[t,e]);return{executeCommand:(0,Z.useCallback)(async t=>{let r=t.trimStart();if(!r.startsWith(`/`))return;let i=x6.match(r);if(!i||i.needsSubcommand)return;let a=i.subcommand||i.command;if(a.completionProvider&&a.requiresArgument){e();return}if(i.command.uiProvider&&i.args!==void 0){let e=i.args.split(/\s+/).filter(Boolean),t=i.subcommand?[i.subcommand.id,...e]:e;if(n(i.command,t))return}try{await x6.execute(i)&&e()}catch{}},[e,n]),showCommandUI:n,renderer:(0,Z.useCallback)(({prompt:e,onExit:t,availableHeight:n,onLoadingChange:r,commandContext:i,onSubmitPrompt:a})=>(0,X.jsx)(M6,{prompt:e,onAccept:t,onCancel:t,availableHeight:n,onLoadingChange:r,commandContext:i,onSubmitPrompt:a}),[]),shouldPreventDefault:(0,Z.useCallback)((e,t)=>!!(t.return||t.upArrow||t.downArrow||t.escape||t.tab),[])}}function N6({output:e,command:t,truncate:n=!1,maxLines:r=10}){let i=e.split(`
75330
+ `)};return(0,X.jsx)(f6,{title:`Export Conversation`,subtitle:`Select export method:`,options:[{label:`Copy to clipboard`,description:`Copy the conversation to your system clipboard`,action:async()=>{let t=e.getSegmentsForExport?.()??[];if(t.length===0){n(`No conversation to export`,`warning`);return}let r=i(t);if(!r.trim()){n(`No text content to export`,`warning`);return}v2(r)?n(`Conversation copied to clipboard`,`info`):n(`Failed to copy to clipboard`,`error`)}},{label:`Save to file`,description:`Save the conversation to a file in the current directory`,action:async()=>{let t=e.getSegmentsForExport?.()??[];if(t.length===0){n(`No conversation to export`,`warning`);return}let r=i(t);if(!r.trim()){n(`No text content to export`,`warning`);return}let a=e.getCwd?.()??process.cwd(),o=O.join(a,`conversation.txt`);try{await Te.writeFile(o,r,`utf-8`),n(`Conversation saved to ${o}`,`info`)}catch(e){n(`Failed to save file: ${e instanceof Error?e.message:`Unknown error`}`,`error`)}}}],onDismiss:r.onDismiss})},execute:async()=>{n(`Use /export in interactive mode to export conversation`,`info`)}},{id:`feedback`,description:`Submit feedback about Abacus.AI CLI`,usage:`/feedback`,uiProvider:(t,n)=>{let r=e.getCwd?.()??process.cwd();return(0,X.jsx)(h6,{version:DZ.default.version,cwd:r,onDismiss:n.onDismiss})},execute:async()=>{n(`Use /feedback in interactive mode to submit feedback`,`info`)}}),x6.clear(),(async()=>{let t=r;if(e.checkEnvAuth){let{shouldHide:n}=e.checkEnvAuth();n&&(t=r.filter(e=>e.id!==`login`&&e.id!==`logout`))}t.forEach(e=>x6.register(e))})()}const w6=(0,Z.createContext)(null);function T6(){let e=(0,Z.use)(w6);if(!e)throw Error(`${T6.name} must be used within ${E6.name}`);return e}function E6({children:e}){let[t,n]=(0,Z.useState)(``),[r,i]=(0,Z.useState)(B0.Prompt),a=(0,Z.useRef)(null),[o,s]=(0,Z.useState)(`idle`),[c,l]=(0,Z.useState)(null),[u,d]=(0,Z.useState)(null),{queuedMessages:f,nq:p,dq:m,removeFromQueue:h,setQueuedMessageContent:g,clearQueue:_}=d3(),[v,y]=(0,Z.useState)([]),b=(0,Z.useCallback)(e=>{y(t=>[...t,e])},[]),x=(0,Z.useCallback)(()=>{y([])},[]),S=(0,Z.useMemo)(()=>({prompt:t,setPrompt:n,mode:r,setMode:i,bufferRef:a,activity:o,setActivity:s,queuedMessages:f,nq:p,dq:m,removeFromQueue:h,setQueuedMessageContent:g,clearQueue:_,attachments:v,setAttachments:y,addAttachment:b,clearAttachments:x,ghostText:c,setGhostText:l,commandOverlay:u,setCommandOverlay:d}),[t,r,o,f,p,m,h,g,_,v,b,x,c,u]);return(0,X.jsx)(w6.Provider,{value:S,children:e})}const D6=/[A-Za-z0-9_.~/\\-]/;function O6(e,t){let[n,r]=t,i=e.split(`
75331
+ `)[n]||``,a=-1;for(let e=Math.min(r,i.length)-1;e>=0;e--){let t=i[e];if(t===`@`){a=e;break}if(!D6.test(t))break}if(a===-1)return null;if(a>0){let e=i[a-1];if(e&&!/\s/.test(e))return null}let o=a+1;for(;o<i.length&&D6.test(i[o]);)o++;let s=Math.min(r,o);return{query:i.slice(a+1,s),startRow:n,startCol:a,endRow:n,endCol:o}}function _We(){return[{regex:RegExp(`(?:^|\\s)@(?:'[^']*'|(?:[A-Za-z0-9_.~/-]|\\\\ )+)`,`gm`),color:`brightcyan`},{regex:RegExp(`^/[A-Za-z0-9_./\\-]+`,`gm`),color:`brightmagenta`},{regex:RegExp(`\\[Pasted text #\\d+ \\+\\d+ lines\\]`,`g`),color:`brightyellow`}]}const k6=(0,Z.memo)(()=>{let{queuedMessages:e}=T6(),t=e.filter(e=>!e.hidden);return t.length===0?null:(0,X.jsx)(Q,{flexDirection:`column`,children:t.map((e,t)=>(0,X.jsxs)(Q,{flexDirection:`row`,gap:1,children:[(0,X.jsx)($,{color:XQ,children:`❯`}),(0,X.jsx)($,{color:XQ,italic:!0,children:e.message.trim()})]},e.id||t))})});k6.displayName=`MessageQueue`;const A6=(0,Z.memo)(({mode:e,prompt:t,handler:n,onExitFilesMode:r,onSubmitPrompt:i,hints:a,availableHeight:o,onLoadingChange:s,commandContext:c})=>n?(0,X.jsx)(X.Fragment,{children:n.render({prompt:t,onExit:r,onSubmitPrompt:i,hints:a,availableHeight:o,onLoadingChange:s,commandContext:c})}):null);A6.displayName=`ModePanel`;function vWe(e){return typeof e==`string`?{label:e}:e}const j6=(0,Z.memo)(({items:e,limit:t=10,maxHeight:n,initialIndex:r=0,isActive:i=!0,showIndex:a=!0,showIndicators:o=!1,onHighlight:s,onSubmit:c,onTab:l,onCancel:u,onEscape:d,renderItem:f})=>{let p=e.length,[m,h]=(0,Z.useState)(Math.max(0,Math.min(r,Math.max(0,p-1)))),[g,_]=(0,Z.useState)(0),v=(0,Z.useMemo)(()=>e.map(vWe),[e]),y=(0,Z.useMemo)(()=>{if(n!==void 0&&n>0){let e=(o?2:0)+(a?1:0);return Math.max(1,Math.min(t,n-e))}return t},[n,t,o,a]),b=Math.max(1,Math.min(y,p||y)),x=Math.floor(b/2);(0,Z.useEffect)(()=>{m>=p&&(h(p===0?0:p-1),_(0))},[p,m]);let S=(0,Z.useEffectEvent)(e=>{typeof s==`function`&&p>0&&s(v[e].label,e)});(0,Z.useEffect)(()=>{S(m)},[m]);let C=(0,Z.useCallback)(e=>{let t=Math.max(0,p-b);return Math.max(0,Math.min(e,t))},[p,b]),w=(0,Z.useCallback)(()=>{if(p===0||m<=0)return;let e=m-1;h(e),e<g+x&&_(C(e-x)),e>g+b-1&&_(C(e-b+1))},[p,m,g,x,b,C]),T=(0,Z.useCallback)(()=>{if(p===0||m>=p-1)return;let e=m+1;h(e),e>g+x&&_(C(e-x)),e<g&&_(C(e))},[p,m,g,x,C]);bZ((e,t)=>{if(i){if(t.upArrow){w();return}if(t.downArrow){T();return}if(t.escape){d?.(),u?.();return}if(t.tab&&!t.ctrl&&!t.meta&&!t.shift){p>0&&l?.(v[m].label,m);return}t.return&&!t.ctrl&&!t.meta&&!t.shift&&(p>0?c?.(v[m].label,m):(d?.(),u?.()))}},{isActive:i});let E=(0,Z.useMemo)(()=>{if(p===0)return[];let e=Math.min(p,g+b);return v.slice(g,e)},[v,p,g,b]),D=n===void 0||n>=3,O=o&&D,k=a&&D;return(0,X.jsxs)(Q,{flexDirection:`column`,children:[O&&p>0&&g>0&&(0,X.jsxs)($,{dimColor:!0,children:[`▲ `,k&&p>1&&`(${m+1}/${p})`]}),p===0?(0,X.jsx)($,{dimColor:!0,children:`No matches`}):E.map((e,t)=>{let n=g+t,r=n===m;return f?(0,X.jsxs)(Q,{flexDirection:`row`,children:[(0,X.jsx)($,{color:r?`brightcyan`:void 0,children:r?`> `:` `}),f(e,r)]},`${e.label}-${n}`):(0,X.jsxs)($,{color:r?`brightcyan`:void 0,wrap:`truncate-end`,children:[r?`> `:` `,e.label,e.description?(0,X.jsxs)($,{dimColor:!0,children:[` `,e.description]}):null,e.badge?(0,X.jsxs)($,{color:`yellow`,children:[` [`,e.badge,`]`]}):null]},`${e.label}-${n}`)}),O&&p>0&&g+b<p&&(0,X.jsxs)($,{dimColor:!0,children:[`▼ `,k&&p>1&&`(${m+1}/${p})`]}),!O&&k&&p>1&&(0,X.jsx)($,{dimColor:!0,children:`(${m+1}/${p})`})]})});j6.displayName=`Select`;const M6=(0,Z.memo)(({prompt:e,onAccept:t,onCancel:n,availableHeight:r,onLoadingChange:i,commandContext:a,onSubmitPrompt:o})=>{let{bufferRef:s,setGhostText:c,setCommandOverlay:l}=T6(),[u,d]=(0,Z.useState)(null),[f,p]=(0,Z.useState)([]),[m,h]=(0,Z.useState)(!1),g=(0,Z.useCallback)(()=>{s.current?.setText(``)},[s]),_=(0,Z.useDeferredValue)((0,Z.useMemo)(()=>{let t=e.trim();return t.startsWith(`/`)?t.slice(1):``},[e])),v=(0,Z.useMemo)(()=>u?u.exactMatch?{type:`commands`,query:u.command.id}:u.needsSubcommand?{type:`subcommands`,query:u.query}:u.subcommand?.completionProvider||u.command.completionProvider?{type:`completions`,query:u.query}:null:{type:`commands`,query:_},[u,_]);(0,Z.useEffect)(()=>{let t=e.trimStart();if(!t.startsWith(`/`)){d(null);return}d(x6.match(t))},[e]),(0,Z.useEffect)(()=>{if(!u||u.needsSubcommand||u.exactMatch){c(null);return}let e=u.subcommand?.ghostProvider||u.command.ghostProvider;if(!e){c(null);return}return c(e(u.query||``)),()=>c(null)},[u,u?.query,c]),(0,Z.useEffect)(()=>{if(u)return;let t=e.trimStart();if(!t.startsWith(`/`))return;let n=cq.matchSkill(t);if(!n){c(null);return}let r=n.skill.frontmatter[`argument-hint`];if(!r){c(null);return}return c(n.args?null:r),()=>c(null)},[u,e,c]),(0,Z.useEffect)(()=>(i?.(m),()=>{i?.(!1)}),[m,i]),(0,Z.useEffect)(()=>{let e=u?.subcommand?.completionProvider||u?.command.completionProvider;if(!e||u?.needsSubcommand){p([]),h(!1);return}h(!0);let t=e(u.query||``);if(t instanceof Promise)t.then(e=>{p(e.map(e=>typeof e==`string`?e:e.label)),h(!1)}).catch(()=>{p([]),h(!1)});else if(Symbol.asyncIterator in Object(t)){let e=t;(async()=>{for await(let t of e)p(t.map(e=>typeof e==`string`?e:e.label));h(!1)})().catch(()=>{p([]),h(!1)})}else Array.isArray(t)&&(p(t.map(e=>typeof e==`string`?e:e.label)),h(!1))},[u,u?.query]);let y=(0,Z.useMemo)(()=>{if(!v)return[];if(v.type===`subcommands`&&u?.command.subcommands)return x6.searchSubcommands(u.command,v.query).map((e,t)=>({type:`subcommand`,display:`${e.id} - ${e.description}`,subcommandIdx:t}));if(v.type===`completions`)return m||f.length===0?[]:f.map(e=>({type:`completion`,display:e,value:e}));let e=x6.search(_,a).map((e,t)=>({type:`command`,display:`${e.id} - ${e.description}`,commandIdx:t})),t=cq.search(_).map(e=>({type:`skill`,display:`${e.id} - ${e.frontmatter.description} [skill]`,skill:e}));return[...e,...t]},[v,u,f,m,_,a]),b=(0,Z.useMemo)(()=>y.map(e=>e.display),[y]),x=(0,Z.useCallback)((e,t)=>{if(!v)return null;let n=y[t];if(!n)return null;if(n.type===`subcommand`&&u?.command.subcommands){let e=x6.searchSubcommands(u.command,v.query)[n.subcommandIdx];return e?`/${u.command.id} ${e.id} `:null}if(n.type===`completion`&&u)return m?null:`${u.subcommand?`/${u.command.id} ${u.subcommand.id}`:`/${u.command.id}`} ${n.value}`;if(n.type===`command`){let e=x6.search(_,a)[n.commandIdx];return e?`/${e.id} `:null}return n.type===`skill`?`/${n.skill.id} `:null},[v,u,_,m,a,y]),S=(0,Z.useCallback)((e,t)=>{let n=s.current;if(!n)return;let r=x(e,t);r&&n.setText(r)},[s,x]),C=(0,Z.useCallback)(async(e,n)=>{let r=s.current;if(!r){t();return}if(!v)return;let i=y[n];if(i){if(i.type===`subcommand`&&u?.command.subcommands){let e=x6.searchSubcommands(u.command,v.query)[i.subcommandIdx];e&&(e.requiresArgument||e.completionProvider?r.setText(`/${u.command.id} ${e.id} `):(await e.execute([]),r.setText(``),t()));return}if(i.type===`completion`&&u){if(m)return;let e=u.command;if(e.uiProvider){let t={onDismiss:()=>{l(null),g()},clearBuffer:g},n=u.subcommand?[u.subcommand.id,i.value]:[i.value],r=e.uiProvider(n,t);if(r){l(r);return}}let n=u.subcommand||u.command;n.execute&&(await n.execute([i.value]),r.setText(``),t());return}if(i.type===`skill`){r.setText(`/${i.skill.id} `);return}if(i.type===`command`){let e=x6.search(_,a)[i.commandIdx];if(!e)return;if(e.subcommands&&e.subcommands.length>0){r.setText(`/${e.id} `);return}if(e.requiresArgument||e.completionProvider){r.setText(`/${e.id} `);return}if(e.uiProvider){let t={onDismiss:()=>{l(null),g()},clearBuffer:g},n=e.uiProvider([],t);if(n){l(n);return}}e.execute&&(await e.execute([]),r.setText(``),t())}}},[s,u,_,t,v,m,a,g,l,y]),w=!!v&&b.length>0;return bZ((e,n)=>{if(!n.return||n.ctrl||n.meta||n.shift)return;let r=s.current;if(!r)return;let i=r.text.trimStart();if(!i.startsWith(`/`))return;let a=x6.match(i);if(!a||a.needsSubcommand){o&&o(i);return}let c=a.subcommand||a.command;if(!(c.completionProvider&&c.requiresArgument)){if(a.command.uiProvider){let e=a.args?a.args.split(/\s+/).filter(Boolean):[],t=a.subcommand?[a.subcommand.id,...e]:e,n={onDismiss:()=>{l(null),g()},clearBuffer:g},r=a.command.uiProvider(t,n);if(r){l(r);return}}(async()=>{await x6.execute(a)&&(r.setText(``),t())})()}},{isActive:!w}),w?(0,X.jsx)(Q,{flexDirection:`column`,children:(0,X.jsx)(j6,{items:b,limit:Math.max(1,Math.min(10,r-2)),maxHeight:r,isActive:!0,showIndex:!0,showIndicators:!0,onSubmit:C,onTab:S,onCancel:n})}):null});M6.displayName=`CommandPicker`;function yWe(e){let{setCommandOverlay:t}=T6(),n=(0,Z.useCallback)((n,r)=>{if(!n.uiProvider)return!1;let i={onDismiss:()=>{t(null),e()},clearBuffer:e},a=n.uiProvider(r,i);return a?(t(a),!0):!1},[t,e]);return{executeCommand:(0,Z.useCallback)(async t=>{let r=t.trimStart();if(!r.startsWith(`/`))return;let i=x6.match(r);if(!i||i.needsSubcommand)return;let a=i.subcommand||i.command;if(a.completionProvider&&a.requiresArgument){e();return}if(i.command.uiProvider&&i.args!==void 0){let e=i.args.split(/\s+/).filter(Boolean),t=i.subcommand?[i.subcommand.id,...e]:e;if(n(i.command,t))return}try{await x6.execute(i)&&e()}catch{}},[e,n]),showCommandUI:n,renderer:(0,Z.useCallback)(({prompt:e,onExit:t,availableHeight:n,onLoadingChange:r,commandContext:i,onSubmitPrompt:a})=>(0,X.jsx)(M6,{prompt:e,onAccept:t,onCancel:t,availableHeight:n,onLoadingChange:r,commandContext:i,onSubmitPrompt:a}),[]),shouldPreventDefault:(0,Z.useCallback)((e,t)=>!!(t.return||t.upArrow||t.downArrow||t.escape||t.tab),[])}}function N6({output:e,command:t,truncate:n=!1,maxLines:r=10}){let i=e.split(`
75330
75332
  `),a=[],o=!1;if(n&&i.length>r){let e=Math.max(1,Math.floor(r/2)),t=i.slice(0,e).map((e,t)=>({line:e,originalIndex:t})),n=i.slice(-e).map((t,n)=>({line:t,originalIndex:i.length-e+n}));a=[...t,...n],o=!0}else a=i.map((e,t)=>({line:e,originalIndex:t}));return(0,X.jsxs)(Q,{flexDirection:`column`,paddingX:1,children:[(0,X.jsx)($,{dimColor:!0,children:`${M0(process.cwd())}$ ${t}`}),e&&a.map((e,t)=>o&&t===Math.floor(a.length/2)?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsxs)($,{dimColor:!0,children:[`... (`,i.length-r,` lines hidden) ...`]}),(0,X.jsx)($,{children:e.line})]},`trunc-${e.originalIndex}`):(0,X.jsx)($,{children:e.line},`line-${e.originalIndex}`))]})}const bWe=[`SIGUSR1`,`SIGUSR2`,`SIGTERM`,`SIGINT`,`SIGHUP`];function xWe(){let e=P.platform(),t={};for(let[e,n]of Object.entries(process.env))n!==void 0&&(t[e]=n);return e===`win32`?{command:process.env.COMSPEC||`cmd.exe`,args:[],env:t}:{command:process.env.SHELL||`/bin/bash`,args:[],env:{...t,BASH_SILENCE_DEPRECATION_WARNING:`1`,PS1:``}}}var SWe=class{shell=null;queue=[];notify=null;isProcessing=!1;destroyed=!1;isWindows;signalHandlers=new Map;constructor(){this.isWindows=P.platform()===`win32`,this.startShell(),this.setupSignalForwarding()}setupSignalForwarding(){for(let e of bWe){let t=()=>{if(this.shell&&!this.shell.killed&&this.shell.exitCode===null)try{this.shell.kill(e)}catch{}};this.signalHandlers.set(e,t),process.on(e,t)}}removeSignalHandlers(){for(let[e,t]of this.signalHandlers)process.removeListener(e,t);this.signalHandlers.clear()}startShell(){if(this.shell||this.destroyed)return;let{command:e,args:t,env:n}=xWe();this.shell=ue(e,t,{stdio:[`pipe`,`pipe`,`pipe`],env:n,cwd:process.cwd(),shell:!1}),this.shell.stdin&&this.shell.stdin.on(`error`,e=>{if(e.code!==`EPIPE`)throw e}),this.shell.stdout&&this.shell.stdout.on(`data`,e=>{let t=e.toString(`utf8`);if(this.queue.push({type:`stdout`,data:t}),this.notify){let e=this.notify;this.notify=null,e()}}),this.shell.stderr&&this.shell.stderr.on(`data`,e=>{let t=e.toString(`utf8`);if(!(t.includes(`no job control in this shell`)||t.includes(`The default interactive shell is now zsh`)||t.includes(`To update your account to use zsh`)||t.includes("please run `chsh -s /bin/zsh`")||t.includes(`For more details, please visit`))&&(this.queue.push({type:`stderr`,data:t}),this.notify)){let e=this.notify;this.notify=null,e()}}),this.shell.on(`exit`,()=>{this.shell=null,this.startShell()})}async executeCommand(e){if(!this.shell||!this.shell.stdin)throw Error(`Shell not initialized`);this.queue.length=0;let t=`__CMD_END_${Date.now()}_${Math.random().toString(36).substring(7)}__`,n;return n=this.isWindows?`${e}\necho ${t}\n`:`${e}\necho "${t}"\n`,this.shell.stdin.write(n),this.isProcessing=!0,{stream:this.createStream(t),exit:this.createExitPromise(t)}}async*createStream(e){for(;;){for(;this.queue.length>0;){let t=this.queue.shift();if(t){if(t.data.includes(e)){let n=t.data.replace(e,``).replace(/\n$/,``);n&&(yield{type:t.type,data:n}),this.isProcessing=!1;return}yield t}}if(!this.isProcessing)return;await new Promise(e=>{this.notify=e})}}async createExitPromise(e){for(;this.isProcessing;)await new Promise(e=>setTimeout(e,100));return 0}killProcessGracefully(e){try{e.kill(`SIGTERM`);let t=setTimeout(()=>{e&&!e.killed&&e.kill(`SIGKILL`)},5e3);t.unref&&t.unref()}catch{}}destroy(){this.destroyed=!0,this.removeSignalHandlers(),this.shell&&=(this.shell.stdin?.on(`error`,e=>{if(e.code!==`EPIPE`)throw e}),this.killProcessGracefully(this.shell),null)}};let P6=null;function CWe(){return P6||=new SWe,P6}function wWe({state:e,setState:t,onCommandComplete:n,commandHistory:r,currentPrompt:i,availableHeight:a}){let{submittedCommand:o,runId:s}=e,c=(0,Z.useMemo)(()=>o?.trim()||``,[o]),l=(0,Z.useRef)(-1),u=(0,Z.useRef)(null);(0,Z.useEffect)(()=>{if(!c||s===l.current)return;l.current=s,u.current&&u.current.abort();let e=new AbortController;return u.current=e,t(e=>({...e,isRunning:!0,output:``})),TWe({command:c,setOutput:e=>{t(t=>({...t,output:e}))},signal:e.signal}).then(r=>{e.signal.aborted||(t(e=>({...e,isRunning:!1})),r!==void 0&&n(r))}).catch(r=>{e.signal.aborted||(t(e=>({...e,isRunning:!1})),n(``))}),()=>{e.abort(),u.current=null}},[c,s,t,n]);let d=i.trim().length>0,f=o?2:3,p=r.slice(-f),m=Math.max(0,r.length-f),h=p.length+(o?1:0),g=Math.max(1,a-h),_=h>0?Math.max(3,Math.floor(g/h)):10,v=d||a<15||h>1;return(0,X.jsxs)(Q,{flexDirection:`column`,children:[p.map((e,t)=>{let n=m+t;return(0,X.jsx)(N6,{output:e.output,command:e.command,truncate:v,maxLines:_},`history-${n}`)}),o&&(0,X.jsx)(N6,{output:e.output,command:c||o,truncate:v,maxLines:_},`submitted-${s}`)]})}async function TWe({command:e,setOutput:t,signal:n}){let{stream:r,exit:i}=await CWe().executeCommand(e),a=``;try{for await(let e of r){if(n.aborted)return;a+=PUe(e.data),n.aborted||t(a)}return n.aborted?void 0:(await i,a)}catch(e){if(n.aborted)return;throw e}}var EWe=Xe({parseShellHistory:()=>I6,shellHistory:()=>OWe,shellHistoryPath:()=>L6});function DWe(e){let t=[];for(let n=0;n<e.length;n++){let r=e[n];r===131&&n+1<e.length?(t.push(e[n+1]^32),n++):t.push(r)}return Buffer.from(t)}function F6(e){return I6(DWe(c.readFileSync(e)).toString(`utf8`))}function I6(e){let t=/^: \d+:0;/;return e.trim().split(`
75331
75333
  `).map(e=>t.test(e)?e.split(`;`).slice(1).join(`;`):e)}function L6({extraPaths:e=[]}={}){if(process.env.HISTFILE)return process.env.HISTFILE;let t=ee.homedir(),n=new Set([O.join(t,`.bash_history`),O.join(t,`.zsh_history`),O.join(t,`.history`)]);for(let t of e)n.add(t);return(()=>{let e,t=0;for(let r of n)c.existsSync(r)&&c.statSync(r).size>t&&(t=c.statSync(r).size,e=r);return e})()}function OWe(e={}){if(process.platform===`win32`){let t=L6(e);if(t)return F6(t);let{stdout:n}=ae.spawnSync(`doskey`,[`/history`],{encoding:`utf8`});return n.trim().split(`\r
75332
- `)}return F6(L6(e))}var kWe=W((()=>{}));const R6=1e3;function AWe(){let[e,t]=(0,Z.useState)({submittedCommand:null,runId:0,output:``,isRunning:!1}),[n,r]=(0,Z.useState)([]),[i,a]=(0,Z.useState)([]),[o,s]=(0,Z.useState)(-1),c=(0,Z.useRef)(!1);(0,Z.useEffect)(()=>{c.current||(c.current=!0,Promise.resolve().then(()=>(kWe(),EWe)).then(e=>{let t=e.shellHistory??e.default;a((typeof t==`function`?t():[]).slice(-R6))}).catch(()=>{}))},[]);let l=(0,Z.useCallback)(e=>{let n=e.trim();n&&(a(e=>e.length>0&&e[e.length-1]===n?e:[...e,n].slice(-R6)),s(-1),t(e=>({submittedCommand:n,runId:e.runId+1,output:``,isRunning:!0})))},[]),u=(0,Z.useCallback)(e=>{t(t=>(t.submittedCommand&&r(n=>[...n,{command:t.submittedCommand,output:e}].slice(-1e3)),{submittedCommand:null,runId:t.runId,output:``,isRunning:!1}))},[]);return{submitCommand:l,renderer:(0,Z.useCallback)(r=>(0,X.jsx)(wWe,{state:e,setState:t,onCommandComplete:u,commandHistory:n,currentPrompt:r.prompt,availableHeight:r.availableHeight}),[e,u,n]),navigateHistory:(0,Z.useCallback)(e=>{if(i.length===0)return null;let t=o;return e===`up`?t=o===-1?i.length-1:Math.max(0,o-1):(t=o===-1?-1:o+1,t>=i.length&&(t=-1)),s(t),t===-1?``:i[t]},[i,o]),getActivity:()=>e.isRunning?`pending`:`idle`}}const jWe=[`no pull requests found`,`no open pull requests`];function MWe(){return new Promise((e,t)=>{se(`gh`,[`pr`,`view`,`--json`,`number,url,reviewDecision,isDraft,state`],{timeout:1e4},(n,r,i)=>{if(n){let r=(i||n.message).toLowerCase();jWe.some(e=>r.includes(e))?e(null):t(n);return}try{let t=JSON.parse(r.trim());if(typeof t.number==`number`&&typeof t.url==`string`&&t.number>0){let n=`pending`;t.state===`MERGED`?n=`merged`:t.state===`CLOSED`?n=`closed`:t.isDraft?n=`draft`:t.reviewDecision===`APPROVED`?n=`approved`:t.reviewDecision===`CHANGES_REQUESTED`&&(n=`changes_requested`),e({number:t.number,url:t.url,reviewState:n});return}}catch{t(Error(`Malformed JSON from gh pr view`))}e(null)})})}const z6=6e4;function NWe(){let{data:e}=qQ({queryKey:[S3.PrInfo],queryFn:MWe,staleTime:z6,refetchInterval:z6,retry:!1,refetchOnMount:!0,refetchOnWindowFocus:!1});return e??null}function B6({href:e,children:t,color:n}){let r=mZ(e),i=hZ();return(0,X.jsx)($,{color:n??WNe,underline:!0,transform:e=>`${r}${e}${i}`,children:t})}B6.displayName=`Link`;const PWe={approved:`green`,pending:`yellow`,changes_requested:`red`,draft:`brightblack`,merged:`magenta`,closed:`brightblack`},V6=(0,Z.memo)(({hints:e,availableHeight:t})=>{let{agentMode:n,isWaitingForYoloConfirm:r}=H0(),i=NWe();if(t!==void 0&&t<1)return null;let a;if(e?.exitKey)a=(0,X.jsxs)($,{dimColor:!0,children:[`Press `,e.exitKey===`c`?`Ctrl+C`:`Ctrl+D`,` again to exit`]});else if(r)a=(0,X.jsxs)($,{dimColor:!0,children:[`Press `,(0,X.jsx)($,{color:`brightred`,children:`shift+tab`}),` again to enable YOLO mode (dangerous)`]});else switch(n){case xd.Normal:a=(0,X.jsx)($,{dimColor:!0,children:`? for shortcuts • shift+tab to cycle modes`});break;case xd.AcceptEdits:a=(0,X.jsxs)($,{dimColor:!0,children:[(0,X.jsx)($,{color:`brightcyan`,children:`⏵⏵`}),` accept edits on (shift+tab to cycle)`]});break;case xd.PlanMode:a=(0,X.jsxs)($,{dimColor:!0,children:[(0,X.jsx)($,{color:`brightcyan`,children:`⏸`}),` plan mode on (shift+tab to cycle)`]});break;case xd.Yolo:a=(0,X.jsxs)($,{dimColor:!0,children:[(0,X.jsx)($,{color:`brightred`,children:`⚠`}),` YOLO mode - all tools auto-accepted (shift+tab to cycle)`]});break;default:a=(0,X.jsx)($,{dimColor:!0,children:`? for shortcuts`})}return i?(0,X.jsxs)(Q,{flexDirection:`row`,gap:1,children:[(0,X.jsxs)(B6,{href:i.url,color:PWe[i.reviewState],children:[`PR #`,i.number]}),(0,X.jsx)($,{dimColor:!0,children:`•`}),a]}):a});V6.displayName=`AgentModeIndicator`;const H6=15e3,FWe=/^(node_modules|\.git|dist|build|out|coverage|\.vscode|\.idea|\.DS_Store)$/;let U6=null;function W6(e,t){let n=e.replace(/\\/g,`/`);return{path:n,name:O.posix.basename(n),isDirectory:t}}function IWe(e){return e.name.startsWith(`.`)||e.path.split(`/`).some(e=>e.startsWith(`.`)&&e!==`.`)}async function LWe(e){try{let t=await RWe(`git`,[`rev-parse`,`--show-toplevel`],e);if(!t)return null;let[n,r]=await Promise.all([G6(`git`,[`ls-files`],t),G6(`git`,[`ls-files`,`--others`,`--exclude-standard`],t)]),i=[],a=new Set;for(let e of[...n,...r]){if(!e)continue;let n=O.resolve(t,e);i.push(W6(n,!1));let r=O.posix.dirname(e);for(;r&&r!==`.`;){let e=O.resolve(t,r);if(a.has(e))break;a.add(e),i.push(W6(e,!0)),r=O.posix.dirname(r)}}return i}catch{return null}}function RWe(e,t,n){return new Promise((r,i)=>{let a=ue(e,t,{cwd:n,stdio:[`ignore`,`pipe`,`pipe`]}),o=``;a.stdout.on(`data`,e=>o+=e.toString()),a.on(`close`,e=>e===0?r(o.trim()):i()),a.on(`error`,i)})}function G6(e,t,n){return new Promise(r=>{let i=[],a=ue(e,t,{cwd:n,stdio:[`ignore`,`pipe`,`pipe`]});pe({input:a.stdout}).on(`line`,e=>i.push(e.trim())),a.on(`close`,()=>r(i)),a.on(`error`,()=>r(i))})}async function zWe(e,t){let n=[`--files`,`--no-messages`,`--max-depth`,`100`];t.includeHidden&&n.push(`--hidden`),t.useGitignore||n.push(`--no-ignore`);for(let e of t.globs)n.push(`-g`,e);for(let e of t.ignoreGlobs)n.push(`-g`,e);return new Promise(t=>{let r=[],i=ue(Ve,n,{cwd:e,stdio:[`ignore`,`pipe`,`pipe`]});pe({input:i.stdout}).on(`line`,t=>{let n=fBe(t.trim());n&&r.push(W6(O.resolve(e,n),!1))}),i.on(`close`,()=>t(r)),i.on(`error`,()=>t(r))})}async function K6(e,t){let n=[],r=async(e,i)=>{if(!(i>12||n.length>=H6))try{let a=await m.readdir(e,{withFileTypes:!0}),o=[];for(let r of a){if(!t&&r.name.startsWith(`.`))continue;let i=O.join(e,r.name);r.isDirectory()?FWe.test(r.name)||(n.push(W6(i,!0)),o.push(i)):r.isFile()&&n.push(W6(i,!1))}await Promise.all(o.map(e=>r(e,i+1)))}catch{}};return await r(e,0),n}function BWe(e){let t=e.includeHidden??!1,n=e.globs??[],r=e.ignoreGlobs??[],i=e.useRipgrep??!0,a=e.useGitignore??!0,o=e.root,s=new Set,c=[],l=e=>{c.length>=H6||s.has(e.path)||(s.add(e.path),!(!t&&IWe(e))&&c.push(e))},u=i&&a&&n.length===0&&r.length===0;return{docs:c,ready:(async()=>{if(u){let e=await LWe(o);if(e){for(let t of e)l(t);return}}if(i){let e=await zWe(o,{includeHidden:t,globs:n,ignoreGlobs:r,useGitignore:a});for(let t of e)l(t);let i=await K6(o,t);for(let e of i)e.isDirectory&&l(e)}else{let e=await K6(o,t);for(let t of e)l(t)}})()}}function VWe(e){let t=O.resolve(e.root);if(U6&&U6.key===t&&Date.now()-U6.at<6e4)return U6.index;let n=BWe(e);return U6={key:t,index:n,at:Date.now()},n}async function HWe(e,t,n){let r=new Map;for(let n=0;n<e.length;n+=64){let i=e.slice(n,n+64);await Promise.all(i.map(async e=>{try{let n=O.isAbsolute(e.path)?e.path:O.resolve(t,e.path),i=await m.stat(n);r.set(e.path,i.mtimeMs)}catch{r.set(e.path,0)}}))}let i=[...e].sort((e,t)=>{let n=(r.get(t.path)??0)-(r.get(e.path)??0);return n===0?e.path.split(`/`).length-t.path.split(`/`).length||e.name.localeCompare(t.name):n}).slice(0,n);return{paths:i.map(e=>e.path),isDirectory:i.map(e=>e.isDirectory)}}async function UWe(e,t){let n=t.root,r=t.maxResults??100;if(!(await m.stat(n).catch(()=>null))?.isDirectory())return{paths:[],isDirectory:[]};let i=VWe(t);await i.ready;let a=e.trim();if(!a)return HWe(i.docs,n,r);let o=new _H(i.docs,{selector:e=>e.path,limit:r}).find(a);return{paths:o.map(e=>e.item.path),isDirectory:o.map(e=>e.item.isDirectory)}}function WWe(e){let[t,n]=(0,Z.useState)([]),[r,i]=(0,Z.useState)([]),a=(0,Z.useRef)(null),o=(0,Z.useRef)(null),s=(0,Z.useRef)(null);return(0,Z.useEffect)(()=>(o.current&&clearTimeout(o.current),a.current&&a.current.abort(),o.current=setTimeout(()=>{if(e===s.current)return;s.current=e;let t=new AbortController;a.current=t,(async()=>{try{let r=await UWe(e,{root:process.cwd()});if(t.signal.aborted)return;n(r.paths.map(mBe)),i(r.isDirectory)}catch{}})()},100),()=>{o.current&&clearTimeout(o.current),a.current&&a.current.abort()}),[e]),{results:t,isDirectory:r}}const q6=(0,Z.memo)(({onAccept:e,onCancel:t,availableHeight:n})=>{let{prompt:r,bufferRef:i}=T6(),[a,o]=(0,Z.useState)(``);(0,Z.useEffect)(()=>{let e=i.current;if(!e){o(``);return}let t=O6(e.text,e.cursor)?.query??``;o(e=>e===t?e:t)},[i,r]);let s=(0,Z.useDeferredValue)(a),{results:c,isDirectory:l}=WWe(s),u=a!==s,d=c.map((e,t)=>l[t]?`${e}/`:e),f=(0,Z.useCallback)((t,n)=>{let r=i.current;if(!r)return e();let a=O6(r.text,r.cursor);if(a){let e=c[n];r.replaceRange(a.startRow,a.startCol,a.endRow,a.endCol,`@${e}${l[n]?`/`:``} `)}e()},[i,e,c,l]);return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(j6,{items:d,limit:Math.max(1,Math.min(10,n-2)),maxHeight:n,isActive:!0,showIndex:!0,showIndicators:!0,onSubmit:f,onTab:f,onCancel:t}),u&&(0,X.jsx)(Q,{marginTop:0,children:(0,X.jsx)($,{dimColor:!0,children:`Searching...`})})]})});q6.displayName=`FileMentionPicker`;const J6=[[`! for terminal/bash mode`,`/ for commands`,`@ for file paths`],[`esc esc to clear input`,`shift + tab to cycle agent modes`,`${ZUe().toLowerCase()} for newline`],[`ctrl + z to undo`,`ctrl + v to paste images`]],Y6=(0,Z.memo)(({availableHeight:e})=>e!==void 0&&e<3?null:(0,X.jsx)(Q,{flexDirection:`row`,columnGap:5,rowGap:1,flexWrap:`wrap`,children:(e!==void 0&&e<6?J6.slice(0,1):e!==void 0&&e<9?J6.slice(0,2):J6).map((e,t)=>(0,X.jsx)(Q,{flexDirection:`column`,children:e.map(e=>(0,X.jsx)($,{dimColor:!0,children:e},e))},t))}));Y6.displayName=`Help`;function GWe(){return{mode:B0.Prompt,render:({prompt:e,hints:t,availableHeight:n})=>(0,X.jsx)(V6,{hints:t,availableHeight:n})}}function KWe(){return{mode:B0.Help,render:({availableHeight:e})=>(0,X.jsx)(Y6,{availableHeight:e})}}function qWe(e){return{mode:B0.Files,render:({prompt:t,availableHeight:n})=>(0,X.jsx)(q6,{onAccept:e,onCancel:e,availableHeight:n}),shouldPreventDefault:(e,t)=>t.upArrow||t.downArrow||t.escape||t.return||t.tab}}function JWe(e,t){let n=AWe(),r=yWe(t);return{handlers:(0,Z.useMemo)(()=>{let t={mode:B0.Bash,render:n.renderer,onSubmit:n.submitCommand},i={mode:B0.Command,render:r.renderer,onSubmit:r.executeCommand,shouldPreventDefault:r.shouldPreventDefault};return new Map([[B0.Prompt,GWe()],[B0.Help,KWe()],[B0.Bash,t],[B0.Command,i],[B0.Files,qWe(e)]])},[n,r,e]),getActivity:n.getActivity,bashNavigateHistory:n.navigateHistory}}const YWe={[B0.Prompt]:{color:void 0,placeholder:`Try "Build a ecommerce website..."`,prefix:`❯`},[B0.Help]:{color:void 0,placeholder:`Try "Build a ecommerce website..."`,prefix:`❯`},[B0.Bash]:{color:`brightgreen`,placeholder:vUe()?`Try "dir"`:`Try "ls -la"`,prefix:`!`},[B0.Command]:{color:`brightmagenta`,placeholder:`Try "/resume <chat title>"`,prefix:`❯`},[B0.Files]:{color:`brightcyan`,placeholder:`Try "@help.md"`,prefix:`@`}},XWe={"!":{mode:B0.Bash,preventDefault:!0,atStartOnly:!0},"?":{mode:B0.Help,preventDefault:!0,atStartOnly:!0},"@":{mode:B0.Files,preventDefault:!1,atStartOnly:!1}},X6=(0,Z.memo)(({hints:e,composerRef:t})=>{let{prompt:n,setPrompt:r,mode:i,setMode:a,bufferRef:o,activity:s,setActivity:c,queuedMessages:l,addToQueue:u,clearQueue:d,addAttachment:f,clearAttachments:p,ghostText:m,commandOverlay:h}=T6(),{updateInfo:g,autoUpdate:_}=mUe(),v=(0,Z.useCallback)(e=>o.current?.getExpandedText(e)??e,[o]),y=(0,Z.useCallback)(()=>{},[]),b=(0,Z.useRef)({text:``,timer:null}),x=(0,Z.useRef)(null);x.current||(x.current=new yq(`cli-repl`),x.current.load());let S=x.current,C=(0,Z.useRef)(``),w=(0,Z.useRef)(0),T=(0,Z.useRef)(null),E=(0,Z.useCallback)(e=>{if(!new Set([B0.Prompt,B0.Help]).has(i))return!1;let t=e.trim();if(!t.startsWith(`/`))return!0;let n=t.slice(1).split(/\s/)[0]||``;return!(n===``||!/[/\\.]/.test(n)&&/^[a-zA-Z]/.test(n))},[i]);(0,Z.useImperativeHandle)(t,()=>({hasText:()=>n.length>0,hasQueue:()=>l.length>0,saveAndClear:()=>{let e=n.trimStart();e&&E(e)&&(S.append(e),S.resetNavigation()),o.current?.setText(``),y(),p()},clear:()=>{o.current?.setText(``),y(),p()},clearQueue:()=>d()}));let{currentFile:D,selectionStartLine:k,selectionEndLine:A}=t3(),{sendMessage:j,segments:M,clearSegments:N,clearSegmentsOnly:P,clearTempSegments:ee,stop:F,addNotification:te,mcp:I,isDirectoryAllowed:L,addAllowedDirectory:R,refreshMcpTools:z,loadConversation:ne,agentStatus:re,segmentsLength:ie,conversationId:ae,dequeuedOnStop:oe,clearDequeuedOnStop:se,listTerminalSessions:ce,getTerminalSessionOutput:le,stopTerminalSession:ue,totalCredits:de}=d3(),{apiClient:fe,authManager:B}=o3(),{data:pe=[],refetch:me}=_Ue(fe),he=WQ(),{cycleAgentMode:ge,resetToNormal:_e,isWaitingForYoloConfirm:ve}=H0(),ye=(0,Z.useContext)(G0),be=gUe(),{requestFullRedraw:V}=zMe(),{handlers:xe,getActivity:Se,bashNavigateHistory:Ce}=JWe(()=>a(B0.Prompt),(0,Z.useCallback)(()=>{o.current?.setText(``)},[o])),we=xe.get(i)||null,[Ee,De]=(0,Z.useState)([]),Oe=(0,Z.useRef)([]),[ke,Ae]=(0,Z.useState)(``),[je,Me]=(0,Z.useState)(null),[Ne,Pe]=(0,Z.useState)(!1),[Fe,Ie]=(0,Z.useState)(!1),Le=(0,Z.useMemo)(()=>({agentStatus:re,segmentsLength:ie,isLoggedIn:je??!1}),[re,ie,je]),Re=(0,Z.useCallback)(async()=>{try{let e=await fe.getConversationsList(hn.agentType,process.cwd());if(e?.result){let t=e.result.slice(0,25);De(t),Oe.current=t}}catch{}},[fe]);(0,Z.useEffect)(()=>{Re()},[Re]),(0,Z.useEffect)(()=>{fe.getUserInfo().then(e=>Me(!!e?.result?.email)).catch(()=>{Me(B.isAuthenticated())})},[fe,B]),(0,Z.useEffect)(()=>{oe&&(o.current?.setText(oe),se())},[oe,se,o]);let ze=ke||pe[0]?.llmName||``;(0,Z.useEffect)(()=>{if(!Ne){Ie(!1);return}let e=setInterval(()=>Ie(e=>!e),500);return()=>clearInterval(e)},[Ne]),(0,Z.useEffect)(()=>{gWe({onExit:()=>{QZ(0)},onNewChat:()=>{N(),d(),o.current?.setText(``),V()},onClearChat:()=>{P(),o.current?.setText(``),V()},onStop:()=>{F()},onModelChange:e=>{let t=pe.find(t=>t.llmName===e);t?(Ae(t.llmName),o.current?.setText(``)):te(`Model not found`,`error`)},onResumeChat:async e=>{let t=Oe.current.find(t=>t.deploymentConversationId===e);if(t||=Oe.current.find(t=>(t.name||t.deploymentConversationId||`Untitled`).toLowerCase().includes(e.toLowerCase())),t||(await Re(),t=Oe.current.find(t=>t.deploymentConversationId===e),t||=Oe.current.find(t=>(t.name||t.deploymentConversationId||`Untitled`).toLowerCase().includes(e.toLowerCase()))),!t)try{let n=(await fe.searchConversations(e,hn.agentType))?.result??[];if(n.length>0&&(t=n.find(t=>t.deploymentConversationId===e),!t)){let r=e.toLowerCase();t=n.find(e=>(e.name||e.deploymentConversationId||`Untitled`).toLowerCase().includes(r))}}catch{}if(t?.deploymentConversationId)try{d(),o.current?.setText(``),await ne(t.deploymentConversationId),te(`Resumed conversation: ${t.name||t.deploymentConversationId}`,`info`)}catch(e){te(`Failed to load conversation: ${e instanceof Error?e.message:`Unknown error`}`,`error`)}else te(`Conversation "${e}" not found`,`error`)},onLogin:async e=>{try{if(B.isEnvAuth()){te(`You are authenticated via an environment variable. Unset it to use /login or /logout.`,`error`);return}if(!e){te(`Usage: /login <email> or /login <api_key>`,`error`);return}if(/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)){let t=e,n=await FJ(),r=await fe.authenticateDeviceForCodeLlm(t,n);if(!r?.success||!r?.result){te(r?.error??`Failed to start device code login`,`error`);return}let{verificationUri:i,userCode:a,pollingInterval:o}=r.result;te(`Open the URL and enter the code to authenticate.\n\nURL: ${i}\nCode: ${a}\n\nPolling for completion...`,`info`),(async()=>{let e=(o||5)*1e3,t=Date.now()+600*1e3;for(;Date.now()<t;){await yUe(e);try{let e=await fe.pollDeviceCode(a);if(e?.success&&e.result?.deviceCode){let t=e.result.deviceCode,n=e.result.chatWebUrl;if(await B.loginWithDeviceCode(t),n){let e=n.replace(/^https?:\/\//,``);fe.setChatWebDomain(e)}te(`Authentication successful!`,`info`),Me(!0),await Re(),await me();return}}catch{}}te(`Authentication timed out. Please try again.`,`error`)})()}else{await B.loginWithApiKey(e);try{(await fe.getUserInfo())?.result?.email?(te(`API key login successful!`,`info`),Me(!0),await Re(),await me()):(await B.logout(),te(`Invalid API key — authentication failed`,`error`))}catch(e){await B.logout(),te(`API key authentication failed: ${e instanceof Error?e.message:`Unknown error`}`,`error`)}}o.current?.setText(``)}catch(e){te(`Login failed: ${e instanceof Error?e.message:`Unknown error`}`,`error`)}},onLogout:async()=>{if(B.isEnvAuth()){te(`You are authenticated via an environment variable. Unset it to use /login or /logout.`,`error`);return}await B.logout(),Me(!1)},getUserInfo:async()=>{try{let e=await fe.getUserInfo();if(e?.success&&e.result){let{name:t,email:n,organization:r}=e.result,i=r?.name||`No team`,a=B.getAuthKind(),o=a.type===`env_api_key`?`API key (env)`:a.type===`env_device_code`?`Device code (env)`:a.type===`api_key`?`API key`:a.type===`device_code`?`Device code`:a.type===`oauth_token`?`OAuth token`:`Unknown`;te(`User Status:\n\nName: ${t||`N/A`}\nEmail: ${n||`N/A`}\nTeam: ${i}\nAuth Method: ${o}`,`info`)}else te(`Failed to get user info`,`error`)}catch{te(`Failed to get user info`,`error`)}},getModels:async()=>pe.filter(e=>e.codeAgentSupported).map(e=>({label:e.name||e.llmName,value:e.llmName,model:e})),getChatTitles:async()=>(await Re(),Oe.current.map(e=>({id:e.deploymentConversationId||``,title:e.name||e.deploymentConversationId||`Untitled`,messageCount:e.hasHistory,date:e.createdAt}))),searchChatTitles:async e=>{try{let t=await fe.searchConversations(e,hn.agentType);if(t?.result)return t.result.map(e=>({id:e.deploymentConversationId||``,title:e.name||e.deploymentConversationId||`Untitled`,messageCount:e.hasHistory,date:e.createdAt}))}catch{}return[]},addNotification:te,mcp:I,isDirectoryAllowed:L,addAllowedDirectory:R,refreshMcpTools:z,getAgentStatus:()=>re,getTotalCredits:de>0?()=>Promise.resolve(de):void 0,loginAuth:{initiateDeviceCode:async e=>{let t=await FJ(),n=await fe.authenticateDeviceForCodeLlm(e,t);return!n?.success||!n?.result?{success:!1,error:n?.error??`Failed to start device code login`}:{success:!0,verificationUri:n.result.verificationUri,userCode:n.result.userCode,pollingInterval:n.result.pollingInterval}},pollDeviceCode:async e=>{let t=await fe.pollDeviceCode(e);return t?.success&&t.result?.deviceCode?{success:!0,deviceCode:t.result.deviceCode,chatWebUrl:t.result.chatWebUrl}:{success:!1}},completeDeviceCodeLogin:async(e,t)=>{if(await B.loginWithDeviceCode(e),t){let e=t.replace(/^https?:\/\//,``);fe.setChatWebDomain(e)}Me(!0),await Re(),await me()},loginWithApiKey:async e=>{if(await B.loginWithApiKey(e),!(await fe.getUserInfo())?.result?.email)throw await B.logout(),Error(`Invalid API key — authentication failed`);Me(!0),await Re(),await me()},isEnvAuth:()=>B.isEnvAuth()},checkEnvAuth:()=>({isEnvAuth:B.isEnvAuth(),shouldHide:B.isEnvAuth()}),getUpdateInfo:()=>g,listTerminalSessions:ce,getTerminalSessionOutput:le,stopTerminalSession:ue,getLastAssistantMessage:()=>{for(let e=M.length-1;e>=0;e--){let t=M[e];if(t.source===`bot`&&t.type===`text`&&t.status===`completed`){let e=C3(t.segment);if(e?.trim())return e}}return null},getCwd:()=>process.cwd(),getSegmentsForExport:()=>M,getOrganizations:async()=>{try{let e=await fe.listOrganizations();return!e?.success||!e.result?[]:e.result.map(e=>({id:e.organizationId,name:e.name,workspace:e.workspace}))}catch{return[]}},onOrgSwitch:async e=>{try{let t=await fe.switchOrganization(e);return t&&(await Re(),await me(),he.invalidateQueries({queryKey:[S3.UserInfo]})),t}catch{return!1}}})},[pe,M,N,P,V,d,o,fe,me,F,te,I,L,R,z,ne,Ee,Re,re,ae,B,g,ce,le,ue,de,he]);let Be=(0,Z.useCallback)(async e=>{try{let t=await Te.stat(e),n=await Te.readFile(e),r=O.extname(e).toLowerCase(),i={".png":`image/png`,".jpg":`image/jpeg`,".jpeg":`image/jpeg`,".webp":`image/webp`,".gif":`image/gif`,".heic":`image/heic`,".heif":`image/heif`}[r]??`image/png`;f({doc_id:`tui-`+Math.random().toString(36).slice(2,11)+`-`+Date.now().toString(36),filename:e,filePath:O.resolve(e),fileName:O.basename(e),content:n.toString(`base64`),mimeType:i,mime_type:i,size:t.size,metadata:{uploadedAt:new Date().toISOString(),source:`tui-clipboard`,isImage:!0,encoding:`base64`}})}catch{}},[f]),Ve=(0,Z.useCallback)(async()=>{if(await g2()){let e=await _2();if(e){let t=y2(b2(e));o.current?.insert(`@${t} `),await Be(e);return}}let e=await cVe();if(!e)return;let t=x2(e.trim());if(t){o.current?.insert(t.mentionText);for(let e of t.persistedImagePaths)Be(e);return}f2(e.trim())||o.current?.insert(e,{isPaste:!0})},[o,Be]),H=(0,Z.useCallback)(e=>{let t=e.target.cursor[0]===0&&e.target.cursor[1]===0;if(!e.key.paste){let t=process.platform===`darwin`&&e.key.super&&e.input===`v`,n=process.platform!==`darwin`&&e.key.ctrl&&e.input===`v`||process.platform===`linux`&&e.key.ctrl&&e.key.shift&&e.input===`V`;if(t||n){Ve(),e.preventDefault();return}}if(e.key.paste){let t=e.input.replace(/[\r\n]+$/,``),n=x2(t.trim());if(n){o.current?.insert(n.mentionText);for(let e of n.persistedImagePaths)Be(e);e.preventDefault();return}if(f2(t.trim())){e.preventDefault();return}(async()=>{if(await g2()){let e=await _2();if(e){let t=y2(b2(e));o.current?.insert(`@${t} `),await Be(e);return}}o.current?.insert(t,{isPaste:!0})})(),e.preventDefault();return}if(e.input.length>3&&!e.key.ctrl&&!e.key.meta&&!e.key.paste){b.current.text+=e.input,b.current.timer&&clearTimeout(b.current.timer),b.current.timer=setTimeout(()=>{let e=b.current.text;b.current={text:``,timer:null};let t=x2(e.trim());if(t){o.current?.insert(t.mentionText);for(let e of t.persistedImagePaths)Be(e);return}f2(e.trim())||o.current?.insert(e,{isPaste:!0})},50),e.preventDefault();return}if(i===B0.Prompt&&e.key.upArrow&&e.target.visualCursor[0]===0&&l.length>0&&n.trim()===``){let t=l.join(`
75333
- `);o.current?.setText(t),d(),e.preventDefault();return}if(we?.shouldPreventDefault&&we.shouldPreventDefault(e.input||``,e.key)){e.preventDefault();return}if((i===B0.Prompt||i===B0.Help||i===B0.Files)&&(e.key.upArrow||e.key.downArrow)){let t=e.target,r=t.visualCursor[0]===0,i=t.visualCursor[0]>=t.allVisualLines.length-1;if(e.key.upArrow&&r){if(S.getEntries().length>0){S.isNavigating()||(C.current=n);let t=S.navigateUp();if(t){o.current?.setText(t.message),e.preventDefault();return}}}else if(e.key.downArrow&&i){if(!S.isNavigating()){e.preventDefault();return}let t=S.navigateDown();t?o.current?.setText(t.message):o.current?.setText(C.current),e.preventDefault();return}}if(i===B0.Bash&&Ce){let t=e.target,n=e.key.upArrow&&t.visualCursor[0]===0,r=e.key.downArrow&&t.visualCursor[0]>=t.allVisualLines.length-1;if(n||r){let t=Ce(e.key.upArrow?`up`:`down`);if(t!==null){o.current?.setText(t),e.preventDefault();return}}}if(t&&e.key.backspace){if(ve){_e(),e.preventDefault();return}i!==B0.Prompt&&(a(B0.Prompt),S.resetNavigation(),C.current=``,e.preventDefault());return}if(i===B0.Prompt&&e.key.shift&&e.key.tab){ge(),e.preventDefault();return}let r=XWe[e.input];if(r&&(!r.atStartOnly||t)){i!==r.mode&&a(r.mode),r.preventDefault&&r.mode!==B0.Command&&e.preventDefault();return}},[i,a,we,Ce,o,Ve,Be,l,n,d,ve,_e,ge,S]);(0,Z.useEffect)(()=>{if(i===B0.Prompt)return;let e=n.trim();if(i===B0.Files){let e=o.current;e&&(O6(e.text,e.cursor)||a(B0.Prompt))}else if(i===B0.Command)if(e.length===0)a(B0.Prompt);else{let t=e.startsWith(`/`),n=e.slice(1).split(/\s/)[0]||``;t&&(n===``||!/[/\\.]/.test(n)&&/^[a-zA-Z]/.test(n))||a(B0.Prompt)}},[i,n,o,a]),(0,Z.useEffect)(()=>{if(i!==B0.Help)return;let e=setTimeout(()=>{a(B0.Prompt)},3e4);return()=>clearTimeout(e)},[i,a]);let He=(0,Z.useCallback)((e,t)=>{let n=w.current;w.current=e.length,r(e);let o=e.trim(),s=o.startsWith(`/`),c=o.slice(1).split(/\s/)[0]||``,l=s&&(c===``||!/[/\\.]/.test(c)&&/^[a-zA-Z]/.test(c)),u=re===Sd.Submitted||re===Sd.Streaming||re===Sd.ExecutingTool||re===Sd.WaitingForToolPermission;e.length>0&&!l&&!u&&ee();let d=O6(e,t.cursor);if(o.length===0&&n>0&&(i===B0.Command||i===B0.Bash||i===B0.Help)){a(B0.Prompt);return}if(d){i!==B0.Files&&a(B0.Files);return}if(i===B0.Files){d||a(B0.Prompt);return}i===B0.Help&&o.length>0&&a(B0.Prompt),T.current&&=(clearTimeout(T.current),null),!l&&i===B0.Command&&o.length>0?a(B0.Prompt):l&&i!==B0.Command&&(T.current=setTimeout(()=>{T.current=null,a(B0.Command)},80))},[i,r,a,ee,re]),Ue=(0,Z.useCallback)(async e=>{let t=e.trim(),n=x6.match(t,i);if(n&&await x6.execute(n)){o.current?.setText(``),p();return}if(t.startsWith(`/`)){let e=cq.matchSkill(t);if(e){if(je===!1){te(`Not logged in. Use /login email@example.com to login.`,`warning`);return}let n=v(t);if(re===Sd.Submitted||re===Sd.Streaming||re===Sd.ExecutingTool||re===Sd.WaitingForToolPermission){u(n),o.current?.setText(``),y();return}j({message:n,selectedModel:ke||pe[0]?.llmName||void 0,activeSkills:[e.skill.id]}),o.current?.setText(``),y(),p();return}}if(we?.onSubmit){we.onSubmit(e),i===B0.Bash?(o.current?.setText(``),c(Se())):i===B0.Command&&a(B0.Prompt),p();return}switch(i){case B0.Prompt:if(je===!1){let t=e.trimStart();t&&E(t)&&(S.append(t),S.resetNavigation()),te(`Not logged in. Use /login email@example.com to login.`,`warning`);return}if(re===Sd.Submitted||re===Sd.Streaming||re===Sd.ExecutingTool||re===Sd.WaitingForToolPermission){let t=v(e.trimStart());u(t),E(t)&&(S.append(t),S.resetNavigation()),C.current=``,y(),o.current?.setText(``);return}let t=ke||pe[0]?.llmName||void 0,n=v(e);E(n)&&(S.append(n),S.resetNavigation()),C.current=``,j({message:n,selectedModel:t}),y(),p();return;default:}},[i,we,j,Se,c,ke,a,o,re,u,te,p,je,v,y,S,pe]),{color:U,placeholder:We,prefix:Ge}=YWe[i],Ke=ie>0?``:We,qe=(0,Z.useMemo)(()=>_We(),[]),Je=(i===B0.Bash?Se():s)===`pending`||re===Sd.WaitingForToolPermission,Ye=M0(process.cwd()),W=(0,Z.useMemo)(()=>(0,X.jsx)(Q,{flexGrow:1,borderStyle:{bottom:`─`},borderBottom:!0,borderTop:!1,borderLeft:!1,borderRight:!1,borderDimColor:!0}),[]);return(0,X.jsxs)(X.Fragment,{children:[h,(0,X.jsx)(Z.Activity,{mode:h?`hidden`:`visible`,children:(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(k6,{}),(0,X.jsxs)(Q,{flexDirection:`row`,alignItems:`flex-end`,children:[ye&&(0,X.jsxs)($,{color:`brightmagenta`,bold:!0,children:[`EXPANDED`,` `]}),W,je===!1&&(0,X.jsx)($,{dimColor:!0,children:` Not logged in`}),je===!1&&ze&&(0,X.jsx)($,{dimColor:!0,children:` •`}),ze&&(0,X.jsxs)($,{children:[` `,pe.find(e=>e.llmName===ze)?.name||ze]}),(je===!1||ze)&&(0,X.jsx)($,{dimColor:!0,children:` •`}),(0,X.jsxs)($,{color:`brightyellow`,children:[` `,Ye]})]}),(0,X.jsxs)(Q,{flexDirection:`row`,gap:1,children:[(0,X.jsx)($,{color:U,dimColor:Fe,children:Ge}),(0,X.jsx)(t6,{ref:o,onChange:He,onKeyDown:H,onSubmit:Ue,placeholder:Ke,grammar:qe,disabled:Je,ghostText:m??void 0})]}),(0,X.jsx)(Q,{flexDirection:`row`,children:W}),(0,X.jsxs)(Q,{justifyContent:`space-between`,children:[(0,X.jsx)(A6,{mode:i,prompt:n,handler:we,onExitFilesMode:()=>a(B0.Prompt),onSubmitPrompt:Ue,hints:e,availableHeight:be,onLoadingChange:Pe,commandContext:Le}),(0,X.jsxs)(Q,{flexDirection:`row`,gap:1,children:[D&&k!==void 0&&A!==void 0?(0,X.jsxs)($,{dimColor:!0,children:[(0,X.jsxs)($,{color:`cyan`,children:[A-k+1,` lines selected`]}),` `,`in `,(0,X.jsx)($,{color:`cyan`,children:O.basename(D)})]}):D&&(0,X.jsxs)($,{dimColor:!0,children:[`in `,(0,X.jsx)($,{color:`cyan`,children:O.basename(D)})]}),e?.escClear&&(0,X.jsx)($,{wrap:`truncate-middle`,dimColor:!0,children:`Press ESC again to clear input`}),e?.escClear&&g&&(0,X.jsx)($,{dimColor:!0,children:`·`}),g&&(0,X.jsxs)($,{wrap:`truncate-middle`,dimColor:!0,children:[`Update available (${g.latestVersion})`,!g.isEphemeral&&(g.installationType===`native`&&_?` · Restart to auto-update`:` · Run: ${RZ(g)}`)]})]})]})]})})]})});X6.displayName=`ComposerInner`;const Z6=(0,Z.memo)(({hints:e,composerRef:t})=>(0,X.jsx)(E6,{children:(0,X.jsx)(X6,{hints:e,composerRef:t})}));Z6.displayName=`Composer`;var Q6=class extends Z.Component{state={hasError:!1,error:null,errorInfo:null};static getDerivedStateFromError(e){return{hasError:!0,error:e,errorInfo:null}}componentDidCatch(e,t){Dl(e,{componentStack:t.componentStack??void 0}),this.setState({error:e,errorInfo:t}),this.props.onError&&this.props.onError(e,t)}render(){let{hasError:e,error:t,errorInfo:n}=this.state,{fallback:r,children:i}=this.props;return e?r?typeof r==`function`?r(t,n):r:(0,X.jsxs)(Q,{flexDirection:`column`,padding:1,children:[(0,X.jsx)($,{color:`red`,bold:!0,children:`Something went wrong.`}),t&&(0,X.jsxs)(Q,{marginTop:1,flexDirection:`column`,children:[(0,X.jsx)($,{color:`yellow`,children:t.toString()}),n?.componentStack&&(0,X.jsx)($,{color:`brightblack`,children:n.componentStack})]})]}):i}};const $6=(0,Z.memo)(({duration:e,credits:t,conversationId:n})=>(0,X.jsxs)(Q,{flexDirection:`column`,paddingY:1,children:[(0,X.jsx)($,{color:QQ,children:`
75334
+ `)}return F6(L6(e))}var kWe=W((()=>{}));const R6=1e3;function AWe(){let[e,t]=(0,Z.useState)({submittedCommand:null,runId:0,output:``,isRunning:!1}),[n,r]=(0,Z.useState)([]),[i,a]=(0,Z.useState)([]),[o,s]=(0,Z.useState)(-1),c=(0,Z.useRef)(!1);(0,Z.useEffect)(()=>{c.current||(c.current=!0,Promise.resolve().then(()=>(kWe(),EWe)).then(e=>{let t=e.shellHistory??e.default;a((typeof t==`function`?t():[]).slice(-R6))}).catch(()=>{}))},[]);let l=(0,Z.useCallback)(e=>{let n=e.trim();n&&(a(e=>e.length>0&&e[e.length-1]===n?e:[...e,n].slice(-R6)),s(-1),t(e=>({submittedCommand:n,runId:e.runId+1,output:``,isRunning:!0})))},[]),u=(0,Z.useCallback)(e=>{t(t=>(t.submittedCommand&&r(n=>[...n,{command:t.submittedCommand,output:e}].slice(-1e3)),{submittedCommand:null,runId:t.runId,output:``,isRunning:!1}))},[]);return{submitCommand:l,renderer:(0,Z.useCallback)(r=>(0,X.jsx)(wWe,{state:e,setState:t,onCommandComplete:u,commandHistory:n,currentPrompt:r.prompt,availableHeight:r.availableHeight}),[e,u,n]),navigateHistory:(0,Z.useCallback)(e=>{if(i.length===0)return null;let t=o;return e===`up`?t=o===-1?i.length-1:Math.max(0,o-1):(t=o===-1?-1:o+1,t>=i.length&&(t=-1)),s(t),t===-1?``:i[t]},[i,o]),getActivity:()=>e.isRunning?`pending`:`idle`}}const jWe=[`no pull requests found`,`no open pull requests`];function MWe(){return new Promise((e,t)=>{se(`gh`,[`pr`,`view`,`--json`,`number,url,reviewDecision,isDraft,state`],{timeout:1e4},(n,r,i)=>{if(n){let r=(i||n.message).toLowerCase();jWe.some(e=>r.includes(e))?e(null):t(n);return}try{let t=JSON.parse(r.trim());if(typeof t.number==`number`&&typeof t.url==`string`&&t.number>0){let n=`pending`;t.state===`MERGED`?n=`merged`:t.state===`CLOSED`?n=`closed`:t.isDraft?n=`draft`:t.reviewDecision===`APPROVED`?n=`approved`:t.reviewDecision===`CHANGES_REQUESTED`&&(n=`changes_requested`),e({number:t.number,url:t.url,reviewState:n});return}}catch{t(Error(`Malformed JSON from gh pr view`))}e(null)})})}const z6=6e4;function NWe(){let{data:e}=qQ({queryKey:[S3.PrInfo],queryFn:MWe,staleTime:z6,refetchInterval:z6,retry:!1,refetchOnMount:!0,refetchOnWindowFocus:!1});return e??null}function B6({href:e,children:t,color:n}){let r=mZ(e),i=hZ();return(0,X.jsx)($,{color:n??WNe,underline:!0,transform:e=>`${r}${e}${i}`,children:t})}B6.displayName=`Link`;const PWe={approved:`green`,pending:`yellow`,changes_requested:`red`,draft:`brightblack`,merged:`magenta`,closed:`brightblack`},V6=(0,Z.memo)(({hints:e,availableHeight:t})=>{let{agentMode:n,isWaitingForYoloConfirm:r}=H0(),i=NWe();if(t!==void 0&&t<1)return null;let a;if(e?.exitKey)a=(0,X.jsxs)($,{dimColor:!0,children:[`Press `,e.exitKey===`c`?`Ctrl+C`:`Ctrl+D`,` again to exit`]});else if(r)a=(0,X.jsxs)($,{dimColor:!0,children:[`Press `,(0,X.jsx)($,{color:`brightred`,children:`shift+tab`}),` again to enable YOLO mode (dangerous)`]});else switch(n){case xd.Normal:a=(0,X.jsx)($,{dimColor:!0,children:`? for shortcuts • shift+tab to cycle modes`});break;case xd.AcceptEdits:a=(0,X.jsxs)($,{dimColor:!0,children:[(0,X.jsx)($,{color:`brightcyan`,children:`⏵⏵`}),` accept edits on (shift+tab to cycle)`]});break;case xd.PlanMode:a=(0,X.jsxs)($,{dimColor:!0,children:[(0,X.jsx)($,{color:`brightcyan`,children:`⏸`}),` plan mode on (shift+tab to cycle)`]});break;case xd.Yolo:a=(0,X.jsxs)($,{dimColor:!0,children:[(0,X.jsx)($,{color:`brightred`,children:`⚠`}),` YOLO mode - all tools auto-accepted (shift+tab to cycle)`]});break;default:a=(0,X.jsx)($,{dimColor:!0,children:`? for shortcuts`})}return i?(0,X.jsxs)(Q,{flexDirection:`row`,gap:1,children:[(0,X.jsxs)(B6,{href:i.url,color:PWe[i.reviewState],children:[`PR #`,i.number]}),(0,X.jsx)($,{dimColor:!0,children:`•`}),a]}):a});V6.displayName=`AgentModeIndicator`;const H6=15e3,FWe=/^(node_modules|\.git|dist|build|out|coverage|\.vscode|\.idea|\.DS_Store)$/;let U6=null;function W6(e,t){let n=e.replace(/\\/g,`/`);return{path:n,name:O.posix.basename(n),isDirectory:t}}function IWe(e){return e.name.startsWith(`.`)||e.path.split(`/`).some(e=>e.startsWith(`.`)&&e!==`.`)}async function LWe(e){try{let t=await RWe(`git`,[`rev-parse`,`--show-toplevel`],e);if(!t)return null;let[n,r]=await Promise.all([G6(`git`,[`ls-files`],t),G6(`git`,[`ls-files`,`--others`,`--exclude-standard`],t)]),i=[],a=new Set;for(let e of[...n,...r]){if(!e)continue;let n=O.resolve(t,e);i.push(W6(n,!1));let r=O.posix.dirname(e);for(;r&&r!==`.`;){let e=O.resolve(t,r);if(a.has(e))break;a.add(e),i.push(W6(e,!0)),r=O.posix.dirname(r)}}return i}catch{return null}}function RWe(e,t,n){return new Promise((r,i)=>{let a=ue(e,t,{cwd:n,stdio:[`ignore`,`pipe`,`pipe`]}),o=``;a.stdout.on(`data`,e=>o+=e.toString()),a.on(`close`,e=>e===0?r(o.trim()):i()),a.on(`error`,i)})}function G6(e,t,n){return new Promise(r=>{let i=[],a=ue(e,t,{cwd:n,stdio:[`ignore`,`pipe`,`pipe`]});pe({input:a.stdout}).on(`line`,e=>i.push(e.trim())),a.on(`close`,()=>r(i)),a.on(`error`,()=>r(i))})}async function zWe(e,t){let n=[`--files`,`--no-messages`,`--max-depth`,`100`];t.includeHidden&&n.push(`--hidden`),t.useGitignore||n.push(`--no-ignore`);for(let e of t.globs)n.push(`-g`,e);for(let e of t.ignoreGlobs)n.push(`-g`,e);return new Promise(t=>{let r=[],i=ue(Ve,n,{cwd:e,stdio:[`ignore`,`pipe`,`pipe`]});pe({input:i.stdout}).on(`line`,t=>{let n=fBe(t.trim());n&&r.push(W6(O.resolve(e,n),!1))}),i.on(`close`,()=>t(r)),i.on(`error`,()=>t(r))})}async function K6(e,t){let n=[],r=async(e,i)=>{if(!(i>12||n.length>=H6))try{let a=await m.readdir(e,{withFileTypes:!0}),o=[];for(let r of a){if(!t&&r.name.startsWith(`.`))continue;let i=O.join(e,r.name);r.isDirectory()?FWe.test(r.name)||(n.push(W6(i,!0)),o.push(i)):r.isFile()&&n.push(W6(i,!1))}await Promise.all(o.map(e=>r(e,i+1)))}catch{}};return await r(e,0),n}function BWe(e){let t=e.includeHidden??!1,n=e.globs??[],r=e.ignoreGlobs??[],i=e.useRipgrep??!0,a=e.useGitignore??!0,o=e.root,s=new Set,c=[],l=e=>{c.length>=H6||s.has(e.path)||(s.add(e.path),!(!t&&IWe(e))&&c.push(e))},u=i&&a&&n.length===0&&r.length===0;return{docs:c,ready:(async()=>{if(u){let e=await LWe(o);if(e){for(let t of e)l(t);return}}if(i){let e=await zWe(o,{includeHidden:t,globs:n,ignoreGlobs:r,useGitignore:a});for(let t of e)l(t);let i=await K6(o,t);for(let e of i)e.isDirectory&&l(e)}else{let e=await K6(o,t);for(let t of e)l(t)}})()}}function VWe(e){let t=O.resolve(e.root);if(U6&&U6.key===t&&Date.now()-U6.at<6e4)return U6.index;let n=BWe(e);return U6={key:t,index:n,at:Date.now()},n}async function HWe(e,t,n){let r=new Map;for(let n=0;n<e.length;n+=64){let i=e.slice(n,n+64);await Promise.all(i.map(async e=>{try{let n=O.isAbsolute(e.path)?e.path:O.resolve(t,e.path),i=await m.stat(n);r.set(e.path,i.mtimeMs)}catch{r.set(e.path,0)}}))}let i=[...e].sort((e,t)=>{let n=(r.get(t.path)??0)-(r.get(e.path)??0);return n===0?e.path.split(`/`).length-t.path.split(`/`).length||e.name.localeCompare(t.name):n}).slice(0,n);return{paths:i.map(e=>e.path),isDirectory:i.map(e=>e.isDirectory)}}async function UWe(e,t){let n=t.root,r=t.maxResults??100;if(!(await m.stat(n).catch(()=>null))?.isDirectory())return{paths:[],isDirectory:[]};let i=VWe(t);await i.ready;let a=e.trim();if(!a)return HWe(i.docs,n,r);let o=new _H(i.docs,{selector:e=>e.path,limit:r}).find(a);return{paths:o.map(e=>e.item.path),isDirectory:o.map(e=>e.item.isDirectory)}}function WWe(e){let[t,n]=(0,Z.useState)([]),[r,i]=(0,Z.useState)([]),a=(0,Z.useRef)(null),o=(0,Z.useRef)(null),s=(0,Z.useRef)(null);return(0,Z.useEffect)(()=>(o.current&&clearTimeout(o.current),a.current&&a.current.abort(),o.current=setTimeout(()=>{if(e===s.current)return;s.current=e;let t=new AbortController;a.current=t,(async()=>{try{let r=await UWe(e,{root:process.cwd()});if(t.signal.aborted)return;n(r.paths.map(mBe)),i(r.isDirectory)}catch{}})()},100),()=>{o.current&&clearTimeout(o.current),a.current&&a.current.abort()}),[e]),{results:t,isDirectory:r}}const q6=(0,Z.memo)(({onAccept:e,onCancel:t,availableHeight:n})=>{let{prompt:r,bufferRef:i}=T6(),[a,o]=(0,Z.useState)(``);(0,Z.useEffect)(()=>{let e=i.current;if(!e){o(``);return}let t=O6(e.text,e.cursor)?.query??``;o(e=>e===t?e:t)},[i,r]);let s=(0,Z.useDeferredValue)(a),{results:c,isDirectory:l}=WWe(s),u=a!==s,d=c.map((e,t)=>l[t]?`${e}/`:e),f=(0,Z.useCallback)((t,n)=>{let r=i.current;if(!r)return e();let a=O6(r.text,r.cursor);if(a){let e=c[n];r.replaceRange(a.startRow,a.startCol,a.endRow,a.endCol,`@${e}${l[n]?`/`:``} `)}e()},[i,e,c,l]);return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(j6,{items:d,limit:Math.max(1,Math.min(10,n-2)),maxHeight:n,isActive:!0,showIndex:!0,showIndicators:!0,onSubmit:f,onTab:f,onCancel:t}),u&&(0,X.jsx)(Q,{marginTop:0,children:(0,X.jsx)($,{dimColor:!0,children:`Searching...`})})]})});q6.displayName=`FileMentionPicker`;const J6=[[`! for terminal/bash mode`,`/ for commands`,`@ for file paths`],[`esc esc to clear input`,`shift + tab to cycle agent modes`,`${ZUe().toLowerCase()} for newline`],[`ctrl + z to undo`,`ctrl + v to paste images`]],Y6=(0,Z.memo)(({availableHeight:e})=>e!==void 0&&e<3?null:(0,X.jsx)(Q,{flexDirection:`row`,columnGap:5,rowGap:1,flexWrap:`wrap`,children:(e!==void 0&&e<6?J6.slice(0,1):e!==void 0&&e<9?J6.slice(0,2):J6).map((e,t)=>(0,X.jsx)(Q,{flexDirection:`column`,children:e.map(e=>(0,X.jsx)($,{dimColor:!0,children:e},e))},t))}));Y6.displayName=`Help`;function GWe(){return{mode:B0.Prompt,render:({prompt:e,hints:t,availableHeight:n})=>(0,X.jsx)(V6,{hints:t,availableHeight:n})}}function KWe(){return{mode:B0.Help,render:({availableHeight:e})=>(0,X.jsx)(Y6,{availableHeight:e})}}function qWe(e){return{mode:B0.Files,render:({prompt:t,availableHeight:n})=>(0,X.jsx)(q6,{onAccept:e,onCancel:e,availableHeight:n}),shouldPreventDefault:(e,t)=>t.upArrow||t.downArrow||t.escape||t.return||t.tab}}function JWe(e,t){let n=AWe(),r=yWe(t);return{handlers:(0,Z.useMemo)(()=>{let t={mode:B0.Bash,render:n.renderer,onSubmit:n.submitCommand},i={mode:B0.Command,render:r.renderer,onSubmit:r.executeCommand,shouldPreventDefault:r.shouldPreventDefault};return new Map([[B0.Prompt,GWe()],[B0.Help,KWe()],[B0.Bash,t],[B0.Command,i],[B0.Files,qWe(e)]])},[n,r,e]),getActivity:n.getActivity,bashNavigateHistory:n.navigateHistory}}const YWe={[B0.Prompt]:{color:void 0,placeholder:`Try "Build a ecommerce website..."`,prefix:`❯`},[B0.Help]:{color:void 0,placeholder:`Try "Build a ecommerce website..."`,prefix:`❯`},[B0.Bash]:{color:`brightgreen`,placeholder:vUe()?`Try "dir"`:`Try "ls -la"`,prefix:`!`},[B0.Command]:{color:`brightmagenta`,placeholder:`Try "/resume <chat title>"`,prefix:`❯`},[B0.Files]:{color:`brightcyan`,placeholder:`Try "@help.md"`,prefix:`@`}},XWe={"!":{mode:B0.Bash,preventDefault:!0,atStartOnly:!0},"?":{mode:B0.Help,preventDefault:!0,atStartOnly:!0},"@":{mode:B0.Files,preventDefault:!1,atStartOnly:!1}},X6=(0,Z.memo)(({hints:e,composerRef:t})=>{let{prompt:n,setPrompt:r,mode:i,setMode:a,bufferRef:o,activity:s,setActivity:c,queuedMessages:l,nq:u,clearQueue:d,addAttachment:f,clearAttachments:p,ghostText:m,commandOverlay:h}=T6(),g=(0,Z.useCallback)(()=>{let e=l.filter(e=>!e.hidden);if(e.length===0)return;let t=e.map(e=>e.message).join(`
75335
+ `);o.current?.setText(t),d()},[l,o,d]),{updateInfo:_,autoUpdate:v}=mUe(),y=(0,Z.useCallback)(e=>o.current?.getExpandedText(e)??e,[o]),b=(0,Z.useCallback)(()=>{},[]),x=(0,Z.useRef)({text:``,timer:null}),S=(0,Z.useRef)(null);S.current||(S.current=new yq(`cli-repl`),S.current.load());let C=S.current,w=(0,Z.useRef)(``),T=(0,Z.useRef)(0),E=(0,Z.useRef)(null),D=(0,Z.useCallback)(e=>{if(!new Set([B0.Prompt,B0.Help]).has(i))return!1;let t=e.trim();if(!t.startsWith(`/`))return!0;let n=t.slice(1).split(/\s/)[0]||``;return!(n===``||!/[/\\.]/.test(n)&&/^[a-zA-Z]/.test(n))},[i]);(0,Z.useImperativeHandle)(t,()=>({hasText:()=>n.length>0,hasQueue:()=>l.some(e=>!e.hidden),saveAndClear:()=>{let e=n.trimStart();e&&D(e)&&(C.append(e),C.resetNavigation()),o.current?.setText(``),b(),p()},clear:()=>{o.current?.setText(``),b(),p()},clearQueue:()=>d(),dequeueAllToComposer:()=>g()}));let{currentFile:k,selectionStartLine:A,selectionEndLine:j}=t3(),{sendMessage:M,segments:N,clearSegments:P,clearSegmentsOnly:ee,clearTempSegments:F,stop:te,addNotification:I,mcp:L,isDirectoryAllowed:R,addAllowedDirectory:z,refreshMcpTools:ne,loadConversation:re,agentStatus:ie,segmentsLength:ae,conversationId:oe,dequeuedOnStop:se,clearDequeuedOnStop:ce,listTerminalSessions:le,getTerminalSessionOutput:ue,stopTerminalSession:de,totalCredits:fe}=d3(),{apiClient:B,authManager:pe}=o3(),{data:me=[],refetch:he}=_Ue(B),ge=WQ(),{cycleAgentMode:_e,resetToNormal:ve,isWaitingForYoloConfirm:ye}=H0(),be=(0,Z.useContext)(G0),V=gUe(),{requestFullRedraw:xe}=zMe(),{handlers:Se,getActivity:Ce,bashNavigateHistory:we}=JWe(()=>a(B0.Prompt),(0,Z.useCallback)(()=>{o.current?.setText(``)},[o])),Ee=Se.get(i)||null,[De,Oe]=(0,Z.useState)([]),ke=(0,Z.useRef)([]),[Ae,je]=(0,Z.useState)(``),[Me,Ne]=(0,Z.useState)(null),[Pe,Fe]=(0,Z.useState)(!1),[Ie,Le]=(0,Z.useState)(!1),Re=(0,Z.useMemo)(()=>({agentStatus:ie,segmentsLength:ae,isLoggedIn:Me??!1}),[ie,ae,Me]),ze=(0,Z.useCallback)(async()=>{try{let e=await B.getConversationsList(hn.agentType,process.cwd());if(e?.result){let t=e.result.slice(0,25);Oe(t),ke.current=t}}catch{}},[B]);(0,Z.useEffect)(()=>{ze()},[ze]),(0,Z.useEffect)(()=>{B.getUserInfo().then(e=>Ne(!!e?.result?.email)).catch(()=>{Ne(pe.isAuthenticated())})},[B,pe]),(0,Z.useEffect)(()=>{se&&(o.current?.setText(se),ce())},[se,ce,o]);let Be=Ae||me[0]?.llmName||``;(0,Z.useEffect)(()=>{if(!Pe){Le(!1);return}let e=setInterval(()=>Le(e=>!e),500);return()=>clearInterval(e)},[Pe]),(0,Z.useEffect)(()=>{gWe({onExit:()=>{QZ(0)},onNewChat:()=>{P(),d(),o.current?.setText(``),xe()},onClearChat:()=>{ee(),o.current?.setText(``),xe()},onStop:()=>{te()},onModelChange:e=>{let t=me.find(t=>t.llmName===e);t?(je(t.llmName),o.current?.setText(``)):I(`Model not found`,`error`)},onResumeChat:async e=>{let t=ke.current.find(t=>t.deploymentConversationId===e);if(t||=ke.current.find(t=>(t.name||t.deploymentConversationId||`Untitled`).toLowerCase().includes(e.toLowerCase())),t||(await ze(),t=ke.current.find(t=>t.deploymentConversationId===e),t||=ke.current.find(t=>(t.name||t.deploymentConversationId||`Untitled`).toLowerCase().includes(e.toLowerCase()))),!t)try{let n=(await B.searchConversations(e,hn.agentType))?.result??[];if(n.length>0&&(t=n.find(t=>t.deploymentConversationId===e),!t)){let r=e.toLowerCase();t=n.find(e=>(e.name||e.deploymentConversationId||`Untitled`).toLowerCase().includes(r))}}catch{}if(t?.deploymentConversationId)try{d(),o.current?.setText(``),await re(t.deploymentConversationId),I(`Resumed conversation: ${t.name||t.deploymentConversationId}`,`info`)}catch(e){I(`Failed to load conversation: ${e instanceof Error?e.message:`Unknown error`}`,`error`)}else I(`Conversation "${e}" not found`,`error`)},onLogin:async e=>{try{if(pe.isEnvAuth()){I(`You are authenticated via an environment variable. Unset it to use /login or /logout.`,`error`);return}if(!e){I(`Usage: /login <email> or /login <api_key>`,`error`);return}if(/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)){let t=e,n=await FJ(),r=await B.authenticateDeviceForCodeLlm(t,n);if(!r?.success||!r?.result){I(r?.error??`Failed to start device code login`,`error`);return}let{verificationUri:i,userCode:a,pollingInterval:o}=r.result;I(`Open the URL and enter the code to authenticate.\n\nURL: ${i}\nCode: ${a}\n\nPolling for completion...`,`info`),(async()=>{let e=(o||5)*1e3,t=Date.now()+600*1e3;for(;Date.now()<t;){await yUe(e);try{let e=await B.pollDeviceCode(a);if(e?.success&&e.result?.deviceCode){let t=e.result.deviceCode,n=e.result.chatWebUrl;if(await pe.loginWithDeviceCode(t),n){let e=n.replace(/^https?:\/\//,``);B.setChatWebDomain(e)}I(`Authentication successful!`,`info`),Ne(!0),await ze(),await he();return}}catch{}}I(`Authentication timed out. Please try again.`,`error`)})()}else{await pe.loginWithApiKey(e);try{(await B.getUserInfo())?.result?.email?(I(`API key login successful!`,`info`),Ne(!0),await ze(),await he()):(await pe.logout(),I(`Invalid API key — authentication failed`,`error`))}catch(e){await pe.logout(),I(`API key authentication failed: ${e instanceof Error?e.message:`Unknown error`}`,`error`)}}o.current?.setText(``)}catch(e){I(`Login failed: ${e instanceof Error?e.message:`Unknown error`}`,`error`)}},onLogout:async()=>{if(pe.isEnvAuth()){I(`You are authenticated via an environment variable. Unset it to use /login or /logout.`,`error`);return}await pe.logout(),Ne(!1)},getUserInfo:async()=>{try{let e=await B.getUserInfo();if(e?.success&&e.result){let{name:t,email:n,organization:r}=e.result,i=r?.name||`No team`,a=pe.getAuthKind(),o=a.type===`env_api_key`?`API key (env)`:a.type===`env_device_code`?`Device code (env)`:a.type===`api_key`?`API key`:a.type===`device_code`?`Device code`:a.type===`oauth_token`?`OAuth token`:`Unknown`;I(`User Status:\n\nName: ${t||`N/A`}\nEmail: ${n||`N/A`}\nTeam: ${i}\nAuth Method: ${o}`,`info`)}else I(`Failed to get user info`,`error`)}catch{I(`Failed to get user info`,`error`)}},getModels:async()=>me.filter(e=>e.codeAgentSupported).map(e=>({label:e.name||e.llmName,value:e.llmName,model:e})),getChatTitles:async()=>(await ze(),ke.current.map(e=>({id:e.deploymentConversationId||``,title:e.name||e.deploymentConversationId||`Untitled`,messageCount:e.hasHistory,date:e.createdAt}))),searchChatTitles:async e=>{try{let t=await B.searchConversations(e,hn.agentType);if(t?.result)return t.result.map(e=>({id:e.deploymentConversationId||``,title:e.name||e.deploymentConversationId||`Untitled`,messageCount:e.hasHistory,date:e.createdAt}))}catch{}return[]},addNotification:I,mcp:L,isDirectoryAllowed:R,addAllowedDirectory:z,refreshMcpTools:ne,getAgentStatus:()=>ie,getTotalCredits:fe>0?()=>Promise.resolve(fe):void 0,loginAuth:{initiateDeviceCode:async e=>{let t=await FJ(),n=await B.authenticateDeviceForCodeLlm(e,t);return!n?.success||!n?.result?{success:!1,error:n?.error??`Failed to start device code login`}:{success:!0,verificationUri:n.result.verificationUri,userCode:n.result.userCode,pollingInterval:n.result.pollingInterval}},pollDeviceCode:async e=>{let t=await B.pollDeviceCode(e);return t?.success&&t.result?.deviceCode?{success:!0,deviceCode:t.result.deviceCode,chatWebUrl:t.result.chatWebUrl}:{success:!1}},completeDeviceCodeLogin:async(e,t)=>{if(await pe.loginWithDeviceCode(e),t){let e=t.replace(/^https?:\/\//,``);B.setChatWebDomain(e)}Ne(!0),await ze(),await he()},loginWithApiKey:async e=>{if(await pe.loginWithApiKey(e),!(await B.getUserInfo())?.result?.email)throw await pe.logout(),Error(`Invalid API key — authentication failed`);Ne(!0),await ze(),await he()},isEnvAuth:()=>pe.isEnvAuth()},checkEnvAuth:()=>({isEnvAuth:pe.isEnvAuth(),shouldHide:pe.isEnvAuth()}),getUpdateInfo:()=>_,listTerminalSessions:le,getTerminalSessionOutput:ue,stopTerminalSession:de,getLastAssistantMessage:()=>{for(let e=N.length-1;e>=0;e--){let t=N[e];if(t.source===`bot`&&t.type===`text`&&t.status===`completed`){let e=C3(t.segment);if(e?.trim())return e}}return null},getCwd:()=>process.cwd(),getSegmentsForExport:()=>N,getOrganizations:async()=>{try{let e=await B.listOrganizations();return!e?.success||!e.result?[]:e.result.map(e=>({id:e.organizationId,name:e.name,workspace:e.workspace}))}catch{return[]}},onOrgSwitch:async e=>{try{let t=await B.switchOrganization(e);return t&&(await ze(),await he(),ge.invalidateQueries({queryKey:[S3.UserInfo]})),t}catch{return!1}}})},[me,N,P,ee,xe,d,o,B,he,te,I,L,R,z,ne,re,De,ze,ie,oe,pe,_,le,ue,de,fe,ge]);let Ve=(0,Z.useCallback)(async e=>{try{let t=await Te.stat(e),n=await Te.readFile(e),r=O.extname(e).toLowerCase(),i={".png":`image/png`,".jpg":`image/jpeg`,".jpeg":`image/jpeg`,".webp":`image/webp`,".gif":`image/gif`,".heic":`image/heic`,".heif":`image/heif`}[r]??`image/png`;f({doc_id:`tui-`+Math.random().toString(36).slice(2,11)+`-`+Date.now().toString(36),filename:e,filePath:O.resolve(e),fileName:O.basename(e),content:n.toString(`base64`),mimeType:i,mime_type:i,size:t.size,metadata:{uploadedAt:new Date().toISOString(),source:`tui-clipboard`,isImage:!0,encoding:`base64`}})}catch{}},[f]),H=(0,Z.useCallback)(async()=>{if(await g2()){let e=await _2();if(e){let t=y2(b2(e));o.current?.insert(`@${t} `),await Ve(e);return}}let e=await cVe();if(!e)return;let t=x2(e.trim());if(t){o.current?.insert(t.mentionText);for(let e of t.persistedImagePaths)Ve(e);return}f2(e.trim())||o.current?.insert(e,{isPaste:!0})},[o,Ve]),He=(0,Z.useCallback)(e=>{let t=e.target.cursor[0]===0&&e.target.cursor[1]===0;if(!e.key.paste){let t=process.platform===`darwin`&&e.key.super&&e.input===`v`,n=process.platform!==`darwin`&&e.key.ctrl&&e.input===`v`||process.platform===`linux`&&e.key.ctrl&&e.key.shift&&e.input===`V`;if(t||n){H(),e.preventDefault();return}}if(e.key.paste){let t=e.input.replace(/[\r\n]+$/,``),n=x2(t.trim());if(n){o.current?.insert(n.mentionText);for(let e of n.persistedImagePaths)Ve(e);e.preventDefault();return}if(f2(t.trim())){e.preventDefault();return}(async()=>{if(await g2()){let e=await _2();if(e){let t=y2(b2(e));o.current?.insert(`@${t} `),await Ve(e);return}}o.current?.insert(t,{isPaste:!0})})(),e.preventDefault();return}if(e.input.length>3&&!e.key.ctrl&&!e.key.meta&&!e.key.paste){x.current.text+=e.input,x.current.timer&&clearTimeout(x.current.timer),x.current.timer=setTimeout(()=>{let e=x.current.text;x.current={text:``,timer:null};let t=x2(e.trim());if(t){o.current?.insert(t.mentionText);for(let e of t.persistedImagePaths)Ve(e);return}f2(e.trim())||o.current?.insert(e,{isPaste:!0})},50),e.preventDefault();return}if(i===B0.Prompt&&e.key.upArrow&&e.target.visualCursor[0]===0&&l.some(e=>!e.hidden)&&n.trim()===``){g(),e.preventDefault();return}if(Ee?.shouldPreventDefault&&Ee.shouldPreventDefault(e.input||``,e.key)){e.preventDefault();return}if((i===B0.Prompt||i===B0.Help||i===B0.Files)&&(e.key.upArrow||e.key.downArrow)){let t=e.target,r=t.visualCursor[0]===0,i=t.visualCursor[0]>=t.allVisualLines.length-1;if(e.key.upArrow&&r){if(C.getEntries().length>0){C.isNavigating()||(w.current=n);let t=C.navigateUp();if(t){o.current?.setText(t.message),e.preventDefault();return}}}else if(e.key.downArrow&&i){if(!C.isNavigating()){e.preventDefault();return}let t=C.navigateDown();t?o.current?.setText(t.message):o.current?.setText(w.current),e.preventDefault();return}}if(i===B0.Bash&&we){let t=e.target,n=e.key.upArrow&&t.visualCursor[0]===0,r=e.key.downArrow&&t.visualCursor[0]>=t.allVisualLines.length-1;if(n||r){let t=we(e.key.upArrow?`up`:`down`);if(t!==null){o.current?.setText(t),e.preventDefault();return}}}if(t&&e.key.backspace){if(ye){ve(),e.preventDefault();return}i!==B0.Prompt&&(a(B0.Prompt),C.resetNavigation(),w.current=``,e.preventDefault());return}if(i===B0.Prompt&&e.key.shift&&e.key.tab){_e(),e.preventDefault();return}let r=XWe[e.input];if(r&&(!r.atStartOnly||t)){i!==r.mode&&a(r.mode),r.preventDefault&&r.mode!==B0.Command&&e.preventDefault();return}},[i,a,Ee,we,o,H,Ve,l,n,d,g,ye,ve,_e,C]);(0,Z.useEffect)(()=>{if(i===B0.Prompt)return;let e=n.trim();if(i===B0.Files){let e=o.current;e&&(O6(e.text,e.cursor)||a(B0.Prompt))}else if(i===B0.Command)if(e.length===0)a(B0.Prompt);else{let t=e.startsWith(`/`),n=e.slice(1).split(/\s/)[0]||``;t&&(n===``||!/[/\\.]/.test(n)&&/^[a-zA-Z]/.test(n))||a(B0.Prompt)}},[i,n,o,a]),(0,Z.useEffect)(()=>{if(i!==B0.Help)return;let e=setTimeout(()=>{a(B0.Prompt)},3e4);return()=>clearTimeout(e)},[i,a]);let Ue=(0,Z.useCallback)((e,t)=>{let n=T.current;T.current=e.length,r(e);let o=e.trim(),s=o.startsWith(`/`),c=o.slice(1).split(/\s/)[0]||``,l=s&&(c===``||!/[/\\.]/.test(c)&&/^[a-zA-Z]/.test(c)),u=ie===Sd.Submitted||ie===Sd.Streaming||ie===Sd.ExecutingTool||ie===Sd.WaitingForToolPermission;e.length>0&&!l&&!u&&F();let d=O6(e,t.cursor);if(o.length===0&&n>0&&(i===B0.Command||i===B0.Bash||i===B0.Help)){a(B0.Prompt);return}if(d){i!==B0.Files&&a(B0.Files);return}if(i===B0.Files){d||a(B0.Prompt);return}i===B0.Help&&o.length>0&&a(B0.Prompt),E.current&&=(clearTimeout(E.current),null),!l&&i===B0.Command&&o.length>0?a(B0.Prompt):l&&i!==B0.Command&&(E.current=setTimeout(()=>{E.current=null,a(B0.Command)},80))},[i,r,a,F,ie]),U=(0,Z.useCallback)(async e=>{let t=e.trim(),n=x6.match(t,i);if(n&&await x6.execute(n)){o.current?.setText(``),p();return}if(t.startsWith(`/`)){let e=cq.matchSkill(t);if(e){if(Me===!1){I(`Not logged in. Use /login email@example.com to login.`,`warning`);return}let n=y(t);if(ie===Sd.Submitted||ie===Sd.Streaming||ie===Sd.ExecutingTool||ie===Sd.WaitingForToolPermission){u(n),o.current?.setText(``),b();return}M({message:n,selectedModel:Ae||me[0]?.llmName||void 0,activeSkills:[e.skill.id]}),o.current?.setText(``),b(),p();return}}if(Ee?.onSubmit){Ee.onSubmit(e),i===B0.Bash?(o.current?.setText(``),c(Ce())):i===B0.Command&&a(B0.Prompt),p();return}switch(i){case B0.Prompt:if(Me===!1){let t=e.trimStart();t&&D(t)&&(C.append(t),C.resetNavigation()),I(`Not logged in. Use /login email@example.com to login.`,`warning`);return}if(ie===Sd.Submitted||ie===Sd.Streaming||ie===Sd.ExecutingTool||ie===Sd.WaitingForToolPermission){let t=y(e.trimStart());u(t),D(t)&&(C.append(t),C.resetNavigation()),w.current=``,b(),o.current?.setText(``);return}let t=Ae||me[0]?.llmName||void 0,n=y(e);D(n)&&(C.append(n),C.resetNavigation()),w.current=``,M({message:n,selectedModel:t}),b(),p();return;default:}},[i,Ee,M,Ce,c,Ae,a,o,ie,u,I,p,Me,y,b,C,me]),{color:We,placeholder:Ge,prefix:Ke}=YWe[i],qe=ae>0?``:Ge,Je=(0,Z.useMemo)(()=>_We(),[]),Ye=(i===B0.Bash?Ce():s)===`pending`||ie===Sd.WaitingForToolPermission,W=M0(process.cwd()),G=(0,Z.useMemo)(()=>(0,X.jsx)(Q,{flexGrow:1,borderStyle:{bottom:`─`},borderBottom:!0,borderTop:!1,borderLeft:!1,borderRight:!1,borderDimColor:!0}),[]);return(0,X.jsxs)(X.Fragment,{children:[h,(0,X.jsx)(Z.Activity,{mode:h?`hidden`:`visible`,children:(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(k6,{}),(0,X.jsxs)(Q,{flexDirection:`row`,alignItems:`flex-end`,children:[be&&(0,X.jsxs)($,{color:`brightmagenta`,bold:!0,children:[`EXPANDED`,` `]}),G,Me===!1&&(0,X.jsx)($,{dimColor:!0,children:` Not logged in`}),Me===!1&&Be&&(0,X.jsx)($,{dimColor:!0,children:` •`}),Be&&(0,X.jsxs)($,{children:[` `,me.find(e=>e.llmName===Be)?.name||Be]}),(Me===!1||Be)&&(0,X.jsx)($,{dimColor:!0,children:` •`}),(0,X.jsxs)($,{color:`brightyellow`,children:[` `,W]})]}),(0,X.jsxs)(Q,{flexDirection:`row`,gap:1,children:[(0,X.jsx)($,{color:We,dimColor:Ie,children:Ke}),(0,X.jsx)(t6,{ref:o,onChange:Ue,onKeyDown:He,onSubmit:U,placeholder:qe,grammar:Je,disabled:Ye,ghostText:m??void 0})]}),(0,X.jsx)(Q,{flexDirection:`row`,children:G}),(0,X.jsxs)(Q,{justifyContent:`space-between`,children:[(0,X.jsx)(A6,{mode:i,prompt:n,handler:Ee,onExitFilesMode:()=>a(B0.Prompt),onSubmitPrompt:U,hints:e,availableHeight:V,onLoadingChange:Fe,commandContext:Re}),(0,X.jsxs)(Q,{flexDirection:`row`,gap:1,children:[k&&A!==void 0&&j!==void 0?(0,X.jsxs)($,{dimColor:!0,children:[(0,X.jsxs)($,{color:`cyan`,children:[j-A+1,` lines selected`]}),` `,`in `,(0,X.jsx)($,{color:`cyan`,children:O.basename(k)})]}):k&&(0,X.jsxs)($,{dimColor:!0,children:[`in `,(0,X.jsx)($,{color:`cyan`,children:O.basename(k)})]}),e?.escClear&&(0,X.jsx)($,{wrap:`truncate-middle`,dimColor:!0,children:`Press ESC again to clear input`}),e?.escClear&&_&&(0,X.jsx)($,{dimColor:!0,children:`·`}),_&&(0,X.jsxs)($,{wrap:`truncate-middle`,dimColor:!0,children:[`Update available (${_.latestVersion})`,!_.isEphemeral&&(_.installationType===`native`&&v?` · Restart to auto-update`:` · Run: ${RZ(_)}`)]})]})]})]})})]})});X6.displayName=`ComposerInner`;const Z6=(0,Z.memo)(({hints:e,composerRef:t})=>(0,X.jsx)(E6,{children:(0,X.jsx)(X6,{hints:e,composerRef:t})}));Z6.displayName=`Composer`;var Q6=class extends Z.Component{state={hasError:!1,error:null,errorInfo:null};static getDerivedStateFromError(e){return{hasError:!0,error:e,errorInfo:null}}componentDidCatch(e,t){Dl(e,{componentStack:t.componentStack??void 0}),this.setState({error:e,errorInfo:t}),this.props.onError&&this.props.onError(e,t)}render(){let{hasError:e,error:t,errorInfo:n}=this.state,{fallback:r,children:i}=this.props;return e?r?typeof r==`function`?r(t,n):r:(0,X.jsxs)(Q,{flexDirection:`column`,padding:1,children:[(0,X.jsx)($,{color:`red`,bold:!0,children:`Something went wrong.`}),t&&(0,X.jsxs)(Q,{marginTop:1,flexDirection:`column`,children:[(0,X.jsx)($,{color:`yellow`,children:t.toString()}),n?.componentStack&&(0,X.jsx)($,{color:`brightblack`,children:n.componentStack})]})]}):i}};const $6=(0,Z.memo)(({duration:e,credits:t,conversationId:n})=>(0,X.jsxs)(Q,{flexDirection:`column`,paddingY:1,children:[(0,X.jsx)($,{color:QQ,children:`
75334
75336
  ▞▀▖▌ ▞▀▖▜▘ ▞▀▖▌ ▜▘
75335
75337
  ▙▄▌▛▀▖▝▀▖▞▀▖▌ ▌▞▀▘ ▙▄▌▐ ▌ ▌ ▐
75336
75338
  ▌ ▌▌ ▌▞▀▌▌ ▖▌ ▌▝▀▖▗▖▌ ▌▐ ▌ ▖▌ ▐
@@ -75424,7 +75426,7 @@ $$`:`${e}$$`},JKe=e=>KKe(e)%2==0?e:qKe(e),YKe=(e,t,n)=>{if(e.substring(t+2).incl
75424
75426
  `);if(t===-1)return e;let n=e.substring(t+1),r=e.substring(0,t),i=n.trim();if(ZKe.test(i)&&!n.match(QKe)){let t=r.split(`
75425
75427
  `).at(-1);if(t&&t.trim().length>0)return`${e}\u200B`}if($Ke.test(i)&&!n.match(eqe)){let t=r.split(`
75426
75428
  `).at(-1);if(t&&t.trim().length>0)return`${e}\u200B`}return e},nqe=e=>{let t=e.match(hKe);if(t){let n=t[2];if(!n||H5.test(n))return e;let r=e.lastIndexOf(t[1]);if(B5(e,r)||V5(e,r))return e;if(e.match(W5)?.length%2==1)return`${e}~~`}else{let t=e.match(bKe);if(t){let n=e.lastIndexOf(t[0].slice(0,2));if(B5(e,n)||V5(e,n))return e;if(e.match(W5)?.length%2==1)return`${e}~`}}return e},n7=e=>e!==!1,r7={COMPARISON_OPERATORS:-10,HTML_TAGS:-5,SETEXT_HEADINGS:0,LINKS:10,BOLD_ITALIC:20,BOLD:30,ITALIC_DOUBLE_UNDERSCORE:40,ITALIC_SINGLE_ASTERISK:41,ITALIC_SINGLE_UNDERSCORE:42,INLINE_CODE:50,STRIKETHROUGH:60,KATEX:70,DEFAULT:100},rqe=[{handler:{name:`comparisonOperators`,handle:cKe,priority:r7.COMPARISON_OPERATORS},optionKey:`comparisonOperators`},{handler:{name:`htmlTags`,handle:VKe,priority:r7.HTML_TAGS},optionKey:`htmlTags`},{handler:{name:`setextHeadings`,handle:tqe,priority:r7.SETEXT_HEADINGS},optionKey:`setextHeadings`},{handler:{name:`links`,handle:t7,priority:r7.LINKS},optionKey:`links`,earlyReturn:e=>e.endsWith(`](streamdown:incomplete-link)`)},{handler:{name:`boldItalic`,handle:zKe,priority:r7.BOLD_ITALIC},optionKey:`boldItalic`},{handler:{name:`bold`,handle:kKe,priority:r7.BOLD},optionKey:`bold`},{handler:{name:`italicDoubleUnderscore`,handle:jKe,priority:r7.ITALIC_DOUBLE_UNDERSCORE},optionKey:`italic`},{handler:{name:`italicSingleAsterisk`,handle:NKe,priority:r7.ITALIC_SINGLE_ASTERISK},optionKey:`italic`},{handler:{name:`italicSingleUnderscore`,handle:IKe,priority:r7.ITALIC_SINGLE_UNDERSCORE},optionKey:`italic`},{handler:{name:`inlineCode`,handle:WKe,priority:r7.INLINE_CODE},optionKey:`inlineCode`},{handler:{name:`strikethrough`,handle:nqe,priority:r7.STRIKETHROUGH},optionKey:`strikethrough`},{handler:{name:`katex`,handle:JKe,priority:r7.KATEX},optionKey:`katex`}],iqe=e=>{let t=e?.linkMode??`protocol`;return rqe.filter(({handler:t,optionKey:n})=>t.name===`links`?n7(e?.links)||n7(e?.images):n7(e?.[n])).map(({handler:e,earlyReturn:n})=>e.name===`links`?{handler:z5(R5({},e),{handle:e=>t7(e,t)}),earlyReturn:t===`protocol`?n:void 0}:{handler:e,earlyReturn:n})},aqe=(e,t)=>{if(!e||typeof e!=`string`)return e;let n=e.endsWith(` `)&&!e.endsWith(` `)?e.slice(0,-1):e,r=iqe(t),i=(t?.handlers??[]).map(e=>({handler:z5(R5({},e),{priority:e.priority??r7.DEFAULT}),earlyReturn:void 0})),a=[...r,...i].sort((e,t)=>(e.handler.priority??0)-(t.handler.priority??0));for(let{handler:e,earlyReturn:t}of a)if(n=e.handle(n),t!=null&&t(n))return n;return n};function oqe(e){if(!e)return!1;let t=e.toLowerCase().trim();return t===`mermaid`||t===`mmd`}function sqe(e){try{return a0(e)}catch{return null}}function i7({children:e,language:t}){let n=(0,Z.useMemo)(()=>S0(),[]);if(oqe(t)){let t=sqe(e||``);if(t!==null)return(0,X.jsx)(Q,{paddingX:1,flexDirection:`row`,alignSelf:`flex-start`,children:(0,X.jsx)($,{children:t})})}let r=e;if(t&&(0,b0.supportsLanguage)(t))try{r=(0,b0.highlight)(e||``,{language:t,theme:n})}catch{}return(0,X.jsx)(Q,{paddingX:1,flexDirection:`row`,alignSelf:`flex-start`,children:(0,X.jsx)($,{children:r})})}i7.displayName=`CodeBlock`;function a7(e){return`text`in e&&typeof e.text==`string`?e.text:`tokens`in e&&Array.isArray(e.tokens)?e.tokens.map(e=>a7(e)).join(``):``}function cqe(e,t){let n=e.length;if(n===0)return e;if(t<=n*5)return e.map(()=>3);let r=t-n*2,i=e.map(e=>Math.max(3,Math.floor(e))),a=i.reduce((e,t)=>e+t,0);for(;a>r;){let e=!1;for(let t=0;t<i.length&&a>r;t++)i[t]>3&&(--i[t],--a,e=!0);if(!e)break}return i}function lqe(e){return`checked`in e&&typeof e.checked==`boolean`}function o7(e,t=!1){return e?e.map((e,n)=>(0,X.jsx)(Z.Fragment,{children:s7(e,t)},n)):null}function s7(e,t=!1){let n=e=>t?(0,X.jsx)($,{dimColor:!0,italic:!0,children:e}):e;switch(e.type){case`strong`:return(0,X.jsx)($,{bold:!0,children:o7(e.tokens,t)});case`em`:return(0,X.jsx)($,{italic:!0,children:o7(e.tokens,t)});case`del`:return(0,X.jsx)($,{strikethrough:!0,children:o7(e.tokens,t)});case`codespan`:return n((0,X.jsx)($,{color:QQ,dimColor:!0,children:e.text}));case`link`:return n((0,X.jsx)(B6,{href:e.href,children:a7(e)}));case`image`:{let t=e,r=t.text||t.href;return n((0,X.jsxs)($,{dimColor:!0,children:[r,` `,t.href!==r&&`(${t.href})`]}))}case`checkbox`:{let t=lqe(e)&&e.checked===!0;return n((0,X.jsx)($,{color:$Q,children:t?`[✓]`:`[ ]`}))}case`text`:return e.tokens?o7(e.tokens,t):n(e.text);case`br`:return`
75427
- `;default:return n(a7(e))}}function c7(e,t=0,n=!1,r){switch(e.type){case`heading`:return(0,X.jsx)(Q,{flexDirection:`column`,children:(0,X.jsx)($,{bold:!0,color:e.depth<=2?QQ:$Q,dimColor:e.depth>2,children:o7(e.tokens,n)})},`heading-${e.depth}`);case`paragraph`:return(0,X.jsx)(Q,{flexDirection:`column`,children:(0,X.jsx)($,{children:o7(e.tokens,n)})},`paragraph`);case`code`:return(0,X.jsx)(i7,{language:e.lang,children:e.text},`code`);case`blockquote`:return(0,X.jsx)(Q,{borderRight:!1,borderTop:!1,borderBottom:!1,borderStyle:`double`,borderColor:r$,paddingLeft:1,flexDirection:`column`,children:e.tokens?.map((e,n)=>(0,X.jsx)(Q,{children:c7(e,t,!0,r)},n))},`blockquote`);case`list`:return(0,X.jsx)(Q,{flexDirection:`column`,children:e.items.map((i,a)=>{let o=e.ordered?(Number(e.start)||1)+a:null,s=i.task===!0,c=i.checked===!0,l=i.tokens?.filter(e=>e.type!==`checkbox`)||[];return(0,X.jsxs)(Q,{flexDirection:`row`,children:[(0,X.jsx)($,{color:$Q,dimColor:!0,children:s?c?`[✓] `:`[ ] `:o===null?`• `:`${o}. `}),(0,X.jsx)(Q,{flexGrow:1,flexDirection:`column`,children:l.map((e,i)=>(0,X.jsx)(Q,{children:c7(e,t+1,n,r)},i))})]},a)})},`list`);case`table`:{let t=e,i=t.header.map((e,n)=>{let r=M3(a7(e));for(let e of t.rows)r=Math.max(r,M3(a7(e[n])));return Math.max(r,3)}),a=i.reduce((e,t)=>e+t+2,0),o=cqe(i,r===void 0?a:Math.max(10,Math.min(r,a)));return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(Q,{flexDirection:`row`,borderTop:!1,borderLeft:!1,borderRight:!1,borderStyle:`single`,borderColor:r$,alignSelf:`flex-start`,children:t.header.map((e,r)=>{let i=t.align?.[r]||null;return(0,X.jsx)(Q,{width:o[r]+2,paddingX:1,justifyContent:i===`center`?`center`:i===`right`?`flex-end`:`flex-start`,children:(0,X.jsx)($,{bold:!0,color:QQ,wrap:`wrap`,children:o7(e.tokens,n)})},r)})}),t.rows.map((e,r)=>(0,X.jsx)(Q,{flexDirection:`row`,children:e.map((e,r)=>{let i=t.align?.[r]||null;return(0,X.jsx)(Q,{width:o[r]+2,paddingX:1,justifyContent:i===`center`?`center`:i===`right`?`flex-end`:`flex-start`,children:(0,X.jsx)($,{wrap:`wrap`,children:o7(e.tokens,n)})},r)})},r))]},`table`)}case`hr`:return(0,X.jsx)(Q,{children:(0,X.jsx)($,{dimColor:!0,children:`─`.repeat(50)})},`hr`);case`space`:return null;default:return(0,X.jsx)(Q,{flexDirection:`column`,children:(0,X.jsx)($,{children:s7(e,n)})})}}function l7({children:e}){let{width:t}=b3(),n=(0,Z.useMemo)(()=>{try{let t=aqe(e);return F5.lexer(t,{gfm:!0,breaks:!0})}catch{return[]}},[e]);return(0,X.jsx)(Q,{flexDirection:`column`,children:(0,Z.useMemo)(()=>{let e=[],r=n.length;return n.forEach((n,i)=>{let a=i===r-1;if(n.type===`space`){e.push((0,X.jsx)(Q,{height:1},`space-${i}`));return}e.push((0,X.jsx)(Q,{flexDirection:`column`,children:c7(n,0,!1,t)},i)),n.type===`heading`&&!a&&e.push((0,X.jsx)(Q,{height:1},`heading-space-${i}`))}),e},[n,t])})}l7.displayName=`Markdown`;const u7=`Pondering...,Thinking...,Processing...,Analyzing...,Exploring...,Crafting...,Building...,Searching...,Connecting...,Reflecting...,Considering...,Examining...,Synthesizing...,Computing...,Reasoning...,Contemplating...,Assembling...,Formulating...,Generating...,Compiling...,Decoding...,Unraveling...,Mapping...,Weaving...,Brewing...,Sculpting...,Distilling...,Parsing...,Digesting...,Conjuring...`.split(`,`);function uqe(e){return e.charAt(0).toUpperCase()+e.slice(1)}function dqe(){return u7[Math.floor(Math.random()*u7.length)]}const fqe=dt([`codellm`,`cli`,`tools`]);function d7(e){let t=g3[e.name];if(t||=(dUe(e.name),g3[e.name]),!t)return(0,X.jsx)(Q,{flexDirection:`column`,children:(0,X.jsxs)($,{color:`red`,children:[`Unknown tool: `,e.name]})});let n;n=e.result?.rejected?(()=>{try{return JSON.parse(e.result.content)}catch{return{}}})().reason===`interrupted`?`interrupted`:`rejected`:e.result?`success`:e.parsedResult?.phase===`error`?`error`:`executing`;let r=e.input??{},i=``;try{i=t.getHeaderParams(r)}catch{}try{return t.renderUI(r,n,e.parsedResult,e.displayData)}catch(n){let r=n instanceof Error?n.message:String(n);return fqe.error`Error rendering tool ${e.name}: ${r}`,(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(T0,{name:t.displayName,params:i,status:`error`}),(0,X.jsx)(E0,{color:`red`,children:`Error rendering tool`})]})}}const f7=(0,Z.memo)(e=>{let{type:t,segment:n,isSpinny:r=!1,source:i}=e;if(t!==`text`)throw Error(`Can only render text segments, got ${t}`);let a=(0,Z.useMemo)(()=>C3(n),[n]);return a?.trim()?i===`user`?(0,X.jsxs)(Q,{flexDirection:`row`,gap:1,children:[(0,X.jsx)($,{color:XQ,children:`❯`}),(0,X.jsx)($,{color:XQ,italic:!0,children:a})]}):r?(0,X.jsx)(Q,{flexDirection:`row`,alignItems:`center`,gap:1,children:(0,X.jsx)(_6,{text:a})}):(0,X.jsx)(Q,{flexDirection:`column`,children:(0,X.jsxs)(Q,{flexDirection:`row`,gap:1,children:[(0,X.jsx)($,{color:`white`,children:`⏺`}),(0,X.jsx)(l7,{children:a.trimStart()})]})}):null});f7.displayName=`TextSegment`;const p7=(0,Z.memo)(e=>{let{segment:t}=e,n=(0,Z.useMemo)(()=>C3(t),[t]);return(0,X.jsxs)(Q,{flexDirection:`row`,gap:1,alignItems:`flex-start`,children:[(0,X.jsx)($,{color:ZQ,children:`✳`}),(0,X.jsx)(Q,{flexDirection:`column`,gap:0,children:n&&(0,X.jsx)($,{color:ZQ,wrap:`wrap`,children:n})})]})});p7.displayName=`ExpandedThinkingSegment`;const m7=(0,Z.memo)(e=>(0,Z.useContext)(G0)?(0,X.jsx)(p7,{...e}):null);m7.displayName=`ThinkingSegment`;const h7=(0,Z.memo)(e=>{let{toolUseRequest:t,toolUseResult:n,toolDisplayData:r,parsedResult:i,isStreamingArgs:a}=e;if(!t)return null;if(a){let e=Array.isArray(t)?t[0]?.name:t.name;return e===`todo_write`?null:(0,X.jsx)(T0,{name:g3[e??``]?.displayName??e??`Tool`,showSpinner:!0})}return Array.isArray(t)?(0,X.jsx)(X.Fragment,{children:t.map((e,t)=>(0,X.jsx)(d7,{...e,result:n,displayData:r,parsedResult:i},e.id??t))}):(0,X.jsx)(d7,{...t,result:n,displayData:r,parsedResult:i})});h7.displayName=`ToolCallSegment`;const g7=(0,Z.memo)(e=>{let{type:t,segment:n,title:r,isSpinny:i=!1}=e,a=(0,Z.useRef)(dqe());if(t!==`collapsible_component`)throw Error(`Can only render collapsible component segments, got ${t}`);let o=(0,Z.useMemo)(()=>C3(n),[n]);if(!o&&!r)throw Error(`Collapsible component segment must have content or title`);let s=r||uqe(a.current);return(0,X.jsxs)(Q,{borderStyle:o?`single`:void 0,borderColor:r$,flexDirection:`column`,alignItems:`flex-start`,gap:1,children:[s&&(0,X.jsx)(Q,{flexDirection:`row`,alignItems:`center`,gap:1,children:i?(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)(_6,{text:`${s}...`}),(0,X.jsx)($,{dimColor:!0,children:`(esc to interrupt)`})]}):(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)($,{children:` `}),(0,X.jsx)($,{color:XQ,children:s})]})}),o&&(0,X.jsx)(l7,{children:o})]})});g7.displayName=`CollapsibleComponentSegment`;const _7=(0,Z.memo)(e=>{let{type:t,message:n,severity:r=`info`,actions:i,flashKey:a}=e;if(t!==`code_llm_notification`)throw Error(`Can only render notification segments, got ${t}`);let[o,s]=(0,Z.useState)(!1),c=(0,Z.useRef)(a);if((0,Z.useEffect)(()=>{if(a!==c.current&&a!=null){c.current=a,s(!0);let e=setTimeout(()=>s(!1),600);return()=>clearTimeout(e)}},[a]),!n)throw Error(`Notification segment must have message`);let l=(0,Z.useMemo)(()=>r===`info`||r===`success`||r===`error`||r===`warning`?r:`info`,[r]),u=(0,Z.useMemo)(()=>{switch(l){case`info`:return e$;case`success`:return t$;case`warning`:return n$;case`error`:return zNe;default:return e$}},[l]),d=e=>e.replace(/_/g,` `).replace(/([A-Z])/g,` $1`).trim().split(` `).filter(e=>e.length>0).map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join(` `),f=(0,Z.useMemo)(()=>(i||[]).filter(e=>e.link),[i]);return(0,X.jsxs)(Q,{flexDirection:`column`,gap:0,children:[(0,X.jsxs)(Q,{flexDirection:`row`,gap:1,children:[(0,X.jsx)($,{color:u,children:o?`◉`:`●`}),(0,X.jsx)($,{color:u,bold:o,inverse:o,children:o?` ${n} `:n})]}),f.length>0&&(0,X.jsx)(Q,{marginLeft:2,flexDirection:`row`,gap:1,children:f.map((e,t)=>(0,X.jsxs)(Z.Fragment,{children:[t>0&&(0,X.jsx)($,{children:` | `}),(0,X.jsx)($,{color:`cyan`,underline:!0,children:d(e.type)})]},t))})]})});_7.displayName=`NotificationSegment`;const v7=(0,Z.memo)(e=>{let t=e.creditsUsed??0;return t<=0?null:(0,X.jsx)(Q,{justifyContent:`flex-end`,children:(0,X.jsxs)($,{dimColor:!0,children:[`Credits used: `,t.toFixed(2)]})})});v7.displayName=`CreditsSegment`;const y7=(0,Z.memo)(({segment:e})=>{switch(e.type){case`text`:return(0,X.jsx)(f7,{...e});case`thinking`:return(0,X.jsx)(m7,{...e});case`code_llm_tool_call`:return(0,X.jsx)(h7,{...e});case`collapsible_component`:return(0,X.jsx)(g7,{...e});case`code_llm_agent_tool_request`:return(0,X.jsx)(h7,{...e});case`code_llm_notification`:return(0,X.jsx)(_7,{...e});case`code_llm_credits`:return(0,X.jsx)(v7,{...e});default:return null}});y7.displayName=`SegmentBase`;function pqe(e,t){return(0,X.jsx)(_7,{id:`error-fallback`,status:`completed`,source:`bot`,type:`code_llm_notification`,message:e.message,severity:`error`})}function b7({segment:e}){return(0,X.jsx)(Q6,{fallback:pqe,children:(0,X.jsx)(y7,{segment:e})})}const x7=`pondering.thinking.processing.analyzing.exploring.crafting.building.searching.connecting.reflecting.considering.examining.synthesizing.computing.reasoning.contemplating.assembling.formulating.generating.compiling.decoding.unraveling.mapping.weaving.brewing.sculpting.distilling.parsing.digesting.conjuring`.split(`.`);function mqe(e){return e.charAt(0).toUpperCase()+e.slice(1)}function S7(){return x7[Math.floor(Math.random()*x7.length)]}function hqe(e,t){let[n,r]=(0,Z.useState)(0),i=(0,Z.useRef)(null);if((0,Z.useEffect)(()=>{if(!e)return;let t=setInterval(()=>{r(e=>e+1)},500);return()=>clearInterval(t)},[e]),!e)return null;let a=Date.now();if(t){if(i.current===null&&(i.current=t+5e3),a>i.current)return null;let n=t-e;return n<5e3?`thought`:`thought for ${h3(n)}`}i.current=null;let o=a-e;return o<5e3?`thinking`:`thinking for ${h3(o)}`}function gqe(e){let[,t]=(0,Z.useState)(0);if((0,Z.useEffect)(()=>{if(!e)return;let n=setInterval(()=>t(e=>e+1),1e3);return()=>clearInterval(n)},[e]),!e)return null;let n=Date.now()-e;return n<5e3?null:h3(n)}const _qe=({status:e,thinkingStartTime:t,thinkingEndTime:n,runStartTime:r})=>{let{activity:i}=r3(),[a,o]=(0,Z.useState)(()=>S7()),s=(0,Z.useRef)(Sd.Idle);(0,Z.useEffect)(()=>{s.current===Sd.Idle&&e!==Sd.Idle&&o(S7()),s.current=e},[e]);let c=hqe(t,n),l=gqe(r);if(!(e!==Sd.Idle&&e!==Sd.WaitingForToolPermission))return null;let u=e===Sd.LoadingConversation?`Resuming`:mqe(a);return(0,X.jsxs)(Q,{paddingLeft:1,flexDirection:`row`,gap:1,children:[(0,X.jsx)($,{color:`cyan`,children:i===`upload`?`↑`:i===`download`?`↓`:`•`}),(0,X.jsx)(_6,{text:`${u}...`}),c&&(0,X.jsxs)($,{color:`cyan`,children:[`(`,c,`)`]}),l&&!c&&(0,X.jsx)($,{dimColor:!0,children:l}),e!==Sd.LoadingConversation&&(0,X.jsx)($,{dimColor:!0,children:`(esc/ctrl+c to interrupt)`})]})};function vqe(e){switch(e){case`completed`:return`✔`;case`in_progress`:return`◼`;default:return`◻`}}function yqe(e){switch(e){case`completed`:return t$;case`in_progress`:return QQ;default:return XQ}}const C7=(0,Z.memo)(({state:e})=>{let t=(0,Z.useContext)(G0);if(e.total===0||t)return null;let{todos:n,total:r,completed:i,inProgress:a,pending:o}=e,s=[];i>0&&s.push(`${i} done`),a>0&&s.push(`${a} in progress`),o>0&&s.push(`${o} open`);let c=s.length>0?`${r} task${r===1?``:`s`} (${s.join(`, `)})`:`${r} task${r===1?``:`s`}`,l=n.slice(0,5),u=r-l.length;return(0,X.jsxs)(Q,{flexDirection:`column`,paddingLeft:1,children:[(0,X.jsx)($,{dimColor:!0,children:c}),l.map(e=>(0,X.jsxs)(Q,{flexDirection:`row`,gap:1,children:[(0,X.jsx)($,{color:yqe(e.status),children:vqe(e.status)}),(0,X.jsx)($,{color:e.status===`completed`?XQ:void 0,dimColor:e.status===`completed`,strikethrough:e.status===`completed`,children:e.content})]},e.id)),u>0&&(0,X.jsxs)($,{dimColor:!0,children:[` `,`+`,u,` more task`,u===1?``:`s`]})]})});C7.displayName=`TodoList`;const w7=new Set([`read`,`grep`,`glob`,`web_search`,`web_fetch`,`get_tab_content`,`bash_output`,`kill_shell`,`get_interactive_elements`,`navigate_to`,`new_tab`,`switch_active_tab`,`close_tab`,`refresh_tab`,`get_diagnostics`]);function T7(e){let t=e.toolUseRequest;return t?Array.isArray(t)?t[0]?.name??``:t.name??``:``}function bqe(e){let t=e.toolUseRequest;return t?Array.isArray(t)?t[0]?.input??{}:t.input??{}:{}}function xqe(e){if(e.isStreamingArgs)return``;let t=T7(e),n=bqe(e),r=g3[t];if(!r)return``;try{return r.getHeaderParams(n)}catch{return``}}function Sqe(e){switch(e){case`read`:return`read`;case`grep`:case`glob`:return`search`;case`web_search`:return`web`;case`web_fetch`:return`fetch`;case`navigate_to`:case`new_tab`:case`switch_active_tab`:case`close_tab`:case`refresh_tab`:case`get_tab_content`:case`get_interactive_elements`:return`browser`;case`bash_output`:return`terminal_output`;case`kill_shell`:return`terminal_kill`;case`get_diagnostics`:return`diag`;default:return`other`}}function Cqe(e){let t=[];function n(e,n,r){let i=n+r;if(i===0)return;let a;if(r>0)switch(e){case`search`:a=i===1?`searching for 1 pattern`:`searching for ${i} patterns`;break;case`read`:a=i===1?`reading 1 file`:`reading ${i} files`;break;case`list`:a=i===1?`listing 1 directory`:`listing ${i} directories`;break;case`web`:a=i===1?`searching the web`:`searching the web ${i} times`;break;case`fetch`:a=i===1?`fetching 1 URL`:`fetching ${i} URLs`;break;case`browser`:a=i===1?`navigating browser`:`navigating browser ${i} times`;break;case`terminal_output`:a=`getting terminal output`;break;case`terminal_kill`:a=i===1?`killing 1 shell`:`killing ${i} shells`;break;case`diag`:a=`checking diagnostics`;break;default:a=i===1?`1 operation`:`${i} operations`;break}else switch(e){case`search`:a=n===1?`searched for 1 pattern`:`searched for ${n} patterns`;break;case`read`:a=n===1?`read 1 file`:`read ${n} files`;break;case`list`:a=n===1?`listed 1 directory`:`listed ${n} directories`;break;case`web`:a=n===1?`searched the web`:`searched the web ${n} times`;break;case`fetch`:a=n===1?`fetched 1 URL`:`fetched ${n} URLs`;break;case`browser`:a=n===1?`navigated browser`:`navigated browser ${n} times`;break;case`terminal_output`:a=`got terminal output`;break;case`terminal_kill`:a=n===1?`killed 1 shell`:`killed ${n} shells`;break;case`diag`:a=`checked diagnostics`;break;default:a=n===1?`1 operation`:`${n} operations`;break}t.push(a)}for(let t of[`search`,`read`,`list`,`web`,`fetch`,`browser`,`terminal_output`,`terminal_kill`,`diag`,`other`]){let r=e[t];r&&n(t,r.completed,r.executing)}return t.join(`, `)}const E7=(0,Z.memo)(({segments:e})=>{let t={},n=null,r=!1,i=!1;for(let a of e){let e=Sqe(T7(a)),o=!a.toolUseResult;if(t[e]||(t[e]={completed:0,executing:0}),o)t[e].executing++,n=a,r=!0;else{t[e].completed++;let n=a.toolUseResult;(n?.rejected||n?.content?.startsWith(`Error:`))&&(i=!0)}}let a=Cqe(t),o=a.charAt(0).toUpperCase()+a.slice(1),s=n?xqe(n):null;return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsxs)(Q,{flexDirection:`row`,gap:1,alignItems:`center`,children:[r?(0,X.jsx)(w0,{}):(0,X.jsx)($,{color:i?`red`:r?`white`:`green`,children:`⏺`}),(0,X.jsxs)($,{children:[o,r?`…`:``]}),(0,X.jsx)($,{color:XQ,dimColor:!0,children:`(ctrl+o to expand)`})]}),s&&(0,X.jsxs)(Q,{flexDirection:`row`,paddingLeft:2,children:[(0,X.jsxs)($,{color:ZQ,dimColor:!0,children:[`⎿`,` `]}),(0,X.jsx)($,{color:ZQ,children:s})]})]})});E7.displayName=`ToolGroupSummary`;const D7=(0,Z.memo)(({questions:e,onResolve:t})=>{let[n,r]=(0,Z.useState)(0),[i,a]=(0,Z.useState)(0),[o,s]=(0,Z.useState)(()=>new Map),[c,l]=(0,Z.useState)(!1),[u,d]=(0,Z.useState)(()=>new Map),f=(0,Z.useRef)(null),p=(0,Z.useCallback)(e=>f.current?.getExpandedText(e)??e,[]),m=e[n],h=o.get(n)??new Set,g=(0,Z.useRef)(i);g.current=i;let _=(0,Z.useRef)(n);_.current=n;let v=(0,Z.useRef)(c);v.current=c;let y=(0,Z.useRef)(e);y.current=e;let b=(0,Z.useRef)(o);b.current=o;let x=(0,Z.useRef)(u);x.current=u;let S=(0,Z.useCallback)((e,t)=>{let n={};for(let r=0;r<y.current.length;r++){let i=y.current[r];if(!i)continue;let a=e.get(r);if(!a||a.size===0)continue;let o=[...a].sort((e,t)=>e-t).map(e=>i.options[e]?.label??``).filter(Boolean),s=t.get(r);n[`question_${r}`]=s?`${o.join(`, `)} — ${s}`:o.join(`, `)}return n},[]),C=(0,Z.useCallback)((e,n)=>{t({type:`question_answers`,answers:S(e,n)})},[t,S]),w=(0,Z.useCallback)((e,t,n)=>{e>=y.current.length?C(t,n):(r(e),a(0),l(!1))},[C]),T=(0,Z.useCallback)(()=>{let e=_.current;if(!y.current[e])return;let t=b.current,n=x.current;w(e+1,t,n)},[w]),E=(0,Z.useRef)(T);E.current=T;let D=(0,Z.useCallback)(e=>{if(e.key.return){let t=p(f.current?.text?.trim()??``),n=_.current,r=new Map(x.current);t?r.set(n,t):r.delete(n),d(r),l(!1),f.current?.setText(``),e.preventDefault();return}if(e.key.escape){l(!1),f.current?.setText(``),e.preventDefault();return}if(e.key.tab){l(!1),f.current?.setText(``),e.preventDefault();return}},[p]),O=(0,Z.useCallback)(e=>{let t=_.current,n=new Map(x.current),r=p(e.trim());r?n.set(t,r):n.delete(t),d(n),l(!1),f.current?.setText(``)},[p]);if(bZ((0,Z.useCallback)((e,t)=>{if(v.current)return;let n=_.current,i=y.current[n];if(!i)return;let o=i.options.length;if(t.upArrow){a(e=>Math.max(0,e-1));return}if(t.downArrow){a(e=>Math.min(o-1,e+1));return}if(t.leftArrow){n>0&&(r(n-1),a(0),l(!1));return}if(t.rightArrow){n<y.current.length-1&&(r(n+1),a(0),l(!1));return}if(e===` `){let e=g.current,t=new Map(b.current),r=new Set(t.get(n)??[]);i.multiSelect?r.has(e)?r.delete(e):r.add(e):(r.clear(),r.add(e)),t.set(n,r),s(t);return}if(t.return){if((b.current.get(n)??new Set).size===0&&!i.multiSelect){let e=g.current,t=new Map(b.current),r=new Set([e]);t.set(n,r),s(t),w(n+1,t,x.current)}else E.current();return}if(t.tab){l(!0),setTimeout(()=>{let e=x.current.get(n)??``;f.current&&e&&f.current.setText(e)},0);return}if(t.escape){C(b.current,x.current);return}},[w,C]),{isActive:!c}),!m)return null;let k=u.get(n);return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(d6,{title:`Questions (${n+1}/${e.length}): ${m.header}`}),(0,X.jsx)(Q,{flexDirection:`column`,paddingLeft:1,paddingY:1,children:(0,X.jsx)($,{children:m.question})}),(0,X.jsx)(Q,{flexDirection:`column`,paddingLeft:1,children:m.options.map((e,t)=>{let n=t===i,r=h.has(t),a=m.multiSelect?r?`[x] `:`[ ] `:r?`◉ `:`○ `;return(0,X.jsxs)(Q,{flexDirection:`row`,children:[(0,X.jsx)($,{color:n?`cyan`:void 0,children:n?`❯ `:` `}),(0,X.jsxs)($,{color:r?`green`:n?void 0:`brightblack`,children:[a,e.label]}),e.description?(0,X.jsxs)($,{dimColor:!0,children:[` — `,e.description]}):null]},t)})}),c?(0,X.jsx)(Q,{flexDirection:`column`,paddingLeft:1,paddingTop:1,children:(0,X.jsxs)(Q,{flexDirection:`row`,children:[(0,X.jsx)($,{color:`cyan`,children:`❯ `}),(0,X.jsx)($,{dimColor:!0,children:`Note: `}),(0,X.jsx)(t6,{ref:f,flexGrow:1,maxWidth:`90%`,placeholder:`Add context or instructions…`,onSubmit:O,onKeyDown:D})]})}):(0,X.jsx)(Q,{flexDirection:`column`,paddingLeft:1,paddingTop:1,children:k&&(0,X.jsxs)($,{dimColor:!0,children:[`Note: `,(0,X.jsx)($,{italic:!0,children:k})]})}),(0,X.jsx)(Q,{borderStyle:u6,borderBottom:!0,borderTop:!1,borderLeft:!1,borderRight:!1}),(0,X.jsx)(Q,{flexDirection:`row`,paddingLeft:1,paddingBottom:1,gap:2,children:c?(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)($,{dimColor:!0,children:`enter save note`}),(0,X.jsx)($,{dimColor:!0,children:`esc discard note`})]}):(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)($,{dimColor:!0,children:`↑↓ option`}),(0,X.jsx)($,{dimColor:!0,children:`space select`}),(0,X.jsx)($,{dimColor:!0,children:`enter confirm`}),e.length>1&&(0,X.jsx)($,{dimColor:!0,children:`←→ navigate`}),(0,X.jsx)($,{dimColor:!0,children:`tab add note`}),(0,X.jsx)($,{dimColor:!0,children:`esc skip`})]})})]})});D7.displayName=`AskUserQuestionPermissionUI`;const O7=(0,Z.memo)(({option:e,index:t,isSelected:n,showAsInput:r,showAsEdit:i,inputPlaceholder:a,inputPrefix:o,inputBufferRef:s,editBufferRef:c,onInputSubmit:l,onInputKeyDown:u,onEditSubmit:d,onEditKeyDown:f})=>i?(0,X.jsxs)(Q,{flexDirection:`row`,children:[(0,X.jsx)($,{color:`cyan`,children:`❯ `}),(0,X.jsx)($,{children:`${t+1}. `}),(0,X.jsx)(t6,{ref:c,flexGrow:1,maxWidth:`90%`,placeholder:`Edit rule...`,onSubmit:d,onKeyDown:f})]}):r?(0,X.jsxs)(Q,{flexDirection:`row`,children:[(0,X.jsx)($,{color:`cyan`,children:`❯ `}),(0,X.jsx)($,{children:`${t+1}. ${o||``}`}),(0,X.jsx)(t6,{ref:s,flexGrow:1,maxWidth:`90%`,placeholder:a,onSubmit:l,onKeyDown:u})]}):(0,X.jsxs)(Q,{flexDirection:`row`,children:[(0,X.jsx)($,{color:n?`cyan`:void 0,children:n?`❯ `:` `}),(0,X.jsxs)($,{color:n?void 0:`brightblack`,children:[`${t+1}. ${e.label}`,e.hint&&!e.rules&&(0,X.jsxs)($,{dimColor:!0,children:[` (`,e.hint,`)`]})]})]}));O7.displayName=`PermissionOptionItem`;const k7=(0,Z.memo)(({options:e,onSelect:t,inputPlaceholder:n=`and tell AbacusAI`,onModeSwitch:r,modeSwitchHint:i})=>{let[a,o]=(0,Z.useState)(0),[s,c]=(0,Z.useState)(!1),[l,u]=(0,Z.useState)(!1),d=(0,Z.useRef)(null),f=(0,Z.useRef)(null),p=(0,Z.useCallback)(e=>d.current?.getExpandedText(e)??e,[]),m=(0,Z.useCallback)(()=>{},[]),h=(0,Z.useRef)(``),g=(0,Z.useRef)(``),_=(0,Z.useMemo)(()=>e.filter(e=>e.value!==`input`),[e]),v=s,y=(0,Z.useRef)(a);y.current=a;let b=(0,Z.useRef)(_.length);b.current=_.length;let x=(0,Z.useRef)(v);x.current=v;let S=(0,Z.useRef)(l);S.current=l;let C=(0,Z.useRef)(t);C.current=t;let w=(0,Z.useRef)(r);w.current=r;let T=(0,Z.useRef)(_);T.current=_;let E=(0,Z.useCallback)(()=>{let e=T.current[y.current];if(e)if(x.current){let t=d.current?.text?.trim();if(t){let n=p(t),r=e.value===`accept`?`accept`:`reject`;C.current({decision:r,userMessage:n,rules:e.rules}),m()}}else e.value!==`input`&&C.current({decision:e.value,rules:e.rules})},[p,m]),D=(0,Z.useRef)(E);D.current=E;let O=(0,Z.useCallback)(e=>{if(e.trim()){let t=T.current[y.current],n=p(e.trim()),r=t?.value===`accept`?`accept`:`reject`;C.current({decision:r,userMessage:n,rules:t?.rules}),m()}},[p,m]),k=(0,Z.useCallback)(e=>{if(e.key.upArrow||e.key.downArrow){let t=T.current[y.current],n=d.current?.text||``;t?.value===`accept`?h.current=n:t?.value===`reject`&&(g.current=n),c(!1),e.key.upArrow?o(e=>Math.max(0,e-1)):o(e=>Math.min(b.current-1,e+1)),e.preventDefault();return}if(e.key.tab){let t=T.current[y.current];t?.value===`accept`?h.current=``:t?.value===`reject`&&(g.current=``),m(),c(!1),e.preventDefault();return}if(e.key.escape){m(),c(!1),C.current({decision:`reject`}),e.preventDefault();return}},[m]),A=(0,Z.useCallback)(e=>{let t=e.split(`,`).map(e=>e.trim()).filter(Boolean);t.length!==0&&T.current[y.current]&&(t.length===1?C.current({decision:`allowAlwaysWithRule`,rules:t}):C.current({decision:`allowAlwaysWithRules`,rules:t}),u(!1))},[]),j=(0,Z.useCallback)(e=>{if(e.key.escape){u(!1),e.preventDefault();return}},[]);bZ((0,Z.useCallback)((e,t)=>{if(!x.current&&!S.current){if(t.upArrow){o(e=>Math.max(0,e-1));return}if(t.downArrow){o(e=>Math.min(b.current-1,e+1));return}if(t.escape){C.current({decision:`reject`});return}if(t.tab&&t.shift){if(w.current){w.current();return}let e=T.current.findIndex(e=>e.value===`allowAlways`);e!==-1&&(o(e),setTimeout(()=>{C.current({decision:`allowAlways`})},0));return}if(t.tab){let e=T.current[y.current];if(e&&(e.value===`accept`||e.value===`reject`)){c(!0);let t=e.value===`accept`?h.current:g.current;setTimeout(()=>{d.current&&t&&d.current.setText(t)},0)}return}if(e===`e`||e===`E`){let e=T.current[y.current];if(e?.rules?.length){u(!0),setTimeout(()=>{f.current?.setText(e.rules.join(`, `))},0);return}}if(t.return){D.current();return}}},[]),{isActive:!0}),(0,Z.useEffect)(()=>{let e=_[a];e&&(e.value!==`accept`&&e.value!==`reject`||(e.value===`accept`?h.current:g.current)&&!s&&c(!0))},[a,_,s]);let M=(0,Z.useRef)(!1);(0,Z.useEffect)(()=>{s&&(M.current=!0)},[s]),(0,Z.useEffect)(()=>{if(!s||!M.current)return;let e=_[a];if(!e)return;let t=e.value===`accept`?h.current:e.value===`reject`?g.current:``;t?setTimeout(()=>{d.current&&d.current.text===``&&d.current.setText(t),M.current=!1},0):M.current=!1},[s,a,_]);let N=_[a],P=s&&N,ee=e=>e.value===`accept`?`Yes, `:e.value===`reject`?`No, `:``,F=!s&&!l&&N&&(N.value===`accept`||N.value===`reject`),te=!s&&!l&&!!N?.rules?.length,I=_.some(e=>e.value===`allowAlways`||e.value===`allowAlwaysWithRule`);return(0,X.jsxs)(Q,{flexDirection:`column`,children:[_.map((e,t)=>{let r=t===a,i=P&&r,o=e.value===`accept`?h.current:e.value===`reject`?g.current:``;return(0,X.jsx)(O7,{option:!i&&o?{...e,label:`${e.label}, ${o}`}:e,index:t,isSelected:r,showAsInput:i,showAsEdit:l&&r,editBufferRef:f,onEditSubmit:A,onEditKeyDown:j,inputPrefix:ee(e),inputPlaceholder:n,inputBufferRef:d,onInputSubmit:O,onInputKeyDown:k},t)}),(0,X.jsx)(Q,{flexDirection:`row`,marginTop:1,gap:2,children:l?(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)($,{dimColor:!0,children:`enter confirm`}),(0,X.jsx)($,{dimColor:!0,children:`esc cancel`})]}):s?(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)($,{dimColor:!0,children:`enter submit`}),(0,X.jsx)($,{dimColor:!0,children:`tab discard note`}),(0,X.jsx)($,{dimColor:!0,children:`esc reject`})]}):(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)($,{dimColor:!0,children:`↑↓ navigate`}),(0,X.jsx)($,{dimColor:!0,children:`enter select`}),F&&(0,X.jsx)($,{dimColor:!0,children:`tab add note`}),te&&(0,X.jsx)($,{dimColor:!0,children:`e edit rule`}),i&&(0,X.jsxs)($,{dimColor:!0,children:[`shift+tab `,i]}),!i&&I&&(0,X.jsx)($,{dimColor:!0,children:`shift+tab don't ask again`}),(0,X.jsx)($,{dimColor:!0,children:`esc reject`})]})})]})});k7.displayName=`PermissionOptions`;function A7(e){return e.decision===`accept`&&e.userMessage?{type:`accept_with_message`,message:e.userMessage}:e.decision===`reject`&&e.userMessage?{type:`reject_with_message`,message:e.userMessage}:e.decision===`allowAlwaysWithRule`?e.rules?.length?{type:`allow_always_with_rule`,rule:e.rules[0]}:`accept`:e.decision===`allowAlwaysWithRules`?e.rules?.length?{type:`allow_always_with_rules`,rules:e.rules}:`accept`:e.decision}const j7=(0,Z.memo)(({filePath:e,originalContent:t,newContent:n,diffShownInEditor:r,onResolve:i})=>{let a=!t,{agentMode:o}=H0(),s=[{label:`Yes, apply changes`,value:`accept`},...o===xd.Normal?[{label:`Allow all edits during this session`,value:`allowAlways`}]:[],{label:`No, reject changes`,value:`reject`}],c=e=>{i(A7(e))};return r?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(d6,{title:`${a?`Create`:`Update`} file ${e}`,subtitle:`Opened changes in the editor`}),(0,X.jsx)(Q,{flexDirection:`column`,paddingLeft:1,children:(0,X.jsx)(k7,{options:s,onSelect:c,onModeSwitch:()=>i(`allowAlways`),modeSwitchHint:`auto-accept all edits`})})]}):(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(d6,{title:`${a?`Create`:`Update`} file ${e}`}),a?a2(e)?(0,X.jsx)(u2,{content:n,maxLinesPerCell:100}):(0,X.jsx)(k0,{filePath:e,content:n,maxLines:100}):a2(e)?(0,X.jsx)(c2,{filePath:e,originalContent:t,newContent:n}):(0,X.jsx)(Q0,{filePath:e,originalContent:t,newContent:n,paddingLeft:1}),(0,X.jsx)(Q,{borderStyle:u6,borderBottom:!0,borderTop:!1,borderLeft:!1,borderRight:!1}),(0,X.jsx)(Q,{flexDirection:`column`,paddingLeft:1,children:(0,X.jsx)(k7,{options:s,onSelect:c,onModeSwitch:()=>i(`allowAlways`),modeSwitchHint:`auto-accept all edits`})})]})});j7.displayName=`EditFilePermissionUI`;const M7=(0,Z.memo)(({filePath:e,originalContent:t,content:n,isNewFile:r,diffShownInEditor:i,onResolve:a})=>{let{agentMode:o}=H0(),s=[{label:`Yes, apply changes`,value:`accept`},...o===xd.Normal?[{label:`Allow all edits during this session`,value:`allowAlways`}]:[],{label:`No, reject changes`,value:`reject`}],c=e=>{a(A7(e))};return i?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(d6,{title:`${r?`Create`:`Update`} file ${e}`,subtitle:`Opened changes in the editor`}),(0,X.jsx)(Q,{flexDirection:`column`,paddingLeft:1,children:(0,X.jsx)(k7,{options:s,onSelect:c,onModeSwitch:()=>a(`allowAlways`),modeSwitchHint:`auto-accept all edits`})})]}):(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(d6,{title:`${r?`Create`:`Update`} file ${e}`}),r?a2(e)?(0,X.jsx)(u2,{content:n,maxLinesPerCell:100}):(0,X.jsx)(k0,{filePath:e,content:n,maxLines:100}):a2(e)?(0,X.jsx)(c2,{filePath:e,originalContent:t,newContent:n}):(0,X.jsx)(Q0,{filePath:e,originalContent:t,newContent:n,paddingLeft:1}),(0,X.jsx)(Q,{borderStyle:u6,borderBottom:!0,borderTop:!1,borderLeft:!1,borderRight:!1}),(0,X.jsx)(Q,{flexDirection:`column`,paddingLeft:1,children:(0,X.jsx)(k7,{options:s,onSelect:c,onModeSwitch:()=>a(`allowAlways`),modeSwitchHint:`auto-accept all edits`})})]})});M7.displayName=`WriteFilePermissionUI`;const N7=(0,Z.memo)(({description:e,url:t,displayName:n,onResolve:r})=>{let i=[{label:`Yes, allow action`,value:`accept`},{label:`Yes, and always allow ${n}`,value:`allowAlwaysWithRule`,rules:[n]},{label:`No, deny action`,value:`reject`}];return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(d6,{title:`Browser action: ${e}`}),(0,X.jsxs)(Q,{flexDirection:`column`,paddingLeft:1,paddingY:1,children:[(0,X.jsx)($,{children:e}),t&&(0,X.jsxs)($,{dimColor:!0,children:[`URL: `,t]})]}),(0,X.jsx)(Q,{borderStyle:u6,borderBottom:!0,borderTop:!1,borderLeft:!1,borderRight:!1}),(0,X.jsx)(Q,{flexDirection:`column`,paddingLeft:1,children:(0,X.jsx)(k7,{options:i,onSelect:e=>{r(A7(e))}})})]})});N7.displayName=`BrowserActionPermissionUI`;const P7=(0,Z.memo)(({command:e,background:t,unmatchedPatterns:n,onResolve:r})=>{let i=(0,Z.useMemo)(()=>S0(),[]),a=FF(e),o=(0,Z.useMemo)(()=>{let e=[{label:`Yes, run command`,value:`accept`}];if(n.length>1){e.push({label:`Yes, and always allow all: ${n.map(e=>`Bash(${e})`).join(`, `)}`,value:`allowAlwaysWithRules`,rules:n.map(e=>`Bash(${e})`)});for(let t of n)e.push({label:`Yes, and always allow Bash(${t})`,value:`allowAlwaysWithRule`,rules:[`Bash(${t})`]})}else n.length===1?e.push({label:`Yes, and always allow Bash(${n[0]})`,value:`allowAlwaysWithRule`,rules:[`Bash(${n[0]})`]}):e.push({label:`Yes, and always allow Bash(${a})`,value:`allowAlwaysWithRule`,rules:[`Bash(${a})`]});return e.push({label:`No, skip command`,value:`reject`}),e},[n,a]);return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(d6,{title:`Bash command`}),(0,X.jsxs)(Q,{flexDirection:`column`,paddingLeft:1,paddingY:1,children:[(0,X.jsx)($,{children:(0,b0.supportsLanguage)(`bash`)?(()=>{try{return(0,b0.highlight)(e,{language:`bash`,theme:i})}catch{return e}})():e}),t&&(0,X.jsx)(Q,{paddingTop:1,children:(0,X.jsx)($,{dimColor:!0,children:`(Running in background)`})})]}),(0,X.jsx)(Q,{borderStyle:u6,borderBottom:!0,borderTop:!1,borderLeft:!1,borderRight:!1}),(0,X.jsx)(Q,{flexDirection:`column`,paddingLeft:1,children:(0,X.jsx)(k7,{options:o,onSelect:e=>{r(A7(e))},inputPlaceholder:`Type here to tell AbacusAI what to do differently`,onModeSwitch:()=>r(`allowAlways`),modeSwitchHint:`allow all tools`})})]})});P7.displayName=`RunTerminalPermissionUI`;const F7=(0,Z.memo)(({title:e,description:t,toolName:n,onResolve:r})=>{let i=(0,Z.useMemo)(()=>S0(),[]),a=[{label:`Yes, allow`,value:`accept`},...n?[{label:`Yes, and always allow ${n}`,value:`allowAlwaysWithRule`,rules:[n]}]:[],{label:`No, deny`,value:`reject`}];return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(d6,{title:e}),(0,X.jsx)(Q,{flexDirection:`column`,paddingLeft:1,paddingY:1,children:(0,X.jsx)($,{children:(0,b0.supportsLanguage)(`json`)?(()=>{try{return(0,b0.highlight)(t,{language:`json`,theme:i})}catch{return t}})():t})}),(0,X.jsx)(Q,{borderStyle:u6,borderBottom:!0,borderTop:!1,borderLeft:!1,borderRight:!1}),(0,X.jsx)(Q,{flexDirection:`column`,paddingLeft:1,children:(0,X.jsx)(k7,{options:a,onSelect:e=>{r(A7(e))}})})]})});F7.displayName=`GenericPermissionUI`;const I7=(0,Z.memo)(({planFilePath:e,planContent:t,onResolve:n})=>(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(d6,{title:`Ready to code? Implement plan: ${e.length>60?`…${e.slice(-60)}`:e}`}),t&&(0,X.jsxs)(Q,{flexDirection:`column`,paddingLeft:1,paddingY:1,children:[(0,X.jsx)($,{dimColor:!0,children:`Here is Abacus's plan:`}),(0,X.jsx)(l7,{children:t})]}),(0,X.jsx)(Q,{borderStyle:u6,borderBottom:!0,borderTop:!1,borderLeft:!1,borderRight:!1}),(0,X.jsx)(Q,{flexDirection:`column`,paddingLeft:1,children:(0,X.jsx)(k7,{options:[{label:`Yes, implement the plan (approve each edit)`,value:`accept`},{label:`Yes, implement the plan (auto-accept all edits)`,value:`allowAlways`,hint:`shift+tab`},{label:`Yes, implement the plan (full permissions granted)`,value:`allowYolo`},{label:`No, keep planning`,value:`reject`}],onSelect:e=>{n(A7(e))},inputPlaceholder:`Add instructions for the implementation`})})]}));I7.displayName=`ExitPlanModePermissionUI`;const L7=(0,Z.memo)(({filePath:e,deducedDirectory:t,onResolve:n})=>{let r=[{label:`Yes, allow read`,value:`accept`},{label:`Yes, and always allow ${t}`,value:`allowAlways`},{label:`No, deny read`,value:`reject`}];return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(d6,{title:`Read file outside workspace`}),(0,X.jsxs)(Q,{flexDirection:`column`,paddingLeft:1,paddingY:1,children:[(0,X.jsx)($,{children:e}),(0,X.jsxs)($,{dimColor:!0,children:[`Directory: `,t]})]}),(0,X.jsx)(Q,{borderStyle:u6,borderBottom:!0,borderTop:!1,borderLeft:!1,borderRight:!1}),(0,X.jsx)(Q,{flexDirection:`column`,paddingLeft:1,children:(0,X.jsx)(k7,{options:r,onSelect:e=>{n(A7(e))}})})]})});L7.displayName=`ReadOutsideDirectoryPermissionUI`;const R7=(0,Z.memo)(({filePath:e,deducedDirectory:t,isNewFile:n,onResolve:r})=>{let i=[{label:`Yes, allow write`,value:`accept`},{label:`Yes, and always allow ${t}`,value:`allowAlways`},{label:`No, deny write`,value:`reject`}];return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(d6,{title:`${n?`Create`:`Write`} file outside workspace`}),(0,X.jsxs)(Q,{flexDirection:`column`,paddingLeft:1,paddingY:1,children:[(0,X.jsx)($,{children:e}),(0,X.jsxs)($,{dimColor:!0,children:[`Directory: `,t]})]}),(0,X.jsx)(Q,{borderStyle:u6,borderBottom:!0,borderTop:!1,borderLeft:!1,borderRight:!1}),(0,X.jsx)(Q,{flexDirection:`column`,paddingLeft:1,children:(0,X.jsx)(k7,{options:i,onSelect:e=>{r(A7(e))}})})]})});R7.displayName=`WriteOutsideDirectoryPermissionUI`;const z7=(0,Z.memo)(({filePath:e,deducedDirectory:t,onResolve:n})=>{let r=[{label:`Yes, allow edit`,value:`accept`},{label:`Yes, and always allow ${t}`,value:`allowAlways`},{label:`No, deny edit`,value:`reject`}];return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(d6,{title:`Edit file outside workspace`}),(0,X.jsxs)(Q,{flexDirection:`column`,paddingLeft:1,paddingY:1,children:[(0,X.jsx)($,{children:e}),(0,X.jsxs)($,{dimColor:!0,children:[`Directory: `,t]})]}),(0,X.jsx)(Q,{borderStyle:u6,borderBottom:!0,borderTop:!1,borderLeft:!1,borderRight:!1}),(0,X.jsx)(Q,{flexDirection:`column`,paddingLeft:1,children:(0,X.jsx)(k7,{options:r,onSelect:e=>{n(A7(e))}})})]})});z7.displayName=`EditOutsideDirectoryPermissionUI`;const B7=(0,Z.memo)(({filePath:e,deducedDirectory:t,onResolve:n})=>{let r=[{label:`Yes, allow notebook edit`,value:`accept`},{label:`Yes, and always allow ${t}`,value:`allowAlways`},{label:`No, deny notebook edit`,value:`reject`}];return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(d6,{title:`Edit notebook outside workspace`}),(0,X.jsxs)(Q,{flexDirection:`column`,paddingLeft:1,paddingY:1,children:[(0,X.jsx)($,{children:e}),(0,X.jsxs)($,{dimColor:!0,children:[`Directory: `,t]})]}),(0,X.jsx)(Q,{borderStyle:u6,borderBottom:!0,borderTop:!1,borderLeft:!1,borderRight:!1}),(0,X.jsx)(Q,{flexDirection:`column`,paddingLeft:1,children:(0,X.jsx)(k7,{options:r,onSelect:e=>{n(A7(e))}})})]})});B7.displayName=`NotebookEditOutsideDirectoryPermissionUI`;const V7=(0,Z.memo)(({notebookPath:e,cellId:t,editMode:n,cellType:r,originalContent:i,newContent:a,onResolve:o})=>{let s=n??`replace`,c=``;c=s===`delete`?`Delete cell${t?` ${t}`:``}`:s===`insert`?`Insert new cell${t?` after ${t}`:` at beginning`} (${r??`code`})`:`Replace cell contents for cell ${t??`unknown`}`;let{agentMode:l}=H0(),u=[{label:`Yes, apply changes`,value:`accept`},...l===xd.Normal?[{label:`Allow all edits during this session`,value:`allowAlways`}]:[],{label:`No, reject changes`,value:`reject`}];return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(d6,{title:`Edit notebook`}),(0,X.jsxs)(Q,{flexDirection:`column`,paddingLeft:1,children:[(0,X.jsx)($,{dimColor:!0,children:e}),(0,X.jsx)($,{dimColor:!0,children:c})]}),s===`delete`?(0,X.jsx)(Q,{flexDirection:`column`,paddingLeft:1,paddingY:1,children:(0,X.jsx)($,{color:`red`,children:`Cell will be deleted`})}):s===`insert`||!i?(0,X.jsx)(Q0,{filePath:i2(r===`markdown`?`markdown`:`python`),originalContent:``,newContent:a,showHeader:!1,paddingLeft:1}):(0,X.jsx)(s2,{cellIndex:0,cellType:r??`code`,cellId:t,language:r===`markdown`?`markdown`:`python`,originalSource:i,newSource:a,status:`modified`}),(0,X.jsx)(Q,{borderStyle:u6,borderBottom:!0,borderTop:!1,borderLeft:!1,borderRight:!1}),(0,X.jsx)(Q,{flexDirection:`column`,paddingLeft:1,children:(0,X.jsx)(k7,{options:u,onSelect:e=>{o(A7(e))},onModeSwitch:()=>o(`allowAlways`),modeSwitchHint:`auto-accept all edits`})})]})});V7.displayName=`NotebookEditPermissionUI`;const H7=(0,Z.memo)(({pendingTool:e})=>{let{request:t,resolve:n}=e;switch(t.type){case`edit_file`:return(0,X.jsx)(j7,{filePath:t.filePath,originalContent:t.originalContent,newContent:t.newContent,diffShownInEditor:t.diffShownInEditor,onResolve:n});case`write_file`:return(0,X.jsx)(M7,{filePath:t.filePath,originalContent:t.originalContent,content:t.content,isNewFile:t.isNewFile,diffShownInEditor:t.diffShownInEditor,onResolve:n});case`run_terminal`:return(0,X.jsx)(P7,{command:t.command,background:t.background,unmatchedPatterns:t.unmatchedPatterns,onResolve:n});case`browser_action`:return(0,X.jsx)(N7,{description:t.description,url:t.url,displayName:t.displayName,onResolve:n});case`generic`:return(0,X.jsx)(F7,{title:`Tool: ${t.toolName}`,description:t.inputSummary,toolName:t.toolName,onResolve:n});case`read_outside_directory`:return(0,X.jsx)(L7,{filePath:t.filePath,deducedDirectory:t.deducedDirectory,onResolve:n});case`write_outside_directory`:return(0,X.jsx)(R7,{filePath:t.filePath,deducedDirectory:t.deducedDirectory,isNewFile:t.isNewFile,onResolve:n});case`edit_outside_directory`:return(0,X.jsx)(z7,{filePath:t.filePath,deducedDirectory:t.deducedDirectory,onResolve:n});case`notebook_edit_outside_directory`:return(0,X.jsx)(B7,{filePath:t.filePath,deducedDirectory:t.deducedDirectory,onResolve:n});case`exit_plan_mode`:return(0,X.jsx)(I7,{planFilePath:t.planFilePath,planContent:t.planContent,onResolve:n});case`ask_user_question`:return(0,X.jsx)(D7,{questions:t.questions,onResolve:n});case`notebook_edit`:return(0,X.jsx)(V7,{notebookPath:t.notebookPath,cellId:t.cellId,editMode:t.editMode,cellType:t.cellType,originalContent:t.originalContent,newContent:t.newContent,onResolve:n});default:return null}});H7.displayName=`ToolPermissionUI`;function wqe(e){let t=(0,Z.useRef)(!1),n=(0,Z.useRef)(e);(0,Z.useEffect)(()=>{n.current=e},[e]),(0,Z.useEffect)(()=>{let e=()=>{t.current||(t.current=!0,n.current())};return process.on(`exit`,e),process.on(`SIGINT`,e),process.on(`SIGTERM`,e),()=>{e(),process.off(`exit`,e),process.off(`SIGINT`,e),process.off(`SIGTERM`,e)}},[])}const U7=(0,Z.createContext)(null),W7=()=>{let e=(0,Z.use)(U7);if(!e)throw Error(`${W7.name} must be used within a ${G7.name}`);return e};function G7({children:e}){let t=(0,Z.useCallback)(e=>{let t=e.split(``).filter(e=>{let t=e.codePointAt(0);return!(t<=31||t===127)}).join(``);process.stdout.write(TZ(t))},[]);wqe(()=>{process.stdout.write(TZ(``))});let n=(0,Z.useMemo)(()=>({setTitle:t}),[t]);return(0,X.jsx)(U7.Provider,{value:n,children:e})}const K7=2e3;function q7(e,t,n){return e===Sd.ExecutingTool?`tool-executing`:e===Sd.Submitted||e===Sd.Streaming?`streaming`:e===Sd.WaitingForToolPermission&&t?`permission-ui`:n()?`idle-with-text`:`idle-empty`}function Tqe(e){let{agentStatus:t,hasPendingPermission:n,isExpandedView:r,composerHasText:i,hasQueuedMessages:a,stopAgent:o,rejectPermission:s,saveAndClearComposer:c,clearComposer:l,dequeueOne:u,clearQueue:d,exitApp:f}=e,[p,m]=(0,Z.useState)(!1),[h,g]=(0,Z.useState)(null),_=(0,Z.useRef)(null),v=(0,Z.useRef)(null),y=(0,Z.useCallback)(()=>{m(!1),_.current&&=(clearTimeout(_.current),null)},[]),b=(0,Z.useCallback)(()=>{g(null),v.current&&=(clearTimeout(v.current),null)},[]),x=(0,Z.useCallback)(()=>{y(),b()},[y,b]),S=q7(t,n,i),C=(0,Z.useRef)(S);return(0,Z.useEffect)(()=>{let e=C.current;C.current=S,e!==S&&x()},[S,x]),bZ((0,Z.useEffectEvent)((e,S)=>{if(S.ctrl&&e===`z`){process.platform!==`win32`&&process.kill(process.pid,`SIGTSTP`);return}let C=S.escape,w=S.ctrl&&e===`c`,T=S.ctrl&&e===`d`;if(!C&&!w&&!T||C&&r)return;let E=q7(t,n,i);if(E===`tool-executing`||E===`streaming`){x(),o();return}if(E===`permission-ui`){x(),s();return}if(E===`idle-with-text`){if(C){p?(l(),x()):(b(),m(!0),_.current=setTimeout(()=>{m(!1),_.current=null},K7));return}let e=w?`c`:`d`;if(h===e){x(),f();return}if(h!==null){b(),g(e),v.current=setTimeout(()=>{g(null),v.current=null},K7);return}y(),c(),a()&&d(),g(e),v.current=setTimeout(()=>{g(null),v.current=null},K7);return}if(E===`idle-empty`){if(C){a()&&u();return}let e=w?`c`:`d`;if(h===e){x(),f();return}if(h!==null){b(),g(e),v.current=setTimeout(()=>{g(null),v.current=null},K7);return}a()&&d(),g(e),v.current=setTimeout(()=>{g(null),v.current=null},K7)}}),{isActive:!0}),(0,Z.useEffect)(()=>()=>{_.current&&clearTimeout(_.current),v.current&&clearTimeout(v.current)},[]),{escClear:p,exitKey:h}}const Eqe={todos:[],completed:0,inProgress:0,pending:0,total:0};function Dqe(e){let t=e.toolUseRequest;if(!t)return null;let n;if(Array.isArray(t)){for(let e=t.length-1;e>=0;e--){let r=t[e];if(r&&r.name===`todo_write`){n=r;break}}if(!n)return null}else if(n=t,n.name!==`todo_write`)return null;let r=n.input;if(!r)return null;let i=r.todos;if(typeof i==`string`)try{i=JSON.parse(i)}catch{return null}return Array.isArray(i)?i.filter(e=>typeof e==`object`&&!!e&&typeof e.content==`string`&&typeof e.status==`string`).map((e,t)=>({id:e.id??`todo-${t}`,content:e.content,status:e.status})):null}function Oqe(e){return(0,Z.useMemo)(()=>{for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.type!==`code_llm_tool_call`&&n.type!==`code_llm_agent_tool_request`)continue;let r=Dqe(n);if(!r)continue;let i=r.filter(e=>e.status!==`cancelled`);return{todos:i,completed:i.filter(e=>e.status===`completed`).length,inProgress:i.filter(e=>e.status===`in_progress`).length,pending:i.filter(e=>e.status===`pending`).length,total:i.length}}return Eqe},[e])}var kqe=G(((e,t)=>{let n={to(e,t){return t?`[${t+1};${e+1}H`:`[${e+1}G`},move(e,t){let n=``;return e<0?n+=`[${-e}D`:e>0&&(n+=`[${e}C`),t<0?n+=`[${-t}A`:t>0&&(n+=`[${t}B`),n},up:(e=1)=>`[${e}A`,down:(e=1)=>`[${e}B`,forward:(e=1)=>`[${e}C`,backward:(e=1)=>`[${e}D`,nextLine:(e=1)=>`\x1B[E`.repeat(e),prevLine:(e=1)=>`\x1B[F`.repeat(e),left:`\x1B[G`,hide:`\x1B[?25l`,show:`\x1B[?25h`,save:`\x1B7`,restore:`\x1B8`};t.exports={cursor:n,scroll:{up:(e=1)=>`\x1B[S`.repeat(e),down:(e=1)=>`\x1B[T`.repeat(e)},erase:{screen:`\x1B[2J`,up:(e=1)=>`\x1B[1J`.repeat(e),down:(e=1)=>`\x1B[J`.repeat(e),line:`\x1B[2K`,lineEnd:`\x1B[K`,lineStart:`\x1B[1K`,lines(e){let t=``;for(let r=0;r<e;r++)t+=this.line+(r<e-1?n.up():``);return e&&(t+=n.left),t}},beep:`\x07`}})),Aqe=G(((e,t)=>{let n=process||{},r=n.argv||[],i=n.env||{},a=!(i.NO_COLOR||r.includes(`--no-color`))&&(!!i.FORCE_COLOR||r.includes(`--color`)||n.platform===`win32`||(n.stdout||{}).isTTY&&i.TERM!==`dumb`||!!i.CI),o=(e,t,n=e)=>r=>{let i=``+r,a=i.indexOf(t,e.length);return~a?e+s(i,t,n,a)+t:e+i+t},s=(e,t,n,r)=>{let i=``,a=0;do i+=e.substring(a,r)+n,a=r+t.length,r=e.indexOf(t,a);while(~r);return i+e.substring(a)},c=(e=a)=>{let t=e?o:()=>String;return{isColorSupported:e,reset:t(`\x1B[0m`,`\x1B[0m`),bold:t(`\x1B[1m`,`\x1B[22m`,`\x1B[22m\x1B[1m`),dim:t(`\x1B[2m`,`\x1B[22m`,`\x1B[22m\x1B[2m`),italic:t(`\x1B[3m`,`\x1B[23m`),underline:t(`\x1B[4m`,`\x1B[24m`),inverse:t(`\x1B[7m`,`\x1B[27m`),hidden:t(`\x1B[8m`,`\x1B[28m`),strikethrough:t(`\x1B[9m`,`\x1B[29m`),black:t(`\x1B[30m`,`\x1B[39m`),red:t(`\x1B[31m`,`\x1B[39m`),green:t(`\x1B[32m`,`\x1B[39m`),yellow:t(`\x1B[33m`,`\x1B[39m`),blue:t(`\x1B[34m`,`\x1B[39m`),magenta:t(`\x1B[35m`,`\x1B[39m`),cyan:t(`\x1B[36m`,`\x1B[39m`),white:t(`\x1B[37m`,`\x1B[39m`),gray:t(`\x1B[90m`,`\x1B[39m`),bgBlack:t(`\x1B[40m`,`\x1B[49m`),bgRed:t(`\x1B[41m`,`\x1B[49m`),bgGreen:t(`\x1B[42m`,`\x1B[49m`),bgYellow:t(`\x1B[43m`,`\x1B[49m`),bgBlue:t(`\x1B[44m`,`\x1B[49m`),bgMagenta:t(`\x1B[45m`,`\x1B[49m`),bgCyan:t(`\x1B[46m`,`\x1B[49m`),bgWhite:t(`\x1B[47m`,`\x1B[49m`),blackBright:t(`\x1B[90m`,`\x1B[39m`),redBright:t(`\x1B[91m`,`\x1B[39m`),greenBright:t(`\x1B[92m`,`\x1B[39m`),yellowBright:t(`\x1B[93m`,`\x1B[39m`),blueBright:t(`\x1B[94m`,`\x1B[39m`),magentaBright:t(`\x1B[95m`,`\x1B[39m`),cyanBright:t(`\x1B[96m`,`\x1B[39m`),whiteBright:t(`\x1B[97m`,`\x1B[39m`),bgBlackBright:t(`\x1B[100m`,`\x1B[49m`),bgRedBright:t(`\x1B[101m`,`\x1B[49m`),bgGreenBright:t(`\x1B[102m`,`\x1B[49m`),bgYellowBright:t(`\x1B[103m`,`\x1B[49m`),bgBlueBright:t(`\x1B[104m`,`\x1B[49m`),bgMagentaBright:t(`\x1B[105m`,`\x1B[49m`),bgCyanBright:t(`\x1B[106m`,`\x1B[49m`),bgWhiteBright:t(`\x1B[107m`,`\x1B[49m`)}};t.exports=c(),t.exports.createColors=c})),J7=kqe(),Y7=Qe(Aqe(),1);function jqe({onlyFirst:e=!1}={}){let t=[`[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?(?:\\u0007|\\u001B\\u005C|\\u009C))`,`(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]))`].join(`|`);return new RegExp(t,e?void 0:`g`)}const Mqe=jqe();function X7(e){if(typeof e!=`string`)throw TypeError(`Expected a \`string\`, got \`${typeof e}\``);return e.replace(Mqe,``)}function Z7(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,`default`)?e.default:e}var Q7={exports:{}};(function(e){var t={};e.exports=t,t.eastAsianWidth=function(e){var t=e.charCodeAt(0),n=e.length==2?e.charCodeAt(1):0,r=t;return 55296<=t&&t<=56319&&56320<=n&&n<=57343&&(t&=1023,n&=1023,r=t<<10|n,r+=65536),r==12288||65281<=r&&r<=65376||65504<=r&&r<=65510?`F`:r==8361||65377<=r&&r<=65470||65474<=r&&r<=65479||65482<=r&&r<=65487||65490<=r&&r<=65495||65498<=r&&r<=65500||65512<=r&&r<=65518?`H`:4352<=r&&r<=4447||4515<=r&&r<=4519||4602<=r&&r<=4607||9001<=r&&r<=9002||11904<=r&&r<=11929||11931<=r&&r<=12019||12032<=r&&r<=12245||12272<=r&&r<=12283||12289<=r&&r<=12350||12353<=r&&r<=12438||12441<=r&&r<=12543||12549<=r&&r<=12589||12593<=r&&r<=12686||12688<=r&&r<=12730||12736<=r&&r<=12771||12784<=r&&r<=12830||12832<=r&&r<=12871||12880<=r&&r<=13054||13056<=r&&r<=19903||19968<=r&&r<=42124||42128<=r&&r<=42182||43360<=r&&r<=43388||44032<=r&&r<=55203||55216<=r&&r<=55238||55243<=r&&r<=55291||63744<=r&&r<=64255||65040<=r&&r<=65049||65072<=r&&r<=65106||65108<=r&&r<=65126||65128<=r&&r<=65131||110592<=r&&r<=110593||127488<=r&&r<=127490||127504<=r&&r<=127546||127552<=r&&r<=127560||127568<=r&&r<=127569||131072<=r&&r<=194367||177984<=r&&r<=196605||196608<=r&&r<=262141?`W`:32<=r&&r<=126||162<=r&&r<=163||165<=r&&r<=166||r==172||r==175||10214<=r&&r<=10221||10629<=r&&r<=10630?`Na`:r==161||r==164||167<=r&&r<=168||r==170||173<=r&&r<=174||176<=r&&r<=180||182<=r&&r<=186||188<=r&&r<=191||r==198||r==208||215<=r&&r<=216||222<=r&&r<=225||r==230||232<=r&&r<=234||236<=r&&r<=237||r==240||242<=r&&r<=243||247<=r&&r<=250||r==252||r==254||r==257||r==273||r==275||r==283||294<=r&&r<=295||r==299||305<=r&&r<=307||r==312||319<=r&&r<=322||r==324||328<=r&&r<=331||r==333||338<=r&&r<=339||358<=r&&r<=359||r==363||r==462||r==464||r==466||r==468||r==470||r==472||r==474||r==476||r==593||r==609||r==708||r==711||713<=r&&r<=715||r==717||r==720||728<=r&&r<=731||r==733||r==735||768<=r&&r<=879||913<=r&&r<=929||931<=r&&r<=937||945<=r&&r<=961||963<=r&&r<=969||r==1025||1040<=r&&r<=1103||r==1105||r==8208||8211<=r&&r<=8214||8216<=r&&r<=8217||8220<=r&&r<=8221||8224<=r&&r<=8226||8228<=r&&r<=8231||r==8240||8242<=r&&r<=8243||r==8245||r==8251||r==8254||r==8308||r==8319||8321<=r&&r<=8324||r==8364||r==8451||r==8453||r==8457||r==8467||r==8470||8481<=r&&r<=8482||r==8486||r==8491||8531<=r&&r<=8532||8539<=r&&r<=8542||8544<=r&&r<=8555||8560<=r&&r<=8569||r==8585||8592<=r&&r<=8601||8632<=r&&r<=8633||r==8658||r==8660||r==8679||r==8704||8706<=r&&r<=8707||8711<=r&&r<=8712||r==8715||r==8719||r==8721||r==8725||r==8730||8733<=r&&r<=8736||r==8739||r==8741||8743<=r&&r<=8748||r==8750||8756<=r&&r<=8759||8764<=r&&r<=8765||r==8776||r==8780||r==8786||8800<=r&&r<=8801||8804<=r&&r<=8807||8810<=r&&r<=8811||8814<=r&&r<=8815||8834<=r&&r<=8835||8838<=r&&r<=8839||r==8853||r==8857||r==8869||r==8895||r==8978||9312<=r&&r<=9449||9451<=r&&r<=9547||9552<=r&&r<=9587||9600<=r&&r<=9615||9618<=r&&r<=9621||9632<=r&&r<=9633||9635<=r&&r<=9641||9650<=r&&r<=9651||9654<=r&&r<=9655||9660<=r&&r<=9661||9664<=r&&r<=9665||9670<=r&&r<=9672||r==9675||9678<=r&&r<=9681||9698<=r&&r<=9701||r==9711||9733<=r&&r<=9734||r==9737||9742<=r&&r<=9743||9748<=r&&r<=9749||r==9756||r==9758||r==9792||r==9794||9824<=r&&r<=9825||9827<=r&&r<=9829||9831<=r&&r<=9834||9836<=r&&r<=9837||r==9839||9886<=r&&r<=9887||9918<=r&&r<=9919||9924<=r&&r<=9933||9935<=r&&r<=9953||r==9955||9960<=r&&r<=9983||r==10045||r==10071||10102<=r&&r<=10111||11093<=r&&r<=11097||12872<=r&&r<=12879||57344<=r&&r<=63743||65024<=r&&r<=65039||r==65533||127232<=r&&r<=127242||127248<=r&&r<=127277||127280<=r&&r<=127337||127344<=r&&r<=127386||917760<=r&&r<=917999||983040<=r&&r<=1048573||1048576<=r&&r<=1114109?`A`:`N`},t.characterLength=function(e){var t=this.eastAsianWidth(e);return t==`F`||t==`W`||t==`A`?2:1};function n(e){return e.match(/[\uD800-\uDBFF][\uDC00-\uDFFF]|[^\uD800-\uDFFF]/g)||[]}t.length=function(e){for(var t=n(e),r=0,i=0;i<t.length;i++)r+=this.characterLength(t[i]);return r},t.slice=function(e,r,i){textLen=t.length(e),r||=0,i||=1,r<0&&(r=textLen+r),i<0&&(i=textLen+i);for(var a=``,o=0,s=n(e),c=0;c<s.length;c++){var l=s[c],u=t.length(l);if(o>=r-(u==2?1:0))if(o+u<=i)a+=l;else break;o+=u}return a}})(Q7);var Nqe=Q7.exports;const Pqe=Z7(Nqe),Fqe=Z7(function(){return/\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67)\uDB40\uDC7F|(?:\uD83E\uDDD1\uD83C\uDFFF\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFC-\uDFFF])|\uD83D\uDC68(?:\uD83C\uDFFB(?:\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF]))|\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|[\u2695\u2696\u2708]\uFE0F|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))?|(?:\uD83C[\uDFFC-\uDFFF])\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF]))|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])\uFE0F|\u200D(?:(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D[\uDC66\uDC67])|\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC)?|(?:\uD83D\uDC69(?:\uD83C\uDFFB\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|(?:\uD83C[\uDFFC-\uDFFF])\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69]))|\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC69(?:\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83E\uDDD1(?:\u200D(?:\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\uD83D\uDE36\u200D\uD83C\uDF2B|\uD83C\uDFF3\uFE0F\u200D\u26A7|\uD83D\uDC3B\u200D\u2744|(?:(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\uD83C\uDFF4\u200D\u2620|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])\u200D[\u2640\u2642]|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u2600-\u2604\u260E\u2611\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26B0\u26B1\u26C8\u26CF\u26D1\u26D3\u26E9\u26F0\u26F1\u26F4\u26F7\u26F8\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u3030\u303D\u3297\u3299]|\uD83C[\uDD70\uDD71\uDD7E\uDD7F\uDE02\uDE37\uDF21\uDF24-\uDF2C\uDF36\uDF7D\uDF96\uDF97\uDF99-\uDF9B\uDF9E\uDF9F\uDFCD\uDFCE\uDFD4-\uDFDF\uDFF5\uDFF7]|\uD83D[\uDC3F\uDCFD\uDD49\uDD4A\uDD6F\uDD70\uDD73\uDD76-\uDD79\uDD87\uDD8A-\uDD8D\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA\uDECB\uDECD-\uDECF\uDEE0-\uDEE5\uDEE9\uDEF0\uDEF3])\uFE0F|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDE35\u200D\uD83D\uDCAB|\uD83D\uDE2E\u200D\uD83D\uDCA8|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83E\uDDD1(?:\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC|\uD83C\uDFFB)?|\uD83D\uDC69(?:\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC|\uD83C\uDFFB)?|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF6\uD83C\uDDE6|\uD83C\uDDF4\uD83C\uDDF2|\uD83D\uDC08\u200D\u2B1B|\u2764\uFE0F\u200D(?:\uD83D\uDD25|\uD83E\uDE79)|\uD83D\uDC41\uFE0F|\uD83C\uDFF3\uFE0F|\uD83C\uDDFF(?:\uD83C[\uDDE6\uDDF2\uDDFC])|\uD83C\uDDFE(?:\uD83C[\uDDEA\uDDF9])|\uD83C\uDDFC(?:\uD83C[\uDDEB\uDDF8])|\uD83C\uDDFB(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA])|\uD83C\uDDFA(?:\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF])|\uD83C\uDDF9(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF])|\uD83C\uDDF8(?:\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF])|\uD83C\uDDF7(?:\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC])|\uD83C\uDDF5(?:\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE])|\uD83C\uDDF3(?:\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF])|\uD83C\uDDF2(?:\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF])|\uD83C\uDDF1(?:\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE])|\uD83C\uDDF0(?:\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF])|\uD83C\uDDEF(?:\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5])|\uD83C\uDDEE(?:\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9])|\uD83C\uDDED(?:\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA])|\uD83C\uDDEC(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE])|\uD83C\uDDEB(?:\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7])|\uD83C\uDDEA(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA])|\uD83C\uDDE9(?:\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF])|\uD83C\uDDE8(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF])|\uD83C\uDDE7(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF])|\uD83C\uDDE6(?:\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF])|[#\*0-9]\uFE0F\u20E3|\u2764\uFE0F|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])|\uD83C\uDFF4|(?:[\u270A\u270B]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270C\u270D]|\uD83D[\uDD74\uDD90])(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])|[\u270A\u270B]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC08\uDC15\uDC3B\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE2E\uDE35\uDE36\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5]|\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD]|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF]|[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF84\uDF86-\uDF93\uDFA0-\uDFC1\uDFC5\uDFC6\uDFC8\uDFC9\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC07\uDC09-\uDC14\uDC16-\uDC3A\uDC3C-\uDC3E\uDC40\uDC44\uDC45\uDC51-\uDC65\uDC6A\uDC79-\uDC7B\uDC7D-\uDC80\uDC84\uDC88-\uDC8E\uDC90\uDC92-\uDCA9\uDCAB-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDDA4\uDDFB-\uDE2D\uDE2F-\uDE34\uDE37-\uDE44\uDE48-\uDE4A\uDE80-\uDEA2\uDEA4-\uDEB3\uDEB7-\uDEBF\uDEC1-\uDEC5\uDED0-\uDED2\uDED5-\uDED7\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0D\uDD0E\uDD10-\uDD17\uDD1D\uDD20-\uDD25\uDD27-\uDD2F\uDD3A\uDD3F-\uDD45\uDD47-\uDD76\uDD78\uDD7A-\uDDB4\uDDB7\uDDBA\uDDBC-\uDDCB\uDDD0\uDDE0-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6]|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5-\uDED7\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0C-\uDD3A\uDD3C-\uDD45\uDD47-\uDD78\uDD7A-\uDDCB\uDDCD-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26A7\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5-\uDED7\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0C-\uDD3A\uDD3C-\uDD45\uDD47-\uDD78\uDD7A-\uDDCB\uDDCD-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6])\uFE0F|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDC8F\uDC91\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDD77\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD])/g});function $7(e,t={}){if(typeof e!=`string`||e.length===0||(t={ambiguousIsNarrow:!0,...t},e=X7(e),e.length===0))return 0;e=e.replace(Fqe(),` `);let n=t.ambiguousIsNarrow?1:2,r=0;for(let t of e){let e=t.codePointAt(0);if(!(e<=31||e>=127&&e<=159||e>=768&&e<=879))switch(Pqe.eastAsianWidth(t)){case`F`:case`W`:r+=2;break;case`A`:r+=n;break;default:r+=1}}return r}const e9=(e=0)=>t=>`\x1B[${t+e}m`,t9=(e=0)=>t=>`\x1B[${38+e};5;${t}m`,n9=(e=0)=>(t,n,r)=>`\x1B[${38+e};2;${t};${n};${r}m`,r9={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}};Object.keys(r9.modifier);const Iqe=Object.keys(r9.color),Lqe=Object.keys(r9.bgColor);[...Iqe,...Lqe];function Rqe(){let e=new Map;for(let[t,n]of Object.entries(r9)){for(let[t,r]of Object.entries(n))r9[t]={open:`\x1B[${r[0]}m`,close:`\x1B[${r[1]}m`},n[t]=r9[t],e.set(r[0],r[1]);Object.defineProperty(r9,t,{value:n,enumerable:!1})}return Object.defineProperty(r9,`codes`,{value:e,enumerable:!1}),r9.color.close=`\x1B[39m`,r9.bgColor.close=`\x1B[49m`,r9.color.ansi=e9(),r9.color.ansi256=t9(),r9.color.ansi16m=n9(),r9.bgColor.ansi=e9(10),r9.bgColor.ansi256=t9(10),r9.bgColor.ansi16m=n9(10),Object.defineProperties(r9,{rgbToAnsi256:{value:(e,t,n)=>e===t&&t===n?e<8?16:e>248?231:Math.round((e-8)/247*24)+232:16+36*Math.round(e/255*5)+6*Math.round(t/255*5)+Math.round(n/255*5),enumerable:!1},hexToRgb:{value:e=>{let t=/[a-f\d]{6}|[a-f\d]{3}/i.exec(e.toString(16));if(!t)return[0,0,0];let[n]=t;n.length===3&&(n=[...n].map(e=>e+e).join(``));let r=Number.parseInt(n,16);return[r>>16&255,r>>8&255,r&255]},enumerable:!1},hexToAnsi256:{value:e=>r9.rgbToAnsi256(...r9.hexToRgb(e)),enumerable:!1},ansi256ToAnsi:{value:e=>{if(e<8)return 30+e;if(e<16)return 90+(e-8);let t,n,r;if(e>=232)t=((e-232)*10+8)/255,n=t,r=t;else{e-=16;let i=e%36;t=Math.floor(e/36)/5,n=Math.floor(i/6)/5,r=i%6/5}let i=Math.max(t,n,r)*2;if(i===0)return 30;let a=30+(Math.round(r)<<2|Math.round(n)<<1|Math.round(t));return i===2&&(a+=60),a},enumerable:!1},rgbToAnsi:{value:(e,t,n)=>r9.ansi256ToAnsi(r9.rgbToAnsi256(e,t,n)),enumerable:!1},hexToAnsi:{value:e=>r9.ansi256ToAnsi(r9.hexToAnsi256(e)),enumerable:!1}}),r9}const zqe=Rqe(),i9=new Set([`\x1B`,`›`]),a9=`]8;;`,o9=e=>`${i9.values().next().value}[${e}m`,s9=e=>`${i9.values().next().value}${a9}${e}`,Bqe=e=>e.split(` `).map(e=>$7(e)),c9=(e,t,n)=>{let r=[...t],i=!1,a=!1,o=$7(X7(e[e.length-1]));for(let[t,s]of r.entries()){let c=$7(s);if(o+c<=n?e[e.length-1]+=s:(e.push(s),o=0),i9.has(s)&&(i=!0,a=r.slice(t+1).join(``).startsWith(a9)),i){a?s===`\x07`&&(i=!1,a=!1):s===`m`&&(i=!1);continue}o+=c,o===n&&t<r.length-1&&(e.push(``),o=0)}!o&&e[e.length-1].length>0&&e.length>1&&(e[e.length-2]+=e.pop())},Vqe=e=>{let t=e.split(` `),n=t.length;for(;n>0&&!($7(t[n-1])>0);)n--;return n===t.length?e:t.slice(0,n).join(` `)+t.slice(n).join(``)},Hqe=(e,t,n={})=>{if(n.trim!==!1&&e.trim()===``)return``;let r=``,i,a,o=Bqe(e),s=[``];for(let[r,i]of e.split(` `).entries()){n.trim!==!1&&(s[s.length-1]=s[s.length-1].trimStart());let e=$7(s[s.length-1]);if(r!==0&&(e>=t&&(n.wordWrap===!1||n.trim===!1)&&(s.push(``),e=0),(e>0||n.trim===!1)&&(s[s.length-1]+=` `,e++)),n.hard&&o[r]>t){let n=t-e,a=1+Math.floor((o[r]-n-1)/t);Math.floor((o[r]-1)/t)<a&&s.push(``),c9(s,i,t);continue}if(e+o[r]>t&&e>0&&o[r]>0){if(n.wordWrap===!1&&e<t){c9(s,i,t);continue}s.push(``)}if(e+o[r]>t&&n.wordWrap===!1){c9(s,i,t);continue}s[s.length-1]+=i}n.trim!==!1&&(s=s.map(e=>Vqe(e)));let c=[...s.join(`
75429
+ `;default:return n(a7(e))}}function c7(e,t=0,n=!1,r){switch(e.type){case`heading`:return(0,X.jsx)(Q,{flexDirection:`column`,children:(0,X.jsx)($,{bold:!0,color:e.depth<=2?QQ:$Q,dimColor:e.depth>2,children:o7(e.tokens,n)})},`heading-${e.depth}`);case`paragraph`:return(0,X.jsx)(Q,{flexDirection:`column`,children:(0,X.jsx)($,{children:o7(e.tokens,n)})},`paragraph`);case`code`:return(0,X.jsx)(i7,{language:e.lang,children:e.text},`code`);case`blockquote`:return(0,X.jsx)(Q,{borderRight:!1,borderTop:!1,borderBottom:!1,borderStyle:`double`,borderColor:r$,paddingLeft:1,flexDirection:`column`,children:e.tokens?.map((e,n)=>(0,X.jsx)(Q,{children:c7(e,t,!0,r)},n))},`blockquote`);case`list`:return(0,X.jsx)(Q,{flexDirection:`column`,children:e.items.map((i,a)=>{let o=e.ordered?(Number(e.start)||1)+a:null,s=i.task===!0,c=i.checked===!0,l=i.tokens?.filter(e=>e.type!==`checkbox`)||[];return(0,X.jsxs)(Q,{flexDirection:`row`,children:[(0,X.jsx)($,{color:$Q,dimColor:!0,children:s?c?`[✓] `:`[ ] `:o===null?`• `:`${o}. `}),(0,X.jsx)(Q,{flexGrow:1,flexDirection:`column`,children:l.map((e,i)=>(0,X.jsx)(Q,{children:c7(e,t+1,n,r)},i))})]},a)})},`list`);case`table`:{let t=e,i=t.header.map((e,n)=>{let r=M3(a7(e));for(let e of t.rows)r=Math.max(r,M3(a7(e[n])));return Math.max(r,3)}),a=i.reduce((e,t)=>e+t+2,0),o=cqe(i,r===void 0?a:Math.max(10,Math.min(r,a)));return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(Q,{flexDirection:`row`,borderTop:!1,borderLeft:!1,borderRight:!1,borderStyle:`single`,borderColor:r$,alignSelf:`flex-start`,children:t.header.map((e,r)=>{let i=t.align?.[r]||null;return(0,X.jsx)(Q,{width:o[r]+2,paddingX:1,justifyContent:i===`center`?`center`:i===`right`?`flex-end`:`flex-start`,children:(0,X.jsx)($,{bold:!0,color:QQ,wrap:`wrap`,children:o7(e.tokens,n)})},r)})}),t.rows.map((e,r)=>(0,X.jsx)(Q,{flexDirection:`row`,children:e.map((e,r)=>{let i=t.align?.[r]||null;return(0,X.jsx)(Q,{width:o[r]+2,paddingX:1,justifyContent:i===`center`?`center`:i===`right`?`flex-end`:`flex-start`,children:(0,X.jsx)($,{wrap:`wrap`,children:o7(e.tokens,n)})},r)})},r))]},`table`)}case`hr`:return(0,X.jsx)(Q,{children:(0,X.jsx)($,{dimColor:!0,children:`─`.repeat(50)})},`hr`);case`space`:return null;default:return(0,X.jsx)(Q,{flexDirection:`column`,children:(0,X.jsx)($,{children:s7(e,n)})})}}function l7({children:e}){let{width:t}=b3(),n=(0,Z.useMemo)(()=>{try{let t=aqe(e);return F5.lexer(t,{gfm:!0,breaks:!0})}catch{return[]}},[e]);return(0,X.jsx)(Q,{flexDirection:`column`,children:(0,Z.useMemo)(()=>{let e=[],r=n.length;return n.forEach((n,i)=>{let a=i===r-1;if(n.type===`space`){e.push((0,X.jsx)(Q,{height:1},`space-${i}`));return}e.push((0,X.jsx)(Q,{flexDirection:`column`,children:c7(n,0,!1,t)},i)),n.type===`heading`&&!a&&e.push((0,X.jsx)(Q,{height:1},`heading-space-${i}`))}),e},[n,t])})}l7.displayName=`Markdown`;const u7=`Pondering...,Thinking...,Processing...,Analyzing...,Exploring...,Crafting...,Building...,Searching...,Connecting...,Reflecting...,Considering...,Examining...,Synthesizing...,Computing...,Reasoning...,Contemplating...,Assembling...,Formulating...,Generating...,Compiling...,Decoding...,Unraveling...,Mapping...,Weaving...,Brewing...,Sculpting...,Distilling...,Parsing...,Digesting...,Conjuring...`.split(`,`);function uqe(e){return e.charAt(0).toUpperCase()+e.slice(1)}function dqe(){return u7[Math.floor(Math.random()*u7.length)]}const fqe=dt([`codellm`,`cli`,`tools`]);function d7(e){let t=g3[e.name];if(t||=(dUe(e.name),g3[e.name]),!t)return(0,X.jsx)(Q,{flexDirection:`column`,children:(0,X.jsxs)($,{color:`red`,children:[`Unknown tool: `,e.name]})});let n;n=e.result?.rejected?(()=>{try{return JSON.parse(e.result.content)}catch{return{}}})().reason===`interrupted`?`interrupted`:`rejected`:e.result?`success`:e.parsedResult?.phase===`error`?`error`:`executing`;let r=e.input??{},i=``;try{i=t.getHeaderParams(r)}catch{}try{return t.renderUI(r,n,e.parsedResult,e.displayData)}catch(n){let r=n instanceof Error?n.message:String(n);return fqe.error`Error rendering tool ${e.name}: ${r}`,(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(T0,{name:t.displayName,params:i,status:`error`}),(0,X.jsx)(E0,{color:`red`,children:`Error rendering tool`})]})}}const f7=(0,Z.memo)(e=>{let{type:t,segment:n,isSpinny:r=!1,source:i}=e;if(t!==`text`)throw Error(`Can only render text segments, got ${t}`);let a=(0,Z.useMemo)(()=>C3(n),[n]);return a?.trim()?i===`user`?(0,X.jsxs)(Q,{flexDirection:`row`,gap:1,children:[(0,X.jsx)($,{color:XQ,children:`❯`}),(0,X.jsx)($,{color:XQ,italic:!0,children:a})]}):r?(0,X.jsx)(Q,{flexDirection:`row`,alignItems:`center`,gap:1,children:(0,X.jsx)(_6,{text:a})}):(0,X.jsx)(Q,{flexDirection:`column`,children:(0,X.jsxs)(Q,{flexDirection:`row`,gap:1,children:[(0,X.jsx)($,{color:`white`,children:`⏺`}),(0,X.jsx)(l7,{children:a.trimStart()})]})}):null});f7.displayName=`TextSegment`;const p7=(0,Z.memo)(e=>{let{segment:t}=e,n=(0,Z.useMemo)(()=>C3(t),[t]);return(0,X.jsxs)(Q,{flexDirection:`row`,gap:1,alignItems:`flex-start`,children:[(0,X.jsx)($,{color:ZQ,children:`✳`}),(0,X.jsx)(Q,{flexDirection:`column`,gap:0,children:n&&(0,X.jsx)($,{color:ZQ,wrap:`wrap`,children:n})})]})});p7.displayName=`ExpandedThinkingSegment`;const m7=(0,Z.memo)(e=>(0,Z.useContext)(G0)?(0,X.jsx)(p7,{...e}):null);m7.displayName=`ThinkingSegment`;const h7=(0,Z.memo)(e=>{let{toolUseRequest:t,toolUseResult:n,toolDisplayData:r,parsedResult:i,isStreamingArgs:a}=e;if(!t)return null;if(a){let e=Array.isArray(t)?t[0]?.name:t.name;return e===`todo_write`?null:(0,X.jsx)(T0,{name:g3[e??``]?.displayName??e??`Tool`,showSpinner:!0})}return Array.isArray(t)?(0,X.jsx)(X.Fragment,{children:t.map((e,t)=>(0,X.jsx)(d7,{...e,result:n,displayData:r,parsedResult:i},e.id??t))}):(0,X.jsx)(d7,{...t,result:n,displayData:r,parsedResult:i})});h7.displayName=`ToolCallSegment`;const g7=(0,Z.memo)(e=>{let{type:t,segment:n,title:r,isSpinny:i=!1}=e,a=(0,Z.useRef)(dqe());if(t!==`collapsible_component`)throw Error(`Can only render collapsible component segments, got ${t}`);let o=(0,Z.useMemo)(()=>C3(n),[n]);if(!o&&!r)throw Error(`Collapsible component segment must have content or title`);let s=r||uqe(a.current);return(0,X.jsxs)(Q,{borderStyle:o?`single`:void 0,borderColor:r$,flexDirection:`column`,alignItems:`flex-start`,gap:1,children:[s&&(0,X.jsx)(Q,{flexDirection:`row`,alignItems:`center`,gap:1,children:i?(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)(_6,{text:`${s}...`}),(0,X.jsx)($,{dimColor:!0,children:`(esc to interrupt)`})]}):(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)($,{children:` `}),(0,X.jsx)($,{color:XQ,children:s})]})}),o&&(0,X.jsx)(l7,{children:o})]})});g7.displayName=`CollapsibleComponentSegment`;const _7=(0,Z.memo)(e=>{let{type:t,message:n,severity:r=`info`,actions:i,flashKey:a}=e;if(t!==`code_llm_notification`)throw Error(`Can only render notification segments, got ${t}`);let[o,s]=(0,Z.useState)(!1),c=(0,Z.useRef)(a);if((0,Z.useEffect)(()=>{if(a!==c.current&&a!=null){c.current=a,s(!0);let e=setTimeout(()=>s(!1),600);return()=>clearTimeout(e)}},[a]),!n)throw Error(`Notification segment must have message`);let l=(0,Z.useMemo)(()=>r===`info`||r===`success`||r===`error`||r===`warning`?r:`info`,[r]),u=(0,Z.useMemo)(()=>{switch(l){case`info`:return e$;case`success`:return t$;case`warning`:return n$;case`error`:return zNe;default:return e$}},[l]),d=e=>e.replace(/_/g,` `).replace(/([A-Z])/g,` $1`).trim().split(` `).filter(e=>e.length>0).map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join(` `),f=(0,Z.useMemo)(()=>(i||[]).filter(e=>e.link),[i]);return(0,X.jsxs)(Q,{flexDirection:`column`,gap:0,children:[(0,X.jsxs)(Q,{flexDirection:`row`,gap:1,children:[(0,X.jsx)($,{color:u,children:o?`◉`:`●`}),(0,X.jsx)($,{color:u,bold:o,inverse:o,children:o?` ${n} `:n})]}),f.length>0&&(0,X.jsx)(Q,{marginLeft:2,flexDirection:`row`,gap:1,children:f.map((e,t)=>(0,X.jsxs)(Z.Fragment,{children:[t>0&&(0,X.jsx)($,{children:` | `}),(0,X.jsx)($,{color:`cyan`,underline:!0,children:d(e.type)})]},t))})]})});_7.displayName=`NotificationSegment`;const v7=(0,Z.memo)(e=>{let t=e.creditsUsed??0;return t<=0?null:(0,X.jsx)(Q,{justifyContent:`flex-end`,children:(0,X.jsxs)($,{dimColor:!0,children:[`Credits used: `,t.toFixed(2)]})})});v7.displayName=`CreditsSegment`;const y7=(0,Z.memo)(({segment:e})=>{switch(e.type){case`text`:return(0,X.jsx)(f7,{...e});case`thinking`:return(0,X.jsx)(m7,{...e});case`code_llm_tool_call`:return(0,X.jsx)(h7,{...e});case`collapsible_component`:return(0,X.jsx)(g7,{...e});case`code_llm_agent_tool_request`:return(0,X.jsx)(h7,{...e});case`code_llm_notification`:return(0,X.jsx)(_7,{...e});case`code_llm_credits`:return(0,X.jsx)(v7,{...e});default:return null}});y7.displayName=`SegmentBase`;function pqe(e,t){return(0,X.jsx)(_7,{id:`error-fallback`,status:`completed`,source:`bot`,type:`code_llm_notification`,message:e.message,severity:`error`})}function b7({segment:e}){return(0,X.jsx)(Q6,{fallback:pqe,children:(0,X.jsx)(y7,{segment:e})})}const x7=`pondering.thinking.processing.analyzing.exploring.crafting.building.searching.connecting.reflecting.considering.examining.synthesizing.computing.reasoning.contemplating.assembling.formulating.generating.compiling.decoding.unraveling.mapping.weaving.brewing.sculpting.distilling.parsing.digesting.conjuring`.split(`.`);function mqe(e){return e.charAt(0).toUpperCase()+e.slice(1)}function S7(){return x7[Math.floor(Math.random()*x7.length)]}function hqe(e,t){let[n,r]=(0,Z.useState)(0),i=(0,Z.useRef)(null);if((0,Z.useEffect)(()=>{if(!e)return;let t=setInterval(()=>{r(e=>e+1)},500);return()=>clearInterval(t)},[e]),!e)return null;let a=Date.now();if(t){if(i.current===null&&(i.current=t+5e3),a>i.current)return null;let n=t-e;return n<5e3?`thought`:`thought for ${h3(n)}`}i.current=null;let o=a-e;return o<5e3?`thinking`:`thinking for ${h3(o)}`}function gqe(e){let[,t]=(0,Z.useState)(0);if((0,Z.useEffect)(()=>{if(!e)return;let n=setInterval(()=>t(e=>e+1),1e3);return()=>clearInterval(n)},[e]),!e)return null;let n=Date.now()-e;return n<5e3?null:h3(n)}const _qe=({status:e,thinkingStartTime:t,thinkingEndTime:n,runStartTime:r})=>{let{activity:i}=r3(),[a,o]=(0,Z.useState)(()=>S7()),s=(0,Z.useRef)(Sd.Idle);(0,Z.useEffect)(()=>{s.current===Sd.Idle&&e!==Sd.Idle&&o(S7()),s.current=e},[e]);let c=hqe(t,n),l=gqe(r);if(!(e!==Sd.Idle&&e!==Sd.WaitingForToolPermission))return null;let u=e===Sd.LoadingConversation?`Resuming`:mqe(a);return(0,X.jsxs)(Q,{paddingLeft:1,flexDirection:`row`,gap:1,children:[(0,X.jsx)($,{color:`cyan`,children:i===`upload`?`↑`:i===`download`?`↓`:`•`}),(0,X.jsx)(_6,{text:`${u}...`}),c&&(0,X.jsxs)($,{color:`cyan`,children:[`(`,c,`)`]}),l&&!c&&(0,X.jsx)($,{dimColor:!0,children:l}),e!==Sd.LoadingConversation&&(0,X.jsx)($,{dimColor:!0,children:`(esc/ctrl+c to interrupt)`})]})};function vqe(e){switch(e){case`completed`:return`✔`;case`in_progress`:return`◼`;default:return`◻`}}function yqe(e){switch(e){case`completed`:return t$;case`in_progress`:return QQ;default:return XQ}}const C7=(0,Z.memo)(({state:e})=>{let t=(0,Z.useContext)(G0);if(e.total===0||t)return null;let{todos:n,total:r,completed:i,inProgress:a,pending:o}=e,s=[];i>0&&s.push(`${i} done`),a>0&&s.push(`${a} in progress`),o>0&&s.push(`${o} open`);let c=s.length>0?`${r} task${r===1?``:`s`} (${s.join(`, `)})`:`${r} task${r===1?``:`s`}`,l=n.slice(0,5),u=r-l.length;return(0,X.jsxs)(Q,{flexDirection:`column`,paddingLeft:1,children:[(0,X.jsx)($,{dimColor:!0,children:c}),l.map(e=>(0,X.jsxs)(Q,{flexDirection:`row`,gap:1,children:[(0,X.jsx)($,{color:yqe(e.status),children:vqe(e.status)}),(0,X.jsx)($,{color:e.status===`completed`?XQ:void 0,dimColor:e.status===`completed`,strikethrough:e.status===`completed`,children:e.content})]},e.id)),u>0&&(0,X.jsxs)($,{dimColor:!0,children:[` `,`+`,u,` more task`,u===1?``:`s`]})]})});C7.displayName=`TodoList`;const w7=new Set([`read`,`grep`,`glob`,`web_search`,`web_fetch`,`get_tab_content`,`bash_output`,`kill_shell`,`get_interactive_elements`,`navigate_to`,`new_tab`,`switch_active_tab`,`close_tab`,`refresh_tab`,`get_diagnostics`]);function T7(e){let t=e.toolUseRequest;return t?Array.isArray(t)?t[0]?.name??``:t.name??``:``}function bqe(e){let t=e.toolUseRequest;return t?Array.isArray(t)?t[0]?.input??{}:t.input??{}:{}}function xqe(e){if(e.isStreamingArgs)return``;let t=T7(e),n=bqe(e),r=g3[t];if(!r)return``;try{return r.getHeaderParams(n)}catch{return``}}function Sqe(e){switch(e){case`read`:return`read`;case`grep`:case`glob`:return`search`;case`web_search`:return`web`;case`web_fetch`:return`fetch`;case`navigate_to`:case`new_tab`:case`switch_active_tab`:case`close_tab`:case`refresh_tab`:case`get_tab_content`:case`get_interactive_elements`:return`browser`;case`bash_output`:return`terminal_output`;case`kill_shell`:return`terminal_kill`;case`get_diagnostics`:return`diag`;default:return`other`}}function Cqe(e){let t=[];function n(e,n,r){let i=n+r;if(i===0)return;let a;if(r>0)switch(e){case`search`:a=i===1?`searching for 1 pattern`:`searching for ${i} patterns`;break;case`read`:a=i===1?`reading 1 file`:`reading ${i} files`;break;case`list`:a=i===1?`listing 1 directory`:`listing ${i} directories`;break;case`web`:a=i===1?`searching the web`:`searching the web ${i} times`;break;case`fetch`:a=i===1?`fetching 1 URL`:`fetching ${i} URLs`;break;case`browser`:a=i===1?`navigating browser`:`navigating browser ${i} times`;break;case`terminal_output`:a=`getting terminal output`;break;case`terminal_kill`:a=i===1?`killing 1 shell`:`killing ${i} shells`;break;case`diag`:a=`checking diagnostics`;break;default:a=i===1?`1 operation`:`${i} operations`;break}else switch(e){case`search`:a=n===1?`searched for 1 pattern`:`searched for ${n} patterns`;break;case`read`:a=n===1?`read 1 file`:`read ${n} files`;break;case`list`:a=n===1?`listed 1 directory`:`listed ${n} directories`;break;case`web`:a=n===1?`searched the web`:`searched the web ${n} times`;break;case`fetch`:a=n===1?`fetched 1 URL`:`fetched ${n} URLs`;break;case`browser`:a=n===1?`navigated browser`:`navigated browser ${n} times`;break;case`terminal_output`:a=`got terminal output`;break;case`terminal_kill`:a=n===1?`killed 1 shell`:`killed ${n} shells`;break;case`diag`:a=`checked diagnostics`;break;default:a=n===1?`1 operation`:`${n} operations`;break}t.push(a)}for(let t of[`search`,`read`,`list`,`web`,`fetch`,`browser`,`terminal_output`,`terminal_kill`,`diag`,`other`]){let r=e[t];r&&n(t,r.completed,r.executing)}return t.join(`, `)}const E7=(0,Z.memo)(({segments:e})=>{let t={},n=null,r=!1,i=!1;for(let a of e){let e=Sqe(T7(a)),o=!a.toolUseResult;if(t[e]||(t[e]={completed:0,executing:0}),o)t[e].executing++,n=a,r=!0;else{t[e].completed++;let n=a.toolUseResult;(n?.rejected||n?.content?.startsWith(`Error:`))&&(i=!0)}}let a=Cqe(t),o=a.charAt(0).toUpperCase()+a.slice(1),s=n?xqe(n):null;return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsxs)(Q,{flexDirection:`row`,gap:1,alignItems:`center`,children:[r?(0,X.jsx)(w0,{}):(0,X.jsx)($,{color:i?`red`:r?`white`:`green`,children:`⏺`}),(0,X.jsxs)($,{children:[o,r?`…`:``]}),(0,X.jsx)($,{color:XQ,dimColor:!0,children:`(ctrl+o to expand)`})]}),s&&(0,X.jsxs)(Q,{flexDirection:`row`,paddingLeft:2,children:[(0,X.jsxs)($,{color:ZQ,dimColor:!0,children:[`⎿`,` `]}),(0,X.jsx)($,{color:ZQ,children:s})]})]})});E7.displayName=`ToolGroupSummary`;const D7=(0,Z.memo)(({questions:e,onResolve:t})=>{let[n,r]=(0,Z.useState)(0),[i,a]=(0,Z.useState)(0),[o,s]=(0,Z.useState)(()=>new Map),[c,l]=(0,Z.useState)(!1),[u,d]=(0,Z.useState)(()=>new Map),f=(0,Z.useRef)(null),p=(0,Z.useCallback)(e=>f.current?.getExpandedText(e)??e,[]),m=e[n],h=o.get(n)??new Set,g=(0,Z.useRef)(i);g.current=i;let _=(0,Z.useRef)(n);_.current=n;let v=(0,Z.useRef)(c);v.current=c;let y=(0,Z.useRef)(e);y.current=e;let b=(0,Z.useRef)(o);b.current=o;let x=(0,Z.useRef)(u);x.current=u;let S=(0,Z.useCallback)((e,t)=>{let n={};for(let r=0;r<y.current.length;r++){let i=y.current[r];if(!i)continue;let a=e.get(r);if(!a||a.size===0)continue;let o=[...a].sort((e,t)=>e-t).map(e=>i.options[e]?.label??``).filter(Boolean),s=t.get(r);n[`question_${r}`]=s?`${o.join(`, `)} — ${s}`:o.join(`, `)}return n},[]),C=(0,Z.useCallback)((e,n)=>{t({type:`question_answers`,answers:S(e,n)})},[t,S]),w=(0,Z.useCallback)((e,t,n)=>{e>=y.current.length?C(t,n):(r(e),a(0),l(!1))},[C]),T=(0,Z.useCallback)(()=>{let e=_.current;if(!y.current[e])return;let t=b.current,n=x.current;w(e+1,t,n)},[w]),E=(0,Z.useRef)(T);E.current=T;let D=(0,Z.useCallback)(e=>{if(e.key.return){let t=p(f.current?.text?.trim()??``),n=_.current,r=new Map(x.current);t?r.set(n,t):r.delete(n),d(r),l(!1),f.current?.setText(``),e.preventDefault();return}if(e.key.escape){l(!1),f.current?.setText(``),e.preventDefault();return}if(e.key.tab){l(!1),f.current?.setText(``),e.preventDefault();return}},[p]),O=(0,Z.useCallback)(e=>{let t=_.current,n=new Map(x.current),r=p(e.trim());r?n.set(t,r):n.delete(t),d(n),l(!1),f.current?.setText(``)},[p]);if(bZ((0,Z.useCallback)((e,t)=>{if(v.current)return;let n=_.current,i=y.current[n];if(!i)return;let o=i.options.length;if(t.upArrow){a(e=>Math.max(0,e-1));return}if(t.downArrow){a(e=>Math.min(o-1,e+1));return}if(t.leftArrow){n>0&&(r(n-1),a(0),l(!1));return}if(t.rightArrow){n<y.current.length-1&&(r(n+1),a(0),l(!1));return}if(e===` `){let e=g.current,t=new Map(b.current),r=new Set(t.get(n)??[]);i.multiSelect?r.has(e)?r.delete(e):r.add(e):(r.clear(),r.add(e)),t.set(n,r),s(t);return}if(t.return){if((b.current.get(n)??new Set).size===0&&!i.multiSelect){let e=g.current,t=new Map(b.current),r=new Set([e]);t.set(n,r),s(t),w(n+1,t,x.current)}else E.current();return}if(t.tab){l(!0),setTimeout(()=>{let e=x.current.get(n)??``;f.current&&e&&f.current.setText(e)},0);return}if(t.escape){C(b.current,x.current);return}},[w,C]),{isActive:!c}),!m)return null;let k=u.get(n);return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(d6,{title:`Questions (${n+1}/${e.length}): ${m.header}`}),(0,X.jsx)(Q,{flexDirection:`column`,paddingLeft:1,paddingY:1,children:(0,X.jsx)($,{children:m.question})}),(0,X.jsx)(Q,{flexDirection:`column`,paddingLeft:1,children:m.options.map((e,t)=>{let n=t===i,r=h.has(t),a=m.multiSelect?r?`[x] `:`[ ] `:r?`◉ `:`○ `;return(0,X.jsxs)(Q,{flexDirection:`row`,children:[(0,X.jsx)($,{color:n?`cyan`:void 0,children:n?`❯ `:` `}),(0,X.jsxs)($,{color:r?`green`:n?void 0:`brightblack`,children:[a,e.label]}),e.description?(0,X.jsxs)($,{dimColor:!0,children:[` — `,e.description]}):null]},t)})}),c?(0,X.jsx)(Q,{flexDirection:`column`,paddingLeft:1,paddingTop:1,children:(0,X.jsxs)(Q,{flexDirection:`row`,children:[(0,X.jsx)($,{color:`cyan`,children:`❯ `}),(0,X.jsx)($,{dimColor:!0,children:`Note: `}),(0,X.jsx)(t6,{ref:f,flexGrow:1,maxWidth:`90%`,placeholder:`Add context or instructions…`,onSubmit:O,onKeyDown:D})]})}):(0,X.jsx)(Q,{flexDirection:`column`,paddingLeft:1,paddingTop:1,children:k&&(0,X.jsxs)($,{dimColor:!0,children:[`Note: `,(0,X.jsx)($,{italic:!0,children:k})]})}),(0,X.jsx)(Q,{borderStyle:u6,borderBottom:!0,borderTop:!1,borderLeft:!1,borderRight:!1}),(0,X.jsx)(Q,{flexDirection:`row`,paddingLeft:1,paddingBottom:1,gap:2,children:c?(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)($,{dimColor:!0,children:`enter save note`}),(0,X.jsx)($,{dimColor:!0,children:`esc discard note`})]}):(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)($,{dimColor:!0,children:`↑↓ option`}),(0,X.jsx)($,{dimColor:!0,children:`space select`}),(0,X.jsx)($,{dimColor:!0,children:`enter confirm`}),e.length>1&&(0,X.jsx)($,{dimColor:!0,children:`←→ navigate`}),(0,X.jsx)($,{dimColor:!0,children:`tab add note`}),(0,X.jsx)($,{dimColor:!0,children:`esc skip`})]})})]})});D7.displayName=`AskUserQuestionPermissionUI`;const O7=(0,Z.memo)(({option:e,index:t,isSelected:n,showAsInput:r,showAsEdit:i,inputPlaceholder:a,inputPrefix:o,inputBufferRef:s,editBufferRef:c,onInputSubmit:l,onInputKeyDown:u,onEditSubmit:d,onEditKeyDown:f})=>i?(0,X.jsxs)(Q,{flexDirection:`row`,children:[(0,X.jsx)($,{color:`cyan`,children:`❯ `}),(0,X.jsx)($,{children:`${t+1}. `}),(0,X.jsx)(t6,{ref:c,flexGrow:1,maxWidth:`90%`,placeholder:`Edit rule...`,onSubmit:d,onKeyDown:f})]}):r?(0,X.jsxs)(Q,{flexDirection:`row`,children:[(0,X.jsx)($,{color:`cyan`,children:`❯ `}),(0,X.jsx)($,{children:`${t+1}. ${o||``}`}),(0,X.jsx)(t6,{ref:s,flexGrow:1,maxWidth:`90%`,placeholder:a,onSubmit:l,onKeyDown:u})]}):(0,X.jsxs)(Q,{flexDirection:`row`,children:[(0,X.jsx)($,{color:n?`cyan`:void 0,children:n?`❯ `:` `}),(0,X.jsxs)($,{color:n?void 0:`brightblack`,children:[`${t+1}. ${e.label}`,e.hint&&!e.rules&&(0,X.jsxs)($,{dimColor:!0,children:[` (`,e.hint,`)`]})]})]}));O7.displayName=`PermissionOptionItem`;const k7=(0,Z.memo)(({options:e,onSelect:t,inputPlaceholder:n=`and tell AbacusAI`,onModeSwitch:r,modeSwitchHint:i})=>{let[a,o]=(0,Z.useState)(0),[s,c]=(0,Z.useState)(!1),[l,u]=(0,Z.useState)(!1),d=(0,Z.useRef)(null),f=(0,Z.useRef)(null),p=(0,Z.useCallback)(e=>d.current?.getExpandedText(e)??e,[]),m=(0,Z.useCallback)(()=>{},[]),h=(0,Z.useRef)(``),g=(0,Z.useRef)(``),_=(0,Z.useMemo)(()=>e.filter(e=>e.value!==`input`),[e]),v=s,y=(0,Z.useRef)(a);y.current=a;let b=(0,Z.useRef)(_.length);b.current=_.length;let x=(0,Z.useRef)(v);x.current=v;let S=(0,Z.useRef)(l);S.current=l;let C=(0,Z.useRef)(t);C.current=t;let w=(0,Z.useRef)(r);w.current=r;let T=(0,Z.useRef)(_);T.current=_;let E=(0,Z.useCallback)(()=>{let e=T.current[y.current];if(e)if(x.current){let t=d.current?.text?.trim();if(t){let n=p(t),r=e.value===`accept`?`accept`:`reject`;C.current({decision:r,userMessage:n,rules:e.rules}),m()}}else e.value!==`input`&&C.current({decision:e.value,rules:e.rules})},[p,m]),D=(0,Z.useRef)(E);D.current=E;let O=(0,Z.useCallback)(e=>{if(e.trim()){let t=T.current[y.current],n=p(e.trim()),r=t?.value===`accept`?`accept`:`reject`;C.current({decision:r,userMessage:n,rules:t?.rules}),m()}},[p,m]),k=(0,Z.useCallback)(e=>{if(e.key.upArrow||e.key.downArrow){let t=T.current[y.current],n=d.current?.text||``;t?.value===`accept`?h.current=n:t?.value===`reject`&&(g.current=n),c(!1),e.key.upArrow?o(e=>Math.max(0,e-1)):o(e=>Math.min(b.current-1,e+1)),e.preventDefault();return}if(e.key.tab){let t=T.current[y.current];t?.value===`accept`?h.current=``:t?.value===`reject`&&(g.current=``),m(),c(!1),e.preventDefault();return}if(e.key.escape){m(),c(!1),C.current({decision:`reject`}),e.preventDefault();return}},[m]),A=(0,Z.useCallback)(e=>{let t=e.split(`,`).map(e=>e.trim()).filter(Boolean);t.length!==0&&T.current[y.current]&&(t.length===1?C.current({decision:`allowAlwaysWithRule`,rules:t}):C.current({decision:`allowAlwaysWithRules`,rules:t}),u(!1))},[]),j=(0,Z.useCallback)(e=>{if(e.key.escape){u(!1),e.preventDefault();return}},[]);bZ((0,Z.useCallback)((e,t)=>{if(!x.current&&!S.current){if(t.upArrow){o(e=>Math.max(0,e-1));return}if(t.downArrow){o(e=>Math.min(b.current-1,e+1));return}if(t.escape){C.current({decision:`reject`});return}if(t.tab&&t.shift){if(w.current){w.current();return}let e=T.current.findIndex(e=>e.value===`allowAlways`);e!==-1&&(o(e),setTimeout(()=>{C.current({decision:`allowAlways`})},0));return}if(t.tab){let e=T.current[y.current];if(e&&(e.value===`accept`||e.value===`reject`)){c(!0);let t=e.value===`accept`?h.current:g.current;setTimeout(()=>{d.current&&t&&d.current.setText(t)},0)}return}if(e===`e`||e===`E`){let e=T.current[y.current];if(e?.rules?.length){u(!0),setTimeout(()=>{f.current?.setText(e.rules.join(`, `))},0);return}}if(t.return){D.current();return}}},[]),{isActive:!0}),(0,Z.useEffect)(()=>{let e=_[a];e&&(e.value!==`accept`&&e.value!==`reject`||(e.value===`accept`?h.current:g.current)&&!s&&c(!0))},[a,_,s]);let M=(0,Z.useRef)(!1);(0,Z.useEffect)(()=>{s&&(M.current=!0)},[s]),(0,Z.useEffect)(()=>{if(!s||!M.current)return;let e=_[a];if(!e)return;let t=e.value===`accept`?h.current:e.value===`reject`?g.current:``;t?setTimeout(()=>{d.current&&d.current.text===``&&d.current.setText(t),M.current=!1},0):M.current=!1},[s,a,_]);let N=_[a],P=s&&N,ee=e=>e.value===`accept`?`Yes, `:e.value===`reject`?`No, `:``,F=!s&&!l&&N&&(N.value===`accept`||N.value===`reject`),te=!s&&!l&&!!N?.rules?.length,I=_.some(e=>e.value===`allowAlways`||e.value===`allowAlwaysWithRule`);return(0,X.jsxs)(Q,{flexDirection:`column`,children:[_.map((e,t)=>{let r=t===a,i=P&&r,o=e.value===`accept`?h.current:e.value===`reject`?g.current:``;return(0,X.jsx)(O7,{option:!i&&o?{...e,label:`${e.label}, ${o}`}:e,index:t,isSelected:r,showAsInput:i,showAsEdit:l&&r,editBufferRef:f,onEditSubmit:A,onEditKeyDown:j,inputPrefix:ee(e),inputPlaceholder:n,inputBufferRef:d,onInputSubmit:O,onInputKeyDown:k},t)}),(0,X.jsx)(Q,{flexDirection:`row`,marginTop:1,gap:2,children:l?(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)($,{dimColor:!0,children:`enter confirm`}),(0,X.jsx)($,{dimColor:!0,children:`esc cancel`})]}):s?(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)($,{dimColor:!0,children:`enter submit`}),(0,X.jsx)($,{dimColor:!0,children:`tab discard note`}),(0,X.jsx)($,{dimColor:!0,children:`esc reject`})]}):(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)($,{dimColor:!0,children:`↑↓ navigate`}),(0,X.jsx)($,{dimColor:!0,children:`enter select`}),F&&(0,X.jsx)($,{dimColor:!0,children:`tab add note`}),te&&(0,X.jsx)($,{dimColor:!0,children:`e edit rule`}),i&&(0,X.jsxs)($,{dimColor:!0,children:[`shift+tab `,i]}),!i&&I&&(0,X.jsx)($,{dimColor:!0,children:`shift+tab don't ask again`}),(0,X.jsx)($,{dimColor:!0,children:`esc reject`})]})})]})});k7.displayName=`PermissionOptions`;function A7(e){return e.decision===`accept`&&e.userMessage?{type:`accept_with_message`,message:e.userMessage}:e.decision===`reject`&&e.userMessage?{type:`reject_with_message`,message:e.userMessage}:e.decision===`allowAlwaysWithRule`?e.rules?.length?{type:`allow_always_with_rule`,rule:e.rules[0]}:`accept`:e.decision===`allowAlwaysWithRules`?e.rules?.length?{type:`allow_always_with_rules`,rules:e.rules}:`accept`:e.decision}const j7=(0,Z.memo)(({filePath:e,originalContent:t,newContent:n,diffShownInEditor:r,onResolve:i})=>{let a=!t,{agentMode:o}=H0(),s=[{label:`Yes, apply changes`,value:`accept`},...o===xd.Normal?[{label:`Allow all edits during this session`,value:`allowAlways`}]:[],{label:`No, reject changes`,value:`reject`}],c=e=>{i(A7(e))};return r?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(d6,{title:`${a?`Create`:`Update`} file ${e}`,subtitle:`Opened changes in the editor`}),(0,X.jsx)(Q,{flexDirection:`column`,paddingLeft:1,children:(0,X.jsx)(k7,{options:s,onSelect:c,onModeSwitch:()=>i(`allowAlways`),modeSwitchHint:`auto-accept all edits`})})]}):(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(d6,{title:`${a?`Create`:`Update`} file ${e}`}),a?a2(e)?(0,X.jsx)(u2,{content:n,maxLinesPerCell:100}):(0,X.jsx)(k0,{filePath:e,content:n,maxLines:100}):a2(e)?(0,X.jsx)(c2,{filePath:e,originalContent:t,newContent:n}):(0,X.jsx)(Q0,{filePath:e,originalContent:t,newContent:n,paddingLeft:1}),(0,X.jsx)(Q,{borderStyle:u6,borderBottom:!0,borderTop:!1,borderLeft:!1,borderRight:!1}),(0,X.jsx)(Q,{flexDirection:`column`,paddingLeft:1,children:(0,X.jsx)(k7,{options:s,onSelect:c,onModeSwitch:()=>i(`allowAlways`),modeSwitchHint:`auto-accept all edits`})})]})});j7.displayName=`EditFilePermissionUI`;const M7=(0,Z.memo)(({filePath:e,originalContent:t,content:n,isNewFile:r,diffShownInEditor:i,onResolve:a})=>{let{agentMode:o}=H0(),s=[{label:`Yes, apply changes`,value:`accept`},...o===xd.Normal?[{label:`Allow all edits during this session`,value:`allowAlways`}]:[],{label:`No, reject changes`,value:`reject`}],c=e=>{a(A7(e))};return i?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(d6,{title:`${r?`Create`:`Update`} file ${e}`,subtitle:`Opened changes in the editor`}),(0,X.jsx)(Q,{flexDirection:`column`,paddingLeft:1,children:(0,X.jsx)(k7,{options:s,onSelect:c,onModeSwitch:()=>a(`allowAlways`),modeSwitchHint:`auto-accept all edits`})})]}):(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(d6,{title:`${r?`Create`:`Update`} file ${e}`}),r?a2(e)?(0,X.jsx)(u2,{content:n,maxLinesPerCell:100}):(0,X.jsx)(k0,{filePath:e,content:n,maxLines:100}):a2(e)?(0,X.jsx)(c2,{filePath:e,originalContent:t,newContent:n}):(0,X.jsx)(Q0,{filePath:e,originalContent:t,newContent:n,paddingLeft:1}),(0,X.jsx)(Q,{borderStyle:u6,borderBottom:!0,borderTop:!1,borderLeft:!1,borderRight:!1}),(0,X.jsx)(Q,{flexDirection:`column`,paddingLeft:1,children:(0,X.jsx)(k7,{options:s,onSelect:c,onModeSwitch:()=>a(`allowAlways`),modeSwitchHint:`auto-accept all edits`})})]})});M7.displayName=`WriteFilePermissionUI`;const N7=(0,Z.memo)(({description:e,url:t,displayName:n,onResolve:r})=>{let i=[{label:`Yes, allow action`,value:`accept`},{label:`Yes, and always allow ${n}`,value:`allowAlwaysWithRule`,rules:[n]},{label:`No, deny action`,value:`reject`}];return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(d6,{title:`Browser action: ${e}`}),(0,X.jsxs)(Q,{flexDirection:`column`,paddingLeft:1,paddingY:1,children:[(0,X.jsx)($,{children:e}),t&&(0,X.jsxs)($,{dimColor:!0,children:[`URL: `,t]})]}),(0,X.jsx)(Q,{borderStyle:u6,borderBottom:!0,borderTop:!1,borderLeft:!1,borderRight:!1}),(0,X.jsx)(Q,{flexDirection:`column`,paddingLeft:1,children:(0,X.jsx)(k7,{options:i,onSelect:e=>{r(A7(e))}})})]})});N7.displayName=`BrowserActionPermissionUI`;const P7=(0,Z.memo)(({command:e,background:t,unmatchedPatterns:n,onResolve:r})=>{let i=(0,Z.useMemo)(()=>S0(),[]),a=FF(e),o=(0,Z.useMemo)(()=>{let e=[{label:`Yes, run command`,value:`accept`}];if(n.length>1){e.push({label:`Yes, and always allow all: ${n.map(e=>`Bash(${e})`).join(`, `)}`,value:`allowAlwaysWithRules`,rules:n.map(e=>`Bash(${e})`)});for(let t of n)e.push({label:`Yes, and always allow Bash(${t})`,value:`allowAlwaysWithRule`,rules:[`Bash(${t})`]})}else n.length===1?e.push({label:`Yes, and always allow Bash(${n[0]})`,value:`allowAlwaysWithRule`,rules:[`Bash(${n[0]})`]}):e.push({label:`Yes, and always allow Bash(${a})`,value:`allowAlwaysWithRule`,rules:[`Bash(${a})`]});return e.push({label:`No, skip command`,value:`reject`}),e},[n,a]);return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(d6,{title:`Bash command`}),(0,X.jsxs)(Q,{flexDirection:`column`,paddingLeft:1,paddingY:1,children:[(0,X.jsx)($,{children:(0,b0.supportsLanguage)(`bash`)?(()=>{try{return(0,b0.highlight)(e,{language:`bash`,theme:i})}catch{return e}})():e}),t&&(0,X.jsx)(Q,{paddingTop:1,children:(0,X.jsx)($,{dimColor:!0,children:`(Running in background)`})})]}),(0,X.jsx)(Q,{borderStyle:u6,borderBottom:!0,borderTop:!1,borderLeft:!1,borderRight:!1}),(0,X.jsx)(Q,{flexDirection:`column`,paddingLeft:1,children:(0,X.jsx)(k7,{options:o,onSelect:e=>{r(A7(e))},inputPlaceholder:`Type here to tell AbacusAI what to do differently`,onModeSwitch:()=>r(`allowAlways`),modeSwitchHint:`allow all tools`})})]})});P7.displayName=`RunTerminalPermissionUI`;const F7=(0,Z.memo)(({title:e,description:t,toolName:n,onResolve:r})=>{let i=(0,Z.useMemo)(()=>S0(),[]),a=[{label:`Yes, allow`,value:`accept`},...n?[{label:`Yes, and always allow ${n}`,value:`allowAlwaysWithRule`,rules:[n]}]:[],{label:`No, deny`,value:`reject`}];return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(d6,{title:e}),(0,X.jsx)(Q,{flexDirection:`column`,paddingLeft:1,paddingY:1,children:(0,X.jsx)($,{children:(0,b0.supportsLanguage)(`json`)?(()=>{try{return(0,b0.highlight)(t,{language:`json`,theme:i})}catch{return t}})():t})}),(0,X.jsx)(Q,{borderStyle:u6,borderBottom:!0,borderTop:!1,borderLeft:!1,borderRight:!1}),(0,X.jsx)(Q,{flexDirection:`column`,paddingLeft:1,children:(0,X.jsx)(k7,{options:a,onSelect:e=>{r(A7(e))}})})]})});F7.displayName=`GenericPermissionUI`;const I7=(0,Z.memo)(({planFilePath:e,planContent:t,onResolve:n})=>(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(d6,{title:`Ready to code? Implement plan: ${e.length>60?`…${e.slice(-60)}`:e}`}),t&&(0,X.jsxs)(Q,{flexDirection:`column`,paddingLeft:1,paddingY:1,children:[(0,X.jsx)($,{dimColor:!0,children:`Here is Abacus's plan:`}),(0,X.jsx)(l7,{children:t})]}),(0,X.jsx)(Q,{borderStyle:u6,borderBottom:!0,borderTop:!1,borderLeft:!1,borderRight:!1}),(0,X.jsx)(Q,{flexDirection:`column`,paddingLeft:1,children:(0,X.jsx)(k7,{options:[{label:`Yes, implement the plan (approve each edit)`,value:`accept`},{label:`Yes, implement the plan (auto-accept all edits)`,value:`allowAlways`,hint:`shift+tab`},{label:`Yes, implement the plan (full permissions granted)`,value:`allowYolo`},{label:`No, keep planning`,value:`reject`}],onSelect:e=>{n(A7(e))},inputPlaceholder:`Add instructions for the implementation`})})]}));I7.displayName=`ExitPlanModePermissionUI`;const L7=(0,Z.memo)(({filePath:e,deducedDirectory:t,onResolve:n})=>{let r=[{label:`Yes, allow read`,value:`accept`},{label:`Yes, and always allow ${t}`,value:`allowAlways`},{label:`No, deny read`,value:`reject`}];return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(d6,{title:`Read file outside workspace`}),(0,X.jsxs)(Q,{flexDirection:`column`,paddingLeft:1,paddingY:1,children:[(0,X.jsx)($,{children:e}),(0,X.jsxs)($,{dimColor:!0,children:[`Directory: `,t]})]}),(0,X.jsx)(Q,{borderStyle:u6,borderBottom:!0,borderTop:!1,borderLeft:!1,borderRight:!1}),(0,X.jsx)(Q,{flexDirection:`column`,paddingLeft:1,children:(0,X.jsx)(k7,{options:r,onSelect:e=>{n(A7(e))}})})]})});L7.displayName=`ReadOutsideDirectoryPermissionUI`;const R7=(0,Z.memo)(({filePath:e,deducedDirectory:t,isNewFile:n,onResolve:r})=>{let i=[{label:`Yes, allow write`,value:`accept`},{label:`Yes, and always allow ${t}`,value:`allowAlways`},{label:`No, deny write`,value:`reject`}];return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(d6,{title:`${n?`Create`:`Write`} file outside workspace`}),(0,X.jsxs)(Q,{flexDirection:`column`,paddingLeft:1,paddingY:1,children:[(0,X.jsx)($,{children:e}),(0,X.jsxs)($,{dimColor:!0,children:[`Directory: `,t]})]}),(0,X.jsx)(Q,{borderStyle:u6,borderBottom:!0,borderTop:!1,borderLeft:!1,borderRight:!1}),(0,X.jsx)(Q,{flexDirection:`column`,paddingLeft:1,children:(0,X.jsx)(k7,{options:i,onSelect:e=>{r(A7(e))}})})]})});R7.displayName=`WriteOutsideDirectoryPermissionUI`;const z7=(0,Z.memo)(({filePath:e,deducedDirectory:t,onResolve:n})=>{let r=[{label:`Yes, allow edit`,value:`accept`},{label:`Yes, and always allow ${t}`,value:`allowAlways`},{label:`No, deny edit`,value:`reject`}];return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(d6,{title:`Edit file outside workspace`}),(0,X.jsxs)(Q,{flexDirection:`column`,paddingLeft:1,paddingY:1,children:[(0,X.jsx)($,{children:e}),(0,X.jsxs)($,{dimColor:!0,children:[`Directory: `,t]})]}),(0,X.jsx)(Q,{borderStyle:u6,borderBottom:!0,borderTop:!1,borderLeft:!1,borderRight:!1}),(0,X.jsx)(Q,{flexDirection:`column`,paddingLeft:1,children:(0,X.jsx)(k7,{options:r,onSelect:e=>{n(A7(e))}})})]})});z7.displayName=`EditOutsideDirectoryPermissionUI`;const B7=(0,Z.memo)(({filePath:e,deducedDirectory:t,onResolve:n})=>{let r=[{label:`Yes, allow notebook edit`,value:`accept`},{label:`Yes, and always allow ${t}`,value:`allowAlways`},{label:`No, deny notebook edit`,value:`reject`}];return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(d6,{title:`Edit notebook outside workspace`}),(0,X.jsxs)(Q,{flexDirection:`column`,paddingLeft:1,paddingY:1,children:[(0,X.jsx)($,{children:e}),(0,X.jsxs)($,{dimColor:!0,children:[`Directory: `,t]})]}),(0,X.jsx)(Q,{borderStyle:u6,borderBottom:!0,borderTop:!1,borderLeft:!1,borderRight:!1}),(0,X.jsx)(Q,{flexDirection:`column`,paddingLeft:1,children:(0,X.jsx)(k7,{options:r,onSelect:e=>{n(A7(e))}})})]})});B7.displayName=`NotebookEditOutsideDirectoryPermissionUI`;const V7=(0,Z.memo)(({notebookPath:e,cellId:t,editMode:n,cellType:r,originalContent:i,newContent:a,onResolve:o})=>{let s=n??`replace`,c=``;c=s===`delete`?`Delete cell${t?` ${t}`:``}`:s===`insert`?`Insert new cell${t?` after ${t}`:` at beginning`} (${r??`code`})`:`Replace cell contents for cell ${t??`unknown`}`;let{agentMode:l}=H0(),u=[{label:`Yes, apply changes`,value:`accept`},...l===xd.Normal?[{label:`Allow all edits during this session`,value:`allowAlways`}]:[],{label:`No, reject changes`,value:`reject`}];return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(d6,{title:`Edit notebook`}),(0,X.jsxs)(Q,{flexDirection:`column`,paddingLeft:1,children:[(0,X.jsx)($,{dimColor:!0,children:e}),(0,X.jsx)($,{dimColor:!0,children:c})]}),s===`delete`?(0,X.jsx)(Q,{flexDirection:`column`,paddingLeft:1,paddingY:1,children:(0,X.jsx)($,{color:`red`,children:`Cell will be deleted`})}):s===`insert`||!i?(0,X.jsx)(Q0,{filePath:i2(r===`markdown`?`markdown`:`python`),originalContent:``,newContent:a,showHeader:!1,paddingLeft:1}):(0,X.jsx)(s2,{cellIndex:0,cellType:r??`code`,cellId:t,language:r===`markdown`?`markdown`:`python`,originalSource:i,newSource:a,status:`modified`}),(0,X.jsx)(Q,{borderStyle:u6,borderBottom:!0,borderTop:!1,borderLeft:!1,borderRight:!1}),(0,X.jsx)(Q,{flexDirection:`column`,paddingLeft:1,children:(0,X.jsx)(k7,{options:u,onSelect:e=>{o(A7(e))},onModeSwitch:()=>o(`allowAlways`),modeSwitchHint:`auto-accept all edits`})})]})});V7.displayName=`NotebookEditPermissionUI`;const H7=(0,Z.memo)(({pendingTool:e})=>{let{request:t,resolve:n}=e;switch(t.type){case`edit_file`:return(0,X.jsx)(j7,{filePath:t.filePath,originalContent:t.originalContent,newContent:t.newContent,diffShownInEditor:t.diffShownInEditor,onResolve:n});case`write_file`:return(0,X.jsx)(M7,{filePath:t.filePath,originalContent:t.originalContent,content:t.content,isNewFile:t.isNewFile,diffShownInEditor:t.diffShownInEditor,onResolve:n});case`run_terminal`:return(0,X.jsx)(P7,{command:t.command,background:t.background,unmatchedPatterns:t.unmatchedPatterns,onResolve:n});case`browser_action`:return(0,X.jsx)(N7,{description:t.description,url:t.url,displayName:t.displayName,onResolve:n});case`generic`:return(0,X.jsx)(F7,{title:`Tool: ${t.toolName}`,description:t.inputSummary,toolName:t.toolName,onResolve:n});case`read_outside_directory`:return(0,X.jsx)(L7,{filePath:t.filePath,deducedDirectory:t.deducedDirectory,onResolve:n});case`write_outside_directory`:return(0,X.jsx)(R7,{filePath:t.filePath,deducedDirectory:t.deducedDirectory,isNewFile:t.isNewFile,onResolve:n});case`edit_outside_directory`:return(0,X.jsx)(z7,{filePath:t.filePath,deducedDirectory:t.deducedDirectory,onResolve:n});case`notebook_edit_outside_directory`:return(0,X.jsx)(B7,{filePath:t.filePath,deducedDirectory:t.deducedDirectory,onResolve:n});case`exit_plan_mode`:return(0,X.jsx)(I7,{planFilePath:t.planFilePath,planContent:t.planContent,onResolve:n});case`ask_user_question`:return(0,X.jsx)(D7,{questions:t.questions,onResolve:n});case`notebook_edit`:return(0,X.jsx)(V7,{notebookPath:t.notebookPath,cellId:t.cellId,editMode:t.editMode,cellType:t.cellType,originalContent:t.originalContent,newContent:t.newContent,onResolve:n});default:return null}});H7.displayName=`ToolPermissionUI`;function wqe(e){let t=(0,Z.useRef)(!1),n=(0,Z.useRef)(e);(0,Z.useEffect)(()=>{n.current=e},[e]),(0,Z.useEffect)(()=>{let e=()=>{t.current||(t.current=!0,n.current())};return process.on(`exit`,e),process.on(`SIGINT`,e),process.on(`SIGTERM`,e),()=>{e(),process.off(`exit`,e),process.off(`SIGINT`,e),process.off(`SIGTERM`,e)}},[])}const U7=(0,Z.createContext)(null),W7=()=>{let e=(0,Z.use)(U7);if(!e)throw Error(`${W7.name} must be used within a ${G7.name}`);return e};function G7({children:e}){let t=(0,Z.useCallback)(e=>{let t=e.split(``).filter(e=>{let t=e.codePointAt(0);return!(t<=31||t===127)}).join(``);process.stdout.write(TZ(t))},[]);wqe(()=>{process.stdout.write(TZ(``))});let n=(0,Z.useMemo)(()=>({setTitle:t}),[t]);return(0,X.jsx)(U7.Provider,{value:n,children:e})}const K7=2e3;function q7(e,t,n){return e===Sd.ExecutingTool?`tool-executing`:e===Sd.Submitted||e===Sd.Streaming?`streaming`:e===Sd.WaitingForToolPermission&&t?`permission-ui`:n()?`idle-with-text`:`idle-empty`}function Tqe(e){let{agentStatus:t,hasPendingPermission:n,isExpandedView:r,composerHasText:i,hasQueuedMessages:a,stopAgent:o,rejectPermission:s,saveAndClearComposer:c,clearComposer:l,dequeueAllToComposer:u,clearQueue:d,exitApp:f}=e,[p,m]=(0,Z.useState)(!1),[h,g]=(0,Z.useState)(null),_=(0,Z.useRef)(null),v=(0,Z.useRef)(null),y=(0,Z.useCallback)(()=>{m(!1),_.current&&=(clearTimeout(_.current),null)},[]),b=(0,Z.useCallback)(()=>{g(null),v.current&&=(clearTimeout(v.current),null)},[]),x=(0,Z.useCallback)(()=>{y(),b()},[y,b]),S=q7(t,n,i),C=(0,Z.useRef)(S);return(0,Z.useEffect)(()=>{let e=C.current;C.current=S,e!==S&&x()},[S,x]),bZ((0,Z.useEffectEvent)((e,S)=>{if(S.ctrl&&e===`z`){process.platform!==`win32`&&process.kill(process.pid,`SIGTSTP`);return}let C=S.escape,w=S.ctrl&&e===`c`,T=S.ctrl&&e===`d`;if(!C&&!w&&!T||C&&r)return;let E=q7(t,n,i);if(E===`tool-executing`||E===`streaming`){x(),o();return}if(E===`permission-ui`){x(),s();return}if(E===`idle-with-text`){if(C){p?(l(),x()):(b(),m(!0),_.current=setTimeout(()=>{m(!1),_.current=null},K7));return}let e=w?`c`:`d`;if(h===e){x(),f();return}if(h!==null){b(),g(e),v.current=setTimeout(()=>{g(null),v.current=null},K7);return}y(),c(),a()&&d(),g(e),v.current=setTimeout(()=>{g(null),v.current=null},K7);return}if(E===`idle-empty`){if(C){a()&&u();return}let e=w?`c`:`d`;if(h===e){x(),f();return}if(h!==null){b(),g(e),v.current=setTimeout(()=>{g(null),v.current=null},K7);return}a()&&d(),g(e),v.current=setTimeout(()=>{g(null),v.current=null},K7)}}),{isActive:!0}),(0,Z.useEffect)(()=>()=>{_.current&&clearTimeout(_.current),v.current&&clearTimeout(v.current)},[]),{escClear:p,exitKey:h}}const Eqe={todos:[],completed:0,inProgress:0,pending:0,total:0};function Dqe(e){let t=e.toolUseRequest;if(!t)return null;let n;if(Array.isArray(t)){for(let e=t.length-1;e>=0;e--){let r=t[e];if(r&&r.name===`todo_write`){n=r;break}}if(!n)return null}else if(n=t,n.name!==`todo_write`)return null;let r=n.input;if(!r)return null;let i=r.todos;if(typeof i==`string`)try{i=JSON.parse(i)}catch{return null}return Array.isArray(i)?i.filter(e=>typeof e==`object`&&!!e&&typeof e.content==`string`&&typeof e.status==`string`).map((e,t)=>({id:e.id??`todo-${t}`,content:e.content,status:e.status})):null}function Oqe(e){return(0,Z.useMemo)(()=>{for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.type!==`code_llm_tool_call`&&n.type!==`code_llm_agent_tool_request`)continue;let r=Dqe(n);if(!r)continue;let i=r.filter(e=>e.status!==`cancelled`);return{todos:i,completed:i.filter(e=>e.status===`completed`).length,inProgress:i.filter(e=>e.status===`in_progress`).length,pending:i.filter(e=>e.status===`pending`).length,total:i.length}}return Eqe},[e])}var kqe=G(((e,t)=>{let n={to(e,t){return t?`[${t+1};${e+1}H`:`[${e+1}G`},move(e,t){let n=``;return e<0?n+=`[${-e}D`:e>0&&(n+=`[${e}C`),t<0?n+=`[${-t}A`:t>0&&(n+=`[${t}B`),n},up:(e=1)=>`[${e}A`,down:(e=1)=>`[${e}B`,forward:(e=1)=>`[${e}C`,backward:(e=1)=>`[${e}D`,nextLine:(e=1)=>`\x1B[E`.repeat(e),prevLine:(e=1)=>`\x1B[F`.repeat(e),left:`\x1B[G`,hide:`\x1B[?25l`,show:`\x1B[?25h`,save:`\x1B7`,restore:`\x1B8`};t.exports={cursor:n,scroll:{up:(e=1)=>`\x1B[S`.repeat(e),down:(e=1)=>`\x1B[T`.repeat(e)},erase:{screen:`\x1B[2J`,up:(e=1)=>`\x1B[1J`.repeat(e),down:(e=1)=>`\x1B[J`.repeat(e),line:`\x1B[2K`,lineEnd:`\x1B[K`,lineStart:`\x1B[1K`,lines(e){let t=``;for(let r=0;r<e;r++)t+=this.line+(r<e-1?n.up():``);return e&&(t+=n.left),t}},beep:`\x07`}})),Aqe=G(((e,t)=>{let n=process||{},r=n.argv||[],i=n.env||{},a=!(i.NO_COLOR||r.includes(`--no-color`))&&(!!i.FORCE_COLOR||r.includes(`--color`)||n.platform===`win32`||(n.stdout||{}).isTTY&&i.TERM!==`dumb`||!!i.CI),o=(e,t,n=e)=>r=>{let i=``+r,a=i.indexOf(t,e.length);return~a?e+s(i,t,n,a)+t:e+i+t},s=(e,t,n,r)=>{let i=``,a=0;do i+=e.substring(a,r)+n,a=r+t.length,r=e.indexOf(t,a);while(~r);return i+e.substring(a)},c=(e=a)=>{let t=e?o:()=>String;return{isColorSupported:e,reset:t(`\x1B[0m`,`\x1B[0m`),bold:t(`\x1B[1m`,`\x1B[22m`,`\x1B[22m\x1B[1m`),dim:t(`\x1B[2m`,`\x1B[22m`,`\x1B[22m\x1B[2m`),italic:t(`\x1B[3m`,`\x1B[23m`),underline:t(`\x1B[4m`,`\x1B[24m`),inverse:t(`\x1B[7m`,`\x1B[27m`),hidden:t(`\x1B[8m`,`\x1B[28m`),strikethrough:t(`\x1B[9m`,`\x1B[29m`),black:t(`\x1B[30m`,`\x1B[39m`),red:t(`\x1B[31m`,`\x1B[39m`),green:t(`\x1B[32m`,`\x1B[39m`),yellow:t(`\x1B[33m`,`\x1B[39m`),blue:t(`\x1B[34m`,`\x1B[39m`),magenta:t(`\x1B[35m`,`\x1B[39m`),cyan:t(`\x1B[36m`,`\x1B[39m`),white:t(`\x1B[37m`,`\x1B[39m`),gray:t(`\x1B[90m`,`\x1B[39m`),bgBlack:t(`\x1B[40m`,`\x1B[49m`),bgRed:t(`\x1B[41m`,`\x1B[49m`),bgGreen:t(`\x1B[42m`,`\x1B[49m`),bgYellow:t(`\x1B[43m`,`\x1B[49m`),bgBlue:t(`\x1B[44m`,`\x1B[49m`),bgMagenta:t(`\x1B[45m`,`\x1B[49m`),bgCyan:t(`\x1B[46m`,`\x1B[49m`),bgWhite:t(`\x1B[47m`,`\x1B[49m`),blackBright:t(`\x1B[90m`,`\x1B[39m`),redBright:t(`\x1B[91m`,`\x1B[39m`),greenBright:t(`\x1B[92m`,`\x1B[39m`),yellowBright:t(`\x1B[93m`,`\x1B[39m`),blueBright:t(`\x1B[94m`,`\x1B[39m`),magentaBright:t(`\x1B[95m`,`\x1B[39m`),cyanBright:t(`\x1B[96m`,`\x1B[39m`),whiteBright:t(`\x1B[97m`,`\x1B[39m`),bgBlackBright:t(`\x1B[100m`,`\x1B[49m`),bgRedBright:t(`\x1B[101m`,`\x1B[49m`),bgGreenBright:t(`\x1B[102m`,`\x1B[49m`),bgYellowBright:t(`\x1B[103m`,`\x1B[49m`),bgBlueBright:t(`\x1B[104m`,`\x1B[49m`),bgMagentaBright:t(`\x1B[105m`,`\x1B[49m`),bgCyanBright:t(`\x1B[106m`,`\x1B[49m`),bgWhiteBright:t(`\x1B[107m`,`\x1B[49m`)}};t.exports=c(),t.exports.createColors=c})),J7=kqe(),Y7=Qe(Aqe(),1);function jqe({onlyFirst:e=!1}={}){let t=[`[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?(?:\\u0007|\\u001B\\u005C|\\u009C))`,`(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]))`].join(`|`);return new RegExp(t,e?void 0:`g`)}const Mqe=jqe();function X7(e){if(typeof e!=`string`)throw TypeError(`Expected a \`string\`, got \`${typeof e}\``);return e.replace(Mqe,``)}function Z7(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,`default`)?e.default:e}var Q7={exports:{}};(function(e){var t={};e.exports=t,t.eastAsianWidth=function(e){var t=e.charCodeAt(0),n=e.length==2?e.charCodeAt(1):0,r=t;return 55296<=t&&t<=56319&&56320<=n&&n<=57343&&(t&=1023,n&=1023,r=t<<10|n,r+=65536),r==12288||65281<=r&&r<=65376||65504<=r&&r<=65510?`F`:r==8361||65377<=r&&r<=65470||65474<=r&&r<=65479||65482<=r&&r<=65487||65490<=r&&r<=65495||65498<=r&&r<=65500||65512<=r&&r<=65518?`H`:4352<=r&&r<=4447||4515<=r&&r<=4519||4602<=r&&r<=4607||9001<=r&&r<=9002||11904<=r&&r<=11929||11931<=r&&r<=12019||12032<=r&&r<=12245||12272<=r&&r<=12283||12289<=r&&r<=12350||12353<=r&&r<=12438||12441<=r&&r<=12543||12549<=r&&r<=12589||12593<=r&&r<=12686||12688<=r&&r<=12730||12736<=r&&r<=12771||12784<=r&&r<=12830||12832<=r&&r<=12871||12880<=r&&r<=13054||13056<=r&&r<=19903||19968<=r&&r<=42124||42128<=r&&r<=42182||43360<=r&&r<=43388||44032<=r&&r<=55203||55216<=r&&r<=55238||55243<=r&&r<=55291||63744<=r&&r<=64255||65040<=r&&r<=65049||65072<=r&&r<=65106||65108<=r&&r<=65126||65128<=r&&r<=65131||110592<=r&&r<=110593||127488<=r&&r<=127490||127504<=r&&r<=127546||127552<=r&&r<=127560||127568<=r&&r<=127569||131072<=r&&r<=194367||177984<=r&&r<=196605||196608<=r&&r<=262141?`W`:32<=r&&r<=126||162<=r&&r<=163||165<=r&&r<=166||r==172||r==175||10214<=r&&r<=10221||10629<=r&&r<=10630?`Na`:r==161||r==164||167<=r&&r<=168||r==170||173<=r&&r<=174||176<=r&&r<=180||182<=r&&r<=186||188<=r&&r<=191||r==198||r==208||215<=r&&r<=216||222<=r&&r<=225||r==230||232<=r&&r<=234||236<=r&&r<=237||r==240||242<=r&&r<=243||247<=r&&r<=250||r==252||r==254||r==257||r==273||r==275||r==283||294<=r&&r<=295||r==299||305<=r&&r<=307||r==312||319<=r&&r<=322||r==324||328<=r&&r<=331||r==333||338<=r&&r<=339||358<=r&&r<=359||r==363||r==462||r==464||r==466||r==468||r==470||r==472||r==474||r==476||r==593||r==609||r==708||r==711||713<=r&&r<=715||r==717||r==720||728<=r&&r<=731||r==733||r==735||768<=r&&r<=879||913<=r&&r<=929||931<=r&&r<=937||945<=r&&r<=961||963<=r&&r<=969||r==1025||1040<=r&&r<=1103||r==1105||r==8208||8211<=r&&r<=8214||8216<=r&&r<=8217||8220<=r&&r<=8221||8224<=r&&r<=8226||8228<=r&&r<=8231||r==8240||8242<=r&&r<=8243||r==8245||r==8251||r==8254||r==8308||r==8319||8321<=r&&r<=8324||r==8364||r==8451||r==8453||r==8457||r==8467||r==8470||8481<=r&&r<=8482||r==8486||r==8491||8531<=r&&r<=8532||8539<=r&&r<=8542||8544<=r&&r<=8555||8560<=r&&r<=8569||r==8585||8592<=r&&r<=8601||8632<=r&&r<=8633||r==8658||r==8660||r==8679||r==8704||8706<=r&&r<=8707||8711<=r&&r<=8712||r==8715||r==8719||r==8721||r==8725||r==8730||8733<=r&&r<=8736||r==8739||r==8741||8743<=r&&r<=8748||r==8750||8756<=r&&r<=8759||8764<=r&&r<=8765||r==8776||r==8780||r==8786||8800<=r&&r<=8801||8804<=r&&r<=8807||8810<=r&&r<=8811||8814<=r&&r<=8815||8834<=r&&r<=8835||8838<=r&&r<=8839||r==8853||r==8857||r==8869||r==8895||r==8978||9312<=r&&r<=9449||9451<=r&&r<=9547||9552<=r&&r<=9587||9600<=r&&r<=9615||9618<=r&&r<=9621||9632<=r&&r<=9633||9635<=r&&r<=9641||9650<=r&&r<=9651||9654<=r&&r<=9655||9660<=r&&r<=9661||9664<=r&&r<=9665||9670<=r&&r<=9672||r==9675||9678<=r&&r<=9681||9698<=r&&r<=9701||r==9711||9733<=r&&r<=9734||r==9737||9742<=r&&r<=9743||9748<=r&&r<=9749||r==9756||r==9758||r==9792||r==9794||9824<=r&&r<=9825||9827<=r&&r<=9829||9831<=r&&r<=9834||9836<=r&&r<=9837||r==9839||9886<=r&&r<=9887||9918<=r&&r<=9919||9924<=r&&r<=9933||9935<=r&&r<=9953||r==9955||9960<=r&&r<=9983||r==10045||r==10071||10102<=r&&r<=10111||11093<=r&&r<=11097||12872<=r&&r<=12879||57344<=r&&r<=63743||65024<=r&&r<=65039||r==65533||127232<=r&&r<=127242||127248<=r&&r<=127277||127280<=r&&r<=127337||127344<=r&&r<=127386||917760<=r&&r<=917999||983040<=r&&r<=1048573||1048576<=r&&r<=1114109?`A`:`N`},t.characterLength=function(e){var t=this.eastAsianWidth(e);return t==`F`||t==`W`||t==`A`?2:1};function n(e){return e.match(/[\uD800-\uDBFF][\uDC00-\uDFFF]|[^\uD800-\uDFFF]/g)||[]}t.length=function(e){for(var t=n(e),r=0,i=0;i<t.length;i++)r+=this.characterLength(t[i]);return r},t.slice=function(e,r,i){textLen=t.length(e),r||=0,i||=1,r<0&&(r=textLen+r),i<0&&(i=textLen+i);for(var a=``,o=0,s=n(e),c=0;c<s.length;c++){var l=s[c],u=t.length(l);if(o>=r-(u==2?1:0))if(o+u<=i)a+=l;else break;o+=u}return a}})(Q7);var Nqe=Q7.exports;const Pqe=Z7(Nqe),Fqe=Z7(function(){return/\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67)\uDB40\uDC7F|(?:\uD83E\uDDD1\uD83C\uDFFF\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFC-\uDFFF])|\uD83D\uDC68(?:\uD83C\uDFFB(?:\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF]))|\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|[\u2695\u2696\u2708]\uFE0F|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))?|(?:\uD83C[\uDFFC-\uDFFF])\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF]))|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])\uFE0F|\u200D(?:(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D[\uDC66\uDC67])|\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC)?|(?:\uD83D\uDC69(?:\uD83C\uDFFB\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|(?:\uD83C[\uDFFC-\uDFFF])\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69]))|\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC69(?:\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83E\uDDD1(?:\u200D(?:\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\uD83D\uDE36\u200D\uD83C\uDF2B|\uD83C\uDFF3\uFE0F\u200D\u26A7|\uD83D\uDC3B\u200D\u2744|(?:(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\uD83C\uDFF4\u200D\u2620|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])\u200D[\u2640\u2642]|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u2600-\u2604\u260E\u2611\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26B0\u26B1\u26C8\u26CF\u26D1\u26D3\u26E9\u26F0\u26F1\u26F4\u26F7\u26F8\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u3030\u303D\u3297\u3299]|\uD83C[\uDD70\uDD71\uDD7E\uDD7F\uDE02\uDE37\uDF21\uDF24-\uDF2C\uDF36\uDF7D\uDF96\uDF97\uDF99-\uDF9B\uDF9E\uDF9F\uDFCD\uDFCE\uDFD4-\uDFDF\uDFF5\uDFF7]|\uD83D[\uDC3F\uDCFD\uDD49\uDD4A\uDD6F\uDD70\uDD73\uDD76-\uDD79\uDD87\uDD8A-\uDD8D\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA\uDECB\uDECD-\uDECF\uDEE0-\uDEE5\uDEE9\uDEF0\uDEF3])\uFE0F|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDE35\u200D\uD83D\uDCAB|\uD83D\uDE2E\u200D\uD83D\uDCA8|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83E\uDDD1(?:\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC|\uD83C\uDFFB)?|\uD83D\uDC69(?:\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC|\uD83C\uDFFB)?|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF6\uD83C\uDDE6|\uD83C\uDDF4\uD83C\uDDF2|\uD83D\uDC08\u200D\u2B1B|\u2764\uFE0F\u200D(?:\uD83D\uDD25|\uD83E\uDE79)|\uD83D\uDC41\uFE0F|\uD83C\uDFF3\uFE0F|\uD83C\uDDFF(?:\uD83C[\uDDE6\uDDF2\uDDFC])|\uD83C\uDDFE(?:\uD83C[\uDDEA\uDDF9])|\uD83C\uDDFC(?:\uD83C[\uDDEB\uDDF8])|\uD83C\uDDFB(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA])|\uD83C\uDDFA(?:\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF])|\uD83C\uDDF9(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF])|\uD83C\uDDF8(?:\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF])|\uD83C\uDDF7(?:\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC])|\uD83C\uDDF5(?:\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE])|\uD83C\uDDF3(?:\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF])|\uD83C\uDDF2(?:\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF])|\uD83C\uDDF1(?:\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE])|\uD83C\uDDF0(?:\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF])|\uD83C\uDDEF(?:\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5])|\uD83C\uDDEE(?:\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9])|\uD83C\uDDED(?:\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA])|\uD83C\uDDEC(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE])|\uD83C\uDDEB(?:\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7])|\uD83C\uDDEA(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA])|\uD83C\uDDE9(?:\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF])|\uD83C\uDDE8(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF])|\uD83C\uDDE7(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF])|\uD83C\uDDE6(?:\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF])|[#\*0-9]\uFE0F\u20E3|\u2764\uFE0F|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])|\uD83C\uDFF4|(?:[\u270A\u270B]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270C\u270D]|\uD83D[\uDD74\uDD90])(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])|[\u270A\u270B]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC08\uDC15\uDC3B\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE2E\uDE35\uDE36\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5]|\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD]|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF]|[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF84\uDF86-\uDF93\uDFA0-\uDFC1\uDFC5\uDFC6\uDFC8\uDFC9\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC07\uDC09-\uDC14\uDC16-\uDC3A\uDC3C-\uDC3E\uDC40\uDC44\uDC45\uDC51-\uDC65\uDC6A\uDC79-\uDC7B\uDC7D-\uDC80\uDC84\uDC88-\uDC8E\uDC90\uDC92-\uDCA9\uDCAB-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDDA4\uDDFB-\uDE2D\uDE2F-\uDE34\uDE37-\uDE44\uDE48-\uDE4A\uDE80-\uDEA2\uDEA4-\uDEB3\uDEB7-\uDEBF\uDEC1-\uDEC5\uDED0-\uDED2\uDED5-\uDED7\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0D\uDD0E\uDD10-\uDD17\uDD1D\uDD20-\uDD25\uDD27-\uDD2F\uDD3A\uDD3F-\uDD45\uDD47-\uDD76\uDD78\uDD7A-\uDDB4\uDDB7\uDDBA\uDDBC-\uDDCB\uDDD0\uDDE0-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6]|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5-\uDED7\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0C-\uDD3A\uDD3C-\uDD45\uDD47-\uDD78\uDD7A-\uDDCB\uDDCD-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26A7\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5-\uDED7\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0C-\uDD3A\uDD3C-\uDD45\uDD47-\uDD78\uDD7A-\uDDCB\uDDCD-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6])\uFE0F|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDC8F\uDC91\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDD77\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD])/g});function $7(e,t={}){if(typeof e!=`string`||e.length===0||(t={ambiguousIsNarrow:!0,...t},e=X7(e),e.length===0))return 0;e=e.replace(Fqe(),` `);let n=t.ambiguousIsNarrow?1:2,r=0;for(let t of e){let e=t.codePointAt(0);if(!(e<=31||e>=127&&e<=159||e>=768&&e<=879))switch(Pqe.eastAsianWidth(t)){case`F`:case`W`:r+=2;break;case`A`:r+=n;break;default:r+=1}}return r}const e9=(e=0)=>t=>`\x1B[${t+e}m`,t9=(e=0)=>t=>`\x1B[${38+e};5;${t}m`,n9=(e=0)=>(t,n,r)=>`\x1B[${38+e};2;${t};${n};${r}m`,r9={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}};Object.keys(r9.modifier);const Iqe=Object.keys(r9.color),Lqe=Object.keys(r9.bgColor);[...Iqe,...Lqe];function Rqe(){let e=new Map;for(let[t,n]of Object.entries(r9)){for(let[t,r]of Object.entries(n))r9[t]={open:`\x1B[${r[0]}m`,close:`\x1B[${r[1]}m`},n[t]=r9[t],e.set(r[0],r[1]);Object.defineProperty(r9,t,{value:n,enumerable:!1})}return Object.defineProperty(r9,`codes`,{value:e,enumerable:!1}),r9.color.close=`\x1B[39m`,r9.bgColor.close=`\x1B[49m`,r9.color.ansi=e9(),r9.color.ansi256=t9(),r9.color.ansi16m=n9(),r9.bgColor.ansi=e9(10),r9.bgColor.ansi256=t9(10),r9.bgColor.ansi16m=n9(10),Object.defineProperties(r9,{rgbToAnsi256:{value:(e,t,n)=>e===t&&t===n?e<8?16:e>248?231:Math.round((e-8)/247*24)+232:16+36*Math.round(e/255*5)+6*Math.round(t/255*5)+Math.round(n/255*5),enumerable:!1},hexToRgb:{value:e=>{let t=/[a-f\d]{6}|[a-f\d]{3}/i.exec(e.toString(16));if(!t)return[0,0,0];let[n]=t;n.length===3&&(n=[...n].map(e=>e+e).join(``));let r=Number.parseInt(n,16);return[r>>16&255,r>>8&255,r&255]},enumerable:!1},hexToAnsi256:{value:e=>r9.rgbToAnsi256(...r9.hexToRgb(e)),enumerable:!1},ansi256ToAnsi:{value:e=>{if(e<8)return 30+e;if(e<16)return 90+(e-8);let t,n,r;if(e>=232)t=((e-232)*10+8)/255,n=t,r=t;else{e-=16;let i=e%36;t=Math.floor(e/36)/5,n=Math.floor(i/6)/5,r=i%6/5}let i=Math.max(t,n,r)*2;if(i===0)return 30;let a=30+(Math.round(r)<<2|Math.round(n)<<1|Math.round(t));return i===2&&(a+=60),a},enumerable:!1},rgbToAnsi:{value:(e,t,n)=>r9.ansi256ToAnsi(r9.rgbToAnsi256(e,t,n)),enumerable:!1},hexToAnsi:{value:e=>r9.ansi256ToAnsi(r9.hexToAnsi256(e)),enumerable:!1}}),r9}const zqe=Rqe(),i9=new Set([`\x1B`,`›`]),a9=`]8;;`,o9=e=>`${i9.values().next().value}[${e}m`,s9=e=>`${i9.values().next().value}${a9}${e}`,Bqe=e=>e.split(` `).map(e=>$7(e)),c9=(e,t,n)=>{let r=[...t],i=!1,a=!1,o=$7(X7(e[e.length-1]));for(let[t,s]of r.entries()){let c=$7(s);if(o+c<=n?e[e.length-1]+=s:(e.push(s),o=0),i9.has(s)&&(i=!0,a=r.slice(t+1).join(``).startsWith(a9)),i){a?s===`\x07`&&(i=!1,a=!1):s===`m`&&(i=!1);continue}o+=c,o===n&&t<r.length-1&&(e.push(``),o=0)}!o&&e[e.length-1].length>0&&e.length>1&&(e[e.length-2]+=e.pop())},Vqe=e=>{let t=e.split(` `),n=t.length;for(;n>0&&!($7(t[n-1])>0);)n--;return n===t.length?e:t.slice(0,n).join(` `)+t.slice(n).join(``)},Hqe=(e,t,n={})=>{if(n.trim!==!1&&e.trim()===``)return``;let r=``,i,a,o=Bqe(e),s=[``];for(let[r,i]of e.split(` `).entries()){n.trim!==!1&&(s[s.length-1]=s[s.length-1].trimStart());let e=$7(s[s.length-1]);if(r!==0&&(e>=t&&(n.wordWrap===!1||n.trim===!1)&&(s.push(``),e=0),(e>0||n.trim===!1)&&(s[s.length-1]+=` `,e++)),n.hard&&o[r]>t){let n=t-e,a=1+Math.floor((o[r]-n-1)/t);Math.floor((o[r]-1)/t)<a&&s.push(``),c9(s,i,t);continue}if(e+o[r]>t&&e>0&&o[r]>0){if(n.wordWrap===!1&&e<t){c9(s,i,t);continue}s.push(``)}if(e+o[r]>t&&n.wordWrap===!1){c9(s,i,t);continue}s[s.length-1]+=i}n.trim!==!1&&(s=s.map(e=>Vqe(e)));let c=[...s.join(`
75428
75430
  `)];for(let[e,t]of c.entries()){if(r+=t,i9.has(t)){let{groups:t}=RegExp(`(?:\\[(?<code>\\d+)m|\\${a9}(?<uri>.*))`).exec(c.slice(e).join(``))||{groups:{}};if(t.code!==void 0){let e=Number.parseFloat(t.code);i=e===39?void 0:e}else t.uri!==void 0&&(a=t.uri.length===0?void 0:t.uri)}let n=zqe.codes.get(Number(i));c[e+1]===`
75429
75431
  `?(a&&(r+=s9(``)),i&&n&&(r+=o9(n))):t===`
75430
75432
  `&&(i&&n&&(r+=o9(i)),a&&(r+=s9(a)))}return r};function l9(e,t,n){return String(e).normalize().replace(/\r\n/g,`
@@ -75492,7 +75494,7 @@ ${V9}${t.trimStart()}`),n=3+o(t.trimStart()).length)}process.stdout.write(`
75492
75494
  `);process.stdout.write(J7.cursor.move(-999,e.length-1)),process.stdout.write(J7.erase.down(e.length))},g=e=>e.replace(/\.+$/,``),_=e=>{let t=(performance.now()-e)/1e3,n=Math.floor(t/60),r=Math.floor(t%60);return n>0?`[${n}m ${r}s]`:`[${r}s]`},v=(u=``)=>{o=!0,i=Gqe(),s=g(u),l=performance.now(),process.stdout.write(`${Y7.default.gray(w9)}
75493
75495
  `);let d=0,f=0;p(),a=setInterval(()=>{if(r&&s===c)return;h(),c=s;let n=Y7.default.magenta(t[d]);if(r)process.stdout.write(`${n} ${s}...`);else if(e===`timer`)process.stdout.write(`${n} ${s} ${_(l)}`);else{let e=`.`.repeat(Math.floor(f)).slice(0,3);process.stdout.write(`${n} ${s}${e}`)}d=d+1<t.length?d+1:0,f=f<t.length?f+.125:0},n)},y=(t=``,n=0)=>{o=!1,clearInterval(a),h();let r=n===0?Y7.default.green(C9):n===1?Y7.default.red(x9):Y7.default.red(S9);s=g(t??s),e===`timer`?process.stdout.write(`${r} ${s} ${_(l)}
75494
75496
  `):process.stdout.write(`${r} ${s}
75495
- `),m(),i()};return{start:v,stop:y,message:(e=``)=>{s=g(e??s)}}};async function W9(e){let{authManager:t,apiClient:n,reason:r,version:i}=e;if(t.isEnvAuth()||r===`welcome`&&t.isAuthenticated())return{success:!0};for(R9(r===`welcome`?`Welcome to Abacus.AI CLI v${i}`:r===`expired`?`Session expired — please log in again`:`Invalid credentials — please log in again`);;){let e=await F9({message:`How would you like to log in?`,options:[{value:`email`,label:`Log in with email`},{value:`apikey`,label:`Log in with API key`}]});if(p9(e))return L9(`Login cancelled`),{success:!1};if(e===`email`){let e=await fJe(t,n);if(e===`cancel`)return L9(`Login cancelled`),{success:!1};if(e===`success`)return z9(`You're all set!`),{success:!0}}else{let e=await pJe(t,n);if(e===`cancel`)return L9(`Login cancelled`),{success:!1};if(e===`success`)return z9(`You're all set!`),{success:!0}}}}async function fJe(e,t){let n=await uJe({message:`Enter your email address`,placeholder:`you@example.com`,validate:e=>{if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e))return`Please enter a valid email address`}});if(p9(n))return`cancel`;let r=U9();r.start(`Initiating device code login...`);let i,a,o;try{let e=await FJ(),s=await t.authenticateDeviceForCodeLlm(n,e);if(!s?.success||!s?.result)return r.stop(`Failed to initiate login`),B9.error(s?.error??`Failed to start device code login`),`retry`;i=s.result.verificationUri,a=s.result.userCode,o=s.result.pollingInterval??5,r.stop(`Device code ready`)}catch(e){return r.stop(`Connection failed`),B9.error(e instanceof Error?e.message:`Failed to connect`),`retry`}I9(`URL: ${i}\nCode: ${a}`,`Open the URL and enter the code to log in`);let[s,c]=await Promise.all([p6(i),m6(a)]);s&&c?B9.info(`Opening browser... (code copied to clipboard)`):s?B9.info(`Opening browser...`):c?B9.info(`Code copied to clipboard. Please open the URL manually.`):B9.info(`Please open the URL above and enter the code to log in.`);let l=U9();l.start(`Waiting for authentication...`);let u=Date.now()+600*1e3,d=o*1e3;for(;Date.now()<u;){await new Promise(e=>setTimeout(e,d));try{let n=await t.pollDeviceCode(a);if(n?.success&&n.result?.deviceCode){if(await e.loginWithDeviceCode(n.result.deviceCode),n.result.chatWebUrl){let e=n.result.chatWebUrl.replace(/^https?:\/\//,``);t.setChatWebDomain(e)}return l.stop(`Authenticated!`),B9.success(`Logged in successfully`),`success`}}catch{}}return l.stop(`Timed out`),B9.error(`Authentication timed out. Please try again.`),`retry`}async function pJe(e,t){let n=await dJe({message:`Enter your API key`});if(p9(n))return`cancel`;let r=U9();r.start(`Validating API key...`);try{await e.loginWithApiKey(n);let i=await t.getUserInfo();return i?.result?.email?(r.stop(`Authenticated!`),B9.success(`Logged in as ${i.result.email}`),`success`):(await e.logout(),r.stop(`Invalid API key`),B9.error(`Invalid API key — authentication failed`),`retry`)}catch(t){return await e.logout(),r.stop(`Login failed`),B9.error(t instanceof Error?t.message:`API key login failed`),`retry`}}function G9(e){return e.type===`code_llm_tool_call`||e.type===`code_llm_agent_tool_request`}function mJe(e){let t=e.toolUseResult;return!!(t?.rejected||t?.content?.startsWith(`Error:`))}function hJe(e){if(e.type!==`code_llm_notification`)return!1;let t=(e.message??``).toLowerCase();return t.includes(`compacting conversation`)||t.includes(`compacted conversation`)}function gJe(e){let t={toolUses:0,responses:0};for(let n of e)switch(n.type){case`code_llm_tool_call`:case`code_llm_agent_tool_request`:t.toolUses+=Array.isArray(n.toolUseRequest)?n.toolUseRequest.length:1;break;case`text`:n.source===`bot`&&t.responses++;break}return t}function _Je(e,t){return{toolUses:e.toolUses+t.toolUses,responses:e.responses+t.responses}}function vJe(e){let t={toolUses:0,responses:0},n=[],r=[],i=0,a=[];for(let a=0;a<e.length;a++){let o=e[a];if(hJe(o)){let e=gJe(n);t=_Je(t,e),r.push(...n),n=[],i++;continue}n.push(o)}i>0&&a.push({kind:`compacted`,id:`compacted-${i}`,counts:t,segments:r});let o=yJe(n);return a.push(...o),a}function yJe(e){let t=[],n=0;for(;n<e.length;){let r=e[n];if(r.type===`thinking`){t.push({kind:`segment`,segment:r}),n++;continue}if(G9(r)&&w7.has(K9(r))){let i=[r],a=n+1;for(;a<e.length;){let t=e[a];if(t.type===`thinking`){a++;continue}if(mJe(i[i.length-1]))break;if(G9(t)&&w7.has(K9(t)))i.push(t),a++;else break}i.length===1?t.push({kind:`segment`,segment:i[0]}):t.push({kind:`tool-group`,id:i[0].id,segments:i}),n=a;continue}t.push({kind:`segment`,segment:r}),n++}return t}function K9(e){let t=e.toolUseRequest;return t?Array.isArray(t)?t[0]?.name??``:t.name??``:``}function bJe(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.type===`thinking`)return{thinkingStartTime:n.thinkingStartTime??null,thinkingEndTime:n.thinkingEndTime??null}}return{thinkingStartTime:null,thinkingEndTime:null}}function xJe({timing:e}){let{setTitle:t}=W7(),{segments:n,agentStatus:r,pendingToolPermission:i,conversationTitle:a,conversationId:o,addNotification:s,stop:c,rejectPendingPermission:l,removeFirstFromQueue:u,clearQueue:d,totalCredits:f}=d3(),p=(0,Z.useRef)(null),{authExpired:m,clearAuthExpired:h}=o3();(0,Z.useEffect)(()=>{m&&(s(`Session expired — use /login to authenticate again.`,`error`),h())},[m,s,h]);let[g,_]=(0,Z.useState)(!1);bZ((e,t)=>{(t.ctrl||t.super)&&e===`o`&&_(e=>!e)});let v=Oqe(n),{lastItem:y,prevItems:b}=(0,Z.useMemo)(()=>{let e=vJe(n.filter(e=>!e.temp&&!e.isSpinny));return{lastItem:e.at(-1)??null,prevItems:e.slice(0,-1)}},[n]),{thinkingStartTime:x,thinkingEndTime:S}=(0,Z.useMemo)(()=>bJe(n),[n]),C=(0,Z.useRef)(Sd.Idle),[w,T]=(0,Z.useState)(null);(0,Z.useEffect)(()=>{let e=C.current===Sd.Idle,t=r!==Sd.Idle&&r!==Sd.WaitingForToolPermission;e&&t?T(Date.now()):r===Sd.Idle&&T(null),C.current=r},[r]);let E=r===Sd.WaitingForToolPermission&&i!==null,[D,O]=(0,Z.useState)(!1),[k,A]=(0,Z.useState)(`0`),[j,M]=(0,Z.useState)(0);(0,Z.useEffect)(()=>{t(a?`${a} • Abacus.AI CLI`:`Abacus.AI CLI`)},[a,t]),(0,Z.useEffect)(()=>ZZ(async()=>{let t=e.getFormattedDuration();M(f),A(t),O(!0),await new Promise(e=>setTimeout(e,100))},{wait:2e3,streams:[process.stdout,process.stderr]}),[e,f]);let N=Tqe({agentStatus:r,hasPendingPermission:i!==null,isExpandedView:g,composerHasText:()=>p.current?.hasText()??!1,hasQueuedMessages:()=>p.current?.hasQueue()??!1,stopAgent:c,rejectPermission:l,saveAndClearComposer:()=>p.current?.saveAndClear(),clearComposer:()=>p.current?.clear(),dequeueOne:u,clearQueue:d,exitApp:()=>QZ(0)}),P=r!==Sd.Idle&&r!==Sd.WaitingForToolPermission,ee=i?.request.tool.id??null;return(0,X.jsx)(G0.Provider,{value:g,children:(0,X.jsxs)(X.Fragment,{children:[(0,X.jsxs)(Q,{flexDirection:`column`,gap:1,paddingBottom:1,width:`95%`,children:[(0,X.jsx)(H8,{}),(0,X.jsxs)(C0.Provider,{value:ee,children:[b.map(e=>e.kind===`compacted`?g?e.segments.map(e=>(0,X.jsx)(b7,{segment:e},e.id)):(0,X.jsx)(_3,{counts:e.counts,segments:e.segments},e.id):e.kind===`segment`?(0,X.jsx)(b7,{segment:e.segment},e.segment.id):g?e.segments.map(e=>(0,X.jsx)(b7,{segment:e},e.id)):(0,X.jsx)(E7,{segments:e.segments},e.id)),y&&(y.kind===`compacted`?g?y.segments.map(e=>(0,X.jsx)(b7,{segment:e},e.id)):(0,X.jsx)(_3,{counts:y.counts,segments:y.segments},y.id):y.kind===`segment`?(0,X.jsx)(b7,{segment:y.segment},y.segment.id):g?y.segments.map(e=>(0,X.jsx)(b7,{segment:e},e.id)):(0,X.jsx)(E7,{segments:y.segments},y.id))]}),[`1`,`true`,`yes`].includes((process.env[`${hn.internalEnvPrefix}TODO_TOOL_UI`]??``).trim().toLowerCase())&&(0,X.jsx)(C7,{state:v}),P&&(0,X.jsx)(Q6,{onError:e=>{process.stderr.write(`[status-indicator error] ${e.stack??e.message}\n`)},children:(0,X.jsx)(_qe,{status:r,thinkingStartTime:x,thinkingEndTime:S,runStartTime:w})})]}),D?(0,X.jsx)($6,{duration:k,credits:j,conversationId:o}):(0,X.jsxs)(X.Fragment,{children:[E&&(0,X.jsx)(Q6,{onError:e=>{process.stderr.write(`[tool-permission error] ${e.stack??e.message}\n`)},children:(0,X.jsx)(H7,{pendingTool:i})}),(0,X.jsx)(Z.Activity,{mode:E?`hidden`:`visible`,children:(0,X.jsx)(Q6,{fallback:e=>(0,X.jsxs)(Q,{flexDirection:`column`,paddingX:1,children:[(0,X.jsx)($,{color:`red`,bold:!0,children:`Something went wrong in the input area.`}),(0,X.jsx)($,{color:`yellow`,children:e.message}),(0,X.jsxs)($,{dimColor:!0,children:[`Press Escape to restart the CLI, or resume with: `,hn.binName,` -c`,` `,o]})]}),onError:e=>{process.stderr.write(`[composer error] ${e.stack??e.message}\n`)},children:(0,X.jsx)(Z6,{hints:N,composerRef:p})})})]})]})})}async function SJe({apiClient:e,authManager:t,configService:n,agentArgs:r}){let i,a=r?.[`permission-mode`];if(a)switch(a){case`yolo`:i=xd.Yolo;break;case`accept-edits`:i=xd.AcceptEdits;break;case`plan`:i=xd.PlanMode;break;default:i=xd.Normal;break}else r?.[`dangerously-skip-permissions`]?i=xd.Yolo:r?.[`auto-accept-edits`]?i=xd.AcceptEdits:r?.[`plan-mode`]&&(i=xd.PlanMode);await iMe();let o=process.stdout,s=e=>{o&&o.writable&&o.write(e)},c=()=>s(uZ),l=()=>s(lZ),u=!1;for(;;){u=!1;let a=new ENe,o=new rUe,s=null,d=()=>{u=!0,s?.unmount()};c();let f=IMe((0,X.jsx)(s3,{client:e,authManager:t,onAuthExpired:d,children:(0,X.jsx)(DNe,{client:a,children:(0,X.jsx)(x3,{children:(0,X.jsx)(G7,{children:(0,X.jsx)(HHe,{children:(0,X.jsx)(hUe,{configService:n,children:(0,X.jsx)(zHe,{children:(0,X.jsx)(W0,{initialMode:i,children:(0,X.jsx)(BHe,{children:(0,X.jsx)(u3,{apiClient:e,configService:n,agentArgs:r,children:(0,X.jsx)(xJe,{timing:o})})})})})})})})})})}),{exitOnCtrlC:!1,suspendable:!0,onSuspended:()=>{process.stderr.write(`
75497
+ `),m(),i()};return{start:v,stop:y,message:(e=``)=>{s=g(e??s)}}};async function W9(e){let{authManager:t,apiClient:n,reason:r,version:i}=e;if(t.isEnvAuth()||r===`welcome`&&t.isAuthenticated())return{success:!0};for(R9(r===`welcome`?`Welcome to Abacus.AI CLI v${i}`:r===`expired`?`Session expired — please log in again`:`Invalid credentials — please log in again`);;){let e=await F9({message:`How would you like to log in?`,options:[{value:`email`,label:`Log in with email`},{value:`apikey`,label:`Log in with API key`}]});if(p9(e))return L9(`Login cancelled`),{success:!1};if(e===`email`){let e=await fJe(t,n);if(e===`cancel`)return L9(`Login cancelled`),{success:!1};if(e===`success`)return z9(`You're all set!`),{success:!0}}else{let e=await pJe(t,n);if(e===`cancel`)return L9(`Login cancelled`),{success:!1};if(e===`success`)return z9(`You're all set!`),{success:!0}}}}async function fJe(e,t){let n=await uJe({message:`Enter your email address`,placeholder:`you@example.com`,validate:e=>{if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e))return`Please enter a valid email address`}});if(p9(n))return`cancel`;let r=U9();r.start(`Initiating device code login...`);let i,a,o;try{let e=await FJ(),s=await t.authenticateDeviceForCodeLlm(n,e);if(!s?.success||!s?.result)return r.stop(`Failed to initiate login`),B9.error(s?.error??`Failed to start device code login`),`retry`;i=s.result.verificationUri,a=s.result.userCode,o=s.result.pollingInterval??5,r.stop(`Device code ready`)}catch(e){return r.stop(`Connection failed`),B9.error(e instanceof Error?e.message:`Failed to connect`),`retry`}I9(`URL: ${i}\nCode: ${a}`,`Open the URL and enter the code to log in`);let[s,c]=await Promise.all([p6(i),m6(a)]);s&&c?B9.info(`Opening browser... (code copied to clipboard)`):s?B9.info(`Opening browser...`):c?B9.info(`Code copied to clipboard. Please open the URL manually.`):B9.info(`Please open the URL above and enter the code to log in.`);let l=U9();l.start(`Waiting for authentication...`);let u=Date.now()+600*1e3,d=o*1e3;for(;Date.now()<u;){await new Promise(e=>setTimeout(e,d));try{let n=await t.pollDeviceCode(a);if(n?.success&&n.result?.deviceCode){if(await e.loginWithDeviceCode(n.result.deviceCode),n.result.chatWebUrl){let e=n.result.chatWebUrl.replace(/^https?:\/\//,``);t.setChatWebDomain(e)}return l.stop(`Authenticated!`),B9.success(`Logged in successfully`),`success`}}catch{}}return l.stop(`Timed out`),B9.error(`Authentication timed out. Please try again.`),`retry`}async function pJe(e,t){let n=await dJe({message:`Enter your API key`});if(p9(n))return`cancel`;let r=U9();r.start(`Validating API key...`);try{await e.loginWithApiKey(n);let i=await t.getUserInfo();return i?.result?.email?(r.stop(`Authenticated!`),B9.success(`Logged in as ${i.result.email}`),`success`):(await e.logout(),r.stop(`Invalid API key`),B9.error(`Invalid API key — authentication failed`),`retry`)}catch(t){return await e.logout(),r.stop(`Login failed`),B9.error(t instanceof Error?t.message:`API key login failed`),`retry`}}function G9(e){return e.type===`code_llm_tool_call`||e.type===`code_llm_agent_tool_request`}function mJe(e){let t=e.toolUseResult;return!!(t?.rejected||t?.content?.startsWith(`Error:`))}function hJe(e){if(e.type!==`code_llm_notification`)return!1;let t=(e.message??``).toLowerCase();return t.includes(`compacting conversation`)||t.includes(`compacted conversation`)}function gJe(e){let t={toolUses:0,responses:0};for(let n of e)switch(n.type){case`code_llm_tool_call`:case`code_llm_agent_tool_request`:t.toolUses+=Array.isArray(n.toolUseRequest)?n.toolUseRequest.length:1;break;case`text`:n.source===`bot`&&t.responses++;break}return t}function _Je(e,t){return{toolUses:e.toolUses+t.toolUses,responses:e.responses+t.responses}}function vJe(e){let t={toolUses:0,responses:0},n=[],r=[],i=0,a=[];for(let a=0;a<e.length;a++){let o=e[a];if(hJe(o)){let e=gJe(n);t=_Je(t,e),r.push(...n),n=[],i++;continue}n.push(o)}i>0&&a.push({kind:`compacted`,id:`compacted-${i}`,counts:t,segments:r});let o=yJe(n);return a.push(...o),a}function yJe(e){let t=[],n=0;for(;n<e.length;){let r=e[n];if(r.type===`thinking`){t.push({kind:`segment`,segment:r}),n++;continue}if(G9(r)&&w7.has(K9(r))){let i=[r],a=n+1;for(;a<e.length;){let t=e[a];if(t.type===`thinking`){a++;continue}if(mJe(i[i.length-1]))break;if(G9(t)&&w7.has(K9(t)))i.push(t),a++;else break}i.length===1?t.push({kind:`segment`,segment:i[0]}):t.push({kind:`tool-group`,id:i[0].id,segments:i}),n=a;continue}t.push({kind:`segment`,segment:r}),n++}return t}function K9(e){let t=e.toolUseRequest;return t?Array.isArray(t)?t[0]?.name??``:t.name??``:``}function bJe(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.type===`thinking`)return{thinkingStartTime:n.thinkingStartTime??null,thinkingEndTime:n.thinkingEndTime??null}}return{thinkingStartTime:null,thinkingEndTime:null}}function xJe({timing:e}){let{setTitle:t}=W7(),{segments:n,agentStatus:r,pendingToolPermission:i,conversationTitle:a,conversationId:o,addNotification:s,stop:c,rejectPendingPermission:l,clearQueue:u,totalCredits:d}=d3(),f=(0,Z.useRef)(null),{authExpired:p,clearAuthExpired:m}=o3();(0,Z.useEffect)(()=>{p&&(s(`Session expired — use /login to authenticate again.`,`error`),m())},[p,s,m]);let[h,g]=(0,Z.useState)(!1);bZ((e,t)=>{(t.ctrl||t.super)&&e===`o`&&g(e=>!e)});let _=Oqe(n),{lastItem:v,prevItems:y}=(0,Z.useMemo)(()=>{let e=vJe(n.filter(e=>!e.temp&&!e.isSpinny));return{lastItem:e.at(-1)??null,prevItems:e.slice(0,-1)}},[n]),{thinkingStartTime:b,thinkingEndTime:x}=(0,Z.useMemo)(()=>bJe(n),[n]),S=(0,Z.useRef)(Sd.Idle),[C,w]=(0,Z.useState)(null);(0,Z.useEffect)(()=>{let e=S.current===Sd.Idle,t=r!==Sd.Idle&&r!==Sd.WaitingForToolPermission;e&&t?w(Date.now()):r===Sd.Idle&&w(null),S.current=r},[r]);let T=r===Sd.WaitingForToolPermission&&i!==null,[E,D]=(0,Z.useState)(!1),[O,k]=(0,Z.useState)(`0`),[A,j]=(0,Z.useState)(0);(0,Z.useEffect)(()=>{t(a?`${a} • Abacus.AI CLI`:`Abacus.AI CLI`)},[a,t]),(0,Z.useEffect)(()=>ZZ(async()=>{let t=e.getFormattedDuration();j(d),k(t),D(!0),await new Promise(e=>setTimeout(e,100))},{wait:2e3,streams:[process.stdout,process.stderr]}),[e,d]);let M=Tqe({agentStatus:r,hasPendingPermission:i!==null,isExpandedView:h,composerHasText:()=>f.current?.hasText()??!1,hasQueuedMessages:()=>f.current?.hasQueue()??!1,stopAgent:c,rejectPermission:l,saveAndClearComposer:()=>f.current?.saveAndClear(),clearComposer:()=>f.current?.clear(),dequeueAllToComposer:()=>f.current?.dequeueAllToComposer(),clearQueue:u,exitApp:()=>QZ(0)}),N=r!==Sd.Idle&&r!==Sd.WaitingForToolPermission,P=i?.request.tool.id??null;return(0,X.jsx)(G0.Provider,{value:h,children:(0,X.jsxs)(X.Fragment,{children:[(0,X.jsxs)(Q,{flexDirection:`column`,gap:1,paddingBottom:1,width:`95%`,children:[(0,X.jsx)(H8,{}),(0,X.jsxs)(C0.Provider,{value:P,children:[y.map(e=>e.kind===`compacted`?h?e.segments.map(e=>(0,X.jsx)(b7,{segment:e},e.id)):(0,X.jsx)(_3,{counts:e.counts,segments:e.segments},e.id):e.kind===`segment`?(0,X.jsx)(b7,{segment:e.segment},e.segment.id):h?e.segments.map(e=>(0,X.jsx)(b7,{segment:e},e.id)):(0,X.jsx)(E7,{segments:e.segments},e.id)),v&&(v.kind===`compacted`?h?v.segments.map(e=>(0,X.jsx)(b7,{segment:e},e.id)):(0,X.jsx)(_3,{counts:v.counts,segments:v.segments},v.id):v.kind===`segment`?(0,X.jsx)(b7,{segment:v.segment},v.segment.id):h?v.segments.map(e=>(0,X.jsx)(b7,{segment:e},e.id)):(0,X.jsx)(E7,{segments:v.segments},v.id))]}),[`1`,`true`,`yes`].includes((process.env[`${hn.internalEnvPrefix}TODO_TOOL_UI`]??``).trim().toLowerCase())&&(0,X.jsx)(C7,{state:_}),N&&(0,X.jsx)(Q6,{onError:e=>{process.stderr.write(`[status-indicator error] ${e.stack??e.message}\n`)},children:(0,X.jsx)(_qe,{status:r,thinkingStartTime:b,thinkingEndTime:x,runStartTime:C})})]}),E?(0,X.jsx)($6,{duration:O,credits:A,conversationId:o}):(0,X.jsxs)(X.Fragment,{children:[T&&(0,X.jsx)(Q6,{onError:e=>{process.stderr.write(`[tool-permission error] ${e.stack??e.message}\n`)},children:(0,X.jsx)(H7,{pendingTool:i})}),(0,X.jsx)(Z.Activity,{mode:T?`hidden`:`visible`,children:(0,X.jsx)(Q6,{fallback:e=>(0,X.jsxs)(Q,{flexDirection:`column`,paddingX:1,children:[(0,X.jsx)($,{color:`red`,bold:!0,children:`Something went wrong in the input area.`}),(0,X.jsx)($,{color:`yellow`,children:e.message}),(0,X.jsxs)($,{dimColor:!0,children:[`Press Escape to restart the CLI, or resume with: `,hn.binName,` -c`,` `,o]})]}),onError:e=>{process.stderr.write(`[composer error] ${e.stack??e.message}\n`)},children:(0,X.jsx)(Z6,{hints:M,composerRef:f})})})]})]})})}async function SJe({apiClient:e,authManager:t,configService:n,agentArgs:r}){let i,a=r?.[`permission-mode`];if(a)switch(a){case`yolo`:i=xd.Yolo;break;case`accept-edits`:i=xd.AcceptEdits;break;case`plan`:i=xd.PlanMode;break;default:i=xd.Normal;break}else r?.[`dangerously-skip-permissions`]?i=xd.Yolo:r?.[`auto-accept-edits`]?i=xd.AcceptEdits:r?.[`plan-mode`]&&(i=xd.PlanMode);await iMe();let o=process.stdout,s=e=>{o&&o.writable&&o.write(e)},c=()=>s(uZ),l=()=>s(lZ),u=!1;for(;;){u=!1;let a=new ENe,o=new rUe,s=null,d=()=>{u=!0,s?.unmount()};c();let f=IMe((0,X.jsx)(s3,{client:e,authManager:t,onAuthExpired:d,children:(0,X.jsx)(DNe,{client:a,children:(0,X.jsx)(x3,{children:(0,X.jsx)(G7,{children:(0,X.jsx)(HHe,{children:(0,X.jsx)(hUe,{configService:n,children:(0,X.jsx)(zHe,{children:(0,X.jsx)(W0,{initialMode:i,children:(0,X.jsx)(BHe,{children:(0,X.jsx)(u3,{apiClient:e,configService:n,agentArgs:r,children:(0,X.jsx)(xJe,{timing:o})})})})})})})})})})}),{exitOnCtrlC:!1,suspendable:!0,onSuspended:()=>{process.stderr.write(`
75496
75498
  Abacus.AI has been suspended. Run \`fg\` to bring Abacus back.
75497
75499
  `)}});s=f;let p=!1,m=()=>{p||(p=!0,l())},h=()=>{p||(p=!0,f.cleanupTerminal())};if(process.once(`exit`,h),await f.waitUntilExit(),process.off(`exit`,h),m(),!u||!(await W9({authManager:t,apiClient:e,reason:`expired`,version:(await Promise.resolve().then(()=>Qe(EZ()))).default.version})).success)break}}const CJe=dt([`codellm`,`cli`,`auth`]);async function wJe(e){let t=await PJ.create(),n=new Ul(t,Sn(),gn.userAgentNames.cli,DZ.default.version),r=new vq({cwd:process.cwd(),extraSources:[{read:async()=>({client:`cli`})}]});await r.load();let i=r.get(`baseUrl`);if(typeof i==`string`&&i)try{new URL(i),n.setUrl(i),n.resetEndpoints(),await n.getApiEndpoint()}catch{CJe.error`Invalid base URL: ${i}`,process.exit(1)}let a=!0;switch(e){case`login`:await TJe(t,n);break;case`logout`:a=await EJe(t);break;case`status`:await DJe(t,n);break;case`switch`:a=await OJe(t,n);break}process.exit(a?0:1)}async function TJe(e,t){if(e.isEnvAuth()){B9.warn(`Currently authenticated via environment variable. Login is not needed.`);return}if(e.isAuthenticated()){let n=(await t.getUserInfo().catch(()=>null))?.result?.email;n&&B9.info(`Already logged in as ${iZ().bold().render(n)}`);let r=await P9({message:`Do you want to log in with a different account?`});if(p9(r)||!r)return;await e.logout()}await W9({authManager:e,apiClient:t,reason:`welcome`,version:DZ.default.version})}async function EJe(e){return e.isEnvAuth()?(B9.warn(`Currently authenticated via environment variable. Unset the environment variable to log out.`),!0):e.isAuthenticated()?await e.logout()?(B9.success(`Logged out successfully.`),!0):(B9.error(`Failed to log out.`),!1):(B9.info(`Not currently logged in.`),!0)}async function DJe(e,t){let n=e.getAuthKind();if(n.type===`logged_out`){console.log(aZ(`yellow`)(`Not logged in`));return}let r=n.type===`env_api_key`||n.type===`env_device_code`?`environment variable`:n.type===`api_key`?`API key`:n.type===`device_code`?`device code`:`OAuth token`;console.log(iZ().bold().render(`Authentication Status`)),console.log(` Method: ${r}`);try{let e=await t.getUserInfo();if(e?.result){let{email:t,name:n,organization:r}=e.result;n&&console.log(` Name: ${n}`),t&&console.log(` Email: ${t}`),r?.name&&console.log(` Org: ${r.name}`)}}catch{console.log(iZ().dim().render(` (Could not fetch user details)`))}}async function OJe(e,t){if(!e.isAuthenticated())return B9.error("Not logged in. Run `auth login` first."),!1;let n=U9();n.start(`Fetching organizations...`);let r;try{let e=await t.listOrganizations();if(!e?.success||!e.result)return n.stop(`Failed to fetch organizations`),B9.error(`Could not retrieve organizations.`),!1;r=e.result,n.stop(`Organizations loaded`)}catch{return n.stop(`Failed`),B9.error(`Could not fetch organizations.`),!1}if(r.length===0)return B9.info(`No organizations available.`),!0;let i;try{i=(await t.getUserInfo())?.result?.organization?.organizationId}catch{}let a=await F9({message:`Select an organization to switch to`,options:r.map(e=>({value:e.organizationId,label:e.name,hint:e.organizationId===i?`current`:e.workspace}))});if(p9(a))return L9(`Cancelled`),!0;if(a===i)return B9.info(`Already on this organization.`),!0;let o=U9();o.start(`Switching organization...`);try{if(await t.switchOrganization(a)){let e=r.find(e=>e.organizationId===a)?.name??a;return o.stop(`Done`),B9.success(`Switched to ${iZ().bold().render(e)}`),!0}else return o.stop(`Failed`),B9.error(`Failed to switch organization.`),!1}catch{return o.stop(`Failed`),B9.error(`Failed to switch organization.`),!1}}async function q9(e){let{currentVersion:t,explicit:n=!1,autoUpdate:r=!0,updateChannel:i,baseUrl:a}=e;if(!n&&IZ()||!n&&!r)return{action:`skipped`};let o;try{o=await LZ(t,i,a,{includeDev:n})}catch{return n?(B9.error(`Failed to check for updates. Please check your network connection.`),{action:`exit`}):{action:`skipped`}}if(!o)return n&&B9.success(`Already up to date (${t})`),{action:`skipped`};if(!n&&o.isEphemeral)return{action:`skipped`};let s=o.installationType===`native`,c=s?`Download v${o.latestVersion}`:RZ(o);R9(`Update available: ${o.currentVersion} → ${o.latestVersion}`),s||I9(c,`Install command`);let l=await P9({message:`Would you like to update now?`,initialValue:!0});if(p9(l))return L9(`Update cancelled`),{action:`exit`};if(l){let e=U9();e.start(`Updating...`);let{ok:t,output:n}=s?await BZ(o):zZ(o);if(t)return e.stop(`Updated to ${o.latestVersion}`),n&&I9(n,`Install output`),z9(`Restarting...`),{action:`updated`,version:o.latestVersion};{e.stop(`Update failed`),n&&I9(n,`Error output`),B9.error(`Update failed. You can try manually running the command above.`);let t=await P9({message:`Continue using v${o.currentVersion}?`,initialValue:!0});return p9(t)||!t?(L9(`Exiting`),{action:`exit`}):(z9(`Continuing with v${o.currentVersion}`),{action:`continue`})}}let u=await P9({message:`Continue using v${o.currentVersion}?`,initialValue:!0});return p9(u)||!u?(L9(`Exiting`),{action:`exit`}):(z9(`Continuing with v${o.currentVersion}`),{action:`continue`})}function kJe(e,t){switch(e){case`bash`:return jJe(t);case`zsh`:return MJe(t);case`fish`:return NJe(t);case`pwsh`:return PJe(t)}}function J9(){if(process.env.PSModulePath!==void 0)return`pwsh`;let e=process.env.SHELL??``;return e.endsWith(`zsh`)?`zsh`:e.endsWith(`bash`)?`bash`:e.endsWith(`fish`)?`fish`:process.platform===`win32`?`pwsh`:null}function AJe(e,t,n){switch(e){case`bash`:return n===`darwin`?[`${t}/.bash_profile`,`${t}/.bashrc`]:[`${t}/.bashrc`,`${t}/.bash_profile`];case`zsh`:return[`${t}/.zshrc`];case`fish`:return[`${t}/.config/fish/config.fish`];case`pwsh`:{let e=n===`win32`?te():t;return n===`win32`?[`${e}\\Documents\\PowerShell\\Microsoft.PowerShell_profile.ps1`,`${e}\\Documents\\WindowsPowerShell\\Microsoft.PowerShell_profile.ps1`]:[`${t}/.config/powershell/Microsoft.PowerShell_profile.ps1`,`${t}/.config/powershell/profile.ps1`]}}}const Y9=`# Abacus AI shell integration`;function jJe(e){return`\
75498
75500
  ${Y9}
@@ -75874,8 +75876,6 @@ Commands:
75874
75876
  auth status Show current authentication status
75875
75877
  auth switch Switch to a different organization
75876
75878
  upgrade Check for updates and install the latest version
75877
- shell-integration Install shell hook (bash/zsh/fish/pwsh)
75878
- shell-integration init <shell> Print hook script for eval (used internally)
75879
75879
 
75880
75880
  Options:
75881
75881
  --help Show this help message