@cerebriline/agents 4.100.253 → 4.100.254

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.
@@ -706,6 +706,17 @@ export declare class AgentRuntime {
706
706
  private consumePendingUserMessage;
707
707
  private updateUsage;
708
708
  private executeToolCalls;
709
+ /**
710
+ * Put the turn's notes on its last tool result, and return any left over.
711
+ *
712
+ * Taken only on a turn that carries on, as they always were: the repetition
713
+ * nudge, whatever the host noticed while the tools ran, and the nudge for a
714
+ * call that was cut. A looping turn that still calls tools is the shape
715
+ * every turn-level detector is blind to (`kessj` message 30: one paragraph
716
+ * written seven times in sixty-five, and the run read as productive), which
717
+ * is why the repetition check is here at all.
718
+ */
719
+ private attachTurnNotes;
709
720
  private findCompletingToolMessage;
710
721
  private prepareToolExecution;
711
722
  private requestToolApproval;
@@ -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,EAKX,YAAY,EAEZ,UAAU,EAKV,cAAc,EACd,iBAAiB,EAEjB,yBAAyB,EAOzB,kBAAkB,IAAI,sBAAsB,EAO5C,iBAAiB,EAEjB,MAAM,eAAe,CAAC;AA2FvB,kEAAkE;AAClE,eAAO,MAAM,wBAAwB,QAAS,CAAC;AAE/C;;;;;;;GAOG;AACH,wBAAgB,qBAAqB,CACpC,SAAS,EAAE,MAAM,EACjB,QAAQ,EAAE,MAAM,EAChB,UAAU,EAAE,MAAM,EAClB,SAAS,EAAE,MAAM,EACjB,WAAW,EAAE,OAAO,GAClB,MAAM,CAmBR;AAYD;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,+BAA+B,IAAI,CAAC;AA+MjD;;;;;;;;;;;GAWG;AACH,wBAAgB,0BAA0B,CACzC,SAAS,CAAC,EAAE,iBAAiB,GAC3B,MAAM,CAcR;AAYD;;;;;;;;;;;;;;;;;GAiBG;AACH,eAAO,MAAM,+BAA+B,IAAI,CAAC;AAEjD;;;;;;;;;;;;;;;;;;GAkBG;AACH,eAAO,MAAM,sCAAsC,IAAI,CAAC;AAExD;;;;;;;;;;;;;;;;;;;GAmBG;AACH,eAAO,MAAM,mCAAmC,OAAO,CAAC;AA0BxD;;;;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;AAiJlC,qBAAa,sBAAuB,SAAQ,KAAK;IAChD,QAAQ,CAAC,MAAM,CAAC,EAAE,OAAO,CAAC;gBAEd,MAAM,CAAC,EAAE,OAAO;CAa5B;AAuND;;;;;;;;;;;;;;GAcG;AACH,eAAO,MAAM,+BAA+B,IAAI,CAAC;AAEjD;;;;;;;;GAQG;AACH,wBAAgB,4BAA4B,CAAC,MAAM,EAAE;IACpD,aAAa,CAAC,EAAE,YAAY,GAAG,UAAU,CAAC;IAC1C,oBAAoB,CAAC,EAAE,MAAM,CAAC;CAC9B,GAAG,MAAM,CAST;AAED,qBAAa,YAAY;IACxB,OAAO,CAAC,MAAM,CAGU;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,CA6CpB;IACF;;;OAGG;IACH,OAAO,CAAC,qBAAqB,CAAgC;IAC7D,uDAAuD;IACvD,OAAO,CAAC,yBAAyB,CAAS;IAC1C;;;OAGG;IACH,OAAO,CAAC,iBAAiB,CAAqB;IAC9C;;;;;;;;OAQG;IACH,OAAO,CAAC,qBAAqB,CAAS;IACtC;;;OAGG;IACH,OAAO,CAAC,sBAAsB,CAAS;IACvC,yFAAyF;IACzF,OAAO,CAAC,2BAA2B,CAAK;IACxC;;;;;;OAMG;IACH,OAAO,CAAC,oBAAoB,CAAS;IACrC,gEAAgE;IAChE,OAAO,CAAC,iBAAiB,CAAS;IAClC;;;;;;;OAOG;IACH,OAAO,CAAC,gBAAgB,CAAqB;IAC7C;;;;;;OAMG;IACH,OAAO,CAAC,gBAAgB,CAAS;IACjC;;;;;;;OAOG;IACH,OAAO,CAAC,0BAA0B,CAAK;IACvC,uEAAuE;IACvE,OAAO,CAAC,8BAA8B,CAAK;IAC3C,+DAA+D;IAC/D,OAAO,CAAC,wBAAwB,CAAS;IACzC;;;;;;;;;;;OAWG;IACH,OAAO,CAAC,wBAAwB,CAAqB;IACrD;;;;;;OAMG;IACH,OAAO,CAAC,gBAAgB,CAAS;IACjC;;;;OAIG;IACH,OAAO,CAAC,gBAAgB,CAA+B;IACvD,OAAO,CAAC,qBAAqB,CAAS;IACtC;;;;OAIG;IACH,OAAO,CAAC,QAAQ,CAAC,gBAAgB,CAG7B;IACJ,yEAAyE;IACzE,OAAO,CAAC,QAAQ,CAAC,0BAA0B,CAA+B;IAC1E,qEAAqE;IACrE,OAAO,CAAC,QAAQ,CAAC,eAAe,CAG5B;IACJ,2EAA2E;IAC3E,OAAO,CAAC,QAAQ,CAAC,0BAA0B,CAGvC;IACJ;;;;;OAKG;IACH,OAAO,CAAC,mBAAmB,CAAS;IACpC,qFAAqF;IACrF,OAAO,CAAC,2BAA2B,CAAK;IACxC;;;OAGG;IACH,OAAO,CAAC,oBAAoB,CAAK;IACjC,+EAA+E;IAC/E,OAAO,CAAC,mBAAmB,CAAK;IAChC;;;;;;OAMG;IACH,OAAO,CAAC,wBAAwB,CAAqB;IACrD,OAAO,CAAC,cAAc,CAAC,CAAgB;IACvC,OAAO,CAAC,eAAe,CAAC,CAAkB;IAC1C;;;;OAIG;IACH,OAAO,CAAC,mBAAmB,CAAK;IAChC;;;;;OAKG;IACH,OAAO,CAAC,sBAAsB,CAAC,CAAS;IACxC,2EAA2E;IAC3E,OAAO,CAAC,iBAAiB,CAAC,CAAoB;IAC9C,mEAAmE;IACnE,OAAO,CAAC,mBAAmB,CAAK;IAChC,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;IAsBhC,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;;;;;;;;;;;;;;;;;;;OAmBG;IACH,QAAQ,IAAI,yBAAyB;YAsBvB,iBAAiB;YAKjB,UAAU;IAkBxB,OAAO,CAAC,aAAa;IAarB,OAAO,CAAC,8BAA8B;IAUtC,OAAO,CAAC,gCAAgC;IAUxC;;;;;;;OAOG;YACW,qBAAqB;IAYnC;;;;OAIG;IACH,OAAO,CAAC,6BAA6B;IAarC;;;OAGG;YACW,yBAAyB;IA0GvC;;;;;;;;;;;;;OAaG;IACH,OAAO,CAAC,kBAAkB;IA6B1B;;;;;;;;;;;;;;;;OAgBG;IACH,OAAO,CAAC,qBAAqB;IA+G7B,+DAA+D;IAC/D,OAAO,CAAC,aAAa;IAIrB;;;;;;;OAOG;IACH,OAAO,CAAC,yBAAyB;IAUjC;;;;;;;OAOG;IACH;;;;;;OAMG;IACH,OAAO,CAAC,wBAAwB;IAIhC;;;;;;OAMG;IACH;;;;;;OAMG;IACH,OAAO,CAAC,sBAAsB;IAoB9B;;;;OAIG;YACW,oBAAoB;IAmClC,+EAA+E;IAC/E,OAAO,CAAC,iBAAiB;YAQX,sBAAsB;IAkHpC;;;;;;;;;;;;;;;;;;;OAmBG;IACH,OAAO,CAAC,iBAAiB;IAazB,OAAO,CAAC,uBAAuB;YAOjB,sBAAsB;YA4CtB,OAAO;IA4xBrB;;;OAGG;YACW,wBAAwB;YAoCxB,kBAAkB;YAgBlB,iBAAiB;IAM/B;;;;;;;;;;;;;;;;;OAiBG;YACW,wCAAwC;IA4ItD;;;;;;;;;;;;;;;;OAgBG;YACW,yCAAyC;IA8BvD;;;;;;OAMG;YACW,sBAAsB;IAwCpC;;;;;;;;;;OAUG;IACH,OAAO,CAAC,4BAA4B;IA+BpC;;;;;;;OAOG;IACH,OAAO,CAAC,cAAc;IAOtB;;;OAGG;YACW,cAAc;IAkB5B;;;;;OAKG;YACW,4CAA4C;IA0D1D;;;;;;;;;;;;;;;;;OAiBG;YACW,yBAAyB;IA8BvC;;;;;;;;;;;;;;;;;;;;;;;OAuBG;IACH,OAAO,CAAC,sBAAsB;IAY9B,OAAO,CAAC,eAAe;IAMvB;;;;;;;;;;;OAWG;YACW,kBAAkB;IAyChC;;;;;;;;;;;;;OAaG;YACW,0BAA0B;IAwFxC,OAAO,CAAC,yBAAyB;IAiBjC,2EAA2E;IAC3E,OAAO,CAAC,oBAAoB;IAK5B,kEAAkE;YACpD,sBAAsB;YAkCtB,wBAAwB;IAiBtC,4EAA4E;YAC9D,mBAAmB;YA6FnB,kCAAkC;IAehD;;;;OAIG;YACW,qBAAqB;YAwapB,uBAAuB;IA+DtC,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;YAuF1B,yBAAyB;YAwBzB,WAAW;YAwCX,gBAAgB;IA0E9B,OAAO,CAAC,yBAAyB;YAsBnB,oBAAoB;YA6GpB,mBAAmB;YAwCnB,mBAAmB;IA8IjC,OAAO,CAAC,SAAS;IAoBjB,OAAO,CAAC,wBAAwB;IAMhC;;;;;;OAMG;YACW,kBAAkB;IAwDhC,2DAA2D;IAC3D,OAAO,CAAC,iBAAiB;IAazB;;;;;;OAMG;YACW,eAAe;IAqB7B,OAAO,CAAC,cAAc;IAMtB,OAAO,CAAC,mBAAmB;IAW3B;;;;;;;;;;OAUG;IACH,OAAO,CAAC,QAAQ,CAAC,WAAW,CAAgD;IAE5E,OAAO,CAAC,eAAe;IAevB,uEAAuE;IACvE,OAAO,CAAC,aAAa;IAQrB;;;;;;;;;OASG;IACH,OAAO,CAAC,KAAK;YAKC,IAAI;IAmHlB,OAAO,CAAC,gBAAgB;CAWxB;AA0DD,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,EAKX,YAAY,EAEZ,UAAU,EAKV,cAAc,EACd,iBAAiB,EAEjB,yBAAyB,EAOzB,kBAAkB,IAAI,sBAAsB,EAO5C,iBAAiB,EAEjB,MAAM,eAAe,CAAC;AA2FvB,kEAAkE;AAClE,eAAO,MAAM,wBAAwB,QAAS,CAAC;AAE/C;;;;;;;GAOG;AACH,wBAAgB,qBAAqB,CACpC,SAAS,EAAE,MAAM,EACjB,QAAQ,EAAE,MAAM,EAChB,UAAU,EAAE,MAAM,EAClB,SAAS,EAAE,MAAM,EACjB,WAAW,EAAE,OAAO,GAClB,MAAM,CAmBR;AAYD;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,+BAA+B,IAAI,CAAC;AA+MjD;;;;;;;;;;;GAWG;AACH,wBAAgB,0BAA0B,CACzC,SAAS,CAAC,EAAE,iBAAiB,GAC3B,MAAM,CAcR;AAYD;;;;;;;;;;;;;;;;;GAiBG;AACH,eAAO,MAAM,+BAA+B,IAAI,CAAC;AAEjD;;;;;;;;;;;;;;;;;;GAkBG;AACH,eAAO,MAAM,sCAAsC,IAAI,CAAC;AAExD;;;;;;;;;;;;;;;;;;;GAmBG;AACH,eAAO,MAAM,mCAAmC,OAAO,CAAC;AA0BxD;;;;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;AAiJlC,qBAAa,sBAAuB,SAAQ,KAAK;IAChD,QAAQ,CAAC,MAAM,CAAC,EAAE,OAAO,CAAC;gBAEd,MAAM,CAAC,EAAE,OAAO;CAa5B;AAuND;;;;;;;;;;;;;;GAcG;AACH,eAAO,MAAM,+BAA+B,IAAI,CAAC;AAEjD;;;;;;;;GAQG;AACH,wBAAgB,4BAA4B,CAAC,MAAM,EAAE;IACpD,aAAa,CAAC,EAAE,YAAY,GAAG,UAAU,CAAC;IAC1C,oBAAoB,CAAC,EAAE,MAAM,CAAC;CAC9B,GAAG,MAAM,CAST;AAED,qBAAa,YAAY;IACxB,OAAO,CAAC,MAAM,CAGU;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,CA6CpB;IACF;;;OAGG;IACH,OAAO,CAAC,qBAAqB,CAAgC;IAC7D,uDAAuD;IACvD,OAAO,CAAC,yBAAyB,CAAS;IAC1C;;;OAGG;IACH,OAAO,CAAC,iBAAiB,CAAqB;IAC9C;;;;;;;;OAQG;IACH,OAAO,CAAC,qBAAqB,CAAS;IACtC;;;OAGG;IACH,OAAO,CAAC,sBAAsB,CAAS;IACvC,yFAAyF;IACzF,OAAO,CAAC,2BAA2B,CAAK;IACxC;;;;;;OAMG;IACH,OAAO,CAAC,oBAAoB,CAAS;IACrC,gEAAgE;IAChE,OAAO,CAAC,iBAAiB,CAAS;IAClC;;;;;;;OAOG;IACH,OAAO,CAAC,gBAAgB,CAAqB;IAC7C;;;;;;OAMG;IACH,OAAO,CAAC,gBAAgB,CAAS;IACjC;;;;;;;OAOG;IACH,OAAO,CAAC,0BAA0B,CAAK;IACvC,uEAAuE;IACvE,OAAO,CAAC,8BAA8B,CAAK;IAC3C,+DAA+D;IAC/D,OAAO,CAAC,wBAAwB,CAAS;IACzC;;;;;;;;;;;OAWG;IACH,OAAO,CAAC,wBAAwB,CAAqB;IACrD;;;;;;OAMG;IACH,OAAO,CAAC,gBAAgB,CAAS;IACjC;;;;OAIG;IACH,OAAO,CAAC,gBAAgB,CAA+B;IACvD,OAAO,CAAC,qBAAqB,CAAS;IACtC;;;;OAIG;IACH,OAAO,CAAC,QAAQ,CAAC,gBAAgB,CAG7B;IACJ,yEAAyE;IACzE,OAAO,CAAC,QAAQ,CAAC,0BAA0B,CAA+B;IAC1E,qEAAqE;IACrE,OAAO,CAAC,QAAQ,CAAC,eAAe,CAG5B;IACJ,2EAA2E;IAC3E,OAAO,CAAC,QAAQ,CAAC,0BAA0B,CAGvC;IACJ;;;;;OAKG;IACH,OAAO,CAAC,mBAAmB,CAAS;IACpC,qFAAqF;IACrF,OAAO,CAAC,2BAA2B,CAAK;IACxC;;;OAGG;IACH,OAAO,CAAC,oBAAoB,CAAK;IACjC,+EAA+E;IAC/E,OAAO,CAAC,mBAAmB,CAAK;IAChC;;;;;;OAMG;IACH,OAAO,CAAC,wBAAwB,CAAqB;IACrD,OAAO,CAAC,cAAc,CAAC,CAAgB;IACvC,OAAO,CAAC,eAAe,CAAC,CAAkB;IAC1C;;;;OAIG;IACH,OAAO,CAAC,mBAAmB,CAAK;IAChC;;;;;OAKG;IACH,OAAO,CAAC,sBAAsB,CAAC,CAAS;IACxC,2EAA2E;IAC3E,OAAO,CAAC,iBAAiB,CAAC,CAAoB;IAC9C,mEAAmE;IACnE,OAAO,CAAC,mBAAmB,CAAK;IAChC,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;IAsBhC,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;;;;;;;;;;;;;;;;;;;OAmBG;IACH,QAAQ,IAAI,yBAAyB;YAsBvB,iBAAiB;YAKjB,UAAU;IAkBxB,OAAO,CAAC,aAAa;IAarB,OAAO,CAAC,8BAA8B;IAUtC,OAAO,CAAC,gCAAgC;IAUxC;;;;;;;OAOG;YACW,qBAAqB;IAYnC;;;;OAIG;IACH,OAAO,CAAC,6BAA6B;IAarC;;;OAGG;YACW,yBAAyB;IA0GvC;;;;;;;;;;;;;OAaG;IACH,OAAO,CAAC,kBAAkB;IA6B1B;;;;;;;;;;;;;;;;OAgBG;IACH,OAAO,CAAC,qBAAqB;IA+G7B,+DAA+D;IAC/D,OAAO,CAAC,aAAa;IAIrB;;;;;;;OAOG;IACH,OAAO,CAAC,yBAAyB;IAUjC;;;;;;;OAOG;IACH;;;;;;OAMG;IACH,OAAO,CAAC,wBAAwB;IAIhC;;;;;;OAMG;IACH;;;;;;OAMG;IACH,OAAO,CAAC,sBAAsB;IAoB9B;;;;OAIG;YACW,oBAAoB;IAmClC,+EAA+E;IAC/E,OAAO,CAAC,iBAAiB;YAQX,sBAAsB;IAkHpC;;;;;;;;;;;;;;;;;;;OAmBG;IACH,OAAO,CAAC,iBAAiB;IAazB,OAAO,CAAC,uBAAuB;YAOjB,sBAAsB;YA4CtB,OAAO;IAqxBrB;;;OAGG;YACW,wBAAwB;YAoCxB,kBAAkB;YAgBlB,iBAAiB;IAM/B;;;;;;;;;;;;;;;;;OAiBG;YACW,wCAAwC;IA4ItD;;;;;;;;;;;;;;;;OAgBG;YACW,yCAAyC;IA8BvD;;;;;;OAMG;YACW,sBAAsB;IAwCpC;;;;;;;;;;OAUG;IACH,OAAO,CAAC,4BAA4B;IA+BpC;;;;;;;OAOG;IACH,OAAO,CAAC,cAAc;IAOtB;;;OAGG;YACW,cAAc;IAkB5B;;;;;OAKG;YACW,4CAA4C;IA0D1D;;;;;;;;;;;;;;;;;OAiBG;YACW,yBAAyB;IA8BvC;;;;;;;;;;;;;;;;;;;;;;;OAuBG;IACH,OAAO,CAAC,sBAAsB;IAY9B,OAAO,CAAC,eAAe;IAMvB;;;;;;;;;;;OAWG;YACW,kBAAkB;IAyChC;;;;;;;;;;;;;OAaG;YACW,0BAA0B;IAwFxC,OAAO,CAAC,yBAAyB;IAiBjC,2EAA2E;IAC3E,OAAO,CAAC,oBAAoB;IAK5B,kEAAkE;YACpD,sBAAsB;YAkCtB,wBAAwB;IAiBtC,4EAA4E;YAC9D,mBAAmB;YA6FnB,kCAAkC;IAehD;;;;OAIG;YACW,qBAAqB;YAwapB,uBAAuB;IA+DtC,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;YAuF1B,yBAAyB;YAwBzB,WAAW;YAwCX,gBAAgB;IA0E9B;;;;;;;;;OASG;IACH,OAAO,CAAC,eAAe;IAmCvB,OAAO,CAAC,yBAAyB;YAsBnB,oBAAoB;YA6GpB,mBAAmB;YAwCnB,mBAAmB;IA8IjC,OAAO,CAAC,SAAS;IAoBjB,OAAO,CAAC,wBAAwB;IAMhC;;;;;;OAMG;YACW,kBAAkB;IAwDhC,2DAA2D;IAC3D,OAAO,CAAC,iBAAiB;IAazB;;;;;;OAMG;YACW,eAAe;IAqB7B,OAAO,CAAC,cAAc;IAMtB,OAAO,CAAC,mBAAmB;IAW3B;;;;;;;;;;OAUG;IACH,OAAO,CAAC,QAAQ,CAAC,WAAW,CAAgD;IAE5E,OAAO,CAAC,eAAe;IAevB,uEAAuE;IACvE,OAAO,CAAC,aAAa;IAQrB;;;;;;;;;OASG;IACH,OAAO,CAAC,KAAK;YAKC,IAAI;IAmHlB,OAAO,CAAC,gBAAgB;CAWxB;AA0DD,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
@@ -1,29 +1,29 @@
1
- var Pn="input_progress";var zr=[/\bserver is shutting down\b/i,/^(?:error:\s*)?(?:503\s*)?loading model\b/i,/\b(?:ECONNREFUSED|ECONNRESET|ECONNABORTED|EPIPE|EHOSTUNREACH|EHOSTDOWN|ENETUNREACH|ENETDOWN|ETIMEDOUT|UND_ERR_SOCKET|UND_ERR_CONNECT_TIMEOUT|UND_ERR_CLOSED)\b/,/\bsocket hang up\b/i,/\bother side closed\b/i,/\bsocket (?:was )?closed\b/i,/\bpremature close\b/i,/\bcannot connect to api\b/i,/^fetch failed$/i,/^terminated$/i,/^(?:error:\s*)?terminated:/i,/\bHTTPParserError\b/,/\bHPE_[A-Z_]+\b/,/^(?:network|connection) (?:error|failure|lost|reset)$/i,/^(?:(?:error:\s*)?(?:502|503|504)\s*)?(?:bad gateway|service unavailable|gateway time-?out)$/i,/^no healthy upstream$/i,/^(?:error:\s*)?(?:500\s*)?invalid input batch\.?$/i,/^(?:error:\s*)?got exception: speculative batch index \d+ is not inside the current sub-batch\b/i,/^(?:error:\s*)?(?:AI_TypeValidationError:\s*)?type validation failed\b[^:\n]*: value:/i,/^(?:error:\s*)?(?:AI_JSONParseError:\s*)?json parsing failed: text:/i],Dr=new Set([502,503,504]);var Et=/^(?:error:\s*)?evicted to keep other in-flight requests alive\b/i;function $n(e,t){return t==="kv_evicted"||Et.test((e??"").trim())}function Pe(e,t=0){if(t>5||e===null||e===void 0)return!1;if(typeof e==="string"){let i=e.trim();if(Et.test(i))return!0;if(!i.startsWith("{"))return!1;try{return Pe(JSON.parse(i),t+1)}catch{return!1}}if(typeof e!=="object")return!1;let n=e;if(n.error_kind==="evicted_kv_full")return!0;for(let i of["error","responseBody","data","cause","message"]){let r=n[i];if(r!==void 0&&r!==e){if(Pe(r,t+1))return!0}}return!1}var Ur=[/projected mean tps below floor/i,/context allocation exhausted/i,/session allocation full/i,/admission (?:rejected|refused|queued)/i,/\btoo many requests\b/i,Et,/\[opencoti_window_unavailable\b/];function Ln(e){let t=(n,i)=>/^[A-Z]/.test(n)?i.charAt(0).toUpperCase()+i.slice(1):i;return e.replace(/\badmission (?:rejected|refused)\b/gi,(n)=>t(n,"admission queued")).replace(/\b(?:rejected|refused)\b/gi,(n)=>t(n,"queued")).replace(/\b(?:rejecting|refusing)\b/gi,(n)=>t(n,"queueing")).replace(/\b(?:rejections|refusals)\b/gi,(n)=>t(n,"retries")).replace(/\b(?:rejection|refusal)\b/gi,(n)=>t(n,"retry"))}function ke(e,t){let n=(e??"").trim();if(t==="rate_limited"||t==="kv_evicted"||Ur.some((i)=>i.test(n)))return"refusal";if(n&&zr.some((i)=>i.test(n)))return"transport";return}function Fr(e){let t=e.code;return typeof t==="string"?t:void 0}function Br(e){let t=e.status??e.statusCode;return typeof t==="number"?t:void 0}function It(e,t=0){if(t>5||e===null||e===void 0)return;if(typeof e==="string")return ke(e);if(typeof e!=="object")return;let n=Br(e);if(n===429||Pe(e,t))return"refusal";let i=e.message,r=typeof i==="string"?ke(i):void 0;if(r==="refusal")return r;let o=Fr(e);if(o&&ke(o)==="transport")return"transport";if(n!==void 0&&Dr.has(n))return"transport";if(r)return r;return It(e.cause,t+1)}var Jt;function p(e,t,n){function i(a,u){if(!a._zod)Object.defineProperty(a,"_zod",{value:{def:u,constr:s,traits:new Set},enumerable:!1});if(a._zod.traits.has(e))return;a._zod.traits.add(e),t(a,u);let c=s.prototype,d=Object.keys(c);for(let y=0;y<d.length;y++){let g=d[y];if(!(g in a))a[g]=c[g].bind(a)}}let r=n?.Parent??Object;class o extends r{}Object.defineProperty(o,"name",{value:e});function s(a){var u;let c=n?.Parent?new o:this;i(c,a),(u=c._zod).deferred??(u.deferred=[]);for(let d of c._zod.deferred)d();return c}return Object.defineProperty(s,"init",{value:i}),Object.defineProperty(s,Symbol.hasInstance,{value:(a)=>{if(n?.Parent&&a instanceof n.Parent)return!0;return a?._zod?.traits?.has(e)}}),Object.defineProperty(s,"name",{value:e}),s}var yp=Symbol("zod_brand");class de extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class Ct extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`);this.name="ZodEncodeError"}}(Jt=globalThis).__zod_globalConfig??(Jt.__zod_globalConfig={});var Ve=globalThis.__zod_globalConfig;function ee(e){if(e)Object.assign(Ve,e);return Ve}function zn(e){let t=Object.values(e).filter((n)=>typeof n==="number");return Object.entries(e).filter(([n,i])=>t.indexOf(+n)===-1).map(([n,i])=>i)}function Yt(e,t="|"){return e.map((n)=>Fn(n)).join(t)}function Tt(e,t){if(typeof t==="bigint")return t.toString();return t}function et(e){return{get value(){{let t=e();return Object.defineProperty(this,"value",{value:t}),t}throw Error("cached value already set")}}}function At(e){return e===null||e===void 0}function xt(e){let t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function jr(e,t){let n=e/t,i=Math.round(n),r=Number.EPSILON*Math.max(Math.abs(n),1);if(Math.abs(n-i)<r)return 0;return n-i}var Xt=Symbol("evaluating");function A(e,t,n){let i=void 0;Object.defineProperty(e,t,{get(){if(i===Xt)return;if(i===void 0)i=Xt,i=n();return i},set(r){Object.defineProperty(e,t,{value:r})},configurable:!0})}function he(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function ae(...e){let t={};for(let n of e){let i=Object.getOwnPropertyDescriptors(n);Object.assign(t,i)}return Object.defineProperties({},t)}function Qt(e){return JSON.stringify(e)}function qr(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var Dn="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function $e(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}var Hr=et(()=>{if(Ve.jitless)return!1;if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return Function(""),!0}catch(e){return!1}});function Ee(e){if($e(e)===!1)return!1;let t=e.constructor;if(t===void 0)return!0;if(typeof t!=="function")return!0;let n=t.prototype;if($e(n)===!1)return!1;if(Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)return!1;return!0}function Un(e){if(Ee(e))return{...e};if(Array.isArray(e))return[...e];if(e instanceof Map)return new Map(e);if(e instanceof Set)return new Set(e);return e}var Wr=new Set(["string","number","symbol"]);function Ie(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function le(e,t,n){let i=new e._zod.constr(t??e._zod.def);if(!t||n?.parent)i._zod.parent=e;return i}function T(e){let t=e;if(!t)return{};if(typeof t==="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}if(delete t.message,typeof t.error==="string")return{...t,error:()=>t.error};return t}function Fn(e){if(typeof e==="bigint")return e.toString()+"n";if(typeof e==="string")return`"${e}"`;return`${e}`}function Vr(e){return Object.keys(e).filter((t)=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}var Zr={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-340282346638528860000000000000000000000,340282346638528860000000000000000000000],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function Gr(e,t){let n=e._zod.def,i=n.checks;if(i&&i.length>0)throw Error(".pick() cannot be used on object schemas containing refinements");let r=ae(e._zod.def,{get shape(){let o={};for(let s in t){if(!(s in n.shape))throw Error(`Unrecognized key: "${s}"`);if(!t[s])continue;o[s]=n.shape[s]}return he(this,"shape",o),o},checks:[]});return le(e,r)}function Kr(e,t){let n=e._zod.def,i=n.checks;if(i&&i.length>0)throw Error(".omit() cannot be used on object schemas containing refinements");let r=ae(e._zod.def,{get shape(){let o={...e._zod.def.shape};for(let s in t){if(!(s in n.shape))throw Error(`Unrecognized key: "${s}"`);if(!t[s])continue;delete o[s]}return he(this,"shape",o),o},checks:[]});return le(e,r)}function Jr(e,t){if(!Ee(t))throw Error("Invalid input to extend: expected a plain object");let n=e._zod.def.checks;if(n&&n.length>0){let r=e._zod.def.shape;for(let o in t)if(Object.getOwnPropertyDescriptor(r,o)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let i=ae(e._zod.def,{get shape(){let r={...e._zod.def.shape,...t};return he(this,"shape",r),r}});return le(e,i)}function Yr(e,t){if(!Ee(t))throw Error("Invalid input to safeExtend: expected a plain object");let n=ae(e._zod.def,{get shape(){let i={...e._zod.def.shape,...t};return he(this,"shape",i),i}});return le(e,n)}function Xr(e,t){if(e._zod.def.checks?.length)throw Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let n=ae(e._zod.def,{get shape(){let i={...e._zod.def.shape,...t._zod.def.shape};return he(this,"shape",i),i},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return le(e,n)}function Qr(e,t,n){let i=t._zod.def.checks;if(i&&i.length>0)throw Error(".partial() cannot be used on object schemas containing refinements");let r=ae(t._zod.def,{get shape(){let o=t._zod.def.shape,s={...o};if(n)for(let a in n){if(!(a in o))throw Error(`Unrecognized key: "${a}"`);if(!n[a])continue;s[a]=e?new e({type:"optional",innerType:o[a]}):o[a]}else for(let a in o)s[a]=e?new e({type:"optional",innerType:o[a]}):o[a];return he(this,"shape",s),s},checks:[]});return le(t,r)}function eo(e,t,n){let i=ae(t._zod.def,{get shape(){let r=t._zod.def.shape,o={...r};if(n)for(let s in n){if(!(s in o))throw Error(`Unrecognized key: "${s}"`);if(!n[s])continue;o[s]=new e({type:"nonoptional",innerType:r[s]})}else for(let s in r)o[s]=new e({type:"nonoptional",innerType:r[s]});return he(this,"shape",o),o}});return le(t,i)}function Te(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function to(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue===!1)return!0;return!1}function se(e,t){return t.map((n)=>{var i;return(i=n).path??(i.path=[]),n.path.unshift(e),n})}function Fe(e){return typeof e==="string"?e:e?.message}function te(e,t,n){let i=e.message?e.message:Fe(e.inst?._zod.def?.error?.(e))??Fe(t?.error?.(e))??Fe(n.customError?.(e))??Fe(n.localeError?.(e))??"Invalid input",{inst:r,continue:o,input:s,...a}=e;if(a.path??(a.path=[]),a.message=i,t?.reportInput)a.input=s;return a}function Rt(e){if(Array.isArray(e))return"array";if(typeof e==="string")return"string";return"unknown"}function no(e){let t=typeof e;switch(t){case"number":return Number.isNaN(e)?"nan":"number";case"object":{if(e===null)return"null";if(Array.isArray(e))return"array";let n=e;if(n&&Object.getPrototypeOf(n)!==Object.prototype&&"constructor"in n&&n.constructor)return n.constructor.name}}return t}function Le(...e){let[t,n,i]=e;if(typeof t==="string")return{message:t,code:"custom",input:n,inst:i};return{...t}}var Bn=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,Tt,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},jn=p("$ZodError",Bn),tt=p("$ZodError",Bn,{Parent:Error});function io(e,t=(n)=>n.message){let n={},i=[];for(let r of e.issues)if(r.path.length>0)n[r.path[0]]=n[r.path[0]]||[],n[r.path[0]].push(t(r));else i.push(t(r));return{formErrors:i,fieldErrors:n}}function ro(e,t=(n)=>n.message){let n={_errors:[]},i=(r,o=[])=>{for(let s of r.issues)if(s.code==="invalid_union"&&s.errors.length)s.errors.map((a)=>i({issues:a},[...o,...s.path]));else if(s.code==="invalid_key")i({issues:s.issues},[...o,...s.path]);else if(s.code==="invalid_element")i({issues:s.issues},[...o,...s.path]);else{let a=[...o,...s.path];if(a.length===0)n._errors.push(t(s));else{let u=n,c=0;while(c<a.length){let d=a[c];if(c!==a.length-1)u[d]=u[d]||{_errors:[]};else u[d]=u[d]||{_errors:[]},u[d]._errors.push(t(s));u=u[d],c++}}}};return i(e),n}var nt=(e)=>(t,n,i,r)=>{let o=i?{...i,async:!1}:{async:!1},s=t._zod.run({value:n,issues:[]},o);if(s instanceof Promise)throw new de;if(s.issues.length){let a=new(r?.Err??e)(s.issues.map((u)=>te(u,o,ee())));throw Dn(a,r?.callee),a}return s.value},en=nt(tt),it=(e)=>async(t,n,i,r)=>{let o=i?{...i,async:!0}:{async:!0},s=t._zod.run({value:n,issues:[]},o);if(s instanceof Promise)s=await s;if(s.issues.length){let a=new(r?.Err??e)(s.issues.map((u)=>te(u,o,ee())));throw Dn(a,r?.callee),a}return s.value},tn=it(tt),rt=(e)=>(t,n,i)=>{let r=i?{...i,async:!1}:{async:!1},o=t._zod.run({value:n,issues:[]},r);if(o instanceof Promise)throw new de;return o.issues.length?{success:!1,error:new(e??jn)(o.issues.map((s)=>te(s,r,ee())))}:{success:!0,data:o.value}},oo=rt(tt),ot=(e)=>async(t,n,i)=>{let r=i?{...i,async:!0}:{async:!0},o=t._zod.run({value:n,issues:[]},r);if(o instanceof Promise)o=await o;return o.issues.length?{success:!1,error:new e(o.issues.map((s)=>te(s,r,ee())))}:{success:!0,data:o.value}},so=ot(tt),ao=(e)=>(t,n,i)=>{let r=i?{...i,direction:"backward"}:{direction:"backward"};return nt(e)(t,n,r)},lo=(e)=>(t,n,i)=>nt(e)(t,n,i),uo=(e)=>async(t,n,i)=>{let r=i?{...i,direction:"backward"}:{direction:"backward"};return it(e)(t,n,r)},co=(e)=>async(t,n,i)=>it(e)(t,n,i),po=(e)=>(t,n,i)=>{let r=i?{...i,direction:"backward"}:{direction:"backward"};return rt(e)(t,n,r)},ho=(e)=>(t,n,i)=>rt(e)(t,n,i),fo=(e)=>async(t,n,i)=>{let r=i?{...i,direction:"backward"}:{direction:"backward"};return ot(e)(t,n,r)},mo=(e)=>async(t,n,i)=>ot(e)(t,n,i),go=/^[cC][0-9a-z]{6,}$/,yo=/^[0-9a-z]+$/,vo=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,bo=/^[0-9a-vA-V]{20}$/,To=/^[A-Za-z0-9]{27}$/,wo=/^[a-zA-Z0-9_-]{21}$/,_o=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,ko=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,nn=(e)=>{if(!e)return/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)},Eo=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Io="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function Co(){return new RegExp(Io,"u")}var Ao=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,xo=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,Ro=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,So=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,No=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,qn=/^[A-Za-z0-9_-]*$/,Oo=/^https?$/,Mo=/^\+[1-9]\d{6,14}$/,Hn="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",Po=new RegExp(`^${Hn}$`);function Wn(e){return typeof e.precision==="number"?e.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":e.precision===0?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d":`(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${e.precision}}`:"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function $o(e){return new RegExp(`^${Wn(e)}$`)}function Lo(e){let t=Wn({precision:e.precision}),n=["Z"];if(e.local)n.push("");if(e.offset)n.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let i=`${t}(?:${n.join("|")})`;return new RegExp(`^${Hn}T(?:${i})$`)}var zo=(e)=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},Do=/^-?\d+$/,Vn=/^-?\d+(?:\.\d+)?$/,Uo=/^(?:true|false)$/i,Fo=/^[^A-Z]*$/,Bo=/^[^a-z]*$/,V=p("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),Zn={number:"number",bigint:"bigint",object:"date"},Gn=p("$ZodCheckLessThan",(e,t)=>{V.init(e,t);let n=Zn[typeof t.value];e._zod.onattach.push((i)=>{let r=i._zod.bag,o=(t.inclusive?r.maximum:r.exclusiveMaximum)??Number.POSITIVE_INFINITY;if(t.value<o)if(t.inclusive)r.maximum=t.value;else r.exclusiveMaximum=t.value}),e._zod.check=(i)=>{if(t.inclusive?i.value<=t.value:i.value<t.value)return;i.issues.push({origin:n,code:"too_big",maximum:typeof t.value==="object"?t.value.getTime():t.value,input:i.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Kn=p("$ZodCheckGreaterThan",(e,t)=>{V.init(e,t);let n=Zn[typeof t.value];e._zod.onattach.push((i)=>{let r=i._zod.bag,o=(t.inclusive?r.minimum:r.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if(t.value>o)if(t.inclusive)r.minimum=t.value;else r.exclusiveMinimum=t.value}),e._zod.check=(i)=>{if(t.inclusive?i.value>=t.value:i.value>t.value)return;i.issues.push({origin:n,code:"too_small",minimum:typeof t.value==="object"?t.value.getTime():t.value,input:i.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),jo=p("$ZodCheckMultipleOf",(e,t)=>{V.init(e,t),e._zod.onattach.push((n)=>{var i;(i=n._zod.bag).multipleOf??(i.multipleOf=t.value)}),e._zod.check=(n)=>{if(typeof n.value!==typeof t.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof n.value==="bigint"?n.value%t.value===BigInt(0):jr(n.value,t.value)===0)return;n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),qo=p("$ZodCheckNumberFormat",(e,t)=>{V.init(e,t),t.format=t.format||"float64";let n=t.format?.includes("int"),i=n?"int":"number",[r,o]=Zr[t.format];e._zod.onattach.push((s)=>{let a=s._zod.bag;if(a.format=t.format,a.minimum=r,a.maximum=o,n)a.pattern=Do}),e._zod.check=(s)=>{let a=s.value;if(n){if(!Number.isInteger(a)){s.issues.push({expected:i,format:t.format,code:"invalid_type",continue:!1,input:a,inst:e});return}if(!Number.isSafeInteger(a)){if(a>0)s.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:i,inclusive:!0,continue:!t.abort});else s.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:i,inclusive:!0,continue:!t.abort});return}}if(a<r)s.issues.push({origin:"number",input:a,code:"too_small",minimum:r,inclusive:!0,inst:e,continue:!t.abort});if(a>o)s.issues.push({origin:"number",input:a,code:"too_big",maximum:o,inclusive:!0,inst:e,continue:!t.abort})}}),Ho=p("$ZodCheckMaxLength",(e,t)=>{var n;V.init(e,t),(n=e._zod.def).when??(n.when=(i)=>{let r=i.value;return!At(r)&&r.length!==void 0}),e._zod.onattach.push((i)=>{let r=i._zod.bag.maximum??Number.POSITIVE_INFINITY;if(t.maximum<r)i._zod.bag.maximum=t.maximum}),e._zod.check=(i)=>{let r=i.value;if(r.length<=t.maximum)return;let o=Rt(r);i.issues.push({origin:o,code:"too_big",maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Wo=p("$ZodCheckMinLength",(e,t)=>{var n;V.init(e,t),(n=e._zod.def).when??(n.when=(i)=>{let r=i.value;return!At(r)&&r.length!==void 0}),e._zod.onattach.push((i)=>{let r=i._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(t.minimum>r)i._zod.bag.minimum=t.minimum}),e._zod.check=(i)=>{let r=i.value;if(r.length>=t.minimum)return;let o=Rt(r);i.issues.push({origin:o,code:"too_small",minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Vo=p("$ZodCheckLengthEquals",(e,t)=>{var n;V.init(e,t),(n=e._zod.def).when??(n.when=(i)=>{let r=i.value;return!At(r)&&r.length!==void 0}),e._zod.onattach.push((i)=>{let r=i._zod.bag;r.minimum=t.length,r.maximum=t.length,r.length=t.length}),e._zod.check=(i)=>{let r=i.value,o=r.length;if(o===t.length)return;let s=Rt(r),a=o>t.length;i.issues.push({origin:s,...a?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:i.value,inst:e,continue:!t.abort})}}),st=p("$ZodCheckStringFormat",(e,t)=>{var n,i;if(V.init(e,t),e._zod.onattach.push((r)=>{let o=r._zod.bag;if(o.format=t.format,t.pattern)o.patterns??(o.patterns=new Set),o.patterns.add(t.pattern)}),t.pattern)(n=e._zod).check??(n.check=(r)=>{if(t.pattern.lastIndex=0,t.pattern.test(r.value))return;r.issues.push({origin:"string",code:"invalid_format",format:t.format,input:r.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})});else(i=e._zod).check??(i.check=()=>{})}),Zo=p("$ZodCheckRegex",(e,t)=>{st.init(e,t),e._zod.check=(n)=>{if(t.pattern.lastIndex=0,t.pattern.test(n.value))return;n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Go=p("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=Fo),st.init(e,t)}),Ko=p("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=Bo),st.init(e,t)}),Jo=p("$ZodCheckIncludes",(e,t)=>{V.init(e,t);let n=Ie(t.includes),i=new RegExp(typeof t.position==="number"?`^.{${t.position}}${n}`:n);t.pattern=i,e._zod.onattach.push((r)=>{let o=r._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(i)}),e._zod.check=(r)=>{if(r.value.includes(t.includes,t.position))return;r.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:r.value,inst:e,continue:!t.abort})}}),Yo=p("$ZodCheckStartsWith",(e,t)=>{V.init(e,t);let n=new RegExp(`^${Ie(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.onattach.push((i)=>{let r=i._zod.bag;r.patterns??(r.patterns=new Set),r.patterns.add(n)}),e._zod.check=(i)=>{if(i.value.startsWith(t.prefix))return;i.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:i.value,inst:e,continue:!t.abort})}}),Xo=p("$ZodCheckEndsWith",(e,t)=>{V.init(e,t);let n=new RegExp(`.*${Ie(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.onattach.push((i)=>{let r=i._zod.bag;r.patterns??(r.patterns=new Set),r.patterns.add(n)}),e._zod.check=(i)=>{if(i.value.endsWith(t.suffix))return;i.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:i.value,inst:e,continue:!t.abort})}}),Qo=p("$ZodCheckOverwrite",(e,t)=>{V.init(e,t),e._zod.check=(n)=>{n.value=t.tx(n.value)}});class Jn{constructor(e=[]){if(this.content=[],this.indent=0,this)this.args=e}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e==="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let t=e.split(`
1
+ var Pn="input_progress";var zr=[/\bserver is shutting down\b/i,/^(?:error:\s*)?(?:503\s*)?loading model\b/i,/\b(?:ECONNREFUSED|ECONNRESET|ECONNABORTED|EPIPE|EHOSTUNREACH|EHOSTDOWN|ENETUNREACH|ENETDOWN|ETIMEDOUT|UND_ERR_SOCKET|UND_ERR_CONNECT_TIMEOUT|UND_ERR_CLOSED)\b/,/\bsocket hang up\b/i,/\bother side closed\b/i,/\bsocket (?:was )?closed\b/i,/\bpremature close\b/i,/\bcannot connect to api\b/i,/^fetch failed$/i,/^terminated$/i,/^(?:error:\s*)?terminated:/i,/\bHTTPParserError\b/,/\bHPE_[A-Z_]+\b/,/^(?:network|connection) (?:error|failure|lost|reset)$/i,/^(?:(?:error:\s*)?(?:502|503|504)\s*)?(?:bad gateway|service unavailable|gateway time-?out)$/i,/^no healthy upstream$/i,/^(?:error:\s*)?(?:500\s*)?invalid input batch\.?$/i,/^(?:error:\s*)?got exception: speculative batch index \d+ is not inside the current sub-batch\b/i,/^(?:error:\s*)?(?:AI_TypeValidationError:\s*)?type validation failed\b[^:\n]*: value:/i,/^(?:error:\s*)?(?:AI_JSONParseError:\s*)?json parsing failed: text:/i],Dr=new Set([502,503,504]);var Et=/^(?:error:\s*)?evicted to keep other in-flight requests alive\b/i;function $n(e,t){return t==="kv_evicted"||Et.test((e??"").trim())}function Me(e,t=0){if(t>5||e===null||e===void 0)return!1;if(typeof e==="string"){let i=e.trim();if(Et.test(i))return!0;if(!i.startsWith("{"))return!1;try{return Me(JSON.parse(i),t+1)}catch{return!1}}if(typeof e!=="object")return!1;let n=e;if(n.error_kind==="evicted_kv_full")return!0;for(let i of["error","responseBody","data","cause","message"]){let r=n[i];if(r!==void 0&&r!==e){if(Me(r,t+1))return!0}}return!1}var Ur=[/projected mean tps below floor/i,/context allocation exhausted/i,/session allocation full/i,/admission (?:rejected|refused|queued)/i,/\btoo many requests\b/i,Et,/\[opencoti_window_unavailable\b/];function Ln(e){let t=(n,i)=>/^[A-Z]/.test(n)?i.charAt(0).toUpperCase()+i.slice(1):i;return e.replace(/\badmission (?:rejected|refused)\b/gi,(n)=>t(n,"admission queued")).replace(/\b(?:rejected|refused)\b/gi,(n)=>t(n,"queued")).replace(/\b(?:rejecting|refusing)\b/gi,(n)=>t(n,"queueing")).replace(/\b(?:rejections|refusals)\b/gi,(n)=>t(n,"retries")).replace(/\b(?:rejection|refusal)\b/gi,(n)=>t(n,"retry"))}function _e(e,t){let n=(e??"").trim();if(t==="rate_limited"||t==="kv_evicted"||Ur.some((i)=>i.test(n)))return"refusal";if(n&&zr.some((i)=>i.test(n)))return"transport";return}function Fr(e){let t=e.code;return typeof t==="string"?t:void 0}function Br(e){let t=e.status??e.statusCode;return typeof t==="number"?t:void 0}function It(e,t=0){if(t>5||e===null||e===void 0)return;if(typeof e==="string")return _e(e);if(typeof e!=="object")return;let n=Br(e);if(n===429||Me(e,t))return"refusal";let i=e.message,r=typeof i==="string"?_e(i):void 0;if(r==="refusal")return r;let o=Fr(e);if(o&&_e(o)==="transport")return"transport";if(n!==void 0&&Dr.has(n))return"transport";if(r)return r;return It(e.cause,t+1)}var Jt;function p(e,t,n){function i(a,u){if(!a._zod)Object.defineProperty(a,"_zod",{value:{def:u,constr:s,traits:new Set},enumerable:!1});if(a._zod.traits.has(e))return;a._zod.traits.add(e),t(a,u);let c=s.prototype,d=Object.keys(c);for(let y=0;y<d.length;y++){let h=d[y];if(!(h in a))a[h]=c[h].bind(a)}}let r=n?.Parent??Object;class o extends r{}Object.defineProperty(o,"name",{value:e});function s(a){var u;let c=n?.Parent?new o:this;i(c,a),(u=c._zod).deferred??(u.deferred=[]);for(let d of c._zod.deferred)d();return c}return Object.defineProperty(s,"init",{value:i}),Object.defineProperty(s,Symbol.hasInstance,{value:(a)=>{if(n?.Parent&&a instanceof n.Parent)return!0;return a?._zod?.traits?.has(e)}}),Object.defineProperty(s,"name",{value:e}),s}var yp=Symbol("zod_brand");class de extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class Ct extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`);this.name="ZodEncodeError"}}(Jt=globalThis).__zod_globalConfig??(Jt.__zod_globalConfig={});var Ve=globalThis.__zod_globalConfig;function ee(e){if(e)Object.assign(Ve,e);return Ve}function zn(e){let t=Object.values(e).filter((n)=>typeof n==="number");return Object.entries(e).filter(([n,i])=>t.indexOf(+n)===-1).map(([n,i])=>i)}function Yt(e,t="|"){return e.map((n)=>Fn(n)).join(t)}function Tt(e,t){if(typeof t==="bigint")return t.toString();return t}function et(e){return{get value(){{let t=e();return Object.defineProperty(this,"value",{value:t}),t}throw Error("cached value already set")}}}function At(e){return e===null||e===void 0}function xt(e){let t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function jr(e,t){let n=e/t,i=Math.round(n),r=Number.EPSILON*Math.max(Math.abs(n),1);if(Math.abs(n-i)<r)return 0;return n-i}var Xt=Symbol("evaluating");function A(e,t,n){let i=void 0;Object.defineProperty(e,t,{get(){if(i===Xt)return;if(i===void 0)i=Xt,i=n();return i},set(r){Object.defineProperty(e,t,{value:r})},configurable:!0})}function he(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function ae(...e){let t={};for(let n of e){let i=Object.getOwnPropertyDescriptors(n);Object.assign(t,i)}return Object.defineProperties({},t)}function Qt(e){return JSON.stringify(e)}function qr(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var Dn="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function Pe(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}var Hr=et(()=>{if(Ve.jitless)return!1;if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return Function(""),!0}catch(e){return!1}});function ke(e){if(Pe(e)===!1)return!1;let t=e.constructor;if(t===void 0)return!0;if(typeof t!=="function")return!0;let n=t.prototype;if(Pe(n)===!1)return!1;if(Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)return!1;return!0}function Un(e){if(ke(e))return{...e};if(Array.isArray(e))return[...e];if(e instanceof Map)return new Map(e);if(e instanceof Set)return new Set(e);return e}var Wr=new Set(["string","number","symbol"]);function Ee(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function le(e,t,n){let i=new e._zod.constr(t??e._zod.def);if(!t||n?.parent)i._zod.parent=e;return i}function b(e){let t=e;if(!t)return{};if(typeof t==="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}if(delete t.message,typeof t.error==="string")return{...t,error:()=>t.error};return t}function Fn(e){if(typeof e==="bigint")return e.toString()+"n";if(typeof e==="string")return`"${e}"`;return`${e}`}function Vr(e){return Object.keys(e).filter((t)=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}var Zr={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-340282346638528860000000000000000000000,340282346638528860000000000000000000000],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function Gr(e,t){let n=e._zod.def,i=n.checks;if(i&&i.length>0)throw Error(".pick() cannot be used on object schemas containing refinements");let r=ae(e._zod.def,{get shape(){let o={};for(let s in t){if(!(s in n.shape))throw Error(`Unrecognized key: "${s}"`);if(!t[s])continue;o[s]=n.shape[s]}return he(this,"shape",o),o},checks:[]});return le(e,r)}function Kr(e,t){let n=e._zod.def,i=n.checks;if(i&&i.length>0)throw Error(".omit() cannot be used on object schemas containing refinements");let r=ae(e._zod.def,{get shape(){let o={...e._zod.def.shape};for(let s in t){if(!(s in n.shape))throw Error(`Unrecognized key: "${s}"`);if(!t[s])continue;delete o[s]}return he(this,"shape",o),o},checks:[]});return le(e,r)}function Jr(e,t){if(!ke(t))throw Error("Invalid input to extend: expected a plain object");let n=e._zod.def.checks;if(n&&n.length>0){let r=e._zod.def.shape;for(let o in t)if(Object.getOwnPropertyDescriptor(r,o)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let i=ae(e._zod.def,{get shape(){let r={...e._zod.def.shape,...t};return he(this,"shape",r),r}});return le(e,i)}function Yr(e,t){if(!ke(t))throw Error("Invalid input to safeExtend: expected a plain object");let n=ae(e._zod.def,{get shape(){let i={...e._zod.def.shape,...t};return he(this,"shape",i),i}});return le(e,n)}function Xr(e,t){if(e._zod.def.checks?.length)throw Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let n=ae(e._zod.def,{get shape(){let i={...e._zod.def.shape,...t._zod.def.shape};return he(this,"shape",i),i},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return le(e,n)}function Qr(e,t,n){let i=t._zod.def.checks;if(i&&i.length>0)throw Error(".partial() cannot be used on object schemas containing refinements");let r=ae(t._zod.def,{get shape(){let o=t._zod.def.shape,s={...o};if(n)for(let a in n){if(!(a in o))throw Error(`Unrecognized key: "${a}"`);if(!n[a])continue;s[a]=e?new e({type:"optional",innerType:o[a]}):o[a]}else for(let a in o)s[a]=e?new e({type:"optional",innerType:o[a]}):o[a];return he(this,"shape",s),s},checks:[]});return le(t,r)}function eo(e,t,n){let i=ae(t._zod.def,{get shape(){let r=t._zod.def.shape,o={...r};if(n)for(let s in n){if(!(s in o))throw Error(`Unrecognized key: "${s}"`);if(!n[s])continue;o[s]=new e({type:"nonoptional",innerType:r[s]})}else for(let s in r)o[s]=new e({type:"nonoptional",innerType:r[s]});return he(this,"shape",o),o}});return le(t,i)}function be(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function to(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue===!1)return!0;return!1}function se(e,t){return t.map((n)=>{var i;return(i=n).path??(i.path=[]),n.path.unshift(e),n})}function Fe(e){return typeof e==="string"?e:e?.message}function te(e,t,n){let i=e.message?e.message:Fe(e.inst?._zod.def?.error?.(e))??Fe(t?.error?.(e))??Fe(n.customError?.(e))??Fe(n.localeError?.(e))??"Invalid input",{inst:r,continue:o,input:s,...a}=e;if(a.path??(a.path=[]),a.message=i,t?.reportInput)a.input=s;return a}function Rt(e){if(Array.isArray(e))return"array";if(typeof e==="string")return"string";return"unknown"}function no(e){let t=typeof e;switch(t){case"number":return Number.isNaN(e)?"nan":"number";case"object":{if(e===null)return"null";if(Array.isArray(e))return"array";let n=e;if(n&&Object.getPrototypeOf(n)!==Object.prototype&&"constructor"in n&&n.constructor)return n.constructor.name}}return t}function $e(...e){let[t,n,i]=e;if(typeof t==="string")return{message:t,code:"custom",input:n,inst:i};return{...t}}var Bn=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,Tt,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},jn=p("$ZodError",Bn),tt=p("$ZodError",Bn,{Parent:Error});function io(e,t=(n)=>n.message){let n={},i=[];for(let r of e.issues)if(r.path.length>0)n[r.path[0]]=n[r.path[0]]||[],n[r.path[0]].push(t(r));else i.push(t(r));return{formErrors:i,fieldErrors:n}}function ro(e,t=(n)=>n.message){let n={_errors:[]},i=(r,o=[])=>{for(let s of r.issues)if(s.code==="invalid_union"&&s.errors.length)s.errors.map((a)=>i({issues:a},[...o,...s.path]));else if(s.code==="invalid_key")i({issues:s.issues},[...o,...s.path]);else if(s.code==="invalid_element")i({issues:s.issues},[...o,...s.path]);else{let a=[...o,...s.path];if(a.length===0)n._errors.push(t(s));else{let u=n,c=0;while(c<a.length){let d=a[c];if(c!==a.length-1)u[d]=u[d]||{_errors:[]};else u[d]=u[d]||{_errors:[]},u[d]._errors.push(t(s));u=u[d],c++}}}};return i(e),n}var nt=(e)=>(t,n,i,r)=>{let o=i?{...i,async:!1}:{async:!1},s=t._zod.run({value:n,issues:[]},o);if(s instanceof Promise)throw new de;if(s.issues.length){let a=new(r?.Err??e)(s.issues.map((u)=>te(u,o,ee())));throw Dn(a,r?.callee),a}return s.value},en=nt(tt),it=(e)=>async(t,n,i,r)=>{let o=i?{...i,async:!0}:{async:!0},s=t._zod.run({value:n,issues:[]},o);if(s instanceof Promise)s=await s;if(s.issues.length){let a=new(r?.Err??e)(s.issues.map((u)=>te(u,o,ee())));throw Dn(a,r?.callee),a}return s.value},tn=it(tt),rt=(e)=>(t,n,i)=>{let r=i?{...i,async:!1}:{async:!1},o=t._zod.run({value:n,issues:[]},r);if(o instanceof Promise)throw new de;return o.issues.length?{success:!1,error:new(e??jn)(o.issues.map((s)=>te(s,r,ee())))}:{success:!0,data:o.value}},oo=rt(tt),ot=(e)=>async(t,n,i)=>{let r=i?{...i,async:!0}:{async:!0},o=t._zod.run({value:n,issues:[]},r);if(o instanceof Promise)o=await o;return o.issues.length?{success:!1,error:new e(o.issues.map((s)=>te(s,r,ee())))}:{success:!0,data:o.value}},so=ot(tt),ao=(e)=>(t,n,i)=>{let r=i?{...i,direction:"backward"}:{direction:"backward"};return nt(e)(t,n,r)},lo=(e)=>(t,n,i)=>nt(e)(t,n,i),uo=(e)=>async(t,n,i)=>{let r=i?{...i,direction:"backward"}:{direction:"backward"};return it(e)(t,n,r)},co=(e)=>async(t,n,i)=>it(e)(t,n,i),po=(e)=>(t,n,i)=>{let r=i?{...i,direction:"backward"}:{direction:"backward"};return rt(e)(t,n,r)},ho=(e)=>(t,n,i)=>rt(e)(t,n,i),fo=(e)=>async(t,n,i)=>{let r=i?{...i,direction:"backward"}:{direction:"backward"};return ot(e)(t,n,r)},mo=(e)=>async(t,n,i)=>ot(e)(t,n,i),go=/^[cC][0-9a-z]{6,}$/,yo=/^[0-9a-z]+$/,vo=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,bo=/^[0-9a-vA-V]{20}$/,To=/^[A-Za-z0-9]{27}$/,wo=/^[a-zA-Z0-9_-]{21}$/,_o=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,ko=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,nn=(e)=>{if(!e)return/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)},Eo=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Io="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function Co(){return new RegExp(Io,"u")}var Ao=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,xo=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,Ro=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,So=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,No=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,qn=/^[A-Za-z0-9_-]*$/,Oo=/^https?$/,Mo=/^\+[1-9]\d{6,14}$/,Hn="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",Po=new RegExp(`^${Hn}$`);function Wn(e){return typeof e.precision==="number"?e.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":e.precision===0?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d":`(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${e.precision}}`:"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function $o(e){return new RegExp(`^${Wn(e)}$`)}function Lo(e){let t=Wn({precision:e.precision}),n=["Z"];if(e.local)n.push("");if(e.offset)n.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let i=`${t}(?:${n.join("|")})`;return new RegExp(`^${Hn}T(?:${i})$`)}var zo=(e)=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},Do=/^-?\d+$/,Vn=/^-?\d+(?:\.\d+)?$/,Uo=/^(?:true|false)$/i,Fo=/^[^A-Z]*$/,Bo=/^[^a-z]*$/,V=p("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),Zn={number:"number",bigint:"bigint",object:"date"},Gn=p("$ZodCheckLessThan",(e,t)=>{V.init(e,t);let n=Zn[typeof t.value];e._zod.onattach.push((i)=>{let r=i._zod.bag,o=(t.inclusive?r.maximum:r.exclusiveMaximum)??Number.POSITIVE_INFINITY;if(t.value<o)if(t.inclusive)r.maximum=t.value;else r.exclusiveMaximum=t.value}),e._zod.check=(i)=>{if(t.inclusive?i.value<=t.value:i.value<t.value)return;i.issues.push({origin:n,code:"too_big",maximum:typeof t.value==="object"?t.value.getTime():t.value,input:i.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Kn=p("$ZodCheckGreaterThan",(e,t)=>{V.init(e,t);let n=Zn[typeof t.value];e._zod.onattach.push((i)=>{let r=i._zod.bag,o=(t.inclusive?r.minimum:r.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if(t.value>o)if(t.inclusive)r.minimum=t.value;else r.exclusiveMinimum=t.value}),e._zod.check=(i)=>{if(t.inclusive?i.value>=t.value:i.value>t.value)return;i.issues.push({origin:n,code:"too_small",minimum:typeof t.value==="object"?t.value.getTime():t.value,input:i.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),jo=p("$ZodCheckMultipleOf",(e,t)=>{V.init(e,t),e._zod.onattach.push((n)=>{var i;(i=n._zod.bag).multipleOf??(i.multipleOf=t.value)}),e._zod.check=(n)=>{if(typeof n.value!==typeof t.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof n.value==="bigint"?n.value%t.value===BigInt(0):jr(n.value,t.value)===0)return;n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),qo=p("$ZodCheckNumberFormat",(e,t)=>{V.init(e,t),t.format=t.format||"float64";let n=t.format?.includes("int"),i=n?"int":"number",[r,o]=Zr[t.format];e._zod.onattach.push((s)=>{let a=s._zod.bag;if(a.format=t.format,a.minimum=r,a.maximum=o,n)a.pattern=Do}),e._zod.check=(s)=>{let a=s.value;if(n){if(!Number.isInteger(a)){s.issues.push({expected:i,format:t.format,code:"invalid_type",continue:!1,input:a,inst:e});return}if(!Number.isSafeInteger(a)){if(a>0)s.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:i,inclusive:!0,continue:!t.abort});else s.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:i,inclusive:!0,continue:!t.abort});return}}if(a<r)s.issues.push({origin:"number",input:a,code:"too_small",minimum:r,inclusive:!0,inst:e,continue:!t.abort});if(a>o)s.issues.push({origin:"number",input:a,code:"too_big",maximum:o,inclusive:!0,inst:e,continue:!t.abort})}}),Ho=p("$ZodCheckMaxLength",(e,t)=>{var n;V.init(e,t),(n=e._zod.def).when??(n.when=(i)=>{let r=i.value;return!At(r)&&r.length!==void 0}),e._zod.onattach.push((i)=>{let r=i._zod.bag.maximum??Number.POSITIVE_INFINITY;if(t.maximum<r)i._zod.bag.maximum=t.maximum}),e._zod.check=(i)=>{let r=i.value;if(r.length<=t.maximum)return;let o=Rt(r);i.issues.push({origin:o,code:"too_big",maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Wo=p("$ZodCheckMinLength",(e,t)=>{var n;V.init(e,t),(n=e._zod.def).when??(n.when=(i)=>{let r=i.value;return!At(r)&&r.length!==void 0}),e._zod.onattach.push((i)=>{let r=i._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(t.minimum>r)i._zod.bag.minimum=t.minimum}),e._zod.check=(i)=>{let r=i.value;if(r.length>=t.minimum)return;let o=Rt(r);i.issues.push({origin:o,code:"too_small",minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Vo=p("$ZodCheckLengthEquals",(e,t)=>{var n;V.init(e,t),(n=e._zod.def).when??(n.when=(i)=>{let r=i.value;return!At(r)&&r.length!==void 0}),e._zod.onattach.push((i)=>{let r=i._zod.bag;r.minimum=t.length,r.maximum=t.length,r.length=t.length}),e._zod.check=(i)=>{let r=i.value,o=r.length;if(o===t.length)return;let s=Rt(r),a=o>t.length;i.issues.push({origin:s,...a?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:i.value,inst:e,continue:!t.abort})}}),st=p("$ZodCheckStringFormat",(e,t)=>{var n,i;if(V.init(e,t),e._zod.onattach.push((r)=>{let o=r._zod.bag;if(o.format=t.format,t.pattern)o.patterns??(o.patterns=new Set),o.patterns.add(t.pattern)}),t.pattern)(n=e._zod).check??(n.check=(r)=>{if(t.pattern.lastIndex=0,t.pattern.test(r.value))return;r.issues.push({origin:"string",code:"invalid_format",format:t.format,input:r.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})});else(i=e._zod).check??(i.check=()=>{})}),Zo=p("$ZodCheckRegex",(e,t)=>{st.init(e,t),e._zod.check=(n)=>{if(t.pattern.lastIndex=0,t.pattern.test(n.value))return;n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Go=p("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=Fo),st.init(e,t)}),Ko=p("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=Bo),st.init(e,t)}),Jo=p("$ZodCheckIncludes",(e,t)=>{V.init(e,t);let n=Ee(t.includes),i=new RegExp(typeof t.position==="number"?`^.{${t.position}}${n}`:n);t.pattern=i,e._zod.onattach.push((r)=>{let o=r._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(i)}),e._zod.check=(r)=>{if(r.value.includes(t.includes,t.position))return;r.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:r.value,inst:e,continue:!t.abort})}}),Yo=p("$ZodCheckStartsWith",(e,t)=>{V.init(e,t);let n=new RegExp(`^${Ee(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.onattach.push((i)=>{let r=i._zod.bag;r.patterns??(r.patterns=new Set),r.patterns.add(n)}),e._zod.check=(i)=>{if(i.value.startsWith(t.prefix))return;i.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:i.value,inst:e,continue:!t.abort})}}),Xo=p("$ZodCheckEndsWith",(e,t)=>{V.init(e,t);let n=new RegExp(`.*${Ee(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.onattach.push((i)=>{let r=i._zod.bag;r.patterns??(r.patterns=new Set),r.patterns.add(n)}),e._zod.check=(i)=>{if(i.value.endsWith(t.suffix))return;i.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:i.value,inst:e,continue:!t.abort})}}),Qo=p("$ZodCheckOverwrite",(e,t)=>{V.init(e,t),e._zod.check=(n)=>{n.value=t.tx(n.value)}});class Jn{constructor(e=[]){if(this.content=[],this.indent=0,this)this.args=e}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e==="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let t=e.split(`
2
2
  `).filter((r)=>r),n=Math.min(...t.map((r)=>r.length-r.trimStart().length)),i=t.map((r)=>r.slice(n)).map((r)=>" ".repeat(this.indent*2)+r);for(let r of i)this.content.push(r)}compile(){let e=Function,t=this?.args,n=[...(this?.content??[""]).map((i)=>` ${i}`)];return new e(...t,n.join(`
3
- `))}}var es={major:4,minor:4,patch:3},x=p("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=es;let i=[...e._zod.def.checks??[]];if(e._zod.traits.has("$ZodCheck"))i.unshift(e);for(let r of i)for(let o of r._zod.onattach)o(e);if(i.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let r=(s,a,u)=>{let c=Te(s),d;for(let y of a){if(y._zod.def.when){if(to(s))continue;if(!y._zod.def.when(s))continue}else if(c)continue;let g=s.issues.length,f=y._zod.check(s);if(f instanceof Promise&&u?.async===!1)throw new de;if(d||f instanceof Promise)d=(d??Promise.resolve()).then(async()=>{if(await f,s.issues.length===g)return;if(!c)c=Te(s,g)});else{if(s.issues.length===g)continue;if(!c)c=Te(s,g)}}if(d)return d.then(()=>s);return s},o=(s,a,u)=>{if(Te(s))return s.aborted=!0,s;let c=r(a,i,u);if(c instanceof Promise){if(u.async===!1)throw new de;return c.then((d)=>e._zod.parse(d,u))}return e._zod.parse(c,u)};e._zod.run=(s,a)=>{if(a.skipChecks)return e._zod.parse(s,a);if(a.direction==="backward"){let c=e._zod.parse({value:s.value,issues:[]},{...a,skipChecks:!0});if(c instanceof Promise)return c.then((d)=>o(d,s,a));return o(c,s,a)}let u=e._zod.parse(s,a);if(u instanceof Promise){if(a.async===!1)throw new de;return u.then((c)=>r(c,i,a))}return r(u,i,a)}}A(e,"~standard",()=>({validate:(r)=>{try{let o=oo(e,r);return o.success?{value:o.data}:{issues:o.error?.issues}}catch(o){return so(e,r).then((s)=>s.success?{value:s.data}:{issues:s.error?.issues})}},vendor:"zod",version:1}))}),St=p("$ZodString",(e,t)=>{x.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??zo(e._zod.bag),e._zod.parse=(n,i)=>{if(t.coerce)try{n.value=String(n.value)}catch(r){}if(typeof n.value==="string")return n;return n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),M=p("$ZodStringFormat",(e,t)=>{st.init(e,t),St.init(e,t)}),ts=p("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=ko),M.init(e,t)}),ns=p("$ZodUUID",(e,t)=>{if(t.version){let n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(n===void 0)throw Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=nn(n))}else t.pattern??(t.pattern=nn());M.init(e,t)}),is=p("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=Eo),M.init(e,t)}),rs=p("$ZodURL",(e,t)=>{M.init(e,t),e._zod.check=(n)=>{try{let i=n.value.trim();if(!t.normalize&&t.protocol?.source===Oo.source){if(!/^https?:\/\//i.test(i)){n.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:n.value,inst:e,continue:!t.abort});return}}let r=new URL(i);if(t.hostname){if(t.hostname.lastIndex=0,!t.hostname.test(r.hostname))n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort})}if(t.protocol){if(t.protocol.lastIndex=0,!t.protocol.test(r.protocol.endsWith(":")?r.protocol.slice(0,-1):r.protocol))n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})}if(t.normalize)n.value=r.href;else n.value=i;return}catch(i){n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),os=p("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=Co()),M.init(e,t)}),ss=p("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=wo),M.init(e,t)}),as=p("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=go),M.init(e,t)}),ls=p("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=yo),M.init(e,t)}),us=p("$ZodULID",(e,t)=>{t.pattern??(t.pattern=vo),M.init(e,t)}),cs=p("$ZodXID",(e,t)=>{t.pattern??(t.pattern=bo),M.init(e,t)}),ds=p("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=To),M.init(e,t)}),ps=p("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=Lo(t)),M.init(e,t)}),hs=p("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=Po),M.init(e,t)}),fs=p("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=$o(t)),M.init(e,t)}),ms=p("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=_o),M.init(e,t)}),gs=p("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=Ao),M.init(e,t),e._zod.bag.format="ipv4"}),ys=p("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=xo),M.init(e,t),e._zod.bag.format="ipv6",e._zod.check=(n)=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}}}),vs=p("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=Ro),M.init(e,t)}),bs=p("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=So),M.init(e,t),e._zod.check=(n)=>{let i=n.value.split("/");try{if(i.length!==2)throw Error();let[r,o]=i;if(!o)throw Error();let s=Number(o);if(`${s}`!==o)throw Error();if(s<0||s>128)throw Error();new URL(`http://[${r}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}}});function Yn(e){if(e==="")return!0;if(/\s/.test(e))return!1;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}var Ts=p("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=No),M.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=(n)=>{if(Yn(n.value))return;n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}});function ws(e){if(!qn.test(e))return!1;let t=e.replace(/[-_]/g,(i)=>i==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return Yn(n)}var _s=p("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=qn),M.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=(n)=>{if(ws(n.value))return;n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),ks=p("$ZodE164",(e,t)=>{t.pattern??(t.pattern=Mo),M.init(e,t)});function Es(e,t=null){try{let n=e.split(".");if(n.length!==3)return!1;let[i]=n;if(!i)return!1;let r=JSON.parse(atob(i));if("typ"in r&&r?.typ!=="JWT")return!1;if(!r.alg)return!1;if(t&&(!("alg"in r)||r.alg!==t))return!1;return!0}catch{return!1}}var Is=p("$ZodJWT",(e,t)=>{M.init(e,t),e._zod.check=(n)=>{if(Es(n.value,t.alg))return;n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),Xn=p("$ZodNumber",(e,t)=>{x.init(e,t),e._zod.pattern=e._zod.bag.pattern??Vn,e._zod.parse=(n,i)=>{if(t.coerce)try{n.value=Number(n.value)}catch(s){}let r=n.value;if(typeof r==="number"&&!Number.isNaN(r)&&Number.isFinite(r))return n;let o=typeof r==="number"?Number.isNaN(r)?"NaN":!Number.isFinite(r)?"Infinity":void 0:void 0;return n.issues.push({expected:"number",code:"invalid_type",input:r,inst:e,...o?{received:o}:{}}),n}}),Cs=p("$ZodNumberFormat",(e,t)=>{qo.init(e,t),Xn.init(e,t)}),As=p("$ZodBoolean",(e,t)=>{x.init(e,t),e._zod.pattern=Uo,e._zod.parse=(n,i)=>{if(t.coerce)try{n.value=Boolean(n.value)}catch(o){}let r=n.value;if(typeof r==="boolean")return n;return n.issues.push({expected:"boolean",code:"invalid_type",input:r,inst:e}),n}}),xs=p("$ZodUnknown",(e,t)=>{x.init(e,t),e._zod.parse=(n)=>n}),Rs=p("$ZodNever",(e,t)=>{x.init(e,t),e._zod.parse=(n,i)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:e}),n)}),Ss=p("$ZodVoid",(e,t)=>{x.init(e,t),e._zod.parse=(n,i)=>{let r=n.value;if(typeof r>"u")return n;return n.issues.push({expected:"void",code:"invalid_type",input:r,inst:e}),n}}),Ns=p("$ZodDate",(e,t)=>{x.init(e,t),e._zod.parse=(n,i)=>{if(t.coerce)try{n.value=new Date(n.value)}catch(s){}let r=n.value,o=r instanceof Date;if(o&&!Number.isNaN(r.getTime()))return n;return n.issues.push({expected:"date",code:"invalid_type",input:r,...o?{received:"Invalid Date"}:{},inst:e}),n}});function rn(e,t,n){if(e.issues.length)t.issues.push(...se(n,e.issues));t.value[n]=e.value}var Os=p("$ZodArray",(e,t)=>{x.init(e,t),e._zod.parse=(n,i)=>{let r=n.value;if(!Array.isArray(r))return n.issues.push({expected:"array",code:"invalid_type",input:r,inst:e}),n;n.value=Array(r.length);let o=[];for(let s=0;s<r.length;s++){let a=r[s],u=t.element._zod.run({value:a,issues:[]},i);if(u instanceof Promise)o.push(u.then((c)=>rn(c,n,s)));else rn(u,n,s)}if(o.length)return Promise.all(o).then(()=>n);return n}});function Ze(e,t,n,i,r,o){let s=n in i;if(e.issues.length){if(r&&o&&!s)return;t.issues.push(...se(n,e.issues))}if(!s&&!r){if(!e.issues.length)t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[n]});return}if(e.value===void 0){if(s)t.value[n]=void 0}else t.value[n]=e.value}function Qn(e){let t=Object.keys(e.shape);for(let i of t)if(!e.shape?.[i]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${i}": expected a Zod schema`);let n=Vr(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function ei(e,t,n,i,r,o){let s=[],a=r.keySet,u=r.catchall._zod,c=u.def.type,d=u.optin==="optional",y=u.optout==="optional";for(let g in t){if(g==="__proto__")continue;if(a.has(g))continue;if(c==="never"){s.push(g);continue}let f=u.run({value:t[g],issues:[]},i);if(f instanceof Promise)e.push(f.then((b)=>Ze(b,n,g,t,d,y)));else Ze(f,n,g,t,d,y)}if(s.length)n.issues.push({code:"unrecognized_keys",keys:s,input:t,inst:o});if(!e.length)return n;return Promise.all(e).then(()=>n)}var Ms=p("$ZodObject",(e,t)=>{if(x.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){let s=t.shape;Object.defineProperty(t,"shape",{get:()=>{let a={...s};return Object.defineProperty(t,"shape",{value:a}),a}})}let n=et(()=>Qn(t));A(e._zod,"propValues",()=>{let s=t.shape,a={};for(let u in s){let c=s[u]._zod;if(c.values){a[u]??(a[u]=new Set);for(let d of c.values)a[u].add(d)}}return a});let i=$e,r=t.catchall,o;e._zod.parse=(s,a)=>{o??(o=n.value);let u=s.value;if(!i(u))return s.issues.push({expected:"object",code:"invalid_type",input:u,inst:e}),s;s.value={};let c=[],d=o.shape;for(let y of o.keys){let g=d[y],f=g._zod.optin==="optional",b=g._zod.optout==="optional",w=g._zod.run({value:u[y],issues:[]},a);if(w instanceof Promise)c.push(w.then((G)=>Ze(G,s,y,u,f,b)));else Ze(w,s,y,u,f,b)}if(!r)return c.length?Promise.all(c).then(()=>s):s;return ei(c,u,s,a,n.value,e)}}),Ps=p("$ZodObjectJIT",(e,t)=>{Ms.init(e,t);let n=e._zod.parse,i=et(()=>Qn(t)),r=(y)=>{let g=new Jn(["shape","payload","ctx"]),f=i.value,b=(U)=>{let I=Qt(U);return`shape[${I}]._zod.run({ value: input[${I}], issues: [] }, ctx)`};g.write("const input = payload.value;");let w=Object.create(null),G=0;for(let U of f.keys)w[U]=`key_${G++}`;g.write("const newResult = {};");for(let U of f.keys){let I=w[U],O=Qt(U),ie=y[U],re=ie?._zod?.optin==="optional",q=ie?._zod?.optout==="optional";if(g.write(`const ${I} = ${b(U)};`),re&&q)g.write(`
3
+ `))}}var es={major:4,minor:4,patch:3},x=p("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=es;let i=[...e._zod.def.checks??[]];if(e._zod.traits.has("$ZodCheck"))i.unshift(e);for(let r of i)for(let o of r._zod.onattach)o(e);if(i.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let r=(s,a,u)=>{let c=be(s),d;for(let y of a){if(y._zod.def.when){if(to(s))continue;if(!y._zod.def.when(s))continue}else if(c)continue;let h=s.issues.length,g=y._zod.check(s);if(g instanceof Promise&&u?.async===!1)throw new de;if(d||g instanceof Promise)d=(d??Promise.resolve()).then(async()=>{if(await g,s.issues.length===h)return;if(!c)c=be(s,h)});else{if(s.issues.length===h)continue;if(!c)c=be(s,h)}}if(d)return d.then(()=>s);return s},o=(s,a,u)=>{if(be(s))return s.aborted=!0,s;let c=r(a,i,u);if(c instanceof Promise){if(u.async===!1)throw new de;return c.then((d)=>e._zod.parse(d,u))}return e._zod.parse(c,u)};e._zod.run=(s,a)=>{if(a.skipChecks)return e._zod.parse(s,a);if(a.direction==="backward"){let c=e._zod.parse({value:s.value,issues:[]},{...a,skipChecks:!0});if(c instanceof Promise)return c.then((d)=>o(d,s,a));return o(c,s,a)}let u=e._zod.parse(s,a);if(u instanceof Promise){if(a.async===!1)throw new de;return u.then((c)=>r(c,i,a))}return r(u,i,a)}}A(e,"~standard",()=>({validate:(r)=>{try{let o=oo(e,r);return o.success?{value:o.data}:{issues:o.error?.issues}}catch(o){return so(e,r).then((s)=>s.success?{value:s.data}:{issues:s.error?.issues})}},vendor:"zod",version:1}))}),St=p("$ZodString",(e,t)=>{x.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??zo(e._zod.bag),e._zod.parse=(n,i)=>{if(t.coerce)try{n.value=String(n.value)}catch(r){}if(typeof n.value==="string")return n;return n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),O=p("$ZodStringFormat",(e,t)=>{st.init(e,t),St.init(e,t)}),ts=p("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=ko),O.init(e,t)}),ns=p("$ZodUUID",(e,t)=>{if(t.version){let n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(n===void 0)throw Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=nn(n))}else t.pattern??(t.pattern=nn());O.init(e,t)}),is=p("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=Eo),O.init(e,t)}),rs=p("$ZodURL",(e,t)=>{O.init(e,t),e._zod.check=(n)=>{try{let i=n.value.trim();if(!t.normalize&&t.protocol?.source===Oo.source){if(!/^https?:\/\//i.test(i)){n.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:n.value,inst:e,continue:!t.abort});return}}let r=new URL(i);if(t.hostname){if(t.hostname.lastIndex=0,!t.hostname.test(r.hostname))n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort})}if(t.protocol){if(t.protocol.lastIndex=0,!t.protocol.test(r.protocol.endsWith(":")?r.protocol.slice(0,-1):r.protocol))n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})}if(t.normalize)n.value=r.href;else n.value=i;return}catch(i){n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),os=p("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=Co()),O.init(e,t)}),ss=p("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=wo),O.init(e,t)}),as=p("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=go),O.init(e,t)}),ls=p("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=yo),O.init(e,t)}),us=p("$ZodULID",(e,t)=>{t.pattern??(t.pattern=vo),O.init(e,t)}),cs=p("$ZodXID",(e,t)=>{t.pattern??(t.pattern=bo),O.init(e,t)}),ds=p("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=To),O.init(e,t)}),ps=p("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=Lo(t)),O.init(e,t)}),hs=p("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=Po),O.init(e,t)}),fs=p("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=$o(t)),O.init(e,t)}),ms=p("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=_o),O.init(e,t)}),gs=p("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=Ao),O.init(e,t),e._zod.bag.format="ipv4"}),ys=p("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=xo),O.init(e,t),e._zod.bag.format="ipv6",e._zod.check=(n)=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}}}),vs=p("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=Ro),O.init(e,t)}),bs=p("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=So),O.init(e,t),e._zod.check=(n)=>{let i=n.value.split("/");try{if(i.length!==2)throw Error();let[r,o]=i;if(!o)throw Error();let s=Number(o);if(`${s}`!==o)throw Error();if(s<0||s>128)throw Error();new URL(`http://[${r}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}}});function Yn(e){if(e==="")return!0;if(/\s/.test(e))return!1;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}var Ts=p("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=No),O.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=(n)=>{if(Yn(n.value))return;n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}});function ws(e){if(!qn.test(e))return!1;let t=e.replace(/[-_]/g,(i)=>i==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return Yn(n)}var _s=p("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=qn),O.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=(n)=>{if(ws(n.value))return;n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),ks=p("$ZodE164",(e,t)=>{t.pattern??(t.pattern=Mo),O.init(e,t)});function Es(e,t=null){try{let n=e.split(".");if(n.length!==3)return!1;let[i]=n;if(!i)return!1;let r=JSON.parse(atob(i));if("typ"in r&&r?.typ!=="JWT")return!1;if(!r.alg)return!1;if(t&&(!("alg"in r)||r.alg!==t))return!1;return!0}catch{return!1}}var Is=p("$ZodJWT",(e,t)=>{O.init(e,t),e._zod.check=(n)=>{if(Es(n.value,t.alg))return;n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),Xn=p("$ZodNumber",(e,t)=>{x.init(e,t),e._zod.pattern=e._zod.bag.pattern??Vn,e._zod.parse=(n,i)=>{if(t.coerce)try{n.value=Number(n.value)}catch(s){}let r=n.value;if(typeof r==="number"&&!Number.isNaN(r)&&Number.isFinite(r))return n;let o=typeof r==="number"?Number.isNaN(r)?"NaN":!Number.isFinite(r)?"Infinity":void 0:void 0;return n.issues.push({expected:"number",code:"invalid_type",input:r,inst:e,...o?{received:o}:{}}),n}}),Cs=p("$ZodNumberFormat",(e,t)=>{qo.init(e,t),Xn.init(e,t)}),As=p("$ZodBoolean",(e,t)=>{x.init(e,t),e._zod.pattern=Uo,e._zod.parse=(n,i)=>{if(t.coerce)try{n.value=Boolean(n.value)}catch(o){}let r=n.value;if(typeof r==="boolean")return n;return n.issues.push({expected:"boolean",code:"invalid_type",input:r,inst:e}),n}}),xs=p("$ZodUnknown",(e,t)=>{x.init(e,t),e._zod.parse=(n)=>n}),Rs=p("$ZodNever",(e,t)=>{x.init(e,t),e._zod.parse=(n,i)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:e}),n)}),Ss=p("$ZodVoid",(e,t)=>{x.init(e,t),e._zod.parse=(n,i)=>{let r=n.value;if(typeof r>"u")return n;return n.issues.push({expected:"void",code:"invalid_type",input:r,inst:e}),n}}),Ns=p("$ZodDate",(e,t)=>{x.init(e,t),e._zod.parse=(n,i)=>{if(t.coerce)try{n.value=new Date(n.value)}catch(s){}let r=n.value,o=r instanceof Date;if(o&&!Number.isNaN(r.getTime()))return n;return n.issues.push({expected:"date",code:"invalid_type",input:r,...o?{received:"Invalid Date"}:{},inst:e}),n}});function rn(e,t,n){if(e.issues.length)t.issues.push(...se(n,e.issues));t.value[n]=e.value}var Os=p("$ZodArray",(e,t)=>{x.init(e,t),e._zod.parse=(n,i)=>{let r=n.value;if(!Array.isArray(r))return n.issues.push({expected:"array",code:"invalid_type",input:r,inst:e}),n;n.value=Array(r.length);let o=[];for(let s=0;s<r.length;s++){let a=r[s],u=t.element._zod.run({value:a,issues:[]},i);if(u instanceof Promise)o.push(u.then((c)=>rn(c,n,s)));else rn(u,n,s)}if(o.length)return Promise.all(o).then(()=>n);return n}});function Ze(e,t,n,i,r,o){let s=n in i;if(e.issues.length){if(r&&o&&!s)return;t.issues.push(...se(n,e.issues))}if(!s&&!r){if(!e.issues.length)t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[n]});return}if(e.value===void 0){if(s)t.value[n]=void 0}else t.value[n]=e.value}function Qn(e){let t=Object.keys(e.shape);for(let i of t)if(!e.shape?.[i]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${i}": expected a Zod schema`);let n=Vr(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function ei(e,t,n,i,r,o){let s=[],a=r.keySet,u=r.catchall._zod,c=u.def.type,d=u.optin==="optional",y=u.optout==="optional";for(let h in t){if(h==="__proto__")continue;if(a.has(h))continue;if(c==="never"){s.push(h);continue}let g=u.run({value:t[h],issues:[]},i);if(g instanceof Promise)e.push(g.then((T)=>Ze(T,n,h,t,d,y)));else Ze(g,n,h,t,d,y)}if(s.length)n.issues.push({code:"unrecognized_keys",keys:s,input:t,inst:o});if(!e.length)return n;return Promise.all(e).then(()=>n)}var Ms=p("$ZodObject",(e,t)=>{if(x.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){let s=t.shape;Object.defineProperty(t,"shape",{get:()=>{let a={...s};return Object.defineProperty(t,"shape",{value:a}),a}})}let n=et(()=>Qn(t));A(e._zod,"propValues",()=>{let s=t.shape,a={};for(let u in s){let c=s[u]._zod;if(c.values){a[u]??(a[u]=new Set);for(let d of c.values)a[u].add(d)}}return a});let i=Pe,r=t.catchall,o;e._zod.parse=(s,a)=>{o??(o=n.value);let u=s.value;if(!i(u))return s.issues.push({expected:"object",code:"invalid_type",input:u,inst:e}),s;s.value={};let c=[],d=o.shape;for(let y of o.keys){let h=d[y],g=h._zod.optin==="optional",T=h._zod.optout==="optional",k=h._zod.run({value:u[y],issues:[]},a);if(k instanceof Promise)c.push(k.then((H)=>Ze(H,s,y,u,g,T)));else Ze(k,s,y,u,g,T)}if(!r)return c.length?Promise.all(c).then(()=>s):s;return ei(c,u,s,a,n.value,e)}}),Ps=p("$ZodObjectJIT",(e,t)=>{Ms.init(e,t);let n=e._zod.parse,i=et(()=>Qn(t)),r=(y)=>{let h=new Jn(["shape","payload","ctx"]),g=i.value,T=(U)=>{let I=Qt(U);return`shape[${I}]._zod.run({ value: input[${I}], issues: [] }, ctx)`};h.write("const input = payload.value;");let k=Object.create(null),H=0;for(let U of g.keys)k[U]=`key_${H++}`;h.write("const newResult = {};");for(let U of g.keys){let I=k[U],M=Qt(U),ie=y[U],re=ie?._zod?.optin==="optional",j=ie?._zod?.optout==="optional";if(h.write(`const ${I} = ${T(U)};`),re&&j)h.write(`
4
4
  if (${I}.issues.length) {
5
- if (${O} in input) {
5
+ if (${M} in input) {
6
6
  payload.issues = payload.issues.concat(${I}.issues.map(iss => ({
7
7
  ...iss,
8
- path: iss.path ? [${O}, ...iss.path] : [${O}]
8
+ path: iss.path ? [${M}, ...iss.path] : [${M}]
9
9
  })));
10
10
  }
11
11
  }
12
12
 
13
13
  if (${I}.value === undefined) {
14
- if (${O} in input) {
15
- newResult[${O}] = undefined;
14
+ if (${M} in input) {
15
+ newResult[${M}] = undefined;
16
16
  }
17
17
  } else {
18
- newResult[${O}] = ${I}.value;
18
+ newResult[${M}] = ${I}.value;
19
19
  }
20
20
 
21
- `);else if(!re)g.write(`
22
- const ${I}_present = ${O} in input;
21
+ `);else if(!re)h.write(`
22
+ const ${I}_present = ${M} in input;
23
23
  if (${I}.issues.length) {
24
24
  payload.issues = payload.issues.concat(${I}.issues.map(iss => ({
25
25
  ...iss,
26
- path: iss.path ? [${O}, ...iss.path] : [${O}]
26
+ path: iss.path ? [${M}, ...iss.path] : [${M}]
27
27
  })));
28
28
  }
29
29
  if (!${I}_present && !${I}.issues.length) {
@@ -31,37 +31,37 @@ var Pn="input_progress";var zr=[/\bserver is shutting down\b/i,/^(?:error:\s*)?(
31
31
  code: "invalid_type",
32
32
  expected: "nonoptional",
33
33
  input: undefined,
34
- path: [${O}]
34
+ path: [${M}]
35
35
  });
36
36
  }
37
37
 
38
38
  if (${I}_present) {
39
39
  if (${I}.value === undefined) {
40
- newResult[${O}] = undefined;
40
+ newResult[${M}] = undefined;
41
41
  } else {
42
- newResult[${O}] = ${I}.value;
42
+ newResult[${M}] = ${I}.value;
43
43
  }
44
44
  }
45
45
 
46
- `);else g.write(`
46
+ `);else h.write(`
47
47
  if (${I}.issues.length) {
48
48
  payload.issues = payload.issues.concat(${I}.issues.map(iss => ({
49
49
  ...iss,
50
- path: iss.path ? [${O}, ...iss.path] : [${O}]
50
+ path: iss.path ? [${M}, ...iss.path] : [${M}]
51
51
  })));
52
52
  }
53
53
 
54
54
  if (${I}.value === undefined) {
55
- if (${O} in input) {
56
- newResult[${O}] = undefined;
55
+ if (${M} in input) {
56
+ newResult[${M}] = undefined;
57
57
  }
58
58
  } else {
59
- newResult[${O}] = ${I}.value;
59
+ newResult[${M}] = ${I}.value;
60
60
  }
61
61
 
62
- `)}g.write("payload.value = newResult;"),g.write("return payload;");let j=g.compile();return(U,I)=>j(y,U,I)},o,s=$e,a=!Ve.jitless,u=a&&Hr.value,c=t.catchall,d;e._zod.parse=(y,g)=>{d??(d=i.value);let f=y.value;if(!s(f))return y.issues.push({expected:"object",code:"invalid_type",input:f,inst:e}),y;if(a&&u&&g?.async===!1&&g.jitless!==!0){if(!o)o=r(t.shape);if(y=o(y,g),!c)return y;return ei([],f,y,g,d,e)}return n(y,g)}});function on(e,t,n,i){for(let o of e)if(o.issues.length===0)return t.value=o.value,t;let r=e.filter((o)=>!Te(o));if(r.length===1)return t.value=r[0].value,r[0];return t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map((o)=>o.issues.map((s)=>te(s,i,ee())))}),t}var ti=p("$ZodUnion",(e,t)=>{x.init(e,t),A(e._zod,"optin",()=>t.options.some((i)=>i._zod.optin==="optional")?"optional":void 0),A(e._zod,"optout",()=>t.options.some((i)=>i._zod.optout==="optional")?"optional":void 0),A(e._zod,"values",()=>{if(t.options.every((i)=>i._zod.values))return new Set(t.options.flatMap((i)=>Array.from(i._zod.values)));return}),A(e._zod,"pattern",()=>{if(t.options.every((i)=>i._zod.pattern)){let i=t.options.map((r)=>r._zod.pattern);return new RegExp(`^(${i.map((r)=>xt(r.source)).join("|")})$`)}return});let n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(i,r)=>{if(n)return n(i,r);let o=!1,s=[];for(let a of t.options){let u=a._zod.run({value:i.value,issues:[]},r);if(u instanceof Promise)s.push(u),o=!0;else{if(u.issues.length===0)return u;s.push(u)}}if(!o)return on(s,i,e,r);return Promise.all(s).then((a)=>on(a,i,e,r))}}),$s=p("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,ti.init(e,t);let n=e._zod.parse;A(e._zod,"propValues",()=>{let r={};for(let o of t.options){let s=o._zod.propValues;if(!s||Object.keys(s).length===0)throw Error(`Invalid discriminated union option at index "${t.options.indexOf(o)}"`);for(let[a,u]of Object.entries(s)){if(!r[a])r[a]=new Set;for(let c of u)r[a].add(c)}}return r});let i=et(()=>{let r=t.options,o=new Map;for(let s of r){let a=s._zod.propValues?.[t.discriminator];if(!a||a.size===0)throw Error(`Invalid discriminated union option at index "${t.options.indexOf(s)}"`);for(let u of a){if(o.has(u))throw Error(`Duplicate discriminator value "${String(u)}"`);o.set(u,s)}}return o});e._zod.parse=(r,o)=>{let s=r.value;if(!$e(s))return r.issues.push({code:"invalid_type",expected:"object",input:s,inst:e}),r;let a=i.value.get(s?.[t.discriminator]);if(a)return a._zod.run(r,o);if(t.unionFallback||o.direction==="backward")return n(r,o);return r.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,options:Array.from(i.value.keys()),input:s,path:[t.discriminator],inst:e}),r}}),Ls=p("$ZodIntersection",(e,t)=>{x.init(e,t),e._zod.parse=(n,i)=>{let r=n.value,o=t.left._zod.run({value:r,issues:[]},i),s=t.right._zod.run({value:r,issues:[]},i);if(o instanceof Promise||s instanceof Promise)return Promise.all([o,s]).then(([a,u])=>sn(n,a,u));return sn(n,o,s)}});function wt(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(Ee(e)&&Ee(t)){let n=Object.keys(t),i=Object.keys(e).filter((o)=>n.indexOf(o)!==-1),r={...e,...t};for(let o of i){let s=wt(e[o],t[o]);if(!s.valid)return{valid:!1,mergeErrorPath:[o,...s.mergeErrorPath]};r[o]=s.data}return{valid:!0,data:r}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let i=0;i<e.length;i++){let r=e[i],o=t[i],s=wt(r,o);if(!s.valid)return{valid:!1,mergeErrorPath:[i,...s.mergeErrorPath]};n.push(s.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function sn(e,t,n){let i=new Map,r;for(let a of t.issues)if(a.code==="unrecognized_keys"){r??(r=a);for(let u of a.keys){if(!i.has(u))i.set(u,{});i.get(u).l=!0}}else e.issues.push(a);for(let a of n.issues)if(a.code==="unrecognized_keys")for(let u of a.keys){if(!i.has(u))i.set(u,{});i.get(u).r=!0}else e.issues.push(a);let o=[...i].filter(([,a])=>a.l&&a.r).map(([a])=>a);if(o.length&&r)e.issues.push({...r,keys:o});if(Te(e))return e;let s=wt(t.value,n.value);if(!s.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(s.mergeErrorPath)}`);return e.value=s.data,e}var ni=p("$ZodTuple",(e,t)=>{x.init(e,t);let n=t.items;e._zod.parse=(i,r)=>{let o=i.value;if(!Array.isArray(o))return i.issues.push({input:o,inst:e,expected:"tuple",code:"invalid_type"}),i;i.value=[];let s=[],a=an(n,"optin"),u=an(n,"optout");if(!t.rest){if(o.length<a)return i.issues.push({code:"too_small",minimum:a,inclusive:!0,input:o,inst:e,origin:"array"}),i;if(o.length>n.length)i.issues.push({code:"too_big",maximum:n.length,inclusive:!0,input:o,inst:e,origin:"array"})}let c=Array(n.length);for(let d=0;d<n.length;d++){let y=n[d]._zod.run({value:o[d],issues:[]},r);if(y instanceof Promise)s.push(y.then((g)=>{c[d]=g}));else c[d]=y}if(t.rest){let d=n.length-1,y=o.slice(n.length);for(let g of y){d++;let f=t.rest._zod.run({value:g,issues:[]},r);if(f instanceof Promise)s.push(f.then((b)=>ln(b,i,d)));else ln(f,i,d)}}if(s.length)return Promise.all(s).then(()=>un(c,i,n,o,u));return un(c,i,n,o,u)}});function an(e,t){for(let n=e.length-1;n>=0;n--)if(e[n]._zod[t]!=="optional")return n+1;return 0}function ln(e,t,n){if(e.issues.length)t.issues.push(...se(n,e.issues));t.value[n]=e.value}function un(e,t,n,i,r){for(let o=0;o<n.length;o++){let s=e[o],a=o<i.length;if(s.issues.length){if(!a&&o>=r){t.value.length=o;break}t.issues.push(...se(o,s.issues))}t.value[o]=s.value}for(let o=t.value.length-1;o>=i.length;o--)if(n[o]._zod.optout==="optional"&&t.value[o]===void 0)t.value.length=o;else break;return t}var zs=p("$ZodRecord",(e,t)=>{x.init(e,t),e._zod.parse=(n,i)=>{let r=n.value;if(!Ee(r))return n.issues.push({expected:"record",code:"invalid_type",input:r,inst:e}),n;let o=[],s=t.keyType._zod.values;if(s){n.value={};let a=new Set;for(let c of s)if(typeof c==="string"||typeof c==="number"||typeof c==="symbol"){a.add(typeof c==="number"?c.toString():c);let d=t.keyType._zod.run({value:c,issues:[]},i);if(d instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(d.issues.length){n.issues.push({code:"invalid_key",origin:"record",issues:d.issues.map((f)=>te(f,i,ee())),input:c,path:[c],inst:e});continue}let y=d.value,g=t.valueType._zod.run({value:r[c],issues:[]},i);if(g instanceof Promise)o.push(g.then((f)=>{if(f.issues.length)n.issues.push(...se(c,f.issues));n.value[y]=f.value}));else{if(g.issues.length)n.issues.push(...se(c,g.issues));n.value[y]=g.value}}let u;for(let c in r)if(!a.has(c))u=u??[],u.push(c);if(u&&u.length>0)n.issues.push({code:"unrecognized_keys",input:r,inst:e,keys:u})}else{n.value={};for(let a of Reflect.ownKeys(r)){if(a==="__proto__")continue;if(!Object.prototype.propertyIsEnumerable.call(r,a))continue;let u=t.keyType._zod.run({value:a,issues:[]},i);if(u instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(typeof a==="string"&&Vn.test(a)&&u.issues.length){let d=t.keyType._zod.run({value:Number(a),issues:[]},i);if(d instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(d.issues.length===0)u=d}if(u.issues.length){if(t.mode==="loose")n.value[a]=r[a];else n.issues.push({code:"invalid_key",origin:"record",issues:u.issues.map((d)=>te(d,i,ee())),input:a,path:[a],inst:e});continue}let c=t.valueType._zod.run({value:r[a],issues:[]},i);if(c instanceof Promise)o.push(c.then((d)=>{if(d.issues.length)n.issues.push(...se(a,d.issues));n.value[u.value]=d.value}));else{if(c.issues.length)n.issues.push(...se(a,c.issues));n.value[u.value]=c.value}}}if(o.length)return Promise.all(o).then(()=>n);return n}}),Ds=p("$ZodEnum",(e,t)=>{x.init(e,t);let n=zn(t.entries),i=new Set(n);e._zod.values=i,e._zod.pattern=new RegExp(`^(${n.filter((r)=>Wr.has(typeof r)).map((r)=>typeof r==="string"?Ie(r):r.toString()).join("|")})$`),e._zod.parse=(r,o)=>{let s=r.value;if(i.has(s))return r;return r.issues.push({code:"invalid_value",values:n,input:s,inst:e}),r}}),Us=p("$ZodLiteral",(e,t)=>{if(x.init(e,t),t.values.length===0)throw Error("Cannot create literal schema with no valid values");let n=new Set(t.values);e._zod.values=n,e._zod.pattern=new RegExp(`^(${t.values.map((i)=>typeof i==="string"?Ie(i):i?Ie(i.toString()):String(i)).join("|")})$`),e._zod.parse=(i,r)=>{let o=i.value;if(n.has(o))return i;return i.issues.push({code:"invalid_value",values:t.values,input:o,inst:e}),i}}),Fs=p("$ZodTransform",(e,t)=>{x.init(e,t),e._zod.optin="optional",e._zod.parse=(n,i)=>{if(i.direction==="backward")throw new Ct(e.constructor.name);let r=t.transform(n.value,n);if(i.async)return(r instanceof Promise?r:Promise.resolve(r)).then((o)=>(n.value=o,n.fallback=!0,n));if(r instanceof Promise)throw new de;return n.value=r,n.fallback=!0,n}});function cn(e,t){if(t===void 0&&(e.issues.length||e.fallback))return{issues:[],value:void 0};return e}var ii=p("$ZodOptional",(e,t)=>{x.init(e,t),e._zod.optin="optional",e._zod.optout="optional",A(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),A(e._zod,"pattern",()=>{let n=t.innerType._zod.pattern;return n?new RegExp(`^(${xt(n.source)})?$`):void 0}),e._zod.parse=(n,i)=>{if(t.innerType._zod.optin==="optional"){let r=n.value,o=t.innerType._zod.run(n,i);if(o instanceof Promise)return o.then((s)=>cn(s,r));return cn(o,r)}if(n.value===void 0)return n;return t.innerType._zod.run(n,i)}}),Bs=p("$ZodExactOptional",(e,t)=>{ii.init(e,t),A(e._zod,"values",()=>t.innerType._zod.values),A(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(n,i)=>t.innerType._zod.run(n,i)}),js=p("$ZodNullable",(e,t)=>{x.init(e,t),A(e._zod,"optin",()=>t.innerType._zod.optin),A(e._zod,"optout",()=>t.innerType._zod.optout),A(e._zod,"pattern",()=>{let n=t.innerType._zod.pattern;return n?new RegExp(`^(${xt(n.source)}|null)$`):void 0}),A(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(n,i)=>{if(n.value===null)return n;return t.innerType._zod.run(n,i)}}),qs=p("$ZodDefault",(e,t)=>{x.init(e,t),e._zod.optin="optional",A(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,i)=>{if(i.direction==="backward")return t.innerType._zod.run(n,i);if(n.value===void 0)return n.value=t.defaultValue,n;let r=t.innerType._zod.run(n,i);if(r instanceof Promise)return r.then((o)=>dn(o,t));return dn(r,t)}});function dn(e,t){if(e.value===void 0)e.value=t.defaultValue;return e}var Hs=p("$ZodPrefault",(e,t)=>{x.init(e,t),e._zod.optin="optional",A(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,i)=>{if(i.direction==="backward")return t.innerType._zod.run(n,i);if(n.value===void 0)n.value=t.defaultValue;return t.innerType._zod.run(n,i)}}),Ws=p("$ZodNonOptional",(e,t)=>{x.init(e,t),A(e._zod,"values",()=>{let n=t.innerType._zod.values;return n?new Set([...n].filter((i)=>i!==void 0)):void 0}),e._zod.parse=(n,i)=>{let r=t.innerType._zod.run(n,i);if(r instanceof Promise)return r.then((o)=>pn(o,e));return pn(r,e)}});function pn(e,t){if(!e.issues.length&&e.value===void 0)e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t});return e}var Vs=p("$ZodCatch",(e,t)=>{x.init(e,t),e._zod.optin="optional",A(e._zod,"optout",()=>t.innerType._zod.optout),A(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,i)=>{if(i.direction==="backward")return t.innerType._zod.run(n,i);let r=t.innerType._zod.run(n,i);if(r instanceof Promise)return r.then((o)=>{if(n.value=o.value,o.issues.length)n.value=t.catchValue({...n,error:{issues:o.issues.map((s)=>te(s,i,ee()))},input:n.value}),n.issues=[],n.fallback=!0;return n});if(n.value=r.value,r.issues.length)n.value=t.catchValue({...n,error:{issues:r.issues.map((o)=>te(o,i,ee()))},input:n.value}),n.issues=[],n.fallback=!0;return n}}),ri=p("$ZodPipe",(e,t)=>{x.init(e,t),A(e._zod,"values",()=>t.in._zod.values),A(e._zod,"optin",()=>t.in._zod.optin),A(e._zod,"optout",()=>t.out._zod.optout),A(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(n,i)=>{if(i.direction==="backward"){let o=t.out._zod.run(n,i);if(o instanceof Promise)return o.then((s)=>Be(s,t.in,i));return Be(o,t.in,i)}let r=t.in._zod.run(n,i);if(r instanceof Promise)return r.then((o)=>Be(o,t.out,i));return Be(r,t.out,i)}});function Be(e,t,n){if(e.issues.length)return e.aborted=!0,e;return t._zod.run({value:e.value,issues:e.issues,fallback:e.fallback},n)}var Zs=p("$ZodPreprocess",(e,t)=>{ri.init(e,t)}),Gs=p("$ZodReadonly",(e,t)=>{x.init(e,t),A(e._zod,"propValues",()=>t.innerType._zod.propValues),A(e._zod,"values",()=>t.innerType._zod.values),A(e._zod,"optin",()=>t.innerType?._zod?.optin),A(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(n,i)=>{if(i.direction==="backward")return t.innerType._zod.run(n,i);let r=t.innerType._zod.run(n,i);if(r instanceof Promise)return r.then(hn);return hn(r)}});function hn(e){return e.value=Object.freeze(e.value),e}var Ks=p("$ZodFunction",(e,t)=>(x.init(e,t),e._def=t,e._zod.def=t,e.implement=(n)=>{if(typeof n!=="function")throw Error("implement() must be called with a function");return function(...i){let r=e._def.input?en(e._def.input,i):i,o=Reflect.apply(n,this,r);if(e._def.output)return en(e._def.output,o);return o}},e.implementAsync=(n)=>{if(typeof n!=="function")throw Error("implementAsync() must be called with a function");return async function(...i){let r=e._def.input?await tn(e._def.input,i):i,o=await Reflect.apply(n,this,r);if(e._def.output)return await tn(e._def.output,o);return o}},e._zod.parse=(n,i)=>{if(typeof n.value!=="function")return n.issues.push({code:"invalid_type",expected:"function",input:n.value,inst:e}),n;if(e._def.output&&e._def.output._zod.def.type==="promise")n.value=e.implementAsync(n.value);else n.value=e.implement(n.value);return n},e.input=(...n)=>{let i=e.constructor;if(Array.isArray(n[0]))return new i({type:"function",input:new ni({type:"tuple",items:n[0],rest:n[1]}),output:e._def.output});return new i({type:"function",input:n[0],output:e._def.output})},e.output=(n)=>new e.constructor({type:"function",input:e._def.input,output:n}),e)),Js=p("$ZodPromise",(e,t)=>{x.init(e,t),e._zod.parse=(n,i)=>Promise.resolve(n.value).then((r)=>t.innerType._zod.run({value:r,issues:[]},i))}),Ys=p("$ZodCustom",(e,t)=>{V.init(e,t),x.init(e,t),e._zod.parse=(n,i)=>n,e._zod.check=(n)=>{let i=n.value,r=t.fn(i);if(r instanceof Promise)return r.then((o)=>fn(o,n,i,e));fn(r,n,i,e);return}});function fn(e,t,n,i){if(!e){let r={code:"custom",input:n,inst:i,path:[...i._zod.def.path??[]],continue:!i._zod.def.abort};if(i._zod.def.params)r.params=i._zod.def.params;t.issues.push(Le(r))}}var Xs=()=>{let e={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"},map:{unit:"entries",verb:"to have"}};function t(r){return e[r]??null}let n={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"},i={nan:"NaN"};return(r)=>{switch(r.code){case"invalid_type":{let o=i[r.expected]??r.expected,s=no(r.input),a=i[s]??s;return`Invalid input: expected ${o}, received ${a}`}case"invalid_value":if(r.values.length===1)return`Invalid input: expected ${Fn(r.values[0])}`;return`Invalid option: expected one of ${Yt(r.values,"|")}`;case"too_big":{let o=r.inclusive?"<=":"<",s=t(r.origin);if(s)return`Too big: expected ${r.origin??"value"} to have ${o}${r.maximum.toString()} ${s.unit??"elements"}`;return`Too big: expected ${r.origin??"value"} to be ${o}${r.maximum.toString()}`}case"too_small":{let o=r.inclusive?">=":">",s=t(r.origin);if(s)return`Too small: expected ${r.origin} to have ${o}${r.minimum.toString()} ${s.unit}`;return`Too small: expected ${r.origin} to be ${o}${r.minimum.toString()}`}case"invalid_format":{let o=r;if(o.format==="starts_with")return`Invalid string: must start with "${o.prefix}"`;if(o.format==="ends_with")return`Invalid string: must end with "${o.suffix}"`;if(o.format==="includes")return`Invalid string: must include "${o.includes}"`;if(o.format==="regex")return`Invalid string: must match pattern ${o.pattern}`;return`Invalid ${n[o.format]??r.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${r.divisor}`;case"unrecognized_keys":return`Unrecognized key${r.keys.length>1?"s":""}: ${Yt(r.keys,", ")}`;case"invalid_key":return`Invalid key in ${r.origin}`;case"invalid_union":if(r.options&&Array.isArray(r.options)&&r.options.length>0)return`Invalid discriminator value. Expected ${r.options.map((o)=>`'${o}'`).join(" | ")}`;return"Invalid input";case"invalid_element":return`Invalid value in ${r.origin}`;default:return"Invalid input"}}};function Qs(){return{localeError:Xs()}}var mn,vp=Symbol("ZodOutput"),bp=Symbol("ZodInput");class oi{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){let n=t[0];if(this._map.set(e,n),n&&typeof n==="object"&&"id"in n)this._idmap.set(n.id,e);return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let t=this._map.get(e);if(t&&typeof t==="object"&&"id"in t)this._idmap.delete(t.id);return this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let n={...this.get(t)??{}};delete n.id;let i={...n,...this._map.get(e)};return Object.keys(i).length?i:void 0}return this._map.get(e)}has(e){return this._map.has(e)}}function ea(){return new oi}(mn=globalThis).__zod_globalRegistry??(mn.__zod_globalRegistry=ea());var Ne=globalThis.__zod_globalRegistry;function ta(e,t){return new e({type:"string",...T(t)})}function na(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...T(t)})}function gn(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...T(t)})}function ia(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...T(t)})}function ra(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...T(t)})}function oa(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...T(t)})}function sa(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...T(t)})}function aa(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...T(t)})}function la(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...T(t)})}function ua(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...T(t)})}function ca(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...T(t)})}function da(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...T(t)})}function pa(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...T(t)})}function ha(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...T(t)})}function fa(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...T(t)})}function ma(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...T(t)})}function ga(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...T(t)})}function ya(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...T(t)})}function va(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...T(t)})}function ba(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...T(t)})}function Ta(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...T(t)})}function wa(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...T(t)})}function _a(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...T(t)})}function ka(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...T(t)})}function Ea(e,t){return new e({type:"string",format:"date",check:"string_format",...T(t)})}function Ia(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...T(t)})}function Ca(e,t){return new e({type:"string",format:"duration",check:"string_format",...T(t)})}function Aa(e,t){return new e({type:"number",checks:[],...T(t)})}function xa(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...T(t)})}function Ra(e,t){return new e({type:"boolean",...T(t)})}function Sa(e){return new e({type:"unknown"})}function Na(e,t){return new e({type:"never",...T(t)})}function Oa(e,t){return new e({type:"void",...T(t)})}function Ma(e,t){return new e({type:"date",...T(t)})}function yn(e,t){return new Gn({check:"less_than",...T(t),value:e,inclusive:!1})}function He(e,t){return new Gn({check:"less_than",...T(t),value:e,inclusive:!0})}function vn(e,t){return new Kn({check:"greater_than",...T(t),value:e,inclusive:!1})}function We(e,t){return new Kn({check:"greater_than",...T(t),value:e,inclusive:!0})}function bn(e,t){return new jo({check:"multiple_of",...T(t),value:e})}function si(e,t){return new Ho({check:"max_length",...T(t),maximum:e})}function Ge(e,t){return new Wo({check:"min_length",...T(t),minimum:e})}function ai(e,t){return new Vo({check:"length_equals",...T(t),length:e})}function Pa(e,t){return new Zo({check:"string_format",format:"regex",...T(t),pattern:e})}function $a(e){return new Go({check:"string_format",format:"lowercase",...T(e)})}function La(e){return new Ko({check:"string_format",format:"uppercase",...T(e)})}function za(e,t){return new Jo({check:"string_format",format:"includes",...T(t),includes:e})}function Da(e,t){return new Yo({check:"string_format",format:"starts_with",...T(t),prefix:e})}function Ua(e,t){return new Xo({check:"string_format",format:"ends_with",...T(t),suffix:e})}function Ae(e){return new Qo({check:"overwrite",tx:e})}function Fa(e){return Ae((t)=>t.normalize(e))}function Ba(){return Ae((e)=>e.trim())}function ja(){return Ae((e)=>e.toLowerCase())}function qa(){return Ae((e)=>e.toUpperCase())}function Ha(){return Ae((e)=>qr(e))}function Wa(e,t,n){return new e({type:"array",element:t,...T(n)})}function Va(e,t,n){let i=T(n);return i.abort??(i.abort=!0),new e({type:"custom",check:"custom",fn:t,...i})}function Za(e,t,n){return new e({type:"custom",check:"custom",fn:t,...T(n)})}function Ga(e,t){let n=Ka((i)=>(i.addIssue=(r)=>{if(typeof r==="string")i.issues.push(Le(r,i.value,n._zod.def));else{let o=r;if(o.fatal)o.continue=!1;o.code??(o.code="custom"),o.input??(o.input=i.value),o.inst??(o.inst=n),o.continue??(o.continue=!n._zod.def.abort),i.issues.push(Le(o))}},e(i.value,i)),t);return n}function Ka(e,t){let n=new V({check:"custom",...T(t)});return n._zod.check=e,n}function Ke(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??Ne,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,cycles:e?.cycles??"ref",reused:e?.reused??"inline",external:e?.external??void 0}}function S(e,t,n={path:[],schemaPath:[]}){var i;let r=e._zod.def,o=t.seen.get(e);if(o){if(o.count++,n.schemaPath.includes(e))o.cycle=n.path;return o.schema}let s={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,s);let a=e._zod.toJSONSchema?.();if(a)s.schema=a;else{let c={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,s.schema,c);else{let y=s.schema,g=t.processors[r.type];if(!g)throw Error(`[toJSONSchema]: Non-representable type encountered: ${r.type}`);g(e,t,y,c)}let d=e._zod.parent;if(d){if(!s.ref)s.ref=d;S(d,t,c),t.seen.get(d).isParent=!0}}let u=t.metadataRegistry.get(e);if(u)Object.assign(s.schema,u);if(t.io==="input"&&H(e))delete s.schema.examples,delete s.schema.default;if(t.io==="input"&&"_prefault"in s.schema)(i=s.schema).default??(i.default=s.schema._prefault);return delete s.schema._prefault,t.seen.get(e).schema}function Je(e,t){let n=e.seen.get(t);if(!n)throw Error("Unprocessed schema. This is a bug in Zod.");let i=new Map;for(let s of e.seen.entries()){let a=e.metadataRegistry.get(s[0])?.id;if(a){let u=i.get(a);if(u&&u!==s[0])throw Error(`Duplicate schema id "${a}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);i.set(a,s[0])}}let r=(s)=>{let a=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){let d=e.external.registry.get(s[0])?.id,y=e.external.uri??((f)=>f);if(d)return{ref:y(d)};let g=s[1].defId??s[1].schema.id??`schema${e.counter++}`;return s[1].defId=g,{defId:g,ref:`${y("__shared")}#/${a}/${g}`}}if(s[1]===n)return{ref:"#"};let u=`#/${a}/`,c=s[1].schema.id??`__schema${e.counter++}`;return{defId:c,ref:u+c}},o=(s)=>{if(s[1].schema.$ref)return;let a=s[1],{ref:u,defId:c}=r(s);if(a.def={...a.schema},c)a.defId=c;let d=a.schema;for(let y in d)delete d[y];d.$ref=u};if(e.cycles==="throw")for(let s of e.seen.entries()){let a=s[1];if(a.cycle)throw Error(`Cycle detected: #/${a.cycle?.join("/")}/<root>
62
+ `)}h.write("payload.value = newResult;"),h.write("return payload;");let Z=h.compile();return(U,I)=>Z(y,U,I)},o,s=Pe,a=!Ve.jitless,u=a&&Hr.value,c=t.catchall,d;e._zod.parse=(y,h)=>{d??(d=i.value);let g=y.value;if(!s(g))return y.issues.push({expected:"object",code:"invalid_type",input:g,inst:e}),y;if(a&&u&&h?.async===!1&&h.jitless!==!0){if(!o)o=r(t.shape);if(y=o(y,h),!c)return y;return ei([],g,y,h,d,e)}return n(y,h)}});function on(e,t,n,i){for(let o of e)if(o.issues.length===0)return t.value=o.value,t;let r=e.filter((o)=>!be(o));if(r.length===1)return t.value=r[0].value,r[0];return t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map((o)=>o.issues.map((s)=>te(s,i,ee())))}),t}var ti=p("$ZodUnion",(e,t)=>{x.init(e,t),A(e._zod,"optin",()=>t.options.some((i)=>i._zod.optin==="optional")?"optional":void 0),A(e._zod,"optout",()=>t.options.some((i)=>i._zod.optout==="optional")?"optional":void 0),A(e._zod,"values",()=>{if(t.options.every((i)=>i._zod.values))return new Set(t.options.flatMap((i)=>Array.from(i._zod.values)));return}),A(e._zod,"pattern",()=>{if(t.options.every((i)=>i._zod.pattern)){let i=t.options.map((r)=>r._zod.pattern);return new RegExp(`^(${i.map((r)=>xt(r.source)).join("|")})$`)}return});let n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(i,r)=>{if(n)return n(i,r);let o=!1,s=[];for(let a of t.options){let u=a._zod.run({value:i.value,issues:[]},r);if(u instanceof Promise)s.push(u),o=!0;else{if(u.issues.length===0)return u;s.push(u)}}if(!o)return on(s,i,e,r);return Promise.all(s).then((a)=>on(a,i,e,r))}}),$s=p("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,ti.init(e,t);let n=e._zod.parse;A(e._zod,"propValues",()=>{let r={};for(let o of t.options){let s=o._zod.propValues;if(!s||Object.keys(s).length===0)throw Error(`Invalid discriminated union option at index "${t.options.indexOf(o)}"`);for(let[a,u]of Object.entries(s)){if(!r[a])r[a]=new Set;for(let c of u)r[a].add(c)}}return r});let i=et(()=>{let r=t.options,o=new Map;for(let s of r){let a=s._zod.propValues?.[t.discriminator];if(!a||a.size===0)throw Error(`Invalid discriminated union option at index "${t.options.indexOf(s)}"`);for(let u of a){if(o.has(u))throw Error(`Duplicate discriminator value "${String(u)}"`);o.set(u,s)}}return o});e._zod.parse=(r,o)=>{let s=r.value;if(!Pe(s))return r.issues.push({code:"invalid_type",expected:"object",input:s,inst:e}),r;let a=i.value.get(s?.[t.discriminator]);if(a)return a._zod.run(r,o);if(t.unionFallback||o.direction==="backward")return n(r,o);return r.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,options:Array.from(i.value.keys()),input:s,path:[t.discriminator],inst:e}),r}}),Ls=p("$ZodIntersection",(e,t)=>{x.init(e,t),e._zod.parse=(n,i)=>{let r=n.value,o=t.left._zod.run({value:r,issues:[]},i),s=t.right._zod.run({value:r,issues:[]},i);if(o instanceof Promise||s instanceof Promise)return Promise.all([o,s]).then(([a,u])=>sn(n,a,u));return sn(n,o,s)}});function wt(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(ke(e)&&ke(t)){let n=Object.keys(t),i=Object.keys(e).filter((o)=>n.indexOf(o)!==-1),r={...e,...t};for(let o of i){let s=wt(e[o],t[o]);if(!s.valid)return{valid:!1,mergeErrorPath:[o,...s.mergeErrorPath]};r[o]=s.data}return{valid:!0,data:r}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let i=0;i<e.length;i++){let r=e[i],o=t[i],s=wt(r,o);if(!s.valid)return{valid:!1,mergeErrorPath:[i,...s.mergeErrorPath]};n.push(s.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function sn(e,t,n){let i=new Map,r;for(let a of t.issues)if(a.code==="unrecognized_keys"){r??(r=a);for(let u of a.keys){if(!i.has(u))i.set(u,{});i.get(u).l=!0}}else e.issues.push(a);for(let a of n.issues)if(a.code==="unrecognized_keys")for(let u of a.keys){if(!i.has(u))i.set(u,{});i.get(u).r=!0}else e.issues.push(a);let o=[...i].filter(([,a])=>a.l&&a.r).map(([a])=>a);if(o.length&&r)e.issues.push({...r,keys:o});if(be(e))return e;let s=wt(t.value,n.value);if(!s.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(s.mergeErrorPath)}`);return e.value=s.data,e}var ni=p("$ZodTuple",(e,t)=>{x.init(e,t);let n=t.items;e._zod.parse=(i,r)=>{let o=i.value;if(!Array.isArray(o))return i.issues.push({input:o,inst:e,expected:"tuple",code:"invalid_type"}),i;i.value=[];let s=[],a=an(n,"optin"),u=an(n,"optout");if(!t.rest){if(o.length<a)return i.issues.push({code:"too_small",minimum:a,inclusive:!0,input:o,inst:e,origin:"array"}),i;if(o.length>n.length)i.issues.push({code:"too_big",maximum:n.length,inclusive:!0,input:o,inst:e,origin:"array"})}let c=Array(n.length);for(let d=0;d<n.length;d++){let y=n[d]._zod.run({value:o[d],issues:[]},r);if(y instanceof Promise)s.push(y.then((h)=>{c[d]=h}));else c[d]=y}if(t.rest){let d=n.length-1,y=o.slice(n.length);for(let h of y){d++;let g=t.rest._zod.run({value:h,issues:[]},r);if(g instanceof Promise)s.push(g.then((T)=>ln(T,i,d)));else ln(g,i,d)}}if(s.length)return Promise.all(s).then(()=>un(c,i,n,o,u));return un(c,i,n,o,u)}});function an(e,t){for(let n=e.length-1;n>=0;n--)if(e[n]._zod[t]!=="optional")return n+1;return 0}function ln(e,t,n){if(e.issues.length)t.issues.push(...se(n,e.issues));t.value[n]=e.value}function un(e,t,n,i,r){for(let o=0;o<n.length;o++){let s=e[o],a=o<i.length;if(s.issues.length){if(!a&&o>=r){t.value.length=o;break}t.issues.push(...se(o,s.issues))}t.value[o]=s.value}for(let o=t.value.length-1;o>=i.length;o--)if(n[o]._zod.optout==="optional"&&t.value[o]===void 0)t.value.length=o;else break;return t}var zs=p("$ZodRecord",(e,t)=>{x.init(e,t),e._zod.parse=(n,i)=>{let r=n.value;if(!ke(r))return n.issues.push({expected:"record",code:"invalid_type",input:r,inst:e}),n;let o=[],s=t.keyType._zod.values;if(s){n.value={};let a=new Set;for(let c of s)if(typeof c==="string"||typeof c==="number"||typeof c==="symbol"){a.add(typeof c==="number"?c.toString():c);let d=t.keyType._zod.run({value:c,issues:[]},i);if(d instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(d.issues.length){n.issues.push({code:"invalid_key",origin:"record",issues:d.issues.map((g)=>te(g,i,ee())),input:c,path:[c],inst:e});continue}let y=d.value,h=t.valueType._zod.run({value:r[c],issues:[]},i);if(h instanceof Promise)o.push(h.then((g)=>{if(g.issues.length)n.issues.push(...se(c,g.issues));n.value[y]=g.value}));else{if(h.issues.length)n.issues.push(...se(c,h.issues));n.value[y]=h.value}}let u;for(let c in r)if(!a.has(c))u=u??[],u.push(c);if(u&&u.length>0)n.issues.push({code:"unrecognized_keys",input:r,inst:e,keys:u})}else{n.value={};for(let a of Reflect.ownKeys(r)){if(a==="__proto__")continue;if(!Object.prototype.propertyIsEnumerable.call(r,a))continue;let u=t.keyType._zod.run({value:a,issues:[]},i);if(u instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(typeof a==="string"&&Vn.test(a)&&u.issues.length){let d=t.keyType._zod.run({value:Number(a),issues:[]},i);if(d instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(d.issues.length===0)u=d}if(u.issues.length){if(t.mode==="loose")n.value[a]=r[a];else n.issues.push({code:"invalid_key",origin:"record",issues:u.issues.map((d)=>te(d,i,ee())),input:a,path:[a],inst:e});continue}let c=t.valueType._zod.run({value:r[a],issues:[]},i);if(c instanceof Promise)o.push(c.then((d)=>{if(d.issues.length)n.issues.push(...se(a,d.issues));n.value[u.value]=d.value}));else{if(c.issues.length)n.issues.push(...se(a,c.issues));n.value[u.value]=c.value}}}if(o.length)return Promise.all(o).then(()=>n);return n}}),Ds=p("$ZodEnum",(e,t)=>{x.init(e,t);let n=zn(t.entries),i=new Set(n);e._zod.values=i,e._zod.pattern=new RegExp(`^(${n.filter((r)=>Wr.has(typeof r)).map((r)=>typeof r==="string"?Ee(r):r.toString()).join("|")})$`),e._zod.parse=(r,o)=>{let s=r.value;if(i.has(s))return r;return r.issues.push({code:"invalid_value",values:n,input:s,inst:e}),r}}),Us=p("$ZodLiteral",(e,t)=>{if(x.init(e,t),t.values.length===0)throw Error("Cannot create literal schema with no valid values");let n=new Set(t.values);e._zod.values=n,e._zod.pattern=new RegExp(`^(${t.values.map((i)=>typeof i==="string"?Ee(i):i?Ee(i.toString()):String(i)).join("|")})$`),e._zod.parse=(i,r)=>{let o=i.value;if(n.has(o))return i;return i.issues.push({code:"invalid_value",values:t.values,input:o,inst:e}),i}}),Fs=p("$ZodTransform",(e,t)=>{x.init(e,t),e._zod.optin="optional",e._zod.parse=(n,i)=>{if(i.direction==="backward")throw new Ct(e.constructor.name);let r=t.transform(n.value,n);if(i.async)return(r instanceof Promise?r:Promise.resolve(r)).then((o)=>(n.value=o,n.fallback=!0,n));if(r instanceof Promise)throw new de;return n.value=r,n.fallback=!0,n}});function cn(e,t){if(t===void 0&&(e.issues.length||e.fallback))return{issues:[],value:void 0};return e}var ii=p("$ZodOptional",(e,t)=>{x.init(e,t),e._zod.optin="optional",e._zod.optout="optional",A(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),A(e._zod,"pattern",()=>{let n=t.innerType._zod.pattern;return n?new RegExp(`^(${xt(n.source)})?$`):void 0}),e._zod.parse=(n,i)=>{if(t.innerType._zod.optin==="optional"){let r=n.value,o=t.innerType._zod.run(n,i);if(o instanceof Promise)return o.then((s)=>cn(s,r));return cn(o,r)}if(n.value===void 0)return n;return t.innerType._zod.run(n,i)}}),Bs=p("$ZodExactOptional",(e,t)=>{ii.init(e,t),A(e._zod,"values",()=>t.innerType._zod.values),A(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(n,i)=>t.innerType._zod.run(n,i)}),js=p("$ZodNullable",(e,t)=>{x.init(e,t),A(e._zod,"optin",()=>t.innerType._zod.optin),A(e._zod,"optout",()=>t.innerType._zod.optout),A(e._zod,"pattern",()=>{let n=t.innerType._zod.pattern;return n?new RegExp(`^(${xt(n.source)}|null)$`):void 0}),A(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(n,i)=>{if(n.value===null)return n;return t.innerType._zod.run(n,i)}}),qs=p("$ZodDefault",(e,t)=>{x.init(e,t),e._zod.optin="optional",A(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,i)=>{if(i.direction==="backward")return t.innerType._zod.run(n,i);if(n.value===void 0)return n.value=t.defaultValue,n;let r=t.innerType._zod.run(n,i);if(r instanceof Promise)return r.then((o)=>dn(o,t));return dn(r,t)}});function dn(e,t){if(e.value===void 0)e.value=t.defaultValue;return e}var Hs=p("$ZodPrefault",(e,t)=>{x.init(e,t),e._zod.optin="optional",A(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,i)=>{if(i.direction==="backward")return t.innerType._zod.run(n,i);if(n.value===void 0)n.value=t.defaultValue;return t.innerType._zod.run(n,i)}}),Ws=p("$ZodNonOptional",(e,t)=>{x.init(e,t),A(e._zod,"values",()=>{let n=t.innerType._zod.values;return n?new Set([...n].filter((i)=>i!==void 0)):void 0}),e._zod.parse=(n,i)=>{let r=t.innerType._zod.run(n,i);if(r instanceof Promise)return r.then((o)=>pn(o,e));return pn(r,e)}});function pn(e,t){if(!e.issues.length&&e.value===void 0)e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t});return e}var Vs=p("$ZodCatch",(e,t)=>{x.init(e,t),e._zod.optin="optional",A(e._zod,"optout",()=>t.innerType._zod.optout),A(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,i)=>{if(i.direction==="backward")return t.innerType._zod.run(n,i);let r=t.innerType._zod.run(n,i);if(r instanceof Promise)return r.then((o)=>{if(n.value=o.value,o.issues.length)n.value=t.catchValue({...n,error:{issues:o.issues.map((s)=>te(s,i,ee()))},input:n.value}),n.issues=[],n.fallback=!0;return n});if(n.value=r.value,r.issues.length)n.value=t.catchValue({...n,error:{issues:r.issues.map((o)=>te(o,i,ee()))},input:n.value}),n.issues=[],n.fallback=!0;return n}}),ri=p("$ZodPipe",(e,t)=>{x.init(e,t),A(e._zod,"values",()=>t.in._zod.values),A(e._zod,"optin",()=>t.in._zod.optin),A(e._zod,"optout",()=>t.out._zod.optout),A(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(n,i)=>{if(i.direction==="backward"){let o=t.out._zod.run(n,i);if(o instanceof Promise)return o.then((s)=>Be(s,t.in,i));return Be(o,t.in,i)}let r=t.in._zod.run(n,i);if(r instanceof Promise)return r.then((o)=>Be(o,t.out,i));return Be(r,t.out,i)}});function Be(e,t,n){if(e.issues.length)return e.aborted=!0,e;return t._zod.run({value:e.value,issues:e.issues,fallback:e.fallback},n)}var Zs=p("$ZodPreprocess",(e,t)=>{ri.init(e,t)}),Gs=p("$ZodReadonly",(e,t)=>{x.init(e,t),A(e._zod,"propValues",()=>t.innerType._zod.propValues),A(e._zod,"values",()=>t.innerType._zod.values),A(e._zod,"optin",()=>t.innerType?._zod?.optin),A(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(n,i)=>{if(i.direction==="backward")return t.innerType._zod.run(n,i);let r=t.innerType._zod.run(n,i);if(r instanceof Promise)return r.then(hn);return hn(r)}});function hn(e){return e.value=Object.freeze(e.value),e}var Ks=p("$ZodFunction",(e,t)=>(x.init(e,t),e._def=t,e._zod.def=t,e.implement=(n)=>{if(typeof n!=="function")throw Error("implement() must be called with a function");return function(...i){let r=e._def.input?en(e._def.input,i):i,o=Reflect.apply(n,this,r);if(e._def.output)return en(e._def.output,o);return o}},e.implementAsync=(n)=>{if(typeof n!=="function")throw Error("implementAsync() must be called with a function");return async function(...i){let r=e._def.input?await tn(e._def.input,i):i,o=await Reflect.apply(n,this,r);if(e._def.output)return await tn(e._def.output,o);return o}},e._zod.parse=(n,i)=>{if(typeof n.value!=="function")return n.issues.push({code:"invalid_type",expected:"function",input:n.value,inst:e}),n;if(e._def.output&&e._def.output._zod.def.type==="promise")n.value=e.implementAsync(n.value);else n.value=e.implement(n.value);return n},e.input=(...n)=>{let i=e.constructor;if(Array.isArray(n[0]))return new i({type:"function",input:new ni({type:"tuple",items:n[0],rest:n[1]}),output:e._def.output});return new i({type:"function",input:n[0],output:e._def.output})},e.output=(n)=>new e.constructor({type:"function",input:e._def.input,output:n}),e)),Js=p("$ZodPromise",(e,t)=>{x.init(e,t),e._zod.parse=(n,i)=>Promise.resolve(n.value).then((r)=>t.innerType._zod.run({value:r,issues:[]},i))}),Ys=p("$ZodCustom",(e,t)=>{V.init(e,t),x.init(e,t),e._zod.parse=(n,i)=>n,e._zod.check=(n)=>{let i=n.value,r=t.fn(i);if(r instanceof Promise)return r.then((o)=>fn(o,n,i,e));fn(r,n,i,e);return}});function fn(e,t,n,i){if(!e){let r={code:"custom",input:n,inst:i,path:[...i._zod.def.path??[]],continue:!i._zod.def.abort};if(i._zod.def.params)r.params=i._zod.def.params;t.issues.push($e(r))}}var Xs=()=>{let e={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"},map:{unit:"entries",verb:"to have"}};function t(r){return e[r]??null}let n={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"},i={nan:"NaN"};return(r)=>{switch(r.code){case"invalid_type":{let o=i[r.expected]??r.expected,s=no(r.input),a=i[s]??s;return`Invalid input: expected ${o}, received ${a}`}case"invalid_value":if(r.values.length===1)return`Invalid input: expected ${Fn(r.values[0])}`;return`Invalid option: expected one of ${Yt(r.values,"|")}`;case"too_big":{let o=r.inclusive?"<=":"<",s=t(r.origin);if(s)return`Too big: expected ${r.origin??"value"} to have ${o}${r.maximum.toString()} ${s.unit??"elements"}`;return`Too big: expected ${r.origin??"value"} to be ${o}${r.maximum.toString()}`}case"too_small":{let o=r.inclusive?">=":">",s=t(r.origin);if(s)return`Too small: expected ${r.origin} to have ${o}${r.minimum.toString()} ${s.unit}`;return`Too small: expected ${r.origin} to be ${o}${r.minimum.toString()}`}case"invalid_format":{let o=r;if(o.format==="starts_with")return`Invalid string: must start with "${o.prefix}"`;if(o.format==="ends_with")return`Invalid string: must end with "${o.suffix}"`;if(o.format==="includes")return`Invalid string: must include "${o.includes}"`;if(o.format==="regex")return`Invalid string: must match pattern ${o.pattern}`;return`Invalid ${n[o.format]??r.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${r.divisor}`;case"unrecognized_keys":return`Unrecognized key${r.keys.length>1?"s":""}: ${Yt(r.keys,", ")}`;case"invalid_key":return`Invalid key in ${r.origin}`;case"invalid_union":if(r.options&&Array.isArray(r.options)&&r.options.length>0)return`Invalid discriminator value. Expected ${r.options.map((o)=>`'${o}'`).join(" | ")}`;return"Invalid input";case"invalid_element":return`Invalid value in ${r.origin}`;default:return"Invalid input"}}};function Qs(){return{localeError:Xs()}}var mn,vp=Symbol("ZodOutput"),bp=Symbol("ZodInput");class oi{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){let n=t[0];if(this._map.set(e,n),n&&typeof n==="object"&&"id"in n)this._idmap.set(n.id,e);return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let t=this._map.get(e);if(t&&typeof t==="object"&&"id"in t)this._idmap.delete(t.id);return this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let n={...this.get(t)??{}};delete n.id;let i={...n,...this._map.get(e)};return Object.keys(i).length?i:void 0}return this._map.get(e)}has(e){return this._map.has(e)}}function ea(){return new oi}(mn=globalThis).__zod_globalRegistry??(mn.__zod_globalRegistry=ea());var Se=globalThis.__zod_globalRegistry;function ta(e,t){return new e({type:"string",...b(t)})}function na(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...b(t)})}function gn(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...b(t)})}function ia(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...b(t)})}function ra(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...b(t)})}function oa(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...b(t)})}function sa(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...b(t)})}function aa(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...b(t)})}function la(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...b(t)})}function ua(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...b(t)})}function ca(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...b(t)})}function da(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...b(t)})}function pa(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...b(t)})}function ha(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...b(t)})}function fa(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...b(t)})}function ma(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...b(t)})}function ga(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...b(t)})}function ya(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...b(t)})}function va(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...b(t)})}function ba(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...b(t)})}function Ta(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...b(t)})}function wa(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...b(t)})}function _a(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...b(t)})}function ka(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...b(t)})}function Ea(e,t){return new e({type:"string",format:"date",check:"string_format",...b(t)})}function Ia(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...b(t)})}function Ca(e,t){return new e({type:"string",format:"duration",check:"string_format",...b(t)})}function Aa(e,t){return new e({type:"number",checks:[],...b(t)})}function xa(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...b(t)})}function Ra(e,t){return new e({type:"boolean",...b(t)})}function Sa(e){return new e({type:"unknown"})}function Na(e,t){return new e({type:"never",...b(t)})}function Oa(e,t){return new e({type:"void",...b(t)})}function Ma(e,t){return new e({type:"date",...b(t)})}function yn(e,t){return new Gn({check:"less_than",...b(t),value:e,inclusive:!1})}function He(e,t){return new Gn({check:"less_than",...b(t),value:e,inclusive:!0})}function vn(e,t){return new Kn({check:"greater_than",...b(t),value:e,inclusive:!1})}function We(e,t){return new Kn({check:"greater_than",...b(t),value:e,inclusive:!0})}function bn(e,t){return new jo({check:"multiple_of",...b(t),value:e})}function si(e,t){return new Ho({check:"max_length",...b(t),maximum:e})}function Ge(e,t){return new Wo({check:"min_length",...b(t),minimum:e})}function ai(e,t){return new Vo({check:"length_equals",...b(t),length:e})}function Pa(e,t){return new Zo({check:"string_format",format:"regex",...b(t),pattern:e})}function $a(e){return new Go({check:"string_format",format:"lowercase",...b(e)})}function La(e){return new Ko({check:"string_format",format:"uppercase",...b(e)})}function za(e,t){return new Jo({check:"string_format",format:"includes",...b(t),includes:e})}function Da(e,t){return new Yo({check:"string_format",format:"starts_with",...b(t),prefix:e})}function Ua(e,t){return new Xo({check:"string_format",format:"ends_with",...b(t),suffix:e})}function Ce(e){return new Qo({check:"overwrite",tx:e})}function Fa(e){return Ce((t)=>t.normalize(e))}function Ba(){return Ce((e)=>e.trim())}function ja(){return Ce((e)=>e.toLowerCase())}function qa(){return Ce((e)=>e.toUpperCase())}function Ha(){return Ce((e)=>qr(e))}function Wa(e,t,n){return new e({type:"array",element:t,...b(n)})}function Va(e,t,n){let i=b(n);return i.abort??(i.abort=!0),new e({type:"custom",check:"custom",fn:t,...i})}function Za(e,t,n){return new e({type:"custom",check:"custom",fn:t,...b(n)})}function Ga(e,t){let n=Ka((i)=>(i.addIssue=(r)=>{if(typeof r==="string")i.issues.push($e(r,i.value,n._zod.def));else{let o=r;if(o.fatal)o.continue=!1;o.code??(o.code="custom"),o.input??(o.input=i.value),o.inst??(o.inst=n),o.continue??(o.continue=!n._zod.def.abort),i.issues.push($e(o))}},e(i.value,i)),t);return n}function Ka(e,t){let n=new V({check:"custom",...b(t)});return n._zod.check=e,n}function Ke(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,cycles:e?.cycles??"ref",reused:e?.reused??"inline",external:e?.external??void 0}}function S(e,t,n={path:[],schemaPath:[]}){var i;let r=e._zod.def,o=t.seen.get(e);if(o){if(o.count++,n.schemaPath.includes(e))o.cycle=n.path;return o.schema}let s={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,s);let a=e._zod.toJSONSchema?.();if(a)s.schema=a;else{let c={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,s.schema,c);else{let y=s.schema,h=t.processors[r.type];if(!h)throw Error(`[toJSONSchema]: Non-representable type encountered: ${r.type}`);h(e,t,y,c)}let d=e._zod.parent;if(d){if(!s.ref)s.ref=d;S(d,t,c),t.seen.get(d).isParent=!0}}let u=t.metadataRegistry.get(e);if(u)Object.assign(s.schema,u);if(t.io==="input"&&q(e))delete s.schema.examples,delete s.schema.default;if(t.io==="input"&&"_prefault"in s.schema)(i=s.schema).default??(i.default=s.schema._prefault);return delete s.schema._prefault,t.seen.get(e).schema}function Je(e,t){let n=e.seen.get(t);if(!n)throw Error("Unprocessed schema. This is a bug in Zod.");let i=new Map;for(let s of e.seen.entries()){let a=e.metadataRegistry.get(s[0])?.id;if(a){let u=i.get(a);if(u&&u!==s[0])throw Error(`Duplicate schema id "${a}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);i.set(a,s[0])}}let r=(s)=>{let a=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){let d=e.external.registry.get(s[0])?.id,y=e.external.uri??((g)=>g);if(d)return{ref:y(d)};let h=s[1].defId??s[1].schema.id??`schema${e.counter++}`;return s[1].defId=h,{defId:h,ref:`${y("__shared")}#/${a}/${h}`}}if(s[1]===n)return{ref:"#"};let u=`#/${a}/`,c=s[1].schema.id??`__schema${e.counter++}`;return{defId:c,ref:u+c}},o=(s)=>{if(s[1].schema.$ref)return;let a=s[1],{ref:u,defId:c}=r(s);if(a.def={...a.schema},c)a.defId=c;let d=a.schema;for(let y in d)delete d[y];d.$ref=u};if(e.cycles==="throw")for(let s of e.seen.entries()){let a=s[1];if(a.cycle)throw Error(`Cycle detected: #/${a.cycle?.join("/")}/<root>
63
63
 
64
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let s of e.seen.entries()){let a=s[1];if(t===s[0]){o(s);continue}if(e.external){let u=e.external.registry.get(s[0])?.id;if(t!==s[0]&&u){o(s);continue}}if(e.metadataRegistry.get(s[0])?.id){o(s);continue}if(a.cycle){o(s);continue}if(a.count>1){if(e.reused==="ref"){o(s);continue}}}}function Ye(e,t){let n=e.seen.get(t);if(!n)throw Error("Unprocessed schema. This is a bug in Zod.");let i=(a)=>{let u=e.seen.get(a);if(u.ref===null)return;let c=u.def??u.schema,d={...c},y=u.ref;if(u.ref=null,y){i(y);let f=e.seen.get(y),b=f.schema;if(b.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"))c.allOf=c.allOf??[],c.allOf.push(b);else Object.assign(c,b);if(Object.assign(c,d),a._zod.parent===y)for(let w in c){if(w==="$ref"||w==="allOf")continue;if(!(w in d))delete c[w]}if(b.$ref&&f.def)for(let w in c){if(w==="$ref"||w==="allOf")continue;if(w in f.def&&JSON.stringify(c[w])===JSON.stringify(f.def[w]))delete c[w]}}let g=a._zod.parent;if(g&&g!==y){i(g);let f=e.seen.get(g);if(f?.schema.$ref){if(c.$ref=f.schema.$ref,f.def)for(let b in c){if(b==="$ref"||b==="allOf")continue;if(b in f.def&&JSON.stringify(c[b])===JSON.stringify(f.def[b]))delete c[b]}}}e.override({zodSchema:a,jsonSchema:c,path:u.path??[]})};for(let a of[...e.seen.entries()].reverse())i(a[0]);let r={};if(e.target==="draft-2020-12")r.$schema="https://json-schema.org/draft/2020-12/schema";else if(e.target==="draft-07")r.$schema="http://json-schema.org/draft-07/schema#";else if(e.target==="draft-04")r.$schema="http://json-schema.org/draft-04/schema#";else if(e.target==="openapi-3.0");if(e.external?.uri){let a=e.external.registry.get(t)?.id;if(!a)throw Error("Schema is missing an `id` property");r.$id=e.external.uri(a)}Object.assign(r,n.def??n.schema);let o=e.metadataRegistry.get(t)?.id;if(o!==void 0&&r.id===o)delete r.id;let s=e.external?.defs??{};for(let a of e.seen.entries()){let u=a[1];if(u.def&&u.defId){if(u.def.id===u.defId)delete u.def.id;s[u.defId]=u.def}}if(e.external);else if(Object.keys(s).length>0)if(e.target==="draft-2020-12")r.$defs=s;else r.definitions=s;try{let a=JSON.parse(JSON.stringify(r));return Object.defineProperty(a,"~standard",{value:{...t["~standard"],jsonSchema:{input:Xe(t,"input",e.processors),output:Xe(t,"output",e.processors)}},enumerable:!1,writable:!1}),a}catch(a){throw Error("Error converting schema to JSON.")}}function H(e,t){let n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);let i=e._zod.def;if(i.type==="transform")return!0;if(i.type==="array")return H(i.element,n);if(i.type==="set")return H(i.valueType,n);if(i.type==="lazy")return H(i.getter(),n);if(i.type==="promise"||i.type==="optional"||i.type==="nonoptional"||i.type==="nullable"||i.type==="readonly"||i.type==="default"||i.type==="prefault")return H(i.innerType,n);if(i.type==="intersection")return H(i.left,n)||H(i.right,n);if(i.type==="record"||i.type==="map")return H(i.keyType,n)||H(i.valueType,n);if(i.type==="pipe"){if(e._zod.traits.has("$ZodCodec"))return!0;return H(i.in,n)||H(i.out,n)}if(i.type==="object"){for(let r in i.shape)if(H(i.shape[r],n))return!0;return!1}if(i.type==="union"){for(let r of i.options)if(H(r,n))return!0;return!1}if(i.type==="tuple"){for(let r of i.items)if(H(r,n))return!0;if(i.rest&&H(i.rest,n))return!0;return!1}return!1}var Ja=(e,t={})=>(n)=>{let i=Ke({...n,processors:t});return S(e,i),Je(i,e),Ye(i,e)},Xe=(e,t,n={})=>(i)=>{let{libraryOptions:r,target:o}=i??{},s=Ke({...r??{},target:o,io:t,processors:n});return S(e,s),Je(s,e),Ye(s,e)},Ya={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},li=(e,t,n,i)=>{let r=n;r.type="string";let{minimum:o,maximum:s,format:a,patterns:u,contentEncoding:c}=e._zod.bag;if(typeof o==="number")r.minLength=o;if(typeof s==="number")r.maxLength=s;if(a){if(r.format=Ya[a]??a,r.format==="")delete r.format;if(a==="time")delete r.format}if(c)r.contentEncoding=c;if(u&&u.size>0){let d=[...u];if(d.length===1)r.pattern=d[0].source;else if(d.length>1)r.allOf=[...d.map((y)=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:y.source}))]}},ui=(e,t,n,i)=>{let r=n,{minimum:o,maximum:s,format:a,multipleOf:u,exclusiveMaximum:c,exclusiveMinimum:d}=e._zod.bag;if(typeof a==="string"&&a.includes("int"))r.type="integer";else r.type="number";let y=typeof d==="number"&&d>=(o??Number.NEGATIVE_INFINITY),g=typeof c==="number"&&c<=(s??Number.POSITIVE_INFINITY),f=t.target==="draft-04"||t.target==="openapi-3.0";if(y)if(f)r.minimum=d,r.exclusiveMinimum=!0;else r.exclusiveMinimum=d;else if(typeof o==="number")r.minimum=o;if(g)if(f)r.maximum=c,r.exclusiveMaximum=!0;else r.exclusiveMaximum=c;else if(typeof s==="number")r.maximum=s;if(typeof u==="number")r.multipleOf=u},ci=(e,t,n,i)=>{n.type="boolean"},Xa=(e,t,n,i)=>{if(t.unrepresentable==="throw")throw Error("BigInt cannot be represented in JSON Schema")},Qa=(e,t,n,i)=>{if(t.unrepresentable==="throw")throw Error("Symbols cannot be represented in JSON Schema")},el=(e,t,n,i)=>{if(t.target==="openapi-3.0")n.type="string",n.nullable=!0,n.enum=[null];else n.type="null"},tl=(e,t,n,i)=>{if(t.unrepresentable==="throw")throw Error("Undefined cannot be represented in JSON Schema")},di=(e,t,n,i)=>{if(t.unrepresentable==="throw")throw Error("Void cannot be represented in JSON Schema")},pi=(e,t,n,i)=>{n.not={}},nl=(e,t,n,i)=>{},hi=(e,t,n,i)=>{},fi=(e,t,n,i)=>{if(t.unrepresentable==="throw")throw Error("Date cannot be represented in JSON Schema")},mi=(e,t,n,i)=>{let r=e._zod.def,o=zn(r.entries);if(o.every((s)=>typeof s==="number"))n.type="number";if(o.every((s)=>typeof s==="string"))n.type="string";n.enum=o},gi=(e,t,n,i)=>{let r=e._zod.def,o=[];for(let s of r.values)if(s===void 0){if(t.unrepresentable==="throw")throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof s==="bigint")if(t.unrepresentable==="throw")throw Error("BigInt literals cannot be represented in JSON Schema");else o.push(Number(s));else o.push(s);if(o.length===0);else if(o.length===1){let s=o[0];if(n.type=s===null?"null":typeof s,t.target==="draft-04"||t.target==="openapi-3.0")n.enum=[s];else n.const=s}else{if(o.every((s)=>typeof s==="number"))n.type="number";if(o.every((s)=>typeof s==="string"))n.type="string";if(o.every((s)=>typeof s==="boolean"))n.type="boolean";if(o.every((s)=>s===null))n.type="null";n.enum=o}},il=(e,t,n,i)=>{if(t.unrepresentable==="throw")throw Error("NaN cannot be represented in JSON Schema")},rl=(e,t,n,i)=>{let r=n,o=e._zod.pattern;if(!o)throw Error("Pattern not found in template literal");r.type="string",r.pattern=o.source},ol=(e,t,n,i)=>{let r=n,o={type:"string",format:"binary",contentEncoding:"binary"},{minimum:s,maximum:a,mime:u}=e._zod.bag;if(s!==void 0)o.minLength=s;if(a!==void 0)o.maxLength=a;if(u)if(u.length===1)o.contentMediaType=u[0],Object.assign(r,o);else Object.assign(r,o),r.anyOf=u.map((c)=>({contentMediaType:c}));else Object.assign(r,o)},sl=(e,t,n,i)=>{n.type="boolean"},yi=(e,t,n,i)=>{if(t.unrepresentable==="throw")throw Error("Custom types cannot be represented in JSON Schema")},vi=(e,t,n,i)=>{if(t.unrepresentable==="throw")throw Error("Function types cannot be represented in JSON Schema")},bi=(e,t,n,i)=>{if(t.unrepresentable==="throw")throw Error("Transforms cannot be represented in JSON Schema")},al=(e,t,n,i)=>{if(t.unrepresentable==="throw")throw Error("Map cannot be represented in JSON Schema")},ll=(e,t,n,i)=>{if(t.unrepresentable==="throw")throw Error("Set cannot be represented in JSON Schema")},Ti=(e,t,n,i)=>{let r=n,o=e._zod.def,{minimum:s,maximum:a}=e._zod.bag;if(typeof s==="number")r.minItems=s;if(typeof a==="number")r.maxItems=a;r.type="array",r.items=S(o.element,t,{...i,path:[...i.path,"items"]})},wi=(e,t,n,i)=>{let r=n,o=e._zod.def;r.type="object",r.properties={};let s=o.shape;for(let c in s)r.properties[c]=S(s[c],t,{...i,path:[...i.path,"properties",c]});let a=new Set(Object.keys(s)),u=new Set([...a].filter((c)=>{let d=o.shape[c]._zod;if(t.io==="input")return d.optin===void 0;else return d.optout===void 0}));if(u.size>0)r.required=Array.from(u);if(o.catchall?._zod.def.type==="never")r.additionalProperties=!1;else if(!o.catchall){if(t.io==="output")r.additionalProperties=!1}else if(o.catchall)r.additionalProperties=S(o.catchall,t,{...i,path:[...i.path,"additionalProperties"]})},_i=(e,t,n,i)=>{let r=e._zod.def,o=r.inclusive===!1,s=r.options.map((a,u)=>S(a,t,{...i,path:[...i.path,o?"oneOf":"anyOf",u]}));if(o)n.oneOf=s;else n.anyOf=s},ki=(e,t,n,i)=>{let r=e._zod.def,o=S(r.left,t,{...i,path:[...i.path,"allOf",0]}),s=S(r.right,t,{...i,path:[...i.path,"allOf",1]}),a=(c)=>("allOf"in c)&&Object.keys(c).length===1,u=[...a(o)?o.allOf:[o],...a(s)?s.allOf:[s]];n.allOf=u},Ei=(e,t,n,i)=>{let r=n,o=e._zod.def;r.type="array";let s=t.target==="draft-2020-12"?"prefixItems":"items",a=t.target==="draft-2020-12"?"items":t.target==="openapi-3.0"?"items":"additionalItems",u=o.items.map((g,f)=>S(g,t,{...i,path:[...i.path,s,f]})),c=o.rest?S(o.rest,t,{...i,path:[...i.path,a,...t.target==="openapi-3.0"?[o.items.length]:[]]}):null;if(t.target==="draft-2020-12"){if(r.prefixItems=u,c)r.items=c}else if(t.target==="openapi-3.0"){if(r.items={anyOf:u},c)r.items.anyOf.push(c);if(r.minItems=u.length,!c)r.maxItems=u.length}else if(r.items=u,c)r.additionalItems=c;let{minimum:d,maximum:y}=e._zod.bag;if(typeof d==="number")r.minItems=d;if(typeof y==="number")r.maxItems=y},Ii=(e,t,n,i)=>{let r=n,o=e._zod.def;r.type="object";let s=o.keyType,a=s._zod.bag?.patterns;if(o.mode==="loose"&&a&&a.size>0){let c=S(o.valueType,t,{...i,path:[...i.path,"patternProperties","*"]});r.patternProperties={};for(let d of a)r.patternProperties[d.source]=c}else{if(t.target==="draft-07"||t.target==="draft-2020-12")r.propertyNames=S(o.keyType,t,{...i,path:[...i.path,"propertyNames"]});r.additionalProperties=S(o.valueType,t,{...i,path:[...i.path,"additionalProperties"]})}let u=s._zod.values;if(u){let c=[...u].filter((d)=>typeof d==="string"||typeof d==="number");if(c.length>0)r.required=c}},Ci=(e,t,n,i)=>{let r=e._zod.def,o=S(r.innerType,t,i),s=t.seen.get(e);if(t.target==="openapi-3.0")s.ref=r.innerType,n.nullable=!0;else n.anyOf=[o,{type:"null"}]},Ai=(e,t,n,i)=>{let r=e._zod.def;S(r.innerType,t,i);let o=t.seen.get(e);o.ref=r.innerType},xi=(e,t,n,i)=>{let r=e._zod.def;S(r.innerType,t,i);let o=t.seen.get(e);o.ref=r.innerType,n.default=JSON.parse(JSON.stringify(r.defaultValue))},Ri=(e,t,n,i)=>{let r=e._zod.def;S(r.innerType,t,i);let o=t.seen.get(e);if(o.ref=r.innerType,t.io==="input")n._prefault=JSON.parse(JSON.stringify(r.defaultValue))},Si=(e,t,n,i)=>{let r=e._zod.def;S(r.innerType,t,i);let o=t.seen.get(e);o.ref=r.innerType;let s;try{s=r.catchValue(void 0)}catch{throw Error("Dynamic catch values are not supported in JSON Schema")}n.default=s},Ni=(e,t,n,i)=>{let r=e._zod.def,o=r.in._zod.traits.has("$ZodTransform"),s=t.io==="input"?o?r.out:r.in:r.out;S(s,t,i);let a=t.seen.get(e);a.ref=s},Oi=(e,t,n,i)=>{let r=e._zod.def;S(r.innerType,t,i);let o=t.seen.get(e);o.ref=r.innerType,n.readOnly=!0},Mi=(e,t,n,i)=>{let r=e._zod.def;S(r.innerType,t,i);let o=t.seen.get(e);o.ref=r.innerType},Nt=(e,t,n,i)=>{let r=e._zod.def;S(r.innerType,t,i);let o=t.seen.get(e);o.ref=r.innerType},ul=(e,t,n,i)=>{let r=e._zod.innerType;S(r,t,i);let o=t.seen.get(e);o.ref=r},Tn={string:li,number:ui,boolean:ci,bigint:Xa,symbol:Qa,null:el,undefined:tl,void:di,never:pi,any:nl,unknown:hi,date:fi,enum:mi,literal:gi,nan:il,template_literal:rl,file:ol,success:sl,custom:yi,function:vi,transform:bi,map:al,set:ll,array:Ti,object:wi,union:_i,intersection:ki,tuple:Ei,record:Ii,nullable:Ci,nonoptional:Ai,default:xi,prefault:Ri,catch:Si,pipe:Ni,readonly:Oi,promise:Mi,optional:Nt,lazy:ul};function cl(e,t){if("_idmap"in e){let i=e,r=Ke({...t,processors:Tn}),o={};for(let u of i._idmap.entries()){let[c,d]=u;S(d,r)}let s={},a={registry:i,uri:t?.uri,defs:o};r.external=a;for(let u of i._idmap.entries()){let[c,d]=u;Je(r,d),s[c]=Ye(r,d)}if(Object.keys(o).length>0){let u=r.target==="draft-2020-12"?"$defs":"definitions";s.__shared={[u]:o}}return{schemas:s}}let n=Ke({...t,processors:Tn});return S(e,n),Je(n,e),Ye(n,e)}var dl=p("ZodISODateTime",(e,t)=>{ps.init(e,t),P.init(e,t)});function pl(e){return ka(dl,e)}var hl=p("ZodISODate",(e,t)=>{hs.init(e,t),P.init(e,t)});function fl(e){return Ea(hl,e)}var ml=p("ZodISOTime",(e,t)=>{fs.init(e,t),P.init(e,t)});function gl(e){return Ia(ml,e)}var yl=p("ZodISODuration",(e,t)=>{ms.init(e,t),P.init(e,t)});function vl(e){return Ca(yl,e)}var bl=(e,t)=>{jn.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:(n)=>ro(e,n)},flatten:{value:(n)=>io(e,n)},addIssue:{value:(n)=>{e.issues.push(n),e.message=JSON.stringify(e.issues,Tt,2)}},addIssues:{value:(n)=>{e.issues.push(...n),e.message=JSON.stringify(e.issues,Tt,2)}},isEmpty:{get(){return e.issues.length===0}}})},J=p("ZodError",bl,{Parent:Error}),Tl=nt(J),wl=it(J),_l=rt(J),kl=ot(J),El=ao(J),Il=lo(J),Cl=uo(J),Al=co(J),xl=po(J),Rl=ho(J),Sl=fo(J),Nl=mo(J),wn=new WeakMap;function ze(e,t,n){let i=Object.getPrototypeOf(e),r=wn.get(i);if(!r)r=new Set,wn.set(i,r);if(r.has(t))return;r.add(t);for(let o in n){let s=n[o];Object.defineProperty(i,o,{configurable:!0,enumerable:!1,get(){let a=s.bind(this);return Object.defineProperty(this,o,{configurable:!0,writable:!0,enumerable:!0,value:a}),a},set(a){Object.defineProperty(this,o,{configurable:!0,writable:!0,enumerable:!0,value:a})}})}}var R=p("ZodType",(e,t)=>(x.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:Xe(e,"input"),output:Xe(e,"output")}}),e.toJSONSchema=Ja(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(n,i)=>Tl(e,n,i,{callee:e.parse}),e.safeParse=(n,i)=>_l(e,n,i),e.parseAsync=async(n,i)=>wl(e,n,i,{callee:e.parseAsync}),e.safeParseAsync=async(n,i)=>kl(e,n,i),e.spa=e.safeParseAsync,e.encode=(n,i)=>El(e,n,i),e.decode=(n,i)=>Il(e,n,i),e.encodeAsync=async(n,i)=>Cl(e,n,i),e.decodeAsync=async(n,i)=>Al(e,n,i),e.safeEncode=(n,i)=>xl(e,n,i),e.safeDecode=(n,i)=>Rl(e,n,i),e.safeEncodeAsync=async(n,i)=>Sl(e,n,i),e.safeDecodeAsync=async(n,i)=>Nl(e,n,i),ze(e,"ZodType",{check(...n){let i=this.def;return this.clone(ae(i,{checks:[...i.checks??[],...n.map((r)=>typeof r==="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),{parent:!0})},with(...n){return this.check(...n)},clone(n,i){return le(this,n,i)},brand(){return this},register(n,i){return n.add(this,i),this},refine(n,i){return this.check(xu(n,i))},superRefine(n,i){return this.check(Ru(n,i))},overwrite(n){return this.check(Ae(n))},optional(){return In(this)},exactOptional(){return fu(this)},nullable(){return Cn(this)},nullish(){return In(Cn(this))},nonoptional(n){return Tu(this,n)},array(){return _(this)},or(n){return X([this,n])},and(n){return lu(this,n)},transform(n){return An(this,zi(n))},default(n){return yu(this,n)},prefault(n){return bu(this,n)},catch(n){return _u(this,n)},pipe(n){return An(this,n)},readonly(){return Iu(this)},describe(n){let i=this.clone();return Ne.add(i,{description:n}),i},meta(...n){if(n.length===0)return Ne.get(this);let i=this.clone();return Ne.add(i,n[0]),i},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(n){return n(this)}}),Object.defineProperty(e,"description",{get(){return Ne.get(e)?.description},configurable:!0}),e)),Pi=p("_ZodString",(e,t)=>{St.init(e,t),R.init(e,t),e._zod.processJSONSchema=(i,r,o)=>li(e,i,r,o);let n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,ze(e,"_ZodString",{regex(...i){return this.check(Pa(...i))},includes(...i){return this.check(za(...i))},startsWith(...i){return this.check(Da(...i))},endsWith(...i){return this.check(Ua(...i))},min(...i){return this.check(Ge(...i))},max(...i){return this.check(si(...i))},length(...i){return this.check(ai(...i))},nonempty(...i){return this.check(Ge(1,...i))},lowercase(i){return this.check($a(i))},uppercase(i){return this.check(La(i))},trim(){return this.check(Ba())},normalize(...i){return this.check(Fa(...i))},toLowerCase(){return this.check(ja())},toUpperCase(){return this.check(qa())},slugify(){return this.check(Ha())}})}),Ol=p("ZodString",(e,t)=>{St.init(e,t),Pi.init(e,t),e.email=(n)=>e.check(na(Ml,n)),e.url=(n)=>e.check(aa(Pl,n)),e.jwt=(n)=>e.check(_a(Kl,n)),e.emoji=(n)=>e.check(la($l,n)),e.guid=(n)=>e.check(gn(_n,n)),e.uuid=(n)=>e.check(ia(je,n)),e.uuidv4=(n)=>e.check(ra(je,n)),e.uuidv6=(n)=>e.check(oa(je,n)),e.uuidv7=(n)=>e.check(sa(je,n)),e.nanoid=(n)=>e.check(ua(Ll,n)),e.guid=(n)=>e.check(gn(_n,n)),e.cuid=(n)=>e.check(ca(zl,n)),e.cuid2=(n)=>e.check(da(Dl,n)),e.ulid=(n)=>e.check(pa(Ul,n)),e.base64=(n)=>e.check(ba(Vl,n)),e.base64url=(n)=>e.check(Ta(Zl,n)),e.xid=(n)=>e.check(ha(Fl,n)),e.ksuid=(n)=>e.check(fa(Bl,n)),e.ipv4=(n)=>e.check(ma(jl,n)),e.ipv6=(n)=>e.check(ga(ql,n)),e.cidrv4=(n)=>e.check(ya(Hl,n)),e.cidrv6=(n)=>e.check(va(Wl,n)),e.e164=(n)=>e.check(wa(Gl,n)),e.datetime=(n)=>e.check(pl(n)),e.date=(n)=>e.check(fl(n)),e.time=(n)=>e.check(gl(n)),e.duration=(n)=>e.check(vl(n))});function l(e){return ta(Ol,e)}var P=p("ZodStringFormat",(e,t)=>{M.init(e,t),Pi.init(e,t)}),Ml=p("ZodEmail",(e,t)=>{is.init(e,t),P.init(e,t)}),_n=p("ZodGUID",(e,t)=>{ts.init(e,t),P.init(e,t)}),je=p("ZodUUID",(e,t)=>{ns.init(e,t),P.init(e,t)}),Pl=p("ZodURL",(e,t)=>{rs.init(e,t),P.init(e,t)}),$l=p("ZodEmoji",(e,t)=>{os.init(e,t),P.init(e,t)}),Ll=p("ZodNanoID",(e,t)=>{ss.init(e,t),P.init(e,t)}),zl=p("ZodCUID",(e,t)=>{as.init(e,t),P.init(e,t)}),Dl=p("ZodCUID2",(e,t)=>{ls.init(e,t),P.init(e,t)}),Ul=p("ZodULID",(e,t)=>{us.init(e,t),P.init(e,t)}),Fl=p("ZodXID",(e,t)=>{cs.init(e,t),P.init(e,t)}),Bl=p("ZodKSUID",(e,t)=>{ds.init(e,t),P.init(e,t)}),jl=p("ZodIPv4",(e,t)=>{gs.init(e,t),P.init(e,t)}),ql=p("ZodIPv6",(e,t)=>{ys.init(e,t),P.init(e,t)}),Hl=p("ZodCIDRv4",(e,t)=>{vs.init(e,t),P.init(e,t)}),Wl=p("ZodCIDRv6",(e,t)=>{bs.init(e,t),P.init(e,t)}),Vl=p("ZodBase64",(e,t)=>{Ts.init(e,t),P.init(e,t)}),Zl=p("ZodBase64URL",(e,t)=>{_s.init(e,t),P.init(e,t)}),Gl=p("ZodE164",(e,t)=>{ks.init(e,t),P.init(e,t)}),Kl=p("ZodJWT",(e,t)=>{Is.init(e,t),P.init(e,t)}),$i=p("ZodNumber",(e,t)=>{Xn.init(e,t),R.init(e,t),e._zod.processJSONSchema=(i,r,o)=>ui(e,i,r,o),ze(e,"ZodNumber",{gt(i,r){return this.check(vn(i,r))},gte(i,r){return this.check(We(i,r))},min(i,r){return this.check(We(i,r))},lt(i,r){return this.check(yn(i,r))},lte(i,r){return this.check(He(i,r))},max(i,r){return this.check(He(i,r))},int(i){return this.check(kn(i))},safe(i){return this.check(kn(i))},positive(i){return this.check(vn(0,i))},nonnegative(i){return this.check(We(0,i))},negative(i){return this.check(yn(0,i))},nonpositive(i){return this.check(He(0,i))},multipleOf(i,r){return this.check(bn(i,r))},step(i,r){return this.check(bn(i,r))},finite(){return this}});let n=e._zod.bag;e.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??0.5),e.isFinite=!0,e.format=n.format??null});function m(e){return Aa($i,e)}var Jl=p("ZodNumberFormat",(e,t)=>{Cs.init(e,t),$i.init(e,t)});function kn(e){return xa(Jl,e)}var Yl=p("ZodBoolean",(e,t)=>{As.init(e,t),R.init(e,t),e._zod.processJSONSchema=(n,i,r)=>ci(e,n,i,r)});function E(e){return Ra(Yl,e)}var Xl=p("ZodUnknown",(e,t)=>{xs.init(e,t),R.init(e,t),e._zod.processJSONSchema=(n,i,r)=>hi(e,n,i,r)});function D(){return Sa(Xl)}var Ql=p("ZodNever",(e,t)=>{Rs.init(e,t),R.init(e,t),e._zod.processJSONSchema=(n,i,r)=>pi(e,n,i,r)});function eu(e){return Na(Ql,e)}var tu=p("ZodVoid",(e,t)=>{Ss.init(e,t),R.init(e,t),e._zod.processJSONSchema=(n,i,r)=>di(e,n,i,r)});function nu(e){return Oa(tu,e)}var iu=p("ZodDate",(e,t)=>{Ns.init(e,t),R.init(e,t),e._zod.processJSONSchema=(i,r,o)=>fi(e,i,r,o),e.min=(i,r)=>e.check(We(i,r)),e.max=(i,r)=>e.check(He(i,r));let n=e._zod.bag;e.minDate=n.minimum?new Date(n.minimum):null,e.maxDate=n.maximum?new Date(n.maximum):null});function Qe(e){return Ma(iu,e)}var ru=p("ZodArray",(e,t)=>{Os.init(e,t),R.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Ti(e,n,i,r),e.element=t.element,ze(e,"ZodArray",{min(n,i){return this.check(Ge(n,i))},nonempty(n){return this.check(Ge(1,n))},max(n,i){return this.check(si(n,i))},length(n,i){return this.check(ai(n,i))},unwrap(){return this.element}})});function _(e,t){return Wa(ru,e,t)}var ou=p("ZodObject",(e,t)=>{Ps.init(e,t),R.init(e,t),e._zod.processJSONSchema=(n,i,r)=>wi(e,n,i,r),A(e,"shape",()=>t.shape),ze(e,"ZodObject",{keyof(){return k(Object.keys(this._zod.def.shape))},catchall(n){return this.clone({...this._zod.def,catchall:n})},passthrough(){return this.clone({...this._zod.def,catchall:D()})},loose(){return this.clone({...this._zod.def,catchall:D()})},strict(){return this.clone({...this._zod.def,catchall:eu()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(n){return Jr(this,n)},safeExtend(n){return Yr(this,n)},merge(n){return Xr(this,n)},pick(n){return Gr(this,n)},omit(n){return Kr(this,n)},partial(...n){return Qr(Di,this,n[0])},required(...n){return eo(Ui,this,n[0])}})});function h(e,t){let n={type:"object",shape:e??{},...T(t)};return new ou(n)}var Li=p("ZodUnion",(e,t)=>{ti.init(e,t),R.init(e,t),e._zod.processJSONSchema=(n,i,r)=>_i(e,n,i,r),e.options=t.options});function X(e,t){return new Li({type:"union",options:e,...T(t)})}var su=p("ZodDiscriminatedUnion",(e,t)=>{Li.init(e,t),$s.init(e,t)});function Ot(e,t,n){return new su({type:"union",options:t,discriminator:e,...T(n)})}var au=p("ZodIntersection",(e,t)=>{Ls.init(e,t),R.init(e,t),e._zod.processJSONSchema=(n,i,r)=>ki(e,n,i,r)});function lu(e,t){return new au({type:"intersection",left:e,right:t})}var uu=p("ZodTuple",(e,t)=>{ni.init(e,t),R.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Ei(e,n,i,r),e.rest=(n)=>e.clone({...e._zod.def,rest:n})});function cu(e,t,n){let i=t instanceof x;return new uu({type:"tuple",items:e,rest:i?t:null,...T(i?n:t)})}var En=p("ZodRecord",(e,t)=>{zs.init(e,t),R.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Ii(e,n,i,r),e.keyType=t.keyType,e.valueType=t.valueType});function z(e,t,n){if(!t||!t._zod)return new En({type:"record",keyType:l(),valueType:e,...T(t)});return new En({type:"record",keyType:e,valueType:t,...T(n)})}var _t=p("ZodEnum",(e,t)=>{Ds.init(e,t),R.init(e,t),e._zod.processJSONSchema=(i,r,o)=>mi(e,i,r,o),e.enum=t.entries,e.options=Object.values(t.entries);let n=new Set(Object.keys(t.entries));e.extract=(i,r)=>{let o={};for(let s of i)if(n.has(s))o[s]=t.entries[s];else throw Error(`Key ${s} not found in enum`);return new _t({...t,checks:[],...T(r),entries:o})},e.exclude=(i,r)=>{let o={...t.entries};for(let s of i)if(n.has(s))delete o[s];else throw Error(`Key ${s} not found in enum`);return new _t({...t,checks:[],...T(r),entries:o})}});function k(e,t){let n=Array.isArray(e)?Object.fromEntries(e.map((i)=>[i,i])):e;return new _t({type:"enum",entries:n,...T(t)})}var du=p("ZodLiteral",(e,t)=>{Us.init(e,t),R.init(e,t),e._zod.processJSONSchema=(n,i,r)=>gi(e,n,i,r),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function L(e,t){return new du({type:"literal",values:Array.isArray(e)?e:[e],...T(t)})}var pu=p("ZodTransform",(e,t)=>{Fs.init(e,t),R.init(e,t),e._zod.processJSONSchema=(n,i,r)=>bi(e,n,i,r),e._zod.parse=(n,i)=>{if(i.direction==="backward")throw new Ct(e.constructor.name);n.addIssue=(o)=>{if(typeof o==="string")n.issues.push(Le(o,n.value,t));else{let s=o;if(s.fatal)s.continue=!1;s.code??(s.code="custom"),s.input??(s.input=n.value),s.inst??(s.inst=e),n.issues.push(Le(s))}};let r=t.transform(n.value,n);if(r instanceof Promise)return r.then((o)=>(n.value=o,n.fallback=!0,n));return n.value=r,n.fallback=!0,n}});function zi(e){return new pu({type:"transform",transform:e})}var Di=p("ZodOptional",(e,t)=>{ii.init(e,t),R.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Nt(e,n,i,r),e.unwrap=()=>e._zod.def.innerType});function In(e){return new Di({type:"optional",innerType:e})}var hu=p("ZodExactOptional",(e,t)=>{Bs.init(e,t),R.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Nt(e,n,i,r),e.unwrap=()=>e._zod.def.innerType});function fu(e){return new hu({type:"optional",innerType:e})}var mu=p("ZodNullable",(e,t)=>{js.init(e,t),R.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Ci(e,n,i,r),e.unwrap=()=>e._zod.def.innerType});function Cn(e){return new mu({type:"nullable",innerType:e})}var gu=p("ZodDefault",(e,t)=>{qs.init(e,t),R.init(e,t),e._zod.processJSONSchema=(n,i,r)=>xi(e,n,i,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function yu(e,t){return new gu({type:"default",innerType:e,get defaultValue(){return typeof t==="function"?t():Un(t)}})}var vu=p("ZodPrefault",(e,t)=>{Hs.init(e,t),R.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Ri(e,n,i,r),e.unwrap=()=>e._zod.def.innerType});function bu(e,t){return new vu({type:"prefault",innerType:e,get defaultValue(){return typeof t==="function"?t():Un(t)}})}var Ui=p("ZodNonOptional",(e,t)=>{Ws.init(e,t),R.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Ai(e,n,i,r),e.unwrap=()=>e._zod.def.innerType});function Tu(e,t){return new Ui({type:"nonoptional",innerType:e,...T(t)})}var wu=p("ZodCatch",(e,t)=>{Vs.init(e,t),R.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Si(e,n,i,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function _u(e,t){return new wu({type:"catch",innerType:e,catchValue:typeof t==="function"?t:()=>t})}var Fi=p("ZodPipe",(e,t)=>{ri.init(e,t),R.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Ni(e,n,i,r),e.in=t.in,e.out=t.out});function An(e,t){return new Fi({type:"pipe",in:e,out:t})}var ku=p("ZodPreprocess",(e,t)=>{Fi.init(e,t),Zs.init(e,t)}),Eu=p("ZodReadonly",(e,t)=>{Gs.init(e,t),R.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Oi(e,n,i,r),e.unwrap=()=>e._zod.def.innerType});function Iu(e){return new Eu({type:"readonly",innerType:e})}var Cu=p("ZodPromise",(e,t)=>{Js.init(e,t),R.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Mi(e,n,i,r),e.unwrap=()=>e._zod.def.innerType});function gt(e){return new Cu({type:"promise",innerType:e})}var Au=p("ZodFunction",(e,t)=>{Ks.init(e,t),R.init(e,t),e._zod.processJSONSchema=(n,i,r)=>vi(e,n,i,r)});function qe(e){return new Au({type:"function",input:Array.isArray(e?.input)?cu(e?.input):e?.input??_(D()),output:e?.output??D()})}var Bi=p("ZodCustom",(e,t)=>{Ys.init(e,t),R.init(e,t),e._zod.processJSONSchema=(n,i,r)=>yi(e,n,i,r)});function K(e,t){return Va(Bi,e??(()=>!0),t)}function xu(e,t={}){return Za(Bi,e,t)}function Ru(e,t){return Ga(e,t)}function ji(e,t){return new ku({type:"pipe",in:zi(e),out:t})}ee(Qs());var qi=["none","minimal","low","medium","high","xhigh","max"],Su=k(qi),Nu=Su.exclude(["none"]),Ou=k([...qi,"default"]).nullable(),Mu=Ot("type",[h({type:L("toggle")}).strict(),h({type:L("effort"),values:_(Ou)}).strict(),h({type:L("budget_tokens"),min:m().min(-1).optional(),max:m().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"]})]),Pu=k(["default","openai-responses","r1"]);var $u=k(["images","video","tools","streaming","prompt-cache","reasoning","reasoning-effort","computer-use","global-endpoint","structured_output","temperature","files"]),Lu=k(["active","preview","deprecated","legacy"]),zu=h({input:m().optional(),output:m().optional(),cacheWrite:m().optional(),cacheRead:m().optional()}),Du=h({maxBudget:m().optional(),outputPrice:m().optional(),thinkingLevel:k(["low","high"]).optional()}),Uu=h({reasoningDefaultOn:E().optional(),apiProtocol:k(["openai-chat","openai-responses","anthropic","gemini"]).optional()}).catchall(D()),xn=k(["text","image","audio","video","pdf"]),Fu=h({input:_(xn),output:_(xn)});var Bu=k(["language","image-generation","speech-generation","video-generation","transcription","realtime"]);var ju=k(["batch","streaming"]);var Hi=h({id:l(),name:l().optional(),description:l().optional(),maxTokens:m().optional(),contextWindow:m().optional(),maxInputTokens:m().optional(),capabilities:_($u).optional(),operation:Bu.optional(),operationModes:_(ju).optional(),modalities:Fu.optional(),reasoningOptions:_(Mu).optional(),apiFormat:Pu.optional(),systemRole:k(["system","developer"]).optional(),temperature:m().optional(),pricing:zu.optional(),thinkingConfig:Du.optional(),status:Lu.optional(),deprecationNotice:l().optional(),replacedBy:l().optional(),releaseDate:l().optional(),deprecationDate:l().optional(),family:l().optional(),metadata:Uu.optional()});var Wi="NOT a tool or system failure. Clarify with user before proceeding.",qu=h({id:l(),name:l(),execution:k(["client","provider"]).optional(),input:D(),output:D(),error:l().optional(),durationMs:m(),startedAt:Qe(),endedAt:Qe()}),Hu=k(["completed","max_iterations","aborted","mistake_limit","error"]),Wu=h({inputTokens:m(),outputTokens:m(),cacheReadTokens:m().optional(),cacheWriteTokens:m().optional(),totalCost:m().optional()}),Tp=h({text:l(),usage:Wu,messages:_(K()),toolCalls:_(qu),iterations:m(),finishReason:Hu,model:h({id:l(),provider:l(),info:Hi.optional()}),startedAt:Qe(),endedAt:Qe(),durationMs:m()}),wp=h({distinctId:l().optional(),sessionId:l().optional(),providerId:l(),modelId:l(),apiKey:l().optional(),baseUrl:l().url().optional(),headers:z(l(),l()).optional(),knownModels:z(l(),Hi).optional(),providerConfig:D().optional(),initialMessages:_(K()).optional(),systemPrompt:l(),tools:_(K()),modelTools:_(K()).optional(),maxIterations:m().positive().optional(),maxParallelToolCalls:m().int().positive().default(8),maxTokensPerTurn:m().positive().optional(),maxToolResultChars:m().int().positive().optional(),temperature:m().nonnegative().optional(),apiTimeoutMs:m().positive().default(180000),userFileContentLoader:qe().input([l()]).output(gt(l())).optional(),toolContextMetadata:z(l(),D()).optional(),execution:h({maxConsecutiveMistakes:m().int().positive().optional(),reminderAfterIterations:m().nonnegative().optional(),reminderText:l().optional(),loopDetection:X([L(!1),h({softThreshold:m().int().positive().optional(),hardThreshold:m().int().positive().optional()})]).optional(),reasoningLoopDetection:X([L(!1),h({minChars:m().int().positive().optional(),window:m().int().positive().optional(),maxPeriod:m().int().positive().optional(),minCycles:m().int().positive().optional(),maxUniqueInWindow:m().int().positive().optional(),minLineChars:m().int().positive().optional(),phraseMaxPeriod:m().int().positive().optional(),phraseMinCycles:m().int().positive().optional(),maxConsecutiveTrips:m().int().positive().optional()})]).optional(),reasoningRepetition:X([L(!1),h({minChars:m().int().positive().optional(),minParagraphChars:m().int().positive().optional(),minStopwords:m().int().nonnegative().optional(),maxRepeatTrip:m().int().positive().optional(),duplicateFractionTrip:m().min(0).max(1).optional(),cooldownTurns:m().int().nonnegative().optional(),maxNudges:m().int().nonnegative().optional(),recoveryTokens:m().int().nonnegative().optional()})]).optional()}).optional(),reasoningEffort:Nu.optional(),thinkingBudgetTokens:m().positive().optional(),thinking:E().optional(),onEvent:qe().input([K()]).output(nu()).optional(),hooks:K().optional(),parentAgentId:l().optional(),extensions:_(K()).optional(),hookErrorMode:k(["ignore","throw"]).default("ignore"),toolPolicies:z(l(),h({enabled:E().optional(),autoApprove:E().optional()})).optional(),unavailableToolReasons:z(l(),l()).optional(),requestToolApproval:qe().input([h({sessionId:l(),agentId:l(),conversationId:l(),iteration:m(),toolCallId:l(),toolName:l(),input:D(),policy:h({enabled:E().optional(),autoApprove:E().optional()}).default({})})]).output(X([h({approved:E(),reason:l().optional()}),gt(h({approved:E(),reason:l().optional()}))])).optional(),onConsecutiveMistakeLimitReached:qe().input([h({iteration:m().int().positive(),consecutiveMistakes:m().int().positive(),maxConsecutiveMistakes:m().int().positive(),reason:k(["api_error","invalid_tool_call","tool_execution_failed"]),details:l().optional()})]).output(X([h({action:L("continue"),guidance:l().optional()}),h({action:L("stop"),reason:l().optional()}),gt(X([h({action:L("continue"),guidance:l().optional()}),h({action:L("stop"),reason:l().optional()})]))])).optional(),logger:K().optional(),extensionContext:K().optional(),abortSignal:K().optional()}),Vu=k(["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"]),Zu=h({id:l().optional(),label:l().optional(),role:l().optional(),participantKey:l().optional(),participantLabel:l().optional(),platformUserId:l().optional(),metadata:z(l(),D()).optional()}),Gu=h({source:l(),sourceEvent:l(),threadId:l(),channelId:l(),isDM:E(),sessionId:l().optional(),workspaceRoot:l().optional(),metadata:z(l(),D()).optional()}),_p=h({actor:Zu,context:Gu,payload:z(l(),D()).optional()}),kp=h({action:k(["allow","deny"]).default("allow"),message:l().optional(),reason:l().optional(),metadata:z(l(),D()).optional()}),Ep=h({adapter:l(),botUserName:l().optional(),event:Vu,payload:z(l(),D()),ts:l()});var Ku=["hooks","tools","commands","rules","skills","messageBuilders","providers","automationEvents","mcp"],Ip=new Set(Ku);var Oe={CLINE_PASS:"ext-cline-pass",CODE_CLOUD_AGENTS:"code-cloud-agents",CODE_ONBOARDING_GITHUB:"code-onboarding-github",CLINE_COMPOSIO_BETA:"CLINE_COMPOSIO_BETA"},Cp={[Oe.CLINE_PASS]:!1,[Oe.CODE_CLOUD_AGENTS]:!1,[Oe.CODE_ONBOARDING_GITHUB]:!1,[Oe.CLINE_COMPOSIO_BETA]:!1},Ap=Object.values(Oe),Ju=k(["agent_start","agent_resume","agent_abort","agent_end","agent_error","tool_call","tool_result","prompt_submit","pre_compact","session_shutdown"]),pe=z(l(),l()),Yu=h({toolName:l(),parameters:pe}),Xu=h({toolName:l(),parameters:pe,result:l(),success:E(),executionTimeMs:m()}),Qu=h({prompt:l(),attachments:_(l())}),ec=h({taskMetadata:pe}),tc=h({taskMetadata:pe,previousState:pe}),nc=h({taskMetadata:pe}),ic=h({taskMetadata:pe}),rc=h({taskId:l(),ulid:l(),contextSize:m(),compactionStrategy:l(),previousApiReqIndex:m(),tokensIn:m(),tokensOut:m(),tokensInCache:m(),tokensOutCache:m(),deletedRangeStart:m(),deletedRangeEnd:m(),contextJsonPath:l(),contextRawPath:l()}),xp=h({clineVersion:l(),hookName:Ju,timestamp:l(),taskId:l(),sessionContext:h({rootSessionId:l().optional(),hookLogPath:l().optional()}).optional(),workspaceRoots:_(l()),workspaceInfo:K().optional(),userId:l(),agent_id:l(),parent_agent_id:l().nullable(),iteration:m().optional(),reason:l().optional(),tool_call:h({id:l(),name:l(),input:D()}).optional(),tool_result:K().optional(),turn:D().optional(),error:h({name:l(),message:l(),stack:l().optional()}).optional(),preToolUse:Yu.optional(),postToolUse:Xu.optional(),userPromptSubmit:Qu.optional(),taskStart:ec.optional(),taskResume:tc.optional(),taskCancel:nc.optional(),taskComplete:ic.optional(),preCompact:rc.optional()}).passthrough();var oc=["readFile","search","bash","webFetch","editor","applyPatch","skills","askQuestion","submit"],Rp=new Set(oc);var Rn="<tool_call>",sc=/<tool_call>|<parameter=[^>]*>|<\/parameter>/g,ac=/<function=[^\s>]+\s*>/,Mt="[SYSTEM] Your last message contained no tool calls, so the run was about to end. If the task is not finished, continue now by emitting the tool calls it needs - do not describe what you are going to do without doing it. If the task really is finished, say so in one short sentence. If it stopped at a limit, a refusal or anything else only the user can change, and you have told the user so, that is finished too: say so in one short sentence and do not look for a way around it.",Vi=" If what you need is a decision from the user, call `ask_question` - that is the only way to reach them. A question written as ordinary text is not a question anyone will see: it reads here as a turn that called nothing, which is what produced this message.",lc="[SYSTEM] You have now taken ";function Zi(e,t){let n=Math.round(t/1000),i=n>=1?`about ${n.toLocaleString("en-US")},000 characters of reasoning`:"a full turn of reasoning";return lc+`${e} turns in a row without calling a single tool, spending ${i} on them. Thinking further has not moved this task, and it will not: you have already reasoned past the point where more of it helps. Stop analysing and make one tool call now - the smallest one that makes any progress at all, even if you are not certain it is the right one, because a call you can check beats an analysis you cannot. If you genuinely cannot make one, say what is blocking you in a single sentence and stop.`}var uc="[SYSTEM] Your last message contained a tool call that could not be read.",cc="<|tool_call>",Sn="<tool_call|>",be='<|"|>',dc=/<\|tool_call>\s*call:([A-Za-z_][\w.-]*)\s*\{/g;function Gi(e){return`(A call to ${e.name?`\`${e.name}\``:"a tool"} was written here but could not be read, so nothing ran. Its text is not kept.)`}function yt(e){return JSON.stringify(e.replace(/\s+/g," ").trim())}function pc(e){let t=[];for(let r=e.indexOf(be);r!==-1;r=e.indexOf(be,r+be.length))t.push(r);let n=(r)=>/([A-Za-z_]\w*)\s*:\s*$/.exec(e.slice(Math.max(0,r-80),r))?.[1],i=()=>{let r=/([A-Za-z_]\w*)\s*:\s*(?!<\|"\|>)([^,{}[\]<]{1,60})<\|"\|>/.exec(e);return r?`The value of \`${r[1]}\` (${yt(r[2])}) closes a string it never opened.`:void 0};for(let r=0;r+1<t.length;r+=2){let o=t[r],s=t[r+1],a=n(o),u=e.slice(o+be.length,s),c=/([^\s,]{0,12})\s*,\s*([A-Za-z_]\w*)\s*:\s*$/.exec(u);if(c&&a){let g=c[1],f=g?`you wrote ${yt(g.slice(-8))} where its closing delimiter belongs`:"its closing delimiter is missing";return`The string for \`${a}\` was never closed: ${f}, just before \`${c[2]}\`. A string argument ends with the same delimiter that opened it and with nothing else - not a backtick, not a quote, not a tag.`}let d=e.slice(s+be.length),y=/^\s*(\S)/.exec(d)?.[1];if(y&&!",}]".includes(y)){let g=/^\s*([A-Za-z_]\w*)\s*:/.exec(d)?.[1];if(!g){let f=i();if(f)return f}return g&&a?`There is no comma between \`${a}\` and \`${g}\`. Every argument is separated from the next by a comma.`:`After the string for \`${a??"an argument"}\` closes, the call continues with ${yt(d.slice(0,24))} where a comma or the end of the call belongs.`}}if(t.length%2===1)return`The string for \`${n(t[t.length-1])??"the last argument"}\` was opened and never closed.`;return i()}function hc(e){let t=[...e.matchAll(dc)];if(t.length===0)return;let n=t[t.length-1]?.[1],i=0;for(let u=1;u<t.length;u+=1){let c=e.slice(t[u-1].index??0,t[u].index??0);if((c.split(be).length-1)%2===1||!c.includes(Sn))i+=1}let r=t[t.length-1],o=(r.index??0)+r[0].length,s=e.indexOf(Sn,o),a=i>0?void 0:pc(e.slice(o,s===-1?void 0:s));return{blocks:t.length,restarts:i,dialect:"gemma",...n?{name:n}:{},...a?{defect:a}:{}}}function xe(e){if(!e)return;if(e.includes(cc)){let u=hc(e);if(u)return u}if(!e.includes(Rn)||!ac.test(e))return;let t=0,n=0,i=0;for(let u of e.matchAll(sc)){let c=u[0];if(c===Rn)t+=1;else if(c==="</parameter>")i+=1;else n+=1}if(t===0)return;let r=Math.max(n-i,0),o=Math.min(Math.max(t-1,0),r),s=[...e.matchAll(/<function=([^\s>]+)\s*>/g)],a=s[s.length-1]?.[1];return{blocks:t,restarts:o,dialect:"qwen",...a?{name:a}:{}}}function Pt(e){let t=e.name?`\`${e.name}\``:"a tool",n=e.dialect==="gemma",i=n?"string argument":"parameter",r=e.restarts>0?` You began ${t} and then, part-way through a ${i} you never closed, started the whole call again${e.restarts>1?`, ${e.restarts} times over`:""}. The reader cannot tell an abandoned call from the value of the ${i} it was abandoned inside, so all of it came back as text.`:e.defect?` It named ${t}. ${e.defect}`:` It named ${t}, but the block was not well formed and could not be read.`,o=n?" Write the call again, once: every string argument opens and closes with the same string delimiter, arguments are separated by commas, and the call is closed after the last one.":" Emit the call once, in one clean block: open it, give each parameter and close each parameter, then close the function and the call.";return uc+r+" Nothing ran, so nothing has changed on disk. The call is not in this conversation any more, so do not look for it or copy it: write it fresh."+o+" Do not restart a call once you have begun it - finish it, or send nothing and start the next turn fresh."}var fc="[SYSTEM] You wrote ";function Ki(e){let t=e.trim().replace(/\s+/g," ").slice(0,200);return fc+`"${t}" and then called nothing, for the second turn running. Saying what you are about to do is not doing it, and the run ends on the next silent turn with the work undone. Emit the tool call itself now - the first one, not a description of it. If you cannot, say plainly what is stopping you in one sentence.`}var Ji=/\b(?:let me|i'?ll|i will|i'?m going to|i am going to|now i(?:'?ll| will)|next,? i(?:'?ll| will)|let'?s)\b/i,Yi=/\b(?:task (?:is )?(?:complete|finished|done)|all done|is now (?:complete|finished|fixed|working)|i(?:'?m| am) (?:done|finished)|nothing (?:else|more) to do|no further changes)\b/i;function at(e){let t=e?.trim();if(!t||Yi.test(t))return;let n=t.slice(-400);return Ji.test(n)?t:void 0}var mc=300;function Xi(e){let t=e?.trim();return!!t&&t.length<=mc&&!/\n\s*\n/.test(t)&&!t.endsWith("?")&&at(t)===void 0}var gc=/(?:^done\b|^i(?:'ve| have) (?:now |fully |successfully )?(?:completed|finished)\b|\b(?:is|are|was|were|has been|have been) (?:now |all |fully |successfully )?(?:complete|completed|finished|done)\b)/i;function Qi(e){return e.slice(-300).includes("?")||Ji.test(e.slice(-400))}function er(e){let t=e?.trim();if(!t)return!1;let n=t.replace(/[*_`]/g,"");return(Yi.test(n)||gc.test(n))&&!Qi(t)}function tr(e){let t=e?.trim();return!!t&&!Qi(t)}var yc=k(["image","audio","video","file"]),vc=Ot("type",[h({type:L("base64"),data:l().min(1)}),h({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")}),h({type:L("artifact"),artifactId:l().min(1)})]);function bc(e){if(e.startsWith("image/"))return"image";if(e.startsWith("audio/"))return"audio";if(e.startsWith("video/"))return"video";return"file"}var Sp=h({id:l().min(1),modality:yc,mediaType:l().min(1),source:vc,name:l().min(1).optional(),sizeBytes:m().int().nonnegative().optional()}).refine((e)=>bc(e.mediaType)===e.modality,{message:"Generated media modality must match its media type",path:["modality"]});function Nn(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function $t(e,t){if(!e&&!t)return;let n=e?.metadata,i=t?.metadata,r={...e??{},...t??{}};if(Nn(n)&&Nn(i))r.metadata={...n,...i};return r}var On=Symbol.for("cline.shared.tokenCalibration");function Tc(e,t){if(e===void 0||t===void 0)return!0;return e===t}function nr(){let e=globalThis,t=e[On];if(t)return t;let n={};return e[On]=n,n}function wc(){return nr().charsPerToken??3}function Lt(e){let t=nr();return Tc(t.outputCapOwner,e)?t.outputCap:void 0}function ir(e){return Math.max(1,Math.ceil(e/wc()))}function we(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function _c(e){let t=e.type;if(typeof t==="string")return[t];return Array.isArray(t)?t.filter((n)=>typeof n==="string"):[]}function kt(e,t){if(_c(e).includes(t))return!0;for(let n of["anyOf","oneOf","allOf"]){let i=e[n];if(Array.isArray(i)&&i.some((r)=>we(r)&&kt(r,t)))return!0}return!1}function kc(e,t){if(typeof e!=="string")return e;let n=e.trim(),i=kt(t,"array"),r=kt(t,"object");if((!i||!n.startsWith("["))&&(!r||!n.startsWith("{")))return e;try{let o=JSON.parse(n);if(Array.isArray(o))return i?o:e;if(we(o))return r?o:e;return e}catch{return e}}function Ce(e,t){let n=kc(e,t);if(Array.isArray(n)){let s=t.items;if(!we(s))return n;let a=!1,u=n.map((c)=>{let d=Ce(c,s);return a||=d!==c,d});return a?u:n}if(!we(n))return n;let i=t.properties;if(!we(i))return n;let r=!1,o={...n};for(let[s,a]of Object.entries(i)){if(!(s in n)||!we(a))continue;let u=Ce(n[s],a);if(u!==n[s])o[s]=u,r=!0}return r?o:n}function rr(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}function B(e){let t=e?.trim();return t?t:void 0}function Ec(e){return cl(e)}var Np=new RegExp(`${"⁣⟦"}([^${"⟧"}]*)${"⟧"}([\\s\\S]*?)${"⟦/⟧⁣"}`,"g");var or=`# Plan Mode
64
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let s of e.seen.entries()){let a=s[1];if(t===s[0]){o(s);continue}if(e.external){let u=e.external.registry.get(s[0])?.id;if(t!==s[0]&&u){o(s);continue}}if(e.metadataRegistry.get(s[0])?.id){o(s);continue}if(a.cycle){o(s);continue}if(a.count>1){if(e.reused==="ref"){o(s);continue}}}}function Ye(e,t){let n=e.seen.get(t);if(!n)throw Error("Unprocessed schema. This is a bug in Zod.");let i=(a)=>{let u=e.seen.get(a);if(u.ref===null)return;let c=u.def??u.schema,d={...c},y=u.ref;if(u.ref=null,y){i(y);let g=e.seen.get(y),T=g.schema;if(T.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"))c.allOf=c.allOf??[],c.allOf.push(T);else Object.assign(c,T);if(Object.assign(c,d),a._zod.parent===y)for(let k in c){if(k==="$ref"||k==="allOf")continue;if(!(k in d))delete c[k]}if(T.$ref&&g.def)for(let k in c){if(k==="$ref"||k==="allOf")continue;if(k in g.def&&JSON.stringify(c[k])===JSON.stringify(g.def[k]))delete c[k]}}let h=a._zod.parent;if(h&&h!==y){i(h);let g=e.seen.get(h);if(g?.schema.$ref){if(c.$ref=g.schema.$ref,g.def)for(let T in c){if(T==="$ref"||T==="allOf")continue;if(T in g.def&&JSON.stringify(c[T])===JSON.stringify(g.def[T]))delete c[T]}}}e.override({zodSchema:a,jsonSchema:c,path:u.path??[]})};for(let a of[...e.seen.entries()].reverse())i(a[0]);let r={};if(e.target==="draft-2020-12")r.$schema="https://json-schema.org/draft/2020-12/schema";else if(e.target==="draft-07")r.$schema="http://json-schema.org/draft-07/schema#";else if(e.target==="draft-04")r.$schema="http://json-schema.org/draft-04/schema#";else if(e.target==="openapi-3.0");if(e.external?.uri){let a=e.external.registry.get(t)?.id;if(!a)throw Error("Schema is missing an `id` property");r.$id=e.external.uri(a)}Object.assign(r,n.def??n.schema);let o=e.metadataRegistry.get(t)?.id;if(o!==void 0&&r.id===o)delete r.id;let s=e.external?.defs??{};for(let a of e.seen.entries()){let u=a[1];if(u.def&&u.defId){if(u.def.id===u.defId)delete u.def.id;s[u.defId]=u.def}}if(e.external);else if(Object.keys(s).length>0)if(e.target==="draft-2020-12")r.$defs=s;else r.definitions=s;try{let a=JSON.parse(JSON.stringify(r));return Object.defineProperty(a,"~standard",{value:{...t["~standard"],jsonSchema:{input:Xe(t,"input",e.processors),output:Xe(t,"output",e.processors)}},enumerable:!1,writable:!1}),a}catch(a){throw Error("Error converting schema to JSON.")}}function q(e,t){let n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);let i=e._zod.def;if(i.type==="transform")return!0;if(i.type==="array")return q(i.element,n);if(i.type==="set")return q(i.valueType,n);if(i.type==="lazy")return q(i.getter(),n);if(i.type==="promise"||i.type==="optional"||i.type==="nonoptional"||i.type==="nullable"||i.type==="readonly"||i.type==="default"||i.type==="prefault")return q(i.innerType,n);if(i.type==="intersection")return q(i.left,n)||q(i.right,n);if(i.type==="record"||i.type==="map")return q(i.keyType,n)||q(i.valueType,n);if(i.type==="pipe"){if(e._zod.traits.has("$ZodCodec"))return!0;return q(i.in,n)||q(i.out,n)}if(i.type==="object"){for(let r in i.shape)if(q(i.shape[r],n))return!0;return!1}if(i.type==="union"){for(let r of i.options)if(q(r,n))return!0;return!1}if(i.type==="tuple"){for(let r of i.items)if(q(r,n))return!0;if(i.rest&&q(i.rest,n))return!0;return!1}return!1}var Ja=(e,t={})=>(n)=>{let i=Ke({...n,processors:t});return S(e,i),Je(i,e),Ye(i,e)},Xe=(e,t,n={})=>(i)=>{let{libraryOptions:r,target:o}=i??{},s=Ke({...r??{},target:o,io:t,processors:n});return S(e,s),Je(s,e),Ye(s,e)},Ya={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},li=(e,t,n,i)=>{let r=n;r.type="string";let{minimum:o,maximum:s,format:a,patterns:u,contentEncoding:c}=e._zod.bag;if(typeof o==="number")r.minLength=o;if(typeof s==="number")r.maxLength=s;if(a){if(r.format=Ya[a]??a,r.format==="")delete r.format;if(a==="time")delete r.format}if(c)r.contentEncoding=c;if(u&&u.size>0){let d=[...u];if(d.length===1)r.pattern=d[0].source;else if(d.length>1)r.allOf=[...d.map((y)=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:y.source}))]}},ui=(e,t,n,i)=>{let r=n,{minimum:o,maximum:s,format:a,multipleOf:u,exclusiveMaximum:c,exclusiveMinimum:d}=e._zod.bag;if(typeof a==="string"&&a.includes("int"))r.type="integer";else r.type="number";let y=typeof d==="number"&&d>=(o??Number.NEGATIVE_INFINITY),h=typeof c==="number"&&c<=(s??Number.POSITIVE_INFINITY),g=t.target==="draft-04"||t.target==="openapi-3.0";if(y)if(g)r.minimum=d,r.exclusiveMinimum=!0;else r.exclusiveMinimum=d;else if(typeof o==="number")r.minimum=o;if(h)if(g)r.maximum=c,r.exclusiveMaximum=!0;else r.exclusiveMaximum=c;else if(typeof s==="number")r.maximum=s;if(typeof u==="number")r.multipleOf=u},ci=(e,t,n,i)=>{n.type="boolean"},Xa=(e,t,n,i)=>{if(t.unrepresentable==="throw")throw Error("BigInt cannot be represented in JSON Schema")},Qa=(e,t,n,i)=>{if(t.unrepresentable==="throw")throw Error("Symbols cannot be represented in JSON Schema")},el=(e,t,n,i)=>{if(t.target==="openapi-3.0")n.type="string",n.nullable=!0,n.enum=[null];else n.type="null"},tl=(e,t,n,i)=>{if(t.unrepresentable==="throw")throw Error("Undefined cannot be represented in JSON Schema")},di=(e,t,n,i)=>{if(t.unrepresentable==="throw")throw Error("Void cannot be represented in JSON Schema")},pi=(e,t,n,i)=>{n.not={}},nl=(e,t,n,i)=>{},hi=(e,t,n,i)=>{},fi=(e,t,n,i)=>{if(t.unrepresentable==="throw")throw Error("Date cannot be represented in JSON Schema")},mi=(e,t,n,i)=>{let r=e._zod.def,o=zn(r.entries);if(o.every((s)=>typeof s==="number"))n.type="number";if(o.every((s)=>typeof s==="string"))n.type="string";n.enum=o},gi=(e,t,n,i)=>{let r=e._zod.def,o=[];for(let s of r.values)if(s===void 0){if(t.unrepresentable==="throw")throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof s==="bigint")if(t.unrepresentable==="throw")throw Error("BigInt literals cannot be represented in JSON Schema");else o.push(Number(s));else o.push(s);if(o.length===0);else if(o.length===1){let s=o[0];if(n.type=s===null?"null":typeof s,t.target==="draft-04"||t.target==="openapi-3.0")n.enum=[s];else n.const=s}else{if(o.every((s)=>typeof s==="number"))n.type="number";if(o.every((s)=>typeof s==="string"))n.type="string";if(o.every((s)=>typeof s==="boolean"))n.type="boolean";if(o.every((s)=>s===null))n.type="null";n.enum=o}},il=(e,t,n,i)=>{if(t.unrepresentable==="throw")throw Error("NaN cannot be represented in JSON Schema")},rl=(e,t,n,i)=>{let r=n,o=e._zod.pattern;if(!o)throw Error("Pattern not found in template literal");r.type="string",r.pattern=o.source},ol=(e,t,n,i)=>{let r=n,o={type:"string",format:"binary",contentEncoding:"binary"},{minimum:s,maximum:a,mime:u}=e._zod.bag;if(s!==void 0)o.minLength=s;if(a!==void 0)o.maxLength=a;if(u)if(u.length===1)o.contentMediaType=u[0],Object.assign(r,o);else Object.assign(r,o),r.anyOf=u.map((c)=>({contentMediaType:c}));else Object.assign(r,o)},sl=(e,t,n,i)=>{n.type="boolean"},yi=(e,t,n,i)=>{if(t.unrepresentable==="throw")throw Error("Custom types cannot be represented in JSON Schema")},vi=(e,t,n,i)=>{if(t.unrepresentable==="throw")throw Error("Function types cannot be represented in JSON Schema")},bi=(e,t,n,i)=>{if(t.unrepresentable==="throw")throw Error("Transforms cannot be represented in JSON Schema")},al=(e,t,n,i)=>{if(t.unrepresentable==="throw")throw Error("Map cannot be represented in JSON Schema")},ll=(e,t,n,i)=>{if(t.unrepresentable==="throw")throw Error("Set cannot be represented in JSON Schema")},Ti=(e,t,n,i)=>{let r=n,o=e._zod.def,{minimum:s,maximum:a}=e._zod.bag;if(typeof s==="number")r.minItems=s;if(typeof a==="number")r.maxItems=a;r.type="array",r.items=S(o.element,t,{...i,path:[...i.path,"items"]})},wi=(e,t,n,i)=>{let r=n,o=e._zod.def;r.type="object",r.properties={};let s=o.shape;for(let c in s)r.properties[c]=S(s[c],t,{...i,path:[...i.path,"properties",c]});let a=new Set(Object.keys(s)),u=new Set([...a].filter((c)=>{let d=o.shape[c]._zod;if(t.io==="input")return d.optin===void 0;else return d.optout===void 0}));if(u.size>0)r.required=Array.from(u);if(o.catchall?._zod.def.type==="never")r.additionalProperties=!1;else if(!o.catchall){if(t.io==="output")r.additionalProperties=!1}else if(o.catchall)r.additionalProperties=S(o.catchall,t,{...i,path:[...i.path,"additionalProperties"]})},_i=(e,t,n,i)=>{let r=e._zod.def,o=r.inclusive===!1,s=r.options.map((a,u)=>S(a,t,{...i,path:[...i.path,o?"oneOf":"anyOf",u]}));if(o)n.oneOf=s;else n.anyOf=s},ki=(e,t,n,i)=>{let r=e._zod.def,o=S(r.left,t,{...i,path:[...i.path,"allOf",0]}),s=S(r.right,t,{...i,path:[...i.path,"allOf",1]}),a=(c)=>("allOf"in c)&&Object.keys(c).length===1,u=[...a(o)?o.allOf:[o],...a(s)?s.allOf:[s]];n.allOf=u},Ei=(e,t,n,i)=>{let r=n,o=e._zod.def;r.type="array";let s=t.target==="draft-2020-12"?"prefixItems":"items",a=t.target==="draft-2020-12"?"items":t.target==="openapi-3.0"?"items":"additionalItems",u=o.items.map((h,g)=>S(h,t,{...i,path:[...i.path,s,g]})),c=o.rest?S(o.rest,t,{...i,path:[...i.path,a,...t.target==="openapi-3.0"?[o.items.length]:[]]}):null;if(t.target==="draft-2020-12"){if(r.prefixItems=u,c)r.items=c}else if(t.target==="openapi-3.0"){if(r.items={anyOf:u},c)r.items.anyOf.push(c);if(r.minItems=u.length,!c)r.maxItems=u.length}else if(r.items=u,c)r.additionalItems=c;let{minimum:d,maximum:y}=e._zod.bag;if(typeof d==="number")r.minItems=d;if(typeof y==="number")r.maxItems=y},Ii=(e,t,n,i)=>{let r=n,o=e._zod.def;r.type="object";let s=o.keyType,a=s._zod.bag?.patterns;if(o.mode==="loose"&&a&&a.size>0){let c=S(o.valueType,t,{...i,path:[...i.path,"patternProperties","*"]});r.patternProperties={};for(let d of a)r.patternProperties[d.source]=c}else{if(t.target==="draft-07"||t.target==="draft-2020-12")r.propertyNames=S(o.keyType,t,{...i,path:[...i.path,"propertyNames"]});r.additionalProperties=S(o.valueType,t,{...i,path:[...i.path,"additionalProperties"]})}let u=s._zod.values;if(u){let c=[...u].filter((d)=>typeof d==="string"||typeof d==="number");if(c.length>0)r.required=c}},Ci=(e,t,n,i)=>{let r=e._zod.def,o=S(r.innerType,t,i),s=t.seen.get(e);if(t.target==="openapi-3.0")s.ref=r.innerType,n.nullable=!0;else n.anyOf=[o,{type:"null"}]},Ai=(e,t,n,i)=>{let r=e._zod.def;S(r.innerType,t,i);let o=t.seen.get(e);o.ref=r.innerType},xi=(e,t,n,i)=>{let r=e._zod.def;S(r.innerType,t,i);let o=t.seen.get(e);o.ref=r.innerType,n.default=JSON.parse(JSON.stringify(r.defaultValue))},Ri=(e,t,n,i)=>{let r=e._zod.def;S(r.innerType,t,i);let o=t.seen.get(e);if(o.ref=r.innerType,t.io==="input")n._prefault=JSON.parse(JSON.stringify(r.defaultValue))},Si=(e,t,n,i)=>{let r=e._zod.def;S(r.innerType,t,i);let o=t.seen.get(e);o.ref=r.innerType;let s;try{s=r.catchValue(void 0)}catch{throw Error("Dynamic catch values are not supported in JSON Schema")}n.default=s},Ni=(e,t,n,i)=>{let r=e._zod.def,o=r.in._zod.traits.has("$ZodTransform"),s=t.io==="input"?o?r.out:r.in:r.out;S(s,t,i);let a=t.seen.get(e);a.ref=s},Oi=(e,t,n,i)=>{let r=e._zod.def;S(r.innerType,t,i);let o=t.seen.get(e);o.ref=r.innerType,n.readOnly=!0},Mi=(e,t,n,i)=>{let r=e._zod.def;S(r.innerType,t,i);let o=t.seen.get(e);o.ref=r.innerType},Nt=(e,t,n,i)=>{let r=e._zod.def;S(r.innerType,t,i);let o=t.seen.get(e);o.ref=r.innerType},ul=(e,t,n,i)=>{let r=e._zod.innerType;S(r,t,i);let o=t.seen.get(e);o.ref=r},Tn={string:li,number:ui,boolean:ci,bigint:Xa,symbol:Qa,null:el,undefined:tl,void:di,never:pi,any:nl,unknown:hi,date:fi,enum:mi,literal:gi,nan:il,template_literal:rl,file:ol,success:sl,custom:yi,function:vi,transform:bi,map:al,set:ll,array:Ti,object:wi,union:_i,intersection:ki,tuple:Ei,record:Ii,nullable:Ci,nonoptional:Ai,default:xi,prefault:Ri,catch:Si,pipe:Ni,readonly:Oi,promise:Mi,optional:Nt,lazy:ul};function cl(e,t){if("_idmap"in e){let i=e,r=Ke({...t,processors:Tn}),o={};for(let u of i._idmap.entries()){let[c,d]=u;S(d,r)}let s={},a={registry:i,uri:t?.uri,defs:o};r.external=a;for(let u of i._idmap.entries()){let[c,d]=u;Je(r,d),s[c]=Ye(r,d)}if(Object.keys(o).length>0){let u=r.target==="draft-2020-12"?"$defs":"definitions";s.__shared={[u]:o}}return{schemas:s}}let n=Ke({...t,processors:Tn});return S(e,n),Je(n,e),Ye(n,e)}var dl=p("ZodISODateTime",(e,t)=>{ps.init(e,t),P.init(e,t)});function pl(e){return ka(dl,e)}var hl=p("ZodISODate",(e,t)=>{hs.init(e,t),P.init(e,t)});function fl(e){return Ea(hl,e)}var ml=p("ZodISOTime",(e,t)=>{fs.init(e,t),P.init(e,t)});function gl(e){return Ia(ml,e)}var yl=p("ZodISODuration",(e,t)=>{ms.init(e,t),P.init(e,t)});function vl(e){return Ca(yl,e)}var bl=(e,t)=>{jn.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:(n)=>ro(e,n)},flatten:{value:(n)=>io(e,n)},addIssue:{value:(n)=>{e.issues.push(n),e.message=JSON.stringify(e.issues,Tt,2)}},addIssues:{value:(n)=>{e.issues.push(...n),e.message=JSON.stringify(e.issues,Tt,2)}},isEmpty:{get(){return e.issues.length===0}}})},J=p("ZodError",bl,{Parent:Error}),Tl=nt(J),wl=it(J),_l=rt(J),kl=ot(J),El=ao(J),Il=lo(J),Cl=uo(J),Al=co(J),xl=po(J),Rl=ho(J),Sl=fo(J),Nl=mo(J),wn=new WeakMap;function Le(e,t,n){let i=Object.getPrototypeOf(e),r=wn.get(i);if(!r)r=new Set,wn.set(i,r);if(r.has(t))return;r.add(t);for(let o in n){let s=n[o];Object.defineProperty(i,o,{configurable:!0,enumerable:!1,get(){let a=s.bind(this);return Object.defineProperty(this,o,{configurable:!0,writable:!0,enumerable:!0,value:a}),a},set(a){Object.defineProperty(this,o,{configurable:!0,writable:!0,enumerable:!0,value:a})}})}}var R=p("ZodType",(e,t)=>(x.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:Xe(e,"input"),output:Xe(e,"output")}}),e.toJSONSchema=Ja(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(n,i)=>Tl(e,n,i,{callee:e.parse}),e.safeParse=(n,i)=>_l(e,n,i),e.parseAsync=async(n,i)=>wl(e,n,i,{callee:e.parseAsync}),e.safeParseAsync=async(n,i)=>kl(e,n,i),e.spa=e.safeParseAsync,e.encode=(n,i)=>El(e,n,i),e.decode=(n,i)=>Il(e,n,i),e.encodeAsync=async(n,i)=>Cl(e,n,i),e.decodeAsync=async(n,i)=>Al(e,n,i),e.safeEncode=(n,i)=>xl(e,n,i),e.safeDecode=(n,i)=>Rl(e,n,i),e.safeEncodeAsync=async(n,i)=>Sl(e,n,i),e.safeDecodeAsync=async(n,i)=>Nl(e,n,i),Le(e,"ZodType",{check(...n){let i=this.def;return this.clone(ae(i,{checks:[...i.checks??[],...n.map((r)=>typeof r==="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),{parent:!0})},with(...n){return this.check(...n)},clone(n,i){return le(this,n,i)},brand(){return this},register(n,i){return n.add(this,i),this},refine(n,i){return this.check(xu(n,i))},superRefine(n,i){return this.check(Ru(n,i))},overwrite(n){return this.check(Ce(n))},optional(){return In(this)},exactOptional(){return fu(this)},nullable(){return Cn(this)},nullish(){return In(Cn(this))},nonoptional(n){return Tu(this,n)},array(){return w(this)},or(n){return Y([this,n])},and(n){return lu(this,n)},transform(n){return An(this,zi(n))},default(n){return yu(this,n)},prefault(n){return bu(this,n)},catch(n){return _u(this,n)},pipe(n){return An(this,n)},readonly(){return Iu(this)},describe(n){let i=this.clone();return Se.add(i,{description:n}),i},meta(...n){if(n.length===0)return Se.get(this);let i=this.clone();return Se.add(i,n[0]),i},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(n){return n(this)}}),Object.defineProperty(e,"description",{get(){return Se.get(e)?.description},configurable:!0}),e)),Pi=p("_ZodString",(e,t)=>{St.init(e,t),R.init(e,t),e._zod.processJSONSchema=(i,r,o)=>li(e,i,r,o);let n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,Le(e,"_ZodString",{regex(...i){return this.check(Pa(...i))},includes(...i){return this.check(za(...i))},startsWith(...i){return this.check(Da(...i))},endsWith(...i){return this.check(Ua(...i))},min(...i){return this.check(Ge(...i))},max(...i){return this.check(si(...i))},length(...i){return this.check(ai(...i))},nonempty(...i){return this.check(Ge(1,...i))},lowercase(i){return this.check($a(i))},uppercase(i){return this.check(La(i))},trim(){return this.check(Ba())},normalize(...i){return this.check(Fa(...i))},toLowerCase(){return this.check(ja())},toUpperCase(){return this.check(qa())},slugify(){return this.check(Ha())}})}),Ol=p("ZodString",(e,t)=>{St.init(e,t),Pi.init(e,t),e.email=(n)=>e.check(na(Ml,n)),e.url=(n)=>e.check(aa(Pl,n)),e.jwt=(n)=>e.check(_a(Kl,n)),e.emoji=(n)=>e.check(la($l,n)),e.guid=(n)=>e.check(gn(_n,n)),e.uuid=(n)=>e.check(ia(je,n)),e.uuidv4=(n)=>e.check(ra(je,n)),e.uuidv6=(n)=>e.check(oa(je,n)),e.uuidv7=(n)=>e.check(sa(je,n)),e.nanoid=(n)=>e.check(ua(Ll,n)),e.guid=(n)=>e.check(gn(_n,n)),e.cuid=(n)=>e.check(ca(zl,n)),e.cuid2=(n)=>e.check(da(Dl,n)),e.ulid=(n)=>e.check(pa(Ul,n)),e.base64=(n)=>e.check(ba(Vl,n)),e.base64url=(n)=>e.check(Ta(Zl,n)),e.xid=(n)=>e.check(ha(Fl,n)),e.ksuid=(n)=>e.check(fa(Bl,n)),e.ipv4=(n)=>e.check(ma(jl,n)),e.ipv6=(n)=>e.check(ga(ql,n)),e.cidrv4=(n)=>e.check(ya(Hl,n)),e.cidrv6=(n)=>e.check(va(Wl,n)),e.e164=(n)=>e.check(wa(Gl,n)),e.datetime=(n)=>e.check(pl(n)),e.date=(n)=>e.check(fl(n)),e.time=(n)=>e.check(gl(n)),e.duration=(n)=>e.check(vl(n))});function l(e){return ta(Ol,e)}var P=p("ZodStringFormat",(e,t)=>{O.init(e,t),Pi.init(e,t)}),Ml=p("ZodEmail",(e,t)=>{is.init(e,t),P.init(e,t)}),_n=p("ZodGUID",(e,t)=>{ts.init(e,t),P.init(e,t)}),je=p("ZodUUID",(e,t)=>{ns.init(e,t),P.init(e,t)}),Pl=p("ZodURL",(e,t)=>{rs.init(e,t),P.init(e,t)}),$l=p("ZodEmoji",(e,t)=>{os.init(e,t),P.init(e,t)}),Ll=p("ZodNanoID",(e,t)=>{ss.init(e,t),P.init(e,t)}),zl=p("ZodCUID",(e,t)=>{as.init(e,t),P.init(e,t)}),Dl=p("ZodCUID2",(e,t)=>{ls.init(e,t),P.init(e,t)}),Ul=p("ZodULID",(e,t)=>{us.init(e,t),P.init(e,t)}),Fl=p("ZodXID",(e,t)=>{cs.init(e,t),P.init(e,t)}),Bl=p("ZodKSUID",(e,t)=>{ds.init(e,t),P.init(e,t)}),jl=p("ZodIPv4",(e,t)=>{gs.init(e,t),P.init(e,t)}),ql=p("ZodIPv6",(e,t)=>{ys.init(e,t),P.init(e,t)}),Hl=p("ZodCIDRv4",(e,t)=>{vs.init(e,t),P.init(e,t)}),Wl=p("ZodCIDRv6",(e,t)=>{bs.init(e,t),P.init(e,t)}),Vl=p("ZodBase64",(e,t)=>{Ts.init(e,t),P.init(e,t)}),Zl=p("ZodBase64URL",(e,t)=>{_s.init(e,t),P.init(e,t)}),Gl=p("ZodE164",(e,t)=>{ks.init(e,t),P.init(e,t)}),Kl=p("ZodJWT",(e,t)=>{Is.init(e,t),P.init(e,t)}),$i=p("ZodNumber",(e,t)=>{Xn.init(e,t),R.init(e,t),e._zod.processJSONSchema=(i,r,o)=>ui(e,i,r,o),Le(e,"ZodNumber",{gt(i,r){return this.check(vn(i,r))},gte(i,r){return this.check(We(i,r))},min(i,r){return this.check(We(i,r))},lt(i,r){return this.check(yn(i,r))},lte(i,r){return this.check(He(i,r))},max(i,r){return this.check(He(i,r))},int(i){return this.check(kn(i))},safe(i){return this.check(kn(i))},positive(i){return this.check(vn(0,i))},nonnegative(i){return this.check(We(0,i))},negative(i){return this.check(yn(0,i))},nonpositive(i){return this.check(He(0,i))},multipleOf(i,r){return this.check(bn(i,r))},step(i,r){return this.check(bn(i,r))},finite(){return this}});let n=e._zod.bag;e.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??0.5),e.isFinite=!0,e.format=n.format??null});function m(e){return Aa($i,e)}var Jl=p("ZodNumberFormat",(e,t)=>{Cs.init(e,t),$i.init(e,t)});function kn(e){return xa(Jl,e)}var Yl=p("ZodBoolean",(e,t)=>{As.init(e,t),R.init(e,t),e._zod.processJSONSchema=(n,i,r)=>ci(e,n,i,r)});function E(e){return Ra(Yl,e)}var Xl=p("ZodUnknown",(e,t)=>{xs.init(e,t),R.init(e,t),e._zod.processJSONSchema=(n,i,r)=>hi(e,n,i,r)});function D(){return Sa(Xl)}var Ql=p("ZodNever",(e,t)=>{Rs.init(e,t),R.init(e,t),e._zod.processJSONSchema=(n,i,r)=>pi(e,n,i,r)});function eu(e){return Na(Ql,e)}var tu=p("ZodVoid",(e,t)=>{Ss.init(e,t),R.init(e,t),e._zod.processJSONSchema=(n,i,r)=>di(e,n,i,r)});function nu(e){return Oa(tu,e)}var iu=p("ZodDate",(e,t)=>{Ns.init(e,t),R.init(e,t),e._zod.processJSONSchema=(i,r,o)=>fi(e,i,r,o),e.min=(i,r)=>e.check(We(i,r)),e.max=(i,r)=>e.check(He(i,r));let n=e._zod.bag;e.minDate=n.minimum?new Date(n.minimum):null,e.maxDate=n.maximum?new Date(n.maximum):null});function Qe(e){return Ma(iu,e)}var ru=p("ZodArray",(e,t)=>{Os.init(e,t),R.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Ti(e,n,i,r),e.element=t.element,Le(e,"ZodArray",{min(n,i){return this.check(Ge(n,i))},nonempty(n){return this.check(Ge(1,n))},max(n,i){return this.check(si(n,i))},length(n,i){return this.check(ai(n,i))},unwrap(){return this.element}})});function w(e,t){return Wa(ru,e,t)}var ou=p("ZodObject",(e,t)=>{Ps.init(e,t),R.init(e,t),e._zod.processJSONSchema=(n,i,r)=>wi(e,n,i,r),A(e,"shape",()=>t.shape),Le(e,"ZodObject",{keyof(){return _(Object.keys(this._zod.def.shape))},catchall(n){return this.clone({...this._zod.def,catchall:n})},passthrough(){return this.clone({...this._zod.def,catchall:D()})},loose(){return this.clone({...this._zod.def,catchall:D()})},strict(){return this.clone({...this._zod.def,catchall:eu()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(n){return Jr(this,n)},safeExtend(n){return Yr(this,n)},merge(n){return Xr(this,n)},pick(n){return Gr(this,n)},omit(n){return Kr(this,n)},partial(...n){return Qr(Di,this,n[0])},required(...n){return eo(Ui,this,n[0])}})});function f(e,t){let n={type:"object",shape:e??{},...b(t)};return new ou(n)}var Li=p("ZodUnion",(e,t)=>{ti.init(e,t),R.init(e,t),e._zod.processJSONSchema=(n,i,r)=>_i(e,n,i,r),e.options=t.options});function Y(e,t){return new Li({type:"union",options:e,...b(t)})}var su=p("ZodDiscriminatedUnion",(e,t)=>{Li.init(e,t),$s.init(e,t)});function Ot(e,t,n){return new su({type:"union",options:t,discriminator:e,...b(n)})}var au=p("ZodIntersection",(e,t)=>{Ls.init(e,t),R.init(e,t),e._zod.processJSONSchema=(n,i,r)=>ki(e,n,i,r)});function lu(e,t){return new au({type:"intersection",left:e,right:t})}var uu=p("ZodTuple",(e,t)=>{ni.init(e,t),R.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Ei(e,n,i,r),e.rest=(n)=>e.clone({...e._zod.def,rest:n})});function cu(e,t,n){let i=t instanceof x;return new uu({type:"tuple",items:e,rest:i?t:null,...b(i?n:t)})}var En=p("ZodRecord",(e,t)=>{zs.init(e,t),R.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Ii(e,n,i,r),e.keyType=t.keyType,e.valueType=t.valueType});function z(e,t,n){if(!t||!t._zod)return new En({type:"record",keyType:l(),valueType:e,...b(t)});return new En({type:"record",keyType:e,valueType:t,...b(n)})}var _t=p("ZodEnum",(e,t)=>{Ds.init(e,t),R.init(e,t),e._zod.processJSONSchema=(i,r,o)=>mi(e,i,r,o),e.enum=t.entries,e.options=Object.values(t.entries);let n=new Set(Object.keys(t.entries));e.extract=(i,r)=>{let o={};for(let s of i)if(n.has(s))o[s]=t.entries[s];else throw Error(`Key ${s} not found in enum`);return new _t({...t,checks:[],...b(r),entries:o})},e.exclude=(i,r)=>{let o={...t.entries};for(let s of i)if(n.has(s))delete o[s];else throw Error(`Key ${s} not found in enum`);return new _t({...t,checks:[],...b(r),entries:o})}});function _(e,t){let n=Array.isArray(e)?Object.fromEntries(e.map((i)=>[i,i])):e;return new _t({type:"enum",entries:n,...b(t)})}var du=p("ZodLiteral",(e,t)=>{Us.init(e,t),R.init(e,t),e._zod.processJSONSchema=(n,i,r)=>gi(e,n,i,r),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function L(e,t){return new du({type:"literal",values:Array.isArray(e)?e:[e],...b(t)})}var pu=p("ZodTransform",(e,t)=>{Fs.init(e,t),R.init(e,t),e._zod.processJSONSchema=(n,i,r)=>bi(e,n,i,r),e._zod.parse=(n,i)=>{if(i.direction==="backward")throw new Ct(e.constructor.name);n.addIssue=(o)=>{if(typeof o==="string")n.issues.push($e(o,n.value,t));else{let s=o;if(s.fatal)s.continue=!1;s.code??(s.code="custom"),s.input??(s.input=n.value),s.inst??(s.inst=e),n.issues.push($e(s))}};let r=t.transform(n.value,n);if(r instanceof Promise)return r.then((o)=>(n.value=o,n.fallback=!0,n));return n.value=r,n.fallback=!0,n}});function zi(e){return new pu({type:"transform",transform:e})}var Di=p("ZodOptional",(e,t)=>{ii.init(e,t),R.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Nt(e,n,i,r),e.unwrap=()=>e._zod.def.innerType});function In(e){return new Di({type:"optional",innerType:e})}var hu=p("ZodExactOptional",(e,t)=>{Bs.init(e,t),R.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Nt(e,n,i,r),e.unwrap=()=>e._zod.def.innerType});function fu(e){return new hu({type:"optional",innerType:e})}var mu=p("ZodNullable",(e,t)=>{js.init(e,t),R.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Ci(e,n,i,r),e.unwrap=()=>e._zod.def.innerType});function Cn(e){return new mu({type:"nullable",innerType:e})}var gu=p("ZodDefault",(e,t)=>{qs.init(e,t),R.init(e,t),e._zod.processJSONSchema=(n,i,r)=>xi(e,n,i,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function yu(e,t){return new gu({type:"default",innerType:e,get defaultValue(){return typeof t==="function"?t():Un(t)}})}var vu=p("ZodPrefault",(e,t)=>{Hs.init(e,t),R.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Ri(e,n,i,r),e.unwrap=()=>e._zod.def.innerType});function bu(e,t){return new vu({type:"prefault",innerType:e,get defaultValue(){return typeof t==="function"?t():Un(t)}})}var Ui=p("ZodNonOptional",(e,t)=>{Ws.init(e,t),R.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Ai(e,n,i,r),e.unwrap=()=>e._zod.def.innerType});function Tu(e,t){return new Ui({type:"nonoptional",innerType:e,...b(t)})}var wu=p("ZodCatch",(e,t)=>{Vs.init(e,t),R.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Si(e,n,i,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function _u(e,t){return new wu({type:"catch",innerType:e,catchValue:typeof t==="function"?t:()=>t})}var Fi=p("ZodPipe",(e,t)=>{ri.init(e,t),R.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Ni(e,n,i,r),e.in=t.in,e.out=t.out});function An(e,t){return new Fi({type:"pipe",in:e,out:t})}var ku=p("ZodPreprocess",(e,t)=>{Fi.init(e,t),Zs.init(e,t)}),Eu=p("ZodReadonly",(e,t)=>{Gs.init(e,t),R.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Oi(e,n,i,r),e.unwrap=()=>e._zod.def.innerType});function Iu(e){return new Eu({type:"readonly",innerType:e})}var Cu=p("ZodPromise",(e,t)=>{Js.init(e,t),R.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Mi(e,n,i,r),e.unwrap=()=>e._zod.def.innerType});function gt(e){return new Cu({type:"promise",innerType:e})}var Au=p("ZodFunction",(e,t)=>{Ks.init(e,t),R.init(e,t),e._zod.processJSONSchema=(n,i,r)=>vi(e,n,i,r)});function qe(e){return new Au({type:"function",input:Array.isArray(e?.input)?cu(e?.input):e?.input??w(D()),output:e?.output??D()})}var Bi=p("ZodCustom",(e,t)=>{Ys.init(e,t),R.init(e,t),e._zod.processJSONSchema=(n,i,r)=>yi(e,n,i,r)});function K(e,t){return Va(Bi,e??(()=>!0),t)}function xu(e,t={}){return Za(Bi,e,t)}function Ru(e,t){return Ga(e,t)}function ji(e,t){return new ku({type:"pipe",in:zi(e),out:t})}ee(Qs());var qi=["none","minimal","low","medium","high","xhigh","max"],Su=_(qi),Nu=Su.exclude(["none"]),Ou=_([...qi,"default"]).nullable(),Mu=Ot("type",[f({type:L("toggle")}).strict(),f({type:L("effort"),values:w(Ou)}).strict(),f({type:L("budget_tokens"),min:m().min(-1).optional(),max:m().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"]})]),Pu=_(["default","openai-responses","r1"]);var $u=_(["images","video","tools","streaming","prompt-cache","reasoning","reasoning-effort","computer-use","global-endpoint","structured_output","temperature","files"]),Lu=_(["active","preview","deprecated","legacy"]),zu=f({input:m().optional(),output:m().optional(),cacheWrite:m().optional(),cacheRead:m().optional()}),Du=f({maxBudget:m().optional(),outputPrice:m().optional(),thinkingLevel:_(["low","high"]).optional()}),Uu=f({reasoningDefaultOn:E().optional(),apiProtocol:_(["openai-chat","openai-responses","anthropic","gemini"]).optional()}).catchall(D()),xn=_(["text","image","audio","video","pdf"]),Fu=f({input:w(xn),output:w(xn)});var Bu=_(["language","image-generation","speech-generation","video-generation","transcription","realtime"]);var ju=_(["batch","streaming"]);var Hi=f({id:l(),name:l().optional(),description:l().optional(),maxTokens:m().optional(),contextWindow:m().optional(),maxInputTokens:m().optional(),capabilities:w($u).optional(),operation:Bu.optional(),operationModes:w(ju).optional(),modalities:Fu.optional(),reasoningOptions:w(Mu).optional(),apiFormat:Pu.optional(),systemRole:_(["system","developer"]).optional(),temperature:m().optional(),pricing:zu.optional(),thinkingConfig:Du.optional(),status:Lu.optional(),deprecationNotice:l().optional(),replacedBy:l().optional(),releaseDate:l().optional(),deprecationDate:l().optional(),family:l().optional(),metadata:Uu.optional()});var Wi="NOT a tool or system failure. Clarify with user before proceeding.",qu=f({id:l(),name:l(),execution:_(["client","provider"]).optional(),input:D(),output:D(),error:l().optional(),durationMs:m(),startedAt:Qe(),endedAt:Qe()}),Hu=_(["completed","max_iterations","aborted","mistake_limit","error"]),Wu=f({inputTokens:m(),outputTokens:m(),cacheReadTokens:m().optional(),cacheWriteTokens:m().optional(),totalCost:m().optional()}),Tp=f({text:l(),usage:Wu,messages:w(K()),toolCalls:w(qu),iterations:m(),finishReason:Hu,model:f({id:l(),provider:l(),info:Hi.optional()}),startedAt:Qe(),endedAt:Qe(),durationMs:m()}),wp=f({distinctId:l().optional(),sessionId:l().optional(),providerId:l(),modelId:l(),apiKey:l().optional(),baseUrl:l().url().optional(),headers:z(l(),l()).optional(),knownModels:z(l(),Hi).optional(),providerConfig:D().optional(),initialMessages:w(K()).optional(),systemPrompt:l(),tools:w(K()),modelTools:w(K()).optional(),maxIterations:m().positive().optional(),maxParallelToolCalls:m().int().positive().default(8),maxTokensPerTurn:m().positive().optional(),maxToolResultChars:m().int().positive().optional(),temperature:m().nonnegative().optional(),apiTimeoutMs:m().positive().default(180000),userFileContentLoader:qe().input([l()]).output(gt(l())).optional(),toolContextMetadata:z(l(),D()).optional(),execution:f({maxConsecutiveMistakes:m().int().positive().optional(),reminderAfterIterations:m().nonnegative().optional(),reminderText:l().optional(),loopDetection:Y([L(!1),f({softThreshold:m().int().positive().optional(),hardThreshold:m().int().positive().optional()})]).optional(),reasoningLoopDetection:Y([L(!1),f({minChars:m().int().positive().optional(),window:m().int().positive().optional(),maxPeriod:m().int().positive().optional(),minCycles:m().int().positive().optional(),maxUniqueInWindow:m().int().positive().optional(),minLineChars:m().int().positive().optional(),phraseMaxPeriod:m().int().positive().optional(),phraseMinCycles:m().int().positive().optional(),maxConsecutiveTrips:m().int().positive().optional()})]).optional(),reasoningRepetition:Y([L(!1),f({minChars:m().int().positive().optional(),minParagraphChars:m().int().positive().optional(),minStopwords:m().int().nonnegative().optional(),maxRepeatTrip:m().int().positive().optional(),duplicateFractionTrip:m().min(0).max(1).optional(),cooldownTurns:m().int().nonnegative().optional(),maxNudges:m().int().nonnegative().optional(),recoveryTokens:m().int().nonnegative().optional()})]).optional()}).optional(),reasoningEffort:Nu.optional(),thinkingBudgetTokens:m().positive().optional(),thinking:E().optional(),onEvent:qe().input([K()]).output(nu()).optional(),hooks:K().optional(),parentAgentId:l().optional(),extensions:w(K()).optional(),hookErrorMode:_(["ignore","throw"]).default("ignore"),toolPolicies:z(l(),f({enabled:E().optional(),autoApprove:E().optional()})).optional(),unavailableToolReasons:z(l(),l()).optional(),requestToolApproval:qe().input([f({sessionId:l(),agentId:l(),conversationId:l(),iteration:m(),toolCallId:l(),toolName:l(),input:D(),policy:f({enabled:E().optional(),autoApprove:E().optional()}).default({})})]).output(Y([f({approved:E(),reason:l().optional()}),gt(f({approved:E(),reason:l().optional()}))])).optional(),onConsecutiveMistakeLimitReached:qe().input([f({iteration:m().int().positive(),consecutiveMistakes:m().int().positive(),maxConsecutiveMistakes:m().int().positive(),reason:_(["api_error","invalid_tool_call","tool_execution_failed"]),details:l().optional()})]).output(Y([f({action:L("continue"),guidance:l().optional()}),f({action:L("stop"),reason:l().optional()}),gt(Y([f({action:L("continue"),guidance:l().optional()}),f({action:L("stop"),reason:l().optional()})]))])).optional(),logger:K().optional(),extensionContext:K().optional(),abortSignal:K().optional()}),Vu=_(["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"]),Zu=f({id:l().optional(),label:l().optional(),role:l().optional(),participantKey:l().optional(),participantLabel:l().optional(),platformUserId:l().optional(),metadata:z(l(),D()).optional()}),Gu=f({source:l(),sourceEvent:l(),threadId:l(),channelId:l(),isDM:E(),sessionId:l().optional(),workspaceRoot:l().optional(),metadata:z(l(),D()).optional()}),_p=f({actor:Zu,context:Gu,payload:z(l(),D()).optional()}),kp=f({action:_(["allow","deny"]).default("allow"),message:l().optional(),reason:l().optional(),metadata:z(l(),D()).optional()}),Ep=f({adapter:l(),botUserName:l().optional(),event:Vu,payload:z(l(),D()),ts:l()});var Ku=["hooks","tools","commands","rules","skills","messageBuilders","providers","automationEvents","mcp"],Ip=new Set(Ku);var Ne={CLINE_PASS:"ext-cline-pass",CODE_CLOUD_AGENTS:"code-cloud-agents",CODE_ONBOARDING_GITHUB:"code-onboarding-github",CLINE_COMPOSIO_BETA:"CLINE_COMPOSIO_BETA"},Cp={[Ne.CLINE_PASS]:!1,[Ne.CODE_CLOUD_AGENTS]:!1,[Ne.CODE_ONBOARDING_GITHUB]:!1,[Ne.CLINE_COMPOSIO_BETA]:!1},Ap=Object.values(Ne),Ju=_(["agent_start","agent_resume","agent_abort","agent_end","agent_error","tool_call","tool_result","prompt_submit","pre_compact","session_shutdown"]),pe=z(l(),l()),Yu=f({toolName:l(),parameters:pe}),Xu=f({toolName:l(),parameters:pe,result:l(),success:E(),executionTimeMs:m()}),Qu=f({prompt:l(),attachments:w(l())}),ec=f({taskMetadata:pe}),tc=f({taskMetadata:pe,previousState:pe}),nc=f({taskMetadata:pe}),ic=f({taskMetadata:pe}),rc=f({taskId:l(),ulid:l(),contextSize:m(),compactionStrategy:l(),previousApiReqIndex:m(),tokensIn:m(),tokensOut:m(),tokensInCache:m(),tokensOutCache:m(),deletedRangeStart:m(),deletedRangeEnd:m(),contextJsonPath:l(),contextRawPath:l()}),xp=f({clineVersion:l(),hookName:Ju,timestamp:l(),taskId:l(),sessionContext:f({rootSessionId:l().optional(),hookLogPath:l().optional()}).optional(),workspaceRoots:w(l()),workspaceInfo:K().optional(),userId:l(),agent_id:l(),parent_agent_id:l().nullable(),iteration:m().optional(),reason:l().optional(),tool_call:f({id:l(),name:l(),input:D()}).optional(),tool_result:K().optional(),turn:D().optional(),error:f({name:l(),message:l(),stack:l().optional()}).optional(),preToolUse:Yu.optional(),postToolUse:Xu.optional(),userPromptSubmit:Qu.optional(),taskStart:ec.optional(),taskResume:tc.optional(),taskCancel:nc.optional(),taskComplete:ic.optional(),preCompact:rc.optional()}).passthrough();var oc=["readFile","search","bash","webFetch","editor","applyPatch","skills","askQuestion","submit"],Rp=new Set(oc);var Rn="<tool_call>",sc=/<tool_call>|<parameter=[^>]*>|<\/parameter>/g,ac=/<function=[^\s>]+\s*>/,Mt="[SYSTEM] Your last message contained no tool calls, so the run was about to end. If the task is not finished, continue now by emitting the tool calls it needs - do not describe what you are going to do without doing it. If the task really is finished, say so in one short sentence. If it stopped at a limit, a refusal or anything else only the user can change, and you have told the user so, that is finished too: say so in one short sentence and do not look for a way around it.",Vi=" If what you need is a decision from the user, call `ask_question` - that is the only way to reach them. A question written as ordinary text is not a question anyone will see: it reads here as a turn that called nothing, which is what produced this message.",lc="[SYSTEM] You have now taken ";function Zi(e,t){let n=Math.round(t/1000),i=n>=1?`about ${n.toLocaleString("en-US")},000 characters of reasoning`:"a full turn of reasoning";return lc+`${e} turns in a row without calling a single tool, spending ${i} on them. Thinking further has not moved this task, and it will not: you have already reasoned past the point where more of it helps. Stop analysing and make one tool call now - the smallest one that makes any progress at all, even if you are not certain it is the right one, because a call you can check beats an analysis you cannot. If you genuinely cannot make one, say what is blocking you in a single sentence and stop.`}var uc="[SYSTEM] Your last message contained a tool call that could not be read.",cc="<|tool_call>",Sn="<tool_call|>",ve='<|"|>',dc=/<\|tool_call>\s*call:([A-Za-z_][\w.-]*)\s*\{/g;function Gi(e){return`(A call to ${e.name?`\`${e.name}\``:"a tool"} was written here but could not be read, so nothing ran. Its text is not kept.)`}function yt(e){return JSON.stringify(e.replace(/\s+/g," ").trim())}function pc(e){let t=[];for(let r=e.indexOf(ve);r!==-1;r=e.indexOf(ve,r+ve.length))t.push(r);let n=(r)=>/([A-Za-z_]\w*)\s*:\s*$/.exec(e.slice(Math.max(0,r-80),r))?.[1],i=()=>{let r=/([A-Za-z_]\w*)\s*:\s*(?!<\|"\|>)([^,{}[\]<]{1,60})<\|"\|>/.exec(e);return r?`The value of \`${r[1]}\` (${yt(r[2])}) closes a string it never opened.`:void 0};for(let r=0;r+1<t.length;r+=2){let o=t[r],s=t[r+1],a=n(o),u=e.slice(o+ve.length,s),c=/([^\s,]{0,12})\s*,\s*([A-Za-z_]\w*)\s*:\s*$/.exec(u);if(c&&a){let h=c[1],g=h?`you wrote ${yt(h.slice(-8))} where its closing delimiter belongs`:"its closing delimiter is missing";return`The string for \`${a}\` was never closed: ${g}, just before \`${c[2]}\`. A string argument ends with the same delimiter that opened it and with nothing else - not a backtick, not a quote, not a tag.`}let d=e.slice(s+ve.length),y=/^\s*(\S)/.exec(d)?.[1];if(y&&!",}]".includes(y)){let h=/^\s*([A-Za-z_]\w*)\s*:/.exec(d)?.[1];if(!h){let g=i();if(g)return g}return h&&a?`There is no comma between \`${a}\` and \`${h}\`. Every argument is separated from the next by a comma.`:`After the string for \`${a??"an argument"}\` closes, the call continues with ${yt(d.slice(0,24))} where a comma or the end of the call belongs.`}}if(t.length%2===1)return`The string for \`${n(t[t.length-1])??"the last argument"}\` was opened and never closed.`;return i()}function hc(e){let t=[...e.matchAll(dc)];if(t.length===0)return;let n=t[t.length-1]?.[1],i=0;for(let u=1;u<t.length;u+=1){let c=e.slice(t[u-1].index??0,t[u].index??0);if((c.split(ve).length-1)%2===1||!c.includes(Sn))i+=1}let r=t[t.length-1],o=(r.index??0)+r[0].length,s=e.indexOf(Sn,o),a=i>0?void 0:pc(e.slice(o,s===-1?void 0:s));return{blocks:t.length,restarts:i,dialect:"gemma",...n?{name:n}:{},...a?{defect:a}:{}}}function Ae(e){if(!e)return;if(e.includes(cc)){let u=hc(e);if(u)return u}if(!e.includes(Rn)||!ac.test(e))return;let t=0,n=0,i=0;for(let u of e.matchAll(sc)){let c=u[0];if(c===Rn)t+=1;else if(c==="</parameter>")i+=1;else n+=1}if(t===0)return;let r=Math.max(n-i,0),o=Math.min(Math.max(t-1,0),r),s=[...e.matchAll(/<function=([^\s>]+)\s*>/g)],a=s[s.length-1]?.[1];return{blocks:t,restarts:o,dialect:"qwen",...a?{name:a}:{}}}function Pt(e){let t=e.name?`\`${e.name}\``:"a tool",n=e.dialect==="gemma",i=n?"string argument":"parameter",r=e.restarts>0?` You began ${t} and then, part-way through a ${i} you never closed, started the whole call again${e.restarts>1?`, ${e.restarts} times over`:""}. The reader cannot tell an abandoned call from the value of the ${i} it was abandoned inside, so all of it came back as text.`:e.defect?` It named ${t}. ${e.defect}`:` It named ${t}, but the block was not well formed and could not be read.`,o=n?" Write the call again, once: every string argument opens and closes with the same string delimiter, arguments are separated by commas, and the call is closed after the last one.":" Emit the call once, in one clean block: open it, give each parameter and close each parameter, then close the function and the call.";return uc+r+" Nothing ran, so nothing has changed on disk. The call is not in this conversation any more, so do not look for it or copy it: write it fresh."+o+" Do not restart a call once you have begun it - finish it, or send nothing and start the next turn fresh."}var fc="[SYSTEM] You wrote ";function Ki(e){let t=e.trim().replace(/\s+/g," ").slice(0,200);return fc+`"${t}" and then called nothing, for the second turn running. Saying what you are about to do is not doing it, and the run ends on the next silent turn with the work undone. Emit the tool call itself now - the first one, not a description of it. If you cannot, say plainly what is stopping you in one sentence.`}var Ji=/\b(?:let me|i'?ll|i will|i'?m going to|i am going to|now i(?:'?ll| will)|next,? i(?:'?ll| will)|let'?s)\b/i,Yi=/\b(?:task (?:is )?(?:complete|finished|done)|all done|is now (?:complete|finished|fixed|working)|i(?:'?m| am) (?:done|finished)|nothing (?:else|more) to do|no further changes)\b/i;function at(e){let t=e?.trim();if(!t||Yi.test(t))return;let n=t.slice(-400);return Ji.test(n)?t:void 0}var mc=300;function Xi(e){let t=e?.trim();return!!t&&t.length<=mc&&!/\n\s*\n/.test(t)&&!t.endsWith("?")&&at(t)===void 0}var gc=/(?:^done\b|^i(?:'ve| have) (?:now |fully |successfully )?(?:completed|finished)\b|\b(?:is|are|was|were|has been|have been) (?:now |all |fully |successfully )?(?:complete|completed|finished|done)\b)/i;function Qi(e){return e.slice(-300).includes("?")||Ji.test(e.slice(-400))}function er(e){let t=e?.trim();if(!t)return!1;let n=t.replace(/[*_`]/g,"");return(Yi.test(n)||gc.test(n))&&!Qi(t)}function tr(e){let t=e?.trim();return!!t&&!Qi(t)}var yc=_(["image","audio","video","file"]),vc=Ot("type",[f({type:L("base64"),data:l().min(1)}),f({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")}),f({type:L("artifact"),artifactId:l().min(1)})]);function bc(e){if(e.startsWith("image/"))return"image";if(e.startsWith("audio/"))return"audio";if(e.startsWith("video/"))return"video";return"file"}var Sp=f({id:l().min(1),modality:yc,mediaType:l().min(1),source:vc,name:l().min(1).optional(),sizeBytes:m().int().nonnegative().optional()}).refine((e)=>bc(e.mediaType)===e.modality,{message:"Generated media modality must match its media type",path:["modality"]});function Nn(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function $t(e,t){if(!e&&!t)return;let n=e?.metadata,i=t?.metadata,r={...e??{},...t??{}};if(Nn(n)&&Nn(i))r.metadata={...n,...i};return r}var On=Symbol.for("cline.shared.tokenCalibration");function Tc(e,t){if(e===void 0||t===void 0)return!0;return e===t}function nr(){let e=globalThis,t=e[On];if(t)return t;let n={};return e[On]=n,n}function wc(){return nr().charsPerToken??3}function Lt(e){let t=nr();return Tc(t.outputCapOwner,e)?t.outputCap:void 0}function ir(e){return Math.max(1,Math.ceil(e/wc()))}function Te(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function _c(e){let t=e.type;if(typeof t==="string")return[t];return Array.isArray(t)?t.filter((n)=>typeof n==="string"):[]}function kt(e,t){if(_c(e).includes(t))return!0;for(let n of["anyOf","oneOf","allOf"]){let i=e[n];if(Array.isArray(i)&&i.some((r)=>Te(r)&&kt(r,t)))return!0}return!1}function kc(e,t){if(typeof e!=="string")return e;let n=e.trim(),i=kt(t,"array"),r=kt(t,"object");if((!i||!n.startsWith("["))&&(!r||!n.startsWith("{")))return e;try{let o=JSON.parse(n);if(Array.isArray(o))return i?o:e;if(Te(o))return r?o:e;return e}catch{return e}}function Ie(e,t){let n=kc(e,t);if(Array.isArray(n)){let s=t.items;if(!Te(s))return n;let a=!1,u=n.map((c)=>{let d=Ie(c,s);return a||=d!==c,d});return a?u:n}if(!Te(n))return n;let i=t.properties;if(!Te(i))return n;let r=!1,o={...n};for(let[s,a]of Object.entries(i)){if(!(s in n)||!Te(a))continue;let u=Ie(n[s],a);if(u!==n[s])o[s]=u,r=!0}return r?o:n}function rr(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}function B(e){let t=e?.trim();return t?t:void 0}function Ec(e){return cl(e)}var Np=new RegExp(`${"⁣⟦"}([^${"⟧"}]*)${"⟧"}([\\s\\S]*?)${"⟦/⟧⁣"}`,"g");var or=`# Plan Mode
65
65
 
66
66
  You are in Plan mode. Your role is to explore, analyze, and plan -- not to execute.
67
67
 
@@ -76,7 +76,7 @@ The run_commands tool remains available in plan mode strictly for read-only insp
76
76
 
77
77
  Once the user has reviewed your plan and explicitly approved it in a follow-up message, use the switch_to_act_mode tool to switch to act mode and begin implementation. Calling switch_to_act_mode immediately starts execution, so never call it in the same turn you present a plan and never treat the original task request as approval -- end your turn after presenting the plan and wait for the user's response.`,Mp=`${or}
78
78
 
79
- Once you have presented your plan, end your turn and wait for the user's response. You do NOT have the ability to switch to act mode yourself -- the user must do it manually with the Plan/Act toggle once they are satisfied with the plan. If the task requires tools that are only available in act mode, ask the user to "toggle to Act mode" (use those words).`;var Ic=h({id:l(),temperature:m().optional(),maxTokens:m().optional(),contextWindow:m().optional(),inputPrice:m().optional(),outputPrice:m().optional(),supportsImages:E().optional()}),Cc=h({models:_(Ic).optional(),openAiBaseUrl:l().optional(),openAiHeaders:z(l(),l()).optional(),azureApiVersion:l().optional(),azureIdentity:E().optional()}),Ac=h({id:l(),thinkingBudgetTokens:m().optional()}),xc=h({name:l(),baseModelId:l(),thinkingBudgetTokens:m().optional()}),Rc=h({models:_(Ac).optional(),customModels:_(xc).optional(),awsRegion:l().optional(),awsUseCrossRegionInference:E().optional(),awsUseGlobalInference:E().optional(),awsBedrockUsePromptCache:E().optional(),awsBedrockEndpoint:l().optional()}),Sc=h({id:l()}),Nc=h({models:_(Sc).optional()}),Oc=h({id:l(),thinkingBudgetTokens:m().optional()}),Mc=h({models:_(Oc).optional(),vertexProjectId:l().optional(),vertexRegion:l().optional()}),Pc=h({id:l(),thinkingBudgetTokens:m().optional(),promptCachingEnabled:E().optional()}),$c=h({models:_(Pc).optional(),baseUrl:l().optional()}),Lc=h({id:l(),thinkingBudgetTokens:m().optional()}),zc=h({models:_(Lc).optional(),baseUrl:l().optional()}),Dc=h({OpenAiCompatible:Cc.optional(),AwsBedrock:Rc.optional(),Cline:Nc.optional(),Vertex:Mc.optional(),LiteLLM:$c.optional(),Anthropic:zc.optional()}),Uc=h({id:l()}),Fc=h({name:l(),url:l(),alwaysEnabled:E().optional(),headers:z(l(),l()).optional()}),Mn=h({alwaysEnabled:E(),name:l(),contents:l()}),vt=h({bucket:l(),accessKeyId:l(),secretAccessKey:l(),region:l().optional(),endpoint:l().optional(),accountId:l().optional()}),Bc=h({enabled:E().optional(),type:X([L("s3_access_keys"),L("r2_access_keys"),L("azure_access_keys")]).optional(),s3AccessSettings:vt.optional(),r2AccessSettings:vt.optional(),azureAccessSettings:vt.optional()}),jc=h({promptUploading:Bc.optional()}),Pp=h({version:l(),providerSettings:Dc.optional(),telemetryEnabled:E().optional(),kanbanEnabled:E().optional(),mcpMarketplaceEnabled:E().optional(),allowedMCPServers:_(Uc).optional(),remoteMCPServers:_(Fc).optional(),blockPersonalRemoteMCPServers:E().optional(),yoloModeAllowed:E().optional(),openTelemetryEnabled:E().optional(),openTelemetryMetricsExporter:l().optional(),openTelemetryLogsExporter:l().optional(),openTelemetryOtlpProtocol:l().optional(),openTelemetryOtlpEndpoint:l().optional(),openTelemetryOtlpHeaders:z(l(),l()).optional(),openTelemetryOtlpMetricsProtocol:l().optional(),openTelemetryOtlpMetricsEndpoint:l().optional(),openTelemetryOtlpMetricsHeaders:z(l(),l()).optional(),openTelemetryOtlpLogsProtocol:l().optional(),openTelemetryOtlpLogsEndpoint:l().optional(),openTelemetryOtlpLogsHeaders:z(l(),l()).optional(),openTelemetryMetricExportInterval:m().optional(),openTelemetryOtlpInsecure:E().optional(),openTelemetryLogBatchSize:m().optional(),openTelemetryLogBatchTimeout:m().optional(),openTelemetryLogMaxQueueSize:m().optional(),enterpriseTelemetry:jc.optional(),globalRules:_(Mn).optional(),globalWorkflows:_(Mn).optional()}),$p=z(l(),l());var Lp=k(["reasoning","prompt-cache","tools","provider-tools","oauth","temperature","files","streaming","vision","computer-use","local-auth","popular"]),zp=k(["anthropic","gemini","openai-chat","openai-responses","openai-r1","ai-sdk"]),Dp=k(["anthropic","ai-sdk","ai-sdk-community","openai","openai-compatible","openai-r1","gemini","bedrock","custom","fetch","vertex"]);var sr="task.provider_request_started",ar="task.provider_stream_started",lr="task.first_chunk_received",ur="task.provider_stream_failed",cr="task.cancelled";var ve=new Map;function qc(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 Hc(e){let t=Date.now(),n=ve.get(e);if(n&&t-n.startMs<3600000){if(n.emitted<5)return n.emitted+=1,{emit:!0,suppressed:0};return n.suppressed+=1,{emit:!1,suppressed:n.suppressed}}let i=n?.suppressed??0;if(ve.delete(e),ve.size>=512){let r=ve.keys().next();if(!r.done)ve.delete(r.value)}return ve.set(e,{startMs:t,emitted:1,suppressed:0}),{emit:!0,suppressed:i}}function dr(e,t){e?.capture({event:"agent.reasoning.unexpected_tokens",properties:zt({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 pr(e,t){if(!e)return;e.capture({event:t.event,properties:zt({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?{}:fr(t.error,t.messageLimit),error_class:t.errorClass})})}function hr(e,t){if(!e)return!1;let n=t.event??"sdk.error",i=Wc(t),r=0;try{let o=Hc(qc(n,i));if(!o.emit)return!0;r=o.suppressed}catch{}return e.capture({event:n,properties:r>0?{...i,suppressed_count:r}:i}),!0}function Wc(e){return zt({...e.context??{},component:e.component,operation:e.operation,severity:e.severity??"error",handled:e.handled??!0,...fr(e.error,e.messageLimit,e.errorMessage)})}function zt(e){let t={};for(let[n,i]of Object.entries(e))if(i!==void 0)t[n]=i;return t}function fr(e,t=500,n){let i=Gc(e)?e:void 0,r=e instanceof Error?e:void 0,o=Me(n)??Me(r?.message)??Me(i?.message)??Kc(e)??"Unknown error",s=Jc(i?.code),a=bt(i?.status)??bt(i?.statusCode)??bt(i?.responseStatus);return{error_type:r?.name?.trim()||Me(i?.name)||r?.constructor?.name||"Error",error_message:Zc(Vc(o),t),...s!==void 0?{error_code:s}:{},...a!==void 0?{error_status:a}:{}}}function Vc(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 Zc(e,t){let n=Math.max(1,Math.floor(t));return e.length>n?e.substring(0,n):e}function Gc(e){return typeof e==="object"&&e!==null}function Me(e){return typeof e==="string"&&e.trim().length>0?e:void 0}function Kc(e){if(e instanceof Error)return;let t=typeof e==="string"?e:String(e);return t==="[object Object]"?void 0:Me(t)}function Jc(e){if(typeof e==="string"&&e.trim().length>0)return e;if(typeof e==="number"&&Number.isFinite(e))return e;return}function bt(e){return typeof e==="number"&&Number.isFinite(e)?e:void 0}var Yc=["rules","skills","workflows","plugins","hooks"];var Up=new Set(Yc);var Xc=h({rootPath:l().min(1),hint:l().min(1).optional(),associatedRemoteUrls:_(l().min(1)).optional(),latestGitCommitHash:l().min(1).optional(),latestGitBranchName:l().min(1).optional()}),Fp=h({currentWorkspacePath:l().min(1).optional(),workspaces:z(l().min(1),Xc)});var Qc=["current_state","boundary_analysis","interface_proposal"];var Q=ji((e)=>e instanceof Date?e.toISOString():e,l().datetime()),_e=k(["pending","in_progress","blocked","completed"]),mr=k(["queued","running","completed","failed","cancelled","interrupted"]),lt=k(["draft","in_review","finalized"]),ed=h({agentId:l(),role:k(["lead","teammate"]),description:l().optional(),status:k(["idle","running","stopped"])}),Bp=h({agentId:l(),rolePrompt:l(),modelId:l().optional(),maxIterations:m().optional(),temperature:m().nonnegative().optional(),seed:m().int().optional(),seedRandom:E().optional(),temperatureBase:m().nonnegative().optional(),temperatureRange:m().min(0).max(100).optional()});function C(e){return ji((t)=>t===null?void 0:t,e.optional())}var jp=h({agentId:l().min(1).describe("Teammate identifier"),rolePrompt:l().min(1).describe("System prompt describing teammate role"),temperature:C(X([m().nonnegative(),l()])).describe(`Sampling temperature for this teammate, over its model's own. "random": a draw within 2% of the model's own temperature (a model at 1.0 gets 0.98 to 1.02); that narrow band is the intended variation. Omit to keep the model's.`),seed:C(X([m().int(),l()])).describe('Sampling seed for this teammate. "random" draws one. Omit to leave it unset.'),temperature_range:C(X([m().min(0).max(100),l()])).describe("Percent the temperature is randomized by, around `temperature` or the model's own. Set it only when the user states a number; left out, 2 applies. Held to 10 at most.")}).strict(),qp=h({agentId:l().min(1).describe("Teammate identifier"),reason:C(l().min(1)).describe("Optional shutdown reason")}),Hp=h({}),gr={create:["title","description"],list:[],claim:["taskId"],complete:["taskId","summary"],block:["taskId","reason"]};var Wp=h({action:k(["create","list","claim","complete","block"]),title:C(l().min(1)).describe("Task title"),description:C(l().min(1)).describe("Task details"),dependsOn:C(_(l().describe("Dependency task ID"))).describe("Array of dependency task IDs"),assignee:C(l().min(1)).describe("Optional assignee"),status:C(k(["pending","in_progress","blocked","completed"])).describe("Optional task status filter"),taskId:C(l()).describe("Task ID"),summary:C(l().min(1)).describe("Completion summary"),reason:C(l().min(1)).describe("Blocking reason")}).superRefine((e,t)=>{for(let n of gr[e.action]){if(e[n]!==void 0)continue;t.addIssue({code:"custom",path:[n],message:`Field "${n}" is required when action=${e.action}`})}}),Vp=h({action:k(["list","claim","complete","block"]),status:C(k(["pending","in_progress","blocked","completed"])).describe("Optional task status filter"),assignee:C(l().min(1)).describe("Optional assignee filter"),taskId:C(l()).describe("Task ID"),summary:C(l().min(1)).describe("Completion summary"),reason:C(l().min(1)).describe("Blocking reason")}).superRefine((e,t)=>{for(let n of gr[e.action]){if(e[n]!==void 0)continue;t.addIssue({code:"custom",path:[n],message:`Field "${n}" is required when action=${e.action}`})}}),Zp=h({agentId:l().describe("Teammate agent ID"),task:l().min(1).describe("Task instructions for the teammate"),taskId:C(l()).describe("Optional shared task list ID"),runMode:C(k(["sync","async"])).describe("Execution mode: 'sync' blocks until the teammate finishes and returns the result (default if omitted); 'async' queues the run and returns a runId immediately — use team_await_runs to collect results later."),continueConversation:C(E()).describe("If true, continue the teammate conversation; otherwise start fresh")}),Gp=h({status:C(k(["queued","running","completed","failed","cancelled","interrupted"])).describe("Optional run status filter. Omit to include all statuses."),agentId:C(l().min(1)).describe("Optional teammate ID filter. Omit to include all teammates."),includeCompleted:C(E()).describe("Include completed/failed runs (default true)")}),Kp=h({runId:l().min(1).describe("Run ID"),reason:C(l().min(1)).describe("Optional cancellation reason")}),Jp=h({runId:C(l().min(1)).describe("Optional async run ID to await. Omit to wait for all active async runs.")}).strict(),Yp=h({toAgentId:l().min(1).describe("Recipient agent ID"),subject:l().min(1).describe("Message subject"),body:l().min(1).describe("Message body"),taskId:C(l().min(1)).describe("Optional task ID context")}),Xp=h({subject:l().min(1).describe("Message subject"),body:l().min(1).describe("Message body"),taskId:C(l().min(1)).describe("Optional task ID context")}),Qp=h({unreadOnly:C(E()).describe("Only unread messages for read action (default true)")}),eh=h({kind:k(["progress","handoff","blocked","decision","done","error"]),summary:l().min(1).describe("Update summary"),taskId:C(l().min(1)).describe("Optional task ID context"),evidence:C(_(l().min(1))).describe("Optional evidence links/snippets"),nextAction:C(l().min(1)).describe("Planned next step")}),th=h({}),nh=h({title:l().describe("Outcome title"),requiredSections:_(l()).default(Qc).describe("Required sections for finalization gate (defaults to current_state,boundary_analysis,interface_proposal)")}),ih=h({outcomeId:l().describe("Outcome ID"),section:l().describe("Section name"),sourceRunId:C(l()).describe("Optional source run ID"),content:l().describe("Section fragment content")}),rh=h({fragmentId:l().describe("Fragment ID"),approved:E().describe("Review decision")}),oh=h({outcomeId:l().describe("Outcome ID")}),sh=h({}),ah=h({teamId:l(),teamName:l(),members:_(ed),taskCounts:z(_e,m()),unreadMessages:m(),missionLogEntries:m(),activeRuns:m(),queuedRuns:m(),outcomeCounts:z(lt,m())}),td=h({id:l(),title:l(),description:l(),status:_e,createdAt:Q,updatedAt:Q,createdBy:l(),assignee:l().optional(),dependsOn:_(l()),summary:l().optional(),isReady:E(),blockedBy:_(l())}),lh=Ot("action",[h({action:L("create"),taskId:l(),status:_e,ignoredFields:_(l()).optional(),note:l().optional()}),h({action:L("list"),tasks:_(td)}),h({action:L("claim"),taskId:l(),status:_e,nextStep:l()}),h({action:L("complete"),taskId:l(),status:_e}),h({action:L("block"),taskId:l(),status:_e})]),uh=h({agentId:l(),mode:k(["sync","async"]),status:k(["dispatched","running","queued","joined"]),dispatched:E(),message:l(),deduped:E().optional(),runId:l().optional(),text:l().optional(),iterations:m().optional(),maxIterations:m().optional(),finishReason:l().optional(),stopReason:L("iteration_cap").optional()}),nd=h({textPreview:l(),text:l().optional(),iterations:m(),finishReason:l(),durationMs:m(),usage:h({inputTokens:m(),outputTokens:m(),cacheReadTokens:m().optional(),cacheWriteTokens:m().optional(),totalCost:m().optional()})}),ch=h({id:l(),agentId:l(),taskId:l().optional(),status:mr,messagePreview:l(),priority:m(),retryCount:m(),maxRetries:m(),nextAttemptAt:Q.optional(),continueConversation:E().optional(),startedAt:Q,endedAt:Q.optional(),leaseOwner:l().optional(),heartbeatAt:Q.optional(),lastProgressAt:Q.optional(),lastProgressMessage:l().optional(),currentActivity:l().optional(),error:l().optional(),resultSummary:nd.optional()}),dh=h({id:l(),teamId:l(),fromAgentId:l(),toAgentId:l(),subject:l(),body:l(),taskId:l().optional(),sentAt:Q,readAt:Q.optional()}),ph=h({id:l(),teamId:l(),title:l(),status:lt,requiredSections:_(l()),createdBy:l(),createdAt:Q,finalizedAt:Q.optional()}),hh=h({outcomeId:l(),status:lt,requiredSections:_(l())}),fh=h({agentId:l(),status:l()}),mh=h({runId:l(),status:mr}),gh=h({id:l(),toAgentId:l()}),yh=h({delivered:m()}),vh=h({id:l()}),bh=h({status:l()}),Th=h({fragmentId:l(),status:l()}),wh=h({outcomeId:l(),status:lt}),id;((e)=>{e.TaskStart="task_start",e.TaskEnd="task_end",e.AgentEvent="agent_event",e.TeammateSpawned="teammate_spawned",e.TeammateShutdown="teammate_shutdown",e.TeamTaskUpdated="team_task_updated",e.TeamMessage="team_message",e.TeamMissionLog="team_mission_log",e.TeamTaskCompleted="team_task_completed",e.RunStarted="run_started",e.RunQueued="run_queued",e.RunProgress="run_progress",e.RunCompleted="run_completed",e.RunFailed="run_failed",e.RunCancelled="run_cancelled",e.RunInterrupted="run_interrupted",e.OutcomeCreated="outcome_created",e.OutcomeFragmentAttached="outcome_fragment_attached",e.OutcomeFragmentReviewed="outcome_fragment_reviewed",e.OutcomeFinalized="outcome_finalized",e.TeamCleaned="team_cleaned"})(id||={});function rd(e){let{$schema:t,...n}=e;if(typeof n.type==="string")return n;if("properties"in n||"required"in n||"additionalProperties"in n)return{type:"object",...n};for(let i of["oneOf","anyOf","allOf"]){let r=n[i];if(!Array.isArray(r)||r.length===0)continue;if(i==="allOf"){if(r.some((o)=>o&&typeof o==="object"&&o.type==="object"))return{type:"object",...n};throw Error('Tool inputSchema must describe an object at the top level, but the schema has a top-level "allOf" with no branch that asserts type: "object". Add type: "object" to at least one allOf branch to make the object constraint explicit.')}if(r.every((o)=>o&&typeof o==="object"&&o.type==="object"))return{type:"object",...n};throw Error(`Tool inputSchema must describe an object at the top level, but the schema has a top-level "${i}" whose branches include non-object types. Pass the strict object schema as inputSchema and reserve union/coercion schemas for use inside execute().`)}return n}function od(e){let t=rd(e.inputSchema instanceof R?Ec(e.inputSchema):e.inputSchema);return{name:e.name,resultPolicy:e.resultPolicy,description:e.description,inputSchema:t,...e.source?{source:e.source}:{},...e.readOnly?{readOnly:!0}:{},lifecycle:e.lifecycle,executionMode:e.executionMode,timeoutMs:e.timeoutMs??30000,retryable:e.retryable??!0,maxRetries:e.maxRetries??3,execute:e.execute}}var _h="Switch from plan mode to act mode. Switching to act mode immediately starts executing the plan, so only call this after the user has explicitly approved the plan in a message sent AFTER you presented it (e.g. 'looks good', 'go ahead', 'switch to act mode'). Never call this in the same turn you present a plan, never call it proactively, and never treat the original task request as approval. "+"Output: a one-line confirmation, as plain text. This call ends the current run and the next one starts in act mode with the file and command tools available, so it is a handover, not a failure — carry on with the plan there.";import{classifyProviderError as xr,createGateway as bd,isRetryableProviderError as Td}from"@cerebriline/llms";import{nanoid as wd}from"nanoid";function Dt(){return{reasoningDeltas:0,reasoningChars:0,textDeltas:0,textChars:0,toolInputChars:0}}var sd=12;function yr(e,t){let n=t.reduce((a,u)=>a+u,0);if(n<=0)return t.map(()=>0);let i=t.map((a)=>e*a/n),r=i.map(Math.floor),o=e-r.reduce((a,u)=>a+u,0),s=i.map((a,u)=>({index:u,rest:a-Math.floor(a)})).sort((a,u)=>u.rest-a.rest);for(let{index:a}of s){if(o<=0)break;r[a]=(r[a]??0)+1,o-=1}return r}function vr(e){let t=Math.floor(e.outputTokens??0);if(!(t>0))return;let{tally:n}=e,i=e.providerReasoningTokens??0;if(i>0){let c=Math.min(t,Math.floor(i)),[d=0,y=0]=yr(t-c,n.textChars+n.toolInputChars>0?[n.textChars,n.toolInputChars]:[1,0]);return{reasoningTokens:c,textTokens:d,toolInputTokens:y,method:"provider"}}let r=n.reasoningDeltas+n.textDeltas,o=n.reasoningChars+n.textChars;if(r>0&&r<=t&&o/r<=sd)return{reasoningTokens:n.reasoningDeltas,textTokens:n.textDeltas,toolInputTokens:t-r,method:"stream-chunks"};let[s=0,a=0,u=0]=yr(t,o+n.toolInputChars>0?[n.reasoningChars,n.textChars,n.toolInputChars]:[0,1,0]);return{reasoningTokens:s,textTokens:a,toolInputTokens:u,method:"chars-share"}}var ut={minChars:4000,window:60,maxPeriod:6,minCycles:20,maxUniqueInWindow:4,minLineChars:2000,phraseMaxPeriod:120,phraseMinCycles:12,maxConsecutiveTrips:3};function Ft(e){let t=`after ${e.chars.toLocaleString()} characters of reasoning`,n=e.sample?` Repeating: ${JSON.stringify(e.sample)}`:"";switch(e.kind){case"low-uniqueness":return`The model's reasoning collapsed into ${e.distinct} distinct lines over ${t}.${n}`;case"line-cycle":return`The model's reasoning repeated a ${e.period}-line block ${e.cycles} times ${t}.${n}`;case"phrase-cycle":return`The model's reasoning repeated a ${e.period}-character phrase ${e.cycles} times ${t}.${n}`}}function br(e){let t=[],n=(i,r)=>{if(typeof i==="string"){if(i)t.push(i)}else if(r<6&&Array.isArray(i))for(let o of i)n(o,r+1);else if(r<6&&i!==null&&typeof i==="object")for(let o of Object.values(i))n(o,r+1)};for(let i of e){if(i.role==="assistant")continue;for(let r of i.content)if(r.type==="text")n(r.text,0);else if(r.type==="tool-result")n(r.output,0)}return t.join(`
79
+ Once you have presented your plan, end your turn and wait for the user's response. You do NOT have the ability to switch to act mode yourself -- the user must do it manually with the Plan/Act toggle once they are satisfied with the plan. If the task requires tools that are only available in act mode, ask the user to "toggle to Act mode" (use those words).`;var Ic=f({id:l(),temperature:m().optional(),maxTokens:m().optional(),contextWindow:m().optional(),inputPrice:m().optional(),outputPrice:m().optional(),supportsImages:E().optional()}),Cc=f({models:w(Ic).optional(),openAiBaseUrl:l().optional(),openAiHeaders:z(l(),l()).optional(),azureApiVersion:l().optional(),azureIdentity:E().optional()}),Ac=f({id:l(),thinkingBudgetTokens:m().optional()}),xc=f({name:l(),baseModelId:l(),thinkingBudgetTokens:m().optional()}),Rc=f({models:w(Ac).optional(),customModels:w(xc).optional(),awsRegion:l().optional(),awsUseCrossRegionInference:E().optional(),awsUseGlobalInference:E().optional(),awsBedrockUsePromptCache:E().optional(),awsBedrockEndpoint:l().optional()}),Sc=f({id:l()}),Nc=f({models:w(Sc).optional()}),Oc=f({id:l(),thinkingBudgetTokens:m().optional()}),Mc=f({models:w(Oc).optional(),vertexProjectId:l().optional(),vertexRegion:l().optional()}),Pc=f({id:l(),thinkingBudgetTokens:m().optional(),promptCachingEnabled:E().optional()}),$c=f({models:w(Pc).optional(),baseUrl:l().optional()}),Lc=f({id:l(),thinkingBudgetTokens:m().optional()}),zc=f({models:w(Lc).optional(),baseUrl:l().optional()}),Dc=f({OpenAiCompatible:Cc.optional(),AwsBedrock:Rc.optional(),Cline:Nc.optional(),Vertex:Mc.optional(),LiteLLM:$c.optional(),Anthropic:zc.optional()}),Uc=f({id:l()}),Fc=f({name:l(),url:l(),alwaysEnabled:E().optional(),headers:z(l(),l()).optional()}),Mn=f({alwaysEnabled:E(),name:l(),contents:l()}),vt=f({bucket:l(),accessKeyId:l(),secretAccessKey:l(),region:l().optional(),endpoint:l().optional(),accountId:l().optional()}),Bc=f({enabled:E().optional(),type:Y([L("s3_access_keys"),L("r2_access_keys"),L("azure_access_keys")]).optional(),s3AccessSettings:vt.optional(),r2AccessSettings:vt.optional(),azureAccessSettings:vt.optional()}),jc=f({promptUploading:Bc.optional()}),Pp=f({version:l(),providerSettings:Dc.optional(),telemetryEnabled:E().optional(),kanbanEnabled:E().optional(),mcpMarketplaceEnabled:E().optional(),allowedMCPServers:w(Uc).optional(),remoteMCPServers:w(Fc).optional(),blockPersonalRemoteMCPServers:E().optional(),yoloModeAllowed:E().optional(),openTelemetryEnabled:E().optional(),openTelemetryMetricsExporter:l().optional(),openTelemetryLogsExporter:l().optional(),openTelemetryOtlpProtocol:l().optional(),openTelemetryOtlpEndpoint:l().optional(),openTelemetryOtlpHeaders:z(l(),l()).optional(),openTelemetryOtlpMetricsProtocol:l().optional(),openTelemetryOtlpMetricsEndpoint:l().optional(),openTelemetryOtlpMetricsHeaders:z(l(),l()).optional(),openTelemetryOtlpLogsProtocol:l().optional(),openTelemetryOtlpLogsEndpoint:l().optional(),openTelemetryOtlpLogsHeaders:z(l(),l()).optional(),openTelemetryMetricExportInterval:m().optional(),openTelemetryOtlpInsecure:E().optional(),openTelemetryLogBatchSize:m().optional(),openTelemetryLogBatchTimeout:m().optional(),openTelemetryLogMaxQueueSize:m().optional(),enterpriseTelemetry:jc.optional(),globalRules:w(Mn).optional(),globalWorkflows:w(Mn).optional()}),$p=z(l(),l());var Lp=_(["reasoning","prompt-cache","tools","provider-tools","oauth","temperature","files","streaming","vision","computer-use","local-auth","popular"]),zp=_(["anthropic","gemini","openai-chat","openai-responses","openai-r1","ai-sdk"]),Dp=_(["anthropic","ai-sdk","ai-sdk-community","openai","openai-compatible","openai-r1","gemini","bedrock","custom","fetch","vertex"]);var sr="task.provider_request_started",ar="task.provider_stream_started",lr="task.first_chunk_received",ur="task.provider_stream_failed",cr="task.cancelled";var ye=new Map;function qc(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 Hc(e){let t=Date.now(),n=ye.get(e);if(n&&t-n.startMs<3600000){if(n.emitted<5)return n.emitted+=1,{emit:!0,suppressed:0};return n.suppressed+=1,{emit:!1,suppressed:n.suppressed}}let i=n?.suppressed??0;if(ye.delete(e),ye.size>=512){let r=ye.keys().next();if(!r.done)ye.delete(r.value)}return ye.set(e,{startMs:t,emitted:1,suppressed:0}),{emit:!0,suppressed:i}}function dr(e,t){e?.capture({event:"agent.reasoning.unexpected_tokens",properties:zt({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 pr(e,t){if(!e)return;e.capture({event:t.event,properties:zt({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?{}:fr(t.error,t.messageLimit),error_class:t.errorClass})})}function hr(e,t){if(!e)return!1;let n=t.event??"sdk.error",i=Wc(t),r=0;try{let o=Hc(qc(n,i));if(!o.emit)return!0;r=o.suppressed}catch{}return e.capture({event:n,properties:r>0?{...i,suppressed_count:r}:i}),!0}function Wc(e){return zt({...e.context??{},component:e.component,operation:e.operation,severity:e.severity??"error",handled:e.handled??!0,...fr(e.error,e.messageLimit,e.errorMessage)})}function zt(e){let t={};for(let[n,i]of Object.entries(e))if(i!==void 0)t[n]=i;return t}function fr(e,t=500,n){let i=Gc(e)?e:void 0,r=e instanceof Error?e:void 0,o=Oe(n)??Oe(r?.message)??Oe(i?.message)??Kc(e)??"Unknown error",s=Jc(i?.code),a=bt(i?.status)??bt(i?.statusCode)??bt(i?.responseStatus);return{error_type:r?.name?.trim()||Oe(i?.name)||r?.constructor?.name||"Error",error_message:Zc(Vc(o),t),...s!==void 0?{error_code:s}:{},...a!==void 0?{error_status:a}:{}}}function Vc(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 Zc(e,t){let n=Math.max(1,Math.floor(t));return e.length>n?e.substring(0,n):e}function Gc(e){return typeof e==="object"&&e!==null}function Oe(e){return typeof e==="string"&&e.trim().length>0?e:void 0}function Kc(e){if(e instanceof Error)return;let t=typeof e==="string"?e:String(e);return t==="[object Object]"?void 0:Oe(t)}function Jc(e){if(typeof e==="string"&&e.trim().length>0)return e;if(typeof e==="number"&&Number.isFinite(e))return e;return}function bt(e){return typeof e==="number"&&Number.isFinite(e)?e:void 0}var Yc=["rules","skills","workflows","plugins","hooks"];var Up=new Set(Yc);var Xc=f({rootPath:l().min(1),hint:l().min(1).optional(),associatedRemoteUrls:w(l().min(1)).optional(),latestGitCommitHash:l().min(1).optional(),latestGitBranchName:l().min(1).optional()}),Fp=f({currentWorkspacePath:l().min(1).optional(),workspaces:z(l().min(1),Xc)});var Qc=["current_state","boundary_analysis","interface_proposal"];var X=ji((e)=>e instanceof Date?e.toISOString():e,l().datetime()),we=_(["pending","in_progress","blocked","completed"]),mr=_(["queued","running","completed","failed","cancelled","interrupted"]),lt=_(["draft","in_review","finalized"]),ed=f({agentId:l(),role:_(["lead","teammate"]),description:l().optional(),status:_(["idle","running","stopped"])}),Bp=f({agentId:l(),rolePrompt:l(),modelId:l().optional(),maxIterations:m().optional(),temperature:m().nonnegative().optional(),seed:m().int().optional(),seedRandom:E().optional(),temperatureBase:m().nonnegative().optional(),temperatureRange:m().min(0).max(100).optional()});function C(e){return ji((t)=>t===null?void 0:t,e.optional())}var jp=f({agentId:l().min(1).describe("Teammate identifier"),rolePrompt:l().min(1).describe("System prompt describing teammate role"),temperature:C(Y([m().nonnegative(),l()])).describe(`Sampling temperature for this teammate, over its model's own. "random": a draw within 2% of the model's own temperature (a model at 1.0 gets 0.98 to 1.02); that narrow band is the intended variation. Omit to keep the model's.`),seed:C(Y([m().int(),l()])).describe('Sampling seed for this teammate. "random" draws one. Omit to leave it unset.'),temperature_range:C(Y([m().min(0).max(100),l()])).describe("Percent the temperature is randomized by, around `temperature` or the model's own. Set it only when the user states a number; left out, 2 applies. Held to 10 at most.")}).strict(),qp=f({agentId:l().min(1).describe("Teammate identifier"),reason:C(l().min(1)).describe("Optional shutdown reason")}),Hp=f({}),gr={create:["title","description"],list:[],claim:["taskId"],complete:["taskId","summary"],block:["taskId","reason"]};var Wp=f({action:_(["create","list","claim","complete","block"]),title:C(l().min(1)).describe("Task title"),description:C(l().min(1)).describe("Task details"),dependsOn:C(w(l().describe("Dependency task ID"))).describe("Array of dependency task IDs"),assignee:C(l().min(1)).describe("Optional assignee"),status:C(_(["pending","in_progress","blocked","completed"])).describe("Optional task status filter"),taskId:C(l()).describe("Task ID"),summary:C(l().min(1)).describe("Completion summary"),reason:C(l().min(1)).describe("Blocking reason")}).superRefine((e,t)=>{for(let n of gr[e.action]){if(e[n]!==void 0)continue;t.addIssue({code:"custom",path:[n],message:`Field "${n}" is required when action=${e.action}`})}}),Vp=f({action:_(["list","claim","complete","block"]),status:C(_(["pending","in_progress","blocked","completed"])).describe("Optional task status filter"),assignee:C(l().min(1)).describe("Optional assignee filter"),taskId:C(l()).describe("Task ID"),summary:C(l().min(1)).describe("Completion summary"),reason:C(l().min(1)).describe("Blocking reason")}).superRefine((e,t)=>{for(let n of gr[e.action]){if(e[n]!==void 0)continue;t.addIssue({code:"custom",path:[n],message:`Field "${n}" is required when action=${e.action}`})}}),Zp=f({agentId:l().describe("Teammate agent ID"),task:l().min(1).describe("Task instructions for the teammate"),taskId:C(l()).describe("Optional shared task list ID"),runMode:C(_(["sync","async"])).describe("Execution mode: 'sync' blocks until the teammate finishes and returns the result (default if omitted); 'async' queues the run and returns a runId immediately — use team_await_runs to collect results later."),continueConversation:C(E()).describe("If true, continue the teammate conversation; otherwise start fresh")}),Gp=f({status:C(_(["queued","running","completed","failed","cancelled","interrupted"])).describe("Optional run status filter. Omit to include all statuses."),agentId:C(l().min(1)).describe("Optional teammate ID filter. Omit to include all teammates."),includeCompleted:C(E()).describe("Include completed/failed runs (default true)")}),Kp=f({runId:l().min(1).describe("Run ID"),reason:C(l().min(1)).describe("Optional cancellation reason")}),Jp=f({runId:C(l().min(1)).describe("Optional async run ID to await. Omit to wait for all active async runs.")}).strict(),Yp=f({toAgentId:l().min(1).describe("Recipient agent ID"),subject:l().min(1).describe("Message subject"),body:l().min(1).describe("Message body"),taskId:C(l().min(1)).describe("Optional task ID context")}),Xp=f({subject:l().min(1).describe("Message subject"),body:l().min(1).describe("Message body"),taskId:C(l().min(1)).describe("Optional task ID context")}),Qp=f({unreadOnly:C(E()).describe("Only unread messages for read action (default true)")}),eh=f({kind:_(["progress","handoff","blocked","decision","done","error"]),summary:l().min(1).describe("Update summary"),taskId:C(l().min(1)).describe("Optional task ID context"),evidence:C(w(l().min(1))).describe("Optional evidence links/snippets"),nextAction:C(l().min(1)).describe("Planned next step")}),th=f({}),nh=f({title:l().describe("Outcome title"),requiredSections:w(l()).default(Qc).describe("Required sections for finalization gate (defaults to current_state,boundary_analysis,interface_proposal)")}),ih=f({outcomeId:l().describe("Outcome ID"),section:l().describe("Section name"),sourceRunId:C(l()).describe("Optional source run ID"),content:l().describe("Section fragment content")}),rh=f({fragmentId:l().describe("Fragment ID"),approved:E().describe("Review decision")}),oh=f({outcomeId:l().describe("Outcome ID")}),sh=f({}),ah=f({teamId:l(),teamName:l(),members:w(ed),taskCounts:z(we,m()),unreadMessages:m(),missionLogEntries:m(),activeRuns:m(),queuedRuns:m(),outcomeCounts:z(lt,m())}),td=f({id:l(),title:l(),description:l(),status:we,createdAt:X,updatedAt:X,createdBy:l(),assignee:l().optional(),dependsOn:w(l()),summary:l().optional(),isReady:E(),blockedBy:w(l())}),lh=Ot("action",[f({action:L("create"),taskId:l(),status:we,ignoredFields:w(l()).optional(),note:l().optional()}),f({action:L("list"),tasks:w(td)}),f({action:L("claim"),taskId:l(),status:we,nextStep:l()}),f({action:L("complete"),taskId:l(),status:we}),f({action:L("block"),taskId:l(),status:we})]),uh=f({agentId:l(),mode:_(["sync","async"]),status:_(["dispatched","running","queued","joined"]),dispatched:E(),message:l(),deduped:E().optional(),runId:l().optional(),text:l().optional(),iterations:m().optional(),maxIterations:m().optional(),finishReason:l().optional(),stopReason:L("iteration_cap").optional()}),nd=f({textPreview:l(),text:l().optional(),iterations:m(),finishReason:l(),durationMs:m(),usage:f({inputTokens:m(),outputTokens:m(),cacheReadTokens:m().optional(),cacheWriteTokens:m().optional(),totalCost:m().optional()})}),ch=f({id:l(),agentId:l(),taskId:l().optional(),status:mr,messagePreview:l(),priority:m(),retryCount:m(),maxRetries:m(),nextAttemptAt:X.optional(),continueConversation:E().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:nd.optional()}),dh=f({id:l(),teamId:l(),fromAgentId:l(),toAgentId:l(),subject:l(),body:l(),taskId:l().optional(),sentAt:X,readAt:X.optional()}),ph=f({id:l(),teamId:l(),title:l(),status:lt,requiredSections:w(l()),createdBy:l(),createdAt:X,finalizedAt:X.optional()}),hh=f({outcomeId:l(),status:lt,requiredSections:w(l())}),fh=f({agentId:l(),status:l()}),mh=f({runId:l(),status:mr}),gh=f({id:l(),toAgentId:l()}),yh=f({delivered:m()}),vh=f({id:l()}),bh=f({status:l()}),Th=f({fragmentId:l(),status:l()}),wh=f({outcomeId:l(),status:lt}),id;((e)=>{e.TaskStart="task_start",e.TaskEnd="task_end",e.AgentEvent="agent_event",e.TeammateSpawned="teammate_spawned",e.TeammateShutdown="teammate_shutdown",e.TeamTaskUpdated="team_task_updated",e.TeamMessage="team_message",e.TeamMissionLog="team_mission_log",e.TeamTaskCompleted="team_task_completed",e.RunStarted="run_started",e.RunQueued="run_queued",e.RunProgress="run_progress",e.RunCompleted="run_completed",e.RunFailed="run_failed",e.RunCancelled="run_cancelled",e.RunInterrupted="run_interrupted",e.OutcomeCreated="outcome_created",e.OutcomeFragmentAttached="outcome_fragment_attached",e.OutcomeFragmentReviewed="outcome_fragment_reviewed",e.OutcomeFinalized="outcome_finalized",e.TeamCleaned="team_cleaned"})(id||={});function rd(e){let{$schema:t,...n}=e;if(typeof n.type==="string")return n;if("properties"in n||"required"in n||"additionalProperties"in n)return{type:"object",...n};for(let i of["oneOf","anyOf","allOf"]){let r=n[i];if(!Array.isArray(r)||r.length===0)continue;if(i==="allOf"){if(r.some((o)=>o&&typeof o==="object"&&o.type==="object"))return{type:"object",...n};throw Error('Tool inputSchema must describe an object at the top level, but the schema has a top-level "allOf" with no branch that asserts type: "object". Add type: "object" to at least one allOf branch to make the object constraint explicit.')}if(r.every((o)=>o&&typeof o==="object"&&o.type==="object"))return{type:"object",...n};throw Error(`Tool inputSchema must describe an object at the top level, but the schema has a top-level "${i}" whose branches include non-object types. Pass the strict object schema as inputSchema and reserve union/coercion schemas for use inside execute().`)}return n}function od(e){let t=rd(e.inputSchema instanceof R?Ec(e.inputSchema):e.inputSchema);return{name:e.name,resultPolicy:e.resultPolicy,description:e.description,inputSchema:t,...e.source?{source:e.source}:{},...e.readOnly?{readOnly:!0}:{},lifecycle:e.lifecycle,executionMode:e.executionMode,timeoutMs:e.timeoutMs??30000,retryable:e.retryable??!0,maxRetries:e.maxRetries??3,execute:e.execute}}var _h="Switch from plan mode to act mode. Switching to act mode immediately starts executing the plan, so only call this after the user has explicitly approved the plan in a message sent AFTER you presented it (e.g. 'looks good', 'go ahead', 'switch to act mode'). Never call this in the same turn you present a plan, never call it proactively, and never treat the original task request as approval. "+"Output: a one-line confirmation, as plain text. This call ends the current run and the next one starts in act mode with the file and command tools available, so it is a handover, not a failure — carry on with the plan there.";import{classifyProviderError as xr,createGateway as bd,isRetryableProviderError as Td}from"@cerebriline/llms";import{nanoid as wd}from"nanoid";function Dt(){return{reasoningDeltas:0,reasoningChars:0,textDeltas:0,textChars:0,toolInputChars:0}}var sd=12;function yr(e,t){let n=t.reduce((a,u)=>a+u,0);if(n<=0)return t.map(()=>0);let i=t.map((a)=>e*a/n),r=i.map(Math.floor),o=e-r.reduce((a,u)=>a+u,0),s=i.map((a,u)=>({index:u,rest:a-Math.floor(a)})).sort((a,u)=>u.rest-a.rest);for(let{index:a}of s){if(o<=0)break;r[a]=(r[a]??0)+1,o-=1}return r}function vr(e){let t=Math.floor(e.outputTokens??0);if(!(t>0))return;let{tally:n}=e,i=e.providerReasoningTokens??0;if(i>0){let c=Math.min(t,Math.floor(i)),[d=0,y=0]=yr(t-c,n.textChars+n.toolInputChars>0?[n.textChars,n.toolInputChars]:[1,0]);return{reasoningTokens:c,textTokens:d,toolInputTokens:y,method:"provider"}}let r=n.reasoningDeltas+n.textDeltas,o=n.reasoningChars+n.textChars;if(r>0&&r<=t&&o/r<=sd)return{reasoningTokens:n.reasoningDeltas,textTokens:n.textDeltas,toolInputTokens:t-r,method:"stream-chunks"};let[s=0,a=0,u=0]=yr(t,o+n.toolInputChars>0?[n.reasoningChars,n.textChars,n.toolInputChars]:[0,1,0]);return{reasoningTokens:s,textTokens:a,toolInputTokens:u,method:"chars-share"}}var ut={minChars:4000,window:60,maxPeriod:6,minCycles:20,maxUniqueInWindow:4,minLineChars:2000,phraseMaxPeriod:120,phraseMinCycles:12,maxConsecutiveTrips:3};function Ft(e){let t=`after ${e.chars.toLocaleString()} characters of reasoning`,n=e.sample?` Repeating: ${JSON.stringify(e.sample)}`:"";switch(e.kind){case"low-uniqueness":return`The model's reasoning collapsed into ${e.distinct} distinct lines over ${t}.${n}`;case"line-cycle":return`The model's reasoning repeated a ${e.period}-line block ${e.cycles} times ${t}.${n}`;case"phrase-cycle":return`The model's reasoning repeated a ${e.period}-character phrase ${e.cycles} times ${t}.${n}`}}function br(e){let t=[],n=(i,r)=>{if(typeof i==="string"){if(i)t.push(i)}else if(r<6&&Array.isArray(i))for(let o of i)n(o,r+1);else if(r<6&&i!==null&&typeof i==="object")for(let o of Object.values(i))n(o,r+1)};for(let i of e){if(i.role==="assistant")continue;for(let r of i.content)if(r.type==="text")n(r.text,0);else if(r.type==="tool-result")n(r.output,0)}return t.join(`
80
80
  `)}var ad=/^\d+\s*\|\s?/;function Ut(e){return e.trim().replace(ad,"").trim()}class ct{cfg;given;chars=0;lines=[];history=[];pending="";verdict=null;source;sourceRuns=new Map;constructor(e={},t={}){this.cfg={...ut,...e},this.given=t.given}get tripped(){return this.verdict}push(e){if(this.verdict||!e)return this.verdict;this.chars+=e.length,this.pending+=e;let t;while((t=this.pending.indexOf(`
81
81
  `))!==-1){let i=this.pending.slice(0,t).trim();if(this.pending=this.pending.slice(t+1),i){if(this.lines.push(i),this.lines.length>this.cfg.window)this.lines.shift();if(this.given)this.history.push(i)}}if(this.chars<this.cfg.minChars)return null;let n=this.detectLowUniqueness()??this.detectLineCycle()??this.detectPhraseCycle();if(n)this.verdict=n;return this.verdict}readSource(){if(!this.given)return;if(!this.source){let e="";try{e=this.given()}catch{}this.source={text:e,lines:e.split(`
82
82
  `).map(Ut).filter((t)=>t!=="")}}return this.source.text?this.source:void 0}remembered(e,t){let n=this.sourceRuns.get(e);if(n===void 0){if(n=t(),this.sourceRuns.size>512)this.sourceRuns.clear();this.sourceRuns.set(e,n)}return n}phraseRunInSource(e){let t=this.readSource();if(!t)return 0;return this.remembered(`p
@@ -85,15 +85,17 @@ ${n.join(`
85
85
  `)}`,()=>{let i=t.lines,r=n.length,o=0;for(let s=0;s+r<=i.length;s++){let a=0,u=s;while(u+r<=i.length){let c=!0;for(let d=0;d<r;d++)if(i[u+d]!==n[d]){c=!1;break}if(!c)break;a++,u+=r}if(a>o)o=a;if(a>1)s=u-r}return o})}stretchInSource(e){let t=this.readSource();if(!t)return 0;let n=new Set([...e].map(Ut));return this.remembered(`s
86
86
  ${[...n].sort().join(`
87
87
  `)}`,()=>{let i=0,r=0;for(let o of t.lines)if(r=n.has(o)?r+1:0,r>i)i=r;return i})}detectLowUniqueness(){if(this.lines.length<this.cfg.window)return null;let e=new Set(this.lines);if(e.size>this.cfg.maxUniqueInWindow)return null;if(this.given){let t=0;for(let n=this.history.length-1;n>=0&&e.has(this.history[n]);n--)t++;if(t-this.stretchInSource(e)<this.cfg.window)return null}return{kind:"low-uniqueness",distinct:e.size,chars:this.chars,sample:[...e].join(" / ").slice(0,160)}}detectLineCycle(){let e=this.lines.length;if(e<this.cfg.maxPeriod*2)return null;for(let t=1;t<=this.cfg.maxPeriod;t++){let n=0;for(let i=e-t;i-t>=0;i-=t){let r=!0;for(let o=0;o<t;o++)if(this.lines[i+o]!==this.lines[i-t+o]){r=!1;break}if(!r)break;n++}if(n>=this.cfg.minCycles){if(this.given){let i=this.history,r=1;for(let o=i.length-t;o-t>=0;o-=t){let s=!0;for(let a=0;a<t;a++)if(i[o+a]!==i[o-t+a]){s=!1;break}if(!s)break;r++}if(r<=this.blockRunInSource(this.lines.slice(e-t)))continue}return{kind:"line-cycle",period:t,cycles:n+1,chars:this.chars,sample:this.lines.slice(e-t).join(" / ").slice(0,160)}}}return null}detectPhraseCycle(){let e=this.pending;if(e.length<this.cfg.minLineChars)return null;for(let t=4;t<=this.cfg.phraseMaxPeriod;t++){let n=e.slice(e.length-t),i=0,r=e.length-t;while(r-t>=0&&e.startsWith(n,r-t))i++,r-=t;if(i>=this.cfg.phraseMinCycles){if(i+1<=this.phraseRunInSource(n))continue;return{kind:"phrase-cycle",period:t,cycles:i+1,chars:this.chars,sample:n.replace(/\s+/g," ").slice(0,160)}}}return null}}var fe={minChars:4000,minParagraphChars:60,minStopwords:3,maxRepeatTrip:4,duplicateFractionTrip:0.25,cooldownTurns:3,maxNudges:1,recoveryTokens:4000};var ld=/\b(the|is|are|to|and|of|it|that|this|be|for|but|so|if|will|need|should|let|now|then|because|actually|wait)\b/g;function ud(e,t){let n=e.trim();return((n.startsWith("```")?n.replace(/```[\s\S]*?```/g,""):n).toLowerCase().match(ld)??[]).length>=t}function dt(e,t=fe){if(e.length<t.minChars)return;let n=e.split(/\n\s*\n/).map((a)=>a.trim()).filter((a)=>a.length>=t.minParagraphChars&&ud(a,t.minStopwords));if(n.length===0)return;let i=new Map;for(let a of n)i.set(a,(i.get(a)??0)+1);let r=0,o=0,s="";for(let[a,u]of i)if(r+=u-1,u>o)o=u,s=a;return{paragraphs:n.length,duplicates:r,duplicateFraction:r/n.length,maxRepeat:o,sample:s}}function Tr(e,t){let n=[];for(let o=e.indexOf(t.sample);o>=0&&n.length<200;o=e.indexOf(t.sample,o+t.sample.length))n.push(Math.round(o/Math.max(1,e.length)*100));let i=t.sample.replace(/\s+/g," "),r=i.length>400?`${i.slice(0,400)} ...`:i;return`${e.length} chars; one passage ${t.maxRepeat} times; ${t.duplicates} of ${t.paragraphs} paragraphs repeat an earlier one; its copies begin at ${n.map((o)=>`${o}%`).join(", ")} of the turn; passage (${i.length} chars): ${JSON.stringify(r)}`}function pt(e,t=fe){if(!e)return!1;return e.maxRepeat>=t.maxRepeatTrip&&e.duplicateFraction>=t.duplicateFractionTrip}function wr(e){let t=e.sample.replace(/\s+/g," ").slice(0,200);return[`[SYSTEM] In your last reply you wrote this same passage ${e.maxRepeat} times, word for word:`,"",` "${t}${e.sample.length>200?"…":""}"`,"",`That reply restated ${e.duplicates} of its ${e.paragraphs} paragraphs verbatim. Re-deriving a conclusion you have already reached will not produce a new one, and none of that reasoning is visible to the user.`,"","You will not find it above: your reasoning from that turn is not carried into this request, so the passage is quoted here because it is the only copy you have. Take it as given rather than looking for it.","","Take the next concrete step instead: make the change, run the check, or say plainly what is blocking you and what you would need to get past it."].join(`
88
- `)}function Bt(e=fe){let t=0,n=Number.NEGATIVE_INFINITY,i=0,r=Math.max(0,e.recoveryTokens)*4;return{get spent(){return t},inspect(o,s){let a=dt(o,e);if(!(pt(a,e)&&!!a)){if(r>0&&t>0){if(i+=o.length,i>=r)t=0,i=0}return}if(t>=e.maxNudges)return;if(s-n<e.cooldownTurns)return;return t+=1,i=0,n=s,wr(a)}}}import{nanoid as cd}from"nanoid";class De{assemblies=new Map;nextIndex=0;add(e){let t=e.toolCallId??`tool_${e.index??this.nextIndex}`;if(e.index==null&&e.toolCallId==null)this.nextIndex+=1;let n=this.assemblies.get(t),i=n===void 0;if(!n)n={toolCallId:e.toolCallId??`tool_${cd(8)}`,inputText:""},this.assemblies.set(t,n);if(e.toolCallId)n.toolCallId=e.toolCallId;if(e.toolName)n.toolName=e.toolName;if(e.input!==void 0)n.inputValue=e.input;if(e.metadata!==void 0)n.metadata=_r(n.metadata,e.metadata);if(e.inputText)n.inputText=md(n.inputText,e.inputText);return{key:t,created:i}}get(e){return this.assemblies.get(e)}inputChars(){let e=0;for(let t of this.assemblies.values())e+=pd(t);return e}finish(e,t){let n=this.assemblies.get(e);if(!n?.toolName)return{invalid:{toolCallId:n?.toolCallId??e,input:ht(n?.inputText??""),reason:"missing_name"}};let i=hd(n,t),r={type:"tool-call",toolCallId:n.toolCallId,toolName:n.toolName,input:i.input,metadata:i.parseError?_r(n.metadata,{inputParseError:i.parseError,rawInputText:n.inputText}):n.metadata};return i.reason?{call:r,invalid:{toolCallId:n.toolCallId,toolName:n.toolName,input:i.invalidInput,reason:i.reason}}:{call:r}}}async function dd(e,t={}){let n=new De,i=[],r="",o="",s="unknown",a;for await(let f of e)switch(f.type){case"text-delta":{r+=f.text;let b=i.at(-1);if(b?.type==="part"&&b.part.type==="text")b.part.text+=f.text;else i.push({type:"part",part:{type:"text",text:f.text}});break}case"reasoning-delta":{o+=f.text;let b=i.at(-1);if(b?.type==="part"&&b.part.type==="reasoning")b.part.text+=f.text,b.part.redacted=f.redacted??b.part.redacted,b.part.metadata=f.metadata??b.part.metadata;else i.push({type:"part",part:{type:"reasoning",text:f.text,redacted:f.redacted,metadata:f.metadata}});break}case"tool-call-delta":{if(f.execution)break;let{key:b,created:w}=n.add(f);if(w)i.push({type:"tool",key:b});break}case"finish":{s=f.reason,a=f.error;break}}let u=new Map((t.tools??[]).map((f)=>[f.name,f.inputSchema])),c=[],d=[],y=[];for(let f of i){if(f.type==="part"){c.push(f.part);continue}let b=n.finish(f.key,s);if(b.invalid)y.push(b.invalid);if(!b.call)continue;if(c.push(b.call),b.invalid)continue;let w=u.get(b.call.toolName);d.push(w?{...b.call,input:Ce(b.call.input,w)}:b.call)}let g=d.length===0&&y.length===0?xe(r):void 0;return{content:c,toolCalls:d,invalidToolCalls:y,text:r,reasoning:o,finishReason:s,...g?{unparsedToolCall:g}:{},...a?{error:a}:{}}}function _r(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 pd(e){if(e.inputText)return e.inputText.length;if(e.inputValue===void 0)return 0;try{return JSON.stringify(e.inputValue)?.length??0}catch{return 0}}function hd(e,t){if(e.inputValue!==void 0)return{input:e.inputValue,invalidInput:ht(JSON.stringify(e.inputValue))};if(!e.inputText.trim())return{input:{},invalidInput:{}};let n=fd(e.inputText);if(n.ok)return{input:n.value,invalidInput:ht(e.inputText)};let r=t==="max-tokens"?`was cut off by the output budget before its arguments finished: the turn ended at the cap with ${e.inputText.length} characters of arguments written. Nothing is wrong with the payload you were writing -- there was no room left to finish it. Send the same work in smaller pieces: edit one region per call rather than rewriting the file, and keep each call's arguments short enough to complete.`:`emitted invalid JSON arguments: ${n.error}`;return{input:{},invalidInput:ht(e.inputText,n.error),parseError:`Tool call ${e.toolName??e.toolCallId} ${r}`,reason:"invalid_arguments"}}function ht(e,t){if(!e.trim())return{};return t?{rawInputText:e,parseError:t}:{rawInputText:e}}function fd(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 md(e,t){if(!e)return t;let n=t.trimStart();if(n.startsWith("{")||n.startsWith("["))return t;return e+t}var gd=2000,Er=!0;function yd(e){Er=e}function qt(){return Er}var jt="intent";function Ir(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function kr(e){if(e.length===0)return;let t=[...e].sort((n,i)=>i.length-n.length).map(Ir).join("|");return new RegExp(`[,{"'=>]\\s*(?:${t})["']?\\s*[:=><]`)}function vd(e){if(e.length===0)return;let t=[...e].sort((n,i)=>i.length-n.length).map(Ir).join("|");return new RegExp(`(?<![A-Za-z0-9_])(?:${t})(?![A-Za-z0-9_])`,"g")}class Ht{maxChars;calls=new Map;intentKey;otherKey;toolName;tailChars;constructor(e){this.maxChars=e?.maxChars??2000;let t=[...new Set(e?.argumentNames??[])].filter((i)=>i.length>0&&i!==jt);this.otherKey=kr(t),this.intentKey=this.otherKey?kr([jt]):void 0;let n=[...new Set(e?.toolNames??[])].filter((i)=>i.length>0);this.toolName=vd(n),this.tailChars=Math.max(jt.length,...t.map((i)=>i.length),...n.map((i)=>i.length))+8}push(e,t,n){if(!this.intentKey||!this.otherKey||t.length===0)return;let i=this.calls.get(e);if(!i)i={phase:"seeking",tail:"",chars:0},this.calls.set(e,i);if(n)i.toolName=n,i.named=!0;if(i.phase==="closed")return;let r=i.tail+t,o=t.length;if(i.phase==="seeking"){let s=this.intentKey.exec(r);if(!i.named&&this.toolName){let a=s?r.slice(0,s.index):r;for(let u of a.matchAll(this.toolName))i.toolName=u[0]}if(!s){i.tail=r.slice(-this.tailChars);return}i.phase="counting",r=r.slice(s.index+s[0].length),o=r.length}if(this.otherKey.test(r)){i.phase="closed",i.tail="";return}if(i.chars+=o,i.tail=r.slice(-this.tailChars),i.chars<=this.maxChars)return;return{toolCallId:e,...i.toolName?{toolName:i.toolName}:{},chars:i.chars,maxChars:this.maxChars}}}function Cr(e){return`(A call to ${e.toolName?`\`${e.toolName}\``:"a tool"} was begun here and cut before it was complete, so nothing ran. Its text is not kept.)`}function Ar(e){let t=e.toolName?`\`${e.toolName}\``:"a tool",n=e.maxChars.toLocaleString("en-US");return`[SYSTEM] Your call to ${t} was cut while you were writing it, and nothing ran. Its \`intent\` had passed ${n} characters. \`intent\` is one sentence saying what the call does. Decide what to do before you begin the call, then make the call again with \`intent\` as that one sentence.`}var _d=Boolean(globalThis.process?.env?.CLINE_TIMING);function kd(e){if(!_d)return;globalThis.process?.stderr?.write?.(`[timing] ${new Date().toISOString()} ${e}
89
- `)}var ft=32000;function Ed(e,t,n,i,r){let o=i,s="raw";if(!o.trim()){s="parsed";try{o=JSON.stringify(r)??""}catch{o=String(r)}}let a=o.replace(/\r?\n/g,"\\n"),u=Math.floor(ft*0.75),c=a.length<=ft?a:`${a.slice(0,u)} …[${a.length-ft} characters not logged]… ${a.slice(-(ft-u))}`;return`[tool-args] iter=${e} ${t} id=${n} ${s} chars=${a.length} ${c}`}var Id="Model reached the maximum output token limit before completing the turn",Cd=2,Ad=2000,xd="[an image was here; the vision model could not describe it, and this model cannot read images. Work from what the surrounding text says about it, or ask for the detail you need.]",Rd="[image omitted — this model does not accept image input; the text above is what the tool reported]";function Sd(e){let t=typeof e.image==="string"?e.image:e.data;if(typeof t==="string")return t.length>0?t:void 0;let n=e.image instanceof Uint8Array?e.image:e.image instanceof ArrayBuffer?new Uint8Array(e.image):void 0;if(!n||n.byteLength===0)return;return Buffer.from(n).toString("base64")}var Nd=8000,Rr="[SYSTEM] Your last reply hit the per-turn output limit before you finished, so it was discarded — none of it, including your reasoning, is in this conversation. "+"Do not try to reproduce it. Take the smallest useful next step instead: make one tool call, or write one short paragraph. If the work you were planning does not fit in one reply, do the part that fits, call the tools it needs, and continue in the next turn.",Od="And what that reasoning had established about the problem itself:",Md="Before it was discarded, your reasoning was condensed into the note below. It is what you had worked out when you ran out of room. Continue from it rather than repeating it. It is a record of your thinking, not an observation of the workspace: where it disagrees with a tool result in this conversation, the tool result is what is true and the note is out of date.",Pd="[SYSTEM] Your answer has been passed on. That message came in while you were working, so it did not replace the task you were given — "+"the work you were doing when it arrived is still unfinished. Take that work up again from where you left off, unless the message told you to change course or to stop.",$d="[SYSTEM] Your last reply ran out of room before any of it was delivered, so it was discarded — none of it, including your reasoning, is in this conversation. "+"Do not try to reproduce it. Take the smallest useful next step instead: make one tool call, or write one short paragraph. If the work you were planning does not fit in one reply, do the part that fits, call the tools it needs, and continue in the next turn.",Ld="[SYSTEM] Your last reply was thinking only: no answer and no tool call arrived. End your thinking, then either make one tool call or write your answer. Keep the thinking short.",zd="[SYSTEM] Your last reply ended inside your thinking: the tool call you wrote there was part of the thinking, so it never ran and nothing was changed by it. Close your thinking first, then send that one call again as an actual tool call. Keep the thinking short.",Sr=3,Dd=2,Ud=1024,Fd=/<\/?tool_call>|<\/function>|<function=|<\/parameter>/;function Bd(e){let t="";for(let n of e.content){if(n.type==="reasoning"){let i=n.text;t+=typeof i==="string"?i:"";continue}if(n.type==="text"){if(n.text?.trim())return;continue}return}return t.trim()?{toolCallInThinking:Fd.test(t)}:void 0}var jd="[SYSTEM] Your last tool call did not parse, so it never ran and nothing was changed by it. "+"The text you wrote before it is still here and still correct — the call around it was malformed, most often because it was cut short. "+"Send that one call again, complete, and nothing else in this reply. If it carries a large argument, make the argument smaller rather than sending the same one again: name a line range instead of a whole file, or split the work across two calls.";function qd(e){if(e?.reason!=="swallowed_key")return jd;let t=e.tool?`\`${e.tool}\` call`:"tool call",n=e.key?`ran on into \`${e.key}\`, so the parser read \`${e.key}\` and what followed as part of that value`:"ran on into the next argument, so the parser read that argument as part of the value";return`[SYSTEM] Your last ${t} was rejected before it ran, and nothing was changed by it. A string argument in it never closed: it ${n}. This happens when a string argument that contains code is ended with a character from that code, such as a backtick or a quote, instead of the tool-call format's own string delimiter. Send that one call again, complete, and nothing else in this reply, with every string argument closed by the format's delimiter.`}var Hd=2,Wd=1,$r=3,Lr=2000,Wt=3,Vd=1000,Zd=15000,Gd="Model returned no content because the response was blocked by a content filter. Retrying is unlikely to help — try rephrasing the request.",Kd="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.",Jd="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.",Yd="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 Se extends Error{constructor(e,t){super(t?.trim()?`${e} (provider reported: ${t.trim()})`:e);this.name="ContextWindowOverflowError"}}function me(e,t=8){return`${e}_${wd(t)}`}function Xd(e){return e.model!==void 0}function Qd(e){if(Xd(e))return e;let{providerId:t,modelId:n,apiKey:i,baseUrl:r,headers:o,options:s,...a}=e,c=bd({providerConfigs:[{providerId:t,apiKey:i,baseUrl:r,headers:o,options:s}],telemetry:a.telemetry}).createAgentModel({providerId:t,modelId:n}),d=a.messageModelInfo??{id:n,provider:t};return{...a,model:c,messageModelInfo:d}}function ep(e,t){return{...t?.["*"]??{},...t?.[e]??{}}}function Gt(e){try{return JSON.stringify(e).length}catch{return String(e).length}}function tp(e){if(typeof e==="string")return e.length;return Gt(e)}function np(e){let t=e.systemPrompt?.length??0,n=0,i=0,r=0;for(let o of e.messages)for(let s of o.content)switch(s.type){case"text":t+=s.text.length;break;case"reasoning":t+=s.text.length;break;case"file":t+=s.content.length;break;case"tool-call":t+=Gt(s.input);break;case"tool-result":{let a=tp(s.output);n+=1,i+=a,r=Math.max(r,a),t+=a;break}}return{messageCount:e.messages.length,toolSchemaCount:e.tools.length,systemPromptChars:e.systemPrompt?.length??0,requestJsonChars:Gt({systemPrompt:e.systemPrompt,messages:e.messages,tools:e.tools,options:e.options}),visibleTextChars:t,estimatedTextTokens:ir(t),toolResultCount:n,toolResultChars:i,maxToolResultChars:r}}class Kt extends Error{constructor(e){super(`Agent runtime exceeded maxIterations (${e})`);this.name="MaxIterationsReachedError"}}class mt extends Error{reason;constructor(e){super(e??"Run stopped by runtime control");this.name="ControlledStopError",this.reason=e}}class ge 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 Vt={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0};function ue(e,t,n){return{id:me("msg"),role:e,content:t,createdAt:Date.now(),metadata:n}}function ne(e){return{...e}}var ip={_:"__",'"':"_q_","<":"_lt_",">":"_gt_"};function Nr(e){return e.replace(/[_"<>]/g,(t)=>ip[t])}function Zt(e,t){let n=[`source="${e.source}"`];if("toolCall"in e)n.push(`tool_name="${Nr(e.toolCall.toolName)}"`,`tool_call_id="${Nr(e.toolCall.toolCallId)}"`);let i=t.trim().replace(/<(\/?)hook_context/gi,"<\\$1hook_context");return`<hook_context ${n.join(" ")}>
88
+ `)}function Bt(e=fe){let t=0,n=Number.NEGATIVE_INFINITY,i=0,r=Math.max(0,e.recoveryTokens)*4;return{get spent(){return t},inspect(o,s){let a=dt(o,e);if(!(pt(a,e)&&!!a)){if(r>0&&t>0){if(i+=o.length,i>=r)t=0,i=0}return}if(t>=e.maxNudges)return;if(s-n<e.cooldownTurns)return;return t+=1,i=0,n=s,wr(a)}}}import{nanoid as cd}from"nanoid";class ze{assemblies=new Map;nextIndex=0;add(e){let t=e.toolCallId??`tool_${e.index??this.nextIndex}`;if(e.index==null&&e.toolCallId==null)this.nextIndex+=1;let n=this.assemblies.get(t),i=n===void 0;if(!n)n={toolCallId:e.toolCallId??`tool_${cd(8)}`,inputText:""},this.assemblies.set(t,n);if(e.toolCallId)n.toolCallId=e.toolCallId;if(e.toolName)n.toolName=e.toolName;if(e.input!==void 0)n.inputValue=e.input;if(e.metadata!==void 0)n.metadata=_r(n.metadata,e.metadata);if(e.inputText)n.inputText=md(n.inputText,e.inputText);return{key:t,created:i}}get(e){return this.assemblies.get(e)}inputChars(){let e=0;for(let t of this.assemblies.values())e+=pd(t);return e}finish(e,t){let n=this.assemblies.get(e);if(!n?.toolName)return{invalid:{toolCallId:n?.toolCallId??e,input:ht(n?.inputText??""),reason:"missing_name"}};let i=hd(n,t),r={type:"tool-call",toolCallId:n.toolCallId,toolName:n.toolName,input:i.input,metadata:i.parseError?_r(n.metadata,{inputParseError:i.parseError,rawInputText:n.inputText}):n.metadata};return i.reason?{call:r,invalid:{toolCallId:n.toolCallId,toolName:n.toolName,input:i.invalidInput,reason:i.reason}}:{call:r}}}async function dd(e,t={}){let n=new ze,i=[],r="",o="",s="unknown",a;for await(let g of e)switch(g.type){case"text-delta":{r+=g.text;let T=i.at(-1);if(T?.type==="part"&&T.part.type==="text")T.part.text+=g.text;else i.push({type:"part",part:{type:"text",text:g.text}});break}case"reasoning-delta":{o+=g.text;let T=i.at(-1);if(T?.type==="part"&&T.part.type==="reasoning")T.part.text+=g.text,T.part.redacted=g.redacted??T.part.redacted,T.part.metadata=g.metadata??T.part.metadata;else i.push({type:"part",part:{type:"reasoning",text:g.text,redacted:g.redacted,metadata:g.metadata}});break}case"tool-call-delta":{if(g.execution)break;let{key:T,created:k}=n.add(g);if(k)i.push({type:"tool",key:T});break}case"finish":{s=g.reason,a=g.error;break}}let u=new Map((t.tools??[]).map((g)=>[g.name,g.inputSchema])),c=[],d=[],y=[];for(let g of i){if(g.type==="part"){c.push(g.part);continue}let T=n.finish(g.key,s);if(T.invalid)y.push(T.invalid);if(!T.call)continue;if(c.push(T.call),T.invalid)continue;let k=u.get(T.call.toolName);d.push(k?{...T.call,input:Ie(T.call.input,k)}:T.call)}let h=d.length===0&&y.length===0?Ae(r):void 0;return{content:c,toolCalls:d,invalidToolCalls:y,text:r,reasoning:o,finishReason:s,...h?{unparsedToolCall:h}:{},...a?{error:a}:{}}}function _r(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 pd(e){if(e.inputText)return e.inputText.length;if(e.inputValue===void 0)return 0;try{return JSON.stringify(e.inputValue)?.length??0}catch{return 0}}function hd(e,t){if(e.inputValue!==void 0)return{input:e.inputValue,invalidInput:ht(JSON.stringify(e.inputValue))};if(!e.inputText.trim())return{input:{},invalidInput:{}};let n=fd(e.inputText);if(n.ok)return{input:n.value,invalidInput:ht(e.inputText)};let r=t==="max-tokens"?`was cut off by the output budget before its arguments finished: the turn ended at the cap with ${e.inputText.length} characters of arguments written. Nothing is wrong with the payload you were writing -- there was no room left to finish it. Send the same work in smaller pieces: edit one region per call rather than rewriting the file, and keep each call's arguments short enough to complete.`:`emitted invalid JSON arguments: ${n.error}`;return{input:{},invalidInput:ht(e.inputText,n.error),parseError:`Tool call ${e.toolName??e.toolCallId} ${r}`,reason:"invalid_arguments"}}function ht(e,t){if(!e.trim())return{};return t?{rawInputText:e,parseError:t}:{rawInputText:e}}function fd(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 md(e,t){if(!e)return t;let n=t.trimStart();if(n.startsWith("{")||n.startsWith("["))return t;return e+t}var gd=2000,Er=!0;function yd(e){Er=e}function qt(){return Er}var jt="intent";function Ir(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function kr(e){if(e.length===0)return;let t=[...e].sort((n,i)=>i.length-n.length).map(Ir).join("|");return new RegExp(`[,{"'=>]\\s*(?:${t})["']?\\s*[:=><]`)}function vd(e){if(e.length===0)return;let t=[...e].sort((n,i)=>i.length-n.length).map(Ir).join("|");return new RegExp(`(?<![A-Za-z0-9_])(?:${t})(?![A-Za-z0-9_])`,"g")}class Ht{maxChars;calls=new Map;intentKey;otherKey;toolName;tailChars;constructor(e){this.maxChars=e?.maxChars??2000;let t=[...new Set(e?.argumentNames??[])].filter((i)=>i.length>0&&i!==jt);this.otherKey=kr(t),this.intentKey=this.otherKey?kr([jt]):void 0;let n=[...new Set(e?.toolNames??[])].filter((i)=>i.length>0);this.toolName=vd(n),this.tailChars=Math.max(jt.length,...t.map((i)=>i.length),...n.map((i)=>i.length))+8}push(e,t,n){if(!this.intentKey||!this.otherKey||t.length===0)return;let i=this.calls.get(e);if(!i)i={phase:"seeking",tail:"",chars:0},this.calls.set(e,i);if(n)i.toolName=n,i.named=!0;if(i.phase==="closed")return;let r=i.tail+t,o=t.length;if(i.phase==="seeking"){let s=this.intentKey.exec(r);if(!i.named&&this.toolName){let a=s?r.slice(0,s.index):r;for(let u of a.matchAll(this.toolName))i.toolName=u[0]}if(!s){i.tail=r.slice(-this.tailChars);return}i.phase="counting",r=r.slice(s.index+s[0].length),o=r.length}if(this.otherKey.test(r)){i.phase="closed",i.tail="";return}if(i.chars+=o,i.tail=r.slice(-this.tailChars),i.chars<=this.maxChars)return;return{toolCallId:e,...i.toolName?{toolName:i.toolName}:{},chars:i.chars,maxChars:this.maxChars}}}function Cr(e){return`(A call to ${e.toolName?`\`${e.toolName}\``:"a tool"} was begun here and cut before it was complete, so nothing ran. Its text is not kept.)`}function Ar(e){let t=e.toolName?`\`${e.toolName}\``:"a tool",n=e.maxChars.toLocaleString("en-US");return`[SYSTEM] Your call to ${t} was cut while you were writing it, and nothing ran. Its \`intent\` had passed ${n} characters. \`intent\` is one sentence saying what the call does. Decide what to do before you begin the call, then make the call again with \`intent\` as that one sentence.`}var _d=Boolean(globalThis.process?.env?.CLINE_TIMING);function kd(e){if(!_d)return;globalThis.process?.stderr?.write?.(`[timing] ${new Date().toISOString()} ${e}
89
+ `)}var ft=32000;function Ed(e,t,n,i,r){let o=i,s="raw";if(!o.trim()){s="parsed";try{o=JSON.stringify(r)??""}catch{o=String(r)}}let a=o.replace(/\r?\n/g,"\\n"),u=Math.floor(ft*0.75),c=a.length<=ft?a:`${a.slice(0,u)} …[${a.length-ft} characters not logged]… ${a.slice(-(ft-u))}`;return`[tool-args] iter=${e} ${t} id=${n} ${s} chars=${a.length} ${c}`}var Id="Model reached the maximum output token limit before completing the turn",Cd=2,Ad=2000,xd="[an image was here; the vision model could not describe it, and this model cannot read images. Work from what the surrounding text says about it, or ask for the detail you need.]",Rd="[image omitted — this model does not accept image input; the text above is what the tool reported]";function Sd(e){let t=typeof e.image==="string"?e.image:e.data;if(typeof t==="string")return t.length>0?t:void 0;let n=e.image instanceof Uint8Array?e.image:e.image instanceof ArrayBuffer?new Uint8Array(e.image):void 0;if(!n||n.byteLength===0)return;return Buffer.from(n).toString("base64")}var Nd=8000,Rr="[SYSTEM] Your last reply hit the per-turn output limit before you finished, so it was discarded — none of it, including your reasoning, is in this conversation. "+"Do not try to reproduce it. Take the smallest useful next step instead: make one tool call, or write one short paragraph. If the work you were planning does not fit in one reply, do the part that fits, call the tools it needs, and continue in the next turn.",Od="And what that reasoning had established about the problem itself:",Md="Before it was discarded, your reasoning was condensed into the note below. It is what you had worked out when you ran out of room. Continue from it rather than repeating it. It is a record of your thinking, not an observation of the workspace: where it disagrees with a tool result in this conversation, the tool result is what is true and the note is out of date.",Pd="[SYSTEM] Your answer has been passed on. That message came in while you were working, so it did not replace the task you were given — "+"the work you were doing when it arrived is still unfinished. Take that work up again from where you left off, unless the message told you to change course or to stop.",$d="[SYSTEM] Your last reply ran out of room before any of it was delivered, so it was discarded — none of it, including your reasoning, is in this conversation. "+"Do not try to reproduce it. Take the smallest useful next step instead: make one tool call, or write one short paragraph. If the work you were planning does not fit in one reply, do the part that fits, call the tools it needs, and continue in the next turn.",Ld="[SYSTEM] Your last reply was thinking only: no answer and no tool call arrived. End your thinking, then either make one tool call or write your answer. Keep the thinking short.",zd="[SYSTEM] Your last reply ended inside your thinking: the tool call you wrote there was part of the thinking, so it never ran and nothing was changed by it. Close your thinking first, then send that one call again as an actual tool call. Keep the thinking short.",Sr=3,Dd=2,Ud=1024,Fd=/<\/?tool_call>|<\/function>|<function=|<\/parameter>/;function Bd(e){let t="";for(let n of e.content){if(n.type==="reasoning"){let i=n.text;t+=typeof i==="string"?i:"";continue}if(n.type==="text"){if(n.text?.trim())return;continue}return}return t.trim()?{toolCallInThinking:Fd.test(t)}:void 0}var jd="[SYSTEM] Your last tool call did not parse, so it never ran and nothing was changed by it. "+"The text you wrote before it is still here and still correct — the call around it was malformed, most often because it was cut short. "+"Send that one call again, complete, and nothing else in this reply. If it carries a large argument, make the argument smaller rather than sending the same one again: name a line range instead of a whole file, or split the work across two calls.";function qd(e){if(e?.reason!=="swallowed_key")return jd;let t=e.tool?`\`${e.tool}\` call`:"tool call",n=e.key?`ran on into \`${e.key}\`, so the parser read \`${e.key}\` and what followed as part of that value`:"ran on into the next argument, so the parser read that argument as part of the value";return`[SYSTEM] Your last ${t} was rejected before it ran, and nothing was changed by it. A string argument in it never closed: it ${n}. This happens when a string argument that contains code is ended with a character from that code, such as a backtick or a quote, instead of the tool-call format's own string delimiter. Send that one call again, complete, and nothing else in this reply, with every string argument closed by the format's delimiter.`}var Hd=2,Wd=1,$r=3,Lr=2000,Wt=3,Vd=1000,Zd=15000,Gd="Model returned no content because the response was blocked by a content filter. Retrying is unlikely to help — try rephrasing the request.",Kd="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.",Jd="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.",Yd="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 Re extends Error{constructor(e,t){super(t?.trim()?`${e} (provider reported: ${t.trim()})`:e);this.name="ContextWindowOverflowError"}}function me(e,t=8){return`${e}_${wd(t)}`}function Xd(e){return e.model!==void 0}function Qd(e){if(Xd(e))return e;let{providerId:t,modelId:n,apiKey:i,baseUrl:r,headers:o,options:s,...a}=e,c=bd({providerConfigs:[{providerId:t,apiKey:i,baseUrl:r,headers:o,options:s}],telemetry:a.telemetry}).createAgentModel({providerId:t,modelId:n}),d=a.messageModelInfo??{id:n,provider:t};return{...a,model:c,messageModelInfo:d}}function ep(e,t){return{...t?.["*"]??{},...t?.[e]??{}}}function Gt(e){try{return JSON.stringify(e).length}catch{return String(e).length}}function tp(e){if(typeof e==="string")return e.length;return Gt(e)}function np(e){let t=e.systemPrompt?.length??0,n=0,i=0,r=0;for(let o of e.messages)for(let s of o.content)switch(s.type){case"text":t+=s.text.length;break;case"reasoning":t+=s.text.length;break;case"file":t+=s.content.length;break;case"tool-call":t+=Gt(s.input);break;case"tool-result":{let a=tp(s.output);n+=1,i+=a,r=Math.max(r,a),t+=a;break}}return{messageCount:e.messages.length,toolSchemaCount:e.tools.length,systemPromptChars:e.systemPrompt?.length??0,requestJsonChars:Gt({systemPrompt:e.systemPrompt,messages:e.messages,tools:e.tools,options:e.options}),visibleTextChars:t,estimatedTextTokens:ir(t),toolResultCount:n,toolResultChars:i,maxToolResultChars:r}}class Kt extends Error{constructor(e){super(`Agent runtime exceeded maxIterations (${e})`);this.name="MaxIterationsReachedError"}}class mt extends Error{reason;constructor(e){super(e??"Run stopped by runtime control");this.name="ControlledStopError",this.reason=e}}class ge 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 Vt={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0};function ue(e,t,n){return{id:me("msg"),role:e,content:t,createdAt:Date.now(),metadata:n}}function ne(e){return{...e}}var ip={_:"__",'"':"_q_","<":"_lt_",">":"_gt_"};function Nr(e){return e.replace(/[_"<>]/g,(t)=>ip[t])}function Zt(e,t){let n=[`source="${e.source}"`];if("toolCall"in e)n.push(`tool_name="${Nr(e.toolCall.toolName)}"`,`tool_call_id="${Nr(e.toolCall.toolCallId)}"`);let i=t.trim().replace(/<(\/?)hook_context/gi,"<\\$1hook_context");return`<hook_context ${n.join(" ")}>
90
90
  ${i}
91
- </hook_context>`}function Z(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 rp(e,t){let n=Math.max(0,(t.inputTokens??0)-(e.inputTokens??0)),i=Math.max(0,(t.outputTokens??0)-(e.outputTokens??0)),r=Math.max(0,(t.cacheReadTokens??0)-(e.cacheReadTokens??0)),o=Math.max(0,(t.cacheWriteTokens??0)-(e.cacheWriteTokens??0)),s=Math.max(0,(t.reasoningTokenCount??0)-(e.reasoningTokenCount??0)),a=e.totalCost??0,u=t.totalCost??0,c=Math.max(0,u-a);if(n===0&&i===0&&r===0&&o===0&&s===0&&c===0)return;return{inputTokens:n>0?n:0,outputTokens:i>0?i:0,cacheReadTokens:r>0?r:0,cacheWriteTokens:o>0?o:0,...s>0?{reasoningTokenCount:s}:{},...c>0?{cost:c}:{}}}function op(e){return e.options?.thinking===!1}function Re(e){if(!e)return"";return e.content.filter((t)=>t.type==="text").map((t)=>t.text).join("")}function Or(e){if(!e)return"";let t=[];for(let n of e.content){if(n.type!=="reasoning")continue;let i=n.text;if(typeof i==="string"&&i.length>0)t.push(i)}return t.join(`
91
+ </hook_context>`}function G(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 rp(e,t){let n=Math.max(0,(t.inputTokens??0)-(e.inputTokens??0)),i=Math.max(0,(t.outputTokens??0)-(e.outputTokens??0)),r=Math.max(0,(t.cacheReadTokens??0)-(e.cacheReadTokens??0)),o=Math.max(0,(t.cacheWriteTokens??0)-(e.cacheWriteTokens??0)),s=Math.max(0,(t.reasoningTokenCount??0)-(e.reasoningTokenCount??0)),a=e.totalCost??0,u=t.totalCost??0,c=Math.max(0,u-a);if(n===0&&i===0&&r===0&&o===0&&s===0&&c===0)return;return{inputTokens:n>0?n:0,outputTokens:i>0?i:0,cacheReadTokens:r>0?r:0,cacheWriteTokens:o>0?o:0,...s>0?{reasoningTokenCount:s}:{},...c>0?{cost:c}:{}}}function op(e){return e.options?.thinking===!1}function xe(e){if(!e)return"";return e.content.filter((t)=>t.type==="text").map((t)=>t.text).join("")}function Or(e){if(!e)return"";let t=[];for(let n of e.content){if(n.type!=="reasoning")continue;let i=n.text;if(typeof i==="string"&&i.length>0)t.push(i)}return t.join(`
92
92
 
93
- `)}function sp(e){if(!e)return 0;return e.content.reduce((t,n)=>{if(n.type!=="reasoning")return t;let i=n.text;return t+(typeof i==="string"?i.length:0)},0)}function Mr(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 ap(e){if(typeof e==="string")return[ue("user",[{type:"text",text:e}])];if(Array.isArray(e))return Z(e);return Z([e])}var lp=8;function up(e){if(e.toolExecution==="sequential")return 1;let t=e.maxParallelToolCalls;if(typeof t==="number"&&Number.isFinite(t))return Math.max(1,Math.floor(t));return lp}class Ue{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:ne(Vt),lastRequestTimings:void 0,lastError:void 0,lastErrorClass:void 0,lastRequestInputTokens:0,lastErrorRetryable:void 0,lastErrorReported:!1,lastFinishReason:void 0};lastToolCallRejection;overflowRecoveryAttempted=!1;lastRequestTokens;compactBeforeNextTurn=!1;imageRecoveryAttempted=!1;consecutiveNoToolCallNudges=0;noToolCallNudgeAsked=!1;calledToolThisRun=!1;stoppedForUserBy;hasCalledAnyTool=!1;consecutiveNoToolCallTurns=0;noToolCallStreakReasoningChars=0;nonConvergenceNudgeSpent=!1;lastNudgedUnreadableCall;intentNudgeSpent=!1;repetitionNudger;repetitionNudgerBuilt=!1;repetitionNudges=new WeakMap;announcedRepetitionRemoval=new WeakSet;unreadableCalls=new WeakMap;unreadableCallFingerprints=new WeakMap;steerAwaitingResume=!1;consecutiveMaxTokensRetries=0;toolCallParseRetries=0;thinkingOnlyRetries=0;truncatedOutputCapTokens;initialization;abortController;reasoningLoopStreak=0;pendingToolIntentNudge;lastIssuedRequest;toolIntentCutStreak=0;modelSteerController;telemetryProviderId;telemetryModelId;constructor(e){this.telemetryProviderId=B(e.messageModelInfo?.provider)??("providerId"in e?B(e.providerId):void 0),this.telemetryModelId=B(e.messageModelInfo?.id)??("modelId"in e?B(e.modelId):void 0);let t=Qd(e),n=up(t);this.config={...t,toolExecution:n>1?"parallel":"sequential",maxParallelToolCalls:n},this.state.agentId=t.agentId??me("agent"),this.state.agentRole=t.agentRole,this.state.parentAgentId=t.parentAgentId,this.state.messages=Z(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 ge?e:new ge(e);this.state.lastError=t.message,this.captureTaskLifecycle(cr,{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=ne(Vt),this.state.lastError=void 0,this.state.lastErrorClass=void 0,this.state.lastErrorRetryable=void 0,this.state.lastErrorReported=!1,this.state.messages=Z(e),this.config={...this.config,initialMessages:Z(e)}}snapshot(){let e=[...this.state.messages],t;return{agentId:this.state.agentId,agentRole:this.state.agentRole,parentAgentId:this.state.parentAgentId,conversationId:this.config.conversationId?.trim()||void 0,runId:this.state.runId,status:this.state.status,iteration:this.state.iteration,get messages(){return t??=Z(e),t},pendingToolCalls:[...this.state.pendingToolCalls],usage:ne(this.state.usage),lastError:this.state.lastError,lastErrorClass:this.state.lastErrorClass}}async ensureInitialized(){this.initialization??=this.initialize(),await this.initialization}async initialize(){this.registerHooks(this.config.hooks);for(let e of this.config.tools??[])this.tools.set(e.name,e);for(let e of this.config.plugins??[]){let t=await e.setup?.({agentId:this.state.agentId,agentRole:this.state.agentRole,systemPrompt:this.config.systemPrompt});for(let n of t?.tools??[])this.tools.set(n.name,n);this.registerHooks(t?.hooks)}}registerHooks(e){if(!e)return;if(e.beforeRun)this.hooks.beforeRun.push(e.beforeRun);if(e.afterRun)this.hooks.afterRun.push(e.afterRun);if(e.beforeModel)this.hooks.beforeModel.push(e.beforeModel);if(e.afterModel)this.hooks.afterModel.push(e.afterModel);if(e.beforeTool)this.hooks.beforeTool.push(e.beforeTool);if(e.afterTool)this.hooks.afterTool.push(e.afterTool);if(e.onEvent)this.hooks.onEvent.push(e.onEvent)}getRequiredCompletionToolNames(){if(this.config.completionPolicy?.requireCompletionTool!==!0)return[];return[...this.tools.values()].filter((e)=>e.lifecycle?.completesRun===!0).map((e)=>e.name).sort()}getCompletionToolReminderMessage(){let e=this.getRequiredCompletionToolNames();if(e.length===0)return;return`[SYSTEM] This run is not complete until you call one of these terminal completion tools: ${e.join(", ")}. Continue working if requirements are not met. If the task is complete, call the appropriate terminal completion tool now.`}async runCompletionBoundary(e,t=!1){let n=this.config.completionPolicy?.onCompletionAttempt;if(!n)return;let i=await n({text:e||void 0,forced:t});return i&&i.length>0?i:void 0}getCompletionReminderMessages(){let e=this.config.completionPolicy?.completionGuard?.();return{messages:[this.getCompletionToolReminderMessage(),e].filter((t)=>Boolean(t)),guardAsked:Boolean(e)}}async getNoToolCallNudgeMessage(e,t=!1,n){let i=this.config.completionPolicy?.maxNoToolCallNudges??0;if(this.consecutiveNoToolCallNudges>=i)return;let r=n??xe(e);if(r)return Pt(r);let o=await this.config.completionPolicy?.describeUnstartedWork?.();if(t&&!o)return;if(this.noToolCallNudgeAsked&&this.consecutiveNoToolCallNudges===0&&!o&&Xi(e))return;if(this.calledToolThisRun&&this.consecutiveNoToolCallNudges===0&&!this.noToolCallNudgeAsked&&!o&&(er(e)||this.stoppedForUserBy!==void 0&&tr(e)))return;if(this.config.completionPolicy?.strongNudges===!1&&!o&&!this.hasCalledAnyTool&&!at(e))return;let s=this.tools.has("ask_question")?Mt+Vi:Mt;return o?s+o:s}repetitionNudgeFor(e){if(!this.repetitionNudgerBuilt){this.repetitionNudgerBuilt=!0;let r=this.config.reasoningRepetition;this.repetitionNudger=r===!1?void 0:Bt({...fe,...r})}if(!e)return;let t=this.repetitionNudges.get(e);if(t)return t.nudge;let n=Or(e),i=n?this.repetitionNudger?.inspect(n,this.state.iteration):void 0;return this.repetitionNudges.set(e,{nudge:i}),i}replaceSpoiledContent(e){if(e.role!=="assistant")return;let t,n={kinds:[],removedChars:0},i=[...e.content],r=Or(e);if(r){this.repetitionNudgeFor(e);let c=e.metadata?.reasoningLoop,d=this.config.reasoningRepetition,y={...fe,...d||{}},g=d===!1?void 0:dt(r,y),f=c?"it collapsed into repeating itself and was cut":g&&pt(g,y)?`it repeated one passage ${g.maxRepeat} times`:void 0;if(f){let b=`[SYSTEM] The reasoning of this turn was removed: ${f}. Only what the turn did is kept.`,w=i.findIndex((j)=>j.type==="reasoning"),G=i.filter((j)=>j.type!=="reasoning");if(G.splice(Math.max(0,w),0,{type:"reasoning",text:b}),i.splice(0,i.length,...G),n.kinds.push("reasoning_loop"),n.removedChars+=r.length,!c&&g){let j=this.repetitionNudges.get(e)?.nudge;t=`the reasoning repeated one passage ${g.maxRepeat} times — removed from the conversation${j?", asking for a different approach":""}`}this.config.logger?.debug?.(`[reasoning-loop] iter=${this.state.iteration} removed: ${c?`${r.length} chars; cut while streaming (${c.kind}${c.cycles!==void 0?`, ${c.cycles} cycles`:""}); unit: ${JSON.stringify(c.sample.slice(0,400))}`:g?Tr(r,g):`${r.length} chars`}`)}}let o=i.some((c)=>c.type==="tool-call"),s=Re(e),a=o?void 0:xe(s);if(a){this.unreadableCalls.set(e,a),this.unreadableCallFingerprints.set(e,Pr(s));let c=i.findIndex((g)=>g.type==="text"),d=i.filter((g)=>g.type!=="text");d.splice(c<0?d.length:Math.min(c,d.length),0,{type:"text",text:Gi(a)}),i.splice(0,i.length,...d),n.kinds.push("unreadable_tool_call"),n.removedChars+=s.length;let y=(g)=>g.replace(/\s+/g," ");this.config.logger?.debug?.(`[unreadable-call] iter=${this.state.iteration} ${s.length} chars; begins: ${y(s.slice(0,400))}${s.length>700?` ...; ends: ${y(s.slice(-300))}`:""}`)}if(n.kinds.length===0)return;this.config.logger?.debug?.(`Replaced spoiled content in an assistant turn (${n.kinds.join(", ")}): ${n.removedChars} chars removed`);let u=e;return u.content=i,u.metadata={...e.metadata??{},spoiledTurn:n},t}nudgesEnabled(){return(this.config.completionPolicy?.maxNoToolCallNudges??0)>0}shouldNudgeNonConvergence(){if(this.nonConvergenceNudgeSpent||!this.nudgesEnabled())return!1;let e=this.config.completionPolicy?.noToolCallTurnStreakLimit??$r;return e>0&&this.consecutiveNoToolCallTurns>=e}turnProducedOutputTokens(e){return this.state.usage.outputTokens>e.outputTokens}continuationRoomTokens(){let e=this.state.lastRequestInputTokens,t=Lt(this.config.sessionId);if(!(e>0)||!t)return;if(t.contextWindow!==void 0)return Math.max(0,t.contextWindow-e-Ud);if(!t.maxTokens)return;let n=Math.max(e,t.estimatedInputTokens??0)+t.maxTokens;return Math.max(0,n-e)}async continueConversation(e,t){let n=await this.config.model.stream({...e,messages:[...e.messages,ue("user",[{type:"text",text:t.instruction}],{displayRole:"system"})],...this.abortController?{signal:this.abortController.signal}:{},options:{...e.options,maxTokens:t.maxTokens,toolChoice:"none"}}),i="";for await(let r of n)if(r.type==="text-delta")i+=r.text;else if(r.type==="usage")this.state.usage.inputTokens+=r.usage.inputTokens??0,this.state.usage.outputTokens+=r.usage.outputTokens??0;else if(r.type==="finish"&&r.reason==="error")throw Error(r.error??"the model call failed");return{text:i.trim()}}recoversTurnFault(e){if(!this.config.recoverTurnFault)return!1;let t=this.config.recoverTurnFaultKinds;return t===void 0||t.includes(e)}async noteDiscardedReasoning(e,t){let n=this.config.condenseDiscardedReasoning;if(!n){this.config.logger?.debug?.("Discarded turn not condensed: no condenser is installed");return}let i=e.content.filter((o)=>o.type==="reasoning"&&typeof o.text==="string").map((o)=>o.text).join("").trim(),r=e.content.filter((o)=>o.type==="text"&&typeof o.text==="string").map((o)=>o.text).join("").trim();if(this.config.logger?.log?.(`Discarded a turn cut off at the output limit: parts=[${e.content.map((o)=>o.type).join(", ")||"none"}] reasoning=${i.length} chars partialReply=${r.length} chars windowBound=${t}`,{severity:"info"}),!i&&!r){this.config.logger?.log?.(`Discarded turn had nothing to condense: parts=[${e.content.map((o)=>o.type).join(", ")||"none"}] contentLength=${e.content.length}`,{severity:"warn"});return}try{let o=this.lastIssuedRequest,s=this.continuationRoomTokens(),a=await n({reasoning:i,...r?{text:r}:{},windowBound:t,...o?{continueConversation:(d)=>this.continueConversation(o,d)}:{},...s!==void 0?{continuationRoomTokens:s}:{}}),u=a?.note?.trim(),c=a?.retrospective?.trim();if(!u&&!c){this.config.logger?.log?.(`Discarded turn was not condensed: the condenser returned nothing for ${i.length} chars of reasoning and ${r.length} chars of partial reply`,{severity:"warn"});return}return this.config.logger?.log?.(`Condensed ${i.length} chars of discarded reasoning into a ${u?.length??0}-char note and a ${c?.length??0}-char retrospective for the retry`,{severity:"info",reasoningChars:i.length,noteChars:u?.length??0,retrospectiveChars:c?.length??0}),{...u?{note:u}:{},...c?{retrospective:c}:{}}}catch(o){this.config.logger?.log?.("Could not condense the discarded reasoning; retrying without a note",{severity:"warn",errorMessage:o instanceof Error?o.message:String(o)});return}}getRetryOutputCap(){if(this.consecutiveMaxTokensRetries<1||this.truncatedOutputCapTokens===void 0)return;let e=Math.floor(this.truncatedOutputCapTokens/2**this.consecutiveMaxTokensRetries);return Math.max(Nd,e)}getMaxTokensRetryBudget(){let e=this.config.completionPolicy?.maxTruncatedTurnRetries;return typeof e==="number"&&Number.isFinite(e)?Math.max(0,Math.floor(e)):Cd}async addUserReminderMessage(e,t){let n=ue("user",[{type:"text",text:e}],{userRunSpan:0,displayRole:"system",...t??{}});return this.state.messages.push(n),await this.emit({type:"message-added",snapshot:this.snapshot(),message:n}),n}async execute(e){if(await this.ensureInitialized(),this.state.status==="running")throw Error("Agent runtime is already running");this.abortController=new AbortController,this.state.runId=me("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=ne(Vt),this.overflowRecoveryAttempted=!1,this.compactBeforeNextTurn=!1,this.imageRecoveryAttempted=!1,this.steerAwaitingResume=!1,this.noToolCallNudgeAsked=!1,this.calledToolThisRun=!1,this.stoppedForUserBy=void 0,this.state.lastRequestInputTokens=0,this.pendingHookContexts=[];try{await this.callBeforeRunHooks(),await this.emit({type:"run-started",snapshot:this.snapshot()});for(let i of e?ap(e):[])this.state.messages.push(i),await this.emit({type:"message-added",snapshot:this.snapshot(),message:i});let t=this.getCompletionToolReminderMessage();if(t)await this.addUserReminderMessage(t);await this.flushPendingHookContexts();let n;while(this.config.maxIterations===void 0||this.state.iteration<this.config.maxIterations){this.throwIfAborted(),this.state.iteration+=1,this.trace(`turn-begin iter=${this.state.iteration}`),await this.emit({type:"turn-started",snapshot:this.snapshot(),iteration:this.state.iteration});let i=ne(this.state.usage);this.resetLastError();let{message:r,finishReason:o,interrupted:s}=await this.generateAssistantMessageWithProviderRetry();if(s&&r.content.length===0){await this.emit({type:"turn-finished",snapshot:this.snapshot(),iteration:this.state.iteration,toolCallCount:0});continue}if(o==="aborted")throw this.normalizeAbortError();if(r.content.length===0){if(o!=="error"&&o!=="content-filter"&&this.turnProducedOutputTokens(i)&&this.consecutiveMaxTokensRetries<this.getMaxTokensRetryBudget()){this.consecutiveMaxTokensRetries+=1,await this.emit({type:"status-notice",snapshot:this.snapshot(),message:"the model produced nothing usable — retrying",metadata:{kind:"empty_turn_recovery",reason:"empty_turn_recovery",phase:"started",iteration:this.state.iteration,attempt:this.consecutiveMaxTokensRetries,finishReason:o}}),await this.addUserReminderMessage($d);continue}if(await this.recoverUnparsableToolCall())continue;if(o==="error")throw this.state.lastFinishReason=o,Error(this.state.lastError??"Model stream failed");if(!this.hasModelToolActivity(r)&&o!=="max-tokens"&&o!=="unknown")throw this.state.lastFinishReason=o,Error(o==="content-filter"?Gd:"Model returned empty response")}let a=r.content.filter((f)=>f.type==="tool-call");if(o==="max-tokens"&&a.length===0&&this.consecutiveMaxTokensRetries<this.getMaxTokensRetryBudget()){this.consecutiveMaxTokensRetries+=1;let f=Lt(this.config.sessionId);this.compactBeforeNextTurn=f?.windowBound??!0,this.truncatedOutputCapTokens=this.compactBeforeNextTurn?void 0:f?.maxTokens;let b=await this.noteDiscardedReasoning(r,this.compactBeforeNextTurn);await this.emit({type:"status-notice",snapshot:this.snapshot(),message:"output limit reached before the turn finished — retrying",metadata:{kind:"max_tokens_turn_recovery",reason:"max_tokens_turn_recovery",phase:"started",iteration:this.state.iteration,attempt:this.consecutiveMaxTokensRetries,maxAttempts:this.getMaxTokensRetryBudget(),outputCapSource:f?.source??"unknown",...typeof f?.maxTokens==="number"?{capTokens:f.maxTokens}:{},compacting:this.compactBeforeNextTurn}}),await this.addUserReminderMessage(b?[Rr,...b.note?[Md,b.note]:[],...b.retrospective?[Od,b.retrospective]:[]].join(`
93
+ `)}function sp(e){if(!e)return 0;return e.content.reduce((t,n)=>{if(n.type!=="reasoning")return t;let i=n.text;return t+(typeof i==="string"?i.length:0)},0)}function Mr(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 ap(e){if(typeof e==="string")return[ue("user",[{type:"text",text:e}])];if(Array.isArray(e))return G(e);return G([e])}var lp=8;function up(e){if(e.toolExecution==="sequential")return 1;let t=e.maxParallelToolCalls;if(typeof t==="number"&&Number.isFinite(t))return Math.max(1,Math.floor(t));return lp}class 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:ne(Vt),lastRequestTimings:void 0,lastError:void 0,lastErrorClass:void 0,lastRequestInputTokens:0,lastErrorRetryable:void 0,lastErrorReported:!1,lastFinishReason:void 0};lastToolCallRejection;overflowRecoveryAttempted=!1;lastRequestTokens;compactBeforeNextTurn=!1;imageRecoveryAttempted=!1;consecutiveNoToolCallNudges=0;noToolCallNudgeAsked=!1;calledToolThisRun=!1;stoppedForUserBy;hasCalledAnyTool=!1;consecutiveNoToolCallTurns=0;noToolCallStreakReasoningChars=0;nonConvergenceNudgeSpent=!1;lastNudgedUnreadableCall;intentNudgeSpent=!1;repetitionNudger;repetitionNudgerBuilt=!1;repetitionNudges=new WeakMap;announcedRepetitionRemoval=new WeakSet;unreadableCalls=new WeakMap;unreadableCallFingerprints=new WeakMap;steerAwaitingResume=!1;consecutiveMaxTokensRetries=0;toolCallParseRetries=0;thinkingOnlyRetries=0;truncatedOutputCapTokens;initialization;abortController;reasoningLoopStreak=0;pendingToolIntentNudge;lastIssuedRequest;toolIntentCutStreak=0;modelSteerController;telemetryProviderId;telemetryModelId;constructor(e){this.telemetryProviderId=B(e.messageModelInfo?.provider)??("providerId"in e?B(e.providerId):void 0),this.telemetryModelId=B(e.messageModelInfo?.id)??("modelId"in e?B(e.modelId):void 0);let t=Qd(e),n=up(t);this.config={...t,toolExecution:n>1?"parallel":"sequential",maxParallelToolCalls:n},this.state.agentId=t.agentId??me("agent"),this.state.agentRole=t.agentRole,this.state.parentAgentId=t.parentAgentId,this.state.messages=G(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 ge?e:new ge(e);this.state.lastError=t.message,this.captureTaskLifecycle(cr,{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=ne(Vt),this.state.lastError=void 0,this.state.lastErrorClass=void 0,this.state.lastErrorRetryable=void 0,this.state.lastErrorReported=!1,this.state.messages=G(e),this.config={...this.config,initialMessages:G(e)}}snapshot(){let e=[...this.state.messages],t;return{agentId:this.state.agentId,agentRole:this.state.agentRole,parentAgentId:this.state.parentAgentId,conversationId:this.config.conversationId?.trim()||void 0,runId:this.state.runId,status:this.state.status,iteration:this.state.iteration,get messages(){return t??=G(e),t},pendingToolCalls:[...this.state.pendingToolCalls],usage:ne(this.state.usage),lastError:this.state.lastError,lastErrorClass:this.state.lastErrorClass}}async ensureInitialized(){this.initialization??=this.initialize(),await this.initialization}async initialize(){this.registerHooks(this.config.hooks);for(let e of this.config.tools??[])this.tools.set(e.name,e);for(let e of this.config.plugins??[]){let t=await e.setup?.({agentId:this.state.agentId,agentRole:this.state.agentRole,systemPrompt:this.config.systemPrompt});for(let n of t?.tools??[])this.tools.set(n.name,n);this.registerHooks(t?.hooks)}}registerHooks(e){if(!e)return;if(e.beforeRun)this.hooks.beforeRun.push(e.beforeRun);if(e.afterRun)this.hooks.afterRun.push(e.afterRun);if(e.beforeModel)this.hooks.beforeModel.push(e.beforeModel);if(e.afterModel)this.hooks.afterModel.push(e.afterModel);if(e.beforeTool)this.hooks.beforeTool.push(e.beforeTool);if(e.afterTool)this.hooks.afterTool.push(e.afterTool);if(e.onEvent)this.hooks.onEvent.push(e.onEvent)}getRequiredCompletionToolNames(){if(this.config.completionPolicy?.requireCompletionTool!==!0)return[];return[...this.tools.values()].filter((e)=>e.lifecycle?.completesRun===!0).map((e)=>e.name).sort()}getCompletionToolReminderMessage(){let e=this.getRequiredCompletionToolNames();if(e.length===0)return;return`[SYSTEM] This run is not complete until you call one of these terminal completion tools: ${e.join(", ")}. Continue working if requirements are not met. If the task is complete, call the appropriate terminal completion tool now.`}async runCompletionBoundary(e,t=!1){let n=this.config.completionPolicy?.onCompletionAttempt;if(!n)return;let i=await n({text:e||void 0,forced:t});return i&&i.length>0?i:void 0}getCompletionReminderMessages(){let e=this.config.completionPolicy?.completionGuard?.();return{messages:[this.getCompletionToolReminderMessage(),e].filter((t)=>Boolean(t)),guardAsked:Boolean(e)}}async getNoToolCallNudgeMessage(e,t=!1,n){let i=this.config.completionPolicy?.maxNoToolCallNudges??0;if(this.consecutiveNoToolCallNudges>=i)return;let r=n??Ae(e);if(r)return Pt(r);let o=await this.config.completionPolicy?.describeUnstartedWork?.();if(t&&!o)return;if(this.noToolCallNudgeAsked&&this.consecutiveNoToolCallNudges===0&&!o&&Xi(e))return;if(this.calledToolThisRun&&this.consecutiveNoToolCallNudges===0&&!this.noToolCallNudgeAsked&&!o&&(er(e)||this.stoppedForUserBy!==void 0&&tr(e)))return;if(this.config.completionPolicy?.strongNudges===!1&&!o&&!this.hasCalledAnyTool&&!at(e))return;let s=this.tools.has("ask_question")?Mt+Vi:Mt;return o?s+o:s}repetitionNudgeFor(e){if(!this.repetitionNudgerBuilt){this.repetitionNudgerBuilt=!0;let r=this.config.reasoningRepetition;this.repetitionNudger=r===!1?void 0:Bt({...fe,...r})}if(!e)return;let t=this.repetitionNudges.get(e);if(t)return t.nudge;let n=Or(e),i=n?this.repetitionNudger?.inspect(n,this.state.iteration):void 0;return this.repetitionNudges.set(e,{nudge:i}),i}replaceSpoiledContent(e){if(e.role!=="assistant")return;let t,n={kinds:[],removedChars:0},i=[...e.content],r=Or(e);if(r){this.repetitionNudgeFor(e);let c=e.metadata?.reasoningLoop,d=this.config.reasoningRepetition,y={...fe,...d||{}},h=d===!1?void 0:dt(r,y),g=c?"it collapsed into repeating itself and was cut":h&&pt(h,y)?`it repeated one passage ${h.maxRepeat} times`:void 0;if(g){let T=`[SYSTEM] The reasoning of this turn was removed: ${g}. Only what the turn did is kept.`,k=i.findIndex((Z)=>Z.type==="reasoning"),H=i.filter((Z)=>Z.type!=="reasoning");if(H.splice(Math.max(0,k),0,{type:"reasoning",text:T}),i.splice(0,i.length,...H),n.kinds.push("reasoning_loop"),n.removedChars+=r.length,!c&&h){let Z=this.repetitionNudges.get(e)?.nudge;t=`the reasoning repeated one passage ${h.maxRepeat} times — removed from the conversation${Z?", asking for a different approach":""}`}this.config.logger?.debug?.(`[reasoning-loop] iter=${this.state.iteration} removed: ${c?`${r.length} chars; cut while streaming (${c.kind}${c.cycles!==void 0?`, ${c.cycles} cycles`:""}); unit: ${JSON.stringify(c.sample.slice(0,400))}`:h?Tr(r,h):`${r.length} chars`}`)}}let o=i.some((c)=>c.type==="tool-call"),s=xe(e),a=o?void 0:Ae(s);if(a){this.unreadableCalls.set(e,a),this.unreadableCallFingerprints.set(e,Pr(s));let c=i.findIndex((h)=>h.type==="text"),d=i.filter((h)=>h.type!=="text");d.splice(c<0?d.length:Math.min(c,d.length),0,{type:"text",text:Gi(a)}),i.splice(0,i.length,...d),n.kinds.push("unreadable_tool_call"),n.removedChars+=s.length;let y=(h)=>h.replace(/\s+/g," ");this.config.logger?.debug?.(`[unreadable-call] iter=${this.state.iteration} ${s.length} chars; begins: ${y(s.slice(0,400))}${s.length>700?` ...; ends: ${y(s.slice(-300))}`:""}`)}if(n.kinds.length===0)return;this.config.logger?.debug?.(`Replaced spoiled content in an assistant turn (${n.kinds.join(", ")}): ${n.removedChars} chars removed`);let u=e;return u.content=i,u.metadata={...e.metadata??{},spoiledTurn:n},t}nudgesEnabled(){return(this.config.completionPolicy?.maxNoToolCallNudges??0)>0}shouldNudgeNonConvergence(){if(this.nonConvergenceNudgeSpent||!this.nudgesEnabled())return!1;let e=this.config.completionPolicy?.noToolCallTurnStreakLimit??$r;return e>0&&this.consecutiveNoToolCallTurns>=e}turnProducedOutputTokens(e){return this.state.usage.outputTokens>e.outputTokens}continuationRoomTokens(){let e=this.state.lastRequestInputTokens,t=Lt(this.config.sessionId);if(!(e>0)||!t)return;if(t.contextWindow!==void 0)return Math.max(0,t.contextWindow-e-Ud);if(!t.maxTokens)return;let n=Math.max(e,t.estimatedInputTokens??0)+t.maxTokens;return Math.max(0,n-e)}async continueConversation(e,t){let n=await this.config.model.stream({...e,messages:[...e.messages,ue("user",[{type:"text",text:t.instruction}],{displayRole:"system"})],...this.abortController?{signal:this.abortController.signal}:{},options:{...e.options,maxTokens:t.maxTokens,toolChoice:"none"}}),i="";for await(let r of n)if(r.type==="text-delta")i+=r.text;else if(r.type==="usage")this.state.usage.inputTokens+=r.usage.inputTokens??0,this.state.usage.outputTokens+=r.usage.outputTokens??0;else if(r.type==="finish"&&r.reason==="error")throw Error(r.error??"the model call failed");return{text:i.trim()}}recoversTurnFault(e){if(!this.config.recoverTurnFault)return!1;let t=this.config.recoverTurnFaultKinds;return t===void 0||t.includes(e)}async noteDiscardedReasoning(e,t){let n=this.config.condenseDiscardedReasoning;if(!n){this.config.logger?.debug?.("Discarded turn not condensed: no condenser is installed");return}let i=e.content.filter((o)=>o.type==="reasoning"&&typeof o.text==="string").map((o)=>o.text).join("").trim(),r=e.content.filter((o)=>o.type==="text"&&typeof o.text==="string").map((o)=>o.text).join("").trim();if(this.config.logger?.log?.(`Discarded a turn cut off at the output limit: parts=[${e.content.map((o)=>o.type).join(", ")||"none"}] reasoning=${i.length} chars partialReply=${r.length} chars windowBound=${t}`,{severity:"info"}),!i&&!r){this.config.logger?.log?.(`Discarded turn had nothing to condense: parts=[${e.content.map((o)=>o.type).join(", ")||"none"}] contentLength=${e.content.length}`,{severity:"warn"});return}try{let o=this.lastIssuedRequest,s=this.continuationRoomTokens(),a=await n({reasoning:i,...r?{text:r}:{},windowBound:t,...o?{continueConversation:(d)=>this.continueConversation(o,d)}:{},...s!==void 0?{continuationRoomTokens:s}:{}}),u=a?.note?.trim(),c=a?.retrospective?.trim();if(!u&&!c){this.config.logger?.log?.(`Discarded turn was not condensed: the condenser returned nothing for ${i.length} chars of reasoning and ${r.length} chars of partial reply`,{severity:"warn"});return}return this.config.logger?.log?.(`Condensed ${i.length} chars of discarded reasoning into a ${u?.length??0}-char note and a ${c?.length??0}-char retrospective for the retry`,{severity:"info",reasoningChars:i.length,noteChars:u?.length??0,retrospectiveChars:c?.length??0}),{...u?{note:u}:{},...c?{retrospective:c}:{}}}catch(o){this.config.logger?.log?.("Could not condense the discarded reasoning; retrying without a note",{severity:"warn",errorMessage:o instanceof Error?o.message:String(o)});return}}getRetryOutputCap(){if(this.consecutiveMaxTokensRetries<1||this.truncatedOutputCapTokens===void 0)return;let e=Math.floor(this.truncatedOutputCapTokens/2**this.consecutiveMaxTokensRetries);return Math.max(Nd,e)}getMaxTokensRetryBudget(){let e=this.config.completionPolicy?.maxTruncatedTurnRetries;return typeof e==="number"&&Number.isFinite(e)?Math.max(0,Math.floor(e)):Cd}async addUserReminderMessage(e,t){let n=ue("user",[{type:"text",text:e}],{userRunSpan:0,displayRole:"system",...t??{}});return this.state.messages.push(n),await this.emit({type:"message-added",snapshot:this.snapshot(),message:n}),n}async execute(e){if(await this.ensureInitialized(),this.state.status==="running")throw Error("Agent runtime is already running");this.abortController=new AbortController,this.state.runId=me("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=ne(Vt),this.overflowRecoveryAttempted=!1,this.compactBeforeNextTurn=!1,this.imageRecoveryAttempted=!1,this.steerAwaitingResume=!1,this.noToolCallNudgeAsked=!1,this.calledToolThisRun=!1,this.stoppedForUserBy=void 0,this.state.lastRequestInputTokens=0,this.pendingHookContexts=[];try{await this.callBeforeRunHooks(),await this.emit({type:"run-started",snapshot:this.snapshot()});for(let i of e?ap(e):[])this.state.messages.push(i),await this.emit({type:"message-added",snapshot:this.snapshot(),message:i});let t=this.getCompletionToolReminderMessage();if(t)await this.addUserReminderMessage(t);await this.flushPendingHookContexts();let n;while(this.config.maxIterations===void 0||this.state.iteration<this.config.maxIterations){this.throwIfAborted(),this.state.iteration+=1,this.trace(`turn-begin iter=${this.state.iteration}`),await this.emit({type:"turn-started",snapshot:this.snapshot(),iteration:this.state.iteration});let i=ne(this.state.usage);this.resetLastError();let{message:r,finishReason:o,interrupted:s}=await this.generateAssistantMessageWithProviderRetry();if(s&&r.content.length===0){await this.emit({type:"turn-finished",snapshot:this.snapshot(),iteration:this.state.iteration,toolCallCount:0});continue}if(o==="aborted")throw this.normalizeAbortError();if(r.content.length===0){if(o!=="error"&&o!=="content-filter"&&this.turnProducedOutputTokens(i)&&this.consecutiveMaxTokensRetries<this.getMaxTokensRetryBudget()){this.consecutiveMaxTokensRetries+=1,await this.emit({type:"status-notice",snapshot:this.snapshot(),message:"the model produced nothing usable — retrying",metadata:{kind:"empty_turn_recovery",reason:"empty_turn_recovery",phase:"started",iteration:this.state.iteration,attempt:this.consecutiveMaxTokensRetries,finishReason:o}}),await this.addUserReminderMessage($d);continue}if(await this.recoverUnparsableToolCall())continue;if(o==="error")throw this.state.lastFinishReason=o,Error(this.state.lastError??"Model stream failed");if(!this.hasModelToolActivity(r)&&o!=="max-tokens"&&o!=="unknown")throw this.state.lastFinishReason=o,Error(o==="content-filter"?Gd:"Model returned empty response")}let a=r.content.filter((h)=>h.type==="tool-call");if(o==="max-tokens"&&a.length===0&&this.consecutiveMaxTokensRetries<this.getMaxTokensRetryBudget()){this.consecutiveMaxTokensRetries+=1;let h=Lt(this.config.sessionId);this.compactBeforeNextTurn=h?.windowBound??!0,this.truncatedOutputCapTokens=this.compactBeforeNextTurn?void 0:h?.maxTokens;let g=await this.noteDiscardedReasoning(r,this.compactBeforeNextTurn);await this.emit({type:"status-notice",snapshot:this.snapshot(),message:"output limit reached before the turn finished — retrying",metadata:{kind:"max_tokens_turn_recovery",reason:"max_tokens_turn_recovery",phase:"started",iteration:this.state.iteration,attempt:this.consecutiveMaxTokensRetries,maxAttempts:this.getMaxTokensRetryBudget(),outputCapSource:h?.source??"unknown",...typeof h?.maxTokens==="number"?{capTokens:h.maxTokens}:{},compacting:this.compactBeforeNextTurn}}),await this.addUserReminderMessage(g?[Rr,...g.note?[Md,g.note]:[],...g.retrospective?[Od,g.retrospective]:[]].join(`
94
94
 
95
- `):Rr,{noticeKind:"max_tokens_turn_recovery",attempt:this.consecutiveMaxTokensRetries,maxAttempts:this.getMaxTokensRetryBudget(),capSource:f?.source??"unknown",...typeof f?.maxTokens==="number"?{capTokens:f.maxTokens}:{},compacting:this.compactBeforeNextTurn});continue}if(n=r,await this.recordAssistantMessage(r,o),s){await this.emit({type:"turn-finished",snapshot:this.snapshot(),iteration:this.state.iteration,toolCallCount:0});continue}if(o==="unknown"&&a.length===0)throw this.state.lastFinishReason=o,Error("Model ended without a recognized finish reason");if(o==="max-tokens"&&a.length===0)throw this.state.lastFinishReason=o,Error(Id);if(o==="error"&&a.length===0){if(await this.recoverUnparsableToolCall())continue;throw this.state.lastFinishReason=o,Error(this.state.lastError??"Model stream failed")}if(this.toolCallParseRetries=0,this.state.pendingToolCalls=a.map((f)=>f.toolCallId),a.length===0){await this.emit({type:"turn-finished",snapshot:this.snapshot(),iteration:this.state.iteration,toolCallCount:0});let f=sp(r);if(f>=Lr)this.consecutiveNoToolCallTurns+=1,this.noToolCallStreakReasoningChars+=f;else this.consecutiveNoToolCallTurns=0,this.noToolCallStreakReasoningChars=0;if(this.steerAwaitingResume){this.steerAwaitingResume=!1,await this.addUserReminderMessage(Pd);continue}if(this.pendingToolIntentNudge){let F=this.pendingToolIntentNudge;this.pendingToolIntentNudge=void 0,await this.addUserReminderMessage(F);continue}let b=[],w=[],G=this.getCompletionReminderMessages();b.push(...G.messages);let j=Re(n),U=n?this.unreadableCalls.get(n):void 0,I=await this.getNoToolCallNudgeMessage(j,G.guardAsked,U);if(I)this.noToolCallNudgeAsked=!0,this.consecutiveNoToolCallNudges+=1,b.push(I),w.push({nudge:"no_tool_call",detail:{consecutive:this.consecutiveNoToolCallNudges}});let O=this.nudgesEnabled()?U??xe(j):void 0,ie=O?(n?this.unreadableCallFingerprints.get(n):void 0)??Pr(j??""):void 0;if(O&&ie!==this.lastNudgedUnreadableCall){this.lastNudgedUnreadableCall=ie;let F=Pt(O);if(!b.includes(F))b.push(F);w.push({nudge:"unparsed_tool_call"})}let re=this.intentNudgeSpent||!this.nudgesEnabled()?void 0:at(j);if(re)this.intentNudgeSpent=!0,b.push(Ki(re)),w.push({nudge:"announced_intent"});if(this.shouldNudgeNonConvergence())this.nonConvergenceNudgeSpent=!0,b.push(Zi(this.consecutiveNoToolCallTurns,this.noToolCallStreakReasoningChars)),w.push({nudge:"non_convergence",detail:{consecutiveNoToolCallTurns:this.consecutiveNoToolCallTurns,reasoningChars:this.noToolCallStreakReasoningChars}});let q=this.nudgesEnabled()?this.repetitionNudgeFor(r):void 0;if(q)b.push(q),w.push({nudge:"silent_repetition"});if(b.length>0){for(let F of new Set(b))await this.addUserReminderMessage(F);for(let F of w){if(F.nudge==="silent_repetition"&&this.announcedRepetitionRemoval.has(r))continue;await this.emit({type:"status-notice",snapshot:this.snapshot(),message:dp(F.nudge),metadata:{kind:"nudge",reason:"nudge",nudge:F.nudge,iteration:this.state.iteration,...F.detail??{}}})}continue}let ye=await this.runCompletionBoundary(Re(n),this.consecutiveNoToolCallNudges>0);if(ye){await this.addUserReminderMessage(ye);continue}let Y=r.metadata?.modelToolActivities||this.reasoningLoopStreak>0?void 0:Bd(r);if(Y&&this.thinkingOnlyRetries<Sr){this.thinkingOnlyRetries+=1,await this.emit({type:"status-notice",snapshot:this.snapshot(),message:Y.toolCallInThinking?"the model wrote its tool call inside its thinking — asking for it again":"the model's turn was thinking only — asking for an answer",metadata:{kind:"thinking_only_recovery",reason:"thinking_only_recovery",phase:"started",iteration:this.state.iteration,attempt:this.thinkingOnlyRetries,maxAttempts:Sr,toolCallInThinking:Y.toolCallInThinking}}),await this.addUserReminderMessage(Y.toolCallInThinking?zd:Ld);continue}let oe=this.finishRun("completed",n);return await this.callAfterRunHooks(oe),await this.emit({type:"run-finished",snapshot:this.snapshot(),result:oe}),oe}this.hasCalledAnyTool=!0,this.calledToolThisRun=!0,this.consecutiveNoToolCallNudges=0,this.thinkingOnlyRetries=0,this.consecutiveNoToolCallTurns=0,this.noToolCallStreakReasoningChars=0,this.consecutiveMaxTokensRetries=0,this.truncatedOutputCapTokens=void 0;let u=Date.now();this.trace(`tools-begin iter=${this.state.iteration} n=${a.length} ${a.map((f)=>f.toolName).join(",")}`);let c=await this.executeToolCalls(a);this.trace(`tools-end iter=${this.state.iteration} took=${Date.now()-u}ms`),this.state.pendingToolCalls=[];for(let f of c)this.state.messages.push(f),await this.emit({type:"message-added",snapshot:this.snapshot(),message:f});if(o==="unknown"&&!c.some((f)=>f.content.some((b)=>b.type==="tool-result"&&!b.isError)))throw this.state.lastFinishReason=o,Error("Model ended without a recognized finish reason or successful tool work");await this.flushPendingHookContexts(),await this.emit({type:"turn-finished",snapshot:this.snapshot(),iteration:this.state.iteration,toolCallCount:a.length});let d=this.findCompletingToolMessage(a,c);if(d){let f=await this.runCompletionBoundary(Mr(d)||Re(n));if(f){await this.addUserReminderMessage(f);continue}let b=this.finishRun("completed",n,Mr(d)||void 0);return await this.callAfterRunHooks(b),await this.emit({type:"run-finished",snapshot:this.snapshot(),result:b}),b}let y=this.repetitionNudgeFor(n);if(y)await this.addUserReminderMessage(y);let g=this.config.completionPolicy?.afterToolsReminder?.();if(g)await this.addUserReminderMessage(g);if(this.pendingToolIntentNudge){let f=this.pendingToolIntentNudge;this.pendingToolIntentNudge=void 0,await this.addUserReminderMessage(f)}}throw new Kt(this.config.maxIterations)}catch(t){let n=t instanceof Error?t:Error(String(t)),i=n instanceof mt,o=this.abortController.signal.aborted||i?"aborted":"failed",s=n instanceof Se?"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??me("run"),status:o,iterations:this.state.iteration,outputText:Re(u),messages:Z(this.state.messages),usage:ne(this.state.usage),error:o==="failed"?n:void 0,abortReason:o==="aborted"?n.message:void 0,...o==="failed"&&n instanceof Kt?{limit:"max_iterations"}:{}};if(this.config.logger?.log?.(`Agent loop caught error (${o}): ${n.name}: ${n.message}`,{severity:o==="failed"?"error":"warn",agentId:this.state.agentId,agentRole:this.state.agentRole,runId:c.runId,status:o,iteration:this.state.iteration,errorName:n.name,errorMessage:n.message,assistantContentPartCount:u?.content.length??0}),await this.callAfterRunHooks(c),o==="failed")await this.emit({type:"run-failed",snapshot:this.snapshot(),error:n,errorClass:s});else await this.emit({type:"run-finished",snapshot:this.snapshot(),result:c});return c}finally{this.abortController=void 0}}async flushPendingHookContexts(){if(this.pendingHookContexts.length===0)return;let e=this.pendingHookContexts.join(`
95
+ `):Rr,{noticeKind:"max_tokens_turn_recovery",attempt:this.consecutiveMaxTokensRetries,maxAttempts:this.getMaxTokensRetryBudget(),capSource:h?.source??"unknown",...typeof h?.maxTokens==="number"?{capTokens:h.maxTokens}:{},compacting:this.compactBeforeNextTurn});continue}if(n=r,await this.recordAssistantMessage(r,o),s){await this.emit({type:"turn-finished",snapshot:this.snapshot(),iteration:this.state.iteration,toolCallCount:0});continue}if(o==="unknown"&&a.length===0)throw this.state.lastFinishReason=o,Error("Model ended without a recognized finish reason");if(o==="max-tokens"&&a.length===0)throw this.state.lastFinishReason=o,Error(Id);if(o==="error"&&a.length===0){if(await this.recoverUnparsableToolCall())continue;throw this.state.lastFinishReason=o,Error(this.state.lastError??"Model stream failed")}if(this.toolCallParseRetries=0,this.state.pendingToolCalls=a.map((h)=>h.toolCallId),a.length===0){await this.emit({type:"turn-finished",snapshot:this.snapshot(),iteration:this.state.iteration,toolCallCount:0});let h=sp(r);if(h>=Lr)this.consecutiveNoToolCallTurns+=1,this.noToolCallStreakReasoningChars+=h;else this.consecutiveNoToolCallTurns=0,this.noToolCallStreakReasoningChars=0;if(this.steerAwaitingResume){this.steerAwaitingResume=!1,await this.addUserReminderMessage(Pd);continue}if(this.pendingToolIntentNudge){let F=this.pendingToolIntentNudge;this.pendingToolIntentNudge=void 0,await this.addUserReminderMessage(F);continue}let g=[],T=[],k=this.getCompletionReminderMessages();g.push(...k.messages);let H=xe(n),Z=n?this.unreadableCalls.get(n):void 0,U=await this.getNoToolCallNudgeMessage(H,k.guardAsked,Z);if(U)this.noToolCallNudgeAsked=!0,this.consecutiveNoToolCallNudges+=1,g.push(U),T.push({nudge:"no_tool_call",detail:{consecutive:this.consecutiveNoToolCallNudges}});let I=this.nudgesEnabled()?Z??Ae(H):void 0,M=I?(n?this.unreadableCallFingerprints.get(n):void 0)??Pr(H??""):void 0;if(I&&M!==this.lastNudgedUnreadableCall){this.lastNudgedUnreadableCall=M;let F=Pt(I);if(!g.includes(F))g.push(F);T.push({nudge:"unparsed_tool_call"})}let ie=this.intentNudgeSpent||!this.nudgesEnabled()?void 0:at(H);if(ie)this.intentNudgeSpent=!0,g.push(Ki(ie)),T.push({nudge:"announced_intent"});if(this.shouldNudgeNonConvergence())this.nonConvergenceNudgeSpent=!0,g.push(Zi(this.consecutiveNoToolCallTurns,this.noToolCallStreakReasoningChars)),T.push({nudge:"non_convergence",detail:{consecutiveNoToolCallTurns:this.consecutiveNoToolCallTurns,reasoningChars:this.noToolCallStreakReasoningChars}});let re=this.nudgesEnabled()?this.repetitionNudgeFor(r):void 0;if(re)g.push(re),T.push({nudge:"silent_repetition"});if(g.length>0){for(let F of new Set(g))await this.addUserReminderMessage(F);for(let F of T){if(F.nudge==="silent_repetition"&&this.announcedRepetitionRemoval.has(r))continue;await this.emit({type:"status-notice",snapshot:this.snapshot(),message:dp(F.nudge),metadata:{kind:"nudge",reason:"nudge",nudge:F.nudge,iteration:this.state.iteration,...F.detail??{}}})}continue}let j=await this.runCompletionBoundary(xe(n),this.consecutiveNoToolCallNudges>0);if(j){await this.addUserReminderMessage(j);continue}let oe=r.metadata?.modelToolActivities||this.reasoningLoopStreak>0?void 0:Bd(r);if(oe&&this.thinkingOnlyRetries<Sr){this.thinkingOnlyRetries+=1,await this.emit({type:"status-notice",snapshot:this.snapshot(),message:oe.toolCallInThinking?"the model wrote its tool call inside its thinking — asking for it again":"the model's turn was thinking only — asking for an answer",metadata:{kind:"thinking_only_recovery",reason:"thinking_only_recovery",phase:"started",iteration:this.state.iteration,attempt:this.thinkingOnlyRetries,maxAttempts:Sr,toolCallInThinking:oe.toolCallInThinking}}),await this.addUserReminderMessage(oe.toolCallInThinking?zd:Ld);continue}let Q=this.finishRun("completed",n);return await this.callAfterRunHooks(Q),await this.emit({type:"run-finished",snapshot:this.snapshot(),result:Q}),Q}this.hasCalledAnyTool=!0,this.calledToolThisRun=!0,this.consecutiveNoToolCallNudges=0,this.thinkingOnlyRetries=0,this.consecutiveNoToolCallTurns=0,this.noToolCallStreakReasoningChars=0,this.consecutiveMaxTokensRetries=0,this.truncatedOutputCapTokens=void 0;let u=Date.now();this.trace(`tools-begin iter=${this.state.iteration} n=${a.length} ${a.map((h)=>h.toolName).join(",")}`);let c=await this.executeToolCalls(a);this.trace(`tools-end iter=${this.state.iteration} took=${Date.now()-u}ms`),this.state.pendingToolCalls=[];let d=this.findCompletingToolMessage(a,c)?[]:this.attachTurnNotes(c,n);for(let h of c)this.state.messages.push(h),await this.emit({type:"message-added",snapshot:this.snapshot(),message:h});if(o==="unknown"&&!c.some((h)=>h.content.some((g)=>g.type==="tool-result"&&!g.isError)))throw this.state.lastFinishReason=o,Error("Model ended without a recognized finish reason or successful tool work");await this.flushPendingHookContexts(),await this.emit({type:"turn-finished",snapshot:this.snapshot(),iteration:this.state.iteration,toolCallCount:a.length});let y=this.findCompletingToolMessage(a,c);if(y){let h=await this.runCompletionBoundary(Mr(y)||xe(n));if(h){await this.addUserReminderMessage(h);continue}let g=this.finishRun("completed",n,Mr(y)||void 0);return await this.callAfterRunHooks(g),await this.emit({type:"run-finished",snapshot:this.snapshot(),result:g}),g}for(let h of d)await this.addUserReminderMessage(h)}throw new Kt(this.config.maxIterations)}catch(t){let n=t instanceof Error?t:Error(String(t)),i=n instanceof mt,o=this.abortController.signal.aborted||i?"aborted":"failed",s=n instanceof Re?"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??me("run"),status:o,iterations:this.state.iteration,outputText:xe(u),messages:G(this.state.messages),usage:ne(this.state.usage),error:o==="failed"?n:void 0,abortReason:o==="aborted"?n.message:void 0,...o==="failed"&&n instanceof Kt?{limit:"max_iterations"}:{}};if(this.config.logger?.log?.(`Agent loop caught error (${o}): ${n.name}: ${n.message}`,{severity:o==="failed"?"error":"warn",agentId:this.state.agentId,agentRole:this.state.agentRole,runId:c.runId,status:o,iteration:this.state.iteration,errorName:n.name,errorMessage:n.message,assistantContentPartCount:u?.content.length??0}),await this.callAfterRunHooks(c),o==="failed")await this.emit({type:"run-failed",snapshot:this.snapshot(),error:n,errorClass:s});else await this.emit({type:"run-finished",snapshot:this.snapshot(),result:c});return c}finally{this.abortController=void 0}}async flushPendingHookContexts(){if(this.pendingHookContexts.length===0)return;let e=this.pendingHookContexts.join(`
96
96
 
97
- `);this.pendingHookContexts=[];let t=ue("user",[{type:"text",text:e}],{userRunSpan:0,displayRole:"system"}),n=this.state.messages.at(-1);if(n?.role==="assistant"&&n.content.some((r)=>r.type==="tool-call"))this.state.messages.splice(-1,0,t);else this.state.messages.push(t);await this.emit({type:"message-added",snapshot:this.snapshot(),message:t})}async callBeforeRunHooks(){for(let e of this.hooks.beforeRun){let t=await e({snapshot:this.snapshot()});if(this.applyStopControl(t),t?.appendContext?.trim())this.pendingHookContexts.push(Zt({source:"RunStart"},t.appendContext))}}async callAfterRunHooks(e){for(let t of this.hooks.afterRun)await t({snapshot:this.snapshot(),result:e})}async generateAssistantMessageRecoveringFaults(){for(let e=1;;e+=1){let t,n,i=!1;try{t=await this.withProviderErrorRetry(()=>this.generateAssistantMessageWithOverflowRecovery())}catch(g){if(this.abortController?.signal.aborted||g instanceof mt||g instanceof Se||g instanceof ge)throw g;n=g,i=!0}let r=this.config.recoverTurnFault,o=()=>{if(i)throw n;return t};if(!r)return o();let s,a,u;if(i)s=It(n),a=n instanceof Error?n.message:String(n),u=Pe(n);else if(t?.finishReason==="error")a=this.state.lastError??"",s=ke(a,this.state.lastErrorClass),u=$n(a,this.state.lastErrorClass);else return o();if(!s||!this.recoversTurnFault(s))return o();let c=B(this.config.sessionId),d=this.lastRequestTokens;if(u)this.config.logger?.log?.(`Engine bug: the server evicted session ${c??"(unnamed)"} (agent ${this.state.agentId}) at ${new Date().toISOString()}, holding ${d!==void 0?`${d.toLocaleString("en-US")} tokens (its last completed request)`:"an unknown number of tokens (no request had completed)"}, turn ${this.state.iteration}, attempt ${e}: ${a}; waiting to send it again`,{severity:"warn",kind:"engine_eviction",...c?{sessionId:c}:{},agentId:this.state.agentId,...d!==void 0?{tokensHeld:d}:{},iteration:this.state.iteration,attempt:e});else this.config.logger?.log?.(s==="refusal"?`Turn ${this.state.iteration} queued by the server (retry ${e}): ${Ln(a)}; waiting to send it again`:`Turn ${this.state.iteration} failed on a ${s} fault (attempt ${e}): ${a}; waiting to send it again`,{severity:s==="refusal"?"info":"warn"});await this.emit({type:"status-notice",snapshot:this.snapshot(),message:u?"the server evicted the turn to keep others alive (an engine bug) — waiting, then retrying":s==="transport"?"the server dropped the turn — waiting for it to come back, then retrying":"the server queued the turn — waiting for room, then retrying",metadata:{kind:"turn_fault_recovery",reason:s,...u?{evicted:!0}:{},phase:"started",iteration:this.state.iteration,attempt:e,providerError:a}});let y=!1;try{y=await r({kind:s,message:a,attempt:e,iteration:this.state.iteration,...u?{evicted:!0}:{},...u&&d!==void 0?{tokensHeld:d}:{},...c?{sessionId:c}:{},...this.abortController?.signal?{signal:this.abortController.signal}:{}})}catch{y=!1}if(this.throwIfAborted(),!y)return o()}}async generateAssistantMessageWithProviderRetry(){let e=()=>this.generateAssistantMessageRecoveringFaults(),t=await e();if(t.finishReason!=="unknown"||t.interrupted)return t;if(t.message.content.some((n)=>n.type==="tool-call")||this.hasModelToolActivity(t.message))return t;return await this.recordAssistantMessage(t.message,t.finishReason),await this.addUserReminderMessage("Previous turn ended unexpectedly. Continue from where you left off.",{displayRole:"system"}),this.resetLastError(),await e()}async withProviderErrorRetry(e){let t=0;for(;;){let n=await e();if(t>=Wt||!this.isRetryableProviderErrorTurn(n))return n;t+=1;let i=this.state.lastError;this.resetLastError();let r=Math.min(Vd*2**(t-1),Zd);await this.emit({type:"status-notice",snapshot:this.snapshot(),message:`provider error — retrying (attempt ${t}/${Wt})`,metadata:{kind:"provider_error_retry",reason:"provider_error_retry",phase:"started",iteration:this.state.iteration,attempt:t,maxRetries:Wt,delayMs:r,providerError:i}}),await this.abortableDelay(r)}}isRetryableProviderErrorTurn(e){if(e.finishReason!=="error")return!1;if(e.message.content.length>0)return!1;let t=e.message.metadata?.modelToolActivities;if(Array.isArray(t)&&t.length>0)return!1;let n=this.state.lastErrorClass;if(n==="auth"||n==="context_window_exceeded")return!1;let i=ke(this.state.lastError??"",n);if(i&&this.recoversTurnFault(i))return!1;return this.state.lastErrorRetryable===!0}resetLastError(){this.state.lastError=void 0,this.state.lastErrorClass=void 0,this.state.lastErrorRetryable=void 0,this.state.lastErrorReported=!1}async abortableDelay(e){this.throwIfAborted();let t=this.abortController?.signal;await new Promise((n,i)=>{let r=()=>{clearTimeout(o),i(this.normalizeAbortError())},o=setTimeout(()=>{t?.removeEventListener("abort",r),n()},e);if(t)t.addEventListener("abort",r,{once:!0})})}async generateAssistantMessageWithOverflowRecovery(){if(this.config.alwaysDescribeImages===!0)await this.describeImagesInTranscript();let e=this.compactBeforeNextTurn;this.compactBeforeNextTurn=!1;let t=await this.generateAssistantMessage(e?{overflowRecovery:!0}:void 0);if(this.isRecoverableImageTurn(t))return await this.retryWithoutImages();if(!this.isRecoverableOverflowTurn(t))return t;this.overflowRecoveryAttempted=!0;let n=this.state.lastError;if(!this.config.prepareTurn)throw new Se(Yd,n);await this.emit({type:"status-notice",snapshot:this.snapshot(),message:"context window exceeded — compacting and retrying",metadata:{kind:"context_overflow_recovery",reason:"context_overflow_recovery",phase:"started",iteration:this.state.iteration,providerError:n}});let i=await this.generateAssistantMessage({overflowRecovery:!0,requireSmallerRequest:!0});if(i.finishReason==="error"&&this.state.lastErrorClass==="context_window_exceeded")throw new Se(Jd,this.state.lastError);return i}async recoverUnparsableToolCall(){if(this.state.lastErrorClass!=="tool_call_unparsable"||this.toolCallParseRetries>=Hd)return!1;return this.toolCallParseRetries+=1,await this.emit({type:"status-notice",snapshot:this.snapshot(),message:"the model's tool call did not parse — asking for it again",metadata:{kind:"tool_call_parse_recovery",reason:"tool_call_parse_recovery",phase:"started",iteration:this.state.iteration,attempt:this.toolCallParseRetries,providerError:this.state.lastError,...this.lastToolCallRejection?{rejection:this.lastToolCallRejection}:{}}}),await this.addUserReminderMessage(qd(this.lastToolCallRejection)),!0}isRecoverableImageTurn(e){return e.finishReason==="error"&&this.state.lastErrorClass==="image_input_unsupported"&&!this.imageRecoveryAttempted&&this.hasImageContent()}hasImageContent(){return this.state.messages.some((e)=>e.content.some((t)=>t.type==="image"))}async retryWithoutImages(){this.imageRecoveryAttempted=!0;let e=this.state.lastError,t=await this.describeImagesInTranscript(),n=0;for(let i of this.state.messages)for(let r=0;r<i.content.length;r++){if(i.content[r]?.type!=="image")continue;n+=1,i.content[r]={type:"text",text:Rd}}return this.config.onImageInputUnsupported?.(),await this.emit({type:"status-notice",snapshot:this.snapshot(),message:"model does not accept images — resending without them",metadata:{kind:"image_input_recovery",reason:"image_input_recovery",phase:"started",iteration:this.state.iteration,droppedImages:n,describedImages:t,providerError:e}}),await this.generateAssistantMessage()}async describeImagesInTranscript(){let e=this.config.describeImages;if(!e)return 0;let t=[],n=[];for(let s of this.state.messages){let a=s.content.filter((u)=>u.type==="text").map((u)=>u.text).join(`
97
+ `);this.pendingHookContexts=[];let t=ue("user",[{type:"text",text:e}],{userRunSpan:0,displayRole:"system"}),n=this.state.messages.at(-1);if(n?.role==="assistant"&&n.content.some((r)=>r.type==="tool-call"))this.state.messages.splice(-1,0,t);else this.state.messages.push(t);await this.emit({type:"message-added",snapshot:this.snapshot(),message:t})}async callBeforeRunHooks(){for(let e of this.hooks.beforeRun){let t=await e({snapshot:this.snapshot()});if(this.applyStopControl(t),t?.appendContext?.trim())this.pendingHookContexts.push(Zt({source:"RunStart"},t.appendContext))}}async callAfterRunHooks(e){for(let t of this.hooks.afterRun)await t({snapshot:this.snapshot(),result:e})}async generateAssistantMessageRecoveringFaults(){for(let e=1;;e+=1){let t,n,i=!1;try{t=await this.withProviderErrorRetry(()=>this.generateAssistantMessageWithOverflowRecovery())}catch(h){if(this.abortController?.signal.aborted||h instanceof mt||h instanceof Re||h instanceof ge)throw h;n=h,i=!0}let r=this.config.recoverTurnFault,o=()=>{if(i)throw n;return t};if(!r)return o();let s,a,u;if(i)s=It(n),a=n instanceof Error?n.message:String(n),u=Me(n);else if(t?.finishReason==="error")a=this.state.lastError??"",s=_e(a,this.state.lastErrorClass),u=$n(a,this.state.lastErrorClass);else return o();if(!s||!this.recoversTurnFault(s))return o();let c=B(this.config.sessionId),d=this.lastRequestTokens;if(u)this.config.logger?.log?.(`Engine bug: the server evicted session ${c??"(unnamed)"} (agent ${this.state.agentId}) at ${new Date().toISOString()}, holding ${d!==void 0?`${d.toLocaleString("en-US")} tokens (its last completed request)`:"an unknown number of tokens (no request had completed)"}, turn ${this.state.iteration}, attempt ${e}: ${a}; waiting to send it again`,{severity:"warn",kind:"engine_eviction",...c?{sessionId:c}:{},agentId:this.state.agentId,...d!==void 0?{tokensHeld:d}:{},iteration:this.state.iteration,attempt:e});else this.config.logger?.log?.(s==="refusal"?`Turn ${this.state.iteration} queued by the server (retry ${e}): ${Ln(a)}; waiting to send it again`:`Turn ${this.state.iteration} failed on a ${s} fault (attempt ${e}): ${a}; waiting to send it again`,{severity:s==="refusal"?"info":"warn"});await this.emit({type:"status-notice",snapshot:this.snapshot(),message:u?"the server evicted the turn to keep others alive (an engine bug) — waiting, then retrying":s==="transport"?"the server dropped the turn — waiting for it to come back, then retrying":"the server queued the turn — waiting for room, then retrying",metadata:{kind:"turn_fault_recovery",reason:s,...u?{evicted:!0}:{},phase:"started",iteration:this.state.iteration,attempt:e,providerError:a}});let y=!1;try{y=await r({kind:s,message:a,attempt:e,iteration:this.state.iteration,...u?{evicted:!0}:{},...u&&d!==void 0?{tokensHeld:d}:{},...c?{sessionId:c}:{},...this.abortController?.signal?{signal:this.abortController.signal}:{}})}catch{y=!1}if(this.throwIfAborted(),!y)return o()}}async generateAssistantMessageWithProviderRetry(){let e=()=>this.generateAssistantMessageRecoveringFaults(),t=await e();if(t.finishReason!=="unknown"||t.interrupted)return t;if(t.message.content.some((n)=>n.type==="tool-call")||this.hasModelToolActivity(t.message))return t;return await this.recordAssistantMessage(t.message,t.finishReason),await this.addUserReminderMessage("Previous turn ended unexpectedly. Continue from where you left off.",{displayRole:"system"}),this.resetLastError(),await e()}async withProviderErrorRetry(e){let t=0;for(;;){let n=await e();if(t>=Wt||!this.isRetryableProviderErrorTurn(n))return n;t+=1;let i=this.state.lastError;this.resetLastError();let r=Math.min(Vd*2**(t-1),Zd);await this.emit({type:"status-notice",snapshot:this.snapshot(),message:`provider error — retrying (attempt ${t}/${Wt})`,metadata:{kind:"provider_error_retry",reason:"provider_error_retry",phase:"started",iteration:this.state.iteration,attempt:t,maxRetries:Wt,delayMs:r,providerError:i}}),await this.abortableDelay(r)}}isRetryableProviderErrorTurn(e){if(e.finishReason!=="error")return!1;if(e.message.content.length>0)return!1;let t=e.message.metadata?.modelToolActivities;if(Array.isArray(t)&&t.length>0)return!1;let n=this.state.lastErrorClass;if(n==="auth"||n==="context_window_exceeded")return!1;let i=_e(this.state.lastError??"",n);if(i&&this.recoversTurnFault(i))return!1;return this.state.lastErrorRetryable===!0}resetLastError(){this.state.lastError=void 0,this.state.lastErrorClass=void 0,this.state.lastErrorRetryable=void 0,this.state.lastErrorReported=!1}async abortableDelay(e){this.throwIfAborted();let t=this.abortController?.signal;await new Promise((n,i)=>{let r=()=>{clearTimeout(o),i(this.normalizeAbortError())},o=setTimeout(()=>{t?.removeEventListener("abort",r),n()},e);if(t)t.addEventListener("abort",r,{once:!0})})}async generateAssistantMessageWithOverflowRecovery(){if(this.config.alwaysDescribeImages===!0)await this.describeImagesInTranscript();let e=this.compactBeforeNextTurn;this.compactBeforeNextTurn=!1;let t=await this.generateAssistantMessage(e?{overflowRecovery:!0}:void 0);if(this.isRecoverableImageTurn(t))return await this.retryWithoutImages();if(!this.isRecoverableOverflowTurn(t))return t;this.overflowRecoveryAttempted=!0;let n=this.state.lastError;if(!this.config.prepareTurn)throw new Re(Yd,n);await this.emit({type:"status-notice",snapshot:this.snapshot(),message:"context window exceeded — compacting and retrying",metadata:{kind:"context_overflow_recovery",reason:"context_overflow_recovery",phase:"started",iteration:this.state.iteration,providerError:n}});let i=await this.generateAssistantMessage({overflowRecovery:!0,requireSmallerRequest:!0});if(i.finishReason==="error"&&this.state.lastErrorClass==="context_window_exceeded")throw new Re(Jd,this.state.lastError);return i}async recoverUnparsableToolCall(){if(this.state.lastErrorClass!=="tool_call_unparsable"||this.toolCallParseRetries>=Hd)return!1;return this.toolCallParseRetries+=1,await this.emit({type:"status-notice",snapshot:this.snapshot(),message:"the model's tool call did not parse — asking for it again",metadata:{kind:"tool_call_parse_recovery",reason:"tool_call_parse_recovery",phase:"started",iteration:this.state.iteration,attempt:this.toolCallParseRetries,providerError:this.state.lastError,...this.lastToolCallRejection?{rejection:this.lastToolCallRejection}:{}}}),await this.addUserReminderMessage(qd(this.lastToolCallRejection)),!0}isRecoverableImageTurn(e){return e.finishReason==="error"&&this.state.lastErrorClass==="image_input_unsupported"&&!this.imageRecoveryAttempted&&this.hasImageContent()}hasImageContent(){return this.state.messages.some((e)=>e.content.some((t)=>t.type==="image"))}async retryWithoutImages(){this.imageRecoveryAttempted=!0;let e=this.state.lastError,t=await this.describeImagesInTranscript(),n=0;for(let i of this.state.messages)for(let r=0;r<i.content.length;r++){if(i.content[r]?.type!=="image")continue;n+=1,i.content[r]={type:"text",text:Rd}}return this.config.onImageInputUnsupported?.(),await this.emit({type:"status-notice",snapshot:this.snapshot(),message:"model does not accept images — resending without them",metadata:{kind:"image_input_recovery",reason:"image_input_recovery",phase:"started",iteration:this.state.iteration,droppedImages:n,describedImages:t,providerError:e}}),await this.generateAssistantMessage()}async describeImagesInTranscript(){let e=this.config.describeImages;if(!e)return 0;let t=[],n=[];for(let s of this.state.messages){let a=s.content.filter((u)=>u.type==="text").map((u)=>u.text).join(`
98
98
  `).slice(0,Ad);for(let u=0;u<s.content.length;u++){let c=s.content[u];if(c?.type!=="image")continue;let d=Sd(c);if(d===void 0)continue;t.push({message:s,index:u}),n.push({image:d,mediaType:c.mediaType,context:a.length>0?a:void 0})}}if(n.length===0)return this.config.logger?.log?.(`Vision describer found no images in ${this.state.messages.length} transcript message(s)`),0;let i=[];try{i=await e(n)}catch(s){this.config.logger?.log?.(`Vision model could not describe ${n.length} image(s): ${s instanceof Error?s.message:String(s)}`,{severity:"warn"})}let r=this.config.modelSupportsImages!==!1,o=0;for(let s=0;s<t.length;s++){let a=i[s]?.trim();if(!a&&r)continue;let u=t[s];u.message.content[u.index]={type:"text",text:a?`[image description, from the vision model]
99
- ${a}`:xd},o+=1}return o}isRecoverableOverflowTurn(e){if(e.finishReason!=="error"||this.state.lastErrorClass!=="context_window_exceeded"||this.overflowRecoveryAttempted)return!1;return!e.message.content.some((t)=>t.type==="tool-call")}hasModelToolActivity(e){let t=e.metadata?.modelToolActivities;return Array.isArray(t)&&t.length>0}async recordAssistantMessage(e,t){let n=this.replaceSpoiledContent(e);if(this.state.messages.push(e),await this.emit({type:"message-added",snapshot:this.snapshot(),message:e}),n)this.announcedRepetitionRemoval.add(e),await this.emit({type:"status-notice",snapshot:this.snapshot(),message:n,metadata:{kind:"reasoning_loop",reason:"reasoning_loop",phase:"removed",iteration:this.state.iteration}});await this.emit({type:"assistant-message",snapshot:this.snapshot(),iteration:this.state.iteration,message:e,finishReason:t})}async generateAssistantMessage(e){let t=new AbortController;this.modelSteerController=t;try{return await this.generateAssistantMessageForRequest(t,e)}finally{this.modelSteerController=void 0}}async prepareModelRequest(e){let t=rr({distinctId:B(this.config.distinctId),clientName:B(this.config.clientName),clientVersion:B(this.config.clientVersion),clineCoreVersion:B(this.config.clineCoreVersion),sessionId:B(this.config.sessionId),agentId:this.state.agentId,conversationId:B(this.config.conversationId),runId:this.state.runId,iteration:this.state.iteration}),n=this.getRetryOutputCap();if(n!==void 0)this.config.logger?.log?.(`Retrying a truncated turn on a reduced output cap of ${n} tokens (attempt ${this.consecutiveMaxTokensRetries}, was ${this.truncatedOutputCapTokens})`,{severity:"info"});let i={systemPrompt:this.config.systemPrompt,messages:Z(this.state.messages),tools:[...this.tools.values()].map((s)=>({name:s.name,description:s.description,inputSchema:s.inputSchema,...s.readOnly?{readOnly:!0}:{}})),modelTools:this.config.modelTools,signal:this.abortController?.signal,options:$t(this.config.modelOptions,{metadata:t,...n!==void 0?{maxTokens:n}:{}})},r=Date.now(),o=await this.consumePendingUserMessage();if(o)i={...i,messages:[...i.messages,...Z([o])]};i=await this.prepareTurnForModelRequest(i,e),this.throwIfAborted();for(let s of this.hooks.beforeModel){let a=await s({snapshot:this.snapshot(),request:i});if(this.throwIfAborted(),this.applyStopControl(a),a?.messages)i={...i,messages:Z(a.messages)};if(a?.tools)i={...i,tools:[...a.tools]};if(a?.options)i={...i,options:$t(i.options,a.options)}}return this.config.logger?.debug("Agent model request diagnostics",{iteration:this.state.iteration,providerId:"providerId"in this.config&&typeof this.config.providerId==="string"?this.config.providerId:void 0,modelId:"modelId"in this.config&&typeof this.config.modelId==="string"?this.config.modelId:void 0,...np(i)}),{request:i,startedAt:r}}async generateAssistantMessageForRequest(e,t){let n=await this.prepareModelRequest(t);return await this.streamPreparedRequest(n,e)}async streamPreparedRequest(e,t){let n=ne(this.state.usage);this.state.lastRequestTimings=void 0;let i=()=>Date.now()-e.startedAt,r=e.request;this.throwIfAborted(),this.captureTaskLifecycle(sr,{durationMs:i(),phase:"provider_request_started"}),r={...r,signal:AbortSignal.any([t.signal,...this.abortController?[this.abortController.signal]:[]])},this.lastIssuedRequest=r;let o=this.openTaskLifecycleStream(r,i),s=[],a=new De,u=new Map,c=[],d=[],y="unknown",g,f="",b="",w=Dt(),G=0,j=this.config.reasoningLoopDetection,U=j===!1?void 0:new ct(j,{given:()=>br(r.messages)}),I,O=this.config.toolIntentLimit,ie=this.toolIntentCutStreak>=Dd;if(ie)this.toolIntentCutStreak=0;let re=O===!1||ie||!qt()?void 0:new Ht({...O,argumentNames:this.toolArgumentNames(),toolNames:[...this.tools.values()].map((v)=>v.name)}),q;for await(let v of o){if(t.signal.aborted)break;switch(this.throwIfAborted(),v.type){case"text-delta":{f+=v.text,w.textDeltas+=1,w.textChars+=v.text.length;let N=d.at(-1);if(N?.type==="part"&&N.part.type==="text")N.part.text+=v.text;else d.push({type:"part",part:{type:"text",text:v.text}});await this.emit({type:"assistant-text-delta",snapshot:this.snapshot(),iteration:this.state.iteration,text:v.text,accumulatedText:f});break}case"media":{d.push({type:"part",part:{type:"media",media:v.media}}),await this.emit({type:"assistant-media",snapshot:this.snapshot(),iteration:this.state.iteration,media:v.media});break}case"reasoning-delta":{b+=v.text,w.reasoningDeltas+=1,w.reasoningChars+=v.text.length;let N=d.at(-1);if(N?.type==="part"&&N.part.type==="reasoning")N.part.text+=v.text,N.part.redacted=v.redacted??N.part.redacted,N.part.metadata=v.metadata??N.part.metadata;else d.push({type:"part",part:{type:"reasoning",text:v.text,redacted:v.redacted,metadata:v.metadata}});await this.emit({type:"assistant-reasoning-delta",snapshot:this.snapshot(),iteration:this.state.iteration,text:v.text,accumulatedText:b,redacted:v.redacted,metadata:v.metadata}),I=U?.push(v.text)??void 0;break}case"tool-input-progress":{if(await this.emit({type:"tool-updated",snapshot:this.snapshot(),iteration:this.state.iteration,toolCall:{type:"tool-call",toolCallId:v.toolCallId,toolName:v.toolName??"tool",input:void 0},update:{kind:Pn,inputChars:v.inputChars,deltas:v.deltas,...v.inputText?{inputText:v.inputText}:{}}}),v.inputText)q=re?.push(v.toolCallId,v.inputText,v.toolName);break}case"tool-call-delta":{if(v.execution){let ce={type:"tool-call",toolCallId:v.toolCallId??me("model_tool"),toolName:v.toolName??"tool",input:v.input,metadata:v.metadata,execution:v.execution};u.set(ce.toolCallId,{toolCallId:ce.toolCallId,toolName:ce.toolName,execution:v.execution,input:ce.input}),await this.emit({type:"tool-started",snapshot:this.snapshot(),iteration:this.state.iteration,toolCall:ce});break}let{key:N,created:W}=a.add(v);if(W)d.push({type:"tool",key:N});break}case"tool-result":{let N=u.get(v.toolCallId),W={...N,toolCallId:v.toolCallId,toolName:v.toolName,execution:v.execution,input:v.input===void 0?N?.input:v.input,output:v.output,isError:v.isError};u.set(v.toolCallId,W);let ce={type:"tool-call",toolCallId:v.toolCallId,toolName:v.toolName,input:W.input,execution:v.execution};await this.emit({type:"tool-finished",snapshot:this.snapshot(),iteration:this.state.iteration,toolCall:ce,message:ue("tool",[{type:"tool-result",toolCallId:v.toolCallId,toolName:v.toolName,output:v.output,isError:v.isError,execution:v.execution}])});break}case"usage":{if(typeof v.usage.inputTokens==="number"&&v.usage.inputTokens>0)this.state.lastRequestInputTokens=v.usage.inputTokens;let N=a.inputChars();w.toolInputChars=Math.max(0,N-G);let W=vr({outputTokens:v.usage.outputTokens,providerReasoningTokens:v.usage.reasoningTokenCount,tally:w});G=N,w=Dt(),await this.updateUsage(v.usage,v.timings,{outputSplit:W});break}case"finish":{if(y=v.reason,g=v.requestId,v.error)this.state.lastError=v.error,this.state.lastErrorClass=v.errorClass??xr(v.error),this.lastToolCallRejection=v.toolCallRejection,this.state.lastErrorRetryable=v.errorRetryable??Td(v.error),this.state.lastErrorReported=v.errorReported===!0;break}}if(I||q)break}if(I)await this.onReasoningLoopCut(I);else if(U)this.reasoningLoopStreak=0;if(q)await this.onToolIntentCut(q);else if(re)this.toolIntentCutStreak=0;this.throwIfAborted();let ye=t.signal.aborted;if(ye)y="stop";if((I||q)&&y==="unknown")y="stop";for(let v of d){if(ye&&(v.type==="tool"||v.part.type==="reasoning"))continue;if(v.type==="part"){s.push(v.part);continue}let N=a.get(v.key);if(q&&N?.toolCallId===q.toolCallId)continue;let W=a.finish(v.key,y);if(W.invalid)c.push(W.invalid);if(!W.call||!N)continue;this.config.logger?.debug?.(Ed(this.state.iteration,W.call.toolName,W.call.toolCallId,N.inputText,W.call.input)),s.push(W.call)}let Y={};if(I)Y.reasoningLoop=I;if(q)s.push({type:"text",text:Cr(q)}),Y.toolIntentOverrun=q;if(c.length>0)Y.invalidToolCalls=c;if(u.size>0)Y.modelToolActivities=[...u.values()];let oe=ue("assistant",s,Object.keys(Y).length>0?Y:void 0),F=rp(n,this.state.usage);if(F){if(this.state.lastRequestTimings)F.timings=this.state.lastRequestTimings;oe.metrics=F,this.captureUnexpectedReasoningTokens(r,F)}if(this.config.messageModelInfo)oe.modelInfo={...this.config.messageModelInfo};for(let v of this.hooks.afterModel){let N=await v({snapshot:this.snapshot(),assistantMessage:oe,finishReason:y,...g?{requestId:g}:{}});this.applyStopControl(N)}return{message:oe,finishReason:y,interrupted:ye}}async*openTaskLifecycleStream(e,t){let n,i="provider_request_started",r=Date.now();this.trace(`request-start iter=${this.state.iteration}`);try{n=await this.config.model.stream(e),this.trace(`stream-open iter=${this.state.iteration} after=${Date.now()-r}ms`),this.throwIfAborted(),i="provider_stream_started",this.captureTaskLifecycle(ar,{durationMs:t(),phase:i})}catch(s){if(e.signal?.aborted&&!this.abortController?.signal.aborted)return;if(!e.signal?.aborted&&!this.isAbortError(s))this.captureTaskLifecycleFailure(s,i,t());throw s}let o=!1;try{for await(let s of n){if(!o)o=!0,this.trace(`first-chunk iter=${this.state.iteration} after=${Date.now()-r}ms type=${s.type}`),i="first_chunk_received",this.captureTaskLifecycle(lr,{durationMs:t(),phase:i,eventType:s.type});yield s}}catch(s){if(e.signal?.aborted&&!this.abortController?.signal.aborted)return;if(!e.signal?.aborted&&!this.isAbortError(s))this.captureTaskLifecycleFailure(s,i,t());throw s}}captureTaskLifecycleFailure(e,t,n){this.captureTaskLifecycle(ur,{durationMs:n,error:e,errorClass:xr(e),phase:t})}captureTaskLifecycle(e,t={}){let n=B(this.config.sessionId);pr(this.config.telemetry,{event:e,sessionId:n,ulid:n,agentId:this.state.agentId,conversationId:B(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 B(this.config.messageModelInfo?.provider)??this.telemetryProviderId}getTelemetryModelId(){return B(this.config.messageModelInfo?.id)??this.telemetryModelId}isAbortError(e){return e instanceof ge||this.abortController?.signal.aborted===!0}captureUnexpectedReasoningTokens(e,t){if(!op(e)||(t.reasoningTokenCount??0)<=0)return;let n=t.reasoningTokenCount;if(n===void 0)return;dr(this.config.telemetry,{sessionId:this.config.sessionId,agentId:this.state.agentId,runId:this.state.runId,iteration:this.state.iteration,providerId:this.config.messageModelInfo?.provider,modelId:this.config.messageModelInfo?.id,requestedThinking:!1,reasoningTokenCount:n})}async prepareTurnForModelRequest(e,t){if(!this.config.prepareTurn)return e;let n=t?.overflowRecovery===!0,i=t?.requireSmallerRequest===!0,r=await this.config.prepareTurn({agentId:this.state.agentId,conversationId:this.config.conversationId,parentAgentId:this.state.parentAgentId??null,iteration:this.state.iteration,messages:e.messages,systemPrompt:e.systemPrompt,tools:e.tools,model:{id:this.config.messageModelInfo?.id,provider:this.config.messageModelInfo?.provider},signal:e.signal,overflowRecovery:n||void 0,previousRequestInputTokens:this.state.lastRequestInputTokens>0?this.state.lastRequestInputTokens:void 0,emitStatusNotice:(s,a)=>{this.emit({type:"status-notice",snapshot:this.snapshot(),message:s,metadata:a})},reportUsage:(s)=>{this.updateUsage(s,void 0,{auxiliary:!0})}});if(i){if(!(r?.messages!==void 0&&JSON.stringify(r.messages).length<JSON.stringify(e.messages).length))throw new Se(Kd,this.state.lastError)}if(!r)return e;let o=e;if(r.messages){let s=Z(r.messages);o={...o,messages:Z(s)}}if(r.systemPrompt!==void 0)o={...o,systemPrompt:r.systemPrompt};return o}async consumePendingUserMessage(){let e=this.config.consumePendingUserMessage;if(!e)return;let t=(await e())?.trim();if(!t)return;let n=ue("user",[{type:"text",text:t}],{userRunSpan:0});return this.steerAwaitingResume=!0,this.state.messages.push(n),await this.emit({type:"message-added",snapshot:this.snapshot(),message:n}),n}async updateUsage(e,t,n){let i=n?.auxiliary===!0;if(this.state.usage={inputTokens:this.state.usage.inputTokens+(e.inputTokens??0),outputTokens:this.state.usage.outputTokens+(e.outputTokens??0),cacheReadTokens:this.state.usage.cacheReadTokens+(e.cacheReadTokens??0),cacheWriteTokens:this.state.usage.cacheWriteTokens+(e.cacheWriteTokens??0),reasoningTokenCount:(this.state.usage.reasoningTokenCount??0)+(e.reasoningTokenCount??0),totalCost:(this.state.usage.totalCost??0)+(e.totalCost??0)},t)this.state.lastRequestTimings=t;if(e.inputTokens!==void 0&&!i)this.lastRequestTokens=(e.inputTokens??0)+(e.outputTokens??0);await this.emit({type:"usage-updated",snapshot:this.snapshot(),usage:ne(this.state.usage),...t?{timings:t}:{},...n?.outputSplit?{outputSplit:n.outputSplit}:{},...i?{auxiliary:!0}:{}})}async executeToolCalls(e){this.pendingHookContexts=[];let t=[];for(let d of e){let y=Date.now(),g=await this.prepareToolExecution(d);g.prepareMs=Date.now()-y,t.push(g)}let n=Array(t.length),i=[],r=[],o=this.config.maxParallelToolCalls>1;t.forEach((d,y)=>{let g=this.tools.get(d.toolCall.toolName);(o&&g?.lifecycle?.boundsOwnConcurrency===!0?r:i).push(y)});let s=r.map(async(d)=>{n[d]=await this.executePreparedTool(t[d])}),a=Math.min(Math.max(1,this.config.maxParallelToolCalls),i.length);if(a<=1){for(let d of i)n[d]=await this.executePreparedTool(t[d]);return await Promise.all(s),n}let u=0,c=async()=>{while(!0){let d=u;if(u+=1,d>=i.length)return;let y=i[d];n[y]=await this.executePreparedTool(t[y])}};return await Promise.all([...Array.from({length:a},()=>c()),...s]),n}findCompletingToolMessage(e,t){for(let n=0;n<e.length;n+=1){let i=e[n];if(this.tools.get(i.toolName)?.lifecycle?.completesRun!==!0)continue;let r=t[n],o=r?.content.find((s)=>s.type==="tool-result"&&s.toolCallId===i.toolCallId);if(o&&!o.isError)return r}return}async prepareToolExecution(e){let t=this.tools.get(e.toolName),n=e.input,i,r=e.metadata&&typeof e.metadata==="object"&&!Array.isArray(e.metadata)?e.metadata:void 0;if(typeof r?.inputParseError==="string")i=r.inputParseError;let o=t?void 0:this.config.unavailableToolReasons?.[e.toolName];if(o)i=`Tool "${e.toolName}" is not offered in this session: ${o}`;let s=r?.toolSource&&typeof r.toolSource==="object"&&!Array.isArray(r.toolSource)?r.toolSource:void 0;if(s?.executionMode==="provider")i=`Tool execution is disabled for provider ${typeof s.providerId==="string"?s.providerId:"provider"}`;if(t&&!i)n=Ce(n,t.inputSchema);let a;if(t&&!i)for(let u of this.hooks.beforeTool){let c=await u({snapshot:this.snapshot(),tool:t,toolCall:{...e,input:n},input:n});if(c?.input!==void 0)n=c.input;if(c?.policy)a={...a,...c.policy};if(c?.appendContext?.trim())this.pendingHookContexts.push(Zt({source:"PreToolUse",toolCall:e},c.appendContext));if(this.applyStopControl(c),c?.skip){i=c.reason??`Tool ${t.name} was blocked by a runtime hook`;break}}if(t&&!i){let u={...ep(e.toolName,this.config.toolPolicies),...a};if(u.enabled===!1)i=`Tool "${e.toolName}" is disabled by policy`;else if(u.autoApprove===!1){let c=await this.requestToolApproval(e,n,u);if(!c.approved)i=`${c.reason??"Tool was not executed"} -- ${Wi}`}}return{toolCall:{...e,input:n},tool:t,input:n,skipReason:i}}async requestToolApproval(e,t,n){let i=this.config.requestToolApproval;if(!i)return{approved:!1,reason:`Tool "${e.toolName}" requires approval but no approval callback is configured`};try{return await i({sessionId:this.config.sessionId?.trim()||this.config.conversationId?.trim()||this.state.runId||this.state.agentId,agentId:this.state.agentId,conversationId:this.config.conversationId?.trim()||this.state.runId||this.state.agentId,iteration:this.state.iteration,toolCallId:e.toolCallId,toolName:e.toolName,input:t,policy:n})}catch(r){return{approved:!1,reason:`Tool "${e.toolName}" approval request failed: ${r instanceof Error?r.message:String(r)}`}}}async executePreparedTool(e){let t=new Date,n=Date.now();await this.emit({type:"tool-started",snapshot:this.snapshot(),iteration:this.state.iteration,toolCall:e.toolCall});let i=Date.now(),r;if(e.skipReason)r={output:{error:e.skipReason},isError:!0};else if(!e.tool)r={output:{error:`Unknown tool: ${e.toolCall.toolName}`},isError:!0};else try{if(r={output:await e.tool.execute(e.input,{sessionId:this.config.sessionId,agentId:this.state.agentId,conversationId:this.config.conversationId,runId:this.state.runId??me("run"),iteration:this.state.iteration,toolCallId:e.toolCall.toolCallId,signal:this.abortController?.signal,metadata:this.config.toolContextMetadata,snapshot:this.snapshot(),reportStoppedForUser:()=>{this.stoppedForUserBy=e.toolCall.toolName},emitUpdate:(d)=>{this.emit({type:"tool-updated",snapshot:this.snapshot(),iteration:this.state.iteration,toolCall:e.toolCall,update:d})}})},this.stoppedForUserBy!==void 0&&this.stoppedForUserBy!==e.toolCall.toolName&&e.tool.readOnly!==!0)this.stoppedForUserBy=void 0}catch(c){r={output:{error:c instanceof Error?c.message:String(c)},isError:!0}}let o=new Date,s=Date.now(),a=Math.max(0,o.getTime()-t.getTime());if(e.tool)for(let c of this.hooks.afterTool){let d=await c({snapshot:this.snapshot(),tool:e.tool,toolCall:e.toolCall,input:e.input,result:r,startedAt:t,endedAt:o,durationMs:a});if(d?.appendContext?.trim())this.pendingHookContexts.push(Zt({source:"PostToolUse",toolCall:e.toolCall},d.appendContext));if(this.applyStopControl(d),d?.result)r=d.result}this.trace(`tool ${e.toolCall.toolName} prepare=${e.prepareMs??-1}ms preEmit=${i-n}ms exec=${s-i}ms afterHooks=${Date.now()-s}ms total=${Date.now()-n}ms | hooks ${this.topEventHooks()}`),this.config.logger?.debug?.(`[tool-timing] ${e.toolCall.toolName} prepare=${e.prepareMs??-1}ms preEmit=${i-n}ms exec=${s-i}ms afterHooks=${Date.now()-s}ms total=${Date.now()-n}ms | hooks ${this.topEventHooks()}`);let u=ue("tool",[{type:"tool-result",toolCallId:e.toolCall.toolCallId,toolName:e.toolCall.toolName,output:r.output,isError:r.isError}]);return await this.emit({type:"tool-finished",snapshot:this.snapshot(),iteration:this.state.iteration,toolCall:e.toolCall,message:u}),u}finishRun(e,t,n){return this.state.status=e,{agentId:this.state.agentId,agentRole:this.state.agentRole,runId:this.state.runId??me("run"),status:e,iterations:this.state.iteration,outputText:n??Re(t??this.findLastAssistantMessage()),messages:Z(this.state.messages),usage:ne(this.state.usage)}}findLastAssistantMessage(){return[...this.state.messages].reverse().find((e)=>e.role==="assistant")}async onReasoningLoopCut(e){this.reasoningLoopStreak+=1;let t=(this.config.reasoningLoopDetection===!1?void 0:this.config.reasoningLoopDetection?.maxConsecutiveTrips)??ut.maxConsecutiveTrips,n=Ft(e),i=this.reasoningLoopStreak>=t,r=i?await this.config.onReasoningLoopLimitReached?.({iteration:this.state.iteration,consecutiveTrips:this.reasoningLoopStreak,maxConsecutiveTrips:t,diagnosis:n}):void 0,o=r?.action==="continue"?r.guidance?.trim():void 0,s=i&&r?.action!=="continue";if(await this.emit({type:"status-notice",snapshot:this.snapshot(),message:s?`${n} Ending the run after ${this.reasoningLoopStreak} turns cut for this.`:i?`${n} That is ${this.reasoningLoopStreak} turns cut for this, and the run was to end here.`:`${n} Cutting the request and continuing.`,metadata:{kind:"reasoning_loop",reason:"reasoning_loop",phase:s?"aborted":"cut",iteration:this.state.iteration,consecutiveTrips:this.reasoningLoopStreak,verdict:e}}),s){this.abort(new ge(n)),this.throwIfAborted();return}if(o)await this.addUserReminderMessage(o)}toolArgumentNames(){let e=new Set;for(let t of this.tools.values()){let n=t.inputSchema?.properties;for(let i of Object.keys(n??{}))e.add(i)}return[...e]}async onToolIntentCut(e){this.toolIntentCutStreak+=1,this.pendingToolIntentNudge=Ar(e);let t=e.toolName?`\`${e.toolName}\``:"a tool";this.config.logger?.log?.(`[tool-intent] cut a call to ${t} at iteration ${this.state.iteration}: intent passed ${e.maxChars} characters`),await this.emit({type:"status-notice",snapshot:this.snapshot(),message:`The model was writing its reasoning into the \`intent\` of a call to ${t} (past ${e.maxChars.toLocaleString("en-US")} characters). Cutting the request and asking it to make the call again.`,metadata:{kind:"tool_intent_overrun",reason:"tool_intent_overrun",phase:"cut",iteration:this.state.iteration,overrun:e}})}throwIfAborted(){if(this.abortController?.signal.aborted)throw this.normalizeAbortError()}normalizeAbortError(){let e=this.abortController?.signal.reason;if(e instanceof Error)return e;if(typeof e==="string")return Error(e);return Error(this.state.lastError??"Run aborted")}eventHookMs=new Map;noteEventHookMs(e,t,n){let i=`${e}#${t}`,r=this.eventHookMs.get(i);if(r)r.ms+=n,r.n+=1;else this.eventHookMs.set(i,{ms:n,n:1})}topEventHooks(e=4){return[...this.eventHookMs.entries()].sort((t,n)=>n[1].ms-t[1].ms).slice(0,e).map(([t,n])=>`${t}=${Math.round(n.ms)}ms/${n.n}`).join(" ")}trace(e){kd(e),this.config.logger?.debug?.(`[timing] ${e}`)}async emit(e){let t=hp(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)hr(this.config.telemetry,{component:"agents",operation:"agent.run",error:e.error,severity:"error",handled:!1,context:{...t,providerId:this.getTelemetryProviderId(),modelId:this.getTelemetryModelId(),...this.state.lastFinishReason?{finishReason:this.state.lastFinishReason}:{}}});break;default:if(!pp.has(e.type))this.config.logger?.debug?.(`Agent event: ${e.type}`,t);break}switch(e.type){case"assistant-text-delta":case"assistant-reasoning-delta":case"assistant-media":case"tool-updated":break;default:this.config.telemetry?.capture({event:`agent.${e.type}`,properties:t});break}let n=0;for(let i of this.listeners){let r=Date.now();i(e),this.noteEventHookMs(e.type,`listener${n}`,Date.now()-r),n+=1}for(let i=0;i<this.hooks.onEvent.length;i+=1){let r=Date.now();await this.hooks.onEvent[i](e),this.noteEventHookMs(e.type,i,Date.now()-r)}}applyStopControl(e){if(!e?.stop)return;if(e.reason)this.state.lastError=e.reason;throw new mt(e.reason)}}var cp={no_tool_call:"the turn ended without calling anything — asking the model to carry on",unparsed_tool_call:"a tool call was written as text and never ran — asking for it again",announced_intent:"the model described the next step instead of taking it — asking it to make the call",non_convergence:"several turns of thinking with no work done — asking for a different approach",silent_repetition:"the turn repeated what the last one said — asking for a different approach"};function dp(e){return cp[e]??`nudged: ${e}`}var pp=new Set(["assistant-text-delta","assistant-reasoning-delta","assistant-media","tool-updated"]);function hp(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 fp(e){return new Ue(e)}var mp=Ue;function gp(e){return new Ue(e)}function Pr(e){let t=e.search(/<\|?tool_call\|?>/),n=(t<0?e:e.slice(t)).replace(/\s+/g," ").trim(),i=5381;for(let r=0;r<n.length;r++)i=(i<<5)+i+n.charCodeAt(r)|0;return`${n.length}:${i}`}export{mp as Agent,Ue as AgentRuntime,ge as AgentRuntimeAbortError,Wd as DEFAULT_MAX_NO_TOOL_CALL_NUDGES,$r as DEFAULT_NO_TOOL_CALL_TURN_STREAK_LIMIT,ut as DEFAULT_REASONING_LOOP_GUARD,fe as DEFAULT_REASONING_REPETITION,gd as DEFAULT_TOOL_INTENT_MAX_CHARS,Lr as NON_CONVERGENCE_MIN_REASONING_CHARS,ct as ReasoningLoopGuard,De as ToolCallAssembler,gp as createAgent,fp as createAgentRuntime,Bt as createRepetitionNudger,od as createTool,Ft as describeReasoningLoop,wr as describeRepetition,dd as finishToolCalls,pt as isRepetitionLoop,qt as isToolIntentGuardEnabled,dt as measureReasoningRepetition,yd as setToolIntentGuardEnabled};
99
+ ${a}`:xd},o+=1}return o}isRecoverableOverflowTurn(e){if(e.finishReason!=="error"||this.state.lastErrorClass!=="context_window_exceeded"||this.overflowRecoveryAttempted)return!1;return!e.message.content.some((t)=>t.type==="tool-call")}hasModelToolActivity(e){let t=e.metadata?.modelToolActivities;return Array.isArray(t)&&t.length>0}async recordAssistantMessage(e,t){let n=this.replaceSpoiledContent(e);if(this.state.messages.push(e),await this.emit({type:"message-added",snapshot:this.snapshot(),message:e}),n)this.announcedRepetitionRemoval.add(e),await this.emit({type:"status-notice",snapshot:this.snapshot(),message:n,metadata:{kind:"reasoning_loop",reason:"reasoning_loop",phase:"removed",iteration:this.state.iteration}});await this.emit({type:"assistant-message",snapshot:this.snapshot(),iteration:this.state.iteration,message:e,finishReason:t})}async generateAssistantMessage(e){let t=new AbortController;this.modelSteerController=t;try{return await this.generateAssistantMessageForRequest(t,e)}finally{this.modelSteerController=void 0}}async prepareModelRequest(e){let t=rr({distinctId:B(this.config.distinctId),clientName:B(this.config.clientName),clientVersion:B(this.config.clientVersion),clineCoreVersion:B(this.config.clineCoreVersion),sessionId:B(this.config.sessionId),agentId:this.state.agentId,conversationId:B(this.config.conversationId),runId:this.state.runId,iteration:this.state.iteration}),n=this.getRetryOutputCap();if(n!==void 0)this.config.logger?.log?.(`Retrying a truncated turn on a reduced output cap of ${n} tokens (attempt ${this.consecutiveMaxTokensRetries}, was ${this.truncatedOutputCapTokens})`,{severity:"info"});let i={systemPrompt:this.config.systemPrompt,messages:G(this.state.messages),tools:[...this.tools.values()].map((s)=>({name:s.name,description:s.description,inputSchema:s.inputSchema,...s.readOnly?{readOnly:!0}:{}})),modelTools:this.config.modelTools,signal:this.abortController?.signal,options:$t(this.config.modelOptions,{metadata:t,...n!==void 0?{maxTokens:n}:{}})},r=Date.now(),o=await this.consumePendingUserMessage();if(o)i={...i,messages:[...i.messages,...G([o])]};i=await this.prepareTurnForModelRequest(i,e),this.throwIfAborted();for(let s of this.hooks.beforeModel){let a=await s({snapshot:this.snapshot(),request:i});if(this.throwIfAborted(),this.applyStopControl(a),a?.messages)i={...i,messages:G(a.messages)};if(a?.tools)i={...i,tools:[...a.tools]};if(a?.options)i={...i,options:$t(i.options,a.options)}}return this.config.logger?.debug("Agent model request diagnostics",{iteration:this.state.iteration,providerId:"providerId"in this.config&&typeof this.config.providerId==="string"?this.config.providerId:void 0,modelId:"modelId"in this.config&&typeof this.config.modelId==="string"?this.config.modelId:void 0,...np(i)}),{request:i,startedAt:r}}async generateAssistantMessageForRequest(e,t){let n=await this.prepareModelRequest(t);return await this.streamPreparedRequest(n,e)}async streamPreparedRequest(e,t){let n=ne(this.state.usage);this.state.lastRequestTimings=void 0;let i=()=>Date.now()-e.startedAt,r=e.request;this.throwIfAborted(),this.captureTaskLifecycle(sr,{durationMs:i(),phase:"provider_request_started"}),r={...r,signal:AbortSignal.any([t.signal,...this.abortController?[this.abortController.signal]:[]])},this.lastIssuedRequest=r;let o=this.openTaskLifecycleStream(r,i),s=[],a=new ze,u=new Map,c=[],d=[],y="unknown",h,g="",T="",k=Dt(),H=0,Z=this.config.reasoningLoopDetection,U=Z===!1?void 0:new ct(Z,{given:()=>br(r.messages)}),I,M=this.config.toolIntentLimit,ie=this.toolIntentCutStreak>=Dd;if(ie)this.toolIntentCutStreak=0;let re=M===!1||ie||!qt()?void 0:new Ht({...M,argumentNames:this.toolArgumentNames(),toolNames:[...this.tools.values()].map((v)=>v.name)}),j;for await(let v of o){if(t.signal.aborted)break;switch(this.throwIfAborted(),v.type){case"text-delta":{g+=v.text,k.textDeltas+=1,k.textChars+=v.text.length;let N=d.at(-1);if(N?.type==="part"&&N.part.type==="text")N.part.text+=v.text;else d.push({type:"part",part:{type:"text",text:v.text}});await this.emit({type:"assistant-text-delta",snapshot:this.snapshot(),iteration:this.state.iteration,text:v.text,accumulatedText:g});break}case"media":{d.push({type:"part",part:{type:"media",media:v.media}}),await this.emit({type:"assistant-media",snapshot:this.snapshot(),iteration:this.state.iteration,media:v.media});break}case"reasoning-delta":{T+=v.text,k.reasoningDeltas+=1,k.reasoningChars+=v.text.length;let N=d.at(-1);if(N?.type==="part"&&N.part.type==="reasoning")N.part.text+=v.text,N.part.redacted=v.redacted??N.part.redacted,N.part.metadata=v.metadata??N.part.metadata;else d.push({type:"part",part:{type:"reasoning",text:v.text,redacted:v.redacted,metadata:v.metadata}});await this.emit({type:"assistant-reasoning-delta",snapshot:this.snapshot(),iteration:this.state.iteration,text:v.text,accumulatedText:T,redacted:v.redacted,metadata:v.metadata}),I=U?.push(v.text)??void 0;break}case"tool-input-progress":{if(await this.emit({type:"tool-updated",snapshot:this.snapshot(),iteration:this.state.iteration,toolCall:{type:"tool-call",toolCallId:v.toolCallId,toolName:v.toolName??"tool",input:void 0},update:{kind:Pn,inputChars:v.inputChars,deltas:v.deltas,...v.inputText?{inputText:v.inputText}:{}}}),v.inputText)j=re?.push(v.toolCallId,v.inputText,v.toolName);break}case"tool-call-delta":{if(v.execution){let ce={type:"tool-call",toolCallId:v.toolCallId??me("model_tool"),toolName:v.toolName??"tool",input:v.input,metadata:v.metadata,execution:v.execution};u.set(ce.toolCallId,{toolCallId:ce.toolCallId,toolName:ce.toolName,execution:v.execution,input:ce.input}),await this.emit({type:"tool-started",snapshot:this.snapshot(),iteration:this.state.iteration,toolCall:ce});break}let{key:N,created:W}=a.add(v);if(W)d.push({type:"tool",key:N});break}case"tool-result":{let N=u.get(v.toolCallId),W={...N,toolCallId:v.toolCallId,toolName:v.toolName,execution:v.execution,input:v.input===void 0?N?.input:v.input,output:v.output,isError:v.isError};u.set(v.toolCallId,W);let ce={type:"tool-call",toolCallId:v.toolCallId,toolName:v.toolName,input:W.input,execution:v.execution};await this.emit({type:"tool-finished",snapshot:this.snapshot(),iteration:this.state.iteration,toolCall:ce,message:ue("tool",[{type:"tool-result",toolCallId:v.toolCallId,toolName:v.toolName,output:v.output,isError:v.isError,execution:v.execution}])});break}case"usage":{if(typeof v.usage.inputTokens==="number"&&v.usage.inputTokens>0)this.state.lastRequestInputTokens=v.usage.inputTokens;let N=a.inputChars();k.toolInputChars=Math.max(0,N-H);let W=vr({outputTokens:v.usage.outputTokens,providerReasoningTokens:v.usage.reasoningTokenCount,tally:k});H=N,k=Dt(),await this.updateUsage(v.usage,v.timings,{outputSplit:W});break}case"finish":{if(y=v.reason,h=v.requestId,v.error)this.state.lastError=v.error,this.state.lastErrorClass=v.errorClass??xr(v.error),this.lastToolCallRejection=v.toolCallRejection,this.state.lastErrorRetryable=v.errorRetryable??Td(v.error),this.state.lastErrorReported=v.errorReported===!0;break}}if(I||j)break}if(I)await this.onReasoningLoopCut(I);else if(U)this.reasoningLoopStreak=0;if(j)await this.onToolIntentCut(j);else if(re)this.toolIntentCutStreak=0;this.throwIfAborted();let oe=t.signal.aborted;if(oe)y="stop";if((I||j)&&y==="unknown")y="stop";for(let v of d){if(oe&&(v.type==="tool"||v.part.type==="reasoning"))continue;if(v.type==="part"){s.push(v.part);continue}let N=a.get(v.key);if(j&&N?.toolCallId===j.toolCallId)continue;let W=a.finish(v.key,y);if(W.invalid)c.push(W.invalid);if(!W.call||!N)continue;this.config.logger?.debug?.(Ed(this.state.iteration,W.call.toolName,W.call.toolCallId,N.inputText,W.call.input)),s.push(W.call)}let Q={};if(I)Q.reasoningLoop=I;if(j)s.push({type:"text",text:Cr(j)}),Q.toolIntentOverrun=j;if(c.length>0)Q.invalidToolCalls=c;if(u.size>0)Q.modelToolActivities=[...u.values()];let F=ue("assistant",s,Object.keys(Q).length>0?Q:void 0),Ue=rp(n,this.state.usage);if(Ue){if(this.state.lastRequestTimings)Ue.timings=this.state.lastRequestTimings;F.metrics=Ue,this.captureUnexpectedReasoningTokens(r,Ue)}if(this.config.messageModelInfo)F.modelInfo={...this.config.messageModelInfo};for(let v of this.hooks.afterModel){let N=await v({snapshot:this.snapshot(),assistantMessage:F,finishReason:y,...h?{requestId:h}:{}});this.applyStopControl(N)}return{message:F,finishReason:y,interrupted:oe}}async*openTaskLifecycleStream(e,t){let n,i="provider_request_started",r=Date.now();this.trace(`request-start iter=${this.state.iteration}`);try{n=await this.config.model.stream(e),this.trace(`stream-open iter=${this.state.iteration} after=${Date.now()-r}ms`),this.throwIfAborted(),i="provider_stream_started",this.captureTaskLifecycle(ar,{durationMs:t(),phase:i})}catch(s){if(e.signal?.aborted&&!this.abortController?.signal.aborted)return;if(!e.signal?.aborted&&!this.isAbortError(s))this.captureTaskLifecycleFailure(s,i,t());throw s}let o=!1;try{for await(let s of n){if(!o)o=!0,this.trace(`first-chunk iter=${this.state.iteration} after=${Date.now()-r}ms type=${s.type}`),i="first_chunk_received",this.captureTaskLifecycle(lr,{durationMs:t(),phase:i,eventType:s.type});yield s}}catch(s){if(e.signal?.aborted&&!this.abortController?.signal.aborted)return;if(!e.signal?.aborted&&!this.isAbortError(s))this.captureTaskLifecycleFailure(s,i,t());throw s}}captureTaskLifecycleFailure(e,t,n){this.captureTaskLifecycle(ur,{durationMs:n,error:e,errorClass:xr(e),phase:t})}captureTaskLifecycle(e,t={}){let n=B(this.config.sessionId);pr(this.config.telemetry,{event:e,sessionId:n,ulid:n,agentId:this.state.agentId,conversationId:B(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 B(this.config.messageModelInfo?.provider)??this.telemetryProviderId}getTelemetryModelId(){return B(this.config.messageModelInfo?.id)??this.telemetryModelId}isAbortError(e){return e instanceof ge||this.abortController?.signal.aborted===!0}captureUnexpectedReasoningTokens(e,t){if(!op(e)||(t.reasoningTokenCount??0)<=0)return;let n=t.reasoningTokenCount;if(n===void 0)return;dr(this.config.telemetry,{sessionId:this.config.sessionId,agentId:this.state.agentId,runId:this.state.runId,iteration:this.state.iteration,providerId:this.config.messageModelInfo?.provider,modelId:this.config.messageModelInfo?.id,requestedThinking:!1,reasoningTokenCount:n})}async prepareTurnForModelRequest(e,t){if(!this.config.prepareTurn)return e;let n=t?.overflowRecovery===!0,i=t?.requireSmallerRequest===!0,r=await this.config.prepareTurn({agentId:this.state.agentId,conversationId:this.config.conversationId,parentAgentId:this.state.parentAgentId??null,iteration:this.state.iteration,messages:e.messages,systemPrompt:e.systemPrompt,tools:e.tools,model:{id:this.config.messageModelInfo?.id,provider:this.config.messageModelInfo?.provider},signal:e.signal,overflowRecovery:n||void 0,previousRequestInputTokens:this.state.lastRequestInputTokens>0?this.state.lastRequestInputTokens:void 0,emitStatusNotice:(s,a)=>{this.emit({type:"status-notice",snapshot:this.snapshot(),message:s,metadata:a})},reportUsage:(s)=>{this.updateUsage(s,void 0,{auxiliary:!0})}});if(i){if(!(r?.messages!==void 0&&JSON.stringify(r.messages).length<JSON.stringify(e.messages).length))throw new Re(Kd,this.state.lastError)}if(!r)return e;let o=e;if(r.messages){let s=G(r.messages);o={...o,messages:G(s)}}if(r.systemPrompt!==void 0)o={...o,systemPrompt:r.systemPrompt};return o}async consumePendingUserMessage(){let e=this.config.consumePendingUserMessage;if(!e)return;let t=(await e())?.trim();if(!t)return;let n=ue("user",[{type:"text",text:t}],{userRunSpan:0});return this.steerAwaitingResume=!0,this.state.messages.push(n),await this.emit({type:"message-added",snapshot:this.snapshot(),message:n}),n}async updateUsage(e,t,n){let i=n?.auxiliary===!0;if(this.state.usage={inputTokens:this.state.usage.inputTokens+(e.inputTokens??0),outputTokens:this.state.usage.outputTokens+(e.outputTokens??0),cacheReadTokens:this.state.usage.cacheReadTokens+(e.cacheReadTokens??0),cacheWriteTokens:this.state.usage.cacheWriteTokens+(e.cacheWriteTokens??0),reasoningTokenCount:(this.state.usage.reasoningTokenCount??0)+(e.reasoningTokenCount??0),totalCost:(this.state.usage.totalCost??0)+(e.totalCost??0)},t)this.state.lastRequestTimings=t;if(e.inputTokens!==void 0&&!i)this.lastRequestTokens=(e.inputTokens??0)+(e.outputTokens??0);await this.emit({type:"usage-updated",snapshot:this.snapshot(),usage:ne(this.state.usage),...t?{timings:t}:{},...n?.outputSplit?{outputSplit:n.outputSplit}:{},...i?{auxiliary:!0}:{}})}async executeToolCalls(e){this.pendingHookContexts=[];let t=[];for(let d of e){let y=Date.now(),h=await this.prepareToolExecution(d);h.prepareMs=Date.now()-y,t.push(h)}let n=Array(t.length),i=[],r=[],o=this.config.maxParallelToolCalls>1;t.forEach((d,y)=>{let h=this.tools.get(d.toolCall.toolName);(o&&h?.lifecycle?.boundsOwnConcurrency===!0?r:i).push(y)});let s=r.map(async(d)=>{n[d]=await this.executePreparedTool(t[d])}),a=Math.min(Math.max(1,this.config.maxParallelToolCalls),i.length);if(a<=1){for(let d of i)n[d]=await this.executePreparedTool(t[d]);return await Promise.all(s),n}let u=0,c=async()=>{while(!0){let d=u;if(u+=1,d>=i.length)return;let y=i[d];n[y]=await this.executePreparedTool(t[y])}};return await Promise.all([...Array.from({length:a},()=>c()),...s]),n}attachTurnNotes(e,t){let n=[],i=this.repetitionNudgeFor(t);if(i)n.push(i);let r=this.config.completionPolicy?.afterToolsReminder?.();if(r)n.push(r);if(this.pendingToolIntentNudge)n.push(this.pendingToolIntentNudge),this.pendingToolIntentNudge=void 0;if(n.length===0)return[];let o=e.at(-1)?.content??[],s;for(let a=o.length-1;a>=0&&!s;a-=1){let u=o[a];if(u?.type==="tool-result")s=u}if(!s)return n;return s.note=[s.note,...n].filter(Boolean).join(`
100
+
101
+ `),[]}findCompletingToolMessage(e,t){for(let n=0;n<e.length;n+=1){let i=e[n];if(this.tools.get(i.toolName)?.lifecycle?.completesRun!==!0)continue;let r=t[n],o=r?.content.find((s)=>s.type==="tool-result"&&s.toolCallId===i.toolCallId);if(o&&!o.isError)return r}return}async prepareToolExecution(e){let t=this.tools.get(e.toolName),n=e.input,i,r=e.metadata&&typeof e.metadata==="object"&&!Array.isArray(e.metadata)?e.metadata:void 0;if(typeof r?.inputParseError==="string")i=r.inputParseError;let o=t?void 0:this.config.unavailableToolReasons?.[e.toolName];if(o)i=`Tool "${e.toolName}" is not offered in this session: ${o}`;let s=r?.toolSource&&typeof r.toolSource==="object"&&!Array.isArray(r.toolSource)?r.toolSource:void 0;if(s?.executionMode==="provider")i=`Tool execution is disabled for provider ${typeof s.providerId==="string"?s.providerId:"provider"}`;if(t&&!i)n=Ie(n,t.inputSchema);let a;if(t&&!i)for(let u of this.hooks.beforeTool){let c=await u({snapshot:this.snapshot(),tool:t,toolCall:{...e,input:n},input:n});if(c?.input!==void 0)n=c.input;if(c?.policy)a={...a,...c.policy};if(c?.appendContext?.trim())this.pendingHookContexts.push(Zt({source:"PreToolUse",toolCall:e},c.appendContext));if(this.applyStopControl(c),c?.skip){i=c.reason??`Tool ${t.name} was blocked by a runtime hook`;break}}if(t&&!i){let u={...ep(e.toolName,this.config.toolPolicies),...a};if(u.enabled===!1)i=`Tool "${e.toolName}" is disabled by policy`;else if(u.autoApprove===!1){let c=await this.requestToolApproval(e,n,u);if(!c.approved)i=`${c.reason??"Tool was not executed"} -- ${Wi}`}}return{toolCall:{...e,input:n},tool:t,input:n,skipReason:i}}async requestToolApproval(e,t,n){let i=this.config.requestToolApproval;if(!i)return{approved:!1,reason:`Tool "${e.toolName}" requires approval but no approval callback is configured`};try{return await i({sessionId:this.config.sessionId?.trim()||this.config.conversationId?.trim()||this.state.runId||this.state.agentId,agentId:this.state.agentId,conversationId:this.config.conversationId?.trim()||this.state.runId||this.state.agentId,iteration:this.state.iteration,toolCallId:e.toolCallId,toolName:e.toolName,input:t,policy:n})}catch(r){return{approved:!1,reason:`Tool "${e.toolName}" approval request failed: ${r instanceof Error?r.message:String(r)}`}}}async executePreparedTool(e){let t=new Date,n=Date.now();await this.emit({type:"tool-started",snapshot:this.snapshot(),iteration:this.state.iteration,toolCall:e.toolCall});let i=Date.now(),r;if(e.skipReason)r={output:{error:e.skipReason},isError:!0};else if(!e.tool)r={output:{error:`Unknown tool: ${e.toolCall.toolName}`},isError:!0};else try{if(r={output:await e.tool.execute(e.input,{sessionId:this.config.sessionId,agentId:this.state.agentId,conversationId:this.config.conversationId,runId:this.state.runId??me("run"),iteration:this.state.iteration,toolCallId:e.toolCall.toolCallId,signal:this.abortController?.signal,metadata:this.config.toolContextMetadata,snapshot:this.snapshot(),reportStoppedForUser:()=>{this.stoppedForUserBy=e.toolCall.toolName},emitUpdate:(d)=>{this.emit({type:"tool-updated",snapshot:this.snapshot(),iteration:this.state.iteration,toolCall:e.toolCall,update:d})}})},this.stoppedForUserBy!==void 0&&this.stoppedForUserBy!==e.toolCall.toolName&&e.tool.readOnly!==!0)this.stoppedForUserBy=void 0}catch(c){r={output:{error:c instanceof Error?c.message:String(c)},isError:!0}}let o=new Date,s=Date.now(),a=Math.max(0,o.getTime()-t.getTime());if(e.tool)for(let c of this.hooks.afterTool){let d=await c({snapshot:this.snapshot(),tool:e.tool,toolCall:e.toolCall,input:e.input,result:r,startedAt:t,endedAt:o,durationMs:a});if(d?.appendContext?.trim())this.pendingHookContexts.push(Zt({source:"PostToolUse",toolCall:e.toolCall},d.appendContext));if(this.applyStopControl(d),d?.result)r=d.result}this.trace(`tool ${e.toolCall.toolName} prepare=${e.prepareMs??-1}ms preEmit=${i-n}ms exec=${s-i}ms afterHooks=${Date.now()-s}ms total=${Date.now()-n}ms | hooks ${this.topEventHooks()}`),this.config.logger?.debug?.(`[tool-timing] ${e.toolCall.toolName} prepare=${e.prepareMs??-1}ms preEmit=${i-n}ms exec=${s-i}ms afterHooks=${Date.now()-s}ms total=${Date.now()-n}ms | hooks ${this.topEventHooks()}`);let u=ue("tool",[{type:"tool-result",toolCallId:e.toolCall.toolCallId,toolName:e.toolCall.toolName,output:r.output,isError:r.isError}]);return await this.emit({type:"tool-finished",snapshot:this.snapshot(),iteration:this.state.iteration,toolCall:e.toolCall,message:u}),u}finishRun(e,t,n){return this.state.status=e,{agentId:this.state.agentId,agentRole:this.state.agentRole,runId:this.state.runId??me("run"),status:e,iterations:this.state.iteration,outputText:n??xe(t??this.findLastAssistantMessage()),messages:G(this.state.messages),usage:ne(this.state.usage)}}findLastAssistantMessage(){return[...this.state.messages].reverse().find((e)=>e.role==="assistant")}async onReasoningLoopCut(e){this.reasoningLoopStreak+=1;let t=(this.config.reasoningLoopDetection===!1?void 0:this.config.reasoningLoopDetection?.maxConsecutiveTrips)??ut.maxConsecutiveTrips,n=Ft(e),i=this.reasoningLoopStreak>=t,r=i?await this.config.onReasoningLoopLimitReached?.({iteration:this.state.iteration,consecutiveTrips:this.reasoningLoopStreak,maxConsecutiveTrips:t,diagnosis:n}):void 0,o=r?.action==="continue"?r.guidance?.trim():void 0,s=i&&r?.action!=="continue";if(await this.emit({type:"status-notice",snapshot:this.snapshot(),message:s?`${n} Ending the run after ${this.reasoningLoopStreak} turns cut for this.`:i?`${n} That is ${this.reasoningLoopStreak} turns cut for this, and the run was to end here.`:`${n} Cutting the request and continuing.`,metadata:{kind:"reasoning_loop",reason:"reasoning_loop",phase:s?"aborted":"cut",iteration:this.state.iteration,consecutiveTrips:this.reasoningLoopStreak,verdict:e}}),s){this.abort(new ge(n)),this.throwIfAborted();return}if(o)await this.addUserReminderMessage(o)}toolArgumentNames(){let e=new Set;for(let t of this.tools.values()){let n=t.inputSchema?.properties;for(let i of Object.keys(n??{}))e.add(i)}return[...e]}async onToolIntentCut(e){this.toolIntentCutStreak+=1,this.pendingToolIntentNudge=Ar(e);let t=e.toolName?`\`${e.toolName}\``:"a tool";this.config.logger?.log?.(`[tool-intent] cut a call to ${t} at iteration ${this.state.iteration}: intent passed ${e.maxChars} characters`),await this.emit({type:"status-notice",snapshot:this.snapshot(),message:`The model was writing its reasoning into the \`intent\` of a call to ${t} (past ${e.maxChars.toLocaleString("en-US")} characters). Cutting the request and asking it to make the call again.`,metadata:{kind:"tool_intent_overrun",reason:"tool_intent_overrun",phase:"cut",iteration:this.state.iteration,overrun:e}})}throwIfAborted(){if(this.abortController?.signal.aborted)throw this.normalizeAbortError()}normalizeAbortError(){let e=this.abortController?.signal.reason;if(e instanceof Error)return e;if(typeof e==="string")return Error(e);return Error(this.state.lastError??"Run aborted")}eventHookMs=new Map;noteEventHookMs(e,t,n){let i=`${e}#${t}`,r=this.eventHookMs.get(i);if(r)r.ms+=n,r.n+=1;else this.eventHookMs.set(i,{ms:n,n:1})}topEventHooks(e=4){return[...this.eventHookMs.entries()].sort((t,n)=>n[1].ms-t[1].ms).slice(0,e).map(([t,n])=>`${t}=${Math.round(n.ms)}ms/${n.n}`).join(" ")}trace(e){kd(e),this.config.logger?.debug?.(`[timing] ${e}`)}async emit(e){let t=hp(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)hr(this.config.telemetry,{component:"agents",operation:"agent.run",error:e.error,severity:"error",handled:!1,context:{...t,providerId:this.getTelemetryProviderId(),modelId:this.getTelemetryModelId(),...this.state.lastFinishReason?{finishReason:this.state.lastFinishReason}:{}}});break;default:if(!pp.has(e.type))this.config.logger?.debug?.(`Agent event: ${e.type}`,t);break}switch(e.type){case"assistant-text-delta":case"assistant-reasoning-delta":case"assistant-media":case"tool-updated":break;default:this.config.telemetry?.capture({event:`agent.${e.type}`,properties:t});break}let n=0;for(let i of this.listeners){let r=Date.now();i(e),this.noteEventHookMs(e.type,`listener${n}`,Date.now()-r),n+=1}for(let i=0;i<this.hooks.onEvent.length;i+=1){let r=Date.now();await this.hooks.onEvent[i](e),this.noteEventHookMs(e.type,i,Date.now()-r)}}applyStopControl(e){if(!e?.stop)return;if(e.reason)this.state.lastError=e.reason;throw new mt(e.reason)}}var cp={no_tool_call:"the turn ended without calling anything — asking the model to carry on",unparsed_tool_call:"a tool call was written as text and never ran — asking for it again",announced_intent:"the model described the next step instead of taking it — asking it to make the call",non_convergence:"several turns of thinking with no work done — asking for a different approach",silent_repetition:"the turn repeated what the last one said — asking for a different approach"};function dp(e){return cp[e]??`nudged: ${e}`}var pp=new Set(["assistant-text-delta","assistant-reasoning-delta","assistant-media","tool-updated"]);function hp(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 fp(e){return new De(e)}var mp=De;function gp(e){return new De(e)}function Pr(e){let t=e.search(/<\|?tool_call\|?>/),n=(t<0?e:e.slice(t)).replace(/\s+/g," ").trim(),i=5381;for(let r=0;r<n.length;r++)i=(i<<5)+i+n.charCodeAt(r)|0;return`${n.length}:${i}`}export{mp as Agent,De as AgentRuntime,ge as AgentRuntimeAbortError,Wd as DEFAULT_MAX_NO_TOOL_CALL_NUDGES,$r as DEFAULT_NO_TOOL_CALL_TURN_STREAK_LIMIT,ut as DEFAULT_REASONING_LOOP_GUARD,fe as DEFAULT_REASONING_REPETITION,gd as DEFAULT_TOOL_INTENT_MAX_CHARS,Lr as NON_CONVERGENCE_MIN_REASONING_CHARS,ct as ReasoningLoopGuard,ze as ToolCallAssembler,gp as createAgent,fp as createAgentRuntime,Bt as createRepetitionNudger,od as createTool,Ft as describeReasoningLoop,wr as describeRepetition,dd as finishToolCalls,pt as isRepetitionLoop,qt as isToolIntentGuardEnabled,dt as measureReasoningRepetition,yd as setToolIntentGuardEnabled};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cerebriline/agents",
3
- "version": "4.100.253",
3
+ "version": "4.100.254",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/mann1x/cline.git",
@@ -9,8 +9,8 @@
9
9
  "main": "dist/index.js",
10
10
  "dependencies": {
11
11
  "nanoid": "^5.1.7",
12
- "@cerebriline/llms": "4.100.253",
13
- "@cerebriline/shared": "4.100.253"
12
+ "@cerebriline/llms": "4.100.254",
13
+ "@cerebriline/shared": "4.100.254"
14
14
  },
15
15
  "exports": {
16
16
  ".": {