@codragraph/cli 2.1.5 → 2.2.0-rc.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (113) hide show
  1. package/README.md +18 -13
  2. package/dist/cli/analyze.d.ts +9 -4
  3. package/dist/cli/analyze.js +37 -13
  4. package/dist/cli/graphpack.d.ts +48 -0
  5. package/dist/cli/graphpack.js +217 -0
  6. package/dist/cli/index.js +81 -3
  7. package/dist/cli/status.d.ts +1 -1
  8. package/dist/cli/status.js +8 -0
  9. package/dist/cli/tool.d.ts +11 -2
  10. package/dist/cli/tool.js +138 -8
  11. package/dist/core/adaptive-profile.d.ts +52 -0
  12. package/dist/core/adaptive-profile.js +180 -0
  13. package/dist/core/cgdb/cgdb-adapter.d.ts +34 -5
  14. package/dist/core/cgdb/cgdb-adapter.js +418 -5
  15. package/dist/core/cgdb/pool-adapter.js +1 -1
  16. package/dist/core/graphpack/index.d.ts +14 -0
  17. package/dist/core/graphpack/index.js +474 -0
  18. package/dist/core/graphpack/types.d.ts +129 -0
  19. package/dist/core/graphpack/types.js +4 -0
  20. package/dist/core/ingestion/pipeline-phases/parse-impl.js +3 -1
  21. package/dist/core/ingestion/pipeline-phases/structure.js +19 -3
  22. package/dist/core/ingestion/pipeline.d.ts +10 -0
  23. package/dist/core/run-analyze.d.ts +27 -2
  24. package/dist/core/run-analyze.js +598 -27
  25. package/dist/core/search/bm25-index.d.ts +19 -0
  26. package/dist/core/search/bm25-index.js +68 -29
  27. package/dist/core/semantic/relationships.d.ts +36 -0
  28. package/dist/core/semantic/relationships.js +261 -0
  29. package/dist/mcp/local/local-backend.js +48 -3
  30. package/dist/mcp/resources.js +125 -0
  31. package/dist/mcp/tools.js +105 -0
  32. package/dist/server/api.js +112 -0
  33. package/dist/storage/repo-manager.d.ts +29 -0
  34. package/dist/web/assets/agent-CQNZQ-hg.js +1139 -0
  35. package/dist/web/assets/architectureDiagram-UL44E2DR-B5_goS_i.js +36 -0
  36. package/dist/web/assets/blockDiagram-7IZFK4PR-D7ZAlDyv.js +132 -0
  37. package/dist/web/assets/{c4Diagram-DFAF54RM-C4Hl3J2U.js → c4Diagram-Y2BXMSZH-Djcgm_54.js} +1 -1
  38. package/dist/web/assets/{chunk-7RZVMHOQ-BitYcNVR.js → chunk-3SSMPTDK-Cv2Zy2FO.js} +1 -1
  39. package/dist/web/assets/{chunk-TBF5ZNIQ-DL5stGM1.js → chunk-6764PJDD-Cppb-jH-.js} +1 -1
  40. package/dist/web/assets/{chunk-KSICW3F5-BYzvDLNI.js → chunk-AZZRMDJM-BHlLC7p3.js} +1 -1
  41. package/dist/web/assets/{chunk-AEOMTBSW-BgTIXPsY.js → chunk-JQRUD6KW-3F8Zg-1N.js} +1 -1
  42. package/dist/web/assets/chunk-KRXBNO2N-C0mbN9a7.js +1 -0
  43. package/dist/web/assets/chunk-LCXTWHL2-BoiuJpIF.js +231 -0
  44. package/dist/web/assets/{chunk-O5ABG6QK-dHwHzA6n.js → chunk-LII3EMHJ-Dqq0Qguw.js} +1 -1
  45. package/dist/web/assets/chunk-RG4AUYOV-Bl5F_gDs.js +206 -0
  46. package/dist/web/assets/{chunk-TU3PZOEN-RLyvLcv-.js → chunk-T5OCTHI4-B2tIcggA.js} +1 -1
  47. package/dist/web/assets/chunk-W44A43WB-BHe37iN7.js +13 -0
  48. package/dist/web/assets/{chunk-RWUO3TPN-BgRTY0_k.js → chunk-ZXARS5L4-wcrIaQvY.js} +1 -1
  49. package/dist/web/assets/classDiagram-KGZ6W3CR-IbI6v_24.js +1 -0
  50. package/dist/web/assets/classDiagram-v2-72OJOZXJ-IbI6v_24.js +1 -0
  51. package/dist/web/assets/{cose-bilkent-PNC4W37J-DVhePRYg.js → cose-bilkent-UX7MHV2Q-BWr7v0Wr.js} +1 -1
  52. package/dist/web/assets/dagre-ND4H6XIP-De5LIh1B.js +4 -0
  53. package/dist/web/assets/diagram-3NCE3AQN-Dd22FSHy.js +43 -0
  54. package/dist/web/assets/diagram-GF46GFSD-Cev3THY8.js +24 -0
  55. package/dist/web/assets/diagram-HNR7UZ2L-D8Z8RQGs.js +3 -0
  56. package/dist/web/assets/diagram-QXG6HAR7-B8VOJOiE.js +24 -0
  57. package/dist/web/assets/diagram-WEQXMOUZ-va1bLoMD.js +10 -0
  58. package/dist/web/assets/{erDiagram-GCSMX5X6-C3dhDFA8.js → erDiagram-L5TCEMPS-B3_9uAoP.js} +5 -5
  59. package/dist/web/assets/{flowDiagram-OTCZ4VVT-CWSFWmhr.js → flowDiagram-H6V6AXG4-98m6maI1.js} +9 -9
  60. package/dist/web/assets/ganttDiagram-JCBTUEKG-vE2nzETb.js +292 -0
  61. package/dist/web/assets/gitGraphDiagram-S2ZK5IYY-DKc8uUg_.js +106 -0
  62. package/dist/web/assets/index-BAhe1HSk.css +1 -0
  63. package/dist/web/assets/index-VTKdaklA.js +1415 -0
  64. package/dist/web/assets/infoDiagram-3YFTVSEB-DYP-Srzx.js +2 -0
  65. package/dist/web/assets/{ishikawaDiagram-YMYX4NHK-DUoJvNP2.js → ishikawaDiagram-BNXS4ZKH-QZnkpmmb.js} +3 -3
  66. package/dist/web/assets/{journeyDiagram-SO5T7YLQ-RMFPNNqz.js → journeyDiagram-M6C3CM3L-B5ojIuqu.js} +1 -1
  67. package/dist/web/assets/{kanban-definition-LJHFXRCJ-BzpDs1K9.js → kanban-definition-75IXJCU3-BJA8liRR.js} +4 -4
  68. package/dist/web/assets/{katex-GD7MH7QM-DBQvrix-.js → katex-K3KEBU37-DUqZiCRL.js} +1 -1
  69. package/dist/web/assets/mindmap-definition-2TDM6QVE-BQj5yylD.js +96 -0
  70. package/dist/web/assets/pieDiagram-CU6KROY3-4eSrPiQz.js +30 -0
  71. package/dist/web/assets/quadrantDiagram-VICAPDV7-PzxN8j55.js +7 -0
  72. package/dist/web/assets/{requirementDiagram-M5DCFWZL-DLHOVTSv.js → requirementDiagram-JXO7QTGE-CtplTc5y.js} +2 -2
  73. package/dist/web/assets/sankeyDiagram-URQDO5SZ-CoSgvkxv.js +40 -0
  74. package/dist/web/assets/sequenceDiagram-VS2MUI6T-D7ygyXvJ.js +162 -0
  75. package/dist/web/assets/stateDiagram-7D4R322I-v01gvwji.js +1 -0
  76. package/dist/web/assets/stateDiagram-v2-36443NZ5-DFD2b8_x.js +1 -0
  77. package/dist/web/assets/{timeline-definition-5SPVSISX-TRSDRgPw.js → timeline-definition-O6YCAMPW-CTI3M65J.js} +4 -4
  78. package/dist/web/assets/{vennDiagram-IE5QUKF5-DNy7HRBM.js → vennDiagram-MWXL3ELB-RnB0XMP7.js} +6 -6
  79. package/dist/web/assets/wardley-L42UT6IY-5TKZOOLJ-C-ZcgEBb.js +173 -0
  80. package/dist/web/assets/wardleyDiagram-CUQ6CDDI-EwRi4kwo.js +78 -0
  81. package/dist/web/assets/{xychartDiagram-ZHJ5623Y-Dr9r7a35.js → xychartDiagram-N2JHSOCM-DA38II6y.js} +4 -4
  82. package/dist/web/index.html +2 -2
  83. package/package.json +2 -2
  84. package/vendor/node_modules/node-addon-api/node_addon_api_except.stamp +0 -0
  85. package/dist/web/assets/agent-D5lb0zXz.js +0 -1089
  86. package/dist/web/assets/architectureDiagram-EMZXCZ2Q-CZtc99v_.js +0 -36
  87. package/dist/web/assets/blockDiagram-IGV67L2C-BtoUp-6Y.js +0 -132
  88. package/dist/web/assets/chunk-3GS5O3IE-DkUjU0WD.js +0 -231
  89. package/dist/web/assets/chunk-3YCYZ6SJ-CQkVgT_z.js +0 -1
  90. package/dist/web/assets/chunk-H3VCZNTA-Cx5XV_aC.js +0 -13
  91. package/dist/web/assets/chunk-HN6EAY2L-BBnyTNdB.js +0 -1
  92. package/dist/web/assets/chunk-PK6DOVAG-CvsEnugt.js +0 -206
  93. package/dist/web/assets/classDiagram-PPOCWD7C-DTr8QIOf.js +0 -1
  94. package/dist/web/assets/classDiagram-v2-23LJLIIU-DTr8QIOf.js +0 -1
  95. package/dist/web/assets/dagre-E77IOHMT-Dzx0A6ZU.js +0 -4
  96. package/dist/web/assets/diagram-H7BISOXX-CC9pRew1.js +0 -43
  97. package/dist/web/assets/diagram-JC5VWROH-Bau_i9tf.js +0 -24
  98. package/dist/web/assets/diagram-LXUTUG65-D9_FM2Gt.js +0 -10
  99. package/dist/web/assets/diagram-WEHSV5V5-BMlayouL.js +0 -24
  100. package/dist/web/assets/ganttDiagram-MUNLMDZQ-D3a67Yol.js +0 -292
  101. package/dist/web/assets/gitGraphDiagram-3HKGZ4G3-7jmry-vM.js +0 -106
  102. package/dist/web/assets/index-BgeqpYgd.js +0 -1415
  103. package/dist/web/assets/index-CT0GtFLZ.css +0 -1
  104. package/dist/web/assets/infoDiagram-MN7RKWGX-G7lhP0Ib.js +0 -2
  105. package/dist/web/assets/mindmap-definition-2EUWGEK5-Bk0O4roa.js +0 -96
  106. package/dist/web/assets/pieDiagram-3IATQBI2-DKU7kpgS.js +0 -30
  107. package/dist/web/assets/quadrantDiagram-E256RVCF-BY0TGWCS.js +0 -7
  108. package/dist/web/assets/sankeyDiagram-L3NBLAOT-DVMj5rX2.js +0 -10
  109. package/dist/web/assets/sequenceDiagram-ZOUHS735-CJC73bV-.js +0 -157
  110. package/dist/web/assets/stateDiagram-MLPALWAM-BCFyESls.js +0 -1
  111. package/dist/web/assets/stateDiagram-v2-B5LQ5ZB2-DahzzIca.js +0 -1
  112. package/dist/web/assets/wardley-RL74JXVD-BCRCBASE-B-eZEzf9.js +0 -161
  113. package/dist/web/assets/wardleyDiagram-XU3VSMPF-BP-r1xzR.js +0 -20
@@ -1,1089 +0,0 @@
1
- var sC=Object.defineProperty;var aC=(t,e,n)=>e in t?sC(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var p=(t,e,n)=>aC(t,typeof e!="symbol"?e+"":e,n);import{bI as ng,bJ as iC,bK as oC}from"./index-BgeqpYgd.js";import{buildDynamicSystemPrompt as cC}from"./context-builder-22jU3V56.js";const uC=["File","Folder","Function","Class","Interface","Method","CodeElement","Community","Process","FeatureCluster","Section","Struct","Enum","Macro","Typedef","Union","Namespace","Trait","Impl","TypeAlias","Const","Static","Variable","Property","Record","Delegate","Annotation","Constructor","Template","Module","Route","Tool"],B0=["CONTAINS","DEFINES","IMPORTS","CALLS","EXTENDS","IMPLEMENTS","HAS_METHOD","HAS_PROPERTY","ACCESSES","METHOD_OVERRIDES","OVERRIDES","METHOD_IMPLEMENTS","MEMBER_OF","STEP_IN_PROCESS","HANDLES_ROUTE","FETCHES","HANDLES_TOOL","ENTRY_POINT_OF","WRAPS","QUERIES","FEATURE_MEMBER_OF","FEATURE_DEPENDS_ON"];var Ey=Object.defineProperty,ue=(t,e)=>{let n={};for(var r in t)Ey(n,r,{get:t[r],enumerable:!0});return Ey(n,Symbol.toStringTag,{value:"Module"}),n};function z0(t){const e=Symbol.for(t);return{brand(n,r){var i,o;const s=r?Symbol.for(`${t}.${r}`):e;class a extends(o=n,i=s,o){constructor(...l){super(...l);p(this,i,!0)}static isInstance(l){return typeof l=="object"&&l!==null&&s in l&&l[s]===!0}}return Object.defineProperty(a,"name",{value:n.name}),a},sub(n){return z0(`${t}.${n}`)},isInstance(n){return typeof n=="object"&&n!==null&&e in n&&n[e]===!0}}}const lC=z0("langchain");var dC=ue({ContextOverflowError:()=>sg,LangChainError:()=>rg,ModelAbortError:()=>gp,addLangChainErrorFields:()=>Lc,ns:()=>zd});function Lc(t,e){return t.lc_error_code=e,t.message=`${t.message}
2
-
3
- Troubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${e}/
4
- `,t}const zd=lC.sub("error");var rg=class extends zd.brand(Error){constructor(e){super(e);p(this,"name","LangChainError");Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}},gp=class extends zd.brand(rg,"model-abort"){constructor(e,n){super(e);p(this,"name","ModelAbortError");p(this,"partialOutput");this.partialOutput=n}},sg=class H0 extends zd.brand(rg,"context-overflow"){constructor(n){super(n??"Input exceeded the model's context window.");p(this,"name","ContextOverflowError");p(this,"cause")}static fromError(n){const r=new H0(n.message);return r.cause=n,r}};function Jo(t){return!!(t&&typeof t=="object"&&"type"in t&&t.type==="tool_call")}function hC(t){return!!(t&&typeof t=="object"&&"toolCall"in t&&t.toolCall!=null&&typeof t.toolCall=="object"&&"id"in t.toolCall&&typeof t.toolCall.id=="string")}var Wl=class extends Error{constructor(e,n){super(e);p(this,"output");this.output=n}};function Gl(t,e=ki){t=t.trim();const n=t.indexOf("```");if(n===-1)return e(t);let r=t.substring(n+3);r.startsWith(`json
5
- `)?r=r.substring(5):r.startsWith("json")?r=r.substring(4):r.startsWith(`
6
- `)&&(r=r.substring(1));const s=r.indexOf("```");let a=r;return s!==-1&&(a=r.substring(0,s)),e(a.trim())}function fC(t){try{return JSON.parse(t)}catch{}const e=t.trim();if(e.length===0)throw new Error("Unexpected end of JSON input");let n=0;function r(){for(;n<e.length&&/\s/.test(e[n]);)n+=1}function s(){if(e[n]!=='"')throw new Error(`Expected '"' at position ${n}, got '${e[n]}'`);n+=1;let l="",d=!1;for(;n<e.length;){const f=e[n];if(d){if(f==="n")l+=`
7
- `;else if(f==="t")l+=" ";else if(f==="r")l+="\r";else if(f==="\\")l+="\\";else if(f==='"')l+='"';else if(f==="b")l+="\b";else if(f==="f")l+="\f";else if(f==="/")l+="/";else if(f==="u"){const h=e.substring(n+1,n+5);if(/^[0-9A-Fa-f]{0,4}$/.test(h))h.length===4?l+=String.fromCharCode(Number.parseInt(h,16)):l+=`u${h}`,n+=h.length;else throw new Error(`Invalid unicode escape sequence '\\u${h}' at position ${n}`)}else throw new Error(`Invalid escape sequence '\\${f}' at position ${n}`);d=!1}else if(f==="\\")d=!0;else{if(f==='"')return n+=1,l;l+=f}n+=1}return d&&(l+="\\"),l}function a(){const l=n;let d="";if(e[n]==="-"&&(d+="-",n+=1),n<e.length&&e[n]==="0"&&(d+="0",n+=1,e[n]>="0"&&e[n]<="9"))throw new Error(`Invalid number at position ${l}`);if(n<e.length&&e[n]>="1"&&e[n]<="9")for(;n<e.length&&e[n]>="0"&&e[n]<="9";)d+=e[n],n+=1;if(n<e.length&&e[n]===".")for(d+=".",n+=1;n<e.length&&e[n]>="0"&&e[n]<="9";)d+=e[n],n+=1;if(n<e.length&&(e[n]==="e"||e[n]==="E"))for(d+=e[n],n+=1,n<e.length&&(e[n]==="+"||e[n]==="-")&&(d+=e[n],n+=1);n<e.length&&e[n]>="0"&&e[n]<="9";)d+=e[n],n+=1;if(d==="-")return-0;const f=Number.parseFloat(d);if(Number.isNaN(f))throw n=l,new Error(`Invalid number '${d}' at position ${l}`);return f}function i(){if(r(),n>=e.length)throw new Error(`Unexpected end of input at position ${n}`);const l=e[n];if(l==="{")return c();if(l==="[")return o();if(l==='"')return s();if("null".startsWith(e.substring(n,n+4)))return n+=Math.min(4,e.length-n),null;if("true".startsWith(e.substring(n,n+4)))return n+=Math.min(4,e.length-n),!0;if("false".startsWith(e.substring(n,n+5)))return n+=Math.min(5,e.length-n),!1;if(l==="-"||l>="0"&&l<="9")return a();throw new Error(`Unexpected character '${l}' at position ${n}`)}function o(){if(e[n]!=="[")throw new Error(`Expected '[' at position ${n}, got '${e[n]}'`);const l=[];if(n+=1,r(),n>=e.length)return l;if(e[n]==="]")return n+=1,l;for(;n<e.length;){if(r(),n>=e.length||(l.push(i()),r(),n>=e.length))return l;if(e[n]==="]")return n+=1,l;if(e[n]===","){n+=1;continue}throw new Error(`Expected ',' or ']' at position ${n}, got '${e[n]}'`)}return l}function c(){if(e[n]!=="{")throw new Error(`Expected '{' at position ${n}, got '${e[n]}'`);const l={};if(n+=1,r(),n>=e.length)return l;if(e[n]==="}")return n+=1,l;for(;n<e.length;){if(r(),n>=e.length)return l;const d=s();if(r(),n>=e.length)return l;if(e[n]!==":")throw new Error(`Expected ':' at position ${n}, got '${e[n]}'`);if(n+=1,r(),n>=e.length||(l[d]=i(),r(),n>=e.length))return l;if(e[n]==="}")return n+=1,l;if(e[n]===","){n+=1;continue}throw new Error(`Expected ',' or '}' at position ${n}, got '${e[n]}'`)}return l}const u=i();if(r(),n<e.length)throw new Error(`Unexpected character '${e[n]}' at position ${n}`);return u}function ki(t){try{return typeof t>"u"?null:fC(t)}catch{return null}}var pC=function(t,e){if(typeof t!="string")throw new TypeError("Expected a string");return e=typeof e>"u"?"_":e,t.replace(/([a-z\d])([A-Z])/g,"$1"+e+"$2").replace(/([A-Z]+)([A-Z][a-z\d]+)/g,"$1"+e+"$2").toLowerCase()};const mC=ng(pC);var ag={exports:{}};const gC=/[\p{Lu}]/u,_C=/[\p{Ll}]/u,Ay=/^[\p{Lu}](?![\p{Lu}])/gu,V0=/([\p{Alpha}\p{N}_]|$)/u,Z0=/[_.\- ]+/,yC=new RegExp("^"+Z0.source),Iy=new RegExp(Z0.source+V0.source,"gu"),xy=new RegExp("\\d+"+V0.source,"gu"),wC=(t,e,n)=>{let r=!1,s=!1,a=!1;for(let i=0;i<t.length;i++){const o=t[i];r&&gC.test(o)?(t=t.slice(0,i)+"-"+t.slice(i),r=!1,a=s,s=!0,i++):s&&a&&_C.test(o)?(t=t.slice(0,i-1)+"-"+t.slice(i-1),a=s,s=!1,r=!0):(r=e(o)===o&&n(o)!==o,a=s,s=n(o)===o&&e(o)!==o)}return t},bC=(t,e)=>(Ay.lastIndex=0,t.replace(Ay,n=>e(n))),vC=(t,e)=>(Iy.lastIndex=0,xy.lastIndex=0,t.replace(Iy,(n,r)=>e(r)).replace(xy,n=>e(n))),W0=(t,e)=>{if(!(typeof t=="string"||Array.isArray(t)))throw new TypeError("Expected the input to be `string | string[]`");if(e={pascalCase:!1,preserveConsecutiveUppercase:!1,...e},Array.isArray(t)?t=t.map(a=>a.trim()).filter(a=>a.length).join("-"):t=t.trim(),t.length===0)return"";const n=e.locale===!1?a=>a.toLowerCase():a=>a.toLocaleLowerCase(e.locale),r=e.locale===!1?a=>a.toUpperCase():a=>a.toLocaleUpperCase(e.locale);return t.length===1?e.pascalCase?r(t):n(t):(t!==n(t)&&(t=wC(t,n,r)),t=t.replace(yC,""),e.preserveConsecutiveUppercase?t=bC(t,n):t=n(t),e.pascalCase&&(t=r(t.charAt(0))+t.slice(1)),vC(t,r))};ag.exports=W0;ag.exports.default=W0;var SC=ag.exports;const TC=ng(SC);function EC(t,e){return(e==null?void 0:e[t])||mC(t)}function AC(t,e){return(e==null?void 0:e[t])||TC(t)}function G0(t,e,n){const r={};for(const s in t)Object.hasOwn(t,s)&&(r[e(s,n)]=t[s]);return r}const q0="__lc_escaped__";function IC(t){return"lc"in t||Object.keys(t).length===1&&"__lc_escaped__"in t}function xC(t){return{[q0]:t}}function K0(t){return Object.keys(t).length===1&&"__lc_escaped__"in t}function kC(t){return t!==null&&typeof t=="object"&&"lc_serializable"in t&&typeof t.toJSON=="function"}function OC(t){var n;let e;return t!==null&&typeof t=="object"?"lc_id"in t&&Array.isArray(t.lc_id)?e=t.lc_id:e=[((n=t.constructor)==null?void 0:n.name)??"Object"]:e=[typeof t],{lc:1,type:"not_implemented",id:e}}function _p(t,e=new WeakSet){if(t!==null&&typeof t=="object"&&!Array.isArray(t)){if(e.has(t))return OC(t);if(kC(t))return t;e.add(t);const n=t;if(IC(n))return e.delete(t),xC(n);const r={};for(const[s,a]of Object.entries(n))r[s]=_p(a,e);return e.delete(t),r}return Array.isArray(t)?t.map(n=>_p(n,e)):t}function yp(t){if(t!==null&&typeof t=="object"&&!Array.isArray(t)){const e=t;if(K0(e))return e[q0];const n={};for(const[r,s]of Object.entries(e))n[r]=yp(s);return n}return Array.isArray(t)?t.map(e=>yp(e)):t}var CC=ue({Serializable:()=>ar,get_lc_unique_name:()=>Hd});function ky(t){return Array.isArray(t)?[...t]:{...t}}function RC(t,e){const n=ky(t);for(const[r,s]of Object.entries(e)){const[a,...i]=r.split(".").reverse();let o=n;for(const c of i.reverse()){if(o[c]===void 0)break;o[c]=ky(o[c]),o=o[c]}o[a]!==void 0&&(o[a]={lc:1,type:"secret",id:[s]})}return n}function Hd(t){const e=Object.getPrototypeOf(t);return typeof t.lc_name=="function"&&(typeof e.lc_name!="function"||t.lc_name()!==e.lc_name())?t.lc_name():t.name}var ar=class J0{constructor(e,...n){p(this,"lc_serializable",!1);p(this,"lc_kwargs");this.lc_serializable_keys!==void 0?this.lc_kwargs=Object.fromEntries(Object.entries(e||{}).filter(([r])=>{var s;return(s=this.lc_serializable_keys)==null?void 0:s.includes(r)})):this.lc_kwargs=e??{}}static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,Hd(this.constructor)]}get lc_secrets(){}get lc_attributes(){}get lc_aliases(){}get lc_serializable_keys(){}toJSON(){if(!this.lc_serializable)return this.toJSONNotImplemented();if(this.lc_kwargs instanceof J0||typeof this.lc_kwargs!="object"||Array.isArray(this.lc_kwargs))return this.toJSONNotImplemented();const e={},n={},r=Object.keys(this.lc_kwargs).reduce((o,c)=>(o[c]=c in this?this[c]:this.lc_kwargs[c],o),{});for(let o=Object.getPrototypeOf(this);o;o=Object.getPrototypeOf(o))Object.assign(e,Reflect.get(o,"lc_aliases",this)),Object.assign(n,Reflect.get(o,"lc_secrets",this)),Object.assign(r,Reflect.get(o,"lc_attributes",this));Object.keys(n).forEach(o=>{let c=this,u=r;const[l,...d]=o.split(".").reverse();for(const f of d.reverse()){if(!(f in c)||c[f]===void 0)return;(!(f in u)||u[f]===void 0)&&(typeof c[f]=="object"&&c[f]!=null?u[f]={}:Array.isArray(c[f])&&(u[f]=[])),c=c[f],u=u[f]}l in c&&c[l]!==void 0&&(u[l]=u[l]||c[l])});const s={},a=new WeakSet;a.add(this);for(const[o,c]of Object.entries(r))s[o]=_p(c,a);const i=G0(Object.keys(n).length?RC(s,n):s,EC,e);return{lc:1,type:"constructor",id:this.lc_id,kwargs:i}}toJSONNotImplemented(){return{lc:1,type:"not_implemented",id:this.lc_id}}};function ir(t){return typeof t=="object"&&t!==null&&"type"in t&&typeof t.type=="string"&&"source_type"in t&&(t.source_type==="url"||t.source_type==="base64"||t.source_type==="text"||t.source_type==="id")}function ig(t){return ir(t)&&t.source_type==="url"&&"url"in t&&typeof t.url=="string"}function og(t){return ir(t)&&t.source_type==="base64"&&"data"in t&&typeof t.data=="string"}function $C(t){return ir(t)&&t.source_type==="text"&&"text"in t&&typeof t.text=="string"}function X0(t){return ir(t)&&t.source_type==="id"&&"id"in t&&typeof t.id=="string"}function Y0(t){if(ir(t)){if(t.source_type==="url")return{type:"image_url",image_url:{url:t.url}};if(t.source_type==="base64"){if(!t.mime_type)throw new Error("mime_type key is required for base64 data.");return{type:"image_url",image_url:{url:`data:${t.mime_type};base64,${t.data}`}}}}throw new Error("Unsupported source type. Only 'url' and 'base64' are supported.")}function wp(t){const e=t.split(";")[0].split("/");if(e.length!==2)throw new Error(`Invalid mime type: "${t}" - does not match type/subtype format.`);const n=e[0].trim(),r=e[1].trim();if(n===""||r==="")throw new Error(`Invalid mime type: "${t}" - type or subtype is empty.`);const s={};for(const a of t.split(";").slice(1)){const i=a.split("=");if(i.length!==2)throw new Error(`Invalid parameter syntax in mime type: "${t}".`);const o=i[0].trim(),c=i[1].trim();if(o==="")throw new Error(`Invalid parameter syntax in mime type: "${t}".`);s[o]=c}return{type:n,subtype:r,parameters:s}}function Ir({dataUrl:t,asTypedArray:e=!1}){const n=t.match(/^data:(\w+\/\w+);base64,([A-Za-z0-9+/]+=*)$/);let r;if(n){r=n[1].toLowerCase();const s=e?Uint8Array.from(atob(n[2]),a=>a.charCodeAt(0)):n[2];return{mime_type:r,data:s}}}function jc(t,e){if(t.type==="text"){if(!e.fromStandardTextBlock)throw new Error(`Converter for ${e.providerName} does not implement \`fromStandardTextBlock\` method.`);return e.fromStandardTextBlock(t)}if(t.type==="image"){if(!e.fromStandardImageBlock)throw new Error(`Converter for ${e.providerName} does not implement \`fromStandardImageBlock\` method.`);return e.fromStandardImageBlock(t)}if(t.type==="audio"){if(!e.fromStandardAudioBlock)throw new Error(`Converter for ${e.providerName} does not implement \`fromStandardAudioBlock\` method.`);return e.fromStandardAudioBlock(t)}if(t.type==="file"){if(!e.fromStandardFileBlock)throw new Error(`Converter for ${e.providerName} does not implement \`fromStandardFileBlock\` method.`);return e.fromStandardFileBlock(t)}throw new Error(`Unable to convert content block type '${t.type}' to provider-specific format: not recognized.`)}function oe(t,e){return be(t)&&t.type===e}function be(t){return typeof t=="object"&&t!==null}function On(t){return Array.isArray(t)}function B(t){return typeof t=="string"}function yr(t){return typeof t=="number"}function cg(t){return t instanceof Uint8Array}function Oy(t){try{return JSON.parse(t)}catch{return}}const Ds=t=>t();function NC(t){if(t.type==="char_location"&&B(t.document_title)&&yr(t.start_char_index)&&yr(t.end_char_index)&&B(t.cited_text)){const{document_title:e,start_char_index:n,end_char_index:r,cited_text:s,...a}=t;return{...a,type:"citation",source:"char",title:e??void 0,startIndex:n,endIndex:r,citedText:s}}if(t.type==="page_location"&&B(t.document_title)&&yr(t.start_page_number)&&yr(t.end_page_number)&&B(t.cited_text)){const{document_title:e,start_page_number:n,end_page_number:r,cited_text:s,...a}=t;return{...a,type:"citation",source:"page",title:e??void 0,startIndex:n,endIndex:r,citedText:s}}if(t.type==="content_block_location"&&B(t.document_title)&&yr(t.start_block_index)&&yr(t.end_block_index)&&B(t.cited_text)){const{document_title:e,start_block_index:n,end_block_index:r,cited_text:s,...a}=t;return{...a,type:"citation",source:"block",title:e??void 0,startIndex:n,endIndex:r,citedText:s}}if(t.type==="web_search_result_location"&&B(t.url)&&B(t.title)&&B(t.encrypted_index)&&B(t.cited_text)){const{url:e,title:n,encrypted_index:r,cited_text:s,...a}=t;return{...a,type:"citation",source:"url",url:e,title:n,startIndex:Number(r),endIndex:Number(r),citedText:s}}if(t.type==="search_result_location"&&B(t.source)&&B(t.title)&&yr(t.start_block_index)&&yr(t.end_block_index)&&B(t.cited_text)){const{source:e,title:n,start_block_index:r,end_block_index:s,cited_text:a,...i}=t;return{...i,type:"citation",source:"search",url:e,title:n??void 0,startIndex:r,endIndex:s,citedText:a}}}function Q0(t){if(oe(t,"document")&&be(t.source)&&"type"in t.source){if(t.source.type==="base64"&&B(t.source.media_type)&&B(t.source.data))return{type:"file",mimeType:t.source.media_type,data:t.source.data};if(t.source.type==="url"&&B(t.source.url))return{type:"file",url:t.source.url};if(t.source.type==="file"&&B(t.source.file_id))return{type:"file",fileId:t.source.file_id};if(t.source.type==="text"&&B(t.source.data))return{type:"file",mimeType:String(t.source.media_type??"text/plain"),data:t.source.data}}else if(oe(t,"image")&&be(t.source)&&"type"in t.source){if(t.source.type==="base64"&&B(t.source.media_type)&&B(t.source.data))return{type:"image",mimeType:t.source.media_type,data:t.source.data};if(t.source.type==="url"&&B(t.source.url))return{type:"image",url:t.source.url};if(t.source.type==="file"&&B(t.source.file_id))return{type:"image",fileId:t.source.file_id}}}function PC(t){function*e(){for(const n of t){const r=Q0(n);r?yield r:yield n}}return Array.from(e())}function Cy(t){function*e(){var r;const n=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;for(const s of n){if(oe(s,"text")&&B(s.text)){const{text:a,citations:i,...o}=s;if(On(i)&&i.length){const c=i.reduce((u,l)=>{const d=NC(l);return d?[...u,d]:u},[]);yield{...o,type:"text",text:a,annotations:c};continue}else{yield{...o,type:"text",text:a};continue}}else if(oe(s,"thinking")&&B(s.thinking)){const{thinking:a,signature:i,...o}=s;yield{...o,type:"reasoning",reasoning:a,signature:i};continue}else if(oe(s,"redacted_thinking")){yield{type:"non_standard",value:s};continue}else if(oe(s,"tool_use")&&B(s.name)&&B(s.id)){yield{type:"tool_call",id:s.id,name:s.name,args:s.input};continue}else if(oe(s,"input_json_delta")){if(LC(t)&&((r=t.tool_call_chunks)!=null&&r.length)){const a=t.tool_call_chunks[0];yield{type:"tool_call_chunk",id:a.id,name:a.name,args:a.args,index:a.index};continue}}else if(oe(s,"server_tool_use")&&B(s.name)&&B(s.id)){const{name:a,id:i}=s;if(a==="web_search"){yield{id:i,type:"server_tool_call",name:"web_search",args:{query:Ds(()=>{if(typeof s.input=="string")return s.input;if(be(s.input)&&B(s.input.query))return s.input.query;if(B(s.partial_json)){const o=Oy(s.partial_json);if(o!=null&&o.query)return o.query}return""})}};continue}else if(s.name==="code_execution"){yield{id:i,type:"server_tool_call",name:"code_execution",args:{code:Ds(()=>{if(typeof s.input=="string")return s.input;if(be(s.input)&&B(s.input.code))return s.input.code;if(B(s.partial_json)){const o=Oy(s.partial_json);if(o!=null&&o.code)return o.code}return""})}};continue}}else if(oe(s,"web_search_tool_result")&&B(s.tool_use_id)&&On(s.content)){const{content:a,tool_use_id:i}=s;yield{type:"server_tool_call_result",name:"web_search",toolCallId:i,status:"success",output:{urls:a.reduce((o,c)=>oe(c,"web_search_result")?[...o,c.url]:o,[])}};continue}else if(oe(s,"code_execution_tool_result")&&B(s.tool_use_id)&&be(s.content)){yield{type:"server_tool_call_result",name:"code_execution",toolCallId:s.tool_use_id,status:"success",output:s.content};continue}else if(oe(s,"mcp_tool_use")){yield{id:s.id,type:"server_tool_call",name:"mcp_tool_use",args:s.input};continue}else if(oe(s,"mcp_tool_result")&&B(s.tool_use_id)&&be(s.content)){yield{type:"server_tool_call_result",name:"mcp_tool_use",toolCallId:s.tool_use_id,status:"success",output:s.content};continue}else if(oe(s,"container_upload")){yield{type:"server_tool_call",name:"container_upload",args:s.input};continue}else if(oe(s,"search_result")){yield{id:s.id,type:"non_standard",value:s};continue}else if(oe(s,"tool_result")){yield{id:s.id,type:"non_standard",value:s};continue}else{const a=Q0(s);if(a){yield a;continue}}yield{type:"non_standard",value:s}}}return Array.from(e())}const MC={translateContent:Cy,translateContentChunk:Cy};function LC(t){return typeof(t==null?void 0:t._getType)=="function"&&typeof t.concat=="function"&&t._getType()==="ai"}function jC(t){return ig(t)?{type:t.type,mimeType:t.mime_type,url:t.url,metadata:t.metadata}:og(t)?{type:t.type,mimeType:t.mime_type??"application/octet-stream",data:t.data,metadata:t.metadata}:X0(t)?{type:t.type,mimeType:t.mime_type,fileId:t.id,metadata:t.metadata}:t}function UC(t){return t.map(jC)}function DC(t){return!!(oe(t,"image_url")&&be(t.image_url)||oe(t,"input_audio")&&be(t.input_audio)||oe(t,"file")&&be(t.file))}function FC(t){if(oe(t,"image_url")&&be(t.image_url)&&B(t.image_url.url)){const e=Ir({dataUrl:t.image_url.url});return e?{type:"image",mimeType:e.mime_type,data:e.data}:{type:"image",url:t.image_url.url}}else{if(oe(t,"input_audio")&&be(t.input_audio)&&B(t.input_audio.data)&&B(t.input_audio.format))return{type:"audio",data:t.input_audio.data,mimeType:`audio/${t.input_audio.format}`};if(oe(t,"file")&&be(t.file)&&B(t.file.data)){const e=Ir({dataUrl:t.file.data});if(e)return{type:"file",data:e.data,mimeType:e.mime_type};if(B(t.file.file_id))return{type:"file",fileId:t.file.file_id}}}return t}function BC(t){const e=[];typeof t.content=="string"?t.content.length>0&&e.push({type:"text",text:t.content}):e.push(...ug(t.content));for(const n of t.tool_calls??[])e.push({type:"tool_call",id:n.id,name:n.name,args:n.args});return e}function zC(t){const e=[];typeof t.content=="string"?t.content.length>0&&e.push({type:"text",text:t.content}):e.push(...ug(t.content));for(const n of t.tool_calls??[])e.push({type:"tool_call",id:n.id,name:n.name,args:n.args});return e}function ug(t){const e=[];for(const n of t)DC(n)?e.push(FC(n)):e.push(n);return e}function HC(t){if(t.type==="url_citation"){const{url:e,title:n,start_index:r,end_index:s}=t;return{type:"citation",url:e,title:n,startIndex:r,endIndex:s}}if(t.type==="file_citation"){const{file_id:e,filename:n,index:r}=t;return{type:"citation",title:n,startIndex:r,endIndex:r,fileId:e}}return t}function eS(t){function*e(){var r;be((r=t.additional_kwargs)==null?void 0:r.reasoning)&&On(t.additional_kwargs.reasoning.summary)&&(yield{type:"reasoning",reasoning:t.additional_kwargs.reasoning.summary.reduce((s,a)=>be(a)&&B(a.text)?`${s}${a.text}`:s,"")});const n=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;for(const s of n)if(oe(s,"text")){const{text:a,annotations:i,phase:o,extras:c,...u}=s,l=be(c)?{...c}:{};B(o)&&(l.phase=o);const d=Object.keys(l).length>0?{extras:l}:{};Array.isArray(i)?yield{...u,...d,type:"text",text:String(a),annotations:i.map(HC)}:yield{...u,...d,type:"text",text:String(a)}}for(const s of t.tool_calls??[])yield{type:"tool_call",id:s.id,name:s.name,args:s.args};if(be(t.additional_kwargs)&&On(t.additional_kwargs.tool_outputs))for(const s of t.additional_kwargs.tool_outputs){if(oe(s,"web_search_call")){const a={};if(be(s.action)&&B(s.action.query)&&(a.query=s.action.query),yield{id:s.id,type:"server_tool_call",name:"web_search",args:a},s.status==="completed"||s.status==="failed"){const i={};be(s.action)&&(i.action=s.action),yield{type:"server_tool_call_result",toolCallId:B(s.id)?s.id:"",status:s.status==="completed"?"success":"error",output:i}}continue}else if(oe(s,"file_search_call")){yield{id:s.id,type:"server_tool_call",name:"file_search",args:{queries:On(s.queries)?s.queries:[]}},(s.status==="completed"||s.status==="failed")&&(yield{type:"server_tool_call_result",toolCallId:B(s.id)?s.id:"",status:s.status==="completed"?"success":"error",output:On(s.results)?{results:s.results}:{}});continue}else if(oe(s,"computer_call")){yield{type:"non_standard",value:s};continue}else if(oe(s,"code_interpreter_call")){if(B(s.code)&&(yield{id:s.id,type:"server_tool_call",name:"code_interpreter",args:{code:s.code}}),On(s.outputs)){const a=Ds(()=>{if(s.status!=="in_progress"){if(s.status==="completed")return 0;if(s.status==="incomplete")return 127;if(s.status!=="interpreting"&&s.status==="failed")return 1}});for(const i of s.outputs)if(oe(i,"logs")){yield{type:"server_tool_call_result",toolCallId:s.id??"",status:"success",output:{type:"code_interpreter_output",returnCode:a??0,stderr:[0,void 0].includes(a)?void 0:String(i.logs),stdout:[0,void 0].includes(a)?String(i.logs):void 0}};continue}}continue}else if(oe(s,"mcp_call")){yield{id:s.id,type:"server_tool_call",name:"mcp_call",args:s.input};continue}else if(oe(s,"mcp_list_tools")){yield{id:s.id,type:"server_tool_call",name:"mcp_list_tools",args:s.input};continue}else if(oe(s,"mcp_approval_request")){yield{type:"non_standard",value:s};continue}else if(oe(s,"tool_search_call")){const a={};be(s.arguments)&&Object.assign(a,s.arguments);const i={};B(s.execution)&&(i.execution=s.execution),B(s.status)&&(i.status=s.status),B(s.call_id)&&(i.call_id=s.call_id),yield{id:B(s.id)?s.id:"",type:"server_tool_call",name:"tool_search",args:a,...Object.keys(i).length>0?{extras:i}:{}};continue}else if(oe(s,"tool_search_output")){const a={name:"tool_search"};B(s.execution)&&(a.execution=s.execution),yield{type:"server_tool_call_result",toolCallId:B(s.id)?s.id:"",status:s.status==="completed"?"success":s.status==="failed"?"error":"success",output:{tools:On(s.tools)?s.tools:[]},extras:a};continue}else if(oe(s,"image_generation_call")){B(s.result)&&(yield{type:"image",mimeType:"image/png",data:s.result,id:B(s.id)?s.id:void 0,metadata:{status:B(s.status)?s.status:void 0}}),yield{type:"non_standard",value:s};continue}be(s)&&(yield{type:"non_standard",value:s})}}return Array.from(e())}function VC(t){function*e(){yield*eS(t);for(const n of t.tool_call_chunks??[])yield{type:"tool_call_chunk",id:n.id,name:n.name,args:n.args}}return Array.from(e())}const ZC={translateContent:t=>typeof t.content=="string"?BC(t):eS(t),translateContentChunk:t=>typeof t.content=="string"?zC(t):VC(t)};function tS(t){return typeof t=="object"&&t!==null&&"type"in t&&"content"in t&&(typeof t.content=="string"||Array.isArray(t.content))}function WC(t,e="pretty"){return e==="pretty"?GC(t):JSON.stringify(t)}function GC(t){const e=[],n=` ${t.type.charAt(0).toUpperCase()+t.type.slice(1)} Message `,r=Math.floor((80-n.length)/2),s="=".repeat(r),a=n.length%2===0?s:`${s}=`;if(e.push(`${s}${n}${a}`),t.type==="ai"){const i=t;if(i.tool_calls&&i.tool_calls.length>0){e.push("Tool Calls:");for(const o of i.tool_calls){e.push(` ${o.name} (${o.id})`),e.push(` Call ID: ${o.id}`),e.push(" Args:");for(const[c,u]of Object.entries(o.args))e.push(` ${c}: ${typeof u=="object"?JSON.stringify(u):u}`)}}}if(t.type==="tool"){const i=t;i.name&&e.push(`Name: ${i.name}`)}return typeof t.content=="string"&&t.content.trim()&&(e.length>1&&e.push(""),e.push(t.content)),e.join(`
8
- `)}const Mh=Symbol.for("langchain.message");function Ry(t){return Array.isArray(t)?t:typeof t=="string"?t===""?[]:[{type:"text",text:t}]:t==null?[]:[t]}function gs(t,e){if(typeof t=="string")return t===""?e:typeof e=="string"?t+e:Array.isArray(e)&&e.length===0?t:Array.isArray(e)&&e.some(n=>ir(n))?[{type:"text",source_type:"text",text:t},...e]:[{type:"text",text:t},...e];if(Array.isArray(e)){const n=Ry(t);return Oi(n,e)??[...n,...e]}else return e===""?t:Array.isArray(t)&&t.some(n=>ir(n))?[...t,{type:"file",source_type:"text",text:e}]:[...Ry(t),{type:"text",text:e}]}function nS(t,e){return t==="error"||e==="error"?"error":"success"}function qC(t,e){function n(r,s){if(typeof r!="object"||r===null||r===void 0)return r;if(s>=e)return Array.isArray(r)?"[Array]":"[Object]";if(Array.isArray(r))return r.map(i=>n(i,s+1));const a={};for(const i of Object.keys(r))a[i]=n(r[i],s+1);return a}return JSON.stringify(n(t,0),null,2)}var L0,bn=class extends ar{constructor(e){const n=typeof e=="string"||Array.isArray(e)?{content:e}:e;n.additional_kwargs||(n.additional_kwargs={}),n.response_metadata||(n.response_metadata={});super(n);p(this,"lc_namespace",["langchain_core","messages"]);p(this,"lc_serializable",!0);p(this,L0,!0);p(this,"id");p(this,"name");p(this,"content");p(this,"additional_kwargs");p(this,"response_metadata");this.name=n.name,n.content===void 0&&n.contentBlocks!==void 0?(this.content=n.contentBlocks,this.response_metadata={output_version:"v1",...n.response_metadata}):n.content!==void 0?(this.content=n.content??[],this.response_metadata=n.response_metadata):(this.content=[],this.response_metadata=n.response_metadata),this.additional_kwargs=n.additional_kwargs,this.id=n.id}get lc_aliases(){return{additional_kwargs:"additional_kwargs",response_metadata:"response_metadata"}}_getType(){return this.type}getType(){return this._getType()}get text(){return typeof this.content=="string"?this.content:Array.isArray(this.content)?this.content.map(e=>typeof e=="string"?e:e.type==="text"?e.text:"").join(""):""}get contentBlocks(){const e=typeof this.content=="string"?[{type:"text",text:this.content}]:this.content;return[UC,ug,PC].reduce((n,r)=>r(n),e)}toDict(){return{type:this.getType(),data:this.toJSON().kwargs}}static lc_name(){return"BaseMessage"}get _printableFields(){return{id:this.id,content:this.content,name:this.name,additional_kwargs:this.additional_kwargs,response_metadata:this.response_metadata}}static isInstance(e){return typeof e=="object"&&e!==null&&Mh in e&&e[Mh]===!0&&tS(e)}_updateId(e){this.id=e,this.lc_kwargs.id=e}get[(L0=Mh,Symbol.toStringTag)](){return this.constructor.lc_name()}[Symbol.for("nodejs.util.inspect.custom")](e){if(e===null)return this;const n=qC(this._printableFields,Math.max(4,e));return`${this.constructor.lc_name()} ${n}`}toFormattedString(e="pretty"){return WC(this,e)}};function KC(t){return Array.isArray(t)&&t.every(e=>typeof e.index=="number")}const rS=["index","created","timestamp"];function dn(t,e,n){const r=(n==null?void 0:n.ignoreKeys)??rS;if(t==null&&e==null)return;if(t==null||e==null)return t??e;const s={...t};for(const[a,i]of Object.entries(e))if(s[a]==null)s[a]=i;else{if(i==null)continue;if(typeof s[a]!=typeof i||Array.isArray(s[a])!==Array.isArray(i))throw new Error(`field[${a}] already exists in the message chunk, but with a different type.`);if(typeof s[a]=="string"){if(a==="type")continue;if(["id","name","output_version","model_provider"].includes(a))i&&(s[a]=i);else{if(r.includes(a))continue;s[a]+=i}}else if(typeof s[a]=="number"){if(r.includes(a))continue;s[a]=s[a]+i}else if(typeof s[a]=="object"&&!Array.isArray(s[a]))s[a]=dn(s[a],i,n);else if(Array.isArray(s[a]))s[a]=Oi(s[a],i,n);else{if(s[a]===i)continue;console.warn(`field[${a}] already exists in this message chunk and value has unsupported type.`)}}return s}function JC(t){return typeof t=="number"||typeof t=="string"}function $y(t){return typeof t!="object"||t===null||!("index"in t)?!1:JC(t.index)}function Ny(t){if(typeof t!="object"||t===null||!("id"in t))return!1;const e=t.id;return e!=null&&e!==""}function XC(t,e){const n=$y(e),r=Ny(e);return!n&&!r?-1:t.findIndex(s=>{const a=$y(s),i=Ny(s);return n&&a?s.index!==e.index?!1:i&&r?s.id===e.id:!0:!n&&!a&&r&&i?s.id===e.id:!1})}function Oi(t,e,n){if(!(t==null&&e==null)){if(t==null||e==null)return t||e;{const r=[...t];for(const s of e){const a=XC(r,s);if(a!==-1)r[a]=dn(r[a],s,n);else{if(typeof s=="object"&&s!==null&&"text"in s&&s.text==="")continue;r.push(s)}}return r}}}function sS(t,e,n){if(!(t==null&&e==null)){if(t==null||e==null)return t??e;if(typeof t!=typeof e)throw new Error(`Cannot merge objects of different types.
9
- Left ${typeof t}
10
- Right ${typeof e}`);if(typeof t=="string"&&typeof e=="string")return t+e;if(Array.isArray(t)&&Array.isArray(e))return Oi(t,e,n);if(typeof t=="object"&&typeof e=="object")return dn(t,e,n);if(t===e)return t;throw new Error(`Can not merge objects of different types.
11
- Left ${t}
12
- Right ${e}`)}}var na=class aS extends bn{static isInstance(e){if(!super.isInstance(e))return!1;let n=Object.getPrototypeOf(e);for(;n!==null;){if(n===aS.prototype)return!0;n=Object.getPrototypeOf(n)}return!1}};function iS(t){return typeof t.role=="string"}function wt(t){return typeof(t==null?void 0:t._getType)=="function"}function Ci(t){return na.isInstance(t)}var YC=ue({ToolMessage:()=>Rn,ToolMessageChunk:()=>Uc,defaultToolCallParser:()=>dg,isDirectToolOutput:()=>lg,isToolMessage:()=>Ia,isToolMessageChunk:()=>oS});function lg(t){return t!=null&&typeof t=="object"&&"lc_direct_tool_output"in t&&t.lc_direct_tool_output===!0}var Rn=class extends bn{constructor(e,n,r){const s=typeof e=="string"||Array.isArray(e)?{content:e,name:r,tool_call_id:n}:e;super(s);p(this,"lc_direct_tool_output",!0);p(this,"type","tool");p(this,"status");p(this,"tool_call_id");p(this,"metadata");p(this,"artifact");this.tool_call_id=s.tool_call_id,this.artifact=s.artifact,this.status=s.status,this.metadata=s.metadata}static lc_name(){return"ToolMessage"}get lc_aliases(){return{tool_call_id:"tool_call_id"}}static isInstance(e){return super.isInstance(e)&&e.type==="tool"}get _printableFields(){return{...super._printableFields,tool_call_id:this.tool_call_id,artifact:this.artifact}}},Uc=class extends na{constructor(e){super(e);p(this,"type","tool");p(this,"tool_call_id");p(this,"status");p(this,"artifact");this.tool_call_id=e.tool_call_id,this.artifact=e.artifact,this.status=e.status}static lc_name(){return"ToolMessageChunk"}concat(e){const n=this.constructor;return new n({content:gs(this.content,e.content),additional_kwargs:dn(this.additional_kwargs,e.additional_kwargs),response_metadata:dn(this.response_metadata,e.response_metadata),artifact:sS(this.artifact,e.artifact),tool_call_id:this.tool_call_id,id:this.id??e.id,status:nS(this.status,e.status)})}get _printableFields(){return{...super._printableFields,tool_call_id:this.tool_call_id,artifact:this.artifact}}};function dg(t){const e=[],n=[];for(const r of t)if(r.function){const s=r.function.name;try{const a=JSON.parse(r.function.arguments);e.push({name:s||"",args:a||{},id:r.id})}catch{n.push({name:s,args:r.function.arguments,id:r.id,error:"Malformed args."})}}else continue;return[e,n]}function Ia(t){return typeof t=="object"&&t!==null&&"getType"in t&&typeof t.getType=="function"&&t.getType()==="tool"}function oS(t){return t._getType()==="tool"}function hg(t){switch(t){case"csv":return"text/csv";case"doc":return"application/vnd.openxmlformats-officedocument.wordprocessingml.document";case"docx":return"application/vnd.openxmlformats-officedocument.wordprocessingml.document";case"html":return"text/html";case"md":return"text/markdown";case"pdf":return"application/pdf";case"txt":return"text/plain";case"xls":return"application/vnd.ms-excel";case"xlsx":return"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";case"gif":return"image/gif";case"jpeg":return"image/jpeg";case"jpg":return"image/jpeg";case"png":return"image/png";case"webp":return"image/webp";case"flv":return"video/flv";case"mkv":return"video/mkv";case"mov":return"video/mov";case"mp4":return"video/mp4";case"mpeg":return"video/mpeg";case"mpg":return"video/mpg";case"three_gp":return"video/three_gp";case"webm":return"video/webm";case"wmv":return"video/wmv";default:return"application/octet-stream"}}function QC(t){if(be(t.document)&&be(t.document.source)){const e=hg(be(t.document)&&B(t.document.format)?t.document.format:"");if(be(t.document.source)){if(be(t.document.source.s3Location)&&B(t.document.source.s3Location.uri))return{type:"file",mimeType:e,fileId:t.document.source.s3Location.uri};if(cg(t.document.source.bytes))return{type:"file",mimeType:e,data:t.document.source.bytes};if(B(t.document.source.text))return{type:"file",mimeType:e,data:Buffer.from(t.document.source.text).toString("base64")};if(On(t.document.source.content))return{type:"file",mimeType:e,data:t.document.source.content.reduce((n,r)=>be(r)&&B(r.text)?n+r.text:n,"")}}}return{type:"non_standard",value:t}}function e1(t){if(oe(t,"image")&&be(t.image)){const e=hg(be(t.image)&&B(t.image.format)?t.image.format:"");if(be(t.image.source)){if(be(t.image.source.s3Location)&&B(t.image.source.s3Location.uri))return{type:"image",mimeType:e,fileId:t.image.source.s3Location.uri};if(cg(t.image.source.bytes))return{type:"image",mimeType:e,data:t.image.source.bytes}}}return{type:"non_standard",value:t}}function t1(t){if(oe(t,"video")&&be(t.video)){const e=hg(be(t.video)&&B(t.video.format)?t.video.format:"");if(be(t.video.source)){if(be(t.video.source.s3Location)&&B(t.video.source.s3Location.uri))return{type:"video",mimeType:e,fileId:t.video.source.s3Location.uri};if(cg(t.video.source.bytes))return{type:"video",mimeType:e,data:t.video.source.bytes}}}return{type:"non_standard",value:t}}function Py(t){function*e(){const n=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;for(const r of n){if(oe(r,"cache_point")){yield{type:"non_standard",value:r};continue}else if(oe(r,"citations_content")&&be(r.citationsContent)){yield{type:"text",text:On(r.citationsContent.content)?r.citationsContent.content.reduce((s,a)=>be(a)&&B(a.text)?s+a.text:s,""):"",annotations:On(r.citationsContent.citations)?r.citationsContent.citations.reduce((s,a)=>{if(be(a)){const i=On(a.sourceContent)?a.sourceContent.reduce((c,u)=>be(u)&&B(u.text)?c+u.text:c,""):"",o=Ds(()=>{if(be(a.location)){const c=a.location.documentChar||a.location.documentPage||a.location.documentChunk;if(be(c))return{source:yr(c.documentIndex)?c.documentIndex.toString():void 0,startIndex:yr(c.start)?c.start:void 0,endIndex:yr(c.end)?c.end:void 0}}return{}});s.push({type:"citation",citedText:i,...o})}return s},[]):[]};continue}else if(oe(r,"document")&&be(r.document)){yield QC(r);continue}else if(oe(r,"guard_content")){yield{type:"non_standard",value:r};continue}else if(oe(r,"image")&&be(r.image)){yield e1(r);continue}else if(oe(r,"reasoning_content")&&B(r.reasoningText)){yield{type:"reasoning",reasoning:r.reasoningText};continue}else if(oe(r,"text")&&B(r.text)){yield{type:"text",text:r.text};continue}else if(oe(r,"tool_result")){yield{type:"non_standard",value:r};continue}else{if(oe(r,"tool_call"))continue;if(oe(r,"video")&&be(r.video)){yield t1(r);continue}}yield{type:"non_standard",value:r}}}return Array.from(e())}const n1={translateContent:Py,translateContentChunk:Py};function My(t){var r;const e=[],n=(r=t.additional_kwargs)==null?void 0:r.reasoning_content;if(B(n)&&n.length>0&&e.push({type:"reasoning",reasoning:n}),typeof t.content=="string")t.content.length>0&&e.push({type:"text",text:t.content});else for(const s of t.content)typeof s=="object"&&"type"in s&&s.type==="text"&&"text"in s&&B(s.text)&&e.push({type:"text",text:s.text});for(const s of t.tool_calls??[])e.push({type:"tool_call",id:s.id,name:s.name,args:s.args});return e}const r1={translateContent:My,translateContentChunk:My};function Ly(t){function*e(){const n=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;for(const r of n){if(oe(r,"text")&&B(r.text)){yield{type:"text",text:r.text};continue}else if(oe(r,"thinking")&&B(r.thinking)){yield{type:"reasoning",reasoning:r.thinking,...r.signature?{signature:r.signature}:{}};continue}else if(oe(r,"inlineData")&&be(r.inlineData)&&B(r.inlineData.mimeType)&&B(r.inlineData.data)){yield{type:"file",mimeType:r.inlineData.mimeType,data:r.inlineData.data};continue}else if(oe(r,"functionCall")&&be(r.functionCall)&&B(r.functionCall.name)&&be(r.functionCall.args)){yield{type:"tool_call",id:t.id,name:r.functionCall.name,args:r.functionCall.args};continue}else if(oe(r,"functionResponse")){yield{type:"non_standard",value:r};continue}else if(oe(r,"fileData")&&be(r.fileData)&&B(r.fileData.mimeType)&&B(r.fileData.fileUri)){yield{type:"file",mimeType:r.fileData.mimeType,fileId:r.fileData.fileUri};continue}else if(oe(r,"executableCode")){yield{type:"non_standard",value:r};continue}else if(oe(r,"codeExecutionResult")){yield{type:"non_standard",value:r};continue}yield{type:"non_standard",value:r}}}return Array.from(e())}const s1={translateContent:Ly,translateContentChunk:Ly};function jy(t){function*e(){const n=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;for(const r of n){if(oe(r,"reasoning")&&B(r.reasoning)){const s=Ds(()=>{var i;const a=n.indexOf(r);if(On((i=t.additional_kwargs)==null?void 0:i.signatures)&&a>=0)return t.additional_kwargs.signatures.at(a)});B(s)?yield{type:"reasoning",reasoning:r.reasoning,signature:s}:yield{type:"reasoning",reasoning:r.reasoning};continue}else if(oe(r,"thinking")&&B(r.thinking)){yield{type:"reasoning",reasoning:r.thinking,...r.signature?{signature:r.signature}:{}};continue}else if(oe(r,"text")&&B(r.text)){yield{type:"text",text:r.text};continue}else if(oe(r,"image_url")){if(B(r.image_url))if(r.image_url.startsWith("data:")){const s=r.image_url.match(/^data:([^;]+);base64,(.+)$/);s?yield{type:"image",data:s[2],mimeType:s[1]}:yield{type:"image",url:r.image_url}}else yield{type:"image",url:r.image_url};continue}else if(oe(r,"media")&&B(r.mimeType)&&B(r.data)){yield{type:"file",mimeType:r.mimeType,data:r.data};continue}yield{type:"non_standard",value:r}}}return Array.from(e())}const a1={translateContent:jy,translateContentChunk:jy};function Uy(t){var r;const e=[],n=(r=t.additional_kwargs)==null?void 0:r.reasoning;if(B(n)&&n.length>0&&e.push({type:"reasoning",reasoning:n}),typeof t.content=="string"){let s=t.content;const a=s.match(/<think>([\s\S]*?)<\/think>/);if(a){const i=a[1].trim();i.length>0&&e.push({type:"reasoning",reasoning:i}),s=s.replace(/<think>[\s\S]*?<\/think>/,"").trim()}s.length>0&&e.push({type:"text",text:s})}else for(const s of t.content)if(typeof s=="object"&&"type"in s&&s.type==="text"&&"text"in s&&B(s.text)){let a=s.text;const i=a.match(/<think>([\s\S]*?)<\/think>/);if(i){const o=i[1].trim();o.length>0&&e.push({type:"reasoning",reasoning:o}),a=a.replace(/<think>[\s\S]*?<\/think>/,"").trim()}a.length>0&&e.push({type:"text",text:a})}for(const s of t.tool_calls??[])e.push({type:"tool_call",id:s.id,name:s.name,args:s.args});return e}const i1={translateContent:Uy,translateContentChunk:Uy};function Dy(t){var r;const e=[],n=(r=t.additional_kwargs)==null?void 0:r.reasoning_content;if(B(n)&&n.length>0&&e.push({type:"reasoning",reasoning:n}),typeof t.content=="string")t.content.length>0&&e.push({type:"text",text:t.content});else for(const s of t.content)typeof s=="object"&&"type"in s&&s.type==="text"&&"text"in s&&B(s.text)&&e.push({type:"text",text:s.text});for(const s of t.tool_calls??[])e.push({type:"tool_call",id:s.id,name:s.name,args:s.args});return e}const o1={translateContent:Dy,translateContentChunk:Dy};function Fy(t){var r,s;const e=[];if(be((r=t.additional_kwargs)==null?void 0:r.reasoning)){const a=t.additional_kwargs.reasoning;if(On(a.summary)){const i=a.summary.reduce((o,c)=>be(c)&&B(c.text)?`${o}${c.text}`:o,"");i.length>0&&e.push({type:"reasoning",reasoning:i})}}const n=(s=t.additional_kwargs)==null?void 0:s.reasoning_content;if(B(n)&&n.length>0&&e.push({type:"reasoning",reasoning:n}),typeof t.content=="string")t.content.length>0&&e.push({type:"text",text:t.content});else for(const a of t.content)typeof a=="object"&&"type"in a&&a.type==="text"&&"text"in a&&B(a.text)&&e.push({type:"text",text:a.text});for(const a of t.tool_calls??[])e.push({type:"tool_call",id:a.id,name:a.name,args:a.args});return e}const c1={translateContent:Fy,translateContentChunk:Fy};function By(t){function*e(){const n=Ds(()=>{var r;if(typeof t.content=="string")return t.additional_kwargs.originalTextContentBlock?[{...t.additional_kwargs.originalTextContentBlock,type:"text"}]:[{type:"text",text:t.content}];{const s=(r=t.additional_kwargs)==null?void 0:r.originalTextContentBlock;if(s!=null&&s.thoughtSignature&&!t.content.some(a=>"thoughtSignature"in a)){const a=[...t.content];for(let i=a.length-1;i>=0;i--){const o=a[i];if(o.type==="text"&&!o.thought)return o.thoughtSignature=s.thoughtSignature,a}}return t.content}});for(const r of n){const s=Ds(()=>oe(r,"text")&&B(r.text)?{type:"text",text:r.text}:oe(r,"inlineData")&&be(r.inlineData)&&B(r.inlineData.mimeType)&&B(r.inlineData.data)?{type:"file",mimeType:r.inlineData.mimeType,data:r.inlineData.data}:oe(r,"functionCall")&&be(r.functionCall)&&B(r.functionCall.name)&&be(r.functionCall.args)?{type:"tool_call",id:t.id,name:r.functionCall.name,args:r.functionCall.args}:oe(r,"functionResponse")?{type:"non_standard",value:r}:oe(r,"fileData")&&be(r.fileData)&&B(r.fileData.mimeType)&&B(r.fileData.fileUri)?{type:"file",mimeType:r.fileData.mimeType,fileId:r.fileData.fileUri}:oe(r,"executableCode")?{type:"non_standard",value:r}:oe(r,"codeExecutionResult")?{type:"non_standard",value:r}:{type:"non_standard",value:r}),a=Ds(()=>"thought"in r&&r.thought?{type:"reasoning",reasoning:s.type==="text"?s.text:"",reasoningContentBlock:s}:s),i={thought:r.thought,thoughtSignature:r.thoughtSignature,partMetadata:r.partMetadata,...a};for(const o in i)i[o]===void 0&&delete i[o];yield i}}return Array.from(e())}const u1={translateContent:By,translateContentChunk:By};globalThis.lc_block_translators_registry??(globalThis.lc_block_translators_registry=new Map([["anthropic",MC],["bedrock-converse",n1],["deepseek",r1],["google",u1],["google-genai",s1],["google-vertexai",a1],["groq",i1],["ollama",o1],["openai",ZC],["xai",c1]]));function cS(t){return globalThis.lc_block_translators_registry.get(t)}function uS(t,e){return dn(t,e)??{}}function lS(t,e){const n={};return((t==null?void 0:t.audio)!==void 0||(e==null?void 0:e.audio)!==void 0)&&(n.audio=((t==null?void 0:t.audio)??0)+((e==null?void 0:e.audio)??0)),((t==null?void 0:t.image)!==void 0||(e==null?void 0:e.image)!==void 0)&&(n.image=((t==null?void 0:t.image)??0)+((e==null?void 0:e.image)??0)),((t==null?void 0:t.video)!==void 0||(e==null?void 0:e.video)!==void 0)&&(n.video=((t==null?void 0:t.video)??0)+((e==null?void 0:e.video)??0)),((t==null?void 0:t.document)!==void 0||(e==null?void 0:e.document)!==void 0)&&(n.document=((t==null?void 0:t.document)??0)+((e==null?void 0:e.document)??0)),((t==null?void 0:t.text)!==void 0||(e==null?void 0:e.text)!==void 0)&&(n.text=((t==null?void 0:t.text)??0)+((e==null?void 0:e.text)??0)),n}function l1(t,e){const n={...lS(t,e)};return((t==null?void 0:t.cache_read)!==void 0||(e==null?void 0:e.cache_read)!==void 0)&&(n.cache_read=((t==null?void 0:t.cache_read)??0)+((e==null?void 0:e.cache_read)??0)),((t==null?void 0:t.cache_creation)!==void 0||(e==null?void 0:e.cache_creation)!==void 0)&&(n.cache_creation=((t==null?void 0:t.cache_creation)??0)+((e==null?void 0:e.cache_creation)??0)),n}function d1(t,e){const n={...lS(t,e)};return((t==null?void 0:t.reasoning)!==void 0||(e==null?void 0:e.reasoning)!==void 0)&&(n.reasoning=((t==null?void 0:t.reasoning)??0)+((e==null?void 0:e.reasoning)??0)),n}function fg(t,e){return{input_tokens:((t==null?void 0:t.input_tokens)??0)+((e==null?void 0:e.input_tokens)??0),output_tokens:((t==null?void 0:t.output_tokens)??0)+((e==null?void 0:e.output_tokens)??0),total_tokens:((t==null?void 0:t.total_tokens)??0)+((e==null?void 0:e.total_tokens)??0),input_token_details:l1(t==null?void 0:t.input_token_details,e==null?void 0:e.input_token_details),output_token_details:d1(t==null?void 0:t.output_token_details,e==null?void 0:e.output_token_details)}}var De=class extends bn{constructor(e){var r;let n;if(typeof e=="string"||Array.isArray(e))n={content:e,tool_calls:[],invalid_tool_calls:[],additional_kwargs:{}};else{n=e;const s=(r=n.additional_kwargs)==null?void 0:r.tool_calls,a=n.tool_calls;s!=null&&s.length>0&&(a===void 0||a.length===0)&&console.warn(["New LangChain packages are available that more efficiently handle",`tool calling.
13
-
14
- Please upgrade your packages to versions that set`,"message tool calls. e.g., `pnpm install @langchain/anthropic`,","pnpm install @langchain/openai`, etc."].join(" "));try{if(s!=null&&a===void 0){const[i,o]=dg(s);n.tool_calls=i??[],n.invalid_tool_calls=o??[]}else n.tool_calls=n.tool_calls??[],n.invalid_tool_calls=n.invalid_tool_calls??[]}catch{n.tool_calls=[],n.invalid_tool_calls=[]}if(n.response_metadata!==void 0&&"output_version"in n.response_metadata&&n.response_metadata.output_version==="v1"&&(n.contentBlocks=n.content,n.content=void 0),n.contentBlocks!==void 0){n.tool_calls&&n.contentBlocks.push(...n.tool_calls.map(o=>({type:"tool_call",id:o.id,name:o.name,args:o.args})));const i=n.contentBlocks.filter(o=>o.type==="tool_call").filter(o=>{var c;return!((c=n.tool_calls)!=null&&c.some(u=>u.id===o.id&&u.name===o.name))});i.length>0&&(n.tool_calls=i.map(o=>({type:"tool_call",id:o.id,name:o.name,args:o.args})))}}super(n);p(this,"type","ai");p(this,"tool_calls",[]);p(this,"invalid_tool_calls",[]);p(this,"usage_metadata");typeof n!="string"&&(this.tool_calls=n.tool_calls??this.tool_calls,this.invalid_tool_calls=n.invalid_tool_calls??this.invalid_tool_calls),this.usage_metadata=n.usage_metadata}get lc_aliases(){return{...super.lc_aliases,tool_calls:"tool_calls",invalid_tool_calls:"invalid_tool_calls",usage_metadata:"usage_metadata"}}static lc_name(){return"AIMessage"}get contentBlocks(){if(this.response_metadata&&"output_version"in this.response_metadata&&this.response_metadata.output_version==="v1")return this.content;if(this.response_metadata&&"model_provider"in this.response_metadata&&typeof this.response_metadata.model_provider=="string"){const n=cS(this.response_metadata.model_provider);if(n)return n.translateContent(this)}const e=super.contentBlocks;if(this.tool_calls){const n=this.tool_calls.filter(r=>!e.some(s=>s.id===r.id&&s.name===r.name));e.push(...n.map(r=>({type:"tool_call",id:r.id,name:r.name,args:r.args})))}return e}get _printableFields(){return{...super._printableFields,tool_calls:this.tool_calls,invalid_tool_calls:this.invalid_tool_calls,usage_metadata:this.usage_metadata}}static isInstance(e){return super.isInstance(e)&&e.type==="ai"}};function or(t){return t._getType()==="ai"}function ql(t){return t._getType()==="ai"}var Qe=class extends na{constructor(e){let n;if(typeof e=="string"||Array.isArray(e))n={content:e,tool_calls:[],invalid_tool_calls:[],tool_call_chunks:[]};else if(e.tool_call_chunks===void 0||e.tool_call_chunks.length===0)n={...e,tool_calls:e.tool_calls??[],invalid_tool_calls:[],tool_call_chunks:[],usage_metadata:e.usage_metadata!==void 0?e.usage_metadata:void 0};else{const r=fS(e.tool_call_chunks??[]);n={...e,tool_call_chunks:r.tool_call_chunks,tool_calls:r.tool_calls,invalid_tool_calls:r.invalid_tool_calls,usage_metadata:e.usage_metadata!==void 0?e.usage_metadata:void 0}}super(n);p(this,"type","ai");p(this,"tool_calls",[]);p(this,"invalid_tool_calls",[]);p(this,"tool_call_chunks",[]);p(this,"usage_metadata");this.tool_call_chunks=n.tool_call_chunks??this.tool_call_chunks,this.tool_calls=n.tool_calls??this.tool_calls,this.invalid_tool_calls=n.invalid_tool_calls??this.invalid_tool_calls,this.usage_metadata=n.usage_metadata}get lc_aliases(){return{...super.lc_aliases,tool_calls:"tool_calls",invalid_tool_calls:"invalid_tool_calls",tool_call_chunks:"tool_call_chunks",usage_metadata:"usage_metadata"}}static lc_name(){return"AIMessageChunk"}get contentBlocks(){if(this.response_metadata&&"output_version"in this.response_metadata&&this.response_metadata.output_version==="v1")return this.content;if(this.response_metadata&&"model_provider"in this.response_metadata&&typeof this.response_metadata.model_provider=="string"){const n=cS(this.response_metadata.model_provider);if(n)return n.translateContent(this)}const e=super.contentBlocks;if(this.tool_calls&&typeof this.content!="string"){const n=this.content.filter(r=>r.type==="tool_call").map(r=>r.id);for(const r of this.tool_calls)r.id&&!n.includes(r.id)&&e.push({...r,type:"tool_call",id:r.id,name:r.name,args:r.args})}return e}get _printableFields(){return{...super._printableFields,tool_calls:this.tool_calls,tool_call_chunks:this.tool_call_chunks,invalid_tool_calls:this.invalid_tool_calls,usage_metadata:this.usage_metadata}}concat(e){const n={content:gs(this.content,e.content),additional_kwargs:dn(this.additional_kwargs,e.additional_kwargs),response_metadata:uS(this.response_metadata,e.response_metadata),tool_call_chunks:[],tool_calls:[],id:this.id??e.id};if(this.tool_call_chunks!==void 0||e.tool_call_chunks!==void 0){const s=Oi(this.tool_call_chunks,e.tool_call_chunks);s!==void 0&&s.length>0&&(n.tool_call_chunks=s)}if(this.tool_calls!==void 0||e.tool_calls!==void 0){const s=Oi(this.tool_calls,e.tool_calls);s!==void 0&&s.length>0&&(n.tool_calls=s)}(this.usage_metadata!==void 0||e.usage_metadata!==void 0)&&(n.usage_metadata=fg(this.usage_metadata,e.usage_metadata));const r=this.constructor;return new r(n)}static isInstance(e){return super.isInstance(e)&&e.type==="ai"}},Kr=class dS extends bn{constructor(n,r){(typeof n=="string"||Array.isArray(n))&&(n={content:n,role:r});super(n);p(this,"type","generic");p(this,"role");this.role=n.role}static lc_name(){return"ChatMessage"}static _chatMessageClass(){return dS}static isInstance(n){return super.isInstance(n)&&n.type==="generic"}get _printableFields(){return{...super._printableFields,role:this.role}}},Dc=class extends na{constructor(e,n){(typeof e=="string"||Array.isArray(e))&&(e={content:e,role:n});super(e);p(this,"type","generic");p(this,"role");this.role=e.role}static lc_name(){return"ChatMessageChunk"}concat(e){const n=this.constructor;return new n({content:gs(this.content,e.content),additional_kwargs:dn(this.additional_kwargs,e.additional_kwargs),response_metadata:dn(this.response_metadata,e.response_metadata),role:this.role,id:this.id??e.id})}static isInstance(e){return super.isInstance(e)&&e.type==="generic"}get _printableFields(){return{...super._printableFields,role:this.role}}};function h1(t){return t._getType()==="generic"}function f1(t){return t._getType()==="generic"}var Vd=class extends bn{constructor(e){super(e);p(this,"type","function");p(this,"name");this.name=e.name}static lc_name(){return"FunctionMessage"}},Fc=class extends na{constructor(){super(...arguments);p(this,"type","function")}static lc_name(){return"FunctionMessageChunk"}concat(e){const n=this.constructor;return new n({content:gs(this.content,e.content),additional_kwargs:dn(this.additional_kwargs,e.additional_kwargs),response_metadata:dn(this.response_metadata,e.response_metadata),name:this.name??"",id:this.id??e.id})}};function p1(t){return t._getType()==="function"}function m1(t){return t._getType()==="function"}var vn=class extends bn{constructor(e){super(e);p(this,"type","human")}static lc_name(){return"HumanMessage"}static isInstance(e){return super.isInstance(e)&&e.type==="human"}},Bc=class extends na{constructor(e){super(e);p(this,"type","human")}static lc_name(){return"HumanMessageChunk"}concat(e){const n=this.constructor;return new n({content:gs(this.content,e.content),additional_kwargs:dn(this.additional_kwargs,e.additional_kwargs),response_metadata:dn(this.response_metadata,e.response_metadata),id:this.id??e.id})}static isInstance(e){return super.isInstance(e)&&e.type==="human"}};function g1(t){return t.getType()==="human"}function _1(t){return t.getType()==="human"}var xa=class extends bn{constructor(e){super({...e,content:[]});p(this,"type","remove");p(this,"id");this.id=e.id}get _printableFields(){return{...super._printableFields,id:this.id}}static isInstance(e){return super.isInstance(e)&&e.type==="remove"}},Gn=class ll extends bn{constructor(n){super(n);p(this,"type","system")}static lc_name(){return"SystemMessage"}concat(n){if(typeof n=="string")return new ll({content:gs(this.content,n),additional_kwargs:this.additional_kwargs,response_metadata:this.response_metadata,id:this.id,name:this.name});if(ll.isInstance(n))return new ll({content:gs(this.content,n.content),additional_kwargs:{...this.additional_kwargs,...n.additional_kwargs},response_metadata:{...this.response_metadata,...n.response_metadata},id:this.id??n.id,name:this.name??n.name});throw new Error("Unexpected chunk type for system message")}static isInstance(n){return super.isInstance(n)&&n.type==="system"}},qs=class extends na{constructor(e){super(e);p(this,"type","system")}static lc_name(){return"SystemMessageChunk"}concat(e){const n=this.constructor;return new n({content:gs(this.content,e.content),additional_kwargs:dn(this.additional_kwargs,e.additional_kwargs),response_metadata:dn(this.response_metadata,e.response_metadata),id:this.id??e.id})}static isInstance(e){return super.isInstance(e)&&e.type==="system"}};function y1(t){return t._getType()==="system"}function w1(t){return t._getType()==="system"}const hS=t=>t();function b1(t){return Jo(t)?t:typeof t.id=="string"&&t.type==="function"&&typeof t.function=="object"&&t.function!==null&&"arguments"in t.function&&typeof t.function.arguments=="string"&&"name"in t.function&&typeof t.function.name=="string"?{id:t.id,args:JSON.parse(t.function.arguments),name:t.function.name,type:"tool_call"}:t}function v1(t){return typeof t=="object"&&t!=null&&t.lc===1&&Array.isArray(t.id)&&t.kwargs!=null&&typeof t.kwargs=="object"}function Lh(t){let e,n;if(v1(t)){const r=t.id.at(-1);r==="HumanMessage"||r==="HumanMessageChunk"?e="user":r==="AIMessage"||r==="AIMessageChunk"?e="assistant":r==="SystemMessage"||r==="SystemMessageChunk"?e="system":r==="FunctionMessage"||r==="FunctionMessageChunk"?e="function":r==="ToolMessage"||r==="ToolMessageChunk"?e="tool":e="unknown",n=t.kwargs}else{const{type:r,...s}=t;e=r,n=s}if(e==="human"||e==="user")return new vn(n);if(e==="ai"||e==="assistant"){const{tool_calls:r,...s}=n;if(!Array.isArray(r))return new De(n);const a=r.map(b1);return new De({...s,tool_calls:a})}else{if(e==="system")return new Gn(n);if(e==="developer")return new Gn({...n,additional_kwargs:{...n.additional_kwargs,__openai_role__:"developer"}});if(e==="tool"&&"tool_call_id"in n)return new Rn({...n,content:n.content,tool_call_id:n.tool_call_id,name:n.name});if(e==="remove"&&"id"in n&&typeof n.id=="string")return new xa({...n,id:n.id});throw Lc(new Error(`Unable to coerce message from array: only human, AI, system, developer, or tool message coercion is currently supported.
15
-
16
- Received: ${JSON.stringify(t,null,2)}`),"MESSAGE_COERCION_FAILURE")}}function Vr(t){if(typeof t=="string")return new vn(t);if(wt(t))return t;if(Array.isArray(t)){const[e,n]=t;return Lh({type:e,content:n})}else if(iS(t)){const{role:e,...n}=t;return Lh({...n,type:e})}else return Lh(t)}function S1(t){if(typeof t=="string")return t;switch(t.type){case"text":return t.text??"";case"text-plain":return t.text??"[text-plain file]";case"image":case"image_url":return"[image]";case"audio":case"input_audio":return"[audio]";case"video":return"[video]";case"file":return"[file]";case"reasoning":case"tool_call":case"tool_call_chunk":case"invalid_tool_call":case"server_tool_call":case"server_tool_call_chunk":case"server_tool_call_result":case"non_standard":return"";default:return t.type?`[${t.type}]`:""}}function pg(t,e="Human",n="AI"){const r=[];for(const s of t){let a;if(s.type==="human")a=e;else if(s.type==="ai")a=n;else if(s.type==="system")a="System";else if(s.type==="tool")a="Tool";else if(s.type==="generic")a=s.role;else throw new Error(`Got unsupported message type: ${s.type}`);const i=s.name?`${s.name}, `:"",o=typeof s.content=="string"?s.content:Array.isArray(s.content)?s.content.map(S1).filter(Boolean).join(""):"";let c=`${a}: ${i}${o}`;if(s.type==="ai"){const u=s;u.tool_calls&&u.tool_calls.length>0?c+=JSON.stringify(u.tool_calls):u.additional_kwargs&&"function_call"in u.additional_kwargs&&(c+=JSON.stringify(u.additional_kwargs.function_call))}r.push(c)}return r.join(`
17
- `)}function T1(t){if(t.data!==void 0)return t;{const e=t;return{type:e.type,data:{content:e.text,role:e.role,name:void 0,tool_call_id:void 0}}}}function mg(t){const e=T1(t);switch(e.type){case"human":return new vn(e.data);case"ai":return new De(e.data);case"system":return new Gn(e.data);case"function":if(e.data.name===void 0)throw new Error("Name must be defined for function messages");return new Vd(e.data);case"tool":if(e.data.tool_call_id===void 0)throw new Error("Tool call ID must be defined for tool messages");return new Rn(e.data);case"generic":if(e.data.role===void 0)throw new Error("Role must be defined for chat messages");return new Kr(e.data);default:throw new Error(`Got unexpected type: ${e.type}`)}}function E1(t){return t.map(mg)}function A1(t){return t.map(e=>e.toDict())}function Kl(t){var n;const e=t._getType();if(e==="human")return new Bc({...t});if(e==="ai"){let r={...t};return"tool_calls"in r&&(r={...r,tool_call_chunks:(n=r.tool_calls)==null?void 0:n.map(s=>({...s,type:"tool_call_chunk",index:void 0,args:JSON.stringify(s.args)}))}),new Qe({...r})}else{if(e==="system")return new qs({...t});if(e==="function")return new Fc({...t});if(Kr.isInstance(t))return new Dc({...t});throw new Error("Unknown message type.")}}function fS(t){var s,a;const e=t.reduce((i,o)=>{const c=i.findIndex(([u])=>"id"in o&&o.id&&"index"in o&&o.index!==void 0?o.id===u.id&&o.index===u.index:"id"in o&&o.id?o.id===u.id:"index"in o&&o.index!==void 0?o.index===u.index:!1);return c!==-1?i[c].push(o):i.push([o]),i},[]),n=[],r=[];for(const i of e){let o=null;const c=((s=i[0])==null?void 0:s.name)??"",u=i.map(f=>f.args||"").join("").trim(),l=u.length?u:"{}",d=(a=i[0])==null?void 0:a.id;try{if(o=ki(l),!d||o===null||typeof o!="object"||Array.isArray(o))throw new Error("Malformed tool call chunk args.");n.push({name:c,args:o,id:d,type:"tool_call"})}catch{r.push({name:c,args:l,id:d,error:"Malformed args.",type:"invalid_tool_call"})}}return{tool_call_chunks:t,tool_calls:n,invalid_tool_calls:r}}var I1=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;function Fs(t){return typeof t=="string"&&I1.test(t)}const Zt=[];for(let t=0;t<256;++t)Zt.push((t+256).toString(16).slice(1));function zc(t,e=0){return(Zt[t[e+0]]+Zt[t[e+1]]+Zt[t[e+2]]+Zt[t[e+3]]+"-"+Zt[t[e+4]]+Zt[t[e+5]]+"-"+Zt[t[e+6]]+Zt[t[e+7]]+"-"+Zt[t[e+8]]+Zt[t[e+9]]+"-"+Zt[t[e+10]]+Zt[t[e+11]]+Zt[t[e+12]]+Zt[t[e+13]]+Zt[t[e+14]]+Zt[t[e+15]]).toLowerCase()}function x1(t,e=0){const n=zc(t,e);if(!Fs(n))throw TypeError("Stringified UUID is invalid");return n}const k1=new Uint8Array(16);function oc(){return crypto.getRandomValues(k1)}const jh={};function rs(t,e,n){var s;let r;if(t)r=zy(t.random??((s=t.rng)==null?void 0:s.call(t))??oc(),t.msecs,t.seq,e,n);else{const a=Date.now(),i=oc();O1(jh,a,i),r=zy(i,jh.msecs,jh.seq,e,n)}return e??zc(r)}function O1(t,e,n){return t.msecs??(t.msecs=-1/0),t.seq??(t.seq=0),e>t.msecs?(t.seq=n[6]<<23|n[7]<<16|n[8]<<8|n[9],t.msecs=e):(t.seq=t.seq+1|0,t.seq===0&&t.msecs++),t}function zy(t,e,n,r,s=0){if(t.length<16)throw new Error("Random bytes length must be >= 16");if(!r)r=new Uint8Array(16),s=0;else if(s<0||s+16>r.length)throw new RangeError(`UUID byte range ${s}:${s+15} is out of buffer bounds`);return e??(e=Date.now()),n??(n=t[6]*127<<24|t[7]<<16|t[8]<<8|t[9]),r[s++]=e/1099511627776&255,r[s++]=e/4294967296&255,r[s++]=e/16777216&255,r[s++]=e/65536&255,r[s++]=e/256&255,r[s++]=e&255,r[s++]=112|n>>>28&15,r[s++]=n>>>20&255,r[s++]=128|n>>>14&63,r[s++]=n>>>6&255,r[s++]=n<<2&255|t[10]&3,r[s++]=t[11],r[s++]=t[12],r[s++]=t[13],r[s++]=t[14],r[s++]=t[15],r}var C1="ffffffff-ffff-ffff-ffff-ffffffffffff",R1="00000000-0000-0000-0000-000000000000";function bp(t){if(!Fs(t))throw TypeError("Invalid UUID");let e;return Uint8Array.of((e=parseInt(t.slice(0,8),16))>>>24,e>>>16&255,e>>>8&255,e&255,(e=parseInt(t.slice(9,13),16))>>>8,e&255,(e=parseInt(t.slice(14,18),16))>>>8,e&255,(e=parseInt(t.slice(19,23),16))>>>8,e&255,(e=parseInt(t.slice(24,36),16))/1099511627776&255,e/4294967296&255,e>>>24&255,e>>>16&255,e>>>8&255,e&255)}const to={};function $1(t,e,n){var a;let r;const s=(t==null?void 0:t._v6)??!1;if(t){const i=Object.keys(t);i.length===1&&i[0]==="_v6"&&(t=void 0)}if(t)r=Hy(t.random??((a=t.rng)==null?void 0:a.call(t))??oc(),t.msecs,t.nsecs,t.clockseq,t.node,e,n);else{const i=Date.now(),o=oc();N1(to,i,o),r=Hy(o,to.msecs,to.nsecs,s?void 0:to.clockseq,s?void 0:to.node,e,n)}return e??zc(r)}function N1(t,e,n){return t.msecs??(t.msecs=-1/0),t.nsecs??(t.nsecs=0),e===t.msecs?(t.nsecs++,t.nsecs>=1e4&&(t.node=void 0,t.nsecs=0)):e>t.msecs?t.nsecs=0:e<t.msecs&&(t.node=void 0),t.node||(t.node=n.slice(10,16),t.node[0]|=1,t.clockseq=(n[8]<<8|n[9])&16383),t.msecs=e,t}function Hy(t,e,n,r,s,a,i=0){if(t.length<16)throw new Error("Random bytes length must be >= 16");if(!a)a=new Uint8Array(16),i=0;else if(i<0||i+16>a.length)throw new RangeError(`UUID byte range ${i}:${i+15} is out of buffer bounds`);e??(e=Date.now()),n??(n=0),r??(r=(t[8]<<8|t[9])&16383),s??(s=t.slice(10,16)),e+=122192928e5;const o=((e&268435455)*1e4+n)%4294967296;a[i++]=o>>>24&255,a[i++]=o>>>16&255,a[i++]=o>>>8&255,a[i++]=o&255;const c=e/4294967296*1e4&268435455;a[i++]=c>>>8&255,a[i++]=c&255,a[i++]=c>>>24&15|16,a[i++]=c>>>16&255,a[i++]=r>>>8|128,a[i++]=r&255;for(let u=0;u<6;++u)a[i++]=s[u];return a}function Hc(t,e,n){return!e&&!t&&crypto.randomUUID?crypto.randomUUID():P1(t,e,n)}function P1(t,e,n){var s;t=t||{};const r=t.random??((s=t.rng)==null?void 0:s.call(t))??oc();if(r.length<16)throw new Error("Random bytes length must be >= 16");if(r[6]=r[6]&15|64,r[8]=r[8]&63|128,e){if(n=n||0,n<0||n+16>e.length)throw new RangeError(`UUID byte range ${n}:${n+15} is out of buffer bounds`);for(let a=0;a<16;++a)e[n+a]=r[a];return e}return zc(r)}function M1(t,e,n,r){switch(t){case 0:return e&n^~e&r;case 1:return e^n^r;case 2:return e&n^e&r^n&r;case 3:return e^n^r}}function Uh(t,e){return t<<e|t>>>32-e}function L1(t){const e=[1518500249,1859775393,2400959708,3395469782],n=[1732584193,4023233417,2562383102,271733878,3285377520],r=new Uint8Array(t.length+1);r.set(t),r[t.length]=128,t=r;const s=t.length/4+2,a=Math.ceil(s/16),i=new Array(a);for(let o=0;o<a;++o){const c=new Uint32Array(16);for(let u=0;u<16;++u)c[u]=t[o*64+u*4]<<24|t[o*64+u*4+1]<<16|t[o*64+u*4+2]<<8|t[o*64+u*4+3];i[o]=c}i[a-1][14]=(t.length-1)*8/2**32,i[a-1][14]=Math.floor(i[a-1][14]),i[a-1][15]=(t.length-1)*8&4294967295;for(let o=0;o<a;++o){const c=new Uint32Array(80);for(let m=0;m<16;++m)c[m]=i[o][m];for(let m=16;m<80;++m)c[m]=Uh(c[m-3]^c[m-8]^c[m-14]^c[m-16],1);let u=n[0],l=n[1],d=n[2],f=n[3],h=n[4];for(let m=0;m<80;++m){const _=Math.floor(m/20),y=Uh(u,5)+M1(_,l,d,f)+h+e[_]+c[m]>>>0;h=f,f=d,d=Uh(l,30)>>>0,l=u,u=y}n[0]=n[0]+u>>>0,n[1]=n[1]+l>>>0,n[2]=n[2]+d>>>0,n[3]=n[3]+f>>>0,n[4]=n[4]+h>>>0}return Uint8Array.of(n[0]>>24,n[0]>>16,n[0]>>8,n[0],n[1]>>24,n[1]>>16,n[1]>>8,n[1],n[2]>>24,n[2]>>16,n[2]>>8,n[2],n[3]>>24,n[3]>>16,n[3]>>8,n[3],n[4]>>24,n[4]>>16,n[4]>>8,n[4])}function j1(t){t=unescape(encodeURIComponent(t));const e=new Uint8Array(t.length);for(let n=0;n<t.length;++n)e[n]=t.charCodeAt(n);return e}const U1="6ba7b810-9dad-11d1-80b4-00c04fd430c8",D1="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function F1(t,e,n,r,s,a){const i=typeof n=="string"?j1(n):n,o=typeof r=="string"?bp(r):r;if(typeof r=="string"&&(r=bp(r)),(r==null?void 0:r.length)!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let c=new Uint8Array(16+i.length);if(c.set(o),c.set(i,o.length),c=e(c),c[6]=c[6]&15|t,c[8]=c[8]&63|128,s){if(a??(a=0),a<0||a+16>s.length)throw new RangeError(`UUID byte range ${a}:${a+15} is out of buffer bounds`);for(let u=0;u<16;++u)s[a+u]=c[u];return s}return zc(c)}function cc(t,e,n,r){return F1(80,L1,t,e,n,r)}cc.DNS=U1;cc.URL=D1;function B1(t){if(!Fs(t))throw TypeError("Invalid UUID");return parseInt(t.slice(14,15),16)}var z1=ue({MAX:()=>C1,NIL:()=>R1,parse:()=>bp,stringify:()=>x1,v1:()=>$1,v4:()=>Hc,v5:()=>cc,v7:()=>rs,validate:()=>Fs,version:()=>B1}),Dh={},H1=ue({getEnv:()=>gg,getEnvironmentVariable:()=>It,getRuntimeEnvironment:()=>yS,isBrowser:()=>pS,isDeno:()=>Zd,isJsDom:()=>gS,isNode:()=>_S,isWebWorker:()=>mS});const pS=()=>typeof window<"u"&&typeof window.document<"u",mS=()=>typeof globalThis=="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope",gS=()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&navigator.userAgent.includes("jsdom"),Zd=()=>typeof Deno<"u",_S=()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!Zd(),gg=()=>{let t;return pS()?t="browser":_S()?t="node":mS()?t="webworker":gS()?t="jsdom":Zd()?t="deno":t="other",t};let Fh;function yS(){return Fh===void 0&&(Fh={library:"langchain-js",runtime:gg()}),Fh}function It(t){try{return typeof process<"u"?Dh==null?void 0:Dh[t]:Zd()?Deno==null?void 0:Deno.env.get(t):void 0}catch{return}}var V1=ue({BaseCallbackHandler:()=>za,callbackHandlerPrefersStreaming:()=>_g,isBaseCallbackHandler:()=>wS}),Z1=class{};function _g(t){return"lc_prefer_streaming"in t&&t.lc_prefer_streaming}var za=class extends Z1{constructor(e){super();p(this,"lc_serializable",!1);p(this,"lc_kwargs");p(this,"ignoreLLM",!1);p(this,"ignoreChain",!1);p(this,"ignoreAgent",!1);p(this,"ignoreRetriever",!1);p(this,"ignoreCustomEvent",!1);p(this,"raiseError",!1);p(this,"awaitHandlers",It("LANGCHAIN_CALLBACKS_BACKGROUND")==="false");this.lc_kwargs=e||{},e&&(this.ignoreLLM=e.ignoreLLM??this.ignoreLLM,this.ignoreChain=e.ignoreChain??this.ignoreChain,this.ignoreAgent=e.ignoreAgent??this.ignoreAgent,this.ignoreRetriever=e.ignoreRetriever??this.ignoreRetriever,this.ignoreCustomEvent=e.ignoreCustomEvent??this.ignoreCustomEvent,this.raiseError=e.raiseError??this.raiseError,this.awaitHandlers=this.raiseError||(e._awaitHandler??this.awaitHandlers))}get lc_namespace(){return["langchain_core","callbacks",this.name]}get lc_secrets(){}get lc_attributes(){}get lc_aliases(){}get lc_serializable_keys(){}static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,Hd(this.constructor)]}copy(){return new this.constructor(this)}toJSON(){return ar.prototype.toJSON.call(this)}toJSONNotImplemented(){return ar.prototype.toJSONNotImplemented.call(this)}static fromMethods(e){class n extends za{constructor(){super();p(this,"name",rs());Object.assign(this,e)}}return new n}};const wS=t=>{const e=t;return e!==void 0&&typeof e.copy=="function"&&typeof e.name=="string"&&typeof e.awaitHandlers=="boolean"},W1=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;function G1(t){return typeof t=="string"&&W1.test(t)}function Vy(t){if(!G1(t))throw TypeError("Invalid UUID");let e;return Uint8Array.of((e=parseInt(t.slice(0,8),16))>>>24,e>>>16&255,e>>>8&255,e&255,(e=parseInt(t.slice(9,13),16))>>>8,e&255,(e=parseInt(t.slice(14,18),16))>>>8,e&255,(e=parseInt(t.slice(19,23),16))>>>8,e&255,(e=parseInt(t.slice(24,36),16))/1099511627776&255,e/4294967296&255,e>>>24&255,e>>>16&255,e>>>8&255,e&255)}const Wt=[];for(let t=0;t<256;++t)Wt.push((t+256).toString(16).slice(1));function yg(t,e=0){return(Wt[t[e+0]]+Wt[t[e+1]]+Wt[t[e+2]]+Wt[t[e+3]]+"-"+Wt[t[e+4]]+Wt[t[e+5]]+"-"+Wt[t[e+6]]+Wt[t[e+7]]+"-"+Wt[t[e+8]]+Wt[t[e+9]]+"-"+Wt[t[e+10]]+Wt[t[e+11]]+Wt[t[e+12]]+Wt[t[e+13]]+Wt[t[e+14]]+Wt[t[e+15]]).toLowerCase()}const q1=new Uint8Array(16);function vp(){return crypto.getRandomValues(q1)}function no(t,e,n){return crypto.randomUUID?crypto.randomUUID():K1(t)}function K1(t,e,n){var s;t=t||{};const r=t.random??((s=t.rng)==null?void 0:s.call(t))??vp();if(r.length<16)throw new Error("Random bytes length must be >= 16");return r[6]=r[6]&15|64,r[8]=r[8]&63|128,yg(r)}function J1(t,e,n,r){switch(t){case 0:return e&n^~e&r;case 1:return e^n^r;case 2:return e&n^e&r^n&r;case 3:return e^n^r}}function Bh(t,e){return t<<e|t>>>32-e}function X1(t){const e=[1518500249,1859775393,2400959708,3395469782],n=[1732584193,4023233417,2562383102,271733878,3285377520],r=new Uint8Array(t.length+1);r.set(t),r[t.length]=128,t=r;const s=t.length/4+2,a=Math.ceil(s/16),i=new Array(a);for(let o=0;o<a;++o){const c=new Uint32Array(16);for(let u=0;u<16;++u)c[u]=t[o*64+u*4]<<24|t[o*64+u*4+1]<<16|t[o*64+u*4+2]<<8|t[o*64+u*4+3];i[o]=c}i[a-1][14]=(t.length-1)*8/2**32,i[a-1][14]=Math.floor(i[a-1][14]),i[a-1][15]=(t.length-1)*8&4294967295;for(let o=0;o<a;++o){const c=new Uint32Array(80);for(let m=0;m<16;++m)c[m]=i[o][m];for(let m=16;m<80;++m)c[m]=Bh(c[m-3]^c[m-8]^c[m-14]^c[m-16],1);let u=n[0],l=n[1],d=n[2],f=n[3],h=n[4];for(let m=0;m<80;++m){const _=Math.floor(m/20),y=Bh(u,5)+J1(_,l,d,f)+h+e[_]+c[m]>>>0;h=f,f=d,d=Bh(l,30)>>>0,l=u,u=y}n[0]=n[0]+u>>>0,n[1]=n[1]+l>>>0,n[2]=n[2]+d>>>0,n[3]=n[3]+f>>>0,n[4]=n[4]+h>>>0}return Uint8Array.of(n[0]>>24,n[0]>>16,n[0]>>8,n[0],n[1]>>24,n[1]>>16,n[1]>>8,n[1],n[2]>>24,n[2]>>16,n[2]>>8,n[2],n[3]>>24,n[3]>>16,n[3]>>8,n[3],n[4]>>24,n[4]>>16,n[4]>>8,n[4])}function Y1(t){t=unescape(encodeURIComponent(t));const e=new Uint8Array(t.length);for(let n=0;n<t.length;++n)e[n]=t.charCodeAt(n);return e}const Q1="6ba7b810-9dad-11d1-80b4-00c04fd430c8",eR="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function tR(t,e,n,r,s,a){const i=typeof n=="string"?Y1(n):n,o=typeof r=="string"?Vy(r):r;if(typeof r=="string"&&(r=Vy(r)),(r==null?void 0:r.length)!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let c=new Uint8Array(16+i.length);if(c.set(o),c.set(i,o.length),c=e(c),c[6]=c[6]&15|t,c[8]=c[8]&63|128,s){if(a??(a=0),a<0||a+16>s.length)throw new RangeError(`UUID byte range ${a}:${a+15} is out of buffer bounds`);for(let u=0;u<16;++u)s[a+u]=c[u];return s}return yg(c)}function wg(t,e,n,r){return tR(80,X1,t,e,n,r)}wg.DNS=Q1;wg.URL=eR;const zh={};function bS(t,e,n){var s;let r;if(t)r=Zy(t.random??((s=t.rng)==null?void 0:s.call(t))??vp(),t.msecs,t.seq,e,n);else{const a=Date.now(),i=vp();nR(zh,a,i),r=Zy(i,zh.msecs,zh.seq,e,n)}return e??yg(r)}function nR(t,e,n){return t.msecs??(t.msecs=-1/0),t.seq??(t.seq=0),e>t.msecs?(t.seq=n[6]<<23|n[7]<<16|n[8]<<8|n[9],t.msecs=e):(t.seq=t.seq+1|0,t.seq===0&&t.msecs++),t}function Zy(t,e,n,r,s=0){if(t.length<16)throw new Error("Random bytes length must be >= 16");if(!r)r=new Uint8Array(16),s=0;else if(s<0||s+16>r.length)throw new RangeError(`UUID byte range ${s}:${s+15} is out of buffer bounds`);return e??(e=Date.now()),n??(n=t[6]*127<<24|t[7]<<16|t[8]<<8|t[9]),r[s++]=e/1099511627776&255,r[s++]=e/4294967296&255,r[s++]=e/16777216&255,r[s++]=e/65536&255,r[s++]=e/256&255,r[s++]=e&255,r[s++]=112|n>>>28&15,r[s++]=n>>>20&255,r[s++]=128|n>>>14&63,r[s++]=n>>>6&255,r[s++]=n<<2&255|t[10]&3,r[s++]=t[11],r[s++]=t[12],r[s++]=t[13],r[s++]=t[14],r[s++]=t[15],r}const rR="gen_ai.operation.name",sR="gen_ai.system",Wy="gen_ai.request.model",aR="gen_ai.response.model",Gy="gen_ai.usage.input_tokens",qy="gen_ai.usage.output_tokens",Ky="gen_ai.usage.total_tokens",iR="gen_ai.request.max_tokens",oR="gen_ai.request.temperature",cR="gen_ai.request.top_p",uR="gen_ai.request.frequency_penalty",lR="gen_ai.request.presence_penalty",dR="gen_ai.response.finish_reasons",hR="gen_ai.prompt",fR="gen_ai.completion",pR="gen_ai.request.extra_query",mR="gen_ai.request.extra_body",gR="gen_ai.serialized.name",_R="gen_ai.serialized.signature",yR="gen_ai.serialized.doc",wR="gen_ai.response.id",bR="gen_ai.response.service_tier",vR="gen_ai.response.system_fingerprint",SR="gen_ai.usage.input_token_details",TR="gen_ai.usage.output_token_details",ER="langsmith.trace.session_id",AR="langsmith.trace.session_name",IR="langsmith.span.kind",xR="langsmith.trace.name",kR="langsmith.metadata",Jy="langsmith.span.tags",OR="langsmith.request.streaming",CR="langsmith.request.headers",RR=(...t)=>fetch(...t),vS=Symbol.for("ls:fetch_implementation"),$R=()=>globalThis[vS]===void 0,NR=t=>async(...e)=>{if(t||Tt("DEBUG")==="true"){const[r,s]=e;console.log(`→ ${(s==null?void 0:s.method)||"GET"} ${r}`)}const n=await(globalThis[vS]??RR)(...e);return(t||Tt("DEBUG")==="true")&&console.log(`← ${n.status} ${n.statusText} ${n.url}`),n},SS=()=>Tt("PROJECT")??Wr("LANGCHAIN_SESSION")??"default",Xy={};function dl(t){Xy[t]||(console.warn(t),Xy[t]=!0)}const F=t=>BigInt(t),TS=F("0x9E3779B1"),ES=F("0x85EBCA77"),PR=F("0xC2B2AE3D"),Ks=F("0x9E3779B185EBCA87"),Pa=F("0xC2B2AE3D27D4EB4F"),AS=F("0x165667B19E3779F9"),bg=F("0x85EBCA77C2B2AE63"),MR=F("0x27D4EB2F165667C5"),LR=F("0x165667919E3779F9"),jR=F("0x9FB21C651E98DF25");function UR(t){const e=new Uint8Array(t.length/2);for(let n=0;n<t.length;n+=2)e[n/2]=parseInt(t.substring(n,n+2),16);return e}const Pr=UR("b8fe6c3923a44bbe7c01812cf721ad1cded46de9839097db7240a4a4b7b3671fcb79e64eccc0e578825ad07dccff7221b8084674f743248ee03590e6813a264c3c2852bb91c300cb88d0658b1b532ea371644897a20df94e3819ef46a9deacd8a8fa763fe39c343ff9dcbbc7c70b4f1d8a51e04bcdb45931c89f7ec9d9787364eac5ac8334d3ebc3c581a0fffa1363eb170ddd51b7f0da49d316552629d4689e2b16be587d47a1fc8ff8b8d17ad031ce45cb3a8f95160428afd7fbcabb4b407e"),Ti=(F(1)<<F(128))-F(1),Pe=(F(1)<<F(64))-F(1),Jl=(F(1)<<F(32))-F(1),ss=64,IS=ss/8,DR=8,fu=4;function ut(t,e=0){return new Uint8Array(t.buffer,t.byteOffset+e,t.length-e)}function ht(t,e=0){return new DataView(t.buffer,t.byteOffset+e).getBigUint64(0,!0)}function hi(t,e=0){return new DataView(t.buffer,t.byteOffset+e).getUint32(0,!0)}function Hh(t,e=0){return t[e]}const FR=t=>(t&F(255))<<F(56)|(t&F(65280))<<F(40)|(t&F(16711680))<<F(24)|(t&F(4278190080))<<F(8)|(t&F(0xff00000000))>>F(8)|(t&F(0xff0000000000))>>F(24)|(t&F(0xff000000000000))>>F(40)|(t&F(0xff00000000000000))>>F(56),BR=t=>(t=(t&F(65535))<<F(16)|(t&F(4294901760))>>F(16),t=(t&F(16711935))<<F(8)|(t&F(4278255360))>>F(8),t),zR=(t,e)=>(t&Jl)*(e&Jl)&Pe,Ri=t=>{if(!t)throw new Error("Assert failed")};function HR(t,e){return(t<<e|t>>F(32)-e)&Jl}function xS(t,e,n){for(let r=0;r<IS;r++){const s=ht(e,r*8),a=s^ht(n,r*8);t[r^1]+=s,t[r]+=zR(a,a>>F(32))}return t}function Yy(t,e,n,r){for(let s=0;s<r;s++)xS(t,ut(e,s*ss),ut(n,s*8));return t}function VR(t,e){for(let n=0;n<IS;n++){const r=ht(e,n*8);let s=t[n];s=Sp(s,F(47)),s^=r,s*=TS,t[n]=s&Pe}return t}function pu(t,e){return kS(t[0]^ht(e,0),t[1]^ht(e,DR))}function Qy(t,e,n){let r=n;return r+=pu(t.slice(0),ut(e,0*fu)),r+=pu(t.slice(2),ut(e,4*fu)),r+=pu(t.slice(4),ut(e,8*fu)),r+=pu(t.slice(6),ut(e,12*fu)),Fr(r&Pe)}function ZR(t,e,n,r,s){const a=Math.floor((n.byteLength-ss)/8),i=ss*a,o=Math.floor((e.byteLength-1)/i);for(let c=0;c<o;c++)t=Yy(t,ut(e,c*i),n,a),t=s(t,ut(n,n.byteLength-ss));{const c=Math.floor((e.byteLength-1-i*o)/ss);t=Yy(t,ut(e,o*i),n,c),t=r(t,ut(e,e.byteLength-ss),ut(n,n.byteLength-ss-7))}return t}function WR(t,e,n){let r=new BigUint64Array([PR,Ks,Pa,AS,bg,ES,MR,TS]);Ri(t.length>128),r=ZR(r,t,e,xS,VR),Ri(r.length*8==64);{const s=Qy(r,ut(e,11),F(t.byteLength)*Ks&Pe);return Qy(r,ut(e,e.byteLength-ss-11),~(F(t.byteLength)*Pa)&Pe)<<F(64)|s}}function kS(t,e){const n=t*e&Ti;return n&Pe^n>>F(64)}function ew(t,e,n){return kS((ht(t,0)^ht(e,0)+n)&Pe,(ht(t,8)^ht(e,8)-n)&Pe)}function hl(t,e,n,r,s){let a=t&Pe,i=t>>F(64)&Pe;return a+=ew(e,r,s),a^=ht(n,0)+ht(n,8),a&=Pe,i+=ew(n,ut(r,16),s),i^=ht(e,0)+ht(e,8),i&=Pe,i<<F(64)|a}function Fr(t){return t^=t>>F(37),t*=LR,t&=Pe,t^=t>>F(32),t}function Xl(t){return t^=t>>F(33),t*=Pa,t&=Pe,t^=t>>F(29),t*=AS,t&=Pe,t^=t>>F(32),t}function GR(t,e,n){const r=t.byteLength;Ri(r>0&&r<=3);const s=F(Hh(t,r-1))|F(r<<8)|F(Hh(t,0)<<16)|F(Hh(t,r>>1)<<24),a=(F(hi(e,0))^F(hi(e,4)))+n,i=(s^a)&Pe,o=(F(hi(e,8))^F(hi(e,12)))-n,c=(HR(BR(s),F(13))^o)&Pe;return(Xl(c)&Pe)<<F(64)|Xl(i)}function Sp(t,e){return t^t>>e}function qR(t,e,n){const r=t.byteLength;Ri(r>=4&&r<=8);{const s=hi(t,0),a=hi(t,r-4),i=F(s)|F(a)<<F(32),o=(ht(e,16)^ht(e,24))+n&Pe;let u=(i^o)*(Ks+(F(r)<<F(2)))&Ti;return u+=(u&Pe)<<F(65),u&=Ti,u^=u>>F(67),Sp(Sp(u&Pe,F(35))*jR&Pe,F(28))|Fr(u>>F(64))<<F(64)}}function KR(t,e,n){const r=t.byteLength;Ri(r>=9&&r<=16);{const s=(ht(e,32)^ht(e,40))+n&Pe,a=(ht(e,48)^ht(e,56))-n&Pe,i=ht(t);let o=ht(t,r-8),c=(i^o^s)*Ks;const u=(c&Pe)+(F(r-1)<<F(54));c=c&(Ti^Pe)|u,o^=a,c+=o+(o&Jl)*(ES-F(1))<<F(64),c&=Ti,c^=FR(c>>F(64));let l=(c&Pe)*Pa;return l+=(c>>F(64))*Pa<<F(64),l&=Ti,Fr(l&Pe)|Fr(l>>F(64))<<F(64)}}function JR(t,e){const n=t.byteLength;return Ri(n<=16),n>8?KR(t,Pr,e):n>=4?qR(t,Pr,e):n>0?GR(t,Pr,e):Xl(e^ht(Pr,64)^ht(Pr,72))|Xl(e^ht(Pr,80)^ht(Pr,88))<<F(64)}function Tp(t){return~t+F(1)&Pe}function XR(t,e,n){let r=F(t.byteLength)*Ks&Pe,s=F(t.byteLength-1)/F(32);for(;s>=0;){const o=Number(s);r=hl(r,ut(t,16*o),ut(t,t.byteLength-16*(o+1)),ut(e,32*o),n),s--}let a=r+(r>>F(64))&Pe;a=Fr(a);let i=(r&Pe)*Ks+(r>>F(64))*bg+(F(t.byteLength)-n&Pe)*Pa;return i&=Pe,i=Tp(Fr(i)),a|i<<F(64)}function YR(t,e,n){let r=F(t.byteLength)*Ks&Pe;for(let i=32;i<160;i+=32)r=hl(r,ut(t,i-32),ut(t,i-16),ut(e,i-32),n);r=Fr(r&Pe)|Fr(r>>F(64))<<F(64);for(let i=160;i<=t.byteLength;i+=32)r=hl(r,ut(t,i-32),ut(t,i-16),ut(e,3+i-160),n);r=hl(r,ut(t,t.byteLength-16),ut(t,t.byteLength-32),ut(e,103),Tp(n));let s=r+(r>>F(64))&Pe;s=Fr(s);let a=(r&Pe)*Ks+(r>>F(64))*bg+(F(t.byteLength)-n&Pe)*Pa;return a&=Pe,a=Tp(Fr(a)),s|a<<F(64)}function QR(t,e=F(0)){const n=t.byteLength;return n<=16?JR(t,e):n<=128?XR(t,Pr,e):n<=240?YR(t,Pr,e):WR(t,Pr)}function e$(t){const e=new Uint8Array(16),n=new DataView(e.buffer),r=t&Pe,s=t>>F(64);return n.setBigUint64(0,s,!1),n.setBigUint64(8,r,!1),e}const OS=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function $e(t,e){if(!OS.test(t)){const n=e!==void 0?`Invalid UUID for ${e}: ${t}`:`Invalid UUID: ${t}`;throw new Error(n)}return t}function t$(t){const e=typeof t=="string"?Date.parse(t):t;return bS({msecs:e,seq:0})}function n$(t){if(!OS.test(t))return null;const e=t[14];return parseInt(e,16)}function r$(t){const e=t.replace(/-/g,""),n=new Uint8Array(16);for(let r=0;r<16;r++)n[r]=parseInt(e.slice(r*2,r*2+2),16);return n}function s$(t){const e=Array.from(t).map(n=>n.toString(16).padStart(2,"0")).join("");return`${e.slice(0,8)}-${e.slice(8,12)}-${e.slice(12,16)}-${e.slice(16,20)}-${e.slice(20)}`}const a$=new TextEncoder;function i$(t){const e=a$.encode(t),n=QR(e);return e$(n)}function mu(t,e){const n=`${t}:${e}`,r=i$(n),s=new Uint8Array(16);if(n$(t)===7){const i=r$(t);s.set(i.slice(0,6),0)}else{const i=Date.now();s[0]=i/1099511627776&255,s[1]=i/4294967296&255,s[2]=i/16777216&255,s[3]=i/65536&255,s[4]=i/256&255,s[5]=i&255}return s[6]=112|r[0]&15,s[7]=r[1],s[8]=128|r[2]&63,s.set(r.slice(3,10),9),s$(s)}const Ep={join:(...t)=>t.join("/"),dirname:t=>t.split("/").slice(0,-1).join("/")};async function o$(t){}async function c$(t,e){}async function u$(t){return[]}async function l$(t){return{size:0}}function d$(t,e){return e===null?!1:Date.now()-t.createdAt>e*1e3}class h${constructor(e={}){Object.defineProperty(this,"cache",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"ttlSeconds",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"refreshIntervalSeconds",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"refreshTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_metrics",{enumerable:!0,configurable:!0,writable:!0,value:{hits:0,misses:0,refreshes:0,refreshErrors:0}}),this.configure(e)}get metrics(){return{...this._metrics}}get totalRequests(){return this._metrics.hits+this._metrics.misses}get hitRate(){const e=this.totalRequests;return e>0?this._metrics.hits/e:0}resetMetrics(){this._metrics={hits:0,misses:0,refreshes:0,refreshErrors:0}}get(e,n){if(this.maxSize===0)return;const r=this.cache.get(e);if(!r){this._metrics.misses+=1;return}return this.cache.delete(e),this.cache.set(e,{...r,refreshFunc:n}),this._metrics.hits+=1,r.value}set(e,n,r){if(this.maxSize===0)return;if(this.refreshTimer===void 0&&this.startRefreshLoop(),!this.cache.has(e)&&this.cache.size>=this.maxSize){const a=this.cache.keys().next().value;a!==void 0&&this.cache.delete(a)}const s={value:n,createdAt:Date.now(),refreshFunc:r};this.cache.delete(e),this.cache.set(e,s)}invalidate(e){this.cache.delete(e)}clear(){this.cache.clear()}get size(){return this.cache.size}stop(){this.refreshTimer&&(clearInterval(this.refreshTimer),this.refreshTimer=void 0)}dump(e){const n={};for(const[s,a]of this.cache.entries())n[s]=a.value;Ep.dirname(e);const r=`${e}.tmp`;try{JSON.stringify({entries:n},null,2)}catch(s){throw s}}load(e){return 0}startRefreshLoop(){this.stop(),this.ttlSeconds!==null&&(this.refreshTimer=setInterval(()=>{this.refreshStaleEntries().catch(e=>{console.warn("Unexpected error in cache refresh loop:",e)})},this.refreshIntervalSeconds*1e3),this.refreshTimer.unref&&this.refreshTimer.unref())}getStaleEntries(){const e=[];for(const[n,r]of this.cache.entries())d$(r,this.ttlSeconds)&&e.push([n,r]);return e}async refreshStaleEntries(){const e=this.getStaleEntries();if(e.length!==0){for(const[n,r]of e)if(r.refreshFunc!==void 0)try{const s=await r.refreshFunc();this.set(n,s,r.refreshFunc),this._metrics.refreshes+=1}catch(s){this._metrics.refreshErrors+=1,console.warn(`Failed to refresh cache entry ${n}:`,s)}}}configure(e){this.stop(),this.refreshIntervalSeconds=e.refreshIntervalSeconds??60,this.maxSize=e.maxSize??100,this.ttlSeconds=e.ttlSeconds??5*60}}const tw=new h$,CS="0.5.25";var Xo={};let Rr;const f$=()=>typeof window<"u"&&typeof window.document<"u",p$=()=>typeof globalThis=="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope",m$=()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&navigator.userAgent.includes("jsdom"),RS=()=>typeof Deno<"u",g$=()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!RS(),$S=()=>Rr||(typeof Bun<"u"?Rr="bun":f$()?Rr="browser":g$()?Rr="node":p$()?Rr="webworker":m$()?Rr="jsdom":RS()?Rr="deno":Rr="other",Rr);let Vh;function NS(){if(Vh===void 0){const t=$S(),e=y$();Vh={library:"langsmith",runtime:t,sdk:"langsmith-js",sdk_version:CS,...e}}return Vh}function PS(){const t=_$(),e={},n=["LANGCHAIN_API_KEY","LANGCHAIN_ENDPOINT","LANGCHAIN_TRACING_V2","LANGCHAIN_PROJECT","LANGCHAIN_SESSION","LANGSMITH_API_KEY","LANGSMITH_ENDPOINT","LANGSMITH_TRACING_V2","LANGSMITH_PROJECT","LANGSMITH_SESSION"];for(const[r,s]of Object.entries(t))typeof s=="string"&&!n.includes(r)&&!r.toLowerCase().includes("key")&&!r.toLowerCase().includes("secret")&&!r.toLowerCase().includes("token")&&(r==="LANGCHAIN_REVISION_ID"?e.revision_id=s:e[r]=s);return e}function _$(){const t={};try{if(typeof process<"u"&&Xo)for(const[e,n]of Object.entries(Xo))(e.startsWith("LANGCHAIN_")||e.startsWith("LANGSMITH_"))&&n!=null&&((e.toLowerCase().includes("key")||e.toLowerCase().includes("secret")||e.toLowerCase().includes("token"))&&typeof n=="string"?t[e]=n.slice(0,2)+"*".repeat(n.length-4)+n.slice(-2):t[e]=n)}catch{}return t}function Wr(t){try{return typeof process<"u"?Xo==null?void 0:Xo[t]:void 0}catch{return}}function Tt(t){return Wr(`LANGSMITH_${t}`)||Wr(`LANGCHAIN_${t}`)}let Zh;function y$(){if(Zh!==void 0)return Zh;const t=["VERCEL_GIT_COMMIT_SHA","NEXT_PUBLIC_VERCEL_GIT_COMMIT_SHA","COMMIT_REF","RENDER_GIT_COMMIT","CI_COMMIT_SHA","CIRCLE_SHA1","CF_PAGES_COMMIT_SHA","REACT_APP_GIT_SHA","SOURCE_VERSION","GITHUB_SHA","TRAVIS_COMMIT","GIT_COMMIT","BUILD_VCS_NUMBER","bamboo_planRepository_revision","Build.SourceVersion","BITBUCKET_COMMIT","DRONE_COMMIT_SHA","SEMAPHORE_GIT_SHA","BUILDKITE_COMMIT"],e={};for(const n of t){const r=Wr(n);r!==void 0&&(e[n]=r)}return Zh=e,e}function nw(){return Wr("OTEL_ENABLED")==="true"||Tt("OTEL_ENABLED")==="true"}const rw=new Set(["langsmith","otel"]);function MS(t){if(t!==void 0)return t;const e=Tt("TRACING_MODE");if(e!==void 0&&e!==""){const n=e.toLowerCase();if(!rw.has(n))throw new Error(`Invalid LANGSMITH_TRACING_MODE=${JSON.stringify(e)}. Must be one of: ${[...rw].sort().join(", ")}`);return nw()&&console.warn("Both LANGSMITH_TRACING_MODE and the legacy OTEL_ENABLED / LANGSMITH_OTEL_ENABLED env vars are set. LANGSMITH_TRACING_MODE takes precedence."),n}return nw()?"otel":"langsmith"}class w${constructor(){Object.defineProperty(this,"hasWarned",{enumerable:!0,configurable:!0,writable:!0,value:!1})}startActiveSpan(e,...n){!this.hasWarned&&MS()==="otel"&&(console.warn('OTel tracing mode is active (via LANGSMITH_TRACING_MODE, OTEL_ENABLED, or LANGSMITH_OTEL_ENABLED), but the required OTEL instances have not been initialized. Please add:\n```\nimport { initializeOTEL } from "langsmith/experimental/otel/setup";\ninitializeOTEL();\n```\nat the beginning of your code.'),this.hasWarned=!0);let r;if(n.length===1&&typeof n[0]=="function"?r=n[0]:n.length===2&&typeof n[1]=="function"?r=n[1]:n.length===3&&typeof n[2]=="function"&&(r=n[2]),typeof r=="function")return r()}}class b${constructor(){Object.defineProperty(this,"mockTracer",{enumerable:!0,configurable:!0,writable:!0,value:new w$})}getTracer(e,n){return this.mockTracer}getActiveSpan(){}setSpan(e,n){return e}getSpan(e){}setSpanContext(e,n){return e}getTracerProvider(){}setGlobalTracerProvider(e){return!1}}class v${active(){return{}}with(e,n){return n()}}const Wh=Symbol.for("ls:otel_trace"),Gh=Symbol.for("ls:otel_context"),sw=Symbol.for("ls:otel_get_default_otlp_tracer_provider"),S$=new b$,T$=new v$;class E${getTraceInstance(){return globalThis[Wh]??S$}getContextInstance(){return globalThis[Gh]??T$}initializeGlobalInstances(e){globalThis[Wh]===void 0&&(globalThis[Wh]=e.trace),globalThis[Gh]===void 0&&(globalThis[Gh]=e.context)}setDefaultOTLPTracerComponents(e){globalThis[sw]=e}getDefaultOTLPTracerComponents(){return globalThis[sw]??void 0}}const vg=new E$;function LS(){return vg.getTraceInstance()}function A$(){return vg.getContextInstance()}function I$(){return vg.getDefaultOTLPTracerComponents()}const x$={llm:"chat",tool:"execute_tool",retriever:"embeddings",embedding:"embeddings",prompt:"chat"};function k$(t){return x$[t]||t}class O${constructor(){Object.defineProperty(this,"spans",{enumerable:!0,configurable:!0,writable:!0,value:new Map})}exportBatch(e,n){for(const r of e)try{if(!r.run)continue;if(r.operation==="post"){const s=this.createSpanForRun(r,r.run,n.get(r.id));s&&!r.run.end_time&&this.spans.set(r.id,s)}else this.updateSpanForRun(r,r.run)}catch(s){console.error(`Error processing operation ${r.id}:`,s)}}createSpanForRun(e,n,r){const s=r&&LS().getSpan(r);if(s)try{return this.finishSpanSetup(s,n,e)}catch(a){console.error(`Failed to create span for run ${e.id}:`,a);return}}finishSpanSetup(e,n,r){return this.setSpanAttributes(e,n,r),n.error?(e.setStatus({code:2}),e.recordException(new Error(n.error))):e.setStatus({code:1}),n.end_time&&e.end(new Date(n.end_time)),e}updateSpanForRun(e,n){try{const r=this.spans.get(e.id);if(!r){console.debug(`No span found for run ${e.id} during update`);return}this.setSpanAttributes(r,n,e),n.error?(r.setStatus({code:2}),r.recordException(new Error(n.error))):r.setStatus({code:1});const s=n.end_time;s&&(r.end(new Date(s)),this.spans.delete(e.id))}catch(r){console.error(`Failed to update span for run ${e.id}:`,r)}}extractModelName(e){var n;if((n=e.extra)!=null&&n.metadata){const r=e.extra.metadata;if(r.ls_model_name)return r.ls_model_name;if(r.invocation_params){const s=r.invocation_params;if(s.model)return s.model;if(s.model_name)return s.model_name}}}setSpanAttributes(e,n,r){var o;if("run_type"in n&&n.run_type){e.setAttribute(IR,n.run_type);const c=k$(n.run_type||"chain");e.setAttribute(rR,c)}"name"in n&&n.name&&e.setAttribute(xR,n.name),"session_id"in n&&n.session_id&&e.setAttribute(ER,n.session_id),"session_name"in n&&n.session_name&&e.setAttribute(AR,n.session_name),this.setGenAiSystem(e,n);const s=this.extractModelName(n);s&&e.setAttribute(Wy,s),"prompt_tokens"in n&&typeof n.prompt_tokens=="number"&&e.setAttribute(Gy,n.prompt_tokens),"completion_tokens"in n&&typeof n.completion_tokens=="number"&&e.setAttribute(qy,n.completion_tokens),"total_tokens"in n&&typeof n.total_tokens=="number"&&e.setAttribute(Ky,n.total_tokens),this.setInvocationParameters(e,n);const a=((o=n.extra)==null?void 0:o.metadata)||{};for(const[c,u]of Object.entries(a))u!=null&&e.setAttribute(`${kR}.${c}`,String(u));const i=n.tags;if(i&&Array.isArray(i)?e.setAttribute(Jy,i.join(", ")):i&&e.setAttribute(Jy,String(i)),"serialized"in n&&typeof n.serialized=="object"){const c=n.serialized;c.name&&e.setAttribute(gR,String(c.name)),c.signature&&e.setAttribute(_R,String(c.signature)),c.doc&&e.setAttribute(yR,String(c.doc))}this.setIOAttributes(e,r)}setGenAiSystem(e,n){let r="langchain";const s=this.extractModelName(n);if(s){const a=s.toLowerCase();a.includes("anthropic")||a.startsWith("claude")?r="anthropic":a.includes("bedrock")?r="aws.bedrock":a.includes("azure")&&a.includes("openai")?r="az.ai.openai":a.includes("azure")&&a.includes("inference")?r="az.ai.inference":a.includes("cohere")?r="cohere":a.includes("deepseek")?r="deepseek":a.includes("gemini")?r="gemini":a.includes("groq")?r="groq":a.includes("watson")||a.includes("ibm")?r="ibm.watsonx.ai":a.includes("mistral")?r="mistral_ai":a.includes("gpt")||a.includes("openai")?r="openai":a.includes("perplexity")||a.includes("sonar")?r="perplexity":a.includes("vertex")?r="vertex_ai":(a.includes("xai")||a.includes("grok"))&&(r="xai")}e.setAttribute(sR,r)}setInvocationParameters(e,n){var s,a;if(!((a=(s=n.extra)==null?void 0:s.metadata)!=null&&a.invocation_params))return;const r=n.extra.metadata.invocation_params;r.max_tokens!==void 0&&e.setAttribute(iR,r.max_tokens),r.temperature!==void 0&&e.setAttribute(oR,r.temperature),r.top_p!==void 0&&e.setAttribute(cR,r.top_p),r.frequency_penalty!==void 0&&e.setAttribute(uR,r.frequency_penalty),r.presence_penalty!==void 0&&e.setAttribute(lR,r.presence_penalty)}setIOAttributes(e,n){if(n.run.inputs)try{const r=n.run.inputs;typeof r=="object"&&r!==null&&(r.model&&Array.isArray(r.messages)&&e.setAttribute(Wy,r.model),r.stream!==void 0&&e.setAttribute(OR,r.stream),r.extra_headers&&e.setAttribute(CR,JSON.stringify(r.extra_headers)),r.extra_query&&e.setAttribute(pR,JSON.stringify(r.extra_query)),r.extra_body&&e.setAttribute(mR,JSON.stringify(r.extra_body))),e.setAttribute(hR,JSON.stringify(r))}catch(r){console.debug(`Failed to process inputs for run ${n.id}`,r)}if(n.run.outputs)try{const r=n.run.outputs,s=this.getUnifiedRunTokens(r);if(s&&(e.setAttribute(Gy,s[0]),e.setAttribute(qy,s[1]),e.setAttribute(Ky,s[0]+s[1])),r&&typeof r=="object"){if(r.model&&e.setAttribute(aR,String(r.model)),r.id&&e.setAttribute(wR,r.id),r.choices&&Array.isArray(r.choices)){const a=r.choices.map(i=>i.finish_reason).filter(i=>i).map(String);a.length>0&&e.setAttribute(dR,a.join(", "))}if(r.service_tier&&e.setAttribute(bR,r.service_tier),r.system_fingerprint&&e.setAttribute(vR,r.system_fingerprint),r.usage_metadata&&typeof r.usage_metadata=="object"){const a=r.usage_metadata;a.input_token_details&&e.setAttribute(SR,JSON.stringify(a.input_token_details)),a.output_token_details&&e.setAttribute(TR,JSON.stringify(a.output_token_details))}}e.setAttribute(fR,JSON.stringify(r))}catch(r){console.debug(`Failed to process outputs for run ${n.id}`,r)}}getUnifiedRunTokens(e){if(!e)return null;let n=this.extractUnifiedRunTokens(e.usage_metadata);if(n)return n;const r=Object.keys(e);for(const i of r){const o=e[i];if(!(!o||typeof o!="object")&&(n=this.extractUnifiedRunTokens(o.usage_metadata),n||o.lc===1&&o.kwargs&&typeof o.kwargs=="object"&&(n=this.extractUnifiedRunTokens(o.kwargs.usage_metadata),n)))return n}const s=e.generations||[];if(!Array.isArray(s))return null;const a=Array.isArray(s[0])?s.flat():s;for(const i of a)if(typeof i=="object"&&i.message&&typeof i.message=="object"&&i.message.kwargs&&typeof i.message.kwargs=="object"&&(n=this.extractUnifiedRunTokens(i.message.kwargs.usage_metadata),n))return n;return null}extractUnifiedRunTokens(e){return!e||typeof e!="object"||typeof e.input_tokens!="number"||typeof e.output_tokens!="number"?null:[e.input_tokens,e.output_tokens]}}const C$=Object.prototype.toString,R$=t=>C$.call(t)==="[object Error]",$$=new Set(["network error","Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed","fetch failed","terminated"," A network error occurred.","Network connection lost"]);function N$(t){if(!(t&&R$(t)&&t.name==="TypeError"&&typeof t.message=="string"))return!1;const{message:n,stack:r}=t;return n==="Load failed"?r===void 0||"__sentry_captured__"in t:n.startsWith("error sending request for url")?!0:$$.has(n)}function P$(t){if(typeof t=="number"){if(t<0)throw new TypeError("Expected `retries` to be a non-negative number.");if(Number.isNaN(t))throw new TypeError("Expected `retries` to be a valid number or Infinity, got NaN.")}else if(t!==void 0)throw new TypeError("Expected `retries` to be a number or Infinity.")}function gu(t,e,{min:n=0,allowInfinity:r=!1}={}){if(e!==void 0){if(typeof e!="number"||Number.isNaN(e))throw new TypeError(`Expected \`${t}\` to be a number${r?" or Infinity":""}.`);if(!r&&!Number.isFinite(e))throw new TypeError(`Expected \`${t}\` to be a finite number.`);if(e<n)throw new TypeError(`Expected \`${t}\` to be ≥ ${n}.`)}}let M$=class extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,{message:e}=e):(this.originalError=new Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}};function L$(t,e){const n=Math.max(1,t+1),r=e.randomize?Math.random()+1:1;let s=Math.round(r*e.minTimeout*e.factor**(n-1));return s=Math.min(s,e.maxTimeout),s}function aw(t,e){return Number.isFinite(e)?e-(performance.now()-t):e}async function j$({error:t,attemptNumber:e,retriesConsumed:n,startTime:r,options:s}){var h,m,_;const a=t instanceof Error?t:new TypeError(`Non-error was thrown: "${t}". You should only throw errors.`);if(a instanceof M$)throw a.originalError;const i=Number.isFinite(s.retries)?Math.max(0,s.retries-n):s.retries,o=s.maxRetryTime??Number.POSITIVE_INFINITY,c=Object.freeze({error:a,attemptNumber:e,retriesLeft:i,retriesConsumed:n});if(await s.onFailedAttempt(c),aw(r,o)<=0)throw a;const u=await s.shouldConsumeRetry(c),l=aw(r,o);if(l<=0||i<=0)throw a;if(a instanceof TypeError&&!N$(a)){if(u)throw a;return(h=s.signal)==null||h.throwIfAborted(),!1}if(!await s.shouldRetry(c))throw a;if(!u)return(m=s.signal)==null||m.throwIfAborted(),!1;const d=L$(n,s),f=Math.min(d,l);return f>0&&await new Promise((y,w)=>{var S,I;const g=()=>{var T;clearTimeout(b),(T=s.signal)==null||T.removeEventListener("abort",g),w(s.signal.reason)},b=setTimeout(()=>{var T;(T=s.signal)==null||T.removeEventListener("abort",g),y()},f);s.unref&&((S=b.unref)==null||S.call(b)),(I=s.signal)==null||I.addEventListener("abort",g,{once:!0})}),(_=s.signal)==null||_.throwIfAborted(),!0}async function U$(t,e={}){var a,i,o;if(e={...e},P$(e.retries),Object.hasOwn(e,"forever"))throw new Error("The `forever` option is no longer supported. For many use-cases, you can set `retries: Infinity` instead.");e.retries??(e.retries=10),e.factor??(e.factor=2),e.minTimeout??(e.minTimeout=1e3),e.maxTimeout??(e.maxTimeout=Number.POSITIVE_INFINITY),e.maxRetryTime??(e.maxRetryTime=Number.POSITIVE_INFINITY),e.randomize??(e.randomize=!1),e.onFailedAttempt??(e.onFailedAttempt=()=>{}),e.shouldRetry??(e.shouldRetry=()=>!0),e.shouldConsumeRetry??(e.shouldConsumeRetry=()=>!0),gu("factor",e.factor,{min:0,allowInfinity:!1}),gu("minTimeout",e.minTimeout,{min:0,allowInfinity:!1}),gu("maxTimeout",e.maxTimeout,{min:0,allowInfinity:!0}),gu("maxRetryTime",e.maxRetryTime,{min:0,allowInfinity:!0}),e.factor>0||(e.factor=1),(a=e.signal)==null||a.throwIfAborted();let n=0,r=0;const s=performance.now();for(;!Number.isFinite(e.retries)||r<=e.retries;){n++;try{(i=e.signal)==null||i.throwIfAborted();const c=await t(n);return(o=e.signal)==null||o.throwIfAborted(),c}catch(c){await j$({error:c,attemptNumber:n,retriesConsumed:r,startTime:s,options:e})&&r++}}throw new Error("Retry attempts exhausted without throwing an error.")}var jS={},US={exports:{}};(function(t){var e=Object.prototype.hasOwnProperty,n="~";function r(){}Object.create&&(r.prototype=Object.create(null),new r().__proto__||(n=!1));function s(c,u,l){this.fn=c,this.context=u,this.once=l||!1}function a(c,u,l,d,f){if(typeof l!="function")throw new TypeError("The listener must be a function");var h=new s(l,d||c,f),m=n?n+u:u;return c._events[m]?c._events[m].fn?c._events[m]=[c._events[m],h]:c._events[m].push(h):(c._events[m]=h,c._eventsCount++),c}function i(c,u){--c._eventsCount===0?c._events=new r:delete c._events[u]}function o(){this._events=new r,this._eventsCount=0}o.prototype.eventNames=function(){var u=[],l,d;if(this._eventsCount===0)return u;for(d in l=this._events)e.call(l,d)&&u.push(n?d.slice(1):d);return Object.getOwnPropertySymbols?u.concat(Object.getOwnPropertySymbols(l)):u},o.prototype.listeners=function(u){var l=n?n+u:u,d=this._events[l];if(!d)return[];if(d.fn)return[d.fn];for(var f=0,h=d.length,m=new Array(h);f<h;f++)m[f]=d[f].fn;return m},o.prototype.listenerCount=function(u){var l=n?n+u:u,d=this._events[l];return d?d.fn?1:d.length:0},o.prototype.emit=function(u,l,d,f,h,m){var _=n?n+u:u;if(!this._events[_])return!1;var y=this._events[_],w=arguments.length,g,b;if(y.fn){switch(y.once&&this.removeListener(u,y.fn,void 0,!0),w){case 1:return y.fn.call(y.context),!0;case 2:return y.fn.call(y.context,l),!0;case 3:return y.fn.call(y.context,l,d),!0;case 4:return y.fn.call(y.context,l,d,f),!0;case 5:return y.fn.call(y.context,l,d,f,h),!0;case 6:return y.fn.call(y.context,l,d,f,h,m),!0}for(b=1,g=new Array(w-1);b<w;b++)g[b-1]=arguments[b];y.fn.apply(y.context,g)}else{var S=y.length,I;for(b=0;b<S;b++)switch(y[b].once&&this.removeListener(u,y[b].fn,void 0,!0),w){case 1:y[b].fn.call(y[b].context);break;case 2:y[b].fn.call(y[b].context,l);break;case 3:y[b].fn.call(y[b].context,l,d);break;case 4:y[b].fn.call(y[b].context,l,d,f);break;default:if(!g)for(I=1,g=new Array(w-1);I<w;I++)g[I-1]=arguments[I];y[b].fn.apply(y[b].context,g)}}return!0},o.prototype.on=function(u,l,d){return a(this,u,l,d,!1)},o.prototype.once=function(u,l,d){return a(this,u,l,d,!0)},o.prototype.removeListener=function(u,l,d,f){var h=n?n+u:u;if(!this._events[h])return this;if(!l)return i(this,h),this;var m=this._events[h];if(m.fn)m.fn===l&&(!f||m.once)&&(!d||m.context===d)&&i(this,h);else{for(var _=0,y=[],w=m.length;_<w;_++)(m[_].fn!==l||f&&!m[_].once||d&&m[_].context!==d)&&y.push(m[_]);y.length?this._events[h]=y.length===1?y[0]:y:i(this,h)}return this},o.prototype.removeAllListeners=function(u){var l;return u?(l=n?n+u:u,this._events[l]&&i(this,l)):(this._events=new r,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=n,o.EventEmitter=o,t.exports=o})(US);var D$=US.exports,Wd={exports:{}},F$=(t,e)=>(e=e||(()=>{}),t.then(n=>new Promise(r=>{r(e())}).then(()=>n),n=>new Promise(r=>{r(e())}).then(()=>{throw n})));const B$=F$;class DS extends Error{constructor(e){super(e),this.name="TimeoutError"}}const FS=(t,e,n)=>new Promise((r,s)=>{if(typeof e!="number"||e<0)throw new TypeError("Expected `milliseconds` to be a positive number");if(e===1/0){r(t);return}const a=setTimeout(()=>{if(typeof n=="function"){try{r(n())}catch(c){s(c)}return}const i=typeof n=="string"?n:`Promise timed out after ${e} milliseconds`,o=n instanceof Error?n:new DS(i);typeof t.cancel=="function"&&t.cancel(),s(o)},e);B$(t.then(r,s),()=>{clearTimeout(a)})});Wd.exports=FS;Wd.exports.default=FS;Wd.exports.TimeoutError=DS;var z$=Wd.exports,Sg={},Tg={};Object.defineProperty(Tg,"__esModule",{value:!0});function H$(t,e,n){let r=0,s=t.length;for(;s>0;){const a=s/2|0;let i=r+a;n(t[i],e)<=0?(r=++i,s-=a+1):s=a}return r}Tg.default=H$;Object.defineProperty(Sg,"__esModule",{value:!0});const V$=Tg;class Z${constructor(){this._queue=[]}enqueue(e,n){n=Object.assign({priority:0},n);const r={priority:n.priority,run:e};if(this.size&&this._queue[this.size-1].priority>=n.priority){this._queue.push(r);return}const s=V$.default(this._queue,r,(a,i)=>i.priority-a.priority);this._queue.splice(s,0,r)}dequeue(){const e=this._queue.shift();return e==null?void 0:e.run}filter(e){return this._queue.filter(n=>n.priority===e.priority).map(n=>n.run)}get size(){return this._queue.length}}Sg.default=Z$;Object.defineProperty(jS,"__esModule",{value:!0});const W$=D$,BS=z$,G$=Sg,_u=()=>{},q$=new BS.TimeoutError;let K$=class extends W${constructor(e){var n,r,s,a;if(super(),this._intervalCount=0,this._intervalEnd=0,this._pendingCount=0,this._resolveEmpty=_u,this._resolveIdle=_u,e=Object.assign({carryoverConcurrencyCount:!1,intervalCap:1/0,interval:0,concurrency:1/0,autoStart:!0,queueClass:G$.default},e),!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${(r=(n=e.intervalCap)===null||n===void 0?void 0:n.toString())!==null&&r!==void 0?r:""}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${(a=(s=e.interval)===null||s===void 0?void 0:s.toString())!==null&&a!==void 0?a:""}\` (${typeof e.interval})`);this._carryoverConcurrencyCount=e.carryoverConcurrencyCount,this._isIntervalIgnored=e.intervalCap===1/0||e.interval===0,this._intervalCap=e.intervalCap,this._interval=e.interval,this._queue=new e.queueClass,this._queueClass=e.queueClass,this.concurrency=e.concurrency,this._timeout=e.timeout,this._throwOnTimeout=e.throwOnTimeout===!0,this._isPaused=e.autoStart===!1}get _doesIntervalAllowAnother(){return this._isIntervalIgnored||this._intervalCount<this._intervalCap}get _doesConcurrentAllowAnother(){return this._pendingCount<this._concurrency}_next(){this._pendingCount--,this._tryToStartAnother(),this.emit("next")}_resolvePromises(){this._resolveEmpty(),this._resolveEmpty=_u,this._pendingCount===0&&(this._resolveIdle(),this._resolveIdle=_u,this.emit("idle"))}_onResumeInterval(){this._onInterval(),this._initializeIntervalIfNeeded(),this._timeoutId=void 0}_isIntervalPaused(){const e=Date.now();if(this._intervalId===void 0){const n=this._intervalEnd-e;if(n<0)this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0;else return this._timeoutId===void 0&&(this._timeoutId=setTimeout(()=>{this._onResumeInterval()},n)),!0}return!1}_tryToStartAnother(){if(this._queue.size===0)return this._intervalId&&clearInterval(this._intervalId),this._intervalId=void 0,this._resolvePromises(),!1;if(!this._isPaused){const e=!this._isIntervalPaused();if(this._doesIntervalAllowAnother&&this._doesConcurrentAllowAnother){const n=this._queue.dequeue();return n?(this.emit("active"),n(),e&&this._initializeIntervalIfNeeded(),!0):!1}}return!1}_initializeIntervalIfNeeded(){this._isIntervalIgnored||this._intervalId!==void 0||(this._intervalId=setInterval(()=>{this._onInterval()},this._interval),this._intervalEnd=Date.now()+this._interval)}_onInterval(){this._intervalCount===0&&this._pendingCount===0&&this._intervalId&&(clearInterval(this._intervalId),this._intervalId=void 0),this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0,this._processQueue()}_processQueue(){for(;this._tryToStartAnother(););}get concurrency(){return this._concurrency}set concurrency(e){if(!(typeof e=="number"&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);this._concurrency=e,this._processQueue()}async add(e,n={}){return new Promise((r,s)=>{const a=async()=>{this._pendingCount++,this._intervalCount++;try{const i=this._timeout===void 0&&n.timeout===void 0?e():BS.default(Promise.resolve(e()),n.timeout===void 0?this._timeout:n.timeout,()=>{(n.throwOnTimeout===void 0?this._throwOnTimeout:n.throwOnTimeout)&&s(q$)});r(await i)}catch(i){s(i)}this._next()};this._queue.enqueue(a,n),this._tryToStartAnother(),this.emit("add")})}async addAll(e,n){return Promise.all(e.map(async r=>this.add(r,n)))}start(){return this._isPaused?(this._isPaused=!1,this._processQueue(),this):this}pause(){this._isPaused=!0}clear(){this._queue=new this._queueClass}async onEmpty(){if(this._queue.size!==0)return new Promise(e=>{const n=this._resolveEmpty;this._resolveEmpty=()=>{n(),e()}})}async onIdle(){if(!(this._pendingCount===0&&this._queue.size===0))return new Promise(e=>{const n=this._resolveIdle;this._resolveIdle=()=>{n(),e()}})}get size(){return this._queue.size}sizeBy(e){return this._queue.filter(e).length}get pending(){return this._pendingCount}get isPaused(){return this._isPaused}get timeout(){return this._timeout}set timeout(e){this._timeout=e}};var ms=jS.default=K$;const J$="default"in ms?ms.default:ms,X$=[408,425,429,500,502,503,504];let iw=class{constructor(e){Object.defineProperty(this,"maxConcurrency",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"maxRetries",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"maxQueueSizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"queue",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onFailedResponseHook",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"queueSizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:0}),this.maxConcurrency=e.maxConcurrency??1/0,this.maxRetries=e.maxRetries??6,this.maxQueueSizeBytes=e.maxQueueSizeBytes,this.queue=new J$({concurrency:this.maxConcurrency}),this.onFailedResponseHook=e==null?void 0:e.onFailedResponseHook}call(e,...n){return this.callWithOptions({},e,...n)}callWithOptions(e,n,...r){const s=e.sizeBytes??0;if(this.maxQueueSizeBytes!==void 0&&s>0&&this.queueSizeBytes+s>this.maxQueueSizeBytes)return Promise.reject(new Error(`Queue size limit (${this.maxQueueSizeBytes} bytes) exceeded. Current queue size: ${this.queueSizeBytes} bytes, attempted addition: ${s} bytes.`));s>0&&(this.queueSizeBytes+=s);const a=this.onFailedResponseHook;let i=this.queue.add(()=>U$(()=>n(...r).catch(o=>{throw o instanceof Error?o:new Error(o)}),{async onFailedAttempt({error:o}){if(typeof o!="object"||o==null)throw o;const c="message"in o&&typeof o.message=="string"?o.message:void 0;if(c!=null&&c.startsWith("Cancel")||c!=null&&c.startsWith("TimeoutError")||c!=null&&c.startsWith("AbortError")||"name"in o&&o.name==="TimeoutError"||"code"in o&&o.code==="ECONNABORTED")throw o;const u="response"in o?o.response:void 0;if(a&&await a(u))return;const l=(u==null?void 0:u.status)??("status"in o?o.status:void 0);if(l!=null&&(typeof l=="number"||typeof l=="string")&&!X$.includes(+l))throw o},retries:this.maxRetries,randomize:!0}),{throwOnTimeout:!0});return s>0&&(i=i.finally(()=>{this.queueSizeBytes-=s})),e.signal?Promise.race([i,new Promise((o,c)=>{var u;(u=e.signal)==null||u.addEventListener("abort",()=>{c(new Error("AbortError"))})})]):i}};function ow(t){return typeof(t==null?void 0:t._getType)=="function"}function cw(t){const e={type:t._getType(),data:{content:t.content}};return t!=null&&t.additional_kwargs&&Object.keys(t.additional_kwargs).length>0&&(e.data.additional_kwargs={...t.additional_kwargs}),e}function qh(t){return`Invalid prompt identifier format: "${t}". Expected one of:
18
- - "prompt-name" (for private prompts)
19
- - "owner/prompt-name" (for prompts with explicit owner)
20
- - "prompt-name:commit-hash" (with commit reference)
21
- - "owner/prompt-name:commit-hash" (with owner and commit)`}class Y$ extends Error{constructor(e){super(e),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="LangSmithConflictError",this.status=409}}class Q$ extends Error{constructor(e){super(e),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="LangSmithNotFoundError",this.status=404}}function Kh(t){return t!=null&&typeof t=="object"&&"name"in t&&(t==null?void 0:t.name)==="LangSmithNotFoundError"}function eN(t){return t!=null&&typeof t=="object"&&"name"in t&&(t==null?void 0:t.name)==="LangSmithConflictError"}async function ce(t,e,n){let r;if(t.ok){n&&(r=await t.text());return}if(t.status===403)try{const i=await t.json();(i==null?void 0:i.error)==="org_scoped_key_requires_workspace"&&(r="This API key is org-scoped and requires workspace specification. Please provide 'workspaceId' parameter, or set LANGSMITH_WORKSPACE_ID environment variable.")}catch{const o=new Error(`${t.status} ${t.statusText}`);throw o.status=t==null?void 0:t.status,o}if(r===void 0)try{r=await t.text()}catch{r=""}const s=`Failed to ${e}. Received status [${t.status}]: ${t.statusText}. Message: ${r}`;if(t.status===404)throw new Q$(s);if(t.status===409)throw new Y$(s);const a=new Error(s);throw a.status=t.status,a}const zS="ERR_CONFLICTING_ENDPOINTS";class tN extends Error{constructor(){super("You cannot provide both LANGSMITH_ENDPOINT / LANGCHAIN_ENDPOINT and LANGSMITH_RUNS_ENDPOINTS."),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:zS}),this.name="ConflictingEndpointsError"}}function nN(t){return typeof t=="object"&&t!==null&&t.code===zS}function En(t){if(!t||t.split("/").length>2||t.startsWith("/")||t.endsWith("/")||t.split(":").length>2)throw new Error(qh(t));const[e,n]=t.split(":"),r=n||"latest";if(e.includes("/")){const[s,a]=e.split("/",2);if(!s||!a)throw new Error(qh(t));return[s,a,r]}else{if(!e)throw new Error(qh(t));return["-",e,r]}}var uw="[...]",rN={result:"[Circular]"},Yl=[],fi=[];const sN=new TextEncoder;function aN(){return{depthLimit:Number.MAX_SAFE_INTEGER,edgesLimit:Number.MAX_SAFE_INTEGER}}function yu(t){return sN.encode(t)}function HS(t){if(t&&typeof t=="object"&&t!==null){if(t instanceof Map)return Object.fromEntries(t);if(t instanceof Set)return Array.from(t);if(t instanceof Date)return t.toISOString();if(t instanceof RegExp)return t.toString();if(t instanceof Error)return{name:t.name,message:t.message}}else if(typeof t=="bigint")return t.toString();return t}function iN(t){return function(e,n){return HS(n)}}function oN(t){try{let s=function(l){const d=r(l);return d>n&&(n=d),d+2},a=function(l){return l===0?2:2+l*4},i=function(l){return l===void 0||typeof l=="function"||typeof l=="symbol"},o=function(l){return l===void 0||typeof l=="function"||typeof l=="symbol"?4:c(l)},c=function(l){if(l===null)return 4;if(l===void 0)return 0;const d=typeof l;if(d==="boolean")return 5;if(d==="number")return Number.isFinite(l)?l.toString().length:4;if(d==="bigint")return l.toString().length+2;if(d==="string")return s(l);if(d==="function"||d==="symbol")return 0;const f=l;if(f instanceof Date)return 26;if(f instanceof RegExp)return r(f.toString())+2;if(f instanceof Error){const m=f.name??"",_=f.message??"";return 22+r(m)+r(_)}if(typeof Buffer<"u"&&f instanceof Buffer)return 28+a(f.byteLength);if(ArrayBuffer.isView(f)){if(f instanceof DataView)return 2;const m=f.length??0,y=f instanceof Float32Array||f instanceof Float64Array?30:12;return 2+m*y}if(f instanceof ArrayBuffer)return 2;if(e.has(f))return 24;if(typeof f.toJSON=="function"){let m;try{m=f.toJSON("")}catch{return 16}e.add(f);const _=c(m);return e.delete(f),_}e.add(f);let h;if(Array.isArray(f)){h=2;const m=f.length;for(let _=0;_<m;_++)h+=o(f[_]),_<m-1&&(h+=1)}else if(f instanceof Map){h=2;let m=0;for(const[_,y]of f){if(i(y))continue;m>0&&(h+=1);const w=typeof _=="string"?_:String(_);h+=r(w)+3,h+=c(y),m++}}else if(f instanceof Set){h=2;let m=0;for(const _ of f)m>0&&(h+=1),h+=o(_),m++}else{h=2;let m=0;const _=Object.keys(f);for(let y=0;y<_.length;y++){const w=_[y],g=f[w];i(g)||(m>0&&(h+=1),h+=r(w)+3,h+=c(g),m++)}}return e.delete(f),h};const e=new Set;let n=0;const r=typeof Buffer<"u"&&typeof Buffer.byteLength=="function"?l=>Buffer.byteLength(l,"utf8"):l=>l.length;return{size:c(t),maxStringLen:n}}catch{return{size:an(t).length,maxStringLen:0}}}function an(t,e,n,r,s){var a;try{const i=JSON.stringify(t,iN(n),r);return yu(i)}catch(i){if(!((a=i.message)!=null&&a.includes("Converting circular structure to JSON")))return console.warn(`[WARNING]: LangSmith received unserializable value.${e?`
22
- Context: ${e}`:""}`),yu("[Unserializable]");Tt("SUPPRESS_CIRCULAR_JSON_WARNINGS")!=="true"&&console.warn(`[WARNING]: LangSmith received circular JSON. This will decrease tracer performance. ${e?`
23
- Context: ${e}`:""}`),typeof s>"u"&&(s=aN()),Ap(t,"",0,[],void 0,0,s);let o;try{fi.length===0?o=JSON.stringify(t,n,r):o=JSON.stringify(t,cN(n),r)}catch{return yu("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;Yl.length!==0;){const c=Yl.pop();c.length===4?Object.defineProperty(c[0],c[1],c[3]):c[0][c[1]]=c[2]}}return yu(o)}}function Jh(t,e,n,r){var s=Object.getOwnPropertyDescriptor(r,n);s.get!==void 0?s.configurable?(Object.defineProperty(r,n,{value:t}),Yl.push([r,n,e,s])):fi.push([e,n,t]):(r[n]=t,Yl.push([r,n,e]))}function Ap(t,e,n,r,s,a,i){a+=1;var o;if(typeof t=="object"&&t!==null){for(o=0;o<r.length;o++)if(r[o]===t){Jh(rN,t,e,s);return}if(typeof i.depthLimit<"u"&&a>i.depthLimit){Jh(uw,t,e,s);return}if(typeof i.edgesLimit<"u"&&n+1>i.edgesLimit){Jh(uw,t,e,s);return}if(r.push(t),Array.isArray(t))for(o=0;o<t.length;o++)Ap(t[o],o,o,r,t,a,i);else{t=HS(t);var c=Object.keys(t);for(o=0;o<c.length;o++){var u=c[o];Ap(t[u],u,o,r,t,a,i)}}r.pop()}}function cN(t){return t=typeof t<"u"?t:function(e,n){return n},function(e,n){if(fi.length>0)for(var r=0;r<fi.length;r++){var s=fi[r];if(s[1]===e&&s[0]===n){n=s[2],fi.splice(r,1);break}}return t.call(this,e,n)}}class uN{constructor(){Object.defineProperty(this,"worker",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"nextId",{enumerable:!0,configurable:!0,writable:!0,value:1}),Object.defineProperty(this,"pending",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"disabled",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"startPromise",{enumerable:!0,configurable:!0,writable:!0,value:null})}async ensureStarted(){if(this.disabled)return!1;if(this.worker!==null)return!0;if(this.startPromise!==null)return this.startPromise;this.startPromise=this._start();try{return await this.startPromise}finally{this.startPromise=null}}async _start(){return this.disabled=!0,!1}async serialize(e){if(!await this.ensureStarted())return null;const r=this.nextId++;return new Promise((s,a)=>{this.pending.set(r,{resolve:s,reject:a});try{this.worker.postMessage({id:r,op:"serialize",payload:e})}catch(i){this.pending.delete(r),a(i)}})}async terminate(){this.worker&&(await this.worker.terminate(),this.worker=null);for(const[,e]of this.pending)e.reject(new Error("worker terminated"));this.pending.clear()}}let Xh=null;function lN(){return Xh===null&&(Xh=new uN),Xh}const dN=64*1024,hN=2048;function fN(t,e=dN,n=hN){if(t===null||typeof t!="object")return typeof t=="string"&&t.length>=e;const r=[t],s=new Set;let a=0;for(;r.length>0;){if(a++>=n)return!1;const i=r.pop();if(i==null)continue;const o=typeof i;if(o==="string"){if(i.length>=e)return!0;continue}if(o!=="object")continue;const c=i;if(s.has(c)||(s.add(c),c instanceof Date||c instanceof RegExp||c instanceof Error||c instanceof ArrayBuffer||ArrayBuffer.isView(c)))continue;if(Array.isArray(c)){for(let l=c.length-1;l>=0;l--)r.push(c[l]);continue}if(c instanceof Map){for(const[,l]of c)r.push(l);continue}if(c instanceof Set){for(const l of c)r.push(l);continue}const u=Object.keys(c);for(let l=u.length-1;l>=0;l--)r.push(c[u[l]])}return!1}function lw(t){return typeof t=="string"&&t.length>0&&!t.includes("Z")&&!t.includes("+")&&!t.includes("-",10)?t+"Z":t}function ro(t){return{...t,start_time:lw(t.start_time),end_time:lw(t.end_time)}}function dw(t,e,n){if(n)return t;const r=NS(),s=e??PS(),a=t.extra??{},i=a.metadata;return t.extra={...a,runtime:{...r,...a==null?void 0:a.runtime},metadata:{...s,...s.revision_id||"revision_id"in t&&t.revision_id?{revision_id:("revision_id"in t?t.revision_id:void 0)??s.revision_id}:{},...i}},t}const pN=t=>{const e=(t==null?void 0:t.toString())??Tt("TRACING_SAMPLING_RATE");if(e===void 0)return;const n=parseFloat(e);if(n<0||n>1)throw new Error(`LANGSMITH_TRACING_SAMPLING_RATE must be between 0 and 1 if set. Got: ${n}`);return n},mN=t=>{const n=t.replace("http://","").replace("https://","").split("/")[0].split(":")[0];return n==="localhost"||n==="127.0.0.1"||n==="::1"};async function gN(t){const e=[];for await(const n of t)e.push(n);return e}function wu(t){if(t!==void 0)return t.trim().replace(/^"(.*)"$/,"$1").replace(/^'(.*)'$/,"$1")}const _N=async t=>{if((t==null?void 0:t.status)===429){const e=parseInt(t.headers.get("retry-after")??"10",10)*1e3;if(e>0)return await new Promise(n=>setTimeout(n,e)),!0}return!1};function hw(t){return typeof t=="number"?Number(t.toFixed(4)):t}const yN=24*1024*1024,VS=1024*1024*1024,wN=1e4,bN=100,fw="https://api.smith.langchain.com";class vN{constructor(e){Object.defineProperty(this,"items",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"sizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"maxSizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSizeBytes=e??VS}peek(){return this.items[0]}push(e){let n;const r=new Promise(a=>{n=a}),s=Tt("PERF_OPTIMIZATION")==="true"?oN(e.item).size:an(e.item,`Serializing run with id: ${e.item.id}`).length;return this.sizeBytes+s>this.maxSizeBytes&&this.items.length>0?(console.warn(`AutoBatchQueue size limit (${this.maxSizeBytes} bytes) exceeded. Dropping run with id: ${e.item.id}. Current queue size: ${this.sizeBytes} bytes, attempted addition: ${s} bytes.`),n(),r):(this.items.push({action:e.action,payload:e.item,otelContext:e.otelContext,apiKey:e.apiKey,apiUrl:e.apiUrl,itemPromiseResolve:n,itemPromise:r,size:s}),this.sizeBytes+=s,r)}pop({upToSizeBytes:e,upToSize:n}){var a;if(e<1)throw new Error("Number of bytes to pop off may not be less than 1.");const r=[];let s=0;for(;s+(((a=this.peek())==null?void 0:a.size)??0)<e&&this.items.length>0&&r.length<n;){const i=this.items.shift();i&&(r.push(i),s+=i.size,this.sizeBytes-=i.size)}if(r.length===0&&this.items.length>0){const i=this.items.shift();r.push(i),s+=i.size,this.sizeBytes-=i.size}return[r.map(i=>({action:i.action,item:i.payload,otelContext:i.otelContext,apiKey:i.apiKey,apiUrl:i.apiUrl,size:i.size})),()=>r.forEach(i=>i.itemPromiseResolve())]}}class jr{get tracingMode(){return this._tracingMode}get _fetch(){return this.fetchImplementation||NR(this.debug)}_trackDrain(e){this._pendingDrains.add(e),e.finally(()=>{this._pendingDrains.delete(e)})}async _serializeBody(e,n){if(!(Tt("PERF_OPTIMIZATION")==="true")||this.manualFlushMode||!fN(e)||(this._serializeWorker===void 0&&(this._serializeWorker=lN()),this._serializeWorker===null))return an(e,n);try{const s=await this._serializeWorker.serialize(e);return s===null?(this._serializeWorker=null,an(e,n)):s}catch{return an(e,n)}}constructor(e={}){var a;Object.defineProperty(this,"apiKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"apiUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"webUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"workspaceId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"caller",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"batchIngestCaller",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"timeout_ms",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_tenantId",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"hideInputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"hideOutputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"hideMetadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"omitTracedRuntimeInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tracingSampleRate",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"filteredPostUuids",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"autoBatchTracing",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"autoBatchQueue",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"autoBatchTimeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"autoBatchAggregationDelayMs",{enumerable:!0,configurable:!0,writable:!0,value:250}),Object.defineProperty(this,"batchSizeBytesLimit",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"batchSizeLimit",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"fetchOptions",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"settings",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"blockOnRootRunFinalization",{enumerable:!0,configurable:!0,writable:!0,value:Wr("LANGSMITH_TRACING_BACKGROUND")==="false"}),Object.defineProperty(this,"traceBatchConcurrency",{enumerable:!0,configurable:!0,writable:!0,value:5}),Object.defineProperty(this,"_serverInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_getServerInfoPromise",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"manualFlushMode",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_serializeWorker",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_pendingDrains",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"langSmithToOTELTranslator",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_tracingMode",{enumerable:!0,configurable:!0,writable:!0,value:"langsmith"}),Object.defineProperty(this,"fetchImplementation",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cachedLSEnvVarsForMetadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_promptCache",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"multipartStreamingDisabled",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_multipartDisabled",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_runCompressionDisabled",{enumerable:!0,configurable:!0,writable:!0,value:Tt("DISABLE_RUN_COMPRESSION")==="true"}),Object.defineProperty(this,"failedTracesDir",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"failedTracesMaxBytes",{enumerable:!0,configurable:!0,writable:!0,value:100*1024*1024}),Object.defineProperty(this,"_customHeaders",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"debug",{enumerable:!0,configurable:!0,writable:!0,value:Wr("LANGSMITH_DEBUG")==="true"});const n=jr.getDefaultClientConfig();if(this.tracingSampleRate=pN(e.tracingSamplingRate),this.apiUrl=wu(e.apiUrl??n.apiUrl)??"",this.apiUrl.endsWith("/")&&(this.apiUrl=this.apiUrl.slice(0,-1)),this.apiKey=wu(e.apiKey??n.apiKey),this.webUrl=wu(e.webUrl??n.webUrl),(a=this.webUrl)!=null&&a.endsWith("/")&&(this.webUrl=this.webUrl.slice(0,-1)),this.workspaceId=wu(e.workspaceId??Tt("WORKSPACE_ID")),this.timeout_ms=e.timeout_ms??9e4,this.caller=new iw({...e.callerOptions??{},maxRetries:4,debug:e.debug??this.debug}),this.traceBatchConcurrency=e.traceBatchConcurrency??this.traceBatchConcurrency,this.traceBatchConcurrency<1)throw new Error("Trace batch concurrency must be positive.");this.debug=e.debug??this.debug,this.fetchImplementation=e.fetchImplementation,this.failedTracesDir=Tt("FAILED_TRACES_DIR")||void 0;const r=Tt("FAILED_TRACES_MAX_MB");if(r){const i=parseInt(r,10);Number.isFinite(i)&&i>0&&(this.failedTracesMaxBytes=i*1024*1024)}const s=e.maxIngestMemoryBytes??VS;this.batchIngestCaller=new iw({maxRetries:4,maxConcurrency:this.traceBatchConcurrency,maxQueueSizeBytes:s,...e.callerOptions??{},onFailedResponseHook:_N,debug:e.debug??this.debug}),this.hideInputs=e.hideInputs??e.anonymizer??n.hideInputs,this.hideOutputs=e.hideOutputs??e.anonymizer??n.hideOutputs,this.hideMetadata=e.hideMetadata??n.hideMetadata,this.omitTracedRuntimeInfo=e.omitTracedRuntimeInfo??!1,this.autoBatchTracing=e.autoBatchTracing??this.autoBatchTracing,this.autoBatchQueue=new vN(s),this.blockOnRootRunFinalization=e.blockOnRootRunFinalization??this.blockOnRootRunFinalization,this.batchSizeBytesLimit=e.batchSizeBytesLimit,this.batchSizeLimit=e.batchSizeLimit,this.fetchOptions=e.fetchOptions||{},this.manualFlushMode=e.manualFlushMode??this.manualFlushMode,this._tracingMode=MS(e.tracingMode),this._tracingMode==="otel"&&(this.langSmithToOTELTranslator=new O$),this.cachedLSEnvVarsForMetadata=PS(),e.cache!==void 0&&e.disablePromptCache&&dl("Both 'cache' and 'disablePromptCache' were provided. The 'cache' parameter is deprecated and will be removed in a future version. Using 'cache' parameter value."),e.cache!==void 0?(dl("The 'cache' parameter is deprecated and will be removed in a future version. Use 'configureGlobalPromptCache()' to configure the global cache, or 'disablePromptCache: true' to disable caching for this client."),e.cache===!1?this._promptCache=void 0:e.cache===!0?this._promptCache=tw:this._promptCache=e.cache):e.disablePromptCache||(this._promptCache=tw),this._customHeaders=e.headers??{}}static getDefaultClientConfig(){const e=Tt("API_KEY"),n=Tt("ENDPOINT")??fw,r=Tt("HIDE_INPUTS")==="true",s=Tt("HIDE_OUTPUTS")==="true",a=Tt("HIDE_METADATA")==="true";return{apiUrl:n,apiKey:e,webUrl:void 0,hideInputs:r,hideOutputs:s,hideMetadata:a}}getHostUrl(){return this.webUrl?this.webUrl:mN(this.apiUrl)?(this.webUrl="http://localhost:3000",this.webUrl):this.apiUrl.endsWith("/api/v1")?(this.webUrl=this.apiUrl.replace("/api/v1",""),this.webUrl):this.apiUrl.includes("/api")&&!this.apiUrl.split(".",1)[0].endsWith("api")?(this.webUrl=this.apiUrl.replace("/api",""),this.webUrl):this.apiUrl.split(".",1)[0].includes("dev")?(this.webUrl="https://dev.smith.langchain.com",this.webUrl):this.apiUrl.split(".",1)[0].includes("eu")?(this.webUrl="https://eu.smith.langchain.com",this.webUrl):this.apiUrl.split(".",1)[0].includes("aws")?(this.webUrl="https://aws.smith.langchain.com",this.webUrl):this.apiUrl.split(".",1)[0].includes("beta")?(this.webUrl="https://beta.smith.langchain.com",this.webUrl):(this.webUrl="https://smith.langchain.com",this.webUrl)}get _mergedHeaders(){const e={"User-Agent":`langsmith-js/${CS}`,...this._customHeaders};return this.apiKey&&(e["x-api-key"]=`${this.apiKey}`),this.workspaceId&&(e["x-tenant-id"]=this.workspaceId),e}get headers(){return this._customHeaders}set headers(e){this._customHeaders=e??{}}_getPlatformEndpointPath(e){return this.apiUrl.slice(-3)!=="/v1"&&this.apiUrl.slice(-4)!=="/v1/"?`/v1/platform/${e}`:`/platform/${e}`}async processInputs(e){return this.hideInputs===!1?e:this.hideInputs===!0?{}:typeof this.hideInputs=="function"?this.hideInputs(e):e}async processOutputs(e){return this.hideOutputs===!1?e:this.hideOutputs===!0?{}:typeof this.hideOutputs=="function"?this.hideOutputs(e):e}async processMetadata(e){return this.hideMetadata===!1?e:this.hideMetadata===!0?{}:typeof this.hideMetadata=="function"?this.hideMetadata(e):e}_filterNewTokenEvents(e){return!e||e.length===0?e:e.map(n=>{if(n.name==="new_token"){const{kwargs:r,...s}=n;return s}return n})}async prepareRunCreateOrUpdateInputs(e){const n={...e};return n.inputs!==void 0&&(n.inputs=await this.processInputs(n.inputs)),n.outputs!==void 0&&(n.outputs=await this.processOutputs(n.outputs)),n.extra!=null&&"metadata"in n.extra&&(n.extra={...n.extra,metadata:await this.processMetadata(n.extra.metadata)}),n.events!==void 0&&(n.events=this._filterNewTokenEvents(n.events)),n}async _getResponse(e,n){const r=(n==null?void 0:n.toString())??"",s=`${this.apiUrl}${e}?${r}`;return await this.caller.call(async()=>{const i=await this._fetch(s,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await ce(i,`fetch ${e}`),i})}async _get(e,n){return(await this._getResponse(e,n)).json()}async*_getPaginated(e,n=new URLSearchParams,r){let s=Number(n.get("offset"))||0;const a=Number(n.get("limit"))||100;for(;;){n.set("offset",String(s)),n.set("limit",String(a));const i=`${this.apiUrl}${e}?${n}`,o=await this.caller.call(async()=>{const u=await this._fetch(i,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await ce(u,`fetch ${e}`),u}),c=r?r(await o.json()):await o.json();if(c.length===0||(yield c,c.length<a))break;s+=c.length}}async*_getCursorPaginatedList(e,n=null,r="POST",s="runs"){const a=n?{...n}:{};for(;;){const i=JSON.stringify(a),c=await(await this.caller.call(async()=>{const l=await this._fetch(`${this.apiUrl}${e}`,{method:r,headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await ce(l,`fetch ${e}`),l})).json();if(!c||!c[s])break;yield c[s];const u=c.cursors;if(!u||!u.next)break;a.cursor=u.next}}_shouldSample(){return this.tracingSampleRate===void 0?!0:Math.random()<this.tracingSampleRate}_filterForSampling(e,n=!1){if(this.tracingSampleRate===void 0)return e;if(n){const r=[];for(const s of e)this.filteredPostUuids.has(s.trace_id)?s.id===s.trace_id&&this.filteredPostUuids.delete(s.trace_id):r.push(s);return r}else{const r=[];for(const s of e){const a=s.trace_id??s.id;this.filteredPostUuids.has(a)||(s.id===a?this._shouldSample()?r.push(s):this.filteredPostUuids.add(a):r.push(s))}return r}}async _getBatchSizeLimitBytes(){var n;const e=await this._ensureServerInfo();return this.batchSizeBytesLimit??((n=e==null?void 0:e.batch_ingest_config)==null?void 0:n.size_limit_bytes)??yN}async _getBatchSizeLimit(){var n;const e=await this._ensureServerInfo();return this.batchSizeLimit??((n=e==null?void 0:e.batch_ingest_config)==null?void 0:n.size_limit)??bN}async _getDatasetExamplesMultiPartSupport(){var n;return((n=(await this._ensureServerInfo()).instance_flags)==null?void 0:n.dataset_examples_multipart_enabled)??!1}drainAutoBatchQueue({batchSizeLimitBytes:e,batchSizeLimit:n}){const r=[];for(;this.autoBatchQueue.items.length>0;){const[s,a]=this.autoBatchQueue.pop({upToSizeBytes:e,upToSize:n});if(!s.length){a();break}const i=s.reduce((u,l)=>{const d=l.apiUrl??this.apiUrl,f=l.apiKey??this.apiKey,m=l.apiKey===this.apiKey&&l.apiUrl===this.apiUrl?"default":`${d}|${f}`;return u[m]||(u[m]=[]),u[m].push(l),u},{}),o=[];for(const[u,l]of Object.entries(i)){const d=this._processBatch(l,{apiUrl:u==="default"?void 0:u.split("|")[0],apiKey:u==="default"?void 0:u.split("|")[1]});o.push(d)}const c=Promise.all(o).finally(a);r.push(c)}return Promise.all(r)}static async _writeTraceToFallbackDir(e,n,r,s,a){try{const i=typeof n=="string"?Buffer.from(n,"utf8"):Buffer.from(n),o=JSON.stringify({version:1,endpoint:s,headers:r,body_base64:i.toString("base64")}),c=`trace_${Date.now()}_${no().slice(0,8)}.json`,u=Ep.join(e,c);if(jr._fallbackDirsCreated.has(e)||(await o$(e),jr._fallbackDirsCreated.add(e)),a!==void 0&&a>0)try{const d=(await u$(e)).filter(h=>h.startsWith("trace_")&&h.endsWith(".json"));let f=0;for(const h of d){const{size:m}=await l$(Ep.join(e,h));f+=m}if(f>=a){console.warn(`Could not write trace to fallback dir ${e} as it's already over size limit (${f} bytes >= ${a} bytes). Increase LANGSMITH_FAILED_TRACES_MAX_MB if possible.`);return}}catch{}await c$(u,o),console.warn(`LangSmith trace upload failed; data saved to ${u} for later replay.`)}catch(i){console.error(`LangSmith tracing error: could not write trace to fallback dir ${e}:`,i)}}async _processBatch(e,n){var s,a;if(!e.length)return;const r=e.reduce((i,o)=>i+(o.size??0),0);try{if(this.langSmithToOTELTranslator!==void 0)this._sendBatchToOTELTranslator(e);else{const i={runCreates:e.filter(u=>u.action==="create").map(u=>u.item),runUpdates:e.filter(u=>u.action==="update").map(u=>u.item)},o=await this._ensureServerInfo();if(!this._multipartDisabled&&(((s=o==null?void 0:o.batch_ingest_config)==null?void 0:s.use_multipart_endpoint)??!0)){const u=!this._runCompressionDisabled&&((a=o==null?void 0:o.instance_flags)==null?void 0:a.gzip_body_enabled);try{await this.multipartIngestRuns(i,{...n,useGzip:u,sizeBytes:r})}catch(l){if(Kh(l))this._multipartDisabled=!0,await this.batchIngestRuns(i,{...n,sizeBytes:r});else throw l}}else await this.batchIngestRuns(i,{...n,sizeBytes:r})}}catch(i){console.error("Error exporting batch:",i)}}_sendBatchToOTELTranslator(e){if(this.langSmithToOTELTranslator!==void 0){const n=new Map,r=[];for(const s of e)s.item.id&&s.otelContext&&(n.set(s.item.id,s.otelContext),s.action==="create"?r.push({operation:"post",id:s.item.id,trace_id:s.item.trace_id??s.item.id,run:s.item}):r.push({operation:"patch",id:s.item.id,trace_id:s.item.trace_id??s.item.id,run:s.item}));this.langSmithToOTELTranslator.exportBatch(r,n)}}async processRunOperation(e){clearTimeout(this.autoBatchTimeout),this.autoBatchTimeout=void 0,e.item=dw(e.item,this.cachedLSEnvVarsForMetadata,this.omitTracedRuntimeInfo);const n=this.autoBatchQueue.push(e);if(this.manualFlushMode)return n;const r=await this._getBatchSizeLimitBytes(),s=await this._getBatchSizeLimit();return(this.autoBatchQueue.sizeBytes>r||this.autoBatchQueue.items.length>s)&&this._trackDrain(this.drainAutoBatchQueue({batchSizeLimitBytes:r,batchSizeLimit:s})),this.autoBatchQueue.items.length>0&&(this.autoBatchTimeout=setTimeout(()=>{this.autoBatchTimeout=void 0,this._trackDrain(this.drainAutoBatchQueue({batchSizeLimitBytes:r,batchSizeLimit:s}))},this.autoBatchAggregationDelayMs)),n}async _getServerInfo(){const n=await(await this.caller.call(async()=>{const r=await this._fetch(`${this.apiUrl}/info`,{method:"GET",headers:{...this._mergedHeaders,Accept:"application/json"},signal:AbortSignal.timeout(wN),...this.fetchOptions});return await ce(r,"get server info"),r})).json();return this.debug&&console.log(`
24
- === LangSmith Server Configuration ===
25
- `+JSON.stringify(n,null,2)+`
26
- `),n}async _ensureServerInfo(){return this._getServerInfoPromise===void 0&&(this._getServerInfoPromise=(async()=>{if(this._serverInfo===void 0)try{this._serverInfo=await this._getServerInfo()}catch(e){console.warn(`[LANGSMITH]: Failed to fetch info on supported operations. Falling back to batch operations and default limits. Info: ${e.status??"Unspecified status code"} ${e.message}`)}return this._serverInfo??{}})()),this._getServerInfoPromise.then(e=>(this._serverInfo===void 0&&(this._getServerInfoPromise=void 0),e))}async _getSettings(){return this.settings||(this.settings=this._get("/settings")),await this.settings}async flush(){const e=await this._getBatchSizeLimitBytes(),n=await this._getBatchSizeLimit();await this.drainAutoBatchQueue({batchSizeLimitBytes:e,batchSizeLimit:n})}_cloneCurrentOTELContext(){const e=LS(),n=A$();if(this.langSmithToOTELTranslator!==void 0){const r=e.getActiveSpan();if(r)return e.setSpan(n.active(),r)}}async createRun(e,n){if(!this._filterForSampling([e]).length)return;const r={...this._mergedHeaders,"Content-Type":"application/json"},s=e.project_name;delete e.project_name;const a=await this.prepareRunCreateOrUpdateInputs({session_name:s,...e,start_time:e.start_time??Date.now()});if(this.autoBatchTracing&&a.trace_id!==void 0&&a.dotted_order!==void 0){const c=this._cloneCurrentOTELContext();this.processRunOperation({action:"create",item:a,otelContext:c,apiKey:n==null?void 0:n.apiKey,apiUrl:n==null?void 0:n.apiUrl}).catch(console.error);return}const i=dw(a,this.cachedLSEnvVarsForMetadata,this.omitTracedRuntimeInfo);(n==null?void 0:n.apiKey)!==void 0&&(r["x-api-key"]=n.apiKey),(n==null?void 0:n.workspaceId)!==void 0&&(r["x-tenant-id"]=n.workspaceId);const o=an(i,`Creating run with id: ${i.id}`);await this.caller.call(async()=>{const c=await this._fetch(`${(n==null?void 0:n.apiUrl)??this.apiUrl}/runs`,{method:"POST",headers:r,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await ce(c,"create run",!0),c})}async batchIngestRuns({runCreates:e,runUpdates:n},r){if(e===void 0&&n===void 0)return;let s=await Promise.all((e==null?void 0:e.map(c=>this.prepareRunCreateOrUpdateInputs(c)))??[]),a=await Promise.all((n==null?void 0:n.map(c=>this.prepareRunCreateOrUpdateInputs(c)))??[]);if(s.length>0&&a.length>0){const c=s.reduce((l,d)=>(d.id&&(l[d.id]=d),l),{}),u=[];for(const l of a)l.id!==void 0&&c[l.id]?c[l.id]={...c[l.id],...l}:u.push(l);s=Object.values(c),a=u}const i={post:s,patch:a};if(!i.post.length&&!i.patch.length)return;const o={post:[],patch:[]};for(const c of["post","patch"]){const u=c,l=i[u].reverse();let d=l.pop();for(;d!==void 0;)o[u].push(d),d=l.pop()}if(o.post.length>0||o.patch.length>0){const c=o.post.map(u=>u.id).concat(o.patch.map(u=>u.id)).join(",");await this._postBatchIngestRuns(await this._serializeBody(o,`Ingesting runs with ids: ${c}`),r)}}async _postBatchIngestRuns(e,n){const r={...this._mergedHeaders,"Content-Type":"application/json",Accept:"application/json"};(n==null?void 0:n.apiKey)!==void 0&&(r["x-api-key"]=n.apiKey),await this.batchIngestCaller.callWithOptions({sizeBytes:n==null?void 0:n.sizeBytes},async()=>{const s=await this._fetch(`${(n==null?void 0:n.apiUrl)??this.apiUrl}/runs/batch`,{method:"POST",headers:r,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:e});return await ce(s,"batch create run",!0),s})}async multipartIngestRuns({runCreates:e,runUpdates:n},r){if(e===void 0&&n===void 0)return;const s={};let a=[];for(const d of e??[]){const f=await this.prepareRunCreateOrUpdateInputs(d);f.id!==void 0&&f.attachments!==void 0&&(s[f.id]=f.attachments),delete f.attachments,a.push(f)}let i=[];for(const d of n??[])i.push(await this.prepareRunCreateOrUpdateInputs(d));if(a.find(d=>d.trace_id===void 0||d.dotted_order===void 0)!==void 0)throw new Error('Multipart ingest requires "trace_id" and "dotted_order" to be set when creating a run');if(i.find(d=>d.trace_id===void 0||d.dotted_order===void 0)!==void 0)throw new Error('Multipart ingest requires "trace_id" and "dotted_order" to be set when updating a run');if(a.length>0&&i.length>0){const d=a.reduce((h,m)=>(m.id&&(h[m.id]=m),h),{}),f=[];for(const h of i)h.id!==void 0&&d[h.id]?d[h.id]={...d[h.id],...h}:f.push(h);a=Object.values(d),i=f}if(a.length===0&&i.length===0)return;const u=[],l=[];for(const[d,f]of[["post",a],["patch",i]])for(const h of f){const{inputs:m,outputs:_,events:y,extra:w,error:g,serialized:b,attachments:S,...I}=h,T={inputs:m,outputs:_,events:y,extra:w,error:g,serialized:b},x=await this._serializeBody(I,`Serializing for multipart ingestion of run with id: ${I.id}`);l.push({name:`${d}.${I.id}`,payload:new Blob([x],{type:`application/json; length=${x.length}`})});for(const[A,M]of Object.entries(T)){if(M===void 0)continue;const O=await this._serializeBody(M,`Serializing ${A} for multipart ingestion of run with id: ${I.id}`);l.push({name:`${d}.${I.id}.${A}`,payload:new Blob([O],{type:`application/json; length=${O.length}`})})}if(I.id!==void 0){const A=s[I.id];if(A){delete s[I.id];for(const[M,O]of Object.entries(A)){let $,H;if(Array.isArray(O)?[$,H]=O:($=O.mimeType,H=O.data),M.includes(".")){console.warn(`Skipping attachment '${M}' for run ${I.id}: Invalid attachment name. Attachment names must not contain periods ('.'). Please rename the attachment and try again.`);continue}l.push({name:`attachment.${I.id}.${M}`,payload:new Blob([H],{type:`${$}; length=${H.byteLength}`})})}}}u.push(`trace=${I.trace_id},id=${I.id}`)}await this._sendMultipartRequest(l,u.join("; "),r)}async _createNodeFetchBody(e,n){const r=[];for(const i of e)r.push(new Blob([`--${n}\r
27
- `])),r.push(new Blob([`Content-Disposition: form-data; name="${i.name}"\r
28
- `,`Content-Type: ${i.payload.type}\r
29
- \r
30
- `])),r.push(i.payload),r.push(new Blob([`\r
31
- `]));return r.push(new Blob([`--${n}--\r
32
- `])),await new Blob(r).arrayBuffer()}async _createMultipartStream(e,n){const r=new TextEncoder;return new ReadableStream({async start(a){const i=async o=>{typeof o=="string"?a.enqueue(r.encode(o)):a.enqueue(o)};for(const o of e){await i(`--${n}\r
33
- `),await i(`Content-Disposition: form-data; name="${o.name}"\r
34
- `),await i(`Content-Type: ${o.payload.type}\r
35
- \r
36
- `);const u=o.payload.stream().getReader();try{let l;for(;!(l=await u.read()).done;)a.enqueue(l.value)}finally{u.releaseLock()}await i(`\r
37
- `)}await i(`--${n}--\r
38
- `),a.close()}})}async _sendMultipartRequest(e,n,r){const s="----LangSmithFormBoundary"+Math.random().toString(36).slice(2),a=()=>this._createNodeFetchBody(e,s),i=()=>this._createMultipartStream(e,s),o=async c=>this.batchIngestCaller.callWithOptions({sizeBytes:r==null?void 0:r.sizeBytes},async()=>{const u=await c(),l={...this._mergedHeaders,"Content-Type":`multipart/form-data; boundary=${s}`};(r==null?void 0:r.apiKey)!==void 0&&(l["x-api-key"]=r.apiKey);let d=u;r!=null&&r.useGzip&&typeof u=="object"&&"pipeThrough"in u&&(d=u.pipeThrough(new CompressionStream("gzip")),l["Content-Encoding"]="gzip");const f=await this._fetch(`${(r==null?void 0:r.apiUrl)??this.apiUrl}/runs/multipart`,{method:"POST",headers:l,body:d,duplex:"half",signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await ce(f,"Failed to send multipart request",!0),f});try{let c,u=!1;$R()&&!this.multipartStreamingDisabled&&$S()!=="bun"?(u=!0,c=await o(i)):c=await o(a),(!this.multipartStreamingDisabled||u)&&c.status===422&&((r==null?void 0:r.apiUrl)??this.apiUrl)!==fw&&(console.warn(`Streaming multipart upload to ${(r==null?void 0:r.apiUrl)??this.apiUrl}/runs/multipart failed. This usually means the host does not support chunked uploads. Retrying with a buffered upload for operation "${n}".`),this.multipartStreamingDisabled=!0,c=await o(a))}catch(c){if(Kh(c))throw c;if(console.warn(`${c.message.trim()}
39
-
40
- Context: ${n}`),this.failedTracesDir){const u=await this._createNodeFetchBody(e,s).catch(()=>null);u&&await jr._writeTraceToFallbackDir(this.failedTracesDir,u,{"Content-Type":`multipart/form-data; boundary=${s}`},"runs/multipart",this.failedTracesMaxBytes)}}}async updateRun(e,n,r){$e(e),n.inputs&&(n.inputs=await this.processInputs(n.inputs)),n.outputs&&(n.outputs=await this.processOutputs(n.outputs)),n.extra!=null&&"metadata"in n.extra&&(n.extra={...n.extra,metadata:await this.processMetadata(n.extra.metadata)}),n.events&&(n.events=this._filterNewTokenEvents(n.events));const s={...n,id:e};if(!this._filterForSampling([s],!0).length)return;if(this.autoBatchTracing&&s.trace_id!==void 0&&s.dotted_order!==void 0){const o=this._cloneCurrentOTELContext();if(n.end_time!==void 0&&s.parent_run_id===void 0&&this.blockOnRootRunFinalization&&!this.manualFlushMode){await this.processRunOperation({action:"update",item:s,otelContext:o,apiKey:r==null?void 0:r.apiKey,apiUrl:r==null?void 0:r.apiUrl}).catch(console.error);return}else this.processRunOperation({action:"update",item:s,otelContext:o,apiKey:r==null?void 0:r.apiKey,apiUrl:r==null?void 0:r.apiUrl}).catch(console.error);return}const a={...this._mergedHeaders,"Content-Type":"application/json"};(r==null?void 0:r.apiKey)!==void 0&&(a["x-api-key"]=r.apiKey),(r==null?void 0:r.workspaceId)!==void 0&&(a["x-tenant-id"]=r.workspaceId);const i=an(n,`Serializing payload to update run with id: ${e}`);await this.caller.call(async()=>{const o=await this._fetch(`${(r==null?void 0:r.apiUrl)??this.apiUrl}/runs/${e}`,{method:"PATCH",headers:a,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await ce(o,"update run",!0),o})}async readRun(e,{loadChildRuns:n}={loadChildRuns:!1}){$e(e);let r=ro(await this._get(`/runs/${e}`));return n&&(r=await this._loadChildRuns(r)),r}async getRunUrl({runId:e,run:n,projectOpts:r}){if(n!==void 0){let s;n.session_id?s=n.session_id:r!=null&&r.projectName?s=(await this.readProject({projectName:r==null?void 0:r.projectName})).id:r!=null&&r.projectId?s=r==null?void 0:r.projectId:s=(await this.readProject({projectName:Tt("PROJECT")||"default"})).id;const a=await this._getTenantId();return`${this.getHostUrl()}/o/${a}/projects/p/${s}/r/${n.id}?poll=true`}else if(e!==void 0){const s=await this.readRun(e);if(!s.app_path)throw new Error(`Run ${e} has no app_path`);return`${this.getHostUrl()}${s.app_path}`}else throw new Error("Must provide either runId or run")}async _loadChildRuns(e){var a;const n=await gN(this.listRuns({isRoot:!1,projectId:e.session_id,traceId:e.trace_id})),r={},s={};n.sort((i,o)=>((i==null?void 0:i.dotted_order)??"").localeCompare((o==null?void 0:o.dotted_order)??""));for(const i of n){if(i.parent_run_id===null||i.parent_run_id===void 0)throw new Error(`Child run ${i.id} has no parent`);(a=i.dotted_order)!=null&&a.startsWith(e.dotted_order??"")&&i.id!==e.id&&(i.parent_run_id in r||(r[i.parent_run_id]=[]),r[i.parent_run_id].push(i),s[i.id]=i)}e.child_runs=r[e.id]||[];for(const i in r)i!==e.id&&(s[i].child_runs=r[i]);return e}async*listRuns(e){const{projectId:n,projectName:r,parentRunId:s,traceId:a,referenceExampleId:i,startTime:o,executionOrder:c,isRoot:u,runType:l,error:d,id:f,query:h,filter:m,traceFilter:_,treeFilter:y,limit:w,select:g,order:b}=e;let S=[];if(n&&(S=Array.isArray(n)?n:[n]),r){const A=Array.isArray(r)?r:[r],M=await Promise.all(A.map(O=>this.readProject({projectName:O}).then($=>$.id)));S.push(...M)}const I=["app_path","completion_cost","completion_tokens","dotted_order","end_time","error","events","extra","feedback_stats","first_token_time","id","inputs","name","outputs","parent_run_id","parent_run_ids","prompt_cost","prompt_tokens","reference_example_id","run_type","session_id","start_time","status","tags","total_cost","total_tokens","trace_id"],T={session:S.length?S:null,run_type:l,reference_example:i,query:h,filter:m,trace_filter:_,tree_filter:y,execution_order:c,parent_run:s,start_time:o?o.toISOString():null,error:d,id:f,limit:w,trace:a,select:g||I,is_root:u,order:b};T.select.includes("child_run_ids")&&dl("Deprecated: 'child_run_ids' in the listRuns select parameter is deprecated and will be removed in a future version.");let x=0;for await(const A of this._getCursorPaginatedList("/runs/query",T)){const M=A.map(ro);if(w){if(x>=w)break;if(M.length+x>w){yield*M.slice(0,w-x);break}x+=M.length,yield*M}else yield*M}}async*listGroupRuns(e){const{projectId:n,projectName:r,groupBy:s,filter:a,startTime:i,endTime:o,limit:c,offset:u}=e,d={session_id:n||(await this.readProject({projectName:r})).id,group_by:s,filter:a,start_time:i?i.toISOString():null,end_time:o?o.toISOString():null,limit:Number(c)||100};let f=Number(u)||0;const h="/runs/group",m=`${this.apiUrl}${h}`;for(;;){const _={...d,offset:f},y=Object.fromEntries(Object.entries(_).filter(([T,x])=>x!==void 0)),w=JSON.stringify(y),b=await(await this.caller.call(async()=>{const T=await this._fetch(m,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:w});return await ce(T,`Failed to fetch ${h}`),T})).json(),{groups:S,total:I}=b;if(S.length===0)break;for(const T of S)yield T;if(f+=S.length,f>=I)break}}async*readThread(e){const{threadId:n,projectId:r,projectName:s,isRoot:a=!0,limit:i,filter:o,order:c="asc"}=e;if(!r&&!s)throw new Error("threadId requires projectId or projectName");const u=`eq(thread_id, ${JSON.stringify(n)})`,l=o?`and(${u}, ${o})`:u;yield*this.listRuns({projectId:r??void 0,projectName:s??void 0,isRoot:a,limit:i,filter:l,order:c})}async listThreads(e){const{projectId:n,projectName:r,limit:s,offset:a=0,filter:i,startTime:o,isRoot:c=!0}=e;if(!n&&!r)throw new Error("Either projectId or projectName must be provided");if(n&&r)throw new Error("Provide exactly one of projectId or projectName");const u=n??(await this.readProject({projectName:r})).id,l=o??new Date(Date.now()-1*24*60*60*1e3),f={session:[u],is_root:c,limit:100,order:"desc",select:["id","name","status","start_time","end_time","thread_id","trace_id","run_type","error","tags","session_id","parent_run_id","total_tokens","total_cost","dotted_order","reference_example_id","feedback_stats","app_path","completion_cost","completion_tokens","prompt_cost","prompt_tokens","first_token_time"],start_time:l.toISOString()};i!=null&&(f.filter=i);const h=new Map;for await(const w of this._getCursorPaginatedList("/runs/query",f))for(const g of w){const b=ro(g),S=b.thread_id;if(S){const I=h.get(S)??[];I.push(b),h.set(S,I)}}const m=[];for(const[w,g]of h.entries()){g.sort((x,A)=>{const M=x,O=A,$=M.start_time??"",H=O.start_time??"";if($!==H)return $.localeCompare(H);const J=M.dotted_order??"",Y=O.dotted_order??"";return J.localeCompare(Y)});const S=[...g.map(x=>x.start_time).filter(Boolean)].sort(),I=S.length?S[0]:"",T=S.length?S[S.length-1]:"";m.push({thread_id:w,runs:g,count:g.length,filter:"",total_tokens:0,total_cost:null,min_start_time:I,max_start_time:T,latency_p50:0,latency_p99:0,feedback_stats:null,first_inputs:"",last_outputs:"",last_error:null})}m.sort((w,g)=>{const b=w.max_start_time??"";return(g.max_start_time??"").localeCompare(b)});const _=a>0?m.slice(a):m;return s!==void 0?_.slice(0,s):_}async getRunStats({id:e,trace:n,parentRun:r,runType:s,projectNames:a,projectIds:i,referenceExampleIds:o,startTime:c,endTime:u,error:l,query:d,filter:f,traceFilter:h,treeFilter:m,isRoot:_,dataSourceType:y}){let w=i||[];a&&(w=[...i||[],...await Promise.all(a.map(x=>this.readProject({projectName:x}).then(A=>A.id)))]);const b=Object.fromEntries(Object.entries({id:e,trace:n,parent_run:r,run_type:s,session:w,reference_example:o,start_time:c,end_time:u,error:l,query:d,filter:f,trace_filter:h,tree_filter:m,is_root:_,data_source_type:y}).filter(([x,A])=>A!==void 0)),S=JSON.stringify(b);return await(await this.caller.call(async()=>{const x=await this._fetch(`${this.apiUrl}/runs/stats`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:S});return await ce(x,"get run stats"),x})).json()}async shareRun(e,{shareId:n}={}){const r={run_id:e,share_token:n||no()};$e(e);const s=JSON.stringify(r),i=await(await this.caller.call(async()=>{const o=await this._fetch(`${this.apiUrl}/runs/${e}/share`,{method:"PUT",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await ce(o,"share run"),o})).json();if(i===null||!("share_token"in i))throw new Error("Invalid response from server");return`${this.getHostUrl()}/public/${i.share_token}/r`}async unshareRun(e){$e(e),await this.caller.call(async()=>{const n=await this._fetch(`${this.apiUrl}/runs/${e}/share`,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await ce(n,"unshare run",!0),n})}async readRunSharedLink(e){$e(e);const r=await(await this.caller.call(async()=>{const s=await this._fetch(`${this.apiUrl}/runs/${e}/share`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await ce(s,"read run shared link"),s})).json();if(!(r===null||!("share_token"in r)))return`${this.getHostUrl()}/public/${r.share_token}/r`}async listSharedRuns(e,{runIds:n}={}){const r=new URLSearchParams({share_token:e});if(n!==void 0)for(const i of n)r.append("id",i);return $e(e),(await(await this.caller.call(async()=>{const i=await this._fetch(`${this.apiUrl}/public/${e}/runs${r}`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await ce(i,"list shared runs"),i})).json()).map(ro)}async readDatasetSharedSchema(e,n){if(!e&&!n)throw new Error("Either datasetId or datasetName must be given");e||(e=(await this.readDataset({datasetName:n})).id),$e(e);const s=await(await this.caller.call(async()=>{const a=await this._fetch(`${this.apiUrl}/datasets/${e}/share`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await ce(a,"read dataset shared schema"),a})).json();return s.url=`${this.getHostUrl()}/public/${s.share_token}/d`,s}async shareDataset(e,n){if(!e&&!n)throw new Error("Either datasetId or datasetName must be given");e||(e=(await this.readDataset({datasetName:n})).id);const r={dataset_id:e};$e(e);const s=JSON.stringify(r),i=await(await this.caller.call(async()=>{const o=await this._fetch(`${this.apiUrl}/datasets/${e}/share`,{method:"PUT",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await ce(o,"share dataset"),o})).json();return i.url=`${this.getHostUrl()}/public/${i.share_token}/d`,i}async unshareDataset(e){$e(e),await this.caller.call(async()=>{const n=await this._fetch(`${this.apiUrl}/datasets/${e}/share`,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await ce(n,"unshare dataset",!0),n})}async readSharedDataset(e){return $e(e),await(await this.caller.call(async()=>{const s=await this._fetch(`${this.apiUrl}/public/${e}/datasets`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await ce(s,"read shared dataset"),s})).json()}async listSharedExamples(e,n){const r={};n!=null&&n.exampleIds&&(r.id=n.exampleIds);const s=new URLSearchParams;Object.entries(r).forEach(([o,c])=>{Array.isArray(c)?c.forEach(u=>s.append(o,u)):s.append(o,c)});const a=await this.caller.call(async()=>{const o=await this._fetch(`${this.apiUrl}/public/${e}/examples?${s.toString()}`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await ce(o,"list shared examples"),o}),i=await a.json();if(!a.ok)throw"detail"in i?new Error(`Failed to list shared examples.
41
- Status: ${a.status}
42
- Message: ${Array.isArray(i.detail)?i.detail.join(`
43
- `):"Unspecified error"}`):new Error(`Failed to list shared examples: ${a.status} ${a.statusText}`);return i.map(o=>({...o,_hostUrl:this.getHostUrl()}))}async createProject({projectName:e,description:n=null,metadata:r=null,upsert:s=!1,projectExtra:a=null,referenceDatasetId:i=null}){const o=s?"?upsert=true":"",c=`${this.apiUrl}/sessions${o}`,u=a||{};r&&(u.metadata=r);const l={name:e,extra:u,description:n};i!==null&&(l.reference_dataset_id=i);const d=JSON.stringify(l);return await(await this.caller.call(async()=>{const m=await this._fetch(c,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:d});return await ce(m,"create project"),m})).json()}async updateProject(e,{name:n=null,description:r=null,metadata:s=null,projectExtra:a=null,endTime:i=null}){const o=`${this.apiUrl}/sessions/${e}`;let c=a;s&&(c={...c||{},metadata:s});const u=JSON.stringify({name:n,extra:c,description:r,end_time:i?new Date(i).toISOString():null});return await(await this.caller.call(async()=>{const f=await this._fetch(o,{method:"PATCH",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:u});return await ce(f,"update project"),f})).json()}async hasProject({projectId:e,projectName:n}){let r="/sessions";const s=new URLSearchParams;if(e!==void 0&&n!==void 0)throw new Error("Must provide either projectName or projectId, not both");if(e!==void 0)$e(e),r+=`/${e}`;else if(n!==void 0)s.append("name",n);else throw new Error("Must provide projectName or projectId");const a=await this.caller.call(async()=>{const i=await this._fetch(`${this.apiUrl}${r}?${s}`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await ce(i,"has project"),i});try{const i=await a.json();return a.ok?Array.isArray(i)?i.length>0:!0:!1}catch{return!1}}async readProject({projectId:e,projectName:n,includeStats:r}){let s="/sessions";const a=new URLSearchParams;if(e!==void 0&&n!==void 0)throw new Error("Must provide either projectName or projectId, not both");if(e!==void 0)$e(e),s+=`/${e}`;else if(n!==void 0)a.append("name",n);else throw new Error("Must provide projectName or projectId");r!==void 0&&a.append("include_stats",r.toString());const i=await this._get(s,a);let o;if(Array.isArray(i)){if(i.length===0)throw new Error(`Project[id=${e}, name=${n}] not found`);o=i[0]}else o=i;return o}async getProjectUrl({projectId:e,projectName:n}){if(e===void 0&&n===void 0)throw new Error("Must provide either projectName or projectId");const r=await this.readProject({projectId:e,projectName:n}),s=await this._getTenantId();return`${this.getHostUrl()}/o/${s}/projects/p/${r.id}`}async getDatasetUrl({datasetId:e,datasetName:n}){if(e===void 0&&n===void 0)throw new Error("Must provide either datasetName or datasetId");const r=await this.readDataset({datasetId:e,datasetName:n}),s=await this._getTenantId();return`${this.getHostUrl()}/o/${s}/datasets/${r.id}`}async _getTenantId(){if(this._tenantId!==null)return this._tenantId;const e=new URLSearchParams({limit:"1"});for await(const n of this._getPaginated("/sessions",e))return this._tenantId=n[0].tenant_id,n[0].tenant_id;throw new Error("No projects found to resolve tenant.")}async*listProjects({projectIds:e,name:n,nameContains:r,referenceDatasetId:s,referenceDatasetName:a,includeStats:i,datasetVersion:o,referenceFree:c,metadata:u}={}){const l=new URLSearchParams;if(e!==void 0)for(const d of e)l.append("id",d);if(n!==void 0&&l.append("name",n),r!==void 0&&l.append("name_contains",r),s!==void 0)l.append("reference_dataset",s);else if(a!==void 0){const d=await this.readDataset({datasetName:a});l.append("reference_dataset",d.id)}i!==void 0&&l.append("include_stats",i.toString()),o!==void 0&&l.append("dataset_version",o),c!==void 0&&l.append("reference_free",c.toString()),u!==void 0&&l.append("metadata",JSON.stringify(u));for await(const d of this._getPaginated("/sessions",l))yield*d}async deleteProject({projectId:e,projectName:n}){let r;if(e===void 0&&n===void 0)throw new Error("Must provide projectName or projectId");if(e!==void 0&&n!==void 0)throw new Error("Must provide either projectName or projectId, not both");e===void 0?r=(await this.readProject({projectName:n})).id:r=e,$e(r),await this.caller.call(async()=>{const s=await this._fetch(`${this.apiUrl}/sessions/${r}`,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await ce(s,`delete session ${r} (${n})`,!0),s})}async uploadCsv({csvFile:e,fileName:n,inputKeys:r,outputKeys:s,description:a,dataType:i,name:o}){const c=`${this.apiUrl}/datasets/upload`,u=new FormData,l=new Blob([e],{type:"text/csv"});return u.append("file",l,n),r.forEach(h=>{u.append("input_keys",h)}),s.forEach(h=>{u.append("output_keys",h)}),a&&u.append("description",a),i&&u.append("data_type",i),o&&u.append("name",o),await(await this.caller.call(async()=>{const h=await this._fetch(c,{method:"POST",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:u});return await ce(h,"upload CSV"),h})).json()}async createDataset(e,{description:n,dataType:r,inputsSchema:s,outputsSchema:a,metadata:i}={}){const o={name:e,description:n,extra:{source:"sdk",...i?{metadata:i}:{}}};r&&(o.data_type=r),s&&(o.inputs_schema_definition=s),a&&(o.outputs_schema_definition=a);const c=JSON.stringify(o);return await(await this.caller.call(async()=>{const d=await this._fetch(`${this.apiUrl}/datasets`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await ce(d,"create dataset"),d})).json()}async readDataset({datasetId:e,datasetName:n}){let r="/datasets";const s=new URLSearchParams({limit:"1"});if(e&&n)throw new Error("Must provide either datasetName or datasetId, not both");if(e)$e(e),r+=`/${e}`;else if(n)s.append("name",n);else throw new Error("Must provide datasetName or datasetId");const a=await this._get(r,s);let i;if(Array.isArray(a)){if(a.length===0)throw new Error(`Dataset[id=${e}, name=${n}] not found`);i=a[0]}else i=a;return i}async hasDataset({datasetId:e,datasetName:n}){try{return await this.readDataset({datasetId:e,datasetName:n}),!0}catch(r){if(r instanceof Error&&r.message.toLocaleLowerCase().includes("not found"))return!1;throw r}}async diffDatasetVersions({datasetId:e,datasetName:n,fromVersion:r,toVersion:s}){let a=e;if(a===void 0&&n===void 0)throw new Error("Must provide either datasetName or datasetId");if(a!==void 0&&n!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");a===void 0&&(a=(await this.readDataset({datasetName:n})).id);const i=new URLSearchParams({from_version:typeof r=="string"?r:r.toISOString(),to_version:typeof s=="string"?s:s.toISOString()});return await this._get(`/datasets/${a}/versions/diff`,i)}async readDatasetOpenaiFinetuning({datasetId:e,datasetName:n}){const r="/datasets";if(e===void 0)if(n!==void 0)e=(await this.readDataset({datasetName:n})).id;else throw new Error("Must provide either datasetName or datasetId");return(await(await this._getResponse(`${r}/${e}/openai_ft`)).text()).trim().split(`
44
- `).map(o=>JSON.parse(o))}async*listDatasets({limit:e=100,offset:n=0,datasetIds:r,datasetName:s,datasetNameContains:a,metadata:i}={}){const o="/datasets",c=new URLSearchParams({limit:e.toString(),offset:n.toString()});if(r!==void 0)for(const u of r)c.append("id",u);s!==void 0&&c.append("name",s),a!==void 0&&c.append("name_contains",a),i!==void 0&&c.append("metadata",JSON.stringify(i));for await(const u of this._getPaginated(o,c))yield*u}async updateDataset(e){const{datasetId:n,datasetName:r,...s}=e;if(!n&&!r)throw new Error("Must provide either datasetName or datasetId");const a=n??(await this.readDataset({datasetName:r})).id;$e(a);const i=JSON.stringify(s);return await(await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/datasets/${a}`,{method:"PATCH",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await ce(c,"update dataset"),c})).json()}async updateDatasetTag(e){const{datasetId:n,datasetName:r,asOf:s,tag:a}=e;if(!n&&!r)throw new Error("Must provide either datasetName or datasetId");const i=n??(await this.readDataset({datasetName:r})).id;$e(i);const o=JSON.stringify({as_of:typeof s=="string"?s:s.toISOString(),tag:a});await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/datasets/${i}/tags`,{method:"PUT",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await ce(c,"update dataset tags",!0),c})}async deleteDataset({datasetId:e,datasetName:n}){let r="/datasets",s=e;if(e!==void 0&&n!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");if(n!==void 0&&(s=(await this.readDataset({datasetName:n})).id),s!==void 0)$e(s),r+=`/${s}`;else throw new Error("Must provide datasetName or datasetId");await this.caller.call(async()=>{const a=await this._fetch(this.apiUrl+r,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await ce(a,`delete ${r}`,!0),a})}async createExample(e,n,r){var l;if(pw(e)&&(n!==void 0||r!==void 0))throw new Error("Cannot provide outputs or options when using ExampleCreate object");let s=n?r==null?void 0:r.datasetId:e.dataset_id;const a=n?r==null?void 0:r.datasetName:e.dataset_name;if(s===void 0&&a===void 0)throw new Error("Must provide either datasetName or datasetId");if(s!==void 0&&a!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");s===void 0&&(s=(await this.readDataset({datasetName:a})).id);const i=(n?r==null?void 0:r.createdAt:e.created_at)||new Date;let o;pw(e)?o=e:o={inputs:e,outputs:n,created_at:i==null?void 0:i.toISOString(),id:r==null?void 0:r.exampleId,metadata:r==null?void 0:r.metadata,split:r==null?void 0:r.split,source_run_id:r==null?void 0:r.sourceRunId,use_source_run_io:r==null?void 0:r.useSourceRunIO,use_source_run_attachments:r==null?void 0:r.useSourceRunAttachments,attachments:r==null?void 0:r.attachments};const c=await this._uploadExamplesMultipart(s,[o]);return await this.readExample(((l=c.example_ids)==null?void 0:l[0])??no())}async createExamples(e){if(Array.isArray(e)){if(e.length===0)return[];const g=e;let b=g[0].dataset_id;const S=g[0].dataset_name;if(b===void 0&&S===void 0)throw new Error("Must provide either datasetName or datasetId");if(b!==void 0&&S!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");b===void 0&&(b=(await this.readDataset({datasetName:S})).id);const I=await this._uploadExamplesMultipart(b,g);return await Promise.all(I.example_ids.map(x=>this.readExample(x)))}const{inputs:n,outputs:r,metadata:s,splits:a,sourceRunIds:i,useSourceRunIOs:o,useSourceRunAttachments:c,attachments:u,exampleIds:l,datasetId:d,datasetName:f}=e;if(n===void 0)throw new Error("Must provide inputs when using legacy parameters");let h=d;const m=f;if(h===void 0&&m===void 0)throw new Error("Must provide either datasetName or datasetId");if(h!==void 0&&m!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");h===void 0&&(h=(await this.readDataset({datasetName:m})).id);const _=n.map((g,b)=>({dataset_id:h,inputs:g,outputs:r==null?void 0:r[b],metadata:s==null?void 0:s[b],split:a==null?void 0:a[b],id:l==null?void 0:l[b],attachments:u==null?void 0:u[b],source_run_id:i==null?void 0:i[b],use_source_run_io:o==null?void 0:o[b],use_source_run_attachments:c==null?void 0:c[b]})),y=await this._uploadExamplesMultipart(h,_);return await Promise.all(y.example_ids.map(g=>this.readExample(g)))}async createLLMExample(e,n,r){return this.createExample({input:e},{output:n},r)}async createChatExample(e,n,r){const s=e.map(i=>ow(i)?cw(i):i),a=ow(n)?cw(n):n;return this.createExample({input:s},{output:a},r)}async readExample(e){$e(e);const n=`/examples/${e}`,r=await this._get(n),{attachment_urls:s,...a}=r,i=a;return s&&(i.attachments=Object.entries(s).reduce((o,[c,u])=>(o[c.slice(11)]={presigned_url:u.presigned_url,mime_type:u.mime_type},o),{})),i}async*listExamples({datasetId:e,datasetName:n,exampleIds:r,asOf:s,splits:a,inlineS3Urls:i,metadata:o,limit:c,offset:u,filter:l,includeAttachments:d}={}){let f;if(e!==void 0&&n!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");if(e!==void 0)f=e;else if(n!==void 0)f=(await this.readDataset({datasetName:n})).id;else throw new Error("Must provide a datasetName or datasetId");const h=new URLSearchParams({dataset:f}),m=s?typeof s=="string"?s:s==null?void 0:s.toISOString():void 0;m&&h.append("as_of",m);const _=i??!0;if(h.append("inline_s3_urls",_.toString()),r!==void 0)for(const w of r)h.append("id",w);if(a!==void 0)for(const w of a)h.append("splits",w);if(o!==void 0){const w=JSON.stringify(o);h.append("metadata",w)}c!==void 0&&h.append("limit",c.toString()),u!==void 0&&h.append("offset",u.toString()),l!==void 0&&h.append("filter",l),d===!0&&["attachment_urls","outputs","metadata"].forEach(w=>h.append("select",w));let y=0;for await(const w of this._getPaginated("/examples",h)){for(const g of w){const{attachment_urls:b,...S}=g,I=S;b&&(I.attachments=Object.entries(b).reduce((T,[x,A])=>(T[x.slice(11)]={presigned_url:A.presigned_url,mime_type:A.mime_type||void 0},T),{})),yield I,y++}if(c!==void 0&&y>=c)break}}async deleteExample(e){$e(e);const n=`/examples/${e}`;await this.caller.call(async()=>{const r=await this._fetch(this.apiUrl+n,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await ce(r,`delete ${n}`,!0),r})}async deleteExamples(e,n){if(e.forEach(r=>$e(r)),n!=null&&n.hardDelete){const r=this._getPlatformEndpointPath("datasets/examples/delete");await this.caller.call(async()=>{const s=await this._fetch(`${this.apiUrl}${r}`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},body:JSON.stringify({example_ids:e,hard_delete:!0}),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await ce(s,"hard delete examples",!0),s})}else{const r=new URLSearchParams;e.forEach(s=>r.append("example_ids",s)),await this.caller.call(async()=>{const s=await this._fetch(`${this.apiUrl}/examples?${r.toString()}`,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await ce(s,"delete examples",!0),s})}}async updateExample(e,n){let r;n?r=e:r=e.id,$e(r);let s;n?s={id:r,...n}:s=e;let a;return s.dataset_id!==void 0?a=s.dataset_id:a=(await this.readExample(r)).dataset_id,this._updateExamplesMultipart(a,[s])}async updateExamples(e){let n;return e[0].dataset_id===void 0?n=(await this.readExample(e[0].id)).dataset_id:n=e[0].dataset_id,this._updateExamplesMultipart(n,e)}async readDatasetVersion({datasetId:e,datasetName:n,asOf:r,tag:s}){let a;if(e?a=e:a=(await this.readDataset({datasetName:n})).id,$e(a),r&&s||!r&&!s)throw new Error("Exactly one of asOf and tag must be specified.");const i=new URLSearchParams;return r!==void 0&&i.append("as_of",typeof r=="string"?r:r.toISOString()),s!==void 0&&i.append("tag",s),await(await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/datasets/${a}/version?${i.toString()}`,{method:"GET",headers:{...this._mergedHeaders},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await ce(c,"read dataset version"),c})).json()}async listDatasetSplits({datasetId:e,datasetName:n,asOf:r}){let s;if(e===void 0&&n===void 0)throw new Error("Must provide dataset name or ID");if(e!==void 0&&n!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");e===void 0?s=(await this.readDataset({datasetName:n})).id:s=e,$e(s);const a=new URLSearchParams,i=r?typeof r=="string"?r:r==null?void 0:r.toISOString():void 0;return i&&a.append("as_of",i),await this._get(`/datasets/${s}/splits`,a)}async updateDatasetSplits({datasetId:e,datasetName:n,splitName:r,exampleIds:s,remove:a=!1}){let i;if(e===void 0&&n===void 0)throw new Error("Must provide dataset name or ID");if(e!==void 0&&n!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");e===void 0?i=(await this.readDataset({datasetName:n})).id:i=e,$e(i);const o={split_name:r,examples:s.map(u=>($e(u),u)),remove:a},c=JSON.stringify(o);await this.caller.call(async()=>{const u=await this._fetch(`${this.apiUrl}/datasets/${i}/splits`,{method:"PUT",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await ce(u,"update dataset splits",!0),u})}async createFeedback(e,n,{score:r,value:s,correction:a,comment:i,sourceInfo:o,feedbackSourceType:c="api",sourceRunId:u,feedbackId:l,feedbackConfig:d,projectId:f,comparativeExperimentId:h,sessionId:m,startTime:_}){var S;if(!e&&!f)throw new Error("One of runId or projectId must be provided");if(e&&f)throw new Error("Only one of runId or projectId can be provided");const y={type:c??"api",metadata:o??{}};u!==void 0&&(y==null?void 0:y.metadata)!==void 0&&!y.metadata.__run&&(y.metadata.__run={run_id:u}),(y==null?void 0:y.metadata)!==void 0&&((S=y.metadata.__run)==null?void 0:S.run_id)!==void 0&&$e(y.metadata.__run.run_id);const w={id:l??bS(),run_id:e,key:n,score:hw(r),value:s,correction:a,comment:i,feedback_source:y,comparative_experiment_id:h,feedbackConfig:d,session_id:m??f,start_time:_},g=JSON.stringify(w),b=`${this.apiUrl}/feedback`;return await this.caller.call(async()=>{const I=await this._fetch(b,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:g});return await ce(I,"create feedback",!0),I}),w}async updateFeedback(e,{score:n,value:r,correction:s,comment:a}){const i={};n!=null&&(i.score=hw(n)),r!=null&&(i.value=r),s!=null&&(i.correction=s),a!=null&&(i.comment=a),$e(e);const o=JSON.stringify(i);await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/feedback/${e}`,{method:"PATCH",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await ce(c,"update feedback",!0),c})}async readFeedback(e){$e(e);const n=`/feedback/${e}`;return await this._get(n)}async deleteFeedback(e){$e(e);const n=`/feedback/${e}`;await this.caller.call(async()=>{const r=await this._fetch(this.apiUrl+n,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await ce(r,`delete ${n}`,!0),r})}async*listFeedback({runIds:e,feedbackKeys:n,feedbackSourceTypes:r}={}){const s=new URLSearchParams;if(e)for(const a of e)$e(a),s.append("run",a);if(n)for(const a of n)s.append("key",a);if(r)for(const a of r)s.append("source",a);for await(const a of this._getPaginated("/feedback",s))yield*a}async createPresignedFeedbackToken(e,n,{expiration:r,feedbackConfig:s}={}){const a={run_id:e,feedback_key:n,feedback_config:s};r?typeof r=="string"?a.expires_at=r:(r!=null&&r.hours||r!=null&&r.minutes||r!=null&&r.days)&&(a.expires_in=r):a.expires_in={hours:3};const i=JSON.stringify(a);return await(await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/feedback/tokens`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await ce(c,"create presigned feedback token"),c})).json()}async createComparativeExperiment({name:e,experimentIds:n,referenceDatasetId:r,createdAt:s,description:a,metadata:i,id:o}){var d;if(n.length===0)throw new Error("At least one experiment is required");if(r||(r=(await this.readProject({projectId:n[0]})).reference_dataset_id),!r==null)throw new Error("A reference dataset is required");const c={id:o,name:e,experiment_ids:n,reference_dataset_id:r,description:a,created_at:(d=s??new Date)==null?void 0:d.toISOString(),extra:{}};i&&(c.extra.metadata=i);const u=JSON.stringify(c);return(await this.caller.call(async()=>{const f=await this._fetch(`${this.apiUrl}/datasets/comparative`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:u});return await ce(f,"create comparative experiment"),f})).json()}async*listPresignedFeedbackTokens(e){$e(e);const n=new URLSearchParams({run_id:e});for await(const r of this._getPaginated("/feedback/tokens",n))yield*r}_selectEvalResults(e){let n;return"results"in e?n=e.results:Array.isArray(e)?n=e:n=[e],n}async _logEvaluationFeedback(e,n,r){const s=this._selectEvalResults(e),a=[];for(const i of s){let o=r||{};i.evaluatorInfo&&(o={...i.evaluatorInfo,...o});let c=null;i.targetRunId?c=i.targetRunId:n&&(c=n.id),a.push(await this.createFeedback(c,i.key,{score:i.score,value:i.value,comment:i.comment,correction:i.correction,sourceInfo:o,sourceRunId:i.sourceRunId,feedbackConfig:i.feedbackConfig,feedbackSourceType:"model",sessionId:n==null?void 0:n.session_id,startTime:n==null?void 0:n.start_time}))}return[s,a]}async logEvaluationFeedback(e,n,r){const[s]=await this._logEvaluationFeedback(e,n,r);return s}async createFeedbackConfig(e){const{feedbackKey:n,feedbackConfig:r,isLowerScoreBetter:s=!1}=e,a={feedback_key:n,feedback_config:r,is_lower_score_better:s};return(await this.caller.call(async()=>{const o=await this._fetch(`${this.apiUrl}/feedback-configs`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:JSON.stringify(a)});return await ce(o,"create feedback config"),o})).json()}async*listFeedbackConfigs(e={}){const{feedbackKeys:n,nameContains:r,limit:s}=e,a=new URLSearchParams;n&&n.forEach(o=>{a.append("key",o)}),r&&a.append("name_contains",r),a.append("limit",(s!==void 0?Math.min(s,100):100).toString());let i=0;for await(const o of this._getPaginated("/feedback-configs",a))if(yield*o,i+=o.length,s!==void 0&&i>=s)break}async updateFeedbackConfig(e,n={}){const{feedbackConfig:r,isLowerScoreBetter:s}=n,a={feedback_key:e};return r!==void 0&&(a.feedback_config=r),s!==void 0&&(a.is_lower_score_better=s),(await this.caller.call(async()=>{const o=await this._fetch(`${this.apiUrl}/feedback-configs`,{method:"PATCH",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:JSON.stringify(a)});return await ce(o,"update feedback config"),o})).json()}async deleteFeedbackConfig(e){const n=new URLSearchParams({feedback_key:e});await this.caller.call(async()=>{const r=await this._fetch(`${this.apiUrl}/feedback-configs?${n}`,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await ce(r,"delete feedback config",!0),r})}async*listAnnotationQueues(e={}){const{queueIds:n,name:r,nameContains:s,limit:a}=e,i=new URLSearchParams;n&&n.forEach((c,u)=>{$e(c,`queueIds[${u}]`),i.append("ids",c)}),r&&i.append("name",r),s&&i.append("name_contains",s),i.append("limit",(a!==void 0?Math.min(a,100):100).toString());let o=0;for await(const c of this._getPaginated("/annotation-queues",i))if(yield*c,o++,a!==void 0&&o>=a)break}async createAnnotationQueue(e){const{name:n,description:r,queueId:s,rubricInstructions:a,rubricItems:i}=e,o={name:n,description:r,id:s||no(),rubric_instructions:a,rubric_items:i},c=JSON.stringify(Object.fromEntries(Object.entries(o).filter(([l,d])=>d!==void 0)));return(await this.caller.call(async()=>{const l=await this._fetch(`${this.apiUrl}/annotation-queues`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await ce(l,"create annotation queue"),l})).json()}async readAnnotationQueue(e){return(await this.caller.call(async()=>{const r=await this._fetch(`${this.apiUrl}/annotation-queues/${$e(e,"queueId")}`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await ce(r,"read annotation queue"),r})).json()}async updateAnnotationQueue(e,n){const{name:r,description:s,rubricInstructions:a,rubricItems:i}=n,o={};r!==void 0&&(o.name=r),s!==void 0&&(o.description=s),a!==void 0&&(o.rubric_instructions=a),i!==void 0&&(o.rubric_items=i);const c=JSON.stringify(o);await this.caller.call(async()=>{const u=await this._fetch(`${this.apiUrl}/annotation-queues/${$e(e,"queueId")}`,{method:"PATCH",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await ce(u,"update annotation queue",!0),u})}async deleteAnnotationQueue(e){await this.caller.call(async()=>{const n=await this._fetch(`${this.apiUrl}/annotation-queues/${$e(e,"queueId")}`,{method:"DELETE",headers:{...this._mergedHeaders,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await ce(n,"delete annotation queue",!0),n})}async addRunsToAnnotationQueue(e,n){const r=JSON.stringify(n.map((s,a)=>$e(s,`runIds[${a}]`).toString()));await this.caller.call(async()=>{const s=await this._fetch(`${this.apiUrl}/annotation-queues/${$e(e,"queueId")}/runs`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:r});return await ce(s,"add runs to annotation queue",!0),s})}async getRunFromAnnotationQueue(e,n){const r=`/annotation-queues/${$e(e,"queueId")}/run`,a=await(await this.caller.call(async()=>{const i=await this._fetch(`${this.apiUrl}${r}/${n}`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await ce(i,"get run from annotation queue"),i})).json();return ro(a)}async deleteRunFromAnnotationQueue(e,n){await this.caller.call(async()=>{const r=await this._fetch(`${this.apiUrl}/annotation-queues/${$e(e,"queueId")}/runs/${$e(n,"queueRunId")}`,{method:"DELETE",headers:{...this._mergedHeaders,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await ce(r,"delete run from annotation queue",!0),r})}async getSizeFromAnnotationQueue(e){return(await this.caller.call(async()=>{const r=await this._fetch(`${this.apiUrl}/annotation-queues/${$e(e,"queueId")}/size`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await ce(r,"get size from annotation queue"),r})).json()}async _currentTenantIsOwner(e){const n=await this._getSettings();return e=="-"||n.tenant_handle===e}async _ownerConflictError(e,n){const r=await this._getSettings();return new Error(`Cannot ${e} for another tenant.
45
-
46
- Current tenant: ${r.tenant_handle}
47
-
48
- Requested tenant: ${n}`)}async _getLatestCommitHash(e){const r=await(await this.caller.call(async()=>{const s=await this._fetch(`${this.apiUrl}/commits/${e}/?limit=1&offset=0`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await ce(s,"get latest commit hash"),s})).json();if(r.commits.length!==0)return r.commits[0].commit_hash}async _likeOrUnlikePrompt(e,n){const[r,s,a]=En(e),i=JSON.stringify({like:n});return(await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/likes/${r}/${s}`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await ce(c,`${n?"like":"unlike"} prompt`),c})).json()}async _getPromptUrl(e){const[n,r,s]=En(e);if(await this._currentTenantIsOwner(n)){const a=await this._getSettings();return s!=="latest"?`${this.getHostUrl()}/prompts/${r}/${s.substring(0,8)}?organizationId=${a.id}`:`${this.getHostUrl()}/prompts/${r}?organizationId=${a.id}`}else return s!=="latest"?`${this.getHostUrl()}/hub/${n}/${r}/${s.substring(0,8)}`:`${this.getHostUrl()}/hub/${n}/${r}`}async promptExists(e){return!!await this.getPrompt(e)}async likePrompt(e){return this._likeOrUnlikePrompt(e,!0)}async unlikePrompt(e){return this._likeOrUnlikePrompt(e,!1)}async*listCommits(e){const[n,r,s]=En(e);for await(const a of this._getPaginated(`/commits/${n}/${r}/`,new URLSearchParams,i=>i.commits))yield*a}async*listPrompts(e){const n=new URLSearchParams;n.append("sort_field",(e==null?void 0:e.sortField)??"updated_at"),n.append("sort_direction","desc"),n.append("is_archived",(!!(e!=null&&e.isArchived)).toString()),(e==null?void 0:e.isPublic)!==void 0&&n.append("is_public",e.isPublic.toString()),e!=null&&e.query&&n.append("query",e.query);for await(const r of this._getPaginated("/repos",n,s=>s.repos))yield*r}async getPrompt(e){const[n,r,s]=En(e),a=await this.caller.call(async()=>{const o=await this._fetch(`${this.apiUrl}/repos/${n}/${r}`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return(o==null?void 0:o.status)===404?null:(await ce(o,"get prompt"),o)}),i=await(a==null?void 0:a.json());return i!=null&&i.repo?i.repo:null}async createPrompt(e,n){const r=await this._getSettings();if(n!=null&&n.isPublic&&!r.tenant_handle)throw new Error(`Cannot create a public prompt without first
49
-
50
- creating a LangChain Hub handle.
51
- You can add a handle by creating a public prompt at:
52
-
53
- https://smith.langchain.com/prompts`);const[s,a,i]=En(e);if(!await this._currentTenantIsOwner(s))throw await this._ownerConflictError("create a prompt",s);const o={repo_handle:a,...(n==null?void 0:n.description)&&{description:n.description},...(n==null?void 0:n.readme)&&{readme:n.readme},...(n==null?void 0:n.tags)&&{tags:n.tags},is_public:!!(n!=null&&n.isPublic)},c=JSON.stringify(o),u=await this.caller.call(async()=>{const d=await this._fetch(`${this.apiUrl}/repos/`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await ce(d,"create prompt"),d}),{repo:l}=await u.json();return l}async createCommit(e,n,r){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");const[s,a,i]=En(e),o=(r==null?void 0:r.parentCommitHash)==="latest"||!(r!=null&&r.parentCommitHash)?await this._getLatestCommitHash(`${s}/${a}`):r==null?void 0:r.parentCommitHash,c={manifest:JSON.parse(JSON.stringify(n)),parent_commit:o,...(r==null?void 0:r.description)!==void 0&&{description:r.description}},u=JSON.stringify(c),d=await(await this.caller.call(async()=>{const f=await this._fetch(`${this.apiUrl}/commits/${s}/${a}`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:u});return await ce(f,"create commit"),f})).json();return this._getPromptUrl(`${s}/${a}${d.commit_hash?`:${d.commit_hash}`:""}`)}async updateExamplesMultipart(e,n=[]){return this._updateExamplesMultipart(e,n)}async _updateExamplesMultipart(e,n=[]){var i;if(!await this._getDatasetExamplesMultiPartSupport())throw new Error("Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version.");const r=new FormData;for(const o of n){const c=o.id,u={...o.metadata&&{metadata:o.metadata},...o.split&&{split:o.split}},l=an(u,`Serializing body for example with id: ${c}`),d=new Blob([l],{type:"application/json"});if(r.append(c,d),o.inputs){const f=an(o.inputs,`Serializing inputs for example with id: ${c}`),h=new Blob([f],{type:"application/json"});r.append(`${c}.inputs`,h)}if(o.outputs){const f=an(o.outputs,`Serializing outputs whle updating example with id: ${c}`),h=new Blob([f],{type:"application/json"});r.append(`${c}.outputs`,h)}if(o.attachments)for(const[f,h]of Object.entries(o.attachments)){let m,_;Array.isArray(h)?[m,_]=h:(m=h.mimeType,_=h.data);const y=new Blob([_],{type:`${m}; length=${_.byteLength}`});r.append(`${c}.attachment.${f}`,y)}if(o.attachments_operations){const f=an(o.attachments_operations,`Serializing attachments while updating example with id: ${c}`),h=new Blob([f],{type:"application/json"});r.append(`${c}.attachments_operations`,h)}}const s=e??((i=n[0])==null?void 0:i.dataset_id);return(await this.caller.call(async()=>{const o=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${s}/examples`)}`,{method:"PATCH",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:r});return await ce(o,"update examples"),o})).json()}async uploadExamplesMultipart(e,n=[]){return this._uploadExamplesMultipart(e,n)}async _uploadExamplesMultipart(e,n=[]){if(!await this._getDatasetExamplesMultiPartSupport())throw new Error("Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version.");const r=new FormData;for(const a of n){const i=(a.id??no()).toString(),o={created_at:a.created_at,...a.metadata&&{metadata:a.metadata},...a.split&&{split:a.split},...a.source_run_id&&{source_run_id:a.source_run_id},...a.use_source_run_io&&{use_source_run_io:a.use_source_run_io},...a.use_source_run_attachments&&{use_source_run_attachments:a.use_source_run_attachments}},c=an(o,`Serializing body for uploaded example with id: ${i}`),u=new Blob([c],{type:"application/json"});if(r.append(i,u),a.inputs){const l=an(a.inputs,`Serializing inputs for uploaded example with id: ${i}`),d=new Blob([l],{type:"application/json"});r.append(`${i}.inputs`,d)}if(a.outputs){const l=an(a.outputs,`Serializing outputs for uploaded example with id: ${i}`),d=new Blob([l],{type:"application/json"});r.append(`${i}.outputs`,d)}if(a.attachments)for(const[l,d]of Object.entries(a.attachments)){let f,h;Array.isArray(d)?[f,h]=d:(f=d.mimeType,h=d.data);const m=new Blob([h],{type:`${f}; length=${h.byteLength}`});r.append(`${i}.attachment.${l}`,m)}}return(await this.caller.call(async()=>{const a=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${e}/examples`)}`,{method:"POST",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:r});return await ce(a,"upload examples"),a})).json()}async updatePrompt(e,n){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");const[r,s]=En(e);if(!await this._currentTenantIsOwner(r))throw await this._ownerConflictError("update a prompt",r);const a={};if((n==null?void 0:n.description)!==void 0&&(a.description=n.description),(n==null?void 0:n.readme)!==void 0&&(a.readme=n.readme),(n==null?void 0:n.tags)!==void 0&&(a.tags=n.tags),(n==null?void 0:n.isPublic)!==void 0&&(a.is_public=n.isPublic),(n==null?void 0:n.isArchived)!==void 0&&(a.is_archived=n.isArchived),Object.keys(a).length===0)throw new Error("No valid update options provided");const i=JSON.stringify(a);return(await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/repos/${r}/${s}`,{method:"PATCH",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await ce(c,"update prompt"),c})).json()}async deletePrompt(e){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");const[n,r,s]=En(e);if(!await this._currentTenantIsOwner(n))throw await this._ownerConflictError("delete a prompt",n);return(await this.caller.call(async()=>{const i=await this._fetch(`${this.apiUrl}/repos/${n}/${r}`,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await ce(i,"delete prompt"),i})).json()}_getPromptCacheKey(e,n){return`${e}${n?":with_model":""}`}async _fetchPromptFromApi(e,n){const[r,s,a]=En(e),o=await(await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/commits/${r}/${s}/${a}${n!=null&&n.includeModel?"?include_model=true":""}`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await ce(c,"pull prompt commit"),c})).json();return{owner:r,repo:s,commit_hash:o.commit_hash,manifest:o.manifest,examples:o.examples,hub_model_config:o.model_config,hub_model_provider:o.model_provider}}async pullPromptCommit(e,n){const r=this._fetchPromptFromApi.bind(this,e,n);if(!(n!=null&&n.skipCache)&&this._promptCache){const s=this._getPromptCacheKey(e,n==null?void 0:n.includeModel),a=this._promptCache.get(s,r);if(a)return a;const i=await r();return this._promptCache.set(s,i,r),i}return this._fetchPromptFromApi(e,n)}async _pullPrompt(e,n){const r=await this.pullPromptCommit(e,{includeModel:n==null?void 0:n.includeModel,skipCache:n==null?void 0:n.skipCache});return JSON.stringify(r.manifest)}async pushPrompt(e,n){return await this.promptExists(e)?n&&Object.keys(n).some(s=>s!=="object")&&await this.updatePrompt(e,{description:n==null?void 0:n.description,readme:n==null?void 0:n.readme,tags:n==null?void 0:n.tags,isPublic:n==null?void 0:n.isPublic}):await this.createPrompt(e,{description:n==null?void 0:n.description,readme:n==null?void 0:n.readme,tags:n==null?void 0:n.tags,isPublic:n==null?void 0:n.isPublic}),n!=null&&n.object?await this.createCommit(e,n==null?void 0:n.object,{parentCommitHash:n==null?void 0:n.parentCommitHash,description:n==null?void 0:n.commitDescription}):await this._getPromptUrl(e)}async agentExists(e){const[n,r]=En(e);return this._repoExists(n,r)}async skillExists(e){const[n,r]=En(e);return this._repoExists(n,r)}async pullAgent(e,n){return await this._pullDirectory(e,"agent",n==null?void 0:n.version)}async pullSkill(e,n){return await this._pullDirectory(e,"skill",n==null?void 0:n.version)}async pushAgent(e,n){return this._pushDirectory(e,"agent",n)}async pushSkill(e,n){return this._pushDirectory(e,"skill",n)}async deleteAgent(e){return this._deleteDirectory(e)}async deleteSkill(e){return this._deleteDirectory(e)}async*listAgents(e){yield*this._listReposByType("agent",e)}async*listSkills(e){yield*this._listReposByType("skill",e)}async*_listReposByType(e,n){const r=new URLSearchParams;r.append("repo_type",e),r.append("is_archived",(!!(n!=null&&n.isArchived)).toString()),(n==null?void 0:n.isPublic)!==void 0&&r.append("is_public",n.isPublic.toString()),n!=null&&n.query&&r.append("query",n.query);for await(const s of this._getPaginated("/repos",r,a=>a.repos))yield*s}async _pullDirectory(e,n,r){const[s,a,i]=En(e),o=r??(i!=="latest"?i:void 0),c=new URL(`${this.apiUrl}/v1/platform/hub/repos/${s}/${a}/directories`);return c.searchParams.set("repo_type",n),o&&c.searchParams.set("commit",o),await(await this.caller.call(async()=>{const l=await this._fetch(c.toString(),{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await ce(l,"pull directory"),l})).json()}async _pushDirectory(e,n,r){if(r.parentCommit!==void 0&&(r.parentCommit.length<8||r.parentCommit.length>64))throw new Error("parent_commit must be 8-64 characters");const[s,a]=En(e);if(!await this._currentTenantIsOwner(s))throw await this._ownerConflictError(`push ${n}`,s);if(await this._repoExists(s,a))(r.description!==void 0||r.readme!==void 0||r.tags!==void 0||r.isPublic!==void 0)&&await this._updateRepoMetadata(s,a,r);else{const l=/^[a-z][a-z0-9-_]*$/;if(!l.test(a))throw new Error(`Invalid repo_handle ${JSON.stringify(a)}: must match ${l}`);await this._createRepo(a,n,r)}const i={files:r.files};r.parentCommit&&(i.parent_commit=r.parentCommit);const u=(await(await this.caller.call(async()=>{const l=await this._fetch(`${this.apiUrl}/v1/platform/hub/repos/${s}/${a}/directories/commits`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:JSON.stringify(i)});return await ce(l,`push ${n}`),l})).json()).commit.commit_hash;return`${this.getHostUrl()}/hub/${s}/${a}:${u.slice(0,8)}`}async _deleteDirectory(e){const[n,r]=En(e);if(!await this._currentTenantIsOwner(n))throw await this._ownerConflictError("delete",n);await this.caller.call(async()=>{const s=await this._fetch(`${this.apiUrl}/v1/platform/hub/repos/${n}/${r}/directories`,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await ce(s,"delete directory"),s})}async _repoExists(e,n){try{return await this.caller.call(async()=>{const r=await this._fetch(`${this.apiUrl}/repos/${e}/${n}`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await ce(r,"check repo exists"),r}),!0}catch(r){if(Kh(r))return!1;throw r}}async _createRepo(e,n,r){const s={repo_handle:e,repo_type:n,is_public:!!r.isPublic};r.description!==void 0&&(s.description=r.description),r.readme!==void 0&&(s.readme=r.readme),r.tags!==void 0&&(s.tags=r.tags);try{await this.caller.call(async()=>{const a=await this._fetch(`${this.apiUrl}/repos/`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:JSON.stringify(s)});return await ce(a,`create ${n}`),a})}catch(a){if(eN(a))return;throw a}}async _updateRepoMetadata(e,n,r){const s={};r.description!==void 0&&(s.description=r.description),r.readme!==void 0&&(s.readme=r.readme),r.tags!==void 0&&(s.tags=r.tags),r.isPublic!==void 0&&(s.is_public=r.isPublic),Object.keys(s).length!==0&&await this.caller.call(async()=>{const a=await this._fetch(`${this.apiUrl}/repos/${e}/${n}`,{method:"PATCH",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:JSON.stringify(s)});return await ce(a,"update repo metadata"),a})}async clonePublicDataset(e,n={}){const{sourceApiUrl:r=this.apiUrl,datasetName:s}=n,[a,i]=this.parseTokenOrUrl(e,r),o=new jr({apiUrl:a,apiKey:"placeholder"}),c=await o.readSharedDataset(i),u=s||c.name;try{if(await this.hasDataset({datasetId:u})){console.log(`Dataset ${u} already exists in your tenant. Skipping.`);return}}catch{}const l=await o.listSharedExamples(i),d=await this.createDataset(u,{description:c.description,dataType:c.data_type||"kv",inputsSchema:c.inputs_schema_definition??void 0,outputsSchema:c.outputs_schema_definition??void 0});try{await this.createExamples({inputs:l.map(f=>f.inputs),outputs:l.flatMap(f=>f.outputs?[f.outputs]:[]),datasetId:d.id})}catch(f){throw console.error(`An error occurred while creating dataset ${u}. You should delete it manually.`),f}}parseTokenOrUrl(e,n,r=2,s="dataset"){try{return $e(e),[n,e]}catch{}try{const i=new URL(e).pathname.split("/").filter(o=>o!=="");if(i.length>=r){const o=i[i.length-r];return[n,o]}else throw new Error(`Invalid public ${s} URL: ${e}`)}catch{throw new Error(`Invalid public ${s} URL or token: ${e}`)}}cleanup(){this._promptCache&&this._promptCache.stop()}async awaitPendingTraceBatches(){var e,n;if(this.manualFlushMode)return console.warn("[WARNING]: When tracing in manual flush mode, you must call `await client.flush()` manually to submit trace batches."),Promise.resolve();for(await new Promise(r=>setTimeout(r,1));this._pendingDrains.size>0;)await Promise.all([...this._pendingDrains]);await Promise.all([...this.autoBatchQueue.items.map(({itemPromise:r})=>r),this.batchIngestCaller.queue.onIdle()]),this.langSmithToOTELTranslator!==void 0&&await((n=(e=I$())==null?void 0:e.DEFAULT_LANGSMITH_SPAN_PROCESSOR)==null?void 0:n.forceFlush())}toString(){const e=[`apiUrl=${JSON.stringify(this.apiUrl)}`];return this.webUrl!==void 0&&e.push(`webUrl=${JSON.stringify(this.webUrl)}`),this.workspaceId!==void 0&&e.push(`workspaceId=${JSON.stringify(this.workspaceId)}`),`[LangSmithClient ${e.join(" ")}]`}[Symbol.for("nodejs.util.inspect.custom")](){return this.toString()}}Object.defineProperty(jr,"_fallbackDirsCreated",{enumerable:!0,configurable:!0,writable:!0,value:new Set});function pw(t){return"dataset_id"in t||"dataset_name"in t}const SN=t=>!!["TRACING_V2","TRACING"].find(n=>Tt(n)==="true"),Bs=Symbol.for("lc:context_variables"),Yh=Symbol.for("langsmith:replica_trace_roots");function mw(t,e){if(Bs in t)return t[Bs][e]}function TN(t,e,n){const r=Bs in t?t[Bs]:{};r[e]=n,t[Bs]=r}const EN="6ba7b810-9dad-11d1-80b4-00c04fd430c8";function gw(t){const n=Object.keys(t).sort().map(r=>`${r}:${t[r]??""}`).join("|");return wg(n,EN)}function AN(t){return t.replace(/[-:.]/g,"")}function ZS(t,e=1){const n=e.toFixed(0).slice(0,3).padStart(3,"0");return`${new Date(t).toISOString().slice(0,-1)}${n}Z`}function WS(t,e,n=1){const r=ZS(t,n);return{dottedOrder:AN(r)+e,microsecondPrecisionDatestring:r}}const IN=new Set(["projectName","updates","reroot"]);function xN(t){const e={};for(const n of Object.keys(t))IN.has(n)&&(e[n]=t[n]);return e}class Ql{constructor(e,n,r,s){Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"project_name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"replicas",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.metadata=e,this.tags=n,this.project_name=r,this.replicas=s}static fromHeader(e){const n=e.split(",");let r={},s=[],a,i;for(const o of n){const[c,u]=o.split("="),l=decodeURIComponent(u);c==="langsmith-metadata"?r=JSON.parse(l):c==="langsmith-tags"?s=l.split(","):c==="langsmith-project"?a=l:c==="langsmith-replicas"&&(i=JSON.parse(l).map(f=>Array.isArray(f)?f:xN(f)))}return new Ql(r,s,a,i)}toHeader(){const e=[];return this.metadata&&Object.keys(this.metadata).length>0&&e.push(`langsmith-metadata=${encodeURIComponent(JSON.stringify(this.metadata))}`),this.tags&&this.tags.length>0&&e.push(`langsmith-tags=${encodeURIComponent(this.tags.join(","))}`),this.project_name&&e.push(`langsmith-project=${encodeURIComponent(this.project_name)}`),e.join(",")}}class xn{constructor(e){var o;if(Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"run_type",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"project_name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"parent_run",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"parent_run_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"child_runs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"start_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"end_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"extra",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"error",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"serialized",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"inputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"outputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"reference_example_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"client",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"events",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"trace_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"dotted_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tracingEnabled",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"execution_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"child_execution_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"attachments",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"replicas",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"distributedParentId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_serialized_start_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_awaitInputsOnPost",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),kN(e)){Object.assign(this,{...e});return}const n=xn.getDefaultConfig(),{metadata:r,...s}=e,a=s.client??xn.getSharedClient(),i={...r,...(o=s==null?void 0:s.extra)==null?void 0:o.metadata};if(s.extra={...s.extra,metadata:i},"id"in s&&s.id==null&&delete s.id,Object.assign(this,{...n,...s,client:a}),this.execution_order??(this.execution_order=1),this.child_execution_order??(this.child_execution_order=1),this.dotted_order||(this._serialized_start_time=ZS(this.start_time,this.execution_order)),this.id||(this.id=t$(this._serialized_start_time??this.start_time)),this.trace_id||(this.parent_run?this.trace_id=this.parent_run.trace_id??this.id:this.trace_id=this.id),this.replicas=$N(this.replicas),!this.dotted_order){const{dottedOrder:c}=WS(this.start_time,this.id,this.execution_order);this.parent_run?this.dotted_order=this.parent_run.dotted_order+"."+c:this.dotted_order=c}}set metadata(e){var n;this.extra={...this.extra,metadata:{...(n=this.extra)==null?void 0:n.metadata,...e}}}get metadata(){var e;return(e=this.extra)==null?void 0:e.metadata}static getDefaultConfig(){const e=Date.now();return{run_type:"chain",project_name:SS(),child_runs:[],api_url:Wr("LANGCHAIN_ENDPOINT")??"http://localhost:1984",api_key:Wr("LANGCHAIN_API_KEY"),caller_options:{},start_time:e,serialized:{},inputs:{},extra:{}}}static getSharedClient(){return xn.sharedClient||(xn.sharedClient=new jr),xn.sharedClient}createChild(e){var f,h,m,_,y,w,g,b,S;const n=this.child_execution_order+1,r=(f=this.replicas)==null?void 0:f.map(I=>{const{reroot:T,...x}=I;return x}),s=e.replicas??r,a=new xn({...e,parent_run:this,project_name:this.project_name,replicas:s,client:this.client,tracingEnabled:this.tracingEnabled,execution_order:n,child_execution_order:n}),i=((h=this.extra)==null?void 0:h.metadata)??{},o=((m=a.extra)==null?void 0:m.metadata)??{};Object.keys(i).length>0&&(a.extra={...a.extra,metadata:{...i,...o}}),Bs in this&&(a[Bs]=this[Bs]);const c=Symbol.for("lc:child_config"),u=((_=e.extra)==null?void 0:_[c])??this.extra[c];if(CN(u)){const I={...u},T=ON(I.callbacks)?(w=(y=I.callbacks).copy)==null?void 0:w.call(y):void 0;T&&(Object.assign(T,{_parentRunId:a.id}),(S=(b=(g=T.handlers)==null?void 0:g.find(GS))==null?void 0:b.updateFromRunTree)==null||S.call(b,a),I.callbacks=T),a.extra[c]=I}const l=new Set;let d=this;for(;d!=null&&!l.has(d.id);)l.add(d.id),d.child_execution_order=Math.max(d.child_execution_order,n),d=d.parent_run;return this.child_runs.push(a),a}async end(e,n,r=Date.now(),s){this.outputs=this.outputs??e,this.error=this.error??n,this.end_time=this.end_time??r,s&&Object.keys(s).length>0&&(this.extra=this.extra?{...this.extra,metadata:{...this.extra.metadata,...s}}:{metadata:s})}_convertToCreate(e,n,r=!0){var o,c;const s=e.extra??{};if(((o=s==null?void 0:s.runtime)==null?void 0:o.library)===void 0&&(s.runtime||(s.runtime={}),n))for(const[u,l]of Object.entries(n))s.runtime[u]||(s.runtime[u]=l);const a=((c=e.parent_run)==null?void 0:c.id)??e.parent_run_id;let i;return r?i=[]:i=e.child_runs.map(u=>this._convertToCreate(u,n,r)),{id:e.id,name:e.name,start_time:e._serialized_start_time??e.start_time,end_time:e.end_time,run_type:e.run_type,reference_example_id:e.reference_example_id,extra:s,serialized:e.serialized,error:e.error,inputs:e.inputs,outputs:e.outputs,session_name:e.project_name,child_runs:i,parent_run_id:a,trace_id:e.trace_id,dotted_order:e.dotted_order,tags:e.tags,attachments:e.attachments,events:e.events}}_sliceParentId(e,n){if(n.dotted_order){const r=n.dotted_order.split(".");let s=null;for(let a=0;a<r.length;a++)if(r[a].slice(-36)===e){s=a;break}if(s!==null){const a=r.slice(s+1);n.dotted_order=a.join("."),a.length>0?n.trace_id=a[0].slice(-36):n.trace_id=n.id}}n.parent_run_id===e&&(n.parent_run_id=void 0)}_setReplicaTraceRoot(e,n){const r=mw(this,Yh)??{};r[e]=n,TN(this,Yh,r);for(const s of this.child_runs)s._setReplicaTraceRoot(e,n)}_remapForProject(e){const{projectName:n,runtimeEnv:r,excludeChildRuns:s=!0,reroot:a=!1,distributedParentId:i,apiUrl:o,apiKey:c,workspaceId:u}=e,l=this._convertToCreate(this,r,s);if(n===this.project_name)return{...l,session_name:n};if(a){if(i)this._sliceParentId(i,l);else if(l.parent_run_id=void 0,l.dotted_order){const g=l.dotted_order.split(".");g.length>0&&(l.dotted_order=g[g.length-1],l.trace_id=l.id)}const w=gw({projectName:n,apiUrl:o,apiKey:c,workspaceId:u});this._setReplicaTraceRoot(w,l.id)}let d;if(!a){const w=mw(this,Yh)??{},g=gw({projectName:n,apiUrl:o,apiKey:c,workspaceId:u});if(d=w[g],d&&(l.trace_id=d,l.dotted_order)){const b=l.dotted_order.split(".");let S=null;for(let I=0;I<b.length;I++)if(b[I].slice(-36)===d){S=I;break}if(S!==null){const I=b.slice(S);l.dotted_order=I.join(".")}}}const f=l.id,h=mu(f,n);let m;l.trace_id?m=mu(l.trace_id,n):m=h;let _;l.parent_run_id&&(_=mu(l.parent_run_id,n));let y;return l.dotted_order&&(y=l.dotted_order.split(".").map(b=>{const S=b.slice(-36),I=mu(S,n);return b.slice(0,-36)+I}).join(".")),{...l,id:h,trace_id:m,parent_run_id:_,dotted_order:y,session_name:n}}async postRun(e=!0){this._awaitInputsOnPost&&(this.inputs=await this.inputs);try{const n=NS();if(this.replicas&&this.replicas.length>0)for(const{projectName:r,apiKey:s,apiUrl:a,workspaceId:i,reroot:o,client:c}of this.replicas){const u=this._remapForProject({projectName:r??this.project_name,runtimeEnv:n,excludeChildRuns:!0,reroot:o,distributedParentId:this.distributedParentId,apiUrl:a,apiKey:s,workspaceId:i});await(c??this.client).createRun(u,{apiKey:s,apiUrl:a,workspaceId:i})}else{const r=this._convertToCreate(this,n,e);await this.client.createRun(r)}if(!e){dl("Posting with excludeChildRuns=false is deprecated and will be removed in a future version.");for(const r of this.child_runs)await r.postRun(!1)}this.child_runs=[]}catch(n){console.error(`Error in postRun for run ${this.id}:`,n)}}async patchRun(e){var n;if(this.replicas&&this.replicas.length>0)for(const{projectName:r,apiKey:s,apiUrl:a,workspaceId:i,updates:o,reroot:c,client:u}of this.replicas){const l=this._remapForProject({projectName:r??this.project_name,runtimeEnv:void 0,excludeChildRuns:!0,reroot:c,distributedParentId:this.distributedParentId,apiUrl:a,apiKey:s,workspaceId:i}),d={id:l.id,name:l.name,run_type:l.run_type,start_time:l.start_time,outputs:l.outputs,error:l.error,parent_run_id:l.parent_run_id,session_name:l.session_name,reference_example_id:l.reference_example_id,end_time:l.end_time,dotted_order:l.dotted_order,trace_id:l.trace_id,events:l.events,tags:l.tags,extra:l.extra,attachments:this.attachments,...o};e!=null&&e.excludeInputs||(d.inputs=l.inputs),await(u??this.client).updateRun(l.id,d,{apiKey:s,apiUrl:a,workspaceId:i})}else try{const r={name:this.name,run_type:this.run_type,start_time:this._serialized_start_time??this.start_time,end_time:this.end_time,error:this.error,outputs:this.outputs,parent_run_id:((n=this.parent_run)==null?void 0:n.id)??this.parent_run_id,reference_example_id:this.reference_example_id,extra:this.extra,events:this.events,dotted_order:this.dotted_order,trace_id:this.trace_id,tags:this.tags,attachments:this.attachments,session_name:this.project_name};e!=null&&e.excludeInputs||(r.inputs=this.inputs),await this.client.updateRun(this.id,r)}catch(r){console.error(`Error in patchRun for run ${this.id}`,r)}this.child_runs=[]}toJSON(){return this._convertToCreate(this,void 0,!1)}addEvent(e){this.events||(this.events=[]),typeof e=="string"?this.events.push({name:"event",time:new Date().toISOString(),message:e}):this.events.push({...e,time:e.time??new Date().toISOString()})}static fromRunnableConfig(e,n){var u,l,d,f;const r=e==null?void 0:e.callbacks;let s,a,i,o=SN();if(r){const h=((u=r==null?void 0:r.getParentRunId)==null?void 0:u.call(r))??"",m=(l=r==null?void 0:r.handlers)==null?void 0:l.find(_=>(_==null?void 0:_.name)=="langchain_tracer");s=(d=m==null?void 0:m.getRun)==null?void 0:d.call(m,h),a=m==null?void 0:m.projectName,i=m==null?void 0:m.client,o=o||!!m}return s?new xn({name:s.name,id:s.id,trace_id:s.trace_id,dotted_order:s.dotted_order,client:i,tracingEnabled:o,project_name:a,tags:[...new Set(((s==null?void 0:s.tags)??[]).concat((e==null?void 0:e.tags)??[]))],extra:{metadata:{...(f=s==null?void 0:s.extra)==null?void 0:f.metadata,...e==null?void 0:e.metadata}}}).createChild(n):new xn({...n,client:i,tracingEnabled:o,project_name:a})}static fromDottedOrder(e){return this.fromHeaders({"langsmith-trace":e})}static fromHeaders(e,n){var l;const r="get"in e&&typeof e.get=="function"?{"langsmith-trace":e.get("langsmith-trace"),baggage:e.get("baggage")}:e,s=r["langsmith-trace"];if(!s||typeof s!="string")return;const a=s.trim(),i=a.split(".").map(d=>{const[f,h]=d.split("Z");return{strTime:f,time:Date.parse(f+"Z"),uuid:h}}),o=i[0].uuid,c={...n,name:(n==null?void 0:n.name)??"parent",run_type:(n==null?void 0:n.run_type)??"chain",start_time:(n==null?void 0:n.start_time)??Date.now(),id:(l=i.at(-1))==null?void 0:l.uuid,trace_id:o,dotted_order:a};if(r.baggage&&typeof r.baggage=="string"){const d=Ql.fromHeader(r.baggage);c.metadata=d.metadata,c.tags=d.tags,c.project_name=d.project_name,c.replicas=d.replicas}const u=new xn(c);return u.distributedParentId=u.id,u}toHeaders(e){var r;const n={"langsmith-trace":this.dotted_order,baggage:new Ql((r=this.extra)==null?void 0:r.metadata,this.tags,this.project_name,this.replicas).toHeader()};if(e)for(const[s,a]of Object.entries(n))e.set(s,a);return n}}Object.defineProperty(xn,"sharedClient",{enumerable:!0,configurable:!0,writable:!0,value:null});function kN(t){return t!=null&&typeof t.createChild=="function"&&typeof t.postRun=="function"}function GS(t){return typeof t=="object"&&t!=null&&typeof t.name=="string"&&t.name==="langchain_tracer"}function _w(t){return Array.isArray(t)&&t.some(e=>GS(e))}function ON(t){return typeof t=="object"&&t!=null&&Array.isArray(t.handlers)}function CN(t){const e=t==null?void 0:t.callbacks;return t!=null&&typeof e=="object"&&(_w(e==null?void 0:e.handlers)||_w(e))}function RN(){const t=Wr("LANGSMITH_RUNS_ENDPOINTS");if(!t)return[];try{const e=JSON.parse(t);if(Array.isArray(e)){const n=[];for(const r of e){if(typeof r!="object"||r===null){console.warn(`Invalid item type in LANGSMITH_RUNS_ENDPOINTS: expected object, got ${typeof r}`);continue}if(typeof r.api_url!="string"){console.warn(`Invalid api_url type in LANGSMITH_RUNS_ENDPOINTS: expected string, got ${typeof r.api_url}`);continue}if(typeof r.api_key!="string"){console.warn(`Invalid api_key type in LANGSMITH_RUNS_ENDPOINTS: expected string, got ${typeof r.api_key}`);continue}n.push({apiUrl:r.api_url.replace(/\/$/,""),apiKey:r.api_key})}return n}else if(typeof e=="object"&&e!==null){NN(e);const n=[];for(const[r,s]of Object.entries(e)){const a=r.replace(/\/$/,"");if(typeof s=="string")n.push({apiUrl:a,apiKey:s});else{console.warn(`Invalid value type in LANGSMITH_RUNS_ENDPOINTS for URL ${r}: expected string, got ${typeof s}`);continue}}return n}else return console.warn(`Invalid LANGSMITH_RUNS_ENDPOINTS – must be valid JSON array of objects with api_url and api_key properties, or object mapping url->apiKey, got ${typeof e}`),[]}catch(e){if(nN(e))throw e;return console.warn("Invalid LANGSMITH_RUNS_ENDPOINTS – must be valid JSON array of objects with api_url and api_key properties, or object mapping url->apiKey"),[]}}function $N(t){return t?t.map(e=>Array.isArray(e)?{projectName:e[0],updates:e[1]}:e):RN()}function NN(t){if(Object.keys(t).length>0&&Tt("ENDPOINT"))throw new tN}var PN=ue({BaseTracer:()=>Ss,isBaseTracer:()=>ri});const MN=t=>{if(t)return t.events=t.events??[],t.child_runs=t.child_runs??[],t};function Ip(t,e){if(t)return new xn({...t,start_time:t._serialized_start_time??t.start_time,parent_run:Ip(e),child_runs:t.child_runs.map(n=>Ip(n)).filter(n=>n!==void 0),extra:{...t.extra,runtime:yS()},tracingEnabled:!1})}function Qh(t,e){return t&&!Array.isArray(t)&&typeof t=="object"?t:{[e]:t}}function ri(t){return typeof t._addRunToRunMap=="function"}var Ss=class extends za{constructor(e){super(...arguments);p(this,"runMap",new Map);p(this,"runTreeMap",new Map);p(this,"usesRunTreeMap",!1)}copy(){return this}getRunById(e){if(e!==void 0)return this.usesRunTreeMap?MN(this.runTreeMap.get(e)):this.runMap.get(e)}stringifyError(e){return e instanceof Error?e.message+(e!=null&&e.stack?`
54
-
55
- ${e.stack}`:""):typeof e=="string"?e:`${e}`}_addChildRun(e,n){e.child_runs.push(n)}_addRunToRunMap(e){const{dottedOrder:n,microsecondPrecisionDatestring:r}=WS(new Date(e.start_time).getTime(),e.id,e.execution_order),s={...e},a=this.getRunById(s.parent_run_id);if(s.parent_run_id!==void 0?a?(this._addChildRun(a,s),a.child_execution_order=Math.max(a.child_execution_order,s.child_execution_order),s.trace_id=a.trace_id,a.dotted_order!==void 0&&(s.dotted_order=[a.dotted_order,n].join("."),s._serialized_start_time=r)):s.parent_run_id=void 0:(s.trace_id=s.id,s.dotted_order=n,s._serialized_start_time=r),this.usesRunTreeMap){const i=Ip(s,a);i!==void 0&&this.runTreeMap.set(s.id,i)}else this.runMap.set(s.id,s);return s}async _endTrace(e){var r;const n=e.parent_run_id!==void 0&&this.getRunById(e.parent_run_id);n?n.child_execution_order=Math.max(n.child_execution_order,e.child_execution_order):await this.persistRun(e),await((r=this.onRunUpdate)==null?void 0:r.call(this,e)),this.usesRunTreeMap?this.runTreeMap.delete(e.id):this.runMap.delete(e.id)}_getExecutionOrder(e){const n=e!==void 0&&this.getRunById(e);return n?n.child_execution_order+1:1}_createRunForLLMStart(e,n,r,s,a,i,o,c){const u=this._getExecutionOrder(s),l=Date.now(),d=o?{...a,metadata:o}:a,f={id:r,name:c??e.id[e.id.length-1],parent_run_id:s,start_time:l,serialized:e,events:[{name:"start",time:new Date(l).toISOString()}],inputs:{prompts:n},execution_order:u,child_runs:[],child_execution_order:u,run_type:"llm",extra:d??{},tags:i||[]};return this._addRunToRunMap(f)}async handleLLMStart(e,n,r,s,a,i,o,c){var l,d;const u=this.getRunById(r)??this._createRunForLLMStart(e,n,r,s,a,i,o,c);return await((l=this.onRunCreate)==null?void 0:l.call(this,u)),await((d=this.onLLMStart)==null?void 0:d.call(this,u)),u}_createRunForChatModelStart(e,n,r,s,a,i,o,c){const u=this._getExecutionOrder(s),l=Date.now(),d=o?{...a,metadata:o}:a,f={id:r,name:c??e.id[e.id.length-1],parent_run_id:s,start_time:l,serialized:e,events:[{name:"start",time:new Date(l).toISOString()}],inputs:{messages:n},execution_order:u,child_runs:[],child_execution_order:u,run_type:"llm",extra:d??{},tags:i||[]};return this._addRunToRunMap(f)}async handleChatModelStart(e,n,r,s,a,i,o,c){var l,d;const u=this.getRunById(r)??this._createRunForChatModelStart(e,n,r,s,a,i,o,c);return await((l=this.onRunCreate)==null?void 0:l.call(this,u)),await((d=this.onLLMStart)==null?void 0:d.call(this,u)),u}async handleLLMEnd(e,n,r,s,a){var o;const i=this.getRunById(n);if(!i||(i==null?void 0:i.run_type)!=="llm")throw new Error("No LLM run to end.");return i.end_time=Date.now(),i.outputs=e,i.events.push({name:"end",time:new Date(i.end_time).toISOString()}),i.extra={...i.extra,...a},await((o=this.onLLMEnd)==null?void 0:o.call(this,i)),await this._endTrace(i),i}async handleLLMError(e,n,r,s,a){var o;const i=this.getRunById(n);if(!i||(i==null?void 0:i.run_type)!=="llm")throw new Error("No LLM run to end.");return i.end_time=Date.now(),i.error=this.stringifyError(e),i.events.push({name:"error",time:new Date(i.end_time).toISOString()}),i.extra={...i.extra,...a},await((o=this.onLLMError)==null?void 0:o.call(this,i)),await this._endTrace(i),i}_createRunForChainStart(e,n,r,s,a,i,o,c,u){const l=this._getExecutionOrder(s),d=Date.now(),f={id:r,name:c??e.id[e.id.length-1],parent_run_id:s,start_time:d,serialized:e,events:[{name:"start",time:new Date(d).toISOString()}],inputs:n,execution_order:l,child_execution_order:l,run_type:o??"chain",child_runs:[],extra:i?{...u,metadata:i}:{...u},tags:a||[]};return this._addRunToRunMap(f)}async handleChainStart(e,n,r,s,a,i,o,c){var l,d;const u=this.getRunById(r)??this._createRunForChainStart(e,n,r,s,a,i,o,c);return await((l=this.onRunCreate)==null?void 0:l.call(this,u)),await((d=this.onChainStart)==null?void 0:d.call(this,u)),u}async handleChainEnd(e,n,r,s,a){var o;const i=this.getRunById(n);if(!i)throw new Error("No chain run to end.");return i.end_time=Date.now(),i.outputs=Qh(e,"output"),i.events.push({name:"end",time:new Date(i.end_time).toISOString()}),(a==null?void 0:a.inputs)!==void 0&&(i.inputs=Qh(a.inputs,"input")),await((o=this.onChainEnd)==null?void 0:o.call(this,i)),await this._endTrace(i),i}async handleChainError(e,n,r,s,a){var o;const i=this.getRunById(n);if(!i)throw new Error("No chain run to end.");return i.end_time=Date.now(),i.error=this.stringifyError(e),i.events.push({name:"error",time:new Date(i.end_time).toISOString()}),(a==null?void 0:a.inputs)!==void 0&&(i.inputs=Qh(a.inputs,"input")),await((o=this.onChainError)==null?void 0:o.call(this,i)),await this._endTrace(i),i}_createRunForToolStart(e,n,r,s,a,i,o){const c=this._getExecutionOrder(s),u=Date.now(),l={id:r,name:o??e.id[e.id.length-1],parent_run_id:s,start_time:u,serialized:e,events:[{name:"start",time:new Date(u).toISOString()}],inputs:{input:n},execution_order:c,child_execution_order:c,run_type:"tool",child_runs:[],extra:i?{metadata:i}:{},tags:a||[]};return this._addRunToRunMap(l)}async handleToolStart(e,n,r,s,a,i,o){var u,l;const c=this.getRunById(r)??this._createRunForToolStart(e,n,r,s,a,i,o);return await((u=this.onRunCreate)==null?void 0:u.call(this,c)),await((l=this.onToolStart)==null?void 0:l.call(this,c)),c}async handleToolEnd(e,n){var s;const r=this.getRunById(n);if(!r||(r==null?void 0:r.run_type)!=="tool")throw new Error("No tool run to end");return r.end_time=Date.now(),r.outputs={output:e},r.events.push({name:"end",time:new Date(r.end_time).toISOString()}),await((s=this.onToolEnd)==null?void 0:s.call(this,r)),await this._endTrace(r),r}async handleToolError(e,n){var s;const r=this.getRunById(n);if(!r||(r==null?void 0:r.run_type)!=="tool")throw new Error("No tool run to end");return r.end_time=Date.now(),r.error=this.stringifyError(e),r.events.push({name:"error",time:new Date(r.end_time).toISOString()}),await((s=this.onToolError)==null?void 0:s.call(this,r)),await this._endTrace(r),r}async handleAgentAction(e,n){var a;const r=this.getRunById(n);if(!r||(r==null?void 0:r.run_type)!=="chain")return;const s=r;s.actions=s.actions||[],s.actions.push(e),s.events.push({name:"agent_action",time:new Date().toISOString(),kwargs:{action:e}}),await((a=this.onAgentAction)==null?void 0:a.call(this,r))}async handleAgentEnd(e,n){var s;const r=this.getRunById(n);!r||(r==null?void 0:r.run_type)!=="chain"||(r.events.push({name:"agent_end",time:new Date().toISOString(),kwargs:{action:e}}),await((s=this.onAgentEnd)==null?void 0:s.call(this,r)))}_createRunForRetrieverStart(e,n,r,s,a,i,o){const c=this._getExecutionOrder(s),u=Date.now(),l={id:r,name:o??e.id[e.id.length-1],parent_run_id:s,start_time:u,serialized:e,events:[{name:"start",time:new Date(u).toISOString()}],inputs:{query:n},execution_order:c,child_execution_order:c,run_type:"retriever",child_runs:[],extra:i?{metadata:i}:{},tags:a||[]};return this._addRunToRunMap(l)}async handleRetrieverStart(e,n,r,s,a,i,o){var u,l;const c=this.getRunById(r)??this._createRunForRetrieverStart(e,n,r,s,a,i,o);return await((u=this.onRunCreate)==null?void 0:u.call(this,c)),await((l=this.onRetrieverStart)==null?void 0:l.call(this,c)),c}async handleRetrieverEnd(e,n){var s;const r=this.getRunById(n);if(!r||(r==null?void 0:r.run_type)!=="retriever")throw new Error("No retriever run to end");return r.end_time=Date.now(),r.outputs={documents:e},r.events.push({name:"end",time:new Date(r.end_time).toISOString()}),await((s=this.onRetrieverEnd)==null?void 0:s.call(this,r)),await this._endTrace(r),r}async handleRetrieverError(e,n){var s;const r=this.getRunById(n);if(!r||(r==null?void 0:r.run_type)!=="retriever")throw new Error("No retriever run to end");return r.end_time=Date.now(),r.error=this.stringifyError(e),r.events.push({name:"error",time:new Date(r.end_time).toISOString()}),await((s=this.onRetrieverError)==null?void 0:s.call(this,r)),await this._endTrace(r),r}async handleText(e,n){var s;const r=this.getRunById(n);!r||(r==null?void 0:r.run_type)!=="chain"||(r.events.push({name:"text",time:new Date().toISOString(),kwargs:{text:e}}),await((s=this.onText)==null?void 0:s.call(this,r)))}async handleLLMNewToken(e,n,r,s,a,i){var c;const o=this.getRunById(r);if(!o||(o==null?void 0:o.run_type)!=="llm")throw new Error('Invalid "runId" provided to "handleLLMNewToken" callback.');return o.events.push({name:"new_token",time:new Date().toISOString(),kwargs:{token:e,idx:n,chunk:i==null?void 0:i.chunk}}),await((c=this.onLLMNewToken)==null?void 0:c.call(this,o,e,{chunk:i==null?void 0:i.chunk})),o}},Eg={exports:{}};Eg.exports;(function(t){const n=(a=0)=>i=>`\x1B[${38+a};5;${i}m`,r=(a=0)=>(i,o,c)=>`\x1B[${38+a};2;${i};${o};${c}m`;function s(){const a=new Map,i={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}};i.color.gray=i.color.blackBright,i.bgColor.bgGray=i.bgColor.bgBlackBright,i.color.grey=i.color.blackBright,i.bgColor.bgGrey=i.bgColor.bgBlackBright;for(const[o,c]of Object.entries(i)){for(const[u,l]of Object.entries(c))i[u]={open:`\x1B[${l[0]}m`,close:`\x1B[${l[1]}m`},c[u]=i[u],a.set(l[0],l[1]);Object.defineProperty(i,o,{value:c,enumerable:!1})}return Object.defineProperty(i,"codes",{value:a,enumerable:!1}),i.color.close="\x1B[39m",i.bgColor.close="\x1B[49m",i.color.ansi256=n(),i.color.ansi16m=r(),i.bgColor.ansi256=n(10),i.bgColor.ansi16m=r(10),Object.defineProperties(i,{rgbToAnsi256:{value:(o,c,u)=>o===c&&c===u?o<8?16:o>248?231:Math.round((o-8)/247*24)+232:16+36*Math.round(o/255*5)+6*Math.round(c/255*5)+Math.round(u/255*5),enumerable:!1},hexToRgb:{value:o=>{const c=/(?<colorString>[a-f\d]{6}|[a-f\d]{3})/i.exec(o.toString(16));if(!c)return[0,0,0];let{colorString:u}=c.groups;u.length===3&&(u=u.split("").map(d=>d+d).join(""));const l=Number.parseInt(u,16);return[l>>16&255,l>>8&255,l&255]},enumerable:!1},hexToAnsi256:{value:o=>i.rgbToAnsi256(...i.hexToRgb(o)),enumerable:!1}}),i}Object.defineProperty(t,"exports",{enumerable:!0,get:s})})(Eg);var LN=Eg.exports;const qS=ng(LN);var jN=ue({ConsoleCallbackHandler:()=>xp});function pn(t,e){return`${t.open}${e}${t.close}`}function tr(t,e){try{return JSON.stringify(t,null,2)}catch{return e}}function yw(t){return typeof t=="string"?t.trim():t==null?t:tr(t,t.toString())}function Ts(t){if(!t.end_time)return"";const e=t.end_time-t.start_time;return e<1e3?`${e}ms`:`${(e/1e3).toFixed(2)}s`}const{color:An}=qS;var xp=class extends Ss{constructor(){super(...arguments);p(this,"name","console_callback_handler")}persistRun(e){return Promise.resolve()}getParents(e){const n=[];let r=e;for(;r.parent_run_id;){const s=this.runMap.get(r.parent_run_id);if(s)n.push(s),r=s;else break}return n}getBreadcrumbs(e){const n=[...this.getParents(e).reverse(),e].map((r,s,a)=>{const i=`${r.execution_order}:${r.run_type}:${r.name}`;return s===a.length-1?pn(qS.bold,i):i}).join(" > ");return pn(An.grey,n)}onChainStart(e){const n=this.getBreadcrumbs(e);console.log(`${pn(An.green,"[chain/start]")} [${n}] Entering Chain run with input: ${tr(e.inputs,"[inputs]")}`)}onChainEnd(e){const n=this.getBreadcrumbs(e);console.log(`${pn(An.cyan,"[chain/end]")} [${n}] [${Ts(e)}] Exiting Chain run with output: ${tr(e.outputs,"[outputs]")}`)}onChainError(e){const n=this.getBreadcrumbs(e);console.log(`${pn(An.red,"[chain/error]")} [${n}] [${Ts(e)}] Chain run errored with error: ${tr(e.error,"[error]")}`)}onLLMStart(e){const n=this.getBreadcrumbs(e),r="prompts"in e.inputs?{prompts:e.inputs.prompts.map(s=>s.trim())}:e.inputs;console.log(`${pn(An.green,"[llm/start]")} [${n}] Entering LLM run with input: ${tr(r,"[inputs]")}`)}onLLMEnd(e){const n=this.getBreadcrumbs(e);console.log(`${pn(An.cyan,"[llm/end]")} [${n}] [${Ts(e)}] Exiting LLM run with output: ${tr(e.outputs,"[response]")}`)}onLLMError(e){const n=this.getBreadcrumbs(e);console.log(`${pn(An.red,"[llm/error]")} [${n}] [${Ts(e)}] LLM run errored with error: ${tr(e.error,"[error]")}`)}onToolStart(e){const n=this.getBreadcrumbs(e);console.log(`${pn(An.green,"[tool/start]")} [${n}] Entering Tool run with input: "${yw(e.inputs.input)}"`)}onToolEnd(e){var r;const n=this.getBreadcrumbs(e);console.log(`${pn(An.cyan,"[tool/end]")} [${n}] [${Ts(e)}] Exiting Tool run with output: "${yw((r=e.outputs)==null?void 0:r.output)}"`)}onToolError(e){const n=this.getBreadcrumbs(e);console.log(`${pn(An.red,"[tool/error]")} [${n}] [${Ts(e)}] Tool run errored with error: ${tr(e.error,"[error]")}`)}onRetrieverStart(e){const n=this.getBreadcrumbs(e);console.log(`${pn(An.green,"[retriever/start]")} [${n}] Entering Retriever run with input: ${tr(e.inputs,"[inputs]")}`)}onRetrieverEnd(e){const n=this.getBreadcrumbs(e);console.log(`${pn(An.cyan,"[retriever/end]")} [${n}] [${Ts(e)}] Exiting Retriever run with output: ${tr(e.outputs,"[outputs]")}`)}onRetrieverError(e){const n=this.getBreadcrumbs(e);console.log(`${pn(An.red,"[retriever/error]")} [${n}] [${Ts(e)}] Retriever run errored with error: ${tr(e.error,"[error]")}`)}onAgentAction(e){const n=e,r=this.getBreadcrumbs(e);console.log(`${pn(An.blue,"[agent/action]")} [${r}] Agent selected action: ${tr(n.actions[n.actions.length-1],"[action]")}`)}};let ef;const KS=()=>(ef===void 0&&(ef=new jr(It("LANGCHAIN_CALLBACKS_BACKGROUND")==="false"?{blockOnRootRunFinalization:!0}:{})),ef);let UN=class{getStore(){}run(e,n){return n()}};const tf=Symbol.for("ls:tracing_async_local_storage"),DN=new UN;let FN=class{getInstance(){return globalThis[tf]??DN}initializeGlobalInstance(e){globalThis[tf]===void 0&&(globalThis[tf]=e)}};const BN=new FN;function zN(t=!1){const e=BN.getInstance().getStore();if(!t&&e===void 0)throw new Error(`Could not get the current run tree.
56
-
57
- Please make sure you are calling this method within a traceable function and that tracing is enabled.`);return e}function Ag(t){return typeof t=="function"&&"langsmith:traceable"in t}var HN=ue({LangChainTracer:()=>xo,OVERRIDABLE_LANGSMITH_INHERITABLE_METADATA_KEYS:()=>Ig});const Ig=new Set(["ls_agent_type"]);function VN(t){let e;for(const n of t)for(const r of n)De.isInstance(r.message)&&r.message.usage_metadata!==void 0&&(e=fg(e,r.message.usage_metadata));return e}var xo=class kp extends Ss{constructor(n={}){super(n);p(this,"name","langchain_tracer");p(this,"projectName");p(this,"exampleId");p(this,"client");p(this,"replicas");p(this,"usesRunTreeMap",!0);p(this,"tracingMetadata");p(this,"tracingTags",[]);this.fields=n;const{exampleId:r,projectName:s,client:a,replicas:i,metadata:o,tags:c}=n;this.projectName=s??SS(),this.replicas=i,this.exampleId=r,this.client=a??KS(),this.tracingMetadata=o?{...o}:void 0,this.tracingTags=c??[];const u=kp.getTraceableRunTree();u&&this.updateFromRunTree(u)}async persistRun(n){}async onRunCreate(n){var r,s;ww(this,n),(r=n.extra)!=null&&r.lc_defers_inputs||await((s=this.getRunTreeWithTracingConfig(n.id))==null?void 0:s.postRun())}async onRunUpdate(n){var s;ww(this,n);const r=this.getRunTreeWithTracingConfig(n.id);(s=n.extra)!=null&&s.lc_defers_inputs?await(r==null?void 0:r.postRun()):await(r==null?void 0:r.patchRun())}onLLMEnd(n){const r=n.outputs;if(r!=null&&r.generations){const s=VN(r.generations);if(s!==void 0){n.extra=n.extra??{};const a=n.extra.metadata??{};a.usage_metadata=s,n.extra.metadata=a}}}copyWithTracingConfig({metadata:n,tags:r}){let s;if(n===void 0)s=this.tracingMetadata?{...this.tracingMetadata}:void 0;else if(this.tracingMetadata===void 0)s={...n};else{s={...this.tracingMetadata};for(const[o,c]of Object.entries(n))(!Object.prototype.hasOwnProperty.call(s,o)||Ig.has(o))&&(s[o]=c)}const a=r?Array.from(new Set([...this.tracingTags,...r])):[...this.tracingTags],i=new kp({...this.fields,metadata:s,tags:a});return i.runMap=this.runMap,i.runTreeMap=this.runTreeMap,i}getRun(n){return this.runTreeMap.get(n)}updateFromRunTree(n){this.runTreeMap.set(n.id,n);let r=n;const s=new Set;for(;r.parent_run&&!(s.has(r.id)||(s.add(r.id),!r.parent_run));)r=r.parent_run;s.clear();const a=[r];for(;a.length>0;){const i=a.shift();!i||s.has(i.id)||(s.add(i.id),this.runTreeMap.set(i.id,i),i.child_runs&&a.push(...i.child_runs))}this.client=n.client??this.client,this.replicas=n.replicas??this.replicas,this.projectName=n.project_name??this.projectName,this.exampleId=n.reference_example_id??this.exampleId,this.fields={...this.fields,client:this.client,replicas:this.replicas,projectName:this.projectName,exampleId:this.exampleId}}getRunTreeWithTracingConfig(n){const r=this.runTreeMap.get(n);if(r)return new xn({...r,client:this.client,project_name:this.projectName,replicas:this.replicas,reference_example_id:this.exampleId,tracingEnabled:!0})}static getTraceableRunTree(){try{return zN(!0)}catch{return}}static[Symbol.hasInstance](n){if(typeof n!="object"||n===null)return!1;const r=n;return"name"in r&&r.name==="langchain_tracer"&&"copyWithTracingConfig"in r&&typeof r.copyWithTracingConfig=="function"&&"getRunTreeWithTracingConfig"in r&&typeof r.getRunTreeWithTracingConfig=="function"}};function ww(t,e){if(t.tracingMetadata){e.extra??(e.extra={});const n=e.extra.metadata??{};let r=!1;for(const[s,a]of Object.entries(t.tracingMetadata))(!Object.prototype.hasOwnProperty.call(n,s)||Ig.has(s))&&n[s]!==a&&(n[s]=a,r=!0);r&&(e.extra.metadata=n)}t.tracingTags.length>0&&(e.tags=Array.from(new Set([...e.tags??[],...t.tracingTags])))}const JS=Symbol.for("ls:tracing_async_local_storage"),Yo=Symbol.for("lc:context_variables"),ZN=t=>{globalThis[JS]=t},uc=()=>globalThis[JS];let ka;function WN(){return new("default"in ms?ms.default:ms)({autoStart:!0,concurrency:1})}function GN(){return typeof ka>"u"&&(ka=WN()),ka}async function Et(t,e){if(e===!0){const n=uc();n!==void 0?await n.run(void 0,async()=>t()):await t()}else ka=GN(),ka.add(async()=>{const n=uc();n!==void 0?await n.run(void 0,async()=>t()):await t()})}async function qN(){const t=KS();await Promise.allSettled([typeof ka<"u"?ka.onIdle():Promise.resolve(),t.awaitPendingTraceBatches()])}var KN=ue({awaitAllCallbacks:()=>qN,consumeCallback:()=>Et});const JN=t=>!!["LANGSMITH_TRACING_V2","LANGCHAIN_TRACING_V2","LANGSMITH_TRACING","LANGCHAIN_TRACING"].find(e=>It(e)==="true");function XS(t){var n,r;const e=uc();if(e!==void 0)return(r=(n=e.getStore())==null?void 0:n[Yo])==null?void 0:r[t]}const XN=Symbol("lc:configure_hooks"),YN=()=>XS(XN)||[];var QN=ue({BaseCallbackManager:()=>YS,BaseRunManager:()=>Zc,CallbackManager:()=>un,CallbackManagerForChainRun:()=>eT,CallbackManagerForLLMRun:()=>Op,CallbackManagerForRetrieverRun:()=>QS,CallbackManagerForToolRun:()=>tT,ensureHandler:()=>lc,parseCallbackConfigArg:()=>Vc});function Vc(t){return t?Array.isArray(t)||"name"in t?{callbacks:t}:t:{}}var YS=class{setHandler(t){return this.setHandlers([t])}},Zc=class{constructor(t,e,n,r,s,a,i,o){this.runId=t,this.handlers=e,this.inheritableHandlers=n,this.tags=r,this.inheritableTags=s,this.metadata=a,this.inheritableMetadata=i,this._parentRunId=o}get parentRunId(){return this._parentRunId}async handleText(t){await Promise.all(this.handlers.map(e=>Et(async()=>{var n;try{await((n=e.handleText)==null?void 0:n.call(e,t,this.runId,this._parentRunId,this.tags))}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleText: ${r}`),e.raiseError)throw r}},e.awaitHandlers)))}async handleCustomEvent(t,e,n,r,s){await Promise.all(this.handlers.map(a=>Et(async()=>{var i;try{await((i=a.handleCustomEvent)==null?void 0:i.call(a,t,e,this.runId,this.tags,this.metadata))}catch(o){if((a.raiseError?console.error:console.warn)(`Error in handler ${a.constructor.name}, handleCustomEvent: ${o}`),a.raiseError)throw o}},a.awaitHandlers)))}},QS=class extends Zc{getChild(t){const e=new un(this.runId);return e.setHandlers(this.inheritableHandlers),e.addTags(this.inheritableTags),e.addMetadata(this.inheritableMetadata),t&&e.addTags([t],!1),e}async handleRetrieverEnd(t){await Promise.all(this.handlers.map(e=>Et(async()=>{var n;if(!e.ignoreRetriever)try{await((n=e.handleRetrieverEnd)==null?void 0:n.call(e,t,this.runId,this._parentRunId,this.tags))}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleRetriever`),e.raiseError)throw r}},e.awaitHandlers)))}async handleRetrieverError(t){await Promise.all(this.handlers.map(e=>Et(async()=>{var n;if(!e.ignoreRetriever)try{await((n=e.handleRetrieverError)==null?void 0:n.call(e,t,this.runId,this._parentRunId,this.tags))}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleRetrieverError: ${r}`),e.raiseError)throw t}},e.awaitHandlers)))}},Op=class extends Zc{async handleLLMNewToken(t,e,n,r,s,a){await Promise.all(this.handlers.map(i=>Et(async()=>{var o;if(!i.ignoreLLM)try{await((o=i.handleLLMNewToken)==null?void 0:o.call(i,t,e??{prompt:0,completion:0},this.runId,this._parentRunId,this.tags,a))}catch(c){if((i.raiseError?console.error:console.warn)(`Error in handler ${i.constructor.name}, handleLLMNewToken: ${c}`),i.raiseError)throw c}},i.awaitHandlers)))}async handleLLMError(t,e,n,r,s){await Promise.all(this.handlers.map(a=>Et(async()=>{var i;if(!a.ignoreLLM)try{await((i=a.handleLLMError)==null?void 0:i.call(a,t,this.runId,this._parentRunId,this.tags,s))}catch(o){if((a.raiseError?console.error:console.warn)(`Error in handler ${a.constructor.name}, handleLLMError: ${o}`),a.raiseError)throw o}},a.awaitHandlers)))}async handleLLMEnd(t,e,n,r,s){await Promise.all(this.handlers.map(a=>Et(async()=>{var i;if(!a.ignoreLLM)try{await((i=a.handleLLMEnd)==null?void 0:i.call(a,t,this.runId,this._parentRunId,this.tags,s))}catch(o){if((a.raiseError?console.error:console.warn)(`Error in handler ${a.constructor.name}, handleLLMEnd: ${o}`),a.raiseError)throw o}},a.awaitHandlers)))}},eT=class extends Zc{getChild(t){const e=new un(this.runId);return e.setHandlers(this.inheritableHandlers),e.addTags(this.inheritableTags),e.addMetadata(this.inheritableMetadata),t&&e.addTags([t],!1),e}async handleChainError(t,e,n,r,s){await Promise.all(this.handlers.map(a=>Et(async()=>{var i;if(!a.ignoreChain)try{await((i=a.handleChainError)==null?void 0:i.call(a,t,this.runId,this._parentRunId,this.tags,s))}catch(o){if((a.raiseError?console.error:console.warn)(`Error in handler ${a.constructor.name}, handleChainError: ${o}`),a.raiseError)throw o}},a.awaitHandlers)))}async handleChainEnd(t,e,n,r,s){await Promise.all(this.handlers.map(a=>Et(async()=>{var i;if(!a.ignoreChain)try{await((i=a.handleChainEnd)==null?void 0:i.call(a,t,this.runId,this._parentRunId,this.tags,s))}catch(o){if((a.raiseError?console.error:console.warn)(`Error in handler ${a.constructor.name}, handleChainEnd: ${o}`),a.raiseError)throw o}},a.awaitHandlers)))}async handleAgentAction(t){await Promise.all(this.handlers.map(e=>Et(async()=>{var n;if(!e.ignoreAgent)try{await((n=e.handleAgentAction)==null?void 0:n.call(e,t,this.runId,this._parentRunId,this.tags))}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleAgentAction: ${r}`),e.raiseError)throw r}},e.awaitHandlers)))}async handleAgentEnd(t){await Promise.all(this.handlers.map(e=>Et(async()=>{var n;if(!e.ignoreAgent)try{await((n=e.handleAgentEnd)==null?void 0:n.call(e,t,this.runId,this._parentRunId,this.tags))}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleAgentEnd: ${r}`),e.raiseError)throw r}},e.awaitHandlers)))}},tT=class extends Zc{getChild(t){const e=new un(this.runId);return e.setHandlers(this.inheritableHandlers),e.addTags(this.inheritableTags),e.addMetadata(this.inheritableMetadata),t&&e.addTags([t],!1),e}async handleToolError(t){await Promise.all(this.handlers.map(e=>Et(async()=>{var n;if(!e.ignoreAgent)try{await((n=e.handleToolError)==null?void 0:n.call(e,t,this.runId,this._parentRunId,this.tags))}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleToolError: ${r}`),e.raiseError)throw r}},e.awaitHandlers)))}async handleToolEvent(t){await Promise.all(this.handlers.map(e=>Et(async()=>{var n;if(!e.ignoreAgent)try{await((n=e.handleToolEvent)==null?void 0:n.call(e,t,this.runId,this._parentRunId,this.tags))}catch(r){if(e.raiseError)throw r}},e.awaitHandlers)))}async handleToolEnd(t){await Promise.all(this.handlers.map(e=>Et(async()=>{var n;if(!e.ignoreAgent)try{await((n=e.handleToolEnd)==null?void 0:n.call(e,t,this.runId,this._parentRunId,this.tags))}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleToolEnd: ${r}`),e.raiseError)throw r}},e.awaitHandlers)))}},un=class ko extends YS{constructor(n,r){super();p(this,"handlers",[]);p(this,"inheritableHandlers",[]);p(this,"tags",[]);p(this,"inheritableTags",[]);p(this,"metadata",{});p(this,"inheritableMetadata",{});p(this,"name","callback_manager");p(this,"_parentRunId");this.handlers=(r==null?void 0:r.handlers)??this.handlers,this.inheritableHandlers=(r==null?void 0:r.inheritableHandlers)??this.inheritableHandlers,this.tags=(r==null?void 0:r.tags)??this.tags,this.inheritableTags=(r==null?void 0:r.inheritableTags)??this.inheritableTags,this.metadata=(r==null?void 0:r.metadata)??this.metadata,this.inheritableMetadata=(r==null?void 0:r.inheritableMetadata)??this.inheritableMetadata,this._parentRunId=n}getParentRunId(){return this._parentRunId}async handleLLMStart(n,r,s=void 0,a=void 0,i=void 0,o=void 0,c=void 0,u=void 0){return Promise.all(r.map(async(l,d)=>{const f=d===0&&s?s:rs();return await Promise.all(this.handlers.map(h=>{if(!h.ignoreLLM)return ri(h)&&h._createRunForLLMStart(n,[l],f,this._parentRunId,i,this.tags,this.metadata,u),Et(async()=>{var m;try{await((m=h.handleLLMStart)==null?void 0:m.call(h,n,[l],f,this._parentRunId,i,this.tags,this.metadata,u))}catch(_){if((h.raiseError?console.error:console.warn)(`Error in handler ${h.constructor.name}, handleLLMStart: ${_}`),h.raiseError)throw _}},h.awaitHandlers)})),new Op(f,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChatModelStart(n,r,s=void 0,a=void 0,i=void 0,o=void 0,c=void 0,u=void 0){return Promise.all(r.map(async(l,d)=>{const f=d===0&&s?s:rs();return await Promise.all(this.handlers.map(h=>{if(!h.ignoreLLM)return ri(h)&&h._createRunForChatModelStart(n,[l],f,this._parentRunId,i,this.tags,this.metadata,u),Et(async()=>{var m,_;try{if(h.handleChatModelStart)await((m=h.handleChatModelStart)==null?void 0:m.call(h,n,[l],f,this._parentRunId,i,this.tags,this.metadata,u));else if(h.handleLLMStart){const y=pg(l);await((_=h.handleLLMStart)==null?void 0:_.call(h,n,[y],f,this._parentRunId,i,this.tags,this.metadata,u))}}catch(y){if((h.raiseError?console.error:console.warn)(`Error in handler ${h.constructor.name}, handleLLMStart: ${y}`),h.raiseError)throw y}},h.awaitHandlers)})),new Op(f,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChainStart(n,r,s=rs(),a=void 0,i=void 0,o=void 0,c=void 0,u=void 0,l=void 0){return await Promise.all(this.handlers.map(d=>{if(!d.ignoreChain)return ri(d)&&d._createRunForChainStart(n,r,s,this._parentRunId,this.tags,this.metadata,a,c,l),Et(async()=>{var f;try{await((f=d.handleChainStart)==null?void 0:f.call(d,n,r,s,this._parentRunId,this.tags,this.metadata,a,c,l))}catch(h){if((d.raiseError?console.error:console.warn)(`Error in handler ${d.constructor.name}, handleChainStart: ${h}`),d.raiseError)throw h}},d.awaitHandlers)})),new eT(s,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleToolStart(n,r,s=rs(),a=void 0,i=void 0,o=void 0,c=void 0,u=void 0){return await Promise.all(this.handlers.map(l=>{if(!l.ignoreAgent)return ri(l)&&l._createRunForToolStart(n,r,s,this._parentRunId,this.tags,this.metadata,c),Et(async()=>{var d;try{await((d=l.handleToolStart)==null?void 0:d.call(l,n,r,s,this._parentRunId,this.tags,this.metadata,c,u))}catch(f){if((l.raiseError?console.error:console.warn)(`Error in handler ${l.constructor.name}, handleToolStart: ${f}`),l.raiseError)throw f}},l.awaitHandlers)})),new tT(s,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleRetrieverStart(n,r,s=rs(),a=void 0,i=void 0,o=void 0,c=void 0){return await Promise.all(this.handlers.map(u=>{if(!u.ignoreRetriever)return ri(u)&&u._createRunForRetrieverStart(n,r,s,this._parentRunId,this.tags,this.metadata,c),Et(async()=>{var l;try{await((l=u.handleRetrieverStart)==null?void 0:l.call(u,n,r,s,this._parentRunId,this.tags,this.metadata,c))}catch(d){if((u.raiseError?console.error:console.warn)(`Error in handler ${u.constructor.name}, handleRetrieverStart: ${d}`),u.raiseError)throw d}},u.awaitHandlers)})),new QS(s,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleCustomEvent(n,r,s,a,i){await Promise.all(this.handlers.map(o=>Et(async()=>{var c;if(!o.ignoreCustomEvent)try{await((c=o.handleCustomEvent)==null?void 0:c.call(o,n,r,s,this.tags,this.metadata))}catch(u){if((o.raiseError?console.error:console.warn)(`Error in handler ${o.constructor.name}, handleCustomEvent: ${u}`),o.raiseError)throw u}},o.awaitHandlers)))}addHandler(n,r=!0){this.handlers.push(n),r&&this.inheritableHandlers.push(n)}removeHandler(n){this.handlers=this.handlers.filter(r=>r!==n),this.inheritableHandlers=this.inheritableHandlers.filter(r=>r!==n)}setHandlers(n,r=!0){this.handlers=[],this.inheritableHandlers=[];for(const s of n)this.addHandler(s,r)}addTags(n,r=!0){this.removeTags(n),this.tags.push(...n),r&&this.inheritableTags.push(...n)}removeTags(n){this.tags=this.tags.filter(r=>!n.includes(r)),this.inheritableTags=this.inheritableTags.filter(r=>!n.includes(r))}addMetadata(n,r=!0){this.metadata={...this.metadata,...n},r&&(this.inheritableMetadata={...this.inheritableMetadata,...n})}removeMetadata(n){for(const r of Object.keys(n))delete this.metadata[r],delete this.inheritableMetadata[r]}copy(n=[],r=!0){const s=new ko(this._parentRunId);for(const a of this.handlers){const i=this.inheritableHandlers.includes(a);s.addHandler(a,i)}for(const a of this.tags){const i=this.inheritableTags.includes(a);s.addTags([a],i)}for(const a of Object.keys(this.metadata)){const i=Object.keys(this.inheritableMetadata).includes(a);s.addMetadata({[a]:this.metadata[a]},i)}for(const a of n)s.handlers.filter(i=>i.name==="console_callback_handler").some(i=>i.name===a.name)||s.addHandler(a,r);return s}static fromHandlers(n){class r extends za{constructor(){super();p(this,"name",rs());Object.assign(this,n)}}const s=new this;return s.addHandler(new r),s}static configure(n,r,s,a,i,o,c){return this._configureSync(n,r,s,a,i,o,c)}static _configureSync(n,r,s,a,i,o,c){var y;let u;(n||r)&&(Array.isArray(n)||!n?(u=new ko,u.setHandlers((n==null?void 0:n.map(lc))??[],!0)):u=n,u=u.copy(Array.isArray(r)?r.map(lc):r==null?void 0:r.handlers,!1));const l=It("LANGCHAIN_VERBOSE")==="true"||(c==null?void 0:c.verbose),d=xo.getTraceableRunTree(),f=(d==null?void 0:d.tracingEnabled)??JN();if((d==null?void 0:d.tracingEnabled)===!1&&u){const w=u.handlers.filter(g=>g.name==="langchain_tracer");for(const g of w)u.removeHandler(g)}const h=f||(It("LANGCHAIN_TRACING")??!1);if(l||h){if(u||(u=new ko),l&&!u.handlers.some(w=>w.name===xp.prototype.name)){const w=new xp;u.addHandler(w,!0)}if(h&&!u.handlers.some(w=>w.name==="langchain_tracer")&&f){const w=new xo;u.addHandler(w,!0)}f&&d&&u._parentRunId===void 0&&(u._parentRunId=d.id,(y=u.handlers.find(w=>w.name==="langchain_tracer"))==null||y.updateFromRunTree(d))}for(const{contextVar:w,inheritable:g=!0,handlerClass:b,envVar:S}of YN()){const I=S&&It(S)==="true"&&b;let T;const x=w!==void 0?XS(w):void 0;x&&wS(x)?T=x:I&&(T=new b({})),T!==void 0&&(u||(u=new ko),u.handlers.some(A=>A.name===T.name)||u.addHandler(T,g))}(s||a)&&u&&(u.addTags(s??[]),u.addTags(a??[],!1)),(i||o)&&u&&(u.addMetadata(i??{}),u.addMetadata(o??{},!1));const m=c==null?void 0:c.tracerInheritableMetadata,_=c==null?void 0:c.tracerInheritableTags;return u&&(m||_)&&(u.handlers=u.handlers.map(w=>w instanceof xo?w.copyWithTracingConfig({metadata:m,tags:_}):w),u.inheritableHandlers=u.inheritableHandlers.map(w=>w instanceof xo?w.copyWithTracingConfig({metadata:m,tags:_}):w)),u}};function lc(t){return"name"in t?t:za.fromMethods(t)}var nT=class{getStore(){}run(t,e){return e()}enterWith(t){}};const eP=new nT,bw=Symbol.for("lc:child_config");var tP=class{getInstance(){return uc()??eP}getRunnableConfig(){var t,e;return(e=(t=this.getInstance().getStore())==null?void 0:t.extra)==null?void 0:e[bw]}runWithConfig(t,e,n){var u;const r=un._configureSync(t==null?void 0:t.callbacks,void 0,t==null?void 0:t.tags,void 0,t==null?void 0:t.metadata),s=this.getInstance(),a=s.getStore(),i=r==null?void 0:r.getParentRunId(),o=(u=r==null?void 0:r.handlers)==null?void 0:u.find(l=>(l==null?void 0:l.name)==="langchain_tracer");let c;return o&&i?c=o.getRunTreeWithTracingConfig(i):n||(c=new xn({name:"<runnable_lambda>",tracingEnabled:!1})),c&&(c.extra={...c.extra,[bw]:t}),a!==void 0&&a[Yo]!==void 0&&(c===void 0&&(c={}),c[Yo]=a[Yo]),s.run(c,e)}initializeGlobalInstance(t){uc()===void 0&&ZN(t)}};const tn=new tP;var nP=ue({AsyncLocalStorageProviderSingleton:()=>tn,MockAsyncLocalStorage:()=>nT,_CONTEXT_VARIABLES_KEY:()=>Yo});const rP=new Set(["api_key"]),sP=new Set(["string","number","boolean"]);function aP(t){const e=t.configurable??{},n=t.metadata??{},r={};for(const[s,a]of Object.entries(e))!s.startsWith("__")&&!Object.prototype.hasOwnProperty.call(n,s)&&!rP.has(s)&&sP.has(typeof a)&&(r[s]=a);return Object.keys(r).length>0?r:void 0}async function Wn(t){return un._configureSync(t==null?void 0:t.callbacks,void 0,t==null?void 0:t.tags,void 0,t==null?void 0:t.metadata,void 0,{tracerInheritableMetadata:t?aP(t):void 0})}function sr(...t){const e={};for(const n of t.filter(r=>!!r))for(const r of Object.keys(n))if(r==="metadata")e[r]={...e[r],...n[r]};else if(r==="tags"){const s=e[r]??[];e[r]=[...new Set(s.concat(n[r]??[]))]}else if(r==="configurable")e[r]={...e[r],...n[r]};else if(r==="timeout")e.timeout===void 0?e.timeout=n.timeout:n.timeout!==void 0&&(e.timeout=Math.min(e.timeout,n.timeout));else if(r==="signal")e.signal===void 0?e.signal=n.signal:n.signal!==void 0&&("any"in AbortSignal?e.signal=AbortSignal.any([e.signal,n.signal]):e.signal=n.signal);else if(r==="callbacks"){const s=e.callbacks,a=n.callbacks;if(Array.isArray(a))if(!s)e.callbacks=a;else if(Array.isArray(s))e.callbacks=s.concat(a);else{const i=s.copy();for(const o of a)i.addHandler(lc(o),!0);e.callbacks=i}else if(a)if(!s)e.callbacks=a;else if(Array.isArray(s)){const i=a.copy();for(const o of s)i.addHandler(lc(o),!0);e.callbacks=i}else e.callbacks=new un(a._parentRunId,{handlers:s.handlers.concat(a.handlers),inheritableHandlers:s.inheritableHandlers.concat(a.inheritableHandlers),tags:Array.from(new Set(s.tags.concat(a.tags))),inheritableTags:Array.from(new Set(s.inheritableTags.concat(a.inheritableTags))),metadata:{...s.metadata,...a.metadata}})}else{const s=r;e[s]=n[s]??e[s]}return e}function Ge(t){var r;const e=tn.getRunnableConfig();let n={tags:[],metadata:{},recursionLimit:25,runId:void 0};if(e){const{runId:s,runName:a,...i}=e;n=Object.entries(i).reduce((o,[c,u])=>(u!==void 0&&(o[c]=u),o),n)}if(t&&(n=Object.entries(t).reduce((s,[a,i])=>(i!==void 0&&(s[a]=i),s),n)),n!=null&&n.configurable&&typeof n.configurable.model=="string"&&((r=n.metadata)==null?void 0:r.model)===void 0&&(n.metadata||(n.metadata={}),n.metadata.model=n.configurable.model),n.timeout!==void 0){if(n.timeout<=0)throw new Error("Timeout must be a positive number");const s=n.timeout,a=AbortSignal.timeout(s);n.metadata||(n.metadata={}),n.metadata.timeoutMs===void 0&&(n.metadata.timeoutMs=s),n.signal!==void 0?"any"in AbortSignal&&(n.signal=AbortSignal.any([n.signal,a])):n.signal=a,delete n.timeout}return n}function et(t={},{callbacks:e,maxConcurrency:n,recursionLimit:r,runName:s,configurable:a,runId:i}={}){const o=Ge(t);return e!==void 0&&(delete o.runName,o.callbacks=e),r!==void 0&&(o.recursionLimit=r),n!==void 0&&(o.maxConcurrency=n),s!==void 0&&(o.runName=s),a!==void 0&&(o.configurable={...o.configurable,...a}),i!==void 0&&delete o.runId,o}function _s(t){if(t)return{configurable:t.configurable,recursionLimit:t.recursionLimit,callbacks:t.callbacks,tags:t.tags,metadata:t.metadata,maxConcurrency:t.maxConcurrency,timeout:t.timeout,signal:t.signal,store:t.store}}async function Gr(t,e){if(e===void 0)return t;let n;return Promise.race([t.catch(r=>{if(!(e!=null&&e.aborted))throw r}),new Promise((r,s)=>{n=()=>{s(dc(e))},e.addEventListener("abort",n,{once:!0}),e.aborted&&s(dc(e))})]).finally(()=>e.removeEventListener("abort",n))}function dc(t){return(t==null?void 0:t.reason)instanceof Error?t.reason:typeof(t==null?void 0:t.reason)=="string"?new Error(t.reason):new Error("Aborted")}var iP=ue({AsyncGeneratorWithSetup:()=>Ha,IterableReadableStream:()=>$n,atee:()=>xg,concat:()=>ys,pipeGeneratorWithSetup:()=>rT}),$n=class Cp extends ReadableStream{constructor(){super(...arguments);p(this,"reader")}ensureReader(){this.reader||(this.reader=this.getReader())}async next(){this.ensureReader();try{const n=await this.reader.read();return n.done?(this.reader.releaseLock(),{done:!0,value:void 0}):{done:!1,value:n.value}}catch(n){throw this.reader.releaseLock(),n}}async return(){if(this.ensureReader(),this.locked){const n=this.reader.cancel();this.reader.releaseLock(),await n}return{done:!0,value:void 0}}async throw(n){if(this.ensureReader(),this.locked){const r=this.reader.cancel();this.reader.releaseLock(),await r}throw n}[Symbol.asyncIterator](){return this}async[Symbol.asyncDispose](){await this.return()}static fromReadableStream(n){const r=n.getReader();return new Cp({start(s){return a();function a(){return r.read().then(({done:i,value:o})=>{if(i){s.close();return}return s.enqueue(o),a()})}},cancel(){r.releaseLock()}})}static fromAsyncGenerator(n){return new Cp({async pull(r){const{value:s,done:a}=await n.next();a&&r.close(),r.enqueue(s)},async cancel(r){await n.return(r)}})}};function xg(t,e=2){const n=Array.from({length:e},()=>[]);return n.map(async function*(s){for(;;)if(s.length===0){const a=await t.next();for(const i of n)i.push(a)}else{if(s[0].done)return;yield s.shift().value}})}function ys(t,e){if(Array.isArray(t)&&Array.isArray(e))return t.concat(e);if(typeof t=="string"&&typeof e=="string")return t+e;if(typeof t=="number"&&typeof e=="number")return t+e;if("concat"in t&&typeof t.concat=="function")return t.concat(e);if(typeof t=="object"&&typeof e=="object"){const n={...t};for(const[r,s]of Object.entries(e))r in n&&!Array.isArray(n[r])?n[r]=ys(n[r],s):n[r]=s;return n}else throw new Error(`Cannot concat ${typeof t} and ${typeof e}`)}var Ha=class{constructor(t){p(this,"generator");p(this,"setup");p(this,"config");p(this,"signal");p(this,"firstResult");p(this,"firstResultUsed",!1);var e;this.generator=t.generator,this.config=t.config,this.signal=t.signal??((e=this.config)==null?void 0:e.signal),this.setup=new Promise((n,r)=>{tn.runWithConfig(_s(t.config),async()=>{this.firstResult=this.signal?Gr(t.generator.next(),this.signal):t.generator.next(),t.startSetup?this.firstResult.then(t.startSetup).then(n,r):this.firstResult.then(s=>n(void 0),r)},!0)})}async next(...t){var e;return(e=this.signal)==null||e.throwIfAborted(),this.firstResultUsed?tn.runWithConfig(_s(this.config),this.signal?async()=>Gr(this.generator.next(...t),this.signal):async()=>this.generator.next(...t),!0):(this.firstResultUsed=!0,this.firstResult)}async return(t){return this.generator.return(t)}async throw(t){return this.generator.throw(t)}[Symbol.asyncIterator](){return this}async[Symbol.asyncDispose](){await this.return()}};async function rT(t,e,n,r,...s){const a=new Ha({generator:e,startSetup:n,signal:r}),i=await a.setup;return{output:t(a,i,...s),setup:i}}/*!
58
- * https://github.com/Starcounter-Jack/JSON-Patch
59
- * (c) 2017-2022 Joachim Wester
60
- * MIT licensed
61
- */const oP=Object.prototype.hasOwnProperty;function Rp(t,e){return oP.call(t,e)}function $p(t){if(Array.isArray(t)){const n=new Array(t.length);for(let r=0;r<n.length;r++)n[r]=""+r;return n}if(Object.keys)return Object.keys(t);let e=[];for(let n in t)Rp(t,n)&&e.push(n);return e}function Tr(t){switch(typeof t){case"object":return JSON.parse(JSON.stringify(t));case"undefined":return null;default:return t}}function Np(t){let e=0;const n=t.length;let r;for(;e<n;){if(r=t.charCodeAt(e),r>=48&&r<=57){e++;continue}return!1}return!0}function Va(t){return t.indexOf("/")===-1&&t.indexOf("~")===-1?t:t.replace(/~/g,"~0").replace(/\//g,"~1")}function cP(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}function Pp(t){if(t===void 0)return!0;if(t){if(Array.isArray(t)){for(let n=0,r=t.length;n<r;n++)if(Pp(t[n]))return!0}else if(typeof t=="object"){const n=$p(t),r=n.length;for(var e=0;e<r;e++)if(Pp(t[n[e]]))return!0}}return!1}function vw(t,e){const n=[t];for(const r in e){const s=typeof e[r]=="object"?JSON.stringify(e[r],null,2):e[r];typeof s<"u"&&n.push(`${r}: ${s}`)}return n.join(`
62
- `)}var uP=class extends Error{constructor(t,e,n,r,s){super(vw(t,{name:e,index:n,operation:r,tree:s})),this.name=e,this.index=n,this.operation=r,this.tree=s,Object.setPrototypeOf(this,new.target.prototype),this.message=vw(t,{name:e,index:n,operation:r,tree:s})}},lP=ue({JsonPatchError:()=>vt,_areEquals:()=>hc,applyOperation:()=>Oa,applyPatch:()=>$i,applyReducer:()=>fP,deepClone:()=>dP,getValueByPointer:()=>ed,validate:()=>sT,validator:()=>td});const vt=uP,dP=Tr,pi={add:function(t,e,n){if(e==="__proto__"||e==="constructor")throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor` prop is banned for security reasons");return t[e]=this.value,{newDocument:n}},remove:function(t,e,n){if(e==="__proto__"||e==="constructor")throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor` prop is banned for security reasons");var r=t[e];return delete t[e],{newDocument:n,removed:r}},replace:function(t,e,n){if(e==="__proto__"||e==="constructor")throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor` prop is banned for security reasons");var r=t[e];return t[e]=this.value,{newDocument:n,removed:r}},move:function(t,e,n){let r=ed(n,this.path);r&&(r=Tr(r));const s=Oa(n,{op:"remove",path:this.from}).removed;return Oa(n,{op:"add",path:this.path,value:s}),{newDocument:n,removed:r}},copy:function(t,e,n){const r=ed(n,this.from);return Oa(n,{op:"add",path:this.path,value:Tr(r)}),{newDocument:n}},test:function(t,e,n){return{newDocument:n,test:hc(t[e],this.value)}},_get:function(t,e,n){return this.value=t[e],{newDocument:n}}};var hP={add:function(t,e,n){return Np(e)?t.splice(e,0,this.value):t[e]=this.value,{newDocument:n,index:e}},remove:function(t,e,n){return{newDocument:n,removed:t.splice(e,1)[0]}},replace:function(t,e,n){var r=t[e];return t[e]=this.value,{newDocument:n,removed:r}},move:pi.move,copy:pi.copy,test:pi.test,_get:pi._get};function ed(t,e){if(e=="")return t;var n={op:"_get",path:e};return Oa(t,n),n.value}function Oa(t,e,n=!1,r=!0,s=!0,a=0){if(n&&(typeof n=="function"?n(e,0,t,e.path):td(e,0)),e.path===""){let i={newDocument:t};if(e.op==="add")return i.newDocument=e.value,i;if(e.op==="replace")return i.newDocument=e.value,i.removed=t,i;if(e.op==="move"||e.op==="copy")return i.newDocument=ed(t,e.from),e.op==="move"&&(i.removed=t),i;if(e.op==="test"){if(i.test=hc(t,e.value),i.test===!1)throw new vt("Test operation failed","TEST_OPERATION_FAILED",a,e,t);return i.newDocument=t,i}else{if(e.op==="remove")return i.removed=t,i.newDocument=null,i;if(e.op==="_get")return e.value=t,i;if(n)throw new vt("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",a,e,t);return i}}else{r||(t=Tr(t));const i=(e.path||"").split("/");let o=t,c=1,u=i.length,l,d,f;for(typeof n=="function"?f=n:f=td;;){if(d=i[c],d&&d.indexOf("~")!=-1&&(d=cP(d)),s&&(d=="__proto__"||d=="prototype"&&c>0&&i[c-1]=="constructor"))throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(n&&l===void 0&&(o[d]===void 0?l=i.slice(0,c).join("/"):c==u-1&&(l=e.path),l!==void 0&&f(e,0,t,l)),c++,Array.isArray(o)){if(d==="-")d=o.length;else{if(n&&!Np(d))throw new vt("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",a,e,t);Np(d)&&(d=~~d)}if(c>=u){if(n&&e.op==="add"&&d>o.length)throw new vt("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",a,e,t);const h=hP[e.op].call(e,o,d,t);if(h.test===!1)throw new vt("Test operation failed","TEST_OPERATION_FAILED",a,e,t);return h}}else if(c>=u){const h=pi[e.op].call(e,o,d,t);if(h.test===!1)throw new vt("Test operation failed","TEST_OPERATION_FAILED",a,e,t);return h}if(o=o[d],n&&c<u&&(!o||typeof o!="object"))throw new vt("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",a,e,t)}}}function $i(t,e,n,r=!0,s=!0){if(n&&!Array.isArray(e))throw new vt("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");r||(t=Tr(t));const a=new Array(e.length);for(let i=0,o=e.length;i<o;i++)a[i]=Oa(t,e[i],n,!0,s,i),t=a[i].newDocument;return a.newDocument=t,a}function fP(t,e,n){const r=Oa(t,e);if(r.test===!1)throw new vt("Test operation failed","TEST_OPERATION_FAILED",n,e,t);return r.newDocument}function td(t,e,n,r){if(typeof t!="object"||t===null||Array.isArray(t))throw new vt("Operation is not an object","OPERATION_NOT_AN_OBJECT",e,t,n);if(pi[t.op]){if(typeof t.path!="string")throw new vt("Operation `path` property is not a string","OPERATION_PATH_INVALID",e,t,n);if(t.path.indexOf("/")!==0&&t.path.length>0)throw new vt('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",e,t,n);if((t.op==="move"||t.op==="copy")&&typeof t.from!="string")throw new vt("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",e,t,n);if((t.op==="add"||t.op==="replace"||t.op==="test")&&t.value===void 0)throw new vt("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",e,t,n);if((t.op==="add"||t.op==="replace"||t.op==="test")&&Pp(t.value))throw new vt("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",e,t,n);if(n){if(t.op=="add"){var s=t.path.split("/").length,a=r.split("/").length;if(s!==a+1&&s!==a)throw new vt("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",e,t,n)}else if(t.op==="replace"||t.op==="remove"||t.op==="_get"){if(t.path!==r)throw new vt("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",e,t,n)}else if(t.op==="move"||t.op==="copy"){var i=sT([{op:"_get",path:t.from,value:void 0}],n);if(i&&i.name==="OPERATION_PATH_UNRESOLVABLE")throw new vt("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",e,t,n)}}}else throw new vt("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",e,t,n)}function sT(t,e,n){try{if(!Array.isArray(t))throw new vt("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(e)$i(Tr(e),Tr(t),n||!0);else{n=n||td;for(var r=0;r<t.length;r++)n(t[r],r,e,void 0)}}catch(s){if(s instanceof vt)return s;throw s}}function hc(t,e){if(t===e)return!0;if(t&&e&&typeof t=="object"&&typeof e=="object"){var n=Array.isArray(t),r=Array.isArray(e),s,a,i;if(n&&r){if(a=t.length,a!=e.length)return!1;for(s=a;s--!==0;)if(!hc(t[s],e[s]))return!1;return!0}if(n!=r)return!1;var o=Object.keys(t);if(a=o.length,a!==Object.keys(e).length)return!1;for(s=a;s--!==0;)if(!e.hasOwnProperty(o[s]))return!1;for(s=a;s--!==0;)if(i=o[s],!hc(t[i],e[i]))return!1;return!0}return t!==t&&e!==e}/*!
63
- * https://github.com/Starcounter-Jack/JSON-Patch
64
- * (c) 2013-2021 Joachim Wester
65
- * MIT license
66
- */function aT(t,e,n,r,s){if(e!==t){typeof e.toJSON=="function"&&(e=e.toJSON());for(var a=$p(e),i=$p(t),o=!1,c=i.length-1;c>=0;c--){var u=i[c],l=t[u];if(Rp(e,u)&&!(e[u]===void 0&&l!==void 0&&Array.isArray(e)===!1)){var d=e[u];typeof l=="object"&&l!=null&&typeof d=="object"&&d!=null&&Array.isArray(l)===Array.isArray(d)?aT(l,d,n,r+"/"+Va(u),s):l!==d&&(s&&n.push({op:"test",path:r+"/"+Va(u),value:Tr(l)}),n.push({op:"replace",path:r+"/"+Va(u),value:Tr(d)}))}else Array.isArray(t)===Array.isArray(e)?(s&&n.push({op:"test",path:r+"/"+Va(u),value:Tr(l)}),n.push({op:"remove",path:r+"/"+Va(u)}),o=!0):(s&&n.push({op:"test",path:r,value:t}),n.push({op:"replace",path:r,value:e}))}if(!(!o&&a.length==i.length))for(var c=0;c<a.length;c++){var u=a[c];!Rp(t,u)&&e[u]!==void 0&&n.push({op:"add",path:r+"/"+Va(u),value:Tr(e[u])})}}}function Gd(t,e,n=!1){var r=[];return aT(t,e,r,"",n),r}({...lP});var pP=ue({LogStreamCallbackHandler:()=>Lp,RunLog:()=>kg,RunLogPatch:()=>as,isLogStreamHandler:()=>iT}),as=class{constructor(t){p(this,"ops");this.ops=t.ops??[]}concat(t){const e=this.ops.concat(t.ops),n=$i({},e);return new kg({ops:e,state:n[n.length-1].newDocument})}},kg=class Mp extends as{constructor(n){super(n);p(this,"state");this.state=n.state}concat(n){const r=this.ops.concat(n.ops),s=$i(this.state,n.ops);return new Mp({ops:r,state:s[s.length-1].newDocument})}static fromRunLogPatch(n){const r=$i({},n.ops);return new Mp({ops:n.ops,state:r[r.length-1].newDocument})}};const iT=t=>t.name==="log_stream_tracer";async function Sw(t,e){if(e==="original")throw new Error("Do not assign inputs with original schema drop the key for now. When inputs are added to streamLog they should be added with standardized schema for streaming events.");const{inputs:n}=t;if(["retriever","llm","prompt"].includes(t.run_type))return n;if(!(Object.keys(n).length===1&&(n==null?void 0:n.input)===""))return n.input}async function Tw(t,e){const{outputs:n}=t;return e==="original"||["retriever","llm","prompt"].includes(t.run_type)?n:n!==void 0&&Object.keys(n).length===1&&(n==null?void 0:n.output)!==void 0?n.output:n}function mP(t){return t!==void 0&&t.message!==void 0}var Lp=class extends Ss{constructor(e){super({_awaitHandler:!0,...e});p(this,"autoClose",!0);p(this,"includeNames");p(this,"includeTypes");p(this,"includeTags");p(this,"excludeNames");p(this,"excludeTypes");p(this,"excludeTags");p(this,"_schemaFormat","original");p(this,"rootId");p(this,"keyMapByRunId",{});p(this,"counterMapByRunName",{});p(this,"transformStream");p(this,"writer");p(this,"receiveStream");p(this,"name","log_stream_tracer");p(this,"lc_prefer_streaming",!0);this.autoClose=(e==null?void 0:e.autoClose)??!0,this.includeNames=e==null?void 0:e.includeNames,this.includeTypes=e==null?void 0:e.includeTypes,this.includeTags=e==null?void 0:e.includeTags,this.excludeNames=e==null?void 0:e.excludeNames,this.excludeTypes=e==null?void 0:e.excludeTypes,this.excludeTags=e==null?void 0:e.excludeTags,this._schemaFormat=(e==null?void 0:e._schemaFormat)??this._schemaFormat,this.transformStream=new TransformStream,this.writer=this.transformStream.writable.getWriter(),this.receiveStream=$n.fromReadableStream(this.transformStream.readable)}[Symbol.asyncIterator](){return this.receiveStream}async persistRun(e){}_includeRun(e){if(e.id===this.rootId)return!1;const n=e.tags??[];let r=this.includeNames===void 0&&this.includeTags===void 0&&this.includeTypes===void 0;return this.includeNames!==void 0&&(r=r||this.includeNames.includes(e.name)),this.includeTypes!==void 0&&(r=r||this.includeTypes.includes(e.run_type)),this.includeTags!==void 0&&(r=r||n.find(s=>{var a;return(a=this.includeTags)==null?void 0:a.includes(s)})!==void 0),this.excludeNames!==void 0&&(r=r&&!this.excludeNames.includes(e.name)),this.excludeTypes!==void 0&&(r=r&&!this.excludeTypes.includes(e.run_type)),this.excludeTags!==void 0&&(r=r&&n.every(s=>{var a;return!((a=this.excludeTags)!=null&&a.includes(s))})),r}async*tapOutputIterable(e,n){for await(const r of n){if(e!==this.rootId){const s=this.keyMapByRunId[e];s&&await this.writer.write(new as({ops:[{op:"add",path:`/logs/${s}/streamed_output/-`,value:r}]}))}yield r}}async onRunCreate(e){var s;if(this.rootId===void 0&&(this.rootId=e.id,await this.writer.write(new as({ops:[{op:"replace",path:"",value:{id:e.id,name:e.name,type:e.run_type,streamed_output:[],final_output:void 0,logs:{}}}]}))),!this._includeRun(e))return;this.counterMapByRunName[e.name]===void 0&&(this.counterMapByRunName[e.name]=0),this.counterMapByRunName[e.name]+=1;const n=this.counterMapByRunName[e.name];this.keyMapByRunId[e.id]=n===1?e.name:`${e.name}:${n}`;const r={id:e.id,name:e.name,type:e.run_type,tags:e.tags??[],metadata:((s=e.extra)==null?void 0:s.metadata)??{},start_time:new Date(e.start_time).toISOString(),streamed_output:[],streamed_output_str:[],final_output:void 0,end_time:void 0};this._schemaFormat==="streaming_events"&&(r.inputs=await Sw(e,this._schemaFormat)),await this.writer.write(new as({ops:[{op:"add",path:`/logs/${this.keyMapByRunId[e.id]}`,value:r}]}))}async onRunUpdate(e){try{const n=this.keyMapByRunId[e.id];if(n===void 0)return;const r=[];this._schemaFormat==="streaming_events"&&r.push({op:"replace",path:`/logs/${n}/inputs`,value:await Sw(e,this._schemaFormat)}),r.push({op:"add",path:`/logs/${n}/final_output`,value:await Tw(e,this._schemaFormat)}),e.end_time!==void 0&&r.push({op:"add",path:`/logs/${n}/end_time`,value:new Date(e.end_time).toISOString()});const s=new as({ops:r});await this.writer.write(s)}finally{if(e.id===this.rootId){const n=new as({ops:[{op:"replace",path:"/final_output",value:await Tw(e,this._schemaFormat)}]});await this.writer.write(n),this.autoClose&&await this.writer.close()}}}async onLLMNewToken(e,n,r){const s=this.keyMapByRunId[e.id];if(s===void 0)return;const a=e.inputs.messages!==void 0;let i;a?mP(r==null?void 0:r.chunk)?i=r==null?void 0:r.chunk:i=new Qe({id:`run-${e.id}`,content:n}):i=n;const o=new as({ops:[{op:"add",path:`/logs/${s}/streamed_output_str/-`,value:n},{op:"add",path:`/logs/${s}/streamed_output/-`,value:i}]});await this.writer.write(o)}},gP=ue({ChatGenerationChunk:()=>qn,GenerationChunk:()=>Ni,RUN_KEY:()=>fc});const fc="__run";var Ni=class oT{constructor(e){p(this,"text");p(this,"generationInfo");this.text=e.text,this.generationInfo=e.generationInfo}concat(e){return new oT({text:this.text+e.text,generationInfo:{...this.generationInfo,...e.generationInfo}})}},qn=class cT extends Ni{constructor(n){super(n);p(this,"message");this.message=n.message}concat(n){return new cT({text:this.text+n.text,generationInfo:{...this.generationInfo,...n.generationInfo},message:this.message.concat(n.message)})}};function bu({name:t,serialized:e}){return t!==void 0?t:(e==null?void 0:e.name)!==void 0?e.name:(e==null?void 0:e.id)!==void 0&&Array.isArray(e==null?void 0:e.id)?e.id[e.id.length-1]:"Unnamed"}const _P=t=>t.name==="event_stream_tracer";var yP=class extends Ss{constructor(e){super({_awaitHandler:!0,...e});p(this,"autoClose",!0);p(this,"includeNames");p(this,"includeTypes");p(this,"includeTags");p(this,"excludeNames");p(this,"excludeTypes");p(this,"excludeTags");p(this,"runInfoMap",new Map);p(this,"tappedPromises",new Map);p(this,"transformStream");p(this,"writer");p(this,"receiveStream");p(this,"readableStreamClosed",!1);p(this,"name","event_stream_tracer");p(this,"lc_prefer_streaming",!0);this.autoClose=(e==null?void 0:e.autoClose)??!0,this.includeNames=e==null?void 0:e.includeNames,this.includeTypes=e==null?void 0:e.includeTypes,this.includeTags=e==null?void 0:e.includeTags,this.excludeNames=e==null?void 0:e.excludeNames,this.excludeTypes=e==null?void 0:e.excludeTypes,this.excludeTags=e==null?void 0:e.excludeTags,this.transformStream=new TransformStream({flush:()=>{this.readableStreamClosed=!0}}),this.writer=this.transformStream.writable.getWriter(),this.receiveStream=$n.fromReadableStream(this.transformStream.readable)}[Symbol.asyncIterator](){return this.receiveStream}async persistRun(e){}_includeRun(e){const n=e.tags??[];let r=this.includeNames===void 0&&this.includeTags===void 0&&this.includeTypes===void 0;return this.includeNames!==void 0&&(r=r||this.includeNames.includes(e.name)),this.includeTypes!==void 0&&(r=r||this.includeTypes.includes(e.runType)),this.includeTags!==void 0&&(r=r||n.find(s=>{var a;return(a=this.includeTags)==null?void 0:a.includes(s)})!==void 0),this.excludeNames!==void 0&&(r=r&&!this.excludeNames.includes(e.name)),this.excludeTypes!==void 0&&(r=r&&!this.excludeTypes.includes(e.runType)),this.excludeTags!==void 0&&(r=r&&n.every(s=>{var a;return!((a=this.excludeTags)!=null&&a.includes(s))})),r}async*tapOutputIterable(e,n){const r=await n.next();if(r.done)return;const s=this.runInfoMap.get(e);if(s===void 0){yield r.value;return}function a(o,c){return o==="llm"&&typeof c=="string"?new Ni({text:c}):c}let i=this.tappedPromises.get(e);if(i===void 0){let o;i=new Promise(c=>{o=c}),this.tappedPromises.set(e,i);try{const c={event:`on_${s.runType}_stream`,run_id:e,name:s.name,tags:s.tags,metadata:s.metadata,data:{}};await this.send({...c,data:{chunk:a(s.runType,r.value)}},s),yield r.value;for await(const u of n)s.runType!=="tool"&&s.runType!=="retriever"&&await this.send({...c,data:{chunk:a(s.runType,u)}},s),yield u}finally{o==null||o()}}else{yield r.value;for await(const o of n)yield o}}async send(e,n){this.readableStreamClosed||this._includeRun(n)&&await this.writer.write(e)}async sendEndEvent(e,n){const r=this.tappedPromises.get(e.run_id);r!==void 0?r.then(()=>{this.send(e,n)}):await this.send(e,n)}async onLLMStart(e){var i,o;const n=bu(e),r=e.inputs.messages!==void 0?"chat_model":"llm",s={tags:e.tags??[],metadata:((i=e.extra)==null?void 0:i.metadata)??{},name:n,runType:r,inputs:e.inputs};this.runInfoMap.set(e.id,s);const a=`on_${r}_start`;await this.send({event:a,data:{input:e.inputs},name:n,tags:e.tags??[],run_id:e.id,metadata:((o=e.extra)==null?void 0:o.metadata)??{}},s)}async onLLMNewToken(e,n,r){const s=this.runInfoMap.get(e.id);let a,i;if(s===void 0)throw new Error(`onLLMNewToken: Run ID ${e.id} not found in run map.`);if(this.runInfoMap.size!==1){if(s.runType==="chat_model")i="on_chat_model_stream",(r==null?void 0:r.chunk)===void 0?a=new Qe({content:n,id:`run-${e.id}`}):a=r.chunk.message;else if(s.runType==="llm")i="on_llm_stream",(r==null?void 0:r.chunk)===void 0?a=new Ni({text:n}):a=r.chunk;else throw new Error(`Unexpected run type ${s.runType}`);await this.send({event:i,data:{chunk:a},run_id:e.id,name:s.name,tags:s.tags,metadata:s.metadata},s)}}async onLLMEnd(e){var i,o,c;const n=this.runInfoMap.get(e.id);this.runInfoMap.delete(e.id);let r;if(n===void 0)throw new Error(`onLLMEnd: Run ID ${e.id} not found in run map.`);const s=(i=e.outputs)==null?void 0:i.generations;let a;if(n.runType==="chat_model"){for(const u of s??[]){if(a!==void 0)break;a=(o=u[0])==null?void 0:o.message}r="on_chat_model_end"}else if(n.runType==="llm")a={generations:s==null?void 0:s.map(u=>u.map(l=>({text:l.text,generationInfo:l.generationInfo}))),llmOutput:((c=e.outputs)==null?void 0:c.llmOutput)??{}},r="on_llm_end";else throw new Error(`onLLMEnd: Unexpected run type: ${n.runType}`);await this.sendEndEvent({event:r,data:{output:a,input:n.inputs},run_id:e.id,name:n.name,tags:n.tags,metadata:n.metadata},n)}async onChainStart(e){var i,o;const n=bu(e),r=e.run_type??"chain",s={tags:e.tags??[],metadata:((i=e.extra)==null?void 0:i.metadata)??{},name:n,runType:e.run_type};let a={};e.inputs.input===""&&Object.keys(e.inputs).length===1?(a={},s.inputs={}):e.inputs.input!==void 0?(a.input=e.inputs.input,s.inputs=e.inputs.input):(a.input=e.inputs,s.inputs=e.inputs),this.runInfoMap.set(e.id,s),await this.send({event:`on_${r}_start`,data:a,name:n,tags:e.tags??[],run_id:e.id,metadata:((o=e.extra)==null?void 0:o.metadata)??{}},s)}async onChainEnd(e){var i;const n=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),n===void 0)throw new Error(`onChainEnd: Run ID ${e.id} not found in run map.`);const r=`on_${e.run_type}_end`,s=e.inputs??n.inputs??{},a={output:((i=e.outputs)==null?void 0:i.output)??e.outputs,input:s};s.input&&Object.keys(s).length===1&&(a.input=s.input,n.inputs=s.input),await this.sendEndEvent({event:r,data:a,run_id:e.id,name:n.name,tags:n.tags,metadata:n.metadata??{}},n)}async onToolStart(e){var s,a;const n=bu(e),r={tags:e.tags??[],metadata:((s=e.extra)==null?void 0:s.metadata)??{},name:n,runType:"tool",inputs:e.inputs??{}};this.runInfoMap.set(e.id,r),await this.send({event:"on_tool_start",data:{input:e.inputs??{}},name:n,run_id:e.id,tags:e.tags??[],metadata:((a=e.extra)==null?void 0:a.metadata)??{}},r)}async onToolEnd(e){var s;const n=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),n===void 0)throw new Error(`onToolEnd: Run ID ${e.id} not found in run map.`);if(n.inputs===void 0)throw new Error(`onToolEnd: Run ID ${e.id} is a tool call, and is expected to have traced inputs.`);const r=((s=e.outputs)==null?void 0:s.output)===void 0?e.outputs:e.outputs.output;await this.sendEndEvent({event:"on_tool_end",data:{output:r,input:n.inputs},run_id:e.id,name:n.name,tags:n.tags,metadata:n.metadata},n)}async onToolError(e){const n=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),n===void 0)throw new Error(`onToolEnd: Run ID ${e.id} not found in run map.`);if(n.inputs===void 0)throw new Error(`onToolEnd: Run ID ${e.id} is a tool call, and is expected to have traced inputs.`);await this.sendEndEvent({event:"on_tool_error",data:{input:n.inputs,error:e.error},run_id:e.id,name:n.name,tags:n.tags,metadata:n.metadata},n)}async onRetrieverStart(e){var s,a;const n=bu(e),r={tags:e.tags??[],metadata:((s=e.extra)==null?void 0:s.metadata)??{},name:n,runType:"retriever",inputs:{query:e.inputs.query}};this.runInfoMap.set(e.id,r),await this.send({event:"on_retriever_start",data:{input:{query:e.inputs.query}},name:n,tags:e.tags??[],run_id:e.id,metadata:((a=e.extra)==null?void 0:a.metadata)??{}},r)}async onRetrieverEnd(e){var r;const n=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),n===void 0)throw new Error(`onRetrieverEnd: Run ID ${e.id} not found in run map.`);await this.sendEndEvent({event:"on_retriever_end",data:{output:((r=e.outputs)==null?void 0:r.documents)??e.outputs,input:n.inputs},run_id:e.id,name:n.name,tags:n.tags,metadata:n.metadata},n)}async handleCustomEvent(e,n,r){const s=this.runInfoMap.get(r);if(s===void 0)throw new Error(`handleCustomEvent: Run ID ${r} not found in run map.`);await this.send({event:"on_custom_event",run_id:r,name:e,tags:s.tags,metadata:s.metadata,data:n},s)}async finish(){const e=[...this.tappedPromises.values()];Promise.all(e).finally(()=>{this.writer.close()})}};const wP=Object.prototype.toString,bP=t=>wP.call(t)==="[object Error]",vP=new Set(["network error","Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed","fetch failed","terminated"," A network error occurred.","Network connection lost"]);function SP(t){if(!(t&&bP(t)&&t.name==="TypeError"&&typeof t.message=="string"))return!1;const{message:e,stack:n}=t;return e==="Load failed"?n===void 0||"__sentry_captured__"in t:e.startsWith("error sending request for url")?!0:vP.has(e)}function TP(t){if(typeof t=="number"){if(t<0)throw new TypeError("Expected `retries` to be a non-negative number.");if(Number.isNaN(t))throw new TypeError("Expected `retries` to be a valid number or Infinity, got NaN.")}else if(t!==void 0)throw new TypeError("Expected `retries` to be a number or Infinity.")}function vu(t,e,{min:n=0,allowInfinity:r=!1}={}){if(e!==void 0){if(typeof e!="number"||Number.isNaN(e))throw new TypeError(`Expected \`${t}\` to be a number${r?" or Infinity":""}.`);if(!r&&!Number.isFinite(e))throw new TypeError(`Expected \`${t}\` to be a finite number.`);if(e<n)throw new TypeError(`Expected \`${t}\` to be ≥ ${n}.`)}}var EP=class extends Error{constructor(t){super(),t instanceof Error?(this.originalError=t,{message:t}=t):(this.originalError=new Error(t),this.originalError.stack=this.stack),this.name="AbortError",this.message=t}};function AP(t,e){const n=Math.max(1,t+1),r=e.randomize?Math.random()+1:1;let s=Math.round(r*e.minTimeout*e.factor**(n-1));return s=Math.min(s,e.maxTimeout),s}function Ew(t,e){return Number.isFinite(e)?e-(performance.now()-t):e}async function IP({error:t,attemptNumber:e,retriesConsumed:n,startTime:r,options:s}){var h,m,_;const a=t instanceof Error?t:new TypeError(`Non-error was thrown: "${t}". You should only throw errors.`);if(a instanceof EP)throw a.originalError;const i=Number.isFinite(s.retries)?Math.max(0,s.retries-n):s.retries,o=s.maxRetryTime??Number.POSITIVE_INFINITY,c=Object.freeze({error:a,attemptNumber:e,retriesLeft:i,retriesConsumed:n});if(await s.onFailedAttempt(c),Ew(r,o)<=0)throw a;const u=await s.shouldConsumeRetry(c),l=Ew(r,o);if(l<=0||i<=0)throw a;if(a instanceof TypeError&&!SP(a)){if(u)throw a;return(h=s.signal)==null||h.throwIfAborted(),!1}if(!await s.shouldRetry(c))throw a;if(!u)return(m=s.signal)==null||m.throwIfAborted(),!1;const d=AP(n,s),f=Math.min(d,l);return f>0&&await new Promise((y,w)=>{var S,I;const g=()=>{var T;clearTimeout(b),(T=s.signal)==null||T.removeEventListener("abort",g),w(s.signal.reason)},b=setTimeout(()=>{var T;(T=s.signal)==null||T.removeEventListener("abort",g),y()},f);s.unref&&((S=b.unref)==null||S.call(b)),(I=s.signal)==null||I.addEventListener("abort",g,{once:!0})}),(_=s.signal)==null||_.throwIfAborted(),!0}async function jp(t,e={}){var a,i,o;if(e={...e},TP(e.retries),Object.hasOwn(e,"forever"))throw new Error("The `forever` option is no longer supported. For many use-cases, you can set `retries: Infinity` instead.");e.retries??(e.retries=10),e.factor??(e.factor=2),e.minTimeout??(e.minTimeout=1e3),e.maxTimeout??(e.maxTimeout=Number.POSITIVE_INFINITY),e.maxRetryTime??(e.maxRetryTime=Number.POSITIVE_INFINITY),e.randomize??(e.randomize=!1),e.onFailedAttempt??(e.onFailedAttempt=()=>{}),e.shouldRetry??(e.shouldRetry=()=>!0),e.shouldConsumeRetry??(e.shouldConsumeRetry=()=>!0),vu("factor",e.factor,{min:0,allowInfinity:!1}),vu("minTimeout",e.minTimeout,{min:0,allowInfinity:!1}),vu("maxTimeout",e.maxTimeout,{min:0,allowInfinity:!0}),vu("maxRetryTime",e.maxRetryTime,{min:0,allowInfinity:!0}),e.factor>0||(e.factor=1),(a=e.signal)==null||a.throwIfAborted();let n=0,r=0;const s=performance.now();for(;!Number.isFinite(e.retries)||r<=e.retries;){n++;try{(i=e.signal)==null||i.throwIfAborted();const c=await t(n);return(o=e.signal)==null||o.throwIfAborted(),c}catch(c){await IP({error:c,attemptNumber:n,retriesConsumed:r,startTime:s,options:e})&&r++}}throw new Error("Retry attempts exhausted without throwing an error.")}var xP=ue({AsyncCaller:()=>Wc});const kP=[400,401,402,403,404,405,406,407,409],OP=t=>{if(typeof t!="object"||t===null)return;if("message"in t&&typeof t.message=="string"&&(t.message.startsWith("Cancel")||t.message.startsWith("AbortError"))||"name"in t&&typeof t.name=="string"&&t.name==="AbortError"||"code"in t&&typeof t.code=="string"&&t.code==="ECONNABORTED")throw t;const e="response"in t&&typeof t.response=="object"&&t.response!==null&&"status"in t.response&&typeof t.response.status=="number"?t.response.status:void 0,n="status"in t&&typeof t.status=="number"?t.status:void 0,r=e??n;if(r&&kP.includes(+r))throw t;if(("error"in t&&typeof t.error=="object"&&t.error!==null&&"code"in t.error&&typeof t.error.code=="string"?t.error.code:void 0)==="insufficient_quota"){const s=new Error("message"in t&&typeof t.message=="string"?t.message:"Insufficient quota");throw s.name="InsufficientQuotaError",s}};var Wc=class{constructor(t){p(this,"maxConcurrency");p(this,"maxRetries");p(this,"onFailedAttempt");p(this,"queue");this.maxConcurrency=t.maxConcurrency??1/0,this.maxRetries=t.maxRetries??6,this.onFailedAttempt=t.onFailedAttempt??OP,this.queue=new("default"in ms?ms.default:ms)({concurrency:this.maxConcurrency})}async call(t,...e){return this.queue.add(()=>jp(()=>t(...e).catch(n=>{throw n instanceof Error?n:new Error(n)}),{onFailedAttempt:({error:n})=>{var r;return(r=this.onFailedAttempt)==null?void 0:r.call(this,n)},retries:this.maxRetries,randomize:!0}),{throwOnTimeout:!0})}callWithOptions(t,e,...n){if(t.signal){let r;return Promise.race([this.call(e,...n),new Promise((s,a)=>{var i;r=()=>{a(dc(t.signal))},(i=t.signal)==null||i.addEventListener("abort",r,{once:!0})})]).finally(()=>{t.signal&&r&&t.signal.removeEventListener("abort",r)})}return this.call(e,...n)}fetch(...t){return this.call(()=>fetch(...t).then(e=>e.ok?e:Promise.reject(e)))}},uT=class extends Ss{constructor({config:e,onStart:n,onEnd:r,onError:s}){super({_awaitHandler:!0});p(this,"name","RootListenersTracer");p(this,"rootId");p(this,"config");p(this,"argOnStart");p(this,"argOnEnd");p(this,"argOnError");this.config=e,this.argOnStart=n,this.argOnEnd=r,this.argOnError=s}persistRun(e){return Promise.resolve()}async onRunCreate(e){this.rootId||(this.rootId=e.id,this.argOnStart&&await this.argOnStart(e,this.config))}async onRunUpdate(e){e.id===this.rootId&&(e.error?this.argOnError&&await this.argOnError(e,this.config):this.argOnEnd&&await this.argOnEnd(e,this.config))}};function Og(t){return t?t.lc_runnable:!1}var CP=class{constructor(t){p(this,"includeNames");p(this,"includeTypes");p(this,"includeTags");p(this,"excludeNames");p(this,"excludeTypes");p(this,"excludeTags");this.includeNames=t.includeNames,this.includeTypes=t.includeTypes,this.includeTags=t.includeTags,this.excludeNames=t.excludeNames,this.excludeTypes=t.excludeTypes,this.excludeTags=t.excludeTags}includeEvent(t,e){let n=this.includeNames===void 0&&this.includeTypes===void 0&&this.includeTags===void 0;const r=t.tags??[];return this.includeNames!==void 0&&(n=n||this.includeNames.includes(t.name)),this.includeTypes!==void 0&&(n=n||this.includeTypes.includes(e)),this.includeTags!==void 0&&(n=n||r.some(s=>{var a;return(a=this.includeTags)==null?void 0:a.includes(s)})),this.excludeNames!==void 0&&(n=n&&!this.excludeNames.includes(t.name)),this.excludeTypes!==void 0&&(n=n&&!this.excludeTypes.includes(e)),this.excludeTags!==void 0&&(n=n&&r.every(s=>{var a;return!((a=this.excludeTags)!=null&&a.includes(s))})),n}};const RP=t=>btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"");function U(t,e,n){function r(o,c){var u;Object.defineProperty(o,"_zod",{value:o._zod??{},enumerable:!1}),(u=o._zod).traits??(u.traits=new Set),o._zod.traits.add(t),e(o,c);for(const l in i.prototype)l in o||Object.defineProperty(o,l,{value:i.prototype[l].bind(o)});o._zod.constr=i,o._zod.def=c}const s=(n==null?void 0:n.Parent)??Object;class a extends s{}Object.defineProperty(a,"name",{value:t});function i(o){var c;const u=n!=null&&n.Parent?new a:this;r(u,o),(c=u._zod).deferred??(c.deferred=[]);for(const l of u._zod.deferred)l();return u}return Object.defineProperty(i,"init",{value:r}),Object.defineProperty(i,Symbol.hasInstance,{value:o=>{var c,u;return n!=null&&n.Parent&&o instanceof n.Parent?!0:(u=(c=o==null?void 0:o._zod)==null?void 0:c.traits)==null?void 0:u.has(t)}}),Object.defineProperty(i,"name",{value:t}),i}class pc extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}const lT={};function Js(t){return lT}function dT(t){const e=Object.values(t).filter(r=>typeof r=="number");return Object.entries(t).filter(([r,s])=>e.indexOf(+r)===-1).map(([r,s])=>s)}function $P(t,e){return typeof e=="bigint"?e.toString():e}function Cg(t){return{get value(){{const e=t();return Object.defineProperty(this,"value",{value:e}),e}}}}function Rg(t){return t==null}function $g(t){const e=t.startsWith("^")?1:0,n=t.endsWith("$")?t.length-1:t.length;return t.slice(e,n)}function NP(t,e){const n=(t.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,s=n>r?n:r,a=Number.parseInt(t.toFixed(s).replace(".","")),i=Number.parseInt(e.toFixed(s).replace(".",""));return a%i/10**s}function ft(t,e,n){Object.defineProperty(t,e,{get(){{const r=n();return t[e]=r,r}},set(r){Object.defineProperty(t,e,{value:r})},configurable:!0})}function Ng(t,e,n){Object.defineProperty(t,e,{value:n,writable:!0,enumerable:!0,configurable:!0})}function so(t){return JSON.stringify(t)}const hT=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};function nd(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}const PP=Cg(()=>{var t;if(typeof navigator<"u"&&((t=navigator==null?void 0:navigator.userAgent)!=null&&t.includes("Cloudflare")))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function rd(t){if(nd(t)===!1)return!1;const e=t.constructor;if(e===void 0)return!0;const n=e.prototype;return!(nd(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}const MP=new Set(["string","number","symbol"]);function Gc(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function cn(t,e,n){const r=new t._zod.constr(e??t._zod.def);return(!e||n!=null&&n.parent)&&(r._zod.parent=t),r}function ye(t){const e=t;if(!e)return{};if(typeof e=="string")return{error:()=>e};if((e==null?void 0:e.message)!==void 0){if((e==null?void 0:e.error)!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function LP(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}const jP={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function UP(t,e){const n={},r=t._zod.def;for(const s in e){if(!(s in r.shape))throw new Error(`Unrecognized key: "${s}"`);e[s]&&(n[s]=r.shape[s])}return cn(t,{...t._zod.def,shape:n,checks:[]})}function DP(t,e){const n={...t._zod.def.shape},r=t._zod.def;for(const s in e){if(!(s in r.shape))throw new Error(`Unrecognized key: "${s}"`);e[s]&&delete n[s]}return cn(t,{...t._zod.def,shape:n,checks:[]})}function fT(t,e){if(!rd(e))throw new Error("Invalid input to extend: expected a plain object");const n={...t._zod.def,get shape(){const r={...t._zod.def.shape,...e};return Ng(this,"shape",r),r},checks:[]};return cn(t,n)}function FP(t,e){return cn(t,{...t._zod.def,get shape(){const n={...t._zod.def.shape,...e._zod.def.shape};return Ng(this,"shape",n),n},catchall:e._zod.def.catchall,checks:[]})}function pT(t,e,n){const r=e._zod.def.shape,s={...r};if(n)for(const a in n){if(!(a in r))throw new Error(`Unrecognized key: "${a}"`);n[a]&&(s[a]=t?new t({type:"optional",innerType:r[a]}):r[a])}else for(const a in r)s[a]=t?new t({type:"optional",innerType:r[a]}):r[a];return cn(e,{...e._zod.def,shape:s,checks:[]})}function BP(t,e,n){const r=e._zod.def.shape,s={...r};if(n)for(const a in n){if(!(a in s))throw new Error(`Unrecognized key: "${a}"`);n[a]&&(s[a]=new t({type:"nonoptional",innerType:r[a]}))}else for(const a in r)s[a]=new t({type:"nonoptional",innerType:r[a]});return cn(e,{...e._zod.def,shape:s,checks:[]})}function Qo(t,e=0){var n;for(let r=e;r<t.issues.length;r++)if(((n=t.issues[r])==null?void 0:n.continue)!==!0)return!0;return!1}function Ls(t,e){return e.map(n=>{var r;return(r=n).path??(r.path=[]),n.path.unshift(t),n})}function Su(t){return typeof t=="string"?t:t==null?void 0:t.message}function Xs(t,e,n){var s,a,i,o,c,u;const r={...t,path:t.path??[]};if(!t.message){const l=Su((i=(a=(s=t.inst)==null?void 0:s._zod.def)==null?void 0:a.error)==null?void 0:i.call(a,t))??Su((o=e==null?void 0:e.error)==null?void 0:o.call(e,t))??Su((c=n.customError)==null?void 0:c.call(n,t))??Su((u=n.localeError)==null?void 0:u.call(n,t))??"Invalid input";r.message=l}return delete r.inst,delete r.continue,e!=null&&e.reportInput||delete r.input,r}function Pg(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function mc(...t){const[e,n,r]=t;return typeof e=="string"?{message:e,code:"custom",input:n,inst:r}:{...e}}const mT=(t,e)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:e,enumerable:!1}),Object.defineProperty(t,"message",{get(){return JSON.stringify(e,$P,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},gT=U("$ZodError",mT),qd=U("$ZodError",mT,{Parent:Error});function zP(t,e=n=>n.message){const n={},r=[];for(const s of t.issues)s.path.length>0?(n[s.path[0]]=n[s.path[0]]||[],n[s.path[0]].push(e(s))):r.push(e(s));return{formErrors:r,fieldErrors:n}}function HP(t,e){const n=e||function(a){return a.message},r={_errors:[]},s=a=>{for(const i of a.issues)if(i.code==="invalid_union"&&i.errors.length)i.errors.map(o=>s({issues:o}));else if(i.code==="invalid_key")s({issues:i.issues});else if(i.code==="invalid_element")s({issues:i.issues});else if(i.path.length===0)r._errors.push(n(i));else{let o=r,c=0;for(;c<i.path.length;){const u=i.path[c];c===i.path.length-1?(o[u]=o[u]||{_errors:[]},o[u]._errors.push(n(i))):o[u]=o[u]||{_errors:[]},o=o[u],c++}}};return s(t),r}function VP(t){const e=[];for(const n of t)typeof n=="number"?e.push(`[${n}]`):typeof n=="symbol"?e.push(`[${JSON.stringify(String(n))}]`):/[^\w$]/.test(n)?e.push(`[${JSON.stringify(n)}]`):(e.length&&e.push("."),e.push(n));return e.join("")}function ZP(t){var r;const e=[],n=[...t.issues].sort((s,a)=>s.path.length-a.path.length);for(const s of n)e.push(`✖ ${s.message}`),(r=s.path)!=null&&r.length&&e.push(` → at ${VP(s.path)}`);return e.join(`
67
- `)}const _T=t=>(e,n,r,s)=>{const a=r?Object.assign(r,{async:!1}):{async:!1},i=e._zod.run({value:n,issues:[]},a);if(i instanceof Promise)throw new pc;if(i.issues.length){const o=new((s==null?void 0:s.Err)??t)(i.issues.map(c=>Xs(c,a,Js())));throw hT(o,s==null?void 0:s.callee),o}return i.value},Kd=_T(qd),yT=t=>async(e,n,r,s)=>{const a=r?Object.assign(r,{async:!0}):{async:!0};let i=e._zod.run({value:n,issues:[]},a);if(i instanceof Promise&&(i=await i),i.issues.length){const o=new((s==null?void 0:s.Err)??t)(i.issues.map(c=>Xs(c,a,Js())));throw hT(o,s==null?void 0:s.callee),o}return i.value},wT=yT(qd),bT=t=>(e,n,r)=>{const s=r?{...r,async:!1}:{async:!1},a=e._zod.run({value:n,issues:[]},s);if(a instanceof Promise)throw new pc;return a.issues.length?{success:!1,error:new(t??gT)(a.issues.map(i=>Xs(i,s,Js())))}:{success:!0,data:a.value}},WP=bT(qd),vT=t=>async(e,n,r)=>{const s=r?Object.assign(r,{async:!0}):{async:!0};let a=e._zod.run({value:n,issues:[]},s);return a instanceof Promise&&(a=await a),a.issues.length?{success:!1,error:new t(a.issues.map(i=>Xs(i,s,Js())))}:{success:!0,data:a.value}},GP=vT(qd),qP=/^[cC][^\s-]{8,}$/,KP=/^[0-9a-z]+$/,JP=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,XP=/^[0-9a-vA-V]{20}$/,YP=/^[A-Za-z0-9]{27}$/,QP=/^[a-zA-Z0-9_-]{21}$/,e2=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,t2=/^([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})$/,Aw=t=>t?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([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)$/,n2=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,r2="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function s2(){return new RegExp(r2,"u")}const a2=/^(?:(?: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])$/,i2=/^(([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})$/,o2=/^((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])$/,c2=/^(([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])$/,u2=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,ST=/^[A-Za-z0-9_-]*$/,l2=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,d2=/^\+(?:[0-9]){6,14}[0-9]$/,TT="(?:(?:\\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])))",h2=new RegExp(`^${TT}$`);function ET(t){const e="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof t.precision=="number"?t.precision===-1?`${e}`:t.precision===0?`${e}:[0-5]\\d`:`${e}:[0-5]\\d\\.\\d{${t.precision}}`:`${e}(?::[0-5]\\d(?:\\.\\d+)?)?`}function f2(t){return new RegExp(`^${ET(t)}$`)}function p2(t){const e=ET({precision:t.precision}),n=["Z"];t.local&&n.push(""),t.offset&&n.push("([+-]\\d{2}:\\d{2})");const r=`${e}(?:${n.join("|")})`;return new RegExp(`^${TT}T(?:${r})$`)}const m2=t=>{const e=t?`[\\s\\S]{${(t==null?void 0:t.minimum)??0},${(t==null?void 0:t.maximum)??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},g2=/^\d+$/,_2=/^-?\d+(?:\.\d+)?/i,y2=/true|false/i,w2=/^[^A-Z]*$/,b2=/^[^a-z]*$/,Mn=U("$ZodCheck",(t,e)=>{var n;t._zod??(t._zod={}),t._zod.def=e,(n=t._zod).onattach??(n.onattach=[])}),AT={number:"number",bigint:"bigint",object:"date"},IT=U("$ZodCheckLessThan",(t,e)=>{Mn.init(t,e);const n=AT[typeof e.value];t._zod.onattach.push(r=>{const s=r._zod.bag,a=(e.inclusive?s.maximum:s.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value<a&&(e.inclusive?s.maximum=e.value:s.exclusiveMaximum=e.value)}),t._zod.check=r=>{(e.inclusive?r.value<=e.value:r.value<e.value)||r.issues.push({origin:n,code:"too_big",maximum:e.value,input:r.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),xT=U("$ZodCheckGreaterThan",(t,e)=>{Mn.init(t,e);const n=AT[typeof e.value];t._zod.onattach.push(r=>{const s=r._zod.bag,a=(e.inclusive?s.minimum:s.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>a&&(e.inclusive?s.minimum=e.value:s.exclusiveMinimum=e.value)}),t._zod.check=r=>{(e.inclusive?r.value>=e.value:r.value>e.value)||r.issues.push({origin:n,code:"too_small",minimum:e.value,input:r.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),v2=U("$ZodCheckMultipleOf",(t,e)=>{Mn.init(t,e),t._zod.onattach.push(n=>{var r;(r=n._zod.bag).multipleOf??(r.multipleOf=e.value)}),t._zod.check=n=>{if(typeof n.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof n.value=="bigint"?n.value%e.value===BigInt(0):NP(n.value,e.value)===0)||n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:e.value,input:n.value,inst:t,continue:!e.abort})}}),S2=U("$ZodCheckNumberFormat",(t,e)=>{var i;Mn.init(t,e),e.format=e.format||"float64";const n=(i=e.format)==null?void 0:i.includes("int"),r=n?"int":"number",[s,a]=jP[e.format];t._zod.onattach.push(o=>{const c=o._zod.bag;c.format=e.format,c.minimum=s,c.maximum=a,n&&(c.pattern=g2)}),t._zod.check=o=>{const c=o.value;if(n){if(!Number.isInteger(c)){o.issues.push({expected:r,format:e.format,code:"invalid_type",input:c,inst:t});return}if(!Number.isSafeInteger(c)){c>0?o.issues.push({input:c,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:r,continue:!e.abort}):o.issues.push({input:c,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:r,continue:!e.abort});return}}c<s&&o.issues.push({origin:"number",input:c,code:"too_small",minimum:s,inclusive:!0,inst:t,continue:!e.abort}),c>a&&o.issues.push({origin:"number",input:c,code:"too_big",maximum:a,inst:t})}}),T2=U("$ZodCheckMaxLength",(t,e)=>{var n;Mn.init(t,e),(n=t._zod.def).when??(n.when=r=>{const s=r.value;return!Rg(s)&&s.length!==void 0}),t._zod.onattach.push(r=>{const s=r._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<s&&(r._zod.bag.maximum=e.maximum)}),t._zod.check=r=>{const s=r.value;if(s.length<=e.maximum)return;const i=Pg(s);r.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:s,inst:t,continue:!e.abort})}}),E2=U("$ZodCheckMinLength",(t,e)=>{var n;Mn.init(t,e),(n=t._zod.def).when??(n.when=r=>{const s=r.value;return!Rg(s)&&s.length!==void 0}),t._zod.onattach.push(r=>{const s=r._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>s&&(r._zod.bag.minimum=e.minimum)}),t._zod.check=r=>{const s=r.value;if(s.length>=e.minimum)return;const i=Pg(s);r.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:s,inst:t,continue:!e.abort})}}),A2=U("$ZodCheckLengthEquals",(t,e)=>{var n;Mn.init(t,e),(n=t._zod.def).when??(n.when=r=>{const s=r.value;return!Rg(s)&&s.length!==void 0}),t._zod.onattach.push(r=>{const s=r._zod.bag;s.minimum=e.length,s.maximum=e.length,s.length=e.length}),t._zod.check=r=>{const s=r.value,a=s.length;if(a===e.length)return;const i=Pg(s),o=a>e.length;r.issues.push({origin:i,...o?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:r.value,inst:t,continue:!e.abort})}}),Jd=U("$ZodCheckStringFormat",(t,e)=>{var n,r;Mn.init(t,e),t._zod.onattach.push(s=>{const a=s._zod.bag;a.format=e.format,e.pattern&&(a.patterns??(a.patterns=new Set),a.patterns.add(e.pattern))}),e.pattern?(n=t._zod).check??(n.check=s=>{e.pattern.lastIndex=0,!e.pattern.test(s.value)&&s.issues.push({origin:"string",code:"invalid_format",format:e.format,input:s.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(r=t._zod).check??(r.check=()=>{})}),I2=U("$ZodCheckRegex",(t,e)=>{Jd.init(t,e),t._zod.check=n=>{e.pattern.lastIndex=0,!e.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),x2=U("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=w2),Jd.init(t,e)}),k2=U("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=b2),Jd.init(t,e)}),O2=U("$ZodCheckIncludes",(t,e)=>{Mn.init(t,e);const n=Gc(e.includes),r=new RegExp(typeof e.position=="number"?`^.{${e.position}}${n}`:n);e.pattern=r,t._zod.onattach.push(s=>{const a=s._zod.bag;a.patterns??(a.patterns=new Set),a.patterns.add(r)}),t._zod.check=s=>{s.value.includes(e.includes,e.position)||s.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:s.value,inst:t,continue:!e.abort})}}),C2=U("$ZodCheckStartsWith",(t,e)=>{Mn.init(t,e);const n=new RegExp(`^${Gc(e.prefix)}.*`);e.pattern??(e.pattern=n),t._zod.onattach.push(r=>{const s=r._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(n)}),t._zod.check=r=>{r.value.startsWith(e.prefix)||r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:r.value,inst:t,continue:!e.abort})}}),R2=U("$ZodCheckEndsWith",(t,e)=>{Mn.init(t,e);const n=new RegExp(`.*${Gc(e.suffix)}$`);e.pattern??(e.pattern=n),t._zod.onattach.push(r=>{const s=r._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(n)}),t._zod.check=r=>{r.value.endsWith(e.suffix)||r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:r.value,inst:t,continue:!e.abort})}}),$2=U("$ZodCheckOverwrite",(t,e)=>{Mn.init(t,e),t._zod.check=n=>{n.value=e.tx(n.value)}});class N2{constructor(e=[]){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}const r=e.split(`
68
- `).filter(i=>i),s=Math.min(...r.map(i=>i.length-i.trimStart().length)),a=r.map(i=>i.slice(s)).map(i=>" ".repeat(this.indent*2)+i);for(const i of a)this.content.push(i)}compile(){const e=Function,n=this==null?void 0:this.args,s=[...((this==null?void 0:this.content)??[""]).map(a=>` ${a}`)];return new e(...n,s.join(`
69
- `))}}const P2={major:4,minor:0,patch:0},at=U("$ZodType",(t,e)=>{var s;var n;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=P2;const r=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&r.unshift(t);for(const a of r)for(const i of a._zod.onattach)i(t);if(r.length===0)(n=t._zod).deferred??(n.deferred=[]),(s=t._zod.deferred)==null||s.push(()=>{t._zod.run=t._zod.parse});else{const a=(i,o,c)=>{let u=Qo(i),l;for(const d of o){if(d._zod.def.when){if(!d._zod.def.when(i))continue}else if(u)continue;const f=i.issues.length,h=d._zod.check(i);if(h instanceof Promise&&(c==null?void 0:c.async)===!1)throw new pc;if(l||h instanceof Promise)l=(l??Promise.resolve()).then(async()=>{await h,i.issues.length!==f&&(u||(u=Qo(i,f)))});else{if(i.issues.length===f)continue;u||(u=Qo(i,f))}}return l?l.then(()=>i):i};t._zod.run=(i,o)=>{const c=t._zod.parse(i,o);if(c instanceof Promise){if(o.async===!1)throw new pc;return c.then(u=>a(u,r,o))}return a(c,r,o)}}t["~standard"]={validate:a=>{var i;try{const o=WP(t,a);return o.success?{value:o.data}:{issues:(i=o.error)==null?void 0:i.issues}}catch{return GP(t,a).then(c=>{var u;return c.success?{value:c.data}:{issues:(u=c.error)==null?void 0:u.issues}})}},vendor:"zod",version:1}}),Mg=U("$ZodString",(t,e)=>{var n;at.init(t,e),t._zod.pattern=[...((n=t==null?void 0:t._zod.bag)==null?void 0:n.patterns)??[]].pop()??m2(t._zod.bag),t._zod.parse=(r,s)=>{if(e.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:t}),r}}),_t=U("$ZodStringFormat",(t,e)=>{Jd.init(t,e),Mg.init(t,e)}),M2=U("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=t2),_t.init(t,e)}),L2=U("$ZodUUID",(t,e)=>{if(e.version){const r={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(r===void 0)throw new Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=Aw(r))}else e.pattern??(e.pattern=Aw());_t.init(t,e)}),j2=U("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=n2),_t.init(t,e)}),U2=U("$ZodURL",(t,e)=>{_t.init(t,e),t._zod.check=n=>{try{const r=n.value,s=new URL(r),a=s.href;e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(s.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:l2.source,input:n.value,inst:t,continue:!e.abort})),e.protocol&&(e.protocol.lastIndex=0,e.protocol.test(s.protocol.endsWith(":")?s.protocol.slice(0,-1):s.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:n.value,inst:t,continue:!e.abort})),!r.endsWith("/")&&a.endsWith("/")?n.value=a.slice(0,-1):n.value=a;return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:t,continue:!e.abort})}}}),D2=U("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=s2()),_t.init(t,e)}),F2=U("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=QP),_t.init(t,e)}),B2=U("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=qP),_t.init(t,e)}),z2=U("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=KP),_t.init(t,e)}),H2=U("$ZodULID",(t,e)=>{e.pattern??(e.pattern=JP),_t.init(t,e)}),V2=U("$ZodXID",(t,e)=>{e.pattern??(e.pattern=XP),_t.init(t,e)}),Z2=U("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=YP),_t.init(t,e)}),W2=U("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=p2(e)),_t.init(t,e)}),G2=U("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=h2),_t.init(t,e)}),q2=U("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=f2(e)),_t.init(t,e)}),K2=U("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=e2),_t.init(t,e)}),J2=U("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=a2),_t.init(t,e),t._zod.onattach.push(n=>{const r=n._zod.bag;r.format="ipv4"})}),X2=U("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=i2),_t.init(t,e),t._zod.onattach.push(n=>{const r=n._zod.bag;r.format="ipv6"}),t._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:t,continue:!e.abort})}}}),Y2=U("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=o2),_t.init(t,e)}),Q2=U("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=c2),_t.init(t,e),t._zod.check=n=>{const[r,s]=n.value.split("/");try{if(!s)throw new Error;const a=Number(s);if(`${a}`!==s)throw new Error;if(a<0||a>128)throw new Error;new URL(`http://[${r}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:t,continue:!e.abort})}}});function kT(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}const eM=U("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=u2),_t.init(t,e),t._zod.onattach.push(n=>{n._zod.bag.contentEncoding="base64"}),t._zod.check=n=>{kT(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:t,continue:!e.abort})}});function tM(t){if(!ST.test(t))return!1;const e=t.replace(/[-_]/g,r=>r==="-"?"+":"/"),n=e.padEnd(Math.ceil(e.length/4)*4,"=");return kT(n)}const nM=U("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=ST),_t.init(t,e),t._zod.onattach.push(n=>{n._zod.bag.contentEncoding="base64url"}),t._zod.check=n=>{tM(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:t,continue:!e.abort})}}),rM=U("$ZodE164",(t,e)=>{e.pattern??(e.pattern=d2),_t.init(t,e)});function sM(t,e=null){try{const n=t.split(".");if(n.length!==3)return!1;const[r]=n;if(!r)return!1;const s=JSON.parse(atob(r));return!("typ"in s&&(s==null?void 0:s.typ)!=="JWT"||!s.alg||e&&(!("alg"in s)||s.alg!==e))}catch{return!1}}const aM=U("$ZodJWT",(t,e)=>{_t.init(t,e),t._zod.check=n=>{sM(n.value,e.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:t,continue:!e.abort})}}),OT=U("$ZodNumber",(t,e)=>{at.init(t,e),t._zod.pattern=t._zod.bag.pattern??_2,t._zod.parse=(n,r)=>{if(e.coerce)try{n.value=Number(n.value)}catch{}const s=n.value;if(typeof s=="number"&&!Number.isNaN(s)&&Number.isFinite(s))return n;const a=typeof s=="number"?Number.isNaN(s)?"NaN":Number.isFinite(s)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:s,inst:t,...a?{received:a}:{}}),n}}),iM=U("$ZodNumber",(t,e)=>{S2.init(t,e),OT.init(t,e)}),oM=U("$ZodBoolean",(t,e)=>{at.init(t,e),t._zod.pattern=y2,t._zod.parse=(n,r)=>{if(e.coerce)try{n.value=!!n.value}catch{}const s=n.value;return typeof s=="boolean"||n.issues.push({expected:"boolean",code:"invalid_type",input:s,inst:t}),n}}),cM=U("$ZodAny",(t,e)=>{at.init(t,e),t._zod.parse=n=>n}),CT=U("$ZodUnknown",(t,e)=>{at.init(t,e),t._zod.parse=n=>n}),RT=U("$ZodNever",(t,e)=>{at.init(t,e),t._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:t}),n)});function Iw(t,e,n){t.issues.length&&e.issues.push(...Ls(n,t.issues)),e.value[n]=t.value}const uM=U("$ZodArray",(t,e)=>{at.init(t,e),t._zod.parse=(n,r)=>{const s=n.value;if(!Array.isArray(s))return n.issues.push({expected:"array",code:"invalid_type",input:s,inst:t}),n;n.value=Array(s.length);const a=[];for(let i=0;i<s.length;i++){const o=s[i],c=e.element._zod.run({value:o,issues:[]},r);c instanceof Promise?a.push(c.then(u=>Iw(u,n,i))):Iw(c,n,i)}return a.length?Promise.all(a).then(()=>n):n}});function Tu(t,e,n){t.issues.length&&e.issues.push(...Ls(n,t.issues)),e.value[n]=t.value}function xw(t,e,n,r){t.issues.length?r[n]===void 0?n in r?e.value[n]=void 0:e.value[n]=t.value:e.issues.push(...Ls(n,t.issues)):t.value===void 0?n in r&&(e.value[n]=void 0):e.value[n]=t.value}const lM=U("$ZodObject",(t,e)=>{at.init(t,e);const n=Cg(()=>{const d=Object.keys(e.shape);for(const h of d)if(!(e.shape[h]instanceof at))throw new Error(`Invalid element at key "${h}": expected a Zod schema`);const f=LP(e.shape);return{shape:e.shape,keys:d,keySet:new Set(d),numKeys:d.length,optionalKeys:new Set(f)}});ft(t._zod,"propValues",()=>{const d=e.shape,f={};for(const h in d){const m=d[h]._zod;if(m.values){f[h]??(f[h]=new Set);for(const _ of m.values)f[h].add(_)}}return f});const r=d=>{const f=new N2(["shape","payload","ctx"]),h=n.value,m=g=>{const b=so(g);return`shape[${b}]._zod.run({ value: input[${b}], issues: [] }, ctx)`};f.write("const input = payload.value;");const _=Object.create(null);let y=0;for(const g of h.keys)_[g]=`key_${y++}`;f.write("const newResult = {}");for(const g of h.keys)if(h.optionalKeys.has(g)){const b=_[g];f.write(`const ${b} = ${m(g)};`);const S=so(g);f.write(`
70
- if (${b}.issues.length) {
71
- if (input[${S}] === undefined) {
72
- if (${S} in input) {
73
- newResult[${S}] = undefined;
74
- }
75
- } else {
76
- payload.issues = payload.issues.concat(
77
- ${b}.issues.map((iss) => ({
78
- ...iss,
79
- path: iss.path ? [${S}, ...iss.path] : [${S}],
80
- }))
81
- );
82
- }
83
- } else if (${b}.value === undefined) {
84
- if (${S} in input) newResult[${S}] = undefined;
85
- } else {
86
- newResult[${S}] = ${b}.value;
87
- }
88
- `)}else{const b=_[g];f.write(`const ${b} = ${m(g)};`),f.write(`
89
- if (${b}.issues.length) payload.issues = payload.issues.concat(${b}.issues.map(iss => ({
90
- ...iss,
91
- path: iss.path ? [${so(g)}, ...iss.path] : [${so(g)}]
92
- })));`),f.write(`newResult[${so(g)}] = ${b}.value`)}f.write("payload.value = newResult;"),f.write("return payload;");const w=f.compile();return(g,b)=>w(d,g,b)};let s;const a=nd,i=!lT.jitless,c=i&&PP.value,u=e.catchall;let l;t._zod.parse=(d,f)=>{l??(l=n.value);const h=d.value;if(!a(h))return d.issues.push({expected:"object",code:"invalid_type",input:h,inst:t}),d;const m=[];if(i&&c&&(f==null?void 0:f.async)===!1&&f.jitless!==!0)s||(s=r(e.shape)),d=s(d,f);else{d.value={};const b=l.shape;for(const S of l.keys){const I=b[S],T=I._zod.run({value:h[S],issues:[]},f),x=I._zod.optin==="optional"&&I._zod.optout==="optional";T instanceof Promise?m.push(T.then(A=>x?xw(A,d,S,h):Tu(A,d,S))):x?xw(T,d,S,h):Tu(T,d,S)}}if(!u)return m.length?Promise.all(m).then(()=>d):d;const _=[],y=l.keySet,w=u._zod,g=w.def.type;for(const b of Object.keys(h)){if(y.has(b))continue;if(g==="never"){_.push(b);continue}const S=w.run({value:h[b],issues:[]},f);S instanceof Promise?m.push(S.then(I=>Tu(I,d,b))):Tu(S,d,b)}return _.length&&d.issues.push({code:"unrecognized_keys",keys:_,input:h,inst:t}),m.length?Promise.all(m).then(()=>d):d}});function kw(t,e,n,r){for(const s of t)if(s.issues.length===0)return e.value=s.value,e;return e.issues.push({code:"invalid_union",input:e.value,inst:n,errors:t.map(s=>s.issues.map(a=>Xs(a,r,Js())))}),e}const $T=U("$ZodUnion",(t,e)=>{at.init(t,e),ft(t._zod,"optin",()=>e.options.some(n=>n._zod.optin==="optional")?"optional":void 0),ft(t._zod,"optout",()=>e.options.some(n=>n._zod.optout==="optional")?"optional":void 0),ft(t._zod,"values",()=>{if(e.options.every(n=>n._zod.values))return new Set(e.options.flatMap(n=>Array.from(n._zod.values)))}),ft(t._zod,"pattern",()=>{if(e.options.every(n=>n._zod.pattern)){const n=e.options.map(r=>r._zod.pattern);return new RegExp(`^(${n.map(r=>$g(r.source)).join("|")})$`)}}),t._zod.parse=(n,r)=>{let s=!1;const a=[];for(const i of e.options){const o=i._zod.run({value:n.value,issues:[]},r);if(o instanceof Promise)a.push(o),s=!0;else{if(o.issues.length===0)return o;a.push(o)}}return s?Promise.all(a).then(i=>kw(i,n,t,r)):kw(a,n,t,r)}}),dM=U("$ZodDiscriminatedUnion",(t,e)=>{$T.init(t,e);const n=t._zod.parse;ft(t._zod,"propValues",()=>{const s={};for(const a of e.options){const i=a._zod.propValues;if(!i||Object.keys(i).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(a)}"`);for(const[o,c]of Object.entries(i)){s[o]||(s[o]=new Set);for(const u of c)s[o].add(u)}}return s});const r=Cg(()=>{const s=e.options,a=new Map;for(const i of s){const o=i._zod.propValues[e.discriminator];if(!o||o.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(i)}"`);for(const c of o){if(a.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);a.set(c,i)}}return a});t._zod.parse=(s,a)=>{const i=s.value;if(!nd(i))return s.issues.push({code:"invalid_type",expected:"object",input:i,inst:t}),s;const o=r.value.get(i==null?void 0:i[e.discriminator]);return o?o._zod.run(s,a):e.unionFallback?n(s,a):(s.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:i,path:[e.discriminator],inst:t}),s)}}),hM=U("$ZodIntersection",(t,e)=>{at.init(t,e),t._zod.parse=(n,r)=>{const s=n.value,a=e.left._zod.run({value:s,issues:[]},r),i=e.right._zod.run({value:s,issues:[]},r);return a instanceof Promise||i instanceof Promise?Promise.all([a,i]).then(([c,u])=>Ow(n,c,u)):Ow(n,a,i)}});function Up(t,e){if(t===e)return{valid:!0,data:t};if(t instanceof Date&&e instanceof Date&&+t==+e)return{valid:!0,data:t};if(rd(t)&&rd(e)){const n=Object.keys(e),r=Object.keys(t).filter(a=>n.indexOf(a)!==-1),s={...t,...e};for(const a of r){const i=Up(t[a],e[a]);if(!i.valid)return{valid:!1,mergeErrorPath:[a,...i.mergeErrorPath]};s[a]=i.data}return{valid:!0,data:s}}if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return{valid:!1,mergeErrorPath:[]};const n=[];for(let r=0;r<t.length;r++){const s=t[r],a=e[r],i=Up(s,a);if(!i.valid)return{valid:!1,mergeErrorPath:[r,...i.mergeErrorPath]};n.push(i.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function Ow(t,e,n){if(e.issues.length&&t.issues.push(...e.issues),n.issues.length&&t.issues.push(...n.issues),Qo(t))return t;const r=Up(e.value,n.value);if(!r.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(r.mergeErrorPath)}`);return t.value=r.data,t}const fM=U("$ZodTuple",(t,e)=>{at.init(t,e);const n=e.items,r=n.length-[...n].reverse().findIndex(s=>s._zod.optin!=="optional");t._zod.parse=(s,a)=>{const i=s.value;if(!Array.isArray(i))return s.issues.push({input:i,inst:t,expected:"tuple",code:"invalid_type"}),s;s.value=[];const o=[];if(!e.rest){const u=i.length>n.length,l=i.length<r-1;if(u||l)return s.issues.push({input:i,inst:t,origin:"array",...u?{code:"too_big",maximum:n.length}:{code:"too_small",minimum:n.length}}),s}let c=-1;for(const u of n){if(c++,c>=i.length&&c>=r)continue;const l=u._zod.run({value:i[c],issues:[]},a);l instanceof Promise?o.push(l.then(d=>Eu(d,s,c))):Eu(l,s,c)}if(e.rest){const u=i.slice(n.length);for(const l of u){c++;const d=e.rest._zod.run({value:l,issues:[]},a);d instanceof Promise?o.push(d.then(f=>Eu(f,s,c))):Eu(d,s,c)}}return o.length?Promise.all(o).then(()=>s):s}});function Eu(t,e,n){t.issues.length&&e.issues.push(...Ls(n,t.issues)),e.value[n]=t.value}const pM=U("$ZodRecord",(t,e)=>{at.init(t,e),t._zod.parse=(n,r)=>{const s=n.value;if(!rd(s))return n.issues.push({expected:"record",code:"invalid_type",input:s,inst:t}),n;const a=[];if(e.keyType._zod.values){const i=e.keyType._zod.values;n.value={};for(const c of i)if(typeof c=="string"||typeof c=="number"||typeof c=="symbol"){const u=e.valueType._zod.run({value:s[c],issues:[]},r);u instanceof Promise?a.push(u.then(l=>{l.issues.length&&n.issues.push(...Ls(c,l.issues)),n.value[c]=l.value})):(u.issues.length&&n.issues.push(...Ls(c,u.issues)),n.value[c]=u.value)}let o;for(const c in s)i.has(c)||(o=o??[],o.push(c));o&&o.length>0&&n.issues.push({code:"unrecognized_keys",input:s,inst:t,keys:o})}else{n.value={};for(const i of Reflect.ownKeys(s)){if(i==="__proto__")continue;const o=e.keyType._zod.run({value:i,issues:[]},r);if(o instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(o.issues.length){n.issues.push({origin:"record",code:"invalid_key",issues:o.issues.map(u=>Xs(u,r,Js())),input:i,path:[i],inst:t}),n.value[o.value]=o.value;continue}const c=e.valueType._zod.run({value:s[i],issues:[]},r);c instanceof Promise?a.push(c.then(u=>{u.issues.length&&n.issues.push(...Ls(i,u.issues)),n.value[o.value]=u.value})):(c.issues.length&&n.issues.push(...Ls(i,c.issues)),n.value[o.value]=c.value)}}return a.length?Promise.all(a).then(()=>n):n}}),mM=U("$ZodEnum",(t,e)=>{at.init(t,e);const n=dT(e.entries);t._zod.values=new Set(n),t._zod.pattern=new RegExp(`^(${n.filter(r=>MP.has(typeof r)).map(r=>typeof r=="string"?Gc(r):r.toString()).join("|")})$`),t._zod.parse=(r,s)=>{const a=r.value;return t._zod.values.has(a)||r.issues.push({code:"invalid_value",values:n,input:a,inst:t}),r}}),gM=U("$ZodLiteral",(t,e)=>{at.init(t,e),t._zod.values=new Set(e.values),t._zod.pattern=new RegExp(`^(${e.values.map(n=>typeof n=="string"?Gc(n):n?n.toString():String(n)).join("|")})$`),t._zod.parse=(n,r)=>{const s=n.value;return t._zod.values.has(s)||n.issues.push({code:"invalid_value",values:e.values,input:s,inst:t}),n}}),_M=U("$ZodTransform",(t,e)=>{at.init(t,e),t._zod.parse=(n,r)=>{const s=e.transform(n.value,n);if(r.async)return(s instanceof Promise?s:Promise.resolve(s)).then(i=>(n.value=i,n));if(s instanceof Promise)throw new pc;return n.value=s,n}}),Lg=U("$ZodOptional",(t,e)=>{at.init(t,e),t._zod.optin="optional",t._zod.optout="optional",ft(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),ft(t._zod,"pattern",()=>{const n=e.innerType._zod.pattern;return n?new RegExp(`^(${$g(n.source)})?$`):void 0}),t._zod.parse=(n,r)=>e.innerType._zod.optin==="optional"?e.innerType._zod.run(n,r):n.value===void 0?n:e.innerType._zod.run(n,r)}),yM=U("$ZodNullable",(t,e)=>{at.init(t,e),ft(t._zod,"optin",()=>e.innerType._zod.optin),ft(t._zod,"optout",()=>e.innerType._zod.optout),ft(t._zod,"pattern",()=>{const n=e.innerType._zod.pattern;return n?new RegExp(`^(${$g(n.source)}|null)$`):void 0}),ft(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(n,r)=>n.value===null?n:e.innerType._zod.run(n,r)}),wM=U("$ZodDefault",(t,e)=>{at.init(t,e),t._zod.optin="optional",ft(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,r)=>{if(n.value===void 0)return n.value=e.defaultValue,n;const s=e.innerType._zod.run(n,r);return s instanceof Promise?s.then(a=>Cw(a,e)):Cw(s,e)}});function Cw(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}const bM=U("$ZodPrefault",(t,e)=>{at.init(t,e),t._zod.optin="optional",ft(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,r)=>(n.value===void 0&&(n.value=e.defaultValue),e.innerType._zod.run(n,r))}),vM=U("$ZodNonOptional",(t,e)=>{at.init(t,e),ft(t._zod,"values",()=>{const n=e.innerType._zod.values;return n?new Set([...n].filter(r=>r!==void 0)):void 0}),t._zod.parse=(n,r)=>{const s=e.innerType._zod.run(n,r);return s instanceof Promise?s.then(a=>Rw(a,t)):Rw(s,t)}});function Rw(t,e){return!t.issues.length&&t.value===void 0&&t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:e}),t}const SM=U("$ZodCatch",(t,e)=>{at.init(t,e),t._zod.optin="optional",ft(t._zod,"optout",()=>e.innerType._zod.optout),ft(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,r)=>{const s=e.innerType._zod.run(n,r);return s instanceof Promise?s.then(a=>(n.value=a.value,a.issues.length&&(n.value=e.catchValue({...n,error:{issues:a.issues.map(i=>Xs(i,r,Js()))},input:n.value}),n.issues=[]),n)):(n.value=s.value,s.issues.length&&(n.value=e.catchValue({...n,error:{issues:s.issues.map(a=>Xs(a,r,Js()))},input:n.value}),n.issues=[]),n)}}),TM=U("$ZodPipe",(t,e)=>{at.init(t,e),ft(t._zod,"values",()=>e.in._zod.values),ft(t._zod,"optin",()=>e.in._zod.optin),ft(t._zod,"optout",()=>e.out._zod.optout),t._zod.parse=(n,r)=>{const s=e.in._zod.run(n,r);return s instanceof Promise?s.then(a=>$w(a,e,r)):$w(s,e,r)}});function $w(t,e,n){return Qo(t)?t:e.out._zod.run({value:t.value,issues:t.issues},n)}const EM=U("$ZodReadonly",(t,e)=>{at.init(t,e),ft(t._zod,"propValues",()=>e.innerType._zod.propValues),ft(t._zod,"values",()=>e.innerType._zod.values),ft(t._zod,"optin",()=>e.innerType._zod.optin),ft(t._zod,"optout",()=>e.innerType._zod.optout),t._zod.parse=(n,r)=>{const s=e.innerType._zod.run(n,r);return s instanceof Promise?s.then(Nw):Nw(s)}});function Nw(t){return t.value=Object.freeze(t.value),t}const AM=U("$ZodCustom",(t,e)=>{Mn.init(t,e),at.init(t,e),t._zod.parse=(n,r)=>n,t._zod.check=n=>{const r=n.value,s=e.fn(r);if(s instanceof Promise)return s.then(a=>Pw(a,n,r,t));Pw(s,n,r,t)}});function Pw(t,e,n,r){if(!t){const s={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(s.params=r._zod.def.params),e.issues.push(mc(s))}}class NT{constructor(){this._map=new Map,this._idmap=new Map}add(e,...n){const r=n[0];if(this._map.set(e,r),r&&typeof r=="object"&&"id"in r){if(this._idmap.has(r.id))throw new Error(`ID ${r.id} already exists in the registry`);this._idmap.set(r.id,e)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(e){const n=this._map.get(e);return n&&typeof n=="object"&&"id"in n&&this._idmap.delete(n.id),this._map.delete(e),this}get(e){const n=e._zod.parent;if(n){const r={...this.get(n)??{}};return delete r.id,{...r,...this._map.get(e)}}return this._map.get(e)}has(e){return this._map.has(e)}}function IM(){return new NT}const zt=IM();function xM(t,e){return new t({type:"string",...ye(e)})}function kM(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...ye(e)})}function Mw(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...ye(e)})}function OM(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...ye(e)})}function CM(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...ye(e)})}function RM(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...ye(e)})}function $M(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...ye(e)})}function NM(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...ye(e)})}function PM(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...ye(e)})}function MM(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...ye(e)})}function LM(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...ye(e)})}function jM(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...ye(e)})}function UM(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...ye(e)})}function DM(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...ye(e)})}function FM(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...ye(e)})}function BM(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...ye(e)})}function zM(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...ye(e)})}function HM(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...ye(e)})}function VM(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...ye(e)})}function ZM(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...ye(e)})}function WM(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...ye(e)})}function GM(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...ye(e)})}function qM(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...ye(e)})}function KM(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...ye(e)})}function JM(t,e){return new t({type:"string",format:"date",check:"string_format",...ye(e)})}function XM(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...ye(e)})}function YM(t,e){return new t({type:"string",format:"duration",check:"string_format",...ye(e)})}function QM(t,e){return new t({type:"number",checks:[],...ye(e)})}function eL(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...ye(e)})}function tL(t,e){return new t({type:"boolean",...ye(e)})}function nL(t){return new t({type:"any"})}function PT(t){return new t({type:"unknown"})}function MT(t,e){return new t({type:"never",...ye(e)})}function Lw(t,e){return new IT({check:"less_than",...ye(e),value:t,inclusive:!1})}function nf(t,e){return new IT({check:"less_than",...ye(e),value:t,inclusive:!0})}function jw(t,e){return new xT({check:"greater_than",...ye(e),value:t,inclusive:!1})}function rf(t,e){return new xT({check:"greater_than",...ye(e),value:t,inclusive:!0})}function Uw(t,e){return new v2({check:"multiple_of",...ye(e),value:t})}function LT(t,e){return new T2({check:"max_length",...ye(e),maximum:t})}function sd(t,e){return new E2({check:"min_length",...ye(e),minimum:t})}function jT(t,e){return new A2({check:"length_equals",...ye(e),length:t})}function rL(t,e){return new I2({check:"string_format",format:"regex",...ye(e),pattern:t})}function sL(t){return new x2({check:"string_format",format:"lowercase",...ye(t)})}function aL(t){return new k2({check:"string_format",format:"uppercase",...ye(t)})}function iL(t,e){return new O2({check:"string_format",format:"includes",...ye(e),includes:t})}function oL(t,e){return new C2({check:"string_format",format:"starts_with",...ye(e),prefix:t})}function cL(t,e){return new R2({check:"string_format",format:"ends_with",...ye(e),suffix:t})}function qc(t){return new $2({check:"overwrite",tx:t})}function uL(t){return qc(e=>e.normalize(t))}function lL(){return qc(t=>t.trim())}function dL(){return qc(t=>t.toLowerCase())}function hL(){return qc(t=>t.toUpperCase())}function fL(t,e,n){return new t({type:"array",element:e,...ye(n)})}function pL(t,e,n){const r=ye(n);return r.abort??(r.abort=!0),new t({type:"custom",check:"custom",fn:e,...r})}function mL(t,e,n){return new t({type:"custom",check:"custom",fn:e,...ye(n)})}class Dw{constructor(e){this.counter=0,this.metadataRegistry=(e==null?void 0:e.metadata)??zt,this.target=(e==null?void 0:e.target)??"draft-2020-12",this.unrepresentable=(e==null?void 0:e.unrepresentable)??"throw",this.override=(e==null?void 0:e.override)??(()=>{}),this.io=(e==null?void 0:e.io)??"output",this.seen=new Map}process(e,n={path:[],schemaPath:[]}){var d,f,h;var r;const s=e._zod.def,a={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},i=this.seen.get(e);if(i)return i.count++,n.schemaPath.includes(e)&&(i.cycle=n.path),i.schema;const o={schema:{},count:1,cycle:void 0,path:n.path};this.seen.set(e,o);const c=(f=(d=e._zod).toJSONSchema)==null?void 0:f.call(d);if(c)o.schema=c;else{const m={...n,schemaPath:[...n.schemaPath,e],path:n.path},_=e._zod.parent;if(_)o.ref=_,this.process(_,m),this.seen.get(_).isParent=!0;else{const y=o.schema;switch(s.type){case"string":{const w=y;w.type="string";const{minimum:g,maximum:b,format:S,patterns:I,contentEncoding:T}=e._zod.bag;if(typeof g=="number"&&(w.minLength=g),typeof b=="number"&&(w.maxLength=b),S&&(w.format=a[S]??S,w.format===""&&delete w.format),T&&(w.contentEncoding=T),I&&I.size>0){const x=[...I];x.length===1?w.pattern=x[0].source:x.length>1&&(o.schema.allOf=[...x.map(A=>({...this.target==="draft-7"?{type:"string"}:{},pattern:A.source}))])}break}case"number":{const w=y,{minimum:g,maximum:b,format:S,multipleOf:I,exclusiveMaximum:T,exclusiveMinimum:x}=e._zod.bag;typeof S=="string"&&S.includes("int")?w.type="integer":w.type="number",typeof x=="number"&&(w.exclusiveMinimum=x),typeof g=="number"&&(w.minimum=g,typeof x=="number"&&(x>=g?delete w.minimum:delete w.exclusiveMinimum)),typeof T=="number"&&(w.exclusiveMaximum=T),typeof b=="number"&&(w.maximum=b,typeof T=="number"&&(T<=b?delete w.maximum:delete w.exclusiveMaximum)),typeof I=="number"&&(w.multipleOf=I);break}case"boolean":{const w=y;w.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema");break}case"null":{y.type="null";break}case"any":break;case"unknown":break;case"undefined":{if(this.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema");break}case"void":{if(this.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema");break}case"never":{y.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{const w=y,{minimum:g,maximum:b}=e._zod.bag;typeof g=="number"&&(w.minItems=g),typeof b=="number"&&(w.maxItems=b),w.type="array",w.items=this.process(s.element,{...m,path:[...m.path,"items"]});break}case"object":{const w=y;w.type="object",w.properties={};const g=s.shape;for(const I in g)w.properties[I]=this.process(g[I],{...m,path:[...m.path,"properties",I]});const b=new Set(Object.keys(g)),S=new Set([...b].filter(I=>{const T=s.shape[I]._zod;return this.io==="input"?T.optin===void 0:T.optout===void 0}));S.size>0&&(w.required=Array.from(S)),((h=s.catchall)==null?void 0:h._zod.def.type)==="never"?w.additionalProperties=!1:s.catchall?s.catchall&&(w.additionalProperties=this.process(s.catchall,{...m,path:[...m.path,"additionalProperties"]})):this.io==="output"&&(w.additionalProperties=!1);break}case"union":{const w=y;w.anyOf=s.options.map((g,b)=>this.process(g,{...m,path:[...m.path,"anyOf",b]}));break}case"intersection":{const w=y,g=this.process(s.left,{...m,path:[...m.path,"allOf",0]}),b=this.process(s.right,{...m,path:[...m.path,"allOf",1]}),S=T=>"allOf"in T&&Object.keys(T).length===1,I=[...S(g)?g.allOf:[g],...S(b)?b.allOf:[b]];w.allOf=I;break}case"tuple":{const w=y;w.type="array";const g=s.items.map((I,T)=>this.process(I,{...m,path:[...m.path,"prefixItems",T]}));if(this.target==="draft-2020-12"?w.prefixItems=g:w.items=g,s.rest){const I=this.process(s.rest,{...m,path:[...m.path,"items"]});this.target==="draft-2020-12"?w.items=I:w.additionalItems=I}s.rest&&(w.items=this.process(s.rest,{...m,path:[...m.path,"items"]}));const{minimum:b,maximum:S}=e._zod.bag;typeof b=="number"&&(w.minItems=b),typeof S=="number"&&(w.maxItems=S);break}case"record":{const w=y;w.type="object",w.propertyNames=this.process(s.keyType,{...m,path:[...m.path,"propertyNames"]}),w.additionalProperties=this.process(s.valueType,{...m,path:[...m.path,"additionalProperties"]});break}case"map":{if(this.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema");break}case"set":{if(this.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema");break}case"enum":{const w=y,g=dT(s.entries);g.every(b=>typeof b=="number")&&(w.type="number"),g.every(b=>typeof b=="string")&&(w.type="string"),w.enum=g;break}case"literal":{const w=y,g=[];for(const b of s.values)if(b===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof b=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");g.push(Number(b))}else g.push(b);if(g.length!==0)if(g.length===1){const b=g[0];w.type=b===null?"null":typeof b,w.const=b}else g.every(b=>typeof b=="number")&&(w.type="number"),g.every(b=>typeof b=="string")&&(w.type="string"),g.every(b=>typeof b=="boolean")&&(w.type="string"),g.every(b=>b===null)&&(w.type="null"),w.enum=g;break}case"file":{const w=y,g={type:"string",format:"binary",contentEncoding:"binary"},{minimum:b,maximum:S,mime:I}=e._zod.bag;b!==void 0&&(g.minLength=b),S!==void 0&&(g.maxLength=S),I?I.length===1?(g.contentMediaType=I[0],Object.assign(w,g)):w.anyOf=I.map(T=>({...g,contentMediaType:T})):Object.assign(w,g);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{const w=this.process(s.innerType,m);y.anyOf=[w,{type:"null"}];break}case"nonoptional":{this.process(s.innerType,m),o.ref=s.innerType;break}case"success":{const w=y;w.type="boolean";break}case"default":{this.process(s.innerType,m),o.ref=s.innerType,y.default=JSON.parse(JSON.stringify(s.defaultValue));break}case"prefault":{this.process(s.innerType,m),o.ref=s.innerType,this.io==="input"&&(y._prefault=JSON.parse(JSON.stringify(s.defaultValue)));break}case"catch":{this.process(s.innerType,m),o.ref=s.innerType;let w;try{w=s.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}y.default=w;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{const w=y,g=e._zod.pattern;if(!g)throw new Error("Pattern not found in template literal");w.type="string",w.pattern=g.source;break}case"pipe":{const w=this.io==="input"?s.in._zod.def.type==="transform"?s.out:s.in:s.out;this.process(w,m),o.ref=w;break}case"readonly":{this.process(s.innerType,m),o.ref=s.innerType,y.readOnly=!0;break}case"promise":{this.process(s.innerType,m),o.ref=s.innerType;break}case"optional":{this.process(s.innerType,m),o.ref=s.innerType;break}case"lazy":{const w=e._zod.innerType;this.process(w,m),o.ref=w;break}case"custom":{if(this.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema");break}}}}const u=this.metadataRegistry.get(e);return u&&Object.assign(o.schema,u),this.io==="input"&&Rt(e)&&(delete o.schema.examples,delete o.schema.default),this.io==="input"&&o.schema._prefault&&((r=o.schema).default??(r.default=o.schema._prefault)),delete o.schema._prefault,this.seen.get(e).schema}emit(e,n){var l,d,f,h,m,_;const r={cycles:(n==null?void 0:n.cycles)??"ref",reused:(n==null?void 0:n.reused)??"inline",external:(n==null?void 0:n.external)??void 0},s=this.seen.get(e);if(!s)throw new Error("Unprocessed schema. This is a bug in Zod.");const a=y=>{var I;const w=this.target==="draft-2020-12"?"$defs":"definitions";if(r.external){const T=(I=r.external.registry.get(y[0]))==null?void 0:I.id,x=r.external.uri??(M=>M);if(T)return{ref:x(T)};const A=y[1].defId??y[1].schema.id??`schema${this.counter++}`;return y[1].defId=A,{defId:A,ref:`${x("__shared")}#/${w}/${A}`}}if(y[1]===s)return{ref:"#"};const b=`#/${w}/`,S=y[1].schema.id??`__schema${this.counter++}`;return{defId:S,ref:b+S}},i=y=>{if(y[1].schema.$ref)return;const w=y[1],{ref:g,defId:b}=a(y);w.def={...w.schema},b&&(w.defId=b);const S=w.schema;for(const I in S)delete S[I];S.$ref=g};if(r.cycles==="throw")for(const y of this.seen.entries()){const w=y[1];if(w.cycle)throw new Error(`Cycle detected: #/${(l=w.cycle)==null?void 0:l.join("/")}/<root>
93
-
94
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const y of this.seen.entries()){const w=y[1];if(e===y[0]){i(y);continue}if(r.external){const b=(d=r.external.registry.get(y[0]))==null?void 0:d.id;if(e!==y[0]&&b){i(y);continue}}if((f=this.metadataRegistry.get(y[0]))==null?void 0:f.id){i(y);continue}if(w.cycle){i(y);continue}if(w.count>1&&r.reused==="ref"){i(y);continue}}const o=(y,w)=>{const g=this.seen.get(y),b=g.def??g.schema,S={...b};if(g.ref===null)return;const I=g.ref;if(g.ref=null,I){o(I,w);const T=this.seen.get(I).schema;T.$ref&&w.target==="draft-7"?(b.allOf=b.allOf??[],b.allOf.push(T)):(Object.assign(b,T),Object.assign(b,S))}g.isParent||this.override({zodSchema:y,jsonSchema:b,path:g.path??[]})};for(const y of[...this.seen.entries()].reverse())o(y[0],{target:this.target});const c={};if(this.target==="draft-2020-12"?c.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?c.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),(h=r.external)!=null&&h.uri){const y=(m=r.external.registry.get(e))==null?void 0:m.id;if(!y)throw new Error("Schema is missing an `id` property");c.$id=r.external.uri(y)}Object.assign(c,s.def);const u=((_=r.external)==null?void 0:_.defs)??{};for(const y of this.seen.entries()){const w=y[1];w.def&&w.defId&&(u[w.defId]=w.def)}r.external||Object.keys(u).length>0&&(this.target==="draft-2020-12"?c.$defs=u:c.definitions=u);try{return JSON.parse(JSON.stringify(c))}catch{throw new Error("Error converting schema to JSON.")}}}function Dp(t,e){if(t instanceof NT){const r=new Dw(e),s={};for(const o of t._idmap.entries()){const[c,u]=o;r.process(u)}const a={},i={registry:t,uri:e==null?void 0:e.uri,defs:s};for(const o of t._idmap.entries()){const[c,u]=o;a[c]=r.emit(u,{...e,external:i})}if(Object.keys(s).length>0){const o=r.target==="draft-2020-12"?"$defs":"definitions";a.__shared={[o]:s}}return{schemas:a}}const n=new Dw(e);return n.process(t),n.emit(t,e)}function Rt(t,e){const n=e??{seen:new Set};if(n.seen.has(t))return!1;n.seen.add(t);const s=t._zod.def;switch(s.type){case"string":case"number":case"bigint":case"boolean":case"date":case"symbol":case"undefined":case"null":case"any":case"unknown":case"never":case"void":case"literal":case"enum":case"nan":case"file":case"template_literal":return!1;case"array":return Rt(s.element,n);case"object":{for(const a in s.shape)if(Rt(s.shape[a],n))return!0;return!1}case"union":{for(const a of s.options)if(Rt(a,n))return!0;return!1}case"intersection":return Rt(s.left,n)||Rt(s.right,n);case"tuple":{for(const a of s.items)if(Rt(a,n))return!0;return!!(s.rest&&Rt(s.rest,n))}case"record":return Rt(s.keyType,n)||Rt(s.valueType,n);case"map":return Rt(s.keyType,n)||Rt(s.valueType,n);case"set":return Rt(s.valueType,n);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return Rt(s.innerType,n);case"lazy":return Rt(s.getter(),n);case"default":return Rt(s.innerType,n);case"prefault":return Rt(s.innerType,n);case"custom":return!1;case"transform":return!0;case"pipe":return Rt(s.in,n)||Rt(s.out,n);case"success":return!1;case"catch":return!1}throw new Error(`Unknown schema type: ${s.type}`)}function pt(t){if(typeof t!="object"||t===null)return!1;const e=t;if(!("_zod"in e))return!1;const n=e._zod;return typeof n=="object"&&n!==null&&"def"in n}function xt(t){if(typeof t!="object"||t===null)return!1;const e=t;if(!("_def"in e)||"_zod"in e)return!1;const n=e._def;return typeof n=="object"&&n!=null&&"typeName"in n}function gL(t){return pt(t)&&console.warn("[WARNING] Attempting to use Zod 4 schema in a context where Zod 3 schema is expected. This may cause unexpected behavior."),xt(t)}function Lt(t){return!t||typeof t!="object"||Array.isArray(t)?!1:!!(pt(t)||xt(t))}function UT(t){return typeof t=="object"&&t!==null&&"_def"in t&&typeof t._def=="object"&&t._def!==null&&"typeName"in t._def&&t._def.typeName==="ZodLiteral"}function DT(t){return pt(t)?typeof t=="object"&&t!==null&&"_zod"in t&&typeof t._zod=="object"&&t._zod!==null&&"def"in t._zod&&typeof t._zod.def=="object"&&t._zod.def!==null&&"type"in t._zod.def&&t._zod.def.type==="literal":!1}function _L(t){return!!(UT(t)||DT(t))}async function Xd(t,e){if(pt(t))try{return{success:!0,data:await wT(t,e)}}catch(n){return{success:!1,error:n}}if(xt(t))return await t.safeParseAsync(e);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}async function Yd(t,e){if(pt(t))return await wT(t,e);if(xt(t))return await t.parseAsync(e);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function yL(t,e){if(pt(t))try{return{success:!0,data:Kd(t,e)}}catch(n){return{success:!1,error:n}}if(xt(t))return t.safeParse(e);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function fl(t,e){if(pt(t))return Kd(t,e);if(xt(t))return t.parse(e);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function Pi(t){var e;if(pt(t))return(e=zt.get(t))==null?void 0:e.description;if(xt(t)||"description"in t&&typeof t.description=="string")return t.description}function wL(t){if(!Lt(t))return!1;if(xt(t)){const e=t._def;if(e.typeName==="ZodObject"){const n=t;return!n.shape||Object.keys(n.shape).length===0}if(e.typeName==="ZodRecord")return!0}if(pt(t)){const e=t._zod.def;if(e.type==="object"){const n=t;return!n.shape||Object.keys(n.shape).length===0}if(e.type==="record")return!0}return typeof t=="object"&&t!==null&&!("shape"in t)}function jg(t){return Lt(t)?xt(t)?t._def.typeName==="ZodString":pt(t)?t._zod.def.type==="string":!1:!1}function Qd(t){return typeof t=="object"&&t!==null&&"_def"in t&&typeof t._def=="object"&&t._def!==null&&"typeName"in t._def&&t._def.typeName==="ZodObject"}function Zr(t){return pt(t)?typeof t=="object"&&t!==null&&"_zod"in t&&typeof t._zod=="object"&&t._zod!==null&&"def"in t._zod&&typeof t._zod.def=="object"&&t._zod.def!==null&&"type"in t._zod.def&&t._zod.def.type==="object":!1}function eh(t){return pt(t)?typeof t=="object"&&t!==null&&"_zod"in t&&typeof t._zod=="object"&&t._zod!==null&&"def"in t._zod&&typeof t._zod.def=="object"&&t._zod.def!==null&&"type"in t._zod.def&&t._zod.def.type==="array":!1}function FT(t){return pt(t)?typeof t=="object"&&t!==null&&"_zod"in t&&typeof t._zod=="object"&&t._zod!==null&&"def"in t._zod&&typeof t._zod.def=="object"&&t._zod.def!==null&&"type"in t._zod.def&&t._zod.def.type==="optional":!1}function BT(t){return pt(t)?typeof t=="object"&&t!==null&&"_zod"in t&&typeof t._zod=="object"&&t._zod!==null&&"def"in t._zod&&typeof t._zod.def=="object"&&t._zod.def!==null&&"type"in t._zod.def&&t._zod.def.type==="nullable":!1}function rr(t){return!!(Qd(t)||Zr(t))}function gc(t){if(xt(t))return t.shape;if(pt(t))return t._zod.def.shape;throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function zT(t,e){if(xt(t))return t.extend(e);if(pt(t))return fT(t,e);throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function Ug(t){if(xt(t))return t.partial();if(pt(t))return pT(Lg,t,void 0);throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function ad(t,e=!1){if(Qd(t))return t.strict();if(Zr(t)){const n=t._zod.def.shape;if(e)for(const[a,i]of Object.entries(t._zod.def.shape)){if(Zr(i))n[a]=ad(i,e);else if(eh(i)){let c=i._zod.def.element;Zr(c)&&(c=ad(c,e)),n[a]=cn(i,{...i._zod.def,element:c})}else n[a]=i;const o=zt.get(i);o&&zt.add(n[a],o)}const r=cn(t,{...t._zod.def,shape:n,catchall:MT(RT)}),s=zt.get(t);return s&&zt.add(r,s),r}throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function Fp(t,e=!1){if(Qd(t))return t.passthrough();if(Zr(t)){const n=t._zod.def.shape;if(e)for(const[a,i]of Object.entries(t._zod.def.shape)){if(Zr(i))n[a]=Fp(i,e);else if(eh(i)){let c=i._zod.def.element;Zr(c)&&(c=Fp(c,e)),n[a]=cn(i,{...i._zod.def,element:c})}else n[a]=i;const o=zt.get(i);o&&zt.add(n[a],o)}const r=cn(t,{...t._zod.def,shape:n,catchall:PT(CT)}),s=zt.get(t);return s&&zt.add(r,s),r}throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function bL(t){if(xt(t))try{const e=t.parse(void 0);return()=>e}catch{return}if(pt(t))try{const e=Kd(t,void 0);return()=>e}catch{return}}function vL(t){return xt(t)&&"typeName"in t._def&&t._def.typeName==="ZodEffects"}function SL(t){return pt(t)&&t._zod.def.type==="pipe"}function ha(t,e,n){const r=n.get(t);if(r!==void 0)return r;if(xt(t))return vL(t)?ha(t._def.schema,e,n):t;if(pt(t)){let s=t;if(SL(t)&&(s=ha(t._zod.def.in,e,n)),e){if(Zr(s)){const i={};for(const[o,c]of Object.entries(s._zod.def.shape))i[o]=ha(c,e,n);s=cn(s,{...s._zod.def,shape:i})}else if(eh(s)){const i=ha(s._zod.def.element,e,n);s=cn(s,{...s._zod.def,element:i})}else if(FT(s)){const i=ha(s._zod.def.innerType,e,n);s=cn(s,{...s._zod.def,innerType:i})}else if(BT(s)){const i=ha(s._zod.def.innerType,e,n);s=cn(s,{...s._zod.def,innerType:i})}}const a=zt.get(t);return a&&zt.add(s,a),n.set(t,s),s}throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function HT(t,e=!1){return ha(t,e,new WeakMap)}function TL(t,e){if(xt(t)){const n=gc(t),r={};for(const[s,a]of Object.entries(n))e(s,a)?r[s]=a.optional():r[s]=a;return t.extend(r)}if(pt(t)){const n=gc(t),r={...t._zod.def.shape};for(const[i,o]of Object.entries(n))e(i,o)&&(r[i]=new Lg({type:"optional",innerType:o}));const s=cn(t,{...t._zod.def,shape:r}),a=zt.get(t);return a&&zt.add(s,a),s}throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function VT(t){return t instanceof Error&&(t.constructor.name==="ZodError"||t.constructor.name==="$ZodError")}function sf(t){return t.replace(/[^a-zA-Z-_0-9]/g,"_")}const EL=["*","_","`"];function AL(t){let e="";for(const[n,r]of Object.entries(t))e+=` classDef ${n} ${r};
95
- `;return e}function IL(t,e,n){const{firstNode:r,lastNode:s,nodeColors:a,withStyles:i=!0,curveStyle:o="linear",wrapLabelNWords:c=9}=n??{};let u=i?`%%{init: {'flowchart': {'curve': '${o}'}}}%%
96
- graph TD;
97
- `:`graph TD;
98
- `;if(i){const m="default",_={[m]:"{0}({1})"};r!==void 0&&(_[r]="{0}([{1}]):::first"),s!==void 0&&(_[s]="{0}([{1}]):::last");for(const[y,w]of Object.entries(t)){const g=w.name.split(":").pop()??"";let b=EL.some(I=>g.startsWith(I)&&g.endsWith(I))?`<p>${g}</p>`:g;Object.keys(w.metadata??{}).length&&(b+=`<hr/><small><em>${Object.entries(w.metadata??{}).map(([I,T])=>`${I} = ${T}`).join(`
99
- `)}</em></small>`);const S=(_[y]??_[m]).replace("{0}",sf(y)).replace("{1}",b);u+=` ${S}
100
- `}}const l={};for(const m of e){const _=m.source.split(":"),y=m.target.split(":"),w=_.filter((g,b)=>g===y[b]).join(":");l[w]||(l[w]=[]),l[w].push(m)}const d=new Set;function f(m){return[...m].sort((_,y)=>_.split(":").length-y.split(":").length)}function h(m,_){const y=m.length===1&&m[0].source===m[0].target;if(_&&!y){const g=_.split(":").pop();if(d.has(_))throw new Error(`Found duplicate subgraph '${g}' at '${_} -- this likely means that you're reusing a subgraph node with the same name. Please adjust your graph to have subgraph nodes with unique names.`);d.add(_),u+=` subgraph ${g}
101
- `}const w=f(Object.keys(l).filter(g=>g.startsWith(`${_}:`)&&g!==_&&g.split(":").length===_.split(":").length+1));for(const g of w)h(l[g],g);for(const g of m){const{source:b,target:S,data:I,conditional:T}=g;let x="";if(I!==void 0){let A=I;const M=A.split(" ");M.length>c&&(A=Array.from({length:Math.ceil(M.length/c)},(O,$)=>M.slice($*c,($+1)*c).join(" ")).join("&nbsp;<br>&nbsp;")),x=T?` -. &nbsp;${A}&nbsp; .-> `:` -- &nbsp;${A}&nbsp; --> `}else x=T?" -.-> ":" --> ";u+=` ${sf(b)}${x}${sf(S)};
102
- `}_&&!y&&(u+=` end
103
- `)}h(l[""]??[],"");for(const m in l)!m.includes(":")&&m!==""&&h(l[m],m);return i&&(u+=AL(a??{})),u}async function xL(t,e){let n=(e==null?void 0:e.backgroundColor)??"white";const r=(e==null?void 0:e.imageType)??"png",s=RP(t);n!==void 0&&(/^#(?:[0-9a-fA-F]{3}){1,2}$/.test(n)||(n=`!${n}`));const a=`https://mermaid.ink/img/${s}?bgColor=${n}&type=${r}`,i=await fetch(a);if(!i.ok)throw new Error(["Failed to render the graph using the Mermaid.INK API.",`Status code: ${i.status}`,`Status text: ${i.statusText}`].join(`
104
- `));return await i.blob()}const kL=Symbol("Let zodToJsonSchema decide on which parser to use"),OL={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},CL=t=>({...OL,...t}),RL=t=>{const e=CL(t),n=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([r,s])=>[s._def,{def:s._def,path:[...e.basePath,e.definitionPath,r],jsonSchema:void 0}]))}},ZT=(t,e)=>{let n=0;for(;n<t.length&&n<e.length&&t[n]===e[n];n++);return[(t.length-n).toString(),...e.slice(n)].join("/")};function Nn(t){if(t.target!=="openAi")return{};const e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?ZT(e,t.currentPath):e.join("/")}}function WT(t,e,n,r){r!=null&&r.errorMessages&&n&&(t.errorMessage={...t.errorMessage,[e]:n})}function tt(t,e,n,r,s){t[e]=n,WT(t,e,r,s)}var Ke;(function(t){t.assertEqual=s=>{};function e(s){}t.assertIs=e;function n(s){throw new Error}t.assertNever=n,t.arrayToEnum=s=>{const a={};for(const i of s)a[i]=i;return a},t.getValidEnumValues=s=>{const a=t.objectKeys(s).filter(o=>typeof s[s[o]]!="number"),i={};for(const o of a)i[o]=s[o];return t.objectValues(i)},t.objectValues=s=>t.objectKeys(s).map(function(a){return s[a]}),t.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{const a=[];for(const i in s)Object.prototype.hasOwnProperty.call(s,i)&&a.push(i);return a},t.find=(s,a)=>{for(const i of s)if(a(i))return i},t.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function r(s,a=" | "){return s.map(i=>typeof i=="string"?`'${i}'`:i).join(a)}t.joinValues=r,t.jsonStringifyReplacer=(s,a)=>typeof a=="bigint"?a.toString():a})(Ke||(Ke={}));var Fw;(function(t){t.mergeShapes=(e,n)=>({...e,...n})})(Fw||(Fw={}));const de=Ke.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),$s=t=>{switch(typeof t){case"undefined":return de.undefined;case"string":return de.string;case"number":return Number.isNaN(t)?de.nan:de.number;case"boolean":return de.boolean;case"function":return de.function;case"bigint":return de.bigint;case"symbol":return de.symbol;case"object":return Array.isArray(t)?de.array:t===null?de.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?de.promise:typeof Map<"u"&&t instanceof Map?de.map:typeof Set<"u"&&t instanceof Set?de.set:typeof Date<"u"&&t instanceof Date?de.date:de.object;default:return de.unknown}},Z=Ke.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class ws extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};const n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=e}format(e){const n=e||function(a){return a.message},r={_errors:[]},s=a=>{for(const i of a.issues)if(i.code==="invalid_union")i.unionErrors.map(s);else if(i.code==="invalid_return_type")s(i.returnTypeError);else if(i.code==="invalid_arguments")s(i.argumentsError);else if(i.path.length===0)r._errors.push(n(i));else{let o=r,c=0;for(;c<i.path.length;){const u=i.path[c];c===i.path.length-1?(o[u]=o[u]||{_errors:[]},o[u]._errors.push(n(i))):o[u]=o[u]||{_errors:[]},o=o[u],c++}}};return s(this),r}static assert(e){if(!(e instanceof ws))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Ke.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=n=>n.message){const n={},r=[];for(const s of this.issues)if(s.path.length>0){const a=s.path[0];n[a]=n[a]||[],n[a].push(e(s))}else r.push(e(s));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}}ws.create=t=>new ws(t);const Bp=(t,e)=>{let n;switch(t.code){case Z.invalid_type:t.received===de.undefined?n="Required":n=`Expected ${t.expected}, received ${t.received}`;break;case Z.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(t.expected,Ke.jsonStringifyReplacer)}`;break;case Z.unrecognized_keys:n=`Unrecognized key(s) in object: ${Ke.joinValues(t.keys,", ")}`;break;case Z.invalid_union:n="Invalid input";break;case Z.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${Ke.joinValues(t.options)}`;break;case Z.invalid_enum_value:n=`Invalid enum value. Expected ${Ke.joinValues(t.options)}, received '${t.received}'`;break;case Z.invalid_arguments:n="Invalid function arguments";break;case Z.invalid_return_type:n="Invalid function return type";break;case Z.invalid_date:n="Invalid date";break;case Z.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(n=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?n=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?n=`Invalid input: must end with "${t.validation.endsWith}"`:Ke.assertNever(t.validation):t.validation!=="regex"?n=`Invalid ${t.validation}`:n="Invalid";break;case Z.too_small:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:n="Invalid input";break;case Z.too_big:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?n=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:n="Invalid input";break;case Z.custom:n="Invalid input";break;case Z.invalid_intersection_types:n="Intersection results could not be merged";break;case Z.not_multiple_of:n=`Number must be a multiple of ${t.multipleOf}`;break;case Z.not_finite:n="Number must be finite";break;default:n=e.defaultError,Ke.assertNever(t)}return{message:n}};let $L=Bp;function NL(){return $L}const PL=t=>{const{data:e,path:n,errorMaps:r,issueData:s}=t,a=[...n,...s.path||[]],i={...s,path:a};if(s.message!==void 0)return{...s,path:a,message:s.message};let o="";const c=r.filter(u=>!!u).slice().reverse();for(const u of c)o=u(i,{data:e,defaultError:o}).message;return{...s,path:a,message:o}};function ne(t,e){const n=NL(),r=PL({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n,n===Bp?void 0:Bp].filter(s=>!!s)});t.common.issues.push(r)}class Kn{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,n){const r=[];for(const s of n){if(s.status==="aborted")return Ce;s.status==="dirty"&&e.dirty(),r.push(s.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,n){const r=[];for(const s of n){const a=await s.key,i=await s.value;r.push({key:a,value:i})}return Kn.mergeObjectSync(e,r)}static mergeObjectSync(e,n){const r={};for(const s of n){const{key:a,value:i}=s;if(a.status==="aborted"||i.status==="aborted")return Ce;a.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),a.value!=="__proto__"&&(typeof i.value<"u"||s.alwaysSet)&&(r[a.value]=i.value)}return{status:e.value,value:r}}}const Ce=Object.freeze({status:"aborted"}),Oo=t=>({status:"dirty",value:t}),ur=t=>({status:"valid",value:t}),Bw=t=>t.status==="aborted",zw=t=>t.status==="dirty",Mi=t=>t.status==="valid",id=t=>typeof Promise<"u"&&t instanceof Promise;var pe;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e==null?void 0:e.message})(pe||(pe={}));class Ys{constructor(e,n,r,s){this._cachedPath=[],this.parent=e,this.data=n,this._path=r,this._key=s}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const Hw=(t,e)=>{if(Mi(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const n=new ws(t.common.issues);return this._error=n,this._error}}};function Ue(t){if(!t)return{};const{errorMap:e,invalid_type_error:n,required_error:r,description:s}=t;if(e&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(i,o)=>{const{message:c}=t;return i.code==="invalid_enum_value"?{message:c??o.defaultError}:typeof o.data>"u"?{message:c??r??o.defaultError}:i.code!=="invalid_type"?{message:o.defaultError}:{message:c??n??o.defaultError}},description:s}}let qe=class{get description(){return this._def.description}_getType(e){return $s(e.data)}_getOrReturnCtx(e,n){return n||{common:e.parent.common,data:e.data,parsedType:$s(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Kn,ctx:{common:e.parent.common,data:e.data,parsedType:$s(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const n=this._parse(e);if(id(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(e){const n=this._parse(e);return Promise.resolve(n)}parse(e,n){const r=this.safeParse(e,n);if(r.success)return r.data;throw r.error}safeParse(e,n){const r={common:{issues:[],async:(n==null?void 0:n.async)??!1,contextualErrorMap:n==null?void 0:n.errorMap},path:(n==null?void 0:n.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:$s(e)},s=this._parseSync({data:e,path:r.path,parent:r});return Hw(r,s)}"~validate"(e){var r,s;const n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:$s(e)};if(!this["~standard"].async)try{const a=this._parseSync({data:e,path:[],parent:n});return Mi(a)?{value:a.value}:{issues:n.common.issues}}catch(a){(s=(r=a==null?void 0:a.message)==null?void 0:r.toLowerCase())!=null&&s.includes("encountered")&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:n}).then(a=>Mi(a)?{value:a.value}:{issues:n.common.issues})}async parseAsync(e,n){const r=await this.safeParseAsync(e,n);if(r.success)return r.data;throw r.error}async safeParseAsync(e,n){const r={common:{issues:[],contextualErrorMap:n==null?void 0:n.errorMap,async:!0},path:(n==null?void 0:n.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:$s(e)},s=this._parse({data:e,path:r.path,parent:r}),a=await(id(s)?s:Promise.resolve(s));return Hw(r,a)}refine(e,n){const r=s=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(s):n;return this._refinement((s,a)=>{const i=e(s),o=()=>a.addIssue({code:Z.custom,...r(s)});return typeof Promise<"u"&&i instanceof Promise?i.then(c=>c?!0:(o(),!1)):i?!0:(o(),!1)})}refinement(e,n){return this._refinement((r,s)=>e(r)?!0:(s.addIssue(typeof n=="function"?n(r,s):n),!1))}_refinement(e){return new ji({schema:this,typeName:j.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:n=>this["~validate"](n)}}optional(){return zs.create(this,this._def)}nullable(){return Ui.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Li.create(this)}promise(){return ld.create(this,this._def)}or(e){return cd.create([this,e],this._def)}and(e){return ud.create(this,e,this._def)}transform(e){return new ji({...Ue(this._def),schema:this,typeName:j.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const n=typeof e=="function"?e:()=>e;return new Kp({...Ue(this._def),innerType:this,defaultValue:n,typeName:j.ZodDefault})}brand(){return new rj({typeName:j.ZodBranded,type:this,...Ue(this._def)})}catch(e){const n=typeof e=="function"?e:()=>e;return new Jp({...Ue(this._def),innerType:this,catchValue:n,typeName:j.ZodCatch})}describe(e){const n=this.constructor;return new n({...this._def,description:e})}pipe(e){return Fg.create(this,e)}readonly(){return Xp.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};const ML=/^c[^\s-]{8,}$/i,LL=/^[0-9a-z]+$/,jL=/^[0-9A-HJKMNP-TV-Z]{26}$/i,UL=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,DL=/^[a-z0-9_-]{21}$/i,FL=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,BL=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,zL=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,HL="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let af;const VL=/^(?:(?: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])$/,ZL=/^(?:(?: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])\/(3[0-2]|[12]?[0-9])$/,WL=/^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,GL=/^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,qL=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,KL=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,GT="((\\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])))",JL=new RegExp(`^${GT}$`);function qT(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);const n=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${n}`}function XL(t){return new RegExp(`^${qT(t)}$`)}function YL(t){let e=`${GT}T${qT(t)}`;const n=[];return n.push(t.local?"Z?":"Z"),t.offset&&n.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${n.join("|")})`,new RegExp(`^${e}$`)}function QL(t,e){return!!((e==="v4"||!e)&&VL.test(t)||(e==="v6"||!e)&&WL.test(t))}function ej(t,e){if(!FL.test(t))return!1;try{const[n]=t.split(".");if(!n)return!1;const r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),s=JSON.parse(atob(r));return!(typeof s!="object"||s===null||"typ"in s&&(s==null?void 0:s.typ)!=="JWT"||!s.alg||e&&s.alg!==e)}catch{return!1}}function tj(t,e){return!!((e==="v4"||!e)&&ZL.test(t)||(e==="v6"||!e)&&GL.test(t))}let zp=class Co extends qe{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==de.string){const a=this._getOrReturnCtx(e);return ne(a,{code:Z.invalid_type,expected:de.string,received:a.parsedType}),Ce}const r=new Kn;let s;for(const a of this._def.checks)if(a.kind==="min")e.data.length<a.value&&(s=this._getOrReturnCtx(e,s),ne(s,{code:Z.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),r.dirty());else if(a.kind==="max")e.data.length>a.value&&(s=this._getOrReturnCtx(e,s),ne(s,{code:Z.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),r.dirty());else if(a.kind==="length"){const i=e.data.length>a.value,o=e.data.length<a.value;(i||o)&&(s=this._getOrReturnCtx(e,s),i?ne(s,{code:Z.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}):o&&ne(s,{code:Z.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}),r.dirty())}else if(a.kind==="email")zL.test(e.data)||(s=this._getOrReturnCtx(e,s),ne(s,{validation:"email",code:Z.invalid_string,message:a.message}),r.dirty());else if(a.kind==="emoji")af||(af=new RegExp(HL,"u")),af.test(e.data)||(s=this._getOrReturnCtx(e,s),ne(s,{validation:"emoji",code:Z.invalid_string,message:a.message}),r.dirty());else if(a.kind==="uuid")UL.test(e.data)||(s=this._getOrReturnCtx(e,s),ne(s,{validation:"uuid",code:Z.invalid_string,message:a.message}),r.dirty());else if(a.kind==="nanoid")DL.test(e.data)||(s=this._getOrReturnCtx(e,s),ne(s,{validation:"nanoid",code:Z.invalid_string,message:a.message}),r.dirty());else if(a.kind==="cuid")ML.test(e.data)||(s=this._getOrReturnCtx(e,s),ne(s,{validation:"cuid",code:Z.invalid_string,message:a.message}),r.dirty());else if(a.kind==="cuid2")LL.test(e.data)||(s=this._getOrReturnCtx(e,s),ne(s,{validation:"cuid2",code:Z.invalid_string,message:a.message}),r.dirty());else if(a.kind==="ulid")jL.test(e.data)||(s=this._getOrReturnCtx(e,s),ne(s,{validation:"ulid",code:Z.invalid_string,message:a.message}),r.dirty());else if(a.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),ne(s,{validation:"url",code:Z.invalid_string,message:a.message}),r.dirty()}else a.kind==="regex"?(a.regex.lastIndex=0,a.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),ne(s,{validation:"regex",code:Z.invalid_string,message:a.message}),r.dirty())):a.kind==="trim"?e.data=e.data.trim():a.kind==="includes"?e.data.includes(a.value,a.position)||(s=this._getOrReturnCtx(e,s),ne(s,{code:Z.invalid_string,validation:{includes:a.value,position:a.position},message:a.message}),r.dirty()):a.kind==="toLowerCase"?e.data=e.data.toLowerCase():a.kind==="toUpperCase"?e.data=e.data.toUpperCase():a.kind==="startsWith"?e.data.startsWith(a.value)||(s=this._getOrReturnCtx(e,s),ne(s,{code:Z.invalid_string,validation:{startsWith:a.value},message:a.message}),r.dirty()):a.kind==="endsWith"?e.data.endsWith(a.value)||(s=this._getOrReturnCtx(e,s),ne(s,{code:Z.invalid_string,validation:{endsWith:a.value},message:a.message}),r.dirty()):a.kind==="datetime"?YL(a).test(e.data)||(s=this._getOrReturnCtx(e,s),ne(s,{code:Z.invalid_string,validation:"datetime",message:a.message}),r.dirty()):a.kind==="date"?JL.test(e.data)||(s=this._getOrReturnCtx(e,s),ne(s,{code:Z.invalid_string,validation:"date",message:a.message}),r.dirty()):a.kind==="time"?XL(a).test(e.data)||(s=this._getOrReturnCtx(e,s),ne(s,{code:Z.invalid_string,validation:"time",message:a.message}),r.dirty()):a.kind==="duration"?BL.test(e.data)||(s=this._getOrReturnCtx(e,s),ne(s,{validation:"duration",code:Z.invalid_string,message:a.message}),r.dirty()):a.kind==="ip"?QL(e.data,a.version)||(s=this._getOrReturnCtx(e,s),ne(s,{validation:"ip",code:Z.invalid_string,message:a.message}),r.dirty()):a.kind==="jwt"?ej(e.data,a.alg)||(s=this._getOrReturnCtx(e,s),ne(s,{validation:"jwt",code:Z.invalid_string,message:a.message}),r.dirty()):a.kind==="cidr"?tj(e.data,a.version)||(s=this._getOrReturnCtx(e,s),ne(s,{validation:"cidr",code:Z.invalid_string,message:a.message}),r.dirty()):a.kind==="base64"?qL.test(e.data)||(s=this._getOrReturnCtx(e,s),ne(s,{validation:"base64",code:Z.invalid_string,message:a.message}),r.dirty()):a.kind==="base64url"?KL.test(e.data)||(s=this._getOrReturnCtx(e,s),ne(s,{validation:"base64url",code:Z.invalid_string,message:a.message}),r.dirty()):Ke.assertNever(a);return{status:r.value,value:e.data}}_regex(e,n,r){return this.refinement(s=>e.test(s),{validation:n,code:Z.invalid_string,...pe.errToObj(r)})}_addCheck(e){return new Co({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...pe.errToObj(e)})}url(e){return this._addCheck({kind:"url",...pe.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...pe.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...pe.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...pe.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...pe.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...pe.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...pe.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...pe.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...pe.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...pe.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...pe.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...pe.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof(e==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,offset:(e==null?void 0:e.offset)??!1,local:(e==null?void 0:e.local)??!1,...pe.errToObj(e==null?void 0:e.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof(e==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,...pe.errToObj(e==null?void 0:e.message)})}duration(e){return this._addCheck({kind:"duration",...pe.errToObj(e)})}regex(e,n){return this._addCheck({kind:"regex",regex:e,...pe.errToObj(n)})}includes(e,n){return this._addCheck({kind:"includes",value:e,position:n==null?void 0:n.position,...pe.errToObj(n==null?void 0:n.message)})}startsWith(e,n){return this._addCheck({kind:"startsWith",value:e,...pe.errToObj(n)})}endsWith(e,n){return this._addCheck({kind:"endsWith",value:e,...pe.errToObj(n)})}min(e,n){return this._addCheck({kind:"min",value:e,...pe.errToObj(n)})}max(e,n){return this._addCheck({kind:"max",value:e,...pe.errToObj(n)})}length(e,n){return this._addCheck({kind:"length",value:e,...pe.errToObj(n)})}nonempty(e){return this.min(1,pe.errToObj(e))}trim(){return new Co({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Co({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Co({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(const n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxLength(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}};zp.create=t=>new zp({checks:[],typeName:j.ZodString,coerce:(t==null?void 0:t.coerce)??!1,...Ue(t)});function nj(t,e){const n=(t.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,s=n>r?n:r,a=Number.parseInt(t.toFixed(s).replace(".","")),i=Number.parseInt(e.toFixed(s).replace(".",""));return a%i/10**s}let Hp=class Vp extends qe{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==de.number){const a=this._getOrReturnCtx(e);return ne(a,{code:Z.invalid_type,expected:de.number,received:a.parsedType}),Ce}let r;const s=new Kn;for(const a of this._def.checks)a.kind==="int"?Ke.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),ne(r,{code:Z.invalid_type,expected:"integer",received:"float",message:a.message}),s.dirty()):a.kind==="min"?(a.inclusive?e.data<a.value:e.data<=a.value)&&(r=this._getOrReturnCtx(e,r),ne(r,{code:Z.too_small,minimum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),s.dirty()):a.kind==="max"?(a.inclusive?e.data>a.value:e.data>=a.value)&&(r=this._getOrReturnCtx(e,r),ne(r,{code:Z.too_big,maximum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),s.dirty()):a.kind==="multipleOf"?nj(e.data,a.value)!==0&&(r=this._getOrReturnCtx(e,r),ne(r,{code:Z.not_multiple_of,multipleOf:a.value,message:a.message}),s.dirty()):a.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),ne(r,{code:Z.not_finite,message:a.message}),s.dirty()):Ke.assertNever(a);return{status:s.value,value:e.data}}gte(e,n){return this.setLimit("min",e,!0,pe.toString(n))}gt(e,n){return this.setLimit("min",e,!1,pe.toString(n))}lte(e,n){return this.setLimit("max",e,!0,pe.toString(n))}lt(e,n){return this.setLimit("max",e,!1,pe.toString(n))}setLimit(e,n,r,s){return new Vp({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:pe.toString(s)}]})}_addCheck(e){return new Vp({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:pe.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:pe.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:pe.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:pe.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:pe.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:pe.toString(n)})}finite(e){return this._addCheck({kind:"finite",message:pe.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:pe.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:pe.toString(e)})}get minValue(){let e=null;for(const n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&Ke.isInteger(e.value))}get isFinite(){let e=null,n=null;for(const r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(e===null||r.value<e)&&(e=r.value)}return Number.isFinite(n)&&Number.isFinite(e)}};Hp.create=t=>new Hp({checks:[],typeName:j.ZodNumber,coerce:(t==null?void 0:t.coerce)||!1,...Ue(t)});class _c extends qe{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==de.bigint)return this._getInvalidInput(e);let r;const s=new Kn;for(const a of this._def.checks)a.kind==="min"?(a.inclusive?e.data<a.value:e.data<=a.value)&&(r=this._getOrReturnCtx(e,r),ne(r,{code:Z.too_small,type:"bigint",minimum:a.value,inclusive:a.inclusive,message:a.message}),s.dirty()):a.kind==="max"?(a.inclusive?e.data>a.value:e.data>=a.value)&&(r=this._getOrReturnCtx(e,r),ne(r,{code:Z.too_big,type:"bigint",maximum:a.value,inclusive:a.inclusive,message:a.message}),s.dirty()):a.kind==="multipleOf"?e.data%a.value!==BigInt(0)&&(r=this._getOrReturnCtx(e,r),ne(r,{code:Z.not_multiple_of,multipleOf:a.value,message:a.message}),s.dirty()):Ke.assertNever(a);return{status:s.value,value:e.data}}_getInvalidInput(e){const n=this._getOrReturnCtx(e);return ne(n,{code:Z.invalid_type,expected:de.bigint,received:n.parsedType}),Ce}gte(e,n){return this.setLimit("min",e,!0,pe.toString(n))}gt(e,n){return this.setLimit("min",e,!1,pe.toString(n))}lte(e,n){return this.setLimit("max",e,!0,pe.toString(n))}lt(e,n){return this.setLimit("max",e,!1,pe.toString(n))}setLimit(e,n,r,s){return new _c({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:pe.toString(s)}]})}_addCheck(e){return new _c({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:pe.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:pe.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:pe.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:pe.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:pe.toString(n)})}get minValue(){let e=null;for(const n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}}_c.create=t=>new _c({checks:[],typeName:j.ZodBigInt,coerce:(t==null?void 0:t.coerce)??!1,...Ue(t)});let Zp=class extends qe{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==de.boolean){const r=this._getOrReturnCtx(e);return ne(r,{code:Z.invalid_type,expected:de.boolean,received:r.parsedType}),Ce}return ur(e.data)}};Zp.create=t=>new Zp({typeName:j.ZodBoolean,coerce:(t==null?void 0:t.coerce)||!1,...Ue(t)});class od extends qe{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==de.date){const a=this._getOrReturnCtx(e);return ne(a,{code:Z.invalid_type,expected:de.date,received:a.parsedType}),Ce}if(Number.isNaN(e.data.getTime())){const a=this._getOrReturnCtx(e);return ne(a,{code:Z.invalid_date}),Ce}const r=new Kn;let s;for(const a of this._def.checks)a.kind==="min"?e.data.getTime()<a.value&&(s=this._getOrReturnCtx(e,s),ne(s,{code:Z.too_small,message:a.message,inclusive:!0,exact:!1,minimum:a.value,type:"date"}),r.dirty()):a.kind==="max"?e.data.getTime()>a.value&&(s=this._getOrReturnCtx(e,s),ne(s,{code:Z.too_big,message:a.message,inclusive:!0,exact:!1,maximum:a.value,type:"date"}),r.dirty()):Ke.assertNever(a);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new od({...this._def,checks:[...this._def.checks,e]})}min(e,n){return this._addCheck({kind:"min",value:e.getTime(),message:pe.toString(n)})}max(e,n){return this._addCheck({kind:"max",value:e.getTime(),message:pe.toString(n)})}get minDate(){let e=null;for(const n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e!=null?new Date(e):null}}od.create=t=>new od({checks:[],coerce:(t==null?void 0:t.coerce)||!1,typeName:j.ZodDate,...Ue(t)});class Vw extends qe{_parse(e){if(this._getType(e)!==de.symbol){const r=this._getOrReturnCtx(e);return ne(r,{code:Z.invalid_type,expected:de.symbol,received:r.parsedType}),Ce}return ur(e.data)}}Vw.create=t=>new Vw({typeName:j.ZodSymbol,...Ue(t)});class Zw extends qe{_parse(e){if(this._getType(e)!==de.undefined){const r=this._getOrReturnCtx(e);return ne(r,{code:Z.invalid_type,expected:de.undefined,received:r.parsedType}),Ce}return ur(e.data)}}Zw.create=t=>new Zw({typeName:j.ZodUndefined,...Ue(t)});class Ww extends qe{_parse(e){if(this._getType(e)!==de.null){const r=this._getOrReturnCtx(e);return ne(r,{code:Z.invalid_type,expected:de.null,received:r.parsedType}),Ce}return ur(e.data)}}Ww.create=t=>new Ww({typeName:j.ZodNull,...Ue(t)});let Wp=class extends qe{constructor(){super(...arguments),this._any=!0}_parse(e){return ur(e.data)}};Wp.create=t=>new Wp({typeName:j.ZodAny,...Ue(t)});let Gw=class extends qe{constructor(){super(...arguments),this._unknown=!0}_parse(e){return ur(e.data)}};Gw.create=t=>new Gw({typeName:j.ZodUnknown,...Ue(t)});let Qs=class extends qe{_parse(e){const n=this._getOrReturnCtx(e);return ne(n,{code:Z.invalid_type,expected:de.never,received:n.parsedType}),Ce}};Qs.create=t=>new Qs({typeName:j.ZodNever,...Ue(t)});class qw extends qe{_parse(e){if(this._getType(e)!==de.undefined){const r=this._getOrReturnCtx(e);return ne(r,{code:Z.invalid_type,expected:de.void,received:r.parsedType}),Ce}return ur(e.data)}}qw.create=t=>new qw({typeName:j.ZodVoid,...Ue(t)});let Li=class pl extends qe{_parse(e){const{ctx:n,status:r}=this._processInputParams(e),s=this._def;if(n.parsedType!==de.array)return ne(n,{code:Z.invalid_type,expected:de.array,received:n.parsedType}),Ce;if(s.exactLength!==null){const i=n.data.length>s.exactLength.value,o=n.data.length<s.exactLength.value;(i||o)&&(ne(n,{code:i?Z.too_big:Z.too_small,minimum:o?s.exactLength.value:void 0,maximum:i?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),r.dirty())}if(s.minLength!==null&&n.data.length<s.minLength.value&&(ne(n,{code:Z.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),r.dirty()),s.maxLength!==null&&n.data.length>s.maxLength.value&&(ne(n,{code:Z.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((i,o)=>s.type._parseAsync(new Ys(n,i,n.path,o)))).then(i=>Kn.mergeArray(r,i));const a=[...n.data].map((i,o)=>s.type._parseSync(new Ys(n,i,n.path,o)));return Kn.mergeArray(r,a)}get element(){return this._def.type}min(e,n){return new pl({...this._def,minLength:{value:e,message:pe.toString(n)}})}max(e,n){return new pl({...this._def,maxLength:{value:e,message:pe.toString(n)}})}length(e,n){return new pl({...this._def,exactLength:{value:e,message:pe.toString(n)}})}nonempty(e){return this.min(1,e)}};Li.create=(t,e)=>new Li({type:t,minLength:null,maxLength:null,exactLength:null,typeName:j.ZodArray,...Ue(e)});function si(t){if(t instanceof bs){const e={};for(const n in t.shape){const r=t.shape[n];e[n]=zs.create(si(r))}return new bs({...t._def,shape:()=>e})}else return t instanceof Li?new Li({...t._def,type:si(t.element)}):t instanceof zs?zs.create(si(t.unwrap())):t instanceof Ui?Ui.create(si(t.unwrap())):t instanceof yc?yc.create(t.items.map(e=>si(e))):t}let bs=class gr extends qe{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape(),n=Ke.objectKeys(e);return this._cached={shape:e,keys:n},this._cached}_parse(e){if(this._getType(e)!==de.object){const u=this._getOrReturnCtx(e);return ne(u,{code:Z.invalid_type,expected:de.object,received:u.parsedType}),Ce}const{status:r,ctx:s}=this._processInputParams(e),{shape:a,keys:i}=this._getCached(),o=[];if(!(this._def.catchall instanceof Qs&&this._def.unknownKeys==="strip"))for(const u in s.data)i.includes(u)||o.push(u);const c=[];for(const u of i){const l=a[u],d=s.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new Ys(s,d,s.path,u)),alwaysSet:u in s.data})}if(this._def.catchall instanceof Qs){const u=this._def.unknownKeys;if(u==="passthrough")for(const l of o)c.push({key:{status:"valid",value:l},value:{status:"valid",value:s.data[l]}});else if(u==="strict")o.length>0&&(ne(s,{code:Z.unrecognized_keys,keys:o}),r.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const u=this._def.catchall;for(const l of o){const d=s.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new Ys(s,d,s.path,l)),alwaysSet:l in s.data})}}return s.common.async?Promise.resolve().then(async()=>{const u=[];for(const l of c){const d=await l.key,f=await l.value;u.push({key:d,value:f,alwaysSet:l.alwaysSet})}return u}).then(u=>Kn.mergeObjectSync(r,u)):Kn.mergeObjectSync(r,c)}get shape(){return this._def.shape()}strict(e){return pe.errToObj,new gr({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(n,r)=>{var a,i;const s=((i=(a=this._def).errorMap)==null?void 0:i.call(a,n,r).message)??r.defaultError;return n.code==="unrecognized_keys"?{message:pe.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new gr({...this._def,unknownKeys:"strip"})}passthrough(){return new gr({...this._def,unknownKeys:"passthrough"})}extend(e){return new gr({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new gr({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:j.ZodObject})}setKey(e,n){return this.augment({[e]:n})}catchall(e){return new gr({...this._def,catchall:e})}pick(e){const n={};for(const r of Ke.objectKeys(e))e[r]&&this.shape[r]&&(n[r]=this.shape[r]);return new gr({...this._def,shape:()=>n})}omit(e){const n={};for(const r of Ke.objectKeys(this.shape))e[r]||(n[r]=this.shape[r]);return new gr({...this._def,shape:()=>n})}deepPartial(){return si(this)}partial(e){const n={};for(const r of Ke.objectKeys(this.shape)){const s=this.shape[r];e&&!e[r]?n[r]=s:n[r]=s.optional()}return new gr({...this._def,shape:()=>n})}required(e){const n={};for(const r of Ke.objectKeys(this.shape))if(e&&!e[r])n[r]=this.shape[r];else{let a=this.shape[r];for(;a instanceof zs;)a=a._def.innerType;n[r]=a}return new gr({...this._def,shape:()=>n})}keyof(){return JT(Ke.objectKeys(this.shape))}};bs.create=(t,e)=>new bs({shape:()=>t,unknownKeys:"strip",catchall:Qs.create(),typeName:j.ZodObject,...Ue(e)});bs.strictCreate=(t,e)=>new bs({shape:()=>t,unknownKeys:"strict",catchall:Qs.create(),typeName:j.ZodObject,...Ue(e)});bs.lazycreate=(t,e)=>new bs({shape:t,unknownKeys:"strip",catchall:Qs.create(),typeName:j.ZodObject,...Ue(e)});let cd=class extends qe{_parse(e){const{ctx:n}=this._processInputParams(e),r=this._def.options;function s(a){for(const o of a)if(o.result.status==="valid")return o.result;for(const o of a)if(o.result.status==="dirty")return n.common.issues.push(...o.ctx.common.issues),o.result;const i=a.map(o=>new ws(o.ctx.common.issues));return ne(n,{code:Z.invalid_union,unionErrors:i}),Ce}if(n.common.async)return Promise.all(r.map(async a=>{const i={...n,common:{...n.common,issues:[]},parent:null};return{result:await a._parseAsync({data:n.data,path:n.path,parent:i}),ctx:i}})).then(s);{let a;const i=[];for(const c of r){const u={...n,common:{...n.common,issues:[]},parent:null},l=c._parseSync({data:n.data,path:n.path,parent:u});if(l.status==="valid")return l;l.status==="dirty"&&!a&&(a={result:l,ctx:u}),u.common.issues.length&&i.push(u.common.issues)}if(a)return n.common.issues.push(...a.ctx.common.issues),a.result;const o=i.map(c=>new ws(c));return ne(n,{code:Z.invalid_union,unionErrors:o}),Ce}}get options(){return this._def.options}};cd.create=(t,e)=>new cd({options:t,typeName:j.ZodUnion,...Ue(e)});function Gp(t,e){const n=$s(t),r=$s(e);if(t===e)return{valid:!0,data:t};if(n===de.object&&r===de.object){const s=Ke.objectKeys(e),a=Ke.objectKeys(t).filter(o=>s.indexOf(o)!==-1),i={...t,...e};for(const o of a){const c=Gp(t[o],e[o]);if(!c.valid)return{valid:!1};i[o]=c.data}return{valid:!0,data:i}}else if(n===de.array&&r===de.array){if(t.length!==e.length)return{valid:!1};const s=[];for(let a=0;a<t.length;a++){const i=t[a],o=e[a],c=Gp(i,o);if(!c.valid)return{valid:!1};s.push(c.data)}return{valid:!0,data:s}}else return n===de.date&&r===de.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}let ud=class extends qe{_parse(e){const{status:n,ctx:r}=this._processInputParams(e),s=(a,i)=>{if(Bw(a)||Bw(i))return Ce;const o=Gp(a.value,i.value);return o.valid?((zw(a)||zw(i))&&n.dirty(),{status:n.value,value:o.data}):(ne(r,{code:Z.invalid_intersection_types}),Ce)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([a,i])=>s(a,i)):s(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};ud.create=(t,e,n)=>new ud({left:t,right:e,typeName:j.ZodIntersection,...Ue(n)});let yc=class KT extends qe{_parse(e){const{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==de.array)return ne(r,{code:Z.invalid_type,expected:de.array,received:r.parsedType}),Ce;if(r.data.length<this._def.items.length)return ne(r,{code:Z.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),Ce;!this._def.rest&&r.data.length>this._def.items.length&&(ne(r,{code:Z.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());const a=[...r.data].map((i,o)=>{const c=this._def.items[o]||this._def.rest;return c?c._parse(new Ys(r,i,r.path,o)):null}).filter(i=>!!i);return r.common.async?Promise.all(a).then(i=>Kn.mergeArray(n,i)):Kn.mergeArray(n,a)}get items(){return this._def.items}rest(e){return new KT({...this._def,rest:e})}};yc.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new yc({items:t,typeName:j.ZodTuple,rest:null,...Ue(e)})};class Kw extends qe{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==de.map)return ne(r,{code:Z.invalid_type,expected:de.map,received:r.parsedType}),Ce;const s=this._def.keyType,a=this._def.valueType,i=[...r.data.entries()].map(([o,c],u)=>({key:s._parse(new Ys(r,o,r.path,[u,"key"])),value:a._parse(new Ys(r,c,r.path,[u,"value"]))}));if(r.common.async){const o=new Map;return Promise.resolve().then(async()=>{for(const c of i){const u=await c.key,l=await c.value;if(u.status==="aborted"||l.status==="aborted")return Ce;(u.status==="dirty"||l.status==="dirty")&&n.dirty(),o.set(u.value,l.value)}return{status:n.value,value:o}})}else{const o=new Map;for(const c of i){const u=c.key,l=c.value;if(u.status==="aborted"||l.status==="aborted")return Ce;(u.status==="dirty"||l.status==="dirty")&&n.dirty(),o.set(u.value,l.value)}return{status:n.value,value:o}}}}Kw.create=(t,e,n)=>new Kw({valueType:e,keyType:t,typeName:j.ZodMap,...Ue(n)});class wc extends qe{_parse(e){const{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==de.set)return ne(r,{code:Z.invalid_type,expected:de.set,received:r.parsedType}),Ce;const s=this._def;s.minSize!==null&&r.data.size<s.minSize.value&&(ne(r,{code:Z.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),n.dirty()),s.maxSize!==null&&r.data.size>s.maxSize.value&&(ne(r,{code:Z.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),n.dirty());const a=this._def.valueType;function i(c){const u=new Set;for(const l of c){if(l.status==="aborted")return Ce;l.status==="dirty"&&n.dirty(),u.add(l.value)}return{status:n.value,value:u}}const o=[...r.data.values()].map((c,u)=>a._parse(new Ys(r,c,r.path,u)));return r.common.async?Promise.all(o).then(c=>i(c)):i(o)}min(e,n){return new wc({...this._def,minSize:{value:e,message:pe.toString(n)}})}max(e,n){return new wc({...this._def,maxSize:{value:e,message:pe.toString(n)}})}size(e,n){return this.min(e,n).max(e,n)}nonempty(e){return this.min(1,e)}}wc.create=(t,e)=>new wc({valueType:t,minSize:null,maxSize:null,typeName:j.ZodSet,...Ue(e)});class Jw extends qe{get schema(){return this._def.getter()}_parse(e){const{ctx:n}=this._processInputParams(e);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}}Jw.create=(t,e)=>new Jw({getter:t,typeName:j.ZodLazy,...Ue(e)});let Xw=class extends qe{_parse(e){if(e.data!==this._def.value){const n=this._getOrReturnCtx(e);return ne(n,{received:n.data,code:Z.invalid_literal,expected:this._def.value}),Ce}return{status:"valid",value:e.data}}get value(){return this._def.value}};Xw.create=(t,e)=>new Xw({value:t,typeName:j.ZodLiteral,...Ue(e)});function JT(t,e){return new Dg({values:t,typeName:j.ZodEnum,...Ue(e)})}let Dg=class qp extends qe{_parse(e){if(typeof e.data!="string"){const n=this._getOrReturnCtx(e),r=this._def.values;return ne(n,{expected:Ke.joinValues(r),received:n.parsedType,code:Z.invalid_type}),Ce}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const n=this._getOrReturnCtx(e),r=this._def.values;return ne(n,{received:n.data,code:Z.invalid_enum_value,options:r}),Ce}return ur(e.data)}get options(){return this._def.values}get enum(){const e={};for(const n of this._def.values)e[n]=n;return e}get Values(){const e={};for(const n of this._def.values)e[n]=n;return e}get Enum(){const e={};for(const n of this._def.values)e[n]=n;return e}extract(e,n=this._def){return qp.create(e,{...this._def,...n})}exclude(e,n=this._def){return qp.create(this.options.filter(r=>!e.includes(r)),{...this._def,...n})}};Dg.create=JT;class Yw extends qe{_parse(e){const n=Ke.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==de.string&&r.parsedType!==de.number){const s=Ke.objectValues(n);return ne(r,{expected:Ke.joinValues(s),received:r.parsedType,code:Z.invalid_type}),Ce}if(this._cache||(this._cache=new Set(Ke.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const s=Ke.objectValues(n);return ne(r,{received:r.data,code:Z.invalid_enum_value,options:s}),Ce}return ur(e.data)}get enum(){return this._def.values}}Yw.create=(t,e)=>new Yw({values:t,typeName:j.ZodNativeEnum,...Ue(e)});class ld extends qe{unwrap(){return this._def.type}_parse(e){const{ctx:n}=this._processInputParams(e);if(n.parsedType!==de.promise&&n.common.async===!1)return ne(n,{code:Z.invalid_type,expected:de.promise,received:n.parsedType}),Ce;const r=n.parsedType===de.promise?n.data:Promise.resolve(n.data);return ur(r.then(s=>this._def.type.parseAsync(s,{path:n.path,errorMap:n.common.contextualErrorMap})))}}ld.create=(t,e)=>new ld({type:t,typeName:j.ZodPromise,...Ue(e)});class ji extends qe{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===j.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:n,ctx:r}=this._processInputParams(e),s=this._def.effect||null,a={addIssue:i=>{ne(r,i),i.fatal?n.abort():n.dirty()},get path(){return r.path}};if(a.addIssue=a.addIssue.bind(a),s.type==="preprocess"){const i=s.transform(r.data,a);if(r.common.async)return Promise.resolve(i).then(async o=>{if(n.value==="aborted")return Ce;const c=await this._def.schema._parseAsync({data:o,path:r.path,parent:r});return c.status==="aborted"?Ce:c.status==="dirty"||n.value==="dirty"?Oo(c.value):c});{if(n.value==="aborted")return Ce;const o=this._def.schema._parseSync({data:i,path:r.path,parent:r});return o.status==="aborted"?Ce:o.status==="dirty"||n.value==="dirty"?Oo(o.value):o}}if(s.type==="refinement"){const i=o=>{const c=s.refinement(o,a);if(r.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return o};if(r.common.async===!1){const o=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?Ce:(o.status==="dirty"&&n.dirty(),i(o.value),{status:n.value,value:o.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(o=>o.status==="aborted"?Ce:(o.status==="dirty"&&n.dirty(),i(o.value).then(()=>({status:n.value,value:o.value}))))}if(s.type==="transform")if(r.common.async===!1){const i=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!Mi(i))return Ce;const o=s.transform(i.value,a);if(o instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:o}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(i=>Mi(i)?Promise.resolve(s.transform(i.value,a)).then(o=>({status:n.value,value:o})):Ce);Ke.assertNever(s)}}ji.create=(t,e,n)=>new ji({schema:t,typeName:j.ZodEffects,effect:e,...Ue(n)});ji.createWithPreprocess=(t,e,n)=>new ji({schema:e,effect:{type:"preprocess",transform:t},typeName:j.ZodEffects,...Ue(n)});let zs=class extends qe{_parse(e){return this._getType(e)===de.undefined?ur(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};zs.create=(t,e)=>new zs({innerType:t,typeName:j.ZodOptional,...Ue(e)});let Ui=class extends qe{_parse(e){return this._getType(e)===de.null?ur(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Ui.create=(t,e)=>new Ui({innerType:t,typeName:j.ZodNullable,...Ue(e)});let Kp=class extends qe{_parse(e){const{ctx:n}=this._processInputParams(e);let r=n.data;return n.parsedType===de.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};Kp.create=(t,e)=>new Kp({innerType:t,typeName:j.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...Ue(e)});let Jp=class extends qe{_parse(e){const{ctx:n}=this._processInputParams(e),r={...n,common:{...n.common,issues:[]}},s=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return id(s)?s.then(a=>({status:"valid",value:a.status==="valid"?a.value:this._def.catchValue({get error(){return new ws(r.common.issues)},input:r.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new ws(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};Jp.create=(t,e)=>new Jp({innerType:t,typeName:j.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...Ue(e)});class Qw extends qe{_parse(e){if(this._getType(e)!==de.nan){const r=this._getOrReturnCtx(e);return ne(r,{code:Z.invalid_type,expected:de.nan,received:r.parsedType}),Ce}return{status:"valid",value:e.data}}}Qw.create=t=>new Qw({typeName:j.ZodNaN,...Ue(t)});class rj extends qe{_parse(e){const{ctx:n}=this._processInputParams(e),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}}class Fg extends qe{_parse(e){const{status:n,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{const a=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return a.status==="aborted"?Ce:a.status==="dirty"?(n.dirty(),Oo(a.value)):this._def.out._parseAsync({data:a.value,path:r.path,parent:r})})();{const s=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?Ce:s.status==="dirty"?(n.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:r.path,parent:r})}}static create(e,n){return new Fg({in:e,out:n,typeName:j.ZodPipeline})}}let Xp=class extends qe{_parse(e){const n=this._def.innerType._parse(e),r=s=>(Mi(s)&&(s.value=Object.freeze(s.value)),s);return id(n)?n.then(s=>r(s)):r(n)}unwrap(){return this._def.innerType}};Xp.create=(t,e)=>new Xp({innerType:t,typeName:j.ZodReadonly,...Ue(e)});var j;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(j||(j={}));const zn=zp.create,Au=Hp.create,of=Zp.create,eb=Wp.create;Qs.create;const sj=Li.create,br=bs.create;cd.create;ud.create;yc.create;const tb=Dg.create;ld.create;zs.create;Ui.create;function aj(t,e){var r,s,a;const n={type:"array"};return(r=t.type)!=null&&r._def&&((a=(s=t.type)==null?void 0:s._def)==null?void 0:a.typeName)!==j.ZodAny&&(n.items=Xe(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&tt(n,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&tt(n,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(tt(n,"minItems",t.exactLength.value,t.exactLength.message,e),tt(n,"maxItems",t.exactLength.value,t.exactLength.message,e)),n}function ij(t,e){const n={type:"integer",format:"int64"};if(!t.checks)return n;for(const r of t.checks)switch(r.kind){case"min":e.target==="jsonSchema7"?r.inclusive?tt(n,"minimum",r.value,r.message,e):tt(n,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(n.exclusiveMinimum=!0),tt(n,"minimum",r.value,r.message,e));break;case"max":e.target==="jsonSchema7"?r.inclusive?tt(n,"maximum",r.value,r.message,e):tt(n,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(n.exclusiveMaximum=!0),tt(n,"maximum",r.value,r.message,e));break;case"multipleOf":tt(n,"multipleOf",r.value,r.message,e);break}return n}function oj(){return{type:"boolean"}}function XT(t,e){return Xe(t.type._def,e)}const cj=(t,e)=>Xe(t.innerType._def,e);function YT(t,e,n){const r=n??e.dateStrategy;if(Array.isArray(r))return{anyOf:r.map(s=>YT(t,e,s))};switch(r){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return uj(t,e)}}const uj=(t,e)=>{const n={type:"integer",format:"unix-time"};if(e.target==="openApi3")return n;for(const r of t.checks)switch(r.kind){case"min":tt(n,"minimum",r.value,r.message,e);break;case"max":tt(n,"maximum",r.value,r.message,e);break}return n};function lj(t,e){return{...Xe(t.innerType._def,e),default:t.defaultValue()}}function dj(t,e){return e.effectStrategy==="input"?Xe(t.schema._def,e):Nn(e)}function hj(t){return{type:"string",enum:Array.from(t.values)}}const fj=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function pj(t,e){const n=[Xe(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),Xe(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(a=>!!a);let r=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0;const s=[];return n.forEach(a=>{if(fj(a))s.push(...a.allOf),a.unevaluatedProperties===void 0&&(r=void 0);else{let i=a;if("additionalProperties"in a&&a.additionalProperties===!1){const{additionalProperties:o,...c}=a;i=c}else r=void 0;s.push(i)}}),s.length?{allOf:s,...r}:void 0}function mj(t,e){const n=typeof t.value;return n!=="bigint"&&n!=="number"&&n!=="boolean"&&n!=="string"?{type:Array.isArray(t.value)?"array":"object"}:e.target==="openApi3"?{type:n==="bigint"?"integer":n,enum:[t.value]}:{type:n==="bigint"?"integer":n,const:t.value}}let cf;const dr={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(cf===void 0&&(cf=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),cf),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?: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])$/,ipv4Cidr:/^(?:(?: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])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function QT(t,e){const n={type:"string"};if(t.checks)for(const r of t.checks)switch(r.kind){case"min":tt(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value,r.message,e);break;case"max":tt(n,"maxLength",typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value,r.message,e);break;case"email":switch(e.emailStrategy){case"format:email":hr(n,"email",r.message,e);break;case"format:idn-email":hr(n,"idn-email",r.message,e);break;case"pattern:zod":mn(n,dr.email,r.message,e);break}break;case"url":hr(n,"uri",r.message,e);break;case"uuid":hr(n,"uuid",r.message,e);break;case"regex":mn(n,r.regex,r.message,e);break;case"cuid":mn(n,dr.cuid,r.message,e);break;case"cuid2":mn(n,dr.cuid2,r.message,e);break;case"startsWith":mn(n,RegExp(`^${uf(r.value,e)}`),r.message,e);break;case"endsWith":mn(n,RegExp(`${uf(r.value,e)}$`),r.message,e);break;case"datetime":hr(n,"date-time",r.message,e);break;case"date":hr(n,"date",r.message,e);break;case"time":hr(n,"time",r.message,e);break;case"duration":hr(n,"duration",r.message,e);break;case"length":tt(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value,r.message,e),tt(n,"maxLength",typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value,r.message,e);break;case"includes":mn(n,RegExp(uf(r.value,e)),r.message,e);break;case"ip":r.version!=="v6"&&hr(n,"ipv4",r.message,e),r.version!=="v4"&&hr(n,"ipv6",r.message,e);break;case"base64url":mn(n,dr.base64url,r.message,e);break;case"jwt":mn(n,dr.jwt,r.message,e);break;case"cidr":r.version!=="v6"&&mn(n,dr.ipv4Cidr,r.message,e),r.version!=="v4"&&mn(n,dr.ipv6Cidr,r.message,e);break;case"emoji":mn(n,dr.emoji(),r.message,e);break;case"ulid":mn(n,dr.ulid,r.message,e);break;case"base64":switch(e.base64Strategy){case"format:binary":hr(n,"binary",r.message,e);break;case"contentEncoding:base64":tt(n,"contentEncoding","base64",r.message,e);break;case"pattern:zod":mn(n,dr.base64,r.message,e);break}break;case"nanoid":mn(n,dr.nanoid,r.message,e);break}return n}function uf(t,e){return e.patternStrategy==="escape"?_j(t):t}const gj=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function _j(t){let e="";for(let n=0;n<t.length;n++)gj.has(t[n])||(e+="\\"),e+=t[n];return e}function hr(t,e,n,r){var s;t.format||(s=t.anyOf)!=null&&s.some(a=>a.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&r.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...n&&r.errorMessages&&{errorMessage:{format:n}}})):tt(t,"format",e,n,r)}function mn(t,e,n,r){var s;t.pattern||(s=t.allOf)!=null&&s.some(a=>a.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&r.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:nb(e,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):tt(t,"pattern",nb(e,r),n,r)}function nb(t,e){var c;if(!e.applyRegexFlags||!t.flags)return t.source;const n={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},r=n.i?t.source.toLowerCase():t.source;let s="",a=!1,i=!1,o=!1;for(let u=0;u<r.length;u++){if(a){s+=r[u],a=!1;continue}if(n.i){if(i){if(r[u].match(/[a-z]/)){o?(s+=r[u],s+=`${r[u-2]}-${r[u]}`.toUpperCase(),o=!1):r[u+1]==="-"&&((c=r[u+2])!=null&&c.match(/[a-z]/))?(s+=r[u],o=!0):s+=`${r[u]}${r[u].toUpperCase()}`;continue}}else if(r[u].match(/[a-z]/)){s+=`[${r[u]}${r[u].toUpperCase()}]`;continue}}if(n.m){if(r[u]==="^"){s+=`(^|(?<=[\r
105
- ]))`;continue}else if(r[u]==="$"){s+=`($|(?=[\r
106
- ]))`;continue}}if(n.s&&r[u]==="."){s+=i?`${r[u]}\r
107
- `:`[${r[u]}\r
108
- ]`;continue}s+=r[u],r[u]==="\\"?a=!0:i&&r[u]==="]"?i=!1:!i&&r[u]==="["&&(i=!0)}try{new RegExp(s)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return s}function eE(t,e){var r,s,a,i,o,c;if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&((r=t.keyType)==null?void 0:r._def.typeName)===j.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((u,l)=>({...u,[l]:Xe(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",l]})??Nn(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};const n={type:"object",additionalProperties:Xe(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return n;if(((s=t.keyType)==null?void 0:s._def.typeName)===j.ZodString&&((a=t.keyType._def.checks)!=null&&a.length)){const{type:u,...l}=QT(t.keyType._def,e);return{...n,propertyNames:l}}else{if(((i=t.keyType)==null?void 0:i._def.typeName)===j.ZodEnum)return{...n,propertyNames:{enum:t.keyType._def.values}};if(((o=t.keyType)==null?void 0:o._def.typeName)===j.ZodBranded&&t.keyType._def.type._def.typeName===j.ZodString&&((c=t.keyType._def.type._def.checks)!=null&&c.length)){const{type:u,...l}=XT(t.keyType._def,e);return{...n,propertyNames:l}}}return n}function yj(t,e){return e.mapStrategy==="record"?eE(t,e):{type:"array",maxItems:125,items:{type:"array",items:[Xe(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||Nn(e),Xe(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||Nn(e)],minItems:2,maxItems:2}}}function wj(t){const e=t.values,n=Object.keys(t.values).filter(s=>typeof e[e[s]]!="number").map(s=>e[s]),r=Array.from(new Set(n.map(s=>typeof s)));return{type:r.length===1?r[0]==="string"?"string":"number":["string","number"],enum:n}}function bj(t){return t.target==="openAi"?void 0:{not:Nn({...t,currentPath:[...t.currentPath,"not"]})}}function vj(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}const dd={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Sj(t,e){if(e.target==="openApi3")return rb(t,e);const n=t.options instanceof Map?Array.from(t.options.values()):t.options;if(n.every(r=>r._def.typeName in dd&&(!r._def.checks||!r._def.checks.length))){const r=n.reduce((s,a)=>{const i=dd[a._def.typeName];return i&&!s.includes(i)?[...s,i]:s},[]);return{type:r.length>1?r:r[0]}}else if(n.every(r=>r._def.typeName==="ZodLiteral"&&!r.description)){const r=n.reduce((s,a)=>{const i=typeof a._def.value;switch(i){case"string":case"number":case"boolean":return[...s,i];case"bigint":return[...s,"integer"];case"object":return a._def.value===null?[...s,"null"]:s;default:return s}},[]);if(r.length===n.length){const s=r.filter((a,i,o)=>o.indexOf(a)===i);return{type:s.length>1?s:s[0],enum:n.reduce((a,i)=>a.includes(i._def.value)?a:[...a,i._def.value],[])}}}else if(n.every(r=>r._def.typeName==="ZodEnum"))return{type:"string",enum:n.reduce((r,s)=>[...r,...s._def.values.filter(a=>!r.includes(a))],[])};return rb(t,e)}const rb=(t,e)=>{const n=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((r,s)=>Xe(r._def,{...e,currentPath:[...e.currentPath,"anyOf",`${s}`]})).filter(r=>!!r&&(!e.strictUnions||typeof r=="object"&&Object.keys(r).length>0));return n.length?{anyOf:n}:void 0};function Tj(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"?{type:dd[t.innerType._def.typeName],nullable:!0}:{type:[dd[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){const r=Xe(t.innerType._def,{...e,currentPath:[...e.currentPath]});return r&&"$ref"in r?{allOf:[r],nullable:!0}:r&&{...r,nullable:!0}}const n=Xe(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}function Ej(t,e){const n={type:"number"};if(!t.checks)return n;for(const r of t.checks)switch(r.kind){case"int":n.type="integer",WT(n,"type",r.message,e);break;case"min":e.target==="jsonSchema7"?r.inclusive?tt(n,"minimum",r.value,r.message,e):tt(n,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(n.exclusiveMinimum=!0),tt(n,"minimum",r.value,r.message,e));break;case"max":e.target==="jsonSchema7"?r.inclusive?tt(n,"maximum",r.value,r.message,e):tt(n,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(n.exclusiveMaximum=!0),tt(n,"maximum",r.value,r.message,e));break;case"multipleOf":tt(n,"multipleOf",r.value,r.message,e);break}return n}function Aj(t,e){const n=e.target==="openAi",r={type:"object",properties:{}},s=[],a=t.shape();for(const o in a){let c=a[o];if(c===void 0||c._def===void 0)continue;let u=xj(c);u&&n&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),u=!1);const l=Xe(c._def,{...e,currentPath:[...e.currentPath,"properties",o],propertyPath:[...e.currentPath,"properties",o]});l!==void 0&&(r.properties[o]=l,u||s.push(o))}s.length&&(r.required=s);const i=Ij(t,e);return i!==void 0&&(r.additionalProperties=i),r}function Ij(t,e){if(t.catchall._def.typeName!=="ZodNever")return Xe(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function xj(t){try{return t.isOptional()}catch{return!0}}const kj=(t,e)=>{var r;if(e.currentPath.toString()===((r=e.propertyPath)==null?void 0:r.toString()))return Xe(t.innerType._def,e);const n=Xe(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return n?{anyOf:[{not:Nn(e)},n]}:Nn(e)},Oj=(t,e)=>{if(e.pipeStrategy==="input")return Xe(t.in._def,e);if(e.pipeStrategy==="output")return Xe(t.out._def,e);const n=Xe(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]});return{allOf:[n,Xe(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",n?"1":"0"]})].filter(r=>r!==void 0)}};function Cj(t,e){return Xe(t.type._def,e)}function Rj(t,e){const n={type:"array",uniqueItems:!0,items:Xe(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&tt(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&tt(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}function $j(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((n,r)=>Xe(n._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[]),additionalItems:Xe(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((n,r)=>Xe(n._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[])}}function Nj(t){return{not:Nn(t)}}function Pj(t){return Nn(t)}const Mj=(t,e)=>Xe(t.innerType._def,e),Lj=(t,e,n)=>{switch(e){case j.ZodString:return QT(t,n);case j.ZodNumber:return Ej(t,n);case j.ZodObject:return Aj(t,n);case j.ZodBigInt:return ij(t,n);case j.ZodBoolean:return oj();case j.ZodDate:return YT(t,n);case j.ZodUndefined:return Nj(n);case j.ZodNull:return vj(n);case j.ZodArray:return aj(t,n);case j.ZodUnion:case j.ZodDiscriminatedUnion:return Sj(t,n);case j.ZodIntersection:return pj(t,n);case j.ZodTuple:return $j(t,n);case j.ZodRecord:return eE(t,n);case j.ZodLiteral:return mj(t,n);case j.ZodEnum:return hj(t);case j.ZodNativeEnum:return wj(t);case j.ZodNullable:return Tj(t,n);case j.ZodOptional:return kj(t,n);case j.ZodMap:return yj(t,n);case j.ZodSet:return Rj(t,n);case j.ZodLazy:return()=>t.getter()._def;case j.ZodPromise:return Cj(t,n);case j.ZodNaN:case j.ZodNever:return bj(n);case j.ZodEffects:return dj(t,n);case j.ZodAny:return Nn(n);case j.ZodUnknown:return Pj(n);case j.ZodDefault:return lj(t,n);case j.ZodBranded:return XT(t,n);case j.ZodReadonly:return Mj(t,n);case j.ZodCatch:return cj(t,n);case j.ZodPipeline:return Oj(t,n);case j.ZodFunction:case j.ZodVoid:case j.ZodSymbol:return;default:return(r=>{})()}};function Xe(t,e,n=!1){var o;const r=e.seen.get(t);if(e.override){const c=(o=e.override)==null?void 0:o.call(e,t,e,r,n);if(c!==kL)return c}if(r&&!n){const c=jj(r,e);if(c!==void 0)return c}const s={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,s);const a=Lj(t,t.typeName,e),i=typeof a=="function"?Xe(a(),e):a;if(i&&Uj(t,e,i),e.postProcess){const c=e.postProcess(i,t,e);return s.jsonSchema=i,c}return s.jsonSchema=i,i}const jj=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:ZT(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((n,r)=>e.currentPath[r]===n)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),Nn(e)):e.$refStrategy==="seen"?Nn(e):void 0}},Uj=(t,e,n)=>(t.description&&(n.description=t.description,e.markdownDescription&&(n.markdownDescription=t.description)),n),Dj=(t,e)=>{const n=RL(e);let r=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((o,[c,u])=>({...o,[c]:Xe(u._def,{...n,currentPath:[...n.basePath,n.definitionPath,c]},!0)??Nn(n)}),{}):void 0;const s=typeof e=="string"?e:e==null?void 0:e.name,a=Xe(t._def,n,!1)??Nn(n);n.flags.hasReferencedOpenAiAnyType&&(r||(r={}),r[n.openAiAnyTypeName]||(r[n.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:n.$refStrategy==="relative"?"1":[...n.basePath,n.definitionPath,n.openAiAnyTypeName].join("/")}}));const i=s===void 0?r?{...a,[n.definitionPath]:r}:a:{$ref:[...n.$refStrategy==="relative"?[]:n.basePath,n.definitionPath,s].join("/"),[n.definitionPath]:{...r,[s]:a}};return n.target==="jsonSchema7"?i.$schema="http://json-schema.org/draft-07/schema#":(n.target==="jsonSchema2019-09"||n.target==="openAi")&&(i.$schema="https://json-schema.org/draft/2019-09/schema#"),n.target==="openAi"&&("anyOf"in i||"oneOf"in i||"allOf"in i||"type"in i&&Array.isArray(i.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),i};var Fj=ue({isSerializableSchema:()=>cr,isStandardJsonSchema:()=>Bg,isStandardSchema:()=>tE});function tE(t){return(typeof t=="object"||typeof t=="function")&&t!==null&&"~standard"in t&&typeof t["~standard"]=="object"&&t["~standard"]!==null&&"validate"in t["~standard"]}function Bg(t){return(typeof t=="object"||typeof t=="function")&&t!==null&&"~standard"in t&&typeof t["~standard"]=="object"&&t["~standard"]!==null&&"jsonSchema"in t["~standard"]}function cr(t){return tE(t)&&Bg(t)}function Ca(t,e){const n=typeof t;if(n!==typeof e)return!1;if(Array.isArray(t)){if(!Array.isArray(e))return!1;const r=t.length;if(r!==e.length)return!1;for(let s=0;s<r;s++)if(!Ca(t[s],e[s]))return!1;return!0}if(n==="object"){if(!t||!e)return t===e;const r=Object.keys(t),s=Object.keys(e);if(r.length!==s.length)return!1;for(const i of r)if(!Ca(t[i],e[i]))return!1;return!0}return t===e}function _r(t){return encodeURI(Bj(t))}function Bj(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}const zj={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},Hj={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},Vj={id:!0,$id:!0,$ref:!0,$schema:!0,$anchor:!0,$vocabulary:!0,$comment:!0,default:!0,enum:!0,const:!0,required:!0,type:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};let Zj=typeof self<"u"&&self.location&&self.location.origin!=="null"?new URL(self.location.origin+self.location.pathname+location.search):new URL("https://github.com/cfworker");function js(t,e=Object.create(null),n=Zj,r=""){if(t&&typeof t=="object"&&!Array.isArray(t)){const a=t.$id||t.id;if(a){const i=new URL(a,n.href);i.hash.length>1?e[i.href]=t:(i.hash="",r===""?n=i:js(t,e,n))}}else if(t!==!0&&t!==!1)return e;const s=n.href+(r?"#"+r:"");if(e[s]!==void 0)throw new Error(`Duplicate schema URI "${s}".`);if(e[s]=t,t===!0||t===!1)return e;if(t.__absolute_uri__===void 0&&Object.defineProperty(t,"__absolute_uri__",{enumerable:!1,value:s}),t.$ref&&t.__absolute_ref__===void 0){const a=new URL(t.$ref,n.href);a.hash=a.hash,Object.defineProperty(t,"__absolute_ref__",{enumerable:!1,value:a.href})}if(t.$recursiveRef&&t.__absolute_recursive_ref__===void 0){const a=new URL(t.$recursiveRef,n.href);a.hash=a.hash,Object.defineProperty(t,"__absolute_recursive_ref__",{enumerable:!1,value:a.href})}if(t.$anchor){const a=new URL("#"+t.$anchor,n.href);e[a.href]=t}for(let a in t){if(Vj[a])continue;const i=`${r}/${_r(a)}`,o=t[a];if(Array.isArray(o)){if(zj[a]){const c=o.length;for(let u=0;u<c;u++)js(o[u],e,n,`${i}/${u}`)}}else if(Hj[a])for(let c in o)js(o[c],e,n,`${i}/${_r(c)}`);else js(o,e,n,i)}return e}const Wj=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,Gj=[0,31,28,31,30,31,30,31,31,30,31,30,31],qj=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,Kj=/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,Jj=/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,Xj=/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,Yj=/^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,Qj=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,e4=/^(?:\/(?:[^~/]|~0|~1)*)*$/,t4=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,n4=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,r4=t=>{if(t[0]==='"')return!1;const[e,n,...r]=t.split("@");return!e||!n||r.length!==0||e.length>64||n.length>253||e[0]==="."||e.endsWith(".")||e.includes("..")||!/^[a-z0-9.-]+$/i.test(n)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(e)?!1:n.split(".").every(s=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(s))},s4=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,a4=/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,i4=t=>t.length>1&&t.length<80&&(/^P\d+([.,]\d+)?W$/.test(t)||/^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(t)&&/^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(t));function $r(t){return t.test.bind(t)}const sb={date:nE,time:rE.bind(void 0,!1),"date-time":u4,duration:i4,uri:h4,"uri-reference":$r(Jj),"uri-template":$r(Xj),url:$r(Yj),email:r4,hostname:$r(Kj),ipv4:$r(s4),ipv6:$r(a4),regex:p4,uuid:$r(Qj),"json-pointer":$r(e4),"json-pointer-uri-fragment":$r(t4),"relative-json-pointer":$r(n4)};function o4(t){return t%4===0&&(t%100!==0||t%400===0)}function nE(t){const e=t.match(Wj);if(!e)return!1;const n=+e[1],r=+e[2],s=+e[3];return r>=1&&r<=12&&s>=1&&s<=(r==2&&o4(n)?29:Gj[r])}function rE(t,e){const n=e.match(qj);if(!n)return!1;const r=+n[1],s=+n[2],a=+n[3],i=!!n[5];return(r<=23&&s<=59&&a<=59||r==23&&s==59&&a==60)&&(!t||i)}const c4=/t|\s/i;function u4(t){const e=t.split(c4);return e.length==2&&nE(e[0])&&rE(!0,e[1])}const l4=/\/|:/,d4=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function h4(t){return l4.test(t)&&d4.test(t)}const f4=/[^\\]\\Z/;function p4(t){if(f4.test(t))return!1;try{return new RegExp(t,"u"),!0}catch{return!1}}function m4(t){let e=0,n=t.length,r=0,s;for(;r<n;)e++,s=t.charCodeAt(r++),s>=55296&&s<=56319&&r<n&&(s=t.charCodeAt(r),(s&64512)==56320&&r++);return e}function gt(t,e,n="2019-09",r=js(e),s=!0,a=null,i="#",o="#",c=Object.create(null)){if(e===!0)return{valid:!0,errors:[]};if(e===!1)return{valid:!1,errors:[{instanceLocation:i,keyword:"false",keywordLocation:i,error:"False boolean schema."}]};const u=typeof t;let l;switch(u){case"boolean":case"number":case"string":l=u;break;case"object":t===null?l="null":Array.isArray(t)?l="array":l="object";break;default:throw new Error(`Instances of "${u}" type are not supported.`)}const{$ref:d,$recursiveRef:f,$recursiveAnchor:h,type:m,const:_,enum:y,required:w,not:g,anyOf:b,allOf:S,oneOf:I,if:T,then:x,else:A,format:M,properties:O,patternProperties:$,additionalProperties:H,unevaluatedProperties:J,minProperties:Y,maxProperties:me,propertyNames:te,dependentRequired:Be,dependentSchemas:P,dependencies:z,prefixItems:Q,items:se,additionalItems:q,unevaluatedItems:re,contains:ve,minContains:ie,maxContains:E,minItems:v,maxItems:N,uniqueItems:k,minimum:ge,maximum:Se,exclusiveMinimum:Ye,exclusiveMaximum:Ze,multipleOf:it,minLength:mt,maxLength:Re,pattern:At,__absolute_ref__:nn,__absolute_recursive_ref__:Xn}=e,L=[];if(h===!0&&a===null&&(a=e),f==="#"){const we=a===null?r[Xn]:a,_e=`${o}/$recursiveRef`,Te=gt(t,a===null?e:a,n,r,s,we,i,_e,c);Te.valid||L.push({instanceLocation:i,keyword:"$recursiveRef",keywordLocation:_e,error:"A subschema had errors."},...Te.errors)}if(d!==void 0){const _e=r[nn||d];if(_e===void 0){let X=`Unresolved $ref "${d}".`;throw nn&&nn!==d&&(X+=` Absolute URI "${nn}".`),X+=`
109
- Known schemas:
110
- - ${Object.keys(r).join(`
111
- - `)}`,new Error(X)}const Te=`${o}/$ref`,G=gt(t,_e,n,r,s,a,i,Te,c);if(G.valid||L.push({instanceLocation:i,keyword:"$ref",keywordLocation:Te,error:"A subschema had errors."},...G.errors),n==="4"||n==="7")return{valid:L.length===0,errors:L}}if(Array.isArray(m)){let we=m.length,_e=!1;for(let Te=0;Te<we;Te++)if(l===m[Te]||m[Te]==="integer"&&l==="number"&&t%1===0&&t===t){_e=!0;break}_e||L.push({instanceLocation:i,keyword:"type",keywordLocation:`${o}/type`,error:`Instance type "${l}" is invalid. Expected "${m.join('", "')}".`})}else m==="integer"?(l!=="number"||t%1||t!==t)&&L.push({instanceLocation:i,keyword:"type",keywordLocation:`${o}/type`,error:`Instance type "${l}" is invalid. Expected "${m}".`}):m!==void 0&&l!==m&&L.push({instanceLocation:i,keyword:"type",keywordLocation:`${o}/type`,error:`Instance type "${l}" is invalid. Expected "${m}".`});if(_!==void 0&&(l==="object"||l==="array"?Ca(t,_)||L.push({instanceLocation:i,keyword:"const",keywordLocation:`${o}/const`,error:`Instance does not match ${JSON.stringify(_)}.`}):t!==_&&L.push({instanceLocation:i,keyword:"const",keywordLocation:`${o}/const`,error:`Instance does not match ${JSON.stringify(_)}.`})),y!==void 0&&(l==="object"||l==="array"?y.some(we=>Ca(t,we))||L.push({instanceLocation:i,keyword:"enum",keywordLocation:`${o}/enum`,error:`Instance does not match any of ${JSON.stringify(y)}.`}):y.some(we=>t===we)||L.push({instanceLocation:i,keyword:"enum",keywordLocation:`${o}/enum`,error:`Instance does not match any of ${JSON.stringify(y)}.`})),g!==void 0){const we=`${o}/not`;gt(t,g,n,r,s,a,i,we).valid&&L.push({instanceLocation:i,keyword:"not",keywordLocation:we,error:'Instance matched "not" schema.'})}let rn=[];if(b!==void 0){const we=`${o}/anyOf`,_e=L.length;let Te=!1;for(let G=0;G<b.length;G++){const X=b[G],Ie=Object.create(c),Ee=gt(t,X,n,r,s,h===!0?a:null,i,`${we}/${G}`,Ie);L.push(...Ee.errors),Te=Te||Ee.valid,Ee.valid&&rn.push(Ie)}Te?L.length=_e:L.splice(_e,0,{instanceLocation:i,keyword:"anyOf",keywordLocation:we,error:"Instance does not match any subschemas."})}if(S!==void 0){const we=`${o}/allOf`,_e=L.length;let Te=!0;for(let G=0;G<S.length;G++){const X=S[G],Ie=Object.create(c),Ee=gt(t,X,n,r,s,h===!0?a:null,i,`${we}/${G}`,Ie);L.push(...Ee.errors),Te=Te&&Ee.valid,Ee.valid&&rn.push(Ie)}Te?L.length=_e:L.splice(_e,0,{instanceLocation:i,keyword:"allOf",keywordLocation:we,error:"Instance does not match every subschema."})}if(I!==void 0){const we=`${o}/oneOf`,_e=L.length,Te=I.filter((G,X)=>{const Ie=Object.create(c),Ee=gt(t,G,n,r,s,h===!0?a:null,i,`${we}/${X}`,Ie);return L.push(...Ee.errors),Ee.valid&&rn.push(Ie),Ee.valid}).length;Te===1?L.length=_e:L.splice(_e,0,{instanceLocation:i,keyword:"oneOf",keywordLocation:we,error:`Instance does not match exactly one subschema (${Te} matches).`})}if((l==="object"||l==="array")&&Object.assign(c,...rn),T!==void 0){const we=`${o}/if`;if(gt(t,T,n,r,s,a,i,we,c).valid){if(x!==void 0){const Te=gt(t,x,n,r,s,a,i,`${o}/then`,c);Te.valid||L.push({instanceLocation:i,keyword:"if",keywordLocation:we,error:'Instance does not match "then" schema.'},...Te.errors)}}else if(A!==void 0){const Te=gt(t,A,n,r,s,a,i,`${o}/else`,c);Te.valid||L.push({instanceLocation:i,keyword:"if",keywordLocation:we,error:'Instance does not match "else" schema.'},...Te.errors)}}if(l==="object"){if(w!==void 0)for(const G of w)G in t||L.push({instanceLocation:i,keyword:"required",keywordLocation:`${o}/required`,error:`Instance does not have required property "${G}".`});const we=Object.keys(t);if(Y!==void 0&&we.length<Y&&L.push({instanceLocation:i,keyword:"minProperties",keywordLocation:`${o}/minProperties`,error:`Instance does not have at least ${Y} properties.`}),me!==void 0&&we.length>me&&L.push({instanceLocation:i,keyword:"maxProperties",keywordLocation:`${o}/maxProperties`,error:`Instance does not have at least ${me} properties.`}),te!==void 0){const G=`${o}/propertyNames`;for(const X in t){const Ie=`${i}/${_r(X)}`,Ee=gt(X,te,n,r,s,a,Ie,G);Ee.valid||L.push({instanceLocation:i,keyword:"propertyNames",keywordLocation:G,error:`Property name "${X}" does not match schema.`},...Ee.errors)}}if(Be!==void 0){const G=`${o}/dependantRequired`;for(const X in Be)if(X in t){const Ie=Be[X];for(const Ee of Ie)Ee in t||L.push({instanceLocation:i,keyword:"dependentRequired",keywordLocation:G,error:`Instance has "${X}" but does not have "${Ee}".`})}}if(P!==void 0)for(const G in P){const X=`${o}/dependentSchemas`;if(G in t){const Ie=gt(t,P[G],n,r,s,a,i,`${X}/${_r(G)}`,c);Ie.valid||L.push({instanceLocation:i,keyword:"dependentSchemas",keywordLocation:X,error:`Instance has "${G}" but does not match dependant schema.`},...Ie.errors)}}if(z!==void 0){const G=`${o}/dependencies`;for(const X in z)if(X in t){const Ie=z[X];if(Array.isArray(Ie))for(const Ee of Ie)Ee in t||L.push({instanceLocation:i,keyword:"dependencies",keywordLocation:G,error:`Instance has "${X}" but does not have "${Ee}".`});else{const Ee=gt(t,Ie,n,r,s,a,i,`${G}/${_r(X)}`);Ee.valid||L.push({instanceLocation:i,keyword:"dependencies",keywordLocation:G,error:`Instance has "${X}" but does not match dependant schema.`},...Ee.errors)}}}const _e=Object.create(null);let Te=!1;if(O!==void 0){const G=`${o}/properties`;for(const X in O){if(!(X in t))continue;const Ie=`${i}/${_r(X)}`,Ee=gt(t[X],O[X],n,r,s,a,Ie,`${G}/${_r(X)}`);if(Ee.valid)c[X]=_e[X]=!0;else if(Te=s,L.push({instanceLocation:i,keyword:"properties",keywordLocation:G,error:`Property "${X}" does not match schema.`},...Ee.errors),Te)break}}if(!Te&&$!==void 0){const G=`${o}/patternProperties`;for(const X in $){const Ie=new RegExp(X,"u"),Ee=$[X];for(const W in t){if(!Ie.test(W))continue;const ze=`${i}/${_r(W)}`,ot=gt(t[W],Ee,n,r,s,a,ze,`${G}/${_r(X)}`);ot.valid?c[W]=_e[W]=!0:(Te=s,L.push({instanceLocation:i,keyword:"patternProperties",keywordLocation:G,error:`Property "${W}" matches pattern "${X}" but does not match associated schema.`},...ot.errors))}}}if(!Te&&H!==void 0){const G=`${o}/additionalProperties`;for(const X in t){if(_e[X])continue;const Ie=`${i}/${_r(X)}`,Ee=gt(t[X],H,n,r,s,a,Ie,G);Ee.valid?c[X]=!0:(Te=s,L.push({instanceLocation:i,keyword:"additionalProperties",keywordLocation:G,error:`Property "${X}" does not match additional properties schema.`},...Ee.errors))}}else if(!Te&&J!==void 0){const G=`${o}/unevaluatedProperties`;for(const X in t)if(!c[X]){const Ie=`${i}/${_r(X)}`,Ee=gt(t[X],J,n,r,s,a,Ie,G);Ee.valid?c[X]=!0:L.push({instanceLocation:i,keyword:"unevaluatedProperties",keywordLocation:G,error:`Property "${X}" does not match unevaluated properties schema.`},...Ee.errors)}}}else if(l==="array"){N!==void 0&&t.length>N&&L.push({instanceLocation:i,keyword:"maxItems",keywordLocation:`${o}/maxItems`,error:`Array has too many items (${t.length} > ${N}).`}),v!==void 0&&t.length<v&&L.push({instanceLocation:i,keyword:"minItems",keywordLocation:`${o}/minItems`,error:`Array has too few items (${t.length} < ${v}).`});const we=t.length;let _e=0,Te=!1;if(Q!==void 0){const G=`${o}/prefixItems`,X=Math.min(Q.length,we);for(;_e<X;_e++){const Ie=gt(t[_e],Q[_e],n,r,s,a,`${i}/${_e}`,`${G}/${_e}`);if(c[_e]=!0,!Ie.valid&&(Te=s,L.push({instanceLocation:i,keyword:"prefixItems",keywordLocation:G,error:"Items did not match schema."},...Ie.errors),Te))break}}if(se!==void 0){const G=`${o}/items`;if(Array.isArray(se)){const X=Math.min(se.length,we);for(;_e<X;_e++){const Ie=gt(t[_e],se[_e],n,r,s,a,`${i}/${_e}`,`${G}/${_e}`);if(c[_e]=!0,!Ie.valid&&(Te=s,L.push({instanceLocation:i,keyword:"items",keywordLocation:G,error:"Items did not match schema."},...Ie.errors),Te))break}}else for(;_e<we;_e++){const X=gt(t[_e],se,n,r,s,a,`${i}/${_e}`,G);if(c[_e]=!0,!X.valid&&(Te=s,L.push({instanceLocation:i,keyword:"items",keywordLocation:G,error:"Items did not match schema."},...X.errors),Te))break}if(!Te&&q!==void 0){const X=`${o}/additionalItems`;for(;_e<we;_e++){const Ie=gt(t[_e],q,n,r,s,a,`${i}/${_e}`,X);c[_e]=!0,Ie.valid||(Te=s,L.push({instanceLocation:i,keyword:"additionalItems",keywordLocation:X,error:"Items did not match additional items schema."},...Ie.errors))}}}if(ve!==void 0)if(we===0&&ie===void 0)L.push({instanceLocation:i,keyword:"contains",keywordLocation:`${o}/contains`,error:"Array is empty. It must contain at least one item matching the schema."});else if(ie!==void 0&&we<ie)L.push({instanceLocation:i,keyword:"minContains",keywordLocation:`${o}/minContains`,error:`Array has less items (${we}) than minContains (${ie}).`});else{const G=`${o}/contains`,X=L.length;let Ie=0;for(let Ee=0;Ee<we;Ee++){const W=gt(t[Ee],ve,n,r,s,a,`${i}/${Ee}`,G);W.valid?(c[Ee]=!0,Ie++):L.push(...W.errors)}Ie>=(ie||0)&&(L.length=X),ie===void 0&&E===void 0&&Ie===0?L.splice(X,0,{instanceLocation:i,keyword:"contains",keywordLocation:G,error:"Array does not contain item matching schema."}):ie!==void 0&&Ie<ie?L.push({instanceLocation:i,keyword:"minContains",keywordLocation:`${o}/minContains`,error:`Array must contain at least ${ie} items matching schema. Only ${Ie} items were found.`}):E!==void 0&&Ie>E&&L.push({instanceLocation:i,keyword:"maxContains",keywordLocation:`${o}/maxContains`,error:`Array may contain at most ${E} items matching schema. ${Ie} items were found.`})}if(!Te&&re!==void 0){const G=`${o}/unevaluatedItems`;for(_e;_e<we;_e++){if(c[_e])continue;const X=gt(t[_e],re,n,r,s,a,`${i}/${_e}`,G);c[_e]=!0,X.valid||L.push({instanceLocation:i,keyword:"unevaluatedItems",keywordLocation:G,error:"Items did not match unevaluated items schema."},...X.errors)}}if(k)for(let G=0;G<we;G++){const X=t[G],Ie=typeof X=="object"&&X!==null;for(let Ee=0;Ee<we;Ee++){if(G===Ee)continue;const W=t[Ee];(X===W||Ie&&(typeof W=="object"&&W!==null)&&Ca(X,W))&&(L.push({instanceLocation:i,keyword:"uniqueItems",keywordLocation:`${o}/uniqueItems`,error:`Duplicate items at indexes ${G} and ${Ee}.`}),G=Number.MAX_SAFE_INTEGER,Ee=Number.MAX_SAFE_INTEGER)}}}else if(l==="number"){if(n==="4"?(ge!==void 0&&(Ye===!0&&t<=ge||t<ge)&&L.push({instanceLocation:i,keyword:"minimum",keywordLocation:`${o}/minimum`,error:`${t} is less than ${Ye?"or equal to ":""} ${ge}.`}),Se!==void 0&&(Ze===!0&&t>=Se||t>Se)&&L.push({instanceLocation:i,keyword:"maximum",keywordLocation:`${o}/maximum`,error:`${t} is greater than ${Ze?"or equal to ":""} ${Se}.`})):(ge!==void 0&&t<ge&&L.push({instanceLocation:i,keyword:"minimum",keywordLocation:`${o}/minimum`,error:`${t} is less than ${ge}.`}),Se!==void 0&&t>Se&&L.push({instanceLocation:i,keyword:"maximum",keywordLocation:`${o}/maximum`,error:`${t} is greater than ${Se}.`}),Ye!==void 0&&t<=Ye&&L.push({instanceLocation:i,keyword:"exclusiveMinimum",keywordLocation:`${o}/exclusiveMinimum`,error:`${t} is less than ${Ye}.`}),Ze!==void 0&&t>=Ze&&L.push({instanceLocation:i,keyword:"exclusiveMaximum",keywordLocation:`${o}/exclusiveMaximum`,error:`${t} is greater than or equal to ${Ze}.`})),it!==void 0){const we=t%it;Math.abs(0-we)>=11920929e-14&&Math.abs(it-we)>=11920929e-14&&L.push({instanceLocation:i,keyword:"multipleOf",keywordLocation:`${o}/multipleOf`,error:`${t} is not a multiple of ${it}.`})}}else if(l==="string"){const we=mt===void 0&&Re===void 0?0:m4(t);mt!==void 0&&we<mt&&L.push({instanceLocation:i,keyword:"minLength",keywordLocation:`${o}/minLength`,error:`String is too short (${we} < ${mt}).`}),Re!==void 0&&we>Re&&L.push({instanceLocation:i,keyword:"maxLength",keywordLocation:`${o}/maxLength`,error:`String is too long (${we} > ${Re}).`}),At!==void 0&&!new RegExp(At,"u").test(t)&&L.push({instanceLocation:i,keyword:"pattern",keywordLocation:`${o}/pattern`,error:"String does not match pattern."}),M!==void 0&&sb[M]&&!sb[M](t)&&L.push({instanceLocation:i,keyword:"format",keywordLocation:`${o}/format`,error:`String does not match format "${M}".`})}return{valid:L.length===0,errors:L}}class g4{constructor(e,n="2019-09",r=!0){p(this,"schema");p(this,"draft");p(this,"shortCircuit");p(this,"lookup");this.schema=e,this.draft=n,this.shortCircuit=r,this.lookup=js(e)}validate(e){return gt(e,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(e,n){n&&(e={...e,$id:n}),js(e,this.lookup)}}var _4=ue({Validator:()=>g4,deepCompareStrict:()=>Ca,toJsonSchema:()=>lt,validatesOnlyStrings:()=>ec});const ab=new WeakMap;function lt(t,e){const n=!e&&t!=null&&typeof t=="object";if(n){const s=ab.get(t);if(s)return s}let r;if(Bg(t)&&!pt(t))r=t["~standard"].jsonSchema.input({target:"draft-07"});else if(pt(t)){const s=HT(t,!0);Zr(s)?r=Dp(ad(s,!0),e):r=Dp(t,e)}else xt(t)?r=Dj(t):r=t;return n&&r!=null&&typeof r=="object"&&ab.set(t,r),r}function ec(t){if(!t||typeof t!="object"||Object.keys(t).length===0||Array.isArray(t))return!1;if("type"in t)return typeof t.type=="string"?t.type==="string":Array.isArray(t.type)?t.type.every(e=>e==="string"):!1;if("enum"in t)return Array.isArray(t.enum)&&t.enum.length>0&&t.enum.every(e=>typeof e=="string");if("const"in t)return typeof t.const=="string";if("allOf"in t&&Array.isArray(t.allOf))return t.allOf.some(e=>ec(e));if("anyOf"in t&&Array.isArray(t.anyOf)||"oneOf"in t&&Array.isArray(t.oneOf)){const e="anyOf"in t?t.anyOf:t.oneOf;return e.length>0&&e.every(n=>ec(n))}if("not"in t)return!1;if("$ref"in t&&typeof t.$ref=="string"){const e=t.$ref,n=js(t);return n[e]?ec(n[e]):!1}return!1}var y4=ue({Graph:()=>bc});function w4(t,e){if(t!==void 0&&!Fs(t))return t;if(Og(e))try{let n=e.getName();return n=n.startsWith("Runnable")?n.slice(8):n,n}catch{return e.getName()}else return e.name??"UnknownSchema"}function b4(t){return Og(t.data)?{type:"runnable",data:{id:t.data.lc_id,name:t.data.getName()}}:{type:"schema",data:{...lt(t.data.schema),title:t.data.name}}}var bc=class sE{constructor(e){p(this,"nodes",{});p(this,"edges",[]);this.nodes=(e==null?void 0:e.nodes)??this.nodes,this.edges=(e==null?void 0:e.edges)??this.edges}toJSON(){const e={};return Object.values(this.nodes).forEach((n,r)=>{e[n.id]=Fs(n.id)?r:n.id}),{nodes:Object.values(this.nodes).map(n=>({id:e[n.id],...b4(n)})),edges:this.edges.map(n=>{const r={source:e[n.source],target:e[n.target]};return typeof n.data<"u"&&(r.data=n.data),typeof n.conditional<"u"&&(r.conditional=n.conditional),r})}}addNode(e,n,r){if(n!==void 0&&this.nodes[n]!==void 0)throw new Error(`Node with id ${n} already exists`);const s=n??Hc(),a={id:s,data:e,name:w4(n,e),metadata:r};return this.nodes[s]=a,a}removeNode(e){delete this.nodes[e.id],this.edges=this.edges.filter(n=>n.source!==e.id&&n.target!==e.id)}addEdge(e,n,r,s){if(this.nodes[e.id]===void 0)throw new Error(`Source node ${e.id} not in graph`);if(this.nodes[n.id]===void 0)throw new Error(`Target node ${n.id} not in graph`);const a={source:e.id,target:n.id,data:r,conditional:s};return this.edges.push(a),a}firstNode(){return ib(this)}lastNode(){return ob(this)}extend(e,n=""){let r=n;Object.values(e.nodes).map(c=>c.id).every(Fs)&&(r="");const s=c=>r?`${r}:${c}`:c;Object.entries(e.nodes).forEach(([c,u])=>{this.nodes[s(c)]={...u,id:s(c)}});const a=e.edges.map(c=>({...c,source:s(c.source),target:s(c.target)}));this.edges=[...this.edges,...a];const i=e.firstNode(),o=e.lastNode();return[i?{id:s(i.id),data:i.data}:void 0,o?{id:s(o.id),data:o.data}:void 0]}trimFirstNode(){const e=this.firstNode();e&&ib(this,[e.id])&&this.removeNode(e)}trimLastNode(){const e=this.lastNode();e&&ob(this,[e.id])&&this.removeNode(e)}reid(){const e=Object.fromEntries(Object.values(this.nodes).map(s=>[s.id,s.name])),n=new Map;Object.values(e).forEach(s=>{n.set(s,(n.get(s)||0)+1)});const r=s=>{const a=e[s];return Fs(s)&&n.get(a)===1?a:s};return new sE({nodes:Object.fromEntries(Object.entries(this.nodes).map(([s,a])=>[r(s),{...a,id:r(s)}])),edges:this.edges.map(s=>({...s,source:r(s.source),target:r(s.target)}))})}drawMermaid(e){const{withStyles:n,curveStyle:r,nodeColors:s={default:"fill:#f2f0ff,line-height:1.2",first:"fill-opacity:0",last:"fill:#bfb6fc"},wrapLabelNWords:a}=e??{},i=this.reid(),o=i.firstNode(),c=i.lastNode();return IL(i.nodes,i.edges,{firstNode:o==null?void 0:o.id,lastNode:c==null?void 0:c.id,withStyles:n,curveStyle:r,nodeColors:s,wrapLabelNWords:a})}async drawMermaidPng(e){return xL(this.drawMermaid(e),{backgroundColor:e==null?void 0:e.backgroundColor})}};function ib(t,e=[]){const n=new Set(t.edges.filter(s=>!e.includes(s.source)).map(s=>s.target)),r=[];for(const s of Object.values(t.nodes))!e.includes(s.id)&&!n.has(s.id)&&r.push(s);return r.length===1?r[0]:void 0}function ob(t,e=[]){const n=new Set(t.edges.filter(s=>!e.includes(s.target)).map(s=>s.source)),r=[];for(const s of Object.values(t.nodes))!e.includes(s.id)&&!n.has(s.id)&&r.push(s);return r.length===1?r[0]:void 0}function v4(t){const e=new TextEncoder,n=new ReadableStream({async start(r){for await(const s of t)r.enqueue(e.encode(`event: data
112
- data: ${JSON.stringify(s)}
113
-
114
- `));r.enqueue(e.encode(`event: end
115
-
116
- `)),r.close()}});return $n.fromReadableStream(n)}function cb(t){return typeof t=="object"&&t!==null&&typeof t[Symbol.iterator]=="function"&&typeof t.next=="function"}const S4=t=>t!=null&&typeof t=="object"&&"next"in t&&typeof t.next=="function";function Yp(t){return typeof t=="object"&&t!==null&&typeof t[Symbol.asyncIterator]=="function"}function aE(t){return t!=null&&typeof t=="object"&&typeof t.next=="function"}async function T4(t,e){var n;try{let r=await t.next();for(;!r.done;)await(e==null?void 0:e(r.value)),r=await t.next();return r.value}finally{await((n=t.return)==null?void 0:n.call(t,void 0))}}function*ub(t,e){for(;;){const{value:n,done:r}=tn.runWithConfig(_s(t),e.next.bind(e),!0);if(r)break;yield n}}async function*Qp(t,e){const n=e[Symbol.asyncIterator]();for(;;){const{value:r,done:s}=await tn.runWithConfig(_s(t),n.next.bind(e),!0);if(s)break;yield r}}function Mt(t,e){return t&&!Array.isArray(t)&&!(t instanceof Date)&&typeof t=="object"?t:{[e]:t}}var Fe=class extends ar{constructor(){super(...arguments);p(this,"lc_runnable",!0);p(this,"name")}getName(e){const n=this.name??this.constructor.lc_name()??this.constructor.name;return e?`${n}${e}`:n}withRetry(e){return new zg({bound:this,kwargs:{},config:{},maxAttemptNumber:e==null?void 0:e.stopAfterAttempt,...e})}withConfig(e){return new Qt({bound:this,config:e,kwargs:{}})}withFallbacks(e){const n=Array.isArray(e)?e:e.fallbacks;return new dE({runnable:this,fallbacks:n})}_getOptionsList(e,n=0){if(Array.isArray(e)&&e.length!==n)throw new Error(`Passed "options" must be an array with the same length as the inputs, but got ${e.length} options for ${n} inputs`);if(Array.isArray(e))return e.map(Ge);if(n>1&&!Array.isArray(e)&&e.runId){console.warn("Provided runId will be used only for the first element of the batch.");const r=Object.fromEntries(Object.entries(e).filter(([s])=>s!=="runId"));return Array.from({length:n},(s,a)=>Ge(a===0?e:r))}return Array.from({length:n},()=>Ge(e))}async batch(e,n,r){var o;const s=this._getOptionsList(n??{},e.length),a=new Wc({maxConcurrency:((o=s[0])==null?void 0:o.maxConcurrency)??(r==null?void 0:r.maxConcurrency),onFailedAttempt:c=>{throw c}}),i=e.map((c,u)=>a.call(async()=>{try{return await this.invoke(c,s[u])}catch(l){if(r!=null&&r.returnExceptions)return l;throw l}}));return Promise.all(i)}async*_streamIterator(e,n){yield this.invoke(e,n)}async stream(e,n){const r=Ge(n),s=new Ha({generator:this._streamIterator(e,r),config:r});return await s.setup,$n.fromAsyncGenerator(s)}_separateRunnableConfigFromCallOptions(e){let n;e===void 0?n=Ge(e):n=Ge({callbacks:e.callbacks,tags:e.tags,metadata:e.metadata,runName:e.runName,configurable:e.configurable,recursionLimit:e.recursionLimit,maxConcurrency:e.maxConcurrency,runId:e.runId,timeout:e.timeout,signal:e.signal});const r={...e};return delete r.callbacks,delete r.tags,delete r.metadata,delete r.runName,delete r.configurable,delete r.recursionLimit,delete r.maxConcurrency,delete r.runId,delete r.timeout,delete r.signal,[n,r]}async _callWithConfig(e,n,r){var o;const s=Ge(r),a=await((o=await Wn(s))==null?void 0:o.handleChainStart(this.toJSON(),Mt(n,"input"),s.runId,s==null?void 0:s.runType,void 0,void 0,(s==null?void 0:s.runName)??this.getName()));delete s.runId;let i;try{i=await Gr(e.call(this,n,s,a),s.signal)}catch(c){throw await(a==null?void 0:a.handleChainError(c)),c}return await(a==null?void 0:a.handleChainEnd(Mt(i,"output"))),i}async _batchWithConfig(e,n,r,s){var u;const a=this._getOptionsList(r??{},n.length),i=await Promise.all(a.map(Wn)),o=await Promise.all(i.map(async(l,d)=>{const f=await(l==null?void 0:l.handleChainStart(this.toJSON(),Mt(n[d],"input"),a[d].runId,a[d].runType,void 0,void 0,a[d].runName??this.getName()));return delete a[d].runId,f}));let c;try{c=await Gr(e.call(this,n,a,o,s),(u=a==null?void 0:a[0])==null?void 0:u.signal)}catch(l){throw await Promise.all(o.map(d=>d==null?void 0:d.handleChainError(l))),l}return await Promise.all(o.map(l=>l==null?void 0:l.handleChainEnd(Mt(c,"output")))),c}_concatOutputChunks(e,n){return ys(e,n)}async*_transformStreamWithConfig(e,n,r){let s,a=!0,i,o=!0;const c=Ge(r),u=await Wn(c),l=this;async function*d(){for await(const h of e){if(a)if(s===void 0)s=h;else try{s=l._concatOutputChunks(s,h)}catch{s=void 0,a=!1}yield h}}let f;try{const h=await rT(n.bind(this),d(),async()=>u==null?void 0:u.handleChainStart(this.toJSON(),{input:""},c.runId,c.runType,void 0,void 0,c.runName??this.getName(),void 0,{lc_defers_inputs:!0}),c.signal,c);delete c.runId,f=h.setup;const m=f==null?void 0:f.handlers.find(_P);let _=h.output;m!==void 0&&f!==void 0&&(_=m.tapOutputIterable(f.runId,_));const y=f==null?void 0:f.handlers.find(iT);y!==void 0&&f!==void 0&&(_=y.tapOutputIterable(f.runId,_));for await(const w of _)if(yield w,o)if(i===void 0)i=w;else try{i=this._concatOutputChunks(i,w)}catch{i=void 0,o=!1}}catch(h){throw await(f==null?void 0:f.handleChainError(h,void 0,void 0,void 0,{inputs:Mt(s,"input")})),h}await(f==null?void 0:f.handleChainEnd(i??{},void 0,void 0,void 0,{inputs:Mt(s,"input")}))}getGraph(e){const n=new bc,r=n.addNode({name:`${this.getName()}Input`,schema:eb()}),s=n.addNode(this),a=n.addNode({name:`${this.getName()}Output`,schema:eb()});return n.addEdge(r,s),n.addEdge(s,a),n}pipe(e){return new Jn({first:this,last:en(e)})}pick(e){return this.pipe(new hE(e))}assign(e){return this.pipe(new Hg(new Wi({steps:e})))}async*transform(e,n){let r;for await(const s of e)r===void 0?r=s:r=this._concatOutputChunks(r,s);yield*this._streamIterator(r,Ge(n))}async*streamLog(e,n,r){const s=new Lp({...r,autoClose:!1,_schemaFormat:"original"}),a=Ge(n);yield*this._streamLog(e,s,a)}async*_streamLog(e,n,r){const{callbacks:s}=r;if(s===void 0)r.callbacks=[n];else if(Array.isArray(s))r.callbacks=s.concat([n]);else{const c=s.copy();c.addHandler(n,!0),r.callbacks=c}const a=this.stream(e,r);async function i(){try{const c=await a;for await(const u of c){const l=new as({ops:[{op:"add",path:"/streamed_output/-",value:u}]});await n.writer.write(l)}}finally{await n.writer.close()}}const o=i();try{for await(const c of n)yield c}finally{await o}}streamEvents(e,n,r){let s;if(n.version==="v1")s=this._streamEventsV1(e,n,r);else if(n.version==="v2")s=this._streamEventsV2(e,n,r);else throw new Error('Only versions "v1" and "v2" of the schema are currently supported.');return n.encoding==="text/event-stream"?v4(s):$n.fromAsyncGenerator(s)}async*_streamEventsV2(e,n,r){var m;const s=new yP({...r,autoClose:!1}),a=Ge(n),i=a.runId??rs();a.runId=i;const o=a.callbacks;if(o===void 0)a.callbacks=[s];else if(Array.isArray(o))a.callbacks=o.concat(s);else{const _=o.copy();_.addHandler(s,!0),a.callbacks=_}const c=new AbortController,u=this;async function l(){let _;try{if(a.signal)if("any"in AbortSignal)_=AbortSignal.any([c.signal,a.signal]);else{const g=new AbortController;a.signal.addEventListener("abort",()=>g.abort(),{once:!0}),c.signal.addEventListener("abort",()=>g.abort(),{once:!0}),_=g.signal}else _=c.signal;const y=await u.stream(e,{...a,signal:_}),w=s.tapOutputIterable(i,y);for await(const g of w)if(c.signal.aborted)break}finally{await s.finish()}}const d=l();let f=!1,h;try{for await(const _ of s){if(!f){_.data.input=e,f=!0,h=_.run_id,yield _;continue}_.run_id===h&&_.event.endsWith("_end")&&(m=_.data)!=null&&m.input&&delete _.data.input,yield _}}finally{c.abort(),await d}}async*_streamEventsV1(e,n,r){let s,a=!1;const i=Ge(n),o=i.tags??[],c=i.metadata??{},u=i.runName??this.getName(),l=new Lp({...r,autoClose:!1,_schemaFormat:"streaming_events"}),d=new CP({...r}),f=this._streamLog(e,l,i);for await(const m of f){if(s?s=s.concat(m):s=kg.fromRunLogPatch(m),s.state===void 0)throw new Error('Internal error: "streamEvents" state is missing. Please open a bug report.');if(!a){a=!0;const g={...s.state},b={run_id:g.id,event:`on_${g.type}_start`,name:u,tags:o,metadata:c,data:{input:e}};d.includeEvent(b,g.type)&&(yield b)}const _=m.ops.filter(g=>g.path.startsWith("/logs/")).map(g=>g.path.split("/")[2]),y=[...new Set(_)];for(const g of y){let b,S={};const I=s.state.logs[g];if(I.end_time===void 0?I.streamed_output.length>0?b="stream":b="start":b="end",b==="start")I.inputs!==void 0&&(S.input=I.inputs);else if(b==="end")I.inputs!==void 0&&(S.input=I.inputs),S.output=I.final_output;else if(b==="stream"){const T=I.streamed_output.length;if(T!==1)throw new Error(`Expected exactly one chunk of streamed output, got ${T} instead. Encountered in: "${I.name}"`);S={chunk:I.streamed_output[0]},I.streamed_output=[]}yield{event:`on_${I.type}_${b}`,name:I.name,run_id:I.id,tags:I.tags,metadata:I.metadata,data:S}}const{state:w}=s;if(w.streamed_output.length>0){const g=w.streamed_output.length;if(g!==1)throw new Error(`Expected exactly one chunk of streamed output, got ${g} instead. Encountered in: "${w.name}"`);const b={chunk:w.streamed_output[0]};w.streamed_output=[];const S={event:`on_${w.type}_stream`,run_id:w.id,tags:o,metadata:c,name:u,data:b};d.includeEvent(S,w.type)&&(yield S)}}const h=s==null?void 0:s.state;if(h!==void 0){const m={event:`on_${h.type}_end`,name:u,run_id:h.id,tags:o,metadata:c,data:{output:h.final_output}};d.includeEvent(m,h.type)&&(yield m)}}static isRunnable(e){return Og(e)}withListeners({onStart:e,onEnd:n,onError:r}){return new Qt({bound:this,config:{},configFactories:[s=>({callbacks:[new uT({config:s,onStart:e,onEnd:n,onError:r})]})]})}asTool(e){return k4(this,e)}},Qt=class iE extends Fe{constructor(n){super(n);p(this,"lc_namespace",["langchain_core","runnables"]);p(this,"lc_serializable",!0);p(this,"bound");p(this,"config");p(this,"kwargs");p(this,"configFactories");this.bound=n.bound,this.kwargs=n.kwargs,this.config=n.config,this.configFactories=n.configFactories}static lc_name(){return"RunnableBinding"}getName(n){return this.bound.getName(n)}async _mergeConfig(...n){const r=sr(this.config,...n);return sr(r,...this.configFactories?await Promise.all(this.configFactories.map(async s=>await s(r))):[])}withConfig(n){return new this.constructor({bound:this.bound,kwargs:this.kwargs,config:{...this.config,...n}})}withRetry(n){return new zg({bound:this.bound,kwargs:this.kwargs,config:this.config,maxAttemptNumber:n==null?void 0:n.stopAfterAttempt,...n})}async invoke(n,r){return this.bound.invoke(n,await this._mergeConfig(r,this.kwargs))}async batch(n,r,s){const a=Array.isArray(r)?await Promise.all(r.map(async i=>this._mergeConfig(Ge(i),this.kwargs))):await this._mergeConfig(Ge(r),this.kwargs);return this.bound.batch(n,a,s)}_concatOutputChunks(n,r){return this.bound._concatOutputChunks(n,r)}async*_streamIterator(n,r){yield*this.bound._streamIterator(n,await this._mergeConfig(Ge(r),this.kwargs))}async stream(n,r){return this.bound.stream(n,await this._mergeConfig(Ge(r),this.kwargs))}async*transform(n,r){yield*this.bound.transform(n,await this._mergeConfig(Ge(r),this.kwargs))}streamEvents(n,r,s){const a=this,i=async function*(){yield*a.bound.streamEvents(n,{...await a._mergeConfig(Ge(r),a.kwargs),version:r.version},s)};return $n.fromAsyncGenerator(i())}static isRunnableBinding(n){return n.bound&&Fe.isRunnable(n.bound)}withListeners({onStart:n,onEnd:r,onError:s}){return new iE({bound:this.bound,kwargs:this.kwargs,config:this.config,configFactories:[a=>({callbacks:[new uT({config:a,onStart:n,onEnd:r,onError:s})]})]})}},E4=class oE extends Fe{constructor(n){super(n);p(this,"lc_serializable",!0);p(this,"lc_namespace",["langchain_core","runnables"]);p(this,"bound");this.bound=n.bound}static lc_name(){return"RunnableEach"}async invoke(n,r){return this._callWithConfig(this._invoke.bind(this),n,r)}async _invoke(n,r,s){return this.bound.batch(n,et(r,{callbacks:s==null?void 0:s.getChild()}))}withListeners({onStart:n,onEnd:r,onError:s}){return new oE({bound:this.bound.withListeners({onStart:n,onEnd:r,onError:s})})}},zg=class extends Qt{constructor(e){super(e);p(this,"lc_namespace",["langchain_core","runnables"]);p(this,"maxAttemptNumber",3);p(this,"onFailedAttempt",()=>{});this.maxAttemptNumber=e.maxAttemptNumber??this.maxAttemptNumber,this.onFailedAttempt=e.onFailedAttempt??this.onFailedAttempt}static lc_name(){return"RunnableRetry"}_patchConfigForRetry(e,n,r){const s=e>1?`retry:attempt:${e}`:void 0;return et(n,{callbacks:r==null?void 0:r.getChild(s)})}async _invoke(e,n,r){return jp(s=>super.invoke(e,this._patchConfigForRetry(s,n,r)),{onFailedAttempt:({error:s})=>this.onFailedAttempt(s,e),retries:Math.max(this.maxAttemptNumber-1,0),randomize:!0})}async invoke(e,n){return this._callWithConfig(this._invoke.bind(this),e,n)}async _batch(e,n,r,s){const a={};try{await jp(async i=>{const o=e.map((f,h)=>h).filter(f=>a[f.toString()]===void 0||a[f.toString()]instanceof Error),c=o.map(f=>e[f]),u=o.map(f=>this._patchConfigForRetry(i,n==null?void 0:n[f],r==null?void 0:r[f])),l=await super.batch(c,u,{...s,returnExceptions:!0});let d;for(let f=0;f<l.length;f+=1){const h=l[f],m=o[f];h instanceof Error&&d===void 0&&(d=h,d.input=c[f]),a[m.toString()]=h}if(d)throw d;return l},{onFailedAttempt:({error:i})=>this.onFailedAttempt(i,i.input),retries:Math.max(this.maxAttemptNumber-1,0),randomize:!0})}catch(i){if((s==null?void 0:s.returnExceptions)!==!0)throw i}return Object.keys(a).sort((i,o)=>parseInt(i,10)-parseInt(o,10)).map(i=>a[parseInt(i,10)])}async batch(e,n,r){return this._batchWithConfig(this._batch.bind(this),e,n,r)}},Jn=class Ro extends Fe{constructor(n){super(n);p(this,"first");p(this,"middle",[]);p(this,"last");p(this,"omitSequenceTags",!1);p(this,"lc_serializable",!0);p(this,"lc_namespace",["langchain_core","runnables"]);this.first=n.first,this.middle=n.middle??this.middle,this.last=n.last,this.name=n.name,this.omitSequenceTags=n.omitSequenceTags??this.omitSequenceTags}static lc_name(){return"RunnableSequence"}get steps(){return[this.first,...this.middle,this.last]}async invoke(n,r){var c,u;const s=Ge(r),a=await((c=await Wn(s))==null?void 0:c.handleChainStart(this.toJSON(),Mt(n,"input"),s.runId,void 0,void 0,void 0,s==null?void 0:s.runName));delete s.runId;let i=n,o;try{const l=[this.first,...this.middle];for(let d=0;d<l.length;d+=1)i=await Gr(l[d].invoke(i,et(s,{callbacks:a==null?void 0:a.getChild(this.omitSequenceTags?void 0:`seq:step:${d+1}`)})),s.signal);if((u=s.signal)!=null&&u.aborted)throw dc(s.signal);o=await this.last.invoke(i,et(s,{callbacks:a==null?void 0:a.getChild(this.omitSequenceTags?void 0:`seq:step:${this.steps.length}`)}))}catch(l){throw await(a==null?void 0:a.handleChainError(l)),l}return await(a==null?void 0:a.handleChainEnd(Mt(o,"output"))),o}async batch(n,r,s){var u;const a=this._getOptionsList(r??{},n.length),i=await Promise.all(a.map(Wn)),o=await Promise.all(i.map(async(l,d)=>{const f=await(l==null?void 0:l.handleChainStart(this.toJSON(),Mt(n[d],"input"),a[d].runId,void 0,void 0,void 0,a[d].runName));return delete a[d].runId,f}));let c=n;try{for(let l=0;l<this.steps.length;l+=1)c=await Gr(this.steps[l].batch(c,o.map((d,f)=>{const h=d==null?void 0:d.getChild(this.omitSequenceTags?void 0:`seq:step:${l+1}`);return et(a[f],{callbacks:h})}),s),(u=a[0])==null?void 0:u.signal)}catch(l){throw await Promise.all(o.map(d=>d==null?void 0:d.handleChainError(l))),l}return await Promise.all(o.map(l=>l==null?void 0:l.handleChainEnd(Mt(c,"output")))),c}_concatOutputChunks(n,r){return this.last._concatOutputChunks(n,r)}async*_streamIterator(n,r){var f;const s=await Wn(r),{runId:a,...i}=r??{},o=await(s==null?void 0:s.handleChainStart(this.toJSON(),Mt(n,"input"),a,void 0,void 0,void 0,i==null?void 0:i.runName)),c=[this.first,...this.middle,this.last];let u=!0,l;async function*d(){yield n}try{let h=c[0].transform(d(),et(i,{callbacks:o==null?void 0:o.getChild(this.omitSequenceTags?void 0:"seq:step:1")}));for(let m=1;m<c.length;m+=1)h=await c[m].transform(h,et(i,{callbacks:o==null?void 0:o.getChild(this.omitSequenceTags?void 0:`seq:step:${m+1}`)}));for await(const m of h)if((f=r==null?void 0:r.signal)==null||f.throwIfAborted(),yield m,u)if(l===void 0)l=m;else try{l=this._concatOutputChunks(l,m)}catch{l=void 0,u=!1}}catch(h){throw await(o==null?void 0:o.handleChainError(h)),h}await(o==null?void 0:o.handleChainEnd(Mt(l,"output")))}getGraph(n){const r=new bc;let s=null;return this.steps.forEach((a,i)=>{const o=a.getGraph(n);i!==0&&o.trimFirstNode(),i!==this.steps.length-1&&o.trimLastNode(),r.extend(o);const c=o.firstNode();if(!c)throw new Error(`Runnable ${a} has no first node`);s&&r.addEdge(s,c),s=o.lastNode()}),r}pipe(n){return Ro.isRunnableSequence(n)?new Ro({first:this.first,middle:this.middle.concat([this.last,n.first,...n.middle]),last:n.last,name:this.name??n.name}):new Ro({first:this.first,middle:[...this.middle,this.last],last:en(n),name:this.name})}static isRunnableSequence(n){return Array.isArray(n.middle)&&Fe.isRunnable(n)}static from([n,...r],s){let a={};return typeof s=="string"?a.name=s:s!==void 0&&(a=s),new Ro({...a,first:en(n),middle:r.slice(0,-1).map(en),last:en(r[r.length-1])})}},Wi=class cE extends Fe{constructor(n){super(n);p(this,"lc_namespace",["langchain_core","runnables"]);p(this,"lc_serializable",!0);p(this,"steps");this.steps={};for(const[r,s]of Object.entries(n.steps))this.steps[r]=en(s)}static lc_name(){return"RunnableMap"}getStepsKeys(){return Object.keys(this.steps)}static from(n){return new cE({steps:n})}async invoke(n,r){var o;const s=Ge(r),a=await((o=await Wn(s))==null?void 0:o.handleChainStart(this.toJSON(),{input:n},s.runId,void 0,void 0,void 0,s==null?void 0:s.runName));delete s.runId;const i={};try{const c=Object.entries(this.steps).map(async([u,l])=>{i[u]=await l.invoke(n,et(s,{callbacks:a==null?void 0:a.getChild(`map:key:${u}`)}))});await Gr(Promise.all(c),s.signal)}catch(c){throw await(a==null?void 0:a.handleChainError(c)),c}return await(a==null?void 0:a.handleChainEnd(i)),i}async*_transform(n,r,s){const a={...this.steps},i=xg(n,Object.keys(a).length),o=new Map(Object.entries(a).map(([c,u],l)=>{const d=u.transform(i[l],et(s,{callbacks:r==null?void 0:r.getChild(`map:key:${c}`)}));return[c,d.next().then(f=>({key:c,gen:d,result:f}))]}));for(;o.size;){const{key:c,result:u,gen:l}=await Gr(Promise.race(o.values()),s==null?void 0:s.signal);o.delete(c),u.done||(yield{[c]:u.value},o.set(c,l.next().then(d=>({key:c,gen:l,result:d}))))}}transform(n,r){return this._transformStreamWithConfig(n,this._transform.bind(this),r)}async stream(n,r){async function*s(){yield n}const a=Ge(r),i=new Ha({generator:this.transform(s(),a),config:a});return await i.setup,$n.fromAsyncGenerator(i)}},A4=class uE extends Fe{constructor(n){super(n);p(this,"lc_serializable",!1);p(this,"lc_namespace",["langchain_core","runnables"]);p(this,"func");if(!Ag(n.func))throw new Error("RunnableTraceable requires a function that is wrapped in traceable higher-order function");this.func=n.func}async invoke(n,r){const[s]=this._getOptionsList(r??{},1),a=await Wn(s);return Gr(this.func(et(s,{callbacks:a}),n),s==null?void 0:s.signal)}async*_streamIterator(n,r){var i,o;const[s]=this._getOptionsList(r??{},1),a=await this.invoke(n,r);if(Yp(a)){for await(const c of a)(i=s==null?void 0:s.signal)==null||i.throwIfAborted(),yield c;return}if(S4(a)){for(;;){(o=s==null?void 0:s.signal)==null||o.throwIfAborted();const c=a.next();if(c.done)break;yield c.value}return}yield a}static from(n){return new uE({func:n})}};function I4(t){if(Ag(t))throw new Error("RunnableLambda requires a function that is not wrapped in traceable higher-order function. This shouldn't happen.")}var Ht=class lE extends Fe{constructor(n){if(Ag(n.func))return A4.from(n.func);super(n);p(this,"lc_namespace",["langchain_core","runnables"]);p(this,"func");I4(n.func),this.func=n.func}static lc_name(){return"RunnableLambda"}static from(n){return new lE({func:n})}async _invoke(n,r,s){return new Promise((a,i)=>{const o=et(r,{callbacks:s==null?void 0:s.getChild(),recursionLimit:((r==null?void 0:r.recursionLimit)??25)-1});tn.runWithConfig(_s(o),async()=>{var c,u;try{let l=await this.func(n,{...o});if(l&&Fe.isRunnable(l)){if((r==null?void 0:r.recursionLimit)===0)throw new Error("Recursion limit reached.");l=await l.invoke(n,{...o,recursionLimit:(o.recursionLimit??25)-1})}else if(Yp(l)){let d;for await(const f of Qp(o,l))if((c=r==null?void 0:r.signal)==null||c.throwIfAborted(),d===void 0)d=f;else try{d=this._concatOutputChunks(d,f)}catch{d=f}l=d}else if(cb(l)){let d;for(const f of ub(o,l))if((u=r==null?void 0:r.signal)==null||u.throwIfAborted(),d===void 0)d=f;else try{d=this._concatOutputChunks(d,f)}catch{d=f}l=d}a(l)}catch(l){i(l)}})})}async invoke(n,r){return this._callWithConfig(this._invoke.bind(this),n,r)}async*_transform(n,r,s){var c,u;let a;for await(const l of n)if(a===void 0)a=l;else try{a=this._concatOutputChunks(a,l)}catch{a=l}const i=et(s,{callbacks:r==null?void 0:r.getChild(),recursionLimit:((s==null?void 0:s.recursionLimit)??25)-1}),o=await new Promise((l,d)=>{tn.runWithConfig(_s(i),async()=>{try{l(await this.func(a,{...i,config:i}))}catch(f){d(f)}})});if(o&&Fe.isRunnable(o)){if((s==null?void 0:s.recursionLimit)===0)throw new Error("Recursion limit reached.");const l=await o.stream(a,i);for await(const d of l)yield d}else if(Yp(o))for await(const l of Qp(i,o))(c=s==null?void 0:s.signal)==null||c.throwIfAborted(),yield l;else if(cb(o))for(const l of ub(i,o))(u=s==null?void 0:s.signal)==null||u.throwIfAborted(),yield l;else yield o}transform(n,r){return this._transformStreamWithConfig(n,this._transform.bind(this),r)}async stream(n,r){async function*s(){yield n}const a=Ge(r),i=new Ha({generator:this.transform(s(),a),config:a});return await i.setup,$n.fromAsyncGenerator(i)}},x4=class extends Wi{},dE=class extends Fe{constructor(e){super(e);p(this,"lc_namespace",["langchain_core","runnables"]);p(this,"lc_serializable",!0);p(this,"runnable");p(this,"fallbacks");this.runnable=e.runnable,this.fallbacks=e.fallbacks}static lc_name(){return"RunnableWithFallbacks"}*runnables(){yield this.runnable;for(const e of this.fallbacks)yield e}async invoke(e,n){const r=Ge(n),s=await Wn(r),{runId:a,...i}=r,o=await(s==null?void 0:s.handleChainStart(this.toJSON(),Mt(e,"input"),a,void 0,void 0,void 0,i==null?void 0:i.runName)),c=et(i,{callbacks:o==null?void 0:o.getChild()});return await tn.runWithConfig(c,async()=>{var l;let u;for(const d of this.runnables()){(l=r==null?void 0:r.signal)==null||l.throwIfAborted();try{const f=await d.invoke(e,c);return await(o==null?void 0:o.handleChainEnd(Mt(f,"output"))),f}catch(f){u===void 0&&(u=f)}}throw u===void 0?new Error("No error stored at end of fallback."):(await(o==null?void 0:o.handleChainError(u)),u)})}async*_streamIterator(e,n){var d;const r=Ge(n),s=await Wn(r),{runId:a,...i}=r,o=await(s==null?void 0:s.handleChainStart(this.toJSON(),Mt(e,"input"),a,void 0,void 0,void 0,i==null?void 0:i.runName));let c,u;for(const f of this.runnables()){(d=r==null?void 0:r.signal)==null||d.throwIfAborted();const h=et(i,{callbacks:o==null?void 0:o.getChild()});try{u=Qp(h,await f.stream(e,h));break}catch(m){c===void 0&&(c=m)}}if(u===void 0){const f=c??new Error("No error stored at end of fallback.");throw await(o==null?void 0:o.handleChainError(f)),f}let l;try{for await(const f of u){yield f;try{l=l===void 0?l:this._concatOutputChunks(l,f)}catch{l=void 0}}}catch(f){throw await(o==null?void 0:o.handleChainError(f)),f}await(o==null?void 0:o.handleChainEnd(Mt(l,"output")))}async batch(e,n,r){var c;if(r!=null&&r.returnExceptions)throw new Error("Not implemented.");const s=this._getOptionsList(n??{},e.length),a=await Promise.all(s.map(u=>Wn(u))),i=await Promise.all(a.map(async(u,l)=>{const d=await(u==null?void 0:u.handleChainStart(this.toJSON(),Mt(e[l],"input"),s[l].runId,void 0,void 0,void 0,s[l].runName));return delete s[l].runId,d}));let o;for(const u of this.runnables()){(c=s[0].signal)==null||c.throwIfAborted();try{const l=await u.batch(e,i.map((d,f)=>et(s[f],{callbacks:d==null?void 0:d.getChild()})),r);return await Promise.all(i.map((d,f)=>d==null?void 0:d.handleChainEnd(Mt(l[f],"output")))),l}catch(l){o===void 0&&(o=l)}}throw o?(await Promise.all(i.map(u=>u==null?void 0:u.handleChainError(o))),o):new Error("No error stored at end of fallbacks.")}};function en(t){if(typeof t=="function")return new Ht({func:t});if(Fe.isRunnable(t))return t;if(!Array.isArray(t)&&typeof t=="object"){const e={};for(const[n,r]of Object.entries(t))e[n]=en(r);return new Wi({steps:e})}else throw new Error(`Expected a Runnable, function or object.
117
- Instead got an unsupported type.`)}var Hg=class extends Fe{constructor(e){e instanceof Wi&&(e={mapper:e});super(e);p(this,"lc_namespace",["langchain_core","runnables"]);p(this,"lc_serializable",!0);p(this,"mapper");this.mapper=e.mapper}static lc_name(){return"RunnableAssign"}async invoke(e,n){const r=await this.mapper.invoke(e,n);return{...e,...r}}async*_transform(e,n,r){const s=this.mapper.getStepsKeys(),[a,i]=xg(e),o=this.mapper.transform(i,et(r,{callbacks:n==null?void 0:n.getChild()})),c=o.next();for await(const u of a){if(typeof u!="object"||Array.isArray(u))throw new Error(`RunnableAssign can only be used with objects as input, got ${typeof u}`);const l=Object.fromEntries(Object.entries(u).filter(([d])=>!s.includes(d)));Object.keys(l).length>0&&(yield l)}yield(await c).value;for await(const u of o)yield u}transform(e,n){return this._transformStreamWithConfig(e,this._transform.bind(this),n)}async stream(e,n){async function*r(){yield e}const s=Ge(n),a=new Ha({generator:this.transform(r(),s),config:s});return await a.setup,$n.fromAsyncGenerator(a)}},hE=class extends Fe{constructor(e){(typeof e=="string"||Array.isArray(e))&&(e={keys:e});super(e);p(this,"lc_namespace",["langchain_core","runnables"]);p(this,"lc_serializable",!0);p(this,"keys");this.keys=e.keys}static lc_name(){return"RunnablePick"}async _pick(e){if(typeof this.keys=="string")return e[this.keys];{const n=this.keys.map(r=>[r,e[r]]).filter(r=>r[1]!==void 0);return n.length===0?void 0:Object.fromEntries(n)}}async invoke(e,n){return this._callWithConfig(this._pick.bind(this),e,n)}async*_transform(e){for await(const n of e){const r=await this._pick(n);r!==void 0&&(yield r)}}transform(e,n){return this._transformStreamWithConfig(e,this._transform.bind(this),n)}async stream(e,n){async function*r(){yield e}const s=Ge(n),a=new Ha({generator:this.transform(r(),s),config:s});return await a.setup,$n.fromAsyncGenerator(a)}},em=class extends Qt{constructor(e){const n=Jn.from([Ht.from(async r=>{let s;if(Jo(r))try{s=await Yd(this.schema,r.args)}catch{throw new Wl("Received tool input did not match expected schema",JSON.stringify(r.args))}else s=r;return s}).withConfig({runName:`${e.name}:parse_input`}),e.bound]).withConfig({runName:e.name});super({bound:n,config:e.config??{}});p(this,"name");p(this,"description");p(this,"schema");this.name=e.name,this.description=e.description,this.schema=e.schema}static lc_name(){return"RunnableToolLike"}};function k4(t,e){const n=e.name??t.getName(),r=e.description??Pi(e.schema);return jg(e.schema)?new em({name:n,description:r,schema:br({input:zn()}).transform(s=>s.input),bound:t}):new em({name:n,description:r,schema:e.schema,bound:t})}var vc=class extends Fe{constructor(e){super(e);p(this,"lc_namespace",["langchain_core","runnables"]);p(this,"lc_serializable",!0);p(this,"func");e&&(this.func=e.func)}static lc_name(){return"RunnablePassthrough"}async invoke(e,n){const r=Ge(n);return this.func&&await this.func(e,r),this._callWithConfig(s=>Promise.resolve(s),e,r)}async*transform(e,n){const r=Ge(n);let s,a=!0;for await(const i of this._transformStreamWithConfig(e,o=>o,r))if(yield i,a)if(s===void 0)s=i;else try{s=ys(s,i)}catch{s=void 0,a=!1}this.func&&s!==void 0&&await this.func(s,r)}static assign(e){return new Hg(new Wi({steps:e}))}},O4=class extends Fe{constructor(e){super(e);p(this,"lc_namespace",["langchain_core","runnables"]);p(this,"lc_serializable",!0);p(this,"runnables");this.runnables=e.runnables}static lc_name(){return"RouterRunnable"}async invoke(e,n){const{key:r,input:s}=e,a=this.runnables[r];if(a===void 0)throw new Error(`No runnable associated with key "${r}".`);return a.invoke(s,Ge(n))}async batch(e,n,r){var d;const s=e.map(f=>f.key),a=e.map(f=>f.input);if(s.find(f=>this.runnables[f]===void 0)!==void 0)throw new Error("One or more keys do not have a corresponding runnable.");const i=s.map(f=>this.runnables[f]),o=this._getOptionsList(n??{},e.length),c=((d=o[0])==null?void 0:d.maxConcurrency)??(r==null?void 0:r.maxConcurrency),u=c&&c>0?c:e.length,l=[];for(let f=0;f<a.length;f+=u){const h=a.slice(f,f+u).map((_,y)=>i[y].invoke(_,o[y])),m=await Promise.all(h);l.push(m)}return l.flat()}async stream(e,n){const{key:r,input:s}=e,a=this.runnables[r];if(a===void 0)throw new Error(`No runnable associated with key "${r}".`);return a.stream(s,n)}},C4=class extends Fe{constructor(e){super(e);p(this,"lc_namespace",["langchain_core","runnables"]);p(this,"lc_serializable",!0);p(this,"default");p(this,"branches");this.branches=e.branches,this.default=e.default}static lc_name(){return"RunnableBranch"}static from(e){if(e.length<1)throw new Error("RunnableBranch requires at least one branch");const n=e.slice(0,-1).map(([s,a])=>[en(s),en(a)]),r=en(e[e.length-1]);return new this({branches:n,default:r})}async _invoke(e,n,r){let s;for(let a=0;a<this.branches.length;a+=1){const[i,o]=this.branches[a];if(await i.invoke(e,et(n,{callbacks:r==null?void 0:r.getChild(`condition:${a+1}`)}))){s=await o.invoke(e,et(n,{callbacks:r==null?void 0:r.getChild(`branch:${a+1}`)}));break}}return s||(s=await this.default.invoke(e,et(n,{callbacks:r==null?void 0:r.getChild("branch:default")}))),s}async invoke(e,n={}){return this._callWithConfig(this._invoke,e,n)}async*_streamIterator(e,n){var o;const r=await((o=await Wn(n))==null?void 0:o.handleChainStart(this.toJSON(),Mt(e,"input"),n==null?void 0:n.runId,void 0,void 0,void 0,n==null?void 0:n.runName));let s,a=!0,i;try{for(let c=0;c<this.branches.length;c+=1){const[u,l]=this.branches[c];if(await u.invoke(e,et(n,{callbacks:r==null?void 0:r.getChild(`condition:${c+1}`)}))){i=await l.stream(e,et(n,{callbacks:r==null?void 0:r.getChild(`branch:${c+1}`)}));for await(const d of i)if(yield d,a)if(s===void 0)s=d;else try{s=ys(s,d)}catch{s=void 0,a=!1}break}}if(i===void 0){i=await this.default.stream(e,et(n,{callbacks:r==null?void 0:r.getChild("branch:default")}));for await(const c of i)if(yield c,a)if(s===void 0)s=c;else try{s=ys(s,c)}catch{s=void 0,a=!1}}}catch(c){throw await(r==null?void 0:r.handleChainError(c)),c}await(r==null?void 0:r.handleChainEnd(s??{}))}};const hd=(t,e)=>{const n=[...new Set(e==null?void 0:e.map(s=>{if(typeof s=="string")return s;const a=new s({});if(!("getType"in a)||typeof a.getType!="function")throw new Error("Invalid type provided.");return a.getType()}))],r=t.getType();return n.some(s=>s===r)};function R4(t,e){return Array.isArray(t)?lb(t,e):Ht.from(n=>lb(n,t))}function lb(t,e={}){const{includeNames:n,excludeNames:r,includeTypes:s,excludeTypes:a,includeIds:i,excludeIds:o}=e,c=[];for(const u of t)if(!(r&&u.name&&r.includes(u.name))){{if(a&&hd(u,a))continue;if(o&&u.id&&o.includes(u.id))continue}s||i||n?(n&&u.name&&n.some(l=>l===u.name)||s&&hd(u,s)||i&&u.id&&i.some(l=>l===u.id))&&c.push(u):c.push(u)}return c}function $4(t){return Array.isArray(t)?db(t):Ht.from(db)}function db(t){if(!t.length)return[];const e=[];for(const n of t){const r=n,s=e.pop();if(!s)e.push(r);else if(r.getType()==="tool"||r.getType()!==s.getType())e.push(s,r);else{const a=Kl(s),i=Kl(r),o=a.concat(i);typeof a.content=="string"&&typeof i.content=="string"&&(o.content=`${a.content}
118
- ${i.content}`),e.push(M4(o))}}return e}function N4(t,e){if(Array.isArray(t)){const n=t;if(!e)throw new Error("Options parameter is required when providing messages.");return hb(n,e)}else{const n=t;return Ht.from(r=>hb(r,n)).withConfig({runName:"trim_messages"})}}async function hb(t,e){const{maxTokens:n,tokenCounter:r,strategy:s="last",allowPartial:a=!1,endOn:i,startOn:o,includeSystem:c=!1,textSplitter:u}=e;if(o&&s==="first")throw new Error("`startOn` should only be specified if `strategy` is 'last'.");if(c&&s==="first")throw new Error("`includeSystem` should only be specified if `strategy` is 'last'.");let l;"getNumTokens"in r?l=async f=>(await Promise.all(f.map(h=>r.getNumTokens(h.content)))).reduce((h,m)=>h+m,0):l=async f=>r(f);let d=pE;if(u&&("splitText"in u?d=u.splitText:d=async f=>u(f)),s==="first")return fE(t,{maxTokens:n,tokenCounter:l,textSplitter:d,partialStrategy:a?"first":void 0,endOn:i});if(s==="last")return P4(t,{maxTokens:n,tokenCounter:l,textSplitter:d,allowPartial:a,includeSystem:c,startOn:o,endOn:i});throw new Error(`Unrecognized strategy: '${s}'. Must be one of 'first' or 'last'.`)}async function fE(t,e){var u;const{maxTokens:n,tokenCounter:r,textSplitter:s,partialStrategy:a,endOn:i}=e;let o=[...t],c=0;for(let l=0;l<o.length;l+=1)if(await r(l>0?o.slice(0,-l):o)<=n){c=o.length-l;break}if(c<o.length&&a){let l=!1;if(Array.isArray(o[c].content)){const d=o[c];if(typeof d.content=="string")throw new Error("Expected content to be an array.");const f=d.content.length,h=a==="last"?[...d.content].reverse():d.content;for(let m=1;m<=f;m+=1){const _=a==="first"?h.slice(0,m):h.slice(-m),y=Object.fromEntries(Object.entries(d).filter(([b])=>b!=="type"&&!b.startsWith("lc_"))),w=Vg(d.getType(),{...y,content:_}),g=[...o.slice(0,c),w];if(await r(g)<=n)o=g,c+=1,l=!0;else break}l&&a==="last"&&(d.content=[...h].reverse())}if(!l){const d=o[c];let f;if(Array.isArray(d.content)&&d.content.some(h=>typeof h=="string"||h.type==="text")?f=(u=d.content.find(h=>h.type==="text"&&h.text))==null?void 0:u.text:typeof d.content=="string"&&(f=d.content),f){const h=await s(f),m=h.length;a==="last"&&h.reverse();for(let _=0;_<m-1;_+=1)if(h.pop(),d.content=h.join(""),await r([...o.slice(0,c),d])<=n){a==="last"&&(d.content=[...h].reverse().join("")),o=[...o.slice(0,c),d],c+=1;break}}}}if(i){const l=Array.isArray(i)?i:[i];for(;c>0&&!hd(o[c-1],l);)c-=1}return o.slice(0,c)}async function P4(t,e){var l;const{allowPartial:n=!1,includeSystem:r=!1,endOn:s,startOn:a,...i}=e;let o=t.map(d=>{const f=Object.fromEntries(Object.entries(d).filter(([h])=>h!=="type"&&!h.startsWith("lc_")));return Vg(d.getType(),f,Ci(d))});if(s){const d=Array.isArray(s)?s:[s];for(;o.length>0&&!hd(o[o.length-1],d);)o=o.slice(0,-1)}const c=r&&((l=o[0])==null?void 0:l.getType())==="system";let u=c?o.slice(0,1).concat(o.slice(1).reverse()):o.reverse();return u=await fE(u,{...i,partialStrategy:n?"last":void 0,endOn:a}),c?[u[0],...u.slice(1).reverse()]:u.reverse()}const fb={human:{message:vn,messageChunk:Bc},ai:{message:De,messageChunk:Qe},system:{message:Gn,messageChunk:qs},developer:{message:Gn,messageChunk:qs},tool:{message:Rn,messageChunk:Uc},function:{message:Vd,messageChunk:Fc},generic:{message:Kr,messageChunk:Dc},remove:{message:xa,messageChunk:xa}};function Vg(t,e,n){var a;let r,s;switch(t){case"human":n?r=new Bc(e):s=new vn(e);break;case"ai":if(n){let i={...e};"tool_calls"in i&&(i={...i,tool_call_chunks:(a=i.tool_calls)==null?void 0:a.map(o=>({...o,type:"tool_call_chunk",index:void 0,args:JSON.stringify(o.args)}))}),r=new Qe(i)}else s=new De(e);break;case"system":n?r=new qs(e):s=new Gn(e);break;case"developer":n?r=new qs({...e,additional_kwargs:{...e.additional_kwargs,__openai_role__:"developer"}}):s=new Gn({...e,additional_kwargs:{...e.additional_kwargs,__openai_role__:"developer"}});break;case"tool":if("tool_call_id"in e)n?r=new Uc(e):s=new Rn(e);else throw new Error("Can not convert ToolMessage to ToolMessageChunk if 'tool_call_id' field is not defined.");break;case"function":if(n)r=new Fc(e);else{if(!e.name)throw new Error("FunctionMessage must have a 'name' field");s=new Vd(e)}break;case"generic":if("role"in e)n?r=new Dc(e):s=new Kr(e);else throw new Error("Can not convert ChatMessage to ChatMessageChunk if 'role' field is not defined.");break;default:throw new Error(`Unrecognized message type ${t}`)}if(n&&r)return r;if(s)return s;throw new Error(`Unrecognized message type ${t}`)}function M4(t){const e=t.getType();let n;const r=Object.fromEntries(Object.entries(t).filter(([s])=>!["type","tool_call_chunks"].includes(s)&&!s.startsWith("lc_")));if(e in fb&&(n=Vg(e,r)),!n)throw new Error(`Unrecognized message chunk class ${e}. Supported classes are ${Object.keys(fb)}`);return n}function pE(t){const e=t.split(`
119
- `);return Promise.resolve([...e.slice(0,-1).map(n=>`${n}
120
- `),e[e.length-1]])}const L4=["tool_call","tool_call_chunk","invalid_tool_call","server_tool_call","server_tool_call_chunk","server_tool_call_result"],j4=["image","video","audio","text-plain","file"],U4=["text","reasoning",...L4,...j4];var D4=ue({AIMessage:()=>De,AIMessageChunk:()=>Qe,BaseMessage:()=>bn,BaseMessageChunk:()=>na,ChatMessage:()=>Kr,ChatMessageChunk:()=>Dc,DEFAULT_MERGE_IGNORE_KEYS:()=>rS,FunctionMessage:()=>Vd,FunctionMessageChunk:()=>Fc,HumanMessage:()=>vn,HumanMessageChunk:()=>Bc,KNOWN_BLOCK_TYPES:()=>U4,RemoveMessage:()=>xa,SystemMessage:()=>Gn,SystemMessageChunk:()=>qs,ToolMessage:()=>Rn,ToolMessageChunk:()=>Uc,_isMessageFieldWithRole:()=>iS,_mergeDicts:()=>dn,_mergeLists:()=>Oi,_mergeObj:()=>sS,_mergeStatus:()=>nS,coerceMessageLikeToMessage:()=>Vr,collapseToolCallChunks:()=>fS,convertToChunk:()=>Kl,convertToOpenAIImageBlock:()=>Y0,convertToProviderContentBlock:()=>jc,defaultTextSplitter:()=>pE,defaultToolCallParser:()=>dg,filterMessages:()=>R4,getBufferString:()=>pg,iife:()=>hS,isAIMessage:()=>or,isAIMessageChunk:()=>ql,isBase64ContentBlock:()=>og,isBaseMessage:()=>wt,isBaseMessageChunk:()=>Ci,isChatMessage:()=>h1,isChatMessageChunk:()=>f1,isDataContentBlock:()=>ir,isDirectToolOutput:()=>lg,isFunctionMessage:()=>p1,isFunctionMessageChunk:()=>m1,isHumanMessage:()=>g1,isHumanMessageChunk:()=>_1,isIDContentBlock:()=>X0,isMessage:()=>tS,isOpenAIToolCallArray:()=>KC,isPlainTextContentBlock:()=>$C,isSystemMessage:()=>y1,isSystemMessageChunk:()=>w1,isToolMessage:()=>Ia,isToolMessageChunk:()=>oS,isURLContentBlock:()=>ig,mapChatMessagesToStoredMessages:()=>A1,mapStoredMessageToChatMessage:()=>mg,mapStoredMessagesToChatMessages:()=>E1,mergeContent:()=>gs,mergeMessageRuns:()=>$4,mergeResponseMetadata:()=>uS,mergeUsageMetadata:()=>fg,parseBase64DataUrl:()=>Ir,parseMimeType:()=>wp,trimMessages:()=>N4}),F4=class extends Qt{constructor(e){let n=Ht.from((i,o)=>this._enterHistory(i,o??{})).withConfig({runName:"loadHistory"});const r=e.historyMessagesKey??e.inputMessagesKey;r&&(n=vc.assign({[r]:n}).withConfig({runName:"insertHistory"}));const s=n.pipe(e.runnable.withListeners({onEnd:(i,o)=>this._exitHistory(i,o??{})})).withConfig({runName:"RunnableWithMessageHistory"}),a=e.config??{};super({...e,config:a,bound:s});p(this,"runnable");p(this,"inputMessagesKey");p(this,"outputMessagesKey");p(this,"historyMessagesKey");p(this,"getMessageHistory");this.runnable=e.runnable,this.getMessageHistory=e.getMessageHistory,this.inputMessagesKey=e.inputMessagesKey,this.outputMessagesKey=e.outputMessagesKey,this.historyMessagesKey=e.historyMessagesKey}_getInputMessages(e){let n;if(typeof e=="object"&&!Array.isArray(e)&&!wt(e)){let r;this.inputMessagesKey?r=this.inputMessagesKey:Object.keys(e).length===1?r=Object.keys(e)[0]:r="input",Array.isArray(e[r])&&Array.isArray(e[r][0])?n=e[r][0]:n=e[r]}else n=e;if(typeof n=="string")return[new vn(n)];if(Array.isArray(n))return n;if(wt(n))return[n];throw new Error(`Expected a string, BaseMessage, or array of BaseMessages.
121
- Got ${JSON.stringify(n,null,2)}`)}_getOutputMessages(e){let n;if(!Array.isArray(e)&&!wt(e)&&typeof e!="string"){let r;this.outputMessagesKey!==void 0?r=this.outputMessagesKey:Object.keys(e).length===1?r=Object.keys(e)[0]:r="output",e.generations!==void 0?n=e.generations[0][0].message:n=e[r]}else n=e;if(typeof n=="string")return[new De(n)];if(Array.isArray(n))return n;if(wt(n))return[n];throw new Error(`Expected a string, BaseMessage, or array of BaseMessages. Received: ${JSON.stringify(n,null,2)}`)}async _enterHistory(e,n){var s;const r=await((s=n==null?void 0:n.configurable)==null?void 0:s.messageHistory).getMessages();return this.historyMessagesKey===void 0?r.concat(this._getInputMessages(e)):r}async _exitHistory(e,n){var c;const r=(c=n.configurable)==null?void 0:c.messageHistory;let s;Array.isArray(e.inputs)&&Array.isArray(e.inputs[0])?s=e.inputs[0]:s=e.inputs;let a=this._getInputMessages(s);if(this.historyMessagesKey===void 0){const u=await r.getMessages();a=a.slice(u.length)}const i=e.outputs;if(!i)throw new Error(`Output values from 'Run' undefined. Run: ${JSON.stringify(e,null,2)}`);const o=this._getOutputMessages(i);await r.addMessages([...a,...o])}async _mergeConfig(...e){const n=await super._mergeConfig(...e);if(!n.configurable||!n.configurable.sessionId){const s={[this.inputMessagesKey??"input"]:"foo"};throw new Error(`sessionId is required. Pass it in as part of the config argument to .invoke() or .stream()
122
- eg. chain.invoke(${JSON.stringify(s)}, ${JSON.stringify({configurable:{sessionId:"123"}})})`)}const{sessionId:r}=n.configurable;return n.configurable.messageHistory=await this.getMessageHistory(r),n}},B4=ue({RouterRunnable:()=>O4,Runnable:()=>Fe,RunnableAssign:()=>Hg,RunnableBinding:()=>Qt,RunnableBranch:()=>C4,RunnableEach:()=>E4,RunnableLambda:()=>Ht,RunnableMap:()=>Wi,RunnableParallel:()=>x4,RunnablePassthrough:()=>vc,RunnablePick:()=>hE,RunnableRetry:()=>zg,RunnableSequence:()=>Jn,RunnableToolLike:()=>em,RunnableWithFallbacks:()=>dE,RunnableWithMessageHistory:()=>F4,_coerceToRunnable:()=>en,ensureConfig:()=>Ge,getCallbackManagerForConfig:()=>Wn,mergeConfigs:()=>sr,patchConfig:()=>et,pickRunnableConfigKeys:()=>_s,raceWithSignal:()=>Gr});const Xt="__start__",dt="__end__",Ps="__input__",th="__error__",lf="__pregel_ns_writes",Hs="__pregel_send",Zg="__pregel_call",Ra="__pregel_read",us="__pregel_checkpointer",fd="__pregel_resuming",ml="__pregel_task_id",Wg="__pregel_stream",z4="__pregel_resume_value",gl="__pregel_resume_map",Vs="__pregel_scratchpad",_l="__pregel_previous",H4="__pregel_durability",tm="checkpoint_id",ls="checkpoint_ns",V4="__pregel_node_finished",is="checkpoint_map",Z4="__pregel_abort_signals",Bt="__interrupt__",ea="__resume__",Gg="__no_writes__",nh="__return__",df="__previous__",Cn="langsmith:hidden",pb="__self__",Di="__pregel_tasks",hs="__pregel_push",nm="__pregel_pull",Ur="00000000-0000-0000-0000-000000000000",W4=[Cn,Ps,Bt,ea,th,Gg,Hs,Ra,us,H4,Wg,fd,ml,Zg,z4,Vs,_l,is,ls,tm],mb=Symbol.for("langgraph.command");var j0,G4=(j0=mb,class{constructor(t){p(this,j0);this[mb]=t}});function rm(t){const e=t;return e!=null&&typeof e.node=="string"&&e.args!==void 0}var Ma=class{constructor(t,e){p(this,"lg_name","Send");p(this,"node");p(this,"args");this.node=t,this.args=Sc(e)}toJSON(){return{lg_name:this.lg_name,node:this.node,args:this.args}}};function Sn(t){return t instanceof Ma}const q4="__overwrite__";function sm(t){return typeof t=="object"&&t!==null&&"__overwrite__"in t?[!0,t[q4]]:[!1,void 0]}function K4(t){return sm(t)[0]}function mE(t){return!t||typeof t!="object"||!("__interrupt__"in t)?!1:Array.isArray(t[Bt])}var mp,Vn=(mp=class extends G4{constructor(e){super(e);p(this,"lg_name","Command");p(this,"lc_direct_tool_output",!0);p(this,"graph");p(this,"update");p(this,"resume");p(this,"goto",[]);this.resume=e.resume,this.graph=e.graph,this.update=e.update,e.goto&&(this.goto=Array.isArray(e.goto)?Sc(e.goto):[Sc(e.goto)])}_updateAsTuples(){return this.update&&typeof this.update=="object"&&!Array.isArray(this.update)?Object.entries(this.update):Array.isArray(this.update)&&this.update.every(e=>Array.isArray(e)&&e.length===2&&typeof e[0]=="string")?this.update:[["__root__",this.update]]}toJSON(){var n;let e;return typeof this.goto=="string"?e=this.goto:Sn(this.goto)?e=this.goto.toJSON():e=(n=this.goto)==null?void 0:n.map(r=>typeof r=="string"?r:r.toJSON()),{lg_name:this.lg_name,update:this.update,resume:this.resume,goto:e}}},p(mp,"PARENT","__parent__"),mp);function Pt(t){return typeof t!="object"||t==null?!1:"lg_name"in t&&t.lg_name==="Command"}function Sc(t,e=new Map){if(t!=null&&typeof t=="object"){if(e.has(t))return e.get(t);let n;if(Array.isArray(t))n=[],e.set(t,n),t.forEach((r,s)=>{n[s]=Sc(r,e)});else if(Pt(t)&&!(t instanceof Vn))n=new Vn(t),e.set(t,n);else if(rm(t)&&!(t instanceof Ma))n=new Ma(t.node,t.args),e.set(t,n);else if(Pt(t)||Sn(t))n=t,e.set(t,n);else if("lc_serializable"in t&&t.lc_serializable)n=t,e.set(t,n);else{n={},e.set(t,n);for(const[r,s]of Object.entries(t))n[r]=Sc(s,e)}return n}return t}var ra=class extends Error{constructor(e,n){let r=e??"";n!=null&&n.lc_error_code&&(r=`${r}
123
-
124
- Troubleshooting URL: https://docs.langchain.com/oss/javascript/langgraph/${n.lc_error_code}/
125
- `);super(r);p(this,"lc_error_code");this.lc_error_code=n==null?void 0:n.lc_error_code}},gE=class extends ra{get is_bubble_up(){return!0}},J4=class extends ra{constructor(t,e){super(t,e),this.name="GraphRecursionError"}static get unminifiable_name(){return"GraphRecursionError"}},yl=class extends ra{constructor(t,e){super(t,e),this.name="GraphValueError"}static get unminifiable_name(){return"GraphValueError"}},Ei=class extends gE{constructor(e,n){super(JSON.stringify(e,null,2),n);p(this,"interrupts");this.name="GraphInterrupt",this.interrupts=e??[]}static get unminifiable_name(){return"GraphInterrupt"}},_E=class extends Ei{constructor(t,e){super([{value:t}],e),this.name="NodeInterrupt"}static get unminifiable_name(){return"NodeInterrupt"}},yE=class extends gE{constructor(e){super();p(this,"command");this.name="ParentCommand",this.command=e}static get unminifiable_name(){return"ParentCommand"}};function X4(t){return t!==void 0&&t.name===yE.unminifiable_name}function wl(t){return t!==void 0&&t.is_bubble_up===!0}function va(t){return t!==void 0&&[Ei.unminifiable_name,_E.unminifiable_name].includes(t.name)}var gb=class extends ra{constructor(t,e){super(t,e),this.name="EmptyInputError"}static get unminifiable_name(){return"EmptyInputError"}},Vt=class extends ra{constructor(t,e){super(t,e),this.name="EmptyChannelError"}static get unminifiable_name(){return"EmptyChannelError"}},ct=class extends ra{constructor(t,e){super(t,e),this.name="InvalidUpdateError"}static get unminifiable_name(){return"InvalidUpdateError"}},Y4=class extends ra{constructor(t,e){super(t,e),this.name="UnreachableNodeError"}static get unminifiable_name(){return"UnreachableNodeError"}},hf=class extends ra{constructor(t,e){super(t,e),this.name="StateGraphInputError",this.message="Invalid StateGraph input. Make sure to pass a valid StateDefinition, Annotation.Root, or Zod schema."}static get unminifiable_name(){return"StateGraphInputError"}};const Q4=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;function eU(t){return typeof t=="string"&&Q4.test(t)}function wE(t){if(!eU(t))throw TypeError("Invalid UUID");var e,n=new Uint8Array(16);return n[0]=(e=parseInt(t.slice(0,8),16))>>>24,n[1]=e>>>16&255,n[2]=e>>>8&255,n[3]=e&255,n[4]=(e=parseInt(t.slice(9,13),16))>>>8,n[5]=e&255,n[6]=(e=parseInt(t.slice(14,18),16))>>>8,n[7]=e&255,n[8]=(e=parseInt(t.slice(19,23),16))>>>8,n[9]=e&255,n[10]=(e=parseInt(t.slice(24,36),16))/1099511627776&255,n[11]=e/4294967296&255,n[12]=e>>>24&255,n[13]=e>>>16&255,n[14]=e>>>8&255,n[15]=e&255,n}var Gt=[];for(var ff=0;ff<256;++ff)Gt.push((ff+256).toString(16).slice(1));function rh(t,e=0){return(Gt[t[e+0]]+Gt[t[e+1]]+Gt[t[e+2]]+Gt[t[e+3]]+"-"+Gt[t[e+4]]+Gt[t[e+5]]+"-"+Gt[t[e+6]]+Gt[t[e+7]]+"-"+Gt[t[e+8]]+Gt[t[e+9]]+"-"+Gt[t[e+10]]+Gt[t[e+11]]+Gt[t[e+12]]+Gt[t[e+13]]+Gt[t[e+14]]+Gt[t[e+15]]).toLowerCase()}var Iu,tU=new Uint8Array(16);function nU(){if(!Iu&&(Iu=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!Iu))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Iu(tU)}var pf,xu,mf=0,gf=0;function rU(t,e,n){var r=0,s=e||new Array(16);t=t||{};var a=t.node,i=t.clockseq;if(t._v6||(a||(a=pf),i==null&&(i=xu)),a==null||i==null){var o=t.random||(t.rng||nU)();a==null&&(a=[o[0],o[1],o[2],o[3],o[4],o[5]],!pf&&!t._v6&&(a[0]|=1,pf=a)),i==null&&(i=(o[6]<<8|o[7])&16383,xu===void 0&&!t._v6&&(xu=i))}var c=t.msecs!==void 0?t.msecs:Date.now(),u=t.nsecs!==void 0?t.nsecs:gf+1,l=c-mf+(u-gf)/1e4;if(l<0&&t.clockseq===void 0&&(i=i+1&16383),(l<0||c>mf)&&t.nsecs===void 0&&(u=0),u>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");mf=c,gf=u,xu=i,c+=122192928e5;var d=((c&268435455)*1e4+u)%4294967296;s[r++]=d>>>24&255,s[r++]=d>>>16&255,s[r++]=d>>>8&255,s[r++]=d&255;var f=c/4294967296*1e4&268435455;s[r++]=f>>>8&255,s[r++]=f&255,s[r++]=f>>>24&15|16,s[r++]=f>>>16&255,s[r++]=i>>>8|128,s[r++]=i&255;for(var h=0;h<6;++h)s[r+h]=a[h];return e||rh(s)}function sU(t){var e=typeof t=="string"?wE(t):t,n=aU(e);return typeof t=="string"?rh(n):n}function aU(t,e=!1){return Uint8Array.of((t[6]&15)<<4|t[7]>>4&15,(t[7]&15)<<4|(t[4]&240)>>4,(t[4]&15)<<4|(t[5]&240)>>4,(t[5]&15)<<4|(t[0]&240)>>4,(t[0]&15)<<4|(t[1]&240)>>4,(t[1]&15)<<4|(t[2]&240)>>4,96|t[2]&15,t[3],t[8],t[9],t[10],t[11],t[12],t[13],t[14],t[15])}function iU(t){t=unescape(encodeURIComponent(t));for(var e=[],n=0;n<t.length;++n)e.push(t.charCodeAt(n));return e}var oU="6ba7b810-9dad-11d1-80b4-00c04fd430c8",cU="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function uU(t,e,n){function r(s,a,i,o){var c;if(typeof s=="string"&&(s=iU(s)),typeof a=="string"&&(a=wE(a)),((c=a)===null||c===void 0?void 0:c.length)!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");var u=new Uint8Array(16+s.length);if(u.set(a),u.set(s,a.length),u=n(u),u[6]=u[6]&15|e,u[8]=u[8]&63|128,i){o=o||0;for(var l=0;l<16;++l)i[o+l]=u[l];return i}return rh(u)}try{r.name=t}catch{}return r.DNS=oU,r.URL=cU,r}function lU(t,e,n,r){switch(t){case 0:return e&n^~e&r;case 1:return e^n^r;case 2:return e&n^e&r^n&r;case 3:return e^n^r}}function _f(t,e){return t<<e|t>>>32-e}function dU(t){var e=[1518500249,1859775393,2400959708,3395469782],n=[1732584193,4023233417,2562383102,271733878,3285377520];if(typeof t=="string"){var r=unescape(encodeURIComponent(t));t=[];for(var s=0;s<r.length;++s)t.push(r.charCodeAt(s))}else Array.isArray(t)||(t=Array.prototype.slice.call(t));t.push(128);for(var a=t.length/4+2,i=Math.ceil(a/16),o=new Array(i),c=0;c<i;++c){for(var u=new Uint32Array(16),l=0;l<16;++l)u[l]=t[c*64+l*4]<<24|t[c*64+l*4+1]<<16|t[c*64+l*4+2]<<8|t[c*64+l*4+3];o[c]=u}o[i-1][14]=(t.length-1)*8/Math.pow(2,32),o[i-1][14]=Math.floor(o[i-1][14]),o[i-1][15]=(t.length-1)*8&4294967295;for(var d=0;d<i;++d){for(var f=new Uint32Array(80),h=0;h<16;++h)f[h]=o[d][h];for(var m=16;m<80;++m)f[m]=_f(f[m-3]^f[m-8]^f[m-14]^f[m-16],1);for(var _=n[0],y=n[1],w=n[2],g=n[3],b=n[4],S=0;S<80;++S){var I=Math.floor(S/20),T=_f(_,5)+lU(I,y,w,g)+b+e[I]+f[S]>>>0;b=g,g=w,w=_f(y,30)>>>0,y=_,_=T}n[0]=n[0]+_>>>0,n[1]=n[1]+y>>>0,n[2]=n[2]+w>>>0,n[3]=n[3]+g>>>0,n[4]=n[4]+b>>>0}return[n[0]>>24&255,n[0]>>16&255,n[0]>>8&255,n[0]&255,n[1]>>24&255,n[1]>>16&255,n[1]>>8&255,n[1]&255,n[2]>>24&255,n[2]>>16&255,n[2]>>8&255,n[2]&255,n[3]>>24&255,n[3]>>16&255,n[3]>>8&255,n[3]&255,n[4]>>24&255,n[4]>>16&255,n[4]>>8&255,n[4]&255]}var hU=uU("v5",80,dU);function _b(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(t,s).enumerable})),n.push.apply(n,r)}return n}function yb(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?_b(Object(n),!0).forEach(function(r){fU(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):_b(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function fU(t,e,n){return(e=pU(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function pU(t){var e=mU(t,"string");return typeof e=="symbol"?e:e+""}function mU(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function gU(t={},e,n=0){var r=rU(yb(yb({},t),{},{_v6:!0}),new Uint8Array(16));return r=sU(r),rh(r)}function bE(t){return gU({clockseq:t})}function mi(t,e){const n=e.replace(/-/g,"").match(/.{2}/g).map(r=>parseInt(r,16));return hU(t,new Uint8Array(n))}const _U="__error__",bl="__scheduled__",yU="__interrupt__",wU="__resume__";var wb="[...]",bU="[Circular]",pd=[],gi=[];function vU(){return{depthLimit:Number.MAX_SAFE_INTEGER,edgesLimit:Number.MAX_SAFE_INTEGER}}function SU(t,e,n,r){typeof r>"u"&&(r=vU()),am(t,"",0,[],void 0,0,r);var s;try{gi.length===0?s=JSON.stringify(t,e,n):s=JSON.stringify(t,TU(e),n)}catch{return JSON.stringify("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;pd.length!==0;){var a=pd.pop();a.length===4?Object.defineProperty(a[0],a[1],a[3]):a[0][a[1]]=a[2]}}return s}function yf(t,e,n,r){var s=Object.getOwnPropertyDescriptor(r,n);s.get!==void 0?s.configurable?(Object.defineProperty(r,n,{value:t}),pd.push([r,n,e,s])):gi.push([e,n,t]):(r[n]=t,pd.push([r,n,e]))}function am(t,e,n,r,s,a,i){a+=1;var o;if(typeof t=="object"&&t!==null){for(o=0;o<r.length;o++)if(r[o]===t){yf(bU,t,e,s);return}if(typeof i.depthLimit<"u"&&a>i.depthLimit){yf(wb,t,e,s);return}if(typeof i.edgesLimit<"u"&&n+1>i.edgesLimit){yf(wb,t,e,s);return}if(r.push(t),Array.isArray(t))for(o=0;o<t.length;o++)am(t[o],o,o,r,t,a,i);else{var c=Object.keys(t);for(o=0;o<c.length;o++){var u=c[o];am(t[u],u,o,r,t,a,i)}}r.pop()}}function TU(t){return t=typeof t<"u"?t:function(e,n){return n},function(e,n){if(gi.length>0)for(var r=0;r<gi.length;r++){var s=gi[r];if(s[1]===e&&s[0]===n){n=s[2],gi.splice(r,1);break}}return t.call(this,e,n)}}const EU=[];var AU=ue({}),IU=ue({});/**
126
- * [js-sha256]{@link https://github.com/emn178/js-sha256}
127
- *
128
- * @version 0.11.1
129
- * @author Chen, Yi-Cyuan [emn178@gmail.com]
130
- * @copyright Chen, Yi-Cyuan 2014-2025
131
- * @license MIT
132
- */var le="0123456789abcdef".split(""),xU=[-2147483648,8388608,32768,128],fr=[24,16,8,0],ku=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],Dt=[];function xr(t,e){e?(Dt[0]=Dt[16]=Dt[1]=Dt[2]=Dt[3]=Dt[4]=Dt[5]=Dt[6]=Dt[7]=Dt[8]=Dt[9]=Dt[10]=Dt[11]=Dt[12]=Dt[13]=Dt[14]=Dt[15]=0,this.blocks=Dt):this.blocks=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],t?(this.h0=3238371032,this.h1=914150663,this.h2=812702999,this.h3=4144912697,this.h4=4290775857,this.h5=1750603025,this.h6=1694076839,this.h7=3204075428):(this.h0=1779033703,this.h1=3144134277,this.h2=1013904242,this.h3=2773480762,this.h4=1359893119,this.h5=2600822924,this.h6=528734635,this.h7=1541459225),this.block=this.start=this.bytes=this.hBytes=0,this.finalized=this.hashed=!1,this.first=!0,this.is224=t}xr.prototype.update=function(t){if(!this.finalized){var e,n=typeof t;if(n!=="string"){if(n==="object"){if(t===null)throw new Error(ERROR);if(ARRAY_BUFFER&&t.constructor===ArrayBuffer)t=new Uint8Array(t);else if(!Array.isArray(t)&&(!ARRAY_BUFFER||!ArrayBuffer.isView(t)))throw new Error(ERROR)}else throw new Error(ERROR);e=!0}for(var r,s=0,a,i=t.length,o=this.blocks;s<i;){if(this.hashed&&(this.hashed=!1,o[0]=this.block,this.block=o[16]=o[1]=o[2]=o[3]=o[4]=o[5]=o[6]=o[7]=o[8]=o[9]=o[10]=o[11]=o[12]=o[13]=o[14]=o[15]=0),e)for(a=this.start;s<i&&a<64;++s)o[a>>>2]|=t[s]<<fr[a++&3];else for(a=this.start;s<i&&a<64;++s)r=t.charCodeAt(s),r<128?o[a>>>2]|=r<<fr[a++&3]:r<2048?(o[a>>>2]|=(192|r>>>6)<<fr[a++&3],o[a>>>2]|=(128|r&63)<<fr[a++&3]):r<55296||r>=57344?(o[a>>>2]|=(224|r>>>12)<<fr[a++&3],o[a>>>2]|=(128|r>>>6&63)<<fr[a++&3],o[a>>>2]|=(128|r&63)<<fr[a++&3]):(r=65536+((r&1023)<<10|t.charCodeAt(++s)&1023),o[a>>>2]|=(240|r>>>18)<<fr[a++&3],o[a>>>2]|=(128|r>>>12&63)<<fr[a++&3],o[a>>>2]|=(128|r>>>6&63)<<fr[a++&3],o[a>>>2]|=(128|r&63)<<fr[a++&3]);this.lastByteIndex=a,this.bytes+=a-this.start,a>=64?(this.block=o[16],this.start=a-64,this.hash(),this.hashed=!0):this.start=a}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296<<0,this.bytes=this.bytes%4294967296),this}};xr.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var t=this.blocks,e=this.lastByteIndex;t[16]=this.block,t[e>>>2]|=xU[e&3],this.block=t[16],e>=56&&(this.hashed||this.hash(),t[0]=this.block,t[16]=t[1]=t[2]=t[3]=t[4]=t[5]=t[6]=t[7]=t[8]=t[9]=t[10]=t[11]=t[12]=t[13]=t[14]=t[15]=0),t[14]=this.hBytes<<3|this.bytes>>>29,t[15]=this.bytes<<3,this.hash()}};xr.prototype.hash=function(){var t=this.h0,e=this.h1,n=this.h2,r=this.h3,s=this.h4,a=this.h5,i=this.h6,o=this.h7,c=this.blocks,u,l,d,f,h,m,_,y,w,g,b;for(u=16;u<64;++u)h=c[u-15],l=(h>>>7|h<<25)^(h>>>18|h<<14)^h>>>3,h=c[u-2],d=(h>>>17|h<<15)^(h>>>19|h<<13)^h>>>10,c[u]=c[u-16]+l+c[u-7]+d<<0;for(b=e&n,u=0;u<64;u+=4)this.first?(this.is224?(y=300032,h=c[0]-1413257819,o=h-150054599<<0,r=h+24177077<<0):(y=704751109,h=c[0]-210244248,o=h-1521486534<<0,r=h+143694565<<0),this.first=!1):(l=(t>>>2|t<<30)^(t>>>13|t<<19)^(t>>>22|t<<10),d=(s>>>6|s<<26)^(s>>>11|s<<21)^(s>>>25|s<<7),y=t&e,f=y^t&n^b,_=s&a^~s&i,h=o+d+_+ku[u]+c[u],m=l+f,o=r+h<<0,r=h+m<<0),l=(r>>>2|r<<30)^(r>>>13|r<<19)^(r>>>22|r<<10),d=(o>>>6|o<<26)^(o>>>11|o<<21)^(o>>>25|o<<7),w=r&t,f=w^r&e^y,_=i&o^~i&s,h=a+d+_+ku[u+1]+c[u+1],m=l+f,i=n+h<<0,n=h+m<<0,l=(n>>>2|n<<30)^(n>>>13|n<<19)^(n>>>22|n<<10),d=(i>>>6|i<<26)^(i>>>11|i<<21)^(i>>>25|i<<7),g=n&r,f=g^n&t^w,_=a&i^~a&o,h=s+d+_+ku[u+2]+c[u+2],m=l+f,a=e+h<<0,e=h+m<<0,l=(e>>>2|e<<30)^(e>>>13|e<<19)^(e>>>22|e<<10),d=(a>>>6|a<<26)^(a>>>11|a<<21)^(a>>>25|a<<7),b=e&n,f=b^e&r^g,_=a&i^~a&o,h=s+d+_+ku[u+3]+c[u+3],m=l+f,s=t+h<<0,t=h+m<<0,this.chromeBugWorkAround=!0;this.h0=this.h0+t<<0,this.h1=this.h1+e<<0,this.h2=this.h2+n<<0,this.h3=this.h3+r<<0,this.h4=this.h4+s<<0,this.h5=this.h5+a<<0,this.h6=this.h6+i<<0,this.h7=this.h7+o<<0};xr.prototype.hex=function(){this.finalize();var t=this.h0,e=this.h1,n=this.h2,r=this.h3,s=this.h4,a=this.h5,i=this.h6,o=this.h7,c=le[t>>>28&15]+le[t>>>24&15]+le[t>>>20&15]+le[t>>>16&15]+le[t>>>12&15]+le[t>>>8&15]+le[t>>>4&15]+le[t&15]+le[e>>>28&15]+le[e>>>24&15]+le[e>>>20&15]+le[e>>>16&15]+le[e>>>12&15]+le[e>>>8&15]+le[e>>>4&15]+le[e&15]+le[n>>>28&15]+le[n>>>24&15]+le[n>>>20&15]+le[n>>>16&15]+le[n>>>12&15]+le[n>>>8&15]+le[n>>>4&15]+le[n&15]+le[r>>>28&15]+le[r>>>24&15]+le[r>>>20&15]+le[r>>>16&15]+le[r>>>12&15]+le[r>>>8&15]+le[r>>>4&15]+le[r&15]+le[s>>>28&15]+le[s>>>24&15]+le[s>>>20&15]+le[s>>>16&15]+le[s>>>12&15]+le[s>>>8&15]+le[s>>>4&15]+le[s&15]+le[a>>>28&15]+le[a>>>24&15]+le[a>>>20&15]+le[a>>>16&15]+le[a>>>12&15]+le[a>>>8&15]+le[a>>>4&15]+le[a&15]+le[i>>>28&15]+le[i>>>24&15]+le[i>>>20&15]+le[i>>>16&15]+le[i>>>12&15]+le[i>>>8&15]+le[i>>>4&15]+le[i&15];return this.is224||(c+=le[o>>>28&15]+le[o>>>24&15]+le[o>>>20&15]+le[o>>>16&15]+le[o>>>12&15]+le[o>>>8&15]+le[o>>>4&15]+le[o&15]),c};xr.prototype.toString=xr.prototype.hex;xr.prototype.digest=function(){this.finalize();var t=this.h0,e=this.h1,n=this.h2,r=this.h3,s=this.h4,a=this.h5,i=this.h6,o=this.h7,c=[t>>>24&255,t>>>16&255,t>>>8&255,t&255,e>>>24&255,e>>>16&255,e>>>8&255,e&255,n>>>24&255,n>>>16&255,n>>>8&255,n&255,r>>>24&255,r>>>16&255,r>>>8&255,r&255,s>>>24&255,s>>>16&255,s>>>8&255,s&255,a>>>24&255,a>>>16&255,a>>>8&255,a&255,i>>>24&255,i>>>16&255,i>>>8&255,i&255];return this.is224||c.push(o>>>24&255,o>>>16&255,o>>>8&255,o&255),c};xr.prototype.array=xr.prototype.digest;xr.prototype.arrayBuffer=function(){this.finalize();var t=new ArrayBuffer(this.is224?28:32),e=new DataView(t);return e.setUint32(0,this.h0),e.setUint32(4,this.h1),e.setUint32(8,this.h2),e.setUint32(12,this.h3),e.setUint32(16,this.h4),e.setUint32(20,this.h5),e.setUint32(24,this.h6),this.is224||e.setUint32(28,this.h7),t};const qg=(...t)=>new xr(!1,!0).update(t.join("")).hex();var kU=ue({sha256:()=>qg}),OU=ue({BaseCache:()=>SE,InMemoryCache:()=>TE,defaultHashKeyEncoder:()=>vE,deserializeStoredGeneration:()=>CU,serializeGeneration:()=>RU});const vE=(...t)=>qg(t.join("_"));function CU(t){return t.message!==void 0?{text:t.text,message:mg(t.message)}:{text:t.text}}function RU(t){const e={text:t.text};return t.message!==void 0&&(e.message=t.message.toDict()),e}var SE=class{constructor(){p(this,"keyEncoder",vE)}makeDefaultKeyEncoder(e){this.keyEncoder=e}};const $U=new Map;var TE=class EE extends SE{constructor(n){super();p(this,"cache");this.cache=n??new Map}lookup(n,r){return Promise.resolve(this.cache.get(this.keyEncoder(n,r))??null)}async update(n,r,s){this.cache.set(this.keyEncoder(n,r),s)}static global(){return new EE($U)}},NU=ue({BaseChatMessageHistory:()=>AE,BaseListChatMessageHistory:()=>Kg,InMemoryChatMessageHistory:()=>PU}),AE=class extends ar{async addMessages(t){for(const e of t)await this.addMessage(e)}},Kg=class extends ar{addUserMessage(t){return this.addMessage(new vn(t))}addAIMessage(t){return this.addMessage(new De(t))}async addMessages(t){for(const e of t)await this.addMessage(e)}clear(){throw new Error("Not implemented.")}},PU=class extends Kg{constructor(e){super(...arguments);p(this,"lc_namespace",["langchain","stores","message","in_memory"]);p(this,"messages",[]);this.messages=e??[]}async getMessages(){return this.messages}async addMessage(e){this.messages.push(e)}async clear(){this.messages=[]}},Zs=class{constructor(t){p(this,"pageContent");p(this,"metadata");p(this,"id");this.pageContent=t.pageContent!==void 0?t.pageContent.toString():"",this.metadata=t.metadata??{},this.id=t.id}},IE=class extends Fe{constructor(){super(...arguments);p(this,"lc_namespace",["langchain_core","documents","transformers"])}invoke(e,n){return this.transformDocuments(e)}},MU=class extends IE{async transformDocuments(t){const e=[];for(const n of t){const r=await this._transformDocument(n);e.push(r)}return e}},LU=ue({BaseDocumentTransformer:()=>IE,Document:()=>Zs,MappingDocumentTransformer:()=>MU}),jU=ue({BaseDocumentLoader:()=>xE}),xE=class{},UU=ue({LangSmithLoader:()=>DU}),DU=class extends xE{constructor(e){super();p(this,"datasetId");p(this,"datasetName");p(this,"exampleIds");p(this,"asOf");p(this,"splits");p(this,"inlineS3Urls");p(this,"offset");p(this,"limit");p(this,"metadata");p(this,"filter");p(this,"contentKey");p(this,"formatContent");p(this,"client");if(e.client&&e.clientConfig)throw new Error("client and clientConfig cannot both be provided.");this.client=e.client??new jr(e==null?void 0:e.clientConfig),this.contentKey=e.contentKey?e.contentKey.split("."):[],this.formatContent=e.formatContent??FU,this.datasetId=e.datasetId,this.datasetName=e.datasetName,this.exampleIds=e.exampleIds,this.asOf=e.asOf,this.splits=e.splits,this.inlineS3Urls=e.inlineS3Urls,this.offset=e.offset,this.limit=e.limit,this.metadata=e.metadata,this.filter=e.filter}async load(){const e=[];for await(const n of this.client.listExamples({datasetId:this.datasetId,datasetName:this.datasetName,exampleIds:this.exampleIds,asOf:this.asOf,splits:this.splits,inlineS3Urls:this.inlineS3Urls,offset:this.offset,limit:this.limit,metadata:this.metadata,filter:this.filter})){let r=n.inputs;for(const i of this.contentKey)r=r[i];const s=this.formatContent(r),a=n;["created_at","modified_at"].forEach(i=>{i in a&&typeof a[i]=="object"&&(a[i]=a[i].toString())}),e.push({pageContent:s,metadata:a})}return e}};function FU(t){if(typeof t=="string")return t;try{return JSON.stringify(t,null,2)}catch{return String(t)}}var BU=ue({Embeddings:()=>Jg}),Jg=class{constructor(e){p(this,"caller");this.caller=new Wc(e??{})}},Xg=class extends ar{constructor(){super(...arguments);p(this,"lc_namespace",["langchain_core","example_selectors","base"])}},kE=class{async getPromptAsync(t,e){return this.getPrompt(t).partial((e==null?void 0:e.partialVariables)??{})}},zU=class extends kE{constructor(e,n=[]){super();p(this,"defaultPrompt");p(this,"conditionals");this.defaultPrompt=e,this.conditionals=n}getPrompt(e){for(const[n,r]of this.conditionals)if(n(e))return r;return this.defaultPrompt}};function HU(t){return t._modelType()==="base_llm"}function VU(t){return t._modelType()==="base_chat_model"}function bb(t){return t.split(/\n| /).length}var ZU=class OE extends Xg{constructor(n){super(n);p(this,"examples",[]);p(this,"examplePrompt");p(this,"getTextLength",bb);p(this,"maxLength",2048);p(this,"exampleTextLengths",[]);this.examplePrompt=n.examplePrompt,this.maxLength=n.maxLength??2048,this.getTextLength=n.getTextLength??bb}async addExample(n){this.examples.push(n);const r=await this.examplePrompt.format(n);this.exampleTextLengths.push(this.getTextLength(r))}async calculateExampleTextLengths(n,r){if(n.length>0)return n;const{examples:s,examplePrompt:a}=r;return(await Promise.all(s.map(i=>a.format(i)))).map(i=>this.getTextLength(i))}async selectExamples(n){const r=Object.values(n).join(" ");let s=this.maxLength-this.getTextLength(r),a=0;const i=[];for(;s>0&&a<this.examples.length;){const o=s-this.exampleTextLengths[a];if(o<0)break;i.push(this.examples[a]),s=o,a+=1}return i}static async fromExamples(n,r){const s=new OE(r);return await Promise.all(n.map(a=>s.addExample(a))),s}};function wf(t){return Object.keys(t).sort().map(e=>t[e])}var WU=class CE extends Xg{constructor(n){super(n);p(this,"vectorStoreRetriever");p(this,"exampleKeys");p(this,"inputKeys");if(this.exampleKeys=n.exampleKeys,this.inputKeys=n.inputKeys,n.vectorStore!==void 0)this.vectorStoreRetriever=n.vectorStore.asRetriever({k:n.k??4,filter:n.filter});else if(n.vectorStoreRetriever)this.vectorStoreRetriever=n.vectorStoreRetriever;else throw new Error('You must specify one of "vectorStore" and "vectorStoreRetriever".')}async addExample(n){const r=wf((this.inputKeys??Object.keys(n)).reduce((s,a)=>({...s,[a]:n[a]}),{})).join(" ");await this.vectorStoreRetriever.addDocuments([new Zs({pageContent:r,metadata:n})])}async selectExamples(n){const r=wf((this.inputKeys??Object.keys(n)).reduce((a,i)=>({...a,[i]:n[i]}),{})).join(" "),s=(await this.vectorStoreRetriever.invoke(r)).map(a=>a.metadata);return this.exampleKeys?s.map(a=>this.exampleKeys.reduce((i,o)=>({...i,[o]:a[o]}),{})):s}static async fromExamples(n,r,s,a={}){const i=a.inputKeys??null,o=n.map(c=>wf(i?i.reduce((u,l)=>({...u,[l]:c[l]}),{}):c).join(" "));return new CE({vectorStore:await s.fromTexts(o,n,r,a),k:a.k??4,exampleKeys:a.exampleKeys,inputKeys:a.inputKeys})}},GU=ue({BaseExampleSelector:()=>Xg,BasePromptSelector:()=>kE,ConditionalPromptSelector:()=>zU,LengthBasedExampleSelector:()=>ZU,SemanticSimilarityExampleSelector:()=>WU,isChatModel:()=>VU,isLLM:()=>HU});const im="10f90ea3-90a4-4962-bf75-83a0f3c1c62a";var qU=class extends ar{constructor(){super(...arguments);p(this,"lc_namespace",["langchain","recordmanagers"])}},RE=class{constructor(t){p(this,"uid");p(this,"hash_");p(this,"contentHash");p(this,"metadataHash");p(this,"pageContent");p(this,"metadata");p(this,"keyEncoder",qg);this.uid=t.uid,this.pageContent=t.pageContent,this.metadata=t.metadata}makeDefaultKeyEncoder(t){this.keyEncoder=t}calculateHashes(){const t=["hash_","content_hash","metadata_hash"];for(const n of t)if(n in this.metadata)throw new Error(`Metadata cannot contain key ${n} as it is reserved for internal use. Restricted keys: [${t.join(", ")}]`);const e=this._hashStringToUUID(this.pageContent);try{const n=this._hashNestedDictToUUID(this.metadata);this.contentHash=e,this.metadataHash=n}catch(n){throw new Error(`Failed to hash metadata: ${n}. Please use a dict that can be serialized using json.`)}this.hash_=this._hashStringToUUID(this.contentHash+this.metadataHash),this.uid||(this.uid=this.hash_)}toDocument(){return new Zs({pageContent:this.pageContent,metadata:this.metadata})}static fromDocument(t,e){const n=new this({pageContent:t.pageContent,metadata:t.metadata,uid:e||t.uid});return n.calculateHashes(),n}_hashStringToUUID(t){return cc(this.keyEncoder(t),im)}_hashNestedDictToUUID(t){const e=JSON.stringify(t,Object.keys(t).sort());return cc(this.keyEncoder(e),im)}};function $E(t,e){const n=[];let r=[];return e.forEach(s=>{r.push(s),r.length>=t&&(n.push(r),r=[])}),r.length>0&&n.push(r),n}function NE(t){const e=new Set,n=[];for(const r of t){if(!r.hash_)throw new Error("Hashed document does not have a hash");e.has(r.hash_)||(e.add(r.hash_),n.push(r))}return n}function PE(t){if(t===null)return e=>null;if(typeof t=="string")return e=>e.metadata[t];if(typeof t=="function")return t;throw new Error(`sourceIdKey should be null, a string or a function, got ${typeof t}`)}const ME=t=>"load"in t&&typeof t.load=="function"&&"loadAndSplit"in t&&typeof t.loadAndSplit=="function";async function KU(t){const{docsSource:e,recordManager:n,vectorStore:r,options:s}=t,{batchSize:a=100,cleanup:i,sourceIdKey:o,cleanupBatchSize:c=1e3,forceUpdate:u=!1}=s??{};if(i==="incremental"&&!o)throw new Error("sourceIdKey is required when cleanup mode is incremental. Please provide through 'options.sourceIdKey'.");const l=ME(e)?await e.load():e,d=PE(o??null),f=await n.getTime();let h=0,m=0,_=0,y=0;const w=$E(a??100,l);for(const g of w){const b=NE(g.map(O=>RE.fromDocument(O))),S=b.map(O=>d(O));i==="incremental"&&b.forEach((O,$)=>{if(S[$]===null)throw new Error("sourceIdKey must be provided when cleanup is incremental")});const I=await n.exists(b.map(O=>O.uid)),T=[],x=[],A=[],M=new Set;if(b.forEach((O,$)=>{if(I[$])if(u)M.add(O.uid);else{A.push(O.uid);return}T.push(O.uid),x.push(O.toDocument())}),A.length>0&&(await n.update(A,{timeAtLeast:f}),y+=A.length),x.length>0&&(await r.addDocuments(x,{ids:T}),h+=x.length-M.size,_+=M.size),await n.update(b.map(O=>O.uid),{timeAtLeast:f,groupIds:S}),i==="incremental"){S.forEach($=>{if(!$)throw new Error("Source id cannot be null")});const O=await n.listKeys({before:f,groupIds:S});O.length>0&&(await r.delete({ids:O}),await n.deleteKeys(O),m+=O.length)}}if(i==="full"){let g=await n.listKeys({before:f,limit:c});for(;g.length>0;)await r.delete({ids:g}),await n.deleteKeys(g),m+=g.length,g=await n.listKeys({before:f,limit:c})}return{numAdded:h,numDeleted:m,numUpdated:_,numSkipped:y}}var JU=ue({RecordManager:()=>qU,UUIDV5_NAMESPACE:()=>im,_HashedDocument:()=>RE,_batch:()=>$E,_deduplicateInOrder:()=>NE,_getSourceIdAssigner:()=>PE,_isBaseDocumentLoader:()=>ME,index:()=>KU}),XU=ue({BasePromptValue:()=>sh,ChatPromptValue:()=>Qg,ImagePromptValue:()=>LE,StringPromptValue:()=>Yg}),sh=class extends ar{},Yg=class extends sh{constructor(e){super({value:e});p(this,"lc_namespace",["langchain_core","prompt_values"]);p(this,"lc_serializable",!0);p(this,"value");this.value=e}static lc_name(){return"StringPromptValue"}toString(){return this.value}toChatMessages(){return[new vn(this.value)]}},Qg=class extends sh{constructor(e){Array.isArray(e)&&(e={messages:e});super(e);p(this,"lc_namespace",["langchain_core","prompt_values"]);p(this,"lc_serializable",!0);p(this,"messages");this.messages=e.messages}static lc_name(){return"ChatPromptValue"}toString(){return pg(this.messages)}toChatMessages(){return this.messages}},LE=class extends sh{constructor(e){"imageUrl"in e||(e={imageUrl:e});super(e);p(this,"lc_namespace",["langchain_core","prompt_values"]);p(this,"lc_serializable",!0);p(this,"imageUrl");p(this,"value");this.imageUrl=e.imageUrl}static lc_name(){return"ImagePromptValue"}toString(){return this.imageUrl.url}toChatMessages(){return[new vn({content:[{type:"image_url",image_url:{detail:this.imageUrl.detail,url:this.imageUrl.url}}]})]}},ah={};ah.byteLength=eD;ah.toByteArray=nD;ah.fromByteArray=aD;var Dr=[],nr=[],YU=typeof Uint8Array<"u"?Uint8Array:Array,bf="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(var Za=0,QU=bf.length;Za<QU;++Za)Dr[Za]=bf[Za],nr[bf.charCodeAt(Za)]=Za;nr[45]=62;nr[95]=63;function jE(t){var e=t.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var n=t.indexOf("=");n===-1&&(n=e);var r=n===e?0:4-n%4;return[n,r]}function eD(t){var e=jE(t),n=e[0],r=e[1];return(n+r)*3/4-r}function tD(t,e,n){return(e+n)*3/4-n}function nD(t){var e,n=jE(t),r=n[0],s=n[1],a=new YU(tD(t,r,s)),i=0,o=s>0?r-4:r,c;for(c=0;c<o;c+=4)e=nr[t.charCodeAt(c)]<<18|nr[t.charCodeAt(c+1)]<<12|nr[t.charCodeAt(c+2)]<<6|nr[t.charCodeAt(c+3)],a[i++]=e>>16&255,a[i++]=e>>8&255,a[i++]=e&255;return s===2&&(e=nr[t.charCodeAt(c)]<<2|nr[t.charCodeAt(c+1)]>>4,a[i++]=e&255),s===1&&(e=nr[t.charCodeAt(c)]<<10|nr[t.charCodeAt(c+1)]<<4|nr[t.charCodeAt(c+2)]>>2,a[i++]=e>>8&255,a[i++]=e&255),a}function rD(t){return Dr[t>>18&63]+Dr[t>>12&63]+Dr[t>>6&63]+Dr[t&63]}function sD(t,e,n){for(var r,s=[],a=e;a<n;a+=3)r=(t[a]<<16&16711680)+(t[a+1]<<8&65280)+(t[a+2]&255),s.push(rD(r));return s.join("")}function aD(t){for(var e,n=t.length,r=n%3,s=[],a=16383,i=0,o=n-r;i<o;i+=a)s.push(sD(t,i,i+a>o?o:i+a));return r===1?(e=t[n-1],s.push(Dr[e>>2]+Dr[e<<4&63]+"==")):r===2&&(e=(t[n-2]<<8)+t[n-1],s.push(Dr[e>>10]+Dr[e>>4&63]+Dr[e<<2&63]+"=")),s.join("")}var iD=Object.defineProperty,oD=(t,e,n)=>e in t?iD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,cD=(t,e,n)=>(oD(t,e+"",n),n);function uD(t,e){let n=Array.from({length:t.length},(r,s)=>({start:s,end:s+1}));for(;n.length>1;){let r=null;for(let s=0;s<n.length-1;s++){const a=t.slice(n[s].start,n[s+1].end),i=e.get(a.join(","));i!=null&&(r==null||i<r[0])&&(r=[i,s])}if(r!=null){const s=r[1];n[s]={start:n[s].start,end:n[s+1].end},n.splice(s+1,1)}else break}return n}function lD(t,e){return t.length===1?[e.get(t.join(","))]:uD(t,e).map(n=>e.get(t.slice(n.start,n.end).join(","))).filter(n=>n!=null)}function dD(t){return t.replace(/[\\^$*+?.()|[\]{}]/g,"\\$&")}var om=class{constructor(t,e){p(this,"specialTokens");p(this,"inverseSpecialTokens");p(this,"patStr");p(this,"textEncoder",new TextEncoder);p(this,"textDecoder",new TextDecoder("utf-8"));p(this,"rankMap",new Map);p(this,"textMap",new Map);this.patStr=t.pat_str;const n=t.bpe_ranks.split(`
133
- `).filter(Boolean).reduce((r,s)=>{const[a,i,...o]=s.split(" "),c=Number.parseInt(i,10);return o.forEach((u,l)=>r[u]=c+l),r},{});for(const[r,s]of Object.entries(n)){const a=ah.toByteArray(r);this.rankMap.set(a.join(","),s),this.textMap.set(s,a)}this.specialTokens={...t.special_tokens,...e},this.inverseSpecialTokens=Object.entries(this.specialTokens).reduce((r,[s,a])=>(r[a]=this.textEncoder.encode(s),r),{})}encode(t,e=[],n="all"){const r=new RegExp(this.patStr,"ug"),s=om.specialTokenRegex(Object.keys(this.specialTokens)),a=[],i=new Set(e==="all"?Object.keys(this.specialTokens):e),o=new Set(n==="all"?Object.keys(this.specialTokens).filter(u=>!i.has(u)):n);if(o.size>0){const u=om.specialTokenRegex([...o]),l=t.match(u);if(l!=null)throw new Error(`The text contains a special token that is not allowed: ${l[0]}`)}let c=0;for(;;){let u=null,l=c;for(;s.lastIndex=l,u=s.exec(t),!(u==null||i.has(u[0]));)l=u.index+1;const d=(u==null?void 0:u.index)??t.length;for(const h of t.substring(c,d).matchAll(r)){const m=this.textEncoder.encode(h[0]),_=this.rankMap.get(m.join(","));if(_!=null){a.push(_);continue}a.push(...lD(m,this.rankMap))}if(u==null)break;let f=this.specialTokens[u[0]];a.push(f),c=u.index+u[0].length}return a}decode(t){const e=[];let n=0;for(let a=0;a<t.length;++a){const i=t[a],o=this.textMap.get(i)??this.inverseSpecialTokens[i];o!=null&&(e.push(o),n+=o.length)}const r=new Uint8Array(n);let s=0;for(const a of e)r.set(a,s),s+=a.length;return this.textDecoder.decode(r)}},UE=om;cD(UE,"specialTokenRegex",t=>new RegExp(t.map(e=>dD(e)).join("|"),"g"));function hD(t){switch(t){case"gpt2":return"gpt2";case"code-cushman-001":case"code-cushman-002":case"code-davinci-001":case"code-davinci-002":case"cushman-codex":case"davinci-codex":case"davinci-002":case"text-davinci-002":case"text-davinci-003":return"p50k_base";case"code-davinci-edit-001":case"text-davinci-edit-001":return"p50k_edit";case"ada":case"babbage":case"babbage-002":case"code-search-ada-code-001":case"code-search-babbage-code-001":case"curie":case"davinci":case"text-ada-001":case"text-babbage-001":case"text-curie-001":case"text-davinci-001":case"text-search-ada-doc-001":case"text-search-babbage-doc-001":case"text-search-curie-doc-001":case"text-search-davinci-doc-001":case"text-similarity-ada-001":case"text-similarity-babbage-001":case"text-similarity-curie-001":case"text-similarity-davinci-001":return"r50k_base";case"gpt-3.5-turbo-instruct-0914":case"gpt-3.5-turbo-instruct":case"gpt-3.5-turbo-16k-0613":case"gpt-3.5-turbo-16k":case"gpt-3.5-turbo-0613":case"gpt-3.5-turbo-0301":case"gpt-3.5-turbo":case"gpt-4-32k-0613":case"gpt-4-32k-0314":case"gpt-4-32k":case"gpt-4-0613":case"gpt-4-0314":case"gpt-4":case"gpt-3.5-turbo-1106":case"gpt-35-turbo":case"gpt-4-1106-preview":case"gpt-4-vision-preview":case"gpt-3.5-turbo-0125":case"gpt-4-turbo":case"gpt-4-turbo-2024-04-09":case"gpt-4-turbo-preview":case"gpt-4-0125-preview":case"text-embedding-ada-002":case"text-embedding-3-small":case"text-embedding-3-large":return"cl100k_base";case"gpt-4o":case"gpt-4o-2024-05-13":case"gpt-4o-2024-08-06":case"gpt-4o-2024-11-20":case"gpt-4o-mini-2024-07-18":case"gpt-4o-mini":case"gpt-4o-search-preview":case"gpt-4o-search-preview-2025-03-11":case"gpt-4o-mini-search-preview":case"gpt-4o-mini-search-preview-2025-03-11":case"gpt-4o-audio-preview":case"gpt-4o-audio-preview-2024-12-17":case"gpt-4o-audio-preview-2024-10-01":case"gpt-4o-mini-audio-preview":case"gpt-4o-mini-audio-preview-2024-12-17":case"o1":case"o1-2024-12-17":case"o1-mini":case"o1-mini-2024-09-12":case"o1-preview":case"o1-preview-2024-09-12":case"o1-pro":case"o1-pro-2025-03-19":case"o3":case"o3-2025-04-16":case"o3-mini":case"o3-mini-2025-01-31":case"o4-mini":case"o4-mini-2025-04-16":case"chatgpt-4o-latest":case"gpt-4o-realtime":case"gpt-4o-realtime-preview-2024-10-01":case"gpt-4o-realtime-preview-2024-12-17":case"gpt-4o-mini-realtime-preview":case"gpt-4o-mini-realtime-preview-2024-12-17":case"gpt-4.1":case"gpt-4.1-2025-04-14":case"gpt-4.1-mini":case"gpt-4.1-mini-2025-04-14":case"gpt-4.1-nano":case"gpt-4.1-nano-2025-04-14":case"gpt-4.5-preview":case"gpt-4.5-preview-2025-02-27":case"gpt-5":case"gpt-5-2025-08-07":case"gpt-5-nano":case"gpt-5-nano-2025-08-07":case"gpt-5-mini":case"gpt-5-mini-2025-08-07":case"gpt-5-chat-latest":return"o200k_base";default:throw new Error("Unknown model")}}var fD=ue({encodingForModel:()=>e_,getEncoding:()=>DE});const Ou={},pD=new Wc({});async function DE(t){return t in Ou||(Ou[t]=pD.fetch(`https://tiktoken.pages.dev/js/${t}.json`).then(e=>e.json()).then(e=>new UE(e)).catch(e=>{throw delete Ou[t],e})),await Ou[t]}async function e_(t){return DE(hD(t))}var mD=ue({BaseLangChain:()=>t_,BaseLanguageModel:()=>n_,calculateMaxTokens:()=>_D,getEmbeddingContextSize:()=>gD,getModelContextSize:()=>FE,getModelNameForTiktoken:()=>ih,isOpenAITool:()=>Gi});const ih=t=>t.startsWith("gpt-5")?"gpt-5":t.startsWith("gpt-3.5-turbo-16k")?"gpt-3.5-turbo-16k":t.startsWith("gpt-3.5-turbo-")?"gpt-3.5-turbo":t.startsWith("gpt-4-32k")?"gpt-4-32k":t.startsWith("gpt-4-")?"gpt-4":t.startsWith("gpt-4o")?"gpt-4o":t,gD=t=>{switch(t){case"text-embedding-ada-002":return 8191;default:return 2046}},FE=t=>{switch(ih(t)){case"gpt-5":case"gpt-5-turbo":case"gpt-5-turbo-preview":return 4e5;case"gpt-4o":case"gpt-4o-mini":case"gpt-4o-2024-05-13":case"gpt-4o-2024-08-06":return 128e3;case"gpt-4-turbo":case"gpt-4-turbo-preview":case"gpt-4-turbo-2024-04-09":case"gpt-4-0125-preview":case"gpt-4-1106-preview":return 128e3;case"gpt-4-32k":case"gpt-4-32k-0314":case"gpt-4-32k-0613":return 32768;case"gpt-4":case"gpt-4-0314":case"gpt-4-0613":return 8192;case"gpt-3.5-turbo-16k":case"gpt-3.5-turbo-16k-0613":return 16384;case"gpt-3.5-turbo":case"gpt-3.5-turbo-0301":case"gpt-3.5-turbo-0613":case"gpt-3.5-turbo-1106":case"gpt-3.5-turbo-0125":return 4096;case"text-davinci-003":case"text-davinci-002":return 4097;case"text-davinci-001":return 2049;case"text-curie-001":case"text-babbage-001":case"text-ada-001":return 2048;case"code-davinci-002":case"code-davinci-001":return 8e3;case"code-cushman-001":return 2048;case"claude-3-5-sonnet-20241022":case"claude-3-5-sonnet-20240620":case"claude-3-opus-20240229":case"claude-3-sonnet-20240229":case"claude-3-haiku-20240307":case"claude-2.1":return 2e5;case"claude-2.0":case"claude-instant-1.2":return 1e5;case"gemini-1.5-pro":case"gemini-1.5-pro-latest":case"gemini-1.5-flash":case"gemini-1.5-flash-latest":return 1e6;case"gemini-pro":case"gemini-pro-vision":return 32768;default:return 4097}};function Gi(t){return typeof t!="object"||!t?!1:!!("type"in t&&t.type==="function"&&"function"in t&&typeof t.function=="object"&&t.function&&"name"in t.function&&"parameters"in t.function)}const _D=async({prompt:t,modelName:e})=>{let n;try{n=(await e_(ih(e))).encode(t).length}catch{console.warn("Failed to calculate number of tokens, falling back to approximate count"),n=Math.ceil(t.length/4)}return FE(e)-n},yD=()=>!1;var t_=class extends Fe{constructor(e){super(e);p(this,"verbose");p(this,"callbacks");p(this,"tags");p(this,"metadata");this.verbose=e.verbose??yD(),this.callbacks=e.callbacks,this.tags=e.tags??[],this.metadata=e.metadata??{},this._addVersion("@langchain/core","1.1.42")}get lc_attributes(){return{callbacks:void 0,verbose:void 0}}_addVersion(e,n){var s;const r=(s=this.metadata)==null?void 0:s.versions;this.metadata={...this.metadata,versions:{...typeof r=="object"&&r!==null?r:{},[e]:n}}}},n_=class extends t_{constructor({callbacks:e,callbackManager:n,...r}){const{cache:s,...a}=r;super({callbacks:e??n,...a});p(this,"caller");p(this,"cache");p(this,"_encoding");typeof s=="object"?this.cache=s:s?this.cache=TE.global():this.cache=void 0,this.caller=new Wc(r??{})}get callKeys(){return["stop","timeout","signal","tags","metadata","callbacks"]}async getNumTokens(e){let n;typeof e=="string"?n=e:n=e.map(s=>typeof s=="string"?s:s.type==="text"&&"text"in s?s.text:"").join("");let r=Math.ceil(n.length/4);if(!this._encoding)try{this._encoding=await e_("modelName"in this?ih(this.modelName):"gpt2")}catch(s){console.warn("Failed to calculate number of tokens, falling back to approximate count",s)}if(this._encoding)try{r=this._encoding.encode(n).length}catch(s){console.warn("Failed to calculate number of tokens, falling back to approximate count",s)}return r}static _convertInputToPromptValue(e){return typeof e=="string"?new Yg(e):Array.isArray(e)?new Qg(e.map(Vr)):e}_identifyingParams(){return{}}_getSerializedCacheKeyParametersForCall({config:e,...n}){const r={...this._identifyingParams(),...n,_type:this._llmType(),_model:this._modelType()};return Object.entries(r).filter(([s,a])=>a!==void 0).map(([s,a])=>`${s}:${JSON.stringify(a)}`).sort().join(",")}serialize(){return{...this._identifyingParams(),_type:this._llmType(),_model:this._modelType()}}static async deserialize(e){throw new Error("Use .toJSON() instead")}get profile(){return{}}_filterInvocationParamsForTracing(e){const{tools:n,functions:r,messages:s,response_format:a,...i}=e;return i}},wD=ue({applyPatch:()=>$i,compare:()=>Gd}),qi=class extends Fe{parseResultWithPrompt(t,e,n){return this.parseResult(t,n)}_baseMessageToString(t){return typeof t.content=="string"?t.content:this._baseMessageContentToString(t.content)}_baseMessageContentToString(t){return JSON.stringify(t)}async invoke(t,e){return typeof t=="string"?this._callWithConfig(async(n,r)=>this.parseResult([{text:n}],r==null?void 0:r.callbacks),t,{...e,runType:"parser"}):this._callWithConfig(async(n,r)=>this.parseResult([{message:n,text:this._baseMessageToString(n)}],r==null?void 0:r.callbacks),t,{...e,runType:"parser"})}},Ki=class extends qi{parseResult(t,e){return this.parse(t[0].text,e)}async parseWithPrompt(t,e,n){return this.parse(t,n)}_type(){throw new Error("_type not implemented")}},ln=class extends Error{constructor(e,n,r,s=!1){super(e);p(this,"llmOutput");p(this,"observation");p(this,"sendToLLM");if(this.llmOutput=n,this.observation=r,this.sendToLLM=s,s&&(r===void 0||n===void 0))throw new Error("Arguments 'observation' & 'llmOutput' are required if 'sendToLlm' is true");Lc(this,"OUTPUT_PARSING_FAILURE")}},Kc=class extends Ki{async*_transform(t){for await(const e of t)typeof e=="string"?yield this.parseResult([{text:e}]):yield this.parseResult([{message:e,text:this._baseMessageToString(e)}])}async*transform(t,e){yield*this._transformStreamWithConfig(t,this._transform.bind(this),{...e,runType:"parser"})}},Jc=class extends Kc{constructor(e){super(e);p(this,"diff",!1);this.diff=(e==null?void 0:e.diff)??this.diff}async*_transform(e){let n,r;for await(const s of e){if(typeof s!="string"&&typeof s.content!="string")throw new Error("Cannot handle non-string output.");let a;if(Ci(s)){if(typeof s.content!="string")throw new Error("Cannot handle non-string message output.");a=new qn({message:s,text:s.content})}else if(wt(s)){if(typeof s.content!="string")throw new Error("Cannot handle non-string message output.");a=new qn({message:Kl(s),text:s.content})}else a=new Ni({text:s});r===void 0?r=a:r=r.concat(a);const i=await this.parsePartialResult([r]);i!=null&&!Ca(i,n)&&(this.diff?yield this._diff(n,i):yield i,n=i)}}getFormatInstructions(){return""}},bD=class extends Kc{constructor(){super(...arguments);p(this,"lc_namespace",["langchain_core","output_parsers","bytes"]);p(this,"lc_serializable",!0);p(this,"textEncoder",new TextEncoder)}static lc_name(){return"BytesOutputParser"}parse(e){return Promise.resolve(this.textEncoder.encode(e))}getFormatInstructions(){return""}},Xc=class extends Kc{constructor(){super(...arguments);p(this,"re")}async*_transform(e){let n="";for await(const r of e)if(typeof r=="string"?n+=r:n+=r.content,this.re){const s=[...n.matchAll(this.re)];if(s.length>1){let a=0;for(const i of s.slice(0,-1))yield[i[1]],a+=(i.index??0)+i[0].length;n=n.slice(a)}}else{const s=await this.parse(n);if(s.length>1){for(const a of s.slice(0,-1))yield[a];n=s[s.length-1]}}for(const r of await this.parse(n))yield[r]}},vD=class extends Xc{constructor(){super(...arguments);p(this,"lc_namespace",["langchain_core","output_parsers","list"]);p(this,"lc_serializable",!0)}static lc_name(){return"CommaSeparatedListOutputParser"}async parse(e){try{return e.trim().split(",").map(n=>n.trim())}catch{throw new ln(`Could not parse output: ${e}`,e)}}getFormatInstructions(){return"Your response should be a list of comma separated values, eg: `foo, bar, baz`"}},SD=class extends Xc{constructor({length:e,separator:n}){super(...arguments);p(this,"lc_namespace",["langchain_core","output_parsers","list"]);p(this,"length");p(this,"separator");this.length=e,this.separator=n||","}async parse(e){try{const n=e.trim().split(this.separator).map(r=>r.trim());if(this.length!==void 0&&n.length!==this.length)throw new ln(`Incorrect number of items. Expected ${this.length}, got ${n.length}.`);return n}catch(n){throw Object.getPrototypeOf(n)===ln.prototype?n:new ln(`Could not parse output: ${e}`)}}getFormatInstructions(){return`Your response should be a list of ${this.length===void 0?"":`${this.length} `}items separated by "${this.separator}" (eg: \`foo${this.separator} bar${this.separator} baz\`)`}},TD=class extends Xc{constructor(){super(...arguments);p(this,"lc_namespace",["langchain_core","output_parsers","list"]);p(this,"lc_serializable",!0);p(this,"re",/\d+\.\s([^\n]+)/g)}static lc_name(){return"NumberedListOutputParser"}getFormatInstructions(){return`Your response should be a numbered list with each item on a new line. For example:
134
-
135
- 1. foo
136
-
137
- 2. bar
138
-
139
- 3. baz`}async parse(e){return[...e.matchAll(this.re)??[]].map(n=>n[1])}},ED=class extends Xc{constructor(){super(...arguments);p(this,"lc_namespace",["langchain_core","output_parsers","list"]);p(this,"lc_serializable",!0);p(this,"re",/^\s*[-*]\s([^\n]+)$/gm)}static lc_name(){return"NumberedListOutputParser"}getFormatInstructions(){return`Your response should be a numbered list with each item on a new line. For example:
140
-
141
- 1. foo
142
-
143
- 2. bar
144
-
145
- 3. baz`}async parse(e){return[...e.matchAll(this.re)??[]].map(n=>n[1])}},AD=class extends Kc{constructor(){super(...arguments);p(this,"lc_namespace",["langchain_core","output_parsers","string"]);p(this,"lc_serializable",!0)}static lc_name(){return"StrOutputParser"}parse(e){return Promise.resolve(e)}getFormatInstructions(){return""}_textContentToString(e){return e.text}_imageUrlContentToString(e){throw new Error('Cannot coerce a multimodal "image_url" message part into a string.')}_messageContentToString(e){switch(e.type){case"text":case"text_delta":if("text"in e)return this._textContentToString(e);break;case"image_url":if("image_url"in e)return this._imageUrlContentToString(e);break;case"reasoning":case"thinking":case"redacted_thinking":return"";default:throw new Error(`Cannot coerce "${e.type}" message part into a string.`)}throw new Error(`Invalid content type: ${e.type}`)}_baseMessageContentToString(e){return e.reduce((n,r)=>n+this._messageContentToString(r),"")}},r_=class extends Jc{constructor(){super(...arguments);p(this,"lc_namespace",["langchain_core","output_parsers"]);p(this,"lc_serializable",!0)}static lc_name(){return"JsonOutputParser"}_concatOutputChunks(e,n){return this.diff?super._concatOutputChunks(e,n):n}_diff(e,n){if(n)return e?Gd(e,n):[{op:"replace",path:"",value:n}]}async parsePartialResult(e){return Gl(e[0].text)}async parse(e){return Gl(e,JSON.parse)}getFormatInstructions(){return""}_baseMessageToString(e){return e.text}},BE=class extends Ki{constructor(e){super();p(this,"lc_namespace",["langchain","output_parsers","standard_schema"]);p(this,"schema");this.schema=e}static lc_name(){return"StandardSchemaOutputParser"}static fromSerializableSchema(e){return new this(e)}async parse(e){try{const n=Gl(e,JSON.parse),r=await this.schema["~standard"].validate(n);if(r.issues)throw new Error(`Validation failed: ${JSON.stringify(r.issues)}`);return r.value}catch(n){throw new ln(`Failed to parse. Text: "${e}". Error: ${n}`,e)}}getFormatInstructions(){return""}},s_=class extends Ki{constructor(e){super(e);p(this,"lc_namespace",["langchain","output_parsers","structured"]);this.schema=e}static lc_name(){return"StructuredOutputParser"}toJSON(){return this.toJSONNotImplemented()}static fromZodSchema(e){return new this(e)}static fromNamesAndDescriptions(e){const n=br(Object.fromEntries(Object.entries(e).map(([r,s])=>[r,zn().describe(s)])));return new this(n)}getFormatInstructions(){return`You must format your output as a JSON value that adheres to a given "JSON Schema" instance.
146
-
147
- "JSON Schema" is a declarative language that allows you to annotate and validate JSON documents.
148
-
149
- For example, the example "JSON Schema" instance {{"properties": {{"foo": {{"description": "a list of test words", "type": "array", "items": {{"type": "string"}}}}}}, "required": ["foo"]}}
150
- would match an object with one required property, "foo". The "type" property specifies "foo" must be an "array", and the "description" property semantically describes it as "a list of test words". The items within "foo" must be strings.
151
- Thus, the object {{"foo": ["bar", "baz"]}} is a well-formatted instance of this example "JSON Schema". The object {{"properties": {{"foo": ["bar", "baz"]}}}} is not well-formatted.
152
-
153
- Your output will be parsed and type-checked according to the provided schema instance, so make sure all fields in your output match the schema exactly and there are no trailing commas!
154
-
155
- Here is the JSON Schema instance your output must adhere to. Include the enclosing markdown codeblock:
156
- \`\`\`json
157
- ${JSON.stringify(lt(this.schema))}
158
- \`\`\`
159
- `}async parse(e){var n,r;try{const s=e.trim(),a=(((n=s.match(/^```(?:json)?\s*([\s\S]*?)```/))==null?void 0:n[1])||((r=s.match(/```json\s*([\s\S]*?)```/))==null?void 0:r[1])||s).replace(/"([^"\\]*(\\.[^"\\]*)*)"/g,(i,o)=>`"${o.replace(/\n/g,"\\n")}"`).replace(/\n/g,"");return await Yd(this.schema,JSON.parse(a))}catch(s){throw new ln(`Failed to parse. Text: "${e}". Error: ${s}`,e)}}},zE=class extends s_{static lc_name(){return"JsonMarkdownStructuredOutputParser"}getFormatInstructions(t){const e=(t==null?void 0:t.interpolationDepth)??1;if(e<1)throw new Error("f string interpolation depth must be at least 1");return`Return a markdown code snippet with a JSON object formatted to look like:
160
- \`\`\`json
161
- ${this._schemaToInstruction(lt(this.schema)).replaceAll("{","{".repeat(e)).replaceAll("}","}".repeat(e))}
162
- \`\`\``}_schemaToInstruction(t,e=2){const n=t;if("type"in n){let r=!1,s;if(Array.isArray(n.type)){const o=n.type.findIndex(c=>c==="null");o!==-1&&(r=!0,n.type.splice(o,1)),s=n.type.join(" | ")}else s=n.type;if(n.type==="object"&&n.properties){const o=n.description?` // ${n.description}`:"";return`{
163
- ${Object.entries(n.properties).map(([c,u])=>{var d;const l=(d=n.required)!=null&&d.includes(c)?"":" (optional)";return`${" ".repeat(e)}"${c}": ${this._schemaToInstruction(u,e+2)}${l}`}).join(`
164
- `)}
165
- ${" ".repeat(e-2)}}${o}`}if(n.type==="array"&&n.items){const o=n.description?` // ${n.description}`:"";return`array[
166
- ${" ".repeat(e)}${this._schemaToInstruction(n.items,e+2)}
167
- ${" ".repeat(e-2)}] ${o}`}const a=r?" (nullable)":"",i=n.description?` // ${n.description}`:"";return`${s}${i}${a}`}if("anyOf"in n)return n.anyOf.map(r=>this._schemaToInstruction(r,e)).join(`
168
- ${" ".repeat(e-2)}`);throw new Error("unsupported schema type")}static fromZodSchema(t){return new this(t)}static fromNamesAndDescriptions(t){const e=br(Object.fromEntries(Object.entries(t).map(([n,r])=>[n,zn().describe(r)])));return new this(e)}},ID=class extends Ki{constructor({inputSchema:e}){super(...arguments);p(this,"structuredInputParser");this.structuredInputParser=new zE(e)}async parse(e){let n;try{n=await this.structuredInputParser.parse(e)}catch(r){throw new ln(`Failed to parse. Text: "${e}". Error: ${r}`,e)}return this.outputProcessor(n)}getFormatInstructions(){return this.structuredInputParser.getFormatInstructions()}};const xD=function(){const t={};t.parser=function(E,v){return new n(E,v)},t.SAXParser=n,t.SAXStream=u,t.createStream=c,t.MAX_BUFFER_LENGTH=64*1024;const e=["comment","sgmlDecl","textNode","tagName","doctype","procInstName","procInstBody","entity","attribName","attribValue","cdata","script"];t.EVENTS=["text","processinginstruction","sgmldeclaration","doctype","comment","opentagstart","attribute","opentag","closetag","opencdata","cdata","closecdata","error","end","ready","script","opennamespace","closenamespace"];function n(E,v){if(!(this instanceof n))return new n(E,v);var N=this;s(N),N.q=N.c="",N.bufferCheckPosition=t.MAX_BUFFER_LENGTH,N.opt=v||{},N.opt.lowercase=N.opt.lowercase||N.opt.lowercasetags,N.looseCase=N.opt.lowercase?"toLowerCase":"toUpperCase",N.tags=[],N.closed=N.closedRoot=N.sawRoot=!1,N.tag=N.error=null,N.strict=!!E,N.noscript=!!(E||N.opt.noscript),N.state=A.BEGIN,N.strictEntities=N.opt.strictEntities,N.ENTITIES=N.strictEntities?Object.create(t.XML_ENTITIES):Object.create(t.ENTITIES),N.attribList=[],N.opt.xmlns&&(N.ns=Object.create(m)),N.trackPosition=N.opt.position!==!1,N.trackPosition&&(N.position=N.line=N.column=0),O(N,"onready")}Object.create||(Object.create=function(E){function v(){}return v.prototype=E,new v}),Object.keys||(Object.keys=function(E){var v=[];for(var N in E)E.hasOwnProperty(N)&&v.push(N);return v});function r(E){for(var v=Math.max(t.MAX_BUFFER_LENGTH,10),N=0,k=0,ge=e.length;k<ge;k++){var Se=E[e[k]].length;if(Se>v)switch(e[k]){case"textNode":H(E);break;case"cdata":$(E,"oncdata",E.cdata),E.cdata="";break;case"script":$(E,"onscript",E.script),E.script="";break;default:Y(E,"Max buffer length exceeded: "+e[k])}N=Math.max(N,Se)}E.bufferCheckPosition=t.MAX_BUFFER_LENGTH-N+E.position}function s(E){for(var v=0,N=e.length;v<N;v++)E[e[v]]=""}function a(E){H(E),E.cdata!==""&&($(E,"oncdata",E.cdata),E.cdata=""),E.script!==""&&($(E,"onscript",E.script),E.script="")}n.prototype={end:function(){me(this)},write:ie,resume:function(){return this.error=null,this},close:function(){return this.write(null)},flush:function(){a(this)}};var i=ReadableStream;i||(i=function(){});var o=t.EVENTS.filter(function(E){return E!=="error"&&E!=="end"});function c(E,v){return new u(E,v)}function u(E,v){if(!(this instanceof u))return new u(E,v);i.apply(this),this._parser=new n(E,v),this.writable=!0,this.readable=!0;var N=this;this._parser.onend=function(){N.emit("end")},this._parser.onerror=function(k){N.emit("error",k),N._parser.error=null},this._decoder=null,o.forEach(function(k){Object.defineProperty(N,"on"+k,{get:function(){return N._parser["on"+k]},set:function(ge){if(!ge)return N.removeAllListeners(k),N._parser["on"+k]=ge,ge;N.on(k,ge)},enumerable:!0,configurable:!1})})}u.prototype=Object.create(i.prototype,{constructor:{value:u}}),u.prototype.write=function(E){return this._parser.write(E.toString()),this.emit("data",E),!0},u.prototype.end=function(E){return E&&E.length&&this.write(E),this._parser.end(),!0},u.prototype.on=function(E,v){var N=this;return!N._parser["on"+E]&&o.indexOf(E)!==-1&&(N._parser["on"+E]=function(){var k=arguments.length===1?[arguments[0]]:Array.apply(null,arguments);k.splice(0,0,E),N.emit.apply(N,k)}),i.prototype.on.call(N,E,v)};var l="[CDATA[",d="DOCTYPE",f="http://www.w3.org/XML/1998/namespace",h="http://www.w3.org/2000/xmlns/",m={xml:f,xmlns:h},_=/[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/,y=/[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040.\d-]/,w=/[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/,g=/[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040.\d-]/;function b(E){return E===" "||E===`
169
- `||E==="\r"||E===" "}function S(E){return E==='"'||E==="'"}function I(E){return E===">"||b(E)}function T(E,v){return E.test(v)}function x(E,v){return!T(E,v)}var A=0;t.STATE={BEGIN:A++,BEGIN_WHITESPACE:A++,TEXT:A++,TEXT_ENTITY:A++,OPEN_WAKA:A++,SGML_DECL:A++,SGML_DECL_QUOTED:A++,DOCTYPE:A++,DOCTYPE_QUOTED:A++,DOCTYPE_DTD:A++,DOCTYPE_DTD_QUOTED:A++,COMMENT_STARTING:A++,COMMENT:A++,COMMENT_ENDING:A++,COMMENT_ENDED:A++,CDATA:A++,CDATA_ENDING:A++,CDATA_ENDING_2:A++,PROC_INST:A++,PROC_INST_BODY:A++,PROC_INST_ENDING:A++,OPEN_TAG:A++,OPEN_TAG_SLASH:A++,ATTRIB:A++,ATTRIB_NAME:A++,ATTRIB_NAME_SAW_WHITE:A++,ATTRIB_VALUE:A++,ATTRIB_VALUE_QUOTED:A++,ATTRIB_VALUE_CLOSED:A++,ATTRIB_VALUE_UNQUOTED:A++,ATTRIB_VALUE_ENTITY_Q:A++,ATTRIB_VALUE_ENTITY_U:A++,CLOSE_TAG:A++,CLOSE_TAG_SAW_WHITE:A++,SCRIPT:A++,SCRIPT_ENDING:A++},t.XML_ENTITIES={amp:"&",gt:">",lt:"<",quot:'"',apos:"'"},t.ENTITIES={amp:"&",gt:">",lt:"<",quot:'"',apos:"'",AElig:198,Aacute:193,Acirc:194,Agrave:192,Aring:197,Atilde:195,Auml:196,Ccedil:199,ETH:208,Eacute:201,Ecirc:202,Egrave:200,Euml:203,Iacute:205,Icirc:206,Igrave:204,Iuml:207,Ntilde:209,Oacute:211,Ocirc:212,Ograve:210,Oslash:216,Otilde:213,Ouml:214,THORN:222,Uacute:218,Ucirc:219,Ugrave:217,Uuml:220,Yacute:221,aacute:225,acirc:226,aelig:230,agrave:224,aring:229,atilde:227,auml:228,ccedil:231,eacute:233,ecirc:234,egrave:232,eth:240,euml:235,iacute:237,icirc:238,igrave:236,iuml:239,ntilde:241,oacute:243,ocirc:244,ograve:242,oslash:248,otilde:245,ouml:246,szlig:223,thorn:254,uacute:250,ucirc:251,ugrave:249,uuml:252,yacute:253,yuml:255,copy:169,reg:174,nbsp:160,iexcl:161,cent:162,pound:163,curren:164,yen:165,brvbar:166,sect:167,uml:168,ordf:170,laquo:171,not:172,shy:173,macr:175,deg:176,plusmn:177,sup1:185,sup2:178,sup3:179,acute:180,micro:181,para:182,middot:183,cedil:184,ordm:186,raquo:187,frac14:188,frac12:189,frac34:190,iquest:191,times:215,divide:247,OElig:338,oelig:339,Scaron:352,scaron:353,Yuml:376,fnof:402,circ:710,tilde:732,Alpha:913,Beta:914,Gamma:915,Delta:916,Epsilon:917,Zeta:918,Eta:919,Theta:920,Iota:921,Kappa:922,Lambda:923,Mu:924,Nu:925,Xi:926,Omicron:927,Pi:928,Rho:929,Sigma:931,Tau:932,Upsilon:933,Phi:934,Chi:935,Psi:936,Omega:937,alpha:945,beta:946,gamma:947,delta:948,epsilon:949,zeta:950,eta:951,theta:952,iota:953,kappa:954,lambda:955,mu:956,nu:957,xi:958,omicron:959,pi:960,rho:961,sigmaf:962,sigma:963,tau:964,upsilon:965,phi:966,chi:967,psi:968,omega:969,thetasym:977,upsih:978,piv:982,ensp:8194,emsp:8195,thinsp:8201,zwnj:8204,zwj:8205,lrm:8206,rlm:8207,ndash:8211,mdash:8212,lsquo:8216,rsquo:8217,sbquo:8218,ldquo:8220,rdquo:8221,bdquo:8222,dagger:8224,Dagger:8225,bull:8226,hellip:8230,permil:8240,prime:8242,Prime:8243,lsaquo:8249,rsaquo:8250,oline:8254,frasl:8260,euro:8364,image:8465,weierp:8472,real:8476,trade:8482,alefsym:8501,larr:8592,uarr:8593,rarr:8594,darr:8595,harr:8596,crarr:8629,lArr:8656,uArr:8657,rArr:8658,dArr:8659,hArr:8660,forall:8704,part:8706,exist:8707,empty:8709,nabla:8711,isin:8712,notin:8713,ni:8715,prod:8719,sum:8721,minus:8722,lowast:8727,radic:8730,prop:8733,infin:8734,ang:8736,and:8743,or:8744,cap:8745,cup:8746,int:8747,there4:8756,sim:8764,cong:8773,asymp:8776,ne:8800,equiv:8801,le:8804,ge:8805,sub:8834,sup:8835,nsub:8836,sube:8838,supe:8839,oplus:8853,otimes:8855,perp:8869,sdot:8901,lceil:8968,rceil:8969,lfloor:8970,rfloor:8971,lang:9001,rang:9002,loz:9674,spades:9824,clubs:9827,hearts:9829,diams:9830},Object.keys(t.ENTITIES).forEach(function(E){var v=t.ENTITIES[E],N=typeof v=="number"?String.fromCharCode(v):v;t.ENTITIES[E]=N});for(var M in t.STATE)t.STATE[t.STATE[M]]=M;A=t.STATE;function O(E,v,N){E[v]&&E[v](N)}function $(E,v,N){E.textNode&&H(E),O(E,v,N)}function H(E){E.textNode=J(E.opt,E.textNode),E.textNode&&O(E,"ontext",E.textNode),E.textNode=""}function J(E,v){return E.trim&&(v=v.trim()),E.normalize&&(v=v.replace(/\s+/g," ")),v}function Y(E,v){return H(E),E.trackPosition&&(v+=`
170
- Line: `+E.line+`
171
- Column: `+E.column+`
172
- Char: `+E.c),v=new Error(v),E.error=v,O(E,"onerror",v),E}function me(E){return E.sawRoot&&!E.closedRoot&&te(E,"Unclosed root tag"),E.state!==A.BEGIN&&E.state!==A.BEGIN_WHITESPACE&&E.state!==A.TEXT&&Y(E,"Unexpected end"),H(E),E.c="",E.closed=!0,O(E,"onend"),n.call(E,E.strict,E.opt),E}function te(E,v){if(typeof E!="object"||!(E instanceof n))throw new Error("bad call to strictFail");E.strict&&Y(E,v)}function Be(E){E.strict||(E.tagName=E.tagName[E.looseCase]());var v=E.tags[E.tags.length-1]||E,N=E.tag={name:E.tagName,attributes:{}};E.opt.xmlns&&(N.ns=v.ns),E.attribList.length=0,$(E,"onopentagstart",N)}function P(E,v){var N=E.indexOf(":")<0?["",E]:E.split(":"),k=N[0],ge=N[1];return v&&E==="xmlns"&&(k="xmlns",ge=""),{prefix:k,local:ge}}function z(E){if(E.strict||(E.attribName=E.attribName[E.looseCase]()),E.attribList.indexOf(E.attribName)!==-1||E.tag.attributes.hasOwnProperty(E.attribName)){E.attribName=E.attribValue="";return}if(E.opt.xmlns){var v=P(E.attribName,!0),N=v.prefix,k=v.local;if(N==="xmlns")if(k==="xml"&&E.attribValue!==f)te(E,"xml: prefix must be bound to "+f+`
173
- Actual: `+E.attribValue);else if(k==="xmlns"&&E.attribValue!==h)te(E,"xmlns: prefix must be bound to "+h+`
174
- Actual: `+E.attribValue);else{var ge=E.tag,Se=E.tags[E.tags.length-1]||E;ge.ns===Se.ns&&(ge.ns=Object.create(Se.ns)),ge.ns[k]=E.attribValue}E.attribList.push([E.attribName,E.attribValue])}else E.tag.attributes[E.attribName]=E.attribValue,$(E,"onattribute",{name:E.attribName,value:E.attribValue});E.attribName=E.attribValue=""}function Q(E,v){if(E.opt.xmlns){var N=E.tag,k=P(E.tagName);N.prefix=k.prefix,N.local=k.local,N.uri=N.ns[k.prefix]||"",N.prefix&&!N.uri&&(te(E,"Unbound namespace prefix: "+JSON.stringify(E.tagName)),N.uri=k.prefix);var ge=E.tags[E.tags.length-1]||E;N.ns&&ge.ns!==N.ns&&Object.keys(N.ns).forEach(function(rn){$(E,"onopennamespace",{prefix:rn,uri:N.ns[rn]})});for(var Se=0,Ye=E.attribList.length;Se<Ye;Se++){var Ze=E.attribList[Se],it=Ze[0],mt=Ze[1],Re=P(it,!0),At=Re.prefix,nn=Re.local,Xn=At===""?"":N.ns[At]||"",L={name:it,value:mt,prefix:At,local:nn,uri:Xn};At&&At!=="xmlns"&&!Xn&&(te(E,"Unbound namespace prefix: "+JSON.stringify(At)),L.uri=At),E.tag.attributes[it]=L,$(E,"onattribute",L)}E.attribList.length=0}E.tag.isSelfClosing=!!v,E.sawRoot=!0,E.tags.push(E.tag),$(E,"onopentag",E.tag),v||(!E.noscript&&E.tagName.toLowerCase()==="script"?E.state=A.SCRIPT:E.state=A.TEXT,E.tag=null,E.tagName=""),E.attribName=E.attribValue="",E.attribList.length=0}function se(E){if(!E.tagName){te(E,"Weird empty close tag."),E.textNode+="</>",E.state=A.TEXT;return}if(E.script){if(E.tagName!=="script"){E.script+="</"+E.tagName+">",E.tagName="",E.state=A.SCRIPT;return}$(E,"onscript",E.script),E.script=""}var v=E.tags.length,N=E.tagName;E.strict||(N=N[E.looseCase]());for(var k=N;v--&&E.tags[v].name!==k;)te(E,"Unexpected close tag");if(v<0){te(E,"Unmatched closing tag: "+E.tagName),E.textNode+="</"+E.tagName+">",E.state=A.TEXT;return}E.tagName=N;for(var ge=E.tags.length;ge-- >v;){var Se=E.tag=E.tags.pop();E.tagName=E.tag.name,$(E,"onclosetag",E.tagName);var Ye={};for(var Ze in Se.ns)Ye[Ze]=Se.ns[Ze];var it=E.tags[E.tags.length-1]||E;E.opt.xmlns&&Se.ns!==it.ns&&Object.keys(Se.ns).forEach(function(mt){var Re=Se.ns[mt];$(E,"onclosenamespace",{prefix:mt,uri:Re})})}v===0&&(E.closedRoot=!0),E.tagName=E.attribValue=E.attribName="",E.attribList.length=0,E.state=A.TEXT}function q(E){var v=E.entity,N=v.toLowerCase(),k,ge="";return E.ENTITIES[v]?E.ENTITIES[v]:E.ENTITIES[N]?E.ENTITIES[N]:(v=N,v.charAt(0)==="#"&&(v.charAt(1)==="x"?(v=v.slice(2),k=parseInt(v,16),ge=k.toString(16)):(v=v.slice(1),k=parseInt(v,10),ge=k.toString(10))),v=v.replace(/^0+/,""),isNaN(k)||ge.toLowerCase()!==v?(te(E,"Invalid character entity"),"&"+E.entity+";"):String.fromCodePoint(k))}function re(E,v){v==="<"?(E.state=A.OPEN_WAKA,E.startTagPosition=E.position):b(v)||(te(E,"Non-whitespace before first tag."),E.textNode=v,E.state=A.TEXT)}function ve(E,v){var N="";return v<E.length&&(N=E.charAt(v)),N}function ie(E){var v=this;if(this.error)throw this.error;if(v.closed)return Y(v,"Cannot write after close. Assign an onready handler.");if(E===null)return me(v);typeof E=="object"&&(E=E.toString());for(var N=0,k="";k=ve(E,N++),v.c=k,!!k;)switch(v.trackPosition&&(v.position++,k===`
175
- `?(v.line++,v.column=0):v.column++),v.state){case A.BEGIN:if(v.state=A.BEGIN_WHITESPACE,k==="\uFEFF")continue;re(v,k);continue;case A.BEGIN_WHITESPACE:re(v,k);continue;case A.TEXT:if(v.sawRoot&&!v.closedRoot){for(var ge=N-1;k&&k!=="<"&&k!=="&";)k=ve(E,N++),k&&v.trackPosition&&(v.position++,k===`
176
- `?(v.line++,v.column=0):v.column++);v.textNode+=E.substring(ge,N-1)}k==="<"&&!(v.sawRoot&&v.closedRoot&&!v.strict)?(v.state=A.OPEN_WAKA,v.startTagPosition=v.position):(!b(k)&&(!v.sawRoot||v.closedRoot)&&te(v,"Text data outside of root node."),k==="&"?v.state=A.TEXT_ENTITY:v.textNode+=k);continue;case A.SCRIPT:k==="<"?v.state=A.SCRIPT_ENDING:v.script+=k;continue;case A.SCRIPT_ENDING:k==="/"?v.state=A.CLOSE_TAG:(v.script+="<"+k,v.state=A.SCRIPT);continue;case A.OPEN_WAKA:if(k==="!")v.state=A.SGML_DECL,v.sgmlDecl="";else if(!b(k))if(T(_,k))v.state=A.OPEN_TAG,v.tagName=k;else if(k==="/")v.state=A.CLOSE_TAG,v.tagName="";else if(k==="?")v.state=A.PROC_INST,v.procInstName=v.procInstBody="";else{if(te(v,"Unencoded <"),v.startTagPosition+1<v.position){var Se=v.position-v.startTagPosition;k=new Array(Se).join(" ")+k}v.textNode+="<"+k,v.state=A.TEXT}continue;case A.SGML_DECL:(v.sgmlDecl+k).toUpperCase()===l?($(v,"onopencdata"),v.state=A.CDATA,v.sgmlDecl="",v.cdata=""):v.sgmlDecl+k==="--"?(v.state=A.COMMENT,v.comment="",v.sgmlDecl=""):(v.sgmlDecl+k).toUpperCase()===d?(v.state=A.DOCTYPE,(v.doctype||v.sawRoot)&&te(v,"Inappropriately located doctype declaration"),v.doctype="",v.sgmlDecl=""):k===">"?($(v,"onsgmldeclaration",v.sgmlDecl),v.sgmlDecl="",v.state=A.TEXT):(S(k)&&(v.state=A.SGML_DECL_QUOTED),v.sgmlDecl+=k);continue;case A.SGML_DECL_QUOTED:k===v.q&&(v.state=A.SGML_DECL,v.q=""),v.sgmlDecl+=k;continue;case A.DOCTYPE:k===">"?(v.state=A.TEXT,$(v,"ondoctype",v.doctype),v.doctype=!0):(v.doctype+=k,k==="["?v.state=A.DOCTYPE_DTD:S(k)&&(v.state=A.DOCTYPE_QUOTED,v.q=k));continue;case A.DOCTYPE_QUOTED:v.doctype+=k,k===v.q&&(v.q="",v.state=A.DOCTYPE);continue;case A.DOCTYPE_DTD:v.doctype+=k,k==="]"?v.state=A.DOCTYPE:S(k)&&(v.state=A.DOCTYPE_DTD_QUOTED,v.q=k);continue;case A.DOCTYPE_DTD_QUOTED:v.doctype+=k,k===v.q&&(v.state=A.DOCTYPE_DTD,v.q="");continue;case A.COMMENT:k==="-"?v.state=A.COMMENT_ENDING:v.comment+=k;continue;case A.COMMENT_ENDING:k==="-"?(v.state=A.COMMENT_ENDED,v.comment=J(v.opt,v.comment),v.comment&&$(v,"oncomment",v.comment),v.comment=""):(v.comment+="-"+k,v.state=A.COMMENT);continue;case A.COMMENT_ENDED:k!==">"?(te(v,"Malformed comment"),v.comment+="--"+k,v.state=A.COMMENT):v.state=A.TEXT;continue;case A.CDATA:k==="]"?v.state=A.CDATA_ENDING:v.cdata+=k;continue;case A.CDATA_ENDING:k==="]"?v.state=A.CDATA_ENDING_2:(v.cdata+="]"+k,v.state=A.CDATA);continue;case A.CDATA_ENDING_2:k===">"?(v.cdata&&$(v,"oncdata",v.cdata),$(v,"onclosecdata"),v.cdata="",v.state=A.TEXT):k==="]"?v.cdata+="]":(v.cdata+="]]"+k,v.state=A.CDATA);continue;case A.PROC_INST:k==="?"?v.state=A.PROC_INST_ENDING:b(k)?v.state=A.PROC_INST_BODY:v.procInstName+=k;continue;case A.PROC_INST_BODY:if(!v.procInstBody&&b(k))continue;k==="?"?v.state=A.PROC_INST_ENDING:v.procInstBody+=k;continue;case A.PROC_INST_ENDING:k===">"?($(v,"onprocessinginstruction",{name:v.procInstName,body:v.procInstBody}),v.procInstName=v.procInstBody="",v.state=A.TEXT):(v.procInstBody+="?"+k,v.state=A.PROC_INST_BODY);continue;case A.OPEN_TAG:T(y,k)?v.tagName+=k:(Be(v),k===">"?Q(v):k==="/"?v.state=A.OPEN_TAG_SLASH:(b(k)||te(v,"Invalid character in tag name"),v.state=A.ATTRIB));continue;case A.OPEN_TAG_SLASH:k===">"?(Q(v,!0),se(v)):(te(v,"Forward-slash in opening tag not followed by >"),v.state=A.ATTRIB);continue;case A.ATTRIB:if(b(k))continue;k===">"?Q(v):k==="/"?v.state=A.OPEN_TAG_SLASH:T(_,k)?(v.attribName=k,v.attribValue="",v.state=A.ATTRIB_NAME):te(v,"Invalid attribute name");continue;case A.ATTRIB_NAME:k==="="?v.state=A.ATTRIB_VALUE:k===">"?(te(v,"Attribute without value"),v.attribValue=v.attribName,z(v),Q(v)):b(k)?v.state=A.ATTRIB_NAME_SAW_WHITE:T(y,k)?v.attribName+=k:te(v,"Invalid attribute name");continue;case A.ATTRIB_NAME_SAW_WHITE:if(k==="=")v.state=A.ATTRIB_VALUE;else{if(b(k))continue;te(v,"Attribute without value"),v.tag.attributes[v.attribName]="",v.attribValue="",$(v,"onattribute",{name:v.attribName,value:""}),v.attribName="",k===">"?Q(v):T(_,k)?(v.attribName=k,v.state=A.ATTRIB_NAME):(te(v,"Invalid attribute name"),v.state=A.ATTRIB)}continue;case A.ATTRIB_VALUE:if(b(k))continue;S(k)?(v.q=k,v.state=A.ATTRIB_VALUE_QUOTED):(te(v,"Unquoted attribute value"),v.state=A.ATTRIB_VALUE_UNQUOTED,v.attribValue=k);continue;case A.ATTRIB_VALUE_QUOTED:if(k!==v.q){k==="&"?v.state=A.ATTRIB_VALUE_ENTITY_Q:v.attribValue+=k;continue}z(v),v.q="",v.state=A.ATTRIB_VALUE_CLOSED;continue;case A.ATTRIB_VALUE_CLOSED:b(k)?v.state=A.ATTRIB:k===">"?Q(v):k==="/"?v.state=A.OPEN_TAG_SLASH:T(_,k)?(te(v,"No whitespace between attributes"),v.attribName=k,v.attribValue="",v.state=A.ATTRIB_NAME):te(v,"Invalid attribute name");continue;case A.ATTRIB_VALUE_UNQUOTED:if(!I(k)){k==="&"?v.state=A.ATTRIB_VALUE_ENTITY_U:v.attribValue+=k;continue}z(v),k===">"?Q(v):v.state=A.ATTRIB;continue;case A.CLOSE_TAG:if(v.tagName)k===">"?se(v):T(y,k)?v.tagName+=k:v.script?(v.script+="</"+v.tagName,v.tagName="",v.state=A.SCRIPT):(b(k)||te(v,"Invalid tagname in closing tag"),v.state=A.CLOSE_TAG_SAW_WHITE);else{if(b(k))continue;x(_,k)?v.script?(v.script+="</"+k,v.state=A.SCRIPT):te(v,"Invalid tagname in closing tag."):v.tagName=k}continue;case A.CLOSE_TAG_SAW_WHITE:if(b(k))continue;k===">"?se(v):te(v,"Invalid characters in closing tag");continue;case A.TEXT_ENTITY:case A.ATTRIB_VALUE_ENTITY_Q:case A.ATTRIB_VALUE_ENTITY_U:var Ye,Ze;switch(v.state){case A.TEXT_ENTITY:Ye=A.TEXT,Ze="textNode";break;case A.ATTRIB_VALUE_ENTITY_Q:Ye=A.ATTRIB_VALUE_QUOTED,Ze="attribValue";break;case A.ATTRIB_VALUE_ENTITY_U:Ye=A.ATTRIB_VALUE_UNQUOTED,Ze="attribValue";break}if(k===";")if(v.opt.unparsedEntities){var it=q(v);v.entity="",v.state=Ye,v.write(it)}else v[Ze]+=q(v),v.entity="",v.state=Ye;else T(v.entity.length?g:w,k)?v.entity+=k:(te(v,"Invalid character in entity name"),v[Ze]+="&"+v.entity+k,v.entity="",v.state=Ye);continue;default:throw new Error(v,"Unknown state: "+v.state)}return v.position>=v.bufferCheckPosition&&r(v),v}/*! http://mths.be/fromcodepoint v0.1.0 by @mathias */return String.fromCodePoint||function(){var E=String.fromCharCode,v=Math.floor,N=function(){var k=16384,ge=[],Se,Ye,Ze=-1,it=arguments.length;if(!it)return"";for(var mt="";++Ze<it;){var Re=Number(arguments[Ze]);if(!isFinite(Re)||Re<0||Re>1114111||v(Re)!==Re)throw RangeError("Invalid code point: "+Re);Re<=65535?ge.push(Re):(Re-=65536,Se=(Re>>10)+55296,Ye=Re%1024+56320,ge.push(Se,Ye)),(Ze+1===it||ge.length>k)&&(mt+=E.apply(null,ge),ge.length=0)}return mt};Object.defineProperty?Object.defineProperty(String,"fromCodePoint",{value:N,configurable:!0,writable:!0}):String.fromCodePoint=N}(),t},kD=xD(),cm=`The output should be formatted as a XML file.
177
- 1. Output should conform to the tags below.
178
- 2. If tags are not given, make them on your own.
179
- 3. Remember to always open and close all the tags.
180
-
181
- As an example, for the tags ["foo", "bar", "baz"]:
182
- 1. String "<foo>
183
- <bar>
184
- <baz></baz>
185
- </bar>
186
- </foo>" is a well-formatted instance of the schema.
187
- 2. String "<foo>
188
- <bar>
189
- </foo>" is a badly-formatted instance.
190
- 3. String "<foo>
191
- <tag>
192
- </tag>
193
- </foo>" is a badly-formatted instance.
194
-
195
- Here are the output tags:
196
- \`\`\`
197
- {tags}
198
- \`\`\``;var OD=class extends Jc{constructor(e){super(e);p(this,"tags");p(this,"lc_namespace",["langchain_core","output_parsers"]);p(this,"lc_serializable",!0);this.tags=e==null?void 0:e.tags}static lc_name(){return"XMLOutputParser"}_diff(e,n){if(n)return e?Gd(e,n):[{op:"replace",path:"",value:n}]}async parsePartialResult(e){return um(e[0].text)}async parse(e){return um(e)}getFormatInstructions(){var e;return this.tags&&this.tags.length>0?cm.replace("{tags}",((e=this.tags)==null?void 0:e.join(", "))??""):cm}};const CD=t=>t.split(`
199
- `).map(e=>e.replace(/^\s+/,"")).join(`
200
- `).trim(),HE=t=>{if(Object.keys(t).length===0)return{};const e={};return t.children.length>0?(e[t.name]=t.children.map(HE),e):(e[t.name]=t.text??void 0,e)};function um(t){const e=CD(t),n=kD.parser(!0);let r={};const s=[];n.onopentag=o=>{const c={name:o.name,attributes:o.attributes,children:[],text:"",isSelfClosing:o.isSelfClosing};s.length>0?s[s.length-1].children.push(c):r=c,o.isSelfClosing||s.push(c)},n.onclosetag=()=>{if(s.length>0){const o=s.pop();s.length===0&&o&&(r=o)}},n.ontext=o=>{if(s.length>0){const c=s[s.length-1];c.text+=o}},n.onattribute=o=>{if(s.length>0){const c=s[s.length-1];c.attributes[o.name]=o.value}};const a=/```(xml)?(.*)```/s.exec(e),i=a?a[2]:e;return n.write(i).close(),r&&r.name==="?xml"&&(r=r.children[0]),HE(r)}var RD=ue({AsymmetricStructuredOutputParser:()=>ID,BaseCumulativeTransformOutputParser:()=>Jc,BaseLLMOutputParser:()=>qi,BaseOutputParser:()=>Ki,BaseTransformOutputParser:()=>Kc,BytesOutputParser:()=>bD,CommaSeparatedListOutputParser:()=>vD,CustomListOutputParser:()=>SD,JsonMarkdownStructuredOutputParser:()=>zE,JsonOutputParser:()=>r_,ListOutputParser:()=>Xc,MarkdownListOutputParser:()=>ED,NumberedListOutputParser:()=>TD,OutputParserException:()=>ln,StandardSchemaOutputParser:()=>BE,StringOutputParser:()=>AD,StructuredOutputParser:()=>s_,XMLOutputParser:()=>OD,XML_FORMAT_INSTRUCTIONS:()=>cm,parseJsonMarkdown:()=>Gl,parsePartialJson:()=>ki,parseXMLMarkdown:()=>um}),$D=ue({extendInteropZodObject:()=>zT,getInteropZodDefaultGetter:()=>bL,getInteropZodObjectShape:()=>gc,getSchemaDescription:()=>Pi,interopParse:()=>fl,interopParseAsync:()=>Yd,interopSafeParse:()=>yL,interopSafeParseAsync:()=>Xd,interopZodObjectMakeFieldsOptional:()=>TL,interopZodObjectPartial:()=>Ug,interopZodObjectPassthrough:()=>Fp,interopZodObjectStrict:()=>ad,interopZodTransformInputSchema:()=>HT,isInteropZodError:()=>VT,isInteropZodLiteral:()=>_L,isInteropZodObject:()=>rr,isInteropZodSchema:()=>Lt,isShapelessZodSchema:()=>wL,isSimpleStringZodSchema:()=>jg,isZodArrayV4:()=>eh,isZodLiteralV3:()=>UT,isZodLiteralV4:()=>DT,isZodNullableV4:()=>BT,isZodObjectV3:()=>Qd,isZodObjectV4:()=>Zr,isZodOptionalV4:()=>FT,isZodSchema:()=>gL,isZodSchemaV3:()=>xt,isZodSchemaV4:()=>pt});function oh(t,e){if(t.function===void 0)return;let n;if(e!=null&&e.partial)try{n=ki(t.function.arguments??"{}")}catch{return}else try{n=JSON.parse(t.function.arguments)}catch(s){throw new ln([`Function "${t.function.name}" arguments:`,"",t.function.arguments,"","are not valid JSON.",`Error: ${s.message}`].join(`
201
- `))}const r={name:t.function.name,args:n,type:"tool_call"};return e!=null&&e.returnId&&(r.id=t.id),r}function VE(t){if(t.id===void 0)throw new Error('All OpenAI tool calls must have an "id" field.');return{id:t.id,type:"function",function:{name:t.name,arguments:JSON.stringify(t.args)}}}function tc(t,e){var n,r;return{name:(n=t.function)==null?void 0:n.name,args:(r=t.function)==null?void 0:r.arguments,id:t.id,error:e,type:"invalid_tool_call"}}var ZE=class extends Jc{constructor(e){super(e);p(this,"returnId",!1);p(this,"lc_namespace",["langchain","output_parsers","openai_tools"]);p(this,"lc_serializable",!0);this.returnId=(e==null?void 0:e.returnId)??this.returnId}static lc_name(){return"JsonOutputToolsParser"}_diff(){throw new Error("Not supported.")}async parse(){throw new Error("Not implemented.")}async parseResult(e){return await this.parsePartialResult(e,!1)}async parsePartialResult(e,n=!0){var i;const r=e[0].message;let s;if(or(r)&&((i=r.tool_calls)!=null&&i.length)?s=r.tool_calls.map(o=>{const{id:c,...u}=o;return this.returnId?{id:c,...u}:u}):r.additional_kwargs.tool_calls!==void 0&&(s=JSON.parse(JSON.stringify(r.additional_kwargs.tool_calls)).map(o=>oh(o,{returnId:this.returnId,partial:n}))),!s)return[];const a=[];for(const o of s)if(o!==void 0){const c={type:o.name,args:o.args,id:o.id};a.push(c)}return a}},WE=class extends ZE{constructor(e){super(e);p(this,"lc_namespace",["langchain","output_parsers","openai_tools"]);p(this,"lc_serializable",!0);p(this,"returnId",!1);p(this,"keyName");p(this,"returnSingle",!1);p(this,"zodSchema");p(this,"serializableSchema");this.keyName=e.keyName,this.returnSingle=e.returnSingle??this.returnSingle,"zodSchema"in e&&(this.zodSchema=e.zodSchema),"serializableSchema"in e&&(this.serializableSchema=e.serializableSchema)}static lc_name(){return"JsonOutputKeyToolsParser"}async _validateResult(e){var r;if(this.serializableSchema!==void 0){const s=await this.serializableSchema["~standard"].validate(e);if(s.issues)throw new ln(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(s.issues)}`,JSON.stringify(e,null,2));return s.value}if(this.zodSchema===void 0)return e;const n=await Xd(this.zodSchema,e);if(n.success)return n.data;throw new ln(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify((r=n.error)==null?void 0:r.issues)}`,JSON.stringify(e,null,2))}async parsePartialResult(e){const n=(await super.parsePartialResult(e)).filter(s=>s.type===this.keyName);let r=n;if(n.length)return this.returnId||(r=n.map(s=>s.args)),this.returnSingle?r[0]:r}async parseResult(e){const n=(await super.parsePartialResult(e,!1)).filter(s=>s.type===this.keyName);let r=n;if(n.length)return this.returnId||(r=n.map(s=>s.args)),this.returnSingle?this._validateResult(r[0]):await Promise.all(r.map(s=>this._validateResult(s)))}},ND=ue({assembleStructuredOutputPipeline:()=>Ji,createContentParser:()=>Fi,createFunctionCallingParser:()=>Yc});function Fi(t){return Lt(t)?s_.fromZodSchema(t):cr(t)?BE.fromSerializableSchema(t):new r_}function Yc(t,e,n){const r=n??WE;return Lt(t)?new r({returnSingle:!0,keyName:e,zodSchema:t}):cr(t)?new r({returnSingle:!0,keyName:e,serializableSchema:t}):new r({returnSingle:!0,keyName:e})}function Ji(t,e,n,r){if(!n){const c=t.pipe(e);return r?c.withConfig({runName:r}):c}const s=vc.assign({parsed:(c,u)=>e.invoke(c.raw,u)}),a=vc.assign({parsed:()=>null}),i=s.withFallbacks({fallbacks:[a]}),o=Jn.from([{raw:t},i]);return r?o.withConfig({runName:r}):o}const PD=t=>t();function vf(t){const e=t.constructor;return new e({...t,content:t.contentBlocks,response_metadata:{...t.response_metadata,output_version:"v1"}})}var MD=ue({BaseChatModel:()=>Jr,SimpleChatModel:()=>LD});function Sf(t){const e=[];for(const n of t){let r=n;if(Array.isArray(n.content))for(let s=0;s<n.content.length;s++){const a=n.content[s];(ig(a)||og(a))&&r===n&&(r=new n.constructor({...r,content:[...n.content.slice(0,s),Y0(a),...n.content.slice(s+1)]}))}e.push(r)}return e}var Jr=class fa extends n_{constructor(n){super(n);p(this,"lc_namespace",["langchain","chat_models",this._llmType()]);p(this,"disableStreaming",!1);p(this,"outputVersion");this.outputVersion=PD(()=>{const r=n.outputVersion??It("LC_OUTPUT_VERSION");return r&&["v0","v1"].includes(r)?r:"v0"})}get callKeys(){return[...super.callKeys,"outputVersion"]}_separateRunnableConfigFromCallOptionsCompat(n){const[r,s]=super._separateRunnableConfigFromCallOptions(n);return s.signal=r.signal,[r,s]}async invoke(n,r){const s=fa._convertInputToPromptValue(n);return(await this.generatePrompt([s],r,r==null?void 0:r.callbacks)).generations[0][0].message}async*_streamResponseChunks(n,r,s){throw new Error("Not implemented.")}async*_streamIterator(n,r){var s,a,i;if(this._streamResponseChunks===fa.prototype._streamResponseChunks||this.disableStreaming)yield this.invoke(n,r);else{const o=fa._convertInputToPromptValue(n).toChatMessages(),[c,u]=this._separateRunnableConfigFromCallOptionsCompat(r),l={...c.metadata,...this.getLsParamsWithDefaults(u)},d=this.invocationParams(u),f=await un.configure(c.callbacks,this.callbacks,c.tags,this.tags,l,this.metadata,{verbose:this.verbose,tracerInheritableMetadata:this._filterInvocationParamsForTracing(d)}),h={options:u,invocation_params:d,batch_size:1},m=u.outputVersion??this.outputVersion,_=await(f==null?void 0:f.handleChatModelStart(this.toJSON(),[Sf(o)],c.runId,void 0,h,void 0,void 0,c.runName));let y,w;try{for await(const g of this._streamResponseChunks(o,u,_==null?void 0:_[0])){if((s=u.signal)==null||s.throwIfAborted(),g.message.id==null){const b=(a=_==null?void 0:_.at(0))==null?void 0:a.runId;b!=null&&g.message._updateId(`run-${b}`)}g.message.response_metadata={...g.generationInfo,...g.message.response_metadata},m==="v1"?yield vf(g.message):yield g.message,y?y=y.concat(g):y=g,ql(g.message)&&g.message.usage_metadata!==void 0&&(w={tokenUsage:{promptTokens:g.message.usage_metadata.input_tokens,completionTokens:g.message.usage_metadata.output_tokens,totalTokens:g.message.usage_metadata.total_tokens}})}(i=u.signal)==null||i.throwIfAborted()}catch(g){throw await Promise.all((_??[]).map(b=>b==null?void 0:b.handleLLMError(g))),g}await Promise.all((_??[]).map(g=>g==null?void 0:g.handleLLMEnd({generations:[[y]],llmOutput:w})))}}getLsParams(n){const r=this.getName().startsWith("Chat")?this.getName().replace("Chat",""):this.getName();return{ls_model_type:"chat",ls_stop:n.stop,ls_provider:r}}getLsParamsWithDefaults(n){return{...this.getLsParams(n),ls_integration:"langchain_chat_model"}}async _generateUncached(n,r,s,a){var f,h,m,_;const i=n.map(y=>y.map(Vr));let o;if(a!==void 0&&a.length===i.length)o=a;else{const y={...s.metadata,...this.getLsParamsWithDefaults(r)},w=this.invocationParams(r),g=await un.configure(s.callbacks,this.callbacks,s.tags,this.tags,y,this.metadata,{verbose:this.verbose,tracerInheritableMetadata:this._filterInvocationParamsForTracing(w)}),b={options:r,invocation_params:w,batch_size:1};o=await(g==null?void 0:g.handleChatModelStart(this.toJSON(),i.map(Sf),s.runId,void 0,b,void 0,void 0,s.runName))}const c=r.outputVersion??this.outputVersion,u=[],l=[];if(o!=null&&o[0].handlers.find(_g)&&!this.disableStreaming&&i.length===1&&this._streamResponseChunks!==fa.prototype._streamResponseChunks)try{const y=await this._streamResponseChunks(i[0],r,o==null?void 0:o[0]);let w,g;for await(const b of y){if((f=r.signal)!=null&&f.aborted){const S=w==null?void 0:w.message;throw new gp("Model invocation was aborted.",S)}if(b.message.id==null){const S=(h=o==null?void 0:o.at(0))==null?void 0:h.runId;S!=null&&b.message._updateId(`run-${S}`)}w===void 0?w=b:w=ys(w,b),ql(b.message)&&b.message.usage_metadata!==void 0&&(g={tokenUsage:{promptTokens:b.message.usage_metadata.input_tokens,completionTokens:b.message.usage_metadata.output_tokens,totalTokens:b.message.usage_metadata.total_tokens}})}if((m=r.signal)!=null&&m.aborted){const b=w==null?void 0:w.message;throw new gp("Model invocation was aborted.",b)}if(w===void 0)throw new Error("Received empty response from chat model call.");u.push([w]),await(o==null?void 0:o[0].handleLLMEnd({generations:u,llmOutput:g}))}catch(y){throw await(o==null?void 0:o[0].handleLLMError(y)),y}else{const y=await Promise.allSettled(i.map(async(w,g)=>{const b=await this._generate(w,{...r,promptIndex:g},o==null?void 0:o[g]);if(c==="v1")for(const S of b.generations)S.message=vf(S.message);return b}));await Promise.all(y.map(async(w,g)=>{var b,S,I;if(w.status==="fulfilled"){const T=w.value;for(const x of T.generations){if(x.message.id==null){const A=(b=o==null?void 0:o.at(0))==null?void 0:b.runId;A!=null&&x.message._updateId(`run-${A}`)}x.message.response_metadata={...x.generationInfo,...x.message.response_metadata}}return T.generations.length===1&&(T.generations[0].message.response_metadata={...T.llmOutput,...T.generations[0].message.response_metadata}),u[g]=T.generations,l[g]=T.llmOutput,(S=o==null?void 0:o[g])==null?void 0:S.handleLLMEnd({generations:[T.generations],llmOutput:T.llmOutput})}else return await((I=o==null?void 0:o[g])==null?void 0:I.handleLLMError(w.reason)),Promise.reject(w.reason)}))}const d={generations:u,llmOutput:l.length?(_=this._combineLLMOutput)==null?void 0:_.call(this,...l):void 0};return Object.defineProperty(d,fc,{value:o?{runIds:o==null?void 0:o.map(y=>y.runId)}:void 0,configurable:!0}),d}async _generateCached({messages:n,cache:r,llmStringKey:s,parsedOptions:a,handledOptions:i}){const o=n.map(g=>g.map(Vr)),c={...i.metadata,...this.getLsParamsWithDefaults(a)},u=this.invocationParams(a),l=await un.configure(i.callbacks,this.callbacks,i.tags,this.tags,c,this.metadata,{verbose:this.verbose,tracerInheritableMetadata:this._filterInvocationParamsForTracing(u)}),d={options:a,invocation_params:u,batch_size:1},f=await(l==null?void 0:l.handleChatModelStart(this.toJSON(),o.map(Sf),i.runId,void 0,d,void 0,void 0,i.runName)),h=[],m=(await Promise.allSettled(o.map(async(g,b)=>{const S=fa._convertInputToPromptValue(g).toString(),I=await r.lookup(S,s);return I==null&&h.push(b),I}))).map((g,b)=>({result:g,runManager:f==null?void 0:f[b]})).filter(({result:g})=>g.status==="fulfilled"&&g.value!=null||g.status==="rejected"),_=a.outputVersion??this.outputVersion,y=[];await Promise.all(m.map(async({result:g,runManager:b},S)=>{if(g.status==="fulfilled"){const I=g.value;return y[S]=I.map(T=>("message"in T&&wt(T.message)&&or(T.message)&&(T.message.usage_metadata={input_tokens:0,output_tokens:0,total_tokens:0},_==="v1"&&(T.message=vf(T.message))),T.generationInfo={...T.generationInfo,tokenUsage:{}},T)),I.length&&await(b==null?void 0:b.handleLLMNewToken(I[0].text)),b==null?void 0:b.handleLLMEnd({generations:[I]},void 0,void 0,void 0,{cached:!0})}else return await(b==null?void 0:b.handleLLMError(g.reason,void 0,void 0,void 0,{cached:!0})),Promise.reject(g.reason)}));const w={generations:y,missingPromptIndices:h,startedRunManagers:f};return Object.defineProperty(w,fc,{value:f?{runIds:f==null?void 0:f.map(g=>g.runId)}:void 0,configurable:!0}),w}async generate(n,r,s){let a;Array.isArray(r)?a={stop:r}:a=r;const i=n.map(_=>_.map(Vr)),[o,c]=this._separateRunnableConfigFromCallOptionsCompat(a);if(o.callbacks=o.callbacks??s,!this.cache)return this._generateUncached(i,c,o);const{cache:u}=this,l=this._getSerializedCacheKeyParametersForCall(c),{generations:d,missingPromptIndices:f,startedRunManagers:h}=await this._generateCached({messages:i,cache:u,llmStringKey:l,parsedOptions:c,handledOptions:o});let m={};if(f.length>0){const _=await this._generateUncached(f.map(y=>i[y]),c,o,h!==void 0?f.map(y=>h==null?void 0:h[y]):void 0);await Promise.all(_.generations.map(async(y,w)=>{const g=f[w];d[g]=y;const b=fa._convertInputToPromptValue(i[g]).toString();return u.update(b,l,y)})),m=_.llmOutput??{}}return{generations:d,llmOutput:m}}invocationParams(n){return{}}_modelType(){return"base_chat_model"}async generatePrompt(n,r,s){const a=n.map(i=>i.toChatMessages());return this.generate(a,r,s)}withStructuredOutput(n,r){if(typeof this.bindTools!="function")throw new Error('Chat model must implement ".bindTools()" to use withStructuredOutput.');if(r!=null&&r.strict)throw new Error('"strict" mode is not supported for this model by default.');const s=n,a=r==null?void 0:r.name,i=Pi(s)??"A function available to call.",o=r==null?void 0:r.method,c=r==null?void 0:r.includeRaw;if(o==="jsonMode")throw new Error('Base withStructuredOutput implementation only supports "functionCalling" as a method.');let u=a??"extract";!Lt(s)&&!cr(s)&&"name"in s&&(u=s.name);const l=Lt(s)||cr(s)?lt(s):s,d=[{type:"function",function:{name:u,description:i,parameters:l}}];return Ji(this.bindTools(d),Ht.from(f=>{if(!Qe.isInstance(f))throw new Error("Input is not an AIMessageChunk.");if(!f.tool_calls||f.tool_calls.length===0)throw new Error("No tool calls found in the response.");const h=f.tool_calls.find(m=>m.name===u);if(!h)throw new Error(`No tool call found with name ${u}.`);return h.args}),c,c?"StructuredOutputRunnable":"StructuredOutput")}},LD=class extends Jr{async _generate(t,e,n){const r=new De(await this._call(t,e,n));if(typeof r.content!="string")throw new Error("Cannot generate with a simple chat model when output is not a string.");return{generations:[{text:r.content,message:r}]}}},jD=ue({BaseLLM:()=>GE,LLM:()=>a_}),GE=class $o extends n_{constructor(){super(...arguments);p(this,"lc_namespace",["langchain","llms",this._llmType()])}async invoke(n,r){const s=$o._convertInputToPromptValue(n);return(await this.generatePrompt([s],r,r==null?void 0:r.callbacks)).generations[0][0].text}async*_streamResponseChunks(n,r,s){throw new Error("Not implemented.")}_separateRunnableConfigFromCallOptionsCompat(n){const[r,s]=super._separateRunnableConfigFromCallOptions(n);return s.signal=r.signal,[r,s]}async*_streamIterator(n,r){if(this._streamResponseChunks===$o.prototype._streamResponseChunks)yield this.invoke(n,r);else{const s=$o._convertInputToPromptValue(n),[a,i]=this._separateRunnableConfigFromCallOptionsCompat(r),o=this.invocationParams(i),c=await un.configure(a.callbacks,this.callbacks,a.tags,this.tags,a.metadata,this.metadata,{verbose:this.verbose,tracerInheritableMetadata:this._filterInvocationParamsForTracing(o)}),u={options:i,invocation_params:o,batch_size:1},l=await(c==null?void 0:c.handleLLMStart(this.toJSON(),[s.toString()],a.runId,void 0,u,void 0,void 0,a.runName));let d=new Ni({text:""});try{for await(const f of this._streamResponseChunks(s.toString(),i,l==null?void 0:l[0]))d?d=d.concat(f):d=f,typeof f.text=="string"&&(yield f.text)}catch(f){throw await Promise.all((l??[]).map(h=>h==null?void 0:h.handleLLMError(f))),f}await Promise.all((l??[]).map(f=>f==null?void 0:f.handleLLMEnd({generations:[[d]]})))}}async generatePrompt(n,r,s){const a=n.map(i=>i.toString());return this.generate(a,r,s)}invocationParams(n){return{}}_flattenLLMResult(n){const r=[];for(let s=0;s<n.generations.length;s+=1){const a=n.generations[s];if(s===0)r.push({generations:[a],llmOutput:n.llmOutput});else{const i=n.llmOutput?{...n.llmOutput,tokenUsage:{}}:void 0;r.push({generations:[a],llmOutput:i})}}return r}async _generateUncached(n,r,s,a){let i;if(a!==void 0&&a.length===n.length)i=a;else{const l=this.invocationParams(r),d=await un.configure(s.callbacks,this.callbacks,s.tags,this.tags,s.metadata,this.metadata,{verbose:this.verbose,tracerInheritableMetadata:this._filterInvocationParamsForTracing(l)}),f={options:r,invocation_params:l,batch_size:n.length};i=await(d==null?void 0:d.handleLLMStart(this.toJSON(),n,s.runId,void 0,f,void 0,void 0,s==null?void 0:s.runName))}const o=!!(i!=null&&i[0].handlers.find(_g));let c;if(o&&n.length===1&&this._streamResponseChunks!==$o.prototype._streamResponseChunks)try{const l=await this._streamResponseChunks(n[0],r,i==null?void 0:i[0]);let d;for await(const f of l)d===void 0?d=f:d=ys(d,f);if(d===void 0)throw new Error("Received empty response from chat model call.");c={generations:[[d]],llmOutput:{}},await(i==null?void 0:i[0].handleLLMEnd(c))}catch(l){throw await(i==null?void 0:i[0].handleLLMError(l)),l}else{try{c=await this._generate(n,r,i==null?void 0:i[0])}catch(d){throw await Promise.all((i??[]).map(f=>f==null?void 0:f.handleLLMError(d))),d}const l=this._flattenLLMResult(c);await Promise.all((i??[]).map((d,f)=>d==null?void 0:d.handleLLMEnd(l[f])))}const u=(i==null?void 0:i.map(l=>l.runId))||void 0;return Object.defineProperty(c,fc,{value:u?{runIds:u}:void 0,configurable:!0}),c}async _generateCached({prompts:n,cache:r,llmStringKey:s,parsedOptions:a,handledOptions:i,runId:o}){const c=this.invocationParams(a),u=await un.configure(i.callbacks,this.callbacks,i.tags,this.tags,i.metadata,this.metadata,{verbose:this.verbose,tracerInheritableMetadata:this._filterInvocationParamsForTracing(c)}),l={options:a,invocation_params:c,batch_size:n.length},d=await(u==null?void 0:u.handleLLMStart(this.toJSON(),n,o,void 0,l,void 0,void 0,i==null?void 0:i.runName)),f=[],h=(await Promise.allSettled(n.map(async(y,w)=>{const g=await r.lookup(y,s);return g==null&&f.push(w),g}))).map((y,w)=>({result:y,runManager:d==null?void 0:d[w]})).filter(({result:y})=>y.status==="fulfilled"&&y.value!=null||y.status==="rejected"),m=[];await Promise.all(h.map(async({result:y,runManager:w},g)=>{if(y.status==="fulfilled"){const b=y.value;return m[g]=b.map(S=>(S.generationInfo={...S.generationInfo,tokenUsage:{}},S)),b.length&&await(w==null?void 0:w.handleLLMNewToken(b[0].text)),w==null?void 0:w.handleLLMEnd({generations:[b]},void 0,void 0,void 0,{cached:!0})}else return await(w==null?void 0:w.handleLLMError(y.reason,void 0,void 0,void 0,{cached:!0})),Promise.reject(y.reason)}));const _={generations:m,missingPromptIndices:f,startedRunManagers:d};return Object.defineProperty(_,fc,{value:d?{runIds:d==null?void 0:d.map(y=>y.runId)}:void 0,configurable:!0}),_}async generate(n,r,s){if(!Array.isArray(n))throw new Error("Argument 'prompts' is expected to be a string[]");let a;Array.isArray(r)?a={stop:r}:a=r;const[i,o]=this._separateRunnableConfigFromCallOptionsCompat(a);if(i.callbacks=i.callbacks??s,!this.cache)return this._generateUncached(n,o,i);const{cache:c}=this,u=this._getSerializedCacheKeyParametersForCall(o),{generations:l,missingPromptIndices:d,startedRunManagers:f}=await this._generateCached({prompts:n,cache:c,llmStringKey:u,parsedOptions:o,handledOptions:i,runId:i.runId});let h={};if(d.length>0){const m=await this._generateUncached(d.map(_=>n[_]),o,i,f!==void 0?d.map(_=>f==null?void 0:f[_]):void 0);await Promise.all(m.generations.map(async(_,y)=>{const w=d[y];return l[w]=_,c.update(n[w],u,_)})),h=m.llmOutput??{}}return{generations:l,llmOutput:h}}_identifyingParams(){return{}}_modelType(){return"base_llm"}},a_=class extends GE{async _generate(t,e,n){return{generations:await Promise.all(t.map((r,s)=>this._call(r,{...e,promptIndex:s},n).then(a=>[{text:a}])))}}},UD=ue({}),DD=ue({BaseMemory:()=>FD,getInputValue:()=>BD,getOutputValue:()=>zD,getPromptInputKey:()=>HD}),FD=class{};const qE=(t,e)=>{if(e!==void 0)return t[e];const n=Object.keys(t);if(n.length===1)return t[n[0]]},BD=(t,e)=>{const n=qE(t,e);if(!n)throw new Error(`input values have ${Object.keys(t).length} keys, you must specify an input key or pass only 1 key as input`);return n},zD=(t,e)=>{const n=qE(t,e);if(!n&&n!=="")throw new Error(`output values have ${Object.keys(t).length} keys, you must specify an output key or pass only 1 key as output`);return n};function HD(t,e){const n=Object.keys(t).filter(r=>!e.includes(r)&&r!=="stop");if(n.length!==1)throw new Error(`One input key expected, but got ${n.length}`);return n[0]}var KE=class extends qi{constructor(e){super();p(this,"lc_namespace",["langchain","output_parsers","openai_functions"]);p(this,"lc_serializable",!0);p(this,"argsOnly",!0);this.argsOnly=(e==null?void 0:e.argsOnly)??this.argsOnly}static lc_name(){return"OutputFunctionsParser"}async parseResult(e){if("message"in e[0]){const n=e[0].message.additional_kwargs.function_call;if(!n)throw new Error(`No function_call in message ${JSON.stringify(e)}`);if(!n.arguments)throw new Error(`No arguments in function_call ${JSON.stringify(e)}`);return this.argsOnly?n.arguments:JSON.stringify(n)}else throw new Error(`No message in generations ${JSON.stringify(e)}`)}},JE=class extends Jc{constructor(e){super(e);p(this,"lc_namespace",["langchain","output_parsers","openai_functions"]);p(this,"lc_serializable",!0);p(this,"outputParser");p(this,"argsOnly",!0);this.argsOnly=(e==null?void 0:e.argsOnly)??this.argsOnly,this.outputParser=new KE(e)}static lc_name(){return"JsonOutputFunctionsParser"}_diff(e,n){if(n)return Gd(e??{},n)}async parsePartialResult(e){const n=e[0];if(!n.message)return;const{message:r}=n,s=r.additional_kwargs.function_call;if(s)return this.argsOnly?ki(s.arguments):{...s,arguments:ki(s.arguments)}}async parseResult(e){const n=await this.outputParser.parseResult(e);if(!n)throw new Error(`No result from "OutputFunctionsParser" ${JSON.stringify(e)}`);return this.parse(n)}async parse(e){const n=JSON.parse(e);return this.argsOnly||(n.arguments=JSON.parse(n.arguments)),n}getFormatInstructions(){return""}},VD=class extends qi{constructor(e){super(e);p(this,"lc_namespace",["langchain","output_parsers","openai_functions"]);p(this,"lc_serializable",!0);p(this,"outputParser",new JE);p(this,"attrName");this.attrName=e.attrName}static lc_name(){return"JsonKeyOutputFunctionsParser"}get lc_aliases(){return{attrName:"key_name"}}async parseResult(e){return(await this.outputParser.parseResult(e))[this.attrName]}},ZD=ue({JsonKeyOutputFunctionsParser:()=>VD,JsonOutputFunctionsParser:()=>JE,OutputFunctionsParser:()=>KE}),WD=ue({JsonOutputKeyToolsParser:()=>WE,JsonOutputToolsParser:()=>ZE,convertLangChainToolCallToOpenAI:()=>VE,makeInvalidToolCall:()=>tc,parseToolCall:()=>oh}),Qc=class extends Fe{constructor(e){super(e);p(this,"lc_serializable",!0);p(this,"lc_namespace",["langchain_core","prompts",this._getPromptType()]);p(this,"inputVariables");p(this,"outputParser");p(this,"partialVariables");p(this,"metadata");p(this,"tags");const{inputVariables:n}=e;if(n.includes("stop"))throw new Error("Cannot have an input variable named 'stop', as it is used internally, please rename.");Object.assign(this,e)}get lc_attributes(){return{partialVariables:void 0}}async mergePartialAndUserVariables(e){const n=this.partialVariables??{},r={};for(const[s,a]of Object.entries(n))typeof a=="string"?r[s]=a:r[s]=await a();return{...r,...e}}async invoke(e,n){const r={...this.metadata,...n==null?void 0:n.metadata},s=[...this.tags??[],...(n==null?void 0:n.tags)??[]];return this._callWithConfig(a=>this.formatPromptValue(a),e,{...n,tags:s,metadata:r,runType:"prompt"})}},Tc=class extends Qc{async formatPromptValue(t){return new Yg(await this.format(t))}};/*!
202
- * mustache.js - Logic-less {{mustache}} templates with JavaScript
203
- * http://github.com/janl/mustache.js
204
- */var GD=Object.prototype.toString,Xi=Array.isArray||function(e){return GD.call(e)==="[object Array]"};function i_(t){return typeof t=="function"}function qD(t){return Xi(t)?"array":typeof t}function Tf(t){return t.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function vb(t,e){return t!=null&&typeof t=="object"&&e in t}function KD(t,e){return t!=null&&typeof t!="object"&&t.hasOwnProperty&&t.hasOwnProperty(e)}var JD=RegExp.prototype.test;function XD(t,e){return JD.call(t,e)}var YD=/\S/;function QD(t){return!XD(YD,t)}var eF={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","/":"&#x2F;","`":"&#x60;","=":"&#x3D;"};function tF(t){return String(t).replace(/[&<>"'`=\/]/g,function(n){return eF[n]})}var nF=/\s*/,rF=/\s+/,Sb=/\s*=/,sF=/\s*\}/,aF=/#|\^|\/|>|\{|&|=|!/;function iF(t,e){if(!t)return[];var n=!1,r=[],s=[],a=[],i=!1,o=!1,c="",u=0;function l(){if(i&&!o)for(;a.length;)delete s[a.pop()];else a=[];i=!1,o=!1}var d,f,h;function m(A){if(typeof A=="string"&&(A=A.split(rF,2)),!Xi(A)||A.length!==2)throw new Error("Invalid tags: "+A);d=new RegExp(Tf(A[0])+"\\s*"),f=new RegExp("\\s*"+Tf(A[1])),h=new RegExp("\\s*"+Tf("}"+A[1]))}m(e||Pn.tags);for(var _=new eu(t),y,w,g,b,S,I;!_.eos();){if(y=_.pos,g=_.scanUntil(d),g)for(var T=0,x=g.length;T<x;++T)b=g.charAt(T),QD(b)?(a.push(s.length),c+=b):(o=!0,n=!0,c+=" "),s.push(["text",b,y,y+1]),y+=1,b===`
205
- `&&(l(),c="",u=0,n=!1);if(!_.scan(d))break;if(i=!0,w=_.scan(aF)||"name",_.scan(nF),w==="="?(g=_.scanUntil(Sb),_.scan(Sb),_.scanUntil(f)):w==="{"?(g=_.scanUntil(h),_.scan(sF),_.scanUntil(f),w="&"):g=_.scanUntil(f),!_.scan(f))throw new Error("Unclosed tag at "+_.pos);if(w==">"?S=[w,g,y,_.pos,c,u,n]:S=[w,g,y,_.pos],u++,s.push(S),w==="#"||w==="^")r.push(S);else if(w==="/"){if(I=r.pop(),!I)throw new Error('Unopened section "'+g+'" at '+y);if(I[1]!==g)throw new Error('Unclosed section "'+I[1]+'" at '+y)}else w==="name"||w==="{"||w==="&"?o=!0:w==="="&&m(g)}if(l(),I=r.pop(),I)throw new Error('Unclosed section "'+I[1]+'" at '+_.pos);return cF(oF(s))}function oF(t){for(var e=[],n,r,s=0,a=t.length;s<a;++s)n=t[s],n&&(n[0]==="text"&&r&&r[0]==="text"?(r[1]+=n[1],r[3]=n[3]):(e.push(n),r=n));return e}function cF(t){for(var e=[],n=e,r=[],s,a,i=0,o=t.length;i<o;++i)switch(s=t[i],s[0]){case"#":case"^":n.push(s),r.push(s),n=s[4]=[];break;case"/":a=r.pop(),a[5]=s[2],n=r.length>0?r[r.length-1][4]:e;break;default:n.push(s)}return e}function eu(t){this.string=t,this.tail=t,this.pos=0}eu.prototype.eos=function(){return this.tail===""};eu.prototype.scan=function(e){var n=this.tail.match(e);if(!n||n.index!==0)return"";var r=n[0];return this.tail=this.tail.substring(r.length),this.pos+=r.length,r};eu.prototype.scanUntil=function(e){var n=this.tail.search(e),r;switch(n){case-1:r=this.tail,this.tail="";break;case 0:r="";break;default:r=this.tail.substring(0,n),this.tail=this.tail.substring(n)}return this.pos+=r.length,r};function Bi(t,e){this.view=t,this.cache={".":this.view},this.parent=e}Bi.prototype.push=function(e){return new Bi(e,this)};Bi.prototype.lookup=function(e){var n=this.cache,r;if(n.hasOwnProperty(e))r=n[e];else{for(var s=this,a,i,o,c=!1;s;){if(e.indexOf(".")>0)for(a=s.view,i=e.split("."),o=0;a!=null&&o<i.length;)o===i.length-1&&(c=vb(a,i[o])||KD(a,i[o])),a=a[i[o++]];else a=s.view[e],c=vb(s.view,e);if(c){r=a;break}s=s.parent}n[e]=r}return i_(r)&&(r=r.call(this.view)),r};function Tn(){this.templateCache={_cache:{},set:function(e,n){this._cache[e]=n},get:function(e){return this._cache[e]},clear:function(){this._cache={}}}}Tn.prototype.clearCache=function(){typeof this.templateCache<"u"&&this.templateCache.clear()};Tn.prototype.parse=function(e,n){var r=this.templateCache,s=e+":"+(n||Pn.tags).join(":"),a=typeof r<"u",i=a?r.get(s):void 0;return i==null&&(i=iF(e,n),a&&r.set(s,i)),i};Tn.prototype.render=function(e,n,r,s){var a=this.getConfigTags(s),i=this.parse(e,a),o=n instanceof Bi?n:new Bi(n,void 0);return this.renderTokens(i,o,r,e,s)};Tn.prototype.renderTokens=function(e,n,r,s,a){for(var i="",o,c,u,l=0,d=e.length;l<d;++l)u=void 0,o=e[l],c=o[0],c==="#"?u=this.renderSection(o,n,r,s,a):c==="^"?u=this.renderInverted(o,n,r,s,a):c===">"?u=this.renderPartial(o,n,r,a):c==="&"?u=this.unescapedValue(o,n):c==="name"?u=this.escapedValue(o,n,a):c==="text"&&(u=this.rawValue(o)),u!==void 0&&(i+=u);return i};Tn.prototype.renderSection=function(e,n,r,s,a){var i=this,o="",c=n.lookup(e[1]);function u(f){return i.render(f,n,r,a)}if(c){if(Xi(c))for(var l=0,d=c.length;l<d;++l)o+=this.renderTokens(e[4],n.push(c[l]),r,s,a);else if(typeof c=="object"||typeof c=="string"||typeof c=="number")o+=this.renderTokens(e[4],n.push(c),r,s,a);else if(i_(c)){if(typeof s!="string")throw new Error("Cannot use higher-order sections without the original template");c=c.call(n.view,s.slice(e[3],e[5]),u),c!=null&&(o+=c)}else o+=this.renderTokens(e[4],n,r,s,a);return o}};Tn.prototype.renderInverted=function(e,n,r,s,a){var i=n.lookup(e[1]);if(!i||Xi(i)&&i.length===0)return this.renderTokens(e[4],n,r,s,a)};Tn.prototype.indentPartial=function(e,n,r){for(var s=n.replace(/[^ \t]/g,""),a=e.split(`
206
- `),i=0;i<a.length;i++)a[i].length&&(i>0||!r)&&(a[i]=s+a[i]);return a.join(`
207
- `)};Tn.prototype.renderPartial=function(e,n,r,s){if(r){var a=this.getConfigTags(s),i=i_(r)?r(e[1]):r[e[1]];if(i!=null){var o=e[6],c=e[5],u=e[4],l=i;c==0&&u&&(l=this.indentPartial(i,u,o));var d=this.parse(l,a);return this.renderTokens(d,n,r,l,s)}}};Tn.prototype.unescapedValue=function(e,n){var r=n.lookup(e[1]);if(r!=null)return r};Tn.prototype.escapedValue=function(e,n,r){var s=this.getConfigEscape(r)||Pn.escape,a=n.lookup(e[1]);if(a!=null)return typeof a=="number"&&s===Pn.escape?String(a):s(a)};Tn.prototype.rawValue=function(e){return e[1]};Tn.prototype.getConfigTags=function(e){return Xi(e)?e:e&&typeof e=="object"?e.tags:void 0};Tn.prototype.getConfigEscape=function(e){if(e&&typeof e=="object"&&!Xi(e))return e.escape};var Pn={name:"mustache.js",version:"4.2.0",tags:["{{","}}"],clearCache:void 0,escape:void 0,parse:void 0,render:void 0,Scanner:void 0,Context:void 0,Writer:void 0,set templateCache(t){Ec.templateCache=t},get templateCache(){return Ec.templateCache}},Ec=new Tn;Pn.clearCache=function(){return Ec.clearCache()};Pn.parse=function(e,n){return Ec.parse(e,n)};Pn.render=function(e,n,r,s){if(typeof e!="string")throw new TypeError('Invalid template! Template should be a "string" but "'+qD(e)+'" was given as the first argument for mustache#render(template, view, partials)');return Ec.render(e,n,r,s)};Pn.escape=tF;Pn.Scanner=eu;Pn.Context=Bi;Pn.Writer=Tn;function XE(){Pn.escape=t=>t}const Ac=t=>{const e=t.split(""),n=[],r=(a,i)=>{for(let o=i;o<e.length;o+=1)if(a.includes(e[o]))return o;return-1};let s=0;for(;s<e.length;)if(e[s]==="{"&&s+1<e.length&&e[s+1]==="{")n.push({type:"literal",text:"{"}),s+=2;else if(e[s]==="}"&&s+1<e.length&&e[s+1]==="}")n.push({type:"literal",text:"}"}),s+=2;else if(e[s]==="{"){const a=r("}",s);if(a<0)throw new Error("Unclosed '{' in template.");n.push({type:"variable",name:e.slice(s+1,a).join("")}),s=a+1}else{if(e[s]==="}")throw new Error("Single '}' in template.");{const a=r("{}",s),i=(a<0?e.slice(s):e.slice(s,a)).join("");n.push({type:"literal",text:i}),s=a<0?e.length:a}}return n},YE=(t,e=[])=>{const n=[];for(const r of t)if(r[0]==="name"){const s=r[1].includes(".")?r[1].split(".")[0]:r[1];n.push({type:"variable",name:s})}else if(["#","&","^",">"].includes(r[0])){if(n.push({type:"variable",name:r[1]}),r[0]==="#"&&r.length>4&&Array.isArray(r[4])){const s=[...e,r[1]],a=YE(r[4],s);n.push(...a)}}else n.push({type:"literal",text:r[1]});return n},md=t=>(XE(),YE(Pn.parse(t))),QE=(t,e)=>Ac(t).reduce((n,r)=>{if(r.type==="variable"){if(r.name in e)return n+(typeof e[r.name]=="string"?e[r.name]:JSON.stringify(e[r.name]));throw new Error(`(f-string) Missing value for input ${r.name}`)}return n+r.text},""),eA=(t,e)=>(XE(),Pn.render(t,e)),gd={"f-string":QE,mustache:eA},tA={"f-string":Ac,mustache:md},Er=(t,e,n)=>{try{return gd[e](t,n)}catch(r){throw Lc(r,"INVALID_PROMPT_INPUT")}},_d=(t,e)=>tA[e](t),tu=(t,e,n)=>{if(!(e in gd))throw new Error(`Invalid template format. Got \`${e}\`;
208
- should be one of ${Object.keys(gd)}`);try{const r=Object.fromEntries(n.map(s=>[s,"foo"]));Array.isArray(t)?t.forEach(s=>{if(s.type==="text"&&"text"in s&&typeof s.text=="string")Er(s.text,e,r);else if(s.type==="image_url"){if(typeof s.image_url=="string")Er(s.image_url,e,r);else if(typeof s.image_url=="object"&&s.image_url!==null&&"url"in s.image_url&&typeof s.image_url.url=="string"){const a=s.image_url.url;Er(a,e,r)}}else throw new Error(`Invalid message template received. ${JSON.stringify(s,null,2)}`)}):Er(t,e,r)}catch(r){throw new Error(`Invalid prompt schema: ${r.message}`)}};var Ws=class No extends Tc{constructor(n){super(n);p(this,"template");p(this,"templateFormat","f-string");p(this,"validateTemplate",!0);p(this,"additionalContentFields");if(n.templateFormat==="mustache"&&n.validateTemplate===void 0&&(this.validateTemplate=!1),Object.assign(this,n),this.validateTemplate){if(this.templateFormat==="mustache")throw new Error("Mustache templates cannot be validated.");let r=this.inputVariables;this.partialVariables&&(r=r.concat(Object.keys(this.partialVariables))),tu(this.template,this.templateFormat,r)}}static lc_name(){return"PromptTemplate"}_getPromptType(){return"prompt"}async format(n){const r=await this.mergePartialAndUserVariables(n);return Er(this.template,this.templateFormat,r)}static fromExamples(n,r,s,a=`
209
-
210
- `,i=""){return new No({inputVariables:s,template:[i,...n,r].join(a)})}static fromTemplate(n,r){const{templateFormat:s="f-string",...a}=r??{},i=new Set;return _d(n,s).forEach(o=>{o.type==="variable"&&i.add(o.name)}),new No({inputVariables:[...i],templateFormat:s,template:n,...a})}async partial(n){const r=this.inputVariables.filter(a=>!(a in n)),s={...this.partialVariables??{},...n};return new No({...this,inputVariables:r,partialVariables:s})}serialize(){if(this.outputParser!==void 0)throw new Error("Cannot serialize a prompt template with an output parser");return{_type:this._getPromptType(),input_variables:this.inputVariables,template:this.template,template_format:this.templateFormat}}static async deserialize(n){if(!n.template)throw new Error("Prompt template must have a template");return new No({inputVariables:n.input_variables,template:n.template,templateFormat:n.template_format})}},vl=class nA extends Qc{constructor(n){super(n);p(this,"lc_namespace",["langchain_core","prompts","image"]);p(this,"template");p(this,"templateFormat","f-string");p(this,"validateTemplate",!0);p(this,"additionalContentFields");if(this.template=n.template,this.templateFormat=n.templateFormat??this.templateFormat,this.validateTemplate=n.validateTemplate??this.validateTemplate,this.additionalContentFields=n.additionalContentFields,this.validateTemplate){let r=this.inputVariables;this.partialVariables&&(r=r.concat(Object.keys(this.partialVariables))),tu([{type:"image_url",image_url:this.template}],this.templateFormat,r)}}static lc_name(){return"ImagePromptTemplate"}_getPromptType(){return"prompt"}async partial(n){const r=this.inputVariables.filter(a=>!(a in n)),s={...this.partialVariables??{},...n};return new nA({...this,inputVariables:r,partialVariables:s})}async format(n){const r={};for(const[o,c]of Object.entries(this.template))typeof c=="string"?r[o]=Er(c,this.templateFormat,n):r[o]=c;const s=n.url||r.url,a=n.detail||r.detail;if(!s)throw new Error("Must provide either an image URL.");if(typeof s!="string")throw new Error("url must be a string.");const i={url:s};return a&&(i.detail=a),i}async formatPromptValue(n){return new LE(await this.format(n))}},lm=class extends Fe{constructor(e){const n=e.templateFormat??"f-string",r=dm(e.template,n);super({inputVariables:r,...e});p(this,"lc_namespace",["langchain_core","prompts","dict"]);p(this,"lc_serializable",!0);p(this,"template");p(this,"templateFormat");p(this,"inputVariables");this.template=e.template,this.templateFormat=n,this.inputVariables=r}static lc_name(){return"DictPromptTemplate"}async format(e){return hm(this.template,e,this.templateFormat)}async invoke(e){return await this._callWithConfig(this.format.bind(this),e,{runType:"prompt"})}};function dm(t,e){const n=[];for(const r of Object.values(t))if(typeof r=="string")_d(r,e).forEach(s=>{s.type==="variable"&&n.push(s.name)});else if(Array.isArray(r))for(const s of r)typeof s=="string"?_d(s,e).forEach(a=>{a.type==="variable"&&n.push(a.name)}):typeof s=="object"&&n.push(...dm(s,e));else typeof r=="object"&&r!==null&&n.push(...dm(r,e));return Array.from(new Set(n))}function hm(t,e,n){const r={};for(const[s,a]of Object.entries(t))if(typeof a=="string")r[s]=Er(a,n,e);else if(Array.isArray(a)){const i=[];for(const o of a)typeof o=="string"?i.push(Er(o,n,e)):typeof o=="object"&&i.push(hm(o,e,n));r[s]=i}else typeof a=="object"&&a!==null?r[s]=hm(a,e,n):r[s]=a;return r}var ch=class extends Fe{constructor(){super(...arguments);p(this,"lc_namespace",["langchain_core","prompts","chat"]);p(this,"lc_serializable",!0)}async invoke(e,n){return this._callWithConfig(r=>this.formatMessages(r),e,{...n,runType:"prompt"})}},fm=class extends ch{constructor(e){typeof e=="string"&&(e={variableName:e});super(e);p(this,"variableName");p(this,"optional");this.variableName=e.variableName,this.optional=e.optional??!1}static lc_name(){return"MessagesPlaceholder"}get inputVariables(){return[this.variableName]}async formatMessages(e){const n=e[this.variableName];if(this.optional&&!n)return[];if(!n){const s=new Error(`Field "${this.variableName}" in prompt uses a MessagesPlaceholder, which expects an array of BaseMessages as an input value. Received: undefined`);throw s.name="InputFormatError",s}let r;try{Array.isArray(n)?r=n.map(Vr):r=[Vr(n)]}catch(s){const a=typeof n=="string"?n:JSON.stringify(n,null,2),i=new Error([`Field "${this.variableName}" in prompt uses a MessagesPlaceholder, which expects an array of BaseMessages or coerceable values as input.`,`Received value: ${a}`,`Additional message: ${s.message}`].join(`
211
-
212
- `));throw i.name="InputFormatError",i.lc_error_code=s.lc_error_code,i}return r}},rA=class extends ch{constructor(e){"prompt"in e||(e={prompt:e});super(e);p(this,"prompt");this.prompt=e.prompt}get inputVariables(){return this.prompt.inputVariables}async formatMessages(e){return[await this.format(e)]}},o_=class extends Qc{constructor(t){super(t)}async format(t){return(await this.formatPromptValue(t)).toString()}async formatPromptValue(t){return new Qg(await this.formatMessages(t))}},sA=class extends rA{constructor(e,n){"prompt"in e||(e={prompt:e,role:n});super(e);p(this,"role");this.role=e.role}static lc_name(){return"ChatMessagePromptTemplate"}async format(e){return new Kr(await this.prompt.format(e),this.role)}static fromTemplate(e,n,r){return new this(Ws.fromTemplate(e,{templateFormat:r==null?void 0:r.templateFormat}),n)}};function uF(t){return t===null||typeof t!="object"||Array.isArray(t)?!1:Object.keys(t).length===1&&"text"in t&&typeof t.text=="string"}function lF(t){return t===null||typeof t!="object"||Array.isArray(t)?!1:"image_url"in t&&(typeof t.image_url=="string"||typeof t.image_url=="object"&&t.image_url!==null&&"url"in t.image_url&&typeof t.image_url.url=="string")}var c_=class extends ch{constructor(e,n){"prompt"in e||(e={prompt:e});super(e);p(this,"lc_namespace",["langchain_core","prompts","chat"]);p(this,"lc_serializable",!0);p(this,"inputVariables",[]);p(this,"additionalOptions",{});p(this,"prompt");p(this,"messageClass");p(this,"chatMessageClass");if(this.prompt=e.prompt,Array.isArray(this.prompt)){let r=[];this.prompt.forEach(s=>{"inputVariables"in s&&(r=r.concat(s.inputVariables))}),this.inputVariables=r}else this.inputVariables=this.prompt.inputVariables;this.additionalOptions=n??this.additionalOptions}static _messageClass(){throw new Error("Can not invoke _messageClass from inside _StringImageMessagePromptTemplate")}createMessage(e){const n=this.constructor;if(n._messageClass())return new(n._messageClass())({content:e});if(n.chatMessageClass){const r=n.chatMessageClass();return new r({content:e,role:this.getRoleFromMessageClass(r.lc_name())})}else throw new Error("No message class defined")}getRoleFromMessageClass(e){switch(e){case"HumanMessage":return"human";case"AIMessage":return"ai";case"SystemMessage":return"system";case"ChatMessage":return"chat";default:throw new Error("Invalid message class name")}}static fromTemplate(e,n){if(typeof e=="string")return new this(Ws.fromTemplate(e,n));const r=[];for(const s of e)if(typeof s=="string")r.push(Ws.fromTemplate(s,n));else if(s!==null)if(uF(s)){let a="";typeof s.text=="string"&&(a=s.text??"");const i={...n,additionalContentFields:s};r.push(Ws.fromTemplate(a,i))}else if(lF(s)){let a=s.image_url??"",i,o=[];if(typeof a=="string"){let c;(n==null?void 0:n.templateFormat)==="mustache"?c=md(a):c=Ac(a);const u=c.flatMap(l=>l.type==="variable"?[l.name]:[]);if(((u==null?void 0:u.length)??0)>0){if(u.length>1)throw new Error(`Only one format variable allowed per image template.
213
- Got: ${u}
214
- From: ${a}`);o=[u[0]]}else o=[];a={url:a},i=new vl({template:a,inputVariables:o,templateFormat:n==null?void 0:n.templateFormat,additionalContentFields:s})}else if(typeof a=="object"){if("url"in a){let c;(n==null?void 0:n.templateFormat)==="mustache"?c=md(a.url):c=Ac(a.url),o=c.flatMap(u=>u.type==="variable"?[u.name]:[])}else o=[];i=new vl({template:a,inputVariables:o,templateFormat:n==null?void 0:n.templateFormat,additionalContentFields:s})}else throw new Error("Invalid image template");r.push(i)}else typeof s=="object"&&r.push(new lm({template:s,templateFormat:n==null?void 0:n.templateFormat}));return new this({prompt:r,additionalOptions:n})}async format(e){if(this.prompt instanceof Tc){const n=await this.prompt.format(e);return this.createMessage(n)}else{const n=[];for(const r of this.prompt){let s={};if(!("inputVariables"in r))throw new Error(`Prompt ${r} does not have inputVariables defined.`);for(const a of r.inputVariables)s||(s={[a]:e[a]}),s={...s,[a]:e[a]};if(r instanceof Tc){const a=await r.format(s);let i;"additionalContentFields"in r&&(i=r.additionalContentFields),a!==""&&n.push({...i,type:"text",text:a})}else if(r instanceof vl){const a=await r.format(s);let i;"additionalContentFields"in r&&(i=r.additionalContentFields),n.push({...i,type:"image_url",image_url:a})}else if(r instanceof lm){const a=await r.format(s);let i;"additionalContentFields"in r&&(i=r.additionalContentFields),n.push({...i,...a})}}return this.createMessage(n)}}async formatMessages(e){return[await this.format(e)]}},u_=class extends c_{static _messageClass(){return vn}static lc_name(){return"HumanMessagePromptTemplate"}},aA=class extends c_{static _messageClass(){return De}static lc_name(){return"AIMessagePromptTemplate"}},iA=class extends c_{static _messageClass(){return Gn}static lc_name(){return"SystemMessagePromptTemplate"}};function dF(t){return typeof t.formatMessages=="function"}function hF(t,e){if(dF(t)||wt(t))return t;if(Array.isArray(t)&&t[0]==="placeholder"){const s=t[1];if((e==null?void 0:e.templateFormat)==="mustache"&&typeof s=="string"&&s.slice(0,2)==="{{"&&s.slice(-2)==="}}")return new fm({variableName:s.slice(2,-2),optional:!0});if(typeof s=="string"&&s[0]==="{"&&s[s.length-1]==="}")return new fm({variableName:s.slice(1,-1),optional:!0});throw new Error(`Invalid placeholder template for format ${(e==null?void 0:e.templateFormat)??'"f-string"'}: "${t[1]}". Expected a variable name surrounded by ${(e==null?void 0:e.templateFormat)==="mustache"?"double":"single"} curly braces.`)}const n=Vr(t);let r;if(typeof n.content=="string"?r=n.content:r=n.content.map(s=>"text"in s?{...s,text:s.text}:"image_url"in s?{...s,image_url:s.image_url}:s),n._getType()==="human")return u_.fromTemplate(r,e);if(n._getType()==="ai")return aA.fromTemplate(r,e);if(n._getType()==="system")return iA.fromTemplate(r,e);if(Kr.isInstance(n))return sA.fromTemplate(n.content,n.role,e);throw new Error(`Could not coerce message prompt template from input. Received message type: "${n._getType()}".`)}function fF(t){return t.constructor.lc_name()==="MessagesPlaceholder"}var l_=class Sl extends o_{constructor(n){super(n);p(this,"promptMessages");p(this,"validateTemplate",!0);p(this,"templateFormat","f-string");if(n.templateFormat==="mustache"&&n.validateTemplate===void 0&&(this.validateTemplate=!1),Object.assign(this,n),this.validateTemplate){const r=new Set;for(const c of this.promptMessages)if(!(c instanceof bn))for(const u of c.inputVariables)r.add(u);const s=this.inputVariables,a=new Set(this.partialVariables?s.concat(Object.keys(this.partialVariables)):s),i=new Set([...a].filter(c=>!r.has(c)));if(i.size>0)throw new Error(`Input variables \`${[...i]}\` are not used in any of the prompt messages.`);const o=new Set([...r].filter(c=>!a.has(c)));if(o.size>0)throw new Error(`Input variables \`${[...o]}\` are used in prompt messages but not in the prompt template.`)}}static lc_name(){return"ChatPromptTemplate"}get lc_aliases(){return{promptMessages:"messages"}}_getPromptType(){return"chat"}async _parseImagePrompts(n,r){return typeof n.content=="string"||(n.content=await Promise.all(n.content.map(async s=>{if(s.type!=="image_url")return s;let a="";typeof s.image_url=="string"?a=s.image_url:typeof s.image_url=="object"&&s.image_url!==null&&"url"in s.image_url&&typeof s.image_url.url=="string"&&(a=s.image_url.url);const i=await Ws.fromTemplate(a,{templateFormat:this.templateFormat}).format(r);return typeof s.image_url=="object"&&s.image_url!==null&&"url"in s.image_url?s.image_url.url=i:s.image_url=i,s}))),n}async formatMessages(n){const r=await this.mergePartialAndUserVariables(n);let s=[];for(const a of this.promptMessages)if(a instanceof bn)s.push(await this._parseImagePrompts(a,r));else{let i;this.templateFormat==="mustache"?i={...r}:i=a.inputVariables.reduce((c,u)=>{if(!(u in r)&&!(fF(a)&&a.optional))throw Lc(new Error(`Missing value for input variable \`${u.toString()}\``),"INVALID_PROMPT_INPUT");return c[u]=r[u],c},{});const o=await a.formatMessages(i);s=s.concat(o)}return s}async partial(n){const r=this.inputVariables.filter(a=>!(a in n)),s={...this.partialVariables??{},...n};return new Sl({...this,inputVariables:r,partialVariables:s})}static fromTemplate(n,r){const s=new u_({prompt:Ws.fromTemplate(n,r)});return this.fromMessages([s])}static fromMessages(n,r){const s=n.reduce((o,c)=>o.concat(c instanceof Sl?c.promptMessages:[hF(c,r)]),[]),a=n.reduce((o,c)=>c instanceof Sl?Object.assign(o,c.partialVariables):o,Object.create(null)),i=new Set;for(const o of s)if(!(o instanceof bn))for(const c of o.inputVariables)c in a||i.add(c);return new this({...r,inputVariables:[...i],promptMessages:s,partialVariables:a,templateFormat:r==null?void 0:r.templateFormat})}},pF=class pm extends Tc{constructor(n){super(n);p(this,"lc_serializable",!1);p(this,"examples");p(this,"exampleSelector");p(this,"examplePrompt");p(this,"suffix","");p(this,"exampleSeparator",`
215
-
216
- `);p(this,"prefix","");p(this,"templateFormat","f-string");p(this,"validateTemplate",!0);if(Object.assign(this,n),this.examples!==void 0&&this.exampleSelector!==void 0)throw new Error("Only one of 'examples' and 'example_selector' should be provided");if(this.examples===void 0&&this.exampleSelector===void 0)throw new Error("One of 'examples' and 'example_selector' should be provided");if(this.validateTemplate){let r=this.inputVariables;this.partialVariables&&(r=r.concat(Object.keys(this.partialVariables))),tu(this.prefix+this.suffix,this.templateFormat,r)}}_getPromptType(){return"few_shot"}static lc_name(){return"FewShotPromptTemplate"}async getExamples(n){if(this.examples!==void 0)return this.examples;if(this.exampleSelector!==void 0)return this.exampleSelector.selectExamples(n);throw new Error("One of 'examples' and 'example_selector' should be provided")}async partial(n){const r=this.inputVariables.filter(a=>!(a in n)),s={...this.partialVariables??{},...n};return new pm({...this,inputVariables:r,partialVariables:s})}async format(n){const r=await this.mergePartialAndUserVariables(n),s=await this.getExamples(r),a=await Promise.all(s.map(i=>this.examplePrompt.format(i)));return Er([this.prefix,...a,this.suffix].join(this.exampleSeparator),this.templateFormat,r)}serialize(){if(this.exampleSelector||!this.examples)throw new Error("Serializing an example selector is not currently supported");if(this.outputParser!==void 0)throw new Error("Serializing an output parser is not currently supported");return{_type:this._getPromptType(),input_variables:this.inputVariables,example_prompt:this.examplePrompt.serialize(),example_separator:this.exampleSeparator,suffix:this.suffix,prefix:this.prefix,template_format:this.templateFormat,examples:this.examples}}static async deserialize(n){const{example_prompt:r}=n;if(!r)throw new Error("Missing example prompt");const s=await Ws.deserialize(r);let a;if(Array.isArray(n.examples))a=n.examples;else throw new Error("Invalid examples format. Only list or string are supported.");return new pm({inputVariables:n.input_variables,examplePrompt:s,examples:a,exampleSeparator:n.example_separator,prefix:n.prefix,suffix:n.suffix,templateFormat:n.template_format})}},mF=class oA extends o_{constructor(n){super(n);p(this,"lc_serializable",!0);p(this,"examples");p(this,"exampleSelector");p(this,"examplePrompt");p(this,"suffix","");p(this,"exampleSeparator",`
217
-
218
- `);p(this,"prefix","");p(this,"templateFormat","f-string");p(this,"validateTemplate",!0);if(this.examples=n.examples,this.examplePrompt=n.examplePrompt,this.exampleSeparator=n.exampleSeparator??`
219
-
220
- `,this.exampleSelector=n.exampleSelector,this.prefix=n.prefix??"",this.suffix=n.suffix??"",this.templateFormat=n.templateFormat??"f-string",this.validateTemplate=n.validateTemplate??!0,this.examples!==void 0&&this.exampleSelector!==void 0)throw new Error("Only one of 'examples' and 'example_selector' should be provided");if(this.examples===void 0&&this.exampleSelector===void 0)throw new Error("One of 'examples' and 'example_selector' should be provided");if(this.validateTemplate){let r=this.inputVariables;this.partialVariables&&(r=r.concat(Object.keys(this.partialVariables))),tu(this.prefix+this.suffix,this.templateFormat,r)}}_getPromptType(){return"few_shot_chat"}static lc_name(){return"FewShotChatMessagePromptTemplate"}async getExamples(n){if(this.examples!==void 0)return this.examples;if(this.exampleSelector!==void 0)return this.exampleSelector.selectExamples(n);throw new Error("One of 'examples' and 'example_selector' should be provided")}async formatMessages(n){const r=await this.mergePartialAndUserVariables(n);let s=await this.getExamples(r);s=s.map(i=>{const o={};return this.examplePrompt.inputVariables.forEach(c=>{o[c]=i[c]}),o});const a=[];for(const i of s){const o=await this.examplePrompt.formatMessages(i);a.push(...o)}return a}async format(n){const r=await this.mergePartialAndUserVariables(n),s=await this.getExamples(r),a=(await Promise.all(s.map(i=>this.examplePrompt.formatMessages(i)))).flat().map(i=>i.content);return Er([this.prefix,...a,this.suffix].join(this.exampleSeparator),this.templateFormat,r)}async partial(n){const r=this.inputVariables.filter(a=>!(a in n)),s={...this.partialVariables??{},...n};return new oA({...this,inputVariables:r,partialVariables:s})}},gF=class Tl extends Qc{constructor(n){super({...n,inputVariables:[]});p(this,"pipelinePrompts");p(this,"finalPrompt");this.pipelinePrompts=n.pipelinePrompts,this.finalPrompt=n.finalPrompt,this.inputVariables=this.computeInputValues()}static lc_name(){return"PipelinePromptTemplate"}computeInputValues(){const n=this.pipelinePrompts.map(s=>s.name),r=this.pipelinePrompts.map(s=>s.prompt.inputVariables.filter(a=>!n.includes(a))).flat();return[...new Set(r)]}static extractRequiredInputValues(n,r){return r.reduce((s,a)=>(s[a]=n[a],s),{})}async formatPipelinePrompts(n){const r=await this.mergePartialAndUserVariables(n);for(const{name:s,prompt:a}of this.pipelinePrompts){const i=Tl.extractRequiredInputValues(r,a.inputVariables);a instanceof l_?r[s]=await a.formatMessages(i):r[s]=await a.format(i)}return Tl.extractRequiredInputValues(r,this.finalPrompt.inputVariables)}async formatPromptValue(n){return this.finalPrompt.formatPromptValue(await this.formatPipelinePrompts(n))}async format(n){return this.finalPrompt.format(await this.formatPipelinePrompts(n))}async partial(n){const r={...this};return r.inputVariables=this.inputVariables.filter(s=>!(s in n)),r.partialVariables={...this.partialVariables??{},...n},new Tl(r)}serialize(){throw new Error("Not implemented.")}_getPromptType(){return"pipeline"}};function Tb(t){return typeof t=="object"&&t!=null&&"withStructuredOutput"in t&&typeof t.withStructuredOutput=="function"}function _F(t){return typeof t=="object"&&t!=null&&"lc_id"in t&&Array.isArray(t.lc_id)&&t.lc_id.join("/")==="langchain_core/runnables/RunnableBinding"}var yF=class cA extends l_{constructor(n){super(n);p(this,"schema");p(this,"method");p(this,"lc_namespace",["langchain_core","prompts","structured"]);this.schema=n.schema,this.method=n.method}get lc_aliases(){return{...super.lc_aliases,schema:"schema_"}}pipe(n){if(Tb(n))return super.pipe(n.withStructuredOutput(this.schema));if(_F(n)&&Tb(n.bound))return super.pipe(new Qt({bound:n.bound.withStructuredOutput(this.schema,...this.method?[{method:this.method}]:[]),kwargs:n.kwargs??{},config:n.config,configFactories:n.configFactories}));throw new Error('Structured prompts need to be piped to a language model that supports the "withStructuredOutput()" method.')}static fromMessagesAndSchema(n,r,s){return cA.fromMessages(n,{schema:r,method:s})}},wF=ue({AIMessagePromptTemplate:()=>aA,BaseChatPromptTemplate:()=>o_,BaseMessagePromptTemplate:()=>ch,BaseMessageStringPromptTemplate:()=>rA,BasePromptTemplate:()=>Qc,BaseStringPromptTemplate:()=>Tc,ChatMessagePromptTemplate:()=>sA,ChatPromptTemplate:()=>l_,DEFAULT_FORMATTER_MAPPING:()=>gd,DEFAULT_PARSER_MAPPING:()=>tA,DictPromptTemplate:()=>lm,FewShotChatMessagePromptTemplate:()=>mF,FewShotPromptTemplate:()=>pF,HumanMessagePromptTemplate:()=>u_,ImagePromptTemplate:()=>vl,MessagesPlaceholder:()=>fm,PipelinePromptTemplate:()=>gF,PromptTemplate:()=>Ws,StructuredPrompt:()=>yF,SystemMessagePromptTemplate:()=>iA,checkValidTemplate:()=>tu,interpolateFString:()=>QE,interpolateMustache:()=>eA,parseFString:()=>Ac,parseMustache:()=>md,parseTemplate:()=>_d,renderTemplate:()=>Er}),bF=ue({BaseDocumentCompressor:()=>vF}),vF=class{static isBaseDocumentCompressor(t){return(t==null?void 0:t.compressDocuments)!==void 0}},SF=ue({BaseRetriever:()=>d_}),d_=class extends Fe{constructor(e){super(e);p(this,"callbacks");p(this,"tags");p(this,"metadata");p(this,"verbose");this.callbacks=e==null?void 0:e.callbacks,this.tags=(e==null?void 0:e.tags)??[],this.metadata=(e==null?void 0:e.metadata)??{},this.verbose=(e==null?void 0:e.verbose)??!1}_getRelevantDocuments(e,n){throw new Error("Not implemented!")}async invoke(e,n){var a;const r=Ge(Vc(n)),s=await((a=await un.configure(r.callbacks,this.callbacks,r.tags,this.tags,r.metadata,this.metadata,{verbose:this.verbose}))==null?void 0:a.handleRetrieverStart(this.toJSON(),e,r.runId,void 0,void 0,void 0,r.runName));try{const i=await this._getRelevantDocuments(e,s);return await(s==null?void 0:s.handleRetrieverEnd(i)),i}catch(i){throw await(s==null?void 0:s.handleRetrieverError(i)),i}}},TF=ue({BaseStore:()=>uA,InMemoryStore:()=>EF}),uA=class extends ar{},EF=class extends uA{constructor(){super(...arguments);p(this,"lc_namespace",["langchain","storage"]);p(this,"store",{})}async mget(e){return e.map(n=>this.store[n])}async mset(e){for(const[n,r]of e)this.store[n]=r}async mdelete(e){for(const n of e)delete this.store[n]}async*yieldKeys(e){const n=Object.keys(this.store);for(const r of n)(e===void 0||r.startsWith(e))&&(yield r)}};const Us={and:"and",or:"or",not:"not"},We={eq:"eq",ne:"ne",lt:"lt",gt:"gt",lte:"lte",gte:"gte"};var lA=class{},h_=class{accept(t){if(this.exprName==="Operation")return t.visitOperation(this);if(this.exprName==="Comparison")return t.visitComparison(this);if(this.exprName==="StructuredQuery")return t.visitStructuredQuery(this);throw new Error("Unknown Expression type")}},f_=class extends h_{},AF=class extends f_{constructor(e,n,r){super();p(this,"exprName","Comparison");this.comparator=e,this.attribute=n,this.value=r}},IF=class extends f_{constructor(e,n){super();p(this,"exprName","Operation");this.operator=e,this.args=n}},xF=class extends h_{constructor(e,n){super();p(this,"exprName","StructuredQuery");this.query=e,this.filter=n}};function dA(t){return t&&typeof t=="object"&&!Array.isArray(t)}function Sr(t){return t?typeof t=="string"&&t.length>0||typeof t=="function"?!1:dA(t)&&Object.keys(t).length===0:!0}function hA(t){if(typeof t=="number")return t%1===0;if(typeof t=="string"){const e=parseInt(t,10);return!Number.isNaN(e)&&e%1===0&&e.toString()===t}return!1}function fA(t){if(typeof t=="number")return t%1!==0;if(typeof t=="string"){const e=parseFloat(t);return!Number.isNaN(e)&&e%1!==0&&e.toString()===t}return!1}function pA(t){return typeof t=="string"&&(Number.isNaN(parseFloat(t))||parseFloat(t).toString()!==t)}function mA(t){return typeof t=="boolean"}function p_(t){let e;if(pA(t))e=t;else if(hA(t))e=parseInt(t,10);else if(fA(t))e=parseFloat(t);else if(mA(t))e=!!t;else throw new Error("Unsupported value type");return e}var m_=class extends lA{},kF=class extends m_{constructor(e){super();p(this,"allowedOperators");p(this,"allowedComparators");this.allowedOperators=(e==null?void 0:e.allowedOperators)??[Us.and,Us.or],this.allowedComparators=(e==null?void 0:e.allowedComparators)??[We.eq,We.ne,We.gt,We.gte,We.lt,We.lte]}formatFunction(e){if(e in We){if(this.allowedComparators.length>0&&this.allowedComparators.indexOf(e)===-1)throw new Error(`Comparator ${e} not allowed. Allowed comparators: ${this.allowedComparators.join(", ")}`)}else if(e in Us){if(this.allowedOperators.length>0&&this.allowedOperators.indexOf(e)===-1)throw new Error(`Operator ${e} not allowed. Allowed operators: ${this.allowedOperators.join(", ")}`)}else throw new Error("Unknown comparator or operator");return`$${e}`}visitOperation(e){var r;const n=(r=e.args)==null?void 0:r.map(s=>s.accept(this));return{[this.formatFunction(e.operator)]:n}}visitComparison(e){return{[e.attribute]:{[this.formatFunction(e.comparator)]:p_(e.value)}}}visitStructuredQuery(e){let n={};return e.filter&&(n={filter:e.filter.accept(this)}),n}mergeFilters(e,n,r="and",s=!1){if(!(Sr(e)&&Sr(n))){if(Sr(e)||r==="replace")return Sr(n)?void 0:n;if(Sr(n))return s?e:r==="and"?void 0:e;if(r==="and")return{$and:[e,n]};if(r==="or")return{$or:[e,n]};throw new Error("Unknown merge type")}}},OF=class extends m_{constructor(){super(...arguments);p(this,"allowedOperators",[Us.and,Us.or]);p(this,"allowedComparators",[We.eq,We.ne,We.gt,We.gte,We.lt,We.lte])}formatFunction(){throw new Error("Not implemented")}getAllowedComparatorsForType(e){switch(e){case"string":return[We.eq,We.ne,We.gt,We.gte,We.lt,We.lte];case"number":return[We.eq,We.ne,We.gt,We.gte,We.lt,We.lte];case"boolean":return[We.eq,We.ne];default:throw new Error(`Unsupported data type: ${e}`)}}getComparatorFunction(e){switch(e){case We.eq:return(n,r)=>n===r;case We.ne:return(n,r)=>n!==r;case We.gt:return(n,r)=>n>r;case We.gte:return(n,r)=>n>=r;case We.lt:return(n,r)=>n<r;case We.lte:return(n,r)=>n<=r;default:throw new Error("Unknown comparator")}}getOperatorFunction(e){switch(e){case Us.and:return(n,r)=>n&&r;case Us.or:return(n,r)=>n||r;default:throw new Error("Unknown operator")}}visitOperation(e){const{operator:n,args:r}=e;if(this.allowedOperators.includes(n)){const s=this.getOperatorFunction(n);return a=>r?r.reduce((i,o)=>{const c=o.accept(this);if(typeof c=="function")return s(i,c(a));throw new Error("Filter is not a function")},!0):!0}else throw new Error("Operator not allowed")}visitComparison(e){const{comparator:n,attribute:r,value:s}=e,a=[We.ne];if(this.allowedComparators.includes(n)){if(!this.getAllowedComparatorsForType(typeof s).includes(n))throw new Error(`'${n}' comparator not allowed to be used with ${typeof s}`);const i=this.getComparatorFunction(n);return o=>{const c=o.metadata[r];return c===void 0?!!a.includes(n):i(c,p_(s))}}else throw new Error("Comparator not allowed")}visitStructuredQuery(e){var r;if(!e.filter)return{};const n=(r=e.filter)==null?void 0:r.accept(this);if(typeof n!="function")throw new Error("Structured query filter is not a function");return{filter:n}}mergeFilters(e,n,r="and"){if(!(Sr(e)&&Sr(n))){if(Sr(e)||r==="replace")return Sr(n)?void 0:n;if(Sr(n))return r==="and"?void 0:e;if(r==="and")return s=>e(s)&&n(s);if(r==="or")return s=>e(s)||n(s);throw new Error("Unknown merge type")}}},CF=ue({BaseTranslator:()=>m_,BasicTranslator:()=>kF,Comparators:()=>We,Comparison:()=>AF,Expression:()=>h_,FilterDirective:()=>f_,FunctionalTranslator:()=>OF,Operation:()=>IF,Operators:()=>Us,StructuredQuery:()=>xF,Visitor:()=>lA,castValue:()=>p_,isBoolean:()=>mA,isFilterEmpty:()=>Sr,isFloat:()=>fA,isInt:()=>hA,isObject:()=>dA,isString:()=>pA});function Ic(t){return bn.isInstance(t)?t.constructor.name||t.type:typeof t}function uh(t,e){return function(n,r){const{isNot:s,utils:a}=this;if(!e(n))return{pass:!1,message:()=>`${a.matcherHint(`toBe${t}`,void 0,void 0)}
221
-
222
- Expected: ${s?"not ":""}${t}
223
- Received: ${Ic(n)}`,actual:Ic(n),expected:t};if(r===void 0)return{pass:!0,message:()=>`${a.matcherHint(`toBe${t}`,void 0,void 0)}
224
-
225
- Expected: not ${t}
226
- Received: ${t}`};const i=n;return typeof r=="string"?{pass:i.content===r,message:()=>`${a.matcherHint(`toBe${t}`,void 0,void 0)}
227
-
228
- Expected: ${t} with content ${a.printExpected(r)}
229
- Received: ${t} with content ${a.printReceived(i.content)}`,actual:i.content,expected:r}:{pass:Object.entries(r).every(([o,c])=>this.equals(i[o],c)),message:()=>{const o={};for(const c of Object.keys(r))o[c]=i[c];return`${a.matcherHint(`toBe${t}`,void 0,void 0)}
230
-
231
- Expected: ${t} matching ${a.printExpected(r)}
232
- Received: ${t} with ${a.printReceived(o)}`},actual:(()=>{const o={};for(const c of Object.keys(r))o[c]=i[c];return o})(),expected:r}}}const gA=uh("HumanMessage",vn.isInstance),_A=uh("AIMessage",De.isInstance),yA=uh("SystemMessage",Gn.isInstance),wA=uh("ToolMessage",Rn.isInstance);function bA(t,e){const{isNot:n,utils:r}=this;if(!De.isInstance(t))return{pass:!1,message:()=>`${r.matcherHint("toHaveToolCalls")}
233
-
234
- Expected: AIMessage
235
- Received: ${Ic(t)}`};const s=t.tool_calls??[];if(s.length!==e.length)return{pass:!1,message:()=>`${r.matcherHint("toHaveToolCalls")}
236
-
237
- Expected ${n?"not ":""}${e.length} tool call(s), received ${s.length}`,actual:s.length,expected:e.length};const a=e.filter(i=>!s.some(o=>Object.entries(i).every(([c,u])=>this.equals(o[c],u))));return a.length>0?{pass:!1,message:()=>`${r.matcherHint("toHaveToolCalls")}
238
-
239
- Could not find matching tool call(s) for:
240
- ${r.printExpected(a)}
241
- Received tool calls: ${r.printReceived(s.map(i=>({name:i.name,id:i.id,args:i.args})))}`,actual:s.map(i=>({name:i.name,id:i.id,args:i.args})),expected:e}:{pass:!0,message:()=>`${r.matcherHint("toHaveToolCalls")}
242
-
243
- Expected AIMessage not to have matching tool calls`}}function vA(t,e){var a;const{isNot:n,utils:r}=this;if(!De.isInstance(t))return{pass:!1,message:()=>`${r.matcherHint("toHaveToolCallCount")}
244
-
245
- Expected: AIMessage
246
- Received: ${Ic(t)}`};const s=((a=t.tool_calls)==null?void 0:a.length)??0;return{pass:s===e,message:()=>`${r.matcherHint("toHaveToolCallCount")}
247
-
248
- Expected ${n?"not ":""}${e} tool call(s)
249
- Received: ${s}`,actual:s,expected:e}}function SA(t,e){const{isNot:n,utils:r}=this;if(!De.isInstance(t))return{pass:!1,message:()=>`${r.matcherHint("toContainToolCall")}
250
-
251
- Expected: AIMessage
252
- Received: ${Ic(t)}`};const s=t.tool_calls??[];return{pass:s.some(a=>Object.entries(e).every(([i,o])=>this.equals(a[i],o))),message:()=>`${r.matcherHint("toContainToolCall")}
253
-
254
- Expected AIMessage ${n?"not ":""}to contain a tool call matching ${r.printExpected(e)}
255
- Received tool calls: ${r.printReceived(s.map(a=>({name:a.name,id:a.id})))}`,actual:s.map(a=>({name:a.name,id:a.id})),expected:e}}function TA(t,e){const{isNot:n,utils:r}=this;if(!Array.isArray(t))return{pass:!1,message:()=>`${r.matcherHint("toHaveToolMessages")}
256
-
257
- Expected an array of messages
258
- Received: ${typeof t}`};const s=t.filter(Rn.isInstance);if(s.length!==e.length)return{pass:!1,message:()=>`${r.matcherHint("toHaveToolMessages")}
259
-
260
- Expected ${n?"not ":""}${e.length} tool message(s), found ${s.length}`,actual:s.length,expected:e.length};for(let a=0;a<e.length;a++)if(!Object.entries(e[a]).every(([i,o])=>this.equals(s[a][i],o)))return{pass:!1,message:()=>{const i={};for(const o of Object.keys(e[a]))i[o]=s[a][o];return`${r.matcherHint("toHaveToolMessages")}
261
-
262
- Tool message at index ${a} did not match:
263
- Expected: ${r.printExpected(e[a])}
264
- Received: ${r.printReceived(i)}`},actual:s[a],expected:e[a]};return{pass:!0,message:()=>`${r.matcherHint("toHaveToolMessages")}
265
-
266
- Expected messages not to contain matching tool messages`}}function EA(t,e){var i;const{isNot:n,utils:r}=this,s=t==null?void 0:t.__interrupt__;if(!(Array.isArray(s)&&s.length>0))return{pass:!1,message:()=>`${r.matcherHint("toHaveBeenInterrupted")}
267
-
268
- Expected result ${n?"not ":""}to have been interrupted
269
- Received __interrupt__: ${r.printReceived(s)}`};if(e===void 0)return{pass:!0,message:()=>`${r.matcherHint("toHaveBeenInterrupted")}
270
-
271
- Expected result not to have been interrupted
272
- Received ${s.length} interrupt(s)`};const a=(i=s[0])==null?void 0:i.value;return{pass:this.equals(a,e),message:()=>`${r.matcherHint("toHaveBeenInterrupted")}
273
-
274
- Expected interrupt value: ${r.printExpected(e)}
275
- Received interrupt value: ${r.printReceived(a)}`,actual:a,expected:e}}function AA(t,e){const{isNot:n,utils:r}=this,s=t==null?void 0:t.structuredResponse;return s===void 0?{pass:!1,message:()=>`${r.matcherHint("toHaveStructuredResponse")}
276
-
277
- Expected result ${n?"not ":""}to have a structured response
278
- Received structuredResponse: undefined`}:e===void 0?{pass:!0,message:()=>`${r.matcherHint("toHaveStructuredResponse")}
279
-
280
- Expected result not to have a structured response`}:{pass:Object.entries(e).every(([a,i])=>this.equals(s[a],i)),message:()=>`${r.matcherHint("toHaveStructuredResponse")}
281
-
282
- Expected structured response: ${r.printExpected(e)}
283
- Received structured response: ${r.printReceived(s)}`,actual:s,expected:e}}const RF={toBeHumanMessage:gA,toBeAIMessage:_A,toBeSystemMessage:yA,toBeToolMessage:wA,toHaveToolCalls:bA,toHaveToolCallCount:vA,toContainToolCall:SA,toHaveToolMessages:TA,toHaveBeenInterrupted:EA,toHaveStructuredResponse:AA};function $F(t){return t.map(e=>e.text).filter(Boolean).join("-")}let Eb=0;function NF(){return Eb+=1,`fake_tc_${Eb}`}var IA=class xA extends Jr{constructor(){super({});p(this,"queue",[]);p(this,"_alwaysThrowError");p(this,"_structuredResponseValue");p(this,"_tools",[]);p(this,"_callIndex",0);p(this,"_calls",[])}get calls(){return this._calls}get callCount(){return this._calls.length}_llmType(){return"fake-model-builder"}_combineLLMOutput(){return[]}respond(n){return typeof n=="function"?this.queue.push({kind:"factory",factory:n}):bn.isInstance(n)?this.queue.push({kind:"message",message:n}):this.queue.push({kind:"error",error:n}),this}respondWithTools(n){return this.queue.push({kind:"toolCalls",toolCalls:n.map(r=>({name:r.name,args:r.args,id:r.id??NF(),type:"tool_call"}))}),this}alwaysThrow(n){return this._alwaysThrowError=n,this}structuredResponse(n){return this._structuredResponseValue=n,this}bindTools(n){const r=[...this._tools,...n],s=new xA;return s.queue=this.queue,s._alwaysThrowError=this._alwaysThrowError,s._structuredResponseValue=this._structuredResponseValue,s._tools=r,s._calls=this._calls,s._callIndex=this._callIndex,s.withConfig({})}withStructuredOutput(n,r){const{_structuredResponseValue:s}=this;return Ht.from(async()=>s)}async _generate(n,r,s){this._calls.push({messages:[...n],options:r});const a=this._callIndex;if(this._callIndex+=1,this._alwaysThrowError)throw this._alwaysThrowError;const i=this.queue[a];if(!i)throw new Error(`FakeModel: no response queued for invocation ${a} (${this.queue.length} total queued).`);if(i.kind==="error")throw i.error;if(i.kind==="factory"){const c=i.factory(n);if(!bn.isInstance(c))throw c;return{generations:[{text:"",message:c}]}}if(i.kind==="message")return{generations:[{text:"",message:i.message}]};const o=$F(n);return{generations:[{text:o,message:new De({content:o,id:a.toString(),tool_calls:i.toolCalls.length>0?i.toolCalls.map(c=>({...c,type:"tool_call"})):void 0})}],llmOutput:{}}}};function PF(){return new IA}var MF=ue({FakeBuiltModel:()=>IA,fakeModel:()=>PF,langchainMatchers:()=>RF,toBeAIMessage:()=>_A,toBeHumanMessage:()=>gA,toBeSystemMessage:()=>yA,toBeToolMessage:()=>wA,toContainToolCall:()=>SA,toHaveBeenInterrupted:()=>EA,toHaveStructuredResponse:()=>AA,toHaveToolCallCount:()=>vA,toHaveToolCalls:()=>bA,toHaveToolMessages:()=>TA});function g_(t){return t!==void 0&&Array.isArray(t.lc_namespace)}function __(t){return t!==void 0&&Fe.isRunnable(t)&&"lc_name"in t.constructor&&typeof t.constructor.lc_name=="function"&&t.constructor.lc_name()==="RunnableToolLike"}function y_(t){return!!t&&typeof t=="object"&&"name"in t&&"schema"in t&&(Lt(t.schema)||t.schema!=null&&typeof t.schema=="object"&&"type"in t.schema&&typeof t.schema.type=="string"&&["null","boolean","object","array","number","string"].includes(t.schema.type))}function vs(t){return y_(t)||__(t)||g_(t)}const LF=U("ZodISODateTime",(t,e)=>{W2.init(t,e),bt.init(t,e)});function jF(t){return KM(LF,t)}const UF=U("ZodISODate",(t,e)=>{G2.init(t,e),bt.init(t,e)});function DF(t){return JM(UF,t)}const FF=U("ZodISOTime",(t,e)=>{q2.init(t,e),bt.init(t,e)});function BF(t){return XM(FF,t)}const zF=U("ZodISODuration",(t,e)=>{K2.init(t,e),bt.init(t,e)});function HF(t){return YM(zF,t)}const VF=(t,e)=>{gT.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:n=>HP(t,n)},flatten:{value:n=>zP(t,n)},addIssue:{value:n=>t.issues.push(n)},addIssues:{value:n=>t.issues.push(...n)},isEmpty:{get(){return t.issues.length===0}}})},lh=U("ZodError",VF,{Parent:Error}),ZF=_T(lh),WF=yT(lh),GF=bT(lh),qF=vT(lh),yt=U("ZodType",(t,e)=>(at.init(t,e),t.def=e,Object.defineProperty(t,"_def",{value:e}),t.check=(...n)=>t.clone({...e,checks:[...e.checks??[],...n.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),t.clone=(n,r)=>cn(t,n,r),t.brand=()=>t,t.register=(n,r)=>(n.add(t,r),t),t.parse=(n,r)=>ZF(t,n,r,{callee:t.parse}),t.safeParse=(n,r)=>GF(t,n,r),t.parseAsync=async(n,r)=>WF(t,n,r,{callee:t.parseAsync}),t.safeParseAsync=async(n,r)=>qF(t,n,r),t.spa=t.safeParseAsync,t.refine=(n,r)=>t.check(HB(n,r)),t.superRefine=n=>t.check(VB(n)),t.overwrite=n=>t.check(qc(n)),t.optional=()=>xb(t),t.nullable=()=>kb(t),t.nullish=()=>xb(kb(t)),t.nonoptional=n=>LB(t,n),t.array=()=>La(t),t.or=n=>nu([t,n]),t.and=n=>EB(t,n),t.transform=n=>Ob(t,CB(n)),t.default=n=>NB(t,n),t.prefault=n=>MB(t,n),t.catch=n=>UB(t,n),t.pipe=n=>Ob(t,n),t.readonly=()=>BB(t),t.describe=n=>{const r=t.clone();return zt.add(r,{description:n}),r},Object.defineProperty(t,"description",{get(){var n;return(n=zt.get(t))==null?void 0:n.description},configurable:!0}),t.meta=(...n)=>{if(n.length===0)return zt.get(t);const r=t.clone();return zt.add(r,n[0]),r},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),kA=U("_ZodString",(t,e)=>{Mg.init(t,e),yt.init(t,e);const n=t._zod.bag;t.format=n.format??null,t.minLength=n.minimum??null,t.maxLength=n.maximum??null,t.regex=(...r)=>t.check(rL(...r)),t.includes=(...r)=>t.check(iL(...r)),t.startsWith=(...r)=>t.check(oL(...r)),t.endsWith=(...r)=>t.check(cL(...r)),t.min=(...r)=>t.check(sd(...r)),t.max=(...r)=>t.check(LT(...r)),t.length=(...r)=>t.check(jT(...r)),t.nonempty=(...r)=>t.check(sd(1,...r)),t.lowercase=r=>t.check(sL(r)),t.uppercase=r=>t.check(aL(r)),t.trim=()=>t.check(lL()),t.normalize=(...r)=>t.check(uL(...r)),t.toLowerCase=()=>t.check(dL()),t.toUpperCase=()=>t.check(hL())}),KF=U("ZodString",(t,e)=>{Mg.init(t,e),kA.init(t,e),t.email=n=>t.check(kM(JF,n)),t.url=n=>t.check(NM(XF,n)),t.jwt=n=>t.check(qM(hB,n)),t.emoji=n=>t.check(PM(YF,n)),t.guid=n=>t.check(Mw(Ab,n)),t.uuid=n=>t.check(OM(Cu,n)),t.uuidv4=n=>t.check(CM(Cu,n)),t.uuidv6=n=>t.check(RM(Cu,n)),t.uuidv7=n=>t.check($M(Cu,n)),t.nanoid=n=>t.check(MM(QF,n)),t.guid=n=>t.check(Mw(Ab,n)),t.cuid=n=>t.check(LM(eB,n)),t.cuid2=n=>t.check(jM(tB,n)),t.ulid=n=>t.check(UM(nB,n)),t.base64=n=>t.check(ZM(uB,n)),t.base64url=n=>t.check(WM(lB,n)),t.xid=n=>t.check(DM(rB,n)),t.ksuid=n=>t.check(FM(sB,n)),t.ipv4=n=>t.check(BM(aB,n)),t.ipv6=n=>t.check(zM(iB,n)),t.cidrv4=n=>t.check(HM(oB,n)),t.cidrv6=n=>t.check(VM(cB,n)),t.e164=n=>t.check(GM(dB,n)),t.datetime=n=>t.check(jF(n)),t.date=n=>t.check(DF(n)),t.time=n=>t.check(BF(n)),t.duration=n=>t.check(HF(n))});function Ve(t){return xM(KF,t)}const bt=U("ZodStringFormat",(t,e)=>{_t.init(t,e),kA.init(t,e)}),JF=U("ZodEmail",(t,e)=>{j2.init(t,e),bt.init(t,e)}),Ab=U("ZodGUID",(t,e)=>{M2.init(t,e),bt.init(t,e)}),Cu=U("ZodUUID",(t,e)=>{L2.init(t,e),bt.init(t,e)}),XF=U("ZodURL",(t,e)=>{U2.init(t,e),bt.init(t,e)}),YF=U("ZodEmoji",(t,e)=>{D2.init(t,e),bt.init(t,e)}),QF=U("ZodNanoID",(t,e)=>{F2.init(t,e),bt.init(t,e)}),eB=U("ZodCUID",(t,e)=>{B2.init(t,e),bt.init(t,e)}),tB=U("ZodCUID2",(t,e)=>{z2.init(t,e),bt.init(t,e)}),nB=U("ZodULID",(t,e)=>{H2.init(t,e),bt.init(t,e)}),rB=U("ZodXID",(t,e)=>{V2.init(t,e),bt.init(t,e)}),sB=U("ZodKSUID",(t,e)=>{Z2.init(t,e),bt.init(t,e)}),aB=U("ZodIPv4",(t,e)=>{J2.init(t,e),bt.init(t,e)}),iB=U("ZodIPv6",(t,e)=>{X2.init(t,e),bt.init(t,e)}),oB=U("ZodCIDRv4",(t,e)=>{Y2.init(t,e),bt.init(t,e)}),cB=U("ZodCIDRv6",(t,e)=>{Q2.init(t,e),bt.init(t,e)}),uB=U("ZodBase64",(t,e)=>{eM.init(t,e),bt.init(t,e)}),lB=U("ZodBase64URL",(t,e)=>{nM.init(t,e),bt.init(t,e)}),dB=U("ZodE164",(t,e)=>{rM.init(t,e),bt.init(t,e)}),hB=U("ZodJWT",(t,e)=>{aM.init(t,e),bt.init(t,e)}),OA=U("ZodNumber",(t,e)=>{OT.init(t,e),yt.init(t,e),t.gt=(r,s)=>t.check(jw(r,s)),t.gte=(r,s)=>t.check(rf(r,s)),t.min=(r,s)=>t.check(rf(r,s)),t.lt=(r,s)=>t.check(Lw(r,s)),t.lte=(r,s)=>t.check(nf(r,s)),t.max=(r,s)=>t.check(nf(r,s)),t.int=r=>t.check(Ib(r)),t.safe=r=>t.check(Ib(r)),t.positive=r=>t.check(jw(0,r)),t.nonnegative=r=>t.check(rf(0,r)),t.negative=r=>t.check(Lw(0,r)),t.nonpositive=r=>t.check(nf(0,r)),t.multipleOf=(r,s)=>t.check(Uw(r,s)),t.step=(r,s)=>t.check(Uw(r,s)),t.finite=()=>t;const n=t._zod.bag;t.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),t.isFinite=!0,t.format=n.format??null});function st(t){return QM(OA,t)}const fB=U("ZodNumberFormat",(t,e)=>{iM.init(t,e),OA.init(t,e)});function Ib(t){return eL(fB,t)}const pB=U("ZodBoolean",(t,e)=>{oM.init(t,e),yt.init(t,e)});function mB(t){return tL(pB,t)}const gB=U("ZodAny",(t,e)=>{cM.init(t,e),yt.init(t,e)});function Ru(){return nL(gB)}const _B=U("ZodUnknown",(t,e)=>{CT.init(t,e),yt.init(t,e)});function yd(){return PT(_B)}const yB=U("ZodNever",(t,e)=>{RT.init(t,e),yt.init(t,e)});function wB(t){return MT(yB,t)}const bB=U("ZodArray",(t,e)=>{uM.init(t,e),yt.init(t,e),t.element=e.element,t.min=(n,r)=>t.check(sd(n,r)),t.nonempty=n=>t.check(sd(1,n)),t.max=(n,r)=>t.check(LT(n,r)),t.length=(n,r)=>t.check(jT(n,r)),t.unwrap=()=>t.element});function La(t,e){return fL(bB,t,e)}const vB=U("ZodObject",(t,e)=>{lM.init(t,e),yt.init(t,e),ft(t,"shape",()=>e.shape),t.keyof=()=>hh(Object.keys(t._zod.def.shape)),t.catchall=n=>t.clone({...t._zod.def,catchall:n}),t.passthrough=()=>t.clone({...t._zod.def,catchall:yd()}),t.loose=()=>t.clone({...t._zod.def,catchall:yd()}),t.strict=()=>t.clone({...t._zod.def,catchall:wB()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=n=>fT(t,n),t.merge=n=>FP(t,n),t.pick=n=>UP(t,n),t.omit=n=>DP(t,n),t.partial=(...n)=>pT(RA,t,n[0]),t.required=(...n)=>BP($A,t,n[0])});function Oe(t,e){const n={type:"object",get shape(){return Ng(this,"shape",{...t}),this.shape},...ye(e)};return new vB(n)}const CA=U("ZodUnion",(t,e)=>{$T.init(t,e),yt.init(t,e),t.options=e.options});function nu(t,e){return new CA({type:"union",options:t,...ye(e)})}const SB=U("ZodDiscriminatedUnion",(t,e)=>{CA.init(t,e),dM.init(t,e)});function dh(t,e,n){return new SB({type:"union",options:e,discriminator:t,...ye(n)})}const TB=U("ZodIntersection",(t,e)=>{hM.init(t,e),yt.init(t,e)});function EB(t,e){return new TB({type:"intersection",left:t,right:e})}const AB=U("ZodTuple",(t,e)=>{fM.init(t,e),yt.init(t,e),t.rest=n=>t.clone({...t._zod.def,rest:n})});function w_(t,e,n){const r=e instanceof at,s=r?n:e,a=r?e:null;return new AB({type:"tuple",items:t,rest:a,...ye(s)})}const IB=U("ZodRecord",(t,e)=>{pM.init(t,e),yt.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});function xB(t,e,n){return new IB({type:"record",keyType:t,valueType:e,...ye(n)})}const mm=U("ZodEnum",(t,e)=>{mM.init(t,e),yt.init(t,e),t.enum=e.entries,t.options=Object.values(e.entries);const n=new Set(Object.keys(e.entries));t.extract=(r,s)=>{const a={};for(const i of r)if(n.has(i))a[i]=e.entries[i];else throw new Error(`Key ${i} not found in enum`);return new mm({...e,checks:[],...ye(s),entries:a})},t.exclude=(r,s)=>{const a={...e.entries};for(const i of r)if(n.has(i))delete a[i];else throw new Error(`Key ${i} not found in enum`);return new mm({...e,checks:[],...ye(s),entries:a})}});function hh(t,e){const n=Array.isArray(t)?Object.fromEntries(t.map(r=>[r,r])):t;return new mm({type:"enum",entries:n,...ye(e)})}const kB=U("ZodLiteral",(t,e)=>{gM.init(t,e),yt.init(t,e),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});function Le(t,e){return new kB({type:"literal",values:Array.isArray(t)?t:[t],...ye(e)})}const OB=U("ZodTransform",(t,e)=>{_M.init(t,e),yt.init(t,e),t._zod.parse=(n,r)=>{n.addIssue=a=>{if(typeof a=="string")n.issues.push(mc(a,n.value,e));else{const i=a;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=n.value),i.inst??(i.inst=t),i.continue??(i.continue=!0),n.issues.push(mc(i))}};const s=e.transform(n.value,n);return s instanceof Promise?s.then(a=>(n.value=a,n)):(n.value=s,n)}});function CB(t){return new OB({type:"transform",transform:t})}const RA=U("ZodOptional",(t,e)=>{Lg.init(t,e),yt.init(t,e),t.unwrap=()=>t._zod.def.innerType});function xb(t){return new RA({type:"optional",innerType:t})}const RB=U("ZodNullable",(t,e)=>{yM.init(t,e),yt.init(t,e),t.unwrap=()=>t._zod.def.innerType});function kb(t){return new RB({type:"nullable",innerType:t})}const $B=U("ZodDefault",(t,e)=>{wM.init(t,e),yt.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function NB(t,e){return new $B({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}const PB=U("ZodPrefault",(t,e)=>{bM.init(t,e),yt.init(t,e),t.unwrap=()=>t._zod.def.innerType});function MB(t,e){return new PB({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}const $A=U("ZodNonOptional",(t,e)=>{vM.init(t,e),yt.init(t,e),t.unwrap=()=>t._zod.def.innerType});function LB(t,e){return new $A({type:"nonoptional",innerType:t,...ye(e)})}const jB=U("ZodCatch",(t,e)=>{SM.init(t,e),yt.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function UB(t,e){return new jB({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}const DB=U("ZodPipe",(t,e)=>{TM.init(t,e),yt.init(t,e),t.in=e.in,t.out=e.out});function Ob(t,e){return new DB({type:"pipe",in:t,out:e})}const FB=U("ZodReadonly",(t,e)=>{EM.init(t,e),yt.init(t,e)});function BB(t){return new FB({type:"readonly",innerType:t})}const NA=U("ZodCustom",(t,e)=>{AM.init(t,e),yt.init(t,e)});function zB(t){const e=new Mn({check:"custom"});return e._zod.check=t,e}function gm(t,e){return pL(NA,()=>!0,e)}function HB(t,e={}){return mL(NA,t,e)}function VB(t){const e=zB(n=>(n.addIssue=r=>{if(typeof r=="string")n.issues.push(mc(r,n.value,e._zod.def));else{const s=r;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=n.value),s.inst??(s.inst=e),s.continue??(s.continue=!e._zod.def.abort),n.issues.push(mc(s))}},t(n.value,n)));return e}var ZB=ue({BaseToolkit:()=>WB,DynamicStructuredTool:()=>LA,DynamicTool:()=>MA,StructuredTool:()=>fh,Tool:()=>PA,ToolInputParsingException:()=>Wl,isLangChainTool:()=>vs,isRunnableToolLike:()=>__,isStructuredTool:()=>g_,isStructuredToolParams:()=>y_,tool:()=>Rs}),fh=class extends t_{constructor(e){super(e??{});p(this,"extras");p(this,"returnDirect",!1);p(this,"verboseParsingErrors",!1);p(this,"responseFormat","content");p(this,"defaultConfig");this.verboseParsingErrors=(e==null?void 0:e.verboseParsingErrors)??this.verboseParsingErrors,this.responseFormat=(e==null?void 0:e.responseFormat)??this.responseFormat,this.defaultConfig=(e==null?void 0:e.defaultConfig)??this.defaultConfig,this.metadata=(e==null?void 0:e.metadata)??this.metadata,this.extras=(e==null?void 0:e.extras)??this.extras}get lc_namespace(){return["langchain","tools"]}async invoke(e,n){let r,s=Ge(sr(this.defaultConfig,n));return Jo(e)?(r=e.args,s={...s,toolCall:e}):r=e,this.call(r,s)}async call(e,n,r){const s=Jo(e)?e.args:e;let a;if(Lt(this.schema))try{a=await Yd(this.schema,s)}catch(m){let _="Received tool input did not match expected schema";throw this.verboseParsingErrors&&(_=`${_}
284
- Details: ${m.message}`),VT(m)&&(_=`${_}
285
-
286
- ${ZP(m)}`),new Wl(_,JSON.stringify(e))}else{const m=gt(s,this.schema);if(!m.valid){let _="Received tool input did not match expected schema";throw this.verboseParsingErrors&&(_=`${_}
287
- Details: ${m.errors.map(y=>`${y.keywordLocation}: ${y.error}`).join(`
288
- `)}`),new Wl(_,JSON.stringify(e))}a=s}const i=Vc(n),o=un.configure(i.callbacks,this.callbacks,i.tags||r,this.tags,i.metadata,this.metadata,{verbose:this.verbose});let c;Jo(e)&&(c=e.id),!c&&hC(i)&&(c=i.toolCall.id);const u=await(o==null?void 0:o.handleToolStart(this.toJSON(),typeof e=="string"?e:JSON.stringify(e),i.runId,void 0,void 0,void 0,i.runName,c));delete i.runId;let l;try{const m=await this._call(a,u,i);l=aE(m)?await T4(m,async _=>{try{await(u==null?void 0:u.handleToolEvent(_))}catch(y){await(u==null?void 0:u.handleToolError(y))}}):m}catch(m){throw await(u==null?void 0:u.handleToolError(m)),m}let d,f;if(this.responseFormat==="content_and_artifact")if(Array.isArray(l)&&l.length===2)[d,f]=l;else throw new Error(`Tool response format is "content_and_artifact" but the output was not a two-tuple.
289
- Result: ${JSON.stringify(l)}`);else d=l;const h=GB({content:d,artifact:f,toolCallId:c,name:this.name,metadata:this.metadata});return await(u==null?void 0:u.handleToolEnd(h)),h}},PA=class extends fh{constructor(e){super(e);p(this,"schema",br({input:zn().optional()}).transform(e=>e.input))}call(e,n){const r=typeof e=="string"||e==null?{input:e}:e;return super.call(r,n)}},MA=class extends PA{constructor(e){super(e);p(this,"name");p(this,"description");p(this,"func");this.name=e.name,this.description=e.description,this.func=e.func,this.returnDirect=e.returnDirect??this.returnDirect}static lc_name(){return"DynamicTool"}async call(e,n){const r=Vc(n);return r.runName===void 0&&(r.runName=this.name),super.call(e,r)}_call(e,n,r){return this.func(e,n,r)}},LA=class extends fh{constructor(e){super(e);p(this,"description");p(this,"func");p(this,"schema");this.name=e.name,this.description=e.description,this.func=e.func,this.returnDirect=e.returnDirect??this.returnDirect,this.schema=e.schema}static lc_name(){return"DynamicStructuredTool"}async call(e,n,r){const s=Vc(n);return s.runName===void 0&&(s.runName=this.name),super.call(e,s,r)}_call(e,n,r){return this.func(e,n,r)}},WB=class{getTools(){return this.tools}};function Rs(t,e){var i;const n=jg(e.schema),r=ec(e.schema);if(!e.schema||n||r)return new MA({...e,description:e.description??((i=e.schema)==null?void 0:i.description)??`${e.name} tool`,func:async(o,c,u)=>new Promise((l,d)=>{const f=et(u,{callbacks:c==null?void 0:c.getChild()});tn.runWithConfig(_s(f),async()=>{try{l(t(o,f))}catch(h){d(h)}})})});const s=e.schema,a=e.description??e.schema.description??`${e.name} tool`;return new LA({...e,description:a,schema:s,func:async(o,c,u)=>new Promise((l,d)=>{let f;const h=()=>{u!=null&&u.signal&&f&&u.signal.removeEventListener("abort",f)};u!=null&&u.signal&&(f=()=>{h(),d(dc(u.signal))},u.signal.addEventListener("abort",f,{once:!0}));const m=et(u,{callbacks:c==null?void 0:c.getChild()});tn.runWithConfig(_s(m),async()=>{var _;try{const y=await t(o,m);if(aE(y)){l(y);return}if((_=u==null?void 0:u.signal)!=null&&_.aborted){h();return}h(),l(y)}catch(y){h(),d(y)}})})})}function GB(t){const{content:e,artifact:n,toolCallId:r,metadata:s}=t;return r&&!lg(e)?typeof e=="string"||Array.isArray(e)&&e.every(a=>typeof a=="object")?new Rn({status:"success",content:e,artifact:n,tool_call_id:r,name:t.name,metadata:s}):new Rn({status:"success",content:qB(e),artifact:n,tool_call_id:r,name:t.name,metadata:s}):e}function qB(t){try{return JSON.stringify(t)??""}catch{return`${t}`}}var KB=ue({RunCollectorCallbackHandler:()=>JB}),JB=class extends Ss{constructor({exampleId:e}={}){super({_awaitHandler:!0});p(this,"name","run_collector");p(this,"exampleId");p(this,"tracedRuns");this.exampleId=e,this.tracedRuns=[]}async persistRun(e){const n={...e};n.reference_example_id=this.exampleId,this.tracedRuns.push(n)}},XB=ue({}),YB=ue({chunkArray:()=>QB});const QB=(t,e)=>t.reduce((n,r,s)=>{const a=Math.floor(s/e);return n[a]=(n[a]||[]).concat([r]),n},[]);var e6=ue({context:()=>t6});function t6(t,...e){const n=t.raw;let r="";for(let s=0;s<n.length;s++){const a=n[s].replace(/\\\n[ \t]*/g,"").replace(/\\`/g,"`").replace(/\\\$/g,"$").replace(/\\\{/g,"{");if(r+=a,s<e.length){const i=n6(e[s],r);r+=typeof i=="string"?i:JSON.stringify(i)}}return r=r6(r),r=r.trim(),r=r.replace(/\\n/g,`
290
- `),r}function n6(t,e){if(typeof t!="string"||!t.includes(`
291
- `))return t;const n=e.slice(e.lastIndexOf(`
292
- `)+1).match(/^(\s+)/);if(n){const r=n[1];return t.replace(/\n/g,`
293
- ${r}`)}return t}function r6(t){const e=t.split(`
294
- `);let n=null;for(const r of e){const s=r.match(/^(\s+)\S+/);if(s){const a=s[1].length;n===null?n=a:n=Math.min(n,a)}}return n===null?t:e.map(r=>r[0]===" "||r[0]===" "?r.slice(n):r).join(`
295
- `)}var s6=ue({EventStreamContentType:()=>a6,convertEventStreamToIterableReadableDataStream:()=>o6,getBytes:()=>jA,getLines:()=>UA,getMessages:()=>DA});const a6="text/event-stream";async function jA(t,e){if(t instanceof ReadableStream){const n=t.getReader();for(;;){const r=await n.read();if(r.done){e(new Uint8Array,!0);break}e(r.value)}}else try{for await(const n of t)e(new Uint8Array(n));e(new Uint8Array,!0)}catch(n){throw new Error(["Parsing event source stream failed.","Ensure your implementation of fetch returns a web or Node readable stream.",`Error: ${n.message}`].join(`
296
- `))}}var _i=function(t){return t[t.NewLine=10]="NewLine",t[t.CarriageReturn=13]="CarriageReturn",t[t.Space=32]="Space",t[t.Colon=58]="Colon",t}(_i||{});function UA(t){let e,n,r,s=!1;return function(i,o){if(o){t(i,0,!0);return}e===void 0?(e=i,n=0,r=-1):e=i6(e,i);const c=e.length;let u=0;for(;n<c;){s&&(e[n]===_i.NewLine&&(u=++n),s=!1);let l=-1;for(;n<c&&l===-1;++n)switch(e[n]){case _i.Colon:r===-1&&(r=n-u);break;case _i.CarriageReturn:s=!0;case _i.NewLine:l=n;break}if(l===-1)break;t(e.subarray(u,l),r),u=n,r=-1}u===c?e=void 0:u!==0&&(e=e.subarray(u),n-=u)}}function DA(t,e,n){let r=Ef();const s=new TextDecoder;return function(i,o,c){if(c){c6(r)||(t==null||t(r),r=Ef());return}if(i.length===0)t==null||t(r),r=Ef();else if(o>0){const u=s.decode(i.subarray(0,o)),l=o+(i[o+1]===_i.Space?2:1),d=s.decode(i.subarray(l));switch(u){case"data":r.data=r.data?r.data+`
297
- `+d:d;break;case"event":r.event=d;break;case"id":e==null||e(r.id=d);break;case"retry":{const f=parseInt(d,10);Number.isNaN(f)||n==null||n(r.retry=f);break}}}}}function i6(t,e){const n=new Uint8Array(t.length+e.length);return n.set(t),n.set(e,t.length),n}function Ef(){return{data:"",event:"",id:"",retry:void 0}}function o6(t,e){const n=new ReadableStream({async start(r){const s=DA(i=>{if(i.event==="error")throw new Error(i.data??"Unspecified event streaming error.");i.event==="metadata"?e==null||e(i):i.data&&r.enqueue(i.data)});await jA(t,UA((i,o,c)=>{s(i,o,c),c&&r.close()}))}});return $n.fromReadableStream(n)}function c6(t){return t.data===""&&t.event===""&&t.id===""&&t.retry===void 0}var u6=ue({}),l6=ue({convertToOpenAIFunction:()=>FA,convertToOpenAITool:()=>wd,isLangChainTool:()=>vs,isRunnableToolLike:()=>__,isStructuredTool:()=>g_,isStructuredToolParams:()=>y_});function FA(t,e){const n=typeof e=="number"?void 0:e;return{name:t.name,description:t.description,parameters:lt(t.schema),...(n==null?void 0:n.strict)!==void 0?{strict:n.strict}:{}}}function wd(t,e){const n=typeof e=="number"?void 0:e;let r;return vs(t)?r={type:"function",function:FA(t)}:r=t,(n==null?void 0:n.strict)!==void 0&&(r.function.strict=n.strict),r}function BA(t,e){let n=0,r=0,s=0;for(let a=0;a<t.length;a++)n+=t[a]*e[a],r+=t[a]*t[a],s+=e[a]*e[a];return n/(Math.sqrt(r)*Math.sqrt(s))}function d6(t,e){let n=0;for(let r=0;r<t.length;r++)n+=t[r]*e[r];return n}function h6(t,e){let n=0;for(let r=0;r<t.length;r++)n+=(t[r]-e[r])*(t[r]-e[r]);return n}function f6(t,e){return Math.sqrt(h6(t,e))}var p6=ue({cosineSimilarity:()=>_m,euclideanDistance:()=>_6,innerProduct:()=>g6,matrixFunc:()=>ph,maximalMarginalRelevance:()=>y6,normalize:()=>m6});function ph(t,e,n){if(t.length===0||t[0].length===0||e.length===0||e[0].length===0)return[[]];if(t[0].length!==e[0].length)throw new Error(`Number of columns in X and Y must be the same. X has shape ${[t.length,t[0].length]} and Y has shape ${[e.length,e[0].length]}.`);return t.map(r=>e.map(s=>n(r,s)).map(s=>Number.isNaN(s)?0:s))}function m6(t,e=!1){const n=w6(t);return t.map(r=>r.map(s=>e?1-s/n:s/n))}function _m(t,e){return ph(t,e,BA)}function g6(t,e){return ph(t,e,d6)}function _6(t,e){return ph(t,e,f6)}function y6(t,e,n=.5,r=4){if(Math.min(r,e.length)<=0)return[];const s=_m(Array.isArray(t[0])?t:[t],e)[0],a=zA(s).maxIndex,i=[e[a]],o=[a];for(;o.length<Math.min(r,e.length);){let c=-1/0,u=-1;const l=_m(e,i);s.forEach((d,f)=>{if(o.includes(f))return;const h=Math.max(...l[f]),m=n*d-(1-n)*h;m>c&&(c=m,u=f)}),i.push(e[u]),o.push(u)}return o}function zA(t){if(t.length===0)return{maxIndex:-1,maxValue:NaN};let e=t[0],n=0;for(let r=1;r<t.length;r+=1)t[r]>e&&(n=r,e=t[r]);return{maxIndex:n,maxValue:e}}function w6(t){return t.reduce((e,n)=>Math.max(e,zA(n).maxValue),0)}var b6=ue({isCloudMetadata:()=>ym,isLocalhost:()=>wm,isPrivateIp:()=>GA,isSafeUrl:()=>k6,isSameOrigin:()=>O6,validateSafeUrl:()=>qA});const v6=["10.0.0.0/8","172.16.0.0/12","192.168.0.0/16","127.0.0.0/8","169.254.0.0/16","0.0.0.0/8","::1/128","fc00::/7","fe80::/10","ff00::/8"],S6=["169.254.169.254","169.254.170.2","100.100.100.200"],T6=["metadata.google.internal","metadata","instance-data"],E6=["localhost","localhost.localdomain"],A6=/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/;function HA(t){return A6.test(t)}function mh(t){return WA(t)!==null}function VA(t){return HA(t)||mh(t)}function ZA(t){if(HA(t))return t.split(".").map(e=>parseInt(e,10));if(mh(t)){const e=WA(t);if(!e)return null;const n=e.split(":"),r=[];for(const s of n)r.push(parseInt(s,16));return r}return null}function WA(t){if(!t||typeof t!="string"||!t.includes(":")||!/^[0-9a-fA-F:]+$/.test(t))return null;let e=t;if(e.includes("::")){const r=e.split("::");if(r.length>2)return null;const[s,a]=r,i=s?s.split(":"):[],o=a?a.split(":"):[],c=8-(i.length+o.length);if(c<0)return null;const u=Array(c).fill("0");e=[...i,...u,...o].filter(l=>l!=="").join(":")}const n=e.split(":");if(n.length!==8)return null;for(const r of n)if(r.length===0||r.length>4||!/^[0-9a-fA-F]+$/.test(r))return null;return n.map(r=>r.padStart(4,"0").toLowerCase()).join(":")}function I6(t){const[e,n]=t.split("/");if(!e||!n)return null;const r=ZA(e);if(!r)return null;const s=parseInt(n,10);if(isNaN(s))return null;const a=mh(e);return a&&s>128||!a&&s>32?null:{addr:r,prefixLen:s,isIpv6:a}}function x6(t,e){const n=ZA(t);if(!n)return!1;const r=I6(e);if(!r)return!1;const s=mh(t);if(s!==r.isIpv6)return!1;const{addr:a,prefixLen:i}=r;if(s)for(let o=0;o<Math.ceil(i/16);o++){const c=65535<<16-Math.min(16,i-o*16)&65535;if((n[o]&c)!==(a[o]&c))return!1}else for(let o=0;o<Math.ceil(i/8);o++){const c=255<<8-Math.min(8,i-o*8)&255;if((n[o]&c)!==(a[o]&c))return!1}return!0}function GA(t){if(!VA(t))return!1;for(const e of v6)if(x6(t,e))return!0;return!1}function ym(t,e){if(S6.includes(e||""))return!0;const n=t.toLowerCase();return!!T6.includes(n)}function wm(t,e){if(e&&(e==="127.0.0.1"||e==="::1"||e==="0.0.0.0"||e.startsWith("127.")))return!0;const n=t.toLowerCase();return!!E6.includes(n)}function qA(t,e){const n=(e==null?void 0:e.allowPrivate)??!1,r=(e==null?void 0:e.allowHttp)??!1;try{let s;try{s=new URL(t)}catch{throw new Error(`Invalid URL: ${t}`)}const a=s.hostname;if(!a)throw new Error("URL missing hostname.");if(ym(a))throw new Error(`URL points to cloud metadata endpoint: ${a}`);if(wm(a)){if(!n)throw new Error(`URL points to localhost: ${a}`);return t}const i=s.protocol;if(i!=="http:"&&i!=="https:")throw new Error(`Invalid URL scheme: ${i}. Only http and https are allowed.`);if(i==="http:"&&!r)throw new Error("HTTP scheme not allowed. Use HTTPS or set allowHttp: true.");if(VA(a)){const o=a;if(wm(a,o)){if(!n)throw new Error(`URL points to localhost: ${a}`);return t}if(ym(a,o))throw new Error(`URL resolves to cloud metadata IP: ${o} (${a})`);if(GA(o)&&!n)throw new Error(`URL resolves to private IP: ${o} (${a}). Set allowPrivate: true to allow.`);return t}return t}catch(s){throw s&&typeof s=="object"&&"message"in s?s:new Error(`URL validation failed: ${s}`)}}function k6(t,e){try{return qA(t,e),!0}catch{return!1}}function O6(t,e){try{return new URL(t).origin===new URL(e).origin}catch{return!1}}var C6=ue({SaveableVectorStore:()=>R6,VectorStore:()=>b_,VectorStoreRetriever:()=>El}),El=class extends d_{constructor(e){super(e);p(this,"vectorStore");p(this,"k",4);p(this,"searchType","similarity");p(this,"searchKwargs");p(this,"filter");this.vectorStore=e.vectorStore,this.k=e.k??this.k,this.searchType=e.searchType??this.searchType,this.filter=e.filter,e.searchType==="mmr"&&(this.searchKwargs=e.searchKwargs)}static lc_name(){return"VectorStoreRetriever"}get lc_namespace(){return["langchain_core","vectorstores"]}_vectorstoreType(){return this.vectorStore._vectorstoreType()}async _getRelevantDocuments(e,n){if(this.searchType==="mmr"){if(typeof this.vectorStore.maxMarginalRelevanceSearch!="function")throw new Error(`The vector store backing this retriever, ${this._vectorstoreType()} does not support max marginal relevance search.`);return this.vectorStore.maxMarginalRelevanceSearch(e,{k:this.k,filter:this.filter,...this.searchKwargs},n==null?void 0:n.getChild("vectorstore"))}return this.vectorStore.similaritySearch(e,this.k,this.filter,n==null?void 0:n.getChild("vectorstore"))}async addDocuments(e,n){return this.vectorStore.addDocuments(e,n)}},b_=class extends ar{constructor(e,n){super(n);p(this,"lc_namespace",["langchain","vectorstores",this._vectorstoreType()]);p(this,"embeddings");this.embeddings=e}async delete(e){throw new Error("Not implemented.")}async similaritySearch(e,n=4,r=void 0,s=void 0){return(await this.similaritySearchVectorWithScore(await this.embeddings.embedQuery(e),n,r)).map(a=>a[0])}async similaritySearchWithScore(e,n=4,r=void 0,s=void 0){return this.similaritySearchVectorWithScore(await this.embeddings.embedQuery(e),n,r)}static fromTexts(e,n,r,s){throw new Error("the Langchain vectorstore implementation you are using forgot to override this, please report a bug")}static fromDocuments(e,n,r){throw new Error("the Langchain vectorstore implementation you are using forgot to override this, please report a bug")}asRetriever(e,n,r,s,a,i){if(typeof e=="number")return new El({vectorStore:this,k:e,filter:n,tags:[...s??[],this._vectorstoreType()],metadata:a,verbose:i,callbacks:r});{const o={vectorStore:this,k:e==null?void 0:e.k,filter:e==null?void 0:e.filter,tags:[...(e==null?void 0:e.tags)??[],this._vectorstoreType()],metadata:e==null?void 0:e.metadata,verbose:e==null?void 0:e.verbose,callbacks:e==null?void 0:e.callbacks,searchType:e==null?void 0:e.searchType};return(e==null?void 0:e.searchType)==="mmr"?new El({...o,searchKwargs:e.searchKwargs}):new El({...o})}}},R6=class extends b_{static load(t,e){throw new Error("Not implemented")}},$6=class extends Jr{_combineLLMOutput(){return[]}_llmType(){return"fake"}async _generate(t,e,n){var s;if((s=e==null?void 0:e.stop)!=null&&s.length)return{generations:[{message:new De(e.stop[0]),text:e.stop[0]}]};const r=t.map(a=>typeof a.content=="string"?a.content:JSON.stringify(a.content,null,2)).join(`
298
- `);return await(n==null?void 0:n.handleLLMNewToken(r)),{generations:[{message:new De(r),text:r}],llmOutput:{}}}},N6=class KA extends Jr{constructor({sleep:n=50,responses:r=[],chunks:s=[],toolStyle:a="openai",thrownErrorString:i,...o}){super(o);p(this,"sleep",50);p(this,"responses",[]);p(this,"chunks",[]);p(this,"toolStyle","openai");p(this,"thrownErrorString");p(this,"tools",[]);this.sleep=n,this.responses=r,this.chunks=s,this.toolStyle=a,this.thrownErrorString=i}_llmType(){return"fake"}bindTools(n){const r=[...this.tools,...n],s=r.map(o=>{switch(this.toolStyle){case"openai":return{type:"function",function:{name:o.name,description:o.description,parameters:lt(o.schema)}};case"anthropic":return{name:o.name,description:o.description,input_schema:lt(o.schema)};case"bedrock":return{toolSpec:{name:o.name,description:o.description,inputSchema:lt(o.schema)}};case"google":return{name:o.name,description:o.description,parameters:lt(o.schema)};default:throw new Error(`Unsupported tool style: ${this.toolStyle}`)}}),a=this.toolStyle==="google"?[{functionDeclarations:s}]:s,i=new KA({sleep:this.sleep,responses:this.responses,chunks:this.chunks,toolStyle:this.toolStyle,thrownErrorString:this.thrownErrorString});return i.tools=r,i.withConfig({tools:a})}async _generate(n,r,s){var a,i,o,c;if(this.thrownErrorString)throw new Error(this.thrownErrorString);return{generations:[{text:"",message:new De({content:((i=(a=this.responses)==null?void 0:a[0])==null?void 0:i.content)??n[0].content??"",tool_calls:(c=(o=this.chunks)==null?void 0:o[0])==null?void 0:c.tool_calls})}]}}async*_streamResponseChunks(n,r,s){var o,c,u,l,d;if(this.thrownErrorString)throw new Error(this.thrownErrorString);if((o=this.chunks)!=null&&o.length){for(const f of this.chunks){const h=new qn({message:new Qe({content:f.content,tool_calls:f.tool_calls,additional_kwargs:f.additional_kwargs??{}}),text:((c=f.content)==null?void 0:c.toString())??""});if((u=r.signal)!=null&&u.aborted)break;yield h,await(s==null?void 0:s.handleLLMNewToken(f.content,void 0,void 0,void 0,void 0,{chunk:h}))}return}const a=((l=this.responses)==null?void 0:l[0])??new De(typeof n[0].content=="string"?n[0].content:""),i=typeof a.content=="string"?a.content:"";for(const f of i){await new Promise(m=>setTimeout(m,this.sleep));const h=new qn({message:new Qe({content:f}),text:f});if((d=r.signal)!=null&&d.aborted)break;yield h,await(s==null?void 0:s.handleLLMNewToken(f,void 0,void 0,void 0,void 0,{chunk:h}))}}},P6=class JA extends Jr{constructor(n){super(n);p(this,"lc_serializable",!0);p(this,"responses");p(this,"i",0);p(this,"sleep");p(this,"emitCustomEvent",!1);p(this,"generationInfo");p(this,"tools",[]);p(this,"toolStyle","openai");const{responses:r,sleep:s,emitCustomEvent:a,generationInfo:i}=n;this.responses=r,this.sleep=s,this.emitCustomEvent=a??this.emitCustomEvent,this.generationInfo=i}static lc_name(){return"FakeListChatModel"}_combineLLMOutput(){return[]}_llmType(){return"fake-list"}async _generate(n,r,s){var a;if(await this._sleepIfRequested(),r!=null&&r.thrownErrorString)throw new Error(r.thrownErrorString);if(this.emitCustomEvent&&await(s==null?void 0:s.handleCustomEvent("some_test_event",{someval:!0})),(a=r==null?void 0:r.stop)!=null&&a.length)return{generations:[this._formatGeneration(r.stop[0])]};{const i=this._currentResponse();return this._incrementResponse(),{generations:[this._formatGeneration(i)],llmOutput:{}}}}_formatGeneration(n){return{message:new De(n),text:n}}async*_streamResponseChunks(n,r,s){var o;const a=this._currentResponse();this._incrementResponse(),this.emitCustomEvent&&await(s==null?void 0:s.handleCustomEvent("some_test_event",{someval:!0}));const i=[...a];for(let c=0;c<i.length;c++){const u=i[c],l=c===i.length-1;if(await this._sleepIfRequested(),r!=null&&r.thrownErrorString)throw new Error(r.thrownErrorString);const d=this._createResponseChunk(u,l?this.generationInfo:void 0);if((o=r.signal)!=null&&o.aborted)break;yield d,s==null||s.handleLLMNewToken(u)}}async _sleepIfRequested(){this.sleep!==void 0&&await this._sleep()}async _sleep(){return new Promise(n=>{setTimeout(()=>n(),this.sleep)})}_createResponseChunk(n,r){return new qn({message:new Qe({content:n}),text:n,generationInfo:r})}_currentResponse(){return this.responses[this.i]}_incrementResponse(){this.i<this.responses.length-1?this.i+=1:this.i=0}bindTools(n){const r=[...this.tools,...n],s=r.map(o=>{switch(this.toolStyle){case"openai":return{type:"function",function:{name:o.name,description:o.description,parameters:lt(o.schema)}};case"anthropic":return{name:o.name,description:o.description,input_schema:lt(o.schema)};case"bedrock":return{toolSpec:{name:o.name,description:o.description,inputSchema:lt(o.schema)}};case"google":return{name:o.name,description:o.description,parameters:lt(o.schema)};default:throw new Error(`Unsupported tool style: ${this.toolStyle}`)}}),a=this.toolStyle==="google"?[{functionDeclarations:s}]:s,i=new JA({responses:this.responses,sleep:this.sleep,emitCustomEvent:this.emitCustomEvent,generationInfo:this.generationInfo});return i.tools=r,i.toolStyle=this.toolStyle,i.i=this.i,i.withConfig({tools:a})}withStructuredOutput(n,r){return Ht.from(async s=>{var i,o;const a=await this.invoke(s);if((o=(i=a.tool_calls)==null?void 0:i[0])!=null&&o.args)return a.tool_calls[0].args;if(typeof a.content=="string")return JSON.parse(a.content);throw new Error("No structured output found")})}},M6=class extends Jg{constructor(e){super(e??{});p(this,"vectorSize");this.vectorSize=(e==null?void 0:e.vectorSize)??4}async embedDocuments(e){return Promise.all(e.map(n=>this.embedQuery(n)))}async embedQuery(e){let n=e;n=n.toLowerCase().replaceAll(/[^a-z ]/g,"");const r=n.length%this.vectorSize,s=r===0?0:this.vectorSize-r,a=n.length+s;n=n.padEnd(a," ");const i=n.length/this.vectorSize,o=[];for(let c=0;c<n.length;c+=i)o.push(n.slice(c,c+i));return o.map(c=>{let u=0;for(let l=0;l<c.length;l+=1)u+=c===" "?0:c.charCodeAt(l);return u%26/26})}},L6=class extends Jg{constructor(t){super(t??{})}embedDocuments(t){return Promise.resolve(t.map(()=>[.1,.2,.3,.4]))}embedQuery(t){return Promise.resolve([.1,.2,.3,.4])}},j6=class extends a_{constructor(e){super(e);p(this,"response");p(this,"thrownErrorString");this.response=e.response,this.thrownErrorString=e.thrownErrorString}_llmType(){return"fake"}async _call(e,n,r){if(this.thrownErrorString)throw new Error(this.thrownErrorString);const s=this.response??e;return await(r==null?void 0:r.handleLLMNewToken(s)),s}},U6=class extends a_{constructor(e){super(e);p(this,"sleep",50);p(this,"responses");p(this,"thrownErrorString");this.sleep=e.sleep??this.sleep,this.responses=e.responses,this.thrownErrorString=e.thrownErrorString}_llmType(){return"fake"}async _call(e){var r,s;if(this.thrownErrorString)throw new Error(this.thrownErrorString);const n=(r=this.responses)==null?void 0:r[0];return this.responses=(s=this.responses)==null?void 0:s.slice(1),n??e}async*_streamResponseChunks(e,n,r){var a,i;if(this.thrownErrorString)throw new Error(this.thrownErrorString);const s=(a=this.responses)==null?void 0:a[0];this.responses=(i=this.responses)==null?void 0:i.slice(1);for(const o of s??e)await new Promise(c=>setTimeout(c,this.sleep)),yield{text:o,generationInfo:{}},await(r==null?void 0:r.handleLLMNewToken(o))}},D6=class extends AE{constructor(){super();p(this,"lc_namespace",["langchain_core","message","fake"]);p(this,"messages",[])}async getMessages(){return this.messages}async addMessage(e){this.messages.push(e)}async addUserMessage(e){this.messages.push(new vn(e))}async addAIMessage(e){this.messages.push(new De(e))}async clear(){this.messages=[]}},F6=class extends Kg{constructor(){super();p(this,"lc_namespace",["langchain_core","message","fake"]);p(this,"messages",[])}async addMessage(e){this.messages.push(e)}async getMessages(){return this.messages}},B6=class extends Ss{constructor(){super();p(this,"name","fake_tracer");p(this,"runs",[])}persistRun(e){return this.runs.push(e),Promise.resolve()}},z6=class extends Ki{constructor(){super(...arguments);p(this,"lc_namespace",["tests","fake"])}getFormatInstructions(){return""}async parse(e){return e.split(",").map(n=>n.trim())}},H6=class extends d_{constructor(e){super();p(this,"lc_namespace",["test","fake"]);p(this,"output",[new Zs({pageContent:"foo"}),new Zs({pageContent:"bar"})]);this.output=(e==null?void 0:e.output)??this.output}async _getRelevantDocuments(e){return this.output}},V6=class extends Fe{constructor(e){super(e);p(this,"lc_namespace",["tests","fake"]);p(this,"returnOptions");this.returnOptions=e.returnOptions}async invoke(e,n){return this.returnOptions?n??{}:{input:e}}},Z6=class extends fh{constructor(e){super(e);p(this,"name");p(this,"description");p(this,"schema");this.name=e.name,this.description=e.description,this.schema=e.schema}async _call(e,n){return JSON.stringify(e)}},W6=class extends Ss{constructor(){super();p(this,"runPromiseResolver");p(this,"runPromise");p(this,"name","single_run_extractor");this.runPromise=new Promise(e=>{this.runPromiseResolver=e})}async persistRun(e){this.runPromiseResolver(e)}async extract(){return this.runPromise}},G6=class XA extends b_{constructor(n,{similarity:r,...s}={}){super(n,s);p(this,"memoryVectors",[]);p(this,"similarity");this.similarity=r??BA}_vectorstoreType(){return"memory"}async addDocuments(n){const r=n.map(({pageContent:s})=>s);return this.addVectors(await this.embeddings.embedDocuments(r),n)}async addVectors(n,r){const s=n.map((a,i)=>({content:r[i].pageContent,embedding:a,metadata:r[i].metadata}));this.memoryVectors=this.memoryVectors.concat(s)}async similaritySearchVectorWithScore(n,r,s){const a=o=>s?s(new Zs({metadata:o.metadata,pageContent:o.content})):!0,i=this.memoryVectors.filter(a);return i.map((o,c)=>({similarity:this.similarity(n,o.embedding),index:c})).sort((o,c)=>o.similarity>c.similarity?-1:0).slice(0,r).map(o=>[new Zs({metadata:i[o.index].metadata,pageContent:i[o.index].content}),o.similarity])}static async fromTexts(n,r,s,a){const i=[];for(let o=0;o<n.length;o+=1){const c=Array.isArray(r)?r[o]:r,u=new Zs({pageContent:n[o],metadata:c});i.push(u)}return XA.fromDocuments(i,s,a)}static async fromDocuments(n,r,s){const a=new this(r,s);return await a.addDocuments(n),a}static async fromExistingIndex(n,r){return new this(n,r)}},q6=ue({FakeChatMessageHistory:()=>D6,FakeChatModel:()=>$6,FakeEmbeddings:()=>L6,FakeLLM:()=>j6,FakeListChatMessageHistory:()=>F6,FakeListChatModel:()=>P6,FakeRetriever:()=>H6,FakeRunnable:()=>V6,FakeSplitIntoListParser:()=>z6,FakeStreamingChatModel:()=>N6,FakeStreamingLLM:()=>U6,FakeTool:()=>Z6,FakeTracer:()=>B6,FakeVectorStore:()=>G6,SingleRunExtractor:()=>W6,SyntheticEmbeddings:()=>M6}),K6=ue({agents:()=>IU,caches:()=>OU,callbacks__base:()=>V1,callbacks__manager:()=>QN,callbacks__promises:()=>KN,chat_history:()=>NU,document_loaders__base:()=>jU,document_loaders__langsmith:()=>UU,documents:()=>LU,embeddings:()=>BU,errors:()=>dC,example_selectors:()=>GU,index:()=>AU,indexing:()=>JU,language_models__base:()=>mD,language_models__chat_models:()=>MD,language_models__llms:()=>jD,language_models__profile:()=>UD,language_models__structured_output:()=>ND,load__serializable:()=>CC,memory:()=>DD,messages:()=>D4,messages__tool:()=>YC,output_parsers:()=>RD,output_parsers__openai_functions:()=>ZD,output_parsers__openai_tools:()=>WD,outputs:()=>gP,prompt_values:()=>XU,prompts:()=>wF,retrievers:()=>SF,retrievers__document_compressors:()=>bF,runnables:()=>B4,runnables__graph:()=>y4,singletons:()=>nP,stores:()=>TF,structured_query:()=>CF,testing:()=>MF,tools:()=>ZB,tracers__base:()=>PN,tracers__console:()=>jN,tracers__log_stream:()=>pP,tracers__run_collector:()=>KB,tracers__tracer_langchain:()=>HN,types__stream:()=>XB,utils__async_caller:()=>xP,utils__chunk_array:()=>YB,utils__context:()=>e6,utils__env:()=>H1,utils__event_source_parse:()=>s6,utils__format:()=>u6,utils__function_calling:()=>l6,utils__hash:()=>kU,utils__json_patch:()=>wD,utils__json_schema:()=>_4,utils__math:()=>p6,utils__ssrf:()=>b6,utils__standard_schema:()=>Fj,utils__stream:()=>iP,utils__testing:()=>q6,utils__tiktoken:()=>fD,utils__types:()=>$D,utils__uuid:()=>z1,vectorstores:()=>C6});const J6=50;function X6(t){const e={};for(let n=t;n&&n.prototype;n=Object.getPrototypeOf(n))Object.assign(e,Reflect.get(n.prototype,"lc_aliases"));return Object.entries(e).reduce((n,[r,s])=>(n[s]=r,n),{})}async function Al(t){const{optionalImportsMap:e,optionalImportEntrypoints:n,importMap:r,secretsMap:s,secretsFromEnv:a,path:i,depth:o,maxDepth:c}=this,u=i.join(".");if(o>c)throw new Error(`Maximum recursion depth (${c}) exceeded during deserialization. This may indicate a malicious payload or you may need to increase maxDepth.`);if(typeof t!="object"||t==null)return t;if(Array.isArray(t))return Promise.all(t.map((f,h)=>Al.call({...this,path:[...i,`${h}`],depth:o+1},f)));const l=t;if(K0(l))return yp(l);if("lc"in l&&"type"in l&&"id"in l&&l.lc===1&&l.type==="secret"){const[f]=l.id;if(f in s)return s[f];if(a){const h=It(f);if(h)return h}throw new Error(`Missing secret "${f}" at ${u}`)}if("lc"in l&&"type"in l&&"id"in l&&l.lc===1&&l.type==="not_implemented"){const f=JSON.stringify(l);throw new Error(`Trying to load an object that doesn't implement serialization: ${u} -> ${f}`)}if("lc"in l&&"type"in l&&"id"in l&&"kwargs"in l&&l.lc===1&&l.type==="constructor"){const f=l,h=JSON.stringify(f),[m,..._]=f.id.slice().reverse(),y=_.reverse(),w={langchain_core:K6,langchain:r};let g=null;const b=[y.join("/")];y[0]==="langchain_community"&&b.push(["langchain",...y.slice(1)].join("/"));const S=b.find(x=>x in e);if(EU.concat(n).includes(y.join("/"))||S)if(S!==void 0)g=await e[S];else throw new Error(`Missing key "${y.join("/")}" for ${u} in load(optionalImportsMap={})`);else{let x;if(y[0]==="langchain"||y[0]==="langchain_core")x=w[y[0]],y.shift();else throw new Error(`Invalid namespace: ${u} -> ${h}`);if(y.length===0)throw new Error(`Invalid namespace: ${u} -> ${h}`);let A;do{if(A=y.join("__"),A in x)break;y.pop()}while(y.length>0);A in x&&(g=x[A])}if(typeof g!="object"||g===null)throw new Error(`Invalid namespace: ${u} -> ${h}`);const I=g[m]??Object.values(g).find(x=>typeof x=="function"&&Hd(x)===m);if(typeof I!="function")throw new Error(`Invalid identifer: ${u} -> ${h}`);const T=new I(G0(await Al.call({...this,path:[...i,"kwargs"],depth:o+1},f.kwargs),AC,X6(I)));return Object.defineProperty(T.constructor,"name",{value:m}),T}const d={};for(const[f,h]of Object.entries(l))d[f]=await Al.call({...this,path:[...i,f],depth:o+1},h);return d}async function Y6(t,e){const n=JSON.parse(t),r={optionalImportsMap:{},optionalImportEntrypoints:[],secretsMap:{},secretsFromEnv:!1,importMap:{},path:["$"],depth:0,maxDepth:J6};return Al.call(r,n)}function Q6(t){return t!==null&&t.lc===1&&t.type==="constructor"&&Array.isArray(t.id)}async function bm(t){if(t&&typeof t=="object"){if(Array.isArray(t))return await Promise.all(t.map(e=>bm(e)));{const e={};for(const[n,r]of Object.entries(t))e[n]=await bm(r);if(e.lc===2&&e.type==="undefined")return;if(e.lc===2&&e.type==="constructor"&&Array.isArray(e.id))try{const n=e.id[e.id.length-1];let r;switch(n){case"Set":r=Set;break;case"Map":r=Map;break;case"RegExp":r=RegExp;break;case"Error":r=Error;break;case"Uint8Array":r=Uint8Array;break;default:return e}return e.method?r[e.method](...e.args||[]):new r(...e.args||[])}catch{return e}else if(Q6(e))return Y6(JSON.stringify(e));return e}}return t}function $u(t,e,n,r){return{lc:2,type:"constructor",id:[t.name],method:e??null,args:n??[],kwargs:r??{}}}function e3(t){return t===void 0?{lc:2,type:"undefined"}:t instanceof Set||t instanceof Map?$u(t.constructor,void 0,[Array.from(t)]):t instanceof RegExp?$u(RegExp,void 0,[t.source,t.flags]):t instanceof Error?$u(t.constructor,void 0,[t.message]):(t==null?void 0:t.lg_name)==="Send"?{node:t.node,args:t.args}:t instanceof Uint8Array?$u(Uint8Array,"from",[Array.from(t)]):t}var t3=class{_dumps(t){return new TextEncoder().encode(SU(t,(e,n)=>e3(n)))}async dumpsTyped(t){return t instanceof Uint8Array?["bytes",t]:["json",this._dumps(t)]}async _loads(t){return bm(JSON.parse(t))}async loadsTyped(t,e){if(t==="bytes")return typeof e=="string"?new TextEncoder().encode(e):e;if(t==="json")return this._loads(typeof e=="string"?e:new TextDecoder().decode(e));throw new Error(`Unknown serialization type: ${t}`)}};function YA(t){if(typeof t!="object"||t===null)return t;const e=Array.isArray(t)?[]:{};for(const n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=YA(t[n]));return e}function QA(){return{v:4,id:bE(-2),ts:new Date().toISOString(),channel_values:{},channel_versions:{},versions_seen:{}}}function bd(t){return{v:t.v,id:t.id,ts:t.ts,channel_values:{...t.channel_values},channel_versions:{...t.channel_versions},versions_seen:YA(t.versions_seen)}}function eI(t,e){return typeof t=="number"&&typeof e=="number"?Math.sign(t-e):String(t).localeCompare(String(e))}function n3(...t){return t.reduce((e,n,r)=>r===0?n:eI(e,n)>=0?e:n)}const r3={[_U]:-1,[bl]:-2,[yU]:-3,[wU]:-4};var ao=class extends Error{constructor(t){super(t),this.name="InvalidNamespaceError"}};function s3(t){if(t.length===0)throw new ao("Namespace cannot be empty.");for(const e of t){if(typeof e!="string")throw new ao(`Invalid namespace label '${e}' found in ${t}. Namespace labels must be strings, but got ${typeof e}.`);if(e.includes("."))throw new ao(`Invalid namespace label '${e}' found in ${t}. Namespace labels cannot contain periods ('.').`);if(e==="")throw new ao(`Namespace labels cannot be empty strings. Got ${e} in ${t}`)}if(t[0]==="langgraph")throw new ao(`Root label for namespace cannot be "langgraph". Got: ${t}`)}var a3=class{async get(t,e){return(await this.batch([{namespace:t,key:e}]))[0]}async search(t,e={}){const{filter:n,limit:r=10,offset:s=0,query:a}=e;return(await this.batch([{namespacePrefix:t,filter:n,limit:r,offset:s,query:a}]))[0]}async put(t,e,n,r){s3(t),await this.batch([{namespace:t,key:e,value:n,index:r}])}async delete(t,e){await this.batch([{namespace:t,key:e,value:null}])}async listNamespaces(t={}){const{prefix:e,suffix:n,maxDepth:r,limit:s=100,offset:a=0}=t,i=[];return e&&i.push({matchType:"prefix",path:e}),n&&i.push({matchType:"suffix",path:n}),(await this.batch([{matchConditions:i.length?i:void 0,maxDepth:r,limit:s,offset:a}]))[0]}start(){}stop(){}};const i3=t=>"lg_name"in t&&t.lg_name==="AsyncBatchedStore"?t.store:t;var o3=class extends a3{constructor(e){super();p(this,"lg_name","AsyncBatchedStore");p(this,"store");p(this,"queue",new Map);p(this,"nextKey",0);p(this,"running",!1);p(this,"processingTask",null);this.store=i3(e)}get isRunning(){return this.running}async batch(e){throw new Error("The `batch` method is not implemented on `AsyncBatchedStore`.\n Instead, it calls the `batch` method on the wrapped store.\n If you are seeing this error, something is wrong.")}async get(e,n){return this.enqueueOperation({namespace:e,key:n})}async search(e,n){const{filter:r,limit:s=10,offset:a=0,query:i}=n||{};return this.enqueueOperation({namespacePrefix:e,filter:r,limit:s,offset:a,query:i})}async put(e,n,r){return this.enqueueOperation({namespace:e,key:n,value:r})}async delete(e,n){return this.enqueueOperation({namespace:e,key:n,value:null})}start(){this.running||(this.running=!0,this.processingTask=this.processBatchQueue())}async stop(){this.running=!1,this.processingTask&&await this.processingTask}enqueueOperation(e){return new Promise((n,r)=>{const s=this.nextKey;this.nextKey+=1,this.queue.set(s,{operation:e,resolve:n,reject:r})})}async processBatchQueue(){for(;this.running;){if(await new Promise(n=>{setTimeout(n,0)}),this.queue.size===0)continue;const e=new Map(this.queue);this.queue.clear();try{const n=Array.from(e.values()).map(({operation:s})=>s),r=await this.store.batch(n);e.forEach(({resolve:s},a)=>{s(r[Array.from(e.keys()).indexOf(a)])})}catch(n){e.forEach(({reject:r})=>{r(n)})}}}toJSON(){return{queue:this.queue,nextKey:this.nextKey,running:this.running,store:"[LangGraphStore]"}}},c3=class{constructor(t){p(this,"serde",new t3);this.serde=t||this.serde}};function tI(t){return t!=null&&t.lg_is_channel===!0}var sa=class{constructor(){p(this,"ValueType");p(this,"UpdateType");p(this,"lg_is_channel",!0)}consume(){return!1}finish(){return!1}isAvailable(){try{return this.get(),!0}catch(t){if(t.name===Vt.unminifiable_name)return!1;throw t}}equals(t){return this===t}};const vm=Symbol.for("LG_IS_ONLY_BASE_CHANNEL");function v_(t){if(t[vm]===!0)return t;const e={};for(const n in t){if(!Object.prototype.hasOwnProperty.call(t,n))continue;const r=t[n];tI(r)&&(e[n]=r)}return Object.assign(e,{[vm]:!0}),e}function vd(t,e){const n=v_(t),r={};for(const s in n){if(!Object.prototype.hasOwnProperty.call(n,s))continue;const a=e.channel_values[s];r[s]=n[s].fromCheckpoint(a)}return Object.assign(r,{[vm]:!0}),r}function ya(t,e,n,r){let s;if(e===void 0)s=t.channel_values;else{s={};for(const a in e)if(Object.prototype.hasOwnProperty.call(e,a))try{s[a]=e[a].checkpoint()}catch(i){if(i.name!==Vt.unminifiable_name)throw i}}return{v:4,id:(r==null?void 0:r.id)??bE(n),ts:new Date().toISOString(),channel_values:s,channel_versions:t.channel_versions,versions_seen:t.versions_seen}}var gh=class nI extends sa{constructor(n){super();p(this,"lc_graph_name","LastValue");p(this,"value",[]);this.initialValueFactory=n,n&&(this.value=[n()])}fromCheckpoint(n){const r=new nI(this.initialValueFactory);return typeof n<"u"&&(r.value=[n]),r}update(n){if(n.length===0)return!1;if(n.length!==1)throw new ct("LastValue can only receive one value per step.",{lc_error_code:"INVALID_CONCURRENT_GRAPH_UPDATE"});return this.value=[n[n.length-1]],!0}get(){if(this.value.length===0)throw new Vt;return this.value[0]}checkpoint(){if(this.value.length===0)throw new Vt;return this.value[0]}isAvailable(){return this.value.length!==0}},u3=class rI extends sa{constructor(){super(...arguments);p(this,"lc_graph_name","LastValueAfterFinish");p(this,"value",[]);p(this,"finished",!1)}fromCheckpoint(n){const r=new rI;if(typeof n<"u"){const[s,a]=n;r.value=[s],r.finished=a}return r}update(n){return n.length===0?!1:(this.finished=!1,this.value=[n[n.length-1]],!0)}get(){if(this.value.length===0||!this.finished)throw new Vt;return this.value[0]}checkpoint(){if(this.value.length!==0)return[this.value[0],this.finished]}consume(){return this.finished?(this.finished=!1,this.value=[],!0):!1}finish(){return!this.finished&&this.value.length>0?(this.finished=!0,!0):!1}isAvailable(){return this.value.length!==0&&this.finished}};const l3=t=>t!=null&&t.lc_graph_name==="BinaryOperatorAggregate";var Sd=class sI extends sa{constructor(n,r){super();p(this,"lc_graph_name","BinaryOperatorAggregate");p(this,"value");p(this,"operator");p(this,"initialValueFactory");this.operator=n,this.initialValueFactory=r,this.value=r==null?void 0:r()}fromCheckpoint(n){const r=new sI(this.operator,this.initialValueFactory);return typeof n<"u"&&(r.value=n),r}update(n){let r=n;if(!r.length)return!1;if(this.value===void 0){const a=r[0],[i,o]=sm(a);i?this.value=o:this.value=a,r=r.slice(1)}let s=!1;for(const a of r)if(K4(a)){if(s)throw new ct("Can receive only one Overwrite value per step.");const[,i]=sm(a);this.value=i,s=!0;continue}else!s&&this.value!==void 0&&(this.value=this.operator(this.value,a));return!0}get(){if(this.value===void 0)throw new Vt;return this.value}checkpoint(){if(this.value===void 0)throw new Vt;return this.value}isAvailable(){return this.value!==void 0}equals(n){return this===n?!0:l3(n)?this.operator===n.operator:!1}},Sm=class{constructor(t){p(this,"lc_graph_name","AnnotationRoot");p(this,"spec");this.spec=t}static isInstance(t){return typeof t=="object"&&t!==null&&"lc_graph_name"in t&&t.lc_graph_name==="AnnotationRoot"}};const $a=function(t){return t?Tm(t):new gh};$a.Root=t=>new Sm(t);function Tm(t){return typeof t=="object"&&t&&"reducer"in t&&t.reducer?new Sd(t.reducer,t.default):typeof t=="object"&&t&&"value"in t&&t.value?new Sd(t.value,t.default):new gh}const d3=["tags","metadata","callbacks","configurable"],h3=["tags","metadata","callbacks","runName","maxConcurrency","recursionLimit","configurable","runId","outputKeys","streamMode","store","writer","interrupt","context","interruptBefore","interruptAfter","checkpointDuring","durability","signal","executionInfo","serverInfo"],f3=25,p3=new Set(["thread_id","checkpoint_id","checkpoint_ns","task_id","run_id","assistant_id","graph_id"]);function m3(t,e){if(!t)return e;const n=e??{};for(const r of p3){if(r in n)continue;const s=t[r];s!==void 0&&(n[r]=s)}return n}function aI(...t){const e={tags:[],metadata:{},callbacks:void 0,recursionLimit:f3,configurable:{}},n=tn.getRunnableConfig();if(n!==void 0){for(const[r,s]of Object.entries(n))if(s!==void 0)if(d3.includes(r)){let a;Array.isArray(s)?a=[...s]:typeof s=="object"?r==="callbacks"&&"copy"in s&&typeof s.copy=="function"?a=s.copy():a={...s}:a=s,e[r]=a}else e[r]=s}for(const r of t)if(r!==void 0)for(const[s,a]of Object.entries(r))a!==void 0&&h3.includes(s)&&(e[s]=a);return e.metadata=m3(e.configurable,e.metadata)??{},e}function g3(){return tn.getRunnableConfig()}function Af(t){return t.split("|").filter(e=>!e.match(/^\d+$/)).map(e=>e.split(":")[0]).join("|")}function _3(t){const e=t.split("|");for(;e.length>1&&e[e.length-1].match(/^\d+$/);)e.pop();return e.slice(0,-1).join("|")}var aa=class extends Fe{constructor(e){super();p(this,"lc_namespace",["langgraph"]);p(this,"func");p(this,"tags");p(this,"config");p(this,"trace",!0);p(this,"recurse",!0);this.name=e.name??e.func.name,this.func=e.func,this.config=e.tags?{tags:e.tags}:void 0,this.trace=e.trace??this.trace,this.recurse=e.recurse??this.recurse}async _tracedInvoke(e,n,r){return new Promise((s,a)=>{const i=et(n,{callbacks:r==null?void 0:r.getChild()});tn.runWithConfig(i,async()=>{try{s(await this.func(e,i))}catch(o){a(o)}})})}async invoke(e,n){let r;const s=aI(n),a=sr(this.config,s);return this.trace?r=await this._callWithConfig(this._tracedInvoke,e,a):r=await tn.runWithConfig(a,async()=>this.func(e,a)),Fe.isRunnable(r)&&this.recurse?await tn.runWithConfig(a,async()=>r.invoke(e,a)):r}};function*Es(t,e){if(e===void 0)yield*t;else for(const n of t)yield[e,n]}async function Ms(t){const e=[];for await(const n of await t)e.push(n);return e}function Po(t){const e=[];for(const n of t)e.push(n);return e}function Wa(t,e){return t?"configurable"in t?{...t,configurable:{...t.configurable,...e}}:{...t,configurable:e}:{configurable:e}}function y3(t){return typeof t=="object"&&(t==null?void 0:t[Symbol.for("LG_SKIP_WRITE")])!==void 0}const Na={[Symbol.for("LG_PASSTHROUGH")]:!0};function Nu(t){return typeof t=="object"&&(t==null?void 0:t[Symbol.for("LG_PASSTHROUGH")])!==void 0}const If=Symbol("IS_WRITER");var wn=class Em extends aa{constructor(n,r){const s=`ChannelWrite<${n.map(a=>Sn(a)?a.node:"channel"in a?a.channel:"...").join(",")}>`;super({writes:n,name:s,tags:r,trace:!1,func:async(a,i)=>this._write(a,i??{})});p(this,"writes");this.writes=n}async _write(n,r){const s=this.writes.map(a=>xf(a)&&Nu(a.value)?{mapper:a.mapper,value:n}:Il(a)&&Nu(a.value)?{channel:a.channel,value:n,skipNone:a.skipNone,mapper:a.mapper}:a);return await Em.doWrite(r,s),n}static async doWrite(n,r){var i;for(const o of r){if(Il(o)){if(o.channel==="__pregel_tasks")throw new ct("Cannot write to the reserved channel TASKS");if(Nu(o.value))throw new ct("PASSTHROUGH value must be replaced")}if(xf(o)&&Nu(o.value))throw new ct("PASSTHROUGH value must be replaced")}const s=[];for(const o of r)if(Sn(o))s.push([Di,o]);else if(xf(o)){const c=await o.mapper.invoke(o.value,n);c!=null&&c.length>0&&s.push(...c)}else if(Il(o)){const c=o.mapper!==void 0?await o.mapper.invoke(o.value,n):o.value;if(y3(c)||o.skipNone&&c===void 0)continue;s.push([o.channel,c])}else throw new Error(`Invalid write entry: ${JSON.stringify(o)}`);((i=n.configurable)==null?void 0:i[Hs])(s)}static isWriter(n){return n instanceof Em||If in n&&!!n[If]}static registerWriter(n){return Object.defineProperty(n,If,{value:!0})}};function Il(t){return t!==void 0&&typeof t.channel=="string"}function xf(t){return t!==void 0&&!Il(t)&&Fe.isRunnable(t.mapper)}var w3=class iI extends aa{constructor(n,r,s=!1){super({trace:!1,func:(a,i)=>iI.doRead(i,this.channel,this.fresh,this.mapper)});p(this,"lc_graph_name","ChannelRead");p(this,"channel");p(this,"fresh",!1);p(this,"mapper");this.fresh=s,this.mapper=r,this.channel=n,this.name=Array.isArray(n)?`ChannelRead<${n.join(",")}>`:`ChannelRead<${n}>`}static doRead(n,r,s,a){var o;const i=(o=n.configurable)==null?void 0:o[Ra];if(!i)throw new Error("Runnable is not configured with a read function. Make sure to call in the context of a Pregel process");return a?a(i(r,s)):i(r,s)}};const Ga=new vc;var xc=class Mo extends Qt{constructor(n){var y;const{channels:r,triggers:s,mapper:a,writers:i,bound:o,kwargs:c,metadata:u,retryPolicy:l,cachePolicy:d,tags:f,subgraphs:h,ends:m}=n,_=[...(y=n.config)!=null&&y.tags?n.config.tags:[],...f??[]];super({...n,bound:n.bound??Ga,config:{...n.config?n.config:{},tags:_}});p(this,"lc_graph_name","PregelNode");p(this,"channels");p(this,"triggers",[]);p(this,"mapper");p(this,"writers",[]);p(this,"bound",Ga);p(this,"kwargs",{});p(this,"metadata",{});p(this,"tags",[]);p(this,"retryPolicy");p(this,"cachePolicy");p(this,"subgraphs");p(this,"ends");this.channels=r,this.triggers=s,this.mapper=a,this.writers=i??this.writers,this.bound=o??this.bound,this.kwargs=c??this.kwargs,this.metadata=u??this.metadata,this.tags=_,this.retryPolicy=l,this.cachePolicy=d,this.subgraphs=h,this.ends=m}getWriters(){var r;const n=[...this.writers];for(;n.length>1&&n[n.length-1]instanceof wn&&n[n.length-2]instanceof wn;){const s=n.slice(-2),a=s[0].writes.concat(s[1].writes);n[n.length-2]=new wn(a,(r=s[0].config)==null?void 0:r.tags),n.pop()}return n}getNode(){const n=this.getWriters();if(!(this.bound===Ga&&n.length===0))return this.bound===Ga&&n.length===1?n[0]:this.bound===Ga?new Jn({first:n[0],middle:n.slice(1,n.length-1),last:n[n.length-1],omitSequenceTags:!0}):n.length>0?new Jn({first:this.bound,middle:n.slice(0,n.length-1),last:n[n.length-1],omitSequenceTags:!0}):this.bound}join(n){if(!Array.isArray(n))throw new Error("channels must be a list");if(typeof this.channels!="object")throw new Error("all channels must be named when using .join()");return new Mo({channels:{...this.channels,...Object.fromEntries(n.map(r=>[r,r]))},triggers:this.triggers,mapper:this.mapper,writers:this.writers,bound:this.bound,kwargs:this.kwargs,config:this.config,retryPolicy:this.retryPolicy,cachePolicy:this.cachePolicy})}pipe(n){return wn.isWriter(n)?new Mo({channels:this.channels,triggers:this.triggers,mapper:this.mapper,writers:[...this.writers,n],bound:this.bound,config:this.config,kwargs:this.kwargs,retryPolicy:this.retryPolicy,cachePolicy:this.cachePolicy}):this.bound===Ga?new Mo({channels:this.channels,triggers:this.triggers,mapper:this.mapper,writers:this.writers,bound:en(n),config:this.config,kwargs:this.kwargs,retryPolicy:this.retryPolicy,cachePolicy:this.cachePolicy}):new Mo({channels:this.channels,triggers:this.triggers,mapper:this.mapper,writers:this.writers,bound:this.bound.pipe(n),config:this.config,kwargs:this.kwargs,retryPolicy:this.retryPolicy,cachePolicy:this.cachePolicy})}};function b3(t){return"steps"in t&&Array.isArray(t.steps)}function S_(t){return"lg_is_pregel"in t&&t.lg_is_pregel===!0}function oI(t){const e=[t];for(const n of e){if(S_(n))return n;b3(n)&&e.push(...n.steps)}}var zi=class cI extends sa{constructor(n=!0){super();p(this,"lc_graph_name","EphemeralValue");p(this,"guard");p(this,"value",[]);this.guard=n}fromCheckpoint(n){const r=new cI(this.guard);return typeof n<"u"&&(r.value=[n]),r}update(n){if(n.length===0){const r=this.value.length>0;return this.value=[],r}if(n.length!==1&&this.guard)throw new ct("EphemeralValue can only receive one value per step.");return this.value=[n[n.length-1]],!0}get(){if(this.value.length===0)throw new Vt;return this.value[0]}checkpoint(){if(this.value.length===0)throw new Vt;return this.value[0]}isAvailable(){return this.value.length!==0}};const V=t=>BigInt(t),rt=(t,e=0)=>new DataView(t.buffer,t.byteOffset+e,t.byteLength-e),uI=V("0x9E3779B1"),lI=V("0x85EBCA77"),v3=V("0xC2B2AE3D"),ta=V("0x9E3779B185EBCA87"),ja=V("0xC2B2AE3D27D4EB4F"),dI=V("0x165667B19E3779F9"),T_=V("0x85EBCA77C2B2AE63"),S3=V("0x27D4EB2F165667C5"),T3=V("0x165667919E3779F9"),E3=V("0x9FB21C651E98DF25"),A3=t=>{const e=t.length;if(e%2!==0)throw new Error("String should have an even number of characters");const n=e/2,r=new Uint8Array(n);let s=0,a=0;for(;a<n;){const i=t.slice(s,s+=2);r[a]=Number.parseInt(i,16),a+=1}return rt(r)},Mr=A3("b8fe6c3923a44bbe7c01812cf721ad1cded46de9839097db7240a4a4b7b3671fcb79e64eccc0e578825ad07dccff7221b8084674f743248ee03590e6813a264c3c2852bb91c300cb88d0658b1b532ea371644897a20df94e3819ef46a9deacd8a8fa763fe39c343ff9dcbbc7c70b4f1d8a51e04bcdb45931c89f7ec9d9787364eac5ac8334d3ebc3c581a0fffa1363eb170ddd51b7f0da49d316552629d4689e2b16be587d47a1fc8ff8b8d17ad031ce45cb3a8f95160428afd7fbcabb4b407e"),Ai=(V(1)<<V(128))-V(1),Me=(V(1)<<V(64))-V(1),Td=(V(1)<<V(32))-V(1),os=64,hI=os/8,I3=8,Pu=4;function Hi(t){if(!t)throw new Error("Assert failed")}function x3(t){const e=new DataView(new ArrayBuffer(8));return e.setBigUint64(0,t,!0),e.getBigUint64(0,!1)}function k3(t){let e=t;return e=(e&V(65535))<<V(16)|(e&V(4294901760))>>V(16),e=(e&V(16711935))<<V(8)|(e&V(4278255360))>>V(8),e}function O3(t,e){return(t&Td)*(e&Td)&Me}function C3(t,e){return(t<<e|t>>V(32)-e)&Td}function fI(t,e,n){for(let r=0;r<hI;r+=1){const s=e.getBigUint64(r*8,!0),a=s^n.getBigUint64(r*8,!0);t[r^1]+=s,t[r]+=O3(a,a>>V(32))}return t}function Cb(t,e,n,r){for(let s=0;s<r;s+=1)fI(t,rt(e,s*os),rt(n,s*8));return t}function R3(t,e){for(let n=0;n<hI;n+=1){const r=e.getBigUint64(n*8,!0);let s=t[n];s=Am(s,V(47)),s^=r,s*=uI,t[n]=s&Me}return t}function Mu(t,e){return pI(t[0]^e.getBigUint64(0,!0),t[1]^e.getBigUint64(I3,!0))}function Rb(t,e,n){let r=n;return r+=Mu(t.slice(0),rt(e,0*Pu)),r+=Mu(t.slice(2),rt(e,4*Pu)),r+=Mu(t.slice(4),rt(e,8*Pu)),r+=Mu(t.slice(6),rt(e,12*Pu)),Br(r&Me)}function $3(t,e,n,r,s){let a=t;const i=Math.floor((n.byteLength-os)/8),o=os*i,c=Math.floor((e.byteLength-1)/o);for(let u=0;u<c;u+=1)a=Cb(a,rt(e,u*o),n,i),a=s(a,rt(n,n.byteLength-os));{const u=Math.floor((e.byteLength-1-o*c)/os);a=Cb(a,rt(e,c*o),n,u),a=r(a,rt(e,e.byteLength-os),rt(n,n.byteLength-os-7))}return a}function N3(t,e){let n=new BigUint64Array([v3,ta,ja,dI,T_,lI,S3,uI]);Hi(t.byteLength>128),n=$3(n,t,e,fI,R3),Hi(n.length*8===64);{const r=Rb(n,rt(e,11),V(t.byteLength)*ta&Me);return Rb(n,rt(e,e.byteLength-os-11),~(V(t.byteLength)*ja)&Me)<<V(64)|r}}function pI(t,e){const n=t*e&Ai;return n&Me^n>>V(64)}function $b(t,e,n){return pI((t.getBigUint64(0,!0)^e.getBigUint64(0,!0)+n)&Me,(t.getBigUint64(8,!0)^e.getBigUint64(8,!0)-n)&Me)}function xl(t,e,n,r,s){let a=t&Me,i=t>>V(64)&Me;return a+=$b(e,r,s),a^=n.getBigUint64(0,!0)+n.getBigUint64(8,!0),a&=Me,i+=$b(n,rt(r,16),s),i^=e.getBigUint64(0,!0)+e.getBigUint64(8,!0),i&=Me,i<<V(64)|a}function Br(t){let e=t;return e^=e>>V(37),e*=T3,e&=Me,e^=e>>V(32),e}function Ed(t){let e=t;return e^=e>>V(33),e*=ja,e&=Me,e^=e>>V(29),e*=dI,e&=Me,e^=e>>V(32),e}function P3(t,e,n){const r=t.byteLength;Hi(r>0&&r<=3);const s=V(t.getUint8(r-1))|V(r<<8)|V(t.getUint8(0)<<16)|V(t.getUint8(r>>1)<<24),a=(s^(V(e.getUint32(0,!0))^V(e.getUint32(4,!0)))+n)&Me,i=(V(e.getUint32(8,!0))^V(e.getUint32(12,!0)))-n;return(Ed((C3(k3(s),V(13))^i)&Me)&Me)<<V(64)|Ed(a)}function Am(t,e){return t^t>>e}function M3(t,e,n){const r=t.byteLength;Hi(r>=4&&r<=8);{const s=t.getUint32(0,!0),a=t.getUint32(r-4,!0);let i=((V(s)|V(a)<<V(32))^(e.getBigUint64(16,!0)^e.getBigUint64(24,!0))+n&Me)*(ta+(V(r)<<V(2)))&Ai;return i+=(i&Me)<<V(65),i&=Ai,i^=i>>V(67),Am(Am(i&Me,V(35))*E3&Me,V(28))|Br(i>>V(64))<<V(64)}}function L3(t,e,n){const r=t.byteLength;Hi(r>=9&&r<=16);{const s=(e.getBigUint64(32,!0)^e.getBigUint64(40,!0))+n&Me,a=(e.getBigUint64(48,!0)^e.getBigUint64(56,!0))-n&Me,i=t.getBigUint64(0,!0);let o=t.getBigUint64(r-8,!0),c=(i^o^s)*ta;const u=(c&Me)+(V(r-1)<<V(54));c=c&(Ai^Me)|u,o^=a,c+=o+(o&Td)*(lI-V(1))<<V(64),c&=Ai,c^=x3(c>>V(64));let l=(c&Me)*ja;return l+=(c>>V(64))*ja<<V(64),l&=Ai,Br(l&Me)|Br(l>>V(64))<<V(64)}}function j3(t,e){const n=t.byteLength;return Hi(n<=16),n>8?L3(t,Mr,e):n>=4?M3(t,Mr,e):n>0?P3(t,Mr,e):Ed(e^Mr.getBigUint64(64,!0)^Mr.getBigUint64(72,!0))|Ed(e^Mr.getBigUint64(80,!0)^Mr.getBigUint64(88,!0))<<V(64)}function Im(t){return~t+V(1)&Me}function U3(t,e,n){let r=V(t.byteLength)*ta&Me,s=V(t.byteLength-1)/V(32);for(;s>=0;){const o=Number(s);r=xl(r,rt(t,16*o),rt(t,t.byteLength-16*(o+1)),rt(e,32*o),n),s-=V(1)}let a=r+(r>>V(64))&Me;a=Br(a);let i=(r&Me)*ta+(r>>V(64))*T_+(V(t.byteLength)-n&Me)*ja;return i&=Me,i=Im(Br(i)),a|i<<V(64)}function D3(t,e,n){let r=V(t.byteLength)*ta&Me;for(let i=32;i<160;i+=32)r=xl(r,rt(t,i-32),rt(t,i-16),rt(e,i-32),n);r=Br(r&Me)|Br(r>>V(64))<<V(64);for(let i=160;i<=t.byteLength;i+=32)r=xl(r,rt(t,i-32),rt(t,i-16),rt(e,3+i-160),n);r=xl(r,rt(t,t.byteLength-16),rt(t,t.byteLength-32),rt(e,103),Im(n));let s=r+(r>>V(64))&Me;s=Br(s);let a=(r&Me)*ta+(r>>V(64))*T_+(V(t.byteLength)-n&Me)*ja;return a&=Me,a=Im(Br(a)),s|a<<V(64)}function pa(t,e=V(0)){const n=new TextEncoder,r=rt(typeof t=="string"?n.encode(t):t),s=r.byteLength,a=i=>i.toString(16).padStart(32,"0");return s<=16?a(j3(r,e)):s<=128?a(U3(r,Mr,e)):s<=240?a(D3(r,Mr,e)):a(N3(r,Mr))}function mI(t){return/^[0-9a-f]{32}$/.test(t)}function Ii(t,e,n=!0,r=!1){try{return t[e].get()}catch(s){if(s.name===Vt.unminifiable_name){if(r)return s;if(n)return null}throw s}}function Ua(t,e,n=!0){if(Array.isArray(e)){const r={};for(const s of e)try{r[s]=Ii(t,s,!n)}catch(a){if(a.name===Vt.unminifiable_name)continue}return r}else return Ii(t,e)}function*F3(t,e){if(t.graph===Vn.PARENT)throw new ct("There is no parent graph.");if(t.goto){let n;Array.isArray(t.goto)?n=t.goto:n=[t.goto];for(const r of n)if(Sn(r))yield[Ur,Di,r];else if(typeof r=="string")yield[Ur,`branch:to:${r}`,"__start__"];else throw new Error(`In Command.send, expected Send or string, got ${typeof r}`)}if(t.resume)if(typeof t.resume=="object"&&Object.keys(t.resume).length&&Object.keys(t.resume).every(mI))for(const[n,r]of Object.entries(t.resume)){const s=e.filter(a=>a[0]===n&&a[1]==="__resume__").map(a=>a[2]).slice(0,1)??[];s.push(r),yield[n,ea,s]}else yield[Ur,ea,t.resume];if(t.update){if(typeof t.update!="object"||!t.update)throw new Error("Expected cmd.update to be a dict mapping channel names to update values");if(Array.isArray(t.update))for(const[n,r]of t.update)yield[Ur,n,r];else for(const[n,r]of Object.entries(t.update))yield[Ur,n,r]}}function*gI(t,e){if(e!=null)if(Array.isArray(t)&&typeof e=="object"&&!Array.isArray(e))for(const n in e)t.includes(n)&&(yield[n,e[n]]);else{if(Array.isArray(t))throw new Error('Input chunk must be an object when "inputChannels" is an array');yield[t,e]}}function*kf(t,e,n){Array.isArray(t)?(e===!0||e.find(([r,s])=>t.includes(r)))&&(yield Ua(n,t)):(e===!0||e.some(([r,s])=>r===t))&&(yield Ii(n,t))}function*B3(t,e,n){const r=e.filter(([o,c])=>{var u;return(o.config===void 0||!((u=o.config.tags)!=null&&u.includes("langsmith:hidden")))&&c[0][0]!=="__error__"&&c[0][0]!=="__interrupt__"});if(!r.length)return;let s;r.some(([o])=>o.writes.some(([c,u])=>c==="__return__"))?s=r.flatMap(([o])=>o.writes.filter(([c,u])=>c===nh).map(([c,u])=>[o.name,u])):Array.isArray(t)?s=r.flatMap(([o])=>{const{writes:c}=o,u={};for(const[l]of c)t.includes(l)&&(u[l]=(u[l]||0)+1);return Object.values(u).some(l=>l>1)?c.filter(([l])=>t.includes(l)).map(([l,d])=>[o.name,{[l]:d}]):[[o.name,Object.fromEntries(c.filter(([l])=>t.includes(l)))]]}):s=r.flatMap(([o])=>o.writes.filter(([c,u])=>c===t).map(([c,u])=>[o.name,u]));const a={};for(const[o,c]of s)o in a||(a[o]=[]),a[o].push(c);const i={};for(const o in a)if(a[o].length===1){const[c]=a[o];i[o]=c}else i[o]=a[o];n&&(i.__metadata__={cached:n}),yield i}function E_(t){const e=typeof t[Xt];if(e==="number")return 0;if(e==="string")return"";for(const n in t){if(!Object.prototype.hasOwnProperty.call(t,n))continue;const r=typeof t[n];if(r==="number")return 0;if(r==="string")return"";break}}function kl(t,e){if(Object.keys(t).length>0){const n=E_(e);return Object.fromEntries(Object.entries(e).filter(([r,s])=>s>(t[r]??n)))}else return e}function z3(t,e){return t&&!Array.isArray(t)&&!(t instanceof Date)&&typeof t=="object"?t:{[e]:t}}function vr(t,e){return t===null?{configurable:e}:(t==null?void 0:t.configurable)===void 0?{...t,configurable:e}:{...t,configurable:{...t.configurable,...e}}}function oa(t,e){var r,s;const n=(e==null?void 0:e.parents)??{};return Object.keys(n).length>0?vr(t,{[is]:{...n,[((r=t.configurable)==null?void 0:r.checkpoint_ns)??""]:(s=t.configurable)==null?void 0:s.checkpoint_id}}):t}function Ad(...t){const e=[...new Set(t.filter(Boolean))];if(e.length===0)return{signal:void 0,dispose:void 0};if(e.length===1)return{signal:e[0],dispose:void 0};const n=new AbortController,r=()=>{var i;const a=(i=e.find(o=>o.aborted))==null?void 0:i.reason;n.abort(a),e.forEach(o=>o.removeEventListener("abort",r))};e.forEach(a=>a.addEventListener("abort",r,{once:!0}));const s=e.find(a=>a.aborted);return s&&n.abort(s.reason),{signal:n.signal,dispose:()=>{e.forEach(a=>a.removeEventListener("abort",r))}}}const H3=(t,e)=>{if(!(!t&&!e))return t?e?Array.isArray(t)&&Array.isArray(e)?[...t,...e]:Array.isArray(t)?[...t,e]:Array.isArray(e)?[t,...e]:[t,e]:t:e};var V3=class{constructor({func:t,name:e,input:n,retry:r,cache:s,callbacks:a}){p(this,"func");p(this,"name");p(this,"input");p(this,"retry");p(this,"cache");p(this,"callbacks");p(this,"__lg_type","call");this.func=t,this.name=e,this.input=n,this.retry=r,this.cache=s,this.callbacks=a}};function Z3(t){return typeof t=="object"&&t!==null&&"__lg_type"in t&&t.__lg_type==="call"}function W3(t,e){return new Jn({name:t,first:new aa({func:n=>e(...n),name:t,trace:!1,recurse:!1}),last:new wn([{channel:nh,value:Na}],[Cn])})}const G3=t=>t!==void 0?t+1:1;function q3(t,e){if(e==null)return!1;for(const n of t)if(e[n])return!0;return!1}function K3(t){let e;for(const n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e==null?e=t[n]:e=n3(e,t[n]));return e}function Lu(t,e,n){const r=E_(t.channel_versions),s=t.versions_seen.__interrupt__??{};let a=!1;if((t.channel_versions.__start__??r)>(s.__start__??r))a=!0;else for(const o in t.channel_versions)if(Object.prototype.hasOwnProperty.call(t.channel_versions,o)&&t.channel_versions[o]>(s[o]??r)){a=!0;break}const i=n.some(o=>{var c,u;return e==="*"?!((u=(c=o.config)==null?void 0:c.tags)!=null&&u.includes(Cn)):e.includes(o.name)});return a&&i}function Ol(t,e,n,r,s=!1){let a=new Set;if(Array.isArray(r))a=new Set(r.filter(o=>n.writes.some(([c,u])=>c===o)));else{for(const[o]of n.writes)if(o===r){a=new Set([o]);break}a=a||new Set}let i;if(s&&a.size>0){const o=Object.fromEntries(Object.entries(e).filter(([l,d])=>a.has(l))),c=ya(t,o,-1),u=vd(o,c);Hn(bd(c),u,[n],void 0,void 0),i=Ua({...e,...u},r)}else i=Ua(e,r);return i}function Of(t,e,n){for(const[r,s]of n)if(["__pregel_push","__pregel_tasks"].includes(r)&&s!=null){if(!Sn(s))throw new ct(`Invalid packet type, expected SendProtocol, got ${JSON.stringify(s)}`);if(!(s.node in e))throw new ct(`Invalid node name "${s.node}" in Send packet`)}t(n)}const J3=new Set([Gg,hs,ea,Bt,nh,th]);function Hn(t,e,n,r,s){var f,h;n.sort((m,_)=>{var g,b;const y=((g=m.path)==null?void 0:g.slice(0,3))||[],w=((b=_.path)==null?void 0:b.slice(0,3))||[];for(let S=0;S<Math.min(y.length,w.length);S+=1){if(y[S]<w[S])return-1;if(y[S]>w[S])return 1}return y.length-w.length});const a=n.some(m=>m.triggers.length>0),i=v_(e);for(const m of n){(f=t.versions_seen)[h=m.name]??(f[h]={});for(const _ of m.triggers)_ in t.channel_versions&&(t.versions_seen[m.name][_]=t.channel_versions[_])}let o=K3(t.channel_versions);const c=new Set(n.flatMap(m=>m.triggers).filter(m=>!W4.includes(m)));let u=!1;for(const m of c)m in i&&i[m].consume()&&r!==void 0&&(t.channel_versions[m]=r(o),u=!0);const l={};for(const m of n)for(const[_,y]of m.writes)J3.has(_)||_ in i&&(l[_]??(l[_]=[]),l[_].push(y));o!=null&&r!=null&&(o=u?r(o):o);const d=new Set;for(const[m,_]of Object.entries(l))if(m in i){const y=i[m];let w;try{w=y.update(_)}catch(g){if(g.name===ct.unminifiable_name){const b=new ct(`Invalid update for channel "${m}" with values ${JSON.stringify(_)}: ${g.message}`);throw b.lc_error_code=g.lc_error_code,b}else throw g}w&&r!==void 0&&(t.channel_versions[m]=r(o),y.isAvailable()&&d.add(m))}if(a)for(const m in i){if(!Object.prototype.hasOwnProperty.call(i,m))continue;const _=i[m];_.isAvailable()&&!d.has(m)&&_.update([])&&r!==void 0&&(t.channel_versions[m]=r(o),_.isAvailable()&&d.add(m))}if(a&&!q3(d,s))for(const m in i){if(!Object.prototype.hasOwnProperty.call(i,m))continue;const _=i[m];_.finish()&&r!==void 0&&(t.channel_versions[m]=r(o),_.isAvailable()&&d.add(m))}return d}function*X3(t,e,n){if(n.updatedChannels!=null&&n.triggerToNodes!=null){const r=new Set;for(const s of n.updatedChannels){const a=n.triggerToNodes[s];for(const i of a??[])r.add(i)}yield*[...r].sort();return}if(!(()=>{for(const r in t.channel_versions)if(t.channel_versions[r]!==null)return!1;return!0})())for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&(yield r)}function yi(t,e,n,r,s,a,i){const o={},c=r[Di];if(c!=null&&c.isAvailable()){const u=c.get().length;for(let l=0;l<u;l+=1){const d=xm([hs,l],t,e,n,r,s,a,i);d!==void 0&&(o[d.id]=d)}}for(const u of X3(t,n,i)){const l=xm([nm,u],t,e,n,r,s,a,i);l!==void 0&&(o[l.id]=l)}return o}function xm(t,e,n,r,s,a,i,o){var h,m,_,y;const{step:c,checkpointer:u,manager:l}=o,d=a.configurable??{},f=d.checkpoint_ns??"";if(t[0]==="__pregel_push"&&Z3(t[t.length-1])){const w=t[t.length-1],g=W3(w.name,w.func),b=[hs],S=f===""?w.name:`${f}|${w.name}`,I=mi(JSON.stringify([S,c.toString(),w.name,hs,t[1],t[2]]),e.id),T=`${S}:${I}`,x=[...t.slice(0,3),!0],A={langgraph_step:c,langgraph_node:w.name,langgraph_triggers:b,langgraph_path:x,langgraph_checkpoint_ns:T,checkpoint_ns:T};if(i){const M=[],O={checkpointId:e.id,checkpointNs:T,taskId:I,threadId:d.thread_id,runId:a.runId!=null?String(a.runId):void 0,nodeAttempt:1};return{name:w.name,input:w.input,proc:g,writes:M,config:{...et(sr(a,{metadata:A,store:o.store??a.store}),{runName:w.name,callbacks:l==null?void 0:l.getChild(`graph:step:${c}`),configurable:{[ml]:I,[Hs]:$=>Of(H=>M.push(...H),r,$),[Ra]:($,H=!1)=>Ol(e,s,{name:w.name,writes:M,triggers:b,path:x},$,H),[us]:u??d.__pregel_checkpointer,[is]:{...d[is],[f]:e.id},[Vs]:Cf({pendingWrites:n??[],taskId:I,currentTaskInput:w.input,resumeMap:(h=a.configurable)==null?void 0:h[gl],namespaceHash:pa(T)}),[_l]:e.channel_values[df],checkpoint_id:void 0,checkpoint_ns:T}}),executionInfo:O},triggers:b,retry_policy:w.retry,cache_key:w.cache?{key:pa((w.cache.keyFunc??JSON.stringify)([w.input])),ns:[lf,w.name??"__dynamic__"],ttl:w.cache.ttl}:void 0,id:I,path:x,writers:[]}}else return{id:I,name:w.name,interrupts:[],path:x}}else if(t[0]==="__pregel_push"){const w=typeof t[1]=="number"?t[1]:parseInt(t[1],10);if(!((m=s.__pregel_tasks)!=null&&m.isAvailable()))return;const g=s[Di].get();if(w<0||w>=g.length)return;const b=rm(g[w])&&!Sn(g[w])?new Ma(g[w].node,g[w].args):g[w];if(!rm(b)){console.warn(`Ignoring invalid packet ${JSON.stringify(b)} in pending sends.`);return}if(!(b.node in r)){console.warn(`Ignoring unknown node name ${b.node} in pending sends.`);return}const S=[hs],I=f===""?b.node:`${f}|${b.node}`,T=mi(JSON.stringify([I,c.toString(),b.node,hs,w.toString()]),e.id),x=`${I}:${T}`;let A={langgraph_step:c,langgraph_node:b.node,langgraph_triggers:S,langgraph_path:t.slice(0,3),langgraph_checkpoint_ns:x,checkpoint_ns:x};if(i){const M=r[b.node],O=M.getNode();if(O!==void 0){M.metadata!==void 0&&(A={...A,...M.metadata});const $=[],H={checkpointId:e.id,checkpointNs:x,taskId:T,threadId:d.thread_id,runId:a.runId!=null?String(a.runId):void 0,nodeAttempt:1};return{name:b.node,input:b.args,proc:O,subgraphs:M.subgraphs,writes:$,config:{...et(sr(a,{metadata:A,tags:M.tags,store:o.store??a.store}),{runName:b.node,callbacks:l==null?void 0:l.getChild(`graph:step:${c}`),configurable:{[ml]:T,[Hs]:J=>Of(Y=>$.push(...Y),r,J),[Ra]:(J,Y=!1)=>Ol(e,s,{name:b.node,writes:$,triggers:S,path:t},J,Y),[us]:u??d.__pregel_checkpointer,[is]:{...d[is],[f]:e.id},[Vs]:Cf({pendingWrites:n??[],taskId:T,currentTaskInput:b.args,resumeMap:(_=a.configurable)==null?void 0:_[gl],namespaceHash:pa(x)}),[_l]:e.channel_values[df],checkpoint_id:void 0,checkpoint_ns:x}}),executionInfo:H},triggers:S,retry_policy:M.retryPolicy,cache_key:M.cachePolicy?{key:pa((M.cachePolicy.keyFunc??JSON.stringify)([b.args])),ns:[lf,M.name??"__dynamic__",b.node],ttl:M.cachePolicy.ttl}:void 0,id:T,path:t,writers:M.getWriters()}}}else return{id:T,name:b.node,interrupts:[],path:t}}else if(t[0]==="__pregel_pull"){const w=t[1].toString(),g=r[w];if(g===void 0)return;if(n!=null&&n.length){const T=f===""?w:`${f}|${w}`,x=mi(JSON.stringify([T,c.toString(),w,nm,w]),e.id);if(n.some(A=>A[0]===x&&A[1]!=="__error__"))return}const b=E_(e.channel_versions);if(b===void 0)return;const S=e.versions_seen[w]??{},I=g.triggers.find(T=>s[T].isAvailable()?(e.channel_versions[T]??b)>(S[T]??b):!1);if(I!==void 0){const T=Y3(g,s,i);if(T===void 0)return;const x=f===""?w:`${f}|${w}`,A=mi(JSON.stringify([x,c.toString(),w,nm,[I]]),e.id),M=`${x}:${A}`;let O={langgraph_step:c,langgraph_node:w,langgraph_triggers:[I],langgraph_path:t,langgraph_checkpoint_ns:M,checkpoint_ns:M};if(i){const $=g.getNode();if($!==void 0){g.metadata!==void 0&&(O={...O,...g.metadata});const H=[],J={checkpointId:e.id,checkpointNs:M,taskId:A,threadId:d.thread_id,runId:a.runId!=null?String(a.runId):void 0,nodeAttempt:1};return{name:w,input:T,proc:$,subgraphs:g.subgraphs,writes:H,config:{...et(sr(a,{metadata:O,tags:g.tags,store:o.store??a.store}),{runName:w,callbacks:l==null?void 0:l.getChild(`graph:step:${c}`),configurable:{[ml]:A,[Hs]:Y=>Of(me=>{H.push(...me)},r,Y),[Ra]:(Y,me=!1)=>Ol(e,s,{name:w,writes:H,triggers:[I],path:t},Y,me),[us]:u??d.__pregel_checkpointer,[is]:{...d[is],[f]:e.id},[Vs]:Cf({pendingWrites:n??[],taskId:A,currentTaskInput:T,resumeMap:(y=a.configurable)==null?void 0:y[gl],namespaceHash:pa(M)}),[_l]:e.channel_values[df],checkpoint_id:void 0,checkpoint_ns:M}}),executionInfo:J},triggers:[I],retry_policy:g.retryPolicy,cache_key:g.cachePolicy?{key:pa((g.cachePolicy.keyFunc??JSON.stringify)([T])),ns:[lf,g.name??"__dynamic__",w],ttl:g.cachePolicy.ttl}:void 0,id:A,path:t,writers:g.getWriters()}}}else return{id:A,name:w,interrupts:[],path:t}}}}function Y3(t,e,n){let r;if(typeof t.channels=="object"&&!Array.isArray(t.channels)){r={};for(const[s,a]of Object.entries(t.channels))if(t.triggers.includes(a))try{r[s]=Ii(e,a,!1)}catch(i){if(i.name===Vt.unminifiable_name)return;throw i}else if(a in e)try{r[s]=Ii(e,a,!1)}catch(i){if(i.name===Vt.unminifiable_name)continue;throw i}}else if(Array.isArray(t.channels)){let s=!1;for(const a of t.channels)try{r=Ii(e,a,!1),s=!0;break}catch(i){if(i.name===Vt.unminifiable_name)continue;throw i}if(!s)return}else throw new Error(`Invalid channels type, expected list or dict, got ${t.channels}`);return n&&t.mapper!==void 0&&(r=t.mapper(r)),r}function Q3(t,e){if(typeof t.args!="object"||t.args===null)return t;const n={};for(const[r,s]of Object.entries(t.args)){const a=e[r];(!a||a.lc_graph_name!=="UntrackedValue")&&(n[r]=s)}return new Ma(t.node,n)}function Cf({pendingWrites:t,taskId:e,currentTaskInput:n,resumeMap:r,namespaceHash:s}){var o;const a=(o=t.find(([c,u])=>c==="00000000-0000-0000-0000-000000000000"&&u==="__resume__"))==null?void 0:o[2],i={callCounter:0,interruptCounter:-1,resume:(()=>{const c=t.filter(([u,l])=>u===e&&l==="__resume__").flatMap(([u,l,d])=>d);if(r!=null&&s in r){const u=r[s];c.push(u)}return c})(),nullResume:a,subgraphCounter:0,currentTaskInput:n,consumeNullResume:()=>{if(i.nullResume)return delete i.nullResume,t.splice(t.findIndex(([c,u])=>c==="00000000-0000-0000-0000-000000000000"&&u==="__resume__"),1),a}};return i}const kc={blue:{start:"\x1B[34m",end:"\x1B[0m"},green:{start:"\x1B[32m",end:"\x1B[0m"},yellow:{start:"\x1B[33;1m",end:"\x1B[0m"}},Oc=(t,e)=>`${t.start}${e}${t.end}`;function*Nb(t){var e;for(const{id:n,name:r,input:s,config:a,triggers:i,writes:o}of t)(e=a==null?void 0:a.tags)!=null&&e.includes("langsmith:hidden")||(yield{id:n,name:r,input:s,triggers:i,interrupts:o.filter(([c,u])=>c===n&&u==="__interrupt__").map(([,c])=>c)})}function ez(t){return typeof t!="object"||t===null?!1:"$writes"in t&&Array.isArray(t.$writes)}function _I(t){const e={};for(const[n,r]of t){const s=String(n);if(s in e){const a=ez(e[s])?e[s].$writes:[e[s]];a.push(r),e[s]={$writes:a}}else e[s]=r}return e}function*tz(t,e){var n;for(const[{id:r,name:s,config:a},i]of t)(n=a==null?void 0:a.tags)!=null&&n.includes("langsmith:hidden")||(yield{id:r,name:s,result:_I(i.filter(([o])=>Array.isArray(e)?e.includes(o):o===e)),interrupts:i.filter(o=>o[0]===Bt).map(o=>o[1])})}function*nz(t,e,n,r,s,a,i,o){var d,f,h;function c(m){const _={};return m.callbacks!=null&&(_.callbacks=m.callbacks),m.configurable!=null&&(_.configurable=m.configurable),m.maxConcurrency!=null&&(_.max_concurrency=m.maxConcurrency),m.metadata!=null&&(_.metadata=m.metadata),m.recursionLimit!=null&&(_.recursion_limit=m.recursionLimit),m.runId!=null&&(_.run_id=m.runId),m.runName!=null&&(_.run_name=m.runName),m.tags!=null&&(_.tags=m.tags),_}const u=(d=t.configurable)==null?void 0:d.checkpoint_ns,l={};for(const m of s){if(!((f=m.subgraphs)!=null&&f.length?m.subgraphs:[m.proc]).find(oI))continue;let _=`${m.name}:${m.id}`;u&&(_=`${u}|${_}`),l[m.id]={configurable:{thread_id:(h=t.configurable)==null?void 0:h.thread_id,checkpoint_ns:_}}}yield{config:c(t),values:Ua(e,n),metadata:r,next:s.map(m=>m.name),tasks:yI(s,a,l,o),parentConfig:i?c(i):void 0}}function yI(t,e,n,r){return t.map(s=>{var u;const a=(u=e.find(([l,d])=>l===s.id&&d==="__error__"))==null?void 0:u[2],i=e.filter(([l,d])=>l===s.id&&d==="__interrupt__").map(([,,l])=>l),o=(()=>{var d;if(a||i.length||!e.length)return;const l=e.findIndex(([f,h])=>f===s.id&&h==="__return__");if(l>=0)return e[l][2];if(typeof r=="string")return(d=e.find(([f,h])=>f===s.id&&h===r))==null?void 0:d[2];if(Array.isArray(r)){const f=e.filter(([h,m])=>h===s.id&&r.includes(m)).map(([,h,m])=>[h,m]);return f.length?_I(f):void 0}})();if(a)return{id:s.id,name:s.name,path:s.path,error:a,interrupts:i,result:o};const c=n==null?void 0:n[s.id];return{id:s.id,name:s.name,path:s.path,interrupts:i,...c!==void 0?{state:c}:{},result:o}})}function rz(t,e,n){console.log([`${Oc(kc.blue,`[${t}:checkpoint]`)}`,`\x1B[1m State at the end of step ${t}:\x1B[0m
299
- `,JSON.stringify(Ua(e,n),null,2)].join(""))}function wI(t,e){const n=e.length;console.log([`${Oc(kc.blue,`[${t}:tasks]`)}`,`\x1B[1m Starting step ${t} with ${n} task${n===1?"":"s"}:\x1B[0m
300
- `,e.map(r=>`- ${Oc(kc.green,String(r.name))} -> ${JSON.stringify(r.input,null,2)}`).join(`
301
- `)].join(""))}function sz(t,e,n){const r={};for(const[s,a]of e)n.includes(s)&&(r[s]||(r[s]=[]),r[s].push(a));console.log([`${Oc(kc.blue,`[${t}:writes]`)}`,`\x1B[1m Finished step ${t} with writes to ${Object.keys(r).length} channel${Object.keys(r).length!==1?"s":""}:\x1B[0m
302
- `,Object.entries(r).map(([s,a])=>`- ${Oc(kc.yellow,s)} -> ${a.map(i=>JSON.stringify(i)).join(", ")}`).join(`
303
- `)].join(""))}var Pb=class extends $n{constructor(e,n){const r=e.getReader(),s=n??new AbortController;super({start(a){return i();function i(){return r.read().then(({done:o,value:c})=>{if(o){a.close();return}return a.enqueue(c),i()})}}});p(this,"_abortController");p(this,"_innerReader");this._abortController=s,this._innerReader=r}async cancel(e){this._abortController.abort(e),this._innerReader.releaseLock()}get signal(){return this._abortController.signal}},bI=class extends $n{constructor(e){let n;const r=new Promise(s=>{n=s});super({start:s=>{n(s)}});p(this,"modes");p(this,"controller");p(this,"passthroughFn");p(this,"_closed",!1);r.then(s=>{this.controller=s}),this.passthroughFn=e.passthroughFn,this.modes=e.modes}get closed(){return this._closed}push(e){var n;(n=this.passthroughFn)==null||n.call(this,e),this.controller.enqueue(e)}close(){try{this.controller.close()}catch{}finally{this._closed=!0}}error(e){this.controller.error(e)}},az=class extends za{constructor(e){super();p(this,"name","StreamToolsHandler");p(this,"streamFn");p(this,"runs",{});this.streamFn=e}handleToolStart(e,n,r,s,a,i,o,c){var d;if(!i||a&&a.includes("langsmith:hidden"))return;const u=((d=i.langgraph_checkpoint_ns)==null?void 0:d.split("|"))??[],l={ns:u,toolCallId:c,toolName:o??"unknown",input:n};this.runs[r]=l,this.streamFn([u,"tools",{event:"on_tool_start",toolCallId:l.toolCallId,name:l.toolName,input:n}])}handleToolEvent(e,n){const r=this.runs[n];r&&this.streamFn([r.ns,"tools",{event:"on_tool_event",toolCallId:r.toolCallId,name:r.toolName,data:e}])}handleToolEnd(e,n){const r=this.runs[n];delete this.runs[n],r&&this.streamFn([r.ns,"tools",{event:"on_tool_end",toolCallId:r.toolCallId,name:r.toolName,output:e}])}handleToolError(e,n){const r=this.runs[n];delete this.runs[n],r&&this.streamFn([r.ns,"tools",{event:"on_tool_error",toolCallId:r.toolCallId,name:r.toolName,error:e}])}};function iz(t){return JSON.stringify(t,function(e,n){const r=this[e];if(r!=null&&typeof r=="object"&&"toDict"in r&&typeof r.toDict=="function"){const{type:s,data:a}=r.toDict();return{...a,type:s}}return n})}function oz(t){return t instanceof Error?{error:t.name,message:t.message}:{error:"Error",message:JSON.stringify(t)}}function A_(t){return typeof t!="object"||t==null?!1:"configurable"in t&&typeof t.configurable=="object"&&t.configurable!=null}function Rf(t){return!A_(t)||!t.configurable.thread_id?null:{thread_id:t.configurable.thread_id,checkpoint_ns:t.configurable.checkpoint_ns||"",checkpoint_id:t.configurable.checkpoint_id||null,checkpoint_map:t.configurable.checkpoint_map||null}}function Mb(t){if(A_(t)){const e=Object.fromEntries(Object.entries(t.configurable).filter(([r])=>!r.startsWith("__"))),n={...t,configurable:e};return delete n.callbacks,n}return t}function Lb(t){const e={...t,checkpoint:Rf(t.config),parent_checkpoint:Rf(t.parentConfig),config:Mb(t.config),parent_config:Mb(t.parentConfig),tasks:t.tasks.map(n=>{if(A_(n.state)){const r=Rf(n.state);if(r!=null){const s={...n,checkpoint:r};return delete s.state,s}}return n})};return delete e.parentConfig,e}function cz(t){const e=new TextEncoder;return new ReadableStream({async start(n){const r=s=>{n.enqueue(e.encode(`event: ${s.event}
304
- data: ${iz(s.data)}
305
-
306
- `))};try{for await(const s of t){const[a,i,o]=s;let c=o;if(i==="debug"){const u=o;u.type==="checkpoint"&&(c={...u,payload:Lb(u.payload)})}i==="checkpoints"&&(c=Lb(o)),r({event:a!=null&&a.length?`${i}|${a.join("|")}`:i,data:c})}}catch(s){r({event:"error",data:oz(s)})}n.close()}})}const ju=Symbol.for("INPUT_DONE"),$f=Symbol.for("INPUT_RESUMING"),uz=25;function lz(...t){return new bI({passthroughFn:e=>{for(const n of t)n.modes.has(e[1])&&n.push(e)},modes:new Set(t.flatMap(e=>Array.from(e.modes)))})}var dz=class extends c3{constructor(e){super();p(this,"cache");p(this,"queue",Promise.resolve());this.cache=e}async get(e){return this.enqueueOperation("get",e)}async set(e){return this.enqueueOperation("set",e)}async clear(e){return this.enqueueOperation("clear",e)}async stop(){await this.queue}enqueueOperation(e,...n){const r=this.queue.then(()=>this.cache[e](...n));return this.queue=r.then(()=>{},()=>{}),r}},hz=class vI{constructor(e){p(this,"input");p(this,"output");p(this,"config");p(this,"checkpointer");p(this,"checkpointerGetNextVersion");p(this,"channels");p(this,"checkpoint");p(this,"checkpointIdSaved");p(this,"checkpointConfig");p(this,"checkpointMetadata");p(this,"checkpointNamespace");p(this,"checkpointPendingWrites",[]);p(this,"checkpointPreviousVersions");p(this,"step");p(this,"stop");p(this,"durability");p(this,"outputKeys");p(this,"streamKeys");p(this,"nodes");p(this,"skipDoneTasks");p(this,"prevCheckpointConfig");p(this,"updatedChannels");p(this,"status","pending");p(this,"tasks",{});p(this,"stream");p(this,"checkpointerPromises",new Set);p(this,"isNested");p(this,"_checkpointerChainedPromise",Promise.resolve());p(this,"store");p(this,"cache");p(this,"manager");p(this,"interruptAfter");p(this,"interruptBefore");p(this,"toInterrupt",[]);p(this,"debug",!1);p(this,"triggerToNodes");this.input=e.input,this.checkpointer=e.checkpointer,this.checkpointer!==void 0?this.checkpointerGetNextVersion=this.checkpointer.getNextVersion.bind(this.checkpointer):this.checkpointerGetNextVersion=G3,this.checkpoint=e.checkpoint,this.checkpointMetadata=e.checkpointMetadata,this.checkpointPreviousVersions=e.checkpointPreviousVersions,this.channels=e.channels,this.checkpointPendingWrites=e.checkpointPendingWrites,this.step=e.step,this.stop=e.stop,this.config=e.config,this.checkpointConfig=e.checkpointConfig,this.isNested=e.isNested,this.manager=e.manager,this.outputKeys=e.outputKeys,this.streamKeys=e.streamKeys,this.nodes=e.nodes,this.skipDoneTasks=e.skipDoneTasks,this.store=e.store,this.cache=e.cache?new dz(e.cache):void 0,this.stream=e.stream,this.checkpointNamespace=e.checkpointNamespace,this.prevCheckpointConfig=e.prevCheckpointConfig,this.interruptAfter=e.interruptAfter,this.interruptBefore=e.interruptBefore,this.durability=e.durability,this.debug=e.debug,this.triggerToNodes=e.triggerToNodes}_trackCheckpointerPromise(e){const n=e.then(r=>(this.checkpointerPromises.delete(n),r),r=>{throw r});this.checkpointerPromises.add(n)}get isResuming(){var o,c,u,l,d;let e=!1;if("__start__"in this.checkpoint.channel_versions)e=!0;else for(const f in this.checkpoint.channel_versions)if(Object.prototype.hasOwnProperty.call(this.checkpoint.channel_versions,f)){e=!0;break}const n=((o=this.config.configurable)==null?void 0:o.__pregel_resuming)!==void 0&&((c=this.config.configurable)==null?void 0:c.__pregel_resuming),r=this.input===null||this.input===void 0,s=Pt(this.input)&&this.input.resume!=null,a=this.input===$f,i=!this.isNested&&((u=this.config.metadata)==null?void 0:u.run_id)!==void 0&&((l=this.checkpointMetadata)==null?void 0:l.run_id)!==void 0&&this.config.metadata.run_id===((d=this.checkpointMetadata)==null?void 0:d.run_id);return e&&(n||r||s||a||i)}static async initialize(e){var b,S,I,T,x,A,M,O,$,H,J,Y;let{config:n,stream:r}=e;r!==void 0&&((b=n.configurable)==null?void 0:b.__pregel_stream)!==void 0&&(r=lz(r,n.configurable[Wg]));const s=n.configurable?!("checkpoint_id"in n.configurable):!0,a=(S=n.configurable)==null?void 0:S[Vs];n.configurable&&a&&(a.subgraphCounter>0&&(n=vr(n,{[ls]:[n.configurable[ls],a.subgraphCounter.toString()].join("|")})),a.subgraphCounter+=1);const i=Ra in(n.configurable??{});!i&&((I=n.configurable)==null?void 0:I.checkpoint_ns)!==void 0&&((T=n.configurable)==null?void 0:T.checkpoint_ns)!==""&&(n=vr(n,{checkpoint_ns:"",checkpoint_id:void 0}));let o=n;((x=n.configurable)==null?void 0:x.checkpoint_map)!==void 0&&((O=(A=n.configurable)==null?void 0:A.checkpoint_map)!=null&&O[(M=n.configurable)==null?void 0:M.checkpoint_ns])&&(o=vr(n,{checkpoint_id:n.configurable[is][($=n.configurable)==null?void 0:$.checkpoint_ns]}));const c=((J=(H=n.configurable)==null?void 0:H.checkpoint_ns)==null?void 0:J.split("|"))??[],u=await((Y=e.checkpointer)==null?void 0:Y.getTuple(o))??{config:n,checkpoint:QA(),metadata:{source:"input",step:-2,parents:{}},pendingWrites:[]};o={...n,...u.config,configurable:{checkpoint_ns:"",...n.configurable,...u.config.configurable}};const l=u.parentConfig,d=bd(u.checkpoint),f={...u.metadata},h=u.pendingWrites??[],m=vd(e.channelSpecs,d),_=(f.step??0)+1,y=_+(n.recursionLimit??uz)+1,w={...d.channel_versions},g=e.store?new o3(e.store):void 0;return g&&await g.start(),new vI({input:e.input,config:n,checkpointer:e.checkpointer,checkpoint:d,checkpointMetadata:f,checkpointConfig:o,prevCheckpointConfig:l,checkpointNamespace:c,channels:m,isNested:i,manager:e.manager,skipDoneTasks:s,step:_,stop:y,checkpointPreviousVersions:w,checkpointPendingWrites:h,outputKeys:e.outputKeys??[],streamKeys:e.streamKeys??[],nodes:e.nodes,stream:r,store:g,cache:e.cache,interruptAfter:e.interruptAfter,interruptBefore:e.interruptBefore,durability:e.durability,debug:e.debug,triggerToNodes:e.triggerToNodes})}_checkpointerPutAfterPrevious(e){this._checkpointerChainedPromise=this._checkpointerChainedPromise.then(()=>{var n;return(n=this.checkpointer)==null?void 0:n.put(e.config,e.checkpoint,e.metadata,e.newVersions)}),this._trackCheckpointerPromise(this._checkpointerChainedPromise)}putWrites(e,n){var c;let r=n;if(r.length===0)return;r.every(([u])=>u in r3)&&(r=Array.from(new Map(r.map(u=>[u[0],u])).values()));let s=!1;for(const u in this.channels)if(Object.prototype.hasOwnProperty.call(this.channels,u)&&this.channels[u].lc_graph_name==="UntrackedValue"){s=!0;break}let a=r;s&&(a=r.filter(([u])=>{const l=this.channels[u];return!l||l.lc_graph_name!=="UntrackedValue"}).map(([u,l])=>u==="__pregel_tasks"&&Sn(l)?[u,Q3(l,this.channels)]:[u,l])),this.checkpointPendingWrites=this.checkpointPendingWrites.filter(u=>u[0]!==e);for(const[u,l]of a)this.checkpointPendingWrites.push([e,u,l]);const i=vr(this.checkpointConfig,{[ls]:((c=this.config.configurable)==null?void 0:c.checkpoint_ns)??"",[tm]:this.checkpoint.id});if(this.durability!=="exit"&&this.checkpointer!=null&&this._trackCheckpointerPromise(this.checkpointer.putWrites(i,a,e)),this.tasks&&this._outputWrites(e,r),!n.length||!this.cache||!this.tasks)return;const o=this.tasks[e];o==null||o.cache_key==null||n[0][0]==="__error__"||n[0][0]==="__interrupt__"||this.cache.set([{key:[o.cache_key.ns,o.cache_key.key],value:o.writes,ttl:o.cache_key.ttl}])}_outputWrites(e,n,r=!1){var a,i;const s=this.tasks[e];if(s!==void 0){if(s.config!==void 0&&(s.config.tags??[]).includes("langsmith:hidden"))return;if(n.length>0)if(n[0][0]==="__interrupt__"){if(((a=s.path)==null?void 0:a[0])==="__pregel_push"&&((i=s.path)==null?void 0:i[s.path.length-1])===!0)return;const o=n.filter(c=>c[0]===Bt).flatMap(c=>c[1]);this._emit([["updates",{[Bt]:o}],["values",{[Bt]:o}]])}else n[0][0]!=="__error__"&&this._emit(Po(Es(B3(this.outputKeys,[[s,n]],r),"updates")));r||this._emit(Po(Es(tz([[s,n]],this.streamKeys),"tasks")))}}async _matchCachedWrites(){if(!this.cache)return[];const e=[],n=([i,o])=>`ns:${i.join(",")}|key:${o}`,r=[],s={};for(const i of Object.values(this.tasks))i.cache_key!=null&&!i.writes.length&&(r.push([i.cache_key.ns,i.cache_key.key]),s[n([i.cache_key.ns,i.cache_key.key])]=i);if(r.length===0)return[];const a=await this.cache.get(r);for(const{key:i,value:o}of a){const c=s[n(i)];c!=null&&(c.writes.push(...o),e.push({task:c,result:o}))}return e}async tick(e){var s,a,i;this.store&&!this.store.isRunning&&await((s=this.store)==null?void 0:s.start());const{inputKeys:n=[]}=e;if(this.status!=="pending")throw new Error(`Cannot tick when status is no longer "pending". Current status: "${this.status}"`);if(![ju,$f].includes(this.input))await this._first(n);else{if(this.toInterrupt.length>0)throw this.status="interrupt_before",new Ei;if(Object.values(this.tasks).every(o=>o.writes.length>0)){const o=Object.values(this.tasks).flatMap(u=>u.writes);this.updatedChannels=Hn(this.checkpoint,this.channels,Object.values(this.tasks),this.checkpointerGetNextVersion,this.triggerToNodes);const c=await Ms(Es(kf(this.outputKeys,o,this.channels),"values"));if(this._emit(c),this.checkpointPendingWrites=[],await this._putCheckpoint({source:"loop"}),Lu(this.checkpoint,this.interruptAfter,Object.values(this.tasks)))throw this.status="interrupt_after",new Ei;((a=this.config.configurable)==null?void 0:a.__pregel_resuming)!==void 0&&((i=this.config.configurable)==null||delete i[fd])}else return!1}if(this.step>this.stop)return this.status="out_of_steps",!1;if(this.tasks=yi(this.checkpoint,this.checkpointPendingWrites,this.nodes,this.channels,this.config,!0,{step:this.step,checkpointer:this.checkpointer,isResuming:this.isResuming,manager:this.manager,store:this.store,stream:this.stream,triggerToNodes:this.triggerToNodes,updatedChannels:this.updatedChannels}),this.checkpointer&&this._emit(await Ms(Es(nz(this.checkpointConfig,this.channels,this.streamKeys,this.checkpointMetadata,Object.values(this.tasks),this.checkpointPendingWrites,this.prevCheckpointConfig,this.outputKeys),"checkpoints"))),Object.values(this.tasks).length===0)return this.status="done",!1;if(this.skipDoneTasks&&this.checkpointPendingWrites.length>0){for(const[o,c,u]of this.checkpointPendingWrites){if(c==="__error__"||c==="__interrupt__"||c==="__resume__")continue;const l=Object.values(this.tasks).find(d=>d.id===o);l&&l.writes.push([c,u])}for(const o of Object.values(this.tasks))o.writes.length>0&&this._outputWrites(o.id,o.writes,!0)}if(Object.values(this.tasks).every(o=>o.writes.length>0))return this.tick({inputKeys:n});if(Lu(this.checkpoint,this.interruptBefore,Object.values(this.tasks)))throw this.status="interrupt_before",new Ei;const r=await Ms(Es(Nb(Object.values(this.tasks)),"tasks"));return this._emit(r),!0}async finishAndHandleError(e){this.durability==="exit"&&(!this.isNested||typeof e<"u"||this.checkpointNamespace.every(r=>!r.includes(":")))&&(this._putCheckpoint(this.checkpointMetadata),this._flushPendingWrites());const n=this._suppressInterrupt(e);return(n||e===void 0)&&(this.output=Ua(this.channels,this.outputKeys)),n&&(this.tasks!==void 0&&this.checkpointPendingWrites.length>0&&Object.values(this.tasks).some(r=>r.writes.length>0)&&(this.updatedChannels=Hn(this.checkpoint,this.channels,Object.values(this.tasks),this.checkpointerGetNextVersion,this.triggerToNodes),this._emit(Po(Es(kf(this.outputKeys,Object.values(this.tasks).flatMap(r=>r.writes),this.channels),"values")))),va(e)&&!e.interrupts.length&&this._emit([["updates",{[Bt]:[]}],["values",{[Bt]:[]}]])),n}async acceptPush(e,n,r){var i,o;if(((i=this.interruptAfter)==null?void 0:i.length)>0&&Lu(this.checkpoint,this.interruptAfter,[e])){this.toInterrupt.push(e);return}const s=xm([hs,e.path??[],n,e.id,r],this.checkpoint,this.checkpointPendingWrites,this.nodes,this.channels,e.config??{},!0,{step:this.step,checkpointer:this.checkpointer,manager:this.manager,store:this.store,stream:this.stream});if(!s)return;if(((o=this.interruptBefore)==null?void 0:o.length)>0&&Lu(this.checkpoint,this.interruptBefore,[s])){this.toInterrupt.push(s);return}this._emit(Po(Es(Nb([s]),"tasks"))),this.debug&&wI(this.step,[s]),this.tasks[s.id]=s,this.skipDoneTasks&&this._matchWrites({[s.id]:s});const a=await this._matchCachedWrites();for(const{task:c}of a)this._outputWrites(c.id,c.writes,!0);return s}_suppressInterrupt(e){return va(e)&&!this.isNested}async _first(e){var i;const{configurable:n}=this.config,r=n==null?void 0:n[Vs];if(r&&r.nullResume!==void 0&&this.putWrites(Ur,[[ea,r.nullResume]]),Pt(this.input)){const o=this.input.resume!=null;if(this.input.resume!=null&&typeof this.input.resume=="object"&&Object.keys(this.input.resume).every(mI)&&((i=this.config).configurable??(i.configurable={}),this.config.configurable[gl]=this.input.resume),o&&this.checkpointer==null)throw new Error("Cannot use Command(resume=...) without checkpointer");const c={};for(const[u,l,d]of F3(this.input,this.checkpointPendingWrites))c[u]??(c[u]=[]),c[u].push([l,d]);if(Object.keys(c).length===0)throw new gb("Received empty Command input");for(const[u,l]of Object.entries(c))this.putWrites(u,l)}const s=(this.checkpointPendingWrites??[]).filter(o=>o[0]===Ur).map(o=>o.slice(1));s.length>0&&Hn(this.checkpoint,this.channels,[{name:Ps,writes:s,triggers:[]}],this.checkpointerGetNextVersion,this.triggerToNodes);const a=Pt(this.input)&&s.length>0;if(this.isResuming||a){for(const c in this.channels)if(Object.prototype.hasOwnProperty.call(this.channels,c)&&this.checkpoint.channel_versions[c]!==void 0){const u=this.checkpoint.channel_versions[c];this.checkpoint.versions_seen[Bt]={...this.checkpoint.versions_seen[Bt],[c]:u}}const o=await Ms(Es(kf(this.outputKeys,!0,this.channels),"values"));this._emit(o)}if(this.isResuming)this.input=$f;else if(a)await this._putCheckpoint({source:"input"}),this.input=ju;else{const o=await Ms(gI(e,this.input));if(o.length>0){const c=yi(this.checkpoint,this.checkpointPendingWrites,this.nodes,this.channels,this.config,!0,{step:this.step});this.updatedChannels=Hn(this.checkpoint,this.channels,Object.values(c).concat([{name:Ps,writes:o,triggers:[]}]),this.checkpointerGetNextVersion,this.triggerToNodes),await this._putCheckpoint({source:"input"}),this.input=ju}else if("__pregel_resuming"in(this.config.configurable??{}))this.input=ju;else throw new gb(`Received no input writes for ${JSON.stringify(e,null,2)}`)}this.isNested||(this.config=vr(this.config,{[fd]:this.isResuming}))}_emit(e){for(const[n,r]of e)if(this.stream.modes.has(n)&&this.stream.push([this.checkpointNamespace,n,r]),(n==="checkpoints"||n==="tasks")&&this.stream.modes.has("debug")){const s=n==="checkpoints"?this.step-1:this.step,a=new Date().toISOString(),i=n==="checkpoints"?"checkpoint":typeof r=="object"&&r!=null&&"result"in r?"task_result":"task";this.stream.push([this.checkpointNamespace,"debug",{step:s,type:i,timestamp:a,payload:r}])}}_putCheckpoint(e){var a;const n=this.checkpointMetadata===e,r=this.checkpointer!=null&&(this.durability!=="exit"||n),s=i=>{var u,l,d;this.prevCheckpointConfig=(l=(u=this.checkpointConfig)==null?void 0:u.configurable)!=null&&l.checkpoint_id?this.checkpointConfig:void 0,this.checkpointConfig=vr(this.checkpointConfig,{[ls]:((d=this.config.configurable)==null?void 0:d.checkpoint_ns)??""});const o={...this.checkpoint.channel_versions},c=kl(this.checkpointPreviousVersions,o);this.checkpointPreviousVersions=o,this._checkpointerPutAfterPrevious({config:{...this.checkpointConfig},checkpoint:bd(i),metadata:{...this.checkpointMetadata},newVersions:c}),this.checkpointConfig={...this.checkpointConfig,configurable:{...this.checkpointConfig.configurable,checkpoint_id:this.checkpoint.id}}};n||(this.checkpointMetadata={...e,step:this.step,parents:((a=this.config.configurable)==null?void 0:a.checkpoint_map)??{}}),this.checkpoint=ya(this.checkpoint,r?this.channels:void 0,this.step,n?{id:this.checkpoint.id}:void 0),r&&s(this.checkpoint),n||(this.step+=1)}_flushPendingWrites(){var r;if(this.checkpointer==null||this.checkpointPendingWrites.length===0)return;const e=vr(this.checkpointConfig,{[ls]:((r=this.config.configurable)==null?void 0:r.checkpoint_ns)??"",[tm]:this.checkpoint.id}),n={};for(const[s,a,i]of this.checkpointPendingWrites)n[s]??(n[s]=[]),n[s].push([a,i]);for(const[s,a]of Object.entries(n))this._trackCheckpointerPromise(this.checkpointer.putWrites(e,a,s))}_matchWrites(e){for(const[n,r,s]of this.checkpointPendingWrites){if(r==="__error__"||r==="__interrupt__"||r==="__resume__")continue;const a=Object.values(e).find(i=>i.id===n);a&&a.writes.push([r,s])}for(const n of Object.values(e))n.writes.length>0&&this._outputWrites(n.id,n.writes,!0)}};function fz(t){return wt(t==null?void 0:t.message)}function jb(t,e,n){if(!t)return;const r=t.langgraph_checkpoint_ns,s=t.checkpoint_ns,a=r??s;if(a)return[a.split("|"),{tags:e,name:n,...t}]}var pz=class extends za{constructor(e){super();p(this,"name","StreamMessagesHandler");p(this,"streamFn");p(this,"metadatas",{});p(this,"seen",{});p(this,"emittedChatModelRunIds",{});p(this,"stableMessageIdMap",{});p(this,"lc_prefer_streaming",!0);this.streamFn=e}_emit(e,n,r,s=!1){var i;if(s&&n.id!==void 0&&this.seen[n.id]!==void 0)return;let a=n.id;r!=null&&(Ia(n)?a??(a=`run-${r}-tool-${n.tool_call_id}`):((a==null||a===`run-${r}`)&&(a=this.stableMessageIdMap[r]??a??`run-${r}`),(i=this.stableMessageIdMap)[r]??(i[r]=a))),a!==n.id&&(n.id=a,n.lc_kwargs.id=a),n.id!=null&&(this.seen[n.id]=n),this.streamFn([e[0],"messages",[n,e[1]]])}handleChatModelStart(e,n,r,s,a,i,o,c){o&&(!i||!i.includes("langsmith:nostream")&&!i.includes("nostream"))&&(this.metadatas[r]=jb(o,i,c))}handleLLMNewToken(e,n,r,s,a,i){const o=i==null?void 0:i.chunk;this.emittedChatModelRunIds[r]=!0,this.metadatas[r]!==void 0&&(fz(o)?this._emit(this.metadatas[r],o.message,r):this._emit(this.metadatas[r],new Qe({content:e}),r))}handleLLMEnd(e,n){var r,s;if(this.metadatas[n]!==void 0){if(!this.emittedChatModelRunIds[n]){const a=(s=(r=e.generations)==null?void 0:r[0])==null?void 0:s[0];wt(a==null?void 0:a.message)&&this._emit(this.metadatas[n],a==null?void 0:a.message,n,!0),delete this.emittedChatModelRunIds[n]}delete this.metadatas[n],delete this.stableMessageIdMap[n]}}handleLLMError(e,n){delete this.metadatas[n]}handleChainStart(e,n,r,s,a,i,o,c){if(i!==void 0&&c===i.langgraph_node&&(a===void 0||!a.includes("langsmith:hidden"))&&(this.metadatas[r]=jb(i,a,c),typeof n=="object")){for(const u of Object.values(n))if((wt(u)||Ci(u))&&u.id!==void 0)this.seen[u.id]=u;else if(Array.isArray(u))for(const l of u)(wt(l)||Ci(l))&&l.id!==void 0&&(this.seen[l.id]=l)}}handleChainEnd(e,n){const r=this.metadatas[n];if(delete this.metadatas[n],r!==void 0){if(wt(e))this._emit(r,e,n,!0);else if(Array.isArray(e))for(const s of e)wt(s)&&this._emit(r,s,n,!0);else if(e!=null&&typeof e=="object"){for(const s of Object.values(e))if(wt(s))this._emit(r,s,n,!0);else if(Array.isArray(s))for(const a of s)wt(a)&&this._emit(r,a,n,!0)}}}handleChainError(e,n){delete this.metadatas[n]}};const mz=[400,401,402,403,404,405,406,407,409],gz=t=>{var n,r;if(t.message.startsWith("Cancel")||t.message.startsWith("AbortError")||t.name==="AbortError"||t.name==="GraphValueError"||(t==null?void 0:t.code)==="ECONNABORTED")return!1;const e=((n=t==null?void 0:t.response)==null?void 0:n.status)??(t==null?void 0:t.status);return!(e&&mz.includes(+e)||((r=t==null?void 0:t.error)==null?void 0:r.code)==="insufficient_quota")};async function SI(t,e,n,r){var d;const s=t.retry_policy??e;let a=s!==void 0?s.initialInterval??500:0,i=0,o,c,u=t.config??{};n&&(u=vr(u,n)),u={...u,signal:r};const l=Date.now();for(u.executionInfo!=null&&(u.executionInfo={...u.executionInfo,nodeFirstAttemptTime:l});!(r!=null&&r.aborted);){t.writes.splice(0,t.writes.length),o=void 0;try{c=await t.proc.invoke(t.input,u);break}catch(f){if(o=f,o.pregelTaskId=t.id,X4(o)){const _=(d=u==null?void 0:u.configurable)==null?void 0:d.checkpoint_ns,y=o.command;if(y.graph===_){for(const w of t.writers)await w.invoke(y,u);o=void 0;break}else if(y.graph===Vn.PARENT){const w=_3(_);o.command=new Vn({...o.command,graph:w})}}if(wl(o)||s===void 0||(i+=1,i>=(s.maxAttempts??3))||!(s.retryOn??gz)(o))break;a=Math.min(s.maxInterval??128e3,a*(s.backoffFactor??2));const h=s.jitter?Math.floor(a+Math.random()*1e3):a;await new Promise(_=>setTimeout(_,h));const m=o.name??o.constructor.unminifiable_name??o.constructor.name;((s==null?void 0:s.logWarning)??!0)&&console.log(`Retrying task "${String(t.name)}" after ${a.toFixed(2)}ms (attempt ${i}) after ${m}: ${o}`),u=vr(u,{[fd]:!0}),u.executionInfo!=null&&(u.executionInfo={...u.executionInfo,nodeAttempt:i+1,nodeFirstAttemptTime:l})}}return{task:t,result:c,error:o,signalAborted:r==null?void 0:r.aborted}}const km=Symbol.for("promiseAdded");function _z(){const t={next:()=>{},wait:Promise.resolve(km)};function e(n){t.next=()=>{t.wait=new Promise(e),n(km)}}return t.wait=new Promise(e),t}var yz=class{constructor({loop:t,nodeFinished:e}){p(this,"nodeFinished");p(this,"loop");this.loop=t,this.nodeFinished=e}async tick(t={}){const{timeout:e,retryPolicy:n,onStepWrite:r,maxConcurrency:s}=t,a=new Set;let i;const o=new AbortController,c=o.signal,u=e?AbortSignal.timeout(e):void 0,l=Object.values(this.loop.tasks).filter(m=>m.writes.length===0),{signals:d,disposeCombinedSignal:f}=this._initializeAbortSignals({exceptionSignal:c,stepTimeoutSignal:u,signal:t.signal}),h=this._executeTasksWithRetry(l,{signals:d,retryPolicy:n,maxConcurrency:s});for await(const{task:m,error:_,signalAborted:y}of h)this._commit(m,_),va(_)||wl(_)&&!va(i)?i=_:_&&(a.size===0||!y)&&(o.abort(),a.add(_));if(f==null||f(),r==null||r(this.loop.step,Object.values(this.loop.tasks).map(m=>m.writes).flat()),a.size===1)throw Array.from(a)[0];if(a.size>1)throw new AggregateError(Array.from(a),`Multiple errors occurred during superstep ${this.loop.step}. See the "errors" field of this exception for more details.`);if(va(i)||wl(i)&&this.loop.isNested)throw i}_initializeAbortSignals({exceptionSignal:t,stepTimeoutSignal:e,signal:n}){var u;const r=((u=this.loop.config.configurable)==null?void 0:u.__pregel_abort_signals)??{},s=r.externalAbortSignal??n,a=e??r.timeoutAbortSignal,{signal:i,dispose:o}=Ad(s,a,t),c={externalAbortSignal:s,timeoutAbortSignal:a,composedAbortSignal:i};return this.loop.config=vr(this.loop.config,{[Z4]:c}),{signals:c,disposeCombinedSignal:o}}async*_executeTasksWithRetry(t,e){var f,h,m;const{retryPolicy:n,maxConcurrency:r,signals:s}=e??{},a=_z(),i={},o={executingTasksMap:i,barrier:a,retryPolicy:n,scheduleTask:async(_,y,w)=>this.loop.acceptPush(_,y,w)};if((f=s==null?void 0:s.composedAbortSignal)!=null&&f.aborted)throw new Error("Abort");let c=0,u;const l=Ad(s==null?void 0:s.externalAbortSignal,s==null?void 0:s.timeoutAbortSignal),d=l.signal?new Promise((_,y)=>{var w;u=()=>y(new Error("Abort")),(w=l.signal)==null||w.addEventListener("abort",u,{once:!0})}):void 0;for(;(c===0||Object.keys(i).length>0)&&t.length;){for(;Object.values(i).length<(r??t.length)&&c<t.length;c+=1){const y=t[c];i[y.id]=SI(y,n,{[Zg]:Cl==null?void 0:Cl.bind(o,this,y)},s==null?void 0:s.composedAbortSignal).catch(w=>{var g;return{task:y,error:w,signalAborted:(g=s==null?void 0:s.composedAbortSignal)==null?void 0:g.aborted}})}const _=await Promise.race([...Object.values(i),...d?[d]:[],a.wait]);_!==km&&(yield _,u!=null&&((h=l.signal)==null||h.removeEventListener("abort",u),(m=l.dispose)==null||m.call(l)),delete i[_.task.id])}}_commit(t,e){var n;if(e!==void 0)if(va(e)){if(e.interrupts.length){const r=e.interrupts.map(a=>[Bt,a]),s=t.writes.filter(a=>a[0]===ea);s.length&&r.push(...s),this.loop.putWrites(t.id,r)}}else wl(e)&&t.writes.length?this.loop.putWrites(t.id,t.writes):this.loop.putWrites(t.id,[[th,{message:e.message,name:e.name}]]);else this.nodeFinished&&(((n=t.config)==null?void 0:n.tags)==null||!t.config.tags.includes("langsmith:hidden"))&&this.nodeFinished(String(t.name)),t.writes.length===0&&t.writes.push([Gg,null]),this.loop.putWrites(t.id,t.writes)}};async function Cl(t,e,n,r,s,a={}){var d,f;const i=(f=(d=e.config)==null?void 0:d.configurable)==null?void 0:f[Vs];if(!i)throw new Error(`BUG: No scratchpad found on task ${e.name}__${e.id}`);const o=i.callCounter;i.callCounter+=1;const c=new V3({func:n,name:r,input:s,cache:a.cache,retry:a.retry,callbacks:a.callbacks}),u=await this.scheduleTask(e,o,c);if(!u)return;const l=this.executingTasksMap[u.id];if(l!==void 0)return l;if(u.writes.length>0){const h=u.writes.filter(([_])=>_===nh),m=u.writes.filter(([_])=>_===th);if(h.length>0){if(h.length===1)return Promise.resolve(h[0][1]);throw new Error(`BUG: multiple returns found for task ${u.name}__${u.id}`)}if(m.length>0){if(m.length===1){const _=m[0][1],y=_ instanceof Error?_:new Error(String(_));return Promise.reject(y)}throw new Error(`BUG: multiple errors found for task ${u.name}__${u.id}`)}return}else{const h=SI(u,a.retry,{[Zg]:Cl.bind(this,t,u)});return this.executingTasksMap[u.id]=h,this.barrier.next(),h.then(({result:m,error:_})=>_?Promise.reject(_):m)}}var Xr=class extends Error{constructor(t){super(t),this.name="GraphValidationError"}};function wz({nodes:t,channels:e,inputChannels:n,outputChannels:r,streamChannels:s,interruptAfterNodes:a,interruptBeforeNodes:i}){if(!e)throw new Xr("Channels not provided");const o=new Set,c=new Set;for(const[u,l]of Object.entries(t)){if(u==="__interrupt__")throw new Xr(`"Node name ${Bt} is reserved"`);if(l.constructor===xc)l.triggers.forEach(d=>o.add(d));else throw new Xr(`Invalid node type ${typeof l}, expected PregelNode`)}for(const u of o)if(!(u in e))throw new Xr(`Subscribed channel '${String(u)}' not in channels`);if(Array.isArray(n)){if(n.every(u=>!o.has(u)))throw new Xr(`None of the input channels ${n} are subscribed to by any node`)}else if(!o.has(n))throw new Xr(`Input channel ${String(n)} is not subscribed to by any node`);Array.isArray(r)?r.forEach(u=>c.add(u)):c.add(r),s&&!Array.isArray(s)?c.add(s):Array.isArray(s)&&s.forEach(u=>c.add(u));for(const u of c)if(!(u in e))throw new Xr(`Output channel '${String(u)}' not in channels`);if(a&&a!=="*"){for(const u of a)if(!(u in t))throw new Xr(`Node ${String(u)} not in nodes`)}if(i&&i!=="*"){for(const u of i)if(!(u in t))throw new Xr(`Node ${String(u)} not in nodes`)}}function Ub(t,e){if(Array.isArray(t)){for(const n of t)if(!(n in e))throw new Error(`Key ${String(n)} not found in channels`)}else if(!(t in e))throw new Error(`Key ${String(t)} not found in channels`)}var bz=class TI extends sa{constructor(n){super();p(this,"lc_graph_name","Topic");p(this,"unique",!1);p(this,"accumulate",!1);p(this,"seen");p(this,"values");this.unique=(n==null?void 0:n.unique)??this.unique,this.accumulate=(n==null?void 0:n.accumulate)??this.accumulate,this.seen=new Set,this.values=[]}fromCheckpoint(n){const r=new TI({unique:this.unique,accumulate:this.accumulate});return typeof n<"u"&&(r.seen=new Set(n[0]),r.values=n[1]),r}update(n){let r=!1;this.accumulate||(r=this.values.length>0,this.values=[]);const s=n.flat();if(s.length>0)if(this.unique)for(const a of s)this.seen.has(a)||(r=!0,this.seen.add(a),this.values.push(a));else r=!0,this.values.push(...s);return r}get(){if(this.values.length===0)throw new Vt;return this.values}checkpoint(){return[[...this.seen],this.values]}isAvailable(){return this.values.length!==0}};function vz(t){var i,o,c;const e=tn.getRunnableConfig();if(!e)throw new Error("Called interrupt() outside the context of a graph.");const n=e.configurable;if(!n)throw new Error("No configurable found in config");if(!n.__pregel_checkpointer)throw new yl("No checkpointer set",{lc_error_code:"MISSING_CHECKPOINTER"});const r=n[Vs];r.interruptCounter+=1;const s=r.interruptCounter;if(r.resume.length>0&&s<r.resume.length)return(i=n[Hs])==null||i.call(n,[[ea,r.resume]]),r.resume[s];if(r.nullResume!==void 0){if(r.resume.length!==s)throw new Error(`Resume length mismatch: ${r.resume.length} !== ${s}`);const u=r.consumeNullResume();return r.resume.push(u),(o=n[Hs])==null||o.call(n,[[ea,r.resume]]),u}const a=(c=n[ls])==null?void 0:c.split("|");throw new Ei([{id:a?pa(a.join("|")):void 0,value:t}])}var Sz=class{static subscribeTo(t,e){const{key:n,tags:r}={key:void 0,tags:void 0,...e??{}};if(Array.isArray(t)&&n!==void 0)throw new Error("Can't specify a key when subscribing to multiple channels");let s;return typeof t=="string"?n?s={[n]:t}:s=[t]:s=Object.fromEntries(t.map(a=>[a,a])),new xc({channels:s,triggers:Array.isArray(t)?t:[t],tags:r})}static writeTo(t,e){const n=[];for(const r of t)n.push({channel:r,value:Na,skipNone:!1});for(const[r,s]of Object.entries(e??{}))Fe.isRunnable(s)||typeof s=="function"?n.push({channel:r,value:Na,skipNone:!0,mapper:en(s)}):n.push({channel:r,value:s,skipNone:!1});return new wn(n)}},Tz=class extends Fe{constructor(){super(...arguments);p(this,"lc_namespace",["langgraph","pregel"])}invoke(e,n){throw new Error("Not implemented")}withConfig(e){return super.withConfig(e)}stream(e,n){return super.stream(e,n)}},Ez=class extends Tz{constructor(e){super(e);p(this,"lc_namespace",["langgraph","pregel"]);p(this,"lg_is_pregel",!0);p(this,"nodes");p(this,"channels");p(this,"inputChannels");p(this,"outputChannels");p(this,"autoValidate",!0);p(this,"streamMode",["values"]);p(this,"streamChannels");p(this,"interruptAfter");p(this,"interruptBefore");p(this,"stepTimeout");p(this,"debug",!1);p(this,"checkpointer");p(this,"retryPolicy");p(this,"config");p(this,"store");p(this,"cache");p(this,"userInterrupt");p(this,"triggerToNodes",{});let{streamMode:n}=e;if(n!=null&&!Array.isArray(n)&&(n=[n]),this.nodes=e.nodes,this.channels=e.channels,"__pregel_tasks"in this.channels&&"lc_graph_name"in this.channels.__pregel_tasks&&this.channels.__pregel_tasks.lc_graph_name!=="Topic")throw new Error(`Channel '${Di}' is reserved and cannot be used in the graph.`);this.channels[Di]=new bz({accumulate:!1}),this.autoValidate=e.autoValidate??this.autoValidate,this.streamMode=n??this.streamMode,this.inputChannels=e.inputChannels,this.outputChannels=e.outputChannels,this.streamChannels=e.streamChannels??this.streamChannels,this.interruptAfter=e.interruptAfter,this.interruptBefore=e.interruptBefore,this.stepTimeout=e.stepTimeout??this.stepTimeout,this.debug=e.debug??this.debug,this.checkpointer=e.checkpointer,this.retryPolicy=e.retryPolicy,this.config=e.config,this.store=e.store,this.cache=e.cache,this.name=e.name,this.triggerToNodes=e.triggerToNodes??this.triggerToNodes,this.userInterrupt=e.userInterrupt,this.autoValidate&&this.validate()}static lc_name(){return"LangGraph"}withConfig(e){const n=sr(this.config,e);return new this.constructor({...this,config:n})}validate(){var e;wz({nodes:this.nodes,channels:this.channels,outputChannels:this.outputChannels,inputChannels:this.inputChannels,streamChannels:this.streamChannels,interruptAfterNodes:this.interruptAfter,interruptBeforeNodes:this.interruptBefore});for(const[n,r]of Object.entries(this.nodes))for(const s of r.triggers)(e=this.triggerToNodes)[s]??(e[s]=[]),this.triggerToNodes[s].push(n);return this}get streamChannelsList(){return Array.isArray(this.streamChannels)?this.streamChannels:this.streamChannels?[this.streamChannels]:Object.keys(this.channels)}get streamChannelsAsIs(){return this.streamChannels?this.streamChannels:Object.keys(this.channels)}async getGraphAsync(e){return this.getGraph(e)}*getSubgraphs(e,n){var r;for(const[s,a]of Object.entries(this.nodes)){if(e!==void 0&&!e.startsWith(s))continue;const i=(r=a.subgraphs)!=null&&r.length?a.subgraphs:[a.bound];for(const o of i){const c=oI(o);if(c!==void 0){if(s===e){yield[s,c];return}if(e===void 0&&(yield[s,c]),n){let u=e;e!==void 0&&(u=e.slice(s.length+1));for(const[l,d]of c.getSubgraphs(u,n))yield[`${s}|${l}`,d]}}}}}async*getSubgraphsAsync(e,n){yield*this.getSubgraphs(e,n)}async _prepareStateSnapshot({config:e,saved:n,subgraphCheckpointer:r,applyPendingWrites:s=!1}){var f,h,m,_,y,w,g,b;if(n===void 0)return{values:{},next:[],config:e,tasks:[]};const a=vd(this.channels,n.checkpoint);if((f=n.pendingWrites)!=null&&f.length){const S=n.pendingWrites.filter(([I,T])=>I===Ur).map(([I,T,x])=>[String(T),x]);S.length>0&&Hn(n.checkpoint,a,[{name:Ps,writes:S,triggers:[]}],void 0,this.triggerToNodes)}const i=Object.values(yi(n.checkpoint,n.pendingWrites,this.nodes,a,n.config,!0,{step:(((h=n.metadata)==null?void 0:h.step)??-1)+1,store:this.store})),o=await Ms(this.getSubgraphsAsync()),c=((m=n.config.configurable)==null?void 0:m.checkpoint_ns)??"",u={};for(const S of i){const I=o.find(([x])=>x===S.name);if(!I)continue;let T=`${String(S.name)}:${S.id}`;if(c&&(T=`${c}|${T}`),r===void 0){const x={configurable:{thread_id:(_=n.config.configurable)==null?void 0:_.thread_id,checkpoint_ns:T}};u[S.id]=x}else{const x={configurable:{[us]:r,thread_id:(y=n.config.configurable)==null?void 0:y.thread_id,checkpoint_ns:T}},A=I[1];u[S.id]=await A.getState(x,{subgraphs:!0})}}if(s&&((w=n.pendingWrites)!=null&&w.length)){const S=Object.fromEntries(i.map(T=>[T.id,T]));for(const[T,x,A]of n.pendingWrites)["__error__","__interrupt__",bl].includes(x)||T in S&&S[T].writes.push([String(x),A]);const I=i.filter(T=>T.writes.length>0);I.length>0&&Hn(n.checkpoint,a,I,void 0,this.triggerToNodes)}let l=n==null?void 0:n.metadata;l&&((b=(g=n==null?void 0:n.config)==null?void 0:g.configurable)!=null&&b.thread_id)&&(l={...l,thread_id:n.config.configurable.thread_id});const d=i.filter(S=>S.writes.length===0).map(S=>S.name);return{values:Ua(a,this.streamChannelsAsIs),next:d,tasks:yI(i,(n==null?void 0:n.pendingWrites)??[],u,this.streamChannelsAsIs),metadata:l,config:oa(n.config,n.metadata),createdAt:n.checkpoint.ts,parentConfig:n.parentConfig}}async getState(e,n){var o,c,u,l;const r=((o=e.configurable)==null?void 0:o.__pregel_checkpointer)??this.checkpointer;if(!r)throw new yl("No checkpointer set",{lc_error_code:"MISSING_CHECKPOINTER"});const s=((c=e.configurable)==null?void 0:c.checkpoint_ns)??"";if(s!==""&&((u=e.configurable)==null?void 0:u.__pregel_checkpointer)===void 0){const d=Af(s);for await(const[f,h]of this.getSubgraphsAsync(d,!0))if(f===d)return await h.getState(Wa(e,{[us]:r}),{subgraphs:n==null?void 0:n.subgraphs})}const a=sr(this.config,e),i=await r.getTuple(e);return await this._prepareStateSnapshot({config:a,saved:i,subgraphCheckpointer:n!=null&&n.subgraphs?r:void 0,applyPendingWrites:!((l=e.configurable)!=null&&l.checkpoint_id)})}async*getStateHistory(e,n){var i,o,c;const r=((i=e.configurable)==null?void 0:i.__pregel_checkpointer)??this.checkpointer;if(!r)throw new yl("No checkpointer set",{lc_error_code:"MISSING_CHECKPOINTER"});const s=((o=e.configurable)==null?void 0:o.checkpoint_ns)??"";if(s!==""&&((c=e.configurable)==null?void 0:c.__pregel_checkpointer)===void 0){const u=Af(s);for await(const[l,d]of this.getSubgraphsAsync(u,!0))if(l===u){yield*d.getStateHistory(Wa(e,{[us]:r}),n);return}}const a=sr(this.config,e,{configurable:{checkpoint_ns:s}});for await(const u of r.list(a,n))yield this._prepareStateSnapshot({config:u.config,saved:u})}async bulkUpdateState(e,n){var o,c,u;const r=((o=e.configurable)==null?void 0:o.__pregel_checkpointer)??this.checkpointer;if(!r)throw new yl("No checkpointer set",{lc_error_code:"MISSING_CHECKPOINTER"});if(n.length===0)throw new Error("No supersteps provided");if(n.some(l=>l.updates.length===0))throw new Error("No updates provided");const s=((c=e.configurable)==null?void 0:c.checkpoint_ns)??"";if(s!==""&&((u=e.configurable)==null?void 0:u.__pregel_checkpointer)===void 0){const l=Af(s);for await(const[,d]of this.getSubgraphsAsync(l,!0))return await d.bulkUpdateState(Wa(e,{[us]:r}),n);throw new Error(`Subgraph "${l}" not found`)}const a=async(l,d)=>{var $,H,J,Y,me,te,Be,P,z,Q,se;const f=this.config?sr(this.config,l):l,h=await r.getTuple(f),m=h!==void 0?bd(h.checkpoint):QA(),_={...h==null?void 0:h.checkpoint.channel_versions},y=(($=h==null?void 0:h.metadata)==null?void 0:$.step)??-1;let w=Wa(f,{checkpoint_ns:((H=f.configurable)==null?void 0:H.checkpoint_ns)??""}),g=f.metadata??{};h!=null&&h.config.configurable&&(w=Wa(f,h.config.configurable),g={...h.metadata,...g});const{values:b,asNode:S}=d[0];if(b==null&&S===void 0){if(d.length>1)throw new ct("Cannot create empty checkpoint with multiple updates");return oa(await r.put(w,ya(m,void 0,y),{source:"update",step:y+1,parents:((J=h==null?void 0:h.metadata)==null?void 0:J.parents)??{}},{}),h?h.metadata:void 0)}const I=vd(this.channels,m);if(b===null&&S==="__end__"){if(d.length>1)throw new ct("Cannot apply multiple updates when clearing state");if(h){const q=yi(m,h.pendingWrites||[],this.nodes,I,h.config,!0,{step:(((Y=h.metadata)==null?void 0:Y.step)??-1)+1,checkpointer:r,store:this.store}),re=(h.pendingWrites||[]).filter(ve=>ve[0]===Ur).map(ve=>ve.slice(1));re.length>0&&Hn(m,I,[{name:Ps,writes:re,triggers:[]}],r.getNextVersion.bind(r),this.triggerToNodes);for(const[ve,ie,E]of h.pendingWrites||[])["__error__","__interrupt__",bl].includes(ie)||ve in q&&q[ve].writes.push([ie,E]);Hn(m,I,Object.values(q),r.getNextVersion.bind(r),this.triggerToNodes)}return oa(await r.put(w,ya(m,I,y),{...g,source:"update",step:y+1,parents:((me=h==null?void 0:h.metadata)==null?void 0:me.parents)??{}},kl(_,m.channel_versions)),h?h.metadata:void 0)}if(S==="__copy__"){if(d.length>1)throw new ct("Cannot copy checkpoint with multiple updates");if(h==null)throw new ct("Cannot copy a non-existent checkpoint");const q=ie=>!Array.isArray(ie)||ie.length===0?!1:ie.every(E=>Array.isArray(E)&&E.length===2),re=ya(m,void 0,y),ve=await r.put(h.parentConfig??Wa(h.config,{checkpoint_id:void 0}),re,{source:"fork",step:y+1,parents:((te=h.metadata)==null?void 0:te.parents)??{}},{});if(q(b)){const ie=yi(re,h.pendingWrites,this.nodes,I,ve,!1,{step:y+2}),E=Object.values(ie).reduce((N,{name:k,id:ge})=>(N[k]??(N[k]=[]),N[k].push({id:ge}),N),{}),v=b.reduce((N,k)=>{var it,mt;const[ge,Se]=k;N[Se]??(N[Se]=[]);const Ye=N[Se].length,Ze=(mt=(it=E[Se])==null?void 0:it[Ye])==null?void 0:mt.id;return N[Se].push({values:ge,asNode:Se,taskId:Ze}),N},{});return a(oa(ve,h.metadata),Object.values(v).flat())}return oa(ve,h.metadata)}if(S==="__input__"){if(d.length>1)throw new ct("Cannot apply multiple updates when updating as input");const q=await Ms(gI(this.inputChannels,b));if(q.length===0)throw new ct(`Received no input writes for ${JSON.stringify(this.inputChannels,null,2)}`);Hn(m,I,[{name:Ps,writes:q,triggers:[]}],r.getNextVersion.bind(this.checkpointer),this.triggerToNodes);const re=((Be=h==null?void 0:h.metadata)==null?void 0:Be.step)!=null?h.metadata.step+1:-1,ve=await r.put(w,ya(m,I,re),{source:"input",step:re,parents:((P=h==null?void 0:h.metadata)==null?void 0:P.parents)??{}},kl(_,m.channel_versions));return await r.putWrites(ve,q,mi(Ps,m.id)),oa(ve,h?h.metadata:void 0)}if(((z=f.configurable)==null?void 0:z.checkpoint_id)===void 0&&(h==null?void 0:h.pendingWrites)!==void 0&&h.pendingWrites.length>0){const q=yi(m,h.pendingWrites,this.nodes,I,h.config,!0,{store:this.store,checkpointer:this.checkpointer,step:(((Q=h.metadata)==null?void 0:Q.step)??-1)+1}),re=(h.pendingWrites??[]).filter(ie=>ie[0]===Ur).map(ie=>ie.slice(1));re.length>0&&Hn(h.checkpoint,I,[{name:Ps,writes:re,triggers:[]}],void 0,this.triggerToNodes);for(const[ie,E,v]of h.pendingWrites)["__error__","__interrupt__",bl].includes(E)||q[ie]===void 0||q[ie].writes.push([E,v]);const ve=Object.values(q).filter(ie=>ie.writes.length>0);ve.length>0&&Hn(m,I,ve,void 0,this.triggerToNodes)}const T=Object.values(m.versions_seen).map(q=>Object.values(q)).flat().find(q=>!!q),x=[];if(d.length===1){let{values:q,asNode:re,taskId:ve}=d[0];if(re===void 0&&Object.keys(this.nodes).length===1)[re]=Object.keys(this.nodes);else if(re===void 0&&T===void 0)typeof this.inputChannels=="string"&&this.nodes[this.inputChannels]!==void 0&&(re=this.inputChannels);else if(re===void 0){const ie=Object.entries(m.versions_seen).map(([E,v])=>Object.values(v).map(N=>[N,E])).flat().filter(([E,v])=>v!==Bt).sort(([E],[v])=>eI(E,v));ie&&(ie.length===1?re=ie[0][1]:ie[ie.length-1][0]!==ie[ie.length-2][0]&&(re=ie[ie.length-1][1]))}if(re===void 0)throw new ct('Ambiguous update, specify "asNode"');x.push({values:q,asNode:re,taskId:ve})}else for(const{asNode:q,values:re,taskId:ve}of d){if(q==null)throw new ct('"asNode" is required when applying multiple updates');x.push({values:re,asNode:q,taskId:ve})}const A=[];for(const{asNode:q,values:re,taskId:ve}of x){if(this.nodes[q]===void 0)throw new ct(`Node "${q.toString()}" does not exist`);const ie=this.nodes[q].getWriters();if(!ie.length)throw new ct(`No writers found for node "${q.toString()}"`);A.push({name:q,input:re,proc:ie.length>1?Jn.from(ie,{omitSequenceTags:!0}):ie[0],writes:[],triggers:[Bt],id:ve??mi("__interrupt__",m.id),writers:[]})}for(const q of A)await q.proc.invoke(q.input,et({...f,store:(f==null?void 0:f.store)??this.store},{runName:f.runName??`${this.getName()}UpdateState`,configurable:{[Hs]:re=>q.writes.push(...re),[Ra]:(re,ve=!1)=>Ol(m,I,q,re,ve)}}));for(const q of A){const re=q.writes.filter(ve=>ve[0]!==hs);h!==void 0&&re.length>0&&await r.putWrites(w,re,q.id)}Hn(m,I,A,r.getNextVersion.bind(this.checkpointer),this.triggerToNodes);const M=kl(_,m.channel_versions),O=await r.put(w,ya(m,I,y+1),{source:"update",step:y+1,parents:((se=h==null?void 0:h.metadata)==null?void 0:se.parents)??{}},M);for(const q of A){const re=q.writes.filter(ve=>ve[0]===hs);re.length>0&&await r.putWrites(O,re,q.id)}return oa(O,h?h.metadata:void 0)};let i=e;for(const{updates:l}of n)i=await a(i,l);return i}async updateState(e,n,r){return this.bulkUpdateState(e,[{updates:[{values:n,asNode:r}]}])}_defaults(e){var I,T,x;const{debug:n,streamMode:r,inputKeys:s,outputKeys:a,interruptAfter:i,interruptBefore:o,...c}=e;let u=!0;const l=n!==void 0?n:this.debug;let d=a;d===void 0?d=this.streamChannelsAsIs:Ub(d,this.channels);let f=s;f===void 0?f=this.inputChannels:Ub(f,this.channels);const h=o??this.interruptBefore??[],m=i??this.interruptAfter??[];let _;r!==void 0?(_=Array.isArray(r)?r:[r],u=typeof r=="string"):(((I=e.configurable)==null?void 0:I.__pregel_task_id)!==void 0?_=["values"]:_=this.streamMode,u=!0);let y;if(this.checkpointer===!1)y=void 0;else if(e!==void 0&&((T=e.configurable)==null?void 0:T.__pregel_checkpointer)!==void 0)y=e.configurable[us];else{if(this.checkpointer===!0)throw new Error("checkpointer: true cannot be used for root graphs.");y=this.checkpointer}const w=e.store??this.store,g=e.cache??this.cache;if(e.durability!=null&&e.checkpointDuring!=null)throw new Error("Cannot use both `durability` and `checkpointDuring` at the same time.");const b=(()=>{if(e.checkpointDuring!=null)return e.checkpointDuring===!1?"exit":"async"})(),S=e.durability??b??((x=e==null?void 0:e.configurable)==null?void 0:x.__pregel_durability)??"async";return[l,_,f,d,c,h,m,y,w,u,g,S]}async stream(e,n){var i;const r=new AbortController,s={recursionLimit:(i=this.config)==null?void 0:i.recursionLimit,...n,signal:Ad(n==null?void 0:n.signal,r.signal).signal},a=await super.stream(e,s);return new Pb((n==null?void 0:n.encoding)==="text/event-stream"?cz(a):a,r)}streamEvents(e,n,r){var i,o;const s=new AbortController,a={recursionLimit:(i=this.config)==null?void 0:i.recursionLimit,...n,callbacks:H3((o=this.config)==null?void 0:o.callbacks,n==null?void 0:n.callbacks),signal:Ad(n==null?void 0:n.signal,s.signal).signal};return new Pb(super.streamEvents(e,a,r),s)}async _validateInput(e){return e}async _validateContext(e){return e}async*_streamIterator(e,n){var $;const r="version"in(n??{})?void 0:(n==null?void 0:n.encoding)??void 0,s=n==null?void 0:n.subgraphs,a=aI(this.config,n);if(a.recursionLimit===void 0||a.recursionLimit<1)throw new Error('Passed "recursionLimit" must be at least 1.');if(this.checkpointer!==void 0&&this.checkpointer!==!1&&a.configurable===void 0)throw new Error('Checkpointer requires one or more of the following "configurable" keys: "thread_id", "checkpoint_ns", "checkpoint_id"');const i=await this._validateInput(e),{runId:o,...c}=a,[u,l,,d,f,h,m,_,y,w,g,b]=this._defaults(c);f.metadata={ls_integration:"langgraph",...f.metadata},typeof f.context<"u"?f.context=await this._validateContext(f.context):f.configurable=await this._validateContext(f.configurable);const S=new bI({modes:new Set(l)});if(this.checkpointer===!0){f.configurable??(f.configurable={});const H=f.configurable.checkpoint_ns??"";f.configurable[ls]=H.split("|").map(J=>J.split(":")[0]).join("|")}if(l.includes("messages")){const H=new pz(Y=>S.push(Y)),{callbacks:J}=f;if(J===void 0)f.callbacks=[H];else if(Array.isArray(J))f.callbacks=J.concat(H);else{const Y=J.copy();Y.addHandler(H,!0),f.callbacks=Y}}if(l.includes("tools")){const H=new az(Y=>S.push(Y)),{callbacks:J}=f;if(J===void 0)f.callbacks=[H];else if(Array.isArray(J))f.callbacks=J.concat(H);else{const Y=J.copy();Y.addHandler(H,!0),f.callbacks=Y}}f.writer??(f.writer=H=>{var Y,me,te;if(!l.includes("custom"))return;const J=(te=(me=(Y=g3())==null?void 0:Y.configurable)==null?void 0:me[ls])==null?void 0:te.split("|").slice(0,-1);S.push([J??[],"custom",H])}),f.interrupt??(f.interrupt=this.userInterrupt??vz),f.serverInfo==null&&(f.serverInfo=Az(f));const I=await(($=await un._configureSync(f==null?void 0:f.callbacks,void 0,f==null?void 0:f.tags,void 0,f==null?void 0:f.metadata,void 0,{tracerInheritableMetadata:kz(f)}))==null?void 0:$.handleChainStart(this.toJSON(),z3(e,"input"),o,void 0,void 0,void 0,(f==null?void 0:f.runName)??this.getName())),T=v_(this.channels);let x,A;const O=(async()=>{var H,J,Y;try{x=await hz.initialize({input:i,config:f,checkpointer:_,nodes:this.nodes,channelSpecs:T,outputKeys:d,streamKeys:this.streamChannelsAsIs,store:y,cache:g,stream:S,interruptAfter:m,interruptBefore:h,manager:I,debug:this.debug,triggerToNodes:this.triggerToNodes,durability:b});const me=new yz({loop:x,nodeFinished:(H=f.configurable)==null?void 0:H[V4]});n!=null&&n.subgraphs&&(x.config.configurable={...x.config.configurable,[Wg]:x.stream}),await this._runLoop({loop:x,runner:me,debug:u,config:f}),b==="sync"&&await Promise.all((x==null?void 0:x.checkpointerPromises)??[])}catch(me){A=me}finally{try{x&&(await((J=x.store)==null?void 0:J.stop()),await((Y=x.cache)==null?void 0:Y.stop())),await Promise.all((x==null?void 0:x.checkpointerPromises)??[])}catch(me){A=A??me}A?S.error(A):S.close()}})();try{for await(const H of S){if(H===void 0)throw new Error("Data structure error.");const[J,Y,me]=H;if(l.includes(Y)){if(r==="text/event-stream"){s?yield[J,Y,me]:yield[null,Y,me];continue}s&&!w?yield[J,Y,me]:w?s?yield[J,me]:yield me:yield[Y,me]}}}catch(H){throw await(I==null?void 0:I.handleChainError(A)),H}finally{await O}await(I==null?void 0:I.handleChainEnd((x==null?void 0:x.output)??{},o,void 0,void 0,void 0))}async invoke(e,n){const r=(n==null?void 0:n.streamMode)??"values",s={...n,outputKeys:(n==null?void 0:n.outputKeys)??this.outputChannels,streamMode:r,encoding:void 0},a=[],i=await this.stream(e,s),o=[];let c;for await(const u of i)r==="values"?mE(u)?o.push(u[Bt]):c=u:a.push(u);if(r==="values"){if(o.length>0){const u=o.flat(1);if(c==null)return{[Bt]:u};if(typeof c=="object")return{...c,[Bt]:u}}return c}return a}async _runLoop(e){const{loop:n,runner:r,debug:s,config:a}=e;let i;try{for(;await n.tick({inputKeys:this.inputChannels});){for(const{task:o}of await n._matchCachedWrites())n._outputWrites(o.id,o.writes,!0);s&&rz(n.checkpointMetadata.step,n.channels,this.streamChannelsList),s&&wI(n.step,Object.values(n.tasks)),await r.tick({timeout:this.stepTimeout,retryPolicy:this.retryPolicy,onStepWrite:(o,c)=>{s&&sz(o,c,this.streamChannelsList)},maxConcurrency:a.maxConcurrency,signal:a.signal})}if(n.status==="out_of_steps")throw new J4([`Recursion limit of ${a.recursionLimit} reached`,"without hitting a stop condition. You can increase the",'limit by setting the "recursionLimit" config key.'].join(" "),{lc_error_code:"GRAPH_RECURSION_LIMIT"})}catch(o){if(i=o,!await n.finishAndHandleError(i))throw o}finally{i===void 0&&await n.finishAndHandleError()}}async clearCache(){var e;await((e=this.cache)==null?void 0:e.clear([]))}};function Az(t){const e=t.metadata??{},n=t.configurable??{},r=e.assistant_id,s=e.graph_id,a=n.langgraph_auth_user;let i;if(a!=null&&typeof a=="object"&&"identity"in a&&(i=a),r!=null||s!=null||i!=null)return{assistantId:r!=null?String(r):"",graphId:s!=null?String(s):"",user:i}}const Iz=new Set(["key","token","secret","password","auth"]);function xz(t,e){const n=t.toLowerCase();let r=!1;for(const s of Iz)if(n.includes(s)){r=!0;break}return t.startsWith("__")||!(typeof e=="string"||typeof e=="number"||typeof e=="boolean")||r}function kz(t){const e=t.configurable;if(!e)return;const n={};for(const[r,s]of Object.entries(e))xz(r,s)||(n[r]=s);return Object.keys(n).length>0?n:void 0}const Oz=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;function Db(t){return typeof t=="string"&&Oz.test(t)}var qt=[];for(var Nf=0;Nf<256;++Nf)qt.push((Nf+256).toString(16).slice(1));function Cz(t,e=0){return(qt[t[e+0]]+qt[t[e+1]]+qt[t[e+2]]+qt[t[e+3]]+"-"+qt[t[e+4]]+qt[t[e+5]]+"-"+qt[t[e+6]]+qt[t[e+7]]+"-"+qt[t[e+8]]+qt[t[e+9]]+"-"+qt[t[e+10]]+qt[t[e+11]]+qt[t[e+12]]+qt[t[e+13]]+qt[t[e+14]]+qt[t[e+15]]).toLowerCase()}var Uu,Rz=new Uint8Array(16);function $z(){if(!Uu&&(Uu=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!Uu))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Uu(Rz)}var Nz=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);const Fb={randomUUID:Nz};function Bb(t,e,n){if(Fb.randomUUID&&!t)return Fb.randomUUID();t=t||{};var r=t.random||(t.rng||$z)();return r[6]=r[6]&15|64,r[8]=r[8]&63|128,Cz(r)}var EI=class{constructor(t){p(this,"path");p(this,"ends");Fe.isRunnable(t.path)?this.path=t.path:this.path=en(t.path),this.ends=Array.isArray(t.pathMap)?t.pathMap.reduce((e,n)=>(e[n]=n,e),{}):t.pathMap}run(t,e){return wn.registerWriter(new aa({name:"<branch_run>",trace:!1,func:async(n,r)=>{try{return await this._route(n,r,t,e)}catch(s){throw s.name===_E.unminifiable_name&&console.warn(`[WARN]: 'NodeInterrupt' thrown in conditional edge. This is likely a bug in your graph implementation.
307
- NodeInterrupt should only be thrown inside a node, not in edge conditions.`),s}}}))}async _route(t,e,n,r){let s=await this.path.invoke(r?r(e):t,e);Array.isArray(s)||(s=[s]);let a;if(this.ends?a=s.map(i=>Sn(i)?i:this.ends[i]):a=s,a.some(i=>!i))throw new Error("Branch condition returned unknown or null destination");if(a.filter(Sn).some(i=>i.node==="__end__"))throw new ct("Cannot send a packet to the END node");return await n(a,e)??t}},Pz=class{constructor(){p(this,"nodes");p(this,"edges");p(this,"branches");p(this,"entryPoint");p(this,"compiled",!1);this.nodes={},this.edges=new Set,this.branches={}}warnIfCompiled(t){this.compiled&&console.warn(t)}get allEdges(){return this.edges}addNode(...t){function e(r){return r.length>=1&&typeof r[0]!="string"}const n=e(t)?Array.isArray(t[0])?t[0]:Object.entries(t[0]):[[t[0],t[1],t[2]]];if(n.length===0)throw new Error("No nodes provided in `addNode`");for(const[r,s,a]of n){for(const o of["|",":"])if(r.includes(o))throw new Error(`"${o}" is a reserved character and is not allowed in node names.`);if(this.warnIfCompiled("Adding a node to a graph that has already been compiled. This will not be reflected in the compiled graph."),r in this.nodes)throw new Error(`Node \`${r}\` already present.`);if(r==="__end__")throw new Error(`Node \`${r}\` is reserved.`);const i=en(s);this.nodes[r]={runnable:i,metadata:a==null?void 0:a.metadata,subgraphs:S_(i)?[i]:a==null?void 0:a.subgraphs,ends:a==null?void 0:a.ends}}return this}addEdge(t,e){if(this.warnIfCompiled("Adding an edge to a graph that has already been compiled. This will not be reflected in the compiled graph."),t==="__end__")throw new Error("END cannot be a start node");if(e==="__start__")throw new Error("START cannot be an end node");if(Array.from(this.edges).some(([n])=>n===t)&&!("channels"in this))throw new Error(`Already found path for ${t}. For multiple edges, use StateGraph.`);return this.edges.add([t,e]),this}addConditionalEdges(t,e,n){var a,i;const r=typeof t=="object"?t:{source:t,path:e,pathMap:n};this.warnIfCompiled("Adding an edge to a graph that has already been compiled. This will not be reflected in the compiled graph."),Fe.isRunnable(r.path)||(r.path=en(r.path));const s=r.path.getName()==="RunnableLambda"?"condition":r.path.getName();if(this.branches[r.source]&&this.branches[r.source][s])throw new Error(`Condition \`${s}\` already present for node \`${t}\``);return(a=this.branches)[i=r.source]??(a[i]={}),this.branches[r.source][s]=new EI(r),this}setEntryPoint(t){return this.warnIfCompiled("Setting the entry point of a graph that has already been compiled. This will not be reflected in the compiled graph."),this.addEdge(Xt,t)}setFinishPoint(t){return this.warnIfCompiled("Setting a finish point of a graph that has already been compiled. This will not be reflected in the compiled graph."),this.addEdge(t,dt)}compile({checkpointer:t,interruptBefore:e,interruptAfter:n,name:r}={}){this.validate([...Array.isArray(e)?e:[],...Array.isArray(n)?n:[]]);const s=new AI({builder:this,checkpointer:t,interruptAfter:n,interruptBefore:e,autoValidate:!1,nodes:{},channels:{[Xt]:new zi,[dt]:new zi},inputChannels:Xt,outputChannels:dt,streamChannels:[],streamMode:"values",name:r});for(const[a,i]of Object.entries(this.nodes))s.attachNode(a,i);for(const[a,i]of this.edges)s.attachEdge(a,i);for(const[a,i]of Object.entries(this.branches))for(const[o,c]of Object.entries(i))s.attachBranch(a,o,c);return s.validate()}validate(t){const e=new Set([...this.allEdges].map(([r,s])=>r));for(const[r]of Object.entries(this.branches))e.add(r);for(const r of e)if(r!=="__start__"&&!(r in this.nodes))throw new Error(`Found edge starting at unknown node \`${r}\``);const n=new Set([...this.allEdges].map(([r,s])=>s));for(const[r,s]of Object.entries(this.branches))for(const a of Object.values(s))if(a.ends!=null)for(const i of Object.values(a.ends))n.add(i);else{n.add(dt);for(const i of Object.keys(this.nodes))i!==r&&n.add(i)}for(const r of Object.values(this.nodes))for(const s of r.ends??[])n.add(s);for(const r of Object.keys(this.nodes))if(!n.has(r))throw new Y4([`Node \`${r}\` is not reachable.`,"","If you are returning Command objects from your node,",'make sure you are passing names of potential destination nodes as an "ends" array','into ".addNode(..., { ends: ["node1", "node2"] })".'].join(`
308
- `),{lc_error_code:"UNREACHABLE_NODE"});for(const r of n)if(r!=="__end__"&&!(r in this.nodes))throw new Error(`Found edge ending at unknown node \`${r}\``);if(t){for(const r of t)if(!(r in this.nodes))throw new Error(`Interrupt node \`${r}\` is not present`)}this.compiled=!0}},AI=class extends Ez{constructor({builder:e,...n}){super(n);p(this,"builder");this.builder=e}attachNode(e,n){this.channels[e]=new zi,this.nodes[e]=new xc({channels:[],triggers:[],metadata:n.metadata,subgraphs:n.subgraphs,ends:n.ends}).pipe(n.runnable).pipe(new wn([{channel:e,value:Na}],[Cn])),this.streamChannels.push(e)}attachEdge(e,n){if(n==="__end__"){if(e==="__start__")throw new Error("Cannot have an edge from START to END");this.nodes[e].writers.push(new wn([{channel:dt,value:Na}],[Cn]))}else this.nodes[n].triggers.push(e),this.nodes[n].channels.push(e)}attachBranch(e,n,r){e==="__start__"&&!this.nodes.__start__&&(this.nodes[Xt]=Sz.subscribeTo(Xt,{tags:[Cn]})),this.nodes[e].pipe(r.run(a=>new wn(a.map(i=>Sn(i)?i:{channel:i==="__end__"?dt:`branch:${e}:${n}:${i}`,value:Na}),[Cn])));const s=r.ends?Object.values(r.ends):Object.keys(this.nodes);for(const a of s)if(a!=="__end__"){const i=`branch:${e}:${n}:${a}`;this.channels[i]=new zi,this.nodes[a].triggers.push(i),this.nodes[a].channels.push(i)}}async getGraphAsync(e){var u,l,d,f;const n=e==null?void 0:e.xray,r=new bc,s={[Xt]:r.addNode({schema:Ru()},Xt)},a={};let i={};n&&(i=Object.fromEntries((await Ms(this.getSubgraphsAsync())).filter(h=>zb(h[1]))));function o(h,m,_,y=!1){if(m==="__end__"&&a.__end__===void 0&&(a[dt]=r.addNode({schema:Ru()},dt)),s[h]!==void 0){if(a[m]===void 0)throw new Error(`End node ${m} not found!`);return r.addEdge(s[h],a[m],_!==m?_:void 0,y)}}for(const[h,m]of Object.entries(this.builder.nodes)){const _=sn(h),y=m.runnable,w=m.metadata??{};if((u=this.interruptBefore)!=null&&u.includes(h)&&((l=this.interruptAfter)!=null&&l.includes(h))?w.__interrupt="before,after":(d=this.interruptBefore)!=null&&d.includes(h)?w.__interrupt="before":(f=this.interruptAfter)!=null&&f.includes(h)&&(w.__interrupt="after"),n){const g=typeof n=="number"?n-1:n,b=i[h]!==void 0?await i[h].getGraphAsync({...e,xray:g}):y.getGraph(e);if(b.trimFirstNode(),b.trimLastNode(),Object.keys(b.nodes).length>1){let T=function(A){return A?A.lc_runnable:!1},x=function(A,M){if(A!==void 0&&!Db(A))return A;if(T(M))try{let O=M.getName();return O=O.startsWith("Runnable")?O.slice(8):O,O}catch{return M.getName()}else return M.name??"UnknownSchema"};const[S,I]=r.extend(b,_);if(S===void 0)throw new Error(`Could not extend subgraph "${h}" due to missing entrypoint.`);I!==void 0&&(s[_]={name:x(I.id,I.data),...I}),a[_]={name:x(S.id,S.data),...S}}else{const S=r.addNode(y,_,w);s[_]=S,a[_]=S}}else{const g=r.addNode(y,_,w);s[_]=g,a[_]=g}}const c=[...this.builder.allEdges].sort(([h],[m])=>h<m?-1:m>h?1:0);for(const[h,m]of c)o(sn(h),sn(m));for(const[h,m]of Object.entries(this.builder.branches)){const _={...Object.fromEntries(Object.keys(this.builder.nodes).filter(y=>y!==h).map(y=>[sn(y),sn(y)])),[dt]:dt};for(const y of Object.values(m)){let w;y.ends!==void 0?w=y.ends:w=_;for(const[g,b]of Object.entries(w))o(sn(h),sn(b),g,!0)}}for(const[h,m]of Object.entries(this.builder.nodes))if(m.ends!==void 0)for(const _ of m.ends)o(sn(h),sn(_),void 0,!0);return r}getGraph(e){var u,l,d,f;const n=e==null?void 0:e.xray,r=new bc,s={[Xt]:r.addNode({schema:Ru()},Xt)},a={};let i={};n&&(i=Object.fromEntries(Po(this.getSubgraphs()).filter(h=>zb(h[1]))));function o(h,m,_,y=!1){return m==="__end__"&&a.__end__===void 0&&(a[dt]=r.addNode({schema:Ru()},dt)),r.addEdge(s[h],a[m],_!==m?_:void 0,y)}for(const[h,m]of Object.entries(this.builder.nodes)){const _=sn(h),y=m.runnable,w=m.metadata??{};if((u=this.interruptBefore)!=null&&u.includes(h)&&((l=this.interruptAfter)!=null&&l.includes(h))?w.__interrupt="before,after":(d=this.interruptBefore)!=null&&d.includes(h)?w.__interrupt="before":(f=this.interruptAfter)!=null&&f.includes(h)&&(w.__interrupt="after"),n){const g=typeof n=="number"?n-1:n,b=i[h]!==void 0?i[h].getGraph({...e,xray:g}):y.getGraph(e);if(b.trimFirstNode(),b.trimLastNode(),Object.keys(b.nodes).length>1){let T=function(A){return A?A.lc_runnable:!1},x=function(A,M){if(A!==void 0&&!Db(A))return A;if(T(M))try{let O=M.getName();return O=O.startsWith("Runnable")?O.slice(8):O,O}catch{return M.getName()}else return M.name??"UnknownSchema"};const[S,I]=r.extend(b,_);if(S===void 0)throw new Error(`Could not extend subgraph "${h}" due to missing entrypoint.`);I!==void 0&&(s[_]={name:x(I.id,I.data),...I}),a[_]={name:x(S.id,S.data),...S}}else{const S=r.addNode(y,_,w);s[_]=S,a[_]=S}}else{const g=r.addNode(y,_,w);s[_]=g,a[_]=g}}const c=[...this.builder.allEdges].sort(([h],[m])=>h<m?-1:m>h?1:0);for(const[h,m]of c)o(sn(h),sn(m));for(const[h,m]of Object.entries(this.builder.branches)){const _={...Object.fromEntries(Object.keys(this.builder.nodes).filter(y=>y!==h).map(y=>[sn(y),sn(y)])),[dt]:dt};for(const y of Object.values(m)){let w;y.ends!==void 0?w=y.ends:w=_;for(const[g,b]of Object.entries(w))o(sn(h),sn(b),g,!0)}}return r}};function zb(t){return typeof t.attachNode=="function"&&typeof t.attachEdge=="function"}function sn(t){return t==="subgraph"?`"${t}"`:t}const Sa=(t,e)=>t.size===e.size&&[...t].every(n=>e.has(n));var Mz=class II extends sa{constructor(n){super();p(this,"lc_graph_name","NamedBarrierValue");p(this,"names");p(this,"seen");this.names=n,this.seen=new Set}fromCheckpoint(n){const r=new II(this.names);return typeof n<"u"&&(r.seen=new Set(n)),r}update(n){let r=!1;for(const s of n)if(this.names.has(s))this.seen.has(s)||(this.seen.add(s),r=!0);else throw new ct(`Value ${JSON.stringify(s)} not in names ${JSON.stringify(this.names)}`);return r}get(){if(!Sa(this.names,this.seen))throw new Vt}checkpoint(){return[...this.seen]}consume(){return this.seen&&this.names&&Sa(this.seen,this.names)?(this.seen=new Set,!0):!1}isAvailable(){return!!this.names&&Sa(this.names,this.seen)}},Lz=class xI extends sa{constructor(n){super();p(this,"lc_graph_name","NamedBarrierValueAfterFinish");p(this,"names");p(this,"seen");p(this,"finished");this.names=n,this.seen=new Set,this.finished=!1}fromCheckpoint(n){const r=new xI(this.names);if(typeof n<"u"){const[s,a]=n;r.seen=new Set(s),r.finished=a}return r}update(n){let r=!1;for(const s of n)if(this.names.has(s)&&!this.seen.has(s))this.seen.add(s),r=!0;else if(!this.names.has(s))throw new ct(`Value ${JSON.stringify(s)} not in names ${JSON.stringify(this.names)}`);return r}get(){if(!this.finished||!Sa(this.names,this.seen))throw new Vt}checkpoint(){return[[...this.seen],this.finished]}consume(){return this.finished&&this.seen&&this.names&&Sa(this.seen,this.names)?(this.seen=new Set,this.finished=!1,!0):!1}finish(){return!this.finished&&this.names&&Sa(this.names,this.seen)?(this.finished=!0,!0):!1}isAvailable(){return this.finished&&!!this.names&&Sa(this.names,this.seen)}};function Lo(t){return typeof t=="object"&&t!==null&&"~standard"in t&&typeof t["~standard"]=="object"&&t["~standard"]!==null&&"validate"in t["~standard"]}function jz(t){return typeof t=="object"&&t!==null&&"~standard"in t&&typeof t["~standard"]=="object"&&t["~standard"]!==null&&"jsonSchema"in t["~standard"]}function qa(t){if(jz(t))try{return t["~standard"].jsonSchema.input({target:"draft-07"})}catch{return}}function Ka(t){if(t!=null&&Lo(t))try{const e=t["~standard"].validate(void 0);if(e&&typeof e=="object"&&!("then"in e&&typeof e.then=="function")){const n=e;if(!n.issues){const r=n.value;return()=>r}}}catch{}}const Pf=Symbol.for("langgraph.channel.missing");var Uz=class kI extends sa{constructor(n){super();p(this,"lc_graph_name","UntrackedValue");p(this,"guard");p(this,"_value",Pf);p(this,"initialValueFactory");this.guard=(n==null?void 0:n.guard)??!0,this.initialValueFactory=n==null?void 0:n.initialValueFactory,this.initialValueFactory&&(this._value=this.initialValueFactory())}fromCheckpoint(n){return new kI({guard:this.guard,initialValueFactory:this.initialValueFactory})}update(n){if(n.length===0)return!1;if(n.length!==1&&this.guard)throw new ct("UntrackedValue(guard=true) can receive only one value per step. Use guard=false if you want to store any one of multiple values.",{lc_error_code:"INVALID_CONCURRENT_GRAPH_UPDATE"});return this._value=n[n.length-1],!0}get(){if(this._value===Pf)throw new Vt;return this._value}checkpoint(){}isAvailable(){return this._value!==Pf}};const Mf=Symbol.for("langgraph.state.reduced_value");var U0,ai=(U0=Mf,class{constructor(t,e){p(this,U0,!0);p(this,"valueSchema");p(this,"inputSchema");p(this,"reducer");p(this,"jsonSchemaExtra");this.reducer=e.reducer,this.jsonSchemaExtra=e.jsonSchemaExtra,this.valueSchema=t,this.inputSchema="inputSchema"in e?e.inputSchema:t,this.jsonSchemaExtra=e.jsonSchemaExtra}static isInstance(t){return typeof t=="object"&&t!==null&&Mf in t&&t[Mf]===!0}});const Hb=Symbol.for("langgraph.state.untracked_value");var D0,io=(D0=Hb,class{constructor(t,e){p(this,D0,!0);p(this,"schema");p(this,"guard");this.schema=t,this.guard=(e==null?void 0:e.guard)??!0}static isInstance(t){return typeof t=="object"&&t!==null&&Hb in t}});const Lf=Symbol.for("langgraph.state.state_schema");var F0,Ta=(F0=Lf,class{constructor(t){p(this,F0,!0);this.fields=t}getChannels(){const t={};for(const[e,n]of Object.entries(this.fields))if(ai.isInstance(n)){const r=Ka(n.valueSchema);t[e]=new Sd(n.reducer,r)}else if(io.isInstance(n)){const r=n.schema?Ka(n.schema):void 0;t[e]=new Uz({guard:n.guard,initialValueFactory:r})}else if(Lo(n))t[e]=new gh(Ka(n));else throw new Error(`Invalid state field "${e}": must be a schema, ReducedValue, UntrackedValue, or ManagedValue`);return t}getJsonSchema(){const t={},e=[];for(const[n,r]of Object.entries(this.fields)){let s;if(ai.isInstance(r)?(s=qa(r.valueSchema),r.jsonSchemaExtra&&(s={...s??{},...r.jsonSchemaExtra})):io.isInstance(r)?s=r.schema?qa(r.schema):void 0:Lo(r)&&(s=qa(r)),s){t[n]=s;let a=!1;ai.isInstance(r)?a=Ka(r.valueSchema)!==void 0:io.isInstance(r)?a=r.schema?Ka(r.schema)!==void 0:!1:a=Ka(r)!==void 0,a||e.push(n)}}return{type:"object",properties:t,required:e.length>0?e:void 0}}getInputJsonSchema(){const t={};for(const[e,n]of Object.entries(this.fields)){let r;ai.isInstance(n)?(r=qa(n.inputSchema),n.jsonSchemaExtra&&(r={...r??{},...n.jsonSchemaExtra})):io.isInstance(n)?r=n.schema?qa(n.schema):void 0:Lo(n)&&(r=qa(n)),r&&(t[e]=r)}return{type:"object",properties:t}}getChannelKeys(){return Object.entries(this.fields).map(([t])=>t)}getAllKeys(){return Object.keys(this.fields)}async validateInput(t){if(t==null||typeof t!="object")return t;const e={};for(const[n,r]of Object.entries(t)){const s=this.fields[n];if(s===void 0){e[n]=r;continue}let a;if(ai.isInstance(s)?a=s.inputSchema:io.isInstance(s)?a=s.schema:Lo(s)&&(a=s),a){const i=await a["~standard"].validate(r);if(i.issues)throw new Error(`Validation failed for field "${n}": ${JSON.stringify(i.issues)}`);e[n]=i.value}else e[n]=r}return e}static isInstance(t){return typeof t=="object"&&t!==null&&Lf in t&&t[Lf]===!0}});function I_(t,e){const n=Array.isArray(t)?t:[t],r=Array.isArray(e)?e:[e],s=n.map(Vr),a=r.map(Vr);for(const l of s)(l.id===null||l.id===void 0)&&(l.id=Bb(),l.lc_kwargs.id=l.id);let i;for(let l=0;l<a.length;l+=1){const d=a[l];(d.id===null||d.id===void 0)&&(d.id=Bb(),d.lc_kwargs.id=d.id),xa.isInstance(d)&&d.id==="__remove_all__"&&(i=l)}if(i!=null)return a.slice(i+1);const o=[...s],c=new Map(o.map((l,d)=>[l.id,d])),u=new Set;for(const l of a){const d=c.get(l.id);if(d!==void 0)xa.isInstance(l)?u.add(l.id):(u.delete(l.id),o[d]=l);else{if(xa.isInstance(l))throw new Error(`Attempting to delete a message with an ID that doesn't exist ('${l.id}')`);c.set(l.id,o.length),o.push(l)}}return o.filter(l=>!u.has(l.id))}new ai(gm().default(()=>[]),{inputSchema:gm(),reducer:I_,jsonSchemaExtra:{langgraph_type:"messages",description:"A list of chat messages"}});var Dz=class{constructor(){p(this,"_map",new Map);p(this,"_extensionCache",new Map)}get(t){return this._map.get(t)}extend(t,e){const n=this.get(t);this._map.set(t,e(n))}remove(t){return this._map.delete(t),this}has(t){return this._map.has(t)}getChannelsForSchema(t){const e={},n=gc(t);for(const[r,s]of Object.entries(n)){const a=this.get(s);a!=null&&a.reducer?e[r]=new Sd(a.reducer.fn,a.default):e[r]=new gh(a==null?void 0:a.default)}return e}getExtendedChannelSchemas(t,e){if(Object.keys(e).length===0)return t;const n=Object.entries(e).filter(([,a])=>a===!0).sort(([a],[i])=>a.localeCompare(i)).map(([a,i])=>`${a}:${i}`).join("|"),r=this._extensionCache.get(n)??new Map;if(r.has(t))return r.get(t);let s=t;if(e.withReducerSchema||e.withJsonSchemaExtrasAsDescription){const a=Object.entries(gc(t)).map(([i,o])=>{var l;const c=this.get(o);let u=e.withReducerSchema?((l=c==null?void 0:c.reducer)==null?void 0:l.schema)??o:o;if(e.withJsonSchemaExtrasAsDescription&&(c!=null&&c.jsonSchemaExtra)){const d=Pi(u)??Pi(o),f=JSON.stringify({...c.jsonSchemaExtra,description:d});u=u.describe(`lg:${f}`)}return[i,u]});s=zT(t,Object.fromEntries(a)),xt(s)&&(s._def.unknownKeys="strip")}return e.asPartial&&(s=Ug(s)),r.set(t,s),this._extensionCache.set(n,r),s}};const OI=new Dz;function ii(t){return t==null?!1:!!(Ta.isInstance(t)||rr(t)||typeof t=="object"&&"lc_graph_name"in t&&t.lc_graph_name==="AnnotationRoot"||typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length>0&&Object.values(t).every(e=>typeof e=="function"||tI(e)))}function Fz(t){if(typeof t!="object"||t==null)return!1;const e=t,n="state"in e&&ii(e.state),r="stateSchema"in e&&ii(e.stateSchema),s="input"in e&&ii(e.input);return!(!n&&!r&&!s||"input"in e&&e.input!=null&&!ii(e.input)||"output"in e&&e.output!=null&&!ii(e.output))}const fs="__root__",Id=Symbol.for("langgraph.state.partial");var Bz=class extends Pz{constructor(e,n){super();p(this,"channels",{});p(this,"waitingEdges",new Set);p(this,"_schemaDefinition");p(this,"_schemaRuntimeDefinition");p(this,"_inputDefinition");p(this,"_inputRuntimeDefinition");p(this,"_outputDefinition");p(this,"_outputRuntimeDefinition");p(this,"_schemaDefinitions",new Map);p(this,"_metaRegistry",OI);p(this,"_configSchema");p(this,"_configRuntimeSchema");p(this,"_interrupt");p(this,"_writer");const r=this._normalizeToStateGraphInit(e,n),s=r.state??r.stateSchema??r.input;if(!s)throw new hf;const a=this._getChannelsFromSchema(s);this._schemaDefinition=a,Ta.isInstance(s)?this._schemaRuntimeDefinition=s:rr(s)&&(this._schemaRuntimeDefinition=s),r.input?Ta.isInstance(r.input)?this._inputRuntimeDefinition=r.input:rr(r.input)?this._inputRuntimeDefinition=r.input:this._inputRuntimeDefinition=Id:this._inputRuntimeDefinition=Id,r.output?Ta.isInstance(r.output)?this._outputRuntimeDefinition=r.output:rr(r.output)?this._outputRuntimeDefinition=r.output:this._outputRuntimeDefinition=this._schemaRuntimeDefinition:this._outputRuntimeDefinition=this._schemaRuntimeDefinition;const i=r.input?this._getChannelsFromSchema(r.input):a,o=r.output?this._getChannelsFromSchema(r.output):a;this._inputDefinition=i,this._outputDefinition=o,this._addSchema(this._schemaDefinition),this._addSchema(this._inputDefinition),this._addSchema(this._outputDefinition),r.context&&rr(r.context)&&(this._configRuntimeSchema=r.context),this._interrupt=r.interrupt,this._writer=r.writer}_normalizeToStateGraphInit(e,n){if(Fz(e)){if(rr(n)||Sm.isInstance(n))return{...e,context:n};const r=n;return{...e,input:e.input??(r==null?void 0:r.input),output:e.output??(r==null?void 0:r.output),context:e.context??(r==null?void 0:r.context),interrupt:e.interrupt??(r==null?void 0:r.interrupt),writer:e.writer??(r==null?void 0:r.writer),nodes:e.nodes??(r==null?void 0:r.nodes)}}if(ii(e)){if(rr(n)||Sm.isInstance(n))return{state:e,context:n};const r=n;return{state:e,input:r==null?void 0:r.input,output:r==null?void 0:r.output,context:r==null?void 0:r.context,interrupt:r==null?void 0:r.interrupt,writer:r==null?void 0:r.writer,nodes:r==null?void 0:r.nodes}}if(Vz(e))return{state:zz(e.channels)};throw new hf}_getChannelsFromSchema(e){if(Ta.isInstance(e))return e.getChannels();if(rr(e))return this._metaRegistry.getChannelsForSchema(e);if(typeof e=="object"&&"lc_graph_name"in e&&e.lc_graph_name==="AnnotationRoot")return e.spec;if(typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length>0)return e;throw new hf("Invalid schema type. Expected StateSchema, Zod object, AnnotationRoot, or StateDefinition.")}get allEdges(){return new Set([...this.edges,...Array.from(this.waitingEdges).flatMap(([e,n])=>e.map(r=>[r,n]))])}_addSchema(e){if(!this._schemaDefinitions.has(e)){this._schemaDefinitions.set(e,e);for(const[n,r]of Object.entries(e)){let s;if(typeof r=="function"?s=r():s=r,this.channels[n]!==void 0){if(!this.channels[n].equals(s)&&s.lc_graph_name!=="LastValue")throw new Error(`Channel "${n}" already exists with a different type.`)}else this.channels[n]=s}}}addNode(...e){function n(s){return s.length>=1&&typeof s[0]!="string"}const r=n(e)?Array.isArray(e[0])?e[0]:Object.entries(e[0]).map(([s,a])=>[s,a]):[[e[0],e[1],e[2]]];if(r.length===0)throw new Error("No nodes provided in `addNode`");for(const[s,a,i]of r){if(s in this.channels)throw new Error(`${s} is already being used as a state attribute (a.k.a. a channel), cannot also be used as a node name.`);for(const d of["|",":"])if(s.includes(d))throw new Error(`"${d}" is a reserved character and is not allowed in node names.`);if(this.warnIfCompiled("Adding a node to a graph that has already been compiled. This will not be reflected in the compiled graph."),s in this.nodes)throw new Error(`Node \`${s}\` already present.`);if(s==="__end__"||s==="__start__")throw new Error(`Node \`${s}\` is reserved.`);let o=this._schemaDefinition;(i==null?void 0:i.input)!==void 0&&(o=this._getChannelsFromSchema(i.input)),this._addSchema(o);let c;Fe.isRunnable(a)?c=a:typeof a=="function"?c=new aa({func:a,name:s,trace:!1}):c=en(a);let u=i==null?void 0:i.cachePolicy;typeof u=="boolean"&&(u=u?{}:void 0);const l={runnable:c,retryPolicy:i==null?void 0:i.retryPolicy,cachePolicy:u,metadata:i==null?void 0:i.metadata,input:o??this._schemaDefinition,subgraphs:S_(c)?[c]:i==null?void 0:i.subgraphs,ends:i==null?void 0:i.ends,defer:i==null?void 0:i.defer};this.nodes[s]=l}return this}addEdge(e,n){if(typeof e=="string")return super.addEdge(e,n);this.compiled&&console.warn("Adding an edge to a graph that has already been compiled. This will not be reflected in the compiled graph.");for(const r of e){if(r==="__end__")throw new Error("END cannot be a start node");if(!Object.keys(this.nodes).some(s=>s===r))throw new Error(`Need to add a node named "${r}" first`)}if(n==="__end__")throw new Error("END cannot be an end node");if(!Object.keys(this.nodes).some(r=>r===n))throw new Error(`Need to add a node named "${n}" first`);return this.waitingEdges.add([e,n]),this}addSequence(e){const n=Array.isArray(e)?e:Object.entries(e);if(n.length===0)throw new Error("Sequence requires at least one node.");let r;for(const[s,a,i]of n){if(s in this.nodes)throw new Error(`Node names must be unique: node with the name "${s}" already exists.`);const o=s;this.addNode(o,a,i),r!=null&&this.addEdge(r,o),r=o}return this}compile({checkpointer:e,store:n,cache:r,interruptBefore:s,interruptAfter:a,name:i,description:o}={}){this.validate([...Array.isArray(s)?s:[],...Array.isArray(a)?a:[]]);const c=Object.keys(this._schemaDefinitions.get(this._outputDefinition)),u=c.length===1&&c[0]===fs?fs:c,l=Object.keys(this.channels),d=l.length===1&&l[0]===fs?fs:l,f=this._interrupt,h=new Hz({builder:this,checkpointer:e,interruptAfter:a,interruptBefore:s,autoValidate:!1,nodes:{},channels:{...this.channels,[Xt]:new zi},inputChannels:Xt,outputChannels:u,streamChannels:d,streamMode:"updates",store:n,cache:r,name:i,description:o,userInterrupt:f});h.attachNode(Xt);for(const[m,_]of Object.entries(this.nodes))h.attachNode(m,_);h.attachBranch(Xt,pb,Vb(),{withReader:!1});for(const[m]of Object.entries(this.nodes))h.attachBranch(m,pb,Vb(),{withReader:!1});for(const[m,_]of this.edges)h.attachEdge(m,_);for(const[m,_]of this.waitingEdges)h.attachEdge(m,_);for(const[m,_]of Object.entries(this.branches))for(const[y,w]of Object.entries(_))h.attachBranch(m,y,w);return h.validate()}};function zz(t){const e={};for(const[n,r]of Object.entries(t))e[n]=Tm(r);return e}var Hz=class extends AI{constructor({description:e,...n}){super(n);p(this,"description");p(this,"_metaRegistry",OI);this.description=e}attachNode(e,n){let r;e==="__start__"?r=Object.entries(this.builder._schemaDefinitions.get(this.builder._inputDefinition)).map(([c])=>c):r=Object.keys(this.builder.channels);function s(c){if(Pt(c))return c.graph===Vn.PARENT?null:c._updateAsTuples();if(Array.isArray(c)&&c.length>0&&c.some(u=>Pt(u))){const u=[];for(const l of c)if(Pt(l)){if(l.graph===Vn.PARENT)continue;u.push(...l._updateAsTuples())}else u.push([fs,l]);return u}else if(c!=null)return[[fs,c]];return null}const a=e;function i(c){if(c){if(Pt(c))return c.graph===Vn.PARENT?null:c._updateAsTuples().filter(([u])=>r.includes(u));if(Array.isArray(c)&&c.length>0&&c.some(Pt)){const u=[];for(const l of c)if(Pt(l)){if(l.graph===Vn.PARENT)continue;u.push(...l._updateAsTuples().filter(([d])=>r.includes(d)))}else{const d=i(l);d&&u.push(...d??[])}return u}else{if(typeof c=="object"&&!Array.isArray(c))return Object.entries(c).filter(([u])=>r.includes(u));{const u=Array.isArray(c)?"array":typeof c;throw new ct(`Expected node "${a.toString()}" to return an object or an array containing at least one Command object, received ${u}`,{lc_error_code:"INVALID_GRAPH_NODE_RETURN_VALUE"})}}}else return null}const o=[{value:Na,mapper:new aa({func:r.length&&r[0]===fs?s:i,trace:!1,recurse:!1})}];if(e==="__start__")this.nodes[e]=new xc({tags:[Cn],triggers:[Xt],channels:[Xt],writers:[new wn(o,[Cn])]});else{const c=(n==null?void 0:n.input)??this.builder._schemaDefinition,u=Object.fromEntries(Object.keys(this.builder._schemaDefinitions.get(c)).map(f=>[f,f])),l=Object.keys(u).length===1&&fs in u,d=`branch:to:${e}`;this.channels[d]=n!=null&&n.defer?new u3:new zi(!1),this.nodes[e]=new xc({triggers:[d],channels:l?Object.keys(u):u,writers:[new wn(o,[Cn])],mapper:l?void 0:f=>Object.fromEntries(Object.entries(f).filter(([h])=>h in u)),bound:n==null?void 0:n.runnable,metadata:n==null?void 0:n.metadata,retryPolicy:n==null?void 0:n.retryPolicy,cachePolicy:n==null?void 0:n.cachePolicy,subgraphs:n==null?void 0:n.subgraphs,ends:n==null?void 0:n.ends})}}attachEdge(e,n){if(n!=="__end__"){if(typeof e=="string")this.nodes[e].writers.push(new wn([{channel:`branch:to:${n}`,value:null}],[Cn]));else if(Array.isArray(e)){const r=`join:${e.join("+")}:${n}`;this.channels[r]=this.builder.nodes[n].defer?new Lz(new Set(e)):new Mz(new Set(e)),this.nodes[n].triggers.push(r);for(const s of e)this.nodes[s].writers.push(new wn([{channel:r,value:s}],[Cn]))}}}attachBranch(e,n,r,s={withReader:!0}){const a=async(i,o)=>{const c=i.filter(l=>l!==dt);if(!c.length)return;const u=c.map(l=>Sn(l)?l:{channel:l==="__end__"?l:`branch:to:${l}`,value:e});await wn.doWrite({...o,tags:(o.tags??[]).concat([Cn])},u)};this.nodes[e].writers.push(r.run(a,s.withReader?i=>w3.doRead(i,this.streamChannels??this.outputChannels,!0):void 0))}async _validateInput(e){if(e==null)return e;const n=this.builder._inputRuntimeDefinition,r=this.builder._schemaRuntimeDefinition;if(Ta.isInstance(n)){if(Pt(e)){const a=e;return e.update&&(a.update=await n.validateInput(Array.isArray(e.update)?Object.fromEntries(e.update):e.update)),a}return await n.validateInput(e)}if(n===Id&&Ta.isInstance(r)){if(Pt(e)){const a=e;return e.update&&(a.update=await r.validateInput(Array.isArray(e.update)?Object.fromEntries(e.update):e.update)),a}return await r.validateInput(e)}const s=(()=>{const a=i=>{if(i!=null)return this._metaRegistry.getExtendedChannelSchemas(i,{withReducerSchema:!0})};if(rr(n))return a(n);if(n===Id)return rr(r)?Ug(a(r)):void 0})();if(Pt(e)){const a=e;return e.update&&s!=null&&(a.update=fl(s,e.update)),a}return s!=null?fl(s,e):e}isInterrupted(e){return mE(e)}async _validateContext(e){const n=this.builder._configRuntimeSchema;return rr(n)&&fl(n,e),e}};function Vz(t){return typeof t=="object"&&t!==null&&t.channels!==void 0}function Zz(t){if(Sn(t))return[t];const e=[];Pt(t)?e.push(t):Array.isArray(t)&&e.push(...t.filter(Pt));const n=[];for(const r of e){if(r.graph===Vn.PARENT)throw new yE(r);Sn(r.goto)||typeof r.goto=="string"?n.push(r.goto):Array.isArray(r.goto)&&n.push(...r.goto)}return n}function Vb(){return new EI({path:new aa({func:Zz,tags:[Cn],trace:!1,recurse:!1,name:"<control_branch>"})})}const CI=t=>Array.isArray(t)&&t.every(wt),Wz=t=>typeof t=="object"&&t!=null&&"messages"in t&&CI(t.messages),Gz=t=>typeof t=="object"&&t!=null&&"lg_tool_call"in t;var qz=class extends aa{constructor(e,n){const{name:r,tags:s,handleToolErrors:a}=n??{};super({name:r,tags:s,func:(i,o)=>this.run(i,o)});p(this,"tools");p(this,"handleToolErrors",!0);p(this,"trace",!1);this.tools=e,this.handleToolErrors=a??this.handleToolErrors}async runTool(e,n){const r=this.tools.find(s=>s.name===e.name);try{if(r===void 0)throw new Error(`Tool "${e.name}" not found.`);const s=await r.invoke({...e,type:"tool_call"},n);return wt(s)&&s.getType()==="tool"||Pt(s)?s:new Rn({status:"success",name:r.name,content:typeof s=="string"?s:JSON.stringify(s),tool_call_id:e.id})}catch(s){if(!this.handleToolErrors||va(s))throw s;return new Rn({status:"error",content:`Error: ${s.message}
309
- Please fix your mistakes.`,name:e.name,tool_call_id:e.id??""})}}async run(e,n){var i;let r;if(Gz(e))r=[await this.runTool(e.lg_tool_call,n)];else{let o;if(CI(e))o=e;else if(Wz(e))o=e.messages;else throw new Error("ToolNode only accepts BaseMessage[] or { messages: BaseMessage[] } as input.");const c=new Set(o.filter(l=>l.getType()==="tool").map(l=>l.tool_call_id));let u;for(let l=o.length-1;l>=0;l-=1){const d=o[l];if(or(d)){u=d;break}}if(u==null||!or(u))throw new Error("ToolNode only accepts AIMessages as input.");r=await Promise.all(((i=u.tool_calls)==null?void 0:i.filter(l=>l.id==null||!c.has(l.id)).map(l=>this.runTool(l,n)))??[])}if(!r.some(Pt))return Array.isArray(e)?r:{messages:r};const s=[];let a=null;for(const o of r)Pt(o)?o.graph===Vn.PARENT&&Array.isArray(o.goto)&&o.goto.every(c=>Sn(c))?a?a.goto.push(...o.goto):a=new Vn({graph:Vn.PARENT,goto:o.goto}):s.push(o):s.push(Array.isArray(e)?[o]:{messages:[o]});return a&&s.push(a),s}};const jf=/<name>(.*?)<\/name>/s,Uf=/<content>(.*?)<\/content>/s;function Kz(t){if(!(wt(t)&&(or(t)||Ci(t)&&ql(t)))||!t.name)return t;const{name:e}=t;if(typeof t.content=="string")return new De({...Object.keys(t.lc_kwargs??{}).length>0?t.lc_kwargs:t,content:`<name>${e}</name><content>${t.content}</content>`,name:void 0});const n=[];let r=0;for(const s of t.content)typeof s=="string"?(r+=1,n.push(`<name>${e}</name><content>${s}</content>`)):typeof s=="object"&&"type"in s&&s.type==="text"?(r+=1,n.push({...s,text:`<name>${e}</name><content>${s.text}</content>`})):n.push(s);return r||n.unshift({type:"text",text:`<name>${e}</name><content></content>`}),new De({...t.lc_kwargs,content:n,name:void 0})}function Jz(t){if(!or(t)||!t.content)return t;let e=[],n;if(Array.isArray(t.content))e=t.content.filter(r=>{if(r.type==="text"&&typeof r.text=="string"){const s=r.text.match(jf),a=r.text.match(Uf);return s&&(!a||a[1]==="")?(n=s[1],!1):!0}return!0}).map(r=>{if(r.type==="text"&&typeof r.text=="string"){const s=r.text.match(jf),a=r.text.match(Uf);return!s||!a?r:(n=s[1],{...r,text:a[1]})}return r});else{const r=t.content,s=r.match(jf),a=r.match(Uf);if(!s||!a)return t;n=s[1],e=a[1]}return new De({...Object.keys(t.lc_kwargs??{}).length>0?t.lc_kwargs:t,content:e,name:n})}function Zb(t,e){let n,r;if(e==="inline")n=Kz,r=Jz;else throw new Error(`Invalid agent name mode: ${e}. Needs to be one of: "inline"`);function s(a){return a.map(n)}return Jn.from([Ht.from(s),t,Ht.from(r)])}function Xz(t){if(typeof t=="string"||wt(t)&&t._getType()==="system")return t;if(typeof t=="function")return async e=>t(e.messages);if(Fe.isRunnable(t))return Ht.from(e=>e.messages).pipe(t);throw new Error(`Unexpected type for messageModifier: ${typeof t}`)}const Du="prompt";function Yz(t){let e;if(t==null)e=Ht.from(n=>n.messages).withConfig({runName:Du});else if(typeof t=="string"){const n=new Gn(t);e=Ht.from(r=>[n,...r.messages??[]]).withConfig({runName:Du})}else if(wt(t)&&t._getType()==="system")e=Ht.from(n=>[t,...n.messages]).withConfig({runName:Du});else if(typeof t=="function")e=Ht.from(t).withConfig({runName:Du});else if(Fe.isRunnable(t))e=t;else throw new Error(`Got unexpected type for 'prompt': ${typeof t}`);return e}function Om(t){return Fe.isRunnable(t)}function Wb(t,e,n){if([t,e,n].filter(s=>s!=null).length>1)throw new Error("Expected only one of prompt, stateModifier, or messageModifier, got multiple values");let r=t;return e!=null?r=e:n!=null&&(r=Xz(n)),Yz(r)}function Vi(t){return"invoke"in t&&typeof t.invoke=="function"&&"_modelType"in t}function Zi(t){return"_queuedMethodOperations"in t&&"_model"in t&&typeof t._model=="function"}function Gb(t){return Vi(t)?"bindTools"in t&&typeof t.bindTools=="function":!1}async function Qz(t,e){let n=t;if(Jn.isRunnableSequence(n)&&(n=n.steps.find(o=>Qt.isRunnableBinding(o)||Vi(o)||Zi(o))||n),Zi(n)&&(n=await n._model()),!Qt.isRunnableBinding(n))return!0;let r=n.kwargs!=null&&typeof n.kwargs=="object"&&"tools"in n.kwargs&&Array.isArray(n.kwargs.tools)?n.kwargs.tools??null:n.config!=null&&typeof n.config=="object"&&"tools"in n.config&&Array.isArray(n.config.tools)?n.config.tools??null:null;if(r!=null&&r.length===1&&"functionDeclarations"in r[0]&&(r=r[0].functionDeclarations),r==null)return!0;if(e.length!==r.length)throw new Error("Number of tools in the model.bindTools() and tools passed to createReactAgent must match");const s=new Set(e.flatMap(o=>Om(o)?o.name:[])),a=new Set;for(const o of r){let c;if("type"in o&&o.type==="function")c=o.function.name;else if("name"in o)c=o.name;else if("toolSpec"in o&&"name"in o.toolSpec)c=o.toolSpec.name;else continue;c&&a.add(c)}const i=[...s].filter(o=>!a.has(o));if(i.length>0)throw new Error(`Missing tools '${i}' in the model.bindTools().Tools in the model.bindTools() must match the tools passed to createReactAgent.`);return!1}const Df=(t,e)=>{if(Gb(t))return t.bindTools(e);if(Qt.isRunnableBinding(t)&&Gb(t.bound)){const n=t.bound.bindTools(e);return Qt.isRunnableBinding(n)?new Qt({bound:n.bound,config:{...t.config,...n.config},kwargs:{...t.kwargs,...n.kwargs},configFactories:n.configFactories??t.configFactories}):new Qt({bound:n,config:t.config,kwargs:t.kwargs,configFactories:t.configFactories})}return null};async function e5(t,e){const n=Df(t,e);if(n)return n;if(Zi(t)){const r=Df(await t._model(),e);if(r)return r}if(Jn.isRunnableSequence(t)){const r=t.steps.findIndex(s=>Qt.isRunnableBinding(s)||Vi(s)||Zi(s));if(r>=0){const s=Df(t.steps[r],e);if(s){const a=t.steps.slice();return a.splice(r,1,s),Jn.from(a)}}}throw new Error(`llm ${t} must define bindTools method.`)}async function t5(t){let e=t;if(Jn.isRunnableSequence(e)&&(e=e.steps.find(n=>Qt.isRunnableBinding(n)||Vi(n)||Zi(n))||e),Zi(e)&&(e=await e._model()),Qt.isRunnableBinding(e)&&(e=e.bound),!Vi(e))throw new Error(`Expected \`llm\` to be a ChatModel or RunnableBinding (e.g. llm.bind_tools(...)) with invoke() and generate() methods, got ${e.constructor.name}`);return e}const n5=()=>$a.Root({messages:$a({reducer:I_,default:()=>[]}),structuredResponse:$a}),r5=$a.Root({llmInputMessages:$a({reducer:(t,e)=>I_([],e),default:()=>[]})});function s5(t){const{llm:e,tools:n,messageModifier:r,stateModifier:s,prompt:a,stateSchema:i,contextSchema:o,checkpointSaver:c,checkpointer:u,interruptBefore:l,interruptAfter:d,store:f,responseFormat:h,preModelHook:m,postModelHook:_,name:y,description:w,version:g="v1",includeAgentName:b}=t;let S,I;Array.isArray(n)?(S=n,I=new qz(S.filter(Om))):(S=n.tools,I=n);let T=null;const x=async P=>{if(T)return T;let z;await Qz(P,S)?z=await e5(P,S):z=P;const Q=Wb(a,s,r),se=b==="inline"?Zb(z,b):z;return T=Q.pipe(se),T},A=async(P,z,Q)=>{const se=await P(z,Q);return Wb(a,s,r).pipe(b==="inline"?Zb(se,b):se)},M=new Set(S.filter(Om).filter(P=>"returnDirect"in P&&P.returnDirect).map(P=>P.name));function O(P){const{messages:z,llmInputMessages:Q,...se}=P;return Q!=null&&Q.length>0?{messages:Q,...se}:{messages:z,...se}}const $=async(P,z)=>{if(h==null)throw new Error("Attempted to generate structured output with no passed response schema. Please contact us for help.");const Q=[...P.messages];let se;const q=typeof e=="function"?await e(P,z):await t5(e);if(!Vi(q))throw new Error(`Expected \`llm\` to be a ChatModel with .withStructuredOutput() method, got ${q.constructor.name}`);if(typeof h=="object"&&"schema"in h){const{prompt:re,schema:ve,...ie}=h;se=q.withStructuredOutput(ve,ie),re!=null&&Q.unshift(new Gn({content:re}))}else se=q.withStructuredOutput(h);return{structuredResponse:await se.invoke(Q,z)}},H=async(P,z)=>{const Q=await(typeof e=="function"?await A(e,P,z):await x(e)).invoke(O(P),z);return Q.name=y,Q.lc_kwargs.name=y,{messages:[Q]}},J=new Bz(i??n5(),o).addNode("tools",I);if(!("messages"in J._schemaDefinition))throw new Error("Missing required `messages` key in state schema.");const Y=J,me=P=>Object.fromEntries(Object.entries(P).filter(([z,Q])=>Q!=null));let te="agent",Be;return m!=null?(Y.addNode("pre_model_hook",m).addEdge("pre_model_hook","agent"),te="pre_model_hook",Be=$a.Root({...J._schemaDefinition,...r5.spec})):te="agent",Y.addNode("agent",H,{input:Be}).addEdge(Xt,te),_!=null&&Y.addNode("post_model_hook",_).addEdge("agent","post_model_hook").addConditionalEdges("post_model_hook",P=>{var ve;const{messages:z}=P,Q=new Set(z.filter(Ia).map(ie=>ie.tool_call_id));let se;for(let ie=z.length-1;ie>=0;ie-=1){const E=z[ie];if(or(E)){se=E;break}}const q=((ve=se==null?void 0:se.tool_calls)==null?void 0:ve.filter(ie=>ie.id==null||!Q.has(ie.id)))??[],re=z[z.length-1];return q.length>0?g==="v2"?q.map(ie=>new Ma("tools",{...P,lg_tool_call:ie})):"tools":re&&Ia(re)?te:h!=null?"generate_structured_response":dt},me({tools:"tools",[te]:te,generate_structured_response:h!=null?"generate_structured_response":null,[dt]:h!=null?null:dt})),h!==void 0&&J.addNode("generate_structured_response",$).addEdge("generate_structured_response",dt),_==null&&Y.addConditionalEdges("agent",P=>{var se;const{messages:z}=P,Q=z[z.length-1];return!or(Q)||!((se=Q.tool_calls)!=null&&se.length)?h!=null?"generate_structured_response":dt:g==="v2"?Q.tool_calls.map(q=>new Ma("tools",{...P,lg_tool_call:q})):"tools"},me({tools:"tools",generate_structured_response:h!=null?"generate_structured_response":null,[dt]:h!=null?null:dt})),M.size>0?Y.addConditionalEdges("tools",P=>{const z=P;for(let Q=z.messages.length-1;Q>=0;Q-=1){const se=z.messages[Q];if(!Ia(se))break;if(se.name!==void 0&&M.has(se.name))return dt}return te},me({[te]:te,[dt]:dt})):Y.addEdge("tools",te),Y.compile({checkpointer:u??c,interruptBefore:l,interruptAfter:d,store:f,name:y,description:w})}function Fu(t,e){return t.lc_error_code=e,t.message=`${t.message}
310
-
311
- Troubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${e}/
312
- `,t}function xe(t,e,n,r,s){if(typeof e=="function"?t!==e||!0:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return e.set(t,n),n}function R(t,e,n,r){if(n==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!r:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return n==="m"?r:n==="a"?r.call(t):r?r.value:e.get(t)}let RI=function(){const{crypto:t}=globalThis;if(t!=null&&t.randomUUID)return RI=t.randomUUID.bind(t),t.randomUUID();const e=new Uint8Array(1),n=t?()=>t.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,r=>(+r^n()&15>>+r/4).toString(16))};function Cm(t){return typeof t=="object"&&t!==null&&("name"in t&&t.name==="AbortError"||"message"in t&&String(t.message).includes("FetchRequestCanceledException"))}const Rm=t=>{if(t instanceof Error)return t;if(typeof t=="object"&&t!==null){try{if(Object.prototype.toString.call(t)==="[object Error]"){const e=new Error(t.message,t.cause?{cause:t.cause}:{});return t.stack&&(e.stack=t.stack),t.cause&&!e.cause&&(e.cause=t.cause),t.name&&(e.name=t.name),e}}catch{}try{return new Error(JSON.stringify(t))}catch{}}return new Error(t)};class he extends Error{}let hn=class $m extends he{constructor(e,n,r,s){super(`${$m.makeMessage(e,n,r)}`),this.status=e,this.headers=s,this.requestID=s==null?void 0:s.get("x-request-id"),this.error=n;const a=n;this.code=a==null?void 0:a.code,this.param=a==null?void 0:a.param,this.type=a==null?void 0:a.type}static makeMessage(e,n,r){const s=n!=null&&n.message?typeof n.message=="string"?n.message:JSON.stringify(n.message):n?JSON.stringify(n):r;return e&&s?`${e} ${s}`:e?`${e} status code (no body)`:s||"(no status code or body)"}static generate(e,n,r,s){if(!e||!s)return new _h({message:r,cause:Rm(n)});const a=n==null?void 0:n.error;return e===400?new $I(e,a,r,s):e===401?new NI(e,a,r,s):e===403?new PI(e,a,r,s):e===404?new MI(e,a,r,s):e===409?new LI(e,a,r,s):e===422?new jI(e,a,r,s):e===429?new UI(e,a,r,s):e>=500?new DI(e,a,r,s):new $m(e,a,r,s)}},Zn=class extends hn{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},_h=class extends hn{constructor({message:e,cause:n}){super(void 0,void 0,e||"Connection error.",void 0),n&&(this.cause=n)}},yh=class extends _h{constructor({message:e}={}){super({message:e??"Request timed out."})}},$I=class extends hn{},NI=class extends hn{},PI=class extends hn{},MI=class extends hn{},LI=class extends hn{},jI=class extends hn{},UI=class extends hn{},DI=class extends hn{};class FI extends he{constructor(){super("Could not parse response content as the length limit was reached")}}class BI extends he{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}class jo extends Error{constructor(e){super(e)}}class zI extends hn{constructor(e,n,r){let s="OAuth2 authentication error",a;if(n&&typeof n=="object"){const i=n;a=i.error;const o=i.error_description;o&&typeof o=="string"?s=o:a&&(s=a)}super(e,n,s,r),this.error_code=a}}class a5 extends he{constructor(e,n,r){super(e),this.provider=n,this.cause=r}}const i5=/^[a-z][a-z0-9+.-]*:/i,o5=t=>i5.test(t);let kn=t=>(kn=Array.isArray,kn(t)),qb=kn;function HI(t){return typeof t!="object"?{}:t??{}}function Kb(t){if(!t)return!0;for(const e in t)return!1;return!0}function c5(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function Rl(t){return t!=null&&typeof t=="object"&&!Array.isArray(t)}const u5=(t,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new he(`${t} must be an integer`);if(e<0)throw new he(`${t} must be a positive integer`);return e},l5=t=>{try{return JSON.parse(t)}catch{return}},ru=t=>new Promise(e=>setTimeout(e,t)),oi="6.35.0",d5=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function h5(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}const f5=()=>{var n;const t=h5();if(t==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":oi,"X-Stainless-OS":Xb(Deno.build.os),"X-Stainless-Arch":Jb(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:((n=Deno.version)==null?void 0:n.deno)??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":oi,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(t==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":oi,"X-Stainless-OS":Xb(globalThis.process.platform??"unknown"),"X-Stainless-Arch":Jb(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};const e=p5();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":oi,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":oi,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function p5(){if(typeof navigator>"u"||!navigator)return null;const t=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(const{key:e,pattern:n}of t){const r=n.exec(navigator.userAgent);if(r){const s=r[1]||0,a=r[2]||0,i=r[3]||0;return{browser:e,version:`${s}.${a}.${i}`}}}return null}const Jb=t=>t==="x32"?"x32":t==="x86_64"||t==="x64"?"x64":t==="arm"?"arm":t==="aarch64"||t==="arm64"?"arm64":t?`other:${t}`:"unknown",Xb=t=>(t=t.toLowerCase(),t.includes("ios")?"iOS":t==="android"?"Android":t==="darwin"?"MacOS":t==="win32"?"Windows":t==="freebsd"?"FreeBSD":t==="openbsd"?"OpenBSD":t==="linux"?"Linux":t?`Other:${t}`:"Unknown");let Yb;const m5=()=>Yb??(Yb=f5());function VI(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function ZI(...t){const e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...t)}function WI(t){let e=Symbol.asyncIterator in t?t[Symbol.asyncIterator]():t[Symbol.iterator]();return ZI({start(){},async pull(n){const{done:r,value:s}=await e.next();r?n.close():n.enqueue(s)},async cancel(){var n;await((n=e.return)==null?void 0:n.call(e))}})}function GI(t){if(t[Symbol.asyncIterator])return t;const e=t.getReader();return{async next(){try{const n=await e.read();return n!=null&&n.done&&e.releaseLock(),n}catch(n){throw e.releaseLock(),n}},async return(){const n=e.cancel();return e.releaseLock(),await n,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function Qb(t){var r,s;if(t===null||typeof t!="object")return;if(t[Symbol.asyncIterator]){await((s=(r=t[Symbol.asyncIterator]()).return)==null?void 0:s.call(r));return}const e=t.getReader(),n=e.cancel();e.releaseLock(),await n}const g5=({headers:t,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)}),qI="RFC3986",KI=t=>String(t),ev={RFC1738:t=>String(t).replace(/%20/g,"+"),RFC3986:KI},_5="RFC1738";let Nm=(t,e)=>(Nm=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),Nm(t,e));const Nr=(()=>{const t=[];for(let e=0;e<256;++e)t.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return t})(),Ff=1024,y5=(t,e,n,r,s)=>{if(t.length===0)return t;let a=t;if(typeof t=="symbol"?a=Symbol.prototype.toString.call(t):typeof t!="string"&&(a=String(t)),n==="iso-8859-1")return escape(a).replace(/%u[0-9a-f]{4}/gi,function(o){return"%26%23"+parseInt(o.slice(2),16)+"%3B"});let i="";for(let o=0;o<a.length;o+=Ff){const c=a.length>=Ff?a.slice(o,o+Ff):a,u=[];for(let l=0;l<c.length;++l){let d=c.charCodeAt(l);if(d===45||d===46||d===95||d===126||d>=48&&d<=57||d>=65&&d<=90||d>=97&&d<=122||s===_5&&(d===40||d===41)){u[u.length]=c.charAt(l);continue}if(d<128){u[u.length]=Nr[d];continue}if(d<2048){u[u.length]=Nr[192|d>>6]+Nr[128|d&63];continue}if(d<55296||d>=57344){u[u.length]=Nr[224|d>>12]+Nr[128|d>>6&63]+Nr[128|d&63];continue}l+=1,d=65536+((d&1023)<<10|c.charCodeAt(l)&1023),u[u.length]=Nr[240|d>>18]+Nr[128|d>>12&63]+Nr[128|d>>6&63]+Nr[128|d&63]}i+=u.join("")}return i};function w5(t){return!t||typeof t!="object"?!1:!!(t.constructor&&t.constructor.isBuffer&&t.constructor.isBuffer(t))}function tv(t,e){if(kn(t)){const n=[];for(let r=0;r<t.length;r+=1)n.push(e(t[r]));return n}return e(t)}const JI={brackets(t){return String(t)+"[]"},comma:"comma",indices(t,e){return String(t)+"["+e+"]"},repeat(t){return String(t)}},XI=function(t,e){Array.prototype.push.apply(t,kn(e)?e:[e])};let nv;const Nt={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:y5,encodeValuesOnly:!1,format:qI,formatter:KI,indices:!1,serializeDate(t){return(nv??(nv=Function.prototype.call.bind(Date.prototype.toISOString)))(t)},skipNulls:!1,strictNullHandling:!1};function b5(t){return typeof t=="string"||typeof t=="number"||typeof t=="boolean"||typeof t=="symbol"||typeof t=="bigint"}const Bf={};function YI(t,e,n,r,s,a,i,o,c,u,l,d,f,h,m,_,y,w){let g=t,b=w,S=0,I=!1;for(;(b=b.get(Bf))!==void 0&&!I;){const O=b.get(t);if(S+=1,typeof O<"u"){if(O===S)throw new RangeError("Cyclic object value");I=!0}typeof b.get(Bf)>"u"&&(S=0)}if(typeof u=="function"?g=u(e,g):g instanceof Date?g=f==null?void 0:f(g):n==="comma"&&kn(g)&&(g=tv(g,function(O){return O instanceof Date?f==null?void 0:f(O):O})),g===null){if(a)return c&&!_?c(e,Nt.encoder,y,"key",h):e;g=""}if(b5(g)||w5(g)){if(c){const O=_?e:c(e,Nt.encoder,y,"key",h);return[(m==null?void 0:m(O))+"="+(m==null?void 0:m(c(g,Nt.encoder,y,"value",h)))]}return[(m==null?void 0:m(e))+"="+(m==null?void 0:m(String(g)))]}const T=[];if(typeof g>"u")return T;let x;if(n==="comma"&&kn(g))_&&c&&(g=tv(g,c)),x=[{value:g.length>0?g.join(",")||null:void 0}];else if(kn(u))x=u;else{const O=Object.keys(g);x=l?O.sort(l):O}const A=o?String(e).replace(/\./g,"%2E"):String(e),M=r&&kn(g)&&g.length===1?A+"[]":A;if(s&&kn(g)&&g.length===0)return M+"[]";for(let O=0;O<x.length;++O){const $=x[O],H=typeof $=="object"&&typeof $.value<"u"?$.value:g[$];if(i&&H===null)continue;const J=d&&o?$.replace(/\./g,"%2E"):$,Y=kn(g)?typeof n=="function"?n(M,J):M:M+(d?"."+J:"["+J+"]");w.set(t,S);const me=new WeakMap;me.set(Bf,w),XI(T,YI(H,Y,n,r,s,a,i,o,n==="comma"&&_&&kn(g)?null:c,u,l,d,f,h,m,_,y,me))}return T}function v5(t=Nt){if(typeof t.allowEmptyArrays<"u"&&typeof t.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof t.encodeDotInKeys<"u"&&typeof t.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(t.encoder!==null&&typeof t.encoder<"u"&&typeof t.encoder!="function")throw new TypeError("Encoder has to be a function.");const e=t.charset||Nt.charset;if(typeof t.charset<"u"&&t.charset!=="utf-8"&&t.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let n=qI;if(typeof t.format<"u"){if(!Nm(ev,t.format))throw new TypeError("Unknown format option provided.");n=t.format}const r=ev[n];let s=Nt.filter;(typeof t.filter=="function"||kn(t.filter))&&(s=t.filter);let a;if(t.arrayFormat&&t.arrayFormat in JI?a=t.arrayFormat:"indices"in t?a=t.indices?"indices":"repeat":a=Nt.arrayFormat,"commaRoundTrip"in t&&typeof t.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");const i=typeof t.allowDots>"u"?t.encodeDotInKeys?!0:Nt.allowDots:!!t.allowDots;return{addQueryPrefix:typeof t.addQueryPrefix=="boolean"?t.addQueryPrefix:Nt.addQueryPrefix,allowDots:i,allowEmptyArrays:typeof t.allowEmptyArrays=="boolean"?!!t.allowEmptyArrays:Nt.allowEmptyArrays,arrayFormat:a,charset:e,charsetSentinel:typeof t.charsetSentinel=="boolean"?t.charsetSentinel:Nt.charsetSentinel,commaRoundTrip:!!t.commaRoundTrip,delimiter:typeof t.delimiter>"u"?Nt.delimiter:t.delimiter,encode:typeof t.encode=="boolean"?t.encode:Nt.encode,encodeDotInKeys:typeof t.encodeDotInKeys=="boolean"?t.encodeDotInKeys:Nt.encodeDotInKeys,encoder:typeof t.encoder=="function"?t.encoder:Nt.encoder,encodeValuesOnly:typeof t.encodeValuesOnly=="boolean"?t.encodeValuesOnly:Nt.encodeValuesOnly,filter:s,format:n,formatter:r,serializeDate:typeof t.serializeDate=="function"?t.serializeDate:Nt.serializeDate,skipNulls:typeof t.skipNulls=="boolean"?t.skipNulls:Nt.skipNulls,sort:typeof t.sort=="function"?t.sort:null,strictNullHandling:typeof t.strictNullHandling=="boolean"?t.strictNullHandling:Nt.strictNullHandling}}function S5(t,e={}){let n=t;const r=v5(e);let s,a;typeof r.filter=="function"?(a=r.filter,n=a("",n)):kn(r.filter)&&(a=r.filter,s=a);const i=[];if(typeof n!="object"||n===null)return"";const o=JI[r.arrayFormat],c=o==="comma"&&r.commaRoundTrip;s||(s=Object.keys(n)),r.sort&&s.sort(r.sort);const u=new WeakMap;for(let f=0;f<s.length;++f){const h=s[f];r.skipNulls&&n[h]===null||XI(i,YI(n[h],h,o,c,r.allowEmptyArrays,r.strictNullHandling,r.skipNulls,r.encodeDotInKeys,r.encode?r.encoder:null,r.filter,r.sort,r.allowDots,r.serializeDate,r.format,r.formatter,r.encodeValuesOnly,r.charset,u))}const l=i.join(r.delimiter);let d=r.addQueryPrefix===!0?"?":"";return r.charsetSentinel&&(r.charset==="iso-8859-1"?d+="utf8=%26%2310003%3B&":d+="utf8=%E2%9C%93&"),l.length>0?d+l:""}function T5(t){return S5(t,{arrayFormat:"brackets"})}function E5(t){let e=0;for(const s of t)e+=s.length;const n=new Uint8Array(e);let r=0;for(const s of t)n.set(s,r),r+=s.length;return n}let rv;function x_(t){let e;return(rv??(e=new globalThis.TextEncoder,rv=e.encode.bind(e)))(t)}let sv;function av(t){let e;return(sv??(e=new globalThis.TextDecoder,sv=e.decode.bind(e)))(t)}var jn,Un;let wh=class{constructor(){jn.set(this,void 0),Un.set(this,void 0),xe(this,jn,new Uint8Array),xe(this,Un,null)}decode(e){if(e==null)return[];const n=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?x_(e):e;xe(this,jn,E5([R(this,jn,"f"),n]));const r=[];let s;for(;(s=A5(R(this,jn,"f"),R(this,Un,"f")))!=null;){if(s.carriage&&R(this,Un,"f")==null){xe(this,Un,s.index);continue}if(R(this,Un,"f")!=null&&(s.index!==R(this,Un,"f")+1||s.carriage)){r.push(av(R(this,jn,"f").subarray(0,R(this,Un,"f")-1))),xe(this,jn,R(this,jn,"f").subarray(R(this,Un,"f"))),xe(this,Un,null);continue}const a=R(this,Un,"f")!==null?s.preceding-1:s.preceding,i=av(R(this,jn,"f").subarray(0,a));r.push(i),xe(this,jn,R(this,jn,"f").subarray(s.index)),xe(this,Un,null)}return r}flush(){return R(this,jn,"f").length?this.decode(`
313
- `):[]}};jn=new WeakMap,Un=new WeakMap;wh.NEWLINE_CHARS=new Set([`
314
- `,"\r"]);wh.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function A5(t,e){for(let s=e??0;s<t.length;s++){if(t[s]===10)return{preceding:s,index:s+1,carriage:!1};if(t[s]===13)return{preceding:s,index:s+1,carriage:!0}}return null}function I5(t){for(let r=0;r<t.length-1;r++){if(t[r]===10&&t[r+1]===10||t[r]===13&&t[r+1]===13)return r+2;if(t[r]===13&&t[r+1]===10&&r+3<t.length&&t[r+2]===13&&t[r+3]===10)return r+4}return-1}const xd={off:0,error:200,warn:300,info:400,debug:500},iv=(t,e,n)=>{if(t){if(c5(xd,t))return t;Kt(n).warn(`${e} was set to ${JSON.stringify(t)}, expected one of ${JSON.stringify(Object.keys(xd))}`)}};function Uo(){}function Bu(t,e,n){return!e||xd[t]>xd[n]?Uo:e[t].bind(e)}const x5={error:Uo,warn:Uo,info:Uo,debug:Uo};let ov=new WeakMap;function Kt(t){const e=t.logger,n=t.logLevel??"off";if(!e)return x5;const r=ov.get(e);if(r&&r[0]===n)return r[1];const s={error:Bu("error",e,n),warn:Bu("warn",e,n),info:Bu("info",e,n),debug:Bu("debug",e,n)};return ov.set(e,[n,s]),s}const ma=t=>(t.options&&(t.options={...t.options},delete t.options.headers),t.headers&&(t.headers=Object.fromEntries((t.headers instanceof Headers?[...t.headers]:Object.entries(t.headers)).map(([e,n])=>[e,e.toLowerCase()==="authorization"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":n]))),"retryOfRequestLogID"in t&&(t.retryOfRequestLogID&&(t.retryOf=t.retryOfRequestLogID),delete t.retryOfRequestLogID),t);var oo;let Cc=class Do{constructor(e,n,r){this.iterator=e,oo.set(this,void 0),this.controller=n,xe(this,oo,r)}static fromSSEResponse(e,n,r,s){let a=!1;const i=r?Kt(r):console;async function*o(){if(a)throw new he("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");a=!0;let c=!1;try{for await(const u of k5(e,n))if(!c){if(u.data.startsWith("[DONE]")){c=!0;continue}if(u.event===null||!u.event.startsWith("thread.")){let l;try{l=JSON.parse(u.data)}catch(d){throw i.error("Could not parse message into JSON:",u.data),i.error("From chunk:",u.raw),d}if(l&&l.error)throw new hn(void 0,l.error,void 0,e.headers);yield s?{event:u.event,data:l}:l}else{let l;try{l=JSON.parse(u.data)}catch(d){throw console.error("Could not parse message into JSON:",u.data),console.error("From chunk:",u.raw),d}if(u.event=="error")throw new hn(void 0,l.error,l.message,void 0);yield{event:u.event,data:l}}}c=!0}catch(u){if(Cm(u))return;throw u}finally{c||n.abort()}}return new Do(o,n,r)}static fromReadableStream(e,n,r){let s=!1;async function*a(){const o=new wh,c=GI(e);for await(const u of c)for(const l of o.decode(u))yield l;for(const u of o.flush())yield u}async function*i(){if(s)throw new he("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let o=!1;try{for await(const c of a())o||c&&(yield JSON.parse(c));o=!0}catch(c){if(Cm(c))return;throw c}finally{o||n.abort()}}return new Do(i,n,r)}[(oo=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){const e=[],n=[],r=this.iterator(),s=a=>({next:()=>{if(a.length===0){const i=r.next();e.push(i),n.push(i)}return a.shift()}});return[new Do(()=>s(e),this.controller,R(this,oo,"f")),new Do(()=>s(n),this.controller,R(this,oo,"f"))]}toReadableStream(){const e=this;let n;return ZI({async start(){n=e[Symbol.asyncIterator]()},async pull(r){try{const{value:s,done:a}=await n.next();if(a)return r.close();const i=x_(JSON.stringify(s)+`
315
- `);r.enqueue(i)}catch(s){r.error(s)}},async cancel(){var r;await((r=n.return)==null?void 0:r.call(n))}})}};async function*k5(t,e){if(!t.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new he("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new he("Attempted to iterate over a response with no body");const n=new C5,r=new wh,s=GI(t.body);for await(const a of O5(s))for(const i of r.decode(a)){const o=n.decode(i);o&&(yield o)}for(const a of r.flush()){const i=n.decode(a);i&&(yield i)}}async function*O5(t){let e=new Uint8Array;for await(const n of t){if(n==null)continue;const r=n instanceof ArrayBuffer?new Uint8Array(n):typeof n=="string"?x_(n):n;let s=new Uint8Array(e.length+r.length);s.set(e),s.set(r,e.length),e=s;let a;for(;(a=I5(e))!==-1;)yield e.slice(0,a),e=e.slice(a)}e.length>0&&(yield e)}let C5=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;const a={event:this.event,data:this.data.join(`
316
- `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],a}if(this.chunks.push(e),e.startsWith(":"))return null;let[n,r,s]=R5(e,":");return s.startsWith(" ")&&(s=s.substring(1)),n==="event"?this.event=s:n==="data"&&this.data.push(s),null}};function R5(t,e){const n=t.indexOf(e);return n!==-1?[t.substring(0,n),e,t.substring(n+e.length)]:[t,"",""]}async function QI(t,e){const{response:n,requestLogID:r,retryOfRequestLogID:s,startTime:a}=e,i=await(async()=>{var d;if(e.options.stream)return Kt(t).debug("response",n.status,n.url,n.headers,n.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(n,e.controller,t,e.options.__synthesizeEventData):Cc.fromSSEResponse(n,e.controller,t,e.options.__synthesizeEventData);if(n.status===204)return null;if(e.options.__binaryResponse)return n;const o=n.headers.get("content-type"),c=(d=o==null?void 0:o.split(";")[0])==null?void 0:d.trim();if((c==null?void 0:c.includes("application/json"))||(c==null?void 0:c.endsWith("+json"))){if(n.headers.get("content-length")==="0")return;const h=await n.json();return ex(h,n)}return await n.text()})();return Kt(t).debug(`[${r}] response parsed`,ma({retryOfRequestLogID:s,url:n.url,status:n.status,body:i,durationMs:Date.now()-a})),i}function ex(t,e){return!t||typeof t!="object"||Array.isArray(t)?t:Object.defineProperty(t,"_request_id",{value:e.headers.get("x-request-id"),enumerable:!1})}var Fo;let tx=class nx extends Promise{constructor(e,n,r=QI){super(s=>{s(null)}),this.responsePromise=n,this.parseResponse=r,Fo.set(this,void 0),xe(this,Fo,e)}_thenUnwrap(e){return new nx(R(this,Fo,"f"),this.responsePromise,async(n,r)=>ex(e(await this.parseResponse(n,r),r),r.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){const[e,n]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:n,request_id:n.headers.get("x-request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(R(this,Fo,"f"),e))),this.parsedPromise}then(e,n){return this.parse().then(e,n)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}};Fo=new WeakMap;var zu;let k_=class{constructor(e,n,r,s){zu.set(this,void 0),xe(this,zu,e),this.options=s,this.response=n,this.body=r}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){const e=this.nextPageRequestOptions();if(!e)throw new he("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await R(this,zu,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(zu=new WeakMap,Symbol.asyncIterator)](){for await(const e of this.iterPages())for(const n of e.getPaginatedItems())yield n}},$5=class extends tx{constructor(e,n,r){super(e,n,async(s,a)=>new r(s,a.response,await QI(s,a),a.options))}async*[Symbol.asyncIterator](){const e=await this;for await(const n of e)yield n}},bh=class extends k_{constructor(e,n,r,s){super(e,n,r,s),this.data=r.data||[],this.object=r.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}};class St extends k_{constructor(e,n,r,s){super(e,n,r,s),this.data=r.data||[],this.has_more=r.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){var r;const e=this.getPaginatedItems(),n=(r=e[e.length-1])==null?void 0:r.id;return n?{...this.options,query:{...HI(this.options.query),after:n}}:null}}class Rc extends k_{constructor(e,n,r,s){super(e,n,r,s),this.data=r.data||[],this.has_more=r.has_more||!1,this.last_id=r.last_id||""}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){const e=this.last_id;return e?{...this.options,query:{...HI(this.options.query),after:e}}:null}}const N5={jwt:"urn:ietf:params:oauth:token-type:jwt",id:"urn:ietf:params:oauth:token-type:id_token"},P5="urn:ietf:params:oauth:grant-type:token-exchange";class M5{constructor(e,n){this.cachedToken=null,this.refreshPromise=null,this.tokenExchangeUrl="https://auth.openai.com/oauth/token",this.config=e,this.fetch=n??VI()}async getToken(){if(!this.cachedToken||this.isTokenExpired(this.cachedToken)){if(this.refreshPromise)return await this.refreshPromise;this.refreshPromise=this.refreshToken();try{return await this.refreshPromise}finally{this.refreshPromise=null}}return this.needsRefresh(this.cachedToken)&&!this.refreshPromise&&(this.refreshPromise=this.refreshToken().finally(()=>{this.refreshPromise=null})),this.cachedToken.token}async refreshToken(){const e=await this.config.provider.getToken(),n=await this.fetch(this.tokenExchangeUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant_type:P5,client_id:this.config.clientId,subject_token:e,subject_token_type:N5[this.config.provider.tokenType],identity_provider_id:this.config.identityProviderId,service_account_id:this.config.serviceAccountId})});if(!n.ok){const i=await n.text();let o;try{o=JSON.parse(i)}catch{}throw n.status===400||n.status===401||n.status===403?new zI(n.status,o,n.headers):hn.generate(n.status,o,`Token exchange failed with status ${n.status}`,n.headers)}const r=await n.json(),s=r.expires_in||3600,a=Date.now()+s*1e3;return this.cachedToken={token:r.access_token,expiresAt:a},r.access_token}isTokenExpired(e){return Date.now()>=e.expiresAt}needsRefresh(e){const r=(this.config.refreshBufferSeconds??1200)*1e3;return Date.now()>=e.expiresAt-r}invalidateToken(){this.cachedToken=null,this.refreshPromise=null}}const rx=()=>{var t;if(typeof File>"u"){const{process:e}=globalThis,n=typeof((t=e==null?void 0:e.versions)==null?void 0:t.node)=="string"&&parseInt(e.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(n?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function nc(t,e,n){return rx(),new File(t,e??"unknown_file",n)}function $l(t){return(typeof t=="object"&&t!==null&&("name"in t&&t.name&&String(t.name)||"url"in t&&t.url&&String(t.url)||"filename"in t&&t.filename&&String(t.filename)||"path"in t&&t.path&&String(t.path))||"").split(/[\\/]/).pop()||void 0}const O_=t=>t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function",vh=async(t,e)=>Pm(t.body)?{...t,body:await sx(t.body,e)}:t,zr=async(t,e)=>({...t,body:await sx(t.body,e)}),cv=new WeakMap;function L5(t){const e=typeof t=="function"?t:t.fetch,n=cv.get(e);if(n)return n;const r=(async()=>{try{const s="Response"in e?e.Response:(await e("data:,")).constructor,a=new FormData;return a.toString()!==await new s(a).text()}catch{return!0}})();return cv.set(e,r),r}const sx=async(t,e)=>{if(!await L5(e))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");const n=new FormData;return await Promise.all(Object.entries(t||{}).map(([r,s])=>Mm(n,r,s))),n},ax=t=>t instanceof Blob&&"name"in t,j5=t=>typeof t=="object"&&t!==null&&(t instanceof Response||O_(t)||ax(t)),Pm=t=>{if(j5(t))return!0;if(Array.isArray(t))return t.some(Pm);if(t&&typeof t=="object"){for(const e in t)if(Pm(t[e]))return!0}return!1},Mm=async(t,e,n)=>{if(n!==void 0){if(n==null)throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")t.append(e,String(n));else if(n instanceof Response)t.append(e,nc([await n.blob()],$l(n)));else if(O_(n))t.append(e,nc([await new Response(WI(n)).blob()],$l(n)));else if(ax(n))t.append(e,n,$l(n));else if(Array.isArray(n))await Promise.all(n.map(r=>Mm(t,e+"[]",r)));else if(typeof n=="object")await Promise.all(Object.entries(n).map(([r,s])=>Mm(t,`${e}[${r}]`,s)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${n} instead`)}},ix=t=>t!=null&&typeof t=="object"&&typeof t.size=="number"&&typeof t.type=="string"&&typeof t.text=="function"&&typeof t.slice=="function"&&typeof t.arrayBuffer=="function",U5=t=>t!=null&&typeof t=="object"&&typeof t.name=="string"&&typeof t.lastModified=="number"&&ix(t),D5=t=>t!=null&&typeof t=="object"&&typeof t.url=="string"&&typeof t.blob=="function";async function F5(t,e,n){if(rx(),t=await t,U5(t))return t instanceof File?t:nc([await t.arrayBuffer()],t.name);if(D5(t)){const s=await t.blob();return e||(e=new URL(t.url).pathname.split(/[\\/]/).pop()),nc(await Lm(s),e,n)}const r=await Lm(t);if(e||(e=$l(t)),!(n!=null&&n.type)){const s=r.find(a=>typeof a=="object"&&"type"in a&&a.type);typeof s=="string"&&(n={...n,type:s})}return nc(r,e,n)}async function Lm(t){var n;let e=[];if(typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer)e.push(t);else if(ix(t))e.push(t instanceof Blob?t:await t.arrayBuffer());else if(O_(t))for await(const r of t)e.push(...await Lm(r));else{const r=(n=t==null?void 0:t.constructor)==null?void 0:n.name;throw new Error(`Unexpected data type: ${typeof t}${r?`; constructor: ${r}`:""}${B5(t)}`)}return e}function B5(t){return typeof t!="object"||t===null?"":`; props: [${Object.getOwnPropertyNames(t).map(n=>`"${n}"`).join(", ")}]`}let fe=class{constructor(e){this._client=e}};function ox(t){return t.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}const uv=Object.freeze(Object.create(null)),z5=(t=ox)=>function(n,...r){if(n.length===1)return n[0];let s=!1;const a=[],i=n.reduce((l,d,f)=>{var _;/[?#]/.test(d)&&(s=!0);const h=r[f];let m=(s?encodeURIComponent:t)(""+h);return f!==r.length&&(h==null||typeof h=="object"&&h.toString===((_=Object.getPrototypeOf(Object.getPrototypeOf(h.hasOwnProperty??uv)??uv))==null?void 0:_.toString))&&(m=h+"",a.push({start:l.length+d.length,length:m.length,error:`Value of type ${Object.prototype.toString.call(h).slice(8,-1)} is not a valid path parameter`})),l+d+(f===r.length?"":m)},""),o=i.split(/[?#]/,1)[0],c=new RegExp("(?<=^|\\/)(?:\\.|%2e){1,2}(?=\\/|$)","gi");let u;for(;(u=c.exec(o))!==null;)a.push({start:u.index,length:u[0].length,error:`Value "${u[0]}" can't be safely passed as a path parameter`});if(a.sort((l,d)=>l.start-d.start),a.length>0){let l=0;const d=a.reduce((f,h)=>{const m=" ".repeat(h.start-l),_="^".repeat(h.length);return l=h.start+h.length,f+m+_},"");throw new he(`Path parameters result in path with invalid segments:
317
- ${a.map(f=>f.error).join(`
318
- `)}
319
- ${i}
320
- ${d}`)}return i},D=z5(ox);let cx=class extends fe{list(e,n={},r){return this._client.getAPIList(D`/chat/completions/${e}/messages`,St,{query:n,...r})}};function kd(t){return t!==void 0&&"function"in t&&t.function!==void 0}function H5(t,e){const n={...t};return Object.defineProperties(n,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:e,enumerable:!1}}),n}function C_(t){return(t==null?void 0:t.$brand)==="auto-parseable-response-format"}function su(t){return(t==null?void 0:t.$brand)==="auto-parseable-tool"}function V5(t,e){return!e||!ux(e)?{...t,choices:t.choices.map(n=>(lx(n.message.tool_calls),{...n,message:{...n.message,parsed:null,...n.message.tool_calls?{tool_calls:n.message.tool_calls}:void 0}}))}:R_(t,e)}function R_(t,e){const n=t.choices.map(r=>{var s;if(r.finish_reason==="length")throw new FI;if(r.finish_reason==="content_filter")throw new BI;return lx(r.message.tool_calls),{...r,message:{...r.message,...r.message.tool_calls?{tool_calls:((s=r.message.tool_calls)==null?void 0:s.map(a=>W5(e,a)))??void 0}:void 0,parsed:r.message.content&&!r.message.refusal?Z5(e,r.message.content):null}}});return{...t,choices:n}}function Z5(t,e){var n,r;return((n=t.response_format)==null?void 0:n.type)!=="json_schema"?null:((r=t.response_format)==null?void 0:r.type)==="json_schema"?"$parseRaw"in t.response_format?t.response_format.$parseRaw(e):JSON.parse(e):null}function W5(t,e){var r;const n=(r=t.tools)==null?void 0:r.find(s=>{var a;return kd(s)&&((a=s.function)==null?void 0:a.name)===e.function.name});return{...e,function:{...e.function,parsed_arguments:su(n)?n.$parseRaw(e.function.arguments):n!=null&&n.function.strict?JSON.parse(e.function.arguments):null}}}function G5(t,e){var r;if(!t||!("tools"in t)||!t.tools)return!1;const n=(r=t.tools)==null?void 0:r.find(s=>{var a;return kd(s)&&((a=s.function)==null?void 0:a.name)===e.function.name});return kd(n)&&(su(n)||(n==null?void 0:n.function.strict)||!1)}function ux(t){var e;return C_(t.response_format)?!0:((e=t.tools)==null?void 0:e.some(n=>su(n)||n.type==="function"&&n.function.strict===!0))??!1}function lx(t){for(const e of t||[])if(e.type!=="function")throw new he(`Currently only \`function\` tool calls are supported; Received \`${e.type}\``)}function q5(t){for(const e of t??[]){if(e.type!=="function")throw new he(`Currently only \`function\` tool types support auto-parsing; Received \`${e.type}\``);if(e.function.strict!==!0)throw new he(`The \`${e.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}const Od=t=>(t==null?void 0:t.role)==="assistant",dx=t=>(t==null?void 0:t.role)==="tool";var jm,Nl,Pl,Bo,zo,Ml,Ho,ts,Vo,Cd,Rd,ci,hx;class $_{constructor(){jm.add(this),this.controller=new AbortController,Nl.set(this,void 0),Pl.set(this,()=>{}),Bo.set(this,()=>{}),zo.set(this,void 0),Ml.set(this,()=>{}),Ho.set(this,()=>{}),ts.set(this,{}),Vo.set(this,!1),Cd.set(this,!1),Rd.set(this,!1),ci.set(this,!1),xe(this,Nl,new Promise((e,n)=>{xe(this,Pl,e,"f"),xe(this,Bo,n,"f")})),xe(this,zo,new Promise((e,n)=>{xe(this,Ml,e,"f"),xe(this,Ho,n,"f")})),R(this,Nl,"f").catch(()=>{}),R(this,zo,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},R(this,jm,"m",hx).bind(this))},0)}_connected(){this.ended||(R(this,Pl,"f").call(this),this._emit("connect"))}get ended(){return R(this,Vo,"f")}get errored(){return R(this,Cd,"f")}get aborted(){return R(this,Rd,"f")}abort(){this.controller.abort()}on(e,n){return(R(this,ts,"f")[e]||(R(this,ts,"f")[e]=[])).push({listener:n}),this}off(e,n){const r=R(this,ts,"f")[e];if(!r)return this;const s=r.findIndex(a=>a.listener===n);return s>=0&&r.splice(s,1),this}once(e,n){return(R(this,ts,"f")[e]||(R(this,ts,"f")[e]=[])).push({listener:n,once:!0}),this}emitted(e){return new Promise((n,r)=>{xe(this,ci,!0),e!=="error"&&this.once("error",r),this.once(e,n)})}async done(){xe(this,ci,!0),await R(this,zo,"f")}_emit(e,...n){if(R(this,Vo,"f"))return;e==="end"&&(xe(this,Vo,!0),R(this,Ml,"f").call(this));const r=R(this,ts,"f")[e];if(r&&(R(this,ts,"f")[e]=r.filter(s=>!s.once),r.forEach(({listener:s})=>s(...n))),e==="abort"){const s=n[0];!R(this,ci,"f")&&!(r!=null&&r.length)&&Promise.reject(s),R(this,Bo,"f").call(this,s),R(this,Ho,"f").call(this,s),this._emit("end");return}if(e==="error"){const s=n[0];!R(this,ci,"f")&&!(r!=null&&r.length)&&Promise.reject(s),R(this,Bo,"f").call(this,s),R(this,Ho,"f").call(this,s),this._emit("end")}}_emitFinal(){}}Nl=new WeakMap,Pl=new WeakMap,Bo=new WeakMap,zo=new WeakMap,Ml=new WeakMap,Ho=new WeakMap,ts=new WeakMap,Vo=new WeakMap,Cd=new WeakMap,Rd=new WeakMap,ci=new WeakMap,jm=new WeakSet,hx=function(e){if(xe(this,Cd,!0),e instanceof Error&&e.name==="AbortError"&&(e=new Zn),e instanceof Zn)return xe(this,Rd,!0),this._emit("abort",e);if(e instanceof he)return this._emit("error",e);if(e instanceof Error){const n=new he(e.message);return n.cause=e,this._emit("error",n)}return this._emit("error",new he(String(e)))};function K5(t){return typeof t.parse=="function"}var gn,Um,$d,Dm,Fm,Bm,fx,px;const J5=10;class mx extends $_{constructor(){super(...arguments),gn.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){var r;this._chatCompletions.push(e),this._emit("chatCompletion",e);const n=(r=e.choices[0])==null?void 0:r.message;return n&&this._addMessage(n),e}_addMessage(e,n=!0){if("content"in e||(e.content=null),this.messages.push(e),n){if(this._emit("message",e),dx(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(Od(e)&&e.tool_calls)for(const r of e.tool_calls)r.type==="function"&&this._emit("functionToolCall",r.function)}}async finalChatCompletion(){await this.done();const e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new he("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),R(this,gn,"m",Um).call(this)}async finalMessage(){return await this.done(),R(this,gn,"m",$d).call(this)}async finalFunctionToolCall(){return await this.done(),R(this,gn,"m",Dm).call(this)}async finalFunctionToolCallResult(){return await this.done(),R(this,gn,"m",Fm).call(this)}async totalUsage(){return await this.done(),R(this,gn,"m",Bm).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){const e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);const n=R(this,gn,"m",$d).call(this);n&&this._emit("finalMessage",n);const r=R(this,gn,"m",Um).call(this);r&&this._emit("finalContent",r);const s=R(this,gn,"m",Dm).call(this);s&&this._emit("finalFunctionToolCall",s);const a=R(this,gn,"m",Fm).call(this);a!=null&&this._emit("finalFunctionToolCallResult",a),this._chatCompletions.some(i=>i.usage)&&this._emit("totalUsage",R(this,gn,"m",Bm).call(this))}async _createChatCompletion(e,n,r){const s=r==null?void 0:r.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),R(this,gn,"m",fx).call(this,n);const a=await e.chat.completions.create({...n,stream:!1},{...r,signal:this.controller.signal});return this._connected(),this._addChatCompletion(R_(a,n))}async _runChatCompletion(e,n,r){for(const s of n.messages)this._addMessage(s,!1);return await this._createChatCompletion(e,n,r)}async _runTools(e,n,r){var h,m,_;const s="tool",{tool_choice:a="auto",stream:i,...o}=n,c=typeof a!="string"&&a.type==="function"&&((h=a==null?void 0:a.function)==null?void 0:h.name),{maxChatCompletions:u=J5}=r||{},l=n.tools.map(y=>{if(su(y)){if(!y.$callback)throw new he("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:y.$callback,name:y.function.name,description:y.function.description||"",parameters:y.function.parameters,parse:y.$parseRaw,strict:!0}}}return y}),d={};for(const y of l)y.type==="function"&&(d[y.function.name||y.function.function.name]=y.function);const f="tools"in n?l.map(y=>y.type==="function"?{type:"function",function:{name:y.function.name||y.function.function.name,parameters:y.function.parameters,description:y.function.description,strict:y.function.strict}}:y):void 0;for(const y of n.messages)this._addMessage(y,!1);for(let y=0;y<u;++y){const g=(m=(await this._createChatCompletion(e,{...o,tool_choice:a,tools:f,messages:[...this.messages]},r)).choices[0])==null?void 0:m.message;if(!g)throw new he("missing message in ChatCompletion response");if(!((_=g.tool_calls)!=null&&_.length))return;for(const b of g.tool_calls){if(b.type!=="function")continue;const S=b.id,{name:I,arguments:T}=b.function,x=d[I];if(x){if(c&&c!==I){const $=`Invalid tool_call: ${JSON.stringify(I)}. ${JSON.stringify(c)} requested. Please try again`;this._addMessage({role:s,tool_call_id:S,content:$});continue}}else{const $=`Invalid tool_call: ${JSON.stringify(I)}. Available options are: ${Object.keys(d).map(H=>JSON.stringify(H)).join(", ")}. Please try again`;this._addMessage({role:s,tool_call_id:S,content:$});continue}let A;try{A=K5(x)?await x.parse(T):T}catch($){const H=$ instanceof Error?$.message:String($);this._addMessage({role:s,tool_call_id:S,content:H});continue}const M=await x.function(A,this),O=R(this,gn,"m",px).call(this,M);if(this._addMessage({role:s,tool_call_id:S,content:O}),c)return}}}}gn=new WeakSet,Um=function(){return R(this,gn,"m",$d).call(this).content??null},$d=function(){let e=this.messages.length;for(;e-- >0;){const n=this.messages[e];if(Od(n))return{...n,content:n.content??null,refusal:n.refusal??null}}throw new he("stream ended without producing a ChatCompletionMessage with role=assistant")},Dm=function(){var e,n;for(let r=this.messages.length-1;r>=0;r--){const s=this.messages[r];if(Od(s)&&((e=s==null?void 0:s.tool_calls)!=null&&e.length))return(n=s.tool_calls.filter(a=>a.type==="function").at(-1))==null?void 0:n.function}},Fm=function(){for(let e=this.messages.length-1;e>=0;e--){const n=this.messages[e];if(dx(n)&&n.content!=null&&typeof n.content=="string"&&this.messages.some(r=>{var s;return r.role==="assistant"&&((s=r.tool_calls)==null?void 0:s.some(a=>a.type==="function"&&a.id===n.tool_call_id))}))return n.content}},Bm=function(){const e={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(const{usage:n}of this._chatCompletions)n&&(e.completion_tokens+=n.completion_tokens,e.prompt_tokens+=n.prompt_tokens,e.total_tokens+=n.total_tokens);return e},fx=function(e){if(e.n!=null&&e.n>1)throw new he("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},px=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)};class N_ extends mx{static runTools(e,n,r){const s=new N_,a={...r,headers:{...r==null?void 0:r.headers,"X-Stainless-Helper-Method":"runTools"}};return s._run(()=>s._runTools(e,n,a)),s}_addMessage(e,n=!0){super._addMessage(e,n),Od(e)&&e.content&&this._emit("content",e.content)}}const gx=1,_x=2,yx=4,wx=8,bx=16,vx=32,Sx=64,Tx=128,Ex=256,Ax=Tx|Ex,Ix=bx|vx|Ax|Sx,xx=gx|_x|Ix,kx=yx|wx,X5=xx|kx,Ft={STR:gx,NUM:_x,ARR:yx,OBJ:wx,NULL:bx,BOOL:vx,NAN:Sx,INFINITY:Tx,MINUS_INFINITY:Ex,INF:Ax,SPECIAL:Ix,ATOM:xx,COLLECTION:kx,ALL:X5};class Y5 extends Error{}class Q5 extends Error{}function e9(t,e=Ft.ALL){if(typeof t!="string")throw new TypeError(`expecting str, got ${typeof t}`);if(!t.trim())throw new Error(`${t} is empty`);return t9(t.trim(),e)}const t9=(t,e)=>{const n=t.length;let r=0;const s=f=>{throw new Y5(`${f} at position ${r}`)},a=f=>{throw new Q5(`${f} at position ${r}`)},i=()=>(d(),r>=n&&s("Unexpected end of input"),t[r]==='"'?o():t[r]==="{"?c():t[r]==="["?u():t.substring(r,r+4)==="null"||Ft.NULL&e&&n-r<4&&"null".startsWith(t.substring(r))?(r+=4,null):t.substring(r,r+4)==="true"||Ft.BOOL&e&&n-r<4&&"true".startsWith(t.substring(r))?(r+=4,!0):t.substring(r,r+5)==="false"||Ft.BOOL&e&&n-r<5&&"false".startsWith(t.substring(r))?(r+=5,!1):t.substring(r,r+8)==="Infinity"||Ft.INFINITY&e&&n-r<8&&"Infinity".startsWith(t.substring(r))?(r+=8,1/0):t.substring(r,r+9)==="-Infinity"||Ft.MINUS_INFINITY&e&&1<n-r&&n-r<9&&"-Infinity".startsWith(t.substring(r))?(r+=9,-1/0):t.substring(r,r+3)==="NaN"||Ft.NAN&e&&n-r<3&&"NaN".startsWith(t.substring(r))?(r+=3,NaN):l()),o=()=>{const f=r;let h=!1;for(r++;r<n&&(t[r]!=='"'||h&&t[r-1]==="\\");)h=t[r]==="\\"?!h:!1,r++;if(t.charAt(r)=='"')try{return JSON.parse(t.substring(f,++r-Number(h)))}catch(m){a(String(m))}else if(Ft.STR&e)try{return JSON.parse(t.substring(f,r-Number(h))+'"')}catch{return JSON.parse(t.substring(f,t.lastIndexOf("\\"))+'"')}s("Unterminated string literal")},c=()=>{r++,d();const f={};try{for(;t[r]!=="}";){if(d(),r>=n&&Ft.OBJ&e)return f;const h=o();d(),r++;try{const m=i();Object.defineProperty(f,h,{value:m,writable:!0,enumerable:!0,configurable:!0})}catch(m){if(Ft.OBJ&e)return f;throw m}d(),t[r]===","&&r++}}catch{if(Ft.OBJ&e)return f;s("Expected '}' at end of object")}return r++,f},u=()=>{r++;const f=[];try{for(;t[r]!=="]";)f.push(i()),d(),t[r]===","&&r++}catch{if(Ft.ARR&e)return f;s("Expected ']' at end of array")}return r++,f},l=()=>{if(r===0){t==="-"&&Ft.NUM&e&&s("Not sure what '-' is");try{return JSON.parse(t)}catch(h){if(Ft.NUM&e)try{return t[t.length-1]==="."?JSON.parse(t.substring(0,t.lastIndexOf("."))):JSON.parse(t.substring(0,t.lastIndexOf("e")))}catch{}a(String(h))}}const f=r;for(t[r]==="-"&&r++;t[r]&&!",]}".includes(t[r]);)r++;r==n&&!(Ft.NUM&e)&&s("Unterminated number literal");try{return JSON.parse(t.substring(f,r))}catch{t.substring(f,r)==="-"&&Ft.NUM&e&&s("Not sure what '-' is");try{return JSON.parse(t.substring(f,t.lastIndexOf("e")))}catch(m){a(String(m))}}},d=()=>{for(;r<n&&`
321
- \r `.includes(t[r]);)r++};return i()},lv=t=>e9(t,Ft.ALL^Ft.NUM);var Ct,Yr,Ja,As,zf,Hu,Hf,Vf,Zf,Vu,Wf,dv;class $c extends mx{constructor(e){super(),Ct.add(this),Yr.set(this,void 0),Ja.set(this,void 0),As.set(this,void 0),xe(this,Yr,e),xe(this,Ja,[])}get currentChatCompletionSnapshot(){return R(this,As,"f")}static fromReadableStream(e){const n=new $c(null);return n._run(()=>n._fromReadableStream(e)),n}static createChatCompletion(e,n,r){const s=new $c(n);return s._run(()=>s._runChatCompletion(e,{...n,stream:!0},{...r,headers:{...r==null?void 0:r.headers,"X-Stainless-Helper-Method":"stream"}})),s}async _createChatCompletion(e,n,r){var i;super._createChatCompletion;const s=r==null?void 0:r.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),R(this,Ct,"m",zf).call(this);const a=await e.chat.completions.create({...n,stream:!0},{...r,signal:this.controller.signal});this._connected();for await(const o of a)R(this,Ct,"m",Hf).call(this,o);if((i=a.controller.signal)!=null&&i.aborted)throw new Zn;return this._addChatCompletion(R(this,Ct,"m",Vu).call(this))}async _fromReadableStream(e,n){var i;const r=n==null?void 0:n.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),R(this,Ct,"m",zf).call(this),this._connected();const s=Cc.fromReadableStream(e,this.controller);let a;for await(const o of s)a&&a!==o.id&&this._addChatCompletion(R(this,Ct,"m",Vu).call(this)),R(this,Ct,"m",Hf).call(this,o),a=o.id;if((i=s.controller.signal)!=null&&i.aborted)throw new Zn;return this._addChatCompletion(R(this,Ct,"m",Vu).call(this))}[(Yr=new WeakMap,Ja=new WeakMap,As=new WeakMap,Ct=new WeakSet,zf=function(){this.ended||xe(this,As,void 0)},Hu=function(n){let r=R(this,Ja,"f")[n.index];return r||(r={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},R(this,Ja,"f")[n.index]=r,r)},Hf=function(n){var s,a,i,o,c,u,l,d,f,h,m,_,y,w,g;if(this.ended)return;const r=R(this,Ct,"m",dv).call(this,n);this._emit("chunk",n,r);for(const b of n.choices){const S=r.choices[b.index];b.delta.content!=null&&((s=S.message)==null?void 0:s.role)==="assistant"&&((a=S.message)!=null&&a.content)&&(this._emit("content",b.delta.content,S.message.content),this._emit("content.delta",{delta:b.delta.content,snapshot:S.message.content,parsed:S.message.parsed})),b.delta.refusal!=null&&((i=S.message)==null?void 0:i.role)==="assistant"&&((o=S.message)!=null&&o.refusal)&&this._emit("refusal.delta",{delta:b.delta.refusal,snapshot:S.message.refusal}),((c=b.logprobs)==null?void 0:c.content)!=null&&((u=S.message)==null?void 0:u.role)==="assistant"&&this._emit("logprobs.content.delta",{content:(l=b.logprobs)==null?void 0:l.content,snapshot:((d=S.logprobs)==null?void 0:d.content)??[]}),((f=b.logprobs)==null?void 0:f.refusal)!=null&&((h=S.message)==null?void 0:h.role)==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:(m=b.logprobs)==null?void 0:m.refusal,snapshot:((_=S.logprobs)==null?void 0:_.refusal)??[]});const I=R(this,Ct,"m",Hu).call(this,S);S.finish_reason&&(R(this,Ct,"m",Zf).call(this,S),I.current_tool_call_index!=null&&R(this,Ct,"m",Vf).call(this,S,I.current_tool_call_index));for(const T of b.delta.tool_calls??[])I.current_tool_call_index!==T.index&&(R(this,Ct,"m",Zf).call(this,S),I.current_tool_call_index!=null&&R(this,Ct,"m",Vf).call(this,S,I.current_tool_call_index)),I.current_tool_call_index=T.index;for(const T of b.delta.tool_calls??[]){const x=(y=S.message.tool_calls)==null?void 0:y[T.index];x!=null&&x.type&&((x==null?void 0:x.type)==="function"?this._emit("tool_calls.function.arguments.delta",{name:(w=x.function)==null?void 0:w.name,index:T.index,arguments:x.function.arguments,parsed_arguments:x.function.parsed_arguments,arguments_delta:((g=T.function)==null?void 0:g.arguments)??""}):(x==null||x.type,void 0))}}},Vf=function(n,r){var i,o,c;if(R(this,Ct,"m",Hu).call(this,n).done_tool_calls.has(r))return;const a=(i=n.message.tool_calls)==null?void 0:i[r];if(!a)throw new Error("no tool call snapshot");if(!a.type)throw new Error("tool call snapshot missing `type`");if(a.type==="function"){const u=(c=(o=R(this,Yr,"f"))==null?void 0:o.tools)==null?void 0:c.find(l=>kd(l)&&l.function.name===a.function.name);this._emit("tool_calls.function.arguments.done",{name:a.function.name,index:r,arguments:a.function.arguments,parsed_arguments:su(u)?u.$parseRaw(a.function.arguments):u!=null&&u.function.strict?JSON.parse(a.function.arguments):null})}else a.type},Zf=function(n){var s,a;const r=R(this,Ct,"m",Hu).call(this,n);if(n.message.content&&!r.content_done){r.content_done=!0;const i=R(this,Ct,"m",Wf).call(this);this._emit("content.done",{content:n.message.content,parsed:i?i.$parseRaw(n.message.content):null})}n.message.refusal&&!r.refusal_done&&(r.refusal_done=!0,this._emit("refusal.done",{refusal:n.message.refusal})),(s=n.logprobs)!=null&&s.content&&!r.logprobs_content_done&&(r.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:n.logprobs.content})),(a=n.logprobs)!=null&&a.refusal&&!r.logprobs_refusal_done&&(r.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:n.logprobs.refusal}))},Vu=function(){if(this.ended)throw new he("stream has ended, this shouldn't happen");const n=R(this,As,"f");if(!n)throw new he("request ended without sending any chunks");return xe(this,As,void 0),xe(this,Ja,[]),n9(n,R(this,Yr,"f"))},Wf=function(){var r;const n=(r=R(this,Yr,"f"))==null?void 0:r.response_format;return C_(n)?n:null},dv=function(n){var r,s,a,i;let o=R(this,As,"f");const{choices:c,...u}=n;o?Object.assign(o,u):o=xe(this,As,{...u,choices:[]});for(const{delta:l,finish_reason:d,index:f,logprobs:h=null,...m}of n.choices){let _=o.choices[f];if(_||(_=o.choices[f]={finish_reason:d,index:f,message:{},logprobs:h,...m}),h)if(!_.logprobs)_.logprobs=Object.assign({},h);else{const{content:T,refusal:x,...A}=h;Object.assign(_.logprobs,A),T&&((r=_.logprobs).content??(r.content=[]),_.logprobs.content.push(...T)),x&&((s=_.logprobs).refusal??(s.refusal=[]),_.logprobs.refusal.push(...x))}if(d&&(_.finish_reason=d,R(this,Yr,"f")&&ux(R(this,Yr,"f")))){if(d==="length")throw new FI;if(d==="content_filter")throw new BI}if(Object.assign(_,m),!l)continue;const{content:y,refusal:w,function_call:g,role:b,tool_calls:S,...I}=l;if(Object.assign(_.message,I),w&&(_.message.refusal=(_.message.refusal||"")+w),b&&(_.message.role=b),g&&(_.message.function_call?(g.name&&(_.message.function_call.name=g.name),g.arguments&&((a=_.message.function_call).arguments??(a.arguments=""),_.message.function_call.arguments+=g.arguments)):_.message.function_call=g),y&&(_.message.content=(_.message.content||"")+y,!_.message.refusal&&R(this,Ct,"m",Wf).call(this)&&(_.message.parsed=lv(_.message.content))),S){_.message.tool_calls||(_.message.tool_calls=[]);for(const{index:T,id:x,type:A,function:M,...O}of S){const $=(i=_.message.tool_calls)[T]??(i[T]={});Object.assign($,O),x&&($.id=x),A&&($.type=A),M&&($.function??($.function={name:M.name??"",arguments:""})),M!=null&&M.name&&($.function.name=M.name),M!=null&&M.arguments&&($.function.arguments+=M.arguments,G5(R(this,Yr,"f"),$)&&($.function.parsed_arguments=lv($.function.arguments)))}}}return o},Symbol.asyncIterator)](){const e=[],n=[];let r=!1;return this.on("chunk",s=>{const a=n.shift();a?a.resolve(s):e.push(s)}),this.on("end",()=>{r=!0;for(const s of n)s.resolve(void 0);n.length=0}),this.on("abort",s=>{r=!0;for(const a of n)a.reject(s);n.length=0}),this.on("error",s=>{r=!0;for(const a of n)a.reject(s);n.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((a,i)=>n.push({resolve:a,reject:i})).then(a=>a?{value:a,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new Cc(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function n9(t,e){const{id:n,choices:r,created:s,model:a,system_fingerprint:i,...o}=t,c={...o,id:n,choices:r.map(({message:u,finish_reason:l,index:d,logprobs:f,...h})=>{if(!l)throw new he(`missing finish_reason for choice ${d}`);const{content:m=null,function_call:_,tool_calls:y,...w}=u,g=u.role;if(!g)throw new he(`missing role for choice ${d}`);if(_){const{arguments:b,name:S}=_;if(b==null)throw new he(`missing function_call.arguments for choice ${d}`);if(!S)throw new he(`missing function_call.name for choice ${d}`);return{...h,message:{content:m,function_call:{arguments:b,name:S},role:g,refusal:u.refusal??null},finish_reason:l,index:d,logprobs:f}}return y?{...h,index:d,finish_reason:l,logprobs:f,message:{...w,role:g,content:m,refusal:u.refusal??null,tool_calls:y.map((b,S)=>{const{function:I,type:T,id:x,...A}=b,{arguments:M,name:O,...$}=I||{};if(x==null)throw new he(`missing choices[${d}].tool_calls[${S}].id
322
- ${Zu(t)}`);if(T==null)throw new he(`missing choices[${d}].tool_calls[${S}].type
323
- ${Zu(t)}`);if(O==null)throw new he(`missing choices[${d}].tool_calls[${S}].function.name
324
- ${Zu(t)}`);if(M==null)throw new he(`missing choices[${d}].tool_calls[${S}].function.arguments
325
- ${Zu(t)}`);return{...A,id:x,type:T,function:{...$,name:O,arguments:M}}})}}:{...h,message:{...w,content:m,role:g,refusal:u.refusal??null},finish_reason:l,index:d,logprobs:f}}),created:s,model:a,object:"chat.completion",...i?{system_fingerprint:i}:{}};return V5(c,e)}function Zu(t){return JSON.stringify(t)}class Nd extends $c{static fromReadableStream(e){const n=new Nd(null);return n._run(()=>n._fromReadableStream(e)),n}static runTools(e,n,r){const s=new Nd(n),a={...r,headers:{...r==null?void 0:r.headers,"X-Stainless-Helper-Method":"runTools"}};return s._run(()=>s._runTools(e,n,a)),s}}let P_=class extends fe{constructor(){super(...arguments),this.messages=new cx(this._client)}create(e,n){return this._client.post("/chat/completions",{body:e,...n,stream:e.stream??!1})}retrieve(e,n){return this._client.get(D`/chat/completions/${e}`,n)}update(e,n,r){return this._client.post(D`/chat/completions/${e}`,{body:n,...r})}list(e={},n){return this._client.getAPIList("/chat/completions",St,{query:e,...n})}delete(e,n){return this._client.delete(D`/chat/completions/${e}`,n)}parse(e,n){return q5(e.tools),this._client.chat.completions.create(e,{...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap(r=>R_(r,e))}runTools(e,n){return e.stream?Nd.runTools(this._client,e,n):N_.runTools(this._client,e,n)}stream(e,n){return $c.createChatCompletion(this._client,e,n)}};P_.Messages=cx;class M_ extends fe{constructor(){super(...arguments),this.completions=new P_(this._client)}}M_.Completions=P_;const Ox=Symbol("brand.privateNullableHeaders");function*r9(t){if(!t)return;if(Ox in t){const{values:r,nulls:s}=t;yield*r.entries();for(const a of s)yield[a,null];return}let e=!1,n;t instanceof Headers?n=t.entries():qb(t)?n=t:(e=!0,n=Object.entries(t??{}));for(let r of n){const s=r[0];if(typeof s!="string")throw new TypeError("expected header name to be a string");const a=qb(r[1])?r[1]:[r[1]];let i=!1;for(const o of a)o!==void 0&&(e&&!i&&(i=!0,yield[s,null]),yield[s,o])}}const ae=t=>{const e=new Headers,n=new Set;for(const r of t){const s=new Set;for(const[a,i]of r9(r)){const o=a.toLowerCase();s.has(o)||(e.delete(a),s.add(o)),i===null?(e.delete(a),n.add(o)):(e.append(a,i),n.delete(o))}}return{[Ox]:!0,values:e,nulls:n}};class Cx extends fe{create(e,n){return this._client.post("/audio/speech",{body:e,...n,headers:ae([{Accept:"application/octet-stream"},n==null?void 0:n.headers]),__binaryResponse:!0})}}class Rx extends fe{create(e,n){return this._client.post("/audio/transcriptions",zr({body:e,...n,stream:e.stream??!1,__metadata:{model:e.model}},this._client))}}class $x extends fe{create(e,n){return this._client.post("/audio/translations",zr({body:e,...n,__metadata:{model:e.model}},this._client))}}class au extends fe{constructor(){super(...arguments),this.transcriptions=new Rx(this._client),this.translations=new $x(this._client),this.speech=new Cx(this._client)}}au.Transcriptions=Rx;au.Translations=$x;au.Speech=Cx;let Nx=class extends fe{create(e,n){return this._client.post("/batches",{body:e,...n})}retrieve(e,n){return this._client.get(D`/batches/${e}`,n)}list(e={},n){return this._client.getAPIList("/batches",St,{query:e,...n})}cancel(e,n){return this._client.post(D`/batches/${e}/cancel`,n)}};class Px extends fe{create(e,n){return this._client.post("/assistants",{body:e,...n,headers:ae([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}retrieve(e,n){return this._client.get(D`/assistants/${e}`,{...n,headers:ae([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}update(e,n,r){return this._client.post(D`/assistants/${e}`,{body:n,...r,headers:ae([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}list(e={},n){return this._client.getAPIList("/assistants",St,{query:e,...n,headers:ae([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}delete(e,n){return this._client.delete(D`/assistants/${e}`,{...n,headers:ae([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}}let Mx=class extends fe{create(e,n){return this._client.post("/realtime/sessions",{body:e,...n,headers:ae([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}};class Lx extends fe{create(e,n){return this._client.post("/realtime/transcription_sessions",{body:e,...n,headers:ae([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}}let Sh=class extends fe{constructor(){super(...arguments),this.sessions=new Mx(this._client),this.transcriptionSessions=new Lx(this._client)}};Sh.Sessions=Mx;Sh.TranscriptionSessions=Lx;let jx=class extends fe{create(e,n){return this._client.post("/chatkit/sessions",{body:e,...n,headers:ae([{"OpenAI-Beta":"chatkit_beta=v1"},n==null?void 0:n.headers])})}cancel(e,n){return this._client.post(D`/chatkit/sessions/${e}/cancel`,{...n,headers:ae([{"OpenAI-Beta":"chatkit_beta=v1"},n==null?void 0:n.headers])})}},Ux=class extends fe{retrieve(e,n){return this._client.get(D`/chatkit/threads/${e}`,{...n,headers:ae([{"OpenAI-Beta":"chatkit_beta=v1"},n==null?void 0:n.headers])})}list(e={},n){return this._client.getAPIList("/chatkit/threads",Rc,{query:e,...n,headers:ae([{"OpenAI-Beta":"chatkit_beta=v1"},n==null?void 0:n.headers])})}delete(e,n){return this._client.delete(D`/chatkit/threads/${e}`,{...n,headers:ae([{"OpenAI-Beta":"chatkit_beta=v1"},n==null?void 0:n.headers])})}listItems(e,n={},r){return this._client.getAPIList(D`/chatkit/threads/${e}/items`,Rc,{query:n,...r,headers:ae([{"OpenAI-Beta":"chatkit_beta=v1"},r==null?void 0:r.headers])})}};class Th extends fe{constructor(){super(...arguments),this.sessions=new jx(this._client),this.threads=new Ux(this._client)}}Th.Sessions=jx;Th.Threads=Ux;let Dx=class extends fe{create(e,n,r){return this._client.post(D`/threads/${e}/messages`,{body:n,...r,headers:ae([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}retrieve(e,n,r){const{thread_id:s}=n;return this._client.get(D`/threads/${s}/messages/${e}`,{...r,headers:ae([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}update(e,n,r){const{thread_id:s,...a}=n;return this._client.post(D`/threads/${s}/messages/${e}`,{body:a,...r,headers:ae([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}list(e,n={},r){return this._client.getAPIList(D`/threads/${e}/messages`,St,{query:n,...r,headers:ae([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}delete(e,n,r){const{thread_id:s}=n;return this._client.delete(D`/threads/${s}/messages/${e}`,{...r,headers:ae([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}};class Fx extends fe{retrieve(e,n,r){const{thread_id:s,run_id:a,...i}=n;return this._client.get(D`/threads/${s}/runs/${a}/steps/${e}`,{query:i,...r,headers:ae([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}list(e,n,r){const{thread_id:s,...a}=n;return this._client.getAPIList(D`/threads/${s}/runs/${e}/steps`,St,{query:a,...r,headers:ae([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}}const s9=t=>{if(typeof Buffer<"u"){const e=Buffer.from(t,"base64");return Array.from(new Float32Array(e.buffer,e.byteOffset,e.length/Float32Array.BYTES_PER_ELEMENT))}else{const e=atob(t),n=e.length,r=new Uint8Array(n);for(let s=0;s<n;s++)r[s]=e.charCodeAt(s);return Array.from(new Float32Array(r.buffer))}};var Gf={};const cs=t=>{var e,n,r,s;if(typeof globalThis.process<"u")return((e=Gf==null?void 0:Gf[t])==null?void 0:e.trim())||void 0;if(typeof globalThis.Deno<"u")return((s=(r=(n=globalThis.Deno.env)==null?void 0:n.get)==null?void 0:r.call(n,t))==null?void 0:s.trim())||void 0};var Jt,Ea,zm,Lr,Ll,wr,Aa,wi,wa,Pd,Bn,jl,Ul,rc,Zo,Wo,hv,fv,pv,mv,gv,_v,yv;class sc extends $_{constructor(){super(...arguments),Jt.add(this),zm.set(this,[]),Lr.set(this,{}),Ll.set(this,{}),wr.set(this,void 0),Aa.set(this,void 0),wi.set(this,void 0),wa.set(this,void 0),Pd.set(this,void 0),Bn.set(this,void 0),jl.set(this,void 0),Ul.set(this,void 0),rc.set(this,void 0)}[(zm=new WeakMap,Lr=new WeakMap,Ll=new WeakMap,wr=new WeakMap,Aa=new WeakMap,wi=new WeakMap,wa=new WeakMap,Pd=new WeakMap,Bn=new WeakMap,jl=new WeakMap,Ul=new WeakMap,rc=new WeakMap,Jt=new WeakSet,Symbol.asyncIterator)](){const e=[],n=[];let r=!1;return this.on("event",s=>{const a=n.shift();a?a.resolve(s):e.push(s)}),this.on("end",()=>{r=!0;for(const s of n)s.resolve(void 0);n.length=0}),this.on("abort",s=>{r=!0;for(const a of n)a.reject(s);n.length=0}),this.on("error",s=>{r=!0;for(const a of n)a.reject(s);n.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((a,i)=>n.push({resolve:a,reject:i})).then(a=>a?{value:a,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){const n=new Ea;return n._run(()=>n._fromReadableStream(e)),n}async _fromReadableStream(e,n){var a;const r=n==null?void 0:n.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),this._connected();const s=Cc.fromReadableStream(e,this.controller);for await(const i of s)R(this,Jt,"m",Zo).call(this,i);if((a=s.controller.signal)!=null&&a.aborted)throw new Zn;return this._addRun(R(this,Jt,"m",Wo).call(this))}toReadableStream(){return new Cc(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,n,r,s){const a=new Ea;return a._run(()=>a._runToolAssistantStream(e,n,r,{...s,headers:{...s==null?void 0:s.headers,"X-Stainless-Helper-Method":"stream"}})),a}async _createToolAssistantStream(e,n,r,s){var c;const a=s==null?void 0:s.signal;a&&(a.aborted&&this.controller.abort(),a.addEventListener("abort",()=>this.controller.abort()));const i={...r,stream:!0},o=await e.submitToolOutputs(n,i,{...s,signal:this.controller.signal});this._connected();for await(const u of o)R(this,Jt,"m",Zo).call(this,u);if((c=o.controller.signal)!=null&&c.aborted)throw new Zn;return this._addRun(R(this,Jt,"m",Wo).call(this))}static createThreadAssistantStream(e,n,r){const s=new Ea;return s._run(()=>s._threadAssistantStream(e,n,{...r,headers:{...r==null?void 0:r.headers,"X-Stainless-Helper-Method":"stream"}})),s}static createAssistantStream(e,n,r,s){const a=new Ea;return a._run(()=>a._runAssistantStream(e,n,r,{...s,headers:{...s==null?void 0:s.headers,"X-Stainless-Helper-Method":"stream"}})),a}currentEvent(){return R(this,jl,"f")}currentRun(){return R(this,Ul,"f")}currentMessageSnapshot(){return R(this,wr,"f")}currentRunStepSnapshot(){return R(this,rc,"f")}async finalRunSteps(){return await this.done(),Object.values(R(this,Lr,"f"))}async finalMessages(){return await this.done(),Object.values(R(this,Ll,"f"))}async finalRun(){if(await this.done(),!R(this,Aa,"f"))throw Error("Final run was not received.");return R(this,Aa,"f")}async _createThreadAssistantStream(e,n,r){var o;const s=r==null?void 0:r.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort()));const a={...n,stream:!0},i=await e.createAndRun(a,{...r,signal:this.controller.signal});this._connected();for await(const c of i)R(this,Jt,"m",Zo).call(this,c);if((o=i.controller.signal)!=null&&o.aborted)throw new Zn;return this._addRun(R(this,Jt,"m",Wo).call(this))}async _createAssistantStream(e,n,r,s){var c;const a=s==null?void 0:s.signal;a&&(a.aborted&&this.controller.abort(),a.addEventListener("abort",()=>this.controller.abort()));const i={...r,stream:!0},o=await e.create(n,i,{...s,signal:this.controller.signal});this._connected();for await(const u of o)R(this,Jt,"m",Zo).call(this,u);if((c=o.controller.signal)!=null&&c.aborted)throw new Zn;return this._addRun(R(this,Jt,"m",Wo).call(this))}static accumulateDelta(e,n){for(const[r,s]of Object.entries(n)){if(!e.hasOwnProperty(r)){e[r]=s;continue}let a=e[r];if(a==null){e[r]=s;continue}if(r==="index"||r==="type"){e[r]=s;continue}if(typeof a=="string"&&typeof s=="string")a+=s;else if(typeof a=="number"&&typeof s=="number")a+=s;else if(Rl(a)&&Rl(s))a=this.accumulateDelta(a,s);else if(Array.isArray(a)&&Array.isArray(s)){if(a.every(i=>typeof i=="string"||typeof i=="number")){a.push(...s);continue}for(const i of s){if(!Rl(i))throw new Error(`Expected array delta entry to be an object but got: ${i}`);const o=i.index;if(o==null)throw console.error(i),new Error("Expected array delta entry to have an `index` property");if(typeof o!="number")throw new Error(`Expected array delta entry \`index\` property to be a number but got ${o}`);const c=a[o];c==null?a.push(i):a[o]=this.accumulateDelta(c,i)}continue}else throw Error(`Unhandled record type: ${r}, deltaValue: ${s}, accValue: ${a}`);e[r]=a}return e}_addRun(e){return e}async _threadAssistantStream(e,n,r){return await this._createThreadAssistantStream(n,e,r)}async _runAssistantStream(e,n,r,s){return await this._createAssistantStream(n,e,r,s)}async _runToolAssistantStream(e,n,r,s){return await this._createToolAssistantStream(n,e,r,s)}}Ea=sc,Zo=function(e){if(!this.ended)switch(xe(this,jl,e),R(this,Jt,"m",pv).call(this,e),e.event){case"thread.created":break;case"thread.run.created":case"thread.run.queued":case"thread.run.in_progress":case"thread.run.requires_action":case"thread.run.completed":case"thread.run.incomplete":case"thread.run.failed":case"thread.run.cancelling":case"thread.run.cancelled":case"thread.run.expired":R(this,Jt,"m",yv).call(this,e);break;case"thread.run.step.created":case"thread.run.step.in_progress":case"thread.run.step.delta":case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":R(this,Jt,"m",fv).call(this,e);break;case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":R(this,Jt,"m",hv).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier")}},Wo=function(){if(this.ended)throw new he("stream has ended, this shouldn't happen");if(!R(this,Aa,"f"))throw Error("Final run has not been received");return R(this,Aa,"f")},hv=function(e){const[n,r]=R(this,Jt,"m",gv).call(this,e,R(this,wr,"f"));xe(this,wr,n),R(this,Ll,"f")[n.id]=n;for(const s of r){const a=n.content[s.index];(a==null?void 0:a.type)=="text"&&this._emit("textCreated",a.text)}switch(e.event){case"thread.message.created":this._emit("messageCreated",e.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",e.data.delta,n),e.data.delta.content)for(const s of e.data.delta.content){if(s.type=="text"&&s.text){let a=s.text,i=n.content[s.index];if(i&&i.type=="text")this._emit("textDelta",a,i.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(s.index!=R(this,wi,"f")){if(R(this,wa,"f"))switch(R(this,wa,"f").type){case"text":this._emit("textDone",R(this,wa,"f").text,R(this,wr,"f"));break;case"image_file":this._emit("imageFileDone",R(this,wa,"f").image_file,R(this,wr,"f"));break}xe(this,wi,s.index)}xe(this,wa,n.content[s.index])}break;case"thread.message.completed":case"thread.message.incomplete":if(R(this,wi,"f")!==void 0){const s=e.data.content[R(this,wi,"f")];if(s)switch(s.type){case"image_file":this._emit("imageFileDone",s.image_file,R(this,wr,"f"));break;case"text":this._emit("textDone",s.text,R(this,wr,"f"));break}}R(this,wr,"f")&&this._emit("messageDone",e.data),xe(this,wr,void 0)}},fv=function(e){const n=R(this,Jt,"m",mv).call(this,e);switch(xe(this,rc,n),e.event){case"thread.run.step.created":this._emit("runStepCreated",e.data);break;case"thread.run.step.delta":const r=e.data.delta;if(r.step_details&&r.step_details.type=="tool_calls"&&r.step_details.tool_calls&&n.step_details.type=="tool_calls")for(const a of r.step_details.tool_calls)a.index==R(this,Pd,"f")?this._emit("toolCallDelta",a,n.step_details.tool_calls[a.index]):(R(this,Bn,"f")&&this._emit("toolCallDone",R(this,Bn,"f")),xe(this,Pd,a.index),xe(this,Bn,n.step_details.tool_calls[a.index]),R(this,Bn,"f")&&this._emit("toolCallCreated",R(this,Bn,"f")));this._emit("runStepDelta",e.data.delta,n);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":xe(this,rc,void 0),e.data.step_details.type=="tool_calls"&&R(this,Bn,"f")&&(this._emit("toolCallDone",R(this,Bn,"f")),xe(this,Bn,void 0)),this._emit("runStepDone",e.data,n);break}},pv=function(e){R(this,zm,"f").push(e),this._emit("event",e)},mv=function(e){switch(e.event){case"thread.run.step.created":return R(this,Lr,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let n=R(this,Lr,"f")[e.data.id];if(!n)throw Error("Received a RunStepDelta before creation of a snapshot");let r=e.data;if(r.delta){const s=Ea.accumulateDelta(n,r.delta);R(this,Lr,"f")[e.data.id]=s}return R(this,Lr,"f")[e.data.id];case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":case"thread.run.step.in_progress":R(this,Lr,"f")[e.data.id]=e.data;break}if(R(this,Lr,"f")[e.data.id])return R(this,Lr,"f")[e.data.id];throw new Error("No snapshot available")},gv=function(e,n){let r=[];switch(e.event){case"thread.message.created":return[e.data,r];case"thread.message.delta":if(!n)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let s=e.data;if(s.delta.content)for(const a of s.delta.content)if(a.index in n.content){let i=n.content[a.index];n.content[a.index]=R(this,Jt,"m",_v).call(this,a,i)}else n.content[a.index]=a,r.push(a);return[n,r];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(n)return[n,r];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},_v=function(e,n){return Ea.accumulateDelta(n,e)},yv=function(e){switch(xe(this,Ul,e.data),e.event){case"thread.run.created":break;case"thread.run.queued":break;case"thread.run.in_progress":break;case"thread.run.requires_action":case"thread.run.cancelled":case"thread.run.failed":case"thread.run.completed":case"thread.run.expired":case"thread.run.incomplete":xe(this,Aa,e.data),R(this,Bn,"f")&&(this._emit("toolCallDone",R(this,Bn,"f")),xe(this,Bn,void 0));break}};let L_=class extends fe{constructor(){super(...arguments),this.steps=new Fx(this._client)}create(e,n,r){const{include:s,...a}=n;return this._client.post(D`/threads/${e}/runs`,{query:{include:s},body:a,...r,headers:ae([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers]),stream:n.stream??!1,__synthesizeEventData:!0})}retrieve(e,n,r){const{thread_id:s}=n;return this._client.get(D`/threads/${s}/runs/${e}`,{...r,headers:ae([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}update(e,n,r){const{thread_id:s,...a}=n;return this._client.post(D`/threads/${s}/runs/${e}`,{body:a,...r,headers:ae([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}list(e,n={},r){return this._client.getAPIList(D`/threads/${e}/runs`,St,{query:n,...r,headers:ae([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}cancel(e,n,r){const{thread_id:s}=n;return this._client.post(D`/threads/${s}/runs/${e}/cancel`,{...r,headers:ae([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}async createAndPoll(e,n,r){const s=await this.create(e,n,r);return await this.poll(s.id,{thread_id:e},r)}createAndStream(e,n,r){return sc.createAssistantStream(e,this._client.beta.threads.runs,n,r)}async poll(e,n,r){var a;const s=ae([r==null?void 0:r.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":((a=r==null?void 0:r.pollIntervalMs)==null?void 0:a.toString())??void 0}]);for(;;){const{data:i,response:o}=await this.retrieve(e,n,{...r,headers:{...r==null?void 0:r.headers,...s}}).withResponse();switch(i.status){case"queued":case"in_progress":case"cancelling":let c=5e3;if(r!=null&&r.pollIntervalMs)c=r.pollIntervalMs;else{const u=o.headers.get("openai-poll-after-ms");if(u){const l=parseInt(u);isNaN(l)||(c=l)}}await ru(c);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return i}}}stream(e,n,r){return sc.createAssistantStream(e,this._client.beta.threads.runs,n,r)}submitToolOutputs(e,n,r){const{thread_id:s,...a}=n;return this._client.post(D`/threads/${s}/runs/${e}/submit_tool_outputs`,{body:a,...r,headers:ae([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers]),stream:n.stream??!1,__synthesizeEventData:!0})}async submitToolOutputsAndPoll(e,n,r){const s=await this.submitToolOutputs(e,n,r);return await this.poll(s.id,n,r)}submitToolOutputsStream(e,n,r){return sc.createToolAssistantStream(e,this._client.beta.threads.runs,n,r)}};L_.Steps=Fx;class Eh extends fe{constructor(){super(...arguments),this.runs=new L_(this._client),this.messages=new Dx(this._client)}create(e={},n){return this._client.post("/threads",{body:e,...n,headers:ae([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}retrieve(e,n){return this._client.get(D`/threads/${e}`,{...n,headers:ae([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}update(e,n,r){return this._client.post(D`/threads/${e}`,{body:n,...r,headers:ae([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}delete(e,n){return this._client.delete(D`/threads/${e}`,{...n,headers:ae([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}createAndRun(e,n){return this._client.post("/threads/runs",{body:e,...n,headers:ae([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers]),stream:e.stream??!1,__synthesizeEventData:!0})}async createAndRunPoll(e,n){const r=await this.createAndRun(e,n);return await this.runs.poll(r.id,{thread_id:r.thread_id},n)}createAndRunStream(e,n){return sc.createThreadAssistantStream(e,this._client.beta.threads,n)}}Eh.Runs=L_;Eh.Messages=Dx;let Yi=class extends fe{constructor(){super(...arguments),this.realtime=new Sh(this._client),this.chatkit=new Th(this._client),this.assistants=new Px(this._client),this.threads=new Eh(this._client)}};Yi.Realtime=Sh;Yi.ChatKit=Th;Yi.Assistants=Px;Yi.Threads=Eh;let Bx=class extends fe{create(e,n){return this._client.post("/completions",{body:e,...n,stream:e.stream??!1})}},zx=class extends fe{retrieve(e,n,r){const{container_id:s}=n;return this._client.get(D`/containers/${s}/files/${e}/content`,{...r,headers:ae([{Accept:"application/binary"},r==null?void 0:r.headers]),__binaryResponse:!0})}},j_=class extends fe{constructor(){super(...arguments),this.content=new zx(this._client)}create(e,n,r){return this._client.post(D`/containers/${e}/files`,vh({body:n,...r},this._client))}retrieve(e,n,r){const{container_id:s}=n;return this._client.get(D`/containers/${s}/files/${e}`,r)}list(e,n={},r){return this._client.getAPIList(D`/containers/${e}/files`,St,{query:n,...r})}delete(e,n,r){const{container_id:s}=n;return this._client.delete(D`/containers/${s}/files/${e}`,{...r,headers:ae([{Accept:"*/*"},r==null?void 0:r.headers])})}};j_.Content=zx;class U_ extends fe{constructor(){super(...arguments),this.files=new j_(this._client)}create(e,n){return this._client.post("/containers",{body:e,...n})}retrieve(e,n){return this._client.get(D`/containers/${e}`,n)}list(e={},n){return this._client.getAPIList("/containers",St,{query:e,...n})}delete(e,n){return this._client.delete(D`/containers/${e}`,{...n,headers:ae([{Accept:"*/*"},n==null?void 0:n.headers])})}}U_.Files=j_;class Hx extends fe{create(e,n,r){const{include:s,...a}=n;return this._client.post(D`/conversations/${e}/items`,{query:{include:s},body:a,...r})}retrieve(e,n,r){const{conversation_id:s,...a}=n;return this._client.get(D`/conversations/${s}/items/${e}`,{query:a,...r})}list(e,n={},r){return this._client.getAPIList(D`/conversations/${e}/items`,Rc,{query:n,...r})}delete(e,n,r){const{conversation_id:s}=n;return this._client.delete(D`/conversations/${s}/items/${e}`,r)}}class D_ extends fe{constructor(){super(...arguments),this.items=new Hx(this._client)}create(e={},n){return this._client.post("/conversations",{body:e,...n})}retrieve(e,n){return this._client.get(D`/conversations/${e}`,n)}update(e,n,r){return this._client.post(D`/conversations/${e}`,{body:n,...r})}delete(e,n){return this._client.delete(D`/conversations/${e}`,n)}}D_.Items=Hx;class Vx extends fe{create(e,n){const r=!!e.encoding_format;let s=r?e.encoding_format:"base64";r&&Kt(this._client).debug("embeddings/user defined encoding_format:",e.encoding_format);const a=this._client.post("/embeddings",{body:{...e,encoding_format:s},...n});return r?a:(Kt(this._client).debug("embeddings/decoding base64 embeddings from base64"),a._thenUnwrap(i=>(i&&i.data&&i.data.forEach(o=>{const c=o.embedding;o.embedding=s9(c)}),i)))}}class Zx extends fe{retrieve(e,n,r){const{eval_id:s,run_id:a}=n;return this._client.get(D`/evals/${s}/runs/${a}/output_items/${e}`,r)}list(e,n,r){const{eval_id:s,...a}=n;return this._client.getAPIList(D`/evals/${s}/runs/${e}/output_items`,St,{query:a,...r})}}class F_ extends fe{constructor(){super(...arguments),this.outputItems=new Zx(this._client)}create(e,n,r){return this._client.post(D`/evals/${e}/runs`,{body:n,...r})}retrieve(e,n,r){const{eval_id:s}=n;return this._client.get(D`/evals/${s}/runs/${e}`,r)}list(e,n={},r){return this._client.getAPIList(D`/evals/${e}/runs`,St,{query:n,...r})}delete(e,n,r){const{eval_id:s}=n;return this._client.delete(D`/evals/${s}/runs/${e}`,r)}cancel(e,n,r){const{eval_id:s}=n;return this._client.post(D`/evals/${s}/runs/${e}`,r)}}F_.OutputItems=Zx;class B_ extends fe{constructor(){super(...arguments),this.runs=new F_(this._client)}create(e,n){return this._client.post("/evals",{body:e,...n})}retrieve(e,n){return this._client.get(D`/evals/${e}`,n)}update(e,n,r){return this._client.post(D`/evals/${e}`,{body:n,...r})}list(e={},n){return this._client.getAPIList("/evals",St,{query:e,...n})}delete(e,n){return this._client.delete(D`/evals/${e}`,n)}}B_.Runs=F_;let Wx=class extends fe{create(e,n){return this._client.post("/files",zr({body:e,...n},this._client))}retrieve(e,n){return this._client.get(D`/files/${e}`,n)}list(e={},n){return this._client.getAPIList("/files",St,{query:e,...n})}delete(e,n){return this._client.delete(D`/files/${e}`,n)}content(e,n){return this._client.get(D`/files/${e}/content`,{...n,headers:ae([{Accept:"application/binary"},n==null?void 0:n.headers]),__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:n=5e3,maxWait:r=30*60*1e3}={}){const s=new Set(["processed","error","deleted"]),a=Date.now();let i=await this.retrieve(e);for(;!i.status||!s.has(i.status);)if(await ru(n),i=await this.retrieve(e),Date.now()-a>r)throw new yh({message:`Giving up on waiting for file ${e} to finish processing after ${r} milliseconds.`});return i}};class Gx extends fe{}let qx=class extends fe{run(e,n){return this._client.post("/fine_tuning/alpha/graders/run",{body:e,...n})}validate(e,n){return this._client.post("/fine_tuning/alpha/graders/validate",{body:e,...n})}};class z_ extends fe{constructor(){super(...arguments),this.graders=new qx(this._client)}}z_.Graders=qx;class Kx extends fe{create(e,n,r){return this._client.getAPIList(D`/fine_tuning/checkpoints/${e}/permissions`,bh,{body:n,method:"post",...r})}retrieve(e,n={},r){return this._client.get(D`/fine_tuning/checkpoints/${e}/permissions`,{query:n,...r})}list(e,n={},r){return this._client.getAPIList(D`/fine_tuning/checkpoints/${e}/permissions`,Rc,{query:n,...r})}delete(e,n,r){const{fine_tuned_model_checkpoint:s}=n;return this._client.delete(D`/fine_tuning/checkpoints/${s}/permissions/${e}`,r)}}let H_=class extends fe{constructor(){super(...arguments),this.permissions=new Kx(this._client)}};H_.Permissions=Kx;class Jx extends fe{list(e,n={},r){return this._client.getAPIList(D`/fine_tuning/jobs/${e}/checkpoints`,St,{query:n,...r})}}class V_ extends fe{constructor(){super(...arguments),this.checkpoints=new Jx(this._client)}create(e,n){return this._client.post("/fine_tuning/jobs",{body:e,...n})}retrieve(e,n){return this._client.get(D`/fine_tuning/jobs/${e}`,n)}list(e={},n){return this._client.getAPIList("/fine_tuning/jobs",St,{query:e,...n})}cancel(e,n){return this._client.post(D`/fine_tuning/jobs/${e}/cancel`,n)}listEvents(e,n={},r){return this._client.getAPIList(D`/fine_tuning/jobs/${e}/events`,St,{query:n,...r})}pause(e,n){return this._client.post(D`/fine_tuning/jobs/${e}/pause`,n)}resume(e,n){return this._client.post(D`/fine_tuning/jobs/${e}/resume`,n)}}V_.Checkpoints=Jx;class Qi extends fe{constructor(){super(...arguments),this.methods=new Gx(this._client),this.jobs=new V_(this._client),this.checkpoints=new H_(this._client),this.alpha=new z_(this._client)}}Qi.Methods=Gx;Qi.Jobs=V_;Qi.Checkpoints=H_;Qi.Alpha=z_;class Xx extends fe{}class Z_ extends fe{constructor(){super(...arguments),this.graderModels=new Xx(this._client)}}Z_.GraderModels=Xx;class Yx extends fe{createVariation(e,n){return this._client.post("/images/variations",zr({body:e,...n},this._client))}edit(e,n){return this._client.post("/images/edits",zr({body:e,...n,stream:e.stream??!1},this._client))}generate(e,n){return this._client.post("/images/generations",{body:e,...n,stream:e.stream??!1})}}let Qx=class extends fe{retrieve(e,n){return this._client.get(D`/models/${e}`,n)}list(e){return this._client.getAPIList("/models",bh,e)}delete(e,n){return this._client.delete(D`/models/${e}`,n)}};class ek extends fe{create(e,n){return this._client.post("/moderations",{body:e,...n})}}class tk extends fe{accept(e,n,r){return this._client.post(D`/realtime/calls/${e}/accept`,{body:n,...r,headers:ae([{Accept:"*/*"},r==null?void 0:r.headers])})}hangup(e,n){return this._client.post(D`/realtime/calls/${e}/hangup`,{...n,headers:ae([{Accept:"*/*"},n==null?void 0:n.headers])})}refer(e,n,r){return this._client.post(D`/realtime/calls/${e}/refer`,{body:n,...r,headers:ae([{Accept:"*/*"},r==null?void 0:r.headers])})}reject(e,n={},r){return this._client.post(D`/realtime/calls/${e}/reject`,{body:n,...r,headers:ae([{Accept:"*/*"},r==null?void 0:r.headers])})}}class nk extends fe{create(e,n){return this._client.post("/realtime/client_secrets",{body:e,...n})}}class Ah extends fe{constructor(){super(...arguments),this.clientSecrets=new nk(this._client),this.calls=new tk(this._client)}}Ah.ClientSecrets=nk;Ah.Calls=tk;function a9(t,e){return!e||!o9(e)?{...t,output_parsed:null,output:t.output.map(n=>n.type==="function_call"?{...n,parsed_arguments:null}:n.type==="message"?{...n,content:n.content.map(r=>({...r,parsed:null}))}:n)}:rk(t,e)}function rk(t,e){const n=t.output.map(s=>{if(s.type==="function_call")return{...s,parsed_arguments:l9(e,s)};if(s.type==="message"){const a=s.content.map(i=>i.type==="output_text"?{...i,parsed:i9(e,i.text)}:i);return{...s,content:a}}return s}),r=Object.assign({},t,{output:n});return Object.getOwnPropertyDescriptor(t,"output_text")||Hm(r),Object.defineProperty(r,"output_parsed",{enumerable:!0,get(){for(const s of r.output)if(s.type==="message"){for(const a of s.content)if(a.type==="output_text"&&a.parsed!==null)return a.parsed}return null}}),r}function i9(t,e){var n,r,s,a;return((r=(n=t.text)==null?void 0:n.format)==null?void 0:r.type)!=="json_schema"?null:"$parseRaw"in((s=t.text)==null?void 0:s.format)?((a=t.text)==null?void 0:a.format).$parseRaw(e):JSON.parse(e)}function o9(t){var e;return!!C_((e=t.text)==null?void 0:e.format)}function c9(t){return(t==null?void 0:t.$brand)==="auto-parseable-tool"}function u9(t,e){return t.find(n=>n.type==="function"&&n.name===e)}function l9(t,e){const n=u9(t.tools??[],e.name);return{...e,...e,parsed_arguments:c9(n)?n.$parseRaw(e.arguments):n!=null&&n.strict?JSON.parse(e.arguments):null}}function Hm(t){const e=[];for(const n of t.output)if(n.type==="message")for(const r of n.content)r.type==="output_text"&&e.push(r.text);t.output_text=e.join("")}var Xa,Wu,Is,Gu,wv,bv,vv,Sv;class W_ extends $_{constructor(e){super(),Xa.add(this),Wu.set(this,void 0),Is.set(this,void 0),Gu.set(this,void 0),xe(this,Wu,e)}static createResponse(e,n,r){const s=new W_(n);return s._run(()=>s._createOrRetrieveResponse(e,n,{...r,headers:{...r==null?void 0:r.headers,"X-Stainless-Helper-Method":"stream"}})),s}async _createOrRetrieveResponse(e,n,r){var o;const s=r==null?void 0:r.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),R(this,Xa,"m",wv).call(this);let a,i=null;"response_id"in n?(a=await e.responses.retrieve(n.response_id,{stream:!0},{...r,signal:this.controller.signal,stream:!0}),i=n.starting_after??null):a=await e.responses.create({...n,stream:!0},{...r,signal:this.controller.signal}),this._connected();for await(const c of a)R(this,Xa,"m",bv).call(this,c,i);if((o=a.controller.signal)!=null&&o.aborted)throw new Zn;return R(this,Xa,"m",vv).call(this)}[(Wu=new WeakMap,Is=new WeakMap,Gu=new WeakMap,Xa=new WeakSet,wv=function(){this.ended||xe(this,Is,void 0)},bv=function(n,r){if(this.ended)return;const s=(i,o)=>{(r==null||o.sequence_number>r)&&this._emit(i,o)},a=R(this,Xa,"m",Sv).call(this,n);switch(s("event",n),n.type){case"response.output_text.delta":{const i=a.output[n.output_index];if(!i)throw new he(`missing output at index ${n.output_index}`);if(i.type==="message"){const o=i.content[n.content_index];if(!o)throw new he(`missing content at index ${n.content_index}`);if(o.type!=="output_text")throw new he(`expected content to be 'output_text', got ${o.type}`);s("response.output_text.delta",{...n,snapshot:o.text})}break}case"response.function_call_arguments.delta":{const i=a.output[n.output_index];if(!i)throw new he(`missing output at index ${n.output_index}`);i.type==="function_call"&&s("response.function_call_arguments.delta",{...n,snapshot:i.arguments});break}default:s(n.type,n);break}},vv=function(){if(this.ended)throw new he("stream has ended, this shouldn't happen");const n=R(this,Is,"f");if(!n)throw new he("request ended without sending any events");xe(this,Is,void 0);const r=d9(n,R(this,Wu,"f"));return xe(this,Gu,r),r},Sv=function(n){var s;let r=R(this,Is,"f");if(!r){if(n.type!=="response.created")throw new he(`When snapshot hasn't been set yet, expected 'response.created' event, got ${n.type}`);return r=xe(this,Is,n.response),r}switch(n.type){case"response.output_item.added":{r.output.push(n.item);break}case"response.content_part.added":{const a=r.output[n.output_index];if(!a)throw new he(`missing output at index ${n.output_index}`);const i=a.type,o=n.part;i==="message"&&o.type!=="reasoning_text"?a.content.push(o):i==="reasoning"&&o.type==="reasoning_text"&&(a.content||(a.content=[]),a.content.push(o));break}case"response.output_text.delta":{const a=r.output[n.output_index];if(!a)throw new he(`missing output at index ${n.output_index}`);if(a.type==="message"){const i=a.content[n.content_index];if(!i)throw new he(`missing content at index ${n.content_index}`);if(i.type!=="output_text")throw new he(`expected content to be 'output_text', got ${i.type}`);i.text+=n.delta}break}case"response.function_call_arguments.delta":{const a=r.output[n.output_index];if(!a)throw new he(`missing output at index ${n.output_index}`);a.type==="function_call"&&(a.arguments+=n.delta);break}case"response.reasoning_text.delta":{const a=r.output[n.output_index];if(!a)throw new he(`missing output at index ${n.output_index}`);if(a.type==="reasoning"){const i=(s=a.content)==null?void 0:s[n.content_index];if(!i)throw new he(`missing content at index ${n.content_index}`);if(i.type!=="reasoning_text")throw new he(`expected content to be 'reasoning_text', got ${i.type}`);i.text+=n.delta}break}case"response.completed":{xe(this,Is,n.response);break}}return r},Symbol.asyncIterator)](){const e=[],n=[];let r=!1;return this.on("event",s=>{const a=n.shift();a?a.resolve(s):e.push(s)}),this.on("end",()=>{r=!0;for(const s of n)s.resolve(void 0);n.length=0}),this.on("abort",s=>{r=!0;for(const a of n)a.reject(s);n.length=0}),this.on("error",s=>{r=!0;for(const a of n)a.reject(s);n.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((a,i)=>n.push({resolve:a,reject:i})).then(a=>a?{value:a,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();const e=R(this,Gu,"f");if(!e)throw new he("stream ended without producing a ChatCompletion");return e}}function d9(t,e){return a9(t,e)}class sk extends fe{list(e,n={},r){return this._client.getAPIList(D`/responses/${e}/input_items`,St,{query:n,...r})}}class ak extends fe{count(e={},n){return this._client.post("/responses/input_tokens",{body:e,...n})}}class Ih extends fe{constructor(){super(...arguments),this.inputItems=new sk(this._client),this.inputTokens=new ak(this._client)}create(e,n){return this._client.post("/responses",{body:e,...n,stream:e.stream??!1})._thenUnwrap(r=>("object"in r&&r.object==="response"&&Hm(r),r))}retrieve(e,n={},r){return this._client.get(D`/responses/${e}`,{query:n,...r,stream:(n==null?void 0:n.stream)??!1})._thenUnwrap(s=>("object"in s&&s.object==="response"&&Hm(s),s))}delete(e,n){return this._client.delete(D`/responses/${e}`,{...n,headers:ae([{Accept:"*/*"},n==null?void 0:n.headers])})}parse(e,n){return this._client.responses.create(e,n)._thenUnwrap(r=>rk(r,e))}stream(e,n){return W_.createResponse(this._client,e,n)}cancel(e,n){return this._client.post(D`/responses/${e}/cancel`,n)}compact(e,n){return this._client.post("/responses/compact",{body:e,...n})}}Ih.InputItems=sk;Ih.InputTokens=ak;let ik=class extends fe{retrieve(e,n){return this._client.get(D`/skills/${e}/content`,{...n,headers:ae([{Accept:"application/binary"},n==null?void 0:n.headers]),__binaryResponse:!0})}};class ok extends fe{retrieve(e,n,r){const{skill_id:s}=n;return this._client.get(D`/skills/${s}/versions/${e}/content`,{...r,headers:ae([{Accept:"application/binary"},r==null?void 0:r.headers]),__binaryResponse:!0})}}let G_=class extends fe{constructor(){super(...arguments),this.content=new ok(this._client)}create(e,n={},r){return this._client.post(D`/skills/${e}/versions`,vh({body:n,...r},this._client))}retrieve(e,n,r){const{skill_id:s}=n;return this._client.get(D`/skills/${s}/versions/${e}`,r)}list(e,n={},r){return this._client.getAPIList(D`/skills/${e}/versions`,St,{query:n,...r})}delete(e,n,r){const{skill_id:s}=n;return this._client.delete(D`/skills/${s}/versions/${e}`,r)}};G_.Content=ok;let xh=class extends fe{constructor(){super(...arguments),this.content=new ik(this._client),this.versions=new G_(this._client)}create(e={},n){return this._client.post("/skills",vh({body:e,...n},this._client))}retrieve(e,n){return this._client.get(D`/skills/${e}`,n)}update(e,n,r){return this._client.post(D`/skills/${e}`,{body:n,...r})}list(e={},n){return this._client.getAPIList("/skills",St,{query:e,...n})}delete(e,n){return this._client.delete(D`/skills/${e}`,n)}};xh.Content=ik;xh.Versions=G_;class ck extends fe{create(e,n,r){return this._client.post(D`/uploads/${e}/parts`,zr({body:n,...r},this._client))}}class q_ extends fe{constructor(){super(...arguments),this.parts=new ck(this._client)}create(e,n){return this._client.post("/uploads",{body:e,...n})}cancel(e,n){return this._client.post(D`/uploads/${e}/cancel`,n)}complete(e,n,r){return this._client.post(D`/uploads/${e}/complete`,{body:n,...r})}}q_.Parts=ck;const h9=async t=>{const e=await Promise.allSettled(t),n=e.filter(s=>s.status==="rejected");if(n.length){for(const s of n)console.error(s.reason);throw new Error(`${n.length} promise(s) failed - see the above errors`)}const r=[];for(const s of e)s.status==="fulfilled"&&r.push(s.value);return r};class uk extends fe{create(e,n,r){return this._client.post(D`/vector_stores/${e}/file_batches`,{body:n,...r,headers:ae([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}retrieve(e,n,r){const{vector_store_id:s}=n;return this._client.get(D`/vector_stores/${s}/file_batches/${e}`,{...r,headers:ae([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}cancel(e,n,r){const{vector_store_id:s}=n;return this._client.post(D`/vector_stores/${s}/file_batches/${e}/cancel`,{...r,headers:ae([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}async createAndPoll(e,n,r){const s=await this.create(e,n);return await this.poll(e,s.id,r)}listFiles(e,n,r){const{vector_store_id:s,...a}=n;return this._client.getAPIList(D`/vector_stores/${s}/file_batches/${e}/files`,St,{query:a,...r,headers:ae([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}async poll(e,n,r){var a;const s=ae([r==null?void 0:r.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":((a=r==null?void 0:r.pollIntervalMs)==null?void 0:a.toString())??void 0}]);for(;;){const{data:i,response:o}=await this.retrieve(n,{vector_store_id:e},{...r,headers:s}).withResponse();switch(i.status){case"in_progress":let c=5e3;if(r!=null&&r.pollIntervalMs)c=r.pollIntervalMs;else{const u=o.headers.get("openai-poll-after-ms");if(u){const l=parseInt(u);isNaN(l)||(c=l)}}await ru(c);break;case"failed":case"cancelled":case"completed":return i}}}async uploadAndPoll(e,{files:n,fileIds:r=[]},s){if(n==null||n.length==0)throw new Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");const a=(s==null?void 0:s.maxConcurrency)??5,i=Math.min(a,n.length),o=this._client,c=n.values(),u=[...r];async function l(f){for(let h of f){const m=await o.files.create({file:h,purpose:"assistants"},s);u.push(m.id)}}const d=Array(i).fill(c).map(l);return await h9(d),await this.createAndPoll(e,{file_ids:u})}}let lk=class extends fe{create(e,n,r){return this._client.post(D`/vector_stores/${e}/files`,{body:n,...r,headers:ae([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}retrieve(e,n,r){const{vector_store_id:s}=n;return this._client.get(D`/vector_stores/${s}/files/${e}`,{...r,headers:ae([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}update(e,n,r){const{vector_store_id:s,...a}=n;return this._client.post(D`/vector_stores/${s}/files/${e}`,{body:a,...r,headers:ae([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}list(e,n={},r){return this._client.getAPIList(D`/vector_stores/${e}/files`,St,{query:n,...r,headers:ae([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}delete(e,n,r){const{vector_store_id:s}=n;return this._client.delete(D`/vector_stores/${s}/files/${e}`,{...r,headers:ae([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}async createAndPoll(e,n,r){const s=await this.create(e,n,r);return await this.poll(e,s.id,r)}async poll(e,n,r){var a;const s=ae([r==null?void 0:r.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":((a=r==null?void 0:r.pollIntervalMs)==null?void 0:a.toString())??void 0}]);for(;;){const i=await this.retrieve(n,{vector_store_id:e},{...r,headers:s}).withResponse(),o=i.data;switch(o.status){case"in_progress":let c=5e3;if(r!=null&&r.pollIntervalMs)c=r.pollIntervalMs;else{const u=i.response.headers.get("openai-poll-after-ms");if(u){const l=parseInt(u);isNaN(l)||(c=l)}}await ru(c);break;case"failed":case"completed":return o}}}async upload(e,n,r){const s=await this._client.files.create({file:n,purpose:"assistants"},r);return this.create(e,{file_id:s.id},r)}async uploadAndPoll(e,n,r){const s=await this.upload(e,n,r);return await this.poll(e,s.id,r)}content(e,n,r){const{vector_store_id:s}=n;return this._client.getAPIList(D`/vector_stores/${s}/files/${e}/content`,bh,{...r,headers:ae([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}};class kh extends fe{constructor(){super(...arguments),this.files=new lk(this._client),this.fileBatches=new uk(this._client)}create(e,n){return this._client.post("/vector_stores",{body:e,...n,headers:ae([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}retrieve(e,n){return this._client.get(D`/vector_stores/${e}`,{...n,headers:ae([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}update(e,n,r){return this._client.post(D`/vector_stores/${e}`,{body:n,...r,headers:ae([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}list(e={},n){return this._client.getAPIList("/vector_stores",St,{query:e,...n,headers:ae([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}delete(e,n){return this._client.delete(D`/vector_stores/${e}`,{...n,headers:ae([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}search(e,n,r){return this._client.getAPIList(D`/vector_stores/${e}/search`,bh,{body:n,method:"post",...r,headers:ae([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}}kh.Files=lk;kh.FileBatches=uk;class dk extends fe{create(e,n){return this._client.post("/videos",zr({body:e,...n},this._client))}retrieve(e,n){return this._client.get(D`/videos/${e}`,n)}list(e={},n){return this._client.getAPIList("/videos",Rc,{query:e,...n})}delete(e,n){return this._client.delete(D`/videos/${e}`,n)}createCharacter(e,n){return this._client.post("/videos/characters",zr({body:e,...n},this._client))}downloadContent(e,n={},r){return this._client.get(D`/videos/${e}/content`,{query:n,...r,headers:ae([{Accept:"application/binary"},r==null?void 0:r.headers]),__binaryResponse:!0})}edit(e,n){return this._client.post("/videos/edits",zr({body:e,...n},this._client))}extend(e,n){return this._client.post("/videos/extensions",zr({body:e,...n},this._client))}getCharacter(e,n){return this._client.get(D`/videos/characters/${e}`,n)}remix(e,n,r){return this._client.post(D`/videos/${e}/remix`,vh({body:n,...r},this._client))}}var ui,hk,Dl;class fk extends fe{constructor(){super(...arguments),ui.add(this)}async unwrap(e,n,r=this._client.webhookSecret,s=300){return await this.verifySignature(e,n,r,s),JSON.parse(e)}async verifySignature(e,n,r=this._client.webhookSecret,s=300){if(typeof crypto>"u"||typeof crypto.subtle.importKey!="function"||typeof crypto.subtle.verify!="function")throw new Error("Webhook signature verification is only supported when the `crypto` global is defined");R(this,ui,"m",hk).call(this,r);const a=ae([n]).values,i=R(this,ui,"m",Dl).call(this,a,"webhook-signature"),o=R(this,ui,"m",Dl).call(this,a,"webhook-timestamp"),c=R(this,ui,"m",Dl).call(this,a,"webhook-id"),u=parseInt(o,10);if(isNaN(u))throw new jo("Invalid webhook timestamp format");const l=Math.floor(Date.now()/1e3);if(l-u>s)throw new jo("Webhook timestamp is too old");if(u>l+s)throw new jo("Webhook timestamp is too new");const d=i.split(" ").map(_=>_.startsWith("v1,")?_.substring(3):_),f=r.startsWith("whsec_")?Buffer.from(r.replace("whsec_",""),"base64"):Buffer.from(r,"utf-8"),h=c?`${c}.${o}.${e}`:`${o}.${e}`,m=await crypto.subtle.importKey("raw",f,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(const _ of d)try{const y=Buffer.from(_,"base64");if(await crypto.subtle.verify("HMAC",m,y,new TextEncoder().encode(h)))return}catch{continue}throw new jo("The given webhook signature does not match the expected signature")}}ui=new WeakSet,hk=function(e){if(typeof e!="string"||e.length===0)throw new Error("The webhook secret must either be set using the env var, OPENAI_WEBHOOK_SECRET, on the client class, OpenAI({ webhookSecret: '123' }), or passed to this function")},Dl=function(e,n){if(!e)throw new Error("Headers are required");const r=e.get(n);if(r==null)throw new Error(`Missing required header: ${n}`);return r};var Vm,K_,Fl,pk;const qf="workload-identity-auth";class Ne{constructor({baseURL:e=cs("OPENAI_BASE_URL"),apiKey:n=cs("OPENAI_API_KEY"),organization:r=cs("OPENAI_ORG_ID")??null,project:s=cs("OPENAI_PROJECT_ID")??null,webhookSecret:a=cs("OPENAI_WEBHOOK_SECRET")??null,workloadIdentity:i,...o}={}){if(Vm.add(this),Fl.set(this,void 0),this.completions=new Bx(this),this.chat=new M_(this),this.embeddings=new Vx(this),this.files=new Wx(this),this.images=new Yx(this),this.audio=new au(this),this.moderations=new ek(this),this.models=new Qx(this),this.fineTuning=new Qi(this),this.graders=new Z_(this),this.vectorStores=new kh(this),this.webhooks=new fk(this),this.beta=new Yi(this),this.batches=new Nx(this),this.uploads=new q_(this),this.responses=new Ih(this),this.realtime=new Ah(this),this.conversations=new D_(this),this.evals=new B_(this),this.containers=new U_(this),this.skills=new xh(this),this.videos=new dk(this),i){if(n&&n!==qf)throw new he("The `apiKey` and `workloadIdentity` arguments are mutually exclusive; only one can be passed at a time.");n=qf}else if(n===void 0)throw new he("Missing credentials. Please pass an `apiKey`, `workloadIdentity`, or set the `OPENAI_API_KEY` environment variable.");const c={apiKey:n,organization:r,project:s,webhookSecret:a,workloadIdentity:i,...o,baseURL:e||"https://api.openai.com/v1"};if(!c.dangerouslyAllowBrowser&&d5())throw new he(`It looks like you're running in a browser-like environment.
326
-
327
- This is disabled by default, as it risks exposing your secret API credentials to attackers.
328
- If you understand the risks and have appropriate mitigations in place,
329
- you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
330
-
331
- new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
332
-
333
- https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
334
- `);this.baseURL=c.baseURL,this.timeout=c.timeout??K_.DEFAULT_TIMEOUT,this.logger=c.logger??console;const u="warn";this.logLevel=u,this.logLevel=iv(c.logLevel,"ClientOptions.logLevel",this)??iv(cs("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??u,this.fetchOptions=c.fetchOptions,this.maxRetries=c.maxRetries??2,this.fetch=c.fetch??VI(),xe(this,Fl,g5),this._options=c,i&&(this._workloadIdentityAuth=new M5(i,this.fetch)),this.apiKey=typeof n=="string"?n:"Missing Key",this.organization=r,this.project=s,this.webhookSecret=a}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,workloadIdentity:this._options.workloadIdentity,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:n}){}async authHeaders(e){return ae([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(e){return T5(e)}getUserAgent(){return`${this.constructor.name}/JS ${oi}`}defaultIdempotencyKey(){return`stainless-node-retry-${RI()}`}makeStatusError(e,n,r,s){return hn.generate(e,n,r,s)}async _callApiKey(){const e=this._options.apiKey;if(typeof e!="function")return!1;let n;try{n=await e()}catch(r){throw r instanceof he?r:new he(`Failed to get token from 'apiKey' function: ${r.message}`,{cause:r})}if(typeof n!="string"||!n)throw new he(`Expected 'apiKey' function argument to return a string but it returned ${n}`);return this.apiKey=n,!0}buildURL(e,n,r){const s=!R(this,Vm,"m",pk).call(this)&&r||this.baseURL,a=o5(e)?new URL(e):new URL(s+(s.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),i=this.defaultQuery(),o=Object.fromEntries(a.searchParams);return(!Kb(i)||!Kb(o))&&(n={...o,...i,...n}),typeof n=="object"&&n&&!Array.isArray(n)&&(a.search=this.stringifyQuery(n)),a.toString()}async prepareOptions(e){await this._callApiKey()}async prepareRequest(e,{url:n,options:r}){}get(e,n){return this.methodRequest("get",e,n)}post(e,n){return this.methodRequest("post",e,n)}patch(e,n){return this.methodRequest("patch",e,n)}put(e,n){return this.methodRequest("put",e,n)}delete(e,n){return this.methodRequest("delete",e,n)}methodRequest(e,n,r){return this.request(Promise.resolve(r).then(s=>({method:e,path:n,...s})))}request(e,n=null){return new tx(this,this.makeRequest(e,n,void 0))}async makeRequest(e,n,r){var w,g,b,S;const s=await e,a=s.maxRetries??this.maxRetries;n==null&&(n=a),await this.prepareOptions(s);const{req:i,url:o,timeout:c}=await this.buildRequest(s,{retryCount:a-n});await this.prepareRequest(i,{url:o,options:s});const u="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),l=r===void 0?"":`, retryOf: ${r}`,d=Date.now();if(Kt(this).debug(`[${u}] sending request`,ma({retryOfRequestLogID:r,method:s.method,url:o,options:s,headers:i.headers})),(w=s.signal)!=null&&w.aborted)throw new Zn;const f=new AbortController,h=await this.fetchWithAuth(o,i,c,f).catch(Rm),m=Date.now();if(h instanceof globalThis.Error){const I=`retrying, ${n} attempts remaining`;if((g=s.signal)!=null&&g.aborted)throw new Zn;const T=Cm(h)||/timed? ?out/i.test(String(h)+("cause"in h?String(h.cause):""));if(n)return Kt(this).info(`[${u}] connection ${T?"timed out":"failed"} - ${I}`),Kt(this).debug(`[${u}] connection ${T?"timed out":"failed"} (${I})`,ma({retryOfRequestLogID:r,url:o,durationMs:m-d,message:h.message})),this.retryRequest(s,n,r??u);throw Kt(this).info(`[${u}] connection ${T?"timed out":"failed"} - error; no more retries left`),Kt(this).debug(`[${u}] connection ${T?"timed out":"failed"} (error; no more retries left)`,ma({retryOfRequestLogID:r,url:o,durationMs:m-d,message:h.message})),h instanceof zI||h instanceof a5?h:T?new yh:new _h({cause:h})}const _=[...h.headers.entries()].filter(([I])=>I==="x-request-id").map(([I,T])=>", "+I+": "+JSON.stringify(T)).join(""),y=`[${u}${l}${_}] ${i.method} ${o} ${h.ok?"succeeded":"failed"} with status ${h.status} in ${m-d}ms`;if(!h.ok){if(h.status===401&&this._workloadIdentityAuth&&!((b=s.__metadata)!=null&&b.hasStreamingBody)&&!((S=s.__metadata)!=null&&S.workloadIdentityTokenRefreshed))return await Qb(h.body),this._workloadIdentityAuth.invalidateToken(),this.makeRequest({...s,__metadata:{...s.__metadata,workloadIdentityTokenRefreshed:!0}},n,r??u);const I=await this.shouldRetry(h);if(n&&I){const $=`retrying, ${n} attempts remaining`;return await Qb(h.body),Kt(this).info(`${y} - ${$}`),Kt(this).debug(`[${u}] response error (${$})`,ma({retryOfRequestLogID:r,url:h.url,status:h.status,headers:h.headers,durationMs:m-d})),this.retryRequest(s,n,r??u,h.headers)}const T=I?"error; no more retries left":"error; not retryable";Kt(this).info(`${y} - ${T}`);const x=await h.text().catch($=>Rm($).message),A=l5(x),M=A?void 0:x;throw Kt(this).debug(`[${u}] response error (${T})`,ma({retryOfRequestLogID:r,url:h.url,status:h.status,headers:h.headers,message:M,durationMs:Date.now()-d})),this.makeStatusError(h.status,A,M,h.headers)}return Kt(this).info(y),Kt(this).debug(`[${u}] response start`,ma({retryOfRequestLogID:r,url:h.url,status:h.status,headers:h.headers,durationMs:m-d})),{response:h,options:s,controller:f,requestLogID:u,retryOfRequestLogID:r,startTime:d}}getAPIList(e,n,r){return this.requestAPIList(n,r&&"then"in r?r.then(s=>({method:"get",path:e,...s})):{method:"get",path:e,...r})}requestAPIList(e,n){const r=this.makeRequest(n,null,void 0);return new $5(this,r,e)}async fetchWithAuth(e,n,r,s){if(this._workloadIdentityAuth){const i=n.headers,o=i.get("Authorization");if(!o||o===`Bearer ${qf}`){const c=await this._workloadIdentityAuth.getToken();i.set("Authorization",`Bearer ${c}`)}}return await this.fetchWithTimeout(e,n,r,s)}async fetchWithTimeout(e,n,r,s){const{signal:a,method:i,...o}=n||{},c=this._makeAbort(s);a&&a.addEventListener("abort",c,{once:!0});const u=setTimeout(c,r),l=globalThis.ReadableStream&&o.body instanceof globalThis.ReadableStream||typeof o.body=="object"&&o.body!==null&&Symbol.asyncIterator in o.body,d={signal:s.signal,...l?{duplex:"half"}:{},method:"GET",...o};i&&(d.method=i.toUpperCase());try{return await this.fetch.call(void 0,e,d)}finally{clearTimeout(u)}}async shouldRetry(e){const n=e.headers.get("x-should-retry");return n==="true"?!0:n==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,n,r,s){let a;const i=s==null?void 0:s.get("retry-after-ms");if(i){const c=parseFloat(i);Number.isNaN(c)||(a=c)}const o=s==null?void 0:s.get("retry-after");if(o&&!a){const c=parseFloat(o);Number.isNaN(c)?a=Date.parse(o)-Date.now():a=c*1e3}if(a===void 0){const c=e.maxRetries??this.maxRetries;a=this.calculateDefaultRetryTimeoutMillis(n,c)}return await ru(a),this.makeRequest(e,n-1,r)}calculateDefaultRetryTimeoutMillis(e,n){const a=n-e,i=Math.min(.5*Math.pow(2,a),8),o=1-Math.random()*.25;return i*o*1e3}async buildRequest(e,{retryCount:n=0}={}){const r={...e},{method:s,path:a,query:i,defaultBaseURL:o}=r,c=this.buildURL(a,i,o);"timeout"in r&&u5("timeout",r.timeout),r.timeout=r.timeout??this.timeout;const{bodyHeaders:u,body:l,isStreamingBody:d}=this.buildBody({options:r});d&&(e.__metadata={...e.__metadata,hasStreamingBody:!0});const f=await this.buildHeaders({options:e,method:s,bodyHeaders:u,retryCount:n});return{req:{method:s,headers:f,...r.signal&&{signal:r.signal},...globalThis.ReadableStream&&l instanceof globalThis.ReadableStream&&{duplex:"half"},...l&&{body:l},...this.fetchOptions??{},...r.fetchOptions??{}},url:c,timeout:r.timeout}}async buildHeaders({options:e,method:n,bodyHeaders:r,retryCount:s}){let a={};this.idempotencyHeader&&n!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),a[this.idempotencyHeader]=e.idempotencyKey);const i=ae([a,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(s),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...m5(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders(e),this._options.defaultHeaders,r,e.headers]);return this.validateHeaders(i),i.values}_makeAbort(e){return()=>e.abort()}buildBody({options:{body:e,headers:n}}){if(!e)return{bodyHeaders:void 0,body:void 0,isStreamingBody:!1};const r=ae([n]),s=typeof globalThis.ReadableStream<"u"&&e instanceof globalThis.ReadableStream,a=!s&&(typeof e=="string"||e instanceof ArrayBuffer||ArrayBuffer.isView(e)||typeof globalThis.Blob<"u"&&e instanceof globalThis.Blob||e instanceof URLSearchParams||e instanceof FormData);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&r.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||s?{bodyHeaders:void 0,body:e,isStreamingBody:!a}:typeof e=="object"&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")?{bodyHeaders:void 0,body:WI(e),isStreamingBody:!0}:typeof e=="object"&&r.values.get("content-type")==="application/x-www-form-urlencoded"?{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(e),isStreamingBody:!1}:{...R(this,Fl,"f").call(this,{body:e,headers:r}),isStreamingBody:!1}}}K_=Ne,Fl=new WeakMap,Vm=new WeakSet,pk=function(){return this.baseURL!=="https://api.openai.com/v1"};Ne.OpenAI=K_;Ne.DEFAULT_TIMEOUT=6e5;Ne.OpenAIError=he;Ne.APIError=hn;Ne.APIConnectionError=_h;Ne.APIConnectionTimeoutError=yh;Ne.APIUserAbortError=Zn;Ne.NotFoundError=MI;Ne.ConflictError=LI;Ne.RateLimitError=UI;Ne.BadRequestError=$I;Ne.AuthenticationError=NI;Ne.InternalServerError=DI;Ne.PermissionDeniedError=PI;Ne.UnprocessableEntityError=jI;Ne.InvalidWebhookSignatureError=jo;Ne.toFile=F5;Ne.Completions=Bx;Ne.Chat=M_;Ne.Embeddings=Vx;Ne.Files=Wx;Ne.Images=Yx;Ne.Audio=au;Ne.Moderations=ek;Ne.Models=Qx;Ne.FineTuning=Qi;Ne.Graders=Z_;Ne.VectorStores=kh;Ne.Webhooks=fk;Ne.Beta=Yi;Ne.Batches=Nx;Ne.Uploads=q_;Ne.Responses=Ih;Ne.Realtime=Ah;Ne.Conversations=D_;Ne.Evals=B_;Ne.Containers=U_;Ne.Skills=xh;Ne.Videos=dk;var f9={};class p9 extends Ne{constructor({baseURL:e=cs("OPENAI_BASE_URL"),apiKey:n=cs("AZURE_OPENAI_API_KEY"),apiVersion:r=cs("OPENAI_API_VERSION"),endpoint:s,deployment:a,azureADTokenProvider:i,dangerouslyAllowBrowser:o,...c}={}){if(!r)throw new he("The OPENAI_API_VERSION environment variable is missing or empty; either provide it, or instantiate the AzureOpenAI client with an apiVersion option, like new AzureOpenAI({ apiVersion: 'My API Version' }).");if(typeof i=="function"&&(o=!0),!i&&!n)throw new he("Missing credentials. Please pass one of `apiKey` and `azureADTokenProvider`, or set the `AZURE_OPENAI_API_KEY` environment variable.");if(i&&n)throw new he("The `apiKey` and `azureADTokenProvider` arguments are mutually exclusive; only one can be passed at a time.");if(c.defaultQuery={...c.defaultQuery,"api-version":r},e){if(s)throw new he("baseURL and endpoint are mutually exclusive")}else{if(s||(s=f9.AZURE_OPENAI_ENDPOINT),!s)throw new he("Must provide one of the `baseURL` or `endpoint` arguments, or the `AZURE_OPENAI_ENDPOINT` environment variable");e=`${s}/openai`}super({apiKey:i??n,baseURL:e,...c,...o!==void 0?{dangerouslyAllowBrowser:o}:{}}),this.apiVersion="",this.apiVersion=r,this.deploymentName=a}async buildRequest(e,n={}){var r;if(m9.has(e.path)&&e.method==="post"&&e.body!==void 0){if(!Rl(e.body))throw new Error("Expected request body to be an object");const s=this.deploymentName||e.body.model||((r=e.__metadata)==null?void 0:r.model);s!==void 0&&!this.baseURL.includes("/deployments")&&(e.path=`/deployments/${s}${e.path}`)}return super.buildRequest(e,n)}async authHeaders(e){return typeof this._options.apiKey=="string"?ae([{"api-key":this.apiKey}]):super.authHeaders(e)}}const m9=new Set(["/completions","/chat/completions","/embeddings","/audio/transcriptions","/audio/translations","/audio/speech","/images/generations","/batches","/images/edits"]);function g9(t){return!!(String(t).includes("context_length_exceeded")||"message"in t&&typeof t.message=="string"&&(t.message.includes("Input tokens exceed the configured limit")||t.message.includes("exceeds the context window")||t.message.includes("maximum context length")))}function J_(t){if(!t||typeof t!="object")return t;let e;return t.constructor.name===yh.name&&"message"in t&&typeof t.message=="string"?(e=new Error(t.message),e.name="TimeoutError"):t.constructor.name===Zn.name&&"message"in t&&typeof t.message=="string"?(e=new Error(t.message),e.name="AbortError"):g9(t)?e=sg.fromError(t):"status"in t&&t.status===400&&"message"in t&&typeof t.message=="string"&&t.message.includes("tool_calls")?e=Fu(t,"INVALID_TOOL_RESULTS"):"status"in t&&t.status===401?e=Fu(t,"MODEL_AUTHENTICATION"):"status"in t&&t.status===429?e=Fu(t,"MODEL_RATE_LIMIT"):"status"in t&&t.status===404?e=Fu(t,"MODEL_NOT_FOUND"):e=t,e}const ps=t=>t();function iu(t){return t?!!(/^o\d/.test(t??"")||t.startsWith("gpt-5")&&!t.startsWith("gpt-5-chat")):!1}function _9(t){return t.role!=="system"&&t.role!=="developer"&&t.role!=="assistant"&&t.role!=="user"&&t.role!=="function"&&t.role!=="tool"&&console.warn(`Unknown message role: ${t.role}`),t.role}function Tv(t){var e,n,r;return((e=t.metadata)==null?void 0:e.filename)??((n=t.metadata)==null?void 0:n.name)??((r=t.metadata)==null?void 0:r.title)}const y9="LC_AUTOGENERATED";function Md(t){var n,r,s;const e=((n=t.metadata)==null?void 0:n.filename)??((r=t.metadata)==null?void 0:r.name)??((s=t.metadata)==null?void 0:s.title);return e||(console.warn("OpenAI may require a filename for file uploads. Specify a filename in the content block metadata, e.g.: { type: 'file', mimeType: '...', data: '...', metadata: { filename: 'my-file.pdf' } }. Using placeholder filename 'LC_AUTOGENERATED'."),y9)}function ou(t){const e=t._getType();switch(e){case"system":return"system";case"ai":return"assistant";case"human":return"user";case"function":return"function";case"tool":return"tool";case"generic":if(!Kr.isInstance(t))throw new Error("Invalid generic chat message");return _9(t);default:throw new Error(`Unknown message type: ${e}`)}}function w9(t){return!!(t.includes("gpt-5.2-pro")||t.includes("gpt-5.4-pro")||t.includes("gpt-5.5-pro")||t.includes("codex"))}function mk(t){const{azureOpenAIApiDeploymentName:e,azureOpenAIApiInstanceName:n,azureOpenAIApiKey:r,azureOpenAIBasePath:s,baseURL:a,azureADTokenProvider:i,azureOpenAIEndpoint:o}=t;if((r||i)&&s&&e)return`${s}/${e}`;if((r||i)&&o&&e)return`${o}/openai/deployments/${e}`;if(r||i){if(!n)throw new Error("azureOpenAIApiInstanceName is required when using azureOpenAIApiKey");if(!e)throw new Error("azureOpenAIApiDeploymentName is a required parameter when using azureOpenAIApiKey");return`https://${n}.openai.azure.com/openai/deployments/${e}`}return a}function Ev(t){return typeof Headers<"u"&&t!==null&&typeof t=="object"&&Object.prototype.toString.call(t)==="[object Headers]"}function b9(t){const e=ps(()=>{if(Ev(t))return t;if(Array.isArray(t))return new Headers(t);if(typeof t=="object"&&t!==null&&"values"in t&&Ev(t.values))return t.values;if(typeof t=="object"&&t!==null){const n=Object.entries(t).filter(([,r])=>typeof r=="string").map(([r,s])=>[r,s]);return new Headers(n)}return new Headers});return Object.fromEntries(e.entries())}function v9(){let t=gg();return(t==="node"||t==="deno")&&(t=`(${t}/${process.version}; ${process.platform}; ${process.arch})`),t}function gk(t,e=!1,n="1.0.0"){const r=b9(t),s=v9(),a=`langchainjs${e?"-azure":""}-openai`;return{...r,"User-Agent":r["User-Agent"]?`${a}/${n} (${s})${r["User-Agent"]}`:`${a}/${n} (${s})`}}function S9(t,e){let n;return vs(t)?n=wd(t):n=t,(e==null?void 0:e.strict)!==void 0&&(n.function.strict=e.strict),n}function T9(t){return t.anyOf!==void 0&&Array.isArray(t.anyOf)}function E9(t){const e=["namespace functions {",""];for(const n of t)n.description&&e.push(`// ${n.description}`),Object.keys(n.parameters.properties??{}).length>0?(e.push(`type ${n.name} = (_: {`),e.push(_k(n.parameters,0)),e.push("}) => any;")):e.push(`type ${n.name} = () => any;`),e.push("");return e.push("} // namespace functions"),e.join(`
335
- `)}function _k(t,e){var r;const n=[];for(const[s,a]of Object.entries(t.properties??{}))a.description&&e<2&&n.push(`// ${a.description}`),(r=t.required)!=null&&r.includes(s)?n.push(`${s}: ${Ld(a,e)},`):n.push(`${s}?: ${Ld(a,e)},`);return n.map(s=>" ".repeat(e)+s).join(`
336
- `)}function Ld(t,e){if(T9(t))return t.anyOf.map(n=>Ld(n,e)).join(" | ");switch(t.type){case"string":return t.enum?t.enum.map(n=>`"${n}"`).join(" | "):"string";case"number":return t.enum?t.enum.map(n=>`${n}`).join(" | "):"number";case"integer":return t.enum?t.enum.map(n=>`${n}`).join(" | "):"number";case"boolean":return"boolean";case"null":return"null";case"object":return["{",_k(t,e+2),"}"].join(`
337
- `);case"array":return t.items?`${Ld(t.items,e)}[]`:"any[]";default:return""}}function yk(t){if(t)return t==="any"||t==="required"?"required":t==="auto"?"auto":t==="none"?"none":typeof t=="string"?{type:"function",function:{name:t}}:t}function X_(t){return"type"in t&&t.type!=="function"}function A9(t){return typeof t=="object"&&t!==null&&"extras"in t&&typeof t.extras=="object"&&t.extras!==null&&"providerToolDefinition"in t.extras&&typeof t.extras.providerToolDefinition=="object"&&t.extras.providerToolDefinition!==null}function I9(t){return t!=null&&typeof t=="object"&&"type"in t&&t.type!=="function"}function jd(t){return typeof t=="object"&&t!==null&&"metadata"in t&&typeof t.metadata=="object"&&t.metadata!==null&&"customTool"in t.metadata&&typeof t.metadata.customTool=="object"&&t.metadata.customTool!==null}function wk(t){return"type"in t&&t.type==="custom"&&"custom"in t&&typeof t.custom=="object"&&t.custom!==null}function x9(t){if(t.type==="custom_tool_call")return{...t,type:"tool_call",call_id:t.id,id:t.call_id,name:t.name,isCustomTool:!0,args:{input:t.input}}}function k9(t){if(t.type==="computer_call")return{...t,type:"tool_call",call_id:t.id,id:t.call_id,name:"computer_use",isComputerTool:!0,args:{action:t.action}}}function O9(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="tool_call"&&"isComputerTool"in t&&t.isComputerTool===!0}function C9(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="tool_call"&&"isCustomTool"in t&&t.isCustomTool===!0}function R9(t){const e=()=>{if(t.custom.format){if(t.custom.format.type==="grammar")return{type:"grammar",definition:t.custom.format.grammar.definition,syntax:t.custom.format.grammar.syntax};if(t.custom.format.type==="text")return{type:"text"}}};return{type:"custom",name:t.custom.name,description:t.custom.description,format:e()}}function $9(t){const e=()=>{if(t.format){if(t.format.type==="grammar")return{type:"grammar",grammar:{definition:t.format.definition,syntax:t.format.syntax}};if(t.format.type==="text")return{type:"text"}}};return{type:"custom",custom:{name:t.name,description:t.description,format:e()}}}const N9=Symbol("Let zodToJsonSchema decide on which parser to use"),Av={name:void 0,$refStrategy:"root",effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",nullableStrategy:"from-target",removeAdditionalStrategy:"passthrough",definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"},P9=t=>typeof t=="string"?{...Av,basePath:["#"],definitions:{},name:t}:{...Av,basePath:["#"],definitions:{},...t},Zm=t=>"_def"in t?t._def:t;function M9(t){if(!t)return!0;for(const e in t)return!1;return!0}const L9=t=>{const e=P9(t),n=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,currentPath:n,propertyPath:void 0,seenRefs:new Set,seen:new Map(Object.entries(e.definitions).map(([r,s])=>[Zm(s),{def:Zm(s),path:[...e.basePath,e.definitionPath,r],jsonSchema:void 0}]))}};function bk(t,e,n,r){r!=null&&r.errorMessages&&n&&(t.errorMessage={...t.errorMessage,[e]:n})}function nt(t,e,n,r,s){t[e]=n,bk(t,e,r,s)}function j9(){return{}}function U9(t,e){var r,s;const n={type:"array"};return((s=(r=t.type)==null?void 0:r._def)==null?void 0:s.typeName)!==j.ZodAny&&(n.items=Je(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&nt(n,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&nt(n,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(nt(n,"minItems",t.exactLength.value,t.exactLength.message,e),nt(n,"maxItems",t.exactLength.value,t.exactLength.message,e)),n}function D9(t,e){const n={type:"integer",format:"int64"};if(!t.checks)return n;for(const r of t.checks)switch(r.kind){case"min":e.target==="jsonSchema7"?r.inclusive?nt(n,"minimum",r.value,r.message,e):nt(n,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(n.exclusiveMinimum=!0),nt(n,"minimum",r.value,r.message,e));break;case"max":e.target==="jsonSchema7"?r.inclusive?nt(n,"maximum",r.value,r.message,e):nt(n,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(n.exclusiveMaximum=!0),nt(n,"maximum",r.value,r.message,e));break;case"multipleOf":nt(n,"multipleOf",r.value,r.message,e);break}return n}function F9(){return{type:"boolean"}}function B9(t,e){return Je(t.type._def,e)}const z9=(t,e)=>Je(t.innerType._def,e);function vk(t,e,n){const r=n??e.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((s,a)=>vk(t,e,s))};switch(r){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return H9(t,e)}}const H9=(t,e)=>{const n={type:"integer",format:"unix-time"};if(e.target==="openApi3")return n;for(const r of t.checks)switch(r.kind){case"min":nt(n,"minimum",r.value,r.message,e);break;case"max":nt(n,"maximum",r.value,r.message,e);break}return n};function V9(t,e){return{...Je(t.innerType._def,e),default:t.defaultValue()}}function Z9(t,e,n){return e.effectStrategy==="input"?Je(t.schema._def,e,n):{}}function W9(t){return{type:"string",enum:[...t.values]}}const G9=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function q9(t,e){const n=[Je(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),Je(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(a=>!!a);let r=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0;const s=[];return n.forEach(a=>{if(G9(a))s.push(...a.allOf),a.unevaluatedProperties===void 0&&(r=void 0);else{let i=a;if("additionalProperties"in a&&a.additionalProperties===!1){const{additionalProperties:o,...c}=a;i=c}else r=void 0;s.push(i)}}),s.length?{allOf:s,...r}:void 0}function K9(t,e){const n=typeof t.value;return n!=="bigint"&&n!=="number"&&n!=="boolean"&&n!=="string"?{type:Array.isArray(t.value)?"array":"object"}:e.target==="openApi3"?{type:n==="bigint"?"integer":n,enum:[t.value]}:{type:n==="bigint"?"integer":n,const:t.value}}let Kf;const ca={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(Kf===void 0&&(Kf=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Kf),base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/};function Sk(t,e){const n={type:"string"};function r(s){return e.patternStrategy==="escape"?J9(s):s}if(t.checks)for(const s of t.checks)switch(s.kind){case"min":nt(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,s.value):s.value,s.message,e);break;case"max":nt(n,"maxLength",typeof n.maxLength=="number"?Math.min(n.maxLength,s.value):s.value,s.message,e);break;case"email":switch(e.emailStrategy){case"format:email":pr(n,"email",s.message,e);break;case"format:idn-email":pr(n,"idn-email",s.message,e);break;case"pattern:zod":mr(n,ca.email,s.message,e);break}break;case"url":pr(n,"uri",s.message,e);break;case"uuid":pr(n,"uuid",s.message,e);break;case"regex":mr(n,s.regex,s.message,e);break;case"cuid":mr(n,ca.cuid,s.message,e);break;case"cuid2":mr(n,ca.cuid2,s.message,e);break;case"startsWith":mr(n,RegExp(`^${r(s.value)}`),s.message,e);break;case"endsWith":mr(n,RegExp(`${r(s.value)}$`),s.message,e);break;case"datetime":pr(n,"date-time",s.message,e);break;case"date":pr(n,"date",s.message,e);break;case"time":pr(n,"time",s.message,e);break;case"duration":pr(n,"duration",s.message,e);break;case"length":nt(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,s.value):s.value,s.message,e),nt(n,"maxLength",typeof n.maxLength=="number"?Math.min(n.maxLength,s.value):s.value,s.message,e);break;case"includes":{mr(n,RegExp(r(s.value)),s.message,e);break}case"ip":{s.version!=="v6"&&pr(n,"ipv4",s.message,e),s.version!=="v4"&&pr(n,"ipv6",s.message,e);break}case"emoji":mr(n,ca.emoji,s.message,e);break;case"ulid":{mr(n,ca.ulid,s.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{pr(n,"binary",s.message,e);break}case"contentEncoding:base64":{nt(n,"contentEncoding","base64",s.message,e);break}case"pattern:zod":{mr(n,ca.base64,s.message,e);break}}break}case"nanoid":mr(n,ca.nanoid,s.message,e)}return n}const J9=t=>Array.from(t).map(e=>/[a-zA-Z0-9]/.test(e)?e:`\\${e}`).join(""),pr=(t,e,n,r)=>{var s;t.format||(s=t.anyOf)!=null&&s.some(a=>a.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&r.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...n&&r.errorMessages&&{errorMessage:{format:n}}})):nt(t,"format",e,n,r)},mr=(t,e,n,r)=>{var s;t.pattern||(s=t.allOf)!=null&&s.some(a=>a.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&r.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:Iv(e,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):nt(t,"pattern",Iv(e,r),n,r)},Iv=(t,e)=>{var u;const n=typeof t=="function"?t():t;if(!e.applyRegexFlags||!n.flags)return n.source;const r={i:n.flags.includes("i"),m:n.flags.includes("m"),s:n.flags.includes("s")},s=r.i?n.source.toLowerCase():n.source;let a="",i=!1,o=!1,c=!1;for(let l=0;l<s.length;l++){if(i){a+=s[l],i=!1;continue}if(r.i){if(o){if(s[l].match(/[a-z]/)){c?(a+=s[l],a+=`${s[l-2]}-${s[l]}`.toUpperCase(),c=!1):s[l+1]==="-"&&((u=s[l+2])!=null&&u.match(/[a-z]/))?(a+=s[l],c=!0):a+=`${s[l]}${s[l].toUpperCase()}`;continue}}else if(s[l].match(/[a-z]/)){a+=`[${s[l]}${s[l].toUpperCase()}]`;continue}}if(r.m){if(s[l]==="^"){a+=`(^|(?<=[\r
338
- ]))`;continue}else if(s[l]==="$"){a+=`($|(?=[\r
339
- ]))`;continue}}if(r.s&&s[l]==="."){a+=o?`${s[l]}\r
340
- `:`[${s[l]}\r
341
- ]`;continue}a+=s[l],s[l]==="\\"?i=!0:o&&s[l]==="]"?o=!1:!o&&s[l]==="["&&(o=!0)}try{const l=new RegExp(a)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),n.source}return a};function Tk(t,e){var r,s,a,i;if(e.target==="openApi3"&&((r=t.keyType)==null?void 0:r._def.typeName)===j.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((o,c)=>({...o,[c]:Je(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",c]})??{}}),{}),additionalProperties:!1};const n={type:"object",additionalProperties:Je(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??{}};if(e.target==="openApi3")return n;if(((s=t.keyType)==null?void 0:s._def.typeName)===j.ZodString&&((a=t.keyType._def.checks)!=null&&a.length)){const o=Object.entries(Sk(t.keyType._def,e)).reduce((c,[u,l])=>u==="type"?c:{...c,[u]:l},{});return{...n,propertyNames:o}}else if(((i=t.keyType)==null?void 0:i._def.typeName)===j.ZodEnum)return{...n,propertyNames:{enum:t.keyType._def.values}};return n}function X9(t,e){if(e.mapStrategy==="record")return Tk(t,e);const n=Je(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||{},r=Je(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||{};return{type:"array",maxItems:125,items:{type:"array",items:[n,r],minItems:2,maxItems:2}}}function Y9(t){const e=t.values,r=Object.keys(t.values).filter(a=>typeof e[e[a]]!="number").map(a=>e[a]),s=Array.from(new Set(r.map(a=>typeof a)));return{type:s.length===1?s[0]==="string"?"string":"number":["string","number"],enum:r}}function Q9(){return{not:{}}}function e8(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}const Ud={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function t8(t,e){if(e.target==="openApi3")return xv(t,e);const n=t.options instanceof Map?Array.from(t.options.values()):t.options;if(n.every(r=>r._def.typeName in Ud&&(!r._def.checks||!r._def.checks.length))){const r=n.reduce((s,a)=>{const i=Ud[a._def.typeName];return i&&!s.includes(i)?[...s,i]:s},[]);return{type:r.length>1?r:r[0]}}else if(n.every(r=>r._def.typeName==="ZodLiteral"&&!r.description)){const r=n.reduce((s,a)=>{const i=typeof a._def.value;switch(i){case"string":case"number":case"boolean":return[...s,i];case"bigint":return[...s,"integer"];case"object":if(a._def.value===null)return[...s,"null"];case"symbol":case"undefined":case"function":default:return s}},[]);if(r.length===n.length){const s=r.filter((a,i,o)=>o.indexOf(a)===i);return{type:s.length>1?s:s[0],enum:n.reduce((a,i)=>a.includes(i._def.value)?a:[...a,i._def.value],[])}}}else if(n.every(r=>r._def.typeName==="ZodEnum"))return{type:"string",enum:n.reduce((r,s)=>[...r,...s._def.values.filter(a=>!r.includes(a))],[])};return xv(t,e)}const xv=(t,e)=>{const n=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((r,s)=>Je(r._def,{...e,currentPath:[...e.currentPath,"anyOf",`${s}`]})).filter(r=>!!r&&(!e.strictUnions||typeof r=="object"&&Object.keys(r).length>0));return n.length?{anyOf:n}:void 0};function n8(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"||e.nullableStrategy==="property"?{type:Ud[t.innerType._def.typeName],nullable:!0}:{type:[Ud[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){const r=Je(t.innerType._def,{...e,currentPath:[...e.currentPath]});return r&&"$ref"in r?{allOf:[r],nullable:!0}:r&&{...r,nullable:!0}}const n=Je(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}function r8(t,e){const n={type:"number"};if(!t.checks)return n;for(const r of t.checks)switch(r.kind){case"int":n.type="integer",bk(n,"type",r.message,e);break;case"min":e.target==="jsonSchema7"?r.inclusive?nt(n,"minimum",r.value,r.message,e):nt(n,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(n.exclusiveMinimum=!0),nt(n,"minimum",r.value,r.message,e));break;case"max":e.target==="jsonSchema7"?r.inclusive?nt(n,"maximum",r.value,r.message,e):nt(n,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(n.exclusiveMaximum=!0),nt(n,"maximum",r.value,r.message,e));break;case"multipleOf":nt(n,"multipleOf",r.value,r.message,e);break}return n}function s8(t,e){return e.removeAdditionalStrategy==="strict"?t.catchall._def.typeName==="ZodNever"?t.unknownKeys!=="strict":Je(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0:t.catchall._def.typeName==="ZodNever"?t.unknownKeys==="passthrough":Je(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0}function a8(t,e){const n={type:"object",...Object.entries(t.shape()).reduce((r,[s,a])=>{var c;if(a===void 0||a._def===void 0)return r;const i=[...e.currentPath,"properties",s],o=Je(a._def,{...e,currentPath:i,propertyPath:i});if(o===void 0)return r;if(e.openaiStrictMode&&a.isOptional()&&!a.isNullable()&&typeof((c=a._def)==null?void 0:c.defaultValue)>"u")throw new Error(`Zod field at \`${i.join("/")}\` uses \`.optional()\` without \`.nullable()\` which is not supported by the API. See: https://platform.openai.com/docs/guides/structured-outputs?api-mode=responses#all-fields-must-be-required`);return{properties:{...r.properties,[s]:o},required:a.isOptional()&&!e.openaiStrictMode?r.required:[...r.required,s]}},{properties:{},required:[]}),additionalProperties:s8(t,e)};return n.required.length||delete n.required,n}const i8=(t,e)=>{if(e.propertyPath&&e.currentPath.slice(0,e.propertyPath.length).toString()===e.propertyPath.toString())return Je(t.innerType._def,{...e,currentPath:e.currentPath});const n=Je(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return n?{anyOf:[{not:{}},n]}:{}},o8=(t,e)=>{if(e.pipeStrategy==="input")return Je(t.in._def,e);if(e.pipeStrategy==="output")return Je(t.out._def,e);const n=Je(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),r=Je(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",n?"1":"0"]});return{allOf:[n,r].filter(s=>s!==void 0)}};function c8(t,e){return Je(t.type._def,e)}function u8(t,e){const r={type:"array",uniqueItems:!0,items:Je(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&nt(r,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&nt(r,"maxItems",t.maxSize.value,t.maxSize.message,e),r}function l8(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((n,r)=>Je(n._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[]),additionalItems:Je(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((n,r)=>Je(n._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[])}}function d8(){return{not:{}}}function h8(){return{}}const f8=(t,e)=>Je(t.innerType._def,e);function Je(t,e,n=!1){var i;const r=e.seen.get(t);if(e.override){const o=(i=e.override)==null?void 0:i.call(e,t,e,r,n);if(o!==N9)return o}if(r&&!n){const o=p8(r,e);if(o!==void 0)return"$ref"in o&&e.seenRefs.add(o.$ref),o}const s={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,s);const a=g8(t,t.typeName,e,n);return a&&_8(t,e,a),s.jsonSchema=a,a}const p8=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"extract-to-root":const n=t.path.slice(e.basePath.length+1).join("_");return n!==e.name&&e.nameStrategy==="duplicate-ref"&&(e.definitions[n]=t.def),{$ref:[...e.basePath,e.definitionPath,n].join("/")};case"relative":return{$ref:m8(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((r,s)=>e.currentPath[s]===r)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),{}):e.$refStrategy==="seen"?{}:void 0}},m8=(t,e)=>{let n=0;for(;n<t.length&&n<e.length&&t[n]===e[n];n++);return[(t.length-n).toString(),...e.slice(n)].join("/")},g8=(t,e,n,r)=>{switch(e){case j.ZodString:return Sk(t,n);case j.ZodNumber:return r8(t,n);case j.ZodObject:return a8(t,n);case j.ZodBigInt:return D9(t,n);case j.ZodBoolean:return F9();case j.ZodDate:return vk(t,n);case j.ZodUndefined:return d8();case j.ZodNull:return e8(n);case j.ZodArray:return U9(t,n);case j.ZodUnion:case j.ZodDiscriminatedUnion:return t8(t,n);case j.ZodIntersection:return q9(t,n);case j.ZodTuple:return l8(t,n);case j.ZodRecord:return Tk(t,n);case j.ZodLiteral:return K9(t,n);case j.ZodEnum:return W9(t);case j.ZodNativeEnum:return Y9(t);case j.ZodNullable:return n8(t,n);case j.ZodOptional:return i8(t,n);case j.ZodMap:return X9(t,n);case j.ZodSet:return u8(t,n);case j.ZodLazy:return Je(t.getter()._def,n);case j.ZodPromise:return c8(t,n);case j.ZodNaN:case j.ZodNever:return Q9();case j.ZodEffects:return Z9(t,n,r);case j.ZodAny:return j9();case j.ZodUnknown:return h8();case j.ZodDefault:return V9(t,n);case j.ZodBranded:return B9(t,n);case j.ZodReadonly:return f8(t,n);case j.ZodCatch:return z9(t,n);case j.ZodPipeline:return o8(t,n);case j.ZodFunction:case j.ZodVoid:case j.ZodSymbol:return;default:return(s=>{})()}},_8=(t,e,n)=>(t.description&&(n.description=t.description,e.markdownDescription&&(n.markdownDescription=t.description)),n),y8=(t,e)=>{const n=L9(e),r=typeof e=="string"?e:(e==null?void 0:e.nameStrategy)==="title"||e==null?void 0:e.name,s=Je(t._def,r===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,r]},!1)??{},a=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;a!==void 0&&(s.title=a);const i=(()=>{if(M9(n.definitions))return;const c={},u=new Set;for(let l=0;l<500;l++){const d=Object.entries(n.definitions).filter(([f])=>!u.has(f));if(d.length===0)break;for(const[f,h]of d)c[f]=Je(Zm(h),{...n,currentPath:[...n.basePath,n.definitionPath,f]},!0)??{},u.add(f)}return c})(),o=r===void 0?i?{...s,[n.definitionPath]:i}:s:n.nameStrategy==="duplicate-ref"?{...s,...i||n.seenRefs.size?{[n.definitionPath]:{...i,...n.seenRefs.size?{[r]:s}:void 0}}:void 0}:{$ref:[...n.$refStrategy==="relative"?[]:n.basePath,n.definitionPath,r].join("/"),[n.definitionPath]:{...i,[r]:s}};return n.target==="jsonSchema7"?o.$schema="http://json-schema.org/draft-07/schema#":n.target==="jsonSchema2019-09"&&(o.$schema="https://json-schema.org/draft/2019-09/schema#"),o};function w8(t){if(t.type!=="object")throw new Error(`Root schema must have type: 'object' but got type: ${t.type?`'${t.type}'`:"undefined"}`);const e=structuredClone(t);return ns(e,[],e)}function Wm(t){if(typeof t=="boolean")return!1;if(t.type==="null")return!0;for(const e of t.oneOf??[])if(Wm(e))return!0;for(const e of t.anyOf??[])if(Wm(e))return!0;return!1}function ns(t,e,n){if(typeof t=="boolean")throw new TypeError(`Expected object schema but got boolean; path=${e.join("/")}`);if(!ga(t))throw new TypeError(`Expected ${JSON.stringify(t)} to be an object; path=${e.join("/")}`);const r=t.$defs;if(ga(r))for(const[f,h]of Object.entries(r))ns(h,[...e,"$defs",f],n);const s=t.definitions;if(ga(s))for(const[f,h]of Object.entries(s))ns(h,[...e,"definitions",f],n);t.type==="object"&&!("additionalProperties"in t)&&(t.additionalProperties=!1);const i=t.required??[],o=t.properties;if(ga(o)){for(const[f,h]of Object.entries(o))if(!Wm(h)&&!i.includes(f))throw new Error(`Zod field at \`${[...e,"properties",f].join("/")}\` uses \`.optional()\` without \`.nullable()\` which is not supported by the API. See: https://platform.openai.com/docs/guides/structured-outputs?api-mode=responses#all-fields-must-be-required`);t.required=Object.keys(o),t.properties=Object.fromEntries(Object.entries(o).map(([f,h])=>[f,ns(h,[...e,"properties",f],n)]))}const c=t.items;ga(c)&&(t.items=ns(c,[...e,"items"],n));const u=t.anyOf;Array.isArray(u)&&(t.anyOf=u.map((f,h)=>ns(f,[...e,"anyOf",String(h)],n)));const l=t.allOf;if(Array.isArray(l))if(l.length===1){const f=ns(l[0],[...e,"allOf","0"],n);Object.assign(t,f),delete t.allOf}else t.allOf=l.map((f,h)=>ns(f,[...e,"allOf",String(h)],n));t.default===null&&delete t.default;const d=t.$ref;if(d&&v8(t,1)){if(typeof d!="string")throw new TypeError(`Received non-string $ref - ${d}; path=${e.join("/")}`);const f=b8(n,d);if(typeof f=="boolean")throw new Error(`Expected \`$ref: ${d}\` to resolve to an object schema but got boolean`);if(!ga(f))throw new Error(`Expected \`$ref: ${d}\` to resolve to an object but got ${JSON.stringify(f)}`);return Object.assign(t,{...f,...t}),delete t.$ref,ns(t,e,n)}return t}function b8(t,e){if(!e.startsWith("#/"))throw new Error(`Unexpected $ref format ${JSON.stringify(e)}; Does not start with #/`);const n=e.slice(2).split("/");let r=t;for(const s of n){if(!ga(r))throw new Error(`encountered non-object entry while resolving ${e} - ${JSON.stringify(r)}`);const a=r[s];if(a===void 0)throw new Error(`Key ${s} not found while resolving ${e}`);r=a}return r}function ga(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function v8(t,e){let n=0;for(const r in t)if(n++,n>e)return!0;return!1}function S8(t,e){return y8(t,{openaiStrictMode:!0,name:e.name,nameStrategy:"duplicate-ref",$refStrategy:"extract-to-root",nullableStrategy:"property"})}function T8(t){return w8(Dp(t,{target:"draft-7"}))}function E8(t){return"_zod"in t}function A8(t,e,n){return H5({type:"json_schema",json_schema:{...n,name:e,strict:!0,schema:E8(t)?T8(t):S8(t,{name:e})}},r=>t.parse(JSON.parse(r)))}const kv=["jsonSchema","functionCalling","jsonMode"];function I8(t,e){if(typeof e<"u"&&!kv.includes(e))throw new Error(`Invalid method: ${e}. Supported methods are: ${kv.join(", ")}`);const n=!t.startsWith("gpt-3")&&!t.startsWith("gpt-4-")&&t!=="gpt-4";if(n&&!e)return"jsonSchema";if(!n&&e==="jsonSchema")throw new Error(`JSON Schema is not supported for model "${t}". Please use a different method, e.g. "functionCalling" or "jsonMode".`);return e??"functionCalling"}function x8(t,e){const n={...t};return Object.defineProperties(n,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:e,enumerable:!1}}),n}function k8(t,e,n){if(xt(t))return A8(t,e,n);if(pt(t))return x8({type:"json_schema",json_schema:{...n,name:e,strict:!0,schema:lt(t,{cycles:"ref",reused:"ref",override(r){r.jsonSchema.title=e}})}},r=>Kd(t,JSON.parse(r)));throw new Error("Unsupported schema response format")}function O8(t,e){if(e&&typeof e=="object"&&"images"in e&&Array.isArray(e.images)){const n=e.images.filter(r=>{var s;return typeof((s=r==null?void 0:r.image_url)==null?void 0:s.url)=="string"}).map(r=>({type:"image",url:r.image_url.url}));return[{type:"text",text:t},...n]}return t}const C8={"gpt-4o-2024-11-20":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.3-codex":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-codex":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-pro":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:272e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4o-mini":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"text-embedding-ada-002":{maxInputTokens:8192,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1536,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-chat-latest":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"codex-mini-latest":{maxInputTokens:2e5,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.1-codex-max":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4o-2024-05-13":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:4096,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.2-chat-latest":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.2-codex":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o3-deep-research":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},o1:{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.1":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o4-mini-deep-research":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.3-codex-spark":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},o3:{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"text-embedding-3-small":{maxInputTokens:8191,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1536,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4.1-nano":{maxInputTokens:1047576,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"text-embedding-3-large":{maxInputTokens:8191,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:3072,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-3.5-turbo":{maxInputTokens:16385,imageInputs:!1,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:4096,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!1,imageUrlInputs:!1,pdfToolMessage:!1,imageToolMessage:!1,toolChoice:!0},"gpt-5.1-codex-mini":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.2":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4.1":{maxInputTokens:1047576,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o3-pro":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4-turbo":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:4096,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o4-mini":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4.1-mini":{maxInputTokens:1047576,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.4":{maxInputTokens:105e4,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o1-preview":{maxInputTokens:128e3,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.4-pro":{maxInputTokens:105e4,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.5":{maxInputTokens:105e4,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:13e4,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.5-pro":{maxInputTokens:105e4,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o1-pro":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.1-codex":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.2-pro":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o3-mini":{maxInputTokens:2e5,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4o-2024-08-06":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-mini":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.1-chat-latest":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4":{maxInputTokens:8192,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-nano":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o1-mini":{maxInputTokens:128e3,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4o":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0}};function Y_(t,e){return typeof t=="string"?{model:t,...e??{}}:t??e}var Q_=class extends Jr{constructor(e){var r,s,a,i;super(e??{});p(this,"temperature");p(this,"topP");p(this,"frequencyPenalty");p(this,"presencePenalty");p(this,"n");p(this,"logitBias");p(this,"model","gpt-3.5-turbo");p(this,"modelKwargs");p(this,"stop");p(this,"stopSequences");p(this,"user");p(this,"timeout");p(this,"streaming",!1);p(this,"streamUsage",!0);p(this,"maxTokens");p(this,"logprobs");p(this,"topLogprobs");p(this,"apiKey");p(this,"organization");p(this,"__includeRawResponse");p(this,"client");p(this,"clientConfig");p(this,"supportsStrictToolCalling");p(this,"audio");p(this,"modalities");p(this,"reasoning");p(this,"zdrEnabled");p(this,"service_tier");p(this,"promptCacheKey");p(this,"promptCacheRetention");p(this,"verbosity");p(this,"defaultOptions");p(this,"lc_serializable",!0);const n=typeof((r=e==null?void 0:e.configuration)==null?void 0:r.apiKey)=="string"||typeof((s=e==null?void 0:e.configuration)==null?void 0:s.apiKey)=="function"?(a=e==null?void 0:e.configuration)==null?void 0:a.apiKey:void 0;this.apiKey=(e==null?void 0:e.apiKey)??n??It("OPENAI_API_KEY"),this.organization=((i=e==null?void 0:e.configuration)==null?void 0:i.organization)??It("OPENAI_ORGANIZATION"),this.model=(e==null?void 0:e.model)??(e==null?void 0:e.modelName)??this.model,this.modelKwargs=(e==null?void 0:e.modelKwargs)??{},this.timeout=e==null?void 0:e.timeout,this.temperature=(e==null?void 0:e.temperature)??this.temperature,this.topP=(e==null?void 0:e.topP)??this.topP,this.frequencyPenalty=(e==null?void 0:e.frequencyPenalty)??this.frequencyPenalty,this.presencePenalty=(e==null?void 0:e.presencePenalty)??this.presencePenalty,this.logprobs=e==null?void 0:e.logprobs,this.topLogprobs=e==null?void 0:e.topLogprobs,this.n=(e==null?void 0:e.n)??this.n,this.logitBias=e==null?void 0:e.logitBias,this.stop=(e==null?void 0:e.stopSequences)??(e==null?void 0:e.stop),this.stopSequences=this.stop,this.user=e==null?void 0:e.user,this.__includeRawResponse=e==null?void 0:e.__includeRawResponse,this.audio=e==null?void 0:e.audio,this.modalities=e==null?void 0:e.modalities,this.reasoning=e==null?void 0:e.reasoning,this.maxTokens=(e==null?void 0:e.maxCompletionTokens)??(e==null?void 0:e.maxTokens),this.promptCacheKey=(e==null?void 0:e.promptCacheKey)??this.promptCacheKey,this.promptCacheRetention=(e==null?void 0:e.promptCacheRetention)??this.promptCacheRetention,this.verbosity=(e==null?void 0:e.verbosity)??this.verbosity,this.disableStreaming=(e==null?void 0:e.disableStreaming)===!0,this.streaming=(e==null?void 0:e.streaming)===!0,this.disableStreaming&&(this.streaming=!1),(e==null?void 0:e.streaming)===!1&&(this.disableStreaming=!0),this.streamUsage=(e==null?void 0:e.streamUsage)??this.streamUsage,this.disableStreaming&&(this.streamUsage=!1),this.clientConfig={apiKey:this.apiKey,organization:this.organization,dangerouslyAllowBrowser:!0,...e==null?void 0:e.configuration},(e==null?void 0:e.supportsStrictToolCalling)!==void 0&&(this.supportsStrictToolCalling=e.supportsStrictToolCalling),(e==null?void 0:e.service_tier)!==void 0&&(this.service_tier=e.service_tier),this.zdrEnabled=(e==null?void 0:e.zdrEnabled)??!1,this._addVersion("@langchain/openai","1.4.5")}_llmType(){return"openai"}static lc_name(){return"ChatOpenAI"}get callKeys(){return[...super.callKeys,"options","function_call","functions","tools","tool_choice","promptIndex","response_format","seed","reasoning","reasoning_effort","service_tier"]}get lc_secrets(){return{apiKey:"OPENAI_API_KEY",organization:"OPENAI_ORGANIZATION"}}get lc_aliases(){return{apiKey:"openai_api_key",modelName:"model"}}get lc_serializable_keys(){return["configuration","logprobs","topLogprobs","prefixMessages","supportsStrictToolCalling","modalities","audio","temperature","maxTokens","topP","frequencyPenalty","presencePenalty","n","logitBias","user","streaming","streamUsage","model","modelName","modelKwargs","stop","stopSequences","timeout","apiKey","cache","maxConcurrency","maxRetries","verbose","callbacks","tags","metadata","disableStreaming","zdrEnabled","reasoning","promptCacheKey","promptCacheRetention","verbosity"]}getLsParams(e){const n=this.invocationParams(e);return{ls_provider:"openai",ls_model_name:this.model,ls_model_type:"chat",ls_temperature:n.temperature??void 0,ls_max_tokens:n.max_tokens??void 0,ls_stop:e.stop}}_identifyingParams(){return{model_name:this.model,...this.invocationParams(),...this.clientConfig}}identifyingParams(){return this._identifyingParams()}_getReasoningParams(e){if(!iu(this.model))return;let n;return this.reasoning!==void 0&&(n={...n,...this.reasoning}),(e==null?void 0:e.reasoning)!==void 0&&(n={...n,...e.reasoning}),(e==null?void 0:e.reasoningEffort)!==void 0&&(n==null?void 0:n.effort)===void 0&&(n={...n,effort:e.reasoningEffort}),n}_getResponseFormat(e){return e&&e.type==="json_schema"&&e.json_schema.schema&&Lt(e.json_schema.schema)?k8(e.json_schema.schema,e.json_schema.name,{description:e.json_schema.description}):e}_combineCallOptions(e){return{...this.defaultOptions,...e??{}}}_getClientOptions(e){if(!this.client){const n=mk({baseURL:this.clientConfig.baseURL}),r={...this.clientConfig,baseURL:n,timeout:this.timeout,maxRetries:0};r.baseURL||delete r.baseURL,r.defaultHeaders=gk(r.defaultHeaders),this.client=new Ne(r)}return{...this.clientConfig,...e}}_convertChatOpenAIToolToCompletionsTool(e,n){return jd(e)?$9(e.metadata.customTool):Gi(e)?(n==null?void 0:n.strict)!==void 0?{...e,function:{...e.function,strict:n.strict}}:e:S9(e,n)}bindTools(e,n){let r;return(n==null?void 0:n.strict)!==void 0?r=n.strict:this.supportsStrictToolCalling!==void 0&&(r=this.supportsStrictToolCalling),this.withConfig({tools:e.map(s=>{var i;if(X_(s)||jd(s))return s;if(A9(s))return s.extras.providerToolDefinition;const a=this._convertChatOpenAIToolToCompletionsTool(s,{strict:r});return vs(s)&&((i=s.extras)==null?void 0:i.defer_loading)===!0?{...a,defer_loading:!0}:a}),...n})}async stream(e,n){return super.stream(e,this._combineCallOptions(n))}async invoke(e,n){return super.invoke(e,this._combineCallOptions(n))}_combineLLMOutput(...e){return e.reduce((n,r)=>(r&&r.tokenUsage&&(n.tokenUsage.completionTokens+=r.tokenUsage.completionTokens??0,n.tokenUsage.promptTokens+=r.tokenUsage.promptTokens??0,n.tokenUsage.totalTokens+=r.tokenUsage.totalTokens??0),n),{tokenUsage:{completionTokens:0,promptTokens:0,totalTokens:0}})}async getNumTokensFromMessages(e){let n=0,r=0,s=0;this.model==="gpt-3.5-turbo-0301"?(r=4,s=-1):(r=3,s=1);const a=await Promise.all(e.map(async i=>{var f,h,m,_,y,w;const[o,c]=await Promise.all([this.getNumTokens(i.content),this.getNumTokens(ou(i))]),u=i.name!==void 0?s+await this.getNumTokens(i.name):0;let l=o+r+c+u;const d=i;if(d._getType()==="function"&&(l-=2),(f=d.additional_kwargs)!=null&&f.function_call&&(l+=3),(h=d==null?void 0:d.additional_kwargs.function_call)!=null&&h.name&&(l+=await this.getNumTokens((m=d.additional_kwargs.function_call)==null?void 0:m.name)),(_=d.additional_kwargs.function_call)!=null&&_.arguments)try{l+=await this.getNumTokens(JSON.stringify(JSON.parse((y=d.additional_kwargs.function_call)==null?void 0:y.arguments)))}catch(g){console.error("Error parsing function arguments",g,JSON.stringify(d.additional_kwargs.function_call)),l+=await this.getNumTokens((w=d.additional_kwargs.function_call)==null?void 0:w.arguments)}return n+=l,l}));return n+=3,{totalCount:n,countPerMessage:a}}async _getNumTokensFromGenerations(e){return(await Promise.all(e.map(async n=>{var r;return(r=n.message.additional_kwargs)!=null&&r.function_call?(await this.getNumTokensFromMessages([n.message])).countPerMessage[0]:await this.getNumTokens(n.message.content)}))).reduce((n,r)=>n+r,0)}async _getEstimatedTokenCountFromPrompt(e,n,r){let s=(await this.getNumTokensFromMessages(e)).totalCount;if(n&&r!=="auto"){const a=E9(n);s+=await this.getNumTokens(a),s+=9}return n&&e.find(a=>a._getType()==="system")&&(s-=4),r==="none"?s+=1:typeof r=="object"&&(s+=await this.getNumTokens(r.name)+4),s}async moderateContent(e,n){const r=this._getClientOptions(n==null?void 0:n.options),s={input:e,model:(n==null?void 0:n.model)??"omni-moderation-latest"};return this.caller.call(async()=>{try{return await this.client.moderations.create(s,r)}catch(a){throw J_(a)}})}get profile(){return C8[this.model]??{}}_getStructuredOutputMethod(e){const n={...e};if(!this.model.startsWith("gpt-3")&&!this.model.startsWith("gpt-4-")&&this.model!=="gpt-4"){if((n==null?void 0:n.method)===void 0)return"jsonSchema"}else n.method==="jsonSchema"&&console.warn(`[WARNING]: JSON Schema is not supported for model "${this.model}". Falling back to tool calling.`);return n.method}withStructuredOutput(e,n){let r,s;const{schema:a,name:i,includeRaw:o}={...n,schema:e};if((n==null?void 0:n.strict)!==void 0&&n.method==="jsonMode")throw new Error("Argument `strict` is only supported for `method` = 'function_calling'");const c=I8(this.model,n==null?void 0:n.method);if(c==="jsonMode"){s=Fi(a);const u=lt(a);r=this.withConfig({outputVersion:"v0",response_format:{type:"json_object"},ls_structured_output_format:{kwargs:{method:"json_mode"},schema:{title:i??"extract",...u}}})}else if(c==="jsonSchema"){const u=lt(a),l={name:i??"extract",description:Pi(u),schema:Lt(a)?a:u,strict:n==null?void 0:n.strict};if(r=this.withConfig({outputVersion:"v0",response_format:{type:"json_schema",json_schema:l},ls_structured_output_format:{kwargs:{method:"json_schema"},schema:{title:l.name,description:l.description,...u}}}),Lt(a)||cr(a)){const d=Fi(a);s=Ht.from(async f=>"parsed"in f.additional_kwargs?f.additional_kwargs.parsed:d.invoke(f.content))}else s=new r_}else{let u=i??"extract";const l=lt(a);let d;Lt(a)||cr(a)?d={name:u,description:l.description,parameters:l}:typeof a.name=="string"&&typeof a.parameters=="object"&&a.parameters!=null?(d=a,u=a.name):(u=a.title??u,d={name:u,description:a.description??"",parameters:a}),r=this.withConfig({outputVersion:"v0",tools:[{type:"function",function:d}],tool_choice:{type:"function",function:{name:u}},ls_structured_output_format:{kwargs:{method:"function_calling"},schema:{title:u,...l}},...(n==null?void 0:n.strict)!==void 0?{strict:n.strict}:{}}),s=Yc(a,u)}return Ji(r,s,o)}};const Ek={providerName:"ChatOpenAI",fromStandardTextBlock(t){return{type:"text",text:t.text}},fromStandardImageBlock(t){var e,n;if(t.source_type==="url")return{type:"image_url",image_url:{url:t.url,...(e=t.metadata)!=null&&e.detail?{detail:t.metadata.detail}:{}}};if(t.source_type==="base64")return{type:"image_url",image_url:{url:`data:${t.mime_type??""};base64,${t.data}`,...(n=t.metadata)!=null&&n.detail?{detail:t.metadata.detail}:{}}};throw new Error(`Image content blocks with source_type ${t.source_type} are not supported for ChatOpenAI`)},fromStandardAudioBlock(t){if(t.source_type==="url"){const e=Ir({dataUrl:t.url});if(!e)throw new Error(`URL audio blocks with source_type ${t.source_type} must be formatted as a data URL for ChatOpenAI`);const n=e.mime_type||t.mime_type||"";let r;try{r=wp(n)}catch{throw new Error(`Audio blocks with source_type ${t.source_type} must have mime type of audio/wav or audio/mp3`)}if(r.type!=="audio"||r.subtype!=="wav"&&r.subtype!=="mp3")throw new Error(`Audio blocks with source_type ${t.source_type} must have mime type of audio/wav or audio/mp3`);return{type:"input_audio",input_audio:{format:r.subtype,data:e.data}}}if(t.source_type==="base64"){let e;try{e=wp(t.mime_type??"")}catch{throw new Error(`Audio blocks with source_type ${t.source_type} must have mime type of audio/wav or audio/mp3`)}if(e.type!=="audio"||e.subtype!=="wav"&&e.subtype!=="mp3")throw new Error(`Audio blocks with source_type ${t.source_type} must have mime type of audio/wav or audio/mp3`);return{type:"input_audio",input_audio:{format:e.subtype,data:t.data}}}throw new Error(`Audio content blocks with source_type ${t.source_type} are not supported for ChatOpenAI`)},fromStandardFileBlock(t){if(t.source_type==="url"){const e=Ir({dataUrl:t.url}),n=Md(t);if(!e)throw new Error(`URL file blocks with source_type ${t.source_type} must be formatted as a data URL for ChatOpenAI`);return{type:"file",file:{file_data:t.url,filename:n}}}if(t.source_type==="base64"){const e=Md(t);return{type:"file",file:{file_data:`data:${t.mime_type??""};base64,${t.data}`,filename:e}}}if(t.source_type==="id")return{type:"file",file:{file_id:t.id}};throw new Error(`File content blocks with source_type ${t.source_type} are not supported for ChatOpenAI`)}},R8=({message:t,rawResponse:e,includeRawResponse:n})=>{var a,i;const r=t.tool_calls,s=t.reasoning_content;switch(t.role){case"assistant":{const o=[],c=[];for(const d of r??[])try{o.push(oh(d,{returnId:!0}))}catch(f){c.push(tc(d,f.message))}const u={function_call:t.function_call,tool_calls:r};n!==void 0&&(u.__raw_response=e),s!==void 0&&(u.reasoning_content=s);const l={model_provider:"openai",model_name:e.model,...e.system_fingerprint?{usage:{...e.usage},system_fingerprint:e.system_fingerprint}:{}};return t.audio&&(u.audio=t.audio),new De({content:O8(t.content||"",(i=(a=e.choices)==null?void 0:a[0])==null?void 0:i.message),tool_calls:o,invalid_tool_calls:c,additional_kwargs:u,response_metadata:l,id:e.id})}default:return new Kr(t.content||"",t.role??"unknown")}},$8=({delta:t,rawResponse:e,includeRawResponse:n,defaultRole:r})=>{var c,u;const s=t.role??r,a=t.content??"";let i;t.function_call?i={function_call:t.function_call}:t.tool_calls?i={tool_calls:t.tool_calls}:i={},n&&(i.__raw_response=e),t.reasoning_content!==void 0&&(i.reasoning_content=t.reasoning_content),t.audio&&(i.audio={...t.audio,index:e.choices[0].index});const o={model_provider:"openai",usage:{...e.usage}};if(s==="user")return new Bc({content:a,response_metadata:o});if(s==="assistant"){const l=[];if(Array.isArray(t.tool_calls))for(const d of t.tool_calls)l.push({name:(c=d.function)==null?void 0:c.name,args:(u=d.function)==null?void 0:u.arguments,id:d.id,index:d.index,type:"tool_call_chunk"});return new Qe({content:a,tool_call_chunks:l,additional_kwargs:i,id:e.id,response_metadata:o})}else return s==="system"?new qs({content:a,response_metadata:o}):s==="developer"?new qs({content:a,response_metadata:o,additional_kwargs:{__openai_role__:"developer"}}):s==="function"?new Fc({content:a,additional_kwargs:i,name:t.name,response_metadata:o}):s==="tool"?new Uc({content:a,additional_kwargs:i,tool_call_id:t.tool_call_id,response_metadata:o}):new Dc({content:a,role:s,response_metadata:o})},N8=t=>{if(t.type==="image"){if(t.url)return{type:"image_url",image_url:{url:t.url}};if(t.data)return{type:"image_url",image_url:{url:`data:${t.mimeType};base64,${t.data}`}}}if(t.type==="audio"&&t.data){const e=hS(()=>{const[,n]=t.mimeType.split("/");return n==="wav"||n==="mp3"?n:"wav"});return{type:"input_audio",input_audio:{data:t.data.toString(),format:e}}}if(t.type==="file"){if(t.data){const e=Md(t);return{type:"file",file:{file_data:`data:${t.mimeType};base64,${t.data}`,filename:e}}}if(t.fileId)return{type:"file",file:{file_id:t.fileId}}}},P8=({message:t,model:e})=>{let n=ou(t);if(n==="system"&&iu(e)&&(n="developer"),n==="developer")return{role:"developer",content:t.contentBlocks.filter(s=>s.type==="text")};if(n==="system")return{role:"system",content:t.contentBlocks.filter(s=>s.type==="text")};if(n==="assistant")return{role:"assistant",content:t.contentBlocks.filter(s=>s.type==="text")};if(n==="tool"&&Rn.isInstance(t))return{role:"tool",tool_call_id:t.tool_call_id,content:t.contentBlocks.filter(s=>s.type==="text")};if(n==="function")return{role:"function",name:t.name??"",content:t.contentBlocks.filter(s=>s.type==="text").join("")};function*r(s){for(const a of s){a.type==="text"&&(yield{type:"text",text:a.text});const i=N8(a);i&&(yield i)}}return{role:"user",content:Array.from(r(t.contentBlocks))}},Ov=({messages:t,model:e})=>t.flatMap(n=>{var i,o;if("output_version"in n.response_metadata&&((i=n.response_metadata)==null?void 0:i.output_version)==="v1")return P8({message:n});let r=ou(n);r==="system"&&iu(e)&&(r="developer");const s=typeof n.content=="string"?n.content:n.content.flatMap(c=>ir(c)?jc(c,Ek):typeof c=="object"&&c!==null&&"type"in c&&c.type==="tool_use"?[]:c),a={role:r,content:s};return n.name!=null&&(a.name=n.name),n.additional_kwargs.function_call!=null&&(a.function_call=n.additional_kwargs.function_call),De.isInstance(n)&&((o=n.tool_calls)!=null&&o.length)?a.tool_calls=n.tool_calls.map(VE):(n.additional_kwargs.tool_calls!=null&&(a.tool_calls=n.additional_kwargs.tool_calls),Rn.isInstance(n)&&n.tool_call_id!=null&&(a.tool_call_id=n.tool_call_id)),n.additional_kwargs.audio&&typeof n.additional_kwargs.audio=="object"&&"id"in n.additional_kwargs.audio?[a,{role:"assistant",audio:{id:n.additional_kwargs.audio.id}}]:a});var Ak=class extends Q_{constructor(t,e){super(Y_(t,e))}invocationParams(t,e){var i;let n;(t==null?void 0:t.strict)!==void 0?n=t.strict:this.supportsStrictToolCalling!==void 0&&(n=this.supportsStrictToolCalling);let r={};(t==null?void 0:t.stream_options)!==void 0?r={stream_options:t.stream_options}:this.streamUsage&&(this.streaming||e!=null&&e.streaming)&&(r={stream_options:{include_usage:!0}});const s={model:this.model,temperature:this.temperature,top_p:this.topP,frequency_penalty:this.frequencyPenalty,presence_penalty:this.presencePenalty,logprobs:this.logprobs,top_logprobs:this.topLogprobs,n:this.n,logit_bias:this.logitBias,stop:(t==null?void 0:t.stop)??this.stopSequences,user:this.user,stream:this.streaming,functions:t==null?void 0:t.functions,function_call:t==null?void 0:t.function_call,tools:(i=t==null?void 0:t.tools)!=null&&i.length?t.tools.map(o=>this._convertChatOpenAIToolToCompletionsTool(o,{strict:n})):void 0,tool_choice:yk(t==null?void 0:t.tool_choice),response_format:this._getResponseFormat(t==null?void 0:t.response_format),seed:t==null?void 0:t.seed,...r,parallel_tool_calls:t==null?void 0:t.parallel_tool_calls,...this.audio||t!=null&&t.audio?{audio:this.audio||(t==null?void 0:t.audio)}:{},...this.modalities||t!=null&&t.modalities?{modalities:this.modalities||(t==null?void 0:t.modalities)}:{},...this.modelKwargs,prompt_cache_key:(t==null?void 0:t.promptCacheKey)??this.promptCacheKey,prompt_cache_retention:(t==null?void 0:t.promptCacheRetention)??this.promptCacheRetention,verbosity:(t==null?void 0:t.verbosity)??this.verbosity};(t==null?void 0:t.prediction)!==void 0&&(s.prediction=t.prediction),this.service_tier!==void 0&&(s.service_tier=this.service_tier),(t==null?void 0:t.service_tier)!==void 0&&(s.service_tier=t.service_tier);const a=this._getReasoningParams(t);return a!==void 0&&a.effort!==void 0&&(s.reasoning_effort=a.effort),iu(s.model)?s.max_completion_tokens=this.maxTokens===-1?void 0:this.maxTokens:s.max_tokens=this.maxTokens===-1?void 0:this.maxTokens,s}async _generate(t,e,n){var i,o,c;(i=e.signal)==null||i.throwIfAborted();const r={},s=this.invocationParams(e),a=Ov({messages:t,model:this.model});if(s.stream){const u=this._streamResponseChunks(t,e,n),l={};for await(const y of u){y.message.response_metadata={...y.generationInfo,...y.message.response_metadata};const w=((o=y.generationInfo)==null?void 0:o.completion)??0;l[w]===void 0?l[w]=y:l[w]=l[w].concat(y)}const d=Object.entries(l).sort(([y],[w])=>parseInt(y,10)-parseInt(w,10)).map(([y,w])=>w),{functions:f,function_call:h}=this.invocationParams(e),m=await this._getEstimatedTokenCountFromPrompt(t,f,h),_=await this._getNumTokensFromGenerations(d);return r.input_tokens=m,r.output_tokens=_,r.total_tokens=m+_,{generations:d,llmOutput:{estimatedTokenUsage:{promptTokens:r.input_tokens,completionTokens:r.output_tokens,totalTokens:r.total_tokens}}}}else{const u=await this.completionWithRetry({...s,stream:!1,messages:a},{signal:e==null?void 0:e.signal,...e==null?void 0:e.options}),{completion_tokens:l,prompt_tokens:d,total_tokens:f,prompt_tokens_details:h,completion_tokens_details:m}=(u==null?void 0:u.usage)??{};l&&(r.output_tokens=(r.output_tokens??0)+l),d&&(r.input_tokens=(r.input_tokens??0)+d),f&&(r.total_tokens=(r.total_tokens??0)+f),((h==null?void 0:h.audio_tokens)!==null||(h==null?void 0:h.cached_tokens)!==null)&&(r.input_token_details={...(h==null?void 0:h.audio_tokens)!==null&&{audio:h==null?void 0:h.audio_tokens},...(h==null?void 0:h.cached_tokens)!==null&&{cache_read:h==null?void 0:h.cached_tokens}}),((m==null?void 0:m.audio_tokens)!==null||(m==null?void 0:m.reasoning_tokens)!==null)&&(r.output_token_details={...(m==null?void 0:m.audio_tokens)!==null&&{audio:m==null?void 0:m.audio_tokens},...(m==null?void 0:m.reasoning_tokens)!==null&&{reasoning:m==null?void 0:m.reasoning_tokens}});const _=[];for(const y of(u==null?void 0:u.choices)??[]){const w={text:((c=y.message)==null?void 0:c.content)??"",message:this._convertCompletionsMessageToBaseMessage(y.message??{role:"assistant"},u)};w.generationInfo={...y.finish_reason?{finish_reason:y.finish_reason}:{},...y.logprobs?{logprobs:y.logprobs}:{}},or(w.message)&&(w.message.usage_metadata=r),w.message=new De(Object.fromEntries(Object.entries(w.message).filter(([g])=>!g.startsWith("lc_")))),_.push(w)}return{generations:_,llmOutput:{tokenUsage:{promptTokens:r.input_tokens,completionTokens:r.output_tokens,totalTokens:r.total_tokens}}}}}async*_streamResponseChunks(t,e,n){var c,u,l,d,f,h,m,_,y,w,g;const r=Ov({messages:t,model:this.model}),s={...this.invocationParams(e,{streaming:!0}),messages:r,stream:!0};let a;const i=await this.completionWithRetry(s,e);let o;for await(const b of i){if((c=e.signal)!=null&&c.aborted)return;const S=(u=b==null?void 0:b.choices)==null?void 0:u[0];if(b.usage&&(o=b.usage),!S)continue;const{delta:I}=S;if(!I)continue;const T=this._convertCompletionsDeltaToBaseMessageChunk(I,b,a);a=I.role??a;const x={prompt:e.promptIndex??0,completion:S.index??0};if(typeof T.content!="string"){console.log("[WARNING]: Received non-string content from OpenAI. This is currently not supported.");continue}const A={...x};S.finish_reason!=null&&(A.finish_reason=S.finish_reason,A.system_fingerprint=b.system_fingerprint,A.model_name=b.model,A.service_tier=b.service_tier),this.logprobs&&(A.logprobs=S.logprobs);const M=new qn({message:T,text:T.content,generationInfo:A});yield M,await(n==null?void 0:n.handleLLMNewToken(M.text??"",x,void 0,void 0,void 0,{chunk:M}))}if(o){const b={...((l=o.prompt_tokens_details)==null?void 0:l.audio_tokens)!==null&&{audio:(d=o.prompt_tokens_details)==null?void 0:d.audio_tokens},...((f=o.prompt_tokens_details)==null?void 0:f.cached_tokens)!==null&&{cache_read:(h=o.prompt_tokens_details)==null?void 0:h.cached_tokens}},S={...((m=o.completion_tokens_details)==null?void 0:m.audio_tokens)!==null&&{audio:(_=o.completion_tokens_details)==null?void 0:_.audio_tokens},...((y=o.completion_tokens_details)==null?void 0:y.reasoning_tokens)!==null&&{reasoning:(w=o.completion_tokens_details)==null?void 0:w.reasoning_tokens}},I=new qn({message:new Qe({content:"",response_metadata:{usage:{...o}},usage_metadata:{input_tokens:o.prompt_tokens,output_tokens:o.completion_tokens,total_tokens:o.total_tokens,...Object.keys(b).length>0&&{input_token_details:b},...Object.keys(S).length>0&&{output_token_details:S}}}),text:""});yield I,await(n==null?void 0:n.handleLLMNewToken(I.text??"",{prompt:0,completion:0},void 0,void 0,void 0,{chunk:I}))}if((g=e.signal)!=null&&g.aborted)throw new Error("AbortError")}async completionWithRetry(t,e){const n=this._getClientOptions(e),r=t.response_format&&t.response_format.type==="json_schema";return this.caller.call(async()=>{try{return r&&!t.stream?await this.client.chat.completions.parse(t,n):await this.client.chat.completions.create(t,n)}catch(s){throw J_(s)}})}_convertCompletionsDeltaToBaseMessageChunk(t,e,n){return $8({delta:t,rawResponse:e,includeRawResponse:this.__includeRawResponse,defaultRole:n})}_convertCompletionsMessageToBaseMessage(t,e){return R8({message:t,rawResponse:e,includeRawResponse:this.__includeRawResponse})}};const ey={openAIApiKey:"openai_api_key",openAIApiVersion:"openai_api_version",openAIBasePath:"openai_api_base",deploymentName:"deployment_name",azureOpenAIEndpoint:"azure_endpoint",azureOpenAIApiVersion:"openai_api_version",azureOpenAIBasePath:"openai_api_base",azureOpenAIApiDeploymentName:"deployment_name"},ty={azureOpenAIApiKey:"AZURE_OPENAI_API_KEY"},ny=["azureOpenAIApiKey","azureOpenAIApiVersion","azureOpenAIBasePath","azureOpenAIEndpoint","azureOpenAIApiInstanceName","azureOpenAIApiDeploymentName","deploymentName","openAIApiKey","openAIApiVersion"];function ry(t,e){return typeof t=="string"?{model:t,deploymentName:t,azureOpenAIApiDeploymentName:t,...e??{}}:t??e}function sy(t){if(this.azureOpenAIApiKey=(t==null?void 0:t.azureOpenAIApiKey)??(typeof(t==null?void 0:t.openAIApiKey)=="string"?t==null?void 0:t.openAIApiKey:void 0)??(typeof(t==null?void 0:t.apiKey)=="string"?t==null?void 0:t.apiKey:void 0)??It("AZURE_OPENAI_API_KEY"),this.azureOpenAIApiInstanceName=(t==null?void 0:t.azureOpenAIApiInstanceName)??It("AZURE_OPENAI_API_INSTANCE_NAME"),this.azureOpenAIApiDeploymentName=(t==null?void 0:t.azureOpenAIApiDeploymentName)??(t==null?void 0:t.deploymentName)??It("AZURE_OPENAI_API_DEPLOYMENT_NAME"),this.azureOpenAIApiVersion=(t==null?void 0:t.azureOpenAIApiVersion)??(t==null?void 0:t.openAIApiVersion)??It("AZURE_OPENAI_API_VERSION"),this.azureOpenAIBasePath=(t==null?void 0:t.azureOpenAIBasePath)??It("AZURE_OPENAI_BASE_PATH"),this.azureOpenAIEndpoint=(t==null?void 0:t.azureOpenAIEndpoint)??It("AZURE_OPENAI_ENDPOINT"),this.azureADTokenProvider=t==null?void 0:t.azureADTokenProvider,!this.azureOpenAIApiKey&&!this.apiKey&&!this.azureADTokenProvider)throw new Error("Azure OpenAI API key or Token Provider not found")}function Ik(t){if(!this.client){const n={azureOpenAIApiDeploymentName:this.azureOpenAIApiDeploymentName,azureOpenAIApiInstanceName:this.azureOpenAIApiInstanceName,azureOpenAIApiKey:this.azureOpenAIApiKey,azureOpenAIBasePath:this.azureOpenAIBasePath,azureADTokenProvider:this.azureADTokenProvider,baseURL:this.clientConfig.baseURL,azureOpenAIEndpoint:this.azureOpenAIEndpoint},r=mk(n),{apiKey:s,...a}=this.clientConfig,i={...a,baseURL:r,timeout:this.timeout,maxRetries:0};this.azureADTokenProvider||(i.apiKey=n.azureOpenAIApiKey),i.baseURL||delete i.baseURL,i.defaultHeaders=gk(i.defaultHeaders,!0,"2.0.0"),this.client=new p9({apiVersion:this.azureOpenAIApiVersion,azureADTokenProvider:this.azureADTokenProvider,deployment:this.azureOpenAIApiDeploymentName,...i})}const e={...this.clientConfig,...t};return this.azureOpenAIApiKey&&(e.headers={"api-key":this.azureOpenAIApiKey,...e.headers},e.query={"api-version":this.azureOpenAIApiVersion,...e.query}),e}function ay(t){const e=t;function n(r){return typeof r=="object"&&r!=null}if(n(e)&&n(e.kwargs)){if(delete e.kwargs.azure_openai_base_path,delete e.kwargs.azure_openai_api_deployment_name,delete e.kwargs.azure_openai_api_key,delete e.kwargs.azure_openai_api_version,delete e.kwargs.azure_open_ai_base_path,!e.kwargs.azure_endpoint&&this.azureOpenAIEndpoint&&(e.kwargs.azure_endpoint=this.azureOpenAIEndpoint),!e.kwargs.azure_endpoint&&this.azureOpenAIBasePath){const r=this.azureOpenAIBasePath.split("/openai/deployments/");if(r.length===2&&r[0].startsWith("http")){const[s]=r;e.kwargs.azure_endpoint=s}}if(!e.kwargs.azure_endpoint&&this.azureOpenAIApiInstanceName&&(e.kwargs.azure_endpoint=`https://${this.azureOpenAIApiInstanceName}.openai.azure.com/`),!e.kwargs.deployment_name&&this.azureOpenAIApiDeploymentName&&(e.kwargs.deployment_name=this.azureOpenAIApiDeploymentName),!e.kwargs.deployment_name&&this.azureOpenAIBasePath){const r=this.azureOpenAIBasePath.split("/openai/deployments/");if(r.length===2){const[,s]=r;e.kwargs.deployment_name=s}}e.kwargs.azure_endpoint&&e.kwargs.deployment_name&&e.kwargs.openai_api_base&&delete e.kwargs.openai_api_base,e.kwargs.azure_openai_api_instance_name&&e.kwargs.azure_endpoint&&delete e.kwargs.azure_openai_api_instance_name}return e}var M8=class extends Ak{constructor(e,n){const r=ry(e,n);super(r);p(this,"azureOpenAIApiVersion");p(this,"azureOpenAIApiKey");p(this,"azureADTokenProvider");p(this,"azureOpenAIApiInstanceName");p(this,"azureOpenAIApiDeploymentName");p(this,"azureOpenAIBasePath");p(this,"azureOpenAIEndpoint");sy.call(this,r)}_llmType(){return"azure_openai"}get lc_aliases(){return{...super.lc_aliases,...ey}}get lc_secrets(){return{...super.lc_secrets,...ty}}get lc_serializable_keys(){return[...super.lc_serializable_keys,...ny]}getLsParams(e){const n=super.getLsParams(e);return n.ls_provider="azure",n}_getClientOptions(e){return Ik.call(this,e)}toJSON(){return ay.call(this,super.toJSON())}};const bi="__openai_function_call_ids__";function xk(t){return t.type==="url_citation"?{type:"citation",source:"url_citation",url:t.url,title:t.title,startIndex:t.start_index,endIndex:t.end_index}:t.type==="file_citation"?{type:"citation",source:"file_citation",title:t.filename,startIndex:t.index,file_id:t.file_id}:t.type==="container_file_citation"?{type:"citation",source:"container_file_citation",title:t.filename,startIndex:t.start_index,endIndex:t.end_index,file_id:t.file_id,container_id:t.container_id}:t.type==="file_path"?{type:"citation",source:"file_path",startIndex:t.index,file_id:t.file_id}:{type:"non_standard",value:t}}function L8(t){if(t.type==="url_citation"||t.type==="file_citation"||t.type==="container_file_citation"||t.type==="file_path")return t;if(t.type==="citation"){const e=t;if(e.source==="url_citation")return{type:"url_citation",url:e.url??"",title:e.title??"",start_index:e.startIndex??0,end_index:e.endIndex??0};if(e.source==="file_citation")return{type:"file_citation",file_id:e.file_id??"",filename:e.title??"",index:e.startIndex??0};if(e.source==="container_file_citation")return{type:"container_file_citation",file_id:e.file_id??"",filename:e.title??"",container_id:e.container_id??"",start_index:e.startIndex??0,end_index:e.endIndex??0};if(e.source==="file_path")return{type:"file_path",file_id:e.file_id??"",index:e.startIndex??0}}return t.type==="non_standard"?t.value:t}const kk=t=>{var r,s,a,i;const e={...((r=t==null?void 0:t.input_tokens_details)==null?void 0:r.cached_tokens)!=null&&{cache_read:(s=t==null?void 0:t.input_tokens_details)==null?void 0:s.cached_tokens}},n={...((a=t==null?void 0:t.output_tokens_details)==null?void 0:a.reasoning_tokens)!=null&&{reasoning:(i=t==null?void 0:t.output_tokens_details)==null?void 0:i.reasoning_tokens}};return{input_tokens:(t==null?void 0:t.input_tokens)??0,output_tokens:(t==null?void 0:t.output_tokens)??0,total_tokens:(t==null?void 0:t.total_tokens)??0,input_token_details:e,output_token_details:n}},Ok=t=>{var c;if(t.error){const u=new Error(t.error.message);throw u.name=t.error.code,u}let e;const n=[],r=[],s=[],a=t.output.map(u=>{if(u.type==="function_call"&&"parsed_arguments"in u){const l={...u};return delete l.parsed_arguments,l}return u}),i={model_provider:"openai",model:t.model,created_at:t.created_at,id:t.id,incomplete_details:t.incomplete_details,metadata:t.metadata,object:t.object,output:a,status:t.status,user:t.user,service_tier:t.service_tier,model_name:t.model},o={};for(const u of t.output)if(u.type==="message")e=u.id,n.push(...u.content.flatMap(l=>l.type==="output_text"?("parsed"in l&&l.parsed!=null&&(o.parsed=l.parsed),{type:"text",text:l.text,annotations:l.annotations.map(xk),...u.phase!==null?{phase:u.phase}:{}}):l.type==="refusal"?(o.refusal=l.refusal,[]):l));else if(u.type==="function_call"){const l={function:{name:u.name,arguments:u.arguments},id:u.call_id};try{r.push(oh(l,{returnId:!0}))}catch(d){let f;typeof d=="object"&&d!=null&&"message"in d&&typeof d.message=="string"&&(f=d.message),s.push(tc(l,f))}o[bi]??(o[bi]={}),u.id&&(o[bi][u.call_id]=u.id)}else if(u.type==="reasoning"){o.reasoning=u;const l=(c=u.summary)==null?void 0:c.map(d=>d.text).filter(Boolean).join("");l&&n.push({type:"reasoning",reasoning:l})}else if(u.type==="custom_tool_call"){const l=x9(u);l?r.push(l):s.push(tc(u,"Malformed custom tool call"))}else if(u.type==="computer_call"){const l=k9(u);l?r.push(l):s.push(tc(u,"Malformed computer call"))}else u.type==="image_generation_call"?(u.result&&n.push({type:"image",mimeType:"image/png",data:u.result,id:u.id,metadata:{status:u.status}}),o.tool_outputs??(o.tool_outputs=[]),o.tool_outputs.push(u)):(o.tool_outputs??(o.tool_outputs=[]),o.tool_outputs.push(u));return new De({id:e,content:n,tool_calls:r,invalid_tool_calls:s,usage_metadata:kk(t.usage),additional_kwargs:o,response_metadata:i})},j8=t=>{const e=(t.summary.length>1?t.summary.reduce((n,r)=>{const s=n[n.length-1];return s.index===r.index?s.text+=r.text:n.push(r),n},[{...t.summary[0]}]):t.summary).map(n=>Object.fromEntries(Object.entries(n).filter(([r])=>r!=="index")));return{...t,summary:e}},U8=t=>{var c,u,l;const e=[];let n={},r;const s=[],a={model_provider:"openai"},i={};let o;if(t.type==="response.output_text.delta")e.push({type:"text",text:t.delta,index:t.content_index});else if(t.type==="response.output_text.annotation.added")e.push({type:"text",text:"",annotations:[xk(t.annotation)],index:t.content_index});else if(t.type==="response.output_item.added"&&t.item.type==="message"){o=t.item.id;const d="phase"in t.item?t.item.phase:void 0;d&&e.push({type:"text",text:"",phase:d,index:0})}else if(t.type==="response.output_item.added"&&t.item.type==="function_call")s.push({type:"tool_call_chunk",name:t.item.name,args:t.item.arguments,id:t.item.call_id,index:t.output_index}),i[bi]={[t.item.call_id]:t.item.id};else if(t.type==="response.output_item.done"&&t.item.type==="computer_call")s.push({type:"tool_call_chunk",name:"computer_use",args:JSON.stringify({action:t.item.action}),id:t.item.call_id,index:t.output_index}),i.tool_outputs=[t.item];else if(t.type==="response.output_item.done"&&t.item.type==="image_generation_call")t.item.result&&e.push({type:"image",mimeType:"image/png",data:t.item.result,id:t.item.id,metadata:{status:t.item.status}}),i.tool_outputs=[t.item];else if(t.type==="response.output_item.done"&&["web_search_call","file_search_call","code_interpreter_call","shell_call","local_shell_call","mcp_call","mcp_list_tools","mcp_approval_request","custom_tool_call","tool_search_call","tool_search_output"].includes(t.item.type))i.tool_outputs=[t.item];else if(t.type==="response.created")a.id=t.response.id,a.model_name=t.response.model,a.model=t.response.model;else if(t.type==="response.completed"){const d=Ok(t.response);r=kk(t.response.usage),((u=(c=t.response.text)==null?void 0:c.format)==null?void 0:u.type)==="json_schema"&&d.text&&(i.parsed??(i.parsed=JSON.parse(d.text)));for(const[f,h]of Object.entries(t.response))f!=="id"&&(f==="output"?a[f]=d.response_metadata.output:a[f]=h)}else if(t.type==="response.function_call_arguments.delta"||t.type==="response.custom_tool_call_input.delta")s.push({type:"tool_call_chunk",args:t.delta,index:t.output_index});else if(t.type==="response.web_search_call.completed"||t.type==="response.file_search_call.completed")n={tool_outputs:{id:t.item_id,type:t.type.replace("response.","").replace(".completed",""),status:"completed"}};else if(t.type==="response.refusal.done")i.refusal=t.refusal;else if(t.type==="response.output_item.added"&&"item"in t&&t.item.type==="reasoning"){const d=t.item.summary?t.item.summary.map((h,m)=>({...h,index:m})):void 0;i.reasoning={id:t.item.id,type:t.item.type,...d?{summary:d}:{}};const f=(l=t.item.summary)==null?void 0:l.map(h=>h.text).filter(Boolean).join("");f&&e.push({type:"reasoning",reasoning:f})}else if(t.type==="response.reasoning_summary_part.added")i.reasoning={type:"reasoning",summary:[{...t.part,index:t.summary_index}]},t.part.text&&e.push({type:"reasoning",reasoning:t.part.text,index:t.summary_index});else if(t.type==="response.reasoning_summary_text.delta")i.reasoning={type:"reasoning",summary:[{text:t.delta,type:"summary_text",index:t.summary_index}]},t.delta&&e.push({type:"reasoning",reasoning:t.delta,index:t.summary_index});else return t.type==="response.image_generation_call.partial_image",null;return new qn({text:e.map(d=>d.text).join(""),message:new Qe({id:o,content:e,tool_call_chunks:s,usage_metadata:r,additional_kwargs:i,response_metadata:a}),generationInfo:n})},D8=t=>{var r;const e=De.isInstance(t)&&((r=t.response_metadata)==null?void 0:r.model_provider)==="openai";function*n(){const s=ps(()=>{try{const g=ou(t);return g==="system"||g==="developer"||g==="assistant"||g==="user"?g:"assistant"}catch{return"assistant"}});let a;const i=new Set,o=new Set,c=new Map,u=new Map;function*l(){if(!a)return;const g=a.content;(typeof g=="string"&&g.length>0||Array.isArray(g)&&g.length>0)&&(yield a),a=void 0}const d=(g,b)=>{a||(a={type:"message",role:s,content:[],...b?{phase:b}:{}}),typeof a.content=="string"?a.content=a.content.length>0?[{type:"input_text",text:a.content},...g]:[...g]:a.content.push(...g)},f=g=>{if(typeof g=="string")return g;try{return JSON.stringify(g??{})}catch{return"{}"}},h=g=>{const b=ps(()=>{var I;const S=(I=g.metadata)==null?void 0:I.detail;return S==="low"||S==="high"||S==="auto"?S:"auto"});if(g.fileId)return{type:"input_image",detail:b,file_id:g.fileId};if(g.url)return{type:"input_image",detail:b,image_url:g.url};if(g.data){const S=typeof g.data=="string"?g.data:Buffer.from(g.data).toString("base64");return{type:"input_image",detail:b,image_url:`data:${g.mimeType??"image/png"};base64,${S}`}}},m=g=>{if(g.fileId){const b=Tv(g);return{type:"input_file",file_id:g.fileId,...b?{filename:b}:{}}}if(g.url){const b=Tv(g);return{...b?{filename:b}:{},type:"input_file",file_url:g.url}}if(g.data){const b=Md(g),S=typeof g.data=="string"?g.data:Buffer.from(g.data).toString("base64");return{type:"input_file",file_data:`data:${g.mimeType??"application/octet-stream"};base64,${S}`,filename:b}}},_=g=>{const b=ps(()=>{var T;if(Array.isArray(g.summary)){const x=((T=g.summary)==null?void 0:T.map(A=>A==null?void 0:A.text).filter(A=>typeof A=="string"))??[];if(x.length>0)return x}return g.reasoning?[g.reasoning]:[]}),S=b.length>0?b.map(T=>({type:"summary_text",text:T})):[{type:"summary_text",text:""}],I={type:"reasoning",id:g.id??"",summary:S};return g.reasoning&&(I.content=[{type:"reasoning_text",text:g.reasoning}]),I},y=g=>({type:"function_call",name:g.name??"",call_id:g.id??"",arguments:f(g.args)}),w=g=>{const b=f(g.output),S=g.status==="success"?"completed":g.status==="error"?"incomplete":void 0;return{type:"function_call_output",call_id:g.toolCallId??"",output:b,...S?{status:S}:{}}};for(const g of t.contentBlocks)if(g.type==="text"){const b=ps(()=>{if("extras"in g&&typeof g.extras=="object"&&g.extras!==null&&"phase"in g.extras)return g.extras.phase});d([{type:"input_text",text:g.text}],b)}else if(g.type!=="invalid_tool_call"){if(g.type==="reasoning")yield*l(),yield _(g);else if(g.type==="tool_call"){yield*l();const b=g.id??"";b&&(i.add(b),c.delete(b)),yield y(g)}else if(g.type==="tool_call_chunk"){if(g.id){const b=c.get(g.id)??{name:g.name,args:[]};g.name&&(b.name=g.name),g.args&&b.args.push(g.args),c.set(g.id,b)}}else if(g.type==="server_tool_call"){yield*l();const b=g.id??"";b&&(o.add(b),u.delete(b)),yield y(g)}else if(g.type==="server_tool_call_chunk"){if(g.id){const b=u.get(g.id)??{name:g.name,args:[]};g.name&&(b.name=g.name),g.args&&b.args.push(g.args),u.set(g.id,b)}}else if(g.type==="server_tool_call_result")yield*l(),yield w(g);else if(g.type!=="audio")if(g.type==="file"){const b=m(g);b&&d([b])}else if(g.type==="image"){const b=h(g);b&&d([b])}else if(g.type==="video"){const b=m(g);b&&d([b])}else g.type==="text-plain"?g.text&&d([{type:"input_text",text:g.text}]):g.type==="non_standard"&&e&&(yield*l(),yield g.value)}yield*l();for(const[g,b]of c){if(!g||i.has(g))continue;const S=b.args.join("");!b.name&&!S||(yield{type:"function_call",call_id:g,name:b.name??"",arguments:S})}for(const[g,b]of u){if(!g||o.has(g))continue;const S=b.args.join("");!b.name&&!S||(yield{type:"function_call",call_id:g,name:b.name??"",arguments:S})}}return Array.from(n())},Cv=({messages:t,zdrEnabled:e,model:n})=>t.flatMap(r=>{var o,c,u,l;const s=r.response_metadata;if((s==null?void 0:s.output_version)==="v1")return D8(r);const a=r.additional_kwargs;let i=ou(r);if(i==="system"&&iu(n)&&(i="developer"),i==="function")throw new Error("Function messages are not supported in Responses API");if(i==="tool"){const d=r;if((a==null?void 0:a.type)==="computer_call_output")return{type:"computer_call_output",output:(()=>{if(typeof d.content=="string")return{type:"input_image",image_url:d.content};if(Array.isArray(d.content)){const h=d.content.find(y=>y.type==="input_image");if(h)return h;const m=d.content.find(y=>y.type==="computer_screenshot");if(m)return m;const _=d.content.find(y=>y.type==="image_url");if(_)return{type:"input_image",image_url:typeof _.image_url=="string"?_.image_url:_.image_url.url}}throw new Error("Invalid computer call output")})(),call_id:d.tool_call_id};if((o=d.additional_kwargs)!=null&&o.customTool)return{type:"custom_tool_call_output",call_id:d.tool_call_id,output:d.content};const f=Array.isArray(d.content)&&d.content.every(h=>typeof h=="object"&&h!==null&&"type"in h&&(h.type==="input_file"||h.type==="input_image"||h.type==="input_text"));return{type:"function_call_output",call_id:d.tool_call_id,id:(c=d.id)!=null&&c.startsWith("fc_")?d.id:void 0,output:f?d.content:typeof d.content!="string"?JSON.stringify(d.content):d.content}}if(i==="assistant"){if(!e&&(s==null?void 0:s.output)!=null&&Array.isArray(s==null?void 0:s.output)&&(s==null?void 0:s.output.length)>0&&(s!=null&&s.output.every(g=>"type"in g)))return s==null?void 0:s.output;const d=[],f=a==null?void 0:a.reasoning,h=!!(f!=null&&f.encrypted_content);if(f&&(!e||h)){const g=j8(f);d.push(g)}let{content:m}=r;if(a!=null&&a.refusal&&(typeof m=="string"&&(m=[{type:"output_text",text:m,annotations:[]}]),m=[...m,{type:"refusal",refusal:a.refusal}]),typeof m=="string"||m.length>0){const g={type:"message",role:"assistant",...r.id&&!e&&r.id.startsWith("msg_")?{id:r.id}:{},content:ps(()=>typeof m=="string"?m:m.flatMap(b=>{if(b.type==="text"){const S=b;return{type:"output_text",text:S.text,annotations:(S.annotations??[]).map(L8)}}return b.type==="output_text"||b.type==="refusal"?b:[]})),phase:ps(()=>{var b;if(Array.isArray(m))return(b=m.find(S=>"phase"in S&&typeof S.phase=="string"))==null?void 0:b.phase})};d.push(g)}const _=a==null?void 0:a[bi];De.isInstance(r)&&((u=r.tool_calls)!=null&&u.length)?d.push(...r.tool_calls.map(g=>C9(g)?{type:"custom_tool_call",id:g.call_id,call_id:g.id??"",input:g.args.input,name:g.name}:O9(g)?{type:"computer_call",id:g.call_id,call_id:g.id??"",action:g.args.action}:{type:"function_call",name:g.name,arguments:JSON.stringify(g.args),call_id:g.id,...e?{}:{id:_==null?void 0:_[g.id]}})):a!=null&&a.tool_calls&&d.push(...a.tool_calls.map(g=>({type:"function_call",name:g.function.name,call_id:g.id,arguments:g.function.arguments,...e?{}:{id:_==null?void 0:_[g.id]}})));const y=(l=s==null?void 0:s.output)!=null&&l.length?s==null?void 0:s.output:a.tool_outputs,w=["computer_call","mcp_call","code_interpreter_call","image_generation_call","shell_call","local_shell_call"];if(y!=null){const g=y==null?void 0:y.filter(b=>w.includes(b.type));g.length>0&&d.push(...g)}return d}if(i==="user"||i==="system"||i==="developer"){if(typeof r.content=="string")return{type:"message",role:i,content:r.content};const d=[],f=r.content.flatMap(h=>(h.type==="mcp_approval_response"&&d.push({type:"mcp_approval_response",approval_request_id:h.approval_request_id,approve:h.approve}),ir(h)?jc(h,Ek):h.type==="text"?{type:"input_text",text:h.text}:h.type==="image_url"?{type:"input_image",image_url:ps(()=>{if(typeof h.image_url=="string")return h.image_url;if(typeof h.image_url=="object"&&h.image_url!==null&&"url"in h.image_url)return h.image_url.url}),detail:ps(()=>{if(typeof h.image_url=="string")return"auto";if(typeof h.image_url=="object"&&h.image_url!==null&&"detail"in h.image_url)return h.image_url.detail})}:h.type==="input_text"||h.type==="input_image"||h.type==="input_file"?h:[]));return f.length>0&&d.push({type:"message",role:i,content:f}),d}return console.warn(`Unsupported role found when converting to OpenAI Responses API: ${i}`),[]});var Ck=class extends Q_{constructor(t,e){super(Y_(t,e))}invocationParams(t){var s;let e;(t==null?void 0:t.strict)!==void 0&&(e=t.strict),e===void 0&&this.supportsStrictToolCalling!==void 0&&(e=this.supportsStrictToolCalling);const n={model:this.model,temperature:this.temperature,top_p:this.topP,user:this.user,service_tier:this.service_tier,stream:this.streaming,previous_response_id:t==null?void 0:t.previous_response_id,truncation:t==null?void 0:t.truncation,include:t==null?void 0:t.include,tools:(s=t==null?void 0:t.tools)!=null&&s.length?this._reduceChatOpenAITools(t.tools,{stream:this.streaming,strict:e}):void 0,tool_choice:I9(t==null?void 0:t.tool_choice)?t==null?void 0:t.tool_choice:(()=>{const a=yk(t==null?void 0:t.tool_choice);if(typeof a=="object"&&"type"in a){if(a.type==="function")return{type:"function",name:a.function.name};if(a.type==="allowed_tools")return{type:"allowed_tools",mode:a.allowed_tools.mode,tools:a.allowed_tools.tools};if(a.type==="custom")return{type:"custom",name:a.custom.name}}})(),text:(()=>{if(t!=null&&t.text)return t.text;const a=this._getResponseFormat(t==null?void 0:t.response_format);return(a==null?void 0:a.type)==="json_schema"?a.json_schema.schema!=null?{format:{type:"json_schema",schema:a.json_schema.schema,description:a.json_schema.description,name:a.json_schema.name,strict:a.json_schema.strict},verbosity:t==null?void 0:t.verbosity}:void 0:{format:a,verbosity:t==null?void 0:t.verbosity}})(),parallel_tool_calls:t==null?void 0:t.parallel_tool_calls,max_output_tokens:this.maxTokens===-1?void 0:this.maxTokens,prompt_cache_key:(t==null?void 0:t.promptCacheKey)??this.promptCacheKey,prompt_cache_retention:(t==null?void 0:t.promptCacheRetention)??this.promptCacheRetention,...this.zdrEnabled?{store:!1}:{},...this.modelKwargs},r=this._getReasoningParams(t);return r!==void 0&&(n.reasoning=r),n}async _generate(t,e,n){var s,a;(s=e.signal)==null||s.throwIfAborted();const r=this.invocationParams(e);if(r.stream){const i=this._streamResponseChunks(t,e,n);let o;for await(const c of i)c.message.response_metadata={...c.generationInfo,...c.message.response_metadata},o=(o==null?void 0:o.concat(c))??c;return{generations:o?[o]:[],llmOutput:{estimatedTokenUsage:(a=o==null?void 0:o.message)==null?void 0:a.usage_metadata}}}else{const i=await this.completionWithRetry({input:Cv({messages:t,zdrEnabled:this.zdrEnabled??!1,model:this.model}),...r,stream:!1},{signal:e==null?void 0:e.signal,...e==null?void 0:e.options});return{generations:[{text:i.output_text,message:Ok(i)}],llmOutput:{id:i.id,estimatedTokenUsage:i.usage?{promptTokens:i.usage.input_tokens,completionTokens:i.usage.output_tokens,totalTokens:i.usage.total_tokens}:void 0}}}}async*_streamResponseChunks(t,e,n){var s;const r=await this.completionWithRetry({...this.invocationParams(e),input:Cv({messages:t,zdrEnabled:this.zdrEnabled??!1,model:this.model}),stream:!0},e);for await(const a of r){if((s=e.signal)!=null&&s.aborted)return;const i=U8(a);i!=null&&(yield i,await(n==null?void 0:n.handleLLMNewToken(i.text||"",{prompt:e.promptIndex??0,completion:0},void 0,void 0,void 0,{chunk:i})))}}async completionWithRetry(t,e){return this.caller.call(async()=>{var r,s;const n=this._getClientOptions(e);try{return((s=(r=t.text)==null?void 0:r.format)==null?void 0:s.type)==="json_schema"&&!t.stream?await this.client.responses.parse(t,n):await this.client.responses.create(t,n)}catch(a){throw J_(a)}})}_reduceChatOpenAITools(t,e){const n=[];for(const r of t)if(X_(r))r.type==="image_generation"&&(e!=null&&e.stream)&&(r.partial_images=1),n.push(r);else if(jd(r)){const s=r.metadata.customTool;n.push({type:"custom",name:s.name,description:s.description,format:s.format})}else if(Gi(r)){const s={};for(const[a,i]of Object.entries(r))a!=="type"&&a!=="function"&&(s[a]=i);n.push({type:"function",name:r.function.name,parameters:r.function.parameters,description:r.function.description,strict:(e==null?void 0:e.strict)??null,...s})}else wk(r)&&n.push(R9(r));return n}},F8=class extends Ck{constructor(e,n){const r=ry(e,n);super(r);p(this,"azureOpenAIApiVersion");p(this,"azureOpenAIApiKey");p(this,"azureADTokenProvider");p(this,"azureOpenAIApiInstanceName");p(this,"azureOpenAIApiDeploymentName");p(this,"azureOpenAIBasePath");p(this,"azureOpenAIEndpoint");sy.call(this,r)}_llmType(){return"azure_openai"}get lc_aliases(){return{...super.lc_aliases,...ey}}get lc_secrets(){return{...super.lc_secrets,...ty}}get lc_serializable_keys(){return[...super.lc_serializable_keys,...ny]}getLsParams(e){const n=super.getLsParams(e);return n.ls_provider="azure",n}_getClientOptions(e){return Ik.call(this,e)}toJSON(){return ay.call(this,super.toJSON())}},Bl=class Rk extends Q_{constructor(n,r){const s=Y_(n,r);super(s);p(this,"useResponsesApi",!1);p(this,"responses");p(this,"completions");p(this,"fields");this.fields=s,this.useResponsesApi=(s==null?void 0:s.useResponsesApi)??!1,this.responses=(s==null?void 0:s.responses)??new Ck(s),this.completions=(s==null?void 0:s.completions)??new Ak(s)}get lc_serializable_keys(){return[...super.lc_serializable_keys,"useResponsesApi"]}get callKeys(){return[...super.callKeys,"useResponsesApi"]}_useResponsesApi(n){var i,o,c,u,l;const r=(i=n==null?void 0:n.tools)==null?void 0:i.some(X_),s=(n==null?void 0:n.previous_response_id)!=null||(n==null?void 0:n.text)!=null||(n==null?void 0:n.truncation)!=null||(n==null?void 0:n.include)!=null||((o=n==null?void 0:n.reasoning)==null?void 0:o.summary)!=null||((c=this.reasoning)==null?void 0:c.summary)!=null,a=((u=n==null?void 0:n.tools)==null?void 0:u.some(wk))||((l=n==null?void 0:n.tools)==null?void 0:l.some(jd));return this.useResponsesApi||r||s||a||w9(this.model)}getLsParams(n){const r=this._combineCallOptions(n);return this._useResponsesApi(n)?this.responses.getLsParams(r):this.completions.getLsParams(r)}invocationParams(n){const r=this._combineCallOptions(n);return this._useResponsesApi(n)?this.responses.invocationParams(r):this.completions.invocationParams(r)}async _generate(n,r,s){return this._useResponsesApi(r)?this.responses._generate(n,r,s):this.completions._generate(n,r,s)}async*_streamResponseChunks(n,r,s){if(this._useResponsesApi(r)){yield*this.responses._streamResponseChunks(n,this._combineCallOptions(r),s);return}yield*this.completions._streamResponseChunks(n,this._combineCallOptions(r),s)}withConfig(n){const r=new Rk(this.fields);return r.defaultOptions={...this.defaultOptions,...n},r}},B8=class extends Bl{constructor(e,n){const r=ry(e,n);super({...r,completions:new M8(r),responses:new F8(r)});p(this,"azureOpenAIApiVersion");p(this,"azureOpenAIApiKey");p(this,"azureADTokenProvider");p(this,"azureOpenAIApiInstanceName");p(this,"azureOpenAIApiDeploymentName");p(this,"azureOpenAIBasePath");p(this,"azureOpenAIEndpoint");sy.call(this,r)}_llmType(){return"azure_openai"}get lc_aliases(){return{...super.lc_aliases,...ey}}get lc_secrets(){return{...super.lc_secrets,...ty}}get lc_serializable_keys(){return[...super.lc_serializable_keys,...ny]}getLsParams(e){const n=super.getLsParams(e);return n.ls_provider="azure",n}_getStructuredOutputMethod(e){const n={...e};return this.model.startsWith("gpt-4o")&&(n==null?void 0:n.method)===void 0?"functionCalling":super._getStructuredOutputMethod(n)}toJSON(){return ay.call(this,super.toJSON())}};const z8=Oe({type:Le("screenshot")}),H8=Oe({type:Le("click"),x:st(),y:st(),button:hh(["left","right","wheel","back","forward"]).default("left")}),V8=Oe({type:Le("double_click"),x:st(),y:st(),button:hh(["left","right","wheel","back","forward"]).default("left")}),Z8=Oe({type:Le("drag"),path:La(Oe({x:st(),y:st()}))}),W8=Oe({type:Le("keypress"),keys:La(Ve())}),G8=Oe({type:Le("move"),x:st(),y:st()}),q8=Oe({type:Le("scroll"),x:st(),y:st(),scroll_x:st(),scroll_y:st()}),K8=Oe({type:Le("type"),text:Ve()}),J8=Oe({type:Le("wait"),duration:st().optional()}),X8=nu([z8,H8,V8,Z8,W8,G8,q8,K8,J8]);Oe({action:X8});const Y8=Oe({type:Le("exec"),command:La(Ve()),env:xB(Ve(),Ve()).optional(),working_directory:Ve().optional(),timeout_ms:st().optional(),user:Ve().optional()});nu([Y8]);Oe({commands:La(Ve()).describe("Array of shell commands to execute"),timeout_ms:st().optional().describe("Optional timeout in milliseconds for the commands"),max_output_length:st().optional().describe("Optional maximum number of characters to return from each command")});const Q8=Oe({type:Le("create_file"),path:Ve(),diff:Ve()}),eH=Oe({type:Le("update_file"),path:Ve(),diff:Ve()}),tH=Oe({type:Le("delete_file"),path:Ve()});nu([Q8,eH,tH]);function Da(t){if(typeof t=="object"&&t!==null){const e={...t};"additionalProperties"in e&&delete e.additionalProperties,"$schema"in e&&delete e.$schema,"strict"in e&&delete e.strict;for(const n in e)n in e&&(Array.isArray(e[n])?e[n]=e[n].map(Da):typeof e[n]=="object"&&e[n]!==null&&(e[n]=Da(e[n])));return e}return t}function Gm(t){const{$schema:e,...n}=Da(Lt(t)||cr(t)?lt(t):t);return n}function nH(t){const{$schema:e,...n}=Da(t);return n}function vi(t,e,n=[]){if(t==null||typeof t!="object")return;const r=t;if(Array.isArray(r.enum)&&r.enum.some(s=>s==="")){const s=n.length?` at path "${n.join(".")}"`:"",a=e?` in tool "${e}"`:"";throw new Error(`Invalid enum: empty string not allowed${a}${s}. Gemini API rejects empty strings in enums.`)}if(r.type==="object"&&r.properties&&typeof r.properties=="object")for(const[s,a]of Object.entries(r.properties))vi(a,e,[...n,s]);r.items&&vi(r.items,e,[...n,"[]"]);for(const s of["anyOf","oneOf","allOf"]){const a=r[s];Array.isArray(a)&&a.forEach((i,o)=>vi(i,e,[...n,`${s}[${o}]`]))}r.additionalProperties&&typeof r.additionalProperties=="object"&&vi(r.additionalProperties,e,[...n,"additionalProperties"])}const iy="__gemini_function_call_thought_signatures__",rH="ErYCCrMCAdHtim9kOoOkrPiCNVsmlpMIKd7ZMxgiFbVQOkgp7nlLcDMzVsZwIzvuT7nQROivoXA72ccC2lSDvR0Gh7dkWaGuj7ctv6t7ZceHnecx0QYa+ix8tYpRfjhyWozQ49lWiws6+YGjCt10KRTyWsZ2h6O7iHTYJwKIRwGUHRKy/qK/6kFxJm5ML00gLq4D8s5Z6DBpp2ZlR+uF4G8jJgeWQgyHWVdx2wGYElaceVAc66tZdPQRdOHpWtgYSI1YdaXgVI8KHY3/EfNc2YqqMIulvkDBAnuMhkAjV9xmBa54Tq+ih3Im4+r3DzqhGqYdsSkhS0kZMwte4Hjs65dZzCw9lANxIqYi1DJ639WNPYihp/DCJCos7o+/EeSPJaio5sgWDyUnMGkY1atsJZ+m7pj7DD5tvQ==",sH=t=>t();function aH(t){return Kr.isInstance(t)?t.role:t.type}function iH(t){switch(t){case"supervisor":case"ai":case"model":return"model";case"system":return"system";case"human":return"user";case"tool":case"function":return"function";default:throw new Error(`Unknown / unsupported author: ${t}`)}}function oH(t){if("mimeType"in t&&"data"in t)return{inlineData:{mimeType:t.mimeType,data:t.data}};if("mimeType"in t&&"fileUri"in t)return{fileData:{mimeType:t.mimeType,fileUri:t.fileUri}};throw new Error("Invalid media content")}function cH(t,e){var n;return(n=e.map(r=>or(r)?r.tool_calls??[]:[]).flat().find(r=>r.id===t.tool_call_id))==null?void 0:n.name}function co(t,e){if("data"in t&&t.data!==void 0){const n=t.data instanceof Uint8Array?btoa(String.fromCharCode(...t.data)):t.data;return{inlineData:{mimeType:t.mimeType||e,data:n}}}if("url"in t&&t.url!==void 0){const n=Ir({dataUrl:t.url});return n?{inlineData:{mimeType:n.mime_type,data:n.data}}:{fileData:{mimeType:t.mimeType||e,fileUri:t.url}}}throw"fileId"in t&&t.fileId!==void 0?new Error("ContentBlock.Multimodal fileId is not supported by Google Generative AI. Use a URL or base64 data instead."):new Error(`Invalid multimodal content block: must have "data", "url", or "fileId" property. Received: ${JSON.stringify(t)}`)}function uH(t){return{providerName:"Google Gemini",fromStandardTextBlock(e){return{text:e.text}},fromStandardImageBlock(e){if(!t)throw new Error("This model does not support images");if(e.source_type==="url"){const n=Ir({dataUrl:e.url});return n?{inlineData:{mimeType:n.mime_type,data:n.data}}:{fileData:{mimeType:e.mime_type??"",fileUri:e.url}}}if(e.source_type==="base64")return{inlineData:{mimeType:e.mime_type??"",data:e.data}};throw new Error(`Unsupported source type: ${e.source_type}`)},fromStandardAudioBlock(e){if(!t)throw new Error("This model does not support audio");if(e.source_type==="url"){const n=Ir({dataUrl:e.url});return n?{inlineData:{mimeType:n.mime_type,data:n.data}}:{fileData:{mimeType:e.mime_type??"",fileUri:e.url}}}if(e.source_type==="base64")return{inlineData:{mimeType:e.mime_type??"",data:e.data}};throw new Error(`Unsupported source type: ${e.source_type}`)},fromStandardFileBlock(e){if(!t)throw new Error("This model does not support files");if(e.source_type==="text")return{text:e.text};if(e.source_type==="url"){const n=Ir({dataUrl:e.url});return n?{inlineData:{mimeType:n.mime_type,data:n.data}}:{fileData:{mimeType:e.mime_type??"",fileUri:e.url}}}if(e.source_type==="base64")return{inlineData:{mimeType:e.mime_type??"",data:e.data}};throw new Error(`Unsupported source type: ${e.source_type}`)}}}function Rv(t,e){var n;if(ir(t))return jc(t,uH(e));if(t.type==="text")return{text:t.text};if(t.type==="executableCode")return{executableCode:t.executableCode};if(t.type==="codeExecutionResult")return{codeExecutionResult:t.codeExecutionResult};if(t.type==="image_url"){if(!e)throw new Error("This model does not support images");let r;if(typeof t.image_url=="string")r=t.image_url;else if(typeof t.image_url=="object"&&"url"in t.image_url)r=t.image_url.url;else throw new Error("Please provide image as base64 encoded data URL");const[s,a]=r.split(",");if(!s.startsWith("data:"))throw new Error("Please provide image as base64 encoded data URL");const[i,o]=s.replace(/^data:/,"").split(";");if(o!=="base64")throw new Error("Please provide image as base64 encoded data URL");return{inlineData:{data:a,mimeType:i}}}else{if(t.type==="media")return oH(t);if(t.type==="image")return co(t,"image/png");if(t.type==="video")return co(t,"video/mp4");if(t.type==="audio")return co(t,"audio/mpeg");if(t.type==="file")return co(t,"application/octet-stream");if(t.type==="text-plain")return"text"in t&&typeof t.text=="string"?{text:t.text}:co(t,"text/plain");if(t.type==="tool_use")return{functionCall:{name:t.name,args:t.input}};if(t.type==="tool_call")return{functionCall:{name:t.name,args:t.args}};if((n=t.type)!=null&&n.includes("/")&&t.type.split("/").length===2&&"data"in t&&typeof t.data=="string")return{inlineData:{mimeType:t.type,data:t.data}};if(t.type==="thinking"){const r=t;return{text:r.thinking,thought:!0,...r.signature?{thoughtSignature:r.signature}:{}}}else{if("functionCall"in t)return;throw"type"in t?new Error(`Unknown content type ${t.type}`):new Error(`Unknown content ${JSON.stringify(t)}`)}}}function lH(t,e,n,r){var o,c;if(Ia(t)){const u=t.name??cH(t,n);if(u===void 0)throw new Error(`Google requires a tool name for each tool call response, and we could not infer a called tool name for ToolMessage "${t.id}" from your passed messages. Please populate a "name" field on that ToolMessage explicitly.`);const l=Array.isArray(t.content)?t.content.map(d=>Rv(d,e)).filter(d=>d!==void 0):t.content;return t.status==="error"?[{functionResponse:{name:u,response:{error:{details:l}}}}]:[{functionResponse:{name:u,response:{result:l}}}]}let s=[];const a=[];typeof t.content=="string"&&t.content&&a.push({text:t.content}),Array.isArray(t.content)&&a.push(...t.content.map(u=>Rv(u,e)).filter(u=>u!==void 0));const i=(o=t.additional_kwargs)==null?void 0:o[iy];return or(t)&&((c=t.tool_calls)!=null&&c.length)&&(s=t.tool_calls.map(u=>{const l=sH(()=>{if(u.id){const d=i==null?void 0:i[u.id];if(d)return d}return r!=null&&r.includes("gemini-3")?rH:""});return{functionCall:{name:u.name,args:u.args},...l?{thoughtSignature:l}:{}}})),[...a,...s]}function $v(t,e,n=!1,r){return t.reduce((s,a,i)=>{if(!wt(a))throw new Error("Unsupported message input");const o=aH(a);if(o==="system"&&i!==0)throw new Error("System message should be the first one");const c=iH(o),u=s.content[s.content.length];if(!s.mergeWithPreviousContent&&u&&u.role===c)throw new Error("Google Generative AI requires alternate messages between authors");const l=lH(a,e,t.slice(0,i),r);if(s.mergeWithPreviousContent){const h=s.content[s.content.length-1];if(!h)throw new Error("There was a problem parsing your system message. Please try a prompt without one.");return h.parts.push(...l),{mergeWithPreviousContent:!1,content:s.content}}let d=c;(d==="function"||d==="system"&&!n)&&(d="user");const f={role:d,parts:l};return{mergeWithPreviousContent:o==="system"&&!n,content:[...s.content,f]}},{content:[],mergeWithPreviousContent:!1}).content}function dH(t,e){var l,d,f,h,m;if(!t.candidates||t.candidates.length===0||!t.candidates[0])return{generations:[],llmOutput:{filters:t.promptFeedback}};const[n]=t.candidates,{content:r,...s}=n,a=(l=r==null?void 0:r.parts)==null?void 0:l.reduce((_,y)=>("functionCall"in y&&y.functionCall&&_.push({...y,id:"id"in y.functionCall&&typeof y.functionCall.id=="string"?y.functionCall.id:Hc()}),_),[]);let i;const o=r==null?void 0:r.parts;Array.isArray(o)&&o.length===1&&"text"in o[0]&&o[0].text&&!o[0].thought?i=o[0].text:Array.isArray(o)&&o.length>0?i=o.map(_=>_.thought&&"text"in _&&_.text?{type:"thinking",thinking:_.text,..._.thoughtSignature?{signature:_.thoughtSignature}:{}}:"text"in _?{type:"text",text:_.text}:"inlineData"in _?{type:"inlineData",inlineData:_.inlineData}:"functionCall"in _?{type:"functionCall",functionCall:_.functionCall}:"functionResponse"in _?{type:"functionResponse",functionResponse:_.functionResponse}:"fileData"in _?{type:"fileData",fileData:_.fileData}:"executableCode"in _?{type:"executableCode",executableCode:_.executableCode}:"codeExecutionResult"in _?{type:"codeExecutionResult",codeExecutionResult:_.codeExecutionResult}:_):i=[];const c=a==null?void 0:a.reduce((_,y)=>("thoughtSignature"in y&&typeof y.thoughtSignature=="string"&&(_[y.id]=y.thoughtSignature),_),{});let u="";return typeof i=="string"?u=i:Array.isArray(i)&&i.length>0&&(u=((d=i.find(_=>"text"in _))==null?void 0:d.text)??u),{generations:[{text:u,message:new De({content:i??"",tool_calls:a==null?void 0:a.map(_=>({type:"tool_call",id:_.id,name:_.functionCall.name,args:_.functionCall.args})),additional_kwargs:{...s,[iy]:c},usage_metadata:e==null?void 0:e.usageMetadata}),generationInfo:s}],llmOutput:{tokenUsage:{promptTokens:(f=e==null?void 0:e.usageMetadata)==null?void 0:f.input_tokens,completionTokens:(h=e==null?void 0:e.usageMetadata)==null?void 0:h.output_tokens,totalTokens:(m=e==null?void 0:e.usageMetadata)==null?void 0:m.total_tokens}}}}function hH(t,e){var d,f;if(!t.candidates||t.candidates.length===0)return null;const[n]=t.candidates,{content:r,...s}=n,a=(d=r.parts)==null?void 0:d.reduce((h,m)=>("functionCall"in m&&m.functionCall&&h.push({...m,id:"id"in m.functionCall&&typeof m.functionCall.id=="string"?m.functionCall.id:Hc()}),h),[]);let i;const o=r==null?void 0:r.parts;Array.isArray(o)&&o.every(h=>"text"in h&&!h.thought)?i=o.map(h=>h.text).join(""):Array.isArray(o)?i=o.map(h=>h.thought&&"text"in h&&h.text?{type:"thinking",thinking:h.text,...h.thoughtSignature?{signature:h.thoughtSignature}:{}}:"text"in h?{type:"text",text:h.text}:"inlineData"in h?{type:"inlineData",inlineData:h.inlineData}:"functionCall"in h?{type:"functionCall",functionCall:h.functionCall}:"functionResponse"in h?{type:"functionResponse",functionResponse:h.functionResponse}:"fileData"in h?{type:"fileData",fileData:h.fileData}:"executableCode"in h?{type:"executableCode",executableCode:h.executableCode}:"codeExecutionResult"in h?{type:"codeExecutionResult",codeExecutionResult:h.codeExecutionResult}:h):i=[];let c="";i&&typeof i=="string"?c=i:Array.isArray(i)&&(c=((f=i.find(h=>"text"in h))==null?void 0:f.text)??"");const u=[];a&&u.push(...a.map(h=>({type:"tool_call_chunk",id:h.id,name:h.functionCall.name,args:JSON.stringify(h.functionCall.args)})));const l=a==null?void 0:a.reduce((h,m)=>("thoughtSignature"in m&&typeof m.thoughtSignature=="string"&&(h[m.id]=m.thoughtSignature),h),{});return new qn({text:c,message:new Qe({content:i||"",name:r?r.role:void 0,tool_call_chunks:u,additional_kwargs:{[iy]:l},response_metadata:{model_provider:"google-genai"},usage_metadata:e.usageMetadata}),generationInfo:s})}function fH(t){return t.every(e=>"functionDeclarations"in e&&Array.isArray(e.functionDeclarations))?t:[{functionDeclarations:t.map(e=>{if(vs(e)){const n=Gm(e.schema);return n.type==="object"&&"properties"in n&&Object.keys(n.properties).length===0?{name:e.name,description:e.description}:(vi(n,e.name),{name:e.name,description:e.description,parameters:n})}if(Gi(e)){const n=nH(e.function.parameters);return vi(n,e.function.name),{name:e.function.name,description:e.function.description??"A function available to call.",parameters:n}}return e})}]}function Nv(t,e){const n={input_tokens:(t==null?void 0:t.promptTokenCount)??0,output_tokens:(t==null?void 0:t.candidatesTokenCount)??0,total_tokens:(t==null?void 0:t.totalTokenCount)??0};if(t!=null&&t.cachedContentTokenCount&&(n.input_token_details??(n.input_token_details={}),n.input_token_details.cache_read=t.cachedContentTokenCount),e==="gemini-3-pro-preview"){const r=Math.max(0,(t==null?void 0:t.promptTokenCount)??-2e5),s=Math.max(0,(t==null?void 0:t.cachedContentTokenCount)??-2e5);r&&(n.input_token_details={...n.input_token_details,over_200k:r}),s&&(n.input_token_details={...n.input_token_details,cache_read_over_200k:s})}return n}var pH=class extends qi{constructor(e){super(e);p(this,"lc_namespace",["langchain","google_genai","output_parsers"]);p(this,"returnId",!1);p(this,"keyName");p(this,"returnSingle",!1);p(this,"zodSchema");p(this,"serializableSchema");this.keyName=e.keyName,this.returnSingle=e.returnSingle??this.returnSingle,this.zodSchema=e.zodSchema,this.serializableSchema=e.serializableSchema}static lc_name(){return"GoogleGenerativeAIToolsOutputParser"}async _validateResult(e){if(this.serializableSchema!==void 0){const r=await this.serializableSchema["~standard"].validate(e);if(r.issues)throw new ln(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(r.issues)}`,JSON.stringify(e,null,2));return r.value}if(this.zodSchema===void 0)return e;const n=await Xd(this.zodSchema,e);if(n.success)return n.data;throw new ln(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(n.error.issues)}`,JSON.stringify(e,null,2))}async parseResult(e){const n=e.flatMap(s=>{const{message:a}=s;return!("tool_calls"in a)||!Array.isArray(a.tool_calls)?[]:a.tool_calls});if(n[0]===void 0)throw new Error("No parseable tool calls provided to GoogleGenerativeAIToolsOutputParser.");const[r]=n;return await this._validateResult(r.args)}},Pv;(function(t){t.STRING="string",t.NUMBER="number",t.INTEGER="integer",t.BOOLEAN="boolean",t.ARRAY="array",t.OBJECT="object"})(Pv||(Pv={}));/**
342
- * @license
343
- * Copyright 2024 Google LLC
344
- *
345
- * Licensed under the Apache License, Version 2.0 (the "License");
346
- * you may not use this file except in compliance with the License.
347
- * You may obtain a copy of the License at
348
- *
349
- * http://www.apache.org/licenses/LICENSE-2.0
350
- *
351
- * Unless required by applicable law or agreed to in writing, software
352
- * distributed under the License is distributed on an "AS IS" BASIS,
353
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
354
- * See the License for the specific language governing permissions and
355
- * limitations under the License.
356
- */var Mv;(function(t){t.LANGUAGE_UNSPECIFIED="language_unspecified",t.PYTHON="python"})(Mv||(Mv={}));var Lv;(function(t){t.OUTCOME_UNSPECIFIED="outcome_unspecified",t.OUTCOME_OK="outcome_ok",t.OUTCOME_FAILED="outcome_failed",t.OUTCOME_DEADLINE_EXCEEDED="outcome_deadline_exceeded"})(Lv||(Lv={}));/**
357
- * @license
358
- * Copyright 2024 Google LLC
359
- *
360
- * Licensed under the Apache License, Version 2.0 (the "License");
361
- * you may not use this file except in compliance with the License.
362
- * You may obtain a copy of the License at
363
- *
364
- * http://www.apache.org/licenses/LICENSE-2.0
365
- *
366
- * Unless required by applicable law or agreed to in writing, software
367
- * distributed under the License is distributed on an "AS IS" BASIS,
368
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
369
- * See the License for the specific language governing permissions and
370
- * limitations under the License.
371
- */const jv=["user","model","function","system"];var Uv;(function(t){t.HARM_CATEGORY_UNSPECIFIED="HARM_CATEGORY_UNSPECIFIED",t.HARM_CATEGORY_HATE_SPEECH="HARM_CATEGORY_HATE_SPEECH",t.HARM_CATEGORY_SEXUALLY_EXPLICIT="HARM_CATEGORY_SEXUALLY_EXPLICIT",t.HARM_CATEGORY_HARASSMENT="HARM_CATEGORY_HARASSMENT",t.HARM_CATEGORY_DANGEROUS_CONTENT="HARM_CATEGORY_DANGEROUS_CONTENT",t.HARM_CATEGORY_CIVIC_INTEGRITY="HARM_CATEGORY_CIVIC_INTEGRITY"})(Uv||(Uv={}));var Dv;(function(t){t.HARM_BLOCK_THRESHOLD_UNSPECIFIED="HARM_BLOCK_THRESHOLD_UNSPECIFIED",t.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",t.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",t.BLOCK_ONLY_HIGH="BLOCK_ONLY_HIGH",t.BLOCK_NONE="BLOCK_NONE"})(Dv||(Dv={}));var Fv;(function(t){t.HARM_PROBABILITY_UNSPECIFIED="HARM_PROBABILITY_UNSPECIFIED",t.NEGLIGIBLE="NEGLIGIBLE",t.LOW="LOW",t.MEDIUM="MEDIUM",t.HIGH="HIGH"})(Fv||(Fv={}));var Bv;(function(t){t.BLOCKED_REASON_UNSPECIFIED="BLOCKED_REASON_UNSPECIFIED",t.SAFETY="SAFETY",t.OTHER="OTHER"})(Bv||(Bv={}));var ac;(function(t){t.FINISH_REASON_UNSPECIFIED="FINISH_REASON_UNSPECIFIED",t.STOP="STOP",t.MAX_TOKENS="MAX_TOKENS",t.SAFETY="SAFETY",t.RECITATION="RECITATION",t.LANGUAGE="LANGUAGE",t.BLOCKLIST="BLOCKLIST",t.PROHIBITED_CONTENT="PROHIBITED_CONTENT",t.SPII="SPII",t.MALFORMED_FUNCTION_CALL="MALFORMED_FUNCTION_CALL",t.OTHER="OTHER"})(ac||(ac={}));var zv;(function(t){t.TASK_TYPE_UNSPECIFIED="TASK_TYPE_UNSPECIFIED",t.RETRIEVAL_QUERY="RETRIEVAL_QUERY",t.RETRIEVAL_DOCUMENT="RETRIEVAL_DOCUMENT",t.SEMANTIC_SIMILARITY="SEMANTIC_SIMILARITY",t.CLASSIFICATION="CLASSIFICATION",t.CLUSTERING="CLUSTERING"})(zv||(zv={}));var Si;(function(t){t.MODE_UNSPECIFIED="MODE_UNSPECIFIED",t.AUTO="AUTO",t.ANY="ANY",t.NONE="NONE"})(Si||(Si={}));var Hv;(function(t){t.MODE_UNSPECIFIED="MODE_UNSPECIFIED",t.MODE_DYNAMIC="MODE_DYNAMIC"})(Hv||(Hv={}));/**
372
- * @license
373
- * Copyright 2024 Google LLC
374
- *
375
- * Licensed under the Apache License, Version 2.0 (the "License");
376
- * you may not use this file except in compliance with the License.
377
- * You may obtain a copy of the License at
378
- *
379
- * http://www.apache.org/licenses/LICENSE-2.0
380
- *
381
- * Unless required by applicable law or agreed to in writing, software
382
- * distributed under the License is distributed on an "AS IS" BASIS,
383
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
384
- * See the License for the specific language governing permissions and
385
- * limitations under the License.
386
- */class on extends Error{constructor(e){super(`[GoogleGenerativeAI Error]: ${e}`)}}class Ya extends on{constructor(e,n){super(e),this.response=n}}class $k extends on{constructor(e,n,r,s){super(e),this.status=n,this.statusText=r,this.errorDetails=s}}class Gs extends on{}class Nk extends on{}/**
387
- * @license
388
- * Copyright 2024 Google LLC
389
- *
390
- * Licensed under the Apache License, Version 2.0 (the "License");
391
- * you may not use this file except in compliance with the License.
392
- * You may obtain a copy of the License at
393
- *
394
- * http://www.apache.org/licenses/LICENSE-2.0
395
- *
396
- * Unless required by applicable law or agreed to in writing, software
397
- * distributed under the License is distributed on an "AS IS" BASIS,
398
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
399
- * See the License for the specific language governing permissions and
400
- * limitations under the License.
401
- */const mH="https://generativelanguage.googleapis.com",gH="v1beta",_H="0.24.1",yH="genai-js";var Fa;(function(t){t.GENERATE_CONTENT="generateContent",t.STREAM_GENERATE_CONTENT="streamGenerateContent",t.COUNT_TOKENS="countTokens",t.EMBED_CONTENT="embedContent",t.BATCH_EMBED_CONTENTS="batchEmbedContents"})(Fa||(Fa={}));class wH{constructor(e,n,r,s,a){this.model=e,this.task=n,this.apiKey=r,this.stream=s,this.requestOptions=a}toString(){var e,n;const r=((e=this.requestOptions)===null||e===void 0?void 0:e.apiVersion)||gH;let a=`${((n=this.requestOptions)===null||n===void 0?void 0:n.baseUrl)||mH}/${r}/${this.model}:${this.task}`;return this.stream&&(a+="?alt=sse"),a}}function bH(t){const e=[];return t!=null&&t.apiClient&&e.push(t.apiClient),e.push(`${yH}/${_H}`),e.join(" ")}async function vH(t){var e;const n=new Headers;n.append("Content-Type","application/json"),n.append("x-goog-api-client",bH(t.requestOptions)),n.append("x-goog-api-key",t.apiKey);let r=(e=t.requestOptions)===null||e===void 0?void 0:e.customHeaders;if(r){if(!(r instanceof Headers))try{r=new Headers(r)}catch(s){throw new Gs(`unable to convert customHeaders value ${JSON.stringify(r)} to Headers: ${s.message}`)}for(const[s,a]of r.entries()){if(s==="x-goog-api-key")throw new Gs(`Cannot set reserved header name ${s}`);if(s==="x-goog-api-client")throw new Gs(`Header name ${s} can only be set using the apiClient field`);n.append(s,a)}}return n}async function SH(t,e,n,r,s,a){const i=new wH(t,e,n,r,a);return{url:i.toString(),fetchOptions:Object.assign(Object.assign({},IH(a)),{method:"POST",headers:await vH(i),body:s})}}async function cu(t,e,n,r,s,a={},i=fetch){const{url:o,fetchOptions:c}=await SH(t,e,n,r,s,a);return TH(o,c,i)}async function TH(t,e,n=fetch){let r;try{r=await n(t,e)}catch(s){EH(s,t)}return r.ok||await AH(r,t),r}function EH(t,e){let n=t;throw n.name==="AbortError"?(n=new Nk(`Request aborted when fetching ${e.toString()}: ${t.message}`),n.stack=t.stack):t instanceof $k||t instanceof Gs||(n=new on(`Error fetching from ${e.toString()}: ${t.message}`),n.stack=t.stack),n}async function AH(t,e){let n="",r;try{const s=await t.json();n=s.error.message,s.error.details&&(n+=` ${JSON.stringify(s.error.details)}`,r=s.error.details)}catch{}throw new $k(`Error fetching from ${e.toString()}: [${t.status} ${t.statusText}] ${n}`,t.status,t.statusText,r)}function IH(t){const e={};if((t==null?void 0:t.signal)!==void 0||(t==null?void 0:t.timeout)>=0){const n=new AbortController;(t==null?void 0:t.timeout)>=0&&setTimeout(()=>n.abort(),t.timeout),t!=null&&t.signal&&t.signal.addEventListener("abort",()=>{n.abort()}),e.signal=n.signal}return e}/**
402
- * @license
403
- * Copyright 2024 Google LLC
404
- *
405
- * Licensed under the Apache License, Version 2.0 (the "License");
406
- * you may not use this file except in compliance with the License.
407
- * You may obtain a copy of the License at
408
- *
409
- * http://www.apache.org/licenses/LICENSE-2.0
410
- *
411
- * Unless required by applicable law or agreed to in writing, software
412
- * distributed under the License is distributed on an "AS IS" BASIS,
413
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
414
- * See the License for the specific language governing permissions and
415
- * limitations under the License.
416
- */function oy(t){return t.text=()=>{if(t.candidates&&t.candidates.length>0){if(t.candidates.length>1&&console.warn(`This response had ${t.candidates.length} candidates. Returning text from the first candidate only. Access response.candidates directly to use the other candidates.`),zl(t.candidates[0]))throw new Ya(`${Ns(t)}`,t);return xH(t)}else if(t.promptFeedback)throw new Ya(`Text not available. ${Ns(t)}`,t);return""},t.functionCall=()=>{if(t.candidates&&t.candidates.length>0){if(t.candidates.length>1&&console.warn(`This response had ${t.candidates.length} candidates. Returning function calls from the first candidate only. Access response.candidates directly to use the other candidates.`),zl(t.candidates[0]))throw new Ya(`${Ns(t)}`,t);return console.warn("response.functionCall() is deprecated. Use response.functionCalls() instead."),Vv(t)[0]}else if(t.promptFeedback)throw new Ya(`Function call not available. ${Ns(t)}`,t)},t.functionCalls=()=>{if(t.candidates&&t.candidates.length>0){if(t.candidates.length>1&&console.warn(`This response had ${t.candidates.length} candidates. Returning function calls from the first candidate only. Access response.candidates directly to use the other candidates.`),zl(t.candidates[0]))throw new Ya(`${Ns(t)}`,t);return Vv(t)}else if(t.promptFeedback)throw new Ya(`Function call not available. ${Ns(t)}`,t)},t}function xH(t){var e,n,r,s;const a=[];if(!((n=(e=t.candidates)===null||e===void 0?void 0:e[0].content)===null||n===void 0)&&n.parts)for(const i of(s=(r=t.candidates)===null||r===void 0?void 0:r[0].content)===null||s===void 0?void 0:s.parts)i.text&&a.push(i.text),i.executableCode&&a.push("\n```"+i.executableCode.language+`
417
- `+i.executableCode.code+"\n```\n"),i.codeExecutionResult&&a.push("\n```\n"+i.codeExecutionResult.output+"\n```\n");return a.length>0?a.join(""):""}function Vv(t){var e,n,r,s;const a=[];if(!((n=(e=t.candidates)===null||e===void 0?void 0:e[0].content)===null||n===void 0)&&n.parts)for(const i of(s=(r=t.candidates)===null||r===void 0?void 0:r[0].content)===null||s===void 0?void 0:s.parts)i.functionCall&&a.push(i.functionCall);if(a.length>0)return a}const kH=[ac.RECITATION,ac.SAFETY,ac.LANGUAGE];function zl(t){return!!t.finishReason&&kH.includes(t.finishReason)}function Ns(t){var e,n,r;let s="";if((!t.candidates||t.candidates.length===0)&&t.promptFeedback)s+="Response was blocked",!((e=t.promptFeedback)===null||e===void 0)&&e.blockReason&&(s+=` due to ${t.promptFeedback.blockReason}`),!((n=t.promptFeedback)===null||n===void 0)&&n.blockReasonMessage&&(s+=`: ${t.promptFeedback.blockReasonMessage}`);else if(!((r=t.candidates)===null||r===void 0)&&r[0]){const a=t.candidates[0];zl(a)&&(s+=`Candidate was blocked due to ${a.finishReason}`,a.finishMessage&&(s+=`: ${a.finishMessage}`))}return s}function Nc(t){return this instanceof Nc?(this.v=t,this):new Nc(t)}function OH(t,e,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r=n.apply(t,e||[]),s,a=[];return s={},i("next"),i("throw"),i("return"),s[Symbol.asyncIterator]=function(){return this},s;function i(f){r[f]&&(s[f]=function(h){return new Promise(function(m,_){a.push([f,h,m,_])>1||o(f,h)})})}function o(f,h){try{c(r[f](h))}catch(m){d(a[0][3],m)}}function c(f){f.value instanceof Nc?Promise.resolve(f.value.v).then(u,l):d(a[0][2],f)}function u(f){o("next",f)}function l(f){o("throw",f)}function d(f,h){f(h),a.shift(),a.length&&o(a[0][0],a[0][1])}}/**
418
- * @license
419
- * Copyright 2024 Google LLC
420
- *
421
- * Licensed under the Apache License, Version 2.0 (the "License");
422
- * you may not use this file except in compliance with the License.
423
- * You may obtain a copy of the License at
424
- *
425
- * http://www.apache.org/licenses/LICENSE-2.0
426
- *
427
- * Unless required by applicable law or agreed to in writing, software
428
- * distributed under the License is distributed on an "AS IS" BASIS,
429
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
430
- * See the License for the specific language governing permissions and
431
- * limitations under the License.
432
- */const Zv=/^data\: (.*)(?:\n\n|\r\r|\r\n\r\n)/;function CH(t){const e=t.body.pipeThrough(new TextDecoderStream("utf8",{fatal:!0})),n=NH(e),[r,s]=n.tee();return{stream:$H(r),response:RH(s)}}async function RH(t){const e=[],n=t.getReader();for(;;){const{done:r,value:s}=await n.read();if(r)return oy(PH(e));e.push(s)}}function $H(t){return OH(this,arguments,function*(){const n=t.getReader();for(;;){const{value:r,done:s}=yield Nc(n.read());if(s)break;yield yield Nc(oy(r))}})}function NH(t){const e=t.getReader();return new ReadableStream({start(r){let s="";return a();function a(){return e.read().then(({value:i,done:o})=>{if(o){if(s.trim()){r.error(new on("Failed to parse stream"));return}r.close();return}s+=i;let c=s.match(Zv),u;for(;c;){try{u=JSON.parse(c[1])}catch{r.error(new on(`Error parsing JSON response: "${c[1]}"`));return}r.enqueue(u),s=s.substring(c[0].length),c=s.match(Zv)}return a()}).catch(i=>{let o=i;throw o.stack=i.stack,o.name==="AbortError"?o=new Nk("Request aborted when reading from the stream"):o=new on("Error reading from the stream"),o})}}})}function PH(t){const e=t[t.length-1],n={promptFeedback:e==null?void 0:e.promptFeedback};for(const r of t){if(r.candidates){let s=0;for(const a of r.candidates)if(n.candidates||(n.candidates=[]),n.candidates[s]||(n.candidates[s]={index:s}),n.candidates[s].citationMetadata=a.citationMetadata,n.candidates[s].groundingMetadata=a.groundingMetadata,n.candidates[s].finishReason=a.finishReason,n.candidates[s].finishMessage=a.finishMessage,n.candidates[s].safetyRatings=a.safetyRatings,a.content&&a.content.parts){n.candidates[s].content||(n.candidates[s].content={role:a.content.role||"user",parts:[]});const i={};for(const o of a.content.parts)o.text&&(i.text=o.text),o.functionCall&&(i.functionCall=o.functionCall),o.executableCode&&(i.executableCode=o.executableCode),o.codeExecutionResult&&(i.codeExecutionResult=o.codeExecutionResult),Object.keys(i).length===0&&(i.text=""),n.candidates[s].content.parts.push(i)}s++}r.usageMetadata&&(n.usageMetadata=r.usageMetadata)}return n}/**
433
- * @license
434
- * Copyright 2024 Google LLC
435
- *
436
- * Licensed under the Apache License, Version 2.0 (the "License");
437
- * you may not use this file except in compliance with the License.
438
- * You may obtain a copy of the License at
439
- *
440
- * http://www.apache.org/licenses/LICENSE-2.0
441
- *
442
- * Unless required by applicable law or agreed to in writing, software
443
- * distributed under the License is distributed on an "AS IS" BASIS,
444
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
445
- * See the License for the specific language governing permissions and
446
- * limitations under the License.
447
- */async function Pk(t,e,n,r){const s=await cu(e,Fa.STREAM_GENERATE_CONTENT,t,!0,JSON.stringify(n),r);return CH(s)}async function Mk(t,e,n,r){const a=await(await cu(e,Fa.GENERATE_CONTENT,t,!1,JSON.stringify(n),r)).json();return{response:oy(a)}}/**
448
- * @license
449
- * Copyright 2024 Google LLC
450
- *
451
- * Licensed under the Apache License, Version 2.0 (the "License");
452
- * you may not use this file except in compliance with the License.
453
- * You may obtain a copy of the License at
454
- *
455
- * http://www.apache.org/licenses/LICENSE-2.0
456
- *
457
- * Unless required by applicable law or agreed to in writing, software
458
- * distributed under the License is distributed on an "AS IS" BASIS,
459
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
460
- * See the License for the specific language governing permissions and
461
- * limitations under the License.
462
- */function Lk(t){if(t!=null){if(typeof t=="string")return{role:"system",parts:[{text:t}]};if(t.text)return{role:"system",parts:[t]};if(t.parts)return t.role?t:{role:"system",parts:t.parts}}}function Pc(t){let e=[];if(typeof t=="string")e=[{text:t}];else for(const n of t)typeof n=="string"?e.push({text:n}):e.push(n);return MH(e)}function MH(t){const e={role:"user",parts:[]},n={role:"function",parts:[]};let r=!1,s=!1;for(const a of t)"functionResponse"in a?(n.parts.push(a),s=!0):(e.parts.push(a),r=!0);if(r&&s)throw new on("Within a single message, FunctionResponse cannot be mixed with other type of part in the request for sending chat message.");if(!r&&!s)throw new on("No content is provided for sending chat message.");return r?e:n}function LH(t,e){var n;let r={model:e==null?void 0:e.model,generationConfig:e==null?void 0:e.generationConfig,safetySettings:e==null?void 0:e.safetySettings,tools:e==null?void 0:e.tools,toolConfig:e==null?void 0:e.toolConfig,systemInstruction:e==null?void 0:e.systemInstruction,cachedContent:(n=e==null?void 0:e.cachedContent)===null||n===void 0?void 0:n.name,contents:[]};const s=t.generateContentRequest!=null;if(t.contents){if(s)throw new Gs("CountTokensRequest must have one of contents or generateContentRequest, not both.");r.contents=t.contents}else if(s)r=Object.assign(Object.assign({},r),t.generateContentRequest);else{const a=Pc(t);r.contents=[a]}return{generateContentRequest:r}}function Wv(t){let e;return t.contents?e=t:e={contents:[Pc(t)]},t.systemInstruction&&(e.systemInstruction=Lk(t.systemInstruction)),e}function jH(t){return typeof t=="string"||Array.isArray(t)?{content:Pc(t)}:t}/**
463
- * @license
464
- * Copyright 2024 Google LLC
465
- *
466
- * Licensed under the Apache License, Version 2.0 (the "License");
467
- * you may not use this file except in compliance with the License.
468
- * You may obtain a copy of the License at
469
- *
470
- * http://www.apache.org/licenses/LICENSE-2.0
471
- *
472
- * Unless required by applicable law or agreed to in writing, software
473
- * distributed under the License is distributed on an "AS IS" BASIS,
474
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
475
- * See the License for the specific language governing permissions and
476
- * limitations under the License.
477
- */const Gv=["text","inlineData","functionCall","functionResponse","executableCode","codeExecutionResult"],UH={user:["text","inlineData"],function:["functionResponse"],model:["text","functionCall","executableCode","codeExecutionResult"],system:["text"]};function DH(t){let e=!1;for(const n of t){const{role:r,parts:s}=n;if(!e&&r!=="user")throw new on(`First content should be with role 'user', got ${r}`);if(!jv.includes(r))throw new on(`Each item should include role field. Got ${r} but valid roles are: ${JSON.stringify(jv)}`);if(!Array.isArray(s))throw new on("Content should have 'parts' property with an array of Parts");if(s.length===0)throw new on("Each Content should have at least one part");const a={text:0,inlineData:0,functionCall:0,functionResponse:0,fileData:0,executableCode:0,codeExecutionResult:0};for(const o of s)for(const c of Gv)c in o&&(a[c]+=1);const i=UH[r];for(const o of Gv)if(!i.includes(o)&&a[o]>0)throw new on(`Content with role '${r}' can't contain '${o}' part`);e=!0}}function qv(t){var e;if(t.candidates===void 0||t.candidates.length===0)return!1;const n=(e=t.candidates[0])===null||e===void 0?void 0:e.content;if(n===void 0||n.parts===void 0||n.parts.length===0)return!1;for(const r of n.parts)if(r===void 0||Object.keys(r).length===0||r.text!==void 0&&r.text==="")return!1;return!0}/**
478
- * @license
479
- * Copyright 2024 Google LLC
480
- *
481
- * Licensed under the Apache License, Version 2.0 (the "License");
482
- * you may not use this file except in compliance with the License.
483
- * You may obtain a copy of the License at
484
- *
485
- * http://www.apache.org/licenses/LICENSE-2.0
486
- *
487
- * Unless required by applicable law or agreed to in writing, software
488
- * distributed under the License is distributed on an "AS IS" BASIS,
489
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
490
- * See the License for the specific language governing permissions and
491
- * limitations under the License.
492
- */const Kv="SILENT_ERROR";class FH{constructor(e,n,r,s={}){this.model=n,this.params=r,this._requestOptions=s,this._history=[],this._sendPromise=Promise.resolve(),this._apiKey=e,r!=null&&r.history&&(DH(r.history),this._history=r.history)}async getHistory(){return await this._sendPromise,this._history}async sendMessage(e,n={}){var r,s,a,i,o,c;await this._sendPromise;const u=Pc(e),l={safetySettings:(r=this.params)===null||r===void 0?void 0:r.safetySettings,generationConfig:(s=this.params)===null||s===void 0?void 0:s.generationConfig,tools:(a=this.params)===null||a===void 0?void 0:a.tools,toolConfig:(i=this.params)===null||i===void 0?void 0:i.toolConfig,systemInstruction:(o=this.params)===null||o===void 0?void 0:o.systemInstruction,cachedContent:(c=this.params)===null||c===void 0?void 0:c.cachedContent,contents:[...this._history,u]},d=Object.assign(Object.assign({},this._requestOptions),n);let f;return this._sendPromise=this._sendPromise.then(()=>Mk(this._apiKey,this.model,l,d)).then(h=>{var m;if(qv(h.response)){this._history.push(u);const _=Object.assign({parts:[],role:"model"},(m=h.response.candidates)===null||m===void 0?void 0:m[0].content);this._history.push(_)}else{const _=Ns(h.response);_&&console.warn(`sendMessage() was unsuccessful. ${_}. Inspect response object for details.`)}f=h}).catch(h=>{throw this._sendPromise=Promise.resolve(),h}),await this._sendPromise,f}async sendMessageStream(e,n={}){var r,s,a,i,o,c;await this._sendPromise;const u=Pc(e),l={safetySettings:(r=this.params)===null||r===void 0?void 0:r.safetySettings,generationConfig:(s=this.params)===null||s===void 0?void 0:s.generationConfig,tools:(a=this.params)===null||a===void 0?void 0:a.tools,toolConfig:(i=this.params)===null||i===void 0?void 0:i.toolConfig,systemInstruction:(o=this.params)===null||o===void 0?void 0:o.systemInstruction,cachedContent:(c=this.params)===null||c===void 0?void 0:c.cachedContent,contents:[...this._history,u]},d=Object.assign(Object.assign({},this._requestOptions),n),f=Pk(this._apiKey,this.model,l,d);return this._sendPromise=this._sendPromise.then(()=>f).catch(h=>{throw new Error(Kv)}).then(h=>h.response).then(h=>{if(qv(h)){this._history.push(u);const m=Object.assign({},h.candidates[0].content);m.role||(m.role="model"),this._history.push(m)}else{const m=Ns(h);m&&console.warn(`sendMessageStream() was unsuccessful. ${m}. Inspect response object for details.`)}}).catch(h=>{h.message!==Kv&&console.error(h)}),f}}/**
493
- * @license
494
- * Copyright 2024 Google LLC
495
- *
496
- * Licensed under the Apache License, Version 2.0 (the "License");
497
- * you may not use this file except in compliance with the License.
498
- * You may obtain a copy of the License at
499
- *
500
- * http://www.apache.org/licenses/LICENSE-2.0
501
- *
502
- * Unless required by applicable law or agreed to in writing, software
503
- * distributed under the License is distributed on an "AS IS" BASIS,
504
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
505
- * See the License for the specific language governing permissions and
506
- * limitations under the License.
507
- */async function BH(t,e,n,r){return(await cu(e,Fa.COUNT_TOKENS,t,!1,JSON.stringify(n),r)).json()}/**
508
- * @license
509
- * Copyright 2024 Google LLC
510
- *
511
- * Licensed under the Apache License, Version 2.0 (the "License");
512
- * you may not use this file except in compliance with the License.
513
- * You may obtain a copy of the License at
514
- *
515
- * http://www.apache.org/licenses/LICENSE-2.0
516
- *
517
- * Unless required by applicable law or agreed to in writing, software
518
- * distributed under the License is distributed on an "AS IS" BASIS,
519
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
520
- * See the License for the specific language governing permissions and
521
- * limitations under the License.
522
- */async function zH(t,e,n,r){return(await cu(e,Fa.EMBED_CONTENT,t,!1,JSON.stringify(n),r)).json()}async function HH(t,e,n,r){const s=n.requests.map(i=>Object.assign(Object.assign({},i),{model:e}));return(await cu(e,Fa.BATCH_EMBED_CONTENTS,t,!1,JSON.stringify({requests:s}),r)).json()}/**
523
- * @license
524
- * Copyright 2024 Google LLC
525
- *
526
- * Licensed under the Apache License, Version 2.0 (the "License");
527
- * you may not use this file except in compliance with the License.
528
- * You may obtain a copy of the License at
529
- *
530
- * http://www.apache.org/licenses/LICENSE-2.0
531
- *
532
- * Unless required by applicable law or agreed to in writing, software
533
- * distributed under the License is distributed on an "AS IS" BASIS,
534
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
535
- * See the License for the specific language governing permissions and
536
- * limitations under the License.
537
- */class Jv{constructor(e,n,r={}){this.apiKey=e,this._requestOptions=r,n.model.includes("/")?this.model=n.model:this.model=`models/${n.model}`,this.generationConfig=n.generationConfig||{},this.safetySettings=n.safetySettings||[],this.tools=n.tools,this.toolConfig=n.toolConfig,this.systemInstruction=Lk(n.systemInstruction),this.cachedContent=n.cachedContent}async generateContent(e,n={}){var r;const s=Wv(e),a=Object.assign(Object.assign({},this._requestOptions),n);return Mk(this.apiKey,this.model,Object.assign({generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:(r=this.cachedContent)===null||r===void 0?void 0:r.name},s),a)}async generateContentStream(e,n={}){var r;const s=Wv(e),a=Object.assign(Object.assign({},this._requestOptions),n);return Pk(this.apiKey,this.model,Object.assign({generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:(r=this.cachedContent)===null||r===void 0?void 0:r.name},s),a)}startChat(e){var n;return new FH(this.apiKey,this.model,Object.assign({generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:(n=this.cachedContent)===null||n===void 0?void 0:n.name},e),this._requestOptions)}async countTokens(e,n={}){const r=LH(e,{model:this.model,generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:this.cachedContent}),s=Object.assign(Object.assign({},this._requestOptions),n);return BH(this.apiKey,this.model,r,s)}async embedContent(e,n={}){const r=jH(e),s=Object.assign(Object.assign({},this._requestOptions),n);return zH(this.apiKey,this.model,r,s)}async batchEmbedContents(e,n={}){const r=Object.assign(Object.assign({},this._requestOptions),n);return HH(this.apiKey,this.model,e,r)}}/**
538
- * @license
539
- * Copyright 2024 Google LLC
540
- *
541
- * Licensed under the Apache License, Version 2.0 (the "License");
542
- * you may not use this file except in compliance with the License.
543
- * You may obtain a copy of the License at
544
- *
545
- * http://www.apache.org/licenses/LICENSE-2.0
546
- *
547
- * Unless required by applicable law or agreed to in writing, software
548
- * distributed under the License is distributed on an "AS IS" BASIS,
549
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
550
- * See the License for the specific language governing permissions and
551
- * limitations under the License.
552
- */class Xv{constructor(e){this.apiKey=e}getGenerativeModel(e,n){if(!e.model)throw new on("Must provide a model name. Example: genai.getGenerativeModel({ model: 'my-model-name' })");return new Jv(this.apiKey,e,n)}getGenerativeModelFromCachedContent(e,n,r){if(!e.name)throw new Gs("Cached content must contain a `name` field.");if(!e.model)throw new Gs("Cached content must contain a `model` field.");const s=["model","systemInstruction"];for(const i of s)if(n!=null&&n[i]&&e[i]&&(n==null?void 0:n[i])!==e[i]){if(i==="model"){const o=n.model.startsWith("models/")?n.model.replace("models/",""):n.model,c=e.model.startsWith("models/")?e.model.replace("models/",""):e.model;if(o===c)continue}throw new Gs(`Different value for "${i}" specified in modelParams (${n[i]}) and cachedContent (${e[i]})`)}const a=Object.assign(Object.assign({},n),{model:e.model,tools:e.tools,toolConfig:e.toolConfig,systemInstruction:e.systemInstruction,cachedContent:e});return new Jv(this.apiKey,a,r)}}function Yv(t,e){const n=VH(t);return{tools:n,toolConfig:WH(n,e)}}function VH(t){let e=[];const n=[];return t.forEach(r=>{if(vs(r)){const[s]=fH([r]);s.functionDeclarations&&e.push(...s.functionDeclarations)}else if(Gi(r)){const{functionDeclarations:s}=ZH(r);if(s)e.push(...s);else throw new Error("Failed to convert OpenAI structured tool to GenerativeAI tool")}else n.push(r)}),n.find(r=>"functionDeclarations"in r)?n.map(r=>{if((e==null?void 0:e.length)>0&&"functionDeclarations"in r){const s={functionDeclarations:[...r.functionDeclarations||[],...e]};return e=[],s}return r}):[...n,...e.length>0?[{functionDeclarations:e}]:[]]}function ZH(t){return{functionDeclarations:[{name:t.function.name,description:t.function.description,parameters:Da(t.function.parameters)}]}}function WH(t,e){if(!t.length||!e)return;const{toolChoice:n,allowedFunctionNames:r}=e,s={any:Si.ANY,auto:Si.AUTO,none:Si.NONE};if(n&&["any","auto","none"].includes(n))return{functionCallingConfig:{mode:s[n]??"MODE_UNSPECIFIED",allowedFunctionNames:r}};if(typeof n=="string"||r)return{functionCallingConfig:{mode:Si.ANY,allowedFunctionNames:[...r??[],...n&&typeof n=="string"?[n]:[]]}}}const GH={"gemini-embedding-001":{maxInputTokens:2048,imageInputs:!1,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:3072,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!1},"gemini-2.5-flash-lite-preview-09-2025":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-2.5-pro-preview-06-05":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-2.5-flash-preview-04-17":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1},"gemini-2.5-flash-preview-09-2025":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-2.5-pro-preview-05-06":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-2.5-flash-preview-05-20":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-2.5-flash":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-live-2.5-flash":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!0,pdfInputs:!1,videoInputs:!0,maxOutputTokens:8e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!0,videoOutputs:!1,toolCalling:!0,structuredOutput:!1},"gemini-3-flash-preview":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-live-2.5-flash-preview-native-audio":{maxInputTokens:131072,imageInputs:!1,audioInputs:!0,pdfInputs:!1,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!0,videoOutputs:!1,toolCalling:!0,structuredOutput:!1},"gemini-2.5-flash-lite":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-2.5-flash-preview-tts":{maxInputTokens:8e3,imageInputs:!1,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:16e3,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!0,videoOutputs:!1,toolCalling:!1,structuredOutput:!1},"gemini-flash-latest":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-2.5-flash-lite-preview-06-17":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1},"gemini-2.5-flash-image":{maxInputTokens:32768,imageInputs:!0,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!0,imageOutputs:!0,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!1},"gemini-2.5-pro-preview-tts":{maxInputTokens:8e3,imageInputs:!1,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:16e3,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!0,videoOutputs:!1,toolCalling:!1,structuredOutput:!1},"gemini-2.5-flash-image-preview":{maxInputTokens:32768,imageInputs:!0,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!0,imageOutputs:!0,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!1},"gemini-1.5-flash-8b":{maxInputTokens:1e6,imageInputs:!0,audioInputs:!0,pdfInputs:!1,videoInputs:!0,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1},"gemini-3-pro-preview":{maxInputTokens:1e6,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:64e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-2.0-flash-lite":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-1.5-flash":{maxInputTokens:1e6,imageInputs:!0,audioInputs:!0,pdfInputs:!1,videoInputs:!0,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1},"gemini-flash-lite-latest":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-2.5-pro":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-2.0-flash":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-1.5-pro":{maxInputTokens:1e6,imageInputs:!0,audioInputs:!0,pdfInputs:!1,videoInputs:!0,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1}};var qH=class extends Jr{constructor(e,n){const r=typeof e=="string"?{...n??{},model:e}:e;super(r);p(this,"lc_serializable",!0);p(this,"lc_namespace",["langchain","chat_models","google_genai"]);p(this,"model");p(this,"temperature");p(this,"maxOutputTokens");p(this,"topP");p(this,"topK");p(this,"stopSequences",[]);p(this,"safetySettings");p(this,"apiKey");p(this,"streaming",!1);p(this,"json");p(this,"streamUsage",!0);p(this,"convertSystemMessageToHumanContent");p(this,"thinkingConfig");p(this,"client");if(this._addVersion("@langchain/google-genai","2.1.29"),this.model=r.model.replace(/^models\//,""),this.maxOutputTokens=r.maxOutputTokens??this.maxOutputTokens,this.maxOutputTokens&&this.maxOutputTokens<0)throw new Error("`maxOutputTokens` must be a positive integer");if(this.temperature=r.temperature??this.temperature,this.temperature&&(this.temperature<0||this.temperature>2))throw new Error("`temperature` must be in the range of [0.0,2.0]");if(this.topP=r.topP??this.topP,this.topP&&this.topP<0)throw new Error("`topP` must be a positive integer");if(this.topP&&this.topP>1)throw new Error("`topP` must be below 1.");if(this.topK=r.topK??this.topK,this.topK&&this.topK<0)throw new Error("`topK` must be a positive integer");if(this.stopSequences=r.stopSequences??this.stopSequences,this.apiKey=r.apiKey??It("GOOGLE_API_KEY"),!this.apiKey)throw new Error("Please set an API key for Google GenerativeAI in the environment variable GOOGLE_API_KEY or in the `apiKey` field of the ChatGoogleGenerativeAI constructor");if(this.safetySettings=r.safetySettings??this.safetySettings,this.safetySettings&&this.safetySettings.length>0&&new Set(this.safetySettings.map(s=>s.category)).size!==this.safetySettings.length)throw new Error("The categories in `safetySettings` array must be unique");this.streaming=r.streaming??this.streaming,this.json=r.json,this.thinkingConfig=r.thinkingConfig??this.thinkingConfig,this.client=new Xv(this.apiKey).getGenerativeModel({model:this.model,safetySettings:this.safetySettings,generationConfig:{stopSequences:this.stopSequences,maxOutputTokens:this.maxOutputTokens,temperature:this.temperature,topP:this.topP,topK:this.topK,...this.json?{responseMimeType:"application/json"}:{},...this.thinkingConfig?{thinkingConfig:this.thinkingConfig}:{}}},{apiVersion:r.apiVersion,baseUrl:r.baseUrl,customHeaders:r.customHeaders}),this.streamUsage=r.streamUsage??this.streamUsage}static lc_name(){return"ChatGoogleGenerativeAI"}get lc_secrets(){return{apiKey:"GOOGLE_API_KEY"}}get lc_aliases(){return{apiKey:"google_api_key"}}get _isMultimodalModel(){return this.model.includes("vision")||this.model.startsWith("gemini-1.5")||this.model.startsWith("gemini-2")||this.model.startsWith("gemma-3-")&&!this.model.startsWith("gemma-3-1b")||this.model.startsWith("gemini-3")}useCachedContent(e,n,r){this.apiKey&&(this.client=new Xv(this.apiKey).getGenerativeModelFromCachedContent(e,n,r))}get useSystemInstruction(){return typeof this.convertSystemMessageToHumanContent=="boolean"?!this.convertSystemMessageToHumanContent:this.computeUseSystemInstruction}get computeUseSystemInstruction(){return this.model==="gemini-1.0-pro-001"||this.model.startsWith("gemini-pro-vision")||this.model.startsWith("gemini-1.0-pro-vision")?!1:this.model!=="gemini-pro"}getLsParams(e){return{ls_provider:"google_genai",ls_model_name:this.model,ls_model_type:"chat",ls_temperature:this.client.generationConfig.temperature,ls_max_tokens:this.client.generationConfig.maxOutputTokens,ls_stop:e.stop}}_combineLLMOutput(){return[]}_llmType(){return"googlegenerativeai"}bindTools(e,n){var r;return this.withConfig({tools:(r=Yv(e))==null?void 0:r.tools,...n})}invocationParams(e){var r;const n=(r=e==null?void 0:e.tools)!=null&&r.length?Yv(e.tools,{toolChoice:e.tool_choice,allowedFunctionNames:e.allowedFunctionNames}):void 0;return e!=null&&e.responseSchema?(this.client.generationConfig.responseSchema=e.responseSchema,this.client.generationConfig.responseMimeType="application/json"):(this.client.generationConfig.responseSchema=void 0,this.client.generationConfig.responseMimeType=this.json?"application/json":void 0),{...n!=null&&n.tools?{tools:n.tools}:{},...n!=null&&n.toolConfig?{toolConfig:n.toolConfig}:{}}}async _generate(e,n,r){var l,d,f,h;(l=n.signal)==null||l.throwIfAborted();const s=$v(e,this._isMultimodalModel,this.useSystemInstruction,this.model);let a=s;if(s[0].role==="system"){const[m]=s;this.client.systemInstruction=m,a=s.slice(1)}const i=this.invocationParams(n);if(this.streaming){const m={},_=this._streamResponseChunks(e,n,r),y=[];for await(const w of _){const g=((d=w.generationInfo)==null?void 0:d.completion)??0;y[g]===void 0?y[g]=w:y[g]=y[g].concat(w)}return{generations:y.filter(w=>w!==void 0),llmOutput:{estimatedTokenUsage:m}}}const o=await this.completionWithRetry({...i,contents:a});let c;"usageMetadata"in o.response&&(c=Nv(o.response.usageMetadata,this.model));const u=dH(o.response,{usageMetadata:c});return((f=u.generations)==null?void 0:f.length)>0&&await(r==null?void 0:r.handleLLMNewToken(((h=u.generations[0])==null?void 0:h.text)??"")),u}async*_streamResponseChunks(e,n,r){var f;const s=$v(e,this._isMultimodalModel,this.useSystemInstruction,this.model);let a=s;if(s[0].role==="system"){const[h]=s;this.client.systemInstruction=h,a=s.slice(1)}const i={...this.invocationParams(n),contents:a},o=await this.caller.callWithOptions({signal:n==null?void 0:n.signal},async()=>{const{stream:h}=await this.client.generateContentStream(i,{signal:n==null?void 0:n.signal});return h});let c,u=0,l=0,d=0;for await(const h of o){if((f=n.signal)!=null&&f.aborted)return;if("usageMetadata"in h&&h.usageMetadata!==void 0&&this.streamUsage!==!1&&n.streamUsage!==!1){c=Nv(h.usageMetadata,this.model);const _=h.usageMetadata.promptTokenCount??0;c.input_tokens=Math.max(0,_-u),u=_;const y=h.usageMetadata.candidatesTokenCount??0;c.output_tokens=Math.max(0,y-l),l=y;const w=h.usageMetadata.totalTokenCount??0;c.total_tokens=Math.max(0,w-d),d=w}const m=hH(h,{usageMetadata:c});m&&(yield m,await(r==null?void 0:r.handleLLMNewToken(m.text??"")))}}async completionWithRetry(e,n){return this.caller.callWithOptions({signal:n==null?void 0:n.signal},async()=>{var r;try{return await this.client.generateContent(e,{signal:n==null?void 0:n.signal})}catch(s){throw(r=s.message)!=null&&r.includes("400 Bad Request")&&(s.status=400),s}})}get profile(){return GH[this.model]??{}}withStructuredOutput(e,n){const r=e,s=n==null?void 0:n.name,a=n==null?void 0:n.method,i=n==null?void 0:n.includeRaw;if(a==="jsonMode")throw new Error('ChatGoogleGenerativeAI only supports "jsonSchema" or "functionCalling" as a method.');let o,c;if(a==="functionCalling"){let u=s??"extract",l;if(Lt(r)||cr(r)){const f=Gm(r);l={name:u,description:f.description??"A function available to call.",parameters:f}}else typeof r.name=="string"&&typeof r.parameters=="object"&&r.parameters!=null?(l=r,l.parameters=Da(r.parameters),u=r.name):l={name:u,description:r.description??"",parameters:Da(r)};const d=[{functionDeclarations:[l]}];o=this.bindTools(d).withConfig({allowedFunctionNames:[u]}),c=Yc(r,u,pH)}else{const u=Gm(r);o=this.withConfig({responseSchema:u}),c=Fi(r)}return Ji(o,c,i,i?"StructuredOutputRunnable":"ChatGoogleGenerativeAIStructuredOutput")}},KH=class extends qi{constructor(e){super(e);p(this,"lc_namespace",["langchain","anthropic","output_parsers"]);p(this,"returnId",!1);p(this,"keyName");p(this,"returnSingle",!1);p(this,"zodSchema");p(this,"serializableSchema");this.keyName=e.keyName,this.returnSingle=e.returnSingle??this.returnSingle,this.zodSchema=e.zodSchema,this.serializableSchema=e.serializableSchema}static lc_name(){return"AnthropicToolsOutputParser"}async _validateResult(e){let n=e;if(typeof e=="string")try{n=JSON.parse(e)}catch(s){throw new ln(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(s.message)}`,e)}else n=e;if(this.serializableSchema!==void 0){const s=await this.serializableSchema["~standard"].validate(n);if(s.issues)throw new ln(`Failed to parse. Text: "${JSON.stringify(n,null,2)}". Error: ${JSON.stringify(s.issues)}`,JSON.stringify(n,null,2));return s.value}if(this.zodSchema===void 0)return n;const r=await Xd(this.zodSchema,n);if(r.success)return r.data;throw new ln(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(r.error.issues)}`,JSON.stringify(n,null,2))}async parseResult(e){const n=e.flatMap(s=>{const{message:a}=s;return Array.isArray(a.content)?jk(a.content)[0]:[]});if(n[0]===void 0)throw new Error("No parseable tool calls provided to AnthropicToolsOutputParser.");const[r]=n;return await this._validateResult(r.args)}};function jk(t){const e=[];for(const n of t)n.type==="tool_use"&&e.push({name:n.name,args:n.input,id:n.id,type:"tool_call"});return e}function JH(t){if(t)return t==="any"||t==="required"?{type:"any"}:t==="auto"?{type:"auto"}:t==="none"?{type:"none"}:typeof t=="string"?{type:"tool",name:t}:t}const XH=Oe({cache_control:gm().optional().nullable(),defer_loading:mB().optional(),input_examples:La(yd()).optional(),allowed_callers:La(yd()).optional()}),Qv={tool_search_tool_regex_20251119:"advanced-tool-use-2025-11-20",tool_search_tool_bm25_20251119:"advanced-tool-use-2025-11-20",memory_20250818:"context-management-2025-06-27",web_fetch_20250910:"web-fetch-2025-09-10",code_execution_20250825:"code-execution-2025-08-25",computer_20251124:"computer-use-2025-11-24",computer_20250124:"computer-use-2025-01-24",mcp_toolset:"mcp-client-2025-11-20"};function YH(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="thinking"}function QH(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="redacted_thinking"}function Uk(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="compaction"}function eV(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="search_result"}function tV(t){return typeof t!="object"||t==null||!("type"in t)||t.type!=="image"||!("source"in t)||typeof t.source!="object"||t.source==null||!("type"in t.source)?!1:t.source.type==="base64"?!(!("media_type"in t.source)||typeof t.source.media_type!="string"||!("data"in t.source)||typeof t.source.data!="string"):t.source.type==="url"?!(!("url"in t.source)||typeof t.source.url!="string"):!1}const nV={providerName:"anthropic",fromStandardTextBlock(t){return{type:"text",text:t.text,..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}}},fromStandardImageBlock(t){if(t.source_type==="url"){const e=Ir({dataUrl:t.url,asTypedArray:!1});return e?{type:"image",source:{type:"base64",data:e.data,media_type:e.mime_type},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}}:{type:"image",source:{type:"url",url:t.url},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}}}else{if(t.source_type==="base64")return{type:"image",source:{type:"base64",data:t.data,media_type:t.mime_type??""},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}};throw new Error(`Unsupported image source type: ${t.source_type}`)}},fromStandardFileBlock(t){const e=(t.mime_type??"").split(";")[0];if(t.source_type==="url"){if(e==="application/pdf"||e==="")return{type:"document",source:{type:"url",url:t.url},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{},..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."context"in(t.metadata??{})?{context:t.metadata.context}:{},..."title"in(t.metadata??{})?{title:t.metadata.title}:{}};throw new Error(`Unsupported file mime type for file url source: ${t.mime_type}`)}else if(t.source_type==="text"){if(e==="text/plain"||e==="")return{type:"document",source:{type:"text",data:t.text,media_type:t.mime_type??""},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{},..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."context"in(t.metadata??{})?{context:t.metadata.context}:{},..."title"in(t.metadata??{})?{title:t.metadata.title}:{}};throw new Error(`Unsupported file mime type for file text source: ${t.mime_type}`)}else if(t.source_type==="base64"){if(e==="application/pdf"||e==="")return{type:"document",source:{type:"base64",data:t.data,media_type:"application/pdf"},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{},..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."context"in(t.metadata??{})?{context:t.metadata.context}:{},..."title"in(t.metadata??{})?{title:t.metadata.title}:{}};if(["image/jpeg","image/png","image/gif","image/webp"].includes(e))return{type:"document",source:{type:"content",content:[{type:"image",source:{type:"base64",data:t.data,media_type:e}}]},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{},..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."context"in(t.metadata??{})?{context:t.metadata.context}:{},..."title"in(t.metadata??{})?{title:t.metadata.title}:{}};throw new Error(`Unsupported file mime type for file base64 source: ${t.mime_type}`)}else throw new Error(`Unsupported file source type: ${t.source_type}`)}},rV=t=>t();function sV(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="citation"}function aV(t){function*e(){for(const n of t)sV(n)&&(n.source==="char"?yield{type:"char_location",file_id:n.url??"",start_char_index:n.startIndex??0,end_char_index:n.endIndex??0,document_title:n.title??null,document_index:0,cited_text:n.citedText??""}:n.source==="page"?yield{type:"page_location",file_id:n.url??"",start_page_number:n.startIndex??0,end_page_number:n.endIndex??0,document_title:n.title??null,document_index:0,cited_text:n.citedText??""}:n.source==="block"?yield{type:"content_block_location",file_id:n.url??"",start_block_index:n.startIndex??0,end_block_index:n.endIndex??0,document_title:n.title??null,document_index:0,cited_text:n.citedText??""}:n.source==="url"?yield{type:"web_search_result_location",url:n.url??"",title:n.title??null,encrypted_index:String(n.startIndex??0),cited_text:n.citedText??""}:n.source==="search"&&(yield{type:"search_result_location",title:n.title??null,start_block_index:n.startIndex??0,end_block_index:n.endIndex??0,search_result_index:0,source:n.source??"",cited_text:n.citedText??""}))}return Array.from(e())}function uo(t){return typeof t=="string"?t:iV(t)}function iV(t){const e=[];for(let n=0,{length:r}=t;n<r;n++)e.push(String.fromCharCode(t[n]));return btoa(e.join(""))}function Jf(t){return(t??"").split(";")[0].toLowerCase()}function Go(t,e){if(t!=null&&typeof t=="object"&&e in t)return t[e]}function Qa(t,e){const n=Go(e,"cache_control");n!==void 0&&(t.cache_control=n);const r=Go(e,"citations");r!==void 0&&(t.citations=r);const s=Go(e,"context");s!==void 0&&(t.context=s);const a=Go(e,"title");return a!==void 0&&(t.title=a),t}function Xf(t,e){const n=Go(e,"cache_control");return n!==void 0&&(t.cache_control=n),t}function e0(t){return new Set(["image/jpeg","image/png","image/gif","image/webp"]).has(t)}function oV(t){const e=[],n=t.response_metadata,r="model_provider"in n&&(n==null?void 0:n.model_provider)==="anthropic";for(const s of t.contentBlocks)if(s.type==="text")s.annotations?e.push({type:"text",text:s.text,citations:aV(s.annotations)}):e.push({type:"text",text:s.text});else if(s.type==="tool_call")e.push({type:"tool_use",id:s.id??"",name:s.name,input:s.args});else if(s.type==="tool_call_chunk"){const a=rV(()=>{if(typeof s.args!="string")return s.args;try{return JSON.parse(s.args)}catch{return{}}});e.push({type:"tool_use",id:s.id??"",name:s.name??"",input:a})}else if(s.type==="reasoning"&&r)e.push({type:"thinking",thinking:s.reasoning,signature:String(s.signature)});else if(s.type==="server_tool_call"&&r)s.name==="web_search"?e.push({type:"server_tool_use",name:s.name,id:s.id??"",input:s.args}):s.name==="code_execution"&&e.push({type:"server_tool_use",name:s.name,id:s.id??"",input:s.args});else if(s.type==="server_tool_call_result"&&r)if(s.name==="web_search"&&Array.isArray(s.output.urls)){const a=s.output.urls.map(i=>({type:"web_search_result",title:"",encrypted_content:"",url:i}));e.push({type:"web_search_tool_result",tool_use_id:s.toolCallId??"",content:a})}else s.name==="code_execution"?e.push({type:"code_execution_tool_result",tool_use_id:s.toolCallId??"",content:s.output}):s.name==="mcp_tool_result"&&e.push({type:"mcp_tool_result",tool_use_id:s.toolCallId??"",content:s.output});else{if(s.type==="audio")throw new Error("Anthropic does not support audio content blocks.");if(s.type==="file"){const a=s.metadata;if(s.fileId){e.push(Qa({type:"document",source:{type:"file",file_id:s.fileId}},a));continue}if(s.url){const i=Jf(s.mimeType);if(i==="application/pdf"||i===""){e.push(Qa({type:"document",source:{type:"url",url:s.url}},a));continue}}if(s.data){const i=Jf(s.mimeType);if(i===""||i==="application/pdf")e.push(Qa({type:"document",source:{type:"base64",data:uo(s.data),media_type:"application/pdf"}},a));else if(i==="text/plain")e.push(Qa({type:"document",source:{type:"text",data:uo(s.data),media_type:"text/plain"}},a));else if(e0(i))e.push(Qa({type:"document",source:{type:"content",content:[{type:"image",source:{type:"base64",data:uo(s.data),media_type:i}}]}},a));else throw new Error(`Unsupported file mime type for Anthropic base64 source: ${i}`);continue}throw new Error("File content block must include a fileId, url, or data property.")}else if(s.type==="image"){const a=s.metadata;if(s.fileId){e.push(Xf({type:"image",source:{type:"file",file_id:s.fileId}},a));continue}if(s.url){e.push(Xf({type:"image",source:{type:"url",url:s.url}},a));continue}if(s.data){const i=Jf(s.mimeType)||"image/png";e0(i)&&e.push(Xf({type:"image",source:{type:"base64",data:uo(s.data),media_type:i}},a));continue}throw new Error("Image content block must include a fileId, url, or data property.")}else s.type==="video"||(s.type==="text-plain"?s.data&&e.push(Qa({type:"document",source:{type:"text",data:uo(s.data),media_type:"text/plain"}},s.metadata)):s.type==="non_standard"&&r&&e.push(s.value))}return e}function Yf(t){const e=Ir({dataUrl:t});if(e)return{type:"base64",media_type:e.mime_type,data:e.data};let n;try{n=new URL(t)}catch{throw new Error([`Malformed image URL: ${JSON.stringify(t)}. Content blocks of type 'image_url' must be a valid http, https, or base64-encoded data URL.`,"Example: data:image/png;base64,/9j/4AAQSk...","Example: https://example.com/image.jpg"].join(`
553
-
554
- `))}if(n.protocol==="http:"||n.protocol==="https:")return{type:"url",url:t};throw new Error([`Invalid image URL protocol: ${JSON.stringify(n.protocol)}. Anthropic only supports images as http, https, or base64-encoded data URLs on 'image_url' content blocks.`,"Example: data:image/png;base64,/9j/4AAQSk...","Example: https://example.com/image.jpg"].join(`
555
-
556
- `))}function cV(t){const e=[];for(const n of t)if(n._getType()==="tool")if(typeof n.content=="string"){const r=e[e.length-1];(r==null?void 0:r._getType())==="human"&&Array.isArray(r.content)&&"type"in r.content[0]&&r.content[0].type==="tool_result"?r.content.push({type:"tool_result",content:n.content,tool_use_id:n.tool_call_id}):e.push(new vn({content:[{type:"tool_result",content:n.content,tool_use_id:n.tool_call_id}]}))}else e.push(new vn({content:[{type:"tool_result",...n.content!=null?{content:qm(n)}:{},tool_use_id:n.tool_call_id}]}));else e.push(n);return e}function Qf(t){if(t.id===void 0)throw new Error('Anthropic requires all tool calls to have an "id".');return{type:"tool_use",id:t.id,name:t.name,input:t.args}}function*uV(t,e){const n=["bash_code_execution_tool_result","input_json_delta","server_tool_use","text_editor_code_execution_tool_result","tool_result","tool_use","web_search_result","web_search_tool_result"],r=["text","text_delta"];for(const s of t){ir(s)&&(yield jc(s,nV));const a="cache_control"in s?s.cache_control:void 0;if(s.type==="image_url"){let i;typeof s.image_url=="string"?i=Yf(s.image_url):typeof s.image_url=="object"&&s.image_url!==null&&"url"in s.image_url&&typeof s.image_url.url=="string"&&(i=Yf(s.image_url.url)),i&&(yield{type:"image",source:i,...a?{cache_control:a}:{}})}else if(tV(s))yield s;else if(s.type==="image"){let i;"url"in s&&typeof s.url=="string"?i=Yf(s.url):"data"in s&&(typeof s.data=="string"||s.data instanceof Uint8Array)?i={type:"base64",media_type:"mimeType"in s&&typeof s.mimeType=="string"?s.mimeType:"image/jpeg",data:typeof s.data=="string"?s.data:Buffer.from(s.data).toString("base64")}:"fileId"in s&&typeof s.fileId=="string"&&(i={type:"file",file_id:s.fileId}),i&&(yield{type:"image",source:i,...a?{cache_control:a}:{}})}else if(s.type==="file"){let i;"url"in s&&typeof s.url=="string"?i={type:"url",url:s.url}:"data"in s&&(typeof s.data=="string"||s.data instanceof Uint8Array)?i={type:"base64",media_type:"mimeType"in s&&typeof s.mimeType=="string"?s.mimeType:"application/pdf",data:typeof s.data=="string"?s.data:Buffer.from(s.data).toString("base64")}:"fileId"in s&&typeof s.fileId=="string"&&(i={type:"file",file_id:s.fileId}),i&&(yield{type:"document",source:i,...a?{cache_control:a}:{}})}else if(s.type==="document")yield{...s,...a?{cache_control:a}:{}};else if(YH(s))yield{type:"thinking",thinking:s.thinking,signature:s.signature,...a?{cache_control:a}:{}};else if(QH(s))yield{type:"redacted_thinking",data:s.data,...a?{cache_control:a}:{}};else if(Uk(s))yield{type:"compaction",content:s.content,...a?{cache_control:a}:{}};else if(eV(s))yield{type:"search_result",title:s.title,source:s.source,..."cache_control"in s&&s.cache_control?{cache_control:s.cache_control}:{},..."citations"in s&&s.citations?{citations:s.citations}:{},content:s.content};else if(r.find(i=>i===s.type)&&"text"in s)yield{type:"text",text:s.text,...a?{cache_control:a}:{},..."citations"in s&&s.citations?{citations:s.citations}:{}};else if(n.find(i=>i===s.type)){const i={...s};if(i.type==="input_json_delta")continue;if(i.type==="tool_use"&&typeof i.input=="string"){const o=e==null?void 0:e.find(c=>c.id===i.id);o?i.input=o.args:i.input=t.filter(c=>c.index===i.index&&c.type==="input_json_delta"&&typeof c.input=="string").reduce((c,u)=>c+u.input,i.input)}if("index"in i&&delete i.index,"input"in i&&typeof i.input=="string")try{i.input=JSON.parse(i.input)}catch{i.input={}}yield{...i,...a?{cache_control:a}:{}}}else s.type==="container_upload"&&(yield{...s,...a?{cache_control:a}:{}})}}function qm(t,e){const{content:n}=t;return typeof n=="string"?n:Array.from(uV(n,e))}function t0(t){const e=cV(t);let n;return e.length>0&&e[0]._getType()==="system"&&(n=t[0].content),{messages:lV((n!==void 0?e.slice(1):e).map(r=>{var a,i;let s;if(r._getType()==="human")s="user";else if(r._getType()==="ai")s="assistant";else if(r._getType()==="tool")s="user";else throw r._getType()==="system"?new Error("System messages are only permitted as the first passed message."):new Error(`Message type "${r.type}" is not supported.`);if(De.isInstance(r)&&((a=r.response_metadata)==null?void 0:a.output_version)==="v1")return{role:s,content:oV(r)};if(De.isInstance(r)&&((i=r.tool_calls)!=null&&i.length)){if(typeof r.content=="string")return r.content===""?{role:s,content:r.tool_calls.map(Qf)}:{role:s,content:[{type:"text",text:r.content},...r.tool_calls.map(Qf)]};{const{content:o}=r,c=qm(r,r.tool_calls),u=Array.isArray(c)?c:[{type:"text",text:c}],l=r.tool_calls.filter(d=>!o.find(f=>(f.type==="tool_use"||f.type==="input_json_delta"||f.type==="server_tool_use")&&f.id===d.id));return{role:s,content:[...u,...l.map(Qf)]}}}else return{role:s,content:qm(r,De.isInstance(r)?r.tool_calls:void 0)}})),system:n}}function n0(t,e){if(!t.messages||t.messages.length===0)return t;const n=[...t.messages],r=n.length-1,s=n[r];if(!s)return t;if(typeof s.content=="string")return n[r]={...s,content:[{type:"text",text:s.content,cache_control:e}]},{...t,messages:n};if(Array.isArray(s.content)&&s.content.length>0){const a=[...s.content],i=a.length-1;return a[i]={...a[i],cache_control:e},n[r]={...s,content:a},{...t,messages:n}}return t}function lV(t){if(!t||t.length<=1)return t;const e=[];let n=t[0];const r=a=>typeof a=="string"?[{type:"text",text:a}]:a,s=a=>a.role!=="user"||typeof a.content=="string"?!1:Array.isArray(a.content)&&a.content.every(i=>i.type==="tool_result");for(let a=1;a<t.length;a+=1){const i=t[a];s(n)&&s(i)?n={...n,content:[...r(n.content),...r(i.content)]}:(e.push(n),n=i)}return e.push(n),e}function Dk(t){return t.type==="enabled"||t.type==="adaptive"}function cy(t){return(t==null?void 0:t.startsWith("claude-opus-4-7"))??!1}function dV(t,e){const n=e&&typeof e=="object"&&"task_budget"in e&&e.task_budget!=null;return cy(t)&&n?["task-budgets-2026-03-13"]:[]}function hV(t){const{model:e,thinking:n,topK:r,topP:s,temperature:a}=t,i=cy(e);if(i&&n.type==="enabled")throw new Error('thinking.type="enabled" is not supported for claude-opus-4-7; use thinking.type="adaptive" instead');if(i&&typeof n=="object"&&n!=null&&"budget_tokens"in n)throw new Error("thinking.budget_tokens is not supported for claude-opus-4-7; use outputConfig.effort instead");if(i){if(r!==void 0)throw new Error("topK is not supported for claude-opus-4-7; omit topK/topP/temperature or use model prompting instead");if(s!==void 0&&s!==1)throw new Error("topP is not supported for claude-opus-4-7 when set to non-default values");if(a!==void 0&&a!==1)throw new Error("temperature is not supported for claude-opus-4-7 when set to non-default values")}if(Dk(n)){if(r!==void 0)throw new Error("topK is not supported when thinking is enabled");if(s!==void 0)throw new Error("topP is not supported when thinking is enabled");if(a!==void 0&&a!==1)throw new Error("temperature is not supported when thinking is enabled")}}function fV(t){const{model:e,thinking:n,topK:r,topP:s,temperature:a}=t,i={};return Dk(n)||cy(e)||(a!==void 0&&(i.temperature=a),r!==void 0&&(i.top_k=r),s!==void 0&&(i.top_p=s)),i}function pV(t,e){var r;const n={model_provider:"anthropic"};if(t.type==="message_start"){const{content:s,usage:a,...i}=t.message,o={};for(const[f,h]of Object.entries(i))h!=null&&(o[f]=h);const{input_tokens:c,output_tokens:u,...l}=a??{},d=Fk(a);return{chunk:new Qe({content:e.coerceContentToString?"":[],additional_kwargs:o,usage_metadata:e.streamUsage?d:void 0,response_metadata:{...n,usage:{...l}},id:t.message.id})}}else if(t.type==="message_delta"){const s={input_tokens:0,output_tokens:t.usage.output_tokens,total_tokens:t.usage.output_tokens},a="context_management"in t.delta?{context_management:t.delta.context_management}:void 0;return{chunk:new Qe({content:e.coerceContentToString?"":[],response_metadata:a,additional_kwargs:{...t.delta},usage_metadata:e.streamUsage?s:void 0})}}else if(t.type==="content_block_start"&&["tool_use","document","server_tool_use","web_search_tool_result"].includes(t.content_block.type)){const s=t.content_block;let a;return s.type==="tool_use"?a=[{id:s.id,index:t.index,name:s.name,args:""}]:a=[],{chunk:new Qe({content:e.coerceContentToString?"":[{index:t.index,...t.content_block,input:s.type==="server_tool_use"||s.type==="tool_use"?"":void 0}],response_metadata:n,additional_kwargs:{},tool_call_chunks:a})}}else if(t.type==="content_block_delta"&&["text_delta","citations_delta","thinking_delta","signature_delta"].includes(t.delta.type)){if(e.coerceContentToString&&"text"in t.delta)return{chunk:new Qe({content:t.delta.text})};{const s=t.delta;return"citation"in s&&(s.citations=[s.citation],delete s.citation),s.type==="thinking_delta"||s.type==="signature_delta"?{chunk:new Qe({content:[{index:t.index,...s,type:"thinking"}],response_metadata:n})}:{chunk:new Qe({content:[{index:t.index,...s,type:"text"}],response_metadata:n})}}}else{if(t.type==="content_block_delta"&&t.delta.type==="input_json_delta")return{chunk:new Qe({content:e.coerceContentToString?"":[{index:t.index,input:t.delta.partial_json,type:t.delta.type}],response_metadata:n,additional_kwargs:{},tool_call_chunks:[{index:t.index,args:t.delta.partial_json}]})};if(t.type==="content_block_start"&&t.content_block.type==="text"){const s=(r=t.content_block)==null?void 0:r.text;if(s!==void 0)return{chunk:new Qe({content:e.coerceContentToString?s:[{index:t.index,...t.content_block}],response_metadata:n,additional_kwargs:{}})}}else{if(t.type==="content_block_start"&&t.content_block.type==="redacted_thinking")return{chunk:new Qe({content:e.coerceContentToString?"":[{index:t.index,...t.content_block}],response_metadata:n})};if(t.type==="content_block_start"&&t.content_block.type==="thinking"){const s=t.content_block.thinking;return{chunk:new Qe({content:e.coerceContentToString?s:[{index:t.index,...t.content_block}],response_metadata:n})}}else{if(t.type==="content_block_start"&&Uk(t.content_block))return{chunk:new Qe({content:e.coerceContentToString?"":[{index:t.index,...t.content_block}],response_metadata:n})};if(t.type==="content_block_delta"&&t.delta.type==="compaction_delta")return{chunk:new Qe({content:e.coerceContentToString?"":[{index:t.index,...t.delta,type:"compaction"}],response_metadata:n})}}}}return null}function mV(t,e){const n={...e,model_provider:"anthropic"},r=e.usage,s=r!=null?Fk(r):void 0;return t.length===1&&t[0].type==="text"?[{text:t[0].text,message:new De({content:t[0].text,additional_kwargs:e,usage_metadata:s,response_metadata:n,id:e.id})}]:[{text:"",message:new De({content:t,additional_kwargs:e,tool_calls:jk(t),usage_metadata:s,response_metadata:n,id:e.id})}]}function Fk(t){const e=t.cache_creation_input_tokens??0,n=t.cache_read_input_tokens??0,r=t.input_tokens+e+n;return{input_tokens:r,output_tokens:t.output_tokens,total_tokens:r+t.output_tokens,input_token_details:{cache_creation:e,cache_read:n}}}function lo(t,e){return t.lc_error_code=e,t.message=`${t.message}
557
-
558
- Troubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${e}/
559
- `,t}function r0(t){let e;return t.status===400&&typeof t.message=="string"&&t.message.includes("prompt is too long")?e=lo(sg.fromError(t),"CONTEXT_OVERFLOW"):t.status===400&&t.message.includes("tool")?e=lo(t,"INVALID_TOOL_RESULTS"):t.status===401?e=lo(t,"MODEL_AUTHENTICATION"):t.status===404?e=lo(t,"MODEL_NOT_FOUND"):t.status===429?e=lo(t,"MODEL_RATE_LIMIT"):e=t,e}const gV={"claude-3-sonnet-20240229":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:4096,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-haiku-4-5":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:64e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-opus-4-5-20251101":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:64e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-3-opus-20240229":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:4096,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-3-5-haiku-20241022":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-3-5-sonnet-20241022":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-sonnet-4-6":{maxInputTokens:1e6,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:64e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-opus-4-0":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-opus-4-7":{maxInputTokens:1e6,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-3-haiku-20240307":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:4096,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-sonnet-4-5-20250929":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:64e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-3-5-haiku-latest":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-opus-4-1":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-sonnet-4-0":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:64e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-3-5-sonnet-20240620":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-opus-4-5":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:64e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-opus-4-1-20250805":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-haiku-4-5-20251001":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:64e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-sonnet-4-20250514":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:64e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-opus-4-6":{maxInputTokens:1e6,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-3-7-sonnet-20250219":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:64e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-sonnet-4-5":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:64e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-opus-4-20250514":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0}};function ee(t,e,n,r,s){if(typeof e=="function"?t!==e||!0:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return e.set(t,n),n}function C(t,e,n,r){if(n==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!r:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return n==="m"?r:n==="a"?r.call(t):r?r.value:e.get(t)}let Bk=function(){const{crypto:t}=globalThis;if(t!=null&&t.randomUUID)return Bk=t.randomUUID.bind(t),t.randomUUID();const e=new Uint8Array(1),n=t?()=>t.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,r=>(+r^n()&15>>+r/4).toString(16))};function Mc(t){return typeof t=="object"&&t!==null&&("name"in t&&t.name==="AbortError"||"message"in t&&String(t.message).includes("FetchRequestCanceledException"))}const Km=t=>{if(t instanceof Error)return t;if(typeof t=="object"&&t!==null){try{if(Object.prototype.toString.call(t)==="[object Error]"){const e=new Error(t.message,t.cause?{cause:t.cause}:{});return t.stack&&(e.stack=t.stack),t.cause&&!e.cause&&(e.cause=t.cause),t.name&&(e.name=t.name),e}}catch{}try{return new Error(JSON.stringify(t))}catch{}}return new Error(t)};class ke extends Error{}class fn extends ke{constructor(e,n,r,s,a){super(`${fn.makeMessage(e,n,r)}`),this.status=e,this.headers=s,this.requestID=s==null?void 0:s.get("request-id"),this.error=n,this.type=a??null}static makeMessage(e,n,r){const s=n!=null&&n.message?typeof n.message=="string"?n.message:JSON.stringify(n.message):n?JSON.stringify(n):r;return e&&s?`${e} ${s}`:e?`${e} status code (no body)`:s||"(no status code or body)"}static generate(e,n,r,s){var o;if(!e||!s)return new Oh({message:r,cause:Km(n)});const a=n,i=(o=a==null?void 0:a.error)==null?void 0:o.type;return e===400?new Hk(e,a,r,s,i):e===401?new Vk(e,a,r,s,i):e===403?new Zk(e,a,r,s,i):e===404?new Wk(e,a,r,s,i):e===409?new Gk(e,a,r,s,i):e===422?new qk(e,a,r,s,i):e===429?new Kk(e,a,r,s,i):e>=500?new Jk(e,a,r,s,i):new fn(e,a,r,s,i)}}class Ar extends fn{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class Oh extends fn{constructor({message:e,cause:n}){super(void 0,void 0,e||"Connection error.",void 0),n&&(this.cause=n)}}class zk extends Oh{constructor({message:e}={}){super({message:e??"Request timed out."})}}class Hk extends fn{}class Vk extends fn{}class Zk extends fn{}class Wk extends fn{}class Gk extends fn{}class qk extends fn{}class Kk extends fn{}class Jk extends fn{}const _V=/^[a-z][a-z0-9+.-]*:/i,yV=t=>_V.test(t);let Jm=t=>(Jm=Array.isArray,Jm(t)),s0=Jm;function Xm(t){return typeof t!="object"?{}:t??{}}function a0(t){if(!t)return!0;for(const e in t)return!1;return!0}function wV(t,e){return Object.prototype.hasOwnProperty.call(t,e)}const bV=(t,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new ke(`${t} must be an integer`);if(e<0)throw new ke(`${t} must be a positive integer`);return e},Xk=t=>{try{return JSON.parse(t)}catch{return}},vV=t=>new Promise(e=>setTimeout(e,t)),li="0.90.0",SV=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function TV(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}const EV=()=>{var n;const t=TV();if(t==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":li,"X-Stainless-OS":o0(Deno.build.os),"X-Stainless-Arch":i0(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:((n=Deno.version)==null?void 0:n.deno)??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":li,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(t==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":li,"X-Stainless-OS":o0(globalThis.process.platform??"unknown"),"X-Stainless-Arch":i0(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};const e=AV();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":li,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":li,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function AV(){if(typeof navigator>"u"||!navigator)return null;const t=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(const{key:e,pattern:n}of t){const r=n.exec(navigator.userAgent);if(r){const s=r[1]||0,a=r[2]||0,i=r[3]||0;return{browser:e,version:`${s}.${a}.${i}`}}}return null}const i0=t=>t==="x32"?"x32":t==="x86_64"||t==="x64"?"x64":t==="arm"?"arm":t==="aarch64"||t==="arm64"?"arm64":t?`other:${t}`:"unknown",o0=t=>(t=t.toLowerCase(),t.includes("ios")?"iOS":t==="android"?"Android":t==="darwin"?"MacOS":t==="win32"?"Windows":t==="freebsd"?"FreeBSD":t==="openbsd"?"OpenBSD":t==="linux"?"Linux":t?`Other:${t}`:"Unknown");let c0;const IV=()=>c0??(c0=EV());function xV(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new Anthropic({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function Yk(...t){const e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...t)}function Qk(t){let e=Symbol.asyncIterator in t?t[Symbol.asyncIterator]():t[Symbol.iterator]();return Yk({start(){},async pull(n){const{done:r,value:s}=await e.next();r?n.close():n.enqueue(s)},async cancel(){var n;await((n=e.return)==null?void 0:n.call(e))}})}function uy(t){if(t[Symbol.asyncIterator])return t;const e=t.getReader();return{async next(){try{const n=await e.read();return n!=null&&n.done&&e.releaseLock(),n}catch(n){throw e.releaseLock(),n}},async return(){const n=e.cancel();return e.releaseLock(),await n,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function kV(t){var r,s;if(t===null||typeof t!="object")return;if(t[Symbol.asyncIterator]){await((s=(r=t[Symbol.asyncIterator]()).return)==null?void 0:s.call(r));return}const e=t.getReader(),n=e.cancel();e.releaseLock(),await n}const OV=({headers:t,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});function CV(t){return Object.entries(t).filter(([e,n])=>typeof n<"u").map(([e,n])=>{if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")return`${encodeURIComponent(e)}=${encodeURIComponent(n)}`;if(n===null)return`${encodeURIComponent(e)}=`;throw new ke(`Cannot stringify type ${typeof n}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}function RV(t){let e=0;for(const s of t)e+=s.length;const n=new Uint8Array(e);let r=0;for(const s of t)n.set(s,r),r+=s.length;return n}let u0;function ly(t){let e;return(u0??(e=new globalThis.TextEncoder,u0=e.encode.bind(e)))(t)}let l0;function d0(t){let e;return(l0??(e=new globalThis.TextDecoder,l0=e.decode.bind(e)))(t)}var Dn,Fn;class uu{constructor(){Dn.set(this,void 0),Fn.set(this,void 0),ee(this,Dn,new Uint8Array),ee(this,Fn,null)}decode(e){if(e==null)return[];const n=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?ly(e):e;ee(this,Dn,RV([C(this,Dn,"f"),n]));const r=[];let s;for(;(s=$V(C(this,Dn,"f"),C(this,Fn,"f")))!=null;){if(s.carriage&&C(this,Fn,"f")==null){ee(this,Fn,s.index);continue}if(C(this,Fn,"f")!=null&&(s.index!==C(this,Fn,"f")+1||s.carriage)){r.push(d0(C(this,Dn,"f").subarray(0,C(this,Fn,"f")-1))),ee(this,Dn,C(this,Dn,"f").subarray(C(this,Fn,"f"))),ee(this,Fn,null);continue}const a=C(this,Fn,"f")!==null?s.preceding-1:s.preceding,i=d0(C(this,Dn,"f").subarray(0,a));r.push(i),ee(this,Dn,C(this,Dn,"f").subarray(s.index)),ee(this,Fn,null)}return r}flush(){return C(this,Dn,"f").length?this.decode(`
560
- `):[]}}Dn=new WeakMap,Fn=new WeakMap;uu.NEWLINE_CHARS=new Set([`
561
- `,"\r"]);uu.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function $V(t,e){for(let s=e??0;s<t.length;s++){if(t[s]===10)return{preceding:s,index:s+1,carriage:!1};if(t[s]===13)return{preceding:s,index:s+1,carriage:!0}}return null}function NV(t){for(let r=0;r<t.length-1;r++){if(t[r]===10&&t[r+1]===10||t[r]===13&&t[r+1]===13)return r+2;if(t[r]===13&&t[r+1]===10&&r+3<t.length&&t[r+2]===13&&t[r+3]===10)return r+4}return-1}const Dd={off:0,error:200,warn:300,info:400,debug:500},h0=(t,e,n)=>{if(t){if(wV(Dd,t))return t;_n(n).warn(`${e} was set to ${JSON.stringify(t)}, expected one of ${JSON.stringify(Object.keys(Dd))}`)}};function qo(){}function qu(t,e,n){return!e||Dd[t]>Dd[n]?qo:e[t].bind(e)}const PV={error:qo,warn:qo,info:qo,debug:qo};let f0=new WeakMap;function _n(t){const e=t.logger,n=t.logLevel??"off";if(!e)return PV;const r=f0.get(e);if(r&&r[0]===n)return r[1];const s={error:qu("error",e,n),warn:qu("warn",e,n),info:qu("info",e,n),debug:qu("debug",e,n)};return f0.set(e,[n,s]),s}const _a=t=>(t.options&&(t.options={...t.options},delete t.options.headers),t.headers&&(t.headers=Object.fromEntries((t.headers instanceof Headers?[...t.headers]:Object.entries(t.headers)).map(([e,n])=>[e,e.toLowerCase()==="x-api-key"||e.toLowerCase()==="authorization"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":n]))),"retryOfRequestLogID"in t&&(t.retryOfRequestLogID&&(t.retryOf=t.retryOfRequestLogID),delete t.retryOfRequestLogID),t);var ho;class Hr{constructor(e,n,r){this.iterator=e,ho.set(this,void 0),this.controller=n,ee(this,ho,r)}static fromSSEResponse(e,n,r){let s=!1;const a=r?_n(r):console;async function*i(){var c;if(s)throw new ke("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let o=!1;try{for await(const u of MV(e,n)){if(u.event==="completion")try{yield JSON.parse(u.data)}catch(l){throw a.error("Could not parse message into JSON:",u.data),a.error("From chunk:",u.raw),l}if(u.event==="message_start"||u.event==="message_delta"||u.event==="message_stop"||u.event==="content_block_start"||u.event==="content_block_delta"||u.event==="content_block_stop"||u.event==="message"||u.event==="user.message"||u.event==="user.interrupt"||u.event==="user.tool_confirmation"||u.event==="user.custom_tool_result"||u.event==="agent.message"||u.event==="agent.thinking"||u.event==="agent.tool_use"||u.event==="agent.tool_result"||u.event==="agent.mcp_tool_use"||u.event==="agent.mcp_tool_result"||u.event==="agent.custom_tool_use"||u.event==="agent.thread_context_compacted"||u.event==="session.status_running"||u.event==="session.status_idle"||u.event==="session.status_rescheduled"||u.event==="session.status_terminated"||u.event==="session.error"||u.event==="session.deleted"||u.event==="span.model_request_start"||u.event==="span.model_request_end")try{yield JSON.parse(u.data)}catch(l){throw a.error("Could not parse message into JSON:",u.data),a.error("From chunk:",u.raw),l}if(u.event!=="ping"&&u.event==="error"){const l=Xk(u.data)??u.data,d=(c=l==null?void 0:l.error)==null?void 0:c.type;throw new fn(void 0,l,void 0,e.headers,d)}}o=!0}catch(u){if(Mc(u))return;throw u}finally{o||n.abort()}}return new Hr(i,n,r)}static fromReadableStream(e,n,r){let s=!1;async function*a(){const o=new uu,c=uy(e);for await(const u of c)for(const l of o.decode(u))yield l;for(const u of o.flush())yield u}async function*i(){if(s)throw new ke("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let o=!1;try{for await(const c of a())o||c&&(yield JSON.parse(c));o=!0}catch(c){if(Mc(c))return;throw c}finally{o||n.abort()}}return new Hr(i,n,r)}[(ho=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){const e=[],n=[],r=this.iterator(),s=a=>({next:()=>{if(a.length===0){const i=r.next();e.push(i),n.push(i)}return a.shift()}});return[new Hr(()=>s(e),this.controller,C(this,ho,"f")),new Hr(()=>s(n),this.controller,C(this,ho,"f"))]}toReadableStream(){const e=this;let n;return Yk({async start(){n=e[Symbol.asyncIterator]()},async pull(r){try{const{value:s,done:a}=await n.next();if(a)return r.close();const i=ly(JSON.stringify(s)+`
562
- `);r.enqueue(i)}catch(s){r.error(s)}},async cancel(){var r;await((r=n.return)==null?void 0:r.call(n))}})}}async function*MV(t,e){if(!t.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new ke("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new ke("Attempted to iterate over a response with no body");const n=new jV,r=new uu,s=uy(t.body);for await(const a of LV(s))for(const i of r.decode(a)){const o=n.decode(i);o&&(yield o)}for(const a of r.flush()){const i=n.decode(a);i&&(yield i)}}async function*LV(t){let e=new Uint8Array;for await(const n of t){if(n==null)continue;const r=n instanceof ArrayBuffer?new Uint8Array(n):typeof n=="string"?ly(n):n;let s=new Uint8Array(e.length+r.length);s.set(e),s.set(r,e.length),e=s;let a;for(;(a=NV(e))!==-1;)yield e.slice(0,a),e=e.slice(a)}e.length>0&&(yield e)}class jV{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;const a={event:this.event,data:this.data.join(`
563
- `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],a}if(this.chunks.push(e),e.startsWith(":"))return null;let[n,r,s]=UV(e,":");return s.startsWith(" ")&&(s=s.substring(1)),n==="event"?this.event=s:n==="data"&&this.data.push(s),null}}function UV(t,e){const n=t.indexOf(e);return n!==-1?[t.substring(0,n),e,t.substring(n+e.length)]:[t,"",""]}async function eO(t,e){const{response:n,requestLogID:r,retryOfRequestLogID:s,startTime:a}=e,i=await(async()=>{var d;if(e.options.stream)return _n(t).debug("response",n.status,n.url,n.headers,n.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(n,e.controller):Hr.fromSSEResponse(n,e.controller);if(n.status===204)return null;if(e.options.__binaryResponse)return n;const o=n.headers.get("content-type"),c=(d=o==null?void 0:o.split(";")[0])==null?void 0:d.trim();if((c==null?void 0:c.includes("application/json"))||(c==null?void 0:c.endsWith("+json"))){if(n.headers.get("content-length")==="0")return;const h=await n.json();return tO(h,n)}return await n.text()})();return _n(t).debug(`[${r}] response parsed`,_a({retryOfRequestLogID:s,url:n.url,status:n.status,body:i,durationMs:Date.now()-a})),i}function tO(t,e){return!t||typeof t!="object"||Array.isArray(t)?t:Object.defineProperty(t,"_request_id",{value:e.headers.get("request-id"),enumerable:!1})}var Ko;class Ch extends Promise{constructor(e,n,r=eO){super(s=>{s(null)}),this.responsePromise=n,this.parseResponse=r,Ko.set(this,void 0),ee(this,Ko,e)}_thenUnwrap(e){return new Ch(C(this,Ko,"f"),this.responsePromise,async(n,r)=>tO(e(await this.parseResponse(n,r),r),r.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){const[e,n]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:n,request_id:n.headers.get("request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(C(this,Ko,"f"),e))),this.parsedPromise}then(e,n){return this.parse().then(e,n)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}}Ko=new WeakMap;var Ku;class nO{constructor(e,n,r,s){Ku.set(this,void 0),ee(this,Ku,e),this.options=s,this.response=n,this.body=r}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){const e=this.nextPageRequestOptions();if(!e)throw new ke("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await C(this,Ku,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(Ku=new WeakMap,Symbol.asyncIterator)](){for await(const e of this.iterPages())for(const n of e.getPaginatedItems())yield n}}class DV extends Ch{constructor(e,n,r){super(e,n,async(s,a)=>new r(s,a.response,await eO(s,a),a.options))}async*[Symbol.asyncIterator](){const e=await this;for await(const n of e)yield n}}class lu extends nO{constructor(e,n,r,s){super(e,n,r,s),this.data=r.data||[],this.has_more=r.has_more||!1,this.first_id=r.first_id||null,this.last_id=r.last_id||null}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){var n;if((n=this.options.query)!=null&&n.before_id){const r=this.first_id;return r?{...this.options,query:{...Xm(this.options.query),before_id:r}}:null}const e=this.last_id;return e?{...this.options,query:{...Xm(this.options.query),after_id:e}}:null}}class Or extends nO{constructor(e,n,r,s){super(e,n,r,s),this.data=r.data||[],this.next_page=r.next_page||null}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){const e=this.next_page;return e?{...this.options,query:{...Xm(this.options.query),page:e}}:null}}const rO=()=>{var t;if(typeof File>"u"){const{process:e}=globalThis,n=typeof((t=e==null?void 0:e.versions)==null?void 0:t.node)=="string"&&parseInt(e.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(n?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function xi(t,e,n){return rO(),new File(t,e??"unknown_file",n)}function Hl(t,e){const n=typeof t=="object"&&t!==null&&("name"in t&&t.name&&String(t.name)||"url"in t&&t.url&&String(t.url)||"filename"in t&&t.filename&&String(t.filename)||"path"in t&&t.path&&String(t.path))||"";return e?n.split(/[\\/]/).pop()||void 0:n}const sO=t=>t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function",dy=async(t,e,n=!0)=>({...t,body:await BV(t.body,e,n)}),p0=new WeakMap;function FV(t){const e=typeof t=="function"?t:t.fetch,n=p0.get(e);if(n)return n;const r=(async()=>{try{const s="Response"in e?e.Response:(await e("data:,")).constructor,a=new FormData;return a.toString()!==await new s(a).text()}catch{return!0}})();return p0.set(e,r),r}const BV=async(t,e,n=!0)=>{if(!await FV(e))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");const r=new FormData;return await Promise.all(Object.entries(t||{}).map(([s,a])=>Ym(r,s,a,n))),r},zV=t=>t instanceof Blob&&"name"in t,Ym=async(t,e,n,r)=>{if(n!==void 0){if(n==null)throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")t.append(e,String(n));else if(n instanceof Response){let s={};const a=n.headers.get("Content-Type");a&&(s={type:a}),t.append(e,xi([await n.blob()],Hl(n,r),s))}else if(sO(n))t.append(e,xi([await new Response(Qk(n)).blob()],Hl(n,r)));else if(zV(n))t.append(e,xi([n],Hl(n,r),{type:n.type}));else if(Array.isArray(n))await Promise.all(n.map(s=>Ym(t,e+"[]",s,r)));else if(typeof n=="object")await Promise.all(Object.entries(n).map(([s,a])=>Ym(t,`${e}[${s}]`,a,r)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${n} instead`)}},aO=t=>t!=null&&typeof t=="object"&&typeof t.size=="number"&&typeof t.type=="string"&&typeof t.text=="function"&&typeof t.slice=="function"&&typeof t.arrayBuffer=="function",HV=t=>t!=null&&typeof t=="object"&&typeof t.name=="string"&&typeof t.lastModified=="number"&&aO(t),VV=t=>t!=null&&typeof t=="object"&&typeof t.url=="string"&&typeof t.blob=="function";async function ZV(t,e,n){if(rO(),t=await t,e||(e=Hl(t,!0)),HV(t))return t instanceof File&&e==null&&n==null?t:xi([await t.arrayBuffer()],e??t.name,{type:t.type,lastModified:t.lastModified,...n});if(VV(t)){const s=await t.blob();return e||(e=new URL(t.url).pathname.split(/[\\/]/).pop()),xi(await Qm(s),e,n)}const r=await Qm(t);if(!(n!=null&&n.type)){const s=r.find(a=>typeof a=="object"&&"type"in a&&a.type);typeof s=="string"&&(n={...n,type:s})}return xi(r,e,n)}async function Qm(t){var n;let e=[];if(typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer)e.push(t);else if(aO(t))e.push(t instanceof Blob?t:await t.arrayBuffer());else if(sO(t))for await(const r of t)e.push(...await Qm(r));else{const r=(n=t==null?void 0:t.constructor)==null?void 0:n.name;throw new Error(`Unexpected data type: ${typeof t}${r?`; constructor: ${r}`:""}${WV(t)}`)}return e}function WV(t){return typeof t!="object"||t===null?"":`; props: [${Object.getOwnPropertyNames(t).map(n=>`"${n}"`).join(", ")}]`}class kt{constructor(e){this._client=e}}const iO=Symbol.for("brand.privateNullableHeaders");function*GV(t){if(!t)return;if(iO in t){const{values:r,nulls:s}=t;yield*r.entries();for(const a of s)yield[a,null];return}let e=!1,n;t instanceof Headers?n=t.entries():s0(t)?n=t:(e=!0,n=Object.entries(t??{}));for(let r of n){const s=r[0];if(typeof s!="string")throw new TypeError("expected header name to be a string");const a=s0(r[1])?r[1]:[r[1]];let i=!1;for(const o of a)o!==void 0&&(e&&!i&&(i=!0,yield[s,null]),yield[s,o])}}const K=t=>{const e=new Headers,n=new Set;for(const r of t){const s=new Set;for(const[a,i]of GV(r)){const o=a.toLowerCase();s.has(o)||(e.delete(a),s.add(o)),i===null?(e.delete(a),n.add(o)):(e.append(a,i),n.delete(o))}}return{[iO]:!0,values:e,nulls:n}};function oO(t){return t.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}const m0=Object.freeze(Object.create(null)),qV=(t=oO)=>function(n,...r){if(n.length===1)return n[0];let s=!1;const a=[],i=n.reduce((l,d,f)=>{var _;/[?#]/.test(d)&&(s=!0);const h=r[f];let m=(s?encodeURIComponent:t)(""+h);return f!==r.length&&(h==null||typeof h=="object"&&h.toString===((_=Object.getPrototypeOf(Object.getPrototypeOf(h.hasOwnProperty??m0)??m0))==null?void 0:_.toString))&&(m=h+"",a.push({start:l.length+d.length,length:m.length,error:`Value of type ${Object.prototype.toString.call(h).slice(8,-1)} is not a valid path parameter`})),l+d+(f===r.length?"":m)},""),o=i.split(/[?#]/,1)[0],c=new RegExp("(?<=^|\\/)(?:\\.|%2e){1,2}(?=\\/|$)","gi");let u;for(;(u=c.exec(o))!==null;)a.push({start:u.index,length:u[0].length,error:`Value "${u[0]}" can't be safely passed as a path parameter`});if(a.sort((l,d)=>l.start-d.start),a.length>0){let l=0;const d=a.reduce((f,h)=>{const m=" ".repeat(h.start-l),_="^".repeat(h.length);return l=h.start+h.length,f+m+_},"");throw new ke(`Path parameters result in path with invalid segments:
564
- ${a.map(f=>f.error).join(`
565
- `)}
566
- ${i}
567
- ${d}`)}return i},Ae=qV(oO);class cO extends kt{create(e,n){const{betas:r,...s}=e;return this._client.post("/v1/environments?beta=true",{body:s,...n,headers:K([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},n==null?void 0:n.headers])})}retrieve(e,n={},r){const{betas:s}=n??{};return this._client.get(Ae`/v1/environments/${e}?beta=true`,{...r,headers:K([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r==null?void 0:r.headers])})}update(e,n,r){const{betas:s,...a}=n;return this._client.post(Ae`/v1/environments/${e}?beta=true`,{body:a,...r,headers:K([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r==null?void 0:r.headers])})}list(e={},n){const{betas:r,...s}=e??{};return this._client.getAPIList("/v1/environments?beta=true",Or,{query:s,...n,headers:K([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},n==null?void 0:n.headers])})}delete(e,n={},r){const{betas:s}=n??{};return this._client.delete(Ae`/v1/environments/${e}?beta=true`,{...r,headers:K([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r==null?void 0:r.headers])})}archive(e,n={},r){const{betas:s}=n??{};return this._client.post(Ae`/v1/environments/${e}/archive?beta=true`,{...r,headers:K([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r==null?void 0:r.headers])})}}const ic=Symbol("anthropic.sdk.stainlessHelper");function Vl(t){return typeof t=="object"&&t!==null&&ic in t}function uO(t,e){const n=new Set;if(t)for(const r of t)Vl(r)&&n.add(r[ic]);if(e){for(const r of e)if(Vl(r)&&n.add(r[ic]),Array.isArray(r.content))for(const s of r.content)Vl(s)&&n.add(s[ic])}return Array.from(n)}function lO(t,e){const n=uO(t,e);return n.length===0?{}:{"x-stainless-helper":n.join(", ")}}function KV(t){return Vl(t)?{"x-stainless-helper":t[ic]}:{}}class dO extends kt{list(e={},n){const{betas:r,...s}=e??{};return this._client.getAPIList("/v1/files",lu,{query:s,...n,headers:K([{"anthropic-beta":[...r??[],"files-api-2025-04-14"].toString()},n==null?void 0:n.headers])})}delete(e,n={},r){const{betas:s}=n??{};return this._client.delete(Ae`/v1/files/${e}`,{...r,headers:K([{"anthropic-beta":[...s??[],"files-api-2025-04-14"].toString()},r==null?void 0:r.headers])})}download(e,n={},r){const{betas:s}=n??{};return this._client.get(Ae`/v1/files/${e}/content`,{...r,headers:K([{"anthropic-beta":[...s??[],"files-api-2025-04-14"].toString(),Accept:"application/binary"},r==null?void 0:r.headers]),__binaryResponse:!0})}retrieveMetadata(e,n={},r){const{betas:s}=n??{};return this._client.get(Ae`/v1/files/${e}`,{...r,headers:K([{"anthropic-beta":[...s??[],"files-api-2025-04-14"].toString()},r==null?void 0:r.headers])})}upload(e,n){const{betas:r,...s}=e;return this._client.post("/v1/files",dy({body:s,...n,headers:K([{"anthropic-beta":[...r??[],"files-api-2025-04-14"].toString()},KV(s.file),n==null?void 0:n.headers])},this._client))}}let hO=class extends kt{retrieve(e,n={},r){const{betas:s}=n??{};return this._client.get(Ae`/v1/models/${e}?beta=true`,{...r,headers:K([{...(s==null?void 0:s.toString())!=null?{"anthropic-beta":s==null?void 0:s.toString()}:void 0},r==null?void 0:r.headers])})}list(e={},n){const{betas:r,...s}=e??{};return this._client.getAPIList("/v1/models?beta=true",lu,{query:s,...n,headers:K([{...(r==null?void 0:r.toString())!=null?{"anthropic-beta":r==null?void 0:r.toString()}:void 0},n==null?void 0:n.headers])})}};class fO extends kt{create(e,n){const{betas:r,...s}=e;return this._client.post("/v1/user_profiles?beta=true",{body:s,...n,headers:K([{"anthropic-beta":[...r??[],"user-profiles-2026-03-24"].toString()},n==null?void 0:n.headers])})}retrieve(e,n={},r){const{betas:s}=n??{};return this._client.get(Ae`/v1/user_profiles/${e}?beta=true`,{...r,headers:K([{"anthropic-beta":[...s??[],"user-profiles-2026-03-24"].toString()},r==null?void 0:r.headers])})}update(e,n,r){const{betas:s,...a}=n;return this._client.post(Ae`/v1/user_profiles/${e}?beta=true`,{body:a,...r,headers:K([{"anthropic-beta":[...s??[],"user-profiles-2026-03-24"].toString()},r==null?void 0:r.headers])})}list(e={},n){const{betas:r,...s}=e??{};return this._client.getAPIList("/v1/user_profiles?beta=true",Or,{query:s,...n,headers:K([{"anthropic-beta":[...r??[],"user-profiles-2026-03-24"].toString()},n==null?void 0:n.headers])})}createEnrollmentURL(e,n={},r){const{betas:s}=n??{};return this._client.post(Ae`/v1/user_profiles/${e}/enrollment_url?beta=true`,{...r,headers:K([{"anthropic-beta":[...s??[],"user-profiles-2026-03-24"].toString()},r==null?void 0:r.headers])})}}let pO=class extends kt{list(e,n={},r){const{betas:s,...a}=n??{};return this._client.getAPIList(Ae`/v1/agents/${e}/versions?beta=true`,Or,{query:a,...r,headers:K([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r==null?void 0:r.headers])})}};class hy extends kt{constructor(){super(...arguments),this.versions=new pO(this._client)}create(e,n){const{betas:r,...s}=e;return this._client.post("/v1/agents?beta=true",{body:s,...n,headers:K([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},n==null?void 0:n.headers])})}retrieve(e,n={},r){const{betas:s,...a}=n??{};return this._client.get(Ae`/v1/agents/${e}?beta=true`,{query:a,...r,headers:K([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r==null?void 0:r.headers])})}update(e,n,r){const{betas:s,...a}=n;return this._client.post(Ae`/v1/agents/${e}?beta=true`,{body:a,...r,headers:K([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r==null?void 0:r.headers])})}list(e={},n){const{betas:r,...s}=e??{};return this._client.getAPIList("/v1/agents?beta=true",Or,{query:s,...n,headers:K([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},n==null?void 0:n.headers])})}archive(e,n={},r){const{betas:s}=n??{};return this._client.post(Ae`/v1/agents/${e}/archive?beta=true`,{...r,headers:K([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r==null?void 0:r.headers])})}}hy.Versions=pO;const mO={"claude-opus-4-20250514":8192,"claude-opus-4-0":8192,"claude-4-opus-20250514":8192,"anthropic.claude-opus-4-20250514-v1:0":8192,"claude-opus-4@20250514":8192,"claude-opus-4-1-20250805":8192,"anthropic.claude-opus-4-1-20250805-v1:0":8192,"claude-opus-4-1@20250805":8192};function gO(t){var e;return(t==null?void 0:t.output_format)??((e=t==null?void 0:t.output_config)==null?void 0:e.format)}function g0(t,e,n){const r=gO(e);return!e||!("parse"in(r??{}))?{...t,content:t.content.map(s=>{if(s.type==="text"){const a=Object.defineProperty({...s},"parsed_output",{value:null,enumerable:!1});return Object.defineProperty(a,"parsed",{get(){return n.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),null},enumerable:!1})}return s}),parsed_output:null}:_O(t,e,n)}function _O(t,e,n){let r=null;const s=t.content.map(a=>{if(a.type==="text"){const i=JV(e,a.text);r===null&&(r=i);const o=Object.defineProperty({...a},"parsed_output",{value:i,enumerable:!1});return Object.defineProperty(o,"parsed",{get(){return n.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),i},enumerable:!1})}return a});return{...t,content:s,parsed_output:r}}function JV(t,e){const n=gO(t);if((n==null?void 0:n.type)!=="json_schema")return null;try{return"parse"in n?n.parse(e):JSON.parse(e)}catch(r){throw new ke(`Failed to parse structured output: ${r}`)}}const XV=t=>{let e=0,n=[];for(;e<t.length;){let r=t[e];if(r==="\\"){e++;continue}if(r==="{"){n.push({type:"brace",value:"{"}),e++;continue}if(r==="}"){n.push({type:"brace",value:"}"}),e++;continue}if(r==="["){n.push({type:"paren",value:"["}),e++;continue}if(r==="]"){n.push({type:"paren",value:"]"}),e++;continue}if(r===":"){n.push({type:"separator",value:":"}),e++;continue}if(r===","){n.push({type:"delimiter",value:","}),e++;continue}if(r==='"'){let o="",c=!1;for(r=t[++e];r!=='"';){if(e===t.length){c=!0;break}if(r==="\\"){if(e++,e===t.length){c=!0;break}o+=r+t[e],r=t[++e]}else o+=r,r=t[++e]}r=t[++e],c||n.push({type:"string",value:o});continue}if(r&&/\s/.test(r)){e++;continue}let a=/[0-9]/;if(r&&a.test(r)||r==="-"||r==="."){let o="";for(r==="-"&&(o+=r,r=t[++e]);r&&a.test(r)||r===".";)o+=r,r=t[++e];n.push({type:"number",value:o});continue}let i=/[a-z]/i;if(r&&i.test(r)){let o="";for(;r&&i.test(r)&&e!==t.length;)o+=r,r=t[++e];if(o=="true"||o=="false"||o==="null")n.push({type:"name",value:o});else{e++;continue}continue}e++}return n},di=t=>{if(t.length===0)return t;let e=t[t.length-1];switch(e.type){case"separator":return t=t.slice(0,t.length-1),di(t);case"number":let n=e.value[e.value.length-1];if(n==="."||n==="-")return t=t.slice(0,t.length-1),di(t);case"string":let r=t[t.length-2];if((r==null?void 0:r.type)==="delimiter")return t=t.slice(0,t.length-1),di(t);if((r==null?void 0:r.type)==="brace"&&r.value==="{")return t=t.slice(0,t.length-1),di(t);break;case"delimiter":return t=t.slice(0,t.length-1),di(t)}return t},YV=t=>{let e=[];return t.map(n=>{n.type==="brace"&&(n.value==="{"?e.push("}"):e.splice(e.lastIndexOf("}"),1)),n.type==="paren"&&(n.value==="["?e.push("]"):e.splice(e.lastIndexOf("]"),1))}),e.length>0&&e.reverse().map(n=>{n==="}"?t.push({type:"brace",value:"}"}):n==="]"&&t.push({type:"paren",value:"]"})}),t},QV=t=>{let e="";return t.map(n=>{switch(n.type){case"string":e+='"'+n.value+'"';break;default:e+=n.value;break}}),e},yO=t=>JSON.parse(QV(YV(di(XV(t)))));var Qn,xs,ei,fo,Ju,po,mo,Xu,go,Qr,_o,Yu,Qu,ua,el,tl,yo,ep,_0,nl,tp,np,rp,y0;const w0="__json_buf";function b0(t){return t.type==="tool_use"||t.type==="server_tool_use"||t.type==="mcp_tool_use"}class Fd{constructor(e,n){Qn.add(this),this.messages=[],this.receivedMessages=[],xs.set(this,void 0),ei.set(this,null),this.controller=new AbortController,fo.set(this,void 0),Ju.set(this,()=>{}),po.set(this,()=>{}),mo.set(this,void 0),Xu.set(this,()=>{}),go.set(this,()=>{}),Qr.set(this,{}),_o.set(this,!1),Yu.set(this,!1),Qu.set(this,!1),ua.set(this,!1),el.set(this,void 0),tl.set(this,void 0),yo.set(this,void 0),nl.set(this,r=>{if(ee(this,Yu,!0),Mc(r)&&(r=new Ar),r instanceof Ar)return ee(this,Qu,!0),this._emit("abort",r);if(r instanceof ke)return this._emit("error",r);if(r instanceof Error){const s=new ke(r.message);return s.cause=r,this._emit("error",s)}return this._emit("error",new ke(String(r)))}),ee(this,fo,new Promise((r,s)=>{ee(this,Ju,r,"f"),ee(this,po,s,"f")})),ee(this,mo,new Promise((r,s)=>{ee(this,Xu,r,"f"),ee(this,go,s,"f")})),C(this,fo,"f").catch(()=>{}),C(this,mo,"f").catch(()=>{}),ee(this,ei,e),ee(this,yo,(n==null?void 0:n.logger)??console)}get response(){return C(this,el,"f")}get request_id(){return C(this,tl,"f")}async withResponse(){ee(this,ua,!0);const e=await C(this,fo,"f");if(!e)throw new Error("Could not resolve a `Response` object");return{data:this,response:e,request_id:e.headers.get("request-id")}}static fromReadableStream(e){const n=new Fd(null);return n._run(()=>n._fromReadableStream(e)),n}static createMessage(e,n,r,{logger:s}={}){const a=new Fd(n,{logger:s});for(const i of n.messages)a._addMessageParam(i);return ee(a,ei,{...n,stream:!0}),a._run(()=>a._createMessage(e,{...n,stream:!0},{...r,headers:{...r==null?void 0:r.headers,"X-Stainless-Helper-Method":"stream"}})),a}_run(e){e().then(()=>{this._emitFinal(),this._emit("end")},C(this,nl,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,n=!0){this.receivedMessages.push(e),n&&this._emit("message",e)}async _createMessage(e,n,r){var i;const s=r==null?void 0:r.signal;let a;s&&(s.aborted&&this.controller.abort(),a=this.controller.abort.bind(this.controller),s.addEventListener("abort",a));try{C(this,Qn,"m",tp).call(this);const{response:o,data:c}=await e.create({...n,stream:!0},{...r,signal:this.controller.signal}).withResponse();this._connected(o);for await(const u of c)C(this,Qn,"m",np).call(this,u);if((i=c.controller.signal)!=null&&i.aborted)throw new Ar;C(this,Qn,"m",rp).call(this)}finally{s&&a&&s.removeEventListener("abort",a)}}_connected(e){this.ended||(ee(this,el,e),ee(this,tl,e==null?void 0:e.headers.get("request-id")),C(this,Ju,"f").call(this,e),this._emit("connect"))}get ended(){return C(this,_o,"f")}get errored(){return C(this,Yu,"f")}get aborted(){return C(this,Qu,"f")}abort(){this.controller.abort()}on(e,n){return(C(this,Qr,"f")[e]||(C(this,Qr,"f")[e]=[])).push({listener:n}),this}off(e,n){const r=C(this,Qr,"f")[e];if(!r)return this;const s=r.findIndex(a=>a.listener===n);return s>=0&&r.splice(s,1),this}once(e,n){return(C(this,Qr,"f")[e]||(C(this,Qr,"f")[e]=[])).push({listener:n,once:!0}),this}emitted(e){return new Promise((n,r)=>{ee(this,ua,!0),e!=="error"&&this.once("error",r),this.once(e,n)})}async done(){ee(this,ua,!0),await C(this,mo,"f")}get currentMessage(){return C(this,xs,"f")}async finalMessage(){return await this.done(),C(this,Qn,"m",ep).call(this)}async finalText(){return await this.done(),C(this,Qn,"m",_0).call(this)}_emit(e,...n){if(C(this,_o,"f"))return;e==="end"&&(ee(this,_o,!0),C(this,Xu,"f").call(this));const r=C(this,Qr,"f")[e];if(r&&(C(this,Qr,"f")[e]=r.filter(s=>!s.once),r.forEach(({listener:s})=>s(...n))),e==="abort"){const s=n[0];!C(this,ua,"f")&&!(r!=null&&r.length)&&Promise.reject(s),C(this,po,"f").call(this,s),C(this,go,"f").call(this,s),this._emit("end");return}if(e==="error"){const s=n[0];!C(this,ua,"f")&&!(r!=null&&r.length)&&Promise.reject(s),C(this,po,"f").call(this,s),C(this,go,"f").call(this,s),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",C(this,Qn,"m",ep).call(this))}async _fromReadableStream(e,n){var a;const r=n==null?void 0:n.signal;let s;r&&(r.aborted&&this.controller.abort(),s=this.controller.abort.bind(this.controller),r.addEventListener("abort",s));try{C(this,Qn,"m",tp).call(this),this._connected(null);const i=Hr.fromReadableStream(e,this.controller);for await(const o of i)C(this,Qn,"m",np).call(this,o);if((a=i.controller.signal)!=null&&a.aborted)throw new Ar;C(this,Qn,"m",rp).call(this)}finally{r&&s&&r.removeEventListener("abort",s)}}[(xs=new WeakMap,ei=new WeakMap,fo=new WeakMap,Ju=new WeakMap,po=new WeakMap,mo=new WeakMap,Xu=new WeakMap,go=new WeakMap,Qr=new WeakMap,_o=new WeakMap,Yu=new WeakMap,Qu=new WeakMap,ua=new WeakMap,el=new WeakMap,tl=new WeakMap,yo=new WeakMap,nl=new WeakMap,Qn=new WeakSet,ep=function(){if(this.receivedMessages.length===0)throw new ke("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},_0=function(){if(this.receivedMessages.length===0)throw new ke("stream ended without producing a Message with role=assistant");const n=this.receivedMessages.at(-1).content.filter(r=>r.type==="text").map(r=>r.text);if(n.length===0)throw new ke("stream ended without producing a content block with type=text");return n.join(" ")},tp=function(){this.ended||ee(this,xs,void 0)},np=function(n){if(this.ended)return;const r=C(this,Qn,"m",y0).call(this,n);switch(this._emit("streamEvent",n,r),n.type){case"content_block_delta":{const s=r.content.at(-1);switch(n.delta.type){case"text_delta":{s.type==="text"&&this._emit("text",n.delta.text,s.text||"");break}case"citations_delta":{s.type==="text"&&this._emit("citation",n.delta.citation,s.citations??[]);break}case"input_json_delta":{b0(s)&&s.input&&this._emit("inputJson",n.delta.partial_json,s.input);break}case"thinking_delta":{s.type==="thinking"&&this._emit("thinking",n.delta.thinking,s.thinking);break}case"signature_delta":{s.type==="thinking"&&this._emit("signature",s.signature);break}case"compaction_delta":{s.type==="compaction"&&s.content&&this._emit("compaction",s.content);break}default:n.delta}break}case"message_stop":{this._addMessageParam(r),this._addMessage(g0(r,C(this,ei,"f"),{logger:C(this,yo,"f")}),!0);break}case"content_block_stop":{this._emit("contentBlock",r.content.at(-1));break}case"message_start":{ee(this,xs,r);break}}},rp=function(){if(this.ended)throw new ke("stream has ended, this shouldn't happen");const n=C(this,xs,"f");if(!n)throw new ke("request ended without sending any chunks");return ee(this,xs,void 0),g0(n,C(this,ei,"f"),{logger:C(this,yo,"f")})},y0=function(n){let r=C(this,xs,"f");if(n.type==="message_start"){if(r)throw new ke(`Unexpected event order, got ${n.type} before receiving "message_stop"`);return n.message}if(!r)throw new ke(`Unexpected event order, got ${n.type} before "message_start"`);switch(n.type){case"message_stop":return r;case"message_delta":return r.container=n.delta.container,r.stop_reason=n.delta.stop_reason,r.stop_sequence=n.delta.stop_sequence,r.usage.output_tokens=n.usage.output_tokens,r.context_management=n.context_management,n.usage.input_tokens!=null&&(r.usage.input_tokens=n.usage.input_tokens),n.usage.cache_creation_input_tokens!=null&&(r.usage.cache_creation_input_tokens=n.usage.cache_creation_input_tokens),n.usage.cache_read_input_tokens!=null&&(r.usage.cache_read_input_tokens=n.usage.cache_read_input_tokens),n.usage.server_tool_use!=null&&(r.usage.server_tool_use=n.usage.server_tool_use),n.usage.iterations!=null&&(r.usage.iterations=n.usage.iterations),r;case"content_block_start":return r.content.push(n.content_block),r;case"content_block_delta":{const s=r.content.at(n.index);switch(n.delta.type){case"text_delta":{(s==null?void 0:s.type)==="text"&&(r.content[n.index]={...s,text:(s.text||"")+n.delta.text});break}case"citations_delta":{(s==null?void 0:s.type)==="text"&&(r.content[n.index]={...s,citations:[...s.citations??[],n.delta.citation]});break}case"input_json_delta":{if(s&&b0(s)){let a=s[w0]||"";a+=n.delta.partial_json;const i={...s};if(Object.defineProperty(i,w0,{value:a,enumerable:!1,writable:!0}),a)try{i.input=yO(a)}catch(o){const c=new ke(`Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: ${o}. JSON: ${a}`);C(this,nl,"f").call(this,c)}r.content[n.index]=i}break}case"thinking_delta":{(s==null?void 0:s.type)==="thinking"&&(r.content[n.index]={...s,thinking:s.thinking+n.delta.thinking});break}case"signature_delta":{(s==null?void 0:s.type)==="thinking"&&(r.content[n.index]={...s,signature:n.delta.signature});break}case"compaction_delta":{(s==null?void 0:s.type)==="compaction"&&(r.content[n.index]={...s,content:(s.content||"")+n.delta.content});break}default:n.delta}return r}case"content_block_stop":return r}},Symbol.asyncIterator)](){const e=[],n=[];let r=!1;return this.on("streamEvent",s=>{const a=n.shift();a?a.resolve(s):e.push(s)}),this.on("end",()=>{r=!0;for(const s of n)s.resolve(void 0);n.length=0}),this.on("abort",s=>{r=!0;for(const a of n)a.reject(s);n.length=0}),this.on("error",s=>{r=!0;for(const a of n)a.reject(s);n.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((a,i)=>n.push({resolve:a,reject:i})).then(a=>a?{value:a,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new Hr(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}class wO extends Error{constructor(e){const n=typeof e=="string"?e:e.map(r=>r.type==="text"?r.text:`[${r.type}]`).join(" ");super(n),this.name="ToolError",this.content=e}}const eZ=1e5,tZ=`You have been working on the task described above but have not yet completed it. Write a continuation summary that will allow you (or another instance of yourself) to resume work efficiently in a future context window where the conversation history will be replaced with this summary. Your summary should be structured, concise, and actionable. Include:
568
- 1. Task Overview
569
- The user's core request and success criteria
570
- Any clarifications or constraints they specified
571
- 2. Current State
572
- What has been completed so far
573
- Files created, modified, or analyzed (with paths if relevant)
574
- Key outputs or artifacts produced
575
- 3. Important Discoveries
576
- Technical constraints or requirements uncovered
577
- Decisions made and their rationale
578
- Errors encountered and how they were resolved
579
- What approaches were tried that didn't work (and why)
580
- 4. Next Steps
581
- Specific actions needed to complete the task
582
- Any blockers or open questions to resolve
583
- Priority order if multiple steps remain
584
- 5. Context to Preserve
585
- User preferences or style requirements
586
- Domain-specific details that aren't obvious
587
- Any promises made to the user
588
- Be concise but complete—err on the side of including information that would prevent duplicate work or repeated mistakes. Write in a way that enables immediate resumption of the task.
589
- Wrap your summary in <summary></summary> tags.`;var wo,ti,la,$t,In,Ln,ds,ks,bo,v0,eg;function S0(){let t,e;return{promise:new Promise((r,s)=>{t=r,e=s}),resolve:t,reject:e}}class bO{constructor(e,n,r){var i;wo.add(this),this.client=e,ti.set(this,!1),la.set(this,!1),$t.set(this,void 0),In.set(this,void 0),Ln.set(this,void 0),ds.set(this,void 0),ks.set(this,void 0),bo.set(this,0),ee(this,$t,{params:{...n,messages:structuredClone(n.messages)}});const a=["BetaToolRunner",...uO(n.tools,n.messages)].join(", ");ee(this,In,{...r,headers:K([{"x-stainless-helper":a},r==null?void 0:r.headers])}),ee(this,ks,S0()),(i=n.compactionControl)!=null&&i.enabled&&console.warn('Anthropic: The `compactionControl` parameter is deprecated and will be removed in a future version. Use server-side compaction instead by passing `edits: [{ type: "compact_20260112" }]` in the params passed to `toolRunner()`. See https://platform.claude.com/docs/en/build-with-claude/compaction')}async*[(ti=new WeakMap,la=new WeakMap,$t=new WeakMap,In=new WeakMap,Ln=new WeakMap,ds=new WeakMap,ks=new WeakMap,bo=new WeakMap,wo=new WeakSet,v0=async function(){var u;const n=C(this,$t,"f").params.compactionControl;if(!n||!n.enabled)return!1;let r=0;if(C(this,Ln,"f")!==void 0)try{const l=await C(this,Ln,"f");r=l.usage.input_tokens+(l.usage.cache_creation_input_tokens??0)+(l.usage.cache_read_input_tokens??0)+l.usage.output_tokens}catch{return!1}const s=n.contextTokenThreshold??eZ;if(r<s)return!1;const a=n.model??C(this,$t,"f").params.model,i=n.summaryPrompt??tZ,o=C(this,$t,"f").params.messages;if(o[o.length-1].role==="assistant"){const l=o[o.length-1];if(Array.isArray(l.content)){const d=l.content.filter(f=>f.type!=="tool_use");d.length===0?o.pop():l.content=d}}const c=await this.client.beta.messages.create({model:a,messages:[...o,{role:"user",content:[{type:"text",text:i}]}],max_tokens:C(this,$t,"f").params.max_tokens},{signal:C(this,In,"f").signal,headers:K([C(this,In,"f").headers,{"x-stainless-helper":"compaction"}])});if(((u=c.content[0])==null?void 0:u.type)!=="text")throw new ke("Expected text response for compaction");return C(this,$t,"f").params.messages=[{role:"user",content:c.content}],!0},Symbol.asyncIterator)](){var e;if(C(this,ti,"f"))throw new ke("Cannot iterate over a consumed stream");ee(this,ti,!0),ee(this,la,!0),ee(this,ds,void 0);try{for(;;){let n;try{if(C(this,$t,"f").params.max_iterations&&C(this,bo,"f")>=C(this,$t,"f").params.max_iterations)break;ee(this,la,!1,"f"),ee(this,ds,void 0,"f"),ee(this,bo,(e=C(this,bo,"f"),e++,e),"f"),ee(this,Ln,void 0,"f");const{max_iterations:r,compactionControl:s,...a}=C(this,$t,"f").params;if(a.stream?(n=this.client.beta.messages.stream({...a},C(this,In,"f")),ee(this,Ln,n.finalMessage(),"f"),C(this,Ln,"f").catch(()=>{}),yield n):(ee(this,Ln,this.client.beta.messages.create({...a,stream:!1},C(this,In,"f")),"f"),yield C(this,Ln,"f")),!await C(this,wo,"m",v0).call(this)){if(!C(this,la,"f")){const{role:c,content:u}=await C(this,Ln,"f");C(this,$t,"f").params.messages.push({role:c,content:u})}const o=await C(this,wo,"m",eg).call(this,C(this,$t,"f").params.messages.at(-1));if(o)C(this,$t,"f").params.messages.push(o);else if(!C(this,la,"f"))break}}finally{n&&n.abort()}}if(!C(this,Ln,"f"))throw new ke("ToolRunner concluded without a message from the server");C(this,ks,"f").resolve(await C(this,Ln,"f"))}catch(n){throw ee(this,ti,!1),C(this,ks,"f").promise.catch(()=>{}),C(this,ks,"f").reject(n),ee(this,ks,S0()),n}}setMessagesParams(e){typeof e=="function"?C(this,$t,"f").params=e(C(this,$t,"f").params):C(this,$t,"f").params=e,ee(this,la,!0),ee(this,ds,void 0)}setRequestOptions(e){typeof e=="function"?ee(this,In,e(C(this,In,"f"))):ee(this,In,{...C(this,In,"f"),...e})}async generateToolResponse(e=C(this,In,"f").signal){const n=await C(this,Ln,"f")??this.params.messages.at(-1);return n?C(this,wo,"m",eg).call(this,n,e):null}done(){return C(this,ks,"f").promise}async runUntilDone(){if(!C(this,ti,"f"))for await(const e of this);return this.done()}get params(){return C(this,$t,"f").params}pushMessages(...e){this.setMessagesParams(n=>({...n,messages:[...n.messages,...e]}))}then(e,n){return this.runUntilDone().then(e,n)}}eg=async function(e,n=C(this,In,"f").signal){return C(this,ds,"f")!==void 0?C(this,ds,"f"):(ee(this,ds,nZ(C(this,$t,"f").params,e,{...C(this,In,"f"),signal:n})),C(this,ds,"f"))};async function nZ(t,e=t.messages.at(-1),n){if(!e||e.role!=="assistant"||!e.content||typeof e.content=="string")return null;const r=e.content.filter(a=>a.type==="tool_use");return r.length===0?null:{role:"user",content:await Promise.all(r.map(async a=>{const i=t.tools.find(o=>("name"in o?o.name:o.mcp_server_name)===a.name);if(!i||!("run"in i))return{type:"tool_result",tool_use_id:a.id,content:`Error: Tool '${a.name}' not found`,is_error:!0};try{let o=a.input;"parse"in i&&i.parse&&(o=i.parse(o));const c=await i.run(o,{toolUseBlock:a,signal:n==null?void 0:n.signal});return{type:"tool_result",tool_use_id:a.id,content:c}}catch(o){return{type:"tool_result",tool_use_id:a.id,content:o instanceof wO?o.content:`Error: ${o instanceof Error?o.message:String(o)}`,is_error:!0}}}))}}class Rh{constructor(e,n){this.iterator=e,this.controller=n}async*decoder(){const e=new uu;for await(const n of this.iterator)for(const r of e.decode(n))yield JSON.parse(r);for(const n of e.flush())yield JSON.parse(n)}[Symbol.asyncIterator](){return this.decoder()}static fromResponse(e,n){if(!e.body)throw n.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new ke("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new ke("Attempted to iterate over a response with no body");return new Rh(uy(e.body),n)}}let vO=class extends kt{create(e,n){const{betas:r,...s}=e;return this._client.post("/v1/messages/batches?beta=true",{body:s,...n,headers:K([{"anthropic-beta":[...r??[],"message-batches-2024-09-24"].toString()},n==null?void 0:n.headers])})}retrieve(e,n={},r){const{betas:s}=n??{};return this._client.get(Ae`/v1/messages/batches/${e}?beta=true`,{...r,headers:K([{"anthropic-beta":[...s??[],"message-batches-2024-09-24"].toString()},r==null?void 0:r.headers])})}list(e={},n){const{betas:r,...s}=e??{};return this._client.getAPIList("/v1/messages/batches?beta=true",lu,{query:s,...n,headers:K([{"anthropic-beta":[...r??[],"message-batches-2024-09-24"].toString()},n==null?void 0:n.headers])})}delete(e,n={},r){const{betas:s}=n??{};return this._client.delete(Ae`/v1/messages/batches/${e}?beta=true`,{...r,headers:K([{"anthropic-beta":[...s??[],"message-batches-2024-09-24"].toString()},r==null?void 0:r.headers])})}cancel(e,n={},r){const{betas:s}=n??{};return this._client.post(Ae`/v1/messages/batches/${e}/cancel?beta=true`,{...r,headers:K([{"anthropic-beta":[...s??[],"message-batches-2024-09-24"].toString()},r==null?void 0:r.headers])})}async results(e,n={},r){const s=await this.retrieve(e);if(!s.results_url)throw new ke(`No batch \`results_url\`; Has it finished processing? ${s.processing_status} - ${s.id}`);const{betas:a}=n??{};return this._client.get(s.results_url,{...r,headers:K([{"anthropic-beta":[...a??[],"message-batches-2024-09-24"].toString(),Accept:"application/binary"},r==null?void 0:r.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((i,o)=>Rh.fromResponse(o.response,o.controller))}};const T0={"claude-1.3":"November 6th, 2024","claude-1.3-100k":"November 6th, 2024","claude-instant-1.1":"November 6th, 2024","claude-instant-1.1-100k":"November 6th, 2024","claude-instant-1.2":"November 6th, 2024","claude-3-sonnet-20240229":"July 21st, 2025","claude-3-opus-20240229":"January 5th, 2026","claude-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025","claude-3-7-sonnet-latest":"February 19th, 2026","claude-3-7-sonnet-20250219":"February 19th, 2026"},rZ=["claude-mythos-preview","claude-opus-4-6"];let du=class extends kt{constructor(){super(...arguments),this.batches=new vO(this._client)}create(e,n){const r=E0(e),{betas:s,...a}=r;a.model in T0&&console.warn(`The model '${a.model}' is deprecated and will reach end-of-life on ${T0[a.model]}
590
- Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),rZ.includes(a.model)&&a.thinking&&a.thinking.type==="enabled"&&console.warn(`Using Claude with ${a.model} and 'thinking.type=enabled' is deprecated. Use 'thinking.type=adaptive' instead which results in better model performance in our testing: https://platform.claude.com/docs/en/build-with-claude/adaptive-thinking`);let i=this._client._options.timeout;if(!a.stream&&i==null){const c=mO[a.model]??void 0;i=this._client.calculateNonstreamingTimeout(a.max_tokens,c)}const o=lO(a.tools,a.messages);return this._client.post("/v1/messages?beta=true",{body:a,timeout:i??6e5,...n,headers:K([{...(s==null?void 0:s.toString())!=null?{"anthropic-beta":s==null?void 0:s.toString()}:void 0},o,n==null?void 0:n.headers]),stream:r.stream??!1})}parse(e,n){return n={...n,headers:K([{"anthropic-beta":[...e.betas??[],"structured-outputs-2025-12-15"].toString()},n==null?void 0:n.headers])},this.create(e,n).then(r=>_O(r,e,{logger:this._client.logger??console}))}stream(e,n){return Fd.createMessage(this,e,n)}countTokens(e,n){const r=E0(e),{betas:s,...a}=r;return this._client.post("/v1/messages/count_tokens?beta=true",{body:a,...n,headers:K([{"anthropic-beta":[...s??[],"token-counting-2024-11-01"].toString()},n==null?void 0:n.headers])})}toolRunner(e,n){return new bO(this._client,e,n)}};function E0(t){var r;if(!t.output_format)return t;if((r=t.output_config)!=null&&r.format)throw new ke("Both output_format and output_config.format were provided. Please use only output_config.format (output_format is deprecated).");const{output_format:e,...n}=t;return{...n,output_config:{...t.output_config,format:e}}}du.Batches=vO;du.BetaToolRunner=bO;du.ToolError=wO;class SO extends kt{list(e,n={},r){const{betas:s,...a}=n??{};return this._client.getAPIList(Ae`/v1/sessions/${e}/events?beta=true`,Or,{query:a,...r,headers:K([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r==null?void 0:r.headers])})}send(e,n,r){const{betas:s,...a}=n;return this._client.post(Ae`/v1/sessions/${e}/events?beta=true`,{body:a,...r,headers:K([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r==null?void 0:r.headers])})}stream(e,n={},r){const{betas:s}=n??{};return this._client.get(Ae`/v1/sessions/${e}/events/stream?beta=true`,{...r,headers:K([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r==null?void 0:r.headers]),stream:!0})}}class TO extends kt{retrieve(e,n,r){const{session_id:s,betas:a}=n;return this._client.get(Ae`/v1/sessions/${s}/resources/${e}?beta=true`,{...r,headers:K([{"anthropic-beta":[...a??[],"managed-agents-2026-04-01"].toString()},r==null?void 0:r.headers])})}update(e,n,r){const{session_id:s,betas:a,...i}=n;return this._client.post(Ae`/v1/sessions/${s}/resources/${e}?beta=true`,{body:i,...r,headers:K([{"anthropic-beta":[...a??[],"managed-agents-2026-04-01"].toString()},r==null?void 0:r.headers])})}list(e,n={},r){const{betas:s,...a}=n??{};return this._client.getAPIList(Ae`/v1/sessions/${e}/resources?beta=true`,Or,{query:a,...r,headers:K([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r==null?void 0:r.headers])})}delete(e,n,r){const{session_id:s,betas:a}=n;return this._client.delete(Ae`/v1/sessions/${s}/resources/${e}?beta=true`,{...r,headers:K([{"anthropic-beta":[...a??[],"managed-agents-2026-04-01"].toString()},r==null?void 0:r.headers])})}add(e,n,r){const{betas:s,...a}=n;return this._client.post(Ae`/v1/sessions/${e}/resources?beta=true`,{body:a,...r,headers:K([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r==null?void 0:r.headers])})}}class $h extends kt{constructor(){super(...arguments),this.events=new SO(this._client),this.resources=new TO(this._client)}create(e,n){const{betas:r,...s}=e;return this._client.post("/v1/sessions?beta=true",{body:s,...n,headers:K([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},n==null?void 0:n.headers])})}retrieve(e,n={},r){const{betas:s}=n??{};return this._client.get(Ae`/v1/sessions/${e}?beta=true`,{...r,headers:K([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r==null?void 0:r.headers])})}update(e,n,r){const{betas:s,...a}=n;return this._client.post(Ae`/v1/sessions/${e}?beta=true`,{body:a,...r,headers:K([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r==null?void 0:r.headers])})}list(e={},n){const{betas:r,...s}=e??{};return this._client.getAPIList("/v1/sessions?beta=true",Or,{query:s,...n,headers:K([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},n==null?void 0:n.headers])})}delete(e,n={},r){const{betas:s}=n??{};return this._client.delete(Ae`/v1/sessions/${e}?beta=true`,{...r,headers:K([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r==null?void 0:r.headers])})}archive(e,n={},r){const{betas:s}=n??{};return this._client.post(Ae`/v1/sessions/${e}/archive?beta=true`,{...r,headers:K([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r==null?void 0:r.headers])})}}$h.Events=SO;$h.Resources=TO;class EO extends kt{create(e,n={},r){const{betas:s,...a}=n??{};return this._client.post(Ae`/v1/skills/${e}/versions?beta=true`,dy({body:a,...r,headers:K([{"anthropic-beta":[...s??[],"skills-2025-10-02"].toString()},r==null?void 0:r.headers])},this._client))}retrieve(e,n,r){const{skill_id:s,betas:a}=n;return this._client.get(Ae`/v1/skills/${s}/versions/${e}?beta=true`,{...r,headers:K([{"anthropic-beta":[...a??[],"skills-2025-10-02"].toString()},r==null?void 0:r.headers])})}list(e,n={},r){const{betas:s,...a}=n??{};return this._client.getAPIList(Ae`/v1/skills/${e}/versions?beta=true`,Or,{query:a,...r,headers:K([{"anthropic-beta":[...s??[],"skills-2025-10-02"].toString()},r==null?void 0:r.headers])})}delete(e,n,r){const{skill_id:s,betas:a}=n;return this._client.delete(Ae`/v1/skills/${s}/versions/${e}?beta=true`,{...r,headers:K([{"anthropic-beta":[...a??[],"skills-2025-10-02"].toString()},r==null?void 0:r.headers])})}}class fy extends kt{constructor(){super(...arguments),this.versions=new EO(this._client)}create(e={},n){const{betas:r,...s}=e??{};return this._client.post("/v1/skills?beta=true",dy({body:s,...n,headers:K([{"anthropic-beta":[...r??[],"skills-2025-10-02"].toString()},n==null?void 0:n.headers])},this._client,!1))}retrieve(e,n={},r){const{betas:s}=n??{};return this._client.get(Ae`/v1/skills/${e}?beta=true`,{...r,headers:K([{"anthropic-beta":[...s??[],"skills-2025-10-02"].toString()},r==null?void 0:r.headers])})}list(e={},n){const{betas:r,...s}=e??{};return this._client.getAPIList("/v1/skills?beta=true",Or,{query:s,...n,headers:K([{"anthropic-beta":[...r??[],"skills-2025-10-02"].toString()},n==null?void 0:n.headers])})}delete(e,n={},r){const{betas:s}=n??{};return this._client.delete(Ae`/v1/skills/${e}?beta=true`,{...r,headers:K([{"anthropic-beta":[...s??[],"skills-2025-10-02"].toString()},r==null?void 0:r.headers])})}}fy.Versions=EO;class AO extends kt{create(e,n,r){const{betas:s,...a}=n;return this._client.post(Ae`/v1/vaults/${e}/credentials?beta=true`,{body:a,...r,headers:K([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r==null?void 0:r.headers])})}retrieve(e,n,r){const{vault_id:s,betas:a}=n;return this._client.get(Ae`/v1/vaults/${s}/credentials/${e}?beta=true`,{...r,headers:K([{"anthropic-beta":[...a??[],"managed-agents-2026-04-01"].toString()},r==null?void 0:r.headers])})}update(e,n,r){const{vault_id:s,betas:a,...i}=n;return this._client.post(Ae`/v1/vaults/${s}/credentials/${e}?beta=true`,{body:i,...r,headers:K([{"anthropic-beta":[...a??[],"managed-agents-2026-04-01"].toString()},r==null?void 0:r.headers])})}list(e,n={},r){const{betas:s,...a}=n??{};return this._client.getAPIList(Ae`/v1/vaults/${e}/credentials?beta=true`,Or,{query:a,...r,headers:K([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r==null?void 0:r.headers])})}delete(e,n,r){const{vault_id:s,betas:a}=n;return this._client.delete(Ae`/v1/vaults/${s}/credentials/${e}?beta=true`,{...r,headers:K([{"anthropic-beta":[...a??[],"managed-agents-2026-04-01"].toString()},r==null?void 0:r.headers])})}archive(e,n,r){const{vault_id:s,betas:a}=n;return this._client.post(Ae`/v1/vaults/${s}/credentials/${e}/archive?beta=true`,{...r,headers:K([{"anthropic-beta":[...a??[],"managed-agents-2026-04-01"].toString()},r==null?void 0:r.headers])})}}class py extends kt{constructor(){super(...arguments),this.credentials=new AO(this._client)}create(e,n){const{betas:r,...s}=e;return this._client.post("/v1/vaults?beta=true",{body:s,...n,headers:K([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},n==null?void 0:n.headers])})}retrieve(e,n={},r){const{betas:s}=n??{};return this._client.get(Ae`/v1/vaults/${e}?beta=true`,{...r,headers:K([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r==null?void 0:r.headers])})}update(e,n,r){const{betas:s,...a}=n;return this._client.post(Ae`/v1/vaults/${e}?beta=true`,{body:a,...r,headers:K([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r==null?void 0:r.headers])})}list(e={},n){const{betas:r,...s}=e??{};return this._client.getAPIList("/v1/vaults?beta=true",Or,{query:s,...n,headers:K([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},n==null?void 0:n.headers])})}delete(e,n={},r){const{betas:s}=n??{};return this._client.delete(Ae`/v1/vaults/${e}?beta=true`,{...r,headers:K([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r==null?void 0:r.headers])})}archive(e,n={},r){const{betas:s}=n??{};return this._client.post(Ae`/v1/vaults/${e}/archive?beta=true`,{...r,headers:K([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r==null?void 0:r.headers])})}}py.Credentials=AO;class Cr extends kt{constructor(){super(...arguments),this.models=new hO(this._client),this.messages=new du(this._client),this.agents=new hy(this._client),this.environments=new cO(this._client),this.sessions=new $h(this._client),this.vaults=new py(this._client),this.files=new dO(this._client),this.skills=new fy(this._client),this.userProfiles=new fO(this._client)}}Cr.Models=hO;Cr.Messages=du;Cr.Agents=hy;Cr.Environments=cO;Cr.Sessions=$h;Cr.Vaults=py;Cr.Files=dO;Cr.Skills=fy;Cr.UserProfiles=fO;class IO extends kt{create(e,n){const{betas:r,...s}=e;return this._client.post("/v1/complete",{body:s,timeout:this._client._options.timeout??6e5,...n,headers:K([{...(r==null?void 0:r.toString())!=null?{"anthropic-beta":r==null?void 0:r.toString()}:void 0},n==null?void 0:n.headers]),stream:e.stream??!1})}}function xO(t){var e;return(e=t==null?void 0:t.output_config)==null?void 0:e.format}function A0(t,e,n){const r=xO(e);return!e||!("parse"in(r??{}))?{...t,content:t.content.map(s=>s.type==="text"?Object.defineProperty({...s},"parsed_output",{value:null,enumerable:!1}):s),parsed_output:null}:kO(t,e)}function kO(t,e,n){let r=null;const s=t.content.map(a=>{if(a.type==="text"){const i=sZ(e,a.text);return r===null&&(r=i),Object.defineProperty({...a},"parsed_output",{value:i,enumerable:!1})}return a});return{...t,content:s,parsed_output:r}}function sZ(t,e){const n=xO(t);if((n==null?void 0:n.type)!=="json_schema")return null;try{return"parse"in n?n.parse(e):JSON.parse(e)}catch(r){throw new ke(`Failed to parse structured output: ${r}`)}}var er,Os,ni,vo,rl,So,To,sl,Eo,es,Ao,al,il,da,ol,cl,Io,sp,I0,ap,ip,op,cp,x0;const k0="__json_buf";function O0(t){return t.type==="tool_use"||t.type==="server_tool_use"}class Bd{constructor(e,n){er.add(this),this.messages=[],this.receivedMessages=[],Os.set(this,void 0),ni.set(this,null),this.controller=new AbortController,vo.set(this,void 0),rl.set(this,()=>{}),So.set(this,()=>{}),To.set(this,void 0),sl.set(this,()=>{}),Eo.set(this,()=>{}),es.set(this,{}),Ao.set(this,!1),al.set(this,!1),il.set(this,!1),da.set(this,!1),ol.set(this,void 0),cl.set(this,void 0),Io.set(this,void 0),ap.set(this,r=>{if(ee(this,al,!0),Mc(r)&&(r=new Ar),r instanceof Ar)return ee(this,il,!0),this._emit("abort",r);if(r instanceof ke)return this._emit("error",r);if(r instanceof Error){const s=new ke(r.message);return s.cause=r,this._emit("error",s)}return this._emit("error",new ke(String(r)))}),ee(this,vo,new Promise((r,s)=>{ee(this,rl,r,"f"),ee(this,So,s,"f")})),ee(this,To,new Promise((r,s)=>{ee(this,sl,r,"f"),ee(this,Eo,s,"f")})),C(this,vo,"f").catch(()=>{}),C(this,To,"f").catch(()=>{}),ee(this,ni,e),ee(this,Io,(n==null?void 0:n.logger)??console)}get response(){return C(this,ol,"f")}get request_id(){return C(this,cl,"f")}async withResponse(){ee(this,da,!0);const e=await C(this,vo,"f");if(!e)throw new Error("Could not resolve a `Response` object");return{data:this,response:e,request_id:e.headers.get("request-id")}}static fromReadableStream(e){const n=new Bd(null);return n._run(()=>n._fromReadableStream(e)),n}static createMessage(e,n,r,{logger:s}={}){const a=new Bd(n,{logger:s});for(const i of n.messages)a._addMessageParam(i);return ee(a,ni,{...n,stream:!0}),a._run(()=>a._createMessage(e,{...n,stream:!0},{...r,headers:{...r==null?void 0:r.headers,"X-Stainless-Helper-Method":"stream"}})),a}_run(e){e().then(()=>{this._emitFinal(),this._emit("end")},C(this,ap,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,n=!0){this.receivedMessages.push(e),n&&this._emit("message",e)}async _createMessage(e,n,r){var i;const s=r==null?void 0:r.signal;let a;s&&(s.aborted&&this.controller.abort(),a=this.controller.abort.bind(this.controller),s.addEventListener("abort",a));try{C(this,er,"m",ip).call(this);const{response:o,data:c}=await e.create({...n,stream:!0},{...r,signal:this.controller.signal}).withResponse();this._connected(o);for await(const u of c)C(this,er,"m",op).call(this,u);if((i=c.controller.signal)!=null&&i.aborted)throw new Ar;C(this,er,"m",cp).call(this)}finally{s&&a&&s.removeEventListener("abort",a)}}_connected(e){this.ended||(ee(this,ol,e),ee(this,cl,e==null?void 0:e.headers.get("request-id")),C(this,rl,"f").call(this,e),this._emit("connect"))}get ended(){return C(this,Ao,"f")}get errored(){return C(this,al,"f")}get aborted(){return C(this,il,"f")}abort(){this.controller.abort()}on(e,n){return(C(this,es,"f")[e]||(C(this,es,"f")[e]=[])).push({listener:n}),this}off(e,n){const r=C(this,es,"f")[e];if(!r)return this;const s=r.findIndex(a=>a.listener===n);return s>=0&&r.splice(s,1),this}once(e,n){return(C(this,es,"f")[e]||(C(this,es,"f")[e]=[])).push({listener:n,once:!0}),this}emitted(e){return new Promise((n,r)=>{ee(this,da,!0),e!=="error"&&this.once("error",r),this.once(e,n)})}async done(){ee(this,da,!0),await C(this,To,"f")}get currentMessage(){return C(this,Os,"f")}async finalMessage(){return await this.done(),C(this,er,"m",sp).call(this)}async finalText(){return await this.done(),C(this,er,"m",I0).call(this)}_emit(e,...n){if(C(this,Ao,"f"))return;e==="end"&&(ee(this,Ao,!0),C(this,sl,"f").call(this));const r=C(this,es,"f")[e];if(r&&(C(this,es,"f")[e]=r.filter(s=>!s.once),r.forEach(({listener:s})=>s(...n))),e==="abort"){const s=n[0];!C(this,da,"f")&&!(r!=null&&r.length)&&Promise.reject(s),C(this,So,"f").call(this,s),C(this,Eo,"f").call(this,s),this._emit("end");return}if(e==="error"){const s=n[0];!C(this,da,"f")&&!(r!=null&&r.length)&&Promise.reject(s),C(this,So,"f").call(this,s),C(this,Eo,"f").call(this,s),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",C(this,er,"m",sp).call(this))}async _fromReadableStream(e,n){var a;const r=n==null?void 0:n.signal;let s;r&&(r.aborted&&this.controller.abort(),s=this.controller.abort.bind(this.controller),r.addEventListener("abort",s));try{C(this,er,"m",ip).call(this),this._connected(null);const i=Hr.fromReadableStream(e,this.controller);for await(const o of i)C(this,er,"m",op).call(this,o);if((a=i.controller.signal)!=null&&a.aborted)throw new Ar;C(this,er,"m",cp).call(this)}finally{r&&s&&r.removeEventListener("abort",s)}}[(Os=new WeakMap,ni=new WeakMap,vo=new WeakMap,rl=new WeakMap,So=new WeakMap,To=new WeakMap,sl=new WeakMap,Eo=new WeakMap,es=new WeakMap,Ao=new WeakMap,al=new WeakMap,il=new WeakMap,da=new WeakMap,ol=new WeakMap,cl=new WeakMap,Io=new WeakMap,ap=new WeakMap,er=new WeakSet,sp=function(){if(this.receivedMessages.length===0)throw new ke("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},I0=function(){if(this.receivedMessages.length===0)throw new ke("stream ended without producing a Message with role=assistant");const n=this.receivedMessages.at(-1).content.filter(r=>r.type==="text").map(r=>r.text);if(n.length===0)throw new ke("stream ended without producing a content block with type=text");return n.join(" ")},ip=function(){this.ended||ee(this,Os,void 0)},op=function(n){if(this.ended)return;const r=C(this,er,"m",x0).call(this,n);switch(this._emit("streamEvent",n,r),n.type){case"content_block_delta":{const s=r.content.at(-1);switch(n.delta.type){case"text_delta":{s.type==="text"&&this._emit("text",n.delta.text,s.text||"");break}case"citations_delta":{s.type==="text"&&this._emit("citation",n.delta.citation,s.citations??[]);break}case"input_json_delta":{O0(s)&&s.input&&this._emit("inputJson",n.delta.partial_json,s.input);break}case"thinking_delta":{s.type==="thinking"&&this._emit("thinking",n.delta.thinking,s.thinking);break}case"signature_delta":{s.type==="thinking"&&this._emit("signature",s.signature);break}default:n.delta}break}case"message_stop":{this._addMessageParam(r),this._addMessage(A0(r,C(this,ni,"f"),{logger:C(this,Io,"f")}),!0);break}case"content_block_stop":{this._emit("contentBlock",r.content.at(-1));break}case"message_start":{ee(this,Os,r);break}}},cp=function(){if(this.ended)throw new ke("stream has ended, this shouldn't happen");const n=C(this,Os,"f");if(!n)throw new ke("request ended without sending any chunks");return ee(this,Os,void 0),A0(n,C(this,ni,"f"),{logger:C(this,Io,"f")})},x0=function(n){let r=C(this,Os,"f");if(n.type==="message_start"){if(r)throw new ke(`Unexpected event order, got ${n.type} before receiving "message_stop"`);return n.message}if(!r)throw new ke(`Unexpected event order, got ${n.type} before "message_start"`);switch(n.type){case"message_stop":return r;case"message_delta":return r.stop_reason=n.delta.stop_reason,r.stop_sequence=n.delta.stop_sequence,r.usage.output_tokens=n.usage.output_tokens,n.usage.input_tokens!=null&&(r.usage.input_tokens=n.usage.input_tokens),n.usage.cache_creation_input_tokens!=null&&(r.usage.cache_creation_input_tokens=n.usage.cache_creation_input_tokens),n.usage.cache_read_input_tokens!=null&&(r.usage.cache_read_input_tokens=n.usage.cache_read_input_tokens),n.usage.server_tool_use!=null&&(r.usage.server_tool_use=n.usage.server_tool_use),r;case"content_block_start":return r.content.push({...n.content_block}),r;case"content_block_delta":{const s=r.content.at(n.index);switch(n.delta.type){case"text_delta":{(s==null?void 0:s.type)==="text"&&(r.content[n.index]={...s,text:(s.text||"")+n.delta.text});break}case"citations_delta":{(s==null?void 0:s.type)==="text"&&(r.content[n.index]={...s,citations:[...s.citations??[],n.delta.citation]});break}case"input_json_delta":{if(s&&O0(s)){let a=s[k0]||"";a+=n.delta.partial_json;const i={...s};Object.defineProperty(i,k0,{value:a,enumerable:!1,writable:!0}),a&&(i.input=yO(a)),r.content[n.index]=i}break}case"thinking_delta":{(s==null?void 0:s.type)==="thinking"&&(r.content[n.index]={...s,thinking:s.thinking+n.delta.thinking});break}case"signature_delta":{(s==null?void 0:s.type)==="thinking"&&(r.content[n.index]={...s,signature:n.delta.signature});break}default:n.delta}return r}case"content_block_stop":return r}},Symbol.asyncIterator)](){const e=[],n=[];let r=!1;return this.on("streamEvent",s=>{const a=n.shift();a?a.resolve(s):e.push(s)}),this.on("end",()=>{r=!0;for(const s of n)s.resolve(void 0);n.length=0}),this.on("abort",s=>{r=!0;for(const a of n)a.reject(s);n.length=0}),this.on("error",s=>{r=!0;for(const a of n)a.reject(s);n.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((a,i)=>n.push({resolve:a,reject:i})).then(a=>a?{value:a,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new Hr(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}class OO extends kt{create(e,n){return this._client.post("/v1/messages/batches",{body:e,...n})}retrieve(e,n){return this._client.get(Ae`/v1/messages/batches/${e}`,n)}list(e={},n){return this._client.getAPIList("/v1/messages/batches",lu,{query:e,...n})}delete(e,n){return this._client.delete(Ae`/v1/messages/batches/${e}`,n)}cancel(e,n){return this._client.post(Ae`/v1/messages/batches/${e}/cancel`,n)}async results(e,n){const r=await this.retrieve(e);if(!r.results_url)throw new ke(`No batch \`results_url\`; Has it finished processing? ${r.processing_status} - ${r.id}`);return this._client.get(r.results_url,{...n,headers:K([{Accept:"application/binary"},n==null?void 0:n.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((s,a)=>Rh.fromResponse(a.response,a.controller))}}class my extends kt{constructor(){super(...arguments),this.batches=new OO(this._client)}create(e,n){e.model in C0&&console.warn(`The model '${e.model}' is deprecated and will reach end-of-life on ${C0[e.model]}
591
- Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),aZ.includes(e.model)&&e.thinking&&e.thinking.type==="enabled"&&console.warn(`Using Claude with ${e.model} and 'thinking.type=enabled' is deprecated. Use 'thinking.type=adaptive' instead which results in better model performance in our testing: https://platform.claude.com/docs/en/build-with-claude/adaptive-thinking`);let r=this._client._options.timeout;if(!e.stream&&r==null){const a=mO[e.model]??void 0;r=this._client.calculateNonstreamingTimeout(e.max_tokens,a)}const s=lO(e.tools,e.messages);return this._client.post("/v1/messages",{body:e,timeout:r??6e5,...n,headers:K([s,n==null?void 0:n.headers]),stream:e.stream??!1})}parse(e,n){return this.create(e,n).then(r=>kO(r,e,{logger:this._client.logger??console}))}stream(e,n){return Bd.createMessage(this,e,n,{logger:this._client.logger??console})}countTokens(e,n){return this._client.post("/v1/messages/count_tokens",{body:e,...n})}}const C0={"claude-1.3":"November 6th, 2024","claude-1.3-100k":"November 6th, 2024","claude-instant-1.1":"November 6th, 2024","claude-instant-1.1-100k":"November 6th, 2024","claude-instant-1.2":"November 6th, 2024","claude-3-sonnet-20240229":"July 21st, 2025","claude-3-opus-20240229":"January 5th, 2026","claude-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025","claude-3-7-sonnet-latest":"February 19th, 2026","claude-3-7-sonnet-20250219":"February 19th, 2026","claude-3-5-haiku-latest":"February 19th, 2026","claude-3-5-haiku-20241022":"February 19th, 2026","claude-opus-4-0":"June 15th, 2026","claude-opus-4-20250514":"June 15th, 2026","claude-sonnet-4-0":"June 15th, 2026","claude-sonnet-4-20250514":"June 15th, 2026"},aZ=["claude-mythos-preview","claude-opus-4-6"];my.Batches=OO;class CO extends kt{retrieve(e,n={},r){const{betas:s}=n??{};return this._client.get(Ae`/v1/models/${e}`,{...r,headers:K([{...(s==null?void 0:s.toString())!=null?{"anthropic-beta":s==null?void 0:s.toString()}:void 0},r==null?void 0:r.headers])})}list(e={},n){const{betas:r,...s}=e??{};return this._client.getAPIList("/v1/models",lu,{query:s,...n,headers:K([{...(r==null?void 0:r.toString())!=null?{"anthropic-beta":r==null?void 0:r.toString()}:void 0},n==null?void 0:n.headers])})}}var up={};const ul=t=>{var e,n,r,s;if(typeof globalThis.process<"u")return((e=up==null?void 0:up[t])==null?void 0:e.trim())||void 0;if(typeof globalThis.Deno<"u")return((s=(r=(n=globalThis.Deno.env)==null?void 0:n.get)==null?void 0:r.call(n,t))==null?void 0:s.trim())||void 0};var tg,gy,Zl,RO;const iZ="\\n\\nHuman:",oZ="\\n\\nAssistant:";class Ot{constructor({baseURL:e=ul("ANTHROPIC_BASE_URL"),apiKey:n=ul("ANTHROPIC_API_KEY")??null,authToken:r=ul("ANTHROPIC_AUTH_TOKEN")??null,...s}={}){tg.add(this),Zl.set(this,void 0);const a={apiKey:n,authToken:r,...s,baseURL:e||"https://api.anthropic.com"};if(!a.dangerouslyAllowBrowser&&SV())throw new ke(`It looks like you're running in a browser-like environment.
592
-
593
- This is disabled by default, as it risks exposing your secret API credentials to attackers.
594
- If you understand the risks and have appropriate mitigations in place,
595
- you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
596
-
597
- new Anthropic({ apiKey, dangerouslyAllowBrowser: true });
598
- `);this.baseURL=a.baseURL,this.timeout=a.timeout??gy.DEFAULT_TIMEOUT,this.logger=a.logger??console;const i="warn";this.logLevel=i,this.logLevel=h0(a.logLevel,"ClientOptions.logLevel",this)??h0(ul("ANTHROPIC_LOG"),"process.env['ANTHROPIC_LOG']",this)??i,this.fetchOptions=a.fetchOptions,this.maxRetries=a.maxRetries??2,this.fetch=a.fetch??xV(),ee(this,Zl,OV),this._options=a,this.apiKey=typeof n=="string"?n:null,this.authToken=r}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,authToken:this.authToken,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:n}){if(!(e.get("x-api-key")||e.get("authorization"))&&!(this.apiKey&&e.get("x-api-key"))&&!n.has("x-api-key")&&!(this.authToken&&e.get("authorization"))&&!n.has("authorization"))throw new Error('Could not resolve authentication method. Expected either apiKey or authToken to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted')}async authHeaders(e){return K([await this.apiKeyAuth(e),await this.bearerAuth(e)])}async apiKeyAuth(e){if(this.apiKey!=null)return K([{"X-Api-Key":this.apiKey}])}async bearerAuth(e){if(this.authToken!=null)return K([{Authorization:`Bearer ${this.authToken}`}])}stringifyQuery(e){return CV(e)}getUserAgent(){return`${this.constructor.name}/JS ${li}`}defaultIdempotencyKey(){return`stainless-node-retry-${Bk()}`}makeStatusError(e,n,r,s){return fn.generate(e,n,r,s)}buildURL(e,n,r){const s=!C(this,tg,"m",RO).call(this)&&r||this.baseURL,a=yV(e)?new URL(e):new URL(s+(s.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),i=this.defaultQuery(),o=Object.fromEntries(a.searchParams);return(!a0(i)||!a0(o))&&(n={...o,...i,...n}),typeof n=="object"&&n&&!Array.isArray(n)&&(a.search=this.stringifyQuery(n)),a.toString()}_calculateNonstreamingTimeout(e){if(3600*e/128e3>600)throw new ke("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#streaming-responses for more details");return 600*1e3}async prepareOptions(e){}async prepareRequest(e,{url:n,options:r}){}get(e,n){return this.methodRequest("get",e,n)}post(e,n){return this.methodRequest("post",e,n)}patch(e,n){return this.methodRequest("patch",e,n)}put(e,n){return this.methodRequest("put",e,n)}delete(e,n){return this.methodRequest("delete",e,n)}methodRequest(e,n,r){return this.request(Promise.resolve(r).then(s=>({method:e,path:n,...s})))}request(e,n=null){return new Ch(this,this.makeRequest(e,n,void 0))}async makeRequest(e,n,r){var w,g;const s=await e,a=s.maxRetries??this.maxRetries;n==null&&(n=a),await this.prepareOptions(s);const{req:i,url:o,timeout:c}=await this.buildRequest(s,{retryCount:a-n});await this.prepareRequest(i,{url:o,options:s});const u="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),l=r===void 0?"":`, retryOf: ${r}`,d=Date.now();if(_n(this).debug(`[${u}] sending request`,_a({retryOfRequestLogID:r,method:s.method,url:o,options:s,headers:i.headers})),(w=s.signal)!=null&&w.aborted)throw new Ar;const f=new AbortController,h=await this.fetchWithTimeout(o,i,c,f).catch(Km),m=Date.now();if(h instanceof globalThis.Error){const b=`retrying, ${n} attempts remaining`;if((g=s.signal)!=null&&g.aborted)throw new Ar;const S=Mc(h)||/timed? ?out/i.test(String(h)+("cause"in h?String(h.cause):""));if(n)return _n(this).info(`[${u}] connection ${S?"timed out":"failed"} - ${b}`),_n(this).debug(`[${u}] connection ${S?"timed out":"failed"} (${b})`,_a({retryOfRequestLogID:r,url:o,durationMs:m-d,message:h.message})),this.retryRequest(s,n,r??u);throw _n(this).info(`[${u}] connection ${S?"timed out":"failed"} - error; no more retries left`),_n(this).debug(`[${u}] connection ${S?"timed out":"failed"} (error; no more retries left)`,_a({retryOfRequestLogID:r,url:o,durationMs:m-d,message:h.message})),S?new zk:new Oh({cause:h})}const _=[...h.headers.entries()].filter(([b])=>b==="request-id").map(([b,S])=>", "+b+": "+JSON.stringify(S)).join(""),y=`[${u}${l}${_}] ${i.method} ${o} ${h.ok?"succeeded":"failed"} with status ${h.status} in ${m-d}ms`;if(!h.ok){const b=await this.shouldRetry(h);if(n&&b){const M=`retrying, ${n} attempts remaining`;return await kV(h.body),_n(this).info(`${y} - ${M}`),_n(this).debug(`[${u}] response error (${M})`,_a({retryOfRequestLogID:r,url:h.url,status:h.status,headers:h.headers,durationMs:m-d})),this.retryRequest(s,n,r??u,h.headers)}const S=b?"error; no more retries left":"error; not retryable";_n(this).info(`${y} - ${S}`);const I=await h.text().catch(M=>Km(M).message),T=Xk(I),x=T?void 0:I;throw _n(this).debug(`[${u}] response error (${S})`,_a({retryOfRequestLogID:r,url:h.url,status:h.status,headers:h.headers,message:x,durationMs:Date.now()-d})),this.makeStatusError(h.status,T,x,h.headers)}return _n(this).info(y),_n(this).debug(`[${u}] response start`,_a({retryOfRequestLogID:r,url:h.url,status:h.status,headers:h.headers,durationMs:m-d})),{response:h,options:s,controller:f,requestLogID:u,retryOfRequestLogID:r,startTime:d}}getAPIList(e,n,r){return this.requestAPIList(n,r&&"then"in r?r.then(s=>({method:"get",path:e,...s})):{method:"get",path:e,...r})}requestAPIList(e,n){const r=this.makeRequest(n,null,void 0);return new DV(this,r,e)}async fetchWithTimeout(e,n,r,s){const{signal:a,method:i,...o}=n||{},c=this._makeAbort(s);a&&a.addEventListener("abort",c,{once:!0});const u=setTimeout(c,r),l=globalThis.ReadableStream&&o.body instanceof globalThis.ReadableStream||typeof o.body=="object"&&o.body!==null&&Symbol.asyncIterator in o.body,d={signal:s.signal,...l?{duplex:"half"}:{},method:"GET",...o};i&&(d.method=i.toUpperCase());try{return await this.fetch.call(void 0,e,d)}finally{clearTimeout(u)}}async shouldRetry(e){const n=e.headers.get("x-should-retry");return n==="true"?!0:n==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,n,r,s){let a;const i=s==null?void 0:s.get("retry-after-ms");if(i){const c=parseFloat(i);Number.isNaN(c)||(a=c)}const o=s==null?void 0:s.get("retry-after");if(o&&!a){const c=parseFloat(o);Number.isNaN(c)?a=Date.parse(o)-Date.now():a=c*1e3}if(a===void 0){const c=e.maxRetries??this.maxRetries;a=this.calculateDefaultRetryTimeoutMillis(n,c)}return await vV(a),this.makeRequest(e,n-1,r)}calculateDefaultRetryTimeoutMillis(e,n){const a=n-e,i=Math.min(.5*Math.pow(2,a),8),o=1-Math.random()*.25;return i*o*1e3}calculateNonstreamingTimeout(e,n){if(36e5*e/128e3>6e5||n!=null&&e>n)throw new ke("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#long-requests for more details");return 6e5}async buildRequest(e,{retryCount:n=0}={}){const r={...e},{method:s,path:a,query:i,defaultBaseURL:o}=r,c=this.buildURL(a,i,o);"timeout"in r&&bV("timeout",r.timeout),r.timeout=r.timeout??this.timeout;const{bodyHeaders:u,body:l}=this.buildBody({options:r}),d=await this.buildHeaders({options:e,method:s,bodyHeaders:u,retryCount:n});return{req:{method:s,headers:d,...r.signal&&{signal:r.signal},...globalThis.ReadableStream&&l instanceof globalThis.ReadableStream&&{duplex:"half"},...l&&{body:l},...this.fetchOptions??{},...r.fetchOptions??{}},url:c,timeout:r.timeout}}async buildHeaders({options:e,method:n,bodyHeaders:r,retryCount:s}){let a={};this.idempotencyHeader&&n!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),a[this.idempotencyHeader]=e.idempotencyKey);const i=K([a,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(s),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...IV(),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":"true"}:void 0,"anthropic-version":"2023-06-01"},await this.authHeaders(e),this._options.defaultHeaders,r,e.headers]);return this.validateHeaders(i),i.values}_makeAbort(e){return()=>e.abort()}buildBody({options:{body:e,headers:n}}){if(!e)return{bodyHeaders:void 0,body:void 0};const r=K([n]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&r.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:typeof e=="object"&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")?{bodyHeaders:void 0,body:Qk(e)}:typeof e=="object"&&r.values.get("content-type")==="application/x-www-form-urlencoded"?{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(e)}:C(this,Zl,"f").call(this,{body:e,headers:r})}}gy=Ot,Zl=new WeakMap,tg=new WeakSet,RO=function(){return this.baseURL!=="https://api.anthropic.com"};Ot.Anthropic=gy;Ot.HUMAN_PROMPT=iZ;Ot.AI_PROMPT=oZ;Ot.DEFAULT_TIMEOUT=6e5;Ot.AnthropicError=ke;Ot.APIError=fn;Ot.APIConnectionError=Oh;Ot.APIConnectionTimeoutError=zk;Ot.APIUserAbortError=Ar;Ot.NotFoundError=Wk;Ot.ConflictError=Gk;Ot.RateLimitError=Kk;Ot.BadRequestError=Hk;Ot.AuthenticationError=Vk;Ot.InternalServerError=Jk;Ot.PermissionDeniedError=Zk;Ot.UnprocessableEntityError=qk;Ot.toFile=ZV;class hu extends Ot{constructor(){super(...arguments),this.completions=new IO(this),this.messages=new my(this),this.models=new CO(this),this.beta=new Cr(this)}}hu.Completions=IO;hu.Messages=my;hu.Models=CO;hu.Beta=Cr;const cZ=t=>t,uZ={"claude-opus-4-7":16384,"claude-opus-4-6":16384,"claude-sonnet-4-6":16384,"claude-opus-4-5":16384,"claude-sonnet-4-5":16384,"claude-haiku-4-5":16384,"claude-opus-4-1":16384,"claude-sonnet-4":16384,"claude-opus-4":16384,"claude-3-7-sonnet":8192,"claude-3-5-sonnet":8192,"claude-3-5-haiku":8192,"claude-3-opus":4096,"claude-3-sonnet":4096,"claude-3-haiku":4096},R0=4096;function lZ(t){var e;return t?((e=Object.entries(uZ).find(([n])=>t.startsWith(n)))==null?void 0:e[1])??R0:R0}function dZ(t){return!!(t.tools&&t.tools.length>0)}function hZ(t){var e;for(const n of t.messages??[])if(typeof n.content!="string"){for(const r of n.content??[])if(typeof r=="object"&&r!=null&&r.type==="document"&&typeof r.citations=="object"&&((e=r.citations)!=null&&e.enabled))return!0}return!1}function fZ(t){return!!(t.thinking&&(t.thinking.type==="enabled"||t.thinking.type==="adaptive"))}function pZ(t){var e,n;return!!((n=(e=t.context_management)==null?void 0:e.edits)!=null&&n.some(r=>r.type==="compact_20260112"))}function mZ(t){return"input_schema"in t}function gZ(t){return typeof t=="object"&&t!==null&&"type"in t&&("name"in t||"mcp_server_name"in t)&&typeof t.type=="string"&&["text_editor_","computer_","bash_","web_search_","web_fetch_","str_replace_editor_","str_replace_based_edit_tool_","code_execution_","memory_","tool_search_","mcp_toolset"].some(e=>typeof t.type=="string"&&t.type.startsWith(e))}function _Z(t,e,...n){return Array.from(new Set([...t??[],...e??[],...n.flatMap(r=>Array.from(r))]))}function yZ(t){if(typeof t.content=="string")return t.content;if(Array.isArray(t.content)&&t.content.length>=1&&"input"in t.content[0])return typeof t.content[0].input=="string"?t.content[0].input:JSON.stringify(t.content[0].input);if(Array.isArray(t.content)&&t.content.length>=1&&"text"in t.content[0]&&typeof t.content[0].text=="string")return t.content[0].text}var wZ=class extends Jr{constructor(e,n){const r=typeof e=="string"?{...n??{},model:e}:e??{};super(r??{});p(this,"lc_serializable",!0);p(this,"anthropicApiKey");p(this,"apiKey");p(this,"apiUrl");p(this,"temperature");p(this,"topK");p(this,"topP");p(this,"maxTokens");p(this,"modelName","claude-sonnet-4-5-20250929");p(this,"model","claude-sonnet-4-5-20250929");p(this,"invocationKwargs");p(this,"stopSequences");p(this,"streaming",!1);p(this,"clientOptions");p(this,"thinking",{type:"disabled"});p(this,"contextManagement");p(this,"outputConfig");p(this,"inferenceGeo");p(this,"batchClient");p(this,"streamingClient");p(this,"streamUsage",!0);p(this,"betas");p(this,"createClient");if(this._addVersion("@langchain/anthropic","1.3.28"),this.anthropicApiKey=(r==null?void 0:r.apiKey)??(r==null?void 0:r.anthropicApiKey)??It("ANTHROPIC_API_KEY"),!this.anthropicApiKey&&!(r!=null&&r.createClient))throw new Error("Anthropic API key not found");this.clientOptions=(r==null?void 0:r.clientOptions)??{},this.apiKey=this.anthropicApiKey,this.apiUrl=r==null?void 0:r.anthropicApiUrl,this.modelName=(r==null?void 0:r.model)??(r==null?void 0:r.modelName)??this.model,this.model=this.modelName,this.invocationKwargs=(r==null?void 0:r.invocationKwargs)??{},this.topP=(r==null?void 0:r.topP)??this.topP,this.temperature=(r==null?void 0:r.temperature)??this.temperature,this.topK=(r==null?void 0:r.topK)??this.topK,this.maxTokens=(r==null?void 0:r.maxTokens)??lZ(this.model),this.stopSequences=(r==null?void 0:r.stopSequences)??this.stopSequences,this.streaming=(r==null?void 0:r.streaming)??!1,this.streamUsage=(r==null?void 0:r.streamUsage)??this.streamUsage,this.thinking=(r==null?void 0:r.thinking)??this.thinking,this.contextManagement=(r==null?void 0:r.contextManagement)??this.contextManagement,this.outputConfig=(r==null?void 0:r.outputConfig)??this.outputConfig,this.inferenceGeo=(r==null?void 0:r.inferenceGeo)??this.inferenceGeo,this.betas=(r==null?void 0:r.betas)??this.betas,this.createClient=(r==null?void 0:r.createClient)??(s=>new hu(s))}static lc_name(){return"ChatAnthropic"}get lc_secrets(){return{anthropicApiKey:"ANTHROPIC_API_KEY",apiKey:"ANTHROPIC_API_KEY"}}get lc_aliases(){return{modelName:"model"}}getLsParams(e){const n=this.invocationParams(e);return{ls_provider:"anthropic",ls_model_name:this.model,ls_model_type:"chat",ls_temperature:n.temperature??void 0,ls_max_tokens:n.max_tokens??void 0,ls_stop:e.stop}}formatStructuredToolToAnthropic(e){if(e)return e.map(n=>{var r;if(vs(n)&&((r=n.extras)!=null&&r.providerToolDefinition))return n.extras.providerToolDefinition;if(gZ(n)||mZ(n))return n;if(Gi(n))return{name:n.function.name,description:n.function.description,input_schema:n.function.parameters};if(vs(n))return{name:n.name,description:n.description,input_schema:Lt(n.schema)?lt(n.schema):n.schema,...n.extras?XH.parse(n.extras):{}};throw new Error(`Unknown tool type passed to ChatAnthropic: ${JSON.stringify(n,null,2)}`)})}bindTools(e,n){return this.withConfig({tools:this.formatStructuredToolToAnthropic(e),...n})}invocationParams(e){var c,u,l;const n=JH(e==null?void 0:e.tool_choice),r=(c=e==null?void 0:e.tools)==null?void 0:c.reduce((d,f)=>{if(typeof f=="object"&&"type"in f&&f.type in Qv){const h=Qv[f.type];if(!d.includes(h))return[...d,h]}return d},[]),s=(()=>{const d={...this.outputConfig,...e==null?void 0:e.outputConfig};return e!=null&&e.outputFormat&&!d.format&&(d.format=e.outputFormat),Object.keys(d).length>0?d:void 0})(),a=(l=(u=this.contextManagement)==null?void 0:u.edits)!=null&&l.some(d=>d.type==="compact_20260112")?["compact-2026-01-12"]:[],i=dV(this.model,s),o={model:this.model,stop_sequences:(e==null?void 0:e.stop)??this.stopSequences,stream:this.streaming,max_tokens:this.maxTokens,tools:this.formatStructuredToolToAnthropic(e==null?void 0:e.tools),tool_choice:n,thinking:this.thinking,context_management:this.contextManagement,...this.invocationKwargs,container:e==null?void 0:e.container,betas:_Z(this.betas,e==null?void 0:e.betas,r??[],a,i),output_config:s,inference_geo:(e==null?void 0:e.inferenceGeo)??this.inferenceGeo,mcp_servers:e==null?void 0:e.mcp_servers};return hV({model:this.model,thinking:this.thinking,topK:this.topK,topP:this.topP,temperature:this.temperature}),Object.assign(o,fV({model:this.model,thinking:this.thinking,topK:this.topK,topP:this.topP,temperature:this.temperature})),o}_identifyingParams(){return{model_name:this.model,...this.invocationParams()}}identifyingParams(){return{model_name:this.model,...this.invocationParams()}}async*_streamResponseChunks(e,n,r){var u;const s=this.invocationParams(n);let a=t0(e);n.cache_control&&(a=n0(a,n.cache_control));const i={...s,...a,stream:!0},o=!dZ(i)&&!hZ(i)&&!fZ(i)&&!pZ(i),c=await this.createStreamWithRetry(i,{headers:n.headers,signal:n.signal});for await(const l of c){if((u=n.signal)!=null&&u.aborted){c.controller.abort();return}const d=this.streamUsage??n.streamUsage,f=pV(l,{streamUsage:d,coerceContentToString:o});if(!f)continue;const{chunk:h}=f,m=yZ(h),_=new qn({message:new Qe({content:h.content,additional_kwargs:h.additional_kwargs,tool_call_chunks:h.tool_call_chunks,usage_metadata:d?h.usage_metadata:void 0,response_metadata:h.response_metadata,id:h.id}),text:m??""});yield _,await(r==null?void 0:r.handleLLMNewToken(m??"",void 0,void 0,void 0,void 0,{chunk:_}))}}async _generateNonStreaming(e,n,r,s){let a=t0(e);s&&(a=n0(a,s));const{content:i,...o}=await this.completionWithRetry({...n,stream:!1,...a},r),c=mV(i,o),{role:u,type:l,...d}=o;return{generations:c,llmOutput:d}}async _generate(e,n,r){var a;if((a=n.signal)==null||a.throwIfAborted(),this.stopSequences&&n.stop)throw new Error('"stopSequence" parameter found in input and default params');const s=this.invocationParams(n);if(s.stream){let i;const o=this._streamResponseChunks(e,n,r);for await(const c of o)i===void 0?i=c:i=i.concat(c);if(i===void 0)throw new Error("No chunks returned from Anthropic API.");return{generations:[{text:i.text,message:i.message}]}}else return this._generateNonStreaming(e,s,{signal:n.signal,headers:n.headers},n.cache_control)}async createStreamWithRetry(e,n){if(!this.streamingClient){const i=this.apiUrl?{baseURL:this.apiUrl}:void 0;this.streamingClient=this.createClient({dangerouslyAllowBrowser:!0,...this.clientOptions,...i,apiKey:this.apiKey,maxRetries:0})}const{betas:r,...s}=e,a=async()=>{var i;try{return(i=e==null?void 0:e.betas)!=null&&i.length?await this.streamingClient.beta.messages.create({...s,betas:r,...this.invocationKwargs,stream:!0},n):await this.streamingClient.messages.create({...s,...this.invocationKwargs,stream:!0},n)}catch(o){throw r0(o)}};return this.caller.call(a)}async completionWithRetry(e,n){if(!this.batchClient){const i=this.apiUrl?{baseURL:this.apiUrl}:void 0;this.batchClient=this.createClient({dangerouslyAllowBrowser:!0,...this.clientOptions,...i,apiKey:this.apiKey,maxRetries:0})}const{betas:r,...s}=e,a=async()=>{var i;try{return(i=e==null?void 0:e.betas)!=null&&i.length?await this.batchClient.beta.messages.create({...s,...this.invocationKwargs,betas:r},n):await this.batchClient.messages.create({...s,...this.invocationKwargs},n)}catch(o){throw r0(o)}};return this.caller.callWithOptions({signal:n.signal??void 0},a)}_llmType(){return"anthropic"}get profile(){return gV[this.model]??{}}withStructuredOutput(e,n){var u,l;let r,s;const{schema:a,name:i,includeRaw:o}={...n,schema:e};let c=(n==null?void 0:n.method)??"functionCalling";if(c==="jsonMode"&&(console.warn('"jsonMode" is not supported for Anthropic models. Falling back to "jsonSchema".'),c="jsonSchema"),c==="jsonSchema"){s=Fi(a);const d=cZ(lt(a));r=this.withConfig({outputVersion:"v0",outputConfig:{format:{type:"json_schema",schema:d}},ls_structured_output_format:{kwargs:{method:"json_schema"},schema:d}})}else if(c==="functionCalling"){let d=i??"extract",f;if(Lt(a)||cr(a)){const h=lt(a);f=[{name:d,description:h.description??"A function available to call.",input_schema:h}]}else typeof a.name=="string"&&typeof a.description=="string"&&typeof a.input_schema=="object"&&a.input_schema!=null?(f=[a],d=a.name):f=[{name:d,description:a.description??"",input_schema:a}];if(s=Yc(a,d,KH),((u=this.thinking)==null?void 0:u.type)==="enabled"||((l=this.thinking)==null?void 0:l.type)==="adaptive"){const h="Anthropic structured output relies on forced tool calling, which is not supported when `thinking` is enabled. This method will raise OutputParserException if tool calls are not generated. Consider disabling `thinking` or adjust your prompt to ensure the tool is called.";console.warn(h),r=this.withConfig({outputVersion:"v0",tools:f,ls_structured_output_format:{kwargs:{method:"functionCalling"},schema:lt(a)}});const m=_=>{if(!_.tool_calls||_.tool_calls.length===0)throw new Error(h);return _};r=r.pipe(m)}else r=this.withConfig({outputVersion:"v0",tools:f,tool_choice:{type:"tool",name:d},ls_structured_output_format:{kwargs:{method:"functionCalling"},schema:lt(a)}})}else throw new TypeError(`Unrecognized structured output method '${c}'. Expected 'functionCalling' or 'jsonSchema'`);return Ji(r,s,o,o?"StructuredOutputRunnable":"ChatAnthropicStructuredOutput")}},$0=class extends wZ{};const bZ=Oe({command:Le("view"),path:Ve()}),vZ=Oe({command:Le("create"),path:Ve(),file_text:Ve()}),SZ=Oe({command:Le("str_replace"),path:Ve(),old_str:Ve(),new_str:Ve()}),TZ=Oe({command:Le("insert"),path:Ve(),insert_line:st(),insert_text:Ve()}),EZ=Oe({command:Le("delete"),path:Ve()}),AZ=Oe({command:Le("rename"),old_path:Ve(),new_path:Ve()});dh("command",[bZ,vZ,SZ,TZ,EZ,AZ]);const IZ=Oe({command:Le("view"),path:Ve(),view_range:w_([st(),st()]).optional()}),xZ=Oe({command:Le("str_replace"),path:Ve(),old_str:Ve(),new_str:Ve()}),kZ=Oe({command:Le("create"),path:Ve(),file_text:Ve()}),OZ=Oe({command:Le("insert"),path:Ve(),insert_line:st(),new_str:Ve()});dh("command",[IZ,xZ,kZ,OZ]);const kr=w_([st(),st()]),$O=Oe({action:Le("screenshot")}),NO=Oe({action:Le("left_click"),coordinate:kr}),PO=Oe({action:Le("right_click"),coordinate:kr}),MO=Oe({action:Le("middle_click"),coordinate:kr}),LO=Oe({action:Le("double_click"),coordinate:kr}),jO=Oe({action:Le("triple_click"),coordinate:kr}),UO=Oe({action:Le("left_click_drag"),start_coordinate:kr,end_coordinate:kr}),DO=Oe({action:Le("left_mouse_down"),coordinate:kr}),FO=Oe({action:Le("left_mouse_up"),coordinate:kr}),BO=Oe({action:Le("scroll"),coordinate:kr,scroll_direction:hh(["up","down","left","right"]),scroll_amount:st()}),zO=Oe({action:Le("type"),text:Ve()}),HO=Oe({action:Le("key"),key:Ve()}),VO=Oe({action:Le("mouse_move"),coordinate:kr}),ZO=Oe({action:Le("hold_key"),key:Ve()}),WO=Oe({action:Le("wait"),duration:st().optional()}),CZ=Oe({action:Le("zoom"),region:w_([st(),st(),st(),st()])});dh("action",[$O,NO,PO,MO,LO,jO,UO,DO,FO,BO,zO,HO,VO,ZO,WO]);dh("action",[$O,NO,PO,MO,LO,jO,UO,DO,FO,BO,zO,HO,VO,ZO,WO,CZ]);const RZ=Oe({command:Ve().describe("The bash command to run")}),$Z=Oe({restart:Le(!0).describe("Set to true to restart the bash session")});nu([RZ,$Z]);function NZ(t,e){var n;return new Qe({content:t.content??"",additional_kwargs:t.thinking&&t.thinking!==""?{reasoning_content:t.thinking}:{},tool_call_chunks:(n=t.tool_calls)==null?void 0:n.map(r=>({name:r.function.name,args:JSON.stringify(r.function.arguments),type:"tool_call_chunk",index:0,id:Hc()})),response_metadata:{...e==null?void 0:e.responseMetadata,model_provider:"ollama"},usage_metadata:e==null?void 0:e.usageMetadata})}function N0(t){const e=t.match(/^data:.*?;base64,(.*)$/);return e?e[1]:""}function PZ(t){var r,s,a,i;if(typeof t.content=="string"){if((r=t.tool_calls)!=null&&r.length){const o=t.tool_calls.map(c=>({id:c.id,type:"function",function:{name:c.name,arguments:c.args}}));return[{role:"assistant",content:t.content,tool_calls:o}]}return[{role:"assistant",content:t.content}]}const e=t.content.filter(o=>o.type==="text"&&typeof o.text=="string").map(o=>({role:"assistant",content:o.text}));let n;if(t.content.find(o=>o.type==="tool_use")&&((s=t.tool_calls)!=null&&s.length)){const o=(a=t.tool_calls)==null?void 0:a.map(c=>({id:c.id,type:"function",function:{name:c.name,arguments:c.args}}));o&&(n={role:"assistant",tool_calls:o,content:""})}else if(t.content.find(o=>o.type==="tool_use")&&!((i=t.tool_calls)!=null&&i.length))throw new Error("'tool_use' content type is not supported without tool calls.");return[...e,...n?[n]:[]]}function MZ(t){return typeof t.content=="string"?[{role:"user",content:t.content}]:t.content.map(e=>{if(e.type==="text")return{role:"user",content:e.text};if(e.type==="image_url"){if(typeof e.image_url=="string")return{role:"user",content:"",images:[N0(e.image_url)]};if(e.image_url.url&&typeof e.image_url.url=="string")return{role:"user",content:"",images:[N0(e.image_url.url)]}}throw new Error(`Unsupported content type: ${e.type}`)})}function LZ(t){if(typeof t.content=="string")return[{role:"system",content:t.content}];if(t.content.every(e=>e.type==="text"&&typeof e.text=="string"))return t.content.map(e=>({role:"system",content:e.text}));throw new Error(`Unsupported content type(s): ${t.content.map(e=>e.type).join(", ")}`)}function jZ(t){if(typeof t.content!="string")throw new Error("Non string tool message content is not supported");return[{role:"tool",content:t.content}]}function UZ(t){return t.flatMap(e=>{if(["human","generic"].includes(e._getType()))return MZ(e);if(e._getType()==="ai")return PZ(e);if(e._getType()==="system")return LZ(e);if(e._getType()==="tool")return jZ(e);throw new Error(`Unsupported message type: ${e._getType()}`)})}var Yt=typeof globalThis<"u"&&globalThis||typeof self<"u"&&self||typeof global<"u"&&global||{},yn={searchParams:"URLSearchParams"in Yt,iterable:"Symbol"in Yt&&"iterator"in Symbol,blob:"FileReader"in Yt&&"Blob"in Yt&&function(){try{return new Blob,!0}catch{return!1}}(),formData:"FormData"in Yt,arrayBuffer:"ArrayBuffer"in Yt};function DZ(t){return t&&DataView.prototype.isPrototypeOf(t)}if(yn.arrayBuffer)var FZ=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],BZ=ArrayBuffer.isView||function(t){return t&&FZ.indexOf(Object.prototype.toString.call(t))>-1};function eo(t){if(typeof t!="string"&&(t=String(t)),/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(t)||t==="")throw new TypeError('Invalid character in header field name: "'+t+'"');return t.toLowerCase()}function _y(t){return typeof t!="string"&&(t=String(t)),t}function yy(t){var e={next:function(){var n=t.shift();return{done:n===void 0,value:n}}};return yn.iterable&&(e[Symbol.iterator]=function(){return e}),e}function jt(t){this.map={},t instanceof jt?t.forEach(function(e,n){this.append(n,e)},this):Array.isArray(t)?t.forEach(function(e){if(e.length!=2)throw new TypeError("Headers constructor: expected name/value pair to be length 2, found"+e.length);this.append(e[0],e[1])},this):t&&Object.getOwnPropertyNames(t).forEach(function(e){this.append(e,t[e])},this)}jt.prototype.append=function(t,e){t=eo(t),e=_y(e);var n=this.map[t];this.map[t]=n?n+", "+e:e};jt.prototype.delete=function(t){delete this.map[eo(t)]};jt.prototype.get=function(t){return t=eo(t),this.has(t)?this.map[t]:null};jt.prototype.has=function(t){return this.map.hasOwnProperty(eo(t))};jt.prototype.set=function(t,e){this.map[eo(t)]=_y(e)};jt.prototype.forEach=function(t,e){for(var n in this.map)this.map.hasOwnProperty(n)&&t.call(e,this.map[n],n,this)};jt.prototype.keys=function(){var t=[];return this.forEach(function(e,n){t.push(n)}),yy(t)};jt.prototype.values=function(){var t=[];return this.forEach(function(e){t.push(e)}),yy(t)};jt.prototype.entries=function(){var t=[];return this.forEach(function(e,n){t.push([n,e])}),yy(t)};yn.iterable&&(jt.prototype[Symbol.iterator]=jt.prototype.entries);function lp(t){if(!t._noBody){if(t.bodyUsed)return Promise.reject(new TypeError("Already read"));t.bodyUsed=!0}}function GO(t){return new Promise(function(e,n){t.onload=function(){e(t.result)},t.onerror=function(){n(t.error)}})}function zZ(t){var e=new FileReader,n=GO(e);return e.readAsArrayBuffer(t),n}function HZ(t){var e=new FileReader,n=GO(e),r=/charset=([A-Za-z0-9_-]+)/.exec(t.type),s=r?r[1]:"utf-8";return e.readAsText(t,s),n}function VZ(t){for(var e=new Uint8Array(t),n=new Array(e.length),r=0;r<e.length;r++)n[r]=String.fromCharCode(e[r]);return n.join("")}function P0(t){if(t.slice)return t.slice(0);var e=new Uint8Array(t.byteLength);return e.set(new Uint8Array(t)),e.buffer}function qO(){return this.bodyUsed=!1,this._initBody=function(t){this.bodyUsed=this.bodyUsed,this._bodyInit=t,t?typeof t=="string"?this._bodyText=t:yn.blob&&Blob.prototype.isPrototypeOf(t)?this._bodyBlob=t:yn.formData&&FormData.prototype.isPrototypeOf(t)?this._bodyFormData=t:yn.searchParams&&URLSearchParams.prototype.isPrototypeOf(t)?this._bodyText=t.toString():yn.arrayBuffer&&yn.blob&&DZ(t)?(this._bodyArrayBuffer=P0(t.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):yn.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(t)||BZ(t))?this._bodyArrayBuffer=P0(t):this._bodyText=t=Object.prototype.toString.call(t):(this._noBody=!0,this._bodyText=""),this.headers.get("content-type")||(typeof t=="string"?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):yn.searchParams&&URLSearchParams.prototype.isPrototypeOf(t)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},yn.blob&&(this.blob=function(){var t=lp(this);if(t)return t;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))}),this.arrayBuffer=function(){if(this._bodyArrayBuffer){var t=lp(this);return t||(ArrayBuffer.isView(this._bodyArrayBuffer)?Promise.resolve(this._bodyArrayBuffer.buffer.slice(this._bodyArrayBuffer.byteOffset,this._bodyArrayBuffer.byteOffset+this._bodyArrayBuffer.byteLength)):Promise.resolve(this._bodyArrayBuffer))}else{if(yn.blob)return this.blob().then(zZ);throw new Error("could not read as ArrayBuffer")}},this.text=function(){var t=lp(this);if(t)return t;if(this._bodyBlob)return HZ(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(VZ(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},yn.formData&&(this.formData=function(){return this.text().then(GZ)}),this.json=function(){return this.text().then(JSON.parse)},this}var ZZ=["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"];function WZ(t){var e=t.toUpperCase();return ZZ.indexOf(e)>-1?e:t}function Ba(t,e){if(!(this instanceof Ba))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');e=e||{};var n=e.body;if(t instanceof Ba){if(t.bodyUsed)throw new TypeError("Already read");this.url=t.url,this.credentials=t.credentials,e.headers||(this.headers=new jt(t.headers)),this.method=t.method,this.mode=t.mode,this.signal=t.signal,!n&&t._bodyInit!=null&&(n=t._bodyInit,t.bodyUsed=!0)}else this.url=String(t);if(this.credentials=e.credentials||this.credentials||"same-origin",(e.headers||!this.headers)&&(this.headers=new jt(e.headers)),this.method=WZ(e.method||this.method||"GET"),this.mode=e.mode||this.mode||null,this.signal=e.signal||this.signal||function(){if("AbortController"in Yt){var a=new AbortController;return a.signal}}(),this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&n)throw new TypeError("Body not allowed for GET or HEAD requests");if(this._initBody(n),(this.method==="GET"||this.method==="HEAD")&&(e.cache==="no-store"||e.cache==="no-cache")){var r=/([?&])_=[^&]*/;if(r.test(this.url))this.url=this.url.replace(r,"$1_="+new Date().getTime());else{var s=/\?/;this.url+=(s.test(this.url)?"&":"?")+"_="+new Date().getTime()}}}Ba.prototype.clone=function(){return new Ba(this,{body:this._bodyInit})};function GZ(t){var e=new FormData;return t.trim().split("&").forEach(function(n){if(n){var r=n.split("="),s=r.shift().replace(/\+/g," "),a=r.join("=").replace(/\+/g," ");e.append(decodeURIComponent(s),decodeURIComponent(a))}}),e}function qZ(t){var e=new jt,n=t.replace(/\r?\n[\t ]+/g," ");return n.split("\r").map(function(r){return r.indexOf(`
599
- `)===0?r.substr(1,r.length):r}).forEach(function(r){var s=r.split(":"),a=s.shift().trim();if(a){var i=s.join(":").trim();try{e.append(a,i)}catch(o){console.warn("Response "+o.message)}}}),e}qO.call(Ba.prototype);function qr(t,e){if(!(this instanceof qr))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');if(e||(e={}),this.type="default",this.status=e.status===void 0?200:e.status,this.status<200||this.status>599)throw new RangeError("Failed to construct 'Response': The status provided (0) is outside the range [200, 599].");this.ok=this.status>=200&&this.status<300,this.statusText=e.statusText===void 0?"":""+e.statusText,this.headers=new jt(e.headers),this.url=e.url||"",this._initBody(t)}qO.call(qr.prototype);qr.prototype.clone=function(){return new qr(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new jt(this.headers),url:this.url})};qr.error=function(){var t=new qr(null,{status:200,statusText:""});return t.ok=!1,t.status=0,t.type="error",t};var KZ=[301,302,303,307,308];qr.redirect=function(t,e){if(KZ.indexOf(e)===-1)throw new RangeError("Invalid status code");return new qr(null,{status:e,headers:{location:t}})};var ba=Yt.DOMException;try{new ba}catch{ba=function(e,n){this.message=e,this.name=n;var r=Error(e);this.stack=r.stack},ba.prototype=Object.create(Error.prototype),ba.prototype.constructor=ba}function KO(t,e){return new Promise(function(n,r){var s=new Ba(t,e);if(s.signal&&s.signal.aborted)return r(new ba("Aborted","AbortError"));var a=new XMLHttpRequest;function i(){a.abort()}a.onload=function(){var u={statusText:a.statusText,headers:qZ(a.getAllResponseHeaders()||"")};s.url.indexOf("file://")===0&&(a.status<200||a.status>599)?u.status=200:u.status=a.status,u.url="responseURL"in a?a.responseURL:u.headers.get("X-Request-URL");var l="response"in a?a.response:a.responseText;setTimeout(function(){n(new qr(l,u))},0)},a.onerror=function(){setTimeout(function(){r(new TypeError("Network request failed"))},0)},a.ontimeout=function(){setTimeout(function(){r(new TypeError("Network request timed out"))},0)},a.onabort=function(){setTimeout(function(){r(new ba("Aborted","AbortError"))},0)};function o(u){try{return u===""&&Yt.location.href?Yt.location.href:u}catch{return u}}if(a.open(s.method,o(s.url),!0),s.credentials==="include"?a.withCredentials=!0:s.credentials==="omit"&&(a.withCredentials=!1),"responseType"in a&&(yn.blob?a.responseType="blob":yn.arrayBuffer&&(a.responseType="arraybuffer")),e&&typeof e.headers=="object"&&!(e.headers instanceof jt||Yt.Headers&&e.headers instanceof Yt.Headers)){var c=[];Object.getOwnPropertyNames(e.headers).forEach(function(u){c.push(eo(u)),a.setRequestHeader(u,_y(e.headers[u]))}),s.headers.forEach(function(u,l){c.indexOf(l)===-1&&a.setRequestHeader(l,u)})}else s.headers.forEach(function(u,l){a.setRequestHeader(l,u)});s.signal&&(s.signal.addEventListener("abort",i),a.onreadystatechange=function(){a.readyState===4&&s.signal.removeEventListener("abort",i)}),a.send(typeof s._bodyInit>"u"?null:s._bodyInit)})}KO.polyfill=!0;Yt.fetch||(Yt.fetch=KO,Yt.Headers=jt,Yt.Request=Ba,Yt.Response=qr);var dp={};const JO="11434",XO=`http://127.0.0.1:${JO}`,JZ="0.6.3";var XZ=Object.defineProperty,YZ=(t,e,n)=>e in t?XZ(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,hp=(t,e,n)=>(YZ(t,typeof e!="symbol"?e+"":e,n),n);class wy extends Error{constructor(e,n){super(e),this.error=e,this.status_code=n,this.name="ResponseError",Error.captureStackTrace&&Error.captureStackTrace(this,wy)}}class QZ{constructor(e,n,r){hp(this,"abortController"),hp(this,"itr"),hp(this,"doneCallback"),this.abortController=e,this.itr=n,this.doneCallback=r}abort(){this.abortController.abort()}async*[Symbol.asyncIterator](){for await(const e of this.itr){if("error"in e)throw new Error(e.error);if(yield e,e.done||e.status==="success"){this.doneCallback();return}}throw new Error("Did not receive done or success response in stream.")}}const by=async t=>{var r;if(t.ok)return;let e=`Error ${t.status}: ${t.statusText}`,n=null;if((r=t.headers.get("content-type"))!=null&&r.includes("application/json"))try{n=await t.json(),e=n.error||e}catch{console.log("Failed to parse error response as JSON")}else try{console.log("Getting text from response"),e=await t.text()||e}catch{console.log("Failed to get text from error response")}throw new wy(e,t.status)};function eW(){var t;if(typeof window<"u"&&window.navigator){const e=navigator;return"userAgentData"in e&&((t=e.userAgentData)!=null&&t.platform)?`${e.userAgentData.platform.toLowerCase()} Browser/${navigator.userAgent};`:navigator.platform?`${navigator.platform.toLowerCase()} Browser/${navigator.userAgent};`:`unknown Browser/${navigator.userAgent};`}else if(typeof process<"u")return`${process.arch} ${process.platform} Node.js/${process.version}`;return""}function tW(t){if(t instanceof Headers){const e={};return t.forEach((n,r)=>{e[r]=n}),e}else return Array.isArray(t)?Object.fromEntries(t):t||{}}const nW=(t,e)=>t[e],vy=async(t,e,n={})=>{const r={"Content-Type":"application/json",Accept:"application/json","User-Agent":`ollama-js/${JZ} (${eW()})`};n.headers=tW(n.headers);try{const a=new URL(e);if(a.protocol==="https:"&&a.hostname==="ollama.com"){const i=typeof process=="object"&&process!==null&&typeof dp=="object"&&dp!==null?nW(dp,"OLLAMA_API_KEY"):void 0;!(n.headers.authorization||n.headers.Authorization)&&i&&(n.headers.Authorization=`Bearer ${i}`)}}catch(a){console.error("error parsing url",a)}const s=Object.fromEntries(Object.entries(n.headers).filter(([a])=>!Object.keys(r).some(i=>i.toLowerCase()===a.toLowerCase())));return n.headers={...r,...s},t(e,n)},fp=async(t,e,n)=>{const r=await vy(t,e,{headers:n==null?void 0:n.headers});return await by(r),r},Cs=async(t,e,n,r)=>{const a=(o=>o!==null&&typeof o=="object"&&!Array.isArray(o))(n)?JSON.stringify(n):n,i=await vy(t,e,{method:"POST",body:a,signal:r==null?void 0:r.signal,headers:r==null?void 0:r.headers});return await by(i),i},rW=async(t,e,n,r)=>{const s=await vy(t,e,{method:"DELETE",body:JSON.stringify(n),headers:r==null?void 0:r.headers});return await by(s),s},sW=async function*(t){const e=new TextDecoder("utf-8");let n="";const r=t.getReader();for(;;){const{done:s,value:a}=await r.read();if(s)break;n+=e.decode(a,{stream:!0});const i=n.split(`
600
- `);n=i.pop()??"";for(const o of i)try{yield JSON.parse(o)}catch{console.warn("invalid json: ",o)}}n+=e.decode();for(const s of n.split(`
601
- `).filter(a=>a!==""))try{yield JSON.parse(s)}catch{console.warn("invalid json: ",s)}},aW=t=>{if(!t)return XO;let e=t.includes("://");t.startsWith(":")&&(t=`http://127.0.0.1${t}`,e=!0),e||(t=`http://${t}`);const n=new URL(t);let r=n.port;r||(e?r=n.protocol==="https:"?"443":"80":r=JO);let s="";n.username&&(s=n.username,n.password&&(s+=`:${n.password}`),s+="@");let a=`${n.protocol}//${s}${n.hostname}:${r}${n.pathname}`;return a.endsWith("/")&&(a=a.slice(0,-1)),a};var iW=Object.defineProperty,oW=(t,e,n)=>e in t?iW(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,pp=(t,e,n)=>(oW(t,typeof e!="symbol"?e+"":e,n),n);let YO=class{constructor(e){pp(this,"config"),pp(this,"fetch"),pp(this,"ongoingStreamedRequests",[]),this.config={host:"",headers:e==null?void 0:e.headers},e!=null&&e.proxy||(this.config.host=aW((e==null?void 0:e.host)??XO)),this.fetch=(e==null?void 0:e.fetch)??fetch}abort(){for(const e of this.ongoingStreamedRequests)e.abort();this.ongoingStreamedRequests.length=0}async processStreamableRequest(e,n){n.stream=n.stream??!1;const r=`${this.config.host}/api/${e}`;if(n.stream){const a=new AbortController,i=await Cs(this.fetch,r,n,{signal:a.signal,headers:this.config.headers});if(!i.body)throw new Error("Missing body");const o=sW(i.body),c=new QZ(a,o,()=>{const u=this.ongoingStreamedRequests.indexOf(c);u>-1&&this.ongoingStreamedRequests.splice(u,1)});return this.ongoingStreamedRequests.push(c),c}return await(await Cs(this.fetch,r,n,{headers:this.config.headers})).json()}async encodeImage(e){if(typeof e!="string"){const n=new Uint8Array(e);let r="";const s=n.byteLength;for(let a=0;a<s;a++)r+=String.fromCharCode(n[a]);return btoa(r)}return e}async generate(e){return e.images&&(e.images=await Promise.all(e.images.map(this.encodeImage.bind(this)))),this.processStreamableRequest("generate",e)}async chat(e){if(e.messages)for(const n of e.messages)n.images&&(n.images=await Promise.all(n.images.map(this.encodeImage.bind(this))));return this.processStreamableRequest("chat",e)}async create(e){return this.processStreamableRequest("create",{...e})}async pull(e){return this.processStreamableRequest("pull",{name:e.model,stream:e.stream,insecure:e.insecure})}async push(e){return this.processStreamableRequest("push",{name:e.model,stream:e.stream,insecure:e.insecure})}async delete(e){return await rW(this.fetch,`${this.config.host}/api/delete`,{name:e.model},{headers:this.config.headers}),{status:"success"}}async copy(e){return await Cs(this.fetch,`${this.config.host}/api/copy`,{...e},{headers:this.config.headers}),{status:"success"}}async list(){return await(await fp(this.fetch,`${this.config.host}/api/tags`,{headers:this.config.headers})).json()}async show(e){return await(await Cs(this.fetch,`${this.config.host}/api/show`,{...e},{headers:this.config.headers})).json()}async embed(e){return await(await Cs(this.fetch,`${this.config.host}/api/embed`,{...e},{headers:this.config.headers})).json()}async embeddings(e){return await(await Cs(this.fetch,`${this.config.host}/api/embeddings`,{...e},{headers:this.config.headers})).json()}async ps(){return await(await fp(this.fetch,`${this.config.host}/api/ps`,{headers:this.config.headers})).json()}async version(){return await(await fp(this.fetch,`${this.config.host}/api/version`,{headers:this.config.headers})).json()}async webSearch(e){if(!e.query||e.query.length===0)throw new Error("Query is required");return await(await Cs(this.fetch,"https://ollama.com/api/web_search",{...e},{headers:this.config.headers})).json()}async webFetch(e){if(!e.url||e.url.length===0)throw new Error("URL is required");return await(await Cs(this.fetch,"https://ollama.com/api/web_fetch",{...e},{headers:this.config.headers})).json()}};new YO;var cW=class extends Jr{constructor(e,n){const r=typeof e=="string"?{...n??{},model:e}:e??{};super(r);p(this,"model","llama3");p(this,"numa");p(this,"numCtx");p(this,"numBatch");p(this,"numGpu");p(this,"mainGpu");p(this,"lowVram");p(this,"f16Kv");p(this,"logitsAll");p(this,"vocabOnly");p(this,"useMmap");p(this,"useMlock");p(this,"embeddingOnly");p(this,"numThread");p(this,"numKeep");p(this,"seed");p(this,"numPredict");p(this,"topK");p(this,"topP");p(this,"tfsZ");p(this,"typicalP");p(this,"repeatLastN");p(this,"temperature");p(this,"repeatPenalty");p(this,"presencePenalty");p(this,"frequencyPenalty");p(this,"mirostat");p(this,"mirostatTau");p(this,"mirostatEta");p(this,"penalizeNewline");p(this,"streaming");p(this,"format");p(this,"keepAlive");p(this,"client");p(this,"checkOrPullModel",!1);p(this,"baseUrl","http://127.0.0.1:11434");p(this,"think");this._addVersion("@langchain/ollama","1.2.7"),this.baseUrl=r.baseUrl??It("OLLAMA_BASE_URL")??this.baseUrl,this.client=new YO({fetch:r.fetch,host:this.baseUrl,headers:r.headers}),this.model=r.model??this.model,this.numa=r.numa,this.numCtx=r.numCtx,this.numBatch=r.numBatch,this.numGpu=r.numGpu,this.mainGpu=r.mainGpu,this.lowVram=r.lowVram,this.f16Kv=r.f16Kv,this.logitsAll=r.logitsAll,this.vocabOnly=r.vocabOnly,this.useMmap=r.useMmap,this.useMlock=r.useMlock,this.embeddingOnly=r.embeddingOnly,this.numThread=r.numThread,this.numKeep=r.numKeep,this.seed=r.seed,this.numPredict=r.numPredict,this.topK=r.topK,this.topP=r.topP,this.tfsZ=r.tfsZ,this.typicalP=r.typicalP,this.repeatLastN=r.repeatLastN,this.temperature=r.temperature,this.repeatPenalty=r.repeatPenalty,this.presencePenalty=r.presencePenalty,this.frequencyPenalty=r.frequencyPenalty,this.mirostat=r.mirostat,this.mirostatTau=r.mirostatTau,this.mirostatEta=r.mirostatEta,this.penalizeNewline=r.penalizeNewline,this.streaming=r.streaming,this.format=r.format,this.keepAlive=r.keepAlive,this.think=r.think,this.checkOrPullModel=r.checkOrPullModel??this.checkOrPullModel}static lc_name(){return"ChatOllama"}_llmType(){return"ollama"}async pull(e,n){const{stream:r,insecure:s,logProgress:a}={stream:!0,...n};if(r)for await(const i of await this.client.pull({model:e,insecure:s,stream:r}))a&&console.log(i);else{const i=await this.client.pull({model:e,insecure:s});a&&console.log(i)}}bindTools(e,n){return this.withConfig({tools:e.map(r=>wd(r)),...n})}getLsParams(e){var r,s;const n=this.invocationParams(e);return{ls_provider:"ollama",ls_model_name:this.model,ls_model_type:"chat",ls_temperature:((r=n.options)==null?void 0:r.temperature)??void 0,ls_max_tokens:((s=n.options)==null?void 0:s.num_predict)??void 0,ls_stop:e.stop}}invocationParams(e){var n;return{model:this.model,format:(e==null?void 0:e.format)??this.format,keep_alive:this.keepAlive,think:this.think,options:{numa:this.numa,num_ctx:this.numCtx,num_batch:this.numBatch,num_gpu:this.numGpu,main_gpu:this.mainGpu,low_vram:this.lowVram,f16_kv:this.f16Kv,logits_all:this.logitsAll,vocab_only:this.vocabOnly,use_mmap:this.useMmap,use_mlock:this.useMlock,embedding_only:this.embeddingOnly,num_thread:this.numThread,num_keep:this.numKeep,seed:this.seed,num_predict:this.numPredict,top_k:this.topK,top_p:this.topP,tfs_z:this.tfsZ,typical_p:this.typicalP,repeat_last_n:this.repeatLastN,temperature:this.temperature,repeat_penalty:this.repeatPenalty,presence_penalty:this.presencePenalty,frequency_penalty:this.frequencyPenalty,mirostat:this.mirostat,mirostat_tau:this.mirostatTau,mirostat_eta:this.mirostatEta,penalize_newline:this.penalizeNewline,stop:e==null?void 0:e.stop},tools:(n=e==null?void 0:e.tools)!=null&&n.length?e.tools.map(r=>wd(r)):void 0}}async checkModelExistsOnMachine(e){const{models:n}=await this.client.list();return!!n.find(r=>r.name===e||r.name===`${e}:latest`)}async _generate(e,n,r){var i;(i=n.signal)==null||i.throwIfAborted(),this.checkOrPullModel&&(await this.checkModelExistsOnMachine(this.model)||await this.pull(this.model,{logProgress:!0}));let s;for await(const o of this._streamResponseChunks(e,n,r))s?s=ys(s,o.message):s=o.message;const a=new De({id:s==null?void 0:s.id,content:(s==null?void 0:s.content)??"",additional_kwargs:s==null?void 0:s.additional_kwargs,tool_calls:s==null?void 0:s.tool_calls,response_metadata:s==null?void 0:s.response_metadata,usage_metadata:s==null?void 0:s.usage_metadata});return{generations:[{text:typeof a.content=="string"?a.content:"",message:a}]}}async*_streamResponseChunks(e,n,r){var u;this.checkOrPullModel&&(await this.checkModelExistsOnMachine(this.model)||await this.pull(this.model,{logProgress:!0}));const s=this.invocationParams(n),a=UZ(e),i={input_tokens:0,output_tokens:0,total_tokens:0},o=await this.client.chat({...s,messages:a,stream:!0});let c;for await(const l of o){if((u=n.signal)!=null&&u.aborted){this.client.abort();return}const{message:d,...f}=l;i.input_tokens+=f.prompt_eval_count??0,i.output_tokens+=f.eval_count??0,i.total_tokens=i.input_tokens+i.output_tokens,c=f;const h=this.think?d.thinking??d.content??"":d.content??"",m=new qn({text:h,message:NZ(d)});yield m,await(r==null?void 0:r.handleLLMNewToken(h,void 0,void 0,void 0,void 0,{chunk:m}))}yield new qn({text:"",message:new Qe({content:"",response_metadata:{...c,model_provider:"ollama"},usage_metadata:i})})}withStructuredOutput(e,n){let r,s;const{schema:a,name:i,includeRaw:o}={...n,schema:e},c=(n==null?void 0:n.method)??"jsonSchema";if(c==="functionCalling"){let u=i??"extract",l;const d=lt(a);Lt(a)||cr(a)?l={name:u,description:d.description,parameters:d}:typeof a.name=="string"&&typeof a.parameters=="object"&&a.parameters!=null?(l=a,u=a.name):l={name:u,description:a.description??"",parameters:a},r=this.bindTools([{type:"function",function:l}]).withConfig({ls_structured_output_format:{kwargs:{method:c},schema:Lt(a)||cr(a)?d:a}}),s=Yc(a,u)}else if(c==="jsonMode"||c==="jsonSchema"){s=Fi(a);const u=lt(a);r=this.withConfig({format:c==="jsonMode"?"json":u,ls_structured_output_format:{kwargs:{method:c},schema:u}})}else throw new TypeError(`Unrecognized structured output method '${c}'. Expected one of 'functionCalling', 'jsonMode', or 'jsonSchema'`);return Ji(r,s,o,o?"StructuredOutputRunnable":"ChatOllamaStructuredOutput")}};const uW=t=>uC.includes(t),lW=t=>B0.includes(t),dW=t=>{const{executeQuery:e,search:n,grep:r,readFile:s,fetchFeatureClusters:a,fetchFeatureClusterDetail:i}=t,o=Rs(async({query:m,limit:_,groupByProcess:y})=>{const w=_??10,g=y??!0;let b;try{b=await n(m,{limit:w,enrich:!0})}catch{return"Search is not available. Please load a repository first."}if(b.length===0)return`No code found matching "${m}". Try different terms or use grep for exact patterns.`;const S=b.slice(0,w).map((O,$)=>{var q,re;const H=O.nodeId||"",J=O.name||((q=O.filePath)==null?void 0:q.split("/").pop())||"Unknown",Y=O.label||"File",me=O.filePath||"",te=O.startLine?` (lines ${O.startLine}-${O.endLine})`:"",Be=((re=O.sources)==null?void 0:re.join("+"))||"hybrid",P=O.score?` [score: ${O.score.toFixed(2)}]`:"";let z="";if(O.connections){const ve=(O.connections.outgoing||[]).filter(k=>k==null?void 0:k.name).slice(0,3),ie=(O.connections.incoming||[]).filter(k=>k==null?void 0:k.name).slice(0,3),E=(k,ge)=>{const Se=k.confidence?Math.round(k.confidence*100):100;return ge==="out"?`-[${k.type} ${Se}%]-> ${k.name}`:`<-[${k.type} ${Se}%]- ${k.name}`},v=ve.map(k=>E(k,"out")),N=ie.map(k=>E(k,"in"));(v.length||N.length)&&(z=`
602
- Connections: ${[...v,...N].join(", ")}`)}const Q=O.cluster||"Unclustered",se=(O.processes||[]).filter(ve=>ve.id&&ve.label);return{idx:$+1,nodeId:H,name:J,label:Y,filePath:me,location:te,sources:Be,score:P,connections:z,clusterLabel:Q,processes:se}}),I=(O,$)=>{const H=$!=null&&$.step?` (step ${$.step}/${$.stepCount??"?"})`:"";return`[${O.idx}] ${O.label}: ${O.name}${O.score}${H}
603
- ID: ${O.nodeId}
604
- File: ${O.filePath}${O.location}
605
- Cluster: ${O.clusterLabel}
606
- Found by: ${O.sources}${O.connections}`};if(!g)return`Found ${b.length} matches:
607
-
608
- ${S.map(O=>I(O)).join(`
609
-
610
- `)}`;const T=new Map,x="__no_process__";for(const O of S){if(O.processes.length===0){T.has(x)||T.set(x,{label:"No process",entries:[]}),T.get(x).entries.push({result:O});continue}for(const $ of O.processes)T.has($.id)||T.set($.id,{label:$.label,stepCount:$.stepCount,entries:[]}),T.get($.id).entries.push({result:O,step:$.step,stepCount:$.stepCount})}const A=Array.from(T.entries()).sort((O,$)=>{const H=O[1].entries.length;return $[1].entries.length-H}),M=[];M.push(`Found ${b.length} matches grouped by process:`),M.push("");for(const[O,$]of A){const H=$.stepCount?`, ${$.stepCount} steps`:"",J=O===x?`NO PROCESS (${$.entries.length} matches)`:`PROCESS: ${$.label} (${$.entries.length} matches${H})`;M.push(J),$.entries.forEach(Y=>{const me=Y.step?{id:O,label:$.label,step:Y.step,stepCount:Y.stepCount}:void 0;M.push(I(Y.result,me))}),M.push("")}return M.join(`
611
- `).trim()},{name:"search",description:"Search for code by keywords or concepts. Combines keyword matching and semantic understanding. Groups results by process with cluster context; use overview/explore for feature clusters.",schema:br({query:zn().describe('What you are looking for (e.g., "authentication middleware", "database connection")'),groupByProcess:of().optional().nullable().describe("Group results by process (default: true)"),limit:Au().optional().nullable().describe("Max results to return (default: 10)")})}),c=Rs(async({query:m,cypher:_})=>{try{if(_.includes("{{QUERY_VECTOR}}")){if(!m)return"Error: Your Cypher contains {{QUERY_VECTOR}} but you didn't provide a 'query' to embed. Add a natural language query.";try{const I=await n(m,{limit:10,mode:"semantic"});if(I.length===0)return"Semantic search returned no results. Embeddings may not be generated yet.";const T=I.map((x,A)=>{var M;return`[${A+1}] ${x.label||"File"}: ${x.name||((M=x.filePath)==null?void 0:M.split("/").pop())||"?"} (score: ${(x.score??0).toFixed(3)})
612
- File: ${x.filePath||"n/a"}`}).join(`
613
- `);return`Semantic search for "${m}" (${I.length} results):
614
-
615
- ${T}`}catch{return"Semantic search not available. Embeddings may not be generated. Use a non-vector Cypher query instead."}}const y=await e(_);if(y.length===0)return"Query returned no results.";const w=y[0],g=typeof w=="object"&&!Array.isArray(w)?Object.keys(w):[];if(g.length>0){const I=`| ${g.join(" | ")} |`,T=`|${g.map(()=>"---").join("|")}|`,x=y.slice(0,50).map(M=>`| ${g.map($=>{const H=M[$];if(H==null)return"";if(typeof H=="object")return JSON.stringify(H);const J=String(H).replace(/\|/g,"\\|");return J.length>60?J.slice(0,57)+"...":J}).join(" | ")} |`).join(`
616
- `),A=y.length>50?`
617
-
618
- _(${y.length-50} more rows)_`:"";return`**${y.length} results:**
619
-
620
- ${I}
621
- ${T}
622
- ${x}${A}`}const b=y.slice(0,50).map((I,T)=>`[${T+1}] ${JSON.stringify(I)}`),S=y.length>50?`
623
- ... (${y.length-50} more)`:"";return`${y.length} results:
624
- ${b.join(`
625
- `)}${S}`}catch(y){return`Cypher error: ${y instanceof Error?y.message:String(y)}
626
-
627
- Check your query syntax. Node tables include File, Folder, Function, Class, Interface, Method, CodeElement, Community, Process, FeatureCluster, Route, Tool, Section. Relation: CodeRelation with type property (CONTAINS, DEFINES, IMPORTS, CALLS, MEMBER_OF, STEP_IN_PROCESS, FEATURE_MEMBER_OF, FEATURE_DEPENDS_ON). Example: MATCH (m)-[:CodeRelation {type: 'FEATURE_MEMBER_OF'}]->(f:FeatureCluster) RETURN f.name, m.filePath`}},{name:"cypher",description:`Execute a Cypher query against the code graph. Use for structural queries like finding callers, tracing imports, class inheritance, or custom traversals.
628
-
629
- Node tables: File, Folder, Function, Class, Interface, Method, CodeElement, Community, Process, FeatureCluster, Route, Tool, Section
630
- Relation: CodeRelation (single table with 'type' property: CONTAINS, DEFINES, IMPORTS, CALLS, EXTENDS, IMPLEMENTS, MEMBER_OF, STEP_IN_PROCESS, FEATURE_MEMBER_OF, FEATURE_DEPENDS_ON)
631
-
632
- Example queries:
633
- - Functions calling a function: MATCH (caller:Function)-[:CodeRelation {type: 'CALLS'}]->(fn:Function {name: 'validate'}) RETURN caller.name, caller.filePath
634
- - Feature members: MATCH (m)-[:CodeRelation {type: 'FEATURE_MEMBER_OF'}]->(f:FeatureCluster {name: 'Settings'}) RETURN m.name, m.filePath, m.startLine
635
- - Feature dependencies: MATCH (a:FeatureCluster)-[:CodeRelation {type: 'FEATURE_DEPENDS_ON'}]->(b:FeatureCluster) RETURN a.name, b.name
636
- - Class inheritance: MATCH (child:Class)-[:CodeRelation {type: 'EXTENDS'}]->(parent:Class) RETURN child.name, parent.name
637
- - Classes implementing interface: MATCH (c:Class)-[:CodeRelation {type: 'IMPLEMENTS'}]->(i:Interface) RETURN c.name, i.name
638
- - Files importing a file: MATCH (f:File)-[:CodeRelation {type: 'IMPORTS'}]->(target:File) WHERE target.name = 'utils.ts' RETURN f.name
639
- - All connections (with confidence): MATCH (n)-[r:CodeRelation]-(m) WHERE n.name = 'MyClass' AND r.confidence > 0.8 RETURN m.name, r.type, r.confidence
640
- - Find fuzzy matches: MATCH (n)-[r:CodeRelation]-(m) WHERE r.confidence < 0.8 RETURN n.name, r.reason
641
-
642
- For semantic+graph queries, include {{QUERY_VECTOR}} placeholder and provide a 'query' parameter:
643
- CALL QUERY_VECTOR_INDEX('CodeEmbedding', 'code_embedding_idx', {{QUERY_VECTOR}}, 10) YIELD node AS emb, distance
644
- WITH emb, distance WHERE distance < 0.5
645
- MATCH (n:Function {id: emb.nodeId}) RETURN n`,schema:br({cypher:zn().describe("The Cypher query to execute"),query:zn().optional().nullable().describe("Natural language query to embed (required if cypher contains {{QUERY_VECTOR}})")})}),u=Rs(async({pattern:m,fileFilter:_,caseSensitive:y,maxResults:w})=>{try{try{new RegExp(m,y?"g":"gi")}catch(x){return`Invalid regex: ${m}. Error: ${x instanceof Error?x.message:String(x)}`}const g=w??100,b=_?`(?=.*${_.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}).*${m}`:m,S=await r(b,g);if(S.length===0)return`No matches for "${m}"${_?` in files matching "${_}"`:""}`;const I=S.map(x=>`${x.filePath}:${x.line}: ${x.text}`).join(`
646
- `),T=S.length>=g?`
647
-
648
- (Showing first ${g} results)`:"";return`Found ${S.length} matches:
649
-
650
- ${I}${T}`}catch(g){return`Grep error: ${g instanceof Error?g.message:String(g)}`}},{name:"grep",description:"Search for exact text patterns across all files using regex. Use for finding specific strings, error messages, TODOs, variable names, etc.",schema:br({pattern:zn().describe('Regex pattern to search for (e.g., "TODO", "console\\.log", "API_KEY")'),fileFilter:zn().optional().nullable().describe('Only search files containing this string (e.g., ".ts", "src/api")'),caseSensitive:of().optional().nullable().describe("Case-sensitive search (default: false)"),maxResults:Au().optional().nullable().describe("Max results (default: 100)")})}),l=Rs(async({filePath:m})=>{try{const _=await s(m),y=5e4;if(_.length>y){const g=_.split(`
651
- `).length;return`File: ${m} (${g} lines, truncated)
652
-
653
- ${_.slice(0,y)}
654
-
655
- ... [truncated]`}const w=_.split(`
656
- `).length;return`File: ${m} (${w} lines)
657
-
658
- ${_}`}catch(_){const y=_ instanceof Error?_.message:String(_);return y.includes("not found")||y.includes("404")?`File not found: "${m}". Use grep to search for the correct path.`:`Error reading file: ${y}`}},{name:"read",description:"Read the full content of a file. Use to see source code after finding files via search or grep.",schema:br({filePath:zn().describe('File path to read (can be partial like "src/utils.ts")')})}),d=Rs(async()=>{try{const m=`
659
- MATCH (f:FeatureCluster)
660
- RETURN f.id AS id, f.name AS name, f.slug AS slug, f.featureKind AS featureKind,
661
- f.description AS description, f.signals AS signals, f.memberCount AS memberCount,
662
- f.confidence AS confidence
663
- ORDER BY f.memberCount DESC
664
- LIMIT 200
665
- `,_=`
666
- MATCH (c:Community)
667
- RETURN c.id AS id, c.label AS label, c.cohesion AS cohesion, c.symbolCount AS symbolCount, c.description AS description
668
- ORDER BY c.symbolCount DESC
669
- LIMIT 200
670
- `,y=`
671
- MATCH (p:Process)
672
- RETURN p.id AS id, p.label AS label, p.processType AS type, p.stepCount AS stepCount, p.communities AS communities
673
- ORDER BY p.stepCount DESC
674
- LIMIT 200
675
- `,w=`
676
- MATCH (a)-[:CodeRelation {type: 'CALLS'}]->(b)
677
- MATCH (a)-[:CodeRelation {type: 'MEMBER_OF'}]->(c1:Community)
678
- MATCH (b)-[:CodeRelation {type: 'MEMBER_OF'}]->(c2:Community)
679
- WHERE c1.id <> c2.id
680
- RETURN c1.label AS \`from\`, c2.label AS \`to\`, COUNT(*) AS calls
681
- ORDER BY calls DESC
682
- LIMIT 15
683
- `,g=`
684
- MATCH (s)-[r:CodeRelation {type: 'STEP_IN_PROCESS'}]->(p:Process)
685
- RETURN p.label AS label, COUNT(r) AS steps
686
- ORDER BY steps DESC
687
- LIMIT 10
688
- `,b=`
689
- MATCH (a:FeatureCluster)-[:CodeRelation {type: 'FEATURE_DEPENDS_ON'}]->(b:FeatureCluster)
690
- RETURN a.name AS \`from\`, b.name AS \`to\`, COUNT(*) AS edges
691
- ORDER BY edges DESC
692
- LIMIT 15
693
- `,S=a?a().catch(()=>({clusters:[]})):e(m).then(P=>({clusters:P.map(z=>({id:Array.isArray(z)?z[0]:z.id,name:Array.isArray(z)?z[1]:z.name,slug:Array.isArray(z)?z[2]:z.slug,featureKind:Array.isArray(z)?z[3]:z.featureKind,description:Array.isArray(z)?z[4]:z.description,signals:Array.isArray(z)?z[5]:z.signals,memberCount:Array.isArray(z)?z[6]:z.memberCount,confidence:Array.isArray(z)?z[7]:z.confidence}))})),[I,T,x,A,M,O]=await Promise.all([S,e(_),e(y),e(w),e(g),e(b)]),$=Array.isArray(I.clusters)?I.clusters:[],H=$.map(P=>{const z=P.confidence!==null&&P.confidence!==void 0?Number(P.confidence).toFixed(2):"";return`| ${P.name||P.slug||P.id||""} | ${P.featureKind||""} | ${P.memberCount??""} | ${z} | ${P.description??""} |`}),J=O.map(P=>{const z=Array.isArray(P)?P[0]:P.from,Q=Array.isArray(P)?P[1]:P.to,se=Array.isArray(P)?P[2]:P.edges;return`- ${z} -> ${Q} (${se} edges)`}),Y=T.map(P=>{const z=Array.isArray(P)?P[1]:P.label,Q=Array.isArray(P)?P[3]:P.symbolCount,se=Array.isArray(P)?P[2]:P.cohesion,q=Array.isArray(P)?P[4]:P.description,re=se!=null?Number(se).toFixed(2):"";return`| ${z||""} | ${Q??""} | ${re} | ${q??""} |`}),me=x.map(P=>{const z=Array.isArray(P)?P[1]:P.label,Q=Array.isArray(P)?P[3]:P.stepCount,se=Array.isArray(P)?P[2]:P.type,q=Array.isArray(P)?P[4]:P.communities,re=Array.isArray(q)?q.length:q?1:0;return`| ${z||""} | ${Q??""} | ${se??""} | ${re} |`}),te=A.map(P=>{const z=Array.isArray(P)?P[0]:P.from,Q=Array.isArray(P)?P[1]:P.to,se=Array.isArray(P)?P[2]:P.calls;return`- ${z} -> ${Q} (${se} calls)`}),Be=M.map(P=>{const z=Array.isArray(P)?P[0]:P.label,Q=Array.isArray(P)?P[1]:P.steps;return`- ${z} (${Q} steps)`});return[`FEATURE CLUSTERS (${$.length} total):`,"| Feature | Kind | Members | Confidence | Description |","| --- | --- | --- | --- | --- |",...H,"",`CLUSTERS (${T.length} total):`,"| Cluster | Symbols | Cohesion | Description |","| --- | --- | --- | --- |",...Y,"",`PROCESSES (${x.length} total):`,"| Process | Steps | Type | Clusters |","| --- | --- | --- | --- |",...me,"","CLUSTER DEPENDENCIES:",...te.length>0?te:["- None found"],"","FEATURE DEPENDENCIES:",...J.length>0?J:["- None found"],"","CRITICAL PATHS:",...Be.length>0?Be:["- None found"]].join(`
694
- `)}catch(m){return`Overview error: ${m instanceof Error?m.message:String(m)}`}},{name:"overview",description:"Codebase map showing feature clusters, structural clusters, processes, and dependencies.",schema:br({})}),f=Rs(async({target:m,type:_})=>{var A,M;const y=m.replace(/'/g,"''");let w=_??null,g=null,b=null,S=null,I=null;const T=(O,$,H)=>Array.isArray(O)?O[$]:O[H],x=O=>(O==null?void 0:O.name)||(O==null?void 0:O.slug)||(O==null?void 0:O.id)||"Unknown feature";if(!w||w==="process"){const O=`
695
- MATCH (p:Process)
696
- WHERE p.id = '${y}' OR p.label = '${y}'
697
- RETURN p.id AS id, p.label AS label, p.processType AS type, p.stepCount AS stepCount
698
- LIMIT 1
699
- `,$=await e(O);$.length>0&&(g=$[0],w="process")}if(!w||w==="feature"){const O=`
700
- MATCH (f:FeatureCluster)
701
- WHERE f.id = '${y}' OR f.name = '${y}' OR f.slug = '${y}'
702
- RETURN f.id AS id, f.name AS name, f.slug AS slug, f.featureKind AS featureKind,
703
- f.description AS description, f.memberCount AS memberCount, f.confidence AS confidence,
704
- f.signals AS signals
705
- LIMIT 1
706
- `,$=await e(O);$.length>0&&(b=$[0],w="feature")}if(!w||w==="cluster"){const O=`
707
- MATCH (c:Community)
708
- WHERE c.id = '${y}' OR c.label = '${y}' OR c.heuristicLabel = '${y}'
709
- RETURN c.id AS id, c.label AS label, c.cohesion AS cohesion, c.symbolCount AS symbolCount, c.description AS description
710
- LIMIT 1
711
- `,$=await e(O);$.length>0&&(S=$[0],w="cluster")}if(!w||w==="symbol"){const O=`
712
- MATCH (n)
713
- WHERE n.name = '${y}' OR n.id = '${y}' OR n.filePath = '${y}'
714
- RETURN n.id AS id, n.name AS name, n.filePath AS filePath, label(n) AS nodeType
715
- LIMIT 5
716
- `,$=await e(O);$.length>0&&(I=$[0],w="symbol")}if(!w)return`Could not find "${m}" as a symbol, feature cluster, structural cluster, or process. Try search first.`;if(w==="process"){const O=T(g,0,"id"),$=T(g,1,"label"),H=T(g,2,"type"),J=T(g,3,"stepCount"),Y=`
717
- MATCH (s)-[r:CodeRelation {type: 'STEP_IN_PROCESS'}]->(p:Process {id: '${O.replace(/'/g,"''")}'})
718
- RETURN s.name AS name, s.filePath AS filePath, r.step AS step
719
- ORDER BY r.step
720
- `,me=`
721
- MATCH (c:Community)<-[:CodeRelation {type: 'MEMBER_OF'}]-(s)
722
- MATCH (s)-[:CodeRelation {type: 'STEP_IN_PROCESS'}]->(p:Process {id: '${O.replace(/'/g,"''")}'})
723
- RETURN DISTINCT c.id AS id, c.label AS label, c.description AS description
724
- ORDER BY c.label
725
- LIMIT 20
726
- `,[te,Be]=await Promise.all([e(Y),e(me)]),P=te.map(Q=>{const se=T(Q,0,"name"),q=T(Q,1,"filePath");return`- ${T(Q,2,"step")}. ${se} (${q||"n/a"})`}),z=Be.map(Q=>{const se=T(Q,1,"label"),q=T(Q,2,"description");return`- ${se}${q?` — ${q}`:""}`});return[`PROCESS: ${$}`,`Type: ${H||"n/a"}`,`Steps: ${J??te.length}`,"","STEPS:",...P.length>0?P:["- None found"],"","CLUSTERS TOUCHED:",...z.length>0?z:["- None found"]].join(`
727
- `)}if(w==="feature"){const O=T(b,0,"id"),$=T(b,1,"name"),H=T(b,2,"slug"),J=T(b,3,"featureKind"),Y=T(b,4,"description"),me=T(b,5,"memberCount"),te=T(b,6,"confidence"),Be=T(b,7,"signals");let P=null;if(i)try{const L=await i(String($||H||O));!L.error&&L.cluster&&(P=L)}catch{P=null}const z=`
728
- MATCH (m)-[r:CodeRelation {type: 'FEATURE_MEMBER_OF'}]->(f:FeatureCluster {id: '${String(O).replace(/'/g,"''")}'})
729
- RETURN m.id AS id, m.name AS name, label(m) AS type, m.filePath AS filePath,
730
- m.startLine AS startLine, m.endLine AS endLine, r.confidence AS confidence,
731
- r.reason AS reason
732
- ORDER BY type, filePath, startLine
733
- LIMIT 80
734
- `,Q=`
735
- MATCH (f:FeatureCluster {id: '${String(O).replace(/'/g,"''")}'})-[r:CodeRelation {type: 'FEATURE_DEPENDS_ON'}]->(d:FeatureCluster)
736
- RETURN d.id AS id, d.name AS name, d.slug AS slug, r.confidence AS confidence
737
- ORDER BY d.name
738
- `,se=`
739
- MATCH (s:FeatureCluster)-[r:CodeRelation {type: 'FEATURE_DEPENDS_ON'}]->(f:FeatureCluster {id: '${String(O).replace(/'/g,"''")}'})
740
- RETURN s.id AS id, s.name AS name, s.slug AS slug, r.confidence AS confidence
741
- ORDER BY s.name
742
- `,q=`
743
- MATCH (m)-[:CodeRelation {type: 'FEATURE_MEMBER_OF'}]->(f:FeatureCluster {id: '${String(O).replace(/'/g,"''")}'}),
744
- (m)-[:CodeRelation {type: 'STEP_IN_PROCESS'}]->(p:Process)
745
- RETURN DISTINCT p.id AS id, p.label AS label, p.processType AS processType, p.stepCount AS stepCount
746
- ORDER BY p.stepCount DESC
747
- LIMIT 20
748
- `,[re,ve,ie,E]=P?[[],[],[],[]]:await Promise.all([e(z),e(Q),e(se),e(q)]),v=P==null?void 0:P.dependencies,N=Array.isArray(v)?[]:(v==null?void 0:v.outgoing)??[],k=Array.isArray(v)?[]:(v==null?void 0:v.incoming)??[],ge=((A=P==null?void 0:P.members)==null?void 0:A.map(L=>({name:L.name||L.id||L.nodeId||"Unknown",type:L.type||L.label||"Node",filePath:L.filePath||"n/a",startLine:L.startLine,endLine:L.endLine,confidence:L.confidence})))??re.map(L=>({name:T(L,1,"name")||T(L,0,"id"),type:T(L,2,"type"),filePath:T(L,3,"filePath")||"n/a",startLine:T(L,4,"startLine"),endLine:T(L,5,"endLine"),confidence:T(L,6,"confidence")})),Se=ge.map(L=>{const rn=L.startLine?`:${L.startLine}${L.endLine?`-${L.endLine}`:""}`:"",we=L.confidence!==null&&L.confidence!==void 0?` (${Math.round(Number(L.confidence)*100)}%)`:"";return`- ${L.type}: ${L.name} (${L.filePath}${rn})${we}`}),Ye=N.length>0?N:ve.map(L=>({id:T(L,0,"id"),name:T(L,1,"name"),slug:T(L,2,"slug"),confidence:T(L,3,"confidence")})),Ze=k.length>0?k:ie.map(L=>({id:T(L,0,"id"),name:T(L,1,"name"),slug:T(L,2,"slug"),confidence:T(L,3,"confidence")})),it=Ye.map(L=>`- ${x(L)}`),mt=Ze.map(L=>`- ${x(L)}`),At=((P==null?void 0:P.processes)??E.map(L=>({id:T(L,0,"id"),label:T(L,1,"label"),heuristicLabel:void 0,processType:T(L,2,"processType"),stepCount:T(L,3,"stepCount")}))).map(L=>`- ${L.label||L.heuristicLabel||L.id||"Unknown process"} (${L.stepCount??"?"} steps)`),nn=te!=null?Number(te).toFixed(2):"n/a",Xn=Array.isArray(Be)?Be.slice(0,8).join(", "):"";return[`FEATURE: ${$||H||O}`,`Kind: ${J||"feature"}`,`Members: ${me??ge.length}`,`Confidence: ${nn}`,`Description: ${Y||((M=P==null?void 0:P.cluster)==null?void 0:M.description)||"n/a"}`,Xn?`Signals: ${Xn}`:"","","TOP MEMBERS:",...Se.length>0?Se:["- None found"],"","DEPENDS ON:",...it.length>0?it:["- None found"],"","USED BY:",...mt.length>0?mt:["- None found"],"","PROCESSES TOUCHING THIS FEATURE:",...At.length>0?At:["- None found"]].filter((L,rn,we)=>L!==""||we[rn-1]!=="").join(`
749
- `)}if(w==="cluster"){const O=T(S,0,"id"),$=T(S,1,"label"),H=T(S,2,"cohesion"),J=T(S,3,"symbolCount"),Y=T(S,4,"description"),me=`
750
- MATCH (c:Community {id: '${O.replace(/'/g,"''")}'})<-[:CodeRelation {type: 'MEMBER_OF'}]-(m)
751
- RETURN m.name AS name, m.filePath AS filePath, label(m) AS nodeType
752
- LIMIT 50
753
- `,te=`
754
- MATCH (c:Community {id: '${O.replace(/'/g,"''")}'})<-[:CodeRelation {type: 'MEMBER_OF'}]-(s)
755
- MATCH (s)-[:CodeRelation {type: 'STEP_IN_PROCESS'}]->(p:Process)
756
- RETURN DISTINCT p.id AS id, p.label AS label, p.stepCount AS stepCount
757
- ORDER BY p.stepCount DESC
758
- LIMIT 20
759
- `,[Be,P]=await Promise.all([e(me),e(te)]),z=Be.map(se=>{const q=T(se,0,"name"),re=T(se,1,"filePath");return`- ${T(se,2,"nodeType")}: ${q} (${re||"n/a"})`}),Q=P.map(se=>{const q=T(se,1,"label"),re=T(se,2,"stepCount");return`- ${q} (${re} steps)`});return[`CLUSTER: ${$}`,`Symbols: ${J??Be.length}`,`Cohesion: ${H!=null?Number(H).toFixed(2):"n/a"}`,`Description: ${Y||"n/a"}`,"","TOP MEMBERS:",...z.length>0?z:["- None found"],"","PROCESSES TOUCHING THIS CLUSTER:",...Q.length>0?Q:["- None found"]].join(`
760
- `)}if(w==="symbol"){const O=T(I,0,"id"),$=T(I,1,"name"),H=T(I,2,"filePath"),J=T(I,3,"nodeType");if(!uW(J))return`Unknown node type "${J}" for symbol "${m}".`;const Y=`
761
- MATCH (n:${J} {id: '${String(O).replace(/'/g,"''")}'})
762
- MATCH (n)-[:CodeRelation {type: 'MEMBER_OF'}]->(c:Community)
763
- RETURN c.label AS label, c.description AS description
764
- LIMIT 1
765
- `,me=`
766
- MATCH (n:${J} {id: '${String(O).replace(/'/g,"''")}'})
767
- MATCH (n)-[:CodeRelation {type: 'FEATURE_MEMBER_OF'}]->(f:FeatureCluster)
768
- RETURN f.name AS name, f.slug AS slug, f.featureKind AS kind
769
- LIMIT 1
770
- `,te=`
771
- MATCH (n:${J} {id: '${String(O).replace(/'/g,"''")}'})
772
- MATCH (n)-[r:CodeRelation {type: 'STEP_IN_PROCESS'}]->(p:Process)
773
- RETURN p.label AS label, r.step AS step, p.stepCount AS stepCount
774
- ORDER BY r.step
775
- `,Be=`
776
- MATCH (n:${J} {id: '${String(O).replace(/'/g,"''")}'})
777
- OPTIONAL MATCH (n)-[r1:CodeRelation]->(dst)
778
- OPTIONAL MATCH (src)-[r2:CodeRelation]->(n)
779
- RETURN
780
- collect(DISTINCT {name: dst.name, type: r1.type, confidence: r1.confidence}) AS outgoing,
781
- collect(DISTINCT {name: src.name, type: r2.type, confidence: r2.confidence}) AS incoming
782
- LIMIT 1
783
- `,[P,z,Q,se]=await Promise.all([e(Y),e(me),e(te),e(Be)]),q=P.length>0?T(P[0],0,"label"):"Unclustered",re=P.length>0?T(P[0],1,"description"):"",ve=z.length>0?T(z[0],0,"name")||T(z[0],1,"slug"):"",ie=z.length>0?T(z[0],2,"kind"):"",E=Q.map(N=>{const k=T(N,0,"label"),ge=T(N,1,"step"),Se=T(N,2,"stepCount");return`- ${k} (step ${ge}/${Se??"?"})`});let v="None";if(se.length>0){const N=se[0],k=Array.isArray(N)?N[0]:N.outgoing||[],ge=Array.isArray(N)?N[1]:N.incoming||[],Se=(k||[]).filter(Re=>Re&&Re.name).slice(0,5),Ye=(ge||[]).filter(Re=>Re&&Re.name).slice(0,5),Ze=(Re,At)=>{const nn=Re.confidence?Math.round(Re.confidence*100):100;return At==="out"?`-[${Re.type} ${nn}%]-> ${Re.name}`:`<-[${Re.type} ${nn}%]- ${Re.name}`},it=Se.map(Re=>Ze(Re,"out")),mt=Ye.map(Re=>Ze(Re,"in"));(it.length||mt.length)&&(v=[...it,...mt].join(", "))}return[`SYMBOL: ${J} ${$}`,`ID: ${O}`,`File: ${H||"n/a"}`,`Feature: ${ve||"Unassigned"}${ie?` (${ie})`:""}`,`Cluster: ${q}${re?` — ${re}`:""}`,"","PROCESSES:",...E.length>0?E:["- None found"],"","CONNECTIONS:",v].join(`
784
- `)}return`Unable to explore "${m}".`},{name:"explore",description:"Deep dive on a symbol, feature cluster, structural cluster, or process. Shows membership, participation, and connections.",schema:br({target:zn().describe("Name or ID of a symbol, feature cluster, cluster, or process"),type:tb(["symbol","feature","cluster","process"]).optional().nullable().describe("Optional target type (auto-detected if omitted)")})}),h=Rs(async({target:m,direction:_,maxDepth:y,relationTypes:w,includeTests:g,minConfidence:b})=>{var Ee;const S=Math.min(y??3,10),I=g??!1,T=b??.7,x=W=>{if(!W)return!1;const ze=W.toLowerCase();return ze.includes(".test.")||ze.includes(".spec.")||ze.includes("__tests__")||ze.includes("__mocks__")||ze.endsWith(".test.ts")||ze.endsWith(".test.tsx")||ze.endsWith(".spec.ts")||ze.endsWith(".spec.tsx")},A=["CALLS","IMPORTS","EXTENDS","IMPLEMENTS"],M=w&&w.length>0?w.filter(W=>lW(W)):A;if(M.length===0)return`No valid relation types provided. Valid types: ${B0.join(", ")}`;const O=M.map(W=>`'${W.replace(/'/g,"''")}'`).join(", "),$=_==="upstream"?"Files that DEPEND ON this (breakage risk)":"Dependencies this RELIES ON",H=m.includes("/"),J=m.replace(/'/g,"''"),Y=H?`
785
- MATCH (n)
786
- WHERE n.filePath IS NOT NULL AND n.filePath CONTAINS '${J}'
787
- RETURN n.id AS id, label(n) AS nodeType, n.filePath AS filePath
788
- LIMIT 10
789
- `:`
790
- MATCH (n)
791
- WHERE n.name = '${J}'
792
- RETURN n.id AS id, label(n) AS nodeType, n.filePath AS filePath
793
- LIMIT 10
794
- `;let me;try{me=await e(Y)}catch(W){return`Error finding target "${m}": ${W}`}if(!me||me.length===0)return`Could not find "${m}" in the codebase. Try using the search tool first to find the exact name.`;const te=me.map(W=>Array.isArray(W)?W[2]:W.filePath).filter(Boolean);if(me.length>1&&!m.includes("/"))return`⚠️ AMBIGUOUS TARGET: Multiple files named "${m}" found:
795
-
796
- ${te.map((W,ze)=>`${ze+1}. ${W}`).join(`
797
- `)}
798
-
799
- Please specify which file you mean by using a more specific path, e.g.:
800
- - impact("${te[0].split("/").slice(-3).join("/")}")
801
- - impact("${((Ee=te[1])==null?void 0:Ee.split("/").slice(-3).join("/"))||te[0]}")`;let Be=me[0];if(m.includes("/")&&me.length>1){const W=me.find(ze=>{const ot=Array.isArray(ze)?ze[2]:ze.filePath;return ot&&ot.toLowerCase().includes(m.toLowerCase())});if(W)Be=W;else return`⚠️ AMBIGUOUS TARGET: Could not uniquely match "${m}". Found:
802
-
803
- ${te.map((ze,ot)=>`${ot+1}. ${ze}`).join(`
804
- `)}
805
-
806
- Please use a more specific path.`}const P=Array.isArray(Be)?Be[0]:Be.id,z=Array.isArray(Be)?Be[1]:Be.nodeType,Q=Array.isArray(Be)?Be[2]:Be.filePath,se="",q=z==="File",re=[],ve=_==="upstream"?q?`
807
- MATCH (affected)-[r:CodeRelation]->(callee)
808
- WHERE callee.filePath = '${(Q||m).replace(/'/g,"''")}'
809
- AND r.type IN [${O}]
810
- AND affected.filePath <> callee.filePath
811
- AND (r.confidence IS NULL OR r.confidence >= ${T})
812
- RETURN DISTINCT
813
- affected.id AS id,
814
- affected.name AS name,
815
- label(affected) AS nodeType,
816
- affected.filePath AS filePath,
817
- affected.startLine AS startLine,
818
- 1 AS depth,
819
- r.type AS edgeType,
820
- r.confidence AS confidence,
821
- r.reason AS reason
822
- LIMIT 300
823
- `:`
824
- MATCH (target {id: '${P.replace(/'/g,"''")}'})
825
- MATCH (affected)-[r:CodeRelation]->(target)
826
- WHERE r.type IN [${O}]
827
- AND (r.confidence IS NULL OR r.confidence >= ${T})
828
- RETURN DISTINCT
829
- affected.id AS id,
830
- affected.name AS name,
831
- label(affected) AS nodeType,
832
- affected.filePath AS filePath,
833
- affected.startLine AS startLine,
834
- 1 AS depth,
835
- r.type AS edgeType,
836
- r.confidence AS confidence,
837
- r.reason AS reason
838
- LIMIT 300
839
- `:q?`
840
- MATCH (caller)-[r:CodeRelation]->(affected)
841
- WHERE caller.filePath = '${(Q||m).replace(/'/g,"''")}'
842
- AND r.type IN [${O}]
843
- AND caller.filePath <> affected.filePath
844
- AND (r.confidence IS NULL OR r.confidence >= ${T})
845
- RETURN DISTINCT
846
- affected.id AS id,
847
- affected.name AS name,
848
- label(affected) AS nodeType,
849
- affected.filePath AS filePath,
850
- affected.startLine AS startLine,
851
- 1 AS depth,
852
- r.type AS edgeType,
853
- r.confidence AS confidence,
854
- r.reason AS reason
855
- LIMIT 300
856
- `:`
857
- MATCH (target {id: '${P.replace(/'/g,"''")}'})
858
- MATCH (target)-[r:CodeRelation]->(affected)
859
- WHERE r.type IN [${O}]
860
- AND (r.confidence IS NULL OR r.confidence >= ${T})
861
- RETURN DISTINCT
862
- affected.id AS id,
863
- affected.name AS name,
864
- label(affected) AS nodeType,
865
- affected.filePath AS filePath,
866
- affected.startLine AS startLine,
867
- 1 AS depth,
868
- r.type AS edgeType,
869
- r.confidence AS confidence,
870
- r.reason AS reason
871
- LIMIT 300
872
- `;if(re.push(e(ve).then(W=>W).catch(W=>[])),S>=2){const W=_==="upstream"?`
873
- MATCH (target {id: '${P.replace(/'/g,"''")}'})
874
- MATCH (a)-[r1:CodeRelation]->(target)
875
- MATCH (affected)-[r2:CodeRelation]->(a)
876
- WHERE r1.type IN [${O}] AND r2.type IN [${O}]
877
- AND affected.id <> target.id
878
- AND (r1.confidence IS NULL OR r1.confidence >= ${T})
879
- AND (r2.confidence IS NULL OR r2.confidence >= ${T})
880
- RETURN DISTINCT
881
- affected.id AS id,
882
- affected.name AS name,
883
- label(affected) AS nodeType,
884
- affected.filePath AS filePath,
885
- affected.startLine AS startLine,
886
- 2 AS depth,
887
- r2.type AS edgeType,
888
- r2.confidence AS confidence,
889
- r2.reason AS reason
890
- LIMIT 200
891
- `:`
892
- MATCH (target {id: '${P.replace(/'/g,"''")}'})
893
- MATCH (target)-[r1:CodeRelation]->(a)
894
- MATCH (a)-[r2:CodeRelation]->(affected)
895
- WHERE r1.type IN [${O}] AND r2.type IN [${O}]
896
- AND affected.id <> target.id
897
- AND (r1.confidence IS NULL OR r1.confidence >= ${T})
898
- AND (r2.confidence IS NULL OR r2.confidence >= ${T})
899
- RETURN DISTINCT
900
- affected.id AS id,
901
- affected.name AS name,
902
- label(affected) AS nodeType,
903
- affected.filePath AS filePath,
904
- affected.startLine AS startLine,
905
- 2 AS depth,
906
- r2.type AS edgeType,
907
- r2.confidence AS confidence,
908
- r2.reason AS reason
909
- LIMIT 200
910
- `;re.push(e(W).catch(ze=>[]))}if(S>=3){const W=_==="upstream"?`
911
- MATCH (target {id: '${P.replace(/'/g,"''")}'})
912
- MATCH (a)-[r1:CodeRelation]->(target)
913
- MATCH (b)-[r2:CodeRelation]->(a)
914
- MATCH (affected)-[r3:CodeRelation]->(b)
915
- WHERE r1.type IN [${O}] AND r2.type IN [${O}] AND r3.type IN [${O}]
916
- AND affected.id <> target.id AND affected.id <> a.id
917
- AND (r1.confidence IS NULL OR r1.confidence >= ${T})
918
- AND (r2.confidence IS NULL OR r2.confidence >= ${T})
919
- AND (r3.confidence IS NULL OR r3.confidence >= ${T})
920
- RETURN DISTINCT
921
- affected.id AS id,
922
- affected.name AS name,
923
- label(affected) AS nodeType,
924
- affected.filePath AS filePath,
925
- affected.startLine AS startLine,
926
- 3 AS depth,
927
- r3.type AS edgeType,
928
- r3.confidence AS confidence,
929
- r3.reason AS reason
930
- LIMIT 100
931
- `:`
932
- MATCH (target {id: '${P.replace(/'/g,"''")}'})
933
- MATCH (target)-[r1:CodeRelation]->(a)
934
- MATCH (a)-[r2:CodeRelation]->(b)
935
- MATCH (b)-[r3:CodeRelation]->(affected)
936
- WHERE r1.type IN [${O}] AND r2.type IN [${O}] AND r3.type IN [${O}]
937
- AND affected.id <> target.id AND affected.id <> a.id
938
- AND (r1.confidence IS NULL OR r1.confidence >= ${T})
939
- AND (r2.confidence IS NULL OR r2.confidence >= ${T})
940
- AND (r3.confidence IS NULL OR r3.confidence >= ${T})
941
- RETURN DISTINCT
942
- affected.id AS id,
943
- affected.name AS name,
944
- label(affected) AS nodeType,
945
- affected.filePath AS filePath,
946
- affected.startLine AS startLine,
947
- 3 AS depth,
948
- r3.type AS edgeType,
949
- r3.confidence AS confidence,
950
- r3.reason AS reason
951
- LIMIT 100
952
- `;re.push(e(W).catch(ze=>[]))}const ie=await Promise.all(re),E=new Map,v=[],N=new Set;ie.forEach((W,ze)=>{const ot=ze+1;W.forEach(He=>{const Ut=Array.isArray(He)?He[0]:He.id,Yn=Array.isArray(He)?He[3]:He.filePath;if(!(!I&&x(Yn))&&Ut&&!N.has(Ut)){N.add(Ut),E.has(ot)||E.set(ot,[]);const ia={id:Ut,name:Array.isArray(He)?He[1]:He.name,nodeType:Array.isArray(He)?He[2]:He.nodeType,filePath:Yn,startLine:Array.isArray(He)?He[4]:He.startLine,edgeType:Array.isArray(He)?He[5]:He.edgeType||"CALLS",confidence:Array.isArray(He)?He[6]:He.confidence??1,reason:Array.isArray(He)?He[7]:He.reason||""};E.get(ot).push(ia),v.push(Ut)}})});const k=v.length;if(k===0){if(q){const W=He=>He.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),ot=((Q||m).split("/").pop()||m).replace(/\.[^/.]+$/,"");try{const Ut=(await r(`\\b${W(ot)}\\b`,15)).filter(Yn=>Yn.filePath!==Q);if(Ut.length>0){const Yn=Ut.map(ia=>`${ia.filePath}:${ia.line}: ${ia.text}`).join(`
953
- `);return`No ${_} dependencies found for "${m}" (types: ${M.join(", ")}), but textual references were detected (graph may be incomplete):
954
-
955
- ${Yn}${se}`}}catch{}}return`No ${_} dependencies found for "${m}" (types: ${M.join(", ")}). This code appears to be ${_==="upstream"?"unused (not called by anything)":"self-contained (no outgoing dependencies)"}.${se}`}const ge=E.get(1)||[],Se=E.get(2)||[],Ye=E.get(3)||[],Ze={high:0,medium:0,low:0};for(const W of E.values())for(const ze of W){const ot=ze.confidence??1;ot>=.9?Ze.high+=1:ot>=.8?Ze.medium+=1:Ze.low+=1}const mt=v.slice(0,500),Re=mt.map(W=>`'${W.replace(/'/g,"''")}'`).join(", ");let At=[],nn=[],Xn=[];if(mt.length>0){const W=`
956
- MATCH (s)-[r:CodeRelation {type: 'STEP_IN_PROCESS'}]->(p:Process)
957
- WHERE s.id IN [${Re}]
958
- RETURN p.label AS label, COUNT(DISTINCT s.id) AS hits, MIN(r.step) AS minStep, p.stepCount AS stepCount
959
- ORDER BY hits DESC
960
- LIMIT 20
961
- `,ze=`
962
- MATCH (s)-[:CodeRelation {type: 'MEMBER_OF'}]->(c:Community)
963
- WHERE s.id IN [${Re}]
964
- RETURN c.label AS label, COUNT(DISTINCT s.id) AS hits
965
- ORDER BY hits DESC
966
- LIMIT 20
967
- `,ot=`
968
- MATCH (s)-[:CodeRelation {type: 'FEATURE_MEMBER_OF'}]->(f:FeatureCluster)
969
- WHERE s.id IN [${Re}]
970
- RETURN f.name AS label, f.featureKind AS kind, COUNT(DISTINCT s.id) AS hits
971
- ORDER BY hits DESC
972
- LIMIT 20
973
- `,He=ge.map(je=>`'${je.id.replace(/'/g,"''")}'`).join(", "),Ut=ge.length>0?`
974
- MATCH (s)-[:CodeRelation {type: 'MEMBER_OF'}]->(c:Community)
975
- WHERE s.id IN [${He}]
976
- RETURN DISTINCT c.label AS label
977
- `:"",Yn=ge.length>0?`
978
- MATCH (s)-[:CodeRelation {type: 'FEATURE_MEMBER_OF'}]->(f:FeatureCluster)
979
- WHERE s.id IN [${He}]
980
- RETURN DISTINCT f.name AS label
981
- `:"",[ia,QO,eC,tC,nC]=await Promise.all([e(W),e(ze),Ut?e(Ut):Promise.resolve([]),e(ot),Yn?e(Yn):Promise.resolve([])]),Sy=new Set;eC.forEach(je=>{const lr=Array.isArray(je)?je[0]:je.label;lr&&Sy.add(lr)});const Ty=new Set;nC.forEach(je=>{const lr=Array.isArray(je)?je[0]:je.label;lr&&Ty.add(lr)}),At=ia.map(je=>({label:Array.isArray(je)?je[0]:je.label,hits:Array.isArray(je)?je[1]:je.hits,minStep:Array.isArray(je)?je[2]:je.minStep,stepCount:Array.isArray(je)?je[3]:je.stepCount})),nn=QO.map(je=>{const lr=Array.isArray(je)?je[0]:je.label,Nh=Array.isArray(je)?je[1]:je.hits,Ph=Sy.has(lr)?"direct":"indirect";return{label:lr,hits:Nh,impact:Ph}}),Xn=tC.map(je=>{const lr=Array.isArray(je)?je[0]:je.label,Nh=Array.isArray(je)?je[1]:je.kind,Ph=Array.isArray(je)?je[2]:je.hits,rC=Ty.has(lr)?"direct":"indirect";return{label:lr,kind:Nh,hits:Ph,impact:rC}})}const L=ge.length,rn=At.length,we=nn.length,_e=Xn.length;let Te="LOW";L>=30||rn>=5||we>=5||_e>=5||k>=200?Te="CRITICAL":L>=15||rn>=3||we>=3||_e>=3||k>=100?Te="HIGH":(L>=5||k>=30)&&(Te="MEDIUM");const G=[`🔴 IMPACT: ${m} | ${_} | ${k} affected`,`Confidence: High ${Ze.high} | Medium ${Ze.medium} | Low ${Ze.low}`,"","AFFECTED PROCESSES:",...At.length>0?At.map(W=>`- ${W.label} - BROKEN at step ${W.minStep??"?"} (${W.hits} symbols, ${W.stepCount??"?"} steps)`):["- None found"],"","AFFECTED FEATURE CLUSTERS:",...Xn.length>0?Xn.map(W=>`- ${W.label}${W.kind?` (${W.kind})`:""} - ${W.impact}, ${W.hits} symbols`):["- None found"],"","AFFECTED CLUSTERS:",...nn.length>0?nn.map(W=>`- ${W.label} (${W.impact}, ${W.hits} symbols)`):["- None found"],"",`RISK: ${Te}`,`- Direct callers: ${L}`,`- Processes affected: ${rn}`,`- Feature clusters affected: ${_e}`,`- Clusters affected: ${we}`,""],X=W=>{var Yn;const ze=((Yn=W.filePath)==null?void 0:Yn.split("/").pop())||"",ot=W.startLine?`${ze}:${W.startLine}`:ze,He=Math.round((W.confidence??1)*100),Ut=He<80?"[fuzzy]":"";return` ${W.nodeType}|${W.name}|${ot}|${W.edgeType}|${He}%${Ut}`},Ie=async W=>{if(!W.filePath||!W.startLine)return null;try{const ot=(await s(W.filePath)).split(`
982
- `),He=W.startLine-1;if(He<0||He>=ot.length)return null;let Ut=ot[He].trim();return Ut.length>80&&(Ut=Ut.slice(0,77)+"..."),Ut}catch{return null}};if(ge.length>0){const W=_==="upstream"?`d=1 (Directly DEPEND ON ${m}):`:`d=1 (${m} USES these):`;G.push(W);for(const ze of ge.slice(0,15)){G.push(X(ze));const ot=await Ie(ze);ot&&G.push(` ↳ "${ot}"`)}ge.length>15&&G.push(` ... +${ge.length-15} more`),G.push("")}if(Se.length>0){const W=_==="upstream"?`d=2 (Indirectly DEPEND ON ${m}):`:`d=2 (${m} USES these indirectly):`;G.push(W),Se.slice(0,15).forEach(ze=>G.push(X(ze))),Se.length>15&&G.push(` ... +${Se.length-15} more`),G.push("")}return Ye.length>0&&(G.push("d=3 (Deep impact/dependency):"),Ye.slice(0,5).forEach(W=>G.push(X(W))),Ye.length>5&&G.push(` ... +${Ye.length-5} more`),G.push("")),G.push("✅ GRAPH ANALYSIS COMPLETE (trusted)"),G.push(`⚠️ Optional: grep("${m}") for dynamic patterns`),G.push(""),G.join(`
983
- `)},{name:"impact",description:`Analyze the impact of changing a function, class, or file.
984
-
985
- Use when users ask:
986
- - "What would break if I changed X?"
987
- - "What depends on X?"
988
- - "Impact analysis for X"
989
-
990
- Direction:
991
- - upstream: Find what CALLS/IMPORTS/EXTENDS this target (what would break)
992
- - downstream: Find what this target CALLS/IMPORTS/EXTENDS (dependencies)
993
-
994
- Output format (compact tabular):
995
- Type|Name|File:Line|EdgeType|Confidence%
996
-
997
- EdgeType: CALLS, IMPORTS, EXTENDS, IMPLEMENTS
998
- Confidence: 100% = certain, <80% = fuzzy match (may be false positive)
999
-
1000
- relationTypes filter (optional):
1001
- - Default: CALLS, IMPORTS, EXTENDS, IMPLEMENTS (usage-based)
1002
- - Can add CONTAINS, DEFINES for structural analysis
1003
-
1004
- Additional output sections:
1005
- - Affected processes (with step impact)
1006
- - Affected feature clusters (product/domain areas)
1007
- - Affected clusters (direct/indirect)
1008
- - Risk summary (based on direct callers, processes, feature clusters, clusters)`,schema:br({target:zn().describe("Name of the function, class, or file to analyze"),direction:tb(["upstream","downstream"]).describe("upstream = what depends on this; downstream = what this depends on"),maxDepth:Au().optional().nullable().describe("Max traversal depth (default: 3, max: 10)"),relationTypes:sj(zn()).optional().nullable().describe("Filter by relation types: CALLS, IMPORTS, EXTENDS, IMPLEMENTS, CONTAINS, DEFINES (default: usage-based)"),includeTests:of().optional().nullable().describe("Include test files in results (default: false, excludes .test.ts, .spec.ts, __tests__)"),minConfidence:Au().optional().nullable().describe("Minimum edge confidence 0-1 (default: 0.7, excludes fuzzy/inferred matches)")})});return[o,c,u,l,d,f,h]},M0=`You are CodraGraph, a Code Analysis Agent with access to a Knowledge Graph. Your responses MUST be grounded.
1009
-
1010
- ## ⚠️ MANDATORY: GROUNDING
1011
- Every factual claim MUST include a citation.
1012
- - File refs: [[src/auth.ts:45-60]] (line range with hyphen)
1013
- - NO citation = NO claim. Say "I didn't find evidence" instead of guessing.
1014
-
1015
- ## ⚠️ MANDATORY: VALIDATION
1016
- Every output MUST be validated.
1017
- - Use cypher to validate the results and confirm completeness of context before final output.
1018
- - NO validation = NO claim. Say "I didn't find evidence" instead of guessing.
1019
- - Do not blindly trust readme or single source of truth. Always validate and cross-reference. Never be lazy.
1020
-
1021
- ## 🧠 CORE PROTOCOL
1022
- You are an investigator. For each question:
1023
- 1. **Search** → Use cypher, search or grep to find relevant code
1024
- 2. **Read** → Use read to see the actual source
1025
- 3. **Trace** → Use cypher to follow connections in the graph
1026
- 4. **Cite** → Ground every finding with [[file:line]] or [[Type:Name]]
1027
- 5. **Validate** → Use cypher to validate the results and confirm completeness of context before final output. ( MUST DO )
1028
-
1029
- ## 🛠️ TOOLS
1030
- - **\`search\`** — Hybrid search. Results grouped by process with cluster context.
1031
- - **\`cypher\`** — Cypher queries against the graph. Use \`{{QUERY_VECTOR}}\` for vector search.
1032
- - **\`grep\`** — Regex search. Best for exact strings, TODOs, error codes.
1033
- - **\`read\`** — Read file content. Always use after search/grep to see full code.
1034
- - **\`explore\`** — Deep dive on a symbol, feature cluster, structural cluster, or process.
1035
- - **\`overview\`** — Codebase map showing feature clusters, structural clusters, and processes.
1036
- - **\`impact\`** — Impact analysis. Shows affected processes, feature clusters, clusters, and risk level.
1037
-
1038
- ## 📊 GRAPH SCHEMA
1039
- Nodes: File, Folder, Function, Class, Interface, Method, Community, Process, FeatureCluster, Route, Tool, Section
1040
- Relations: \`CodeRelation\` with \`type\` property: CONTAINS, DEFINES, IMPORTS, CALLS, EXTENDS, IMPLEMENTS, MEMBER_OF, STEP_IN_PROCESS, FEATURE_MEMBER_OF, FEATURE_DEPENDS_ON
1041
-
1042
- ## 📐 GRAPH SEMANTICS (Important!)
1043
- **Edge Types:**
1044
- - \`CALLS\`: Method invocation OR constructor injection. If A receives B as parameter and uses it, A→B is CALLS. This is intentional simplification.
1045
- - \`IMPORTS\`: File-level import/include statement.
1046
- - \`EXTENDS/IMPLEMENTS\`: Class inheritance.
1047
-
1048
- **Process Nodes:**
1049
- - Process labels use format: "EntryPoint → Terminal" (e.g., "onCreate → showToast")
1050
- - These are heuristic names from tracing execution flow, NOT application-defined names
1051
- - Entry points are detected via export status, naming patterns, and framework conventions
1052
-
1053
- **FeatureCluster Nodes:**
1054
- - Feature clusters are human/product areas like Settings, Auth, AI, Billing, Admin, or Docs.
1055
- - Use \`overview\` first to find relevant feature areas, then \`explore\` with \`type: "feature"\` to load focused files, line ranges, dependencies, and flows.
1056
- - Prefer feature context before broad exploration when the user asks to refactor or understand an application area.
1057
-
1058
- Cypher examples:
1059
- - \`MATCH (f:Function) RETURN f.name LIMIT 10\`
1060
- - \`MATCH (f:File)-[:CodeRelation {type: 'IMPORTS'}]->(g:File) RETURN f.name, g.name\`
1061
- - \`MATCH (m)-[:CodeRelation {type: 'FEATURE_MEMBER_OF'}]->(f:FeatureCluster {name: 'Settings'}) RETURN m.name, m.filePath, m.startLine\`
1062
-
1063
- ## 📝CRITICAL RULES
1064
- - **impact output is trusted.** Do NOT re-validate with cypher. Optionally run the suggested grep commands for dynamic patterns.
1065
- - **Cite or retract.** Never state something you can't ground.
1066
- - **Read before concluding.** Don't guess from names alone.
1067
- - **Retry on failure.** If a tool fails, fix the input and try again.
1068
- - **Cyfer tool validation** prefer using cyfer tool in anything that requires graph connections.
1069
- - **OUTPUT STYLE** Prefer using tables and mermaid diagrams instead of long explanations.
1070
- - ALWAYS USE MERMAID FOR VISUALIZATION AND STRUCTURING THE OUTPUT.
1071
-
1072
- ## 🎯 OUTPUT STYLE
1073
- Think like a senior architect. Be concise—no fluff, short, precise and to the point.
1074
- - Use tables for comparisons/rankings
1075
- - Use mermaid diagrams for flows/dependencies
1076
- - Surface deep insights: patterns, coupling, design decisions
1077
- - End with **TL;DR** (short summary of the response, summing up the response and the most critical parts)
1078
-
1079
- ## MERMAID RULES
1080
- When generating diagrams:
1081
- - NO special characters in node labels: quotes, (), /, &, <, >
1082
- - Wrap labels with spaces in quotes: A["My Label"]
1083
- - Use simple IDs: A, B, C or auth, db, api
1084
- - Flowchart: graph TD or graph LR (not flowchart)
1085
- - Always test mentally: would this parse?
1086
-
1087
- BAD: A[User's Data] --> B(Process & Save)
1088
- GOOD: A["User Data"] --> B["Process and Save"]
1089
- `,hW=t=>{switch(t.provider){case"openai":{const e=t;if(!e.apiKey||e.apiKey.trim()==="")throw new Error("OpenAI API key is required but was not provided");return new Bl({apiKey:e.apiKey,modelName:e.model,temperature:e.temperature??.1,maxTokens:e.maxTokens,configuration:{apiKey:e.apiKey,...e.baseUrl?{baseURL:e.baseUrl}:{}},streaming:!0})}case"azure-openai":{const e=t;return new B8({azureOpenAIApiKey:e.apiKey,azureOpenAIApiInstanceName:fW(e.endpoint),azureOpenAIApiDeploymentName:e.deploymentName,azureOpenAIApiVersion:e.apiVersion??"2024-12-01-preview",streaming:!0})}case"gemini":{const e=t;return new qH({apiKey:e.apiKey,model:e.model,temperature:e.temperature??.1,maxOutputTokens:e.maxTokens,streaming:!0})}case"anthropic":{const e=t;return new $0({anthropicApiKey:e.apiKey,model:e.model,temperature:e.temperature??.1,maxTokens:e.maxTokens??8192,streaming:!0})}case"ollama":{const e=t;return new cW({baseUrl:e.baseUrl??oC,model:e.model,temperature:e.temperature??.1,streaming:!0,numPredict:3e4,numCtx:32768})}case"openrouter":{const e=t;if(!e.apiKey||e.apiKey.trim()==="")throw new Error("OpenRouter API key is required but was not provided");return new Bl({openAIApiKey:e.apiKey,apiKey:e.apiKey,modelName:e.model,temperature:e.temperature??.1,maxTokens:e.maxTokens,configuration:{apiKey:e.apiKey,baseURL:e.baseUrl??iC},streaming:!0})}case"minimax":{const e=t;if(!e.apiKey||e.apiKey.trim()==="")throw new Error("MiniMax API key is required but was not provided");return new $0({anthropicApiKey:e.apiKey,model:e.model,temperature:e.temperature??.1,maxTokens:e.maxTokens??8192,streaming:!0,clientOptions:{baseURL:"https://api.minimax.io/anthropic"}})}case"glm":{const e=t;if(!e.apiKey||e.apiKey.trim()==="")throw new Error("GLM API key is required but was not provided");return new Bl({apiKey:e.apiKey,modelName:e.model,temperature:e.temperature??.1,maxTokens:e.maxTokens,configuration:{apiKey:e.apiKey,baseURL:e.baseUrl??"https://api.z.ai/api/coding/paas/v4"},streaming:!0})}default:throw new Error(`Unsupported provider: ${t.provider}`)}},fW=t=>{try{const n=new URL(t).hostname,r=n.match(/^([^.]+)\.openai\.azure\.com/);return r?r[1]:n.split(".")[0]}catch{return t}},xG=(t,e,n)=>{const r=hW(t),s=dW(e),a=n?cC(M0,n):M0;return s5({llm:r,tools:s,messageModifier:new Gn(a)})};async function*kG(t,e){var n,r,s,a,i,o;try{const c=e.map(_=>({role:_.role,content:_.content})),u=await t.stream({messages:c},{streamMode:["values","messages"],recursionLimit:50}),l=new Set,d=new Set;let f=c.length,h=0,m=!1;for await(const _ of u){let y,w;if(Array.isArray(_)&&_.length===2&&typeof _[0]=="string"?[y,w]=_:Array.isArray(_)&&((n=_[0])!=null&&n._getType)?(y="messages",w=_):(y="values",w=_),y==="messages"){const[g]=Array.isArray(w)?w:[w];if(!g)continue;const b=((r=g._getType)==null?void 0:r.call(g))||g.type||((s=g.constructor)==null?void 0:s.name)||"unknown";if(b==="ai"||b==="AIMessage"||b==="AIMessageChunk"){const S=g.content,I=g.tool_calls||[];let T="";if(typeof S=="string"?T=S:Array.isArray(S)&&(T=S.filter(x=>x.type==="text"||typeof x=="string").map(x=>typeof x=="string"?x:x.text||"").join("")),T&&T.length>0){const x=!m||I.length>0||h>0;yield{type:x?"reasoning":"content",[x?"reasoning":"content"]:T}}if(I.length>0){m=!0,h+=I.length;for(const x of I){const A=x.id||`tool-${Date.now()}-${Math.random().toString(36).slice(2)}`;if(!l.has(A)){l.add(A);let M;try{M=(a=x.function)!=null&&a.arguments?JSON.parse(x.function.arguments):{}}catch{M={}}yield{type:"tool_call",toolCall:{id:A,name:x.name||((i=x.function)==null?void 0:i.name)||"unknown",args:x.args||M,status:"running"}}}}}}if(b==="tool"||b==="ToolMessage"){const S=g.tool_call_id||"";if(S&&!d.has(S)){d.add(S);const I=typeof g.content=="string"?g.content:JSON.stringify(g.content);yield{type:"tool_result",toolCall:{id:S,name:g.name||"tool",args:{},result:I,status:"completed"}},h=Math.max(0,h-1)}}}if(y==="values"&&(w!=null&&w.messages)){const g=w.messages||[];for(let b=f;b<g.length;b++){const S=g[b],I=((o=S._getType)==null?void 0:o.call(S))||S.type||"unknown";if((I==="ai"||I==="AIMessage")&&!l.size){const T=S.tool_calls||[];for(const x of T){const A=x.id||`tool-${Date.now()}`;l.has(A)||(h++,l.add(A),yield{type:"tool_call",toolCall:{id:A,name:x.name||"unknown",args:x.args||{},status:"running"}})}}if(I==="tool"||I==="ToolMessage"){const T=S.tool_call_id||"";if(T&&!d.has(T)){d.add(T);const x=typeof S.content=="string"?S.content:JSON.stringify(S.content);yield{type:"tool_result",toolCall:{id:T,name:S.name||"tool",args:{},result:x,status:"completed"}},h=Math.max(0,h-1)}}}f=g.length}}yield{type:"done"}}catch(c){yield{type:"error",error:c instanceof Error?c.message:String(c)}}}const OG=async(t,e)=>{var a;const n=e.map(i=>({role:i.role,content:i.content})),r=await t.invoke({messages:n}),s=r.messages[r.messages.length-1];return((a=s==null?void 0:s.content)==null?void 0:a.toString())??"No response generated."};export{M0 as BASE_SYSTEM_PROMPT,hW as createChatModel,xG as createGraphRAGAgent,OG as invokeAgent,kG as streamAgentResponse};