@cerebriline/agents 4.100.276 → 4.100.282

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +65 -72
  2. package/package.json +3 -3
package/dist/index.js CHANGED
@@ -1,67 +1,60 @@
1
- var Jn="input_progress";var oo=[/\bserver is shutting down\b/i,/^(?:error:\s*)?(?:503\s*)?loading model\b/i,/\b(?:ECONNREFUSED|ECONNRESET|ECONNABORTED|EPIPE|EHOSTUNREACH|EHOSTDOWN|ENETUNREACH|ENETDOWN|ETIMEDOUT|UND_ERR_SOCKET|UND_ERR_CONNECT_TIMEOUT|UND_ERR_CLOSED)\b/,/\bsocket hang up\b/i,/\bother side closed\b/i,/\bsocket (?:was )?closed\b/i,/\bpremature close\b/i,/\bcannot connect to api\b/i,/^fetch failed$/i,/^terminated$/i,/^(?:error:\s*)?terminated:/i,/\bHTTPParserError\b/,/\bHPE_[A-Z_]+\b/,/^(?:network|connection) (?:error|failure|lost|reset)$/i,/^(?:(?:error:\s*)?(?:502|503|504)\s*)?(?:bad gateway|service unavailable|gateway time-?out)$/i,/^no healthy upstream$/i,/^(?:error:\s*)?(?:500\s*)?invalid input batch\.?$/i,/^(?:error:\s*)?got exception: speculative batch index \d+ is not inside the current sub-batch\b/i,/^(?:error:\s*)?(?:AI_TypeValidationError:\s*)?type validation failed\b[^:\n]*: value:/i,/^(?:error:\s*)?(?:AI_JSONParseError:\s*)?json parsing failed: text:/i],so=new Set([502,503,504]);var Nt=/^(?:error:\s*)?evicted to keep other in-flight requests alive\b/i;function Yn(e,t){return t==="kv_evicted"||Nt.test((e??"").trim())}function ze(e,t=0){if(t>5||e===null||e===void 0)return!1;if(typeof e==="string"){let i=e.trim();if(Nt.test(i))return!0;if(!i.startsWith("{"))return!1;try{return ze(JSON.parse(i),t+1)}catch{return!1}}if(typeof e!=="object")return!1;let n=e;if(n.error_kind==="evicted_kv_full")return!0;for(let i of["error","responseBody","data","cause","message"]){let r=n[i];if(r!==void 0&&r!==e){if(ze(r,t+1))return!0}}return!1}var ao=[/projected mean tps below floor/i,/context allocation exhausted/i,/session allocation full/i,/admission (?:rejected|refused|queued)/i,/\btoo many requests\b/i,Nt,/\[opencoti_window_unavailable\b/];function Xn(e){let t=(n,i)=>/^[A-Z]/.test(n)?i.charAt(0).toUpperCase()+i.slice(1):i;return e.replace(/\badmission (?:rejected|refused)\b/gi,(n)=>t(n,"admission queued")).replace(/\b(?:rejected|refused)\b/gi,(n)=>t(n,"queued")).replace(/\b(?:rejecting|refusing)\b/gi,(n)=>t(n,"queueing")).replace(/\b(?:rejections|refusals)\b/gi,(n)=>t(n,"retries")).replace(/\b(?:rejection|refusal)\b/gi,(n)=>t(n,"retry"))}function Ie(e,t){let n=(e??"").trim();if(t==="rate_limited"||t==="kv_evicted"||ao.some((i)=>i.test(n)))return"refusal";if(n&&oo.some((i)=>i.test(n)))return"transport";return}function lo(e){let t=e.code;return typeof t==="string"?t:void 0}function uo(e){let t=e.status??e.statusCode;return typeof t==="number"?t:void 0}function Ot(e,t=0){if(t>5||e===null||e===void 0)return;if(typeof e==="string")return Ie(e);if(typeof e!=="object")return;let n=uo(e);if(n===429||ze(e,t))return"refusal";let i=e.message,r=typeof i==="string"?Ie(i):void 0;if(r==="refusal")return r;let o=lo(e);if(o&&Ie(o)==="transport")return"transport";if(n!==void 0&&so.has(n))return"transport";if(r)return r;return Ot(e.cause,t+1)}var hn;function h(e,t,n){function i(a,u){if(!a._zod)Object.defineProperty(a,"_zod",{value:{def:u,constr:s,traits:new Set},enumerable:!1});if(a._zod.traits.has(e))return;a._zod.traits.add(e),t(a,u);let c=s.prototype,d=Object.keys(c);for(let y=0;y<d.length;y++){let p=d[y];if(!(p in a))a[p]=c[p].bind(a)}}let r=n?.Parent??Object;class o extends r{}Object.defineProperty(o,"name",{value:e});function s(a){var u;let c=n?.Parent?new o:this;i(c,a),(u=c._zod).deferred??(u.deferred=[]);for(let d of c._zod.deferred)d();return c}return Object.defineProperty(s,"init",{value:i}),Object.defineProperty(s,Symbol.hasInstance,{value:(a)=>{if(n?.Parent&&a instanceof n.Parent)return!0;return a?._zod?.traits?.has(e)}}),Object.defineProperty(s,"name",{value:e}),s}var Wp=Symbol("zod_brand");class pe extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class Mt extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`);this.name="ZodEncodeError"}}(hn=globalThis).__zod_globalConfig??(hn.__zod_globalConfig={});var Qe=globalThis.__zod_globalConfig;function ne(e){if(e)Object.assign(Qe,e);return Qe}function Qn(e){let t=Object.values(e).filter((n)=>typeof n==="number");return Object.entries(e).filter(([n,i])=>t.indexOf(+n)===-1).map(([n,i])=>i)}function fn(e,t="|"){return e.map((n)=>ni(n)).join(t)}function xt(e,t){if(typeof t==="bigint")return t.toString();return t}function at(e){return{get value(){{let t=e();return Object.defineProperty(this,"value",{value:t}),t}throw Error("cached value already set")}}}function Pt(e){return e===null||e===void 0}function $t(e){let t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function co(e,t){let n=e/t,i=Math.round(n),r=Number.EPSILON*Math.max(Math.abs(n),1);if(Math.abs(n-i)<r)return 0;return n-i}var mn=Symbol("evaluating");function R(e,t,n){let i=void 0;Object.defineProperty(e,t,{get(){if(i===mn)return;if(i===void 0)i=mn,i=n();return i},set(r){Object.defineProperty(e,t,{value:r})},configurable:!0})}function fe(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function ue(...e){let t={};for(let n of e){let i=Object.getOwnPropertyDescriptors(n);Object.assign(t,i)}return Object.defineProperties({},t)}function gn(e){return JSON.stringify(e)}function po(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var ei="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function De(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}var ho=at(()=>{if(Qe.jitless)return!1;if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return Function(""),!0}catch(e){return!1}});function Ae(e){if(De(e)===!1)return!1;let t=e.constructor;if(t===void 0)return!0;if(typeof t!=="function")return!0;let n=t.prototype;if(De(n)===!1)return!1;if(Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)return!1;return!0}function ti(e){if(Ae(e))return{...e};if(Array.isArray(e))return[...e];if(e instanceof Map)return new Map(e);if(e instanceof Set)return new Set(e);return e}var fo=new Set(["string","number","symbol"]);function xe(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ce(e,t,n){let i=new e._zod.constr(t??e._zod.def);if(!t||n?.parent)i._zod.parent=e;return i}function T(e){let t=e;if(!t)return{};if(typeof t==="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}if(delete t.message,typeof t.error==="string")return{...t,error:()=>t.error};return t}function ni(e){if(typeof e==="bigint")return e.toString()+"n";if(typeof e==="string")return`"${e}"`;return`${e}`}function mo(e){return Object.keys(e).filter((t)=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}var go={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-340282346638528860000000000000000000000,340282346638528860000000000000000000000],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function yo(e,t){let n=e._zod.def,i=n.checks;if(i&&i.length>0)throw Error(".pick() cannot be used on object schemas containing refinements");let r=ue(e._zod.def,{get shape(){let o={};for(let s in t){if(!(s in n.shape))throw Error(`Unrecognized key: "${s}"`);if(!t[s])continue;o[s]=n.shape[s]}return fe(this,"shape",o),o},checks:[]});return ce(e,r)}function vo(e,t){let n=e._zod.def,i=n.checks;if(i&&i.length>0)throw Error(".omit() cannot be used on object schemas containing refinements");let r=ue(e._zod.def,{get shape(){let o={...e._zod.def.shape};for(let s in t){if(!(s in n.shape))throw Error(`Unrecognized key: "${s}"`);if(!t[s])continue;delete o[s]}return fe(this,"shape",o),o},checks:[]});return ce(e,r)}function bo(e,t){if(!Ae(t))throw Error("Invalid input to extend: expected a plain object");let n=e._zod.def.checks;if(n&&n.length>0){let r=e._zod.def.shape;for(let o in t)if(Object.getOwnPropertyDescriptor(r,o)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let i=ue(e._zod.def,{get shape(){let r={...e._zod.def.shape,...t};return fe(this,"shape",r),r}});return ce(e,i)}function To(e,t){if(!Ae(t))throw Error("Invalid input to safeExtend: expected a plain object");let n=ue(e._zod.def,{get shape(){let i={...e._zod.def.shape,...t};return fe(this,"shape",i),i}});return ce(e,n)}function wo(e,t){if(e._zod.def.checks?.length)throw Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let n=ue(e._zod.def,{get shape(){let i={...e._zod.def.shape,...t._zod.def.shape};return fe(this,"shape",i),i},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return ce(e,n)}function _o(e,t,n){let i=t._zod.def.checks;if(i&&i.length>0)throw Error(".partial() cannot be used on object schemas containing refinements");let r=ue(t._zod.def,{get shape(){let o=t._zod.def.shape,s={...o};if(n)for(let a in n){if(!(a in o))throw Error(`Unrecognized key: "${a}"`);if(!n[a])continue;s[a]=e?new e({type:"optional",innerType:o[a]}):o[a]}else for(let a in o)s[a]=e?new e({type:"optional",innerType:o[a]}):o[a];return fe(this,"shape",s),s},checks:[]});return ce(t,r)}function ko(e,t,n){let i=ue(t._zod.def,{get shape(){let r=t._zod.def.shape,o={...r};if(n)for(let s in n){if(!(s in o))throw Error(`Unrecognized key: "${s}"`);if(!n[s])continue;o[s]=new e({type:"nonoptional",innerType:r[s]})}else for(let s in r)o[s]=new e({type:"nonoptional",innerType:r[s]});return fe(this,"shape",o),o}});return ce(t,i)}function _e(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function Eo(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue===!1)return!0;return!1}function le(e,t){return t.map((n)=>{var i;return(i=n).path??(i.path=[]),n.path.unshift(e),n})}function Ze(e){return typeof e==="string"?e:e?.message}function re(e,t,n){let i=e.message?e.message:Ze(e.inst?._zod.def?.error?.(e))??Ze(t?.error?.(e))??Ze(n.customError?.(e))??Ze(n.localeError?.(e))??"Invalid input",{inst:r,continue:o,input:s,...a}=e;if(a.path??(a.path=[]),a.message=i,t?.reportInput)a.input=s;return a}function Lt(e){if(Array.isArray(e))return"array";if(typeof e==="string")return"string";return"unknown"}function Io(e){let t=typeof e;switch(t){case"number":return Number.isNaN(e)?"nan":"number";case"object":{if(e===null)return"null";if(Array.isArray(e))return"array";let n=e;if(n&&Object.getPrototypeOf(n)!==Object.prototype&&"constructor"in n&&n.constructor)return n.constructor.name}}return t}function Ue(...e){let[t,n,i]=e;if(typeof t==="string")return{message:t,code:"custom",input:n,inst:i};return{...t}}var ii=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,xt,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},ri=h("$ZodError",ii),lt=h("$ZodError",ii,{Parent:Error});function Ao(e,t=(n)=>n.message){let n={},i=[];for(let r of e.issues)if(r.path.length>0)n[r.path[0]]=n[r.path[0]]||[],n[r.path[0]].push(t(r));else i.push(t(r));return{formErrors:i,fieldErrors:n}}function xo(e,t=(n)=>n.message){let n={_errors:[]},i=(r,o=[])=>{for(let s of r.issues)if(s.code==="invalid_union"&&s.errors.length)s.errors.map((a)=>i({issues:a},[...o,...s.path]));else if(s.code==="invalid_key")i({issues:s.issues},[...o,...s.path]);else if(s.code==="invalid_element")i({issues:s.issues},[...o,...s.path]);else{let a=[...o,...s.path];if(a.length===0)n._errors.push(t(s));else{let u=n,c=0;while(c<a.length){let d=a[c];if(c!==a.length-1)u[d]=u[d]||{_errors:[]};else u[d]=u[d]||{_errors:[]},u[d]._errors.push(t(s));u=u[d],c++}}}};return i(e),n}var ut=(e)=>(t,n,i,r)=>{let o=i?{...i,async:!1}:{async:!1},s=t._zod.run({value:n,issues:[]},o);if(s instanceof Promise)throw new pe;if(s.issues.length){let a=new(r?.Err??e)(s.issues.map((u)=>re(u,o,ne())));throw ei(a,r?.callee),a}return s.value},yn=ut(lt),ct=(e)=>async(t,n,i,r)=>{let o=i?{...i,async:!0}:{async:!0},s=t._zod.run({value:n,issues:[]},o);if(s instanceof Promise)s=await s;if(s.issues.length){let a=new(r?.Err??e)(s.issues.map((u)=>re(u,o,ne())));throw ei(a,r?.callee),a}return s.value},vn=ct(lt),dt=(e)=>(t,n,i)=>{let r=i?{...i,async:!1}:{async:!1},o=t._zod.run({value:n,issues:[]},r);if(o instanceof Promise)throw new pe;return o.issues.length?{success:!1,error:new(e??ri)(o.issues.map((s)=>re(s,r,ne())))}:{success:!0,data:o.value}},Co=dt(lt),pt=(e)=>async(t,n,i)=>{let r=i?{...i,async:!0}:{async:!0},o=t._zod.run({value:n,issues:[]},r);if(o instanceof Promise)o=await o;return o.issues.length?{success:!1,error:new e(o.issues.map((s)=>re(s,r,ne())))}:{success:!0,data:o.value}},Ro=pt(lt),So=(e)=>(t,n,i)=>{let r=i?{...i,direction:"backward"}:{direction:"backward"};return ut(e)(t,n,r)},No=(e)=>(t,n,i)=>ut(e)(t,n,i),Oo=(e)=>async(t,n,i)=>{let r=i?{...i,direction:"backward"}:{direction:"backward"};return ct(e)(t,n,r)},Mo=(e)=>async(t,n,i)=>ct(e)(t,n,i),Po=(e)=>(t,n,i)=>{let r=i?{...i,direction:"backward"}:{direction:"backward"};return dt(e)(t,n,r)},$o=(e)=>(t,n,i)=>dt(e)(t,n,i),Lo=(e)=>async(t,n,i)=>{let r=i?{...i,direction:"backward"}:{direction:"backward"};return pt(e)(t,n,r)},zo=(e)=>async(t,n,i)=>pt(e)(t,n,i),Do=/^[cC][0-9a-z]{6,}$/,Uo=/^[0-9a-z]+$/,Fo=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Bo=/^[0-9a-vA-V]{20}$/,jo=/^[A-Za-z0-9]{27}$/,qo=/^[a-zA-Z0-9_-]{21}$/,Ho=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Wo=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,bn=(e)=>{if(!e)return/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)},Vo=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Zo="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function Go(){return new RegExp(Zo,"u")}var Ko=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Jo=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,Yo=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,Xo=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Qo=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,oi=/^[A-Za-z0-9_-]*$/,es=/^https?$/,ts=/^\+[1-9]\d{6,14}$/,si="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",ns=new RegExp(`^${si}$`);function ai(e){return typeof e.precision==="number"?e.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":e.precision===0?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d":`(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${e.precision}}`:"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function is(e){return new RegExp(`^${ai(e)}$`)}function rs(e){let t=ai({precision:e.precision}),n=["Z"];if(e.local)n.push("");if(e.offset)n.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let i=`${t}(?:${n.join("|")})`;return new RegExp(`^${si}T(?:${i})$`)}var os=(e)=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},ss=/^-?\d+$/,li=/^-?\d+(?:\.\d+)?$/,as=/^(?:true|false)$/i,ls=/^[^A-Z]*$/,us=/^[^a-z]*$/,J=h("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),ui={number:"number",bigint:"bigint",object:"date"},ci=h("$ZodCheckLessThan",(e,t)=>{J.init(e,t);let n=ui[typeof t.value];e._zod.onattach.push((i)=>{let r=i._zod.bag,o=(t.inclusive?r.maximum:r.exclusiveMaximum)??Number.POSITIVE_INFINITY;if(t.value<o)if(t.inclusive)r.maximum=t.value;else r.exclusiveMaximum=t.value}),e._zod.check=(i)=>{if(t.inclusive?i.value<=t.value:i.value<t.value)return;i.issues.push({origin:n,code:"too_big",maximum:typeof t.value==="object"?t.value.getTime():t.value,input:i.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),di=h("$ZodCheckGreaterThan",(e,t)=>{J.init(e,t);let n=ui[typeof t.value];e._zod.onattach.push((i)=>{let r=i._zod.bag,o=(t.inclusive?r.minimum:r.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if(t.value>o)if(t.inclusive)r.minimum=t.value;else r.exclusiveMinimum=t.value}),e._zod.check=(i)=>{if(t.inclusive?i.value>=t.value:i.value>t.value)return;i.issues.push({origin:n,code:"too_small",minimum:typeof t.value==="object"?t.value.getTime():t.value,input:i.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),cs=h("$ZodCheckMultipleOf",(e,t)=>{J.init(e,t),e._zod.onattach.push((n)=>{var i;(i=n._zod.bag).multipleOf??(i.multipleOf=t.value)}),e._zod.check=(n)=>{if(typeof n.value!==typeof t.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof n.value==="bigint"?n.value%t.value===BigInt(0):co(n.value,t.value)===0)return;n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),ds=h("$ZodCheckNumberFormat",(e,t)=>{J.init(e,t),t.format=t.format||"float64";let n=t.format?.includes("int"),i=n?"int":"number",[r,o]=go[t.format];e._zod.onattach.push((s)=>{let a=s._zod.bag;if(a.format=t.format,a.minimum=r,a.maximum=o,n)a.pattern=ss}),e._zod.check=(s)=>{let a=s.value;if(n){if(!Number.isInteger(a)){s.issues.push({expected:i,format:t.format,code:"invalid_type",continue:!1,input:a,inst:e});return}if(!Number.isSafeInteger(a)){if(a>0)s.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:i,inclusive:!0,continue:!t.abort});else s.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:i,inclusive:!0,continue:!t.abort});return}}if(a<r)s.issues.push({origin:"number",input:a,code:"too_small",minimum:r,inclusive:!0,inst:e,continue:!t.abort});if(a>o)s.issues.push({origin:"number",input:a,code:"too_big",maximum:o,inclusive:!0,inst:e,continue:!t.abort})}}),ps=h("$ZodCheckMaxLength",(e,t)=>{var n;J.init(e,t),(n=e._zod.def).when??(n.when=(i)=>{let r=i.value;return!Pt(r)&&r.length!==void 0}),e._zod.onattach.push((i)=>{let r=i._zod.bag.maximum??Number.POSITIVE_INFINITY;if(t.maximum<r)i._zod.bag.maximum=t.maximum}),e._zod.check=(i)=>{let r=i.value;if(r.length<=t.maximum)return;let o=Lt(r);i.issues.push({origin:o,code:"too_big",maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),hs=h("$ZodCheckMinLength",(e,t)=>{var n;J.init(e,t),(n=e._zod.def).when??(n.when=(i)=>{let r=i.value;return!Pt(r)&&r.length!==void 0}),e._zod.onattach.push((i)=>{let r=i._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(t.minimum>r)i._zod.bag.minimum=t.minimum}),e._zod.check=(i)=>{let r=i.value;if(r.length>=t.minimum)return;let o=Lt(r);i.issues.push({origin:o,code:"too_small",minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),fs=h("$ZodCheckLengthEquals",(e,t)=>{var n;J.init(e,t),(n=e._zod.def).when??(n.when=(i)=>{let r=i.value;return!Pt(r)&&r.length!==void 0}),e._zod.onattach.push((i)=>{let r=i._zod.bag;r.minimum=t.length,r.maximum=t.length,r.length=t.length}),e._zod.check=(i)=>{let r=i.value,o=r.length;if(o===t.length)return;let s=Lt(r),a=o>t.length;i.issues.push({origin:s,...a?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:i.value,inst:e,continue:!t.abort})}}),ht=h("$ZodCheckStringFormat",(e,t)=>{var n,i;if(J.init(e,t),e._zod.onattach.push((r)=>{let o=r._zod.bag;if(o.format=t.format,t.pattern)o.patterns??(o.patterns=new Set),o.patterns.add(t.pattern)}),t.pattern)(n=e._zod).check??(n.check=(r)=>{if(t.pattern.lastIndex=0,t.pattern.test(r.value))return;r.issues.push({origin:"string",code:"invalid_format",format:t.format,input:r.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})});else(i=e._zod).check??(i.check=()=>{})}),ms=h("$ZodCheckRegex",(e,t)=>{ht.init(e,t),e._zod.check=(n)=>{if(t.pattern.lastIndex=0,t.pattern.test(n.value))return;n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),gs=h("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=ls),ht.init(e,t)}),ys=h("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=us),ht.init(e,t)}),vs=h("$ZodCheckIncludes",(e,t)=>{J.init(e,t);let n=xe(t.includes),i=new RegExp(typeof t.position==="number"?`^.{${t.position}}${n}`:n);t.pattern=i,e._zod.onattach.push((r)=>{let o=r._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(i)}),e._zod.check=(r)=>{if(r.value.includes(t.includes,t.position))return;r.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:r.value,inst:e,continue:!t.abort})}}),bs=h("$ZodCheckStartsWith",(e,t)=>{J.init(e,t);let n=new RegExp(`^${xe(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.onattach.push((i)=>{let r=i._zod.bag;r.patterns??(r.patterns=new Set),r.patterns.add(n)}),e._zod.check=(i)=>{if(i.value.startsWith(t.prefix))return;i.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:i.value,inst:e,continue:!t.abort})}}),Ts=h("$ZodCheckEndsWith",(e,t)=>{J.init(e,t);let n=new RegExp(`.*${xe(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.onattach.push((i)=>{let r=i._zod.bag;r.patterns??(r.patterns=new Set),r.patterns.add(n)}),e._zod.check=(i)=>{if(i.value.endsWith(t.suffix))return;i.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:i.value,inst:e,continue:!t.abort})}}),ws=h("$ZodCheckOverwrite",(e,t)=>{J.init(e,t),e._zod.check=(n)=>{n.value=t.tx(n.value)}});class pi{constructor(e=[]){if(this.content=[],this.indent=0,this)this.args=e}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e==="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let t=e.split(`
2
- `).filter((r)=>r),n=Math.min(...t.map((r)=>r.length-r.trimStart().length)),i=t.map((r)=>r.slice(n)).map((r)=>" ".repeat(this.indent*2)+r);for(let r of i)this.content.push(r)}compile(){let e=Function,t=this?.args,n=[...(this?.content??[""]).map((i)=>` ${i}`)];return new e(...t,n.join(`
3
- `))}}var _s={major:4,minor:4,patch:3},S=h("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=_s;let i=[...e._zod.def.checks??[]];if(e._zod.traits.has("$ZodCheck"))i.unshift(e);for(let r of i)for(let o of r._zod.onattach)o(e);if(i.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let r=(s,a,u)=>{let c=_e(s),d;for(let y of a){if(y._zod.def.when){if(Eo(s))continue;if(!y._zod.def.when(s))continue}else if(c)continue;let p=s.issues.length,v=y._zod.check(s);if(v instanceof Promise&&u?.async===!1)throw new pe;if(d||v instanceof Promise)d=(d??Promise.resolve()).then(async()=>{if(await v,s.issues.length===p)return;if(!c)c=_e(s,p)});else{if(s.issues.length===p)continue;if(!c)c=_e(s,p)}}if(d)return d.then(()=>s);return s},o=(s,a,u)=>{if(_e(s))return s.aborted=!0,s;let c=r(a,i,u);if(c instanceof Promise){if(u.async===!1)throw new pe;return c.then((d)=>e._zod.parse(d,u))}return e._zod.parse(c,u)};e._zod.run=(s,a)=>{if(a.skipChecks)return e._zod.parse(s,a);if(a.direction==="backward"){let c=e._zod.parse({value:s.value,issues:[]},{...a,skipChecks:!0});if(c instanceof Promise)return c.then((d)=>o(d,s,a));return o(c,s,a)}let u=e._zod.parse(s,a);if(u instanceof Promise){if(a.async===!1)throw new pe;return u.then((c)=>r(c,i,a))}return r(u,i,a)}}R(e,"~standard",()=>({validate:(r)=>{try{let o=Co(e,r);return o.success?{value:o.data}:{issues:o.error?.issues}}catch(o){return Ro(e,r).then((s)=>s.success?{value:s.data}:{issues:s.error?.issues})}},vendor:"zod",version:1}))}),zt=h("$ZodString",(e,t)=>{S.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??os(e._zod.bag),e._zod.parse=(n,i)=>{if(t.coerce)try{n.value=String(n.value)}catch(r){}if(typeof n.value==="string")return n;return n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),M=h("$ZodStringFormat",(e,t)=>{ht.init(e,t),zt.init(e,t)}),ks=h("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=Wo),M.init(e,t)}),Es=h("$ZodUUID",(e,t)=>{if(t.version){let n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(n===void 0)throw Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=bn(n))}else t.pattern??(t.pattern=bn());M.init(e,t)}),Is=h("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=Vo),M.init(e,t)}),As=h("$ZodURL",(e,t)=>{M.init(e,t),e._zod.check=(n)=>{try{let i=n.value.trim();if(!t.normalize&&t.protocol?.source===es.source){if(!/^https?:\/\//i.test(i)){n.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:n.value,inst:e,continue:!t.abort});return}}let r=new URL(i);if(t.hostname){if(t.hostname.lastIndex=0,!t.hostname.test(r.hostname))n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort})}if(t.protocol){if(t.protocol.lastIndex=0,!t.protocol.test(r.protocol.endsWith(":")?r.protocol.slice(0,-1):r.protocol))n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})}if(t.normalize)n.value=r.href;else n.value=i;return}catch(i){n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),xs=h("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=Go()),M.init(e,t)}),Cs=h("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=qo),M.init(e,t)}),Rs=h("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Do),M.init(e,t)}),Ss=h("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=Uo),M.init(e,t)}),Ns=h("$ZodULID",(e,t)=>{t.pattern??(t.pattern=Fo),M.init(e,t)}),Os=h("$ZodXID",(e,t)=>{t.pattern??(t.pattern=Bo),M.init(e,t)}),Ms=h("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=jo),M.init(e,t)}),Ps=h("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=rs(t)),M.init(e,t)}),$s=h("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=ns),M.init(e,t)}),Ls=h("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=is(t)),M.init(e,t)}),zs=h("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=Ho),M.init(e,t)}),Ds=h("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=Ko),M.init(e,t),e._zod.bag.format="ipv4"}),Us=h("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=Jo),M.init(e,t),e._zod.bag.format="ipv6",e._zod.check=(n)=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}}}),Fs=h("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=Yo),M.init(e,t)}),Bs=h("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=Xo),M.init(e,t),e._zod.check=(n)=>{let i=n.value.split("/");try{if(i.length!==2)throw Error();let[r,o]=i;if(!o)throw Error();let s=Number(o);if(`${s}`!==o)throw Error();if(s<0||s>128)throw Error();new URL(`http://[${r}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}}});function hi(e){if(e==="")return!0;if(/\s/.test(e))return!1;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}var js=h("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=Qo),M.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=(n)=>{if(hi(n.value))return;n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}});function qs(e){if(!oi.test(e))return!1;let t=e.replace(/[-_]/g,(i)=>i==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return hi(n)}var Hs=h("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=oi),M.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=(n)=>{if(qs(n.value))return;n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),Ws=h("$ZodE164",(e,t)=>{t.pattern??(t.pattern=ts),M.init(e,t)});function Vs(e,t=null){try{let n=e.split(".");if(n.length!==3)return!1;let[i]=n;if(!i)return!1;let r=JSON.parse(atob(i));if("typ"in r&&r?.typ!=="JWT")return!1;if(!r.alg)return!1;if(t&&(!("alg"in r)||r.alg!==t))return!1;return!0}catch{return!1}}var Zs=h("$ZodJWT",(e,t)=>{M.init(e,t),e._zod.check=(n)=>{if(Vs(n.value,t.alg))return;n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),fi=h("$ZodNumber",(e,t)=>{S.init(e,t),e._zod.pattern=e._zod.bag.pattern??li,e._zod.parse=(n,i)=>{if(t.coerce)try{n.value=Number(n.value)}catch(s){}let r=n.value;if(typeof r==="number"&&!Number.isNaN(r)&&Number.isFinite(r))return n;let o=typeof r==="number"?Number.isNaN(r)?"NaN":!Number.isFinite(r)?"Infinity":void 0:void 0;return n.issues.push({expected:"number",code:"invalid_type",input:r,inst:e,...o?{received:o}:{}}),n}}),Gs=h("$ZodNumberFormat",(e,t)=>{ds.init(e,t),fi.init(e,t)}),Ks=h("$ZodBoolean",(e,t)=>{S.init(e,t),e._zod.pattern=as,e._zod.parse=(n,i)=>{if(t.coerce)try{n.value=Boolean(n.value)}catch(o){}let r=n.value;if(typeof r==="boolean")return n;return n.issues.push({expected:"boolean",code:"invalid_type",input:r,inst:e}),n}}),Js=h("$ZodUnknown",(e,t)=>{S.init(e,t),e._zod.parse=(n)=>n}),Ys=h("$ZodNever",(e,t)=>{S.init(e,t),e._zod.parse=(n,i)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:e}),n)}),Xs=h("$ZodVoid",(e,t)=>{S.init(e,t),e._zod.parse=(n,i)=>{let r=n.value;if(typeof r>"u")return n;return n.issues.push({expected:"void",code:"invalid_type",input:r,inst:e}),n}}),Qs=h("$ZodDate",(e,t)=>{S.init(e,t),e._zod.parse=(n,i)=>{if(t.coerce)try{n.value=new Date(n.value)}catch(s){}let r=n.value,o=r instanceof Date;if(o&&!Number.isNaN(r.getTime()))return n;return n.issues.push({expected:"date",code:"invalid_type",input:r,...o?{received:"Invalid Date"}:{},inst:e}),n}});function Tn(e,t,n){if(e.issues.length)t.issues.push(...le(n,e.issues));t.value[n]=e.value}var ea=h("$ZodArray",(e,t)=>{S.init(e,t),e._zod.parse=(n,i)=>{let r=n.value;if(!Array.isArray(r))return n.issues.push({expected:"array",code:"invalid_type",input:r,inst:e}),n;n.value=Array(r.length);let o=[];for(let s=0;s<r.length;s++){let a=r[s],u=t.element._zod.run({value:a,issues:[]},i);if(u instanceof Promise)o.push(u.then((c)=>Tn(c,n,s)));else Tn(u,n,s)}if(o.length)return Promise.all(o).then(()=>n);return n}});function et(e,t,n,i,r,o){let s=n in i;if(e.issues.length){if(r&&o&&!s)return;t.issues.push(...le(n,e.issues))}if(!s&&!r){if(!e.issues.length)t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[n]});return}if(e.value===void 0){if(s)t.value[n]=void 0}else t.value[n]=e.value}function mi(e){let t=Object.keys(e.shape);for(let i of t)if(!e.shape?.[i]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${i}": expected a Zod schema`);let n=mo(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function gi(e,t,n,i,r,o){let s=[],a=r.keySet,u=r.catchall._zod,c=u.def.type,d=u.optin==="optional",y=u.optout==="optional";for(let p in t){if(p==="__proto__")continue;if(a.has(p))continue;if(c==="never"){s.push(p);continue}let v=u.run({value:t[p],issues:[]},i);if(v instanceof Promise)e.push(v.then((b)=>et(b,n,p,t,d,y)));else et(v,n,p,t,d,y)}if(s.length)n.issues.push({code:"unrecognized_keys",keys:s,input:t,inst:o});if(!e.length)return n;return Promise.all(e).then(()=>n)}var ta=h("$ZodObject",(e,t)=>{if(S.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){let s=t.shape;Object.defineProperty(t,"shape",{get:()=>{let a={...s};return Object.defineProperty(t,"shape",{value:a}),a}})}let n=at(()=>mi(t));R(e._zod,"propValues",()=>{let s=t.shape,a={};for(let u in s){let c=s[u]._zod;if(c.values){a[u]??(a[u]=new Set);for(let d of c.values)a[u].add(d)}}return a});let i=De,r=t.catchall,o;e._zod.parse=(s,a)=>{o??(o=n.value);let u=s.value;if(!i(u))return s.issues.push({expected:"object",code:"invalid_type",input:u,inst:e}),s;s.value={};let c=[],d=o.shape;for(let y of o.keys){let p=d[y],v=p._zod.optin==="optional",b=p._zod.optout==="optional",w=p._zod.run({value:u[y],issues:[]},a);if(w instanceof Promise)c.push(w.then((F)=>et(F,s,y,u,v,b)));else et(w,s,y,u,v,b)}if(!r)return c.length?Promise.all(c).then(()=>s):s;return gi(c,u,s,a,n.value,e)}}),na=h("$ZodObjectJIT",(e,t)=>{ta.init(e,t);let n=e._zod.parse,i=at(()=>mi(t)),r=(y)=>{let p=new pi(["shape","payload","ctx"]),v=i.value,b=(H)=>{let A=gn(H);return`shape[${A}]._zod.run({ value: input[${A}], issues: [] }, ctx)`};p.write("const input = payload.value;");let w=Object.create(null),F=0;for(let H of v.keys)w[H]=`key_${F++}`;p.write("const newResult = {};");for(let H of v.keys){let A=w[H],P=gn(H),G=y[H],se=G?._zod?.optin==="optional",be=G?._zod?.optout==="optional";if(p.write(`const ${A} = ${b(H)};`),se&&be)p.write(`
4
- if (${A}.issues.length) {
5
- if (${P} in input) {
6
- payload.issues = payload.issues.concat(${A}.issues.map(iss => ({
7
- ...iss,
8
- path: iss.path ? [${P}, ...iss.path] : [${P}]
9
- })));
1
+ var Hr="input_progress";var Ts=[/\bserver is shutting down\b/i,/^(?:error:\s*)?(?:503\s*)?loading model\b/i,/\b(?:ECONNREFUSED|ECONNRESET|ECONNABORTED|EPIPE|EHOSTUNREACH|EHOSTDOWN|ENETUNREACH|ENETDOWN|ETIMEDOUT|UND_ERR_SOCKET|UND_ERR_CONNECT_TIMEOUT|UND_ERR_CLOSED)\b/,/\bsocket hang up\b/i,/\bother side closed\b/i,/\bsocket (?:was )?closed\b/i,/\bpremature close\b/i,/\bcannot connect to api\b/i,/^fetch failed$/i,/^terminated$/i,/^(?:error:\s*)?terminated:/i,/\bHTTPParserError\b/,/\bHPE_[A-Z_]+\b/,/^(?:network|connection) (?:error|failure|lost|reset)$/i,/^(?:(?:error:\s*)?(?:502|503|504)\s*)?(?:bad gateway|service unavailable|gateway time-?out)$/i,/^no healthy upstream$/i,/^(?:error:\s*)?(?:500\s*)?invalid input batch\.?$/i,/^(?:error:\s*)?got exception: speculative batch index \d+ is not inside the current sub-batch\b/i,/^(?:error:\s*)?(?:AI_TypeValidationError:\s*)?type validation failed\b[^:\n]*: value:/i,/^(?:error:\s*)?(?:AI_JSONParseError:\s*)?json parsing failed: text:/i],ws=new Set([502,503,504]);var un=/^(?:error:\s*)?evicted to keep other in-flight requests alive\b/i;function Wr(e,t){return t==="kv_evicted"||un.test((e??"").trim())}function Je(e,t=0){if(t>5||e===null||e===void 0)return!1;if(typeof e==="string"){let r=e.trim();if(un.test(r))return!0;if(!r.startsWith("{"))return!1;try{return Je(JSON.parse(r),t+1)}catch{return!1}}if(typeof e!=="object")return!1;let n=e;if(n.error_kind==="evicted_kv_full")return!0;for(let r of["error","responseBody","data","cause","message"]){let i=n[r];if(i!==void 0&&i!==e){if(Je(i,t+1))return!0}}return!1}var _s=[/projected mean tps below floor/i,/context allocation exhausted/i,/session allocation full/i,/admission (?:rejected|refused|queued)/i,/\btoo many requests\b/i,un,/\[opencoti_window_unavailable\b/];function Zr(e){let t=(n,r)=>/^[A-Z]/.test(n)?r.charAt(0).toUpperCase()+r.slice(1):r;return e.replace(/\badmission (?:rejected|refused)\b/gi,(n)=>t(n,"admission queued")).replace(/\b(?:rejected|refused)\b/gi,(n)=>t(n,"queued")).replace(/\b(?:rejecting|refusing)\b/gi,(n)=>t(n,"queueing")).replace(/\b(?:rejections|refusals)\b/gi,(n)=>t(n,"retries")).replace(/\b(?:rejection|refusal)\b/gi,(n)=>t(n,"retry"))}function Ne(e,t){let n=(e??"").trim();if(t==="rate_limited"||t==="kv_evicted"||_s.some((r)=>r.test(n)))return"refusal";if(n&&Ts.some((r)=>r.test(n)))return"transport";return}function ks(e){let t=e.code;return typeof t==="string"?t:void 0}function Es(e){let t=e.status??e.statusCode;return typeof t==="number"?t:void 0}function cn(e,t=0){if(t>5||e===null||e===void 0)return;if(typeof e==="string")return Ne(e);if(typeof e!=="object")return;let n=Es(e);if(n===429||Je(e,t))return"refusal";let r=e.message,i=typeof r==="string"?Ne(r):void 0;if(i==="refusal")return i;let o=ks(e);if(o&&Ne(o)==="transport")return"transport";if(n!==void 0&&ws.has(n))return"transport";if(i)return i;return cn(e.cause,t+1)}function Yt(e){let t=Object.values(e).filter((n)=>typeof n==="number");return Object.entries(e).filter(([n,r])=>t.indexOf(+n)===-1).map(([n,r])=>r)}function Yn(e,t="|"){return e.map((n)=>Xr(n)).join(t)}function Xt(e,t){if(typeof t==="bigint")return t.toString();return t}class Vr{constructor(e){this._getter=e,this._value=void 0}get value(){let e=this._getter;if(e!==void 0)this._value=e(),this._getter=void 0;return this._value}}function Ct(e){return new Vr(e)}function As(e){return e===null||e===void 0}function dn(e){let t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function xs(e,t){let n=e/t,r=Math.round(n),i=4*Number.EPSILON*Math.max(Math.abs(n),1);if(Math.abs(n-r)<i)return 0;return n-r}function ce(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function pn(e){let t=Object.getOwnPropertyDescriptor(e,"shape");return t?.get?t.get.raw:t?.value}function pe(e){return pn(e._zod.def)??e._zod.def.shape}function Gr(e,t,n){Object.defineProperty(e,t,{get(){let r=n();return ce(this,t,r),r},enumerable:!0,configurable:!0})}function Kr(e,t,n){if(t in e)ce(e,t,n);else e[t]=n}function _e(e,t,n,r){let i=pe(t);for(let o of n){let s=Object.getOwnPropertyDescriptor(i,o);if(!s.enumerable)continue;if(s.get)Gr(e,o,()=>{let a=t._zod.def.shape[o];return r?r(a,o):a});else Kr(e,o,r?r(s.value,o):s.value)}}function Is(e,t){for(let n of Reflect.ownKeys(t)){let r=Object.getOwnPropertyDescriptor(t,n);if(!r.enumerable)continue;if(r.get)Gr(e,n,()=>t[n]);else Kr(e,n,r.value)}}function ee(...e){let t={};for(let n of e){let r=Object.getOwnPropertyDescriptors(n);Object.assign(t,r)}return Object.defineProperties({},t)}function Cs(e){return JSON.stringify(e)}function Ss(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var Jr="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function Ye(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}var Rs=Ct(()=>{if(re.jitless)return!1;if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return Function(""),!0}catch(e){return!1}});function Me(e){if(Ye(e)===!1)return!1;let t=e.constructor;if(t===void 0)return!0;if(typeof t!=="function")return!0;let n=t.prototype;if(Ye(n)===!1)return!1;if(Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)return!1;return!0}function Yr(e){if(Me(e))return{...e};if(Array.isArray(e))return[...e];if(e instanceof Map)return new Map(e);if(e instanceof Set)return new Set(e);return e}var Os=new Set(["string","number","symbol"]);function Pe(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Te(e,t,n){let r=new e._zod.constr(t??e._zod.def);if(!t||n?.parent)r._zod.parent=e;return r}function w(e){let t=e;if(!t)return{};if(typeof t==="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}if(delete t.message,typeof t.error==="string")return{...t,error:()=>t.error};return t}function Xr(e){if(typeof e==="bigint")return e.toString()+"n";if(typeof e==="string")return`"${e}"`;return`${e}`}function Ns(e){return Object.keys(e).filter((t)=>e[t]._zod.optin!==void 0&&e[t]._zod.optout==="optional")}var Qr=(()=>({safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-340282346638528860000000000000000000000,340282346638528860000000000000000000000],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]}))(),Ms={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function Ps(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(".pick() cannot be used on object schemas containing refinements");let i={};return _e(i,e,St(e,t)),Te(e,ee(n,{shape:i,checks:[]}))}function St(e,t){let n=pe(e),r=[];for(let i of Reflect.ownKeys(t)){if(!Object.getOwnPropertyDescriptor(n,i)?.enumerable)throw Error(`Unrecognized key: "${String(i)}"`);if(t[i])r.push(i)}return r}function $s(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(".omit() cannot be used on object schemas containing refinements");let i=new Set(St(e,t)),o={};return _e(o,e,Reflect.ownKeys(pe(e)).filter((s)=>!i.has(s))),Te(e,ee(n,{shape:o,checks:[]}))}function Ls(e,t){if(!Me(t))throw Error("Invalid input to extend: expected a plain object");let n=e._zod.def.checks;if(n&&n.length>0){let r=pe(e);for(let i of Reflect.ownKeys(t))if(Object.getOwnPropertyDescriptor(r,i)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return Te(e,ee(e._zod.def,{shape:ei(e,t)}))}function ei(e,t){let n={};return _e(n,e,Reflect.ownKeys(pe(e))),Is(n,t),n}function zs(e,t){if(!Me(t))throw Error("Invalid input to safeExtend: expected a plain object");return Te(e,ee(e._zod.def,{shape:ei(e,t)}))}function Ds(e,t){if(!t?._zod?.def)throw Error("Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`.");if(e._zod.def.checks?.length)throw Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let n={};_e(n,e,Reflect.ownKeys(pe(e))),_e(n,t,Reflect.ownKeys(pe(t)));let r=ee(e._zod.def,{shape:n,get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return Te(e,r)}function Xn(e,t,n,r="partial"){let i=t._zod.def.checks;if(i&&i.length>0)throw Error(`.${r}() cannot be used on object schemas containing refinements`);let o=n?new Set(St(t,n)):void 0,s={};return _e(s,t,Reflect.ownKeys(pe(t)),e&&((a,l)=>o&&!o.has(l)?a:new e({type:"optional",innerType:a}))),Te(t,ee(t._zod.def,{shape:s,checks:[]}))}function Us(e,t,n){let r=n?new Set(St(t,n)):void 0,i={};return _e(i,t,Reflect.ownKeys(pe(t)),(o,s)=>r&&!r.has(s)?o:new e({type:"nonoptional",innerType:o})),Te(t,ee(t._zod.def,{shape:i}))}function le(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function Fs(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue===!1)return!0;return!1}function ge(e,t){return t.map((n)=>{var r;return(r=n).path??(r.path=[]),n.path.unshift(e),n})}function qe(e){return typeof e==="string"?e:e?.message}function Qn(e){let t=[];for(let n of e??[]){let r=n._zod.def;if(!/_(length|size)$|_equals$/.test(r.check))break;let i=r.maximum??r.length??r.size;if(i>=0)t.push([i,n])}return t}function Qt(e,t,n){var r;for(let i=t;i<e.length;i++)(r=e[i]).schema??(r.schema=n)}function ve(e,t,n){var r;let i=e.inst?._zod?.traits;if(i?.has("$ZodType"))if(i.has("$ZodCheck"))(r=e).schema??(r.schema=e.inst);else e.schema=e.inst;let o=e.schema!==e.inst?e.schema?._zod.def?.error:void 0,s=e.message?e.message:qe(e.inst?._zod.def?.error?.(e))??qe(o?.(e))??qe(t?.error?.(e))??qe(n.customError?.(e))??qe(n.localeError?.(e))??"Invalid input",a={};for(let l of Object.keys(e)){if(l==="inst"||l==="schema"||l==="continue"||l==="input"||l==="__proto__")continue;a[l]=e[l]}if(a.path??(a.path=[]),a.message=s,t?.reportInput)a.input=e.input;return a}var js=/[\uD800-\uDBFF]/;function fn(e){let t=e.length;if(!js.test(e))return t;let n=t;for(let r=0;r<t-1;r++)if((e.charCodeAt(r)&64512)===55296&&(e.charCodeAt(r+1)&64512)===56320)n--,r++;return n}function hn(e){if(Array.isArray(e))return"array";if(typeof e==="string")return"string";return"unknown"}function Bs(e){let t=typeof e;switch(t){case"number":return Number.isNaN(e)?"nan":"number";case"object":{if(e===null)return"null";if(Array.isArray(e))return"array";let n=e;if(n&&Object.getPrototypeOf(n)!==Object.prototype&&"constructor"in n&&n.constructor)return n.constructor.name}}return t}function Xe(...e){let[t,n,r]=e;if(typeof t==="string")return{message:t,code:"custom",input:n,inst:r};return{...t}}function qs(e,t){for(let n in t){let r=Object.getOwnPropertyDescriptor(t,n);if(r.get)Object.defineProperty(e,n,{...r,enumerable:!1});else Hs(e,n,r.value)}}function be(e,t,n,r=!0){return Object.defineProperty(e,t,{configurable:!0,writable:!0,enumerable:r,value:n}),n}function ti(e,t,n){return be(e,t,n,!1)}function mn(e,t){for(let n in e){let r=e[n];Object.defineProperty(t,n,{configurable:!0,enumerable:!0,get(){return be(this,n,r(this))},set(i){be(this,n,i)}})}return t}function Hs(e,t,n){Object.defineProperty(e,t,{configurable:!0,get(){return this==null?n:be(this,t,n.bind(this))},set(r){be(this,t,r)}})}function Ws(e,t){let n=Object.getPrototypeOf(e);return t in n?void 0:n}var qt,me=!1,Zs={configurable:!0,get(){me=!0;return}};function O(e,t,n){let r=Object.getPrototypeOf(e._zod);if(t in r&&qt!==e._zod){qt=void 0;return}qt=e._zod,Object.defineProperty(r,t,{configurable:!0,get(){Object.defineProperty(this,t,Zs);let i=me;me=!1;try{let o=n(this);if(me)delete this[t];else Object.defineProperty(this,t,{configurable:!0,writable:!0,value:o});return me=me||i,o}catch(o){throw delete this[t],me=me||i,o}},set(i){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:i})}})}function Vs(e,t,n,r){let i=Ws(e,t);if(!i)return;Object.defineProperty(i,t,{configurable:!0,get(){let o={configurable:!0,writable:!0,enumerable:r,value:void 0};return Object.defineProperty(this,t,o),o.value=n(this),Object.defineProperty(this,t,o),o.value},set(o){Object.defineProperty(this,t,{configurable:!0,writable:!0,enumerable:r,value:o})}})}var Gs="~constantCatch";function Ks(e){let t=()=>e;return t[Gs]=!0,t}var er,Ht={value:void 0,enumerable:!1},tr="captureStackTrace"in Error?Error:null;function Js(e){let t=tr;if(t){let n=t.stackTraceLimit;if(typeof n==="number"){try{t.stackTraceLimit=0}catch{return tr=null,new e}try{return new e}finally{t.stackTraceLimit=n}}}return new e}function m(e,t,n,r){let i={};function o(p){this.def=p,this.constr=h,this.traits=new Set}o.prototype=i;let s=n,a=s&&new WeakSet;function l(p,f){if(!p._zod){Ht.value=new o(f);try{Object.defineProperty(p,"_zod",Ht)}finally{Ht.value=void 0}}else if(p._zod.traits.has(e))return;if(p._zod.traits.add(e),t(p,f),a){let T=Object.getPrototypeOf(p),k=p._zod.constr.prototype,_=T;while(_&&_!==k)_=Object.getPrototypeOf(_);let B=_??T;if(!a.has(B))a.add(B),qs(B,s)}let g=h.prototype;for(let T in g){if(!Object.prototype.hasOwnProperty.call(g,T))continue;if(!(T in p))p[T]=g[T].bind(p)}}let u=r?.Parent??Object;class d extends u{}Object.defineProperty(d,"name",{value:e});function h(p){let f=r?.Parent?Js(d):this;l(f,p);let g=f._zod.deferred;if(g){for(let k of g)k();f._zod.deferred=void 0}let T=globalThis.__zod_globalConfig?.postProcessor;if(T)T(f);return f}return Object.defineProperty(h,"init",{value:l}),Object.defineProperty(h,Symbol.hasInstance,{value:(p)=>{if(r?.Parent&&p instanceof r.Parent)return!0;return p?._zod?.traits?.has(e)}}),Object.defineProperty(h,"name",{value:e}),h}class ye extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class gn extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`);this.name="ZodEncodeError"}}(er=globalThis).__zod_globalConfig??(er.__zod_globalConfig={});var re=globalThis.__zod_globalConfig;function ue(e){if(e)Object.assign(re,e);return re}function Ys(){let e=this._zod;return e.message??(e.message=JSON.stringify(e.def,Xt,2)),e.message}function Xs(e){this._zod.message=e}var Qs={get:Ys,set:Xs,enumerable:!0,configurable:!0},Wt={value:void 0,enumerable:!1},nr=new WeakSet([Object.prototype,Error.prototype]),ni=(e,t)=>{e.name="$ZodError",Wt.value=t,Object.defineProperty(e,"issues",Wt),Wt.value=void 0,Object.defineProperty(e,"message",Qs);let n=Object.getPrototypeOf(e);if(!nr.has(n))nr.add(n),Object.defineProperty(n,"toString",{configurable:!0,enumerable:!1,get(){let r=()=>this.message;return Object.defineProperty(this,"toString",{value:r,configurable:!0,writable:!0}),r},set(r){Object.defineProperty(this,"toString",{value:r,configurable:!0,writable:!0})}})},ea=m("$ZodError",ni),ri=m("$ZodError",ni,void 0,{Parent:Error});function ta(e,t,n){if(!Object.prototype.hasOwnProperty.call(e,t))if(t==="__proto__")Object.defineProperty(e,t,{value:n(),writable:!0,enumerable:!0,configurable:!0});else e[t]=n();return e[t]}function na(e,t=(n)=>n.message){let n={},r=[];for(let i of e.issues)if(i.path.length>0)ta(n,i.path[0],()=>[]).push(t(i));else r.push(t(i));return{formErrors:r,fieldErrors:n}}function ra(e,t=(n)=>n.message){let n={_errors:[]},r=(i,o=[])=>{for(let s of i.issues)if(s.code==="invalid_union"&&s.errors.length)s.errors.map((a)=>r({issues:a},[...o,...s.path]));else if(s.code==="invalid_key")r({issues:s.issues},[...o,...s.path]);else if(s.code==="invalid_element")r({issues:s.issues},[...o,...s.path]);else{let a=[...o,...s.path];if(a.length===0)n._errors.push(t(s));else{let l=n,u=0;while(u<a.length){let d=a[u],h=u===a.length-1;if(d==="_errors"){if(h)l._errors.push(t(s));u++;continue}if(!Object.prototype.hasOwnProperty.call(l,d))Object.defineProperty(l,d,{value:{_errors:[]},enumerable:!0,writable:!0,configurable:!0});let p=l[d];if(h)p._errors.push(t(s));l=p,u++}}}};return r(e),n}function Rt(e,t){return{callee:t?.callee??e,Err:t?.Err}}var Ot=(e)=>{let t=(n,r,i,o)=>{let s=i?{...i,async:!1}:{async:!1},a=n._zod.run({value:r,issues:[]},s);if(a instanceof Promise)throw new ye;if(a.issues.length){let l=new(o?.Err??e)(a.issues.map((u)=>ve(u,s,ue())));throw Jr(l,o?.callee??t),l}return a.value};return t},rr=Ot(ri),Nt=(e)=>{let t=async(n,r,i,o)=>{let s=i?{...i,async:!0}:{async:!0},a=n._zod.run({value:r,issues:[]},s);if(a instanceof Promise)a=await a;if(a.issues.length){let l=new(o?.Err??e)(a.issues.map((u)=>ve(u,s,ue())));throw Jr(l,o?.callee??t),l}return a.value};return t},ir=Nt(ri),yn=(e)=>(t,n,r)=>{let i=r?{...r,async:!1}:{async:!1},o=t._zod.run({value:n,issues:[]},i);if(o instanceof Promise)throw new ye;return o.issues.length?ii(e,o.issues,i):{success:!0,data:o.value}};function ii(e,t,n){let r;return{success:!1,get error(){if(!r)r=new e(t.map((i)=>ve(i,n,ue()))),t=void 0,n=void 0;return r},set error(i){r=i,t=void 0,n=void 0}}}var vn=(e)=>async(t,n,r)=>{let i=r?{...r,async:!0}:{async:!0},o=t._zod.run({value:n,issues:[]},i);if(o instanceof Promise)o=await o;return o.issues.length?ii(e,o.issues,i):{success:!0,data:o.value}},ia=Symbol.for("zod.compile.invalid"),oa=Symbol.for("zod.compile.fallback"),sa=(e,t,n)=>{let r=e._zod.bag.validator;if(r!==void 0){if(r(t)!==ia)return!0;if(r.definite===!0&&n===void 0)return!1}return aa(e,t,n)};function aa(e,t,n){let r=n?{...n,async:!1,abortEarly:!0}:{async:!1,abortEarly:!0},i=e._zod.bag.fallbackRun,o;if(i)r[oa]=!0,o=i({value:t,issues:[]},r);else o=e._zod.run({value:t,issues:[]},r);if(o instanceof Promise)throw new ye;return o.issues.length===0}var la=async(e,t,n)=>{let r=n?{...n,async:!0,abortEarly:!0}:{async:!0,abortEarly:!0},i=e._zod.run({value:t,issues:[]},r);if(i instanceof Promise)i=await i;return i.issues.length===0},ua=(e)=>{let t=Ot(e),n=(r,i,o,s)=>{let a=o?{...o,direction:"backward"}:{direction:"backward"};return t(r,i,a,Rt(n,s))};return n},ca=(e)=>{let t=Ot(e),n=(r,i,o,s)=>t(r,i,o,Rt(n,s));return n},da=(e)=>{let t=Nt(e),n=async(r,i,o,s)=>{let a=o?{...o,direction:"backward"}:{direction:"backward"};return await t(r,i,a,Rt(n,s))};return n},pa=(e)=>{let t=Nt(e),n=async(r,i,o,s)=>await t(r,i,o,Rt(n,s));return n},fa=(e)=>(t,n,r)=>{let i=r?{...r,direction:"backward"}:{direction:"backward"};return yn(e)(t,n,i)},ha=(e)=>(t,n,r)=>yn(e)(t,n,r),ma=(e)=>async(t,n,r)=>{let i=r?{...r,direction:"backward"}:{direction:"backward"};return vn(e)(t,n,i)},ga=(e)=>async(t,n,r)=>vn(e)(t,n,r),ya=/^[cC][0-9a-z]{6,}$/,va=/^[0-9a-z]+$/,ba=/^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/,Ta=/^[0-9a-vA-V]{20}$/,wa=/^[A-Za-z0-9]{27}$/,_a=/^[a-zA-Z0-9_-]{21}$/;function ka(e){return new RegExp(`^[a-zA-Z0-9_-]{${e}}$`)}var Ea=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Aa=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,or=(e)=>{if(!e)return/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)},xa=/^(?:[A-Za-z0-9_'+\-]+\.)*[A-Za-z0-9_'+\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Ia="^(?=[\\s\\S]*[\\p{Extended_Pictographic}\\p{Regional_Indicator}\\u20E3])[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$";function Ca(){return new RegExp(Ia,"u")}var Sa=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Ra=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,Oa=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,Na=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Ma=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Pa=/^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/,$a=/^https?$/,La=/^\+[1-9]\d{6,14}$/,oi="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))";function za(e){return new RegExp(`^${e}$`)}var Da=za(oi);function en(e){return typeof e.precision==="number"?e.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":e.precision===0?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d":`(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${e.precision}}`:e.seconds?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?":"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function Ua(e){return new RegExp(`^${en(e)}$`)}function Fa(e){let t=["Z"];if(e.offset)t.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let n=`${en({precision:e.precision,seconds:!0})}(?:${t.join("|")})`,r=e.local?`${n}|${en({precision:e.precision})}`:n;return new RegExp(`^${oi}T(?:${r})$`)}var ja=/^[\s\S]{0,}$/,Ba=/^-?\d+$/,bn=/^-?\d+(?:\.\d+)?$/,qa=/^(?:true|false)$/i,Ha=/^[^A-Z]*$/,Wa=/^[^a-z]*$/,Q=m("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),Tn=(e)=>{let t=e.value;return!As(t)&&t.length!==void 0},bt={number:"number",bigint:"bigint",object:"date"},si=m("$ZodCheckLessThan",(e,t)=>{Q.init(e,t);let n=bt[typeof t.value];e._zod.check=(r)=>{if(t.inclusive?r.value<=t.value:r.value<t.value)return;r.issues.push({origin:bt[typeof r.value]??n,code:"too_big",maximum:typeof t.value==="object"?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),ai=m("$ZodCheckGreaterThan",(e,t)=>{Q.init(e,t);let n=bt[typeof t.value];e._zod.check=(r)=>{if(t.inclusive?r.value>=t.value:r.value>t.value)return;r.issues.push({origin:bt[typeof r.value]??n,code:"too_small",minimum:typeof t.value==="object"?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Za=m("$ZodCheckMultipleOf",(e,t)=>{Q.init(e,t),e._zod.check=(n)=>{if(typeof n.value!==typeof t.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof n.value==="bigint"?t.value!==BigInt(0)&&n.value%t.value===BigInt(0):xs(n.value,t.value)===0)return;n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),Va=m("$ZodCheckNumberFormat",(e,t)=>{Q.init(e,t),t.format=t.format||"float64";let n=t.format?.includes("int"),r=n?"int":"number",[i,o]=Qr[t.format];e._zod.check=(s)=>{let a=s.value;if(n){if(!Number.isInteger(a)){s.issues.push({expected:r,format:t.format,code:"invalid_type",continue:!1,input:a,inst:e});return}if(!Number.isSafeInteger(a)){if(a>0)s.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,inclusive:!0,continue:!t.abort});else s.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,inclusive:!0,continue:!t.abort});return}}if(a<i)s.issues.push({origin:"number",input:a,code:"too_small",minimum:i,inclusive:!0,inst:e,continue:!t.abort});if(a>o)s.issues.push({origin:"number",input:a,code:"too_big",maximum:o,inclusive:!0,inst:e,continue:!t.abort})}}),Ga=m("$ZodCheckMaxLength",(e,t)=>{var n;Q.init(e,t),(n=e._zod.def).when??(n.when=Tn),e._zod.check=(r)=>{let i=r.value,o=i.length;if((typeof i==="string"&&o>t.maximum?fn(i):o)<=t.maximum)return;let s=hn(i);r.issues.push({origin:s,code:"too_big",maximum:t.maximum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),Ka=m("$ZodCheckMinLength",(e,t)=>{var n;Q.init(e,t),(n=e._zod.def).when??(n.when=Tn),e._zod.check=(r)=>{let i=r.value,o=i.length;if((typeof i==="string"&&o>=t.minimum&&o<t.minimum*2?fn(i):o)>=t.minimum)return;let s=hn(i);r.issues.push({origin:s,code:"too_small",minimum:t.minimum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),Ja=m("$ZodCheckLengthEquals",(e,t)=>{var n;Q.init(e,t),(n=e._zod.def).when??(n.when=Tn),e._zod.check=(r)=>{let i=r.value,o=i.length,s=typeof i==="string"&&o>=t.length&&o<=t.length*2?fn(i):o;if(s===t.length)return;let a=hn(i),l=s>t.length;r.issues.push({origin:a,...l?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:r.value,inst:e,continue:!t.abort})}}),Mt=m("$ZodCheckStringFormat",(e,t)=>{var n,r;if(Q.init(e,t),t.pattern)(n=e._zod).check??(n.check=(i)=>{if(t.pattern.lastIndex=0,t.pattern.test(i.value))return;i.issues.push({origin:"string",code:"invalid_format",format:t.format,input:i.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})});else(r=e._zod).check??(r.check=()=>{})}),Ya=m("$ZodCheckRegex",(e,t)=>{Mt.init(e,t),e._zod.check=(n)=>{if(t.pattern.lastIndex=0,t.pattern.test(n.value))return;n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Xa=m("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=Ha),Mt.init(e,t)}),Qa=m("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=Wa),Mt.init(e,t)}),el=m("$ZodCheckIncludes",(e,t)=>{Q.init(e,t);let n=Pe(t.includes),r=new RegExp(typeof t.position==="number"?`^.{${t.position},}${n}`:n);t.pattern=r,e._zod.check=(i)=>{if(i.value.includes(t.includes,t.position))return;i.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:i.value,inst:e,continue:!t.abort})}}),tl=m("$ZodCheckStartsWith",(e,t)=>{Q.init(e,t);let n=new RegExp(`^${Pe(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.check=(r)=>{if(r.value.startsWith(t.prefix))return;r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:r.value,inst:e,continue:!t.abort})}}),nl=m("$ZodCheckEndsWith",(e,t)=>{Q.init(e,t);let n=new RegExp(`.*${Pe(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.check=(r)=>{if(r.value.endsWith(t.suffix))return;r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:r.value,inst:e,continue:!t.abort})}}),rl=m("$ZodCheckOverwrite",(e,t)=>{Q.init(e,t),e._zod.check=(n)=>{n.value=t.tx(n.value)}});class li{constructor(e=[],t={}){this.content=[],this.indent=0,this.args=e,this.closed=t}indented(e){this.indent+=1;try{e(this)}finally{this.indent-=1}}write(e){if(typeof e==="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let t=e.split(`
2
+ `).filter((i)=>i),n=Math.min(...t.map((i)=>i.length-i.trimStart().length)),r=t.map((i)=>i.slice(n)).map((i)=>" ".repeat(this.indent*2)+i);for(let i of r)this.content.push(i)}compile(){let e=Function,t=this?.content??[""];return new e(...Object.keys(this.closed),`return function (${this.args.join(", ")}) {
3
+ ${t.join(`
4
+ `)}
5
+ };`)(...Object.values(this.closed))}}var il={major:4,minor:6,patch:7},N=m("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=il;let r=e._zod.def.checks,i=e._zod.traits.has("$ZodCheck")?[e,...r??[]]:r?.length?[...r]:[];for(let o of i)for(let s of o._zod.onattach)s(e);if(i.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let o=(a,l,u)=>{if(a.memo)return a;let d=le(a),h;for(let p of l){if(p._zod.def.when){if(Fs(a))continue;if(!p._zod.def.when(a))continue}else if(d)continue;let f=a.issues.length,g=p._zod.check(a);if(g instanceof Promise&&u?.async===!1)throw new ye;if(h||g instanceof Promise)h=(h??Promise.resolve()).then(async()=>{if(await g,a.issues.length===f)return;if(Qt(a.issues,f,e),!d)d=le(a,f)});else{if(a.issues.length===f)continue;if(Qt(a.issues,f,e),!d)d=le(a,f)}}if(h)return h.then(()=>a);return a},s=(a,l,u)=>{if(le(a))return a.aborted=!0,a;let d=o(l,i,u);if(d instanceof Promise){if(u.async===!1)throw new ye;return d.then((h)=>e._zod.parse(h,u))}return e._zod.parse(d,u)};e._zod.run=(a,l)=>{if(l.skipChecks)return e._zod.parse(a,l);if(l.direction==="backward"){let d=e._zod.parse({value:a.value,issues:[]},{...l,skipChecks:!0});if(d instanceof Promise)return d.then((h)=>s(h,a,l));return s(d,a,l)}let u=e._zod.parse(a,l);if(u instanceof Promise){if(l.async===!1)throw new ye;return u.then((d)=>o(d,i,l))}return o(u,i,l)}}},{get "~standard"(){return ti(this,"~standard",ci(this))},set "~standard"(e){be(this,"~standard",e)}}),ui=(e,t)=>e.issues.length?{issues:e.issues.map((n)=>ve(n,t,ue()))}:{value:e.value};async function ol(e,t){let n={async:!0};return ui(await e._zod.run({value:t,issues:[]},n),n)}function ci(e){return{validate:(t)=>{let n={async:!1};try{let r=e._zod.run({value:t,issues:[]},n);if(!(r instanceof Promise))return ui(r,n)}catch(r){}return ol(e,t)},vendor:"zod",version:1}}var wn=m("$ZodString",(e,t)=>{N.init(e,t),e._zod.pattern=t.pattern??ja,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch(i){}if(typeof n.value==="string")return n;return n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),z=m("$ZodStringFormat",(e,t)=>{Mt.init(e,t),wn.init(e,t)}),sl=m("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=Aa),z.init(e,t)}),al=m("$ZodUUID",(e,t)=>{if(t.version){let n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(n===void 0)throw Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=or(n))}else t.pattern??(t.pattern=or());z.init(e,t)}),ll=m("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=xa),z.init(e,t)}),di=1,Tt=2;function pi(e){try{if(typeof URL<"u"&&typeof URL.canParse==="function")return URL.canParse(e);return new URL(e),!0}catch{return!1}}function ul(e,t){if(!("normalize"in t)&&!("hostname"in t)&&!("protocol"in t))return pi(e)||Tt;return cl(e,t)}function cl(e,t){if(!t.normalize&&t.protocol?.source===$a.source&&!/^https?:\/\//i.test(e))return di;try{if(typeof URL<"u"){let n=URL;if(typeof n.parse==="function")return n.parse(e)??Tt}return new URL(e)}catch{return Tt}}var dl=/[\t\n\r]/g;function sr(e){return e.replace(dl,"")}function pl(e,t){return t.lastIndex=0,t.test(e.hostname)}function fl(e,t){return t.lastIndex=0,t.test(e.protocol.endsWith(":")?e.protocol.slice(0,-1):e.protocol)}var hl=m("$ZodURL",(e,t)=>{z.init(e,t),e._zod.check=(n)=>{try{let r=n.value.trim(),i=ul(r,t);if(i===di){n.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:n.value,inst:e,continue:!t.abort});return}if(i===Tt){n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort});return}if(i===!0){n.value=sr(r);return}if(t.hostname&&!pl(i,t.hostname))n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort});if(t.protocol&&!fl(i,t.protocol))n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort});n.value=t.normalize?i.href:sr(r);return}catch(r){n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),ml=m("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=Ca()),z.init(e,t)}),gl=m("$ZodNanoID",(e,t)=>{if(t.length!==void 0&&(!Number.isInteger(t.length)||t.length<1))throw Error(`Invalid nanoid length: ${t.length}`);t.pattern??(t.pattern=t.length===void 0?_a:ka(t.length)),z.init(e,t)}),yl=m("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=ya),z.init(e,t)}),vl=m("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=va),z.init(e,t)}),bl=m("$ZodULID",(e,t)=>{t.pattern??(t.pattern=ba),z.init(e,t)}),Tl=m("$ZodXID",(e,t)=>{t.pattern??(t.pattern=Ta),z.init(e,t)}),wl=m("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=wa),z.init(e,t)}),_l=m("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=Fa(t)),z.init(e,t)}),kl=m("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=Da),z.init(e,t)}),El=m("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=Ua(t)),z.init(e,t)}),Al=m("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=Ea),z.init(e,t)}),xl=m("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=Sa),z.init(e,t)}),Il=/^[0-9a-fA-F:.]+$/;function fi(e){if(!Il.test(e))return!1;return pi(`http://[${e}]`)}var Cl=m("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=Ra),z.init(e,t),e._zod.check=(n)=>{if(!fi(n.value))n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}}),Sl=m("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=Oa),z.init(e,t)});function Rl(e){let t=e.split("/");if(t.length!==2)return!1;let[n,r]=t;if(!r)return!1;let i=Number(r);if(`${i}`!==r)return!1;if(i<0||i>128)return!1;return fi(n)}var Ol=m("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=Na),z.init(e,t),e._zod.check=(n)=>{if(!Rl(n.value))n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}});function hi(e){if(e==="")return!0;if(/\s/.test(e))return!1;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}var mi=/^[0-9a-zA-Z+/]*={0,2}$/,Nl=m("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=mi),z.init(e,t),e._zod.check=(n)=>{if(hi(n.value))return;n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}}),_n=/^[A-Za-z0-9_-]*$/;function Ml(e){if(!_n.test(e))return!1;let t=e.replace(/[-_]/g,(r)=>r==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return hi(n)}var Pl=m("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=_n),z.init(e,t),e._zod.check=(n)=>{if(Ml(n.value))return;n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),$l=m("$ZodE164",(e,t)=>{t.pattern??(t.pattern=La),z.init(e,t)});function Ll(e,t=null){try{let n=e.split(".");if(n.length!==3)return!1;let[r]=n;if(!r)return!1;let i=JSON.parse(atob(r));if("typ"in i&&i?.typ!=="JWT")return!1;if(!i.alg)return!1;if(t&&(!("alg"in i)||i.alg!==t))return!1;return!0}catch{return!1}}var zl=m("$ZodJWT",(e,t)=>{z.init(e,t),e._zod.check=(n)=>{if(Ll(n.value,t.alg))return;n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),gi=m("$ZodNumber",(e,t)=>{N.init(e,t),e._zod.pattern=bn,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch(s){}let i=n.value;if(typeof i==="number"&&!Number.isNaN(i)&&Number.isFinite(i))return n;let o=typeof i==="number"?Number.isNaN(i)?"NaN":!Number.isFinite(i)?String(i):void 0:void 0;return n.issues.push({expected:"number",code:"invalid_type",input:i,inst:e,...o?{received:o}:{}}),n}}),Dl=m("$ZodNumberFormat",(e,t)=>{Va.init(e,t),gi.init(e,t)}),Ul=m("$ZodBoolean",(e,t)=>{N.init(e,t),e._zod.pattern=qa,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Boolean(n.value)}catch(o){}let i=n.value;if(typeof i==="boolean")return n;return n.issues.push({expected:"boolean",code:"invalid_type",input:i,inst:e}),n}}),Fl=m("$ZodUnknown",(e,t)=>{N.init(e,t),e._zod.parse=(n)=>n}),jl=m("$ZodNever",(e,t)=>{N.init(e,t),e._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:e}),n)}),Bl=m("$ZodVoid",(e,t)=>{N.init(e,t),e._zod.parse=(n,r)=>{let i=n.value;if(typeof i>"u")return n;return n.issues.push({expected:"void",code:"invalid_type",input:i,inst:e}),n}}),ql=m("$ZodDate",(e,t)=>{N.init(e,t),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=new Date(n.value)}catch(s){}let i=n.value,o=i instanceof Date;if(o&&!Number.isNaN(i.getTime()))return n;return n.issues.push({expected:"date",code:"invalid_type",input:i,...o?{received:"Invalid Date"}:{},inst:e}),n}});function Hl(e,t){let n=Qn(e._zod.def.checks);if(!n.length)return;let r=Math.min(...n.map((o)=>o[0])),i=e._zod.parse;e._zod.parse=(o,s)=>{let a=t(o.value);if(a>r&&!s?.skipChecks&&s?.direction!=="backward"){for(let[l,u]of Qn(e._zod.def.checks))if(a>l&&u._zod.def.when(o)){let d=o.issues.length;return u._zod.check(o),o.issues[d].continue=!1,Qt(o.issues,d,e),o}}return i(o,s)}}var Wl=(e)=>Array.isArray(e)?e.length:-1;function ar(e,t,n){if(e.issues.length)t.issues.push(...ge(n,e.issues));t.value[n]=e.value}var Zl=m("$ZodArray",(e,t)=>{N.init(e,t);let n=re.memoizer;n?.attach(e),e._zod.parse=(r,i)=>{let o=r.value;if(!Array.isArray(o))return r.issues.push({expected:"array",code:"invalid_type",input:o,inst:e}),r;r.value=n?n.alloc(e,r,Array(o.length),i):Array(o.length);let s=[],a=i?.abortEarly;for(let l=0;l<o.length;l++){let u=o[l],d=t.element._zod.run({value:u,issues:[]},i);if(d instanceof Promise)s.push(d.then((h)=>ar(h,r,l)));else if(ar(d,r,l),a&&d.issues.length!==0&&le(d))break}if(s.length)return Promise.all(s).then(()=>r);return r},Hl(e,Wl)});function wt(e,t,n,r,i,o){let s=n in r,a=o==="optional";if(!s&&a&&i==="optional")return;if(e.issues.length){if(i!==void 0&&a&&!s)return;t.issues.push(...ge(n,e.issues))}if(!s&&i===void 0){if(!e.issues.length)t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[n]});return}if(e.value===void 0){if(s||i==="defaulted"&&!a)t.value[n]=void 0}else t.value[n]=e.value}var Vl=[];function yi(e){let t=Object.keys(e.shape),n=Object.getOwnPropertySymbols(e.shape),r=n.length?n:Vl,i=r.length?[...t,...r]:t;for(let s of i)if(!e.shape?.[s]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${String(s)}": expected a Zod schema`);let o=Ns(e.shape);return{...e,allKeys:i,symbolKeys:r,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(o)}}function vi(e,t,n,r,i,o,s){let a=[],l=i.keySet,u=i.catchall._zod,d=u.def.type,{optin:h,optout:p}=u,f=0;for(let g in t){if(s&&n.issues.length!==f){if(le(n,f))break;f=n.issues.length}if(l.has(g))continue;if(g==="__proto__"){if(d==="never")a.push(g);continue}if(d==="never"){a.push(g);continue}let T=u.run({value:t[g],issues:[]},r);if(T instanceof Promise)e.push(T.then((k)=>wt(k,n,g,t,h,p)));else wt(T,n,g,t,h,p)}if(a.length)n.issues.push({code:"unrecognized_keys",keys:a,input:t,inst:o,continue:!0});if(!e.length)return n;return Promise.all(e).then(()=>n)}var Gl=m("$ZodObject",(e,t)=>{N.init(e,t);let n=Object.getOwnPropertyDescriptor(t,"shape"),r=n?.get?n.get.raw:t.shape??{};if(r){let u=()=>{let d={...r};return Object.defineProperty(t,"shape",{value:d}),u.raw=d,d};u.raw=r,Object.defineProperty(t,"shape",{get:u})}let i=Ct(()=>yi(t));O(e,"propValues",(u)=>{let d=u.def.shape,h={};for(let p in d){let f=d[p]._zod;if(f.values){if(!Object.prototype.hasOwnProperty.call(h,p))ce(h,p,new Set);for(let g of f.values)h[p].add(g);if(f.optin!==void 0)h[p].add(void 0)}}return h});let o=Ye,s=t.catchall,a,l=re.memoizer;l?.attach(e),e._zod.parse=(u,d)=>{a??(a=i.value);let h=u.value;if(!o(h))return u.issues.push({expected:"object",code:"invalid_type",input:h,inst:e}),u;u.value=l?l.alloc(e,u,{},d):{};let p=[],f=a.shape,g=d?.abortEarly,T=u.issues.length;for(let k of a.allKeys){if(g&&u.issues.length!==T){if(le(u,T))break;T=u.issues.length}if(k==="__proto__")continue;let _=f[k],B=_._zod.optin,J=_._zod.optout,P=_._zod.run({value:h[k],issues:[]},d);if(P instanceof Promise)p.push(P.then((E)=>wt(E,u,k,h,B,J)));else wt(P,u,k,h,B,J)}if(!s)return p.length?Promise.all(p).then(()=>u):u;return vi(p,h,u,d,i.value,e,g===!0)}}),Kl=m("$ZodObjectJIT",(e,t)=>{Gl.init(e,t);let n=e._zod.parse,r=Ct(()=>yi(t)),i=re.memoizer,o=(p)=>{let f=r.value,g=f.symbolKeys,T=new li(["payload","ctx"],{shape:p,inst:e,memo:i,syms:g}),k=(P)=>`shape[${P}]._zod.run({ value: input[${P}], issues: [] }, ctx)`,_=(P,E)=>`
6
+ let ${P}_ab = false;
7
+ for (let i = 0; i < ${P}.issues.length; i++) {
8
+ const iss = ${P}.issues[i];
9
+ iss.path = iss.path ? [${E}, ...iss.path] : [${E}];
10
+ payload.issues.push(iss);
11
+ if (iss.continue !== true) ${P}_ab = true;
10
12
  }
11
- }
12
-
13
- if (${A}.value === undefined) {
14
- if (${P} in input) {
15
- newResult[${P}] = undefined;
13
+ if (${P}_ab && ctx && ctx.abortEarly) {
14
+ payload.value = newResult;
15
+ return payload;
16
+ }`;T.write("const input = payload.value;");let B=Object.create(null),J=0;for(let P of f.allKeys)B[P]=`key_${J++}`;T.write(i?"const newResult = memo.alloc(inst, payload, {}, ctx);":"const newResult = {};");for(let P of f.allKeys){if(P==="__proto__")continue;let E=B[P],V=typeof P==="symbol"?`syms[${g.indexOf(P)}]`:Cs(P),he=`${V} in input`,oe=p[P],q=oe?._zod?.optin,C=q!==void 0,it=oe?._zod?.optout==="optional";if(T.write(`const ${E} = ${k(V)};`),C&&it){let ot=q==="optional"?`${E}_present`:`${E}.value !== undefined || ${E}_present`;T.write(`
17
+ const ${E}_present = ${he};
18
+ if (!${E}.issues.length || ${E}_present) {
19
+ if (${E}.issues.length) {${_(E,V)}
20
+ }
21
+
22
+ if (${ot}) {
23
+ newResult[${V}] = ${E}.value;
16
24
  }
17
- } else {
18
- newResult[${P}] = ${A}.value;
19
25
  }
20
-
21
- `);else if(!se)p.write(`
22
- const ${A}_present = ${P} in input;
23
- if (${A}.issues.length) {
24
- payload.issues = payload.issues.concat(${A}.issues.map(iss => ({
25
- ...iss,
26
- path: iss.path ? [${P}, ...iss.path] : [${P}]
27
- })));
26
+
27
+ `)}else if(!C)T.write(`
28
+ const ${E}_present = ${he};
29
+ if (${E}.issues.length) {${_(E,V)}
28
30
  }
29
- if (!${A}_present && !${A}.issues.length) {
31
+ if (!${E}_present && !${E}.issues.length) {
30
32
  payload.issues.push({
31
33
  code: "invalid_type",
32
34
  expected: "nonoptional",
33
35
  input: undefined,
34
- path: [${P}]
36
+ path: [${V}]
35
37
  });
38
+ if (ctx && ctx.abortEarly) {
39
+ payload.value = newResult;
40
+ return payload;
41
+ }
36
42
  }
37
43
 
38
- if (${A}_present) {
39
- if (${A}.value === undefined) {
40
- newResult[${P}] = undefined;
41
- } else {
42
- newResult[${P}] = ${A}.value;
43
- }
44
+ if (${E}_present) {
45
+ newResult[${V}] = ${E}.value;
44
46
  }
45
47
 
46
- `);else p.write(`
47
- if (${A}.issues.length) {
48
- payload.issues = payload.issues.concat(${A}.issues.map(iss => ({
49
- ...iss,
50
- path: iss.path ? [${P}, ...iss.path] : [${P}]
51
- })));
48
+ `);else if(T.write(`
49
+ if (${E}.issues.length) {${_(E,V)}
52
50
  }
53
-
54
- if (${A}.value === undefined) {
55
- if (${P} in input) {
56
- newResult[${P}] = undefined;
57
- }
58
- } else {
59
- newResult[${P}] = ${A}.value;
51
+ `),q==="defaulted")T.write(`newResult[${V}] = ${E}.value;`);else T.write(`
52
+ if (${E}.value !== undefined || ${he}) {
53
+ newResult[${V}] = ${E}.value;
60
54
  }
61
-
62
- `)}p.write("payload.value = newResult;"),p.write("return payload;");let B=p.compile();return(H,A)=>B(y,H,A)},o,s=De,a=!Qe.jitless,u=a&&ho.value,c=t.catchall,d;e._zod.parse=(y,p)=>{d??(d=i.value);let v=y.value;if(!s(v))return y.issues.push({expected:"object",code:"invalid_type",input:v,inst:e}),y;if(a&&u&&p?.async===!1&&p.jitless!==!0){if(!o)o=r(t.shape);if(y=o(y,p),!c)return y;return gi([],v,y,p,d,e)}return n(y,p)}});function wn(e,t,n,i){for(let o of e)if(o.issues.length===0)return t.value=o.value,t;let r=e.filter((o)=>!_e(o));if(r.length===1)return t.value=r[0].value,r[0];return t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map((o)=>o.issues.map((s)=>re(s,i,ne())))}),t}var yi=h("$ZodUnion",(e,t)=>{S.init(e,t),R(e._zod,"optin",()=>t.options.some((i)=>i._zod.optin==="optional")?"optional":void 0),R(e._zod,"optout",()=>t.options.some((i)=>i._zod.optout==="optional")?"optional":void 0),R(e._zod,"values",()=>{if(t.options.every((i)=>i._zod.values))return new Set(t.options.flatMap((i)=>Array.from(i._zod.values)));return}),R(e._zod,"pattern",()=>{if(t.options.every((i)=>i._zod.pattern)){let i=t.options.map((r)=>r._zod.pattern);return new RegExp(`^(${i.map((r)=>$t(r.source)).join("|")})$`)}return});let n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(i,r)=>{if(n)return n(i,r);let o=!1,s=[];for(let a of t.options){let u=a._zod.run({value:i.value,issues:[]},r);if(u instanceof Promise)s.push(u),o=!0;else{if(u.issues.length===0)return u;s.push(u)}}if(!o)return wn(s,i,e,r);return Promise.all(s).then((a)=>wn(a,i,e,r))}}),ia=h("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,yi.init(e,t);let n=e._zod.parse;R(e._zod,"propValues",()=>{let r={};for(let o of t.options){let s=o._zod.propValues;if(!s||Object.keys(s).length===0)throw Error(`Invalid discriminated union option at index "${t.options.indexOf(o)}"`);for(let[a,u]of Object.entries(s)){if(!r[a])r[a]=new Set;for(let c of u)r[a].add(c)}}return r});let i=at(()=>{let r=t.options,o=new Map;for(let s of r){let a=s._zod.propValues?.[t.discriminator];if(!a||a.size===0)throw Error(`Invalid discriminated union option at index "${t.options.indexOf(s)}"`);for(let u of a){if(o.has(u))throw Error(`Duplicate discriminator value "${String(u)}"`);o.set(u,s)}}return o});e._zod.parse=(r,o)=>{let s=r.value;if(!De(s))return r.issues.push({code:"invalid_type",expected:"object",input:s,inst:e}),r;let a=i.value.get(s?.[t.discriminator]);if(a)return a._zod.run(r,o);if(t.unionFallback||o.direction==="backward")return n(r,o);return r.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,options:Array.from(i.value.keys()),input:s,path:[t.discriminator],inst:e}),r}}),ra=h("$ZodIntersection",(e,t)=>{S.init(e,t),e._zod.parse=(n,i)=>{let r=n.value,o=t.left._zod.run({value:r,issues:[]},i),s=t.right._zod.run({value:r,issues:[]},i);if(o instanceof Promise||s instanceof Promise)return Promise.all([o,s]).then(([a,u])=>_n(n,a,u));return _n(n,o,s)}});function Ct(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e===+t)return{valid:!0,data:e};if(Ae(e)&&Ae(t)){let n=Object.keys(t),i=Object.keys(e).filter((o)=>n.indexOf(o)!==-1),r={...e,...t};for(let o of i){let s=Ct(e[o],t[o]);if(!s.valid)return{valid:!1,mergeErrorPath:[o,...s.mergeErrorPath]};r[o]=s.data}return{valid:!0,data:r}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let i=0;i<e.length;i++){let r=e[i],o=t[i],s=Ct(r,o);if(!s.valid)return{valid:!1,mergeErrorPath:[i,...s.mergeErrorPath]};n.push(s.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function _n(e,t,n){let i=new Map,r;for(let a of t.issues)if(a.code==="unrecognized_keys"){r??(r=a);for(let u of a.keys){if(!i.has(u))i.set(u,{});i.get(u).l=!0}}else e.issues.push(a);for(let a of n.issues)if(a.code==="unrecognized_keys")for(let u of a.keys){if(!i.has(u))i.set(u,{});i.get(u).r=!0}else e.issues.push(a);let o=[...i].filter(([,a])=>a.l&&a.r).map(([a])=>a);if(o.length&&r)e.issues.push({...r,keys:o});if(_e(e))return e;let s=Ct(t.value,n.value);if(!s.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(s.mergeErrorPath)}`);return e.value=s.data,e}var vi=h("$ZodTuple",(e,t)=>{S.init(e,t);let n=t.items;e._zod.parse=(i,r)=>{let o=i.value;if(!Array.isArray(o))return i.issues.push({input:o,inst:e,expected:"tuple",code:"invalid_type"}),i;i.value=[];let s=[],a=kn(n,"optin"),u=kn(n,"optout");if(!t.rest){if(o.length<a)return i.issues.push({code:"too_small",minimum:a,inclusive:!0,input:o,inst:e,origin:"array"}),i;if(o.length>n.length)i.issues.push({code:"too_big",maximum:n.length,inclusive:!0,input:o,inst:e,origin:"array"})}let c=Array(n.length);for(let d=0;d<n.length;d++){let y=n[d]._zod.run({value:o[d],issues:[]},r);if(y instanceof Promise)s.push(y.then((p)=>{c[d]=p}));else c[d]=y}if(t.rest){let d=n.length-1,y=o.slice(n.length);for(let p of y){d++;let v=t.rest._zod.run({value:p,issues:[]},r);if(v instanceof Promise)s.push(v.then((b)=>En(b,i,d)));else En(v,i,d)}}if(s.length)return Promise.all(s).then(()=>In(c,i,n,o,u));return In(c,i,n,o,u)}});function kn(e,t){for(let n=e.length-1;n>=0;n--)if(e[n]._zod[t]!=="optional")return n+1;return 0}function En(e,t,n){if(e.issues.length)t.issues.push(...le(n,e.issues));t.value[n]=e.value}function In(e,t,n,i,r){for(let o=0;o<n.length;o++){let s=e[o],a=o<i.length;if(s.issues.length){if(!a&&o>=r){t.value.length=o;break}t.issues.push(...le(o,s.issues))}t.value[o]=s.value}for(let o=t.value.length-1;o>=i.length;o--)if(n[o]._zod.optout==="optional"&&t.value[o]===void 0)t.value.length=o;else break;return t}var oa=h("$ZodRecord",(e,t)=>{S.init(e,t),e._zod.parse=(n,i)=>{let r=n.value;if(!Ae(r))return n.issues.push({expected:"record",code:"invalid_type",input:r,inst:e}),n;let o=[],s=t.keyType._zod.values;if(s){n.value={};let a=new Set;for(let c of s)if(typeof c==="string"||typeof c==="number"||typeof c==="symbol"){a.add(typeof c==="number"?c.toString():c);let d=t.keyType._zod.run({value:c,issues:[]},i);if(d instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(d.issues.length){n.issues.push({code:"invalid_key",origin:"record",issues:d.issues.map((v)=>re(v,i,ne())),input:c,path:[c],inst:e});continue}let y=d.value,p=t.valueType._zod.run({value:r[c],issues:[]},i);if(p instanceof Promise)o.push(p.then((v)=>{if(v.issues.length)n.issues.push(...le(c,v.issues));n.value[y]=v.value}));else{if(p.issues.length)n.issues.push(...le(c,p.issues));n.value[y]=p.value}}let u;for(let c in r)if(!a.has(c))u=u??[],u.push(c);if(u&&u.length>0)n.issues.push({code:"unrecognized_keys",input:r,inst:e,keys:u})}else{n.value={};for(let a of Reflect.ownKeys(r)){if(a==="__proto__")continue;if(!Object.prototype.propertyIsEnumerable.call(r,a))continue;let u=t.keyType._zod.run({value:a,issues:[]},i);if(u instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(typeof a==="string"&&li.test(a)&&u.issues.length){let d=t.keyType._zod.run({value:Number(a),issues:[]},i);if(d instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(d.issues.length===0)u=d}if(u.issues.length){if(t.mode==="loose")n.value[a]=r[a];else n.issues.push({code:"invalid_key",origin:"record",issues:u.issues.map((d)=>re(d,i,ne())),input:a,path:[a],inst:e});continue}let c=t.valueType._zod.run({value:r[a],issues:[]},i);if(c instanceof Promise)o.push(c.then((d)=>{if(d.issues.length)n.issues.push(...le(a,d.issues));n.value[u.value]=d.value}));else{if(c.issues.length)n.issues.push(...le(a,c.issues));n.value[u.value]=c.value}}}if(o.length)return Promise.all(o).then(()=>n);return n}}),sa=h("$ZodEnum",(e,t)=>{S.init(e,t);let n=Qn(t.entries),i=new Set(n);e._zod.values=i,e._zod.pattern=new RegExp(`^(${n.filter((r)=>fo.has(typeof r)).map((r)=>typeof r==="string"?xe(r):r.toString()).join("|")})$`),e._zod.parse=(r,o)=>{let s=r.value;if(i.has(s))return r;return r.issues.push({code:"invalid_value",values:n,input:s,inst:e}),r}}),aa=h("$ZodLiteral",(e,t)=>{if(S.init(e,t),t.values.length===0)throw Error("Cannot create literal schema with no valid values");let n=new Set(t.values);e._zod.values=n,e._zod.pattern=new RegExp(`^(${t.values.map((i)=>typeof i==="string"?xe(i):i?xe(i.toString()):String(i)).join("|")})$`),e._zod.parse=(i,r)=>{let o=i.value;if(n.has(o))return i;return i.issues.push({code:"invalid_value",values:t.values,input:o,inst:e}),i}}),la=h("$ZodTransform",(e,t)=>{S.init(e,t),e._zod.optin="optional",e._zod.parse=(n,i)=>{if(i.direction==="backward")throw new Mt(e.constructor.name);let r=t.transform(n.value,n);if(i.async)return(r instanceof Promise?r:Promise.resolve(r)).then((o)=>(n.value=o,n.fallback=!0,n));if(r instanceof Promise)throw new pe;return n.value=r,n.fallback=!0,n}});function An(e,t){if(t===void 0&&(e.issues.length||e.fallback))return{issues:[],value:void 0};return e}var bi=h("$ZodOptional",(e,t)=>{S.init(e,t),e._zod.optin="optional",e._zod.optout="optional",R(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),R(e._zod,"pattern",()=>{let n=t.innerType._zod.pattern;return n?new RegExp(`^(${$t(n.source)})?$`):void 0}),e._zod.parse=(n,i)=>{if(t.innerType._zod.optin==="optional"){let r=n.value,o=t.innerType._zod.run(n,i);if(o instanceof Promise)return o.then((s)=>An(s,r));return An(o,r)}if(n.value===void 0)return n;return t.innerType._zod.run(n,i)}}),ua=h("$ZodExactOptional",(e,t)=>{bi.init(e,t),R(e._zod,"values",()=>t.innerType._zod.values),R(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(n,i)=>t.innerType._zod.run(n,i)}),ca=h("$ZodNullable",(e,t)=>{S.init(e,t),R(e._zod,"optin",()=>t.innerType._zod.optin),R(e._zod,"optout",()=>t.innerType._zod.optout),R(e._zod,"pattern",()=>{let n=t.innerType._zod.pattern;return n?new RegExp(`^(${$t(n.source)}|null)$`):void 0}),R(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(n,i)=>{if(n.value===null)return n;return t.innerType._zod.run(n,i)}}),da=h("$ZodDefault",(e,t)=>{S.init(e,t),e._zod.optin="optional",R(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,i)=>{if(i.direction==="backward")return t.innerType._zod.run(n,i);if(n.value===void 0)return n.value=t.defaultValue,n;let r=t.innerType._zod.run(n,i);if(r instanceof Promise)return r.then((o)=>xn(o,t));return xn(r,t)}});function xn(e,t){if(e.value===void 0)e.value=t.defaultValue;return e}var pa=h("$ZodPrefault",(e,t)=>{S.init(e,t),e._zod.optin="optional",R(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,i)=>{if(i.direction==="backward")return t.innerType._zod.run(n,i);if(n.value===void 0)n.value=t.defaultValue;return t.innerType._zod.run(n,i)}}),ha=h("$ZodNonOptional",(e,t)=>{S.init(e,t),R(e._zod,"values",()=>{let n=t.innerType._zod.values;return n?new Set([...n].filter((i)=>i!==void 0)):void 0}),e._zod.parse=(n,i)=>{let r=t.innerType._zod.run(n,i);if(r instanceof Promise)return r.then((o)=>Cn(o,e));return Cn(r,e)}});function Cn(e,t){if(!e.issues.length&&e.value===void 0)e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t});return e}var fa=h("$ZodCatch",(e,t)=>{S.init(e,t),e._zod.optin="optional",R(e._zod,"optout",()=>t.innerType._zod.optout),R(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,i)=>{if(i.direction==="backward")return t.innerType._zod.run(n,i);let r=t.innerType._zod.run(n,i);if(r instanceof Promise)return r.then((o)=>{if(n.value=o.value,o.issues.length)n.value=t.catchValue({...n,error:{issues:o.issues.map((s)=>re(s,i,ne()))},input:n.value}),n.issues=[],n.fallback=!0;return n});if(n.value=r.value,r.issues.length)n.value=t.catchValue({...n,error:{issues:r.issues.map((o)=>re(o,i,ne()))},input:n.value}),n.issues=[],n.fallback=!0;return n}}),Ti=h("$ZodPipe",(e,t)=>{S.init(e,t),R(e._zod,"values",()=>t.in._zod.values),R(e._zod,"optin",()=>t.in._zod.optin),R(e._zod,"optout",()=>t.out._zod.optout),R(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(n,i)=>{if(i.direction==="backward"){let o=t.out._zod.run(n,i);if(o instanceof Promise)return o.then((s)=>Ge(s,t.in,i));return Ge(o,t.in,i)}let r=t.in._zod.run(n,i);if(r instanceof Promise)return r.then((o)=>Ge(o,t.out,i));return Ge(r,t.out,i)}});function Ge(e,t,n){if(e.issues.length)return e.aborted=!0,e;return t._zod.run({value:e.value,issues:e.issues,fallback:e.fallback},n)}var ma=h("$ZodPreprocess",(e,t)=>{Ti.init(e,t)}),ga=h("$ZodReadonly",(e,t)=>{S.init(e,t),R(e._zod,"propValues",()=>t.innerType._zod.propValues),R(e._zod,"values",()=>t.innerType._zod.values),R(e._zod,"optin",()=>t.innerType?._zod?.optin),R(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(n,i)=>{if(i.direction==="backward")return t.innerType._zod.run(n,i);let r=t.innerType._zod.run(n,i);if(r instanceof Promise)return r.then(Rn);return Rn(r)}});function Rn(e){return e.value=Object.freeze(e.value),e}var ya=h("$ZodFunction",(e,t)=>(S.init(e,t),e._def=t,e._zod.def=t,e.implement=(n)=>{if(typeof n!=="function")throw Error("implement() must be called with a function");return function(...i){let r=e._def.input?yn(e._def.input,i):i,o=Reflect.apply(n,this,r);if(e._def.output)return yn(e._def.output,o);return o}},e.implementAsync=(n)=>{if(typeof n!=="function")throw Error("implementAsync() must be called with a function");return async function(...i){let r=e._def.input?await vn(e._def.input,i):i,o=await Reflect.apply(n,this,r);if(e._def.output)return await vn(e._def.output,o);return o}},e._zod.parse=(n,i)=>{if(typeof n.value!=="function")return n.issues.push({code:"invalid_type",expected:"function",input:n.value,inst:e}),n;if(e._def.output&&e._def.output._zod.def.type==="promise")n.value=e.implementAsync(n.value);else n.value=e.implement(n.value);return n},e.input=(...n)=>{let i=e.constructor;if(Array.isArray(n[0]))return new i({type:"function",input:new vi({type:"tuple",items:n[0],rest:n[1]}),output:e._def.output});return new i({type:"function",input:n[0],output:e._def.output})},e.output=(n)=>new e.constructor({type:"function",input:e._def.input,output:n}),e)),va=h("$ZodPromise",(e,t)=>{S.init(e,t),e._zod.parse=(n,i)=>Promise.resolve(n.value).then((r)=>t.innerType._zod.run({value:r,issues:[]},i))}),ba=h("$ZodCustom",(e,t)=>{J.init(e,t),S.init(e,t),e._zod.parse=(n,i)=>n,e._zod.check=(n)=>{let i=n.value,r=t.fn(i);if(r instanceof Promise)return r.then((o)=>Sn(o,n,i,e));Sn(r,n,i,e);return}});function Sn(e,t,n,i){if(!e){let r={code:"custom",input:n,inst:i,path:[...i._zod.def.path??[]],continue:!i._zod.def.abort};if(i._zod.def.params)r.params=i._zod.def.params;t.issues.push(Ue(r))}}var Ta=()=>{let e={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"},map:{unit:"entries",verb:"to have"}};function t(r){return e[r]??null}let n={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"},i={nan:"NaN"};return(r)=>{switch(r.code){case"invalid_type":{let o=i[r.expected]??r.expected,s=Io(r.input),a=i[s]??s;return`Invalid input: expected ${o}, received ${a}`}case"invalid_value":if(r.values.length===1)return`Invalid input: expected ${ni(r.values[0])}`;return`Invalid option: expected one of ${fn(r.values,"|")}`;case"too_big":{let o=r.inclusive?"<=":"<",s=t(r.origin);if(s)return`Too big: expected ${r.origin??"value"} to have ${o}${r.maximum.toString()} ${s.unit??"elements"}`;return`Too big: expected ${r.origin??"value"} to be ${o}${r.maximum.toString()}`}case"too_small":{let o=r.inclusive?">=":">",s=t(r.origin);if(s)return`Too small: expected ${r.origin} to have ${o}${r.minimum.toString()} ${s.unit}`;return`Too small: expected ${r.origin} to be ${o}${r.minimum.toString()}`}case"invalid_format":{let o=r;if(o.format==="starts_with")return`Invalid string: must start with "${o.prefix}"`;if(o.format==="ends_with")return`Invalid string: must end with "${o.suffix}"`;if(o.format==="includes")return`Invalid string: must include "${o.includes}"`;if(o.format==="regex")return`Invalid string: must match pattern ${o.pattern}`;return`Invalid ${n[o.format]??r.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${r.divisor}`;case"unrecognized_keys":return`Unrecognized key${r.keys.length>1?"s":""}: ${fn(r.keys,", ")}`;case"invalid_key":return`Invalid key in ${r.origin}`;case"invalid_union":if(r.options&&Array.isArray(r.options)&&r.options.length>0)return`Invalid discriminator value. Expected ${r.options.map((o)=>`'${o}'`).join(" | ")}`;return"Invalid input";case"invalid_element":return`Invalid value in ${r.origin}`;default:return"Invalid input"}}};function wa(){return{localeError:Ta()}}var Nn,Vp=Symbol("ZodOutput"),Zp=Symbol("ZodInput");class wi{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){let n=t[0];if(this._map.set(e,n),n&&typeof n==="object"&&"id"in n)this._idmap.set(n.id,e);return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let t=this._map.get(e);if(t&&typeof t==="object"&&"id"in t)this._idmap.delete(t.id);return this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let n={...this.get(t)??{}};delete n.id;let i={...n,...this._map.get(e)};return Object.keys(i).length?i:void 0}return this._map.get(e)}has(e){return this._map.has(e)}}function _a(){return new wi}(Nn=globalThis).__zod_globalRegistry??(Nn.__zod_globalRegistry=_a());var Pe=globalThis.__zod_globalRegistry;function ka(e,t){return new e({type:"string",...T(t)})}function Ea(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...T(t)})}function On(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...T(t)})}function Ia(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...T(t)})}function Aa(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...T(t)})}function xa(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...T(t)})}function Ca(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...T(t)})}function Ra(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...T(t)})}function Sa(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...T(t)})}function Na(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...T(t)})}function Oa(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...T(t)})}function Ma(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...T(t)})}function Pa(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...T(t)})}function $a(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...T(t)})}function La(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...T(t)})}function za(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...T(t)})}function Da(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...T(t)})}function Ua(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...T(t)})}function Fa(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...T(t)})}function Ba(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...T(t)})}function ja(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...T(t)})}function qa(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...T(t)})}function Ha(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...T(t)})}function Wa(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...T(t)})}function Va(e,t){return new e({type:"string",format:"date",check:"string_format",...T(t)})}function Za(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...T(t)})}function Ga(e,t){return new e({type:"string",format:"duration",check:"string_format",...T(t)})}function Ka(e,t){return new e({type:"number",checks:[],...T(t)})}function Ja(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...T(t)})}function Ya(e,t){return new e({type:"boolean",...T(t)})}function Xa(e){return new e({type:"unknown"})}function Qa(e,t){return new e({type:"never",...T(t)})}function el(e,t){return new e({type:"void",...T(t)})}function tl(e,t){return new e({type:"date",...T(t)})}function Mn(e,t){return new ci({check:"less_than",...T(t),value:e,inclusive:!1})}function Ye(e,t){return new ci({check:"less_than",...T(t),value:e,inclusive:!0})}function Pn(e,t){return new di({check:"greater_than",...T(t),value:e,inclusive:!1})}function Xe(e,t){return new di({check:"greater_than",...T(t),value:e,inclusive:!0})}function $n(e,t){return new cs({check:"multiple_of",...T(t),value:e})}function _i(e,t){return new ps({check:"max_length",...T(t),maximum:e})}function tt(e,t){return new hs({check:"min_length",...T(t),minimum:e})}function ki(e,t){return new fs({check:"length_equals",...T(t),length:e})}function nl(e,t){return new ms({check:"string_format",format:"regex",...T(t),pattern:e})}function il(e){return new gs({check:"string_format",format:"lowercase",...T(e)})}function rl(e){return new ys({check:"string_format",format:"uppercase",...T(e)})}function ol(e,t){return new vs({check:"string_format",format:"includes",...T(t),includes:e})}function sl(e,t){return new bs({check:"string_format",format:"starts_with",...T(t),prefix:e})}function al(e,t){return new Ts({check:"string_format",format:"ends_with",...T(t),suffix:e})}function Re(e){return new ws({check:"overwrite",tx:e})}function ll(e){return Re((t)=>t.normalize(e))}function ul(){return Re((e)=>e.trim())}function cl(){return Re((e)=>e.toLowerCase())}function dl(){return Re((e)=>e.toUpperCase())}function pl(){return Re((e)=>po(e))}function hl(e,t,n){return new e({type:"array",element:t,...T(n)})}function fl(e,t,n){let i=T(n);return i.abort??(i.abort=!0),new e({type:"custom",check:"custom",fn:t,...i})}function ml(e,t,n){return new e({type:"custom",check:"custom",fn:t,...T(n)})}function gl(e,t){let n=yl((i)=>(i.addIssue=(r)=>{if(typeof r==="string")i.issues.push(Ue(r,i.value,n._zod.def));else{let o=r;if(o.fatal)o.continue=!1;o.code??(o.code="custom"),o.input??(o.input=i.value),o.inst??(o.inst=n),o.continue??(o.continue=!n._zod.def.abort),i.issues.push(Ue(o))}},e(i.value,i)),t);return n}function yl(e,t){let n=new J({check:"custom",...T(t)});return n._zod.check=e,n}function nt(e){let t=e?.target??"draft-2020-12";if(t==="draft-4")t="draft-04";if(t==="draft-7")t="draft-07";return{processors:e.processors??{},metadataRegistry:e?.metadata??Pe,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 O(e,t,n={path:[],schemaPath:[]}){var i;let r=e._zod.def,o=t.seen.get(e);if(o){if(o.count++,n.schemaPath.includes(e))o.cycle=n.path;return o.schema}let s={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,s);let a=e._zod.toJSONSchema?.();if(a)s.schema=a;else{let c={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,s.schema,c);else{let y=s.schema,p=t.processors[r.type];if(!p)throw Error(`[toJSONSchema]: Non-representable type encountered: ${r.type}`);p(e,t,y,c)}let d=e._zod.parent;if(d){if(!s.ref)s.ref=d;O(d,t,c),t.seen.get(d).isParent=!0}}let u=t.metadataRegistry.get(e);if(u)Object.assign(s.schema,u);if(t.io==="input"&&Z(e))delete s.schema.examples,delete s.schema.default;if(t.io==="input"&&"_prefault"in s.schema)(i=s.schema).default??(i.default=s.schema._prefault);return delete s.schema._prefault,t.seen.get(e).schema}function it(e,t){let n=e.seen.get(t);if(!n)throw Error("Unprocessed schema. This is a bug in Zod.");let i=new Map;for(let s of e.seen.entries()){let a=e.metadataRegistry.get(s[0])?.id;if(a){let u=i.get(a);if(u&&u!==s[0])throw Error(`Duplicate schema id "${a}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);i.set(a,s[0])}}let r=(s)=>{let a=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){let d=e.external.registry.get(s[0])?.id,y=e.external.uri??((v)=>v);if(d)return{ref:y(d)};let p=s[1].defId??s[1].schema.id??`schema${e.counter++}`;return s[1].defId=p,{defId:p,ref:`${y("__shared")}#/${a}/${p}`}}if(s[1]===n)return{ref:"#"};let u=`#/${a}/`,c=s[1].schema.id??`__schema${e.counter++}`;return{defId:c,ref:u+c}},o=(s)=>{if(s[1].schema.$ref)return;let a=s[1],{ref:u,defId:c}=r(s);if(a.def={...a.schema},c)a.defId=c;let d=a.schema;for(let y in d)delete d[y];d.$ref=u};if(e.cycles==="throw")for(let s of e.seen.entries()){let a=s[1];if(a.cycle)throw Error(`Cycle detected: #/${a.cycle?.join("/")}/<root>
55
+ `)}return T.write("payload.value = newResult;"),T.write("return payload;"),T.compile()},s,a=Ye,l=!re.jitless,u=l&&Rs.value,d=t.catchall,h;e._zod.parse=(p,f)=>{h??(h=r.value);let g=p.value;if(!a(g))return p.issues.push({expected:"object",code:"invalid_type",input:g,inst:e}),p;if(l&&u&&f?.async===!1&&f.jitless!==!0){if(!s)s=o(t.shape);if(p=s(p,f),!d)return p;return vi([],g,p,f,h,e,f?.abortEarly===!0)}return n(p,f)}});function lr(e,t,n,r){for(let o of e)if(o.issues.length===0)return t.value=o.value,t;let i=e.filter((o)=>!le(o));if(i.length===1)return t.value=i[0].value,i[0];return t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map((o)=>o.issues.map((s)=>ve(s,r,ue())))}),t}var bi=m("$ZodUnion",(e,t)=>{N.init(e,t),O(e,"optin",(r)=>r.def.options.some((i)=>i._zod.optin==="defaulted")?"defaulted":r.def.options.some((i)=>i._zod.optin!==void 0)?"optional":void 0),O(e,"optout",(r)=>r.def.options.some((i)=>i._zod.optout==="optional")?"optional":void 0),O(e,"values",(r)=>{if(r.def.options.every((i)=>i._zod.values))return new Set(r.def.options.flatMap((i)=>Array.from(i._zod.values)));return}),O(e,"pattern",(r)=>{if(r.def.options.every((i)=>i._zod.pattern)){let i=r.def.options.map((o)=>o._zod.pattern);return new RegExp(`^(${i.map((o)=>dn(o.source)).join("|")})$`)}return});let n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(r,i)=>{if(n)return n(r,i);let o=!1,s=[];for(let a of t.options){let l=a._zod.run({value:r.value,issues:[]},i);if(l instanceof Promise)s.push(l),o=!0;else{if(l.issues.length===0)return l;s.push(l)}}if(!o)return lr(s,r,e,i);return Promise.all(s).then((a)=>lr(a,r,e,i))}});function Jl(e){let t=new Map;for(let n of e.options){let r=n._zod.propValues?.[e.discriminator];if(!r||r.size===0)throw Error(`Invalid discriminated union option at index "${e.options.indexOf(n)}"`);for(let i of r)if(t.has(i)){if(i!==void 0)throw Error(`Duplicate discriminator value "${String(i)}"`);t.set(i,null)}else t.set(i,n)}return t}var Yl=m("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,bi.init(e,t);let n=e._zod.parse;O(e,"propValues",(i)=>{let o={},s=0;for(let a of i.def.options){let l=a._zod.propValues;if(!l||Object.keys(l).length===0)throw Error(`Invalid discriminated union option at index "${i.def.options.indexOf(a)}"`);if(l[i.def.discriminator]?.has(void 0))s++;for(let[u,d]of Object.entries(l)){if(!Object.prototype.hasOwnProperty.call(o,u))ce(o,u,new Set);for(let h of d)o[u].add(h)}}if(!i.def.unionFallback&&s>1)o[i.def.discriminator]?.delete(void 0);return o}),t.options.forEach((i,o)=>{let s=pn(i._zod.def);if(s&&!Object.prototype.hasOwnProperty.call(s,t.discriminator))throw Error(`Invalid discriminated union option at index "${o}"`)});let r=Ct(()=>Jl(t));e._zod.parse=(i,o)=>{let s=i.value;if(!Ye(s))return i.issues.push({code:"invalid_type",expected:"object",input:s,inst:e}),i;let a=s?.[t.discriminator],l=r.value.get(a);if(l&&(a!==void 0||o.direction!=="backward"))return l._zod.run(i,o);if(t.unionFallback||o.direction==="backward")return n(i,o);return i.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,options:Array.from(r.value.keys()).filter((u)=>r.value.get(u)!==null),input:s,path:[t.discriminator],inst:e}),i}}),Xl=m("$ZodIntersection",(e,t)=>{N.init(e,t),e._zod.parse=(n,r)=>{let i=n.value,o=t.left._zod.run({value:i,issues:[]},r),s=t.right._zod.run({value:i,issues:[]},r);if(o instanceof Promise||s instanceof Promise)return Promise.all([o,s]).then(([a,l])=>ur(n,a,l));return ur(n,o,s)}});function tn(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e===+t)return{valid:!0,data:e};if(Me(e)&&Me(t)){let n=Object.keys(t),r=Object.keys(e).filter((o)=>n.indexOf(o)!==-1),i={...e,...t};if(Object.prototype.hasOwnProperty.call(i,"__proto__"))delete i.__proto__;for(let o of r){if(o==="__proto__")continue;let s=tn(e[o],t[o]);if(!s.valid)return{valid:!1,mergeErrorPath:[o,...s.mergeErrorPath]};i[o]=s.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],o=t[r],s=tn(i,o);if(!s.valid)return{valid:!1,mergeErrorPath:[r,...s.mergeErrorPath]};n.push(s.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function ur(e,t,n){let r=new Map,i,o=new Map,s=(u,d)=>{let h;if(u.code==="unrecognized_keys"&&!u.path?.length)i??(i=u),h=u.keys;else if(u.code==="invalid_key"&&u.origin==="record"&&u.path?.length===1){let p=String(u.path[0]);if(!o.has(p))o.set(p,u);h=[p]}else return!1;for(let p of h){if(!r.has(p))r.set(p,{});r.get(p)[d]=!0}return!0};for(let u of t.issues)if(!s(u,"l"))e.issues.push(u);for(let u of n.issues)if(!s(u,"r"))e.issues.push(u);let a=[...r].filter(([,u])=>u.l&&u.r).map(([u])=>u);if(a.length){let u=i?a.filter((d)=>i.keys.includes(d)):[];if(u.length)e.issues.push({...i,keys:u});for(let d of a)if(!u.includes(d)&&o.has(d))e.issues.push(o.get(d))}let l=tn(t.value,n.value);if(!l.valid){if(le(e))return e;throw Error(`Unmergable intersection. Error path: ${JSON.stringify(l.mergeErrorPath)}`)}return e.value=l.data,e}var Ti=m("$ZodTuple",(e,t)=>{N.init(e,t);let n=t.items,r=re.memoizer;r?.attach(e),e._zod.parse=(i,o)=>{let s=i.value;if(!Array.isArray(s))return i.issues.push({input:s,inst:e,expected:"tuple",code:"invalid_type"}),i;i.value=r?r.alloc(e,i,[],o):[];let a=[],l=cr(n,"optin"),u=cr(n,"optout");if(!t.rest){if(s.length<l)return i.issues.push({code:"too_small",minimum:l,inclusive:!0,input:s,inst:e,origin:"array"}),i;if(s.length>n.length)i.issues.push({code:"too_big",maximum:n.length,inclusive:!0,input:s,inst:e,origin:"array"})}let d=Array(n.length),h=t.rest?o?.abortEarly:void 0,p=!1;for(let f=0;f<n.length;f++){let g=n[f]._zod.run({value:s[f],issues:[]},o);if(g instanceof Promise)a.push(g.then((T)=>{d[f]=T}));else if(d[f]=g,h&&!p&&g.issues.length)p=le(g)}if(t.rest&&!p){let f=n.length-1,g=s.slice(n.length),T=i.issues.length;for(let k of g){if(h&&i.issues.length!==T){if(le(i,T))break;T=i.issues.length}f++;let _=t.rest._zod.run({value:k,issues:[]},o);if(_ instanceof Promise)a.push(_.then((B)=>dr(B,i,f)));else dr(_,i,f)}}if(a.length)return Promise.all(a).then(()=>pr(d,i,n,s,u));return pr(d,i,n,s,u)}});function cr(e,t){for(let n=e.length-1;n>=0;n--)if(!(t==="optin"?e[n]._zod.optin!==void 0:e[n]._zod.optout==="optional"))return n+1;return 0}function dr(e,t,n){if(e.issues.length)t.issues.push(...ge(n,e.issues));t.value[n]=e.value}function pr(e,t,n,r,i){for(let o=0;o<n.length;o++){let s=e[o],a=o<r.length;if(!a&&o>=i&&n[o]._zod.optin==="optional"){t.value.length=o;break}if(s.issues.length){if(!a&&o>=i){t.value.length=o;break}t.issues.push(...ge(o,s.issues))}t.value[o]=s.value}for(let o=t.value.length-1;o>=r.length;o--)if(n[o]._zod.optout==="optional"&&t.value[o]===void 0)t.value.length=o;else break;return t}var Ql=m("$ZodRecord",(e,t)=>{N.init(e,t);let n=re.memoizer;n?.attach(e),e._zod.parse=(r,i)=>{let o=r.value;if(!Me(o))return r.issues.push({expected:"record",code:"invalid_type",input:o,inst:e}),r;let s=[],a=t.keyType._zod.values;if(a&&!t.partial){r.value=n?n.alloc(e,r,{},i):{};let l=new Set;for(let d of a)if(typeof d==="string"||typeof d==="number"||typeof d==="symbol"){if(l.add(typeof d==="number"?d.toString():d),d==="__proto__")continue;let h=t.keyType._zod.run({value:d,issues:[]},i);if(h instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(h.issues.length){r.issues.push({code:"invalid_key",origin:"record",issues:h.issues.map((g)=>ve(g,i,ue())),input:d,path:[d],inst:e});continue}let p=h.value;if(p==="__proto__")continue;let f=t.valueType._zod.run({value:o[d],issues:[]},i);if(f instanceof Promise)s.push(f.then((g)=>{if(g.issues.length)r.issues.push(...ge(d,g.issues));r.value[p]=g.value}));else{if(f.issues.length)r.issues.push(...ge(d,f.issues));r.value[p]=f.value}}let u;for(let d in o)if(!l.has(d))if(t.mode==="loose"){if(d==="__proto__")continue;r.value[d]=o[d]}else u=u??[],u.push(d);if(u&&u.length>0)r.issues.push({code:"unrecognized_keys",input:o,inst:e,keys:u,continue:!0})}else{r.value=n?n.alloc(e,r,{},i):{};let l;for(let u of Reflect.ownKeys(o)){if(u==="__proto__")continue;if(!Object.prototype.propertyIsEnumerable.call(o,u))continue;let d=t.keyType._zod.run({value:u,issues:[]},i);if(d instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(typeof u==="string"&&bn.test(u)&&d.issues.length){let f=t.keyType._zod.run({value:Number(u),issues:[]},i);if(f instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(f.issues.length===0)d=f}if(d.issues.length){if(t.mode==="loose")r.value[u]=o[u];else if(a)l=l??[],l.push(u);else r.issues.push({code:"invalid_key",origin:"record",issues:d.issues.map((f)=>ve(f,i,ue())),input:u,path:[u],inst:e});continue}let h=d.value;if(h==="__proto__")continue;let p=t.valueType._zod.run({value:o[u],issues:[]},i);if(p instanceof Promise)s.push(p.then((f)=>{if(f.issues.length)r.issues.push(...ge(u,f.issues));r.value[h]=f.value}));else{if(p.issues.length)r.issues.push(...ge(u,p.issues));r.value[h]=p.value}}if(l&&l.length>0)r.issues.push({code:"unrecognized_keys",input:o,inst:e,keys:l,continue:!0})}if(s.length)return Promise.all(s).then(()=>r);return r}}),eu=m("$ZodEnum",(e,t)=>{N.init(e,t);let n=Yt(t.entries),r=new Set(n);e._zod.values=r,O(e,"pattern",(i)=>{let o=Yt(i.def.entries).filter((s)=>Os.has(typeof s));return new RegExp(o.length?`^(${o.map((s)=>Pe(s.toString())).join("|")})$`:"^[^\\s\\S]$")}),e._zod.parse=(i,o)=>{let s=i.value;if(r.has(s))return i;return i.issues.push({code:"invalid_value",values:n,input:s,inst:e}),i}}),tu=m("$ZodLiteral",(e,t)=>{N.init(e,t);let n=new Set(t.values);e._zod.values=n,O(e,"pattern",(r)=>{let i=r.def.values;return new RegExp(i.length?`^(${i.map((o)=>typeof o==="string"?Pe(o):o?Pe(o.toString()):String(o)).join("|")})$`:"^[^\\s\\S]$")}),e._zod.parse=(r,i)=>{let o=r.value;if(n.has(o))return r;return r.issues.push({code:"invalid_value",values:t.values,input:o,inst:e}),r}}),nu=m("$ZodTransform",(e,t)=>{N.init(e,t),e._zod.optin="optional",re.memoizer?.guard(e),e._zod.parse=(n,r)=>{if(r.direction==="backward")throw new gn(e.constructor.name);let i=t.transform(n.value,n);if(r.async)return(i instanceof Promise?i:Promise.resolve(i)).then((o)=>(n.value=o,n));if(i instanceof Promise)throw new ye;return n.value=i,n}});function fr(e,t){return e.value=t.issues.length?void 0:t.value,e}var wi=m("$ZodOptional",(e,t)=>{N.init(e,t),O(e,"optin",(n)=>n.def.innerType._zod.optin==="defaulted"?"defaulted":"optional"),e._zod.optout="optional",O(e,"values",(n)=>{let r=n.def.innerType._zod.values;return r?new Set([...r,void 0]):void 0}),O(e,"pattern",(n)=>{let r=n.def.innerType._zod.pattern;return r?new RegExp(`^(${dn(r.source)})?$`):void 0}),e._zod.parse=(n,r)=>{if(n.value===void 0){if(t.innerType._zod.optin!=="defaulted")return n;let i=t.innerType._zod.run({value:n.value,issues:[]},r);if(i instanceof Promise)return i.then((o)=>fr(n,o));return fr(n,i)}return t.innerType._zod.run(n,r)}}),ru=m("$ZodExactOptional",(e,t)=>{wi.init(e,t),O(e,"values",(n)=>n.def.innerType._zod.values),O(e,"pattern",(n)=>n.def.innerType._zod.pattern),e._zod.parse=(n,r)=>t.innerType._zod.run(n,r)}),iu=m("$ZodNullable",(e,t)=>{N.init(e,t),O(e,"optin",(n)=>n.def.innerType._zod.optin),O(e,"optout",(n)=>n.def.innerType._zod.optout),O(e,"pattern",(n)=>{let r=n.def.innerType._zod.pattern;return r?new RegExp(`^(${dn(r.source)}|null)$`):void 0}),O(e,"values",(n)=>n.def.innerType._zod.values?new Set([...n.def.innerType._zod.values,null]):void 0),e._zod.parse=(n,r)=>{if(n.value===null)return n;return t.innerType._zod.run(n,r)}}),ou=m("$ZodDefault",(e,t)=>{N.init(e,t),e._zod.optin="defaulted",O(e,"values",(n)=>n.def.innerType._zod.values),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);if(n.value===void 0)return n.value=t.defaultValue,n;let i=t.innerType._zod.run(n,r);if(i instanceof Promise)return i.then((o)=>hr(o,t));return hr(i,t)}});function hr(e,t){if(e.value===void 0)e.value=t.defaultValue;return e}var su=m("$ZodPrefault",(e,t)=>{N.init(e,t),e._zod.optin="defaulted",O(e,"values",(n)=>n.def.innerType._zod.values),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);if(n.value===void 0)n.value=t.defaultValue;return t.innerType._zod.run(n,r)}}),au=m("$ZodNonOptional",(e,t)=>{N.init(e,t),O(e,"values",(n)=>{let r=n.def.innerType._zod.values;return r?new Set([...r].filter((i)=>i!==void 0)):void 0}),e._zod.parse=(n,r)=>{let i=t.innerType._zod.run(n,r);if(i instanceof Promise)return i.then((o)=>mr(o,e));return mr(i,e)}});function mr(e,t){if(!e.issues.length&&e.value===void 0)e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t});return e}function gr(e,t,n,r){if(!t.issues.length){if(e.value=t.value,t.memo)e.memo=!0;return e}return e.value=n.catchValue({...t,value:e.value,error:{issues:t.issues.map((i)=>ve(i,r,ue()))},input:e.value}),e}var lu=m("$ZodCatch",(e,t)=>{N.init(e,t),O(e,"optin",(n)=>n.def.innerType._zod.optin==="defaulted"?"defaulted":"optional"),O(e,"optout",(n)=>n.def.innerType._zod.optout),O(e,"values",(n)=>n.def.innerType._zod.values),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);let i=t.innerType._zod.run({value:n.value,issues:[]},r);if(i instanceof Promise)return i.then((o)=>gr(n,o,t,r));return gr(n,i,t,r)}}),_i=m("$ZodPipe",(e,t)=>{N.init(e,t),O(e,"values",(n)=>n.def.in._zod.values),O(e,"optin",(n)=>n.def.in._zod.optin),O(e,"optout",(n)=>n.def.out._zod.optout),O(e,"propValues",(n)=>n.def.in._zod.propValues),e._zod.parse=(n,r)=>{if(r.direction==="backward"){let o=t.out._zod.run(n,r);if(o instanceof Promise)return o.then((s)=>ut(s,t.in,r));return ut(o,t.in,r)}let i=t.in._zod.run(n,r);if(i instanceof Promise)return i.then((o)=>ut(o,t.out,r));return ut(i,t.out,r)}});function ut(e,t,n){if(e.issues.some((r)=>r.code!=="unrecognized_keys"))return e.aborted=!0,e;return t._zod.run({value:e.value,issues:e.issues},n)}var uu=m("$ZodPreprocess",(e,t)=>{_i.init(e,t)}),cu=m("$ZodReadonly",(e,t)=>{N.init(e,t),O(e,"propValues",(n)=>n.def.innerType._zod.propValues),O(e,"values",(n)=>n.def.innerType._zod.values),O(e,"optin",(n)=>n.def.innerType?._zod?.optin),O(e,"optout",(n)=>n.def.innerType?._zod?.optout),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);let i=t.innerType._zod.run(n,r);if(i instanceof Promise)return i.then(yr);return yr(i)}});function yr(e){if(!e.memo)e.value=Object.freeze(e.value);return e}var du=m("$ZodFunction",(e,t)=>(N.init(e,t),Object.defineProperty(e,"_def",{value:t}),e._zod.def=t,e.implement=(n)=>{if(typeof n!=="function")throw Error("implement() must be called with a function");return Object.defineProperty(function(...r){let i=e._def.input?rr(e._def.input,r):r,o=Reflect.apply(n,this,i);if(e._def.output)return rr(e._def.output,o);return o},"_zod",{value:e._zod,enumerable:!1})},e.implementAsync=(n)=>{if(typeof n!=="function")throw Error("implementAsync() must be called with a function");return Object.defineProperty(async function(...r){let i=e._def.input?await ir(e._def.input,r):r,o=await Reflect.apply(n,this,i);if(e._def.output)return await ir(e._def.output,o);return o},"_zod",{value:e._zod,enumerable:!1})},e._zod.parse=(n,r)=>{if(typeof n.value!=="function")return n.issues.push({code:"invalid_type",expected:"function",input:n.value,inst:e}),n;if(e._def.output&&e._def.output._zod.def.type==="promise")n.value=e.implementAsync(n.value);else n.value=e.implement(n.value);return n},e.input=(...n)=>{let r=e.constructor;if(Array.isArray(n[0]))return new r({type:"function",input:new Ti({type:"tuple",items:n[0],rest:n[1]}),output:e._def.output});return new r({type:"function",input:n[0],output:e._def.output})},e.output=(n)=>new e.constructor({type:"function",input:e._def.input,output:n}),e)),pu=m("$ZodPromise",(e,t)=>{N.init(e,t),e._zod.parse=(n,r)=>Promise.resolve(n.value).then((i)=>t.innerType._zod.run({value:i,issues:[]},r))}),fu=m("$ZodCustom",(e,t)=>{Q.init(e,t),N.init(e,t),e._zod.parse=(n,r)=>n,e._zod.check=(n)=>{let r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then((o)=>vr(o,n,r,e));vr(i,n,r,e);return}});function vr(e,t,n,r){if(!e){let i={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};if(r._zod.def.params)i.params=r._zod.def.params;t.issues.push(Xe(i))}}class ki extends Error{constructor(){super("Cannot parse a reference cycle that closes through a transform");this.name="ZodCyclicError"}}var nn="~memo",br=[];function Ei(e){return e!==null&&typeof e==="object"}function Zt(e){return e.map((t)=>t.path?{...t,path:t.path.slice()}:{...t})}var Ai=new WeakMap,He=0,mt=1,Ge=2;function gt(e,t,n){let r=Ai.get(e);if(r!==void 0)return r?Ge:He;if(t.has(e))return Ge;t.add(e);let i=He,o=(d)=>{if(i!==Ge&&d?._zod){let h=gt(d,t,n);if(h>i)i=h}},s=(d,h)=>{let p=He;for(let f of Reflect.ownKeys(d)){let g=Object.getOwnPropertyDescriptor(d,f);if(h&&!g.enumerable)continue;let T=g.get?mt:g.value?._zod?gt(g.value,t,n):He;if(T>p)p=T}return p},a=(d)=>{if(d>i)i=d},l=e._zod.def;switch(l.type){case"object":{let d=pn(l);a(d?s(d,!0):mt),o(l.catchall);break}case"array":o(l.element);break;case"tuple":for(let d of l.items)o(d);o(l.rest);break;case"record":case"map":o(l.keyType),o(l.valueType);break;case"set":o(l.valueType);break;case"union":for(let d of l.options)o(d);break;case"intersection":o(l.left),o(l.right);break;case"optional":case"nullable":case"default":case"prefault":case"catch":case"readonly":case"nonoptional":case"promise":case"success":o(l.innerType);break;case"pipe":o(l.in),o(l.out);break;case"function":o(l.input),o(l.output);break;case"lazy":{let d=l._cachedInner??(n?e._zod.innerType:void 0);a(d?gt(d,t,!1):mt);break}case"template_literal":case"string":case"number":case"int":case"boolean":case"bigint":case"symbol":case"undefined":case"null":case"void":case"never":case"any":case"unknown":case"date":case"nan":case"enum":case"literal":case"file":case"transform":case"custom":break;default:for(let d in l){let h=Object.getOwnPropertyDescriptor(l,d);if(!h||h.get)continue;let p=h.value;if(!p||typeof p!=="object")continue;if(p._zod)o(p);else if(Array.isArray(p))for(let f of p)o(f)}}return t.delete(e),hu(e,i)}function hu(e,t){if(t!==mt)Ai.set(e,t===Ge);return t}function mu(e,t){let n=e.buckets.get(t);if(!n)n=new WeakMap,e.buckets.set(t,n);return n}var ct,dt=[],gu={alloc(e,t,n){let r=ct;if(!r)return n;ct=void 0;let i={value:n,issues:null};return r.set(t.value,i),dt.push(i),n},guard(e){var t;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{let n=e._zod.parse,r=(i,o)=>{if(o.direction!=="backward"&&vu(o,i.value))throw new ki;return n(i,o)};if(e._zod.parse=r,e._zod.run===n)e._zod.run=r})},attach(e){var t;let n,r=!1,i,o;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{let s=e._zod.parse,a=(l,u)=>{if(n===void 0){let _=gt(e,new Set,!1);if(_===He){if(e._zod.parse=s,e._zod.run===a)e._zod.run=s;return s(l,u)}if(_===Ge||r)n=!0;else r=!0}let d=l.value;if(!Ei(d))return s(l,u);let h=u[nn];if(!h)h={buckets:new WeakMap,backEdges:void 0},u[nn]=h;let p;if(i===u)p=o;else p=mu(h,e),i=u,o=p;let f=p.get(d);if(f){if(l.value=f.value,f.issues){if(f.issues.length)l.issues.push(...Zt(f.issues))}else l.memo=!0,h.backEdges??(h.backEdges=new WeakSet),h.backEdges.add(f.value);return l}ct=p;let g=dt.length,T=s(l,u);ct=void 0;let k=dt.length>g?dt.pop():void 0;if(T instanceof Promise)return T.then((_)=>{if(k)k.issues=_.issues.length?Zt(_.issues):br;return _});if(k)k.issues=T.issues.length?Zt(T.issues):br;return T};if(e._zod.parse=a,e._zod.run===s)e._zod.run=a})}};function yu(){return gu}function vu(e,t){let n=e[nn]?.backEdges;return n!==void 0&&Ei(t)&&n.has(t)}var bu=()=>{let e={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"},map:{unit:"entries",verb:"to have"}};function t(o){return e[o]??null}let n={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",currency_code:"currency code",credit_card:"credit card number",iban:"IBAN",jwt:"JWT",template_literal:"input"},r={nan:"NaN"};function i(o,s){if(o==="number"&&typeof s==="number"&&!Number.isFinite(s))return String(s);return r[o]??o}return(o)=>{switch(o.code){case"invalid_type":{let s=i(o.expected),a=Bs(o.input),l=i(a,o.input);return`Invalid input: expected ${s}, received ${l}`}case"invalid_value":if(o.values.length===1)return`Invalid input: expected ${Xr(o.values[0])}`;return`Invalid option: expected one of ${Yn(o.values,"|")}`;case"too_big":{let s=o.exact?"exactly ":o.inclusive?"<=":"<",a=t(o.origin);if(a)return`Too big: expected ${o.origin??"value"} to have ${s}${o.maximum.toString()} ${a.unit??"elements"}`;return`Too big: expected ${o.origin??"value"} to be ${s}${o.maximum.toString()}`}case"too_small":{let s=o.exact?"exactly ":o.inclusive?">=":">",a=t(o.origin);if(a)return`Too small: expected ${o.origin} to have ${s}${o.minimum.toString()} ${a.unit}`;return`Too small: expected ${o.origin} to be ${s}${o.minimum.toString()}`}case"invalid_format":{let s=o;if(s.format==="starts_with")return`Invalid string: must start with "${s.prefix}"`;if(s.format==="ends_with")return`Invalid string: must end with "${s.suffix}"`;if(s.format==="includes")return`Invalid string: must include "${s.includes}"`;if(s.format==="regex")return`Invalid string: must match pattern ${s.pattern}`;return`Invalid ${n[s.format]??o.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${o.divisor}`;case"unrecognized_keys":return`Unrecognized key${o.keys.length>1?"s":""}: ${Yn(o.keys,", ")}`;case"invalid_key":return`Invalid key in ${o.origin}`;case"invalid_union":if(o.options&&Array.isArray(o.options)&&o.options.length>0)return`Invalid discriminator value. Expected ${o.options.map((s)=>`'${s}'`).join(" | ")}`;if(o.inclusive===!1)return"Invalid input: more than one option matched";return"Invalid input";case"invalid_element":return`Invalid value in ${o.origin}`;default:return"Invalid input"}}};function Tu(){return{localeError:bu()}}var Tr;class xi{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){let n=t[0];if(this._map.set(e,n),n&&typeof n==="object"&&"id"in n)this._idmap.set(n.id,e);return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let t=this._map.get(e);if(t&&typeof t==="object"&&"id"in t)this._idmap.delete(t.id);return 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 wu(){return new xi}(Tr=globalThis).__zod_globalRegistry??(Tr.__zod_globalRegistry=wu());var We=globalThis.__zod_globalRegistry;function Ii(e){if(e.checks)e.checks=[...e.checks];return e}function _u(e,t){return new e(Ii({type:"string",...w(t)}))}function ku(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...w(t)})}function Eu(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...w(t)})}function Au(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...w(t)})}function xu(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...w(t)})}function Iu(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...w(t)})}function Cu(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...w(t)})}function Su(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...w(t)})}function Ru(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...w(t)})}function Ou(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...w(t)})}function Nu(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...w(t)})}function Mu(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...w(t)})}function Pu(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...w(t)})}function $u(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...w(t)})}function Lu(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...w(t)})}function zu(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...w(t)})}function Du(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...w(t)})}function Uu(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...w(t)})}function Fu(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...w(t)})}function ju(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...w(t)})}function Bu(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...w(t)})}function qu(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...w(t)})}function Hu(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...w(t)})}function Wu(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...w(t)})}function Zu(e,t){return new e({type:"string",format:"date",check:"string_format",...w(t)})}function Vu(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...w(t)})}function Gu(e,t){return new e({type:"string",format:"duration",check:"string_format",...w(t)})}function Ku(e,t){return new e(Ii({type:"number",checks:[],...w(t)}))}function Ju(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...w(t)})}function Yu(e,t){return new e({type:"boolean",...w(t)})}function Xu(e){return new e({type:"unknown"})}function Qu(e,t){return new e({type:"never",...w(t)})}function ec(e,t){return new e({type:"void",...w(t)})}function tc(e,t){return new e({type:"date",...w(t)})}function wr(e,t){return new si({check:"less_than",...w(t),value:e,inclusive:!1})}function yt(e,t){return new si({check:"less_than",...w(t),value:e,inclusive:!0})}function _r(e,t){return new ai({check:"greater_than",...w(t),value:e,inclusive:!1})}function vt(e,t){return new ai({check:"greater_than",...w(t),value:e,inclusive:!0})}function kr(e,t){return new Za({check:"multiple_of",...w(t),value:e})}function Ci(e,t){return new Ga({check:"max_length",...w(t),maximum:e})}function _t(e,t){return new Ka({check:"min_length",...w(t),minimum:e})}function Si(e,t){return new Ja({check:"length_equals",...w(t),length:e})}function nc(e,t){return new Ya({check:"string_format",format:"regex",...w(t),pattern:e})}function rc(e){return new Xa({check:"string_format",format:"lowercase",...w(e)})}function ic(e){return new Qa({check:"string_format",format:"uppercase",...w(e)})}function oc(e,t){return new el({check:"string_format",format:"includes",...w(t),includes:e})}function sc(e,t){return new tl({check:"string_format",format:"starts_with",...w(t),prefix:e})}function ac(e,t){return new nl({check:"string_format",format:"ends_with",...w(t),suffix:e})}function De(e){return new rl({check:"overwrite",tx:e})}function lc(e){return De((t)=>t.normalize(e))}function uc(){return De((e)=>e.trim())}function cc(){return De((e)=>e.toLowerCase())}function dc(){return De((e)=>e.toUpperCase())}function pc(){return De((e)=>Ss(e))}function fc(e,t,n){return new e({type:"array",element:t,...w(n)})}function hc(e,t,n){let r=w(n);return r.abort??(r.abort=!0),new e({type:"custom",check:"custom",fn:t,...r})}function mc(e,t,n){return new e({type:"custom",check:"custom",fn:t,...w(n)})}function gc(e,t){let n=yc((r)=>(r.addIssue=(i)=>{if(typeof i==="string")r.issues.push(Xe(i,r.value,n._zod.def));else{let o=i;if(o.fatal)o.continue=!1;if(o.code??(o.code="custom"),!("input"in o))o.input=r.value;o.inst??(o.inst=n),o.continue??(o.continue=!n._zod.def.abort),r.issues.push(Xe(o))}},e(r.value,r)),t);return n}function yc(e,t){let n=new Q({check:"custom",...w(t)});return n._zod.check=e,n}function Ke(e,...t){for(let n of t)for(let r of Reflect.ownKeys(n))if(Object.prototype.propertyIsEnumerable.call(n,r))ce(e,r,n[r]);return e}function kt(e){let t=e?.target??"draft-2020-12";if(t==="draft-4")t="draft-04";if(t==="draft-7")t="draft-07";return{processors:e.processors??{},metadataRegistry:e?.metadata??We,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,sharedDefsExtractedFor:void 0,sharedEmitDoneFor:void 0,cycles:e?.cycles??"ref",reused:e?.reused??"inline",intersections:[],deferred:[],external:e?.external??void 0}}function Z(e,t,n,r,i){let o=typeof t.unrepresentable==="function"?t.unrepresentable({zodSchema:e,path:r.path,message:i}):t.unrepresentable;if(o==="any")return!1;if(o===void 0||o==="throw")throw Error(i);return Object.assign(n,o),!0}function L(e,t,n={path:[],schemaPath:[]}){var r;let i=e._zod.def,o=t.seen.get(e);if(o){if(o.count++,n.schemaPath.includes(e))o.cycle=n.path;return o.schema}let s={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,s),t.sharedDefsExtractedFor=void 0,t.sharedEmitDoneFor=void 0;let a=e._zod.toJSONSchema?.();if(a)s.schema=a;else{let u={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,s.schema,u);else{let h=s.schema,p=t.processors[i.type];if(!p)throw Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);p(e,t,h,u)}let d=e._zod.parent;if(d){if(!s.ref)s.ref=d;L(d,t,u),t.seen.get(d).isParent=!0}}let l=t.metadataRegistry.get(e);if(l)Ke(s.schema,l);if(t.io==="input"&&Y(e))delete s.schema.examples,delete s.schema.default;if(t.io==="input"&&"_prefault"in s.schema)(r=s.schema).default??(r.default=s.schema._prefault);return delete s.schema._prefault,t.seen.get(e).schema}function Er(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}function Et(e,t){let n=e.seen.get(t);if(!n)throw Error("Unprocessed schema. This is a bug in Zod.");if(e.external&&e.sharedDefsExtractedFor===e.external)return;let r=new Map;for(let s of e.seen.entries()){let a=e.metadataRegistry.get(s[0])?.id;if(a){let l=r.get(a);if(l&&l!==s[0])throw Error(`Duplicate schema id "${a}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(a,s[0])}}let i=(s)=>{let a=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){let h=e.external.registry.get(s[0])?.id,p=e.external.uri??((g)=>g);if(h)return{ref:p(h)};let f=s[1].defId??s[1].schema.id??`schema${e.counter++}`;return s[1].defId=f,{defId:f,ref:`${p("__shared")}#/${a}/${Er(f)}`}}let l="#",u=`${l}/${a}/`;if(s[1]===n&&!s[1].schema.id)return{ref:l};let d=s[1].schema.id??`__schema${e.counter++}`;return{defId:d,ref:u+Er(d)}},o=(s)=>{if(s[1].schema.$ref)return;let a=s[1],{ref:l,defId:u}=i(s);if(a.def={...a.schema},u)a.defId=u;let d=a.schema;for(let h in d)delete d[h];d.$ref=l};if(e.cycles==="throw")for(let s of e.seen.entries()){let a=s[1];if(a.cycle)throw Error(`Cycle detected: #/${a.cycle?.join("/")}/<root>
63
56
 
64
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let s of e.seen.entries()){let a=s[1];if(t===s[0]){o(s);continue}if(e.external){let u=e.external.registry.get(s[0])?.id;if(t!==s[0]&&u){o(s);continue}}if(e.metadataRegistry.get(s[0])?.id){o(s);continue}if(a.cycle){o(s);continue}if(a.count>1){if(e.reused==="ref"){o(s);continue}}}}function rt(e,t){let n=e.seen.get(t);if(!n)throw Error("Unprocessed schema. This is a bug in Zod.");let i=(a)=>{let u=e.seen.get(a);if(u.ref===null)return;let c=u.def??u.schema,d={...c},y=u.ref;if(u.ref=null,y){i(y);let v=e.seen.get(y),b=v.schema;if(b.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"))c.allOf=c.allOf??[],c.allOf.push(b);else Object.assign(c,b);if(Object.assign(c,d),a._zod.parent===y)for(let w in c){if(w==="$ref"||w==="allOf")continue;if(!(w in d))delete c[w]}if(b.$ref&&v.def)for(let w in c){if(w==="$ref"||w==="allOf")continue;if(w in v.def&&JSON.stringify(c[w])===JSON.stringify(v.def[w]))delete c[w]}}let p=a._zod.parent;if(p&&p!==y){i(p);let v=e.seen.get(p);if(v?.schema.$ref){if(c.$ref=v.schema.$ref,v.def)for(let b in c){if(b==="$ref"||b==="allOf")continue;if(b in v.def&&JSON.stringify(c[b])===JSON.stringify(v.def[b]))delete c[b]}}}e.override({zodSchema:a,jsonSchema:c,path:u.path??[]})};for(let a of[...e.seen.entries()].reverse())i(a[0]);let r={};if(e.target==="draft-2020-12")r.$schema="https://json-schema.org/draft/2020-12/schema";else if(e.target==="draft-07")r.$schema="http://json-schema.org/draft-07/schema#";else if(e.target==="draft-04")r.$schema="http://json-schema.org/draft-04/schema#";else if(e.target==="openapi-3.0");if(e.external?.uri){let a=e.external.registry.get(t)?.id;if(!a)throw Error("Schema is missing an `id` property");r.$id=e.external.uri(a)}Object.assign(r,n.def??n.schema);let o=e.metadataRegistry.get(t)?.id;if(o!==void 0&&r.id===o)delete r.id;let s=e.external?.defs??{};for(let a of e.seen.entries()){let u=a[1];if(u.def&&u.defId){if(u.def.id===u.defId)delete u.def.id;s[u.defId]=u.def}}if(e.external);else if(Object.keys(s).length>0)if(e.target==="draft-2020-12")r.$defs=s;else r.definitions=s;try{let a=JSON.parse(JSON.stringify(r));return Object.defineProperty(a,"~standard",{value:{...t["~standard"],jsonSchema:{input:ot(t,"input",e.processors),output:ot(t,"output",e.processors)}},enumerable:!1,writable:!1}),a}catch(a){throw Error("Error converting schema to JSON.")}}function Z(e,t){let n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);let i=e._zod.def;if(i.type==="transform")return!0;if(i.type==="array")return Z(i.element,n);if(i.type==="set")return Z(i.valueType,n);if(i.type==="lazy")return Z(i.getter(),n);if(i.type==="promise"||i.type==="optional"||i.type==="nonoptional"||i.type==="nullable"||i.type==="readonly"||i.type==="default"||i.type==="prefault")return Z(i.innerType,n);if(i.type==="intersection")return Z(i.left,n)||Z(i.right,n);if(i.type==="record"||i.type==="map")return Z(i.keyType,n)||Z(i.valueType,n);if(i.type==="pipe"){if(e._zod.traits.has("$ZodCodec"))return!0;return Z(i.in,n)||Z(i.out,n)}if(i.type==="object"){for(let r in i.shape)if(Z(i.shape[r],n))return!0;return!1}if(i.type==="union"){for(let r of i.options)if(Z(r,n))return!0;return!1}if(i.type==="tuple"){for(let r of i.items)if(Z(r,n))return!0;if(i.rest&&Z(i.rest,n))return!0;return!1}return!1}var vl=(e,t={})=>(n)=>{let i=nt({...n,processors:t});return O(e,i),it(i,e),rt(i,e)},ot=(e,t,n={})=>(i)=>{let{libraryOptions:r,target:o}=i??{},s=nt({...r??{},target:o,io:t,processors:n});return O(e,s),it(s,e),rt(s,e)},bl={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},Ei=(e,t,n,i)=>{let r=n;r.type="string";let{minimum:o,maximum:s,format:a,patterns:u,contentEncoding:c}=e._zod.bag;if(typeof o==="number")r.minLength=o;if(typeof s==="number")r.maxLength=s;if(a){if(r.format=bl[a]??a,r.format==="")delete r.format;if(a==="time")delete r.format}if(c)r.contentEncoding=c;if(u&&u.size>0){let d=[...u];if(d.length===1)r.pattern=d[0].source;else if(d.length>1)r.allOf=[...d.map((y)=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:y.source}))]}},Ii=(e,t,n,i)=>{let r=n,{minimum:o,maximum:s,format:a,multipleOf:u,exclusiveMaximum:c,exclusiveMinimum:d}=e._zod.bag;if(typeof a==="string"&&a.includes("int"))r.type="integer";else r.type="number";let y=typeof d==="number"&&d>=(o??Number.NEGATIVE_INFINITY),p=typeof c==="number"&&c<=(s??Number.POSITIVE_INFINITY),v=t.target==="draft-04"||t.target==="openapi-3.0";if(y)if(v)r.minimum=d,r.exclusiveMinimum=!0;else r.exclusiveMinimum=d;else if(typeof o==="number")r.minimum=o;if(p)if(v)r.maximum=c,r.exclusiveMaximum=!0;else r.exclusiveMaximum=c;else if(typeof s==="number")r.maximum=s;if(typeof u==="number")r.multipleOf=u},Ai=(e,t,n,i)=>{n.type="boolean"},Tl=(e,t,n,i)=>{if(t.unrepresentable==="throw")throw Error("BigInt cannot be represented in JSON Schema")},wl=(e,t,n,i)=>{if(t.unrepresentable==="throw")throw Error("Symbols cannot be represented in JSON Schema")},_l=(e,t,n,i)=>{if(t.target==="openapi-3.0")n.type="string",n.nullable=!0,n.enum=[null];else n.type="null"},kl=(e,t,n,i)=>{if(t.unrepresentable==="throw")throw Error("Undefined cannot be represented in JSON Schema")},xi=(e,t,n,i)=>{if(t.unrepresentable==="throw")throw Error("Void cannot be represented in JSON Schema")},Ci=(e,t,n,i)=>{n.not={}},El=(e,t,n,i)=>{},Ri=(e,t,n,i)=>{},Si=(e,t,n,i)=>{if(t.unrepresentable==="throw")throw Error("Date cannot be represented in JSON Schema")},Ni=(e,t,n,i)=>{let r=e._zod.def,o=Qn(r.entries);if(o.every((s)=>typeof s==="number"))n.type="number";if(o.every((s)=>typeof s==="string"))n.type="string";n.enum=o},Oi=(e,t,n,i)=>{let r=e._zod.def,o=[];for(let s of r.values)if(s===void 0){if(t.unrepresentable==="throw")throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof s==="bigint")if(t.unrepresentable==="throw")throw Error("BigInt literals cannot be represented in JSON Schema");else o.push(Number(s));else o.push(s);if(o.length===0);else if(o.length===1){let s=o[0];if(n.type=s===null?"null":typeof s,t.target==="draft-04"||t.target==="openapi-3.0")n.enum=[s];else n.const=s}else{if(o.every((s)=>typeof s==="number"))n.type="number";if(o.every((s)=>typeof s==="string"))n.type="string";if(o.every((s)=>typeof s==="boolean"))n.type="boolean";if(o.every((s)=>s===null))n.type="null";n.enum=o}},Il=(e,t,n,i)=>{if(t.unrepresentable==="throw")throw Error("NaN cannot be represented in JSON Schema")},Al=(e,t,n,i)=>{let r=n,o=e._zod.pattern;if(!o)throw Error("Pattern not found in template literal");r.type="string",r.pattern=o.source},xl=(e,t,n,i)=>{let r=n,o={type:"string",format:"binary",contentEncoding:"binary"},{minimum:s,maximum:a,mime:u}=e._zod.bag;if(s!==void 0)o.minLength=s;if(a!==void 0)o.maxLength=a;if(u)if(u.length===1)o.contentMediaType=u[0],Object.assign(r,o);else Object.assign(r,o),r.anyOf=u.map((c)=>({contentMediaType:c}));else Object.assign(r,o)},Cl=(e,t,n,i)=>{n.type="boolean"},Mi=(e,t,n,i)=>{if(t.unrepresentable==="throw")throw Error("Custom types cannot be represented in JSON Schema")},Pi=(e,t,n,i)=>{if(t.unrepresentable==="throw")throw Error("Function types cannot be represented in JSON Schema")},$i=(e,t,n,i)=>{if(t.unrepresentable==="throw")throw Error("Transforms cannot be represented in JSON Schema")},Rl=(e,t,n,i)=>{if(t.unrepresentable==="throw")throw Error("Map cannot be represented in JSON Schema")},Sl=(e,t,n,i)=>{if(t.unrepresentable==="throw")throw Error("Set cannot be represented in JSON Schema")},Li=(e,t,n,i)=>{let r=n,o=e._zod.def,{minimum:s,maximum:a}=e._zod.bag;if(typeof s==="number")r.minItems=s;if(typeof a==="number")r.maxItems=a;r.type="array",r.items=O(o.element,t,{...i,path:[...i.path,"items"]})},zi=(e,t,n,i)=>{let r=n,o=e._zod.def;r.type="object",r.properties={};let s=o.shape;for(let c in s)r.properties[c]=O(s[c],t,{...i,path:[...i.path,"properties",c]});let a=new Set(Object.keys(s)),u=new Set([...a].filter((c)=>{let d=o.shape[c]._zod;if(t.io==="input")return d.optin===void 0;else return d.optout===void 0}));if(u.size>0)r.required=Array.from(u);if(o.catchall?._zod.def.type==="never")r.additionalProperties=!1;else if(!o.catchall){if(t.io==="output")r.additionalProperties=!1}else if(o.catchall)r.additionalProperties=O(o.catchall,t,{...i,path:[...i.path,"additionalProperties"]})},Di=(e,t,n,i)=>{let r=e._zod.def,o=r.inclusive===!1,s=r.options.map((a,u)=>O(a,t,{...i,path:[...i.path,o?"oneOf":"anyOf",u]}));if(o)n.oneOf=s;else n.anyOf=s},Ui=(e,t,n,i)=>{let r=e._zod.def,o=O(r.left,t,{...i,path:[...i.path,"allOf",0]}),s=O(r.right,t,{...i,path:[...i.path,"allOf",1]}),a=(c)=>("allOf"in c)&&Object.keys(c).length===1,u=[...a(o)?o.allOf:[o],...a(s)?s.allOf:[s]];n.allOf=u},Fi=(e,t,n,i)=>{let r=n,o=e._zod.def;r.type="array";let s=t.target==="draft-2020-12"?"prefixItems":"items",a=t.target==="draft-2020-12"?"items":t.target==="openapi-3.0"?"items":"additionalItems",u=o.items.map((p,v)=>O(p,t,{...i,path:[...i.path,s,v]})),c=o.rest?O(o.rest,t,{...i,path:[...i.path,a,...t.target==="openapi-3.0"?[o.items.length]:[]]}):null;if(t.target==="draft-2020-12"){if(r.prefixItems=u,c)r.items=c}else if(t.target==="openapi-3.0"){if(r.items={anyOf:u},c)r.items.anyOf.push(c);if(r.minItems=u.length,!c)r.maxItems=u.length}else if(r.items=u,c)r.additionalItems=c;let{minimum:d,maximum:y}=e._zod.bag;if(typeof d==="number")r.minItems=d;if(typeof y==="number")r.maxItems=y},Bi=(e,t,n,i)=>{let r=n,o=e._zod.def;r.type="object";let s=o.keyType,a=s._zod.bag?.patterns;if(o.mode==="loose"&&a&&a.size>0){let c=O(o.valueType,t,{...i,path:[...i.path,"patternProperties","*"]});r.patternProperties={};for(let d of a)r.patternProperties[d.source]=c}else{if(t.target==="draft-07"||t.target==="draft-2020-12")r.propertyNames=O(o.keyType,t,{...i,path:[...i.path,"propertyNames"]});r.additionalProperties=O(o.valueType,t,{...i,path:[...i.path,"additionalProperties"]})}let u=s._zod.values;if(u){let c=[...u].filter((d)=>typeof d==="string"||typeof d==="number");if(c.length>0)r.required=c}},ji=(e,t,n,i)=>{let r=e._zod.def,o=O(r.innerType,t,i),s=t.seen.get(e);if(t.target==="openapi-3.0")s.ref=r.innerType,n.nullable=!0;else n.anyOf=[o,{type:"null"}]},qi=(e,t,n,i)=>{let r=e._zod.def;O(r.innerType,t,i);let o=t.seen.get(e);o.ref=r.innerType},Hi=(e,t,n,i)=>{let r=e._zod.def;O(r.innerType,t,i);let o=t.seen.get(e);o.ref=r.innerType,n.default=JSON.parse(JSON.stringify(r.defaultValue))},Wi=(e,t,n,i)=>{let r=e._zod.def;O(r.innerType,t,i);let o=t.seen.get(e);if(o.ref=r.innerType,t.io==="input")n._prefault=JSON.parse(JSON.stringify(r.defaultValue))},Vi=(e,t,n,i)=>{let r=e._zod.def;O(r.innerType,t,i);let o=t.seen.get(e);o.ref=r.innerType;let s;try{s=r.catchValue(void 0)}catch{throw Error("Dynamic catch values are not supported in JSON Schema")}n.default=s},Zi=(e,t,n,i)=>{let r=e._zod.def,o=r.in._zod.traits.has("$ZodTransform"),s=t.io==="input"?o?r.out:r.in:r.out;O(s,t,i);let a=t.seen.get(e);a.ref=s},Gi=(e,t,n,i)=>{let r=e._zod.def;O(r.innerType,t,i);let o=t.seen.get(e);o.ref=r.innerType,n.readOnly=!0},Ki=(e,t,n,i)=>{let r=e._zod.def;O(r.innerType,t,i);let o=t.seen.get(e);o.ref=r.innerType},Dt=(e,t,n,i)=>{let r=e._zod.def;O(r.innerType,t,i);let o=t.seen.get(e);o.ref=r.innerType},Nl=(e,t,n,i)=>{let r=e._zod.innerType;O(r,t,i);let o=t.seen.get(e);o.ref=r},Ln={string:Ei,number:Ii,boolean:Ai,bigint:Tl,symbol:wl,null:_l,undefined:kl,void:xi,never:Ci,any:El,unknown:Ri,date:Si,enum:Ni,literal:Oi,nan:Il,template_literal:Al,file:xl,success:Cl,custom:Mi,function:Pi,transform:$i,map:Rl,set:Sl,array:Li,object:zi,union:Di,intersection:Ui,tuple:Fi,record:Bi,nullable:ji,nonoptional:qi,default:Hi,prefault:Wi,catch:Vi,pipe:Zi,readonly:Gi,promise:Ki,optional:Dt,lazy:Nl};function Ol(e,t){if("_idmap"in e){let i=e,r=nt({...t,processors:Ln}),o={};for(let u of i._idmap.entries()){let[c,d]=u;O(d,r)}let s={},a={registry:i,uri:t?.uri,defs:o};r.external=a;for(let u of i._idmap.entries()){let[c,d]=u;it(r,d),s[c]=rt(r,d)}if(Object.keys(o).length>0){let u=r.target==="draft-2020-12"?"$defs":"definitions";s.__shared={[u]:o}}return{schemas:s}}let n=nt({...t,processors:Ln});return O(e,n),it(n,e),rt(n,e)}var Ml=h("ZodISODateTime",(e,t)=>{Ps.init(e,t),L.init(e,t)});function Pl(e){return Wa(Ml,e)}var $l=h("ZodISODate",(e,t)=>{$s.init(e,t),L.init(e,t)});function Ll(e){return Va($l,e)}var zl=h("ZodISOTime",(e,t)=>{Ls.init(e,t),L.init(e,t)});function Dl(e){return Za(zl,e)}var Ul=h("ZodISODuration",(e,t)=>{zs.init(e,t),L.init(e,t)});function Fl(e){return Ga(Ul,e)}var Bl=(e,t)=>{ri.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:(n)=>xo(e,n)},flatten:{value:(n)=>Ao(e,n)},addIssue:{value:(n)=>{e.issues.push(n),e.message=JSON.stringify(e.issues,xt,2)}},addIssues:{value:(n)=>{e.issues.push(...n),e.message=JSON.stringify(e.issues,xt,2)}},isEmpty:{get(){return e.issues.length===0}}})},Q=h("ZodError",Bl,{Parent:Error}),jl=ut(Q),ql=ct(Q),Hl=dt(Q),Wl=pt(Q),Vl=So(Q),Zl=No(Q),Gl=Oo(Q),Kl=Mo(Q),Jl=Po(Q),Yl=$o(Q),Xl=Lo(Q),Ql=zo(Q),zn=new WeakMap;function Fe(e,t,n){let i=Object.getPrototypeOf(e),r=zn.get(i);if(!r)r=new Set,zn.set(i,r);if(r.has(t))return;r.add(t);for(let o in n){let s=n[o];Object.defineProperty(i,o,{configurable:!0,enumerable:!1,get(){let a=s.bind(this);return Object.defineProperty(this,o,{configurable:!0,writable:!0,enumerable:!0,value:a}),a},set(a){Object.defineProperty(this,o,{configurable:!0,writable:!0,enumerable:!0,value:a})}})}}var N=h("ZodType",(e,t)=>(S.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:ot(e,"input"),output:ot(e,"output")}}),e.toJSONSchema=vl(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(n,i)=>jl(e,n,i,{callee:e.parse}),e.safeParse=(n,i)=>Hl(e,n,i),e.parseAsync=async(n,i)=>ql(e,n,i,{callee:e.parseAsync}),e.safeParseAsync=async(n,i)=>Wl(e,n,i),e.spa=e.safeParseAsync,e.encode=(n,i)=>Vl(e,n,i),e.decode=(n,i)=>Zl(e,n,i),e.encodeAsync=async(n,i)=>Gl(e,n,i),e.decodeAsync=async(n,i)=>Kl(e,n,i),e.safeEncode=(n,i)=>Jl(e,n,i),e.safeDecode=(n,i)=>Yl(e,n,i),e.safeEncodeAsync=async(n,i)=>Xl(e,n,i),e.safeDecodeAsync=async(n,i)=>Ql(e,n,i),Fe(e,"ZodType",{check(...n){let i=this.def;return this.clone(ue(i,{checks:[...i.checks??[],...n.map((r)=>typeof r==="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),{parent:!0})},with(...n){return this.check(...n)},clone(n,i){return ce(this,n,i)},brand(){return this},register(n,i){return n.add(this,i),this},refine(n,i){return this.check(Ju(n,i))},superRefine(n,i){return this.check(Yu(n,i))},overwrite(n){return this.check(Re(n))},optional(){return Bn(this)},exactOptional(){return Lu(this)},nullable(){return jn(this)},nullish(){return Bn(jn(this))},nonoptional(n){return ju(this,n)},array(){return k(this)},or(n){return ee([this,n])},and(n){return Su(this,n)},transform(n){return qn(this,Qi(n))},default(n){return Uu(this,n)},prefault(n){return Bu(this,n)},catch(n){return Hu(this,n)},pipe(n){return qn(this,n)},readonly(){return Zu(this)},describe(n){let i=this.clone();return Pe.add(i,{description:n}),i},meta(...n){if(n.length===0)return Pe.get(this);let i=this.clone();return Pe.add(i,n[0]),i},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(n){return n(this)}}),Object.defineProperty(e,"description",{get(){return Pe.get(e)?.description},configurable:!0}),e)),Ji=h("_ZodString",(e,t)=>{zt.init(e,t),N.init(e,t),e._zod.processJSONSchema=(i,r,o)=>Ei(e,i,r,o);let n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,Fe(e,"_ZodString",{regex(...i){return this.check(nl(...i))},includes(...i){return this.check(ol(...i))},startsWith(...i){return this.check(sl(...i))},endsWith(...i){return this.check(al(...i))},min(...i){return this.check(tt(...i))},max(...i){return this.check(_i(...i))},length(...i){return this.check(ki(...i))},nonempty(...i){return this.check(tt(1,...i))},lowercase(i){return this.check(il(i))},uppercase(i){return this.check(rl(i))},trim(){return this.check(ul())},normalize(...i){return this.check(ll(...i))},toLowerCase(){return this.check(cl())},toUpperCase(){return this.check(dl())},slugify(){return this.check(pl())}})}),eu=h("ZodString",(e,t)=>{zt.init(e,t),Ji.init(e,t),e.email=(n)=>e.check(Ea(tu,n)),e.url=(n)=>e.check(Ra(nu,n)),e.jwt=(n)=>e.check(Ha(yu,n)),e.emoji=(n)=>e.check(Sa(iu,n)),e.guid=(n)=>e.check(On(Dn,n)),e.uuid=(n)=>e.check(Ia(Ke,n)),e.uuidv4=(n)=>e.check(Aa(Ke,n)),e.uuidv6=(n)=>e.check(xa(Ke,n)),e.uuidv7=(n)=>e.check(Ca(Ke,n)),e.nanoid=(n)=>e.check(Na(ru,n)),e.guid=(n)=>e.check(On(Dn,n)),e.cuid=(n)=>e.check(Oa(ou,n)),e.cuid2=(n)=>e.check(Ma(su,n)),e.ulid=(n)=>e.check(Pa(au,n)),e.base64=(n)=>e.check(Ba(fu,n)),e.base64url=(n)=>e.check(ja(mu,n)),e.xid=(n)=>e.check($a(lu,n)),e.ksuid=(n)=>e.check(La(uu,n)),e.ipv4=(n)=>e.check(za(cu,n)),e.ipv6=(n)=>e.check(Da(du,n)),e.cidrv4=(n)=>e.check(Ua(pu,n)),e.cidrv6=(n)=>e.check(Fa(hu,n)),e.e164=(n)=>e.check(qa(gu,n)),e.datetime=(n)=>e.check(Pl(n)),e.date=(n)=>e.check(Ll(n)),e.time=(n)=>e.check(Dl(n)),e.duration=(n)=>e.check(Fl(n))});function l(e){return ka(eu,e)}var L=h("ZodStringFormat",(e,t)=>{M.init(e,t),Ji.init(e,t)}),tu=h("ZodEmail",(e,t)=>{Is.init(e,t),L.init(e,t)}),Dn=h("ZodGUID",(e,t)=>{ks.init(e,t),L.init(e,t)}),Ke=h("ZodUUID",(e,t)=>{Es.init(e,t),L.init(e,t)}),nu=h("ZodURL",(e,t)=>{As.init(e,t),L.init(e,t)}),iu=h("ZodEmoji",(e,t)=>{xs.init(e,t),L.init(e,t)}),ru=h("ZodNanoID",(e,t)=>{Cs.init(e,t),L.init(e,t)}),ou=h("ZodCUID",(e,t)=>{Rs.init(e,t),L.init(e,t)}),su=h("ZodCUID2",(e,t)=>{Ss.init(e,t),L.init(e,t)}),au=h("ZodULID",(e,t)=>{Ns.init(e,t),L.init(e,t)}),lu=h("ZodXID",(e,t)=>{Os.init(e,t),L.init(e,t)}),uu=h("ZodKSUID",(e,t)=>{Ms.init(e,t),L.init(e,t)}),cu=h("ZodIPv4",(e,t)=>{Ds.init(e,t),L.init(e,t)}),du=h("ZodIPv6",(e,t)=>{Us.init(e,t),L.init(e,t)}),pu=h("ZodCIDRv4",(e,t)=>{Fs.init(e,t),L.init(e,t)}),hu=h("ZodCIDRv6",(e,t)=>{Bs.init(e,t),L.init(e,t)}),fu=h("ZodBase64",(e,t)=>{js.init(e,t),L.init(e,t)}),mu=h("ZodBase64URL",(e,t)=>{Hs.init(e,t),L.init(e,t)}),gu=h("ZodE164",(e,t)=>{Ws.init(e,t),L.init(e,t)}),yu=h("ZodJWT",(e,t)=>{Zs.init(e,t),L.init(e,t)}),Yi=h("ZodNumber",(e,t)=>{fi.init(e,t),N.init(e,t),e._zod.processJSONSchema=(i,r,o)=>Ii(e,i,r,o),Fe(e,"ZodNumber",{gt(i,r){return this.check(Pn(i,r))},gte(i,r){return this.check(Xe(i,r))},min(i,r){return this.check(Xe(i,r))},lt(i,r){return this.check(Mn(i,r))},lte(i,r){return this.check(Ye(i,r))},max(i,r){return this.check(Ye(i,r))},int(i){return this.check(Un(i))},safe(i){return this.check(Un(i))},positive(i){return this.check(Pn(0,i))},nonnegative(i){return this.check(Xe(0,i))},negative(i){return this.check(Mn(0,i))},nonpositive(i){return this.check(Ye(0,i))},multipleOf(i,r){return this.check($n(i,r))},step(i,r){return this.check($n(i,r))},finite(){return this}});let n=e._zod.bag;e.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??0.5),e.isFinite=!0,e.format=n.format??null});function g(e){return Ka(Yi,e)}var vu=h("ZodNumberFormat",(e,t)=>{Gs.init(e,t),Yi.init(e,t)});function Un(e){return Ja(vu,e)}var bu=h("ZodBoolean",(e,t)=>{Ks.init(e,t),N.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Ai(e,n,i,r)});function I(e){return Ya(bu,e)}var Tu=h("ZodUnknown",(e,t)=>{Js.init(e,t),N.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Ri(e,n,i,r)});function q(){return Xa(Tu)}var wu=h("ZodNever",(e,t)=>{Ys.init(e,t),N.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Ci(e,n,i,r)});function _u(e){return Qa(wu,e)}var ku=h("ZodVoid",(e,t)=>{Xs.init(e,t),N.init(e,t),e._zod.processJSONSchema=(n,i,r)=>xi(e,n,i,r)});function Eu(e){return el(ku,e)}var Iu=h("ZodDate",(e,t)=>{Qs.init(e,t),N.init(e,t),e._zod.processJSONSchema=(i,r,o)=>Si(e,i,r,o),e.min=(i,r)=>e.check(Xe(i,r)),e.max=(i,r)=>e.check(Ye(i,r));let n=e._zod.bag;e.minDate=n.minimum?new Date(n.minimum):null,e.maxDate=n.maximum?new Date(n.maximum):null});function st(e){return tl(Iu,e)}var Au=h("ZodArray",(e,t)=>{ea.init(e,t),N.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Li(e,n,i,r),e.element=t.element,Fe(e,"ZodArray",{min(n,i){return this.check(tt(n,i))},nonempty(n){return this.check(tt(1,n))},max(n,i){return this.check(_i(n,i))},length(n,i){return this.check(ki(n,i))},unwrap(){return this.element}})});function k(e,t){return hl(Au,e,t)}var xu=h("ZodObject",(e,t)=>{na.init(e,t),N.init(e,t),e._zod.processJSONSchema=(n,i,r)=>zi(e,n,i,r),R(e,"shape",()=>t.shape),Fe(e,"ZodObject",{keyof(){return E(Object.keys(this._zod.def.shape))},catchall(n){return this.clone({...this._zod.def,catchall:n})},passthrough(){return this.clone({...this._zod.def,catchall:q()})},loose(){return this.clone({...this._zod.def,catchall:q()})},strict(){return this.clone({...this._zod.def,catchall:_u()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(n){return bo(this,n)},safeExtend(n){return To(this,n)},merge(n){return wo(this,n)},pick(n){return yo(this,n)},omit(n){return vo(this,n)},partial(...n){return _o(er,this,n[0])},required(...n){return ko(tr,this,n[0])}})});function f(e,t){let n={type:"object",shape:e??{},...T(t)};return new xu(n)}var Xi=h("ZodUnion",(e,t)=>{yi.init(e,t),N.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Di(e,n,i,r),e.options=t.options});function ee(e,t){return new Xi({type:"union",options:e,...T(t)})}var Cu=h("ZodDiscriminatedUnion",(e,t)=>{Xi.init(e,t),ia.init(e,t)});function Ut(e,t,n){return new Cu({type:"union",options:t,discriminator:e,...T(n)})}var Ru=h("ZodIntersection",(e,t)=>{ra.init(e,t),N.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Ui(e,n,i,r)});function Su(e,t){return new Ru({type:"intersection",left:e,right:t})}var Nu=h("ZodTuple",(e,t)=>{vi.init(e,t),N.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Fi(e,n,i,r),e.rest=(n)=>e.clone({...e._zod.def,rest:n})});function Ou(e,t,n){let i=t instanceof S;return new Nu({type:"tuple",items:e,rest:i?t:null,...T(i?n:t)})}var Fn=h("ZodRecord",(e,t)=>{oa.init(e,t),N.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Bi(e,n,i,r),e.keyType=t.keyType,e.valueType=t.valueType});function U(e,t,n){if(!t||!t._zod)return new Fn({type:"record",keyType:l(),valueType:e,...T(t)});return new Fn({type:"record",keyType:e,valueType:t,...T(n)})}var Rt=h("ZodEnum",(e,t)=>{sa.init(e,t),N.init(e,t),e._zod.processJSONSchema=(i,r,o)=>Ni(e,i,r,o),e.enum=t.entries,e.options=Object.values(t.entries);let n=new Set(Object.keys(t.entries));e.extract=(i,r)=>{let o={};for(let s of i)if(n.has(s))o[s]=t.entries[s];else throw Error(`Key ${s} not found in enum`);return new Rt({...t,checks:[],...T(r),entries:o})},e.exclude=(i,r)=>{let o={...t.entries};for(let s of i)if(n.has(s))delete o[s];else throw Error(`Key ${s} not found in enum`);return new Rt({...t,checks:[],...T(r),entries:o})}});function E(e,t){let n=Array.isArray(e)?Object.fromEntries(e.map((i)=>[i,i])):e;return new Rt({type:"enum",entries:n,...T(t)})}var Mu=h("ZodLiteral",(e,t)=>{aa.init(e,t),N.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Oi(e,n,i,r),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function z(e,t){return new Mu({type:"literal",values:Array.isArray(e)?e:[e],...T(t)})}var Pu=h("ZodTransform",(e,t)=>{la.init(e,t),N.init(e,t),e._zod.processJSONSchema=(n,i,r)=>$i(e,n,i,r),e._zod.parse=(n,i)=>{if(i.direction==="backward")throw new Mt(e.constructor.name);n.addIssue=(o)=>{if(typeof o==="string")n.issues.push(Ue(o,n.value,t));else{let s=o;if(s.fatal)s.continue=!1;s.code??(s.code="custom"),s.input??(s.input=n.value),s.inst??(s.inst=e),n.issues.push(Ue(s))}};let r=t.transform(n.value,n);if(r instanceof Promise)return r.then((o)=>(n.value=o,n.fallback=!0,n));return n.value=r,n.fallback=!0,n}});function Qi(e){return new Pu({type:"transform",transform:e})}var er=h("ZodOptional",(e,t)=>{bi.init(e,t),N.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Dt(e,n,i,r),e.unwrap=()=>e._zod.def.innerType});function Bn(e){return new er({type:"optional",innerType:e})}var $u=h("ZodExactOptional",(e,t)=>{ua.init(e,t),N.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Dt(e,n,i,r),e.unwrap=()=>e._zod.def.innerType});function Lu(e){return new $u({type:"optional",innerType:e})}var zu=h("ZodNullable",(e,t)=>{ca.init(e,t),N.init(e,t),e._zod.processJSONSchema=(n,i,r)=>ji(e,n,i,r),e.unwrap=()=>e._zod.def.innerType});function jn(e){return new zu({type:"nullable",innerType:e})}var Du=h("ZodDefault",(e,t)=>{da.init(e,t),N.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Hi(e,n,i,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Uu(e,t){return new Du({type:"default",innerType:e,get defaultValue(){return typeof t==="function"?t():ti(t)}})}var Fu=h("ZodPrefault",(e,t)=>{pa.init(e,t),N.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Wi(e,n,i,r),e.unwrap=()=>e._zod.def.innerType});function Bu(e,t){return new Fu({type:"prefault",innerType:e,get defaultValue(){return typeof t==="function"?t():ti(t)}})}var tr=h("ZodNonOptional",(e,t)=>{ha.init(e,t),N.init(e,t),e._zod.processJSONSchema=(n,i,r)=>qi(e,n,i,r),e.unwrap=()=>e._zod.def.innerType});function ju(e,t){return new tr({type:"nonoptional",innerType:e,...T(t)})}var qu=h("ZodCatch",(e,t)=>{fa.init(e,t),N.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Vi(e,n,i,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Hu(e,t){return new qu({type:"catch",innerType:e,catchValue:typeof t==="function"?t:()=>t})}var nr=h("ZodPipe",(e,t)=>{Ti.init(e,t),N.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Zi(e,n,i,r),e.in=t.in,e.out=t.out});function qn(e,t){return new nr({type:"pipe",in:e,out:t})}var Wu=h("ZodPreprocess",(e,t)=>{nr.init(e,t),ma.init(e,t)}),Vu=h("ZodReadonly",(e,t)=>{ga.init(e,t),N.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Gi(e,n,i,r),e.unwrap=()=>e._zod.def.innerType});function Zu(e){return new Vu({type:"readonly",innerType:e})}var Gu=h("ZodPromise",(e,t)=>{va.init(e,t),N.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Ki(e,n,i,r),e.unwrap=()=>e._zod.def.innerType});function kt(e){return new Gu({type:"promise",innerType:e})}var Ku=h("ZodFunction",(e,t)=>{ya.init(e,t),N.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Pi(e,n,i,r)});function Je(e){return new Ku({type:"function",input:Array.isArray(e?.input)?Ou(e?.input):e?.input??k(q()),output:e?.output??q()})}var ir=h("ZodCustom",(e,t)=>{ba.init(e,t),N.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Mi(e,n,i,r)});function X(e,t){return fl(ir,e??(()=>!0),t)}function Ju(e,t={}){return ml(ir,e,t)}function Yu(e,t){return gl(e,t)}function rr(e,t){return new Wu({type:"pipe",in:Qi(e),out:t})}ne(wa());var or=["none","minimal","low","medium","high","xhigh","max"],Xu=E(or),Qu=Xu.exclude(["none"]),ec=E([...or,"default"]).nullable(),tc=Ut("type",[f({type:z("toggle")}).strict(),f({type:z("effort"),values:k(ec)}).strict(),f({type:z("budget_tokens"),min:g().min(-1).optional(),max:g().min(0).optional()}).strict().refine((e)=>e.min===void 0||e.max===void 0||e.min<=e.max,{message:"Minimum reasoning budget cannot exceed maximum",path:["min"]})]),nc=E(["default","openai-responses","r1"]);var ic=E(["images","video","tools","streaming","prompt-cache","reasoning","reasoning-effort","computer-use","global-endpoint","structured_output","temperature","files"]),rc=E(["active","preview","deprecated","legacy"]),oc=f({input:g().optional(),output:g().optional(),cacheWrite:g().optional(),cacheRead:g().optional()}),sc=f({maxBudget:g().optional(),outputPrice:g().optional(),thinkingLevel:E(["low","high"]).optional()}),ac=f({reasoningDefaultOn:I().optional(),apiProtocol:E(["openai-chat","openai-responses","anthropic","gemini"]).optional()}).catchall(q()),Hn=E(["text","image","audio","video","pdf"]),lc=f({input:k(Hn),output:k(Hn)});var uc=E(["language","image-generation","speech-generation","video-generation","transcription","realtime"]);var cc=E(["batch","streaming"]);var sr=f({id:l(),name:l().optional(),description:l().optional(),maxTokens:g().optional(),contextWindow:g().optional(),maxInputTokens:g().optional(),capabilities:k(ic).optional(),operation:uc.optional(),operationModes:k(cc).optional(),modalities:lc.optional(),reasoningOptions:k(tc).optional(),apiFormat:nc.optional(),systemRole:E(["system","developer"]).optional(),temperature:g().optional(),pricing:oc.optional(),thinkingConfig:sc.optional(),status:rc.optional(),deprecationNotice:l().optional(),replacedBy:l().optional(),releaseDate:l().optional(),deprecationDate:l().optional(),family:l().optional(),metadata:ac.optional()});var ar="NOT a tool or system failure. Clarify with user before proceeding.",dc=f({id:l(),name:l(),execution:E(["client","provider"]).optional(),input:q(),output:q(),error:l().optional(),durationMs:g(),startedAt:st(),endedAt:st()}),pc=E(["completed","max_iterations","aborted","mistake_limit","error"]),hc=f({inputTokens:g(),outputTokens:g(),cacheReadTokens:g().optional(),cacheWriteTokens:g().optional(),totalCost:g().optional()}),Gp=f({text:l(),usage:hc,messages:k(X()),toolCalls:k(dc),iterations:g(),finishReason:pc,model:f({id:l(),provider:l(),info:sr.optional()}),startedAt:st(),endedAt:st(),durationMs:g()}),Kp=f({distinctId:l().optional(),sessionId:l().optional(),providerId:l(),modelId:l(),apiKey:l().optional(),baseUrl:l().url().optional(),headers:U(l(),l()).optional(),knownModels:U(l(),sr).optional(),providerConfig:q().optional(),initialMessages:k(X()).optional(),systemPrompt:l(),tools:k(X()),modelTools:k(X()).optional(),maxIterations:g().positive().optional(),maxParallelToolCalls:g().int().positive().default(8),maxTokensPerTurn:g().positive().optional(),maxToolResultChars:g().int().positive().optional(),temperature:g().nonnegative().optional(),apiTimeoutMs:g().positive().default(180000),userFileContentLoader:Je().input([l()]).output(kt(l())).optional(),toolContextMetadata:U(l(),q()).optional(),execution:f({maxConsecutiveMistakes:g().int().positive().optional(),reminderAfterIterations:g().nonnegative().optional(),reminderText:l().optional(),loopDetection:ee([z(!1),f({softThreshold:g().int().positive().optional(),hardThreshold:g().int().positive().optional()})]).optional(),reasoningLoopDetection:ee([z(!1),f({minChars:g().int().positive().optional(),window:g().int().positive().optional(),lineCycleWindow:g().int().positive().optional(),maxPeriod:g().int().positive().optional(),minCycles:g().int().positive().optional(),maxUniqueInWindow:g().int().positive().optional(),minLineChars:g().int().positive().optional(),phraseMaxPeriod:g().int().positive().optional(),phraseMinCycles:g().int().positive().optional(),blockMinPeriod:g().int().positive().optional(),blockMaxPeriod:g().int().nonnegative().optional(),blockMinCycles:g().int().positive().optional(),blockMinChars:g().int().nonnegative().optional(),maxConsecutiveTrips:g().int().positive().optional()})]).optional(),reasoningRepetition:ee([z(!1),f({minChars:g().int().positive().optional(),minParagraphChars:g().int().positive().optional(),minStopwords:g().int().nonnegative().optional(),maxRepeatTrip:g().int().positive().optional(),duplicateFractionTrip:g().min(0).max(1).optional(),cooldownTurns:g().int().nonnegative().optional(),maxNudges:g().int().nonnegative().optional(),recoveryTokens:g().int().nonnegative().optional()})]).optional()}).optional(),reasoningEffort:Qu.optional(),thinkingBudgetTokens:g().positive().optional(),thinking:I().optional(),onEvent:Je().input([X()]).output(Eu()).optional(),hooks:X().optional(),parentAgentId:l().optional(),extensions:k(X()).optional(),hookErrorMode:E(["ignore","throw"]).default("ignore"),toolPolicies:U(l(),f({enabled:I().optional(),autoApprove:I().optional()})).optional(),unavailableToolReasons:U(l(),l()).optional(),requestToolApproval:Je().input([f({sessionId:l(),agentId:l(),conversationId:l(),iteration:g(),toolCallId:l(),toolName:l(),input:q(),policy:f({enabled:I().optional(),autoApprove:I().optional()}).default({})})]).output(ee([f({approved:I(),reason:l().optional()}),kt(f({approved:I(),reason:l().optional()}))])).optional(),onConsecutiveMistakeLimitReached:Je().input([f({iteration:g().int().positive(),consecutiveMistakes:g().int().positive(),maxConsecutiveMistakes:g().int().positive(),reason:E(["api_error","invalid_tool_call","tool_execution_failed"]),details:l().optional()})]).output(ee([f({action:z("continue"),guidance:l().optional()}),f({action:z("stop"),reason:l().optional()}),kt(ee([f({action:z("continue"),guidance:l().optional()}),f({action:z("stop"),reason:l().optional()})]))])).optional(),logger:X().optional(),extensionContext:X().optional(),abortSignal:X().optional()}),fc=E(["connector.started","connector.stopping","session.authorize","message.received","message.denied","message.completed","message.failed","session.started","session.reused","session.reset","schedule.delivery.started","schedule.delivery.sent","schedule.delivery.failed"]),mc=f({id:l().optional(),label:l().optional(),role:l().optional(),participantKey:l().optional(),participantLabel:l().optional(),platformUserId:l().optional(),metadata:U(l(),q()).optional()}),gc=f({source:l(),sourceEvent:l(),threadId:l(),channelId:l(),isDM:I(),sessionId:l().optional(),workspaceRoot:l().optional(),metadata:U(l(),q()).optional()}),Jp=f({actor:mc,context:gc,payload:U(l(),q()).optional()}),Yp=f({action:E(["allow","deny"]).default("allow"),message:l().optional(),reason:l().optional(),metadata:U(l(),q()).optional()}),Xp=f({adapter:l(),botUserName:l().optional(),event:fc,payload:U(l(),q()),ts:l()});var yc=["hooks","tools","commands","rules","skills","messageBuilders","providers","automationEvents","mcp"],Qp=new Set(yc);var $e={CLINE_PASS:"ext-cline-pass",CODE_CLOUD_AGENTS:"code-cloud-agents",CODE_ONBOARDING_GITHUB:"code-onboarding-github",CLINE_COMPOSIO_BETA:"CLINE_COMPOSIO_BETA"},eh={[$e.CLINE_PASS]:!1,[$e.CODE_CLOUD_AGENTS]:!1,[$e.CODE_ONBOARDING_GITHUB]:!1,[$e.CLINE_COMPOSIO_BETA]:!1},th=Object.values($e),vc=E(["agent_start","agent_resume","agent_abort","agent_end","agent_error","tool_call","tool_result","prompt_submit","pre_compact","session_shutdown"]),he=U(l(),l()),bc=f({toolName:l(),parameters:he}),Tc=f({toolName:l(),parameters:he,result:l(),success:I(),executionTimeMs:g()}),wc=f({prompt:l(),attachments:k(l())}),_c=f({taskMetadata:he}),kc=f({taskMetadata:he,previousState:he}),Ec=f({taskMetadata:he}),Ic=f({taskMetadata:he}),Ac=f({taskId:l(),ulid:l(),contextSize:g(),compactionStrategy:l(),previousApiReqIndex:g(),tokensIn:g(),tokensOut:g(),tokensInCache:g(),tokensOutCache:g(),deletedRangeStart:g(),deletedRangeEnd:g(),contextJsonPath:l(),contextRawPath:l()}),nh=f({clineVersion:l(),hookName:vc,timestamp:l(),taskId:l(),sessionContext:f({rootSessionId:l().optional(),hookLogPath:l().optional()}).optional(),workspaceRoots:k(l()),workspaceInfo:X().optional(),userId:l(),agent_id:l(),parent_agent_id:l().nullable(),iteration:g().optional(),reason:l().optional(),tool_call:f({id:l(),name:l(),input:q()}).optional(),tool_result:X().optional(),turn:q().optional(),error:f({name:l(),message:l(),stack:l().optional()}).optional(),preToolUse:bc.optional(),postToolUse:Tc.optional(),userPromptSubmit:wc.optional(),taskStart:_c.optional(),taskResume:kc.optional(),taskCancel:Ec.optional(),taskComplete:Ic.optional(),preCompact:Ac.optional()}).passthrough();var xc=["readFile","search","bash","webFetch","editor","applyPatch","skills","askQuestion","submit"],ih=new Set(xc);var Wn="<tool_call>",Cc=/<tool_call>|<parameter=[^>]*>|<\/parameter>/g,Rc=/<function=[^\s>]+\s*>/,Ft="[SYSTEM] Your last message contained no tool calls, so the run was about to end. If the task is not finished, continue now by emitting the tool calls it needs - do not describe what you are going to do without doing it. If the task really is finished, say so in one short sentence. If it stopped at a limit, a refusal or anything else only the user can change, and you have told the user so, that is finished too: say so in one short sentence and do not look for a way around it.",lr=" If what you need is a decision from the user, call `ask_question` - that is the only way to reach them. A question written as ordinary text is not a question anyone will see: it reads here as a turn that called nothing, which is what produced this message.",Sc="[SYSTEM] You have now taken ";function ur(e,t){let n=Math.round(t/1000),i=n>=1?`about ${n.toLocaleString("en-US")},000 characters of reasoning`:"a full turn of reasoning";return Sc+`${e} turns in a row without calling a single tool, spending ${i} on them. Thinking further has not moved this task, and it will not: you have already reasoned past the point where more of it helps. Stop analysing and make one tool call now - the smallest one that makes any progress at all, even if you are not certain it is the right one, because a call you can check beats an analysis you cannot. If you genuinely cannot make one, say what is blocking you in a single sentence and stop.`}var Nc="[SYSTEM] Your last message contained a tool call that could not be read.",Oc="<|tool_call>",Vn="<tool_call|>",we='<|"|>',Mc=/<\|tool_call>\s*call:([A-Za-z_][\w.-]*)\s*\{/g;function cr(e){return`(A call to ${e.name?`\`${e.name}\``:"a tool"} was written here but could not be read, so nothing ran. Its text is not kept.)`}function Et(e){return JSON.stringify(e.replace(/\s+/g," ").trim())}function Pc(e){let t=[];for(let r=e.indexOf(we);r!==-1;r=e.indexOf(we,r+we.length))t.push(r);let n=(r)=>/([A-Za-z_]\w*)\s*:\s*$/.exec(e.slice(Math.max(0,r-80),r))?.[1],i=()=>{let r=/([A-Za-z_]\w*)\s*:\s*(?!<\|"\|>)([^,{}[\]<]{1,60})<\|"\|>/.exec(e);return r?`The value of \`${r[1]}\` (${Et(r[2])}) closes a string it never opened.`:void 0};for(let r=0;r+1<t.length;r+=2){let o=t[r],s=t[r+1],a=n(o),u=e.slice(o+we.length,s),c=/([^\s,]{0,12})\s*,\s*([A-Za-z_]\w*)\s*:\s*$/.exec(u);if(c&&a){let p=c[1],v=p?`you wrote ${Et(p.slice(-8))} where its closing delimiter belongs`:"its closing delimiter is missing";return`The string for \`${a}\` was never closed: ${v}, just before \`${c[2]}\`. A string argument ends with the same delimiter that opened it and with nothing else - not a backtick, not a quote, not a tag.`}let d=e.slice(s+we.length),y=/^\s*(\S)/.exec(d)?.[1];if(y&&!",}]".includes(y)){let p=/^\s*([A-Za-z_]\w*)\s*:/.exec(d)?.[1];if(!p){let v=i();if(v)return v}return p&&a?`There is no comma between \`${a}\` and \`${p}\`. Every argument is separated from the next by a comma.`:`After the string for \`${a??"an argument"}\` closes, the call continues with ${Et(d.slice(0,24))} where a comma or the end of the call belongs.`}}if(t.length%2===1)return`The string for \`${n(t[t.length-1])??"the last argument"}\` was opened and never closed.`;return i()}function $c(e){let t=[...e.matchAll(Mc)];if(t.length===0)return;let n=t[t.length-1]?.[1],i=0;for(let u=1;u<t.length;u+=1){let c=e.slice(t[u-1].index??0,t[u].index??0);if((c.split(we).length-1)%2===1||!c.includes(Vn))i+=1}let r=t[t.length-1],o=(r.index??0)+r[0].length,s=e.indexOf(Vn,o),a=i>0?void 0:Pc(e.slice(o,s===-1?void 0:s));return{blocks:t.length,restarts:i,dialect:"gemma",...n?{name:n}:{},...a?{defect:a}:{}}}function Se(e){if(!e)return;if(e.includes(Oc)){let u=$c(e);if(u)return u}if(!e.includes(Wn)||!Rc.test(e))return;let t=0,n=0,i=0;for(let u of e.matchAll(Cc)){let c=u[0];if(c===Wn)t+=1;else if(c==="</parameter>")i+=1;else n+=1}if(t===0)return;let r=Math.max(n-i,0),o=Math.min(Math.max(t-1,0),r),s=[...e.matchAll(/<function=([^\s>]+)\s*>/g)],a=s[s.length-1]?.[1];return{blocks:t,restarts:o,dialect:"qwen",...a?{name:a}:{}}}function Bt(e){let t=e.name?`\`${e.name}\``:"a tool",n=e.dialect==="gemma",i=n?"string argument":"parameter",r=e.restarts>0?` You began ${t} and then, part-way through a ${i} you never closed, started the whole call again${e.restarts>1?`, ${e.restarts} times over`:""}. The reader cannot tell an abandoned call from the value of the ${i} it was abandoned inside, so all of it came back as text.`:e.defect?` It named ${t}. ${e.defect}`:` It named ${t}, but the block was not well formed and could not be read.`,o=n?" Write the call again, once: every string argument opens and closes with the same string delimiter, arguments are separated by commas, and the call is closed after the last one.":" Emit the call once, in one clean block: open it, give each parameter and close each parameter, then close the function and the call.";return Nc+r+" Nothing ran, so nothing has changed on disk. The call is not in this conversation any more, so do not look for it or copy it: write it fresh."+o+" Do not restart a call once you have begun it - finish it, or send nothing and start the next turn fresh."}var Lc="[SYSTEM] You wrote ";function dr(e){let t=e.trim().replace(/\s+/g," ").slice(0,200);return Lc+`"${t}" and then called nothing. Saying what you are about to do is not doing it, and the run ends on the next silent turn with the work undone. Emit the tool call itself now - the first one, not a description of it. If you cannot, say plainly what is stopping you in one sentence.`}var pr=/\b(?:let me|i'?ll|i will|i'?m going to|i am going to|now i(?:'?ll| will)|next,? i(?:'?ll| will)|let['’]s)\b/i,hr=/\b(?:task (?:is )?(?:complete|finished|done)|all done|is now (?:complete|finished|fixed|working)|i(?:'?m| am) (?:done|finished)|nothing (?:else|more) to do|no further changes)\b/i;function ft(e){let t=e?.trim();if(!t||hr.test(t))return;let n=t.slice(-400);return pr.test(n)?t:void 0}var zc=300;function fr(e){let t=e?.trim();return!!t&&t.length<=zc&&!/\n\s*\n/.test(t)&&!t.endsWith("?")&&ft(t)===void 0}var Dc=/(?:^done\b|^i(?:'ve| have) (?:now |fully |successfully )?(?:completed|finished)\b|\b(?:is|are|was|were|has been|have been) (?:now |all |fully |successfully )?(?:complete|completed|finished|done)\b)/i;function mr(e){return e.slice(-300).includes("?")||pr.test(e.slice(-400))}function gr(e){let t=e?.trim();if(!t)return!1;let n=t.replace(/[*_`]/g,"");return(hr.test(n)||Dc.test(n))&&!mr(t)}function yr(e){let t=e?.trim();return!!t&&!mr(t)}var Uc=E(["image","audio","video","file"]),Fc=Ut("type",[f({type:z("base64"),data:l().min(1)}),f({type:z("url"),url:l().url().refine((e)=>{let t=new URL(e).protocol;return t==="http:"||t==="https:"},"Generated media URLs must use HTTP or HTTPS")}),f({type:z("artifact"),artifactId:l().min(1)})]);function Bc(e){if(e.startsWith("image/"))return"image";if(e.startsWith("audio/"))return"audio";if(e.startsWith("video/"))return"video";return"file"}var rh=f({id:l().min(1),modality:Uc,mediaType:l().min(1),source:Fc,name:l().min(1).optional(),sizeBytes:g().int().nonnegative().optional()}).refine((e)=>Bc(e.mediaType)===e.modality,{message:"Generated media modality must match its media type",path:["modality"]});function Zn(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function jt(e,t){if(!e&&!t)return;let n=e?.metadata,i=t?.metadata,r={...e??{},...t??{}};if(Zn(n)&&Zn(i))r.metadata={...n,...i};return r}var jc=3;var Gn=Symbol.for("cline.shared.tokenCalibration");function qc(e,t){if(e===void 0||t===void 0)return!0;return e===t}function vr(){let e=globalThis,t=e[Gn];if(t)return t;let n={};return e[Gn]=n,n}function Hc(){return vr().charsPerToken??jc}function qt(e){let t=vr();return qc(t.outputCapOwner,e)?t.outputCap:void 0}function br(e){return Math.max(1,Math.ceil(e/Hc()))}function ke(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function Wc(e){let t=e.type;if(typeof t==="string")return[t];return Array.isArray(t)?t.filter((n)=>typeof n==="string"):[]}function St(e,t){if(Wc(e).includes(t))return!0;for(let n of["anyOf","oneOf","allOf"]){let i=e[n];if(Array.isArray(i)&&i.some((r)=>ke(r)&&St(r,t)))return!0}return!1}function Vc(e,t){if(typeof e!=="string")return e;let n=e.trim(),i=St(t,"array"),r=St(t,"object");if((!i||!n.startsWith("["))&&(!r||!n.startsWith("{")))return e;try{let o=JSON.parse(n);if(Array.isArray(o))return i?o:e;if(ke(o))return r?o:e;return e}catch{return e}}function Ce(e,t){let n=Vc(e,t);if(Array.isArray(n)){let s=t.items;if(!ke(s))return n;let a=!1,u=n.map((c)=>{let d=Ce(c,s);return a||=d!==c,d});return a?u:n}if(!ke(n))return n;let i=t.properties;if(!ke(i))return n;let r=!1,o={...n};for(let[s,a]of Object.entries(i)){if(!(s in n)||!ke(a))continue;let u=Ce(n[s],a);if(u!==n[s])o[s]=u,r=!0}return r?o:n}function Tr(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}function V(e){let t=e?.trim();return t?t:void 0}function Zc(e){return Ol(e)}var oh=new RegExp(`${"⁣⟦"}([^${"⟧"}]*)${"⟧"}([\\s\\S]*?)${"⟦/⟧⁣"}`,"g");var wr=`# Plan Mode
57
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let s of e.seen.entries()){let a=s[1];if(t===s[0]){o(s);continue}if(e.external){let l=e.external.registry.get(s[0])?.id;if(t!==s[0]&&l){o(s);continue}}if(e.metadataRegistry.get(s[0])?.id){o(s);continue}if(a.cycle){o(s);continue}if(a.count>1){if(e.reused==="ref")o(s)}}if(e.external)e.sharedDefsExtractedFor=e.external}function Ri(e){let t=e.anyOf;if(!Array.isArray(t)||t.length===0||e.type!==void 0)return;let n=[];for(let r of t){if(!r||typeof r!=="object")return;Ri(r);let i=Object.keys(r);if(i.length!==1||i[0]!=="type")return;let o=r.type;for(let s of Array.isArray(o)?o:[o]){if(typeof s!=="string")return;if(!n.includes(s))n.push(s)}}delete e.anyOf,e.type=n.length===1?n[0]:n}var Oi=new Set(["type","properties","required","additionalProperties"]),Ar=["oneOf","anyOf"];function xr(e){let t=e.additionalProperties;if(t===void 0||t===!1||typeof t!=="object"||t===null)return null;return Object.keys(t).length?t:null}function rn(e){let t=[];for(let o of e){if(typeof o!=="object"||o.type!=="object")return null;for(let s in o)if(!Oi.has(s))return null;t.push(o)}let n={},r=new Set;for(let o of t){for(let s in o.properties){if(Object.prototype.hasOwnProperty.call(n,s))continue;let a=[];for(let u of t){let d=u.properties?.[s]??xr(u);if(d===null||d===void 0)continue;if(!a.some((h)=>JSON.stringify(h)===JSON.stringify(d)))a.push(d)}let l=a.length===1?a[0]:rn(a)??{allOf:a};ce(n,s,l)}for(let s of o.required??[])r.add(s)}let i={type:"object",properties:n};if(r.size)i.required=[...r];if(t.every((o)=>o.additionalProperties===!1))i.additionalProperties=!1;else{let o=[];for(let s of t){let a=xr(s);if(a&&!o.some((l)=>JSON.stringify(l)===JSON.stringify(a)))o.push(a)}if(o.length===1)i.additionalProperties=o[0];else if(o.length>1)i.additionalProperties={allOf:o}}return i}function vc(e){let t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(let i of Oi)if(i in e)return;let n=t.filter((i)=>Ar.some((o)=>Array.isArray(i[o]))),r=null;if(!n.length)r=rn(t);else{let i=n[0],o=Ar.find((l)=>Array.isArray(i[l]));if(Object.keys(i).length!==1)return;let s=t.filter((l)=>l!==i),a=i[o].map((l)=>rn([...s,l]));if(a.some((l)=>!l))return;r={[o]:a}}if(!r)return;delete e.allOf,Ke(e,r)}function At(e,t){let n=e.seen.get(t);if(!n)throw Error("Unprocessed schema. This is a bug in Zod.");let r=(a)=>{let l=e.seen.get(a);if(l.ref===null)return;let u=l.def??l.schema,d={...u},h=l.ref;if(l.ref=null,h){r(h);let f=e.seen.get(h),g=f.schema;if(g.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"))u.allOf=u.allOf??[],u.allOf.push(g);else Ke(u,g);if(Ke(u,d),a._zod.parent===h)for(let T in u){if(T==="$ref"||T==="allOf")continue;if(!(T in d))delete u[T]}if(g.$ref&&f.def)for(let T in u){if(T==="$ref"||T==="allOf")continue;if(T in f.def&&JSON.stringify(u[T])===JSON.stringify(f.def[T]))delete u[T]}}let p=a._zod.parent;if(p&&p!==h){r(p);let f=e.seen.get(p);if(f?.schema.$ref){if(u.$ref=f.schema.$ref,f.def)for(let g in u){if(g==="$ref"||g==="allOf")continue;if(g in f.def&&JSON.stringify(u[g])===JSON.stringify(f.def[g]))delete u[g]}}}e.override({zodSchema:a,jsonSchema:u,path:l.path??[]})};if(!e.external||e.sharedEmitDoneFor!==e.external){for(let a of[...e.seen.entries()].reverse())r(a[0]);if(e.target!=="openapi-3.0")for(let a of e.seen.entries())Ri(a[1].def??a[1].schema);for(let a of e.deferred)a();if(e.intersections.length){let a=new Map;for(let l of e.seen.values())for(let u of[l.schema,l.def]){let d=u?.allOf;if(!Array.isArray(d))continue;let h=a.get(d);if(h)h.push(u);else a.set(d,[u])}for(let l of e.intersections)for(let u of a.get(l)??[])vc(u)}}let i={};if(e.target==="draft-2020-12")i.$schema="https://json-schema.org/draft/2020-12/schema";else if(e.target==="draft-07")i.$schema="http://json-schema.org/draft-07/schema#";else if(e.target==="draft-04")i.$schema="http://json-schema.org/draft-04/schema#";else if(e.target==="openapi-3.0");if(e.external?.uri){let a=e.external.registry.get(t)?.id;if(!a)throw Error("Schema is missing an `id` property");i.$id=e.external.uri(a)}Ke(i,n.defId?n.schema:n.def??n.schema);let o=e.metadataRegistry.get(t)?.id;if(o!==void 0&&i.id===o)delete i.id;let s=e.external?.defs??{};if(!e.external||e.sharedEmitDoneFor!==e.external)for(let a of e.seen.entries()){let l=a[1];if(l.def&&l.defId){if(l.def.id===l.defId)delete l.def.id;ce(s,l.defId,l.def)}}if(e.external)e.sharedEmitDoneFor=e.external;if(e.external);else if(Object.keys(s).length>0)if(e.target==="draft-2020-12")i.$defs=s;else i.definitions=s;try{let a=JSON.parse(JSON.stringify(i));return Object.defineProperty(a,"~standard",{value:{...t["~standard"],jsonSchema:{input:xt(t,"input",e.processors),output:xt(t,"output",e.processors)}},enumerable:!1,writable:!1}),a}catch(a){throw Error("Error converting schema to JSON.")}}function Y(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 Y(r.element,n);if(r.type==="set")return Y(r.valueType,n);if(r.type==="lazy")return Y(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"||r.type==="catch")return Y(r.innerType,n);if(r.type==="intersection")return Y(r.left,n)||Y(r.right,n);if(r.type==="record"||r.type==="map")return Y(r.keyType,n)||Y(r.valueType,n);if(r.type==="pipe"){if(e._zod.traits.has("$ZodCodec"))return!0;return Y(r.in,n)||Y(r.out,n)}if(r.type==="object"){for(let i in r.shape)if(Y(r.shape[i],n))return!0;return!1}if(r.type==="union"){for(let i of r.options)if(Y(i,n))return!0;return!1}if(r.type==="tuple"){for(let i of r.items)if(Y(i,n))return!0;if(r.rest&&Y(r.rest,n))return!0;return!1}return!1}var bc=(e,t={})=>(n)=>{let r=kt({...n,processors:t});return L(e,r),Et(r,e),At(r,e)},xt=(e,t,n={})=>(r)=>{let{libraryOptions:i,target:o}=r??{},s=kt({...i??{},target:o,io:t,processors:n});return L(e,s),Et(s,e),At(s,e)},$e=(e,t,n)=>{if(e[t]===void 0||n>e[t])e[t]=n},Le=(e,t,n)=>{if(e[t]===void 0||n<e[t])e[t]=n},Ir=(e,t)=>{$e(e,"minimum",t),Le(e,"maximum",t)},Ni=(e,t)=>{if(e.multipleOf??(e.multipleOf=[]),!e.multipleOf.includes(t))e.multipleOf.push(t)},Mi=(e,t)=>{e.patterns??(e.patterns=new Set),e.patterns.add(t)},Pi=(e,t)=>{e.mime=e.mime?e.mime.filter((n)=>t.includes(n)):[...t]},$i=(e,t)=>{if(e.format=t,t.includes("int"))e.isInt=!0},Cr=(e,t)=>$e(e,"minimum",t.minimum),Sr=(e,t)=>Le(e,"maximum",t.maximum),Rr=(e)=>(t,n)=>{$i(t,n.format);let[r,i]=e[n.format];$e(t,"minimum",r),Le(t,"maximum",i)},Tc={greater_than:(e,t)=>$e(e,t.inclusive?"minimum":"exclusiveMinimum",t.value),less_than:(e,t)=>Le(e,t.inclusive?"maximum":"exclusiveMaximum",t.value),multiple_of:(e,t)=>Ni(e,t.value),number_format:Rr(Qr),bigint_format:Rr(Ms),min_length:Cr,max_length:Sr,length_equals:(e,t)=>Ir(e,t.length),min_size:Cr,max_size:Sr,size_equals:(e,t)=>Ir(e,t.size),string_format:(e,t)=>{if($i(e,t.format),t.pattern)Mi(e,t.pattern);if(t.format==="base64"||t.format==="base64url")e.contentEncoding=t.format;if(t.local||t.precision===-1)e.laxFormat=!0},mime_type:(e,t)=>Pi(e,t.mime)};function X(e){let t={},n=e._zod.def,r=e._zod.traits.has("$ZodCheck")?[e,...n.checks??[]]:n.checks??[];for(let o of r)Tc[o._zod.def.check]?.(t,o._zod.def);let i=e._zod.bag;if(i.minimum!==void 0)$e(t,"minimum",i.minimum);if(i.exclusiveMinimum!==void 0)$e(t,"exclusiveMinimum",i.exclusiveMinimum);if(i.maximum!==void 0)Le(t,"maximum",i.maximum);if(i.exclusiveMaximum!==void 0)Le(t,"exclusiveMaximum",i.exclusiveMaximum);if(i.multipleOf!==void 0)Ni(t,i.multipleOf);if(i.format!==void 0){if(t.format??(t.format=i.format),i.format.includes("int"))t.isInt=!0}if(i.mime)Pi(t,i.mime);for(let o of i.patterns??[])Mi(t,o);return t}var wc={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},_c=new Map([[mi,Ma],[_n,Pa]]),Li=(e)=>_c.get(e)??e,zi=(e,t,n,r)=>{let i=n;i.type="string";let{minimum:o,maximum:s,format:a,patterns:l,contentEncoding:u,laxFormat:d}=X(e);if(typeof o==="number")i.minLength=o;if(typeof s==="number")i.maxLength=s;if(a){if(i.format=wc[a]??a,i.format==="")delete i.format;if(a==="time"||d)delete i.format}if(u)i.contentEncoding=u;if(l&&l.size>0){let h=[...l].map(Li);if(h.length===1)i.pattern=h[0].source;else if(h.length>1)i.allOf=[...h.map((p)=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:p.source}))]}},Di=(e,t,n,r)=>{let i=n,{minimum:o,maximum:s,multipleOf:a,exclusiveMaximum:l,exclusiveMinimum:u,isInt:d}=X(e);i.type=d?"integer":"number";let h=typeof u==="number"&&u>=(o??Number.NEGATIVE_INFINITY),p=typeof l==="number"&&l<=(s??Number.POSITIVE_INFINITY),f=t.target==="draft-04"||t.target==="openapi-3.0";if(h)if(f)i.minimum=u,i.exclusiveMinimum=!0;else i.exclusiveMinimum=u;else if(typeof o==="number")i.minimum=o;if(p)if(f)i.maximum=l,i.exclusiveMaximum=!0;else i.exclusiveMaximum=l;else if(typeof s==="number")i.maximum=s;if(a){let g=new Set;for(let _ of a)if(Number.isFinite(_)&&_!==0)g.add(Math.abs(_));else Z(e,t,i,r,`A multipleOf divisor of ${_} cannot be represented in JSON Schema`);let[T,...k]=g;if(T!==void 0)i.multipleOf=T;if(k.length)i.allOf=[...i.allOf??[],...k.map((_)=>({multipleOf:_}))]}},Ui=(e,t,n,r)=>{n.type="boolean"},kc=(e,t,n,r)=>{Z(e,t,n,r,"BigInt cannot be represented in JSON Schema")},Ec=(e,t,n,r)=>{Z(e,t,n,r,"Symbols cannot be represented in JSON Schema")},Ac=(e,t,n,r)=>{if(t.target==="openapi-3.0")n.type="string",n.nullable=!0,n.enum=[null];else n.type="null"},xc=(e,t,n,r)=>{Z(e,t,n,r,"Undefined cannot be represented in JSON Schema")},Fi=(e,t,n,r)=>{Z(e,t,n,r,"Void cannot be represented in JSON Schema")},ji=(e,t,n,r)=>{n.not={}},Ic=(e,t,n,r)=>{},Bi=(e,t,n,r)=>{},qi=(e,t,n,r)=>{Z(e,t,n,r,"Date cannot be represented in JSON Schema")},Hi=(e,t,n,r)=>{let i=e._zod.def,o=Yt(i.entries);if(o.length===0){n.not={};return}if(o.every((s)=>typeof s==="number"))n.type="number";if(o.every((s)=>typeof s==="string"))n.type="string";n.enum=o},Wi=(e,t,n,r)=>{let i=e._zod.def;if(i.values.length===0){n.not={};return}let o=[];for(let s of i.values)if(s===void 0){if(Z(e,t,n,r,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof s==="bigint"){if(Z(e,t,n,r,"BigInt literals cannot be represented in JSON Schema"))return;o.push(Number(s))}else o.push(s);if(o.length===0);else if(o.length===1){let s=o[0];if(n.type=s===null?"null":typeof s,t.target==="draft-04"||t.target==="openapi-3.0")n.enum=[s];else n.const=s}else{if(o.every((s)=>typeof s==="number"))n.type="number";if(o.every((s)=>typeof s==="string"))n.type="string";if(o.every((s)=>typeof s==="boolean"))n.type="boolean";if(o.every((s)=>s===null))n.type="null";n.enum=o}},Cc=(e,t,n,r)=>{Z(e,t,n,r,"NaN cannot be represented in JSON Schema")},Sc=(e,t,n,r)=>{let i=n,o=e._zod.pattern;if(!o)throw Error("Pattern not found in template literal");i.type="string",i.pattern=o.source},Rc=(e,t,n,r)=>{let i=n;i.type="string",i.format="binary",i.contentEncoding="binary";let{minimum:o,maximum:s,mime:a}=X(e);if(o!==void 0)i.minLength=o;if(s!==void 0)i.maxLength=s;if(!a)return;if(a.length===0)i.not={};else if(a.length===1)i.contentMediaType=a[0];else i.anyOf=a.map((l)=>({contentMediaType:l}))},Oc=(e,t,n,r)=>{n.type="boolean"},Zi=(e,t,n,r)=>{Z(e,t,n,r,"Custom types cannot be represented in JSON Schema")},Vi=(e,t,n,r)=>{Z(e,t,n,r,"Function types cannot be represented in JSON Schema")},Gi=(e,t,n,r)=>{Z(e,t,n,r,"Transforms cannot be represented in JSON Schema")},Nc=(e,t,n,r)=>{Z(e,t,n,r,"Map cannot be represented in JSON Schema")},Mc=(e,t,n,r)=>{Z(e,t,n,r,"Set cannot be represented in JSON Schema")},Ki=(e,t,n,r)=>{let i=n,o=e._zod.def,{minimum:s,maximum:a}=X(e);if(typeof s==="number")i.minItems=s;if(typeof a==="number")i.maxItems=a;i.type="array",i.items=L(o.element,t,{...r,path:[...r.path,"items"]})};function Qe(e){let t=e._zod.def;if(t.type==="pipe"&&t.in._zod.traits.has("$ZodTransform"))return Qe(t.out);if(t.type==="catch")return Qe(t.innerType);return e._zod.optin}var Ji=(e,t,n,r)=>{let i=n,o=e._zod.def,s=o.shape;if(Object.getOwnPropertySymbols(s).length&&Z(e,t,i,r,"Symbol keys cannot be represented in JSON Schema"))return;i.type="object",i.properties={};for(let l in s)ce(i.properties,l,L(s[l],t,{...r,path:[...r.path,"properties",l]}));let a=[];for(let l of Object.keys(s)){let u=o.shape[l];if(t.io==="input"?Qe(u)===void 0:u._zod.optout===void 0)a.push(l)}if(a.length>0)i.required=a;if(o.catchall?._zod.def.type==="never")i.additionalProperties=!1;else if(!o.catchall){if(t.io==="output")i.additionalProperties=!1}else if(o.catchall)i.additionalProperties=L(o.catchall,t,{...r,path:[...r.path,"additionalProperties"]})},Yi=(e,t,n,r)=>{let i=e._zod.def,o=i.inclusive===!1,s=i.options.map((a,l)=>L(a,t,{...r,path:[...r.path,o?"oneOf":"anyOf",l]}));if(o)n.oneOf=s;else n.anyOf=s},Xi=(e,t,n,r)=>{let i=e._zod.def,o=L(i.left,t,{...r,path:[...r.path,"allOf",0]}),s=L(i.right,t,{...r,path:[...r.path,"allOf",1]}),a=(u)=>("allOf"in u)&&Object.keys(u).length===1,l=[...a(o)?o.allOf:[o],...a(s)?s.allOf:[s]];n.allOf=l,t.intersections.push(l)},Qi=(e,t,n,r)=>{let i=n,o=e._zod.def;i.type="array";let s=t.target==="draft-2020-12"?"prefixItems":"items",a=t.target==="draft-2020-12"?"items":t.target==="openapi-3.0"?"items":"additionalItems",l=o.items.map((T,k)=>L(T,t,{...r,path:[...r.path,s,k]})),u=o.rest?L(o.rest,t,{...r,path:[...r.path,a,...t.target==="openapi-3.0"?[o.items.length]:[]]}):null,d=o.items.length;while(d>0){let T=o.items[d-1];if(!(t.io==="input"?Qe(T)!==void 0:T._zod.optout==="optional"))break;d--}let h=o.items.length,p=!o.rest;if(t.target==="draft-2020-12"){if(i.prefixItems=l,p)i.items=!1;else if(u)i.items=u;if(d>0)i.minItems=d;if(p)i.maxItems=h}else if(t.target==="openapi-3.0"){if(i.items={anyOf:l},u)i.items.anyOf.push(u);if(d>0)i.minItems=d;if(p)i.maxItems=h}else{if(i.items=l,p)i.additionalItems=!1;else if(u)i.additionalItems=u;if(d>0)i.minItems=d;if(p)i.maxItems=h}let{minimum:f,maximum:g}=X(e);if(typeof f==="number")i.minItems=f;if(typeof g==="number")i.maxItems=g};function on(e,t,n){if(t.$ref){if(n.has(t))return t;n.add(t);let g=e.get(t)?.def;if(!g)return t;let T=on(e,g,n);return T===g?t:T}for(let g of["anyOf","oneOf"]){let T=t[g];if(!Array.isArray(T))continue;let k=T.map((_)=>on(e,_,n));if(k.some((_,B)=>_!==T[B]))t={...t,[g]:k}}let r=Array.isArray(t.type)?t.type:[t.type],i=!r.includes("string")&&r.some((g)=>g==="number"||g==="integer"),o=t.enum??(t.const!==void 0?[t.const]:void 0);if(!i&&!o?.some((g)=>typeof g==="number"))return t;let{minimum:s,maximum:a,exclusiveMinimum:l,exclusiveMaximum:u,multipleOf:d,format:h,id:p,...f}=t;if(f.enum)f.enum=f.enum.map((g)=>typeof g==="number"?String(g):g);else if(typeof f.const==="number")f.const=String(f.const);if(!i)return f;if(f.type="string",!o)f.pattern=(r.includes("number")?bn:Ba).source;return f}var sn=new WeakMap;function Pc(e){let t=new Map;for(let r of e.seen.values())if(r.def&&!t.has(r.schema))t.set(r.schema,r);let n=new Map;for(let r of sn.get(e)??[]){let i=e.seen.get(r),o=(i?.def??i?.schema)?.propertyNames;if(!o||o===!0||n.has(o))continue;let s=on(t,o,new Set);if(s!==o)n.set(o,s)}if(!n.size)return;for(let r of e.seen.values())for(let i of[r.schema,r.def]){let o=i&&n.get(i.propertyNames);if(o)i.propertyNames=o}}var eo=(e,t,n,r)=>{let i=n,o=e._zod.def;i.type="object";let s=o.keyType,a=X(s).patterns;if(o.mode==="loose"&&a&&a.size>0){let d=L(o.valueType,t,{...r,path:[...r.path,"patternProperties","*"]});i.patternProperties={};for(let h of a)ce(i.patternProperties,Li(h).source,d)}else{if(t.target==="draft-07"||t.target==="draft-2020-12"){i.propertyNames=L(o.keyType,t,{...r,path:[...r.path,"propertyNames"]});let d=sn.get(t);if(!d)d=[],sn.set(t,d),t.deferred.push(()=>Pc(t));d.push(e)}i.additionalProperties=L(o.valueType,t,{...r,path:[...r.path,"additionalProperties"]})}let l=s._zod.values,u=t.io==="input"&&Qe(o.valueType)!==void 0;if(l&&!o.partial&&!u){let d=[...l].filter((h)=>typeof h==="string"||typeof h==="number");if(d.length>0)i.required=d.map(String)}},to=(e,t,n,r)=>{let i=e._zod.def,o=L(i.innerType,t,r),s=t.seen.get(e);if(t.target==="openapi-3.0")s.ref=i.innerType,n.nullable=!0;else n.anyOf=[o,{type:"null"}]},no=(e,t,n,r)=>{let i=e._zod.def;L(i.innerType,t,r);let o=t.seen.get(e);o.ref=i.innerType},kn=Symbol();function ro(e,t,n,r,i){let o=!1,s=JSON.stringify(e,(a,l)=>{if(typeof l!=="bigint")return l;return o=!0,null});if(!o)return JSON.parse(s);return Z(t,n,r,i,"BigInt defaults cannot be represented in JSON Schema"),kn}var io=(e,t,n,r)=>{let i=e._zod.def;L(i.innerType,t,r);let o=t.seen.get(e);o.ref=i.innerType;let s=ro(i.defaultValue,e,t,n,r);if(s!==kn)n.default=s},oo=(e,t,n,r)=>{let i=e._zod.def;L(i.innerType,t,r);let o=t.seen.get(e);if(o.ref=i.innerType,t.io!=="input")return;let s=ro(i.defaultValue,e,t,n,r);if(s!==kn)n._prefault=s},so=(e,t,n,r)=>{let i=e._zod.def;L(i.innerType,t,r);let o=t.seen.get(e);o.ref=i.innerType;let s;try{s=i.catchValue(void 0)}catch{Z(e,t,n,r,"Dynamic catch values are not supported in JSON Schema");return}n.default=s},ao=(e,t,n,r)=>{let i=e._zod.def,o=i.in._zod.traits.has("$ZodTransform"),s=t.io==="input"?o?i.out:i.in:i.out;L(s,t,r);let a=t.seen.get(e);a.ref=s},lo=(e,t,n,r)=>{let i=e._zod.def;L(i.innerType,t,r);let o=t.seen.get(e);o.ref=i.innerType,n.readOnly=!0},uo=(e,t,n,r)=>{let i=e._zod.def;L(i.innerType,t,r);let o=t.seen.get(e);o.ref=i.innerType},En=(e,t,n,r)=>{let i=e._zod.def;L(i.innerType,t,r);let o=t.seen.get(e);o.ref=i.innerType},$c=(e,t,n,r)=>{let i=e._zod.innerType;L(i,t,r);let o=t.seen.get(e);o.ref=i},Or={string:zi,number:Di,boolean:Ui,bigint:kc,symbol:Ec,null:Ac,undefined:xc,void:Fi,never:ji,any:Ic,unknown:Bi,date:qi,enum:Hi,literal:Wi,nan:Cc,template_literal:Sc,file:Rc,success:Oc,custom:Zi,function:Vi,transform:Gi,map:Nc,set:Mc,array:Ki,object:Ji,union:Yi,intersection:Xi,tuple:Qi,record:eo,nullable:to,nonoptional:no,default:io,prefault:oo,catch:so,pipe:ao,readonly:lo,promise:uo,optional:En,lazy:$c};function Lc(e,t){if("_idmap"in e){let r=e,i=kt({...t,processors:Or}),o={};for(let l of r._idmap.entries()){let[u,d]=l;L(d,i)}let s={},a={registry:r,uri:t?.uri,defs:o};i.external=a;for(let l of r._idmap.entries()){let[u,d]=l;Et(i,d),ce(s,u,At(i,d))}if(Object.keys(o).length>0){let l=i.target==="draft-2020-12"?"$defs":"definitions";s.__shared={[l]:o}}return{schemas:s}}let n=kt({...t,processors:Or});return L(e,n),Et(n,e),At(n,e)}var Nr=new WeakSet([Object.prototype,Error.prototype]);function pt(e,t,n){Object.defineProperty(e,t,{configurable:!0,enumerable:!1,get(){let r=n(this);return Object.defineProperty(this,t,{value:r,configurable:!0,writable:!0}),r},set(r){Object.defineProperty(this,t,{value:r,configurable:!0,writable:!0})}})}var zc=(e,t)=>{ea.init(e,t),e.name="ZodError";let n=Object.getPrototypeOf(e);if(Nr.has(n))return;Nr.add(n),pt(n,"format",(r)=>(i)=>ra(r,i)),pt(n,"flatten",(r)=>(i)=>na(r,i)),pt(n,"addIssue",(r)=>(i)=>{r.issues.push(i),r.message=JSON.stringify(r.issues,Xt,2)}),pt(n,"addIssues",(r)=>(i)=>{r.issues.push(...i),r.message=JSON.stringify(r.issues,Xt,2)}),Object.defineProperty(n,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}})},ie=m("ZodError",zc,void 0,{Parent:Error}),Dc=Ot(ie),Uc=Nt(ie),Fc=yn(ie),jc=vn(ie),Bc=ua(ie),qc=ca(ie),Hc=da(ie),Wc=pa(ie),Zc=fa(ie),Vc=ha(ie),Gc=ma(ie),Kc=ga(ie);function Jc(){if(!re.localeError)ue(Tu())}function et(){if(!re.memoizer)ue({memoizer:yu()})}var M=m("ZodType",(e,t)=>(Jc(),N.init(e,t),e.def=t,e.type=t.type,e),{check(...e){let t=this.def;return this.clone(ee(t,{checks:[...t.checks??[],...e.map((n)=>typeof n==="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return Te(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(Yd(e,t))},superRefine(e,t){return this.check(Xd(e,t))},overwrite(e){return this.check(De(e))},optional(){return $r(this)},exactOptional(){return zd(this)},nullable(){return Lr(this)},nullish(){return $r(Lr(this))},nonoptional(e){return qd(this,e)},array(){return x(this)},or(e){return se([this,e])},and(e){return Nd(this,e)},transform(e){return zr(this,ho(e))},default(e){return Fd(this,e)},prefault(e){return Bd(this,e)},catch(e){return Wd(this,e)},pipe(e){return zr(this,e)},readonly(){return Gd(this)},describe(e){let t=this.clone();return We.add(t,{description:e}),t},meta(...e){if(e.length===0)return We.get(this);let t=this.clone();return We.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e,...t){return t.length===0?e(this):e(this,...t)},get "~standard"(){return ti(this,"~standard",{...ci(this),jsonSchema:{input:xt(this,"input"),output:xt(this,"output")}})},set "~standard"(e){be(this,"~standard",e)},parse:function e(t,n){return Dc(this,t,n,{callee:e})},parseAsync:async function e(t,n){return await Uc(this,t,n,{callee:e})},safeParse(e,t){return Fc(this,e,t)},async safeParseAsync(e,t){return jc(this,e,t)},get spa(){return this?.safeParseAsync},set spa(e){be(this,"spa",e)},validate(e,t){return sa(this,e,t)},validateAsync(e,t){return la(this,e,t)},encode:function e(t,n){return Bc(this,t,n,{callee:e})},decode:function e(t,n){return qc(this,t,n,{callee:e})},encodeAsync:async function e(t,n){return await Hc(this,t,n,{callee:e})},decodeAsync:async function e(t,n){return await Wc(this,t,n,{callee:e})},safeEncode(e,t){return Zc(this,e,t)},safeDecode(e,t){return Vc(this,e,t)},async safeEncodeAsync(e,t){return Gc(this,e,t)},async safeDecodeAsync(e,t){return Kc(this,e,t)},toJSONSchema(e){return bc(this,{})(e)},get description(){return We.get(this)?.description},get _def(){return this._zod.def}}),co=m("_ZodString",(e,t)=>{wn.init(e,t),M.init(e,t),e._zod.processJSONSchema=(n,r,i)=>zi(e,n,r,i)},mn({format:(e)=>X(e).format??null,minLength:(e)=>X(e).minimum??null,maxLength:(e)=>X(e).maximum??null},{regex(...e){return this.check(nc(...e))},includes(...e){return this.check(oc(...e))},startsWith(...e){return this.check(sc(...e))},endsWith(...e){return this.check(ac(...e))},min(...e){return this.check(_t(...e))},max(...e){return this.check(Ci(...e))},length(...e){return this.check(Si(...e))},nonempty(...e){return this.check(_t(1,...e))},lowercase(e){return this.check(rc(e))},uppercase(e){return this.check(ic(e))},trim(){return this.check(uc())},normalize(...e){return this.check(lc(...e))},toLowerCase(){return this.check(cc())},toUpperCase(){return this.check(dc())},slugify(){return this.check(pc())}})),Yc=m("ZodString",(e,t)=>{wn.init(e,t),co.init(e,t)},{email(e){return this.check(ku(nd,e))},url(e){return this.check(Su(id,e))},jwt(e){return this.check(Hu(bd,e))},emoji(e){return this.check(Ru(od,e))},guid(e){return this.check(Eu(rd,e))},uuid(e){return this.check(Au(ft,e))},uuidv4(e){return this.check(xu(ft,e))},uuidv6(e){return this.check(Iu(ft,e))},uuidv7(e){return this.check(Cu(ft,e))},nanoid(e){return this.check(Ou(sd,e))},cuid(e){return this.check(Nu(ad,e))},cuid2(e){return this.check(Mu(ld,e))},ulid(e){return this.check(Pu(ud,e))},base64(e){return this.check(ju(gd,e))},base64url(e){return this.check(Bu(yd,e))},xid(e){return this.check($u(cd,e))},ksuid(e){return this.check(Lu(dd,e))},ipv4(e){return this.check(zu(pd,e))},ipv6(e){return this.check(Du(fd,e))},cidrv4(e){return this.check(Uu(hd,e))},cidrv6(e){return this.check(Fu(md,e))},e164(e){return this.check(qu(vd,e))},datetime(e){return this.check(Wu(Xc,e))},date(e){return this.check(Zu(Qc,e))},time(e){return this.check(Vu(ed,e))},duration(e){return this.check(Gu(td,e))}});function c(e){return _u(Yc,e)}var D=m("ZodStringFormat",(e,t)=>{z.init(e,t),co.init(e,t)}),Xc=m("ZodISODateTime",(e,t)=>{_l.init(e,t),D.init(e,t)}),Qc=m("ZodISODate",(e,t)=>{kl.init(e,t),D.init(e,t)}),ed=m("ZodISOTime",(e,t)=>{El.init(e,t),D.init(e,t)}),td=m("ZodISODuration",(e,t)=>{Al.init(e,t),D.init(e,t)}),nd=m("ZodEmail",(e,t)=>{ll.init(e,t),D.init(e,t)}),rd=m("ZodGUID",(e,t)=>{sl.init(e,t),D.init(e,t)}),ft=m("ZodUUID",(e,t)=>{al.init(e,t),D.init(e,t)}),id=m("ZodURL",(e,t)=>{hl.init(e,t),D.init(e,t)}),od=m("ZodEmoji",(e,t)=>{ml.init(e,t),D.init(e,t)}),sd=m("ZodNanoID",(e,t)=>{gl.init(e,t),D.init(e,t)}),ad=m("ZodCUID",(e,t)=>{yl.init(e,t),D.init(e,t)}),ld=m("ZodCUID2",(e,t)=>{vl.init(e,t),D.init(e,t)}),ud=m("ZodULID",(e,t)=>{bl.init(e,t),D.init(e,t)}),cd=m("ZodXID",(e,t)=>{Tl.init(e,t),D.init(e,t)}),dd=m("ZodKSUID",(e,t)=>{wl.init(e,t),D.init(e,t)}),pd=m("ZodIPv4",(e,t)=>{xl.init(e,t),D.init(e,t)}),fd=m("ZodIPv6",(e,t)=>{Cl.init(e,t),D.init(e,t)}),hd=m("ZodCIDRv4",(e,t)=>{Sl.init(e,t),D.init(e,t)}),md=m("ZodCIDRv6",(e,t)=>{Ol.init(e,t),D.init(e,t)}),gd=m("ZodBase64",(e,t)=>{Nl.init(e,t),D.init(e,t)}),yd=m("ZodBase64URL",(e,t)=>{Pl.init(e,t),D.init(e,t)}),vd=m("ZodE164",(e,t)=>{$l.init(e,t),D.init(e,t)}),bd=m("ZodJWT",(e,t)=>{zl.init(e,t),D.init(e,t)}),po=m("ZodNumber",(e,t)=>{gi.init(e,t),M.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Di(e,n,r,i),e.isFinite=!0},mn({minValue:(e)=>{let{minimum:t,exclusiveMinimum:n}=X(e);return Math.max(t??Number.NEGATIVE_INFINITY,n??Number.NEGATIVE_INFINITY)},maxValue:(e)=>{let{maximum:t,exclusiveMaximum:n}=X(e);return Math.min(t??Number.POSITIVE_INFINITY,n??Number.POSITIVE_INFINITY)},isInt:(e)=>{let{isInt:t,multipleOf:n}=X(e);return!!t||!!n?.some(Number.isSafeInteger)},format:(e)=>X(e).format??null},{gt(e,t){return this.check(_r(e,t))},gte(e,t){return this.check(vt(e,t))},min(e,t){return this.check(vt(e,t))},lt(e,t){return this.check(wr(e,t))},lte(e,t){return this.check(yt(e,t))},max(e,t){return this.check(yt(e,t))},int(e){return this.check(Mr(e))},safe(e){return this.check(Mr(e))},positive(e){return this.check(_r(0,e))},nonnegative(e){return this.check(vt(0,e))},negative(e){return this.check(wr(0,e))},nonpositive(e){return this.check(yt(0,e))},multipleOf(e,t){return this.check(kr(e,t))},step(e,t){return this.check(kr(e,t))},finite(){return this}}));function b(e){return Ku(po,e)}var Td=m("ZodNumberFormat",(e,t)=>{Dl.init(e,t),po.init(e,t)});function Mr(e){return Ju(Td,e)}var wd=m("ZodBoolean",(e,t)=>{Ul.init(e,t),M.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Ui(e,n,r,i)});function S(e){return Yu(wd,e)}var _d=m("ZodUnknown",(e,t)=>{Fl.init(e,t),M.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Bi(e,n,r,i)});function W(){return Xu(_d)}var kd=m("ZodNever",(e,t)=>{jl.init(e,t),M.init(e,t),e._zod.processJSONSchema=(n,r,i)=>ji(e,n,r,i)});function Ed(e){return Qu(kd,e)}var Ad=m("ZodVoid",(e,t)=>{Bl.init(e,t),M.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Fi(e,n,r,i)});function xd(e){return ec(Ad,e)}var Id=m("ZodDate",(e,t)=>{ql.init(e,t),M.init(e,t),e._zod.processJSONSchema=(n,r,i)=>qi(e,n,r,i),e.min=(n,r)=>e.check(vt(n,r)),e.max=(n,r)=>e.check(yt(n,r))},mn({minDate:(e)=>{let{minimum:t}=X(e);return t?new Date(t):null},maxDate:(e)=>{let{maximum:t}=X(e);return t?new Date(t):null}},{}));function It(e){return tc(Id,e)}var Cd=m("ZodArray",(e,t)=>{et(),Zl.init(e,t),M.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Ki(e,n,r,i),e.element=t.element},{min(e,t){return this.check(_t(e,t))},nonempty(e){return this.check(_t(1,e))},max(e,t){return this.check(Ci(e,t))},length(e,t){return this.check(Si(e,t))},unwrap(){return this.element}});function x(e,t){return fc(Cd,e,t)}var Sd=m("ZodObject",(e,t)=>{et(),Kl.init(e,t),M.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Ji(e,n,r,i),Vs(e,"shape",(n)=>n._zod.def.shape,!1)},{keyof(){return I(Object.keys(this._zod.def.shape))},catchall(e){return this.clone(ee(this._zod.def,{catchall:e}))},passthrough(){return this.clone(ee(this._zod.def,{catchall:W()}))},loose(){return this.clone(ee(this._zod.def,{catchall:W()}))},strict(){return this.clone(ee(this._zod.def,{catchall:Ed()}))},strip(){return this.clone(ee(this._zod.def,{catchall:void 0}))},extend(e){return Ls(this,e)},safeExtend(e){return zs(this,e)},merge(e){return Ds(this,e)},pick(e){return Ps(this,e)},omit(e){return $s(this,e)},partial(...e){return Xn(xn,this,e[0])},exactPartial(...e){return Xn(mo,this,e[0],"exactPartial")},required(...e){return Us(go,this,e[0])}});function y(e,t){let n={type:"object",shape:e??{},...w(t)};return new Sd(n)}var fo=m("ZodUnion",(e,t)=>{bi.init(e,t),M.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Yi(e,n,r,i),e.options=t.options});function se(e,t){return new fo({type:"union",options:e,...w(t)})}var Rd=m("ZodDiscriminatedUnion",(e,t)=>{fo.init(e,t),Yl.init(e,t)});function An(e,t,n){return new Rd({type:"union",options:t,discriminator:e,...w(n)})}var Od=m("ZodIntersection",(e,t)=>{Xl.init(e,t),M.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Xi(e,n,r,i)});function Nd(e,t){return new Od({type:"intersection",left:e,right:t})}var Md=m("ZodTuple",(e,t)=>{et(),Ti.init(e,t),M.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Qi(e,n,r,i)},{rest(e){return this.clone({...this._zod.def,rest:e})},partial(){let e=this._zod.def;if(e.checks?.length)throw Error(".partial() cannot be used on tuple schemas containing refinements");return this.clone({...e,items:e.items.map((t)=>new xn({type:"optional",innerType:t}))})}});function Pd(e,t,n){let r=t instanceof N;return new Md({type:"tuple",items:e,rest:r?t:null,...w(r?n:t)})}var Pr=m("ZodRecord",(e,t)=>{et(),Ql.init(e,t),M.init(e,t),e._zod.processJSONSchema=(n,r,i)=>eo(e,n,r,i),e.keyType=t.keyType,e.valueType=t.valueType});function j(e,t,n){if(!t||!t._zod)return new Pr({type:"record",keyType:c(),valueType:e,...w(t)});return new Pr({type:"record",keyType:e,valueType:t,...w(n)})}var an=m("ZodEnum",(e,t)=>{eu.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,i,o)=>Hi(e,r,i,o),e.enum=t.entries,e.options=[...e._zod.values];let n=new Set(Object.keys(t.entries));e.extract=(r,i)=>{let o={};for(let s of r)if(n.has(s))o[s]=t.entries[s];else throw Error(`Key ${s} not found in enum`);return new an({...t,checks:[],...w(i),entries:o})},e.exclude=(r,i)=>{let o={...t.entries};for(let s of r)if(n.has(s))delete o[s];else throw Error(`Key ${s} not found in enum`);return new an({...t,checks:[],...w(i),entries:o})}});function I(e,t){let n=Array.isArray(e)?Object.fromEntries(e.map((r)=>[r,r])):e;return new an({type:"enum",entries:n,...w(t)})}var $d=m("ZodLiteral",(e,t)=>{tu.init(e,t),M.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Wi(e,n,r,i),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function U(e,t){return new $d({type:"literal",values:Array.isArray(e)?e:[e],...w(t)})}var Ld=m("ZodTransform",(e,t)=>{et(),nu.init(e,t),M.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Gi(e,n,r,i),e._zod.parse=(n,r)=>{if(r.direction==="backward")throw new gn(e.constructor.name);n.addIssue=(o)=>{if(typeof o==="string")n.issues.push(Xe(o,n.value,t));else{let s=o;if(s.fatal)s.continue=!1;if(s.code??(s.code="custom"),!("input"in s))s.input=n.value;s.inst??(s.inst=e),n.issues.push(Xe(s))}};let i=t.transform(n.value,n);if(i instanceof Promise)return i.then((o)=>(n.value=o,n));return n.value=i,n}});function ho(e){return new Ld({type:"transform",transform:e})}var xn=m("ZodOptional",(e,t)=>{wi.init(e,t),M.init(e,t),e._zod.processJSONSchema=(n,r,i)=>En(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function $r(e){return new xn({type:"optional",innerType:e})}var mo=m("ZodExactOptional",(e,t)=>{ru.init(e,t),M.init(e,t),e._zod.processJSONSchema=(n,r,i)=>En(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function zd(e){return new mo({type:"optional",innerType:e})}var Dd=m("ZodNullable",(e,t)=>{iu.init(e,t),M.init(e,t),e._zod.processJSONSchema=(n,r,i)=>to(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function Lr(e){return new Dd({type:"nullable",innerType:e})}var Ud=m("ZodDefault",(e,t)=>{ou.init(e,t),M.init(e,t),e._zod.processJSONSchema=(n,r,i)=>io(e,n,r,i),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Fd(e,t){return new Ud({type:"default",innerType:e,get defaultValue(){return typeof t==="function"?t():Yr(t)}})}var jd=m("ZodPrefault",(e,t)=>{su.init(e,t),M.init(e,t),e._zod.processJSONSchema=(n,r,i)=>oo(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function Bd(e,t){return new jd({type:"prefault",innerType:e,get defaultValue(){return typeof t==="function"?t():Yr(t)}})}var go=m("ZodNonOptional",(e,t)=>{au.init(e,t),M.init(e,t),e._zod.processJSONSchema=(n,r,i)=>no(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function qd(e,t){return new go({type:"nonoptional",innerType:e,...w(t)})}var Hd=m("ZodCatch",(e,t)=>{lu.init(e,t),M.init(e,t),e._zod.processJSONSchema=(n,r,i)=>so(e,n,r,i),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Wd(e,t){return new Hd({type:"catch",innerType:e,catchValue:typeof t==="function"?t:Ks(t)})}var yo=m("ZodPipe",(e,t)=>{_i.init(e,t),M.init(e,t),e._zod.processJSONSchema=(n,r,i)=>ao(e,n,r,i),e.in=t.in,e.out=t.out});function zr(e,t){return new yo({type:"pipe",in:e,out:t})}var Zd=m("ZodPreprocess",(e,t)=>{yo.init(e,t),uu.init(e,t)}),Vd=m("ZodReadonly",(e,t)=>{cu.init(e,t),M.init(e,t),e._zod.processJSONSchema=(n,r,i)=>lo(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function Gd(e){return new Vd({type:"readonly",innerType:e})}var Kd=m("ZodPromise",(e,t)=>{pu.init(e,t),M.init(e,t),e._zod.processJSONSchema=(n,r,i)=>uo(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function Vt(e){return new Kd({type:"promise",innerType:e})}var Jd=m("ZodFunction",(e,t)=>{du.init(e,t),M.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Vi(e,n,r,i)});function ht(e){return new Jd({type:"function",input:Array.isArray(e?.input)?Pd(e?.input):e?.input??x(W()),output:e?.output??W()})}var vo=m("ZodCustom",(e,t)=>{fu.init(e,t),M.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Zi(e,n,r,i)});function ne(e,t){return hc(vo,e??(()=>!0),t)}function Yd(e,t={}){return mc(vo,e,t)}function Xd(e,t){return gc(e,t)}function bo(e,t){return new Zd({type:"pipe",in:ho(e),out:t})}var To=["none","minimal","low","medium","high","xhigh","max"],Qd=I(To),ep=Qd.exclude(["none"]),tp=I([...To,"default"]).nullable(),np=An("type",[y({type:U("toggle")}).strict(),y({type:U("effort"),values:x(tp)}).strict(),y({type:U("budget_tokens"),min:b().min(-1).optional(),max:b().min(0).optional()}).strict().refine((e)=>e.min===void 0||e.max===void 0||e.min<=e.max,{message:"Minimum reasoning budget cannot exceed maximum",path:["min"]})]),rp=I(["default","openai-responses","r1"]);var ip=I(["images","video","tools","streaming","prompt-cache","reasoning","reasoning-effort","computer-use","global-endpoint","structured_output","temperature","files"]),op=I(["active","preview","deprecated","legacy"]),sp=y({input:b().optional(),output:b().optional(),cacheWrite:b().optional(),cacheRead:b().optional()}),ap=y({maxBudget:b().optional(),outputPrice:b().optional(),thinkingLevel:I(["low","high"]).optional()}),lp=y({reasoningDefaultOn:S().optional(),apiProtocol:I(["openai-chat","openai-responses","anthropic","gemini"]).optional()}).catchall(W()),Dr=I(["text","image","audio","video","pdf"]),up=y({input:x(Dr),output:x(Dr)});var cp=I(["language","image-generation","speech-generation","video-generation","transcription","realtime"]);var dp=I(["batch","streaming"]);var wo=y({id:c(),name:c().optional(),description:c().optional(),maxTokens:b().optional(),contextWindow:b().optional(),maxInputTokens:b().optional(),capabilities:x(ip).optional(),operation:cp.optional(),operationModes:x(dp).optional(),modalities:up.optional(),reasoningOptions:x(np).optional(),apiFormat:rp.optional(),systemRole:I(["system","developer"]).optional(),temperature:b().optional(),pricing:sp.optional(),thinkingConfig:ap.optional(),status:op.optional(),deprecationNotice:c().optional(),replacedBy:c().optional(),releaseDate:c().optional(),deprecationDate:c().optional(),family:c().optional(),metadata:lp.optional()});var _o="NOT a tool or system failure. Clarify with user before proceeding.",pp=y({id:c(),name:c(),execution:I(["client","provider"]).optional(),input:W(),output:W(),error:c().optional(),durationMs:b(),startedAt:It(),endedAt:It()}),fp=I(["completed","max_iterations","aborted","mistake_limit","error"]),hp=y({inputTokens:b(),outputTokens:b(),cacheReadTokens:b().optional(),cacheWriteTokens:b().optional(),totalCost:b().optional()}),Kh=y({text:c(),usage:hp,messages:x(ne()),toolCalls:x(pp),iterations:b(),finishReason:fp,model:y({id:c(),provider:c(),info:wo.optional()}),startedAt:It(),endedAt:It(),durationMs:b()}),Jh=y({distinctId:c().optional(),sessionId:c().optional(),providerId:c(),modelId:c(),apiKey:c().optional(),baseUrl:c().url().optional(),headers:j(c(),c()).optional(),knownModels:j(c(),wo).optional(),providerConfig:W().optional(),initialMessages:x(ne()).optional(),systemPrompt:c(),tools:x(ne()),modelTools:x(ne()).optional(),maxIterations:b().positive().optional(),maxParallelToolCalls:b().int().positive().default(8),maxTokensPerTurn:b().positive().optional(),maxToolResultChars:b().int().positive().optional(),temperature:b().nonnegative().optional(),apiTimeoutMs:b().positive().default(180000),userFileContentLoader:ht().input([c()]).output(Vt(c())).optional(),toolContextMetadata:j(c(),W()).optional(),execution:y({maxConsecutiveMistakes:b().int().positive().optional(),reminderAfterIterations:b().nonnegative().optional(),reminderText:c().optional(),loopDetection:se([U(!1),y({softThreshold:b().int().positive().optional(),hardThreshold:b().int().positive().optional()})]).optional(),reasoningLoopDetection:se([U(!1),y({minChars:b().int().positive().optional(),window:b().int().positive().optional(),lineCycleWindow:b().int().positive().optional(),maxPeriod:b().int().positive().optional(),minCycles:b().int().positive().optional(),maxUniqueInWindow:b().int().positive().optional(),minLineChars:b().int().positive().optional(),phraseMaxPeriod:b().int().positive().optional(),phraseMinCycles:b().int().positive().optional(),blockMinPeriod:b().int().positive().optional(),blockMaxPeriod:b().int().nonnegative().optional(),blockMinCycles:b().int().positive().optional(),blockMinChars:b().int().nonnegative().optional(),maxConsecutiveTrips:b().int().positive().optional()})]).optional(),reasoningRepetition:se([U(!1),y({minChars:b().int().positive().optional(),minParagraphChars:b().int().positive().optional(),minStopwords:b().int().nonnegative().optional(),maxRepeatTrip:b().int().positive().optional(),duplicateFractionTrip:b().min(0).max(1).optional(),cooldownTurns:b().int().nonnegative().optional(),maxNudges:b().int().nonnegative().optional(),recoveryTokens:b().int().nonnegative().optional()})]).optional()}).optional(),reasoningEffort:ep.optional(),thinkingBudgetTokens:b().positive().optional(),thinking:S().optional(),onEvent:ht().input([ne()]).output(xd()).optional(),hooks:ne().optional(),parentAgentId:c().optional(),extensions:x(ne()).optional(),hookErrorMode:I(["ignore","throw"]).default("ignore"),toolPolicies:j(c(),y({enabled:S().optional(),autoApprove:S().optional()})).optional(),unavailableToolReasons:j(c(),c()).optional(),requestToolApproval:ht().input([y({sessionId:c(),agentId:c(),conversationId:c(),iteration:b(),toolCallId:c(),toolName:c(),input:W(),policy:y({enabled:S().optional(),autoApprove:S().optional()}).default({})})]).output(se([y({approved:S(),reason:c().optional()}),Vt(y({approved:S(),reason:c().optional()}))])).optional(),onConsecutiveMistakeLimitReached:ht().input([y({iteration:b().int().positive(),consecutiveMistakes:b().int().positive(),maxConsecutiveMistakes:b().int().positive(),reason:I(["api_error","invalid_tool_call","tool_execution_failed"]),details:c().optional()})]).output(se([y({action:U("continue"),guidance:c().optional()}),y({action:U("stop"),reason:c().optional()}),Vt(se([y({action:U("continue"),guidance:c().optional()}),y({action:U("stop"),reason:c().optional()})]))])).optional(),logger:ne().optional(),extensionContext:ne().optional(),abortSignal:ne().optional()}),mp=I(["connector.started","connector.stopping","session.authorize","message.received","message.denied","message.completed","message.failed","session.started","session.reused","session.reset","schedule.delivery.started","schedule.delivery.sent","schedule.delivery.failed"]),gp=y({id:c().optional(),label:c().optional(),role:c().optional(),participantKey:c().optional(),participantLabel:c().optional(),platformUserId:c().optional(),metadata:j(c(),W()).optional()}),yp=y({source:c(),sourceEvent:c(),threadId:c(),channelId:c(),isDM:S(),sessionId:c().optional(),workspaceRoot:c().optional(),metadata:j(c(),W()).optional()}),Yh=y({actor:gp,context:yp,payload:j(c(),W()).optional()}),Xh=y({action:I(["allow","deny"]).default("allow"),message:c().optional(),reason:c().optional(),metadata:j(c(),W()).optional()}),Qh=y({adapter:c(),botUserName:c().optional(),event:mp,payload:j(c(),W()),ts:c()});var vp=["hooks","tools","commands","rules","skills","messageBuilders","providers","automationEvents","mcp"],em=new Set(vp);var Ze={CLINE_PASS:"ext-cline-pass",CODE_CLOUD_AGENTS:"code-cloud-agents",CODE_ONBOARDING_GITHUB:"code-onboarding-github",CLINE_COMPOSIO_BETA:"CLINE_COMPOSIO_BETA"},tm={[Ze.CLINE_PASS]:!1,[Ze.CODE_CLOUD_AGENTS]:!1,[Ze.CODE_ONBOARDING_GITHUB]:!1,[Ze.CLINE_COMPOSIO_BETA]:!1},nm=Object.values(Ze),bp=I(["agent_start","agent_resume","agent_abort","agent_end","agent_error","tool_call","tool_result","prompt_submit","pre_compact","session_shutdown"]),ke=j(c(),c()),Tp=y({toolName:c(),parameters:ke}),wp=y({toolName:c(),parameters:ke,result:c(),success:S(),executionTimeMs:b()}),_p=y({prompt:c(),attachments:x(c())}),kp=y({taskMetadata:ke}),Ep=y({taskMetadata:ke,previousState:ke}),Ap=y({taskMetadata:ke}),xp=y({taskMetadata:ke}),Ip=y({taskId:c(),ulid:c(),contextSize:b(),compactionStrategy:c(),previousApiReqIndex:b(),tokensIn:b(),tokensOut:b(),tokensInCache:b(),tokensOutCache:b(),deletedRangeStart:b(),deletedRangeEnd:b(),contextJsonPath:c(),contextRawPath:c()}),rm=y({clineVersion:c(),hookName:bp,timestamp:c(),taskId:c(),sessionContext:y({rootSessionId:c().optional(),hookLogPath:c().optional()}).optional(),workspaceRoots:x(c()),workspaceInfo:ne().optional(),userId:c(),agent_id:c(),parent_agent_id:c().nullable(),iteration:b().optional(),reason:c().optional(),tool_call:y({id:c(),name:c(),input:W()}).optional(),tool_result:ne().optional(),turn:W().optional(),error:y({name:c(),message:c(),stack:c().optional()}).optional(),preToolUse:Tp.optional(),postToolUse:wp.optional(),userPromptSubmit:_p.optional(),taskStart:kp.optional(),taskResume:Ep.optional(),taskCancel:Ap.optional(),taskComplete:xp.optional(),preCompact:Ip.optional()}).passthrough();var Cp=["readFile","search","bash","webFetch","editor","applyPatch","skills","askQuestion","submit"],im=new Set(Cp);var Ur="<tool_call>",Sp=/<tool_call>|<parameter=[^>]*>|<\/parameter>/g,Rp=/<function=[^\s>]+\s*>/,In="[SYSTEM] Your last message contained no tool calls, so the run was about to end. If the task is not finished, continue now by emitting the tool calls it needs - do not describe what you are going to do without doing it. If the task really is finished, say so in one short sentence. If it stopped at a limit, a refusal or anything else only the user can change, and you have told the user so, that is finished too: say so in one short sentence and do not look for a way around it.",ko=" If what you need is a decision from the user, call `ask_question` - that is the only way to reach them. A question written as ordinary text is not a question anyone will see: it reads here as a turn that called nothing, which is what produced this message.",Op="[SYSTEM] You have now taken ";function Eo(e,t){let n=Math.round(t/1000),r=n>=1?`about ${n.toLocaleString("en-US")},000 characters of reasoning`:"a full turn of reasoning";return Op+`${e} turns in a row without calling a single tool, spending ${r} on them. Thinking further has not moved this task, and it will not: you have already reasoned past the point where more of it helps. Stop analysing and make one tool call now - the smallest one that makes any progress at all, even if you are not certain it is the right one, because a call you can check beats an analysis you cannot. If you genuinely cannot make one, say what is blocking you in a single sentence and stop.`}var Np="[SYSTEM] Your last message contained a tool call that could not be read.",Mp="<|tool_call>",Fr="<tool_call|>",Se='<|"|>',Pp=/<\|tool_call>\s*call:([A-Za-z_][\w.-]*)\s*\{/g;function Ao(e){return`(A call to ${e.name?`\`${e.name}\``:"a tool"} was written here but could not be read, so nothing ran. Its text is not kept.)`}function Gt(e){return JSON.stringify(e.replace(/\s+/g," ").trim())}function $p(e){let t=[];for(let i=e.indexOf(Se);i!==-1;i=e.indexOf(Se,i+Se.length))t.push(i);let n=(i)=>/([A-Za-z_]\w*)\s*:\s*$/.exec(e.slice(Math.max(0,i-80),i))?.[1],r=()=>{let i=/([A-Za-z_]\w*)\s*:\s*(?!<\|"\|>)([^,{}[\]<]{1,60})<\|"\|>/.exec(e);return i?`The value of \`${i[1]}\` (${Gt(i[2])}) closes a string it never opened.`:void 0};for(let i=0;i+1<t.length;i+=2){let o=t[i],s=t[i+1],a=n(o),l=e.slice(o+Se.length,s),u=/([^\s,]{0,12})\s*,\s*([A-Za-z_]\w*)\s*:\s*$/.exec(l);if(u&&a){let p=u[1],f=p?`you wrote ${Gt(p.slice(-8))} where its closing delimiter belongs`:"its closing delimiter is missing";return`The string for \`${a}\` was never closed: ${f}, just before \`${u[2]}\`. A string argument ends with the same delimiter that opened it and with nothing else - not a backtick, not a quote, not a tag.`}let d=e.slice(s+Se.length),h=/^\s*(\S)/.exec(d)?.[1];if(h&&!",}]".includes(h)){let p=/^\s*([A-Za-z_]\w*)\s*:/.exec(d)?.[1];if(!p){let f=r();if(f)return f}return p&&a?`There is no comma between \`${a}\` and \`${p}\`. Every argument is separated from the next by a comma.`:`After the string for \`${a??"an argument"}\` closes, the call continues with ${Gt(d.slice(0,24))} where a comma or the end of the call belongs.`}}if(t.length%2===1)return`The string for \`${n(t[t.length-1])??"the last argument"}\` was opened and never closed.`;return r()}function Lp(e){let t=[...e.matchAll(Pp)];if(t.length===0)return;let n=t[t.length-1]?.[1],r=0;for(let l=1;l<t.length;l+=1){let u=e.slice(t[l-1].index??0,t[l].index??0);if((u.split(Se).length-1)%2===1||!u.includes(Fr))r+=1}let i=t[t.length-1],o=(i.index??0)+i[0].length,s=e.indexOf(Fr,o),a=r>0?void 0:$p(e.slice(o,s===-1?void 0:s));return{blocks:t.length,restarts:r,dialect:"gemma",...n?{name:n}:{},...a?{defect:a}:{}}}function Ue(e){if(!e)return;if(e.includes(Mp)){let l=Lp(e);if(l)return l}if(!e.includes(Ur)||!Rp.test(e))return;let t=0,n=0,r=0;for(let l of e.matchAll(Sp)){let u=l[0];if(u===Ur)t+=1;else if(u==="</parameter>")r+=1;else n+=1}if(t===0)return;let i=Math.max(n-r,0),o=Math.min(Math.max(t-1,0),i),s=[...e.matchAll(/<function=([^\s>]+)\s*>/g)],a=s[s.length-1]?.[1];return{blocks:t,restarts:o,dialect:"qwen",...a?{name:a}:{}}}function Cn(e){let t=e.name?`\`${e.name}\``:"a tool",n=e.dialect==="gemma",r=n?"string argument":"parameter",i=e.restarts>0?` You began ${t} and then, part-way through a ${r} you never closed, started the whole call again${e.restarts>1?`, ${e.restarts} times over`:""}. The reader cannot tell an abandoned call from the value of the ${r} it was abandoned inside, so all of it came back as text.`:e.defect?` It named ${t}. ${e.defect}`:` It named ${t}, but the block was not well formed and could not be read.`,o=n?" Write the call again, once: every string argument opens and closes with the same string delimiter, arguments are separated by commas, and the call is closed after the last one.":" Emit the call once, in one clean block: open it, give each parameter and close each parameter, then close the function and the call.";return Np+i+" Nothing ran, so nothing has changed on disk. The call is not in this conversation any more, so do not look for it or copy it: write it fresh."+o+" Do not restart a call once you have begun it - finish it, or send nothing and start the next turn fresh."}var zp="[SYSTEM] You wrote ";function xo(e){let t=e.trim().replace(/\s+/g," ").slice(0,200);return zp+`"${t}" and then called nothing. Saying what you are about to do is not doing it, and the run ends on the next silent turn with the work undone. Emit the tool call itself now - the first one, not a description of it. If you cannot, say plainly what is stopping you in one sentence.`}var Io=/\b(?:let me|i'?ll|i will|i'?m going to|i am going to|now i(?:'?ll| will)|next,? i(?:'?ll| will)|let['’]s)\b/i,Co=/\b(?:task (?:is )?(?:complete|finished|done)|all done|is now (?:complete|finished|fixed|working)|i(?:'?m| am) (?:done|finished)|nothing (?:else|more) to do|no further changes)\b/i;function Pt(e){let t=e?.trim();if(!t||Co.test(t))return;let n=t.slice(-400);return Io.test(n)?t:void 0}var Dp=300;function So(e){let t=e?.trim();return!!t&&t.length<=Dp&&!/\n\s*\n/.test(t)&&!t.endsWith("?")&&Pt(t)===void 0}var Up=/(?:^done\b|^i(?:'ve| have) (?:now |fully |successfully )?(?:completed|finished)\b|\b(?:is|are|was|were|has been|have been) (?:now |all |fully |successfully )?(?:complete|completed|finished|done)\b)/i;function Ro(e){return e.slice(-300).includes("?")||Io.test(e.slice(-400))}function Oo(e){let t=e?.trim();if(!t)return!1;let n=t.replace(/[*_`]/g,"");return(Co.test(n)||Up.test(n))&&!Ro(t)}function No(e){let t=e?.trim();return!!t&&!Ro(t)}var Fp=I(["image","audio","video","file"]),jp=An("type",[y({type:U("base64"),data:c().min(1)}),y({type:U("url"),url:c().url().refine((e)=>{let t=new URL(e).protocol;return t==="http:"||t==="https:"},"Generated media URLs must use HTTP or HTTPS")}),y({type:U("artifact"),artifactId:c().min(1)})]);function Bp(e){if(e.startsWith("image/"))return"image";if(e.startsWith("audio/"))return"audio";if(e.startsWith("video/"))return"video";return"file"}var om=y({id:c().min(1),modality:Fp,mediaType:c().min(1),source:jp,name:c().min(1).optional(),sizeBytes:b().int().nonnegative().optional()}).refine((e)=>Bp(e.mediaType)===e.modality,{message:"Generated media modality must match its media type",path:["modality"]});function jr(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function Sn(e,t){if(!e&&!t)return;let n=e?.metadata,r=t?.metadata,i={...e??{},...t??{}};if(jr(n)&&jr(r))i.metadata={...n,...r};return i}var qp=3;var Br=Symbol.for("cline.shared.tokenCalibration");function Hp(e,t){if(e===void 0||t===void 0)return!0;return e===t}function Mo(){let e=globalThis,t=e[Br];if(t)return t;let n={};return e[Br]=n,n}function Wp(){return Mo().charsPerToken??qp}function Rn(e){let t=Mo();return Hp(t.outputCapOwner,e)?t.outputCap:void 0}function Po(e){return Math.max(1,Math.ceil(e/Wp()))}function Re(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function Zp(e){let t=e.type;if(typeof t==="string")return[t];return Array.isArray(t)?t.filter((n)=>typeof n==="string"):[]}function ln(e,t){if(Zp(e).includes(t))return!0;for(let n of["anyOf","oneOf","allOf"]){let r=e[n];if(Array.isArray(r)&&r.some((i)=>Re(i)&&ln(i,t)))return!0}return!1}function Vp(e,t){if(typeof e!=="string")return e;let n=e.trim(),r=ln(t,"array"),i=ln(t,"object");if((!r||!n.startsWith("["))&&(!i||!n.startsWith("{")))return e;try{let o=JSON.parse(n);if(Array.isArray(o))return r?o:e;if(Re(o))return i?o:e;return e}catch{return e}}function ze(e,t){let n=Vp(e,t);if(Array.isArray(n)){let s=t.items;if(!Re(s))return n;let a=!1,l=n.map((u)=>{let d=ze(u,s);return a||=d!==u,d});return a?l:n}if(!Re(n))return n;let r=t.properties;if(!Re(r))return n;let i=!1,o={...n};for(let[s,a]of Object.entries(r)){if(!(s in n)||!Re(a))continue;let l=ze(n[s],a);if(l!==n[s])o[s]=l,i=!0}return i?o:n}function $o(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}function K(e){let t=e?.trim();return t?t:void 0}var Gp=String.raw`\x60|"|'|<\/[A-Za-z][\w-]*>`,Kp=String.raw`\s*,\s*[A-Za-z_]\w*\s*:\s*(?:\x60[^\x60\n]*\x60|"[^"\n]*"|'[^'\n]*'|-?\d+(?:\.\d+)?|true|false|null)`,sm=new RegExp(String.raw`(${Gp})((?:${Kp})+)[ \t]*\}?[ \t]*$`);function Jp(e){return Lc(e)}var am=new RegExp(`${"⁣⟦"}([^${"⟧"}]*)${"⟧"}([\\s\\S]*?)${"⟦/⟧⁣"}`,"g");var Lo=`# Plan Mode
65
58
 
66
59
  You are in Plan mode. Your role is to explore, analyze, and plan -- not to execute.
67
60
 
@@ -72,36 +65,36 @@ You are in Plan mode. Your role is to explore, analyze, and plan -- not to execu
72
65
  - Do NOT edit files, write code, run destructive commands, or make any changes
73
66
  - Do NOT implement anything -- focus on understanding and alignment first
74
67
 
75
- The run_commands tool remains available in plan mode strictly for read-only inspection -- listing files, reading configs, inspecting git history and diffs, checking tool versions, and the like. Searching is not among them: search_codebase and grep are tools of their own and neither goes through the shell. Never use it to change anything: no creating, modifying, or deleting files, no writing scripts that make changes, and no state-changing commands (installs, migrations, database or schema changes, container commands that mutate state, etc.). File-editing commands (rm/mv/cp, in-place edits like sed -i, output redirection to files outside /tmp, git commands that change the working tree, package installs) are hard-blocked in plan mode: they are not executed and return a tool error instead, so do not attempt them. The sed tool is blocked the same way when in_place is true, and for the same reason; without it the tool only prints what the script would produce, which is read-only and allowed. If the task requires a mutation, put it in the plan; it happens only after the user switches to act mode.`,sh=`${wr}
68
+ The run_commands tool remains available in plan mode strictly for read-only inspection -- listing files, reading configs, inspecting git history and diffs, checking tool versions, and the like. Searching is not among them: search_codebase and grep are tools of their own and neither goes through the shell. Never use it to change anything: no creating, modifying, or deleting files, no writing scripts that make changes, and no state-changing commands (installs, migrations, database or schema changes, container commands that mutate state, etc.). File-editing commands (rm/mv/cp, in-place edits like sed -i, output redirection to files outside /tmp, git commands that change the working tree, package installs) are hard-blocked in plan mode: they are not executed and return a tool error instead, so do not attempt them. The sed tool is blocked the same way when in_place is true, and for the same reason; without it the tool only prints what the script would produce, which is read-only and allowed. If the task requires a mutation, put it in the plan; it happens only after the user switches to act mode.`,lm=`${Lo}
76
69
 
77
- Once the user has reviewed your plan and explicitly approved it in a follow-up message, use the switch_to_act_mode tool to switch to act mode and begin implementation. Calling switch_to_act_mode immediately starts execution, so never call it in the same turn you present a plan and never treat the original task request as approval -- end your turn after presenting the plan and wait for the user's response.`,ah=`${wr}
70
+ Once the user has reviewed your plan and explicitly approved it in a follow-up message, use the switch_to_act_mode tool to switch to act mode and begin implementation. Calling switch_to_act_mode immediately starts execution, so never call it in the same turn you present a plan and never treat the original task request as approval -- end your turn after presenting the plan and wait for the user's response.`,um=`${Lo}
78
71
 
79
- Once you have presented your plan, end your turn and wait for the user's response. You do NOT have the ability to switch to act mode yourself -- the user must do it manually with the Plan/Act toggle once they are satisfied with the plan. If the task requires tools that are only available in act mode, ask the user to "toggle to Act mode" (use those words).`;var Gc=f({id:l(),temperature:g().optional(),maxTokens:g().optional(),contextWindow:g().optional(),inputPrice:g().optional(),outputPrice:g().optional(),supportsImages:I().optional()}),Kc=f({models:k(Gc).optional(),openAiBaseUrl:l().optional(),openAiHeaders:U(l(),l()).optional(),azureApiVersion:l().optional(),azureIdentity:I().optional()}),Jc=f({id:l(),thinkingBudgetTokens:g().optional()}),Yc=f({name:l(),baseModelId:l(),thinkingBudgetTokens:g().optional()}),Xc=f({models:k(Jc).optional(),customModels:k(Yc).optional(),awsRegion:l().optional(),awsUseCrossRegionInference:I().optional(),awsUseGlobalInference:I().optional(),awsBedrockUsePromptCache:I().optional(),awsBedrockEndpoint:l().optional()}),Qc=f({id:l()}),ed=f({models:k(Qc).optional()}),td=f({id:l(),thinkingBudgetTokens:g().optional()}),nd=f({models:k(td).optional(),vertexProjectId:l().optional(),vertexRegion:l().optional()}),id=f({id:l(),thinkingBudgetTokens:g().optional(),promptCachingEnabled:I().optional()}),rd=f({models:k(id).optional(),baseUrl:l().optional()}),od=f({id:l(),thinkingBudgetTokens:g().optional()}),sd=f({models:k(od).optional(),baseUrl:l().optional()}),ad=f({OpenAiCompatible:Kc.optional(),AwsBedrock:Xc.optional(),Cline:ed.optional(),Vertex:nd.optional(),LiteLLM:rd.optional(),Anthropic:sd.optional()}),ld=f({id:l()}),ud=f({name:l(),url:l(),alwaysEnabled:I().optional(),headers:U(l(),l()).optional()}),Kn=f({alwaysEnabled:I(),name:l(),contents:l()}),It=f({bucket:l(),accessKeyId:l(),secretAccessKey:l(),region:l().optional(),endpoint:l().optional(),accountId:l().optional()}),cd=f({enabled:I().optional(),type:ee([z("s3_access_keys"),z("r2_access_keys"),z("azure_access_keys")]).optional(),s3AccessSettings:It.optional(),r2AccessSettings:It.optional(),azureAccessSettings:It.optional()}),dd=f({promptUploading:cd.optional()}),lh=f({version:l(),providerSettings:ad.optional(),telemetryEnabled:I().optional(),kanbanEnabled:I().optional(),mcpMarketplaceEnabled:I().optional(),allowedMCPServers:k(ld).optional(),remoteMCPServers:k(ud).optional(),blockPersonalRemoteMCPServers:I().optional(),yoloModeAllowed:I().optional(),openTelemetryEnabled:I().optional(),openTelemetryMetricsExporter:l().optional(),openTelemetryLogsExporter:l().optional(),openTelemetryOtlpProtocol:l().optional(),openTelemetryOtlpEndpoint:l().optional(),openTelemetryOtlpHeaders:U(l(),l()).optional(),openTelemetryOtlpMetricsProtocol:l().optional(),openTelemetryOtlpMetricsEndpoint:l().optional(),openTelemetryOtlpMetricsHeaders:U(l(),l()).optional(),openTelemetryOtlpLogsProtocol:l().optional(),openTelemetryOtlpLogsEndpoint:l().optional(),openTelemetryOtlpLogsHeaders:U(l(),l()).optional(),openTelemetryMetricExportInterval:g().optional(),openTelemetryOtlpInsecure:I().optional(),openTelemetryLogBatchSize:g().optional(),openTelemetryLogBatchTimeout:g().optional(),openTelemetryLogMaxQueueSize:g().optional(),enterpriseTelemetry:dd.optional(),globalRules:k(Kn).optional(),globalWorkflows:k(Kn).optional()}),uh=U(l(),l());var ch=E(["reasoning","prompt-cache","tools","provider-tools","oauth","temperature","files","streaming","vision","computer-use","local-auth","popular"]),dh=E(["anthropic","gemini","openai-chat","openai-responses","openai-r1","ai-sdk"]),ph=E(["anthropic","ai-sdk","ai-sdk-community","openai","openai-compatible","openai-r1","gemini","bedrock","custom","fetch","vertex"]);var _r="task.provider_request_started",kr="task.provider_stream_started",Er="task.first_chunk_received",Ir="task.provider_stream_failed",Ar="task.cancelled";var Te=new Map;function pd(e,t){let n=typeof t.error_message==="string"?t.error_message:"";return[e,t.component,t.operation,t.error_type,t.error_code??"",t.error_status??"",n.replace(/\d+/g,"#").replace(/\s+/g," ").trim().toLowerCase().slice(0,256)].join("\x00")}function hd(e){let t=Date.now(),n=Te.get(e);if(n&&t-n.startMs<3600000){if(n.emitted<5)return n.emitted+=1,{emit:!0,suppressed:0};return n.suppressed+=1,{emit:!1,suppressed:n.suppressed}}let i=n?.suppressed??0;if(Te.delete(e),Te.size>=512){let r=Te.keys().next();if(!r.done)Te.delete(r.value)}return Te.set(e,{startMs:t,emitted:1,suppressed:0}),{emit:!0,suppressed:i}}function xr(e,t){e?.capture({event:"agent.reasoning.unexpected_tokens",properties:Ht({sessionId:t.sessionId,agentId:t.agentId,runId:t.runId,iteration:t.iteration,providerId:t.providerId,modelId:t.modelId,requestedThinking:t.requestedThinking,reasoningTokenCount:t.reasoningTokenCount})})}function Cr(e,t){if(!e)return;e.capture({event:t.event,properties:Ht({sessionId:t.sessionId,ulid:t.ulid??t.sessionId,agentId:t.agentId,conversationId:t.conversationId,runId:t.runId,iteration:t.iteration,provider:t.providerId,providerId:t.providerId,model:t.modelId,modelId:t.modelId,phase:t.phase,durationMs:t.durationMs,eventType:t.eventType,...t.error===void 0?{}:Sr(t.error,t.messageLimit),error_class:t.errorClass})})}function Rr(e,t){if(!e)return!1;let n=t.event??"sdk.error",i=fd(t),r=0;try{let o=hd(pd(n,i));if(!o.emit)return!0;r=o.suppressed}catch{}return e.capture({event:n,properties:r>0?{...i,suppressed_count:r}:i}),!0}function fd(e){return Ht({...e.context??{},component:e.component,operation:e.operation,severity:e.severity??"error",handled:e.handled??!0,...Sr(e.error,e.messageLimit,e.errorMessage)})}function Ht(e){let t={};for(let[n,i]of Object.entries(e))if(i!==void 0)t[n]=i;return t}function Sr(e,t=500,n){let i=yd(e)?e:void 0,r=e instanceof Error?e:void 0,o=Le(n)??Le(r?.message)??Le(i?.message)??vd(e)??"Unknown error",s=bd(i?.code),a=At(i?.status)??At(i?.statusCode)??At(i?.responseStatus);return{error_type:r?.name?.trim()||Le(i?.name)||r?.constructor?.name||"Error",error_message:gd(md(o),t),...s!==void 0?{error_code:s}:{},...a!==void 0?{error_status:a}:{}}}function md(e){return e.replace(/(authorization=Bearer\s+)[^&\s]+/gi,"$1[redacted]").replace(/(api[_-]?key|access[_-]?token|refresh[_-]?token|authorization|password|secret)=([^&\s]+)/gi,"$1=[redacted]").replace(/(Bearer\s+)[A-Za-z0-9._~+/-]+=*/gi,"$1[redacted]").replace(/\/Users\/[^/\s]+/g,"/Users/[redacted]").replace(/\/home\/[^/\s]+/g,"/home/[redacted]").replace(/([A-Za-z]:[\\/]+Users[\\/]+)[^\\/\s]+/g,"$1[redacted]")}function gd(e,t){let n=Math.max(1,Math.floor(t));return e.length>n?e.substring(0,n):e}function yd(e){return typeof e==="object"&&e!==null}function Le(e){return typeof e==="string"&&e.trim().length>0?e:void 0}function vd(e){if(e instanceof Error)return;let t=typeof e==="string"?e:String(e);return t==="[object Object]"?void 0:Le(t)}function bd(e){if(typeof e==="string"&&e.trim().length>0)return e;if(typeof e==="number"&&Number.isFinite(e))return e;return}function At(e){return typeof e==="number"&&Number.isFinite(e)?e:void 0}var Td=["rules","skills","workflows","plugins","hooks"];var hh=new Set(Td);var wd=f({rootPath:l().min(1),hint:l().min(1).optional(),associatedRemoteUrls:k(l().min(1)).optional(),latestGitCommitHash:l().min(1).optional(),latestGitBranchName:l().min(1).optional()}),fh=f({currentWorkspacePath:l().min(1).optional(),workspaces:U(l().min(1),wd)});var _d=["current_state","boundary_analysis","interface_proposal"];var te=rr((e)=>e instanceof Date?e.toISOString():e,l().datetime()),Ee=E(["pending","in_progress","blocked","completed"]),Nr=E(["queued","running","completed","failed","cancelled","interrupted"]),mt=E(["draft","in_review","finalized"]),kd=f({agentId:l(),role:E(["lead","teammate"]),description:l().optional(),status:E(["idle","running","stopped"])}),mh=f({agentId:l(),rolePrompt:l(),modelId:l().optional(),maxIterations:g().optional(),temperature:g().nonnegative().optional(),seed:g().int().optional(),seedRandom:I().optional(),temperatureBase:g().nonnegative().optional(),temperatureRange:g().min(0).max(100).optional()});function C(e){return rr((t)=>t===null?void 0:t,e.optional())}var gh=f({agentId:l().min(1).describe("Teammate identifier"),rolePrompt:l().min(1).describe("System prompt describing teammate role"),temperature:C(ee([g().nonnegative(),l()])).describe(`Sampling temperature for this teammate, over its model's own. "random": a draw within 2% of the model's own temperature (a model at 1.0 gets 0.98 to 1.02); that narrow band is the intended variation. Omit to keep the model's.`),seed:C(ee([g().int(),l()])).describe('Sampling seed for this teammate. "random" draws one. Omit to leave it unset.'),temperature_range:C(ee([g().min(0).max(100),l()])).describe("Percent the temperature is randomized by, around `temperature` or the model's own. Set it only when the user states a number; left out, 2 applies. Held to 10 at most.")}).strict(),yh=f({agentId:l().min(1).describe("Teammate identifier"),reason:C(l().min(1)).describe("Optional shutdown reason")}),vh=f({}),Or={create:["title","description"],list:[],claim:["taskId"],complete:["taskId","summary"],block:["taskId","reason"]};var bh=f({action:E(["create","list","claim","complete","block"]),title:C(l().min(1)).describe("Task title"),description:C(l().min(1)).describe("Task details"),dependsOn:C(k(l().describe("Dependency task ID"))).describe("Array of dependency task IDs"),assignee:C(l().min(1)).describe("Optional assignee"),status:C(E(["pending","in_progress","blocked","completed"])).describe("Optional task status filter"),taskId:C(l()).describe("Task ID"),summary:C(l().min(1)).describe("Completion summary"),reason:C(l().min(1)).describe("Blocking reason")}).superRefine((e,t)=>{for(let n of Or[e.action]){if(e[n]!==void 0)continue;t.addIssue({code:"custom",path:[n],message:`Field "${n}" is required when action=${e.action}`})}}),Th=f({action:E(["list","claim","complete","block"]),status:C(E(["pending","in_progress","blocked","completed"])).describe("Optional task status filter"),assignee:C(l().min(1)).describe("Optional assignee filter"),taskId:C(l()).describe("Task ID"),summary:C(l().min(1)).describe("Completion summary"),reason:C(l().min(1)).describe("Blocking reason")}).superRefine((e,t)=>{for(let n of Or[e.action]){if(e[n]!==void 0)continue;t.addIssue({code:"custom",path:[n],message:`Field "${n}" is required when action=${e.action}`})}}),wh=f({agentId:l().describe("Teammate agent ID"),task:l().min(1).describe("Task instructions for the teammate"),taskId:C(l()).describe("Optional shared task list ID"),runMode:C(E(["sync","async"])).describe("Execution mode: 'sync' blocks until the teammate finishes and returns the result (default if omitted); 'async' queues the run and returns a runId immediately — use team_await_runs to collect results later."),continueConversation:C(I()).describe("If true, continue the teammate conversation; otherwise start fresh")}),_h=f({status:C(E(["queued","running","completed","failed","cancelled","interrupted"])).describe("Optional run status filter. Omit to include all statuses."),agentId:C(l().min(1)).describe("Optional teammate ID filter. Omit to include all teammates."),includeCompleted:C(I()).describe("Include completed/failed runs (default true)")}),kh=f({runId:l().min(1).describe("Run ID"),reason:C(l().min(1)).describe("Optional cancellation reason")}),Eh=f({runId:C(l().min(1)).describe("Optional async run ID to await. Omit to wait for all active async runs.")}).strict(),Ih=f({toAgentId:l().min(1).describe("Recipient agent ID"),subject:l().min(1).describe("Message subject"),body:l().min(1).describe("Message body"),taskId:C(l().min(1)).describe("Optional task ID context")}),Ah=f({subject:l().min(1).describe("Message subject"),body:l().min(1).describe("Message body"),taskId:C(l().min(1)).describe("Optional task ID context")}),xh=f({unreadOnly:C(I()).describe("Only unread messages for read action (default true)")}),Ch=f({kind:E(["progress","handoff","blocked","decision","done","error"]),summary:l().min(1).describe("Update summary"),taskId:C(l().min(1)).describe("Optional task ID context"),evidence:C(k(l().min(1))).describe("Optional evidence links/snippets"),nextAction:C(l().min(1)).describe("Planned next step")}),Rh=f({}),Sh=f({title:l().describe("Outcome title"),requiredSections:k(l()).default(_d).describe("Required sections for finalization gate (defaults to current_state,boundary_analysis,interface_proposal)")}),Nh=f({outcomeId:l().describe("Outcome ID"),section:l().describe("Section name"),sourceRunId:C(l()).describe("Optional source run ID"),content:l().describe("Section fragment content")}),Oh=f({fragmentId:l().describe("Fragment ID"),approved:I().describe("Review decision")}),Mh=f({outcomeId:l().describe("Outcome ID")}),Ph=f({}),$h=f({teamId:l(),teamName:l(),members:k(kd),taskCounts:U(Ee,g()),unreadMessages:g(),missionLogEntries:g(),activeRuns:g(),queuedRuns:g(),outcomeCounts:U(mt,g())}),Ed=f({id:l(),title:l(),description:l(),status:Ee,createdAt:te,updatedAt:te,createdBy:l(),assignee:l().optional(),dependsOn:k(l()),summary:l().optional(),isReady:I(),blockedBy:k(l())}),Lh=Ut("action",[f({action:z("create"),taskId:l(),status:Ee,ignoredFields:k(l()).optional(),note:l().optional()}),f({action:z("list"),tasks:k(Ed)}),f({action:z("claim"),taskId:l(),status:Ee,nextStep:l()}),f({action:z("complete"),taskId:l(),status:Ee}),f({action:z("block"),taskId:l(),status:Ee})]),zh=f({agentId:l(),mode:E(["sync","async"]),status:E(["dispatched","running","queued","joined"]),dispatched:I(),message:l(),deduped:I().optional(),runId:l().optional(),text:l().optional(),iterations:g().optional(),maxIterations:g().optional(),finishReason:l().optional(),stopReason:z("iteration_cap").optional()}),Id=f({textPreview:l(),text:l().optional(),iterations:g(),finishReason:l(),durationMs:g(),usage:f({inputTokens:g(),outputTokens:g(),cacheReadTokens:g().optional(),cacheWriteTokens:g().optional(),totalCost:g().optional()})}),Dh=f({id:l(),agentId:l(),taskId:l().optional(),status:Nr,messagePreview:l(),priority:g(),retryCount:g(),maxRetries:g(),nextAttemptAt:te.optional(),continueConversation:I().optional(),startedAt:te,endedAt:te.optional(),leaseOwner:l().optional(),heartbeatAt:te.optional(),lastProgressAt:te.optional(),lastProgressMessage:l().optional(),currentActivity:l().optional(),error:l().optional(),resultSummary:Id.optional()}),Uh=f({id:l(),teamId:l(),fromAgentId:l(),toAgentId:l(),subject:l(),body:l(),taskId:l().optional(),sentAt:te,readAt:te.optional()}),Fh=f({id:l(),teamId:l(),title:l(),status:mt,requiredSections:k(l()),createdBy:l(),createdAt:te,finalizedAt:te.optional()}),Bh=f({outcomeId:l(),status:mt,requiredSections:k(l())}),jh=f({agentId:l(),status:l()}),qh=f({runId:l(),status:Nr}),Hh=f({id:l(),toAgentId:l()}),Wh=f({delivered:g()}),Vh=f({id:l()}),Zh=f({status:l()}),Gh=f({fragmentId:l(),status:l()}),Kh=f({outcomeId:l(),status:mt}),Ad;((e)=>{e.TaskStart="task_start",e.TaskEnd="task_end",e.AgentEvent="agent_event",e.TeammateSpawned="teammate_spawned",e.TeammateShutdown="teammate_shutdown",e.TeamTaskUpdated="team_task_updated",e.TeamMessage="team_message",e.TeamMissionLog="team_mission_log",e.TeamTaskCompleted="team_task_completed",e.RunStarted="run_started",e.RunQueued="run_queued",e.RunProgress="run_progress",e.RunCompleted="run_completed",e.RunFailed="run_failed",e.RunCancelled="run_cancelled",e.RunInterrupted="run_interrupted",e.OutcomeCreated="outcome_created",e.OutcomeFragmentAttached="outcome_fragment_attached",e.OutcomeFragmentReviewed="outcome_fragment_reviewed",e.OutcomeFinalized="outcome_finalized",e.TeamCleaned="team_cleaned"})(Ad||={});function xd(e){let{$schema:t,...n}=e;if(typeof n.type==="string")return n;if("properties"in n||"required"in n||"additionalProperties"in n)return{type:"object",...n};for(let i of["oneOf","anyOf","allOf"]){let r=n[i];if(!Array.isArray(r)||r.length===0)continue;if(i==="allOf"){if(r.some((o)=>o&&typeof o==="object"&&o.type==="object"))return{type:"object",...n};throw Error('Tool inputSchema must describe an object at the top level, but the schema has a top-level "allOf" with no branch that asserts type: "object". Add type: "object" to at least one allOf branch to make the object constraint explicit.')}if(r.every((o)=>o&&typeof o==="object"&&o.type==="object"))return{type:"object",...n};throw Error(`Tool inputSchema must describe an object at the top level, but the schema has a top-level "${i}" whose branches include non-object types. Pass the strict object schema as inputSchema and reserve union/coercion schemas for use inside execute().`)}return n}function Cd(e){let t=xd(e.inputSchema instanceof N?Zc(e.inputSchema):e.inputSchema);return{name:e.name,resultPolicy:e.resultPolicy,description:e.description,inputSchema:t,...e.source?{source:e.source}:{},...e.readOnly?{readOnly:!0}:{},lifecycle:e.lifecycle,executionMode:e.executionMode,timeoutMs:e.timeoutMs??30000,retryable:e.retryable??!0,maxRetries:e.maxRetries??3,execute:e.execute}}var Jh="Switch from plan mode to act mode. Switching to act mode immediately starts executing the plan, so only call this after the user has explicitly approved the plan in a message sent AFTER you presented it (e.g. 'looks good', 'go ahead', 'switch to act mode'). Never call this in the same turn you present a plan, never call it proactively, and never treat the original task request as approval. "+"Output: a one-line confirmation, as plain text. This call ends the current run and the next one starts in act mode with the file and command tools available, so it is a handover, not a failure — carry on with the plan there.";import{classifyProviderError as Jr,createGateway as Vd,isRetryableProviderError as Zd}from"@cerebriline/llms";import{nanoid as Gd}from"nanoid";function Wt(){return{reasoningDeltas:0,reasoningChars:0,textDeltas:0,textChars:0,toolInputChars:0}}var Rd=12;function Mr(e,t){let n=t.reduce((a,u)=>a+u,0);if(n<=0)return t.map(()=>0);let i=t.map((a)=>e*a/n),r=i.map(Math.floor),o=e-r.reduce((a,u)=>a+u,0),s=i.map((a,u)=>({index:u,rest:a-Math.floor(a)})).sort((a,u)=>u.rest-a.rest);for(let{index:a}of s){if(o<=0)break;r[a]=(r[a]??0)+1,o-=1}return r}function Pr(e){let t=Math.floor(e.outputTokens??0);if(!(t>0))return;let{tally:n}=e,i=e.providerReasoningTokens??0;if(i>0){let c=Math.min(t,Math.floor(i)),[d=0,y=0]=Mr(t-c,n.textChars+n.toolInputChars>0?[n.textChars,n.toolInputChars]:[1,0]);return{reasoningTokens:c,textTokens:d,toolInputTokens:y,method:"provider"}}let r=n.reasoningDeltas+n.textDeltas,o=n.reasoningChars+n.textChars;if(r>0&&r<=t&&o/r<=Rd)return{reasoningTokens:n.reasoningDeltas,textTokens:n.textDeltas,toolInputTokens:t-r,method:"stream-chunks"};let[s=0,a=0,u=0]=Mr(t,o+n.toolInputChars>0?[n.reasoningChars,n.textChars,n.toolInputChars]:[0,1,0]);return{reasoningTokens:s,textTokens:a,toolInputTokens:u,method:"chars-share"}}var gt={minChars:4000,window:60,lineCycleWindow:126,maxPeriod:6,minCycles:20,maxUniqueInWindow:4,minLineChars:2000,phraseMaxPeriod:120,phraseMinCycles:12,blockMinPeriod:7,blockMaxPeriod:400,blockMinCycles:3,blockMinChars:200,maxConsecutiveTrips:3};function Vt(e,t="reasoning"){let n=`after ${e.chars.toLocaleString()} characters${t==="reasoning"?" of reasoning":""}`,i=e.sample?` Repeating: ${JSON.stringify(e.sample)}`:"";switch(e.kind){case"low-uniqueness":return`The model's ${t} collapsed into ${e.distinct} distinct lines over ${n}.${i}`;case"line-cycle":case"block-cycle":return`The model's ${t} repeated a ${e.period}-line block ${e.cycles} times ${n}.${i}`;case"phrase-cycle":return`The model's ${t} repeated a ${e.period}-character phrase ${e.cycles} times ${n}.${i}`;case"restated-lines":return`The model's ${t} kept writing the same lines again: ${e.distinct} distinct lines, one of them ${e.cycles} times, ${n}.${i}`}}function Zt(e){let t=[],n=(i,r)=>{if(typeof i==="string"){if(i)t.push(i)}else if(r<6&&Array.isArray(i))for(let o of i)n(o,r+1);else if(r<6&&i!==null&&typeof i==="object")for(let o of Object.values(i))n(o,r+1)};for(let i of e){if(i.role==="assistant")continue;for(let r of i.content)if(r.type==="text")n(r.text,0);else if(r.type==="tool-result")n(r.output,0)}return t.join(`
80
- `)}var Sd=/^\d+\s*\|\s?/;function Ne(e){return e.trim().replace(Sd,"").trim()}class me{cfg;given;chars=0;lines=[];cycleLines=[];history=[];pending="";verdict=null;source;sourceRuns=new Map;recent=[];streaks=[];block;constructor(e={},t={}){this.cfg={...gt,...e},this.given=t.given}get tripped(){return this.verdict}push(e){if(this.verdict||!e)return this.verdict;this.chars+=e.length,this.pending+=e;let t;while((t=this.pending.indexOf(`
81
- `))!==-1){let i=this.pending.slice(0,t).trim();if(this.pending=this.pending.slice(t+1),i){if(this.lines.push(i),this.lines.length>this.cfg.window)this.lines.shift();if(this.cycleLines.push(i),this.cycleLines.length>this.cfg.lineCycleWindow)this.cycleLines.shift();if(this.given)this.history.push(i);this.trackBlocks(i)}}if(this.chars<this.cfg.minChars)return null;let n=this.detectLowUniqueness()??this.detectLineCycle()??this.detectBlockCycle()??this.detectPhraseCycle();if(n)this.verdict=n;return this.verdict}readSource(){if(!this.given)return;if(!this.source){let e="";try{e=this.given()}catch{}this.source={text:e,lines:e.split(`
82
- `).map(Ne).filter((t)=>t!=="")}}return this.source.text?this.source:void 0}remembered(e,t){let n=this.sourceRuns.get(e);if(n===void 0){if(n=t(),this.sourceRuns.size>512)this.sourceRuns.clear();this.sourceRuns.set(e,n)}return n}phraseRunInSource(e){let t=this.readSource();if(!t)return 0;return this.remembered(`p
83
- ${e}`,()=>{let n=0,i=t.text.indexOf(e);while(i!==-1){let r=1,o=i+e.length;while(t.text.startsWith(e,o))r++,o+=e.length;if(r>n)n=r;i=t.text.indexOf(e,o)}return n})}blockRunInSource(e){let t=this.readSource();if(!t)return 0;let n=e.map(Ne);return this.remembered(`b
72
+ Once you have presented your plan, end your turn and wait for the user's response. You do NOT have the ability to switch to act mode yourself -- the user must do it manually with the Plan/Act toggle once they are satisfied with the plan. If the task requires tools that are only available in act mode, ask the user to "toggle to Act mode" (use those words).`;var Yp=y({id:c(),temperature:b().optional(),maxTokens:b().optional(),contextWindow:b().optional(),inputPrice:b().optional(),outputPrice:b().optional(),supportsImages:S().optional()}),Xp=y({models:x(Yp).optional(),openAiBaseUrl:c().optional(),openAiHeaders:j(c(),c()).optional(),azureApiVersion:c().optional(),azureIdentity:S().optional()}),Qp=y({id:c(),thinkingBudgetTokens:b().optional()}),ef=y({name:c(),baseModelId:c(),thinkingBudgetTokens:b().optional()}),tf=y({models:x(Qp).optional(),customModels:x(ef).optional(),awsRegion:c().optional(),awsUseCrossRegionInference:S().optional(),awsUseGlobalInference:S().optional(),awsBedrockUsePromptCache:S().optional(),awsBedrockEndpoint:c().optional()}),nf=y({id:c()}),rf=y({models:x(nf).optional()}),of=y({id:c(),thinkingBudgetTokens:b().optional()}),sf=y({models:x(of).optional(),vertexProjectId:c().optional(),vertexRegion:c().optional()}),af=y({id:c(),thinkingBudgetTokens:b().optional(),promptCachingEnabled:S().optional()}),lf=y({models:x(af).optional(),baseUrl:c().optional()}),uf=y({id:c(),thinkingBudgetTokens:b().optional()}),cf=y({models:x(uf).optional(),baseUrl:c().optional()}),df=y({OpenAiCompatible:Xp.optional(),AwsBedrock:tf.optional(),Cline:rf.optional(),Vertex:sf.optional(),LiteLLM:lf.optional(),Anthropic:cf.optional()}),pf=y({id:c()}),ff=y({name:c(),url:c(),alwaysEnabled:S().optional(),headers:j(c(),c()).optional()}),qr=y({alwaysEnabled:S(),name:c(),contents:c()}),Kt=y({bucket:c(),accessKeyId:c(),secretAccessKey:c(),region:c().optional(),endpoint:c().optional(),accountId:c().optional()}),hf=y({enabled:S().optional(),type:se([U("s3_access_keys"),U("r2_access_keys"),U("azure_access_keys")]).optional(),s3AccessSettings:Kt.optional(),r2AccessSettings:Kt.optional(),azureAccessSettings:Kt.optional()}),mf=y({promptUploading:hf.optional()}),cm=y({version:c(),providerSettings:df.optional(),telemetryEnabled:S().optional(),kanbanEnabled:S().optional(),mcpMarketplaceEnabled:S().optional(),allowedMCPServers:x(pf).optional(),remoteMCPServers:x(ff).optional(),blockPersonalRemoteMCPServers:S().optional(),yoloModeAllowed:S().optional(),openTelemetryEnabled:S().optional(),openTelemetryMetricsExporter:c().optional(),openTelemetryLogsExporter:c().optional(),openTelemetryOtlpProtocol:c().optional(),openTelemetryOtlpEndpoint:c().optional(),openTelemetryOtlpHeaders:j(c(),c()).optional(),openTelemetryOtlpMetricsProtocol:c().optional(),openTelemetryOtlpMetricsEndpoint:c().optional(),openTelemetryOtlpMetricsHeaders:j(c(),c()).optional(),openTelemetryOtlpLogsProtocol:c().optional(),openTelemetryOtlpLogsEndpoint:c().optional(),openTelemetryOtlpLogsHeaders:j(c(),c()).optional(),openTelemetryMetricExportInterval:b().optional(),openTelemetryOtlpInsecure:S().optional(),openTelemetryLogBatchSize:b().optional(),openTelemetryLogBatchTimeout:b().optional(),openTelemetryLogMaxQueueSize:b().optional(),enterpriseTelemetry:mf.optional(),globalRules:x(qr).optional(),globalWorkflows:x(qr).optional()}),dm=j(c(),c());var pm=I(["reasoning","prompt-cache","tools","provider-tools","oauth","temperature","files","streaming","vision","computer-use","local-auth","popular"]),fm=I(["anthropic","gemini","openai-chat","openai-responses","openai-r1","ai-sdk"]),hm=I(["anthropic","ai-sdk","ai-sdk-community","openai","openai-compatible","openai-r1","gemini","bedrock","custom","fetch","vertex"]);var zo="task.provider_request_started",Do="task.provider_stream_started",Uo="task.first_chunk_received",Fo="task.provider_stream_failed",jo="task.cancelled";var Ce=new Map;function gf(e,t){let n=typeof t.error_message==="string"?t.error_message:"";return[e,t.component,t.operation,t.error_type,t.error_code??"",t.error_status??"",n.replace(/\d+/g,"#").replace(/\s+/g," ").trim().toLowerCase().slice(0,256)].join("\x00")}function yf(e){let t=Date.now(),n=Ce.get(e);if(n&&t-n.startMs<3600000){if(n.emitted<5)return n.emitted+=1,{emit:!0,suppressed:0};return n.suppressed+=1,{emit:!1,suppressed:n.suppressed}}let r=n?.suppressed??0;if(Ce.delete(e),Ce.size>=512){let i=Ce.keys().next();if(!i.done)Ce.delete(i.value)}return Ce.set(e,{startMs:t,emitted:1,suppressed:0}),{emit:!0,suppressed:r}}function Bo(e,t){e?.capture({event:"agent.reasoning.unexpected_tokens",properties:On({sessionId:t.sessionId,agentId:t.agentId,runId:t.runId,iteration:t.iteration,providerId:t.providerId,modelId:t.modelId,requestedThinking:t.requestedThinking,reasoningTokenCount:t.reasoningTokenCount})})}function qo(e,t){if(!e)return;e.capture({event:t.event,properties:On({sessionId:t.sessionId,ulid:t.ulid??t.sessionId,agentId:t.agentId,conversationId:t.conversationId,runId:t.runId,iteration:t.iteration,provider:t.providerId,providerId:t.providerId,model:t.modelId,modelId:t.modelId,phase:t.phase,durationMs:t.durationMs,eventType:t.eventType,...t.error===void 0?{}:Wo(t.error,t.messageLimit),error_class:t.errorClass})})}function Ho(e,t){if(!e)return!1;let n=t.event??"sdk.error",r=vf(t),i=0;try{let o=yf(gf(n,r));if(!o.emit)return!0;i=o.suppressed}catch{}return e.capture({event:n,properties:i>0?{...r,suppressed_count:i}:r}),!0}function vf(e){return On({...e.context??{},component:e.component,operation:e.operation,severity:e.severity??"error",handled:e.handled??!0,...Wo(e.error,e.messageLimit,e.errorMessage)})}function On(e){let t={};for(let[n,r]of Object.entries(e))if(r!==void 0)t[n]=r;return t}function Wo(e,t=500,n){let r=wf(e)?e:void 0,i=e instanceof Error?e:void 0,o=Ve(n)??Ve(i?.message)??Ve(r?.message)??_f(e)??"Unknown error",s=kf(r?.code),a=Jt(r?.status)??Jt(r?.statusCode)??Jt(r?.responseStatus);return{error_type:i?.name?.trim()||Ve(r?.name)||i?.constructor?.name||"Error",error_message:Tf(bf(o),t),...s!==void 0?{error_code:s}:{},...a!==void 0?{error_status:a}:{}}}function bf(e){return e.replace(/(authorization=Bearer\s+)[^&\s]+/gi,"$1[redacted]").replace(/(api[_-]?key|access[_-]?token|refresh[_-]?token|authorization|password|secret)=([^&\s]+)/gi,"$1=[redacted]").replace(/(Bearer\s+)[A-Za-z0-9._~+/-]+=*/gi,"$1[redacted]").replace(/\/Users\/[^/\s]+/g,"/Users/[redacted]").replace(/\/home\/[^/\s]+/g,"/home/[redacted]").replace(/([A-Za-z]:[\\/]+Users[\\/]+)[^\\/\s]+/g,"$1[redacted]")}function Tf(e,t){let n=Math.max(1,Math.floor(t));return e.length>n?e.substring(0,n):e}function wf(e){return typeof e==="object"&&e!==null}function Ve(e){return typeof e==="string"&&e.trim().length>0?e:void 0}function _f(e){if(e instanceof Error)return;let t=typeof e==="string"?e:String(e);return t==="[object Object]"?void 0:Ve(t)}function kf(e){if(typeof e==="string"&&e.trim().length>0)return e;if(typeof e==="number"&&Number.isFinite(e))return e;return}function Jt(e){return typeof e==="number"&&Number.isFinite(e)?e:void 0}var Ef=["rules","skills","workflows","plugins","hooks"];var mm=new Set(Ef);var Af=y({rootPath:c().min(1),hint:c().min(1).optional(),associatedRemoteUrls:x(c().min(1)).optional(),latestGitCommitHash:c().min(1).optional(),latestGitBranchName:c().min(1).optional()}),gm=y({currentWorkspacePath:c().min(1).optional(),workspaces:j(c().min(1),Af)});var xf=["current_state","boundary_analysis","interface_proposal"];var ae=bo((e)=>e instanceof Date?e.toISOString():e,c().datetime()),Oe=I(["pending","in_progress","blocked","completed"]),Zo=I(["queued","running","completed","failed","cancelled","interrupted"]),$t=I(["draft","in_review","finalized"]),If=y({agentId:c(),role:I(["lead","teammate"]),description:c().optional(),status:I(["idle","running","stopped"])}),ym=y({agentId:c(),rolePrompt:c(),modelId:c().optional(),maxIterations:b().optional(),temperature:b().nonnegative().optional(),seed:b().int().optional(),seedRandom:S().optional(),temperatureBase:b().nonnegative().optional(),temperatureRange:b().min(0).max(100).optional()});function R(e){return bo((t)=>t===null?void 0:t,e.optional())}var vm=y({agentId:c().min(1).describe("Teammate identifier"),rolePrompt:c().min(1).describe("System prompt describing teammate role"),temperature:R(se([b().nonnegative(),c()])).describe(`Sampling temperature for this teammate, over its model's own. "random": a draw within 2% of the model's own temperature (a model at 1.0 gets 0.98 to 1.02); that narrow band is the intended variation. Omit to keep the model's.`),seed:R(se([b().int(),c()])).describe('Sampling seed for this teammate. "random" draws one. Omit to leave it unset.'),temperature_range:R(se([b().min(0).max(100),c()])).describe("Percent the temperature is randomized by, around `temperature` or the model's own. Set it only when the user states a number; left out, 2 applies. Held to 10 at most.")}).strict(),bm=y({agentId:c().min(1).describe("Teammate identifier"),reason:R(c().min(1)).describe("Optional shutdown reason")}),Tm=y({}),Vo={create:["title","description"],list:[],claim:["taskId"],complete:["taskId","summary"],block:["taskId","reason"]};var wm=y({action:I(["create","list","claim","complete","block"]),title:R(c().min(1)).describe("Task title"),description:R(c().min(1)).describe("Task details"),dependsOn:R(x(c().describe("Dependency task ID"))).describe("Array of dependency task IDs"),assignee:R(c().min(1)).describe("Optional assignee"),status:R(I(["pending","in_progress","blocked","completed"])).describe("Optional task status filter"),taskId:R(c()).describe("Task ID"),summary:R(c().min(1)).describe("Completion summary"),reason:R(c().min(1)).describe("Blocking reason")}).superRefine((e,t)=>{for(let n of Vo[e.action]){if(e[n]!==void 0)continue;t.addIssue({code:"custom",path:[n],message:`Field "${n}" is required when action=${e.action}`})}}),_m=y({action:I(["list","claim","complete","block"]),status:R(I(["pending","in_progress","blocked","completed"])).describe("Optional task status filter"),assignee:R(c().min(1)).describe("Optional assignee filter"),taskId:R(c()).describe("Task ID"),summary:R(c().min(1)).describe("Completion summary"),reason:R(c().min(1)).describe("Blocking reason")}).superRefine((e,t)=>{for(let n of Vo[e.action]){if(e[n]!==void 0)continue;t.addIssue({code:"custom",path:[n],message:`Field "${n}" is required when action=${e.action}`})}}),km=y({agentId:c().describe("Teammate agent ID"),task:c().min(1).describe("Task instructions for the teammate"),taskId:R(c()).describe("Optional shared task list ID"),runMode:R(I(["sync","async"])).describe("Execution mode: 'sync' blocks until the teammate finishes and returns the result (default if omitted); 'async' queues the run and returns a runId immediately — use team_await_runs to collect results later."),continueConversation:R(S()).describe("If true, continue the teammate conversation; otherwise start fresh")}),Em=y({status:R(I(["queued","running","completed","failed","cancelled","interrupted"])).describe("Optional run status filter. Omit to include all statuses."),agentId:R(c().min(1)).describe("Optional teammate ID filter. Omit to include all teammates."),includeCompleted:R(S()).describe("Include completed/failed runs (default true)")}),Am=y({runId:c().min(1).describe("Run ID"),reason:R(c().min(1)).describe("Optional cancellation reason")}),xm=y({runId:R(c().min(1)).describe("Optional async run ID to await. Omit to wait for all active async runs.")}).strict(),Im=y({toAgentId:c().min(1).describe("Recipient agent ID"),subject:c().min(1).describe("Message subject"),body:c().min(1).describe("Message body"),taskId:R(c().min(1)).describe("Optional task ID context")}),Cm=y({subject:c().min(1).describe("Message subject"),body:c().min(1).describe("Message body"),taskId:R(c().min(1)).describe("Optional task ID context")}),Sm=y({unreadOnly:R(S()).describe("Only unread messages for read action (default true)")}),Rm=y({kind:I(["progress","handoff","blocked","decision","done","error"]),summary:c().min(1).describe("Update summary"),taskId:R(c().min(1)).describe("Optional task ID context"),evidence:R(x(c().min(1))).describe("Optional evidence links/snippets"),nextAction:R(c().min(1)).describe("Planned next step")}),Om=y({}),Nm=y({title:c().describe("Outcome title"),requiredSections:x(c()).default(xf).describe("Required sections for finalization gate (defaults to current_state,boundary_analysis,interface_proposal)")}),Mm=y({outcomeId:c().describe("Outcome ID"),section:c().describe("Section name"),sourceRunId:R(c()).describe("Optional source run ID"),content:c().describe("Section fragment content")}),Pm=y({fragmentId:c().describe("Fragment ID"),approved:S().describe("Review decision")}),$m=y({outcomeId:c().describe("Outcome ID")}),Lm=y({}),zm=y({teamId:c(),teamName:c(),members:x(If),taskCounts:j(Oe,b()),unreadMessages:b(),missionLogEntries:b(),activeRuns:b(),queuedRuns:b(),outcomeCounts:j($t,b())}),Cf=y({id:c(),title:c(),description:c(),status:Oe,createdAt:ae,updatedAt:ae,createdBy:c(),assignee:c().optional(),dependsOn:x(c()),summary:c().optional(),isReady:S(),blockedBy:x(c())}),Dm=An("action",[y({action:U("create"),taskId:c(),status:Oe,ignoredFields:x(c()).optional(),note:c().optional()}),y({action:U("list"),tasks:x(Cf)}),y({action:U("claim"),taskId:c(),status:Oe,nextStep:c()}),y({action:U("complete"),taskId:c(),status:Oe}),y({action:U("block"),taskId:c(),status:Oe})]),Um=y({agentId:c(),mode:I(["sync","async"]),status:I(["dispatched","running","queued","joined"]),dispatched:S(),message:c(),deduped:S().optional(),runId:c().optional(),text:c().optional(),iterations:b().optional(),maxIterations:b().optional(),finishReason:c().optional(),stopReason:U("iteration_cap").optional()}),Sf=y({textPreview:c(),text:c().optional(),iterations:b(),finishReason:c(),durationMs:b(),usage:y({inputTokens:b(),outputTokens:b(),cacheReadTokens:b().optional(),cacheWriteTokens:b().optional(),totalCost:b().optional()})}),Fm=y({id:c(),agentId:c(),taskId:c().optional(),status:Zo,messagePreview:c(),priority:b(),retryCount:b(),maxRetries:b(),nextAttemptAt:ae.optional(),continueConversation:S().optional(),startedAt:ae,endedAt:ae.optional(),leaseOwner:c().optional(),heartbeatAt:ae.optional(),lastProgressAt:ae.optional(),lastProgressMessage:c().optional(),currentActivity:c().optional(),error:c().optional(),resultSummary:Sf.optional()}),jm=y({id:c(),teamId:c(),fromAgentId:c(),toAgentId:c(),subject:c(),body:c(),taskId:c().optional(),sentAt:ae,readAt:ae.optional()}),Bm=y({id:c(),teamId:c(),title:c(),status:$t,requiredSections:x(c()),createdBy:c(),createdAt:ae,finalizedAt:ae.optional()}),qm=y({outcomeId:c(),status:$t,requiredSections:x(c())}),Hm=y({agentId:c(),status:c()}),Wm=y({runId:c(),status:Zo}),Zm=y({id:c(),toAgentId:c()}),Vm=y({delivered:b()}),Gm=y({id:c()}),Km=y({status:c()}),Jm=y({fragmentId:c(),status:c()}),Ym=y({outcomeId:c(),status:$t}),Rf;((e)=>{e.TaskStart="task_start",e.TaskEnd="task_end",e.AgentEvent="agent_event",e.TeammateSpawned="teammate_spawned",e.TeammateShutdown="teammate_shutdown",e.TeamTaskUpdated="team_task_updated",e.TeamMessage="team_message",e.TeamMissionLog="team_mission_log",e.TeamTaskCompleted="team_task_completed",e.RunStarted="run_started",e.RunQueued="run_queued",e.RunProgress="run_progress",e.RunCompleted="run_completed",e.RunFailed="run_failed",e.RunCancelled="run_cancelled",e.RunInterrupted="run_interrupted",e.OutcomeCreated="outcome_created",e.OutcomeFragmentAttached="outcome_fragment_attached",e.OutcomeFragmentReviewed="outcome_fragment_reviewed",e.OutcomeFinalized="outcome_finalized",e.TeamCleaned="team_cleaned"})(Rf||={});function Of(e){let{$schema:t,...n}=e;if(typeof n.type==="string")return n;if("properties"in n||"required"in n||"additionalProperties"in n)return{type:"object",...n};for(let r of["oneOf","anyOf","allOf"]){let i=n[r];if(!Array.isArray(i)||i.length===0)continue;if(r==="allOf"){if(i.some((o)=>o&&typeof o==="object"&&o.type==="object"))return{type:"object",...n};throw Error('Tool inputSchema must describe an object at the top level, but the schema has a top-level "allOf" with no branch that asserts type: "object". Add type: "object" to at least one allOf branch to make the object constraint explicit.')}if(i.every((o)=>o&&typeof o==="object"&&o.type==="object"))return{type:"object",...n};throw Error(`Tool inputSchema must describe an object at the top level, but the schema has a top-level "${r}" whose branches include non-object types. Pass the strict object schema as inputSchema and reserve union/coercion schemas for use inside execute().`)}return n}function Nf(e){let t=Of(e.inputSchema instanceof M?Jp(e.inputSchema):e.inputSchema);return{name:e.name,resultPolicy:e.resultPolicy,description:e.description,inputSchema:t,...e.source?{source:e.source}:{},...e.readOnly?{readOnly:!0}:{},lifecycle:e.lifecycle,executionMode:e.executionMode,timeoutMs:e.timeoutMs??30000,retryable:e.retryable??!0,maxRetries:e.maxRetries??3,execute:e.execute}}var Xm="Switch from plan mode to act mode. Switching to act mode immediately starts executing the plan, so only call this after the user has explicitly approved the plan in a message sent AFTER you presented it (e.g. 'looks good', 'go ahead', 'switch to act mode'). Never call this in the same turn you present a plan, never call it proactively, and never treat the original task request as approval. "+"Output: a one-line confirmation, as plain text. This call ends the current run and the next one starts in act mode with the file and command tools available, so it is a handover, not a failure — carry on with the plan there.";import{classifyProviderError as ds,createGateway as Jf,isRetryableProviderError as Yf}from"@cerebriline/llms";import{nanoid as Xf}from"nanoid";function Nn(){return{reasoningDeltas:0,reasoningChars:0,textDeltas:0,textChars:0,toolInputChars:0}}var Mf=12;function Go(e,t){let n=t.reduce((a,l)=>a+l,0);if(n<=0)return t.map(()=>0);let r=t.map((a)=>e*a/n),i=r.map(Math.floor),o=e-i.reduce((a,l)=>a+l,0),s=r.map((a,l)=>({index:l,rest:a-Math.floor(a)})).sort((a,l)=>l.rest-a.rest);for(let{index:a}of s){if(o<=0)break;i[a]=(i[a]??0)+1,o-=1}return i}function Ko(e){let t=Math.floor(e.outputTokens??0);if(!(t>0))return;let{tally:n}=e,r=e.providerReasoningTokens??0;if(r>0){let u=Math.min(t,Math.floor(r)),[d=0,h=0]=Go(t-u,n.textChars+n.toolInputChars>0?[n.textChars,n.toolInputChars]:[1,0]);return{reasoningTokens:u,textTokens:d,toolInputTokens:h,method:"provider"}}let i=n.reasoningDeltas+n.textDeltas,o=n.reasoningChars+n.textChars;if(i>0&&i<=t&&o/i<=Mf)return{reasoningTokens:n.reasoningDeltas,textTokens:n.textDeltas,toolInputTokens:t-i,method:"stream-chunks"};let[s=0,a=0,l=0]=Go(t,o+n.toolInputChars>0?[n.reasoningChars,n.textChars,n.toolInputChars]:[0,1,0]);return{reasoningTokens:s,textTokens:a,toolInputTokens:l,method:"chars-share"}}var Lt={minChars:4000,window:60,lineCycleWindow:126,maxPeriod:6,minCycles:20,maxUniqueInWindow:4,minLineChars:2000,phraseMaxPeriod:120,phraseMinCycles:12,blockMinPeriod:7,blockMaxPeriod:400,blockMinCycles:3,blockMinChars:200,maxConsecutiveTrips:3};function Mn(e,t="reasoning"){let n=`after ${e.chars.toLocaleString()} characters${t==="reasoning"?" of reasoning":""}`,r=e.sample?` Repeating: ${JSON.stringify(e.sample)}`:"";switch(e.kind){case"low-uniqueness":return`The model's ${t} collapsed into ${e.distinct} distinct lines over ${n}.${r}`;case"line-cycle":case"block-cycle":return`The model's ${t} repeated a ${e.period}-line block ${e.cycles} times ${n}.${r}`;case"phrase-cycle":return`The model's ${t} repeated a ${e.period}-character phrase ${e.cycles} times ${n}.${r}`;case"restated-lines":return`The model's ${t} kept writing the same lines again: ${e.distinct} distinct lines, one of them ${e.cycles} times, ${n}.${r}`}}function Pn(e){let t=[],n=(r,i)=>{if(typeof r==="string"){if(r)t.push(r)}else if(i<6&&Array.isArray(r))for(let o of r)n(o,i+1);else if(i<6&&r!==null&&typeof r==="object")for(let o of Object.values(r))n(o,i+1)};for(let r of e){if(r.role==="assistant")continue;for(let i of r.content)if(i.type==="text")n(i.text,0);else if(i.type==="tool-result")n(i.output,0)}return t.join(`
73
+ `)}var Pf=/^\d+\s*\|\s?/;function Fe(e){return e.trim().replace(Pf,"").trim()}class Ee{cfg;given;chars=0;lines=[];cycleLines=[];history=[];pending="";verdict=null;source;sourceRuns=new Map;recent=[];streaks=[];block;constructor(e={},t={}){this.cfg={...Lt,...e},this.given=t.given}get tripped(){return this.verdict}push(e){if(this.verdict||!e)return this.verdict;this.chars+=e.length,this.pending+=e;let t;while((t=this.pending.indexOf(`
74
+ `))!==-1){let r=this.pending.slice(0,t).trim();if(this.pending=this.pending.slice(t+1),r){if(this.lines.push(r),this.lines.length>this.cfg.window)this.lines.shift();if(this.cycleLines.push(r),this.cycleLines.length>this.cfg.lineCycleWindow)this.cycleLines.shift();if(this.given)this.history.push(r);this.trackBlocks(r)}}if(this.chars<this.cfg.minChars)return null;let n=this.detectLowUniqueness()??this.detectLineCycle()??this.detectBlockCycle()??this.detectPhraseCycle();if(n)this.verdict=n;return this.verdict}readSource(){if(!this.given)return;if(!this.source){let e="";try{e=this.given()}catch{}this.source={text:e,lines:e.split(`
75
+ `).map(Fe).filter((t)=>t!=="")}}return this.source.text?this.source:void 0}remembered(e,t){let n=this.sourceRuns.get(e);if(n===void 0){if(n=t(),this.sourceRuns.size>512)this.sourceRuns.clear();this.sourceRuns.set(e,n)}return n}phraseRunInSource(e){let t=this.readSource();if(!t)return 0;return this.remembered(`p
76
+ ${e}`,()=>{let n=0,r=t.text.indexOf(e);while(r!==-1){let i=1,o=r+e.length;while(t.text.startsWith(e,o))i++,o+=e.length;if(i>n)n=i;r=t.text.indexOf(e,o)}return n})}blockRunInSource(e){let t=this.readSource();if(!t)return 0;let n=e.map(Fe);return this.remembered(`b
84
77
  ${n.join(`
85
- `)}`,()=>{let i=t.lines,r=n.length,o=0;for(let s=0;s+r<=i.length;s++){let a=0,u=s;while(u+r<=i.length){let c=!0;for(let d=0;d<r;d++)if(i[u+d]!==n[d]){c=!1;break}if(!c)break;a++,u+=r}if(a>o)o=a;if(a>1)s=u-r}return o})}stretchInSource(e){let t=this.readSource();if(!t)return 0;let n=new Set([...e].map(Ne));return this.remembered(`s
78
+ `)}`,()=>{let r=t.lines,i=n.length,o=0;for(let s=0;s+i<=r.length;s++){let a=0,l=s;while(l+i<=r.length){let u=!0;for(let d=0;d<i;d++)if(r[l+d]!==n[d]){u=!1;break}if(!u)break;a++,l+=i}if(a>o)o=a;if(a>1)s=l-i}return o})}stretchInSource(e){let t=this.readSource();if(!t)return 0;let n=new Set([...e].map(Fe));return this.remembered(`s
86
79
  ${[...n].sort().join(`
87
- `)}`,()=>{let i=0,r=0;for(let o of t.lines)if(r=n.has(o)?r+1:0,r>i)i=r;return i})}detectLowUniqueness(){if(this.lines.length<this.cfg.window)return null;let e=new Set(this.lines);if(e.size>this.cfg.maxUniqueInWindow)return null;if(this.given){let t=0;for(let n=this.history.length-1;n>=0&&e.has(this.history[n]);n--)t++;if(t-this.stretchInSource(e)<this.cfg.window)return null}return{kind:"low-uniqueness",distinct:e.size,chars:this.chars,sample:[...e].join(" / ").slice(0,160)}}detectLineCycle(){let e=this.cycleLines,t=e.length;if(t<this.cfg.maxPeriod*2)return null;for(let n=1;n<=this.cfg.maxPeriod;n++){let i=0;for(let r=t-n;r-n>=0;r-=n){let o=!0;for(let s=0;s<n;s++)if(e[r+s]!==e[r-n+s]){o=!1;break}if(!o)break;i++}if(i>=this.cfg.minCycles){if(this.given){let r=this.history,o=1;for(let s=r.length-n;s-n>=0;s-=n){let a=!0;for(let u=0;u<n;u++)if(r[s+u]!==r[s-n+u]){a=!1;break}if(!a)break;o++}if(o<=this.blockRunInSource(e.slice(t-n)))continue}return{kind:"line-cycle",period:n,cycles:i+1,chars:this.chars,sample:e.slice(t-n).join(" / ").slice(0,160)}}}return null}trackBlocks(e){let{blockMinPeriod:t,blockMaxPeriod:n}=this.cfg;if(n<t)return;if(this.recent.push(e),this.recent.length>n+1)this.recent.shift();let i=this.recent.length;this.block=void 0;for(let r=t;r<=n&&r<i;r++){let o=this.recent[i-1]===this.recent[i-1-r]?(this.streaks[r]??0)+1:0;if(this.streaks[r]=o,!this.block&&o>=(this.cfg.blockMinCycles-1)*r&&this.recent.slice(i-r).reduce((s,a)=>s+a.length,0)>=this.cfg.blockMinChars)this.block={period:r,cycles:Math.floor(o/r)+1}}}detectBlockCycle(){let e=this.block;if(!e)return null;let t=this.recent.slice(this.recent.length-e.period);if(e.cycles<=this.blockRunInSource(t))return null;return{kind:"block-cycle",period:e.period,cycles:e.cycles,chars:this.chars,sample:t.join(" / ").slice(0,160)}}detectPhraseCycle(){let e=this.pending;if(e.length<this.cfg.minLineChars)return null;for(let t=4;t<=this.cfg.phraseMaxPeriod;t++){let n=e.slice(e.length-t),i=0,r=e.length-t;while(r-t>=0&&e.startsWith(n,r-t))i++,r-=t;if(i>=this.cfg.phraseMinCycles){if(i+1<=this.phraseRunInSource(n))continue;return{kind:"phrase-cycle",period:t,cycles:i+1,chars:this.chars,sample:n.replace(/\s+/g," ").slice(0,160)}}}return null}}var ge={minChars:4000,minParagraphChars:60,minStopwords:3,maxRepeatTrip:4,duplicateFractionTrip:0.25,cooldownTurns:3,maxNudges:1,recoveryTokens:4000};var Nd=/\b(the|is|are|to|and|of|it|that|this|be|for|but|so|if|will|need|should|let|now|then|because|actually|wait)\b/g;function Od(e,t){let n=e.trim();return((n.startsWith("```")?n.replace(/```[\s\S]*?```/g,""):n).toLowerCase().match(Nd)??[]).length>=t}function yt(e,t=ge){if(e.length<t.minChars)return;let n=e.split(/\n\s*\n/).map((a)=>a.trim()).filter((a)=>a.length>=t.minParagraphChars&&Od(a,t.minStopwords));if(n.length===0)return;let i=new Map;for(let a of n)i.set(a,(i.get(a)??0)+1);let r=0,o=0,s="";for(let[a,u]of i)if(r+=u-1,u>o)o=u,s=a;return{paragraphs:n.length,duplicates:r,duplicateFraction:r/n.length,maxRepeat:o,sample:s}}function $r(e,t){let n=[];for(let o=e.indexOf(t.sample);o>=0&&n.length<200;o=e.indexOf(t.sample,o+t.sample.length))n.push(Math.round(o/Math.max(1,e.length)*100));let i=t.sample.replace(/\s+/g," "),r=i.length>400?`${i.slice(0,400)} ...`:i;return`${e.length} chars; one passage ${t.maxRepeat} times; ${t.duplicates} of ${t.paragraphs} paragraphs repeat an earlier one; its copies begin at ${n.map((o)=>`${o}%`).join(", ")} of the turn; passage (${i.length} chars): ${JSON.stringify(r)}`}function vt(e,t=ge){if(!e)return!1;return e.maxRepeat>=t.maxRepeatTrip&&e.duplicateFraction>=t.duplicateFractionTrip}function Lr(e){let t=e.sample.replace(/\s+/g," ").slice(0,200);return[`[SYSTEM] In your last reply you wrote this same passage ${e.maxRepeat} times, word for word:`,"",` "${t}${e.sample.length>200?"…":""}"`,"",`That reply restated ${e.duplicates} of its ${e.paragraphs} paragraphs verbatim. Re-deriving a conclusion you have already reached will not produce a new one, and none of that reasoning is visible to the user.`,"","You will not find it above: your reasoning from that turn is not carried into this request, so the passage is quoted here because it is the only copy you have. Take it as given rather than looking for it.","","Take the next concrete step instead: make the change, run the check, or say plainly what is blocking you and what you would need to get past it."].join(`
88
- `)}function Gt(e=ge){let t=0,n=Number.NEGATIVE_INFINITY,i=0,r=Math.max(0,e.recoveryTokens)*4;return{get spent(){return t},inspect(o,s){let a=yt(o,e);if(!(vt(a,e)&&!!a)){if(r>0&&t>0){if(i+=o.length,i>=r)t=0,i=0}return}if(t>=e.maxNudges)return;if(s-n<e.cooldownTurns)return;return t+=1,i=0,n=s,Lr(a)}}}var Md={n:`
89
- `,t:"\t",r:"",'"':'"',"\\":"\\","/":"/"};class Kt{config;options;calls=new Map;verdict;constructor(e={},t={}){this.config=e;this.options=t}push(e,t,n){if(this.verdict||!t)return this.verdict;let i=this.calls.get(e);if(!i)i={guard:new me(this.config,this.options),restated:new Ur(this.options.given),escaping:!1},this.calls.set(e,i);if(i.json===void 0){let s=t.trimStart()[0];if(s!==void 0)i.json=s==="{"||s==="["}let r=i.json?Ld(i,t):t,o=i.guard.push(r)??i.restated.push(r)??void 0;if(o)this.verdict={toolCallId:e,...n?{toolName:n}:{},verdict:o};return this.verdict}}var zr=24,Pd=300,Dr=0.3,$d=50;class Ur{given;counts=new Map;pending="";chars=0;lines=0;excess=0;nextCheck=Pd;source;constructor(e){this.given=e}push(e){this.chars+=e.length,this.pending+=e;let t;while((t=this.pending.indexOf(`
90
- `))!==-1){let o=Ne(this.pending.slice(0,t));if(this.pending=this.pending.slice(t+1),o.length<zr)continue;let s=(this.counts.get(o)??0)+1;if(this.counts.set(o,s),this.lines++,s>2)this.excess++}if(this.lines<this.nextCheck||this.excess<Dr*this.lines)return;if(this.excessBeyondSource()<Dr*this.lines){this.nextCheck=this.lines+$d;return}let i="",r=0;for(let[o,s]of this.counts)if(s>r)r=s,i=o;return{kind:"restated-lines",chars:this.chars,cycles:r,distinct:this.counts.size,sample:i.slice(0,160)}}excessBeyondSource(){if(this.source===void 0){this.source=new Map;let t="";try{t=this.given?.()??""}catch{}for(let n of t.split(`
91
- `)){let i=Ne(n);if(i.length>=zr)this.source.set(i,(this.source.get(i)??0)+1)}}let e=0;for(let[t,n]of this.counts)e+=Math.max(0,n-Math.max(2,(this.source.get(t)??0)+1));return e}}function Ld(e,t){let n="";for(let i of t)if(e.escaping)e.escaping=!1,n+=Md[i]??`\\${i}`;else if(i==="\\")e.escaping=!0;else n+=i;return n}function Fr(e){return`(A call to ${e.toolName?`\`${e.toolName}\``:"a tool"} was begun here and cut before it was complete, so nothing ran. Its text is not kept.)`}function Jt(e){return e.kind==="phrase-cycle"?`the same ${e.period}-character run ${e.cycles} times`:e.kind==="low-uniqueness"?`the same ${e.distinct} lines over and over`:e.kind==="restated-lines"?`lines already written twice, one of them ${e.cycles} times`:`the same ${e.period}-line block ${e.cycles} times`}function Br(e){return`[SYSTEM] Your call to ${e.toolName?`\`${e.toolName}\``:"a tool"} was cut while you were writing it, and nothing ran: its arguments had come to repeat ${Jt(e.verdict)}. Make the call again with only what it needs.`}function jr(e){return`[SYSTEM] Your reply was cut while you were writing it, and none of it is kept: it had come to repeat ${Jt(e)}. Carry on with the task from where it stands.`}function qr(e){return`[SYSTEM] Your thinking was cut while you were writing it, and none of it is kept: it had come to repeat ${Jt(e)}. Carry on with the task from where it stands: make the next tool call now rather than working the plan out again.`}import{nanoid as zd}from"nanoid";class je{assemblies=new Map;nextIndex=0;add(e){let t=e.toolCallId??`tool_${e.index??this.nextIndex}`;if(e.index==null&&e.toolCallId==null)this.nextIndex+=1;let n=this.assemblies.get(t),i=n===void 0;if(!n)n={toolCallId:e.toolCallId??`tool_${zd(8)}`,inputText:""},this.assemblies.set(t,n);if(e.toolCallId)n.toolCallId=e.toolCallId;if(e.toolName)n.toolName=e.toolName;if(e.input!==void 0)n.inputValue=e.input;if(e.metadata!==void 0)n.metadata=Hr(n.metadata,e.metadata);if(e.inputText)n.inputText=jd(n.inputText,e.inputText);return{key:t,created:i}}get(e){return this.assemblies.get(e)}inputChars(){let e=0;for(let t of this.assemblies.values())e+=Ud(t);return e}finish(e,t,n=!1){let i=this.assemblies.get(e);if(!i?.toolName)return{invalid:{toolCallId:i?.toolCallId??e,input:Be(i?.inputText??""),reason:"missing_name"}};let r=Fd(i,t,n),o={type:"tool-call",toolCallId:i.toolCallId,toolName:i.toolName,input:r.input,metadata:r.parseError?Hr(i.metadata,{inputParseError:r.parseError,rawInputText:i.inputText}):i.metadata};return r.reason?{call:o,invalid:{toolCallId:i.toolCallId,toolName:i.toolName,input:r.invalidInput,reason:r.reason}}:{call:o}}}async function Dd(e,t={}){let n=new je,i=[],r="",o="",s="unknown",a;for await(let b of e)switch(b.type){case"text-delta":{r+=b.text;let w=i.at(-1);if(w?.type==="part"&&w.part.type==="text")w.part.text+=b.text;else i.push({type:"part",part:{type:"text",text:b.text}});break}case"reasoning-delta":{o+=b.text;let w=i.at(-1);if(w?.type==="part"&&w.part.type==="reasoning")w.part.text+=b.text,w.part.redacted=b.redacted??w.part.redacted,w.part.metadata=b.metadata??w.part.metadata;else i.push({type:"part",part:{type:"reasoning",text:b.text,redacted:b.redacted,metadata:b.metadata}});break}case"tool-call-delta":{if(b.execution)break;let{key:w,created:F}=n.add(b);if(F)i.push({type:"tool",key:w});break}case"finish":{s=b.reason,a=b.error;break}}let u=new Map((t.tools??[]).map((b)=>[b.name,b.inputSchema])),c=[],d=[],y=[],p;for(let b of i)if(b.type==="tool")p=b.key;for(let b of i){if(b.type==="part"){c.push(b.part);continue}let w=n.finish(b.key,s,b.key===p);if(w.invalid)y.push(w.invalid);if(!w.call)continue;if(c.push(w.call),w.invalid)continue;let F=u.get(w.call.toolName);d.push(F?{...w.call,input:Ce(w.call.input,F)}:w.call)}let v=d.length===0&&y.length===0?Se(r):void 0;return{content:c,toolCalls:d,invalidToolCalls:y,text:r,reasoning:o,finishReason:s,...v?{unparsedToolCall:v}:{},...a?{error:a}:{}}}function Hr(e,t){if(!t||typeof t!=="object"||Array.isArray(t))return t;if(!e||typeof e!=="object"||Array.isArray(e))return t;return{...e,...t}}function Ud(e){if(e.inputText)return e.inputText.length;if(e.inputValue===void 0)return 0;try{return JSON.stringify(e.inputValue)?.length??0}catch{return 0}}function Fd(e,t,n=!1){if(t==="max-tokens"&&n){let s=e.inputValue!==void 0?JSON.stringify(e.inputValue):e.inputText;if(s.trim())return{input:{},invalidInput:Be(s),parseError:`Tool call ${e.toolName??e.toolCallId} was cut off by the output budget: the turn ended at the cap while this call was being written, ${s.length} characters into its arguments, so what arrived may not be all of it, and it was not run. Send the same work in smaller pieces: edit one region per call rather than rewriting the file, and keep each call's arguments short enough to complete.`,reason:"invalid_arguments"}}if(e.inputValue!==void 0)return{input:e.inputValue,invalidInput:Be(JSON.stringify(e.inputValue))};if(!e.inputText.trim())return{input:{},invalidInput:{}};let i=Bd(e.inputText);if(i.ok)return{input:i.value,invalidInput:Be(e.inputText)};let o=t==="max-tokens"?`was cut off by the output budget before its arguments finished: the turn ended at the cap with ${e.inputText.length} characters of arguments written. Nothing is wrong with the payload you were writing -- there was no room left to finish it. Send the same work in smaller pieces: edit one region per call rather than rewriting the file, and keep each call's arguments short enough to complete.`:`emitted invalid JSON arguments: ${i.error}`;return{input:{},invalidInput:Be(e.inputText,i.error),parseError:`Tool call ${e.toolName??e.toolCallId} ${o}`,reason:"invalid_arguments"}}function Be(e,t){if(!e.trim())return{};return t?{rawInputText:e,parseError:t}:{rawInputText:e}}function Bd(e){let t=e.trim();if(!t)return{ok:!1,error:"Tool call arguments were empty."};try{return{ok:!0,value:JSON.parse(t)}}catch{}if(!(t.startsWith("{")||t.startsWith("[")))return{ok:!1,error:"Tool call arguments must be encoded as a JSON object or array."};return{ok:!1,error:"Tool call arguments could not be parsed as JSON. Ensure the outer tool payload is valid JSON and escape embedded quotes/newlines inside string fields."}}function jd(e,t){if(!e)return t;let n=t.trimStart();if(n.startsWith("{")||n.startsWith("["))return t;return e+t}var qd=2000,Vr=!0;function Hd(e){Vr=e}function Xt(){return Vr}var Yt="intent";function Zr(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Wr(e){if(e.length===0)return;let t=[...e].sort((n,i)=>i.length-n.length).map(Zr).join("|");return new RegExp(`[,{"'=>]\\s*(?:${t})["']?\\s*[:=><]`)}function Wd(e){if(e.length===0)return;let t=[...e].sort((n,i)=>i.length-n.length).map(Zr).join("|");return new RegExp(`(?<![A-Za-z0-9_])(?:${t})(?![A-Za-z0-9_])`,"g")}class Qt{maxChars;calls=new Map;intentKey;otherKey;toolName;tailChars;constructor(e){this.maxChars=e?.maxChars??2000;let t=[...new Set(e?.argumentNames??[])].filter((i)=>i.length>0&&i!==Yt);this.otherKey=Wr(t),this.intentKey=this.otherKey?Wr([Yt]):void 0;let n=[...new Set(e?.toolNames??[])].filter((i)=>i.length>0);this.toolName=Wd(n),this.tailChars=Math.max(Yt.length,...t.map((i)=>i.length),...n.map((i)=>i.length))+8}push(e,t,n){if(!this.intentKey||!this.otherKey||t.length===0)return;let i=this.calls.get(e);if(!i)i={phase:"seeking",tail:"",chars:0},this.calls.set(e,i);if(n)i.toolName=n,i.named=!0;if(i.phase==="closed")return;let r=i.tail+t,o=t.length;if(i.phase==="seeking"){let s=this.intentKey.exec(r);if(!i.named&&this.toolName){let a=s?r.slice(0,s.index):r;for(let u of a.matchAll(this.toolName))i.toolName=u[0]}if(!s){i.tail=r.slice(-this.tailChars);return}i.phase="counting",r=r.slice(s.index+s[0].length),o=r.length}if(this.otherKey.test(r)){i.phase="closed",i.tail="";return}if(i.chars+=o,i.tail=r.slice(-this.tailChars),i.chars<=this.maxChars)return;return{toolCallId:e,...i.toolName?{toolName:i.toolName}:{},chars:i.chars,maxChars:this.maxChars}}}function Gr(e){return`(A call to ${e.toolName?`\`${e.toolName}\``:"a tool"} was begun here and cut before it was complete, so nothing ran. Its text is not kept.)`}function Kr(e){let t=e.toolName?`\`${e.toolName}\``:"a tool",n=e.maxChars.toLocaleString("en-US");return`[SYSTEM] Your call to ${t} was cut while you were writing it, and nothing ran. Its \`intent\` had passed ${n} characters. \`intent\` is one sentence saying what the call does. Decide what to do before you begin the call, then make the call again with \`intent\` as that one sentence.`}var Kd=Boolean(globalThis.process?.env?.CLINE_TIMING);function Jd(e){if(!Kd)return;globalThis.process?.stderr?.write?.(`[timing] ${new Date().toISOString()} ${e}
92
- `)}var bt=32000;function Yd(e,t,n,i,r){let o=i,s="raw";if(!o.trim()){s="parsed";try{o=JSON.stringify(r)??""}catch{o=String(r)}}let a=o.replace(/\r?\n/g,"\\n"),u=Math.floor(bt*0.75),c=a.length<=bt?a:`${a.slice(0,u)} …[${a.length-bt} characters not logged]… ${a.slice(-(bt-u))}`;return`[tool-args] iter=${e} ${t} id=${n} ${s} chars=${a.length} ${c}`}var Xd="Model reached the maximum output token limit before completing the turn",Qd=2,ep=2000,tp="[an image was here; the vision model could not describe it, and this model cannot read images. Work from what the surrounding text says about it, or ask for the detail you need.]",np="[image omitted — this model does not accept image input; the text above is what the tool reported]";function ip(e){let t=typeof e.image==="string"?e.image:e.data;if(typeof t==="string")return t.length>0?t:void 0;let n=e.image instanceof Uint8Array?e.image:e.image instanceof ArrayBuffer?new Uint8Array(e.image):void 0;if(!n||n.byteLength===0)return;return Buffer.from(n).toString("base64")}var rp=8000,Yr="[SYSTEM] Your last reply hit the per-turn output limit before you finished, so it was discarded — none of it, including your reasoning, is in this conversation. "+"Do not try to reproduce it. Take the smallest useful next step instead: make one tool call, or write one short paragraph. If the work you were planning does not fit in one reply, do the part that fits, call the tools it needs, and continue in the next turn.";function op(e){if(!Array.isArray(e)||e.length===0)return;let t=e.filter((i)=>typeof i==="object"&&i!==null&&typeof i.chars==="number");if(t.length===0)return;return`It ended while you were writing a call to ${t.map((i)=>`\`${i.toolName??"a tool"}\` (${i.chars.toLocaleString("en-US")} characters of arguments written)`).join(", ")}. That call was not run, so it changed nothing. If it was one large edit or file, split it into smaller calls.`}var sp="And what that reasoning had established about the problem itself:",ap="Before it was discarded, your reasoning was condensed into the note below. It is what you had worked out when you ran out of room. Continue from it rather than repeating it. It is a record of your thinking, not an observation of the workspace: where it disagrees with a tool result in this conversation, the tool result is what is true and the note is out of date.",lp="[SYSTEM] Your answer has been passed on. That message came in while you were working, so it did not replace the task you were given — "+"the work you were doing when it arrived is still unfinished. Take that work up again from where you left off, unless the message told you to change course or to stop.",up="[SYSTEM] Your last reply ran out of room before any of it was delivered, so it was discarded — none of it, including your reasoning, is in this conversation. "+"Do not try to reproduce it. Take the smallest useful next step instead: make one tool call, or write one short paragraph. If the work you were planning does not fit in one reply, do the part that fits, call the tools it needs, and continue in the next turn.",cp="[SYSTEM] Your last reply was thinking only: no answer and no tool call arrived. End your thinking, then either make one tool call or write your answer. Keep the thinking short.",dp="[SYSTEM] Your last reply ended inside your thinking: the tool call you wrote there was part of the thinking, so it never ran and nothing was changed by it. Close your thinking first, then send that one call again as an actual tool call. Keep the thinking short.",Xr=3,pp=2,hp=1024,fp=/<\/?tool_call>|<\/function>|<function=|<\/parameter>/;function mp(e){let t="";for(let n of e.content){if(n.type==="reasoning"){let i=n.text;t+=typeof i==="string"?i:"";continue}if(n.type==="text"){if(n.text?.trim())return;continue}return}return t.trim()?{toolCallInThinking:fp.test(t)}:void 0}var gp="[SYSTEM] Your last tool call did not parse, so it never ran and nothing was changed by it. "+"The text you wrote before it is still here and still correct — the call around it was malformed, most often because it was cut short. "+"Send that one call again, complete, and nothing else in this reply. If it carries a large argument, make the argument smaller rather than sending the same one again: name a line range instead of a whole file, or split the work across two calls.";function yp(e){if(e?.reason!=="swallowed_key")return gp;let t=e.tool?`\`${e.tool}\` call`:"tool call",n=e.key?`ran on into \`${e.key}\`, so the parser read \`${e.key}\` and what followed as part of that value`:"ran on into the next argument, so the parser read that argument as part of the value";return`[SYSTEM] Your last ${t} was rejected before it ran, and nothing was changed by it. A string argument in it never closed: it ${n}. This happens when a string argument that contains code is ended with a character from that code, such as a backtick or a quote, instead of the tool-call format's own string delimiter. Send that one call again, complete, and nothing else in this reply, with every string argument closed by the format's delimiter.`}var vp=2,bp=1,io=3,ro=2000,en=3,Tp=1000,wp=15000,_p="Model returned no content because the response was blocked by a content filter. Retrying is unlikely to help — try rephrasing the request.",kp="The request exceeds the model's context window and there is no conversation history to compact — the system prompt, tools, and current input alone are too large. Reduce attached content or switch to a model with a larger context window.",Ep="The conversation still exceeds the model's context window after compacting it. Start a new session or switch to a model with a larger context window.",Ip="The conversation exceeds the model's context window. Compact the conversation, start a new session, or switch to a model with a larger context window.";class Me extends Error{constructor(e,t){super(t?.trim()?`${e} (provider reported: ${t.trim()})`:e);this.name="ContextWindowOverflowError"}}function ye(e,t=8){return`${e}_${Gd(t)}`}function Ap(e){return e.model!==void 0}function xp(e){if(Ap(e))return e;let{providerId:t,modelId:n,apiKey:i,baseUrl:r,headers:o,options:s,...a}=e,c=Vd({providerConfigs:[{providerId:t,apiKey:i,baseUrl:r,headers:o,options:s}],telemetry:a.telemetry}).createAgentModel({providerId:t,modelId:n}),d=a.messageModelInfo??{id:n,provider:t};return{...a,model:c,messageModelInfo:d}}function Cp(e,t){return{...t?.["*"]??{},...t?.[e]??{}}}function rn(e){try{return JSON.stringify(e).length}catch{return String(e).length}}function Rp(e){if(typeof e==="string")return e.length;return rn(e)}function Sp(e){let t=e.systemPrompt?.length??0,n=0,i=0,r=0;for(let o of e.messages)for(let s of o.content)switch(s.type){case"text":t+=s.text.length;break;case"reasoning":t+=s.text.length;break;case"file":t+=s.content.length;break;case"tool-call":t+=rn(s.input);break;case"tool-result":{let a=Rp(s.output);n+=1,i+=a,r=Math.max(r,a),t+=a;break}}return{messageCount:e.messages.length,toolSchemaCount:e.tools.length,systemPromptChars:e.systemPrompt?.length??0,requestJsonChars:rn({systemPrompt:e.systemPrompt,messages:e.messages,tools:e.tools,options:e.options}),visibleTextChars:t,estimatedTextTokens:br(t),toolResultCount:n,toolResultChars:i,maxToolResultChars:r}}class on extends Error{constructor(e){super(`Agent runtime exceeded maxIterations (${e})`);this.name="MaxIterationsReachedError"}}class Tt extends Error{reason;constructor(e){super(e??"Run stopped by runtime control");this.name="ControlledStopError",this.reason=e}}class ve extends Error{reason;constructor(e){let t=typeof e==="string"?e:e instanceof Error?e.message:e===void 0?"Run aborted":String(e);super(t);this.name="AgentRuntimeAbortError",this.reason=e}}var tn={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0};function de(e,t,n){return{id:ye("msg"),role:e,content:t,createdAt:Date.now(),metadata:n}}function oe(e){return{...e}}var Np={_:"__",'"':"_q_","<":"_lt_",">":"_gt_"};function Qr(e){return e.replace(/[_"<>]/g,(t)=>Np[t])}function nn(e,t){let n=[`source="${e.source}"`];if("toolCall"in e)n.push(`tool_name="${Qr(e.toolCall.toolName)}"`,`tool_call_id="${Qr(e.toolCall.toolCallId)}"`);let i=t.trim().replace(/<(\/?)hook_context/gi,"<\\$1hook_context");return`<hook_context ${n.join(" ")}>
93
- ${i}
94
- </hook_context>`}function Y(e){return e.map((t)=>({...t,content:t.content.map((n)=>({...n})),metadata:t.metadata?{...t.metadata}:void 0,modelInfo:t.modelInfo?{...t.modelInfo}:void 0,metrics:t.metrics?{...t.metrics}:void 0}))}function Op(e,t){let n=Math.max(0,(t.inputTokens??0)-(e.inputTokens??0)),i=Math.max(0,(t.outputTokens??0)-(e.outputTokens??0)),r=Math.max(0,(t.cacheReadTokens??0)-(e.cacheReadTokens??0)),o=Math.max(0,(t.cacheWriteTokens??0)-(e.cacheWriteTokens??0)),s=Math.max(0,(t.reasoningTokenCount??0)-(e.reasoningTokenCount??0)),a=e.totalCost??0,u=t.totalCost??0,c=Math.max(0,u-a);if(n===0&&i===0&&r===0&&o===0&&s===0&&c===0)return;return{inputTokens:n>0?n:0,outputTokens:i>0?i:0,cacheReadTokens:r>0?r:0,cacheWriteTokens:o>0?o:0,...s>0?{reasoningTokenCount:s}:{},...c>0?{cost:c}:{}}}function Mp(e){return e.options?.thinking===!1}function Oe(e){if(!e)return"";return e.content.filter((t)=>t.type==="text").map((t)=>t.text).join("")}function eo(e){if(!e)return"";let t=[];for(let n of e.content){if(n.type!=="reasoning")continue;let i=n.text;if(typeof i==="string"&&i.length>0)t.push(i)}return t.join(`
80
+ `)}`,()=>{let r=0,i=0;for(let o of t.lines)if(i=n.has(o)?i+1:0,i>r)r=i;return r})}detectLowUniqueness(){if(this.lines.length<this.cfg.window)return null;let e=new Set(this.lines);if(e.size>this.cfg.maxUniqueInWindow)return null;if(this.given){let t=0;for(let n=this.history.length-1;n>=0&&e.has(this.history[n]);n--)t++;if(t-this.stretchInSource(e)<this.cfg.window)return null}return{kind:"low-uniqueness",distinct:e.size,chars:this.chars,sample:[...e].join(" / ").slice(0,160)}}detectLineCycle(){let e=this.cycleLines,t=e.length;if(t<this.cfg.maxPeriod*2)return null;for(let n=1;n<=this.cfg.maxPeriod;n++){let r=0;for(let i=t-n;i-n>=0;i-=n){let o=!0;for(let s=0;s<n;s++)if(e[i+s]!==e[i-n+s]){o=!1;break}if(!o)break;r++}if(r>=this.cfg.minCycles){if(this.given){let i=this.history,o=1;for(let s=i.length-n;s-n>=0;s-=n){let a=!0;for(let l=0;l<n;l++)if(i[s+l]!==i[s-n+l]){a=!1;break}if(!a)break;o++}if(o<=this.blockRunInSource(e.slice(t-n)))continue}return{kind:"line-cycle",period:n,cycles:r+1,chars:this.chars,sample:e.slice(t-n).join(" / ").slice(0,160)}}}return null}trackBlocks(e){let{blockMinPeriod:t,blockMaxPeriod:n}=this.cfg;if(n<t)return;if(this.recent.push(e),this.recent.length>n+1)this.recent.shift();let r=this.recent.length;this.block=void 0;for(let i=t;i<=n&&i<r;i++){let o=this.recent[r-1]===this.recent[r-1-i]?(this.streaks[i]??0)+1:0;if(this.streaks[i]=o,!this.block&&o>=(this.cfg.blockMinCycles-1)*i&&this.recent.slice(r-i).reduce((s,a)=>s+a.length,0)>=this.cfg.blockMinChars)this.block={period:i,cycles:Math.floor(o/i)+1}}}detectBlockCycle(){let e=this.block;if(!e)return null;let t=this.recent.slice(this.recent.length-e.period);if(e.cycles<=this.blockRunInSource(t))return null;return{kind:"block-cycle",period:e.period,cycles:e.cycles,chars:this.chars,sample:t.join(" / ").slice(0,160)}}detectPhraseCycle(){let e=this.pending;if(e.length<this.cfg.minLineChars)return null;for(let t=4;t<=this.cfg.phraseMaxPeriod;t++){let n=e.slice(e.length-t),r=0,i=e.length-t;while(i-t>=0&&e.startsWith(n,i-t))r++,i-=t;if(r>=this.cfg.phraseMinCycles){if(r+1<=this.phraseRunInSource(n))continue;return{kind:"phrase-cycle",period:t,cycles:r+1,chars:this.chars,sample:n.replace(/\s+/g," ").slice(0,160)}}}return null}}var Ae={minChars:4000,minParagraphChars:60,minStopwords:3,maxRepeatTrip:4,duplicateFractionTrip:0.25,cooldownTurns:3,maxNudges:1,recoveryTokens:4000};var $f=/\b(the|is|are|to|and|of|it|that|this|be|for|but|so|if|will|need|should|let|now|then|because|actually|wait)\b/g;function Lf(e,t){let n=e.trim();return((n.startsWith("```")?n.replace(/```[\s\S]*?```/g,""):n).toLowerCase().match($f)??[]).length>=t}function zt(e,t=Ae){if(e.length<t.minChars)return;let n=e.split(/\n\s*\n/).map((a)=>a.trim()).filter((a)=>a.length>=t.minParagraphChars&&Lf(a,t.minStopwords));if(n.length===0)return;let r=new Map;for(let a of n)r.set(a,(r.get(a)??0)+1);let i=0,o=0,s="";for(let[a,l]of r)if(i+=l-1,l>o)o=l,s=a;return{paragraphs:n.length,duplicates:i,duplicateFraction:i/n.length,maxRepeat:o,sample:s}}function Jo(e,t){let n=[];for(let o=e.indexOf(t.sample);o>=0&&n.length<200;o=e.indexOf(t.sample,o+t.sample.length))n.push(Math.round(o/Math.max(1,e.length)*100));let r=t.sample.replace(/\s+/g," "),i=r.length>400?`${r.slice(0,400)} ...`:r;return`${e.length} chars; one passage ${t.maxRepeat} times; ${t.duplicates} of ${t.paragraphs} paragraphs repeat an earlier one; its copies begin at ${n.map((o)=>`${o}%`).join(", ")} of the turn; passage (${r.length} chars): ${JSON.stringify(i)}`}function Dt(e,t=Ae){if(!e)return!1;return e.maxRepeat>=t.maxRepeatTrip&&e.duplicateFraction>=t.duplicateFractionTrip}function Yo(e){let t=e.sample.replace(/\s+/g," ").slice(0,200);return[`[SYSTEM] In your last reply you wrote this same passage ${e.maxRepeat} times, word for word:`,"",` "${t}${e.sample.length>200?"…":""}"`,"",`That reply restated ${e.duplicates} of its ${e.paragraphs} paragraphs verbatim. Re-deriving a conclusion you have already reached will not produce a new one, and none of that reasoning is visible to the user.`,"","You will not find it above: your reasoning from that turn is not carried into this request, so the passage is quoted here because it is the only copy you have. Take it as given rather than looking for it.","","Take the next concrete step instead: make the change, run the check, or say plainly what is blocking you and what you would need to get past it."].join(`
81
+ `)}function $n(e=Ae){let t=0,n=Number.NEGATIVE_INFINITY,r=0,i=Math.max(0,e.recoveryTokens)*4;return{get spent(){return t},inspect(o,s){let a=zt(o,e);if(!(Dt(a,e)&&!!a)){if(i>0&&t>0){if(r+=o.length,r>=i)t=0,r=0}return}if(t>=e.maxNudges)return;if(s-n<e.cooldownTurns)return;return t+=1,r=0,n=s,Yo(a)}}}var zf={n:`
82
+ `,t:"\t",r:"",'"':'"',"\\":"\\","/":"/"};class Ln{config;options;calls=new Map;verdict;constructor(e={},t={}){this.config=e;this.options=t}push(e,t,n){if(this.verdict||!t)return this.verdict;let r=this.calls.get(e);if(!r)r={guard:new Ee(this.config,this.options),restated:new es(this.options.given),escaping:!1},this.calls.set(e,r);if(r.json===void 0){let s=t.trimStart()[0];if(s!==void 0)r.json=s==="{"||s==="["}let i=r.json?Ff(r,t):t,o=r.guard.push(i)??r.restated.push(i)??void 0;if(o)this.verdict={toolCallId:e,...n?{toolName:n}:{},verdict:o};return this.verdict}}var Xo=24,Df=300,Qo=0.3,Uf=50;class es{given;counts=new Map;pending="";chars=0;lines=0;excess=0;nextCheck=Df;source;constructor(e){this.given=e}push(e){this.chars+=e.length,this.pending+=e;let t;while((t=this.pending.indexOf(`
83
+ `))!==-1){let o=Fe(this.pending.slice(0,t));if(this.pending=this.pending.slice(t+1),o.length<Xo)continue;let s=(this.counts.get(o)??0)+1;if(this.counts.set(o,s),this.lines++,s>2)this.excess++}if(this.lines<this.nextCheck||this.excess<Qo*this.lines)return;if(this.excessBeyondSource()<Qo*this.lines){this.nextCheck=this.lines+Uf;return}let r="",i=0;for(let[o,s]of this.counts)if(s>i)i=s,r=o;return{kind:"restated-lines",chars:this.chars,cycles:i,distinct:this.counts.size,sample:r.slice(0,160)}}excessBeyondSource(){if(this.source===void 0){this.source=new Map;let t="";try{t=this.given?.()??""}catch{}for(let n of t.split(`
84
+ `)){let r=Fe(n);if(r.length>=Xo)this.source.set(r,(this.source.get(r)??0)+1)}}let e=0;for(let[t,n]of this.counts)e+=Math.max(0,n-Math.max(2,(this.source.get(t)??0)+1));return e}}function Ff(e,t){let n="";for(let r of t)if(e.escaping)e.escaping=!1,n+=zf[r]??`\\${r}`;else if(r==="\\")e.escaping=!0;else n+=r;return n}function ts(e){return`(A call to ${e.toolName?`\`${e.toolName}\``:"a tool"} was begun here and cut before it was complete, so nothing ran. Its text is not kept.)`}function zn(e){return e.kind==="phrase-cycle"?`the same ${e.period}-character run ${e.cycles} times`:e.kind==="low-uniqueness"?`the same ${e.distinct} lines over and over`:e.kind==="restated-lines"?`lines already written twice, one of them ${e.cycles} times`:`the same ${e.period}-line block ${e.cycles} times`}function ns(e){return`[SYSTEM] Your call to ${e.toolName?`\`${e.toolName}\``:"a tool"} was cut while you were writing it, and nothing ran: its arguments had come to repeat ${zn(e.verdict)}. Make the call again with only what it needs.`}function rs(e){return`[SYSTEM] Your reply was cut while you were writing it, and none of it is kept: it had come to repeat ${zn(e)}. Carry on with the task from where it stands.`}function is(e){return`[SYSTEM] Your thinking was cut while you were writing it, and none of it is kept: it had come to repeat ${zn(e)}. Carry on with the task from where it stands: make the next tool call now rather than working the plan out again.`}import{nanoid as jf}from"nanoid";class nt{assemblies=new Map;nextIndex=0;add(e){let t=e.toolCallId??`tool_${e.index??this.nextIndex}`;if(e.index==null&&e.toolCallId==null)this.nextIndex+=1;let n=this.assemblies.get(t),r=n===void 0;if(!n)n={toolCallId:e.toolCallId??`tool_${jf(8)}`,inputText:""},this.assemblies.set(t,n);if(e.toolCallId)n.toolCallId=e.toolCallId;if(e.toolName)n.toolName=e.toolName;if(e.input!==void 0)n.inputValue=e.input;if(e.metadata!==void 0)n.metadata=os(n.metadata,e.metadata);if(e.inputText)n.inputText=Zf(n.inputText,e.inputText);return{key:t,created:r}}get(e){return this.assemblies.get(e)}inputChars(){let e=0;for(let t of this.assemblies.values())e+=qf(t);return e}finish(e,t,n=!1){let r=this.assemblies.get(e);if(!r?.toolName)return{invalid:{toolCallId:r?.toolCallId??e,input:tt(r?.inputText??""),reason:"missing_name"}};let i=Hf(r,t,n),o={type:"tool-call",toolCallId:r.toolCallId,toolName:r.toolName,input:i.input,metadata:i.parseError?os(r.metadata,{inputParseError:i.parseError,rawInputText:r.inputText}):r.metadata};return i.reason?{call:o,invalid:{toolCallId:r.toolCallId,toolName:r.toolName,input:i.invalidInput,reason:i.reason}}:{call:o}}}async function Bf(e,t={}){let n=new nt,r=[],i="",o="",s="unknown",a;for await(let g of e)switch(g.type){case"text-delta":{i+=g.text;let T=r.at(-1);if(T?.type==="part"&&T.part.type==="text")T.part.text+=g.text;else r.push({type:"part",part:{type:"text",text:g.text}});break}case"reasoning-delta":{o+=g.text;let T=r.at(-1);if(T?.type==="part"&&T.part.type==="reasoning")T.part.text+=g.text,T.part.redacted=g.redacted??T.part.redacted,T.part.metadata=g.metadata??T.part.metadata;else r.push({type:"part",part:{type:"reasoning",text:g.text,redacted:g.redacted,metadata:g.metadata}});break}case"tool-call-delta":{if(g.execution)break;let{key:T,created:k}=n.add(g);if(k)r.push({type:"tool",key:T});break}case"finish":{s=g.reason,a=g.error;break}}let l=new Map((t.tools??[]).map((g)=>[g.name,g.inputSchema])),u=[],d=[],h=[],p;for(let g of r)if(g.type==="tool")p=g.key;for(let g of r){if(g.type==="part"){u.push(g.part);continue}let T=n.finish(g.key,s,g.key===p);if(T.invalid)h.push(T.invalid);if(!T.call)continue;if(u.push(T.call),T.invalid)continue;let k=l.get(T.call.toolName);d.push(k?{...T.call,input:ze(T.call.input,k)}:T.call)}let f=d.length===0&&h.length===0?Ue(i):void 0;return{content:u,toolCalls:d,invalidToolCalls:h,text:i,reasoning:o,finishReason:s,...f?{unparsedToolCall:f}:{},...a?{error:a}:{}}}function os(e,t){if(!t||typeof t!=="object"||Array.isArray(t))return t;if(!e||typeof e!=="object"||Array.isArray(e))return t;return{...e,...t}}function qf(e){if(e.inputText)return e.inputText.length;if(e.inputValue===void 0)return 0;try{return JSON.stringify(e.inputValue)?.length??0}catch{return 0}}function Hf(e,t,n=!1){if(t==="max-tokens"&&n){let s=e.inputValue!==void 0?JSON.stringify(e.inputValue):e.inputText;if(s.trim())return{input:{},invalidInput:tt(s),parseError:`Tool call ${e.toolName??e.toolCallId} was cut off by the output budget: the turn ended at the cap while this call was being written, ${s.length} characters into its arguments, so what arrived may not be all of it, and it was not run. Send the same work in smaller pieces: edit one region per call rather than rewriting the file, and keep each call's arguments short enough to complete.`,reason:"invalid_arguments"}}if(e.inputValue!==void 0)return{input:e.inputValue,invalidInput:tt(JSON.stringify(e.inputValue))};if(!e.inputText.trim())return{input:{},invalidInput:{}};let r=Wf(e.inputText);if(r.ok)return{input:r.value,invalidInput:tt(e.inputText)};let o=t==="max-tokens"?`was cut off by the output budget before its arguments finished: the turn ended at the cap with ${e.inputText.length} characters of arguments written. Nothing is wrong with the payload you were writing -- there was no room left to finish it. Send the same work in smaller pieces: edit one region per call rather than rewriting the file, and keep each call's arguments short enough to complete.`:`emitted invalid JSON arguments: ${r.error}`;return{input:{},invalidInput:tt(e.inputText,r.error),parseError:`Tool call ${e.toolName??e.toolCallId} ${o}`,reason:"invalid_arguments"}}function tt(e,t){if(!e.trim())return{};return t?{rawInputText:e,parseError:t}:{rawInputText:e}}function Wf(e){let t=e.trim();if(!t)return{ok:!1,error:"Tool call arguments were empty."};try{return{ok:!0,value:JSON.parse(t)}}catch{}if(!(t.startsWith("{")||t.startsWith("[")))return{ok:!1,error:"Tool call arguments must be encoded as a JSON object or array."};return{ok:!1,error:"Tool call arguments could not be parsed as JSON. Ensure the outer tool payload is valid JSON and escape embedded quotes/newlines inside string fields."}}function Zf(e,t){if(!e)return t;let n=t.trimStart();if(n.startsWith("{")||n.startsWith("["))return t;return e+t}var Vf=2000,as=!0;function Gf(e){as=e}function Un(){return as}var Dn="intent";function ls(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ss(e){if(e.length===0)return;let t=[...e].sort((n,r)=>r.length-n.length).map(ls).join("|");return new RegExp(`[,{"'=>]\\s*(?:${t})["']?\\s*[:=><]`)}function Kf(e){if(e.length===0)return;let t=[...e].sort((n,r)=>r.length-n.length).map(ls).join("|");return new RegExp(`(?<![A-Za-z0-9_])(?:${t})(?![A-Za-z0-9_])`,"g")}class Fn{maxChars;calls=new Map;intentKey;otherKey;toolName;tailChars;constructor(e){this.maxChars=e?.maxChars??2000;let t=[...new Set(e?.argumentNames??[])].filter((r)=>r.length>0&&r!==Dn);this.otherKey=ss(t),this.intentKey=this.otherKey?ss([Dn]):void 0;let n=[...new Set(e?.toolNames??[])].filter((r)=>r.length>0);this.toolName=Kf(n),this.tailChars=Math.max(Dn.length,...t.map((r)=>r.length),...n.map((r)=>r.length))+8}push(e,t,n){if(!this.intentKey||!this.otherKey||t.length===0)return;let r=this.calls.get(e);if(!r)r={phase:"seeking",tail:"",chars:0},this.calls.set(e,r);if(n)r.toolName=n,r.named=!0;if(r.phase==="closed")return;let i=r.tail+t,o=t.length;if(r.phase==="seeking"){let s=this.intentKey.exec(i);if(!r.named&&this.toolName){let a=s?i.slice(0,s.index):i;for(let l of a.matchAll(this.toolName))r.toolName=l[0]}if(!s){r.tail=i.slice(-this.tailChars);return}r.phase="counting",i=i.slice(s.index+s[0].length),o=i.length}if(this.otherKey.test(i)){r.phase="closed",r.tail="";return}if(r.chars+=o,r.tail=i.slice(-this.tailChars),r.chars<=this.maxChars)return;return{toolCallId:e,...r.toolName?{toolName:r.toolName}:{},chars:r.chars,maxChars:this.maxChars}}}function us(e){return`(A call to ${e.toolName?`\`${e.toolName}\``:"a tool"} was begun here and cut before it was complete, so nothing ran. Its text is not kept.)`}function cs(e){let t=e.toolName?`\`${e.toolName}\``:"a tool",n=e.maxChars.toLocaleString("en-US");return`[SYSTEM] Your call to ${t} was cut while you were writing it, and nothing ran. Its \`intent\` had passed ${n} characters. \`intent\` is one sentence saying what the call does. Decide what to do before you begin the call, then make the call again with \`intent\` as that one sentence.`}var Qf=Boolean(globalThis.process?.env?.CLINE_TIMING);function eh(e){if(!Qf)return;globalThis.process?.stderr?.write?.(`[timing] ${new Date().toISOString()} ${e}
85
+ `)}var Ut=32000;function th(e,t,n,r,i){let o=r,s="raw";if(!o.trim()){s="parsed";try{o=JSON.stringify(i)??""}catch{o=String(i)}}let a=o.replace(/\r?\n/g,"\\n"),l=Math.floor(Ut*0.75),u=a.length<=Ut?a:`${a.slice(0,l)} …[${a.length-Ut} characters not logged]… ${a.slice(-(Ut-l))}`;return`[tool-args] iter=${e} ${t} id=${n} ${s} chars=${a.length} ${u}`}var nh="Model reached the maximum output token limit before completing the turn",rh=2,ih=2000,oh="[an image was here; the vision model could not describe it, and this model cannot read images. Work from what the surrounding text says about it, or ask for the detail you need.]",sh="[image omitted — this model does not accept image input; the text above is what the tool reported]";function ah(e){let t=typeof e.image==="string"?e.image:e.data;if(typeof t==="string")return t.length>0?t:void 0;let n=e.image instanceof Uint8Array?e.image:e.image instanceof ArrayBuffer?new Uint8Array(e.image):void 0;if(!n||n.byteLength===0)return;return Buffer.from(n).toString("base64")}var lh=8000,ps="[SYSTEM] Your last reply hit the per-turn output limit before you finished, so it was discarded — none of it, including your reasoning, is in this conversation. "+"Do not try to reproduce it. Take the smallest useful next step instead: make one tool call, or write one short paragraph. If the work you were planning does not fit in one reply, do the part that fits, call the tools it needs, and continue in the next turn.";function uh(e){if(!Array.isArray(e)||e.length===0)return;let t=e.filter((r)=>typeof r==="object"&&r!==null&&typeof r.chars==="number");if(t.length===0)return;return`It ended while you were writing a call to ${t.map((r)=>`\`${r.toolName??"a tool"}\` (${r.chars.toLocaleString("en-US")} characters of arguments written)`).join(", ")}. That call was not run, so it changed nothing. If it was one large edit or file, split it into smaller calls.`}var ch="And what that reasoning had established about the problem itself:",dh="Before it was discarded, your reasoning was condensed into the note below. It is what you had worked out when you ran out of room. Continue from it rather than repeating it. It is a record of your thinking, not an observation of the workspace: where it disagrees with a tool result in this conversation, the tool result is what is true and the note is out of date.",ph="[SYSTEM] Your answer has been passed on. That message came in while you were working, so it did not replace the task you were given — "+"the work you were doing when it arrived is still unfinished. Take that work up again from where you left off, unless the message told you to change course or to stop.",fh="[SYSTEM] Your last reply ran out of room before any of it was delivered, so it was discarded — none of it, including your reasoning, is in this conversation. "+"Do not try to reproduce it. Take the smallest useful next step instead: make one tool call, or write one short paragraph. If the work you were planning does not fit in one reply, do the part that fits, call the tools it needs, and continue in the next turn.",hh="[SYSTEM] Your last reply was thinking only: no answer and no tool call arrived. End your thinking, then either make one tool call or write your answer. Keep the thinking short.",mh="[SYSTEM] Your last reply ended inside your thinking: the tool call you wrote there was part of the thinking, so it never ran and nothing was changed by it. Close your thinking first, then send that one call again as an actual tool call. Keep the thinking short.",fs=3,gh=2,yh=1024,vh=/<\/?tool_call>|<\/function>|<function=|<\/parameter>/;function bh(e){let t="";for(let n of e.content){if(n.type==="reasoning"){let r=n.text;t+=typeof r==="string"?r:"";continue}if(n.type==="text"){if(n.text?.trim())return;continue}return}return t.trim()?{toolCallInThinking:vh.test(t)}:void 0}var Th="[SYSTEM] Your last tool call did not parse, so it never ran and nothing was changed by it. "+"The text you wrote before it is still here and still correct — the call around it was malformed, most often because it was cut short. "+"Send that one call again, complete, and nothing else in this reply. If it carries a large argument, make the argument smaller rather than sending the same one again: name a line range instead of a whole file, or split the work across two calls.";function wh(e){if(e?.reason!=="swallowed_key")return Th;let t=e.tool?`\`${e.tool}\` call`:"tool call",n=e.key?`ran on into \`${e.key}\`, so the parser read \`${e.key}\` and what followed as part of that value`:"ran on into the next argument, so the parser read that argument as part of the value";return`[SYSTEM] Your last ${t} was rejected before it ran, and nothing was changed by it. A string argument in it never closed: it ${n}. This happens when a string argument that contains code is ended with a character from that code, such as a backtick or a quote, instead of the tool-call format's own string delimiter. Send that one call again, complete, and nothing else in this reply, with every string argument closed by the format's delimiter.`}var _h=2,kh=1,vs=3,bs=2000,jn=3,Eh=1000,Ah=15000,xh="Model returned no content because the response was blocked by a content filter. Retrying is unlikely to help — try rephrasing the request.",Ih="The request exceeds the model's context window and there is no conversation history to compact — the system prompt, tools, and current input alone are too large. Reduce attached content or switch to a model with a larger context window.",Ch="The conversation still exceeds the model's context window after compacting it. Start a new session or switch to a model with a larger context window.",Sh="The conversation exceeds the model's context window. Compact the conversation, start a new session, or switch to a model with a larger context window.";class Be extends Error{constructor(e,t){super(t?.trim()?`${e} (provider reported: ${t.trim()})`:e);this.name="ContextWindowOverflowError"}}function xe(e,t=8){return`${e}_${Xf(t)}`}function Rh(e){return e.model!==void 0}function Oh(e){if(Rh(e))return e;let{providerId:t,modelId:n,apiKey:r,baseUrl:i,headers:o,options:s,...a}=e,u=Jf({providerConfigs:[{providerId:t,apiKey:r,baseUrl:i,headers:o,options:s}],telemetry:a.telemetry}).createAgentModel({providerId:t,modelId:n}),d=a.messageModelInfo??{id:n,provider:t};return{...a,model:u,messageModelInfo:d}}function Nh(e,t){return{...t?.["*"]??{},...t?.[e]??{}}}function Hn(e){try{return JSON.stringify(e).length}catch{return String(e).length}}function Mh(e){if(typeof e==="string")return e.length;return Hn(e)}function Ph(e){let t=e.systemPrompt?.length??0,n=0,r=0,i=0;for(let o of e.messages)for(let s of o.content)switch(s.type){case"text":t+=s.text.length;break;case"reasoning":t+=s.text.length;break;case"file":t+=s.content.length;break;case"tool-call":t+=Hn(s.input);break;case"tool-result":{let a=Mh(s.output);n+=1,r+=a,i=Math.max(i,a),t+=a;break}}return{messageCount:e.messages.length,toolSchemaCount:e.tools.length,systemPromptChars:e.systemPrompt?.length??0,requestJsonChars:Hn({systemPrompt:e.systemPrompt,messages:e.messages,tools:e.tools,options:e.options}),visibleTextChars:t,estimatedTextTokens:Po(t),toolResultCount:n,toolResultChars:r,maxToolResultChars:i}}class Wn extends Error{constructor(e){super(`Agent runtime exceeded maxIterations (${e})`);this.name="MaxIterationsReachedError"}}class Ft extends Error{reason;constructor(e){super(e??"Run stopped by runtime control");this.name="ControlledStopError",this.reason=e}}class Ie extends Error{reason;constructor(e){let t=typeof e==="string"?e:e instanceof Error?e.message:e===void 0?"Run aborted":String(e);super(t);this.name="AgentRuntimeAbortError",this.reason=e}}var Bn={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0};function we(e,t,n){return{id:xe("msg"),role:e,content:t,createdAt:Date.now(),metadata:n}}function fe(e){return{...e}}var $h={_:"__",'"':"_q_","<":"_lt_",">":"_gt_"};function hs(e){return e.replace(/[_"<>]/g,(t)=>$h[t])}function qn(e,t){let n=[`source="${e.source}"`];if("toolCall"in e)n.push(`tool_name="${hs(e.toolCall.toolName)}"`,`tool_call_id="${hs(e.toolCall.toolCallId)}"`);let r=t.trim().replace(/<(\/?)hook_context/gi,"<\\$1hook_context");return`<hook_context ${n.join(" ")}>
86
+ ${r}
87
+ </hook_context>`}function te(e){return e.map((t)=>({...t,content:t.content.map((n)=>({...n})),metadata:t.metadata?{...t.metadata}:void 0,modelInfo:t.modelInfo?{...t.modelInfo}:void 0,metrics:t.metrics?{...t.metrics}:void 0}))}function Lh(e,t){let n=Math.max(0,(t.inputTokens??0)-(e.inputTokens??0)),r=Math.max(0,(t.outputTokens??0)-(e.outputTokens??0)),i=Math.max(0,(t.cacheReadTokens??0)-(e.cacheReadTokens??0)),o=Math.max(0,(t.cacheWriteTokens??0)-(e.cacheWriteTokens??0)),s=Math.max(0,(t.reasoningTokenCount??0)-(e.reasoningTokenCount??0)),a=e.totalCost??0,l=t.totalCost??0,u=Math.max(0,l-a);if(n===0&&r===0&&i===0&&o===0&&s===0&&u===0)return;return{inputTokens:n>0?n:0,outputTokens:r>0?r:0,cacheReadTokens:i>0?i:0,cacheWriteTokens:o>0?o:0,...s>0?{reasoningTokenCount:s}:{},...u>0?{cost:u}:{}}}function zh(e){return e.options?.thinking===!1}function je(e){if(!e)return"";return e.content.filter((t)=>t.type==="text").map((t)=>t.text).join("")}function ms(e){if(!e)return"";let t=[];for(let n of e.content){if(n.type!=="reasoning")continue;let r=n.text;if(typeof r==="string"&&r.length>0)t.push(r)}return t.join(`
95
88
 
96
- `)}function Pp(e){if(!e)return 0;return e.content.reduce((t,n)=>{if(n.type!=="reasoning")return t;let i=n.text;return t+(typeof i==="string"?i.length:0)},0)}function to(e){let t=e?.content.find((n)=>n.type==="tool-result");if(!t||t.isError)return"";if(typeof t.output==="string")return t.output;try{return JSON.stringify(t.output)}catch{return String(t.output)}}function $p(e){if(typeof e==="string")return[de("user",[{type:"text",text:e}])];if(Array.isArray(e))return Y(e);return Y([e])}var Lp=8;function zp(e){if(e.toolExecution==="sequential")return 1;let t=e.maxParallelToolCalls;if(typeof t==="number"&&Number.isFinite(t))return Math.max(1,Math.floor(t));return Lp}class qe{config;listeners=new Set;tools=new Map;hooks={beforeRun:[],afterRun:[],beforeModel:[],afterModel:[],beforeTool:[],afterTool:[],onEvent:[]};pendingHookContexts=[];state={agentId:"",agentRole:void 0,parentAgentId:void 0,runId:void 0,status:"idle",iteration:0,messages:[],pendingToolCalls:[],usage:oe(tn),lastRequestTimings:void 0,lastError:void 0,lastErrorClass:void 0,lastRequestInputTokens:0,lastErrorRetryable:void 0,lastErrorReported:!1,lastFinishReason:void 0};lastToolCallRejection;overflowRecoveryAttempted=!1;lastRequestTokens;compactBeforeNextTurn=!1;imageRecoveryAttempted=!1;consecutiveNoToolCallNudges=0;noToolCallNudgeAsked=!1;calledToolThisRun=!1;stoppedForUserBy;hasCalledAnyTool=!1;consecutiveNoToolCallTurns=0;noToolCallStreakReasoningChars=0;nonConvergenceNudgeSpent=!1;lastNudgedUnreadableCall;intentNudgeSpent=!1;repetitionNudger;repetitionNudgerBuilt=!1;repetitionNudges=new WeakMap;announcedRepetitionRemoval=new WeakSet;unreadableCalls=new WeakMap;unreadableCallFingerprints=new WeakMap;steerAwaitingResume=!1;consecutiveMaxTokensRetries=0;toolCallParseRetries=0;thinkingOnlyRetries=0;truncatedOutputCapTokens;initialization;abortController;reasoningLoopStreak=0;pendingToolIntentNudge;lastIssuedRequest;toolIntentCutStreak=0;modelSteerController;telemetryProviderId;telemetryModelId;constructor(e){this.telemetryProviderId=V(e.messageModelInfo?.provider)??("providerId"in e?V(e.providerId):void 0),this.telemetryModelId=V(e.messageModelInfo?.id)??("modelId"in e?V(e.modelId):void 0);let t=xp(e),n=zp(t);this.config={...t,toolExecution:n>1?"parallel":"sequential",maxParallelToolCalls:n},this.state.agentId=t.agentId??ye("agent"),this.state.agentRole=t.agentRole,this.state.parentAgentId=t.parentAgentId,this.state.messages=Y(t.initialMessages??[])}async run(e){return this.execute(e)}async continue(e){return this.execute(e)}notifyPendingUserMessage(){this.modelSteerController?.abort()}abort(e){if(!this.abortController)return;if(this.abortController.signal.aborted)return;let t=e instanceof ve?e:new ve(e);this.state.lastError=t.message,this.captureTaskLifecycle(Ar,{error:t}),this.abortController.abort(t)}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}restore(e){this.abort("Agent state restored"),this.state.runId=void 0,this.state.status="idle",this.state.iteration=0,this.state.pendingToolCalls=[],this.state.usage=oe(tn),this.state.lastError=void 0,this.state.lastErrorClass=void 0,this.state.lastErrorRetryable=void 0,this.state.lastErrorReported=!1,this.state.messages=Y(e),this.config={...this.config,initialMessages:Y(e)}}snapshot(){let e=[...this.state.messages],t;return{agentId:this.state.agentId,agentRole:this.state.agentRole,parentAgentId:this.state.parentAgentId,conversationId:this.config.conversationId?.trim()||void 0,runId:this.state.runId,status:this.state.status,iteration:this.state.iteration,get messages(){return t??=Y(e),t},pendingToolCalls:[...this.state.pendingToolCalls],usage:oe(this.state.usage),lastError:this.state.lastError,lastErrorClass:this.state.lastErrorClass}}async ensureInitialized(){this.initialization??=this.initialize(),await this.initialization}async initialize(){this.registerHooks(this.config.hooks);for(let e of this.config.tools??[])this.tools.set(e.name,e);for(let e of this.config.plugins??[]){let t=await e.setup?.({agentId:this.state.agentId,agentRole:this.state.agentRole,systemPrompt:this.config.systemPrompt});for(let n of t?.tools??[])this.tools.set(n.name,n);this.registerHooks(t?.hooks)}}registerHooks(e){if(!e)return;if(e.beforeRun)this.hooks.beforeRun.push(e.beforeRun);if(e.afterRun)this.hooks.afterRun.push(e.afterRun);if(e.beforeModel)this.hooks.beforeModel.push(e.beforeModel);if(e.afterModel)this.hooks.afterModel.push(e.afterModel);if(e.beforeTool)this.hooks.beforeTool.push(e.beforeTool);if(e.afterTool)this.hooks.afterTool.push(e.afterTool);if(e.onEvent)this.hooks.onEvent.push(e.onEvent)}getRequiredCompletionToolNames(){if(this.config.completionPolicy?.requireCompletionTool!==!0)return[];return[...this.tools.values()].filter((e)=>e.lifecycle?.completesRun===!0).map((e)=>e.name).sort()}getCompletionToolReminderMessage(){let e=this.getRequiredCompletionToolNames();if(e.length===0)return;return`[SYSTEM] This run is not complete until you call one of these terminal completion tools: ${e.join(", ")}. Continue working if requirements are not met. If the task is complete, call the appropriate terminal completion tool now.`}async runCompletionBoundary(e,t=!1){let n=this.config.completionPolicy?.onCompletionAttempt;if(!n)return;let i=await n({text:e||void 0,forced:t});return i&&i.length>0?i:void 0}getCompletionReminderMessages(){let e=this.config.completionPolicy?.completionGuard?.();return{messages:[this.getCompletionToolReminderMessage(),e].filter((t)=>Boolean(t)),guardAsked:Boolean(e)}}async getNoToolCallNudgeMessage(e,t=!1,n){let i=this.config.completionPolicy?.maxNoToolCallNudges??0;if(this.consecutiveNoToolCallNudges>=i)return;let r=n??Se(e);if(r)return Bt(r);let o=await this.config.completionPolicy?.describeUnstartedWork?.();if(t&&!o)return;if(this.noToolCallNudgeAsked&&this.consecutiveNoToolCallNudges===0&&!o&&fr(e))return;if(this.calledToolThisRun&&this.consecutiveNoToolCallNudges===0&&!this.noToolCallNudgeAsked&&!o&&(gr(e)||this.stoppedForUserBy!==void 0&&yr(e)))return;if(this.config.completionPolicy?.strongNudges===!1&&!o&&!this.hasCalledAnyTool&&!ft(e))return;let s=this.tools.has("ask_question")?Ft+lr:Ft;return o?s+o:s}repetitionNudgeFor(e){if(!this.repetitionNudgerBuilt){this.repetitionNudgerBuilt=!0;let r=this.config.reasoningRepetition;this.repetitionNudger=r===!1?void 0:Gt({...ge,...r})}if(!e)return;let t=this.repetitionNudges.get(e);if(t)return t.nudge;let n=eo(e),i=n?this.repetitionNudger?.inspect(n,this.state.iteration):void 0;return this.repetitionNudges.set(e,{nudge:i}),i}replaceSpoiledContent(e){if(e.role!=="assistant")return;let t,n={kinds:[],removedChars:0},i=[...e.content],r=eo(e);if(r){this.repetitionNudgeFor(e);let c=e.metadata?.reasoningLoop,d=this.config.reasoningRepetition,y={...ge,...d||{}},p=d===!1?void 0:yt(r,y),v=c?"it collapsed into repeating itself and was cut":p&&vt(p,y)?`it repeated one passage ${p.maxRepeat} times`:void 0;if(v){let b=`[SYSTEM] The reasoning of this turn was removed: ${v}. Only what the turn did is kept.`,w=i.findIndex((B)=>B.type==="reasoning"),F=i.filter((B)=>B.type!=="reasoning");if(F.splice(Math.max(0,w),0,{type:"reasoning",text:b}),i.splice(0,i.length,...F),n.kinds.push("reasoning_loop"),n.removedChars+=r.length,this.recordCut({channel:"reasoning",cause:c?"reasoning_loop":"reasoning_repetition",...c?{verdict:c}:{},text:r}),!c&&p){let B=this.repetitionNudges.get(e)?.nudge;t=`the reasoning repeated one passage ${p.maxRepeat} times — removed from the conversation${B?", asking for a different approach":""}`}this.config.logger?.debug?.(`[reasoning-loop] iter=${this.state.iteration} removed: ${c?`${r.length} chars; cut while streaming (${c.kind}${c.cycles!==void 0?`, ${c.cycles} cycles`:""}); unit: ${JSON.stringify(c.sample.slice(0,400))}`:p?$r(r,p):`${r.length} chars`}`)}}let o=i.some((c)=>c.type==="tool-call"),s=Oe(e),a=o?void 0:Se(s);if(a){this.unreadableCalls.set(e,a),this.unreadableCallFingerprints.set(e,no(s));let c=i.findIndex((p)=>p.type==="text"),d=i.filter((p)=>p.type!=="text");d.splice(c<0?d.length:Math.min(c,d.length),0,{type:"text",text:cr(a)}),i.splice(0,i.length,...d),n.kinds.push("unreadable_tool_call"),n.removedChars+=s.length,this.recordCut({channel:"reply",cause:"unreadable_tool_call",text:s});let y=(p)=>p.replace(/\s+/g," ");this.config.logger?.debug?.(`[unreadable-call] iter=${this.state.iteration} ${s.length} chars; begins: ${y(s.slice(0,400))}${s.length>700?` ...; ends: ${y(s.slice(-300))}`:""}`)}if(n.kinds.length===0)return;this.config.logger?.debug?.(`Replaced spoiled content in an assistant turn (${n.kinds.join(", ")}): ${n.removedChars} chars removed`);let u=e;return u.content=i,u.metadata={...e.metadata??{},spoiledTurn:n},t}nudgesEnabled(){return(this.config.completionPolicy?.maxNoToolCallNudges??0)>0}shouldNudgeNonConvergence(){if(this.nonConvergenceNudgeSpent||!this.nudgesEnabled())return!1;let e=this.config.completionPolicy?.noToolCallTurnStreakLimit??io;return e>0&&this.consecutiveNoToolCallTurns>=e}turnProducedOutputTokens(e){return this.state.usage.outputTokens>e.outputTokens}continuationRoomTokens(){let e=this.state.lastRequestInputTokens,t=qt(this.config.sessionId);if(!(e>0)||!t)return;if(t.contextWindow!==void 0)return Math.max(0,t.contextWindow-e-hp);if(!t.maxTokens)return;let n=Math.max(e,t.estimatedInputTokens??0)+t.maxTokens;return Math.max(0,n-e)}async continueConversation(e,t){let n=new AbortController,i=await this.config.model.stream({...e,messages:[...e.messages,de("user",[{type:"text",text:t.instruction}],{displayRole:"system"})],signal:this.abortController?AbortSignal.any([this.abortController.signal,n.signal]):n.signal,options:{...e.options,maxTokens:t.maxTokens,toolChoice:"none"}}),r="";for await(let o of i){if(o.type==="tool-input-progress"||o.type==="tool-call-delta"&&!o.execution)throw n.abort(),Error(`the model started calling ${o.toolName??"a tool"} instead of answering (tool choice "none" was not enforced)`);if(o.type==="text-delta")r+=o.text;else if(o.type==="usage")this.state.usage.inputTokens+=o.usage.inputTokens??0,this.state.usage.outputTokens+=o.usage.outputTokens??0;else if(o.type==="finish"&&o.reason==="error")throw Error(o.error??"the model call failed")}return{text:r.trim()}}recoversTurnFault(e){if(!this.config.recoverTurnFault)return!1;let t=this.config.recoverTurnFaultKinds;return t===void 0||t.includes(e)}userRequestsInTranscript(){let e=[],t=(n)=>{let i=typeof n==="string"?n.trim():"";if(i&&!e.includes(i))e.push(i)};for(let n of this.state.messages){if(n.role!=="user")continue;let i=n.metadata;if(i?.kind==="compaction_summary"){if(Array.isArray(i.userRequests))for(let r of i.userRequests)t(r);continue}if(i?.userRunSpan===0||n.content.some((r)=>r.type==="tool-result"))continue;t(n.content.filter((r)=>r.type==="text"&&typeof r.text==="string").map((r)=>r.text).join(`
97
- `))}return e}async noteDiscardedReasoning(e,t){let n=this.config.condenseDiscardedReasoning;if(!n){this.config.logger?.debug?.("Discarded turn not condensed: no condenser is installed");return}let i=e.content.filter((o)=>o.type==="reasoning"&&typeof o.text==="string").map((o)=>o.text).join("").trim(),r=e.content.filter((o)=>o.type==="text"&&typeof o.text==="string").map((o)=>o.text).join("").trim();if(this.config.logger?.log?.(`Discarded a turn cut off at the output limit: parts=[${e.content.map((o)=>o.type).join(", ")||"none"}] reasoning=${i.length} chars partialReply=${r.length} chars windowBound=${t}`,{severity:"info"}),!i&&!r){this.config.logger?.log?.(`Discarded turn had nothing to condense: parts=[${e.content.map((o)=>o.type).join(", ")||"none"}] contentLength=${e.content.length}`,{severity:"warn"});return}try{let o=this.lastIssuedRequest,s=this.continuationRoomTokens(),a=this.userRequestsInTranscript(),u=await n({reasoning:i,...r?{text:r}:{},windowBound:t,...a.length>0?{userRequests:a}:{},transcript:this.state.messages,...o?{continueConversation:(y)=>this.continueConversation(o,y)}:{},...s!==void 0?{continuationRoomTokens:s}:{},...this.abortController?{abortSignal:this.abortController.signal}:{}}),c=u?.note?.trim(),d=u?.retrospective?.trim();if(!c&&!d){this.config.logger?.log?.(`Discarded turn was not condensed: the condenser returned nothing for ${i.length} chars of reasoning and ${r.length} chars of partial reply`,{severity:"warn"});return}return this.config.logger?.log?.(`Condensed ${i.length} chars of discarded reasoning into a ${c?.length??0}-char note and a ${d?.length??0}-char retrospective for the retry`,{severity:"info",reasoningChars:i.length,noteChars:c?.length??0,retrospectiveChars:d?.length??0}),{...c?{note:c}:{},...d?{retrospective:d}:{}}}catch(o){if(this.abortController?.signal.aborted){this.config.logger?.log?.("Stopped condensing the discarded reasoning: the run was aborted",{severity:"info"});return}this.config.logger?.log?.("Could not condense the discarded reasoning; retrying without a note",{severity:"warn",errorMessage:o instanceof Error?o.message:String(o)});return}}getRetryOutputCap(){if(this.consecutiveMaxTokensRetries<1||this.truncatedOutputCapTokens===void 0)return;let e=Math.floor(this.truncatedOutputCapTokens/2**this.consecutiveMaxTokensRetries);return Math.max(rp,e)}getMaxTokensRetryBudget(){let e=this.config.completionPolicy?.maxTruncatedTurnRetries;return typeof e==="number"&&Number.isFinite(e)?Math.max(0,Math.floor(e)):Qd}async addUserReminderMessage(e,t){let n=de("user",[{type:"text",text:e}],{userRunSpan:0,displayRole:"system",...t??{}});return this.state.messages.push(n),await this.emit({type:"message-added",snapshot:this.snapshot(),message:n}),n}async execute(e){if(await this.ensureInitialized(),this.state.status==="running")throw Error("Agent runtime is already running");this.abortController=new AbortController,this.state.runId=ye("run"),this.state.status="running",this.state.iteration=0,this.state.pendingToolCalls=[],this.state.lastError=void 0,this.state.lastErrorClass=void 0,this.state.lastErrorRetryable=void 0,this.state.lastErrorReported=!1,this.state.lastFinishReason=void 0,this.state.usage=oe(tn),this.overflowRecoveryAttempted=!1,this.compactBeforeNextTurn=!1,this.imageRecoveryAttempted=!1,this.steerAwaitingResume=!1,this.noToolCallNudgeAsked=!1,this.calledToolThisRun=!1,this.stoppedForUserBy=void 0,this.state.lastRequestInputTokens=0,this.pendingHookContexts=[];try{await this.callBeforeRunHooks(),await this.emit({type:"run-started",snapshot:this.snapshot()});for(let i of e?$p(e):[])this.state.messages.push(i),await this.emit({type:"message-added",snapshot:this.snapshot(),message:i});let t=this.getCompletionToolReminderMessage();if(t)await this.addUserReminderMessage(t);await this.flushPendingHookContexts();let n;while(this.config.maxIterations===void 0||this.state.iteration<this.config.maxIterations){this.throwIfAborted(),this.state.iteration+=1,this.trace(`turn-begin iter=${this.state.iteration}`),await this.emit({type:"turn-started",snapshot:this.snapshot(),iteration:this.state.iteration});let i=oe(this.state.usage);this.resetLastError();let{message:r,finishReason:o,interrupted:s}=await this.generateAssistantMessageWithProviderRetry();if(s&&r.content.length===0){await this.emit({type:"turn-finished",snapshot:this.snapshot(),iteration:this.state.iteration,toolCallCount:0});continue}if(o==="aborted")throw this.normalizeAbortError();if(r.content.length===0){if(o!=="error"&&o!=="content-filter"&&this.turnProducedOutputTokens(i)&&this.consecutiveMaxTokensRetries<this.getMaxTokensRetryBudget()){this.consecutiveMaxTokensRetries+=1,await this.emit({type:"status-notice",snapshot:this.snapshot(),message:"the model produced nothing usable — retrying",metadata:{kind:"empty_turn_recovery",reason:"empty_turn_recovery",phase:"started",iteration:this.state.iteration,attempt:this.consecutiveMaxTokensRetries,finishReason:o}}),await this.addUserReminderMessage(up);continue}if(await this.recoverUnparsableToolCall())continue;if(o==="error")throw this.state.lastFinishReason=o,Error(this.state.lastError??"Model stream failed");if(!this.hasModelToolActivity(r)&&o!=="max-tokens"&&o!=="unknown")throw this.state.lastFinishReason=o,Error(o==="content-filter"?_p:"Model returned empty response")}let a=r.content.filter((p)=>p.type==="tool-call");if(o==="max-tokens"&&a.length===0&&this.consecutiveMaxTokensRetries<this.getMaxTokensRetryBudget()){this.consecutiveMaxTokensRetries+=1;let p=qt(this.config.sessionId);this.compactBeforeNextTurn=p?.windowBound??!0,this.truncatedOutputCapTokens=this.compactBeforeNextTurn?void 0:p?.maxTokens;let v=await this.noteDiscardedReasoning(r,this.compactBeforeNextTurn);await this.emit({type:"status-notice",snapshot:this.snapshot(),message:"output limit reached before the turn finished — retrying",metadata:{kind:"max_tokens_turn_recovery",reason:"max_tokens_turn_recovery",phase:"started",iteration:this.state.iteration,attempt:this.consecutiveMaxTokensRetries,maxAttempts:this.getMaxTokensRetryBudget(),outputCapSource:p?.source??"unknown",...typeof p?.maxTokens==="number"?{capTokens:p.maxTokens}:{},compacting:this.compactBeforeNextTurn}});let b=op(r.metadata?.unfinishedToolCalls),w=b?`${Yr} ${b}`:Yr;await this.addUserReminderMessage(v?[w,...v.note?[ap,v.note]:[],...v.retrospective?[sp,v.retrospective]:[]].join(`
89
+ `)}function Dh(e){if(!e)return 0;return e.content.reduce((t,n)=>{if(n.type!=="reasoning")return t;let r=n.text;return t+(typeof r==="string"?r.length:0)},0)}function gs(e){let t=e?.content.find((n)=>n.type==="tool-result");if(!t||t.isError)return"";if(typeof t.output==="string")return t.output;try{return JSON.stringify(t.output)}catch{return String(t.output)}}function Uh(e){if(typeof e==="string")return[we("user",[{type:"text",text:e}])];if(Array.isArray(e))return te(e);return te([e])}var Fh=8;function jh(e){if(e.toolExecution==="sequential")return 1;let t=e.maxParallelToolCalls;if(typeof t==="number"&&Number.isFinite(t))return Math.max(1,Math.floor(t));return Fh}class rt{config;listeners=new Set;tools=new Map;hooks={beforeRun:[],afterRun:[],beforeModel:[],afterModel:[],beforeTool:[],afterTool:[],onEvent:[]};pendingHookContexts=[];state={agentId:"",agentRole:void 0,parentAgentId:void 0,runId:void 0,status:"idle",iteration:0,messages:[],pendingToolCalls:[],usage:fe(Bn),lastRequestTimings:void 0,lastError:void 0,lastErrorClass:void 0,lastRequestInputTokens:0,lastErrorRetryable:void 0,lastErrorReported:!1,lastFinishReason:void 0};lastToolCallRejection;overflowRecoveryAttempted=!1;lastRequestTokens;compactBeforeNextTurn=!1;imageRecoveryAttempted=!1;consecutiveNoToolCallNudges=0;noToolCallNudgeAsked=!1;calledToolThisRun=!1;stoppedForUserBy;hasCalledAnyTool=!1;consecutiveNoToolCallTurns=0;noToolCallStreakReasoningChars=0;nonConvergenceNudgeSpent=!1;lastNudgedUnreadableCall;intentNudgeSpent=!1;repetitionNudger;repetitionNudgerBuilt=!1;repetitionNudges=new WeakMap;announcedRepetitionRemoval=new WeakSet;unreadableCalls=new WeakMap;unreadableCallFingerprints=new WeakMap;steerAwaitingResume=!1;consecutiveMaxTokensRetries=0;toolCallParseRetries=0;thinkingOnlyRetries=0;truncatedOutputCapTokens;initialization;abortController;reasoningLoopStreak=0;pendingToolIntentNudge;lastIssuedRequest;toolIntentCutStreak=0;modelSteerController;telemetryProviderId;telemetryModelId;constructor(e){this.telemetryProviderId=K(e.messageModelInfo?.provider)??("providerId"in e?K(e.providerId):void 0),this.telemetryModelId=K(e.messageModelInfo?.id)??("modelId"in e?K(e.modelId):void 0);let t=Oh(e),n=jh(t);this.config={...t,toolExecution:n>1?"parallel":"sequential",maxParallelToolCalls:n},this.state.agentId=t.agentId??xe("agent"),this.state.agentRole=t.agentRole,this.state.parentAgentId=t.parentAgentId,this.state.messages=te(t.initialMessages??[])}async run(e){return this.execute(e)}async continue(e){return this.execute(e)}notifyPendingUserMessage(){this.modelSteerController?.abort()}abort(e){if(!this.abortController)return;if(this.abortController.signal.aborted)return;let t=e instanceof Ie?e:new Ie(e);this.state.lastError=t.message,this.captureTaskLifecycle(jo,{error:t}),this.abortController.abort(t)}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}restore(e){this.abort("Agent state restored"),this.state.runId=void 0,this.state.status="idle",this.state.iteration=0,this.state.pendingToolCalls=[],this.state.usage=fe(Bn),this.state.lastError=void 0,this.state.lastErrorClass=void 0,this.state.lastErrorRetryable=void 0,this.state.lastErrorReported=!1,this.state.messages=te(e),this.config={...this.config,initialMessages:te(e)}}snapshot(){let e=[...this.state.messages],t;return{agentId:this.state.agentId,agentRole:this.state.agentRole,parentAgentId:this.state.parentAgentId,conversationId:this.config.conversationId?.trim()||void 0,runId:this.state.runId,status:this.state.status,iteration:this.state.iteration,get messages(){return t??=te(e),t},pendingToolCalls:[...this.state.pendingToolCalls],usage:fe(this.state.usage),lastError:this.state.lastError,lastErrorClass:this.state.lastErrorClass}}async ensureInitialized(){this.initialization??=this.initialize(),await this.initialization}async initialize(){this.registerHooks(this.config.hooks);for(let e of this.config.tools??[])this.tools.set(e.name,e);for(let e of this.config.plugins??[]){let t=await e.setup?.({agentId:this.state.agentId,agentRole:this.state.agentRole,systemPrompt:this.config.systemPrompt});for(let n of t?.tools??[])this.tools.set(n.name,n);this.registerHooks(t?.hooks)}}registerHooks(e){if(!e)return;if(e.beforeRun)this.hooks.beforeRun.push(e.beforeRun);if(e.afterRun)this.hooks.afterRun.push(e.afterRun);if(e.beforeModel)this.hooks.beforeModel.push(e.beforeModel);if(e.afterModel)this.hooks.afterModel.push(e.afterModel);if(e.beforeTool)this.hooks.beforeTool.push(e.beforeTool);if(e.afterTool)this.hooks.afterTool.push(e.afterTool);if(e.onEvent)this.hooks.onEvent.push(e.onEvent)}getRequiredCompletionToolNames(){if(this.config.completionPolicy?.requireCompletionTool!==!0)return[];return[...this.tools.values()].filter((e)=>e.lifecycle?.completesRun===!0).map((e)=>e.name).sort()}getCompletionToolReminderMessage(){let e=this.getRequiredCompletionToolNames();if(e.length===0)return;return`[SYSTEM] This run is not complete until you call one of these terminal completion tools: ${e.join(", ")}. Continue working if requirements are not met. If the task is complete, call the appropriate terminal completion tool now.`}async runCompletionBoundary(e,t=!1){let n=this.config.completionPolicy?.onCompletionAttempt;if(!n)return;let r=await n({text:e||void 0,forced:t});return r&&r.length>0?r:void 0}getCompletionReminderMessages(){let e=this.config.completionPolicy?.completionGuard?.();return{messages:[this.getCompletionToolReminderMessage(),e].filter((t)=>Boolean(t)),guardAsked:Boolean(e)}}async getNoToolCallNudgeMessage(e,t=!1,n){let r=this.config.completionPolicy?.maxNoToolCallNudges??0;if(this.consecutiveNoToolCallNudges>=r)return;let i=n??Ue(e);if(i)return Cn(i);let o=await this.config.completionPolicy?.describeUnstartedWork?.();if(t&&!o)return;if(this.noToolCallNudgeAsked&&this.consecutiveNoToolCallNudges===0&&!o&&So(e))return;if(this.calledToolThisRun&&this.consecutiveNoToolCallNudges===0&&!this.noToolCallNudgeAsked&&!o&&(Oo(e)||this.stoppedForUserBy!==void 0&&No(e)))return;if(this.config.completionPolicy?.strongNudges===!1&&!o&&!this.hasCalledAnyTool&&!Pt(e))return;let s=this.tools.has("ask_question")?In+ko:In;return o?s+o:s}repetitionNudgeFor(e){if(!this.repetitionNudgerBuilt){this.repetitionNudgerBuilt=!0;let i=this.config.reasoningRepetition;this.repetitionNudger=i===!1?void 0:$n({...Ae,...i})}if(!e)return;let t=this.repetitionNudges.get(e);if(t)return t.nudge;let n=ms(e),r=n?this.repetitionNudger?.inspect(n,this.state.iteration):void 0;return this.repetitionNudges.set(e,{nudge:r}),r}replaceSpoiledContent(e){if(e.role!=="assistant")return;let t,n={kinds:[],removedChars:0},r=[...e.content],i=ms(e);if(i){this.repetitionNudgeFor(e);let u=e.metadata?.reasoningLoop,d=this.config.reasoningRepetition,h={...Ae,...d||{}},p=d===!1?void 0:zt(i,h),f=u?"it collapsed into repeating itself and was cut":p&&Dt(p,h)?`it repeated one passage ${p.maxRepeat} times`:void 0;if(f){let g=`[SYSTEM] The reasoning of this turn was removed: ${f}. Only what the turn did is kept.`,T=r.findIndex((_)=>_.type==="reasoning"),k=r.filter((_)=>_.type!=="reasoning");if(k.splice(Math.max(0,T),0,{type:"reasoning",text:g}),r.splice(0,r.length,...k),n.kinds.push("reasoning_loop"),n.removedChars+=i.length,this.recordCut({channel:"reasoning",cause:u?"reasoning_loop":"reasoning_repetition",...u?{verdict:u}:{},text:i}),!u&&p){let _=this.repetitionNudges.get(e)?.nudge;t=`the reasoning repeated one passage ${p.maxRepeat} times — removed from the conversation${_?", asking for a different approach":""}`}this.config.logger?.debug?.(`[reasoning-loop] iter=${this.state.iteration} removed: ${u?`${i.length} chars; cut while streaming (${u.kind}${u.cycles!==void 0?`, ${u.cycles} cycles`:""}); unit: ${JSON.stringify(u.sample.slice(0,400))}`:p?Jo(i,p):`${i.length} chars`}`)}}let o=r.some((u)=>u.type==="tool-call"),s=je(e),a=o?void 0:Ue(s);if(a){this.unreadableCalls.set(e,a),this.unreadableCallFingerprints.set(e,ys(s));let u=r.findIndex((p)=>p.type==="text"),d=r.filter((p)=>p.type!=="text");d.splice(u<0?d.length:Math.min(u,d.length),0,{type:"text",text:Ao(a)}),r.splice(0,r.length,...d),n.kinds.push("unreadable_tool_call"),n.removedChars+=s.length,this.recordCut({channel:"reply",cause:"unreadable_tool_call",text:s});let h=(p)=>p.replace(/\s+/g," ");this.config.logger?.debug?.(`[unreadable-call] iter=${this.state.iteration} ${s.length} chars; begins: ${h(s.slice(0,400))}${s.length>700?` ...; ends: ${h(s.slice(-300))}`:""}`)}if(n.kinds.length===0)return;this.config.logger?.debug?.(`Replaced spoiled content in an assistant turn (${n.kinds.join(", ")}): ${n.removedChars} chars removed`);let l=e;return l.content=r,l.metadata={...e.metadata??{},spoiledTurn:n},t}nudgesEnabled(){return(this.config.completionPolicy?.maxNoToolCallNudges??0)>0}shouldNudgeNonConvergence(){if(this.nonConvergenceNudgeSpent||!this.nudgesEnabled())return!1;let e=this.config.completionPolicy?.noToolCallTurnStreakLimit??vs;return e>0&&this.consecutiveNoToolCallTurns>=e}turnProducedOutputTokens(e){return this.state.usage.outputTokens>e.outputTokens}continuationRoomTokens(){let e=this.state.lastRequestInputTokens,t=Rn(this.config.sessionId);if(!(e>0)||!t)return;if(t.contextWindow!==void 0)return Math.max(0,t.contextWindow-e-yh);if(!t.maxTokens)return;let n=Math.max(e,t.estimatedInputTokens??0)+t.maxTokens;return Math.max(0,n-e)}async continueConversation(e,t){let n=new AbortController,r=await this.config.model.stream({...e,messages:[...e.messages,we("user",[{type:"text",text:t.instruction}],{displayRole:"system"})],signal:this.abortController?AbortSignal.any([this.abortController.signal,n.signal]):n.signal,options:{...e.options,maxTokens:t.maxTokens,toolChoice:"none"}}),i="";for await(let o of r){if(o.type==="tool-input-progress"||o.type==="tool-call-delta"&&!o.execution)throw n.abort(),Error(`the model started calling ${o.toolName??"a tool"} instead of answering (tool choice "none" was not enforced)`);if(o.type==="text-delta")i+=o.text;else if(o.type==="usage")this.state.usage.inputTokens+=o.usage.inputTokens??0,this.state.usage.outputTokens+=o.usage.outputTokens??0;else if(o.type==="finish"&&o.reason==="error")throw Error(o.error??"the model call failed")}return{text:i.trim()}}recoversTurnFault(e){if(!this.config.recoverTurnFault)return!1;let t=this.config.recoverTurnFaultKinds;return t===void 0||t.includes(e)}userRequestsInTranscript(){let e=[],t=(n)=>{let r=typeof n==="string"?n.trim():"";if(r&&!e.includes(r))e.push(r)};for(let n of this.state.messages){if(n.role!=="user")continue;let r=n.metadata;if(r?.kind==="compaction_summary"){if(Array.isArray(r.userRequests))for(let i of r.userRequests)t(i);continue}if(r?.userRunSpan===0||n.content.some((i)=>i.type==="tool-result"))continue;t(n.content.filter((i)=>i.type==="text"&&typeof i.text==="string").map((i)=>i.text).join(`
90
+ `))}return e}async noteDiscardedReasoning(e,t){let n=this.config.condenseDiscardedReasoning;if(!n){this.config.logger?.debug?.("Discarded turn not condensed: no condenser is installed");return}let r=e.content.filter((o)=>o.type==="reasoning"&&typeof o.text==="string").map((o)=>o.text).join("").trim(),i=e.content.filter((o)=>o.type==="text"&&typeof o.text==="string").map((o)=>o.text).join("").trim();if(this.config.logger?.log?.(`Discarded a turn cut off at the output limit: parts=[${e.content.map((o)=>o.type).join(", ")||"none"}] reasoning=${r.length} chars partialReply=${i.length} chars windowBound=${t}`,{severity:"info"}),!r&&!i){this.config.logger?.log?.(`Discarded turn had nothing to condense: parts=[${e.content.map((o)=>o.type).join(", ")||"none"}] contentLength=${e.content.length}`,{severity:"warn"});return}try{let o=this.lastIssuedRequest,s=this.continuationRoomTokens(),a=this.userRequestsInTranscript(),l=await n({reasoning:r,...i?{text:i}:{},windowBound:t,...a.length>0?{userRequests:a}:{},transcript:this.state.messages,...o?{continueConversation:(h)=>this.continueConversation(o,h)}:{},...s!==void 0?{continuationRoomTokens:s}:{},...this.abortController?{abortSignal:this.abortController.signal}:{}}),u=l?.note?.trim(),d=l?.retrospective?.trim();if(!u&&!d){this.config.logger?.log?.(`Discarded turn was not condensed: the condenser returned nothing for ${r.length} chars of reasoning and ${i.length} chars of partial reply`,{severity:"warn"});return}return this.config.logger?.log?.(`Condensed ${r.length} chars of discarded reasoning into a ${u?.length??0}-char note and a ${d?.length??0}-char retrospective for the retry`,{severity:"info",reasoningChars:r.length,noteChars:u?.length??0,retrospectiveChars:d?.length??0}),{...u?{note:u}:{},...d?{retrospective:d}:{}}}catch(o){if(this.abortController?.signal.aborted){this.config.logger?.log?.("Stopped condensing the discarded reasoning: the run was aborted",{severity:"info"});return}this.config.logger?.log?.("Could not condense the discarded reasoning; retrying without a note",{severity:"warn",errorMessage:o instanceof Error?o.message:String(o)});return}}getRetryOutputCap(){if(this.consecutiveMaxTokensRetries<1||this.truncatedOutputCapTokens===void 0)return;let e=Math.floor(this.truncatedOutputCapTokens/2**this.consecutiveMaxTokensRetries);return Math.max(lh,e)}getMaxTokensRetryBudget(){let e=this.config.completionPolicy?.maxTruncatedTurnRetries;return typeof e==="number"&&Number.isFinite(e)?Math.max(0,Math.floor(e)):rh}async addUserReminderMessage(e,t){let n=we("user",[{type:"text",text:e}],{userRunSpan:0,displayRole:"system",...t??{}});return this.state.messages.push(n),await this.emit({type:"message-added",snapshot:this.snapshot(),message:n}),n}async execute(e){if(await this.ensureInitialized(),this.state.status==="running")throw Error("Agent runtime is already running");this.abortController=new AbortController,this.state.runId=xe("run"),this.state.status="running",this.state.iteration=0,this.state.pendingToolCalls=[],this.state.lastError=void 0,this.state.lastErrorClass=void 0,this.state.lastErrorRetryable=void 0,this.state.lastErrorReported=!1,this.state.lastFinishReason=void 0,this.state.usage=fe(Bn),this.overflowRecoveryAttempted=!1,this.compactBeforeNextTurn=!1,this.imageRecoveryAttempted=!1,this.steerAwaitingResume=!1,this.noToolCallNudgeAsked=!1,this.calledToolThisRun=!1,this.stoppedForUserBy=void 0,this.state.lastRequestInputTokens=0,this.pendingHookContexts=[];try{await this.callBeforeRunHooks(),await this.emit({type:"run-started",snapshot:this.snapshot()});for(let r of e?Uh(e):[])this.state.messages.push(r),await this.emit({type:"message-added",snapshot:this.snapshot(),message:r});let t=this.getCompletionToolReminderMessage();if(t)await this.addUserReminderMessage(t);await this.flushPendingHookContexts();let n;while(this.config.maxIterations===void 0||this.state.iteration<this.config.maxIterations){this.throwIfAborted(),this.state.iteration+=1,this.trace(`turn-begin iter=${this.state.iteration}`),await this.emit({type:"turn-started",snapshot:this.snapshot(),iteration:this.state.iteration});let r=fe(this.state.usage);this.resetLastError();let{message:i,finishReason:o,interrupted:s}=await this.generateAssistantMessageWithProviderRetry();if(s&&i.content.length===0){await this.emit({type:"turn-finished",snapshot:this.snapshot(),iteration:this.state.iteration,toolCallCount:0});continue}if(o==="aborted")throw this.normalizeAbortError();if(i.content.length===0){if(o!=="error"&&o!=="content-filter"&&this.turnProducedOutputTokens(r)&&this.consecutiveMaxTokensRetries<this.getMaxTokensRetryBudget()){this.consecutiveMaxTokensRetries+=1,await this.emit({type:"status-notice",snapshot:this.snapshot(),message:"the model produced nothing usable — retrying",metadata:{kind:"empty_turn_recovery",reason:"empty_turn_recovery",phase:"started",iteration:this.state.iteration,attempt:this.consecutiveMaxTokensRetries,finishReason:o}}),await this.addUserReminderMessage(fh);continue}if(await this.recoverUnparsableToolCall())continue;if(o==="error")throw this.state.lastFinishReason=o,Error(this.state.lastError??"Model stream failed");if(!this.hasModelToolActivity(i)&&o!=="max-tokens"&&o!=="unknown")throw this.state.lastFinishReason=o,Error(o==="content-filter"?xh:"Model returned empty response")}let a=i.content.filter((p)=>p.type==="tool-call");if(o==="max-tokens"&&a.length===0&&this.consecutiveMaxTokensRetries<this.getMaxTokensRetryBudget()){this.consecutiveMaxTokensRetries+=1;let p=Rn(this.config.sessionId);this.compactBeforeNextTurn=p?.windowBound??!0,this.truncatedOutputCapTokens=this.compactBeforeNextTurn?void 0:p?.maxTokens;let f=await this.noteDiscardedReasoning(i,this.compactBeforeNextTurn);await this.emit({type:"status-notice",snapshot:this.snapshot(),message:"output limit reached before the turn finished — retrying",metadata:{kind:"max_tokens_turn_recovery",reason:"max_tokens_turn_recovery",phase:"started",iteration:this.state.iteration,attempt:this.consecutiveMaxTokensRetries,maxAttempts:this.getMaxTokensRetryBudget(),outputCapSource:p?.source??"unknown",...typeof p?.maxTokens==="number"?{capTokens:p.maxTokens}:{},compacting:this.compactBeforeNextTurn}});let g=uh(i.metadata?.unfinishedToolCalls),T=g?`${ps} ${g}`:ps;await this.addUserReminderMessage(f?[T,...f.note?[dh,f.note]:[],...f.retrospective?[ch,f.retrospective]:[]].join(`
98
91
 
99
- `):w,{noticeKind:"max_tokens_turn_recovery",attempt:this.consecutiveMaxTokensRetries,maxAttempts:this.getMaxTokensRetryBudget(),capSource:p?.source??"unknown",...typeof p?.maxTokens==="number"?{capTokens:p.maxTokens}:{},compacting:this.compactBeforeNextTurn});continue}if(n=r,await this.recordAssistantMessage(r,o),s){await this.emit({type:"turn-finished",snapshot:this.snapshot(),iteration:this.state.iteration,toolCallCount:0});continue}if(o==="unknown"&&a.length===0)throw this.state.lastFinishReason=o,Error("Model ended without a recognized finish reason");if(o==="max-tokens"&&a.length===0)throw this.state.lastFinishReason=o,Error(Xd);if(o==="error"&&a.length===0){if(await this.recoverUnparsableToolCall())continue;throw this.state.lastFinishReason=o,Error(this.state.lastError??"Model stream failed")}if(this.toolCallParseRetries=0,this.state.pendingToolCalls=a.map((p)=>p.toolCallId),a.length===0){await this.emit({type:"turn-finished",snapshot:this.snapshot(),iteration:this.state.iteration,toolCallCount:0});let p=Pp(r);if(p>=ro)this.consecutiveNoToolCallTurns+=1,this.noToolCallStreakReasoningChars+=p;else this.consecutiveNoToolCallTurns=0,this.noToolCallStreakReasoningChars=0;if(this.steerAwaitingResume){this.steerAwaitingResume=!1,await this.addUserReminderMessage(lp);continue}if(this.pendingToolIntentNudge){let x=this.pendingToolIntentNudge;this.pendingToolIntentNudge=void 0,await this.addUserReminderMessage(x);continue}let v=[],b=[],w=this.getCompletionReminderMessages();v.push(...w.messages);let F=Oe(n),B=n?this.unreadableCalls.get(n):void 0,H=await this.getNoToolCallNudgeMessage(F,w.guardAsked,B);if(H)this.noToolCallNudgeAsked=!0,this.consecutiveNoToolCallNudges+=1,v.push(H),b.push({nudge:"no_tool_call",detail:{consecutive:this.consecutiveNoToolCallNudges}});let A=this.nudgesEnabled()?B??Se(F):void 0,P=A?(n?this.unreadableCallFingerprints.get(n):void 0)??no(F??""):void 0;if(A&&P!==this.lastNudgedUnreadableCall){this.lastNudgedUnreadableCall=P;let x=Bt(A);if(!v.includes(x))v.push(x);b.push({nudge:"unparsed_tool_call"})}let G=this.intentNudgeSpent||!this.nudgesEnabled()?void 0:ft(F);if(G)this.intentNudgeSpent=!0,v.push(dr(G)),b.push({nudge:"announced_intent"});if(this.shouldNudgeNonConvergence())this.nonConvergenceNudgeSpent=!0,v.push(ur(this.consecutiveNoToolCallTurns,this.noToolCallStreakReasoningChars)),b.push({nudge:"non_convergence",detail:{consecutiveNoToolCallTurns:this.consecutiveNoToolCallTurns,reasoningChars:this.noToolCallStreakReasoningChars}});let se=this.nudgesEnabled()?this.repetitionNudgeFor(r):void 0;if(se)v.push(se),b.push({nudge:"silent_repetition"});if(v.length>0){for(let x of new Set(v))await this.addUserReminderMessage(x);for(let x of b){if(x.nudge==="silent_repetition"&&this.announcedRepetitionRemoval.has(r))continue;await this.emit({type:"status-notice",snapshot:this.snapshot(),message:Up(x.nudge),metadata:{kind:"nudge",reason:"nudge",nudge:x.nudge,iteration:this.state.iteration,...x.detail??{}}})}continue}let be=await this.runCompletionBoundary(Oe(n),this.consecutiveNoToolCallNudges>0);if(be){await this.addUserReminderMessage(be);continue}let ae=r.metadata?.modelToolActivities||this.reasoningLoopStreak>0?void 0:mp(r);if(ae&&this.thinkingOnlyRetries<Xr){this.thinkingOnlyRetries+=1,await this.emit({type:"status-notice",snapshot:this.snapshot(),message:ae.toolCallInThinking?"the model wrote its tool call inside its thinking — asking for it again":"the model's turn was thinking only — asking for an answer",metadata:{kind:"thinking_only_recovery",reason:"thinking_only_recovery",phase:"started",iteration:this.state.iteration,attempt:this.thinkingOnlyRetries,maxAttempts:Xr,toolCallInThinking:ae.toolCallInThinking}}),await this.addUserReminderMessage(ae.toolCallInThinking?dp:cp);continue}let K=this.finishRun("completed",n);return await this.callAfterRunHooks(K),await this.emit({type:"run-finished",snapshot:this.snapshot(),result:K}),K}this.hasCalledAnyTool=!0,this.calledToolThisRun=!0,this.consecutiveNoToolCallNudges=0,this.thinkingOnlyRetries=0,this.consecutiveNoToolCallTurns=0,this.noToolCallStreakReasoningChars=0,this.consecutiveMaxTokensRetries=0,this.truncatedOutputCapTokens=void 0;let u=Date.now();this.trace(`tools-begin iter=${this.state.iteration} n=${a.length} ${a.map((p)=>p.toolName).join(",")}`);let c=await this.executeToolCalls(a);this.trace(`tools-end iter=${this.state.iteration} took=${Date.now()-u}ms`),this.state.pendingToolCalls=[];let d=this.findCompletingToolMessage(a,c)?[]:this.attachTurnNotes(c,n);for(let p of c)this.state.messages.push(p),await this.emit({type:"message-added",snapshot:this.snapshot(),message:p});if(o==="unknown"&&!c.some((p)=>p.content.some((v)=>v.type==="tool-result"&&!v.isError)))throw this.state.lastFinishReason=o,Error("Model ended without a recognized finish reason or successful tool work");await this.flushPendingHookContexts(),await this.emit({type:"turn-finished",snapshot:this.snapshot(),iteration:this.state.iteration,toolCallCount:a.length});let y=this.findCompletingToolMessage(a,c);if(y){let p=await this.runCompletionBoundary(to(y)||Oe(n));if(p){await this.addUserReminderMessage(p);continue}let v=this.finishRun("completed",n,to(y)||void 0);return await this.callAfterRunHooks(v),await this.emit({type:"run-finished",snapshot:this.snapshot(),result:v}),v}for(let p of d)await this.addUserReminderMessage(p)}throw new on(this.config.maxIterations)}catch(t){let n=t instanceof Error?t:Error(String(t)),i=n instanceof Tt,o=this.abortController.signal.aborted||i?"aborted":"failed",s=n instanceof Me?"context_window_exceeded":n.message===this.state.lastError?this.state.lastErrorClass:void 0,a=n.message===this.state.lastError&&this.state.lastErrorReported;this.state.status=o,this.state.lastError=n.message,this.state.lastErrorClass=s,this.state.lastErrorReported=a;let u=this.findLastAssistantMessage(),c={agentId:this.state.agentId,agentRole:this.state.agentRole,runId:this.state.runId??ye("run"),status:o,iterations:this.state.iteration,outputText:Oe(u),messages:Y(this.state.messages),usage:oe(this.state.usage),error:o==="failed"?n:void 0,abortReason:o==="aborted"?n.message:void 0,...o==="failed"&&n instanceof on?{limit:"max_iterations"}:{}};if(this.config.logger?.log?.(`Agent loop caught error (${o}): ${n.name}: ${n.message}`,{severity:o==="failed"?"error":"warn",agentId:this.state.agentId,agentRole:this.state.agentRole,runId:c.runId,status:o,iteration:this.state.iteration,errorName:n.name,errorMessage:n.message,assistantContentPartCount:u?.content.length??0}),await this.callAfterRunHooks(c),o==="failed")await this.emit({type:"run-failed",snapshot:this.snapshot(),error:n,errorClass:s});else await this.emit({type:"run-finished",snapshot:this.snapshot(),result:c});return c}finally{this.abortController=void 0}}async flushPendingHookContexts(){if(this.pendingHookContexts.length===0)return;let e=this.pendingHookContexts.join(`
92
+ `):T,{noticeKind:"max_tokens_turn_recovery",attempt:this.consecutiveMaxTokensRetries,maxAttempts:this.getMaxTokensRetryBudget(),capSource:p?.source??"unknown",...typeof p?.maxTokens==="number"?{capTokens:p.maxTokens}:{},compacting:this.compactBeforeNextTurn});continue}if(n=i,await this.recordAssistantMessage(i,o),s){await this.emit({type:"turn-finished",snapshot:this.snapshot(),iteration:this.state.iteration,toolCallCount:0});continue}if(o==="unknown"&&a.length===0)throw this.state.lastFinishReason=o,Error("Model ended without a recognized finish reason");if(o==="max-tokens"&&a.length===0)throw this.state.lastFinishReason=o,Error(nh);if(o==="error"&&a.length===0){if(await this.recoverUnparsableToolCall())continue;throw this.state.lastFinishReason=o,Error(this.state.lastError??"Model stream failed")}if(this.toolCallParseRetries=0,this.state.pendingToolCalls=a.map((p)=>p.toolCallId),a.length===0){await this.emit({type:"turn-finished",snapshot:this.snapshot(),iteration:this.state.iteration,toolCallCount:0});let p=Dh(i);if(p>=bs)this.consecutiveNoToolCallTurns+=1,this.noToolCallStreakReasoningChars+=p;else this.consecutiveNoToolCallTurns=0,this.noToolCallStreakReasoningChars=0;if(this.steerAwaitingResume){this.steerAwaitingResume=!1,await this.addUserReminderMessage(ph);continue}if(this.pendingToolIntentNudge){let C=this.pendingToolIntentNudge;this.pendingToolIntentNudge=void 0,await this.addUserReminderMessage(C);continue}let f=[],g=[],T=this.getCompletionReminderMessages();f.push(...T.messages);let k=je(n),_=n?this.unreadableCalls.get(n):void 0,B=await this.getNoToolCallNudgeMessage(k,T.guardAsked,_);if(B)this.noToolCallNudgeAsked=!0,this.consecutiveNoToolCallNudges+=1,f.push(B),g.push({nudge:"no_tool_call",detail:{consecutive:this.consecutiveNoToolCallNudges}});let J=this.nudgesEnabled()?_??Ue(k):void 0,P=J?(n?this.unreadableCallFingerprints.get(n):void 0)??ys(k??""):void 0;if(J&&P!==this.lastNudgedUnreadableCall){this.lastNudgedUnreadableCall=P;let C=Cn(J);if(!f.includes(C))f.push(C);g.push({nudge:"unparsed_tool_call"})}let E=this.intentNudgeSpent||!this.nudgesEnabled()?void 0:Pt(k);if(E)this.intentNudgeSpent=!0,f.push(xo(E)),g.push({nudge:"announced_intent"});if(this.shouldNudgeNonConvergence())this.nonConvergenceNudgeSpent=!0,f.push(Eo(this.consecutiveNoToolCallTurns,this.noToolCallStreakReasoningChars)),g.push({nudge:"non_convergence",detail:{consecutiveNoToolCallTurns:this.consecutiveNoToolCallTurns,reasoningChars:this.noToolCallStreakReasoningChars}});let V=this.nudgesEnabled()?this.repetitionNudgeFor(i):void 0;if(V)f.push(V),g.push({nudge:"silent_repetition"});if(f.length>0){for(let C of new Set(f))await this.addUserReminderMessage(C);for(let C of g){if(C.nudge==="silent_repetition"&&this.announcedRepetitionRemoval.has(i))continue;await this.emit({type:"status-notice",snapshot:this.snapshot(),message:qh(C.nudge),metadata:{kind:"nudge",reason:"nudge",nudge:C.nudge,iteration:this.state.iteration,...C.detail??{}}})}continue}let he=await this.runCompletionBoundary(je(n),this.consecutiveNoToolCallNudges>0);if(he){await this.addUserReminderMessage(he);continue}let oe=i.metadata?.modelToolActivities||this.reasoningLoopStreak>0?void 0:bh(i);if(oe&&this.thinkingOnlyRetries<fs){this.thinkingOnlyRetries+=1,await this.emit({type:"status-notice",snapshot:this.snapshot(),message:oe.toolCallInThinking?"the model wrote its tool call inside its thinking — asking for it again":"the model's turn was thinking only — asking for an answer",metadata:{kind:"thinking_only_recovery",reason:"thinking_only_recovery",phase:"started",iteration:this.state.iteration,attempt:this.thinkingOnlyRetries,maxAttempts:fs,toolCallInThinking:oe.toolCallInThinking}}),await this.addUserReminderMessage(oe.toolCallInThinking?mh:hh);continue}let q=this.finishRun("completed",n);return await this.callAfterRunHooks(q),await this.emit({type:"run-finished",snapshot:this.snapshot(),result:q}),q}this.hasCalledAnyTool=!0,this.calledToolThisRun=!0,this.consecutiveNoToolCallNudges=0,this.thinkingOnlyRetries=0,this.consecutiveNoToolCallTurns=0,this.noToolCallStreakReasoningChars=0,this.consecutiveMaxTokensRetries=0,this.truncatedOutputCapTokens=void 0;let l=Date.now();this.trace(`tools-begin iter=${this.state.iteration} n=${a.length} ${a.map((p)=>p.toolName).join(",")}`);let u=await this.executeToolCalls(a);this.trace(`tools-end iter=${this.state.iteration} took=${Date.now()-l}ms`),this.state.pendingToolCalls=[];let d=this.findCompletingToolMessage(a,u)?[]:this.attachTurnNotes(u,n);for(let p of u)this.state.messages.push(p),await this.emit({type:"message-added",snapshot:this.snapshot(),message:p});if(o==="unknown"&&!u.some((p)=>p.content.some((f)=>f.type==="tool-result"&&!f.isError)))throw this.state.lastFinishReason=o,Error("Model ended without a recognized finish reason or successful tool work");await this.flushPendingHookContexts(),await this.emit({type:"turn-finished",snapshot:this.snapshot(),iteration:this.state.iteration,toolCallCount:a.length});let h=this.findCompletingToolMessage(a,u);if(h){let p=await this.runCompletionBoundary(gs(h)||je(n));if(p){await this.addUserReminderMessage(p);continue}let f=this.finishRun("completed",n,gs(h)||void 0);return await this.callAfterRunHooks(f),await this.emit({type:"run-finished",snapshot:this.snapshot(),result:f}),f}for(let p of d)await this.addUserReminderMessage(p)}throw new Wn(this.config.maxIterations)}catch(t){let n=t instanceof Error?t:Error(String(t)),r=n instanceof Ft,o=this.abortController.signal.aborted||r?"aborted":"failed",s=n instanceof Be?"context_window_exceeded":n.message===this.state.lastError?this.state.lastErrorClass:void 0,a=n.message===this.state.lastError&&this.state.lastErrorReported;this.state.status=o,this.state.lastError=n.message,this.state.lastErrorClass=s,this.state.lastErrorReported=a;let l=this.findLastAssistantMessage(),u={agentId:this.state.agentId,agentRole:this.state.agentRole,runId:this.state.runId??xe("run"),status:o,iterations:this.state.iteration,outputText:je(l),messages:te(this.state.messages),usage:fe(this.state.usage),error:o==="failed"?n:void 0,abortReason:o==="aborted"?n.message:void 0,...o==="failed"&&n instanceof Wn?{limit:"max_iterations"}:{}};if(this.config.logger?.log?.(`Agent loop caught error (${o}): ${n.name}: ${n.message}`,{severity:o==="failed"?"error":"warn",agentId:this.state.agentId,agentRole:this.state.agentRole,runId:u.runId,status:o,iteration:this.state.iteration,errorName:n.name,errorMessage:n.message,assistantContentPartCount:l?.content.length??0}),await this.callAfterRunHooks(u),o==="failed")await this.emit({type:"run-failed",snapshot:this.snapshot(),error:n,errorClass:s});else await this.emit({type:"run-finished",snapshot:this.snapshot(),result:u});return u}finally{this.abortController=void 0}}async flushPendingHookContexts(){if(this.pendingHookContexts.length===0)return;let e=this.pendingHookContexts.join(`
100
93
 
101
- `);this.pendingHookContexts=[];let t=de("user",[{type:"text",text:e}],{userRunSpan:0,displayRole:"system"}),n=this.state.messages.at(-1);if(n?.role==="assistant"&&n.content.some((r)=>r.type==="tool-call"))this.state.messages.splice(-1,0,t);else this.state.messages.push(t);await this.emit({type:"message-added",snapshot:this.snapshot(),message:t})}async callBeforeRunHooks(){for(let e of this.hooks.beforeRun){let t=await e({snapshot:this.snapshot()});if(this.applyStopControl(t),t?.appendContext?.trim())this.pendingHookContexts.push(nn({source:"RunStart"},t.appendContext))}}async callAfterRunHooks(e){for(let t of this.hooks.afterRun)await t({snapshot:this.snapshot(),result:e})}async generateAssistantMessageRecoveringFaults(){for(let e=1;;e+=1){let t,n,i=!1;try{t=await this.withProviderErrorRetry(()=>this.generateAssistantMessageWithOverflowRecovery())}catch(p){if(this.abortController?.signal.aborted||p instanceof Tt||p instanceof Me||p instanceof ve)throw p;n=p,i=!0}let r=this.config.recoverTurnFault,o=()=>{if(i)throw n;return t};if(!r)return o();let s,a,u;if(i)s=Ot(n),a=n instanceof Error?n.message:String(n),u=ze(n);else if(t?.finishReason==="error")a=this.state.lastError??"",s=Ie(a,this.state.lastErrorClass),u=Yn(a,this.state.lastErrorClass);else return o();if(!s||!this.recoversTurnFault(s))return o();let c=V(this.config.sessionId),d=this.lastRequestTokens;if(u)this.config.logger?.log?.(`Engine bug: the server evicted session ${c??"(unnamed)"} (agent ${this.state.agentId}) at ${new Date().toISOString()}, holding ${d!==void 0?`${d.toLocaleString("en-US")} tokens (its last completed request)`:"an unknown number of tokens (no request had completed)"}, turn ${this.state.iteration}, attempt ${e}: ${a}; waiting to send it again`,{severity:"warn",kind:"engine_eviction",...c?{sessionId:c}:{},agentId:this.state.agentId,...d!==void 0?{tokensHeld:d}:{},iteration:this.state.iteration,attempt:e});else this.config.logger?.log?.(s==="refusal"?`Turn ${this.state.iteration} queued by the server (retry ${e}): ${Xn(a)}; waiting to send it again`:`Turn ${this.state.iteration} failed on a ${s} fault (attempt ${e}): ${a}; waiting to send it again`,{severity:s==="refusal"?"info":"warn"});await this.emit({type:"status-notice",snapshot:this.snapshot(),message:u?"the server evicted the turn to keep others alive (an engine bug) — waiting, then retrying":s==="transport"?"the server dropped the turn — waiting for it to come back, then retrying":"the server queued the turn — waiting for room, then retrying",metadata:{kind:"turn_fault_recovery",reason:s,...u?{evicted:!0}:{},phase:"started",iteration:this.state.iteration,attempt:e,providerError:a}});let y=!1;try{y=await r({kind:s,message:a,attempt:e,iteration:this.state.iteration,...u?{evicted:!0}:{},...u&&d!==void 0?{tokensHeld:d}:{},...c?{sessionId:c}:{},...this.abortController?.signal?{signal:this.abortController.signal}:{}})}catch{y=!1}if(this.throwIfAborted(),!y)return o()}}async generateAssistantMessageWithProviderRetry(){let e=()=>this.generateAssistantMessageRecoveringFaults(),t=await e();if(t.finishReason!=="unknown"||t.interrupted)return t;if(t.message.content.some((n)=>n.type==="tool-call")||this.hasModelToolActivity(t.message))return t;return await this.recordAssistantMessage(t.message,t.finishReason),await this.addUserReminderMessage("Previous turn ended unexpectedly. Continue from where you left off.",{displayRole:"system"}),this.resetLastError(),await e()}async withProviderErrorRetry(e){let t=0;for(;;){let n=await e();if(t>=en||!this.isRetryableProviderErrorTurn(n))return n;t+=1;let i=this.state.lastError;this.resetLastError();let r=Math.min(Tp*2**(t-1),wp);await this.emit({type:"status-notice",snapshot:this.snapshot(),message:`provider error — retrying (attempt ${t}/${en})`,metadata:{kind:"provider_error_retry",reason:"provider_error_retry",phase:"started",iteration:this.state.iteration,attempt:t,maxRetries:en,delayMs:r,providerError:i}}),await this.abortableDelay(r)}}isRetryableProviderErrorTurn(e){if(e.finishReason!=="error")return!1;if(e.message.content.length>0)return!1;let t=e.message.metadata?.modelToolActivities;if(Array.isArray(t)&&t.length>0)return!1;let n=this.state.lastErrorClass;if(n==="auth"||n==="context_window_exceeded")return!1;let i=Ie(this.state.lastError??"",n);if(i&&this.recoversTurnFault(i))return!1;return this.state.lastErrorRetryable===!0}resetLastError(){this.state.lastError=void 0,this.state.lastErrorClass=void 0,this.state.lastErrorRetryable=void 0,this.state.lastErrorReported=!1}async abortableDelay(e){this.throwIfAborted();let t=this.abortController?.signal;await new Promise((n,i)=>{let r=()=>{clearTimeout(o),i(this.normalizeAbortError())},o=setTimeout(()=>{t?.removeEventListener("abort",r),n()},e);if(t)t.addEventListener("abort",r,{once:!0})})}async generateAssistantMessageWithOverflowRecovery(){if(this.config.alwaysDescribeImages===!0)await this.describeImagesInTranscript();let e=this.compactBeforeNextTurn;this.compactBeforeNextTurn=!1;let t=await this.generateAssistantMessage(e?{overflowRecovery:!0}:void 0);if(this.isRecoverableImageTurn(t))return await this.retryWithoutImages();if(!this.isRecoverableOverflowTurn(t))return t;this.overflowRecoveryAttempted=!0;let n=this.state.lastError;if(!this.config.prepareTurn)throw new Me(Ip,n);await this.emit({type:"status-notice",snapshot:this.snapshot(),message:"context window exceeded — compacting and retrying",metadata:{kind:"context_overflow_recovery",reason:"context_overflow_recovery",phase:"started",iteration:this.state.iteration,providerError:n}});let i=await this.generateAssistantMessage({overflowRecovery:!0,requireSmallerRequest:!0});if(i.finishReason==="error"&&this.state.lastErrorClass==="context_window_exceeded")throw new Me(Ep,this.state.lastError);return i}async recoverUnparsableToolCall(){if(this.state.lastErrorClass!=="tool_call_unparsable"||this.toolCallParseRetries>=vp)return!1;return this.toolCallParseRetries+=1,await this.emit({type:"status-notice",snapshot:this.snapshot(),message:"the model's tool call did not parse — asking for it again",metadata:{kind:"tool_call_parse_recovery",reason:"tool_call_parse_recovery",phase:"started",iteration:this.state.iteration,attempt:this.toolCallParseRetries,providerError:this.state.lastError,...this.lastToolCallRejection?{rejection:this.lastToolCallRejection}:{}}}),await this.addUserReminderMessage(yp(this.lastToolCallRejection)),!0}isRecoverableImageTurn(e){return e.finishReason==="error"&&this.state.lastErrorClass==="image_input_unsupported"&&!this.imageRecoveryAttempted&&this.hasImageContent()}hasImageContent(){return this.state.messages.some((e)=>e.content.some((t)=>t.type==="image"))}async retryWithoutImages(){this.imageRecoveryAttempted=!0;let e=this.state.lastError,t=await this.describeImagesInTranscript(),n=0;for(let i of this.state.messages)for(let r=0;r<i.content.length;r++){if(i.content[r]?.type!=="image")continue;n+=1,i.content[r]={type:"text",text:np}}return this.config.onImageInputUnsupported?.(),await this.emit({type:"status-notice",snapshot:this.snapshot(),message:"model does not accept images — resending without them",metadata:{kind:"image_input_recovery",reason:"image_input_recovery",phase:"started",iteration:this.state.iteration,droppedImages:n,describedImages:t,providerError:e}}),await this.generateAssistantMessage()}async describeImagesInTranscript(){let e=this.config.describeImages;if(!e)return 0;let t=[],n=[];for(let s of this.state.messages){let a=s.content.filter((u)=>u.type==="text").map((u)=>u.text).join(`
102
- `).slice(0,ep);for(let u=0;u<s.content.length;u++){let c=s.content[u];if(c?.type!=="image")continue;let d=ip(c);if(d===void 0)continue;t.push({message:s,index:u}),n.push({image:d,mediaType:c.mediaType,context:a.length>0?a:void 0})}}if(n.length===0)return this.config.logger?.log?.(`Vision describer found no images in ${this.state.messages.length} transcript message(s)`),0;let i=[];try{i=await e(n)}catch(s){this.config.logger?.log?.(`Vision model could not describe ${n.length} image(s): ${s instanceof Error?s.message:String(s)}`,{severity:"warn"})}let r=this.config.modelSupportsImages!==!1,o=0;for(let s=0;s<t.length;s++){let a=i[s]?.trim();if(!a&&r)continue;let u=t[s];u.message.content[u.index]={type:"text",text:a?`[image description, from the vision model]
103
- ${a}`:tp},o+=1}return o}isRecoverableOverflowTurn(e){if(e.finishReason!=="error"||this.state.lastErrorClass!=="context_window_exceeded"||this.overflowRecoveryAttempted)return!1;return!e.message.content.some((t)=>t.type==="tool-call")}hasModelToolActivity(e){let t=e.metadata?.modelToolActivities;return Array.isArray(t)&&t.length>0}async recordAssistantMessage(e,t){let n=this.replaceSpoiledContent(e);if(this.state.messages.push(e),await this.emit({type:"message-added",snapshot:this.snapshot(),message:e}),n)this.announcedRepetitionRemoval.add(e),await this.emit({type:"status-notice",snapshot:this.snapshot(),message:n,metadata:{kind:"reasoning_loop",reason:"reasoning_loop",phase:"removed",iteration:this.state.iteration,nudged:Boolean(this.repetitionNudges.get(e)?.nudge)}});await this.emit({type:"assistant-message",snapshot:this.snapshot(),iteration:this.state.iteration,message:e,finishReason:t})}async generateAssistantMessage(e){let t=new AbortController;this.modelSteerController=t;try{return await this.generateAssistantMessageForRequest(t,e)}finally{this.modelSteerController=void 0}}async prepareModelRequest(e){let t=Tr({distinctId:V(this.config.distinctId),clientName:V(this.config.clientName),clientVersion:V(this.config.clientVersion),clineCoreVersion:V(this.config.clineCoreVersion),sessionId:V(this.config.sessionId),agentId:this.state.agentId,conversationId:V(this.config.conversationId),runId:this.state.runId,iteration:this.state.iteration}),n=this.getRetryOutputCap();if(n!==void 0)this.config.logger?.log?.(`Retrying a truncated turn on a reduced output cap of ${n} tokens (attempt ${this.consecutiveMaxTokensRetries}, was ${this.truncatedOutputCapTokens})`,{severity:"info"});let i={systemPrompt:this.config.systemPrompt,messages:Y(this.state.messages),tools:[...this.tools.values()].map((s)=>({name:s.name,description:s.description,inputSchema:s.inputSchema,...s.readOnly?{readOnly:!0}:{}})),modelTools:this.config.modelTools,signal:this.abortController?.signal,options:jt(this.config.modelOptions,{metadata:t,...n!==void 0?{maxTokens:n}:{}})},r=Date.now(),o=await this.consumePendingUserMessage();if(o)i={...i,messages:[...i.messages,...Y([o])]};i=await this.prepareTurnForModelRequest(i,e),this.throwIfAborted();for(let s of this.hooks.beforeModel){let a=await s({snapshot:this.snapshot(),request:i});if(this.throwIfAborted(),this.applyStopControl(a),a?.messages)i={...i,messages:Y(a.messages)};if(a?.tools)i={...i,tools:[...a.tools]};if(a?.options)i={...i,options:jt(i.options,a.options)}}return this.config.logger?.debug("Agent model request diagnostics",{iteration:this.state.iteration,providerId:"providerId"in this.config&&typeof this.config.providerId==="string"?this.config.providerId:void 0,modelId:"modelId"in this.config&&typeof this.config.modelId==="string"?this.config.modelId:void 0,...Sp(i)}),{request:i,startedAt:r}}async generateAssistantMessageForRequest(e,t){let n=await this.prepareModelRequest(t);return await this.streamPreparedRequest(n,e)}async streamPreparedRequest(e,t){let n=oe(this.state.usage);this.state.lastRequestTimings=void 0;let i=()=>Date.now()-e.startedAt,r=e.request;this.throwIfAborted(),this.captureTaskLifecycle(_r,{durationMs:i(),phase:"provider_request_started"}),r={...r,signal:AbortSignal.any([t.signal,...this.abortController?[this.abortController.signal]:[]])},this.lastIssuedRequest=r;let o=this.openTaskLifecycleStream(r,i),s=[],a=new je,u=new Map,c=new Map,d=new Map,y=[],p=[],v="unknown",b,w="",F="",B=Wt(),H=0,A=this.config.reasoningLoopDetection,P=A===!1?void 0:new me(A,{given:()=>Zt(r.messages)}),G,se=()=>Zt(r.messages),be=A===!1?void 0:new me(A,{given:se}),ae=A===!1?void 0:new Kt(A,{given:se}),K,x,sn=this.config.toolIntentLimit,an=this.toolIntentCutStreak>=pp;if(an)this.toolIntentCutStreak=0;let ln=sn===!1||an||!Xt()?void 0:new Qt({...sn,argumentNames:this.toolArgumentNames(),toolNames:[...this.tools.values()].map((m)=>m.name)}),W;for await(let m of o){if(t.signal.aborted)break;switch(this.throwIfAborted(),m.type){case"text-delta":{w+=m.text,B.textDeltas+=1,B.textChars+=m.text.length;let _=p.at(-1);if(_?.type==="part"&&_.part.type==="text")_.part.text+=m.text;else p.push({type:"part",part:{type:"text",text:m.text}});await this.emit({type:"assistant-text-delta",snapshot:this.snapshot(),iteration:this.state.iteration,text:m.text,accumulatedText:w}),K=be?.push(m.text)??void 0;break}case"media":{p.push({type:"part",part:{type:"media",media:m.media}}),await this.emit({type:"assistant-media",snapshot:this.snapshot(),iteration:this.state.iteration,media:m.media});break}case"reasoning-delta":{F+=m.text,B.reasoningDeltas+=1,B.reasoningChars+=m.text.length;let _=p.at(-1);if(_?.type==="part"&&_.part.type==="reasoning")_.part.text+=m.text,_.part.redacted=m.redacted??_.part.redacted,_.part.metadata=m.metadata??_.part.metadata;else p.push({type:"part",part:{type:"reasoning",text:m.text,redacted:m.redacted,metadata:m.metadata}});await this.emit({type:"assistant-reasoning-delta",snapshot:this.snapshot(),iteration:this.state.iteration,text:m.text,accumulatedText:F,redacted:m.redacted,metadata:m.metadata}),G=P?.push(m.text)??void 0;break}case"tool-input-progress":{if(await this.emit({type:"tool-updated",snapshot:this.snapshot(),iteration:this.state.iteration,toolCall:{type:"tool-call",toolCallId:m.toolCallId,toolName:m.toolName??"tool",input:void 0},update:{kind:Jn,inputChars:m.inputChars,deltas:m.deltas,...m.inputText?{inputText:m.inputText}:{}}}),m.toolName)c.set(m.toolCallId,m.toolName);if(m.inputText)u.set(m.toolCallId,(u.get(m.toolCallId)??"")+m.inputText),W=ln?.push(m.toolCallId,m.inputText,m.toolName),x=ae?.push(m.toolCallId,m.inputText,m.toolName);break}case"tool-call-delta":{if(m.execution){let D={type:"tool-call",toolCallId:m.toolCallId??ye("model_tool"),toolName:m.toolName??"tool",input:m.input,metadata:m.metadata,execution:m.execution};d.set(D.toolCallId,{toolCallId:D.toolCallId,toolName:D.toolName,execution:m.execution,input:D.input}),await this.emit({type:"tool-started",snapshot:this.snapshot(),iteration:this.state.iteration,toolCall:D});break}let{key:_,created:j}=a.add(m);if(j)p.push({type:"tool",key:_});break}case"tool-result":{let _=d.get(m.toolCallId),j={..._,toolCallId:m.toolCallId,toolName:m.toolName,execution:m.execution,input:m.input===void 0?_?.input:m.input,output:m.output,isError:m.isError};d.set(m.toolCallId,j);let D={type:"tool-call",toolCallId:m.toolCallId,toolName:m.toolName,input:j.input,execution:m.execution};await this.emit({type:"tool-finished",snapshot:this.snapshot(),iteration:this.state.iteration,toolCall:D,message:de("tool",[{type:"tool-result",toolCallId:m.toolCallId,toolName:m.toolName,output:m.output,isError:m.isError,execution:m.execution}])});break}case"usage":{if(typeof m.usage.inputTokens==="number"&&m.usage.inputTokens>0)this.state.lastRequestInputTokens=m.usage.inputTokens;let _=a.inputChars();B.toolInputChars=Math.max(0,_-H);let j=Pr({outputTokens:m.usage.outputTokens,providerReasoningTokens:m.usage.reasoningTokenCount,tally:B});H=_,B=Wt(),await this.updateUsage(m.usage,m.timings,{outputSplit:j});break}case"finish":{if(v=m.reason,b=m.requestId,m.error)this.state.lastError=m.error,this.state.lastErrorClass=m.errorClass??Jr(m.error),this.lastToolCallRejection=m.toolCallRejection,this.state.lastErrorRetryable=m.errorRetryable??Zd(m.error),this.state.lastErrorReported=m.errorReported===!0;break}}if(G||K||x||W)break}if(ae&&!x&&!W)for(let m of p){if(m.type!=="tool")continue;let _=a.get(m.key);if(!_?.inputText||u.has(_.toolCallId))continue;if(x=ae.push(_.toolCallId,_.inputText,_.toolName),x)break}let wt=(m,_)=>_?`${m}
94
+ `);this.pendingHookContexts=[];let t=we("user",[{type:"text",text:e}],{userRunSpan:0,displayRole:"system"}),n=this.state.messages.at(-1);if(n?.role==="assistant"&&n.content.some((i)=>i.type==="tool-call"))this.state.messages.splice(-1,0,t);else this.state.messages.push(t);await this.emit({type:"message-added",snapshot:this.snapshot(),message:t})}async callBeforeRunHooks(){for(let e of this.hooks.beforeRun){let t=await e({snapshot:this.snapshot()});if(this.applyStopControl(t),t?.appendContext?.trim())this.pendingHookContexts.push(qn({source:"RunStart"},t.appendContext))}}async callAfterRunHooks(e){for(let t of this.hooks.afterRun)await t({snapshot:this.snapshot(),result:e})}async generateAssistantMessageRecoveringFaults(){for(let e=1;;e+=1){let t,n,r=!1;try{t=await this.withProviderErrorRetry(()=>this.generateAssistantMessageWithOverflowRecovery())}catch(p){if(this.abortController?.signal.aborted||p instanceof Ft||p instanceof Be||p instanceof Ie)throw p;n=p,r=!0}let i=this.config.recoverTurnFault,o=()=>{if(r)throw n;return t};if(!i)return o();let s,a,l;if(r)s=cn(n),a=n instanceof Error?n.message:String(n),l=Je(n);else if(t?.finishReason==="error")a=this.state.lastError??"",s=Ne(a,this.state.lastErrorClass),l=Wr(a,this.state.lastErrorClass);else return o();if(!s||!this.recoversTurnFault(s))return o();let u=K(this.config.sessionId),d=this.lastRequestTokens;if(l)this.config.logger?.log?.(`Engine bug: the server evicted session ${u??"(unnamed)"} (agent ${this.state.agentId}) at ${new Date().toISOString()}, holding ${d!==void 0?`${d.toLocaleString("en-US")} tokens (its last completed request)`:"an unknown number of tokens (no request had completed)"}, turn ${this.state.iteration}, attempt ${e}: ${a}; waiting to send it again`,{severity:"warn",kind:"engine_eviction",...u?{sessionId:u}:{},agentId:this.state.agentId,...d!==void 0?{tokensHeld:d}:{},iteration:this.state.iteration,attempt:e});else this.config.logger?.log?.(s==="refusal"?`Turn ${this.state.iteration} queued by the server (retry ${e}): ${Zr(a)}; waiting to send it again`:`Turn ${this.state.iteration} failed on a ${s} fault (attempt ${e}): ${a}; waiting to send it again`,{severity:s==="refusal"?"info":"warn"});await this.emit({type:"status-notice",snapshot:this.snapshot(),message:l?"the server evicted the turn to keep others alive (an engine bug) — waiting, then retrying":s==="transport"?"the server dropped the turn — waiting for it to come back, then retrying":"the server queued the turn — waiting for room, then retrying",metadata:{kind:"turn_fault_recovery",reason:s,...l?{evicted:!0}:{},phase:"started",iteration:this.state.iteration,attempt:e,providerError:a}});let h=!1;try{h=await i({kind:s,message:a,attempt:e,iteration:this.state.iteration,...l?{evicted:!0}:{},...l&&d!==void 0?{tokensHeld:d}:{},...u?{sessionId:u}:{},...this.abortController?.signal?{signal:this.abortController.signal}:{}})}catch{h=!1}if(this.throwIfAborted(),!h)return o()}}async generateAssistantMessageWithProviderRetry(){let e=()=>this.generateAssistantMessageRecoveringFaults(),t=await e();if(t.finishReason!=="unknown"||t.interrupted)return t;if(t.message.content.some((n)=>n.type==="tool-call")||this.hasModelToolActivity(t.message))return t;return await this.recordAssistantMessage(t.message,t.finishReason),await this.addUserReminderMessage("Previous turn ended unexpectedly. Continue from where you left off.",{displayRole:"system"}),this.resetLastError(),await e()}async withProviderErrorRetry(e){let t=0;for(;;){let n=await e();if(t>=jn||!this.isRetryableProviderErrorTurn(n))return n;t+=1;let r=this.state.lastError;this.resetLastError();let i=Math.min(Eh*2**(t-1),Ah);await this.emit({type:"status-notice",snapshot:this.snapshot(),message:`provider error — retrying (attempt ${t}/${jn})`,metadata:{kind:"provider_error_retry",reason:"provider_error_retry",phase:"started",iteration:this.state.iteration,attempt:t,maxRetries:jn,delayMs:i,providerError:r}}),await this.abortableDelay(i)}}isRetryableProviderErrorTurn(e){if(e.finishReason!=="error")return!1;if(e.message.content.length>0)return!1;let t=e.message.metadata?.modelToolActivities;if(Array.isArray(t)&&t.length>0)return!1;let n=this.state.lastErrorClass;if(n==="auth"||n==="context_window_exceeded")return!1;let r=Ne(this.state.lastError??"",n);if(r&&this.recoversTurnFault(r))return!1;return this.state.lastErrorRetryable===!0}resetLastError(){this.state.lastError=void 0,this.state.lastErrorClass=void 0,this.state.lastErrorRetryable=void 0,this.state.lastErrorReported=!1}async abortableDelay(e){this.throwIfAborted();let t=this.abortController?.signal;await new Promise((n,r)=>{let i=()=>{clearTimeout(o),r(this.normalizeAbortError())},o=setTimeout(()=>{t?.removeEventListener("abort",i),n()},e);if(t)t.addEventListener("abort",i,{once:!0})})}async generateAssistantMessageWithOverflowRecovery(){if(this.config.alwaysDescribeImages===!0)await this.describeImagesInTranscript();let e=this.compactBeforeNextTurn;this.compactBeforeNextTurn=!1;let t=await this.generateAssistantMessage(e?{overflowRecovery:!0}:void 0);if(this.isRecoverableImageTurn(t))return await this.retryWithoutImages();if(!this.isRecoverableOverflowTurn(t))return t;this.overflowRecoveryAttempted=!0;let n=this.state.lastError;if(!this.config.prepareTurn)throw new Be(Sh,n);await this.emit({type:"status-notice",snapshot:this.snapshot(),message:"context window exceeded — compacting and retrying",metadata:{kind:"context_overflow_recovery",reason:"context_overflow_recovery",phase:"started",iteration:this.state.iteration,providerError:n}});let r=await this.generateAssistantMessage({overflowRecovery:!0,requireSmallerRequest:!0});if(r.finishReason==="error"&&this.state.lastErrorClass==="context_window_exceeded")throw new Be(Ch,this.state.lastError);return r}async recoverUnparsableToolCall(){if(this.state.lastErrorClass!=="tool_call_unparsable"||this.toolCallParseRetries>=_h)return!1;return this.toolCallParseRetries+=1,await this.emit({type:"status-notice",snapshot:this.snapshot(),message:"the model's tool call did not parse — asking for it again",metadata:{kind:"tool_call_parse_recovery",reason:"tool_call_parse_recovery",phase:"started",iteration:this.state.iteration,attempt:this.toolCallParseRetries,providerError:this.state.lastError,...this.lastToolCallRejection?{rejection:this.lastToolCallRejection}:{}}}),await this.addUserReminderMessage(wh(this.lastToolCallRejection)),!0}isRecoverableImageTurn(e){return e.finishReason==="error"&&this.state.lastErrorClass==="image_input_unsupported"&&!this.imageRecoveryAttempted&&this.hasImageContent()}hasImageContent(){return this.state.messages.some((e)=>e.content.some((t)=>t.type==="image"))}async retryWithoutImages(){this.imageRecoveryAttempted=!0;let e=this.state.lastError,t=await this.describeImagesInTranscript(),n=0;for(let r of this.state.messages)for(let i=0;i<r.content.length;i++){if(r.content[i]?.type!=="image")continue;n+=1,r.content[i]={type:"text",text:sh}}return this.config.onImageInputUnsupported?.(),await this.emit({type:"status-notice",snapshot:this.snapshot(),message:"model does not accept images — resending without them",metadata:{kind:"image_input_recovery",reason:"image_input_recovery",phase:"started",iteration:this.state.iteration,droppedImages:n,describedImages:t,providerError:e}}),await this.generateAssistantMessage()}async describeImagesInTranscript(){let e=this.config.describeImages;if(!e)return 0;let t=[],n=[];for(let s of this.state.messages){let a=s.content.filter((l)=>l.type==="text").map((l)=>l.text).join(`
95
+ `).slice(0,ih);for(let l=0;l<s.content.length;l++){let u=s.content[l];if(u?.type!=="image")continue;let d=ah(u);if(d===void 0)continue;t.push({message:s,index:l}),n.push({image:d,mediaType:u.mediaType,context:a.length>0?a:void 0})}}if(n.length===0)return this.config.logger?.log?.(`Vision describer found no images in ${this.state.messages.length} transcript message(s)`),0;let r=[];try{r=await e(n)}catch(s){this.config.logger?.log?.(`Vision model could not describe ${n.length} image(s): ${s instanceof Error?s.message:String(s)}`,{severity:"warn"})}let i=this.config.modelSupportsImages!==!1,o=0;for(let s=0;s<t.length;s++){let a=r[s]?.trim();if(!a&&i)continue;let l=t[s];l.message.content[l.index]={type:"text",text:a?`[image description, from the vision model]
96
+ ${a}`:oh},o+=1}return o}isRecoverableOverflowTurn(e){if(e.finishReason!=="error"||this.state.lastErrorClass!=="context_window_exceeded"||this.overflowRecoveryAttempted)return!1;return!e.message.content.some((t)=>t.type==="tool-call")}hasModelToolActivity(e){let t=e.metadata?.modelToolActivities;return Array.isArray(t)&&t.length>0}async recordAssistantMessage(e,t){let n=this.replaceSpoiledContent(e);if(this.state.messages.push(e),await this.emit({type:"message-added",snapshot:this.snapshot(),message:e}),n)this.announcedRepetitionRemoval.add(e),await this.emit({type:"status-notice",snapshot:this.snapshot(),message:n,metadata:{kind:"reasoning_loop",reason:"reasoning_loop",phase:"removed",iteration:this.state.iteration,nudged:Boolean(this.repetitionNudges.get(e)?.nudge)}});await this.emit({type:"assistant-message",snapshot:this.snapshot(),iteration:this.state.iteration,message:e,finishReason:t})}async generateAssistantMessage(e){let t=new AbortController;this.modelSteerController=t;try{return await this.generateAssistantMessageForRequest(t,e)}finally{this.modelSteerController=void 0}}async prepareModelRequest(e){let t=$o({distinctId:K(this.config.distinctId),clientName:K(this.config.clientName),clientVersion:K(this.config.clientVersion),clineCoreVersion:K(this.config.clineCoreVersion),sessionId:K(this.config.sessionId),agentId:this.state.agentId,conversationId:K(this.config.conversationId),runId:this.state.runId,iteration:this.state.iteration}),n=this.getRetryOutputCap();if(n!==void 0)this.config.logger?.log?.(`Retrying a truncated turn on a reduced output cap of ${n} tokens (attempt ${this.consecutiveMaxTokensRetries}, was ${this.truncatedOutputCapTokens})`,{severity:"info"});let r={systemPrompt:this.config.systemPrompt,messages:te(this.state.messages),tools:[...this.tools.values()].map((s)=>({name:s.name,description:s.description,inputSchema:s.inputSchema,...s.readOnly?{readOnly:!0}:{}})),modelTools:this.config.modelTools,signal:this.abortController?.signal,options:Sn(this.config.modelOptions,{metadata:t,...n!==void 0?{maxTokens:n}:{}})},i=Date.now(),o=await this.consumePendingUserMessage();if(o)r={...r,messages:[...r.messages,...te([o])]};r=await this.prepareTurnForModelRequest(r,e),this.throwIfAborted();for(let s of this.hooks.beforeModel){let a=await s({snapshot:this.snapshot(),request:r});if(this.throwIfAborted(),this.applyStopControl(a),a?.messages)r={...r,messages:te(a.messages)};if(a?.tools)r={...r,tools:[...a.tools]};if(a?.options)r={...r,options:Sn(r.options,a.options)}}return this.config.logger?.debug("Agent model request diagnostics",{iteration:this.state.iteration,providerId:"providerId"in this.config&&typeof this.config.providerId==="string"?this.config.providerId:void 0,modelId:"modelId"in this.config&&typeof this.config.modelId==="string"?this.config.modelId:void 0,...Ph(r)}),{request:r,startedAt:i}}async generateAssistantMessageForRequest(e,t){let n=await this.prepareModelRequest(t);return await this.streamPreparedRequest(n,e)}async streamPreparedRequest(e,t){let n=fe(this.state.usage);this.state.lastRequestTimings=void 0;let r=()=>Date.now()-e.startedAt,i=e.request;this.throwIfAborted(),this.captureTaskLifecycle(zo,{durationMs:r(),phase:"provider_request_started"}),i={...i,signal:AbortSignal.any([t.signal,...this.abortController?[this.abortController.signal]:[]])},this.lastIssuedRequest=i;let o=this.openTaskLifecycleStream(i,r),s=[],a=new nt,l=new Map,u=new Map,d=new Map,h=[],p=[],f="unknown",g,T="",k="",_=Nn(),B=0,J=this.config.reasoningLoopDetection,P=J===!1?void 0:new Ee(J,{given:()=>Pn(i.messages)}),E,V=()=>Pn(i.messages),he=J===!1?void 0:new Ee(J,{given:V}),oe=J===!1?void 0:new Ln(J,{given:V}),q,C,it=this.config.toolIntentLimit,ot=this.toolIntentCutStreak>=gh;if(ot)this.toolIntentCutStreak=0;let Zn=it===!1||ot||!Un()?void 0:new Fn({...it,argumentNames:this.toolArgumentNames(),toolNames:[...this.tools.values()].map((v)=>v.name)}),G;for await(let v of o){if(t.signal.aborted)break;switch(this.throwIfAborted(),v.type){case"text-delta":{T+=v.text,_.textDeltas+=1,_.textChars+=v.text.length;let A=p.at(-1);if(A?.type==="part"&&A.part.type==="text")A.part.text+=v.text;else p.push({type:"part",part:{type:"text",text:v.text}});await this.emit({type:"assistant-text-delta",snapshot:this.snapshot(),iteration:this.state.iteration,text:v.text,accumulatedText:T}),q=he?.push(v.text)??void 0;break}case"media":{p.push({type:"part",part:{type:"media",media:v.media}}),await this.emit({type:"assistant-media",snapshot:this.snapshot(),iteration:this.state.iteration,media:v.media});break}case"reasoning-delta":{k+=v.text,_.reasoningDeltas+=1,_.reasoningChars+=v.text.length;let A=p.at(-1);if(A?.type==="part"&&A.part.type==="reasoning")A.part.text+=v.text,A.part.redacted=v.redacted??A.part.redacted,A.part.metadata=v.metadata??A.part.metadata;else p.push({type:"part",part:{type:"reasoning",text:v.text,redacted:v.redacted,metadata:v.metadata}});await this.emit({type:"assistant-reasoning-delta",snapshot:this.snapshot(),iteration:this.state.iteration,text:v.text,accumulatedText:k,redacted:v.redacted,metadata:v.metadata}),E=P?.push(v.text)??void 0;break}case"tool-input-progress":{if(await this.emit({type:"tool-updated",snapshot:this.snapshot(),iteration:this.state.iteration,toolCall:{type:"tool-call",toolCallId:v.toolCallId,toolName:v.toolName??"tool",input:void 0},update:{kind:Hr,inputChars:v.inputChars,deltas:v.deltas,...v.inputText?{inputText:v.inputText}:{}}}),v.toolName)u.set(v.toolCallId,v.toolName);if(v.inputText)l.set(v.toolCallId,(l.get(v.toolCallId)??"")+v.inputText),G=Zn?.push(v.toolCallId,v.inputText,v.toolName),C=oe?.push(v.toolCallId,v.inputText,v.toolName);break}case"tool-call-delta":{if(v.execution){let F={type:"tool-call",toolCallId:v.toolCallId??xe("model_tool"),toolName:v.toolName??"tool",input:v.input,metadata:v.metadata,execution:v.execution};d.set(F.toolCallId,{toolCallId:F.toolCallId,toolName:F.toolName,execution:v.execution,input:F.input}),await this.emit({type:"tool-started",snapshot:this.snapshot(),iteration:this.state.iteration,toolCall:F});break}let{key:A,created:H}=a.add(v);if(H)p.push({type:"tool",key:A});break}case"tool-result":{let A=d.get(v.toolCallId),H={...A,toolCallId:v.toolCallId,toolName:v.toolName,execution:v.execution,input:v.input===void 0?A?.input:v.input,output:v.output,isError:v.isError};d.set(v.toolCallId,H);let F={type:"tool-call",toolCallId:v.toolCallId,toolName:v.toolName,input:H.input,execution:v.execution};await this.emit({type:"tool-finished",snapshot:this.snapshot(),iteration:this.state.iteration,toolCall:F,message:we("tool",[{type:"tool-result",toolCallId:v.toolCallId,toolName:v.toolName,output:v.output,isError:v.isError,execution:v.execution}])});break}case"usage":{if(typeof v.usage.inputTokens==="number"&&v.usage.inputTokens>0)this.state.lastRequestInputTokens=v.usage.inputTokens;let A=a.inputChars();_.toolInputChars=Math.max(0,A-B);let H=Ko({outputTokens:v.usage.outputTokens,providerReasoningTokens:v.usage.reasoningTokenCount,tally:_});B=A,_=Nn(),await this.updateUsage(v.usage,v.timings,{outputSplit:H});break}case"finish":{if(f=v.reason,g=v.requestId,v.error)this.state.lastError=v.error,this.state.lastErrorClass=v.errorClass??ds(v.error),this.lastToolCallRejection=v.toolCallRejection,this.state.lastErrorRetryable=v.errorRetryable??Yf(v.error),this.state.lastErrorReported=v.errorReported===!0;break}}if(E||q||C||G)break}if(oe&&!C&&!G)for(let v of p){if(v.type!=="tool")continue;let A=a.get(v.key);if(!A?.inputText||l.has(A.toolCallId))continue;if(C=oe.push(A.toolCallId,A.inputText,A.toolName),C)break}let jt=(v,A)=>A?`${v}
104
97
 
105
- ${_}`:m;if(G)this.pendingToolIntentNudge=wt(qr(G),await this.onReasoningLoopCut(G));else if(K)this.pendingToolIntentNudge=wt(jr(K),await this.onReasoningLoopCut(K,"reply","answer_loop"));else if(x)this.pendingToolIntentNudge=wt(Br(x),await this.onReasoningLoopCut(x.verdict,`call to \`${x.toolName??"a tool"}\``,"argument_loop"));else if(P)this.reasoningLoopStreak=0;if(W)await this.onToolIntentCut(W);else if(ln)this.toolIntentCutStreak=0;this.throwIfAborted();let _t=t.signal.aborted;if(_t)v="stop";if((G||K||x||W)&&v==="unknown")v="stop";let un="",cn;for(let m of p)if(m.type==="tool")cn=m.key;for(let m of p){if(_t&&(m.type==="tool"||m.part.type==="reasoning"))continue;if(m.type==="part"){if(K&&m.part.type==="text"){un+=m.part.text;continue}s.push(m.part);continue}let _=a.get(m.key);if(W&&_?.toolCallId===W.toolCallId||x&&_?.toolCallId===x.toolCallId)continue;let j=a.finish(m.key,v,m.key===cn);if(j.invalid)y.push(j.invalid);if(!j.call||!_)continue;this.config.logger?.debug?.(Yd(this.state.iteration,j.call.toolName,j.call.toolCallId,_.inputText,j.call.input)),s.push(j.call)}let ie={};if(G)ie.reasoningLoop=G;if(K)this.recordCut({channel:"reply",cause:"answer_loop",verdict:K,text:un}),s.push({type:"text",text:"(The reply here was cut: it had come to repeat itself. Its text is not kept.)"}),ie.answerLoop=K;let dn=(m)=>u.get(m)||a.get(m)?.inputText||"";if(x)this.recordCut({channel:"tool_arguments",cause:"argument_loop",verdict:x.verdict,...x.toolName?{toolName:x.toolName}:{},toolCallId:x.toolCallId,text:dn(x.toolCallId)}),s.push({type:"text",text:Fr(x)}),ie.argumentLoop=x;if(W)this.recordCut({channel:"tool_arguments",cause:"tool_intent_overrun",...W.toolName?{toolName:W.toolName}:{},toolCallId:W.toolCallId,text:dn(W.toolCallId)}),s.push({type:"text",text:Gr(W)}),ie.toolIntentOverrun=W;if(v==="max-tokens"){let m=new Set(s.flatMap((D)=>D.type==="tool-call"?[D.toolCallId]:[])),_=new Set(y.map((D)=>D.toolCallId)),j=[];for(let[D,pn]of u){if(m.has(D)&&!_.has(D)||D===x?.toolCallId||D===W?.toolCallId)continue;let Ve=c.get(D);if(this.recordCut({channel:"tool_arguments",cause:"output_limit",...Ve?{toolName:Ve}:{},toolCallId:D,text:pn}),!_.has(D))j.push({...Ve?{toolName:Ve}:{},chars:pn.length})}if(j.length>0)ie.unfinishedToolCalls=j}if(y.length>0)ie.invalidToolCalls=y;if(d.size>0)ie.modelToolActivities=[...d.values()];let He=de("assistant",s,Object.keys(ie).length>0?ie:void 0),We=Op(n,this.state.usage);if(We){if(this.state.lastRequestTimings)We.timings=this.state.lastRequestTimings;He.metrics=We,this.captureUnexpectedReasoningTokens(r,We)}if(this.config.messageModelInfo)He.modelInfo={...this.config.messageModelInfo};for(let m of this.hooks.afterModel){let _=await m({snapshot:this.snapshot(),assistantMessage:He,finishReason:v,...b?{requestId:b}:{}});this.applyStopControl(_)}return{message:He,finishReason:v,interrupted:_t}}async*openTaskLifecycleStream(e,t){let n,i="provider_request_started",r=Date.now();this.trace(`request-start iter=${this.state.iteration}`);try{n=await this.config.model.stream(e),this.trace(`stream-open iter=${this.state.iteration} after=${Date.now()-r}ms`),this.throwIfAborted(),i="provider_stream_started",this.captureTaskLifecycle(kr,{durationMs:t(),phase:i})}catch(s){if(e.signal?.aborted&&!this.abortController?.signal.aborted)return;if(!e.signal?.aborted&&!this.isAbortError(s))this.captureTaskLifecycleFailure(s,i,t());throw s}let o=!1;try{for await(let s of n){if(!o)o=!0,this.trace(`first-chunk iter=${this.state.iteration} after=${Date.now()-r}ms type=${s.type}`),i="first_chunk_received",this.captureTaskLifecycle(Er,{durationMs:t(),phase:i,eventType:s.type});yield s}}catch(s){if(e.signal?.aborted&&!this.abortController?.signal.aborted)return;if(!e.signal?.aborted&&!this.isAbortError(s))this.captureTaskLifecycleFailure(s,i,t());throw s}}captureTaskLifecycleFailure(e,t,n){this.captureTaskLifecycle(Ir,{durationMs:n,error:e,errorClass:Jr(e),phase:t})}captureTaskLifecycle(e,t={}){let n=V(this.config.sessionId);Cr(this.config.telemetry,{event:e,sessionId:n,ulid:n,agentId:this.state.agentId,conversationId:V(this.config.conversationId),runId:this.state.runId,iteration:this.state.iteration>0?this.state.iteration:void 0,providerId:this.getTelemetryProviderId(),modelId:this.getTelemetryModelId(),...t})}getTelemetryProviderId(){return V(this.config.messageModelInfo?.provider)??this.telemetryProviderId}getTelemetryModelId(){return V(this.config.messageModelInfo?.id)??this.telemetryModelId}isAbortError(e){return e instanceof ve||this.abortController?.signal.aborted===!0}captureUnexpectedReasoningTokens(e,t){if(!Mp(e)||(t.reasoningTokenCount??0)<=0)return;let n=t.reasoningTokenCount;if(n===void 0)return;xr(this.config.telemetry,{sessionId:this.config.sessionId,agentId:this.state.agentId,runId:this.state.runId,iteration:this.state.iteration,providerId:this.config.messageModelInfo?.provider,modelId:this.config.messageModelInfo?.id,requestedThinking:!1,reasoningTokenCount:n})}async prepareTurnForModelRequest(e,t){if(!this.config.prepareTurn)return e;let n=t?.overflowRecovery===!0,i=t?.requireSmallerRequest===!0,r=await this.config.prepareTurn({agentId:this.state.agentId,conversationId:this.config.conversationId,parentAgentId:this.state.parentAgentId??null,iteration:this.state.iteration,messages:e.messages,systemPrompt:e.systemPrompt,tools:e.tools,model:{id:this.config.messageModelInfo?.id,provider:this.config.messageModelInfo?.provider},signal:e.signal,overflowRecovery:n||void 0,previousRequestInputTokens:this.state.lastRequestInputTokens>0?this.state.lastRequestInputTokens:void 0,emitStatusNotice:(s,a)=>{this.emit({type:"status-notice",snapshot:this.snapshot(),message:s,metadata:a})},reportUsage:(s)=>{this.updateUsage(s,void 0,{auxiliary:!0})}});if(i){if(!(r?.messages!==void 0&&JSON.stringify(r.messages).length<JSON.stringify(e.messages).length))throw new Me(kp,this.state.lastError)}if(!r)return e;let o=e;if(r.messages){let s=Y(r.messages);o={...o,messages:Y(s)}}if(r.systemPrompt!==void 0)o={...o,systemPrompt:r.systemPrompt};return o}async consumePendingUserMessage(){let e=this.config.consumePendingUserMessage;if(!e)return;let t=(await e())?.trim();if(!t)return;let n=de("user",[{type:"text",text:t}],{userRunSpan:0});return this.steerAwaitingResume=!0,this.state.messages.push(n),await this.emit({type:"message-added",snapshot:this.snapshot(),message:n}),n}async updateUsage(e,t,n){let i=n?.auxiliary===!0;if(this.state.usage={inputTokens:this.state.usage.inputTokens+(e.inputTokens??0),outputTokens:this.state.usage.outputTokens+(e.outputTokens??0),cacheReadTokens:this.state.usage.cacheReadTokens+(e.cacheReadTokens??0),cacheWriteTokens:this.state.usage.cacheWriteTokens+(e.cacheWriteTokens??0),reasoningTokenCount:(this.state.usage.reasoningTokenCount??0)+(e.reasoningTokenCount??0),totalCost:(this.state.usage.totalCost??0)+(e.totalCost??0)},t)this.state.lastRequestTimings=t;if(e.inputTokens!==void 0&&!i)this.lastRequestTokens=(e.inputTokens??0)+(e.outputTokens??0);await this.emit({type:"usage-updated",snapshot:this.snapshot(),usage:oe(this.state.usage),...t?{timings:t}:{},...n?.outputSplit?{outputSplit:n.outputSplit}:{},...i?{auxiliary:!0}:{}})}async executeToolCalls(e){this.pendingHookContexts=[];let t=[];for(let d of e){let y=Date.now(),p=await this.prepareToolExecution(d);p.prepareMs=Date.now()-y,t.push(p)}let n=Array(t.length),i=[],r=[],o=this.config.maxParallelToolCalls>1;t.forEach((d,y)=>{let p=this.tools.get(d.toolCall.toolName);(o&&p?.lifecycle?.boundsOwnConcurrency===!0?r:i).push(y)});let s=r.map(async(d)=>{n[d]=await this.executePreparedTool(t[d])}),a=Math.min(Math.max(1,this.config.maxParallelToolCalls),i.length);if(a<=1){for(let d of i)n[d]=await this.executePreparedTool(t[d]);return await Promise.all(s),n}let u=0,c=async()=>{while(!0){let d=u;if(u+=1,d>=i.length)return;let y=i[d];n[y]=await this.executePreparedTool(t[y])}};return await Promise.all([...Array.from({length:a},()=>c()),...s]),n}attachTurnNotes(e,t){let n=[],i=this.repetitionNudgeFor(t);if(i)n.push(i);let r=this.config.completionPolicy?.afterToolsReminder?.();if(r)n.push(r);if(this.pendingToolIntentNudge)n.push(this.pendingToolIntentNudge),this.pendingToolIntentNudge=void 0;if(n.length===0)return[];let o=e.at(-1)?.content??[],s;for(let a=o.length-1;a>=0&&!s;a-=1){let u=o[a];if(u?.type==="tool-result")s=u}if(!s)return n;return s.note=[s.note,...n].filter(Boolean).join(`
98
+ ${A}`:v;if(E)this.pendingToolIntentNudge=jt(is(E),await this.onReasoningLoopCut(E));else if(q)this.pendingToolIntentNudge=jt(rs(q),await this.onReasoningLoopCut(q,"reply","answer_loop"));else if(C)this.pendingToolIntentNudge=jt(ns(C),await this.onReasoningLoopCut(C.verdict,`call to \`${C.toolName??"a tool"}\``,"argument_loop"));else if(P)this.reasoningLoopStreak=0;if(G)await this.onToolIntentCut(G);else if(Zn)this.toolIntentCutStreak=0;this.throwIfAborted();let Bt=t.signal.aborted;if(Bt)f="stop";if((E||q||C||G)&&f==="unknown")f="stop";let Vn="",Gn;for(let v of p)if(v.type==="tool")Gn=v.key;for(let v of p){if(Bt&&(v.type==="tool"||v.part.type==="reasoning"))continue;if(v.type==="part"){if(q&&v.part.type==="text"){Vn+=v.part.text;continue}s.push(v.part);continue}let A=a.get(v.key);if(G&&A?.toolCallId===G.toolCallId||C&&A?.toolCallId===C.toolCallId)continue;let H=a.finish(v.key,f,v.key===Gn);if(H.invalid)h.push(H.invalid);if(!H.call||!A)continue;this.config.logger?.debug?.(th(this.state.iteration,H.call.toolName,H.call.toolCallId,A.inputText,H.call.input)),s.push(H.call)}let de={};if(E)de.reasoningLoop=E;if(q)this.recordCut({channel:"reply",cause:"answer_loop",verdict:q,text:Vn}),s.push({type:"text",text:"(The reply here was cut: it had come to repeat itself. Its text is not kept.)"}),de.answerLoop=q;let Kn=(v)=>l.get(v)||a.get(v)?.inputText||"";if(C)this.recordCut({channel:"tool_arguments",cause:"argument_loop",verdict:C.verdict,...C.toolName?{toolName:C.toolName}:{},toolCallId:C.toolCallId,text:Kn(C.toolCallId)}),s.push({type:"text",text:ts(C)}),de.argumentLoop=C;if(G)this.recordCut({channel:"tool_arguments",cause:"tool_intent_overrun",...G.toolName?{toolName:G.toolName}:{},toolCallId:G.toolCallId,text:Kn(G.toolCallId)}),s.push({type:"text",text:us(G)}),de.toolIntentOverrun=G;if(f==="max-tokens"){let v=new Set(s.flatMap((F)=>F.type==="tool-call"?[F.toolCallId]:[])),A=new Set(h.map((F)=>F.toolCallId)),H=[];for(let[F,Jn]of l){if(v.has(F)&&!A.has(F)||F===C?.toolCallId||F===G?.toolCallId)continue;let lt=u.get(F);if(this.recordCut({channel:"tool_arguments",cause:"output_limit",...lt?{toolName:lt}:{},toolCallId:F,text:Jn}),!A.has(F))H.push({...lt?{toolName:lt}:{},chars:Jn.length})}if(H.length>0)de.unfinishedToolCalls=H}if(h.length>0)de.invalidToolCalls=h;if(d.size>0)de.modelToolActivities=[...d.values()];let st=we("assistant",s,Object.keys(de).length>0?de:void 0),at=Lh(n,this.state.usage);if(at){if(this.state.lastRequestTimings)at.timings=this.state.lastRequestTimings;st.metrics=at,this.captureUnexpectedReasoningTokens(i,at)}if(this.config.messageModelInfo)st.modelInfo={...this.config.messageModelInfo};for(let v of this.hooks.afterModel){let A=await v({snapshot:this.snapshot(),assistantMessage:st,finishReason:f,...g?{requestId:g}:{}});this.applyStopControl(A)}return{message:st,finishReason:f,interrupted:Bt}}async*openTaskLifecycleStream(e,t){let n,r="provider_request_started",i=Date.now();this.trace(`request-start iter=${this.state.iteration}`);try{n=await this.config.model.stream(e),this.trace(`stream-open iter=${this.state.iteration} after=${Date.now()-i}ms`),this.throwIfAborted(),r="provider_stream_started",this.captureTaskLifecycle(Do,{durationMs:t(),phase:r})}catch(s){if(e.signal?.aborted&&!this.abortController?.signal.aborted)return;if(!e.signal?.aborted&&!this.isAbortError(s))this.captureTaskLifecycleFailure(s,r,t());throw s}let o=!1;try{for await(let s of n){if(!o)o=!0,this.trace(`first-chunk iter=${this.state.iteration} after=${Date.now()-i}ms type=${s.type}`),r="first_chunk_received",this.captureTaskLifecycle(Uo,{durationMs:t(),phase:r,eventType:s.type});yield s}}catch(s){if(e.signal?.aborted&&!this.abortController?.signal.aborted)return;if(!e.signal?.aborted&&!this.isAbortError(s))this.captureTaskLifecycleFailure(s,r,t());throw s}}captureTaskLifecycleFailure(e,t,n){this.captureTaskLifecycle(Fo,{durationMs:n,error:e,errorClass:ds(e),phase:t})}captureTaskLifecycle(e,t={}){let n=K(this.config.sessionId);qo(this.config.telemetry,{event:e,sessionId:n,ulid:n,agentId:this.state.agentId,conversationId:K(this.config.conversationId),runId:this.state.runId,iteration:this.state.iteration>0?this.state.iteration:void 0,providerId:this.getTelemetryProviderId(),modelId:this.getTelemetryModelId(),...t})}getTelemetryProviderId(){return K(this.config.messageModelInfo?.provider)??this.telemetryProviderId}getTelemetryModelId(){return K(this.config.messageModelInfo?.id)??this.telemetryModelId}isAbortError(e){return e instanceof Ie||this.abortController?.signal.aborted===!0}captureUnexpectedReasoningTokens(e,t){if(!zh(e)||(t.reasoningTokenCount??0)<=0)return;let n=t.reasoningTokenCount;if(n===void 0)return;Bo(this.config.telemetry,{sessionId:this.config.sessionId,agentId:this.state.agentId,runId:this.state.runId,iteration:this.state.iteration,providerId:this.config.messageModelInfo?.provider,modelId:this.config.messageModelInfo?.id,requestedThinking:!1,reasoningTokenCount:n})}async prepareTurnForModelRequest(e,t){if(!this.config.prepareTurn)return e;let n=t?.overflowRecovery===!0,r=t?.requireSmallerRequest===!0,i=await this.config.prepareTurn({agentId:this.state.agentId,conversationId:this.config.conversationId,parentAgentId:this.state.parentAgentId??null,iteration:this.state.iteration,messages:e.messages,systemPrompt:e.systemPrompt,tools:e.tools,model:{id:this.config.messageModelInfo?.id,provider:this.config.messageModelInfo?.provider},signal:e.signal,overflowRecovery:n||void 0,previousRequestInputTokens:this.state.lastRequestInputTokens>0?this.state.lastRequestInputTokens:void 0,emitStatusNotice:(s,a)=>{this.emit({type:"status-notice",snapshot:this.snapshot(),message:s,metadata:a})},reportUsage:(s)=>{this.updateUsage(s,void 0,{auxiliary:!0})}});if(r){if(!(i?.messages!==void 0&&JSON.stringify(i.messages).length<JSON.stringify(e.messages).length))throw new Be(Ih,this.state.lastError)}if(!i)return e;let o=e;if(i.messages){let s=te(i.messages);o={...o,messages:te(s)}}if(i.systemPrompt!==void 0)o={...o,systemPrompt:i.systemPrompt};return o}async consumePendingUserMessage(){let e=this.config.consumePendingUserMessage;if(!e)return;let t=(await e())?.trim();if(!t)return;let n=we("user",[{type:"text",text:t}],{userRunSpan:0});return this.steerAwaitingResume=!0,this.state.messages.push(n),await this.emit({type:"message-added",snapshot:this.snapshot(),message:n}),n}async updateUsage(e,t,n){let r=n?.auxiliary===!0;if(this.state.usage={inputTokens:this.state.usage.inputTokens+(e.inputTokens??0),outputTokens:this.state.usage.outputTokens+(e.outputTokens??0),cacheReadTokens:this.state.usage.cacheReadTokens+(e.cacheReadTokens??0),cacheWriteTokens:this.state.usage.cacheWriteTokens+(e.cacheWriteTokens??0),reasoningTokenCount:(this.state.usage.reasoningTokenCount??0)+(e.reasoningTokenCount??0),totalCost:(this.state.usage.totalCost??0)+(e.totalCost??0)},t)this.state.lastRequestTimings=t;if(e.inputTokens!==void 0&&!r)this.lastRequestTokens=(e.inputTokens??0)+(e.outputTokens??0);await this.emit({type:"usage-updated",snapshot:this.snapshot(),usage:fe(this.state.usage),...t?{timings:t}:{},...n?.outputSplit?{outputSplit:n.outputSplit}:{},...r?{auxiliary:!0}:{}})}async executeToolCalls(e){this.pendingHookContexts=[];let t=[];for(let d of e){let h=Date.now(),p=await this.prepareToolExecution(d);p.prepareMs=Date.now()-h,t.push(p)}let n=Array(t.length),r=[],i=[],o=this.config.maxParallelToolCalls>1;t.forEach((d,h)=>{let p=this.tools.get(d.toolCall.toolName);(o&&p?.lifecycle?.boundsOwnConcurrency===!0?i:r).push(h)});let s=i.map(async(d)=>{n[d]=await this.executePreparedTool(t[d])}),a=Math.min(Math.max(1,this.config.maxParallelToolCalls),r.length);if(a<=1){for(let d of r)n[d]=await this.executePreparedTool(t[d]);return await Promise.all(s),n}let l=0,u=async()=>{while(!0){let d=l;if(l+=1,d>=r.length)return;let h=r[d];n[h]=await this.executePreparedTool(t[h])}};return await Promise.all([...Array.from({length:a},()=>u()),...s]),n}attachTurnNotes(e,t){let n=[],r=this.repetitionNudgeFor(t);if(r)n.push(r);let i=this.config.completionPolicy?.afterToolsReminder?.();if(i)n.push(i);if(this.pendingToolIntentNudge)n.push(this.pendingToolIntentNudge),this.pendingToolIntentNudge=void 0;if(n.length===0)return[];let o=e.at(-1)?.content??[],s;for(let a=o.length-1;a>=0&&!s;a-=1){let l=o[a];if(l?.type==="tool-result")s=l}if(!s)return n;return s.note=[s.note,...n].filter(Boolean).join(`
106
99
 
107
- `),[]}findCompletingToolMessage(e,t){for(let n=0;n<e.length;n+=1){let i=e[n];if(this.tools.get(i.toolName)?.lifecycle?.completesRun!==!0)continue;let r=t[n],o=r?.content.find((s)=>s.type==="tool-result"&&s.toolCallId===i.toolCallId);if(o&&!o.isError)return r}return}async prepareToolExecution(e){let t=this.tools.get(e.toolName),n=e.input,i,r=e.metadata&&typeof e.metadata==="object"&&!Array.isArray(e.metadata)?e.metadata:void 0;if(typeof r?.inputParseError==="string")i=r.inputParseError;let o=t?void 0:this.config.unavailableToolReasons?.[e.toolName];if(o)i=`Tool "${e.toolName}" is not offered in this session: ${o}`;let s=r?.toolSource&&typeof r.toolSource==="object"&&!Array.isArray(r.toolSource)?r.toolSource:void 0;if(s?.executionMode==="provider")i=`Tool execution is disabled for provider ${typeof s.providerId==="string"?s.providerId:"provider"}`;if(t&&!i)n=Ce(n,t.inputSchema);let a;if(t&&!i)for(let u of this.hooks.beforeTool){let c=await u({snapshot:this.snapshot(),tool:t,toolCall:{...e,input:n},input:n});if(c?.input!==void 0)n=c.input;if(c?.policy)a={...a,...c.policy};if(c?.appendContext?.trim())this.pendingHookContexts.push(nn({source:"PreToolUse",toolCall:e},c.appendContext));if(this.applyStopControl(c),c?.skip){i=c.reason??`Tool ${t.name} was blocked by a runtime hook`;break}}if(t&&!i){let u={...Cp(e.toolName,this.config.toolPolicies),...a};if(u.enabled===!1)i=`Tool "${e.toolName}" is disabled by policy`;else if(u.autoApprove===!1){let c=await this.requestToolApproval(e,n,u);if(!c.approved)i=`${c.reason??"Tool was not executed"} -- ${ar}`}}return{toolCall:{...e,input:n},tool:t,input:n,skipReason:i}}async requestToolApproval(e,t,n){let i=this.config.requestToolApproval;if(!i)return{approved:!1,reason:`Tool "${e.toolName}" requires approval but no approval callback is configured`};try{return await i({sessionId:this.config.sessionId?.trim()||this.config.conversationId?.trim()||this.state.runId||this.state.agentId,agentId:this.state.agentId,conversationId:this.config.conversationId?.trim()||this.state.runId||this.state.agentId,iteration:this.state.iteration,toolCallId:e.toolCallId,toolName:e.toolName,input:t,policy:n})}catch(r){return{approved:!1,reason:`Tool "${e.toolName}" approval request failed: ${r instanceof Error?r.message:String(r)}`}}}async executePreparedTool(e){let t=new Date,n=Date.now();await this.emit({type:"tool-started",snapshot:this.snapshot(),iteration:this.state.iteration,toolCall:e.toolCall});let i=Date.now(),r;if(e.skipReason)r={output:{error:e.skipReason},isError:!0};else if(!e.tool)r={output:{error:`Unknown tool: ${e.toolCall.toolName}`},isError:!0};else try{if(r={output:await e.tool.execute(e.input,{sessionId:this.config.sessionId,agentId:this.state.agentId,conversationId:this.config.conversationId,runId:this.state.runId??ye("run"),iteration:this.state.iteration,toolCallId:e.toolCall.toolCallId,signal:this.abortController?.signal,metadata:this.config.toolContextMetadata,snapshot:this.snapshot(),reportStoppedForUser:()=>{this.stoppedForUserBy=e.toolCall.toolName},emitUpdate:(d)=>{this.emit({type:"tool-updated",snapshot:this.snapshot(),iteration:this.state.iteration,toolCall:e.toolCall,update:d})}})},this.stoppedForUserBy!==void 0&&this.stoppedForUserBy!==e.toolCall.toolName&&e.tool.readOnly!==!0)this.stoppedForUserBy=void 0}catch(c){r={output:{error:c instanceof Error?c.message:String(c)},isError:!0}}let o=new Date,s=Date.now(),a=Math.max(0,o.getTime()-t.getTime());if(e.tool)for(let c of this.hooks.afterTool){let d=await c({snapshot:this.snapshot(),tool:e.tool,toolCall:e.toolCall,input:e.input,result:r,startedAt:t,endedAt:o,durationMs:a});if(d?.appendContext?.trim())this.pendingHookContexts.push(nn({source:"PostToolUse",toolCall:e.toolCall},d.appendContext));if(this.applyStopControl(d),d?.result)r=d.result}this.trace(`tool ${e.toolCall.toolName} prepare=${e.prepareMs??-1}ms preEmit=${i-n}ms exec=${s-i}ms afterHooks=${Date.now()-s}ms total=${Date.now()-n}ms | hooks ${this.topEventHooks()}`),this.config.logger?.debug?.(`[tool-timing] ${e.toolCall.toolName} prepare=${e.prepareMs??-1}ms preEmit=${i-n}ms exec=${s-i}ms afterHooks=${Date.now()-s}ms total=${Date.now()-n}ms | hooks ${this.topEventHooks()}`);let u=de("tool",[{type:"tool-result",toolCallId:e.toolCall.toolCallId,toolName:e.toolCall.toolName,output:r.output,isError:r.isError}]);return await this.emit({type:"tool-finished",snapshot:this.snapshot(),iteration:this.state.iteration,toolCall:e.toolCall,message:u}),u}finishRun(e,t,n){return this.state.status=e,{agentId:this.state.agentId,agentRole:this.state.agentRole,runId:this.state.runId??ye("run"),status:e,iterations:this.state.iteration,outputText:n??Oe(t??this.findLastAssistantMessage()),messages:Y(this.state.messages),usage:oe(this.state.usage)}}findLastAssistantMessage(){return[...this.state.messages].reverse().find((e)=>e.role==="assistant")}recordCut(e){let t=this.config.onLoopCut;if(!t||!e.text)return;let n={agentId:this.state.agentId,iteration:this.state.iteration,...e};Promise.resolve().then(()=>t(n)).catch((i)=>{this.config.logger?.debug?.(`[loop-cut] could not keep the ${e.channel} cut at iteration ${n.iteration}: ${String(i)}`)})}async onReasoningLoopCut(e,t="reasoning",n="reasoning_loop"){this.reasoningLoopStreak+=1;let i=(this.config.reasoningLoopDetection===!1?void 0:this.config.reasoningLoopDetection?.maxConsecutiveTrips)??gt.maxConsecutiveTrips,r=Vt(e,t),o=this.reasoningLoopStreak>=i,s=o?await this.config.onReasoningLoopLimitReached?.({iteration:this.state.iteration,consecutiveTrips:this.reasoningLoopStreak,maxConsecutiveTrips:i,diagnosis:r}):void 0,a=s?.action==="continue"?s.guidance?.trim():void 0,u=o&&s?.action!=="continue";if(await this.emit({type:"status-notice",snapshot:this.snapshot(),message:u?`${r} Ending the run after ${this.reasoningLoopStreak} turns cut for this.`:o?`${r} That is ${this.reasoningLoopStreak} turns cut for this, and the run was to end here.`:`${r} Cutting the request and continuing.`,metadata:{kind:"reasoning_loop",reason:"reasoning_loop",phase:u?"aborted":"cut",cause:n,iteration:this.state.iteration,consecutiveTrips:this.reasoningLoopStreak,maxConsecutiveTrips:i,verdict:e,channel:t}}),u){this.abort(new ve(r)),this.throwIfAborted();return}return a}toolArgumentNames(){let e=new Set;for(let t of this.tools.values()){let n=t.inputSchema?.properties;for(let i of Object.keys(n??{}))e.add(i)}return[...e]}async onToolIntentCut(e){this.toolIntentCutStreak+=1,this.pendingToolIntentNudge=Kr(e);let t=e.toolName?`\`${e.toolName}\``:"a tool";this.config.logger?.log?.(`[tool-intent] cut a call to ${t} at iteration ${this.state.iteration}: intent passed ${e.maxChars} characters`),await this.emit({type:"status-notice",snapshot:this.snapshot(),message:`The model was writing its reasoning into the \`intent\` of a call to ${t} (past ${e.maxChars.toLocaleString("en-US")} characters). Cutting the request and asking it to make the call again.`,metadata:{kind:"tool_intent_overrun",reason:"tool_intent_overrun",phase:"cut",iteration:this.state.iteration,overrun:e}})}throwIfAborted(){if(this.abortController?.signal.aborted)throw this.normalizeAbortError()}normalizeAbortError(){let e=this.abortController?.signal.reason;if(e instanceof Error)return e;if(typeof e==="string")return Error(e);return Error(this.state.lastError??"Run aborted")}eventHookMs=new Map;noteEventHookMs(e,t,n){let i=`${e}#${t}`,r=this.eventHookMs.get(i);if(r)r.ms+=n,r.n+=1;else this.eventHookMs.set(i,{ms:n,n:1})}topEventHooks(e=4){return[...this.eventHookMs.entries()].sort((t,n)=>n[1].ms-t[1].ms).slice(0,e).map(([t,n])=>`${t}=${Math.round(n.ms)}ms/${n.n}`).join(" ")}trace(e){Jd(e),this.config.logger?.debug?.(`[timing] ${e}`)}async emit(e){let t=Bp(e);switch(e.type){case"run-started":this.config.logger?.info?.("Agent run started",t);break;case"tool-finished":this.config.logger?.info?.("Agent tool finished",t);break;case"run-failed":if(this.config.logger?.error?.("Agent run failed",{...t,error:e.error}),!this.state.lastErrorReported)Rr(this.config.telemetry,{component:"agents",operation:"agent.run",error:e.error,severity:"error",handled:!1,context:{...t,providerId:this.getTelemetryProviderId(),modelId:this.getTelemetryModelId(),...this.state.lastFinishReason?{finishReason:this.state.lastFinishReason}:{}}});break;default:if(!Fp.has(e.type))this.config.logger?.debug?.(`Agent event: ${e.type}`,t);break}switch(e.type){case"assistant-text-delta":case"assistant-reasoning-delta":case"assistant-media":case"tool-updated":break;default:this.config.telemetry?.capture({event:`agent.${e.type}`,properties:t});break}let n=0;for(let i of this.listeners){let r=Date.now();i(e),this.noteEventHookMs(e.type,`listener${n}`,Date.now()-r),n+=1}for(let i=0;i<this.hooks.onEvent.length;i+=1){let r=Date.now();await this.hooks.onEvent[i](e),this.noteEventHookMs(e.type,i,Date.now()-r)}}applyStopControl(e){if(!e?.stop)return;if(e.reason)this.state.lastError=e.reason;throw new Tt(e.reason)}}var Dp={no_tool_call:"the turn ended without calling anything — asking the model to carry on",unparsed_tool_call:"a tool call was written as text and never ran — asking for it again",announced_intent:"the model described the next step instead of taking it — asking it to make the call",non_convergence:"several turns of thinking with no work done — asking for a different approach",silent_repetition:"the turn repeated what the last one said — asking for a different approach"};function Up(e){return Dp[e]??`nudged: ${e}`}var Fp=new Set(["assistant-text-delta","assistant-reasoning-delta","assistant-media","tool-updated"]);function Bp(e){return{agentId:e.snapshot.agentId,agentRole:e.snapshot.agentRole,runId:e.snapshot.runId,status:e.snapshot.status,iteration:e.snapshot.iteration,eventType:e.type}}function jp(e){return new qe(e)}var qp=qe;function Hp(e){return new qe(e)}function no(e){let t=e.search(/<\|?tool_call\|?>/),n=(t<0?e:e.slice(t)).replace(/\s+/g," ").trim(),i=5381;for(let r=0;r<n.length;r++)i=(i<<5)+i+n.charCodeAt(r)|0;return`${n.length}:${i}`}export{qp as Agent,qe as AgentRuntime,ve as AgentRuntimeAbortError,bp as DEFAULT_MAX_NO_TOOL_CALL_NUDGES,io as DEFAULT_NO_TOOL_CALL_TURN_STREAK_LIMIT,gt as DEFAULT_REASONING_LOOP_GUARD,ge as DEFAULT_REASONING_REPETITION,qd as DEFAULT_TOOL_INTENT_MAX_CHARS,ro as NON_CONVERGENCE_MIN_REASONING_CHARS,me as ReasoningLoopGuard,je as ToolCallAssembler,Hp as createAgent,jp as createAgentRuntime,Gt as createRepetitionNudger,Cd as createTool,Vt as describeReasoningLoop,Lr as describeRepetition,Dd as finishToolCalls,vt as isRepetitionLoop,Xt as isToolIntentGuardEnabled,yt as measureReasoningRepetition,Hd as setToolIntentGuardEnabled};
100
+ `),[]}findCompletingToolMessage(e,t){for(let n=0;n<e.length;n+=1){let r=e[n];if(this.tools.get(r.toolName)?.lifecycle?.completesRun!==!0)continue;let i=t[n],o=i?.content.find((s)=>s.type==="tool-result"&&s.toolCallId===r.toolCallId);if(o&&!o.isError)return i}return}async prepareToolExecution(e){let t=this.tools.get(e.toolName),n=e.input,r,i=e.metadata&&typeof e.metadata==="object"&&!Array.isArray(e.metadata)?e.metadata:void 0;if(typeof i?.inputParseError==="string")r=i.inputParseError;let o=t?void 0:this.config.unavailableToolReasons?.[e.toolName];if(o)r=`Tool "${e.toolName}" is not offered in this session: ${o}`;let s=i?.toolSource&&typeof i.toolSource==="object"&&!Array.isArray(i.toolSource)?i.toolSource:void 0;if(s?.executionMode==="provider")r=`Tool execution is disabled for provider ${typeof s.providerId==="string"?s.providerId:"provider"}`;if(t&&!r)n=ze(n,t.inputSchema);let a;if(t&&!r)for(let l of this.hooks.beforeTool){let u=await l({snapshot:this.snapshot(),tool:t,toolCall:{...e,input:n},input:n});if(u?.input!==void 0)n=u.input;if(u?.policy)a={...a,...u.policy};if(u?.appendContext?.trim())this.pendingHookContexts.push(qn({source:"PreToolUse",toolCall:e},u.appendContext));if(this.applyStopControl(u),u?.skip){r=u.reason??`Tool ${t.name} was blocked by a runtime hook`;break}}if(t&&!r){let l={...Nh(e.toolName,this.config.toolPolicies),...a};if(l.enabled===!1)r=`Tool "${e.toolName}" is disabled by policy`;else if(l.autoApprove===!1){let u=await this.requestToolApproval(e,n,l);if(!u.approved)r=`${u.reason??"Tool was not executed"} -- ${_o}`}}return{toolCall:{...e,input:n},tool:t,input:n,skipReason:r}}async requestToolApproval(e,t,n){let r=this.config.requestToolApproval;if(!r)return{approved:!1,reason:`Tool "${e.toolName}" requires approval but no approval callback is configured`};try{return await r({sessionId:this.config.sessionId?.trim()||this.config.conversationId?.trim()||this.state.runId||this.state.agentId,agentId:this.state.agentId,conversationId:this.config.conversationId?.trim()||this.state.runId||this.state.agentId,iteration:this.state.iteration,toolCallId:e.toolCallId,toolName:e.toolName,input:t,policy:n})}catch(i){return{approved:!1,reason:`Tool "${e.toolName}" approval request failed: ${i instanceof Error?i.message:String(i)}`}}}async executePreparedTool(e){let t=new Date,n=Date.now();await this.emit({type:"tool-started",snapshot:this.snapshot(),iteration:this.state.iteration,toolCall:e.toolCall});let r=Date.now(),i;if(e.skipReason)i={output:{error:e.skipReason},isError:!0};else if(!e.tool)i={output:{error:`Unknown tool: ${e.toolCall.toolName}`},isError:!0};else try{if(i={output:await e.tool.execute(e.input,{sessionId:this.config.sessionId,agentId:this.state.agentId,conversationId:this.config.conversationId,runId:this.state.runId??xe("run"),iteration:this.state.iteration,toolCallId:e.toolCall.toolCallId,signal:this.abortController?.signal,metadata:this.config.toolContextMetadata,snapshot:this.snapshot(),reportStoppedForUser:()=>{this.stoppedForUserBy=e.toolCall.toolName},emitUpdate:(d)=>{this.emit({type:"tool-updated",snapshot:this.snapshot(),iteration:this.state.iteration,toolCall:e.toolCall,update:d})}})},this.stoppedForUserBy!==void 0&&this.stoppedForUserBy!==e.toolCall.toolName&&e.tool.readOnly!==!0)this.stoppedForUserBy=void 0}catch(u){i={output:{error:u instanceof Error?u.message:String(u)},isError:!0}}let o=new Date,s=Date.now(),a=Math.max(0,o.getTime()-t.getTime());if(e.tool)for(let u of this.hooks.afterTool){let d=await u({snapshot:this.snapshot(),tool:e.tool,toolCall:e.toolCall,input:e.input,result:i,startedAt:t,endedAt:o,durationMs:a});if(d?.appendContext?.trim())this.pendingHookContexts.push(qn({source:"PostToolUse",toolCall:e.toolCall},d.appendContext));if(this.applyStopControl(d),d?.result)i=d.result}this.trace(`tool ${e.toolCall.toolName} prepare=${e.prepareMs??-1}ms preEmit=${r-n}ms exec=${s-r}ms afterHooks=${Date.now()-s}ms total=${Date.now()-n}ms | hooks ${this.topEventHooks()}`),this.config.logger?.debug?.(`[tool-timing] ${e.toolCall.toolName} prepare=${e.prepareMs??-1}ms preEmit=${r-n}ms exec=${s-r}ms afterHooks=${Date.now()-s}ms total=${Date.now()-n}ms | hooks ${this.topEventHooks()}`);let l=we("tool",[{type:"tool-result",toolCallId:e.toolCall.toolCallId,toolName:e.toolCall.toolName,output:i.output,isError:i.isError}]);return await this.emit({type:"tool-finished",snapshot:this.snapshot(),iteration:this.state.iteration,toolCall:e.toolCall,message:l}),l}finishRun(e,t,n){return this.state.status=e,{agentId:this.state.agentId,agentRole:this.state.agentRole,runId:this.state.runId??xe("run"),status:e,iterations:this.state.iteration,outputText:n??je(t??this.findLastAssistantMessage()),messages:te(this.state.messages),usage:fe(this.state.usage)}}findLastAssistantMessage(){return[...this.state.messages].reverse().find((e)=>e.role==="assistant")}recordCut(e){let t=this.config.onLoopCut;if(!t||!e.text)return;let n={agentId:this.state.agentId,iteration:this.state.iteration,...e};Promise.resolve().then(()=>t(n)).catch((r)=>{this.config.logger?.debug?.(`[loop-cut] could not keep the ${e.channel} cut at iteration ${n.iteration}: ${String(r)}`)})}async onReasoningLoopCut(e,t="reasoning",n="reasoning_loop"){this.reasoningLoopStreak+=1;let r=(this.config.reasoningLoopDetection===!1?void 0:this.config.reasoningLoopDetection?.maxConsecutiveTrips)??Lt.maxConsecutiveTrips,i=Mn(e,t),o=this.reasoningLoopStreak>=r,s=o?await this.config.onReasoningLoopLimitReached?.({iteration:this.state.iteration,consecutiveTrips:this.reasoningLoopStreak,maxConsecutiveTrips:r,diagnosis:i}):void 0,a=s?.action==="continue"?s.guidance?.trim():void 0,l=o&&s?.action!=="continue";if(await this.emit({type:"status-notice",snapshot:this.snapshot(),message:l?`${i} Ending the run after ${this.reasoningLoopStreak} turns cut for this.`:o?`${i} That is ${this.reasoningLoopStreak} turns cut for this, and the run was to end here.`:`${i} Cutting the request and continuing.`,metadata:{kind:"reasoning_loop",reason:"reasoning_loop",phase:l?"aborted":"cut",cause:n,iteration:this.state.iteration,consecutiveTrips:this.reasoningLoopStreak,maxConsecutiveTrips:r,verdict:e,channel:t}}),l){this.abort(new Ie(i)),this.throwIfAborted();return}return a}toolArgumentNames(){let e=new Set;for(let t of this.tools.values()){let n=t.inputSchema?.properties;for(let r of Object.keys(n??{}))e.add(r)}return[...e]}async onToolIntentCut(e){this.toolIntentCutStreak+=1,this.pendingToolIntentNudge=cs(e);let t=e.toolName?`\`${e.toolName}\``:"a tool";this.config.logger?.log?.(`[tool-intent] cut a call to ${t} at iteration ${this.state.iteration}: intent passed ${e.maxChars} characters`),await this.emit({type:"status-notice",snapshot:this.snapshot(),message:`The model was writing its reasoning into the \`intent\` of a call to ${t} (past ${e.maxChars.toLocaleString("en-US")} characters). Cutting the request and asking it to make the call again.`,metadata:{kind:"tool_intent_overrun",reason:"tool_intent_overrun",phase:"cut",iteration:this.state.iteration,overrun:e}})}throwIfAborted(){if(this.abortController?.signal.aborted)throw this.normalizeAbortError()}normalizeAbortError(){let e=this.abortController?.signal.reason;if(e instanceof Error)return e;if(typeof e==="string")return Error(e);return Error(this.state.lastError??"Run aborted")}eventHookMs=new Map;noteEventHookMs(e,t,n){let r=`${e}#${t}`,i=this.eventHookMs.get(r);if(i)i.ms+=n,i.n+=1;else this.eventHookMs.set(r,{ms:n,n:1})}topEventHooks(e=4){return[...this.eventHookMs.entries()].sort((t,n)=>n[1].ms-t[1].ms).slice(0,e).map(([t,n])=>`${t}=${Math.round(n.ms)}ms/${n.n}`).join(" ")}trace(e){eh(e),this.config.logger?.debug?.(`[timing] ${e}`)}async emit(e){let t=Wh(e);switch(e.type){case"run-started":this.config.logger?.info?.("Agent run started",t);break;case"tool-finished":this.config.logger?.info?.("Agent tool finished",t);break;case"run-failed":if(this.config.logger?.error?.("Agent run failed",{...t,error:e.error}),!this.state.lastErrorReported)Ho(this.config.telemetry,{component:"agents",operation:"agent.run",error:e.error,severity:"error",handled:!1,context:{...t,providerId:this.getTelemetryProviderId(),modelId:this.getTelemetryModelId(),...this.state.lastFinishReason?{finishReason:this.state.lastFinishReason}:{}}});break;default:if(!Hh.has(e.type))this.config.logger?.debug?.(`Agent event: ${e.type}`,t);break}switch(e.type){case"assistant-text-delta":case"assistant-reasoning-delta":case"assistant-media":case"tool-updated":break;default:this.config.telemetry?.capture({event:`agent.${e.type}`,properties:t});break}let n=0;for(let r of this.listeners){let i=Date.now();r(e),this.noteEventHookMs(e.type,`listener${n}`,Date.now()-i),n+=1}for(let r=0;r<this.hooks.onEvent.length;r+=1){let i=Date.now();await this.hooks.onEvent[r](e),this.noteEventHookMs(e.type,r,Date.now()-i)}}applyStopControl(e){if(!e?.stop)return;if(e.reason)this.state.lastError=e.reason;throw new Ft(e.reason)}}var Bh={no_tool_call:"the turn ended without calling anything — asking the model to carry on",unparsed_tool_call:"a tool call was written as text and never ran — asking for it again",announced_intent:"the model described the next step instead of taking it — asking it to make the call",non_convergence:"several turns of thinking with no work done — asking for a different approach",silent_repetition:"the turn repeated what the last one said — asking for a different approach"};function qh(e){return Bh[e]??`nudged: ${e}`}var Hh=new Set(["assistant-text-delta","assistant-reasoning-delta","assistant-media","tool-updated"]);function Wh(e){return{agentId:e.snapshot.agentId,agentRole:e.snapshot.agentRole,runId:e.snapshot.runId,status:e.snapshot.status,iteration:e.snapshot.iteration,eventType:e.type}}function Zh(e){return new rt(e)}var Vh=rt;function Gh(e){return new rt(e)}function ys(e){let t=e.search(/<\|?tool_call\|?>/),n=(t<0?e:e.slice(t)).replace(/\s+/g," ").trim(),r=5381;for(let i=0;i<n.length;i++)r=(r<<5)+r+n.charCodeAt(i)|0;return`${n.length}:${r}`}export{Vh as Agent,rt as AgentRuntime,Ie as AgentRuntimeAbortError,kh as DEFAULT_MAX_NO_TOOL_CALL_NUDGES,vs as DEFAULT_NO_TOOL_CALL_TURN_STREAK_LIMIT,Lt as DEFAULT_REASONING_LOOP_GUARD,Ae as DEFAULT_REASONING_REPETITION,Vf as DEFAULT_TOOL_INTENT_MAX_CHARS,bs as NON_CONVERGENCE_MIN_REASONING_CHARS,Ee as ReasoningLoopGuard,nt as ToolCallAssembler,Gh as createAgent,Zh as createAgentRuntime,$n as createRepetitionNudger,Nf as createTool,Mn as describeReasoningLoop,Yo as describeRepetition,Bf as finishToolCalls,Dt as isRepetitionLoop,Un as isToolIntentGuardEnabled,zt as measureReasoningRepetition,Gf as setToolIntentGuardEnabled};