@x-otto/tui 0.0.1-alpha.19 → 0.0.1-alpha.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -88,7 +88,7 @@ import{$ as e,$t as t,A as n,An as r,At as i,B as a,Bt as o,C as s,Cn as c,Ct as
88
88
 
89
89
  `)}t.write(`payload.value = newResult;`),t.write(`return payload;`);let s=t.compile();return(t,n)=>s(e,t,n)},a,o=wu,s=!lu.jitless,c=s&&Tu.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?Gf([],p,d,f,u,e):d):n(d,f):(d.issues.push({expected:`object`,code:`invalid_type`,input:p,inst:e}),d)}});function Jf(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=>!Vu(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=>Wu(e,r,uu())))}),t)}const Yf=Q(`$ZodUnion`,(e,t)=>{sf.init(e,t),vu(e._zod,`optin`,()=>t.options.some(e=>e._zod.optin===`optional`)?`optional`:void 0),vu(e._zod,`optout`,()=>t.options.some(e=>e._zod.optout===`optional`)?`optional`:void 0),vu(e._zod,`values`,()=>{if(t.options.every(e=>e._zod.values))return new Set(t.options.flatMap(e=>Array.from(e._zod.values)))}),vu(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=>hu(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=>Jf(t,i,e,a)):Jf(s,i,e,a)}}),Xf=Q(`$ZodIntersection`,(e,t)=>{sf.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])=>Qf(e,t,n)):Qf(e,i,a)}});function Zf(e,t){if(e===t||e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(Eu(e)&&Eu(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=Zf(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=Zf(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 Qf(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}),Vu(e))return e;let o=Zf(t.value,n.value);if(!o.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(o.mergeErrorPath)}`);return e.value=o.data,e}const $f=Q(`$ZodEnum`,(e,t)=>{sf.init(e,t);let n=du(t.entries),r=new Set(n);e._zod.values=r,e._zod.pattern=RegExp(`^(${n.filter(e=>Ou.has(typeof e)).map(e=>typeof e==`string`?ku(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}}),ep=Q(`$ZodTransform`,(e,t)=>{sf.init(e,t),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new cu(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 su;return n.value=i,n}});function tp(e,t){return e.issues.length&&t===void 0?{issues:[],value:void 0}:e}const np=Q(`$ZodOptional`,(e,t)=>{sf.init(e,t),e._zod.optin=`optional`,e._zod.optout=`optional`,vu(e._zod,`values`,()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),vu(e._zod,`pattern`,()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${hu(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=>tp(t,e.value)):tp(r,e.value)}return e.value===void 0?e:t.innerType._zod.run(e,n)}}),rp=Q(`$ZodExactOptional`,(e,t)=>{np.init(e,t),vu(e._zod,`values`,()=>t.innerType._zod.values),vu(e._zod,`pattern`,()=>t.innerType._zod.pattern),e._zod.parse=(e,n)=>t.innerType._zod.run(e,n)}),ip=Q(`$ZodNullable`,(e,t)=>{sf.init(e,t),vu(e._zod,`optin`,()=>t.innerType._zod.optin),vu(e._zod,`optout`,()=>t.innerType._zod.optout),vu(e._zod,`pattern`,()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${hu(e.source)}|null)$`):void 0}),vu(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)}),ap=Q(`$ZodDefault`,(e,t)=>{sf.init(e,t),e._zod.optin=`optional`,vu(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=>op(e,t)):op(r,t)}});function op(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const sp=Q(`$ZodPrefault`,(e,t)=>{sf.init(e,t),e._zod.optin=`optional`,vu(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))}),cp=Q(`$ZodNonOptional`,(e,t)=>{sf.init(e,t),vu(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=>lp(t,e)):lp(i,e)}});function lp(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 up=Q(`$ZodCatch`,(e,t)=>{sf.init(e,t),vu(e._zod,`optin`,()=>t.innerType._zod.optin),vu(e._zod,`optout`,()=>t.innerType._zod.optout),vu(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=>Wu(e,n,uu()))},input:e.value}),e.issues=[]),e)):(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>Wu(e,n,uu()))},input:e.value}),e.issues=[]),e)}}),dp=Q(`$ZodPipe`,(e,t)=>{sf.init(e,t),vu(e._zod,`values`,()=>t.in._zod.values),vu(e._zod,`optin`,()=>t.in._zod.optin),vu(e._zod,`optout`,()=>t.out._zod.optout),vu(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=>fp(e,t.in,n)):fp(r,t.in,n)}let r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>fp(e,t.out,n)):fp(r,t.out,n)}});function fp(e,t,n){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},n)}const pp=Q(`$ZodReadonly`,(e,t)=>{sf.init(e,t),vu(e._zod,`propValues`,()=>t.innerType._zod.propValues),vu(e._zod,`values`,()=>t.innerType._zod.values),vu(e._zod,`optin`,()=>t.innerType?._zod?.optin),vu(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(mp):mp(r)}});function mp(e){return e.value=Object.freeze(e.value),e}const hp=Q(`$ZodCustom`,(e,t)=>{Vd.init(e,t),sf.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=>gp(t,n,r,e));gp(i,n,r,e)}});function gp(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(Ku(e))}}var _p,vp=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 yp(){return new vp}(_p=globalThis).__zod_globalRegistry??(_p.__zod_globalRegistry=yp());const bp=globalThis.__zod_globalRegistry;function xp(e,t){return new e({type:`string`,...ju(t)})}function Sp(e,t){return new e({type:`string`,format:`email`,check:`string_format`,abort:!1,...ju(t)})}function Cp(e,t){return new e({type:`string`,format:`guid`,check:`string_format`,abort:!1,...ju(t)})}function wp(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,...ju(t)})}function Tp(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v4`,...ju(t)})}function Ep(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v6`,...ju(t)})}function Dp(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v7`,...ju(t)})}function Op(e,t){return new e({type:`string`,format:`url`,check:`string_format`,abort:!1,...ju(t)})}function kp(e,t){return new e({type:`string`,format:`emoji`,check:`string_format`,abort:!1,...ju(t)})}function Ap(e,t){return new e({type:`string`,format:`nanoid`,check:`string_format`,abort:!1,...ju(t)})}function jp(e,t){return new e({type:`string`,format:`cuid`,check:`string_format`,abort:!1,...ju(t)})}function Mp(e,t){return new e({type:`string`,format:`cuid2`,check:`string_format`,abort:!1,...ju(t)})}function Np(e,t){return new e({type:`string`,format:`ulid`,check:`string_format`,abort:!1,...ju(t)})}function Pp(e,t){return new e({type:`string`,format:`xid`,check:`string_format`,abort:!1,...ju(t)})}function Fp(e,t){return new e({type:`string`,format:`ksuid`,check:`string_format`,abort:!1,...ju(t)})}function Ip(e,t){return new e({type:`string`,format:`ipv4`,check:`string_format`,abort:!1,...ju(t)})}function Lp(e,t){return new e({type:`string`,format:`ipv6`,check:`string_format`,abort:!1,...ju(t)})}function Rp(e,t){return new e({type:`string`,format:`cidrv4`,check:`string_format`,abort:!1,...ju(t)})}function zp(e,t){return new e({type:`string`,format:`cidrv6`,check:`string_format`,abort:!1,...ju(t)})}function Bp(e,t){return new e({type:`string`,format:`base64`,check:`string_format`,abort:!1,...ju(t)})}function Vp(e,t){return new e({type:`string`,format:`base64url`,check:`string_format`,abort:!1,...ju(t)})}function Hp(e,t){return new e({type:`string`,format:`e164`,check:`string_format`,abort:!1,...ju(t)})}function Up(e,t){return new e({type:`string`,format:`jwt`,check:`string_format`,abort:!1,...ju(t)})}function Wp(e,t){return new e({type:`string`,format:`datetime`,check:`string_format`,offset:!1,local:!1,precision:null,...ju(t)})}function Gp(e,t){return new e({type:`string`,format:`date`,check:`string_format`,...ju(t)})}function Kp(e,t){return new e({type:`string`,format:`time`,check:`string_format`,precision:null,...ju(t)})}function qp(e,t){return new e({type:`string`,format:`duration`,check:`string_format`,...ju(t)})}function Jp(e,t){return new e({type:`number`,checks:[],...ju(t)})}function Yp(e,t){return new e({type:`number`,check:`number_format`,abort:!1,format:`safeint`,...ju(t)})}function Xp(e,t){return new e({type:`boolean`,...ju(t)})}function Zp(e){return new e({type:`unknown`})}function Qp(e,t){return new e({type:`never`,...ju(t)})}function $p(e,t){return new Ud({check:`less_than`,...ju(t),value:e,inclusive:!1})}function em(e,t){return new Ud({check:`less_than`,...ju(t),value:e,inclusive:!0})}function tm(e,t){return new Wd({check:`greater_than`,...ju(t),value:e,inclusive:!1})}function nm(e,t){return new Wd({check:`greater_than`,...ju(t),value:e,inclusive:!0})}function rm(e,t){return new Gd({check:`multiple_of`,...ju(t),value:e})}function im(e,t){return new qd({check:`max_length`,...ju(t),maximum:e})}function am(e,t){return new Jd({check:`min_length`,...ju(t),minimum:e})}function om(e,t){return new Yd({check:`length_equals`,...ju(t),length:e})}function sm(e,t){return new Zd({check:`string_format`,format:`regex`,...ju(t),pattern:e})}function cm(e){return new Qd({check:`string_format`,format:`lowercase`,...ju(e)})}function lm(e){return new $d({check:`string_format`,format:`uppercase`,...ju(e)})}function um(e,t){return new ef({check:`string_format`,format:`includes`,...ju(t),includes:e})}function dm(e,t){return new tf({check:`string_format`,format:`starts_with`,...ju(t),prefix:e})}function fm(e,t){return new nf({check:`string_format`,format:`ends_with`,...ju(t),suffix:e})}function pm(e){return new rf({check:`overwrite`,tx:e})}function mm(e){return pm(t=>t.normalize(e))}function hm(){return pm(e=>e.trim())}function gm(){return pm(e=>e.toLowerCase())}function _m(){return pm(e=>e.toUpperCase())}function vm(){return pm(e=>Su(e))}function ym(e,t,n){return new e({type:`array`,element:t,...ju(n)})}function bm(e,t,n){return new e({type:`custom`,check:`custom`,fn:t,...ju(n)})}function xm(e){let t=Sm(n=>(n.addIssue=e=>{if(typeof e==`string`)n.issues.push(Ku(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(Ku(r))}},e(n.value,n)));return t}function Sm(e,t){let n=new Vd({check:`custom`,...ju(t)});return n._zod.check=e,n}function Cm(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??bp,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 wm(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,wm(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`&&Dm(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 Tm(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>
90
90
 
91
- 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 Em(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:km(t,`input`,e.processors),output:km(t,`output`,e.processors)}},enumerable:!1,writable:!1}),n}catch{throw Error(`Error converting schema to JSON.`)}}function Dm(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 Dm(r.element,n);if(r.type===`set`)return Dm(r.valueType,n);if(r.type===`lazy`)return Dm(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 Dm(r.innerType,n);if(r.type===`intersection`)return Dm(r.left,n)||Dm(r.right,n);if(r.type===`record`||r.type===`map`)return Dm(r.keyType,n)||Dm(r.valueType,n);if(r.type===`pipe`)return Dm(r.in,n)||Dm(r.out,n);if(r.type===`object`){for(let e in r.shape)if(Dm(r.shape[e],n))return!0;return!1}if(r.type===`union`){for(let e of r.options)if(Dm(e,n))return!0;return!1}if(r.type===`tuple`){for(let e of r.items)if(Dm(e,n))return!0;return!!(r.rest&&Dm(r.rest,n))}return!1}const Om=(e,t={})=>n=>{let r=Cm({...n,processors:t});return wm(e,r),Tm(r,e),Em(r,e)},km=(e,t,n={})=>r=>{let{libraryOptions:i,target:a}=r??{},o=Cm({...i??{},target:a,io:t,processors:n});return wm(e,o),Tm(o,e),Em(o,e)},Am={guid:`uuid`,url:`uri`,datetime:`date-time`,json_string:`json-string`,regex:``},jm=(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=Am[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}))])}},Mm=(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)},Nm=(e,t,n,r)=>{n.type=`boolean`},Pm=(e,t,n,r)=>{n.not={}},Fm=(e,t,n,r)=>{let i=e._zod.def,a=du(i.entries);a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),n.enum=a},Im=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Custom types cannot be represented in JSON Schema`)},Lm=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Transforms cannot be represented in JSON Schema`)},Rm=(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=wm(a.element,t,{...r,path:[...r.path,`items`]})},zm=(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]=wm(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=wm(a.catchall,t,{...r,path:[...r.path,`additionalProperties`]})):t.io===`output`&&(i.additionalProperties=!1)},Bm=(e,t,n,r)=>{let i=e._zod.def,a=i.inclusive===!1,o=i.options.map((e,n)=>wm(e,t,{...r,path:[...r.path,a?`oneOf`:`anyOf`,n]}));a?n.oneOf=o:n.anyOf=o},Vm=(e,t,n,r)=>{let i=e._zod.def,a=wm(i.left,t,{...r,path:[...r.path,`allOf`,0]}),o=wm(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]]},Hm=(e,t,n,r)=>{let i=e._zod.def,a=wm(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`}]},Um=(e,t,n,r)=>{let i=e._zod.def;wm(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},Wm=(e,t,n,r)=>{let i=e._zod.def;wm(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.default=JSON.parse(JSON.stringify(i.defaultValue))},Gm=(e,t,n,r)=>{let i=e._zod.def;wm(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)))},Km=(e,t,n,r)=>{let i=e._zod.def;wm(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},qm=(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;wm(a,t,r);let o=t.seen.get(e);o.ref=a},Jm=(e,t,n,r)=>{let i=e._zod.def;wm(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.readOnly=!0},Ym=(e,t,n,r)=>{let i=e._zod.def;wm(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},Xm=Q(`ZodISODateTime`,(e,t)=>{xf.init(e,t),Sh.init(e,t)});function Zm(e){return Wp(Xm,e)}const Qm=Q(`ZodISODate`,(e,t)=>{Sf.init(e,t),Sh.init(e,t)});function $m(e){return Gp(Qm,e)}const eh=Q(`ZodISOTime`,(e,t)=>{Cf.init(e,t),Sh.init(e,t)});function th(e){return Kp(eh,e)}const nh=Q(`ZodISODuration`,(e,t)=>{wf.init(e,t),Sh.init(e,t)});function rh(e){return qp(nh,e)}const ih=(e,t)=>{Ju.init(e,t),e.name=`ZodError`,Object.defineProperties(e,{format:{value:t=>Zu(e,t)},flatten:{value:t=>Xu(e,t)},addIssue:{value:t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,fu,2)}},addIssues:{value:t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,fu,2)}},isEmpty:{get(){return e.issues.length===0}}})};Q(`ZodError`,ih);const ah=Q(`ZodError`,ih,{Parent:Error}),oh=Qu(ah),sh=$u(ah),ch=ed(ah),lh=nd(ah),uh=id(ah),dh=ad(ah),fh=od(ah),ph=sd(ah),mh=cd(ah),hh=ld(ah),gh=ud(ah),_h=dd(ah),vh=Q(`ZodType`,(e,t)=>(sf.init(e,t),Object.assign(e[`~standard`],{jsonSchema:{input:km(e,`input`),output:km(e,`output`)}}),e.toJSONSchema=Om(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,`_def`,{value:t}),e.check=(...n)=>e.clone(bu(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)=>Au(e,t,n),e.brand=()=>e,e.register=((t,n)=>(t.add(e,n),e)),e.parse=(t,n)=>oh(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>ch(e,t,n),e.parseAsync=async(t,n)=>sh(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>lh(e,t,n),e.spa=e.safeParseAsync,e.encode=(t,n)=>uh(e,t,n),e.decode=(t,n)=>dh(e,t,n),e.encodeAsync=async(t,n)=>fh(e,t,n),e.decodeAsync=async(t,n)=>ph(e,t,n),e.safeEncode=(t,n)=>mh(e,t,n),e.safeDecode=(t,n)=>hh(e,t,n),e.safeEncodeAsync=async(t,n)=>gh(e,t,n),e.safeDecodeAsync=async(t,n)=>_h(e,t,n),e.refine=(t,n)=>e.check(kg(t,n)),e.superRefine=t=>e.check(Ag(t)),e.overwrite=t=>e.check(pm(t)),e.optional=()=>dg(e),e.exactOptional=()=>pg(e),e.nullable=()=>hg(e),e.nullish=()=>dg(hg(e)),e.nonoptional=t=>xg(e,t),e.array=()=>$h(e),e.or=t=>rg([e,t]),e.and=t=>ag(e,t),e.transform=t=>Tg(e,lg(t)),e.default=t=>_g(e,t),e.prefault=t=>yg(e,t),e.catch=t=>Cg(e,t),e.pipe=t=>Tg(e,t),e.readonly=()=>Dg(e),e.describe=t=>{let n=e.clone();return bp.add(n,{description:t}),n},Object.defineProperty(e,`description`,{get(){return bp.get(e)?.description},configurable:!0}),e.meta=(...t)=>{if(t.length===0)return bp.get(e);let n=e.clone();return bp.add(n,t[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e.apply=t=>t(e),e)),yh=Q(`_ZodString`,(e,t)=>{cf.init(e,t),vh.init(e,t),e._zod.processJSONSchema=(t,n,r)=>jm(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(sm(...t)),e.includes=(...t)=>e.check(um(...t)),e.startsWith=(...t)=>e.check(dm(...t)),e.endsWith=(...t)=>e.check(fm(...t)),e.min=(...t)=>e.check(am(...t)),e.max=(...t)=>e.check(im(...t)),e.length=(...t)=>e.check(om(...t)),e.nonempty=(...t)=>e.check(am(1,...t)),e.lowercase=t=>e.check(cm(t)),e.uppercase=t=>e.check(lm(t)),e.trim=()=>e.check(hm()),e.normalize=(...t)=>e.check(mm(...t)),e.toLowerCase=()=>e.check(gm()),e.toUpperCase=()=>e.check(_m()),e.slugify=()=>e.check(vm())}),bh=Q(`ZodString`,(e,t)=>{cf.init(e,t),yh.init(e,t),e.email=t=>e.check(Sp(Ch,t)),e.url=t=>e.check(Op(Eh,t)),e.jwt=t=>e.check(Up(Vh,t)),e.emoji=t=>e.check(kp(Dh,t)),e.guid=t=>e.check(Cp(wh,t)),e.uuid=t=>e.check(wp(Th,t)),e.uuidv4=t=>e.check(Tp(Th,t)),e.uuidv6=t=>e.check(Ep(Th,t)),e.uuidv7=t=>e.check(Dp(Th,t)),e.nanoid=t=>e.check(Ap(Oh,t)),e.guid=t=>e.check(Cp(wh,t)),e.cuid=t=>e.check(jp(kh,t)),e.cuid2=t=>e.check(Mp(Ah,t)),e.ulid=t=>e.check(Np(jh,t)),e.base64=t=>e.check(Bp(Rh,t)),e.base64url=t=>e.check(Vp(zh,t)),e.xid=t=>e.check(Pp(Mh,t)),e.ksuid=t=>e.check(Fp(Nh,t)),e.ipv4=t=>e.check(Ip(Ph,t)),e.ipv6=t=>e.check(Lp(Fh,t)),e.cidrv4=t=>e.check(Rp(Ih,t)),e.cidrv6=t=>e.check(zp(Lh,t)),e.e164=t=>e.check(Hp(Bh,t)),e.datetime=t=>e.check(Zm(t)),e.date=t=>e.check($m(t)),e.time=t=>e.check(th(t)),e.duration=t=>e.check(rh(t))});function xh(e){return xp(bh,e)}const Sh=Q(`ZodStringFormat`,(e,t)=>{lf.init(e,t),yh.init(e,t)}),Ch=Q(`ZodEmail`,(e,t)=>{ff.init(e,t),Sh.init(e,t)}),wh=Q(`ZodGUID`,(e,t)=>{uf.init(e,t),Sh.init(e,t)}),Th=Q(`ZodUUID`,(e,t)=>{df.init(e,t),Sh.init(e,t)}),Eh=Q(`ZodURL`,(e,t)=>{pf.init(e,t),Sh.init(e,t)}),Dh=Q(`ZodEmoji`,(e,t)=>{mf.init(e,t),Sh.init(e,t)}),Oh=Q(`ZodNanoID`,(e,t)=>{hf.init(e,t),Sh.init(e,t)}),kh=Q(`ZodCUID`,(e,t)=>{gf.init(e,t),Sh.init(e,t)}),Ah=Q(`ZodCUID2`,(e,t)=>{_f.init(e,t),Sh.init(e,t)}),jh=Q(`ZodULID`,(e,t)=>{vf.init(e,t),Sh.init(e,t)}),Mh=Q(`ZodXID`,(e,t)=>{yf.init(e,t),Sh.init(e,t)}),Nh=Q(`ZodKSUID`,(e,t)=>{bf.init(e,t),Sh.init(e,t)}),Ph=Q(`ZodIPv4`,(e,t)=>{Tf.init(e,t),Sh.init(e,t)}),Fh=Q(`ZodIPv6`,(e,t)=>{Ef.init(e,t),Sh.init(e,t)}),Ih=Q(`ZodCIDRv4`,(e,t)=>{Df.init(e,t),Sh.init(e,t)}),Lh=Q(`ZodCIDRv6`,(e,t)=>{Of.init(e,t),Sh.init(e,t)}),Rh=Q(`ZodBase64`,(e,t)=>{Af.init(e,t),Sh.init(e,t)}),zh=Q(`ZodBase64URL`,(e,t)=>{Mf.init(e,t),Sh.init(e,t)}),Bh=Q(`ZodE164`,(e,t)=>{Nf.init(e,t),Sh.init(e,t)}),Vh=Q(`ZodJWT`,(e,t)=>{Ff.init(e,t),Sh.init(e,t)}),Hh=Q(`ZodNumber`,(e,t)=>{If.init(e,t),vh.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Mm(e,t,n,r),e.gt=(t,n)=>e.check(tm(t,n)),e.gte=(t,n)=>e.check(nm(t,n)),e.min=(t,n)=>e.check(nm(t,n)),e.lt=(t,n)=>e.check($p(t,n)),e.lte=(t,n)=>e.check(em(t,n)),e.max=(t,n)=>e.check(em(t,n)),e.int=t=>e.check(Gh(t)),e.safe=t=>e.check(Gh(t)),e.positive=t=>e.check(tm(0,t)),e.nonnegative=t=>e.check(nm(0,t)),e.negative=t=>e.check($p(0,t)),e.nonpositive=t=>e.check(em(0,t)),e.multipleOf=(t,n)=>e.check(rm(t,n)),e.step=(t,n)=>e.check(rm(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 Uh(e){return Jp(Hh,e)}const Wh=Q(`ZodNumberFormat`,(e,t)=>{Lf.init(e,t),Hh.init(e,t)});function Gh(e){return Yp(Wh,e)}const Kh=Q(`ZodBoolean`,(e,t)=>{Rf.init(e,t),vh.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Nm(e,t,n,r)});function qh(e){return Xp(Kh,e)}const Jh=Q(`ZodUnknown`,(e,t)=>{zf.init(e,t),vh.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function Yh(){return Zp(Jh)}const Xh=Q(`ZodNever`,(e,t)=>{Bf.init(e,t),vh.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Pm(e,t,n,r)});function Zh(e){return Qp(Xh,e)}const Qh=Q(`ZodArray`,(e,t)=>{Hf.init(e,t),vh.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Rm(e,t,n,r),e.element=t.element,e.min=(t,n)=>e.check(am(t,n)),e.nonempty=t=>e.check(am(1,t)),e.max=(t,n)=>e.check(im(t,n)),e.length=(t,n)=>e.check(om(t,n)),e.unwrap=()=>e.element});function $h(e,t){return ym(Qh,e,t)}const eg=Q(`ZodObject`,(e,t)=>{qf.init(e,t),vh.init(e,t),e._zod.processJSONSchema=(t,n,r)=>zm(e,t,n,r),vu(e,`shape`,()=>t.shape),e.keyof=()=>sg(Object.keys(e._zod.def.shape)),e.catchall=t=>e.clone({...e._zod.def,catchall:t}),e.passthrough=()=>e.clone({...e._zod.def,catchall:Yh()}),e.loose=()=>e.clone({...e._zod.def,catchall:Yh()}),e.strict=()=>e.clone({...e._zod.def,catchall:Zh()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=t=>Iu(e,t),e.safeExtend=t=>Lu(e,t),e.merge=t=>Ru(e,t),e.pick=t=>Pu(e,t),e.omit=t=>Fu(e,t),e.partial=(...t)=>zu(ug,e,t[0]),e.required=(...t)=>Bu(bg,e,t[0])});function tg(e,t){return new eg({type:`object`,shape:e??{},...ju(t)})}const ng=Q(`ZodUnion`,(e,t)=>{Yf.init(e,t),vh.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Bm(e,t,n,r),e.options=t.options});function rg(e,t){return new ng({type:`union`,options:e,...ju(t)})}const ig=Q(`ZodIntersection`,(e,t)=>{Xf.init(e,t),vh.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Vm(e,t,n,r)});function ag(e,t){return new ig({type:`intersection`,left:e,right:t})}const og=Q(`ZodEnum`,(e,t)=>{$f.init(e,t),vh.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Fm(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 og({...t,checks:[],...ju(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 og({...t,checks:[],...ju(r),entries:i})}});function sg(e,t){return new og({type:`enum`,entries:Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e,...ju(t)})}const cg=Q(`ZodTransform`,(e,t)=>{ep.init(e,t),vh.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Lm(e,t,n,r),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new cu(e.constructor.name);n.addIssue=r=>{if(typeof r==`string`)n.issues.push(Ku(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(Ku(t))}};let i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n)):(n.value=i,n)}});function lg(e){return new cg({type:`transform`,transform:e})}const ug=Q(`ZodOptional`,(e,t)=>{np.init(e,t),vh.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ym(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function dg(e){return new ug({type:`optional`,innerType:e})}const fg=Q(`ZodExactOptional`,(e,t)=>{rp.init(e,t),vh.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ym(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function pg(e){return new fg({type:`optional`,innerType:e})}const mg=Q(`ZodNullable`,(e,t)=>{ip.init(e,t),vh.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Hm(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function hg(e){return new mg({type:`nullable`,innerType:e})}const gg=Q(`ZodDefault`,(e,t)=>{ap.init(e,t),vh.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Wm(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function _g(e,t){return new gg({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():Du(t)}})}const vg=Q(`ZodPrefault`,(e,t)=>{sp.init(e,t),vh.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Gm(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function yg(e,t){return new vg({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():Du(t)}})}const bg=Q(`ZodNonOptional`,(e,t)=>{cp.init(e,t),vh.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Um(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function xg(e,t){return new bg({type:`nonoptional`,innerType:e,...ju(t)})}const Sg=Q(`ZodCatch`,(e,t)=>{up.init(e,t),vh.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Km(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Cg(e,t){return new Sg({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:()=>t})}const wg=Q(`ZodPipe`,(e,t)=>{dp.init(e,t),vh.init(e,t),e._zod.processJSONSchema=(t,n,r)=>qm(e,t,n,r),e.in=t.in,e.out=t.out});function Tg(e,t){return new wg({type:`pipe`,in:e,out:t})}const Eg=Q(`ZodReadonly`,(e,t)=>{pp.init(e,t),vh.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Jm(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Dg(e){return new Eg({type:`readonly`,innerType:e})}const Og=Q(`ZodCustom`,(e,t)=>{hp.init(e,t),vh.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Im(e,t,n,r)});function kg(e,t={}){return bm(Og,e,t)}function Ag(e){return xm(e)}fn(`@x-otto/provider:tool-roundtrip`),fn(`@x-otto/provider:openai-usage`),fn(`@x-otto/provider:stream-state`),fn(`@x-otto/provider:chat-completions-stream`),fn(`@x-otto/provider:oauth:templates`);var jg=class{entries=new Map;sources=new Map;reserved;constructor(e={}){this.reserved=new Set(e.reserved??[])}register(e,t,n){if(this.reserved.has(e))return!1;let r=this.sources.get(e);return n!==void 0&&this.entries.has(e)&&r!==n?!1:(this.entries.set(e,t),n===void 0?this.sources.delete(e):this.sources.set(e,n),!0)}replace(e,t,n){this.entries.set(e,t),this.sources.set(e,n)}unregister(e){this.entries.delete(e),this.sources.delete(e)}unregisterBySource(e,t){let n=[];for(let[r,i]of[...this.sources.entries()])i===e&&!t?.has(r)&&(this.entries.delete(r),this.sources.delete(r),n.push(r));return n}get(e){return this.entries.get(e)}getSource(e){return this.sources.get(e)}has(e){return this.entries.has(e)}list(){return[...this.entries.keys()]}all(){return[...this.entries.entries()]}getKeysBySource(e){return[...this.sources.entries()].filter(([,t])=>t===e).map(([e])=>e)}markReserved(e){this.reserved.add(e)}isReserved(e){return this.reserved.has(e)}get size(){return this.entries.size}};fn(`@x-otto/ai:model-registry`),tg({id:xh().min(1),name:xh().min(1),api:xh().min(1),provider:xh().min(1),baseUrl:xh().min(1),reasoning:qh(),input:$h(sg([`text`,`image`])).min(1),cost:tg({input:Uh(),output:Uh(),cacheRead:Uh(),cacheWrite:Uh()}).optional(),contextWindow:Uh().int().positive(),maxOutputTokens:Uh().int().positive(),thinkingLevels:$h(sg([`low`,`medium`,`high`,`xhigh`,`max`])).optional(),thinkingMode:sg([`enabled`,`adaptive`]).optional()});const Mg=[];new Map(Mg.map(e=>[e.id,e])),new jg({reserved:new Set(Mg.map(e=>e.id))}),Object.fromEntries(Mg.filter(e=>e.env).map(e=>[e.id,e.env])),Mg.filter(e=>e.oauth).map(e=>e.id),fn(`@x-otto/ai:model-fetch`),xn(process.env.OTTO_MODEL_FETCH_TIMEOUT_MS,1e4),fn(`@x-otto/ai:model-catalog`),fn(`@x-otto/ai:oauth-refresh-coordinator`),fn(`@x-otto/ai:auth-store`);const Ng=[{id:`chat.message.before`,kind:`interceptor`},{id:`chat.message.after`,kind:`interceptor`},{id:`tool.execute.before`,kind:`interceptor`},{id:`tool.execute.after`,kind:`interceptor`},{id:`messages.transform`,kind:`interceptor`},{id:`chat.params`,kind:`interceptor`},{id:`system.prompt.transform`,kind:`interceptor`},{id:`session.created`,kind:`observer`},{id:`session.restored`,kind:`observer`},{id:`session.deleted`,kind:`observer`},{id:`session.idle`,kind:`observer`},{id:`session.error`,kind:`observer`},{id:`stream.start`,kind:`observer`},{id:`stream.end`,kind:`observer`},{id:`compaction.before`,kind:`observer`},{id:`compaction.after`,kind:`observer`},{id:`memory.prune.before`,kind:`interceptor`},{id:`process.spawned`,kind:`observer`},{id:`process.exited`,kind:`observer`},{id:`task.created`,kind:`observer`},{id:`task.started`,kind:`observer`},{id:`task.completed`,kind:`observer`},{id:`task.failed`,kind:`observer`},{id:`task.cancelled`,kind:`observer`},{id:`notification`,kind:`observer`}];Ng.map(e=>e.id),new Set(Ng.filter(e=>e.kind===`interceptor`).map(e=>e.id)),fn(`@x-otto/hooks:stream-metrics`),fn(`@x-otto/hooks:compaction`),fn(`@x-otto/hooks:tool-error-tracker`),fn(`@x-otto/hooks:token-budget`),fn(`@x-otto/hooks`),xn(process.env.OTTO_HOOK_TIMEOUT_MS,5e3),fn(`@x-otto/hooks:permission`);const Pg=process.emitWarning;process.emitWarning=function(e,...t){if(!(typeof e==`string`&&e.includes(`SQLite is an experimental feature`)))return Pg.call(process,e,...t)},Sn.O_DSYNC==null?Sn.O_WRONLY|Sn.O_CREAT|Sn.O_APPEND:Sn.O_WRONLY|Sn.O_CREAT|Sn.O_APPEND|Sn.O_DSYNC,[`You are a sub-agent: do not interact with the user directly; do not expand the task scope; on completion, report your conclusion and any remaining risks.`].join(`
91
+ 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 Em(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:km(t,`input`,e.processors),output:km(t,`output`,e.processors)}},enumerable:!1,writable:!1}),n}catch{throw Error(`Error converting schema to JSON.`)}}function Dm(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 Dm(r.element,n);if(r.type===`set`)return Dm(r.valueType,n);if(r.type===`lazy`)return Dm(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 Dm(r.innerType,n);if(r.type===`intersection`)return Dm(r.left,n)||Dm(r.right,n);if(r.type===`record`||r.type===`map`)return Dm(r.keyType,n)||Dm(r.valueType,n);if(r.type===`pipe`)return Dm(r.in,n)||Dm(r.out,n);if(r.type===`object`){for(let e in r.shape)if(Dm(r.shape[e],n))return!0;return!1}if(r.type===`union`){for(let e of r.options)if(Dm(e,n))return!0;return!1}if(r.type===`tuple`){for(let e of r.items)if(Dm(e,n))return!0;return!!(r.rest&&Dm(r.rest,n))}return!1}const Om=(e,t={})=>n=>{let r=Cm({...n,processors:t});return wm(e,r),Tm(r,e),Em(r,e)},km=(e,t,n={})=>r=>{let{libraryOptions:i,target:a}=r??{},o=Cm({...i??{},target:a,io:t,processors:n});return wm(e,o),Tm(o,e),Em(o,e)},Am={guid:`uuid`,url:`uri`,datetime:`date-time`,json_string:`json-string`,regex:``},jm=(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=Am[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}))])}},Mm=(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)},Nm=(e,t,n,r)=>{n.type=`boolean`},Pm=(e,t,n,r)=>{n.not={}},Fm=(e,t,n,r)=>{let i=e._zod.def,a=du(i.entries);a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),n.enum=a},Im=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Custom types cannot be represented in JSON Schema`)},Lm=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Transforms cannot be represented in JSON Schema`)},Rm=(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=wm(a.element,t,{...r,path:[...r.path,`items`]})},zm=(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]=wm(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=wm(a.catchall,t,{...r,path:[...r.path,`additionalProperties`]})):t.io===`output`&&(i.additionalProperties=!1)},Bm=(e,t,n,r)=>{let i=e._zod.def,a=i.inclusive===!1,o=i.options.map((e,n)=>wm(e,t,{...r,path:[...r.path,a?`oneOf`:`anyOf`,n]}));a?n.oneOf=o:n.anyOf=o},Vm=(e,t,n,r)=>{let i=e._zod.def,a=wm(i.left,t,{...r,path:[...r.path,`allOf`,0]}),o=wm(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]]},Hm=(e,t,n,r)=>{let i=e._zod.def,a=wm(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`}]},Um=(e,t,n,r)=>{let i=e._zod.def;wm(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},Wm=(e,t,n,r)=>{let i=e._zod.def;wm(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.default=JSON.parse(JSON.stringify(i.defaultValue))},Gm=(e,t,n,r)=>{let i=e._zod.def;wm(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)))},Km=(e,t,n,r)=>{let i=e._zod.def;wm(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},qm=(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;wm(a,t,r);let o=t.seen.get(e);o.ref=a},Jm=(e,t,n,r)=>{let i=e._zod.def;wm(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.readOnly=!0},Ym=(e,t,n,r)=>{let i=e._zod.def;wm(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},Xm=Q(`ZodISODateTime`,(e,t)=>{xf.init(e,t),Sh.init(e,t)});function Zm(e){return Wp(Xm,e)}const Qm=Q(`ZodISODate`,(e,t)=>{Sf.init(e,t),Sh.init(e,t)});function $m(e){return Gp(Qm,e)}const eh=Q(`ZodISOTime`,(e,t)=>{Cf.init(e,t),Sh.init(e,t)});function th(e){return Kp(eh,e)}const nh=Q(`ZodISODuration`,(e,t)=>{wf.init(e,t),Sh.init(e,t)});function rh(e){return qp(nh,e)}const ih=(e,t)=>{Ju.init(e,t),e.name=`ZodError`,Object.defineProperties(e,{format:{value:t=>Zu(e,t)},flatten:{value:t=>Xu(e,t)},addIssue:{value:t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,fu,2)}},addIssues:{value:t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,fu,2)}},isEmpty:{get(){return e.issues.length===0}}})};Q(`ZodError`,ih);const ah=Q(`ZodError`,ih,{Parent:Error}),oh=Qu(ah),sh=$u(ah),ch=ed(ah),lh=nd(ah),uh=id(ah),dh=ad(ah),fh=od(ah),ph=sd(ah),mh=cd(ah),hh=ld(ah),gh=ud(ah),_h=dd(ah),vh=Q(`ZodType`,(e,t)=>(sf.init(e,t),Object.assign(e[`~standard`],{jsonSchema:{input:km(e,`input`),output:km(e,`output`)}}),e.toJSONSchema=Om(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,`_def`,{value:t}),e.check=(...n)=>e.clone(bu(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)=>Au(e,t,n),e.brand=()=>e,e.register=((t,n)=>(t.add(e,n),e)),e.parse=(t,n)=>oh(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>ch(e,t,n),e.parseAsync=async(t,n)=>sh(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>lh(e,t,n),e.spa=e.safeParseAsync,e.encode=(t,n)=>uh(e,t,n),e.decode=(t,n)=>dh(e,t,n),e.encodeAsync=async(t,n)=>fh(e,t,n),e.decodeAsync=async(t,n)=>ph(e,t,n),e.safeEncode=(t,n)=>mh(e,t,n),e.safeDecode=(t,n)=>hh(e,t,n),e.safeEncodeAsync=async(t,n)=>gh(e,t,n),e.safeDecodeAsync=async(t,n)=>_h(e,t,n),e.refine=(t,n)=>e.check(kg(t,n)),e.superRefine=t=>e.check(Ag(t)),e.overwrite=t=>e.check(pm(t)),e.optional=()=>dg(e),e.exactOptional=()=>pg(e),e.nullable=()=>hg(e),e.nullish=()=>dg(hg(e)),e.nonoptional=t=>xg(e,t),e.array=()=>$h(e),e.or=t=>rg([e,t]),e.and=t=>ag(e,t),e.transform=t=>Tg(e,lg(t)),e.default=t=>_g(e,t),e.prefault=t=>yg(e,t),e.catch=t=>Cg(e,t),e.pipe=t=>Tg(e,t),e.readonly=()=>Dg(e),e.describe=t=>{let n=e.clone();return bp.add(n,{description:t}),n},Object.defineProperty(e,`description`,{get(){return bp.get(e)?.description},configurable:!0}),e.meta=(...t)=>{if(t.length===0)return bp.get(e);let n=e.clone();return bp.add(n,t[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e.apply=t=>t(e),e)),yh=Q(`_ZodString`,(e,t)=>{cf.init(e,t),vh.init(e,t),e._zod.processJSONSchema=(t,n,r)=>jm(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(sm(...t)),e.includes=(...t)=>e.check(um(...t)),e.startsWith=(...t)=>e.check(dm(...t)),e.endsWith=(...t)=>e.check(fm(...t)),e.min=(...t)=>e.check(am(...t)),e.max=(...t)=>e.check(im(...t)),e.length=(...t)=>e.check(om(...t)),e.nonempty=(...t)=>e.check(am(1,...t)),e.lowercase=t=>e.check(cm(t)),e.uppercase=t=>e.check(lm(t)),e.trim=()=>e.check(hm()),e.normalize=(...t)=>e.check(mm(...t)),e.toLowerCase=()=>e.check(gm()),e.toUpperCase=()=>e.check(_m()),e.slugify=()=>e.check(vm())}),bh=Q(`ZodString`,(e,t)=>{cf.init(e,t),yh.init(e,t),e.email=t=>e.check(Sp(Ch,t)),e.url=t=>e.check(Op(Eh,t)),e.jwt=t=>e.check(Up(Vh,t)),e.emoji=t=>e.check(kp(Dh,t)),e.guid=t=>e.check(Cp(wh,t)),e.uuid=t=>e.check(wp(Th,t)),e.uuidv4=t=>e.check(Tp(Th,t)),e.uuidv6=t=>e.check(Ep(Th,t)),e.uuidv7=t=>e.check(Dp(Th,t)),e.nanoid=t=>e.check(Ap(Oh,t)),e.guid=t=>e.check(Cp(wh,t)),e.cuid=t=>e.check(jp(kh,t)),e.cuid2=t=>e.check(Mp(Ah,t)),e.ulid=t=>e.check(Np(jh,t)),e.base64=t=>e.check(Bp(Rh,t)),e.base64url=t=>e.check(Vp(zh,t)),e.xid=t=>e.check(Pp(Mh,t)),e.ksuid=t=>e.check(Fp(Nh,t)),e.ipv4=t=>e.check(Ip(Ph,t)),e.ipv6=t=>e.check(Lp(Fh,t)),e.cidrv4=t=>e.check(Rp(Ih,t)),e.cidrv6=t=>e.check(zp(Lh,t)),e.e164=t=>e.check(Hp(Bh,t)),e.datetime=t=>e.check(Zm(t)),e.date=t=>e.check($m(t)),e.time=t=>e.check(th(t)),e.duration=t=>e.check(rh(t))});function xh(e){return xp(bh,e)}const Sh=Q(`ZodStringFormat`,(e,t)=>{lf.init(e,t),yh.init(e,t)}),Ch=Q(`ZodEmail`,(e,t)=>{ff.init(e,t),Sh.init(e,t)}),wh=Q(`ZodGUID`,(e,t)=>{uf.init(e,t),Sh.init(e,t)}),Th=Q(`ZodUUID`,(e,t)=>{df.init(e,t),Sh.init(e,t)}),Eh=Q(`ZodURL`,(e,t)=>{pf.init(e,t),Sh.init(e,t)}),Dh=Q(`ZodEmoji`,(e,t)=>{mf.init(e,t),Sh.init(e,t)}),Oh=Q(`ZodNanoID`,(e,t)=>{hf.init(e,t),Sh.init(e,t)}),kh=Q(`ZodCUID`,(e,t)=>{gf.init(e,t),Sh.init(e,t)}),Ah=Q(`ZodCUID2`,(e,t)=>{_f.init(e,t),Sh.init(e,t)}),jh=Q(`ZodULID`,(e,t)=>{vf.init(e,t),Sh.init(e,t)}),Mh=Q(`ZodXID`,(e,t)=>{yf.init(e,t),Sh.init(e,t)}),Nh=Q(`ZodKSUID`,(e,t)=>{bf.init(e,t),Sh.init(e,t)}),Ph=Q(`ZodIPv4`,(e,t)=>{Tf.init(e,t),Sh.init(e,t)}),Fh=Q(`ZodIPv6`,(e,t)=>{Ef.init(e,t),Sh.init(e,t)}),Ih=Q(`ZodCIDRv4`,(e,t)=>{Df.init(e,t),Sh.init(e,t)}),Lh=Q(`ZodCIDRv6`,(e,t)=>{Of.init(e,t),Sh.init(e,t)}),Rh=Q(`ZodBase64`,(e,t)=>{Af.init(e,t),Sh.init(e,t)}),zh=Q(`ZodBase64URL`,(e,t)=>{Mf.init(e,t),Sh.init(e,t)}),Bh=Q(`ZodE164`,(e,t)=>{Nf.init(e,t),Sh.init(e,t)}),Vh=Q(`ZodJWT`,(e,t)=>{Ff.init(e,t),Sh.init(e,t)}),Hh=Q(`ZodNumber`,(e,t)=>{If.init(e,t),vh.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Mm(e,t,n,r),e.gt=(t,n)=>e.check(tm(t,n)),e.gte=(t,n)=>e.check(nm(t,n)),e.min=(t,n)=>e.check(nm(t,n)),e.lt=(t,n)=>e.check($p(t,n)),e.lte=(t,n)=>e.check(em(t,n)),e.max=(t,n)=>e.check(em(t,n)),e.int=t=>e.check(Gh(t)),e.safe=t=>e.check(Gh(t)),e.positive=t=>e.check(tm(0,t)),e.nonnegative=t=>e.check(nm(0,t)),e.negative=t=>e.check($p(0,t)),e.nonpositive=t=>e.check(em(0,t)),e.multipleOf=(t,n)=>e.check(rm(t,n)),e.step=(t,n)=>e.check(rm(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 Uh(e){return Jp(Hh,e)}const Wh=Q(`ZodNumberFormat`,(e,t)=>{Lf.init(e,t),Hh.init(e,t)});function Gh(e){return Yp(Wh,e)}const Kh=Q(`ZodBoolean`,(e,t)=>{Rf.init(e,t),vh.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Nm(e,t,n,r)});function qh(e){return Xp(Kh,e)}const Jh=Q(`ZodUnknown`,(e,t)=>{zf.init(e,t),vh.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function Yh(){return Zp(Jh)}const Xh=Q(`ZodNever`,(e,t)=>{Bf.init(e,t),vh.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Pm(e,t,n,r)});function Zh(e){return Qp(Xh,e)}const Qh=Q(`ZodArray`,(e,t)=>{Hf.init(e,t),vh.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Rm(e,t,n,r),e.element=t.element,e.min=(t,n)=>e.check(am(t,n)),e.nonempty=t=>e.check(am(1,t)),e.max=(t,n)=>e.check(im(t,n)),e.length=(t,n)=>e.check(om(t,n)),e.unwrap=()=>e.element});function $h(e,t){return ym(Qh,e,t)}const eg=Q(`ZodObject`,(e,t)=>{qf.init(e,t),vh.init(e,t),e._zod.processJSONSchema=(t,n,r)=>zm(e,t,n,r),vu(e,`shape`,()=>t.shape),e.keyof=()=>sg(Object.keys(e._zod.def.shape)),e.catchall=t=>e.clone({...e._zod.def,catchall:t}),e.passthrough=()=>e.clone({...e._zod.def,catchall:Yh()}),e.loose=()=>e.clone({...e._zod.def,catchall:Yh()}),e.strict=()=>e.clone({...e._zod.def,catchall:Zh()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=t=>Iu(e,t),e.safeExtend=t=>Lu(e,t),e.merge=t=>Ru(e,t),e.pick=t=>Pu(e,t),e.omit=t=>Fu(e,t),e.partial=(...t)=>zu(ug,e,t[0]),e.required=(...t)=>Bu(bg,e,t[0])});function tg(e,t){return new eg({type:`object`,shape:e??{},...ju(t)})}const ng=Q(`ZodUnion`,(e,t)=>{Yf.init(e,t),vh.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Bm(e,t,n,r),e.options=t.options});function rg(e,t){return new ng({type:`union`,options:e,...ju(t)})}const ig=Q(`ZodIntersection`,(e,t)=>{Xf.init(e,t),vh.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Vm(e,t,n,r)});function ag(e,t){return new ig({type:`intersection`,left:e,right:t})}const og=Q(`ZodEnum`,(e,t)=>{$f.init(e,t),vh.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Fm(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 og({...t,checks:[],...ju(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 og({...t,checks:[],...ju(r),entries:i})}});function sg(e,t){return new og({type:`enum`,entries:Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e,...ju(t)})}const cg=Q(`ZodTransform`,(e,t)=>{ep.init(e,t),vh.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Lm(e,t,n,r),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new cu(e.constructor.name);n.addIssue=r=>{if(typeof r==`string`)n.issues.push(Ku(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(Ku(t))}};let i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n)):(n.value=i,n)}});function lg(e){return new cg({type:`transform`,transform:e})}const ug=Q(`ZodOptional`,(e,t)=>{np.init(e,t),vh.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ym(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function dg(e){return new ug({type:`optional`,innerType:e})}const fg=Q(`ZodExactOptional`,(e,t)=>{rp.init(e,t),vh.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ym(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function pg(e){return new fg({type:`optional`,innerType:e})}const mg=Q(`ZodNullable`,(e,t)=>{ip.init(e,t),vh.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Hm(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function hg(e){return new mg({type:`nullable`,innerType:e})}const gg=Q(`ZodDefault`,(e,t)=>{ap.init(e,t),vh.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Wm(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function _g(e,t){return new gg({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():Du(t)}})}const vg=Q(`ZodPrefault`,(e,t)=>{sp.init(e,t),vh.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Gm(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function yg(e,t){return new vg({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():Du(t)}})}const bg=Q(`ZodNonOptional`,(e,t)=>{cp.init(e,t),vh.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Um(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function xg(e,t){return new bg({type:`nonoptional`,innerType:e,...ju(t)})}const Sg=Q(`ZodCatch`,(e,t)=>{up.init(e,t),vh.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Km(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Cg(e,t){return new Sg({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:()=>t})}const wg=Q(`ZodPipe`,(e,t)=>{dp.init(e,t),vh.init(e,t),e._zod.processJSONSchema=(t,n,r)=>qm(e,t,n,r),e.in=t.in,e.out=t.out});function Tg(e,t){return new wg({type:`pipe`,in:e,out:t})}const Eg=Q(`ZodReadonly`,(e,t)=>{pp.init(e,t),vh.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Jm(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Dg(e){return new Eg({type:`readonly`,innerType:e})}const Og=Q(`ZodCustom`,(e,t)=>{hp.init(e,t),vh.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Im(e,t,n,r)});function kg(e,t={}){return bm(Og,e,t)}function Ag(e){return xm(e)}fn(`@x-otto/provider:tool-roundtrip`),fn(`@x-otto/provider:openai-usage`),fn(`@x-otto/provider:stream-state`),fn(`@x-otto/provider:chat-completions-stream`),fn(`@x-otto/provider:oauth:templates`);var jg=class{entries=new Map;sources=new Map;reserved;constructor(e={}){this.reserved=new Set(e.reserved??[])}register(e,t,n){if(this.reserved.has(e))return!1;let r=this.sources.get(e);return n!==void 0&&this.entries.has(e)&&r!==n?!1:(this.entries.set(e,t),n===void 0?this.sources.delete(e):this.sources.set(e,n),!0)}replace(e,t,n){this.entries.set(e,t),this.sources.set(e,n)}unregister(e){this.entries.delete(e),this.sources.delete(e)}unregisterBySource(e,t){let n=[];for(let[r,i]of[...this.sources.entries()])i===e&&!t?.has(r)&&(this.entries.delete(r),this.sources.delete(r),n.push(r));return n}get(e){return this.entries.get(e)}getSource(e){return this.sources.get(e)}has(e){return this.entries.has(e)}list(){return[...this.entries.keys()]}all(){return[...this.entries.entries()]}getKeysBySource(e){return[...this.sources.entries()].filter(([,t])=>t===e).map(([e])=>e)}markReserved(e){this.reserved.add(e)}isReserved(e){return this.reserved.has(e)}get size(){return this.entries.size}};fn(`@x-otto/ai:model-registry`),tg({id:xh().min(1),name:xh().min(1),api:xh().min(1),provider:xh().min(1),baseUrl:xh().min(1),reasoning:qh(),input:$h(sg([`text`,`image`])).min(1),cost:tg({input:Uh(),output:Uh(),cacheRead:Uh(),cacheWrite:Uh()}).optional(),contextWindow:Uh().int().positive(),maxOutputTokens:Uh().int().positive(),thinkingLevels:$h(sg([`low`,`medium`,`high`,`xhigh`,`max`])).optional(),thinkingMode:sg([`enabled`,`adaptive`]).optional()});const Mg=[];new Map(Mg.map(e=>[e.id,e])),new jg({reserved:new Set(Mg.map(e=>e.id))}),Object.fromEntries(Mg.filter(e=>e.env).map(e=>[e.id,e.env])),Mg.filter(e=>e.oauth).map(e=>e.id),fn(`@x-otto/ai:model-fetch`),xn(process.env.OTTO_MODEL_FETCH_TIMEOUT_MS,1e4),fn(`@x-otto/ai:model-catalog`),fn(`@x-otto/ai:oauth-refresh-coordinator`),fn(`@x-otto/ai:auth-watcher`),fn(`@x-otto/ai:auth-store`);const Ng=[{id:`chat.message.before`,kind:`interceptor`},{id:`chat.message.after`,kind:`interceptor`},{id:`tool.execute.before`,kind:`interceptor`},{id:`tool.execute.after`,kind:`interceptor`},{id:`messages.transform`,kind:`interceptor`},{id:`chat.params`,kind:`interceptor`},{id:`system.prompt.transform`,kind:`interceptor`},{id:`session.created`,kind:`observer`},{id:`session.restored`,kind:`observer`},{id:`session.deleted`,kind:`observer`},{id:`session.idle`,kind:`observer`},{id:`session.error`,kind:`observer`},{id:`stream.start`,kind:`observer`},{id:`stream.end`,kind:`observer`},{id:`compaction.before`,kind:`observer`},{id:`compaction.after`,kind:`observer`},{id:`memory.prune.before`,kind:`interceptor`},{id:`process.spawned`,kind:`observer`},{id:`process.exited`,kind:`observer`},{id:`task.created`,kind:`observer`},{id:`task.started`,kind:`observer`},{id:`task.completed`,kind:`observer`},{id:`task.failed`,kind:`observer`},{id:`task.cancelled`,kind:`observer`},{id:`notification`,kind:`observer`}];Ng.map(e=>e.id),new Set(Ng.filter(e=>e.kind===`interceptor`).map(e=>e.id)),fn(`@x-otto/hooks:stream-metrics`),fn(`@x-otto/hooks:compaction`),fn(`@x-otto/hooks:tool-error-tracker`),fn(`@x-otto/hooks:token-budget`),fn(`@x-otto/hooks`),xn(process.env.OTTO_HOOK_TIMEOUT_MS,5e3),fn(`@x-otto/hooks:permission`);const Pg=process.emitWarning;process.emitWarning=function(e,...t){if(!(typeof e==`string`&&e.includes(`SQLite is an experimental feature`)))return Pg.call(process,e,...t)},Sn.O_DSYNC==null?Sn.O_WRONLY|Sn.O_CREAT|Sn.O_APPEND:Sn.O_WRONLY|Sn.O_CREAT|Sn.O_APPEND|Sn.O_DSYNC,[`You are a sub-agent: do not interact with the user directly; do not expand the task scope; on completion, report your conclusion and any remaining risks.`].join(`
92
92
  `);const Fg=`[a-zA-Z0-9][a-zA-Z0-9-]*`;RegExp(`<!--\\s*requires-capability:\\s*(${Fg})\\s*-->([\\s\\S]*?)<!--\\s*/requires-capability\\s*-->`,`g`),RegExp(`<!--\\s*requires-capability:\\s*(${Fg})\\s*-->`,`g`),Nn(jn(Un(import.meta.url)),`..`,`prompts`),xn(process.env.OTTO_SESSION_IDLE_TIMEOUT_MS,1800*1e3),xn(process.env.OTTO_SESSION_MAX,50),xn(process.env.OTTO_SESSION_PAGE_SIZE,20),xn(process.env.OTTO_SESSION_SNAPSHOT_VERSION,1);const Ig=[{id:`loop.start`,category:`agent_work_loop`,label:`Loop Start`,pausable:!0,traceable:!0},{id:`model.before`,category:`agent_work_loop`,label:`Model Before`,pausable:!0},{id:`model.after`,category:`agent_work_loop`,label:`Model After`,pausable:!0},{id:`tool.before`,category:`agent_work_loop`,label:`Tool Before`,pausable:!0},{id:`tool.after`,category:`agent_work_loop`,label:`Tool After`,pausable:!0},{id:`loop.end`,category:`agent_work_loop`,label:`Loop End`,pausable:!0,traceable:!0},{id:`loop.cleanup`,category:`agent_work_loop`,label:`Loop Cleanup`,pausable:!0},{id:`agent.aborted`,category:`agent_work_loop`,label:`Agent Aborted`,pausable:!0,traceable:!0},{id:`agent.error`,category:`agent_work_loop`,label:`Agent Error`,pausable:!0,traceable:!0},{id:`agent.done`,category:`agent_work_loop`,label:`Agent Done`,pausable:!0,traceable:!0},{id:`steering.check`,category:`work_loop_injection`,label:`Steering Check`,pausable:!0},{id:`follow.up.check`,category:`work_loop_injection`,label:`Follow Up Check`,pausable:!0},{id:`context.transform`,category:`work_loop_injection`,label:`Context Transform`,pausable:!0},{id:`tool.resolve`,category:`tool_executor`,label:`Tool Resolve`,pausable:!0},{id:`tool.validate`,category:`tool_executor`,label:`Tool Validate`,pausable:!0},{id:`tool.hook.before`,category:`tool_executor`,label:`Tool Hook Before`,pausable:!0},{id:`tool.hook.after`,category:`tool_executor`,label:`Tool Hook After`,pausable:!0},{id:`prompt.before`,category:`session_prompt_lifecycle`,label:`Prompt Before`,pausable:!0,traceable:!0},{id:`prompt.after`,category:`session_prompt_lifecycle`,label:`Prompt After`,pausable:!0,traceable:!0},{id:`context.build`,category:`session_prompt_lifecycle`,label:`Context Build`,pausable:!0,traceable:!0},{id:`messages.persist`,category:`session_prompt_lifecycle`,label:`Messages Persist`,pausable:!0,traceable:!0},{id:`memory.prune`,category:`work_loop_injection`,label:`Memory Prune`,traceable:!0},{id:`memory.archive`,category:`session_prompt_lifecycle`,label:`Memory Archive`,traceable:!0},{id:`stream.ttft`,category:`agent_work_loop`,label:`Stream First Token Latency`,traceable:!0},{id:`chat.message.before`,category:`lifecycle_hook`,label:`Chat Message Before`,hook:`interceptor`},{id:`chat.message.after`,category:`lifecycle_hook`,label:`Chat Message After`,hook:`interceptor`},{id:`chat.params`,category:`lifecycle_hook`,label:`Chat Params`,hook:`interceptor`},{id:`system.prompt.transform`,category:`lifecycle_hook`,label:`System Prompt Transform`,hook:`interceptor`},{id:`messages.transform`,category:`lifecycle_hook`,label:`Messages Transform`,hook:`interceptor`},{id:`tool.execute.before`,category:`lifecycle_hook`,label:`Tool Execute Before`,hook:`interceptor`},{id:`tool.execute.after`,category:`lifecycle_hook`,label:`Tool Execute After`,hook:`interceptor`},{id:`memory.prune.before`,category:`lifecycle_hook`,label:`Memory Prune Before`,hook:`interceptor`},{id:`session.idle`,category:`lifecycle_hook`,label:`Session Idle`,hook:`observer`},{id:`session.error`,category:`lifecycle_hook`,label:`Session Error`,hook:`observer`},{id:`status.change`,category:`turn_observable`,label:`Status Change`,observable:!0},{id:`turn.start`,category:`turn_observable`,label:`Turn Start`,observable:!0,traceable:!0},{id:`turn.end`,category:`turn_observable`,label:`Turn End`,observable:!0,traceable:!0},{id:`stream.event`,category:`turn_observable`,label:`Stream Event`,observable:!0,traceable:!0},{id:`tool.call.start`,category:`turn_observable`,label:`Tool Call Start`,observable:!0,traceable:!0},{id:`tool.call.end`,category:`turn_observable`,label:`Tool Call End`,observable:!0,traceable:!0},{id:`steering.injected`,category:`turn_observable`,label:`Steering Injected`,observable:!0},{id:`follow.up.start`,category:`turn_observable`,label:`Follow Up Start`,observable:!0},{id:`max.turns`,category:`turn_observable`,label:`Max Tool Turns Reached`,observable:!0,traceable:!0},{id:`progress.stall`,category:`turn_observable`,label:`Progress Stall Detected`,observable:!0,traceable:!0},{id:`tool.call.mismatch`,category:`turn_observable`,label:`Tool Call Protocol Mismatch`,observable:!0,traceable:!0},{id:`prompt.budget`,category:`turn_observable`,label:`Prompt Budget Exceeded`,observable:!0,traceable:!0},{id:`compaction.reactive`,category:`turn_observable`,label:`Reactive Compaction`,observable:!0,traceable:!0},{id:`image.cap`,category:`turn_observable`,label:`Image Cap`,traceable:!0},{id:`image.vision-gate`,category:`turn_observable`,label:`Vision Capability Gate`,traceable:!0},{id:`image.vision-delegate`,category:`turn_observable`,label:`Vision Delegation Result`,observable:!0,traceable:!0},{id:`image.degradation`,category:`turn_observable`,label:`Image Degradation`,observable:!0,traceable:!0},{id:`process.memory.sample`,category:`turn_observable`,label:`Process Memory Sample`,traceable:!0},{id:`stream.retry`,category:`turn_observable`,label:`Stream Retry`,observable:!0,traceable:!0},{id:`stream.retry.accelerated`,category:`turn_observable`,label:`Stream Retry Accelerated`,observable:!0,traceable:!0},{id:`turn.truncated`,category:`turn_observable`,label:`Turn Truncated`,observable:!0,traceable:!0},{id:`rate.limit.exhausted`,category:`turn_observable`,label:`Rate Limit Exhausted`,observable:!0,traceable:!0},{id:`stream.auth-failed`,category:`turn_observable`,label:`Stream Auth Failed`,observable:!0,traceable:!0},{id:`error`,category:`turn_observable`,label:`Error`,observable:!0},{id:`abort`,category:`turn_observable`,label:`Abort`,observable:!0},{id:`lifecycle.tool.completed`,category:`turn_observable`,label:`Lifecycle Tool Completed`,observable:!0},{id:`lifecycle.tool.completed.crossBoundary`,category:`turn_observable`,label:`Lifecycle Tool Completed (Cross Prompt Boundary)`,observable:!0},{id:`lifecycle.tool.timeout`,category:`turn_observable`,label:`Lifecycle Tool Timeout`,observable:!0,traceable:!0},{id:`wire.snapshot.capture`,category:`turn_observable`,label:`Wire Snapshot Capture`,traceable:!0}];Ig.filter(e=>e.hook!==void 0).map(e=>e.id),Ig.filter(e=>e.observable===!0).map(e=>e.id),Ig.filter(e=>e.traceable===!0).map(e=>e.id),Ig.filter(e=>e.pausable===!0).map(e=>({point:e.id,name:e.label,category:e.category}));const Lg={maxToolTurns:120,traceResultMaxChars:512,maxToolResultChars:1e5,minToolResultChars:2e3,promptToolResultFraction:.5,maxToolConcurrency:10,progressDistinctRatio:.5,progressSignatureCap:512,progressSignatureArgsMaxChars:1024,stallWindowTurns:8,stallRepeatThreshold:4};new class{map=new Map;set(e,t){this.map.set(e,t)}get(e){return this.map.get(e)}delete(e){this.map.delete(e)}},fn(`@x-otto/agent:tool-executor`),fn(`@x-otto/agent`);const Rg={toolGuidance:{name:`tool-guidance-injection`,priority:20,lane:`stable`,budgetBytes:2e4},skillLoopGuidance:{name:`skill-loop-guidance-injection`,priority:21,lane:`stable`,budgetBytes:2e3},environment:{name:`runtime:environment`,priority:25,lane:`stable`,budgetBytes:8e3},memoryIndex:{name:`runtime:memory-index`,priority:35,lane:`stable`,budgetBytes:24e3},skillCatalog:{name:`skill-catalog-injection`,priority:38,lane:`stable`,budgetBytes:12e3},lesson:{name:`lesson-injection`,priority:40,lane:`stable`,budgetBytes:1e4},lessonRelevantHints:{name:`lesson-relevant-hints`,priority:41,lane:`volatile`,budgetBytes:4e3},internalize:{name:`internalize-skill-injection`,priority:42,lane:`volatile`,budgetBytes:4e3},memoryDelta:{name:`memory-delta-injection`,priority:60,lane:`volatile`,budgetBytes:8e3},todoReminder:{name:`todo-reminder-injection`,priority:62,lane:`volatile`,budgetBytes:4e3},docSyncReminder:{name:`doc-sync-reminder-injection`,priority:64,lane:`volatile`,budgetBytes:4e3}};Object.values(Rg),fn(`@x-otto/runtime/hooks`),Lg.maxToolTurns;const zg=e=>{try{return process.kill(e,0),!0}catch{return!1}},Bg=(e,t)=>{try{process.kill(-e,t)}catch{try{process.kill(e,t)}catch{}}},Vg=e=>{try{Ln(`taskkill`,[`/F`,`/T`,`/PID`,`${e}`],{stdio:`ignore`,timeout:5e3})}catch{}};new class{entries=new Map;maxProcesses;graceMs;clock;spawnListeners=new Set;exitListeners=new Set;constructor(e={}){this.maxProcesses=e.maxProcesses??64,this.graceMs=e.graceMs??2e3,this.clock=e.clock??(()=>Date.now())}onSpawn(e){return this.spawnListeners.add(e),()=>this.spawnListeners.delete(e)}onExit(e){return this.exitListeners.add(e),()=>this.exitListeners.delete(e)}notify(e,t){for(let n of[...e])try{n(t)}catch{}}register(e){if(this.entries.size>=this.maxProcesses&&this.evictLeastRecent(),this.entries.size>=this.maxProcesses)throw Error(`Background process limit (${this.maxProcesses}) reached; stop one with kill_shell first.`);let t=e.child.pid;if(t===void 0)throw Error(`Cannot register a child process without a pid`);let n=e.now??this.clock(),r={id:e.id,sessionId:e.sessionId,owner:e.owner,pid:t,pgid:t,command:e.command,cwd:e.cwd,port:e.port,url:e.url,logPath:e.logPath,startedAt:n,lastUsed:n,status:`running`,keepAlive:e.keepAlive},i={info:r,child:e.child};return this.entries.set(e.id,i),e.child.once(`exit`,e=>{r.status===`running`?(r.status=`exited`,r.exitCode=e??void 0):r.status===`killing`&&(r.status=`killed`),i.silenced||this.notify(this.exitListeners,r)}),this.notify(this.spawnListeners,r),r}get(e){return this.entries.get(e)?.info}getForSession(e,t){let n=this.entries.get(t);return n&&n.info.sessionId===e?n.info:void 0}list(){return[...this.entries.values()].map(e=>e.info)}listForSession(e){return this.list().filter(t=>t.sessionId===e)}touch(e){let t=this.entries.get(e);t&&(t.info.lastUsed=this.clock())}updateDetectedService(e,t){let n=this.entries.get(e);n&&(n.info.detectedService?.url&&!t.url||(n.info.detectedService=t))}remove(e){let t=this.entries.get(e);t&&(t.silenced=!0,this.entries.delete(e))}size(){return this.entries.size}async kill(e){let t=this.entries.get(e);t&&await this.killEntry(t)}async killAll(){await Promise.all([...this.entries.values()].map(e=>this.killEntry(e)))}async killAllForOwner(e){await Promise.all([...this.entries.values()].filter(t=>t.info.owner===e).map(e=>this.killEntry(e)))}async killAllForSession(e){await Promise.all([...this.entries.values()].filter(t=>t.info.sessionId===e).map(e=>this.killEntry(e)))}killAllSync(){for(let e of this.entries.values())this.killEntrySync(e)}killEntrySync(e){let{info:t}=e;t.status===`exited`||t.status===`killed`||(process.platform===`win32`?Vg(t.pid):Bg(t.pgid,`SIGKILL`),t.status=`killed`)}evictLeastRecent(){let e;for(let t of this.entries.values()){if(t.info.status===`exited`||t.info.status===`killed`){e=t;break}t.info.keepAlive||(!e||t.info.lastUsed<e.info.lastUsed)&&(e=t)}e&&(e.silenced=!0,this.killEntrySync(e),this.entries.delete(e.info.id))}async killEntry(e){let{info:t}=e;if(t.status===`running`){if(t.status=`killing`,process.platform===`win32`){Vg(t.pid),t.status=`killed`;return}Bg(t.pgid,`SIGTERM`),await this.waitForExit(e,this.graceMs)||Bg(t.pgid,`SIGKILL`),t.status=`killed`}}waitForExit(e,t){return new Promise(n=>{let r=!1,i,a=t=>{r||(r=!0,clearTimeout(i),e.child.removeListener(`exit`,o),n(t))},o=()=>a(!0);if(e.child.once(`exit`,o),!zg(e.info.pid)){a(!0);return}i=setTimeout(()=>a(!1),t)})}};let Hg=0;var Ug=class extends Wn{id;child;config;status=`starting`;_clock;_pid;_pgid;_exitResult=null;_exitResolve=null;_stdoutBuf=``;_stderrBuf=``;lastUsed;constructor(e,t,n){if(super(),this._clock=n,this.id=`proc_${++Hg}_${this._clock()}`,this.child=e,this.config=t,this._pid=e.pid,this._pgid=e.pid,this.lastUsed=this._clock(),this.child.on(`spawn`,()=>{this._pid=this.child.pid,this._pgid=this.child.pid,this.status===`starting`&&(this.status=`running`)}),this.child.on(`error`,e=>{this.lastUsed=this._clock(),(this.status===`starting`||this.status===`running`)&&(this.status=`errored`),this.emit(`error`,e)}),this.child.on(`exit`,(e,t)=>{this.lastUsed=this._clock();let n={code:e,signal:t,timedOut:!1};this._exitResult=n,this.status===`running`?this.status=`exited`:this.status===`killing`&&(this.status=`killed`),this.emit(`exit`,n),this._exitResolve&&=(this._exitResolve(n),null)}),this.child.stdout&&this.child.stdout.on(`data`,e=>{this.lastUsed=this._clock();let t=e.toString(`utf-8`);for(this._stdoutBuf+=t;;){let e=this._stdoutBuf.indexOf(`
93
93
  `);if(e===-1)break;let t=this._stdoutBuf.slice(0,e).replace(/\r$/,``);this._stdoutBuf=this._stdoutBuf.slice(e+1),this.emit(`stdoutLine`,t)}}),this.child.stderr&&this.child.stderr.on(`data`,e=>{this.lastUsed=this._clock();let t=e.toString(`utf-8`);for(this._stderrBuf+=t;;){let e=this._stderrBuf.indexOf(`
94
94
  `);if(e===-1)break;let t=this._stderrBuf.slice(0,e).replace(/\r$/,``);this._stderrBuf=this._stderrBuf.slice(e+1),this.emit(`stderrLine`,t)}}),t.signal){let e=()=>{this.kill({reason:`aborted`})};t.signal.aborted?e():t.signal.addEventListener(`abort`,e,{once:!0})}}get pid(){return this._pid}get pgid(){return this._pgid}get stdin(){return this.child.stdin&&!this.child.stdin.destroyed?this.child.stdin:null}get stdout(){return this.child.stdout&&!this.child.stdout.destroyed?this.child.stdout:null}get stderr(){return this.child.stderr&&!this.child.stderr.destroyed?this.child.stderr:null}onStdoutLine(e){return this.on(`stdoutLine`,e),()=>this.off(`stdoutLine`,e)}onStderrLine(e){return this.on(`stderrLine`,e),()=>this.off(`stderrLine`,e)}onExit(e){return this.on(`exit`,e),()=>this.off(`exit`,e)}onError(e){return this.on(`error`,e),()=>this.off(`error`,e)}async kill(e){if(this.status===`killed`||this.status===`exited`)return;this.status=`killing`,this.lastUsed=this._clock();let t=e?.graceMs??this.config.killGraceMs??2e3,n=this._pid,r=this._pgid;if(!n||!zg(n)){this.status=`killed`;return}if(process.platform===`win32`){Vg(n),this.status=`killed`;return}Bg(r??n,`SIGTERM`),await new Promise(e=>{let r=!1,i=t=>{r||(r=!0,clearTimeout(o),e(t))},a=()=>i(!0);if(this.child.once(`exit`,a),!zg(n)){i(!0);return}let o=setTimeout(()=>{this.child.removeListener(`exit`,a),i(!1)},t)})||Bg(r??n,`SIGKILL`),this.status=`killed`}async waitForExit(e=3e4){return this._exitResult?this._exitResult:new Promise(t=>{if(this._exitResult){t(this._exitResult);return}let n=!1,r=e=>{n||(n=!0,clearTimeout(a),this.off(`exit`,i),t(e))},i=e=>r(e);this.on(`exit`,i);let a=setTimeout(()=>{r({code:null,signal:null,timedOut:!0})},e)})}};new class{_entries=new Map;_maxProcesses;killGraceMs;killTimeoutMs;_clock;_spawnListeners=new Set;_exitListeners=new Set;constructor(e={}){this._maxProcesses=e.maxProcesses??128,this.killGraceMs=e.killGraceMs??2e3,this.killTimeoutMs=e.killTimeoutMs??3e4,this._clock=e.clock??(()=>Date.now())}onSpawn(e){return this._spawnListeners.add(e),()=>this._spawnListeners.delete(e)}onExit(e){return this._exitListeners.add(e),()=>this._exitListeners.delete(e)}onAllExited(e){let t=()=>{this._entries.size===0&&e()},n=()=>t();return this._exitListeners.add(n),t(),()=>this._exitListeners.delete(n)}spawn(e){if(this._entries.size>=this._maxProcesses&&this._evictLeastRecent(),this._entries.size>=this._maxProcesses)throw Error(`Process limit (${this._maxProcesses}) reached. Stop unused processes first.`);let t={...e.options,stdio:e.options?.stdio??[`pipe`,`pipe`,`pipe`],cwd:e.cwd??e.options?.cwd,env:dn(e.env??e.options?.env),...e.keepAlive===!0?{}:{detached:!0}},n=In(e.command,e.args??[],t),r=new Ug(n,e,this._clock);this._entries.set(r.id,{proc:r,child:n}),r.onExit(()=>{if(!this._entries.get(r.id))return;let t=e.lifecycle??`evictable`;e.keepAlive!==!0&&t!==`pinned`&&this._entries.delete(r.id);for(let e of[...this._exitListeners])try{e(r)}catch{}});for(let e of[...this._spawnListeners])try{e(r)}catch{}return r}get(e){return this._entries.get(e)?.proc}list(e){let t=[...this._entries.values()];return e?.owner&&(t=t.filter(t=>t.proc.config.owner.type===e.owner.type&&t.proc.config.owner.id===e.owner.id)),e?.sessionId&&(t=t.filter(t=>t.proc.config.sessionId===e.sessionId)),e?.category&&(t=t.filter(t=>t.proc.config.category===e.category)),t.map(e=>e.proc)}listForSession(e){return this.list({sessionId:e})}listForOwner(e){return this.list({owner:e})}touch(e){let t=this._entries.get(e);t&&(t.proc.lastUsed=this._clock())}remove(e){this._entries.delete(e)}size(){return this._entries.size}async killAll(e,t){let n=this.list(e).filter(e=>!e.config.keepAlive);await Promise.all(n.map(e=>e.kill(t)))}killAllSync(){let e=process.platform===`win32`,t=[];for(let[n,r]of this._entries){let i=r.proc;if(i.config.keepAlive||i.status!==`running`&&i.status!==`starting`)continue;let a=i.pid;a&&(e?t.push(a):Bg(i.pgid??a,`SIGKILL`),this._entries.delete(n))}if(e&&t.length>0)try{Ln(`taskkill`,[`/F`,`/T`,...t.map(String).flatMap(e=>[`/PID`,e])],{stdio:`ignore`,timeout:5e3})}catch{}}async killAllForOwner(e,t){return this.killAll({owner:{type:e,id:t}})}async killAllForSession(e){return this.killAll({sessionId:e})}registerChild(e,t){if(this._entries.size>=this._maxProcesses&&this._evictLeastRecent(),this._entries.size>=this._maxProcesses)throw Error(`Process limit (${this._maxProcesses}) reached. Stop unused processes first.`);let n=new Ug(t,e,this._clock);this._entries.set(n.id,{proc:n,child:t}),n.onExit(()=>{if(!this._entries.get(n.id))return;let t=e.lifecycle??`evictable`;e.keepAlive!==!0&&t!==`pinned`&&this._entries.delete(n.id);for(let e of[...this._exitListeners])try{e(n)}catch{}});for(let e of[...this._spawnListeners])try{e(n)}catch{}return n}_evictLeastRecent(){let e;for(let t of this._entries.values()){let n=t.proc.config,r=n.lifecycle??`evictable`;if(t.proc.status===`exited`||t.proc.status===`killed`||t.proc.status===`errored`){e=t;break}n.keepAlive||r!==`pinned`&&(!e||t.proc.lastUsed<e.proc.lastUsed)&&(e=t)}if(!e)return;let t=e.proc.pid;t&&zg(t)&&(process.platform===`win32`?Vg(t):Bg(e.proc.pgid??t,`SIGKILL`)),this._entries.delete(e.proc.id)}};function Wg(e,t){return Pn(`git`,[`-C`,e,...t],{encoding:`utf-8`,stdio:[`ignore`,`pipe`,`pipe`]}).trimEnd()}function Gg(e,t){try{Wg(e.repoRoot,[`worktree`,`remove`,`--force`,e.path])}catch(e){t?.(`worktree remove`,e)}try{Wg(e.repoRoot,[`branch`,`-D`,e.branch])}catch(e){t?.(`branch delete`,e)}try{Wg(e.repoRoot,[`worktree`,`prune`])}catch(e){t?.(`worktree prune`,e)}}const Kg=new Set([`applied`,`failed`,`canceled`]);new class{entries=new Map;maxJobs;clock;onWorktreeCleanupError;spawnListeners=new Set;updateListeners=new Set;exitListeners=new Set;removeListeners=new Set;retained=new Set;constructor(e={}){this.maxJobs=e.maxJobs??16,this.clock=e.clock??(()=>Date.now()),this.onWorktreeCleanupError=e.onWorktreeCleanupError}setWorktreeCleanupErrorHandler(e){this.onWorktreeCleanupError=e}onSpawn(e){return this.spawnListeners.add(e),()=>this.spawnListeners.delete(e)}onUpdate(e){return this.updateListeners.add(e),()=>this.updateListeners.delete(e)}onExit(e){return this.exitListeners.add(e),()=>this.exitListeners.delete(e)}onRemove(e){return this.removeListeners.add(e),()=>this.removeListeners.delete(e)}retain(e,t){t?this.retained.add(e):this.retained.delete(e)}notify(e,t){for(let n of[...e])try{n(t)}catch{}}register(e){if(this.entries.size>=this.maxJobs&&this.evictTerminal(),this.entries.size>=this.maxJobs)throw Error(`Agent job limit (${this.maxJobs}) reached; cancel one with stop first.`);let t=e.now??this.clock(),n={id:e.id,sessionId:e.sessionId,type:`agent-session`,title:e.title,origin:e.origin??`user`,status:`running`,worktree:e.worktree,outputPath:e.outputPath,startedAt:t};return this.entries.set(e.id,{info:n,abort:e.abort}),this.notify(this.spawnListeners,n),n}get(e){return this.entries.get(e)?.info}getForSession(e,t){let n=this.entries.get(t);return n&&n.info.sessionId===e?n.info:void 0}list(){return[...this.entries.values()].map(e=>e.info)}listForSession(e){return this.list().filter(t=>t.sessionId===e)}size(){return this.entries.size}update(e,t){let n=this.entries.get(e);n&&(Kg.has(n.info.status)||(Object.assign(n.info,t),this.notify(this.updateListeners,n.info),Kg.has(n.info.status)&&(n.info.status!==`canceled`&&Gg(n.info.worktree,(t,n)=>this.onWorktreeCleanupError?.(e,t,n)),this.notify(this.exitListeners,n.info))))}cancel(e){let t=this.entries.get(e);if(!(!t||Kg.has(t.info.status))){try{t.abort()}catch{}Gg(t.info.worktree,(t,n)=>this.onWorktreeCleanupError?.(e,t,n)),this.update(e,{status:`canceled`})}}remove(e){let t=this.entries.get(e);t&&Gg(t.info.worktree,(t,n)=>this.onWorktreeCleanupError?.(e,t,n)),this.retained.delete(e),this.entries.delete(e),t&&this.notify(this.removeListeners,t.info)}evictTerminal(){for(let[e,t]of this.entries)if(Kg.has(t.info.status)&&!this.retained.has(e)){this.remove(e);return}}cleanupAll(){for(let[e,t]of this.entries)if(!Kg.has(t.info.status)){try{t.abort()}catch{}Gg(t.info.worktree,(t,n)=>this.onWorktreeCleanupError?.(e,t,n)),t.info.status=`canceled`}}};const qg=new Set([`done`,`error`,`aborted`]),Jg=new Set([`edit`,`write`,`delete`,`edit_file`,`write_file`]);function Yg(e){return Jg.has(e)}new class extends un{observations=new Map;abortFns=new Map;messagesRefs=new Map;streamingTexts=new Map;turns=new Map;evictTimers=new Map;pinned=new Set;now;warnMs;stalledMs;evictMs;constructor(e={}){super(),this.now=e.now??Date.now,this.warnMs=e.warnMs??3e3,this.stalledMs=e.stalledMs??3e4,this.evictMs=e.evictMs??15e3}register(e){let t=this.now(),n=this.evictTimers.get(e.id);n&&(clearTimeout(n),this.evictTimers.delete(e.id)),e.abort&&this.abortFns.set(e.id,e.abort),e.messages&&this.messagesRefs.set(e.id,e.messages),this.streamingTexts.set(e.id,``),this.turns.set(e.id,[]),this.observations.set(e.id,{id:e.id,agentName:e.agentName,title:e.title,prompt:e.prompt,model:e.model,modelDecidedBy:e.modelDecidedBy,origin:e.origin??`main`,depth:e.depth??0,status:`streaming`,turnIndex:0,toolUseCount:0,filesEdited:0,tokenCount:0,inputTokens:0,lastActivity:`starting`,lastEventAt:t,abortable:e.abortable??e.abort!==void 0,startedAt:t}),this.emit(`change`)}abort(e){let t=this.observations.get(e),n=this.abortFns.get(e);return!t||!n||qg.has(t.status)?!1:(n(),!0)}record(e,t){let n=this.observations.get(e);if(!n)return;n.lastEventAt=this.now();let r=!0;switch(t.type){case`turn.start`:n.turnIndex=t.turnIndex,n.status=`streaming`,n.lastActivity=`thinking`,n.blockedOn=`model_io`,n.blockDetail=void 0,this.streamingTexts.set(e,``),this.turns.get(e)?.push({index:t.turnIndex,startedAt:this.now(),toolCount:0,tools:[],outputTokens:0});break;case`stream.event`:{let i=t.event;i.type===`text_delta`?(n.lastActivity=`responding`,n.blockedOn=void 0,this.streamingTexts.set(e,(this.streamingTexts.get(e)??``)+i.delta)):i.type.startsWith(`thinking`)&&(n.lastActivity=`thinking`,n.blockedOn=void 0),r=!1;break}case`tool.call.start`:{n.toolUseCount+=1,n.status=`tool_executing`,n.lastActivity=`using ${t.toolCall.name}`,n.blockedOn=`process`,n.blockDetail=t.toolCall.name;let r=this.turns.get(e);r?.length&&(r[r.length-1].toolCount+=1,r[r.length-1].tools.push(t.toolCall.name));break}case`tool.call.end`:n.status=`streaming`,n.lastActivity=`thinking`,n.blockedOn=`model_io`,n.blockDetail=void 0,Yg(t.toolCall.name)&&(n.filesEdited+=1);break;case`turn.end`:{let r=t.message.usage.outputTokens??0;n.tokenCount+=r,n.inputTokens=t.message.usage.inputTokens??n.inputTokens,this.streamingTexts.set(e,``);let i=this.turns.get(e),a=i?.[i.length-1];a&&a.endedAt===void 0&&(a.endedAt=this.now(),a.outputTokens=r);break}case`stream.retry`:n.lastActivity=`reconnecting ${t.attempt}/${t.maxRetries}`,n.blockedOn=`model_io`;break;case`status.change`:this.applyTerminal(n,t.to);break;case`error`:this.markTerminal(n,`error`);break;case`abort`:this.markTerminal(n,`aborted`);break;case`lifecycle.tool.completed`:n.lastActivity=`${t.toolName} ${t.isError?`failed`:`completed`} (background)`,n.lastEventAt=this.now(),r=!0;break;case`lifecycle.tool.completed.crossBoundary`:n.lastActivity=`${t.toolName} completed in background (result not shown — belongs to a previous prompt)`,n.lastEventAt=this.now(),r=!0;break;default:r=!1;break}r&&this.emit(`change`)}setAwaitingApproval(e,t){let n=this.observations.get(e);n&&(n.status=`awaiting_gate`,n.lastActivity=`awaiting approval`,n.blockedOn=`approval`,n.blockDetail=t,n.lastEventAt=this.now(),this.emit(`change`))}clearAwaitingApproval(e){let t=this.observations.get(e);!t||t.status!==`awaiting_gate`||(t.status=`streaming`,t.lastActivity=`thinking`,t.blockedOn=`model_io`,t.blockDetail=void 0,t.lastEventAt=this.now(),this.emit(`change`))}setToolWaiting(e,t){let n=this.observations.get(e);n&&(n.status=`tool_waiting`,n.lastActivity=t,n.blockedOn=`process`,n.blockDetail=t,n.lastEventAt=this.now(),this.emit(`change`))}clearToolWaiting(e){let t=this.observations.get(e);!t||t.status!==`tool_waiting`||(t.status=`streaming`,t.lastActivity=`thinking`,t.blockedOn=`model_io`,t.blockDetail=void 0,t.lastEventAt=this.now(),this.emit(`change`))}markEnded(e,t=`done`){let n=this.observations.get(e);!n||qg.has(n.status)||(this.markTerminal(n,t),this.emit(`change`))}pin(e){let t=this.evictTimers.get(e);t&&(clearTimeout(t),this.evictTimers.delete(e)),this.pinned.add(e)}unpin(e){this.pinned.delete(e);let t=this.observations.get(e);t&&t.endedAt!==void 0&&this.scheduleEvict(e)}remove(e){let t=this.evictTimers.get(e);t&&(clearTimeout(t),this.evictTimers.delete(e)),this.observations.delete(e),this.abortFns.delete(e),this.messagesRefs.delete(e),this.streamingTexts.delete(e),this.turns.delete(e),this.pinned.delete(e),this.emit(`change`)}get(e){let t=this.observations.get(e);return t?this.toSnapshot(t):void 0}getMessages(e){let t=this.messagesRefs.get(e);if(t)return[...typeof t==`function`?t():t]}setMessages(e,t){this.messagesRefs.has(e)&&this.messagesRefs.set(e,[...t])}getStreamingText(e){return this.streamingTexts.get(e)??``}getTurns(e){let t=this.turns.get(e);return t?t.map(e=>({...e,tools:[...e.tools]})):[]}list(){return[...this.observations.values()].map(e=>this.toSnapshot(e))}listActive(){return this.list().filter(e=>!qg.has(e.status))}subscribe(e){return this.on(`change`,e)}clear(){for(let e of this.evictTimers.values())clearTimeout(e);this.evictTimers.clear(),this.observations.clear(),this.abortFns.clear(),this.messagesRefs.clear(),this.streamingTexts.clear(),this.turns.clear(),this.pinned.clear()}applyTerminal(e,t){t===`completed`?this.markTerminal(e,`done`):t===`error`?this.markTerminal(e,`error`):t===`aborted`&&this.markTerminal(e,`aborted`)}markTerminal(e,t){e.status=t,e.lastActivity=t,e.blockedOn=void 0,e.blockDetail=void 0,e.endedAt=this.now(),this.scheduleEvict(e.id)}scheduleEvict(e){if(this.pinned.has(e))return;let t=this.evictTimers.get(e);t&&clearTimeout(t);let n=setTimeout(()=>{this.observations.delete(e),this.evictTimers.delete(e),this.abortFns.delete(e),this.messagesRefs.delete(e),this.streamingTexts.delete(e),this.turns.delete(e),this.emit(`change`)},this.evictMs);n.unref?.(),this.evictTimers.set(e,n)}toSnapshot(e){let t=e.endedAt!==void 0,n=t?0:Math.max(0,this.now()-e.lastEventAt),r=t?`none`:n>this.stalledMs?`stalled`:n>this.warnMs?`warn`:`none`;return{...e,idleMs:n,stall:r}}};const Xg={"tool-guidance-injection":`Tool guidance`,"skill-loop-guidance-injection":`Skill loop guidance`,"runtime:environment":`Environment`,"runtime:memory-index":`Memory index`,"skill-catalog-injection":`Skill catalog`,"lesson-injection":`Lesson`,"lesson-relevant-hints":`Lesson relevant hints`,"internalize-skill-injection":`Internalize`,"memory-delta-injection":`Memory delta`,"todo-reminder-injection":`TODO reminder`,"doc-sync-reminder-injection":`Doc sync reminder`},Zg=Object.values(Rg).map(e=>({name:e.name,label:Xg[e.name]??e.name,lane:e.lane,priority:e.priority}));function Qg(e){let t=Zg.length,n=Math.round(e/t);return Zg.map(e=>({label:e.label,lane:e.lane,estimatedTokens:n}))}function $g(){let e=sr({open:!1,conversationTurns:[],systemSections:[],modelName:``,contextWindow:0,contextPercent:0,totalUsed:0,free:0});return{store:e,toggle(t){e.setState({open:t??!e.getState().open})},reset(){e.setState({open:!1,conversationTurns:[],systemSections:[],modelName:``,contextWindow:0,contextPercent:0,totalUsed:0,free:0})},addTurn(t){let n=[...e.getState().conversationTurns,t];e.setState({conversationTurns:n.length>Vn?n.slice(n.length-Vn):n})},markTurns(t){let{turnIndex:n,...r}=t,i=e.getState().conversationTurns.map(e=>e.turnIndex===n?{...e,...r}:e);e.setState({conversationTurns:i})},setBudget(t){e.setState({modelName:t.modelName,contextWindow:t.contextWindow,contextPercent:t.contextPercent,totalUsed:t.totalUsed,free:t.free,systemSections:Qg(t.overheadTokens)})}}}const e_=Kt(void 0),t_=e_.Provider;function n_(){let e=Jt(e_);if(!e)throw Error(`useAppStoresContext must be used within <AppStoresProvider>`);return e}const r_=[`/pane/tasks`,`/pane/delegates`,`/pane/edited-files`,`/pane/subagents`,`/pane/schedule`,`/pane/clipboard`];function i_(e){return r_.includes(e)}const a_=[`taskFocus`,`background`,`editedFiles`,`subagents`,`schedule`,`clipboard`];function o_(e){return i_(e)||e===`/overlay/paste-confirm`}function s_(e){return e===`/`||i_(e)||e===`/overlay/paste-confirm`}function c_(e){return e===`prompt`||a_.includes(e)}function l_(){L()?.navigate(`/`,{reset:!0})}function u_(){let{currentPath:e}=_e();return e===`/`?`prompt`:e===`/home`?`home`:e===`/pane/delegates`||e===`/pane/delegates/output`?`background`:e===`/pane/edited-files`?`editedFiles`:e.startsWith(`/pane/edited-files/`)?`editedFileFull`:e===`/subagent`?`subagentContext`:e===`/pane/subagents`?`subagents`:e===`/pane/clipboard`?`clipboard`:e===`/pane/schedule`?`schedule`:e===`/pane/tasks`?`taskFocus`:e.startsWith(`/pane/tasks/`)?`taskDetail`:e===`/pane/draft`?`draft`:e===`/pane/queue`?`queue`:e.startsWith(`/pane/queue/`)?`queueEdit`:e===`/pane/shell`?`shell`:e===`/pane/sigil`?`sigilPane`:e===`/pane/perf`?`perf`:e===`/pane/cache`?`cacheStats`:e===`/pane/compaction-log`?`compactionLog`:e===`/pane/gallery`?`gallery`:e===`/pane/notifications`?`notifications`:e===`/pane/proxy`?`proxy`:e===`/pane/prompts`?`prompts`:e===`/pane/context`?`info`:(e.startsWith(`/dialog/`)||e.startsWith(`/viewer/`),`prompt`)}const d_=`onA2uiAction.onAlertResolve.onBackToContextPane.onBackgroundApply.onBackgroundClose.onBackgroundDelete.onBackgroundKill.onBackgroundOutputClose.onBackgroundSwitch.onBackgroundViewOutput.onCacheDismiss.onCancelUpgrade.onCloseNotifications.onCompactionLogDismiss.onContextDismiss.onConfirmResolve.onCyclePermissionMode.onDelegateSupply.onDismissNotification.onDismissToast.onDraftDelete.onDraftDeleteMany.onDraftSave.onErrorRetryFocusChange.onExitSubagentContext.onFocusOwnerChange.onScrollActiveChange.onGalleryDismiss.onHistoryPush.onInfoDismiss.onInputAction.onInputResolve.onOnboardingResolve.onInterrupt.onKeybindingPanelDismiss.onMemoryDismiss.onPaneOwnsViewportChange.onPerfDismiss.onPerfRefresh.onPermissionDecision.onPopQueued.onPromptResolve.onProxyClear.onProxyTest.onProxyDismiss.onProxyOpenModal.onProxySubmitUrl.onProxyToggleEnabled.onPulseSurveyChange.onQuestionsResolve.onQueueDelete.onQueueEditText.onQueueMove.onQueueSendNow.onSelectResolve.onSessionSelect.onInstallCapability.onDismissCapabilityRecommendations.onShellAbort.onShellAskAi.onShellCopyOutput.onShellDismiss.onShortcutsDialogDismiss.onSigilSelect.onSubmit.onToast.onToggleDelegates.onToggleDraftPane.onToggleEditedFiles.onToggleNotifications.onToggleQueuePane.onTogglePrompts.onToggleSchedule.onToggleSubagents.onUpgrade.onViewDetails.onWithdrawPending.onWithdrawSteer`.split(`.`);function f_(e){let t={};for(let n of d_)t[n]=e[n];return t}const p_=Kt(null),m_=p_.Provider;function h_(){let e=Jt(p_);if(!e)throw Error(`useAppCallbacks must be used within AppCallbacksProvider`);return e}function g_(e){let{queuedItemsLength:t,subagentContext:n,backgroundOutput:r}=e,{onPaneOwnsViewportChange:i}=h_(),{currentPath:a}=_e(),[o,s]=G(null),[c,l]=G(null),[u,d]=G(null),[f,p]=G(null),m=qt(e=>{p(e),e?L()?.ensure(`/viewer/shell-output`):L()?.goBack()},[]),[h,g]=G(null),[_,v]=G(!1),[y,b]=G(!1),[x,S]=G(!1),[C,w]=G(!1),[ee,T]=G(``),E=!!n||o!==null||!!r||u!=null,te=qt(e=>{i?.(!0),s(e),l(e.path),L()?.ensure(`/pane/edited-files/full`)},[i]),ne=qt(()=>{i?.(u!=null),s(null),l(null),L()?.goBack()},[i,u]),re=qt(e=>{i?.(!0),d(e),L()?.ensure(`/pane/tasks/${e}`)},[i]),ie=qt(()=>{i?.(o!==null),d(null),L()?.goBack()},[i,o]);return U(()=>{let e=a.startsWith(`/pane/edited-files/`);!e&&o!==null&&(s(null),l(null));let t=a.startsWith(`/pane/tasks/`)?u:null;t!==u&&d(t),t!==u&&i?.(e||t!=null),h!==null&&a!==`/pane/queue/edit`&&(g(null),v(!1),b(!1)),f&&!a.startsWith(`/viewer/shell-output`)&&p(null)},[a,o,i,h,f,u]),U(()=>{h!==null&&h>=t&&(g(null),v(!1),b(!1),a===`/pane/queue/edit`&&L()?.goBack())},[a,h,t]),{editedFileFull:o,editedFileFullPath:c,openEditedFileFull:te,closeEditedFileFull:ne,taskDetailTurn:u,openTaskDetail:re,closeTaskDetail:ie,shellFullOutput:f,setShellFullOutput:m,queueEditIndex:h,setQueueEditIndex:g,queueCloseConfirm:_,setQueueCloseConfirm:v,queueEscSuppress:y,setQueueEscSuppress:b,interruptConfirm:x,setInterruptConfirm:S,popQueuedConfirm:C,setPopQueuedConfirm:w,supplyDraft:ee,setSupplyDraft:T,fullScreenPaneActive:E}}let __=null;function v_(e){__=e}function y_(){let e=__;return e?.hasSelection()?(e.clear(),!0):!1}function b_(e,t){let n=e.getState().offset;return e.subscribe(()=>{let r=e.getState().offset;r!==n&&(n=r,t())})}function x_(e){let{showHome:t,tasksLength:n,backgroundTasksLength:r,editedFilesLength:i,subagentsLength:a,servicesCount:o,clipboardHasContent:s,shellExecutionRunning:c,routeDerivedOwner:l,currentPath:u,backgroundOutput:d,a2uiButtons:f,scrollOffset:p,editedFilesOpen:m,subagentsOpen:h,setTasksCollapsed:g,keybindingOverrides:_,promptSuggestions:v,onFillPromptSuggestion:y,isPromptDraftEmpty:b,capabilityCardShown:S,capabilityItemIds:C,onInstallCapability:w,onDismissCapabilityRecommendations:ee}=e,{onToggleDelegates:T,onToggleEditedFiles:E,onToggleSubagents:te,onToggleDraftPane:ne,onToggleQueuePane:re,onShellAbort:ie,onInterrupt:ae,onA2uiAction:oe,onCyclePermissionMode:D,onToggleNotifications:se,onSubmit:O}=h_(),ce=qt(()=>{let e=L();e&&e.currentPath!==`/`&&e.navigate(`/`,{reset:!0})},[]),ue=qt(e=>{let t=L();if(!t)return!1;let c=t.currentPath===`/home`?`/`:t.currentPath,l=[...n>0?[{path:`/pane/tasks`,activate:()=>{g(()=>!1),t.navigate(`/pane/tasks`,{replace:!0})}}]:[],...r>0?[{path:`/pane/delegates`,activate:()=>{T?.()}}]:[],...o>0?[{path:`/overlay/services`,activate:()=>{t.ensure(`/overlay/services`)}}]:[],...i>0?[{path:`/pane/edited-files`,activate:()=>{E?.()}}]:[],...a>0?[{path:`/pane/subagents`,activate:()=>{te?.()}}]:[],...s?[{path:`/pane/clipboard`,activate:()=>{t.navigate(`/pane/clipboard`,{replace:!0})}}]:[],{path:`/`,activate:()=>ce()}];return l.length<=1?!1:(l[(Math.max(0,l.findIndex(e=>c===e.path||c.startsWith(e.path+`/`)))+e+l.length)%l.length]?.activate(),!0)},[r,ce,i,T,E,te,a,n,s,o,g]);Lt(`app-global-prelude`,(e,t)=>t.ctrl&&e===`c`?c?(ie?.(),!0):(ae?.(),!0):!1),ge(`selection-escape`,(e,t)=>!t.escape||t.ctrl||t.meta||t.shift?!1:o_(u)?(y_(),!1):y_()),x(`app-prompt-global`,(e,r)=>{if(r.tab&&!r.ctrl&&!r.meta&&!r.shift)return u.startsWith(`/dialog/`)||u.startsWith(`/viewer/`)||St(u)||![`prompt`,`home`,`taskFocus`,`background`,`editedFiles`,`subagents`,`schedule`,`draft`,`queue`,`clipboard`].includes(l)||u===`/pane/delegates`&&d?!1:ue(r.shift?-1:1);let i=b?.()??!0;if(i&&p===0&&f&&f.length>0&&e>=`1`&&e<=`9`&&!r.ctrl&&!r.meta){let t=f.find(t=>t.key===e);if(t&&oe)return oe(t.componentId,t.action,t.payload),!0}if(i&&t&&v&&v.length>0&&e>=`1`&&e<=`9`&&!r.ctrl&&!r.meta){let t=v[Number(e)-1];if(t&&y)return y(t),!0}if(i&&t&&S&&C&&C.length>0&&!r.ctrl&&!r.meta){if(e===`0`)return ee?.(),!0;if(e>=`1`&&e<=`9`){let t=C[Number(e)-1];if(t&&w)return w(t),!0}}if(u===`/`&&r.ctrl&&e===`k`)return!1;let a=rt(Ve,l,e,r,_);if(a===`smart-close`)return u===`/pane/tasks`?(l_(),!0):m?(E?.(),!0):h?(te?.(),!0):(n>0?(g(()=>!1),L()?.navigate(`/pane/tasks`,{replace:!0})):g(e=>!e),!0);let o={"cycle-permission-mode":()=>{D?.()},"toggle-notifications":()=>{se?.()},"toggle-edited-files":()=>{E?.()},"toggle-subagents":()=>{te?.()},"toggle-delegates":()=>{T?.()},"toggle-clipboard":()=>{if(u===`/pane/clipboard`){l_();return}s&&L()?.navigate(`/pane/clipboard`,{replace:!0})},"toggle-draft-pane":()=>{ne?.()},"toggle-queue-pane":()=>{re?.()},"open-keybinding-panel":()=>{O?.(`/keybindings`,`send`)}};return a&&o[a]?(o[a](),!0):!1});let k=le();tn((e,t)=>{k.dispatch(e,t)})}function S_(e){let t=e>=60,n=e>=76,r=e>=100;return{modelName:!0,occupancyBar:!0,hintText:!0,permissionMode:t,perfIndicator:t,notificationBell:t,scheduleIndicator:t,cost:n,providerUsage:n,language:n,pluginStatusItems:r,liveClock:r}}const C_={narrow:0,medium:1,low:2};function w_(e){return e.map((e,t)=>({entry:e,index:t})).sort((e,t)=>{let n=C_[e.entry.tier]-C_[t.entry.tier];if(n!==0)return n;if(e.entry.isHost!==t.entry.isHost)return e.entry.isHost?-1:1;let r=(e.entry.order??0)-(t.entry.order??0);return r===0?e.index-t.index:r}).map(e=>e.entry)}const T_=new Map;function E_(e){let t=T_.get(e);return t||(t={consecutiveSlowCalls:0,tripped:!1},T_.set(e,t)),t}function D_(){T_.clear()}function O_(e,t){let n=E_(e.id);if(n.tripped)return null;let r=Date.now(),i=null;try{i=e.render(t)}catch{i=null}if(Date.now()-r>5){if(n.consecutiveSlowCalls+=1,n.consecutiveSlowCalls>=3)return n.tripped=!0,null}else n.consecutiveSlowCalls=0;return i}function k_(e){let t;for(let n of e){if(n.tickMs===void 0)continue;let e=Math.max(1e3,n.tickMs);(t===void 0||e<t)&&(t=e)}return t}function A_(e){let{columns:t,permissionMode:n,cost:r,providerUsage:i,pluginStatusItems:a,statusWidgets:o,modelName:s}=e,[c,l]=G(0);U(()=>{if(!i)return;let e=setInterval(()=>l(e=>e+1),3e4);return()=>clearInterval(e)},[i]);let[u,d]=G(0);U(()=>{let e=k_(o);if(e===void 0)return;let t=setInterval(()=>d(e=>e+1),e);return()=>clearInterval(t)},[o]);let f=Yt(()=>S_(t),[t]);return{footerVisible:f,badgeEntries:Yt(()=>{let e=[];if(f.permissionMode&&n&&e.push({id:`host:permission-mode`,text:B.t(`pref.permModeLabel`,{context:n}),color:n===`bypass`?`warning`:`inactive`,separator:`dot`,tier:`narrow`,isHost:!0}),f.cost&&r&&e.push({id:`host:cost`,text:r,separator:`space`,tier:`medium`,isHost:!0}),f.providerUsage&&i){let t=Date.now(),n=rr(i,t);n&&e.push({id:`host:provider-usage`,text:n,color:or(i.status,i.limitType,i.usedPercent,i.resetsAt,t,i.overageStatus),separator:`dot`,tier:`medium`,isHost:!0})}if(f.pluginStatusItems&&a)for(let t of a)e.push({id:t.id,text:t.text,separator:`space`,tier:`low`,isHost:!1});if(f.pluginStatusItems&&o.length>0){let n={nowMs:Date.now(),model:s,providerUsage:i,columns:t};for(let t of o){let r=O_(t,n);r&&e.push({id:t.id,text:r.text,color:r.color,separator:`space`,tier:`low`,isHost:!1,order:t.order})}}return w_(e)},[f,n,r,i,c,a,o,u,s,t])}}function j_(e){let{shellExecution:t,subagentContext:n,agentProcessing:r,queuedItems:i,pendingEcho:a,pendingSteers:o,onRequestPopQueuedConfirm:s}=e,{onExitSubagentContext:c,onPopQueued:l,onInterrupt:u,onWithdrawPending:d,onWithdrawSteer:f}=h_();return qt(()=>{if(!t){if(n){c?.();return}if(r){if(i.length>0){s?s():l?.();return}if(o&&o.length>0){let e=o[o.length-1];e&&f?.(e.id);return}if(a){d?.(a.text,a.mode);return}u?.();return}}},[t,n,c,r,i,a,o,l,u,d,f,s])}let M_=null;function N_(e){M_=e}function P_(){return M_}function F_(){let[e,t]=G(null),n=W(null),r=qt(e=>{n.current=e,t(e),!e&&L()?.currentPath===`/pane/sigil`&&L()?.goBack()},[]),i=W(null),[a,o]=G(null),s=W(!1),[c,l]=G(null),u=W(null),d=qt((e,t,n)=>{i.current=n,r({sigil:e,query:t,mode:`sigil`}),L()?.navigate(`/pane/sigil`)},[]),f=qt(()=>{if(n.current?.mode===`history`){r(null);return}i.current=null,r({sigil:`#`,query:``,mode:`history`}),L()?.navigate(`/pane/sigil`)},[]);return U(()=>(N_(f),()=>N_(null)),[f]),{sigilState:e,setSigilState:r,sigilApplyRef:i,hadSigilFocusRef:s,chipContentViewerRequest:a,pasteContent:c,handleSigilTrigger:d,handleHistorySearch:f,handleChipReopen:qt((e,n,r)=>{i.current={select:r.select,cancel:()=>r.cancel()},t({sigil:`@`,query:``}),L()?.navigate(`/pane/sigil`)},[]),handleChipViewPaste:qt((e,t)=>{lt(L(),_,!0),o({label:e,content:t,onDismiss:()=>{o(null),lt(L(),_,!1)}})},[]),handleSigilClose:qt(()=>{r(null)},[]),handlePasteConfirmRequest:qt((e,t)=>{u.current=t,l(e),lt(L(),S,!0)},[]),handlePasteConfirm:qt(()=>{u.current?.confirm(),u.current=null,l(null),lt(L(),S,!1)},[]),handlePasteCancel:qt(()=>{u.current?.cancel(),u.current=null,l(null),lt(L(),S,!1)},[])}}function I_(e){let{sigilState:t,setSigilState:n,sigilApplyRef:r,hadSigilFocusRef:i,focusOwner:a,preempted:o}=e;U(()=>{if(!t){i.current=!1;return}if(a===`sigilPane`&&!o){i.current=!0;return}i.current&&=(n(null),r.current?.cancel(!1),!1)},[t,a,o])}function L_(){let e=sr({budget:null});return{store:e,setBudget(t){e.setState({budget:t})},reset(){e.setState({budget:null})}}}function R_(e,t){return e.toolCallId&&t.toolCallId&&e.toolCallId===t.toolCallId?{...e,...t}:{...e,...t,oldContent:e.oldContent??t.oldContent,newContent:t.newContent??e.newContent,addedLines:e.addedLines+t.addedLines,removedLines:e.removedLines+t.removedLines,timestamp:Math.max(e.timestamp,t.timestamp),turnId:t.turnId??e.turnId,toolCallId:t.toolCallId??e.toolCallId}}function z_(e){let t=e.split(`/`);return t.length<=3?e:`…/${t.slice(-2).join(`/`)}`}function B_(e){switch(e){case`edit`:return`~`;case`write`:return`+`;case`delete`:return`-`}}function V_(e,t){switch(e){case`edit`:return t.accent;case`write`:return t.success;case`delete`:return t.error}}function H_({files:e,focused:r,onDismiss:i,onOpenFileFull:a,fullOpenPath:o=null,rows:s=24}){let c=R(),{expanded:l,handleExpandKey:u}=_a(s),[d,f]=ga(`editedFiles`,e.length),p=W(0);if(E(`edited-files-pane`,(t,n)=>{if(n.escape)return o===null?(L()?.navigate(`/`,{reset:!0}),i?.(),!0):!0;if(u(t,n))return!0;if(Pe(`list-nav-up`,t,n,`editedFiles`))return f(e=>Math.max(0,e-1)),!0;if(Pe(`list-nav-down`,t,n,`editedFiles`))return f(t=>Math.min(e.length-1,t+1)),!0;if(n.return){let t=e[d];return t&&a?.(t),!0}return!1},{isActive:r}),e.length===0)return null;let m=e.reduce((e,t)=>e+t.addedLines,0),h=e.reduce((e,t)=>e+t.removedLines,0),g=Math.min(d,e.length-1),_=Tt(e,g,n(e.length,s,3,l?10:5),p.current);return p.current=_.scrollTop,q(J,{flexDirection:`column`,children:[q(J,{children:[K(Y,{color:c.special,children:`▸ `}),K(Y,{color:r?c.text:c.inactive,children:B.t(`panelTitle.editedFilesTitle`)}),q(D,{type:`secondary`,children:[` `,B.t(`diff.fileCountLabel`,{count:e.length})]}),m>0&&q(Y,{color:c.diffAdd,children:[` +`,m]}),h>0&&q(Y,{color:c.diffRemove,children:[` -`,h]}),!r&&q(D,{type:`secondary`,dim:!0,children:[` `,t(`v`)]}),r&&K(J,{marginLeft:I.tight,children:K(C,{dim:!0,items:[[`+`,l?B.t(`hint.collapseHeight`):B.t(`hint.expandHeight`)],[`${O.up}${O.down}`,B.t(`hint.select`)],[O.enter,B.t(`hint.view`)],[O.esc,B.t(`hint.close`)],[O.tab,B.t(`hint.tabFocus`)]]})})]}),q(J,{marginLeft:I.section,flexDirection:`column`,children:[_.hasMoreAbove&&K(Y,{dimColor:!0,children:B.t(`scroll.above`,{n:1})}),_.rows.map((e,t)=>{let n=_.scrollTop+t===g,i=n&&r?c.selection:c.inactive;return q(J,{flexDirection:`row`,children:[K(Y,{color:i,children:n?Ae():Ft()}),q(Y,{color:V_(e.operation,c),children:[B_(e.operation),` `]}),K(Y,{color:i,children:z_(e.path)}),e.addedLines>0&&q(Y,{color:c.diffAdd,children:[` +`,e.addedLines]}),e.removedLines>0&&q(Y,{color:c.diffRemove,children:[` -`,e.removedLines]})]},`${e.path}-${e.timestamp}`)}),_.hasMoreBelow&&K(Y,{dimColor:!0,children:B.t(`scroll.below`,{n:1})})]})]})}function U_(e={}){return{tasks:[],tasksTitle:void 0,turnBoundaries:[],editedFiles:[],backgroundTasks:[],subagentsAccum:new Map,scheduleTasks:[],drafts:e.drafts??[],queued:[],pendingPermission:null,clipboardChars:0,clipboardText:``,clipboardFailed:!1,clipboardJustCopied:!1,backgroundOutput:null,subagentContext:null,forcedUpgrade:null,pendingEcho:null,pendingSteers:[],modelName:e.modelName??``,pluginStatusItems:[],statusWidgets:[],needsSetup:e.needsSetup??!1,permissionMode:e.permissionMode??`auto`,commands:e.commands??[],paneOwnsViewportFlag:!1,shellExecution:null,recentMentions:e.recentMentions??[],sessionList:[],sessionTitle:``,ftueStage:void 0,capabilityRecommendations:[],capabilityDismissed:!1,updateAvailable:void 0}}function W_(e={}){let t=sr(U_(e)),n,r={},i=()=>n?.();return{store:t,reset(){t.setState(U_(e))},setNotify(e){n=e},setEffects(e){r=e},actions:{setTasks(e,n){t.setState({tasks:e}),t.setState({tasksTitle:n}),i()},setEditedFiles(e){t.setState({editedFiles:e.sort((e,t)=>t.timestamp-e.timestamp)}),i()},addEditedFile(e){let n=[...t.getState().editedFiles],r=n.findIndex(t=>t.path===e.path);r>=0?n[r]=R_(n[r],e):n.push(e),n.sort((e,t)=>t.timestamp-e.timestamp),t.setState({editedFiles:n}),i()},setBackgroundTasks(e){if(t.setState({backgroundTasks:e}),e.some(e=>e.type===`agent-session`)){let n=new Map(t.getState().subagentsAccum);for(let t of e)t.type===`agent-session`&&n.set(t.id,t);t.setState({subagentsAccum:n})}i()},setTurnBoundaries(e){t.setState({turnBoundaries:[...e]})},addTurnBoundary(e){t.setState({turnBoundaries:[...t.getState().turnBoundaries,e]})},setDrafts(e){t.setState({drafts:e}),i()},setScheduleTasks(e){t.setState({scheduleTasks:e}),i()},setRecentMentions(e){t.setState({recentMentions:e}),i()},setModelName(e){t.setState({modelName:e}),i()},setSessionList(e){t.setState({sessionList:e}),i()},setSessionTitle(e){t.setState({sessionTitle:e}),i()},setNeedsSetup(e){t.getState().needsSetup!==e&&(t.setState({needsSetup:e}),i())},setFtueStage(e){t.getState().ftueStage!==e&&(t.setState({ftueStage:e}),i())},setCapabilityRecommendations(e){t.setState({capabilityRecommendations:e}),i()},setUpdateAvailable(e){t.setState({updateAvailable:e}),i()},dismissCapabilityRecommendations(){t.getState().capabilityDismissed||(t.setState({capabilityDismissed:!0}),i())},setPermissionMode(e){t.setState({permissionMode:e}),i()},setForcedUpgrade(e){t.setState({forcedUpgrade:e}),r.syncForcedUpgradeRoute?.(!!e),i()},setPluginStatusItems(e){t.setState({pluginStatusItems:e}),r.registerStatusItems?.(e),i()},setBackgroundOutput(e){t.setState({backgroundOutput:e}),r.backgroundOutputRoute?.(e!==null),r.flushScrollbackIfIdle?.(),i()}}}}function G_(){let e=sr({memory:void 0,memoryHistory:[],notify:void 0,indicatorLevel:`healthy`,pluginMetrics:[]});return{store:e,reset(){e.setState({memory:void 0,memoryHistory:[],notify:void 0,indicatorLevel:`healthy`,pluginMetrics:[]})},setMemory(t){let n=[...e.getState().memoryHistory,t.heapUsed].slice(-32);e.setState({memory:t,memoryHistory:n})},setNotify(t){e.setState({notify:t})},setIndicatorLevel(t){e.setState({indicatorLevel:t})},setPluginMetrics(t){e.setState({pluginMetrics:t})}}}function K_(){let e=sr({view:null});return{store:e,setView(t){e.setState({view:t})}}}function q_(){return{view:{configPath:`~/.otto/config.json`}}}function J_(){let e=sr(q_());return{store:e,setView(t){e.setState({view:t})}}}function Y_(e=Date.now){let t=sr({entries:[]}),n=1,r=r=>{let i=[{...r,id:n++,timestamp:e()},...t.getState().entries].slice(0,20);t.setState({entries:i})};return{store:t,recordCompaction(e,t,n){r({kind:`compact`,before:e,after:t,summary:n})},recordPrune(e,t){r({kind:`prune`,tokensSaved:e,prunedCount:t})},recordHistoryCapped(e){r({kind:`history_capped`,removedCount:e})}}}const X_={categoryIndex:0,itemIndex:0,variantIndex:0};function Z_(){let e=sr({...X_});return{store:e,reset(){e.setState({...X_})},setCategoryIndex(t){e.setState({categoryIndex:t,itemIndex:0,variantIndex:0})},setItemIndex(t){e.setState({itemIndex:t,variantIndex:0})},setVariantIndex(t){e.setState({variantIndex:t})}}}function Q_(e){let{taskStore:t,budgetStore:n,perfStore:r,cacheStore:i,proxyStore:a,compactionLogStore:o,galleryStore:s,streamStore:c}=e;return{taskStore:Yt(()=>t??W_(),[t]),budgetStore:Yt(()=>n??L_(),[n]),perfStore:Yt(()=>r??G_(),[r]),cacheStore:Yt(()=>i??K_(),[i]),proxyStore:Yt(()=>a??J_(),[a]),compactionLogStore:Yt(()=>o??Y_(),[o]),galleryStore:Yt(()=>s??Z_(),[s]),streamStore:Yt(()=>c??Tl(),[c])}}const $_={tasks:N.itemActive,delegates:N.service,services:N.serviceSignal,edited:N.edited,subagents:N.attention,clipboard:N.clipboard},ev={tasks:`K`,delegates:`P`,edited:`V`,subagents:`T`,clipboard:`G`},tv=N.clipboard,nv={tasks:`/pane/tasks`,delegates:`/pane/delegates`,services:`/overlay/services`,edited:`/pane/edited-files`,subagents:`/pane/subagents`,clipboard:`/pane/clipboard`};function rv({counts:e,labels:t,currentPath:n=``}){let r=[{id:`tasks`,count:e.tasks,label:t.tasks},{id:`delegates`,count:e.delegates,label:t.delegates},{id:`services`,count:e.services,label:t.services},{id:`edited`,count:e.edited,label:t.edited},{id:`subagents`,count:e.subagents,label:t.subagents},{id:`clipboard`,count:e.clipboard,label:t.clipboard}].map(t=>{let r=nv[t.id],i=r!==``&&(n===r||n.startsWith(`${r}/`));return t.id===`clipboard`&&e.clipboardJustCopied?{id:t.id,icon:tv,label:t.label,count:t.count,active:i,keyHint:ev[t.id],tone:`success`}:{id:t.id,icon:$_[t.id],label:t.label,count:t.count,active:i,keyHint:ev[t.id]}}).filter(e=>e.count>0);if(e.clipboardFailed){let e=r.filter(e=>e.id!==`clipboard`);return e.push({id:`clipboard`,icon:$_.clipboard,label:t.clipboardFailed,count:0,active:!1,hideCount:!0,keyHint:ev.clipboard,tone:`warning`}),e}return r}function iv(e){return e.length>0}function av(e){return e.filter(e=>(e.type??`process`)===`process`&&e.status===`running`&&e.detectedService).length}function ov(e){if(!e)return;let t=process.env.HOME;return t&&(e===t||e.startsWith(t+`/`))?`~`+e.slice(t.length):e}const sv=[{en:`Use ↑/↓ for input history; Ctrl+R opens fuzzy history search.`,zh:`输入框里按 ↑/↓ 浏览历史输入,Ctrl+R 模糊搜索历史。`},{en:`Use /feedback to report a bug or request a feature via GitHub.`,zh:`输入 /feedback 可通过 GitHub 提交 bug 或功能建议。`},{en:`During a run, press Esc on an empty prompt to interrupt and steer.`,zh:`运行时输入框为空按 Esc 可中断,otto 停下来让你接管方向。`},{en:`Shift+Enter newline; Option+Enter queues a follow-up (Ctrl+Q manages).`,zh:`Shift+Enter 换行;Option+Enter 排队追加消息,Ctrl+Q 管理队列。`},{en:`While otto works, plain Enter steers the current turn.`,zh:`otto 工作中按普通 Enter 可注入引导消息到当前回合。`},{en:`Type /model then Tab to pick a model and switch mid-session.`,zh:`输入 /model 后按 Tab 自动补全可用模型,会话中途即可切换。`},{en:`Use /install for skills/plugins/MCP; manage them in /extension.`,zh:`/install 从文件或 URL 安装技能/插件/MCP,/extension 面板管理。`},{en:`Reasoning streams inline; /effort changes its intensity.`,zh:`推理过程实时内联在对话流中生成,/effort 调节推理强度。`},{en:`Type /open then Tab to browse and open files in the viewer.`,zh:`输入 /open 按 Tab 浏览目录,在内置查看器打开文件。`},{en:`Ctrl+S saves the current input as a draft; Ctrl+O lists and loads drafts.`,zh:`Ctrl+S 把当前输入存为草稿,Ctrl+O 打开草稿面板选择载入。`},{en:`Ctrl+R or /history searches session and shell history.`,zh:`Ctrl+R(或 /history)搜索会话与 shell 历史,选中即回填。`},{en:`Large pastes become chips; press Enter on a chip to view it.`,zh:`大段粘贴自动折叠成占位标记,光标停在标记上按 Enter 查看原文。`},{en:`Use /compact to free context; /compact log shows pruned items.`,zh:`长会话用 /compact 释放上下文,/compact log 查看裁剪明细。`},{en:"Run `otto doctor` in another terminal for a full health check.",zh:"在另一个终端运行 `otto doctor` 做完整环境健康诊断。"},{en:`Otto can fall back to another model after failure or rate limits.`,zh:`当前模型失败或限流时,otto 自动回退到已配置的其他模型。`},{en:`Use /schedule add with cron syntax for recurring tasks.`,zh:`/schedule add 用 cron 表达式设定期任务(如日报)。`},{en:`Use /queue to reorder or remove queued follow-ups.`,zh:`/queue 面板管理排队消息,move 调顺序,remove 删除。`},{en:`Tab completes slash commands and arguments: /model gpt<Tab>.`,zh:`Tab 补全斜杠命令及其参数(试试 /model gpt<Tab>)。`},{en:`Ctrl+P opens Delegates; press Enter to view job output.`,zh:`Ctrl+P 打开委派面板查看后台任务,Enter 实时查看其输出。`},{en:`Use /job <directive> to run work in a background worktree.`,zh:`/job <指令> 在后台 worktree 跑任务,不阻塞当前会话。`},{en:`Language, model, and permission mode persist across sessions.`,zh:`语言、模型、权限模式跨会话自动持久化。`},{en:`Ctrl+V lists edited files; Enter opens a full-screen diff.`,zh:`Ctrl+V 列出本会话修改的文件及 +/- 统计,Enter 打开全屏 diff。`},{en:`Scroll with Alt+↑/↓ or PgUp/PgDn; press / in review to search.`,zh:`Alt+↑/↓ 或 PageUp/PageDown 滚动对话流,回看态按 / 搜索。`},{en:`Use /perf for memory and rendering health; /diagnose for failures.`,zh:`/perf 查看内存占用与渲染健康度,/diagnose 汇总反复出现的失败并给改进建议。`},{en:`Use /preference to switch theme or language.`,zh:`/preference theme 切 dark/light/system 主题,/preference lang 切中英文。`},{en:`Wheel scrolling works by default; drag to select, release to copy.`,zh:`滚轮/触控板开箱即用,拖拽即选中、松手自动复制。`},{en:`Use /upgrade for otto updates; /upgrade --check checks extensions.`,zh:`/upgrade 检查 otto 更新,/upgrade --check 检查扩展更新。`},{en:`Use /resume for recent sessions; /pin keeps favorites on top.`,zh:`/resume 切换最近会话,/pin 把常用会话置顶。`}];function cv({active:e,resetKey:t,isZh:n,delayMs:r=6e4,rotateMs:i=2e4}){let[a,s]=G(!1),[c,l]=G(()=>lv()),u=W(e);u.current=e;let d=W(0),[f,p]=G(0);if(o(`idle-tip-activity`,()=>{d.current+=1,p(d.current)},{isActive:e}),U(()=>{if(!e){s(!1);return}s(!1);let t=setTimeout(()=>{u.current&&s(!0)},r);return()=>{clearTimeout(t)}},[e,t,r,f]),U(()=>{if(!a)return;let e=setInterval(()=>{l(e=>(e+1)%sv.length)},i);return()=>clearInterval(e)},[a,i]),!e||!a)return null;let m=sv[c%sv.length];return m?n?m.zh:m.en:null}function lv(){let e=new Date,t=`${e.getFullYear()}-${e.getMonth()+1}-${e.getDate()}`,n=0;for(let e=0;e<t.length;e++)n=(n<<5)-n+t.charCodeAt(e)|0;return Math.abs(n)%sv.length}function uv(){return K(J,{children:K(Y,{color:R().warning,children:`🕶 ${B.t(`welcome.shadowChip`)}`})})}function dv(){let e=R();return q(J,{flexDirection:`column`,marginBottom:I.tight,children:[K(Y,{bold:!0,color:e.warning,children:`🕶 ${B.t(`welcome.shadowBannerTitle`)}`}),K(Y,{color:e.suggestion,children:B.t(`welcome.shadowGuarantee`)}),q(J,{marginTop:I.tight,flexDirection:`column`,children:[K(Y,{color:e.inactive,children:B.t(`welcome.shadowNotGuaranteedTitle`)}),K(Y,{color:e.inactive,children:` • ${B.t(`welcome.shadowNg1`)}`}),K(Y,{color:e.inactive,children:` • ${B.t(`welcome.shadowNg2`)}`}),K(Y,{color:e.inactive,children:` • ${B.t(`welcome.shadowNg3`)}`}),K(Y,{color:e.inactive,children:` • ${B.t(`welcome.shadowNg4`)}`})]})]})}const fv=[`#E06C75`,`#D19A66`,`#E5C07B`,`#98C379`,`#61AFEF`,`#C678DD`],pv=[`#B5403A`,`#B45F1F`,`#96740F`,`#4E7A34`,`#2364A8`,`#7B4FC4`];function mv(e){let t=2*e;return 375+t+188+t}function hv(e){return 2*e}function gv(e,t){return Math.min(t,Math.floor(e/2)+1)}function _v(e,t){let n=hv(t),r=e%mv(t);if(r<375)return{phase:`brand`,progress:0,t:r};let i=r-375;if(i<n)return{phase:`entering`,progress:gv(i,t),t:i};let a=i-n;if(a<188)return{phase:`hold`,progress:t,t:a};let o=a-188;return o<n?{phase:`exiting`,progress:gv(o,t),t:o}:{phase:`brand`,progress:0,t:r}}function vv(e){let t=e%16;return t<=8?t/8:(16-t)/8}function yv(e){return Math.floor(e/3)%fv.length}function bv(e,t,n){let r=n===`light`?pv:fv,i=yv(t),a=[];for(let t=0;t<e;t++)a.push(r[(t+i)%r.length]);return a}function xv(e,t){let n=parseInt(e.slice(1),16),r=n>>16&255,i=n>>8&255,a=n&255,o=e=>Math.round(e+(255-e)*t),s=e=>e.toString(16).padStart(2,`0`).toUpperCase();return`#${s(o(r))}${s(o(i))}${s(o(a))}`}function Sv(e,t,n,r,i,a,o){let s=i===`light`?pv:fv,c=a.phase===`hold`?vv(a.t):0,l=[];for(let i=0;i<e.length;i++){let u=a.phase===`hold`||a.phase===`entering`&&i<a.progress||a.phase===`exiting`&&i>=a.progress,d=Math.abs(i-t)<=n,f;if(u){let e=s[(i+r)%s.length];f=xv(e,d?.5+.25*c:.5*c)}else f=d?o.brandShimmer:o.brand;let p=l[l.length-1];p&&p.color===f?p.text+=e[i]:l.push({text:e[i],color:f})}return l}const Cv=[`✦`,`✧`,`·`,`⋆`],wv=[`~`,`°`,`·`,`˘`,`∼`],Tv=[`▄▀▀▄ ▀█▀ ▀█▀ ▄▀▀▄`,`▀▄▄▀ █ █ ▀▄▄▀`],Ev=[{left:2,phase:0},{left:8,phase:11},{left:13,phase:22}],Dv=[{left:1,phase:16}],Ov=[{left:1,phase:0},{left:5,phase:10},{left:9,phase:20},{left:14,phase:30}],kv=[{left:3,phase:15},{left:10,phase:35}];function Av(e,t){let n=(e+t)%32,r=n<=16?n/16:(32-n)/16;return r<.15?0:r<.5?1:r<.85?2:3}function jv(e,t){let n=(e+t)%70,r=(Math.sin(n/70*Math.PI*2)+1)/2;return r<.1?0:r<.4?1:r<.75?2:3}function Mv(e,t){return wv[Math.floor((e+t)/8)%wv.length]}function Nv({isNight:e=!1}){let t=R(),{resolvedTheme:n}=Ne(),[r,i]=V.useState(0),a=He();Ge(80,i);let o=e&&!a,s=!e&&!a,c=a?null:_v(r,Tv[0].length),l=yv(r),u={brand:t.brand,brandShimmer:t.brandShimmer},d=e=>e===1?t.accentDim:e===3?t.accentBright:t.accent,f=(e,t,n)=>{let i=Av(r,e.phase);return i===0?null:K(J,{position:`absolute`,top:t,left:e.left,children:K(Y,{color:d(i),children:Cv[n%Cv.length]})},`${t}-${e.left}`)},p=(e,t,n)=>{let i=jv(r,e.phase);return i===0?null:K(J,{position:`absolute`,top:t,left:e.left,children:K(Y,{color:d(i),children:Mv(r,e.phase)})},`ripple-${n}`)};return q(J,{position:`relative`,flexDirection:`column`,children:[Tv.map((e,i)=>{let a=fl(r+i*3,e.length);return K(J,{flexDirection:`row`,children:c&&c.phase!==`brand`?Sv(e,a,2,l,n,c,u).map((e,t)=>K(Y,{bold:!0,color:e.color,children:e.text},t)):dl(e,a,2).map((e,n)=>K(Y,{bold:!0,color:e.bright?t.brandShimmer:t.brand,children:e.text},n))},i)}),o&&Ev.map((e,t)=>f(e,-1,t)),o&&Dv.map((e,t)=>f(e,Tv.length,t)),s&&Ov.map((e,t)=>p(e,-1,t)),s&&kv.map((e,t)=>p(e,Tv.length,t))]})}const Pv=[`provider`,`authentication`,`model`],Fv={provider:{titleKey:`recovery.titleProvider`,ctaKey:`recovery.ctaProvider`,hintKey:`recovery.hintProvider`},authentication:{titleKey:`recovery.titleAuth`,ctaKey:`recovery.ctaAuth`,hintKey:`recovery.hintAuth`},model:{titleKey:`recovery.titleModel`,ctaKey:`recovery.ctaModel`,hintKey:`recovery.hintModel`}};function Iv(e,t){if(e===`ready`||e===`first-prompt`)return null;let n=Fv[e],r=Pv.indexOf(e)+1,i=t<80;return{titleKey:n.titleKey,ctaKey:n.ctaKey,...i?{}:{hintKey:n.hintKey},step:r,totalSteps:Pv.length}}function Lv(e,t){return e||(t?`model`:void 0)}function Rv(e){return!e||e===`ready`||e===`first-prompt`?null:Fv[e].ctaKey}function zv(e,t){return e===void 0?t:!(e===`ready`||e===`first-prompt`)}function Bv(e,t,n){return t!==`first-prompt`||n||e.length===0?null:{items:e.slice(0,3)}}function Vv({version:e=`0.1.0`,buildId:t,cwd:n,width:r,nickname:i,updateAvailable:a,weather:o,ftueStage:c,promptSuggestions:l,capabilityRecommendations:u,capabilityDismissed:d=!1,shadow:f=!1}){let p=R(),m=n?n.replace(process.env.HOME??`~`,`~`):void 0,h=r??process.stdout.columns??80,g=h>=60,_=V.useMemo(()=>{let e=new Date().getHours();return e<5?`late`:e<9?`earlyMorning`:e<12?`morning`:e<18?`afternoon`:e<22?`evening`:`night`},[]),v=_===`night`||_===`late`,[y]=V.useState(()=>{let e=new Date,t=B.language===`zh`?[`日`,`一`,`二`,`三`,`四`,`五`,`六`]:[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`],n=t[e.getDay()]??t[0],r=i?B.language===`zh`?`,${i}`:`, ${i}`:``;return B.t(`welcome.greeting`,{context:_,wday:n,who:r})}),b=y,x=B.t(`welcome.version`),S=B.t(`welcome.workspace`),C=Math.max(Mt(x),Mt(S))+4,w=Tv.map(e=>Mt(e)),ee=Math.max(...w),T=e=>` `.repeat(Math.max(0,ee-(w[e]??ee))),E=c?Iv(c,h):null,te=(c===void 0||c===`ready`)&&l&&l.length>0?l.slice(0,3):[],ne=Bv(u??[],c,d);return K(J,{flexDirection:`column`,children:q(J,{flexDirection:`column`,paddingX:I.tight,paddingTop:I.section,...Ue,borderColor:p.panelBorder,children:[g&&q(J,{marginBottom:I.tight,flexDirection:`row`,children:[K(Nv,{isNight:v}),q(J,{flexDirection:`column`,marginLeft:I.loose,children:[q(J,{flexDirection:`row`,children:[q(D,{type:`secondary`,children:[T(0),s(x,C)]}),q(D,{type:`secondary`,children:[`v`,e]}),t!=null&&q(D,{type:`secondary`,dim:!0,children:[` `,`(build `,t,`)`]})]}),m&&q(J,{flexDirection:`row`,children:[q(D,{type:`secondary`,children:[T(1),s(S,C)]}),K(D,{type:`secondary`,children:m})]})]})]}),!g&&q(J,{flexDirection:`column`,marginBottom:I.tight,children:[q(J,{flexDirection:`row`,children:[dl(`otto`,1).map((e,t)=>K(Y,{bold:!0,color:e.bright?p.brandShimmer:p.brand,children:e.text},t)),K(D,{type:`secondary`,children:` ${s(x,C)}`}),q(D,{type:`secondary`,children:[`v`,e]}),t!=null&&q(D,{type:`secondary`,dim:!0,children:[` `,`(build `,t,`)`]})]}),m&&q(J,{flexDirection:`row`,children:[K(D,{type:`secondary`,children:` ${s(S,C)}`}),K(D,{type:`secondary`,children:m})]})]}),a&&a.newer&&K(J,{marginBottom:I.tight,children:K(Y,{color:a.forced?p.warning:p.accent,children:a.forced?B.t(`update.forcedBanner`,{latest:a.latest}):B.t(`update.availableBanner`,{latest:a.latest})})}),K(J,{marginBottom:I.tight,children:i&&b.includes(i)?q(Y,{color:p.text,bold:!0,children:[b.slice(0,b.indexOf(i)),K(Y,{color:p.accent,children:i}),b.slice(b.indexOf(i)+i.length)]}):K(Y,{color:p.text,bold:!0,children:b})}),E&&q(J,{flexDirection:`column`,marginBottom:I.tight,children:[q(J,{children:[K(Y,{color:p.warning,bold:!0,children:B.t(E.titleKey)}),K(D,{type:`secondary`,children:` ${E.step}/${E.totalSteps}`})]}),E.hintKey&&K(D,{type:`secondary`,children:B.t(E.hintKey)}),K(Y,{color:p.accent,children:B.t(E.ctaKey)})]}),te.length>0&&q(J,{flexDirection:`column`,marginBottom:I.tight,children:[K(D,{type:`secondary`,children:B.t(`welcome.suggestionsLabel`)}),te.map((e,t)=>q(J,{flexDirection:`row`,children:[q(Y,{color:p.accent,children:[` [`,t+1,`] `]}),K(D,{type:`secondary`,children:e})]},t))]}),ne&&q(J,{flexDirection:`column`,marginBottom:I.tight,children:[K(D,{type:`secondary`,children:B.t(`capability.sectionTitle`)}),ne.items.map((e,t)=>q(J,{flexDirection:`row`,children:[q(Y,{color:p.accent,children:[` [`,t+1,`] `]}),K(D,{type:`secondary`,children:B.t(e.reasonKey)})]},e.extensionId)),q(J,{flexDirection:`row`,children:[K(Y,{color:p.accent,children:` [0] `}),K(D,{type:`secondary`,children:B.t(`capability.actionNotNow`)})]})]}),f&&K(dv,{}),o&&q(J,{marginBottom:I.tight,children:[q(Y,{color:p.accent,children:[o.condition,` `,o.temp,`°C`]}),q(D,{type:`secondary`,children:[` `,o.location]})]})]})})}function Hv(e,t){let n=Ca();U(()=>{if(n)return n.registerWheel(e)},[n,...t])}function Uv({title:e,status:t,messages:n,streamText:r=``,rows:i=24,columns:o=80,onDismiss:s}){let c=R(),l=a();E(`subagent-context-view`,(e,t)=>t.escape?(s?.(),!0):v(e,t)?!0:t.upArrow?(p(e=>x(e+1)),!0):t.downArrow?(p(e=>x(e-1)),!0):t.pageUp?(p(e=>x(e+y)),!0):t.pageDown?(p(e=>x(e-y)),!0):e===`g`&&!t.ctrl&&!t.meta?(p(b),!0):e===`G`&&!t.ctrl&&!t.meta?(p(0),!0):!1,{isActive:l?l.currentPath===`/subagent`:!0});let u=[];for(let e of n){let t=hc(e,o);t.length>0&&u.push(t)}let d=[];for(let e=0;e<u.length;e++)e>0&&d.push(``),d.push(...u[e]);let[f,p]=G(0),m=f===0,h=ul(r,o-Be.borderInset,3);if(m&&h.length>0){d.length>0&&d.push(``),d.push(`⏺ assistant (streaming)`);for(let e of h)d.push(` ${e}`)}let{maxRows:g,expanded:_,handleExpandKey:v}=_a(i),y=Math.max(1,g-7),b=Math.max(0,d.length-y),x=e=>Math.min(b,Math.max(0,e)),S=b-x(f),w=d.slice(S,S+y);return Hv(e=>p(t=>x(t+e*3)),[b]),q(M,{maxHeight:g,header:q(J,{flexDirection:`column`,children:[K(Y,{color:c.secondary,italic:!0,children:B.t(`subagent.header`,{title:e,status:t})}),K(Y,{children:` `})]}),footer:K(C,{items:[[`+`,_?B.t(`hint.collapseHeight`):B.t(`hint.expandHeight`)],...b>0?[[`${O.up}${O.down}`,B.t(`hint.scroll`)]]:[],[O.esc,B.t(`hint.back`)]]}),children:[K(J,{height:1,children:S>0&&K(D,{type:`secondary`,dim:!0,children:B.t(`subagent.contextEarlierLines`,{n:S})})}),K(J,{flexDirection:`column`,height:_?Math.max(1,g-7):void 0,children:w.map((e,t)=>K(Y,{children:e},`${S+t}`))})]})}function Wv(e,t,n=60){if(e.length===0)return null;let r=Math.max(0,Math.min(t,e.length-1));for(let t=r;t>=0;t--){let r=e[t];if(!r||r.role!==`user`)continue;let i=Gv(r.content);if(i)return qv(i,n)}return null}function Gv(e){return typeof e==`string`?e.trim():Array.isArray(e)?e.map(e=>typeof e==`string`?e:Kv(e)?e.text:``).filter(Boolean).join(` `).trim():Kv(e)?String(e.text).trim():``}function Kv(e){return!!e&&typeof e==`object`&&typeof e.text==`string`}function qv(e,t){let n=e.replace(/\s+/g,` `).trim();return n.length<=t?n:`${n.slice(0,Math.max(1,t-1))}…`}function Jv(e,t){let n=e.replace(/\s+/g,` `).trim();return t<=0?``:A(n,t)}function Yv({sessionTitle:e,reviewing:t,turnPrompt:n,maxWidth:r}){let i=t&&n?n:e??``;return i===``||r===void 0?i:Jv(i,r)}function Xv(e){return typeof e==`string`&&/^[a-f\d]{8}$/i.test(e)}function Zv(e){let t=h_(),{taskStore:n}=n_(),r=X(n.store,e=>e.sessionTitle),i=X(n.store,e=>e.sessionList),a=X(n.store,e=>e.needsSetup),o=X(n.store,e=>e.ftueStage),s=X(n.store,e=>e.updateAvailable),c=X(n.store,e=>e.pendingPermission),l=X(n.store,e=>e.subagentContext),u=X(n.store,e=>e.pendingEcho),d=X(n.store,e=>e.pendingSteers),f=X(e.scrollStore.store,e=>e.offset>0),[p,m]=V.useState(null);V.useEffect(()=>{l&&m(null)},[l]);let h=X(e.scrollStore.store,e=>e.offset),g=X(e.scrollStore.store,e=>e.atTranscriptTop),_=V.useMemo(()=>{if(!f)return null;let t=Math.max(0,e.messages.length-1-Math.floor(h/3));return Wv(e.messages,t)},[f,h,e.messages]),v=Lv(o,a);if(e.welcome&&e.showHome)return K(Vv,{version:e.welcome.version,buildId:e.welcome.buildId,cwd:e.welcome.cwd,width:e.columns,nickname:e.welcome.nickname,updateAvailable:s??e.welcome.updateAvailable,weather:e.welcome.weather,sessionList:i,onSessionSelect:t.onSessionSelect,ftueStage:v,promptSuggestions:e.promptSuggestions,capabilityRecommendations:e.capabilityRecommendations,capabilityDismissed:e.capabilityDismissed,shadow:e.shadow});let y=Yv({sessionTitle:r,reviewing:f,turnPrompt:_,maxWidth:Math.max(1,e.columns-2)}),b=y.length>0&&!Xv(y)&&!g,x=Math.max(1,e.rows-(b?1:0)-(p?1:0));return q(J,{flexDirection:`column`,flexGrow:1,justifyContent:`flex-end`,children:[b&&K(J,{height:1,flexShrink:0,flexDirection:`row`,children:K(Y,{dimColor:!0,children:`${N.userPrompt} ${y}`})}),l?(()=>{let n=l;return K(Uv,{title:n.title,status:n.status,messages:n.messages,streamText:n.streamText,rows:x,columns:e.columns,onDismiss:t.onExitSubagentContext})})():K(Xt,{children:K(Ml,{streamStore:e.streamStore,completedMessages:e.messages,columns:e.columns,rows:x,maxPreviewRows:e.fullScreenPaneActive?0:e.maxPreviewRows,suppressLive:e.fullScreenPaneActive||f,pendingEcho:u??null,scrollbackMode:e.scrollbackMode??!1,pendingSteers:d??[],windowMode:e.windowMode,scrollStore:e.scrollStore,earlierLoading:e.earlierLoading,earlierEnded:e.earlierEnded,onNeedEarlier:e.onNeedEarlier,onPrepend:e.onPrepend,findQuery:e.findQuery,findActiveMatch:e.findActiveMatch,onFindNavigateTo:e.onFindNavigateTo,onFindCountChange:e.onFindCountChange,onReviewHintChange:m,renderReviewHint:!1,topbarReserved:b,pendingPermission:c??null,suppressSpinner:e.fullScreenPaneActive})}),p&&K(J,{height:1,flexShrink:0,flexDirection:`row`,children:K(Y,{dimColor:!0,children:p})})]})}const Qv={running:N.todoActive,exited:N.check,killed:N.cross,failed:N.cross};function $v(e,t){return e===`running`?t.special:e===`exited`?t.success:t.error}function ey(e){if((e.type??`process`)===`agent-session`)switch(e.agentStatus){case`running`:return N.todoActive;case`ready`:return N.attention;case`needs_input`:return N.attention;case`applied`:return N.check;default:return N.cross}return Qv[e.status]}function ty(e,t){if((e.type??`process`)===`agent-session`){if(e.stall===`stalled`)return t.error;if(e.stall===`warn`)return t.warning;switch(e.agentStatus){case`running`:return t.special;case`ready`:return t.selection;case`needs_input`:return t.warning;case`applied`:return t.success;default:return t.error}}return $v(e.status,t)}function ny({tasks:e,columns:r=80,onClose:i,onKill:a,onViewOutput:o,onApply:s,onSwitch:c,onDelete:l,active:u=!0,rows:d=24}){let f=R(),[p,m]=ga(`delegates`,e.length),h=W(0),{expanded:g,handleExpandKey:_}=_a(d??24),v=e.some(e=>(e.type??`process`)===`agent-session`?e.agentStatus===`running`:e.status===`running`),[,y]=G(0);U(()=>{if(!v)return;let e=setInterval(()=>y(e=>(e+1)%1e6),1e3);return()=>clearInterval(e)},[v]),E(`delegates-pane`,(t,n)=>{if(n.escape||t===`q`)return i?.(),!0;if(_(t,n))return!0;if(Pe(`list-nav-up`,t,n,`background`))return m(e=>Math.max(0,e-1)),!0;if(Pe(`list-nav-down`,t,n,`background`))return m(t=>Math.max(0,Math.min(e.length-1,t+1))),!0;let r=e[p],u=r?No(r):!1;return t===`k`&&u&&r?(a?.(r.id),!0):(t===`o`||n.return)&&r?(o?.(r.id),!0):t===`a`&&r?.type===`agent-session`&&r.agentStatus===`ready`&&r.diffStat?(s?.(r.id),!0):t===`s`&&r?.type===`agent-session`?(c?.(r.id),!0):t===`d`&&r&&!u?(l?.(r.id),!0):!1},{isActive:u,ignoreRoute:!0});let b=e.filter(No).length,x=Date.now(),S=Math.max(12,Math.min(48,r-28));if(!u){if(e.length===0)return null;let n=e[Math.min(p,e.length-1)];return q(J,{flexDirection:`column`,children:[q(J,{children:[K(Y,{color:f.special,children:`▸ `}),K(D,{type:`secondary`,children:B.t(`bg.tasksTitle`)}),q(D,{type:`secondary`,children:[` `,e.length]}),b>0&&q(D,{type:`secondary`,children:[` · `,B.t(`bg.runningSuffix`,{n:b})]}),q(D,{type:`secondary`,dim:!0,children:[` `,t(`p`)]})]}),n&&q(J,{flexDirection:`row`,children:[K(D,{type:`secondary`,children:`${N.pointer} `}),K(D,{type:`secondary`,children:A(n.command,S).padEnd(S)}),q(D,{type:`secondary`,dim:!0,children:[` `,Lo(n,x)]})]})]})}let w=e[Math.min(p,e.length-1)],ee=(w?.type??`process`)===`agent-session`&&w?.agentStatus===`ready`&&!!w?.diffStat,T=!!w&&!No(w),te=Math.min(p,e.length-1),ne=[],re,ie=0;e.forEach((e,t)=>{let n=jo(e);n!==re&&(ie>0&&ne.push({type:`spacer`}),ne.push({type:`header`,category:n}),ie++,re=n),ne.push({type:`entry`,task:e,index:t})});let ae=Tt(ne,ne.findIndex(e=>e.type===`entry`&&e.index===te),n(ne.length,d,3,g?10:5),h.current);return h.current=ae.scrollTop,q(J,{flexDirection:`column`,children:[q(J,{children:[K(Y,{color:f.special,children:`▸ `}),K(Y,{color:f.text,children:B.t(`bg.tasksTitle`)}),q(D,{type:`secondary`,children:[` `,b>0?B.t(`bg.runningSuffix`,{n:b}):`${e.length} total`,e.length>b?` · ${B.t(`bg.doneSuffix`,{n:e.length-b})}`:``]}),K(J,{marginLeft:I.tight,children:K(C,{dim:!0,items:[[`+`,g?B.t(`hint.collapseHeight`):B.t(`hint.expandHeight`)],[`${O.up}${O.down}`,B.t(`hint.select`)],[`k`,B.t(`hint.kill`)],[`o`,B.t(`hint.output`)],...ee?[[`a`,B.t(`hint.apply`)]]:[],...T?[[`d`,B.t(`hint.delete`)]]:[],[O.esc,B.t(`hint.close`)],[O.tab,B.t(`hint.tabFocus`)]]})})]}),K(J,{marginLeft:I.section,flexDirection:`column`,children:e.length===0?K(D,{type:`secondary`,dim:!0,children:B.t(`bg.empty`)}):q(Xt,{children:[ae.hasMoreAbove&&K(Y,{dimColor:!0,children:B.t(`scroll.above`,{n:1})}),ae.rows.map((e,t)=>{if(e.type===`spacer`)return K(Y,{children:` `},`spacer-${t}`);if(e.type===`header`)return K(D,{type:`secondary`,dim:!0,children:B.t(`bg.categoryLabel`,{context:e.category})},`h-${t}`);let n=e.task,r=e.index===p;return q(J,{flexDirection:`row`,children:[K(Y,{color:r?f.selection:f.inactive,children:r?Ae():Ft()}),q(Y,{color:ty(n,f),children:[ey(n),` `]}),K(Y,{color:r?f.selection:f.inactive,children:A(n.command,S).padEnd(S)}),(n.type??`process`)===`agent-session`&&n.model&&q(D,{type:`secondary`,dim:!0,children:[` `,String(n.model)]}),q(D,{type:`secondary`,dim:!0,children:[` `,Lo(n,x)]})]},n.id)}),ae.hasMoreBelow&&K(Y,{dimColor:!0,children:B.t(`scroll.below`,{n:1})})]})})]})}function ry({view:e,columns:t=80,rows:n,active:r=!0,onDismiss:i}){let a=R(),o=e.prompt!==void 0,s=e.messages!==void 0&&e.messages.length>0,c=!!e.diff?.trim(),l=(o?1:0)+(s?1:0)+(c?1:0)>=2,[u,d]=G(c?`diff`:s?`conversation`:`prompt`),[f,p]=G(0),[m,h]=G(!1),[g,_]=G(``),[v,y]=G(-1),{maxRows:b,expanded:x,handleExpandKey:S}=_a(n??24),w=Math.max(1,b-10);U(()=>p(0),[e.id,u]);let ee=Math.max(8,t-Be.contentInset),T=[],te=[];if(u===`diff`)T=(e.diff??``).split(`