@cerebriline/agents 4.100.290 → 4.100.292
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agent-runtime.d.ts +15 -0
- package/dist/agent-runtime.d.ts.map +1 -1
- package/dist/index.js +32 -24
- package/package.json +3 -3
package/dist/index.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
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 xs(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 As(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)?)?)$/,xa=/^([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})$`)},Aa=/^(?:[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!xs(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):As(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(`
|
|
1
|
+
var Zr="input_progress";var xs=[/\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],Is=new Set([502,503,504]);var cn=/^(?:error:\s*)?evicted to keep other in-flight requests alive\b/i;function Vr(e,t){return t==="kv_evicted"||cn.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(cn.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 Cs=[/projected mean tps below floor/i,/context allocation exhausted/i,/session allocation full/i,/admission (?:rejected|refused|queued)/i,/\btoo many requests\b/i,cn,/\[opencoti_window_unavailable\b/];function Gr(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"||Cs.some((r)=>r.test(n)))return"refusal";if(n&&xs.some((r)=>r.test(n)))return"transport";return}function Ss(e){let t=e.code;return typeof t==="string"?t:void 0}function Rs(e){let t=e.status??e.statusCode;return typeof t==="number"?t:void 0}function dn(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=Rs(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=Ss(e);if(o&&Ne(o)==="transport")return"transport";if(n!==void 0&&Is.has(n))return"transport";if(i)return i;return dn(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 Xn(e,t="|"){return e.map((n)=>ei(n)).join(t)}function Xt(e,t){if(typeof t==="bigint")return t.toString();return t}class Kr{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 Kr(e)}function Os(e){return e===null||e===void 0}function pn(e){let t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function Ns(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 fn(e){let t=Object.getOwnPropertyDescriptor(e,"shape");return t?.get?t.get.raw:t?.value}function pe(e){return fn(e._zod.def)??e._zod.def.shape}function Jr(e,t,n){Object.defineProperty(e,t,{get(){let r=n();return ce(this,t,r),r},enumerable:!0,configurable:!0})}function Yr(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)Jr(e,o,()=>{let a=t._zod.def.shape[o];return r?r(a,o):a});else Yr(e,o,r?r(s.value,o):s.value)}}function Ms(e,t){for(let n of Reflect.ownKeys(t)){let r=Object.getOwnPropertyDescriptor(t,n);if(!r.enumerable)continue;if(r.get)Jr(e,n,()=>t[n]);else Yr(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 Ps(e){return JSON.stringify(e)}function $s(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var Xr="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function Ye(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}var Ls=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 Qr(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 zs=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 ei(e){if(typeof e==="bigint")return e.toString()+"n";if(typeof e==="string")return`"${e}"`;return`${e}`}function Ds(e){return Object.keys(e).filter((t)=>e[t]._zod.optin!==void 0&&e[t]._zod.optout==="optional")}var ti=(()=>({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]}))(),Us={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function Fs(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 js(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 Bs(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:ni(e,t)}))}function ni(e,t){let n={};return _e(n,e,Reflect.ownKeys(pe(e))),Ms(n,t),n}function qs(e,t){if(!Me(t))throw Error("Invalid input to safeExtend: expected a plain object");return Te(e,ee(e._zod.def,{shape:ni(e,t)}))}function Hs(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 Qn(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 Ws(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 Zs(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 er(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 Vs=/[\uD800-\uDBFF]/;function hn(e){let t=e.length;if(!Vs.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 mn(e){if(Array.isArray(e))return"array";if(typeof e==="string")return"string";return"unknown"}function Gs(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 Ks(e,t){for(let n in t){let r=Object.getOwnPropertyDescriptor(t,n);if(r.get)Object.defineProperty(e,n,{...r,enumerable:!1});else Js(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 ri(e,t,n){return be(e,t,n,!1)}function gn(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 Js(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 Ys(e,t){let n=Object.getPrototypeOf(e);return t in n?void 0:n}var qt,me=!1,Xs={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,Xs);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 Qs(e,t,n,r){let i=Ys(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 ea="~constantCatch";function ta(e){let t=()=>e;return t[ea]=!0,t}var tr,Ht={value:void 0,enumerable:!1},nr="captureStackTrace"in Error?Error:null;function na(e){let t=nr;if(t){let n=t.stackTraceLimit;if(typeof n==="number"){try{t.stackTraceLimit=0}catch{return nr=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),Ks(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?na(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 yn extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`);this.name="ZodEncodeError"}}(tr=globalThis).__zod_globalConfig??(tr.__zod_globalConfig={});var re=globalThis.__zod_globalConfig;function ue(e){if(e)Object.assign(re,e);return re}function ra(){let e=this._zod;return e.message??(e.message=JSON.stringify(e.def,Xt,2)),e.message}function ia(e){this._zod.message=e}var oa={get:ra,set:ia,enumerable:!0,configurable:!0},Wt={value:void 0,enumerable:!1},rr=new WeakSet([Object.prototype,Error.prototype]),ii=(e,t)=>{e.name="$ZodError",Wt.value=t,Object.defineProperty(e,"issues",Wt),Wt.value=void 0,Object.defineProperty(e,"message",oa);let n=Object.getPrototypeOf(e);if(!rr.has(n))rr.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})}})},sa=m("$ZodError",ii),oi=m("$ZodError",ii,void 0,{Parent:Error});function aa(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 la(e,t=(n)=>n.message){let n={},r=[];for(let i of e.issues)if(i.path.length>0)aa(n,i.path[0],()=>[]).push(t(i));else r.push(t(i));return{formErrors:r,fieldErrors:n}}function ua(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 Xr(l,o?.callee??t),l}return a.value};return t},ir=Ot(oi),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 Xr(l,o?.callee??t),l}return a.value};return t},or=Nt(oi),vn=(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?si(e,o.issues,i):{success:!0,data:o.value}};function si(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 bn=(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?si(e,o.issues,i):{success:!0,data:o.value}},ca=Symbol.for("zod.compile.invalid"),da=Symbol.for("zod.compile.fallback"),pa=(e,t,n)=>{let r=e._zod.bag.validator;if(r!==void 0){if(r(t)!==ca)return!0;if(r.definite===!0&&n===void 0)return!1}return fa(e,t,n)};function fa(e,t,n){let r=n?{...n,async:!1,abortEarly:!0}:{async:!1,abortEarly:!0},i=e._zod.bag.fallbackRun,o;if(i)r[da]=!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 ha=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},ma=(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},ga=(e)=>{let t=Ot(e),n=(r,i,o,s)=>t(r,i,o,Rt(n,s));return n},ya=(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},va=(e)=>{let t=Nt(e),n=async(r,i,o,s)=>await t(r,i,o,Rt(n,s));return n},ba=(e)=>(t,n,r)=>{let i=r?{...r,direction:"backward"}:{direction:"backward"};return vn(e)(t,n,i)},Ta=(e)=>(t,n,r)=>vn(e)(t,n,r),wa=(e)=>async(t,n,r)=>{let i=r?{...r,direction:"backward"}:{direction:"backward"};return bn(e)(t,n,i)},_a=(e)=>async(t,n,r)=>bn(e)(t,n,r),ka=/^[cC][0-9a-z]{6,}$/,Ea=/^[0-9a-z]+$/,Aa=/^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/,xa=/^[0-9a-vA-V]{20}$/,Ia=/^[A-Za-z0-9]{27}$/,Ca=/^[a-zA-Z0-9_-]{21}$/;function Sa(e){return new RegExp(`^[a-zA-Z0-9_-]{${e}}$`)}var Ra=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Oa=/^([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})$/,sr=(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})$`)},Na=/^(?:[A-Za-z0-9_'+\-]+\.)*[A-Za-z0-9_'+\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Ma="^(?=[\\s\\S]*[\\p{Extended_Pictographic}\\p{Regional_Indicator}\\u20E3])[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$";function Pa(){return new RegExp(Ma,"u")}var $a=/^(?:(?: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])$/,La=/^(([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}|:))$/,za=/^((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])$/,Da=/^(([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])$/,Ua=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Fa=/^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/,ja=/^https?$/,Ba=/^\+[1-9]\d{6,14}$/,ai="(?:(?:\\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 qa(e){return new RegExp(`^${e}$`)}var Ha=qa(ai);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 Wa(e){return new RegExp(`^${en(e)}$`)}function Za(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(`^${ai}T(?:${r})$`)}var Va=/^[\s\S]{0,}$/,Ga=/^-?\d+$/,Tn=/^-?\d+(?:\.\d+)?$/,Ka=/^(?:true|false)$/i,Ja=/^[^A-Z]*$/,Ya=/^[^a-z]*$/,Q=m("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),wn=(e)=>{let t=e.value;return!Os(t)&&t.length!==void 0},bt={number:"number",bigint:"bigint",object:"date"},li=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})}}),ui=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})}}),Xa=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):Ns(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})}}),Qa=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]=ti[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})}}),el=m("$ZodCheckMaxLength",(e,t)=>{var n;Q.init(e,t),(n=e._zod.def).when??(n.when=wn),e._zod.check=(r)=>{let i=r.value,o=i.length;if((typeof i==="string"&&o>t.maximum?hn(i):o)<=t.maximum)return;let s=mn(i);r.issues.push({origin:s,code:"too_big",maximum:t.maximum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),tl=m("$ZodCheckMinLength",(e,t)=>{var n;Q.init(e,t),(n=e._zod.def).when??(n.when=wn),e._zod.check=(r)=>{let i=r.value,o=i.length;if((typeof i==="string"&&o>=t.minimum&&o<t.minimum*2?hn(i):o)>=t.minimum)return;let s=mn(i);r.issues.push({origin:s,code:"too_small",minimum:t.minimum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),nl=m("$ZodCheckLengthEquals",(e,t)=>{var n;Q.init(e,t),(n=e._zod.def).when??(n.when=wn),e._zod.check=(r)=>{let i=r.value,o=i.length,s=typeof i==="string"&&o>=t.length&&o<=t.length*2?hn(i):o;if(s===t.length)return;let a=mn(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=()=>{})}),rl=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})}}),il=m("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=Ja),Mt.init(e,t)}),ol=m("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=Ya),Mt.init(e,t)}),sl=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})}}),al=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})}}),ll=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})}}),ul=m("$ZodCheckOverwrite",(e,t)=>{Q.init(e,t),e._zod.check=(n)=>{n.value=t.tx(n.value)}});class ci{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
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
3
|
${t.join(`
|
|
4
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=xa),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=Aa),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)}),xl=m("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=Ea),z.init(e,t)}),Al=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)=>`
|
|
5
|
+
};`)(...Object.values(this.closed))}}var cl={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=cl;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(Zs(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 ri(this,"~standard",pi(this))},set "~standard"(e){be(this,"~standard",e)}}),di=(e,t)=>e.issues.length?{issues:e.issues.map((n)=>ve(n,t,ue()))}:{value:e.value};async function dl(e,t){let n={async:!0};return di(await e._zod.run({value:t,issues:[]},n),n)}function pi(e){return{validate:(t)=>{let n={async:!1};try{let r=e._zod.run({value:t,issues:[]},n);if(!(r instanceof Promise))return di(r,n)}catch(r){}return dl(e,t)},vendor:"zod",version:1}}var _n=m("$ZodString",(e,t)=>{N.init(e,t),e._zod.pattern=t.pattern??Va,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),_n.init(e,t)}),pl=m("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=Oa),z.init(e,t)}),fl=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=sr(n))}else t.pattern??(t.pattern=sr());z.init(e,t)}),hl=m("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=Na),z.init(e,t)}),fi=1,Tt=2;function hi(e){try{if(typeof URL<"u"&&typeof URL.canParse==="function")return URL.canParse(e);return new URL(e),!0}catch{return!1}}function ml(e,t){if(!("normalize"in t)&&!("hostname"in t)&&!("protocol"in t))return hi(e)||Tt;return gl(e,t)}function gl(e,t){if(!t.normalize&&t.protocol?.source===ja.source&&!/^https?:\/\//i.test(e))return fi;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 yl=/[\t\n\r]/g;function ar(e){return e.replace(yl,"")}function vl(e,t){return t.lastIndex=0,t.test(e.hostname)}function bl(e,t){return t.lastIndex=0,t.test(e.protocol.endsWith(":")?e.protocol.slice(0,-1):e.protocol)}var Tl=m("$ZodURL",(e,t)=>{z.init(e,t),e._zod.check=(n)=>{try{let r=n.value.trim(),i=ml(r,t);if(i===fi){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=ar(r);return}if(t.hostname&&!vl(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&&!bl(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:ar(r);return}catch(r){n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),wl=m("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=Pa()),z.init(e,t)}),_l=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?Ca:Sa(t.length)),z.init(e,t)}),kl=m("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=ka),z.init(e,t)}),El=m("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=Ea),z.init(e,t)}),Al=m("$ZodULID",(e,t)=>{t.pattern??(t.pattern=Aa),z.init(e,t)}),xl=m("$ZodXID",(e,t)=>{t.pattern??(t.pattern=xa),z.init(e,t)}),Il=m("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=Ia),z.init(e,t)}),Cl=m("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=Za(t)),z.init(e,t)}),Sl=m("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=Ha),z.init(e,t)}),Rl=m("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=Wa(t)),z.init(e,t)}),Ol=m("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=Ra),z.init(e,t)}),Nl=m("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=$a),z.init(e,t)}),Ml=/^[0-9a-fA-F:.]+$/;function mi(e){if(!Ml.test(e))return!1;return hi(`http://[${e}]`)}var Pl=m("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=La),z.init(e,t),e._zod.check=(n)=>{if(!mi(n.value))n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}}),$l=m("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=za),z.init(e,t)});function Ll(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 mi(n)}var zl=m("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=Da),z.init(e,t),e._zod.check=(n)=>{if(!Ll(n.value))n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}});function gi(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 yi=/^[0-9a-zA-Z+/]*={0,2}$/,Dl=m("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=yi),z.init(e,t),e._zod.check=(n)=>{if(gi(n.value))return;n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}}),kn=/^[A-Za-z0-9_-]*$/;function Ul(e){if(!kn.test(e))return!1;let t=e.replace(/[-_]/g,(r)=>r==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return gi(n)}var Fl=m("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=kn),z.init(e,t),e._zod.check=(n)=>{if(Ul(n.value))return;n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),jl=m("$ZodE164",(e,t)=>{t.pattern??(t.pattern=Ba),z.init(e,t)});function Bl(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 ql=m("$ZodJWT",(e,t)=>{z.init(e,t),e._zod.check=(n)=>{if(Bl(n.value,t.alg))return;n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),vi=m("$ZodNumber",(e,t)=>{N.init(e,t),e._zod.pattern=Tn,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}}),Hl=m("$ZodNumberFormat",(e,t)=>{Qa.init(e,t),vi.init(e,t)}),Wl=m("$ZodBoolean",(e,t)=>{N.init(e,t),e._zod.pattern=Ka,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}}),Zl=m("$ZodUnknown",(e,t)=>{N.init(e,t),e._zod.parse=(n)=>n}),Vl=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)}),Gl=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}}),Kl=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 Jl(e,t){let n=er(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 er(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 Yl=(e)=>Array.isArray(e)?e.length:-1;function lr(e,t,n){if(e.issues.length)t.issues.push(...ge(n,e.issues));t.value[n]=e.value}var Xl=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)=>lr(h,r,l)));else if(lr(d,r,l),a&&d.issues.length!==0&&le(d))break}if(s.length)return Promise.all(s).then(()=>r);return r},Jl(e,Yl)});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 Ql=[];function bi(e){let t=Object.keys(e.shape),n=Object.getOwnPropertySymbols(e.shape),r=n.length?n:Ql,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=Ds(e.shape);return{...e,allKeys:i,symbolKeys:r,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(o)}}function Ti(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 eu=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(()=>bi(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 Ti(p,h,u,d,i.value,e,g===!0)}}),tu=m("$ZodObjectJIT",(e,t)=>{eu.init(e,t);let n=e._zod.parse,r=Ct(()=>bi(t)),i=re.memoizer,o=(p)=>{let f=r.value,g=f.symbolKeys,T=new ci(["payload","ctx"],{shape:p,inst:e,memo:i,syms:g}),k=(P)=>`shape[${P}]._zod.run({ value: input[${P}], issues: [] }, ctx)`,_=(P,E)=>`
|
|
6
6
|
let ${P}_ab = false;
|
|
7
7
|
for (let i = 0; i < ${P}.issues.length; i++) {
|
|
8
8
|
const iss = ${P}.issues[i];
|
|
@@ -13,7 +13,7 @@ ${t.join(`
|
|
|
13
13
|
if (${P}_ab && ctx && ctx.abortEarly) {
|
|
14
14
|
payload.value = newResult;
|
|
15
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)}]`:
|
|
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)}]`:Ps(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
17
|
const ${E}_present = ${he};
|
|
18
18
|
if (!${E}.issues.length || ${E}_present) {
|
|
19
19
|
if (${E}.issues.length) {${_(E,V)}
|
|
@@ -52,9 +52,9 @@ ${t.join(`
|
|
|
52
52
|
if (${E}.value !== undefined || ${he}) {
|
|
53
53
|
newResult[${V}] = ${E}.value;
|
|
54
54
|
}
|
|
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 xi=new WeakMap,He=0,mt=1,Ge=2;function gt(e,t,n){let r=xi.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)xi.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 Ai{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 Ai}(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 xu(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...w(t)})}function Au(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>
|
|
55
|
+
`)}return T.write("payload.value = newResult;"),T.write("return payload;"),T.compile()},s,a=Ye,l=!re.jitless,u=l&&Ls.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 Ti([],g,p,f,h,e,f?.abortEarly===!0)}return n(p,f)}});function ur(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 wi=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)=>pn(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 ur(s,r,e,i);return Promise.all(s).then((a)=>ur(a,r,e,i))}});function nu(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 ru=m("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,wi.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=fn(i._zod.def);if(s&&!Object.prototype.hasOwnProperty.call(s,t.discriminator))throw Error(`Invalid discriminated union option at index "${o}"`)});let r=Ct(()=>nu(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}}),iu=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])=>cr(n,a,l));return cr(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 cr(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 _i=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=dr(n,"optin"),u=dr(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)=>pr(B,i,f)));else pr(_,i,f)}}if(a.length)return Promise.all(a).then(()=>fr(d,i,n,s,u));return fr(d,i,n,s,u)}});function dr(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 pr(e,t,n){if(e.issues.length)t.issues.push(...ge(n,e.issues));t.value[n]=e.value}function fr(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 ou=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"&&Tn.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}}),su=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)=>zs.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}}),au=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}}),lu=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 yn(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 hr(e,t){return e.value=t.issues.length?void 0:t.value,e}var ki=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(`^(${pn(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)=>hr(n,o));return hr(n,i)}return t.innerType._zod.run(n,r)}}),uu=m("$ZodExactOptional",(e,t)=>{ki.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)}),cu=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(`^(${pn(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)}}),du=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)=>mr(o,t));return mr(i,t)}});function mr(e,t){if(e.value===void 0)e.value=t.defaultValue;return e}var pu=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)}}),fu=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)=>gr(o,e));return gr(i,e)}});function gr(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 yr(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 hu=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)=>yr(n,o,t,r));return yr(n,i,t,r)}}),Ei=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 mu=m("$ZodPreprocess",(e,t)=>{Ei.init(e,t)}),gu=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(vr);return vr(i)}});function vr(e){if(!e.memo)e.value=Object.freeze(e.value);return e}var yu=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?ir(e._def.input,r):r,o=Reflect.apply(n,this,i);if(e._def.output)return ir(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 or(e._def.input,r):r,o=await Reflect.apply(n,this,i);if(e._def.output)return await or(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 _i({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)),vu=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))}),bu=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)=>br(o,n,r,e));br(i,n,r,e);return}});function br(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 Ai extends Error{constructor(){super("Cannot parse a reference cycle that closes through a transform");this.name="ZodCyclicError"}}var nn="~memo",Tr=[];function xi(e){return e!==null&&typeof e==="object"}function Zt(e){return e.map((t)=>t.path?{...t,path:t.path.slice()}:{...t})}var Ii=new WeakMap,He=0,mt=1,Ge=2;function gt(e,t,n){let r=Ii.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=fn(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),Tu(e,i)}function Tu(e,t){if(t!==mt)Ii.set(e,t===Ge);return t}function wu(e,t){let n=e.buckets.get(t);if(!n)n=new WeakMap,e.buckets.set(t,n);return n}var ct,dt=[],_u={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"&&Eu(o,i.value))throw new Ai;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(!xi(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=wu(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):Tr;return _});if(k)k.issues=T.issues.length?Zt(T.issues):Tr;return T};if(e._zod.parse=a,e._zod.run===s)e._zod.run=a})}};function ku(){return _u}function Eu(e,t){let n=e[nn]?.backEdges;return n!==void 0&&xi(t)&&n.has(t)}var Au=()=>{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=Gs(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 ${ei(o.values[0])}`;return`Invalid option: expected one of ${Xn(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":""}: ${Xn(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 xu(){return{localeError:Au()}}var wr;class Ci{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 Iu(){return new Ci}(wr=globalThis).__zod_globalRegistry??(wr.__zod_globalRegistry=Iu());var We=globalThis.__zod_globalRegistry;function Si(e){if(e.checks)e.checks=[...e.checks];return e}function Cu(e,t){return new e(Si({type:"string",...w(t)}))}function Su(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...w(t)})}function Ru(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...w(t)})}function Ou(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...w(t)})}function Nu(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...w(t)})}function Mu(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...w(t)})}function Pu(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...w(t)})}function $u(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...w(t)})}function Lu(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...w(t)})}function zu(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...w(t)})}function Du(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...w(t)})}function Uu(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...w(t)})}function Fu(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...w(t)})}function ju(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...w(t)})}function Bu(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...w(t)})}function qu(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...w(t)})}function Hu(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...w(t)})}function Wu(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...w(t)})}function Zu(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...w(t)})}function Vu(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...w(t)})}function Gu(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...w(t)})}function Ku(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...w(t)})}function Ju(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...w(t)})}function Yu(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...w(t)})}function Xu(e,t){return new e({type:"string",format:"date",check:"string_format",...w(t)})}function Qu(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...w(t)})}function ec(e,t){return new e({type:"string",format:"duration",check:"string_format",...w(t)})}function tc(e,t){return new e(Si({type:"number",checks:[],...w(t)}))}function nc(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...w(t)})}function rc(e,t){return new e({type:"boolean",...w(t)})}function ic(e){return new e({type:"unknown"})}function oc(e,t){return new e({type:"never",...w(t)})}function sc(e,t){return new e({type:"void",...w(t)})}function ac(e,t){return new e({type:"date",...w(t)})}function _r(e,t){return new li({check:"less_than",...w(t),value:e,inclusive:!1})}function yt(e,t){return new li({check:"less_than",...w(t),value:e,inclusive:!0})}function kr(e,t){return new ui({check:"greater_than",...w(t),value:e,inclusive:!1})}function vt(e,t){return new ui({check:"greater_than",...w(t),value:e,inclusive:!0})}function Er(e,t){return new Xa({check:"multiple_of",...w(t),value:e})}function Ri(e,t){return new el({check:"max_length",...w(t),maximum:e})}function _t(e,t){return new tl({check:"min_length",...w(t),minimum:e})}function Oi(e,t){return new nl({check:"length_equals",...w(t),length:e})}function lc(e,t){return new rl({check:"string_format",format:"regex",...w(t),pattern:e})}function uc(e){return new il({check:"string_format",format:"lowercase",...w(e)})}function cc(e){return new ol({check:"string_format",format:"uppercase",...w(e)})}function dc(e,t){return new sl({check:"string_format",format:"includes",...w(t),includes:e})}function pc(e,t){return new al({check:"string_format",format:"starts_with",...w(t),prefix:e})}function fc(e,t){return new ll({check:"string_format",format:"ends_with",...w(t),suffix:e})}function De(e){return new ul({check:"overwrite",tx:e})}function hc(e){return De((t)=>t.normalize(e))}function mc(){return De((e)=>e.trim())}function gc(){return De((e)=>e.toLowerCase())}function yc(){return De((e)=>e.toUpperCase())}function vc(){return De((e)=>$s(e))}function bc(e,t,n){return new e({type:"array",element:t,...w(n)})}function Tc(e,t,n){let r=w(n);return r.abort??(r.abort=!0),new e({type:"custom",check:"custom",fn:t,...r})}function wc(e,t,n){return new e({type:"custom",check:"custom",fn:t,...w(n)})}function _c(e,t){let n=kc((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 kc(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 Ar(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}/${Ar(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+Ar(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>
|
|
56
56
|
|
|
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"]),xr=["oneOf","anyOf"];function Ar(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]??Ar(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=Ar(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)=>xr.some((o)=>Array.isArray(i[o]))),r=null;if(!n.length)r=rn(t);else{let i=n[0],o=xr.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 xt(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:At(t,"input",e.processors),output:At(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),xt(r,e)},At=(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),xt(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")},xc=(e,t,n,r)=>{if(t.target==="openapi-3.0")n.type="string",n.nullable=!0,n.enum=[null];else n.type="null"},Ac=(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:xc,undefined:Ac,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,xt(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),xt(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 A(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:At(this,"input"),output:At(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(xu(ft,e))},uuidv4(e){return this.check(Au(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)=>{xl.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)=>{Al.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 xd=m("ZodVoid",(e,t)=>{Bl.init(e,t),M.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Fi(e,n,r,i)});function Ad(e){return ec(xd,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 A(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(An,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 xn(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 An({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 An=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 An({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??A(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=xn("type",[y({type:U("toggle")}).strict(),y({type:U("effort"),values:A(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:A(Dr),output:A(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:A(ip).optional(),operation:cp.optional(),operationModes:A(dp).optional(),modalities:up.optional(),reasoningOptions:A(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()}),Jh=y({text:c(),usage:hp,messages:A(ne()),toolCalls:A(pp),iterations:b(),finishReason:fp,model:y({id:c(),provider:c(),info:wo.optional()}),startedAt:It(),endedAt:It(),durationMs:b()}),Yh=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:A(ne()).optional(),systemPrompt:c(),tools:A(ne()),modelTools:A(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(Ad()).optional(),hooks:ne().optional(),parentAgentId:c().optional(),extensions:A(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()}),Xh=y({actor:gp,context:yp,payload:j(c(),W()).optional()}),Qh=y({action:I(["allow","deny"]).default("allow"),message:c().optional(),reason:c().optional(),metadata:j(c(),W()).optional()}),em=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"],tm=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"},nm={[Ze.CLINE_PASS]:!1,[Ze.CODE_CLOUD_AGENTS]:!1,[Ze.CODE_ONBOARDING_GITHUB]:!1,[Ze.CLINE_COMPOSIO_BETA]:!1},rm=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:A(c())}),kp=y({taskMetadata:ke}),Ep=y({taskMetadata:ke,previousState:ke}),xp=y({taskMetadata:ke}),Ap=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()}),im=y({clineVersion:c(),hookName:bp,timestamp:c(),taskId:c(),sessionContext:y({rootSessionId:c().optional(),hookLogPath:c().optional()}).optional(),workspaceRoots:A(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:xp.optional(),taskComplete:Ap.optional(),preCompact:Ip.optional()}).passthrough();var Cp=["readFile","search","bash","webFetch","editor","applyPatch","skills","askQuestion","submit"],om=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 xo(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 Ao(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=xn("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 sm=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)`,Jp=String.raw`\s*,\s*([A-Za-z_]\w*)\s*:\s*(?:\[\s*[\x60"']?|\{|[\x60"'])?`,am=new RegExp(String.raw`(${Gp})((?:${Kp})*)(?:${Jp})?[ \t]*\}?[ \t]*$`);function Yp(e){return Lc(e)}var lm=new RegExp(`${"⟦"}([^${"⟧"}]*)${"⟧"}([\\s\\S]*?)${"⟦/⟧"}`,"g");var Lo=`# 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 Ni(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;Ni(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 Mi=new Set(["type","properties","required","additionalProperties"]),xr=["oneOf","anyOf"];function Ir(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(!Mi.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]??Ir(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=Ir(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 Ec(e){let t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(let i of Mi)if(i in e)return;let n=t.filter((i)=>xr.some((o)=>Array.isArray(i[o]))),r=null;if(!n.length)r=rn(t);else{let i=n[0],o=xr.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())Ni(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)??[])Ec(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 Ac=(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},Cr=(e,t)=>{$e(e,"minimum",t),Le(e,"maximum",t)},Pi=(e,t)=>{if(e.multipleOf??(e.multipleOf=[]),!e.multipleOf.includes(t))e.multipleOf.push(t)},$i=(e,t)=>{e.patterns??(e.patterns=new Set),e.patterns.add(t)},Li=(e,t)=>{e.mime=e.mime?e.mime.filter((n)=>t.includes(n)):[...t]},zi=(e,t)=>{if(e.format=t,t.includes("int"))e.isInt=!0},Sr=(e,t)=>$e(e,"minimum",t.minimum),Rr=(e,t)=>Le(e,"maximum",t.maximum),Or=(e)=>(t,n)=>{zi(t,n.format);let[r,i]=e[n.format];$e(t,"minimum",r),Le(t,"maximum",i)},xc={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)=>Pi(e,t.value),number_format:Or(ti),bigint_format:Or(Us),min_length:Sr,max_length:Rr,length_equals:(e,t)=>Cr(e,t.length),min_size:Sr,max_size:Rr,size_equals:(e,t)=>Cr(e,t.size),string_format:(e,t)=>{if(zi(e,t.format),t.pattern)$i(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)=>Li(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)xc[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)Pi(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)Li(t,i.mime);for(let o of i.patterns??[])$i(t,o);return t}var Ic={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},Cc=new Map([[yi,Ua],[kn,Fa]]),Di=(e)=>Cc.get(e)??e,Ui=(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=Ic[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(Di);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}))]}},Fi=(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:_}))]}},ji=(e,t,n,r)=>{n.type="boolean"},Sc=(e,t,n,r)=>{Z(e,t,n,r,"BigInt cannot be represented in JSON Schema")},Rc=(e,t,n,r)=>{Z(e,t,n,r,"Symbols cannot be represented in JSON Schema")},Oc=(e,t,n,r)=>{if(t.target==="openapi-3.0")n.type="string",n.nullable=!0,n.enum=[null];else n.type="null"},Nc=(e,t,n,r)=>{Z(e,t,n,r,"Undefined cannot be represented in JSON Schema")},Bi=(e,t,n,r)=>{Z(e,t,n,r,"Void cannot be represented in JSON Schema")},qi=(e,t,n,r)=>{n.not={}},Mc=(e,t,n,r)=>{},Hi=(e,t,n,r)=>{},Wi=(e,t,n,r)=>{Z(e,t,n,r,"Date cannot be represented in JSON Schema")},Zi=(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},Vi=(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}},Pc=(e,t,n,r)=>{Z(e,t,n,r,"NaN cannot be represented in JSON Schema")},$c=(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},Lc=(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}))},zc=(e,t,n,r)=>{n.type="boolean"},Gi=(e,t,n,r)=>{Z(e,t,n,r,"Custom types cannot be represented in JSON Schema")},Ki=(e,t,n,r)=>{Z(e,t,n,r,"Function types cannot be represented in JSON Schema")},Ji=(e,t,n,r)=>{Z(e,t,n,r,"Transforms cannot be represented in JSON Schema")},Dc=(e,t,n,r)=>{Z(e,t,n,r,"Map cannot be represented in JSON Schema")},Uc=(e,t,n,r)=>{Z(e,t,n,r,"Set cannot be represented in JSON Schema")},Yi=(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 Xi=(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"]})},Qi=(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},eo=(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)},to=(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")?Tn:Ga).source;return f}var sn=new WeakMap;function Fc(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 no=(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,Di(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(()=>Fc(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)}},ro=(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"}]},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},En=Symbol();function oo(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"),En}var 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=oo(i.defaultValue,e,t,n,r);if(s!==En)n.default=s},ao=(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=oo(i.defaultValue,e,t,n,r);if(s!==En)n._prefault=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;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},uo=(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},co=(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},po=(e,t,n,r)=>{let i=e._zod.def;L(i.innerType,t,r);let o=t.seen.get(e);o.ref=i.innerType},An=(e,t,n,r)=>{let i=e._zod.def;L(i.innerType,t,r);let o=t.seen.get(e);o.ref=i.innerType},jc=(e,t,n,r)=>{let i=e._zod.innerType;L(i,t,r);let o=t.seen.get(e);o.ref=i},Nr={string:Ui,number:Fi,boolean:ji,bigint:Sc,symbol:Rc,null:Oc,undefined:Nc,void:Bi,never:qi,any:Mc,unknown:Hi,date:Wi,enum:Zi,literal:Vi,nan:Pc,template_literal:$c,file:Lc,success:zc,custom:Gi,function:Ki,transform:Ji,map:Dc,set:Uc,array:Yi,object:Xi,union:Qi,intersection:eo,tuple:to,record:no,nullable:ro,nonoptional:io,default:so,prefault:ao,catch:lo,pipe:uo,readonly:co,promise:po,optional:An,lazy:jc};function Bc(e,t){if("_idmap"in e){let r=e,i=kt({...t,processors:Nr}),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:Nr});return L(e,n),Et(n,e),At(n,e)}var Mr=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 qc=(e,t)=>{sa.init(e,t),e.name="ZodError";let n=Object.getPrototypeOf(e);if(Mr.has(n))return;Mr.add(n),pt(n,"format",(r)=>(i)=>ua(r,i)),pt(n,"flatten",(r)=>(i)=>la(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",qc,void 0,{Parent:Error}),Hc=Ot(ie),Wc=Nt(ie),Zc=vn(ie),Vc=bn(ie),Gc=ma(ie),Kc=ga(ie),Jc=ya(ie),Yc=va(ie),Xc=ba(ie),Qc=Ta(ie),ed=wa(ie),td=_a(ie);function nd(){if(!re.localeError)ue(xu())}function et(){if(!re.memoizer)ue({memoizer:ku()})}var M=m("ZodType",(e,t)=>(nd(),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(rp(e,t))},superRefine(e,t){return this.check(ip(e,t))},overwrite(e){return this.check(De(e))},optional(){return Lr(this)},exactOptional(){return qd(this)},nullable(){return zr(this)},nullish(){return Lr(zr(this))},nonoptional(e){return Kd(this,e)},array(){return x(this)},or(e){return se([this,e])},and(e){return Dd(this,e)},transform(e){return Dr(this,go(e))},default(e){return Zd(this,e)},prefault(e){return Gd(this,e)},catch(e){return Yd(this,e)},pipe(e){return Dr(this,e)},readonly(){return ep(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 ri(this,"~standard",{...pi(this),jsonSchema:{input:xt(this,"input"),output:xt(this,"output")}})},set "~standard"(e){be(this,"~standard",e)},parse:function e(t,n){return Hc(this,t,n,{callee:e})},parseAsync:async function e(t,n){return await Wc(this,t,n,{callee:e})},safeParse(e,t){return Zc(this,e,t)},async safeParseAsync(e,t){return Vc(this,e,t)},get spa(){return this?.safeParseAsync},set spa(e){be(this,"spa",e)},validate(e,t){return pa(this,e,t)},validateAsync(e,t){return ha(this,e,t)},encode:function e(t,n){return Gc(this,t,n,{callee:e})},decode:function e(t,n){return Kc(this,t,n,{callee:e})},encodeAsync:async function e(t,n){return await Jc(this,t,n,{callee:e})},decodeAsync:async function e(t,n){return await Yc(this,t,n,{callee:e})},safeEncode(e,t){return Xc(this,e,t)},safeDecode(e,t){return Qc(this,e,t)},async safeEncodeAsync(e,t){return ed(this,e,t)},async safeDecodeAsync(e,t){return td(this,e,t)},toJSONSchema(e){return Ac(this,{})(e)},get description(){return We.get(this)?.description},get _def(){return this._zod.def}}),fo=m("_ZodString",(e,t)=>{_n.init(e,t),M.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Ui(e,n,r,i)},gn({format:(e)=>X(e).format??null,minLength:(e)=>X(e).minimum??null,maxLength:(e)=>X(e).maximum??null},{regex(...e){return this.check(lc(...e))},includes(...e){return this.check(dc(...e))},startsWith(...e){return this.check(pc(...e))},endsWith(...e){return this.check(fc(...e))},min(...e){return this.check(_t(...e))},max(...e){return this.check(Ri(...e))},length(...e){return this.check(Oi(...e))},nonempty(...e){return this.check(_t(1,...e))},lowercase(e){return this.check(uc(e))},uppercase(e){return this.check(cc(e))},trim(){return this.check(mc())},normalize(...e){return this.check(hc(...e))},toLowerCase(){return this.check(gc())},toUpperCase(){return this.check(yc())},slugify(){return this.check(vc())}})),rd=m("ZodString",(e,t)=>{_n.init(e,t),fo.init(e,t)},{email(e){return this.check(Su(ld,e))},url(e){return this.check($u(cd,e))},jwt(e){return this.check(Ju(Ad,e))},emoji(e){return this.check(Lu(dd,e))},guid(e){return this.check(Ru(ud,e))},uuid(e){return this.check(Ou(ft,e))},uuidv4(e){return this.check(Nu(ft,e))},uuidv6(e){return this.check(Mu(ft,e))},uuidv7(e){return this.check(Pu(ft,e))},nanoid(e){return this.check(zu(pd,e))},cuid(e){return this.check(Du(fd,e))},cuid2(e){return this.check(Uu(hd,e))},ulid(e){return this.check(Fu(md,e))},base64(e){return this.check(Vu(_d,e))},base64url(e){return this.check(Gu(kd,e))},xid(e){return this.check(ju(gd,e))},ksuid(e){return this.check(Bu(yd,e))},ipv4(e){return this.check(qu(vd,e))},ipv6(e){return this.check(Hu(bd,e))},cidrv4(e){return this.check(Wu(Td,e))},cidrv6(e){return this.check(Zu(wd,e))},e164(e){return this.check(Ku(Ed,e))},datetime(e){return this.check(Yu(id,e))},date(e){return this.check(Xu(od,e))},time(e){return this.check(Qu(sd,e))},duration(e){return this.check(ec(ad,e))}});function c(e){return Cu(rd,e)}var D=m("ZodStringFormat",(e,t)=>{z.init(e,t),fo.init(e,t)}),id=m("ZodISODateTime",(e,t)=>{Cl.init(e,t),D.init(e,t)}),od=m("ZodISODate",(e,t)=>{Sl.init(e,t),D.init(e,t)}),sd=m("ZodISOTime",(e,t)=>{Rl.init(e,t),D.init(e,t)}),ad=m("ZodISODuration",(e,t)=>{Ol.init(e,t),D.init(e,t)}),ld=m("ZodEmail",(e,t)=>{hl.init(e,t),D.init(e,t)}),ud=m("ZodGUID",(e,t)=>{pl.init(e,t),D.init(e,t)}),ft=m("ZodUUID",(e,t)=>{fl.init(e,t),D.init(e,t)}),cd=m("ZodURL",(e,t)=>{Tl.init(e,t),D.init(e,t)}),dd=m("ZodEmoji",(e,t)=>{wl.init(e,t),D.init(e,t)}),pd=m("ZodNanoID",(e,t)=>{_l.init(e,t),D.init(e,t)}),fd=m("ZodCUID",(e,t)=>{kl.init(e,t),D.init(e,t)}),hd=m("ZodCUID2",(e,t)=>{El.init(e,t),D.init(e,t)}),md=m("ZodULID",(e,t)=>{Al.init(e,t),D.init(e,t)}),gd=m("ZodXID",(e,t)=>{xl.init(e,t),D.init(e,t)}),yd=m("ZodKSUID",(e,t)=>{Il.init(e,t),D.init(e,t)}),vd=m("ZodIPv4",(e,t)=>{Nl.init(e,t),D.init(e,t)}),bd=m("ZodIPv6",(e,t)=>{Pl.init(e,t),D.init(e,t)}),Td=m("ZodCIDRv4",(e,t)=>{$l.init(e,t),D.init(e,t)}),wd=m("ZodCIDRv6",(e,t)=>{zl.init(e,t),D.init(e,t)}),_d=m("ZodBase64",(e,t)=>{Dl.init(e,t),D.init(e,t)}),kd=m("ZodBase64URL",(e,t)=>{Fl.init(e,t),D.init(e,t)}),Ed=m("ZodE164",(e,t)=>{jl.init(e,t),D.init(e,t)}),Ad=m("ZodJWT",(e,t)=>{ql.init(e,t),D.init(e,t)}),ho=m("ZodNumber",(e,t)=>{vi.init(e,t),M.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Fi(e,n,r,i),e.isFinite=!0},gn({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(kr(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(_r(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(Pr(e))},safe(e){return this.check(Pr(e))},positive(e){return this.check(kr(0,e))},nonnegative(e){return this.check(vt(0,e))},negative(e){return this.check(_r(0,e))},nonpositive(e){return this.check(yt(0,e))},multipleOf(e,t){return this.check(Er(e,t))},step(e,t){return this.check(Er(e,t))},finite(){return this}}));function b(e){return tc(ho,e)}var xd=m("ZodNumberFormat",(e,t)=>{Hl.init(e,t),ho.init(e,t)});function Pr(e){return nc(xd,e)}var Id=m("ZodBoolean",(e,t)=>{Wl.init(e,t),M.init(e,t),e._zod.processJSONSchema=(n,r,i)=>ji(e,n,r,i)});function S(e){return rc(Id,e)}var Cd=m("ZodUnknown",(e,t)=>{Zl.init(e,t),M.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Hi(e,n,r,i)});function W(){return ic(Cd)}var Sd=m("ZodNever",(e,t)=>{Vl.init(e,t),M.init(e,t),e._zod.processJSONSchema=(n,r,i)=>qi(e,n,r,i)});function Rd(e){return oc(Sd,e)}var Od=m("ZodVoid",(e,t)=>{Gl.init(e,t),M.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Bi(e,n,r,i)});function Nd(e){return sc(Od,e)}var Md=m("ZodDate",(e,t)=>{Kl.init(e,t),M.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Wi(e,n,r,i),e.min=(n,r)=>e.check(vt(n,r)),e.max=(n,r)=>e.check(yt(n,r))},gn({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 ac(Md,e)}var Pd=m("ZodArray",(e,t)=>{et(),Xl.init(e,t),M.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Yi(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(Ri(e,t))},length(e,t){return this.check(Oi(e,t))},unwrap(){return this.element}});function x(e,t){return bc(Pd,e,t)}var $d=m("ZodObject",(e,t)=>{et(),tu.init(e,t),M.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Xi(e,n,r,i),Qs(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:Rd()}))},strip(){return this.clone(ee(this._zod.def,{catchall:void 0}))},extend(e){return Bs(this,e)},safeExtend(e){return qs(this,e)},merge(e){return Hs(this,e)},pick(e){return Fs(this,e)},omit(e){return js(this,e)},partial(...e){return Qn(In,this,e[0])},exactPartial(...e){return Qn(yo,this,e[0],"exactPartial")},required(...e){return Ws(vo,this,e[0])}});function y(e,t){let n={type:"object",shape:e??{},...w(t)};return new $d(n)}var mo=m("ZodUnion",(e,t)=>{wi.init(e,t),M.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Qi(e,n,r,i),e.options=t.options});function se(e,t){return new mo({type:"union",options:e,...w(t)})}var Ld=m("ZodDiscriminatedUnion",(e,t)=>{mo.init(e,t),ru.init(e,t)});function xn(e,t,n){return new Ld({type:"union",options:t,discriminator:e,...w(n)})}var zd=m("ZodIntersection",(e,t)=>{iu.init(e,t),M.init(e,t),e._zod.processJSONSchema=(n,r,i)=>eo(e,n,r,i)});function Dd(e,t){return new zd({type:"intersection",left:e,right:t})}var Ud=m("ZodTuple",(e,t)=>{et(),_i.init(e,t),M.init(e,t),e._zod.processJSONSchema=(n,r,i)=>to(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 In({type:"optional",innerType:t}))})}});function Fd(e,t,n){let r=t instanceof N;return new Ud({type:"tuple",items:e,rest:r?t:null,...w(r?n:t)})}var $r=m("ZodRecord",(e,t)=>{et(),ou.init(e,t),M.init(e,t),e._zod.processJSONSchema=(n,r,i)=>no(e,n,r,i),e.keyType=t.keyType,e.valueType=t.valueType});function j(e,t,n){if(!t||!t._zod)return new $r({type:"record",keyType:c(),valueType:e,...w(t)});return new $r({type:"record",keyType:e,valueType:t,...w(n)})}var an=m("ZodEnum",(e,t)=>{su.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,i,o)=>Zi(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 jd=m("ZodLiteral",(e,t)=>{au.init(e,t),M.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Vi(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 jd({type:"literal",values:Array.isArray(e)?e:[e],...w(t)})}var Bd=m("ZodTransform",(e,t)=>{et(),lu.init(e,t),M.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Ji(e,n,r,i),e._zod.parse=(n,r)=>{if(r.direction==="backward")throw new yn(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 go(e){return new Bd({type:"transform",transform:e})}var In=m("ZodOptional",(e,t)=>{ki.init(e,t),M.init(e,t),e._zod.processJSONSchema=(n,r,i)=>An(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function Lr(e){return new In({type:"optional",innerType:e})}var yo=m("ZodExactOptional",(e,t)=>{uu.init(e,t),M.init(e,t),e._zod.processJSONSchema=(n,r,i)=>An(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function qd(e){return new yo({type:"optional",innerType:e})}var Hd=m("ZodNullable",(e,t)=>{cu.init(e,t),M.init(e,t),e._zod.processJSONSchema=(n,r,i)=>ro(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function zr(e){return new Hd({type:"nullable",innerType:e})}var Wd=m("ZodDefault",(e,t)=>{du.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.removeDefault=e.unwrap});function Zd(e,t){return new Wd({type:"default",innerType:e,get defaultValue(){return typeof t==="function"?t():Qr(t)}})}var Vd=m("ZodPrefault",(e,t)=>{pu.init(e,t),M.init(e,t),e._zod.processJSONSchema=(n,r,i)=>ao(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function Gd(e,t){return new Vd({type:"prefault",innerType:e,get defaultValue(){return typeof t==="function"?t():Qr(t)}})}var vo=m("ZodNonOptional",(e,t)=>{fu.init(e,t),M.init(e,t),e._zod.processJSONSchema=(n,r,i)=>io(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function Kd(e,t){return new vo({type:"nonoptional",innerType:e,...w(t)})}var Jd=m("ZodCatch",(e,t)=>{hu.init(e,t),M.init(e,t),e._zod.processJSONSchema=(n,r,i)=>lo(e,n,r,i),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Yd(e,t){return new Jd({type:"catch",innerType:e,catchValue:typeof t==="function"?t:ta(t)})}var bo=m("ZodPipe",(e,t)=>{Ei.init(e,t),M.init(e,t),e._zod.processJSONSchema=(n,r,i)=>uo(e,n,r,i),e.in=t.in,e.out=t.out});function Dr(e,t){return new bo({type:"pipe",in:e,out:t})}var Xd=m("ZodPreprocess",(e,t)=>{bo.init(e,t),mu.init(e,t)}),Qd=m("ZodReadonly",(e,t)=>{gu.init(e,t),M.init(e,t),e._zod.processJSONSchema=(n,r,i)=>co(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function ep(e){return new Qd({type:"readonly",innerType:e})}var tp=m("ZodPromise",(e,t)=>{vu.init(e,t),M.init(e,t),e._zod.processJSONSchema=(n,r,i)=>po(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function Vt(e){return new tp({type:"promise",innerType:e})}var np=m("ZodFunction",(e,t)=>{yu.init(e,t),M.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Ki(e,n,r,i)});function ht(e){return new np({type:"function",input:Array.isArray(e?.input)?Fd(e?.input):e?.input??x(W()),output:e?.output??W()})}var To=m("ZodCustom",(e,t)=>{bu.init(e,t),M.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Gi(e,n,r,i)});function ne(e,t){return Tc(To,e??(()=>!0),t)}function rp(e,t={}){return wc(To,e,t)}function ip(e,t){return _c(e,t)}function wo(e,t){return new Xd({type:"pipe",in:go(e),out:t})}var _o=["none","minimal","low","medium","high","xhigh","max"],op=I(_o),sp=op.exclude(["none"]),ap=I([..._o,"default"]).nullable(),lp=xn("type",[y({type:U("toggle")}).strict(),y({type:U("effort"),values:x(ap)}).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"]})]),up=I(["default","openai-responses","r1"]);var cp=I(["images","video","tools","streaming","prompt-cache","reasoning","reasoning-effort","computer-use","global-endpoint","structured_output","temperature","files"]),dp=I(["active","preview","deprecated","legacy"]),pp=y({input:b().optional(),output:b().optional(),cacheWrite:b().optional(),cacheRead:b().optional()}),fp=y({maxBudget:b().optional(),outputPrice:b().optional(),thinkingLevel:I(["low","high"]).optional()}),hp=y({reasoningDefaultOn:S().optional(),apiProtocol:I(["openai-chat","openai-responses","anthropic","gemini"]).optional()}).catchall(W()),Ur=I(["text","image","audio","video","pdf"]),mp=y({input:x(Ur),output:x(Ur)});var gp=I(["language","image-generation","speech-generation","video-generation","transcription","realtime"]);var yp=I(["batch","streaming"]);var ko=y({id:c(),name:c().optional(),description:c().optional(),maxTokens:b().optional(),contextWindow:b().optional(),maxInputTokens:b().optional(),capabilities:x(cp).optional(),operation:gp.optional(),operationModes:x(yp).optional(),modalities:mp.optional(),reasoningOptions:x(lp).optional(),apiFormat:up.optional(),systemRole:I(["system","developer"]).optional(),temperature:b().optional(),pricing:pp.optional(),thinkingConfig:fp.optional(),status:dp.optional(),deprecationNotice:c().optional(),replacedBy:c().optional(),releaseDate:c().optional(),deprecationDate:c().optional(),family:c().optional(),metadata:hp.optional()});var Eo="NOT a tool or system failure. Clarify with user before proceeding.",vp=y({id:c(),name:c(),execution:I(["client","provider"]).optional(),input:W(),output:W(),error:c().optional(),durationMs:b(),startedAt:It(),endedAt:It()}),bp=I(["completed","max_iterations","aborted","mistake_limit","error"]),Tp=y({inputTokens:b(),outputTokens:b(),cacheReadTokens:b().optional(),cacheWriteTokens:b().optional(),totalCost:b().optional()}),rm=y({text:c(),usage:Tp,messages:x(ne()),toolCalls:x(vp),iterations:b(),finishReason:bp,model:y({id:c(),provider:c(),info:ko.optional()}),startedAt:It(),endedAt:It(),durationMs:b()}),im=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(),ko).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:sp.optional(),thinkingBudgetTokens:b().positive().optional(),thinking:S().optional(),onEvent:ht().input([ne()]).output(Nd()).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()}),wp=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"]),_p=y({id:c().optional(),label:c().optional(),role:c().optional(),participantKey:c().optional(),participantLabel:c().optional(),platformUserId:c().optional(),metadata:j(c(),W()).optional()}),kp=y({source:c(),sourceEvent:c(),threadId:c(),channelId:c(),isDM:S(),sessionId:c().optional(),workspaceRoot:c().optional(),metadata:j(c(),W()).optional()}),om=y({actor:_p,context:kp,payload:j(c(),W()).optional()}),sm=y({action:I(["allow","deny"]).default("allow"),message:c().optional(),reason:c().optional(),metadata:j(c(),W()).optional()}),am=y({adapter:c(),botUserName:c().optional(),event:wp,payload:j(c(),W()),ts:c()});var Ep=["hooks","tools","commands","rules","skills","messageBuilders","providers","automationEvents","mcp"],lm=new Set(Ep);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"},um={[Ze.CLINE_PASS]:!1,[Ze.CODE_CLOUD_AGENTS]:!1,[Ze.CODE_ONBOARDING_GITHUB]:!1,[Ze.CLINE_COMPOSIO_BETA]:!1},cm=Object.values(Ze),Ap=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()),xp=y({toolName:c(),parameters:ke}),Ip=y({toolName:c(),parameters:ke,result:c(),success:S(),executionTimeMs:b()}),Cp=y({prompt:c(),attachments:x(c())}),Sp=y({taskMetadata:ke}),Rp=y({taskMetadata:ke,previousState:ke}),Op=y({taskMetadata:ke}),Np=y({taskMetadata:ke}),Mp=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()}),dm=y({clineVersion:c(),hookName:Ap,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:xp.optional(),postToolUse:Ip.optional(),userPromptSubmit:Cp.optional(),taskStart:Sp.optional(),taskResume:Rp.optional(),taskCancel:Op.optional(),taskComplete:Np.optional(),preCompact:Mp.optional()}).passthrough();var Pp=["readFile","search","bash","webFetch","editor","applyPatch","skills","askQuestion","submit"],pm=new Set(Pp);var Fr="<tool_call>",$p=/<tool_call>|<parameter=[^>]*>|<\/parameter>/g,Lp=/<function=[^\s>]+\s*>/,Cn="[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.";function Ao(e){return["[SYSTEM] You are in plan mode: this run makes no changes, and it does not switch to act mode on its own - only the user decides that.",e?'If the plan is ready, ask the user how to proceed with one `ask_question` call, with these options: "Switch to act mode and carry out the plan", "Discuss the plan further", and "Stop here and wait for instructions". Mark the one you would pick with " (recommended)".':'If the plan is ready, end by asking the user how to proceed: "Switch to act mode and carry out the plan", "Discuss the plan further", and "Stop here and wait for instructions".',"If you still need to look at something before the plan is ready, carry on with read-only tools.","Do not call `switch_to_act_mode` until the user has chosen to switch."].join(" ")}var xo=" 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.",zp="[SYSTEM] You have now taken ";function Io(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 zp+`${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 Dp="[SYSTEM] Your last message contained a tool call that could not be read.",Up="<|tool_call>",jr="<tool_call|>",Se='<|"|>',Fp=/<\|tool_call>\s*call:([A-Za-z_][\w.-]*)\s*\{/g;function Co(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 jp(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 Bp(e){let t=[...e.matchAll(Fp)];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(jr))r+=1}let i=t[t.length-1],o=(i.index??0)+i[0].length,s=e.indexOf(jr,o),a=r>0?void 0:jp(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(Up)){let l=Bp(e);if(l)return l}if(!e.includes(Fr)||!Lp.test(e))return;let t=0,n=0,r=0;for(let l of e.matchAll($p)){let u=l[0];if(u===Fr)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 Sn(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 Dp+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 qp="[SYSTEM] You wrote ";function So(e){let t=e.trim().replace(/\s+/g," ").slice(0,200);return qp+`"${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 Ro=/\b(?:let me(?!\s+know)|i'?ll|i will|i'?m going to|i am going to|now i(?:'?ll| will)|next,? i(?:'?ll| will)|let['’]s)\b/i,Oo=/\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||Oo.test(t))return;let n=t.slice(-400);return Ro.test(n)?t:void 0}var Hp=300;function No(e){let t=e?.trim();return!!t&&t.length<=Hp&&!/\n\s*\n/.test(t)&&!t.endsWith("?")&&Pt(t)===void 0}var Wp=/(?:^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 Mo(e){return e.slice(-300).includes("?")||Ro.test(e.slice(-400))}function Po(e){let t=e?.trim();if(!t)return!1;let n=t.replace(/[*_`]/g,"");return(Oo.test(n)||Wp.test(n))&&!Mo(t)}function $o(e){let t=e?.trim();return!!t&&!Mo(t)}var Zp=I(["image","audio","video","file"]),Vp=xn("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 Gp(e){if(e.startsWith("image/"))return"image";if(e.startsWith("audio/"))return"audio";if(e.startsWith("video/"))return"video";return"file"}var fm=y({id:c().min(1),modality:Zp,mediaType:c().min(1),source:Vp,name:c().min(1).optional(),sizeBytes:b().int().nonnegative().optional()}).refine((e)=>Gp(e.mediaType)===e.modality,{message:"Generated media modality must match its media type",path:["modality"]});function Br(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function Rn(e,t){if(!e&&!t)return;let n=e?.metadata,r=t?.metadata,i={...e??{},...t??{}};if(Br(n)&&Br(r))i.metadata={...n,...r};return i}var Kp=3;var qr=Symbol.for("cline.shared.tokenCalibration");function Jp(e,t){if(e===void 0||t===void 0)return!0;return e===t}function Lo(){let e=globalThis,t=e[qr];if(t)return t;let n={};return e[qr]=n,n}function Yp(){return Lo().charsPerToken??Kp}function On(e){let t=Lo();return Jp(t.outputCapOwner,e)?t.outputCap:void 0}function zo(e){return Math.max(1,Math.ceil(e/Yp()))}function Re(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function Xp(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(Xp(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 Qp(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=Qp(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 Do(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 ef=String.raw`\x60|"|'|<\/[A-Za-z][\w-]*>`,tf=String.raw`\s*,\s*[A-Za-z_]\w*\s*:\s*(?:\x60[^\x60\n]*\x60|"[^"\n]*"|'[^'\n]*'|-?\d+(?:\.\d+)?|true|false|null)`,nf=String.raw`\s*,\s*([A-Za-z_]\w*)\s*:\s*(?:\[\s*[\x60"']?|\{|[\x60"'])?`,hm=new RegExp(String.raw`(${ef})((?:${tf})*)(?:${nf})?[ \t]*\}?[ \t]*$`);function rf(e){return Bc(e)}var mm=new RegExp(`${"⟦"}([^${"⟧"}]*)${"⟧"}([\\s\\S]*?)${"⟦/⟧"}`,"g");var Uo=`# Plan Mode
|
|
58
58
|
|
|
59
59
|
You are in Plan mode. Your role is to explore, analyze, and plan -- not to execute.
|
|
60
60
|
|
|
@@ -65,36 +65,44 @@ You are in Plan mode. Your role is to explore, analyze, and plan -- not to execu
|
|
|
65
65
|
- Do NOT edit files, write code, run destructive commands, or make any changes
|
|
66
66
|
- Do NOT implement anything -- focus on understanding and alignment first
|
|
67
67
|
|
|
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
|
|
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.
|
|
69
69
|
|
|
70
|
-
|
|
70
|
+
## What the plan needs
|
|
71
71
|
|
|
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 Xp=y({id:c(),temperature:b().optional(),maxTokens:b().optional(),contextWindow:b().optional(),inputPrice:b().optional(),outputPrice:b().optional(),supportsImages:S().optional()}),Qp=y({models:A(Xp).optional(),openAiBaseUrl:c().optional(),openAiHeaders:j(c(),c()).optional(),azureApiVersion:c().optional(),azureIdentity:S().optional()}),ef=y({id:c(),thinkingBudgetTokens:b().optional()}),tf=y({name:c(),baseModelId:c(),thinkingBudgetTokens:b().optional()}),nf=y({models:A(ef).optional(),customModels:A(tf).optional(),awsRegion:c().optional(),awsUseCrossRegionInference:S().optional(),awsUseGlobalInference:S().optional(),awsBedrockUsePromptCache:S().optional(),awsBedrockEndpoint:c().optional()}),rf=y({id:c()}),of=y({models:A(rf).optional()}),sf=y({id:c(),thinkingBudgetTokens:b().optional()}),af=y({models:A(sf).optional(),vertexProjectId:c().optional(),vertexRegion:c().optional()}),lf=y({id:c(),thinkingBudgetTokens:b().optional(),promptCachingEnabled:S().optional()}),uf=y({models:A(lf).optional(),baseUrl:c().optional()}),cf=y({id:c(),thinkingBudgetTokens:b().optional()}),df=y({models:A(cf).optional(),baseUrl:c().optional()}),pf=y({OpenAiCompatible:Qp.optional(),AwsBedrock:nf.optional(),Cline:of.optional(),Vertex:af.optional(),LiteLLM:uf.optional(),Anthropic:df.optional()}),ff=y({id:c()}),hf=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()}),mf=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()}),gf=y({promptUploading:mf.optional()}),dm=y({version:c(),providerSettings:pf.optional(),telemetryEnabled:S().optional(),kanbanEnabled:S().optional(),mcpMarketplaceEnabled:S().optional(),allowedMCPServers:A(ff).optional(),remoteMCPServers:A(hf).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:gf.optional(),globalRules:A(qr).optional(),globalWorkflows:A(qr).optional()}),pm=j(c(),c());var fm=I(["reasoning","prompt-cache","tools","provider-tools","oauth","temperature","files","streaming","vision","computer-use","local-auth","popular"]),hm=I(["anthropic","gemini","openai-chat","openai-responses","openai-r1","ai-sdk"]),mm=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 yf(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 vf(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=bf(t),i=0;try{let o=vf(yf(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 bf(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=_f(e)?e:void 0,i=e instanceof Error?e:void 0,o=Ve(n)??Ve(i?.message)??Ve(r?.message)??kf(e)??"Unknown error",s=Ef(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:wf(Tf(o),t),...s!==void 0?{error_code:s}:{},...a!==void 0?{error_status:a}:{}}}function Tf(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 wf(e,t){let n=Math.max(1,Math.floor(t));return e.length>n?e.substring(0,n):e}function _f(e){return typeof e==="object"&&e!==null}function Ve(e){return typeof e==="string"&&e.trim().length>0?e:void 0}function kf(e){if(e instanceof Error)return;let t=typeof e==="string"?e:String(e);return t==="[object Object]"?void 0:Ve(t)}function Ef(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 xf=["rules","skills","workflows","plugins","hooks"];var gm=new Set(xf);var Af=y({rootPath:c().min(1),hint:c().min(1).optional(),associatedRemoteUrls:A(c().min(1)).optional(),latestGitCommitHash:c().min(1).optional(),latestGitBranchName:c().min(1).optional()}),ym=y({currentWorkspacePath:c().min(1).optional(),workspaces:j(c().min(1),Af)});var If=["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"]),Cf=y({agentId:c(),role:I(["lead","teammate"]),description:c().optional(),status:I(["idle","running","stopped"])}),vm=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 bm=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(),Tm=y({agentId:c().min(1).describe("Teammate identifier"),reason:R(c().min(1)).describe("Optional shutdown reason")}),wm=y({}),Vo={create:["title","description"],list:[],claim:["taskId"],complete:["taskId","summary"],block:["taskId","reason"]};var _m=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(A(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}`})}}),km=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}`})}}),Em=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")}),xm=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")}),Im=y({runId:R(c().min(1)).describe("Optional async run ID to await. Omit to wait for all active async runs.")}).strict(),Cm=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")}),Sm=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")}),Rm=y({unreadOnly:R(S()).describe("Only unread messages for read action (default true)")}),Om=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(A(c().min(1))).describe("Optional evidence links/snippets"),nextAction:R(c().min(1)).describe("Planned next step")}),Nm=y({}),Mm=y({title:c().describe("Outcome title"),requiredSections:A(c()).default(If).describe("Required sections for finalization gate (defaults to current_state,boundary_analysis,interface_proposal)")}),Pm=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")}),$m=y({fragmentId:c().describe("Fragment ID"),approved:S().describe("Review decision")}),Lm=y({outcomeId:c().describe("Outcome ID")}),zm=y({}),Dm=y({teamId:c(),teamName:c(),members:A(Cf),taskCounts:j(Oe,b()),unreadMessages:b(),missionLogEntries:b(),activeRuns:b(),queuedRuns:b(),outcomeCounts:j($t,b())}),Sf=y({id:c(),title:c(),description:c(),status:Oe,createdAt:ae,updatedAt:ae,createdBy:c(),assignee:c().optional(),dependsOn:A(c()),summary:c().optional(),isReady:S(),blockedBy:A(c())}),Um=xn("action",[y({action:U("create"),taskId:c(),status:Oe,ignoredFields:A(c()).optional(),note:c().optional()}),y({action:U("list"),tasks:A(Sf)}),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})]),Fm=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()}),Rf=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()})}),jm=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:Rf.optional()}),Bm=y({id:c(),teamId:c(),fromAgentId:c(),toAgentId:c(),subject:c(),body:c(),taskId:c().optional(),sentAt:ae,readAt:ae.optional()}),qm=y({id:c(),teamId:c(),title:c(),status:$t,requiredSections:A(c()),createdBy:c(),createdAt:ae,finalizedAt:ae.optional()}),Hm=y({outcomeId:c(),status:$t,requiredSections:A(c())}),Wm=y({agentId:c(),status:c()}),Zm=y({runId:c(),status:Zo}),Vm=y({id:c(),toAgentId:c()}),Gm=y({delivered:b()}),Km=y({id:c()}),Jm=y({status:c()}),Ym=y({fragmentId:c(),status:c()}),Xm=y({outcomeId:c(),status:$t}),Of;((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"})(Of||={});function Nf(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 Mf(e){let t=Nf(e.inputSchema instanceof M?Yp(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 Qm="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 Yf,isRetryableProviderError as Xf}from"@cerebriline/llms";import{nanoid as Qf}from"nanoid";function Nn(){return{reasoningDeltas:0,reasoningChars:0,textDeltas:0,textChars:0,toolInputChars:0}}var Pf=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<=Pf)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
|
-
|
|
72
|
+
The plan is what this mode produces: the user approves or changes it before anything is done, and act mode carries it out as written. Make it complete enough to follow without guessing:
|
|
73
|
+
- The cause, found first. Read, search and run read-only checks until you can say in one sentence what is wrong and where, and plan the fix from that.
|
|
74
|
+
- One step per change: which file and where (function, line), what changes into what, and why that removes the cause.
|
|
75
|
+
- How each step is checked: the command to run and the result that shows it worked, ending with the check for the whole request.
|
|
76
|
+
- What you are unsure of, and how act mode will find out (what to look at if the first fix does not hold).`,gm=`${Uo}
|
|
77
|
+
|
|
78
|
+
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.`,ym=`${Uo}
|
|
79
|
+
|
|
80
|
+
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 of=y({id:c(),temperature:b().optional(),maxTokens:b().optional(),contextWindow:b().optional(),inputPrice:b().optional(),outputPrice:b().optional(),supportsImages:S().optional()}),sf=y({models:x(of).optional(),openAiBaseUrl:c().optional(),openAiHeaders:j(c(),c()).optional(),azureApiVersion:c().optional(),azureIdentity:S().optional()}),af=y({id:c(),thinkingBudgetTokens:b().optional()}),lf=y({name:c(),baseModelId:c(),thinkingBudgetTokens:b().optional()}),uf=y({models:x(af).optional(),customModels:x(lf).optional(),awsRegion:c().optional(),awsUseCrossRegionInference:S().optional(),awsUseGlobalInference:S().optional(),awsBedrockUsePromptCache:S().optional(),awsBedrockEndpoint:c().optional()}),cf=y({id:c()}),df=y({models:x(cf).optional()}),pf=y({id:c(),thinkingBudgetTokens:b().optional()}),ff=y({models:x(pf).optional(),vertexProjectId:c().optional(),vertexRegion:c().optional()}),hf=y({id:c(),thinkingBudgetTokens:b().optional(),promptCachingEnabled:S().optional()}),mf=y({models:x(hf).optional(),baseUrl:c().optional()}),gf=y({id:c(),thinkingBudgetTokens:b().optional()}),yf=y({models:x(gf).optional(),baseUrl:c().optional()}),vf=y({OpenAiCompatible:sf.optional(),AwsBedrock:uf.optional(),Cline:df.optional(),Vertex:ff.optional(),LiteLLM:mf.optional(),Anthropic:yf.optional()}),bf=y({id:c()}),Tf=y({name:c(),url:c(),alwaysEnabled:S().optional(),headers:j(c(),c()).optional()}),Hr=y({alwaysEnabled:S(),name:c(),contents:c()}),Kt=y({bucket:c(),accessKeyId:c(),secretAccessKey:c(),region:c().optional(),endpoint:c().optional(),accountId:c().optional()}),wf=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()}),_f=y({promptUploading:wf.optional()}),vm=y({version:c(),providerSettings:vf.optional(),telemetryEnabled:S().optional(),kanbanEnabled:S().optional(),mcpMarketplaceEnabled:S().optional(),allowedMCPServers:x(bf).optional(),remoteMCPServers:x(Tf).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:_f.optional(),globalRules:x(Hr).optional(),globalWorkflows:x(Hr).optional()}),bm=j(c(),c());var Tm=I(["reasoning","prompt-cache","tools","provider-tools","oauth","temperature","files","streaming","vision","computer-use","local-auth","popular"]),wm=I(["anthropic","gemini","openai-chat","openai-responses","openai-r1","ai-sdk"]),_m=I(["anthropic","ai-sdk","ai-sdk-community","openai","openai-compatible","openai-r1","gemini","bedrock","custom","fetch","vertex"]);var Fo="task.provider_request_started",jo="task.provider_stream_started",Bo="task.first_chunk_received",qo="task.provider_stream_failed",Ho="task.cancelled";var Ce=new Map;function kf(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 Ef(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 Wo(e,t){e?.capture({event:"agent.reasoning.unexpected_tokens",properties:Nn({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 Zo(e,t){if(!e)return;e.capture({event:t.event,properties:Nn({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?{}:Go(t.error,t.messageLimit),error_class:t.errorClass})})}function Vo(e,t){if(!e)return!1;let n=t.event??"sdk.error",r=Af(t),i=0;try{let o=Ef(kf(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 Af(e){return Nn({...e.context??{},component:e.component,operation:e.operation,severity:e.severity??"error",handled:e.handled??!0,...Go(e.error,e.messageLimit,e.errorMessage)})}function Nn(e){let t={};for(let[n,r]of Object.entries(e))if(r!==void 0)t[n]=r;return t}function Go(e,t=500,n){let r=Cf(e)?e:void 0,i=e instanceof Error?e:void 0,o=Ve(n)??Ve(i?.message)??Ve(r?.message)??Sf(e)??"Unknown error",s=Rf(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:If(xf(o),t),...s!==void 0?{error_code:s}:{},...a!==void 0?{error_status:a}:{}}}function xf(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 If(e,t){let n=Math.max(1,Math.floor(t));return e.length>n?e.substring(0,n):e}function Cf(e){return typeof e==="object"&&e!==null}function Ve(e){return typeof e==="string"&&e.trim().length>0?e:void 0}function Sf(e){if(e instanceof Error)return;let t=typeof e==="string"?e:String(e);return t==="[object Object]"?void 0:Ve(t)}function Rf(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 Of=["rules","skills","workflows","plugins","hooks"];var km=new Set(Of);var Nf=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()}),Em=y({currentWorkspacePath:c().min(1).optional(),workspaces:j(c().min(1),Nf)});var Mf=["current_state","boundary_analysis","interface_proposal"];var ae=wo((e)=>e instanceof Date?e.toISOString():e,c().datetime()),Oe=I(["pending","in_progress","blocked","completed"]),Ko=I(["queued","running","completed","failed","cancelled","interrupted"]),$t=I(["draft","in_review","finalized"]),Pf=y({agentId:c(),role:I(["lead","teammate"]),description:c().optional(),status:I(["idle","running","stopped"])}),Am=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 wo((t)=>t===null?void 0:t,e.optional())}var xm=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(),Im=y({agentId:c().min(1).describe("Teammate identifier"),reason:R(c().min(1)).describe("Optional shutdown reason")}),Cm=y({}),Jo={create:["title","description"],list:[],claim:["taskId"],complete:["taskId","summary"],block:["taskId","reason"]};var Sm=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 Jo[e.action]){if(e[n]!==void 0)continue;t.addIssue({code:"custom",path:[n],message:`Field "${n}" is required when action=${e.action}`})}}),Rm=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 Jo[e.action]){if(e[n]!==void 0)continue;t.addIssue({code:"custom",path:[n],message:`Field "${n}" is required when action=${e.action}`})}}),Om=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")}),Nm=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)")}),Mm=y({runId:c().min(1).describe("Run ID"),reason:R(c().min(1)).describe("Optional cancellation reason")}),Pm=y({runId:R(c().min(1)).describe("Optional async run ID to await. Omit to wait for all active async runs.")}).strict(),$m=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")}),Lm=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")}),zm=y({unreadOnly:R(S()).describe("Only unread messages for read action (default true)")}),Dm=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")}),Um=y({}),Fm=y({title:c().describe("Outcome title"),requiredSections:x(c()).default(Mf).describe("Required sections for finalization gate (defaults to current_state,boundary_analysis,interface_proposal)")}),jm=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")}),Bm=y({fragmentId:c().describe("Fragment ID"),approved:S().describe("Review decision")}),qm=y({outcomeId:c().describe("Outcome ID")}),Hm=y({}),Wm=y({teamId:c(),teamName:c(),members:x(Pf),taskCounts:j(Oe,b()),unreadMessages:b(),missionLogEntries:b(),activeRuns:b(),queuedRuns:b(),outcomeCounts:j($t,b())}),$f=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())}),Zm=xn("action",[y({action:U("create"),taskId:c(),status:Oe,ignoredFields:x(c()).optional(),note:c().optional()}),y({action:U("list"),tasks:x($f)}),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})]),Vm=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()}),Lf=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()})}),Gm=y({id:c(),agentId:c(),taskId:c().optional(),status:Ko,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:Lf.optional()}),Km=y({id:c(),teamId:c(),fromAgentId:c(),toAgentId:c(),subject:c(),body:c(),taskId:c().optional(),sentAt:ae,readAt:ae.optional()}),Jm=y({id:c(),teamId:c(),title:c(),status:$t,requiredSections:x(c()),createdBy:c(),createdAt:ae,finalizedAt:ae.optional()}),Ym=y({outcomeId:c(),status:$t,requiredSections:x(c())}),Xm=y({agentId:c(),status:c()}),Qm=y({runId:c(),status:Ko}),eg=y({id:c(),toAgentId:c()}),tg=y({delivered:b()}),ng=y({id:c()}),rg=y({status:c()}),ig=y({fragmentId:c(),status:c()}),og=y({outcomeId:c(),status:$t}),zf;((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"})(zf||={});function Df(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 Uf(e){let t=Df(e.inputSchema instanceof M?rf(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 Yo="switch_to_act_mode",sg="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.";var Wr=new WeakMap;function Xo(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function Ff(e){let{type:t,...n}=e;if(!Array.isArray(t))return e;let r=t.filter((i)=>typeof i==="string").map((i)=>({type:i}));if(r.length===0)return n;if(r.length===1)return{...n,type:r[0]?.type};if(Array.isArray(n.anyOf)){let{anyOf:i,...o}=n;return{...o,allOf:[{anyOf:i},{anyOf:r}]}}return{...n,anyOf:r}}function un(e,t){if(Array.isArray(e)){let o=!1,s=e.map((a)=>{let l=un(a,t);if(l!==a)o=!0;return l});return o?s:e}if(!Xo(e))return e;let n=!1,r={};for(let[o,s]of Object.entries(e)){let a=un(s,o==="items");if(a!==s)n=!0;r[o]=a}let i=n?r:e;if(t&&Array.isArray(i.type))return Ff(i);return i}function Qo(e){if(!Xo(e))return e;let t=Wr.get(e);if(t!==void 0)return t;let n=un(e,!1);return Wr.set(e,n),n}import{classifyProviderError as ys,createGateway as ih,isRetryableProviderError as oh}from"@cerebriline/llms";import{nanoid as sh}from"nanoid";function Mn(){return{reasoningDeltas:0,reasoningChars:0,textDeltas:0,textChars:0,toolInputChars:0}}var jf=12;function es(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 ts(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]=es(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<=jf)return{reasoningTokens:n.reasoningDeltas,textTokens:n.textDeltas,toolInputTokens:t-i,method:"stream-chunks"};let[s=0,a=0,l=0]=es(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 Pn(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 $n(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(`
|
|
81
|
+
`)}var Bf=/^\d+\s*\|\s?/;function Fe(e){return e.trim().replace(Bf,"").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
82
|
`))!==-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
83
|
`).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
84
|
${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
|
|
77
85
|
${n.join(`
|
|
78
86
|
`)}`,()=>{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
|
|
79
87
|
${[...n].sort().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
|
|
81
|
-
`)}function
|
|
82
|
-
`,t:"\t",r:"",'"':'"',"\\":"\\","/":"/"};class
|
|
83
|
-
`))!==-1){let o=Fe(this.pending.slice(0,t));if(this.pending=this.pending.slice(t+1),o.length<
|
|
84
|
-
`)){let r=Fe(n);if(r.length>=
|
|
85
|
-
`)}var Ut=32000;function
|
|
88
|
+
`)}`,()=>{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 qf=/\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 Hf(e,t){let n=e.trim();return((n.startsWith("```")?n.replace(/```[\s\S]*?```/g,""):n).toLowerCase().match(qf)??[]).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&&Hf(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 ns(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 rs(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(`
|
|
89
|
+
`)}function Ln(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,rs(a)}}}var Wf={n:`
|
|
90
|
+
`,t:"\t",r:"",'"':'"',"\\":"\\","/":"/"};class zn{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 ss(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?Gf(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 is=24,Zf=300,os=0.3,Vf=50;class ss{given;counts=new Map;pending="";chars=0;lines=0;excess=0;nextCheck=Zf;source;constructor(e){this.given=e}push(e){this.chars+=e.length,this.pending+=e;let t;while((t=this.pending.indexOf(`
|
|
91
|
+
`))!==-1){let o=Fe(this.pending.slice(0,t));if(this.pending=this.pending.slice(t+1),o.length<is)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<os*this.lines)return;if(this.excessBeyondSource()<os*this.lines){this.nextCheck=this.lines+Vf;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(`
|
|
92
|
+
`)){let r=Fe(n);if(r.length>=is)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 Gf(e,t){let n="";for(let r of t)if(e.escaping)e.escaping=!1,n+=Wf[r]??`\\${r}`;else if(r==="\\")e.escaping=!0;else n+=r;return n}function as(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 Dn(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 ls(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 ${Dn(e.verdict)}. Make the call again with only what it needs.`}function us(e){return`[SYSTEM] Your reply was cut while you were writing it, and none of it is kept: it had come to repeat ${Dn(e)}. Carry on with the task from where it stands.`}function cs(e){return`[SYSTEM] Your thinking was cut while you were writing it, and none of it is kept: it had come to repeat ${Dn(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 Kf}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_${Kf(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=ds(n.metadata,e.metadata);if(e.inputText)n.inputText=eh(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+=Yf(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=Xf(r,t,n),o={type:"tool-call",toolCallId:r.toolCallId,toolName:r.toolName,input:i.input,metadata:i.parseError?ds(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 Jf(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 ds(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 Yf(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 Xf(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=Qf(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 Qf(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 eh(e,t){if(!e)return t;let n=t.trimStart();if(n.startsWith("{")||n.startsWith("["))return t;return e+t}var th=2000,fs=!0;function nh(e){fs=e}function Fn(){return fs}var Un="intent";function hs(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ps(e){if(e.length===0)return;let t=[...e].sort((n,r)=>r.length-n.length).map(hs).join("|");return new RegExp(`[,{"'=>]\\s*(?:${t})["']?\\s*[:=><]`)}function rh(e){if(e.length===0)return;let t=[...e].sort((n,r)=>r.length-n.length).map(hs).join("|");return new RegExp(`(?<![A-Za-z0-9_])(?:${t})(?![A-Za-z0-9_])`,"g")}class jn{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!==Un);this.otherKey=ps(t),this.intentKey=this.otherKey?ps([Un]):void 0;let n=[...new Set(e?.toolNames??[])].filter((r)=>r.length>0);this.toolName=rh(n),this.tailChars=Math.max(Un.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 ms(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 gs(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 ah=Boolean(globalThis.process?.env?.CLINE_TIMING);function lh(e){if(!ah)return;globalThis.process?.stderr?.write?.(`[timing] ${new Date().toISOString()} ${e}
|
|
93
|
+
`)}var Ut=32000;function uh(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 ch="Model reached the maximum output token limit before completing the turn",dh=2,ph=2000,fh="[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.]",hh="[image omitted — this model does not accept image input; the text above is what the tool reported]";function mh(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 gh=8000,vs="[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 yh(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 vh="And what that reasoning had established about the problem itself:",bh="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.",Th="[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.",wh="[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.",_h="[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.",kh="[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.",bs=3,Eh=2,Ah=1024,xh=/<\/?tool_call>|<\/function>|<function=|<\/parameter>/;function Ih(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:xh.test(t)}:void 0}var Ch="[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 Sh(e){if(e?.reason!=="swallowed_key")return Ch;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 Rh=2,Oh=1,Es=3,As=2000,Bn=3,Nh=1000,Mh=15000,Ph="Model returned no content because the response was blocked by a content filter. Retrying is unlikely to help — try rephrasing the request.",$h="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.",Lh="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.",zh="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}_${sh(t)}`}function Dh(e){return e.model!==void 0}function Uh(e){if(Dh(e))return e;let{providerId:t,modelId:n,apiKey:r,baseUrl:i,headers:o,options:s,...a}=e,u=ih({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 Fh(e,t){return{...t?.["*"]??{},...t?.[e]??{}}}function Wn(e){try{return JSON.stringify(e).length}catch{return String(e).length}}function jh(e){if(typeof e==="string")return e.length;return Wn(e)}function Bh(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+=Wn(s.input);break;case"tool-result":{let a=jh(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:Wn({systemPrompt:e.systemPrompt,messages:e.messages,tools:e.tools,options:e.options}),visibleTextChars:t,estimatedTextTokens:zo(t),toolResultCount:n,toolResultChars:r,maxToolResultChars:i}}class Zn 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 qn={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 qh={_:"__",'"':"_q_","<":"_lt_",">":"_gt_"};function Ts(e){return e.replace(/[_"<>]/g,(t)=>qh[t])}function Hn(e,t){let n=[`source="${e.source}"`];if("toolCall"in e)n.push(`tool_name="${Ts(e.toolCall.toolName)}"`,`tool_call_id="${Ts(e.toolCall.toolCallId)}"`);let r=t.trim().replace(/<(\/?)hook_context/gi,"<\\$1hook_context");return`<hook_context ${n.join(" ")}>
|
|
86
94
|
${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
|
|
95
|
+
</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 Hh(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 Wh(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 ws(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(`
|
|
88
96
|
|
|
89
|
-
`)}function Uh(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 Fh(e){if(typeof e==="string")return[we("user",[{type:"text",text:e}])];if(Array.isArray(e))return te(e);return te([e])}var jh=8;function Bh(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 jh}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=Nh(e),n=Bh(t);this.config={...t,toolExecution:n>1?"parallel":"sequential",maxParallelToolCalls:n},this.state.agentId=t.agentId??Ae("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({...xe,...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={...xe,...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:xo(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-vh);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(
|
|
97
|
+
`)}function Zh(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 _s(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 Vh(e){if(typeof e==="string")return[we("user",[{type:"text",text:e}])];if(Array.isArray(e))return te(e);return te([e])}var Gh=8;function Kh(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 Gh}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(qn),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;planModeNudgeSpent=!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=Uh(e),n=Kh(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(Ho,{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(qn),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)}}requestSchema(e){let t=Qo(e.inputSchema);if(t!==e.inputSchema&&!this.sanitizedSchemaLogged.has(e.name))this.sanitizedSchemaLogged.add(e.name),this.config.logger?.log?.(`Tool schema for ${e.name}: list types on array items rewritten as anyOf for template compatibility`,{severity:"info"});return t}sanitizedSchemaLogged=new Set;isPlanMode(){return this.tools.has(Yo)}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 Sn(i);if(this.isPlanMode()){if(this.planModeNudgeSpent||!this.calledToolThisRun)return;return this.planModeNudgeSpent=!0,Ao(this.tools.has("ask_question"))}let o=await this.config.completionPolicy?.describeUnstartedWork?.();if(t&&!o)return;if(this.noToolCallNudgeAsked&&this.consecutiveNoToolCallNudges===0&&!o&&No(e))return;if(this.calledToolThisRun&&this.consecutiveNoToolCallNudges===0&&!this.noToolCallNudgeAsked&&!o&&(Po(e)||this.stoppedForUserBy!==void 0&&$o(e)))return;if(this.config.completionPolicy?.strongNudges===!1&&!o&&!this.hasCalledAnyTool&&!Pt(e))return;let s=this.tools.has("ask_question")?Cn+xo:Cn;return o?s+o:s}repetitionNudgeFor(e){if(!this.repetitionNudgerBuilt){this.repetitionNudgerBuilt=!0;let i=this.config.reasoningRepetition;this.repetitionNudger=i===!1?void 0:Ln({...Ae,...i})}if(!e)return;let t=this.repetitionNudges.get(e);if(t)return t.nudge;let n=ws(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=ws(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?ns(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,ks(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:Co(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??Es;return e>0&&this.consecutiveNoToolCallTurns>=e}turnProducedOutputTokens(e){return this.state.usage.outputTokens>e.outputTokens}continuationRoomTokens(){let e=this.state.lastRequestInputTokens,t=On(this.config.sessionId);if(!(e>0)||!t)return;if(t.contextWindow!==void 0)return Math.max(0,t.contextWindow-e-Ah);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(`
|
|
98
|
+
`))}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(gh,e)}getMaxTokensRetryBudget(){let e=this.config.completionPolicy?.maxTruncatedTurnRetries;return typeof e==="number"&&Number.isFinite(e)?Math.max(0,Math.floor(e)):dh}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(qn),this.overflowRecoveryAttempted=!1,this.compactBeforeNextTurn=!1,this.imageRecoveryAttempted=!1,this.steerAwaitingResume=!1,this.noToolCallNudgeAsked=!1,this.calledToolThisRun=!1,this.planModeNudgeSpent=!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?Vh(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(wh);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"?Ph:"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=On(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=yh(i.metadata?.unfinishedToolCalls),T=g?`${vs} ${g}`:vs;await this.addUserReminderMessage(f?[T,...f.note?[bh,f.note]:[],...f.retrospective?[vh,f.retrospective]:[]].join(`
|
|
91
99
|
|
|
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(
|
|
100
|
+
`):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(ch);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=Zh(i);if(p>=As)this.consecutiveNoToolCallTurns+=1,this.noToolCallStreakReasoningChars+=p;else this.consecutiveNoToolCallTurns=0,this.noToolCallStreakReasoningChars=0;if(this.steerAwaitingResume){this.steerAwaitingResume=!1,await this.addUserReminderMessage(Th);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)??ks(k??""):void 0;if(J&&P!==this.lastNudgedUnreadableCall){this.lastNudgedUnreadableCall=P;let C=Sn(J);if(!f.includes(C))f.push(C);g.push({nudge:"unparsed_tool_call"})}let E=this.intentNudgeSpent||!this.nudgesEnabled()||this.isPlanMode()?void 0:Pt(k);if(E)this.intentNudgeSpent=!0,f.push(So(E)),g.push({nudge:"announced_intent"});if(this.shouldNudgeNonConvergence())this.nonConvergenceNudgeSpent=!0,f.push(Io(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:Yh(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:Ih(i);if(oe&&this.thinkingOnlyRetries<bs){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:bs,toolCallInThinking:oe.toolCallInThinking}}),await this.addUserReminderMessage(oe.toolCallInThinking?kh:_h);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(_s(h)||je(n));if(p){await this.addUserReminderMessage(p);continue}let f=this.finishRun("completed",n,_s(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 Zn(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 Zn?{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(`
|
|
93
101
|
|
|
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(
|
|
95
|
-
`).slice(0,
|
|
96
|
-
${a}`:
|
|
102
|
+
`);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(Hn({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=dn(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=Vr(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}): ${Gr(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>=Bn||!this.isRetryableProviderErrorTurn(n))return n;t+=1;let r=this.state.lastError;this.resetLastError();let i=Math.min(Nh*2**(t-1),Mh);await this.emit({type:"status-notice",snapshot:this.snapshot(),message:`provider error — retrying (attempt ${t}/${Bn})`,metadata:{kind:"provider_error_retry",reason:"provider_error_retry",phase:"started",iteration:this.state.iteration,attempt:t,maxRetries:Bn,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(zh,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(Lh,this.state.lastError);return r}async recoverUnparsableToolCall(){if(this.state.lastErrorClass!=="tool_call_unparsable"||this.toolCallParseRetries>=Rh)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(Sh(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:hh}}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(`
|
|
103
|
+
`).slice(0,ph);for(let l=0;l<s.content.length;l++){let u=s.content[l];if(u?.type!=="image")continue;let d=mh(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]
|
|
104
|
+
${a}`:fh},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=Do({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:this.requestSchema(s),...s.readOnly?{readOnly:!0}:{}})),modelTools:this.config.modelTools,signal:this.abortController?.signal,options:Rn(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:Rn(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,...Bh(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(Fo,{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="",_=Mn(),B=0,J=this.config.reasoningLoopDetection,P=J===!1?void 0:new Ee(J,{given:()=>$n(i.messages)}),E,V=()=>$n(i.messages),he=J===!1?void 0:new Ee(J,{given:V}),oe=J===!1?void 0:new zn(J,{given:V}),q,C,it=this.config.toolIntentLimit,ot=this.toolIntentCutStreak>=Eh;if(ot)this.toolIntentCutStreak=0;let Vn=it===!1||ot||!Fn()?void 0:new jn({...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:Zr,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=Vn?.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=ts({outputTokens:v.usage.outputTokens,providerReasoningTokens:v.usage.reasoningTokenCount,tally:_});B=A,_=Mn(),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??ys(v.error),this.lastToolCallRejection=v.toolCallRejection,this.state.lastErrorRetryable=v.errorRetryable??oh(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}
|
|
97
105
|
|
|
98
|
-
${
|
|
106
|
+
${A}`:v;if(E)this.pendingToolIntentNudge=jt(cs(E),await this.onReasoningLoopCut(E));else if(q)this.pendingToolIntentNudge=jt(us(q),await this.onReasoningLoopCut(q,"reply","answer_loop"));else if(C)this.pendingToolIntentNudge=jt(ls(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(Vn)this.toolIntentCutStreak=0;this.throwIfAborted();let Bt=t.signal.aborted;if(Bt)f="stop";if((E||q||C||G)&&f==="unknown")f="stop";let Gn="",Kn;for(let v of p)if(v.type==="tool")Kn=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"){Gn+=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===Kn);if(H.invalid)h.push(H.invalid);if(!H.call||!A)continue;this.config.logger?.debug?.(uh(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:Gn}),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 Jn=(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:Jn(C.toolCallId)}),s.push({type:"text",text:as(C)}),de.argumentLoop=C;if(G)this.recordCut({channel:"tool_arguments",cause:"tool_intent_overrun",...G.toolName?{toolName:G.toolName}:{},toolCallId:G.toolCallId,text:Jn(G.toolCallId)}),s.push({type:"text",text:ms(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,Yn]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:Yn}),!A.has(F))H.push({...lt?{toolName:lt}:{},chars:Yn.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=Hh(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(jo,{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(Bo,{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(qo,{durationMs:n,error:e,errorClass:ys(e),phase:t})}captureTaskLifecycle(e,t={}){let n=K(this.config.sessionId);Zo(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(!Wh(e)||(t.reasoningTokenCount??0)<=0)return;let n=t.reasoningTokenCount;if(n===void 0)return;Wo(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($h,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(`
|
|
99
107
|
|
|
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={...Mh(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??Ae("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??Ae("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){th(e),this.config.logger?.debug?.(`[timing] ${e}`)}async emit(e){let t=Zh(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(!Wh.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 qh={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 Hh(e){return qh[e]??`nudged: ${e}`}var Wh=new Set(["assistant-text-delta","assistant-reasoning-delta","assistant-media","tool-updated"]);function Zh(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 Vh(e){return new rt(e)}var Gh=rt;function Kh(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{Gh as Agent,rt as AgentRuntime,Ie as AgentRuntimeAbortError,Eh as DEFAULT_MAX_NO_TOOL_CALL_NUDGES,vs as DEFAULT_NO_TOOL_CALL_TURN_STREAK_LIMIT,Lt as DEFAULT_REASONING_LOOP_GUARD,xe as DEFAULT_REASONING_REPETITION,Gf as DEFAULT_TOOL_INTENT_MAX_CHARS,bs as NON_CONVERGENCE_MIN_REASONING_CHARS,Ee as ReasoningLoopGuard,nt as ToolCallAssembler,Kh as createAgent,Vh as createAgentRuntime,$n as createRepetitionNudger,Mf as createTool,Mn as describeReasoningLoop,Yo as describeRepetition,qf as finishToolCalls,Dt as isRepetitionLoop,Un as isToolIntentGuardEnabled,zt as measureReasoningRepetition,Kf as setToolIntentGuardEnabled};
|
|
108
|
+
`),[]}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(Hn({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={...Fh(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"} -- ${Eo}`}}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(Hn({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=Pn(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=gs(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){lh(e),this.config.logger?.debug?.(`[timing] ${e}`)}async emit(e){let t=Qh(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)Vo(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(!Xh.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 Jh={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 Yh(e){return Jh[e]??`nudged: ${e}`}var Xh=new Set(["assistant-text-delta","assistant-reasoning-delta","assistant-media","tool-updated"]);function Qh(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 em(e){return new rt(e)}var tm=rt;function nm(e){return new rt(e)}function ks(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{tm as Agent,rt as AgentRuntime,Ie as AgentRuntimeAbortError,Oh as DEFAULT_MAX_NO_TOOL_CALL_NUDGES,Es as DEFAULT_NO_TOOL_CALL_TURN_STREAK_LIMIT,Lt as DEFAULT_REASONING_LOOP_GUARD,Ae as DEFAULT_REASONING_REPETITION,th as DEFAULT_TOOL_INTENT_MAX_CHARS,As as NON_CONVERGENCE_MIN_REASONING_CHARS,Ee as ReasoningLoopGuard,nt as ToolCallAssembler,nm as createAgent,em as createAgentRuntime,Ln as createRepetitionNudger,Uf as createTool,Pn as describeReasoningLoop,rs as describeRepetition,Jf as finishToolCalls,Dt as isRepetitionLoop,Fn as isToolIntentGuardEnabled,zt as measureReasoningRepetition,nh as setToolIntentGuardEnabled};
|