@cline/agents 0.0.87 → 0.0.88

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.
@@ -1 +1 @@
1
- {"version":3,"file":"agent-runtime.d.ts","sourceRoot":"","sources":["../src/agent-runtime.ts"],"names":[],"mappings":"AAAA,OAAO,EAGN,KAAK,uBAAuB,EAE5B,MAAM,aAAa,CAAC;AACrB,OAAO,KAAK,EAIX,YAAY,EAEZ,UAAU,EAKV,cAAc,EACd,iBAAiB,EAEjB,yBAAyB,EAOzB,kBAAkB,IAAI,sBAAsB,EAM5C,MAAM,eAAe,CAAC;AA2DvB;;;;GAIG;AACH,eAAO,MAAM,kDAAkD,sPACgL,CAAC;AAEhP;;;GAGG;AACH,eAAO,MAAM,+CAA+C,0JAC4F,CAAC;AAEzJ;;;GAGG;AACH,eAAO,MAAM,2CAA2C,2JACiG,CAAC;AAuB1J,MAAM,MAAM,aAAa,GAAG,MAAM,GAAG,YAAY,GAAG,SAAS,YAAY,EAAE,CAAC;AAC5E,MAAM,MAAM,kBAAkB,GAAG,CAAC,KAAK,EAAE,iBAAiB,KAAK,IAAI,CAAC;AAEpE;;;;GAIG;AACH,MAAM,WAAW,2BAA4B,SAAQ,sBAAsB;IAC1E,KAAK,EAAE,UAAU,CAAC;CAClB;AAED;;;;GAIG;AACH,MAAM,WAAW,8BAChB,SAAQ,IAAI,CAAC,sBAAsB,EAAE,OAAO,CAAC;IAC7C,gDAAgD;IAChD,UAAU,EAAE,MAAM,CAAC;IACnB,sBAAsB;IACtB,OAAO,EAAE,MAAM,CAAC;IAChB,+BAA+B;IAC/B,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,kCAAkC;IAClC,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,0CAA0C;IAC1C,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACjC,wCAAwC;IACxC,OAAO,CAAC,EAAE,uBAAuB,CAAC,SAAS,CAAC,CAAC;CAC7C;AAED;;;;;GAKG;AACH,MAAM,MAAM,kBAAkB,GAC3B,2BAA2B,GAC3B,8BAA8B,CAAC;AAuJlC,qBAAa,sBAAuB,SAAQ,KAAK;IAChD,QAAQ,CAAC,MAAM,CAAC,EAAE,OAAO,CAAC;gBAEd,MAAM,CAAC,EAAE,OAAO;CAa5B;AAkLD,qBAAa,YAAY;IACxB,OAAO,CAAC,MAAM,CACU;IACxB,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAiC;IAE3D,OAAO,CAAC,QAAQ,CAAC,KAAK,CAA0C;IAChE,OAAO,CAAC,KAAK,CAQX;IACF;;;;;;OAMG;IACH,OAAO,CAAC,mBAAmB,CAAgB;IAC3C,OAAO,CAAC,QAAQ,CAAC,KAAK,CA6BpB;IACF,uDAAuD;IACvD,OAAO,CAAC,yBAAyB,CAAS;IAC1C,2FAA2F;IAC3F,OAAO,CAAC,sBAAsB,CAAK;IACnC,6EAA6E;IAC7E,OAAO,CAAC,0BAA0B,CAAS;IAC3C,OAAO,CAAC,cAAc,CAAC,CAAgB;IACvC,OAAO,CAAC,eAAe,CAAC,CAAkB;IAC1C,OAAO,CAAC,oBAAoB,CAAC,CAAkB;IAC/C,OAAO,CAAC,QAAQ,CAAC,mBAAmB,CAAC,CAAS;IAC9C,OAAO,CAAC,QAAQ,CAAC,gBAAgB,CAAC,CAAS;gBAE/B,MAAM,EAAE,kBAAkB;IAkBhC,GAAG,CAAC,KAAK,EAAE,aAAa,GAAG,OAAO,CAAC,cAAc,CAAC;IAIlD,QAAQ,CAAC,KAAK,CAAC,EAAE,aAAa,GAAG,OAAO,CAAC,cAAc,CAAC;IAI9D,+EAA+E;IAC/E,wBAAwB,IAAI,IAAI;IAIhC,KAAK,CAAC,MAAM,CAAC,EAAE,OAAO,GAAG,IAAI;IAkB7B,SAAS,CAAC,QAAQ,EAAE,kBAAkB,GAAG,MAAM,IAAI;IAOnD;;;;;;;OAOG;IACH,OAAO,CAAC,QAAQ,EAAE,SAAS,YAAY,EAAE,GAAG,IAAI;IAqBhD,QAAQ,IAAI,yBAAyB;YAiBvB,iBAAiB;YAKjB,UAAU;IAkBxB,OAAO,CAAC,aAAa;IAarB,OAAO,CAAC,8BAA8B;IAUtC,OAAO,CAAC,gCAAgC;IAUxC,OAAO,CAAC,6BAA6B;YAOvB,sBAAsB;YAatB,OAAO;IA4QrB;;;OAGG;YACW,wBAAwB;YAoCxB,kBAAkB;YAgBlB,iBAAiB;IAM/B;;;;;OAKG;YACW,kCAAkC;IAsBhD;;;;;;;;;;;;;;OAcG;YACW,yCAAyC;IAUvD;;;;;;OAMG;YACW,sBAAsB;IAwCpC;;;;;;;;;;OAUG;IACH,OAAO,CAAC,4BAA4B;IAuBpC;;;;;;;OAOG;IACH,OAAO,CAAC,cAAc;IAOtB;;;OAGG;YACW,cAAc;IAkB5B;;;;;;;;;OASG;YACW,4CAA4C;IA+C1D,OAAO,CAAC,yBAAyB;IAiBjC,OAAO,CAAC,0BAA0B;IAsBlC,4EAA4E;IAC5E,OAAO,CAAC,oBAAoB;IAK5B;;;;;;;;;;;;;;;;;;;;;;;;;OAyBG;YACW,gCAAgC;IAoH9C,kEAAkE;YACpD,sBAAsB;YAmBtB,wBAAwB;IAgBtC;;;;OAIG;YACW,oBAAoB;IAiBlC,4EAA4E;YAC9D,mBAAmB;YAqFnB,kCAAkC;IAchD;;;;OAIG;YACW,qBAAqB;YAwUpB,uBAAuB;IAuDtC,OAAO,CAAC,2BAA2B;IAanC,OAAO,CAAC,oBAAoB;IAmB5B,OAAO,CAAC,sBAAsB;IAO9B,OAAO,CAAC,mBAAmB;IAM3B,OAAO,CAAC,YAAY;IAOpB,OAAO,CAAC,gCAAgC;YA2B1B,0BAA0B;YA2E1B,yBAAyB;YAqBzB,WAAW;YAoBX,gBAAgB;IAwC9B,OAAO,CAAC,yBAAyB;YAsBnB,oBAAoB;YAkGpB,mBAAmB;YAwCnB,mBAAmB;IA0GjC,OAAO,CAAC,SAAS;IAoBjB,OAAO,CAAC,wBAAwB;IAMhC,OAAO,CAAC,cAAc;IAMtB,OAAO,CAAC,mBAAmB;YAWb,IAAI;IAiFlB,OAAO,CAAC,gBAAgB;CAWxB;AAkHD,wBAAgB,kBAAkB,CAAC,MAAM,EAAE,kBAAkB,GAAG,YAAY,CAE3E;AAED;;;;;;;;;GASG;AACH,eAAO,MAAM,KAAK,qBAAe,CAAC;AAClC,MAAM,MAAM,KAAK,GAAG,YAAY,CAAC;AAEjC,wBAAgB,WAAW,CAAC,MAAM,EAAE,kBAAkB,GAAG,YAAY,CAEpE"}
1
+ {"version":3,"file":"agent-runtime.d.ts","sourceRoot":"","sources":["../src/agent-runtime.ts"],"names":[],"mappings":"AAAA,OAAO,EAGN,KAAK,uBAAuB,EAE5B,MAAM,aAAa,CAAC;AACrB,OAAO,KAAK,EAIX,YAAY,EAEZ,UAAU,EAKV,cAAc,EACd,iBAAiB,EAEjB,yBAAyB,EAOzB,kBAAkB,IAAI,sBAAsB,EAM5C,MAAM,eAAe,CAAC;AAmEvB;;;;GAIG;AACH,eAAO,MAAM,kDAAkD,sPACgL,CAAC;AAEhP;;;GAGG;AACH,eAAO,MAAM,+CAA+C,0JAC4F,CAAC;AAEzJ;;;GAGG;AACH,eAAO,MAAM,2CAA2C,2JACiG,CAAC;AAuB1J,MAAM,MAAM,aAAa,GAAG,MAAM,GAAG,YAAY,GAAG,SAAS,YAAY,EAAE,CAAC;AAC5E,MAAM,MAAM,kBAAkB,GAAG,CAAC,KAAK,EAAE,iBAAiB,KAAK,IAAI,CAAC;AAEpE;;;;GAIG;AACH,MAAM,WAAW,2BAA4B,SAAQ,sBAAsB;IAC1E,KAAK,EAAE,UAAU,CAAC;CAClB;AAED;;;;GAIG;AACH,MAAM,WAAW,8BAChB,SAAQ,IAAI,CAAC,sBAAsB,EAAE,OAAO,CAAC;IAC7C,gDAAgD;IAChD,UAAU,EAAE,MAAM,CAAC;IACnB,sBAAsB;IACtB,OAAO,EAAE,MAAM,CAAC;IAChB,+BAA+B;IAC/B,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,kCAAkC;IAClC,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,0CAA0C;IAC1C,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACjC,wCAAwC;IACxC,OAAO,CAAC,EAAE,uBAAuB,CAAC,SAAS,CAAC,CAAC;CAC7C;AAED;;;;;GAKG;AACH,MAAM,MAAM,kBAAkB,GAC3B,2BAA2B,GAC3B,8BAA8B,CAAC;AAuJlC,qBAAa,sBAAuB,SAAQ,KAAK;IAChD,QAAQ,CAAC,MAAM,CAAC,EAAE,OAAO,CAAC;gBAEd,MAAM,CAAC,EAAE,OAAO;CAa5B;AAkLD,qBAAa,YAAY;IACxB,OAAO,CAAC,MAAM,CACU;IACxB,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAiC;IAE3D,OAAO,CAAC,QAAQ,CAAC,KAAK,CAA0C;IAChE,OAAO,CAAC,KAAK,CAQX;IACF;;;;;;OAMG;IACH,OAAO,CAAC,mBAAmB,CAAgB;IAC3C,OAAO,CAAC,QAAQ,CAAC,KAAK,CAuCpB;IACF,uDAAuD;IACvD,OAAO,CAAC,yBAAyB,CAAS;IAC1C,2FAA2F;IAC3F,OAAO,CAAC,sBAAsB,CAAK;IACnC,6EAA6E;IAC7E,OAAO,CAAC,0BAA0B,CAAS;IAC3C,OAAO,CAAC,cAAc,CAAC,CAAgB;IACvC,OAAO,CAAC,eAAe,CAAC,CAAkB;IAC1C,OAAO,CAAC,oBAAoB,CAAC,CAAkB;IAC/C,OAAO,CAAC,QAAQ,CAAC,mBAAmB,CAAC,CAAS;IAC9C,OAAO,CAAC,QAAQ,CAAC,gBAAgB,CAAC,CAAS;gBAE/B,MAAM,EAAE,kBAAkB;IAkBhC,GAAG,CAAC,KAAK,EAAE,aAAa,GAAG,OAAO,CAAC,cAAc,CAAC;IAIlD,QAAQ,CAAC,KAAK,CAAC,EAAE,aAAa,GAAG,OAAO,CAAC,cAAc,CAAC;IAI9D,+EAA+E;IAC/E,wBAAwB,IAAI,IAAI;IAIhC,KAAK,CAAC,MAAM,CAAC,EAAE,OAAO,GAAG,IAAI;IAkB7B,SAAS,CAAC,QAAQ,EAAE,kBAAkB,GAAG,MAAM,IAAI;IAOnD;;;;;;;OAOG;IACH,OAAO,CAAC,QAAQ,EAAE,SAAS,YAAY,EAAE,GAAG,IAAI;IAqBhD,QAAQ,IAAI,yBAAyB;YAiBvB,iBAAiB;YAKjB,UAAU;IAkBxB,OAAO,CAAC,aAAa;IAarB,OAAO,CAAC,8BAA8B;IAUtC,OAAO,CAAC,gCAAgC;IAUxC,OAAO,CAAC,6BAA6B;YAOvB,sBAAsB;YAatB,OAAO;IA4RrB;;;OAGG;YACW,wBAAwB;YAoCxB,kBAAkB;YAgBlB,iBAAiB;IAM/B;;;;;OAKG;YACW,kCAAkC;IAsBhD;;;;;;;;;;;;;;OAcG;YACW,yCAAyC;IAUvD;;;;;;OAMG;YACW,sBAAsB;IAwCpC;;;;;;;;;;OAUG;IACH,OAAO,CAAC,4BAA4B;IAuBpC;;;;;;;OAOG;IACH,OAAO,CAAC,cAAc;IAOtB;;;OAGG;YACW,cAAc;IAkB5B;;;;;;;;;OASG;YACW,4CAA4C;IA+C1D,OAAO,CAAC,yBAAyB;IAiBjC,OAAO,CAAC,0BAA0B;IAsBlC,4EAA4E;IAC5E,OAAO,CAAC,oBAAoB;IAK5B;;;;;;;;;;;;;;;;;;;;;;;;;OAyBG;YACW,gCAAgC;IAoH9C,kEAAkE;YACpD,sBAAsB;YAmBtB,wBAAwB;IAgBtC;;;;OAIG;YACW,oBAAoB;IAiBlC,4EAA4E;YAC9D,mBAAmB;YAqFnB,kCAAkC;IAchD;;;;OAIG;YACW,qBAAqB;YAwUpB,uBAAuB;IAuDtC,OAAO,CAAC,2BAA2B;IAanC,OAAO,CAAC,oBAAoB;IAmB5B,OAAO,CAAC,sBAAsB;IAO9B,OAAO,CAAC,mBAAmB;IAM3B,OAAO,CAAC,YAAY;IAOpB,OAAO,CAAC,gCAAgC;YA2B1B,0BAA0B;YA2E1B,yBAAyB;YAqBzB,WAAW;YAoBX,gBAAgB;IAwC9B,OAAO,CAAC,yBAAyB;YAsBnB,oBAAoB;YAkGpB,mBAAmB;YAwCnB,mBAAmB;IA0GjC,OAAO,CAAC,SAAS;IAoBjB,OAAO,CAAC,wBAAwB;IAMhC,OAAO,CAAC,cAAc;IAMtB,OAAO,CAAC,mBAAmB;YAWb,IAAI;IAoFlB,OAAO,CAAC,gBAAgB;CAWxB;AAkHD,wBAAgB,kBAAkB,CAAC,MAAM,EAAE,kBAAkB,GAAG,YAAY,CAE3E;AAED;;;;;;;;;GASG;AACH,eAAO,MAAM,KAAK,qBAAe,CAAC;AAClC,MAAM,MAAM,KAAK,GAAG,YAAY,CAAC;AAEjC,wBAAgB,WAAW,CAAC,MAAM,EAAE,kBAAkB,GAAG,YAAY,CAEpE"}
package/dist/index.js CHANGED
@@ -54,7 +54,7 @@ ${t.join(`
54
54
  }
55
55
  `)}return _.write("payload.value = newResult;"),_.write("return payload;"),_.compile()},s,a=Pe,u=!K.jitless,c=u&&Wi.value,d=t.catchall,f;e._zod.parse=(h,g)=>{f??(f=r.value);let v=h.value;if(!a(v))return h.issues.push({expected:"object",code:"invalid_type",input:v,inst:e}),h;if(u&&c&&g?.async===!1&&g.jitless!==!0){if(!s)s=o(t.shape);if(h=s(h,g),!d)return h;return br([],v,h,g,f,e,g?.abortEarly===!0)}return n(h,g)}});function mn(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)=>!Q(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)=>ae(s,r,ee())))}),t}var _r=p("$ZodUnion",(e,t)=>{R.init(e,t),C(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),C(e,"optout",(r)=>r.def.options.some((i)=>i._zod.optout==="optional")?"optional":void 0),C(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}),C(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)=>Ot(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 u=a._zod.run({value:r.value,issues:[]},i);if(u instanceof Promise)s.push(u),o=!0;else{if(u.issues.length===0)return u;s.push(u)}}if(!o)return mn(s,r,e,i);return Promise.all(s).then((a)=>mn(a,r,e,i))}});function pa(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 fa=p("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,_r.init(e,t);let n=e._zod.parse;C(e,"propValues",(i)=>{let o={},s=0;for(let a of i.def.options){let u=a._zod.propValues;if(!u||Object.keys(u).length===0)throw Error(`Invalid discriminated union option at index "${i.def.options.indexOf(a)}"`);if(u[i.def.discriminator]?.has(void 0))s++;for(let[c,d]of Object.entries(u)){if(!Object.prototype.hasOwnProperty.call(o,c))te(o,c,new Set);for(let f of d)o[c].add(f)}}if(!i.def.unionFallback&&s>1)o[i.def.discriminator]?.delete(void 0);return o}),t.options.forEach((i,o)=>{let s=Pt(i._zod.def);if(s&&!Object.prototype.hasOwnProperty.call(s,t.discriminator))throw Error(`Invalid discriminated union option at index "${o}"`)});let r=ot(()=>pa(t));e._zod.parse=(i,o)=>{let s=i.value;if(!Pe(s))return i.issues.push({code:"invalid_type",expected:"object",input:s,inst:e}),i;let a=s?.[t.discriminator],u=r.value.get(a);if(u&&(a!==void 0||o.direction!=="backward"))return u._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((c)=>r.value.get(c)!==null),input:s,path:[t.discriminator],inst:e}),i}}),ha=p("$ZodIntersection",(e,t)=>{R.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,u])=>gn(n,a,u));return gn(n,o,s)}});function Et(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(be(e)&&be(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=Et(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=Et(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 gn(e,t,n){let r=new Map,i,o=new Map,s=(c,d)=>{let f;if(c.code==="unrecognized_keys"&&!c.path?.length)i??(i=c),f=c.keys;else if(c.code==="invalid_key"&&c.origin==="record"&&c.path?.length===1){let h=String(c.path[0]);if(!o.has(h))o.set(h,c);f=[h]}else return!1;for(let h of f){if(!r.has(h))r.set(h,{});r.get(h)[d]=!0}return!0};for(let c of t.issues)if(!s(c,"l"))e.issues.push(c);for(let c of n.issues)if(!s(c,"r"))e.issues.push(c);let a=[...r].filter(([,c])=>c.l&&c.r).map(([c])=>c);if(a.length){let c=i?a.filter((d)=>i.keys.includes(d)):[];if(c.length)e.issues.push({...i,keys:c});for(let d of a)if(!c.includes(d)&&o.has(d))e.issues.push(o.get(d))}let u=Et(t.value,n.value);if(!u.valid){if(Q(e))return e;throw Error(`Unmergable intersection. Error path: ${JSON.stringify(u.mergeErrorPath)}`)}return e.value=u.data,e}var wr=p("$ZodTuple",(e,t)=>{R.init(e,t);let n=t.items,r=K.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=[],u=yn(n,"optin"),c=yn(n,"optout");if(!t.rest){if(s.length<u)return i.issues.push({code:"too_small",minimum:u,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),f=t.rest?o?.abortEarly:void 0,h=!1;for(let g=0;g<n.length;g++){let v=n[g]._zod.run({value:s[g],issues:[]},o);if(v instanceof Promise)a.push(v.then((_)=>{d[g]=_}));else if(d[g]=v,f&&!h&&v.issues.length)h=Q(v)}if(t.rest&&!h){let g=n.length-1,v=s.slice(n.length),_=i.issues.length;for(let S of v){if(f&&i.issues.length!==_){if(Q(i,_))break;_=i.issues.length}g++;let k=t.rest._zod.run({value:S,issues:[]},o);if(k instanceof Promise)a.push(k.then((U)=>vn(U,i,g)));else vn(k,i,g)}}if(a.length)return Promise.all(a).then(()=>bn(d,i,n,s,c));return bn(d,i,n,s,c)}});function yn(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 vn(e,t,n){if(e.issues.length)t.issues.push(...oe(n,e.issues));t.value[n]=e.value}function bn(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(...oe(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 ma=p("$ZodRecord",(e,t)=>{R.init(e,t);let n=K.memoizer;n?.attach(e),e._zod.parse=(r,i)=>{let o=r.value;if(!be(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 u=new Set;for(let d of a)if(typeof d==="string"||typeof d==="number"||typeof d==="symbol"){if(u.add(typeof d==="number"?d.toString():d),d==="__proto__")continue;let f=t.keyType._zod.run({value:d,issues:[]},i);if(f instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(f.issues.length){r.issues.push({code:"invalid_key",origin:"record",issues:f.issues.map((v)=>ae(v,i,ee())),input:d,path:[d],inst:e});continue}let h=f.value;if(h==="__proto__")continue;let g=t.valueType._zod.run({value:o[d],issues:[]},i);if(g instanceof Promise)s.push(g.then((v)=>{if(v.issues.length)r.issues.push(...oe(d,v.issues));r.value[h]=v.value}));else{if(g.issues.length)r.issues.push(...oe(d,g.issues));r.value[h]=g.value}}let c;for(let d in o)if(!u.has(d))if(t.mode==="loose"){if(d==="__proto__")continue;r.value[d]=o[d]}else c=c??[],c.push(d);if(c&&c.length>0)r.issues.push({code:"unrecognized_keys",input:o,inst:e,keys:c,continue:!0})}else{r.value=n?n.alloc(e,r,{},i):{};let u;for(let c of Reflect.ownKeys(o)){if(c==="__proto__")continue;if(!Object.prototype.propertyIsEnumerable.call(o,c))continue;let d=t.keyType._zod.run({value:c,issues:[]},i);if(d instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(typeof c==="string"&&Ut.test(c)&&d.issues.length){let g=t.keyType._zod.run({value:Number(c),issues:[]},i);if(g instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(g.issues.length===0)d=g}if(d.issues.length){if(t.mode==="loose")r.value[c]=o[c];else if(a)u=u??[],u.push(c);else r.issues.push({code:"invalid_key",origin:"record",issues:d.issues.map((g)=>ae(g,i,ee())),input:c,path:[c],inst:e});continue}let f=d.value;if(f==="__proto__")continue;let h=t.valueType._zod.run({value:o[c],issues:[]},i);if(h instanceof Promise)s.push(h.then((g)=>{if(g.issues.length)r.issues.push(...oe(c,g.issues));r.value[f]=g.value}));else{if(h.issues.length)r.issues.push(...oe(c,h.issues));r.value[f]=h.value}}if(u&&u.length>0)r.issues.push({code:"unrecognized_keys",input:o,inst:e,keys:u,continue:!0})}if(s.length)return Promise.all(s).then(()=>r);return r}}),ga=p("$ZodEnum",(e,t)=>{R.init(e,t);let n=wt(t.entries),r=new Set(n);e._zod.values=r,C(e,"pattern",(i)=>{let o=wt(i.def.entries).filter((s)=>Ji.has(typeof s));return new RegExp(o.length?`^(${o.map((s)=>_e(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}}),ya=p("$ZodLiteral",(e,t)=>{R.init(e,t);let n=new Set(t.values);e._zod.values=n,C(e,"pattern",(r)=>{let i=r.def.values;return new RegExp(i.length?`^(${i.map((o)=>typeof o==="string"?_e(o):o?_e(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}}),va=p("$ZodTransform",(e,t)=>{R.init(e,t),e._zod.optin="optional",K.memoizer?.guard(e),e._zod.parse=(n,r)=>{if(r.direction==="backward")throw new $t(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 se;return n.value=i,n}});function _n(e,t){return e.value=t.issues.length?void 0:t.value,e}var Tr=p("$ZodOptional",(e,t)=>{R.init(e,t),C(e,"optin",(n)=>n.def.innerType._zod.optin==="defaulted"?"defaulted":"optional"),e._zod.optout="optional",C(e,"values",(n)=>{let r=n.def.innerType._zod.values;return r?new Set([...r,void 0]):void 0}),C(e,"pattern",(n)=>{let r=n.def.innerType._zod.pattern;return r?new RegExp(`^(${Ot(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)=>_n(n,o));return _n(n,i)}return t.innerType._zod.run(n,r)}}),ba=p("$ZodExactOptional",(e,t)=>{Tr.init(e,t),C(e,"values",(n)=>n.def.innerType._zod.values),C(e,"pattern",(n)=>n.def.innerType._zod.pattern),e._zod.parse=(n,r)=>t.innerType._zod.run(n,r)}),_a=p("$ZodNullable",(e,t)=>{R.init(e,t),C(e,"optin",(n)=>n.def.innerType._zod.optin),C(e,"optout",(n)=>n.def.innerType._zod.optout),C(e,"pattern",(n)=>{let r=n.def.innerType._zod.pattern;return r?new RegExp(`^(${Ot(r.source)}|null)$`):void 0}),C(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)}}),wa=p("$ZodDefault",(e,t)=>{R.init(e,t),e._zod.optin="defaulted",C(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)=>wn(o,t));return wn(i,t)}});function wn(e,t){if(e.value===void 0)e.value=t.defaultValue;return e}var Ta=p("$ZodPrefault",(e,t)=>{R.init(e,t),e._zod.optin="defaulted",C(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)}}),ka=p("$ZodNonOptional",(e,t)=>{R.init(e,t),C(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)=>Tn(o,e));return Tn(i,e)}});function Tn(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 kn(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)=>ae(i,r,ee()))},input:e.value}),e}var Ea=p("$ZodCatch",(e,t)=>{R.init(e,t),C(e,"optin",(n)=>n.def.innerType._zod.optin==="defaulted"?"defaulted":"optional"),C(e,"optout",(n)=>n.def.innerType._zod.optout),C(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)=>kn(n,o,t,r));return kn(n,i,t,r)}}),kr=p("$ZodPipe",(e,t)=>{R.init(e,t),C(e,"values",(n)=>n.def.in._zod.values),C(e,"optin",(n)=>n.def.in._zod.optin),C(e,"optout",(n)=>n.def.out._zod.optout),C(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)=>Ue(s,t.in,r));return Ue(o,t.in,r)}let i=t.in._zod.run(n,r);if(i instanceof Promise)return i.then((o)=>Ue(o,t.out,r));return Ue(i,t.out,r)}});function Ue(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 Aa=p("$ZodPreprocess",(e,t)=>{kr.init(e,t)}),Ia=p("$ZodReadonly",(e,t)=>{R.init(e,t),C(e,"propValues",(n)=>n.def.innerType._zod.propValues),C(e,"values",(n)=>n.def.innerType._zod.values),C(e,"optin",(n)=>n.def.innerType?._zod?.optin),C(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(En);return En(i)}});function En(e){if(!e.memo)e.value=Object.freeze(e.value);return e}var Sa=p("$ZodFunction",(e,t)=>(R.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?cn(e._def.input,r):r,o=Reflect.apply(n,this,i);if(e._def.output)return cn(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 dn(e._def.input,r):r,o=await Reflect.apply(n,this,i);if(e._def.output)return await dn(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 wr({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)),xa=p("$ZodPromise",(e,t)=>{R.init(e,t),e._zod.parse=(n,r)=>Promise.resolve(n.value).then((i)=>t.innerType._zod.run({value:i,issues:[]},r))}),Ca=p("$ZodCustom",(e,t)=>{H.init(e,t),R.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)=>An(o,n,r,e));An(i,n,r,e);return}});function An(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(Ne(i))}}class Er extends Error{constructor(){super("Cannot parse a reference cycle that closes through a transform");this.name="ZodCyclicError"}}var At="~memo",In=[];function Ar(e){return e!==null&&typeof e==="object"}function yt(e){return e.map((t)=>t.path?{...t,path:t.path.slice()}:{...t})}var Ir=new WeakMap,Ie=0,He=1,Re=2;function Ve(e,t,n){let r=Ir.get(e);if(r!==void 0)return r?Re:Ie;if(t.has(e))return Re;t.add(e);let i=Ie,o=(d)=>{if(i!==Re&&d?._zod){let f=Ve(d,t,n);if(f>i)i=f}},s=(d,f)=>{let h=Ie;for(let g of Reflect.ownKeys(d)){let v=Object.getOwnPropertyDescriptor(d,g);if(f&&!v.enumerable)continue;let _=v.get?He:v.value?._zod?Ve(v.value,t,n):Ie;if(_>h)h=_}return h},a=(d)=>{if(d>i)i=d},u=e._zod.def;switch(u.type){case"object":{let d=Pt(u);a(d?s(d,!0):He),o(u.catchall);break}case"array":o(u.element);break;case"tuple":for(let d of u.items)o(d);o(u.rest);break;case"record":case"map":o(u.keyType),o(u.valueType);break;case"set":o(u.valueType);break;case"union":for(let d of u.options)o(d);break;case"intersection":o(u.left),o(u.right);break;case"optional":case"nullable":case"default":case"prefault":case"catch":case"readonly":case"nonoptional":case"promise":case"success":o(u.innerType);break;case"pipe":o(u.in),o(u.out);break;case"function":o(u.input),o(u.output);break;case"lazy":{let d=u._cachedInner??(n?e._zod.innerType:void 0);a(d?Ve(d,t,!1):He);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 u){let f=Object.getOwnPropertyDescriptor(u,d);if(!f||f.get)continue;let h=f.value;if(!h||typeof h!=="object")continue;if(h._zod)o(h);else if(Array.isArray(h))for(let g of h)o(g)}}return t.delete(e),Ra(e,i)}function Ra(e,t){if(t!==He)Ir.set(e,t===Re);return t}function Oa(e,t){let n=e.buckets.get(t);if(!n)n=new WeakMap,e.buckets.set(t,n);return n}var je,Be=[],Pa={alloc(e,t,n){let r=je;if(!r)return n;je=void 0;let i={value:n,issues:null};return r.set(t.value,i),Be.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"&&Ma(o,i.value))throw new Er;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=(u,c)=>{if(n===void 0){let k=Ve(e,new Set,!1);if(k===Ie){if(e._zod.parse=s,e._zod.run===a)e._zod.run=s;return s(u,c)}if(k===Re||r)n=!0;else r=!0}let d=u.value;if(!Ar(d))return s(u,c);let f=c[At];if(!f)f={buckets:new WeakMap,backEdges:void 0},c[At]=f;let h;if(i===c)h=o;else h=Oa(f,e),i=c,o=h;let g=h.get(d);if(g){if(u.value=g.value,g.issues){if(g.issues.length)u.issues.push(...yt(g.issues))}else u.memo=!0,f.backEdges??(f.backEdges=new WeakSet),f.backEdges.add(g.value);return u}je=h;let v=Be.length,_=s(u,c);je=void 0;let S=Be.length>v?Be.pop():void 0;if(_ instanceof Promise)return _.then((k)=>{if(S)S.issues=k.issues.length?yt(k.issues):In;return k});if(S)S.issues=_.issues.length?yt(_.issues):In;return _};if(e._zod.parse=a,e._zod.run===s)e._zod.run=a})}};function Na(){return Pa}function Ma(e,t){let n=e[At]?.backEdges;return n!==void 0&&Ar(t)&&n.has(t)}var za=()=>{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=oo(o.input),u=i(a,o.input);return`Invalid input: expected ${s}, received ${u}`}case"invalid_value":if(o.values.length===1)return`Invalid input: expected ${Qn(o.values[0])}`;return`Invalid option: expected one of ${rn(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":""}: ${rn(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 $a(){return{localeError:za()}}var Sn;class Sr{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 La(){return new Sr}(Sn=globalThis).__zod_globalRegistry??(Sn.__zod_globalRegistry=La());var Se=globalThis.__zod_globalRegistry;function xr(e){if(e.checks)e.checks=[...e.checks];return e}function Da(e,t){return new e(xr({type:"string",...w(t)}))}function Ua(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...w(t)})}function ja(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...w(t)})}function Ba(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...w(t)})}function Fa(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...w(t)})}function qa(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...w(t)})}function Za(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...w(t)})}function Ha(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...w(t)})}function Va(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...w(t)})}function Wa(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...w(t)})}function Ja(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...w(t)})}function Ka(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...w(t)})}function Ga(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...w(t)})}function Ya(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...w(t)})}function Xa(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...w(t)})}function Qa(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...w(t)})}function el(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...w(t)})}function tl(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...w(t)})}function nl(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...w(t)})}function rl(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...w(t)})}function il(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...w(t)})}function ol(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...w(t)})}function sl(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...w(t)})}function al(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...w(t)})}function ll(e,t){return new e({type:"string",format:"date",check:"string_format",...w(t)})}function ul(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...w(t)})}function cl(e,t){return new e({type:"string",format:"duration",check:"string_format",...w(t)})}function dl(e,t){return new e(xr({type:"number",checks:[],...w(t)}))}function pl(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...w(t)})}function fl(e,t){return new e({type:"boolean",...w(t)})}function hl(e){return new e({type:"unknown"})}function ml(e,t){return new e({type:"never",...w(t)})}function gl(e,t){return new e({type:"void",...w(t)})}function yl(e,t){return new e({type:"date",...w(t)})}function xn(e,t){return new ar({check:"less_than",...w(t),value:e,inclusive:!1})}function We(e,t){return new ar({check:"less_than",...w(t),value:e,inclusive:!0})}function Cn(e,t){return new lr({check:"greater_than",...w(t),value:e,inclusive:!1})}function Je(e,t){return new lr({check:"greater_than",...w(t),value:e,inclusive:!0})}function Rn(e,t){return new cs({check:"multiple_of",...w(t),value:e})}function Cr(e,t){return new ps({check:"max_length",...w(t),maximum:e})}function Xe(e,t){return new fs({check:"min_length",...w(t),minimum:e})}function Rr(e,t){return new hs({check:"length_equals",...w(t),length:e})}function vl(e,t){return new ms({check:"string_format",format:"regex",...w(t),pattern:e})}function bl(e){return new gs({check:"string_format",format:"lowercase",...w(e)})}function _l(e){return new ys({check:"string_format",format:"uppercase",...w(e)})}function wl(e,t){return new vs({check:"string_format",format:"includes",...w(t),includes:e})}function Tl(e,t){return new bs({check:"string_format",format:"starts_with",...w(t),prefix:e})}function kl(e,t){return new _s({check:"string_format",format:"ends_with",...w(t),suffix:e})}function ke(e){return new ws({check:"overwrite",tx:e})}function El(e){return ke((t)=>t.normalize(e))}function Al(){return ke((e)=>e.trim())}function Il(){return ke((e)=>e.toLowerCase())}function Sl(){return ke((e)=>e.toUpperCase())}function xl(){return ke((e)=>Vi(e))}function Cl(e,t,n){return new e({type:"array",element:t,...w(n)})}function Rl(e,t,n){let r=w(n);return r.abort??(r.abort=!0),new e({type:"custom",check:"custom",fn:t,...r})}function Ol(e,t,n){return new e({type:"custom",check:"custom",fn:t,...w(n)})}function Pl(e,t){let n=Nl((r)=>(r.addIssue=(i)=>{if(typeof i==="string")r.issues.push(Ne(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(Ne(o))}},e(r.value,r)),t);return n}function Nl(e,t){let n=new H({check:"custom",...w(t)});return n._zod.check=e,n}function Oe(e,...t){for(let n of t)for(let r of Reflect.ownKeys(n))if(Object.prototype.propertyIsEnumerable.call(n,r))te(e,r,n[r]);return e}function Qe(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??Se,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 B(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 P(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 c={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,s.schema,c);else{let f=s.schema,h=t.processors[i.type];if(!h)throw Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);h(e,t,f,c)}let d=e._zod.parent;if(d){if(!s.ref)s.ref=d;P(d,t,c),t.seen.get(d).isParent=!0}}let u=t.metadataRegistry.get(e);if(u)Oe(s.schema,u);if(t.io==="input"&&F(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 On(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 u=r.get(a);if(u&&u!==s[0])throw Error(`Duplicate schema id "${a}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(a,s[0])}}let i=(s)=>{let a=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){let f=e.external.registry.get(s[0])?.id,h=e.external.uri??((v)=>v);if(f)return{ref:h(f)};let g=s[1].defId??s[1].schema.id??`schema${e.counter++}`;return s[1].defId=g,{defId:g,ref:`${h("__shared")}#/${a}/${On(g)}`}}let u="#",c=`${u}/${a}/`;if(s[1]===n&&!s[1].schema.id)return{ref:u};let d=s[1].schema.id??`__schema${e.counter++}`;return{defId:d,ref:c+On(d)}},o=(s)=>{if(s[1].schema.$ref)return;let a=s[1],{ref:u,defId:c}=i(s);if(a.def={...a.schema},c)a.defId=c;let d=a.schema;for(let f in d)delete d[f];d.$ref=u};if(e.cycles==="throw")for(let s of e.seen.entries()){let a=s[1];if(a.cycle)throw Error(`Cycle detected: #/${a.cycle?.join("/")}/<root>
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 u=e.external.registry.get(s[0])?.id;if(t!==s[0]&&u){o(s);continue}}if(e.metadataRegistry.get(s[0])?.id){o(s);continue}if(a.cycle){o(s);continue}if(a.count>1){if(e.reused==="ref")o(s)}}if(e.external)e.sharedDefsExtractedFor=e.external}function Or(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;Or(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 Pr=new Set(["type","properties","required","additionalProperties"]),Pn=["oneOf","anyOf"];function Nn(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 It(e){let t=[];for(let o of e){if(typeof o!=="object"||o.type!=="object")return null;for(let s in o)if(!Pr.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 c of t){let d=c.properties?.[s]??Nn(c);if(d===null||d===void 0)continue;if(!a.some((f)=>JSON.stringify(f)===JSON.stringify(d)))a.push(d)}let u=a.length===1?a[0]:It(a)??{allOf:a};te(n,s,u)}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=Nn(s);if(a&&!o.some((u)=>JSON.stringify(u)===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 Ml(e){let t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(let i of Pr)if(i in e)return;let n=t.filter((i)=>Pn.some((o)=>Array.isArray(i[o]))),r=null;if(!n.length)r=It(t);else{let i=n[0],o=Pn.find((u)=>Array.isArray(i[u]));if(Object.keys(i).length!==1)return;let s=t.filter((u)=>u!==i),a=i[o].map((u)=>It([...s,u]));if(a.some((u)=>!u))return;r={[o]:a}}if(!r)return;delete e.allOf,Oe(e,r)}function tt(e,t){let n=e.seen.get(t);if(!n)throw Error("Unprocessed schema. This is a bug in Zod.");let r=(a)=>{let u=e.seen.get(a);if(u.ref===null)return;let c=u.def??u.schema,d={...c},f=u.ref;if(u.ref=null,f){r(f);let g=e.seen.get(f),v=g.schema;if(v.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"))c.allOf=c.allOf??[],c.allOf.push(v);else Oe(c,v);if(Oe(c,d),a._zod.parent===f)for(let _ in c){if(_==="$ref"||_==="allOf")continue;if(!(_ in d))delete c[_]}if(v.$ref&&g.def)for(let _ in c){if(_==="$ref"||_==="allOf")continue;if(_ in g.def&&JSON.stringify(c[_])===JSON.stringify(g.def[_]))delete c[_]}}let h=a._zod.parent;if(h&&h!==f){r(h);let g=e.seen.get(h);if(g?.schema.$ref){if(c.$ref=g.schema.$ref,g.def)for(let v in c){if(v==="$ref"||v==="allOf")continue;if(v in g.def&&JSON.stringify(c[v])===JSON.stringify(g.def[v]))delete c[v]}}}e.override({zodSchema:a,jsonSchema:c,path:u.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())Or(a[1].def??a[1].schema);for(let a of e.deferred)a();if(e.intersections.length){let a=new Map;for(let u of e.seen.values())for(let c of[u.schema,u.def]){let d=c?.allOf;if(!Array.isArray(d))continue;let f=a.get(d);if(f)f.push(c);else a.set(d,[c])}for(let u of e.intersections)for(let c of a.get(u)??[])Ml(c)}}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)}Oe(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 u=a[1];if(u.def&&u.defId){if(u.def.id===u.defId)delete u.def.id;te(s,u.defId,u.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:nt(t,"input",e.processors),output:nt(t,"output",e.processors)}},enumerable:!1,writable:!1}),a}catch(a){throw Error("Error converting schema to JSON.")}}function F(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 F(r.element,n);if(r.type==="set")return F(r.valueType,n);if(r.type==="lazy")return F(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 F(r.innerType,n);if(r.type==="intersection")return F(r.left,n)||F(r.right,n);if(r.type==="record"||r.type==="map")return F(r.keyType,n)||F(r.valueType,n);if(r.type==="pipe"){if(e._zod.traits.has("$ZodCodec"))return!0;return F(r.in,n)||F(r.out,n)}if(r.type==="object"){for(let i in r.shape)if(F(r.shape[i],n))return!0;return!1}if(r.type==="union"){for(let i of r.options)if(F(i,n))return!0;return!1}if(r.type==="tuple"){for(let i of r.items)if(F(i,n))return!0;if(r.rest&&F(r.rest,n))return!0;return!1}return!1}var zl=(e,t={})=>(n)=>{let r=Qe({...n,processors:t});return P(e,r),et(r,e),tt(r,e)},nt=(e,t,n={})=>(r)=>{let{libraryOptions:i,target:o}=r??{},s=Qe({...i??{},target:o,io:t,processors:n});return P(e,s),et(s,e),tt(s,e)},we=(e,t,n)=>{if(e[t]===void 0||n>e[t])e[t]=n},Te=(e,t,n)=>{if(e[t]===void 0||n<e[t])e[t]=n},Mn=(e,t)=>{we(e,"minimum",t),Te(e,"maximum",t)},Nr=(e,t)=>{if(e.multipleOf??(e.multipleOf=[]),!e.multipleOf.includes(t))e.multipleOf.push(t)},Mr=(e,t)=>{e.patterns??(e.patterns=new Set),e.patterns.add(t)},zr=(e,t)=>{e.mime=e.mime?e.mime.filter((n)=>t.includes(n)):[...t]},$r=(e,t)=>{if(e.format=t,t.includes("int"))e.isInt=!0},zn=(e,t)=>we(e,"minimum",t.minimum),$n=(e,t)=>Te(e,"maximum",t.maximum),Ln=(e)=>(t,n)=>{$r(t,n.format);let[r,i]=e[n.format];we(t,"minimum",r),Te(t,"maximum",i)},$l={greater_than:(e,t)=>we(e,t.inclusive?"minimum":"exclusiveMinimum",t.value),less_than:(e,t)=>Te(e,t.inclusive?"maximum":"exclusiveMaximum",t.value),multiple_of:(e,t)=>Nr(e,t.value),number_format:Ln(er),bigint_format:Ln(Gi),min_length:zn,max_length:$n,length_equals:(e,t)=>Mn(e,t.length),min_size:zn,max_size:$n,size_equals:(e,t)=>Mn(e,t.size),string_format:(e,t)=>{if($r(e,t.format),t.pattern)Mr(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)=>zr(e,t.mime)};function q(e){let t={},n=e._zod.def,r=e._zod.traits.has("$ZodCheck")?[e,...n.checks??[]]:n.checks??[];for(let o of r)$l[o._zod.def.check]?.(t,o._zod.def);let i=e._zod.bag;if(i.minimum!==void 0)we(t,"minimum",i.minimum);if(i.exclusiveMinimum!==void 0)we(t,"exclusiveMinimum",i.exclusiveMinimum);if(i.maximum!==void 0)Te(t,"maximum",i.maximum);if(i.exclusiveMaximum!==void 0)Te(t,"exclusiveMaximum",i.exclusiveMaximum);if(i.multipleOf!==void 0)Nr(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)zr(t,i.mime);for(let o of i.patterns??[])Mr(t,o);return t}var Ll={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},Dl=new Map([[gr,Yo],[Ft,Xo]]),Lr=(e)=>Dl.get(e)??e,Dr=(e,t,n,r)=>{let i=n;i.type="string";let{minimum:o,maximum:s,format:a,patterns:u,contentEncoding:c,laxFormat:d}=q(e);if(typeof o==="number")i.minLength=o;if(typeof s==="number")i.maxLength=s;if(a){if(i.format=Ll[a]??a,i.format==="")delete i.format;if(a==="time"||d)delete i.format}if(c)i.contentEncoding=c;if(u&&u.size>0){let f=[...u].map(Lr);if(f.length===1)i.pattern=f[0].source;else if(f.length>1)i.allOf=[...f.map((h)=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:h.source}))]}},Ur=(e,t,n,r)=>{let i=n,{minimum:o,maximum:s,multipleOf:a,exclusiveMaximum:u,exclusiveMinimum:c,isInt:d}=q(e);i.type=d?"integer":"number";let f=typeof c==="number"&&c>=(o??Number.NEGATIVE_INFINITY),h=typeof u==="number"&&u<=(s??Number.POSITIVE_INFINITY),g=t.target==="draft-04"||t.target==="openapi-3.0";if(f)if(g)i.minimum=c,i.exclusiveMinimum=!0;else i.exclusiveMinimum=c;else if(typeof o==="number")i.minimum=o;if(h)if(g)i.maximum=u,i.exclusiveMaximum=!0;else i.exclusiveMaximum=u;else if(typeof s==="number")i.maximum=s;if(a){let v=new Set;for(let k of a)if(Number.isFinite(k)&&k!==0)v.add(Math.abs(k));else B(e,t,i,r,`A multipleOf divisor of ${k} cannot be represented in JSON Schema`);let[_,...S]=v;if(_!==void 0)i.multipleOf=_;if(S.length)i.allOf=[...i.allOf??[],...S.map((k)=>({multipleOf:k}))]}},jr=(e,t,n,r)=>{n.type="boolean"},Ul=(e,t,n,r)=>{B(e,t,n,r,"BigInt cannot be represented in JSON Schema")},jl=(e,t,n,r)=>{B(e,t,n,r,"Symbols cannot be represented in JSON Schema")},Bl=(e,t,n,r)=>{if(t.target==="openapi-3.0")n.type="string",n.nullable=!0,n.enum=[null];else n.type="null"},Fl=(e,t,n,r)=>{B(e,t,n,r,"Undefined cannot be represented in JSON Schema")},Br=(e,t,n,r)=>{B(e,t,n,r,"Void cannot be represented in JSON Schema")},Fr=(e,t,n,r)=>{n.not={}},ql=(e,t,n,r)=>{},qr=(e,t,n,r)=>{},Zr=(e,t,n,r)=>{B(e,t,n,r,"Date cannot be represented in JSON Schema")},Hr=(e,t,n,r)=>{let i=e._zod.def,o=wt(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},Vr=(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(B(e,t,n,r,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof s==="bigint"){if(B(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}},Zl=(e,t,n,r)=>{B(e,t,n,r,"NaN cannot be represented in JSON Schema")},Hl=(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},Vl=(e,t,n,r)=>{let i=n;i.type="string",i.format="binary",i.contentEncoding="binary";let{minimum:o,maximum:s,mime:a}=q(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((u)=>({contentMediaType:u}))},Wl=(e,t,n,r)=>{n.type="boolean"},Wr=(e,t,n,r)=>{B(e,t,n,r,"Custom types cannot be represented in JSON Schema")},Jr=(e,t,n,r)=>{B(e,t,n,r,"Function types cannot be represented in JSON Schema")},Kr=(e,t,n,r)=>{B(e,t,n,r,"Transforms cannot be represented in JSON Schema")},Jl=(e,t,n,r)=>{B(e,t,n,r,"Map cannot be represented in JSON Schema")},Kl=(e,t,n,r)=>{B(e,t,n,r,"Set cannot be represented in JSON Schema")},Gr=(e,t,n,r)=>{let i=n,o=e._zod.def,{minimum:s,maximum:a}=q(e);if(typeof s==="number")i.minItems=s;if(typeof a==="number")i.maxItems=a;i.type="array",i.items=P(o.element,t,{...r,path:[...r.path,"items"]})};function Me(e){let t=e._zod.def;if(t.type==="pipe"&&t.in._zod.traits.has("$ZodTransform"))return Me(t.out);if(t.type==="catch")return Me(t.innerType);return e._zod.optin}var Yr=(e,t,n,r)=>{let i=n,o=e._zod.def,s=o.shape;if(Object.getOwnPropertySymbols(s).length&&B(e,t,i,r,"Symbol keys cannot be represented in JSON Schema"))return;i.type="object",i.properties={};for(let u in s)te(i.properties,u,P(s[u],t,{...r,path:[...r.path,"properties",u]}));let a=[];for(let u of Object.keys(s)){let c=o.shape[u];if(t.io==="input"?Me(c)===void 0:c._zod.optout===void 0)a.push(u)}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=P(o.catchall,t,{...r,path:[...r.path,"additionalProperties"]})},Xr=(e,t,n,r)=>{let i=e._zod.def,o=i.inclusive===!1,s=i.options.map((a,u)=>P(a,t,{...r,path:[...r.path,o?"oneOf":"anyOf",u]}));if(o)n.oneOf=s;else n.anyOf=s},Qr=(e,t,n,r)=>{let i=e._zod.def,o=P(i.left,t,{...r,path:[...r.path,"allOf",0]}),s=P(i.right,t,{...r,path:[...r.path,"allOf",1]}),a=(c)=>("allOf"in c)&&Object.keys(c).length===1,u=[...a(o)?o.allOf:[o],...a(s)?s.allOf:[s]];n.allOf=u,t.intersections.push(u)},ei=(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",u=o.items.map((_,S)=>P(_,t,{...r,path:[...r.path,s,S]})),c=o.rest?P(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 _=o.items[d-1];if(!(t.io==="input"?Me(_)!==void 0:_._zod.optout==="optional"))break;d--}let f=o.items.length,h=!o.rest;if(t.target==="draft-2020-12"){if(i.prefixItems=u,h)i.items=!1;else if(c)i.items=c;if(d>0)i.minItems=d;if(h)i.maxItems=f}else if(t.target==="openapi-3.0"){if(i.items={anyOf:u},c)i.items.anyOf.push(c);if(d>0)i.minItems=d;if(h)i.maxItems=f}else{if(i.items=u,h)i.additionalItems=!1;else if(c)i.additionalItems=c;if(d>0)i.minItems=d;if(h)i.maxItems=f}let{minimum:g,maximum:v}=q(e);if(typeof g==="number")i.minItems=g;if(typeof v==="number")i.maxItems=v};function St(e,t,n){if(t.$ref){if(n.has(t))return t;n.add(t);let v=e.get(t)?.def;if(!v)return t;let _=St(e,v,n);return _===v?t:_}for(let v of["anyOf","oneOf"]){let _=t[v];if(!Array.isArray(_))continue;let S=_.map((k)=>St(e,k,n));if(S.some((k,U)=>k!==_[U]))t={...t,[v]:S}}let r=Array.isArray(t.type)?t.type:[t.type],i=!r.includes("string")&&r.some((v)=>v==="number"||v==="integer"),o=t.enum??(t.const!==void 0?[t.const]:void 0);if(!i&&!o?.some((v)=>typeof v==="number"))return t;let{minimum:s,maximum:a,exclusiveMinimum:u,exclusiveMaximum:c,multipleOf:d,format:f,id:h,...g}=t;if(g.enum)g.enum=g.enum.map((v)=>typeof v==="number"?String(v):v);else if(typeof g.const==="number")g.const=String(g.const);if(!i)return g;if(g.type="string",!o)g.pattern=(r.includes("number")?Ut:ss).source;return g}var xt=new WeakMap;function Gl(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 xt.get(e)??[]){let i=e.seen.get(r),o=(i?.def??i?.schema)?.propertyNames;if(!o||o===!0||n.has(o))continue;let s=St(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 ti=(e,t,n,r)=>{let i=n,o=e._zod.def;i.type="object";let s=o.keyType,a=q(s).patterns;if(o.mode==="loose"&&a&&a.size>0){let d=P(o.valueType,t,{...r,path:[...r.path,"patternProperties","*"]});i.patternProperties={};for(let f of a)te(i.patternProperties,Lr(f).source,d)}else{if(t.target==="draft-07"||t.target==="draft-2020-12"){i.propertyNames=P(o.keyType,t,{...r,path:[...r.path,"propertyNames"]});let d=xt.get(t);if(!d)d=[],xt.set(t,d),t.deferred.push(()=>Gl(t));d.push(e)}i.additionalProperties=P(o.valueType,t,{...r,path:[...r.path,"additionalProperties"]})}let u=s._zod.values,c=t.io==="input"&&Me(o.valueType)!==void 0;if(u&&!o.partial&&!c){let d=[...u].filter((f)=>typeof f==="string"||typeof f==="number");if(d.length>0)i.required=d.map(String)}},ni=(e,t,n,r)=>{let i=e._zod.def,o=P(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"}]},ri=(e,t,n,r)=>{let i=e._zod.def;P(i.innerType,t,r);let o=t.seen.get(e);o.ref=i.innerType},qt=Symbol();function ii(e,t,n,r,i){let o=!1,s=JSON.stringify(e,(a,u)=>{if(typeof u!=="bigint")return u;return o=!0,null});if(!o)return JSON.parse(s);return B(t,n,r,i,"BigInt defaults cannot be represented in JSON Schema"),qt}var oi=(e,t,n,r)=>{let i=e._zod.def;P(i.innerType,t,r);let o=t.seen.get(e);o.ref=i.innerType;let s=ii(i.defaultValue,e,t,n,r);if(s!==qt)n.default=s},si=(e,t,n,r)=>{let i=e._zod.def;P(i.innerType,t,r);let o=t.seen.get(e);if(o.ref=i.innerType,t.io!=="input")return;let s=ii(i.defaultValue,e,t,n,r);if(s!==qt)n._prefault=s},ai=(e,t,n,r)=>{let i=e._zod.def;P(i.innerType,t,r);let o=t.seen.get(e);o.ref=i.innerType;let s;try{s=i.catchValue(void 0)}catch{B(e,t,n,r,"Dynamic catch values are not supported in JSON Schema");return}n.default=s},li=(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;P(s,t,r);let a=t.seen.get(e);a.ref=s},ui=(e,t,n,r)=>{let i=e._zod.def;P(i.innerType,t,r);let o=t.seen.get(e);o.ref=i.innerType,n.readOnly=!0},ci=(e,t,n,r)=>{let i=e._zod.def;P(i.innerType,t,r);let o=t.seen.get(e);o.ref=i.innerType},Zt=(e,t,n,r)=>{let i=e._zod.def;P(i.innerType,t,r);let o=t.seen.get(e);o.ref=i.innerType},Yl=(e,t,n,r)=>{let i=e._zod.innerType;P(i,t,r);let o=t.seen.get(e);o.ref=i},Dn={string:Dr,number:Ur,boolean:jr,bigint:Ul,symbol:jl,null:Bl,undefined:Fl,void:Br,never:Fr,any:ql,unknown:qr,date:Zr,enum:Hr,literal:Vr,nan:Zl,template_literal:Hl,file:Vl,success:Wl,custom:Wr,function:Jr,transform:Kr,map:Jl,set:Kl,array:Gr,object:Yr,union:Xr,intersection:Qr,tuple:ei,record:ti,nullable:ni,nonoptional:ri,default:oi,prefault:si,catch:ai,pipe:li,readonly:ui,promise:ci,optional:Zt,lazy:Yl};function Xl(e,t){if("_idmap"in e){let r=e,i=Qe({...t,processors:Dn}),o={};for(let u of r._idmap.entries()){let[c,d]=u;P(d,i)}let s={},a={registry:r,uri:t?.uri,defs:o};i.external=a;for(let u of r._idmap.entries()){let[c,d]=u;et(i,d),te(s,c,tt(i,d))}if(Object.keys(o).length>0){let u=i.target==="draft-2020-12"?"$defs":"definitions";s.__shared={[u]:o}}return{schemas:s}}let n=Qe({...t,processors:Dn});return P(e,n),et(n,e),tt(n,e)}var Un=new WeakSet([Object.prototype,Error.prototype]);function Fe(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 Ql=(e,t)=>{vo.init(e,t),e.name="ZodError";let n=Object.getPrototypeOf(e);if(Un.has(n))return;Un.add(n),Fe(n,"format",(r)=>(i)=>wo(r,i)),Fe(n,"flatten",(r)=>(i)=>_o(r,i)),Fe(n,"addIssue",(r)=>(i)=>{r.issues.push(i),r.message=JSON.stringify(r.issues,Tt,2)}),Fe(n,"addIssues",(r)=>(i)=>{r.issues.push(...i),r.message=JSON.stringify(r.issues,Tt,2)}),Object.defineProperty(n,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}})},G=p("ZodError",Ql,void 0,{Parent:Error}),eu=lt(G),tu=ut(G),nu=Lt(G),ru=Dt(G),iu=So(G),ou=xo(G),su=Co(G),au=Ro(G),lu=Oo(G),uu=Po(G),cu=No(G),du=Mo(G);function pu(){if(!K.localeError)ee($a())}function ze(){if(!K.memoizer)ee({memoizer:Na()})}var O=p("ZodType",(e,t)=>(pu(),R.init(e,t),e.def=t,e.type=t.type,e),{check(...e){let t=this.def;return this.clone(V(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 ue(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(fc(e,t))},superRefine(e,t){return this.check(hc(e,t))},overwrite(e){return this.check(ke(e))},optional(){return Fn(this)},exactOptional(){return Qu(this)},nullable(){return qn(this)},nullish(){return Fn(qn(this))},nonoptional(e){return oc(this,e)},array(){return E(this)},or(e){return ge([this,e])},and(e){return Ju(this,e)},transform(e){return Zn(this,hi(e))},default(e){return nc(this,e)},prefault(e){return ic(this,e)},catch(e){return ac(this,e)},pipe(e){return Zn(this,e)},readonly(){return cc(this)},describe(e){let t=this.clone();return Se.add(t,{description:e}),t},meta(...e){if(e.length===0)return Se.get(this);let t=this.clone();return Se.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 nr(this,"~standard",{...dr(this),jsonSchema:{input:nt(this,"input"),output:nt(this,"output")}})},set "~standard"(e){le(this,"~standard",e)},parse:function e(t,n){return eu(this,t,n,{callee:e})},parseAsync:async function e(t,n){return await tu(this,t,n,{callee:e})},safeParse(e,t){return nu(this,e,t)},async safeParseAsync(e,t){return ru(this,e,t)},get spa(){return this?.safeParseAsync},set spa(e){le(this,"spa",e)},validate(e,t){return Eo(this,e,t)},validateAsync(e,t){return Io(this,e,t)},encode:function e(t,n){return iu(this,t,n,{callee:e})},decode:function e(t,n){return ou(this,t,n,{callee:e})},encodeAsync:async function e(t,n){return await su(this,t,n,{callee:e})},decodeAsync:async function e(t,n){return await au(this,t,n,{callee:e})},safeEncode(e,t){return lu(this,e,t)},safeDecode(e,t){return uu(this,e,t)},async safeEncodeAsync(e,t){return cu(this,e,t)},async safeDecodeAsync(e,t){return du(this,e,t)},toJSONSchema(e){return zl(this,{})(e)},get description(){return Se.get(this)?.description},get _def(){return this._zod.def}}),di=p("_ZodString",(e,t)=>{Bt.init(e,t),O.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Dr(e,n,r,i)},zt({format:(e)=>q(e).format??null,minLength:(e)=>q(e).minimum??null,maxLength:(e)=>q(e).maximum??null},{regex(...e){return this.check(vl(...e))},includes(...e){return this.check(wl(...e))},startsWith(...e){return this.check(Tl(...e))},endsWith(...e){return this.check(kl(...e))},min(...e){return this.check(Xe(...e))},max(...e){return this.check(Cr(...e))},length(...e){return this.check(Rr(...e))},nonempty(...e){return this.check(Xe(1,...e))},lowercase(e){return this.check(bl(e))},uppercase(e){return this.check(_l(e))},trim(){return this.check(Al())},normalize(...e){return this.check(El(...e))},toLowerCase(){return this.check(Il())},toUpperCase(){return this.check(Sl())},slugify(){return this.check(xl())}})),fu=p("ZodString",(e,t)=>{Bt.init(e,t),di.init(e,t)},{email(e){return this.check(Ua(vu,e))},url(e){return this.check(Ha(_u,e))},jwt(e){return this.check(sl(zu,e))},emoji(e){return this.check(Va(wu,e))},guid(e){return this.check(ja(bu,e))},uuid(e){return this.check(Ba(qe,e))},uuidv4(e){return this.check(Fa(qe,e))},uuidv6(e){return this.check(qa(qe,e))},uuidv7(e){return this.check(Za(qe,e))},nanoid(e){return this.check(Wa(Tu,e))},cuid(e){return this.check(Ja(ku,e))},cuid2(e){return this.check(Ka(Eu,e))},ulid(e){return this.check(Ga(Au,e))},base64(e){return this.check(rl(Pu,e))},base64url(e){return this.check(il(Nu,e))},xid(e){return this.check(Ya(Iu,e))},ksuid(e){return this.check(Xa(Su,e))},ipv4(e){return this.check(Qa(xu,e))},ipv6(e){return this.check(el(Cu,e))},cidrv4(e){return this.check(tl(Ru,e))},cidrv6(e){return this.check(nl(Ou,e))},e164(e){return this.check(ol(Mu,e))},datetime(e){return this.check(al(hu,e))},date(e){return this.check(ll(mu,e))},time(e){return this.check(ul(gu,e))},duration(e){return this.check(cl(yu,e))}});function l(e){return Da(fu,e)}var z=p("ZodStringFormat",(e,t)=>{M.init(e,t),di.init(e,t)}),hu=p("ZodISODateTime",(e,t)=>{js.init(e,t),z.init(e,t)}),mu=p("ZodISODate",(e,t)=>{Bs.init(e,t),z.init(e,t)}),gu=p("ZodISOTime",(e,t)=>{Fs.init(e,t),z.init(e,t)}),yu=p("ZodISODuration",(e,t)=>{qs.init(e,t),z.init(e,t)}),vu=p("ZodEmail",(e,t)=>{Is.init(e,t),z.init(e,t)}),bu=p("ZodGUID",(e,t)=>{Es.init(e,t),z.init(e,t)}),qe=p("ZodUUID",(e,t)=>{As.init(e,t),z.init(e,t)}),_u=p("ZodURL",(e,t)=>{Ps.init(e,t),z.init(e,t)}),wu=p("ZodEmoji",(e,t)=>{Ns.init(e,t),z.init(e,t)}),Tu=p("ZodNanoID",(e,t)=>{Ms.init(e,t),z.init(e,t)}),ku=p("ZodCUID",(e,t)=>{zs.init(e,t),z.init(e,t)}),Eu=p("ZodCUID2",(e,t)=>{$s.init(e,t),z.init(e,t)}),Au=p("ZodULID",(e,t)=>{Ls.init(e,t),z.init(e,t)}),Iu=p("ZodXID",(e,t)=>{Ds.init(e,t),z.init(e,t)}),Su=p("ZodKSUID",(e,t)=>{Us.init(e,t),z.init(e,t)}),xu=p("ZodIPv4",(e,t)=>{Zs.init(e,t),z.init(e,t)}),Cu=p("ZodIPv6",(e,t)=>{Vs.init(e,t),z.init(e,t)}),Ru=p("ZodCIDRv4",(e,t)=>{Ws.init(e,t),z.init(e,t)}),Ou=p("ZodCIDRv6",(e,t)=>{Ks.init(e,t),z.init(e,t)}),Pu=p("ZodBase64",(e,t)=>{Gs.init(e,t),z.init(e,t)}),Nu=p("ZodBase64URL",(e,t)=>{Xs.init(e,t),z.init(e,t)}),Mu=p("ZodE164",(e,t)=>{Qs.init(e,t),z.init(e,t)}),zu=p("ZodJWT",(e,t)=>{ta.init(e,t),z.init(e,t)}),pi=p("ZodNumber",(e,t)=>{yr.init(e,t),O.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Ur(e,n,r,i),e.isFinite=!0},zt({minValue:(e)=>{let{minimum:t,exclusiveMinimum:n}=q(e);return Math.max(t??Number.NEGATIVE_INFINITY,n??Number.NEGATIVE_INFINITY)},maxValue:(e)=>{let{maximum:t,exclusiveMaximum:n}=q(e);return Math.min(t??Number.POSITIVE_INFINITY,n??Number.POSITIVE_INFINITY)},isInt:(e)=>{let{isInt:t,multipleOf:n}=q(e);return!!t||!!n?.some(Number.isSafeInteger)},format:(e)=>q(e).format??null},{gt(e,t){return this.check(Cn(e,t))},gte(e,t){return this.check(Je(e,t))},min(e,t){return this.check(Je(e,t))},lt(e,t){return this.check(xn(e,t))},lte(e,t){return this.check(We(e,t))},max(e,t){return this.check(We(e,t))},int(e){return this.check(jn(e))},safe(e){return this.check(jn(e))},positive(e){return this.check(Cn(0,e))},nonnegative(e){return this.check(Je(0,e))},negative(e){return this.check(xn(0,e))},nonpositive(e){return this.check(We(0,e))},multipleOf(e,t){return this.check(Rn(e,t))},step(e,t){return this.check(Rn(e,t))},finite(){return this}}));function b(e){return dl(pi,e)}var $u=p("ZodNumberFormat",(e,t)=>{na.init(e,t),pi.init(e,t)});function jn(e){return pl($u,e)}var Lu=p("ZodBoolean",(e,t)=>{ra.init(e,t),O.init(e,t),e._zod.processJSONSchema=(n,r,i)=>jr(e,n,r,i)});function I(e){return fl(Lu,e)}var Du=p("ZodUnknown",(e,t)=>{ia.init(e,t),O.init(e,t),e._zod.processJSONSchema=(n,r,i)=>qr(e,n,r,i)});function j(){return hl(Du)}var Uu=p("ZodNever",(e,t)=>{oa.init(e,t),O.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Fr(e,n,r,i)});function ju(e){return ml(Uu,e)}var Bu=p("ZodVoid",(e,t)=>{sa.init(e,t),O.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Br(e,n,r,i)});function Fu(e){return gl(Bu,e)}var qu=p("ZodDate",(e,t)=>{aa.init(e,t),O.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Zr(e,n,r,i),e.min=(n,r)=>e.check(Je(n,r)),e.max=(n,r)=>e.check(We(n,r))},zt({minDate:(e)=>{let{minimum:t}=q(e);return t?new Date(t):null},maxDate:(e)=>{let{maximum:t}=q(e);return t?new Date(t):null}},{}));function rt(e){return yl(qu,e)}var Zu=p("ZodArray",(e,t)=>{ze(),la.init(e,t),O.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Gr(e,n,r,i),e.element=t.element},{min(e,t){return this.check(Xe(e,t))},nonempty(e){return this.check(Xe(1,e))},max(e,t){return this.check(Cr(e,t))},length(e,t){return this.check(Rr(e,t))},unwrap(){return this.element}});function E(e,t){return Cl(Zu,e,t)}var Hu=p("ZodObject",(e,t)=>{ze(),da.init(e,t),O.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Yr(e,n,r,i),co(e,"shape",(n)=>n._zod.def.shape,!1)},{keyof(){return A(Object.keys(this._zod.def.shape))},catchall(e){return this.clone(V(this._zod.def,{catchall:e}))},passthrough(){return this.clone(V(this._zod.def,{catchall:j()}))},loose(){return this.clone(V(this._zod.def,{catchall:j()}))},strict(){return this.clone(V(this._zod.def,{catchall:ju()}))},strip(){return this.clone(V(this._zod.def,{catchall:void 0}))},extend(e){return Qi(this,e)},safeExtend(e){return eo(this,e)},merge(e){return to(this,e)},pick(e){return Yi(this,e)},omit(e){return Xi(this,e)},partial(...e){return on(Vt,this,e[0])},exactPartial(...e){return on(mi,this,e[0],"exactPartial")},required(...e){return no(gi,this,e[0])}});function m(e,t){let n={type:"object",shape:e??{},...w(t)};return new Hu(n)}var fi=p("ZodUnion",(e,t)=>{_r.init(e,t),O.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Xr(e,n,r,i),e.options=t.options});function ge(e,t){return new fi({type:"union",options:e,...w(t)})}var Vu=p("ZodDiscriminatedUnion",(e,t)=>{fi.init(e,t),fa.init(e,t)});function Ht(e,t,n){return new Vu({type:"union",options:t,discriminator:e,...w(n)})}var Wu=p("ZodIntersection",(e,t)=>{ha.init(e,t),O.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Qr(e,n,r,i)});function Ju(e,t){return new Wu({type:"intersection",left:e,right:t})}var Ku=p("ZodTuple",(e,t)=>{ze(),wr.init(e,t),O.init(e,t),e._zod.processJSONSchema=(n,r,i)=>ei(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 Vt({type:"optional",innerType:t}))})}});function Gu(e,t,n){let r=t instanceof R;return new Ku({type:"tuple",items:e,rest:r?t:null,...w(r?n:t)})}var Bn=p("ZodRecord",(e,t)=>{ze(),ma.init(e,t),O.init(e,t),e._zod.processJSONSchema=(n,r,i)=>ti(e,n,r,i),e.keyType=t.keyType,e.valueType=t.valueType});function D(e,t,n){if(!t||!t._zod)return new Bn({type:"record",keyType:l(),valueType:e,...w(t)});return new Bn({type:"record",keyType:e,valueType:t,...w(n)})}var Ct=p("ZodEnum",(e,t)=>{ga.init(e,t),O.init(e,t),e._zod.processJSONSchema=(r,i,o)=>Hr(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 Ct({...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 Ct({...t,checks:[],...w(i),entries:o})}});function A(e,t){let n=Array.isArray(e)?Object.fromEntries(e.map((r)=>[r,r])):e;return new Ct({type:"enum",entries:n,...w(t)})}var Yu=p("ZodLiteral",(e,t)=>{ya.init(e,t),O.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Vr(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 L(e,t){return new Yu({type:"literal",values:Array.isArray(e)?e:[e],...w(t)})}var Xu=p("ZodTransform",(e,t)=>{ze(),va.init(e,t),O.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Kr(e,n,r,i),e._zod.parse=(n,r)=>{if(r.direction==="backward")throw new $t(e.constructor.name);n.addIssue=(o)=>{if(typeof o==="string")n.issues.push(Ne(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(Ne(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 hi(e){return new Xu({type:"transform",transform:e})}var Vt=p("ZodOptional",(e,t)=>{Tr.init(e,t),O.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Zt(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function Fn(e){return new Vt({type:"optional",innerType:e})}var mi=p("ZodExactOptional",(e,t)=>{ba.init(e,t),O.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Zt(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function Qu(e){return new mi({type:"optional",innerType:e})}var ec=p("ZodNullable",(e,t)=>{_a.init(e,t),O.init(e,t),e._zod.processJSONSchema=(n,r,i)=>ni(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function qn(e){return new ec({type:"nullable",innerType:e})}var tc=p("ZodDefault",(e,t)=>{wa.init(e,t),O.init(e,t),e._zod.processJSONSchema=(n,r,i)=>oi(e,n,r,i),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function nc(e,t){return new tc({type:"default",innerType:e,get defaultValue(){return typeof t==="function"?t():Xn(t)}})}var rc=p("ZodPrefault",(e,t)=>{Ta.init(e,t),O.init(e,t),e._zod.processJSONSchema=(n,r,i)=>si(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function ic(e,t){return new rc({type:"prefault",innerType:e,get defaultValue(){return typeof t==="function"?t():Xn(t)}})}var gi=p("ZodNonOptional",(e,t)=>{ka.init(e,t),O.init(e,t),e._zod.processJSONSchema=(n,r,i)=>ri(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function oc(e,t){return new gi({type:"nonoptional",innerType:e,...w(t)})}var sc=p("ZodCatch",(e,t)=>{Ea.init(e,t),O.init(e,t),e._zod.processJSONSchema=(n,r,i)=>ai(e,n,r,i),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function ac(e,t){return new sc({type:"catch",innerType:e,catchValue:typeof t==="function"?t:fo(t)})}var yi=p("ZodPipe",(e,t)=>{kr.init(e,t),O.init(e,t),e._zod.processJSONSchema=(n,r,i)=>li(e,n,r,i),e.in=t.in,e.out=t.out});function Zn(e,t){return new yi({type:"pipe",in:e,out:t})}var lc=p("ZodPreprocess",(e,t)=>{yi.init(e,t),Aa.init(e,t)}),uc=p("ZodReadonly",(e,t)=>{Ia.init(e,t),O.init(e,t),e._zod.processJSONSchema=(n,r,i)=>ui(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function cc(e){return new uc({type:"readonly",innerType:e})}var dc=p("ZodPromise",(e,t)=>{xa.init(e,t),O.init(e,t),e._zod.processJSONSchema=(n,r,i)=>ci(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function vt(e){return new dc({type:"promise",innerType:e})}var pc=p("ZodFunction",(e,t)=>{Sa.init(e,t),O.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Jr(e,n,r,i)});function Ze(e){return new pc({type:"function",input:Array.isArray(e?.input)?Gu(e?.input):e?.input??E(j()),output:e?.output??j()})}var vi=p("ZodCustom",(e,t)=>{Ca.init(e,t),O.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Wr(e,n,r,i)});function J(e,t){return Rl(vi,e??(()=>!0),t)}function fc(e,t={}){return Ol(vi,e,t)}function hc(e,t){return Pl(e,t)}function bi(e,t){return new lc({type:"pipe",in:hi(e),out:t})}var _i=["none","minimal","low","medium","high","xhigh","max"],mc=A(_i),gc=mc.exclude(["none"]),yc=A([..._i,"default"]).nullable(),vc=Ht("type",[m({type:L("toggle")}).strict(),m({type:L("effort"),values:E(yc)}).strict(),m({type:L("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"]})]),bc=A(["default","openai-responses","r1"]);var _c=A(["images","video","tools","streaming","prompt-cache","reasoning","reasoning-effort","computer-use","global-endpoint","structured_output","temperature","files"]),wc=A(["active","preview","deprecated","legacy"]),Tc=m({input:b().optional(),output:b().optional(),cacheWrite:b().optional(),cacheRead:b().optional()}),kc=m({maxBudget:b().optional(),outputPrice:b().optional(),thinkingLevel:A(["low","high"]).optional()}),Ec=m({reasoningDefaultOn:I().optional(),apiProtocol:A(["openai-chat","openai-responses","anthropic","gemini"]).optional()}).catchall(j()),Hn=A(["text","image","audio","video","pdf"]),Ac=m({input:E(Hn),output:E(Hn)});var Ic=A(["language","image-generation","speech-generation","video-generation","transcription","realtime"]);var Sc=A(["batch","streaming"]);var wi=m({id:l(),name:l().optional(),description:l().optional(),maxTokens:b().optional(),contextWindow:b().optional(),maxInputTokens:b().optional(),capabilities:E(_c).optional(),operation:Ic.optional(),operationModes:E(Sc).optional(),modalities:Ac.optional(),reasoningOptions:E(vc).optional(),apiFormat:bc.optional(),systemRole:A(["system","developer"]).optional(),temperature:b().optional(),pricing:Tc.optional(),thinkingConfig:kc.optional(),status:wc.optional(),deprecationNotice:l().optional(),replacedBy:l().optional(),releaseDate:l().optional(),deprecationDate:l().optional(),family:l().optional(),metadata:Ec.optional()});var Ti="NOT a tool or system failure. Clarify with user before proceeding.",xc=m({id:l(),name:l(),execution:A(["client","provider"]).optional(),input:j(),output:j(),error:l().optional(),durationMs:b(),startedAt:rt(),endedAt:rt()}),Cc=A(["completed","max_iterations","aborted","mistake_limit","error"]),Rc=m({inputTokens:b(),outputTokens:b(),cacheReadTokens:b().optional(),cacheWriteTokens:b().optional(),totalCost:b().optional()}),sp=m({text:l(),usage:Rc,messages:E(J()),toolCalls:E(xc),iterations:b(),finishReason:Cc,model:m({id:l(),provider:l(),info:wi.optional()}),startedAt:rt(),endedAt:rt(),durationMs:b()}),ap=m({distinctId:l().optional(),sessionId:l().optional(),providerId:l(),modelId:l(),apiKey:l().optional(),baseUrl:l().url().optional(),headers:D(l(),l()).optional(),knownModels:D(l(),wi).optional(),providerConfig:j().optional(),initialMessages:E(J()).optional(),systemPrompt:l(),tools:E(J()),modelTools:E(J()).optional(),maxIterations:b().positive().optional(),maxParallelToolCalls:b().int().positive().default(8),maxTokensPerTurn:b().positive().optional(),temperature:b().nonnegative().optional(),apiTimeoutMs:b().positive().default(180000),userFileContentLoader:Ze().input([l()]).output(vt(l())).optional(),toolContextMetadata:D(l(),j()).optional(),execution:m({maxConsecutiveMistakes:b().int().positive().optional(),reminderAfterIterations:b().nonnegative().optional(),reminderText:l().optional(),loopDetection:ge([L(!1),m({softThreshold:b().int().positive().optional(),hardThreshold:b().int().positive().optional()})]).optional()}).optional(),reasoningEffort:gc.optional(),thinkingBudgetTokens:b().positive().optional(),thinking:I().optional(),onEvent:Ze().input([J()]).output(Fu()).optional(),hooks:J().optional(),parentAgentId:l().optional(),extensions:E(J()).optional(),hookErrorMode:A(["ignore","throw"]).default("ignore"),toolPolicies:D(l(),m({enabled:I().optional(),autoApprove:I().optional()})).optional(),requestToolApproval:Ze().input([m({sessionId:l(),agentId:l(),conversationId:l(),iteration:b(),toolCallId:l(),toolName:l(),input:j(),policy:m({enabled:I().optional(),autoApprove:I().optional()}).default({})})]).output(ge([m({approved:I(),reason:l().optional()}),vt(m({approved:I(),reason:l().optional()}))])).optional(),onConsecutiveMistakeLimitReached:Ze().input([m({iteration:b().int().positive(),consecutiveMistakes:b().int().positive(),maxConsecutiveMistakes:b().int().positive(),reason:A(["api_error","invalid_tool_call","tool_execution_failed"]),details:l().optional()})]).output(ge([m({action:L("continue"),guidance:l().optional()}),m({action:L("stop"),reason:l().optional()}),vt(ge([m({action:L("continue"),guidance:l().optional()}),m({action:L("stop"),reason:l().optional()})]))])).optional(),logger:J().optional(),extensionContext:J().optional(),abortSignal:J().optional()}),Oc=A(["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"]),Pc=m({id:l().optional(),label:l().optional(),role:l().optional(),participantKey:l().optional(),participantLabel:l().optional(),platformUserId:l().optional(),metadata:D(l(),j()).optional()}),Nc=m({source:l(),sourceEvent:l(),threadId:l(),channelId:l(),isDM:I(),sessionId:l().optional(),workspaceRoot:l().optional(),metadata:D(l(),j()).optional()}),lp=m({actor:Pc,context:Nc,payload:D(l(),j()).optional()}),up=m({action:A(["allow","deny"]).default("allow"),message:l().optional(),reason:l().optional(),metadata:D(l(),j()).optional()}),cp=m({adapter:l(),botUserName:l().optional(),event:Oc,payload:D(l(),j()),ts:l()});var Mc=["hooks","tools","commands","rules","skills","messageBuilders","providers","automationEvents","mcp"],dp=new Set(Mc);var xe={CLINE_PASS:"ext-cline-pass",CODE_CLOUD_AGENTS:"code-cloud-agents",CODE_ONBOARDING_GITHUB:"code-onboarding-github",CLINE_COMPOSIO_BETA:"CLINE_COMPOSIO_BETA"},pp={[xe.CLINE_PASS]:!1,[xe.CODE_CLOUD_AGENTS]:!1,[xe.CODE_ONBOARDING_GITHUB]:!1,[xe.CLINE_COMPOSIO_BETA]:!1},fp=Object.values(xe),zc=A(["agent_start","agent_resume","agent_abort","agent_end","agent_error","tool_call","tool_result","prompt_submit","pre_compact","session_shutdown"]),fe=D(l(),l()),$c=m({toolName:l(),parameters:fe}),Lc=m({toolName:l(),parameters:fe,result:l(),success:I(),executionTimeMs:b()}),Dc=m({prompt:l(),attachments:E(l())}),Uc=m({taskMetadata:fe}),jc=m({taskMetadata:fe,previousState:fe}),Bc=m({taskMetadata:fe}),Fc=m({taskMetadata:fe}),qc=m({taskId:l(),ulid:l(),contextSize:b(),compactionStrategy:l(),previousApiReqIndex:b(),tokensIn:b(),tokensOut:b(),tokensInCache:b(),tokensOutCache:b(),deletedRangeStart:b(),deletedRangeEnd:b(),contextJsonPath:l(),contextRawPath:l()}),hp=m({clineVersion:l(),hookName:zc,timestamp:l(),taskId:l(),sessionContext:m({rootSessionId:l().optional(),hookLogPath:l().optional()}).optional(),workspaceRoots:E(l()),workspaceInfo:J().optional(),userId:l(),agent_id:l(),parent_agent_id:l().nullable(),iteration:b().optional(),reason:l().optional(),tool_call:m({id:l(),name:l(),input:j()}).optional(),tool_result:J().optional(),turn:j().optional(),error:m({name:l(),message:l(),stack:l().optional()}).optional(),preToolUse:$c.optional(),postToolUse:Lc.optional(),userPromptSubmit:Dc.optional(),taskStart:Uc.optional(),taskResume:jc.optional(),taskCancel:Bc.optional(),taskComplete:Fc.optional(),preCompact:qc.optional()}).passthrough();var Zc=["readFile","search","bash","webFetch","editor","applyPatch","skills","askQuestion","submit"],mp=new Set(Zc);var Hc=A(["image","audio","video","file"]),Vc=Ht("type",[m({type:L("base64"),data:l().min(1)}),m({type:L("url"),url:l().url().refine((e)=>{let t=new URL(e).protocol;return t==="http:"||t==="https:"},"Generated media URLs must use HTTP or HTTPS")}),m({type:L("artifact"),artifactId:l().min(1)})]);function Wc(e){if(e.startsWith("image/"))return"image";if(e.startsWith("audio/"))return"audio";if(e.startsWith("video/"))return"video";return"file"}var gp=m({id:l().min(1),modality:Hc,mediaType:l().min(1),source:Vc,name:l().min(1).optional(),sizeBytes:b().int().nonnegative().optional()}).refine((e)=>Wc(e.mediaType)===e.modality,{message:"Generated media modality must match its media type",path:["modality"]});function Vn(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function Wt(e,t){if(!e&&!t)return;let n=e?.metadata,r=t?.metadata,i={...e??{},...t??{}};if(Vn(n)&&Vn(r))i.metadata={...n,...r};return i}function ki(e){return Math.max(1,Math.ceil(e/3))}function ye(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function Jc(e){let t=e.type;if(typeof t==="string")return[t];return Array.isArray(t)?t.filter((n)=>typeof n==="string"):[]}function Rt(e,t){if(Jc(e).includes(t))return!0;for(let n of["anyOf","oneOf","allOf"]){let r=e[n];if(Array.isArray(r)&&r.some((i)=>ye(i)&&Rt(i,t)))return!0}return!1}function Kc(e,t){if(typeof e!=="string")return e;let n=e.trim(),r=Rt(t,"array"),i=Rt(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(ye(o))return i?o:e;return e}catch{return e}}function it(e,t){let n=Kc(e,t);if(Array.isArray(n)){let s=t.items;if(!ye(s))return n;let a=!1,u=n.map((c)=>{let d=it(c,s);return a||=d!==c,d});return a?u:n}if(!ye(n))return n;let r=t.properties;if(!ye(r))return n;let i=!1,o={...n};for(let[s,a]of Object.entries(r)){if(!(s in n)||!ye(a))continue;let u=it(n[s],a);if(u!==n[s])o[s]=u,i=!0}return i?o:n}function Ei(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}function Z(e){let t=e?.trim();return t?t:void 0}function Gc(e){return Xl(e)}var Ai=`# 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 u=e.external.registry.get(s[0])?.id;if(t!==s[0]&&u){o(s);continue}}if(e.metadataRegistry.get(s[0])?.id){o(s);continue}if(a.cycle){o(s);continue}if(a.count>1){if(e.reused==="ref")o(s)}}if(e.external)e.sharedDefsExtractedFor=e.external}function Or(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;Or(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 Pr=new Set(["type","properties","required","additionalProperties"]),Pn=["oneOf","anyOf"];function Nn(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 It(e){let t=[];for(let o of e){if(typeof o!=="object"||o.type!=="object")return null;for(let s in o)if(!Pr.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 c of t){let d=c.properties?.[s]??Nn(c);if(d===null||d===void 0)continue;if(!a.some((f)=>JSON.stringify(f)===JSON.stringify(d)))a.push(d)}let u=a.length===1?a[0]:It(a)??{allOf:a};te(n,s,u)}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=Nn(s);if(a&&!o.some((u)=>JSON.stringify(u)===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 Ml(e){let t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(let i of Pr)if(i in e)return;let n=t.filter((i)=>Pn.some((o)=>Array.isArray(i[o]))),r=null;if(!n.length)r=It(t);else{let i=n[0],o=Pn.find((u)=>Array.isArray(i[u]));if(Object.keys(i).length!==1)return;let s=t.filter((u)=>u!==i),a=i[o].map((u)=>It([...s,u]));if(a.some((u)=>!u))return;r={[o]:a}}if(!r)return;delete e.allOf,Oe(e,r)}function tt(e,t){let n=e.seen.get(t);if(!n)throw Error("Unprocessed schema. This is a bug in Zod.");let r=(a)=>{let u=e.seen.get(a);if(u.ref===null)return;let c=u.def??u.schema,d={...c},f=u.ref;if(u.ref=null,f){r(f);let g=e.seen.get(f),v=g.schema;if(v.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"))c.allOf=c.allOf??[],c.allOf.push(v);else Oe(c,v);if(Oe(c,d),a._zod.parent===f)for(let _ in c){if(_==="$ref"||_==="allOf")continue;if(!(_ in d))delete c[_]}if(v.$ref&&g.def)for(let _ in c){if(_==="$ref"||_==="allOf")continue;if(_ in g.def&&JSON.stringify(c[_])===JSON.stringify(g.def[_]))delete c[_]}}let h=a._zod.parent;if(h&&h!==f){r(h);let g=e.seen.get(h);if(g?.schema.$ref){if(c.$ref=g.schema.$ref,g.def)for(let v in c){if(v==="$ref"||v==="allOf")continue;if(v in g.def&&JSON.stringify(c[v])===JSON.stringify(g.def[v]))delete c[v]}}}e.override({zodSchema:a,jsonSchema:c,path:u.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())Or(a[1].def??a[1].schema);for(let a of e.deferred)a();if(e.intersections.length){let a=new Map;for(let u of e.seen.values())for(let c of[u.schema,u.def]){let d=c?.allOf;if(!Array.isArray(d))continue;let f=a.get(d);if(f)f.push(c);else a.set(d,[c])}for(let u of e.intersections)for(let c of a.get(u)??[])Ml(c)}}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)}Oe(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 u=a[1];if(u.def&&u.defId){if(u.def.id===u.defId)delete u.def.id;te(s,u.defId,u.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:nt(t,"input",e.processors),output:nt(t,"output",e.processors)}},enumerable:!1,writable:!1}),a}catch(a){throw Error("Error converting schema to JSON.")}}function F(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 F(r.element,n);if(r.type==="set")return F(r.valueType,n);if(r.type==="lazy")return F(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 F(r.innerType,n);if(r.type==="intersection")return F(r.left,n)||F(r.right,n);if(r.type==="record"||r.type==="map")return F(r.keyType,n)||F(r.valueType,n);if(r.type==="pipe"){if(e._zod.traits.has("$ZodCodec"))return!0;return F(r.in,n)||F(r.out,n)}if(r.type==="object"){for(let i in r.shape)if(F(r.shape[i],n))return!0;return!1}if(r.type==="union"){for(let i of r.options)if(F(i,n))return!0;return!1}if(r.type==="tuple"){for(let i of r.items)if(F(i,n))return!0;if(r.rest&&F(r.rest,n))return!0;return!1}return!1}var zl=(e,t={})=>(n)=>{let r=Qe({...n,processors:t});return P(e,r),et(r,e),tt(r,e)},nt=(e,t,n={})=>(r)=>{let{libraryOptions:i,target:o}=r??{},s=Qe({...i??{},target:o,io:t,processors:n});return P(e,s),et(s,e),tt(s,e)},we=(e,t,n)=>{if(e[t]===void 0||n>e[t])e[t]=n},Te=(e,t,n)=>{if(e[t]===void 0||n<e[t])e[t]=n},Mn=(e,t)=>{we(e,"minimum",t),Te(e,"maximum",t)},Nr=(e,t)=>{if(e.multipleOf??(e.multipleOf=[]),!e.multipleOf.includes(t))e.multipleOf.push(t)},Mr=(e,t)=>{e.patterns??(e.patterns=new Set),e.patterns.add(t)},zr=(e,t)=>{e.mime=e.mime?e.mime.filter((n)=>t.includes(n)):[...t]},$r=(e,t)=>{if(e.format=t,t.includes("int"))e.isInt=!0},zn=(e,t)=>we(e,"minimum",t.minimum),$n=(e,t)=>Te(e,"maximum",t.maximum),Ln=(e)=>(t,n)=>{$r(t,n.format);let[r,i]=e[n.format];we(t,"minimum",r),Te(t,"maximum",i)},$l={greater_than:(e,t)=>we(e,t.inclusive?"minimum":"exclusiveMinimum",t.value),less_than:(e,t)=>Te(e,t.inclusive?"maximum":"exclusiveMaximum",t.value),multiple_of:(e,t)=>Nr(e,t.value),number_format:Ln(er),bigint_format:Ln(Gi),min_length:zn,max_length:$n,length_equals:(e,t)=>Mn(e,t.length),min_size:zn,max_size:$n,size_equals:(e,t)=>Mn(e,t.size),string_format:(e,t)=>{if($r(e,t.format),t.pattern)Mr(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)=>zr(e,t.mime)};function q(e){let t={},n=e._zod.def,r=e._zod.traits.has("$ZodCheck")?[e,...n.checks??[]]:n.checks??[];for(let o of r)$l[o._zod.def.check]?.(t,o._zod.def);let i=e._zod.bag;if(i.minimum!==void 0)we(t,"minimum",i.minimum);if(i.exclusiveMinimum!==void 0)we(t,"exclusiveMinimum",i.exclusiveMinimum);if(i.maximum!==void 0)Te(t,"maximum",i.maximum);if(i.exclusiveMaximum!==void 0)Te(t,"exclusiveMaximum",i.exclusiveMaximum);if(i.multipleOf!==void 0)Nr(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)zr(t,i.mime);for(let o of i.patterns??[])Mr(t,o);return t}var Ll={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},Dl=new Map([[gr,Yo],[Ft,Xo]]),Lr=(e)=>Dl.get(e)??e,Dr=(e,t,n,r)=>{let i=n;i.type="string";let{minimum:o,maximum:s,format:a,patterns:u,contentEncoding:c,laxFormat:d}=q(e);if(typeof o==="number")i.minLength=o;if(typeof s==="number")i.maxLength=s;if(a){if(i.format=Ll[a]??a,i.format==="")delete i.format;if(a==="time"||d)delete i.format}if(c)i.contentEncoding=c;if(u&&u.size>0){let f=[...u].map(Lr);if(f.length===1)i.pattern=f[0].source;else if(f.length>1)i.allOf=[...f.map((h)=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:h.source}))]}},Ur=(e,t,n,r)=>{let i=n,{minimum:o,maximum:s,multipleOf:a,exclusiveMaximum:u,exclusiveMinimum:c,isInt:d}=q(e);i.type=d?"integer":"number";let f=typeof c==="number"&&c>=(o??Number.NEGATIVE_INFINITY),h=typeof u==="number"&&u<=(s??Number.POSITIVE_INFINITY),g=t.target==="draft-04"||t.target==="openapi-3.0";if(f)if(g)i.minimum=c,i.exclusiveMinimum=!0;else i.exclusiveMinimum=c;else if(typeof o==="number")i.minimum=o;if(h)if(g)i.maximum=u,i.exclusiveMaximum=!0;else i.exclusiveMaximum=u;else if(typeof s==="number")i.maximum=s;if(a){let v=new Set;for(let k of a)if(Number.isFinite(k)&&k!==0)v.add(Math.abs(k));else B(e,t,i,r,`A multipleOf divisor of ${k} cannot be represented in JSON Schema`);let[_,...S]=v;if(_!==void 0)i.multipleOf=_;if(S.length)i.allOf=[...i.allOf??[],...S.map((k)=>({multipleOf:k}))]}},jr=(e,t,n,r)=>{n.type="boolean"},Ul=(e,t,n,r)=>{B(e,t,n,r,"BigInt cannot be represented in JSON Schema")},jl=(e,t,n,r)=>{B(e,t,n,r,"Symbols cannot be represented in JSON Schema")},Bl=(e,t,n,r)=>{if(t.target==="openapi-3.0")n.type="string",n.nullable=!0,n.enum=[null];else n.type="null"},Fl=(e,t,n,r)=>{B(e,t,n,r,"Undefined cannot be represented in JSON Schema")},Br=(e,t,n,r)=>{B(e,t,n,r,"Void cannot be represented in JSON Schema")},Fr=(e,t,n,r)=>{n.not={}},ql=(e,t,n,r)=>{},qr=(e,t,n,r)=>{},Zr=(e,t,n,r)=>{B(e,t,n,r,"Date cannot be represented in JSON Schema")},Hr=(e,t,n,r)=>{let i=e._zod.def,o=wt(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},Vr=(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(B(e,t,n,r,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof s==="bigint"){if(B(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}},Zl=(e,t,n,r)=>{B(e,t,n,r,"NaN cannot be represented in JSON Schema")},Hl=(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},Vl=(e,t,n,r)=>{let i=n;i.type="string",i.format="binary",i.contentEncoding="binary";let{minimum:o,maximum:s,mime:a}=q(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((u)=>({contentMediaType:u}))},Wl=(e,t,n,r)=>{n.type="boolean"},Wr=(e,t,n,r)=>{B(e,t,n,r,"Custom types cannot be represented in JSON Schema")},Jr=(e,t,n,r)=>{B(e,t,n,r,"Function types cannot be represented in JSON Schema")},Kr=(e,t,n,r)=>{B(e,t,n,r,"Transforms cannot be represented in JSON Schema")},Jl=(e,t,n,r)=>{B(e,t,n,r,"Map cannot be represented in JSON Schema")},Kl=(e,t,n,r)=>{B(e,t,n,r,"Set cannot be represented in JSON Schema")},Gr=(e,t,n,r)=>{let i=n,o=e._zod.def,{minimum:s,maximum:a}=q(e);if(typeof s==="number")i.minItems=s;if(typeof a==="number")i.maxItems=a;i.type="array",i.items=P(o.element,t,{...r,path:[...r.path,"items"]})};function Me(e){let t=e._zod.def;if(t.type==="pipe"&&t.in._zod.traits.has("$ZodTransform"))return Me(t.out);if(t.type==="catch")return Me(t.innerType);return e._zod.optin}var Yr=(e,t,n,r)=>{let i=n,o=e._zod.def,s=o.shape;if(Object.getOwnPropertySymbols(s).length&&B(e,t,i,r,"Symbol keys cannot be represented in JSON Schema"))return;i.type="object",i.properties={};for(let u in s)te(i.properties,u,P(s[u],t,{...r,path:[...r.path,"properties",u]}));let a=[];for(let u of Object.keys(s)){let c=o.shape[u];if(t.io==="input"?Me(c)===void 0:c._zod.optout===void 0)a.push(u)}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=P(o.catchall,t,{...r,path:[...r.path,"additionalProperties"]})},Xr=(e,t,n,r)=>{let i=e._zod.def,o=i.inclusive===!1,s=i.options.map((a,u)=>P(a,t,{...r,path:[...r.path,o?"oneOf":"anyOf",u]}));if(o)n.oneOf=s;else n.anyOf=s},Qr=(e,t,n,r)=>{let i=e._zod.def,o=P(i.left,t,{...r,path:[...r.path,"allOf",0]}),s=P(i.right,t,{...r,path:[...r.path,"allOf",1]}),a=(c)=>("allOf"in c)&&Object.keys(c).length===1,u=[...a(o)?o.allOf:[o],...a(s)?s.allOf:[s]];n.allOf=u,t.intersections.push(u)},ei=(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",u=o.items.map((_,S)=>P(_,t,{...r,path:[...r.path,s,S]})),c=o.rest?P(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 _=o.items[d-1];if(!(t.io==="input"?Me(_)!==void 0:_._zod.optout==="optional"))break;d--}let f=o.items.length,h=!o.rest;if(t.target==="draft-2020-12"){if(i.prefixItems=u,h)i.items=!1;else if(c)i.items=c;if(d>0)i.minItems=d;if(h)i.maxItems=f}else if(t.target==="openapi-3.0"){if(i.items={anyOf:u},c)i.items.anyOf.push(c);if(d>0)i.minItems=d;if(h)i.maxItems=f}else{if(i.items=u,h)i.additionalItems=!1;else if(c)i.additionalItems=c;if(d>0)i.minItems=d;if(h)i.maxItems=f}let{minimum:g,maximum:v}=q(e);if(typeof g==="number")i.minItems=g;if(typeof v==="number")i.maxItems=v};function St(e,t,n){if(t.$ref){if(n.has(t))return t;n.add(t);let v=e.get(t)?.def;if(!v)return t;let _=St(e,v,n);return _===v?t:_}for(let v of["anyOf","oneOf"]){let _=t[v];if(!Array.isArray(_))continue;let S=_.map((k)=>St(e,k,n));if(S.some((k,U)=>k!==_[U]))t={...t,[v]:S}}let r=Array.isArray(t.type)?t.type:[t.type],i=!r.includes("string")&&r.some((v)=>v==="number"||v==="integer"),o=t.enum??(t.const!==void 0?[t.const]:void 0);if(!i&&!o?.some((v)=>typeof v==="number"))return t;let{minimum:s,maximum:a,exclusiveMinimum:u,exclusiveMaximum:c,multipleOf:d,format:f,id:h,...g}=t;if(g.enum)g.enum=g.enum.map((v)=>typeof v==="number"?String(v):v);else if(typeof g.const==="number")g.const=String(g.const);if(!i)return g;if(g.type="string",!o)g.pattern=(r.includes("number")?Ut:ss).source;return g}var xt=new WeakMap;function Gl(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 xt.get(e)??[]){let i=e.seen.get(r),o=(i?.def??i?.schema)?.propertyNames;if(!o||o===!0||n.has(o))continue;let s=St(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 ti=(e,t,n,r)=>{let i=n,o=e._zod.def;i.type="object";let s=o.keyType,a=q(s).patterns;if(o.mode==="loose"&&a&&a.size>0){let d=P(o.valueType,t,{...r,path:[...r.path,"patternProperties","*"]});i.patternProperties={};for(let f of a)te(i.patternProperties,Lr(f).source,d)}else{if(t.target==="draft-07"||t.target==="draft-2020-12"){i.propertyNames=P(o.keyType,t,{...r,path:[...r.path,"propertyNames"]});let d=xt.get(t);if(!d)d=[],xt.set(t,d),t.deferred.push(()=>Gl(t));d.push(e)}i.additionalProperties=P(o.valueType,t,{...r,path:[...r.path,"additionalProperties"]})}let u=s._zod.values,c=t.io==="input"&&Me(o.valueType)!==void 0;if(u&&!o.partial&&!c){let d=[...u].filter((f)=>typeof f==="string"||typeof f==="number");if(d.length>0)i.required=d.map(String)}},ni=(e,t,n,r)=>{let i=e._zod.def,o=P(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"}]},ri=(e,t,n,r)=>{let i=e._zod.def;P(i.innerType,t,r);let o=t.seen.get(e);o.ref=i.innerType},qt=Symbol();function ii(e,t,n,r,i){let o=!1,s=JSON.stringify(e,(a,u)=>{if(typeof u!=="bigint")return u;return o=!0,null});if(!o)return JSON.parse(s);return B(t,n,r,i,"BigInt defaults cannot be represented in JSON Schema"),qt}var oi=(e,t,n,r)=>{let i=e._zod.def;P(i.innerType,t,r);let o=t.seen.get(e);o.ref=i.innerType;let s=ii(i.defaultValue,e,t,n,r);if(s!==qt)n.default=s},si=(e,t,n,r)=>{let i=e._zod.def;P(i.innerType,t,r);let o=t.seen.get(e);if(o.ref=i.innerType,t.io!=="input")return;let s=ii(i.defaultValue,e,t,n,r);if(s!==qt)n._prefault=s},ai=(e,t,n,r)=>{let i=e._zod.def;P(i.innerType,t,r);let o=t.seen.get(e);o.ref=i.innerType;let s;try{s=i.catchValue(void 0)}catch{B(e,t,n,r,"Dynamic catch values are not supported in JSON Schema");return}n.default=s},li=(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;P(s,t,r);let a=t.seen.get(e);a.ref=s},ui=(e,t,n,r)=>{let i=e._zod.def;P(i.innerType,t,r);let o=t.seen.get(e);o.ref=i.innerType,n.readOnly=!0},ci=(e,t,n,r)=>{let i=e._zod.def;P(i.innerType,t,r);let o=t.seen.get(e);o.ref=i.innerType},Zt=(e,t,n,r)=>{let i=e._zod.def;P(i.innerType,t,r);let o=t.seen.get(e);o.ref=i.innerType},Yl=(e,t,n,r)=>{let i=e._zod.innerType;P(i,t,r);let o=t.seen.get(e);o.ref=i},Dn={string:Dr,number:Ur,boolean:jr,bigint:Ul,symbol:jl,null:Bl,undefined:Fl,void:Br,never:Fr,any:ql,unknown:qr,date:Zr,enum:Hr,literal:Vr,nan:Zl,template_literal:Hl,file:Vl,success:Wl,custom:Wr,function:Jr,transform:Kr,map:Jl,set:Kl,array:Gr,object:Yr,union:Xr,intersection:Qr,tuple:ei,record:ti,nullable:ni,nonoptional:ri,default:oi,prefault:si,catch:ai,pipe:li,readonly:ui,promise:ci,optional:Zt,lazy:Yl};function Xl(e,t){if("_idmap"in e){let r=e,i=Qe({...t,processors:Dn}),o={};for(let u of r._idmap.entries()){let[c,d]=u;P(d,i)}let s={},a={registry:r,uri:t?.uri,defs:o};i.external=a;for(let u of r._idmap.entries()){let[c,d]=u;et(i,d),te(s,c,tt(i,d))}if(Object.keys(o).length>0){let u=i.target==="draft-2020-12"?"$defs":"definitions";s.__shared={[u]:o}}return{schemas:s}}let n=Qe({...t,processors:Dn});return P(e,n),et(n,e),tt(n,e)}var Un=new WeakSet([Object.prototype,Error.prototype]);function Fe(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 Ql=(e,t)=>{vo.init(e,t),e.name="ZodError";let n=Object.getPrototypeOf(e);if(Un.has(n))return;Un.add(n),Fe(n,"format",(r)=>(i)=>wo(r,i)),Fe(n,"flatten",(r)=>(i)=>_o(r,i)),Fe(n,"addIssue",(r)=>(i)=>{r.issues.push(i),r.message=JSON.stringify(r.issues,Tt,2)}),Fe(n,"addIssues",(r)=>(i)=>{r.issues.push(...i),r.message=JSON.stringify(r.issues,Tt,2)}),Object.defineProperty(n,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}})},G=p("ZodError",Ql,void 0,{Parent:Error}),eu=lt(G),tu=ut(G),nu=Lt(G),ru=Dt(G),iu=So(G),ou=xo(G),su=Co(G),au=Ro(G),lu=Oo(G),uu=Po(G),cu=No(G),du=Mo(G);function pu(){if(!K.localeError)ee($a())}function ze(){if(!K.memoizer)ee({memoizer:Na()})}var O=p("ZodType",(e,t)=>(pu(),R.init(e,t),e.def=t,e.type=t.type,e),{check(...e){let t=this.def;return this.clone(V(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 ue(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(fc(e,t))},superRefine(e,t){return this.check(hc(e,t))},overwrite(e){return this.check(ke(e))},optional(){return Fn(this)},exactOptional(){return Qu(this)},nullable(){return qn(this)},nullish(){return Fn(qn(this))},nonoptional(e){return oc(this,e)},array(){return E(this)},or(e){return ge([this,e])},and(e){return Ju(this,e)},transform(e){return Zn(this,hi(e))},default(e){return nc(this,e)},prefault(e){return ic(this,e)},catch(e){return ac(this,e)},pipe(e){return Zn(this,e)},readonly(){return cc(this)},describe(e){let t=this.clone();return Se.add(t,{description:e}),t},meta(...e){if(e.length===0)return Se.get(this);let t=this.clone();return Se.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 nr(this,"~standard",{...dr(this),jsonSchema:{input:nt(this,"input"),output:nt(this,"output")}})},set "~standard"(e){le(this,"~standard",e)},parse:function e(t,n){return eu(this,t,n,{callee:e})},parseAsync:async function e(t,n){return await tu(this,t,n,{callee:e})},safeParse(e,t){return nu(this,e,t)},async safeParseAsync(e,t){return ru(this,e,t)},get spa(){return this?.safeParseAsync},set spa(e){le(this,"spa",e)},validate(e,t){return Eo(this,e,t)},validateAsync(e,t){return Io(this,e,t)},encode:function e(t,n){return iu(this,t,n,{callee:e})},decode:function e(t,n){return ou(this,t,n,{callee:e})},encodeAsync:async function e(t,n){return await su(this,t,n,{callee:e})},decodeAsync:async function e(t,n){return await au(this,t,n,{callee:e})},safeEncode(e,t){return lu(this,e,t)},safeDecode(e,t){return uu(this,e,t)},async safeEncodeAsync(e,t){return cu(this,e,t)},async safeDecodeAsync(e,t){return du(this,e,t)},toJSONSchema(e){return zl(this,{})(e)},get description(){return Se.get(this)?.description},get _def(){return this._zod.def}}),di=p("_ZodString",(e,t)=>{Bt.init(e,t),O.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Dr(e,n,r,i)},zt({format:(e)=>q(e).format??null,minLength:(e)=>q(e).minimum??null,maxLength:(e)=>q(e).maximum??null},{regex(...e){return this.check(vl(...e))},includes(...e){return this.check(wl(...e))},startsWith(...e){return this.check(Tl(...e))},endsWith(...e){return this.check(kl(...e))},min(...e){return this.check(Xe(...e))},max(...e){return this.check(Cr(...e))},length(...e){return this.check(Rr(...e))},nonempty(...e){return this.check(Xe(1,...e))},lowercase(e){return this.check(bl(e))},uppercase(e){return this.check(_l(e))},trim(){return this.check(Al())},normalize(...e){return this.check(El(...e))},toLowerCase(){return this.check(Il())},toUpperCase(){return this.check(Sl())},slugify(){return this.check(xl())}})),fu=p("ZodString",(e,t)=>{Bt.init(e,t),di.init(e,t)},{email(e){return this.check(Ua(vu,e))},url(e){return this.check(Ha(_u,e))},jwt(e){return this.check(sl(zu,e))},emoji(e){return this.check(Va(wu,e))},guid(e){return this.check(ja(bu,e))},uuid(e){return this.check(Ba(qe,e))},uuidv4(e){return this.check(Fa(qe,e))},uuidv6(e){return this.check(qa(qe,e))},uuidv7(e){return this.check(Za(qe,e))},nanoid(e){return this.check(Wa(Tu,e))},cuid(e){return this.check(Ja(ku,e))},cuid2(e){return this.check(Ka(Eu,e))},ulid(e){return this.check(Ga(Au,e))},base64(e){return this.check(rl(Pu,e))},base64url(e){return this.check(il(Nu,e))},xid(e){return this.check(Ya(Iu,e))},ksuid(e){return this.check(Xa(Su,e))},ipv4(e){return this.check(Qa(xu,e))},ipv6(e){return this.check(el(Cu,e))},cidrv4(e){return this.check(tl(Ru,e))},cidrv6(e){return this.check(nl(Ou,e))},e164(e){return this.check(ol(Mu,e))},datetime(e){return this.check(al(hu,e))},date(e){return this.check(ll(mu,e))},time(e){return this.check(ul(gu,e))},duration(e){return this.check(cl(yu,e))}});function l(e){return Da(fu,e)}var z=p("ZodStringFormat",(e,t)=>{M.init(e,t),di.init(e,t)}),hu=p("ZodISODateTime",(e,t)=>{js.init(e,t),z.init(e,t)}),mu=p("ZodISODate",(e,t)=>{Bs.init(e,t),z.init(e,t)}),gu=p("ZodISOTime",(e,t)=>{Fs.init(e,t),z.init(e,t)}),yu=p("ZodISODuration",(e,t)=>{qs.init(e,t),z.init(e,t)}),vu=p("ZodEmail",(e,t)=>{Is.init(e,t),z.init(e,t)}),bu=p("ZodGUID",(e,t)=>{Es.init(e,t),z.init(e,t)}),qe=p("ZodUUID",(e,t)=>{As.init(e,t),z.init(e,t)}),_u=p("ZodURL",(e,t)=>{Ps.init(e,t),z.init(e,t)}),wu=p("ZodEmoji",(e,t)=>{Ns.init(e,t),z.init(e,t)}),Tu=p("ZodNanoID",(e,t)=>{Ms.init(e,t),z.init(e,t)}),ku=p("ZodCUID",(e,t)=>{zs.init(e,t),z.init(e,t)}),Eu=p("ZodCUID2",(e,t)=>{$s.init(e,t),z.init(e,t)}),Au=p("ZodULID",(e,t)=>{Ls.init(e,t),z.init(e,t)}),Iu=p("ZodXID",(e,t)=>{Ds.init(e,t),z.init(e,t)}),Su=p("ZodKSUID",(e,t)=>{Us.init(e,t),z.init(e,t)}),xu=p("ZodIPv4",(e,t)=>{Zs.init(e,t),z.init(e,t)}),Cu=p("ZodIPv6",(e,t)=>{Vs.init(e,t),z.init(e,t)}),Ru=p("ZodCIDRv4",(e,t)=>{Ws.init(e,t),z.init(e,t)}),Ou=p("ZodCIDRv6",(e,t)=>{Ks.init(e,t),z.init(e,t)}),Pu=p("ZodBase64",(e,t)=>{Gs.init(e,t),z.init(e,t)}),Nu=p("ZodBase64URL",(e,t)=>{Xs.init(e,t),z.init(e,t)}),Mu=p("ZodE164",(e,t)=>{Qs.init(e,t),z.init(e,t)}),zu=p("ZodJWT",(e,t)=>{ta.init(e,t),z.init(e,t)}),pi=p("ZodNumber",(e,t)=>{yr.init(e,t),O.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Ur(e,n,r,i),e.isFinite=!0},zt({minValue:(e)=>{let{minimum:t,exclusiveMinimum:n}=q(e);return Math.max(t??Number.NEGATIVE_INFINITY,n??Number.NEGATIVE_INFINITY)},maxValue:(e)=>{let{maximum:t,exclusiveMaximum:n}=q(e);return Math.min(t??Number.POSITIVE_INFINITY,n??Number.POSITIVE_INFINITY)},isInt:(e)=>{let{isInt:t,multipleOf:n}=q(e);return!!t||!!n?.some(Number.isSafeInteger)},format:(e)=>q(e).format??null},{gt(e,t){return this.check(Cn(e,t))},gte(e,t){return this.check(Je(e,t))},min(e,t){return this.check(Je(e,t))},lt(e,t){return this.check(xn(e,t))},lte(e,t){return this.check(We(e,t))},max(e,t){return this.check(We(e,t))},int(e){return this.check(jn(e))},safe(e){return this.check(jn(e))},positive(e){return this.check(Cn(0,e))},nonnegative(e){return this.check(Je(0,e))},negative(e){return this.check(xn(0,e))},nonpositive(e){return this.check(We(0,e))},multipleOf(e,t){return this.check(Rn(e,t))},step(e,t){return this.check(Rn(e,t))},finite(){return this}}));function b(e){return dl(pi,e)}var $u=p("ZodNumberFormat",(e,t)=>{na.init(e,t),pi.init(e,t)});function jn(e){return pl($u,e)}var Lu=p("ZodBoolean",(e,t)=>{ra.init(e,t),O.init(e,t),e._zod.processJSONSchema=(n,r,i)=>jr(e,n,r,i)});function I(e){return fl(Lu,e)}var Du=p("ZodUnknown",(e,t)=>{ia.init(e,t),O.init(e,t),e._zod.processJSONSchema=(n,r,i)=>qr(e,n,r,i)});function j(){return hl(Du)}var Uu=p("ZodNever",(e,t)=>{oa.init(e,t),O.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Fr(e,n,r,i)});function ju(e){return ml(Uu,e)}var Bu=p("ZodVoid",(e,t)=>{sa.init(e,t),O.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Br(e,n,r,i)});function Fu(e){return gl(Bu,e)}var qu=p("ZodDate",(e,t)=>{aa.init(e,t),O.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Zr(e,n,r,i),e.min=(n,r)=>e.check(Je(n,r)),e.max=(n,r)=>e.check(We(n,r))},zt({minDate:(e)=>{let{minimum:t}=q(e);return t?new Date(t):null},maxDate:(e)=>{let{maximum:t}=q(e);return t?new Date(t):null}},{}));function rt(e){return yl(qu,e)}var Zu=p("ZodArray",(e,t)=>{ze(),la.init(e,t),O.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Gr(e,n,r,i),e.element=t.element},{min(e,t){return this.check(Xe(e,t))},nonempty(e){return this.check(Xe(1,e))},max(e,t){return this.check(Cr(e,t))},length(e,t){return this.check(Rr(e,t))},unwrap(){return this.element}});function E(e,t){return Cl(Zu,e,t)}var Hu=p("ZodObject",(e,t)=>{ze(),da.init(e,t),O.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Yr(e,n,r,i),co(e,"shape",(n)=>n._zod.def.shape,!1)},{keyof(){return A(Object.keys(this._zod.def.shape))},catchall(e){return this.clone(V(this._zod.def,{catchall:e}))},passthrough(){return this.clone(V(this._zod.def,{catchall:j()}))},loose(){return this.clone(V(this._zod.def,{catchall:j()}))},strict(){return this.clone(V(this._zod.def,{catchall:ju()}))},strip(){return this.clone(V(this._zod.def,{catchall:void 0}))},extend(e){return Qi(this,e)},safeExtend(e){return eo(this,e)},merge(e){return to(this,e)},pick(e){return Yi(this,e)},omit(e){return Xi(this,e)},partial(...e){return on(Vt,this,e[0])},exactPartial(...e){return on(mi,this,e[0],"exactPartial")},required(...e){return no(gi,this,e[0])}});function m(e,t){let n={type:"object",shape:e??{},...w(t)};return new Hu(n)}var fi=p("ZodUnion",(e,t)=>{_r.init(e,t),O.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Xr(e,n,r,i),e.options=t.options});function ge(e,t){return new fi({type:"union",options:e,...w(t)})}var Vu=p("ZodDiscriminatedUnion",(e,t)=>{fi.init(e,t),fa.init(e,t)});function Ht(e,t,n){return new Vu({type:"union",options:t,discriminator:e,...w(n)})}var Wu=p("ZodIntersection",(e,t)=>{ha.init(e,t),O.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Qr(e,n,r,i)});function Ju(e,t){return new Wu({type:"intersection",left:e,right:t})}var Ku=p("ZodTuple",(e,t)=>{ze(),wr.init(e,t),O.init(e,t),e._zod.processJSONSchema=(n,r,i)=>ei(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 Vt({type:"optional",innerType:t}))})}});function Gu(e,t,n){let r=t instanceof R;return new Ku({type:"tuple",items:e,rest:r?t:null,...w(r?n:t)})}var Bn=p("ZodRecord",(e,t)=>{ze(),ma.init(e,t),O.init(e,t),e._zod.processJSONSchema=(n,r,i)=>ti(e,n,r,i),e.keyType=t.keyType,e.valueType=t.valueType});function D(e,t,n){if(!t||!t._zod)return new Bn({type:"record",keyType:l(),valueType:e,...w(t)});return new Bn({type:"record",keyType:e,valueType:t,...w(n)})}var Ct=p("ZodEnum",(e,t)=>{ga.init(e,t),O.init(e,t),e._zod.processJSONSchema=(r,i,o)=>Hr(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 Ct({...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 Ct({...t,checks:[],...w(i),entries:o})}});function A(e,t){let n=Array.isArray(e)?Object.fromEntries(e.map((r)=>[r,r])):e;return new Ct({type:"enum",entries:n,...w(t)})}var Yu=p("ZodLiteral",(e,t)=>{ya.init(e,t),O.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Vr(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 L(e,t){return new Yu({type:"literal",values:Array.isArray(e)?e:[e],...w(t)})}var Xu=p("ZodTransform",(e,t)=>{ze(),va.init(e,t),O.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Kr(e,n,r,i),e._zod.parse=(n,r)=>{if(r.direction==="backward")throw new $t(e.constructor.name);n.addIssue=(o)=>{if(typeof o==="string")n.issues.push(Ne(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(Ne(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 hi(e){return new Xu({type:"transform",transform:e})}var Vt=p("ZodOptional",(e,t)=>{Tr.init(e,t),O.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Zt(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function Fn(e){return new Vt({type:"optional",innerType:e})}var mi=p("ZodExactOptional",(e,t)=>{ba.init(e,t),O.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Zt(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function Qu(e){return new mi({type:"optional",innerType:e})}var ec=p("ZodNullable",(e,t)=>{_a.init(e,t),O.init(e,t),e._zod.processJSONSchema=(n,r,i)=>ni(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function qn(e){return new ec({type:"nullable",innerType:e})}var tc=p("ZodDefault",(e,t)=>{wa.init(e,t),O.init(e,t),e._zod.processJSONSchema=(n,r,i)=>oi(e,n,r,i),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function nc(e,t){return new tc({type:"default",innerType:e,get defaultValue(){return typeof t==="function"?t():Xn(t)}})}var rc=p("ZodPrefault",(e,t)=>{Ta.init(e,t),O.init(e,t),e._zod.processJSONSchema=(n,r,i)=>si(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function ic(e,t){return new rc({type:"prefault",innerType:e,get defaultValue(){return typeof t==="function"?t():Xn(t)}})}var gi=p("ZodNonOptional",(e,t)=>{ka.init(e,t),O.init(e,t),e._zod.processJSONSchema=(n,r,i)=>ri(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function oc(e,t){return new gi({type:"nonoptional",innerType:e,...w(t)})}var sc=p("ZodCatch",(e,t)=>{Ea.init(e,t),O.init(e,t),e._zod.processJSONSchema=(n,r,i)=>ai(e,n,r,i),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function ac(e,t){return new sc({type:"catch",innerType:e,catchValue:typeof t==="function"?t:fo(t)})}var yi=p("ZodPipe",(e,t)=>{kr.init(e,t),O.init(e,t),e._zod.processJSONSchema=(n,r,i)=>li(e,n,r,i),e.in=t.in,e.out=t.out});function Zn(e,t){return new yi({type:"pipe",in:e,out:t})}var lc=p("ZodPreprocess",(e,t)=>{yi.init(e,t),Aa.init(e,t)}),uc=p("ZodReadonly",(e,t)=>{Ia.init(e,t),O.init(e,t),e._zod.processJSONSchema=(n,r,i)=>ui(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function cc(e){return new uc({type:"readonly",innerType:e})}var dc=p("ZodPromise",(e,t)=>{xa.init(e,t),O.init(e,t),e._zod.processJSONSchema=(n,r,i)=>ci(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function vt(e){return new dc({type:"promise",innerType:e})}var pc=p("ZodFunction",(e,t)=>{Sa.init(e,t),O.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Jr(e,n,r,i)});function Ze(e){return new pc({type:"function",input:Array.isArray(e?.input)?Gu(e?.input):e?.input??E(j()),output:e?.output??j()})}var vi=p("ZodCustom",(e,t)=>{Ca.init(e,t),O.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Wr(e,n,r,i)});function J(e,t){return Rl(vi,e??(()=>!0),t)}function fc(e,t={}){return Ol(vi,e,t)}function hc(e,t){return Pl(e,t)}function bi(e,t){return new lc({type:"pipe",in:hi(e),out:t})}var _i=["none","minimal","low","medium","high","xhigh","max"],mc=A(_i),gc=mc.exclude(["none"]),yc=A([..._i,"default"]).nullable(),vc=Ht("type",[m({type:L("toggle")}).strict(),m({type:L("effort"),values:E(yc)}).strict(),m({type:L("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"]})]),bc=A(["default","openai-responses","r1"]);var _c=A(["images","video","tools","streaming","prompt-cache","reasoning","reasoning-effort","computer-use","global-endpoint","structured_output","temperature","files"]),wc=A(["active","preview","deprecated","legacy"]),Tc=m({input:b().optional(),output:b().optional(),cacheWrite:b().optional(),cacheRead:b().optional()}),kc=m({maxBudget:b().optional(),outputPrice:b().optional(),thinkingLevel:A(["low","high"]).optional()}),Ec=m({reasoningDefaultOn:I().optional(),apiProtocol:A(["openai-chat","openai-responses","anthropic","gemini"]).optional()}).catchall(j()),Hn=A(["text","image","audio","video","pdf"]),Ac=m({input:E(Hn),output:E(Hn)});var Ic=A(["language","image-generation","speech-generation","video-generation","transcription","realtime"]);var Sc=A(["batch","streaming"]);var wi=m({id:l(),name:l().optional(),description:l().optional(),maxTokens:b().optional(),contextWindow:b().optional(),maxInputTokens:b().optional(),capabilities:E(_c).optional(),operation:Ic.optional(),operationModes:E(Sc).optional(),modalities:Ac.optional(),reasoningOptions:E(vc).optional(),apiFormat:bc.optional(),systemRole:A(["system","developer"]).optional(),temperature:b().optional(),pricing:Tc.optional(),thinkingConfig:kc.optional(),status:wc.optional(),deprecationNotice:l().optional(),replacedBy:l().optional(),releaseDate:l().optional(),deprecationDate:l().optional(),family:l().optional(),metadata:Ec.optional()});var Ti="NOT a tool or system failure. Clarify with user before proceeding.",xc=m({id:l(),name:l(),execution:A(["client","provider"]).optional(),input:j(),output:j(),error:l().optional(),durationMs:b(),startedAt:rt(),endedAt:rt()}),Cc=A(["completed","max_iterations","aborted","mistake_limit","error"]),Rc=m({inputTokens:b(),outputTokens:b(),cacheReadTokens:b().optional(),cacheWriteTokens:b().optional(),totalCost:b().optional()}),ap=m({text:l(),usage:Rc,messages:E(J()),toolCalls:E(xc),iterations:b(),finishReason:Cc,model:m({id:l(),provider:l(),info:wi.optional()}),startedAt:rt(),endedAt:rt(),durationMs:b()}),lp=m({distinctId:l().optional(),sessionId:l().optional(),providerId:l(),modelId:l(),apiKey:l().optional(),baseUrl:l().url().optional(),headers:D(l(),l()).optional(),knownModels:D(l(),wi).optional(),providerConfig:j().optional(),initialMessages:E(J()).optional(),systemPrompt:l(),tools:E(J()),modelTools:E(J()).optional(),maxIterations:b().positive().optional(),maxParallelToolCalls:b().int().positive().default(8),maxTokensPerTurn:b().positive().optional(),temperature:b().nonnegative().optional(),apiTimeoutMs:b().positive().default(180000),userFileContentLoader:Ze().input([l()]).output(vt(l())).optional(),toolContextMetadata:D(l(),j()).optional(),execution:m({maxConsecutiveMistakes:b().int().positive().optional(),reminderAfterIterations:b().nonnegative().optional(),reminderText:l().optional(),loopDetection:ge([L(!1),m({softThreshold:b().int().positive().optional(),hardThreshold:b().int().positive().optional()})]).optional()}).optional(),reasoningEffort:gc.optional(),thinkingBudgetTokens:b().positive().optional(),thinking:I().optional(),onEvent:Ze().input([J()]).output(Fu()).optional(),hooks:J().optional(),parentAgentId:l().optional(),extensions:E(J()).optional(),hookErrorMode:A(["ignore","throw"]).default("ignore"),toolPolicies:D(l(),m({enabled:I().optional(),autoApprove:I().optional()})).optional(),requestToolApproval:Ze().input([m({sessionId:l(),agentId:l(),conversationId:l(),iteration:b(),toolCallId:l(),toolName:l(),input:j(),policy:m({enabled:I().optional(),autoApprove:I().optional()}).default({})})]).output(ge([m({approved:I(),reason:l().optional()}),vt(m({approved:I(),reason:l().optional()}))])).optional(),onConsecutiveMistakeLimitReached:Ze().input([m({iteration:b().int().positive(),consecutiveMistakes:b().int().positive(),maxConsecutiveMistakes:b().int().positive(),reason:A(["api_error","invalid_tool_call","tool_execution_failed"]),details:l().optional()})]).output(ge([m({action:L("continue"),guidance:l().optional()}),m({action:L("stop"),reason:l().optional()}),vt(ge([m({action:L("continue"),guidance:l().optional()}),m({action:L("stop"),reason:l().optional()})]))])).optional(),logger:J().optional(),extensionContext:J().optional(),abortSignal:J().optional()}),Oc=A(["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"]),Pc=m({id:l().optional(),label:l().optional(),role:l().optional(),participantKey:l().optional(),participantLabel:l().optional(),platformUserId:l().optional(),metadata:D(l(),j()).optional()}),Nc=m({source:l(),sourceEvent:l(),threadId:l(),channelId:l(),isDM:I(),sessionId:l().optional(),workspaceRoot:l().optional(),metadata:D(l(),j()).optional()}),up=m({actor:Pc,context:Nc,payload:D(l(),j()).optional()}),cp=m({action:A(["allow","deny"]).default("allow"),message:l().optional(),reason:l().optional(),metadata:D(l(),j()).optional()}),dp=m({adapter:l(),botUserName:l().optional(),event:Oc,payload:D(l(),j()),ts:l()});var Mc=["hooks","tools","commands","rules","skills","messageBuilders","providers","automationEvents","mcp"],pp=new Set(Mc);var xe={CLINE_PASS:"ext-cline-pass",CODE_CLOUD_AGENTS:"code-cloud-agents",CODE_ONBOARDING_GITHUB:"code-onboarding-github",CLINE_COMPOSIO_BETA:"CLINE_COMPOSIO_BETA"},fp={[xe.CLINE_PASS]:!1,[xe.CODE_CLOUD_AGENTS]:!1,[xe.CODE_ONBOARDING_GITHUB]:!1,[xe.CLINE_COMPOSIO_BETA]:!1},hp=Object.values(xe),zc=A(["agent_start","agent_resume","agent_abort","agent_end","agent_error","tool_call","tool_result","prompt_submit","pre_compact","session_shutdown"]),fe=D(l(),l()),$c=m({toolName:l(),parameters:fe}),Lc=m({toolName:l(),parameters:fe,result:l(),success:I(),executionTimeMs:b()}),Dc=m({prompt:l(),attachments:E(l())}),Uc=m({taskMetadata:fe}),jc=m({taskMetadata:fe,previousState:fe}),Bc=m({taskMetadata:fe}),Fc=m({taskMetadata:fe}),qc=m({taskId:l(),ulid:l(),contextSize:b(),compactionStrategy:l(),previousApiReqIndex:b(),tokensIn:b(),tokensOut:b(),tokensInCache:b(),tokensOutCache:b(),deletedRangeStart:b(),deletedRangeEnd:b(),contextJsonPath:l(),contextRawPath:l()}),mp=m({clineVersion:l(),hookName:zc,timestamp:l(),taskId:l(),sessionContext:m({rootSessionId:l().optional(),hookLogPath:l().optional()}).optional(),workspaceRoots:E(l()),workspaceInfo:J().optional(),userId:l(),agent_id:l(),parent_agent_id:l().nullable(),iteration:b().optional(),reason:l().optional(),tool_call:m({id:l(),name:l(),input:j()}).optional(),tool_result:J().optional(),turn:j().optional(),error:m({name:l(),message:l(),stack:l().optional()}).optional(),preToolUse:$c.optional(),postToolUse:Lc.optional(),userPromptSubmit:Dc.optional(),taskStart:Uc.optional(),taskResume:jc.optional(),taskCancel:Bc.optional(),taskComplete:Fc.optional(),preCompact:qc.optional()}).passthrough();var Zc=["readFile","search","bash","webFetch","editor","applyPatch","skills","askQuestion","submit"],gp=new Set(Zc);var Hc=A(["image","audio","video","file"]),Vc=Ht("type",[m({type:L("base64"),data:l().min(1)}),m({type:L("url"),url:l().url().refine((e)=>{let t=new URL(e).protocol;return t==="http:"||t==="https:"},"Generated media URLs must use HTTP or HTTPS")}),m({type:L("artifact"),artifactId:l().min(1)})]);function Wc(e){if(e.startsWith("image/"))return"image";if(e.startsWith("audio/"))return"audio";if(e.startsWith("video/"))return"video";return"file"}var yp=m({id:l().min(1),modality:Hc,mediaType:l().min(1),source:Vc,name:l().min(1).optional(),sizeBytes:b().int().nonnegative().optional()}).refine((e)=>Wc(e.mediaType)===e.modality,{message:"Generated media modality must match its media type",path:["modality"]});function Vn(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function Wt(e,t){if(!e&&!t)return;let n=e?.metadata,r=t?.metadata,i={...e??{},...t??{}};if(Vn(n)&&Vn(r))i.metadata={...n,...r};return i}function ki(e){return Math.max(1,Math.ceil(e/3))}function ye(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function Jc(e){let t=e.type;if(typeof t==="string")return[t];return Array.isArray(t)?t.filter((n)=>typeof n==="string"):[]}function Rt(e,t){if(Jc(e).includes(t))return!0;for(let n of["anyOf","oneOf","allOf"]){let r=e[n];if(Array.isArray(r)&&r.some((i)=>ye(i)&&Rt(i,t)))return!0}return!1}function Kc(e,t){if(typeof e!=="string")return e;let n=e.trim(),r=Rt(t,"array"),i=Rt(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(ye(o))return i?o:e;return e}catch{return e}}function it(e,t){let n=Kc(e,t);if(Array.isArray(n)){let s=t.items;if(!ye(s))return n;let a=!1,u=n.map((c)=>{let d=it(c,s);return a||=d!==c,d});return a?u:n}if(!ye(n))return n;let r=t.properties;if(!ye(r))return n;let i=!1,o={...n};for(let[s,a]of Object.entries(r)){if(!(s in n)||!ye(a))continue;let u=it(n[s],a);if(u!==n[s])o[s]=u,i=!0}return i?o:n}function Ei(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}function Z(e){let t=e?.trim();return t?t:void 0}function Gc(e){return Xl(e)}var Ai=`# 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,12 +65,12 @@ 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, searching (grep), reading configs, inspecting git history and diffs, checking tool versions, and the like. 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. If the task requires a mutation, put it in the plan; it happens only after the user switches to act mode.`,yp=`${Ai}
68
+ The run_commands tool remains available in plan mode strictly for read-only inspection -- listing files, searching (grep), reading configs, inspecting git history and diffs, checking tool versions, and the like. 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. If the task requires a mutation, put it in the plan; it happens only after the user switches to act mode.`,vp=`${Ai}
69
69
 
70
- Once the user has reviewed your plan and explicitly approved it in a follow-up message, use the switch_to_act_mode tool to switch to act mode and begin implementation. Calling switch_to_act_mode immediately starts execution, so never call it in the same turn you present a plan and never treat the original task request as approval -- end your turn after presenting the plan and wait for the user's response.`,vp=`${Ai}
70
+ Once the user has reviewed your plan and explicitly approved it in a follow-up message, use the switch_to_act_mode tool to switch to act mode and begin implementation. Calling switch_to_act_mode immediately starts execution, so never call it in the same turn you present a plan and never treat the original task request as approval -- end your turn after presenting the plan and wait for the user's response.`,bp=`${Ai}
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 Yc=m({id:l(),temperature:b().optional(),maxTokens:b().optional(),contextWindow:b().optional(),inputPrice:b().optional(),outputPrice:b().optional(),supportsImages:I().optional()}),Xc=m({models:E(Yc).optional(),openAiBaseUrl:l().optional(),openAiHeaders:D(l(),l()).optional(),azureApiVersion:l().optional(),azureIdentity:I().optional()}),Qc=m({id:l(),thinkingBudgetTokens:b().optional()}),ed=m({name:l(),baseModelId:l(),thinkingBudgetTokens:b().optional()}),td=m({models:E(Qc).optional(),customModels:E(ed).optional(),awsRegion:l().optional(),awsUseCrossRegionInference:I().optional(),awsUseGlobalInference:I().optional(),awsBedrockUsePromptCache:I().optional(),awsBedrockEndpoint:l().optional()}),nd=m({id:l()}),rd=m({models:E(nd).optional()}),id=m({id:l(),thinkingBudgetTokens:b().optional()}),od=m({models:E(id).optional(),vertexProjectId:l().optional(),vertexRegion:l().optional()}),sd=m({id:l(),thinkingBudgetTokens:b().optional(),promptCachingEnabled:I().optional()}),ad=m({models:E(sd).optional(),baseUrl:l().optional()}),ld=m({id:l(),thinkingBudgetTokens:b().optional()}),ud=m({models:E(ld).optional(),baseUrl:l().optional()}),cd=m({OpenAiCompatible:Xc.optional(),AwsBedrock:td.optional(),Cline:rd.optional(),Vertex:od.optional(),LiteLLM:ad.optional(),Anthropic:ud.optional()}),dd=m({id:l()}),pd=m({name:l(),url:l(),alwaysEnabled:I().optional(),headers:D(l(),l()).optional()}),Wn=m({alwaysEnabled:I(),name:l(),contents:l()}),bt=m({bucket:l(),accessKeyId:l(),secretAccessKey:l(),region:l().optional(),endpoint:l().optional(),accountId:l().optional()}),fd=m({enabled:I().optional(),type:ge([L("s3_access_keys"),L("r2_access_keys"),L("azure_access_keys")]).optional(),s3AccessSettings:bt.optional(),r2AccessSettings:bt.optional(),azureAccessSettings:bt.optional()}),hd=m({promptUploading:fd.optional()}),bp=m({version:l(),providerSettings:cd.optional(),telemetryEnabled:I().optional(),kanbanEnabled:I().optional(),mcpMarketplaceEnabled:I().optional(),allowedMCPServers:E(dd).optional(),remoteMCPServers:E(pd).optional(),blockPersonalRemoteMCPServers:I().optional(),yoloModeAllowed:I().optional(),openTelemetryEnabled:I().optional(),openTelemetryMetricsExporter:l().optional(),openTelemetryLogsExporter:l().optional(),openTelemetryOtlpProtocol:l().optional(),openTelemetryOtlpEndpoint:l().optional(),openTelemetryOtlpHeaders:D(l(),l()).optional(),openTelemetryOtlpMetricsProtocol:l().optional(),openTelemetryOtlpMetricsEndpoint:l().optional(),openTelemetryOtlpMetricsHeaders:D(l(),l()).optional(),openTelemetryOtlpLogsProtocol:l().optional(),openTelemetryOtlpLogsEndpoint:l().optional(),openTelemetryOtlpLogsHeaders:D(l(),l()).optional(),openTelemetryMetricExportInterval:b().optional(),openTelemetryOtlpInsecure:I().optional(),openTelemetryLogBatchSize:b().optional(),openTelemetryLogBatchTimeout:b().optional(),openTelemetryLogMaxQueueSize:b().optional(),enterpriseTelemetry:hd.optional(),globalRules:E(Wn).optional(),globalWorkflows:E(Wn).optional()}),_p=D(l(),l());var wp=A(["reasoning","prompt-cache","tools","provider-tools","oauth","temperature","files","streaming","vision","computer-use","local-auth","popular"]),Tp=A(["anthropic","gemini","openai-chat","openai-responses","openai-r1","ai-sdk"]),kp=A(["anthropic","ai-sdk","ai-sdk-community","openai","openai-compatible","openai-r1","gemini","bedrock","custom","fetch","vertex"]);var Ii="task.provider_request_started",Si="task.provider_stream_started",xi="task.first_chunk_received",Ci="task.provider_stream_failed",Ri="task.cancelled",$e="task.max_tokens_recovery";var me=new Map;function md(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 gd(e){let t=Date.now(),n=me.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(me.delete(e),me.size>=512){let i=me.keys().next();if(!i.done)me.delete(i.value)}return me.set(e,{startMs:t,emitted:1,suppressed:0}),{emit:!0,suppressed:r}}function Oi(e,t){e?.capture({event:"agent.reasoning.unexpected_tokens",properties:Jt({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 Pi(e,t){if(!e)return;e.capture({event:t.event,properties:Jt({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?{}:Mi(t.error,t.messageLimit),error_class:t.errorClass})})}function Ni(e,t){if(!e)return!1;let n=t.event??"sdk.error",r=yd(t),i=0;try{let o=gd(md(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 yd(e){return Jt({...e.context??{},component:e.component,operation:e.operation,severity:e.severity??"error",handled:e.handled??!0,...Mi(e.error,e.messageLimit,e.errorMessage)})}function Jt(e){let t={};for(let[n,r]of Object.entries(e))if(r!==void 0)t[n]=r;return t}function Mi(e,t=500,n){let r=_d(e)?e:void 0,i=e instanceof Error?e:void 0,o=Ce(n)??Ce(i?.message)??Ce(r?.message)??wd(e)??"Unknown error",s=Td(r?.code),a=_t(r?.status)??_t(r?.statusCode)??_t(r?.responseStatus);return{error_type:i?.name?.trim()||Ce(r?.name)||i?.constructor?.name||"Error",error_message:bd(vd(o),t),...s!==void 0?{error_code:s}:{},...a!==void 0?{error_status:a}:{}}}function vd(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 bd(e,t){let n=Math.max(1,Math.floor(t));return e.length>n?e.substring(0,n):e}function _d(e){return typeof e==="object"&&e!==null}function Ce(e){return typeof e==="string"&&e.trim().length>0?e:void 0}function wd(e){if(e instanceof Error)return;let t=typeof e==="string"?e:String(e);return t==="[object Object]"?void 0:Ce(t)}function Td(e){if(typeof e==="string"&&e.trim().length>0)return e;if(typeof e==="number"&&Number.isFinite(e))return e;return}function _t(e){return typeof e==="number"&&Number.isFinite(e)?e:void 0}var kd=["rules","skills","workflows","plugins","hooks"];var Ep=new Set(kd);var Ed=m({rootPath:l().min(1),hint:l().min(1).optional(),associatedRemoteUrls:E(l().min(1)).optional(),latestGitCommitHash:l().min(1).optional(),latestGitBranchName:l().min(1).optional()}),Ap=m({currentWorkspacePath:l().min(1).optional(),workspaces:D(l().min(1),Ed)});var Ad=["current_state","boundary_analysis","interface_proposal"];var X=bi((e)=>e instanceof Date?e.toISOString():e,l().datetime()),ve=A(["pending","in_progress","blocked","completed"]),zi=A(["queued","running","completed","failed","cancelled","interrupted"]),dt=A(["draft","in_review","finalized"]),Id=m({agentId:l(),role:A(["lead","teammate"]),description:l().optional(),status:A(["idle","running","stopped"])}),Ip=m({agentId:l(),rolePrompt:l(),modelId:l().optional(),maxIterations:b().optional()});function N(e){return bi((t)=>t===null?void 0:t,e.optional())}var Sp=m({agentId:l().min(1).describe("Teammate identifier"),rolePrompt:l().min(1).describe("System prompt describing teammate role")}).strict(),xp=m({agentId:l().min(1).describe("Teammate identifier"),reason:N(l().min(1)).describe("Optional shutdown reason")}),Cp=m({}),Sd={create:["title","description"],list:[],claim:["taskId"],complete:["taskId","summary"],block:["taskId","reason"]};var Rp=m({action:A(["create","list","claim","complete","block"]),title:N(l().min(1)).describe("Task title"),description:N(l().min(1)).describe("Task details"),dependsOn:N(E(l().describe("Dependency task ID"))).describe("Array of dependency task IDs"),assignee:N(l().min(1)).describe("Optional assignee"),status:N(A(["pending","in_progress","blocked","completed"])).describe("Optional task status filter"),taskId:N(l()).describe("Task ID"),summary:N(l().min(1)).describe("Completion summary"),reason:N(l().min(1)).describe("Blocking reason")}).superRefine((e,t)=>{for(let n of Sd[e.action]){if(e[n]!==void 0)continue;t.addIssue({code:"custom",path:[n],message:`Field "${n}" is required when action=${e.action}`})}}),Op=m({agentId:l().describe("Teammate agent ID"),task:l().min(1).describe("Task instructions for the teammate"),taskId:N(l()).describe("Optional shared task list ID"),runMode:N(A(["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:N(I()).describe("If true, continue the teammate conversation; otherwise start fresh")}),Pp=m({status:N(A(["queued","running","completed","failed","cancelled","interrupted"])).describe("Optional run status filter. Omit to include all statuses."),agentId:N(l().min(1)).describe("Optional teammate ID filter. Omit to include all teammates."),includeCompleted:N(I()).describe("Include completed/failed runs (default true)")}),Np=m({runId:l().min(1).describe("Run ID"),reason:N(l().min(1)).describe("Optional cancellation reason")}),Mp=m({runId:N(l().min(1)).describe("Optional async run ID to await. Omit to wait for all active async runs.")}).strict(),zp=m({toAgentId:l().min(1).describe("Recipient agent ID"),subject:l().min(1).describe("Message subject"),body:l().min(1).describe("Message body"),taskId:N(l().min(1)).describe("Optional task ID context")}),$p=m({subject:l().min(1).describe("Message subject"),body:l().min(1).describe("Message body"),taskId:N(l().min(1)).describe("Optional task ID context")}),Lp=m({unreadOnly:N(I()).describe("Only unread messages for read action (default true)")}),Dp=m({kind:A(["progress","handoff","blocked","decision","done","error"]),summary:l().min(1).describe("Update summary"),taskId:N(l().min(1)).describe("Optional task ID context"),evidence:N(E(l().min(1))).describe("Optional evidence links/snippets"),nextAction:N(l().min(1)).describe("Planned next step")}),Up=m({}),jp=m({title:l().describe("Outcome title"),requiredSections:E(l()).default(Ad).describe("Required sections for finalization gate (defaults to current_state,boundary_analysis,interface_proposal)")}),Bp=m({outcomeId:l().describe("Outcome ID"),section:l().describe("Section name"),sourceRunId:N(l()).describe("Optional source run ID"),content:l().describe("Section fragment content")}),Fp=m({fragmentId:l().describe("Fragment ID"),approved:I().describe("Review decision")}),qp=m({outcomeId:l().describe("Outcome ID")}),Zp=m({}),Hp=m({teamId:l(),teamName:l(),members:E(Id),taskCounts:D(ve,b()),unreadMessages:b(),missionLogEntries:b(),activeRuns:b(),queuedRuns:b(),outcomeCounts:D(dt,b())}),xd=m({id:l(),title:l(),description:l(),status:ve,createdAt:X,updatedAt:X,createdBy:l(),assignee:l().optional(),dependsOn:E(l()),summary:l().optional(),isReady:I(),blockedBy:E(l())}),Vp=Ht("action",[m({action:L("create"),taskId:l(),status:ve,ignoredFields:E(l()).optional(),note:l().optional()}),m({action:L("list"),tasks:E(xd)}),m({action:L("claim"),taskId:l(),status:ve,nextStep:l()}),m({action:L("complete"),taskId:l(),status:ve}),m({action:L("block"),taskId:l(),status:ve})]),Wp=m({agentId:l(),mode:A(["sync","async"]),status:A(["dispatched","running","queued","joined"]),dispatched:I(),message:l(),deduped:I().optional(),runId:l().optional(),text:l().optional(),iterations:b().optional()}),Cd=m({textPreview:l(),iterations:b(),finishReason:l(),durationMs:b(),usage:m({inputTokens:b(),outputTokens:b(),cacheReadTokens:b().optional(),cacheWriteTokens:b().optional(),totalCost:b().optional()})}),Jp=m({id:l(),agentId:l(),taskId:l().optional(),status:zi,messagePreview:l(),priority:b(),retryCount:b(),maxRetries:b(),nextAttemptAt:X.optional(),continueConversation:I().optional(),startedAt:X,endedAt:X.optional(),leaseOwner:l().optional(),heartbeatAt:X.optional(),lastProgressAt:X.optional(),lastProgressMessage:l().optional(),currentActivity:l().optional(),error:l().optional(),resultSummary:Cd.optional()}),Kp=m({id:l(),teamId:l(),fromAgentId:l(),toAgentId:l(),subject:l(),body:l(),taskId:l().optional(),sentAt:X,readAt:X.optional()}),Gp=m({id:l(),teamId:l(),title:l(),status:dt,requiredSections:E(l()),createdBy:l(),createdAt:X,finalizedAt:X.optional()}),Yp=m({outcomeId:l(),status:dt,requiredSections:E(l())}),Xp=m({agentId:l(),status:l()}),Qp=m({runId:l(),status:zi}),ef=m({id:l(),toAgentId:l()}),tf=m({delivered:b()}),nf=m({id:l()}),rf=m({status:l()}),of=m({fragmentId:l(),status:l()}),sf=m({outcomeId:l(),status:dt}),Rd;((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"})(Rd||={});function Od(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 Pd(e){let t=Od(e.inputSchema instanceof O?Gc(e.inputSchema):e.inputSchema);return{name:e.name,description:e.description,inputSchema:t,lifecycle:e.lifecycle,executionMode:e.executionMode,timeoutMs:e.timeoutMs??30000,retryable:e.retryable??!0,maxRetries:e.maxRetries??3,execute:e.execute}}import{classifyProviderError as $i,createGateway as Nd,isRetryableProviderError as Md}from"@cline/llms";import{nanoid as zd}from"nanoid";var $d="Model reached the maximum output token limit before completing the turn",Kt=3,Ld="Your previous response was cut off because it reached the model's output-token limit before finishing. Keep responses concise: take one small step at a time, avoid long explanations, and write large files or command output in smaller chunks across multiple tool calls.",Gt=3,Dd=1000,Ud=15000,jd="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.",Bd="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.",Fd="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 Ee extends Error{constructor(e,t){super(t?.trim()?`${e} (provider reported: ${t.trim()})`:e);this.name="ContextWindowOverflowError"}}function de(e,t=8){return`${e}_${zd(t)}`}function qd(e){return e.model!==void 0}function Zd(e){if(qd(e))return e;let{providerId:t,modelId:n,apiKey:r,baseUrl:i,headers:o,options:s,...a}=e,c=Nd({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:c,messageModelInfo:d}}function Hd(e,t){return{...t?.["*"]??{},...t?.[e]??{}}}function Qt(e){try{return JSON.stringify(e).length}catch{return String(e).length}}function Vd(e){if(typeof e==="string")return e.length;return Qt(e)}function Wd(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+=Qt(s.input);break;case"tool-result":{let a=Vd(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:Qt({systemPrompt:e.systemPrompt,messages:e.messages,tools:e.tools,options:e.options}),visibleTextChars:t,estimatedTextTokens:ki(t),toolResultCount:n,toolResultChars:r,maxToolResultChars:i}}class en extends Error{reason;constructor(e){super(e??"Run stopped by runtime control");this.name="ControlledStopError",this.reason=e}}class Le 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 Yt={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0};function he(e,t,n){return{id:de("msg"),role:e,content:t,createdAt:Date.now(),metadata:n}}function ce(e){return{...e}}var Jd={_:"__",'"':"_q_","<":"_lt_",">":"_gt_"};function Li(e){return e.replace(/[_"<>]/g,(t)=>Jd[t])}function Xt(e,t){let n=[`source="${e.source}"`];if("toolCall"in e)n.push(`tool_name="${Li(e.toolCall.toolName)}"`,`tool_call_id="${Li(e.toolCall.toolCallId)}"`);let r=t.trim().replace(/<(\/?)hook_context/gi,"<\\$1hook_context");return`<hook_context ${n.join(" ")}>
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 Yc=m({id:l(),temperature:b().optional(),maxTokens:b().optional(),contextWindow:b().optional(),inputPrice:b().optional(),outputPrice:b().optional(),supportsImages:I().optional()}),Xc=m({models:E(Yc).optional(),openAiBaseUrl:l().optional(),openAiHeaders:D(l(),l()).optional(),azureApiVersion:l().optional(),azureIdentity:I().optional()}),Qc=m({id:l(),thinkingBudgetTokens:b().optional()}),ed=m({name:l(),baseModelId:l(),thinkingBudgetTokens:b().optional()}),td=m({models:E(Qc).optional(),customModels:E(ed).optional(),awsRegion:l().optional(),awsUseCrossRegionInference:I().optional(),awsUseGlobalInference:I().optional(),awsBedrockUsePromptCache:I().optional(),awsBedrockEndpoint:l().optional()}),nd=m({id:l()}),rd=m({models:E(nd).optional()}),id=m({id:l(),thinkingBudgetTokens:b().optional()}),od=m({models:E(id).optional(),vertexProjectId:l().optional(),vertexRegion:l().optional()}),sd=m({id:l(),thinkingBudgetTokens:b().optional(),promptCachingEnabled:I().optional()}),ad=m({models:E(sd).optional(),baseUrl:l().optional()}),ld=m({id:l(),thinkingBudgetTokens:b().optional()}),ud=m({models:E(ld).optional(),baseUrl:l().optional()}),cd=m({OpenAiCompatible:Xc.optional(),AwsBedrock:td.optional(),Cline:rd.optional(),Vertex:od.optional(),LiteLLM:ad.optional(),Anthropic:ud.optional()}),dd=m({id:l()}),pd=m({name:l(),url:l(),alwaysEnabled:I().optional(),headers:D(l(),l()).optional()}),Wn=m({alwaysEnabled:I(),name:l(),contents:l()}),bt=m({bucket:l(),accessKeyId:l(),secretAccessKey:l(),region:l().optional(),endpoint:l().optional(),accountId:l().optional()}),fd=m({enabled:I().optional(),type:ge([L("s3_access_keys"),L("r2_access_keys"),L("azure_access_keys")]).optional(),s3AccessSettings:bt.optional(),r2AccessSettings:bt.optional(),azureAccessSettings:bt.optional()}),hd=m({promptUploading:fd.optional()}),_p=m({version:l(),providerSettings:cd.optional(),telemetryEnabled:I().optional(),kanbanEnabled:I().optional(),mcpMarketplaceEnabled:I().optional(),allowedMCPServers:E(dd).optional(),remoteMCPServers:E(pd).optional(),blockPersonalRemoteMCPServers:I().optional(),yoloModeAllowed:I().optional(),openTelemetryEnabled:I().optional(),openTelemetryMetricsExporter:l().optional(),openTelemetryLogsExporter:l().optional(),openTelemetryOtlpProtocol:l().optional(),openTelemetryOtlpEndpoint:l().optional(),openTelemetryOtlpHeaders:D(l(),l()).optional(),openTelemetryOtlpMetricsProtocol:l().optional(),openTelemetryOtlpMetricsEndpoint:l().optional(),openTelemetryOtlpMetricsHeaders:D(l(),l()).optional(),openTelemetryOtlpLogsProtocol:l().optional(),openTelemetryOtlpLogsEndpoint:l().optional(),openTelemetryOtlpLogsHeaders:D(l(),l()).optional(),openTelemetryMetricExportInterval:b().optional(),openTelemetryOtlpInsecure:I().optional(),openTelemetryLogBatchSize:b().optional(),openTelemetryLogBatchTimeout:b().optional(),openTelemetryLogMaxQueueSize:b().optional(),enterpriseTelemetry:hd.optional(),globalRules:E(Wn).optional(),globalWorkflows:E(Wn).optional()}),wp=D(l(),l());var Tp=A(["reasoning","prompt-cache","tools","provider-tools","oauth","temperature","files","streaming","vision","computer-use","local-auth","popular"]),kp=A(["anthropic","gemini","openai-chat","openai-responses","openai-r1","ai-sdk"]),Ep=A(["anthropic","ai-sdk","ai-sdk-community","openai","openai-compatible","openai-r1","gemini","bedrock","custom","fetch","vertex"]);var Ii="task.provider_request_started",Si="task.provider_stream_started",xi="task.first_chunk_received",Ci="task.provider_stream_failed",Ri="task.cancelled",$e="task.max_tokens_recovery";var me=new Map;function md(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 gd(e){let t=Date.now(),n=me.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(me.delete(e),me.size>=512){let i=me.keys().next();if(!i.done)me.delete(i.value)}return me.set(e,{startMs:t,emitted:1,suppressed:0}),{emit:!0,suppressed:r}}function Oi(e,t){e?.capture({event:"agent.reasoning.unexpected_tokens",properties:Jt({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 Pi(e,t){if(!e)return;e.capture({event:t.event,properties:Jt({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?{}:Mi(t.error,t.messageLimit),error_class:t.errorClass})})}function Ni(e,t){if(!e)return!1;let n=t.event??"sdk.error",r=yd(t),i=0;try{let o=gd(md(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 yd(e){return Jt({...e.context??{},component:e.component,operation:e.operation,severity:e.severity??"error",handled:e.handled??!0,...Mi(e.error,e.messageLimit,e.errorMessage)})}function Jt(e){let t={};for(let[n,r]of Object.entries(e))if(r!==void 0)t[n]=r;return t}function Mi(e,t=500,n){let r=_d(e)?e:void 0,i=e instanceof Error?e:void 0,o=Ce(n)??Ce(i?.message)??Ce(r?.message)??wd(e)??"Unknown error",s=Td(r?.code),a=_t(r?.status)??_t(r?.statusCode)??_t(r?.responseStatus);return{error_type:i?.name?.trim()||Ce(r?.name)||i?.constructor?.name||"Error",error_message:bd(vd(o),t),...s!==void 0?{error_code:s}:{},...a!==void 0?{error_status:a}:{}}}function vd(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 bd(e,t){let n=Math.max(1,Math.floor(t));return e.length>n?e.substring(0,n):e}function _d(e){return typeof e==="object"&&e!==null}function Ce(e){return typeof e==="string"&&e.trim().length>0?e:void 0}function wd(e){if(e instanceof Error)return;let t=typeof e==="string"?e:String(e);return t==="[object Object]"?void 0:Ce(t)}function Td(e){if(typeof e==="string"&&e.trim().length>0)return e;if(typeof e==="number"&&Number.isFinite(e))return e;return}function _t(e){return typeof e==="number"&&Number.isFinite(e)?e:void 0}var kd=["rules","skills","workflows","plugins","hooks"];var Ap=new Set(kd);var Ed=m({rootPath:l().min(1),hint:l().min(1).optional(),associatedRemoteUrls:E(l().min(1)).optional(),latestGitCommitHash:l().min(1).optional(),latestGitBranchName:l().min(1).optional()}),Ip=m({currentWorkspacePath:l().min(1).optional(),workspaces:D(l().min(1),Ed)});var Ad=["current_state","boundary_analysis","interface_proposal"];var X=bi((e)=>e instanceof Date?e.toISOString():e,l().datetime()),ve=A(["pending","in_progress","blocked","completed"]),zi=A(["queued","running","completed","failed","cancelled","interrupted"]),dt=A(["draft","in_review","finalized"]),Id=m({agentId:l(),role:A(["lead","teammate"]),description:l().optional(),status:A(["idle","running","stopped"])}),Sp=m({agentId:l(),rolePrompt:l(),modelId:l().optional(),maxIterations:b().optional()});function N(e){return bi((t)=>t===null?void 0:t,e.optional())}var xp=m({agentId:l().min(1).describe("Teammate identifier"),rolePrompt:l().min(1).describe("System prompt describing teammate role")}).strict(),Cp=m({agentId:l().min(1).describe("Teammate identifier"),reason:N(l().min(1)).describe("Optional shutdown reason")}),Rp=m({}),Sd={create:["title","description"],list:[],claim:["taskId"],complete:["taskId","summary"],block:["taskId","reason"]};var Op=m({action:A(["create","list","claim","complete","block"]),title:N(l().min(1)).describe("Task title"),description:N(l().min(1)).describe("Task details"),dependsOn:N(E(l().describe("Dependency task ID"))).describe("Array of dependency task IDs"),assignee:N(l().min(1)).describe("Optional assignee"),status:N(A(["pending","in_progress","blocked","completed"])).describe("Optional task status filter"),taskId:N(l()).describe("Task ID"),summary:N(l().min(1)).describe("Completion summary"),reason:N(l().min(1)).describe("Blocking reason")}).superRefine((e,t)=>{for(let n of Sd[e.action]){if(e[n]!==void 0)continue;t.addIssue({code:"custom",path:[n],message:`Field "${n}" is required when action=${e.action}`})}}),Pp=m({agentId:l().describe("Teammate agent ID"),task:l().min(1).describe("Task instructions for the teammate"),taskId:N(l()).describe("Optional shared task list ID"),runMode:N(A(["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:N(I()).describe("If true, continue the teammate conversation; otherwise start fresh")}),Np=m({status:N(A(["queued","running","completed","failed","cancelled","interrupted"])).describe("Optional run status filter. Omit to include all statuses."),agentId:N(l().min(1)).describe("Optional teammate ID filter. Omit to include all teammates."),includeCompleted:N(I()).describe("Include completed/failed runs (default true)")}),Mp=m({runId:l().min(1).describe("Run ID"),reason:N(l().min(1)).describe("Optional cancellation reason")}),zp=m({runId:N(l().min(1)).describe("Optional async run ID to await. Omit to wait for all active async runs.")}).strict(),$p=m({toAgentId:l().min(1).describe("Recipient agent ID"),subject:l().min(1).describe("Message subject"),body:l().min(1).describe("Message body"),taskId:N(l().min(1)).describe("Optional task ID context")}),Lp=m({subject:l().min(1).describe("Message subject"),body:l().min(1).describe("Message body"),taskId:N(l().min(1)).describe("Optional task ID context")}),Dp=m({unreadOnly:N(I()).describe("Only unread messages for read action (default true)")}),Up=m({kind:A(["progress","handoff","blocked","decision","done","error"]),summary:l().min(1).describe("Update summary"),taskId:N(l().min(1)).describe("Optional task ID context"),evidence:N(E(l().min(1))).describe("Optional evidence links/snippets"),nextAction:N(l().min(1)).describe("Planned next step")}),jp=m({}),Bp=m({title:l().describe("Outcome title"),requiredSections:E(l()).default(Ad).describe("Required sections for finalization gate (defaults to current_state,boundary_analysis,interface_proposal)")}),Fp=m({outcomeId:l().describe("Outcome ID"),section:l().describe("Section name"),sourceRunId:N(l()).describe("Optional source run ID"),content:l().describe("Section fragment content")}),qp=m({fragmentId:l().describe("Fragment ID"),approved:I().describe("Review decision")}),Zp=m({outcomeId:l().describe("Outcome ID")}),Hp=m({}),Vp=m({teamId:l(),teamName:l(),members:E(Id),taskCounts:D(ve,b()),unreadMessages:b(),missionLogEntries:b(),activeRuns:b(),queuedRuns:b(),outcomeCounts:D(dt,b())}),xd=m({id:l(),title:l(),description:l(),status:ve,createdAt:X,updatedAt:X,createdBy:l(),assignee:l().optional(),dependsOn:E(l()),summary:l().optional(),isReady:I(),blockedBy:E(l())}),Wp=Ht("action",[m({action:L("create"),taskId:l(),status:ve,ignoredFields:E(l()).optional(),note:l().optional()}),m({action:L("list"),tasks:E(xd)}),m({action:L("claim"),taskId:l(),status:ve,nextStep:l()}),m({action:L("complete"),taskId:l(),status:ve}),m({action:L("block"),taskId:l(),status:ve})]),Jp=m({agentId:l(),mode:A(["sync","async"]),status:A(["dispatched","running","queued","joined"]),dispatched:I(),message:l(),deduped:I().optional(),runId:l().optional(),text:l().optional(),iterations:b().optional()}),Cd=m({textPreview:l(),iterations:b(),finishReason:l(),durationMs:b(),usage:m({inputTokens:b(),outputTokens:b(),cacheReadTokens:b().optional(),cacheWriteTokens:b().optional(),totalCost:b().optional()})}),Kp=m({id:l(),agentId:l(),taskId:l().optional(),status:zi,messagePreview:l(),priority:b(),retryCount:b(),maxRetries:b(),nextAttemptAt:X.optional(),continueConversation:I().optional(),startedAt:X,endedAt:X.optional(),leaseOwner:l().optional(),heartbeatAt:X.optional(),lastProgressAt:X.optional(),lastProgressMessage:l().optional(),currentActivity:l().optional(),error:l().optional(),resultSummary:Cd.optional()}),Gp=m({id:l(),teamId:l(),fromAgentId:l(),toAgentId:l(),subject:l(),body:l(),taskId:l().optional(),sentAt:X,readAt:X.optional()}),Yp=m({id:l(),teamId:l(),title:l(),status:dt,requiredSections:E(l()),createdBy:l(),createdAt:X,finalizedAt:X.optional()}),Xp=m({outcomeId:l(),status:dt,requiredSections:E(l())}),Qp=m({agentId:l(),status:l()}),ef=m({runId:l(),status:zi}),tf=m({id:l(),toAgentId:l()}),nf=m({delivered:b()}),rf=m({id:l()}),of=m({status:l()}),sf=m({fragmentId:l(),status:l()}),af=m({outcomeId:l(),status:dt}),Rd;((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"})(Rd||={});function Od(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 Pd(e){let t=Od(e.inputSchema instanceof O?Gc(e.inputSchema):e.inputSchema);return{name:e.name,description:e.description,inputSchema:t,lifecycle:e.lifecycle,executionMode:e.executionMode,timeoutMs:e.timeoutMs??30000,retryable:e.retryable??!0,maxRetries:e.maxRetries??3,execute:e.execute}}import{classifyProviderError as $i,createGateway as Nd,isRetryableProviderError as Md}from"@cline/llms";import{nanoid as zd}from"nanoid";var $d="Model reached the maximum output token limit before completing the turn",Kt=3,Ld="Your previous response was cut off because it reached the model's output-token limit before finishing. Keep responses concise: take one small step at a time, avoid long explanations, and write large files or command output in smaller chunks across multiple tool calls.",Gt=3,Dd=1000,Ud=15000,jd="Model returned no content because the response was blocked by a content filter. Retrying is unlikely to help — try rephrasing the request.",Bd="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.",Fd="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.",qd="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 Ee extends Error{constructor(e,t){super(t?.trim()?`${e} (provider reported: ${t.trim()})`:e);this.name="ContextWindowOverflowError"}}function de(e,t=8){return`${e}_${zd(t)}`}function Zd(e){return e.model!==void 0}function Hd(e){if(Zd(e))return e;let{providerId:t,modelId:n,apiKey:r,baseUrl:i,headers:o,options:s,...a}=e,c=Nd({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:c,messageModelInfo:d}}function Vd(e,t){return{...t?.["*"]??{},...t?.[e]??{}}}function Qt(e){try{return JSON.stringify(e).length}catch{return String(e).length}}function Wd(e){if(typeof e==="string")return e.length;return Qt(e)}function Jd(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+=Qt(s.input);break;case"tool-result":{let a=Wd(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:Qt({systemPrompt:e.systemPrompt,messages:e.messages,tools:e.tools,options:e.options}),visibleTextChars:t,estimatedTextTokens:ki(t),toolResultCount:n,toolResultChars:r,maxToolResultChars:i}}class en extends Error{reason;constructor(e){super(e??"Run stopped by runtime control");this.name="ControlledStopError",this.reason=e}}class Le 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 Yt={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0};function he(e,t,n){return{id:de("msg"),role:e,content:t,createdAt:Date.now(),metadata:n}}function ce(e){return{...e}}var Kd={_:"__",'"':"_q_","<":"_lt_",">":"_gt_"};function Li(e){return e.replace(/[_"<>]/g,(t)=>Kd[t])}function Xt(e,t){let n=[`source="${e.source}"`];if("toolCall"in e)n.push(`tool_name="${Li(e.toolCall.toolName)}"`,`tool_call_id="${Li(e.toolCall.toolCallId)}"`);let r=t.trim().replace(/<(\/?)hook_context/gi,"<\\$1hook_context");return`<hook_context ${n.join(" ")}>
73
73
  ${r}
74
- </hook_context>`}function W(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 Kd(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,u=t.totalCost??0,c=Math.max(0,u-a);if(n===0&&r===0&&i===0&&o===0&&s===0&&c===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}:{},...c>0?{cost:c}:{}}}function Gd(e){return e.options?.thinking===!1}function Di(e){if(!e)return"";return e.content.filter((t)=>t.type==="text").map((t)=>t.text).join("")}function Yd(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 Xd(e){if(typeof e==="string")return[he("user",[{type:"text",text:e}])];if(Array.isArray(e))return W(e);return W([e])}class De{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:ce(Yt),lastError:void 0,lastErrorClass:void 0,lastRequestInputTokens:0,lastErrorRetryable:void 0,lastErrorReported:!1};overflowRecoveryAttempted=!1;maxTokensRecoveryCount=0;maxTokensRecoveryAttempted=!1;initialization;abortController;modelSteerController;telemetryProviderId;telemetryModelId;constructor(e){this.telemetryProviderId=Z(e.messageModelInfo?.provider)??("providerId"in e?Z(e.providerId):void 0),this.telemetryModelId=Z(e.messageModelInfo?.id)??("modelId"in e?Z(e.modelId):void 0);let t=Zd(e);this.config={...t,toolExecution:t.toolExecution??"sequential"},this.state.agentId=t.agentId??de("agent"),this.state.agentRole=t.agentRole,this.state.parentAgentId=t.parentAgentId,this.state.messages=W(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 Le?e:new Le(e);this.state.lastError=t.message,this.captureTaskLifecycle(Ri,{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=ce(Yt),this.state.lastError=void 0,this.state.lastErrorClass=void 0,this.state.lastErrorRetryable=void 0,this.state.lastErrorReported=!1,this.state.messages=W(e),this.config={...this.config,initialMessages:W(e)}}snapshot(){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,messages:W(this.state.messages),pendingToolCalls:[...this.state.pendingToolCalls],usage:ce(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.`}getCompletionReminderMessages(){return[this.getCompletionToolReminderMessage(),this.config.completionPolicy?.completionGuard?.()].filter((e)=>Boolean(e))}async addUserReminderMessage(e){let t=he("user",[{type:"text",text:e}],{userRunSpan:0});return this.state.messages.push(t),await this.emit({type:"message-added",snapshot:this.snapshot(),message:t}),t}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=de("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.usage=ce(Yt),this.overflowRecoveryAttempted=!1,this.state.lastRequestInputTokens=0,this.pendingHookContexts=[],this.maxTokensRecoveryCount=0,this.maxTokensRecoveryAttempted=!1;try{await this.callBeforeRunHooks(),await this.emit({type:"run-started",snapshot:this.snapshot()});for(let r of e?Xd(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,await this.emit({type:"turn-started",snapshot:this.snapshot(),iteration:this.state.iteration}),this.resetLastError();let{message:r,finishReason:i,interrupted:o}=await this.generateAssistantMessageWithProviderRetry();if(o&&r.content.length===0){await this.emit({type:"turn-finished",snapshot:this.snapshot(),iteration:this.state.iteration,toolCallCount:0});continue}if(i==="aborted")throw this.normalizeAbortError();if(r.content.length===0){if(i==="error")throw Error(this.state.lastError??"Model stream failed");let c=r.metadata?.modelToolActivities;if(!(Array.isArray(c)&&c.length>0)&&i!=="max-tokens")throw Error("Model returned empty response")}let s=r.content.filter((c)=>c.type==="tool-call");if(n=r,await this.recordAssistantMessage(r,i),o){await this.emit({type:"turn-finished",snapshot:this.snapshot(),iteration:this.state.iteration,toolCallCount:0});continue}if(i==="max-tokens"&&s.length===0){if(await this.recoverFromIncompleteMaxTokensTurn()){await this.emit({type:"turn-finished",snapshot:this.snapshot(),iteration:this.state.iteration,toolCallCount:0});continue}throw Error($d)}if(i==="error"&&s.length===0)throw Error(this.state.lastError??"Model stream failed");if(s.length>0)this.maxTokensRecoveryCount=0;if(this.state.pendingToolCalls=s.map((c)=>c.toolCallId),s.length===0){await this.emit({type:"turn-finished",snapshot:this.snapshot(),iteration:this.state.iteration,toolCallCount:0});let c=this.getCompletionReminderMessages();if(c.length>0){for(let f of c)await this.addUserReminderMessage(f);continue}let d=this.finishRun("completed",n);return await this.callAfterRunHooks(d),await this.emit({type:"run-finished",snapshot:this.snapshot(),result:d}),d}let a=await this.executeToolCalls(s);this.state.pendingToolCalls=[];for(let c of a)this.state.messages.push(c),await this.emit({type:"message-added",snapshot:this.snapshot(),message:c});await this.flushPendingHookContexts(),await this.emit({type:"turn-finished",snapshot:this.snapshot(),iteration:this.state.iteration,toolCallCount:s.length});let u=this.findCompletingToolMessage(s,a);if(u){let c=this.finishRun("completed",n,Yd(u)||void 0);return await this.callAfterRunHooks(c),await this.emit({type:"run-finished",snapshot:this.snapshot(),result:c}),c}}throw Error(`Agent runtime exceeded maxIterations (${this.config.maxIterations})`)}catch(t){let n=t instanceof Error?t:Error(String(t)),r=n instanceof en,o=this.abortController.signal.aborted||r?"aborted":"failed",s=n instanceof Ee?"context_window_exceeded":n.message===this.state.lastError?this.state.lastErrorClass:void 0,a=n.message===this.state.lastError&&this.state.lastErrorReported;this.state.status=o,this.state.lastError=n.message,this.state.lastErrorClass=s,this.state.lastErrorReported=a;let u=this.findLastAssistantMessage(),c={agentId:this.state.agentId,agentRole:this.state.agentRole,runId:this.state.runId??de("run"),status:o,iterations:this.state.iteration,outputText:Di(u),messages:W(this.state.messages),usage:ce(this.state.usage),error:o==="failed"?n:void 0};if(this.config.logger?.log?.("Agent loop caught error",{severity:o==="failed"?"error":"warn",agentId:this.state.agentId,agentRole:this.state.agentRole,runId:c.runId,status:o,iteration:this.state.iteration,errorName:n.name,errorMessage:n.message,assistantContentPartCount:u?.content.length??0}),await this.callAfterRunHooks(c),o==="failed")await this.emit({type:"run-failed",snapshot:this.snapshot(),error:n,errorClass:s});else await this.emit({type:"run-finished",snapshot:this.snapshot(),result:c});return c}finally{this.abortController=void 0}}async flushPendingHookContexts(){if(this.pendingHookContexts.length===0)return;let e=this.pendingHookContexts.join(`
74
+ </hook_context>`}function W(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 Gd(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,u=t.totalCost??0,c=Math.max(0,u-a);if(n===0&&r===0&&i===0&&o===0&&s===0&&c===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}:{},...c>0?{cost:c}:{}}}function Yd(e){return e.options?.thinking===!1}function Di(e){if(!e)return"";return e.content.filter((t)=>t.type==="text").map((t)=>t.text).join("")}function Xd(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 Qd(e){if(typeof e==="string")return[he("user",[{type:"text",text:e}])];if(Array.isArray(e))return W(e);return W([e])}class De{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:ce(Yt),lastError:void 0,lastErrorClass:void 0,lastRequestInputTokens:0,lastErrorRetryable:void 0,lastErrorReported:!1,lastFinishReason:void 0};overflowRecoveryAttempted=!1;maxTokensRecoveryCount=0;maxTokensRecoveryAttempted=!1;initialization;abortController;modelSteerController;telemetryProviderId;telemetryModelId;constructor(e){this.telemetryProviderId=Z(e.messageModelInfo?.provider)??("providerId"in e?Z(e.providerId):void 0),this.telemetryModelId=Z(e.messageModelInfo?.id)??("modelId"in e?Z(e.modelId):void 0);let t=Hd(e);this.config={...t,toolExecution:t.toolExecution??"sequential"},this.state.agentId=t.agentId??de("agent"),this.state.agentRole=t.agentRole,this.state.parentAgentId=t.parentAgentId,this.state.messages=W(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 Le?e:new Le(e);this.state.lastError=t.message,this.captureTaskLifecycle(Ri,{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=ce(Yt),this.state.lastError=void 0,this.state.lastErrorClass=void 0,this.state.lastErrorRetryable=void 0,this.state.lastErrorReported=!1,this.state.messages=W(e),this.config={...this.config,initialMessages:W(e)}}snapshot(){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,messages:W(this.state.messages),pendingToolCalls:[...this.state.pendingToolCalls],usage:ce(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.`}getCompletionReminderMessages(){return[this.getCompletionToolReminderMessage(),this.config.completionPolicy?.completionGuard?.()].filter((e)=>Boolean(e))}async addUserReminderMessage(e){let t=he("user",[{type:"text",text:e}],{userRunSpan:0});return this.state.messages.push(t),await this.emit({type:"message-added",snapshot:this.snapshot(),message:t}),t}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=de("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=ce(Yt),this.overflowRecoveryAttempted=!1,this.state.lastRequestInputTokens=0,this.pendingHookContexts=[],this.maxTokensRecoveryCount=0,this.maxTokensRecoveryAttempted=!1;try{await this.callBeforeRunHooks(),await this.emit({type:"run-started",snapshot:this.snapshot()});for(let r of e?Qd(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,await this.emit({type:"turn-started",snapshot:this.snapshot(),iteration:this.state.iteration}),this.resetLastError();let{message:r,finishReason:i,interrupted:o}=await this.generateAssistantMessageWithProviderRetry();if(o&&r.content.length===0){await this.emit({type:"turn-finished",snapshot:this.snapshot(),iteration:this.state.iteration,toolCallCount:0});continue}if(i==="aborted")throw this.normalizeAbortError();if(r.content.length===0){if(i==="error")throw this.state.lastFinishReason=i,Error(this.state.lastError??"Model stream failed");let c=r.metadata?.modelToolActivities;if(!(Array.isArray(c)&&c.length>0)&&i!=="max-tokens")throw this.state.lastFinishReason=i,Error(i==="content-filter"?jd:"Model returned empty response")}let s=r.content.filter((c)=>c.type==="tool-call");if(n=r,await this.recordAssistantMessage(r,i),o){await this.emit({type:"turn-finished",snapshot:this.snapshot(),iteration:this.state.iteration,toolCallCount:0});continue}if(i==="max-tokens"&&s.length===0){if(await this.recoverFromIncompleteMaxTokensTurn()){await this.emit({type:"turn-finished",snapshot:this.snapshot(),iteration:this.state.iteration,toolCallCount:0});continue}throw this.state.lastFinishReason=i,Error($d)}if(i==="error"&&s.length===0)throw this.state.lastFinishReason=i,Error(this.state.lastError??"Model stream failed");if(s.length>0)this.maxTokensRecoveryCount=0;if(this.state.pendingToolCalls=s.map((c)=>c.toolCallId),s.length===0){await this.emit({type:"turn-finished",snapshot:this.snapshot(),iteration:this.state.iteration,toolCallCount:0});let c=this.getCompletionReminderMessages();if(c.length>0){for(let f of c)await this.addUserReminderMessage(f);continue}let d=this.finishRun("completed",n);return await this.callAfterRunHooks(d),await this.emit({type:"run-finished",snapshot:this.snapshot(),result:d}),d}let a=await this.executeToolCalls(s);this.state.pendingToolCalls=[];for(let c of a)this.state.messages.push(c),await this.emit({type:"message-added",snapshot:this.snapshot(),message:c});await this.flushPendingHookContexts(),await this.emit({type:"turn-finished",snapshot:this.snapshot(),iteration:this.state.iteration,toolCallCount:s.length});let u=this.findCompletingToolMessage(s,a);if(u){let c=this.finishRun("completed",n,Xd(u)||void 0);return await this.callAfterRunHooks(c),await this.emit({type:"run-finished",snapshot:this.snapshot(),result:c}),c}}throw Error(`Agent runtime exceeded maxIterations (${this.config.maxIterations})`)}catch(t){let n=t instanceof Error?t:Error(String(t)),r=n instanceof en,o=this.abortController.signal.aborted||r?"aborted":"failed",s=n instanceof Ee?"context_window_exceeded":n.message===this.state.lastError?this.state.lastErrorClass:void 0,a=n.message===this.state.lastError&&this.state.lastErrorReported;this.state.status=o,this.state.lastError=n.message,this.state.lastErrorClass=s,this.state.lastErrorReported=a;let u=this.findLastAssistantMessage(),c={agentId:this.state.agentId,agentRole:this.state.agentRole,runId:this.state.runId??de("run"),status:o,iterations:this.state.iteration,outputText:Di(u),messages:W(this.state.messages),usage:ce(this.state.usage),error:o==="failed"?n:void 0};if(this.config.logger?.log?.("Agent loop caught error",{severity:o==="failed"?"error":"warn",agentId:this.state.agentId,agentRole:this.state.agentRole,runId:c.runId,status:o,iteration:this.state.iteration,errorName:n.name,errorMessage:n.message,assistantContentPartCount:u?.content.length??0}),await this.callAfterRunHooks(c),o==="failed")await this.emit({type:"run-failed",snapshot:this.snapshot(),error:n,errorClass:s});else await this.emit({type:"run-finished",snapshot:this.snapshot(),result:c});return c}finally{this.abortController=void 0}}async flushPendingHookContexts(){if(this.pendingHookContexts.length===0)return;let e=this.pendingHookContexts.join(`
75
75
 
76
- `);this.pendingHookContexts=[];let t=he("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(Xt({source:"RunStart"},t.appendContext))}}async callAfterRunHooks(e){for(let t of this.hooks.afterRun)await t({snapshot:this.snapshot(),result:e})}async recoverFromIncompleteMaxTokensTurn(){if(this.maxTokensRecoveryCount>=Kt)return!1;return this.maxTokensRecoveryCount+=1,await this.emit({type:"status-notice",snapshot:this.snapshot(),message:`output-token limit reached before a tool call — nudging for a more concise response (attempt ${this.maxTokensRecoveryCount}/${Kt})`,metadata:{kind:"max_tokens_recovery",reason:"max_tokens_recovery",phase:"started",iteration:this.state.iteration,attempt:this.maxTokensRecoveryCount,maxRetries:Kt}}),await this.addUserReminderMessage(Ld),!0}async generateAssistantMessageWithProviderRetry(){return await this.withProviderErrorRetry(()=>this.generateAssistantMessageWithOverflowRecovery())}async withProviderErrorRetry(e){let t=0;for(;;){let n=await e();if(t>=Gt||!this.isRetryableProviderErrorTurn(n))return n;t+=1;let r=this.state.lastError;this.resetLastError();let i=Math.min(Dd*2**(t-1),Ud);await this.emit({type:"status-notice",snapshot:this.snapshot(),message:`provider error — retrying (attempt ${t}/${Gt})`,metadata:{kind:"provider_error_retry",reason:"provider_error_retry",phase:"started",iteration:this.state.iteration,attempt:t,maxRetries:Gt,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;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(){let e=await this.generateAssistantMessage();if(this.isRecoverableMaxTokensTurn(e))return await this.retryTruncatedTurnWithCompaction(e);if(!this.isRecoverableOverflowTurn(e))return e;this.overflowRecoveryAttempted=!0;let t=this.state.lastError;if(!this.config.prepareTurn)throw new Ee(Fd,t);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:t}});let n=await this.generateAssistantMessage({overflowRecovery:!0});if(n.finishReason==="error"&&this.state.lastErrorClass==="context_window_exceeded")throw new Ee(Bd,this.state.lastError);return n}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")}isRecoverableMaxTokensTurn(e){if(e.finishReason!=="max-tokens"||this.maxTokensRecoveryAttempted||!this.config.prepareTurn)return!1;if(e.message.content.some((t)=>t.type==="tool-call"))return!1;return!this.hasModelToolActivity(e.message)}hasModelToolActivity(e){let t=e.metadata?.modelToolActivities;return Array.isArray(t)&&t.length>0}async retryTruncatedTurnWithCompaction(e){this.maxTokensRecoveryAttempted=!0;let t={kind:"max_tokens_compaction",reason:"max_tokens_compaction",iteration:this.state.iteration};this.captureTaskLifecycle($e,{phase:"started"});let n;try{await this.emit({type:"status-notice",snapshot:this.snapshot(),message:"response hit the output token limit — compacting and retrying",metadata:{...t,phase:"started"}});let r=await this.prepareModelRequest({overflowRecovery:!0});n=await this.withProviderErrorRetry(()=>this.issuePreparedRequest(r))}catch(r){if(r instanceof Ee)return this.captureTaskLifecycle($e,{phase:"failed",eventType:"nothing_to_compact"}),await this.emit({type:"status-notice",snapshot:this.snapshot(),message:"output-token-limit recovery failed: nothing to compact",metadata:{...t,phase:"failed"}}),e;throw this.captureTaskLifecycle($e,{phase:"failed",eventType:"recovery_threw",error:r}),await this.recordAssistantMessage(e.message,e.finishReason),r}if(this.captureTaskLifecycle($e,{phase:"retried",eventType:n.finishReason}),n.finishReason==="aborted")throw await this.recordAssistantMessage(e.message,e.finishReason),this.normalizeAbortError();if(n.finishReason==="error"&&!n.message.content.some((r)=>r.type==="tool-call")){if(await this.recordAssistantMessage(e.message,e.finishReason),n.message.content.length>0||this.hasModelToolActivity(n.message))await this.recordAssistantMessage(n.message,n.finishReason);throw Error(this.state.lastError??"Model stream failed")}if(n.message.content.length===0&&!this.hasModelToolActivity(n.message))return e;return n}async recordAssistantMessage(e,t){this.state.messages.push(e),await this.emit({type:"message-added",snapshot:this.snapshot(),message:e}),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 issuePreparedRequest(e){let t=new AbortController;this.modelSteerController=t;try{return await this.streamPreparedRequest({...e,startedAt:Date.now()},t)}finally{this.modelSteerController=void 0}}async prepareModelRequest(e){let t=Ei({distinctId:Z(this.config.distinctId),clientName:Z(this.config.clientName),clientVersion:Z(this.config.clientVersion),clineCoreVersion:Z(this.config.clineCoreVersion),sessionId:Z(this.config.sessionId),agentId:this.state.agentId,conversationId:Z(this.config.conversationId),runId:this.state.runId,iteration:this.state.iteration}),n={systemPrompt:this.config.systemPrompt,messages:W(this.state.messages),tools:[...this.tools.values()].map((i)=>({name:i.name,description:i.description,inputSchema:i.inputSchema})),modelTools:this.config.modelTools,signal:this.abortController?.signal,options:Wt(this.config.modelOptions,{metadata:t})},r=Date.now();if(this.state.iteration>1){let i=await this.consumePendingUserMessage();if(i)n={...n,messages:[...n.messages,...W([i])]}}n=await this.prepareTurnForModelRequest(n,e),this.throwIfAborted();for(let i of this.hooks.beforeModel){let o=await i({snapshot:this.snapshot(),request:n});if(this.throwIfAborted(),this.applyStopControl(o),o?.messages)n={...n,messages:W(o.messages)};if(o?.tools)n={...n,tools:[...o.tools]};if(o?.options)n={...n,options:Wt(n.options,o.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,...Wd(n)}),{request:n,startedAt:r}}async generateAssistantMessageForRequest(e,t){let n=await this.prepareModelRequest(t);return await this.streamPreparedRequest(n,e)}async streamPreparedRequest(e,t){let n=ce(this.state.usage),r=()=>Date.now()-e.startedAt,i=e.request;this.throwIfAborted(),this.captureTaskLifecycle(Ii,{durationMs:r(),phase:"provider_request_started"}),i={...i,signal:AbortSignal.any([t.signal,...this.abortController?[this.abortController.signal]:[]])};let o=this.openTaskLifecycleStream(i,r),s=[],a=new Map,u=new Map,c=[],d=[],f=0,h="stop",g,v="",_="";for await(let y of o){if(t.signal.aborted)break;switch(this.throwIfAborted(),y.type){case"text-delta":{v+=y.text;let T=d.at(-1);if(T?.type==="part"&&T.part.type==="text")T.part.text+=y.text;else d.push({type:"part",part:{type:"text",text:y.text}});await this.emit({type:"assistant-text-delta",snapshot:this.snapshot(),iteration:this.state.iteration,text:y.text,accumulatedText:v});break}case"media":{d.push({type:"part",part:{type:"media",media:y.media}}),await this.emit({type:"assistant-media",snapshot:this.snapshot(),iteration:this.state.iteration,media:y.media});break}case"reasoning-delta":{_+=y.text;let T=d.at(-1);if(T?.type==="part"&&T.part.type==="reasoning")T.part.text+=y.text,T.part.redacted=y.redacted??T.part.redacted,T.part.metadata=y.metadata??T.part.metadata;else d.push({type:"part",part:{type:"reasoning",text:y.text,redacted:y.redacted,metadata:y.metadata}});await this.emit({type:"assistant-reasoning-delta",snapshot:this.snapshot(),iteration:this.state.iteration,text:y.text,accumulatedText:_,redacted:y.redacted,metadata:y.metadata});break}case"tool-call-delta":{if(y.execution){let Y={type:"tool-call",toolCallId:y.toolCallId??de("model_tool"),toolName:y.toolName??"tool",input:y.input,metadata:y.metadata,execution:y.execution};u.set(Y.toolCallId,{toolCallId:Y.toolCallId,toolName:Y.toolName,execution:y.execution,input:Y.input}),await this.emit({type:"tool-started",snapshot:this.snapshot(),iteration:this.state.iteration,toolCall:Y});break}let T=y.toolCallId??`tool_${y.index??f}`;if(y.index==null&&y.toolCallId==null)f+=1;let x=a.get(T);if(!x)x={toolCallId:y.toolCallId??de("tool"),inputText:""},a.set(T,x),d.push({type:"tool",key:T});if(y.toolCallId)x.toolCallId=y.toolCallId;if(y.toolName)x.toolName=y.toolName;if(y.input!==void 0)x.inputValue=y.input;if(y.metadata!==void 0)x.metadata=Ui(x.metadata,y.metadata);if(y.inputText)x.inputText=np(x.inputText,y.inputText);break}case"tool-result":{let T=u.get(y.toolCallId),x={...T,toolCallId:y.toolCallId,toolName:y.toolName,execution:y.execution,input:y.input===void 0?T?.input:y.input,output:y.output,isError:y.isError};u.set(y.toolCallId,x);let Y={type:"tool-call",toolCallId:y.toolCallId,toolName:y.toolName,input:x.input,execution:y.execution};await this.emit({type:"tool-finished",snapshot:this.snapshot(),iteration:this.state.iteration,toolCall:Y,message:he("tool",[{type:"tool-result",toolCallId:y.toolCallId,toolName:y.toolName,output:y.output,isError:y.isError,execution:y.execution}])});break}case"usage":{if(typeof y.usage.inputTokens==="number"&&y.usage.inputTokens>0)this.state.lastRequestInputTokens=y.usage.inputTokens;await this.updateUsage(y.usage);break}case"finish":{if(h=y.reason,g=y.requestId,y.error)this.state.lastError=y.error,this.state.lastErrorClass=y.errorClass??$i(y.error),this.state.lastErrorRetryable=y.errorRetryable??Md(y.error),this.state.lastErrorReported=y.errorReported===!0;break}}}this.throwIfAborted();let S=t.signal.aborted;if(S)h="stop";for(let y of d){if(S&&(y.type==="tool"||y.part.type==="reasoning"))continue;if(y.type==="part"){s.push(y.part);continue}let T=a.get(y.key);if(!T?.toolName){c.push({toolCallId:T?.toolCallId??y.key,input:pt(T?.inputText??""),reason:"missing_name"});continue}let x=ep(T);if(x.reason)c.push({toolCallId:T.toolCallId,toolName:T.toolName,input:x.invalidInput,reason:x.reason});s.push({type:"tool-call",toolCallId:T.toolCallId,toolName:T.toolName,input:x.input,metadata:x.parseError?Ui(T.metadata,{inputParseError:x.parseError,rawInputText:T.inputText}):T.metadata})}let k={};if(c.length>0)k.invalidToolCalls=c;if(u.size>0)k.modelToolActivities=[...u.values()];let U=he("assistant",s,Object.keys(k).length>0?k:void 0),re=Kd(n,this.state.usage);if(re)U.metrics=re,this.captureUnexpectedReasoningTokens(i,re);if(this.config.messageModelInfo)U.modelInfo={...this.config.messageModelInfo};for(let y of this.hooks.afterModel){let T=await y({snapshot:this.snapshot(),assistantMessage:U,finishReason:h,...g?{requestId:g}:{}});this.applyStopControl(T)}return{message:U,finishReason:h,interrupted:S}}async*openTaskLifecycleStream(e,t){let n,r="provider_request_started";try{n=await this.config.model.stream(e),this.throwIfAborted(),r="provider_stream_started",this.captureTaskLifecycle(Si,{durationMs:t(),phase:r})}catch(o){if(e.signal?.aborted&&!this.abortController?.signal.aborted)return;if(!e.signal?.aborted&&!this.isAbortError(o))this.captureTaskLifecycleFailure(o,r,t());throw o}let i=!1;try{for await(let o of n){if(!i)i=!0,r="first_chunk_received",this.captureTaskLifecycle(xi,{durationMs:t(),phase:r,eventType:o.type});yield o}}catch(o){if(e.signal?.aborted&&!this.abortController?.signal.aborted)return;if(!e.signal?.aborted&&!this.isAbortError(o))this.captureTaskLifecycleFailure(o,r,t());throw o}}captureTaskLifecycleFailure(e,t,n){this.captureTaskLifecycle(Ci,{durationMs:n,error:e,errorClass:$i(e),phase:t})}captureTaskLifecycle(e,t={}){let n=Z(this.config.sessionId);Pi(this.config.telemetry,{event:e,sessionId:n,ulid:n,agentId:this.state.agentId,conversationId:Z(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 Z(this.config.messageModelInfo?.provider)??this.telemetryProviderId}getTelemetryModelId(){return Z(this.config.messageModelInfo?.id)??this.telemetryModelId}isAbortError(e){return e instanceof Le||this.abortController?.signal.aborted===!0}captureUnexpectedReasoningTokens(e,t){if(!Gd(e)||(t.reasoningTokenCount??0)<=0)return;let n=t.reasoningTokenCount;if(n===void 0)return;Oi(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=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:(o,s)=>{this.emit({type:"status-notice",snapshot:this.snapshot(),message:o,metadata:s})}});if(n){if(!(r?.messages!==void 0&&JSON.stringify(r.messages).length<JSON.stringify(e.messages).length))throw new Ee(jd,this.state.lastError)}if(!r)return e;let i=e;if(r.messages){let o=W(r.messages);i={...i,messages:W(o)}}if(r.systemPrompt!==void 0)i={...i,systemPrompt:r.systemPrompt};return i}async consumePendingUserMessage(){let e=this.config.consumePendingUserMessage;if(!e)return;let t=(await e())?.trim();if(!t)return;let n=he("user",[{type:"text",text:t}],{userRunSpan:0});return this.state.messages.push(n),await this.emit({type:"message-added",snapshot:this.snapshot(),message:n}),n}async updateUsage(e){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)},await this.emit({type:"usage-updated",snapshot:this.snapshot(),usage:ce(this.state.usage)})}async executeToolCalls(e){this.pendingHookContexts=[];let t=[];for(let r of e)t.push(await this.prepareToolExecution(r));let n=[];for(let r=0;r<t.length;){let i=t[r];if((i.tool?.executionMode??this.config.toolExecution)==="sequential"){n.push(await this.executePreparedTool(i)),r+=1;continue}let s=r;while(r<t.length&&(t[r].tool?.executionMode??this.config.toolExecution)==="parallel")r+=1;n.push(...await Promise.all(t.slice(s,r).map((a)=>this.executePreparedTool(a))))}return n}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=i?.toolSource&&typeof i.toolSource==="object"&&!Array.isArray(i.toolSource)?i.toolSource:void 0;if(o?.executionMode==="provider")r=`Tool execution is disabled for provider ${typeof o.providerId==="string"?o.providerId:"provider"}`;if(t&&!r)n=it(n,t.inputSchema);let s;if(t&&!r)for(let a of this.hooks.beforeTool){let u=await a({snapshot:this.snapshot(),tool:t,toolCall:{...e,input:n},input:n});if(u?.input!==void 0)n=u.input;if(u?.policy)s={...s,...u.policy};if(u?.appendContext?.trim())this.pendingHookContexts.push(Xt({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 a={...Hd(e.toolName,this.config.toolPolicies),...s};if(a.enabled===!1)r=`Tool "${e.toolName}" is disabled by policy`;else if(a.autoApprove===!1){let u=await this.requestToolApproval(e,n,a);if(!u.approved)r=`${u.reason??"Tool was not executed"} -- ${Ti}`}}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;await this.emit({type:"tool-started",snapshot:this.snapshot(),iteration:this.state.iteration,toolCall:e.toolCall});let n;if(e.skipReason)n={output:{error:e.skipReason},isError:!0};else if(!e.tool)n={output:{error:`Unknown tool: ${e.toolCall.toolName}`},isError:!0};else try{n={output:await e.tool.execute(e.input,{sessionId:this.config.sessionId,agentId:this.state.agentId,conversationId:this.config.conversationId,runId:this.state.runId??de("run"),iteration:this.state.iteration,toolCallId:e.toolCall.toolCallId,signal:this.abortController?.signal,metadata:this.config.toolContextMetadata,snapshot:this.snapshot(),emitUpdate:(a)=>{this.emit({type:"tool-updated",snapshot:this.snapshot(),iteration:this.state.iteration,toolCall:e.toolCall,update:a})}})}}catch(s){n={output:{error:s instanceof Error?s.message:String(s)},isError:!0}}let r=new Date,i=Math.max(0,r.getTime()-t.getTime());if(e.tool)for(let s of this.hooks.afterTool){let a=await s({snapshot:this.snapshot(),tool:e.tool,toolCall:e.toolCall,input:e.input,result:n,startedAt:t,endedAt:r,durationMs:i});if(a?.appendContext?.trim())this.pendingHookContexts.push(Xt({source:"PostToolUse",toolCall:e.toolCall},a.appendContext));if(this.applyStopControl(a),a?.result)n=a.result}let o=he("tool",[{type:"tool-result",toolCallId:e.toolCall.toolCallId,toolName:e.toolCall.toolName,output:n.output,isError:n.isError}]);return await this.emit({type:"tool-finished",snapshot:this.snapshot(),iteration:this.state.iteration,toolCall:e.toolCall,message:o}),o}finishRun(e,t,n){return this.state.status=e,{agentId:this.state.agentId,agentRole:this.state.agentRole,runId:this.state.runId??de("run"),status:e,iterations:this.state.iteration,outputText:n??Di(t??this.findLastAssistantMessage()),messages:W(this.state.messages),usage:ce(this.state.usage)}}findLastAssistantMessage(){return[...this.state.messages].reverse().find((e)=>e.role==="assistant")}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")}async emit(e){let t=Qd(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)Ni(this.config.telemetry,{component:"agents",operation:"agent.run",error:e.error,severity:"error",handled:!1,context:{...t,providerId:this.getTelemetryProviderId(),modelId:this.getTelemetryModelId()}});break;default:this.config.logger?.debug?.("Agent event",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}for(let n of this.listeners)n(e);for(let n of this.hooks.onEvent)await n(e)}applyStopControl(e){if(!e?.stop)return;if(e.reason)this.state.lastError=e.reason;throw new en(e.reason)}}function Qd(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 Ui(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 ep(e){if(e.inputValue!==void 0)return{input:e.inputValue,invalidInput:pt(JSON.stringify(e.inputValue))};if(!e.inputText.trim())return{input:{},invalidInput:{}};let t=tp(e.inputText);if(t.ok)return{input:t.value,invalidInput:pt(e.inputText)};return{input:{},invalidInput:pt(e.inputText,t.error),parseError:`Tool call ${e.toolName??e.toolCallId} emitted invalid JSON arguments: ${t.error}`,reason:"invalid_arguments"}}function pt(e,t){if(!e.trim())return{};return t?{rawInputText:e,parseError:t}:{rawInputText:e}}function tp(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 np(e,t){if(!e)return t;let n=t.trimStart();if(n.startsWith("{")||n.startsWith("["))return t;return e+t}function rp(e){return new De(e)}var ip=De;function op(e){return new De(e)}export{ip as Agent,De as AgentRuntime,Le as AgentRuntimeAbortError,op as createAgent,rp as createAgentRuntime,Pd as createTool};
76
+ `);this.pendingHookContexts=[];let t=he("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(Xt({source:"RunStart"},t.appendContext))}}async callAfterRunHooks(e){for(let t of this.hooks.afterRun)await t({snapshot:this.snapshot(),result:e})}async recoverFromIncompleteMaxTokensTurn(){if(this.maxTokensRecoveryCount>=Kt)return!1;return this.maxTokensRecoveryCount+=1,await this.emit({type:"status-notice",snapshot:this.snapshot(),message:`output-token limit reached before a tool call — nudging for a more concise response (attempt ${this.maxTokensRecoveryCount}/${Kt})`,metadata:{kind:"max_tokens_recovery",reason:"max_tokens_recovery",phase:"started",iteration:this.state.iteration,attempt:this.maxTokensRecoveryCount,maxRetries:Kt}}),await this.addUserReminderMessage(Ld),!0}async generateAssistantMessageWithProviderRetry(){return await this.withProviderErrorRetry(()=>this.generateAssistantMessageWithOverflowRecovery())}async withProviderErrorRetry(e){let t=0;for(;;){let n=await e();if(t>=Gt||!this.isRetryableProviderErrorTurn(n))return n;t+=1;let r=this.state.lastError;this.resetLastError();let i=Math.min(Dd*2**(t-1),Ud);await this.emit({type:"status-notice",snapshot:this.snapshot(),message:`provider error — retrying (attempt ${t}/${Gt})`,metadata:{kind:"provider_error_retry",reason:"provider_error_retry",phase:"started",iteration:this.state.iteration,attempt:t,maxRetries:Gt,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;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(){let e=await this.generateAssistantMessage();if(this.isRecoverableMaxTokensTurn(e))return await this.retryTruncatedTurnWithCompaction(e);if(!this.isRecoverableOverflowTurn(e))return e;this.overflowRecoveryAttempted=!0;let t=this.state.lastError;if(!this.config.prepareTurn)throw new Ee(qd,t);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:t}});let n=await this.generateAssistantMessage({overflowRecovery:!0});if(n.finishReason==="error"&&this.state.lastErrorClass==="context_window_exceeded")throw new Ee(Fd,this.state.lastError);return n}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")}isRecoverableMaxTokensTurn(e){if(e.finishReason!=="max-tokens"||this.maxTokensRecoveryAttempted||!this.config.prepareTurn)return!1;if(e.message.content.some((t)=>t.type==="tool-call"))return!1;return!this.hasModelToolActivity(e.message)}hasModelToolActivity(e){let t=e.metadata?.modelToolActivities;return Array.isArray(t)&&t.length>0}async retryTruncatedTurnWithCompaction(e){this.maxTokensRecoveryAttempted=!0;let t={kind:"max_tokens_compaction",reason:"max_tokens_compaction",iteration:this.state.iteration};this.captureTaskLifecycle($e,{phase:"started"});let n;try{await this.emit({type:"status-notice",snapshot:this.snapshot(),message:"response hit the output token limit — compacting and retrying",metadata:{...t,phase:"started"}});let r=await this.prepareModelRequest({overflowRecovery:!0});n=await this.withProviderErrorRetry(()=>this.issuePreparedRequest(r))}catch(r){if(r instanceof Ee)return this.captureTaskLifecycle($e,{phase:"failed",eventType:"nothing_to_compact"}),await this.emit({type:"status-notice",snapshot:this.snapshot(),message:"output-token-limit recovery failed: nothing to compact",metadata:{...t,phase:"failed"}}),e;throw this.captureTaskLifecycle($e,{phase:"failed",eventType:"recovery_threw",error:r}),await this.recordAssistantMessage(e.message,e.finishReason),r}if(this.captureTaskLifecycle($e,{phase:"retried",eventType:n.finishReason}),n.finishReason==="aborted")throw await this.recordAssistantMessage(e.message,e.finishReason),this.normalizeAbortError();if(n.finishReason==="error"&&!n.message.content.some((r)=>r.type==="tool-call")){if(await this.recordAssistantMessage(e.message,e.finishReason),n.message.content.length>0||this.hasModelToolActivity(n.message))await this.recordAssistantMessage(n.message,n.finishReason);throw Error(this.state.lastError??"Model stream failed")}if(n.message.content.length===0&&!this.hasModelToolActivity(n.message))return e;return n}async recordAssistantMessage(e,t){this.state.messages.push(e),await this.emit({type:"message-added",snapshot:this.snapshot(),message:e}),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 issuePreparedRequest(e){let t=new AbortController;this.modelSteerController=t;try{return await this.streamPreparedRequest({...e,startedAt:Date.now()},t)}finally{this.modelSteerController=void 0}}async prepareModelRequest(e){let t=Ei({distinctId:Z(this.config.distinctId),clientName:Z(this.config.clientName),clientVersion:Z(this.config.clientVersion),clineCoreVersion:Z(this.config.clineCoreVersion),sessionId:Z(this.config.sessionId),agentId:this.state.agentId,conversationId:Z(this.config.conversationId),runId:this.state.runId,iteration:this.state.iteration}),n={systemPrompt:this.config.systemPrompt,messages:W(this.state.messages),tools:[...this.tools.values()].map((i)=>({name:i.name,description:i.description,inputSchema:i.inputSchema})),modelTools:this.config.modelTools,signal:this.abortController?.signal,options:Wt(this.config.modelOptions,{metadata:t})},r=Date.now();if(this.state.iteration>1){let i=await this.consumePendingUserMessage();if(i)n={...n,messages:[...n.messages,...W([i])]}}n=await this.prepareTurnForModelRequest(n,e),this.throwIfAborted();for(let i of this.hooks.beforeModel){let o=await i({snapshot:this.snapshot(),request:n});if(this.throwIfAborted(),this.applyStopControl(o),o?.messages)n={...n,messages:W(o.messages)};if(o?.tools)n={...n,tools:[...o.tools]};if(o?.options)n={...n,options:Wt(n.options,o.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,...Jd(n)}),{request:n,startedAt:r}}async generateAssistantMessageForRequest(e,t){let n=await this.prepareModelRequest(t);return await this.streamPreparedRequest(n,e)}async streamPreparedRequest(e,t){let n=ce(this.state.usage),r=()=>Date.now()-e.startedAt,i=e.request;this.throwIfAborted(),this.captureTaskLifecycle(Ii,{durationMs:r(),phase:"provider_request_started"}),i={...i,signal:AbortSignal.any([t.signal,...this.abortController?[this.abortController.signal]:[]])};let o=this.openTaskLifecycleStream(i,r),s=[],a=new Map,u=new Map,c=[],d=[],f=0,h="stop",g,v="",_="";for await(let y of o){if(t.signal.aborted)break;switch(this.throwIfAborted(),y.type){case"text-delta":{v+=y.text;let T=d.at(-1);if(T?.type==="part"&&T.part.type==="text")T.part.text+=y.text;else d.push({type:"part",part:{type:"text",text:y.text}});await this.emit({type:"assistant-text-delta",snapshot:this.snapshot(),iteration:this.state.iteration,text:y.text,accumulatedText:v});break}case"media":{d.push({type:"part",part:{type:"media",media:y.media}}),await this.emit({type:"assistant-media",snapshot:this.snapshot(),iteration:this.state.iteration,media:y.media});break}case"reasoning-delta":{_+=y.text;let T=d.at(-1);if(T?.type==="part"&&T.part.type==="reasoning")T.part.text+=y.text,T.part.redacted=y.redacted??T.part.redacted,T.part.metadata=y.metadata??T.part.metadata;else d.push({type:"part",part:{type:"reasoning",text:y.text,redacted:y.redacted,metadata:y.metadata}});await this.emit({type:"assistant-reasoning-delta",snapshot:this.snapshot(),iteration:this.state.iteration,text:y.text,accumulatedText:_,redacted:y.redacted,metadata:y.metadata});break}case"tool-call-delta":{if(y.execution){let Y={type:"tool-call",toolCallId:y.toolCallId??de("model_tool"),toolName:y.toolName??"tool",input:y.input,metadata:y.metadata,execution:y.execution};u.set(Y.toolCallId,{toolCallId:Y.toolCallId,toolName:Y.toolName,execution:y.execution,input:Y.input}),await this.emit({type:"tool-started",snapshot:this.snapshot(),iteration:this.state.iteration,toolCall:Y});break}let T=y.toolCallId??`tool_${y.index??f}`;if(y.index==null&&y.toolCallId==null)f+=1;let x=a.get(T);if(!x)x={toolCallId:y.toolCallId??de("tool"),inputText:""},a.set(T,x),d.push({type:"tool",key:T});if(y.toolCallId)x.toolCallId=y.toolCallId;if(y.toolName)x.toolName=y.toolName;if(y.input!==void 0)x.inputValue=y.input;if(y.metadata!==void 0)x.metadata=Ui(x.metadata,y.metadata);if(y.inputText)x.inputText=rp(x.inputText,y.inputText);break}case"tool-result":{let T=u.get(y.toolCallId),x={...T,toolCallId:y.toolCallId,toolName:y.toolName,execution:y.execution,input:y.input===void 0?T?.input:y.input,output:y.output,isError:y.isError};u.set(y.toolCallId,x);let Y={type:"tool-call",toolCallId:y.toolCallId,toolName:y.toolName,input:x.input,execution:y.execution};await this.emit({type:"tool-finished",snapshot:this.snapshot(),iteration:this.state.iteration,toolCall:Y,message:he("tool",[{type:"tool-result",toolCallId:y.toolCallId,toolName:y.toolName,output:y.output,isError:y.isError,execution:y.execution}])});break}case"usage":{if(typeof y.usage.inputTokens==="number"&&y.usage.inputTokens>0)this.state.lastRequestInputTokens=y.usage.inputTokens;await this.updateUsage(y.usage);break}case"finish":{if(h=y.reason,g=y.requestId,y.error)this.state.lastError=y.error,this.state.lastErrorClass=y.errorClass??$i(y.error),this.state.lastErrorRetryable=y.errorRetryable??Md(y.error),this.state.lastErrorReported=y.errorReported===!0;break}}}this.throwIfAborted();let S=t.signal.aborted;if(S)h="stop";for(let y of d){if(S&&(y.type==="tool"||y.part.type==="reasoning"))continue;if(y.type==="part"){s.push(y.part);continue}let T=a.get(y.key);if(!T?.toolName){c.push({toolCallId:T?.toolCallId??y.key,input:pt(T?.inputText??""),reason:"missing_name"});continue}let x=tp(T);if(x.reason)c.push({toolCallId:T.toolCallId,toolName:T.toolName,input:x.invalidInput,reason:x.reason});s.push({type:"tool-call",toolCallId:T.toolCallId,toolName:T.toolName,input:x.input,metadata:x.parseError?Ui(T.metadata,{inputParseError:x.parseError,rawInputText:T.inputText}):T.metadata})}let k={};if(c.length>0)k.invalidToolCalls=c;if(u.size>0)k.modelToolActivities=[...u.values()];let U=he("assistant",s,Object.keys(k).length>0?k:void 0),re=Gd(n,this.state.usage);if(re)U.metrics=re,this.captureUnexpectedReasoningTokens(i,re);if(this.config.messageModelInfo)U.modelInfo={...this.config.messageModelInfo};for(let y of this.hooks.afterModel){let T=await y({snapshot:this.snapshot(),assistantMessage:U,finishReason:h,...g?{requestId:g}:{}});this.applyStopControl(T)}return{message:U,finishReason:h,interrupted:S}}async*openTaskLifecycleStream(e,t){let n,r="provider_request_started";try{n=await this.config.model.stream(e),this.throwIfAborted(),r="provider_stream_started",this.captureTaskLifecycle(Si,{durationMs:t(),phase:r})}catch(o){if(e.signal?.aborted&&!this.abortController?.signal.aborted)return;if(!e.signal?.aborted&&!this.isAbortError(o))this.captureTaskLifecycleFailure(o,r,t());throw o}let i=!1;try{for await(let o of n){if(!i)i=!0,r="first_chunk_received",this.captureTaskLifecycle(xi,{durationMs:t(),phase:r,eventType:o.type});yield o}}catch(o){if(e.signal?.aborted&&!this.abortController?.signal.aborted)return;if(!e.signal?.aborted&&!this.isAbortError(o))this.captureTaskLifecycleFailure(o,r,t());throw o}}captureTaskLifecycleFailure(e,t,n){this.captureTaskLifecycle(Ci,{durationMs:n,error:e,errorClass:$i(e),phase:t})}captureTaskLifecycle(e,t={}){let n=Z(this.config.sessionId);Pi(this.config.telemetry,{event:e,sessionId:n,ulid:n,agentId:this.state.agentId,conversationId:Z(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 Z(this.config.messageModelInfo?.provider)??this.telemetryProviderId}getTelemetryModelId(){return Z(this.config.messageModelInfo?.id)??this.telemetryModelId}isAbortError(e){return e instanceof Le||this.abortController?.signal.aborted===!0}captureUnexpectedReasoningTokens(e,t){if(!Yd(e)||(t.reasoningTokenCount??0)<=0)return;let n=t.reasoningTokenCount;if(n===void 0)return;Oi(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=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:(o,s)=>{this.emit({type:"status-notice",snapshot:this.snapshot(),message:o,metadata:s})}});if(n){if(!(r?.messages!==void 0&&JSON.stringify(r.messages).length<JSON.stringify(e.messages).length))throw new Ee(Bd,this.state.lastError)}if(!r)return e;let i=e;if(r.messages){let o=W(r.messages);i={...i,messages:W(o)}}if(r.systemPrompt!==void 0)i={...i,systemPrompt:r.systemPrompt};return i}async consumePendingUserMessage(){let e=this.config.consumePendingUserMessage;if(!e)return;let t=(await e())?.trim();if(!t)return;let n=he("user",[{type:"text",text:t}],{userRunSpan:0});return this.state.messages.push(n),await this.emit({type:"message-added",snapshot:this.snapshot(),message:n}),n}async updateUsage(e){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)},await this.emit({type:"usage-updated",snapshot:this.snapshot(),usage:ce(this.state.usage)})}async executeToolCalls(e){this.pendingHookContexts=[];let t=[];for(let r of e)t.push(await this.prepareToolExecution(r));let n=[];for(let r=0;r<t.length;){let i=t[r];if((i.tool?.executionMode??this.config.toolExecution)==="sequential"){n.push(await this.executePreparedTool(i)),r+=1;continue}let s=r;while(r<t.length&&(t[r].tool?.executionMode??this.config.toolExecution)==="parallel")r+=1;n.push(...await Promise.all(t.slice(s,r).map((a)=>this.executePreparedTool(a))))}return n}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=i?.toolSource&&typeof i.toolSource==="object"&&!Array.isArray(i.toolSource)?i.toolSource:void 0;if(o?.executionMode==="provider")r=`Tool execution is disabled for provider ${typeof o.providerId==="string"?o.providerId:"provider"}`;if(t&&!r)n=it(n,t.inputSchema);let s;if(t&&!r)for(let a of this.hooks.beforeTool){let u=await a({snapshot:this.snapshot(),tool:t,toolCall:{...e,input:n},input:n});if(u?.input!==void 0)n=u.input;if(u?.policy)s={...s,...u.policy};if(u?.appendContext?.trim())this.pendingHookContexts.push(Xt({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 a={...Vd(e.toolName,this.config.toolPolicies),...s};if(a.enabled===!1)r=`Tool "${e.toolName}" is disabled by policy`;else if(a.autoApprove===!1){let u=await this.requestToolApproval(e,n,a);if(!u.approved)r=`${u.reason??"Tool was not executed"} -- ${Ti}`}}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;await this.emit({type:"tool-started",snapshot:this.snapshot(),iteration:this.state.iteration,toolCall:e.toolCall});let n;if(e.skipReason)n={output:{error:e.skipReason},isError:!0};else if(!e.tool)n={output:{error:`Unknown tool: ${e.toolCall.toolName}`},isError:!0};else try{n={output:await e.tool.execute(e.input,{sessionId:this.config.sessionId,agentId:this.state.agentId,conversationId:this.config.conversationId,runId:this.state.runId??de("run"),iteration:this.state.iteration,toolCallId:e.toolCall.toolCallId,signal:this.abortController?.signal,metadata:this.config.toolContextMetadata,snapshot:this.snapshot(),emitUpdate:(a)=>{this.emit({type:"tool-updated",snapshot:this.snapshot(),iteration:this.state.iteration,toolCall:e.toolCall,update:a})}})}}catch(s){n={output:{error:s instanceof Error?s.message:String(s)},isError:!0}}let r=new Date,i=Math.max(0,r.getTime()-t.getTime());if(e.tool)for(let s of this.hooks.afterTool){let a=await s({snapshot:this.snapshot(),tool:e.tool,toolCall:e.toolCall,input:e.input,result:n,startedAt:t,endedAt:r,durationMs:i});if(a?.appendContext?.trim())this.pendingHookContexts.push(Xt({source:"PostToolUse",toolCall:e.toolCall},a.appendContext));if(this.applyStopControl(a),a?.result)n=a.result}let o=he("tool",[{type:"tool-result",toolCallId:e.toolCall.toolCallId,toolName:e.toolCall.toolName,output:n.output,isError:n.isError}]);return await this.emit({type:"tool-finished",snapshot:this.snapshot(),iteration:this.state.iteration,toolCall:e.toolCall,message:o}),o}finishRun(e,t,n){return this.state.status=e,{agentId:this.state.agentId,agentRole:this.state.agentRole,runId:this.state.runId??de("run"),status:e,iterations:this.state.iteration,outputText:n??Di(t??this.findLastAssistantMessage()),messages:W(this.state.messages),usage:ce(this.state.usage)}}findLastAssistantMessage(){return[...this.state.messages].reverse().find((e)=>e.role==="assistant")}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")}async emit(e){let t=ep(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)Ni(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:this.config.logger?.debug?.("Agent event",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}for(let n of this.listeners)n(e);for(let n of this.hooks.onEvent)await n(e)}applyStopControl(e){if(!e?.stop)return;if(e.reason)this.state.lastError=e.reason;throw new en(e.reason)}}function ep(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 Ui(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 tp(e){if(e.inputValue!==void 0)return{input:e.inputValue,invalidInput:pt(JSON.stringify(e.inputValue))};if(!e.inputText.trim())return{input:{},invalidInput:{}};let t=np(e.inputText);if(t.ok)return{input:t.value,invalidInput:pt(e.inputText)};return{input:{},invalidInput:pt(e.inputText,t.error),parseError:`Tool call ${e.toolName??e.toolCallId} emitted invalid JSON arguments: ${t.error}`,reason:"invalid_arguments"}}function pt(e,t){if(!e.trim())return{};return t?{rawInputText:e,parseError:t}:{rawInputText:e}}function np(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 rp(e,t){if(!e)return t;let n=t.trimStart();if(n.startsWith("{")||n.startsWith("["))return t;return e+t}function ip(e){return new De(e)}var op=De;function sp(e){return new De(e)}export{op as Agent,De as AgentRuntime,Le as AgentRuntimeAbortError,sp as createAgent,ip as createAgentRuntime,Pd as createTool};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cline/agents",
3
- "version": "0.0.87",
3
+ "version": "0.0.88",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "https://github.com/cline/cline",
@@ -8,8 +8,8 @@
8
8
  },
9
9
  "main": "dist/index.js",
10
10
  "dependencies": {
11
- "@cline/llms": "0.0.87",
12
- "@cline/shared": "0.0.87",
11
+ "@cline/llms": "0.0.88",
12
+ "@cline/shared": "0.0.88",
13
13
  "nanoid": "^5.1.7"
14
14
  },
15
15
  "exports": {