gitnexus 1.6.6-rc.2 β†’ 1.6.6-rc.21

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 (112) hide show
  1. package/dist/_shared/index.d.ts +1 -1
  2. package/dist/_shared/index.d.ts.map +1 -1
  3. package/dist/_shared/index.js.map +1 -1
  4. package/dist/_shared/scope-resolution/reference-site.d.ts +8 -0
  5. package/dist/_shared/scope-resolution/reference-site.d.ts.map +1 -1
  6. package/dist/_shared/scope-resolution/registries/context.d.ts +18 -1
  7. package/dist/_shared/scope-resolution/registries/context.d.ts.map +1 -1
  8. package/dist/_shared/scope-resolution/registries/context.js.map +1 -1
  9. package/dist/_shared/scope-resolution/registries/lookup-core.d.ts +4 -2
  10. package/dist/_shared/scope-resolution/registries/lookup-core.d.ts.map +1 -1
  11. package/dist/_shared/scope-resolution/registries/lookup-core.js +8 -23
  12. package/dist/_shared/scope-resolution/registries/lookup-core.js.map +1 -1
  13. package/dist/cli/analyze.js +65 -3
  14. package/dist/cli/eval-server.d.ts +14 -3
  15. package/dist/cli/eval-server.js +79 -9
  16. package/dist/cli/index.js +3 -1
  17. package/dist/cli/serve.js +6 -1
  18. package/dist/cli/setup.js +6 -4
  19. package/dist/cli/wiki.d.ts +1 -0
  20. package/dist/cli/wiki.js +32 -8
  21. package/dist/core/ingestion/languages/cpp/captures.js +165 -9
  22. package/dist/core/ingestion/languages/cpp/constraint-filter.js +102 -32
  23. package/dist/core/ingestion/languages/cpp/type-classifier.d.ts +9 -9
  24. package/dist/core/ingestion/languages/cpp/type-classifier.js +12 -8
  25. package/dist/core/ingestion/languages/java.js +35 -0
  26. package/dist/core/ingestion/languages/javascript/arity.d.ts +11 -0
  27. package/dist/core/ingestion/languages/javascript/arity.js +11 -0
  28. package/dist/core/ingestion/languages/javascript/captures.d.ts +30 -0
  29. package/dist/core/ingestion/languages/javascript/captures.js +655 -0
  30. package/dist/core/ingestion/languages/javascript/import-target.d.ts +29 -0
  31. package/dist/core/ingestion/languages/javascript/import-target.js +53 -0
  32. package/dist/core/ingestion/languages/javascript/index.d.ts +48 -0
  33. package/dist/core/ingestion/languages/javascript/index.js +48 -0
  34. package/dist/core/ingestion/languages/javascript/interpret.d.ts +29 -0
  35. package/dist/core/ingestion/languages/javascript/interpret.js +41 -0
  36. package/dist/core/ingestion/languages/javascript/merge-bindings.d.ts +16 -0
  37. package/dist/core/ingestion/languages/javascript/merge-bindings.js +18 -0
  38. package/dist/core/ingestion/languages/javascript/query.d.ts +52 -0
  39. package/dist/core/ingestion/languages/javascript/query.js +413 -0
  40. package/dist/core/ingestion/languages/javascript/scope-resolver.d.ts +37 -0
  41. package/dist/core/ingestion/languages/javascript/scope-resolver.js +73 -0
  42. package/dist/core/ingestion/languages/javascript/simple-hooks.d.ts +32 -0
  43. package/dist/core/ingestion/languages/javascript/simple-hooks.js +37 -0
  44. package/dist/core/ingestion/languages/typescript/simple-hooks.d.ts +10 -0
  45. package/dist/core/ingestion/languages/typescript/simple-hooks.js +4 -1
  46. package/dist/core/ingestion/languages/typescript.js +15 -0
  47. package/dist/core/ingestion/model/field-registry.d.ts +17 -3
  48. package/dist/core/ingestion/model/field-registry.js +19 -4
  49. package/dist/core/ingestion/model/owned-members-lookup.d.ts +19 -0
  50. package/dist/core/ingestion/model/owned-members-lookup.js +43 -0
  51. package/dist/core/ingestion/model/type-registry.d.ts +9 -0
  52. package/dist/core/ingestion/model/type-registry.js +18 -0
  53. package/dist/core/ingestion/registry-primary-flag.js +1 -0
  54. package/dist/core/ingestion/resolve-references.d.ts +3 -1
  55. package/dist/core/ingestion/resolve-references.js +5 -1
  56. package/dist/core/ingestion/scope-extractor.js +4 -0
  57. package/dist/core/ingestion/scope-resolution/passes/free-call-fallback.d.ts +1 -0
  58. package/dist/core/ingestion/scope-resolution/passes/free-call-fallback.js +37 -7
  59. package/dist/core/ingestion/scope-resolution/passes/overload-narrowing.d.ts +2 -0
  60. package/dist/core/ingestion/scope-resolution/passes/overload-narrowing.js +8 -1
  61. package/dist/core/ingestion/scope-resolution/passes/receiver-bound-calls.js +2 -0
  62. package/dist/core/ingestion/scope-resolution/pipeline/reconcile-ownership.d.ts +4 -2
  63. package/dist/core/ingestion/scope-resolution/pipeline/reconcile-ownership.js +48 -9
  64. package/dist/core/ingestion/scope-resolution/pipeline/registry.js +2 -0
  65. package/dist/core/ingestion/scope-resolution/pipeline/run.js +2 -0
  66. package/dist/core/lbug/lbug-adapter.d.ts +3 -1
  67. package/dist/core/lbug/lbug-adapter.js +33 -19
  68. package/dist/core/lbug/lbug-config.d.ts +1 -1
  69. package/dist/core/lbug/lbug-config.js +1 -1
  70. package/dist/core/lbug/pool-adapter.d.ts +19 -7
  71. package/dist/core/lbug/pool-adapter.js +70 -44
  72. package/dist/core/lbug/query-params.d.ts +1 -0
  73. package/dist/core/lbug/query-params.js +21 -0
  74. package/dist/core/search/bm25-index.js +4 -6
  75. package/dist/core/wiki/generator.d.ts +13 -0
  76. package/dist/core/wiki/generator.js +45 -4
  77. package/dist/core/wiki/llm-client.d.ts +1 -1
  78. package/dist/core/wiki/llm-client.js +23 -6
  79. package/dist/mcp/local/local-backend.d.ts +18 -3
  80. package/dist/mcp/local/local-backend.js +127 -11
  81. package/dist/mcp/tools.js +10 -0
  82. package/dist/server/api.d.ts +3 -0
  83. package/dist/server/api.js +58 -30
  84. package/package.json +3 -3
  85. package/web/assets/agent-SmDhIVj9.js +608 -0
  86. package/web/assets/{architectureDiagram-UL44E2DR-DvIkEGkp.js β†’ architectureDiagram-UL44E2DR-ChS6kfgC.js} +1 -1
  87. package/web/assets/{chunk-LCXTWHL2-CqJ0oo1x.js β†’ chunk-LCXTWHL2-CikfiTEP.js} +1 -1
  88. package/web/assets/{chunk-RG4AUYOV-D0M6vdq9.js β†’ chunk-RG4AUYOV-D0pH0sP0.js} +1 -1
  89. package/web/assets/{classDiagram-KGZ6W3CR-BB-saqC1.js β†’ classDiagram-KGZ6W3CR-VJjLBrQ3.js} +1 -1
  90. package/web/assets/{classDiagram-v2-72OJOZXJ-Bp2bAlS5.js β†’ classDiagram-v2-72OJOZXJ-CL_v399n.js} +1 -1
  91. package/web/assets/{diagram-3NCE3AQN-BUxnDPOY.js β†’ diagram-3NCE3AQN-DTTuOnDj.js} +1 -1
  92. package/web/assets/{diagram-GF46GFSD-BJTyqqvI.js β†’ diagram-GF46GFSD-Di3e_png.js} +1 -1
  93. package/web/assets/{diagram-QXG6HAR7-DilMHamP.js β†’ diagram-QXG6HAR7-CVQY1hhk.js} +1 -1
  94. package/web/assets/{diagram-WEQXMOUZ-8KUrarg1.js β†’ diagram-WEQXMOUZ-BoxS7CN3.js} +1 -1
  95. package/web/assets/{erDiagram-L5TCEMPS-Doj9mSiW.js β†’ erDiagram-L5TCEMPS-CLTuHusW.js} +1 -1
  96. package/web/assets/{flowDiagram-H6V6AXG4-BOSR-i3p.js β†’ flowDiagram-H6V6AXG4-CQfVb2C4.js} +1 -1
  97. package/web/assets/{index-j4-NuleT.js β†’ index-BuC2I_Cj.js} +5 -5
  98. package/web/assets/{infoDiagram-3YFTVSEB-Ce_TvtaV.js β†’ infoDiagram-3YFTVSEB-BOk6LlXV.js} +1 -1
  99. package/web/assets/{ishikawaDiagram-BNXS4ZKH-4MXIDCSF.js β†’ ishikawaDiagram-BNXS4ZKH-C0sASGB6.js} +1 -1
  100. package/web/assets/{kanban-definition-75IXJCU3-yYdfm8Kk.js β†’ kanban-definition-75IXJCU3-DT9Lizpz.js} +1 -1
  101. package/web/assets/{mindmap-definition-2TDM6QVE-DFNEKM77.js β†’ mindmap-definition-2TDM6QVE-BEYaB7hb.js} +1 -1
  102. package/web/assets/{pieDiagram-CU6KROY3-iZAqpvhd.js β†’ pieDiagram-CU6KROY3-DCgHNkyY.js} +1 -1
  103. package/web/assets/{requirementDiagram-JXO7QTGE-CtDijhnf.js β†’ requirementDiagram-JXO7QTGE-D6vDU9M2.js} +1 -1
  104. package/web/assets/{sequenceDiagram-VS2MUI6T-BdjvyCHM.js β†’ sequenceDiagram-VS2MUI6T-CJrGCTXy.js} +1 -1
  105. package/web/assets/{stateDiagram-7D4R322I-e5odN9fG.js β†’ stateDiagram-7D4R322I-BvxQnQyL.js} +1 -1
  106. package/web/assets/{stateDiagram-v2-36443NZ5-vPsvjR2D.js β†’ stateDiagram-v2-36443NZ5-D8ziO9W2.js} +1 -1
  107. package/web/assets/{timeline-definition-O6YCAMPW-DPAksNQp.js β†’ timeline-definition-O6YCAMPW-B45j2q3m.js} +1 -1
  108. package/web/assets/{vennDiagram-MWXL3ELB-Dtlfdt7J.js β†’ vennDiagram-MWXL3ELB-CRkZRDhi.js} +1 -1
  109. package/web/assets/{wardleyDiagram-CUQ6CDDI-B23uRMUC.js β†’ wardleyDiagram-CUQ6CDDI-BekUytZJ.js} +1 -1
  110. package/web/assets/{xychartDiagram-N2JHSOCM-DxwHeksW.js β†’ xychartDiagram-N2JHSOCM-BeMqwSgr.js} +1 -1
  111. package/web/index.html +1 -1
  112. package/web/assets/agent-D2kLt6Dl.js +0 -597
@@ -1,597 +0,0 @@
1
- import{r as e,t}from"./chunk-CilyBKbf.js";import{o as n,s as r}from"./index-j4-NuleT.js";import{buildDynamicSystemPrompt as i}from"./context-builder-_HS0v2ma.js";var a=Object.defineProperty,o=(e,t)=>{let n={};for(var r in e)a(n,r,{get:e[r],enumerable:!0});return t||a(n,Symbol.toStringTag,{value:`Module`}),n};function s(e){let t=Symbol.for(e);return{brand(n,r){let i=r?Symbol.for(`${e}.${r}`):t;class a extends n{[i]=!0;constructor(...e){super(...e)}static isInstance(e){return typeof e==`object`&&!!e&&i in e&&e[i]===!0}}return Object.defineProperty(a,`name`,{value:n.name}),a},sub(t){return s(`${e}.${t}`)},isInstance(e){return typeof e==`object`&&!!e&&t in e&&e[t]===!0}}}var c=s(`langchain`),l=o({ContextOverflowError:()=>m,LangChainError:()=>f,ModelAbortError:()=>p,addLangChainErrorFields:()=>u,ns:()=>d});function u(e,t){return e.lc_error_code=t,e.message=`${e.message}\n\nTroubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${t}/\n`,e}var d=c.sub(`error`),f=class extends d.brand(Error){name=`LangChainError`;constructor(e){super(e),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}},p=class extends d.brand(f,`model-abort`){name=`ModelAbortError`;partialOutput;constructor(e,t){super(e),this.partialOutput=t}},m=class e extends d.brand(f,`context-overflow`){name=`ContextOverflowError`;cause;constructor(e){super(e??`Input exceeded the model's context window.`)}static fromError(t){let n=new e(t.message);return n.cause=t,n}};function h(e){return!!(e&&typeof e==`object`&&`type`in e&&e.type===`tool_call`)}function g(e){return!!(e&&typeof e==`object`&&`toolCall`in e&&e.toolCall!=null&&typeof e.toolCall==`object`&&`id`in e.toolCall&&typeof e.toolCall.id==`string`)}var _=class extends Error{output;constructor(e,t){super(e),this.output=t}};function v(e,t=b){e=e.trim();let n=e.indexOf("```");if(n===-1)return t(e);let r=e.substring(n+3);r.startsWith(`json
2
- `)?r=r.substring(5):r.startsWith(`json`)?r=r.substring(4):r.startsWith(`
3
- `)&&(r=r.substring(1));let i=r.indexOf("```"),a=r;return i!==-1&&(a=r.substring(0,i)),t(a.trim())}function y(e){try{return JSON.parse(e)}catch{}let t=e.trim();if(t.length===0)throw Error(`Unexpected end of JSON input`);let n=0;function r(){for(;n<t.length&&/\s/.test(t[n]);)n+=1}function i(){if(t[n]!==`"`)throw Error(`Expected '"' at position ${n}, got '${t[n]}'`);n+=1;let e=``,r=!1;for(;n<t.length;){let i=t[n];if(r){if(i===`n`)e+=`
4
- `;else if(i===`t`)e+=` `;else if(i===`r`)e+=`\r`;else if(i===`\\`)e+=`\\`;else if(i===`"`)e+=`"`;else if(i===`b`)e+=`\b`;else if(i===`f`)e+=`\f`;else if(i===`/`)e+=`/`;else if(i===`u`){let r=t.substring(n+1,n+5);if(/^[0-9A-Fa-f]{0,4}$/.test(r))r.length===4?e+=String.fromCharCode(Number.parseInt(r,16)):e+=`u${r}`,n+=r.length;else throw Error(`Invalid unicode escape sequence '\\u${r}' at position ${n}`)}else throw Error(`Invalid escape sequence '\\${i}' at position ${n}`);r=!1}else if(i===`\\`)r=!0;else if(i===`"`)return n+=1,e;else e+=i;n+=1}return r&&(e+=`\\`),e}function a(){let e=n,r=``;if(t[n]===`-`&&(r+=`-`,n+=1),n<t.length&&t[n]===`0`&&(r+=`0`,n+=1,t[n]>=`0`&&t[n]<=`9`))throw Error(`Invalid number at position ${e}`);if(n<t.length&&t[n]>=`1`&&t[n]<=`9`)for(;n<t.length&&t[n]>=`0`&&t[n]<=`9`;)r+=t[n],n+=1;if(n<t.length&&t[n]===`.`)for(r+=`.`,n+=1;n<t.length&&t[n]>=`0`&&t[n]<=`9`;)r+=t[n],n+=1;if(n<t.length&&(t[n]===`e`||t[n]===`E`))for(r+=t[n],n+=1,n<t.length&&(t[n]===`+`||t[n]===`-`)&&(r+=t[n],n+=1);n<t.length&&t[n]>=`0`&&t[n]<=`9`;)r+=t[n],n+=1;if(r===`-`)return-0;let i=Number.parseFloat(r);if(Number.isNaN(i))throw n=e,Error(`Invalid number '${r}' at position ${e}`);return i}function o(){if(r(),n>=t.length)throw Error(`Unexpected end of input at position ${n}`);let e=t[n];if(e===`{`)return c();if(e===`[`)return s();if(e===`"`)return i();if(`null`.startsWith(t.substring(n,n+4)))return n+=Math.min(4,t.length-n),null;if(`true`.startsWith(t.substring(n,n+4)))return n+=Math.min(4,t.length-n),!0;if(`false`.startsWith(t.substring(n,n+5)))return n+=Math.min(5,t.length-n),!1;if(e===`-`||e>=`0`&&e<=`9`)return a();throw Error(`Unexpected character '${e}' at position ${n}`)}function s(){if(t[n]!==`[`)throw Error(`Expected '[' at position ${n}, got '${t[n]}'`);let e=[];if(n+=1,r(),n>=t.length)return e;if(t[n]===`]`)return n+=1,e;for(;n<t.length;){if(r(),n>=t.length||(e.push(o()),r(),n>=t.length))return e;if(t[n]===`]`)return n+=1,e;if(t[n]===`,`){n+=1;continue}throw Error(`Expected ',' or ']' at position ${n}, got '${t[n]}'`)}return e}function c(){if(t[n]!==`{`)throw Error(`Expected '{' at position ${n}, got '${t[n]}'`);let e={};if(n+=1,r(),n>=t.length)return e;if(t[n]===`}`)return n+=1,e;for(;n<t.length;){if(r(),n>=t.length)return e;let a=i();if(r(),n>=t.length)return e;if(t[n]!==`:`)throw Error(`Expected ':' at position ${n}, got '${t[n]}'`);if(n+=1,r(),n>=t.length||(e[a]=o(),r(),n>=t.length))return e;if(t[n]===`}`)return n+=1,e;if(t[n]===`,`){n+=1;continue}throw Error(`Expected ',' or '}' at position ${n}, got '${t[n]}'`)}return e}let l=o();if(r(),n<t.length)throw Error(`Unexpected character '${t[n]}' at position ${n}`);return l}function b(e){try{return e===void 0?null:y(e)}catch{return null}}var ee=t(((e,t)=>{t.exports=function(e,t){if(typeof e!=`string`)throw TypeError(`Expected a string`);return t=t===void 0?`_`:t,e.replace(/([a-z\d])([A-Z])/g,`$1`+t+`$2`).replace(/([A-Z]+)([A-Z][a-z\d]+)/g,`$1`+t+`$2`).toLowerCase()}})),x=t(((e,t)=>{var n=/[\p{Lu}]/u,r=/[\p{Ll}]/u,i=/^[\p{Lu}](?![\p{Lu}])/gu,a=/([\p{Alpha}\p{N}_]|$)/u,o=/[_.\- ]+/,s=RegExp(`^`+o.source),c=new RegExp(o.source+a.source,`gu`),l=RegExp(`\\d+`+a.source,`gu`),u=(e,t,i)=>{let a=!1,o=!1,s=!1;for(let c=0;c<e.length;c++){let l=e[c];a&&n.test(l)?(e=e.slice(0,c)+`-`+e.slice(c),a=!1,s=o,o=!0,c++):o&&s&&r.test(l)?(e=e.slice(0,c-1)+`-`+e.slice(c-1),s=o,o=!1,a=!0):(a=t(l)===l&&i(l)!==l,s=o,o=i(l)===l&&t(l)!==l)}return e},d=(e,t)=>(i.lastIndex=0,e.replace(i,e=>t(e))),f=(e,t)=>(c.lastIndex=0,l.lastIndex=0,e.replace(c,(e,n)=>t(n)).replace(l,e=>t(e))),p=(e,t)=>{if(!(typeof e==`string`||Array.isArray(e)))throw TypeError("Expected the input to be `string | string[]`");if(t={pascalCase:!1,preserveConsecutiveUppercase:!1,...t},e=Array.isArray(e)?e.map(e=>e.trim()).filter(e=>e.length).join(`-`):e.trim(),e.length===0)return``;let n=t.locale===!1?e=>e.toLowerCase():e=>e.toLocaleLowerCase(t.locale),r=t.locale===!1?e=>e.toUpperCase():e=>e.toLocaleUpperCase(t.locale);return e.length===1?t.pascalCase?r(e):n(e):(e!==n(e)&&(e=u(e,n,r)),e=e.replace(s,``),e=t.preserveConsecutiveUppercase?d(e,n):n(e),t.pascalCase&&(e=r(e.charAt(0))+e.slice(1)),f(e,r))};t.exports=p,t.exports.default=p})),te=e(ee(),1),S=e(x(),1);function ne(e,t){return t?.[e]||(0,te.default)(e)}function re(e,t){return t?.[e]||(0,S.default)(e)}function ie(e,t,n){let r={};for(let i in e)Object.hasOwn(e,i)&&(r[t(i,n)]=e[i]);return r}var ae=`__lc_escaped__`;function oe(e){return`lc`in e||Object.keys(e).length===1&&`__lc_escaped__`in e}function se(e){return{[ae]:e}}function ce(e){return Object.keys(e).length===1&&`__lc_escaped__`in e}function C(e){return typeof e==`object`&&!!e&&`lc_serializable`in e&&typeof e.toJSON==`function`}function le(e){let t;return t=typeof e==`object`&&e?`lc_id`in e&&Array.isArray(e.lc_id)?e.lc_id:[e.constructor?.name??`Object`]:[typeof e],{lc:1,type:`not_implemented`,id:t}}function ue(e,t=new WeakSet){if(typeof e==`object`&&e&&!Array.isArray(e)){if(t.has(e))return le(e);if(C(e))return e;t.add(e);let n=e;if(oe(n))return t.delete(e),se(n);let r={};for(let[e,i]of Object.entries(n))r[e]=ue(i,t);return t.delete(e),r}return Array.isArray(e)?e.map(e=>ue(e,t)):e}function de(e){if(typeof e==`object`&&e&&!Array.isArray(e)){let t=e;if(ce(t))return t[ae];let n={};for(let[e,r]of Object.entries(t))n[e]=de(r);return n}return Array.isArray(e)?e.map(e=>de(e)):e}var fe=o({Serializable:()=>ge,get_lc_unique_name:()=>he});function pe(e){return Array.isArray(e)?[...e]:{...e}}function me(e,t){let n=pe(e);for(let[e,r]of Object.entries(t)){let[t,...i]=e.split(`.`).reverse(),a=n;for(let e of i.reverse()){if(a[e]===void 0)break;a[e]=pe(a[e]),a=a[e]}a[t]!==void 0&&(a[t]={lc:1,type:`secret`,id:[r]})}return n}function he(e){let t=Object.getPrototypeOf(e);return typeof e.lc_name==`function`&&(typeof t.lc_name!=`function`||e.lc_name()!==t.lc_name())?e.lc_name():e.name}var ge=class e{lc_serializable=!1;lc_kwargs;static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,he(this.constructor)]}get lc_secrets(){}get lc_attributes(){}get lc_aliases(){}get lc_serializable_keys(){}constructor(e,...t){this.lc_serializable_keys===void 0?this.lc_kwargs=e??{}:this.lc_kwargs=Object.fromEntries(Object.entries(e||{}).filter(([e])=>this.lc_serializable_keys?.includes(e)))}toJSON(){if(!this.lc_serializable||this.lc_kwargs instanceof e||typeof this.lc_kwargs!=`object`||Array.isArray(this.lc_kwargs))return this.toJSONNotImplemented();let t={},n={},r=Object.keys(this.lc_kwargs).reduce((e,t)=>(e[t]=t in this?this[t]:this.lc_kwargs[t],e),{});for(let e=Object.getPrototypeOf(this);e;e=Object.getPrototypeOf(e))Object.assign(t,Reflect.get(e,`lc_aliases`,this)),Object.assign(n,Reflect.get(e,`lc_secrets`,this)),Object.assign(r,Reflect.get(e,`lc_attributes`,this));Object.keys(n).forEach(e=>{let t=this,n=r,[i,...a]=e.split(`.`).reverse();for(let e of a.reverse()){if(!(e in t)||t[e]===void 0)return;(!(e in n)||n[e]===void 0)&&(typeof t[e]==`object`&&t[e]!=null?n[e]={}:Array.isArray(t[e])&&(n[e]=[])),t=t[e],n=n[e]}i in t&&t[i]!==void 0&&(n[i]=n[i]||t[i])});let i={},a=new WeakSet;a.add(this);for(let[e,t]of Object.entries(r))i[e]=ue(t,a);let o=ie(Object.keys(n).length?me(i,n):i,ne,t);return{lc:1,type:`constructor`,id:this.lc_id,kwargs:o}}toJSONNotImplemented(){return{lc:1,type:`not_implemented`,id:this.lc_id}}};function _e(e){return typeof e==`object`&&!!e&&`type`in e&&typeof e.type==`string`&&`source_type`in e&&(e.source_type===`url`||e.source_type===`base64`||e.source_type===`text`||e.source_type===`id`)}function ve(e){return _e(e)&&e.source_type===`url`&&`url`in e&&typeof e.url==`string`}function ye(e){return _e(e)&&e.source_type===`base64`&&`data`in e&&typeof e.data==`string`}function be(e){return _e(e)&&e.source_type===`text`&&`text`in e&&typeof e.text==`string`}function xe(e){return _e(e)&&e.source_type===`id`&&`id`in e&&typeof e.id==`string`}function Se(e){if(_e(e)){if(e.source_type===`url`)return{type:`image_url`,image_url:{url:e.url}};if(e.source_type===`base64`){if(!e.mime_type)throw Error(`mime_type key is required for base64 data.`);return{type:`image_url`,image_url:{url:`data:${e.mime_type};base64,${e.data}`}}}}throw Error(`Unsupported source type. Only 'url' and 'base64' are supported.`)}function Ce(e){let t=e.split(`;`)[0].split(`/`);if(t.length!==2)throw Error(`Invalid mime type: "${e}" - does not match type/subtype format.`);let n=t[0].trim(),r=t[1].trim();if(n===``||r===``)throw Error(`Invalid mime type: "${e}" - type or subtype is empty.`);let i={};for(let t of e.split(`;`).slice(1)){let n=t.split(`=`);if(n.length!==2)throw Error(`Invalid parameter syntax in mime type: "${e}".`);let r=n[0].trim(),a=n[1].trim();if(r===``)throw Error(`Invalid parameter syntax in mime type: "${e}".`);i[r]=a}return{type:n,subtype:r,parameters:i}}function we({dataUrl:e,asTypedArray:t=!1}){let n=e.match(/^data:(\w+\/\w+);base64,([A-Za-z0-9+/]+=*)$/),r;if(n){r=n[1].toLowerCase();let e=t?Uint8Array.from(atob(n[2]),e=>e.charCodeAt(0)):n[2];return{mime_type:r,data:e}}}function Te(e,t){if(e.type===`text`){if(!t.fromStandardTextBlock)throw Error(`Converter for ${t.providerName} does not implement \`fromStandardTextBlock\` method.`);return t.fromStandardTextBlock(e)}if(e.type===`image`){if(!t.fromStandardImageBlock)throw Error(`Converter for ${t.providerName} does not implement \`fromStandardImageBlock\` method.`);return t.fromStandardImageBlock(e)}if(e.type===`audio`){if(!t.fromStandardAudioBlock)throw Error(`Converter for ${t.providerName} does not implement \`fromStandardAudioBlock\` method.`);return t.fromStandardAudioBlock(e)}if(e.type===`file`){if(!t.fromStandardFileBlock)throw Error(`Converter for ${t.providerName} does not implement \`fromStandardFileBlock\` method.`);return t.fromStandardFileBlock(e)}throw Error(`Unable to convert content block type '${e.type}' to provider-specific format: not recognized.`)}function w(e,t){return T(e)&&e.type===t}function T(e){return typeof e==`object`&&!!e}function Ee(e){return Array.isArray(e)}function E(e){return typeof e==`string`}function De(e){return typeof e==`number`}function Oe(e){return e instanceof Uint8Array}function D(e){try{return JSON.parse(e)}catch{return}}var ke=e=>e();function Ae(e){if(e.type===`char_location`&&E(e.document_title)&&De(e.start_char_index)&&De(e.end_char_index)&&E(e.cited_text)){let{document_title:t,start_char_index:n,end_char_index:r,cited_text:i,...a}=e;return{...a,type:`citation`,source:`char`,title:t??void 0,startIndex:n,endIndex:r,citedText:i}}if(e.type===`page_location`&&E(e.document_title)&&De(e.start_page_number)&&De(e.end_page_number)&&E(e.cited_text)){let{document_title:t,start_page_number:n,end_page_number:r,cited_text:i,...a}=e;return{...a,type:`citation`,source:`page`,title:t??void 0,startIndex:n,endIndex:r,citedText:i}}if(e.type===`content_block_location`&&E(e.document_title)&&De(e.start_block_index)&&De(e.end_block_index)&&E(e.cited_text)){let{document_title:t,start_block_index:n,end_block_index:r,cited_text:i,...a}=e;return{...a,type:`citation`,source:`block`,title:t??void 0,startIndex:n,endIndex:r,citedText:i}}if(e.type===`web_search_result_location`&&E(e.url)&&E(e.title)&&E(e.encrypted_index)&&E(e.cited_text)){let{url:t,title:n,encrypted_index:r,cited_text:i,...a}=e;return{...a,type:`citation`,source:`url`,url:t,title:n,startIndex:Number(r),endIndex:Number(r),citedText:i}}if(e.type===`search_result_location`&&E(e.source)&&E(e.title)&&De(e.start_block_index)&&De(e.end_block_index)&&E(e.cited_text)){let{source:t,title:n,start_block_index:r,end_block_index:i,cited_text:a,...o}=e;return{...o,type:`citation`,source:`search`,url:t,title:n??void 0,startIndex:r,endIndex:i,citedText:a}}}function je(e){if(w(e,`document`)&&T(e.source)&&`type`in e.source){if(e.source.type===`base64`&&E(e.source.media_type)&&E(e.source.data))return{type:`file`,mimeType:e.source.media_type,data:e.source.data};if(e.source.type===`url`&&E(e.source.url))return{type:`file`,url:e.source.url};if(e.source.type===`file`&&E(e.source.file_id))return{type:`file`,fileId:e.source.file_id};if(e.source.type===`text`&&E(e.source.data))return{type:`file`,mimeType:String(e.source.media_type??`text/plain`),data:e.source.data}}else if(w(e,`image`)&&T(e.source)&&`type`in e.source){if(e.source.type===`base64`&&E(e.source.media_type)&&E(e.source.data))return{type:`image`,mimeType:e.source.media_type,data:e.source.data};if(e.source.type===`url`&&E(e.source.url))return{type:`image`,url:e.source.url};if(e.source.type===`file`&&E(e.source.file_id))return{type:`image`,fileId:e.source.file_id}}}function Me(e){function*t(){for(let t of e){let e=je(t);e?yield e:yield t}}return Array.from(t())}function Ne(e){function*t(){let t=typeof e.content==`string`?[{type:`text`,text:e.content}]:e.content;for(let n of t){if(w(n,`text`)&&E(n.text)){let{text:e,citations:t,...r}=n;if(Ee(t)&&t.length){let n=t.reduce((e,t)=>{let n=Ae(t);return n?[...e,n]:e},[]);yield{...r,type:`text`,text:e,annotations:n};continue}else{yield{...r,type:`text`,text:e};continue}}else if(w(n,`thinking`)&&E(n.thinking)){let{thinking:e,signature:t,...r}=n;yield{...r,type:`reasoning`,reasoning:e,signature:t};continue}else if(w(n,`redacted_thinking`)){yield{type:`non_standard`,value:n};continue}else if(w(n,`tool_use`)&&E(n.name)&&E(n.id)){yield{type:`tool_call`,id:n.id,name:n.name,args:n.input};continue}else if(w(n,`input_json_delta`)){if(Fe(e)&&e.tool_call_chunks?.length){let t=e.tool_call_chunks[0];yield{type:`tool_call_chunk`,id:t.id,name:t.name,args:t.args,index:t.index};continue}}else if(w(n,`server_tool_use`)&&E(n.name)&&E(n.id)){let{name:e,id:t}=n;if(e===`web_search`){yield{id:t,type:`server_tool_call`,name:`web_search`,args:{query:ke(()=>{if(typeof n.input==`string`)return n.input;if(T(n.input)&&E(n.input.query))return n.input.query;if(E(n.partial_json)){let e=D(n.partial_json);if(e?.query)return e.query}return``})}};continue}else if(n.name===`code_execution`){yield{id:t,type:`server_tool_call`,name:`code_execution`,args:{code:ke(()=>{if(typeof n.input==`string`)return n.input;if(T(n.input)&&E(n.input.code))return n.input.code;if(E(n.partial_json)){let e=D(n.partial_json);if(e?.code)return e.code}return``})}};continue}}else if(w(n,`web_search_tool_result`)&&E(n.tool_use_id)&&Ee(n.content)){let{content:e,tool_use_id:t}=n;yield{type:`server_tool_call_result`,name:`web_search`,toolCallId:t,status:`success`,output:{urls:e.reduce((e,t)=>w(t,`web_search_result`)?[...e,t.url]:e,[])}};continue}else if(w(n,`code_execution_tool_result`)&&E(n.tool_use_id)&&T(n.content)){yield{type:`server_tool_call_result`,name:`code_execution`,toolCallId:n.tool_use_id,status:`success`,output:n.content};continue}else if(w(n,`mcp_tool_use`)){yield{id:n.id,type:`server_tool_call`,name:`mcp_tool_use`,args:n.input};continue}else if(w(n,`mcp_tool_result`)&&E(n.tool_use_id)&&T(n.content)){yield{type:`server_tool_call_result`,name:`mcp_tool_use`,toolCallId:n.tool_use_id,status:`success`,output:n.content};continue}else if(w(n,`container_upload`)){yield{type:`server_tool_call`,name:`container_upload`,args:n.input};continue}else if(w(n,`search_result`)){yield{id:n.id,type:`non_standard`,value:n};continue}else if(w(n,`tool_result`)){yield{id:n.id,type:`non_standard`,value:n};continue}else{let e=je(n);if(e){yield e;continue}}yield{type:`non_standard`,value:n}}}return Array.from(t())}var Pe={translateContent:Ne,translateContentChunk:Ne};function Fe(e){return typeof e?._getType==`function`&&typeof e.concat==`function`&&e._getType()===`ai`}function Ie(e){return ve(e)?{type:e.type,mimeType:e.mime_type,url:e.url,metadata:e.metadata}:ye(e)?{type:e.type,mimeType:e.mime_type??`application/octet-stream`,data:e.data,metadata:e.metadata}:xe(e)?{type:e.type,mimeType:e.mime_type,fileId:e.id,metadata:e.metadata}:e}function Le(e){return e.map(Ie)}function Re(e){return!!(w(e,`image_url`)&&T(e.image_url)||w(e,`input_audio`)&&T(e.input_audio)||w(e,`file`)&&T(e.file))}function ze(e){if(w(e,`image_url`)&&T(e.image_url)&&E(e.image_url.url)){let t=we({dataUrl:e.image_url.url});return t?{type:`image`,mimeType:t.mime_type,data:t.data}:{type:`image`,url:e.image_url.url}}else if(w(e,`input_audio`)&&T(e.input_audio)&&E(e.input_audio.data)&&E(e.input_audio.format))return{type:`audio`,data:e.input_audio.data,mimeType:`audio/${e.input_audio.format}`};else if(w(e,`file`)&&T(e.file)&&E(e.file.data)){let t=we({dataUrl:e.file.data});if(t)return{type:`file`,data:t.data,mimeType:t.mime_type};if(E(e.file.file_id))return{type:`file`,fileId:e.file.file_id}}return e}function Be(e){let t=[];typeof e.content==`string`?e.content.length>0&&t.push({type:`text`,text:e.content}):t.push(...He(e.content));for(let n of e.tool_calls??[])t.push({type:`tool_call`,id:n.id,name:n.name,args:n.args});return t}function Ve(e){let t=[];typeof e.content==`string`?e.content.length>0&&t.push({type:`text`,text:e.content}):t.push(...He(e.content));for(let n of e.tool_calls??[])t.push({type:`tool_call`,id:n.id,name:n.name,args:n.args});return t}function He(e){let t=[];for(let n of e)Re(n)?t.push(ze(n)):t.push(n);return t}function Ue(e){if(e.type===`url_citation`){let{url:t,title:n,start_index:r,end_index:i}=e;return{type:`citation`,url:t,title:n,startIndex:r,endIndex:i}}if(e.type===`file_citation`){let{file_id:t,filename:n,index:r}=e;return{type:`citation`,title:n,startIndex:r,endIndex:r,fileId:t}}return e}function We(e){function*t(){T(e.additional_kwargs?.reasoning)&&Ee(e.additional_kwargs.reasoning.summary)&&(yield{type:`reasoning`,reasoning:e.additional_kwargs.reasoning.summary.reduce((e,t)=>T(t)&&E(t.text)?`${e}${t.text}`:e,``)});let t=typeof e.content==`string`?[{type:`text`,text:e.content}]:e.content;for(let e of t)if(w(e,`text`)){let{text:t,annotations:n,phase:r,extras:i,...a}=e,o=T(i)?{...i}:{};E(r)&&(o.phase=r);let s=Object.keys(o).length>0?{extras:o}:{};Array.isArray(n)?yield{...a,...s,type:`text`,text:String(t),annotations:n.map(Ue)}:yield{...a,...s,type:`text`,text:String(t)}}for(let t of e.tool_calls??[])yield{type:`tool_call`,id:t.id,name:t.name,args:t.args};if(T(e.additional_kwargs)&&Ee(e.additional_kwargs.tool_outputs))for(let t of e.additional_kwargs.tool_outputs){if(w(t,`web_search_call`)){let e={};if(T(t.action)&&E(t.action.query)&&(e.query=t.action.query),yield{id:t.id,type:`server_tool_call`,name:`web_search`,args:e},t.status===`completed`||t.status===`failed`){let e={};T(t.action)&&(e.action=t.action),yield{type:`server_tool_call_result`,toolCallId:E(t.id)?t.id:``,status:t.status===`completed`?`success`:`error`,output:e}}continue}else if(w(t,`file_search_call`)){yield{id:t.id,type:`server_tool_call`,name:`file_search`,args:{queries:Ee(t.queries)?t.queries:[]}},(t.status===`completed`||t.status===`failed`)&&(yield{type:`server_tool_call_result`,toolCallId:E(t.id)?t.id:``,status:t.status===`completed`?`success`:`error`,output:Ee(t.results)?{results:t.results}:{}});continue}else if(w(t,`computer_call`)){yield{type:`non_standard`,value:t};continue}else if(w(t,`code_interpreter_call`)){if(E(t.code)&&(yield{id:t.id,type:`server_tool_call`,name:`code_interpreter`,args:{code:t.code}}),Ee(t.outputs)){let e=ke(()=>{if(t.status!==`in_progress`){if(t.status===`completed`)return 0;if(t.status===`incomplete`)return 127;if(t.status!==`interpreting`&&t.status===`failed`)return 1}});for(let n of t.outputs)if(w(n,`logs`)){yield{type:`server_tool_call_result`,toolCallId:t.id??``,status:`success`,output:{type:`code_interpreter_output`,returnCode:e??0,stderr:[0,void 0].includes(e)?void 0:String(n.logs),stdout:[0,void 0].includes(e)?String(n.logs):void 0}};continue}}continue}else if(w(t,`mcp_call`)){yield{id:t.id,type:`server_tool_call`,name:`mcp_call`,args:t.input};continue}else if(w(t,`mcp_list_tools`)){yield{id:t.id,type:`server_tool_call`,name:`mcp_list_tools`,args:t.input};continue}else if(w(t,`mcp_approval_request`)){yield{type:`non_standard`,value:t};continue}else if(w(t,`tool_search_call`)){let e={};T(t.arguments)&&Object.assign(e,t.arguments);let n={};E(t.execution)&&(n.execution=t.execution),E(t.status)&&(n.status=t.status),E(t.call_id)&&(n.call_id=t.call_id),yield{id:E(t.id)?t.id:``,type:`server_tool_call`,name:`tool_search`,args:e,...Object.keys(n).length>0?{extras:n}:{}};continue}else if(w(t,`tool_search_output`)){let e={name:`tool_search`};E(t.execution)&&(e.execution=t.execution),yield{type:`server_tool_call_result`,toolCallId:E(t.id)?t.id:``,status:t.status===`completed`?`success`:t.status===`failed`?`error`:`success`,output:{tools:Ee(t.tools)?t.tools:[]},extras:e};continue}else if(w(t,`image_generation_call`)){E(t.result)&&(yield{type:`image`,mimeType:`image/png`,data:t.result,id:E(t.id)?t.id:void 0,metadata:{status:E(t.status)?t.status:void 0}}),yield{type:`non_standard`,value:t};continue}T(t)&&(yield{type:`non_standard`,value:t})}}return Array.from(t())}function Ge(e){function*t(){yield*We(e);for(let t of e.tool_call_chunks??[])yield{type:`tool_call_chunk`,id:t.id,name:t.name,args:t.args}}return Array.from(t())}var Ke={translateContent:e=>typeof e.content==`string`?Be(e):We(e),translateContentChunk:e=>typeof e.content==`string`?Ve(e):Ge(e)};function qe(e){return typeof e==`object`&&!!e&&`type`in e&&`content`in e&&(typeof e.content==`string`||Array.isArray(e.content))}function Je(e,t=`pretty`){return t===`pretty`?Ye(e):JSON.stringify(e)}function Ye(e){let t=[],n=` ${e.type.charAt(0).toUpperCase()+e.type.slice(1)} Message `,r=Math.floor((80-n.length)/2),i=`=`.repeat(r),a=n.length%2==0?i:`${i}=`;if(t.push(`${i}${n}${a}`),e.type===`ai`){let n=e;if(n.tool_calls&&n.tool_calls.length>0){t.push(`Tool Calls:`);for(let e of n.tool_calls){t.push(` ${e.name} (${e.id})`),t.push(` Call ID: ${e.id}`),t.push(` Args:`);for(let[n,r]of Object.entries(e.args))t.push(` ${n}: ${typeof r==`object`?JSON.stringify(r):r}`)}}}if(e.type===`tool`){let n=e;n.name&&t.push(`Name: ${n.name}`)}return typeof e.content==`string`&&e.content.trim()&&(t.length>1&&t.push(``),t.push(e.content)),t.join(`
5
- `)}var Xe=Symbol.for(`langchain.message`);function Ze(e){return Array.isArray(e)?e:typeof e==`string`?e===``?[]:[{type:`text`,text:e}]:e==null?[]:[e]}function Qe(e,t){if(typeof e==`string`)return e===``?t:typeof t==`string`?e+t:Array.isArray(t)&&t.length===0?e:Array.isArray(t)&&t.some(e=>_e(e))?[{type:`text`,source_type:`text`,text:e},...t]:[{type:`text`,text:e},...t];if(Array.isArray(t)){let n=Ze(e);return lt(n,t)??[...n,...t]}else if(t===``)return e;else if(Array.isArray(e)&&e.some(e=>_e(e)))return[...e,{type:`file`,source_type:`text`,text:t}];else return[...Ze(e),{type:`text`,text:t}]}function $e(e,t){return e===`error`||t===`error`?`error`:`success`}function et(e,t){function n(e,r){if(typeof e!=`object`||!e||e===void 0)return e;if(r>=t)return Array.isArray(e)?`[Array]`:`[Object]`;if(Array.isArray(e))return e.map(e=>n(e,r+1));let i={};for(let t of Object.keys(e))i[t]=n(e[t],r+1);return i}return JSON.stringify(n(e,0),null,2)}var tt=class extends ge{lc_namespace=[`langchain_core`,`messages`];lc_serializable=!0;get lc_aliases(){return{additional_kwargs:`additional_kwargs`,response_metadata:`response_metadata`}}[Xe]=!0;id;name;content;additional_kwargs;response_metadata;_getType(){return this.type}getType(){return this._getType()}constructor(e){let t=typeof e==`string`||Array.isArray(e)?{content:e}:e;t.additional_kwargs||={},t.response_metadata||={},super(t),this.name=t.name,t.content===void 0&&t.contentBlocks!==void 0?(this.content=t.contentBlocks,this.response_metadata={output_version:`v1`,...t.response_metadata}):t.content===void 0?(this.content=[],this.response_metadata=t.response_metadata):(this.content=t.content??[],this.response_metadata=t.response_metadata),this.additional_kwargs=t.additional_kwargs,this.id=t.id}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(){let e=typeof this.content==`string`?[{type:`text`,text:this.content}]:this.content;return[Le,He,Me].reduce((e,t)=>t(e),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&&Xe in e&&e[Xe]===!0&&qe(e)}_updateId(e){this.id=e,this.lc_kwargs.id=e}get[Symbol.toStringTag](){return this.constructor.lc_name()}[Symbol.for(`nodejs.util.inspect.custom`)](e){if(e===null)return this;let t=et(this._printableFields,Math.max(4,e));return`${this.constructor.lc_name()} ${t}`}toFormattedString(e=`pretty`){return Je(this,e)}};function nt(e){return Array.isArray(e)&&e.every(e=>typeof e.index==`number`)}var rt=[`index`,`created`,`timestamp`];function it(e,t,n){let r=n?.ignoreKeys??rt;if(e==null&&t==null)return;if(e==null||t==null)return e??t;let i={...e};for(let[e,a]of Object.entries(t))if(i[e]==null)i[e]=a;else if(a==null)continue;else if(typeof i[e]!=typeof a||Array.isArray(i[e])!==Array.isArray(a))throw Error(`field[${e}] already exists in the message chunk, but with a different type.`);else if(typeof i[e]==`string`){if(e===`type`)continue;if([`id`,`name`,`output_version`,`model_provider`].includes(e))a&&(i[e]=a);else if(r.includes(e))continue;else i[e]+=a}else if(typeof i[e]==`number`){if(r.includes(e))continue;i[e]=i[e]+a}else if(typeof i[e]==`object`&&!Array.isArray(i[e]))i[e]=it(i[e],a,n);else if(Array.isArray(i[e]))i[e]=lt(i[e],a,n);else if(i[e]===a)continue;else console.warn(`field[${e}] already exists in this message chunk and value has unsupported type.`);return i}function at(e){return typeof e==`number`||typeof e==`string`}function ot(e){return typeof e!=`object`||!e||!(`index`in e)?!1:at(e.index)}function st(e){if(typeof e!=`object`||!e||!(`id`in e))return!1;let t=e.id;return t!=null&&t!==``}function ct(e,t){let n=ot(t),r=st(t);return!n&&!r?-1:e.findIndex(e=>{let i=ot(e),a=st(e);return n&&i?e.index===t.index?a&&r?e.id===t.id:!0:!1:!n&&!i&&r&&a?e.id===t.id:!1})}function lt(e,t,n){if(!(e==null&&t==null)){if(e==null||t==null)return e||t;{let r=[...e];for(let e of t){let t=ct(r,e);if(t!==-1)r[t]=it(r[t],e,n);else if(typeof e==`object`&&e&&`text`in e&&e.text===``)continue;else r.push(e)}return r}}}function ut(e,t,n){if(!(e==null&&t==null)){if(e==null||t==null)return e??t;if(typeof e!=typeof t)throw Error(`Cannot merge objects of different types.\nLeft ${typeof e}\nRight ${typeof t}`);if(typeof e==`string`&&typeof t==`string`)return e+t;if(Array.isArray(e)&&Array.isArray(t))return lt(e,t,n);if(typeof e==`object`&&typeof t==`object`)return it(e,t,n);if(e===t)return e;throw Error(`Can not merge objects of different types.\nLeft ${e}\nRight ${t}`)}}var dt=class e extends tt{static isInstance(t){if(!super.isInstance(t))return!1;let n=Object.getPrototypeOf(t);for(;n!==null;){if(n===e.prototype)return!0;n=Object.getPrototypeOf(n)}return!1}};function ft(e){return typeof e.role==`string`}function pt(e){return typeof e?._getType==`function`}function mt(e){return dt.isInstance(e)}var ht=o({ToolMessage:()=>_t,ToolMessageChunk:()=>vt,defaultToolCallParser:()=>yt,isDirectToolOutput:()=>gt,isToolMessage:()=>bt,isToolMessageChunk:()=>xt});function gt(e){return typeof e==`object`&&!!e&&`lc_direct_tool_output`in e&&e.lc_direct_tool_output===!0}var _t=class extends tt{static lc_name(){return`ToolMessage`}get lc_aliases(){return{tool_call_id:`tool_call_id`}}lc_direct_tool_output=!0;type=`tool`;status;tool_call_id;metadata;artifact;constructor(e,t,n){let r=typeof e==`string`||Array.isArray(e)?{content:e,name:n,tool_call_id:t}:e;super(r),this.tool_call_id=r.tool_call_id,this.artifact=r.artifact,this.status=r.status,this.metadata=r.metadata}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}}},vt=class extends dt{type=`tool`;tool_call_id;status;artifact;constructor(e){super(e),this.tool_call_id=e.tool_call_id,this.artifact=e.artifact,this.status=e.status}static lc_name(){return`ToolMessageChunk`}concat(e){let t=this.constructor;return new t({content:Qe(this.content,e.content),additional_kwargs:it(this.additional_kwargs,e.additional_kwargs),response_metadata:it(this.response_metadata,e.response_metadata),artifact:ut(this.artifact,e.artifact),tool_call_id:this.tool_call_id,id:this.id??e.id,status:$e(this.status,e.status)})}get _printableFields(){return{...super._printableFields,tool_call_id:this.tool_call_id,artifact:this.artifact}}};function yt(e){let t=[],n=[];for(let r of e)if(r.function){let e=r.function.name;try{let n=JSON.parse(r.function.arguments);t.push({name:e||``,args:n||{},id:r.id})}catch{n.push({name:e,args:r.function.arguments,id:r.id,error:`Malformed args.`})}}else continue;return[t,n]}function bt(e){return typeof e==`object`&&!!e&&`getType`in e&&typeof e.getType==`function`&&e.getType()===`tool`}function xt(e){return e._getType()===`tool`}function St(e){switch(e){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 Ct(e){if(T(e.document)&&T(e.document.source)){let t=St(T(e.document)&&E(e.document.format)?e.document.format:``);if(T(e.document.source)){if(T(e.document.source.s3Location)&&E(e.document.source.s3Location.uri))return{type:`file`,mimeType:t,fileId:e.document.source.s3Location.uri};if(Oe(e.document.source.bytes))return{type:`file`,mimeType:t,data:e.document.source.bytes};if(E(e.document.source.text))return{type:`file`,mimeType:t,data:Buffer.from(e.document.source.text).toString(`base64`)};if(Ee(e.document.source.content))return{type:`file`,mimeType:t,data:e.document.source.content.reduce((e,t)=>T(t)&&E(t.text)?e+t.text:e,``)}}}return{type:`non_standard`,value:e}}function wt(e){if(w(e,`image`)&&T(e.image)){let t=St(T(e.image)&&E(e.image.format)?e.image.format:``);if(T(e.image.source)){if(T(e.image.source.s3Location)&&E(e.image.source.s3Location.uri))return{type:`image`,mimeType:t,fileId:e.image.source.s3Location.uri};if(Oe(e.image.source.bytes))return{type:`image`,mimeType:t,data:e.image.source.bytes}}}return{type:`non_standard`,value:e}}function Tt(e){if(w(e,`video`)&&T(e.video)){let t=St(T(e.video)&&E(e.video.format)?e.video.format:``);if(T(e.video.source)){if(T(e.video.source.s3Location)&&E(e.video.source.s3Location.uri))return{type:`video`,mimeType:t,fileId:e.video.source.s3Location.uri};if(Oe(e.video.source.bytes))return{type:`video`,mimeType:t,data:e.video.source.bytes}}}return{type:`non_standard`,value:e}}function Et(e){function*t(){let t=typeof e.content==`string`?[{type:`text`,text:e.content}]:e.content;for(let e of t){if(w(e,`cache_point`)){yield{type:`non_standard`,value:e};continue}else if(w(e,`citations_content`)&&T(e.citationsContent)){yield{type:`text`,text:Ee(e.citationsContent.content)?e.citationsContent.content.reduce((e,t)=>T(t)&&E(t.text)?e+t.text:e,``):``,annotations:Ee(e.citationsContent.citations)?e.citationsContent.citations.reduce((e,t)=>{if(T(t)){let n=Ee(t.sourceContent)?t.sourceContent.reduce((e,t)=>T(t)&&E(t.text)?e+t.text:e,``):``,r=ke(()=>{if(T(t.location)){let e=t.location.documentChar||t.location.documentPage||t.location.documentChunk;if(T(e))return{source:De(e.documentIndex)?e.documentIndex.toString():void 0,startIndex:De(e.start)?e.start:void 0,endIndex:De(e.end)?e.end:void 0}}return{}});e.push({type:`citation`,citedText:n,...r})}return e},[]):[]};continue}else if(w(e,`document`)&&T(e.document)){yield Ct(e);continue}else if(w(e,`guard_content`)){yield{type:`non_standard`,value:e};continue}else if(w(e,`image`)&&T(e.image)){yield wt(e);continue}else if(w(e,`reasoning_content`)&&E(e.reasoningText)){yield{type:`reasoning`,reasoning:e.reasoningText};continue}else if(w(e,`text`)&&E(e.text)){yield{type:`text`,text:e.text};continue}else if(w(e,`tool_result`)){yield{type:`non_standard`,value:e};continue}else if(w(e,`tool_call`))continue;else if(w(e,`video`)&&T(e.video)){yield Tt(e);continue}yield{type:`non_standard`,value:e}}}return Array.from(t())}var Dt={translateContent:Et,translateContentChunk:Et};function Ot(e){let t=[],n=e.additional_kwargs?.reasoning_content;if(E(n)&&n.length>0&&t.push({type:`reasoning`,reasoning:n}),typeof e.content==`string`)e.content.length>0&&t.push({type:`text`,text:e.content});else for(let n of e.content)typeof n==`object`&&`type`in n&&n.type===`text`&&`text`in n&&E(n.text)&&t.push({type:`text`,text:n.text});for(let n of e.tool_calls??[])t.push({type:`tool_call`,id:n.id,name:n.name,args:n.args});return t}var kt={translateContent:Ot,translateContentChunk:Ot};function At(e){function*t(){let t=typeof e.content==`string`?[{type:`text`,text:e.content}]:e.content;for(let n of t){if(w(n,`text`)&&E(n.text)){yield{type:`text`,text:n.text};continue}else if(w(n,`thinking`)&&E(n.thinking)){yield{type:`reasoning`,reasoning:n.thinking,...n.signature?{signature:n.signature}:{}};continue}else if(w(n,`inlineData`)&&T(n.inlineData)&&E(n.inlineData.mimeType)&&E(n.inlineData.data)){yield{type:`file`,mimeType:n.inlineData.mimeType,data:n.inlineData.data};continue}else if(w(n,`functionCall`)&&T(n.functionCall)&&E(n.functionCall.name)&&T(n.functionCall.args)){yield{type:`tool_call`,id:e.id,name:n.functionCall.name,args:n.functionCall.args};continue}else if(w(n,`functionResponse`)){yield{type:`non_standard`,value:n};continue}else if(w(n,`fileData`)&&T(n.fileData)&&E(n.fileData.mimeType)&&E(n.fileData.fileUri)){yield{type:`file`,mimeType:n.fileData.mimeType,fileId:n.fileData.fileUri};continue}else if(w(n,`executableCode`)){yield{type:`non_standard`,value:n};continue}else if(w(n,`codeExecutionResult`)){yield{type:`non_standard`,value:n};continue}yield{type:`non_standard`,value:n}}}return Array.from(t())}var jt={translateContent:At,translateContentChunk:At};function Mt(e){function*t(){let t=typeof e.content==`string`?[{type:`text`,text:e.content}]:e.content;for(let n of t){if(w(n,`reasoning`)&&E(n.reasoning)){let r=ke(()=>{let r=t.indexOf(n);if(Ee(e.additional_kwargs?.signatures)&&r>=0)return e.additional_kwargs.signatures.at(r)});E(r)?yield{type:`reasoning`,reasoning:n.reasoning,signature:r}:yield{type:`reasoning`,reasoning:n.reasoning};continue}else if(w(n,`thinking`)&&E(n.thinking)){yield{type:`reasoning`,reasoning:n.thinking,...n.signature?{signature:n.signature}:{}};continue}else if(w(n,`text`)&&E(n.text)){yield{type:`text`,text:n.text};continue}else if(w(n,`image_url`)){if(E(n.image_url))if(n.image_url.startsWith(`data:`)){let e=n.image_url.match(/^data:([^;]+);base64,(.+)$/);e?yield{type:`image`,data:e[2],mimeType:e[1]}:yield{type:`image`,url:n.image_url}}else yield{type:`image`,url:n.image_url};continue}else if(w(n,`media`)&&E(n.mimeType)&&E(n.data)){yield{type:`file`,mimeType:n.mimeType,data:n.data};continue}yield{type:`non_standard`,value:n}}}return Array.from(t())}var Nt={translateContent:Mt,translateContentChunk:Mt};function Pt(e){let t=[],n=e.additional_kwargs?.reasoning;if(E(n)&&n.length>0&&t.push({type:`reasoning`,reasoning:n}),typeof e.content==`string`){let n=e.content,r=n.match(/<think>([\s\S]*?)<\/think>/);if(r){let e=r[1].trim();e.length>0&&t.push({type:`reasoning`,reasoning:e}),n=n.replace(/<think>[\s\S]*?<\/think>/,``).trim()}n.length>0&&t.push({type:`text`,text:n})}else for(let n of e.content)if(typeof n==`object`&&`type`in n&&n.type===`text`&&`text`in n&&E(n.text)){let e=n.text,r=e.match(/<think>([\s\S]*?)<\/think>/);if(r){let n=r[1].trim();n.length>0&&t.push({type:`reasoning`,reasoning:n}),e=e.replace(/<think>[\s\S]*?<\/think>/,``).trim()}e.length>0&&t.push({type:`text`,text:e})}for(let n of e.tool_calls??[])t.push({type:`tool_call`,id:n.id,name:n.name,args:n.args});return t}var Ft={translateContent:Pt,translateContentChunk:Pt};function It(e){let t=[],n=e.additional_kwargs?.reasoning_content;if(E(n)&&n.length>0&&t.push({type:`reasoning`,reasoning:n}),typeof e.content==`string`)e.content.length>0&&t.push({type:`text`,text:e.content});else for(let n of e.content)typeof n==`object`&&`type`in n&&n.type===`text`&&`text`in n&&E(n.text)&&t.push({type:`text`,text:n.text});for(let n of e.tool_calls??[])t.push({type:`tool_call`,id:n.id,name:n.name,args:n.args});return t}var Lt={translateContent:It,translateContentChunk:It};function Rt(e){let t=[];if(T(e.additional_kwargs?.reasoning)){let n=e.additional_kwargs.reasoning;if(Ee(n.summary)){let e=n.summary.reduce((e,t)=>T(t)&&E(t.text)?`${e}${t.text}`:e,``);e.length>0&&t.push({type:`reasoning`,reasoning:e})}}let n=e.additional_kwargs?.reasoning_content;if(E(n)&&n.length>0&&t.push({type:`reasoning`,reasoning:n}),typeof e.content==`string`)e.content.length>0&&t.push({type:`text`,text:e.content});else for(let n of e.content)typeof n==`object`&&`type`in n&&n.type===`text`&&`text`in n&&E(n.text)&&t.push({type:`text`,text:n.text});for(let n of e.tool_calls??[])t.push({type:`tool_call`,id:n.id,name:n.name,args:n.args});return t}var zt={translateContent:Rt,translateContentChunk:Rt};function Bt(e){function*t(){let t=ke(()=>{if(typeof e.content==`string`)return e.additional_kwargs.originalTextContentBlock?[{...e.additional_kwargs.originalTextContentBlock,type:`text`}]:[{type:`text`,text:e.content}];{let t=e.additional_kwargs?.originalTextContentBlock;if(t?.thoughtSignature&&!e.content.some(e=>`thoughtSignature`in e)){let n=[...e.content];for(let e=n.length-1;e>=0;e--){let r=n[e];if(r.type===`text`&&!r.thought)return r.thoughtSignature=t.thoughtSignature,n}}return e.content}});for(let n of t){let t=ke(()=>w(n,`text`)&&E(n.text)?{type:`text`,text:n.text}:w(n,`inlineData`)&&T(n.inlineData)&&E(n.inlineData.mimeType)&&E(n.inlineData.data)?{type:`file`,mimeType:n.inlineData.mimeType,data:n.inlineData.data}:w(n,`functionCall`)&&T(n.functionCall)&&E(n.functionCall.name)&&T(n.functionCall.args)?{type:`tool_call`,id:e.id,name:n.functionCall.name,args:n.functionCall.args}:w(n,`functionResponse`)?{type:`non_standard`,value:n}:w(n,`fileData`)&&T(n.fileData)&&E(n.fileData.mimeType)&&E(n.fileData.fileUri)?{type:`file`,mimeType:n.fileData.mimeType,fileId:n.fileData.fileUri}:(w(n,`executableCode`)||w(n,`codeExecutionResult`),{type:`non_standard`,value:n})),r=ke(()=>`thought`in n&&n.thought?{type:`reasoning`,reasoning:t.type===`text`?t.text:``,reasoningContentBlock:t}:t),i={thought:n.thought,thoughtSignature:n.thoughtSignature,partMetadata:n.partMetadata,...r};for(let e in i)i[e]===void 0&&delete i[e];yield i}}return Array.from(t())}globalThis.lc_block_translators_registry??=new Map([[`anthropic`,Pe],[`bedrock-converse`,Dt],[`deepseek`,kt],[`google`,{translateContent:Bt,translateContentChunk:Bt}],[`google-genai`,jt],[`google-vertexai`,Nt],[`groq`,Ft],[`ollama`,Lt],[`openai`,Ke],[`xai`,zt]]);function Vt(e){return globalThis.lc_block_translators_registry.get(e)}function Ht(e,t){return it(e,t)??{}}function Ut(e,t){let n={};return(e?.audio!==void 0||t?.audio!==void 0)&&(n.audio=(e?.audio??0)+(t?.audio??0)),(e?.image!==void 0||t?.image!==void 0)&&(n.image=(e?.image??0)+(t?.image??0)),(e?.video!==void 0||t?.video!==void 0)&&(n.video=(e?.video??0)+(t?.video??0)),(e?.document!==void 0||t?.document!==void 0)&&(n.document=(e?.document??0)+(t?.document??0)),(e?.text!==void 0||t?.text!==void 0)&&(n.text=(e?.text??0)+(t?.text??0)),n}function Wt(e,t){let n={...Ut(e,t)};return(e?.cache_read!==void 0||t?.cache_read!==void 0)&&(n.cache_read=(e?.cache_read??0)+(t?.cache_read??0)),(e?.cache_creation!==void 0||t?.cache_creation!==void 0)&&(n.cache_creation=(e?.cache_creation??0)+(t?.cache_creation??0)),n}function Gt(e,t){let n={...Ut(e,t)};return(e?.reasoning!==void 0||t?.reasoning!==void 0)&&(n.reasoning=(e?.reasoning??0)+(t?.reasoning??0)),n}function Kt(e,t){return{input_tokens:(e?.input_tokens??0)+(t?.input_tokens??0),output_tokens:(e?.output_tokens??0)+(t?.output_tokens??0),total_tokens:(e?.total_tokens??0)+(t?.total_tokens??0),input_token_details:Wt(e?.input_token_details,t?.input_token_details),output_token_details:Gt(e?.output_token_details,t?.output_token_details)}}var qt=class extends tt{type=`ai`;tool_calls=[];invalid_tool_calls=[];usage_metadata;get lc_aliases(){return{...super.lc_aliases,tool_calls:`tool_calls`,invalid_tool_calls:`invalid_tool_calls`,usage_metadata:`usage_metadata`}}constructor(e){let t;if(typeof e==`string`||Array.isArray(e))t={content:e,tool_calls:[],invalid_tool_calls:[],additional_kwargs:{}};else{t=e;let n=t.additional_kwargs?.tool_calls,r=t.tool_calls;n!=null&&n.length>0&&(r===void 0||r.length===0)&&console.warn([`New LangChain packages are available that more efficiently handle`,`tool calling.
6
-
7
- 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(n!=null&&r===void 0){let[e,r]=yt(n);t.tool_calls=e??[],t.invalid_tool_calls=r??[]}else t.tool_calls=t.tool_calls??[],t.invalid_tool_calls=t.invalid_tool_calls??[]}catch{t.tool_calls=[],t.invalid_tool_calls=[]}if(t.response_metadata!==void 0&&`output_version`in t.response_metadata&&t.response_metadata.output_version===`v1`&&(t.contentBlocks=t.content,t.content=void 0),t.contentBlocks!==void 0){if(t.tool_calls){let e=t.tool_calls.filter(e=>!t.contentBlocks?.some(t=>t.type===`tool_call`&&t.id===e.id&&t.name===e.name));t.contentBlocks.push(...e.map(e=>({type:`tool_call`,id:e.id,name:e.name,args:e.args})))}let e=t.contentBlocks.filter(e=>e.type===`tool_call`).filter(e=>!t.tool_calls?.some(t=>t.id===e.id&&t.name===e.name));e.length>0&&(t.tool_calls=[...t.tool_calls??[],...e.map(e=>({type:`tool_call`,id:e.id,name:e.name,args:e.args}))])}}super(t),typeof t!=`string`&&(this.tool_calls=t.tool_calls??this.tool_calls,this.invalid_tool_calls=t.invalid_tool_calls??this.invalid_tool_calls),this.usage_metadata=t.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`){let e=Vt(this.response_metadata.model_provider);if(e)return e.translateContent(this)}let e=super.contentBlocks;if(this.tool_calls){let t=this.tool_calls.filter(t=>!e.some(e=>e.id===t.id&&e.name===t.name));e.push(...t.map(e=>({type:`tool_call`,id:e.id,name:e.name,args:e.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 Jt(e){return e._getType()===`ai`}function Yt(e){return e._getType()===`ai`}var Xt=class extends dt{type=`ai`;tool_calls=[];invalid_tool_calls=[];tool_call_chunks=[];usage_metadata;constructor(e){let t;if(typeof e==`string`||Array.isArray(e))t={content:e,tool_calls:[],invalid_tool_calls:[],tool_call_chunks:[]};else if(e.tool_call_chunks===void 0||e.tool_call_chunks.length===0)t={...e,tool_calls:e.tool_calls??[],invalid_tool_calls:[],tool_call_chunks:[],usage_metadata:e.usage_metadata===void 0?void 0:e.usage_metadata};else{let n=Dn(e.tool_call_chunks??[]);t={...e,tool_call_chunks:n.tool_call_chunks,tool_calls:n.tool_calls,invalid_tool_calls:n.invalid_tool_calls,usage_metadata:e.usage_metadata===void 0?void 0:e.usage_metadata}}super(t),this.tool_call_chunks=t.tool_call_chunks??this.tool_call_chunks,this.tool_calls=t.tool_calls??this.tool_calls,this.invalid_tool_calls=t.invalid_tool_calls??this.invalid_tool_calls,this.usage_metadata=t.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`){let e=Vt(this.response_metadata.model_provider);if(e)return e.translateContent(this)}let e=super.contentBlocks;if(this.tool_calls&&typeof this.content!=`string`){let t=this.content.filter(e=>e.type===`tool_call`).map(e=>e.id);for(let n of this.tool_calls)n.id&&!t.includes(n.id)&&e.push({...n,type:`tool_call`,id:n.id,name:n.name,args:n.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){let t={content:Qe(this.content,e.content),additional_kwargs:it(this.additional_kwargs,e.additional_kwargs),response_metadata:Ht(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){let n=lt(this.tool_call_chunks,e.tool_call_chunks);n!==void 0&&n.length>0&&(t.tool_call_chunks=n)}if(this.tool_calls!==void 0||e.tool_calls!==void 0){let n=lt(this.tool_calls,e.tool_calls);n!==void 0&&n.length>0&&(t.tool_calls=n)}(this.usage_metadata!==void 0||e.usage_metadata!==void 0)&&(t.usage_metadata=Kt(this.usage_metadata,e.usage_metadata));let n=this.constructor;return new n(t)}static isInstance(e){return super.isInstance(e)&&e.type===`ai`}},Zt=class e extends tt{static lc_name(){return`ChatMessage`}type=`generic`;role;static _chatMessageClass(){return e}constructor(e,t){(typeof e==`string`||Array.isArray(e))&&(e={content:e,role:t}),super(e),this.role=e.role}static isInstance(e){return super.isInstance(e)&&e.type===`generic`}get _printableFields(){return{...super._printableFields,role:this.role}}},Qt=class extends dt{static lc_name(){return`ChatMessageChunk`}type=`generic`;role;constructor(e,t){(typeof e==`string`||Array.isArray(e))&&(e={content:e,role:t}),super(e),this.role=e.role}concat(e){let t=this.constructor;return new t({content:Qe(this.content,e.content),additional_kwargs:it(this.additional_kwargs,e.additional_kwargs),response_metadata:it(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 $t(e){return e._getType()===`generic`}function en(e){return e._getType()===`generic`}var tn=class extends tt{static lc_name(){return`FunctionMessage`}type=`function`;name;constructor(e){super(e),this.name=e.name}},nn=class extends dt{static lc_name(){return`FunctionMessageChunk`}type=`function`;concat(e){let t=this.constructor;return new t({content:Qe(this.content,e.content),additional_kwargs:it(this.additional_kwargs,e.additional_kwargs),response_metadata:it(this.response_metadata,e.response_metadata),name:this.name??``,id:this.id??e.id})}};function rn(e){return e._getType()===`function`}function an(e){return e._getType()===`function`}var on=class extends tt{static lc_name(){return`HumanMessage`}type=`human`;constructor(e){super(e)}static isInstance(e){return super.isInstance(e)&&e.type===`human`}},sn=class extends dt{static lc_name(){return`HumanMessageChunk`}type=`human`;constructor(e){super(e)}concat(e){let t=this.constructor;return new t({content:Qe(this.content,e.content),additional_kwargs:it(this.additional_kwargs,e.additional_kwargs),response_metadata:it(this.response_metadata,e.response_metadata),id:this.id??e.id})}static isInstance(e){return super.isInstance(e)&&e.type===`human`}};function cn(e){return e.getType()===`human`}function ln(e){return e.getType()===`human`}var un=class extends tt{type=`remove`;id;constructor(e){super({...e,content:[]}),this.id=e.id}get _printableFields(){return{...super._printableFields,id:this.id}}static isInstance(e){return super.isInstance(e)&&e.type===`remove`}},dn=class e extends tt{static lc_name(){return`SystemMessage`}type=`system`;constructor(e){super(e)}concat(t){if(typeof t==`string`)return new e({content:Qe(this.content,t),additional_kwargs:this.additional_kwargs,response_metadata:this.response_metadata,id:this.id,name:this.name});if(e.isInstance(t))return new e({content:Qe(this.content,t.content),additional_kwargs:{...this.additional_kwargs,...t.additional_kwargs},response_metadata:{...this.response_metadata,...t.response_metadata},id:this.id??t.id,name:this.name??t.name});throw Error(`Unexpected chunk type for system message`)}static isInstance(e){return super.isInstance(e)&&e.type===`system`}},fn=class extends dt{static lc_name(){return`SystemMessageChunk`}type=`system`;constructor(e){super(e)}concat(e){let t=this.constructor;return new t({content:Qe(this.content,e.content),additional_kwargs:it(this.additional_kwargs,e.additional_kwargs),response_metadata:it(this.response_metadata,e.response_metadata),id:this.id??e.id})}static isInstance(e){return super.isInstance(e)&&e.type===`system`}};function pn(e){return e._getType()===`system`}function mn(e){return e._getType()===`system`}var hn=e=>e();function gn(e){return h(e)?e:typeof e.id==`string`&&e.type===`function`&&typeof e.function==`object`&&e.function!==null&&`arguments`in e.function&&typeof e.function.arguments==`string`&&`name`in e.function&&typeof e.function.name==`string`?{id:e.id,args:JSON.parse(e.function.arguments),name:e.function.name,type:`tool_call`}:e}function _n(e){return typeof e==`object`&&!!e&&e.lc===1&&Array.isArray(e.id)&&e.kwargs!=null&&typeof e.kwargs==`object`}function vn(e){let t,n;if(_n(e)){let r=e.id.at(-1);t=r===`HumanMessage`||r===`HumanMessageChunk`?`user`:r===`AIMessage`||r===`AIMessageChunk`?`assistant`:r===`SystemMessage`||r===`SystemMessageChunk`?`system`:r===`FunctionMessage`||r===`FunctionMessageChunk`?`function`:r===`ToolMessage`||r===`ToolMessageChunk`?`tool`:`unknown`,n=e.kwargs}else{let{type:r,...i}=e;t=r,n=i}if(t===`human`||t===`user`)return new on(n);if(t===`ai`||t===`assistant`){let{tool_calls:e,...t}=n;if(!Array.isArray(e))return new qt(n);let r=e.map(gn);return new qt({...t,tool_calls:r})}else if(t===`system`)return new dn(n);else if(t===`developer`)return new dn({...n,additional_kwargs:{...n.additional_kwargs,__openai_role__:`developer`}});else if(t===`tool`&&`tool_call_id`in n)return new _t({...n,content:n.content,tool_call_id:n.tool_call_id,name:n.name});else if(t===`remove`&&`id`in n&&typeof n.id==`string`)return new un({...n,id:n.id});else throw u(Error(`Unable to coerce message from array: only human, AI, system, developer, or tool message coercion is currently supported.\n\nReceived: ${JSON.stringify(e,null,2)}`),`MESSAGE_COERCION_FAILURE`)}function yn(e){if(typeof e==`string`)return new on(e);if(pt(e))return e;if(Array.isArray(e)){let[t,n]=e;return vn({type:t,content:n})}else if(ft(e)){let{role:t,...n}=e;return vn({...n,type:t})}else return vn(e)}function bn(e){if(typeof e==`string`)return e;switch(e.type){case`text`:return e.text??``;case`text-plain`:return e.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 e.type?`[${e.type}]`:``}}function xn(e,t=`Human`,n=`AI`){let r=[];for(let i of e){let e;if(i.type===`human`)e=t;else if(i.type===`ai`)e=n;else if(i.type===`system`)e=`System`;else if(i.type===`tool`)e=`Tool`;else if(i.type===`generic`)e=i.role;else throw Error(`Got unsupported message type: ${i.type}`);let a=i.name?`${i.name}, `:``,o=typeof i.content==`string`?i.content:Array.isArray(i.content)?i.content.map(bn).filter(Boolean).join(``):``,s=`${e}: ${a}${o}`;if(i.type===`ai`){let e=i;e.tool_calls&&e.tool_calls.length>0?s+=JSON.stringify(e.tool_calls):e.additional_kwargs&&`function_call`in e.additional_kwargs&&(s+=JSON.stringify(e.additional_kwargs.function_call))}r.push(s)}return r.join(`
8
- `)}function Sn(e){if(e.data!==void 0)return e;{let t=e;return{type:t.type,data:{content:t.text,role:t.role,name:void 0,tool_call_id:void 0}}}}function Cn(e){let t=Sn(e);switch(t.type){case`human`:return new on(t.data);case`ai`:return new qt(t.data);case`system`:return new dn(t.data);case`function`:if(t.data.name===void 0)throw Error(`Name must be defined for function messages`);return new tn(t.data);case`tool`:if(t.data.tool_call_id===void 0)throw Error(`Tool call ID must be defined for tool messages`);return new _t(t.data);case`generic`:if(t.data.role===void 0)throw Error(`Role must be defined for chat messages`);return new Zt(t.data);default:throw Error(`Got unexpected type: ${t.type}`)}}function wn(e){return e.map(Cn)}function Tn(e){return e.map(e=>e.toDict())}function En(e){let t=e._getType();if(t===`human`)return new sn({...e});if(t===`ai`){let t={...e};return`tool_calls`in t&&(t={...t,tool_call_chunks:t.tool_calls?.map(e=>({...e,type:`tool_call_chunk`,index:void 0,args:JSON.stringify(e.args)}))}),new Xt({...t})}else if(t===`system`)return new fn({...e});else if(t===`function`)return new nn({...e});else if(Zt.isInstance(e))return new Qt({...e});else throw Error(`Unknown message type.`)}function Dn(e){let t=e.reduce((e,t)=>{let n=e.findIndex(([e])=>`id`in t&&t.id&&`index`in t&&t.index!==void 0?t.id===e.id&&t.index===e.index:`id`in t&&t.id?t.id===e.id:`index`in t&&t.index!==void 0?t.index===e.index:!1);return n===-1?e.push([t]):e[n].push(t),e},[]),n=[],r=[];for(let e of t){let t=null,i=e[0]?.name??``,a=e.map(e=>e.args||``).join(``).trim(),o=a.length?a:`{}`,s=e[0]?.id;try{if(t=b(o),!s||typeof t!=`object`||!t||Array.isArray(t))throw Error(`Malformed tool call chunk args.`);n.push({name:i,args:t,id:s,type:`tool_call`})}catch{r.push({name:i,args:o,id:s,error:`Malformed args.`,type:`invalid_tool_call`})}}return{tool_call_chunks:e,tool_calls:n,invalid_tool_calls:r}}var On=/^(?:[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 kn(e){return typeof e==`string`&&On.test(e)}var An=[];for(let e=0;e<256;++e)An.push((e+256).toString(16).slice(1));function jn(e,t=0){return(An[e[t+0]]+An[e[t+1]]+An[e[t+2]]+An[e[t+3]]+`-`+An[e[t+4]]+An[e[t+5]]+`-`+An[e[t+6]]+An[e[t+7]]+`-`+An[e[t+8]]+An[e[t+9]]+`-`+An[e[t+10]]+An[e[t+11]]+An[e[t+12]]+An[e[t+13]]+An[e[t+14]]+An[e[t+15]]).toLowerCase()}function Mn(e,t=0){let n=jn(e,t);if(!kn(n))throw TypeError(`Stringified UUID is invalid`);return n}var Nn=new Uint8Array(16);function Pn(){return crypto.getRandomValues(Nn)}var Fn={};function In(e,t,n){let r;if(e)r=Rn(e.random??e.rng?.()??Pn(),e.msecs,e.seq,t,n);else{let e=Date.now(),i=Pn();Ln(Fn,e,i),r=Rn(i,Fn.msecs,Fn.seq,t,n)}return t??jn(r)}function Ln(e,t,n){return e.msecs??=-1/0,e.seq??=0,t>e.msecs?(e.seq=n[6]<<23|n[7]<<16|n[8]<<8|n[9],e.msecs=t):(e.seq=e.seq+1|0,e.seq===0&&e.msecs++),e}function Rn(e,t,n,r,i=0){if(e.length<16)throw Error(`Random bytes length must be >= 16`);if(!r)r=new Uint8Array(16),i=0;else if(i<0||i+16>r.length)throw RangeError(`UUID byte range ${i}:${i+15} is out of buffer bounds`);return t??=Date.now(),n??=e[6]*127<<24|e[7]<<16|e[8]<<8|e[9],r[i++]=t/1099511627776&255,r[i++]=t/4294967296&255,r[i++]=t/16777216&255,r[i++]=t/65536&255,r[i++]=t/256&255,r[i++]=t&255,r[i++]=112|n>>>28&15,r[i++]=n>>>20&255,r[i++]=128|n>>>14&63,r[i++]=n>>>6&255,r[i++]=n<<2&255|e[10]&3,r[i++]=e[11],r[i++]=e[12],r[i++]=e[13],r[i++]=e[14],r[i++]=e[15],r}var zn=`ffffffff-ffff-ffff-ffff-ffffffffffff`,Bn=`00000000-0000-0000-0000-000000000000`;function Vn(e){if(!kn(e))throw TypeError(`Invalid UUID`);let t;return Uint8Array.of((t=parseInt(e.slice(0,8),16))>>>24,t>>>16&255,t>>>8&255,t&255,(t=parseInt(e.slice(9,13),16))>>>8,t&255,(t=parseInt(e.slice(14,18),16))>>>8,t&255,(t=parseInt(e.slice(19,23),16))>>>8,t&255,(t=parseInt(e.slice(24,36),16))/1099511627776&255,t/4294967296&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255)}var Hn={};function Un(e,t,n){let r,i=e?._v6??!1;if(e){let t=Object.keys(e);t.length===1&&t[0]===`_v6`&&(e=void 0)}if(e)r=Gn(e.random??e.rng?.()??Pn(),e.msecs,e.nsecs,e.clockseq,e.node,t,n);else{let e=Date.now(),a=Pn();Wn(Hn,e,a),r=Gn(a,Hn.msecs,Hn.nsecs,i?void 0:Hn.clockseq,i?void 0:Hn.node,t,n)}return t??jn(r)}function Wn(e,t,n){return e.msecs??=-1/0,e.nsecs??=0,t===e.msecs?(e.nsecs++,e.nsecs>=1e4&&(e.node=void 0,e.nsecs=0)):t>e.msecs?e.nsecs=0:t<e.msecs&&(e.node=void 0),e.node||(e.node=n.slice(10,16),e.node[0]|=1,e.clockseq=(n[8]<<8|n[9])&16383),e.msecs=t,e}function Gn(e,t,n,r,i,a,o=0){if(e.length<16)throw Error(`Random bytes length must be >= 16`);if(!a)a=new Uint8Array(16),o=0;else if(o<0||o+16>a.length)throw RangeError(`UUID byte range ${o}:${o+15} is out of buffer bounds`);t??=Date.now(),n??=0,r??=(e[8]<<8|e[9])&16383,i??=e.slice(10,16),t+=0xb1d069b5400;let s=((t&268435455)*1e4+n)%4294967296;a[o++]=s>>>24&255,a[o++]=s>>>16&255,a[o++]=s>>>8&255,a[o++]=s&255;let c=t/4294967296*1e4&268435455;a[o++]=c>>>8&255,a[o++]=c&255,a[o++]=c>>>24&15|16,a[o++]=c>>>16&255,a[o++]=r>>>8|128,a[o++]=r&255;for(let e=0;e<6;++e)a[o++]=i[e];return a}function Kn(e,t,n){return!t&&!e&&crypto.randomUUID?crypto.randomUUID():qn(e,t,n)}function qn(e,t,n){e||={};let r=e.random??e.rng?.()??Pn();if(r.length<16)throw Error(`Random bytes length must be >= 16`);if(r[6]=r[6]&15|64,r[8]=r[8]&63|128,t){if(n||=0,n<0||n+16>t.length)throw RangeError(`UUID byte range ${n}:${n+15} is out of buffer bounds`);for(let e=0;e<16;++e)t[n+e]=r[e];return t}return jn(r)}function Jn(e,t,n,r){switch(e){case 0:return t&n^~t&r;case 1:return t^n^r;case 2:return t&n^t&r^n&r;case 3:return t^n^r}}function Yn(e,t){return e<<t|e>>>32-t}function Xn(e){let t=[1518500249,1859775393,2400959708,3395469782],n=[1732584193,4023233417,2562383102,271733878,3285377520],r=new Uint8Array(e.length+1);r.set(e),r[e.length]=128,e=r;let i=e.length/4+2,a=Math.ceil(i/16),o=Array(a);for(let t=0;t<a;++t){let n=new Uint32Array(16);for(let r=0;r<16;++r)n[r]=e[t*64+r*4]<<24|e[t*64+r*4+1]<<16|e[t*64+r*4+2]<<8|e[t*64+r*4+3];o[t]=n}o[a-1][14]=(e.length-1)*8/2**32,o[a-1][14]=Math.floor(o[a-1][14]),o[a-1][15]=(e.length-1)*8&4294967295;for(let e=0;e<a;++e){let r=new Uint32Array(80);for(let t=0;t<16;++t)r[t]=o[e][t];for(let e=16;e<80;++e)r[e]=Yn(r[e-3]^r[e-8]^r[e-14]^r[e-16],1);let i=n[0],a=n[1],s=n[2],c=n[3],l=n[4];for(let e=0;e<80;++e){let n=Math.floor(e/20),o=Yn(i,5)+Jn(n,a,s,c)+l+t[n]+r[e]>>>0;l=c,c=s,s=Yn(a,30)>>>0,a=i,i=o}n[0]=n[0]+i>>>0,n[1]=n[1]+a>>>0,n[2]=n[2]+s>>>0,n[3]=n[3]+c>>>0,n[4]=n[4]+l>>>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 Zn(e){e=unescape(encodeURIComponent(e));let t=new Uint8Array(e.length);for(let n=0;n<e.length;++n)t[n]=e.charCodeAt(n);return t}var Qn=`6ba7b810-9dad-11d1-80b4-00c04fd430c8`,$n=`6ba7b811-9dad-11d1-80b4-00c04fd430c8`;function er(e,t,n,r,i,a){let o=typeof n==`string`?Zn(n):n,s=typeof r==`string`?Vn(r):r;if(typeof r==`string`&&(r=Vn(r)),r?.length!==16)throw TypeError(`Namespace must be array-like (16 iterable integer values, 0-255)`);let c=new Uint8Array(16+o.length);if(c.set(s),c.set(o,s.length),c=t(c),c[6]=c[6]&15|e,c[8]=c[8]&63|128,i){if(a??=0,a<0||a+16>i.length)throw RangeError(`UUID byte range ${a}:${a+15} is out of buffer bounds`);for(let e=0;e<16;++e)i[a+e]=c[e];return i}return jn(c)}function tr(e,t,n,r){return er(80,Xn,e,t,n,r)}tr.DNS=Qn,tr.URL=$n;function nr(e){if(!kn(e))throw TypeError(`Invalid UUID`);return parseInt(e.slice(14,15),16)}var rr=o({MAX:()=>zn,NIL:()=>Bn,parse:()=>Vn,stringify:()=>Mn,v1:()=>Un,v4:()=>Kn,v5:()=>tr,v7:()=>In,validate:()=>kn,version:()=>nr}),ir=o({getEnv:()=>ur,getEnvironmentVariable:()=>pr,getRuntimeEnvironment:()=>fr,isBrowser:()=>ar,isDeno:()=>cr,isJsDom:()=>sr,isNode:()=>lr,isWebWorker:()=>or}),ar=()=>typeof window<`u`&&window.document!==void 0,or=()=>typeof globalThis==`object`&&globalThis.constructor&&globalThis.constructor.name===`DedicatedWorkerGlobalScope`,sr=()=>typeof window<`u`&&window.name===`nodejs`||typeof navigator<`u`&&navigator.userAgent.includes(`jsdom`),cr=()=>typeof Deno<`u`,lr=()=>typeof process<`u`&&process.versions!==void 0&&process.versions.node!==void 0&&!cr(),ur=()=>{let e;return e=ar()?`browser`:lr()?`node`:or()?`webworker`:sr()?`jsdom`:cr()?`deno`:`other`,e},dr;function fr(){return dr===void 0&&(dr={library:`langchain-js`,runtime:ur()}),dr}function pr(e){try{return typeof process<`u`?{}?.[e]:cr()?Deno?.env.get(e):void 0}catch{return}}var mr=o({BaseCallbackHandler:()=>vr,callbackHandlerPrefersChatModelStreamEvents:()=>_r,callbackHandlerPrefersStreaming:()=>gr,isBaseCallbackHandler:()=>yr}),hr=class{};function gr(e){return`lc_prefer_streaming`in e&&e.lc_prefer_streaming}function _r(e){return`lc_prefer_chat_model_stream_events`in e&&e.lc_prefer_chat_model_stream_events}var vr=class extends hr{lc_serializable=!1;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,he(this.constructor)]}lc_kwargs;ignoreLLM=!1;ignoreChain=!1;ignoreAgent=!1;ignoreRetriever=!1;ignoreCustomEvent=!1;raiseError=!1;awaitHandlers=pr(`LANGCHAIN_CALLBACKS_BACKGROUND`)===`false`;constructor(e){super(),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))}copy(){return new this.constructor(this)}toJSON(){return ge.prototype.toJSON.call(this)}toJSONNotImplemented(){return ge.prototype.toJSONNotImplemented.call(this)}static fromMethods(e){class t extends vr{name=In();constructor(){super(),Object.assign(this,e)}}return new t}},yr=e=>{let t=e;return t!==void 0&&typeof t.copy==`function`&&typeof t.name==`string`&&typeof t.awaitHandlers==`boolean`},br=/^(?:[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 xr(e){return typeof e==`string`&&br.test(e)}function Sr(e){if(!xr(e))throw TypeError(`Invalid UUID`);var t,n=new Uint8Array(16);return n[0]=(t=parseInt(e.slice(0,8),16))>>>24,n[1]=t>>>16&255,n[2]=t>>>8&255,n[3]=t&255,n[4]=(t=parseInt(e.slice(9,13),16))>>>8,n[5]=t&255,n[6]=(t=parseInt(e.slice(14,18),16))>>>8,n[7]=t&255,n[8]=(t=parseInt(e.slice(19,23),16))>>>8,n[9]=t&255,n[10]=(t=parseInt(e.slice(24,36),16))/1099511627776&255,n[11]=t/4294967296&255,n[12]=t>>>24&255,n[13]=t>>>16&255,n[14]=t>>>8&255,n[15]=t&255,n}for(var Cr=[],wr=0;wr<256;++wr)Cr.push((wr+256).toString(16).slice(1));function Tr(e,t=0){return(Cr[e[t+0]]+Cr[e[t+1]]+Cr[e[t+2]]+Cr[e[t+3]]+`-`+Cr[e[t+4]]+Cr[e[t+5]]+`-`+Cr[e[t+6]]+Cr[e[t+7]]+`-`+Cr[e[t+8]]+Cr[e[t+9]]+`-`+Cr[e[t+10]]+Cr[e[t+11]]+Cr[e[t+12]]+Cr[e[t+13]]+Cr[e[t+14]]+Cr[e[t+15]]).toLowerCase()}var Er,Dr=new Uint8Array(16);function Or(){if(!Er&&(Er=typeof crypto<`u`&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!Er))throw Error(`crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported`);return Er(Dr)}function kr(e){e=unescape(encodeURIComponent(e));for(var t=[],n=0;n<e.length;++n)t.push(e.charCodeAt(n));return t}var Ar=`6ba7b810-9dad-11d1-80b4-00c04fd430c8`,jr=`6ba7b811-9dad-11d1-80b4-00c04fd430c8`;function Mr(e,t,n){function r(e,r,i,a){if(typeof e==`string`&&(e=kr(e)),typeof r==`string`&&(r=Sr(r)),r?.length!==16)throw TypeError(`Namespace must be array-like (16 iterable integer values, 0-255)`);var o=new Uint8Array(16+e.length);if(o.set(r),o.set(e,r.length),o=n(o),o[6]=o[6]&15|t,o[8]=o[8]&63|128,i){a||=0;for(var s=0;s<16;++s)i[a+s]=o[s];return i}return Tr(o)}try{r.name=e}catch{}return r.DNS=Ar,r.URL=jr,r}var Nr={randomUUID:typeof crypto<`u`&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function Pr(e,t,n){if(Nr.randomUUID&&!t&&!e)return Nr.randomUUID();e||={};var r=e.random||(e.rng||Or)();if(r[6]=r[6]&15|64,r[8]=r[8]&63|128,t){n||=0;for(var i=0;i<16;++i)t[n+i]=r[i];return t}return Tr(r)}function Fr(e,t,n,r){switch(e){case 0:return t&n^~t&r;case 1:return t^n^r;case 2:return t&n^t&r^n&r;case 3:return t^n^r}}function Ir(e,t){return e<<t|e>>>32-t}function Lr(e){var t=[1518500249,1859775393,2400959708,3395469782],n=[1732584193,4023233417,2562383102,271733878,3285377520];if(typeof e==`string`){var r=unescape(encodeURIComponent(e));e=[];for(var i=0;i<r.length;++i)e.push(r.charCodeAt(i))}else Array.isArray(e)||(e=Array.prototype.slice.call(e));e.push(128);for(var a=e.length/4+2,o=Math.ceil(a/16),s=Array(o),c=0;c<o;++c){for(var l=new Uint32Array(16),u=0;u<16;++u)l[u]=e[c*64+u*4]<<24|e[c*64+u*4+1]<<16|e[c*64+u*4+2]<<8|e[c*64+u*4+3];s[c]=l}s[o-1][14]=(e.length-1)*8/2**32,s[o-1][14]=Math.floor(s[o-1][14]),s[o-1][15]=(e.length-1)*8&4294967295;for(var d=0;d<o;++d){for(var f=new Uint32Array(80),p=0;p<16;++p)f[p]=s[d][p];for(var m=16;m<80;++m)f[m]=Ir(f[m-3]^f[m-8]^f[m-14]^f[m-16],1);for(var h=n[0],g=n[1],_=n[2],v=n[3],y=n[4],b=0;b<80;++b){var ee=Math.floor(b/20),x=Ir(h,5)+Fr(ee,g,_,v)+y+t[ee]+f[b]>>>0;y=v,v=_,_=Ir(g,30)>>>0,g=h,h=x}n[0]=n[0]+h>>>0,n[1]=n[1]+g>>>0,n[2]=n[2]+_>>>0,n[3]=n[3]+v>>>0,n[4]=n[4]+y>>>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 Rr=Mr(`v5`,80,Lr),zr=null,Br=null,Vr=0;function Hr(e,t,n){e||={};var r=t&&n||0,i=t||new Uint8Array(16),a=e.random||(e.rng||Or)(),o=e.msecs===void 0?Date.now():e.msecs,s=e.seq===void 0?null:e.seq,c=Br,l=zr;return o>Vr&&e.msecs===void 0&&(Vr=o,s!==null&&(c=null,l=null)),s!==null&&(s>2147483647&&(s=2147483647),c=s>>>19&4095,l=s&524287),(c===null||l===null)&&(c=a[6]&127,c=c<<8|a[7],l=a[8]&63,l=l<<8|a[9],l=l<<5|a[10]>>>3),o+1e4>Vr&&s===null?++l>524287&&(l=0,++c>4095&&(c=0,Vr++)):Vr=o,Br=c,zr=l,i[r++]=Vr/1099511627776&255,i[r++]=Vr/4294967296&255,i[r++]=Vr/16777216&255,i[r++]=Vr/65536&255,i[r++]=Vr/256&255,i[r++]=Vr&255,i[r++]=c>>>4&15|112,i[r++]=c&255,i[r++]=l>>>13&63|128,i[r++]=l>>>5&255,i[r++]=l<<3&255|a[10]&7,i[r++]=a[11],i[r++]=a[12],i[r++]=a[13],i[r++]=a[14],i[r++]=a[15],t||Tr(i)}var Ur=`gen_ai.operation.name`,Wr=`gen_ai.system`,Gr=`gen_ai.request.model`,Kr=`gen_ai.response.model`,qr=`gen_ai.usage.input_tokens`,Jr=`gen_ai.usage.output_tokens`,Yr=`gen_ai.usage.total_tokens`,Xr=`gen_ai.request.max_tokens`,Zr=`gen_ai.request.temperature`,Qr=`gen_ai.request.top_p`,$r=`gen_ai.request.frequency_penalty`,ei=`gen_ai.request.presence_penalty`,ti=`gen_ai.response.finish_reasons`,ni=`gen_ai.prompt`,ri=`gen_ai.completion`,ii=`gen_ai.request.extra_query`,ai=`gen_ai.request.extra_body`,oi=`gen_ai.serialized.name`,si=`gen_ai.serialized.signature`,ci=`gen_ai.serialized.doc`,li=`gen_ai.response.id`,ui=`gen_ai.response.service_tier`,di=`gen_ai.response.system_fingerprint`,fi=`gen_ai.usage.input_token_details`,pi=`gen_ai.usage.output_token_details`,mi=`langsmith.trace.session_id`,hi=`langsmith.trace.session_name`,gi=`langsmith.span.kind`,_i=`langsmith.trace.name`,vi=`langsmith.metadata`,yi=`langsmith.span.tags`,bi=`langsmith.request.streaming`,xi=`langsmith.request.headers`,Si=(...e)=>fetch(...e),Ci=void 0,wi=Symbol.for(`ls:fetch_implementation`),Ti=()=>globalThis[wi]===void 0?!0:Ci??!1,Ei=e=>async(...t)=>{if(e||no(`DEBUG`)===`true`){let[e,n]=t;console.log(`β†’ ${n?.method||`GET`} ${e}`)}let n=await(globalThis[wi]??Si)(...t);return(e||no(`DEBUG`)===`true`)&&console.log(`← ${n.status} ${n.statusText} ${n.url}`),n},Di=()=>no(`PROJECT`)??to(`LANGCHAIN_SESSION`)??`default`,Oi={};function ki(e){Oi[e]||(console.warn(e),Oi[e]=!0)}var O=e=>BigInt(e),Ai=O(`0x9E3779B1`),ji=O(`0x85EBCA77`),Mi=O(`0xC2B2AE3D`),Ni=O(`0x9E3779B185EBCA87`),Pi=O(`0xC2B2AE3D27D4EB4F`),Fi=O(`0x165667B19E3779F9`),Ii=O(`0x85EBCA77C2B2AE63`),Li=O(`0x27D4EB2F165667C5`),Ri=O(`0x165667919E3779F9`),zi=O(`0x9FB21C651E98DF25`);function Bi(e){let t=new Uint8Array(e.length/2);for(let n=0;n<e.length;n+=2)t[n/2]=parseInt(e.substring(n,n+2),16);return t}var Vi=Bi(`b8fe6c3923a44bbe7c01812cf721ad1cded46de9839097db7240a4a4b7b3671fcb79e64eccc0e578825ad07dccff7221b8084674f743248ee03590e6813a264c3c2852bb91c300cb88d0658b1b532ea371644897a20df94e3819ef46a9deacd8a8fa763fe39c343ff9dcbbc7c70b4f1d8a51e04bcdb45931c89f7ec9d9787364eac5ac8334d3ebc3c581a0fffa1363eb170ddd51b7f0da49d316552629d4689e2b16be587d47a1fc8ff8b8d17ad031ce45cb3a8f95160428afd7fbcabb4b407e`),Hi=(O(1)<<O(128))-O(1),Ui=(O(1)<<O(64))-O(1),Wi=(O(1)<<O(32))-O(1),Gi=64,Ki=Gi/8,qi=8,Ji=4;function Yi(e,t=0){return new Uint8Array(e.buffer,e.byteOffset+t,e.length-t)}function Xi(e,t=0){return new DataView(e.buffer,e.byteOffset+t).getBigUint64(0,!0)}function Zi(e,t=0){return new DataView(e.buffer,e.byteOffset+t).getUint32(0,!0)}function Qi(e,t=0){return e[t]}var $i=e=>(e&O(255))<<O(56)|(e&O(65280))<<O(40)|(e&O(16711680))<<O(24)|(e&O(4278190080))<<O(8)|(e&O(0xff00000000))>>O(8)|(e&O(0xff0000000000))>>O(24)|(e&O(0xff000000000000))>>O(40)|(e&O(0xff00000000000000))>>O(56),ea=e=>(e=(e&O(65535))<<O(16)|(e&O(4294901760))>>O(16),e=(e&O(16711935))<<O(8)|(e&O(4278255360))>>O(8),e),ta=(e,t)=>(e&Wi)*(t&Wi)&Ui,na=e=>{if(!e)throw Error(`Assert failed`)};function ra(e,t){return(e<<t|e>>O(32)-t)&Wi}function ia(e,t,n){for(let r=0;r<Ki;r++){let i=Xi(t,r*8),a=i^Xi(n,r*8);e[r^1]+=i,e[r]+=ta(a,a>>O(32))}return e}function aa(e,t,n,r){for(let i=0;i<r;i++)ia(e,Yi(t,i*Gi),Yi(n,i*8));return e}function oa(e,t){for(let n=0;n<Ki;n++){let r=Xi(t,n*8),i=e[n];i=_a(i,O(47)),i^=r,i*=Ai,e[n]=i&Ui}return e}function sa(e,t){return da(e[0]^Xi(t,0),e[1]^Xi(t,qi))}function ca(e,t,n){let r=n;return r+=sa(e.slice(0),Yi(t,0*Ji)),r+=sa(e.slice(2),Yi(t,4*Ji)),r+=sa(e.slice(4),Yi(t,8*Ji)),r+=sa(e.slice(6),Yi(t,12*Ji)),ma(r&Ui)}function la(e,t,n,r,i){let a=Math.floor((n.byteLength-Gi)/8),o=Gi*a,s=Math.floor((t.byteLength-1)/o);for(let r=0;r<s;r++)e=aa(e,Yi(t,r*o),n,a),e=i(e,Yi(n,n.byteLength-Gi));{let i=Math.floor((t.byteLength-1-o*s)/Gi);e=aa(e,Yi(t,s*o),n,i),e=r(e,Yi(t,t.byteLength-Gi),Yi(n,n.byteLength-Gi-7))}return e}function ua(e,t,n){let r=new BigUint64Array([Mi,Ni,Pi,Fi,Ii,ji,Li,Ai]);na(e.length>128),r=la(r,e,t,ia,oa),na(r.length*8==64);{let n=ca(r,Yi(t,11),O(e.byteLength)*Ni&Ui);return ca(r,Yi(t,t.byteLength-Gi-11),~(O(e.byteLength)*Pi)&Ui)<<O(64)|n}}function da(e,t){let n=e*t&Hi;return n&Ui^n>>O(64)}function fa(e,t,n){return da((Xi(e,0)^Xi(t,0)+n)&Ui,(Xi(e,8)^Xi(t,8)-n)&Ui)}function pa(e,t,n,r,i){let a=e&Ui,o=e>>O(64)&Ui;return a+=fa(t,r,i),a^=Xi(n,0)+Xi(n,8),a&=Ui,o+=fa(n,Yi(r,16),i),o^=Xi(t,0)+Xi(t,8),o&=Ui,o<<O(64)|a}function ma(e){return e^=e>>O(37),e*=Ri,e&=Ui,e^=e>>O(32),e}function ha(e){return e^=e>>O(33),e*=Pi,e&=Ui,e^=e>>O(29),e*=Fi,e&=Ui,e^=e>>O(32),e}function ga(e,t,n){let r=e.byteLength;na(r>0&&r<=3);let i=O(Qi(e,r-1))|O(r<<8)|O(Qi(e,0)<<16)|O(Qi(e,r>>1)<<24),a=(i^(O(Zi(t,0))^O(Zi(t,4)))+n)&Ui,o=(O(Zi(t,8))^O(Zi(t,12)))-n;return(ha((ra(ea(i),O(13))^o)&Ui)&Ui)<<O(64)|ha(a)}function _a(e,t){return e^e>>t}function va(e,t,n){let r=e.byteLength;na(r>=4&&r<=8);{let i=Zi(e,0),a=Zi(e,r-4),o=((O(i)|O(a)<<O(32))^(Xi(t,16)^Xi(t,24))+n&Ui)*(Ni+(O(r)<<O(2)))&Hi;return o+=(o&Ui)<<O(65),o&=Hi,o^=o>>O(67),_a(_a(o&Ui,O(35))*zi&Ui,O(28))|ma(o>>O(64))<<O(64)}}function ya(e,t,n){let r=e.byteLength;na(r>=9&&r<=16);{let i=(Xi(t,32)^Xi(t,40))+n&Ui,a=(Xi(t,48)^Xi(t,56))-n&Ui,o=Xi(e),s=Xi(e,r-8),c=(o^s^i)*Ni,l=(c&Ui)+(O(r-1)<<O(54));c=c&(Hi^Ui)|l,s^=a,c+=s+(s&Wi)*(ji-O(1))<<O(64),c&=Hi,c^=$i(c>>O(64));let u=(c&Ui)*Pi;return u+=(c>>O(64))*Pi<<O(64),u&=Hi,ma(u&Ui)|ma(u>>O(64))<<O(64)}}function ba(e,t){let n=e.byteLength;return na(n<=16),n>8?ya(e,Vi,t):n>=4?va(e,Vi,t):n>0?ga(e,Vi,t):ha(t^Xi(Vi,64)^Xi(Vi,72))|ha(t^Xi(Vi,80)^Xi(Vi,88))<<O(64)}function xa(e){return~e+O(1)&Ui}function Sa(e,t,n){let r=O(e.byteLength)*Ni&Ui,i=O(e.byteLength-1)/O(32);for(;i>=0;){let a=Number(i);r=pa(r,Yi(e,16*a),Yi(e,e.byteLength-16*(a+1)),Yi(t,32*a),n),i--}let a=r+(r>>O(64))&Ui;a=ma(a);let o=(r&Ui)*Ni+(r>>O(64))*Ii+(O(e.byteLength)-n&Ui)*Pi;return o&=Ui,o=xa(ma(o)),a|o<<O(64)}function Ca(e,t,n){let r=O(e.byteLength)*Ni&Ui;for(let i=32;i<160;i+=32)r=pa(r,Yi(e,i-32),Yi(e,i-16),Yi(t,i-32),n);r=ma(r&Ui)|ma(r>>O(64))<<O(64);for(let i=160;i<=e.byteLength;i+=32)r=pa(r,Yi(e,i-32),Yi(e,i-16),Yi(t,3+i-160),n);r=pa(r,Yi(e,e.byteLength-16),Yi(e,e.byteLength-32),Yi(t,103),xa(n));let i=r+(r>>O(64))&Ui;i=ma(i);let a=(r&Ui)*Ni+(r>>O(64))*Ii+(O(e.byteLength)-n&Ui)*Pi;return a&=Ui,a=xa(ma(a)),i|a<<O(64)}function wa(e,t=O(0)){let n=e.byteLength;return n<=16?ba(e,t):n<=128?Sa(e,Vi,t):n<=240?Ca(e,Vi,t):ua(e,Vi,t)}function Ta(e){let t=new Uint8Array(16),n=new DataView(t.buffer),r=e&Ui,i=e>>O(64);return n.setBigUint64(0,i,!1),n.setBigUint64(8,r,!1),t}var Ea=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function k(e,t){if(!Ea.test(e)){let n=t===void 0?`Invalid UUID: ${e}`:`Invalid UUID for ${t}: ${e}`;throw Error(n)}return e}function Da(e){return Hr({msecs:typeof e==`string`?Date.parse(e):e,seq:0})}function Oa(e){if(!Ea.test(e))return null;let t=e[14];return parseInt(t,16)}function ka(e){let t=e.replace(/-/g,``),n=new Uint8Array(16);for(let e=0;e<16;e++)n[e]=parseInt(t.slice(e*2,e*2+2),16);return n}function Aa(e){let t=Array.from(e).map(e=>e.toString(16).padStart(2,`0`)).join(``);return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}var ja=new TextEncoder;function Ma(e){return Ta(wa(ja.encode(e)))}function Na(e,t){let n=Ma(`${e}:${t}`),r=new Uint8Array(16);if(Oa(e)===7){let t=ka(e);r.set(t.slice(0,6),0)}else{let e=Date.now();r[0]=e/1099511627776&255,r[1]=e/4294967296&255,r[2]=e/16777216&255,r[3]=e/65536&255,r[4]=e/256&255,r[5]=e&255}return r[6]=112|n[0]&15,r[7]=n[1],r[8]=128|n[2]&63,r.set(n.slice(3,10),9),Aa(r)}var Pa={join:(...e)=>e.join(`/`),dirname:e=>e.split(`/`).slice(0,-1).join(`/`)};async function Fa(e){}async function Ia(e,t){}async function La(e){return[]}async function Ra(e){return{size:0}}function za(e){return!1}function Ba(e){return``}function Va(e,t){return t===null?!1:Date.now()-e.createdAt>t*1e3}var Ha=new class{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(){let e=this.totalRequests;return e>0?this._metrics.hits/e:0}resetMetrics(){this._metrics={hits:0,misses:0,refreshes:0,refreshErrors:0}}get(e,t){if(this.maxSize===0)return;let n=this.cache.get(e);if(!n){this._metrics.misses+=1;return}return this.cache.delete(e),this.cache.set(e,{...n,refreshFunc:t}),this._metrics.hits+=1,n.value}set(e,t,n){if(this.maxSize===0)return;if(this.refreshTimer===void 0&&this.startRefreshLoop(),!this.cache.has(e)&&this.cache.size>=this.maxSize){let e=this.cache.keys().next().value;e!==void 0&&this.cache.delete(e)}let r={value:t,createdAt:Date.now(),refreshFunc:n};this.cache.delete(e),this.cache.set(e,r)}invalidate(e){this.cache.delete(e)}clear(){this.cache.clear()}get size(){return this.cache.size}stop(){this.refreshTimer&&=(clearInterval(this.refreshTimer),void 0)}dump(e){let t={};for(let[e,n]of this.cache.entries())t[e]=n.value;Pa.dirname(e),`${e}`;try{JSON.stringify({entries:t},null,2)}catch(e){throw e}}load(e){if(!za(e))return 0;let t;try{let n=Ba(e);t=JSON.parse(n).entries??null}catch{return 0}if(!t)return 0;let n=0,r=Date.now();for(let[e,i]of Object.entries(t)){if(this.cache.size>=this.maxSize)break;let t={value:i,createdAt:r};this.cache.set(e,t),n+=1}return n}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(){let e=[];for(let[t,n]of this.cache.entries())Va(n,this.ttlSeconds)&&e.push([t,n]);return e}async refreshStaleEntries(){let e=this.getStaleEntries();if(e.length!==0){for(let[t,n]of e)if(n.refreshFunc!==void 0)try{let e=await n.refreshFunc();this.set(t,e,n.refreshFunc),this._metrics.refreshes+=1}catch(e){this._metrics.refreshErrors+=1,console.warn(`Failed to refresh cache entry ${t}:`,e)}}}configure(e){this.stop(),this.refreshIntervalSeconds=e.refreshIntervalSeconds??60,this.maxSize=e.maxSize??100,this.ttlSeconds=e.ttlSeconds??300}},Ua=`0.5.23`,Wa,Ga=()=>typeof window<`u`&&window.document!==void 0,Ka=()=>typeof globalThis==`object`&&globalThis.constructor&&globalThis.constructor.name===`DedicatedWorkerGlobalScope`,qa=()=>typeof window<`u`&&window.name===`nodejs`||typeof navigator<`u`&&navigator.userAgent.includes(`jsdom`),Ja=()=>typeof Deno<`u`,Ya=()=>typeof process<`u`&&process.versions!==void 0&&process.versions.node!==void 0&&!Ja(),Xa=()=>Wa||(Wa=typeof Bun<`u`?`bun`:Ga()?`browser`:Ya()?`node`:Ka()?`webworker`:qa()?`jsdom`:Ja()?`deno`:`other`,Wa),Za;function Qa(){return Za===void 0&&(Za={library:`langsmith`,runtime:Xa(),sdk:`langsmith-js`,sdk_version:Ua,...io()}),Za}function $a(){let e=eo(),t={},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(let[r,i]of Object.entries(e))typeof i==`string`&&!n.includes(r)&&!r.toLowerCase().includes(`key`)&&!r.toLowerCase().includes(`secret`)&&!r.toLowerCase().includes(`token`)&&(r===`LANGCHAIN_REVISION_ID`?t.revision_id=i:t[r]=i);return t}function eo(){let e={};try{if(typeof process<`u`)for(let[t,n]of Object.entries({}))(t.startsWith(`LANGCHAIN_`)||t.startsWith(`LANGSMITH_`))&&n!=null&&((t.toLowerCase().includes(`key`)||t.toLowerCase().includes(`secret`)||t.toLowerCase().includes(`token`))&&typeof n==`string`?e[t]=n.slice(0,2)+`*`.repeat(n.length-4)+n.slice(-2):e[t]=n)}catch{}return e}function to(e){try{return typeof process<`u`?{}?.[e]:void 0}catch{return}}function no(e){return to(`LANGSMITH_${e}`)||to(`LANGCHAIN_${e}`)}var ro;function io(){if(ro!==void 0)return ro;let e=[`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`],t={};for(let n of e){let e=to(n);e!==void 0&&(t[n]=e)}return ro=t,t}function ao(){return to(`OTEL_ENABLED`)===`true`||no(`OTEL_ENABLED`)===`true`}var oo=class{constructor(){Object.defineProperty(this,`hasWarned`,{enumerable:!0,configurable:!0,writable:!0,value:!1})}startActiveSpan(e,...t){!this.hasWarned&&ao()&&(console.warn('You have enabled OTEL export via the `OTEL_ENABLED` or `LANGSMITH_OTEL_ENABLED` environment variable, but have not initialized the required OTEL instances. Please add:\n```\nimport { initializeOTEL } from "langsmith/experimental/otel/setup";\ninitializeOTEL();\n```\nat the beginning of your code.'),this.hasWarned=!0);let n;if(t.length===1&&typeof t[0]==`function`?n=t[0]:t.length===2&&typeof t[1]==`function`?n=t[1]:t.length===3&&typeof t[2]==`function`&&(n=t[2]),typeof n==`function`)return n()}},so=class{constructor(){Object.defineProperty(this,`mockTracer`,{enumerable:!0,configurable:!0,writable:!0,value:new oo})}getTracer(e,t){return this.mockTracer}getActiveSpan(){}setSpan(e,t){return e}getSpan(e){}setSpanContext(e,t){return e}getTracerProvider(){}setGlobalTracerProvider(e){return!1}},co=class{active(){return{}}with(e,t){return t()}},lo=Symbol.for(`ls:otel_trace`),uo=Symbol.for(`ls:otel_context`),fo=Symbol.for(`ls:otel_get_default_otlp_tracer_provider`),po=new so,mo=new co,ho=new class{getTraceInstance(){return globalThis[lo]??po}getContextInstance(){return globalThis[uo]??mo}initializeGlobalInstances(e){globalThis[lo]===void 0&&(globalThis[lo]=e.trace),globalThis[uo]===void 0&&(globalThis[uo]=e.context)}setDefaultOTLPTracerComponents(e){globalThis[fo]=e}getDefaultOTLPTracerComponents(){return globalThis[fo]??void 0}};function go(){return ho.getTraceInstance()}function _o(){return ho.getContextInstance()}function vo(){return ho.getDefaultOTLPTracerComponents()}var yo={llm:`chat`,tool:`execute_tool`,retriever:`embeddings`,embedding:`embeddings`,prompt:`chat`};function bo(e){return yo[e]||e}var xo=class{constructor(){Object.defineProperty(this,`spans`,{enumerable:!0,configurable:!0,writable:!0,value:new Map})}exportBatch(e,t){for(let n of e)try{if(!n.run)continue;if(n.operation===`post`){let e=this.createSpanForRun(n,n.run,t.get(n.id));e&&!n.run.end_time&&this.spans.set(n.id,e)}else this.updateSpanForRun(n,n.run)}catch(e){console.error(`Error processing operation ${n.id}:`,e)}}createSpanForRun(e,t,n){let r=n&&go().getSpan(n);if(r)try{return this.finishSpanSetup(r,t,e)}catch(t){console.error(`Failed to create span for run ${e.id}:`,t);return}}finishSpanSetup(e,t,n){return this.setSpanAttributes(e,t,n),t.error?(e.setStatus({code:2}),e.recordException(Error(t.error))):e.setStatus({code:1}),t.end_time&&e.end(new Date(t.end_time)),e}updateSpanForRun(e,t){try{let n=this.spans.get(e.id);if(!n){console.debug(`No span found for run ${e.id} during update`);return}this.setSpanAttributes(n,t,e),t.error?(n.setStatus({code:2}),n.recordException(Error(t.error))):n.setStatus({code:1});let r=t.end_time;r&&(n.end(new Date(r)),this.spans.delete(e.id))}catch(t){console.error(`Failed to update span for run ${e.id}:`,t)}}extractModelName(e){if(e.extra?.metadata){let t=e.extra.metadata;if(t.ls_model_name)return t.ls_model_name;if(t.invocation_params){let e=t.invocation_params;if(e.model)return e.model;if(e.model_name)return e.model_name}}}setSpanAttributes(e,t,n){if(`run_type`in t&&t.run_type){e.setAttribute(gi,t.run_type);let n=bo(t.run_type||`chain`);e.setAttribute(Ur,n)}`name`in t&&t.name&&e.setAttribute(_i,t.name),`session_id`in t&&t.session_id&&e.setAttribute(mi,t.session_id),`session_name`in t&&t.session_name&&e.setAttribute(hi,t.session_name),this.setGenAiSystem(e,t);let r=this.extractModelName(t);r&&e.setAttribute(Gr,r),`prompt_tokens`in t&&typeof t.prompt_tokens==`number`&&e.setAttribute(qr,t.prompt_tokens),`completion_tokens`in t&&typeof t.completion_tokens==`number`&&e.setAttribute(Jr,t.completion_tokens),`total_tokens`in t&&typeof t.total_tokens==`number`&&e.setAttribute(Yr,t.total_tokens),this.setInvocationParameters(e,t);let i=t.extra?.metadata||{};for(let[t,n]of Object.entries(i))n!=null&&e.setAttribute(`${vi}.${t}`,String(n));let a=t.tags;if(a&&Array.isArray(a)?e.setAttribute(yi,a.join(`, `)):a&&e.setAttribute(yi,String(a)),`serialized`in t&&typeof t.serialized==`object`){let n=t.serialized;n.name&&e.setAttribute(oi,String(n.name)),n.signature&&e.setAttribute(si,String(n.signature)),n.doc&&e.setAttribute(ci,String(n.doc))}this.setIOAttributes(e,n)}setGenAiSystem(e,t){let n=`langchain`,r=this.extractModelName(t);if(r){let e=r.toLowerCase();e.includes(`anthropic`)||e.startsWith(`claude`)?n=`anthropic`:e.includes(`bedrock`)?n=`aws.bedrock`:e.includes(`azure`)&&e.includes(`openai`)?n=`az.ai.openai`:e.includes(`azure`)&&e.includes(`inference`)?n=`az.ai.inference`:e.includes(`cohere`)?n=`cohere`:e.includes(`deepseek`)?n=`deepseek`:e.includes(`gemini`)?n=`gemini`:e.includes(`groq`)?n=`groq`:e.includes(`watson`)||e.includes(`ibm`)?n=`ibm.watsonx.ai`:e.includes(`mistral`)?n=`mistral_ai`:e.includes(`gpt`)||e.includes(`openai`)?n=`openai`:e.includes(`perplexity`)||e.includes(`sonar`)?n=`perplexity`:e.includes(`vertex`)?n=`vertex_ai`:(e.includes(`xai`)||e.includes(`grok`))&&(n=`xai`)}e.setAttribute(Wr,n)}setInvocationParameters(e,t){if(!t.extra?.metadata?.invocation_params)return;let n=t.extra.metadata.invocation_params;n.max_tokens!==void 0&&e.setAttribute(Xr,n.max_tokens),n.temperature!==void 0&&e.setAttribute(Zr,n.temperature),n.top_p!==void 0&&e.setAttribute(Qr,n.top_p),n.frequency_penalty!==void 0&&e.setAttribute($r,n.frequency_penalty),n.presence_penalty!==void 0&&e.setAttribute(ei,n.presence_penalty)}setIOAttributes(e,t){if(t.run.inputs)try{let n=t.run.inputs;typeof n==`object`&&n&&(n.model&&Array.isArray(n.messages)&&e.setAttribute(Gr,n.model),n.stream!==void 0&&e.setAttribute(bi,n.stream),n.extra_headers&&e.setAttribute(xi,JSON.stringify(n.extra_headers)),n.extra_query&&e.setAttribute(ii,JSON.stringify(n.extra_query)),n.extra_body&&e.setAttribute(ai,JSON.stringify(n.extra_body))),e.setAttribute(ni,JSON.stringify(n))}catch(e){console.debug(`Failed to process inputs for run ${t.id}`,e)}if(t.run.outputs)try{let n=t.run.outputs,r=this.getUnifiedRunTokens(n);if(r&&(e.setAttribute(qr,r[0]),e.setAttribute(Jr,r[1]),e.setAttribute(Yr,r[0]+r[1])),n&&typeof n==`object`){if(n.model&&e.setAttribute(Kr,String(n.model)),n.id&&e.setAttribute(li,n.id),n.choices&&Array.isArray(n.choices)){let t=n.choices.map(e=>e.finish_reason).filter(e=>e).map(String);t.length>0&&e.setAttribute(ti,t.join(`, `))}if(n.service_tier&&e.setAttribute(ui,n.service_tier),n.system_fingerprint&&e.setAttribute(di,n.system_fingerprint),n.usage_metadata&&typeof n.usage_metadata==`object`){let t=n.usage_metadata;t.input_token_details&&e.setAttribute(fi,JSON.stringify(t.input_token_details)),t.output_token_details&&e.setAttribute(pi,JSON.stringify(t.output_token_details))}}e.setAttribute(ri,JSON.stringify(n))}catch(e){console.debug(`Failed to process outputs for run ${t.id}`,e)}}getUnifiedRunTokens(e){if(!e)return null;let t=this.extractUnifiedRunTokens(e.usage_metadata);if(t)return t;let n=Object.keys(e);for(let r of n){let n=e[r];if(!(!n||typeof n!=`object`)&&(t=this.extractUnifiedRunTokens(n.usage_metadata),t||n.lc===1&&n.kwargs&&typeof n.kwargs==`object`&&(t=this.extractUnifiedRunTokens(n.kwargs.usage_metadata),t)))return t}let r=e.generations||[];if(!Array.isArray(r))return null;let i=Array.isArray(r[0])?r.flat():r;for(let e of i)if(typeof e==`object`&&e.message&&typeof e.message==`object`&&e.message.kwargs&&typeof e.message.kwargs==`object`&&(t=this.extractUnifiedRunTokens(e.message.kwargs.usage_metadata),t))return t;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]}},So=Object.prototype.toString,Co=e=>So.call(e)===`[object Error]`,wo=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 To(e){if(!(e&&Co(e)&&e.name===`TypeError`&&typeof e.message==`string`))return!1;let{message:t,stack:n}=e;return t===`Load failed`?n===void 0||`__sentry_captured__`in e:t.startsWith(`error sending request for url`)?!0:wo.has(t)}function Eo(e){if(typeof e==`number`){if(e<0)throw TypeError("Expected `retries` to be a non-negative number.");if(Number.isNaN(e))throw TypeError("Expected `retries` to be a valid number or Infinity, got NaN.")}else if(e!==void 0)throw TypeError("Expected `retries` to be a number or Infinity.")}function Do(e,t,{min:n=0,allowInfinity:r=!1}={}){if(t!==void 0){if(typeof t!=`number`||Number.isNaN(t))throw TypeError(`Expected \`${e}\` to be a number${r?` or Infinity`:``}.`);if(!r&&!Number.isFinite(t))throw TypeError(`Expected \`${e}\` to be a finite number.`);if(t<n)throw TypeError(`Expected \`${e}\` to be \u2265 ${n}.`)}}var Oo=class extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,{message:e}=e):(this.originalError=Error(e),this.originalError.stack=this.stack),this.name=`AbortError`,this.message=e}};function ko(e,t){let n=Math.max(1,e+1),r=t.randomize?Math.random()+1:1,i=Math.round(r*t.minTimeout*t.factor**(n-1));return i=Math.min(i,t.maxTimeout),i}function Ao(e,t){return Number.isFinite(t)?t-(performance.now()-e):t}async function jo({error:e,attemptNumber:t,retriesConsumed:n,startTime:r,options:i}){let a=e instanceof Error?e:TypeError(`Non-error was thrown: "${e}". You should only throw errors.`);if(a instanceof Oo)throw a.originalError;let o=Number.isFinite(i.retries)?Math.max(0,i.retries-n):i.retries,s=i.maxRetryTime??1/0,c=Object.freeze({error:a,attemptNumber:t,retriesLeft:o,retriesConsumed:n});if(await i.onFailedAttempt(c),Ao(r,s)<=0)throw a;let l=await i.shouldConsumeRetry(c),u=Ao(r,s);if(u<=0||o<=0)throw a;if(a instanceof TypeError&&!To(a)){if(l)throw a;return i.signal?.throwIfAborted(),!1}if(!await i.shouldRetry(c))throw a;if(!l)return i.signal?.throwIfAborted(),!1;let d=ko(n,i),f=Math.min(d,u);return f>0&&await new Promise((e,t)=>{let n=()=>{clearTimeout(r),i.signal?.removeEventListener(`abort`,n),t(i.signal.reason)},r=setTimeout(()=>{i.signal?.removeEventListener(`abort`,n),e()},f);i.unref&&r.unref?.(),i.signal?.addEventListener(`abort`,n,{once:!0})}),i.signal?.throwIfAborted(),!0}async function Mo(e,t={}){if(t={...t},Eo(t.retries),Object.hasOwn(t,`forever`))throw Error("The `forever` option is no longer supported. For many use-cases, you can set `retries: Infinity` instead.");t.retries??=10,t.factor??=2,t.minTimeout??=1e3,t.maxTimeout??=1/0,t.maxRetryTime??=1/0,t.randomize??=!1,t.onFailedAttempt??=()=>{},t.shouldRetry??=()=>!0,t.shouldConsumeRetry??=()=>!0,Do(`factor`,t.factor,{min:0,allowInfinity:!1}),Do(`minTimeout`,t.minTimeout,{min:0,allowInfinity:!1}),Do(`maxTimeout`,t.maxTimeout,{min:0,allowInfinity:!0}),Do(`maxRetryTime`,t.maxRetryTime,{min:0,allowInfinity:!0}),t.factor>0||(t.factor=1),t.signal?.throwIfAborted();let n=0,r=0,i=performance.now();for(;!Number.isFinite(t.retries)||r<=t.retries;){n++;try{t.signal?.throwIfAborted();let r=await e(n);return t.signal?.throwIfAborted(),r}catch(e){await jo({error:e,attemptNumber:n,retriesConsumed:r,startTime:i,options:t})&&r++}}throw Error(`Retry attempts exhausted without throwing an error.`)}var No=t(((e,t)=>{var n=Object.prototype.hasOwnProperty,r=`~`;function i(){}Object.create&&(i.prototype=Object.create(null),new i().__proto__||(r=!1));function a(e,t,n){this.fn=e,this.context=t,this.once=n||!1}function o(e,t,n,i,o){if(typeof n!=`function`)throw TypeError(`The listener must be a function`);var s=new a(n,i||e,o),c=r?r+t:t;return e._events[c]?e._events[c].fn?e._events[c]=[e._events[c],s]:e._events[c].push(s):(e._events[c]=s,e._eventsCount++),e}function s(e,t){--e._eventsCount===0?e._events=new i:delete e._events[t]}function c(){this._events=new i,this._eventsCount=0}c.prototype.eventNames=function(){var e=[],t,i;if(this._eventsCount===0)return e;for(i in t=this._events)n.call(t,i)&&e.push(r?i.slice(1):i);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e},c.prototype.listeners=function(e){var t=r?r+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var i=0,a=n.length,o=Array(a);i<a;i++)o[i]=n[i].fn;return o},c.prototype.listenerCount=function(e){var t=r?r+e:e,n=this._events[t];return n?n.fn?1:n.length:0},c.prototype.emit=function(e,t,n,i,a,o){var s=r?r+e:e;if(!this._events[s])return!1;var c=this._events[s],l=arguments.length,u,d;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),l){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,t),!0;case 3:return c.fn.call(c.context,t,n),!0;case 4:return c.fn.call(c.context,t,n,i),!0;case 5:return c.fn.call(c.context,t,n,i,a),!0;case 6:return c.fn.call(c.context,t,n,i,a,o),!0}for(d=1,u=Array(l-1);d<l;d++)u[d-1]=arguments[d];c.fn.apply(c.context,u)}else{var f=c.length,p;for(d=0;d<f;d++)switch(c[d].once&&this.removeListener(e,c[d].fn,void 0,!0),l){case 1:c[d].fn.call(c[d].context);break;case 2:c[d].fn.call(c[d].context,t);break;case 3:c[d].fn.call(c[d].context,t,n);break;case 4:c[d].fn.call(c[d].context,t,n,i);break;default:if(!u)for(p=1,u=Array(l-1);p<l;p++)u[p-1]=arguments[p];c[d].fn.apply(c[d].context,u)}}return!0},c.prototype.on=function(e,t,n){return o(this,e,t,n,!1)},c.prototype.once=function(e,t,n){return o(this,e,t,n,!0)},c.prototype.removeListener=function(e,t,n,i){var a=r?r+e:e;if(!this._events[a])return this;if(!t)return s(this,a),this;var o=this._events[a];if(o.fn)o.fn===t&&(!i||o.once)&&(!n||o.context===n)&&s(this,a);else{for(var c=0,l=[],u=o.length;c<u;c++)(o[c].fn!==t||i&&!o[c].once||n&&o[c].context!==n)&&l.push(o[c]);l.length?this._events[a]=l.length===1?l[0]:l:s(this,a)}return this},c.prototype.removeAllListeners=function(e){var t;return e?(t=r?r+e:e,this._events[t]&&s(this,t)):(this._events=new i,this._eventsCount=0),this},c.prototype.off=c.prototype.removeListener,c.prototype.addListener=c.prototype.on,c.prefixed=r,c.EventEmitter=c,t!==void 0&&(t.exports=c)})),Po=t(((e,t)=>{t.exports=(e,t)=>(t||=(()=>{}),e.then(e=>new Promise(e=>{e(t())}).then(()=>e),e=>new Promise(e=>{e(t())}).then(()=>{throw e})))})),Fo=t(((e,t)=>{var n=Po(),r=class extends Error{constructor(e){super(e),this.name=`TimeoutError`}},i=(e,t,i)=>new Promise((a,o)=>{if(typeof t!=`number`||t<0)throw TypeError("Expected `milliseconds` to be a positive number");if(t===1/0){a(e);return}let s=setTimeout(()=>{if(typeof i==`function`){try{a(i())}catch(e){o(e)}return}let n=typeof i==`string`?i:`Promise timed out after ${t} milliseconds`,s=i instanceof Error?i:new r(n);typeof e.cancel==`function`&&e.cancel(),o(s)},t);n(e.then(a,o),()=>{clearTimeout(s)})});t.exports=i,t.exports.default=i,t.exports.TimeoutError=r})),Io=t((e=>{Object.defineProperty(e,`__esModule`,{value:!0});function t(e,t,n){let r=0,i=e.length;for(;i>0;){let a=i/2|0,o=r+a;n(e[o],t)<=0?(r=++o,i-=a+1):i=a}return r}e.default=t})),Lo=t((e=>{Object.defineProperty(e,`__esModule`,{value:!0});var t=Io();e.default=class{constructor(){this._queue=[]}enqueue(e,n){n=Object.assign({priority:0},n);let r={priority:n.priority,run:e};if(this.size&&this._queue[this.size-1].priority>=n.priority){this._queue.push(r);return}let i=t.default(this._queue,r,(e,t)=>t.priority-e.priority);this._queue.splice(i,0,r)}dequeue(){return this._queue.shift()?.run}filter(e){return this._queue.filter(t=>t.priority===e.priority).map(e=>e.run)}get size(){return this._queue.length}}})),Ro=e(t((e=>{Object.defineProperty(e,`__esModule`,{value:!0});var t=No(),n=Fo(),r=Lo(),i=()=>{},a=new n.TimeoutError;e.default=class extends t{constructor(e){if(super(),this._intervalCount=0,this._intervalEnd=0,this._pendingCount=0,this._resolveEmpty=i,this._resolveIdle=i,e=Object.assign({carryoverConcurrencyCount:!1,intervalCap:1/0,interval:0,concurrency:1/0,autoStart:!0,queueClass:r.default},e),!(typeof e.intervalCap==`number`&&e.intervalCap>=1))throw TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${e.intervalCap?.toString()??``}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${e.interval?.toString()??``}\` (${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=i,this._pendingCount===0&&(this._resolveIdle(),this._resolveIdle=i,this.emit(`idle`))}_onResumeInterval(){this._onInterval(),this._initializeIntervalIfNeeded(),this._timeoutId=void 0}_isIntervalPaused(){let e=Date.now();if(this._intervalId===void 0){let t=this._intervalEnd-e;if(t<0)this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0;else return this._timeoutId===void 0&&(this._timeoutId=setTimeout(()=>{this._onResumeInterval()},t)),!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){let e=!this._isIntervalPaused();if(this._doesIntervalAllowAnother&&this._doesConcurrentAllowAnother){let t=this._queue.dequeue();return t?(this.emit(`active`),t(),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 TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);this._concurrency=e,this._processQueue()}async add(e,t={}){return new Promise((r,i)=>{this._queue.enqueue(async()=>{this._pendingCount++,this._intervalCount++;try{r(await(this._timeout===void 0&&t.timeout===void 0?e():n.default(Promise.resolve(e()),t.timeout===void 0?this._timeout:t.timeout,()=>{(t.throwOnTimeout===void 0?this._throwOnTimeout:t.throwOnTimeout)&&i(a)})))}catch(e){i(e)}this._next()},t),this._tryToStartAnother(),this.emit(`add`)})}async addAll(e,t){return Promise.all(e.map(async e=>this.add(e,t)))}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=>{let t=this._resolveEmpty;this._resolveEmpty=()=>{t(),e()}})}async onIdle(){if(!(this._pendingCount===0&&this._queue.size===0))return new Promise(e=>{let t=this._resolveIdle;this._resolveIdle=()=>{t(),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}}}))(),1),zo=`default`in Ro.default?Ro.default.default:Ro.default,Bo=[408,425,429,500,502,503,504],Vo=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 zo({concurrency:this.maxConcurrency}),this.onFailedResponseHook=e?.onFailedResponseHook}call(e,...t){return this.callWithOptions({},e,...t)}callWithOptions(e,t,...n){let r=e.sizeBytes??0;if(this.maxQueueSizeBytes!==void 0&&r>0&&this.queueSizeBytes+r>this.maxQueueSizeBytes)return Promise.reject(Error(`Queue size limit (${this.maxQueueSizeBytes} bytes) exceeded. Current queue size: ${this.queueSizeBytes} bytes, attempted addition: ${r} bytes.`));r>0&&(this.queueSizeBytes+=r);let i=this.onFailedResponseHook,a=this.queue.add(()=>Mo(()=>t(...n).catch(e=>{throw e instanceof Error?e:Error(e)}),{async onFailedAttempt({error:e}){if(typeof e!=`object`||!e)throw e;let t=`message`in e&&typeof e.message==`string`?e.message:void 0;if(t?.startsWith(`Cancel`)||t?.startsWith(`TimeoutError`)||t?.startsWith(`AbortError`)||`name`in e&&e.name===`TimeoutError`||`code`in e&&e.code===`ECONNABORTED`)throw e;let n=`response`in e?e.response:void 0;if(i&&await i(n))return;let r=n?.status??(`status`in e?e.status:void 0);if(r!=null&&(typeof r==`number`||typeof r==`string`)&&!Bo.includes(+r))throw e},retries:this.maxRetries,randomize:!0}),{throwOnTimeout:!0});return r>0&&(a=a.finally(()=>{this.queueSizeBytes-=r})),e.signal?Promise.race([a,new Promise((t,n)=>{e.signal?.addEventListener(`abort`,()=>{n(Error(`AbortError`))})})]):a}};function Ho(e){return typeof e?._getType==`function`}function Uo(e){let t={type:e._getType(),data:{content:e.content}};return e?.additional_kwargs&&Object.keys(e.additional_kwargs).length>0&&(t.data.additional_kwargs={...e.additional_kwargs}),t}function Wo(e){return`Invalid prompt identifier format: "${e}". Expected one of:\n - "prompt-name" (for private prompts)\n - "owner/prompt-name" (for prompts with explicit owner)\n - "prompt-name:commit-hash" (with commit reference)\n - "owner/prompt-name:commit-hash" (with owner and commit)`}var Go=class 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}},Ko=class 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 qo(e){return typeof e==`object`&&!!e&&`name`in e&&e?.name===`LangSmithNotFoundError`}function Jo(e){return typeof e==`object`&&!!e&&`name`in e&&e?.name===`LangSmithConflictError`}async function A(e,t,n){let r;if(e.ok){n&&(r=await e.text());return}if(e.status===403)try{(await e.json())?.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{let t=Error(`${e.status} ${e.statusText}`);throw t.status=e?.status,t}if(r===void 0)try{r=await e.text()}catch{r=``}let i=`Failed to ${t}. Received status [${e.status}]: ${e.statusText}. Message: ${r}`;if(e.status===404)throw new Ko(i);if(e.status===409)throw new Go(i);let a=Error(i);throw a.status=e.status,a}var Yo=`ERR_CONFLICTING_ENDPOINTS`,Xo=class 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:Yo}),this.name=`ConflictingEndpointsError`}};function Zo(e){return typeof e==`object`&&!!e&&e.code===Yo}function Qo(e){if(!e||e.split(`/`).length>2||e.startsWith(`/`)||e.endsWith(`/`)||e.split(`:`).length>2)throw Error(Wo(e));let[t,n]=e.split(`:`),r=n||`latest`;if(t.includes(`/`)){let[n,i]=t.split(`/`,2);if(!n||!i)throw Error(Wo(e));return[n,i,r]}else{if(!t)throw Error(Wo(e));return[`-`,t,r]}}var $o=`[...]`,es={result:`[Circular]`},ts=[],ns=[],rs=new TextEncoder;function is(){return{depthLimit:2**53-1,edgesLimit:2**53-1}}function as(e){return rs.encode(e)}function os(e){if(e&&typeof e==`object`&&e){if(e instanceof Map)return Object.fromEntries(e);if(e instanceof Set)return Array.from(e);if(e instanceof Date)return e.toISOString();if(e instanceof RegExp)return e.toString();if(e instanceof Error)return{name:e.name,message:e.message}}else if(typeof e==`bigint`)return e.toString();return e}function ss(e){return function(t,n){if(e){let r=e.call(this,t,n);if(r!==void 0)return r}return os(n)}}function cs(e){try{let t=new Set,n=typeof Buffer<`u`&&typeof Buffer.byteLength==`function`?e=>Buffer.byteLength(e,`utf8`):e=>e.length;function r(e){return n(e)+2}function i(e){return e===0?2:2+e*4}function a(e){return e===void 0||typeof e==`function`||typeof e==`symbol`}function o(e){return e===void 0||typeof e==`function`||typeof e==`symbol`?4:s(e)}function s(e){if(e===null)return 4;if(e===void 0)return 0;let c=typeof e;if(c===`boolean`)return 5;if(c===`number`)return Number.isFinite(e)?e.toString().length:4;if(c===`bigint`)return e.toString().length+2;if(c===`string`)return r(e);if(c===`function`||c===`symbol`)return 0;let l=e;if(l instanceof Date)return 26;if(l instanceof RegExp)return n(l.toString())+2;if(l instanceof Error){let e=l.name??``,t=l.message??``;return 22+n(e)+n(t)}if(typeof Buffer<`u`&&l instanceof Buffer)return 28+i(l.byteLength);if(ArrayBuffer.isView(l))return l instanceof DataView?2:2+(l.length??0)*(l instanceof Float32Array||l instanceof Float64Array?30:12);if(l instanceof ArrayBuffer)return 2;if(t.has(l))return 24;if(typeof l.toJSON==`function`){let e;try{e=l.toJSON(``)}catch{return 16}t.add(l);let n=s(e);return t.delete(l),n}t.add(l);let u;if(Array.isArray(l)){u=2;let e=l.length;for(let t=0;t<e;t++)u+=o(l[t]),t<e-1&&(u+=1)}else if(l instanceof Map){u=2;let e=0;for(let[t,r]of l)a(r)||(e>0&&(u+=1),u+=n(typeof t==`string`?t:String(t))+3,u+=s(r),e++)}else if(l instanceof Set){u=2;let e=0;for(let t of l)e>0&&(u+=1),u+=o(t),e++}else{u=2;let e=0,t=Object.keys(l);for(let r=0;r<t.length;r++){let i=t[r],o=l[i];a(o)||(e>0&&(u+=1),u+=n(i)+3,u+=s(o),e++)}}return t.delete(l),u}return s(e)}catch{return ls(e).length}}function ls(e,t,n,r,i){try{return as(JSON.stringify(e,ss(n),r))}catch(a){if(!a.message?.includes(`Converting circular structure to JSON`))return console.warn(`[WARNING]: LangSmith received unserializable value.${t?`\nContext: ${t}`:``}`),as(`[Unserializable]`);no(`SUPPRESS_CIRCULAR_JSON_WARNINGS`)!==`true`&&console.warn(`[WARNING]: LangSmith received circular JSON. This will decrease tracer performance. ${t?`\nContext: ${t}`:``}`),i===void 0&&(i=is()),ds(e,``,0,[],void 0,0,i);let o;try{o=ns.length===0?JSON.stringify(e,n,r):JSON.stringify(e,fs(n),r)}catch{return as(`[unable to serialize, circular reference is too complex to analyze]`)}finally{for(;ts.length!==0;){let e=ts.pop();e.length===4?Object.defineProperty(e[0],e[1],e[3]):e[0][e[1]]=e[2]}}return as(o)}}function us(e,t,n,r){var i=Object.getOwnPropertyDescriptor(r,n);i.get===void 0?(r[n]=e,ts.push([r,n,t])):i.configurable?(Object.defineProperty(r,n,{value:e}),ts.push([r,n,t,i])):ns.push([t,n,e])}function ds(e,t,n,r,i,a,o){a+=1;var s;if(typeof e==`object`&&e){for(s=0;s<r.length;s++)if(r[s]===e){us(es,e,t,i);return}if(o.depthLimit!==void 0&&a>o.depthLimit){us($o,e,t,i);return}if(o.edgesLimit!==void 0&&n+1>o.edgesLimit){us($o,e,t,i);return}if(r.push(e),Array.isArray(e))for(s=0;s<e.length;s++)ds(e[s],s,s,r,e,a,o);else{e=os(e);var c=Object.keys(e);for(s=0;s<c.length;s++){var l=c[s];ds(e[l],l,s,r,e,a,o)}}r.pop()}}function fs(e){return e=e===void 0?function(e,t){return t}:e,function(t,n){if(ns.length>0)for(var r=0;r<ns.length;r++){var i=ns[r];if(i[1]===t&&i[0]===n){n=i[2],ns.splice(r,1);break}}return e.call(this,t,n)}}function ps(e){return typeof e==`string`&&e.length>0&&!e.includes(`Z`)&&!e.includes(`+`)&&!e.includes(`-`,10)?e+`Z`:e}function ms(e){return{...e,start_time:ps(e.start_time),end_time:ps(e.end_time)}}function hs(e,t,n){if(n)return e;let r=Qa(),i=t??$a(),a=e.extra??{},o=a.metadata;return e.extra={...a,runtime:{...r,...a?.runtime},metadata:{...i,...i.revision_id||`revision_id`in e&&e.revision_id?{revision_id:(`revision_id`in e?e.revision_id:void 0)??i.revision_id}:{},...o}},e}var gs=e=>{let t=e?.toString()??no(`TRACING_SAMPLING_RATE`);if(t===void 0)return;let n=parseFloat(t);if(n<0||n>1)throw Error(`LANGSMITH_TRACING_SAMPLING_RATE must be between 0 and 1 if set. Got: ${n}`);return n},_s=e=>{let t=e.replace(`http://`,``).replace(`https://`,``).split(`/`)[0].split(`:`)[0];return t===`localhost`||t===`127.0.0.1`||t===`::1`};async function vs(e){let t=[];for await(let n of e)t.push(n);return t}function ys(e){if(e!==void 0)return e.trim().replace(/^"(.*)"$/,`$1`).replace(/^'(.*)'$/,`$1`)}var bs=async e=>{if(e?.status===429){let t=parseInt(e.headers.get(`retry-after`)??`10`,10)*1e3;if(t>0)return await new Promise(e=>setTimeout(e,t)),!0}return!1};function xs(e){return typeof e==`number`?Number(e.toFixed(4)):e}var Ss=1e4,Cs=100,ws=`https://api.smith.langchain.com`,Ts=class{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??1073741824}peek(){return this.items[0]}push(e){let t,n=new Promise(e=>{t=e}),r=no(`PERF_OPTIMIZATION`)===`true`?cs(e.item):ls(e.item,`Serializing run with id: ${e.item.id}`).length;return this.sizeBytes+r>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: ${r} bytes.`),t(),n):(this.items.push({action:e.action,payload:e.item,otelContext:e.otelContext,apiKey:e.apiKey,apiUrl:e.apiUrl,itemPromiseResolve:t,itemPromise:n,size:r}),this.sizeBytes+=r,n)}pop({upToSizeBytes:e,upToSize:t}){if(e<1)throw Error(`Number of bytes to pop off may not be less than 1.`);let n=[],r=0;for(;r+(this.peek()?.size??0)<e&&this.items.length>0&&n.length<t;){let e=this.items.shift();e&&(n.push(e),r+=e.size,this.sizeBytes-=e.size)}if(n.length===0&&this.items.length>0){let e=this.items.shift();n.push(e),r+=e.size,this.sizeBytes-=e.size}return[n.map(e=>({action:e.action,item:e.payload,otelContext:e.otelContext,apiKey:e.apiKey,apiUrl:e.apiUrl,size:e.size})),()=>n.forEach(e=>e.itemPromiseResolve())]}},Es=class e{get _fetch(){return this.fetchImplementation||Ei(this.debug)}constructor(t={}){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:to(`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,`langSmithToOTELTranslator`,{enumerable:!0,configurable:!0,writable:!0,value:void 0}),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:no(`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:to(`LANGSMITH_DEBUG`)===`true`});let n=e.getDefaultClientConfig();if(this.tracingSampleRate=gs(t.tracingSamplingRate),this.apiUrl=ys(t.apiUrl??n.apiUrl)??``,this.apiUrl.endsWith(`/`)&&(this.apiUrl=this.apiUrl.slice(0,-1)),this.apiKey=ys(t.apiKey??n.apiKey),this.webUrl=ys(t.webUrl??n.webUrl),this.webUrl?.endsWith(`/`)&&(this.webUrl=this.webUrl.slice(0,-1)),this.workspaceId=ys(t.workspaceId??no(`WORKSPACE_ID`)),this.timeout_ms=t.timeout_ms??9e4,this.caller=new Vo({...t.callerOptions??{},maxRetries:4,debug:t.debug??this.debug}),this.traceBatchConcurrency=t.traceBatchConcurrency??this.traceBatchConcurrency,this.traceBatchConcurrency<1)throw Error(`Trace batch concurrency must be positive.`);this.debug=t.debug??this.debug,this.fetchImplementation=t.fetchImplementation,this.failedTracesDir=no(`FAILED_TRACES_DIR`)||void 0;let r=no(`FAILED_TRACES_MAX_MB`);if(r){let e=parseInt(r,10);Number.isFinite(e)&&e>0&&(this.failedTracesMaxBytes=e*1024*1024)}let i=t.maxIngestMemoryBytes??1073741824;this.batchIngestCaller=new Vo({maxRetries:4,maxConcurrency:this.traceBatchConcurrency,maxQueueSizeBytes:i,...t.callerOptions??{},onFailedResponseHook:bs,debug:t.debug??this.debug}),this.hideInputs=t.hideInputs??t.anonymizer??n.hideInputs,this.hideOutputs=t.hideOutputs??t.anonymizer??n.hideOutputs,this.hideMetadata=t.hideMetadata??n.hideMetadata,this.omitTracedRuntimeInfo=t.omitTracedRuntimeInfo??!1,this.autoBatchTracing=t.autoBatchTracing??this.autoBatchTracing,this.autoBatchQueue=new Ts(i),this.blockOnRootRunFinalization=t.blockOnRootRunFinalization??this.blockOnRootRunFinalization,this.batchSizeBytesLimit=t.batchSizeBytesLimit,this.batchSizeLimit=t.batchSizeLimit,this.fetchOptions=t.fetchOptions||{},this.manualFlushMode=t.manualFlushMode??this.manualFlushMode,ao()&&(this.langSmithToOTELTranslator=new xo),this.cachedLSEnvVarsForMetadata=$a(),t.cache!==void 0&&t.disablePromptCache&&ki(`Both 'cache' and 'disablePromptCache' were provided. The 'cache' parameter is deprecated and will be removed in a future version. Using 'cache' parameter value.`),t.cache===void 0?t.disablePromptCache||(this._promptCache=Ha):(ki(`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.`),t.cache===!1?this._promptCache=void 0:t.cache===!0?this._promptCache=Ha:this._promptCache=t.cache),this._customHeaders=t.headers??{}}static getDefaultClientConfig(){let e=no(`API_KEY`);return{apiUrl:no(`ENDPOINT`)??ws,apiKey:e,webUrl:void 0,hideInputs:no(`HIDE_INPUTS`)===`true`,hideOutputs:no(`HIDE_OUTPUTS`)===`true`,hideMetadata:no(`HIDE_METADATA`)===`true`}}getHostUrl(){return this.webUrl?this.webUrl:_s(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(){let e={"User-Agent":`langsmith-js/${Ua}`,...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(e=>{if(e.name===`new_token`){let{kwargs:t,...n}=e;return n}return e})}async prepareRunCreateOrUpdateInputs(e){let t={...e};return t.inputs!==void 0&&(t.inputs=await this.processInputs(t.inputs)),t.outputs!==void 0&&(t.outputs=await this.processOutputs(t.outputs)),t.extra!=null&&`metadata`in t.extra&&(t.extra={...t.extra,metadata:await this.processMetadata(t.extra.metadata)}),t.events!==void 0&&(t.events=this._filterNewTokenEvents(t.events)),t}async _getResponse(e,t){let n=t?.toString()??``,r=`${this.apiUrl}${e}?${n}`;return await this.caller.call(async()=>{let t=await this._fetch(r,{method:`GET`,headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await A(t,`fetch ${e}`),t})}async _get(e,t){return(await this._getResponse(e,t)).json()}async*_getPaginated(e,t=new URLSearchParams,n){let r=Number(t.get(`offset`))||0,i=Number(t.get(`limit`))||100;for(;;){t.set(`offset`,String(r)),t.set(`limit`,String(i));let a=`${this.apiUrl}${e}?${t}`,o=await this.caller.call(async()=>{let t=await this._fetch(a,{method:`GET`,headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await A(t,`fetch ${e}`),t}),s=n?n(await o.json()):await o.json();if(s.length===0||(yield s,s.length<i))break;r+=s.length}}async*_getCursorPaginatedList(e,t=null,n=`POST`,r=`runs`){let i=t?{...t}:{};for(;;){let t=JSON.stringify(i),a=await(await this.caller.call(async()=>{let r=await this._fetch(`${this.apiUrl}${e}`,{method:n,headers:{...this._mergedHeaders,"Content-Type":`application/json`},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:t});return await A(r,`fetch ${e}`),r})).json();if(!a||!a[r])break;yield a[r];let o=a.cursors;if(!o||!o.next)break;i.cursor=o.next}}_shouldSample(){return this.tracingSampleRate===void 0?!0:Math.random()<this.tracingSampleRate}_filterForSampling(e,t=!1){if(this.tracingSampleRate===void 0)return e;if(t){let t=[];for(let n of e)this.filteredPostUuids.has(n.trace_id)?n.id===n.trace_id&&this.filteredPostUuids.delete(n.trace_id):t.push(n);return t}else{let t=[];for(let n of e){let e=n.trace_id??n.id;this.filteredPostUuids.has(e)||(n.id===e?this._shouldSample()?t.push(n):this.filteredPostUuids.add(e):t.push(n))}return t}}async _getBatchSizeLimitBytes(){let e=await this._ensureServerInfo();return this.batchSizeBytesLimit??e?.batch_ingest_config?.size_limit_bytes??25165824}async _getBatchSizeLimit(){let e=await this._ensureServerInfo();return this.batchSizeLimit??e?.batch_ingest_config?.size_limit??Cs}async _getDatasetExamplesMultiPartSupport(){return(await this._ensureServerInfo()).instance_flags?.dataset_examples_multipart_enabled??!1}drainAutoBatchQueue({batchSizeLimitBytes:e,batchSizeLimit:t}){let n=[];for(;this.autoBatchQueue.items.length>0;){let[r,i]=this.autoBatchQueue.pop({upToSizeBytes:e,upToSize:t});if(!r.length){i();break}let a=r.reduce((e,t)=>{let n=t.apiUrl??this.apiUrl,r=t.apiKey??this.apiKey,i=t.apiKey===this.apiKey&&t.apiUrl===this.apiUrl?`default`:`${n}|${r}`;return e[i]||(e[i]=[]),e[i].push(t),e},{}),o=[];for(let[e,t]of Object.entries(a)){let n=this._processBatch(t,{apiUrl:e===`default`?void 0:e.split(`|`)[0],apiKey:e===`default`?void 0:e.split(`|`)[1]});o.push(n)}let s=Promise.all(o).finally(i);n.push(s)}return Promise.all(n)}static async _writeTraceToFallbackDir(t,n,r,i,a){try{let o=typeof n==`string`?Buffer.from(n,`utf8`):Buffer.from(n),s=JSON.stringify({version:1,endpoint:i,headers:r,body_base64:o.toString(`base64`)}),c=`trace_${Date.now()}_${Pr().slice(0,8)}.json`,l=Pa.join(t,c);if(e._fallbackDirsCreated.has(t)||(await Fa(t),e._fallbackDirsCreated.add(t)),a!==void 0&&a>0)try{let e=(await La(t)).filter(e=>e.startsWith(`trace_`)&&e.endsWith(`.json`)),n=0;for(let r of e){let{size:e}=await Ra(Pa.join(t,r));n+=e}if(n>=a){console.warn(`Could not write trace to fallback dir ${t} as it's already over size limit (${n} bytes >= ${a} bytes). Increase LANGSMITH_FAILED_TRACES_MAX_MB if possible.`);return}}catch{}await Ia(l,s),console.warn(`LangSmith trace upload failed; data saved to ${l} for later replay.`)}catch(e){console.error(`LangSmith tracing error: could not write trace to fallback dir ${t}:`,e)}}async _processBatch(e,t){if(!e.length)return;let n=e.reduce((e,t)=>e+(t.size??0),0);try{if(this.langSmithToOTELTranslator!==void 0)this._sendBatchToOTELTranslator(e);else{let r={runCreates:e.filter(e=>e.action===`create`).map(e=>e.item),runUpdates:e.filter(e=>e.action===`update`).map(e=>e.item)},i=await this._ensureServerInfo();if(!this._multipartDisabled&&(i?.batch_ingest_config?.use_multipart_endpoint??!0)){let e=!this._runCompressionDisabled&&i?.instance_flags?.gzip_body_enabled;try{await this.multipartIngestRuns(r,{...t,useGzip:e,sizeBytes:n})}catch(e){if(qo(e))this._multipartDisabled=!0,await this.batchIngestRuns(r,{...t,sizeBytes:n});else throw e}}else await this.batchIngestRuns(r,{...t,sizeBytes:n})}}catch(e){console.error(`Error exporting batch:`,e)}}_sendBatchToOTELTranslator(e){if(this.langSmithToOTELTranslator!==void 0){let t=new Map,n=[];for(let r of e)r.item.id&&r.otelContext&&(t.set(r.item.id,r.otelContext),r.action===`create`?n.push({operation:`post`,id:r.item.id,trace_id:r.item.trace_id??r.item.id,run:r.item}):n.push({operation:`patch`,id:r.item.id,trace_id:r.item.trace_id??r.item.id,run:r.item}));this.langSmithToOTELTranslator.exportBatch(n,t)}}async processRunOperation(e){clearTimeout(this.autoBatchTimeout),this.autoBatchTimeout=void 0,e.item=hs(e.item,this.cachedLSEnvVarsForMetadata,this.omitTracedRuntimeInfo);let t=this.autoBatchQueue.push(e);if(this.manualFlushMode)return t;let n=await this._getBatchSizeLimitBytes(),r=await this._getBatchSizeLimit();return(this.autoBatchQueue.sizeBytes>n||this.autoBatchQueue.items.length>r)&&this.drainAutoBatchQueue({batchSizeLimitBytes:n,batchSizeLimit:r}),this.autoBatchQueue.items.length>0&&(this.autoBatchTimeout=setTimeout(()=>{this.autoBatchTimeout=void 0,this.drainAutoBatchQueue({batchSizeLimitBytes:n,batchSizeLimit:r})},this.autoBatchAggregationDelayMs)),t}async _getServerInfo(){let e=await(await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/info`,{method:`GET`,headers:{Accept:`application/json`},signal:AbortSignal.timeout(Ss),...this.fetchOptions});return await A(e,`get server info`),e})).json();return this.debug&&console.log(`
9
- === LangSmith Server Configuration ===
10
- `+JSON.stringify(e,null,2)+`
11
- `),e}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._get(`/settings`),await this.settings}async flush(){let e=await this._getBatchSizeLimitBytes(),t=await this._getBatchSizeLimit();await this.drainAutoBatchQueue({batchSizeLimitBytes:e,batchSizeLimit:t})}_cloneCurrentOTELContext(){let e=go(),t=_o();if(this.langSmithToOTELTranslator!==void 0){let n=e.getActiveSpan();if(n)return e.setSpan(t.active(),n)}}async createRun(e,t){if(!this._filterForSampling([e]).length)return;let n={...this._mergedHeaders,"Content-Type":`application/json`},r=e.project_name;delete e.project_name;let i=await this.prepareRunCreateOrUpdateInputs({session_name:r,...e,start_time:e.start_time??Date.now()});if(this.autoBatchTracing&&i.trace_id!==void 0&&i.dotted_order!==void 0){let e=this._cloneCurrentOTELContext();this.processRunOperation({action:`create`,item:i,otelContext:e,apiKey:t?.apiKey,apiUrl:t?.apiUrl}).catch(console.error);return}let a=hs(i,this.cachedLSEnvVarsForMetadata,this.omitTracedRuntimeInfo);t?.apiKey!==void 0&&(n[`x-api-key`]=t.apiKey),t?.workspaceId!==void 0&&(n[`x-tenant-id`]=t.workspaceId);let o=ls(a,`Creating run with id: ${a.id}`);await this.caller.call(async()=>{let e=await this._fetch(`${t?.apiUrl??this.apiUrl}/runs`,{method:`POST`,headers:n,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await A(e,`create run`,!0),e})}async batchIngestRuns({runCreates:e,runUpdates:t},n){if(e===void 0&&t===void 0)return;let r=await Promise.all(e?.map(e=>this.prepareRunCreateOrUpdateInputs(e))??[]),i=await Promise.all(t?.map(e=>this.prepareRunCreateOrUpdateInputs(e))??[]);if(r.length>0&&i.length>0){let e=r.reduce((e,t)=>(t.id&&(e[t.id]=t),e),{}),t=[];for(let n of i)n.id!==void 0&&e[n.id]?e[n.id]={...e[n.id],...n}:t.push(n);r=Object.values(e),i=t}let a={post:r,patch:i};if(!a.post.length&&!a.patch.length)return;let o={post:[],patch:[]};for(let e of[`post`,`patch`]){let t=e,n=a[t].reverse(),r=n.pop();for(;r!==void 0;)o[t].push(r),r=n.pop()}if(o.post.length>0||o.patch.length>0){let e=o.post.map(e=>e.id).concat(o.patch.map(e=>e.id)).join(`,`);await this._postBatchIngestRuns(ls(o,`Ingesting runs with ids: ${e}`),n)}}async _postBatchIngestRuns(e,t){let n={...this._mergedHeaders,"Content-Type":`application/json`,Accept:`application/json`};t?.apiKey!==void 0&&(n[`x-api-key`]=t.apiKey),await this.batchIngestCaller.callWithOptions({sizeBytes:t?.sizeBytes},async()=>{let r=await this._fetch(`${t?.apiUrl??this.apiUrl}/runs/batch`,{method:`POST`,headers:n,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:e});return await A(r,`batch create run`,!0),r})}async multipartIngestRuns({runCreates:e,runUpdates:t},n){if(e===void 0&&t===void 0)return;let r={},i=[];for(let t of e??[]){let e=await this.prepareRunCreateOrUpdateInputs(t);e.id!==void 0&&e.attachments!==void 0&&(r[e.id]=e.attachments),delete e.attachments,i.push(e)}let a=[];for(let e of t??[])a.push(await this.prepareRunCreateOrUpdateInputs(e));if(i.find(e=>e.trace_id===void 0||e.dotted_order===void 0)!==void 0)throw Error(`Multipart ingest requires "trace_id" and "dotted_order" to be set when creating a run`);if(a.find(e=>e.trace_id===void 0||e.dotted_order===void 0)!==void 0)throw Error(`Multipart ingest requires "trace_id" and "dotted_order" to be set when updating a run`);if(i.length>0&&a.length>0){let e=i.reduce((e,t)=>(t.id&&(e[t.id]=t),e),{}),t=[];for(let n of a)n.id!==void 0&&e[n.id]?e[n.id]={...e[n.id],...n}:t.push(n);i=Object.values(e),a=t}if(i.length===0&&a.length===0)return;let o=[],s=[];for(let[e,t]of[[`post`,i],[`patch`,a]])for(let n of t){let{inputs:t,outputs:i,events:a,extra:c,error:l,serialized:u,attachments:d,...f}=n,p={inputs:t,outputs:i,events:a,extra:c,error:l,serialized:u},m=ls(f,`Serializing for multipart ingestion of run with id: ${f.id}`);s.push({name:`${e}.${f.id}`,payload:new Blob([m],{type:`application/json; length=${m.length}`})});for(let[t,n]of Object.entries(p)){if(n===void 0)continue;let r=ls(n,`Serializing ${t} for multipart ingestion of run with id: ${f.id}`);s.push({name:`${e}.${f.id}.${t}`,payload:new Blob([r],{type:`application/json; length=${r.length}`})})}if(f.id!==void 0){let e=r[f.id];if(e){delete r[f.id];for(let[t,n]of Object.entries(e)){let e,r;if(Array.isArray(n)?[e,r]=n:(e=n.mimeType,r=n.data),t.includes(`.`)){console.warn(`Skipping attachment '${t}' for run ${f.id}: Invalid attachment name. Attachment names must not contain periods ('.'). Please rename the attachment and try again.`);continue}s.push({name:`attachment.${f.id}.${t}`,payload:new Blob([r],{type:`${e}; length=${r.byteLength}`})})}}}o.push(`trace=${f.trace_id},id=${f.id}`)}await this._sendMultipartRequest(s,o.join(`; `),n)}async _createNodeFetchBody(e,t){let n=[];for(let r of e)n.push(new Blob([`--${t}\r\n`])),n.push(new Blob([`Content-Disposition: form-data; name="${r.name}"\r\n`,`Content-Type: ${r.payload.type}\r\n\r\n`])),n.push(r.payload),n.push(new Blob([`\r
12
- `]));return n.push(new Blob([`--${t}--\r\n`])),await new Blob(n).arrayBuffer()}async _createMultipartStream(e,t){let n=new TextEncoder;return new ReadableStream({async start(r){let i=async e=>{typeof e==`string`?r.enqueue(n.encode(e)):r.enqueue(e)};for(let n of e){await i(`--${t}\r\n`),await i(`Content-Disposition: form-data; name="${n.name}"\r\n`),await i(`Content-Type: ${n.payload.type}\r\n\r\n`);let e=n.payload.stream().getReader();try{let t;for(;!(t=await e.read()).done;)r.enqueue(t.value)}finally{e.releaseLock()}await i(`\r
13
- `)}await i(`--${t}--\r\n`),r.close()}})}async _sendMultipartRequest(t,n,r){let i=`----LangSmithFormBoundary`+Math.random().toString(36).slice(2),a=()=>this._createNodeFetchBody(t,i),o=()=>this._createMultipartStream(t,i),s=async e=>this.batchIngestCaller.callWithOptions({sizeBytes:r?.sizeBytes},async()=>{let t=await e(),n={...this._mergedHeaders,"Content-Type":`multipart/form-data; boundary=${i}`};r?.apiKey!==void 0&&(n[`x-api-key`]=r.apiKey);let a=t;r?.useGzip&&typeof t==`object`&&`pipeThrough`in t&&(a=t.pipeThrough(new CompressionStream(`gzip`)),n[`Content-Encoding`]=`gzip`);let o=await this._fetch(`${r?.apiUrl??this.apiUrl}/runs/multipart`,{method:`POST`,headers:n,body:a,duplex:`half`,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await A(o,`Failed to send multipart request`,!0),o});try{let e,t=!1;Ti()&&!this.multipartStreamingDisabled&&Xa()!==`bun`?(t=!0,e=await s(o)):e=await s(a),(!this.multipartStreamingDisabled||t)&&e.status===422&&(r?.apiUrl??this.apiUrl)!==ws&&(console.warn(`Streaming multipart upload to ${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,e=await s(a))}catch(r){if(qo(r))throw r;if(console.warn(`${r.message.trim()}\n\nContext: ${n}`),this.failedTracesDir){let n=await this._createNodeFetchBody(t,i).catch(()=>null);n&&await e._writeTraceToFallbackDir(this.failedTracesDir,n,{"Content-Type":`multipart/form-data; boundary=${i}`},`runs/multipart`,this.failedTracesMaxBytes)}}}async updateRun(e,t,n){k(e),t.inputs&&=await this.processInputs(t.inputs),t.outputs&&=await this.processOutputs(t.outputs),t.extra!=null&&`metadata`in t.extra&&(t.extra={...t.extra,metadata:await this.processMetadata(t.extra.metadata)}),t.events&&=this._filterNewTokenEvents(t.events);let r={...t,id:e};if(!this._filterForSampling([r],!0).length)return;if(this.autoBatchTracing&&r.trace_id!==void 0&&r.dotted_order!==void 0){let e=this._cloneCurrentOTELContext();if(t.end_time!==void 0&&r.parent_run_id===void 0&&this.blockOnRootRunFinalization&&!this.manualFlushMode){await this.processRunOperation({action:`update`,item:r,otelContext:e,apiKey:n?.apiKey,apiUrl:n?.apiUrl}).catch(console.error);return}else this.processRunOperation({action:`update`,item:r,otelContext:e,apiKey:n?.apiKey,apiUrl:n?.apiUrl}).catch(console.error);return}let i={...this._mergedHeaders,"Content-Type":`application/json`};n?.apiKey!==void 0&&(i[`x-api-key`]=n.apiKey),n?.workspaceId!==void 0&&(i[`x-tenant-id`]=n.workspaceId);let a=ls(t,`Serializing payload to update run with id: ${e}`);await this.caller.call(async()=>{let t=await this._fetch(`${n?.apiUrl??this.apiUrl}/runs/${e}`,{method:`PATCH`,headers:i,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await A(t,`update run`,!0),t})}async readRun(e,{loadChildRuns:t}={loadChildRuns:!1}){k(e);let n=ms(await this._get(`/runs/${e}`));return t&&(n=await this._loadChildRuns(n)),n}async getRunUrl({runId:e,run:t,projectOpts:n}){if(t!==void 0){let e;e=t.session_id?t.session_id:n?.projectName?(await this.readProject({projectName:n?.projectName})).id:n?.projectId?n?.projectId:(await this.readProject({projectName:no(`PROJECT`)||`default`})).id;let r=await this._getTenantId();return`${this.getHostUrl()}/o/${r}/projects/p/${e}/r/${t.id}?poll=true`}else if(e!==void 0){let t=await this.readRun(e);if(!t.app_path)throw Error(`Run ${e} has no app_path`);return`${this.getHostUrl()}${t.app_path}`}else throw Error(`Must provide either runId or run`)}async _loadChildRuns(e){let t=await vs(this.listRuns({isRoot:!1,projectId:e.session_id,traceId:e.trace_id})),n={},r={};t.sort((e,t)=>(e?.dotted_order??``).localeCompare(t?.dotted_order??``));for(let i of t){if(i.parent_run_id===null||i.parent_run_id===void 0)throw Error(`Child run ${i.id} has no parent`);i.dotted_order?.startsWith(e.dotted_order??``)&&i.id!==e.id&&(i.parent_run_id in n||(n[i.parent_run_id]=[]),n[i.parent_run_id].push(i),r[i.id]=i)}e.child_runs=n[e.id]||[];for(let t in n)t!==e.id&&(r[t].child_runs=n[t]);return e}async*listRuns(e){let{projectId:t,projectName:n,parentRunId:r,traceId:i,referenceExampleId:a,startTime:o,executionOrder:s,isRoot:c,runType:l,error:u,id:d,query:f,filter:p,traceFilter:m,treeFilter:h,limit:g,select:_,order:v}=e,y=[];if(t&&(y=Array.isArray(t)?t:[t]),n){let e=Array.isArray(n)?n:[n],t=await Promise.all(e.map(e=>this.readProject({projectName:e}).then(e=>e.id)));y.push(...t)}let b={session:y.length?y:null,run_type:l,reference_example:a,query:f,filter:p,trace_filter:m,tree_filter:h,execution_order:s,parent_run:r,start_time:o?o.toISOString():null,error:u,id:d,limit:g,trace:i,select:_||`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`.split(`.`),is_root:c,order:v};b.select.includes(`child_run_ids`)&&ki(`Deprecated: 'child_run_ids' in the listRuns select parameter is deprecated and will be removed in a future version.`);let ee=0;for await(let e of this._getCursorPaginatedList(`/runs/query`,b)){let t=e.map(ms);if(g){if(ee>=g)break;if(t.length+ee>g){yield*t.slice(0,g-ee);break}ee+=t.length,yield*t}else yield*t}}async*listGroupRuns(e){let{projectId:t,projectName:n,groupBy:r,filter:i,startTime:a,endTime:o,limit:s,offset:c}=e,l={session_id:t||(await this.readProject({projectName:n})).id,group_by:r,filter:i,start_time:a?a.toISOString():null,end_time:o?o.toISOString():null,limit:Number(s)||100},u=Number(c)||0,d=`/runs/group`,f=`${this.apiUrl}${d}`;for(;;){let e={...l,offset:u},t=Object.fromEntries(Object.entries(e).filter(([e,t])=>t!==void 0)),n=JSON.stringify(t),{groups:r,total:i}=await(await this.caller.call(async()=>{let e=await this._fetch(f,{method:`POST`,headers:{...this._mergedHeaders,"Content-Type":`application/json`},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:n});return await A(e,`Failed to fetch ${d}`),e})).json();if(r.length===0)break;for(let e of r)yield e;if(u+=r.length,u>=i)break}}async*readThread(e){let{threadId:t,projectId:n,projectName:r,isRoot:i=!0,limit:a,filter:o,order:s=`asc`}=e;if(!n&&!r)throw Error(`threadId requires projectId or projectName`);let c=`eq(thread_id, ${JSON.stringify(t)})`,l=o?`and(${c}, ${o})`:c;yield*this.listRuns({projectId:n??void 0,projectName:r??void 0,isRoot:i,limit:a,filter:l,order:s})}async listThreads(e){let{projectId:t,projectName:n,limit:r,offset:i=0,filter:a,startTime:o,isRoot:s=!0}=e;if(!t&&!n)throw Error(`Either projectId or projectName must be provided`);if(t&&n)throw Error(`Provide exactly one of projectId or projectName`);let c=t??(await this.readProject({projectName:n})).id,l=o??new Date(Date.now()-1440*60*1e3),u={session:[c],is_root:s,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()};a!=null&&(u.filter=a);let d=new Map;for await(let e of this._getCursorPaginatedList(`/runs/query`,u))for(let t of e){let e=ms(t),n=e.thread_id;if(n){let t=d.get(n)??[];t.push(e),d.set(n,t)}}let f=[];for(let[e,t]of d.entries()){t.sort((e,t)=>{let n=e,r=t,i=n.start_time??``,a=r.start_time??``;if(i!==a)return i.localeCompare(a);let o=n.dotted_order??``,s=r.dotted_order??``;return o.localeCompare(s)});let n=[...t.map(e=>e.start_time).filter(Boolean)].sort(),r=n.length?n[0]:``,i=n.length?n[n.length-1]:``;f.push({thread_id:e,runs:t,count:t.length,filter:``,total_tokens:0,total_cost:null,min_start_time:r,max_start_time:i,latency_p50:0,latency_p99:0,feedback_stats:null,first_inputs:``,last_outputs:``,last_error:null})}f.sort((e,t)=>{let n=e.max_start_time??``;return(t.max_start_time??``).localeCompare(n)});let p=i>0?f.slice(i):f;return r===void 0?p:p.slice(0,r)}async getRunStats({id:e,trace:t,parentRun:n,runType:r,projectNames:i,projectIds:a,referenceExampleIds:o,startTime:s,endTime:c,error:l,query:u,filter:d,traceFilter:f,treeFilter:p,isRoot:m,dataSourceType:h}){let g=a||[];i&&(g=[...a||[],...await Promise.all(i.map(e=>this.readProject({projectName:e}).then(e=>e.id)))]);let _=Object.fromEntries(Object.entries({id:e,trace:t,parent_run:n,run_type:r,session:g,reference_example:o,start_time:s,end_time:c,error:l,query:u,filter:d,trace_filter:f,tree_filter:p,is_root:m,data_source_type:h}).filter(([e,t])=>t!==void 0)),v=JSON.stringify(_);return await(await this.caller.call(async()=>{let e=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:v});return await A(e,`get run stats`),e})).json()}async shareRun(e,{shareId:t}={}){let n={run_id:e,share_token:t||Pr()};k(e);let r=JSON.stringify(n),i=await(await this.caller.call(async()=>{let t=await this._fetch(`${this.apiUrl}/runs/${e}/share`,{method:`PUT`,headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:r});return await A(t,`share run`),t})).json();if(i===null||!(`share_token`in i))throw Error(`Invalid response from server`);return`${this.getHostUrl()}/public/${i.share_token}/r`}async unshareRun(e){k(e),await this.caller.call(async()=>{let t=await this._fetch(`${this.apiUrl}/runs/${e}/share`,{method:`DELETE`,headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await A(t,`unshare run`,!0),t})}async readRunSharedLink(e){k(e);let t=await(await this.caller.call(async()=>{let t=await this._fetch(`${this.apiUrl}/runs/${e}/share`,{method:`GET`,headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await A(t,`read run shared link`),t})).json();if(!(t===null||!(`share_token`in t)))return`${this.getHostUrl()}/public/${t.share_token}/r`}async listSharedRuns(e,{runIds:t}={}){let n=new URLSearchParams({share_token:e});if(t!==void 0)for(let e of t)n.append(`id`,e);return k(e),(await(await this.caller.call(async()=>{let t=await this._fetch(`${this.apiUrl}/public/${e}/runs${n}`,{method:`GET`,headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await A(t,`list shared runs`),t})).json()).map(ms)}async readDatasetSharedSchema(e,t){if(!e&&!t)throw Error(`Either datasetId or datasetName must be given`);e||=(await this.readDataset({datasetName:t})).id,k(e);let n=await(await this.caller.call(async()=>{let t=await this._fetch(`${this.apiUrl}/datasets/${e}/share`,{method:`GET`,headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await A(t,`read dataset shared schema`),t})).json();return n.url=`${this.getHostUrl()}/public/${n.share_token}/d`,n}async shareDataset(e,t){if(!e&&!t)throw Error(`Either datasetId or datasetName must be given`);e||=(await this.readDataset({datasetName:t})).id;let n={dataset_id:e};k(e);let r=JSON.stringify(n),i=await(await this.caller.call(async()=>{let t=await this._fetch(`${this.apiUrl}/datasets/${e}/share`,{method:`PUT`,headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:r});return await A(t,`share dataset`),t})).json();return i.url=`${this.getHostUrl()}/public/${i.share_token}/d`,i}async unshareDataset(e){k(e),await this.caller.call(async()=>{let t=await this._fetch(`${this.apiUrl}/datasets/${e}/share`,{method:`DELETE`,headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await A(t,`unshare dataset`,!0),t})}async readSharedDataset(e){return k(e),await(await this.caller.call(async()=>{let t=await this._fetch(`${this.apiUrl}/public/${e}/datasets`,{method:`GET`,headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await A(t,`read shared dataset`),t})).json()}async listSharedExamples(e,t){let n={};t?.exampleIds&&(n.id=t.exampleIds);let r=new URLSearchParams;Object.entries(n).forEach(([e,t])=>{Array.isArray(t)?t.forEach(t=>r.append(e,t)):r.append(e,t)});let i=await this.caller.call(async()=>{let t=await this._fetch(`${this.apiUrl}/public/${e}/examples?${r.toString()}`,{method:`GET`,headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await A(t,`list shared examples`),t}),a=await i.json();if(!i.ok)throw`detail`in a?Error(`Failed to list shared examples.\nStatus: ${i.status}\nMessage: ${Array.isArray(a.detail)?a.detail.join(`
14
- `):`Unspecified error`}`):Error(`Failed to list shared examples: ${i.status} ${i.statusText}`);return a.map(e=>({...e,_hostUrl:this.getHostUrl()}))}async createProject({projectName:e,description:t=null,metadata:n=null,upsert:r=!1,projectExtra:i=null,referenceDatasetId:a=null}){let o=r?`?upsert=true`:``,s=`${this.apiUrl}/sessions${o}`,c=i||{};n&&(c.metadata=n);let l={name:e,extra:c,description:t};a!==null&&(l.reference_dataset_id=a);let u=JSON.stringify(l);return await(await this.caller.call(async()=>{let e=await this._fetch(s,{method:`POST`,headers:{...this._mergedHeaders,"Content-Type":`application/json`},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:u});return await A(e,`create project`),e})).json()}async updateProject(e,{name:t=null,description:n=null,metadata:r=null,projectExtra:i=null,endTime:a=null}){let o=`${this.apiUrl}/sessions/${e}`,s=i;r&&(s={...s||{},metadata:r});let c=JSON.stringify({name:t,extra:s,description:n,end_time:a?new Date(a).toISOString():null});return await(await this.caller.call(async()=>{let e=await this._fetch(o,{method:`PATCH`,headers:{...this._mergedHeaders,"Content-Type":`application/json`},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await A(e,`update project`),e})).json()}async hasProject({projectId:e,projectName:t}){let n=`/sessions`,r=new URLSearchParams;if(e!==void 0&&t!==void 0)throw Error(`Must provide either projectName or projectId, not both`);if(e!==void 0)k(e),n+=`/${e}`;else if(t!==void 0)r.append(`name`,t);else throw Error(`Must provide projectName or projectId`);let i=await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}${n}?${r}`,{method:`GET`,headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await A(e,`has project`),e});try{let e=await i.json();return i.ok?Array.isArray(e)?e.length>0:!0:!1}catch{return!1}}async readProject({projectId:e,projectName:t,includeStats:n}){let r=`/sessions`,i=new URLSearchParams;if(e!==void 0&&t!==void 0)throw Error(`Must provide either projectName or projectId, not both`);if(e!==void 0)k(e),r+=`/${e}`;else if(t!==void 0)i.append(`name`,t);else throw Error(`Must provide projectName or projectId`);n!==void 0&&i.append(`include_stats`,n.toString());let a=await this._get(r,i),o;if(Array.isArray(a)){if(a.length===0)throw Error(`Project[id=${e}, name=${t}] not found`);o=a[0]}else o=a;return o}async getProjectUrl({projectId:e,projectName:t}){if(e===void 0&&t===void 0)throw Error(`Must provide either projectName or projectId`);let n=await this.readProject({projectId:e,projectName:t}),r=await this._getTenantId();return`${this.getHostUrl()}/o/${r}/projects/p/${n.id}`}async getDatasetUrl({datasetId:e,datasetName:t}){if(e===void 0&&t===void 0)throw Error(`Must provide either datasetName or datasetId`);let n=await this.readDataset({datasetId:e,datasetName:t}),r=await this._getTenantId();return`${this.getHostUrl()}/o/${r}/datasets/${n.id}`}async _getTenantId(){if(this._tenantId!==null)return this._tenantId;let e=new URLSearchParams({limit:`1`});for await(let t of this._getPaginated(`/sessions`,e))return this._tenantId=t[0].tenant_id,t[0].tenant_id;throw Error(`No projects found to resolve tenant.`)}async*listProjects({projectIds:e,name:t,nameContains:n,referenceDatasetId:r,referenceDatasetName:i,includeStats:a,datasetVersion:o,referenceFree:s,metadata:c}={}){let l=new URLSearchParams;if(e!==void 0)for(let t of e)l.append(`id`,t);if(t!==void 0&&l.append(`name`,t),n!==void 0&&l.append(`name_contains`,n),r!==void 0)l.append(`reference_dataset`,r);else if(i!==void 0){let e=await this.readDataset({datasetName:i});l.append(`reference_dataset`,e.id)}a!==void 0&&l.append(`include_stats`,a.toString()),o!==void 0&&l.append(`dataset_version`,o),s!==void 0&&l.append(`reference_free`,s.toString()),c!==void 0&&l.append(`metadata`,JSON.stringify(c));for await(let e of this._getPaginated(`/sessions`,l))yield*e}async deleteProject({projectId:e,projectName:t}){let n;if(e===void 0&&t===void 0)throw Error(`Must provide projectName or projectId`);if(e!==void 0&&t!==void 0)throw Error(`Must provide either projectName or projectId, not both`);n=e===void 0?(await this.readProject({projectName:t})).id:e,k(n),await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/sessions/${n}`,{method:`DELETE`,headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await A(e,`delete session ${n} (${t})`,!0),e})}async uploadCsv({csvFile:e,fileName:t,inputKeys:n,outputKeys:r,description:i,dataType:a,name:o}){let s=`${this.apiUrl}/datasets/upload`,c=new FormData,l=new Blob([e],{type:`text/csv`});return c.append(`file`,l,t),n.forEach(e=>{c.append(`input_keys`,e)}),r.forEach(e=>{c.append(`output_keys`,e)}),i&&c.append(`description`,i),a&&c.append(`data_type`,a),o&&c.append(`name`,o),await(await this.caller.call(async()=>{let e=await this._fetch(s,{method:`POST`,headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await A(e,`upload CSV`),e})).json()}async createDataset(e,{description:t,dataType:n,inputsSchema:r,outputsSchema:i,metadata:a}={}){let o={name:e,description:t,extra:{source:`sdk`,...a?{metadata:a}:{}}};n&&(o.data_type=n),r&&(o.inputs_schema_definition=r),i&&(o.outputs_schema_definition=i);let s=JSON.stringify(o);return await(await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/datasets`,{method:`POST`,headers:{...this._mergedHeaders,"Content-Type":`application/json`},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await A(e,`create dataset`),e})).json()}async readDataset({datasetId:e,datasetName:t}){let n=`/datasets`,r=new URLSearchParams({limit:`1`});if(e&&t)throw Error(`Must provide either datasetName or datasetId, not both`);if(e)k(e),n+=`/${e}`;else if(t)r.append(`name`,t);else throw Error(`Must provide datasetName or datasetId`);let i=await this._get(n,r),a;if(Array.isArray(i)){if(i.length===0)throw Error(`Dataset[id=${e}, name=${t}] not found`);a=i[0]}else a=i;return a}async hasDataset({datasetId:e,datasetName:t}){try{return await this.readDataset({datasetId:e,datasetName:t}),!0}catch(e){if(e instanceof Error&&e.message.toLocaleLowerCase().includes(`not found`))return!1;throw e}}async diffDatasetVersions({datasetId:e,datasetName:t,fromVersion:n,toVersion:r}){let i=e;if(i===void 0&&t===void 0)throw Error(`Must provide either datasetName or datasetId`);if(i!==void 0&&t!==void 0)throw Error(`Must provide either datasetName or datasetId, not both`);i===void 0&&(i=(await this.readDataset({datasetName:t})).id);let a=new URLSearchParams({from_version:typeof n==`string`?n:n.toISOString(),to_version:typeof r==`string`?r:r.toISOString()});return await this._get(`/datasets/${i}/versions/diff`,a)}async readDatasetOpenaiFinetuning({datasetId:e,datasetName:t}){if(e===void 0)if(t!==void 0)e=(await this.readDataset({datasetName:t})).id;else throw Error(`Must provide either datasetName or datasetId`);return(await(await this._getResponse(`/datasets/${e}/openai_ft`)).text()).trim().split(`
15
- `).map(e=>JSON.parse(e))}async*listDatasets({limit:e=100,offset:t=0,datasetIds:n,datasetName:r,datasetNameContains:i,metadata:a}={}){let o=new URLSearchParams({limit:e.toString(),offset:t.toString()});if(n!==void 0)for(let e of n)o.append(`id`,e);r!==void 0&&o.append(`name`,r),i!==void 0&&o.append(`name_contains`,i),a!==void 0&&o.append(`metadata`,JSON.stringify(a));for await(let e of this._getPaginated(`/datasets`,o))yield*e}async updateDataset(e){let{datasetId:t,datasetName:n,...r}=e;if(!t&&!n)throw Error(`Must provide either datasetName or datasetId`);let i=t??(await this.readDataset({datasetName:n})).id;k(i);let a=JSON.stringify(r);return await(await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/datasets/${i}`,{method:`PATCH`,headers:{...this._mergedHeaders,"Content-Type":`application/json`},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await A(e,`update dataset`),e})).json()}async updateDatasetTag(e){let{datasetId:t,datasetName:n,asOf:r,tag:i}=e;if(!t&&!n)throw Error(`Must provide either datasetName or datasetId`);let a=t??(await this.readDataset({datasetName:n})).id;k(a);let o=JSON.stringify({as_of:typeof r==`string`?r:r.toISOString(),tag:i});await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/datasets/${a}/tags`,{method:`PUT`,headers:{...this._mergedHeaders,"Content-Type":`application/json`},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await A(e,`update dataset tags`,!0),e})}async deleteDataset({datasetId:e,datasetName:t}){let n=`/datasets`,r=e;if(e!==void 0&&t!==void 0)throw Error(`Must provide either datasetName or datasetId, not both`);if(t!==void 0&&(r=(await this.readDataset({datasetName:t})).id),r!==void 0)k(r),n+=`/${r}`;else throw Error(`Must provide datasetName or datasetId`);await this.caller.call(async()=>{let e=await this._fetch(this.apiUrl+n,{method:`DELETE`,headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await A(e,`delete ${n}`,!0),e})}async createExample(e,t,n){if(Ds(e)&&(t!==void 0||n!==void 0))throw Error(`Cannot provide outputs or options when using ExampleCreate object`);let r=t?n?.datasetId:e.dataset_id,i=t?n?.datasetName:e.dataset_name;if(r===void 0&&i===void 0)throw Error(`Must provide either datasetName or datasetId`);if(r!==void 0&&i!==void 0)throw Error(`Must provide either datasetName or datasetId, not both`);r===void 0&&(r=(await this.readDataset({datasetName:i})).id);let a=(t?n?.createdAt:e.created_at)||new Date,o;o=Ds(e)?e:{inputs:e,outputs:t,created_at:a?.toISOString(),id:n?.exampleId,metadata:n?.metadata,split:n?.split,source_run_id:n?.sourceRunId,use_source_run_io:n?.useSourceRunIO,use_source_run_attachments:n?.useSourceRunAttachments,attachments:n?.attachments};let s=await this._uploadExamplesMultipart(r,[o]);return await this.readExample(s.example_ids?.[0]??Pr())}async createExamples(e){if(Array.isArray(e)){if(e.length===0)return[];let t=e,n=t[0].dataset_id,r=t[0].dataset_name;if(n===void 0&&r===void 0)throw Error(`Must provide either datasetName or datasetId`);if(n!==void 0&&r!==void 0)throw Error(`Must provide either datasetName or datasetId, not both`);n===void 0&&(n=(await this.readDataset({datasetName:r})).id);let i=await this._uploadExamplesMultipart(n,t);return await Promise.all(i.example_ids.map(e=>this.readExample(e)))}let{inputs:t,outputs:n,metadata:r,splits:i,sourceRunIds:a,useSourceRunIOs:o,useSourceRunAttachments:s,attachments:c,exampleIds:l,datasetId:u,datasetName:d}=e;if(t===void 0)throw Error(`Must provide inputs when using legacy parameters`);let f=u,p=d;if(f===void 0&&p===void 0)throw Error(`Must provide either datasetName or datasetId`);if(f!==void 0&&p!==void 0)throw Error(`Must provide either datasetName or datasetId, not both`);f===void 0&&(f=(await this.readDataset({datasetName:p})).id);let m=t.map((e,t)=>({dataset_id:f,inputs:e,outputs:n?.[t],metadata:r?.[t],split:i?.[t],id:l?.[t],attachments:c?.[t],source_run_id:a?.[t],use_source_run_io:o?.[t],use_source_run_attachments:s?.[t]})),h=await this._uploadExamplesMultipart(f,m);return await Promise.all(h.example_ids.map(e=>this.readExample(e)))}async createLLMExample(e,t,n){return this.createExample({input:e},{output:t},n)}async createChatExample(e,t,n){let r=e.map(e=>Ho(e)?Uo(e):e),i=Ho(t)?Uo(t):t;return this.createExample({input:r},{output:i},n)}async readExample(e){k(e);let t=`/examples/${e}`,{attachment_urls:n,...r}=await this._get(t),i=r;return n&&(i.attachments=Object.entries(n).reduce((e,[t,n])=>(e[t.slice(11)]={presigned_url:n.presigned_url,mime_type:n.mime_type},e),{})),i}async*listExamples({datasetId:e,datasetName:t,exampleIds:n,asOf:r,splits:i,inlineS3Urls:a,metadata:o,limit:s,offset:c,filter:l,includeAttachments:u}={}){let d;if(e!==void 0&&t!==void 0)throw Error(`Must provide either datasetName or datasetId, not both`);if(e!==void 0)d=e;else if(t!==void 0)d=(await this.readDataset({datasetName:t})).id;else throw Error(`Must provide a datasetName or datasetId`);let f=new URLSearchParams({dataset:d}),p=r?typeof r==`string`?r:r?.toISOString():void 0;p&&f.append(`as_of`,p);let m=a??!0;if(f.append(`inline_s3_urls`,m.toString()),n!==void 0)for(let e of n)f.append(`id`,e);if(i!==void 0)for(let e of i)f.append(`splits`,e);if(o!==void 0){let e=JSON.stringify(o);f.append(`metadata`,e)}s!==void 0&&f.append(`limit`,s.toString()),c!==void 0&&f.append(`offset`,c.toString()),l!==void 0&&f.append(`filter`,l),u===!0&&[`attachment_urls`,`outputs`,`metadata`].forEach(e=>f.append(`select`,e));let h=0;for await(let e of this._getPaginated(`/examples`,f)){for(let t of e){let{attachment_urls:e,...n}=t,r=n;e&&(r.attachments=Object.entries(e).reduce((e,[t,n])=>(e[t.slice(11)]={presigned_url:n.presigned_url,mime_type:n.mime_type||void 0},e),{})),yield r,h++}if(s!==void 0&&h>=s)break}}async deleteExample(e){k(e);let t=`/examples/${e}`;await this.caller.call(async()=>{let e=await this._fetch(this.apiUrl+t,{method:`DELETE`,headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await A(e,`delete ${t}`,!0),e})}async deleteExamples(e,t){if(e.forEach(e=>k(e)),t?.hardDelete){let t=this._getPlatformEndpointPath(`datasets/examples/delete`);await this.caller.call(async()=>{let n=await this._fetch(`${this.apiUrl}${t}`,{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 A(n,`hard delete examples`,!0),n})}else{let t=new URLSearchParams;e.forEach(e=>t.append(`example_ids`,e)),await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/examples?${t.toString()}`,{method:`DELETE`,headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await A(e,`delete examples`,!0),e})}}async updateExample(e,t){let n;n=t?e:e.id,k(n);let r;r=t?{id:n,...t}:e;let i;return i=r.dataset_id===void 0?(await this.readExample(n)).dataset_id:r.dataset_id,this._updateExamplesMultipart(i,[r])}async updateExamples(e){let t;return t=e[0].dataset_id===void 0?(await this.readExample(e[0].id)).dataset_id:e[0].dataset_id,this._updateExamplesMultipart(t,e)}async readDatasetVersion({datasetId:e,datasetName:t,asOf:n,tag:r}){let i;if(i=e||(await this.readDataset({datasetName:t})).id,k(i),n&&r||!n&&!r)throw Error(`Exactly one of asOf and tag must be specified.`);let a=new URLSearchParams;return n!==void 0&&a.append(`as_of`,typeof n==`string`?n:n.toISOString()),r!==void 0&&a.append(`tag`,r),await(await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/datasets/${i}/version?${a.toString()}`,{method:`GET`,headers:{...this._mergedHeaders},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await A(e,`read dataset version`),e})).json()}async listDatasetSplits({datasetId:e,datasetName:t,asOf:n}){let r;if(e===void 0&&t===void 0)throw Error(`Must provide dataset name or ID`);if(e!==void 0&&t!==void 0)throw Error(`Must provide either datasetName or datasetId, not both`);r=e===void 0?(await this.readDataset({datasetName:t})).id:e,k(r);let i=new URLSearchParams,a=n?typeof n==`string`?n:n?.toISOString():void 0;return a&&i.append(`as_of`,a),await this._get(`/datasets/${r}/splits`,i)}async updateDatasetSplits({datasetId:e,datasetName:t,splitName:n,exampleIds:r,remove:i=!1}){let a;if(e===void 0&&t===void 0)throw Error(`Must provide dataset name or ID`);if(e!==void 0&&t!==void 0)throw Error(`Must provide either datasetName or datasetId, not both`);a=e===void 0?(await this.readDataset({datasetName:t})).id:e,k(a);let o={split_name:n,examples:r.map(e=>(k(e),e)),remove:i},s=JSON.stringify(o);await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/datasets/${a}/splits`,{method:`PUT`,headers:{...this._mergedHeaders,"Content-Type":`application/json`},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await A(e,`update dataset splits`,!0),e})}async createFeedback(e,t,{score:n,value:r,correction:i,comment:a,sourceInfo:o,feedbackSourceType:s=`api`,sourceRunId:c,feedbackId:l,feedbackConfig:u,projectId:d,comparativeExperimentId:f,sessionId:p,startTime:m}){if(!e&&!d)throw Error(`One of runId or projectId must be provided`);if(e&&d)throw Error(`Only one of runId or projectId can be provided`);let h={type:s??`api`,metadata:o??{}};c!==void 0&&h?.metadata!==void 0&&!h.metadata.__run&&(h.metadata.__run={run_id:c}),h?.metadata!==void 0&&h.metadata.__run?.run_id!==void 0&&k(h.metadata.__run.run_id);let g={id:l??Hr(),run_id:e,key:t,score:xs(n),value:r,correction:i,comment:a,feedback_source:h,comparative_experiment_id:f,feedbackConfig:u,session_id:p??d,start_time:m},_=JSON.stringify(g),v=`${this.apiUrl}/feedback`;return await this.caller.call(async()=>{let e=await this._fetch(v,{method:`POST`,headers:{...this._mergedHeaders,"Content-Type":`application/json`},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:_});return await A(e,`create feedback`,!0),e}),g}async updateFeedback(e,{score:t,value:n,correction:r,comment:i}){let a={};t!=null&&(a.score=xs(t)),n!=null&&(a.value=n),r!=null&&(a.correction=r),i!=null&&(a.comment=i),k(e);let o=JSON.stringify(a);await this.caller.call(async()=>{let t=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 A(t,`update feedback`,!0),t})}async readFeedback(e){k(e);let t=`/feedback/${e}`;return await this._get(t)}async deleteFeedback(e){k(e);let t=`/feedback/${e}`;await this.caller.call(async()=>{let e=await this._fetch(this.apiUrl+t,{method:`DELETE`,headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await A(e,`delete ${t}`,!0),e})}async*listFeedback({runIds:e,feedbackKeys:t,feedbackSourceTypes:n}={}){let r=new URLSearchParams;if(e)for(let t of e)k(t),r.append(`run`,t);if(t)for(let e of t)r.append(`key`,e);if(n)for(let e of n)r.append(`source`,e);for await(let e of this._getPaginated(`/feedback`,r))yield*e}async createPresignedFeedbackToken(e,t,{expiration:n,feedbackConfig:r}={}){let i={run_id:e,feedback_key:t,feedback_config:r};n?typeof n==`string`?i.expires_at=n:(n?.hours||n?.minutes||n?.days)&&(i.expires_in=n):i.expires_in={hours:3};let a=JSON.stringify(i);return await(await this.caller.call(async()=>{let e=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:a});return await A(e,`create presigned feedback token`),e})).json()}async createComparativeExperiment({name:e,experimentIds:t,referenceDatasetId:n,createdAt:r,description:i,metadata:a,id:o}){if(t.length===0)throw Error(`At least one experiment is required`);if(n||=(await this.readProject({projectId:t[0]})).reference_dataset_id,!n==null)throw Error(`A reference dataset is required`);let s={id:o,name:e,experiment_ids:t,reference_dataset_id:n,description:i,created_at:(r??new Date)?.toISOString(),extra:{}};a&&(s.extra.metadata=a);let c=JSON.stringify(s);return(await this.caller.call(async()=>{let e=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:c});return await A(e,`create comparative experiment`),e})).json()}async*listPresignedFeedbackTokens(e){k(e);let t=new URLSearchParams({run_id:e});for await(let e of this._getPaginated(`/feedback/tokens`,t))yield*e}_selectEvalResults(e){let t;return t=`results`in e?e.results:Array.isArray(e)?e:[e],t}async _logEvaluationFeedback(e,t,n){let r=this._selectEvalResults(e),i=[];for(let e of r){let r=n||{};e.evaluatorInfo&&(r={...e.evaluatorInfo,...r});let a=null;e.targetRunId?a=e.targetRunId:t&&(a=t.id),i.push(await this.createFeedback(a,e.key,{score:e.score,value:e.value,comment:e.comment,correction:e.correction,sourceInfo:r,sourceRunId:e.sourceRunId,feedbackConfig:e.feedbackConfig,feedbackSourceType:`model`,sessionId:t?.session_id,startTime:t?.start_time}))}return[r,i]}async logEvaluationFeedback(e,t,n){let[r]=await this._logEvaluationFeedback(e,t,n);return r}async createFeedbackConfig(e){let{feedbackKey:t,feedbackConfig:n,isLowerScoreBetter:r=!1}=e,i={feedback_key:t,feedback_config:n,is_lower_score_better:r};return(await this.caller.call(async()=>{let e=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(i)});return await A(e,`create feedback config`),e})).json()}async*listFeedbackConfigs(e={}){let{feedbackKeys:t,nameContains:n,limit:r}=e,i=new URLSearchParams;t&&t.forEach(e=>{i.append(`key`,e)}),n&&i.append(`name_contains`,n),i.append(`limit`,(r===void 0?100:Math.min(r,100)).toString());let a=0;for await(let e of this._getPaginated(`/feedback-configs`,i))if(yield*e,a+=e.length,r!==void 0&&a>=r)break}async updateFeedbackConfig(e,t={}){let{feedbackConfig:n,isLowerScoreBetter:r}=t,i={feedback_key:e};return n!==void 0&&(i.feedback_config=n),r!==void 0&&(i.is_lower_score_better=r),(await this.caller.call(async()=>{let e=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(i)});return await A(e,`update feedback config`),e})).json()}async deleteFeedbackConfig(e){let t=new URLSearchParams({feedback_key:e});await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/feedback-configs?${t}`,{method:`DELETE`,headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await A(e,`delete feedback config`,!0),e})}async*listAnnotationQueues(e={}){let{queueIds:t,name:n,nameContains:r,limit:i}=e,a=new URLSearchParams;t&&t.forEach((e,t)=>{k(e,`queueIds[${t}]`),a.append(`ids`,e)}),n&&a.append(`name`,n),r&&a.append(`name_contains`,r),a.append(`limit`,(i===void 0?100:Math.min(i,100)).toString());let o=0;for await(let e of this._getPaginated(`/annotation-queues`,a))if(yield*e,o++,i!==void 0&&o>=i)break}async createAnnotationQueue(e){let{name:t,description:n,queueId:r,rubricInstructions:i,rubricItems:a}=e,o={name:t,description:n,id:r||Pr(),rubric_instructions:i,rubric_items:a},s=JSON.stringify(Object.fromEntries(Object.entries(o).filter(([e,t])=>t!==void 0)));return(await this.caller.call(async()=>{let e=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:s});return await A(e,`create annotation queue`),e})).json()}async readAnnotationQueue(e){return(await this.caller.call(async()=>{let t=await this._fetch(`${this.apiUrl}/annotation-queues/${k(e,`queueId`)}`,{method:`GET`,headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await A(t,`read annotation queue`),t})).json()}async updateAnnotationQueue(e,t){let{name:n,description:r,rubricInstructions:i,rubricItems:a}=t,o={};n!==void 0&&(o.name=n),r!==void 0&&(o.description=r),i!==void 0&&(o.rubric_instructions=i),a!==void 0&&(o.rubric_items=a);let s=JSON.stringify(o);await this.caller.call(async()=>{let t=await this._fetch(`${this.apiUrl}/annotation-queues/${k(e,`queueId`)}`,{method:`PATCH`,headers:{...this._mergedHeaders,"Content-Type":`application/json`},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await A(t,`update annotation queue`,!0),t})}async deleteAnnotationQueue(e){await this.caller.call(async()=>{let t=await this._fetch(`${this.apiUrl}/annotation-queues/${k(e,`queueId`)}`,{method:`DELETE`,headers:{...this._mergedHeaders,Accept:`application/json`},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await A(t,`delete annotation queue`,!0),t})}async addRunsToAnnotationQueue(e,t){let n=JSON.stringify(t.map((e,t)=>k(e,`runIds[${t}]`).toString()));await this.caller.call(async()=>{let t=await this._fetch(`${this.apiUrl}/annotation-queues/${k(e,`queueId`)}/runs`,{method:`POST`,headers:{...this._mergedHeaders,"Content-Type":`application/json`},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:n});return await A(t,`add runs to annotation queue`,!0),t})}async getRunFromAnnotationQueue(e,t){let n=`/annotation-queues/${k(e,`queueId`)}/run`;return ms(await(await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}${n}/${t}`,{method:`GET`,headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await A(e,`get run from annotation queue`),e})).json())}async deleteRunFromAnnotationQueue(e,t){await this.caller.call(async()=>{let n=await this._fetch(`${this.apiUrl}/annotation-queues/${k(e,`queueId`)}/runs/${k(t,`queueRunId`)}`,{method:`DELETE`,headers:{...this._mergedHeaders,Accept:`application/json`},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await A(n,`delete run from annotation queue`,!0),n})}async getSizeFromAnnotationQueue(e){return(await this.caller.call(async()=>{let t=await this._fetch(`${this.apiUrl}/annotation-queues/${k(e,`queueId`)}/size`,{method:`GET`,headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await A(t,`get size from annotation queue`),t})).json()}async _currentTenantIsOwner(e){let t=await this._getSettings();return e==`-`||t.tenant_handle===e}async _ownerConflictError(e,t){let n=await this._getSettings();return Error(`Cannot ${e} for another tenant.\n
16
- Current tenant: ${n.tenant_handle}\n
17
- Requested tenant: ${t}`)}async _getLatestCommitHash(e){let t=await(await this.caller.call(async()=>{let t=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 A(t,`get latest commit hash`),t})).json();if(t.commits.length!==0)return t.commits[0].commit_hash}async _likeOrUnlikePrompt(e,t){let[n,r,i]=Qo(e),a=JSON.stringify({like:t});return(await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/likes/${n}/${r}`,{method:`POST`,headers:{...this._mergedHeaders,"Content-Type":`application/json`},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await A(e,`${t?`like`:`unlike`} prompt`),e})).json()}async _getPromptUrl(e){let[t,n,r]=Qo(e);if(await this._currentTenantIsOwner(t)){let e=await this._getSettings();return r===`latest`?`${this.getHostUrl()}/prompts/${n}?organizationId=${e.id}`:`${this.getHostUrl()}/prompts/${n}/${r.substring(0,8)}?organizationId=${e.id}`}else return r===`latest`?`${this.getHostUrl()}/hub/${t}/${n}`:`${this.getHostUrl()}/hub/${t}/${n}/${r.substring(0,8)}`}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){let[t,n,r]=Qo(e);for await(let e of this._getPaginated(`/commits/${t}/${n}/`,new URLSearchParams,e=>e.commits))yield*e}async*listPrompts(e){let t=new URLSearchParams;t.append(`sort_field`,e?.sortField??`updated_at`),t.append(`sort_direction`,`desc`),t.append(`is_archived`,(!!e?.isArchived).toString()),e?.isPublic!==void 0&&t.append(`is_public`,e.isPublic.toString()),e?.query&&t.append(`query`,e.query);for await(let e of this._getPaginated(`/repos`,t,e=>e.repos))yield*e}async getPrompt(e){let[t,n,r]=Qo(e),i=await(await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/repos/${t}/${n}`,{method:`GET`,headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return e?.status===404?null:(await A(e,`get prompt`),e)}))?.json();return i?.repo?i.repo:null}async createPrompt(e,t){let n=await this._getSettings();if(t?.isPublic&&!n.tenant_handle)throw Error(`Cannot create a public prompt without first
18
-
19
- creating a LangChain Hub handle.
20
- You can add a handle by creating a public prompt at:
21
-
22
- https://smith.langchain.com/prompts`);let[r,i,a]=Qo(e);if(!await this._currentTenantIsOwner(r))throw await this._ownerConflictError(`create a prompt`,r);let o={repo_handle:i,...t?.description&&{description:t.description},...t?.readme&&{readme:t.readme},...t?.tags&&{tags:t.tags},is_public:!!t?.isPublic},s=JSON.stringify(o),{repo:c}=await(await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/repos/`,{method:`POST`,headers:{...this._mergedHeaders,"Content-Type":`application/json`},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await A(e,`create prompt`),e})).json();return c}async createCommit(e,t,n){if(!await this.promptExists(e))throw Error(`Prompt does not exist, you must create it first.`);let[r,i,a]=Qo(e),o=n?.parentCommitHash===`latest`||!n?.parentCommitHash?await this._getLatestCommitHash(`${r}/${i}`):n?.parentCommitHash,s={manifest:JSON.parse(JSON.stringify(t)),parent_commit:o,...n?.description!==void 0&&{description:n.description}},c=JSON.stringify(s),l=await(await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/commits/${r}/${i}`,{method:`POST`,headers:{...this._mergedHeaders,"Content-Type":`application/json`},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await A(e,`create commit`),e})).json();return this._getPromptUrl(`${r}/${i}${l.commit_hash?`:${l.commit_hash}`:``}`)}async updateExamplesMultipart(e,t=[]){return this._updateExamplesMultipart(e,t)}async _updateExamplesMultipart(e,t=[]){if(!await this._getDatasetExamplesMultiPartSupport())throw Error(`Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version.`);let n=new FormData;for(let e of t){let t=e.id,r=ls({...e.metadata&&{metadata:e.metadata},...e.split&&{split:e.split}},`Serializing body for example with id: ${t}`),i=new Blob([r],{type:`application/json`});if(n.append(t,i),e.inputs){let r=ls(e.inputs,`Serializing inputs for example with id: ${t}`),i=new Blob([r],{type:`application/json`});n.append(`${t}.inputs`,i)}if(e.outputs){let r=ls(e.outputs,`Serializing outputs whle updating example with id: ${t}`),i=new Blob([r],{type:`application/json`});n.append(`${t}.outputs`,i)}if(e.attachments)for(let[r,i]of Object.entries(e.attachments)){let e,a;Array.isArray(i)?[e,a]=i:(e=i.mimeType,a=i.data);let o=new Blob([a],{type:`${e}; length=${a.byteLength}`});n.append(`${t}.attachment.${r}`,o)}if(e.attachments_operations){let r=ls(e.attachments_operations,`Serializing attachments while updating example with id: ${t}`),i=new Blob([r],{type:`application/json`});n.append(`${t}.attachments_operations`,i)}}let r=e??t[0]?.dataset_id;return(await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${r}/examples`)}`,{method:`PATCH`,headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:n});return await A(e,`update examples`),e})).json()}async uploadExamplesMultipart(e,t=[]){return this._uploadExamplesMultipart(e,t)}async _uploadExamplesMultipart(e,t=[]){if(!await this._getDatasetExamplesMultiPartSupport())throw Error(`Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version.`);let n=new FormData;for(let e of t){let t=(e.id??Pr()).toString(),r=ls({created_at:e.created_at,...e.metadata&&{metadata:e.metadata},...e.split&&{split:e.split},...e.source_run_id&&{source_run_id:e.source_run_id},...e.use_source_run_io&&{use_source_run_io:e.use_source_run_io},...e.use_source_run_attachments&&{use_source_run_attachments:e.use_source_run_attachments}},`Serializing body for uploaded example with id: ${t}`),i=new Blob([r],{type:`application/json`});if(n.append(t,i),e.inputs){let r=ls(e.inputs,`Serializing inputs for uploaded example with id: ${t}`),i=new Blob([r],{type:`application/json`});n.append(`${t}.inputs`,i)}if(e.outputs){let r=ls(e.outputs,`Serializing outputs for uploaded example with id: ${t}`),i=new Blob([r],{type:`application/json`});n.append(`${t}.outputs`,i)}if(e.attachments)for(let[r,i]of Object.entries(e.attachments)){let e,a;Array.isArray(i)?[e,a]=i:(e=i.mimeType,a=i.data);let o=new Blob([a],{type:`${e}; length=${a.byteLength}`});n.append(`${t}.attachment.${r}`,o)}}return(await this.caller.call(async()=>{let t=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${e}/examples`)}`,{method:`POST`,headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:n});return await A(t,`upload examples`),t})).json()}async updatePrompt(e,t){if(!await this.promptExists(e))throw Error(`Prompt does not exist, you must create it first.`);let[n,r]=Qo(e);if(!await this._currentTenantIsOwner(n))throw await this._ownerConflictError(`update a prompt`,n);let i={};if(t?.description!==void 0&&(i.description=t.description),t?.readme!==void 0&&(i.readme=t.readme),t?.tags!==void 0&&(i.tags=t.tags),t?.isPublic!==void 0&&(i.is_public=t.isPublic),t?.isArchived!==void 0&&(i.is_archived=t.isArchived),Object.keys(i).length===0)throw Error(`No valid update options provided`);let a=JSON.stringify(i);return(await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/repos/${n}/${r}`,{method:`PATCH`,headers:{...this._mergedHeaders,"Content-Type":`application/json`},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await A(e,`update prompt`),e})).json()}async deletePrompt(e){if(!await this.promptExists(e))throw Error(`Prompt does not exist, you must create it first.`);let[t,n,r]=Qo(e);if(!await this._currentTenantIsOwner(t))throw await this._ownerConflictError(`delete a prompt`,t);return(await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/repos/${t}/${n}`,{method:`DELETE`,headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await A(e,`delete prompt`),e})).json()}_getPromptCacheKey(e,t){return`${e}${t?`:with_model`:``}`}async _fetchPromptFromApi(e,t){let[n,r,i]=Qo(e),a=await(await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/commits/${n}/${r}/${i}${t?.includeModel?`?include_model=true`:``}`,{method:`GET`,headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await A(e,`pull prompt commit`),e})).json();return{owner:n,repo:r,commit_hash:a.commit_hash,manifest:a.manifest,examples:a.examples}}async pullPromptCommit(e,t){let n=this._fetchPromptFromApi.bind(this,e,t);if(!t?.skipCache&&this._promptCache){let r=this._getPromptCacheKey(e,t?.includeModel),i=this._promptCache.get(r,n);if(i)return i;let a=await n();return this._promptCache.set(r,a,n),a}return this._fetchPromptFromApi(e,t)}async _pullPrompt(e,t){let n=await this.pullPromptCommit(e,{includeModel:t?.includeModel,skipCache:t?.skipCache});return JSON.stringify(n.manifest)}async pushPrompt(e,t){return await this.promptExists(e)?t&&Object.keys(t).some(e=>e!==`object`)&&await this.updatePrompt(e,{description:t?.description,readme:t?.readme,tags:t?.tags,isPublic:t?.isPublic}):await this.createPrompt(e,{description:t?.description,readme:t?.readme,tags:t?.tags,isPublic:t?.isPublic}),t?.object?await this.createCommit(e,t?.object,{parentCommitHash:t?.parentCommitHash,description:t?.commitDescription}):await this._getPromptUrl(e)}async agentExists(e){let[t,n]=Qo(e);return this._repoExists(t,n)}async skillExists(e){let[t,n]=Qo(e);return this._repoExists(t,n)}async pullAgent(e,t){return await this._pullDirectory(e,`agent`,t?.version)}async pullSkill(e,t){return await this._pullDirectory(e,`skill`,t?.version)}async pushAgent(e,t){return this._pushDirectory(e,`agent`,t)}async pushSkill(e,t){return this._pushDirectory(e,`skill`,t)}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,t){let n=new URLSearchParams;n.append(`repo_type`,e),n.append(`is_archived`,(!!t?.isArchived).toString()),t?.isPublic!==void 0&&n.append(`is_public`,t.isPublic.toString()),t?.query&&n.append(`query`,t.query);for await(let e of this._getPaginated(`/repos`,n,e=>e.repos))yield*e}async _pullDirectory(e,t,n){let[r,i,a]=Qo(e),o=n??(a===`latest`?void 0:a),s=new URL(`${this.apiUrl}/v1/platform/hub/repos/${r}/${i}/directories`);return s.searchParams.set(`repo_type`,t),o&&s.searchParams.set(`commit`,o),await(await this.caller.call(async()=>{let e=await this._fetch(s.toString(),{method:`GET`,headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await A(e,`pull directory`),e})).json()}async _pushDirectory(e,t,n){if(n.parentCommit!==void 0&&(n.parentCommit.length<8||n.parentCommit.length>64))throw Error(`parent_commit must be 8-64 characters`);let[r,i]=Qo(e);if(!await this._currentTenantIsOwner(r))throw await this._ownerConflictError(`push ${t}`,r);if(await this._repoExists(r,i))(n.description!==void 0||n.readme!==void 0||n.tags!==void 0||n.isPublic!==void 0)&&await this._updateRepoMetadata(r,i,n);else{let e=/^[a-z][a-z0-9-_]*$/;if(!e.test(i))throw Error(`Invalid repo_handle ${JSON.stringify(i)}: must match ${e}`);await this._createRepo(i,t,n)}let a={files:n.files};n.parentCommit&&(a.parent_commit=n.parentCommit);let o=(await(await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/v1/platform/hub/repos/${r}/${i}/directories/commits`,{method:`POST`,headers:{...this._mergedHeaders,"Content-Type":`application/json`},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:JSON.stringify(a)});return await A(e,`push ${t}`),e})).json()).commit.commit_hash;return`${this.getHostUrl()}/hub/${r}/${i}:${o.slice(0,8)}`}async _deleteDirectory(e){let[t,n]=Qo(e);if(!await this._currentTenantIsOwner(t))throw await this._ownerConflictError(`delete`,t);await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/v1/platform/hub/repos/${t}/${n}/directories`,{method:`DELETE`,headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await A(e,`delete directory`),e})}async _repoExists(e,t){try{return await this.caller.call(async()=>{let n=await this._fetch(`${this.apiUrl}/repos/${e}/${t}`,{method:`GET`,headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await A(n,`check repo exists`),n}),!0}catch(e){if(qo(e))return!1;throw e}}async _createRepo(e,t,n){let r={repo_handle:e,repo_type:t,is_public:!!n.isPublic};n.description!==void 0&&(r.description=n.description),n.readme!==void 0&&(r.readme=n.readme),n.tags!==void 0&&(r.tags=n.tags);try{await this.caller.call(async()=>{let e=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(r)});return await A(e,`create ${t}`),e})}catch(e){if(Jo(e))return;throw e}}async _updateRepoMetadata(e,t,n){let r={};n.description!==void 0&&(r.description=n.description),n.readme!==void 0&&(r.readme=n.readme),n.tags!==void 0&&(r.tags=n.tags),n.isPublic!==void 0&&(r.is_public=n.isPublic),Object.keys(r).length!==0&&await this.caller.call(async()=>{let n=await this._fetch(`${this.apiUrl}/repos/${e}/${t}`,{method:`PATCH`,headers:{...this._mergedHeaders,"Content-Type":`application/json`},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:JSON.stringify(r)});return await A(n,`update repo metadata`),n})}async clonePublicDataset(t,n={}){let{sourceApiUrl:r=this.apiUrl,datasetName:i}=n,[a,o]=this.parseTokenOrUrl(t,r),s=new e({apiUrl:a,apiKey:`placeholder`}),c=await s.readSharedDataset(o),l=i||c.name;try{if(await this.hasDataset({datasetId:l})){console.log(`Dataset ${l} already exists in your tenant. Skipping.`);return}}catch{}let u=await s.listSharedExamples(o),d=await this.createDataset(l,{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:u.map(e=>e.inputs),outputs:u.flatMap(e=>e.outputs?[e.outputs]:[]),datasetId:d.id})}catch(e){throw console.error(`An error occurred while creating dataset ${l}. You should delete it manually.`),e}}parseTokenOrUrl(e,t,n=2,r=`dataset`){try{return k(e),[t,e]}catch{}try{let i=new URL(e).pathname.split(`/`).filter(e=>e!==``);if(i.length>=n)return[t,i[i.length-n]];throw Error(`Invalid public ${r} URL: ${e}`)}catch{throw Error(`Invalid public ${r} URL or token: ${e}`)}}cleanup(){this._promptCache&&this._promptCache.stop()}async awaitPendingTraceBatches(){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();await new Promise(e=>setTimeout(e,1)),await Promise.all([...this.autoBatchQueue.items.map(({itemPromise:e})=>e),this.batchIngestCaller.queue.onIdle()]),this.langSmithToOTELTranslator!==void 0&&await vo()?.DEFAULT_LANGSMITH_SPAN_PROCESSOR?.forceFlush()}toString(){let 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(Es,`_fallbackDirsCreated`,{enumerable:!0,configurable:!0,writable:!0,value:new Set});function Ds(e){return`dataset_id`in e||`dataset_name`in e}var Os=e=>e===void 0?!![`TRACING_V2`,`TRACING`].find(e=>no(e)===`true`):e,ks=Symbol.for(`lc:context_variables`),As=Symbol.for(`langsmith:replica_trace_roots`);function js(e,t){if(ks in e)return e[ks][t]}function Ms(e,t,n){let r=ks in e?e[ks]:{};r[t]=n,e[ks]=r}var Ns=36,Ps=`6ba7b810-9dad-11d1-80b4-00c04fd430c8`;function Fs(e){return Rr(Object.keys(e).sort().map(t=>`${t}:${e[t]??``}`).join(`|`),Ps)}function Is(e){return e.replace(/[-:.]/g,``)}function Ls(e,t=1){let n=t.toFixed(0).slice(0,3).padStart(3,`0`);return`${new Date(e).toISOString().slice(0,-1)}${n}Z`}function Rs(e,t,n=1){let r=Ls(e,n);return{dottedOrder:Is(r)+t,microsecondPrecisionDatestring:r}}var zs=new Set([`projectName`,`updates`,`reroot`]);function Bs(e){let t={};for(let n of Object.keys(e))zs.has(n)&&(t[n]=e[n]);return t}var Vs=class e{constructor(e,t,n,r){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=t,this.project_name=n,this.replicas=r}static fromHeader(t){let n=t.split(`,`),r={},i=[],a,o;for(let e of n){let[t,n]=e.split(`=`),s=decodeURIComponent(n);t===`langsmith-metadata`?r=JSON.parse(s):t===`langsmith-tags`?i=s.split(`,`):t===`langsmith-project`?a=s:t===`langsmith-replicas`&&(o=JSON.parse(s).map(e=>Array.isArray(e)?e:Bs(e)))}return new e(r,i,a,o)}toHeader(){let 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(`,`)}},Hs=class e{constructor(t){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}),Us(t)){Object.assign(this,{...t});return}let n=e.getDefaultConfig(),{metadata:r,...i}=t,a=i.client??e.getSharedClient(),o={...r,...i?.extra?.metadata};if(i.extra={...i.extra,metadata:o},`id`in i&&i.id==null&&delete i.id,Object.assign(this,{...n,...i,client:a}),this.execution_order??=1,this.child_execution_order??=1,this.dotted_order||(this._serialized_start_time=Ls(this.start_time,this.execution_order)),this.id||=Da(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=Ys(this.replicas),!this.dotted_order){let{dottedOrder:e}=Rs(this.start_time,this.id,this.execution_order);this.parent_run?this.dotted_order=this.parent_run.dotted_order+`.`+e:this.dotted_order=e}}set metadata(e){this.extra={...this.extra,metadata:{...this.extra?.metadata,...e}}}get metadata(){return this.extra?.metadata}static getDefaultConfig(){let e=Date.now();return{run_type:`chain`,project_name:Di(),child_runs:[],api_url:to(`LANGCHAIN_ENDPOINT`)??`http://localhost:1984`,api_key:to(`LANGCHAIN_API_KEY`),caller_options:{},start_time:e,serialized:{},inputs:{},extra:{}}}static getSharedClient(){return e.sharedClient||=new Es,e.sharedClient}createChild(t){let n=this.child_execution_order+1,r=this.replicas?.map(e=>{let{reroot:t,...n}=e;return n}),i=t.replicas??r,a=new e({...t,parent_run:this,project_name:this.project_name,replicas:i,client:this.client,tracingEnabled:this.tracingEnabled,execution_order:n,child_execution_order:n}),o=this.extra?.metadata??{},s=a.extra?.metadata??{};Object.keys(o).length>0&&(a.extra={...a.extra,metadata:{...o,...s}}),ks in this&&(a[ks]=this[ks]);let c=Symbol.for(`lc:child_config`),l=t.extra?.[c]??this.extra[c];if(qs(l)){let e={...l},t=Ks(e.callbacks)?e.callbacks.copy?.():void 0;t&&(Object.assign(t,{_parentRunId:a.id}),t.handlers?.find(Ws)?.updateFromRunTree?.(a),e.callbacks=t),a.extra[c]=e}let u=new Set,d=this;for(;d!=null&&!u.has(d.id);)u.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,t,n=Date.now(),r){this.outputs=this.outputs??e,this.error=this.error??t,this.end_time=this.end_time??n,r&&Object.keys(r).length>0&&(this.extra=this.extra?{...this.extra,metadata:{...this.extra.metadata,...r}}:{metadata:r})}_convertToCreate(e,t,n=!0){let r=e.extra??{};if(r?.runtime?.library===void 0&&(r.runtime||={},t))for(let[e,n]of Object.entries(t))r.runtime[e]||(r.runtime[e]=n);let i=e.parent_run?.id??e.parent_run_id,a;return a=n?[]:e.child_runs.map(e=>this._convertToCreate(e,t,n)),{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:r,serialized:e.serialized,error:e.error,inputs:e.inputs,outputs:e.outputs,session_name:e.project_name,child_runs:a,parent_run_id:i,trace_id:e.trace_id,dotted_order:e.dotted_order,tags:e.tags,attachments:e.attachments,events:e.events}}_sliceParentId(e,t){if(t.dotted_order){let n=t.dotted_order.split(`.`),r=null;for(let t=0;t<n.length;t++)if(n[t].slice(-Ns)===e){r=t;break}if(r!==null){let e=n.slice(r+1);t.dotted_order=e.join(`.`),e.length>0?t.trace_id=e[0].slice(-Ns):t.trace_id=t.id}}t.parent_run_id===e&&(t.parent_run_id=void 0)}_setReplicaTraceRoot(e,t){let n=js(this,As)??{};n[e]=t,Ms(this,As,n);for(let n of this.child_runs)n._setReplicaTraceRoot(e,t)}_remapForProject(e){let{projectName:t,runtimeEnv:n,excludeChildRuns:r=!0,reroot:i=!1,distributedParentId:a,apiUrl:o,apiKey:s,workspaceId:c}=e,l=this._convertToCreate(this,n,r);if(t===this.project_name)return{...l,session_name:t};if(i){if(a)this._sliceParentId(a,l);else if(l.parent_run_id=void 0,l.dotted_order){let e=l.dotted_order.split(`.`);e.length>0&&(l.dotted_order=e[e.length-1],l.trace_id=l.id)}let e=Fs({projectName:t,apiUrl:o,apiKey:s,workspaceId:c});this._setReplicaTraceRoot(e,l.id)}let u;if(!i&&(u=(js(this,As)??{})[Fs({projectName:t,apiUrl:o,apiKey:s,workspaceId:c})],u&&(l.trace_id=u,l.dotted_order))){let e=l.dotted_order.split(`.`),t=null;for(let n=0;n<e.length;n++)if(e[n].slice(-Ns)===u){t=n;break}t!==null&&(l.dotted_order=e.slice(t).join(`.`))}let d=l.id,f=Na(d,t),p;p=l.trace_id?Na(l.trace_id,t):f;let m;l.parent_run_id&&(m=Na(l.parent_run_id,t));let h;return l.dotted_order&&(h=l.dotted_order.split(`.`).map(e=>{let n=Na(e.slice(-Ns),t);return e.slice(0,-Ns)+n}).join(`.`)),{...l,id:f,trace_id:p,parent_run_id:m,dotted_order:h,session_name:t}}async postRun(e=!0){this._awaitInputsOnPost&&(this.inputs=await this.inputs);try{let t=Qa();if(this.replicas&&this.replicas.length>0)for(let{projectName:e,apiKey:n,apiUrl:r,workspaceId:i,reroot:a}of this.replicas){let o=this._remapForProject({projectName:e??this.project_name,runtimeEnv:t,excludeChildRuns:!0,reroot:a,distributedParentId:this.distributedParentId,apiUrl:r,apiKey:n,workspaceId:i});await this.client.createRun(o,{apiKey:n,apiUrl:r,workspaceId:i})}else{let n=this._convertToCreate(this,t,e);await this.client.createRun(n)}if(!e){ki(`Posting with excludeChildRuns=false is deprecated and will be removed in a future version.`);for(let e of this.child_runs)await e.postRun(!1)}this.child_runs=[]}catch(e){console.error(`Error in postRun for run ${this.id}:`,e)}}async patchRun(e){if(this.replicas&&this.replicas.length>0)for(let{projectName:t,apiKey:n,apiUrl:r,workspaceId:i,updates:a,reroot:o}of this.replicas){let s=this._remapForProject({projectName:t??this.project_name,runtimeEnv:void 0,excludeChildRuns:!0,reroot:o,distributedParentId:this.distributedParentId,apiUrl:r,apiKey:n,workspaceId:i}),c={id:s.id,name:s.name,run_type:s.run_type,start_time:s.start_time,outputs:s.outputs,error:s.error,parent_run_id:s.parent_run_id,session_name:s.session_name,reference_example_id:s.reference_example_id,end_time:s.end_time,dotted_order:s.dotted_order,trace_id:s.trace_id,events:s.events,tags:s.tags,extra:s.extra,attachments:this.attachments,...a};e?.excludeInputs||(c.inputs=s.inputs),await this.client.updateRun(s.id,c,{apiKey:n,apiUrl:r,workspaceId:i})}else try{let t={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:this.parent_run?.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?.excludeInputs||(t.inputs=this.inputs),await this.client.updateRun(this.id,t)}catch(e){console.error(`Error in patchRun for run ${this.id}`,e)}this.child_runs=[]}toJSON(){return this._convertToCreate(this,void 0,!1)}addEvent(e){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(t,n){let r=t?.callbacks,i,a,o,s=Os();if(r){let e=r?.getParentRunId?.()??``,t=r?.handlers?.find(e=>e?.name==`langchain_tracer`);i=t?.getRun?.(e),a=t?.projectName,o=t?.client,s||=!!t}return i?new e({name:i.name,id:i.id,trace_id:i.trace_id,dotted_order:i.dotted_order,client:o,tracingEnabled:s,project_name:a,tags:[...new Set((i?.tags??[]).concat(t?.tags??[]))],extra:{metadata:{...i?.extra?.metadata,...t?.metadata}}}).createChild(n):new e({...n,client:o,tracingEnabled:s,project_name:a})}static fromDottedOrder(e){return this.fromHeaders({"langsmith-trace":e})}static fromHeaders(t,n){let r=`get`in t&&typeof t.get==`function`?{"langsmith-trace":t.get(`langsmith-trace`),baggage:t.get(`baggage`)}:t,i=r[`langsmith-trace`];if(!i||typeof i!=`string`)return;let a=i.trim(),o=a.split(`.`).map(e=>{let[t,n]=e.split(`Z`);return{strTime:t,time:Date.parse(t+`Z`),uuid:n}}),s=o[0].uuid,c={...n,name:n?.name??`parent`,run_type:n?.run_type??`chain`,start_time:n?.start_time??Date.now(),id:o.at(-1)?.uuid,trace_id:s,dotted_order:a};if(r.baggage&&typeof r.baggage==`string`){let e=Vs.fromHeader(r.baggage);c.metadata=e.metadata,c.tags=e.tags,c.project_name=e.project_name,c.replicas=e.replicas}let l=new e(c);return l.distributedParentId=l.id,l}toHeaders(e){let t={"langsmith-trace":this.dotted_order,baggage:new Vs(this.extra?.metadata,this.tags,this.project_name,this.replicas).toHeader()};if(e)for(let[n,r]of Object.entries(t))e.set(n,r);return t}};Object.defineProperty(Hs,`sharedClient`,{enumerable:!0,configurable:!0,writable:!0,value:null});function Us(e){return e!=null&&typeof e.createChild==`function`&&typeof e.postRun==`function`}function Ws(e){return typeof e==`object`&&!!e&&typeof e.name==`string`&&e.name===`langchain_tracer`}function Gs(e){return Array.isArray(e)&&e.some(e=>Ws(e))}function Ks(e){return typeof e==`object`&&!!e&&Array.isArray(e.handlers)}function qs(e){let t=e?.callbacks;return e!=null&&typeof t==`object`&&(Gs(t?.handlers)||Gs(t))}function Js(){let e=to(`LANGSMITH_RUNS_ENDPOINTS`);if(!e)return[];try{let t=JSON.parse(e);if(Array.isArray(t)){let e=[];for(let n of t){if(typeof n!=`object`||!n){console.warn(`Invalid item type in LANGSMITH_RUNS_ENDPOINTS: expected object, got ${typeof n}`);continue}if(typeof n.api_url!=`string`){console.warn(`Invalid api_url type in LANGSMITH_RUNS_ENDPOINTS: expected string, got ${typeof n.api_url}`);continue}if(typeof n.api_key!=`string`){console.warn(`Invalid api_key type in LANGSMITH_RUNS_ENDPOINTS: expected string, got ${typeof n.api_key}`);continue}e.push({apiUrl:n.api_url.replace(/\/$/,``),apiKey:n.api_key})}return e}else if(typeof t==`object`&&t){Xs(t);let e=[];for(let[n,r]of Object.entries(t)){let t=n.replace(/\/$/,``);if(typeof r==`string`)e.push({apiUrl:t,apiKey:r});else{console.warn(`Invalid value type in LANGSMITH_RUNS_ENDPOINTS for URL ${n}: expected string, got ${typeof r}`);continue}}return e}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 t}`),[]}catch(e){if(Zo(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 Ys(e){return e?e.map(e=>Array.isArray(e)?{projectName:e[0],updates:e[1]}:e):Js()}function Xs(e){if(Object.keys(e).length>0&&no(`ENDPOINT`))throw new Xo}var Zs=o({BaseTracer:()=>nc,isBaseTracer:()=>tc}),Qs=e=>{if(e)return e.events=e.events??[],e.child_runs=e.child_runs??[],e};function $s(e,t){if(e)return new Hs({...e,start_time:e._serialized_start_time??e.start_time,parent_run:$s(t),child_runs:e.child_runs.map(e=>$s(e)).filter(e=>e!==void 0),extra:{...e.extra,runtime:fr()},tracingEnabled:!1})}function ec(e,t){return e&&!Array.isArray(e)&&typeof e==`object`?e:{[t]:e}}function tc(e){return typeof e._addRunToRunMap==`function`}var nc=class extends vr{runMap=new Map;runTreeMap=new Map;usesRunTreeMap=!1;constructor(e){super(...arguments)}copy(){return this}getRunById(e){if(e!==void 0)return this.usesRunTreeMap?Qs(this.runTreeMap.get(e)):this.runMap.get(e)}stringifyError(e){return e instanceof Error?e.message+(e?.stack?`\n\n${e.stack}`:``):typeof e==`string`?e:`${e}`}_addChildRun(e,t){e.child_runs.push(t)}_addRunToRunMap(e){let{dottedOrder:t,microsecondPrecisionDatestring:n}=Rs(new Date(e.start_time).getTime(),e.id,e.execution_order),r={...e},i=this.getRunById(r.parent_run_id);if(r.parent_run_id===void 0?(r.trace_id=r.id,r.dotted_order=t,r._serialized_start_time=n):i?(this._addChildRun(i,r),i.child_execution_order=Math.max(i.child_execution_order,r.child_execution_order),r.trace_id=i.trace_id,i.dotted_order!==void 0&&(r.dotted_order=[i.dotted_order,t].join(`.`),r._serialized_start_time=n)):r.parent_run_id=void 0,this.usesRunTreeMap){let e=$s(r,i);e!==void 0&&this.runTreeMap.set(r.id,e)}else this.runMap.set(r.id,r);return r}async _endTrace(e){let t=e.parent_run_id!==void 0&&this.getRunById(e.parent_run_id);t?t.child_execution_order=Math.max(t.child_execution_order,e.child_execution_order):await this.persistRun(e),await this.onRunUpdate?.(e),this.usesRunTreeMap?this.runTreeMap.delete(e.id):this.runMap.delete(e.id)}_getExecutionOrder(e){let t=e!==void 0&&this.getRunById(e);return t?t.child_execution_order+1:1}_createRunForLLMStart(e,t,n,r,i,a,o,s){let c=this._getExecutionOrder(r),l=Date.now(),u=o?{...i,metadata:o}:i,d={id:n,name:s??e.id[e.id.length-1],parent_run_id:r,start_time:l,serialized:e,events:[{name:`start`,time:new Date(l).toISOString()}],inputs:{prompts:t},execution_order:c,child_runs:[],child_execution_order:c,run_type:`llm`,extra:u??{},tags:a||[]};return this._addRunToRunMap(d)}async handleLLMStart(e,t,n,r,i,a,o,s){let c=this.getRunById(n)??this._createRunForLLMStart(e,t,n,r,i,a,o,s);return await this.onRunCreate?.(c),await this.onLLMStart?.(c),c}_createRunForChatModelStart(e,t,n,r,i,a,o,s){let c=this._getExecutionOrder(r),l=Date.now(),u=o?{...i,metadata:o}:i,d={id:n,name:s??e.id[e.id.length-1],parent_run_id:r,start_time:l,serialized:e,events:[{name:`start`,time:new Date(l).toISOString()}],inputs:{messages:t},execution_order:c,child_runs:[],child_execution_order:c,run_type:`llm`,extra:u??{},tags:a||[]};return this._addRunToRunMap(d)}async handleChatModelStart(e,t,n,r,i,a,o,s){let c=this.getRunById(n)??this._createRunForChatModelStart(e,t,n,r,i,a,o,s);return await this.onRunCreate?.(c),await this.onLLMStart?.(c),c}async handleLLMEnd(e,t,n,r,i){let a=this.getRunById(t);if(!a||a?.run_type!==`llm`)throw Error(`No LLM run to end.`);return a.end_time=Date.now(),a.outputs=e,a.events.push({name:`end`,time:new Date(a.end_time).toISOString()}),a.extra={...a.extra,...i},await this.onLLMEnd?.(a),await this._endTrace(a),a}async handleLLMError(e,t,n,r,i){let a=this.getRunById(t);if(!a||a?.run_type!==`llm`)throw Error(`No LLM run to end.`);return a.end_time=Date.now(),a.error=this.stringifyError(e),a.events.push({name:`error`,time:new Date(a.end_time).toISOString()}),a.extra={...a.extra,...i},await this.onLLMError?.(a),await this._endTrace(a),a}_createRunForChainStart(e,t,n,r,i,a,o,s,c){let l=this._getExecutionOrder(r),u=Date.now(),d={id:n,name:s??e.id[e.id.length-1],parent_run_id:r,start_time:u,serialized:e,events:[{name:`start`,time:new Date(u).toISOString()}],inputs:t,execution_order:l,child_execution_order:l,run_type:o??`chain`,child_runs:[],extra:a?{...c,metadata:a}:{...c},tags:i||[]};return this._addRunToRunMap(d)}async handleChainStart(e,t,n,r,i,a,o,s){let c=this.getRunById(n)??this._createRunForChainStart(e,t,n,r,i,a,o,s);return await this.onRunCreate?.(c),await this.onChainStart?.(c),c}async handleChainEnd(e,t,n,r,i){let a=this.getRunById(t);if(!a)throw Error(`No chain run to end.`);return a.end_time=Date.now(),a.outputs=ec(e,`output`),a.events.push({name:`end`,time:new Date(a.end_time).toISOString()}),i?.inputs!==void 0&&(a.inputs=ec(i.inputs,`input`)),await this.onChainEnd?.(a),await this._endTrace(a),a}async handleChainError(e,t,n,r,i){let a=this.getRunById(t);if(!a)throw Error(`No chain run to end.`);return a.end_time=Date.now(),a.error=this.stringifyError(e),a.events.push({name:`error`,time:new Date(a.end_time).toISOString()}),i?.inputs!==void 0&&(a.inputs=ec(i.inputs,`input`)),await this.onChainError?.(a),await this._endTrace(a),a}_createRunForToolStart(e,t,n,r,i,a,o){let s=this._getExecutionOrder(r),c=Date.now(),l={id:n,name:o??e.id[e.id.length-1],parent_run_id:r,start_time:c,serialized:e,events:[{name:`start`,time:new Date(c).toISOString()}],inputs:{input:t},execution_order:s,child_execution_order:s,run_type:`tool`,child_runs:[],extra:a?{metadata:a}:{},tags:i||[]};return this._addRunToRunMap(l)}async handleToolStart(e,t,n,r,i,a,o){let s=this.getRunById(n)??this._createRunForToolStart(e,t,n,r,i,a,o);return await this.onRunCreate?.(s),await this.onToolStart?.(s),s}async handleToolEnd(e,t){let n=this.getRunById(t);if(!n||n?.run_type!==`tool`)throw Error(`No tool run to end`);return n.end_time=Date.now(),n.outputs={output:e},n.events.push({name:`end`,time:new Date(n.end_time).toISOString()}),await this.onToolEnd?.(n),await this._endTrace(n),n}async handleToolError(e,t){let n=this.getRunById(t);if(!n||n?.run_type!==`tool`)throw Error(`No tool run to end`);return n.end_time=Date.now(),n.error=this.stringifyError(e),n.events.push({name:`error`,time:new Date(n.end_time).toISOString()}),await this.onToolError?.(n),await this._endTrace(n),n}async handleAgentAction(e,t){let n=this.getRunById(t);if(!n||n?.run_type!==`chain`)return;let r=n;r.actions=r.actions||[],r.actions.push(e),r.events.push({name:`agent_action`,time:new Date().toISOString(),kwargs:{action:e}}),await this.onAgentAction?.(n)}async handleAgentEnd(e,t){let n=this.getRunById(t);!n||n?.run_type!==`chain`||(n.events.push({name:`agent_end`,time:new Date().toISOString(),kwargs:{action:e}}),await this.onAgentEnd?.(n))}_createRunForRetrieverStart(e,t,n,r,i,a,o){let s=this._getExecutionOrder(r),c=Date.now(),l={id:n,name:o??e.id[e.id.length-1],parent_run_id:r,start_time:c,serialized:e,events:[{name:`start`,time:new Date(c).toISOString()}],inputs:{query:t},execution_order:s,child_execution_order:s,run_type:`retriever`,child_runs:[],extra:a?{metadata:a}:{},tags:i||[]};return this._addRunToRunMap(l)}async handleRetrieverStart(e,t,n,r,i,a,o){let s=this.getRunById(n)??this._createRunForRetrieverStart(e,t,n,r,i,a,o);return await this.onRunCreate?.(s),await this.onRetrieverStart?.(s),s}async handleRetrieverEnd(e,t){let n=this.getRunById(t);if(!n||n?.run_type!==`retriever`)throw Error(`No retriever run to end`);return n.end_time=Date.now(),n.outputs={documents:e},n.events.push({name:`end`,time:new Date(n.end_time).toISOString()}),await this.onRetrieverEnd?.(n),await this._endTrace(n),n}async handleRetrieverError(e,t){let n=this.getRunById(t);if(!n||n?.run_type!==`retriever`)throw Error(`No retriever run to end`);return n.end_time=Date.now(),n.error=this.stringifyError(e),n.events.push({name:`error`,time:new Date(n.end_time).toISOString()}),await this.onRetrieverError?.(n),await this._endTrace(n),n}async handleText(e,t){let n=this.getRunById(t);!n||n?.run_type!==`chain`||(n.events.push({name:`text`,time:new Date().toISOString(),kwargs:{text:e}}),await this.onText?.(n))}async handleLLMNewToken(e,t,n,r,i,a){let o=this.getRunById(n);if(!o||o?.run_type!==`llm`)throw Error(`Invalid "runId" provided to "handleLLMNewToken" callback.`);return o.events.push({name:`new_token`,time:new Date().toISOString(),kwargs:{token:e,idx:t,chunk:a?.chunk}}),await this.onLLMNewToken?.(o,e,{chunk:a?.chunk}),o}},rc=e(t(((e,t)=>{var n=10,r=(e=0)=>t=>`\u001B[${38+e};5;${t}m`,i=(e=0)=>(t,n,r)=>`\u001B[${38+e};2;${t};${n};${r}m`;function a(){let e=new Map,t={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]}};t.color.gray=t.color.blackBright,t.bgColor.bgGray=t.bgColor.bgBlackBright,t.color.grey=t.color.blackBright,t.bgColor.bgGrey=t.bgColor.bgBlackBright;for(let[n,r]of Object.entries(t)){for(let[n,i]of Object.entries(r))t[n]={open:`\u001B[${i[0]}m`,close:`\u001B[${i[1]}m`},r[n]=t[n],e.set(i[0],i[1]);Object.defineProperty(t,n,{value:r,enumerable:!1})}return Object.defineProperty(t,`codes`,{value:e,enumerable:!1}),t.color.close=`\x1B[39m`,t.bgColor.close=`\x1B[49m`,t.color.ansi256=r(),t.color.ansi16m=i(),t.bgColor.ansi256=r(n),t.bgColor.ansi16m=i(n),Object.defineProperties(t,{rgbToAnsi256:{value:(e,t,n)=>e===t&&t===n?e<8?16:e>248?231:Math.round((e-8)/247*24)+232:16+36*Math.round(e/255*5)+6*Math.round(t/255*5)+Math.round(n/255*5),enumerable:!1},hexToRgb:{value:e=>{let t=/(?<colorString>[a-f\d]{6}|[a-f\d]{3})/i.exec(e.toString(16));if(!t)return[0,0,0];let{colorString:n}=t.groups;n.length===3&&(n=n.split(``).map(e=>e+e).join(``));let r=Number.parseInt(n,16);return[r>>16&255,r>>8&255,r&255]},enumerable:!1},hexToAnsi256:{value:e=>t.rgbToAnsi256(...t.hexToRgb(e)),enumerable:!1}}),t}Object.defineProperty(t,`exports`,{enumerable:!0,get:a})}))(),1),ic=o({ConsoleCallbackHandler:()=>uc});function ac(e,t){return`${e.open}${t}${e.close}`}function oc(e,t){try{return JSON.stringify(e,null,2)}catch{return t}}function sc(e){return typeof e==`string`?e.trim():e==null?e:oc(e,e.toString())}function cc(e){if(!e.end_time)return``;let t=e.end_time-e.start_time;return t<1e3?`${t}ms`:`${(t/1e3).toFixed(2)}s`}var{color:lc}=rc.default,uc=class extends nc{name=`console_callback_handler`;persistRun(e){return Promise.resolve()}getParents(e){let t=[],n=e;for(;n.parent_run_id;){let e=this.runMap.get(n.parent_run_id);if(e)t.push(e),n=e;else break}return t}getBreadcrumbs(e){let t=[...this.getParents(e).reverse(),e].map((e,t,n)=>{let r=`${e.execution_order}:${e.run_type}:${e.name}`;return t===n.length-1?ac(rc.default.bold,r):r}).join(` > `);return ac(lc.grey,t)}onChainStart(e){let t=this.getBreadcrumbs(e);console.log(`${ac(lc.green,`[chain/start]`)} [${t}] Entering Chain run with input: ${oc(e.inputs,`[inputs]`)}`)}onChainEnd(e){let t=this.getBreadcrumbs(e);console.log(`${ac(lc.cyan,`[chain/end]`)} [${t}] [${cc(e)}] Exiting Chain run with output: ${oc(e.outputs,`[outputs]`)}`)}onChainError(e){let t=this.getBreadcrumbs(e);console.log(`${ac(lc.red,`[chain/error]`)} [${t}] [${cc(e)}] Chain run errored with error: ${oc(e.error,`[error]`)}`)}onLLMStart(e){let t=this.getBreadcrumbs(e),n=`prompts`in e.inputs?{prompts:e.inputs.prompts.map(e=>e.trim())}:e.inputs;console.log(`${ac(lc.green,`[llm/start]`)} [${t}] Entering LLM run with input: ${oc(n,`[inputs]`)}`)}onLLMEnd(e){let t=this.getBreadcrumbs(e);console.log(`${ac(lc.cyan,`[llm/end]`)} [${t}] [${cc(e)}] Exiting LLM run with output: ${oc(e.outputs,`[response]`)}`)}onLLMError(e){let t=this.getBreadcrumbs(e);console.log(`${ac(lc.red,`[llm/error]`)} [${t}] [${cc(e)}] LLM run errored with error: ${oc(e.error,`[error]`)}`)}onToolStart(e){let t=this.getBreadcrumbs(e);console.log(`${ac(lc.green,`[tool/start]`)} [${t}] Entering Tool run with input: "${sc(e.inputs.input)}"`)}onToolEnd(e){let t=this.getBreadcrumbs(e);console.log(`${ac(lc.cyan,`[tool/end]`)} [${t}] [${cc(e)}] Exiting Tool run with output: "${sc(e.outputs?.output)}"`)}onToolError(e){let t=this.getBreadcrumbs(e);console.log(`${ac(lc.red,`[tool/error]`)} [${t}] [${cc(e)}] Tool run errored with error: ${oc(e.error,`[error]`)}`)}onRetrieverStart(e){let t=this.getBreadcrumbs(e);console.log(`${ac(lc.green,`[retriever/start]`)} [${t}] Entering Retriever run with input: ${oc(e.inputs,`[inputs]`)}`)}onRetrieverEnd(e){let t=this.getBreadcrumbs(e);console.log(`${ac(lc.cyan,`[retriever/end]`)} [${t}] [${cc(e)}] Exiting Retriever run with output: ${oc(e.outputs,`[outputs]`)}`)}onRetrieverError(e){let t=this.getBreadcrumbs(e);console.log(`${ac(lc.red,`[retriever/error]`)} [${t}] [${cc(e)}] Retriever run errored with error: ${oc(e.error,`[error]`)}`)}onAgentAction(e){let t=e,n=this.getBreadcrumbs(e);console.log(`${ac(lc.blue,`[agent/action]`)} [${n}] Agent selected action: ${oc(t.actions[t.actions.length-1],`[action]`)}`)}},dc,fc=()=>(dc===void 0&&(dc=new Es(pr(`LANGCHAIN_CALLBACKS_BACKGROUND`)===`false`?{blockOnRootRunFinalization:!0}:{})),dc),pc=class{getStore(){}run(e,t){return t()}},mc=Symbol.for(`ls:tracing_async_local_storage`),hc=new pc,gc=new class{getInstance(){return globalThis[mc]??hc}initializeGlobalInstance(e){globalThis[mc]===void 0&&(globalThis[mc]=e)}};function _c(e=!1){let t=gc.getInstance().getStore();if(!e&&t===void 0)throw Error(`Could not get the current run tree.
23
-
24
- Please make sure you are calling this method within a traceable function and that tracing is enabled.`);return t}function vc(e){return typeof e==`function`&&`langsmith:traceable`in e}var yc=o({LangChainTracer:()=>Sc,OVERRIDABLE_LANGSMITH_INHERITABLE_METADATA_KEYS:()=>bc}),bc=new Set([`ls_agent_type`]);function xc(e){let t;for(let n of e)for(let e of n)qt.isInstance(e.message)&&e.message.usage_metadata!==void 0&&(t=Kt(t,e.message.usage_metadata));return t}var Sc=class e extends nc{name=`langchain_tracer`;projectName;exampleId;client;replicas;usesRunTreeMap=!0;tracingMetadata;tracingTags=[];constructor(t={}){super(t),this.fields=t;let{exampleId:n,projectName:r,client:i,replicas:a,metadata:o,tags:s}=t;this.projectName=r??Di(),this.replicas=a,this.exampleId=n,this.client=i??fc(),this.tracingMetadata=o?{...o}:void 0,this.tracingTags=s??[];let c=e.getTraceableRunTree();c&&this.updateFromRunTree(c)}async persistRun(e){}async onRunCreate(e){Cc(this,e),e.extra?.lc_defers_inputs||await this.getRunTreeWithTracingConfig(e.id)?.postRun()}async onRunUpdate(e){Cc(this,e);let t=this.getRunTreeWithTracingConfig(e.id);e.extra?.lc_defers_inputs?await t?.postRun():await t?.patchRun()}onLLMEnd(e){let t=e.outputs;if(t?.generations){let n=xc(t.generations);if(n!==void 0){e.extra=e.extra??{};let t=e.extra.metadata??{};t.usage_metadata=n,e.extra.metadata=t}}}copyWithTracingConfig({metadata:t,tags:n}){let r;if(t===void 0)r=this.tracingMetadata?{...this.tracingMetadata}:void 0;else if(this.tracingMetadata===void 0)r={...t};else{r={...this.tracingMetadata};for(let[e,n]of Object.entries(t))(!Object.prototype.hasOwnProperty.call(r,e)||bc.has(e))&&(r[e]=n)}let i=n?Array.from(new Set([...this.tracingTags,...n])):[...this.tracingTags],a=new e({...this.fields,metadata:r,tags:i});return a.runMap=this.runMap,a.runTreeMap=this.runTreeMap,a}getRun(e){return this.runTreeMap.get(e)}updateFromRunTree(e){this.runTreeMap.set(e.id,e);let t=e,n=new Set;for(;t.parent_run&&!(n.has(t.id)||(n.add(t.id),!t.parent_run));)t=t.parent_run;n.clear();let r=[t];for(;r.length>0;){let e=r.shift();!e||n.has(e.id)||(n.add(e.id),this.runTreeMap.set(e.id,e),e.child_runs&&r.push(...e.child_runs))}this.client=e.client??this.client,this.replicas=e.replicas??this.replicas,this.projectName=e.project_name??this.projectName,this.exampleId=e.reference_example_id??this.exampleId,this.fields={...this.fields,client:this.client,replicas:this.replicas,projectName:this.projectName,exampleId:this.exampleId}}getRunTreeWithTracingConfig(e){let t=this.runTreeMap.get(e);if(t)return new Hs({...t,client:this.client,project_name:this.projectName,replicas:this.replicas,reference_example_id:this.exampleId,tracingEnabled:!0})}static getTraceableRunTree(){try{return _c(!0)}catch{return}}static[Symbol.hasInstance](e){if(typeof e!=`object`||!e)return!1;let t=e;return`name`in t&&t.name===`langchain_tracer`&&`copyWithTracingConfig`in t&&typeof t.copyWithTracingConfig==`function`&&`getRunTreeWithTracingConfig`in t&&typeof t.getRunTreeWithTracingConfig==`function`}};function Cc(e,t){if(e.tracingMetadata){t.extra??={};let n=t.extra.metadata??{},r=!1;for(let[t,i]of Object.entries(e.tracingMetadata))(!Object.prototype.hasOwnProperty.call(n,t)||bc.has(t))&&n[t]!==i&&(n[t]=i,r=!0);r&&(t.extra.metadata=n)}e.tracingTags.length>0&&(t.tags=Array.from(new Set([...t.tags??[],...e.tracingTags])))}var wc=Symbol.for(`ls:tracing_async_local_storage`),Tc=Symbol.for(`lc:context_variables`),Ec=e=>{globalThis[wc]=e},Dc=()=>globalThis[wc],Oc;function kc(){return new(`default`in Ro.default?Ro.default.default:Ro.default)({autoStart:!0,concurrency:1})}function Ac(){return Oc===void 0&&(Oc=kc()),Oc}async function jc(e,t){if(t===!0){let t=Dc();t===void 0?await e():await t.run(void 0,async()=>e())}else Oc=Ac(),Oc.add(async()=>{let t=Dc();t===void 0?await e():await t.run(void 0,async()=>e())})}async function Mc(){let e=fc();await Promise.allSettled([Oc===void 0?Promise.resolve():Oc.onIdle(),e.awaitPendingTraceBatches()])}var Nc=o({awaitAllCallbacks:()=>Mc,consumeCallback:()=>jc}),Pc=e=>e===void 0?!![`LANGSMITH_TRACING_V2`,`LANGCHAIN_TRACING_V2`,`LANGSMITH_TRACING`,`LANGCHAIN_TRACING`].find(e=>pr(e)===`true`):e;function Fc(e){let t=Dc();if(t!==void 0)return t.getStore()?.[Tc]?.[e]}var Ic=Symbol(`lc:configure_hooks`),Lc=()=>Fc(Ic)||[],Rc=o({BaseCallbackManager:()=>Bc,BaseRunManager:()=>Vc,CallbackManager:()=>Kc,CallbackManagerForChainRun:()=>Wc,CallbackManagerForLLMRun:()=>Uc,CallbackManagerForRetrieverRun:()=>Hc,CallbackManagerForToolRun:()=>Gc,ensureHandler:()=>qc,parseCallbackConfigArg:()=>zc});function zc(e){return e?Array.isArray(e)||`name`in e?{callbacks:e}:e:{}}var Bc=class{setHandler(e){return this.setHandlers([e])}},Vc=class{constructor(e,t,n,r,i,a,o,s){this.runId=e,this.handlers=t,this.inheritableHandlers=n,this.tags=r,this.inheritableTags=i,this.metadata=a,this.inheritableMetadata=o,this._parentRunId=s}get parentRunId(){return this._parentRunId}async handleText(e){await Promise.all(this.handlers.map(t=>jc(async()=>{try{await t.handleText?.(e,this.runId,this._parentRunId,this.tags)}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleText: ${e}`),t.raiseError)throw e}},t.awaitHandlers)))}async handleCustomEvent(e,t,n,r,i){await Promise.all(this.handlers.map(n=>jc(async()=>{try{await n.handleCustomEvent?.(e,t,this.runId,this.tags,this.metadata)}catch(e){if((n.raiseError?console.error:console.warn)(`Error in handler ${n.constructor.name}, handleCustomEvent: ${e}`),n.raiseError)throw e}},n.awaitHandlers)))}},Hc=class extends Vc{getChild(e){let t=new Kc(this.runId);return t.setHandlers(this.inheritableHandlers),t.addTags(this.inheritableTags),t.addMetadata(this.inheritableMetadata),e&&t.addTags([e],!1),t}async handleRetrieverEnd(e){await Promise.all(this.handlers.map(t=>jc(async()=>{if(!t.ignoreRetriever)try{await t.handleRetrieverEnd?.(e,this.runId,this._parentRunId,this.tags)}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleRetriever`),t.raiseError)throw e}},t.awaitHandlers)))}async handleRetrieverError(e){await Promise.all(this.handlers.map(t=>jc(async()=>{if(!t.ignoreRetriever)try{await t.handleRetrieverError?.(e,this.runId,this._parentRunId,this.tags)}catch(n){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleRetrieverError: ${n}`),t.raiseError)throw e}},t.awaitHandlers)))}},Uc=class extends Vc{async handleLLMNewToken(e,t,n,r,i,a){await Promise.all(this.handlers.map(n=>jc(async()=>{if(!n.ignoreLLM)try{await n.handleLLMNewToken?.(e,t??{prompt:0,completion:0},this.runId,this._parentRunId,this.tags,a)}catch(e){if((n.raiseError?console.error:console.warn)(`Error in handler ${n.constructor.name}, handleLLMNewToken: ${e}`),n.raiseError)throw e}},n.awaitHandlers)))}async handleChatModelStreamEvent(e){await Promise.all(this.handlers.map(t=>jc(async()=>{if(!t.ignoreLLM)try{await t.handleChatModelStreamEvent?.(e,this.runId,this._parentRunId,this.tags)}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleChatModelStreamEvent: ${e}`),t.raiseError)throw e}},t.awaitHandlers)))}async handleLLMError(e,t,n,r,i){await Promise.all(this.handlers.map(t=>jc(async()=>{if(!t.ignoreLLM)try{await t.handleLLMError?.(e,this.runId,this._parentRunId,this.tags,i)}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleLLMError: ${e}`),t.raiseError)throw e}},t.awaitHandlers)))}async handleLLMEnd(e,t,n,r,i){await Promise.all(this.handlers.map(t=>jc(async()=>{if(!t.ignoreLLM)try{await t.handleLLMEnd?.(e,this.runId,this._parentRunId,this.tags,i)}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleLLMEnd: ${e}`),t.raiseError)throw e}},t.awaitHandlers)))}},Wc=class extends Vc{getChild(e){let t=new Kc(this.runId);return t.setHandlers(this.inheritableHandlers),t.addTags(this.inheritableTags),t.addMetadata(this.inheritableMetadata),e&&t.addTags([e],!1),t}async handleChainError(e,t,n,r,i){await Promise.all(this.handlers.map(t=>jc(async()=>{if(!t.ignoreChain)try{await t.handleChainError?.(e,this.runId,this._parentRunId,this.tags,i)}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleChainError: ${e}`),t.raiseError)throw e}},t.awaitHandlers)))}async handleChainEnd(e,t,n,r,i){await Promise.all(this.handlers.map(t=>jc(async()=>{if(!t.ignoreChain)try{await t.handleChainEnd?.(e,this.runId,this._parentRunId,this.tags,i)}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleChainEnd: ${e}`),t.raiseError)throw e}},t.awaitHandlers)))}async handleAgentAction(e){await Promise.all(this.handlers.map(t=>jc(async()=>{if(!t.ignoreAgent)try{await t.handleAgentAction?.(e,this.runId,this._parentRunId,this.tags)}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleAgentAction: ${e}`),t.raiseError)throw e}},t.awaitHandlers)))}async handleAgentEnd(e){await Promise.all(this.handlers.map(t=>jc(async()=>{if(!t.ignoreAgent)try{await t.handleAgentEnd?.(e,this.runId,this._parentRunId,this.tags)}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleAgentEnd: ${e}`),t.raiseError)throw e}},t.awaitHandlers)))}},Gc=class extends Vc{getChild(e){let t=new Kc(this.runId);return t.setHandlers(this.inheritableHandlers),t.addTags(this.inheritableTags),t.addMetadata(this.inheritableMetadata),e&&t.addTags([e],!1),t}async handleToolError(e){await Promise.all(this.handlers.map(t=>jc(async()=>{if(!t.ignoreAgent)try{await t.handleToolError?.(e,this.runId,this._parentRunId,this.tags)}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleToolError: ${e}`),t.raiseError)throw e}},t.awaitHandlers)))}async handleToolEvent(e){await Promise.all(this.handlers.map(t=>jc(async()=>{if(!t.ignoreAgent)try{await t.handleToolEvent?.(e,this.runId,this._parentRunId,this.tags)}catch(e){if(t.raiseError)throw e}},t.awaitHandlers)))}async handleToolEnd(e){await Promise.all(this.handlers.map(t=>jc(async()=>{if(!t.ignoreAgent)try{await t.handleToolEnd?.(e,this.runId,this._parentRunId,this.tags)}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleToolEnd: ${e}`),t.raiseError)throw e}},t.awaitHandlers)))}},Kc=class e extends Bc{handlers=[];inheritableHandlers=[];tags=[];inheritableTags=[];metadata={};inheritableMetadata={};name=`callback_manager`;_parentRunId;constructor(e,t){super(),this.handlers=t?.handlers??this.handlers,this.inheritableHandlers=t?.inheritableHandlers??this.inheritableHandlers,this.tags=t?.tags??this.tags,this.inheritableTags=t?.inheritableTags??this.inheritableTags,this.metadata=t?.metadata??this.metadata,this.inheritableMetadata=t?.inheritableMetadata??this.inheritableMetadata,this._parentRunId=e}getParentRunId(){return this._parentRunId}async handleLLMStart(e,t,n=void 0,r=void 0,i=void 0,a=void 0,o=void 0,s=void 0){return Promise.all(t.map(async(t,r)=>{let a=r===0&&n?n:In();return await Promise.all(this.handlers.map(n=>{if(!n.ignoreLLM)return tc(n)&&n._createRunForLLMStart(e,[t],a,this._parentRunId,i,this.tags,this.metadata,s),jc(async()=>{try{await n.handleLLMStart?.(e,[t],a,this._parentRunId,i,this.tags,this.metadata,s)}catch(e){if((n.raiseError?console.error:console.warn)(`Error in handler ${n.constructor.name}, handleLLMStart: ${e}`),n.raiseError)throw e}},n.awaitHandlers)})),new Uc(a,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChatModelStart(e,t,n=void 0,r=void 0,i=void 0,a=void 0,o=void 0,s=void 0){return Promise.all(t.map(async(t,r)=>{let a=r===0&&n?n:In();return await Promise.all(this.handlers.map(n=>{if(!n.ignoreLLM)return tc(n)&&n._createRunForChatModelStart(e,[t],a,this._parentRunId,i,this.tags,this.metadata,s),jc(async()=>{try{if(n.handleChatModelStart)await n.handleChatModelStart?.(e,[t],a,this._parentRunId,i,this.tags,this.metadata,s);else if(n.handleLLMStart){let r=xn(t);await n.handleLLMStart?.(e,[r],a,this._parentRunId,i,this.tags,this.metadata,s)}}catch(e){if((n.raiseError?console.error:console.warn)(`Error in handler ${n.constructor.name}, handleLLMStart: ${e}`),n.raiseError)throw e}},n.awaitHandlers)})),new Uc(a,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChainStart(e,t,n=In(),r=void 0,i=void 0,a=void 0,o=void 0,s=void 0,c=void 0){return await Promise.all(this.handlers.map(i=>{if(!i.ignoreChain)return tc(i)&&i._createRunForChainStart(e,t,n,this._parentRunId,this.tags,this.metadata,r,o,c),jc(async()=>{try{await i.handleChainStart?.(e,t,n,this._parentRunId,this.tags,this.metadata,r,o,c)}catch(e){if((i.raiseError?console.error:console.warn)(`Error in handler ${i.constructor.name}, handleChainStart: ${e}`),i.raiseError)throw e}},i.awaitHandlers)})),new Wc(n,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleToolStart(e,t,n=In(),r=void 0,i=void 0,a=void 0,o=void 0,s=void 0){return await Promise.all(this.handlers.map(r=>{if(!r.ignoreAgent)return tc(r)&&r._createRunForToolStart(e,t,n,this._parentRunId,this.tags,this.metadata,o),jc(async()=>{try{await r.handleToolStart?.(e,t,n,this._parentRunId,this.tags,this.metadata,o,s)}catch(e){if((r.raiseError?console.error:console.warn)(`Error in handler ${r.constructor.name}, handleToolStart: ${e}`),r.raiseError)throw e}},r.awaitHandlers)})),new Gc(n,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleRetrieverStart(e,t,n=In(),r=void 0,i=void 0,a=void 0,o=void 0){return await Promise.all(this.handlers.map(r=>{if(!r.ignoreRetriever)return tc(r)&&r._createRunForRetrieverStart(e,t,n,this._parentRunId,this.tags,this.metadata,o),jc(async()=>{try{await r.handleRetrieverStart?.(e,t,n,this._parentRunId,this.tags,this.metadata,o)}catch(e){if((r.raiseError?console.error:console.warn)(`Error in handler ${r.constructor.name}, handleRetrieverStart: ${e}`),r.raiseError)throw e}},r.awaitHandlers)})),new Hc(n,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleCustomEvent(e,t,n,r,i){await Promise.all(this.handlers.map(r=>jc(async()=>{if(!r.ignoreCustomEvent)try{await r.handleCustomEvent?.(e,t,n,this.tags,this.metadata)}catch(e){if((r.raiseError?console.error:console.warn)(`Error in handler ${r.constructor.name}, handleCustomEvent: ${e}`),r.raiseError)throw e}},r.awaitHandlers)))}addHandler(e,t=!0){this.handlers.push(e),t&&this.inheritableHandlers.push(e)}removeHandler(e){this.handlers=this.handlers.filter(t=>t!==e),this.inheritableHandlers=this.inheritableHandlers.filter(t=>t!==e)}setHandlers(e,t=!0){this.handlers=[],this.inheritableHandlers=[];for(let n of e)this.addHandler(n,t)}addTags(e,t=!0){this.removeTags(e),this.tags.push(...e),t&&this.inheritableTags.push(...e)}removeTags(e){this.tags=this.tags.filter(t=>!e.includes(t)),this.inheritableTags=this.inheritableTags.filter(t=>!e.includes(t))}addMetadata(e,t=!0){this.metadata={...this.metadata,...e},t&&(this.inheritableMetadata={...this.inheritableMetadata,...e})}removeMetadata(e){for(let t of Object.keys(e))delete this.metadata[t],delete this.inheritableMetadata[t]}copy(t=[],n=!0){let r=new e(this._parentRunId);for(let e of this.handlers){let t=this.inheritableHandlers.includes(e);r.addHandler(e,t)}for(let e of this.tags){let t=this.inheritableTags.includes(e);r.addTags([e],t)}for(let e of Object.keys(this.metadata)){let t=Object.keys(this.inheritableMetadata).includes(e);r.addMetadata({[e]:this.metadata[e]},t)}for(let e of t)r.handlers.filter(e=>e.name===`console_callback_handler`).some(t=>t.name===e.name)||r.addHandler(e,n);return r}static fromHandlers(e){class t extends vr{name=In();constructor(){super(),Object.assign(this,e)}}let n=new this;return n.addHandler(new t),n}static configure(e,t,n,r,i,a,o){return this._configureSync(e,t,n,r,i,a,o)}static _configureSync(t,n,r,i,a,o,s){let c;(t||n)&&(Array.isArray(t)||!t?(c=new e,c.setHandlers(t?.map(qc)??[],!0)):c=t,c=c.copy(Array.isArray(n)?n.map(qc):n?.handlers,!1));let l=pr(`LANGCHAIN_VERBOSE`)===`true`||s?.verbose,u=Sc.getTraceableRunTree(),d=u?.tracingEnabled??Pc();if(u?.tracingEnabled===!1&&c){let e=c.handlers.filter(e=>e.name===`langchain_tracer`);for(let t of e)c.removeHandler(t)}let f=d||(pr(`LANGCHAIN_TRACING`)??!1);if(l||f){if(c||=new e,l&&!c.handlers.some(e=>e.name===uc.prototype.name)){let e=new uc;c.addHandler(e,!0)}if(f&&!c.handlers.some(e=>e.name===`langchain_tracer`)&&d){let e=new Sc;c.addHandler(e,!0)}d&&u&&c._parentRunId===void 0&&(c._parentRunId=u.id,c.handlers.find(e=>e.name===`langchain_tracer`)?.updateFromRunTree(u))}for(let{contextVar:t,inheritable:n=!0,handlerClass:r,envVar:i}of Lc()){let a=i&&pr(i)===`true`&&r,o,s=t===void 0?void 0:Fc(t);s&&yr(s)?o=s:a&&(o=new r({})),o!==void 0&&(c||=new e,c.handlers.some(e=>e.name===o.name)||c.addHandler(o,n))}(r||i)&&c&&(c.addTags(r??[]),c.addTags(i??[],!1)),(a||o)&&c&&(c.addMetadata(a??{}),c.addMetadata(o??{},!1));let p=s?.tracerInheritableMetadata,m=s?.tracerInheritableTags;return c&&(p||m)&&(c.handlers=c.handlers.map(e=>e instanceof Sc?e.copyWithTracingConfig({metadata:p,tags:m}):e),c.inheritableHandlers=c.inheritableHandlers.map(e=>e instanceof Sc?e.copyWithTracingConfig({metadata:p,tags:m}):e)),c}};function qc(e){return`name`in e?e:vr.fromMethods(e)}var Jc=class{getStore(){}run(e,t){return t()}enterWith(e){}},Yc=new Jc,Xc=Symbol.for(`lc:child_config`),Zc=new class{getInstance(){return Dc()??Yc}getRunnableConfig(){return this.getInstance().getStore()?.extra?.[Xc]}runWithConfig(e,t,n){let r=Kc._configureSync(e?.callbacks,void 0,e?.tags,void 0,e?.metadata),i=this.getInstance(),a=i.getStore(),o=r?.getParentRunId(),s=r?.handlers?.find(e=>e?.name===`langchain_tracer`),c;return s&&o?c=s.getRunTreeWithTracingConfig(o):n||(c=new Hs({name:`<runnable_lambda>`,tracingEnabled:!1})),c&&(c.extra={...c.extra,[Xc]:e}),a!==void 0&&a[Tc]!==void 0&&(c===void 0&&(c={}),c[Tc]=a[Tc]),i.run(c,t)}initializeGlobalInstance(e){Dc()===void 0&&Ec(e)}},Qc=o({AsyncLocalStorageProviderSingleton:()=>Zc,MockAsyncLocalStorage:()=>Jc,_CONTEXT_VARIABLES_KEY:()=>Tc}),$c=new Set([`api_key`]),el=new Set([`string`,`number`,`boolean`]);function tl(e){let t=e.configurable??{},n=e.metadata??{},r={};for(let[e,i]of Object.entries(t))!e.startsWith(`__`)&&!Object.prototype.hasOwnProperty.call(n,e)&&!$c.has(e)&&el.has(typeof i)&&(r[e]=i);return Object.keys(r).length>0?r:void 0}async function nl(e){return Kc._configureSync(e?.callbacks,void 0,e?.tags,void 0,e?.metadata,void 0,{tracerInheritableMetadata:e?tl(e):void 0})}function rl(...e){let t={};for(let n of e.filter(e=>!!e))for(let e of Object.keys(n))if(e===`metadata`)t[e]={...t[e],...n[e]};else if(e===`tags`){let r=t[e]??[];t[e]=[...new Set(r.concat(n[e]??[]))]}else if(e===`configurable`)t[e]={...t[e],...n[e]};else if(e===`timeout`)t.timeout===void 0?t.timeout=n.timeout:n.timeout!==void 0&&(t.timeout=Math.min(t.timeout,n.timeout));else if(e===`signal`)t.signal===void 0?t.signal=n.signal:n.signal!==void 0&&(`any`in AbortSignal?t.signal=AbortSignal.any([t.signal,n.signal]):t.signal=n.signal);else if(e===`callbacks`){let e=t.callbacks,r=n.callbacks;if(Array.isArray(r))if(!e)t.callbacks=r;else if(Array.isArray(e))t.callbacks=e.concat(r);else{let n=e.copy();for(let e of r)n.addHandler(qc(e),!0);t.callbacks=n}else if(r)if(!e)t.callbacks=r;else if(Array.isArray(e)){let n=r.copy();for(let t of e)n.addHandler(qc(t),!0);t.callbacks=n}else t.callbacks=new Kc(r._parentRunId,{handlers:e.handlers.concat(r.handlers),inheritableHandlers:e.inheritableHandlers.concat(r.inheritableHandlers),tags:Array.from(new Set(e.tags.concat(r.tags))),inheritableTags:Array.from(new Set(e.inheritableTags.concat(r.inheritableTags))),metadata:{...e.metadata,...r.metadata}})}else{let r=e;t[r]=n[r]??t[r]}return t}function il(e){let t=Zc.getRunnableConfig(),n={tags:[],metadata:{},recursionLimit:25,runId:void 0};if(t){let{runId:e,runName:r,...i}=t;n=Object.entries(i).reduce((e,[t,n])=>(n!==void 0&&(e[t]=n),e),n)}if(e&&(n=Object.entries(e).reduce((e,[t,n])=>(n!==void 0&&(e[t]=n),e),n)),n?.configurable&&typeof n.configurable.model==`string`&&n.metadata?.model===void 0&&(n.metadata||={},n.metadata.model=n.configurable.model),n.timeout!==void 0){if(n.timeout<=0)throw Error(`Timeout must be a positive number`);let e=n.timeout,t=AbortSignal.timeout(e);n.metadata||={},n.metadata.timeoutMs===void 0&&(n.metadata.timeoutMs=e),n.signal===void 0?n.signal=t:`any`in AbortSignal&&(n.signal=AbortSignal.any([n.signal,t])),delete n.timeout}return n}function al(e={},{callbacks:t,maxConcurrency:n,recursionLimit:r,runName:i,configurable:a,runId:o}={}){let s=il(e);return t!==void 0&&(delete s.runName,s.callbacks=t),r!==void 0&&(s.recursionLimit=r),n!==void 0&&(s.maxConcurrency=n),i!==void 0&&(s.runName=i),a!==void 0&&(s.configurable={...s.configurable,...a}),o!==void 0&&delete s.runId,s}function ol(e){if(e)return{configurable:e.configurable,recursionLimit:e.recursionLimit,callbacks:e.callbacks,tags:e.tags,metadata:e.metadata,maxConcurrency:e.maxConcurrency,timeout:e.timeout,signal:e.signal,store:e.store}}async function sl(e,t){if(t===void 0)return e;let n;return Promise.race([e.catch(e=>{if(!t?.aborted)throw e}),new Promise((e,r)=>{n=()=>{r(cl(t))},t.addEventListener(`abort`,n,{once:!0}),t.aborted&&r(cl(t))})]).finally(()=>t.removeEventListener(`abort`,n))}function cl(e){return e?.reason instanceof Error?e.reason:typeof e?.reason==`string`?Error(e.reason):Error(`Aborted`)}var ll=o({AsyncGeneratorWithSetup:()=>pl,IterableReadableStream:()=>ul,atee:()=>dl,concat:()=>fl,pipeGeneratorWithSetup:()=>ml}),ul=class e extends ReadableStream{reader;ensureReader(){this.reader||=this.getReader()}async next(){this.ensureReader();try{let e=await this.reader.read();return e.done?(this.reader.releaseLock(),{done:!0,value:void 0}):{done:!1,value:e.value}}catch(e){throw this.reader.releaseLock(),e}}async return(){if(this.ensureReader(),this.locked){let e=this.reader.cancel();this.reader.releaseLock(),await e}return{done:!0,value:void 0}}async throw(e){if(this.ensureReader(),this.locked){let e=this.reader.cancel();this.reader.releaseLock(),await e}throw e}[Symbol.asyncIterator](){return this}async[Symbol.asyncDispose](){await this.return()}static fromReadableStream(t){let n=t.getReader();return new e({start(e){return t();function t(){return n.read().then(({done:n,value:r})=>{if(n){e.close();return}return e.enqueue(r),t()})}},cancel(){n.releaseLock()}})}static fromAsyncGenerator(t){return new e({async pull(e){let{value:n,done:r}=await t.next();r&&e.close(),e.enqueue(n)},async cancel(e){await t.return(e)}})}};function dl(e,t=2){let n=Array.from({length:t},()=>[]);return n.map(async function*(t){for(;;)if(t.length===0){let t=await e.next();for(let e of n)e.push(t)}else if(t[0].done)return;else yield t.shift().value})}function fl(e,t){if(Array.isArray(e)&&Array.isArray(t))return e.concat(t);if(typeof e==`string`&&typeof t==`string`||typeof e==`number`&&typeof t==`number`)return e+t;if(`concat`in e&&typeof e.concat==`function`)return e.concat(t);if(typeof e==`object`&&typeof t==`object`){let n={...e};for(let[e,r]of Object.entries(t))e in n&&!Array.isArray(n[e])?n[e]=fl(n[e],r):n[e]=r;return n}else throw Error(`Cannot concat ${typeof e} and ${typeof t}`)}var pl=class{generator;setup;config;signal;firstResult;firstResultUsed=!1;constructor(e){this.generator=e.generator,this.config=e.config,this.signal=e.signal??this.config?.signal,this.setup=new Promise((t,n)=>{Zc.runWithConfig(ol(e.config),async()=>{this.firstResult=this.signal?sl(e.generator.next(),this.signal):e.generator.next(),e.startSetup?this.firstResult.then(e.startSetup).then(t,n):this.firstResult.then(e=>t(void 0),n)},!0)})}async next(...e){return this.signal?.throwIfAborted(),this.firstResultUsed?Zc.runWithConfig(ol(this.config),this.signal?async()=>sl(this.generator.next(...e),this.signal):async()=>this.generator.next(...e),!0):(this.firstResultUsed=!0,this.firstResult)}async return(e){return this.generator.return(e)}async throw(e){return this.generator.throw(e)}[Symbol.asyncIterator](){return this}async[Symbol.asyncDispose](){await this.return()}};async function ml(e,t,n,r,...i){let a=new pl({generator:t,startSetup:n,signal:r}),o=await a.setup;return{output:e(a,o,...i),setup:o}}var hl=Object.prototype.hasOwnProperty;function gl(e,t){return hl.call(e,t)}function _l(e){if(Array.isArray(e)){let t=Array(e.length);for(let e=0;e<t.length;e++)t[e]=``+e;return t}if(Object.keys)return Object.keys(e);let t=[];for(let n in e)gl(e,n)&&t.push(n);return t}function vl(e){switch(typeof e){case`object`:return JSON.parse(JSON.stringify(e));case`undefined`:return null;default:return e}}function yl(e){let t=0,n=e.length,r;for(;t<n;){if(r=e.charCodeAt(t),r>=48&&r<=57){t++;continue}return!1}return!0}function bl(e){return e.indexOf(`/`)===-1&&e.indexOf(`~`)===-1?e:e.replace(/~/g,`~0`).replace(/\//g,`~1`)}function xl(e){return e.replace(/~1/g,`/`).replace(/~0/g,`~`)}function Sl(e){if(e===void 0)return!0;if(e){if(Array.isArray(e)){for(let t=0,n=e.length;t<n;t++)if(Sl(e[t]))return!0}else if(typeof e==`object`){let n=_l(e),r=n.length;for(var t=0;t<r;t++)if(Sl(e[n[t]]))return!0}}return!1}function Cl(e,t){let n=[e];for(let e in t){let r=typeof t[e]==`object`?JSON.stringify(t[e],null,2):t[e];r!==void 0&&n.push(`${e}: ${r}`)}return n.join(`
25
- `)}var wl=class extends Error{constructor(e,t,n,r,i){super(Cl(e,{name:t,index:n,operation:r,tree:i})),this.name=t,this.index=n,this.operation=r,this.tree=i,Object.setPrototypeOf(this,new.target.prototype),this.message=Cl(e,{name:t,index:n,operation:r,tree:i})}},Tl=o({JsonPatchError:()=>El,_areEquals:()=>Il,applyOperation:()=>jl,applyPatch:()=>Ml,applyReducer:()=>Nl,deepClone:()=>Dl,getValueByPointer:()=>Al,validate:()=>Fl,validator:()=>Pl}),El=wl,Dl=vl,Ol={add:function(e,t,n){if(t===`__proto__`||t===`constructor`)throw TypeError("JSON-Patch: modifying `__proto__` or `constructor` prop is banned for security reasons");return e[t]=this.value,{newDocument:n}},remove:function(e,t,n){if(t===`__proto__`||t===`constructor`)throw TypeError("JSON-Patch: modifying `__proto__` or `constructor` prop is banned for security reasons");var r=e[t];return delete e[t],{newDocument:n,removed:r}},replace:function(e,t,n){if(t===`__proto__`||t===`constructor`)throw TypeError("JSON-Patch: modifying `__proto__` or `constructor` prop is banned for security reasons");var r=e[t];return e[t]=this.value,{newDocument:n,removed:r}},move:function(e,t,n){let r=Al(n,this.path);r&&=vl(r);let i=jl(n,{op:`remove`,path:this.from}).removed;return jl(n,{op:`add`,path:this.path,value:i}),{newDocument:n,removed:r}},copy:function(e,t,n){let r=Al(n,this.from);return jl(n,{op:`add`,path:this.path,value:vl(r)}),{newDocument:n}},test:function(e,t,n){return{newDocument:n,test:Il(e[t],this.value)}},_get:function(e,t,n){return this.value=e[t],{newDocument:n}}},kl={add:function(e,t,n){return yl(t)?e.splice(t,0,this.value):e[t]=this.value,{newDocument:n,index:t}},remove:function(e,t,n){return{newDocument:n,removed:e.splice(t,1)[0]}},replace:function(e,t,n){var r=e[t];return e[t]=this.value,{newDocument:n,removed:r}},move:Ol.move,copy:Ol.copy,test:Ol.test,_get:Ol._get};function Al(e,t){if(t==``)return e;var n={op:`_get`,path:t};return jl(e,n),n.value}function jl(e,t,n=!1,r=!0,i=!0,a=0){if(n&&(typeof n==`function`?n(t,0,e,t.path):Pl(t,0)),t.path===``){let r={newDocument:e};if(t.op===`add`)return r.newDocument=t.value,r;if(t.op===`replace`)return r.newDocument=t.value,r.removed=e,r;if(t.op===`move`||t.op===`copy`)return r.newDocument=Al(e,t.from),t.op===`move`&&(r.removed=e),r;if(t.op===`test`){if(r.test=Il(e,t.value),r.test===!1)throw new El(`Test operation failed`,`TEST_OPERATION_FAILED`,a,t,e);return r.newDocument=e,r}else if(t.op===`remove`)return r.removed=e,r.newDocument=null,r;else if(t.op===`_get`)return t.value=e,r;else if(n)throw new El("Operation `op` property is not one of operations defined in RFC-6902",`OPERATION_OP_INVALID`,a,t,e);else return r}else{r||(e=vl(e));let o=(t.path||``).split(`/`),s=e,c=1,l=o.length,u,d,f;for(f=typeof n==`function`?n:Pl;;){if(d=o[c],d&&d.indexOf(`~`)!=-1&&(d=xl(d)),i&&(d==`__proto__`||d==`prototype`&&c>0&&o[c-1]==`constructor`))throw 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&&u===void 0&&(s[d]===void 0?u=o.slice(0,c).join(`/`):c==l-1&&(u=t.path),u!==void 0&&f(t,0,e,u)),c++,Array.isArray(s)){if(d===`-`)d=s.length;else if(n&&!yl(d))throw new El(`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,t,e);else yl(d)&&(d=~~d);if(c>=l){if(n&&t.op===`add`&&d>s.length)throw new El(`The specified index MUST NOT be greater than the number of elements in the array`,`OPERATION_VALUE_OUT_OF_BOUNDS`,a,t,e);let r=kl[t.op].call(t,s,d,e);if(r.test===!1)throw new El(`Test operation failed`,`TEST_OPERATION_FAILED`,a,t,e);return r}}else if(c>=l){let n=Ol[t.op].call(t,s,d,e);if(n.test===!1)throw new El(`Test operation failed`,`TEST_OPERATION_FAILED`,a,t,e);return n}if(s=s[d],n&&c<l&&(!s||typeof s!=`object`))throw new El(`Cannot perform operation at the desired path`,`OPERATION_PATH_UNRESOLVABLE`,a,t,e)}}}function Ml(e,t,n,r=!0,i=!0){if(n&&!Array.isArray(t))throw new El(`Patch sequence must be an array`,`SEQUENCE_NOT_AN_ARRAY`);r||(e=vl(e));let a=Array(t.length);for(let r=0,o=t.length;r<o;r++)a[r]=jl(e,t[r],n,!0,i,r),e=a[r].newDocument;return a.newDocument=e,a}function Nl(e,t,n){let r=jl(e,t);if(r.test===!1)throw new El(`Test operation failed`,`TEST_OPERATION_FAILED`,n,t,e);return r.newDocument}function Pl(e,t,n,r){if(typeof e!=`object`||!e||Array.isArray(e))throw new El(`Operation is not an object`,`OPERATION_NOT_AN_OBJECT`,t,e,n);if(!Ol[e.op])throw new El("Operation `op` property is not one of operations defined in RFC-6902",`OPERATION_OP_INVALID`,t,e,n);if(typeof e.path!=`string`)throw new El("Operation `path` property is not a string",`OPERATION_PATH_INVALID`,t,e,n);if(e.path.indexOf(`/`)!==0&&e.path.length>0)throw new El('Operation `path` property must start with "/"',`OPERATION_PATH_INVALID`,t,e,n);if((e.op===`move`||e.op===`copy`)&&typeof e.from!=`string`)throw new El("Operation `from` property is not present (applicable in `move` and `copy` operations)",`OPERATION_FROM_REQUIRED`,t,e,n);if((e.op===`add`||e.op===`replace`||e.op===`test`)&&e.value===void 0)throw new El("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)",`OPERATION_VALUE_REQUIRED`,t,e,n);if((e.op===`add`||e.op===`replace`||e.op===`test`)&&Sl(e.value))throw new El("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)",`OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED`,t,e,n);if(n){if(e.op==`add`){var i=e.path.split(`/`).length,a=r.split(`/`).length;if(i!==a+1&&i!==a)throw new El("Cannot perform an `add` operation at the desired path",`OPERATION_PATH_CANNOT_ADD`,t,e,n)}else if(e.op===`replace`||e.op===`remove`||e.op===`_get`){if(e.path!==r)throw new El(`Cannot perform the operation at a path that does not exist`,`OPERATION_PATH_UNRESOLVABLE`,t,e,n)}else if(e.op===`move`||e.op===`copy`){var o=Fl([{op:`_get`,path:e.from,value:void 0}],n);if(o&&o.name===`OPERATION_PATH_UNRESOLVABLE`)throw new El(`Cannot perform the operation from a path that does not exist`,`OPERATION_FROM_UNRESOLVABLE`,t,e,n)}}}function Fl(e,t,n){try{if(!Array.isArray(e))throw new El(`Patch sequence must be an array`,`SEQUENCE_NOT_AN_ARRAY`);if(t)Ml(vl(t),vl(e),n||!0);else{n||=Pl;for(var r=0;r<e.length;r++)n(e[r],r,t,void 0)}}catch(e){if(e instanceof El)return e;throw e}}function Il(e,t){if(e===t)return!0;if(e&&t&&typeof e==`object`&&typeof t==`object`){var n=Array.isArray(e),r=Array.isArray(t),i,a,o;if(n&&r){if(a=e.length,a!=t.length)return!1;for(i=a;i--!==0;)if(!Il(e[i],t[i]))return!1;return!0}if(n!=r)return!1;var s=Object.keys(e);if(a=s.length,a!==Object.keys(t).length)return!1;for(i=a;i--!==0;)if(!t.hasOwnProperty(s[i]))return!1;for(i=a;i--!==0;)if(o=s[i],!Il(e[o],t[o]))return!1;return!0}return e!==e&&t!==t}function Ll(e,t,n,r,i){if(t!==e){typeof t.toJSON==`function`&&(t=t.toJSON());for(var a=_l(t),o=_l(e),s=!1,c=o.length-1;c>=0;c--){var l=o[c],u=e[l];if(gl(t,l)&&!(t[l]===void 0&&u!==void 0&&Array.isArray(t)===!1)){var d=t[l];typeof u==`object`&&u&&typeof d==`object`&&d&&Array.isArray(u)===Array.isArray(d)?Ll(u,d,n,r+`/`+bl(l),i):u!==d&&(i&&n.push({op:`test`,path:r+`/`+bl(l),value:vl(u)}),n.push({op:`replace`,path:r+`/`+bl(l),value:vl(d)}))}else Array.isArray(e)===Array.isArray(t)?(i&&n.push({op:`test`,path:r+`/`+bl(l),value:vl(u)}),n.push({op:`remove`,path:r+`/`+bl(l)}),s=!0):(i&&n.push({op:`test`,path:r,value:e}),n.push({op:`replace`,path:r,value:t}))}if(!(!s&&a.length==o.length))for(var c=0;c<a.length;c++){var l=a[c];!gl(e,l)&&t[l]!==void 0&&n.push({op:`add`,path:r+`/`+bl(l),value:vl(t[l])})}}}function Rl(e,t,n=!1){var r=[];return Ll(e,t,r,``,n),r}({...Tl});var zl=o({LogStreamCallbackHandler:()=>Kl,RunLog:()=>Vl,RunLogPatch:()=>Bl,isLogStreamHandler:()=>Hl}),Bl=class{ops;constructor(e){this.ops=e.ops??[]}concat(e){let t=this.ops.concat(e.ops),n=Ml({},t);return new Vl({ops:t,state:n[n.length-1].newDocument})}},Vl=class e extends Bl{state;constructor(e){super(e),this.state=e.state}concat(t){let n=this.ops.concat(t.ops),r=Ml(this.state,t.ops);return new e({ops:n,state:r[r.length-1].newDocument})}static fromRunLogPatch(t){let n=Ml({},t.ops);return new e({ops:t.ops,state:n[n.length-1].newDocument})}},Hl=e=>e.name===`log_stream_tracer`;async function Ul(e,t){if(t===`original`)throw 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.`);let{inputs:n}=e;if([`retriever`,`llm`,`prompt`].includes(e.run_type))return n;if(!(Object.keys(n).length===1&&n?.input===``))return n.input}async function Wl(e,t){let{outputs:n}=e;return t===`original`||[`retriever`,`llm`,`prompt`].includes(e.run_type)?n:n!==void 0&&Object.keys(n).length===1&&n?.output!==void 0?n.output:n}function Gl(e){return e!==void 0&&e.message!==void 0}var Kl=class extends nc{autoClose=!0;includeNames;includeTypes;includeTags;excludeNames;excludeTypes;excludeTags;_schemaFormat=`original`;rootId;keyMapByRunId={};counterMapByRunName={};transformStream;writer;receiveStream;name=`log_stream_tracer`;lc_prefer_streaming=!0;constructor(e){super({_awaitHandler:!0,...e}),this.autoClose=e?.autoClose??!0,this.includeNames=e?.includeNames,this.includeTypes=e?.includeTypes,this.includeTags=e?.includeTags,this.excludeNames=e?.excludeNames,this.excludeTypes=e?.excludeTypes,this.excludeTags=e?.excludeTags,this._schemaFormat=e?._schemaFormat??this._schemaFormat,this.transformStream=new TransformStream,this.writer=this.transformStream.writable.getWriter(),this.receiveStream=ul.fromReadableStream(this.transformStream.readable)}[Symbol.asyncIterator](){return this.receiveStream}async persistRun(e){}_includeRun(e){if(e.id===this.rootId)return!1;let t=e.tags??[],n=this.includeNames===void 0&&this.includeTags===void 0&&this.includeTypes===void 0;return this.includeNames!==void 0&&(n||=this.includeNames.includes(e.name)),this.includeTypes!==void 0&&(n||=this.includeTypes.includes(e.run_type)),this.includeTags!==void 0&&(n||=t.find(e=>this.includeTags?.includes(e))!==void 0),this.excludeNames!==void 0&&(n&&=!this.excludeNames.includes(e.name)),this.excludeTypes!==void 0&&(n&&=!this.excludeTypes.includes(e.run_type)),this.excludeTags!==void 0&&(n&&=t.every(e=>!this.excludeTags?.includes(e))),n}async*tapOutputIterable(e,t){for await(let n of t){if(e!==this.rootId){let t=this.keyMapByRunId[e];t&&await this.writer.write(new Bl({ops:[{op:`add`,path:`/logs/${t}/streamed_output/-`,value:n}]}))}yield n}}async onRunCreate(e){if(this.rootId===void 0&&(this.rootId=e.id,await this.writer.write(new Bl({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;let t=this.counterMapByRunName[e.name];this.keyMapByRunId[e.id]=t===1?e.name:`${e.name}:${t}`;let n={id:e.id,name:e.name,type:e.run_type,tags:e.tags??[],metadata:e.extra?.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`&&(n.inputs=await Ul(e,this._schemaFormat)),await this.writer.write(new Bl({ops:[{op:`add`,path:`/logs/${this.keyMapByRunId[e.id]}`,value:n}]}))}async onRunUpdate(e){try{let t=this.keyMapByRunId[e.id];if(t===void 0)return;let n=[];this._schemaFormat===`streaming_events`&&n.push({op:`replace`,path:`/logs/${t}/inputs`,value:await Ul(e,this._schemaFormat)}),n.push({op:`add`,path:`/logs/${t}/final_output`,value:await Wl(e,this._schemaFormat)}),e.end_time!==void 0&&n.push({op:`add`,path:`/logs/${t}/end_time`,value:new Date(e.end_time).toISOString()});let r=new Bl({ops:n});await this.writer.write(r)}finally{if(e.id===this.rootId){let t=new Bl({ops:[{op:`replace`,path:`/final_output`,value:await Wl(e,this._schemaFormat)}]});await this.writer.write(t),this.autoClose&&await this.writer.close()}}}async onLLMNewToken(e,t,n){let r=this.keyMapByRunId[e.id];if(r===void 0)return;let i=e.inputs.messages!==void 0,a;a=i?Gl(n?.chunk)?n?.chunk:new Xt({id:`run-${e.id}`,content:t}):t;let o=new Bl({ops:[{op:`add`,path:`/logs/${r}/streamed_output_str/-`,value:t},{op:`add`,path:`/logs/${r}/streamed_output/-`,value:a}]});await this.writer.write(o)}},ql=o({ChatGenerationChunk:()=>Xl,GenerationChunk:()=>Yl,RUN_KEY:()=>Jl}),Jl=`__run`,Yl=class e{text;generationInfo;constructor(e){this.text=e.text,this.generationInfo=e.generationInfo}concat(t){return new e({text:this.text+t.text,generationInfo:{...this.generationInfo,...t.generationInfo}})}},Xl=class e extends Yl{message;constructor(e){super(e),this.message=e.message}concat(t){return new e({text:this.text+t.text,generationInfo:{...this.generationInfo,...t.generationInfo},message:this.message.concat(t.message)})}};function Zl({name:e,serialized:t}){return e===void 0?t?.name===void 0?t?.id!==void 0&&Array.isArray(t?.id)?t.id[t.id.length-1]:`Unnamed`:t.name:e}var Ql=e=>e.name===`event_stream_tracer`,$l=class extends nc{autoClose=!0;includeNames;includeTypes;includeTags;excludeNames;excludeTypes;excludeTags;runInfoMap=new Map;tappedPromises=new Map;transformStream;writer;receiveStream;readableStreamClosed=!1;name=`event_stream_tracer`;lc_prefer_streaming=!0;constructor(e){super({_awaitHandler:!0,...e}),this.autoClose=e?.autoClose??!0,this.includeNames=e?.includeNames,this.includeTypes=e?.includeTypes,this.includeTags=e?.includeTags,this.excludeNames=e?.excludeNames,this.excludeTypes=e?.excludeTypes,this.excludeTags=e?.excludeTags,this.transformStream=new TransformStream({flush:()=>{this.readableStreamClosed=!0}}),this.writer=this.transformStream.writable.getWriter(),this.receiveStream=ul.fromReadableStream(this.transformStream.readable)}[Symbol.asyncIterator](){return this.receiveStream}async persistRun(e){}_includeRun(e){let t=e.tags??[],n=this.includeNames===void 0&&this.includeTags===void 0&&this.includeTypes===void 0;return this.includeNames!==void 0&&(n||=this.includeNames.includes(e.name)),this.includeTypes!==void 0&&(n||=this.includeTypes.includes(e.runType)),this.includeTags!==void 0&&(n||=t.find(e=>this.includeTags?.includes(e))!==void 0),this.excludeNames!==void 0&&(n&&=!this.excludeNames.includes(e.name)),this.excludeTypes!==void 0&&(n&&=!this.excludeTypes.includes(e.runType)),this.excludeTags!==void 0&&(n&&=t.every(e=>!this.excludeTags?.includes(e))),n}async*tapOutputIterable(e,t){let n=await t.next();if(n.done)return;let r=this.runInfoMap.get(e);if(r===void 0){yield n.value;return}function i(e,t){return e===`llm`&&typeof t==`string`?new Yl({text:t}):t}let a=this.tappedPromises.get(e);if(a===void 0){let o;a=new Promise(e=>{o=e}),this.tappedPromises.set(e,a);try{let a={event:`on_${r.runType}_stream`,run_id:e,name:r.name,tags:r.tags,metadata:r.metadata,data:{}};await this.send({...a,data:{chunk:i(r.runType,n.value)}},r),yield n.value;for await(let e of t)r.runType!==`tool`&&r.runType!==`retriever`&&await this.send({...a,data:{chunk:i(r.runType,e)}},r),yield e}finally{o?.()}}else{yield n.value;for await(let e of t)yield e}}async send(e,t){this.readableStreamClosed||this._includeRun(t)&&await this.writer.write(e)}async sendEndEvent(e,t){let n=this.tappedPromises.get(e.run_id);n===void 0?await this.send(e,t):n.then(()=>{this.send(e,t)})}async onLLMStart(e){let t=Zl(e),n=e.inputs.messages===void 0?`llm`:`chat_model`,r={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:n,inputs:e.inputs};this.runInfoMap.set(e.id,r);let i=`on_${n}_start`;await this.send({event:i,data:{input:e.inputs},name:t,tags:e.tags??[],run_id:e.id,metadata:e.extra?.metadata??{}},r)}async onLLMNewToken(e,t,n){let r=this.runInfoMap.get(e.id),i,a;if(r===void 0)throw Error(`onLLMNewToken: Run ID ${e.id} not found in run map.`);if(this.runInfoMap.size!==1){if(r.runType===`chat_model`)a=`on_chat_model_stream`,i=n?.chunk===void 0?new Xt({content:t,id:`run-${e.id}`}):n.chunk.message;else if(r.runType===`llm`)a=`on_llm_stream`,i=n?.chunk===void 0?new Yl({text:t}):n.chunk;else throw Error(`Unexpected run type ${r.runType}`);await this.send({event:a,data:{chunk:i},run_id:e.id,name:r.name,tags:r.tags,metadata:r.metadata},r)}}async onLLMEnd(e){let t=this.runInfoMap.get(e.id);this.runInfoMap.delete(e.id);let n;if(t===void 0)throw Error(`onLLMEnd: Run ID ${e.id} not found in run map.`);let r=e.outputs?.generations,i;if(t.runType===`chat_model`){for(let e of r??[]){if(i!==void 0)break;i=e[0]?.message}n=`on_chat_model_end`}else if(t.runType===`llm`)i={generations:r?.map(e=>e.map(e=>({text:e.text,generationInfo:e.generationInfo}))),llmOutput:e.outputs?.llmOutput??{}},n=`on_llm_end`;else throw Error(`onLLMEnd: Unexpected run type: ${t.runType}`);await this.sendEndEvent({event:n,data:{output:i,input:t.inputs},run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata},t)}async onChainStart(e){let t=Zl(e),n=e.run_type??`chain`,r={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:e.run_type},i={};e.inputs.input===``&&Object.keys(e.inputs).length===1?(i={},r.inputs={}):e.inputs.input===void 0?(i.input=e.inputs,r.inputs=e.inputs):(i.input=e.inputs.input,r.inputs=e.inputs.input),this.runInfoMap.set(e.id,r),await this.send({event:`on_${n}_start`,data:i,name:t,tags:e.tags??[],run_id:e.id,metadata:e.extra?.metadata??{}},r)}async onChainEnd(e){let t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),t===void 0)throw Error(`onChainEnd: Run ID ${e.id} not found in run map.`);let n=`on_${e.run_type}_end`,r=e.inputs??t.inputs??{},i={output:e.outputs?.output??e.outputs,input:r};r.input&&Object.keys(r).length===1&&(i.input=r.input,t.inputs=r.input),await this.sendEndEvent({event:n,data:i,run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata??{}},t)}async onToolStart(e){let t=Zl(e),n={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:`tool`,inputs:e.inputs??{}};this.runInfoMap.set(e.id,n),await this.send({event:`on_tool_start`,data:{input:e.inputs??{}},name:t,run_id:e.id,tags:e.tags??[],metadata:e.extra?.metadata??{}},n)}async onToolEnd(e){let t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),t===void 0)throw Error(`onToolEnd: Run ID ${e.id} not found in run map.`);if(t.inputs===void 0)throw Error(`onToolEnd: Run ID ${e.id} is a tool call, and is expected to have traced inputs.`);let n=e.outputs?.output===void 0?e.outputs:e.outputs.output;await this.sendEndEvent({event:`on_tool_end`,data:{output:n,input:t.inputs},run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata},t)}async onToolError(e){let t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),t===void 0)throw Error(`onToolEnd: Run ID ${e.id} not found in run map.`);if(t.inputs===void 0)throw 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:t.inputs,error:e.error},run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata},t)}async onRetrieverStart(e){let t=Zl(e),n={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:`retriever`,inputs:{query:e.inputs.query}};this.runInfoMap.set(e.id,n),await this.send({event:`on_retriever_start`,data:{input:{query:e.inputs.query}},name:t,tags:e.tags??[],run_id:e.id,metadata:e.extra?.metadata??{}},n)}async onRetrieverEnd(e){let t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),t===void 0)throw Error(`onRetrieverEnd: Run ID ${e.id} not found in run map.`);await this.sendEndEvent({event:`on_retriever_end`,data:{output:e.outputs?.documents??e.outputs,input:t.inputs},run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata},t)}async handleCustomEvent(e,t,n){let r=this.runInfoMap.get(n);if(r===void 0)throw Error(`handleCustomEvent: Run ID ${n} not found in run map.`);await this.send({event:`on_custom_event`,run_id:n,name:e,tags:r.tags,metadata:r.metadata,data:t},r)}async finish(){let e=[...this.tappedPromises.values()];Promise.all(e).finally(()=>{this.writer.close()})}},eu=Object.prototype.toString,tu=e=>eu.call(e)===`[object Error]`,nu=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 ru(e){if(!(e&&tu(e)&&e.name===`TypeError`&&typeof e.message==`string`))return!1;let{message:t,stack:n}=e;return t===`Load failed`?n===void 0||`__sentry_captured__`in e:t.startsWith(`error sending request for url`)?!0:nu.has(t)}function iu(e){if(typeof e==`number`){if(e<0)throw TypeError("Expected `retries` to be a non-negative number.");if(Number.isNaN(e))throw TypeError("Expected `retries` to be a valid number or Infinity, got NaN.")}else if(e!==void 0)throw TypeError("Expected `retries` to be a number or Infinity.")}function au(e,t,{min:n=0,allowInfinity:r=!1}={}){if(t!==void 0){if(typeof t!=`number`||Number.isNaN(t))throw TypeError(`Expected \`${e}\` to be a number${r?` or Infinity`:``}.`);if(!r&&!Number.isFinite(t))throw TypeError(`Expected \`${e}\` to be a finite number.`);if(t<n)throw TypeError(`Expected \`${e}\` to be \u2265 ${n}.`)}}var ou=class extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,{message:e}=e):(this.originalError=Error(e),this.originalError.stack=this.stack),this.name=`AbortError`,this.message=e}};function su(e,t){let n=Math.max(1,e+1),r=t.randomize?Math.random()+1:1,i=Math.round(r*t.minTimeout*t.factor**(n-1));return i=Math.min(i,t.maxTimeout),i}function cu(e,t){return Number.isFinite(t)?t-(performance.now()-e):t}async function lu({error:e,attemptNumber:t,retriesConsumed:n,startTime:r,options:i}){let a=e instanceof Error?e:TypeError(`Non-error was thrown: "${e}". You should only throw errors.`);if(a instanceof ou)throw a.originalError;let o=Number.isFinite(i.retries)?Math.max(0,i.retries-n):i.retries,s=i.maxRetryTime??1/0,c=Object.freeze({error:a,attemptNumber:t,retriesLeft:o,retriesConsumed:n});if(await i.onFailedAttempt(c),cu(r,s)<=0)throw a;let l=await i.shouldConsumeRetry(c),u=cu(r,s);if(u<=0||o<=0)throw a;if(a instanceof TypeError&&!ru(a)){if(l)throw a;return i.signal?.throwIfAborted(),!1}if(!await i.shouldRetry(c))throw a;if(!l)return i.signal?.throwIfAborted(),!1;let d=su(n,i),f=Math.min(d,u);return f>0&&await new Promise((e,t)=>{let n=()=>{clearTimeout(r),i.signal?.removeEventListener(`abort`,n),t(i.signal.reason)},r=setTimeout(()=>{i.signal?.removeEventListener(`abort`,n),e()},f);i.unref&&r.unref?.(),i.signal?.addEventListener(`abort`,n,{once:!0})}),i.signal?.throwIfAborted(),!0}async function uu(e,t={}){if(t={...t},iu(t.retries),Object.hasOwn(t,`forever`))throw Error("The `forever` option is no longer supported. For many use-cases, you can set `retries: Infinity` instead.");t.retries??=10,t.factor??=2,t.minTimeout??=1e3,t.maxTimeout??=1/0,t.maxRetryTime??=1/0,t.randomize??=!1,t.onFailedAttempt??=()=>{},t.shouldRetry??=()=>!0,t.shouldConsumeRetry??=()=>!0,au(`factor`,t.factor,{min:0,allowInfinity:!1}),au(`minTimeout`,t.minTimeout,{min:0,allowInfinity:!1}),au(`maxTimeout`,t.maxTimeout,{min:0,allowInfinity:!0}),au(`maxRetryTime`,t.maxRetryTime,{min:0,allowInfinity:!0}),t.factor>0||(t.factor=1),t.signal?.throwIfAborted();let n=0,r=0,i=performance.now();for(;!Number.isFinite(t.retries)||r<=t.retries;){n++;try{t.signal?.throwIfAborted();let r=await e(n);return t.signal?.throwIfAborted(),r}catch(e){await lu({error:e,attemptNumber:n,retriesConsumed:r,startTime:i,options:t})&&r++}}throw Error(`Retry attempts exhausted without throwing an error.`)}var du=o({AsyncCaller:()=>mu}),fu=[400,401,402,403,404,405,406,407,409],pu=e=>{if(typeof e!=`object`||!e)return;if(`message`in e&&typeof e.message==`string`&&(e.message.startsWith(`Cancel`)||e.message.startsWith(`AbortError`))||`name`in e&&typeof e.name==`string`&&e.name===`AbortError`||`code`in e&&typeof e.code==`string`&&e.code===`ECONNABORTED`)throw e;let t=`response`in e&&typeof e.response==`object`&&e.response!==null&&`status`in e.response&&typeof e.response.status==`number`?e.response.status:void 0,n=`status`in e&&typeof e.status==`number`?e.status:void 0,r=t??n;if(r&&fu.includes(+r))throw e;if((`error`in e&&typeof e.error==`object`&&e.error!==null&&`code`in e.error&&typeof e.error.code==`string`?e.error.code:void 0)===`insufficient_quota`){let t=Error(`message`in e&&typeof e.message==`string`?e.message:`Insufficient quota`);throw t.name=`InsufficientQuotaError`,t}},mu=class{maxConcurrency;maxRetries;onFailedAttempt;queue;constructor(e){this.maxConcurrency=e.maxConcurrency??1/0,this.maxRetries=e.maxRetries??6,this.onFailedAttempt=e.onFailedAttempt??pu;let t=`default`in Ro.default?Ro.default.default:Ro.default;this.queue=new t({concurrency:this.maxConcurrency})}async call(e,...t){return this.queue.add(()=>uu(()=>e(...t).catch(e=>{throw e instanceof Error?e:Error(e)}),{onFailedAttempt:({error:e})=>this.onFailedAttempt?.(e),retries:this.maxRetries,randomize:!0}),{throwOnTimeout:!0})}callWithOptions(e,t,...n){if(e.signal){let r;return Promise.race([this.call(t,...n),new Promise((t,n)=>{r=()=>{n(cl(e.signal))},e.signal?.addEventListener(`abort`,r,{once:!0})})]).finally(()=>{e.signal&&r&&e.signal.removeEventListener(`abort`,r)})}return this.call(t,...n)}fetch(...e){return this.call(()=>fetch(...e).then(e=>e.ok?e:Promise.reject(e)))}},hu=class extends nc{name=`RootListenersTracer`;rootId;config;argOnStart;argOnEnd;argOnError;constructor({config:e,onStart:t,onEnd:n,onError:r}){super({_awaitHandler:!0}),this.config=e,this.argOnStart=t,this.argOnEnd=n,this.argOnError=r}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 gu(e){return e?e.lc_runnable:!1}var _u=class{includeNames;includeTypes;includeTags;excludeNames;excludeTypes;excludeTags;constructor(e){this.includeNames=e.includeNames,this.includeTypes=e.includeTypes,this.includeTags=e.includeTags,this.excludeNames=e.excludeNames,this.excludeTypes=e.excludeTypes,this.excludeTags=e.excludeTags}includeEvent(e,t){let n=this.includeNames===void 0&&this.includeTypes===void 0&&this.includeTags===void 0,r=e.tags??[];return this.includeNames!==void 0&&(n||=this.includeNames.includes(e.name)),this.includeTypes!==void 0&&(n||=this.includeTypes.includes(t)),this.includeTags!==void 0&&(n||=r.some(e=>this.includeTags?.includes(e))),this.excludeNames!==void 0&&(n&&=!this.excludeNames.includes(e.name)),this.excludeTypes!==void 0&&(n&&=!this.excludeTypes.includes(t)),this.excludeTags!==void 0&&(n&&=r.every(e=>!this.excludeTags?.includes(e))),n}},vu=e=>btoa(e).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``);Object.freeze({status:`aborted`});function j(e,t,n){function r(n,r){var i;Object.defineProperty(n,`_zod`,{value:n._zod??{},enumerable:!1}),(i=n._zod).traits??(i.traits=new Set),n._zod.traits.add(e),t(n,r);for(let e in o.prototype)e in n||Object.defineProperty(n,e,{value:o.prototype[e].bind(n)});n._zod.constr=o,n._zod.def=r}let i=n?.Parent??Object;class a extends i{}Object.defineProperty(a,`name`,{value:e});function o(e){var t;let i=n?.Parent?new a:this;r(i,e),(t=i._zod).deferred??(t.deferred=[]);for(let e of i._zod.deferred)e();return i}return Object.defineProperty(o,`init`,{value:r}),Object.defineProperty(o,Symbol.hasInstance,{value:t=>n?.Parent&&t instanceof n.Parent?!0:t?._zod?.traits?.has(e)}),Object.defineProperty(o,`name`,{value:e}),o}var yu=class extends Error{constructor(){super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`)}},bu={};function xu(e){return e&&Object.assign(bu,e),bu}function Su(e){let t=Object.values(e).filter(e=>typeof e==`number`);return Object.entries(e).filter(([e,n])=>t.indexOf(+e)===-1).map(([e,t])=>t)}function Cu(e,t){return typeof t==`bigint`?t.toString():t}function wu(e){return{get value(){{let t=e();return Object.defineProperty(this,`value`,{value:t}),t}throw Error(`cached value already set`)}}}function Tu(e){return e==null}function Eu(e){let t=+!!e.startsWith(`^`),n=e.endsWith(`$`)?e.length-1:e.length;return e.slice(t,n)}function Du(e,t){let n=(e.toString().split(`.`)[1]||``).length,r=(t.toString().split(`.`)[1]||``).length,i=n>r?n:r;return Number.parseInt(e.toFixed(i).replace(`.`,``))%Number.parseInt(t.toFixed(i).replace(`.`,``))/10**i}function Ou(e,t,n){Object.defineProperty(e,t,{get(){{let r=n();return e[t]=r,r}throw Error(`cached value already set`)},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function ku(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Au(e){return JSON.stringify(e)}var ju=Error.captureStackTrace?Error.captureStackTrace:(...e)=>{};function Mu(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var Nu=wu(()=>{if(typeof navigator<`u`&&navigator?.userAgent?.includes(`Cloudflare`))return!1;try{return Function(``),!0}catch{return!1}});function Pu(e){if(Mu(e)===!1)return!1;let t=e.constructor;if(t===void 0)return!0;let n=t.prototype;return!(Mu(n)===!1||Object.prototype.hasOwnProperty.call(n,`isPrototypeOf`)===!1)}var Fu=new Set([`string`,`number`,`symbol`]);function Iu(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function Lu(e,t,n){let r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function M(e){let t=e;if(!t)return{};if(typeof t==`string`)return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error==`string`?{...t,error:()=>t.error}:t}function Ru(e){return Object.keys(e).filter(t=>e[t]._zod.optin===`optional`&&e[t]._zod.optout===`optional`)}var zu={safeint:[-(2**53-1),2**53-1],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function Bu(e,t){let n={},r=e._zod.def;for(let e in t){if(!(e in r.shape))throw Error(`Unrecognized key: "${e}"`);t[e]&&(n[e]=r.shape[e])}return Lu(e,{...e._zod.def,shape:n,checks:[]})}function Vu(e,t){let n={...e._zod.def.shape},r=e._zod.def;for(let e in t){if(!(e in r.shape))throw Error(`Unrecognized key: "${e}"`);t[e]&&delete n[e]}return Lu(e,{...e._zod.def,shape:n,checks:[]})}function Hu(e,t){if(!Pu(t))throw Error(`Invalid input to extend: expected a plain object`);return Lu(e,{...e._zod.def,get shape(){let n={...e._zod.def.shape,...t};return ku(this,`shape`,n),n},checks:[]})}function Uu(e,t){return Lu(e,{...e._zod.def,get shape(){let n={...e._zod.def.shape,...t._zod.def.shape};return ku(this,`shape`,n),n},catchall:t._zod.def.catchall,checks:[]})}function Wu(e,t,n){let r=t._zod.def.shape,i={...r};if(n)for(let t in n){if(!(t in r))throw Error(`Unrecognized key: "${t}"`);n[t]&&(i[t]=e?new e({type:`optional`,innerType:r[t]}):r[t])}else for(let t in r)i[t]=e?new e({type:`optional`,innerType:r[t]}):r[t];return Lu(t,{...t._zod.def,shape:i,checks:[]})}function Gu(e,t,n){let r=t._zod.def.shape,i={...r};if(n)for(let t in n){if(!(t in i))throw Error(`Unrecognized key: "${t}"`);n[t]&&(i[t]=new e({type:`nonoptional`,innerType:r[t]}))}else for(let t in r)i[t]=new e({type:`nonoptional`,innerType:r[t]});return Lu(t,{...t._zod.def,shape:i,checks:[]})}function Ku(e,t=0){for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function qu(e,t){return t.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function Ju(e){return typeof e==`string`?e:e?.message}function Yu(e,t,n){let r={...e,path:e.path??[]};return e.message||(r.message=Ju(e.inst?._zod.def?.error?.(e))??Ju(t?.error?.(e))??Ju(n.customError?.(e))??Ju(n.localeError?.(e))??`Invalid input`),delete r.inst,delete r.continue,t?.reportInput||delete r.input,r}function Xu(e){return Array.isArray(e)?`array`:typeof e==`string`?`string`:`unknown`}function Zu(...e){let[t,n,r]=e;return typeof t==`string`?{message:t,code:`custom`,input:n,inst:r}:{...t}}var Qu=(e,t)=>{e.name=`$ZodError`,Object.defineProperty(e,`_zod`,{value:e._zod,enumerable:!1}),Object.defineProperty(e,`issues`,{value:t,enumerable:!1}),Object.defineProperty(e,`message`,{get(){return JSON.stringify(t,Cu,2)},enumerable:!0}),Object.defineProperty(e,`toString`,{value:()=>e.message,enumerable:!1})},$u=j(`$ZodError`,Qu),ed=j(`$ZodError`,Qu,{Parent:Error});function td(e,t=e=>e.message){let n={},r=[];for(let i of e.issues)i.path.length>0?(n[i.path[0]]=n[i.path[0]]||[],n[i.path[0]].push(t(i))):r.push(t(i));return{formErrors:r,fieldErrors:n}}function nd(e,t){let n=t||function(e){return e.message},r={_errors:[]},i=e=>{for(let t of e.issues)if(t.code===`invalid_union`&&t.errors.length)t.errors.map(e=>i({issues:e}));else if(t.code===`invalid_key`)i({issues:t.issues});else if(t.code===`invalid_element`)i({issues:t.issues});else if(t.path.length===0)r._errors.push(n(t));else{let e=r,i=0;for(;i<t.path.length;){let r=t.path[i];i===t.path.length-1?(e[r]=e[r]||{_errors:[]},e[r]._errors.push(n(t))):e[r]=e[r]||{_errors:[]},e=e[r],i++}}};return i(e),r}function rd(e){let t=[];for(let n of e)typeof n==`number`?t.push(`[${n}]`):typeof n==`symbol`?t.push(`[${JSON.stringify(String(n))}]`):/[^\w$]/.test(n)?t.push(`[${JSON.stringify(n)}]`):(t.length&&t.push(`.`),t.push(n));return t.join(``)}function id(e){let t=[],n=[...e.issues].sort((e,t)=>e.path.length-t.path.length);for(let e of n)t.push(`βœ– ${e.message}`),e.path?.length&&t.push(` β†’ at ${rd(e.path)}`);return t.join(`
26
- `)}var ad=e=>(t,n,r,i)=>{let a=r?Object.assign(r,{async:!1}):{async:!1},o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise)throw new yu;if(o.issues.length){let t=new(i?.Err??e)(o.issues.map(e=>Yu(e,a,xu())));throw ju(t,i?.callee),t}return o.value},od=ad(ed),sd=e=>async(t,n,r,i)=>{let a=r?Object.assign(r,{async:!0}):{async:!0},o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise&&(o=await o),o.issues.length){let t=new(i?.Err??e)(o.issues.map(e=>Yu(e,a,xu())));throw ju(t,i?.callee),t}return o.value},cd=sd(ed),ld=e=>(t,n,r)=>{let i=r?{...r,async:!1}:{async:!1},a=t._zod.run({value:n,issues:[]},i);if(a instanceof Promise)throw new yu;return a.issues.length?{success:!1,error:new(e??$u)(a.issues.map(e=>Yu(e,i,xu())))}:{success:!0,data:a.value}},ud=ld(ed),dd=e=>async(t,n,r)=>{let i=r?Object.assign(r,{async:!0}):{async:!0},a=t._zod.run({value:n,issues:[]},i);return a instanceof Promise&&(a=await a),a.issues.length?{success:!1,error:new e(a.issues.map(e=>Yu(e,i,xu())))}:{success:!0,data:a.value}},fd=dd(ed),pd=/^[cC][^\s-]{8,}$/,md=/^[0-9a-z]+$/,hd=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,gd=/^[0-9a-vA-V]{20}$/,_d=/^[A-Za-z0-9]{27}$/,vd=/^[a-zA-Z0-9_-]{21}$/,yd=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,bd=/^([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})$/,xd=e=>e?RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([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)$/,Sd=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Cd=`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;function wd(){return new RegExp(Cd,`u`)}var Td=/^(?:(?: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])$/,Ed=/^(([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})$/,Dd=/^((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])$/,Od=/^(([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])$/,kd=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Ad=/^[A-Za-z0-9_-]*$/,jd=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,Md=/^\+(?:[0-9]){6,14}[0-9]$/,Nd=`(?:(?:\\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])))`,Pd=RegExp(`^${Nd}$`);function Fd(e){let t=`(?:[01]\\d|2[0-3]):[0-5]\\d`;return typeof e.precision==`number`?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function Id(e){return RegExp(`^${Fd(e)}$`)}function Ld(e){let t=Fd({precision:e.precision}),n=[`Z`];e.local&&n.push(``),e.offset&&n.push(`([+-]\\d{2}:\\d{2})`);let r=`${t}(?:${n.join(`|`)})`;return RegExp(`^${Nd}T(?:${r})$`)}var Rd=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??``}}`:`[\\s\\S]*`;return RegExp(`^${t}$`)},zd=/^\d+$/,Bd=/^-?\d+(?:\.\d+)?/i,Vd=/true|false/i,Hd=/^[^A-Z]*$/,Ud=/^[^a-z]*$/,Wd=j(`$ZodCheck`,(e,t)=>{var n;e._zod??={},e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),Gd={number:`number`,bigint:`bigint`,object:`date`},Kd=j(`$ZodCheckLessThan`,(e,t)=>{Wd.init(e,t);let n=Gd[typeof t.value];e._zod.onattach.push(e=>{let n=e._zod.bag,r=(t.inclusive?n.maximum:n.exclusiveMaximum)??1/0;t.value<r&&(t.inclusive?n.maximum=t.value:n.exclusiveMaximum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:n,code:`too_big`,maximum:t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),qd=j(`$ZodCheckGreaterThan`,(e,t)=>{Wd.init(e,t);let n=Gd[typeof t.value];e._zod.onattach.push(e=>{let n=e._zod.bag,r=(t.inclusive?n.minimum:n.exclusiveMinimum)??-1/0;t.value>r&&(t.inclusive?n.minimum=t.value:n.exclusiveMinimum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:n,code:`too_small`,minimum:t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Jd=j(`$ZodCheckMultipleOf`,(e,t)=>{Wd.init(e,t),e._zod.onattach.push(e=>{var n;(n=e._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw Error(`Cannot mix number and bigint in multiple_of check.`);(typeof n.value==`bigint`?n.value%t.value===BigInt(0):Du(n.value,t.value)===0)||n.issues.push({origin:typeof n.value,code:`not_multiple_of`,divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),Yd=j(`$ZodCheckNumberFormat`,(e,t)=>{Wd.init(e,t),t.format=t.format||`float64`;let n=t.format?.includes(`int`),r=n?`int`:`number`,[i,a]=zu[t.format];e._zod.onattach.push(e=>{let r=e._zod.bag;r.format=t.format,r.minimum=i,r.maximum=a,n&&(r.pattern=zd)}),e._zod.check=o=>{let s=o.value;if(n){if(!Number.isInteger(s)){o.issues.push({expected:r,format:t.format,code:`invalid_type`,input:s,inst:e});return}if(!Number.isSafeInteger(s)){s>0?o.issues.push({input:s,code:`too_big`,maximum:2**53-1,note:`Integers must be within the safe integer range.`,inst:e,origin:r,continue:!t.abort}):o.issues.push({input:s,code:`too_small`,minimum:-(2**53-1),note:`Integers must be within the safe integer range.`,inst:e,origin:r,continue:!t.abort});return}}s<i&&o.issues.push({origin:`number`,input:s,code:`too_small`,minimum:i,inclusive:!0,inst:e,continue:!t.abort}),s>a&&o.issues.push({origin:`number`,input:s,code:`too_big`,maximum:a,inst:e})}}),Xd=j(`$ZodCheckMaxLength`,(e,t)=>{var n;Wd.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!Tu(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag.maximum??1/0;t.maximum<n&&(e._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{let r=n.value;if(r.length<=t.maximum)return;let i=Xu(r);n.issues.push({origin:i,code:`too_big`,maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Zd=j(`$ZodCheckMinLength`,(e,t)=>{var n;Wd.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!Tu(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag.minimum??-1/0;t.minimum>n&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{let r=n.value;if(r.length>=t.minimum)return;let i=Xu(r);n.issues.push({origin:i,code:`too_small`,minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Qd=j(`$ZodCheckLengthEquals`,(e,t)=>{var n;Wd.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!Tu(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag;n.minimum=t.length,n.maximum=t.length,n.length=t.length}),e._zod.check=n=>{let r=n.value,i=r.length;if(i===t.length)return;let a=Xu(r),o=i>t.length;n.issues.push({origin:a,...o?{code:`too_big`,maximum:t.length}:{code:`too_small`,minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),$d=j(`$ZodCheckStringFormat`,(e,t)=>{var n,r;Wd.init(e,t),e._zod.onattach.push(e=>{let n=e._zod.bag;n.format=t.format,t.pattern&&(n.patterns??=new Set,n.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),ef=j(`$ZodCheckRegex`,(e,t)=>{$d.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:`regex`,input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),tf=j(`$ZodCheckLowerCase`,(e,t)=>{t.pattern??=Hd,$d.init(e,t)}),nf=j(`$ZodCheckUpperCase`,(e,t)=>{t.pattern??=Ud,$d.init(e,t)}),rf=j(`$ZodCheckIncludes`,(e,t)=>{Wd.init(e,t);let n=Iu(t.includes),r=new RegExp(typeof t.position==`number`?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(r)}),e._zod.check=n=>{n.value.includes(t.includes,t.position)||n.issues.push({origin:`string`,code:`invalid_format`,format:`includes`,includes:t.includes,input:n.value,inst:e,continue:!t.abort})}}),af=j(`$ZodCheckStartsWith`,(e,t)=>{Wd.init(e,t);let n=RegExp(`^${Iu(t.prefix)}.*`);t.pattern??=n,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(n)}),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`starts_with`,prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),of=j(`$ZodCheckEndsWith`,(e,t)=>{Wd.init(e,t);let n=RegExp(`.*${Iu(t.suffix)}$`);t.pattern??=n,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(n)}),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`ends_with`,suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}}),sf=j(`$ZodCheckOverwrite`,(e,t)=>{Wd.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}}),cf=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),--this.indent}write(e){if(typeof e==`function`){e(this,{execution:`sync`}),e(this,{execution:`async`});return}let t=e.split(`
27
- `).filter(e=>e),n=Math.min(...t.map(e=>e.length-e.trimStart().length)),r=t.map(e=>e.slice(n)).map(e=>` `.repeat(this.indent*2)+e);for(let e of r)this.content.push(e)}compile(){let e=Function,t=this?.args,n=[...(this?.content??[``]).map(e=>` ${e}`)];return new e(...t,n.join(`
28
- `))}},lf={major:4,minor:0,patch:0},uf=j(`$ZodType`,(e,t)=>{var n;e??={},e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=lf;let r=[...e._zod.def.checks??[]];e._zod.traits.has(`$ZodCheck`)&&r.unshift(e);for(let t of r)for(let n of t._zod.onattach)n(e);if(r.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let t=(e,t,n)=>{let r=Ku(e),i;for(let a of t){if(a._zod.def.when){if(!a._zod.def.when(e))continue}else if(r)continue;let t=e.issues.length,o=a._zod.check(e);if(o instanceof Promise&&n?.async===!1)throw new yu;if(i||o instanceof Promise)i=(i??Promise.resolve()).then(async()=>{await o,e.issues.length!==t&&(r||=Ku(e,t))});else{if(e.issues.length===t)continue;r||=Ku(e,t)}}return i?i.then(()=>e):e};e._zod.run=(n,i)=>{let a=e._zod.parse(n,i);if(a instanceof Promise){if(i.async===!1)throw new yu;return a.then(e=>t(e,r,i))}return t(a,r,i)}}e[`~standard`]={validate:t=>{try{let n=ud(e,t);return n.success?{value:n.data}:{issues:n.error?.issues}}catch{return fd(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:`zod`,version:1}}),df=j(`$ZodString`,(e,t)=>{uf.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??Rd(e._zod.bag),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value==`string`||n.issues.push({expected:`string`,code:`invalid_type`,input:n.value,inst:e}),n}}),ff=j(`$ZodStringFormat`,(e,t)=>{$d.init(e,t),df.init(e,t)}),pf=j(`$ZodGUID`,(e,t)=>{t.pattern??=bd,ff.init(e,t)}),mf=j(`$ZodUUID`,(e,t)=>{if(t.version){let e={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(e===void 0)throw Error(`Invalid UUID version: "${t.version}"`);t.pattern??=xd(e)}else t.pattern??=xd();ff.init(e,t)}),hf=j(`$ZodEmail`,(e,t)=>{t.pattern??=Sd,ff.init(e,t)}),gf=j(`$ZodURL`,(e,t)=>{ff.init(e,t),e._zod.check=n=>{try{let r=n.value,i=new URL(r),a=i.href;t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(i.hostname)||n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid hostname`,pattern:jd.source,input:n.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(i.protocol.endsWith(`:`)?i.protocol.slice(0,-1):i.protocol)||n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid protocol`,pattern:t.protocol.source,input:n.value,inst:e,continue:!t.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:e,continue:!t.abort})}}}),_f=j(`$ZodEmoji`,(e,t)=>{t.pattern??=wd(),ff.init(e,t)}),vf=j(`$ZodNanoID`,(e,t)=>{t.pattern??=vd,ff.init(e,t)}),yf=j(`$ZodCUID`,(e,t)=>{t.pattern??=pd,ff.init(e,t)}),bf=j(`$ZodCUID2`,(e,t)=>{t.pattern??=md,ff.init(e,t)}),xf=j(`$ZodULID`,(e,t)=>{t.pattern??=hd,ff.init(e,t)}),Sf=j(`$ZodXID`,(e,t)=>{t.pattern??=gd,ff.init(e,t)}),Cf=j(`$ZodKSUID`,(e,t)=>{t.pattern??=_d,ff.init(e,t)}),wf=j(`$ZodISODateTime`,(e,t)=>{t.pattern??=Ld(t),ff.init(e,t)}),Tf=j(`$ZodISODate`,(e,t)=>{t.pattern??=Pd,ff.init(e,t)}),Ef=j(`$ZodISOTime`,(e,t)=>{t.pattern??=Id(t),ff.init(e,t)}),Df=j(`$ZodISODuration`,(e,t)=>{t.pattern??=yd,ff.init(e,t)}),Of=j(`$ZodIPv4`,(e,t)=>{t.pattern??=Td,ff.init(e,t),e._zod.onattach.push(e=>{let t=e._zod.bag;t.format=`ipv4`})}),kf=j(`$ZodIPv6`,(e,t)=>{t.pattern??=Ed,ff.init(e,t),e._zod.onattach.push(e=>{let t=e._zod.bag;t.format=`ipv6`}),e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:`invalid_format`,format:`ipv6`,input:n.value,inst:e,continue:!t.abort})}}}),Af=j(`$ZodCIDRv4`,(e,t)=>{t.pattern??=Dd,ff.init(e,t)}),jf=j(`$ZodCIDRv6`,(e,t)=>{t.pattern??=Od,ff.init(e,t),e._zod.check=n=>{let[r,i]=n.value.split(`/`);try{if(!i)throw Error();let e=Number(i);if(`${e}`!==i||e<0||e>128)throw Error();new URL(`http://[${r}]`)}catch{n.issues.push({code:`invalid_format`,format:`cidrv6`,input:n.value,inst:e,continue:!t.abort})}}});function Mf(e){if(e===``)return!0;if(e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}var Nf=j(`$ZodBase64`,(e,t)=>{t.pattern??=kd,ff.init(e,t),e._zod.onattach.push(e=>{e._zod.bag.contentEncoding=`base64`}),e._zod.check=n=>{Mf(n.value)||n.issues.push({code:`invalid_format`,format:`base64`,input:n.value,inst:e,continue:!t.abort})}});function Pf(e){if(!Ad.test(e))return!1;let t=e.replace(/[-_]/g,e=>e===`-`?`+`:`/`);return Mf(t.padEnd(Math.ceil(t.length/4)*4,`=`))}var Ff=j(`$ZodBase64URL`,(e,t)=>{t.pattern??=Ad,ff.init(e,t),e._zod.onattach.push(e=>{e._zod.bag.contentEncoding=`base64url`}),e._zod.check=n=>{Pf(n.value)||n.issues.push({code:`invalid_format`,format:`base64url`,input:n.value,inst:e,continue:!t.abort})}}),If=j(`$ZodE164`,(e,t)=>{t.pattern??=Md,ff.init(e,t)});function Lf(e,t=null){try{let n=e.split(`.`);if(n.length!==3)return!1;let[r]=n;if(!r)return!1;let i=JSON.parse(atob(r));return!(`typ`in i&&i?.typ!==`JWT`||!i.alg||t&&(!(`alg`in i)||i.alg!==t))}catch{return!1}}var Rf=j(`$ZodJWT`,(e,t)=>{ff.init(e,t),e._zod.check=n=>{Lf(n.value,t.alg)||n.issues.push({code:`invalid_format`,format:`jwt`,input:n.value,inst:e,continue:!t.abort})}}),zf=j(`$ZodNumber`,(e,t)=>{uf.init(e,t),e._zod.pattern=e._zod.bag.pattern??Bd,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}let i=n.value;if(typeof i==`number`&&!Number.isNaN(i)&&Number.isFinite(i))return n;let a=typeof i==`number`?Number.isNaN(i)?`NaN`:Number.isFinite(i)?void 0:`Infinity`:void 0;return n.issues.push({expected:`number`,code:`invalid_type`,input:i,inst:e,...a?{received:a}:{}}),n}}),Bf=j(`$ZodNumber`,(e,t)=>{Yd.init(e,t),zf.init(e,t)}),Vf=j(`$ZodBoolean`,(e,t)=>{uf.init(e,t),e._zod.pattern=Vd,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=!!n.value}catch{}let i=n.value;return typeof i==`boolean`||n.issues.push({expected:`boolean`,code:`invalid_type`,input:i,inst:e}),n}}),Hf=j(`$ZodAny`,(e,t)=>{uf.init(e,t),e._zod.parse=e=>e}),Uf=j(`$ZodUnknown`,(e,t)=>{uf.init(e,t),e._zod.parse=e=>e}),Wf=j(`$ZodNever`,(e,t)=>{uf.init(e,t),e._zod.parse=(t,n)=>(t.issues.push({expected:`never`,code:`invalid_type`,input:t.value,inst:e}),t)});function Gf(e,t,n){e.issues.length&&t.issues.push(...qu(n,e.issues)),t.value[n]=e.value}var Kf=j(`$ZodArray`,(e,t)=>{uf.init(e,t),e._zod.parse=(n,r)=>{let i=n.value;if(!Array.isArray(i))return n.issues.push({expected:`array`,code:`invalid_type`,input:i,inst:e}),n;n.value=Array(i.length);let a=[];for(let e=0;e<i.length;e++){let o=i[e],s=t.element._zod.run({value:o,issues:[]},r);s instanceof Promise?a.push(s.then(t=>Gf(t,n,e))):Gf(s,n,e)}return a.length?Promise.all(a).then(()=>n):n}});function qf(e,t,n){e.issues.length&&t.issues.push(...qu(n,e.issues)),t.value[n]=e.value}function Jf(e,t,n,r){e.issues.length?r[n]===void 0?n in r?t.value[n]=void 0:t.value[n]=e.value:t.issues.push(...qu(n,e.issues)):e.value===void 0?n in r&&(t.value[n]=void 0):t.value[n]=e.value}var Yf=j(`$ZodObject`,(e,t)=>{uf.init(e,t);let n=wu(()=>{let e=Object.keys(t.shape);for(let n of e)if(!(t.shape[n]instanceof uf))throw Error(`Invalid element at key "${n}": expected a Zod schema`);let n=Ru(t.shape);return{shape:t.shape,keys:e,keySet:new Set(e),numKeys:e.length,optionalKeys:new Set(n)}});Ou(e._zod,`propValues`,()=>{let e=t.shape,n={};for(let t in e){let r=e[t]._zod;if(r.values){n[t]??(n[t]=new Set);for(let e of r.values)n[t].add(e)}}return n});let r=e=>{let t=new cf([`shape`,`payload`,`ctx`]),r=n.value,i=e=>{let t=Au(e);return`shape[${t}]._zod.run({ value: input[${t}], issues: [] }, ctx)`};t.write(`const input = payload.value;`);let a=Object.create(null),o=0;for(let e of r.keys)a[e]=`key_${o++}`;t.write(`const newResult = {}`);for(let e of r.keys)if(r.optionalKeys.has(e)){let n=a[e];t.write(`const ${n} = ${i(e)};`);let r=Au(e);t.write(`
29
- if (${n}.issues.length) {
30
- if (input[${r}] === undefined) {
31
- if (${r} in input) {
32
- newResult[${r}] = undefined;
33
- }
34
- } else {
35
- payload.issues = payload.issues.concat(
36
- ${n}.issues.map((iss) => ({
37
- ...iss,
38
- path: iss.path ? [${r}, ...iss.path] : [${r}],
39
- }))
40
- );
41
- }
42
- } else if (${n}.value === undefined) {
43
- if (${r} in input) newResult[${r}] = undefined;
44
- } else {
45
- newResult[${r}] = ${n}.value;
46
- }
47
- `)}else{let n=a[e];t.write(`const ${n} = ${i(e)};`),t.write(`
48
- if (${n}.issues.length) payload.issues = payload.issues.concat(${n}.issues.map(iss => ({
49
- ...iss,
50
- path: iss.path ? [${Au(e)}, ...iss.path] : [${Au(e)}]
51
- })));`),t.write(`newResult[${Au(e)}] = ${n}.value`)}t.write(`payload.value = newResult;`),t.write(`return payload;`);let s=t.compile();return(t,n)=>s(e,t,n)},i,a=Mu,o=!bu.jitless,s=o&&Nu.value,c=t.catchall,l;e._zod.parse=(u,d)=>{l??=n.value;let f=u.value;if(!a(f))return u.issues.push({expected:`object`,code:`invalid_type`,input:f,inst:e}),u;let p=[];if(o&&s&&d?.async===!1&&d.jitless!==!0)i||=r(t.shape),u=i(u,d);else{u.value={};let e=l.shape;for(let t of l.keys){let n=e[t],r=n._zod.run({value:f[t],issues:[]},d),i=n._zod.optin===`optional`&&n._zod.optout===`optional`;r instanceof Promise?p.push(r.then(e=>i?Jf(e,u,t,f):qf(e,u,t))):i?Jf(r,u,t,f):qf(r,u,t)}}if(!c)return p.length?Promise.all(p).then(()=>u):u;let m=[],h=l.keySet,g=c._zod,_=g.def.type;for(let e of Object.keys(f)){if(h.has(e))continue;if(_===`never`){m.push(e);continue}let t=g.run({value:f[e],issues:[]},d);t instanceof Promise?p.push(t.then(t=>qf(t,u,e))):qf(t,u,e)}return m.length&&u.issues.push({code:`unrecognized_keys`,keys:m,input:f,inst:e}),p.length?Promise.all(p).then(()=>u):u}});function Xf(e,t,n,r){for(let n of e)if(n.issues.length===0)return t.value=n.value,t;return t.issues.push({code:`invalid_union`,input:t.value,inst:n,errors:e.map(e=>e.issues.map(e=>Yu(e,r,xu())))}),t}var Zf=j(`$ZodUnion`,(e,t)=>{uf.init(e,t),Ou(e._zod,`optin`,()=>t.options.some(e=>e._zod.optin===`optional`)?`optional`:void 0),Ou(e._zod,`optout`,()=>t.options.some(e=>e._zod.optout===`optional`)?`optional`:void 0),Ou(e._zod,`values`,()=>{if(t.options.every(e=>e._zod.values))return new Set(t.options.flatMap(e=>Array.from(e._zod.values)))}),Ou(e._zod,`pattern`,()=>{if(t.options.every(e=>e._zod.pattern)){let e=t.options.map(e=>e._zod.pattern);return RegExp(`^(${e.map(e=>Eu(e.source)).join(`|`)})$`)}}),e._zod.parse=(n,r)=>{let i=!1,a=[];for(let e of t.options){let t=e._zod.run({value:n.value,issues:[]},r);if(t instanceof Promise)a.push(t),i=!0;else{if(t.issues.length===0)return t;a.push(t)}}return i?Promise.all(a).then(t=>Xf(t,n,e,r)):Xf(a,n,e,r)}}),Qf=j(`$ZodDiscriminatedUnion`,(e,t)=>{Zf.init(e,t);let n=e._zod.parse;Ou(e._zod,`propValues`,()=>{let e={};for(let n of t.options){let r=n._zod.propValues;if(!r||Object.keys(r).length===0)throw Error(`Invalid discriminated union option at index "${t.options.indexOf(n)}"`);for(let[t,n]of Object.entries(r)){e[t]||(e[t]=new Set);for(let r of n)e[t].add(r)}}return e});let r=wu(()=>{let e=t.options,n=new Map;for(let r of e){let e=r._zod.propValues[t.discriminator];if(!e||e.size===0)throw Error(`Invalid discriminated union option at index "${t.options.indexOf(r)}"`);for(let t of e){if(n.has(t))throw Error(`Duplicate discriminator value "${String(t)}"`);n.set(t,r)}}return n});e._zod.parse=(i,a)=>{let o=i.value;if(!Mu(o))return i.issues.push({code:`invalid_type`,expected:`object`,input:o,inst:e}),i;let s=r.value.get(o?.[t.discriminator]);return s?s._zod.run(i,a):t.unionFallback?n(i,a):(i.issues.push({code:`invalid_union`,errors:[],note:`No matching discriminator`,input:o,path:[t.discriminator],inst:e}),i)}}),$f=j(`$ZodIntersection`,(e,t)=>{uf.init(e,t),e._zod.parse=(e,n)=>{let r=e.value,i=t.left._zod.run({value:r,issues:[]},n),a=t.right._zod.run({value:r,issues:[]},n);return i instanceof Promise||a instanceof Promise?Promise.all([i,a]).then(([t,n])=>tp(e,t,n)):tp(e,i,a)}});function ep(e,t){if(e===t||e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(Pu(e)&&Pu(t)){let n=Object.keys(t),r=Object.keys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=ep(e[n],t[n]);if(!r.valid)return{valid:!1,mergeErrorPath:[n,...r.mergeErrorPath]};i[n]=r.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let r=0;r<e.length;r++){let i=e[r],a=t[r],o=ep(i,a);if(!o.valid)return{valid:!1,mergeErrorPath:[r,...o.mergeErrorPath]};n.push(o.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function tp(e,t,n){if(t.issues.length&&e.issues.push(...t.issues),n.issues.length&&e.issues.push(...n.issues),Ku(e))return e;let r=ep(t.value,n.value);if(!r.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(r.mergeErrorPath)}`);return e.value=r.data,e}var np=j(`$ZodTuple`,(e,t)=>{uf.init(e,t);let n=t.items,r=n.length-[...n].reverse().findIndex(e=>e._zod.optin!==`optional`);e._zod.parse=(i,a)=>{let o=i.value;if(!Array.isArray(o))return i.issues.push({input:o,inst:e,expected:`tuple`,code:`invalid_type`}),i;i.value=[];let s=[];if(!t.rest){let t=o.length>n.length,a=o.length<r-1;if(t||a)return i.issues.push({input:o,inst:e,origin:`array`,...t?{code:`too_big`,maximum:n.length}:{code:`too_small`,minimum:n.length}}),i}let c=-1;for(let e of n){if(c++,c>=o.length&&c>=r)continue;let t=e._zod.run({value:o[c],issues:[]},a);t instanceof Promise?s.push(t.then(e=>rp(e,i,c))):rp(t,i,c)}if(t.rest){let e=o.slice(n.length);for(let n of e){c++;let e=t.rest._zod.run({value:n,issues:[]},a);e instanceof Promise?s.push(e.then(e=>rp(e,i,c))):rp(e,i,c)}}return s.length?Promise.all(s).then(()=>i):i}});function rp(e,t,n){e.issues.length&&t.issues.push(...qu(n,e.issues)),t.value[n]=e.value}var ip=j(`$ZodRecord`,(e,t)=>{uf.init(e,t),e._zod.parse=(n,r)=>{let i=n.value;if(!Pu(i))return n.issues.push({expected:`record`,code:`invalid_type`,input:i,inst:e}),n;let a=[];if(t.keyType._zod.values){let o=t.keyType._zod.values;n.value={};for(let e of o)if(typeof e==`string`||typeof e==`number`||typeof e==`symbol`){let o=t.valueType._zod.run({value:i[e],issues:[]},r);o instanceof Promise?a.push(o.then(t=>{t.issues.length&&n.issues.push(...qu(e,t.issues)),n.value[e]=t.value})):(o.issues.length&&n.issues.push(...qu(e,o.issues)),n.value[e]=o.value)}let s;for(let e in i)o.has(e)||(s??=[],s.push(e));s&&s.length>0&&n.issues.push({code:`unrecognized_keys`,input:i,inst:e,keys:s})}else{n.value={};for(let o of Reflect.ownKeys(i)){if(o===`__proto__`)continue;let s=t.keyType._zod.run({value:o,issues:[]},r);if(s instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(s.issues.length){n.issues.push({origin:`record`,code:`invalid_key`,issues:s.issues.map(e=>Yu(e,r,xu())),input:o,path:[o],inst:e}),n.value[s.value]=s.value;continue}let c=t.valueType._zod.run({value:i[o],issues:[]},r);c instanceof Promise?a.push(c.then(e=>{e.issues.length&&n.issues.push(...qu(o,e.issues)),n.value[s.value]=e.value})):(c.issues.length&&n.issues.push(...qu(o,c.issues)),n.value[s.value]=c.value)}}return a.length?Promise.all(a).then(()=>n):n}}),ap=j(`$ZodEnum`,(e,t)=>{uf.init(e,t);let n=Su(t.entries);e._zod.values=new Set(n),e._zod.pattern=RegExp(`^(${n.filter(e=>Fu.has(typeof e)).map(e=>typeof e==`string`?Iu(e):e.toString()).join(`|`)})$`),e._zod.parse=(t,r)=>{let i=t.value;return e._zod.values.has(i)||t.issues.push({code:`invalid_value`,values:n,input:i,inst:e}),t}}),op=j(`$ZodLiteral`,(e,t)=>{uf.init(e,t),e._zod.values=new Set(t.values),e._zod.pattern=RegExp(`^(${t.values.map(e=>typeof e==`string`?Iu(e):e?e.toString():String(e)).join(`|`)})$`),e._zod.parse=(n,r)=>{let i=n.value;return e._zod.values.has(i)||n.issues.push({code:`invalid_value`,values:t.values,input:i,inst:e}),n}}),sp=j(`$ZodTransform`,(e,t)=>{uf.init(e,t),e._zod.parse=(e,n)=>{let r=t.transform(e.value,e);if(n.async)return(r instanceof Promise?r:Promise.resolve(r)).then(t=>(e.value=t,e));if(r instanceof Promise)throw new yu;return e.value=r,e}}),cp=j(`$ZodOptional`,(e,t)=>{uf.init(e,t),e._zod.optin=`optional`,e._zod.optout=`optional`,Ou(e._zod,`values`,()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),Ou(e._zod,`pattern`,()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${Eu(e.source)})?$`):void 0}),e._zod.parse=(e,n)=>t.innerType._zod.optin===`optional`?t.innerType._zod.run(e,n):e.value===void 0?e:t.innerType._zod.run(e,n)}),lp=j(`$ZodNullable`,(e,t)=>{uf.init(e,t),Ou(e._zod,`optin`,()=>t.innerType._zod.optin),Ou(e._zod,`optout`,()=>t.innerType._zod.optout),Ou(e._zod,`pattern`,()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${Eu(e.source)}|null)$`):void 0}),Ou(e._zod,`values`,()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(e,n)=>e.value===null?e:t.innerType._zod.run(e,n)}),up=j(`$ZodDefault`,(e,t)=>{uf.init(e,t),e._zod.optin=`optional`,Ou(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if(e.value===void 0)return e.value=t.defaultValue,e;let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(e=>dp(e,t)):dp(r,t)}});function dp(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}var fp=j(`$ZodPrefault`,(e,t)=>{uf.init(e,t),e._zod.optin=`optional`,Ou(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>(e.value===void 0&&(e.value=t.defaultValue),t.innerType._zod.run(e,n))}),pp=j(`$ZodNonOptional`,(e,t)=>{uf.init(e,t),Ou(e._zod,`values`,()=>{let e=t.innerType._zod.values;return e?new Set([...e].filter(e=>e!==void 0)):void 0}),e._zod.parse=(n,r)=>{let i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(t=>mp(t,e)):mp(i,e)}});function mp(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:`invalid_type`,expected:`nonoptional`,input:e.value,inst:t}),e}var hp=j(`$ZodCatch`,(e,t)=>{uf.init(e,t),e._zod.optin=`optional`,Ou(e._zod,`optout`,()=>t.innerType._zod.optout),Ou(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(r=>(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>Yu(e,n,xu()))},input:e.value}),e.issues=[]),e)):(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>Yu(e,n,xu()))},input:e.value}),e.issues=[]),e)}}),gp=j(`$ZodPipe`,(e,t)=>{uf.init(e,t),Ou(e._zod,`values`,()=>t.in._zod.values),Ou(e._zod,`optin`,()=>t.in._zod.optin),Ou(e._zod,`optout`,()=>t.out._zod.optout),e._zod.parse=(e,n)=>{let r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>_p(e,t,n)):_p(r,t,n)}});function _p(e,t,n){return Ku(e)?e:t.out._zod.run({value:e.value,issues:e.issues},n)}var vp=j(`$ZodReadonly`,(e,t)=>{uf.init(e,t),Ou(e._zod,`propValues`,()=>t.innerType._zod.propValues),Ou(e._zod,`values`,()=>t.innerType._zod.values),Ou(e._zod,`optin`,()=>t.innerType._zod.optin),Ou(e._zod,`optout`,()=>t.innerType._zod.optout),e._zod.parse=(e,n)=>{let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(yp):yp(r)}});function yp(e){return e.value=Object.freeze(e.value),e}var bp=j(`$ZodCustom`,(e,t)=>{Wd.init(e,t),uf.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=n=>{let r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then(t=>xp(t,n,r,e));xp(i,n,r,e)}});function xp(e,t,n,r){if(!e){let e={code:`custom`,input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(e.params=r._zod.def.params),t.issues.push(Zu(e))}}var Sp=class{constructor(){this._map=new Map,this._idmap=new Map}add(e,...t){let n=t[0];if(this._map.set(e,n),n&&typeof n==`object`&&`id`in n){if(this._idmap.has(n.id))throw Error(`ID ${n.id} already exists in the registry`);this._idmap.set(n.id,e)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(e){let t=this._map.get(e);return t&&typeof t==`object`&&`id`in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let n={...this.get(t)??{}};return delete n.id,{...n,...this._map.get(e)}}return this._map.get(e)}has(e){return this._map.has(e)}};function Cp(){return new Sp}var wp=Cp();function Tp(e,t){return new e({type:`string`,...M(t)})}function Ep(e,t){return new e({type:`string`,format:`email`,check:`string_format`,abort:!1,...M(t)})}function Dp(e,t){return new e({type:`string`,format:`guid`,check:`string_format`,abort:!1,...M(t)})}function Op(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,...M(t)})}function kp(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v4`,...M(t)})}function Ap(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v6`,...M(t)})}function jp(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v7`,...M(t)})}function Mp(e,t){return new e({type:`string`,format:`url`,check:`string_format`,abort:!1,...M(t)})}function Np(e,t){return new e({type:`string`,format:`emoji`,check:`string_format`,abort:!1,...M(t)})}function Pp(e,t){return new e({type:`string`,format:`nanoid`,check:`string_format`,abort:!1,...M(t)})}function Fp(e,t){return new e({type:`string`,format:`cuid`,check:`string_format`,abort:!1,...M(t)})}function Ip(e,t){return new e({type:`string`,format:`cuid2`,check:`string_format`,abort:!1,...M(t)})}function Lp(e,t){return new e({type:`string`,format:`ulid`,check:`string_format`,abort:!1,...M(t)})}function Rp(e,t){return new e({type:`string`,format:`xid`,check:`string_format`,abort:!1,...M(t)})}function zp(e,t){return new e({type:`string`,format:`ksuid`,check:`string_format`,abort:!1,...M(t)})}function Bp(e,t){return new e({type:`string`,format:`ipv4`,check:`string_format`,abort:!1,...M(t)})}function Vp(e,t){return new e({type:`string`,format:`ipv6`,check:`string_format`,abort:!1,...M(t)})}function Hp(e,t){return new e({type:`string`,format:`cidrv4`,check:`string_format`,abort:!1,...M(t)})}function Up(e,t){return new e({type:`string`,format:`cidrv6`,check:`string_format`,abort:!1,...M(t)})}function Wp(e,t){return new e({type:`string`,format:`base64`,check:`string_format`,abort:!1,...M(t)})}function Gp(e,t){return new e({type:`string`,format:`base64url`,check:`string_format`,abort:!1,...M(t)})}function Kp(e,t){return new e({type:`string`,format:`e164`,check:`string_format`,abort:!1,...M(t)})}function qp(e,t){return new e({type:`string`,format:`jwt`,check:`string_format`,abort:!1,...M(t)})}function Jp(e,t){return new e({type:`string`,format:`datetime`,check:`string_format`,offset:!1,local:!1,precision:null,...M(t)})}function Yp(e,t){return new e({type:`string`,format:`date`,check:`string_format`,...M(t)})}function Xp(e,t){return new e({type:`string`,format:`time`,check:`string_format`,precision:null,...M(t)})}function Zp(e,t){return new e({type:`string`,format:`duration`,check:`string_format`,...M(t)})}function Qp(e,t){return new e({type:`number`,checks:[],...M(t)})}function $p(e,t){return new e({type:`number`,check:`number_format`,abort:!1,format:`safeint`,...M(t)})}function em(e,t){return new e({type:`boolean`,...M(t)})}function tm(e){return new e({type:`any`})}function nm(e){return new e({type:`unknown`})}function rm(e,t){return new e({type:`never`,...M(t)})}function im(e,t){return new Kd({check:`less_than`,...M(t),value:e,inclusive:!1})}function am(e,t){return new Kd({check:`less_than`,...M(t),value:e,inclusive:!0})}function om(e,t){return new qd({check:`greater_than`,...M(t),value:e,inclusive:!1})}function sm(e,t){return new qd({check:`greater_than`,...M(t),value:e,inclusive:!0})}function cm(e,t){return new Jd({check:`multiple_of`,...M(t),value:e})}function lm(e,t){return new Xd({check:`max_length`,...M(t),maximum:e})}function um(e,t){return new Zd({check:`min_length`,...M(t),minimum:e})}function dm(e,t){return new Qd({check:`length_equals`,...M(t),length:e})}function fm(e,t){return new ef({check:`string_format`,format:`regex`,...M(t),pattern:e})}function pm(e){return new tf({check:`string_format`,format:`lowercase`,...M(e)})}function mm(e){return new nf({check:`string_format`,format:`uppercase`,...M(e)})}function hm(e,t){return new rf({check:`string_format`,format:`includes`,...M(t),includes:e})}function gm(e,t){return new af({check:`string_format`,format:`starts_with`,...M(t),prefix:e})}function _m(e,t){return new of({check:`string_format`,format:`ends_with`,...M(t),suffix:e})}function vm(e){return new sf({check:`overwrite`,tx:e})}function ym(e){return vm(t=>t.normalize(e))}function bm(){return vm(e=>e.trim())}function xm(){return vm(e=>e.toLowerCase())}function Sm(){return vm(e=>e.toUpperCase())}function Cm(e,t,n){return new e({type:`array`,element:t,...M(n)})}function wm(e,t,n){let r=M(n);return r.abort??=!0,new e({type:`custom`,check:`custom`,fn:t,...r})}function Tm(e,t,n){return new e({type:`custom`,check:`custom`,fn:t,...M(n)})}var Em=class{constructor(e){this.counter=0,this.metadataRegistry=e?.metadata??wp,this.target=e?.target??`draft-2020-12`,this.unrepresentable=e?.unrepresentable??`throw`,this.override=e?.override??(()=>{}),this.io=e?.io??`output`,this.seen=new Map}process(e,t={path:[],schemaPath:[]}){var n;let r=e._zod.def,i={guid:`uuid`,url:`uri`,datetime:`date-time`,json_string:`json-string`,regex:``},a=this.seen.get(e);if(a)return a.count++,t.schemaPath.includes(e)&&(a.cycle=t.path),a.schema;let o={schema:{},count:1,cycle:void 0,path:t.path};this.seen.set(e,o);let s=e._zod.toJSONSchema?.();if(s)o.schema=s;else{let n={...t,schemaPath:[...t.schemaPath,e],path:t.path},a=e._zod.parent;if(a)o.ref=a,this.process(a,n),this.seen.get(a).isParent=!0;else{let t=o.schema;switch(r.type){case`string`:{let n=t;n.type=`string`;let{minimum:r,maximum:a,format:s,patterns:c,contentEncoding:l}=e._zod.bag;if(typeof r==`number`&&(n.minLength=r),typeof a==`number`&&(n.maxLength=a),s&&(n.format=i[s]??s,n.format===``&&delete n.format),l&&(n.contentEncoding=l),c&&c.size>0){let e=[...c];e.length===1?n.pattern=e[0].source:e.length>1&&(o.schema.allOf=[...e.map(e=>({...this.target===`draft-7`?{type:`string`}:{},pattern:e.source}))])}break}case`number`:{let n=t,{minimum:r,maximum:i,format:a,multipleOf:o,exclusiveMaximum:s,exclusiveMinimum:c}=e._zod.bag;typeof a==`string`&&a.includes(`int`)?n.type=`integer`:n.type=`number`,typeof c==`number`&&(n.exclusiveMinimum=c),typeof r==`number`&&(n.minimum=r,typeof c==`number`&&(c>=r?delete n.minimum:delete n.exclusiveMinimum)),typeof s==`number`&&(n.exclusiveMaximum=s),typeof i==`number`&&(n.maximum=i,typeof s==`number`&&(s<=i?delete n.maximum:delete n.exclusiveMaximum)),typeof o==`number`&&(n.multipleOf=o);break}case`boolean`:{let e=t;e.type=`boolean`;break}case`bigint`:if(this.unrepresentable===`throw`)throw Error(`BigInt cannot be represented in JSON Schema`);break;case`symbol`:if(this.unrepresentable===`throw`)throw Error(`Symbols cannot be represented in JSON Schema`);break;case`null`:t.type=`null`;break;case`any`:break;case`unknown`:break;case`undefined`:if(this.unrepresentable===`throw`)throw Error(`Undefined cannot be represented in JSON Schema`);break;case`void`:if(this.unrepresentable===`throw`)throw Error(`Void cannot be represented in JSON Schema`);break;case`never`:t.not={};break;case`date`:if(this.unrepresentable===`throw`)throw Error(`Date cannot be represented in JSON Schema`);break;case`array`:{let i=t,{minimum:a,maximum:o}=e._zod.bag;typeof a==`number`&&(i.minItems=a),typeof o==`number`&&(i.maxItems=o),i.type=`array`,i.items=this.process(r.element,{...n,path:[...n.path,`items`]});break}case`object`:{let e=t;e.type=`object`,e.properties={};let i=r.shape;for(let t in i)e.properties[t]=this.process(i[t],{...n,path:[...n.path,`properties`,t]});let a=new Set(Object.keys(i)),o=new Set([...a].filter(e=>{let t=r.shape[e]._zod;return this.io===`input`?t.optin===void 0:t.optout===void 0}));o.size>0&&(e.required=Array.from(o)),r.catchall?._zod.def.type===`never`?e.additionalProperties=!1:r.catchall?r.catchall&&(e.additionalProperties=this.process(r.catchall,{...n,path:[...n.path,`additionalProperties`]})):this.io===`output`&&(e.additionalProperties=!1);break}case`union`:{let e=t;e.anyOf=r.options.map((e,t)=>this.process(e,{...n,path:[...n.path,`anyOf`,t]}));break}case`intersection`:{let e=t,i=this.process(r.left,{...n,path:[...n.path,`allOf`,0]}),a=this.process(r.right,{...n,path:[...n.path,`allOf`,1]}),o=e=>`allOf`in e&&Object.keys(e).length===1;e.allOf=[...o(i)?i.allOf:[i],...o(a)?a.allOf:[a]];break}case`tuple`:{let i=t;i.type=`array`;let a=r.items.map((e,t)=>this.process(e,{...n,path:[...n.path,`prefixItems`,t]}));if(this.target===`draft-2020-12`?i.prefixItems=a:i.items=a,r.rest){let e=this.process(r.rest,{...n,path:[...n.path,`items`]});this.target===`draft-2020-12`?i.items=e:i.additionalItems=e}r.rest&&(i.items=this.process(r.rest,{...n,path:[...n.path,`items`]}));let{minimum:o,maximum:s}=e._zod.bag;typeof o==`number`&&(i.minItems=o),typeof s==`number`&&(i.maxItems=s);break}case`record`:{let e=t;e.type=`object`,e.propertyNames=this.process(r.keyType,{...n,path:[...n.path,`propertyNames`]}),e.additionalProperties=this.process(r.valueType,{...n,path:[...n.path,`additionalProperties`]});break}case`map`:if(this.unrepresentable===`throw`)throw Error(`Map cannot be represented in JSON Schema`);break;case`set`:if(this.unrepresentable===`throw`)throw Error(`Set cannot be represented in JSON Schema`);break;case`enum`:{let e=t,n=Su(r.entries);n.every(e=>typeof e==`number`)&&(e.type=`number`),n.every(e=>typeof e==`string`)&&(e.type=`string`),e.enum=n;break}case`literal`:{let e=t,n=[];for(let e of r.values)if(e===void 0){if(this.unrepresentable===`throw`)throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof e==`bigint`){if(this.unrepresentable===`throw`)throw Error(`BigInt literals cannot be represented in JSON Schema`);n.push(Number(e))}else n.push(e);if(n.length!==0)if(n.length===1){let t=n[0];e.type=t===null?`null`:typeof t,e.const=t}else n.every(e=>typeof e==`number`)&&(e.type=`number`),n.every(e=>typeof e==`string`)&&(e.type=`string`),n.every(e=>typeof e==`boolean`)&&(e.type=`string`),n.every(e=>e===null)&&(e.type=`null`),e.enum=n;break}case`file`:{let n=t,r={type:`string`,format:`binary`,contentEncoding:`binary`},{minimum:i,maximum:a,mime:o}=e._zod.bag;i!==void 0&&(r.minLength=i),a!==void 0&&(r.maxLength=a),o?o.length===1?(r.contentMediaType=o[0],Object.assign(n,r)):n.anyOf=o.map(e=>({...r,contentMediaType:e})):Object.assign(n,r);break}case`transform`:if(this.unrepresentable===`throw`)throw Error(`Transforms cannot be represented in JSON Schema`);break;case`nullable`:t.anyOf=[this.process(r.innerType,n),{type:`null`}];break;case`nonoptional`:this.process(r.innerType,n),o.ref=r.innerType;break;case`success`:{let e=t;e.type=`boolean`;break}case`default`:this.process(r.innerType,n),o.ref=r.innerType,t.default=JSON.parse(JSON.stringify(r.defaultValue));break;case`prefault`:this.process(r.innerType,n),o.ref=r.innerType,this.io===`input`&&(t._prefault=JSON.parse(JSON.stringify(r.defaultValue)));break;case`catch`:{this.process(r.innerType,n),o.ref=r.innerType;let e;try{e=r.catchValue(void 0)}catch{throw Error(`Dynamic catch values are not supported in JSON Schema`)}t.default=e;break}case`nan`:if(this.unrepresentable===`throw`)throw Error(`NaN cannot be represented in JSON Schema`);break;case`template_literal`:{let n=t,r=e._zod.pattern;if(!r)throw Error(`Pattern not found in template literal`);n.type=`string`,n.pattern=r.source;break}case`pipe`:{let e=this.io===`input`?r.in._zod.def.type===`transform`?r.out:r.in:r.out;this.process(e,n),o.ref=e;break}case`readonly`:this.process(r.innerType,n),o.ref=r.innerType,t.readOnly=!0;break;case`promise`:this.process(r.innerType,n),o.ref=r.innerType;break;case`optional`:this.process(r.innerType,n),o.ref=r.innerType;break;case`lazy`:{let t=e._zod.innerType;this.process(t,n),o.ref=t;break}case`custom`:if(this.unrepresentable===`throw`)throw Error(`Custom types cannot be represented in JSON Schema`);break;default:}}}let c=this.metadataRegistry.get(e);return c&&Object.assign(o.schema,c),this.io===`input`&&Om(e)&&(delete o.schema.examples,delete o.schema.default),this.io===`input`&&o.schema._prefault&&((n=o.schema).default??(n.default=o.schema._prefault)),delete o.schema._prefault,this.seen.get(e).schema}emit(e,t){let n={cycles:t?.cycles??`ref`,reused:t?.reused??`inline`,external:t?.external??void 0},r=this.seen.get(e);if(!r)throw Error(`Unprocessed schema. This is a bug in Zod.`);let i=e=>{let t=this.target===`draft-2020-12`?`$defs`:`definitions`;if(n.external){let r=n.external.registry.get(e[0])?.id,i=n.external.uri??(e=>e);if(r)return{ref:i(r)};let a=e[1].defId??e[1].schema.id??`schema${this.counter++}`;return e[1].defId=a,{defId:a,ref:`${i(`__shared`)}#/${t}/${a}`}}if(e[1]===r)return{ref:`#`};let i=`#/${t}/`,a=e[1].schema.id??`__schema${this.counter++}`;return{defId:a,ref:i+a}},a=e=>{if(e[1].schema.$ref)return;let t=e[1],{ref:n,defId:r}=i(e);t.def={...t.schema},r&&(t.defId=r);let a=t.schema;for(let e in a)delete a[e];a.$ref=n};if(n.cycles===`throw`)for(let e of this.seen.entries()){let t=e[1];if(t.cycle)throw Error(`Cycle detected: #/${t.cycle?.join(`/`)}/<root>
52
-
53
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let t of this.seen.entries()){let r=t[1];if(e===t[0]){a(t);continue}if(n.external){let r=n.external.registry.get(t[0])?.id;if(e!==t[0]&&r){a(t);continue}}if(this.metadataRegistry.get(t[0])?.id){a(t);continue}if(r.cycle){a(t);continue}if(r.count>1&&n.reused===`ref`){a(t);continue}}let o=(e,t)=>{let n=this.seen.get(e),r=n.def??n.schema,i={...r};if(n.ref===null)return;let a=n.ref;if(n.ref=null,a){o(a,t);let e=this.seen.get(a).schema;e.$ref&&t.target===`draft-7`?(r.allOf=r.allOf??[],r.allOf.push(e)):(Object.assign(r,e),Object.assign(r,i))}n.isParent||this.override({zodSchema:e,jsonSchema:r,path:n.path??[]})};for(let e of[...this.seen.entries()].reverse())o(e[0],{target:this.target});let s={};if(this.target===`draft-2020-12`?s.$schema=`https://json-schema.org/draft/2020-12/schema`:this.target===`draft-7`?s.$schema=`http://json-schema.org/draft-07/schema#`:console.warn(`Invalid target: ${this.target}`),n.external?.uri){let t=n.external.registry.get(e)?.id;if(!t)throw Error("Schema is missing an `id` property");s.$id=n.external.uri(t)}Object.assign(s,r.def);let c=n.external?.defs??{};for(let e of this.seen.entries()){let t=e[1];t.def&&t.defId&&(c[t.defId]=t.def)}n.external||Object.keys(c).length>0&&(this.target===`draft-2020-12`?s.$defs=c:s.definitions=c);try{return JSON.parse(JSON.stringify(s))}catch{throw Error(`Error converting schema to JSON.`)}}};function Dm(e,t){if(e instanceof Sp){let n=new Em(t),r={};for(let t of e._idmap.entries()){let[e,r]=t;n.process(r)}let i={},a={registry:e,uri:t?.uri,defs:r};for(let r of e._idmap.entries()){let[e,o]=r;i[e]=n.emit(o,{...t,external:a})}return Object.keys(r).length>0&&(i.__shared={[n.target===`draft-2020-12`?`$defs`:`definitions`]:r}),{schemas:i}}let n=new Em(t);return n.process(e),n.emit(e,t)}function Om(e,t){let n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);let r=e._zod.def;switch(r.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 Om(r.element,n);case`object`:for(let e in r.shape)if(Om(r.shape[e],n))return!0;return!1;case`union`:for(let e of r.options)if(Om(e,n))return!0;return!1;case`intersection`:return Om(r.left,n)||Om(r.right,n);case`tuple`:for(let e of r.items)if(Om(e,n))return!0;return!!(r.rest&&Om(r.rest,n));case`record`:return Om(r.keyType,n)||Om(r.valueType,n);case`map`:return Om(r.keyType,n)||Om(r.valueType,n);case`set`:return Om(r.valueType,n);case`promise`:case`optional`:case`nonoptional`:case`nullable`:case`readonly`:return Om(r.innerType,n);case`lazy`:return Om(r.getter(),n);case`default`:return Om(r.innerType,n);case`prefault`:return Om(r.innerType,n);case`custom`:return!1;case`transform`:return!0;case`pipe`:return Om(r.in,n)||Om(r.out,n);case`success`:return!1;case`catch`:return!1;default:}throw Error(`Unknown schema type: ${r.type}`)}function km(e){if(typeof e!=`object`||!e)return!1;let t=e;if(!(`_zod`in t))return!1;let n=t._zod;return typeof n==`object`&&!!n&&`def`in n}function Am(e){if(typeof e!=`object`||!e)return!1;let t=e;if(!(`_def`in t)||`_zod`in t)return!1;let n=t._def;return typeof n==`object`&&!!n&&`typeName`in n}function jm(e){return km(e)&&console.warn(`[WARNING] Attempting to use Zod 4 schema in a context where Zod 3 schema is expected. This may cause unexpected behavior.`),Am(e)}function Mm(e){return!e||typeof e!=`object`||Array.isArray(e)?!1:!!(km(e)||Am(e))}function Nm(e){return!!(typeof e==`object`&&e&&`_def`in e&&typeof e._def==`object`&&e._def!==null&&`typeName`in e._def&&e._def.typeName===`ZodLiteral`)}function Pm(e){return km(e)?!!(typeof e==`object`&&e&&`_zod`in e&&typeof e._zod==`object`&&e._zod!==null&&`def`in e._zod&&typeof e._zod.def==`object`&&e._zod.def!==null&&`type`in e._zod.def&&e._zod.def.type===`literal`):!1}function Fm(e){return!!(Nm(e)||Pm(e))}async function Im(e,t){if(km(e))try{return{success:!0,data:await cd(e,t)}}catch(e){return{success:!1,error:e}}if(Am(e))return await e.safeParseAsync(t);throw Error(`Schema must be an instance of z3.ZodType or z4.$ZodType`)}async function Lm(e,t){if(km(e))return await cd(e,t);if(Am(e))return await e.parseAsync(t);throw Error(`Schema must be an instance of z3.ZodType or z4.$ZodType`)}function Rm(e,t){if(km(e))try{return{success:!0,data:od(e,t)}}catch(e){return{success:!1,error:e}}if(Am(e))return e.safeParse(t);throw Error(`Schema must be an instance of z3.ZodType or z4.$ZodType`)}function zm(e,t){if(km(e))return od(e,t);if(Am(e))return e.parse(t);throw Error(`Schema must be an instance of z3.ZodType or z4.$ZodType`)}function Bm(e){if(km(e))return wp.get(e)?.description;if(Am(e)||`description`in e&&typeof e.description==`string`)return e.description}function Vm(e){if(!Mm(e))return!1;if(Am(e)){let t=e._def;if(t.typeName===`ZodObject`){let t=e;return!t.shape||Object.keys(t.shape).length===0}if(t.typeName===`ZodRecord`)return!0}if(km(e)){let t=e._zod.def;if(t.type===`object`){let t=e;return!t.shape||Object.keys(t.shape).length===0}if(t.type===`record`)return!0}return!!(typeof e==`object`&&e&&!(`shape`in e))}function Hm(e){return Mm(e)?Am(e)?e._def.typeName===`ZodString`:km(e)?e._zod.def.type===`string`:!1:!1}function Um(e){return!!(typeof e==`object`&&e&&`_def`in e&&typeof e._def==`object`&&e._def!==null&&`typeName`in e._def&&e._def.typeName===`ZodObject`)}function Wm(e){return km(e)?!!(typeof e==`object`&&e&&`_zod`in e&&typeof e._zod==`object`&&e._zod!==null&&`def`in e._zod&&typeof e._zod.def==`object`&&e._zod.def!==null&&`type`in e._zod.def&&e._zod.def.type===`object`):!1}function Gm(e){return km(e)?!!(typeof e==`object`&&e&&`_zod`in e&&typeof e._zod==`object`&&e._zod!==null&&`def`in e._zod&&typeof e._zod.def==`object`&&e._zod.def!==null&&`type`in e._zod.def&&e._zod.def.type===`array`):!1}function Km(e){return km(e)?!!(typeof e==`object`&&e&&`_zod`in e&&typeof e._zod==`object`&&e._zod!==null&&`def`in e._zod&&typeof e._zod.def==`object`&&e._zod.def!==null&&`type`in e._zod.def&&e._zod.def.type===`optional`):!1}function qm(e){return km(e)?!!(typeof e==`object`&&e&&`_zod`in e&&typeof e._zod==`object`&&e._zod!==null&&`def`in e._zod&&typeof e._zod.def==`object`&&e._zod.def!==null&&`type`in e._zod.def&&e._zod.def.type===`nullable`):!1}function Jm(e){return!!(Um(e)||Wm(e))}function Ym(e){if(Am(e))return e.shape;if(km(e))return e._zod.def.shape;throw Error(`Schema must be an instance of z3.ZodObject or z4.$ZodObject`)}function Xm(e,t){if(Am(e))return e.extend(t);if(km(e))return Hu(e,t);throw Error(`Schema must be an instance of z3.ZodObject or z4.$ZodObject`)}function Zm(e){if(Am(e))return e.partial();if(km(e))return Wu(cp,e,void 0);throw Error(`Schema must be an instance of z3.ZodObject or z4.$ZodObject`)}function Qm(e,t=!1){if(Um(e))return e.strict();if(Wm(e)){let n=e._zod.def.shape;if(t)for(let[r,i]of Object.entries(e._zod.def.shape)){if(Wm(i))n[r]=Qm(i,t);else if(Gm(i)){let e=i._zod.def.element;Wm(e)&&(e=Qm(e,t)),n[r]=Lu(i,{...i._zod.def,element:e})}else n[r]=i;let e=wp.get(i);e&&wp.add(n[r],e)}let r=Lu(e,{...e._zod.def,shape:n,catchall:rm(Wf)}),i=wp.get(e);return i&&wp.add(r,i),r}throw Error(`Schema must be an instance of z3.ZodObject or z4.$ZodObject`)}function $m(e,t=!1){if(Um(e))return e.passthrough();if(Wm(e)){let n=e._zod.def.shape;if(t)for(let[r,i]of Object.entries(e._zod.def.shape)){if(Wm(i))n[r]=$m(i,t);else if(Gm(i)){let e=i._zod.def.element;Wm(e)&&(e=$m(e,t)),n[r]=Lu(i,{...i._zod.def,element:e})}else n[r]=i;let e=wp.get(i);e&&wp.add(n[r],e)}let r=Lu(e,{...e._zod.def,shape:n,catchall:nm(Uf)}),i=wp.get(e);return i&&wp.add(r,i),r}throw Error(`Schema must be an instance of z3.ZodObject or z4.$ZodObject`)}function eh(e){if(Am(e))try{let t=e.parse(void 0);return()=>t}catch{return}if(km(e))try{let t=od(e,void 0);return()=>t}catch{return}}function th(e){return Am(e)&&`typeName`in e._def&&e._def.typeName===`ZodEffects`}function nh(e){return km(e)&&e._zod.def.type===`pipe`}function rh(e,t,n){let r=n.get(e);if(r!==void 0)return r;if(Am(e))return th(e)?rh(e._def.schema,t,n):e;if(km(e)){let r=e;if(nh(e)&&(r=rh(e._zod.def.in,t,n)),t){if(Wm(r)){let e={};for(let[i,a]of Object.entries(r._zod.def.shape))e[i]=rh(a,t,n);r=Lu(r,{...r._zod.def,shape:e})}else if(Gm(r)){let e=rh(r._zod.def.element,t,n);r=Lu(r,{...r._zod.def,element:e})}else if(Km(r)){let e=rh(r._zod.def.innerType,t,n);r=Lu(r,{...r._zod.def,innerType:e})}else if(qm(r)){let e=rh(r._zod.def.innerType,t,n);r=Lu(r,{...r._zod.def,innerType:e})}}let i=wp.get(e);return i&&wp.add(r,i),n.set(e,r),r}throw Error(`Schema must be an instance of z3.ZodType or z4.$ZodType`)}function ih(e,t=!1){return rh(e,t,new WeakMap)}function ah(e,t){if(Am(e)){let n=Ym(e),r={};for(let[e,i]of Object.entries(n))t(e,i)?r[e]=i.optional():r[e]=i;return e.extend(r)}if(km(e)){let n=Ym(e),r={...e._zod.def.shape};for(let[e,i]of Object.entries(n))t(e,i)&&(r[e]=new cp({type:`optional`,innerType:i}));let i=Lu(e,{...e._zod.def,shape:r}),a=wp.get(e);return a&&wp.add(i,a),i}throw Error(`Schema must be an instance of z3.ZodObject or z4.$ZodObject`)}function oh(e){return e instanceof Error&&(e.constructor.name===`ZodError`||e.constructor.name===`$ZodError`)}function sh(e){return e.replace(/[^a-zA-Z-_0-9]/g,`_`)}var ch=[`*`,`_`,"`"];function lh(e){let t=``;for(let[n,r]of Object.entries(e))t+=`\tclassDef ${n} ${r};\n`;return t}function uh(e,t,n){let{firstNode:r,lastNode:i,nodeColors:a,withStyles:o=!0,curveStyle:s=`linear`,wrapLabelNWords:c=9}=n??{},l=o?`%%{init: {'flowchart': {'curve': '${s}'}}}%%\ngraph TD;\n`:`graph TD;
54
- `;if(o){let t=`default`,n={[t]:`{0}({1})`};r!==void 0&&(n[r]=`{0}([{1}]):::first`),i!==void 0&&(n[i]=`{0}([{1}]):::last`);for(let[r,i]of Object.entries(e)){let e=i.name.split(`:`).pop()??``,a=ch.some(t=>e.startsWith(t)&&e.endsWith(t))?`<p>${e}</p>`:e;Object.keys(i.metadata??{}).length&&(a+=`<hr/><small><em>${Object.entries(i.metadata??{}).map(([e,t])=>`${e} = ${t}`).join(`
55
- `)}</em></small>`);let o=(n[r]??n[t]).replace(`{0}`,sh(r)).replace(`{1}`,a);l+=`\t${o}\n`}}let u={};for(let e of t){let t=e.source.split(`:`),n=e.target.split(`:`),r=t.filter((e,t)=>e===n[t]).join(`:`);u[r]||(u[r]=[]),u[r].push(e)}let d=new Set;function f(e){return[...e].sort((e,t)=>e.split(`:`).length-t.split(`:`).length)}function p(e,t){let n=e.length===1&&e[0].source===e[0].target;if(t&&!n){let e=t.split(`:`).pop();if(d.has(t))throw Error(`Found duplicate subgraph '${e}' at '${t} -- 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(t),l+=`\tsubgraph ${e}\n`}let r=f(Object.keys(u).filter(e=>e.startsWith(`${t}:`)&&e!==t&&e.split(`:`).length===t.split(`:`).length+1));for(let e of r)p(u[e],e);for(let t of e){let{source:e,target:n,data:r,conditional:i}=t,a=``;if(r!==void 0){let e=r,t=e.split(` `);t.length>c&&(e=Array.from({length:Math.ceil(t.length/c)},(e,n)=>t.slice(n*c,(n+1)*c).join(` `)).join(`&nbsp;<br>&nbsp;`)),a=i?` -. &nbsp;${e}&nbsp; .-> `:` -- &nbsp;${e}&nbsp; --> `}else a=i?` -.-> `:` --> `;l+=`\t${sh(e)}${a}${sh(n)};\n`}t&&!n&&(l+=` end
56
- `)}p(u[``]??[],``);for(let e in u)!e.includes(`:`)&&e!==``&&p(u[e],e);return o&&(l+=lh(a??{})),l}async function dh(e,t){let n=t?.backgroundColor??`white`,r=t?.imageType??`png`,i=vu(e);n!==void 0&&(/^#(?:[0-9a-fA-F]{3}){1,2}$/.test(n)||(n=`!${n}`));let a=`https://mermaid.ink/img/${i}?bgColor=${n}&type=${r}`,o=await fetch(a);if(!o.ok)throw Error([`Failed to render the graph using the Mermaid.INK API.`,`Status code: ${o.status}`,`Status text: ${o.statusText}`].join(`
57
- `));return await o.blob()}var fh=Symbol(`Let zodToJsonSchema decide on which parser to use`),ph={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`},mh=e=>typeof e==`string`?{...ph,name:e}:{...ph,...e},hh=e=>{let t=mh(e),n=t.name===void 0?t.basePath:[...t.basePath,t.definitionPath,t.name];return{...t,flags:{hasReferencedOpenAiAnyType:!1},currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([e,n])=>[n._def,{def:n._def,path:[...t.basePath,t.definitionPath,e],jsonSchema:void 0}]))}},gh=(e,t)=>{let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];n++);return[(e.length-n).toString(),...t.slice(n)].join(`/`)};function _h(e){if(e.target!==`openAi`)return{};let t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy===`relative`?gh(t,e.currentPath):t.join(`/`)}}function vh(e,t,n,r){r?.errorMessages&&n&&(e.errorMessage={...e.errorMessage,[t]:n})}function yh(e,t,n,r,i){e[t]=n,vh(e,t,r,i)}var bh;(function(e){e.assertEqual=e=>{};function t(e){}e.assertIs=t;function n(e){throw Error()}e.assertNever=n,e.arrayToEnum=e=>{let t={};for(let n of e)t[n]=n;return t},e.getValidEnumValues=t=>{let n=e.objectKeys(t).filter(e=>typeof t[t[e]]!=`number`),r={};for(let e of n)r[e]=t[e];return e.objectValues(r)},e.objectValues=t=>e.objectKeys(t).map(function(e){return t[e]}),e.objectKeys=typeof Object.keys==`function`?e=>Object.keys(e):e=>{let t=[];for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.push(n);return t},e.find=(e,t)=>{for(let n of e)if(t(n))return n},e.isInteger=typeof Number.isInteger==`function`?e=>Number.isInteger(e):e=>typeof e==`number`&&Number.isFinite(e)&&Math.floor(e)===e;function r(e,t=` | `){return e.map(e=>typeof e==`string`?`'${e}'`:e).join(t)}e.joinValues=r,e.jsonStringifyReplacer=(e,t)=>typeof t==`bigint`?t.toString():t})(bh||={});var xh;(function(e){e.mergeShapes=(e,t)=>({...e,...t})})(xh||={});var N=bh.arrayToEnum([`string`,`nan`,`number`,`integer`,`float`,`boolean`,`date`,`bigint`,`symbol`,`function`,`undefined`,`null`,`array`,`object`,`unknown`,`promise`,`void`,`never`,`map`,`set`]),Sh=e=>{switch(typeof e){case`undefined`:return N.undefined;case`string`:return N.string;case`number`:return Number.isNaN(e)?N.nan:N.number;case`boolean`:return N.boolean;case`function`:return N.function;case`bigint`:return N.bigint;case`symbol`:return N.symbol;case`object`:return Array.isArray(e)?N.array:e===null?N.null:e.then&&typeof e.then==`function`&&e.catch&&typeof e.catch==`function`?N.promise:typeof Map<`u`&&e instanceof Map?N.map:typeof Set<`u`&&e instanceof Set?N.set:typeof Date<`u`&&e instanceof Date?N.date:N.object;default:return N.unknown}},P=bh.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`]),Ch=class e extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name=`ZodError`,this.issues=e}format(e){let t=e||function(e){return e.message},n={_errors:[]},r=e=>{for(let i of e.issues)if(i.code===`invalid_union`)i.unionErrors.map(r);else if(i.code===`invalid_return_type`)r(i.returnTypeError);else if(i.code===`invalid_arguments`)r(i.argumentsError);else if(i.path.length===0)n._errors.push(t(i));else{let e=n,r=0;for(;r<i.path.length;){let n=i.path[r];r===i.path.length-1?(e[n]=e[n]||{_errors:[]},e[n]._errors.push(t(i))):e[n]=e[n]||{_errors:[]},e=e[n],r++}}};return r(this),n}static assert(t){if(!(t instanceof e))throw Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,bh.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=e=>e.message){let t={},n=[];for(let r of this.issues)if(r.path.length>0){let n=r.path[0];t[n]=t[n]||[],t[n].push(e(r))}else n.push(e(r));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}};Ch.create=e=>new Ch(e);var wh=(e,t)=>{let n;switch(e.code){case P.invalid_type:n=e.received===N.undefined?`Required`:`Expected ${e.expected}, received ${e.received}`;break;case P.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,bh.jsonStringifyReplacer)}`;break;case P.unrecognized_keys:n=`Unrecognized key(s) in object: ${bh.joinValues(e.keys,`, `)}`;break;case P.invalid_union:n=`Invalid input`;break;case P.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${bh.joinValues(e.options)}`;break;case P.invalid_enum_value:n=`Invalid enum value. Expected ${bh.joinValues(e.options)}, received '${e.received}'`;break;case P.invalid_arguments:n=`Invalid function arguments`;break;case P.invalid_return_type:n=`Invalid function return type`;break;case P.invalid_date:n=`Invalid date`;break;case P.invalid_string:typeof e.validation==`object`?`includes`in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position==`number`&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):`startsWith`in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:`endsWith`in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:bh.assertNever(e.validation):n=e.validation===`regex`?`Invalid`:`Invalid ${e.validation}`;break;case P.too_small:n=e.type===`array`?`Array must contain ${e.exact?`exactly`:e.inclusive?`at least`:`more than`} ${e.minimum} element(s)`:e.type===`string`?`String must contain ${e.exact?`exactly`:e.inclusive?`at least`:`over`} ${e.minimum} character(s)`:e.type===`number`||e.type===`bigint`?`Number must be ${e.exact?`exactly equal to `:e.inclusive?`greater than or equal to `:`greater than `}${e.minimum}`:e.type===`date`?`Date must be ${e.exact?`exactly equal to `:e.inclusive?`greater than or equal to `:`greater than `}${new Date(Number(e.minimum))}`:`Invalid input`;break;case P.too_big:n=e.type===`array`?`Array must contain ${e.exact?`exactly`:e.inclusive?`at most`:`less than`} ${e.maximum} element(s)`:e.type===`string`?`String must contain ${e.exact?`exactly`:e.inclusive?`at most`:`under`} ${e.maximum} character(s)`:e.type===`number`?`Number must be ${e.exact?`exactly`:e.inclusive?`less than or equal to`:`less than`} ${e.maximum}`:e.type===`bigint`?`BigInt must be ${e.exact?`exactly`:e.inclusive?`less than or equal to`:`less than`} ${e.maximum}`:e.type===`date`?`Date must be ${e.exact?`exactly`:e.inclusive?`smaller than or equal to`:`smaller than`} ${new Date(Number(e.maximum))}`:`Invalid input`;break;case P.custom:n=`Invalid input`;break;case P.invalid_intersection_types:n=`Intersection results could not be merged`;break;case P.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case P.not_finite:n=`Number must be finite`;break;default:n=t.defaultError,bh.assertNever(e)}return{message:n}},Th=wh;function Eh(){return Th}var Dh=e=>{let{data:t,path:n,errorMaps:r,issueData:i}=e,a=[...n,...i.path||[]],o={...i,path:a};if(i.message!==void 0)return{...i,path:a,message:i.message};let s=``,c=r.filter(e=>!!e).slice().reverse();for(let e of c)s=e(o,{data:t,defaultError:s}).message;return{...i,path:a,message:s}};function F(e,t){let n=Eh(),r=Dh({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===wh?void 0:wh].filter(e=>!!e)});e.common.issues.push(r)}var Oh=class e{constructor(){this.value=`valid`}dirty(){this.value===`valid`&&(this.value=`dirty`)}abort(){this.value!==`aborted`&&(this.value=`aborted`)}static mergeArray(e,t){let n=[];for(let r of t){if(r.status===`aborted`)return I;r.status===`dirty`&&e.dirty(),n.push(r.value)}return{status:e.value,value:n}}static async mergeObjectAsync(t,n){let r=[];for(let e of n){let t=await e.key,n=await e.value;r.push({key:t,value:n})}return e.mergeObjectSync(t,r)}static mergeObjectSync(e,t){let n={};for(let r of t){let{key:t,value:i}=r;if(t.status===`aborted`||i.status===`aborted`)return I;t.status===`dirty`&&e.dirty(),i.status===`dirty`&&e.dirty(),t.value!==`__proto__`&&(i.value!==void 0||r.alwaysSet)&&(n[t.value]=i.value)}return{status:e.value,value:n}}},I=Object.freeze({status:`aborted`}),kh=e=>({status:`dirty`,value:e}),Ah=e=>({status:`valid`,value:e}),jh=e=>e.status===`aborted`,Mh=e=>e.status===`dirty`,Nh=e=>e.status===`valid`,Ph=e=>typeof Promise<`u`&&e instanceof Promise,L;(function(e){e.errToObj=e=>typeof e==`string`?{message:e}:e||{},e.toString=e=>typeof e==`string`?e:e?.message})(L||={});var Fh=class{constructor(e,t,n,r){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=r}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}},Ih=(e,t)=>{if(Nh(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw Error(`Validation failed but no issues detected.`);return{success:!1,get error(){if(this._error)return this._error;let t=new Ch(e.common.issues);return this._error=t,this._error}}};function R(e){if(!e)return{};let{errorMap:t,invalid_type_error:n,required_error:r,description:i}=e;if(t&&(n||r))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:i}:{errorMap:(t,i)=>{let{message:a}=e;return t.code===`invalid_enum_value`?{message:a??i.defaultError}:i.data===void 0?{message:a??r??i.defaultError}:t.code===`invalid_type`?{message:a??n??i.defaultError}:{message:i.defaultError}},description:i}}var Lh=class{get description(){return this._def.description}_getType(e){return Sh(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:Sh(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Oh,ctx:{common:e.parent.common,data:e.data,parsedType:Sh(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(Ph(t))throw Error(`Synchronous parse encountered promise.`);return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){let n={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Sh(e)};return Ih(n,this._parseSync({data:e,path:n.path,parent:n}))}"~validate"(e){let t={common:{issues:[],async:!!this[`~standard`].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Sh(e)};if(!this[`~standard`].async)try{let n=this._parseSync({data:e,path:[],parent:t});return Nh(n)?{value:n.value}:{issues:t.common.issues}}catch(e){e?.message?.toLowerCase()?.includes(`encountered`)&&(this[`~standard`].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(e=>Nh(e)?{value:e.value}:{issues:t.common.issues})}async parseAsync(e,t){let n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){let n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Sh(e)},r=this._parse({data:e,path:n.path,parent:n});return Ih(n,await(Ph(r)?r:Promise.resolve(r)))}refine(e,t){let n=e=>typeof t==`string`||t===void 0?{message:t}:typeof t==`function`?t(e):t;return this._refinement((t,r)=>{let i=e(t),a=()=>r.addIssue({code:P.custom,...n(t)});return typeof Promise<`u`&&i instanceof Promise?i.then(e=>e?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(e,t){return this._refinement((n,r)=>e(n)?!0:(r.addIssue(typeof t==`function`?t(n,r):t),!1))}_refinement(e){return new Bg({schema:this,typeName:z.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:e=>this[`~validate`](e)}}optional(){return Vg.create(this,this._def)}nullable(){return Hg.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return xg.create(this)}promise(){return zg.create(this,this._def)}or(e){return wg.create([this,e],this._def)}and(e){return Og.create(this,e,this._def)}transform(e){return new Bg({...R(this._def),schema:this,typeName:z.ZodEffects,effect:{type:`transform`,transform:e}})}default(e){let t=typeof e==`function`?e:()=>e;return new Ug({...R(this._def),innerType:this,defaultValue:t,typeName:z.ZodDefault})}brand(){return new Kg({typeName:z.ZodBranded,type:this,...R(this._def)})}catch(e){let t=typeof e==`function`?e:()=>e;return new Wg({...R(this._def),innerType:this,catchValue:t,typeName:z.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return qg.create(this,e)}readonly(){return Jg.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Rh=/^c[^\s-]{8,}$/i,zh=/^[0-9a-z]+$/,Bh=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Vh=/^[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,Hh=/^[a-z0-9_-]{21}$/i,Uh=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Wh=/^[-+]?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)?)??$/,Gh=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Kh=`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,qh,Jh=/^(?:(?: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])$/,Yh=/^(?:(?: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])$/,Xh=/^(([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]))$/,Zh=/^(([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])$/,Qh=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,$h=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,eg=`((\\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])))`,tg=RegExp(`^${eg}$`);function ng(e){let t=`[0-5]\\d`;e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision??(t=`${t}(\\.\\d+)?`);let n=e.precision?`+`:`?`;return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${n}`}function rg(e){return RegExp(`^${ng(e)}$`)}function ig(e){let t=`${eg}T${ng(e)}`,n=[];return n.push(e.local?`Z?`:`Z`),e.offset&&n.push(`([+-]\\d{2}:?\\d{2})`),t=`${t}(${n.join(`|`)})`,RegExp(`^${t}$`)}function ag(e,t){return!!((t===`v4`||!t)&&Jh.test(e)||(t===`v6`||!t)&&Xh.test(e))}function og(e,t){if(!Uh.test(e))return!1;try{let[n]=e.split(`.`);if(!n)return!1;let r=n.replace(/-/g,`+`).replace(/_/g,`/`).padEnd(n.length+(4-n.length%4)%4,`=`),i=JSON.parse(atob(r));return!(typeof i!=`object`||!i||`typ`in i&&i?.typ!==`JWT`||!i.alg||t&&i.alg!==t)}catch{return!1}}function sg(e,t){return!!((t===`v4`||!t)&&Yh.test(e)||(t===`v6`||!t)&&Zh.test(e))}var cg=class e extends Lh{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==N.string){let t=this._getOrReturnCtx(e);return F(t,{code:P.invalid_type,expected:N.string,received:t.parsedType}),I}let t=new Oh,n;for(let r of this._def.checks)if(r.kind===`min`)e.data.length<r.value&&(n=this._getOrReturnCtx(e,n),F(n,{code:P.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!1,message:r.message}),t.dirty());else if(r.kind===`max`)e.data.length>r.value&&(n=this._getOrReturnCtx(e,n),F(n,{code:P.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!1,message:r.message}),t.dirty());else if(r.kind===`length`){let i=e.data.length>r.value,a=e.data.length<r.value;(i||a)&&(n=this._getOrReturnCtx(e,n),i?F(n,{code:P.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}):a&&F(n,{code:P.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}),t.dirty())}else if(r.kind===`email`)Gh.test(e.data)||(n=this._getOrReturnCtx(e,n),F(n,{validation:`email`,code:P.invalid_string,message:r.message}),t.dirty());else if(r.kind===`emoji`)qh||=new RegExp(Kh,`u`),qh.test(e.data)||(n=this._getOrReturnCtx(e,n),F(n,{validation:`emoji`,code:P.invalid_string,message:r.message}),t.dirty());else if(r.kind===`uuid`)Vh.test(e.data)||(n=this._getOrReturnCtx(e,n),F(n,{validation:`uuid`,code:P.invalid_string,message:r.message}),t.dirty());else if(r.kind===`nanoid`)Hh.test(e.data)||(n=this._getOrReturnCtx(e,n),F(n,{validation:`nanoid`,code:P.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid`)Rh.test(e.data)||(n=this._getOrReturnCtx(e,n),F(n,{validation:`cuid`,code:P.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid2`)zh.test(e.data)||(n=this._getOrReturnCtx(e,n),F(n,{validation:`cuid2`,code:P.invalid_string,message:r.message}),t.dirty());else if(r.kind===`ulid`)Bh.test(e.data)||(n=this._getOrReturnCtx(e,n),F(n,{validation:`ulid`,code:P.invalid_string,message:r.message}),t.dirty());else if(r.kind===`url`)try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),F(n,{validation:`url`,code:P.invalid_string,message:r.message}),t.dirty()}else r.kind===`regex`?(r.regex.lastIndex=0,r.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),F(n,{validation:`regex`,code:P.invalid_string,message:r.message}),t.dirty())):r.kind===`trim`?e.data=e.data.trim():r.kind===`includes`?e.data.includes(r.value,r.position)||(n=this._getOrReturnCtx(e,n),F(n,{code:P.invalid_string,validation:{includes:r.value,position:r.position},message:r.message}),t.dirty()):r.kind===`toLowerCase`?e.data=e.data.toLowerCase():r.kind===`toUpperCase`?e.data=e.data.toUpperCase():r.kind===`startsWith`?e.data.startsWith(r.value)||(n=this._getOrReturnCtx(e,n),F(n,{code:P.invalid_string,validation:{startsWith:r.value},message:r.message}),t.dirty()):r.kind===`endsWith`?e.data.endsWith(r.value)||(n=this._getOrReturnCtx(e,n),F(n,{code:P.invalid_string,validation:{endsWith:r.value},message:r.message}),t.dirty()):r.kind===`datetime`?ig(r).test(e.data)||(n=this._getOrReturnCtx(e,n),F(n,{code:P.invalid_string,validation:`datetime`,message:r.message}),t.dirty()):r.kind===`date`?tg.test(e.data)||(n=this._getOrReturnCtx(e,n),F(n,{code:P.invalid_string,validation:`date`,message:r.message}),t.dirty()):r.kind===`time`?rg(r).test(e.data)||(n=this._getOrReturnCtx(e,n),F(n,{code:P.invalid_string,validation:`time`,message:r.message}),t.dirty()):r.kind===`duration`?Wh.test(e.data)||(n=this._getOrReturnCtx(e,n),F(n,{validation:`duration`,code:P.invalid_string,message:r.message}),t.dirty()):r.kind===`ip`?ag(e.data,r.version)||(n=this._getOrReturnCtx(e,n),F(n,{validation:`ip`,code:P.invalid_string,message:r.message}),t.dirty()):r.kind===`jwt`?og(e.data,r.alg)||(n=this._getOrReturnCtx(e,n),F(n,{validation:`jwt`,code:P.invalid_string,message:r.message}),t.dirty()):r.kind===`cidr`?sg(e.data,r.version)||(n=this._getOrReturnCtx(e,n),F(n,{validation:`cidr`,code:P.invalid_string,message:r.message}),t.dirty()):r.kind===`base64`?Qh.test(e.data)||(n=this._getOrReturnCtx(e,n),F(n,{validation:`base64`,code:P.invalid_string,message:r.message}),t.dirty()):r.kind===`base64url`?$h.test(e.data)||(n=this._getOrReturnCtx(e,n),F(n,{validation:`base64url`,code:P.invalid_string,message:r.message}),t.dirty()):bh.assertNever(r);return{status:t.value,value:e.data}}_regex(e,t,n){return this.refinement(t=>e.test(t),{validation:t,code:P.invalid_string,...L.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(e){return this._addCheck({kind:`email`,...L.errToObj(e)})}url(e){return this._addCheck({kind:`url`,...L.errToObj(e)})}emoji(e){return this._addCheck({kind:`emoji`,...L.errToObj(e)})}uuid(e){return this._addCheck({kind:`uuid`,...L.errToObj(e)})}nanoid(e){return this._addCheck({kind:`nanoid`,...L.errToObj(e)})}cuid(e){return this._addCheck({kind:`cuid`,...L.errToObj(e)})}cuid2(e){return this._addCheck({kind:`cuid2`,...L.errToObj(e)})}ulid(e){return this._addCheck({kind:`ulid`,...L.errToObj(e)})}base64(e){return this._addCheck({kind:`base64`,...L.errToObj(e)})}base64url(e){return this._addCheck({kind:`base64url`,...L.errToObj(e)})}jwt(e){return this._addCheck({kind:`jwt`,...L.errToObj(e)})}ip(e){return this._addCheck({kind:`ip`,...L.errToObj(e)})}cidr(e){return this._addCheck({kind:`cidr`,...L.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:e?.precision===void 0?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...L.errToObj(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:e?.precision===void 0?null:e?.precision,...L.errToObj(e?.message)})}duration(e){return this._addCheck({kind:`duration`,...L.errToObj(e)})}regex(e,t){return this._addCheck({kind:`regex`,regex:e,...L.errToObj(t)})}includes(e,t){return this._addCheck({kind:`includes`,value:e,position:t?.position,...L.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:`startsWith`,value:e,...L.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:`endsWith`,value:e,...L.errToObj(t)})}min(e,t){return this._addCheck({kind:`min`,value:e,...L.errToObj(t)})}max(e,t){return this._addCheck({kind:`max`,value:e,...L.errToObj(t)})}length(e,t){return this._addCheck({kind:`length`,value:e,...L.errToObj(t)})}nonempty(e){return this.min(1,L.errToObj(e))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:`trim`}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:`toLowerCase`}]})}toUpperCase(){return new e({...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(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}};cg.create=e=>new cg({checks:[],typeName:z.ZodString,coerce:e?.coerce??!1,...R(e)});function lg(e,t){let n=(e.toString().split(`.`)[1]||``).length,r=(t.toString().split(`.`)[1]||``).length,i=n>r?n:r;return Number.parseInt(e.toFixed(i).replace(`.`,``))%Number.parseInt(t.toFixed(i).replace(`.`,``))/10**i}var ug=class e extends Lh{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)!==N.number){let t=this._getOrReturnCtx(e);return F(t,{code:P.invalid_type,expected:N.number,received:t.parsedType}),I}let t,n=new Oh;for(let r of this._def.checks)r.kind===`int`?bh.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),F(t,{code:P.invalid_type,expected:`integer`,received:`float`,message:r.message}),n.dirty()):r.kind===`min`?(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),F(t,{code:P.too_small,minimum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`max`?(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),F(t,{code:P.too_big,maximum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`multipleOf`?lg(e.data,r.value)!==0&&(t=this._getOrReturnCtx(e,t),F(t,{code:P.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):r.kind===`finite`?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),F(t,{code:P.not_finite,message:r.message}),n.dirty()):bh.assertNever(r);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit(`min`,e,!0,L.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,L.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,L.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,L.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:L.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(e){return this._addCheck({kind:`int`,message:L.toString(e)})}positive(e){return this._addCheck({kind:`min`,value:0,inclusive:!1,message:L.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:0,inclusive:!1,message:L.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:0,inclusive:!0,message:L.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:0,inclusive:!0,message:L.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:L.toString(t)})}finite(e){return this._addCheck({kind:`finite`,message:L.toString(e)})}safe(e){return this._addCheck({kind:`min`,inclusive:!0,value:-(2**53-1),message:L.toString(e)})._addCheck({kind:`max`,inclusive:!0,value:2**53-1,message:L.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind===`int`||e.kind===`multipleOf`&&bh.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let n of this._def.checks)if(n.kind===`finite`||n.kind===`int`||n.kind===`multipleOf`)return!0;else n.kind===`min`?(t===null||n.value>t)&&(t=n.value):n.kind===`max`&&(e===null||n.value<e)&&(e=n.value);return Number.isFinite(t)&&Number.isFinite(e)}};ug.create=e=>new ug({checks:[],typeName:z.ZodNumber,coerce:e?.coerce||!1,...R(e)});var dg=class e extends Lh{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)!==N.bigint)return this._getInvalidInput(e);let t,n=new Oh;for(let r of this._def.checks)r.kind===`min`?(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),F(t,{code:P.too_small,type:`bigint`,minimum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty()):r.kind===`max`?(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),F(t,{code:P.too_big,type:`bigint`,maximum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty()):r.kind===`multipleOf`?e.data%r.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),F(t,{code:P.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):bh.assertNever(r);return{status:n.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return F(t,{code:P.invalid_type,expected:N.bigint,received:t.parsedType}),I}gte(e,t){return this.setLimit(`min`,e,!0,L.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,L.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,L.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,L.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:L.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!1,message:L.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!1,message:L.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!0,message:L.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!0,message:L.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:L.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}};dg.create=e=>new dg({checks:[],typeName:z.ZodBigInt,coerce:e?.coerce??!1,...R(e)});var fg=class extends Lh{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==N.boolean){let t=this._getOrReturnCtx(e);return F(t,{code:P.invalid_type,expected:N.boolean,received:t.parsedType}),I}return Ah(e.data)}};fg.create=e=>new fg({typeName:z.ZodBoolean,coerce:e?.coerce||!1,...R(e)});var pg=class e extends Lh{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==N.date){let t=this._getOrReturnCtx(e);return F(t,{code:P.invalid_type,expected:N.date,received:t.parsedType}),I}if(Number.isNaN(e.data.getTime()))return F(this._getOrReturnCtx(e),{code:P.invalid_date}),I;let t=new Oh,n;for(let r of this._def.checks)r.kind===`min`?e.data.getTime()<r.value&&(n=this._getOrReturnCtx(e,n),F(n,{code:P.too_small,message:r.message,inclusive:!0,exact:!1,minimum:r.value,type:`date`}),t.dirty()):r.kind===`max`?e.data.getTime()>r.value&&(n=this._getOrReturnCtx(e,n),F(n,{code:P.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:`date`}),t.dirty()):bh.assertNever(r);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(e,t){return this._addCheck({kind:`min`,value:e.getTime(),message:L.toString(t)})}max(e,t){return this._addCheck({kind:`max`,value:e.getTime(),message:L.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e==null?null:new Date(e)}get maxDate(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e==null?null:new Date(e)}};pg.create=e=>new pg({checks:[],coerce:e?.coerce||!1,typeName:z.ZodDate,...R(e)});var mg=class extends Lh{_parse(e){if(this._getType(e)!==N.symbol){let t=this._getOrReturnCtx(e);return F(t,{code:P.invalid_type,expected:N.symbol,received:t.parsedType}),I}return Ah(e.data)}};mg.create=e=>new mg({typeName:z.ZodSymbol,...R(e)});var hg=class extends Lh{_parse(e){if(this._getType(e)!==N.undefined){let t=this._getOrReturnCtx(e);return F(t,{code:P.invalid_type,expected:N.undefined,received:t.parsedType}),I}return Ah(e.data)}};hg.create=e=>new hg({typeName:z.ZodUndefined,...R(e)});var gg=class extends Lh{_parse(e){if(this._getType(e)!==N.null){let t=this._getOrReturnCtx(e);return F(t,{code:P.invalid_type,expected:N.null,received:t.parsedType}),I}return Ah(e.data)}};gg.create=e=>new gg({typeName:z.ZodNull,...R(e)});var _g=class extends Lh{constructor(){super(...arguments),this._any=!0}_parse(e){return Ah(e.data)}};_g.create=e=>new _g({typeName:z.ZodAny,...R(e)});var vg=class extends Lh{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Ah(e.data)}};vg.create=e=>new vg({typeName:z.ZodUnknown,...R(e)});var yg=class extends Lh{_parse(e){let t=this._getOrReturnCtx(e);return F(t,{code:P.invalid_type,expected:N.never,received:t.parsedType}),I}};yg.create=e=>new yg({typeName:z.ZodNever,...R(e)});var bg=class extends Lh{_parse(e){if(this._getType(e)!==N.undefined){let t=this._getOrReturnCtx(e);return F(t,{code:P.invalid_type,expected:N.void,received:t.parsedType}),I}return Ah(e.data)}};bg.create=e=>new bg({typeName:z.ZodVoid,...R(e)});var xg=class e extends Lh{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),r=this._def;if(t.parsedType!==N.array)return F(t,{code:P.invalid_type,expected:N.array,received:t.parsedType}),I;if(r.exactLength!==null){let e=t.data.length>r.exactLength.value,i=t.data.length<r.exactLength.value;(e||i)&&(F(t,{code:e?P.too_big:P.too_small,minimum:i?r.exactLength.value:void 0,maximum:e?r.exactLength.value:void 0,type:`array`,inclusive:!0,exact:!0,message:r.exactLength.message}),n.dirty())}if(r.minLength!==null&&t.data.length<r.minLength.value&&(F(t,{code:P.too_small,minimum:r.minLength.value,type:`array`,inclusive:!0,exact:!1,message:r.minLength.message}),n.dirty()),r.maxLength!==null&&t.data.length>r.maxLength.value&&(F(t,{code:P.too_big,maximum:r.maxLength.value,type:`array`,inclusive:!0,exact:!1,message:r.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((e,n)=>r.type._parseAsync(new Fh(t,e,t.path,n)))).then(e=>Oh.mergeArray(n,e));let i=[...t.data].map((e,n)=>r.type._parseSync(new Fh(t,e,t.path,n)));return Oh.mergeArray(n,i)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:L.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:L.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:L.toString(n)}})}nonempty(e){return this.min(1,e)}};xg.create=(e,t)=>new xg({type:e,minLength:null,maxLength:null,exactLength:null,typeName:z.ZodArray,...R(t)});function Sg(e){if(e instanceof Cg){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=Vg.create(Sg(r))}return new Cg({...e._def,shape:()=>t})}else if(e instanceof xg)return new xg({...e._def,type:Sg(e.element)});else if(e instanceof Vg)return Vg.create(Sg(e.unwrap()));else if(e instanceof Hg)return Hg.create(Sg(e.unwrap()));else if(e instanceof kg)return kg.create(e.items.map(e=>Sg(e)));else return e}var Cg=class e extends Lh{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=bh.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==N.object){let t=this._getOrReturnCtx(e);return F(t,{code:P.invalid_type,expected:N.object,received:t.parsedType}),I}let{status:t,ctx:n}=this._processInputParams(e),{shape:r,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof yg&&this._def.unknownKeys===`strip`))for(let e in n.data)i.includes(e)||a.push(e);let o=[];for(let e of i){let t=r[e],i=n.data[e];o.push({key:{status:`valid`,value:e},value:t._parse(new Fh(n,i,n.path,e)),alwaysSet:e in n.data})}if(this._def.catchall instanceof yg){let e=this._def.unknownKeys;if(e===`passthrough`)for(let e of a)o.push({key:{status:`valid`,value:e},value:{status:`valid`,value:n.data[e]}});else if(e===`strict`)a.length>0&&(F(n,{code:P.unrecognized_keys,keys:a}),t.dirty());else if(e!==`strip`)throw Error(`Internal ZodObject error: invalid unknownKeys value.`)}else{let e=this._def.catchall;for(let t of a){let r=n.data[t];o.push({key:{status:`valid`,value:t},value:e._parse(new Fh(n,r,n.path,t)),alwaysSet:t in n.data})}}return n.common.async?Promise.resolve().then(async()=>{let e=[];for(let t of o){let n=await t.key,r=await t.value;e.push({key:n,value:r,alwaysSet:t.alwaysSet})}return e}).then(e=>Oh.mergeObjectSync(t,e)):Oh.mergeObjectSync(t,o)}get shape(){return this._def.shape()}strict(t){return L.errToObj,new e({...this._def,unknownKeys:`strict`,...t===void 0?{}:{errorMap:(e,n)=>{let r=this._def.errorMap?.(e,n).message??n.defaultError;return e.code===`unrecognized_keys`?{message:L.errToObj(t).message??r}:{message:r}}}})}strip(){return new e({...this._def,unknownKeys:`strip`})}passthrough(){return new e({...this._def,unknownKeys:`passthrough`})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:z.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let n={};for(let e of bh.objectKeys(t))t[e]&&this.shape[e]&&(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}omit(t){let n={};for(let e of bh.objectKeys(this.shape))t[e]||(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}deepPartial(){return Sg(this)}partial(t){let n={};for(let e of bh.objectKeys(this.shape)){let r=this.shape[e];t&&!t[e]?n[e]=r:n[e]=r.optional()}return new e({...this._def,shape:()=>n})}required(t){let n={};for(let e of bh.objectKeys(this.shape))if(t&&!t[e])n[e]=this.shape[e];else{let t=this.shape[e];for(;t instanceof Vg;)t=t._def.innerType;n[e]=t}return new e({...this._def,shape:()=>n})}keyof(){return Ig(bh.objectKeys(this.shape))}};Cg.create=(e,t)=>new Cg({shape:()=>e,unknownKeys:`strip`,catchall:yg.create(),typeName:z.ZodObject,...R(t)}),Cg.strictCreate=(e,t)=>new Cg({shape:()=>e,unknownKeys:`strict`,catchall:yg.create(),typeName:z.ZodObject,...R(t)}),Cg.lazycreate=(e,t)=>new Cg({shape:e,unknownKeys:`strip`,catchall:yg.create(),typeName:z.ZodObject,...R(t)});var wg=class extends Lh{_parse(e){let{ctx:t}=this._processInputParams(e),n=this._def.options;function r(e){for(let t of e)if(t.result.status===`valid`)return t.result;for(let n of e)if(n.result.status===`dirty`)return t.common.issues.push(...n.ctx.common.issues),n.result;let n=e.map(e=>new Ch(e.ctx.common.issues));return F(t,{code:P.invalid_union,unionErrors:n}),I}if(t.common.async)return Promise.all(n.map(async e=>{let n={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:n}),ctx:n}})).then(r);{let e,r=[];for(let i of n){let n={...t,common:{...t.common,issues:[]},parent:null},a=i._parseSync({data:t.data,path:t.path,parent:n});if(a.status===`valid`)return a;a.status===`dirty`&&!e&&(e={result:a,ctx:n}),n.common.issues.length&&r.push(n.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;let i=r.map(e=>new Ch(e));return F(t,{code:P.invalid_union,unionErrors:i}),I}}get options(){return this._def.options}};wg.create=(e,t)=>new wg({options:e,typeName:z.ZodUnion,...R(t)});var Tg=e=>e instanceof Pg?Tg(e.schema):e instanceof Bg?Tg(e.innerType()):e instanceof Fg?[e.value]:e instanceof Lg?e.options:e instanceof Rg?bh.objectValues(e.enum):e instanceof Ug?Tg(e._def.innerType):e instanceof hg?[void 0]:e instanceof gg?[null]:e instanceof Vg?[void 0,...Tg(e.unwrap())]:e instanceof Hg?[null,...Tg(e.unwrap())]:e instanceof Kg||e instanceof Jg?Tg(e.unwrap()):e instanceof Wg?Tg(e._def.innerType):[],Eg=class e extends Lh{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==N.object)return F(t,{code:P.invalid_type,expected:N.object,received:t.parsedType}),I;let n=this.discriminator,r=t.data[n],i=this.optionsMap.get(r);return i?t.common.async?i._parseAsync({data:t.data,path:t.path,parent:t}):i._parseSync({data:t.data,path:t.path,parent:t}):(F(t,{code:P.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),I)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){let i=new Map;for(let e of n){let n=Tg(e.shape[t]);if(!n.length)throw Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let r of n){if(i.has(r))throw Error(`Discriminator property ${String(t)} has duplicate value ${String(r)}`);i.set(r,e)}}return new e({typeName:z.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:i,...R(r)})}};function Dg(e,t){let n=Sh(e),r=Sh(t);if(e===t)return{valid:!0,data:e};if(n===N.object&&r===N.object){let n=bh.objectKeys(t),r=bh.objectKeys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=Dg(e[n],t[n]);if(!r.valid)return{valid:!1};i[n]=r.data}return{valid:!0,data:i}}else if(n===N.array&&r===N.array){if(e.length!==t.length)return{valid:!1};let n=[];for(let r=0;r<e.length;r++){let i=e[r],a=t[r],o=Dg(i,a);if(!o.valid)return{valid:!1};n.push(o.data)}return{valid:!0,data:n}}else if(n===N.date&&r===N.date&&+e==+t)return{valid:!0,data:e};else return{valid:!1}}var Og=class extends Lh{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=(e,r)=>{if(jh(e)||jh(r))return I;let i=Dg(e.value,r.value);return i.valid?((Mh(e)||Mh(r))&&t.dirty(),{status:t.value,value:i.data}):(F(n,{code:P.invalid_intersection_types}),I)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([e,t])=>r(e,t)):r(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};Og.create=(e,t,n)=>new Og({left:e,right:t,typeName:z.ZodIntersection,...R(n)});var kg=class e extends Lh{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==N.array)return F(n,{code:P.invalid_type,expected:N.array,received:n.parsedType}),I;if(n.data.length<this._def.items.length)return F(n,{code:P.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),I;!this._def.rest&&n.data.length>this._def.items.length&&(F(n,{code:P.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),t.dirty());let r=[...n.data].map((e,t)=>{let r=this._def.items[t]||this._def.rest;return r?r._parse(new Fh(n,e,n.path,t)):null}).filter(e=>!!e);return n.common.async?Promise.all(r).then(e=>Oh.mergeArray(t,e)):Oh.mergeArray(t,r)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};kg.create=(e,t)=>{if(!Array.isArray(e))throw Error(`You must pass an array of schemas to z.tuple([ ... ])`);return new kg({items:e,typeName:z.ZodTuple,rest:null,...R(t)})};var Ag=class e extends Lh{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==N.object)return F(n,{code:P.invalid_type,expected:N.object,received:n.parsedType}),I;let r=[],i=this._def.keyType,a=this._def.valueType;for(let e in n.data)r.push({key:i._parse(new Fh(n,e,n.path,e)),value:a._parse(new Fh(n,n.data[e],n.path,e)),alwaysSet:e in n.data});return n.common.async?Oh.mergeObjectAsync(t,r):Oh.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof Lh?new e({keyType:t,valueType:n,typeName:z.ZodRecord,...R(r)}):new e({keyType:cg.create(),valueType:t,typeName:z.ZodRecord,...R(n)})}},jg=class extends Lh{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==N.map)return F(n,{code:P.invalid_type,expected:N.map,received:n.parsedType}),I;let r=this._def.keyType,i=this._def.valueType,a=[...n.data.entries()].map(([e,t],a)=>({key:r._parse(new Fh(n,e,n.path,[a,`key`])),value:i._parse(new Fh(n,t,n.path,[a,`value`]))}));if(n.common.async){let e=new Map;return Promise.resolve().then(async()=>{for(let n of a){let r=await n.key,i=await n.value;if(r.status===`aborted`||i.status===`aborted`)return I;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}})}else{let e=new Map;for(let n of a){let r=n.key,i=n.value;if(r.status===`aborted`||i.status===`aborted`)return I;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}}}};jg.create=(e,t,n)=>new jg({valueType:t,keyType:e,typeName:z.ZodMap,...R(n)});var Mg=class e extends Lh{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==N.set)return F(n,{code:P.invalid_type,expected:N.set,received:n.parsedType}),I;let r=this._def;r.minSize!==null&&n.data.size<r.minSize.value&&(F(n,{code:P.too_small,minimum:r.minSize.value,type:`set`,inclusive:!0,exact:!1,message:r.minSize.message}),t.dirty()),r.maxSize!==null&&n.data.size>r.maxSize.value&&(F(n,{code:P.too_big,maximum:r.maxSize.value,type:`set`,inclusive:!0,exact:!1,message:r.maxSize.message}),t.dirty());let i=this._def.valueType;function a(e){let n=new Set;for(let r of e){if(r.status===`aborted`)return I;r.status===`dirty`&&t.dirty(),n.add(r.value)}return{status:t.value,value:n}}let o=[...n.data.values()].map((e,t)=>i._parse(new Fh(n,e,n.path,t)));return n.common.async?Promise.all(o).then(e=>a(e)):a(o)}min(t,n){return new e({...this._def,minSize:{value:t,message:L.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:L.toString(n)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};Mg.create=(e,t)=>new Mg({valueType:e,minSize:null,maxSize:null,typeName:z.ZodSet,...R(t)});var Ng=class e extends Lh{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==N.function)return F(t,{code:P.invalid_type,expected:N.function,received:t.parsedType}),I;function n(e,n){return Dh({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,Eh(),wh].filter(e=>!!e),issueData:{code:P.invalid_arguments,argumentsError:n}})}function r(e,n){return Dh({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,Eh(),wh].filter(e=>!!e),issueData:{code:P.invalid_return_type,returnTypeError:n}})}let i={errorMap:t.common.contextualErrorMap},a=t.data;if(this._def.returns instanceof zg){let e=this;return Ah(async function(...t){let o=new Ch([]),s=await e._def.args.parseAsync(t,i).catch(e=>{throw o.addIssue(n(t,e)),o}),c=await Reflect.apply(a,this,s);return await e._def.returns._def.type.parseAsync(c,i).catch(e=>{throw o.addIssue(r(c,e)),o})})}else{let e=this;return Ah(function(...t){let o=e._def.args.safeParse(t,i);if(!o.success)throw new Ch([n(t,o.error)]);let s=Reflect.apply(a,this,o.data),c=e._def.returns.safeParse(s,i);if(!c.success)throw new Ch([r(s,c.error)]);return c.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:kg.create(t).rest(vg.create())})}returns(t){return new e({...this._def,returns:t})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(t,n,r){return new e({args:t||kg.create([]).rest(vg.create()),returns:n||vg.create(),typeName:z.ZodFunction,...R(r)})}},Pg=class extends Lh{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};Pg.create=(e,t)=>new Pg({getter:e,typeName:z.ZodLazy,...R(t)});var Fg=class extends Lh{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return F(t,{received:t.data,code:P.invalid_literal,expected:this._def.value}),I}return{status:`valid`,value:e.data}}get value(){return this._def.value}};Fg.create=(e,t)=>new Fg({value:e,typeName:z.ZodLiteral,...R(t)});function Ig(e,t){return new Lg({values:e,typeName:z.ZodEnum,...R(t)})}var Lg=class e extends Lh{_parse(e){if(typeof e.data!=`string`){let t=this._getOrReturnCtx(e),n=this._def.values;return F(t,{expected:bh.joinValues(n),received:t.parsedType,code:P.invalid_type}),I}if(this._cache||=new Set(this._def.values),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return F(t,{received:t.data,code:P.invalid_enum_value,options:n}),I}return Ah(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(t,n=this._def){return e.create(t,{...this._def,...n})}exclude(t,n=this._def){return e.create(this.options.filter(e=>!t.includes(e)),{...this._def,...n})}};Lg.create=Ig;var Rg=class extends Lh{_parse(e){let t=bh.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==N.string&&n.parsedType!==N.number){let e=bh.objectValues(t);return F(n,{expected:bh.joinValues(e),received:n.parsedType,code:P.invalid_type}),I}if(this._cache||=new Set(bh.getValidEnumValues(this._def.values)),!this._cache.has(e.data)){let e=bh.objectValues(t);return F(n,{received:n.data,code:P.invalid_enum_value,options:e}),I}return Ah(e.data)}get enum(){return this._def.values}};Rg.create=(e,t)=>new Rg({values:e,typeName:z.ZodNativeEnum,...R(t)});var zg=class extends Lh{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);return t.parsedType!==N.promise&&t.common.async===!1?(F(t,{code:P.invalid_type,expected:N.promise,received:t.parsedType}),I):Ah((t.parsedType===N.promise?t.data:Promise.resolve(t.data)).then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}};zg.create=(e,t)=>new zg({type:e,typeName:z.ZodPromise,...R(t)});var Bg=class extends Lh{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===z.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=this._def.effect||null,i={addIssue:e=>{F(n,e),e.fatal?t.abort():t.dirty()},get path(){return n.path}};if(i.addIssue=i.addIssue.bind(i),r.type===`preprocess`){let e=r.transform(n.data,i);if(n.common.async)return Promise.resolve(e).then(async e=>{if(t.value===`aborted`)return I;let r=await this._def.schema._parseAsync({data:e,path:n.path,parent:n});return r.status===`aborted`?I:r.status===`dirty`||t.value===`dirty`?kh(r.value):r});{if(t.value===`aborted`)return I;let r=this._def.schema._parseSync({data:e,path:n.path,parent:n});return r.status===`aborted`?I:r.status===`dirty`||t.value===`dirty`?kh(r.value):r}}if(r.type===`refinement`){let e=e=>{let t=r.refinement(e,i);if(n.common.async)return Promise.resolve(t);if(t instanceof Promise)throw Error(`Async refinement encountered during synchronous parse operation. Use .parseAsync instead.`);return e};if(n.common.async===!1){let r=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return r.status===`aborted`?I:(r.status===`dirty`&&t.dirty(),e(r.value),{status:t.value,value:r.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(n=>n.status===`aborted`?I:(n.status===`dirty`&&t.dirty(),e(n.value).then(()=>({status:t.value,value:n.value}))))}if(r.type===`transform`)if(n.common.async===!1){let e=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!Nh(e))return I;let a=r.transform(e.value,i);if(a instanceof Promise)throw Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);return{status:t.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(e=>Nh(e)?Promise.resolve(r.transform(e.value,i)).then(e=>({status:t.value,value:e})):I);bh.assertNever(r)}};Bg.create=(e,t,n)=>new Bg({schema:e,typeName:z.ZodEffects,effect:t,...R(n)}),Bg.createWithPreprocess=(e,t,n)=>new Bg({schema:t,effect:{type:`preprocess`,transform:e},typeName:z.ZodEffects,...R(n)});var Vg=class extends Lh{_parse(e){return this._getType(e)===N.undefined?Ah(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Vg.create=(e,t)=>new Vg({innerType:e,typeName:z.ZodOptional,...R(t)});var Hg=class extends Lh{_parse(e){return this._getType(e)===N.null?Ah(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Hg.create=(e,t)=>new Hg({innerType:e,typeName:z.ZodNullable,...R(t)});var Ug=class extends Lh{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===N.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};Ug.create=(e,t)=>new Ug({innerType:e,typeName:z.ZodDefault,defaultValue:typeof t.default==`function`?t.default:()=>t.default,...R(t)});var Wg=class extends Lh{_parse(e){let{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},r=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return Ph(r)?r.then(e=>({status:`valid`,value:e.status===`valid`?e.value:this._def.catchValue({get error(){return new Ch(n.common.issues)},input:n.data})})):{status:`valid`,value:r.status===`valid`?r.value:this._def.catchValue({get error(){return new Ch(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Wg.create=(e,t)=>new Wg({innerType:e,typeName:z.ZodCatch,catchValue:typeof t.catch==`function`?t.catch:()=>t.catch,...R(t)});var Gg=class extends Lh{_parse(e){if(this._getType(e)!==N.nan){let t=this._getOrReturnCtx(e);return F(t,{code:P.invalid_type,expected:N.nan,received:t.parsedType}),I}return{status:`valid`,value:e.data}}};Gg.create=e=>new Gg({typeName:z.ZodNaN,...R(e)});var Kg=class extends Lh{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}},qg=class e extends Lh{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let e=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return e.status===`aborted`?I:e.status===`dirty`?(t.dirty(),kh(e.value)):this._def.out._parseAsync({data:e.value,path:n.path,parent:n})})();{let e=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return e.status===`aborted`?I:e.status===`dirty`?(t.dirty(),{status:`dirty`,value:e.value}):this._def.out._parseSync({data:e.value,path:n.path,parent:n})}}static create(t,n){return new e({in:t,out:n,typeName:z.ZodPipeline})}},Jg=class extends Lh{_parse(e){let t=this._def.innerType._parse(e),n=e=>(Nh(e)&&(e.value=Object.freeze(e.value)),e);return Ph(t)?t.then(e=>n(e)):n(t)}unwrap(){return this._def.innerType}};Jg.create=(e,t)=>new Jg({innerType:e,typeName:z.ZodReadonly,...R(t)}),Cg.lazycreate;var z;(function(e){e.ZodString=`ZodString`,e.ZodNumber=`ZodNumber`,e.ZodNaN=`ZodNaN`,e.ZodBigInt=`ZodBigInt`,e.ZodBoolean=`ZodBoolean`,e.ZodDate=`ZodDate`,e.ZodSymbol=`ZodSymbol`,e.ZodUndefined=`ZodUndefined`,e.ZodNull=`ZodNull`,e.ZodAny=`ZodAny`,e.ZodUnknown=`ZodUnknown`,e.ZodNever=`ZodNever`,e.ZodVoid=`ZodVoid`,e.ZodArray=`ZodArray`,e.ZodObject=`ZodObject`,e.ZodUnion=`ZodUnion`,e.ZodDiscriminatedUnion=`ZodDiscriminatedUnion`,e.ZodIntersection=`ZodIntersection`,e.ZodTuple=`ZodTuple`,e.ZodRecord=`ZodRecord`,e.ZodMap=`ZodMap`,e.ZodSet=`ZodSet`,e.ZodFunction=`ZodFunction`,e.ZodLazy=`ZodLazy`,e.ZodLiteral=`ZodLiteral`,e.ZodEnum=`ZodEnum`,e.ZodEffects=`ZodEffects`,e.ZodNativeEnum=`ZodNativeEnum`,e.ZodOptional=`ZodOptional`,e.ZodNullable=`ZodNullable`,e.ZodDefault=`ZodDefault`,e.ZodCatch=`ZodCatch`,e.ZodPromise=`ZodPromise`,e.ZodBranded=`ZodBranded`,e.ZodPipeline=`ZodPipeline`,e.ZodReadonly=`ZodReadonly`})(z||={});var Yg=cg.create,Xg=ug.create;Gg.create,dg.create;var Zg=fg.create;pg.create,mg.create,hg.create,gg.create;var Qg=_g.create;vg.create,yg.create,bg.create;var $g=xg.create,e_=Cg.create;Cg.strictCreate,wg.create,Eg.create,Og.create,kg.create,Ag.create,jg.create,Mg.create,Ng.create,Pg.create,Fg.create;var t_=Lg.create;Rg.create,zg.create,Bg.create,Vg.create,Hg.create,Bg.createWithPreprocess,qg.create;function n_(e,t){let n={type:`array`};return e.type?._def&&e.type?._def?.typeName!==z.ZodAny&&(n.items=K_(e.type._def,{...t,currentPath:[...t.currentPath,`items`]})),e.minLength&&yh(n,`minItems`,e.minLength.value,e.minLength.message,t),e.maxLength&&yh(n,`maxItems`,e.maxLength.value,e.maxLength.message,t),e.exactLength&&(yh(n,`minItems`,e.exactLength.value,e.exactLength.message,t),yh(n,`maxItems`,e.exactLength.value,e.exactLength.message,t)),n}function r_(e,t){let n={type:`integer`,format:`int64`};if(!e.checks)return n;for(let r of e.checks)switch(r.kind){case`min`:t.target===`jsonSchema7`?r.inclusive?yh(n,`minimum`,r.value,r.message,t):yh(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),yh(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?yh(n,`maximum`,r.value,r.message,t):yh(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),yh(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:yh(n,`multipleOf`,r.value,r.message,t);break}return n}function i_(){return{type:`boolean`}}function a_(e,t){return K_(e.type._def,t)}var o_=(e,t)=>K_(e.innerType._def,t);function s_(e,t,n){let r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map(n=>s_(e,t,n))};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 c_(e,t)}}var c_=(e,t)=>{let n={type:`integer`,format:`unix-time`};if(t.target===`openApi3`)return n;for(let r of e.checks)switch(r.kind){case`min`:yh(n,`minimum`,r.value,r.message,t);break;case`max`:yh(n,`maximum`,r.value,r.message,t);break}return n};function l_(e,t){return{...K_(e.innerType._def,t),default:e.defaultValue()}}function u_(e,t){return t.effectStrategy===`input`?K_(e.schema._def,t):_h(t)}function d_(e){return{type:`string`,enum:Array.from(e.values)}}var f_=e=>`type`in e&&e.type===`string`?!1:`allOf`in e;function p_(e,t){let n=[K_(e.left._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]}),K_(e.right._def,{...t,currentPath:[...t.currentPath,`allOf`,`1`]})].filter(e=>!!e),r=t.target===`jsonSchema2019-09`?{unevaluatedProperties:!1}:void 0,i=[];return n.forEach(e=>{if(f_(e))i.push(...e.allOf),e.unevaluatedProperties===void 0&&(r=void 0);else{let t=e;if(`additionalProperties`in e&&e.additionalProperties===!1){let{additionalProperties:n,...r}=e;t=r}else r=void 0;i.push(t)}}),i.length?{allOf:i,...r}:void 0}function m_(e,t){let n=typeof e.value;return n!==`bigint`&&n!==`number`&&n!==`boolean`&&n!==`string`?{type:Array.isArray(e.value)?`array`:`object`}:t.target===`openApi3`?{type:n===`bigint`?`integer`:n,enum:[e.value]}:{type:n===`bigint`?`integer`:n,const:e.value}}var h_=void 0,g_={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:()=>(h_===void 0&&(h_=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)),h_),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 __(e,t){let n={type:`string`};if(e.checks)for(let r of e.checks)switch(r.kind){case`min`:yh(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t);break;case`max`:yh(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case`email`:switch(t.emailStrategy){case`format:email`:x_(n,`email`,r.message,t);break;case`format:idn-email`:x_(n,`idn-email`,r.message,t);break;case`pattern:zod`:S_(n,g_.email,r.message,t);break}break;case`url`:x_(n,`uri`,r.message,t);break;case`uuid`:x_(n,`uuid`,r.message,t);break;case`regex`:S_(n,r.regex,r.message,t);break;case`cuid`:S_(n,g_.cuid,r.message,t);break;case`cuid2`:S_(n,g_.cuid2,r.message,t);break;case`startsWith`:S_(n,RegExp(`^${v_(r.value,t)}`),r.message,t);break;case`endsWith`:S_(n,RegExp(`${v_(r.value,t)}$`),r.message,t);break;case`datetime`:x_(n,`date-time`,r.message,t);break;case`date`:x_(n,`date`,r.message,t);break;case`time`:x_(n,`time`,r.message,t);break;case`duration`:x_(n,`duration`,r.message,t);break;case`length`:yh(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t),yh(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case`includes`:S_(n,RegExp(v_(r.value,t)),r.message,t);break;case`ip`:r.version!==`v6`&&x_(n,`ipv4`,r.message,t),r.version!==`v4`&&x_(n,`ipv6`,r.message,t);break;case`base64url`:S_(n,g_.base64url,r.message,t);break;case`jwt`:S_(n,g_.jwt,r.message,t);break;case`cidr`:r.version!==`v6`&&S_(n,g_.ipv4Cidr,r.message,t),r.version!==`v4`&&S_(n,g_.ipv6Cidr,r.message,t);break;case`emoji`:S_(n,g_.emoji(),r.message,t);break;case`ulid`:S_(n,g_.ulid,r.message,t);break;case`base64`:switch(t.base64Strategy){case`format:binary`:x_(n,`binary`,r.message,t);break;case`contentEncoding:base64`:yh(n,`contentEncoding`,`base64`,r.message,t);break;case`pattern:zod`:S_(n,g_.base64,r.message,t);break}break;case`nanoid`:S_(n,g_.nanoid,r.message,t);break;case`toLowerCase`:case`toUpperCase`:case`trim`:break;default:(e=>{})(r)}return n}function v_(e,t){return t.patternStrategy===`escape`?b_(e):e}var y_=new Set(`ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789`);function b_(e){let t=``;for(let n=0;n<e.length;n++)y_.has(e[n])||(t+=`\\`),t+=e[n];return t}function x_(e,t,n,r){e.format||e.anyOf?.some(e=>e.format)?(e.anyOf||=[],e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&r.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.anyOf.push({format:t,...n&&r.errorMessages&&{errorMessage:{format:n}}})):yh(e,`format`,t,n,r)}function S_(e,t,n,r){e.pattern||e.allOf?.some(e=>e.pattern)?(e.allOf||=[],e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&r.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.allOf.push({pattern:C_(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):yh(e,`pattern`,C_(t,r),n,r)}function C_(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;let n={i:e.flags.includes(`i`),m:e.flags.includes(`m`),s:e.flags.includes(`s`)},r=n.i?e.source.toLowerCase():e.source,i=``,a=!1,o=!1,s=!1;for(let e=0;e<r.length;e++){if(a){i+=r[e],a=!1;continue}if(n.i){if(o){if(r[e].match(/[a-z]/)){s?(i+=r[e],i+=`${r[e-2]}-${r[e]}`.toUpperCase(),s=!1):r[e+1]===`-`&&r[e+2]?.match(/[a-z]/)?(i+=r[e],s=!0):i+=`${r[e]}${r[e].toUpperCase()}`;continue}}else if(r[e].match(/[a-z]/)){i+=`[${r[e]}${r[e].toUpperCase()}]`;continue}}if(n.m){if(r[e]===`^`){i+=`(^|(?<=[\r
58
- ]))`;continue}else if(r[e]===`$`){i+=`($|(?=[\r
59
- ]))`;continue}}if(n.s&&r[e]===`.`){i+=o?`${r[e]}\r\n`:`[${r[e]}\r\n]`;continue}i+=r[e],r[e]===`\\`?a=!0:o&&r[e]===`]`?o=!1:!o&&r[e]===`[`&&(o=!0)}try{new RegExp(i)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join(`/`)} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return i}function w_(e,t){if(t.target===`openAi`&&console.warn(`Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead.`),t.target===`openApi3`&&e.keyType?._def.typeName===z.ZodEnum)return{type:`object`,required:e.keyType._def.values,properties:e.keyType._def.values.reduce((n,r)=>({...n,[r]:K_(e.valueType._def,{...t,currentPath:[...t.currentPath,`properties`,r]})??_h(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};let n={type:`object`,additionalProperties:K_(e.valueType._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]})??t.allowedAdditionalProperties};if(t.target===`openApi3`)return n;if(e.keyType?._def.typeName===z.ZodString&&e.keyType._def.checks?.length){let{type:r,...i}=__(e.keyType._def,t);return{...n,propertyNames:i}}else if(e.keyType?._def.typeName===z.ZodEnum)return{...n,propertyNames:{enum:e.keyType._def.values}};else if(e.keyType?._def.typeName===z.ZodBranded&&e.keyType._def.type._def.typeName===z.ZodString&&e.keyType._def.type._def.checks?.length){let{type:r,...i}=a_(e.keyType._def,t);return{...n,propertyNames:i}}return n}function T_(e,t){return t.mapStrategy===`record`?w_(e,t):{type:`array`,maxItems:125,items:{type:`array`,items:[K_(e.keyType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`0`]})||_h(t),K_(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`1`]})||_h(t)],minItems:2,maxItems:2}}}function E_(e){let t=e.values,n=Object.keys(e.values).filter(e=>typeof t[t[e]]!=`number`).map(e=>t[e]),r=Array.from(new Set(n.map(e=>typeof e)));return{type:r.length===1?r[0]===`string`?`string`:`number`:[`string`,`number`],enum:n}}function D_(e){return e.target===`openAi`?void 0:{not:_h({...e,currentPath:[...e.currentPath,`not`]})}}function O_(e){return e.target===`openApi3`?{enum:[`null`],nullable:!0}:{type:`null`}}var k_={ZodString:`string`,ZodNumber:`number`,ZodBigInt:`integer`,ZodBoolean:`boolean`,ZodNull:`null`};function A_(e,t){if(t.target===`openApi3`)return j_(e,t);let n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(e=>e._def.typeName in k_&&(!e._def.checks||!e._def.checks.length))){let e=n.reduce((e,t)=>{let n=k_[t._def.typeName];return n&&!e.includes(n)?[...e,n]:e},[]);return{type:e.length>1?e:e[0]}}else if(n.every(e=>e._def.typeName===`ZodLiteral`&&!e.description)){let e=n.reduce((e,t)=>{let n=typeof t._def.value;switch(n){case`string`:case`number`:case`boolean`:return[...e,n];case`bigint`:return[...e,`integer`];case`object`:return t._def.value===null?[...e,`null`]:e;default:return e}},[]);if(e.length===n.length){let t=e.filter((e,t,n)=>n.indexOf(e)===t);return{type:t.length>1?t:t[0],enum:n.reduce((e,t)=>e.includes(t._def.value)?e:[...e,t._def.value],[])}}}else if(n.every(e=>e._def.typeName===`ZodEnum`))return{type:`string`,enum:n.reduce((e,t)=>[...e,...t._def.values.filter(t=>!e.includes(t))],[])};return j_(e,t)}var j_=(e,t)=>{let n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((e,n)=>K_(e._def,{...t,currentPath:[...t.currentPath,`anyOf`,`${n}`]})).filter(e=>!!e&&(!t.strictUnions||typeof e==`object`&&Object.keys(e).length>0));return n.length?{anyOf:n}:void 0};function M_(e,t){if([`ZodString`,`ZodNumber`,`ZodBigInt`,`ZodBoolean`,`ZodNull`].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return t.target===`openApi3`?{type:k_[e.innerType._def.typeName],nullable:!0}:{type:[k_[e.innerType._def.typeName],`null`]};if(t.target===`openApi3`){let n=K_(e.innerType._def,{...t,currentPath:[...t.currentPath]});return n&&`$ref`in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let n=K_(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`0`]});return n&&{anyOf:[n,{type:`null`}]}}function N_(e,t){let n={type:`number`};if(!e.checks)return n;for(let r of e.checks)switch(r.kind){case`int`:n.type=`integer`,vh(n,`type`,r.message,t);break;case`min`:t.target===`jsonSchema7`?r.inclusive?yh(n,`minimum`,r.value,r.message,t):yh(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),yh(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?yh(n,`maximum`,r.value,r.message,t):yh(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),yh(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:yh(n,`multipleOf`,r.value,r.message,t);break}return n}function P_(e,t){let n=t.target===`openAi`,r={type:`object`,properties:{}},i=[],a=e.shape();for(let e in a){let o=a[e];if(o===void 0||o._def===void 0)continue;let s=I_(o);s&&n&&(o._def.typeName===`ZodOptional`&&(o=o._def.innerType),o.isNullable()||(o=o.nullable()),s=!1);let c=K_(o._def,{...t,currentPath:[...t.currentPath,`properties`,e],propertyPath:[...t.currentPath,`properties`,e]});c!==void 0&&(r.properties[e]=c,s||i.push(e))}i.length&&(r.required=i);let o=F_(e,t);return o!==void 0&&(r.additionalProperties=o),r}function F_(e,t){if(e.catchall._def.typeName!==`ZodNever`)return K_(e.catchall._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]});switch(e.unknownKeys){case`passthrough`:return t.allowedAdditionalProperties;case`strict`:return t.rejectedAdditionalProperties;case`strip`:return t.removeAdditionalStrategy===`strict`?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}function I_(e){try{return e.isOptional()}catch{return!0}}var L_=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return K_(e.innerType._def,t);let n=K_(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`1`]});return n?{anyOf:[{not:_h(t)},n]}:_h(t)},R_=(e,t)=>{if(t.pipeStrategy===`input`)return K_(e.in._def,t);if(t.pipeStrategy===`output`)return K_(e.out._def,t);let n=K_(e.in._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]});return{allOf:[n,K_(e.out._def,{...t,currentPath:[...t.currentPath,`allOf`,n?`1`:`0`]})].filter(e=>e!==void 0)}};function z_(e,t){return K_(e.type._def,t)}function B_(e,t){let n={type:`array`,uniqueItems:!0,items:K_(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`]})};return e.minSize&&yh(n,`minItems`,e.minSize.value,e.minSize.message,t),e.maxSize&&yh(n,`maxItems`,e.maxSize.value,e.maxSize.message,t),n}function V_(e,t){return e.rest?{type:`array`,minItems:e.items.length,items:e.items.map((e,n)=>K_(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[]),additionalItems:K_(e.rest._def,{...t,currentPath:[...t.currentPath,`additionalItems`]})}:{type:`array`,minItems:e.items.length,maxItems:e.items.length,items:e.items.map((e,n)=>K_(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[])}}function H_(e){return{not:_h(e)}}function U_(e){return _h(e)}var W_=(e,t)=>K_(e.innerType._def,t),G_=(e,t,n)=>{switch(t){case z.ZodString:return __(e,n);case z.ZodNumber:return N_(e,n);case z.ZodObject:return P_(e,n);case z.ZodBigInt:return r_(e,n);case z.ZodBoolean:return i_();case z.ZodDate:return s_(e,n);case z.ZodUndefined:return H_(n);case z.ZodNull:return O_(n);case z.ZodArray:return n_(e,n);case z.ZodUnion:case z.ZodDiscriminatedUnion:return A_(e,n);case z.ZodIntersection:return p_(e,n);case z.ZodTuple:return V_(e,n);case z.ZodRecord:return w_(e,n);case z.ZodLiteral:return m_(e,n);case z.ZodEnum:return d_(e);case z.ZodNativeEnum:return E_(e);case z.ZodNullable:return M_(e,n);case z.ZodOptional:return L_(e,n);case z.ZodMap:return T_(e,n);case z.ZodSet:return B_(e,n);case z.ZodLazy:return()=>e.getter()._def;case z.ZodPromise:return z_(e,n);case z.ZodNaN:case z.ZodNever:return D_(n);case z.ZodEffects:return u_(e,n);case z.ZodAny:return _h(n);case z.ZodUnknown:return U_(n);case z.ZodDefault:return l_(e,n);case z.ZodBranded:return a_(e,n);case z.ZodReadonly:return W_(e,n);case z.ZodCatch:return o_(e,n);case z.ZodPipeline:return R_(e,n);case z.ZodFunction:case z.ZodVoid:case z.ZodSymbol:return;default:return(e=>void 0)(t)}};function K_(e,t,n=!1){let r=t.seen.get(e);if(t.override){let i=t.override?.(e,t,r,n);if(i!==fh)return i}if(r&&!n){let e=q_(r,t);if(e!==void 0)return e}let i={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,i);let a=G_(e,e.typeName,t),o=typeof a==`function`?K_(a(),t):a;if(o&&J_(e,t,o),t.postProcess){let n=t.postProcess(o,e,t);return i.jsonSchema=o,n}return i.jsonSchema=o,o}var q_=(e,t)=>{switch(t.$refStrategy){case`root`:return{$ref:e.path.join(`/`)};case`relative`:return{$ref:gh(t.currentPath,e.path)};case`none`:case`seen`:return e.path.length<t.currentPath.length&&e.path.every((e,n)=>t.currentPath[n]===e)?(console.warn(`Recursive reference detected at ${t.currentPath.join(`/`)}! Defaulting to any`),_h(t)):t.$refStrategy===`seen`?_h(t):void 0}},J_=(e,t,n)=>(e.description&&(n.description=e.description,t.markdownDescription&&(n.markdownDescription=e.description)),n),Y_=(e,t)=>{let n=hh(t),r=typeof t==`object`&&t.definitions?Object.entries(t.definitions).reduce((e,[t,r])=>({...e,[t]:K_(r._def,{...n,currentPath:[...n.basePath,n.definitionPath,t]},!0)??_h(n)}),{}):void 0,i=typeof t==`string`?t:t?.nameStrategy===`title`?void 0:t?.name,a=K_(e._def,i===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,i]},!1)??_h(n),o=typeof t==`object`&&t.name!==void 0&&t.nameStrategy===`title`?t.name:void 0;o!==void 0&&(a.title=o),n.flags.hasReferencedOpenAiAnyType&&(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(`/`)}}));let s=i===void 0?r?{...a,[n.definitionPath]:r}:a:{$ref:[...n.$refStrategy===`relative`?[]:n.basePath,n.definitionPath,i].join(`/`),[n.definitionPath]:{...r,[i]:a}};return n.target===`jsonSchema7`?s.$schema=`http://json-schema.org/draft-07/schema#`:(n.target===`jsonSchema2019-09`||n.target===`openAi`)&&(s.$schema=`https://json-schema.org/draft/2019-09/schema#`),n.target===`openAi`&&(`anyOf`in s||`oneOf`in s||`allOf`in s||`type`in s&&Array.isArray(s.type))&&console.warn(`Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.`),s},X_=o({isSerializableSchema:()=>$_,isStandardJsonSchema:()=>Q_,isStandardSchema:()=>Z_});function Z_(e){return(typeof e==`object`||typeof e==`function`)&&e!==null&&`~standard`in e&&typeof e[`~standard`]==`object`&&e[`~standard`]!==null&&`validate`in e[`~standard`]}function Q_(e){return(typeof e==`object`||typeof e==`function`)&&e!==null&&`~standard`in e&&typeof e[`~standard`]==`object`&&e[`~standard`]!==null&&`jsonSchema`in e[`~standard`]}function $_(e){return Z_(e)&&Q_(e)}function ev(e,t){let n=typeof e;if(n!==typeof t)return!1;if(Array.isArray(e)){if(!Array.isArray(t))return!1;let n=e.length;if(n!==t.length)return!1;for(let r=0;r<n;r++)if(!ev(e[r],t[r]))return!1;return!0}if(n===`object`){if(!e||!t)return e===t;let n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(let r of n)if(!ev(e[r],t[r]))return!1;return!0}return e===t}function tv(e){return encodeURI(nv(e))}function nv(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}var rv={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},iv={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},av={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},ov=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 sv(e,t=Object.create(null),n=ov,r=``){if(e&&typeof e==`object`&&!Array.isArray(e)){let i=e.$id||e.id;if(i){let a=new URL(i,n.href);a.hash.length>1?t[a.href]=e:(a.hash=``,r===``?n=a:sv(e,t,n))}}else if(e!==!0&&e!==!1)return t;let i=n.href+(r?`#`+r:``);if(t[i]!==void 0)throw Error(`Duplicate schema URI "${i}".`);if(t[i]=e,e===!0||e===!1)return t;if(e.__absolute_uri__===void 0&&Object.defineProperty(e,`__absolute_uri__`,{enumerable:!1,value:i}),e.$ref&&e.__absolute_ref__===void 0){let t=new URL(e.$ref,n.href);t.hash=t.hash,Object.defineProperty(e,`__absolute_ref__`,{enumerable:!1,value:t.href})}if(e.$recursiveRef&&e.__absolute_recursive_ref__===void 0){let t=new URL(e.$recursiveRef,n.href);t.hash=t.hash,Object.defineProperty(e,`__absolute_recursive_ref__`,{enumerable:!1,value:t.href})}if(e.$anchor){let r=new URL(`#`+e.$anchor,n.href);t[r.href]=e}for(let i in e){if(av[i])continue;let a=`${r}/${tv(i)}`,o=e[i];if(Array.isArray(o)){if(rv[i]){let e=o.length;for(let r=0;r<e;r++)sv(o[r],t,n,`${a}/${r}`)}}else if(iv[i])for(let e in o)sv(o[e],t,n,`${a}/${tv(e)}`);else sv(o,t,n,a)}return t}var cv=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,lv=[0,31,28,31,30,31,30,31,31,30,31,30,31],uv=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,dv=/^(?=.{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,fv=/^(?:[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,pv=/^(?:(?:[^\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,mv=/^(?:(?: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,hv=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,gv=/^(?:\/(?:[^~/]|~0|~1)*)*$/,_v=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,vv=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,yv=e=>{if(e[0]===`"`)return!1;let[t,n,...r]=e.split(`@`);return!t||!n||r.length!==0||t.length>64||n.length>253||t[0]===`.`||t.endsWith(`.`)||t.includes(`..`)||!/^[a-z0-9.-]+$/i.test(n)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(t)?!1:n.split(`.`).every(e=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(e))},bv=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,xv=/^((([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,Sv=e=>e.length>1&&e.length<80&&(/^P\d+([.,]\d+)?W$/.test(e)||/^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(e)&&/^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(e));function Cv(e){return e.test.bind(e)}var wv={date:Ev,time:Dv.bind(void 0,!1),"date-time":kv,duration:Sv,uri:Mv,"uri-reference":Cv(fv),"uri-template":Cv(pv),url:Cv(mv),email:yv,hostname:Cv(dv),ipv4:Cv(bv),ipv6:Cv(xv),regex:Pv,uuid:Cv(hv),"json-pointer":Cv(gv),"json-pointer-uri-fragment":Cv(_v),"relative-json-pointer":Cv(vv)};function Tv(e){return e%4==0&&(e%100!=0||e%400==0)}function Ev(e){let t=e.match(cv);if(!t)return!1;let n=+t[1],r=+t[2],i=+t[3];return r>=1&&r<=12&&i>=1&&i<=(r==2&&Tv(n)?29:lv[r])}function Dv(e,t){let n=t.match(uv);if(!n)return!1;let r=+n[1],i=+n[2],a=+n[3],o=!!n[5];return(r<=23&&i<=59&&a<=59||r==23&&i==59&&a==60)&&(!e||o)}var Ov=/t|\s/i;function kv(e){let t=e.split(Ov);return t.length==2&&Ev(t[0])&&Dv(!0,t[1])}var Av=/\/|:/,jv=/^(?:[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 Mv(e){return Av.test(e)&&jv.test(e)}var Nv=/[^\\]\\Z/;function Pv(e){if(Nv.test(e))return!1;try{return new RegExp(e,`u`),!0}catch{return!1}}function Fv(e){let t=0,n=e.length,r=0,i;for(;r<n;)t++,i=e.charCodeAt(r++),i>=55296&&i<=56319&&r<n&&(i=e.charCodeAt(r),(i&64512)==56320&&r++);return t}function Iv(e,t,n=`2019-09`,r=sv(t),i=!0,a=null,o=`#`,s=`#`,c=Object.create(null)){if(t===!0)return{valid:!0,errors:[]};if(t===!1)return{valid:!1,errors:[{instanceLocation:o,keyword:`false`,keywordLocation:o,error:`False boolean schema.`}]};let l=typeof e,u;switch(l){case`boolean`:case`number`:case`string`:u=l;break;case`object`:u=e===null?`null`:Array.isArray(e)?`array`:`object`;break;default:throw Error(`Instances of "${l}" type are not supported.`)}let{$ref:d,$recursiveRef:f,$recursiveAnchor:p,type:m,const:h,enum:g,required:_,not:v,anyOf:y,allOf:b,oneOf:ee,if:x,then:te,else:S,format:ne,properties:re,patternProperties:ie,additionalProperties:ae,unevaluatedProperties:oe,minProperties:se,maxProperties:ce,propertyNames:C,dependentRequired:le,dependentSchemas:ue,dependencies:de,prefixItems:fe,items:pe,additionalItems:me,unevaluatedItems:he,contains:ge,minContains:_e,maxContains:ve,minItems:ye,maxItems:be,uniqueItems:xe,minimum:Se,maximum:Ce,exclusiveMinimum:we,exclusiveMaximum:Te,multipleOf:w,minLength:T,maxLength:Ee,pattern:E,__absolute_ref__:De,__absolute_recursive_ref__:Oe}=t,D=[];if(p===!0&&a===null&&(a=t),f===`#`){let l=a===null?r[Oe]:a,u=`${s}/$recursiveRef`,d=Iv(e,a===null?t:a,n,r,i,l,o,u,c);d.valid||D.push({instanceLocation:o,keyword:`$recursiveRef`,keywordLocation:u,error:`A subschema had errors.`},...d.errors)}if(d!==void 0){let t=r[De||d];if(t===void 0){let e=`Unresolved $ref "${d}".`;throw De&&De!==d&&(e+=` Absolute URI "${De}".`),e+=`\nKnown schemas:\n- ${Object.keys(r).join(`
60
- - `)}`,Error(e)}let l=`${s}/$ref`,u=Iv(e,t,n,r,i,a,o,l,c);if(u.valid||D.push({instanceLocation:o,keyword:`$ref`,keywordLocation:l,error:`A subschema had errors.`},...u.errors),n===`4`||n===`7`)return{valid:D.length===0,errors:D}}if(Array.isArray(m)){let t=m.length,n=!1;for(let r=0;r<t;r++)if(u===m[r]||m[r]===`integer`&&u===`number`&&e%1==0&&e===e){n=!0;break}n||D.push({instanceLocation:o,keyword:`type`,keywordLocation:`${s}/type`,error:`Instance type "${u}" is invalid. Expected "${m.join(`", "`)}".`})}else m===`integer`?(u!==`number`||e%1||e!==e)&&D.push({instanceLocation:o,keyword:`type`,keywordLocation:`${s}/type`,error:`Instance type "${u}" is invalid. Expected "${m}".`}):m!==void 0&&u!==m&&D.push({instanceLocation:o,keyword:`type`,keywordLocation:`${s}/type`,error:`Instance type "${u}" is invalid. Expected "${m}".`});if(h!==void 0&&(u===`object`||u===`array`?ev(e,h)||D.push({instanceLocation:o,keyword:`const`,keywordLocation:`${s}/const`,error:`Instance does not match ${JSON.stringify(h)}.`}):e!==h&&D.push({instanceLocation:o,keyword:`const`,keywordLocation:`${s}/const`,error:`Instance does not match ${JSON.stringify(h)}.`})),g!==void 0&&(u===`object`||u===`array`?g.some(t=>ev(e,t))||D.push({instanceLocation:o,keyword:`enum`,keywordLocation:`${s}/enum`,error:`Instance does not match any of ${JSON.stringify(g)}.`}):g.some(t=>e===t)||D.push({instanceLocation:o,keyword:`enum`,keywordLocation:`${s}/enum`,error:`Instance does not match any of ${JSON.stringify(g)}.`})),v!==void 0){let t=`${s}/not`;Iv(e,v,n,r,i,a,o,t).valid&&D.push({instanceLocation:o,keyword:`not`,keywordLocation:t,error:`Instance matched "not" schema.`})}let ke=[];if(y!==void 0){let t=`${s}/anyOf`,l=D.length,u=!1;for(let s=0;s<y.length;s++){let l=y[s],d=Object.create(c),f=Iv(e,l,n,r,i,p===!0?a:null,o,`${t}/${s}`,d);D.push(...f.errors),u||=f.valid,f.valid&&ke.push(d)}u?D.length=l:D.splice(l,0,{instanceLocation:o,keyword:`anyOf`,keywordLocation:t,error:`Instance does not match any subschemas.`})}if(b!==void 0){let t=`${s}/allOf`,l=D.length,u=!0;for(let s=0;s<b.length;s++){let l=b[s],d=Object.create(c),f=Iv(e,l,n,r,i,p===!0?a:null,o,`${t}/${s}`,d);D.push(...f.errors),u&&=f.valid,f.valid&&ke.push(d)}u?D.length=l:D.splice(l,0,{instanceLocation:o,keyword:`allOf`,keywordLocation:t,error:`Instance does not match every subschema.`})}if(ee!==void 0){let t=`${s}/oneOf`,l=D.length,u=ee.filter((s,l)=>{let u=Object.create(c),d=Iv(e,s,n,r,i,p===!0?a:null,o,`${t}/${l}`,u);return D.push(...d.errors),d.valid&&ke.push(u),d.valid}).length;u===1?D.length=l:D.splice(l,0,{instanceLocation:o,keyword:`oneOf`,keywordLocation:t,error:`Instance does not match exactly one subschema (${u} matches).`})}if((u===`object`||u===`array`)&&Object.assign(c,...ke),x!==void 0){let t=`${s}/if`;if(Iv(e,x,n,r,i,a,o,t,c).valid){if(te!==void 0){let l=Iv(e,te,n,r,i,a,o,`${s}/then`,c);l.valid||D.push({instanceLocation:o,keyword:`if`,keywordLocation:t,error:`Instance does not match "then" schema.`},...l.errors)}}else if(S!==void 0){let l=Iv(e,S,n,r,i,a,o,`${s}/else`,c);l.valid||D.push({instanceLocation:o,keyword:`if`,keywordLocation:t,error:`Instance does not match "else" schema.`},...l.errors)}}if(u===`object`){if(_!==void 0)for(let t of _)t in e||D.push({instanceLocation:o,keyword:`required`,keywordLocation:`${s}/required`,error:`Instance does not have required property "${t}".`});let t=Object.keys(e);if(se!==void 0&&t.length<se&&D.push({instanceLocation:o,keyword:`minProperties`,keywordLocation:`${s}/minProperties`,error:`Instance does not have at least ${se} properties.`}),ce!==void 0&&t.length>ce&&D.push({instanceLocation:o,keyword:`maxProperties`,keywordLocation:`${s}/maxProperties`,error:`Instance does not have at least ${ce} properties.`}),C!==void 0){let t=`${s}/propertyNames`;for(let s in e){let e=`${o}/${tv(s)}`,c=Iv(s,C,n,r,i,a,e,t);c.valid||D.push({instanceLocation:o,keyword:`propertyNames`,keywordLocation:t,error:`Property name "${s}" does not match schema.`},...c.errors)}}if(le!==void 0){let t=`${s}/dependantRequired`;for(let n in le)if(n in e){let r=le[n];for(let i of r)i in e||D.push({instanceLocation:o,keyword:`dependentRequired`,keywordLocation:t,error:`Instance has "${n}" but does not have "${i}".`})}}if(ue!==void 0)for(let t in ue){let l=`${s}/dependentSchemas`;if(t in e){let s=Iv(e,ue[t],n,r,i,a,o,`${l}/${tv(t)}`,c);s.valid||D.push({instanceLocation:o,keyword:`dependentSchemas`,keywordLocation:l,error:`Instance has "${t}" but does not match dependant schema.`},...s.errors)}}if(de!==void 0){let t=`${s}/dependencies`;for(let s in de)if(s in e){let c=de[s];if(Array.isArray(c))for(let n of c)n in e||D.push({instanceLocation:o,keyword:`dependencies`,keywordLocation:t,error:`Instance has "${s}" but does not have "${n}".`});else{let l=Iv(e,c,n,r,i,a,o,`${t}/${tv(s)}`);l.valid||D.push({instanceLocation:o,keyword:`dependencies`,keywordLocation:t,error:`Instance has "${s}" but does not match dependant schema.`},...l.errors)}}}let l=Object.create(null),u=!1;if(re!==void 0){let t=`${s}/properties`;for(let s in re){if(!(s in e))continue;let d=`${o}/${tv(s)}`,f=Iv(e[s],re[s],n,r,i,a,d,`${t}/${tv(s)}`);if(f.valid)c[s]=l[s]=!0;else if(u=i,D.push({instanceLocation:o,keyword:`properties`,keywordLocation:t,error:`Property "${s}" does not match schema.`},...f.errors),u)break}}if(!u&&ie!==void 0){let t=`${s}/patternProperties`;for(let s in ie){let d=new RegExp(s,`u`),f=ie[s];for(let p in e){if(!d.test(p))continue;let m=`${o}/${tv(p)}`,h=Iv(e[p],f,n,r,i,a,m,`${t}/${tv(s)}`);h.valid?c[p]=l[p]=!0:(u=i,D.push({instanceLocation:o,keyword:`patternProperties`,keywordLocation:t,error:`Property "${p}" matches pattern "${s}" but does not match associated schema.`},...h.errors))}}}if(!u&&ae!==void 0){let t=`${s}/additionalProperties`;for(let s in e){if(l[s])continue;let d=`${o}/${tv(s)}`,f=Iv(e[s],ae,n,r,i,a,d,t);f.valid?c[s]=!0:(u=i,D.push({instanceLocation:o,keyword:`additionalProperties`,keywordLocation:t,error:`Property "${s}" does not match additional properties schema.`},...f.errors))}}else if(!u&&oe!==void 0){let t=`${s}/unevaluatedProperties`;for(let s in e)if(!c[s]){let l=`${o}/${tv(s)}`,u=Iv(e[s],oe,n,r,i,a,l,t);u.valid?c[s]=!0:D.push({instanceLocation:o,keyword:`unevaluatedProperties`,keywordLocation:t,error:`Property "${s}" does not match unevaluated properties schema.`},...u.errors)}}}else if(u===`array`){be!==void 0&&e.length>be&&D.push({instanceLocation:o,keyword:`maxItems`,keywordLocation:`${s}/maxItems`,error:`Array has too many items (${e.length} > ${be}).`}),ye!==void 0&&e.length<ye&&D.push({instanceLocation:o,keyword:`minItems`,keywordLocation:`${s}/minItems`,error:`Array has too few items (${e.length} < ${ye}).`});let t=e.length,l=0,u=!1;if(fe!==void 0){let d=`${s}/prefixItems`,f=Math.min(fe.length,t);for(;l<f;l++){let t=Iv(e[l],fe[l],n,r,i,a,`${o}/${l}`,`${d}/${l}`);if(c[l]=!0,!t.valid&&(u=i,D.push({instanceLocation:o,keyword:`prefixItems`,keywordLocation:d,error:`Items did not match schema.`},...t.errors),u))break}}if(pe!==void 0){let d=`${s}/items`;if(Array.isArray(pe)){let s=Math.min(pe.length,t);for(;l<s;l++){let t=Iv(e[l],pe[l],n,r,i,a,`${o}/${l}`,`${d}/${l}`);if(c[l]=!0,!t.valid&&(u=i,D.push({instanceLocation:o,keyword:`items`,keywordLocation:d,error:`Items did not match schema.`},...t.errors),u))break}}else for(;l<t;l++){let t=Iv(e[l],pe,n,r,i,a,`${o}/${l}`,d);if(c[l]=!0,!t.valid&&(u=i,D.push({instanceLocation:o,keyword:`items`,keywordLocation:d,error:`Items did not match schema.`},...t.errors),u))break}if(!u&&me!==void 0){let d=`${s}/additionalItems`;for(;l<t;l++){let t=Iv(e[l],me,n,r,i,a,`${o}/${l}`,d);c[l]=!0,t.valid||(u=i,D.push({instanceLocation:o,keyword:`additionalItems`,keywordLocation:d,error:`Items did not match additional items schema.`},...t.errors))}}}if(ge!==void 0)if(t===0&&_e===void 0)D.push({instanceLocation:o,keyword:`contains`,keywordLocation:`${s}/contains`,error:`Array is empty. It must contain at least one item matching the schema.`});else if(_e!==void 0&&t<_e)D.push({instanceLocation:o,keyword:`minContains`,keywordLocation:`${s}/minContains`,error:`Array has less items (${t}) than minContains (${_e}).`});else{let l=`${s}/contains`,u=D.length,d=0;for(let s=0;s<t;s++){let t=Iv(e[s],ge,n,r,i,a,`${o}/${s}`,l);t.valid?(c[s]=!0,d++):D.push(...t.errors)}d>=(_e||0)&&(D.length=u),_e===void 0&&ve===void 0&&d===0?D.splice(u,0,{instanceLocation:o,keyword:`contains`,keywordLocation:l,error:`Array does not contain item matching schema.`}):_e!==void 0&&d<_e?D.push({instanceLocation:o,keyword:`minContains`,keywordLocation:`${s}/minContains`,error:`Array must contain at least ${_e} items matching schema. Only ${d} items were found.`}):ve!==void 0&&d>ve&&D.push({instanceLocation:o,keyword:`maxContains`,keywordLocation:`${s}/maxContains`,error:`Array may contain at most ${ve} items matching schema. ${d} items were found.`})}if(!u&&he!==void 0){let u=`${s}/unevaluatedItems`;for(;l<t;l++){if(c[l])continue;let t=Iv(e[l],he,n,r,i,a,`${o}/${l}`,u);c[l]=!0,t.valid||D.push({instanceLocation:o,keyword:`unevaluatedItems`,keywordLocation:u,error:`Items did not match unevaluated items schema.`},...t.errors)}}if(xe)for(let n=0;n<t;n++){let r=e[n],i=typeof r==`object`&&!!r;for(let a=0;a<t;a++){if(n===a)continue;let t=e[a];(r===t||i&&typeof t==`object`&&t&&ev(r,t))&&(D.push({instanceLocation:o,keyword:`uniqueItems`,keywordLocation:`${s}/uniqueItems`,error:`Duplicate items at indexes ${n} and ${a}.`}),n=2**53-1,a=2**53-1)}}}else if(u===`number`){if(n===`4`?(Se!==void 0&&(we===!0&&e<=Se||e<Se)&&D.push({instanceLocation:o,keyword:`minimum`,keywordLocation:`${s}/minimum`,error:`${e} is less than ${we?`or equal to `:``} ${Se}.`}),Ce!==void 0&&(Te===!0&&e>=Ce||e>Ce)&&D.push({instanceLocation:o,keyword:`maximum`,keywordLocation:`${s}/maximum`,error:`${e} is greater than ${Te?`or equal to `:``} ${Ce}.`})):(Se!==void 0&&e<Se&&D.push({instanceLocation:o,keyword:`minimum`,keywordLocation:`${s}/minimum`,error:`${e} is less than ${Se}.`}),Ce!==void 0&&e>Ce&&D.push({instanceLocation:o,keyword:`maximum`,keywordLocation:`${s}/maximum`,error:`${e} is greater than ${Ce}.`}),we!==void 0&&e<=we&&D.push({instanceLocation:o,keyword:`exclusiveMinimum`,keywordLocation:`${s}/exclusiveMinimum`,error:`${e} is less than ${we}.`}),Te!==void 0&&e>=Te&&D.push({instanceLocation:o,keyword:`exclusiveMaximum`,keywordLocation:`${s}/exclusiveMaximum`,error:`${e} is greater than or equal to ${Te}.`})),w!==void 0){let t=e%w;Math.abs(0-t)>=1.1920929e-7&&Math.abs(w-t)>=1.1920929e-7&&D.push({instanceLocation:o,keyword:`multipleOf`,keywordLocation:`${s}/multipleOf`,error:`${e} is not a multiple of ${w}.`})}}else if(u===`string`){let t=T===void 0&&Ee===void 0?0:Fv(e);T!==void 0&&t<T&&D.push({instanceLocation:o,keyword:`minLength`,keywordLocation:`${s}/minLength`,error:`String is too short (${t} < ${T}).`}),Ee!==void 0&&t>Ee&&D.push({instanceLocation:o,keyword:`maxLength`,keywordLocation:`${s}/maxLength`,error:`String is too long (${t} > ${Ee}).`}),E!==void 0&&!new RegExp(E,`u`).test(e)&&D.push({instanceLocation:o,keyword:`pattern`,keywordLocation:`${s}/pattern`,error:`String does not match pattern.`}),ne!==void 0&&wv[ne]&&!wv[ne](e)&&D.push({instanceLocation:o,keyword:`format`,keywordLocation:`${s}/format`,error:`String does not match format "${ne}".`})}return{valid:D.length===0,errors:D}}var Lv=class{schema;draft;shortCircuit;lookup;constructor(e,t=`2019-09`,n=!0){this.schema=e,this.draft=t,this.shortCircuit=n,this.lookup=sv(e)}validate(e){return Iv(e,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(e,t){t&&(e={...e,$id:t}),sv(e,this.lookup)}},Rv=o({Validator:()=>Lv,deepCompareStrict:()=>ev,toJsonSchema:()=>Bv,validatesOnlyStrings:()=>Vv}),zv=new WeakMap;function Bv(e,t){let n=!t&&typeof e==`object`&&!!e;if(n){let t=zv.get(e);if(t)return t}let r;if(Q_(e)&&!km(e))r=e[`~standard`].jsonSchema.input({target:`draft-07`});else if(km(e)){let n=ih(e,!0);r=Wm(n)?Dm(Qm(n,!0),t):Dm(e,t)}else r=Am(e)?Y_(e):e;return n&&typeof r==`object`&&r&&zv.set(e,r),r}function Vv(e){if(!e||typeof e!=`object`||Object.keys(e).length===0||Array.isArray(e))return!1;if(`type`in e)return typeof e.type==`string`?e.type===`string`:Array.isArray(e.type)?e.type.every(e=>e===`string`):!1;if(`enum`in e)return Array.isArray(e.enum)&&e.enum.length>0&&e.enum.every(e=>typeof e==`string`);if(`const`in e)return typeof e.const==`string`;if(`allOf`in e&&Array.isArray(e.allOf))return e.allOf.some(e=>Vv(e));if(`anyOf`in e&&Array.isArray(e.anyOf)||`oneOf`in e&&Array.isArray(e.oneOf)){let t=`anyOf`in e?e.anyOf:e.oneOf;return t.length>0&&t.every(e=>Vv(e))}if(`not`in e)return!1;if(`$ref`in e&&typeof e.$ref==`string`){let t=e.$ref,n=sv(e);return n[t]?Vv(n[t]):!1}return!1}var Hv=o({Graph:()=>Gv});function Uv(e,t){if(e!==void 0&&!kn(e))return e;if(gu(t))try{let e=t.getName();return e=e.startsWith(`Runnable`)?e.slice(8):e,e}catch{return t.getName()}else return t.name??`UnknownSchema`}function Wv(e){return gu(e.data)?{type:`runnable`,data:{id:e.data.lc_id,name:e.data.getName()}}:{type:`schema`,data:{...Bv(e.data.schema),title:e.data.name}}}var Gv=class e{nodes={};edges=[];constructor(e){this.nodes=e?.nodes??this.nodes,this.edges=e?.edges??this.edges}toJSON(){let e={};return Object.values(this.nodes).forEach((t,n)=>{e[t.id]=kn(t.id)?n:t.id}),{nodes:Object.values(this.nodes).map(t=>({id:e[t.id],...Wv(t)})),edges:this.edges.map(t=>{let n={source:e[t.source],target:e[t.target]};return t.data!==void 0&&(n.data=t.data),t.conditional!==void 0&&(n.conditional=t.conditional),n})}}addNode(e,t,n){if(t!==void 0&&this.nodes[t]!==void 0)throw Error(`Node with id ${t} already exists`);let r=t??Kn(),i={id:r,data:e,name:Uv(t,e),metadata:n};return this.nodes[r]=i,i}removeNode(e){delete this.nodes[e.id],this.edges=this.edges.filter(t=>t.source!==e.id&&t.target!==e.id)}addEdge(e,t,n,r){if(this.nodes[e.id]===void 0)throw Error(`Source node ${e.id} not in graph`);if(this.nodes[t.id]===void 0)throw Error(`Target node ${t.id} not in graph`);let i={source:e.id,target:t.id,data:n,conditional:r};return this.edges.push(i),i}firstNode(){return Kv(this)}lastNode(){return qv(this)}extend(e,t=``){let n=t;Object.values(e.nodes).map(e=>e.id).every(kn)&&(n=``);let r=e=>n?`${n}:${e}`:e;Object.entries(e.nodes).forEach(([e,t])=>{this.nodes[r(e)]={...t,id:r(e)}});let i=e.edges.map(e=>({...e,source:r(e.source),target:r(e.target)}));this.edges=[...this.edges,...i];let a=e.firstNode(),o=e.lastNode();return[a?{id:r(a.id),data:a.data}:void 0,o?{id:r(o.id),data:o.data}:void 0]}trimFirstNode(){let e=this.firstNode();e&&Kv(this,[e.id])&&this.removeNode(e)}trimLastNode(){let e=this.lastNode();e&&qv(this,[e.id])&&this.removeNode(e)}reid(){let t=Object.fromEntries(Object.values(this.nodes).map(e=>[e.id,e.name])),n=new Map;Object.values(t).forEach(e=>{n.set(e,(n.get(e)||0)+1)});let r=e=>{let r=t[e];return kn(e)&&n.get(r)===1?r:e};return new e({nodes:Object.fromEntries(Object.entries(this.nodes).map(([e,t])=>[r(e),{...t,id:r(e)}])),edges:this.edges.map(e=>({...e,source:r(e.source),target:r(e.target)}))})}drawMermaid(e){let{withStyles:t,curveStyle:n,nodeColors:r={default:`fill:#f2f0ff,line-height:1.2`,first:`fill-opacity:0`,last:`fill:#bfb6fc`},wrapLabelNWords:i}=e??{},a=this.reid(),o=a.firstNode(),s=a.lastNode();return uh(a.nodes,a.edges,{firstNode:o?.id,lastNode:s?.id,withStyles:t,curveStyle:n,nodeColors:r,wrapLabelNWords:i})}async drawMermaidPng(e){return dh(this.drawMermaid(e),{backgroundColor:e?.backgroundColor})}};function Kv(e,t=[]){let n=new Set(e.edges.filter(e=>!t.includes(e.source)).map(e=>e.target)),r=[];for(let i of Object.values(e.nodes))!t.includes(i.id)&&!n.has(i.id)&&r.push(i);return r.length===1?r[0]:void 0}function qv(e,t=[]){let n=new Set(e.edges.filter(e=>!t.includes(e.target)).map(e=>e.source)),r=[];for(let i of Object.values(e.nodes))!t.includes(i.id)&&!n.has(i.id)&&r.push(i);return r.length===1?r[0]:void 0}function Jv(e){let t=new TextEncoder,n=new ReadableStream({async start(n){for await(let r of e)n.enqueue(t.encode(`event: data\ndata: ${JSON.stringify(r)}\n\n`));n.enqueue(t.encode(`event: end
61
-
62
- `)),n.close()}});return ul.fromReadableStream(n)}function Yv(e){return typeof e==`object`&&!!e&&typeof e[Symbol.iterator]==`function`&&typeof e.next==`function`}var Xv=e=>typeof e==`object`&&!!e&&`next`in e&&typeof e.next==`function`;function Zv(e){return typeof e==`object`&&!!e&&typeof e[Symbol.asyncIterator]==`function`}function Qv(e){return typeof e==`object`&&!!e&&typeof e.next==`function`}async function $v(e,t){try{let n=await e.next();for(;!n.done;)await t?.(n.value),n=await e.next();return n.value}finally{await e.return?.(void 0)}}function*ey(e,t){for(;;){let{value:n,done:r}=Zc.runWithConfig(ol(e),t.next.bind(t),!0);if(r)break;yield n}}async function*ty(e,t){let n=t[Symbol.asyncIterator]();for(;;){let{value:r,done:i}=await Zc.runWithConfig(ol(e),n.next.bind(t),!0);if(i)break;yield r}}function ny(e,t){return e&&!Array.isArray(e)&&!(e instanceof Date)&&typeof e==`object`?e:{[t]:e}}var ry=class extends ge{lc_runnable=!0;name;getName(e){let t=this.name??this.constructor.lc_name()??this.constructor.name;return e?`${t}${e}`:t}withRetry(e){return new oy({bound:this,kwargs:{},config:{},maxAttemptNumber:e?.stopAfterAttempt,...e})}withConfig(e){return new iy({bound:this,config:e,kwargs:{}})}withFallbacks(e){let t=Array.isArray(e)?e:e.fallbacks;return new py({runnable:this,fallbacks:t})}_getOptionsList(e,t=0){if(Array.isArray(e)&&e.length!==t)throw Error(`Passed "options" must be an array with the same length as the inputs, but got ${e.length} options for ${t} inputs`);if(Array.isArray(e))return e.map(il);if(t>1&&!Array.isArray(e)&&e.runId){console.warn(`Provided runId will be used only for the first element of the batch.`);let n=Object.fromEntries(Object.entries(e).filter(([e])=>e!==`runId`));return Array.from({length:t},(t,r)=>il(r===0?e:n))}return Array.from({length:t},()=>il(e))}async batch(e,t,n){let r=this._getOptionsList(t??{},e.length),i=new mu({maxConcurrency:r[0]?.maxConcurrency??n?.maxConcurrency,onFailedAttempt:e=>{throw e}}),a=e.map((e,t)=>i.call(async()=>{try{return await this.invoke(e,r[t])}catch(e){if(n?.returnExceptions)return e;throw e}}));return Promise.all(a)}async*_streamIterator(e,t){yield this.invoke(e,t)}async stream(e,t){let n=il(t),r=new pl({generator:this._streamIterator(e,n),config:n});return await r.setup,ul.fromAsyncGenerator(r)}_separateRunnableConfigFromCallOptions(e){let t;t=il(e===void 0?e:{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});let n={...e};return delete n.callbacks,delete n.tags,delete n.metadata,delete n.runName,delete n.configurable,delete n.recursionLimit,delete n.maxConcurrency,delete n.runId,delete n.timeout,delete n.signal,[t,n]}async _callWithConfig(e,t,n){let r=il(n),i=await(await nl(r))?.handleChainStart(this.toJSON(),ny(t,`input`),r.runId,r?.runType,void 0,void 0,r?.runName??this.getName());delete r.runId;let a;try{a=await sl(e.call(this,t,r,i),r.signal)}catch(e){throw await i?.handleChainError(e),e}return await i?.handleChainEnd(ny(a,`output`)),a}async _batchWithConfig(e,t,n,r){let i=this._getOptionsList(n??{},t.length),a=await Promise.all(i.map(nl)),o=await Promise.all(a.map(async(e,n)=>{let r=await e?.handleChainStart(this.toJSON(),ny(t[n],`input`),i[n].runId,i[n].runType,void 0,void 0,i[n].runName??this.getName());return delete i[n].runId,r})),s;try{s=await sl(e.call(this,t,i,o,r),i?.[0]?.signal)}catch(e){throw await Promise.all(o.map(t=>t?.handleChainError(e))),e}return await Promise.all(o.map(e=>e?.handleChainEnd(ny(s,`output`)))),s}_concatOutputChunks(e,t){return fl(e,t)}async*_transformStreamWithConfig(e,t,n){let r,i=!0,a,o=!0,s=il(n),c=await nl(s),l=this;async function*u(){for await(let t of e){if(i)if(r===void 0)r=t;else try{r=l._concatOutputChunks(r,t)}catch{r=void 0,i=!1}yield t}}let d;try{let e=await ml(t.bind(this),u(),async()=>c?.handleChainStart(this.toJSON(),{input:``},s.runId,s.runType,void 0,void 0,s.runName??this.getName(),void 0,{lc_defers_inputs:!0}),s.signal,s);delete s.runId,d=e.setup;let n=d?.handlers.find(Ql),r=e.output;n!==void 0&&d!==void 0&&(r=n.tapOutputIterable(d.runId,r));let i=d?.handlers.find(Hl);i!==void 0&&d!==void 0&&(r=i.tapOutputIterable(d.runId,r));for await(let e of r)if(yield e,o)if(a===void 0)a=e;else try{a=this._concatOutputChunks(a,e)}catch{a=void 0,o=!1}}catch(e){throw await d?.handleChainError(e,void 0,void 0,void 0,{inputs:ny(r,`input`)}),e}await d?.handleChainEnd(a??{},void 0,void 0,void 0,{inputs:ny(r,`input`)})}getGraph(e){let t=new Gv,n=t.addNode({name:`${this.getName()}Input`,schema:Qg()}),r=t.addNode(this),i=t.addNode({name:`${this.getName()}Output`,schema:Qg()});return t.addEdge(n,r),t.addEdge(r,i),t}pipe(e){return new sy({first:this,last:my(e)})}pick(e){return this.pipe(new gy(e))}assign(e){return this.pipe(new hy(new cy({steps:e})))}async*transform(e,t){let n;for await(let t of e)n=n===void 0?t:this._concatOutputChunks(n,t);yield*this._streamIterator(n,il(t))}async*streamLog(e,t,n){let r=new Kl({...n,autoClose:!1,_schemaFormat:`original`}),i=il(t);yield*this._streamLog(e,r,i)}async*_streamLog(e,t,n){let{callbacks:r}=n;if(r===void 0)n.callbacks=[t];else if(Array.isArray(r))n.callbacks=r.concat([t]);else{let e=r.copy();e.addHandler(t,!0),n.callbacks=e}let i=this.stream(e,n);async function a(){try{let e=await i;for await(let n of e){let e=new Bl({ops:[{op:`add`,path:`/streamed_output/-`,value:n}]});await t.writer.write(e)}}finally{await t.writer.close()}}let o=a();try{for await(let e of t)yield e}finally{await o}}streamEvents(e,t,n){let r;if(t.version===`v1`)r=this._streamEventsV1(e,t,n);else if(t.version===`v2`)r=this._streamEventsV2(e,t,n);else throw Error(`Only versions "v1" and "v2" of the schema are currently supported.`);return t.encoding===`text/event-stream`?Jv(r):ul.fromAsyncGenerator(r)}async*_streamEventsV2(e,t,n){let r=new $l({...n,autoClose:!1}),i=il(t),a=i.runId??In();i.runId=a;let o=i.callbacks;if(o===void 0)i.callbacks=[r];else if(Array.isArray(o))i.callbacks=o.concat(r);else{let e=o.copy();e.addHandler(r,!0),i.callbacks=e}let s=new AbortController,c=this;async function l(){let t;try{if(i.signal)if(`any`in AbortSignal)t=AbortSignal.any([s.signal,i.signal]);else{let e=new AbortController;i.signal.addEventListener(`abort`,()=>e.abort(),{once:!0}),s.signal.addEventListener(`abort`,()=>e.abort(),{once:!0}),t=e.signal}else t=s.signal;let n=await c.stream(e,{...i,signal:t}),o=r.tapOutputIterable(a,n);for await(let e of o)if(s.signal.aborted)break}finally{await r.finish()}}let u=l(),d=!1,f;try{for await(let t of r){if(!d){t.data.input=e,d=!0,f=t.run_id,yield t;continue}t.run_id===f&&t.event.endsWith(`_end`)&&t.data?.input&&delete t.data.input,yield t}}finally{s.abort(),await u}}async*_streamEventsV1(e,t,n){let r,i=!1,a=il(t),o=a.tags??[],s=a.metadata??{},c=a.runName??this.getName(),l=new Kl({...n,autoClose:!1,_schemaFormat:`streaming_events`}),u=new _u({...n}),d=this._streamLog(e,l,a);for await(let t of d){if(r=r?r.concat(t):Vl.fromRunLogPatch(t),r.state===void 0)throw Error(`Internal error: "streamEvents" state is missing. Please open a bug report.`);if(!i){i=!0;let t={...r.state},n={run_id:t.id,event:`on_${t.type}_start`,name:c,tags:o,metadata:s,data:{input:e}};u.includeEvent(n,t.type)&&(yield n)}let n=t.ops.filter(e=>e.path.startsWith(`/logs/`)).map(e=>e.path.split(`/`)[2]),a=[...new Set(n)];for(let e of a){let t,n={},i=r.state.logs[e];if(t=i.end_time===void 0?i.streamed_output.length>0?`stream`:`start`:`end`,t===`start`)i.inputs!==void 0&&(n.input=i.inputs);else if(t===`end`)i.inputs!==void 0&&(n.input=i.inputs),n.output=i.final_output;else if(t===`stream`){let e=i.streamed_output.length;if(e!==1)throw Error(`Expected exactly one chunk of streamed output, got ${e} instead. Encountered in: "${i.name}"`);n={chunk:i.streamed_output[0]},i.streamed_output=[]}yield{event:`on_${i.type}_${t}`,name:i.name,run_id:i.id,tags:i.tags,metadata:i.metadata,data:n}}let{state:l}=r;if(l.streamed_output.length>0){let e=l.streamed_output.length;if(e!==1)throw Error(`Expected exactly one chunk of streamed output, got ${e} instead. Encountered in: "${l.name}"`);let t={chunk:l.streamed_output[0]};l.streamed_output=[];let n={event:`on_${l.type}_stream`,run_id:l.id,tags:o,metadata:s,name:c,data:t};u.includeEvent(n,l.type)&&(yield n)}}let f=r?.state;if(f!==void 0){let e={event:`on_${f.type}_end`,name:c,run_id:f.id,tags:o,metadata:s,data:{output:f.final_output}};u.includeEvent(e,f.type)&&(yield e)}}static isRunnable(e){return gu(e)}withListeners({onStart:e,onEnd:t,onError:n}){return new iy({bound:this,config:{},configFactories:[r=>({callbacks:[new hu({config:r,onStart:e,onEnd:t,onError:n})]})]})}asTool(e){return vy(this,e)}},iy=class e extends ry{static lc_name(){return`RunnableBinding`}lc_namespace=[`langchain_core`,`runnables`];lc_serializable=!0;bound;config;kwargs;configFactories;constructor(e){super(e),this.bound=e.bound,this.kwargs=e.kwargs,this.config=e.config,this.configFactories=e.configFactories}getName(e){return this.bound.getName(e)}async _mergeConfig(...e){let t=rl(this.config,...e);return rl(t,...this.configFactories?await Promise.all(this.configFactories.map(async e=>await e(t))):[])}withConfig(e){return new this.constructor({bound:this.bound,kwargs:this.kwargs,config:{...this.config,...e}})}withRetry(e){return new oy({bound:this.bound,kwargs:this.kwargs,config:this.config,maxAttemptNumber:e?.stopAfterAttempt,...e})}async invoke(e,t){return this.bound.invoke(e,await this._mergeConfig(t,this.kwargs))}async batch(e,t,n){let r=Array.isArray(t)?await Promise.all(t.map(async e=>this._mergeConfig(il(e),this.kwargs))):await this._mergeConfig(il(t),this.kwargs);return this.bound.batch(e,r,n)}_concatOutputChunks(e,t){return this.bound._concatOutputChunks(e,t)}async*_streamIterator(e,t){yield*this.bound._streamIterator(e,await this._mergeConfig(il(t),this.kwargs))}async stream(e,t){return this.bound.stream(e,await this._mergeConfig(il(t),this.kwargs))}async*transform(e,t){yield*this.bound.transform(e,await this._mergeConfig(il(t),this.kwargs))}streamEvents(e,t,n){let r=this;return ul.fromAsyncGenerator(async function*(){yield*r.bound.streamEvents(e,{...await r._mergeConfig(il(t),r.kwargs),version:t.version},n)}())}static isRunnableBinding(e){return e.bound&&ry.isRunnable(e.bound)}withListeners({onStart:t,onEnd:n,onError:r}){return new e({bound:this.bound,kwargs:this.kwargs,config:this.config,configFactories:[e=>({callbacks:[new hu({config:e,onStart:t,onEnd:n,onError:r})]})]})}},ay=class e extends ry{static lc_name(){return`RunnableEach`}lc_serializable=!0;lc_namespace=[`langchain_core`,`runnables`];bound;constructor(e){super(e),this.bound=e.bound}async invoke(e,t){return this._callWithConfig(this._invoke.bind(this),e,t)}async _invoke(e,t,n){return this.bound.batch(e,al(t,{callbacks:n?.getChild()}))}withListeners({onStart:t,onEnd:n,onError:r}){return new e({bound:this.bound.withListeners({onStart:t,onEnd:n,onError:r})})}},oy=class extends iy{static lc_name(){return`RunnableRetry`}lc_namespace=[`langchain_core`,`runnables`];maxAttemptNumber=3;onFailedAttempt=()=>{};constructor(e){super(e),this.maxAttemptNumber=e.maxAttemptNumber??this.maxAttemptNumber,this.onFailedAttempt=e.onFailedAttempt??this.onFailedAttempt}_patchConfigForRetry(e,t,n){let r=e>1?`retry:attempt:${e}`:void 0;return al(t,{callbacks:n?.getChild(r)})}async _invoke(e,t,n){return uu(r=>super.invoke(e,this._patchConfigForRetry(r,t,n)),{onFailedAttempt:({error:t})=>this.onFailedAttempt(t,e),retries:Math.max(this.maxAttemptNumber-1,0),randomize:!0})}async invoke(e,t){return this._callWithConfig(this._invoke.bind(this),e,t)}async _batch(e,t,n,r){let i={};try{await uu(async a=>{let o=e.map((e,t)=>t).filter(e=>i[e.toString()]===void 0||i[e.toString()]instanceof Error),s=o.map(t=>e[t]),c=o.map(e=>this._patchConfigForRetry(a,t?.[e],n?.[e])),l=await super.batch(s,c,{...r,returnExceptions:!0}),u;for(let e=0;e<l.length;e+=1){let t=l[e],n=o[e];t instanceof Error&&u===void 0&&(u=t,u.input=s[e]),i[n.toString()]=t}if(u)throw u;return l},{onFailedAttempt:({error:e})=>this.onFailedAttempt(e,e.input),retries:Math.max(this.maxAttemptNumber-1,0),randomize:!0})}catch(e){if(r?.returnExceptions!==!0)throw e}return Object.keys(i).sort((e,t)=>parseInt(e,10)-parseInt(t,10)).map(e=>i[parseInt(e,10)])}async batch(e,t,n){return this._batchWithConfig(this._batch.bind(this),e,t,n)}},sy=class e extends ry{static lc_name(){return`RunnableSequence`}first;middle=[];last;omitSequenceTags=!1;lc_serializable=!0;lc_namespace=[`langchain_core`,`runnables`];constructor(e){super(e),this.first=e.first,this.middle=e.middle??this.middle,this.last=e.last,this.name=e.name,this.omitSequenceTags=e.omitSequenceTags??this.omitSequenceTags}get steps(){return[this.first,...this.middle,this.last]}async invoke(e,t){let n=il(t),r=await(await nl(n))?.handleChainStart(this.toJSON(),ny(e,`input`),n.runId,void 0,void 0,void 0,n?.runName);delete n.runId;let i=e,a;try{let e=[this.first,...this.middle];for(let t=0;t<e.length;t+=1)i=await sl(e[t].invoke(i,al(n,{callbacks:r?.getChild(this.omitSequenceTags?void 0:`seq:step:${t+1}`)})),n.signal);if(n.signal?.aborted)throw cl(n.signal);a=await this.last.invoke(i,al(n,{callbacks:r?.getChild(this.omitSequenceTags?void 0:`seq:step:${this.steps.length}`)}))}catch(e){throw await r?.handleChainError(e),e}return await r?.handleChainEnd(ny(a,`output`)),a}async batch(e,t,n){let r=this._getOptionsList(t??{},e.length),i=await Promise.all(r.map(nl)),a=await Promise.all(i.map(async(t,n)=>{let i=await t?.handleChainStart(this.toJSON(),ny(e[n],`input`),r[n].runId,void 0,void 0,void 0,r[n].runName);return delete r[n].runId,i})),o=e;try{for(let e=0;e<this.steps.length;e+=1)o=await sl(this.steps[e].batch(o,a.map((t,n)=>{let i=t?.getChild(this.omitSequenceTags?void 0:`seq:step:${e+1}`);return al(r[n],{callbacks:i})}),n),r[0]?.signal)}catch(e){throw await Promise.all(a.map(t=>t?.handleChainError(e))),e}return await Promise.all(a.map(e=>e?.handleChainEnd(ny(o,`output`)))),o}_concatOutputChunks(e,t){return this.last._concatOutputChunks(e,t)}async*_streamIterator(e,t){let n=await nl(t),{runId:r,...i}=t??{},a=await n?.handleChainStart(this.toJSON(),ny(e,`input`),r,void 0,void 0,void 0,i?.runName),o=[this.first,...this.middle,this.last],s=!0,c;async function*l(){yield e}try{let e=o[0].transform(l(),al(i,{callbacks:a?.getChild(this.omitSequenceTags?void 0:`seq:step:1`)}));for(let t=1;t<o.length;t+=1)e=await o[t].transform(e,al(i,{callbacks:a?.getChild(this.omitSequenceTags?void 0:`seq:step:${t+1}`)}));for await(let n of e)if(t?.signal?.throwIfAborted(),yield n,s)if(c===void 0)c=n;else try{c=this._concatOutputChunks(c,n)}catch{c=void 0,s=!1}}catch(e){throw await a?.handleChainError(e),e}await a?.handleChainEnd(ny(c,`output`))}getGraph(e){let t=new Gv,n=null;return this.steps.forEach((r,i)=>{let a=r.getGraph(e);i!==0&&a.trimFirstNode(),i!==this.steps.length-1&&a.trimLastNode(),t.extend(a);let o=a.firstNode();if(!o)throw Error(`Runnable ${r} has no first node`);n&&t.addEdge(n,o),n=a.lastNode()}),t}pipe(t){return e.isRunnableSequence(t)?new e({first:this.first,middle:this.middle.concat([this.last,t.first,...t.middle]),last:t.last,name:this.name??t.name}):new e({first:this.first,middle:[...this.middle,this.last],last:my(t),name:this.name})}static isRunnableSequence(e){return Array.isArray(e.middle)&&ry.isRunnable(e)}static from([t,...n],r){let i={};return typeof r==`string`?i.name=r:r!==void 0&&(i=r),new e({...i,first:my(t),middle:n.slice(0,-1).map(my),last:my(n[n.length-1])})}},cy=class e extends ry{static lc_name(){return`RunnableMap`}lc_namespace=[`langchain_core`,`runnables`];lc_serializable=!0;steps;getStepsKeys(){return Object.keys(this.steps)}constructor(e){super(e),this.steps={};for(let[t,n]of Object.entries(e.steps))this.steps[t]=my(n)}static from(t){return new e({steps:t})}async invoke(e,t){let n=il(t),r=await(await nl(n))?.handleChainStart(this.toJSON(),{input:e},n.runId,void 0,void 0,void 0,n?.runName);delete n.runId;let i={};try{let t=Object.entries(this.steps).map(async([t,a])=>{i[t]=await a.invoke(e,al(n,{callbacks:r?.getChild(`map:key:${t}`)}))});await sl(Promise.all(t),n.signal)}catch(e){throw await r?.handleChainError(e),e}return await r?.handleChainEnd(i),i}async*_transform(e,t,n){let r={...this.steps},i=dl(e,Object.keys(r).length),a=new Map(Object.entries(r).map(([e,r],a)=>{let o=r.transform(i[a],al(n,{callbacks:t?.getChild(`map:key:${e}`)}));return[e,o.next().then(t=>({key:e,gen:o,result:t}))]}));for(;a.size;){let{key:e,result:t,gen:r}=await sl(Promise.race(a.values()),n?.signal);a.delete(e),t.done||(yield{[e]:t.value},a.set(e,r.next().then(t=>({key:e,gen:r,result:t}))))}}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){async function*n(){yield e}let r=il(t),i=new pl({generator:this.transform(n(),r),config:r});return await i.setup,ul.fromAsyncGenerator(i)}},ly=class e extends ry{lc_serializable=!1;lc_namespace=[`langchain_core`,`runnables`];func;constructor(e){if(super(e),!vc(e.func))throw Error(`RunnableTraceable requires a function that is wrapped in traceable higher-order function`);this.func=e.func}async invoke(e,t){let[n]=this._getOptionsList(t??{},1),r=await nl(n);return sl(this.func(al(n,{callbacks:r}),e),n?.signal)}async*_streamIterator(e,t){let[n]=this._getOptionsList(t??{},1),r=await this.invoke(e,t);if(Zv(r)){for await(let e of r)n?.signal?.throwIfAborted(),yield e;return}if(Xv(r)){for(;;){n?.signal?.throwIfAborted();let e=r.next();if(e.done)break;yield e.value}return}yield r}static from(t){return new e({func:t})}};function uy(e){if(vc(e))throw Error(`RunnableLambda requires a function that is not wrapped in traceable higher-order function. This shouldn't happen.`)}var dy=class e extends ry{static lc_name(){return`RunnableLambda`}lc_namespace=[`langchain_core`,`runnables`];func;constructor(e){if(vc(e.func))return ly.from(e.func);super(e),uy(e.func),this.func=e.func}static from(t){return new e({func:t})}async _invoke(e,t,n){return new Promise((r,i)=>{let a=al(t,{callbacks:n?.getChild(),recursionLimit:(t?.recursionLimit??25)-1});Zc.runWithConfig(ol(a),async()=>{try{let n=await this.func(e,{...a});if(n&&ry.isRunnable(n)){if(t?.recursionLimit===0)throw Error(`Recursion limit reached.`);n=await n.invoke(e,{...a,recursionLimit:(a.recursionLimit??25)-1})}else if(Zv(n)){let e;for await(let r of ty(a,n))if(t?.signal?.throwIfAborted(),e===void 0)e=r;else try{e=this._concatOutputChunks(e,r)}catch{e=r}n=e}else if(Yv(n)){let e;for(let r of ey(a,n))if(t?.signal?.throwIfAborted(),e===void 0)e=r;else try{e=this._concatOutputChunks(e,r)}catch{e=r}n=e}r(n)}catch(e){i(e)}})})}async invoke(e,t){return this._callWithConfig(this._invoke.bind(this),e,t)}async*_transform(e,t,n){let r;for await(let t of e)if(r===void 0)r=t;else try{r=this._concatOutputChunks(r,t)}catch{r=t}let i=al(n,{callbacks:t?.getChild(),recursionLimit:(n?.recursionLimit??25)-1}),a=await new Promise((e,t)=>{Zc.runWithConfig(ol(i),async()=>{try{e(await this.func(r,{...i,config:i}))}catch(e){t(e)}})});if(a&&ry.isRunnable(a)){if(n?.recursionLimit===0)throw Error(`Recursion limit reached.`);let e=await a.stream(r,i);for await(let t of e)yield t}else if(Zv(a))for await(let e of ty(i,a))n?.signal?.throwIfAborted(),yield e;else if(Yv(a))for(let e of ey(i,a))n?.signal?.throwIfAborted(),yield e;else yield a}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){async function*n(){yield e}let r=il(t),i=new pl({generator:this.transform(n(),r),config:r});return await i.setup,ul.fromAsyncGenerator(i)}},fy=class extends cy{},py=class extends ry{static lc_name(){return`RunnableWithFallbacks`}lc_namespace=[`langchain_core`,`runnables`];lc_serializable=!0;runnable;fallbacks;constructor(e){super(e),this.runnable=e.runnable,this.fallbacks=e.fallbacks}*runnables(){yield this.runnable;for(let e of this.fallbacks)yield e}async invoke(e,t){let n=il(t),r=await nl(n),{runId:i,...a}=n,o=await r?.handleChainStart(this.toJSON(),ny(e,`input`),i,void 0,void 0,void 0,a?.runName),s=al(a,{callbacks:o?.getChild()});return await Zc.runWithConfig(s,async()=>{let t;for(let r of this.runnables()){n?.signal?.throwIfAborted();try{let t=await r.invoke(e,s);return await o?.handleChainEnd(ny(t,`output`)),t}catch(e){t===void 0&&(t=e)}}throw t===void 0?Error(`No error stored at end of fallback.`):(await o?.handleChainError(t),t)})}async*_streamIterator(e,t){let n=il(t),r=await nl(n),{runId:i,...a}=n,o=await r?.handleChainStart(this.toJSON(),ny(e,`input`),i,void 0,void 0,void 0,a?.runName),s,c;for(let t of this.runnables()){n?.signal?.throwIfAborted();let r=al(a,{callbacks:o?.getChild()});try{c=ty(r,await t.stream(e,r));break}catch(e){s===void 0&&(s=e)}}if(c===void 0){let e=s??Error(`No error stored at end of fallback.`);throw await o?.handleChainError(e),e}let l;try{for await(let e of c){yield e;try{l=l===void 0?l:this._concatOutputChunks(l,e)}catch{l=void 0}}}catch(e){throw await o?.handleChainError(e),e}await o?.handleChainEnd(ny(l,`output`))}async batch(e,t,n){if(n?.returnExceptions)throw Error(`Not implemented.`);let r=this._getOptionsList(t??{},e.length),i=await Promise.all(r.map(e=>nl(e))),a=await Promise.all(i.map(async(t,n)=>{let i=await t?.handleChainStart(this.toJSON(),ny(e[n],`input`),r[n].runId,void 0,void 0,void 0,r[n].runName);return delete r[n].runId,i})),o;for(let t of this.runnables()){r[0].signal?.throwIfAborted();try{let i=await t.batch(e,a.map((e,t)=>al(r[t],{callbacks:e?.getChild()})),n);return await Promise.all(a.map((e,t)=>e?.handleChainEnd(ny(i[t],`output`)))),i}catch(e){o===void 0&&(o=e)}}throw o?(await Promise.all(a.map(e=>e?.handleChainError(o))),o):Error(`No error stored at end of fallbacks.`)}};function my(e){if(typeof e==`function`)return new dy({func:e});if(ry.isRunnable(e))return e;if(!Array.isArray(e)&&typeof e==`object`){let t={};for(let[n,r]of Object.entries(e))t[n]=my(r);return new cy({steps:t})}else throw Error(`Expected a Runnable, function or object.
63
- Instead got an unsupported type.`)}var hy=class extends ry{static lc_name(){return`RunnableAssign`}lc_namespace=[`langchain_core`,`runnables`];lc_serializable=!0;mapper;constructor(e){e instanceof cy&&(e={mapper:e}),super(e),this.mapper=e.mapper}async invoke(e,t){let n=await this.mapper.invoke(e,t);return{...e,...n}}async*_transform(e,t,n){let r=this.mapper.getStepsKeys(),[i,a]=dl(e),o=this.mapper.transform(a,al(n,{callbacks:t?.getChild()})),s=o.next();for await(let e of i){if(typeof e!=`object`||Array.isArray(e))throw Error(`RunnableAssign can only be used with objects as input, got ${typeof e}`);let t=Object.fromEntries(Object.entries(e).filter(([e])=>!r.includes(e)));Object.keys(t).length>0&&(yield t)}yield(await s).value;for await(let e of o)yield e}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){async function*n(){yield e}let r=il(t),i=new pl({generator:this.transform(n(),r),config:r});return await i.setup,ul.fromAsyncGenerator(i)}},gy=class extends ry{static lc_name(){return`RunnablePick`}lc_namespace=[`langchain_core`,`runnables`];lc_serializable=!0;keys;constructor(e){(typeof e==`string`||Array.isArray(e))&&(e={keys:e}),super(e),this.keys=e.keys}async _pick(e){if(typeof this.keys==`string`)return e[this.keys];{let t=this.keys.map(t=>[t,e[t]]).filter(e=>e[1]!==void 0);return t.length===0?void 0:Object.fromEntries(t)}}async invoke(e,t){return this._callWithConfig(this._pick.bind(this),e,t)}async*_transform(e){for await(let t of e){let e=await this._pick(t);e!==void 0&&(yield e)}}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){async function*n(){yield e}let r=il(t),i=new pl({generator:this.transform(n(),r),config:r});return await i.setup,ul.fromAsyncGenerator(i)}},_y=class extends iy{name;description;schema;constructor(e){let t=sy.from([dy.from(async e=>{let t;if(h(e))try{t=await Lm(this.schema,e.args)}catch{throw new _(`Received tool input did not match expected schema`,JSON.stringify(e.args))}else t=e;return t}).withConfig({runName:`${e.name}:parse_input`}),e.bound]).withConfig({runName:e.name});super({bound:t,config:e.config??{}}),this.name=e.name,this.description=e.description,this.schema=e.schema}static lc_name(){return`RunnableToolLike`}};function vy(e,t){let n=t.name??e.getName(),r=t.description??Bm(t.schema);return Hm(t.schema)?new _y({name:n,description:r,schema:e_({input:Yg()}).transform(e=>e.input),bound:e}):new _y({name:n,description:r,schema:t.schema,bound:e})}var yy=class extends ry{static lc_name(){return`RunnablePassthrough`}lc_namespace=[`langchain_core`,`runnables`];lc_serializable=!0;func;constructor(e){super(e),e&&(this.func=e.func)}async invoke(e,t){let n=il(t);return this.func&&await this.func(e,n),this._callWithConfig(e=>Promise.resolve(e),e,n)}async*transform(e,t){let n=il(t),r,i=!0;for await(let t of this._transformStreamWithConfig(e,e=>e,n))if(yield t,i)if(r===void 0)r=t;else try{r=fl(r,t)}catch{r=void 0,i=!1}this.func&&r!==void 0&&await this.func(r,n)}static assign(e){return new hy(new cy({steps:e}))}},by=class extends ry{static lc_name(){return`RouterRunnable`}lc_namespace=[`langchain_core`,`runnables`];lc_serializable=!0;runnables;constructor(e){super(e),this.runnables=e.runnables}async invoke(e,t){let{key:n,input:r}=e,i=this.runnables[n];if(i===void 0)throw Error(`No runnable associated with key "${n}".`);return i.invoke(r,il(t))}async batch(e,t,n){let r=e.map(e=>e.key),i=e.map(e=>e.input);if(r.find(e=>this.runnables[e]===void 0)!==void 0)throw Error(`One or more keys do not have a corresponding runnable.`);let a=r.map(e=>this.runnables[e]),o=this._getOptionsList(t??{},e.length),s=o[0]?.maxConcurrency??n?.maxConcurrency,c=s&&s>0?s:e.length,l=[];for(let e=0;e<i.length;e+=c){let t=i.slice(e,e+c).map((e,t)=>a[t].invoke(e,o[t])),n=await Promise.all(t);l.push(n)}return l.flat()}async stream(e,t){let{key:n,input:r}=e,i=this.runnables[n];if(i===void 0)throw Error(`No runnable associated with key "${n}".`);return i.stream(r,t)}},xy=class extends ry{static lc_name(){return`RunnableBranch`}lc_namespace=[`langchain_core`,`runnables`];lc_serializable=!0;default;branches;constructor(e){super(e),this.branches=e.branches,this.default=e.default}static from(e){if(e.length<1)throw Error(`RunnableBranch requires at least one branch`);let t=e.slice(0,-1).map(([e,t])=>[my(e),my(t)]),n=my(e[e.length-1]);return new this({branches:t,default:n})}async _invoke(e,t,n){let r;for(let i=0;i<this.branches.length;i+=1){let[a,o]=this.branches[i];if(await a.invoke(e,al(t,{callbacks:n?.getChild(`condition:${i+1}`)}))){r=await o.invoke(e,al(t,{callbacks:n?.getChild(`branch:${i+1}`)}));break}}return r||=await this.default.invoke(e,al(t,{callbacks:n?.getChild(`branch:default`)})),r}async invoke(e,t={}){return this._callWithConfig(this._invoke,e,t)}async*_streamIterator(e,t){let n=await(await nl(t))?.handleChainStart(this.toJSON(),ny(e,`input`),t?.runId,void 0,void 0,void 0,t?.runName),r,i=!0,a;try{for(let o=0;o<this.branches.length;o+=1){let[s,c]=this.branches[o];if(await s.invoke(e,al(t,{callbacks:n?.getChild(`condition:${o+1}`)}))){a=await c.stream(e,al(t,{callbacks:n?.getChild(`branch:${o+1}`)}));for await(let e of a)if(yield e,i)if(r===void 0)r=e;else try{r=fl(r,e)}catch{r=void 0,i=!1}break}}if(a===void 0){a=await this.default.stream(e,al(t,{callbacks:n?.getChild(`branch:default`)}));for await(let e of a)if(yield e,i)if(r===void 0)r=e;else try{r=fl(r,e)}catch{r=void 0,i=!1}}}catch(e){throw await n?.handleChainError(e),e}await n?.handleChainEnd(r??{})}},Sy=(e,t)=>{let n=[...new Set(t?.map(e=>{if(typeof e==`string`)return e;let t=new e({});if(!(`getType`in t)||typeof t.getType!=`function`)throw Error(`Invalid type provided.`);return t.getType()}))],r=e.getType();return n.some(e=>e===r)};function Cy(e,t){return Array.isArray(e)?wy(e,t):dy.from(t=>wy(t,e))}function wy(e,t={}){let{includeNames:n,excludeNames:r,includeTypes:i,excludeTypes:a,includeIds:o,excludeIds:s}=t,c=[];for(let t of e)r&&t.name&&r.includes(t.name)||a&&Sy(t,a)||s&&t.id&&s.includes(t.id)||(i||o||n?(n&&t.name&&n.some(e=>e===t.name)||i&&Sy(t,i)||o&&t.id&&o.some(e=>e===t.id))&&c.push(t):c.push(t));return c}function Ty(e){return Array.isArray(e)?Ey(e):dy.from(Ey)}function Ey(e){if(!e.length)return[];let t=[];for(let n of e){let e=n,r=t.pop();if(!r)t.push(e);else if(e.getType()===`tool`||e.getType()!==r.getType())t.push(r,e);else{let n=En(r),i=En(e),a=n.concat(i);typeof n.content==`string`&&typeof i.content==`string`&&(a.content=`${n.content}\n${i.content}`),t.push(Ny(a))}}return t}function Dy(e,t){if(Array.isArray(e)){let n=e;if(!t)throw Error(`Options parameter is required when providing messages.`);return Oy(n,t)}else{let t=e;return dy.from(e=>Oy(e,t)).withConfig({runName:`trim_messages`})}}async function Oy(e,t){let{maxTokens:n,tokenCounter:r,strategy:i=`last`,allowPartial:a=!1,endOn:o,startOn:s,includeSystem:c=!1,textSplitter:l}=t;if(s&&i===`first`)throw Error("`startOn` should only be specified if `strategy` is 'last'.");if(c&&i===`first`)throw Error("`includeSystem` should only be specified if `strategy` is 'last'.");let u;u=`getNumTokens`in r?async e=>(await Promise.all(e.map(e=>r.getNumTokens(e.content)))).reduce((e,t)=>e+t,0):async e=>r(e);let d=Py;if(l&&(d=`splitText`in l?l.splitText:async e=>l(e)),i===`first`)return ky(e,{maxTokens:n,tokenCounter:u,textSplitter:d,partialStrategy:a?`first`:void 0,endOn:o});if(i===`last`)return Ay(e,{maxTokens:n,tokenCounter:u,textSplitter:d,allowPartial:a,includeSystem:c,startOn:s,endOn:o});throw Error(`Unrecognized strategy: '${i}'. Must be one of 'first' or 'last'.`)}async function ky(e,t){let{maxTokens:n,tokenCounter:r,textSplitter:i,partialStrategy:a,endOn:o}=t,s=[...e],c=0;for(let e=0;e<s.length;e+=1)if(await r(e>0?s.slice(0,-e):s)<=n){c=s.length-e;break}if(c<s.length&&a){let e=!1;if(Array.isArray(s[c].content)){let t=s[c];if(typeof t.content==`string`)throw Error(`Expected content to be an array.`);let i=t.content.length,o=a===`last`?[...t.content].reverse():t.content;for(let l=1;l<=i;l+=1){let i=a===`first`?o.slice(0,l):o.slice(-l),u=Object.fromEntries(Object.entries(t).filter(([e])=>e!==`type`&&!e.startsWith(`lc_`))),d=My(t.getType(),{...u,content:i}),f=[...s.slice(0,c),d];if(await r(f)<=n)s=f,c+=1,e=!0;else break}e&&a===`last`&&(t.content=[...o].reverse())}if(!e){let e=s[c],t;if(Array.isArray(e.content)&&e.content.some(e=>typeof e==`string`||e.type===`text`)?t=e.content.find(e=>e.type===`text`&&e.text)?.text:typeof e.content==`string`&&(t=e.content),t){let o=await i(t),l=o.length;a===`last`&&o.reverse();for(let t=0;t<l-1;t+=1)if(o.pop(),e.content=o.join(``),await r([...s.slice(0,c),e])<=n){a===`last`&&(e.content=[...o].reverse().join(``)),s=[...s.slice(0,c),e],c+=1;break}}}}if(o){let e=Array.isArray(o)?o:[o];for(;c>0&&!Sy(s[c-1],e);)--c}return s.slice(0,c)}async function Ay(e,t){let{allowPartial:n=!1,includeSystem:r=!1,endOn:i,startOn:a,...o}=t,s=e.map(e=>{let t=Object.fromEntries(Object.entries(e).filter(([e])=>e!==`type`&&!e.startsWith(`lc_`)));return My(e.getType(),t,mt(e))});if(i){let e=Array.isArray(i)?i:[i];for(;s.length>0&&!Sy(s[s.length-1],e);)s=s.slice(0,-1)}let c=r&&s[0]?.getType()===`system`,l=c?s.slice(0,1).concat(s.slice(1).reverse()):s.reverse();return l=await ky(l,{...o,partialStrategy:n?`last`:void 0,endOn:a}),c?[l[0],...l.slice(1).reverse()]:l.reverse()}var jy={human:{message:on,messageChunk:sn},ai:{message:qt,messageChunk:Xt},system:{message:dn,messageChunk:fn},developer:{message:dn,messageChunk:fn},tool:{message:_t,messageChunk:vt},function:{message:tn,messageChunk:nn},generic:{message:Zt,messageChunk:Qt},remove:{message:un,messageChunk:un}};function My(e,t,n){let r,i;switch(e){case`human`:n?r=new sn(t):i=new on(t);break;case`ai`:if(n){let e={...t};`tool_calls`in e&&(e={...e,tool_call_chunks:e.tool_calls?.map(e=>({...e,type:`tool_call_chunk`,index:void 0,args:JSON.stringify(e.args)}))}),r=new Xt(e)}else i=new qt(t);break;case`system`:n?r=new fn(t):i=new dn(t);break;case`developer`:n?r=new fn({...t,additional_kwargs:{...t.additional_kwargs,__openai_role__:`developer`}}):i=new dn({...t,additional_kwargs:{...t.additional_kwargs,__openai_role__:`developer`}});break;case`tool`:if(`tool_call_id`in t)n?r=new vt(t):i=new _t(t);else throw Error(`Can not convert ToolMessage to ToolMessageChunk if 'tool_call_id' field is not defined.`);break;case`function`:if(n)r=new nn(t);else{if(!t.name)throw Error(`FunctionMessage must have a 'name' field`);i=new tn(t)}break;case`generic`:if(`role`in t)n?r=new Qt(t):i=new Zt(t);else throw Error(`Can not convert ChatMessage to ChatMessageChunk if 'role' field is not defined.`);break;default:throw Error(`Unrecognized message type ${e}`)}if(n&&r)return r;if(i)return i;throw Error(`Unrecognized message type ${e}`)}function Ny(e){let t=e.getType(),n,r=Object.fromEntries(Object.entries(e).filter(([e])=>![`type`,`tool_call_chunks`].includes(e)&&!e.startsWith(`lc_`)));if(t in jy&&(n=My(t,r)),!n)throw Error(`Unrecognized message chunk class ${t}. Supported classes are ${Object.keys(jy)}`);return n}function Py(e){let t=e.split(`
64
- `);return Promise.resolve([...t.slice(0,-1).map(e=>`${e}\n`),t[t.length-1]])}var Fy=[`tool_call`,`tool_call_chunk`,`invalid_tool_call`,`server_tool_call`,`server_tool_call_chunk`,`server_tool_call_result`],Iy=[`image`,`video`,`audio`,`text-plain`,`file`],Ly=[`text`,`reasoning`,...Fy,...Iy],Ry=o({AIMessage:()=>qt,AIMessageChunk:()=>Xt,BaseMessage:()=>tt,BaseMessageChunk:()=>dt,ChatMessage:()=>Zt,ChatMessageChunk:()=>Qt,DEFAULT_MERGE_IGNORE_KEYS:()=>rt,FunctionMessage:()=>tn,FunctionMessageChunk:()=>nn,HumanMessage:()=>on,HumanMessageChunk:()=>sn,KNOWN_BLOCK_TYPES:()=>Ly,RemoveMessage:()=>un,SystemMessage:()=>dn,SystemMessageChunk:()=>fn,ToolMessage:()=>_t,ToolMessageChunk:()=>vt,_isMessageFieldWithRole:()=>ft,_mergeDicts:()=>it,_mergeLists:()=>lt,_mergeObj:()=>ut,_mergeStatus:()=>$e,coerceMessageLikeToMessage:()=>yn,collapseToolCallChunks:()=>Dn,convertToChunk:()=>En,convertToOpenAIImageBlock:()=>Se,convertToProviderContentBlock:()=>Te,defaultTextSplitter:()=>Py,defaultToolCallParser:()=>yt,filterMessages:()=>Cy,getBufferString:()=>xn,iife:()=>hn,isAIMessage:()=>Jt,isAIMessageChunk:()=>Yt,isBase64ContentBlock:()=>ye,isBaseMessage:()=>pt,isBaseMessageChunk:()=>mt,isChatMessage:()=>$t,isChatMessageChunk:()=>en,isDataContentBlock:()=>_e,isDirectToolOutput:()=>gt,isFunctionMessage:()=>rn,isFunctionMessageChunk:()=>an,isHumanMessage:()=>cn,isHumanMessageChunk:()=>ln,isIDContentBlock:()=>xe,isMessage:()=>qe,isOpenAIToolCallArray:()=>nt,isPlainTextContentBlock:()=>be,isSystemMessage:()=>pn,isSystemMessageChunk:()=>mn,isToolMessage:()=>bt,isToolMessageChunk:()=>xt,isURLContentBlock:()=>ve,mapChatMessagesToStoredMessages:()=>Tn,mapStoredMessageToChatMessage:()=>Cn,mapStoredMessagesToChatMessages:()=>wn,mergeContent:()=>Qe,mergeMessageRuns:()=>Ty,mergeResponseMetadata:()=>Ht,mergeUsageMetadata:()=>Kt,parseBase64DataUrl:()=>we,parseMimeType:()=>Ce,trimMessages:()=>Dy}),zy=class extends iy{runnable;inputMessagesKey;outputMessagesKey;historyMessagesKey;getMessageHistory;constructor(e){let t=dy.from((e,t)=>this._enterHistory(e,t??{})).withConfig({runName:`loadHistory`}),n=e.historyMessagesKey??e.inputMessagesKey;n&&(t=yy.assign({[n]:t}).withConfig({runName:`insertHistory`}));let r=t.pipe(e.runnable.withListeners({onEnd:(e,t)=>this._exitHistory(e,t??{})})).withConfig({runName:`RunnableWithMessageHistory`}),i=e.config??{};super({...e,config:i,bound:r}),this.runnable=e.runnable,this.getMessageHistory=e.getMessageHistory,this.inputMessagesKey=e.inputMessagesKey,this.outputMessagesKey=e.outputMessagesKey,this.historyMessagesKey=e.historyMessagesKey}_getInputMessages(e){let t;if(typeof e==`object`&&!Array.isArray(e)&&!pt(e)){let n;n=this.inputMessagesKey?this.inputMessagesKey:Object.keys(e).length===1?Object.keys(e)[0]:`input`,t=Array.isArray(e[n])&&Array.isArray(e[n][0])?e[n][0]:e[n]}else t=e;if(typeof t==`string`)return[new on(t)];if(Array.isArray(t))return t;if(pt(t))return[t];throw Error(`Expected a string, BaseMessage, or array of BaseMessages.\nGot ${JSON.stringify(t,null,2)}`)}_getOutputMessages(e){let t;if(!Array.isArray(e)&&!pt(e)&&typeof e!=`string`){let n;n=this.outputMessagesKey===void 0?Object.keys(e).length===1?Object.keys(e)[0]:`output`:this.outputMessagesKey,t=e.generations===void 0?e[n]:e.generations[0][0].message}else t=e;if(typeof t==`string`)return[new qt(t)];if(Array.isArray(t))return t;if(pt(t))return[t];throw Error(`Expected a string, BaseMessage, or array of BaseMessages. Received: ${JSON.stringify(t,null,2)}`)}async _enterHistory(e,t){let n=await(t?.configurable?.messageHistory).getMessages();return this.historyMessagesKey===void 0?n.concat(this._getInputMessages(e)):n}async _exitHistory(e,t){let n=t.configurable?.messageHistory,r;r=Array.isArray(e.inputs)&&Array.isArray(e.inputs[0])?e.inputs[0]:e.inputs;let i=this._getInputMessages(r);if(this.historyMessagesKey===void 0){let e=await n.getMessages();i=i.slice(e.length)}let a=e.outputs;if(!a)throw Error(`Output values from 'Run' undefined. Run: ${JSON.stringify(e,null,2)}`);let o=this._getOutputMessages(a);await n.addMessages([...i,...o])}async _mergeConfig(...e){let t=await super._mergeConfig(...e);if(!t.configurable||!t.configurable.sessionId){let e={[this.inputMessagesKey??`input`]:`foo`};throw Error(`sessionId is required. Pass it in as part of the config argument to .invoke() or .stream()\neg. chain.invoke(${JSON.stringify(e)}, ${JSON.stringify({configurable:{sessionId:`123`}})})`)}let{sessionId:n}=t.configurable;return t.configurable.messageHistory=await this.getMessageHistory(n),t}},By=o({RouterRunnable:()=>by,Runnable:()=>ry,RunnableAssign:()=>hy,RunnableBinding:()=>iy,RunnableBranch:()=>xy,RunnableEach:()=>ay,RunnableLambda:()=>dy,RunnableMap:()=>cy,RunnableParallel:()=>fy,RunnablePassthrough:()=>yy,RunnablePick:()=>gy,RunnableRetry:()=>oy,RunnableSequence:()=>sy,RunnableToolLike:()=>_y,RunnableWithFallbacks:()=>py,RunnableWithMessageHistory:()=>zy,_coerceToRunnable:()=>my,ensureConfig:()=>il,getCallbackManagerForConfig:()=>nl,mergeConfigs:()=>rl,patchConfig:()=>al,pickRunnableConfigKeys:()=>ol,raceWithSignal:()=>sl}),Vy=`__start__`,Hy=`__end__`,Uy=`__input__`,Wy=`__error__`,Gy=`__pregel_ns_writes`,Ky=`__pregel_send`,qy=`__pregel_call`,Jy=`__pregel_read`,Yy=`__pregel_checkpointer`,Xy=`__pregel_resuming`,Zy=`__pregel_task_id`,Qy=`__pregel_stream`,$y=`__pregel_resume_value`,eb=`__pregel_resume_map`,tb=`__pregel_scratchpad`,nb=`__pregel_previous`,rb=`__pregel_durability`,ib=`checkpoint_id`,ab=`checkpoint_ns`,ob=`__pregel_node_finished`,sb=`checkpoint_map`,cb=`__pregel_abort_signals`,lb=`__interrupt__`,ub=`__resume__`,db=`__no_writes__`,fb=`__return__`,pb=`__previous__`,mb=`langsmith:hidden`,hb=`__self__`,gb=`__pregel_tasks`,_b=`__pregel_push`,vb=`__pregel_pull`,yb=`00000000-0000-0000-0000-000000000000`,bb=[mb,Uy,lb,ub,Wy,db,Ky,Jy,Yy,rb,Qy,Xy,Zy,qy,$y,tb,nb,sb,ab,ib],xb=Symbol.for(`langgraph.command`),Sb=class{[xb];constructor(e){this[xb]=e}};function Cb(e){let t=e;return t!=null&&typeof t.node==`string`&&t.args!==void 0}var wb=class{lg_name=`Send`;node;args;constructor(e,t){this.node=e,this.args=Mb(t)}toJSON(){return{lg_name:this.lg_name,node:this.node,args:this.args}}};function Tb(e){return e instanceof wb}var Eb=`__overwrite__`;function Db(e){return typeof e==`object`&&e&&`__overwrite__`in e?[!0,e[Eb]]:[!1,void 0]}function Ob(e){return Db(e)[0]}function kb(e){return!e||typeof e!=`object`||!(`__interrupt__`in e)?!1:Array.isArray(e[lb])}var Ab=class extends Sb{lg_name=`Command`;lc_direct_tool_output=!0;graph;update;resume;goto=[];static PARENT=`__parent__`;constructor(e){super(e),this.resume=e.resume,this.graph=e.graph,this.update=e.update,e.goto&&(this.goto=Array.isArray(e.goto)?Mb(e.goto):[Mb(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(){let e;return e=typeof this.goto==`string`?this.goto:Tb(this.goto)?this.goto.toJSON():this.goto?.map(e=>typeof e==`string`?e:e.toJSON()),{lg_name:this.lg_name,update:this.update,resume:this.resume,goto:e}}};function jb(e){return typeof e!=`object`||!e?!1:`lg_name`in e&&e.lg_name===`Command`}function Mb(e,t=new Map){if(typeof e==`object`&&e){if(t.has(e))return t.get(e);let n;if(Array.isArray(e))n=[],t.set(e,n),e.forEach((e,r)=>{n[r]=Mb(e,t)});else if(jb(e)&&!(e instanceof Ab))n=new Ab(e),t.set(e,n);else if(Cb(e)&&!(e instanceof wb))n=new wb(e.node,e.args),t.set(e,n);else if(jb(e)||Tb(e))n=e,t.set(e,n);else if(`lc_serializable`in e&&e.lc_serializable)n=e,t.set(e,n);else{n={},t.set(e,n);for(let[r,i]of Object.entries(e))n[r]=Mb(i,t)}return n}return e}var Nb=class extends Error{lc_error_code;constructor(e,t){let n=e??``;t?.lc_error_code&&(n=`${n}\n\nTroubleshooting URL: https://docs.langchain.com/oss/javascript/langgraph/${t.lc_error_code}/\n`),super(n),this.lc_error_code=t?.lc_error_code}},Pb=class extends Nb{get is_bubble_up(){return!0}},Fb=class extends Nb{constructor(e,t){super(e,t),this.name=`GraphRecursionError`}static get unminifiable_name(){return`GraphRecursionError`}},Ib=class extends Nb{constructor(e,t){super(e,t),this.name=`GraphValueError`}static get unminifiable_name(){return`GraphValueError`}},Lb=class extends Pb{interrupts;constructor(e,t){super(JSON.stringify(e,null,2),t),this.name=`GraphInterrupt`,this.interrupts=e??[]}static get unminifiable_name(){return`GraphInterrupt`}},Rb=class extends Lb{constructor(e,t){super([{value:e}],t),this.name=`NodeInterrupt`}static get unminifiable_name(){return`NodeInterrupt`}},zb=class extends Pb{command;constructor(e){super(),this.name=`ParentCommand`,this.command=e}static get unminifiable_name(){return`ParentCommand`}};function Bb(e){return e!==void 0&&e.name===zb.unminifiable_name}function Vb(e){return e!==void 0&&e.is_bubble_up===!0}function Hb(e){return e!==void 0&&[Lb.unminifiable_name,Rb.unminifiable_name].includes(e.name)}var Ub=class extends Nb{constructor(e,t){super(e,t),this.name=`EmptyInputError`}static get unminifiable_name(){return`EmptyInputError`}},Wb=class extends Nb{constructor(e,t){super(e,t),this.name=`EmptyChannelError`}static get unminifiable_name(){return`EmptyChannelError`}},Gb=class extends Nb{constructor(e,t){super(e,t),this.name=`InvalidUpdateError`}static get unminifiable_name(){return`InvalidUpdateError`}},Kb=class extends Nb{constructor(e,t){super(e,t),this.name=`UnreachableNodeError`}static get unminifiable_name(){return`UnreachableNodeError`}},qb=class extends Nb{constructor(e,t){super(e,t),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`}},Jb=/^(?:[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 Yb(e){return typeof e==`string`&&Jb.test(e)}function Xb(e){if(!Yb(e))throw TypeError(`Invalid UUID`);var t,n=new Uint8Array(16);return n[0]=(t=parseInt(e.slice(0,8),16))>>>24,n[1]=t>>>16&255,n[2]=t>>>8&255,n[3]=t&255,n[4]=(t=parseInt(e.slice(9,13),16))>>>8,n[5]=t&255,n[6]=(t=parseInt(e.slice(14,18),16))>>>8,n[7]=t&255,n[8]=(t=parseInt(e.slice(19,23),16))>>>8,n[9]=t&255,n[10]=(t=parseInt(e.slice(24,36),16))/1099511627776&255,n[11]=t/4294967296&255,n[12]=t>>>24&255,n[13]=t>>>16&255,n[14]=t>>>8&255,n[15]=t&255,n}for(var Zb=[],Qb=0;Qb<256;++Qb)Zb.push((Qb+256).toString(16).slice(1));function $b(e,t=0){return(Zb[e[t+0]]+Zb[e[t+1]]+Zb[e[t+2]]+Zb[e[t+3]]+`-`+Zb[e[t+4]]+Zb[e[t+5]]+`-`+Zb[e[t+6]]+Zb[e[t+7]]+`-`+Zb[e[t+8]]+Zb[e[t+9]]+`-`+Zb[e[t+10]]+Zb[e[t+11]]+Zb[e[t+12]]+Zb[e[t+13]]+Zb[e[t+14]]+Zb[e[t+15]]).toLowerCase()}var ex,tx=new Uint8Array(16);function nx(){if(!ex&&(ex=typeof crypto<`u`&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!ex))throw Error(`crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported`);return ex(tx)}var rx,ix,ax=0,ox=0;function sx(e,t,n){var r=t&&n||0,i=t||Array(16);e||={};var a=e.node,o=e.clockseq;if(e._v6||(a||=rx,o??=ix),a==null||o==null){var s=e.random||(e.rng||nx)();a??(a=[s[0],s[1],s[2],s[3],s[4],s[5]],!rx&&!e._v6&&(a[0]|=1,rx=a)),o??(o=(s[6]<<8|s[7])&16383,ix===void 0&&!e._v6&&(ix=o))}var c=e.msecs===void 0?Date.now():e.msecs,l=e.nsecs===void 0?ox+1:e.nsecs,u=c-ax+(l-ox)/1e4;if(u<0&&e.clockseq===void 0&&(o=o+1&16383),(u<0||c>ax)&&e.nsecs===void 0&&(l=0),l>=1e4)throw Error(`uuid.v1(): Can't create more than 10M uuids/sec`);ax=c,ox=l,ix=o,c+=0xb1d069b5400;var d=((c&268435455)*1e4+l)%4294967296;i[r++]=d>>>24&255,i[r++]=d>>>16&255,i[r++]=d>>>8&255,i[r++]=d&255;var f=c/4294967296*1e4&268435455;i[r++]=f>>>8&255,i[r++]=f&255,i[r++]=f>>>24&15|16,i[r++]=f>>>16&255,i[r++]=o>>>8|128,i[r++]=o&255;for(var p=0;p<6;++p)i[r+p]=a[p];return t||$b(i)}function cx(e){var t=lx(typeof e==`string`?Xb(e):e);return typeof e==`string`?$b(t):t}function lx(e,t=!1){return Uint8Array.of((e[6]&15)<<4|e[7]>>4&15,(e[7]&15)<<4|(e[4]&240)>>4,(e[4]&15)<<4|(e[5]&240)>>4,(e[5]&15)<<4|(e[0]&240)>>4,(e[0]&15)<<4|(e[1]&240)>>4,(e[1]&15)<<4|(e[2]&240)>>4,96|e[2]&15,e[3],e[8],e[9],e[10],e[11],e[12],e[13],e[14],e[15])}function ux(e){e=unescape(encodeURIComponent(e));for(var t=[],n=0;n<e.length;++n)t.push(e.charCodeAt(n));return t}var dx=`6ba7b810-9dad-11d1-80b4-00c04fd430c8`,fx=`6ba7b811-9dad-11d1-80b4-00c04fd430c8`;function px(e,t,n){function r(e,r,i,a){if(typeof e==`string`&&(e=ux(e)),typeof r==`string`&&(r=Xb(r)),r?.length!==16)throw TypeError(`Namespace must be array-like (16 iterable integer values, 0-255)`);var o=new Uint8Array(16+e.length);if(o.set(r),o.set(e,r.length),o=n(o),o[6]=o[6]&15|t,o[8]=o[8]&63|128,i){a||=0;for(var s=0;s<16;++s)i[a+s]=o[s];return i}return $b(o)}try{r.name=e}catch{}return r.DNS=dx,r.URL=fx,r}function mx(e,t,n,r){switch(e){case 0:return t&n^~t&r;case 1:return t^n^r;case 2:return t&n^t&r^n&r;case 3:return t^n^r}}function hx(e,t){return e<<t|e>>>32-t}function gx(e){var t=[1518500249,1859775393,2400959708,3395469782],n=[1732584193,4023233417,2562383102,271733878,3285377520];if(typeof e==`string`){var r=unescape(encodeURIComponent(e));e=[];for(var i=0;i<r.length;++i)e.push(r.charCodeAt(i))}else Array.isArray(e)||(e=Array.prototype.slice.call(e));e.push(128);for(var a=e.length/4+2,o=Math.ceil(a/16),s=Array(o),c=0;c<o;++c){for(var l=new Uint32Array(16),u=0;u<16;++u)l[u]=e[c*64+u*4]<<24|e[c*64+u*4+1]<<16|e[c*64+u*4+2]<<8|e[c*64+u*4+3];s[c]=l}s[o-1][14]=(e.length-1)*8/2**32,s[o-1][14]=Math.floor(s[o-1][14]),s[o-1][15]=(e.length-1)*8&4294967295;for(var d=0;d<o;++d){for(var f=new Uint32Array(80),p=0;p<16;++p)f[p]=s[d][p];for(var m=16;m<80;++m)f[m]=hx(f[m-3]^f[m-8]^f[m-14]^f[m-16],1);for(var h=n[0],g=n[1],_=n[2],v=n[3],y=n[4],b=0;b<80;++b){var ee=Math.floor(b/20),x=hx(h,5)+mx(ee,g,_,v)+y+t[ee]+f[b]>>>0;y=v,v=_,_=hx(g,30)>>>0,g=h,h=x}n[0]=n[0]+h>>>0,n[1]=n[1]+g>>>0,n[2]=n[2]+_>>>0,n[3]=n[3]+v>>>0,n[4]=n[4]+y>>>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 _x=px(`v5`,80,gx);function vx(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function yx(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?vx(Object(n),!0).forEach(function(t){bx(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):vx(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function bx(e,t,n){return(t=xx(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function xx(e){var t=Sx(e,`string`);return typeof t==`symbol`?t:t+``}function Sx(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function Cx(e={},t,n=0){var r=sx(yx(yx({},e),{},{_v6:!0}),new Uint8Array(16));if(r=cx(r),t){for(var i=0;i<16;i++)t[n+i]=r[i];return t}return $b(r)}function wx(e){return Cx({clockseq:e})}function Tx(e,t){let n=t.replace(/-/g,``).match(/.{2}/g).map(e=>parseInt(e,16));return _x(e,new Uint8Array(n))}var Ex=`__error__`,Dx=`__scheduled__`,Ox=`__interrupt__`,kx=`__resume__`,Ax=`[...]`,jx=`[Circular]`,Mx=[],Nx=[];function Px(){return{depthLimit:2**53-1,edgesLimit:2**53-1}}function Fx(e,t,n,r){r===void 0&&(r=Px()),Lx(e,``,0,[],void 0,0,r);var i;try{i=Nx.length===0?JSON.stringify(e,t,n):JSON.stringify(e,Rx(t),n)}catch{return JSON.stringify(`[unable to serialize, circular reference is too complex to analyze]`)}finally{for(;Mx.length!==0;){var a=Mx.pop();a.length===4?Object.defineProperty(a[0],a[1],a[3]):a[0][a[1]]=a[2]}}return i}function Ix(e,t,n,r){var i=Object.getOwnPropertyDescriptor(r,n);i.get===void 0?(r[n]=e,Mx.push([r,n,t])):i.configurable?(Object.defineProperty(r,n,{value:e}),Mx.push([r,n,t,i])):Nx.push([t,n,e])}function Lx(e,t,n,r,i,a,o){a+=1;var s;if(typeof e==`object`&&e){for(s=0;s<r.length;s++)if(r[s]===e){Ix(jx,e,t,i);return}if(o.depthLimit!==void 0&&a>o.depthLimit){Ix(Ax,e,t,i);return}if(o.edgesLimit!==void 0&&n+1>o.edgesLimit){Ix(Ax,e,t,i);return}if(r.push(e),Array.isArray(e))for(s=0;s<e.length;s++)Lx(e[s],s,s,r,e,a,o);else{var c=Object.keys(e);for(s=0;s<c.length;s++){var l=c[s];Lx(e[l],l,s,r,e,a,o)}}r.pop()}}function Rx(e){return e=e===void 0?function(e,t){return t}:e,function(t,n){if(Nx.length>0)for(var r=0;r<Nx.length;r++){var i=Nx[r];if(i[1]===t&&i[0]===n){n=i[2],Nx.splice(r,1);break}}return e.call(this,t,n)}}var zx=[],Bx=o({}),Vx=o({}),B=`0123456789abcdef`.split(``),Hx=[-2147483648,8388608,32768,128],Ux=[24,16,8,0],Wx=[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],Gx=[];function Kx(e,t){t?(Gx[0]=Gx[16]=Gx[1]=Gx[2]=Gx[3]=Gx[4]=Gx[5]=Gx[6]=Gx[7]=Gx[8]=Gx[9]=Gx[10]=Gx[11]=Gx[12]=Gx[13]=Gx[14]=Gx[15]=0,this.blocks=Gx):this.blocks=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],e?(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=e}Kx.prototype.update=function(e){if(!this.finalized){var t,n=typeof e;if(n!==`string`){if(n===`object`){if(e===null)throw Error(ERROR);if(ARRAY_BUFFER&&e.constructor===ArrayBuffer)e=new Uint8Array(e);else if(!Array.isArray(e)&&(!ARRAY_BUFFER||!ArrayBuffer.isView(e)))throw Error(ERROR)}else throw Error(ERROR);t=!0}for(var r,i=0,a,o=e.length,s=this.blocks;i<o;){if(this.hashed&&(this.hashed=!1,s[0]=this.block,this.block=s[16]=s[1]=s[2]=s[3]=s[4]=s[5]=s[6]=s[7]=s[8]=s[9]=s[10]=s[11]=s[12]=s[13]=s[14]=s[15]=0),t)for(a=this.start;i<o&&a<64;++i)s[a>>>2]|=e[i]<<Ux[a++&3];else for(a=this.start;i<o&&a<64;++i)r=e.charCodeAt(i),r<128?s[a>>>2]|=r<<Ux[a++&3]:r<2048?(s[a>>>2]|=(192|r>>>6)<<Ux[a++&3],s[a>>>2]|=(128|r&63)<<Ux[a++&3]):r<55296||r>=57344?(s[a>>>2]|=(224|r>>>12)<<Ux[a++&3],s[a>>>2]|=(128|r>>>6&63)<<Ux[a++&3],s[a>>>2]|=(128|r&63)<<Ux[a++&3]):(r=65536+((r&1023)<<10|e.charCodeAt(++i)&1023),s[a>>>2]|=(240|r>>>18)<<Ux[a++&3],s[a>>>2]|=(128|r>>>12&63)<<Ux[a++&3],s[a>>>2]|=(128|r>>>6&63)<<Ux[a++&3],s[a>>>2]|=(128|r&63)<<Ux[a++&3]);this.lastByteIndex=a,this.bytes+=a-this.start,a>=64?(this.block=s[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%=4294967296),this}},Kx.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var e=this.blocks,t=this.lastByteIndex;e[16]=this.block,e[t>>>2]|=Hx[t&3],this.block=e[16],t>=56&&(this.hashed||this.hash(),e[0]=this.block,e[16]=e[1]=e[2]=e[3]=e[4]=e[5]=e[6]=e[7]=e[8]=e[9]=e[10]=e[11]=e[12]=e[13]=e[14]=e[15]=0),e[14]=this.hBytes<<3|this.bytes>>>29,e[15]=this.bytes<<3,this.hash()}},Kx.prototype.hash=function(){var e=this.h0,t=this.h1,n=this.h2,r=this.h3,i=this.h4,a=this.h5,o=this.h6,s=this.h7,c=this.blocks,l,u,d,f,p,m,h,g,_,v,y;for(l=16;l<64;++l)p=c[l-15],u=(p>>>7|p<<25)^(p>>>18|p<<14)^p>>>3,p=c[l-2],d=(p>>>17|p<<15)^(p>>>19|p<<13)^p>>>10,c[l]=c[l-16]+u+c[l-7]+d<<0;for(y=t&n,l=0;l<64;l+=4)this.first?(this.is224?(g=300032,p=c[0]-1413257819,s=p-150054599<<0,r=p+24177077<<0):(g=704751109,p=c[0]-210244248,s=p-1521486534<<0,r=p+143694565<<0),this.first=!1):(u=(e>>>2|e<<30)^(e>>>13|e<<19)^(e>>>22|e<<10),d=(i>>>6|i<<26)^(i>>>11|i<<21)^(i>>>25|i<<7),g=e&t,f=g^e&n^y,h=i&a^~i&o,p=s+d+h+Wx[l]+c[l],m=u+f,s=r+p<<0,r=p+m<<0),u=(r>>>2|r<<30)^(r>>>13|r<<19)^(r>>>22|r<<10),d=(s>>>6|s<<26)^(s>>>11|s<<21)^(s>>>25|s<<7),_=r&e,f=_^r&t^g,h=o&s^~o&i,p=a+d+h+Wx[l+1]+c[l+1],m=u+f,o=n+p<<0,n=p+m<<0,u=(n>>>2|n<<30)^(n>>>13|n<<19)^(n>>>22|n<<10),d=(o>>>6|o<<26)^(o>>>11|o<<21)^(o>>>25|o<<7),v=n&r,f=v^n&e^_,h=a&o^~a&s,p=i+d+h+Wx[l+2]+c[l+2],m=u+f,a=t+p<<0,t=p+m<<0,u=(t>>>2|t<<30)^(t>>>13|t<<19)^(t>>>22|t<<10),d=(a>>>6|a<<26)^(a>>>11|a<<21)^(a>>>25|a<<7),y=t&n,f=y^t&r^v,h=a&o^~a&s,p=i+d+h+Wx[l+3]+c[l+3],m=u+f,i=e+p<<0,e=p+m<<0,this.chromeBugWorkAround=!0;this.h0=this.h0+e<<0,this.h1=this.h1+t<<0,this.h2=this.h2+n<<0,this.h3=this.h3+r<<0,this.h4=this.h4+i<<0,this.h5=this.h5+a<<0,this.h6=this.h6+o<<0,this.h7=this.h7+s<<0},Kx.prototype.hex=function(){this.finalize();var e=this.h0,t=this.h1,n=this.h2,r=this.h3,i=this.h4,a=this.h5,o=this.h6,s=this.h7,c=B[e>>>28&15]+B[e>>>24&15]+B[e>>>20&15]+B[e>>>16&15]+B[e>>>12&15]+B[e>>>8&15]+B[e>>>4&15]+B[e&15]+B[t>>>28&15]+B[t>>>24&15]+B[t>>>20&15]+B[t>>>16&15]+B[t>>>12&15]+B[t>>>8&15]+B[t>>>4&15]+B[t&15]+B[n>>>28&15]+B[n>>>24&15]+B[n>>>20&15]+B[n>>>16&15]+B[n>>>12&15]+B[n>>>8&15]+B[n>>>4&15]+B[n&15]+B[r>>>28&15]+B[r>>>24&15]+B[r>>>20&15]+B[r>>>16&15]+B[r>>>12&15]+B[r>>>8&15]+B[r>>>4&15]+B[r&15]+B[i>>>28&15]+B[i>>>24&15]+B[i>>>20&15]+B[i>>>16&15]+B[i>>>12&15]+B[i>>>8&15]+B[i>>>4&15]+B[i&15]+B[a>>>28&15]+B[a>>>24&15]+B[a>>>20&15]+B[a>>>16&15]+B[a>>>12&15]+B[a>>>8&15]+B[a>>>4&15]+B[a&15]+B[o>>>28&15]+B[o>>>24&15]+B[o>>>20&15]+B[o>>>16&15]+B[o>>>12&15]+B[o>>>8&15]+B[o>>>4&15]+B[o&15];return this.is224||(c+=B[s>>>28&15]+B[s>>>24&15]+B[s>>>20&15]+B[s>>>16&15]+B[s>>>12&15]+B[s>>>8&15]+B[s>>>4&15]+B[s&15]),c},Kx.prototype.toString=Kx.prototype.hex,Kx.prototype.digest=function(){this.finalize();var e=this.h0,t=this.h1,n=this.h2,r=this.h3,i=this.h4,a=this.h5,o=this.h6,s=this.h7,c=[e>>>24&255,e>>>16&255,e>>>8&255,e&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255,n>>>24&255,n>>>16&255,n>>>8&255,n&255,r>>>24&255,r>>>16&255,r>>>8&255,r&255,i>>>24&255,i>>>16&255,i>>>8&255,i&255,a>>>24&255,a>>>16&255,a>>>8&255,a&255,o>>>24&255,o>>>16&255,o>>>8&255,o&255];return this.is224||c.push(s>>>24&255,s>>>16&255,s>>>8&255,s&255),c},Kx.prototype.array=Kx.prototype.digest,Kx.prototype.arrayBuffer=function(){this.finalize();var e=new ArrayBuffer(this.is224?28:32),t=new DataView(e);return t.setUint32(0,this.h0),t.setUint32(4,this.h1),t.setUint32(8,this.h2),t.setUint32(12,this.h3),t.setUint32(16,this.h4),t.setUint32(20,this.h5),t.setUint32(24,this.h6),this.is224||t.setUint32(28,this.h7),e};var qx=(...e)=>new Kx(!1,!0).update(e.join(``)).hex(),Jx=o({sha256:()=>qx}),Yx=o({BaseCache:()=>$x,InMemoryCache:()=>tS,defaultHashKeyEncoder:()=>Xx,deserializeStoredGeneration:()=>Zx,serializeGeneration:()=>Qx}),Xx=(...e)=>qx(e.join(`_`));function Zx(e){return e.message===void 0?{text:e.text}:{text:e.text,message:Cn(e.message)}}function Qx(e){let t={text:e.text};return e.message!==void 0&&(t.message=e.message.toDict()),t}var $x=class{keyEncoder=Xx;makeDefaultKeyEncoder(e){this.keyEncoder=e}},eS=new Map,tS=class e extends $x{cache;constructor(e){super(),this.cache=e??new Map}lookup(e,t){return Promise.resolve(this.cache.get(this.keyEncoder(e,t))??null)}async update(e,t,n){this.cache.set(this.keyEncoder(e,t),n)}static global(){return new e(eS)}},nS=o({BaseChatMessageHistory:()=>rS,BaseListChatMessageHistory:()=>iS,InMemoryChatMessageHistory:()=>aS}),rS=class extends ge{async addMessages(e){for(let t of e)await this.addMessage(t)}},iS=class extends ge{addUserMessage(e){return this.addMessage(new on(e))}addAIMessage(e){return this.addMessage(new qt(e))}async addMessages(e){for(let t of e)await this.addMessage(t)}clear(){throw Error(`Not implemented.`)}},aS=class extends iS{lc_namespace=[`langchain`,`stores`,`message`,`in_memory`];messages=[];constructor(e){super(...arguments),this.messages=e??[]}async getMessages(){return this.messages}async addMessage(e){this.messages.push(e)}async clear(){this.messages=[]}},oS=class{pageContent;metadata;id;constructor(e){this.pageContent=e.pageContent===void 0?``:e.pageContent.toString(),this.metadata=e.metadata??{},this.id=e.id}},sS=class extends ry{lc_namespace=[`langchain_core`,`documents`,`transformers`];invoke(e,t){return this.transformDocuments(e)}},cS=class extends sS{async transformDocuments(e){let t=[];for(let n of e){let e=await this._transformDocument(n);t.push(e)}return t}},lS=o({BaseDocumentTransformer:()=>sS,Document:()=>oS,MappingDocumentTransformer:()=>cS}),uS=o({BaseDocumentLoader:()=>dS}),dS=class{},fS=o({LangSmithLoader:()=>pS}),pS=class extends dS{datasetId;datasetName;exampleIds;asOf;splits;inlineS3Urls;offset;limit;metadata;filter;contentKey;formatContent;client;constructor(e){if(super(),e.client&&e.clientConfig)throw Error(`client and clientConfig cannot both be provided.`);this.client=e.client??new Es(e?.clientConfig),this.contentKey=e.contentKey?e.contentKey.split(`.`):[],this.formatContent=e.formatContent??mS,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(){let e=[];for await(let t 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 n=t.inputs;for(let e of this.contentKey)n=n[e];let r=this.formatContent(n),i=t;[`created_at`,`modified_at`].forEach(e=>{e in i&&typeof i[e]==`object`&&(i[e]=i[e].toString())}),e.push({pageContent:r,metadata:i})}return e}};function mS(e){if(typeof e==`string`)return e;try{return JSON.stringify(e,null,2)}catch{return String(e)}}var hS=o({Embeddings:()=>gS}),gS=class{caller;constructor(e){this.caller=new mu(e??{})}},_S=class extends ge{lc_namespace=[`langchain_core`,`example_selectors`,`base`]},vS=class{async getPromptAsync(e,t){return this.getPrompt(e).partial(t?.partialVariables??{})}},yS=class extends vS{defaultPrompt;conditionals;constructor(e,t=[]){super(),this.defaultPrompt=e,this.conditionals=t}getPrompt(e){for(let[t,n]of this.conditionals)if(t(e))return n;return this.defaultPrompt}};function bS(e){return e._modelType()===`base_llm`}function xS(e){return e._modelType()===`base_chat_model`}function SS(e){return e.split(/\n| /).length}var CS=class e extends _S{examples=[];examplePrompt;getTextLength=SS;maxLength=2048;exampleTextLengths=[];constructor(e){super(e),this.examplePrompt=e.examplePrompt,this.maxLength=e.maxLength??2048,this.getTextLength=e.getTextLength??SS}async addExample(e){this.examples.push(e);let t=await this.examplePrompt.format(e);this.exampleTextLengths.push(this.getTextLength(t))}async calculateExampleTextLengths(e,t){if(e.length>0)return e;let{examples:n,examplePrompt:r}=t;return(await Promise.all(n.map(e=>r.format(e)))).map(e=>this.getTextLength(e))}async selectExamples(e){let t=Object.values(e).join(` `),n=this.maxLength-this.getTextLength(t),r=0,i=[];for(;n>0&&r<this.examples.length;){let e=n-this.exampleTextLengths[r];if(e<0)break;i.push(this.examples[r]),n=e,r+=1}return i}static async fromExamples(t,n){let r=new e(n);return await Promise.all(t.map(e=>r.addExample(e))),r}};function wS(e){return Object.keys(e).sort().map(t=>e[t])}var TS=class e extends _S{vectorStoreRetriever;exampleKeys;inputKeys;constructor(e){if(super(e),this.exampleKeys=e.exampleKeys,this.inputKeys=e.inputKeys,e.vectorStore!==void 0)this.vectorStoreRetriever=e.vectorStore.asRetriever({k:e.k??4,filter:e.filter});else if(e.vectorStoreRetriever)this.vectorStoreRetriever=e.vectorStoreRetriever;else throw Error(`You must specify one of "vectorStore" and "vectorStoreRetriever".`)}async addExample(e){let t=wS((this.inputKeys??Object.keys(e)).reduce((t,n)=>({...t,[n]:e[n]}),{})).join(` `);await this.vectorStoreRetriever.addDocuments([new oS({pageContent:t,metadata:e})])}async selectExamples(e){let t=wS((this.inputKeys??Object.keys(e)).reduce((t,n)=>({...t,[n]:e[n]}),{})).join(` `),n=(await this.vectorStoreRetriever.invoke(t)).map(e=>e.metadata);return this.exampleKeys?n.map(e=>this.exampleKeys.reduce((t,n)=>({...t,[n]:e[n]}),{})):n}static async fromExamples(t,n,r,i={}){let a=i.inputKeys??null,o=t.map(e=>wS(a?a.reduce((t,n)=>({...t,[n]:e[n]}),{}):e).join(` `));return new e({vectorStore:await r.fromTexts(o,t,n,i),k:i.k??4,exampleKeys:i.exampleKeys,inputKeys:i.inputKeys})}},ES=o({BaseExampleSelector:()=>_S,BasePromptSelector:()=>vS,ConditionalPromptSelector:()=>yS,LengthBasedExampleSelector:()=>CS,SemanticSimilarityExampleSelector:()=>TS,isChatModel:()=>xS,isLLM:()=>bS}),DS=`10f90ea3-90a4-4962-bf75-83a0f3c1c62a`,OS=class extends ge{lc_namespace=[`langchain`,`recordmanagers`]},kS=class{uid;hash_;contentHash;metadataHash;pageContent;metadata;keyEncoder=qx;constructor(e){this.uid=e.uid,this.pageContent=e.pageContent,this.metadata=e.metadata}makeDefaultKeyEncoder(e){this.keyEncoder=e}calculateHashes(){let e=[`hash_`,`content_hash`,`metadata_hash`];for(let t of e)if(t in this.metadata)throw Error(`Metadata cannot contain key ${t} as it is reserved for internal use. Restricted keys: [${e.join(`, `)}]`);let t=this._hashStringToUUID(this.pageContent);try{let e=this._hashNestedDictToUUID(this.metadata);this.contentHash=t,this.metadataHash=e}catch(e){throw Error(`Failed to hash metadata: ${e}. Please use a dict that can be serialized using json.`)}this.hash_=this._hashStringToUUID(this.contentHash+this.metadataHash),this.uid||=this.hash_}toDocument(){return new oS({pageContent:this.pageContent,metadata:this.metadata})}static fromDocument(e,t){let n=new this({pageContent:e.pageContent,metadata:e.metadata,uid:t||e.uid});return n.calculateHashes(),n}_hashStringToUUID(e){return tr(this.keyEncoder(e),DS)}_hashNestedDictToUUID(e){let t=JSON.stringify(e,Object.keys(e).sort());return tr(this.keyEncoder(t),DS)}};function AS(e,t){let n=[],r=[];return t.forEach(t=>{r.push(t),r.length>=e&&(n.push(r),r=[])}),r.length>0&&n.push(r),n}function jS(e){let t=new Set,n=[];for(let r of e){if(!r.hash_)throw Error(`Hashed document does not have a hash`);t.has(r.hash_)||(t.add(r.hash_),n.push(r))}return n}function MS(e){if(e===null)return e=>null;if(typeof e==`string`)return t=>t.metadata[e];if(typeof e==`function`)return e;throw Error(`sourceIdKey should be null, a string or a function, got ${typeof e}`)}var NS=e=>`load`in e&&typeof e.load==`function`&&`loadAndSplit`in e&&typeof e.loadAndSplit==`function`;async function PS(e){let{docsSource:t,recordManager:n,vectorStore:r,options:i}=e,{batchSize:a=100,cleanup:o,sourceIdKey:s,cleanupBatchSize:c=1e3,forceUpdate:l=!1}=i??{};if(o===`incremental`&&!s)throw Error(`sourceIdKey is required when cleanup mode is incremental. Please provide through 'options.sourceIdKey'.`);let u=NS(t)?await t.load():t,d=MS(s??null),f=await n.getTime(),p=0,m=0,h=0,g=0,_=AS(a??100,u);for(let e of _){let t=jS(e.map(e=>kS.fromDocument(e))),i=t.map(e=>d(e));o===`incremental`&&t.forEach((e,t)=>{if(i[t]===null)throw Error(`sourceIdKey must be provided when cleanup is incremental`)});let a=await n.exists(t.map(e=>e.uid)),s=[],c=[],u=[],_=new Set;if(t.forEach((e,t)=>{if(a[t])if(l)_.add(e.uid);else{u.push(e.uid);return}s.push(e.uid),c.push(e.toDocument())}),u.length>0&&(await n.update(u,{timeAtLeast:f}),g+=u.length),c.length>0&&(await r.addDocuments(c,{ids:s}),p+=c.length-_.size,h+=_.size),await n.update(t.map(e=>e.uid),{timeAtLeast:f,groupIds:i}),o===`incremental`){i.forEach(e=>{if(!e)throw Error(`Source id cannot be null`)});let e=await n.listKeys({before:f,groupIds:i});e.length>0&&(await r.delete({ids:e}),await n.deleteKeys(e),m+=e.length)}}if(o===`full`){let e=await n.listKeys({before:f,limit:c});for(;e.length>0;)await r.delete({ids:e}),await n.deleteKeys(e),m+=e.length,e=await n.listKeys({before:f,limit:c})}return{numAdded:p,numDeleted:m,numUpdated:h,numSkipped:g}}var FS=o({RecordManager:()=>OS,UUIDV5_NAMESPACE:()=>DS,_HashedDocument:()=>kS,_batch:()=>AS,_deduplicateInOrder:()=>jS,_getSourceIdAssigner:()=>MS,_isBaseDocumentLoader:()=>NS,index:()=>PS}),IS=o({BasePromptValue:()=>LS,ChatPromptValue:()=>zS,ImagePromptValue:()=>BS,StringPromptValue:()=>RS}),LS=class extends ge{},RS=class extends LS{static lc_name(){return`StringPromptValue`}lc_namespace=[`langchain_core`,`prompt_values`];lc_serializable=!0;value;constructor(e){super({value:e}),this.value=e}toString(){return this.value}toChatMessages(){return[new on(this.value)]}},zS=class extends LS{lc_namespace=[`langchain_core`,`prompt_values`];lc_serializable=!0;static lc_name(){return`ChatPromptValue`}messages;constructor(e){Array.isArray(e)&&(e={messages:e}),super(e),this.messages=e.messages}toString(){return xn(this.messages)}toChatMessages(){return this.messages}},BS=class extends LS{lc_namespace=[`langchain_core`,`prompt_values`];lc_serializable=!0;static lc_name(){return`ImagePromptValue`}imageUrl;value;constructor(e){`imageUrl`in e||(e={imageUrl:e}),super(e),this.imageUrl=e.imageUrl}toString(){return this.imageUrl.url}toChatMessages(){return[new on({content:[{type:`image_url`,image_url:{detail:this.imageUrl.detail,url:this.imageUrl.url}}]})]}},VS=e(t((e=>{e.toByteArray=l;for(var t=[],n=[],r=typeof Uint8Array<`u`?Uint8Array:Array,i=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,a=0,o=i.length;a<o;++a)t[a]=i[a],n[i.charCodeAt(a)]=a;n[45]=62,n[95]=63;function s(e){var t=e.length;if(t%4>0)throw Error(`Invalid string. Length must be a multiple of 4`);var n=e.indexOf(`=`);n===-1&&(n=t);var r=n===t?0:4-n%4;return[n,r]}function c(e,t,n){return(t+n)*3/4-n}function l(e){var t,i=s(e),a=i[0],o=i[1],l=new r(c(e,a,o)),u=0,d=o>0?a-4:a,f;for(f=0;f<d;f+=4)t=n[e.charCodeAt(f)]<<18|n[e.charCodeAt(f+1)]<<12|n[e.charCodeAt(f+2)]<<6|n[e.charCodeAt(f+3)],l[u++]=t>>16&255,l[u++]=t>>8&255,l[u++]=t&255;return o===2&&(t=n[e.charCodeAt(f)]<<2|n[e.charCodeAt(f+1)]>>4,l[u++]=t&255),o===1&&(t=n[e.charCodeAt(f)]<<10|n[e.charCodeAt(f+1)]<<4|n[e.charCodeAt(f+2)]>>2,l[u++]=t>>8&255,l[u++]=t&255),l}}))(),1),HS=Object.defineProperty,US=(e,t,n)=>t in e?HS(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,WS=(e,t,n)=>(US(e,typeof t==`symbol`?t:t+``,n),n);function GS(e,t){let n=Array.from({length:e.length},(e,t)=>({start:t,end:t+1}));for(;n.length>1;){let r=null;for(let i=0;i<n.length-1;i++){let a=e.slice(n[i].start,n[i+1].end),o=t.get(a.join(`,`));o!=null&&(r==null||o<r[0])&&(r=[o,i])}if(r!=null){let e=r[1];n[e]={start:n[e].start,end:n[e+1].end},n.splice(e+1,1)}else break}return n}function KS(e,t){return e.length===1?[t.get(e.join(`,`))]:GS(e,t).map(n=>t.get(e.slice(n.start,n.end).join(`,`))).filter(e=>e!=null)}function qS(e){return e.replace(/[\\^$*+?.()|[\]{}]/g,`\\$&`)}var JS=class{specialTokens;inverseSpecialTokens;patStr;textEncoder=new TextEncoder;textDecoder=new TextDecoder(`utf-8`);rankMap=new Map;textMap=new Map;constructor(e,t){this.patStr=e.pat_str;let n=e.bpe_ranks.split(`
65
- `).filter(Boolean).reduce((e,t)=>{let[n,r,...i]=t.split(` `),a=Number.parseInt(r,10);return i.forEach((t,n)=>e[t]=a+n),e},{});for(let[e,t]of Object.entries(n)){let n=VS.toByteArray(e);this.rankMap.set(n.join(`,`),t),this.textMap.set(t,n)}this.specialTokens={...e.special_tokens,...t},this.inverseSpecialTokens=Object.entries(this.specialTokens).reduce((e,[t,n])=>(e[n]=this.textEncoder.encode(t),e),{})}encode(e,t=[],n=`all`){let r=new RegExp(this.patStr,`ug`),i=JS.specialTokenRegex(Object.keys(this.specialTokens)),a=[],o=new Set(t===`all`?Object.keys(this.specialTokens):t),s=new Set(n===`all`?Object.keys(this.specialTokens).filter(e=>!o.has(e)):n);if(s.size>0){let t=JS.specialTokenRegex([...s]),n=e.match(t);if(n!=null)throw Error(`The text contains a special token that is not allowed: ${n[0]}`)}let c=0;for(;;){let t=null,n=c;for(;i.lastIndex=n,t=i.exec(e),!(t==null||o.has(t[0]));)n=t.index+1;let s=t?.index??e.length;for(let t of e.substring(c,s).matchAll(r)){let e=this.textEncoder.encode(t[0]),n=this.rankMap.get(e.join(`,`));if(n!=null){a.push(n);continue}a.push(...KS(e,this.rankMap))}if(t==null)break;let l=this.specialTokens[t[0]];a.push(l),c=t.index+t[0].length}return a}decode(e){let t=[],n=0;for(let r=0;r<e.length;++r){let i=e[r],a=this.textMap.get(i)??this.inverseSpecialTokens[i];a!=null&&(t.push(a),n+=a.length)}let r=new Uint8Array(n),i=0;for(let e of t)r.set(e,i),i+=e.length;return this.textDecoder.decode(r)}},YS=JS;WS(YS,`specialTokenRegex`,e=>new RegExp(e.map(e=>qS(e)).join(`|`),`g`));function XS(e){switch(e){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 Error(`Unknown model`)}}var ZS=o({encodingForModel:()=>tC,getEncoding:()=>eC}),QS={},$S=new mu({});async function eC(e){return e in QS||(QS[e]=$S.fetch(`https://tiktoken.pages.dev/js/${e}.json`).then(e=>e.json()).then(e=>new YS(e)).catch(t=>{throw delete QS[e],t})),await QS[e]}async function tC(e){return eC(XS(e))}var nC=o({BaseLangChain:()=>lC,BaseLanguageModel:()=>uC,calculateMaxTokens:()=>sC,getEmbeddingContextSize:()=>iC,getModelContextSize:()=>aC,getModelNameForTiktoken:()=>rC,isOpenAITool:()=>oC}),rC=e=>e.startsWith(`gpt-5`)?`gpt-5`:e.startsWith(`gpt-3.5-turbo-16k`)?`gpt-3.5-turbo-16k`:e.startsWith(`gpt-3.5-turbo-`)?`gpt-3.5-turbo`:e.startsWith(`gpt-4-32k`)?`gpt-4-32k`:e.startsWith(`gpt-4-`)?`gpt-4`:e.startsWith(`gpt-4o`)?`gpt-4o`:e,iC=e=>{switch(e){case`text-embedding-ada-002`:return 8191;default:return 2046}},aC=e=>{switch(rC(e)){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 oC(e){return typeof e!=`object`||!e?!1:!!(`type`in e&&e.type===`function`&&`function`in e&&typeof e.function==`object`&&e.function&&`name`in e.function&&`parameters`in e.function)}var sC=async({prompt:e,modelName:t})=>{let n;try{n=(await tC(rC(t))).encode(e).length}catch{console.warn(`Failed to calculate number of tokens, falling back to approximate count`),n=Math.ceil(e.length/4)}return aC(t)-n},cC=()=>!1,lC=class extends ry{verbose;callbacks;tags;metadata;get lc_attributes(){return{callbacks:void 0,verbose:void 0}}constructor(e){super(e),this.verbose=e.verbose??cC(),this.callbacks=e.callbacks,this.tags=e.tags??[],this.metadata=e.metadata??{},this._addVersion(`@langchain/core`,`1.1.45`)}_addVersion(e,t){let n=this.metadata?.versions;this.metadata={...this.metadata,versions:{...typeof n==`object`&&n?n:{},[e]:t}}}},uC=class extends lC{get callKeys(){return[`stop`,`timeout`,`signal`,`tags`,`metadata`,`callbacks`]}caller;cache;constructor({callbacks:e,callbackManager:t,...n}){let{cache:r,...i}=n;super({callbacks:e??t,...i}),typeof r==`object`?this.cache=r:r?this.cache=tS.global():this.cache=void 0,this.caller=new mu(n??{})}_encoding;async getNumTokens(e){let t;t=typeof e==`string`?e:e.map(e=>typeof e==`string`?e:e.type===`text`&&`text`in e?e.text:``).join(``);let n=Math.ceil(t.length/4);if(!this._encoding)try{this._encoding=await tC(`modelName`in this?rC(this.modelName):`gpt2`)}catch(e){console.warn(`Failed to calculate number of tokens, falling back to approximate count`,e)}if(this._encoding)try{n=this._encoding.encode(t).length}catch(e){console.warn(`Failed to calculate number of tokens, falling back to approximate count`,e)}return n}static _convertInputToPromptValue(e){return typeof e==`string`?new RS(e):Array.isArray(e)?new zS(e.map(yn)):e}_identifyingParams(){return{}}_getSerializedCacheKeyParametersForCall({config:e,...t}){let n={...this._identifyingParams(),...t,_type:this._llmType(),_model:this._modelType()};return Object.entries(n).filter(([e,t])=>t!==void 0).map(([e,t])=>`${e}:${JSON.stringify(t)}`).sort().join(`,`)}serialize(){return{...this._identifyingParams(),_type:this._llmType(),_model:this._modelType()}}static async deserialize(e){throw Error(`Use .toJSON() instead`)}get profile(){return{}}_filterInvocationParamsForTracing(e){let{tools:t,functions:n,messages:r,response_format:i,...a}=e;return a}},dC=o({applyPatch:()=>Ml,compare:()=>Rl}),fC=class extends ry{parseResultWithPrompt(e,t,n){return this.parseResult(e,n)}_baseMessageToString(e){return typeof e.content==`string`?e.content:this._baseMessageContentToString(e.content)}_baseMessageContentToString(e){return JSON.stringify(e)}async invoke(e,t){return typeof e==`string`?this._callWithConfig(async(e,t)=>this.parseResult([{text:e}],t?.callbacks),e,{...t,runType:`parser`}):this._callWithConfig(async(e,t)=>this.parseResult([{message:e,text:this._baseMessageToString(e)}],t?.callbacks),e,{...t,runType:`parser`})}},pC=class extends fC{parseResult(e,t){return this.parse(e[0].text,t)}async parseWithPrompt(e,t,n){return this.parse(e,n)}_type(){throw Error(`_type not implemented`)}},mC=class extends Error{llmOutput;observation;sendToLLM;constructor(e,t,n,r=!1){if(super(e),this.llmOutput=t,this.observation=n,this.sendToLLM=r,r&&(n===void 0||t===void 0))throw Error(`Arguments 'observation' & 'llmOutput' are required if 'sendToLlm' is true`);u(this,`OUTPUT_PARSING_FAILURE`)}},hC=class extends pC{async*_transform(e){for await(let t of e)typeof t==`string`?yield this.parseResult([{text:t}]):yield this.parseResult([{message:t,text:this._baseMessageToString(t)}])}async*transform(e,t){yield*this._transformStreamWithConfig(e,this._transform.bind(this),{...t,runType:`parser`})}},gC=class extends hC{diff=!1;constructor(e){super(e),this.diff=e?.diff??this.diff}async*_transform(e){let t,n;for await(let r of e){if(typeof r!=`string`&&typeof r.content!=`string`)throw Error(`Cannot handle non-string output.`);let e;if(mt(r)){if(typeof r.content!=`string`)throw Error(`Cannot handle non-string message output.`);e=new Xl({message:r,text:r.content})}else if(pt(r)){if(typeof r.content!=`string`)throw Error(`Cannot handle non-string message output.`);e=new Xl({message:En(r),text:r.content})}else e=new Yl({text:r});n=n===void 0?e:n.concat(e);let i=await this.parsePartialResult([n]);i!=null&&!ev(i,t)&&(this.diff?yield this._diff(t,i):yield i,t=i)}}getFormatInstructions(){return``}},_C=class extends hC{static lc_name(){return`BytesOutputParser`}lc_namespace=[`langchain_core`,`output_parsers`,`bytes`];lc_serializable=!0;textEncoder=new TextEncoder;parse(e){return Promise.resolve(this.textEncoder.encode(e))}getFormatInstructions(){return``}},vC=class extends hC{re;async*_transform(e){let t=``;for await(let n of e)if(typeof n==`string`?t+=n:t+=n.content,this.re){let e=[...t.matchAll(this.re)];if(e.length>1){let n=0;for(let t of e.slice(0,-1))yield[t[1]],n+=(t.index??0)+t[0].length;t=t.slice(n)}}else{let e=await this.parse(t);if(e.length>1){for(let t of e.slice(0,-1))yield[t];t=e[e.length-1]}}for(let e of await this.parse(t))yield[e]}},yC=class extends vC{static lc_name(){return`CommaSeparatedListOutputParser`}lc_namespace=[`langchain_core`,`output_parsers`,`list`];lc_serializable=!0;async parse(e){try{return e.trim().split(`,`).map(e=>e.trim())}catch{throw new mC(`Could not parse output: ${e}`,e)}}getFormatInstructions(){return"Your response should be a list of comma separated values, eg: `foo, bar, baz`"}},bC=class extends vC{lc_namespace=[`langchain_core`,`output_parsers`,`list`];length;separator;constructor({length:e,separator:t}){super(...arguments),this.length=e,this.separator=t||`,`}async parse(e){try{let t=e.trim().split(this.separator).map(e=>e.trim());if(this.length!==void 0&&t.length!==this.length)throw new mC(`Incorrect number of items. Expected ${this.length}, got ${t.length}.`);return t}catch(t){throw Object.getPrototypeOf(t)===mC.prototype?t:new mC(`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\`)`}},xC=class extends vC{static lc_name(){return`NumberedListOutputParser`}lc_namespace=[`langchain_core`,`output_parsers`,`list`];lc_serializable=!0;getFormatInstructions(){return`Your response should be a numbered list with each item on a new line. For example:
66
-
67
- 1. foo
68
-
69
- 2. bar
70
-
71
- 3. baz`}re=/\d+\.\s([^\n]+)/g;async parse(e){return[...e.matchAll(this.re)??[]].map(e=>e[1])}},SC=class extends vC{static lc_name(){return`NumberedListOutputParser`}lc_namespace=[`langchain_core`,`output_parsers`,`list`];lc_serializable=!0;getFormatInstructions(){return`Your response should be a numbered list with each item on a new line. For example:
72
-
73
- 1. foo
74
-
75
- 2. bar
76
-
77
- 3. baz`}re=/^\s*[-*]\s([^\n]+)$/gm;async parse(e){return[...e.matchAll(this.re)??[]].map(e=>e[1])}},CC=class extends hC{static lc_name(){return`StrOutputParser`}lc_namespace=[`langchain_core`,`output_parsers`,`string`];lc_serializable=!0;parse(e){return Promise.resolve(e)}getFormatInstructions(){return``}_textContentToString(e){return e.text}_imageUrlContentToString(e){throw 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 Error(`Cannot coerce "${e.type}" message part into a string.`)}throw Error(`Invalid content type: ${e.type}`)}_baseMessageContentToString(e){return e.reduce((e,t)=>e+this._messageContentToString(t),``)}},wC=class extends gC{static lc_name(){return`JsonOutputParser`}lc_namespace=[`langchain_core`,`output_parsers`];lc_serializable=!0;_concatOutputChunks(e,t){return this.diff?super._concatOutputChunks(e,t):t}_diff(e,t){if(t)return e?Rl(e,t):[{op:`replace`,path:``,value:t}]}async parsePartialResult(e){return v(e[0].text)}async parse(e){return v(e,JSON.parse)}getFormatInstructions(){return``}_baseMessageToString(e){return e.text}},TC=class extends pC{static lc_name(){return`StandardSchemaOutputParser`}lc_namespace=[`langchain`,`output_parsers`,`standard_schema`];schema;constructor(e){super(),this.schema=e}static fromSerializableSchema(e){return new this(e)}async parse(e){try{let t=v(e,JSON.parse),n=await this.schema[`~standard`].validate(t);if(n.issues)throw Error(`Validation failed: ${JSON.stringify(n.issues)}`);return n.value}catch(t){throw new mC(`Failed to parse. Text: "${e}". Error: ${t}`,e)}}_baseMessageToString(e){return e.text}getFormatInstructions(){return``}},EC=class extends pC{static lc_name(){return`StructuredOutputParser`}lc_namespace=[`langchain`,`output_parsers`,`structured`];toJSON(){return this.toJSONNotImplemented()}constructor(e){super(e),this.schema=e}static fromZodSchema(e){return new this(e)}static fromNamesAndDescriptions(e){let t=e_(Object.fromEntries(Object.entries(e).map(([e,t])=>[e,Yg().describe(t)])));return new this(t)}getFormatInstructions(){return`You must format your output as a JSON value that adheres to a given "JSON Schema" instance.
78
-
79
- "JSON Schema" is a declarative language that allows you to annotate and validate JSON documents.
80
-
81
- For example, the example "JSON Schema" instance {{"properties": {{"foo": {{"description": "a list of test words", "type": "array", "items": {{"type": "string"}}}}}}, "required": ["foo"]}}
82
- 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.
83
- 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.
84
-
85
- 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!
86
-
87
- Here is the JSON Schema instance your output must adhere to. Include the enclosing markdown codeblock:
88
- \`\`\`json
89
- ${JSON.stringify(Bv(this.schema))}
90
- \`\`\`
91
- `}async parse(e){try{let t=e.trim(),n=(t.match(/^```(?:json)?\s*([\s\S]*?)```/)?.[1]||t.match(/```json\s*([\s\S]*?)```/)?.[1]||t).replace(/"([^"\\]*(\\.[^"\\]*)*)"/g,(e,t)=>`"${t.replace(/\n/g,`\\n`)}"`).replace(/\n/g,``);return await Lm(this.schema,JSON.parse(n))}catch(t){throw new mC(`Failed to parse. Text: "${e}". Error: ${t}`,e)}}_baseMessageToString(e){return e.text}},DC=class extends EC{static lc_name(){return`JsonMarkdownStructuredOutputParser`}getFormatInstructions(e){let t=e?.interpolationDepth??1;if(t<1)throw Error(`f string interpolation depth must be at least 1`);return`Return a markdown code snippet with a JSON object formatted to look like:\n\`\`\`json\n${this._schemaToInstruction(Bv(this.schema)).replaceAll(`{`,`{`.repeat(t)).replaceAll(`}`,`}`.repeat(t))}\n\`\`\``}_schemaToInstruction(e,t=2){let n=e;if(`type`in n){let e=!1,r;if(Array.isArray(n.type)){let t=n.type.findIndex(e=>e===`null`);t!==-1&&(e=!0,n.type.splice(t,1)),r=n.type.join(` | `)}else r=n.type;if(n.type===`object`&&n.properties){let e=n.description?` // ${n.description}`:``;return`{\n${Object.entries(n.properties).map(([e,r])=>{let i=n.required?.includes(e)?``:` (optional)`;return`${` `.repeat(t)}"${e}": ${this._schemaToInstruction(r,t+2)}${i}`}).join(`
92
- `)}\n${` `.repeat(t-2)}}${e}`}if(n.type===`array`&&n.items){let e=n.description?` // ${n.description}`:``;return`array[\n${` `.repeat(t)}${this._schemaToInstruction(n.items,t+2)}\n${` `.repeat(t-2)}] ${e}`}let i=e?` (nullable)`:``,a=n.description?` // ${n.description}`:``;return`${r}${a}${i}`}if(`anyOf`in n)return n.anyOf.map(e=>this._schemaToInstruction(e,t)).join(`\n${` `.repeat(t-2)}`);throw Error(`unsupported schema type`)}static fromZodSchema(e){return new this(e)}static fromNamesAndDescriptions(e){let t=e_(Object.fromEntries(Object.entries(e).map(([e,t])=>[e,Yg().describe(t)])));return new this(t)}},OC=class extends pC{structuredInputParser;constructor({inputSchema:e}){super(...arguments),this.structuredInputParser=new DC(e)}async parse(e){let t;try{t=await this.structuredInputParser.parse(e)}catch(t){throw new mC(`Failed to parse. Text: "${e}". Error: ${t}`,e)}return this.outputProcessor(t)}getFormatInstructions(){return this.structuredInputParser.getFormatInstructions()}},kC=function(){let e={};e.parser=function(e,t){return new n(e,t)},e.SAXParser=n,e.SAXStream=l,e.createStream=c,e.MAX_BUFFER_LENGTH=64*1024;let t=[`comment`,`sgmlDecl`,`textNode`,`tagName`,`doctype`,`procInstName`,`procInstBody`,`entity`,`attribName`,`attribValue`,`cdata`,`script`];e.EVENTS=[`text`,`processinginstruction`,`sgmldeclaration`,`doctype`,`comment`,`opentagstart`,`attribute`,`opentag`,`closetag`,`opencdata`,`cdata`,`closecdata`,`error`,`end`,`ready`,`script`,`opennamespace`,`closenamespace`];function n(t,r){if(!(this instanceof n))return new n(t,r);var a=this;i(a),a.q=a.c=``,a.bufferCheckPosition=e.MAX_BUFFER_LENGTH,a.opt=r||{},a.opt.lowercase=a.opt.lowercase||a.opt.lowercasetags,a.looseCase=a.opt.lowercase?`toLowerCase`:`toUpperCase`,a.tags=[],a.closed=a.closedRoot=a.sawRoot=!1,a.tag=a.error=null,a.strict=!!t,a.noscript=!!(t||a.opt.noscript),a.state=S.BEGIN,a.strictEntities=a.opt.strictEntities,a.ENTITIES=a.strictEntities?Object.create(e.XML_ENTITIES):Object.create(e.ENTITIES),a.attribList=[],a.opt.xmlns&&(a.ns=Object.create(m)),a.trackPosition=a.opt.position!==!1,a.trackPosition&&(a.position=a.line=a.column=0),re(a,`onready`)}Object.create||(Object.create=function(e){function t(){}return t.prototype=e,new t}),Object.keys||(Object.keys=function(e){var t=[];for(var n in e)e.hasOwnProperty(n)&&t.push(n);return t});function r(n){for(var r=Math.max(e.MAX_BUFFER_LENGTH,10),i=0,a=0,o=t.length;a<o;a++){var s=n[t[a]].length;if(s>r)switch(t[a]){case`textNode`:ae(n);break;case`cdata`:ie(n,`oncdata`,n.cdata),n.cdata=``;break;case`script`:ie(n,`onscript`,n.script),n.script=``;break;default:se(n,`Max buffer length exceeded: `+t[a])}i=Math.max(i,s)}n.bufferCheckPosition=e.MAX_BUFFER_LENGTH-i+n.position}function i(e){for(var n=0,r=t.length;n<r;n++)e[t[n]]=``}function a(e){ae(e),e.cdata!==``&&(ie(e,`oncdata`,e.cdata),e.cdata=``),e.script!==``&&(ie(e,`onscript`,e.script),e.script=``)}n.prototype={end:function(){ce(this)},write:_e,resume:function(){return this.error=null,this},close:function(){return this.write(null)},flush:function(){a(this)}};var o=ReadableStream;o||=function(){};var s=e.EVENTS.filter(function(e){return e!==`error`&&e!==`end`});function c(e,t){return new l(e,t)}function l(e,t){if(!(this instanceof l))return new l(e,t);o.apply(this),this._parser=new n(e,t),this.writable=!0,this.readable=!0;var r=this;this._parser.onend=function(){r.emit(`end`)},this._parser.onerror=function(e){r.emit(`error`,e),r._parser.error=null},this._decoder=null,s.forEach(function(e){Object.defineProperty(r,`on`+e,{get:function(){return r._parser[`on`+e]},set:function(t){if(!t)return r.removeAllListeners(e),r._parser[`on`+e]=t,t;r.on(e,t)},enumerable:!0,configurable:!1})})}l.prototype=Object.create(o.prototype,{constructor:{value:l}}),l.prototype.write=function(e){return this._parser.write(e.toString()),this.emit(`data`,e),!0},l.prototype.end=function(e){return e&&e.length&&this.write(e),this._parser.end(),!0},l.prototype.on=function(e,t){var n=this;return!n._parser[`on`+e]&&s.indexOf(e)!==-1&&(n._parser[`on`+e]=function(){var t=arguments.length===1?[arguments[0]]:Array.apply(null,arguments);t.splice(0,0,e),n.emit.apply(n,t)}),o.prototype.on.call(n,e,t)};var u=`[CDATA[`,d=`DOCTYPE`,f=`http://www.w3.org/XML/1998/namespace`,p=`http://www.w3.org/2000/xmlns/`,m={xml:f,xmlns:p},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]/,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-]/,_=/[#:_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]/,v=/[#:_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 y(e){return e===` `||e===`
93
- `||e===`\r`||e===` `}function b(e){return e===`"`||e===`'`}function ee(e){return e===`>`||y(e)}function x(e,t){return e.test(t)}function te(e,t){return!x(e,t)}var S=0;for(var ne in e.STATE={BEGIN:S++,BEGIN_WHITESPACE:S++,TEXT:S++,TEXT_ENTITY:S++,OPEN_WAKA:S++,SGML_DECL:S++,SGML_DECL_QUOTED:S++,DOCTYPE:S++,DOCTYPE_QUOTED:S++,DOCTYPE_DTD:S++,DOCTYPE_DTD_QUOTED:S++,COMMENT_STARTING:S++,COMMENT:S++,COMMENT_ENDING:S++,COMMENT_ENDED:S++,CDATA:S++,CDATA_ENDING:S++,CDATA_ENDING_2:S++,PROC_INST:S++,PROC_INST_BODY:S++,PROC_INST_ENDING:S++,OPEN_TAG:S++,OPEN_TAG_SLASH:S++,ATTRIB:S++,ATTRIB_NAME:S++,ATTRIB_NAME_SAW_WHITE:S++,ATTRIB_VALUE:S++,ATTRIB_VALUE_QUOTED:S++,ATTRIB_VALUE_CLOSED:S++,ATTRIB_VALUE_UNQUOTED:S++,ATTRIB_VALUE_ENTITY_Q:S++,ATTRIB_VALUE_ENTITY_U:S++,CLOSE_TAG:S++,CLOSE_TAG_SAW_WHITE:S++,SCRIPT:S++,SCRIPT_ENDING:S++},e.XML_ENTITIES={amp:`&`,gt:`>`,lt:`<`,quot:`"`,apos:`'`},e.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(e.ENTITIES).forEach(function(t){var n=e.ENTITIES[t],r=typeof n==`number`?String.fromCharCode(n):n;e.ENTITIES[t]=r}),e.STATE)e.STATE[e.STATE[ne]]=ne;S=e.STATE;function re(e,t,n){e[t]&&e[t](n)}function ie(e,t,n){e.textNode&&ae(e),re(e,t,n)}function ae(e){e.textNode=oe(e.opt,e.textNode),e.textNode&&re(e,`ontext`,e.textNode),e.textNode=``}function oe(e,t){return e.trim&&(t=t.trim()),e.normalize&&(t=t.replace(/\s+/g,` `)),t}function se(e,t){return ae(e),e.trackPosition&&(t+=`
94
- Line: `+e.line+`
95
- Column: `+e.column+`
96
- Char: `+e.c),t=Error(t),e.error=t,re(e,`onerror`,t),e}function ce(e){return e.sawRoot&&!e.closedRoot&&C(e,`Unclosed root tag`),e.state!==S.BEGIN&&e.state!==S.BEGIN_WHITESPACE&&e.state!==S.TEXT&&se(e,`Unexpected end`),ae(e),e.c=``,e.closed=!0,re(e,`onend`),n.call(e,e.strict,e.opt),e}function C(e,t){if(typeof e!=`object`||!(e instanceof n))throw Error(`bad call to strictFail`);e.strict&&se(e,t)}function le(e){e.strict||(e.tagName=e.tagName[e.looseCase]());var t=e.tags[e.tags.length-1]||e,n=e.tag={name:e.tagName,attributes:{}};e.opt.xmlns&&(n.ns=t.ns),e.attribList.length=0,ie(e,`onopentagstart`,n)}function ue(e,t){var n=e.indexOf(`:`)<0?[``,e]:e.split(`:`),r=n[0],i=n[1];return t&&e===`xmlns`&&(r=`xmlns`,i=``),{prefix:r,local:i}}function de(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 t=ue(e.attribName,!0),n=t.prefix,r=t.local;if(n===`xmlns`)if(r===`xml`&&e.attribValue!==f)C(e,`xml: prefix must be bound to `+f+`
97
- Actual: `+e.attribValue);else if(r===`xmlns`&&e.attribValue!==p)C(e,`xmlns: prefix must be bound to `+p+`
98
- Actual: `+e.attribValue);else{var i=e.tag,a=e.tags[e.tags.length-1]||e;i.ns===a.ns&&(i.ns=Object.create(a.ns)),i.ns[r]=e.attribValue}e.attribList.push([e.attribName,e.attribValue])}else e.tag.attributes[e.attribName]=e.attribValue,ie(e,`onattribute`,{name:e.attribName,value:e.attribValue});e.attribName=e.attribValue=``}function fe(e,t){if(e.opt.xmlns){var n=e.tag,r=ue(e.tagName);n.prefix=r.prefix,n.local=r.local,n.uri=n.ns[r.prefix]||``,n.prefix&&!n.uri&&(C(e,`Unbound namespace prefix: `+JSON.stringify(e.tagName)),n.uri=r.prefix);var i=e.tags[e.tags.length-1]||e;n.ns&&i.ns!==n.ns&&Object.keys(n.ns).forEach(function(t){ie(e,`onopennamespace`,{prefix:t,uri:n.ns[t]})});for(var a=0,o=e.attribList.length;a<o;a++){var s=e.attribList[a],c=s[0],l=s[1],u=ue(c,!0),d=u.prefix,f=u.local,p=d===``?``:n.ns[d]||``,m={name:c,value:l,prefix:d,local:f,uri:p};d&&d!==`xmlns`&&!p&&(C(e,`Unbound namespace prefix: `+JSON.stringify(d)),m.uri=d),e.tag.attributes[c]=m,ie(e,`onattribute`,m)}e.attribList.length=0}e.tag.isSelfClosing=!!t,e.sawRoot=!0,e.tags.push(e.tag),ie(e,`onopentag`,e.tag),t||(!e.noscript&&e.tagName.toLowerCase()===`script`?e.state=S.SCRIPT:e.state=S.TEXT,e.tag=null,e.tagName=``),e.attribName=e.attribValue=``,e.attribList.length=0}function pe(e){if(!e.tagName){C(e,`Weird empty close tag.`),e.textNode+=`</>`,e.state=S.TEXT;return}if(e.script){if(e.tagName!==`script`){e.script+=`</`+e.tagName+`>`,e.tagName=``,e.state=S.SCRIPT;return}ie(e,`onscript`,e.script),e.script=``}var t=e.tags.length,n=e.tagName;e.strict||(n=n[e.looseCase]());for(var r=n;t--&&e.tags[t].name!==r;)C(e,`Unexpected close tag`);if(t<0){C(e,`Unmatched closing tag: `+e.tagName),e.textNode+=`</`+e.tagName+`>`,e.state=S.TEXT;return}e.tagName=n;for(var i=e.tags.length;i-- >t;){var a=e.tag=e.tags.pop();e.tagName=e.tag.name,ie(e,`onclosetag`,e.tagName);var o={};for(var s in a.ns)o[s]=a.ns[s];var c=e.tags[e.tags.length-1]||e;e.opt.xmlns&&a.ns!==c.ns&&Object.keys(a.ns).forEach(function(t){var n=a.ns[t];ie(e,`onclosenamespace`,{prefix:t,uri:n})})}t===0&&(e.closedRoot=!0),e.tagName=e.attribValue=e.attribName=``,e.attribList.length=0,e.state=S.TEXT}function me(e){var t=e.entity,n=t.toLowerCase(),r,i=``;return e.ENTITIES[t]?e.ENTITIES[t]:e.ENTITIES[n]?e.ENTITIES[n]:(t=n,t.charAt(0)===`#`&&(t.charAt(1)===`x`?(t=t.slice(2),r=parseInt(t,16),i=r.toString(16)):(t=t.slice(1),r=parseInt(t,10),i=r.toString(10))),t=t.replace(/^0+/,``),isNaN(r)||i.toLowerCase()!==t?(C(e,`Invalid character entity`),`&`+e.entity+`;`):String.fromCodePoint(r))}function he(e,t){t===`<`?(e.state=S.OPEN_WAKA,e.startTagPosition=e.position):y(t)||(C(e,`Non-whitespace before first tag.`),e.textNode=t,e.state=S.TEXT)}function ge(e,t){var n=``;return t<e.length&&(n=e.charAt(t)),n}function _e(e){var t=this;if(this.error)throw this.error;if(t.closed)return se(t,`Cannot write after close. Assign an onready handler.`);if(e===null)return ce(t);typeof e==`object`&&(e=e.toString());for(var n=0,i=``;i=ge(e,n++),t.c=i,i;)switch(t.trackPosition&&(t.position++,i===`
99
- `?(t.line++,t.column=0):t.column++),t.state){case S.BEGIN:if(t.state=S.BEGIN_WHITESPACE,i===`ο»Ώ`)continue;he(t,i);continue;case S.BEGIN_WHITESPACE:he(t,i);continue;case S.TEXT:if(t.sawRoot&&!t.closedRoot){for(var a=n-1;i&&i!==`<`&&i!==`&`;)i=ge(e,n++),i&&t.trackPosition&&(t.position++,i===`
100
- `?(t.line++,t.column=0):t.column++);t.textNode+=e.substring(a,n-1)}i===`<`&&!(t.sawRoot&&t.closedRoot&&!t.strict)?(t.state=S.OPEN_WAKA,t.startTagPosition=t.position):(!y(i)&&(!t.sawRoot||t.closedRoot)&&C(t,`Text data outside of root node.`),i===`&`?t.state=S.TEXT_ENTITY:t.textNode+=i);continue;case S.SCRIPT:i===`<`?t.state=S.SCRIPT_ENDING:t.script+=i;continue;case S.SCRIPT_ENDING:i===`/`?t.state=S.CLOSE_TAG:(t.script+=`<`+i,t.state=S.SCRIPT);continue;case S.OPEN_WAKA:if(i===`!`)t.state=S.SGML_DECL,t.sgmlDecl=``;else if(!y(i))if(x(h,i))t.state=S.OPEN_TAG,t.tagName=i;else if(i===`/`)t.state=S.CLOSE_TAG,t.tagName=``;else if(i===`?`)t.state=S.PROC_INST,t.procInstName=t.procInstBody=``;else{if(C(t,`Unencoded <`),t.startTagPosition+1<t.position){var o=t.position-t.startTagPosition;i=Array(o).join(` `)+i}t.textNode+=`<`+i,t.state=S.TEXT}continue;case S.SGML_DECL:(t.sgmlDecl+i).toUpperCase()===u?(ie(t,`onopencdata`),t.state=S.CDATA,t.sgmlDecl=``,t.cdata=``):t.sgmlDecl+i===`--`?(t.state=S.COMMENT,t.comment=``,t.sgmlDecl=``):(t.sgmlDecl+i).toUpperCase()===d?(t.state=S.DOCTYPE,(t.doctype||t.sawRoot)&&C(t,`Inappropriately located doctype declaration`),t.doctype=``,t.sgmlDecl=``):i===`>`?(ie(t,`onsgmldeclaration`,t.sgmlDecl),t.sgmlDecl=``,t.state=S.TEXT):(b(i)&&(t.state=S.SGML_DECL_QUOTED),t.sgmlDecl+=i);continue;case S.SGML_DECL_QUOTED:i===t.q&&(t.state=S.SGML_DECL,t.q=``),t.sgmlDecl+=i;continue;case S.DOCTYPE:i===`>`?(t.state=S.TEXT,ie(t,`ondoctype`,t.doctype),t.doctype=!0):(t.doctype+=i,i===`[`?t.state=S.DOCTYPE_DTD:b(i)&&(t.state=S.DOCTYPE_QUOTED,t.q=i));continue;case S.DOCTYPE_QUOTED:t.doctype+=i,i===t.q&&(t.q=``,t.state=S.DOCTYPE);continue;case S.DOCTYPE_DTD:t.doctype+=i,i===`]`?t.state=S.DOCTYPE:b(i)&&(t.state=S.DOCTYPE_DTD_QUOTED,t.q=i);continue;case S.DOCTYPE_DTD_QUOTED:t.doctype+=i,i===t.q&&(t.state=S.DOCTYPE_DTD,t.q=``);continue;case S.COMMENT:i===`-`?t.state=S.COMMENT_ENDING:t.comment+=i;continue;case S.COMMENT_ENDING:i===`-`?(t.state=S.COMMENT_ENDED,t.comment=oe(t.opt,t.comment),t.comment&&ie(t,`oncomment`,t.comment),t.comment=``):(t.comment+=`-`+i,t.state=S.COMMENT);continue;case S.COMMENT_ENDED:i===`>`?t.state=S.TEXT:(C(t,`Malformed comment`),t.comment+=`--`+i,t.state=S.COMMENT);continue;case S.CDATA:i===`]`?t.state=S.CDATA_ENDING:t.cdata+=i;continue;case S.CDATA_ENDING:i===`]`?t.state=S.CDATA_ENDING_2:(t.cdata+=`]`+i,t.state=S.CDATA);continue;case S.CDATA_ENDING_2:i===`>`?(t.cdata&&ie(t,`oncdata`,t.cdata),ie(t,`onclosecdata`),t.cdata=``,t.state=S.TEXT):i===`]`?t.cdata+=`]`:(t.cdata+=`]]`+i,t.state=S.CDATA);continue;case S.PROC_INST:i===`?`?t.state=S.PROC_INST_ENDING:y(i)?t.state=S.PROC_INST_BODY:t.procInstName+=i;continue;case S.PROC_INST_BODY:if(!t.procInstBody&&y(i))continue;i===`?`?t.state=S.PROC_INST_ENDING:t.procInstBody+=i;continue;case S.PROC_INST_ENDING:i===`>`?(ie(t,`onprocessinginstruction`,{name:t.procInstName,body:t.procInstBody}),t.procInstName=t.procInstBody=``,t.state=S.TEXT):(t.procInstBody+=`?`+i,t.state=S.PROC_INST_BODY);continue;case S.OPEN_TAG:x(g,i)?t.tagName+=i:(le(t),i===`>`?fe(t):i===`/`?t.state=S.OPEN_TAG_SLASH:(y(i)||C(t,`Invalid character in tag name`),t.state=S.ATTRIB));continue;case S.OPEN_TAG_SLASH:i===`>`?(fe(t,!0),pe(t)):(C(t,`Forward-slash in opening tag not followed by >`),t.state=S.ATTRIB);continue;case S.ATTRIB:if(y(i))continue;i===`>`?fe(t):i===`/`?t.state=S.OPEN_TAG_SLASH:x(h,i)?(t.attribName=i,t.attribValue=``,t.state=S.ATTRIB_NAME):C(t,`Invalid attribute name`);continue;case S.ATTRIB_NAME:i===`=`?t.state=S.ATTRIB_VALUE:i===`>`?(C(t,`Attribute without value`),t.attribValue=t.attribName,de(t),fe(t)):y(i)?t.state=S.ATTRIB_NAME_SAW_WHITE:x(g,i)?t.attribName+=i:C(t,`Invalid attribute name`);continue;case S.ATTRIB_NAME_SAW_WHITE:if(i===`=`)t.state=S.ATTRIB_VALUE;else if(y(i))continue;else C(t,`Attribute without value`),t.tag.attributes[t.attribName]=``,t.attribValue=``,ie(t,`onattribute`,{name:t.attribName,value:``}),t.attribName=``,i===`>`?fe(t):x(h,i)?(t.attribName=i,t.state=S.ATTRIB_NAME):(C(t,`Invalid attribute name`),t.state=S.ATTRIB);continue;case S.ATTRIB_VALUE:if(y(i))continue;b(i)?(t.q=i,t.state=S.ATTRIB_VALUE_QUOTED):(C(t,`Unquoted attribute value`),t.state=S.ATTRIB_VALUE_UNQUOTED,t.attribValue=i);continue;case S.ATTRIB_VALUE_QUOTED:if(i!==t.q){i===`&`?t.state=S.ATTRIB_VALUE_ENTITY_Q:t.attribValue+=i;continue}de(t),t.q=``,t.state=S.ATTRIB_VALUE_CLOSED;continue;case S.ATTRIB_VALUE_CLOSED:y(i)?t.state=S.ATTRIB:i===`>`?fe(t):i===`/`?t.state=S.OPEN_TAG_SLASH:x(h,i)?(C(t,`No whitespace between attributes`),t.attribName=i,t.attribValue=``,t.state=S.ATTRIB_NAME):C(t,`Invalid attribute name`);continue;case S.ATTRIB_VALUE_UNQUOTED:if(!ee(i)){i===`&`?t.state=S.ATTRIB_VALUE_ENTITY_U:t.attribValue+=i;continue}de(t),i===`>`?fe(t):t.state=S.ATTRIB;continue;case S.CLOSE_TAG:if(t.tagName)i===`>`?pe(t):x(g,i)?t.tagName+=i:t.script?(t.script+=`</`+t.tagName,t.tagName=``,t.state=S.SCRIPT):(y(i)||C(t,`Invalid tagname in closing tag`),t.state=S.CLOSE_TAG_SAW_WHITE);else{if(y(i))continue;te(h,i)?t.script?(t.script+=`</`+i,t.state=S.SCRIPT):C(t,`Invalid tagname in closing tag.`):t.tagName=i}continue;case S.CLOSE_TAG_SAW_WHITE:if(y(i))continue;i===`>`?pe(t):C(t,`Invalid characters in closing tag`);continue;case S.TEXT_ENTITY:case S.ATTRIB_VALUE_ENTITY_Q:case S.ATTRIB_VALUE_ENTITY_U:var s,c;switch(t.state){case S.TEXT_ENTITY:s=S.TEXT,c=`textNode`;break;case S.ATTRIB_VALUE_ENTITY_Q:s=S.ATTRIB_VALUE_QUOTED,c=`attribValue`;break;case S.ATTRIB_VALUE_ENTITY_U:s=S.ATTRIB_VALUE_UNQUOTED,c=`attribValue`;break}if(i===`;`)if(t.opt.unparsedEntities){var l=me(t);t.entity=``,t.state=s,t.write(l)}else t[c]+=me(t),t.entity=``,t.state=s;else x(t.entity.length?v:_,i)?t.entity+=i:(C(t,`Invalid character in entity name`),t[c]+=`&`+t.entity+i,t.entity=``,t.state=s);continue;default:throw Error(t,`Unknown state: `+t.state)}return t.position>=t.bufferCheckPosition&&r(t),t}return String.fromCodePoint||(function(){var e=String.fromCharCode,t=Math.floor,n=function(){var n=16384,r=[],i,a,o=-1,s=arguments.length;if(!s)return``;for(var c=``;++o<s;){var l=Number(arguments[o]);if(!isFinite(l)||l<0||l>1114111||t(l)!==l)throw RangeError(`Invalid code point: `+l);l<=65535?r.push(l):(l-=65536,i=(l>>10)+55296,a=l%1024+56320,r.push(i,a)),(o+1===s||r.length>n)&&(c+=e.apply(null,r),r.length=0)}return c};Object.defineProperty?Object.defineProperty(String,`fromCodePoint`,{value:n,configurable:!0,writable:!0}):String.fromCodePoint=n})(),e}(),AC=`The output should be formatted as a XML file.
101
- 1. Output should conform to the tags below.
102
- 2. If tags are not given, make them on your own.
103
- 3. Remember to always open and close all the tags.
104
-
105
- As an example, for the tags ["foo", "bar", "baz"]:
106
- 1. String "<foo>
107
- <bar>
108
- <baz></baz>
109
- </bar>
110
- </foo>" is a well-formatted instance of the schema.
111
- 2. String "<foo>
112
- <bar>
113
- </foo>" is a badly-formatted instance.
114
- 3. String "<foo>
115
- <tag>
116
- </tag>
117
- </foo>" is a badly-formatted instance.
118
-
119
- Here are the output tags:
120
- \`\`\`
121
- {tags}
122
- \`\`\``,jC=class extends gC{tags;constructor(e){super(e),this.tags=e?.tags}static lc_name(){return`XMLOutputParser`}lc_namespace=[`langchain_core`,`output_parsers`];lc_serializable=!0;_diff(e,t){if(t)return e?Rl(e,t):[{op:`replace`,path:``,value:t}]}async parsePartialResult(e){return PC(e[0].text)}async parse(e){return PC(e)}getFormatInstructions(){return this.tags&&this.tags.length>0?AC.replace(`{tags}`,this.tags?.join(`, `)??``):AC}},MC=e=>e.split(`
123
- `).map(e=>e.replace(/^\s+/,``)).join(`
124
- `).trim(),NC=e=>{if(Object.keys(e).length===0)return{};let t={};return e.children.length>0?(t[e.name]=e.children.map(NC),t):(t[e.name]=e.text??void 0,t)};function PC(e){let t=MC(e),n=kC.parser(!0),r={},i=[];n.onopentag=e=>{let t={name:e.name,attributes:e.attributes,children:[],text:``,isSelfClosing:e.isSelfClosing};i.length>0?i[i.length-1].children.push(t):r=t,e.isSelfClosing||i.push(t)},n.onclosetag=()=>{if(i.length>0){let e=i.pop();i.length===0&&e&&(r=e)}},n.ontext=e=>{if(i.length>0){let t=i[i.length-1];t.text+=e}},n.onattribute=e=>{if(i.length>0){let t=i[i.length-1];t.attributes[e.name]=e.value}};let a=/```(xml)?(.*)```/s.exec(t),o=a?a[2]:t;return n.write(o).close(),r&&r.name===`?xml`&&(r=r.children[0]),NC(r)}var FC=o({AsymmetricStructuredOutputParser:()=>OC,BaseCumulativeTransformOutputParser:()=>gC,BaseLLMOutputParser:()=>fC,BaseOutputParser:()=>pC,BaseTransformOutputParser:()=>hC,BytesOutputParser:()=>_C,CommaSeparatedListOutputParser:()=>yC,CustomListOutputParser:()=>bC,JsonMarkdownStructuredOutputParser:()=>DC,JsonOutputParser:()=>wC,ListOutputParser:()=>vC,MarkdownListOutputParser:()=>SC,NumberedListOutputParser:()=>xC,OutputParserException:()=>mC,StandardSchemaOutputParser:()=>TC,StringOutputParser:()=>CC,StructuredOutputParser:()=>EC,XMLOutputParser:()=>jC,XML_FORMAT_INSTRUCTIONS:()=>AC,parseJsonMarkdown:()=>v,parsePartialJson:()=>b,parseXMLMarkdown:()=>PC}),IC=o({extendInteropZodObject:()=>Xm,getInteropZodDefaultGetter:()=>eh,getInteropZodObjectShape:()=>Ym,getSchemaDescription:()=>Bm,interopParse:()=>zm,interopParseAsync:()=>Lm,interopSafeParse:()=>Rm,interopSafeParseAsync:()=>Im,interopZodObjectMakeFieldsOptional:()=>ah,interopZodObjectPartial:()=>Zm,interopZodObjectPassthrough:()=>$m,interopZodObjectStrict:()=>Qm,interopZodTransformInputSchema:()=>ih,isInteropZodError:()=>oh,isInteropZodLiteral:()=>Fm,isInteropZodObject:()=>Jm,isInteropZodSchema:()=>Mm,isShapelessZodSchema:()=>Vm,isSimpleStringZodSchema:()=>Hm,isZodArrayV4:()=>Gm,isZodLiteralV3:()=>Nm,isZodLiteralV4:()=>Pm,isZodNullableV4:()=>qm,isZodObjectV3:()=>Um,isZodObjectV4:()=>Wm,isZodOptionalV4:()=>Km,isZodSchema:()=>jm,isZodSchemaV3:()=>Am,isZodSchemaV4:()=>km});function LC(e,t){if(e.function===void 0)return;let n;if(t?.partial)try{n=b(e.function.arguments??`{}`)}catch{return}else try{n=JSON.parse(e.function.arguments)}catch(t){throw new mC([`Function "${e.function.name}" arguments:`,``,e.function.arguments,``,`are not valid JSON.`,`Error: ${t.message}`].join(`
125
- `))}let r={name:e.function.name,args:n,type:`tool_call`};return t?.returnId&&(r.id=e.id),r}function RC(e){if(e.id===void 0)throw Error(`All OpenAI tool calls must have an "id" field.`);return{id:e.id,type:`function`,function:{name:e.name,arguments:JSON.stringify(e.args)}}}function zC(e,t){return{name:e.function?.name,args:e.function?.arguments,id:e.id,error:t,type:`invalid_tool_call`}}var BC=class extends gC{static lc_name(){return`JsonOutputToolsParser`}returnId=!1;lc_namespace=[`langchain`,`output_parsers`,`openai_tools`];lc_serializable=!0;constructor(e){super(e),this.returnId=e?.returnId??this.returnId}_diff(){throw Error(`Not supported.`)}async parse(){throw Error(`Not implemented.`)}async parseResult(e){return await this.parsePartialResult(e,!1)}async parsePartialResult(e,t=!0){let n=e[0].message,r;if(Jt(n)&&n.tool_calls?.length?r=n.tool_calls.map(e=>{let{id:t,...n}=e;return this.returnId?{id:t,...n}:n}):n.additional_kwargs.tool_calls!==void 0&&(r=JSON.parse(JSON.stringify(n.additional_kwargs.tool_calls)).map(e=>LC(e,{returnId:this.returnId,partial:t}))),!r)return[];let i=[];for(let e of r)if(e!==void 0){let t={type:e.name,args:e.args,id:e.id};i.push(t)}return i}},VC=class extends BC{static lc_name(){return`JsonOutputKeyToolsParser`}lc_namespace=[`langchain`,`output_parsers`,`openai_tools`];lc_serializable=!0;returnId=!1;keyName;returnSingle=!1;zodSchema;serializableSchema;constructor(e){super(e),this.keyName=e.keyName,this.returnSingle=e.returnSingle??this.returnSingle,`zodSchema`in e&&(this.zodSchema=e.zodSchema),`serializableSchema`in e&&(this.serializableSchema=e.serializableSchema)}async _validateResult(e){if(this.serializableSchema!==void 0){let t=await this.serializableSchema[`~standard`].validate(e);if(t.issues)throw new mC(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(t.issues)}`,JSON.stringify(e,null,2));return t.value}if(this.zodSchema===void 0)return e;let t=await Im(this.zodSchema,e);if(t.success)return t.data;throw new mC(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(t.error?.issues)}`,JSON.stringify(e,null,2))}async parsePartialResult(e){let t=(await super.parsePartialResult(e)).filter(e=>e.type===this.keyName),n=t;if(t.length)return this.returnId||(n=t.map(e=>e.args)),this.returnSingle?n[0]:n}async parseResult(e){let t=(await super.parsePartialResult(e,!1)).filter(e=>e.type===this.keyName),n=t;if(t.length)return this.returnId||(n=t.map(e=>e.args)),this.returnSingle?this._validateResult(n[0]):await Promise.all(n.map(e=>this._validateResult(e)))}},HC=o({assembleStructuredOutputPipeline:()=>GC,createContentParser:()=>UC,createFunctionCallingParser:()=>WC});function UC(e){return Mm(e)?EC.fromZodSchema(e):$_(e)?TC.fromSerializableSchema(e):new wC}function WC(e,t,n){let r=n??VC;return Mm(e)?new r({returnSingle:!0,keyName:t,zodSchema:e}):$_(e)?new r({returnSingle:!0,keyName:t,serializableSchema:e}):new r({returnSingle:!0,keyName:t})}function GC(e,t,n,r){if(!n){let n=e.pipe(t);return r?n.withConfig({runName:r}):n}let i=yy.assign({parsed:(e,n)=>t.invoke(e.raw,n)}),a=yy.assign({parsed:()=>null}),o=i.withFallbacks({fallbacks:[a]}),s=sy.from([{raw:e},o]);return r?s.withConfig({runName:r}):s}var KC=o({ChatModelStream:()=>aw,ReasoningContentStream:()=>rw,TextContentStream:()=>tw,ToolCallsStream:()=>nw,UsageMetadataStream:()=>iw}),qC=class{events=[];finished=!1;waiters=[];error=null;push(e){this.events.push(e);let t=this.waiters.splice(0);for(let e of t)e()}finish(){this.finished=!0;let e=this.waiters.splice(0);for(let t of e)t()}setError(e){this.error=e,this.finished=!0;let t=this.waiters.splice(0);for(let e of t)e()}async*iterate(){if(this.finished){if(this.error)throw this.error;yield*this.events;return}let e=0;for(;;){for(;e<this.events.length;)yield this.events[e],e++;if(this.finished){if(this.error)throw this.error;return}await new Promise(t=>{if(e<this.events.length||this.finished){t();return}this.waiters.push(t)})}}};function JC(e,t){switch(t.type){case`text-delta`:return e.type===`text`?{...e,text:(e.text??``)+t.text}:e;case`reasoning-delta`:return e.type===`thinking`?{...e,thinking:(e.thinking??``)+t.reasoning}:e.type===`reasoning`?{...e,reasoning:(e.reasoning??``)+t.reasoning}:e;case`data-delta`:return{...e,data:(e.data??``)+t.data};case`block-delta`:return{...e,...t.fields};default:throw Error(`Unknown delta type: ${JSON.stringify(t)}`)}}function YC(e){if(e.event!==`content-block-delta`)return;if(`delta`in e&&e.delta)return e.delta;let t=e.content;if(typeof t!=`object`||!t)return;let n=t;if(n.type===`text`&&typeof n.text==`string`)return{type:`text-delta`,text:n.text};if(n.type===`reasoning`&&typeof n.reasoning==`string`)return{type:`reasoning-delta`,reasoning:n.reasoning};if(n.type===`thinking`&&typeof n.thinking==`string`)return{type:`reasoning-delta`,reasoning:n.thinking};if(typeof n.data==`string`)return{type:`data-delta`,data:n.data,encoding:`base64`};if(typeof n.type==`string`)return{type:`block-delta`,fields:{...n,type:n.type}}}function XC(e){if(typeof e!=`object`||!e)return;let t=e;if(t.type===`reasoning`&&typeof t.reasoning==`string`)return t.reasoning;if(t.type===`thinking`&&typeof t.thinking==`string`)return t.thinking}function ZC(e){if(typeof e!=`object`||!e)return!1;let t=e.type;return t===`reasoning`||t===`thinking`}function QC(e){if(e)return{...e,input_tokens:e.input_tokens??0,output_tokens:e.output_tokens??0,total_tokens:e.total_tokens??0}}function $C(e){if(typeof e==`object`&&e&&!Array.isArray(e))return e;if(typeof e!=`string`||e.length===0)return{};try{let t=JSON.parse(e);return typeof t==`object`&&t&&!Array.isArray(t)?t:{}}catch{return{}}}function ew(e){let t=e;if(e.type===`tool_call`||e.type!==`tool_call_chunk`&&e.type!==`tool_use`&&e.type!==`input_json_delta`)return e;let n=typeof t.name==`string`?t.name:void 0;if(n==null)return e;let r=t.args??t.input;return{...t,type:`tool_call`,name:n,args:$C(r)}}var tw=class{_buffer;constructor(e){this._buffer=e}get full(){let e=this._buffer;return{async*[Symbol.asyncIterator](){let t=``;for await(let n of e.iterate()){let e=YC(n);e?.type===`text-delta`&&(t+=e.text,yield t)}}}}[Symbol.asyncIterator](){let e=this._buffer;async function*t(){for await(let t of e.iterate()){let e=YC(t);e?.type===`text-delta`&&(yield e.text)}}return t()}then(e,t){return(async()=>{let e=``;for await(let t of this)e+=t;return e})().then(e,t)}},nw=class{_buffer;constructor(e){this._buffer=e}get full(){let e=this._buffer;return{async*[Symbol.asyncIterator](){let t=[];for await(let n of e.iterate())n.event===`content-block-finish`&&n.content.type===`tool_call`&&(t.push(n.content),yield[...t])}}}[Symbol.asyncIterator](){let e=this._buffer;async function*t(){for await(let t of e.iterate())t.event===`content-block-finish`&&t.content.type===`tool_call`&&(yield t.content)}return t()}then(e,t){return(async()=>{let e=[];for await(let t of this)e.push(t);return e})().then(e,t)}},rw=class{_buffer;constructor(e){this._buffer=e}get full(){let e=this._buffer;return{async*[Symbol.asyncIterator](){let t=``,n=!1;for await(let r of e.iterate())if(r.event===`content-block-start`){if(!ZC(r.content)){if(n)return;continue}n=!0;let e=XC(r.content);if(e==null||e.length===0)continue;t+=e,yield t}else if(r.event===`content-block-delta`){let e=YC(r);if(e?.type!==`reasoning-delta`)continue;n=!0;let i=e.reasoning;if(i==null||i.length===0)continue;t+=i,yield t}else if(r.event===`content-block-finish`&&ZC(r.content))return;else if(r.event===`message-finish`)return}}}[Symbol.asyncIterator](){let e=this._buffer;async function*t(){let t=!1;for await(let n of e.iterate())if(n.event===`content-block-start`){if(!ZC(n.content)){if(t)return;continue}t=!0;let e=XC(n.content);e!=null&&e.length>0&&(yield e)}else if(n.event===`content-block-delta`){let e=YC(n);if(e?.type!==`reasoning-delta`)continue;t=!0;let r=e.reasoning;r!=null&&r.length>0&&(yield r)}else if(n.event===`content-block-finish`&&ZC(n.content))return;else if(n.event===`message-finish`)return}return t()}then(e,t){return(async()=>{let e=``;for await(let t of this)e+=t;return e})().then(e,t)}},iw=class{_buffer;constructor(e){this._buffer=e}[Symbol.asyncIterator](){let e=this._buffer;async function*t(){for await(let t of e.iterate())if(t.event===`usage`){let e=QC(t.usage);e&&(yield e)}else if(t.event===`message-start`&&t.usage){let e=QC(t.usage);e&&(yield e)}else if(t.event===`message-finish`&&t.usage){let e=QC(t.usage);e&&(yield e)}}return t()}then(e,t){return(async()=>{let e;for await(let t of this)e=t;return e})().then(e,t)}},aw=class{_buffer;constructor(e){this._buffer=new qC,this._consume(e)}async _consume(e){try{for await(let t of e)this._buffer.push(t);this._buffer.finish()}catch(e){this._buffer.setError(e instanceof Error?e:Error(String(e)))}}[Symbol.asyncIterator](){return this._buffer.iterate()}get text(){return new tw(this._buffer)}get toolCalls(){return new nw(this._buffer)}get reasoning(){return new rw(this._buffer)}get usage(){return new iw(this._buffer)}get output(){return this._assembleMessage()}then(e,t){return this._assembleMessage().then(e,t)}async _assembleMessage(){let e=[],t,n,r={},i;for await(let a of this._buffer.iterate())switch(a.event){case`message-start`:t=a.id??t,a.usage&&(n=QC(a.usage));break;case`content-block-start`:e[a.index]=a.content;break;case`content-block-delta`:{let t=e[a.index],n=YC(a);t&&n&&(e[a.index]=JC(t,n));break}case`content-block-finish`:e[a.index]=a.content;break;case`usage`:n=QC(a.usage);break;case`message-finish`:i=a.reason,a.usage&&(n=QC(a.usage)),a.responseMetadata&&(r={...r,...a.responseMetadata});break;default:break}let a=e.filter(e=>e!=null).map(ew);return new qt({id:t,content:a,usage_metadata:n,response_metadata:{...r,...i?{finish_reason:i}:{},output_version:`v1`}})}},ow=o({convertChunksToEvents:()=>pw,finalizeContentBlock:()=>gw}),sw={wav:`audio/wav`,mp3:`audio/mpeg`,flac:`audio/flac`,opus:`audio/opus`,aac:`audio/aac`,pcm16:`audio/pcm`},cw={png:`image/png`,jpeg:`image/jpeg`,jpg:`image/jpeg`,webp:`image/webp`,gif:`image/gif`};function lw(e){let t=0;for(let n of e.keys())n>=t&&(t=n+1);return t}function uw(e){let t=e.additional_kwargs;return typeof t==`object`&&t?t:{}}function dw(e){let t=uw(e).tool_outputs;if(!Array.isArray(t))return[];let n=[];for(let e of t){if(typeof e!=`object`||!e)continue;let t=e;if(t.type!==`image_generation_call`)continue;let r=typeof t.result==`string`?t.result:void 0,i=typeof t.url==`string`?t.url:void 0;if(r==null&&i==null)continue;let a=typeof t.output_format==`string`?t.output_format.toLowerCase():void 0,o=(a==null?void 0:cw[a])??`image/png`;n.push({type:`image`,...typeof t.id==`string`?{id:t.id}:{},...i==null?{}:{url:i},...r==null?{}:{data:r},mimeType:o})}return n}function fw(e){let t=uw(e).audio;if(typeof t!=`object`||!t)return;let n=t,r=typeof n.data==`string`?n.data:void 0,i=typeof n.url==`string`?n.url:void 0,a=typeof n.transcript==`string`?n.transcript:void 0;if(r==null&&i==null&&a==null)return;let o=typeof n.mime_type==`string`?n.mime_type:typeof n.mimeType==`string`?n.mimeType:void 0,s=typeof n.format==`string`?n.format.toLowerCase():void 0,c=o??(s==null?void 0:sw[s])??(r==null?`audio/pcm`:`audio/wav`);return{...typeof n.id==`string`?{id:n.id}:{},...r==null?{}:{data:r},...i==null?{}:{url:i},...a==null?{}:{transcript:a},mimeType:c}}async function*pw(e,t){let n=new Map,r=!1,i,a,o=new Set;for await(let s of e){t?.signal?.throwIfAborted();let e=s.message,c=!1;if(!r){r=!0;let t={event:`message-start`,id:e.id??void 0};Xt.isInstance(e)&&e.usage_metadata&&(t.usage=e.usage_metadata,i={...e.usage_metadata},c=!0),yield t}let l=e.content;if(typeof l==`string`){if(l!==``){if(!n.has(0)){let e={type:`text`,text:``};n.set(0,{type:`text`,accumulated:e}),yield{event:`content-block-start`,index:0,content:e}}let e=n.get(0);e.accumulated={...e.accumulated,text:(e.accumulated.text??``)+l},yield{event:`content-block-delta`,index:0,delta:{type:`text-delta`,text:l}}}}else if(Array.isArray(l))for(let e of l){let t=typeof e.index==`number`?e.index:n.size;if(!n.has(t))n.set(t,{type:e.type,accumulated:{...e}}),yield{event:`content-block-start`,index:t,content:{...e}};else{let r=n.get(t),i=hw(e);r.accumulated=mw(r.accumulated,i),yield{event:`content-block-delta`,index:t,delta:i}}}if(Xt.isInstance(e)&&e.tool_call_chunks&&e.tool_call_chunks.length>0)for(let t of e.tool_call_chunks){let e=typeof t.index==`number`?t.index:n.size;if(!n.has(e)){let r={type:`tool_call_chunk`,id:t.id,name:t.name,args:``,index:e};n.set(e,{type:`tool_call_chunk`,accumulated:r}),yield{event:`content-block-start`,index:e,content:r}}let r=n.get(e).accumulated;t.id!=null&&(r.id=t.id),t.name!=null&&(r.name=t.name),r.args=(r.args??``)+(t.args??``),yield{event:`content-block-delta`,index:e,delta:{type:`block-delta`,fields:{type:`tool_call_chunk`,...`id`in r&&r.id!=null?{id:r.id}:{},...`name`in r&&r.name!=null?{name:r.name}:{},args:r.args}}}}let u=fw(e);if(u!=null){if(a==null){let e=lw(n);a={index:e,id:u.id,mimeType:u.mimeType,transcript:``};let t={type:`audio`,...u.id==null?{}:{id:u.id},...u.url==null?{}:{url:u.url},data:``,mimeType:u.mimeType};n.set(e,{type:`audio`,accumulated:t}),yield{event:`content-block-start`,index:e,content:t}}let e=n.get(a.index);if(e!=null){let t=e.accumulated;u.id!=null&&a.id==null&&(a.id=u.id,t.id=u.id),u.transcript!=null&&(a.transcript+=u.transcript,t.transcript=a.transcript,yield{event:`content-block-delta`,index:a.index,delta:{type:`block-delta`,fields:{type:`audio`,transcript:a.transcript}}}),u.data!=null&&u.data.length>0&&(t.data=(t.data??``)+u.data,yield{event:`content-block-delta`,index:a.index,delta:{type:`data-delta`,data:u.data,encoding:`base64`}})}}for(let t of dw(e)){let e=t,r=e.id??e.url??(e.data==null?void 0:`${e.data.length}:${e.data.slice(0,32)}`);if(r!=null&&o.has(r))continue;r!=null&&o.add(r);let i=lw(n);n.set(i,{type:`image`,accumulated:t}),yield{event:`content-block-start`,index:i,content:t}}if(!c&&Xt.isInstance(e)&&e.usage_metadata){let t=e.usage_metadata;i=i?{input_tokens:i.input_tokens+t.input_tokens,output_tokens:i.output_tokens+t.output_tokens,total_tokens:i.total_tokens+t.total_tokens}:{...t},yield{event:`usage`,usage:{...i}}}}for(let[e,t]of n)yield{event:`content-block-finish`,index:e,content:gw(t.accumulated)};yield{event:`message-finish`,reason:`stop`,...i?{usage:i}:{}}}function mw(e,t){switch(t.type){case`text-delta`:return e.type===`text`?{...e,text:(e.text??``)+t.text}:e;case`reasoning-delta`:return e.type===`thinking`?{...e,thinking:(e.thinking??``)+t.reasoning}:e.type===`reasoning`?{...e,reasoning:(e.reasoning??``)+t.reasoning}:e;case`data-delta`:return{...e,data:(e.data??``)+t.data};case`block-delta`:return{...e,...t.fields};default:throw Error(`Unknown delta type: ${JSON.stringify(t)}`)}}function hw(e){if(e.type===`text`)return{type:`text-delta`,text:e.text};if(e.type===`reasoning`)return{type:`reasoning-delta`,reasoning:e.reasoning};if(e.type===`thinking`&&typeof e.thinking==`string`)return{type:`reasoning-delta`,reasoning:e.thinking};if(typeof e.data==`string`)return{type:`data-delta`,data:e.data,encoding:`base64`};if(typeof e.type==`string`)return{type:`block-delta`,fields:{...e}};throw Error(`Unsupported content block delta: ${JSON.stringify(e)}`)}function gw(e){if(e.type===`tool_call_chunk`){let t=e,n;try{n=JSON.parse(t.args??`{}`)}catch{return{type:`invalid_tool_call`,id:t.id,name:t.name,args:t.args,error:`Failed to parse tool call arguments as JSON`}}return{type:`tool_call`,id:t.id,name:t.name,args:n}}return e}var _w=e=>e();function vw(e){let t=e.constructor;return new t({...e,content:e.contentBlocks,response_metadata:{...e.response_metadata,output_version:`v1`}})}var yw=o({BaseChatModel:()=>xw,SimpleChatModel:()=>Sw});function bw(e){let t=[];for(let n of e){let e=n;if(Array.isArray(n.content))for(let t=0;t<n.content.length;t++){let r=n.content[t];(ve(r)||ye(r))&&e===n&&(e=new n.constructor({...e,content:[...n.content.slice(0,t),Se(r),...n.content.slice(t+1)]}))}t.push(e)}return t}var xw=class e extends uC{lc_namespace=[`langchain`,`chat_models`,this._llmType()];disableStreaming=!1;outputVersion;get callKeys(){return[...super.callKeys,`outputVersion`]}constructor(e){super(e),this.outputVersion=_w(()=>{let t=e.outputVersion??pr(`LC_OUTPUT_VERSION`);return t&&[`v0`,`v1`].includes(t)?t:`v0`})}_separateRunnableConfigFromCallOptionsCompat(e){let[t,n]=super._separateRunnableConfigFromCallOptions(e);return n.signal=t.signal,[t,n]}async invoke(t,n){let r=e._convertInputToPromptValue(t);return(await this.generatePrompt([r],n,n?.callbacks)).generations[0][0].message}async*_streamResponseChunks(e,t,n){throw Error(`Not implemented.`)}async*_streamChatModelEvents(e,t,n){yield*pw(this._streamResponseChunks(e,t,n),{signal:t.signal})}streamV2(t,n){let r=e._convertInputToPromptValue(t).toChatMessages(),[,i]=this._separateRunnableConfigFromCallOptionsCompat(n);return new aw(this._streamChatModelEvents(r,i))}async*_streamIterator(t,n){if(this._streamResponseChunks===e.prototype._streamResponseChunks||this.disableStreaming)yield this.invoke(t,n);else{let r=e._convertInputToPromptValue(t).toChatMessages(),[i,a]=this._separateRunnableConfigFromCallOptionsCompat(n),o={...i.metadata,...this.getLsParamsWithDefaults(a)},s=this.invocationParams(a),c=await Kc.configure(i.callbacks,this.callbacks,i.tags,this.tags,o,this.metadata,{verbose:this.verbose,tracerInheritableMetadata:this._filterInvocationParamsForTracing(s)}),l={options:a,invocation_params:s,batch_size:1},u=a.outputVersion??this.outputVersion,d=await c?.handleChatModelStart(this.toJSON(),[bw(r)],i.runId,void 0,l,void 0,void 0,i.runName),f,p;try{for await(let e of this._streamResponseChunks(r,a,d?.[0])){if(a.signal?.throwIfAborted(),e.message.id==null){let t=d?.at(0)?.runId;t!=null&&e.message._updateId(`run-${t}`)}e.message.response_metadata={...e.generationInfo,...e.message.response_metadata},u===`v1`?yield vw(e.message):yield e.message,f=f?f.concat(e):e,Yt(e.message)&&e.message.usage_metadata!==void 0&&(p={tokenUsage:{promptTokens:e.message.usage_metadata.input_tokens,completionTokens:e.message.usage_metadata.output_tokens,totalTokens:e.message.usage_metadata.total_tokens}})}a.signal?.throwIfAborted()}catch(e){throw await Promise.all((d??[]).map(t=>t?.handleLLMError(e))),e}await Promise.all((d??[]).map(e=>e?.handleLLMEnd({generations:[[f]],llmOutput:p})))}}getLsParams(e){let t=this.getName().startsWith(`Chat`)?this.getName().replace(`Chat`,``):this.getName();return{ls_model_type:`chat`,ls_stop:e.stop,ls_provider:t}}getLsParamsWithDefaults(e){return{...this.getLsParams(e),ls_integration:`langchain_chat_model`}}async _generateUncached(t,n,r,i){let a=t.map(e=>e.map(yn)),o;if(i!==void 0&&i.length===a.length)o=i;else{let e={...r.metadata,...this.getLsParamsWithDefaults(n)},t=this.invocationParams(n),i=await Kc.configure(r.callbacks,this.callbacks,r.tags,this.tags,e,this.metadata,{verbose:this.verbose,tracerInheritableMetadata:this._filterInvocationParamsForTracing(t)}),s={options:n,invocation_params:t,batch_size:1};o=await i?.handleChatModelStart(this.toJSON(),a.map(bw),r.runId,void 0,s,void 0,void 0,r.runName)}let s=n.outputVersion??this.outputVersion,c=[],l=[],u=!!o?.[0].handlers.find(_r),d=!!o?.[0].handlers.find(gr);if(u&&!this.disableStreaming&&a.length===1&&(this._streamChatModelEvents!==e.prototype._streamChatModelEvents||this._streamResponseChunks!==e.prototype._streamResponseChunks))try{let e=!1,t=o?.[0],r=this._streamChatModelEvents(a[0],n),i=await new aw({async*[Symbol.asyncIterator](){for await(let i of r){n.signal?.throwIfAborted(),e=!0;let r=i.event===`message-start`&&i.id==null&&t?.runId!=null?{...i,id:`run-${t.runId}`}:i;await t?.handleChatModelStreamEvent(r),yield r}}});if(n.signal?.throwIfAborted(),!e)throw Error(`Received empty response from chat model call.`);if(i.id==null){let e=o?.at(0)?.runId;e!=null&&i._updateId(`run-${e}`)}let s={text:i.text,message:i};c.push([s]);let l=i.usage_metadata===void 0?void 0:{tokenUsage:{promptTokens:i.usage_metadata.input_tokens,completionTokens:i.usage_metadata.output_tokens,totalTokens:i.usage_metadata.total_tokens}};await o?.[0].handleLLMEnd({generations:c,llmOutput:l})}catch(e){throw await o?.[0].handleLLMError(e),e}else if(d&&!this.disableStreaming&&a.length===1&&this._streamResponseChunks!==e.prototype._streamResponseChunks)try{let e=await this._streamResponseChunks(a[0],n,o?.[0]),t,r;for await(let i of e){if(n.signal?.aborted){let e=t?.message;throw new p(`Model invocation was aborted.`,e)}if(i.message.id==null){let e=o?.at(0)?.runId;e!=null&&i.message._updateId(`run-${e}`)}t=t===void 0?i:fl(t,i),Yt(i.message)&&i.message.usage_metadata!==void 0&&(r={tokenUsage:{promptTokens:i.message.usage_metadata.input_tokens,completionTokens:i.message.usage_metadata.output_tokens,totalTokens:i.message.usage_metadata.total_tokens}})}if(n.signal?.aborted){let e=t?.message;throw new p(`Model invocation was aborted.`,e)}if(t===void 0)throw Error(`Received empty response from chat model call.`);c.push([t]),await o?.[0].handleLLMEnd({generations:c,llmOutput:r})}catch(e){throw await o?.[0].handleLLMError(e),e}else{let e=await Promise.allSettled(a.map(async(e,t)=>{let r=await this._generate(e,{...n,promptIndex:t},o?.[t]);if(s===`v1`)for(let e of r.generations)e.message=vw(e.message);return r}));await Promise.all(e.map(async(e,t)=>{if(e.status===`fulfilled`){let n=e.value;for(let e of n.generations){if(e.message.id==null){let t=o?.at(0)?.runId;t!=null&&e.message._updateId(`run-${t}`)}e.message.response_metadata={...e.generationInfo,...e.message.response_metadata}}return n.generations.length===1&&(n.generations[0].message.response_metadata={...n.llmOutput,...n.generations[0].message.response_metadata}),c[t]=n.generations,l[t]=n.llmOutput,o?.[t]?.handleLLMEnd({generations:[n.generations],llmOutput:n.llmOutput})}else return await o?.[t]?.handleLLMError(e.reason),Promise.reject(e.reason)}))}let f={generations:c,llmOutput:l.length?this._combineLLMOutput?.(...l):void 0};return Object.defineProperty(f,Jl,{value:o?{runIds:o?.map(e=>e.runId)}:void 0,configurable:!0}),f}async _generateCached({messages:t,cache:n,llmStringKey:r,parsedOptions:i,handledOptions:a}){let o=t.map(e=>e.map(yn)),s={...a.metadata,...this.getLsParamsWithDefaults(i)},c=this.invocationParams(i),l=await Kc.configure(a.callbacks,this.callbacks,a.tags,this.tags,s,this.metadata,{verbose:this.verbose,tracerInheritableMetadata:this._filterInvocationParamsForTracing(c)}),u={options:i,invocation_params:c,batch_size:1},d=await l?.handleChatModelStart(this.toJSON(),o.map(bw),a.runId,void 0,u,void 0,void 0,a.runName),f=[],p=(await Promise.allSettled(o.map(async(t,i)=>{let a=e._convertInputToPromptValue(t).toString(),o=await n.lookup(a,r);return o??f.push(i),o}))).map((e,t)=>({result:e,runManager:d?.[t]})).filter(({result:e})=>e.status===`fulfilled`&&e.value!=null||e.status===`rejected`),m=i.outputVersion??this.outputVersion,h=[];await Promise.all(p.map(async({result:e,runManager:t},n)=>{if(e.status===`fulfilled`){let r=e.value;return h[n]=r.map(e=>(`message`in e&&pt(e.message)&&Jt(e.message)&&(e.message.usage_metadata={input_tokens:0,output_tokens:0,total_tokens:0},m===`v1`&&(e.message=vw(e.message))),e.generationInfo={...e.generationInfo,tokenUsage:{}},e)),r.length&&await t?.handleLLMNewToken(r[0].text),t?.handleLLMEnd({generations:[r]},void 0,void 0,void 0,{cached:!0})}else return await t?.handleLLMError(e.reason,void 0,void 0,void 0,{cached:!0}),Promise.reject(e.reason)}));let g={generations:h,missingPromptIndices:f,startedRunManagers:d};return Object.defineProperty(g,Jl,{value:d?{runIds:d?.map(e=>e.runId)}:void 0,configurable:!0}),g}async generate(t,n,r){let i;i=Array.isArray(n)?{stop:n}:n;let a=t.map(e=>e.map(yn)),[o,s]=this._separateRunnableConfigFromCallOptionsCompat(i);if(o.callbacks=o.callbacks??r,!this.cache)return this._generateUncached(a,s,o);let{cache:c}=this,l=this._getSerializedCacheKeyParametersForCall(s),{generations:u,missingPromptIndices:d,startedRunManagers:f}=await this._generateCached({messages:a,cache:c,llmStringKey:l,parsedOptions:s,handledOptions:o}),p={};if(d.length>0){let t=await this._generateUncached(d.map(e=>a[e]),s,o,f===void 0?void 0:d.map(e=>f?.[e]));await Promise.all(t.generations.map(async(t,n)=>{let r=d[n];u[r]=t;let i=e._convertInputToPromptValue(a[r]).toString();return c.update(i,l,t)})),p=t.llmOutput??{}}return{generations:u,llmOutput:p}}invocationParams(e){return{}}_modelType(){return`base_chat_model`}async generatePrompt(e,t,n){let r=e.map(e=>e.toChatMessages());return this.generate(r,t,n)}withStructuredOutput(e,t){if(typeof this.bindTools!=`function`)throw Error(`Chat model must implement ".bindTools()" to use withStructuredOutput.`);if(t?.strict)throw Error(`"strict" mode is not supported for this model by default.`);let n=e,r=t?.name,i=Bm(n)??`A function available to call.`,a=t?.method,o=t?.includeRaw;if(a===`jsonMode`)throw Error(`Base withStructuredOutput implementation only supports "functionCalling" as a method.`);let s=r??`extract`;!Mm(n)&&!$_(n)&&`name`in n&&(s=n.name);let c=Mm(n)||$_(n)?Bv(n):n,l=[{type:`function`,function:{name:s,description:i,parameters:c}}];return GC(this.bindTools(l),dy.from(e=>{if(!Xt.isInstance(e))throw Error(`Input is not an AIMessageChunk.`);if(!e.tool_calls||e.tool_calls.length===0)throw Error(`No tool calls found in the response.`);let t=e.tool_calls.find(e=>e.name===s);if(!t)throw Error(`No tool call found with name ${s}.`);return t.args}),o,o?`StructuredOutputRunnable`:`StructuredOutput`)}},Sw=class extends xw{async _generate(e,t,n){let r=new qt(await this._call(e,t,n));if(typeof r.content!=`string`)throw Error(`Cannot generate with a simple chat model when output is not a string.`);return{generations:[{text:r.content,message:r}]}}},Cw=o({}),ww=o({BaseLLM:()=>Tw,LLM:()=>Ew}),Tw=class e extends uC{lc_namespace=[`langchain`,`llms`,this._llmType()];async invoke(t,n){let r=e._convertInputToPromptValue(t);return(await this.generatePrompt([r],n,n?.callbacks)).generations[0][0].text}async*_streamResponseChunks(e,t,n){throw Error(`Not implemented.`)}_separateRunnableConfigFromCallOptionsCompat(e){let[t,n]=super._separateRunnableConfigFromCallOptions(e);return n.signal=t.signal,[t,n]}async*_streamIterator(t,n){if(this._streamResponseChunks===e.prototype._streamResponseChunks)yield this.invoke(t,n);else{let r=e._convertInputToPromptValue(t),[i,a]=this._separateRunnableConfigFromCallOptionsCompat(n),o=this.invocationParams(a),s=await Kc.configure(i.callbacks,this.callbacks,i.tags,this.tags,i.metadata,this.metadata,{verbose:this.verbose,tracerInheritableMetadata:this._filterInvocationParamsForTracing(o)}),c={options:a,invocation_params:o,batch_size:1},l=await s?.handleLLMStart(this.toJSON(),[r.toString()],i.runId,void 0,c,void 0,void 0,i.runName),u=new Yl({text:``});try{for await(let e of this._streamResponseChunks(r.toString(),a,l?.[0]))u=u?u.concat(e):e,typeof e.text==`string`&&(yield e.text)}catch(e){throw await Promise.all((l??[]).map(t=>t?.handleLLMError(e))),e}await Promise.all((l??[]).map(e=>e?.handleLLMEnd({generations:[[u]]})))}}async generatePrompt(e,t,n){let r=e.map(e=>e.toString());return this.generate(r,t,n)}invocationParams(e){return{}}_flattenLLMResult(e){let t=[];for(let n=0;n<e.generations.length;n+=1){let r=e.generations[n];if(n===0)t.push({generations:[r],llmOutput:e.llmOutput});else{let n=e.llmOutput?{...e.llmOutput,tokenUsage:{}}:void 0;t.push({generations:[r],llmOutput:n})}}return t}async _generateUncached(t,n,r,i){let a;if(i!==void 0&&i.length===t.length)a=i;else{let e=this.invocationParams(n),i=await Kc.configure(r.callbacks,this.callbacks,r.tags,this.tags,r.metadata,this.metadata,{verbose:this.verbose,tracerInheritableMetadata:this._filterInvocationParamsForTracing(e)}),o={options:n,invocation_params:e,batch_size:t.length};a=await i?.handleLLMStart(this.toJSON(),t,r.runId,void 0,o,void 0,void 0,r?.runName)}let o=!!a?.[0].handlers.find(gr),s;if(o&&t.length===1&&this._streamResponseChunks!==e.prototype._streamResponseChunks)try{let e=await this._streamResponseChunks(t[0],n,a?.[0]),r;for await(let t of e)r=r===void 0?t:fl(r,t);if(r===void 0)throw Error(`Received empty response from chat model call.`);s={generations:[[r]],llmOutput:{}},await a?.[0].handleLLMEnd(s)}catch(e){throw await a?.[0].handleLLMError(e),e}else{try{s=await this._generate(t,n,a?.[0])}catch(e){throw await Promise.all((a??[]).map(t=>t?.handleLLMError(e))),e}let e=this._flattenLLMResult(s);await Promise.all((a??[]).map((t,n)=>t?.handleLLMEnd(e[n])))}let c=a?.map(e=>e.runId)||void 0;return Object.defineProperty(s,Jl,{value:c?{runIds:c}:void 0,configurable:!0}),s}async _generateCached({prompts:e,cache:t,llmStringKey:n,parsedOptions:r,handledOptions:i,runId:a}){let o=this.invocationParams(r),s=await Kc.configure(i.callbacks,this.callbacks,i.tags,this.tags,i.metadata,this.metadata,{verbose:this.verbose,tracerInheritableMetadata:this._filterInvocationParamsForTracing(o)}),c={options:r,invocation_params:o,batch_size:e.length},l=await s?.handleLLMStart(this.toJSON(),e,a,void 0,c,void 0,void 0,i?.runName),u=[],d=(await Promise.allSettled(e.map(async(e,r)=>{let i=await t.lookup(e,n);return i??u.push(r),i}))).map((e,t)=>({result:e,runManager:l?.[t]})).filter(({result:e})=>e.status===`fulfilled`&&e.value!=null||e.status===`rejected`),f=[];await Promise.all(d.map(async({result:e,runManager:t},n)=>{if(e.status===`fulfilled`){let r=e.value;return f[n]=r.map(e=>(e.generationInfo={...e.generationInfo,tokenUsage:{}},e)),r.length&&await t?.handleLLMNewToken(r[0].text),t?.handleLLMEnd({generations:[r]},void 0,void 0,void 0,{cached:!0})}else return await t?.handleLLMError(e.reason,void 0,void 0,void 0,{cached:!0}),Promise.reject(e.reason)}));let p={generations:f,missingPromptIndices:u,startedRunManagers:l};return Object.defineProperty(p,Jl,{value:l?{runIds:l?.map(e=>e.runId)}:void 0,configurable:!0}),p}async generate(e,t,n){if(!Array.isArray(e))throw Error(`Argument 'prompts' is expected to be a string[]`);let r;r=Array.isArray(t)?{stop:t}:t;let[i,a]=this._separateRunnableConfigFromCallOptionsCompat(r);if(i.callbacks=i.callbacks??n,!this.cache)return this._generateUncached(e,a,i);let{cache:o}=this,s=this._getSerializedCacheKeyParametersForCall(a),{generations:c,missingPromptIndices:l,startedRunManagers:u}=await this._generateCached({prompts:e,cache:o,llmStringKey:s,parsedOptions:a,handledOptions:i,runId:i.runId}),d={};if(l.length>0){let t=await this._generateUncached(l.map(t=>e[t]),a,i,u===void 0?void 0:l.map(e=>u?.[e]));await Promise.all(t.generations.map(async(t,n)=>{let r=l[n];return c[r]=t,o.update(e[r],s,t)})),d=t.llmOutput??{}}return{generations:c,llmOutput:d}}_identifyingParams(){return{}}_modelType(){return`base_llm`}},Ew=class extends Tw{async _generate(e,t,n){return{generations:await Promise.all(e.map((e,r)=>this._call(e,{...t,promptIndex:r},n).then(e=>[{text:e}])))}}},Dw=o({}),Ow=o({BaseMemory:()=>kw,getInputValue:()=>jw,getOutputValue:()=>Mw,getPromptInputKey:()=>Nw}),kw=class{},Aw=(e,t)=>{if(t!==void 0)return e[t];let n=Object.keys(e);if(n.length===1)return e[n[0]]},jw=(e,t)=>{let n=Aw(e,t);if(!n)throw Error(`input values have ${Object.keys(e).length} keys, you must specify an input key or pass only 1 key as input`);return n},Mw=(e,t)=>{let n=Aw(e,t);if(!n&&n!==``)throw Error(`output values have ${Object.keys(e).length} keys, you must specify an output key or pass only 1 key as output`);return n};function Nw(e,t){let n=Object.keys(e).filter(e=>!t.includes(e)&&e!==`stop`);if(n.length!==1)throw Error(`One input key expected, but got ${n.length}`);return n[0]}var Pw=class extends fC{static lc_name(){return`OutputFunctionsParser`}lc_namespace=[`langchain`,`output_parsers`,`openai_functions`];lc_serializable=!0;argsOnly=!0;constructor(e){super(),this.argsOnly=e?.argsOnly??this.argsOnly}async parseResult(e){if(`message`in e[0]){let t=e[0].message.additional_kwargs.function_call;if(!t)throw Error(`No function_call in message ${JSON.stringify(e)}`);if(!t.arguments)throw Error(`No arguments in function_call ${JSON.stringify(e)}`);return this.argsOnly?t.arguments:JSON.stringify(t)}else throw Error(`No message in generations ${JSON.stringify(e)}`)}},Fw=class extends gC{static lc_name(){return`JsonOutputFunctionsParser`}lc_namespace=[`langchain`,`output_parsers`,`openai_functions`];lc_serializable=!0;outputParser;argsOnly=!0;constructor(e){super(e),this.argsOnly=e?.argsOnly??this.argsOnly,this.outputParser=new Pw(e)}_diff(e,t){if(t)return Rl(e??{},t)}async parsePartialResult(e){let t=e[0];if(!t.message)return;let{message:n}=t,r=n.additional_kwargs.function_call;if(r)return this.argsOnly?b(r.arguments):{...r,arguments:b(r.arguments)}}async parseResult(e){let t=await this.outputParser.parseResult(e);if(!t)throw Error(`No result from "OutputFunctionsParser" ${JSON.stringify(e)}`);return this.parse(t)}async parse(e){let t=JSON.parse(e);return this.argsOnly||(t.arguments=JSON.parse(t.arguments)),t}getFormatInstructions(){return``}},Iw=class extends fC{static lc_name(){return`JsonKeyOutputFunctionsParser`}lc_namespace=[`langchain`,`output_parsers`,`openai_functions`];lc_serializable=!0;outputParser=new Fw;attrName;get lc_aliases(){return{attrName:`key_name`}}constructor(e){super(e),this.attrName=e.attrName}async parseResult(e){return(await this.outputParser.parseResult(e))[this.attrName]}},Lw=o({JsonKeyOutputFunctionsParser:()=>Iw,JsonOutputFunctionsParser:()=>Fw,OutputFunctionsParser:()=>Pw}),Rw=o({JsonOutputKeyToolsParser:()=>VC,JsonOutputToolsParser:()=>BC,convertLangChainToolCallToOpenAI:()=>RC,makeInvalidToolCall:()=>zC,parseToolCall:()=>LC}),zw=class extends ry{lc_serializable=!0;lc_namespace=[`langchain_core`,`prompts`,this._getPromptType()];get lc_attributes(){return{partialVariables:void 0}}inputVariables;outputParser;partialVariables;metadata;tags;constructor(e){super(e);let{inputVariables:t}=e;if(t.includes(`stop`))throw Error(`Cannot have an input variable named 'stop', as it is used internally, please rename.`);Object.assign(this,e)}async mergePartialAndUserVariables(e){let t=this.partialVariables??{},n={};for(let[e,r]of Object.entries(t))typeof r==`string`?n[e]=r:n[e]=await r();return{...n,...e}}async invoke(e,t){let n={...this.metadata,...t?.metadata},r=[...this.tags??[],...t?.tags??[]];return this._callWithConfig(e=>this.formatPromptValue(e),e,{...t,tags:r,metadata:n,runType:`prompt`})}},Bw=class extends zw{async formatPromptValue(e){return new RS(await this.format(e))}},Vw=Object.prototype.toString,Hw=Array.isArray||function(e){return Vw.call(e)===`[object Array]`};function Uw(e){return typeof e==`function`}function Ww(e){return Hw(e)?`array`:typeof e}function Gw(e){return e.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,`\\$&`)}function Kw(e,t){return typeof e==`object`&&!!e&&t in e}function qw(e,t){return e!=null&&typeof e!=`object`&&e.hasOwnProperty&&e.hasOwnProperty(t)}var Jw=RegExp.prototype.test;function Yw(e,t){return Jw.call(e,t)}var Xw=/\S/;function Zw(e){return!Yw(Xw,e)}var Qw={"&":`&amp;`,"<":`&lt;`,">":`&gt;`,'"':`&quot;`,"'":`&#39;`,"/":`&#x2F;`,"`":`&#x60;`,"=":`&#x3D;`};function $w(e){return String(e).replace(/[&<>"'`=\/]/g,function(e){return Qw[e]})}var eT=/\s*/,tT=/\s+/,nT=/\s*=/,rT=/\s*\}/,iT=/#|\^|\/|>|\{|&|=|!/;function aT(e,t){if(!e)return[];var n=!1,r=[],i=[],a=[],o=!1,s=!1,c=``,l=0;function u(){if(o&&!s)for(;a.length;)delete i[a.pop()];else a=[];o=!1,s=!1}var d,f,p;function m(e){if(typeof e==`string`&&(e=e.split(tT,2)),!Hw(e)||e.length!==2)throw Error(`Invalid tags: `+e);d=RegExp(Gw(e[0])+`\\s*`),f=RegExp(`\\s*`+Gw(e[1])),p=RegExp(`\\s*`+Gw(`}`+e[1]))}m(t||dT.tags);for(var h=new cT(e),g,_,v,y,b,ee;!h.eos();){if(g=h.pos,v=h.scanUntil(d),v)for(var x=0,te=v.length;x<te;++x)y=v.charAt(x),Zw(y)?(a.push(i.length),c+=y):(s=!0,n=!0,c+=` `),i.push([`text`,y,g,g+1]),g+=1,y===`
126
- `&&(u(),c=``,l=0,n=!1);if(!h.scan(d))break;if(o=!0,_=h.scan(iT)||`name`,h.scan(eT),_===`=`?(v=h.scanUntil(nT),h.scan(nT),h.scanUntil(f)):_===`{`?(v=h.scanUntil(p),h.scan(rT),h.scanUntil(f),_=`&`):v=h.scanUntil(f),!h.scan(f))throw Error(`Unclosed tag at `+h.pos);if(b=_==`>`?[_,v,g,h.pos,c,l,n]:[_,v,g,h.pos],l++,i.push(b),_===`#`||_===`^`)r.push(b);else if(_===`/`){if(ee=r.pop(),!ee)throw Error(`Unopened section "`+v+`" at `+g);if(ee[1]!==v)throw Error(`Unclosed section "`+ee[1]+`" at `+g)}else _===`name`||_===`{`||_===`&`?s=!0:_===`=`&&m(v)}if(u(),ee=r.pop(),ee)throw Error(`Unclosed section "`+ee[1]+`" at `+h.pos);return sT(oT(i))}function oT(e){for(var t=[],n,r,i=0,a=e.length;i<a;++i)n=e[i],n&&(n[0]===`text`&&r&&r[0]===`text`?(r[1]+=n[1],r[3]=n[3]):(t.push(n),r=n));return t}function sT(e){for(var t=[],n=t,r=[],i,a,o=0,s=e.length;o<s;++o)switch(i=e[o],i[0]){case`#`:case`^`:n.push(i),r.push(i),n=i[4]=[];break;case`/`:a=r.pop(),a[5]=i[2],n=r.length>0?r[r.length-1][4]:t;break;default:n.push(i)}return t}function cT(e){this.string=e,this.tail=e,this.pos=0}cT.prototype.eos=function(){return this.tail===``},cT.prototype.scan=function(e){var t=this.tail.match(e);if(!t||t.index!==0)return``;var n=t[0];return this.tail=this.tail.substring(n.length),this.pos+=n.length,n},cT.prototype.scanUntil=function(e){var t=this.tail.search(e),n;switch(t){case-1:n=this.tail,this.tail=``;break;case 0:n=``;break;default:n=this.tail.substring(0,t),this.tail=this.tail.substring(t)}return this.pos+=n.length,n};function lT(e,t){this.view=e,this.cache={".":this.view},this.parent=t}lT.prototype.push=function(e){return new lT(e,this)},lT.prototype.lookup=function(e){var t=this.cache,n;if(t.hasOwnProperty(e))n=t[e];else{for(var r=this,i,a,o,s=!1;r;){if(e.indexOf(`.`)>0)for(i=r.view,a=e.split(`.`),o=0;i!=null&&o<a.length;)o===a.length-1&&(s=Kw(i,a[o])||qw(i,a[o])),i=i[a[o++]];else i=r.view[e],s=Kw(r.view,e);if(s){n=i;break}r=r.parent}t[e]=n}return Uw(n)&&(n=n.call(this.view)),n};function uT(){this.templateCache={_cache:{},set:function(e,t){this._cache[e]=t},get:function(e){return this._cache[e]},clear:function(){this._cache={}}}}uT.prototype.clearCache=function(){this.templateCache!==void 0&&this.templateCache.clear()},uT.prototype.parse=function(e,t){var n=this.templateCache,r=e+`:`+(t||dT.tags).join(`:`),i=n!==void 0,a=i?n.get(r):void 0;return a??(a=aT(e,t),i&&n.set(r,a)),a},uT.prototype.render=function(e,t,n,r){var i=this.getConfigTags(r),a=this.parse(e,i),o=t instanceof lT?t:new lT(t,void 0);return this.renderTokens(a,o,n,e,r)},uT.prototype.renderTokens=function(e,t,n,r,i){for(var a=``,o,s,c,l=0,u=e.length;l<u;++l)c=void 0,o=e[l],s=o[0],s===`#`?c=this.renderSection(o,t,n,r,i):s===`^`?c=this.renderInverted(o,t,n,r,i):s===`>`?c=this.renderPartial(o,t,n,i):s===`&`?c=this.unescapedValue(o,t):s===`name`?c=this.escapedValue(o,t,i):s===`text`&&(c=this.rawValue(o)),c!==void 0&&(a+=c);return a},uT.prototype.renderSection=function(e,t,n,r,i){var a=this,o=``,s=t.lookup(e[1]);function c(e){return a.render(e,t,n,i)}if(s){if(Hw(s))for(var l=0,u=s.length;l<u;++l)o+=this.renderTokens(e[4],t.push(s[l]),n,r,i);else if(typeof s==`object`||typeof s==`string`||typeof s==`number`)o+=this.renderTokens(e[4],t.push(s),n,r,i);else if(Uw(s)){if(typeof r!=`string`)throw Error(`Cannot use higher-order sections without the original template`);s=s.call(t.view,r.slice(e[3],e[5]),c),s!=null&&(o+=s)}else o+=this.renderTokens(e[4],t,n,r,i);return o}},uT.prototype.renderInverted=function(e,t,n,r,i){var a=t.lookup(e[1]);if(!a||Hw(a)&&a.length===0)return this.renderTokens(e[4],t,n,r,i)},uT.prototype.indentPartial=function(e,t,n){for(var r=t.replace(/[^ \t]/g,``),i=e.split(`
127
- `),a=0;a<i.length;a++)i[a].length&&(a>0||!n)&&(i[a]=r+i[a]);return i.join(`
128
- `)},uT.prototype.renderPartial=function(e,t,n,r){if(n){var i=this.getConfigTags(r),a=Uw(n)?n(e[1]):n[e[1]];if(a!=null){var o=e[6],s=e[5],c=e[4],l=a;s==0&&c&&(l=this.indentPartial(a,c,o));var u=this.parse(l,i);return this.renderTokens(u,t,n,l,r)}}},uT.prototype.unescapedValue=function(e,t){var n=t.lookup(e[1]);if(n!=null)return n},uT.prototype.escapedValue=function(e,t,n){var r=this.getConfigEscape(n)||dT.escape,i=t.lookup(e[1]);if(i!=null)return typeof i==`number`&&r===dT.escape?String(i):r(i)},uT.prototype.rawValue=function(e){return e[1]},uT.prototype.getConfigTags=function(e){if(Hw(e))return e;if(e&&typeof e==`object`)return e.tags},uT.prototype.getConfigEscape=function(e){if(e&&typeof e==`object`&&!Hw(e))return e.escape};var dT={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(e){fT.templateCache=e},get templateCache(){return fT.templateCache}},fT=new uT;dT.clearCache=function(){return fT.clearCache()},dT.parse=function(e,t){return fT.parse(e,t)},dT.render=function(e,t,n,r){if(typeof e!=`string`)throw TypeError(`Invalid template! Template should be a "string" but "`+Ww(e)+`" was given as the first argument for mustache#render(template, view, partials)`);return fT.render(e,t,n,r)},dT.escape=$w,dT.Scanner=cT,dT.Context=lT,dT.Writer=uT;function pT(){dT.escape=e=>e}var mT=e=>{let t=e.split(``),n=[],r=(e,n)=>{for(let r=n;r<t.length;r+=1)if(e.includes(t[r]))return r;return-1},i=0;for(;i<t.length;)if(t[i]===`{`&&i+1<t.length&&t[i+1]===`{`)n.push({type:`literal`,text:`{`}),i+=2;else if(t[i]===`}`&&i+1<t.length&&t[i+1]===`}`)n.push({type:`literal`,text:`}`}),i+=2;else if(t[i]===`{`){let e=r(`}`,i);if(e<0)throw Error(`Unclosed '{' in template.`);n.push({type:`variable`,name:t.slice(i+1,e).join(``)}),i=e+1}else if(t[i]===`}`)throw Error(`Single '}' in template.`);else{let e=r(`{}`,i),a=(e<0?t.slice(i):t.slice(i,e)).join(``);n.push({type:`literal`,text:a}),i=e<0?t.length:e}return n},hT=(e,t=[])=>{let n=[];for(let r of e)if(r[0]===`name`){let e=r[1].includes(`.`)?r[1].split(`.`)[0]:r[1];n.push({type:`variable`,name:e})}else if([`#`,`&`,`^`,`>`].includes(r[0])){if(n.push({type:`variable`,name:r[1]}),r[0]===`#`&&r.length>4&&Array.isArray(r[4])){let e=[...t,r[1]],i=hT(r[4],e);n.push(...i)}}else n.push({type:`literal`,text:r[1]});return n},gT=e=>(pT(),hT(dT.parse(e))),_T=(e,t)=>mT(e).reduce((e,n)=>{if(n.type===`variable`){if(n.name in t)return e+(typeof t[n.name]==`string`?t[n.name]:JSON.stringify(t[n.name]));throw Error(`(f-string) Missing value for input ${n.name}`)}return e+n.text},``),vT=(e,t)=>(pT(),dT.render(e,t)),yT={"f-string":_T,mustache:vT},bT={"f-string":mT,mustache:gT},xT=(e,t,n)=>{try{return yT[t](e,n)}catch(e){throw u(e,`INVALID_PROMPT_INPUT`)}},ST=(e,t)=>bT[t](e),CT=(e,t,n)=>{if(!(t in yT))throw Error(`Invalid template format. Got \`${t}\`;
129
- should be one of ${Object.keys(yT)}`);try{let r=Object.fromEntries(n.map(e=>[e,`foo`]));Array.isArray(e)?e.forEach(e=>{if(e.type===`text`&&`text`in e&&typeof e.text==`string`)xT(e.text,t,r);else if(e.type===`image_url`){if(typeof e.image_url==`string`)xT(e.image_url,t,r);else if(typeof e.image_url==`object`&&e.image_url!==null&&`url`in e.image_url&&typeof e.image_url.url==`string`){let n=e.image_url.url;xT(n,t,r)}}else throw Error(`Invalid message template received. ${JSON.stringify(e,null,2)}`)}):xT(e,t,r)}catch(e){throw Error(`Invalid prompt schema: ${e.message}`)}},wT=class e extends Bw{static lc_name(){return`PromptTemplate`}template;templateFormat=`f-string`;validateTemplate=!0;additionalContentFields;constructor(e){if(super(e),e.templateFormat===`mustache`&&e.validateTemplate===void 0&&(this.validateTemplate=!1),Object.assign(this,e),this.validateTemplate){if(this.templateFormat===`mustache`)throw Error(`Mustache templates cannot be validated.`);let e=this.inputVariables;this.partialVariables&&(e=e.concat(Object.keys(this.partialVariables))),CT(this.template,this.templateFormat,e)}}_getPromptType(){return`prompt`}async format(e){let t=await this.mergePartialAndUserVariables(e);return xT(this.template,this.templateFormat,t)}static fromExamples(t,n,r,i=`
130
-
131
- `,a=``){return new e({inputVariables:r,template:[a,...t,n].join(i)})}static fromTemplate(t,n){let{templateFormat:r=`f-string`,...i}=n??{},a=new Set;return ST(t,r).forEach(e=>{e.type===`variable`&&a.add(e.name)}),new e({inputVariables:[...a],templateFormat:r,template:t,...i})}async partial(t){let n=this.inputVariables.filter(e=>!(e in t)),r={...this.partialVariables??{},...t};return new e({...this,inputVariables:n,partialVariables:r})}serialize(){if(this.outputParser!==void 0)throw 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(t){if(!t.template)throw Error(`Prompt template must have a template`);return new e({inputVariables:t.input_variables,template:t.template,templateFormat:t.template_format})}},TT=class e extends zw{static lc_name(){return`ImagePromptTemplate`}lc_namespace=[`langchain_core`,`prompts`,`image`];template;templateFormat=`f-string`;validateTemplate=!0;additionalContentFields;constructor(e){if(super(e),this.template=e.template,this.templateFormat=e.templateFormat??this.templateFormat,this.validateTemplate=e.validateTemplate??this.validateTemplate,this.additionalContentFields=e.additionalContentFields,this.validateTemplate){let e=this.inputVariables;this.partialVariables&&(e=e.concat(Object.keys(this.partialVariables))),CT([{type:`image_url`,image_url:this.template}],this.templateFormat,e)}}_getPromptType(){return`prompt`}async partial(t){let n=this.inputVariables.filter(e=>!(e in t)),r={...this.partialVariables??{},...t};return new e({...this,inputVariables:n,partialVariables:r})}async format(e){let t={};for(let[n,r]of Object.entries(this.template))typeof r==`string`?t[n]=xT(r,this.templateFormat,e):t[n]=r;let n=e.url||t.url,r=e.detail||t.detail;if(!n)throw Error(`Must provide either an image URL.`);if(typeof n!=`string`)throw Error(`url must be a string.`);let i={url:n};return r&&(i.detail=r),i}async formatPromptValue(e){return new BS(await this.format(e))}},ET=class extends ry{lc_namespace=[`langchain_core`,`prompts`,`dict`];lc_serializable=!0;template;templateFormat;inputVariables;static lc_name(){return`DictPromptTemplate`}constructor(e){let t=e.templateFormat??`f-string`,n=DT(e.template,t);super({inputVariables:n,...e}),this.template=e.template,this.templateFormat=t,this.inputVariables=n}async format(e){return OT(this.template,e,this.templateFormat)}async invoke(e){return await this._callWithConfig(this.format.bind(this),e,{runType:`prompt`})}};function DT(e,t){let n=[];for(let r of Object.values(e))if(typeof r==`string`)ST(r,t).forEach(e=>{e.type===`variable`&&n.push(e.name)});else if(Array.isArray(r))for(let e of r)typeof e==`string`?ST(e,t).forEach(e=>{e.type===`variable`&&n.push(e.name)}):typeof e==`object`&&n.push(...DT(e,t));else typeof r==`object`&&r&&n.push(...DT(r,t));return Array.from(new Set(n))}function OT(e,t,n){let r={};for(let[i,a]of Object.entries(e))if(typeof a==`string`)r[i]=xT(a,n,t);else if(Array.isArray(a)){let e=[];for(let r of a)typeof r==`string`?e.push(xT(r,n,t)):typeof r==`object`&&e.push(OT(r,t,n));r[i]=e}else typeof a==`object`&&a?r[i]=OT(a,t,n):r[i]=a;return r}var kT=class extends ry{lc_namespace=[`langchain_core`,`prompts`,`chat`];lc_serializable=!0;async invoke(e,t){return this._callWithConfig(e=>this.formatMessages(e),e,{...t,runType:`prompt`})}},AT=class extends kT{static lc_name(){return`MessagesPlaceholder`}variableName;optional;constructor(e){typeof e==`string`&&(e={variableName:e}),super(e),this.variableName=e.variableName,this.optional=e.optional??!1}get inputVariables(){return[this.variableName]}async formatMessages(e){let t=e[this.variableName];if(this.optional&&!t)return[];if(!t){let e=Error(`Field "${this.variableName}" in prompt uses a MessagesPlaceholder, which expects an array of BaseMessages as an input value. Received: undefined`);throw e.name=`InputFormatError`,e}let n;try{n=Array.isArray(t)?t.map(yn):[yn(t)]}catch(e){let n=typeof t==`string`?t:JSON.stringify(t,null,2),r=Error([`Field "${this.variableName}" in prompt uses a MessagesPlaceholder, which expects an array of BaseMessages or coerceable values as input.`,`Received value: ${n}`,`Additional message: ${e.message}`].join(`
132
-
133
- `));throw r.name=`InputFormatError`,r.lc_error_code=e.lc_error_code,r}return n}},jT=class extends kT{prompt;constructor(e){`prompt`in e||(e={prompt:e}),super(e),this.prompt=e.prompt}get inputVariables(){return this.prompt.inputVariables}async formatMessages(e){return[await this.format(e)]}},MT=class extends zw{constructor(e){super(e)}async format(e){return(await this.formatPromptValue(e)).toString()}async formatPromptValue(e){return new zS(await this.formatMessages(e))}},NT=class extends jT{static lc_name(){return`ChatMessagePromptTemplate`}role;constructor(e,t){`prompt`in e||(e={prompt:e,role:t}),super(e),this.role=e.role}async format(e){return new Zt(await this.prompt.format(e),this.role)}static fromTemplate(e,t,n){return new this(wT.fromTemplate(e,{templateFormat:n?.templateFormat}),t)}};function PT(e){return typeof e!=`object`||!e||Array.isArray(e)?!1:Object.keys(e).length===1&&`text`in e&&typeof e.text==`string`}function FT(e){return typeof e!=`object`||!e||Array.isArray(e)?!1:`image_url`in e&&(typeof e.image_url==`string`||typeof e.image_url==`object`&&e.image_url!==null&&`url`in e.image_url&&typeof e.image_url.url==`string`)}var IT=class extends kT{lc_namespace=[`langchain_core`,`prompts`,`chat`];lc_serializable=!0;inputVariables=[];additionalOptions={};prompt;messageClass;static _messageClass(){throw Error(`Can not invoke _messageClass from inside _StringImageMessagePromptTemplate`)}chatMessageClass;constructor(e,t){if(`prompt`in e||(e={prompt:e}),super(e),this.prompt=e.prompt,Array.isArray(this.prompt)){let e=[];this.prompt.forEach(t=>{`inputVariables`in t&&(e=e.concat(t.inputVariables))}),this.inputVariables=e}else this.inputVariables=this.prompt.inputVariables;this.additionalOptions=t??this.additionalOptions}createMessage(e){let t=this.constructor;if(t._messageClass())return new(t._messageClass())({content:e});if(t.chatMessageClass){let n=t.chatMessageClass();return new n({content:e,role:this.getRoleFromMessageClass(n.lc_name())})}else throw 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 Error(`Invalid message class name`)}}static fromTemplate(e,t){if(typeof e==`string`)return new this(wT.fromTemplate(e,t));let n=[];for(let r of e)if(typeof r==`string`)n.push(wT.fromTemplate(r,t));else if(r!==null)if(PT(r)){let e=``;typeof r.text==`string`&&(e=r.text??``);let i={...t,additionalContentFields:r};n.push(wT.fromTemplate(e,i))}else if(FT(r)){let e=r.image_url??``,i,a=[];if(typeof e==`string`){let n;n=t?.templateFormat===`mustache`?gT(e):mT(e);let o=n.flatMap(e=>e.type===`variable`?[e.name]:[]);if((o?.length??0)>0){if(o.length>1)throw Error(`Only one format variable allowed per image template.\nGot: ${o}\nFrom: ${e}`);a=[o[0]]}else a=[];e={url:e},i=new TT({template:e,inputVariables:a,templateFormat:t?.templateFormat,additionalContentFields:r})}else if(typeof e==`object`){if(`url`in e){let n;n=t?.templateFormat===`mustache`?gT(e.url):mT(e.url),a=n.flatMap(e=>e.type===`variable`?[e.name]:[])}else a=[];i=new TT({template:e,inputVariables:a,templateFormat:t?.templateFormat,additionalContentFields:r})}else throw Error(`Invalid image template`);n.push(i)}else typeof r==`object`&&n.push(new ET({template:r,templateFormat:t?.templateFormat}));return new this({prompt:n,additionalOptions:t})}async format(e){if(this.prompt instanceof Bw){let t=await this.prompt.format(e);return this.createMessage(t)}else{let t=[];for(let n of this.prompt){let r={};if(!(`inputVariables`in n))throw Error(`Prompt ${n} does not have inputVariables defined.`);for(let t of n.inputVariables)r||={[t]:e[t]},r={...r,[t]:e[t]};if(n instanceof Bw){let e=await n.format(r),i;`additionalContentFields`in n&&(i=n.additionalContentFields),e!==``&&t.push({...i,type:`text`,text:e})}else if(n instanceof TT){let e=await n.format(r),i;`additionalContentFields`in n&&(i=n.additionalContentFields),t.push({...i,type:`image_url`,image_url:e})}else if(n instanceof ET){let e=await n.format(r),i;`additionalContentFields`in n&&(i=n.additionalContentFields),t.push({...i,...e})}}return this.createMessage(t)}}async formatMessages(e){return[await this.format(e)]}},LT=class extends IT{static _messageClass(){return on}static lc_name(){return`HumanMessagePromptTemplate`}},RT=class extends IT{static _messageClass(){return qt}static lc_name(){return`AIMessagePromptTemplate`}},zT=class extends IT{static _messageClass(){return dn}static lc_name(){return`SystemMessagePromptTemplate`}};function BT(e){return typeof e.formatMessages==`function`}function VT(e,t){if(BT(e)||pt(e))return e;if(Array.isArray(e)&&e[0]===`placeholder`){let n=e[1];if(t?.templateFormat===`mustache`&&typeof n==`string`&&n.slice(0,2)===`{{`&&n.slice(-2)===`}}`)return new AT({variableName:n.slice(2,-2),optional:!0});if(typeof n==`string`&&n[0]===`{`&&n[n.length-1]===`}`)return new AT({variableName:n.slice(1,-1),optional:!0});throw Error(`Invalid placeholder template for format ${t?.templateFormat??`"f-string"`}: "${e[1]}". Expected a variable name surrounded by ${t?.templateFormat===`mustache`?`double`:`single`} curly braces.`)}let n=yn(e),r;if(r=typeof n.content==`string`?n.content:n.content.map(e=>`text`in e?{...e,text:e.text}:`image_url`in e?{...e,image_url:e.image_url}:e),n._getType()===`human`)return LT.fromTemplate(r,t);if(n._getType()===`ai`)return RT.fromTemplate(r,t);if(n._getType()===`system`)return zT.fromTemplate(r,t);if(Zt.isInstance(n))return NT.fromTemplate(n.content,n.role,t);throw Error(`Could not coerce message prompt template from input. Received message type: "${n._getType()}".`)}function HT(e){return e.constructor.lc_name()===`MessagesPlaceholder`}var UT=class e extends MT{static lc_name(){return`ChatPromptTemplate`}get lc_aliases(){return{promptMessages:`messages`}}promptMessages;validateTemplate=!0;templateFormat=`f-string`;constructor(e){if(super(e),e.templateFormat===`mustache`&&e.validateTemplate===void 0&&(this.validateTemplate=!1),Object.assign(this,e),this.validateTemplate){let e=new Set;for(let t of this.promptMessages)if(!(t instanceof tt))for(let n of t.inputVariables)e.add(n);let t=this.inputVariables,n=new Set(this.partialVariables?t.concat(Object.keys(this.partialVariables)):t),r=new Set([...n].filter(t=>!e.has(t)));if(r.size>0)throw Error(`Input variables \`${[...r]}\` are not used in any of the prompt messages.`);let i=new Set([...e].filter(e=>!n.has(e)));if(i.size>0)throw Error(`Input variables \`${[...i]}\` are used in prompt messages but not in the prompt template.`)}}_getPromptType(){return`chat`}async _parseImagePrompts(e,t){return typeof e.content==`string`||(e.content=await Promise.all(e.content.map(async e=>{if(e.type!==`image_url`)return e;let n=``;typeof e.image_url==`string`?n=e.image_url:typeof e.image_url==`object`&&e.image_url!==null&&`url`in e.image_url&&typeof e.image_url.url==`string`&&(n=e.image_url.url);let r=await wT.fromTemplate(n,{templateFormat:this.templateFormat}).format(t);return typeof e.image_url==`object`&&e.image_url!==null&&`url`in e.image_url?e.image_url.url=r:e.image_url=r,e}))),e}async formatMessages(e){let t=await this.mergePartialAndUserVariables(e),n=[];for(let e of this.promptMessages)if(e instanceof tt)n.push(await this._parseImagePrompts(e,t));else{let r;r=this.templateFormat===`mustache`?{...t}:e.inputVariables.reduce((n,r)=>{if(!(r in t)&&!(HT(e)&&e.optional))throw u(Error(`Missing value for input variable \`${r.toString()}\``),`INVALID_PROMPT_INPUT`);return n[r]=t[r],n},{});let i=await e.formatMessages(r);n=n.concat(i)}return n}async partial(t){let n=this.inputVariables.filter(e=>!(e in t)),r={...this.partialVariables??{},...t};return new e({...this,inputVariables:n,partialVariables:r})}static fromTemplate(e,t){let n=new LT({prompt:wT.fromTemplate(e,t)});return this.fromMessages([n])}static fromMessages(t,n){let r=t.reduce((t,r)=>t.concat(r instanceof e?r.promptMessages:[VT(r,n)]),[]),i=t.reduce((t,n)=>n instanceof e?Object.assign(t,n.partialVariables):t,Object.create(null)),a=new Set;for(let e of r)if(!(e instanceof tt))for(let t of e.inputVariables)t in i||a.add(t);return new this({...n,inputVariables:[...a],promptMessages:r,partialVariables:i,templateFormat:n?.templateFormat})}},WT=class e extends Bw{lc_serializable=!1;examples;exampleSelector;examplePrompt;suffix=``;exampleSeparator=`
134
-
135
- `;prefix=``;templateFormat=`f-string`;validateTemplate=!0;constructor(e){if(super(e),Object.assign(this,e),this.examples!==void 0&&this.exampleSelector!==void 0)throw Error(`Only one of 'examples' and 'example_selector' should be provided`);if(this.examples===void 0&&this.exampleSelector===void 0)throw Error(`One of 'examples' and 'example_selector' should be provided`);if(this.validateTemplate){let e=this.inputVariables;this.partialVariables&&(e=e.concat(Object.keys(this.partialVariables))),CT(this.prefix+this.suffix,this.templateFormat,e)}}_getPromptType(){return`few_shot`}static lc_name(){return`FewShotPromptTemplate`}async getExamples(e){if(this.examples!==void 0)return this.examples;if(this.exampleSelector!==void 0)return this.exampleSelector.selectExamples(e);throw Error(`One of 'examples' and 'example_selector' should be provided`)}async partial(t){let n=this.inputVariables.filter(e=>!(e in t)),r={...this.partialVariables??{},...t};return new e({...this,inputVariables:n,partialVariables:r})}async format(e){let t=await this.mergePartialAndUserVariables(e),n=await this.getExamples(t),r=await Promise.all(n.map(e=>this.examplePrompt.format(e)));return xT([this.prefix,...r,this.suffix].join(this.exampleSeparator),this.templateFormat,t)}serialize(){if(this.exampleSelector||!this.examples)throw Error(`Serializing an example selector is not currently supported`);if(this.outputParser!==void 0)throw 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(t){let{example_prompt:n}=t;if(!n)throw Error(`Missing example prompt`);let r=await wT.deserialize(n),i;if(Array.isArray(t.examples))i=t.examples;else throw Error(`Invalid examples format. Only list or string are supported.`);return new e({inputVariables:t.input_variables,examplePrompt:r,examples:i,exampleSeparator:t.example_separator,prefix:t.prefix,suffix:t.suffix,templateFormat:t.template_format})}},GT=class e extends MT{lc_serializable=!0;examples;exampleSelector;examplePrompt;suffix=``;exampleSeparator=`
136
-
137
- `;prefix=``;templateFormat=`f-string`;validateTemplate=!0;_getPromptType(){return`few_shot_chat`}static lc_name(){return`FewShotChatMessagePromptTemplate`}constructor(e){if(super(e),this.examples=e.examples,this.examplePrompt=e.examplePrompt,this.exampleSeparator=e.exampleSeparator??`
138
-
139
- `,this.exampleSelector=e.exampleSelector,this.prefix=e.prefix??``,this.suffix=e.suffix??``,this.templateFormat=e.templateFormat??`f-string`,this.validateTemplate=e.validateTemplate??!0,this.examples!==void 0&&this.exampleSelector!==void 0)throw Error(`Only one of 'examples' and 'example_selector' should be provided`);if(this.examples===void 0&&this.exampleSelector===void 0)throw Error(`One of 'examples' and 'example_selector' should be provided`);if(this.validateTemplate){let e=this.inputVariables;this.partialVariables&&(e=e.concat(Object.keys(this.partialVariables))),CT(this.prefix+this.suffix,this.templateFormat,e)}}async getExamples(e){if(this.examples!==void 0)return this.examples;if(this.exampleSelector!==void 0)return this.exampleSelector.selectExamples(e);throw Error(`One of 'examples' and 'example_selector' should be provided`)}async formatMessages(e){let t=await this.mergePartialAndUserVariables(e),n=await this.getExamples(t);n=n.map(e=>{let t={};return this.examplePrompt.inputVariables.forEach(n=>{t[n]=e[n]}),t});let r=[];for(let e of n){let t=await this.examplePrompt.formatMessages(e);r.push(...t)}return r}async format(e){let t=await this.mergePartialAndUserVariables(e),n=await this.getExamples(t),r=(await Promise.all(n.map(e=>this.examplePrompt.formatMessages(e)))).flat().map(e=>e.content);return xT([this.prefix,...r,this.suffix].join(this.exampleSeparator),this.templateFormat,t)}async partial(t){let n=this.inputVariables.filter(e=>!(e in t)),r={...this.partialVariables??{},...t};return new e({...this,inputVariables:n,partialVariables:r})}},KT=class e extends zw{static lc_name(){return`PipelinePromptTemplate`}pipelinePrompts;finalPrompt;constructor(e){super({...e,inputVariables:[]}),this.pipelinePrompts=e.pipelinePrompts,this.finalPrompt=e.finalPrompt,this.inputVariables=this.computeInputValues()}computeInputValues(){let e=this.pipelinePrompts.map(e=>e.name),t=this.pipelinePrompts.map(t=>t.prompt.inputVariables.filter(t=>!e.includes(t))).flat();return[...new Set(t)]}static extractRequiredInputValues(e,t){return t.reduce((t,n)=>(t[n]=e[n],t),{})}async formatPipelinePrompts(t){let n=await this.mergePartialAndUserVariables(t);for(let{name:t,prompt:r}of this.pipelinePrompts){let i=e.extractRequiredInputValues(n,r.inputVariables);r instanceof UT?n[t]=await r.formatMessages(i):n[t]=await r.format(i)}return e.extractRequiredInputValues(n,this.finalPrompt.inputVariables)}async formatPromptValue(e){return this.finalPrompt.formatPromptValue(await this.formatPipelinePrompts(e))}async format(e){return this.finalPrompt.format(await this.formatPipelinePrompts(e))}async partial(t){let n={...this};return n.inputVariables=this.inputVariables.filter(e=>!(e in t)),n.partialVariables={...this.partialVariables??{},...t},new e(n)}serialize(){throw Error(`Not implemented.`)}_getPromptType(){return`pipeline`}};function qT(e){return typeof e==`object`&&!!e&&`withStructuredOutput`in e&&typeof e.withStructuredOutput==`function`}function JT(e){return typeof e==`object`&&!!e&&`lc_id`in e&&Array.isArray(e.lc_id)&&e.lc_id.join(`/`)===`langchain_core/runnables/RunnableBinding`}var YT=class e extends UT{schema;method;lc_namespace=[`langchain_core`,`prompts`,`structured`];get lc_aliases(){return{...super.lc_aliases,schema:`schema_`}}constructor(e){super(e),this.schema=e.schema,this.method=e.method}pipe(e){if(qT(e))return super.pipe(e.withStructuredOutput(this.schema));if(JT(e)&&qT(e.bound))return super.pipe(new iy({bound:e.bound.withStructuredOutput(this.schema,...this.method?[{method:this.method}]:[]),kwargs:e.kwargs??{},config:e.config,configFactories:e.configFactories}));throw Error(`Structured prompts need to be piped to a language model that supports the "withStructuredOutput()" method.`)}static fromMessagesAndSchema(t,n,r){return e.fromMessages(t,{schema:n,method:r})}},XT=o({AIMessagePromptTemplate:()=>RT,BaseChatPromptTemplate:()=>MT,BaseMessagePromptTemplate:()=>kT,BaseMessageStringPromptTemplate:()=>jT,BasePromptTemplate:()=>zw,BaseStringPromptTemplate:()=>Bw,ChatMessagePromptTemplate:()=>NT,ChatPromptTemplate:()=>UT,DEFAULT_FORMATTER_MAPPING:()=>yT,DEFAULT_PARSER_MAPPING:()=>bT,DictPromptTemplate:()=>ET,FewShotChatMessagePromptTemplate:()=>GT,FewShotPromptTemplate:()=>WT,HumanMessagePromptTemplate:()=>LT,ImagePromptTemplate:()=>TT,MessagesPlaceholder:()=>AT,PipelinePromptTemplate:()=>KT,PromptTemplate:()=>wT,StructuredPrompt:()=>YT,SystemMessagePromptTemplate:()=>zT,checkValidTemplate:()=>CT,interpolateFString:()=>_T,interpolateMustache:()=>vT,parseFString:()=>mT,parseMustache:()=>gT,parseTemplate:()=>ST,renderTemplate:()=>xT}),ZT=o({BaseDocumentCompressor:()=>QT}),QT=class{static isBaseDocumentCompressor(e){return e?.compressDocuments!==void 0}},$T=o({BaseRetriever:()=>eE}),eE=class extends ry{callbacks;tags;metadata;verbose;constructor(e){super(e),this.callbacks=e?.callbacks,this.tags=e?.tags??[],this.metadata=e?.metadata??{},this.verbose=e?.verbose??!1}_getRelevantDocuments(e,t){throw Error(`Not implemented!`)}async invoke(e,t){let n=il(zc(t)),r=await(await Kc.configure(n.callbacks,this.callbacks,n.tags,this.tags,n.metadata,this.metadata,{verbose:this.verbose}))?.handleRetrieverStart(this.toJSON(),e,n.runId,void 0,void 0,void 0,n.runName);try{let t=await this._getRelevantDocuments(e,r);return await r?.handleRetrieverEnd(t),t}catch(e){throw await r?.handleRetrieverError(e),e}}},tE=o({BaseStore:()=>nE,InMemoryStore:()=>rE}),nE=class extends ge{},rE=class extends nE{lc_namespace=[`langchain`,`storage`];store={};async mget(e){return e.map(e=>this.store[e])}async mset(e){for(let[t,n]of e)this.store[t]=n}async mdelete(e){for(let t of e)delete this.store[t]}async*yieldKeys(e){let t=Object.keys(this.store);for(let n of t)(e===void 0||n.startsWith(e))&&(yield n)}},iE={and:`and`,or:`or`,not:`not`},aE={eq:`eq`,ne:`ne`,lt:`lt`,gt:`gt`,lte:`lte`,gte:`gte`},oE=class{},sE=class{accept(e){if(this.exprName===`Operation`)return e.visitOperation(this);if(this.exprName===`Comparison`)return e.visitComparison(this);if(this.exprName===`StructuredQuery`)return e.visitStructuredQuery(this);throw Error(`Unknown Expression type`)}},cE=class extends sE{},lE=class extends cE{exprName=`Comparison`;constructor(e,t,n){super(),this.comparator=e,this.attribute=t,this.value=n}},uE=class extends cE{exprName=`Operation`;constructor(e,t){super(),this.operator=e,this.args=t}},dE=class extends sE{exprName=`StructuredQuery`;constructor(e,t){super(),this.query=e,this.filter=t}};function fE(e){return e&&typeof e==`object`&&!Array.isArray(e)}function pE(e){return e?typeof e==`string`&&e.length>0||typeof e==`function`?!1:fE(e)&&Object.keys(e).length===0:!0}function mE(e){if(typeof e==`number`)return e%1==0;if(typeof e==`string`){let t=parseInt(e,10);return!Number.isNaN(t)&&t%1==0&&t.toString()===e}return!1}function hE(e){if(typeof e==`number`)return e%1!=0;if(typeof e==`string`){let t=parseFloat(e);return!Number.isNaN(t)&&t%1!=0&&t.toString()===e}return!1}function gE(e){return typeof e==`string`&&(Number.isNaN(parseFloat(e))||parseFloat(e).toString()!==e)}function _E(e){return typeof e==`boolean`}function vE(e){let t;if(gE(e))t=e;else if(mE(e))t=parseInt(e,10);else if(hE(e))t=parseFloat(e);else if(_E(e))t=!!e;else throw Error(`Unsupported value type`);return t}var yE=class extends oE{},bE=class extends yE{allowedOperators;allowedComparators;constructor(e){super(),this.allowedOperators=e?.allowedOperators??[iE.and,iE.or],this.allowedComparators=e?.allowedComparators??[aE.eq,aE.ne,aE.gt,aE.gte,aE.lt,aE.lte]}formatFunction(e){if(e in aE){if(this.allowedComparators.length>0&&this.allowedComparators.indexOf(e)===-1)throw Error(`Comparator ${e} not allowed. Allowed comparators: ${this.allowedComparators.join(`, `)}`)}else if(e in iE){if(this.allowedOperators.length>0&&this.allowedOperators.indexOf(e)===-1)throw Error(`Operator ${e} not allowed. Allowed operators: ${this.allowedOperators.join(`, `)}`)}else throw Error(`Unknown comparator or operator`);return`$${e}`}visitOperation(e){let t=e.args?.map(e=>e.accept(this));return{[this.formatFunction(e.operator)]:t}}visitComparison(e){return{[e.attribute]:{[this.formatFunction(e.comparator)]:vE(e.value)}}}visitStructuredQuery(e){let t={};return e.filter&&(t={filter:e.filter.accept(this)}),t}mergeFilters(e,t,n=`and`,r=!1){if(!(pE(e)&&pE(t))){if(pE(e)||n===`replace`)return pE(t)?void 0:t;if(pE(t))return r?e:n===`and`?void 0:e;if(n===`and`)return{$and:[e,t]};if(n===`or`)return{$or:[e,t]};throw Error(`Unknown merge type`)}}},xE=class extends yE{allowedOperators=[iE.and,iE.or];allowedComparators=[aE.eq,aE.ne,aE.gt,aE.gte,aE.lt,aE.lte];formatFunction(){throw Error(`Not implemented`)}getAllowedComparatorsForType(e){switch(e){case`string`:return[aE.eq,aE.ne,aE.gt,aE.gte,aE.lt,aE.lte];case`number`:return[aE.eq,aE.ne,aE.gt,aE.gte,aE.lt,aE.lte];case`boolean`:return[aE.eq,aE.ne];default:throw Error(`Unsupported data type: ${e}`)}}getComparatorFunction(e){switch(e){case aE.eq:return(e,t)=>e===t;case aE.ne:return(e,t)=>e!==t;case aE.gt:return(e,t)=>e>t;case aE.gte:return(e,t)=>e>=t;case aE.lt:return(e,t)=>e<t;case aE.lte:return(e,t)=>e<=t;default:throw Error(`Unknown comparator`)}}getOperatorFunction(e){switch(e){case iE.and:return(e,t)=>e&&t;case iE.or:return(e,t)=>e||t;default:throw Error(`Unknown operator`)}}visitOperation(e){let{operator:t,args:n}=e;if(this.allowedOperators.includes(t)){let e=this.getOperatorFunction(t);return t=>n?n.reduce((n,r)=>{let i=r.accept(this);if(typeof i==`function`)return e(n,i(t));throw Error(`Filter is not a function`)},!0):!0}else throw Error(`Operator not allowed`)}visitComparison(e){let{comparator:t,attribute:n,value:r}=e,i=[aE.ne];if(this.allowedComparators.includes(t)){if(!this.getAllowedComparatorsForType(typeof r).includes(t))throw Error(`'${t}' comparator not allowed to be used with ${typeof r}`);let e=this.getComparatorFunction(t);return a=>{let o=a.metadata[n];return o===void 0?!!i.includes(t):e(o,vE(r))}}else throw Error(`Comparator not allowed`)}visitStructuredQuery(e){if(!e.filter)return{};let t=e.filter?.accept(this);if(typeof t!=`function`)throw Error(`Structured query filter is not a function`);return{filter:t}}mergeFilters(e,t,n=`and`){if(!(pE(e)&&pE(t))){if(pE(e)||n===`replace`)return pE(t)?void 0:t;if(pE(t))return n===`and`?void 0:e;if(n===`and`)return n=>e(n)&&t(n);if(n===`or`)return n=>e(n)||t(n);throw Error(`Unknown merge type`)}}},SE=o({BaseTranslator:()=>yE,BasicTranslator:()=>bE,Comparators:()=>aE,Comparison:()=>lE,Expression:()=>sE,FilterDirective:()=>cE,FunctionalTranslator:()=>xE,Operation:()=>uE,Operators:()=>iE,StructuredQuery:()=>dE,Visitor:()=>oE,castValue:()=>vE,isBoolean:()=>_E,isFilterEmpty:()=>pE,isFloat:()=>hE,isInt:()=>mE,isObject:()=>fE,isString:()=>gE});function CE(e){return tt.isInstance(e)?e.constructor.name||e.type:typeof e}function wE(e,t){return function(n,r){let{isNot:i,utils:a}=this;if(!t(n))return{pass:!1,message:()=>`${a.matcherHint(`toBe${e}`,void 0,void 0)}\n\nExpected: ${i?`not `:``}${e}\nReceived: ${CE(n)}`,actual:CE(n),expected:e};if(r===void 0)return{pass:!0,message:()=>`${a.matcherHint(`toBe${e}`,void 0,void 0)}\n\nExpected: not ${e}\nReceived: ${e}`};let o=n;return typeof r==`string`?{pass:o.content===r,message:()=>`${a.matcherHint(`toBe${e}`,void 0,void 0)}\n\nExpected: ${e} with content ${a.printExpected(r)}\nReceived: ${e} with content ${a.printReceived(o.content)}`,actual:o.content,expected:r}:{pass:Object.entries(r).every(([e,t])=>this.equals(o[e],t)),message:()=>{let t={};for(let e of Object.keys(r))t[e]=o[e];return`${a.matcherHint(`toBe${e}`,void 0,void 0)}\n\nExpected: ${e} matching ${a.printExpected(r)}\nReceived: ${e} with ${a.printReceived(t)}`},actual:(()=>{let e={};for(let t of Object.keys(r))e[t]=o[t];return e})(),expected:r}}}var TE=wE(`HumanMessage`,on.isInstance),EE=wE(`AIMessage`,qt.isInstance),DE=wE(`SystemMessage`,dn.isInstance),OE=wE(`ToolMessage`,_t.isInstance);function kE(e,t){let{isNot:n,utils:r}=this;if(!qt.isInstance(e))return{pass:!1,message:()=>`${r.matcherHint(`toHaveToolCalls`)}\n\nExpected: AIMessage\nReceived: ${CE(e)}`};let i=e.tool_calls??[];if(i.length!==t.length)return{pass:!1,message:()=>`${r.matcherHint(`toHaveToolCalls`)}\n\nExpected ${n?`not `:``}${t.length} tool call(s), received ${i.length}`,actual:i.length,expected:t.length};let a=t.filter(e=>!i.some(t=>Object.entries(e).every(([e,n])=>this.equals(t[e],n))));return a.length>0?{pass:!1,message:()=>`${r.matcherHint(`toHaveToolCalls`)}\n\nCould not find matching tool call(s) for:\n${r.printExpected(a)}\nReceived tool calls: ${r.printReceived(i.map(e=>({name:e.name,id:e.id,args:e.args})))}`,actual:i.map(e=>({name:e.name,id:e.id,args:e.args})),expected:t}:{pass:!0,message:()=>`${r.matcherHint(`toHaveToolCalls`)}\n\nExpected AIMessage not to have matching tool calls`}}function AE(e,t){let{isNot:n,utils:r}=this;if(!qt.isInstance(e))return{pass:!1,message:()=>`${r.matcherHint(`toHaveToolCallCount`)}\n\nExpected: AIMessage\nReceived: ${CE(e)}`};let i=e.tool_calls?.length??0;return{pass:i===t,message:()=>`${r.matcherHint(`toHaveToolCallCount`)}\n\nExpected ${n?`not `:``}${t} tool call(s)\nReceived: ${i}`,actual:i,expected:t}}function jE(e,t){let{isNot:n,utils:r}=this;if(!qt.isInstance(e))return{pass:!1,message:()=>`${r.matcherHint(`toContainToolCall`)}\n\nExpected: AIMessage\nReceived: ${CE(e)}`};let i=e.tool_calls??[];return{pass:i.some(e=>Object.entries(t).every(([t,n])=>this.equals(e[t],n))),message:()=>`${r.matcherHint(`toContainToolCall`)}\n\nExpected AIMessage ${n?`not `:``}to contain a tool call matching ${r.printExpected(t)}\nReceived tool calls: ${r.printReceived(i.map(e=>({name:e.name,id:e.id})))}`,actual:i.map(e=>({name:e.name,id:e.id})),expected:t}}function ME(e,t){let{isNot:n,utils:r}=this;if(!Array.isArray(e))return{pass:!1,message:()=>`${r.matcherHint(`toHaveToolMessages`)}\n\nExpected an array of messages\nReceived: ${typeof e}`};let i=e.filter(_t.isInstance);if(i.length!==t.length)return{pass:!1,message:()=>`${r.matcherHint(`toHaveToolMessages`)}\n\nExpected ${n?`not `:``}${t.length} tool message(s), found ${i.length}`,actual:i.length,expected:t.length};for(let e=0;e<t.length;e++)if(!Object.entries(t[e]).every(([t,n])=>this.equals(i[e][t],n)))return{pass:!1,message:()=>{let n={};for(let r of Object.keys(t[e]))n[r]=i[e][r];return`${r.matcherHint(`toHaveToolMessages`)}\n\nTool message at index ${e} did not match:\nExpected: ${r.printExpected(t[e])}\nReceived: ${r.printReceived(n)}`},actual:i[e],expected:t[e]};return{pass:!0,message:()=>`${r.matcherHint(`toHaveToolMessages`)}\n\nExpected messages not to contain matching tool messages`}}function NE(e,t){let{isNot:n,utils:r}=this,i=e?.__interrupt__;if(!(Array.isArray(i)&&i.length>0))return{pass:!1,message:()=>`${r.matcherHint(`toHaveBeenInterrupted`)}\n\nExpected result ${n?`not `:``}to have been interrupted\nReceived __interrupt__: ${r.printReceived(i)}`};if(t===void 0)return{pass:!0,message:()=>`${r.matcherHint(`toHaveBeenInterrupted`)}\n\nExpected result not to have been interrupted\nReceived ${i.length} interrupt(s)`};let a=i[0]?.value;return{pass:this.equals(a,t),message:()=>`${r.matcherHint(`toHaveBeenInterrupted`)}\n\nExpected interrupt value: ${r.printExpected(t)}\nReceived interrupt value: ${r.printReceived(a)}`,actual:a,expected:t}}function PE(e,t){let{isNot:n,utils:r}=this,i=e?.structuredResponse;return i===void 0?{pass:!1,message:()=>`${r.matcherHint(`toHaveStructuredResponse`)}\n\nExpected result ${n?`not `:``}to have a structured response\nReceived structuredResponse: undefined`}:t===void 0?{pass:!0,message:()=>`${r.matcherHint(`toHaveStructuredResponse`)}\n\nExpected result not to have a structured response`}:{pass:Object.entries(t).every(([e,t])=>this.equals(i[e],t)),message:()=>`${r.matcherHint(`toHaveStructuredResponse`)}\n\nExpected structured response: ${r.printExpected(t)}\nReceived structured response: ${r.printReceived(i)}`,actual:i,expected:t}}var FE={toBeHumanMessage:TE,toBeAIMessage:EE,toBeSystemMessage:DE,toBeToolMessage:OE,toHaveToolCalls:kE,toHaveToolCallCount:AE,toContainToolCall:jE,toHaveToolMessages:ME,toHaveBeenInterrupted:NE,toHaveStructuredResponse:PE};function IE(e){return e.map(e=>e.text).filter(Boolean).join(`-`)}var LE=0;function RE(){return LE+=1,`fake_tc_${LE}`}var zE=class e extends xw{queue=[];_alwaysThrowError;_structuredResponseValue;_tools=[];_callIndex=0;_calls=[];get calls(){return this._calls}get callCount(){return this._calls.length}constructor(){super({})}_llmType(){return`fake-model-builder`}_combineLLMOutput(){return[]}respond(e){return typeof e==`function`?this.queue.push({kind:`factory`,factory:e}):tt.isInstance(e)?this.queue.push({kind:`message`,message:e}):this.queue.push({kind:`error`,error:e}),this}respondWithTools(e){return this.queue.push({kind:`toolCalls`,toolCalls:e.map(e=>({name:e.name,args:e.args,id:e.id??RE(),type:`tool_call`}))}),this}alwaysThrow(e){return this._alwaysThrowError=e,this}structuredResponse(e){return this._structuredResponseValue=e,this}bindTools(t){let n=[...this._tools,...t],r=new e;return r.queue=this.queue,r._alwaysThrowError=this._alwaysThrowError,r._structuredResponseValue=this._structuredResponseValue,r._tools=n,r._calls=this._calls,r._callIndex=this._callIndex,r.withConfig({})}withStructuredOutput(e,t){let{_structuredResponseValue:n}=this;return dy.from(async()=>n)}async _generate(e,t,n){this._calls.push({messages:[...e],options:t});let r=this._callIndex;if(this._callIndex+=1,this._alwaysThrowError)throw this._alwaysThrowError;let i=this.queue[r];if(!i)throw Error(`FakeModel: no response queued for invocation ${r} (${this.queue.length} total queued).`);if(i.kind===`error`)throw i.error;if(i.kind===`factory`){let t=i.factory(e);if(!tt.isInstance(t))throw t;return{generations:[{text:``,message:t}]}}if(i.kind===`message`)return{generations:[{text:``,message:i.message}]};let a=IE(e);return{generations:[{text:a,message:new qt({content:a,id:r.toString(),tool_calls:i.toolCalls.length>0?i.toolCalls.map(e=>({...e,type:`tool_call`})):void 0})}],llmOutput:{}}}};function BE(){return new zE}var VE=o({FakeBuiltModel:()=>zE,fakeModel:()=>BE,langchainMatchers:()=>FE,toBeAIMessage:()=>EE,toBeHumanMessage:()=>TE,toBeSystemMessage:()=>DE,toBeToolMessage:()=>OE,toContainToolCall:()=>jE,toHaveBeenInterrupted:()=>NE,toHaveStructuredResponse:()=>PE,toHaveToolCallCount:()=>AE,toHaveToolCalls:()=>kE,toHaveToolMessages:()=>ME});function HE(e){return e!==void 0&&Array.isArray(e.lc_namespace)}function UE(e){return e!==void 0&&ry.isRunnable(e)&&`lc_name`in e.constructor&&typeof e.constructor.lc_name==`function`&&e.constructor.lc_name()===`RunnableToolLike`}function WE(e){return!!e&&typeof e==`object`&&`name`in e&&`schema`in e&&(Mm(e.schema)||e.schema!=null&&typeof e.schema==`object`&&`type`in e.schema&&typeof e.schema.type==`string`&&[`null`,`boolean`,`object`,`array`,`number`,`string`].includes(e.schema.type))}function GE(e){return WE(e)||UE(e)||HE(e)}var KE=j(`ZodISODateTime`,(e,t)=>{wf.init(e,t),uD.init(e,t)});function qE(e){return Jp(KE,e)}var JE=j(`ZodISODate`,(e,t)=>{Tf.init(e,t),uD.init(e,t)});function YE(e){return Yp(JE,e)}var XE=j(`ZodISOTime`,(e,t)=>{Ef.init(e,t),uD.init(e,t)});function ZE(e){return Xp(XE,e)}var QE=j(`ZodISODuration`,(e,t)=>{Df.init(e,t),uD.init(e,t)});function $E(e){return Zp(QE,e)}var eD=(e,t)=>{$u.init(e,t),e.name=`ZodError`,Object.defineProperties(e,{format:{value:t=>nd(e,t)},flatten:{value:t=>td(e,t)},addIssue:{value:t=>e.issues.push(t)},addIssues:{value:t=>e.issues.push(...t)},isEmpty:{get(){return e.issues.length===0}}})};j(`ZodError`,eD);var tD=j(`ZodError`,eD,{Parent:Error}),nD=ad(tD),rD=sd(tD),iD=ld(tD),aD=dd(tD),oD=j(`ZodType`,(e,t)=>(uf.init(e,t),e.def=t,Object.defineProperty(e,`_def`,{value:t}),e.check=(...n)=>e.clone({...t,checks:[...t.checks??[],...n.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]}),e.clone=(t,n)=>Lu(e,t,n),e.brand=()=>e,e.register=((t,n)=>(t.add(e,n),e)),e.parse=(t,n)=>nD(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>iD(e,t,n),e.parseAsync=async(t,n)=>rD(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>aD(e,t,n),e.spa=e.safeParseAsync,e.refine=(t,n)=>e.check(EO(t,n)),e.superRefine=t=>e.check(DO(t)),e.overwrite=t=>e.check(vm(t)),e.optional=()=>cO(e),e.nullable=()=>uO(e),e.nullish=()=>cO(uO(e)),e.nonoptional=t=>gO(e,t),e.array=()=>UD(e),e.or=t=>KD([e,t]),e.and=t=>XD(e,t),e.transform=t=>bO(e,oO(t)),e.default=t=>fO(e,t),e.prefault=t=>mO(e,t),e.catch=t=>vO(e,t),e.pipe=t=>bO(e,t),e.readonly=()=>SO(e),e.describe=t=>{let n=e.clone();return wp.add(n,{description:t}),n},Object.defineProperty(e,`description`,{get(){return wp.get(e)?.description},configurable:!0}),e.meta=(...t)=>{if(t.length===0)return wp.get(e);let n=e.clone();return wp.add(n,t[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),sD=j(`_ZodString`,(e,t)=>{df.init(e,t),oD.init(e,t);let n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,e.regex=(...t)=>e.check(fm(...t)),e.includes=(...t)=>e.check(hm(...t)),e.startsWith=(...t)=>e.check(gm(...t)),e.endsWith=(...t)=>e.check(_m(...t)),e.min=(...t)=>e.check(um(...t)),e.max=(...t)=>e.check(lm(...t)),e.length=(...t)=>e.check(dm(...t)),e.nonempty=(...t)=>e.check(um(1,...t)),e.lowercase=t=>e.check(pm(t)),e.uppercase=t=>e.check(mm(t)),e.trim=()=>e.check(bm()),e.normalize=(...t)=>e.check(ym(...t)),e.toLowerCase=()=>e.check(xm()),e.toUpperCase=()=>e.check(Sm())}),cD=j(`ZodString`,(e,t)=>{df.init(e,t),sD.init(e,t),e.email=t=>e.check(Ep(dD,t)),e.url=t=>e.check(Mp(mD,t)),e.jwt=t=>e.check(qp(kD,t)),e.emoji=t=>e.check(Np(hD,t)),e.guid=t=>e.check(Dp(fD,t)),e.uuid=t=>e.check(Op(pD,t)),e.uuidv4=t=>e.check(kp(pD,t)),e.uuidv6=t=>e.check(Ap(pD,t)),e.uuidv7=t=>e.check(jp(pD,t)),e.nanoid=t=>e.check(Pp(gD,t)),e.guid=t=>e.check(Dp(fD,t)),e.cuid=t=>e.check(Fp(_D,t)),e.cuid2=t=>e.check(Ip(vD,t)),e.ulid=t=>e.check(Lp(yD,t)),e.base64=t=>e.check(Wp(ED,t)),e.base64url=t=>e.check(Gp(DD,t)),e.xid=t=>e.check(Rp(bD,t)),e.ksuid=t=>e.check(zp(xD,t)),e.ipv4=t=>e.check(Bp(SD,t)),e.ipv6=t=>e.check(Vp(CD,t)),e.cidrv4=t=>e.check(Hp(wD,t)),e.cidrv6=t=>e.check(Up(TD,t)),e.e164=t=>e.check(Kp(OD,t)),e.datetime=t=>e.check(qE(t)),e.date=t=>e.check(YE(t)),e.time=t=>e.check(ZE(t)),e.duration=t=>e.check($E(t))});function lD(e){return Tp(cD,e)}var uD=j(`ZodStringFormat`,(e,t)=>{ff.init(e,t),sD.init(e,t)}),dD=j(`ZodEmail`,(e,t)=>{hf.init(e,t),uD.init(e,t)}),fD=j(`ZodGUID`,(e,t)=>{pf.init(e,t),uD.init(e,t)}),pD=j(`ZodUUID`,(e,t)=>{mf.init(e,t),uD.init(e,t)}),mD=j(`ZodURL`,(e,t)=>{gf.init(e,t),uD.init(e,t)}),hD=j(`ZodEmoji`,(e,t)=>{_f.init(e,t),uD.init(e,t)}),gD=j(`ZodNanoID`,(e,t)=>{vf.init(e,t),uD.init(e,t)}),_D=j(`ZodCUID`,(e,t)=>{yf.init(e,t),uD.init(e,t)}),vD=j(`ZodCUID2`,(e,t)=>{bf.init(e,t),uD.init(e,t)}),yD=j(`ZodULID`,(e,t)=>{xf.init(e,t),uD.init(e,t)}),bD=j(`ZodXID`,(e,t)=>{Sf.init(e,t),uD.init(e,t)}),xD=j(`ZodKSUID`,(e,t)=>{Cf.init(e,t),uD.init(e,t)}),SD=j(`ZodIPv4`,(e,t)=>{Of.init(e,t),uD.init(e,t)}),CD=j(`ZodIPv6`,(e,t)=>{kf.init(e,t),uD.init(e,t)}),wD=j(`ZodCIDRv4`,(e,t)=>{Af.init(e,t),uD.init(e,t)}),TD=j(`ZodCIDRv6`,(e,t)=>{jf.init(e,t),uD.init(e,t)}),ED=j(`ZodBase64`,(e,t)=>{Nf.init(e,t),uD.init(e,t)}),DD=j(`ZodBase64URL`,(e,t)=>{Ff.init(e,t),uD.init(e,t)}),OD=j(`ZodE164`,(e,t)=>{If.init(e,t),uD.init(e,t)}),kD=j(`ZodJWT`,(e,t)=>{Rf.init(e,t),uD.init(e,t)}),AD=j(`ZodNumber`,(e,t)=>{zf.init(e,t),oD.init(e,t),e.gt=(t,n)=>e.check(om(t,n)),e.gte=(t,n)=>e.check(sm(t,n)),e.min=(t,n)=>e.check(sm(t,n)),e.lt=(t,n)=>e.check(im(t,n)),e.lte=(t,n)=>e.check(am(t,n)),e.max=(t,n)=>e.check(am(t,n)),e.int=t=>e.check(ND(t)),e.safe=t=>e.check(ND(t)),e.positive=t=>e.check(om(0,t)),e.nonnegative=t=>e.check(sm(0,t)),e.negative=t=>e.check(im(0,t)),e.nonpositive=t=>e.check(am(0,t)),e.multipleOf=(t,n)=>e.check(cm(t,n)),e.step=(t,n)=>e.check(cm(t,n)),e.finite=()=>e;let n=e._zod.bag;e.minValue=Math.max(n.minimum??-1/0,n.exclusiveMinimum??-1/0)??null,e.maxValue=Math.min(n.maximum??1/0,n.exclusiveMaximum??1/0)??null,e.isInt=(n.format??``).includes(`int`)||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null});function jD(e){return Qp(AD,e)}var MD=j(`ZodNumberFormat`,(e,t)=>{Bf.init(e,t),AD.init(e,t)});function ND(e){return $p(MD,e)}var PD=j(`ZodBoolean`,(e,t)=>{Vf.init(e,t),oD.init(e,t)});function FD(e){return em(PD,e)}var ID=j(`ZodAny`,(e,t)=>{Hf.init(e,t),oD.init(e,t)});function LD(){return tm(ID)}var RD=j(`ZodUnknown`,(e,t)=>{Uf.init(e,t),oD.init(e,t)});function zD(){return nm(RD)}var BD=j(`ZodNever`,(e,t)=>{Wf.init(e,t),oD.init(e,t)});function VD(e){return rm(BD,e)}var HD=j(`ZodArray`,(e,t)=>{Kf.init(e,t),oD.init(e,t),e.element=t.element,e.min=(t,n)=>e.check(um(t,n)),e.nonempty=t=>e.check(um(1,t)),e.max=(t,n)=>e.check(lm(t,n)),e.length=(t,n)=>e.check(dm(t,n)),e.unwrap=()=>e.element});function UD(e,t){return Cm(HD,e,t)}var WD=j(`ZodObject`,(e,t)=>{Yf.init(e,t),oD.init(e,t),Ou(e,`shape`,()=>t.shape),e.keyof=()=>nO(Object.keys(e._zod.def.shape)),e.catchall=t=>e.clone({...e._zod.def,catchall:t}),e.passthrough=()=>e.clone({...e._zod.def,catchall:zD()}),e.loose=()=>e.clone({...e._zod.def,catchall:zD()}),e.strict=()=>e.clone({...e._zod.def,catchall:VD()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=t=>Hu(e,t),e.merge=t=>Uu(e,t),e.pick=t=>Bu(e,t),e.omit=t=>Vu(e,t),e.partial=(...t)=>Wu(sO,e,t[0]),e.required=(...t)=>Gu(hO,e,t[0])});function V(e,t){return new WD({type:`object`,get shape(){return ku(this,`shape`,{...e}),this.shape},...M(t)})}var GD=j(`ZodUnion`,(e,t)=>{Zf.init(e,t),oD.init(e,t),e.options=t.options});function KD(e,t){return new GD({type:`union`,options:e,...M(t)})}var qD=j(`ZodDiscriminatedUnion`,(e,t)=>{GD.init(e,t),Qf.init(e,t)});function JD(e,t,n){return new qD({type:`union`,options:t,discriminator:e,...M(n)})}var YD=j(`ZodIntersection`,(e,t)=>{$f.init(e,t),oD.init(e,t)});function XD(e,t){return new YD({type:`intersection`,left:e,right:t})}var ZD=j(`ZodTuple`,(e,t)=>{np.init(e,t),oD.init(e,t),e.rest=t=>e.clone({...e._zod.def,rest:t})});function QD(e,t,n){let r=t instanceof uf;return new ZD({type:`tuple`,items:e,rest:r?t:null,...M(r?n:t)})}var $D=j(`ZodRecord`,(e,t)=>{ip.init(e,t),oD.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType});function eO(e,t,n){return new $D({type:`record`,keyType:e,valueType:t,...M(n)})}var tO=j(`ZodEnum`,(e,t)=>{ap.init(e,t),oD.init(e,t),e.enum=t.entries,e.options=Object.values(t.entries);let n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{let i={};for(let r of e)if(n.has(r))i[r]=t.entries[r];else throw Error(`Key ${r} not found in enum`);return new tO({...t,checks:[],...M(r),entries:i})},e.exclude=(e,r)=>{let i={...t.entries};for(let t of e)if(n.has(t))delete i[t];else throw Error(`Key ${t} not found in enum`);return new tO({...t,checks:[],...M(r),entries:i})}});function nO(e,t){return new tO({type:`enum`,entries:Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e,...M(t)})}var rO=j(`ZodLiteral`,(e,t)=>{op.init(e,t),oD.init(e,t),e.values=new Set(t.values),Object.defineProperty(e,`value`,{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function iO(e,t){return new rO({type:`literal`,values:Array.isArray(e)?e:[e],...M(t)})}var aO=j(`ZodTransform`,(e,t)=>{sp.init(e,t),oD.init(e,t),e._zod.parse=(n,r)=>{n.addIssue=r=>{if(typeof r==`string`)n.issues.push(Zu(r,n.value,t));else{let t=r;t.fatal&&(t.continue=!1),t.code??=`custom`,t.input??=n.value,t.inst??=e,t.continue??=!0,n.issues.push(Zu(t))}};let i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n)):(n.value=i,n)}});function oO(e){return new aO({type:`transform`,transform:e})}var sO=j(`ZodOptional`,(e,t)=>{cp.init(e,t),oD.init(e,t),e.unwrap=()=>e._zod.def.innerType});function cO(e){return new sO({type:`optional`,innerType:e})}var lO=j(`ZodNullable`,(e,t)=>{lp.init(e,t),oD.init(e,t),e.unwrap=()=>e._zod.def.innerType});function uO(e){return new lO({type:`nullable`,innerType:e})}var dO=j(`ZodDefault`,(e,t)=>{up.init(e,t),oD.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function fO(e,t){return new dO({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():t}})}var pO=j(`ZodPrefault`,(e,t)=>{fp.init(e,t),oD.init(e,t),e.unwrap=()=>e._zod.def.innerType});function mO(e,t){return new pO({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():t}})}var hO=j(`ZodNonOptional`,(e,t)=>{pp.init(e,t),oD.init(e,t),e.unwrap=()=>e._zod.def.innerType});function gO(e,t){return new hO({type:`nonoptional`,innerType:e,...M(t)})}var _O=j(`ZodCatch`,(e,t)=>{hp.init(e,t),oD.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function vO(e,t){return new _O({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:()=>t})}var yO=j(`ZodPipe`,(e,t)=>{gp.init(e,t),oD.init(e,t),e.in=t.in,e.out=t.out});function bO(e,t){return new yO({type:`pipe`,in:e,out:t})}var xO=j(`ZodReadonly`,(e,t)=>{vp.init(e,t),oD.init(e,t)});function SO(e){return new xO({type:`readonly`,innerType:e})}var CO=j(`ZodCustom`,(e,t)=>{bp.init(e,t),oD.init(e,t)});function wO(e){let t=new Wd({check:`custom`});return t._zod.check=e,t}function TO(e,t){return wm(CO,e??(()=>!0),t)}function EO(e,t={}){return Tm(CO,e,t)}function DO(e){let t=wO(n=>(n.addIssue=e=>{if(typeof e==`string`)n.issues.push(Zu(e,n.value,t._zod.def));else{let r=e;r.fatal&&(r.continue=!1),r.code??=`custom`,r.input??=n.value,r.inst??=t,r.continue??=!t._zod.def.abort,n.issues.push(Zu(r))}},e(n.value,n)));return t}var OO=o({BaseToolkit:()=>NO,DynamicStructuredTool:()=>MO,DynamicTool:()=>jO,StructuredTool:()=>kO,Tool:()=>AO,ToolInputParsingException:()=>_,isLangChainTool:()=>GE,isRunnableToolLike:()=>UE,isStructuredTool:()=>HE,isStructuredToolParams:()=>WE,tool:()=>PO}),kO=class extends lC{extras;returnDirect=!1;verboseParsingErrors=!1;get lc_namespace(){return[`langchain`,`tools`]}responseFormat=`content`;defaultConfig;constructor(e){super(e??{}),this.verboseParsingErrors=e?.verboseParsingErrors??this.verboseParsingErrors,this.responseFormat=e?.responseFormat??this.responseFormat,this.defaultConfig=e?.defaultConfig??this.defaultConfig,this.metadata=e?.metadata??this.metadata,this.extras=e?.extras??this.extras}async invoke(e,t){let n,r=il(rl(this.defaultConfig,t));return h(e)?(n=e.args,r={...r,toolCall:e}):n=e,this.call(n,r)}async call(e,t,n){let r=h(e)?e.args:e,i;if(Mm(this.schema))try{i=await Lm(this.schema,r)}catch(t){let n=`Received tool input did not match expected schema`;throw this.verboseParsingErrors&&(n=`${n}\nDetails: ${t.message}`),oh(t)&&(n=`${n}\n\n${id(t)}`),new _(n,JSON.stringify(e))}else{let t=Iv(r,this.schema);if(!t.valid){let n=`Received tool input did not match expected schema`;throw this.verboseParsingErrors&&(n=`${n}\nDetails: ${t.errors.map(e=>`${e.keywordLocation}: ${e.error}`).join(`
140
- `)}`),new _(n,JSON.stringify(e))}i=r}let a=zc(t),o=Kc.configure(a.callbacks,this.callbacks,a.tags||n,this.tags,a.metadata,this.metadata,{verbose:this.verbose}),s;h(e)&&(s=e.id),!s&&g(a)&&(s=a.toolCall.id);let c=await o?.handleToolStart(this.toJSON(),typeof e==`string`?e:JSON.stringify(e),a.runId,void 0,void 0,void 0,a.runName,s);delete a.runId;let l;try{let e=await this._call(i,c,a);l=Qv(e)?await $v(e,async e=>{try{await c?.handleToolEvent(e)}catch(e){await c?.handleToolError(e)}}):e}catch(e){throw await c?.handleToolError(e),e}let u,d;if(this.responseFormat===`content_and_artifact`)if(Array.isArray(l)&&l.length===2)[u,d]=l;else throw Error(`Tool response format is "content_and_artifact" but the output was not a two-tuple.\nResult: ${JSON.stringify(l)}`);else u=l;let f=FO({content:u,artifact:d,toolCallId:s,name:this.name,metadata:this.metadata});return await c?.handleToolEnd(f),f}},AO=class extends kO{schema=e_({input:Yg().optional()}).transform(e=>e.input);constructor(e){super(e)}call(e,t){let n=typeof e==`string`||e==null?{input:e}:e;return super.call(n,t)}},jO=class extends AO{static lc_name(){return`DynamicTool`}name;description;func;constructor(e){super(e),this.name=e.name,this.description=e.description,this.func=e.func,this.returnDirect=e.returnDirect??this.returnDirect}async call(e,t){let n=zc(t);return n.runName===void 0&&(n.runName=this.name),super.call(e,n)}_call(e,t,n){return this.func(e,t,n)}},MO=class extends kO{static lc_name(){return`DynamicStructuredTool`}description;func;schema;constructor(e){super(e),this.name=e.name,this.description=e.description,this.func=e.func,this.returnDirect=e.returnDirect??this.returnDirect,this.schema=e.schema}async call(e,t,n){let r=zc(t);return r.runName===void 0&&(r.runName=this.name),super.call(e,r,n)}_call(e,t,n){return this.func(e,t,n)}},NO=class{getTools(){return this.tools}};function PO(e,t){let n=Hm(t.schema),r=Vv(t.schema);if(!t.schema||n||r)return new jO({...t,description:t.description??t.schema?.description??`${t.name} tool`,func:async(t,n,r)=>new Promise((i,a)=>{let o=al(r,{callbacks:n?.getChild()});Zc.runWithConfig(ol(o),async()=>{try{i(e(t,o))}catch(e){a(e)}})})});let i=t.schema,a=t.description??t.schema.description??`${t.name} tool`;return new MO({...t,description:a,schema:i,func:async(t,n,r)=>new Promise((i,a)=>{let o,s=()=>{r?.signal&&o&&r.signal.removeEventListener(`abort`,o)};r?.signal&&(o=()=>{s(),a(cl(r.signal))},r.signal.addEventListener(`abort`,o,{once:!0}));let c=al(r,{callbacks:n?.getChild()});Zc.runWithConfig(ol(c),async()=>{try{let n=await e(t,c);if(Qv(n)){i(n);return}if(r?.signal?.aborted){s();return}s(),i(n)}catch(e){s(),a(e)}})})})}function FO(e){let{content:t,artifact:n,toolCallId:r,metadata:i}=e;return r&&!gt(t)?typeof t==`string`||Array.isArray(t)&&t.every(e=>typeof e==`object`)?new _t({status:`success`,content:t,artifact:n,tool_call_id:r,name:e.name,metadata:i}):new _t({status:`success`,content:IO(t),artifact:n,tool_call_id:r,name:e.name,metadata:i}):t}function IO(e){try{return JSON.stringify(e)??``}catch{return`${e}`}}var LO=o({RunCollectorCallbackHandler:()=>RO}),RO=class extends nc{name=`run_collector`;exampleId;tracedRuns;constructor({exampleId:e}={}){super({_awaitHandler:!0}),this.exampleId=e,this.tracedRuns=[]}async persistRun(e){let t={...e};t.reference_example_id=this.exampleId,this.tracedRuns.push(t)}},zO=o({}),BO=o({chunkArray:()=>VO}),VO=(e,t)=>e.reduce((e,n,r)=>{let i=Math.floor(r/t);return e[i]=(e[i]||[]).concat([n]),e},[]),HO=o({context:()=>UO});function UO(e,...t){let n=e.raw,r=``;for(let e=0;e<n.length;e++){let i=n[e].replace(/\\\n[ \t]*/g,``).replace(/\\`/g,"`").replace(/\\\$/g,`$`).replace(/\\\{/g,`{`);if(r+=i,e<t.length){let n=WO(t[e],r);r+=typeof n==`string`?n:JSON.stringify(n)}}return r=GO(r),r=r.trim(),r=r.replace(/\\n/g,`
141
- `),r}function WO(e,t){if(typeof e!=`string`||!e.includes(`
142
- `))return e;let n=t.slice(t.lastIndexOf(`
143
- `)+1).match(/^(\s+)/);if(n){let t=n[1];return e.replace(/\n/g,`\n${t}`)}return e}function GO(e){let t=e.split(`
144
- `),n=null;for(let e of t){let t=e.match(/^(\s+)\S+/);if(t){let e=t[1].length;n=n===null?e:Math.min(n,e)}}return n===null?e:t.map(e=>e[0]===` `||e[0]===` `?e.slice(n):e).join(`
145
- `)}var KO=o({EventStreamContentType:()=>qO,convertEventStreamToIterableReadableDataStream:()=>$O,getBytes:()=>JO,getLines:()=>YO,getMessages:()=>XO}),qO=`text/event-stream`;async function JO(e,t){if(e instanceof ReadableStream){let n=e.getReader();for(;;){let e=await n.read();if(e.done){t(new Uint8Array,!0);break}t(e.value)}}else try{for await(let n of e)t(new Uint8Array(n));t(new Uint8Array,!0)}catch(e){throw Error([`Parsing event source stream failed.`,`Ensure your implementation of fetch returns a web or Node readable stream.`,`Error: ${e.message}`].join(`
146
- `))}}function YO(e){let t,n,r,i=!1;return function(a,o){if(o){e(a,0,!0);return}t===void 0?(t=a,n=0,r=-1):t=ZO(t,a);let s=t.length,c=0;for(;n<s;){i&&=(t[n]===10&&(c=++n),!1);let a=-1;for(;n<s&&a===-1;++n)switch(t[n]){case 58:r===-1&&(r=n-c);break;case 13:i=!0;case 10:a=n;break}if(a===-1)break;e(t.subarray(c,a),r),c=n,r=-1}c===s?t=void 0:c!==0&&(t=t.subarray(c),n-=c)}}function XO(e,t,n){let r=QO(),i=new TextDecoder;return function(a,o,s){if(s){ek(r)||(e?.(r),r=QO());return}if(a.length===0)e?.(r),r=QO();else if(o>0){let e=i.decode(a.subarray(0,o)),s=o+(a[o+1]===32?2:1),c=i.decode(a.subarray(s));switch(e){case`data`:r.data=r.data?r.data+`
147
- `+c:c;break;case`event`:r.event=c;break;case`id`:t?.(r.id=c);break;case`retry`:{let e=parseInt(c,10);Number.isNaN(e)||n?.(r.retry=e);break}}}}}function ZO(e,t){let n=new Uint8Array(e.length+t.length);return n.set(e),n.set(t,e.length),n}function QO(){return{data:``,event:``,id:``,retry:void 0}}function $O(e,t){let n=new ReadableStream({async start(n){let r=XO(e=>{if(e.event===`error`)throw Error(e.data??`Unspecified event streaming error.`);e.event===`metadata`?t?.(e):e.data&&n.enqueue(e.data)});await JO(e,YO((e,t,i)=>{r(e,t,i),i&&n.close()}))}});return ul.fromReadableStream(n)}function ek(e){return e.data===``&&e.event===``&&e.id===``&&e.retry===void 0}var tk=o({}),nk=o({convertToOpenAIFunction:()=>rk,convertToOpenAITool:()=>ik,isLangChainTool:()=>GE,isRunnableToolLike:()=>UE,isStructuredTool:()=>HE,isStructuredToolParams:()=>WE});function rk(e,t){let n=typeof t==`number`?void 0:t;return{name:e.name,description:e.description,parameters:Bv(e.schema),...n?.strict===void 0?{}:{strict:n.strict}}}function ik(e,t){let n=typeof t==`number`?void 0:t,r;return r=GE(e)?{type:`function`,function:rk(e)}:e,n?.strict!==void 0&&(r.function.strict=n.strict),r}function ak(e,t){let n=0,r=0,i=0;for(let a=0;a<e.length;a++)n+=e[a]*t[a],r+=e[a]*e[a],i+=t[a]*t[a];return n/(Math.sqrt(r)*Math.sqrt(i))}function ok(e,t){let n=0;for(let r=0;r<e.length;r++)n+=e[r]*t[r];return n}function sk(e,t){let n=0;for(let r=0;r<e.length;r++)n+=(e[r]-t[r])*(e[r]-t[r]);return n}function ck(e,t){return Math.sqrt(sk(e,t))}var lk=o({cosineSimilarity:()=>fk,euclideanDistance:()=>mk,innerProduct:()=>pk,matrixFunc:()=>uk,maximalMarginalRelevance:()=>hk,normalize:()=>dk});function uk(e,t,n){if(e.length===0||e[0].length===0||t.length===0||t[0].length===0)return[[]];if(e[0].length!==t[0].length)throw Error(`Number of columns in X and Y must be the same. X has shape ${[e.length,e[0].length]} and Y has shape ${[t.length,t[0].length]}.`);return e.map(e=>t.map(t=>n(e,t)).map(e=>Number.isNaN(e)?0:e))}function dk(e,t=!1){let n=_k(e);return e.map(e=>e.map(e=>t?1-e/n:e/n))}function fk(e,t){return uk(e,t,ak)}function pk(e,t){return uk(e,t,ok)}function mk(e,t){return uk(e,t,ck)}function hk(e,t,n=.5,r=4){if(Math.min(r,t.length)<=0)return[];let i=fk(Array.isArray(e[0])?e:[e],t)[0],a=gk(i).maxIndex,o=[t[a]],s=[a];for(;s.length<Math.min(r,t.length);){let e=-1/0,r=-1,a=fk(t,o);i.forEach((t,i)=>{if(s.includes(i))return;let o=Math.max(...a[i]),c=n*t-(1-n)*o;c>e&&(e=c,r=i)}),o.push(t[r]),s.push(r)}return s}function gk(e){if(e.length===0)return{maxIndex:-1,maxValue:NaN};let t=e[0],n=0;for(let r=1;r<e.length;r+=1)e[r]>t&&(n=r,t=e[r]);return{maxIndex:n,maxValue:t}}function _k(e){return e.reduce((e,t)=>Math.max(e,gk(t).maxValue),0)}var vk=o({isCloudMetadata:()=>Mk,isLocalhost:()=>Nk,isPrivateIp:()=>jk,isSafeUrl:()=>Fk,isSameOrigin:()=>Ik,validateSafeUrl:()=>Pk}),yk=[`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`],bk=[`169.254.169.254`,`169.254.170.2`,`100.100.100.200`],xk=[`metadata.google.internal`,`metadata`,`instance-data`],Sk=[`localhost`,`localhost.localdomain`],Ck=/^(?:(?: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 wk(e){return Ck.test(e)}function Tk(e){return Ok(e)!==null}function Ek(e){return wk(e)||Tk(e)}function Dk(e){if(wk(e))return e.split(`.`).map(e=>parseInt(e,10));if(Tk(e)){let t=Ok(e);if(!t)return null;let n=t.split(`:`),r=[];for(let e of n)r.push(parseInt(e,16));return r}return null}function Ok(e){if(!e||typeof e!=`string`||!e.includes(`:`)||!/^[0-9a-fA-F:]+$/.test(e))return null;let t=e;if(t.includes(`::`)){let e=t.split(`::`);if(e.length>2)return null;let[n,r]=e,i=n?n.split(`:`):[],a=r?r.split(`:`):[],o=8-(i.length+a.length);if(o<0)return null;let s=Array(o).fill(`0`);t=[...i,...s,...a].filter(e=>e!==``).join(`:`)}let n=t.split(`:`);if(n.length!==8)return null;for(let e of n)if(e.length===0||e.length>4||!/^[0-9a-fA-F]+$/.test(e))return null;return n.map(e=>e.padStart(4,`0`).toLowerCase()).join(`:`)}function kk(e){let[t,n]=e.split(`/`);if(!t||!n)return null;let r=Dk(t);if(!r)return null;let i=parseInt(n,10);if(isNaN(i))return null;let a=Tk(t);return a&&i>128||!a&&i>32?null:{addr:r,prefixLen:i,isIpv6:a}}function Ak(e,t){let n=Dk(e);if(!n)return!1;let r=kk(t);if(!r)return!1;let i=Tk(e);if(i!==r.isIpv6)return!1;let{addr:a,prefixLen:o}=r;if(i)for(let e=0;e<Math.ceil(o/16);e++){let t=65535<<16-Math.min(16,o-e*16)&65535;if((n[e]&t)!==(a[e]&t))return!1}else for(let e=0;e<Math.ceil(o/8);e++){let t=255<<8-Math.min(8,o-e*8)&255;if((n[e]&t)!==(a[e]&t))return!1}return!0}function jk(e){if(!Ek(e))return!1;for(let t of yk)if(Ak(e,t))return!0;return!1}function Mk(e,t){if(bk.includes(t||``))return!0;let n=e.toLowerCase();return!!xk.includes(n)}function Nk(e,t){if(t&&(t===`127.0.0.1`||t===`::1`||t===`0.0.0.0`||t.startsWith(`127.`)))return!0;let n=e.toLowerCase();return!!Sk.includes(n)}function Pk(e,t){let n=t?.allowPrivate??!1,r=t?.allowHttp??!1;try{let t;try{t=new URL(e)}catch{throw Error(`Invalid URL: ${e}`)}let i=t.hostname;if(!i)throw Error(`URL missing hostname.`);if(Mk(i))throw Error(`URL points to cloud metadata endpoint: ${i}`);if(Nk(i)){if(!n)throw Error(`URL points to localhost: ${i}`);return e}let a=t.protocol;if(a!==`http:`&&a!==`https:`)throw Error(`Invalid URL scheme: ${a}. Only http and https are allowed.`);if(a===`http:`&&!r)throw Error(`HTTP scheme not allowed. Use HTTPS or set allowHttp: true.`);if(Ek(i)){let t=i;if(Nk(i,t)){if(!n)throw Error(`URL points to localhost: ${i}`);return e}if(Mk(i,t))throw Error(`URL resolves to cloud metadata IP: ${t} (${i})`);if(jk(t)&&!n)throw Error(`URL resolves to private IP: ${t} (${i}). Set allowPrivate: true to allow.`);return e}return e}catch(e){throw e&&typeof e==`object`&&`message`in e?e:Error(`URL validation failed: ${e}`)}}function Fk(e,t){try{return Pk(e,t),!0}catch{return!1}}function Ik(e,t){try{return new URL(e).origin===new URL(t).origin}catch{return!1}}var Lk=o({SaveableVectorStore:()=>Bk,VectorStore:()=>zk,VectorStoreRetriever:()=>Rk}),Rk=class extends eE{static lc_name(){return`VectorStoreRetriever`}get lc_namespace(){return[`langchain_core`,`vectorstores`]}vectorStore;k=4;searchType=`similarity`;searchKwargs;filter;_vectorstoreType(){return this.vectorStore._vectorstoreType()}constructor(e){super(e),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)}async _getRelevantDocuments(e,t){if(this.searchType===`mmr`){if(typeof this.vectorStore.maxMarginalRelevanceSearch!=`function`)throw 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},t?.getChild(`vectorstore`))}return this.vectorStore.similaritySearch(e,this.k,this.filter,t?.getChild(`vectorstore`))}async addDocuments(e,t){return this.vectorStore.addDocuments(e,t)}},zk=class extends ge{lc_namespace=[`langchain`,`vectorstores`,this._vectorstoreType()];embeddings;constructor(e,t){super(t),this.embeddings=e}async delete(e){throw Error(`Not implemented.`)}async similaritySearch(e,t=4,n=void 0,r=void 0){return(await this.similaritySearchVectorWithScore(await this.embeddings.embedQuery(e),t,n)).map(e=>e[0])}async similaritySearchWithScore(e,t=4,n=void 0,r=void 0){return this.similaritySearchVectorWithScore(await this.embeddings.embedQuery(e),t,n)}static fromTexts(e,t,n,r){throw Error(`the Langchain vectorstore implementation you are using forgot to override this, please report a bug`)}static fromDocuments(e,t,n){throw Error(`the Langchain vectorstore implementation you are using forgot to override this, please report a bug`)}asRetriever(e,t,n,r,i,a){if(typeof e==`number`)return new Rk({vectorStore:this,k:e,filter:t,tags:[...r??[],this._vectorstoreType()],metadata:i,verbose:a,callbacks:n});{let t={vectorStore:this,k:e?.k,filter:e?.filter,tags:[...e?.tags??[],this._vectorstoreType()],metadata:e?.metadata,verbose:e?.verbose,callbacks:e?.callbacks,searchType:e?.searchType};return e?.searchType===`mmr`?new Rk({...t,searchKwargs:e.searchKwargs}):new Rk({...t})}}},Bk=class extends zk{static load(e,t){throw Error(`Not implemented`)}},Vk=class extends xw{_combineLLMOutput(){return[]}_llmType(){return`fake`}async _generate(e,t,n){if(t?.stop?.length)return{generations:[{message:new qt(t.stop[0]),text:t.stop[0]}]};let r=e.map(e=>typeof e.content==`string`?e.content:JSON.stringify(e.content,null,2)).join(`
148
- `);return await n?.handleLLMNewToken(r),{generations:[{message:new qt(r),text:r}],llmOutput:{}}}},Hk=class e extends xw{sleep=50;responses=[];chunks=[];toolStyle=`openai`;thrownErrorString;tools=[];constructor({sleep:e=50,responses:t=[],chunks:n=[],toolStyle:r=`openai`,thrownErrorString:i,...a}){super(a),this.sleep=e,this.responses=t,this.chunks=n,this.toolStyle=r,this.thrownErrorString=i}_llmType(){return`fake`}bindTools(t){let n=[...this.tools,...t],r=n.map(e=>{switch(this.toolStyle){case`openai`:return{type:`function`,function:{name:e.name,description:e.description,parameters:Bv(e.schema)}};case`anthropic`:return{name:e.name,description:e.description,input_schema:Bv(e.schema)};case`bedrock`:return{toolSpec:{name:e.name,description:e.description,inputSchema:Bv(e.schema)}};case`google`:return{name:e.name,description:e.description,parameters:Bv(e.schema)};default:throw Error(`Unsupported tool style: ${this.toolStyle}`)}}),i=this.toolStyle===`google`?[{functionDeclarations:r}]:r,a=new e({sleep:this.sleep,responses:this.responses,chunks:this.chunks,toolStyle:this.toolStyle,thrownErrorString:this.thrownErrorString});return a.tools=n,a.withConfig({tools:i})}async _generate(e,t,n){if(this.thrownErrorString)throw Error(this.thrownErrorString);return{generations:[{text:``,message:new qt({content:this.responses?.[0]?.content??e[0].content??``,tool_calls:this.chunks?.[0]?.tool_calls})}]}}async*_streamResponseChunks(e,t,n){if(this.thrownErrorString)throw Error(this.thrownErrorString);if(this.chunks?.length){for(let e of this.chunks){let r=new Xl({message:new Xt({content:e.content,tool_calls:e.tool_calls,additional_kwargs:e.additional_kwargs??{}}),text:e.content?.toString()??``});if(t.signal?.aborted)break;yield r,await n?.handleLLMNewToken(e.content,void 0,void 0,void 0,void 0,{chunk:r})}return}let r=this.responses?.[0]??new qt(typeof e[0].content==`string`?e[0].content:``),i=typeof r.content==`string`?r.content:``;for(let e of i){await new Promise(e=>setTimeout(e,this.sleep));let r=new Xl({message:new Xt({content:e}),text:e});if(t.signal?.aborted)break;yield r,await n?.handleLLMNewToken(e,void 0,void 0,void 0,void 0,{chunk:r})}}},Uk=class e extends xw{static lc_name(){return`FakeListChatModel`}lc_serializable=!0;responses;i=0;sleep;emitCustomEvent=!1;generationInfo;tools=[];toolStyle=`openai`;constructor(e){super(e);let{responses:t,sleep:n,emitCustomEvent:r,generationInfo:i}=e;this.responses=t,this.sleep=n,this.emitCustomEvent=r??this.emitCustomEvent,this.generationInfo=i}_combineLLMOutput(){return[]}_llmType(){return`fake-list`}async _generate(e,t,n){if(await this._sleepIfRequested(),t?.thrownErrorString)throw Error(t.thrownErrorString);if(this.emitCustomEvent&&await n?.handleCustomEvent(`some_test_event`,{someval:!0}),t?.stop?.length)return{generations:[this._formatGeneration(t.stop[0])]};{let e=this._currentResponse();return this._incrementResponse(),{generations:[this._formatGeneration(e)],llmOutput:{}}}}_formatGeneration(e){return{message:new qt(e),text:e}}async*_streamResponseChunks(e,t,n){let r=this._currentResponse();this._incrementResponse(),this.emitCustomEvent&&await n?.handleCustomEvent(`some_test_event`,{someval:!0});let i=[...r];for(let e=0;e<i.length;e++){let r=i[e],a=e===i.length-1;if(await this._sleepIfRequested(),t?.thrownErrorString)throw Error(t.thrownErrorString);let o=this._createResponseChunk(r,a?this.generationInfo:void 0);if(t.signal?.aborted)break;yield o,n?.handleLLMNewToken(r)}}async _sleepIfRequested(){this.sleep!==void 0&&await this._sleep()}async _sleep(){return new Promise(e=>{setTimeout(()=>e(),this.sleep)})}_createResponseChunk(e,t){return new Xl({message:new Xt({content:e}),text:e,generationInfo:t})}_currentResponse(){return this.responses[this.i]}_incrementResponse(){this.i<this.responses.length-1?this.i+=1:this.i=0}bindTools(t){let n=[...this.tools,...t],r=n.map(e=>{switch(this.toolStyle){case`openai`:return{type:`function`,function:{name:e.name,description:e.description,parameters:Bv(e.schema)}};case`anthropic`:return{name:e.name,description:e.description,input_schema:Bv(e.schema)};case`bedrock`:return{toolSpec:{name:e.name,description:e.description,inputSchema:Bv(e.schema)}};case`google`:return{name:e.name,description:e.description,parameters:Bv(e.schema)};default:throw Error(`Unsupported tool style: ${this.toolStyle}`)}}),i=this.toolStyle===`google`?[{functionDeclarations:r}]:r,a=new e({responses:this.responses,sleep:this.sleep,emitCustomEvent:this.emitCustomEvent,generationInfo:this.generationInfo});return a.tools=n,a.toolStyle=this.toolStyle,a.i=this.i,a.withConfig({tools:i})}withStructuredOutput(e,t){return dy.from(async e=>{let t=await this.invoke(e);if(t.tool_calls?.[0]?.args)return t.tool_calls[0].args;if(typeof t.content==`string`)return JSON.parse(t.content);throw Error(`No structured output found`)})}},Wk=class extends gS{vectorSize;constructor(e){super(e??{}),this.vectorSize=e?.vectorSize??4}async embedDocuments(e){return Promise.all(e.map(e=>this.embedQuery(e)))}async embedQuery(e){let t=e;t=t.toLowerCase().replaceAll(/[^a-z ]/g,``);let n=t.length%this.vectorSize,r=n===0?0:this.vectorSize-n,i=t.length+r;t=t.padEnd(i,` `);let a=t.length/this.vectorSize,o=[];for(let e=0;e<t.length;e+=a)o.push(t.slice(e,e+a));return o.map(e=>{let t=0;for(let n=0;n<e.length;n+=1)t+=e===` `?0:e.charCodeAt(n);return t%26/26})}},Gk=class extends gS{constructor(e){super(e??{})}embedDocuments(e){return Promise.resolve(e.map(()=>[.1,.2,.3,.4]))}embedQuery(e){return Promise.resolve([.1,.2,.3,.4])}},Kk=class extends Ew{response;thrownErrorString;constructor(e){super(e),this.response=e.response,this.thrownErrorString=e.thrownErrorString}_llmType(){return`fake`}async _call(e,t,n){if(this.thrownErrorString)throw Error(this.thrownErrorString);let r=this.response??e;return await n?.handleLLMNewToken(r),r}},qk=class extends Ew{sleep=50;responses;thrownErrorString;constructor(e){super(e),this.sleep=e.sleep??this.sleep,this.responses=e.responses,this.thrownErrorString=e.thrownErrorString}_llmType(){return`fake`}async _call(e){if(this.thrownErrorString)throw Error(this.thrownErrorString);let t=this.responses?.[0];return this.responses=this.responses?.slice(1),t??e}async*_streamResponseChunks(e,t,n){if(this.thrownErrorString)throw Error(this.thrownErrorString);let r=this.responses?.[0];this.responses=this.responses?.slice(1);for(let t of r??e)await new Promise(e=>setTimeout(e,this.sleep)),yield{text:t,generationInfo:{}},await n?.handleLLMNewToken(t)}},Jk=class extends rS{lc_namespace=[`langchain_core`,`message`,`fake`];messages=[];constructor(){super()}async getMessages(){return this.messages}async addMessage(e){this.messages.push(e)}async addUserMessage(e){this.messages.push(new on(e))}async addAIMessage(e){this.messages.push(new qt(e))}async clear(){this.messages=[]}},Yk=class extends iS{lc_namespace=[`langchain_core`,`message`,`fake`];messages=[];constructor(){super()}async addMessage(e){this.messages.push(e)}async getMessages(){return this.messages}},Xk=class extends nc{name=`fake_tracer`;runs=[];constructor(){super()}persistRun(e){return this.runs.push(e),Promise.resolve()}},Zk=class extends pC{lc_namespace=[`tests`,`fake`];getFormatInstructions(){return``}async parse(e){return e.split(`,`).map(e=>e.trim())}},Qk=class extends eE{lc_namespace=[`test`,`fake`];output=[new oS({pageContent:`foo`}),new oS({pageContent:`bar`})];constructor(e){super(),this.output=e?.output??this.output}async _getRelevantDocuments(e){return this.output}},$k=class extends ry{lc_namespace=[`tests`,`fake`];returnOptions;constructor(e){super(e),this.returnOptions=e.returnOptions}async invoke(e,t){return this.returnOptions?t??{}:{input:e}}},eA=class extends kO{name;description;schema;constructor(e){super(e),this.name=e.name,this.description=e.description,this.schema=e.schema}async _call(e,t){return JSON.stringify(e)}},tA=class extends nc{runPromiseResolver;runPromise;name=`single_run_extractor`;constructor(){super(),this.runPromise=new Promise(e=>{this.runPromiseResolver=e})}async persistRun(e){this.runPromiseResolver(e)}async extract(){return this.runPromise}},nA=class e extends zk{memoryVectors=[];similarity;_vectorstoreType(){return`memory`}constructor(e,{similarity:t,...n}={}){super(e,n),this.similarity=t??ak}async addDocuments(e){let t=e.map(({pageContent:e})=>e);return this.addVectors(await this.embeddings.embedDocuments(t),e)}async addVectors(e,t){let n=e.map((e,n)=>({content:t[n].pageContent,embedding:e,metadata:t[n].metadata}));this.memoryVectors=this.memoryVectors.concat(n)}async similaritySearchVectorWithScore(e,t,n){let r=this.memoryVectors.filter(e=>n?n(new oS({metadata:e.metadata,pageContent:e.content})):!0);return r.map((t,n)=>({similarity:this.similarity(e,t.embedding),index:n})).sort((e,t)=>e.similarity>t.similarity?-1:0).slice(0,t).map(e=>[new oS({metadata:r[e.index].metadata,pageContent:r[e.index].content}),e.similarity])}static async fromTexts(t,n,r,i){let a=[];for(let e=0;e<t.length;e+=1){let r=Array.isArray(n)?n[e]:n,i=new oS({pageContent:t[e],metadata:r});a.push(i)}return e.fromDocuments(a,r,i)}static async fromDocuments(e,t,n){let r=new this(t,n);return await r.addDocuments(e),r}static async fromExistingIndex(e,t){return new this(e,t)}},rA=o({FakeChatMessageHistory:()=>Jk,FakeChatModel:()=>Vk,FakeEmbeddings:()=>Gk,FakeLLM:()=>Kk,FakeListChatMessageHistory:()=>Yk,FakeListChatModel:()=>Uk,FakeRetriever:()=>Qk,FakeRunnable:()=>$k,FakeSplitIntoListParser:()=>Zk,FakeStreamingChatModel:()=>Hk,FakeStreamingLLM:()=>qk,FakeTool:()=>eA,FakeTracer:()=>Xk,FakeVectorStore:()=>nA,SingleRunExtractor:()=>tA,SyntheticEmbeddings:()=>Wk}),iA=o({agents:()=>Vx,caches:()=>Yx,callbacks__base:()=>mr,callbacks__manager:()=>Rc,callbacks__promises:()=>Nc,chat_history:()=>nS,document_loaders__base:()=>uS,document_loaders__langsmith:()=>fS,documents:()=>lS,embeddings:()=>hS,errors:()=>l,example_selectors:()=>ES,index:()=>Bx,indexing:()=>FS,language_models__base:()=>nC,language_models__chat_models:()=>yw,language_models__compat:()=>ow,language_models__event:()=>Cw,language_models__llms:()=>ww,language_models__profile:()=>Dw,language_models__stream:()=>KC,language_models__structured_output:()=>HC,load__serializable:()=>fe,memory:()=>Ow,messages:()=>Ry,messages__tool:()=>ht,output_parsers:()=>FC,output_parsers__openai_functions:()=>Lw,output_parsers__openai_tools:()=>Rw,outputs:()=>ql,prompt_values:()=>IS,prompts:()=>XT,retrievers:()=>$T,retrievers__document_compressors:()=>ZT,runnables:()=>By,runnables__graph:()=>Hv,singletons:()=>Qc,stores:()=>tE,structured_query:()=>SE,testing:()=>VE,tools:()=>OO,tracers__base:()=>Zs,tracers__console:()=>ic,tracers__log_stream:()=>zl,tracers__run_collector:()=>LO,tracers__tracer_langchain:()=>yc,types__stream:()=>zO,utils__async_caller:()=>du,utils__chunk_array:()=>BO,utils__context:()=>HO,utils__env:()=>ir,utils__event_source_parse:()=>KO,utils__format:()=>tk,utils__function_calling:()=>nk,utils__hash:()=>Jx,utils__json_patch:()=>dC,utils__json_schema:()=>Rv,utils__math:()=>lk,utils__ssrf:()=>vk,utils__standard_schema:()=>X_,utils__stream:()=>ll,utils__testing:()=>rA,utils__tiktoken:()=>ZS,utils__types:()=>IC,utils__uuid:()=>rr,vectorstores:()=>Lk}),aA=50;function oA(e){let t={};for(let n=e;n&&n.prototype;n=Object.getPrototypeOf(n))Object.assign(t,Reflect.get(n.prototype,`lc_aliases`));return Object.entries(t).reduce((e,[t,n])=>(e[n]=t,e),{})}async function sA(e){let{optionalImportsMap:t,optionalImportEntrypoints:n,importMap:r,secretsMap:i,secretsFromEnv:a,path:o,depth:s,maxDepth:c}=this,l=o.join(`.`);if(s>c)throw Error(`Maximum recursion depth (${c}) exceeded during deserialization. This may indicate a malicious payload or you may need to increase maxDepth.`);if(typeof e!=`object`||!e)return e;if(Array.isArray(e))return Promise.all(e.map((e,t)=>sA.call({...this,path:[...o,`${t}`],depth:s+1},e)));let u=e;if(ce(u))return de(u);if(`lc`in u&&`type`in u&&`id`in u&&u.lc===1&&u.type===`secret`){let[e]=u.id;if(e in i)return i[e];if(a){let t=pr(e);if(t)return t}throw Error(`Missing secret "${e}" at ${l}`)}if(`lc`in u&&`type`in u&&`id`in u&&u.lc===1&&u.type===`not_implemented`){let e=JSON.stringify(u);throw Error(`Trying to load an object that doesn't implement serialization: ${l} -> ${e}`)}if(`lc`in u&&`type`in u&&`id`in u&&`kwargs`in u&&u.lc===1&&u.type===`constructor`){let e=u,i=JSON.stringify(e),[a,...c]=e.id.slice().reverse(),d=c.reverse(),f={langchain_core:iA,langchain:r},p=null,m=[d.join(`/`)];d[0]===`langchain_community`&&m.push([`langchain`,...d.slice(1)].join(`/`));let h=m.find(e=>e in t);if(zx.concat(n).includes(d.join(`/`))||h)if(h!==void 0)p=await t[h];else throw Error(`Missing key "${d.join(`/`)}" for ${l} in load(optionalImportsMap={})`);else{let e;if(d[0]===`langchain`||d[0]===`langchain_core`)e=f[d[0]],d.shift();else throw Error(`Invalid namespace: ${l} -> ${i}`);if(d.length===0)throw Error(`Invalid namespace: ${l} -> ${i}`);let t;do{if(t=d.join(`__`),t in e)break;d.pop()}while(d.length>0);t in e&&(p=e[t])}if(typeof p!=`object`||!p)throw Error(`Invalid namespace: ${l} -> ${i}`);let g=p[a]??Object.values(p).find(e=>typeof e==`function`&&he(e)===a);if(typeof g!=`function`)throw Error(`Invalid identifer: ${l} -> ${i}`);let _=new g(ie(await sA.call({...this,path:[...o,`kwargs`],depth:s+1},e.kwargs),re,oA(g)));return Object.defineProperty(_.constructor,`name`,{value:a}),_}let d={};for(let[e,t]of Object.entries(u))d[e]=await sA.call({...this,path:[...o,e],depth:s+1},t);return d}async function cA(e,t){let n=JSON.parse(e),r={optionalImportsMap:t?.optionalImportsMap??{},optionalImportEntrypoints:t?.optionalImportEntrypoints??[],secretsMap:t?.secretsMap??{},secretsFromEnv:t?.secretsFromEnv??!1,importMap:t?.importMap??{},path:[`$`],depth:0,maxDepth:t?.maxDepth??aA};return sA.call(r,n)}function lA(e){return e!==null&&e.lc===1&&e.type===`constructor`&&Array.isArray(e.id)}async function uA(e){if(e&&typeof e==`object`){if(Array.isArray(e))return await Promise.all(e.map(e=>uA(e)));{let t={};for(let[n,r]of Object.entries(e))t[n]=await uA(r);if(t.lc===2&&t.type===`undefined`)return;if(t.lc===2&&t.type===`constructor`&&Array.isArray(t.id))try{let e=t.id[t.id.length-1],n;switch(e){case`Set`:n=Set;break;case`Map`:n=Map;break;case`RegExp`:n=RegExp;break;case`Error`:n=Error;break;case`Uint8Array`:n=Uint8Array;break;default:return t}return t.method?n[t.method](...t.args||[]):new n(...t.args||[])}catch{return t}else if(lA(t))return cA(JSON.stringify(t));return t}}return e}function dA(e,t,n,r){return{lc:2,type:`constructor`,id:[e.name],method:t??null,args:n??[],kwargs:r??{}}}function fA(e){return e===void 0?{lc:2,type:`undefined`}:e instanceof Set||e instanceof Map?dA(e.constructor,void 0,[Array.from(e)]):e instanceof RegExp?dA(RegExp,void 0,[e.source,e.flags]):e instanceof Error?dA(e.constructor,void 0,[e.message]):e?.lg_name===`Send`?{node:e.node,args:e.args}:e instanceof Uint8Array?dA(Uint8Array,`from`,[Array.from(e)]):e}var pA=class{_dumps(e){return new TextEncoder().encode(Fx(e,(e,t)=>fA(t)))}async dumpsTyped(e){return e instanceof Uint8Array?[`bytes`,e]:[`json`,this._dumps(e)]}async _loads(e){return uA(JSON.parse(e))}async loadsTyped(e,t){if(e===`bytes`)return typeof t==`string`?new TextEncoder().encode(t):t;if(e===`json`)return this._loads(typeof t==`string`?t:new TextDecoder().decode(t));throw Error(`Unknown serialization type: ${e}`)}};function mA(e){if(typeof e!=`object`||!e)return e;let t=Array.isArray(e)?[]:{};for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=mA(e[n]));return t}function hA(){return{v:4,id:wx(-2),ts:new Date().toISOString(),channel_values:{},channel_versions:{},versions_seen:{}}}function gA(e){return{v:e.v,id:e.id,ts:e.ts,channel_values:{...e.channel_values},channel_versions:{...e.channel_versions},versions_seen:mA(e.versions_seen)}}function _A(e,t){return typeof e==`number`&&typeof t==`number`?Math.sign(e-t):String(e).localeCompare(String(t))}function vA(...e){return e.reduce((e,t,n)=>n===0?t:_A(e,t)>=0?e:t)}var yA={[Ex]:-1,[Dx]:-2,[Ox]:-3,[kx]:-4},bA=class extends Error{constructor(e){super(e),this.name=`InvalidNamespaceError`}};function xA(e){if(e.length===0)throw new bA(`Namespace cannot be empty.`);for(let t of e){if(typeof t!=`string`)throw new bA(`Invalid namespace label '${t}' found in ${e}. Namespace labels must be strings, but got ${typeof t}.`);if(t.includes(`.`))throw new bA(`Invalid namespace label '${t}' found in ${e}. Namespace labels cannot contain periods ('.').`);if(t===``)throw new bA(`Namespace labels cannot be empty strings. Got ${t} in ${e}`)}if(e[0]===`langgraph`)throw new bA(`Root label for namespace cannot be "langgraph". Got: ${e}`)}var SA=class{async get(e,t){return(await this.batch([{namespace:e,key:t}]))[0]}async search(e,t={}){let{filter:n,limit:r=10,offset:i=0,query:a}=t;return(await this.batch([{namespacePrefix:e,filter:n,limit:r,offset:i,query:a}]))[0]}async put(e,t,n,r){xA(e),await this.batch([{namespace:e,key:t,value:n,index:r}])}async delete(e,t){await this.batch([{namespace:e,key:t,value:null}])}async listNamespaces(e={}){let{prefix:t,suffix:n,maxDepth:r,limit:i=100,offset:a=0}=e,o=[];return t&&o.push({matchType:`prefix`,path:t}),n&&o.push({matchType:`suffix`,path:n}),(await this.batch([{matchConditions:o.length?o:void 0,maxDepth:r,limit:i,offset:a}]))[0]}start(){}stop(){}},CA=e=>`lg_name`in e&&e.lg_name===`AsyncBatchedStore`?e.store:e,wA=class extends SA{lg_name=`AsyncBatchedStore`;store;queue=new Map;nextKey=0;running=!1;processingTask=null;constructor(e){super(),this.store=CA(e)}get isRunning(){return this.running}async batch(e){throw 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,t){return this.enqueueOperation({namespace:e,key:t})}async search(e,t){let{filter:n,limit:r=10,offset:i=0,query:a}=t||{};return this.enqueueOperation({namespacePrefix:e,filter:n,limit:r,offset:i,query:a})}async put(e,t,n){return this.enqueueOperation({namespace:e,key:t,value:n})}async delete(e,t){return this.enqueueOperation({namespace:e,key:t,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((t,n)=>{let r=this.nextKey;this.nextKey+=1,this.queue.set(r,{operation:e,resolve:t,reject:n})})}async processBatchQueue(){for(;this.running;){if(await new Promise(e=>{setTimeout(e,0)}),this.queue.size===0)continue;let e=new Map(this.queue);this.queue.clear();try{let t=Array.from(e.values()).map(({operation:e})=>e),n=await this.store.batch(t);e.forEach(({resolve:t},r)=>{t(n[Array.from(e.keys()).indexOf(r)])})}catch(t){e.forEach(({reject:e})=>{e(t)})}}}toJSON(){return{queue:this.queue,nextKey:this.nextKey,running:this.running,store:`[LangGraphStore]`}}},TA=class{serde=new pA;constructor(e){this.serde=e||this.serde}};function EA(e){return e!=null&&e.lg_is_channel===!0}var DA=class{ValueType;UpdateType;lg_is_channel=!0;consume(){return!1}finish(){return!1}isAvailable(){try{return this.get(),!0}catch(e){if(e.name===Wb.unminifiable_name)return!1;throw e}}equals(e){return this===e}},OA=Symbol.for(`LG_IS_ONLY_BASE_CHANNEL`);function kA(e){if(e[OA]===!0)return e;let t={};for(let n in e){if(!Object.prototype.hasOwnProperty.call(e,n))continue;let r=e[n];EA(r)&&(t[n]=r)}return Object.assign(t,{[OA]:!0}),t}function AA(e,t){let n=kA(e),r={};for(let e in n){if(!Object.prototype.hasOwnProperty.call(n,e))continue;let i=t.channel_values[e];r[e]=n[e].fromCheckpoint(i)}return Object.assign(r,{[OA]:!0}),r}function jA(e,t,n,r){let i;if(t===void 0)i=e.channel_values;else{i={};for(let e in t)if(Object.prototype.hasOwnProperty.call(t,e))try{i[e]=t[e].checkpoint()}catch(e){if(e.name!==Wb.unminifiable_name)throw e}}return{v:4,id:r?.id??wx(n),ts:new Date().toISOString(),channel_values:i,channel_versions:e.channel_versions,versions_seen:e.versions_seen}}var MA=class e extends DA{lc_graph_name=`LastValue`;value=[];constructor(e){super(),this.initialValueFactory=e,e&&(this.value=[e()])}fromCheckpoint(t){let n=new e(this.initialValueFactory);return t!==void 0&&(n.value=[t]),n}update(e){if(e.length===0)return!1;if(e.length!==1)throw new Gb(`LastValue can only receive one value per step.`,{lc_error_code:`INVALID_CONCURRENT_GRAPH_UPDATE`});return this.value=[e[e.length-1]],!0}get(){if(this.value.length===0)throw new Wb;return this.value[0]}checkpoint(){if(this.value.length===0)throw new Wb;return this.value[0]}isAvailable(){return this.value.length!==0}},NA=class e extends DA{lc_graph_name=`LastValueAfterFinish`;value=[];finished=!1;fromCheckpoint(t){let n=new e;if(t!==void 0){let[e,r]=t;n.value=[e],n.finished=r}return n}update(e){return e.length===0?!1:(this.finished=!1,this.value=[e[e.length-1]],!0)}get(){if(this.value.length===0||!this.finished)throw new Wb;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}},PA=e=>e!=null&&e.lc_graph_name===`BinaryOperatorAggregate`,FA=class e extends DA{lc_graph_name=`BinaryOperatorAggregate`;value;operator;initialValueFactory;constructor(e,t){super(),this.operator=e,this.initialValueFactory=t,this.value=t?.()}fromCheckpoint(t){let n=new e(this.operator,this.initialValueFactory);return t!==void 0&&(n.value=t),n}update(e){let t=e;if(!t.length)return!1;if(this.value===void 0){let e=t[0],[n,r]=Db(e);n?this.value=r:this.value=e,t=t.slice(1)}let n=!1;for(let e of t)if(Ob(e)){if(n)throw new Gb(`Can receive only one Overwrite value per step.`);let[,t]=Db(e);this.value=t,n=!0;continue}else !n&&this.value!==void 0&&(this.value=this.operator(this.value,e));return!0}get(){if(this.value===void 0)throw new Wb;return this.value}checkpoint(){if(this.value===void 0)throw new Wb;return this.value}isAvailable(){return this.value!==void 0}equals(e){return this===e?!0:PA(e)?this.operator===e.operator:!1}},IA=class{lc_graph_name=`AnnotationRoot`;spec;constructor(e){this.spec=e}static isInstance(e){return typeof e==`object`&&!!e&&`lc_graph_name`in e&&e.lc_graph_name===`AnnotationRoot`}},LA=function(e){return e?RA(e):new MA};LA.Root=e=>new IA(e);function RA(e){return typeof e==`object`&&e&&`reducer`in e&&e.reducer?new FA(e.reducer,e.default):typeof e==`object`&&e&&`value`in e&&e.value?new FA(e.value,e.default):new MA}var zA=[`tags`,`metadata`,`callbacks`,`configurable`],BA=[`tags`,`metadata`,`callbacks`,`runName`,`maxConcurrency`,`recursionLimit`,`configurable`,`runId`,`outputKeys`,`streamMode`,`store`,`writer`,`interrupt`,`context`,`interruptBefore`,`interruptAfter`,`checkpointDuring`,`durability`,`signal`,`executionInfo`,`serverInfo`],VA=25,HA=new Set([`thread_id`,`checkpoint_id`,`checkpoint_ns`,`task_id`,`run_id`,`assistant_id`,`graph_id`]);function UA(e,t){if(!e)return t;let n=t??{};for(let t of HA){if(t in n)continue;let r=e[t];r!==void 0&&(n[t]=r)}return n}function WA(...e){let t={tags:[],metadata:{},callbacks:void 0,recursionLimit:VA,configurable:{}},n=Zc.getRunnableConfig();if(n!==void 0){for(let[e,r]of Object.entries(n))if(r!==void 0)if(zA.includes(e)){let n;n=Array.isArray(r)?[...r]:typeof r==`object`?e===`callbacks`&&`copy`in r&&typeof r.copy==`function`?r.copy():{...r}:r,t[e]=n}else t[e]=r}for(let n of e)if(n!==void 0)for(let[e,r]of Object.entries(n))r!==void 0&&BA.includes(e)&&(t[e]=r);return t.metadata=UA(t.configurable,t.metadata)??{},t}function GA(){return Zc.getRunnableConfig()}function KA(e){return e.split(`|`).filter(e=>!e.match(/^\d+$/)).map(e=>e.split(`:`)[0]).join(`|`)}function qA(e){let t=e.split(`|`);for(;t.length>1&&t[t.length-1].match(/^\d+$/);)t.pop();return t.slice(0,-1).join(`|`)}var JA=class extends ry{lc_namespace=[`langgraph`];func;tags;config;trace=!0;recurse=!0;constructor(e){super(),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,t,n){return new Promise((r,i)=>{let a=al(t,{callbacks:n?.getChild()});Zc.runWithConfig(a,async()=>{try{r(await this.func(e,a))}catch(e){i(e)}})})}async invoke(e,t){let n,r=WA(t),i=rl(this.config,r);return n=this.trace?await this._callWithConfig(this._tracedInvoke,e,i):await Zc.runWithConfig(i,async()=>this.func(e,i)),ry.isRunnable(n)&&this.recurse?await Zc.runWithConfig(i,async()=>n.invoke(e,i)):n}};function*YA(e,t){if(t===void 0)yield*e;else for(let n of e)yield[t,n]}async function XA(e){let t=[];for await(let n of await e)t.push(n);return t}function ZA(e){let t=[];for(let n of e)t.push(n);return t}function QA(e,t){return e?`configurable`in e?{...e,configurable:{...e.configurable,...t}}:{...e,configurable:t}:{configurable:t}}function $A(e){return typeof e==`object`&&e?.[Symbol.for(`LG_SKIP_WRITE`)]!==void 0}var ej={[Symbol.for(`LG_PASSTHROUGH`)]:!0};function tj(e){return typeof e==`object`&&e?.[Symbol.for(`LG_PASSTHROUGH`)]!==void 0}var nj=Symbol(`IS_WRITER`),rj=class e extends JA{writes;constructor(e,t){let n=`ChannelWrite<${e.map(e=>Tb(e)?e.node:`channel`in e?e.channel:`...`).join(`,`)}>`;super({writes:e,name:n,tags:t,trace:!1,func:async(e,t)=>this._write(e,t??{})}),this.writes=e}async _write(t,n){let r=this.writes.map(e=>aj(e)&&tj(e.value)?{mapper:e.mapper,value:t}:ij(e)&&tj(e.value)?{channel:e.channel,value:t,skipNone:e.skipNone,mapper:e.mapper}:e);return await e.doWrite(n,r),t}static async doWrite(e,t){for(let e of t){if(ij(e)){if(e.channel===`__pregel_tasks`)throw new Gb(`Cannot write to the reserved channel TASKS`);if(tj(e.value))throw new Gb(`PASSTHROUGH value must be replaced`)}if(aj(e)&&tj(e.value))throw new Gb(`PASSTHROUGH value must be replaced`)}let n=[];for(let r of t)if(Tb(r))n.push([gb,r]);else if(aj(r)){let t=await r.mapper.invoke(r.value,e);t!=null&&t.length>0&&n.push(...t)}else if(ij(r)){let t=r.mapper===void 0?r.value:await r.mapper.invoke(r.value,e);if($A(t)||r.skipNone&&t===void 0)continue;n.push([r.channel,t])}else throw Error(`Invalid write entry: ${JSON.stringify(r)}`);let r=e.configurable?.[Ky];r(n)}static isWriter(t){return t instanceof e||nj in t&&!!t[nj]}static registerWriter(e){return Object.defineProperty(e,nj,{value:!0})}};function ij(e){return e!==void 0&&typeof e.channel==`string`}function aj(e){return e!==void 0&&!ij(e)&&ry.isRunnable(e.mapper)}var oj=class e extends JA{lc_graph_name=`ChannelRead`;channel;fresh=!1;mapper;constructor(t,n,r=!1){super({trace:!1,func:(t,n)=>e.doRead(n,this.channel,this.fresh,this.mapper)}),this.fresh=r,this.mapper=n,this.channel=t,this.name=Array.isArray(t)?`ChannelRead<${t.join(`,`)}>`:`ChannelRead<${t}>`}static doRead(e,t,n,r){let i=e.configurable?.[Jy];if(!i)throw Error(`Runnable is not configured with a read function. Make sure to call in the context of a Pregel process`);return r?r(i(t,n)):i(t,n)}},sj=new yy,cj=class e extends iy{lc_graph_name=`PregelNode`;channels;triggers=[];mapper;writers=[];bound=sj;kwargs={};metadata={};tags=[];retryPolicy;cachePolicy;subgraphs;ends;constructor(e){let{channels:t,triggers:n,mapper:r,writers:i,bound:a,kwargs:o,metadata:s,retryPolicy:c,cachePolicy:l,tags:u,subgraphs:d,ends:f}=e,p=[...e.config?.tags?e.config.tags:[],...u??[]];super({...e,bound:e.bound??sj,config:{...e.config?e.config:{},tags:p}}),this.channels=t,this.triggers=n,this.mapper=r,this.writers=i??this.writers,this.bound=a??this.bound,this.kwargs=o??this.kwargs,this.metadata=s??this.metadata,this.tags=p,this.retryPolicy=c,this.cachePolicy=l,this.subgraphs=d,this.ends=f}getWriters(){let e=[...this.writers];for(;e.length>1&&e[e.length-1]instanceof rj&&e[e.length-2]instanceof rj;){let t=e.slice(-2),n=t[0].writes.concat(t[1].writes);e[e.length-2]=new rj(n,t[0].config?.tags),e.pop()}return e}getNode(){let e=this.getWriters();if(!(this.bound===sj&&e.length===0))return this.bound===sj&&e.length===1?e[0]:this.bound===sj?new sy({first:e[0],middle:e.slice(1,e.length-1),last:e[e.length-1],omitSequenceTags:!0}):e.length>0?new sy({first:this.bound,middle:e.slice(0,e.length-1),last:e[e.length-1],omitSequenceTags:!0}):this.bound}join(t){if(!Array.isArray(t))throw Error(`channels must be a list`);if(typeof this.channels!=`object`)throw Error(`all channels must be named when using .join()`);return new e({channels:{...this.channels,...Object.fromEntries(t.map(e=>[e,e]))},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(t){return rj.isWriter(t)?new e({channels:this.channels,triggers:this.triggers,mapper:this.mapper,writers:[...this.writers,t],bound:this.bound,config:this.config,kwargs:this.kwargs,retryPolicy:this.retryPolicy,cachePolicy:this.cachePolicy}):this.bound===sj?new e({channels:this.channels,triggers:this.triggers,mapper:this.mapper,writers:this.writers,bound:my(t),config:this.config,kwargs:this.kwargs,retryPolicy:this.retryPolicy,cachePolicy:this.cachePolicy}):new e({channels:this.channels,triggers:this.triggers,mapper:this.mapper,writers:this.writers,bound:this.bound.pipe(t),config:this.config,kwargs:this.kwargs,retryPolicy:this.retryPolicy,cachePolicy:this.cachePolicy})}};function lj(e){return`steps`in e&&Array.isArray(e.steps)}function uj(e){return`lg_is_pregel`in e&&e.lg_is_pregel===!0}function dj(e){let t=[e];for(let e of t)if(uj(e))return e;else lj(e)&&t.push(...e.steps)}var fj=class e extends DA{lc_graph_name=`EphemeralValue`;guard;value=[];constructor(e=!0){super(),this.guard=e}fromCheckpoint(t){let n=new e(this.guard);return t!==void 0&&(n.value=[t]),n}update(e){if(e.length===0){let e=this.value.length>0;return this.value=[],e}if(e.length!==1&&this.guard)throw new Gb(`EphemeralValue can only receive one value per step.`);return this.value=[e[e.length-1]],!0}get(){if(this.value.length===0)throw new Wb;return this.value[0]}checkpoint(){if(this.value.length===0)throw new Wb;return this.value[0]}isAvailable(){return this.value.length!==0}},H=e=>BigInt(e),pj=(e,t=0)=>new DataView(e.buffer,e.byteOffset+t,e.byteLength-t),mj=H(`0x9E3779B1`),hj=H(`0x85EBCA77`),gj=H(`0xC2B2AE3D`),_j=H(`0x9E3779B185EBCA87`),vj=H(`0xC2B2AE3D27D4EB4F`),yj=H(`0x165667B19E3779F9`),bj=H(`0x85EBCA77C2B2AE63`),xj=H(`0x27D4EB2F165667C5`),Sj=H(`0x165667919E3779F9`),Cj=H(`0x9FB21C651E98DF25`),wj=(e=>{let t=e.length;if(t%2!=0)throw Error(`String should have an even number of characters`);let n=t/2,r=new Uint8Array(n),i=0,a=0;for(;a<n;){let t=e.slice(i,i+=2);r[a]=Number.parseInt(t,16),a+=1}return pj(r)})(`b8fe6c3923a44bbe7c01812cf721ad1cded46de9839097db7240a4a4b7b3671fcb79e64eccc0e578825ad07dccff7221b8084674f743248ee03590e6813a264c3c2852bb91c300cb88d0658b1b532ea371644897a20df94e3819ef46a9deacd8a8fa763fe39c343ff9dcbbc7c70b4f1d8a51e04bcdb45931c89f7ec9d9787364eac5ac8334d3ebc3c581a0fffa1363eb170ddd51b7f0da49d316552629d4689e2b16be587d47a1fc8ff8b8d17ad031ce45cb3a8f95160428afd7fbcabb4b407e`),Tj=(H(1)<<H(128))-H(1),Ej=(H(1)<<H(64))-H(1),Dj=(H(1)<<H(32))-H(1),Oj=64,kj=Oj/8,Aj=8,jj=4;function Mj(e){if(!e)throw Error(`Assert failed`)}function Nj(e){let t=new DataView(new ArrayBuffer(8));return t.setBigUint64(0,e,!0),t.getBigUint64(0,!1)}function Pj(e){let t=e;return t=(t&H(65535))<<H(16)|(t&H(4294901760))>>H(16),t=(t&H(16711935))<<H(8)|(t&H(4278255360))>>H(8),t}function Fj(e,t){return(e&Dj)*(t&Dj)&Ej}function Ij(e,t){return(e<<t|e>>H(32)-t)&Dj}function Lj(e,t,n){for(let r=0;r<kj;r+=1){let i=t.getBigUint64(r*8,!0),a=i^n.getBigUint64(r*8,!0);e[r^1]+=i,e[r]+=Fj(a,a>>H(32))}return e}function Rj(e,t,n,r){for(let i=0;i<r;i+=1)Lj(e,pj(t,i*Oj),pj(n,i*8));return e}function zj(e,t){for(let n=0;n<kj;n+=1){let r=t.getBigUint64(n*8,!0),i=e[n];i=Xj(i,H(47)),i^=r,i*=mj,e[n]=i&Ej}return e}function Bj(e,t){return Wj(e[0]^t.getBigUint64(0,!0),e[1]^t.getBigUint64(Aj,!0))}function Vj(e,t,n){let r=n;return r+=Bj(e.slice(0),pj(t,0*jj)),r+=Bj(e.slice(2),pj(t,4*jj)),r+=Bj(e.slice(4),pj(t,8*jj)),r+=Bj(e.slice(6),pj(t,12*jj)),qj(r&Ej)}function Hj(e,t,n,r,i){let a=e,o=Math.floor((n.byteLength-Oj)/8),s=Oj*o,c=Math.floor((t.byteLength-1)/s);for(let e=0;e<c;e+=1)a=Rj(a,pj(t,e*s),n,o),a=i(a,pj(n,n.byteLength-Oj));{let e=Math.floor((t.byteLength-1-s*c)/Oj);a=Rj(a,pj(t,c*s),n,e),a=r(a,pj(t,t.byteLength-Oj),pj(n,n.byteLength-Oj-7))}return a}function Uj(e,t){let n=new BigUint64Array([gj,_j,vj,yj,bj,hj,xj,mj]);Mj(e.byteLength>128),n=Hj(n,e,t,Lj,zj),Mj(n.length*8==64);{let r=Vj(n,pj(t,11),H(e.byteLength)*_j&Ej);return Vj(n,pj(t,t.byteLength-Oj-11),~(H(e.byteLength)*vj)&Ej)<<H(64)|r}}function Wj(e,t){let n=e*t&Tj;return n&Ej^n>>H(64)}function Gj(e,t,n){return Wj((e.getBigUint64(0,!0)^t.getBigUint64(0,!0)+n)&Ej,(e.getBigUint64(8,!0)^t.getBigUint64(8,!0)-n)&Ej)}function Kj(e,t,n,r,i){let a=e&Ej,o=e>>H(64)&Ej;return a+=Gj(t,r,i),a^=n.getBigUint64(0,!0)+n.getBigUint64(8,!0),a&=Ej,o+=Gj(n,pj(r,16),i),o^=t.getBigUint64(0,!0)+t.getBigUint64(8,!0),o&=Ej,o<<H(64)|a}function qj(e){let t=e;return t^=t>>H(37),t*=Sj,t&=Ej,t^=t>>H(32),t}function Jj(e){let t=e;return t^=t>>H(33),t*=vj,t&=Ej,t^=t>>H(29),t*=yj,t&=Ej,t^=t>>H(32),t}function Yj(e,t,n){let r=e.byteLength;Mj(r>0&&r<=3);let i=H(e.getUint8(r-1))|H(r<<8)|H(e.getUint8(0)<<16)|H(e.getUint8(r>>1)<<24),a=(i^(H(t.getUint32(0,!0))^H(t.getUint32(4,!0)))+n)&Ej,o=(H(t.getUint32(8,!0))^H(t.getUint32(12,!0)))-n;return(Jj((Ij(Pj(i),H(13))^o)&Ej)&Ej)<<H(64)|Jj(a)}function Xj(e,t){return e^e>>t}function Zj(e,t,n){let r=e.byteLength;Mj(r>=4&&r<=8);{let i=e.getUint32(0,!0),a=e.getUint32(r-4,!0),o=((H(i)|H(a)<<H(32))^(t.getBigUint64(16,!0)^t.getBigUint64(24,!0))+n&Ej)*(_j+(H(r)<<H(2)))&Tj;return o+=(o&Ej)<<H(65),o&=Tj,o^=o>>H(67),Xj(Xj(o&Ej,H(35))*Cj&Ej,H(28))|qj(o>>H(64))<<H(64)}}function Qj(e,t,n){let r=e.byteLength;Mj(r>=9&&r<=16);{let i=(t.getBigUint64(32,!0)^t.getBigUint64(40,!0))+n&Ej,a=(t.getBigUint64(48,!0)^t.getBigUint64(56,!0))-n&Ej,o=e.getBigUint64(0,!0),s=e.getBigUint64(r-8,!0),c=(o^s^i)*_j,l=(c&Ej)+(H(r-1)<<H(54));c=c&(Tj^Ej)|l,s^=a,c+=s+(s&Dj)*(hj-H(1))<<H(64),c&=Tj,c^=Nj(c>>H(64));let u=(c&Ej)*vj;return u+=(c>>H(64))*vj<<H(64),u&=Tj,qj(u&Ej)|qj(u>>H(64))<<H(64)}}function $j(e,t){let n=e.byteLength;return Mj(n<=16),n>8?Qj(e,wj,t):n>=4?Zj(e,wj,t):n>0?Yj(e,wj,t):Jj(t^wj.getBigUint64(64,!0)^wj.getBigUint64(72,!0))|Jj(t^wj.getBigUint64(80,!0)^wj.getBigUint64(88,!0))<<H(64)}function eM(e){return~e+H(1)&Ej}function tM(e,t,n){let r=H(e.byteLength)*_j&Ej,i=H(e.byteLength-1)/H(32);for(;i>=0;){let a=Number(i);r=Kj(r,pj(e,16*a),pj(e,e.byteLength-16*(a+1)),pj(t,32*a),n),i-=H(1)}let a=r+(r>>H(64))&Ej;a=qj(a);let o=(r&Ej)*_j+(r>>H(64))*bj+(H(e.byteLength)-n&Ej)*vj;return o&=Ej,o=eM(qj(o)),a|o<<H(64)}function nM(e,t,n){let r=H(e.byteLength)*_j&Ej;for(let i=32;i<160;i+=32)r=Kj(r,pj(e,i-32),pj(e,i-16),pj(t,i-32),n);r=qj(r&Ej)|qj(r>>H(64))<<H(64);for(let i=160;i<=e.byteLength;i+=32)r=Kj(r,pj(e,i-32),pj(e,i-16),pj(t,3+i-160),n);r=Kj(r,pj(e,e.byteLength-16),pj(e,e.byteLength-32),pj(t,103),eM(n));let i=r+(r>>H(64))&Ej;i=qj(i);let a=(r&Ej)*_j+(r>>H(64))*bj+(H(e.byteLength)-n&Ej)*vj;return a&=Ej,a=eM(qj(a)),i|a<<H(64)}function rM(e,t=H(0)){let n=new TextEncoder,r=pj(typeof e==`string`?n.encode(e):e),i=r.byteLength;return(e=>e.toString(16).padStart(32,`0`))(i<=16?$j(r,t):i<=128?tM(r,wj,t):i<=240?nM(r,wj,t):Uj(r,wj))}function iM(e){return/^[0-9a-f]{32}$/.test(e)}function aM(e,t,n=!0,r=!1){try{return e[t].get()}catch(e){if(e.name===Wb.unminifiable_name){if(r)return e;if(n)return null}throw e}}function oM(e,t,n=!0){if(Array.isArray(t)){let r={};for(let i of t)try{r[i]=aM(e,i,!n)}catch(e){if(e.name===Wb.unminifiable_name)continue}return r}else return aM(e,t)}function*sM(e,t){if(e.graph===Ab.PARENT)throw new Gb(`There is no parent graph.`);if(e.goto){let t;t=Array.isArray(e.goto)?e.goto:[e.goto];for(let e of t)if(Tb(e))yield[yb,gb,e];else if(typeof e==`string`)yield[yb,`branch:to:${e}`,`__start__`];else throw Error(`In Command.send, expected Send or string, got ${typeof e}`)}if(e.resume)if(typeof e.resume==`object`&&Object.keys(e.resume).length&&Object.keys(e.resume).every(iM))for(let[n,r]of Object.entries(e.resume)){let e=t.filter(e=>e[0]===n&&e[1]===`__resume__`).map(e=>e[2]).slice(0,1)??[];e.push(r),yield[n,ub,e]}else yield[yb,ub,e.resume];if(e.update){if(typeof e.update!=`object`||!e.update)throw Error(`Expected cmd.update to be a dict mapping channel names to update values`);if(Array.isArray(e.update))for(let[t,n]of e.update)yield[yb,t,n];else for(let[t,n]of Object.entries(e.update))yield[yb,t,n]}}function*cM(e,t){if(t!=null)if(Array.isArray(e)&&typeof t==`object`&&!Array.isArray(t))for(let n in t)e.includes(n)&&(yield[n,t[n]]);else if(Array.isArray(e))throw Error(`Input chunk must be an object when "inputChannels" is an array`);else yield[e,t]}function*lM(e,t,n){Array.isArray(e)?(t===!0||t.find(([t,n])=>e.includes(t)))&&(yield oM(n,e)):(t===!0||t.some(([t,n])=>t===e))&&(yield aM(n,e))}function*uM(e,t,n){let r=t.filter(([e,t])=>(e.config===void 0||!e.config.tags?.includes(`langsmith:hidden`))&&t[0][0]!==`__error__`&&t[0][0]!==`__interrupt__`);if(!r.length)return;let i;i=r.some(([e])=>e.writes.some(([e,t])=>e===`__return__`))?r.flatMap(([e])=>e.writes.filter(([e,t])=>e===fb).map(([t,n])=>[e.name,n])):Array.isArray(e)?r.flatMap(([t])=>{let{writes:n}=t,r={};for(let[t]of n)e.includes(t)&&(r[t]=(r[t]||0)+1);return Object.values(r).some(e=>e>1)?n.filter(([t])=>e.includes(t)).map(([e,n])=>[t.name,{[e]:n}]):[[t.name,Object.fromEntries(n.filter(([t])=>e.includes(t)))]]}):r.flatMap(([t])=>t.writes.filter(([t,n])=>t===e).map(([e,n])=>[t.name,n]));let a={};for(let[e,t]of i)e in a||(a[e]=[]),a[e].push(t);let o={};for(let e in a)if(a[e].length===1){let[t]=a[e];o[e]=t}else o[e]=a[e];n&&(o.__metadata__={cached:n}),yield o}function dM(e){let t=typeof e[Vy];if(t===`number`)return 0;if(t===`string`)return``;for(let t in e){if(!Object.prototype.hasOwnProperty.call(e,t))continue;let n=typeof e[t];if(n===`number`)return 0;if(n===`string`)return``;break}}function fM(e,t){if(Object.keys(e).length>0){let n=dM(t);return Object.fromEntries(Object.entries(t).filter(([t,r])=>r>(e[t]??n)))}else return t}function pM(e,t){return e&&!Array.isArray(e)&&!(e instanceof Date)&&typeof e==`object`?e:{[t]:e}}function mM(e,t){return e===null?{configurable:t}:e?.configurable===void 0?{...e,configurable:t}:{...e,configurable:{...e.configurable,...t}}}function hM(e,t){let n=t?.parents??{};return Object.keys(n).length>0?mM(e,{[sb]:{...n,[e.configurable?.checkpoint_ns??``]:e.configurable?.checkpoint_id}}):e}function gM(...e){let t=[...new Set(e.filter(Boolean))];if(t.length===0)return{signal:void 0,dispose:void 0};if(t.length===1)return{signal:t[0],dispose:void 0};let n=new AbortController,r=()=>{let e=t.find(e=>e.aborted)?.reason;n.abort(e),t.forEach(e=>e.removeEventListener(`abort`,r))};t.forEach(e=>e.addEventListener(`abort`,r,{once:!0}));let i=t.find(e=>e.aborted);return i&&n.abort(i.reason),{signal:n.signal,dispose:()=>{t.forEach(e=>e.removeEventListener(`abort`,r))}}}var _M=(e,t)=>{if(!(!e&&!t))return e?t?Array.isArray(e)&&Array.isArray(t)?[...e,...t]:Array.isArray(e)?[...e,t]:Array.isArray(t)?[e,...t]:[e,t]:e:t},vM=class{func;name;input;retry;cache;callbacks;__lg_type=`call`;constructor({func:e,name:t,input:n,retry:r,cache:i,callbacks:a}){this.func=e,this.name=t,this.input=n,this.retry=r,this.cache=i,this.callbacks=a}};function yM(e){return typeof e==`object`&&!!e&&`__lg_type`in e&&e.__lg_type===`call`}function bM(e,t){return new sy({name:e,first:new JA({func:e=>t(...e),name:e,trace:!1,recurse:!1}),last:new rj([{channel:fb,value:ej}],[mb])})}var xM=e=>e===void 0?1:e+1;function SM(e,t){if(t==null)return!1;for(let n of e)if(t[n])return!0;return!1}function CM(e){let t;for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t=t==null?e[n]:vA(t,e[n]));return t}function wM(e,t,n){let r=dM(e.channel_versions),i=e.versions_seen.__interrupt__??{},a=!1;if((e.channel_versions.__start__??r)>(i.__start__??r))a=!0;else for(let t in e.channel_versions)if(Object.prototype.hasOwnProperty.call(e.channel_versions,t)&&e.channel_versions[t]>(i[t]??r)){a=!0;break}let o=n.some(e=>t===`*`?!e.config?.tags?.includes(mb):t.includes(e.name));return a&&o}function TM(e,t,n,r,i=!1){let a=new Set;if(Array.isArray(r))a=new Set(r.filter(e=>n.writes.some(([t,n])=>t===e)));else{for(let[e]of n.writes)if(e===r){a=new Set([e]);break}a||=new Set}let o;if(i&&a.size>0){let i=Object.fromEntries(Object.entries(t).filter(([e,t])=>a.has(e))),s=jA(e,i,-1),c=AA(i,s);OM(gA(s),c,[n],void 0,void 0),o=oM({...t,...c},r)}else o=oM(t,r);return o}function EM(e,t,n){for(let[e,r]of n)if([`__pregel_push`,`__pregel_tasks`].includes(e)&&r!=null){if(!Tb(r))throw new Gb(`Invalid packet type, expected SendProtocol, got ${JSON.stringify(r)}`);if(!(r.node in t))throw new Gb(`Invalid node name "${r.node}" in Send packet`)}e(n)}var DM=new Set([db,_b,ub,lb,fb,Wy]);function OM(e,t,n,r,i){n.sort((e,t)=>{let n=e.path?.slice(0,3)||[],r=t.path?.slice(0,3)||[];for(let e=0;e<Math.min(n.length,r.length);e+=1){if(n[e]<r[e])return-1;if(n[e]>r[e])return 1}return n.length-r.length});let a=n.some(e=>e.triggers.length>0),o=kA(t);for(let t of n){e.versions_seen[t.name]??={};for(let n of t.triggers)n in e.channel_versions&&(e.versions_seen[t.name][n]=e.channel_versions[n])}let s=CM(e.channel_versions),c=new Set(n.flatMap(e=>e.triggers).filter(e=>!bb.includes(e))),l=!1;for(let t of c)t in o&&o[t].consume()&&r!==void 0&&(e.channel_versions[t]=r(s),l=!0);let u={};for(let e of n)for(let[t,n]of e.writes)DM.has(t)||t in o&&(u[t]??=[],u[t].push(n));s!=null&&r!=null&&(s=l?r(s):s);let d=new Set;for(let[t,n]of Object.entries(u))if(t in o){let i=o[t],a;try{a=i.update(n)}catch(e){if(e.name===Gb.unminifiable_name){let r=new Gb(`Invalid update for channel "${t}" with values ${JSON.stringify(n)}: ${e.message}`);throw r.lc_error_code=e.lc_error_code,r}else throw e}a&&r!==void 0&&(e.channel_versions[t]=r(s),i.isAvailable()&&d.add(t))}if(a)for(let t in o){if(!Object.prototype.hasOwnProperty.call(o,t))continue;let n=o[t];n.isAvailable()&&!d.has(t)&&n.update([])&&r!==void 0&&(e.channel_versions[t]=r(s),n.isAvailable()&&d.add(t))}if(a&&!SM(d,i))for(let t in o){if(!Object.prototype.hasOwnProperty.call(o,t))continue;let n=o[t];n.finish()&&r!==void 0&&(e.channel_versions[t]=r(s),n.isAvailable()&&d.add(t))}return d}function*kM(e,t,n){if(n.updatedChannels!=null&&n.triggerToNodes!=null){let e=new Set;for(let t of n.updatedChannels){let r=n.triggerToNodes[t];for(let t of r??[])e.add(t)}yield*[...e].sort();return}if(!(()=>{for(let t in e.channel_versions)if(e.channel_versions[t]!==null)return!1;return!0})())for(let e in t)Object.prototype.hasOwnProperty.call(t,e)&&(yield e)}function AM(e,t,n,r,i,a,o){let s={},c=r[gb];if(c?.isAvailable()){let l=c.get().length;for(let c=0;c<l;c+=1){let l=jM([_b,c],e,t,n,r,i,a,o);l!==void 0&&(s[l.id]=l)}}for(let c of kM(e,n,o)){let l=jM([vb,c],e,t,n,r,i,a,o);l!==void 0&&(s[l.id]=l)}return s}function jM(e,t,n,r,i,a,o,s){let{step:c,checkpointer:l,manager:u}=s,d=a.configurable??{},f=d.checkpoint_ns??``;if(e[0]===`__pregel_push`&&yM(e[e.length-1])){let p=e[e.length-1],m=bM(p.name,p.func),h=[_b],g=f===``?p.name:`${f}|${p.name}`,_=Tx(JSON.stringify([g,c.toString(),p.name,_b,e[1],e[2]]),t.id),v=`${g}:${_}`,y=[...e.slice(0,3),!0],b={langgraph_step:c,langgraph_node:p.name,langgraph_triggers:h,langgraph_path:y,langgraph_checkpoint_ns:v,checkpoint_ns:v};if(o){let e=[],o={checkpointId:t.id,checkpointNs:v,taskId:_,threadId:d.thread_id,runId:a.runId==null?void 0:String(a.runId),nodeAttempt:1};return{name:p.name,input:p.input,proc:m,writes:e,config:{...al(rl(a,{metadata:b,store:s.store??a.store}),{runName:p.name,callbacks:u?.getChild(`graph:step:${c}`),configurable:{[Zy]:_,[Ky]:t=>EM(t=>e.push(...t),r,t),[Jy]:(n,r=!1)=>TM(t,i,{name:p.name,writes:e,triggers:h,path:y},n,r),[Yy]:l??d.__pregel_checkpointer,[sb]:{...d[sb],[f]:t.id},[tb]:PM({pendingWrites:n??[],taskId:_,currentTaskInput:p.input,resumeMap:a.configurable?.[eb],namespaceHash:rM(v)}),[nb]:t.channel_values[pb],checkpoint_id:void 0,checkpoint_ns:v}}),executionInfo:o},triggers:h,retry_policy:p.retry,cache_key:p.cache?{key:rM((p.cache.keyFunc??JSON.stringify)([p.input])),ns:[Gy,p.name??`__dynamic__`],ttl:p.cache.ttl}:void 0,id:_,path:y,writers:[]}}else return{id:_,name:p.name,interrupts:[],path:y}}else if(e[0]===`__pregel_push`){let p=typeof e[1]==`number`?e[1]:parseInt(e[1],10);if(!i.__pregel_tasks?.isAvailable())return;let m=i[gb].get();if(p<0||p>=m.length)return;let h=Cb(m[p])&&!Tb(m[p])?new wb(m[p].node,m[p].args):m[p];if(!Cb(h)){console.warn(`Ignoring invalid packet ${JSON.stringify(h)} in pending sends.`);return}if(!(h.node in r)){console.warn(`Ignoring unknown node name ${h.node} in pending sends.`);return}let g=[_b],_=f===``?h.node:`${f}|${h.node}`,v=Tx(JSON.stringify([_,c.toString(),h.node,_b,p.toString()]),t.id),y=`${_}:${v}`,b={langgraph_step:c,langgraph_node:h.node,langgraph_triggers:g,langgraph_path:e.slice(0,3),langgraph_checkpoint_ns:y,checkpoint_ns:y};if(o){let o=r[h.node],p=o.getNode();if(p!==void 0){o.metadata!==void 0&&(b={...b,...o.metadata});let m=[],_={checkpointId:t.id,checkpointNs:y,taskId:v,threadId:d.thread_id,runId:a.runId==null?void 0:String(a.runId),nodeAttempt:1};return{name:h.node,input:h.args,proc:p,subgraphs:o.subgraphs,writes:m,config:{...al(rl(a,{metadata:b,tags:o.tags,store:s.store??a.store}),{runName:h.node,callbacks:u?.getChild(`graph:step:${c}`),configurable:{[Zy]:v,[Ky]:e=>EM(e=>m.push(...e),r,e),[Jy]:(n,r=!1)=>TM(t,i,{name:h.node,writes:m,triggers:g,path:e},n,r),[Yy]:l??d.__pregel_checkpointer,[sb]:{...d[sb],[f]:t.id},[tb]:PM({pendingWrites:n??[],taskId:v,currentTaskInput:h.args,resumeMap:a.configurable?.[eb],namespaceHash:rM(y)}),[nb]:t.channel_values[pb],checkpoint_id:void 0,checkpoint_ns:y}}),executionInfo:_},triggers:g,retry_policy:o.retryPolicy,cache_key:o.cachePolicy?{key:rM((o.cachePolicy.keyFunc??JSON.stringify)([h.args])),ns:[Gy,o.name??`__dynamic__`,h.node],ttl:o.cachePolicy.ttl}:void 0,id:v,path:e,writers:o.getWriters()}}}else return{id:v,name:h.node,interrupts:[],path:e}}else if(e[0]===`__pregel_pull`){let p=e[1].toString(),m=r[p];if(m===void 0)return;if(n?.length){let e=f===``?p:`${f}|${p}`,r=Tx(JSON.stringify([e,c.toString(),p,vb,p]),t.id);if(n.some(e=>e[0]===r&&e[1]!==`__error__`))return}let h=dM(t.channel_versions);if(h===void 0)return;let g=t.versions_seen[p]??{},_=m.triggers.find(e=>i[e].isAvailable()?(t.channel_versions[e]??h)>(g[e]??h):!1);if(_!==void 0){let h=MM(m,i,o);if(h===void 0)return;let g=f===``?p:`${f}|${p}`,v=Tx(JSON.stringify([g,c.toString(),p,vb,[_]]),t.id),y=`${g}:${v}`,b={langgraph_step:c,langgraph_node:p,langgraph_triggers:[_],langgraph_path:e,langgraph_checkpoint_ns:y,checkpoint_ns:y};if(o){let o=m.getNode();if(o!==void 0){m.metadata!==void 0&&(b={...b,...m.metadata});let g=[],ee={checkpointId:t.id,checkpointNs:y,taskId:v,threadId:d.thread_id,runId:a.runId==null?void 0:String(a.runId),nodeAttempt:1};return{name:p,input:h,proc:o,subgraphs:m.subgraphs,writes:g,config:{...al(rl(a,{metadata:b,tags:m.tags,store:s.store??a.store}),{runName:p,callbacks:u?.getChild(`graph:step:${c}`),configurable:{[Zy]:v,[Ky]:e=>EM(e=>{g.push(...e)},r,e),[Jy]:(n,r=!1)=>TM(t,i,{name:p,writes:g,triggers:[_],path:e},n,r),[Yy]:l??d.__pregel_checkpointer,[sb]:{...d[sb],[f]:t.id},[tb]:PM({pendingWrites:n??[],taskId:v,currentTaskInput:h,resumeMap:a.configurable?.[eb],namespaceHash:rM(y)}),[nb]:t.channel_values[pb],checkpoint_id:void 0,checkpoint_ns:y}}),executionInfo:ee},triggers:[_],retry_policy:m.retryPolicy,cache_key:m.cachePolicy?{key:rM((m.cachePolicy.keyFunc??JSON.stringify)([h])),ns:[Gy,m.name??`__dynamic__`,p],ttl:m.cachePolicy.ttl}:void 0,id:v,path:e,writers:m.getWriters()}}}else return{id:v,name:p,interrupts:[],path:e}}}}function MM(e,t,n){let r;if(typeof e.channels==`object`&&!Array.isArray(e.channels)){r={};for(let[n,i]of Object.entries(e.channels))if(e.triggers.includes(i))try{r[n]=aM(t,i,!1)}catch(e){if(e.name===Wb.unminifiable_name)return;throw e}else if(i in t)try{r[n]=aM(t,i,!1)}catch(e){if(e.name===Wb.unminifiable_name)continue;throw e}}else if(Array.isArray(e.channels)){let n=!1;for(let i of e.channels)try{r=aM(t,i,!1),n=!0;break}catch(e){if(e.name===Wb.unminifiable_name)continue;throw e}if(!n)return}else throw Error(`Invalid channels type, expected list or dict, got ${e.channels}`);return n&&e.mapper!==void 0&&(r=e.mapper(r)),r}function NM(e,t){if(typeof e.args!=`object`||e.args===null)return e;let n={};for(let[r,i]of Object.entries(e.args)){let e=t[r];(!e||e.lc_graph_name!==`UntrackedValue`)&&(n[r]=i)}return new wb(e.node,n)}function PM({pendingWrites:e,taskId:t,currentTaskInput:n,resumeMap:r,namespaceHash:i}){let a=e.find(([e,t])=>e===`00000000-0000-0000-0000-000000000000`&&t===`__resume__`)?.[2],o={callCounter:0,interruptCounter:-1,resume:(()=>{let n=e.filter(([e,n])=>e===t&&n===`__resume__`).flatMap(([e,t,n])=>n);if(r!=null&&i in r){let e=r[i];n.push(e)}return n})(),nullResume:a,subgraphCounter:0,currentTaskInput:n,consumeNullResume:()=>{if(o.nullResume)return delete o.nullResume,e.splice(e.findIndex(([e,t])=>e===`00000000-0000-0000-0000-000000000000`&&t===`__resume__`),1),a}};return o}var FM={blue:{start:`\x1B[34m`,end:`\x1B[0m`},green:{start:`\x1B[32m`,end:`\x1B[0m`},yellow:{start:`\x1B[33;1m`,end:`\x1B[0m`}},IM=(e,t)=>`${e.start}${t}${e.end}`;function*LM(e){for(let{id:t,name:n,input:r,config:i,triggers:a,writes:o}of e)i?.tags?.includes(`langsmith:hidden`)||(yield{id:t,name:n,input:r,triggers:a,interrupts:o.filter(([e,n])=>e===t&&n===`__interrupt__`).map(([,e])=>e)})}function RM(e){return typeof e!=`object`||!e?!1:`$writes`in e&&Array.isArray(e.$writes)}function zM(e){let t={};for(let[n,r]of e){let e=String(n);if(e in t){let n=RM(t[e])?t[e].$writes:[t[e]];n.push(r),t[e]={$writes:n}}else t[e]=r}return t}function*BM(e,t){for(let[{id:n,name:r,config:i},a]of e)i?.tags?.includes(`langsmith:hidden`)||(yield{id:n,name:r,result:zM(a.filter(([e])=>Array.isArray(t)?t.includes(e):e===t)),interrupts:a.filter(e=>e[0]===lb).map(e=>e[1])})}function*VM(e,t,n,r,i,a,o,s){function c(e){let t={};return e.callbacks!=null&&(t.callbacks=e.callbacks),e.configurable!=null&&(t.configurable=e.configurable),e.maxConcurrency!=null&&(t.max_concurrency=e.maxConcurrency),e.metadata!=null&&(t.metadata=e.metadata),e.recursionLimit!=null&&(t.recursion_limit=e.recursionLimit),e.runId!=null&&(t.run_id=e.runId),e.runName!=null&&(t.run_name=e.runName),e.tags!=null&&(t.tags=e.tags),t}let l=e.configurable?.checkpoint_ns,u={};for(let t of i){if(!(t.subgraphs?.length?t.subgraphs:[t.proc]).find(dj))continue;let n=`${t.name}:${t.id}`;l&&(n=`${l}|${n}`),u[t.id]={configurable:{thread_id:e.configurable?.thread_id,checkpoint_ns:n}}}yield{config:c(e),values:oM(t,n),metadata:r,next:i.map(e=>e.name),tasks:HM(i,a,u,s),parentConfig:o?c(o):void 0}}function HM(e,t,n,r){return e.map(e=>{let i=t.find(([t,n])=>t===e.id&&n===`__error__`)?.[2],a=t.filter(([t,n])=>t===e.id&&n===`__interrupt__`).map(([,,e])=>e),o=(()=>{if(i||a.length||!t.length)return;let n=t.findIndex(([t,n])=>t===e.id&&n===`__return__`);if(n>=0)return t[n][2];if(typeof r==`string`)return t.find(([t,n])=>t===e.id&&n===r)?.[2];if(Array.isArray(r)){let n=t.filter(([t,n])=>t===e.id&&r.includes(n)).map(([,e,t])=>[e,t]);return n.length?zM(n):void 0}})();if(i)return{id:e.id,name:e.name,path:e.path,error:i,interrupts:a,result:o};let s=n?.[e.id];return{id:e.id,name:e.name,path:e.path,interrupts:a,...s===void 0?{}:{state:s},result:o}})}function UM(e,t,n){console.log([`${IM(FM.blue,`[${e}:checkpoint]`)}`,`\x1b[1m State at the end of step ${e}:\x1b[0m\n`,JSON.stringify(oM(t,n),null,2)].join(``))}function WM(e,t){let n=t.length;console.log([`${IM(FM.blue,`[${e}:tasks]`)}`,`\x1b[1m Starting step ${e} with ${n} task${n===1?``:`s`}:\x1b[0m\n`,t.map(e=>`- ${IM(FM.green,String(e.name))} -> ${JSON.stringify(e.input,null,2)}`).join(`
149
- `)].join(``))}function GM(e,t,n){let r={};for(let[e,i]of t)n.includes(e)&&(r[e]||(r[e]=[]),r[e].push(i));console.log([`${IM(FM.blue,`[${e}:writes]`)}`,`\x1b[1m Finished step ${e} with writes to ${Object.keys(r).length} channel${Object.keys(r).length===1?``:`s`}:\x1b[0m\n`,Object.entries(r).map(([e,t])=>`- ${IM(FM.yellow,e)} -> ${t.map(e=>JSON.stringify(e)).join(`, `)}`).join(`
150
- `)].join(``))}var KM=class extends ul{_abortController;_innerReader;constructor(e,t){let n=e.getReader(),r=t??new AbortController;super({start(e){return t();function t(){return n.read().then(({done:n,value:r})=>{if(n){e.close();return}return e.enqueue(r),t()})}}}),this._abortController=r,this._innerReader=n}async cancel(e){this._abortController.abort(e),this._innerReader.releaseLock()}get signal(){return this._abortController.signal}},qM=class extends ul{modes;controller;passthroughFn;_closed=!1;get closed(){return this._closed}constructor(e){let t,n=new Promise(e=>{t=e});super({start:e=>{t(e)}}),n.then(e=>{this.controller=e}),this.passthroughFn=e.passthroughFn,this.modes=e.modes}push(e){this.passthroughFn?.(e),this.controller.enqueue(e)}close(){try{this.controller.close()}catch{}finally{this._closed=!0}}error(e){this.controller.error(e)}},JM=class extends vr{name=`StreamToolsHandler`;streamFn;runs={};constructor(e){super(),this.streamFn=e}handleToolStart(e,t,n,r,i,a,o,s){if(!a||i&&i.includes(`langsmith:hidden`))return;let c=a.langgraph_checkpoint_ns?.split(`|`)??[],l={ns:c,toolCallId:s,toolName:o??`unknown`,input:t};this.runs[n]=l,this.streamFn([c,`tools`,{event:`on_tool_start`,toolCallId:l.toolCallId,name:l.toolName,input:t}])}handleToolEvent(e,t){let n=this.runs[t];n&&this.streamFn([n.ns,`tools`,{event:`on_tool_event`,toolCallId:n.toolCallId,name:n.toolName,data:e}])}handleToolEnd(e,t){let n=this.runs[t];delete this.runs[t],n&&this.streamFn([n.ns,`tools`,{event:`on_tool_end`,toolCallId:n.toolCallId,name:n.toolName,output:e}])}handleToolError(e,t){let n=this.runs[t];delete this.runs[t],n&&this.streamFn([n.ns,`tools`,{event:`on_tool_error`,toolCallId:n.toolCallId,name:n.toolName,error:e}])}};function YM(e){return JSON.stringify(e,function(e,t){let n=this[e];if(typeof n==`object`&&n&&`toDict`in n&&typeof n.toDict==`function`){let{type:e,data:t}=n.toDict();return{...t,type:e}}return t})}function XM(e){return e instanceof Error?{error:e.name,message:e.message}:{error:`Error`,message:JSON.stringify(e)}}function ZM(e){return typeof e!=`object`||!e?!1:`configurable`in e&&typeof e.configurable==`object`&&e.configurable!=null}function QM(e){return!ZM(e)||!e.configurable.thread_id?null:{thread_id:e.configurable.thread_id,checkpoint_ns:e.configurable.checkpoint_ns||``,checkpoint_id:e.configurable.checkpoint_id||null,checkpoint_map:e.configurable.checkpoint_map||null}}function $M(e){if(ZM(e)){let t=Object.fromEntries(Object.entries(e.configurable).filter(([e])=>!e.startsWith(`__`))),n={...e,configurable:t};return delete n.callbacks,n}return e}function eN(e){let t={...e,checkpoint:QM(e.config),parent_checkpoint:QM(e.parentConfig),config:$M(e.config),parent_config:$M(e.parentConfig),tasks:e.tasks.map(e=>{if(ZM(e.state)){let t=QM(e.state);if(t!=null){let n={...e,checkpoint:t};return delete n.state,n}}return e})};return delete t.parentConfig,t}function tN(e){let t=new TextEncoder;return new ReadableStream({async start(n){let r=e=>{n.enqueue(t.encode(`event: ${e.event}\ndata: ${YM(e.data)}\n\n`))};try{for await(let t of e){let[e,n,i]=t,a=i;if(n===`debug`){let e=i;e.type===`checkpoint`&&(a={...e,payload:eN(e.payload)})}n===`checkpoints`&&(a=eN(i)),r({event:e?.length?`${n}|${e.join(`|`)}`:n,data:a})}}catch(e){r({event:`error`,data:XM(e)})}n.close()}})}var nN=Symbol.for(`INPUT_DONE`),rN=Symbol.for(`INPUT_RESUMING`),iN=25;function aN(...e){return new qM({passthroughFn:t=>{for(let n of e)n.modes.has(t[1])&&n.push(t)},modes:new Set(e.flatMap(e=>Array.from(e.modes)))})}var oN=class extends TA{cache;queue=Promise.resolve();constructor(e){super(),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,...t){let n=this.queue.then(()=>this.cache[e](...t));return this.queue=n.then(()=>void 0,()=>void 0),n}},sN=class e{input;output;config;checkpointer;checkpointerGetNextVersion;channels;checkpoint;checkpointIdSaved;checkpointConfig;checkpointMetadata;checkpointNamespace;checkpointPendingWrites=[];checkpointPreviousVersions;step;stop;durability;outputKeys;streamKeys;nodes;skipDoneTasks;prevCheckpointConfig;updatedChannels;status=`pending`;tasks={};stream;checkpointerPromises=new Set;isNested;_checkpointerChainedPromise=Promise.resolve();_trackCheckpointerPromise(e){let t=e.then(e=>(this.checkpointerPromises.delete(t),e),e=>{throw e});this.checkpointerPromises.add(t)}store;cache;manager;interruptAfter;interruptBefore;toInterrupt=[];debug=!1;triggerToNodes;get isResuming(){let e=!1;if(`__start__`in this.checkpoint.channel_versions)e=!0;else for(let t in this.checkpoint.channel_versions)if(Object.prototype.hasOwnProperty.call(this.checkpoint.channel_versions,t)){e=!0;break}let t=this.config.configurable?.__pregel_resuming!==void 0&&this.config.configurable?.__pregel_resuming,n=this.input===null||this.input===void 0,r=jb(this.input)&&this.input.resume!=null,i=this.input===rN,a=!this.isNested&&this.config.metadata?.run_id!==void 0&&this.checkpointMetadata?.run_id!==void 0&&this.config.metadata.run_id===this.checkpointMetadata?.run_id;return e&&(t||n||r||i||a)}constructor(e){this.input=e.input,this.checkpointer=e.checkpointer,this.checkpointer===void 0?this.checkpointerGetNextVersion=xM:this.checkpointerGetNextVersion=this.checkpointer.getNextVersion.bind(this.checkpointer),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 oN(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}static async initialize(t){let{config:n,stream:r}=t;r!==void 0&&n.configurable?.__pregel_stream!==void 0&&(r=aN(r,n.configurable[Qy]));let i=n.configurable?!(`checkpoint_id`in n.configurable):!0,a=n.configurable?.[tb];n.configurable&&a&&(a.subgraphCounter>0&&(n=mM(n,{[ab]:[n.configurable[ab],a.subgraphCounter.toString()].join(`|`)})),a.subgraphCounter+=1);let o=Jy in(n.configurable??{});!o&&n.configurable?.checkpoint_ns!==void 0&&n.configurable?.checkpoint_ns!==``&&(n=mM(n,{checkpoint_ns:``,checkpoint_id:void 0}));let s=n;n.configurable?.checkpoint_map!==void 0&&n.configurable?.checkpoint_map?.[n.configurable?.checkpoint_ns]&&(s=mM(n,{checkpoint_id:n.configurable[sb][n.configurable?.checkpoint_ns]}));let c=n.configurable?.checkpoint_ns?.split(`|`)??[],l=await t.checkpointer?.getTuple(s)??{config:n,checkpoint:hA(),metadata:{source:`input`,step:-2,parents:{}},pendingWrites:[]};s={...n,...l.config,configurable:{checkpoint_ns:``,...n.configurable,...l.config.configurable}};let u=l.parentConfig,d=gA(l.checkpoint),f={...l.metadata},p=l.pendingWrites??[],m=AA(t.channelSpecs,d),h=(f.step??0)+1,g=h+(n.recursionLimit??iN)+1,_={...d.channel_versions},v=t.store?new wA(t.store):void 0;return v&&await v.start(),new e({input:t.input,config:n,checkpointer:t.checkpointer,checkpoint:d,checkpointMetadata:f,checkpointConfig:s,prevCheckpointConfig:u,checkpointNamespace:c,channels:m,isNested:o,manager:t.manager,skipDoneTasks:i,step:h,stop:g,checkpointPreviousVersions:_,checkpointPendingWrites:p,outputKeys:t.outputKeys??[],streamKeys:t.streamKeys??[],nodes:t.nodes,stream:r,store:v,cache:t.cache,interruptAfter:t.interruptAfter,interruptBefore:t.interruptBefore,durability:t.durability,debug:t.debug,triggerToNodes:t.triggerToNodes})}_checkpointerPutAfterPrevious(e){this._checkpointerChainedPromise=this._checkpointerChainedPromise.then(()=>this.checkpointer?.put(e.config,e.checkpoint,e.metadata,e.newVersions)),this._trackCheckpointerPromise(this._checkpointerChainedPromise)}putWrites(e,t){let n=t;if(n.length===0)return;n.every(([e])=>e in yA)&&(n=Array.from(new Map(n.map(e=>[e[0],e])).values()));let r=!1;for(let e in this.channels)if(Object.prototype.hasOwnProperty.call(this.channels,e)&&this.channels[e].lc_graph_name===`UntrackedValue`){r=!0;break}let i=n;r&&(i=n.filter(([e])=>{let t=this.channels[e];return!t||t.lc_graph_name!==`UntrackedValue`}).map(([e,t])=>e===`__pregel_tasks`&&Tb(t)?[e,NM(t,this.channels)]:[e,t])),this.checkpointPendingWrites=this.checkpointPendingWrites.filter(t=>t[0]!==e);for(let[t,n]of i)this.checkpointPendingWrites.push([e,t,n]);let a=mM(this.checkpointConfig,{[ab]:this.config.configurable?.checkpoint_ns??``,[ib]:this.checkpoint.id});if(this.durability!==`exit`&&this.checkpointer!=null&&this._trackCheckpointerPromise(this.checkpointer.putWrites(a,i,e)),this.tasks&&this._outputWrites(e,n),!t.length||!this.cache||!this.tasks)return;let o=this.tasks[e];o==null||o.cache_key==null||t[0][0]===`__error__`||t[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,t,n=!1){let r=this.tasks[e];if(r!==void 0){if(r.config!==void 0&&(r.config.tags??[]).includes(`langsmith:hidden`))return;if(t.length>0)if(t[0][0]===`__interrupt__`){if(r.path?.[0]===`__pregel_push`&&r.path?.[r.path.length-1]===!0)return;let e=t.filter(e=>e[0]===lb).flatMap(e=>e[1]);this._emit([[`updates`,{[lb]:e}],[`values`,{[lb]:e}]])}else t[0][0]!==`__error__`&&this._emit(ZA(YA(uM(this.outputKeys,[[r,t]],n),`updates`)));n||this._emit(ZA(YA(BM([[r,t]],this.streamKeys),`tasks`)))}}async _matchCachedWrites(){if(!this.cache)return[];let e=[],t=([e,t])=>`ns:${e.join(`,`)}|key:${t}`,n=[],r={};for(let e of Object.values(this.tasks))e.cache_key!=null&&!e.writes.length&&(n.push([e.cache_key.ns,e.cache_key.key]),r[t([e.cache_key.ns,e.cache_key.key])]=e);if(n.length===0)return[];let i=await this.cache.get(n);for(let{key:n,value:a}of i){let i=r[t(n)];i!=null&&(i.writes.push(...a),e.push({task:i,result:a}))}return e}async tick(e){this.store&&!this.store.isRunning&&await this.store?.start();let{inputKeys:t=[]}=e;if(this.status!==`pending`)throw Error(`Cannot tick when status is no longer "pending". Current status: "${this.status}"`);if(![nN,rN].includes(this.input))await this._first(t);else if(this.toInterrupt.length>0)throw this.status=`interrupt_before`,new Lb;else if(Object.values(this.tasks).every(e=>e.writes.length>0)){let e=Object.values(this.tasks).flatMap(e=>e.writes);this.updatedChannels=OM(this.checkpoint,this.channels,Object.values(this.tasks),this.checkpointerGetNextVersion,this.triggerToNodes);let t=await XA(YA(lM(this.outputKeys,e,this.channels),`values`));if(this._emit(t),this.checkpointPendingWrites=[],await this._putCheckpoint({source:`loop`}),wM(this.checkpoint,this.interruptAfter,Object.values(this.tasks)))throw this.status=`interrupt_after`,new Lb;this.config.configurable?.__pregel_resuming!==void 0&&delete this.config.configurable?.[Xy]}else return!1;if(this.step>this.stop)return this.status=`out_of_steps`,!1;if(this.tasks=AM(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 XA(YA(VM(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(let[e,t,n]of this.checkpointPendingWrites){if(t===`__error__`||t===`__interrupt__`||t===`__resume__`)continue;let r=Object.values(this.tasks).find(t=>t.id===e);r&&r.writes.push([t,n])}for(let e of Object.values(this.tasks))e.writes.length>0&&this._outputWrites(e.id,e.writes,!0)}if(Object.values(this.tasks).every(e=>e.writes.length>0))return this.tick({inputKeys:t});if(wM(this.checkpoint,this.interruptBefore,Object.values(this.tasks)))throw this.status=`interrupt_before`,new Lb;let n=await XA(YA(LM(Object.values(this.tasks)),`tasks`));return this._emit(n),!0}async finishAndHandleError(e){this.durability===`exit`&&(!this.isNested||e!==void 0||this.checkpointNamespace.every(e=>!e.includes(`:`)))&&(this._putCheckpoint(this.checkpointMetadata),this._flushPendingWrites());let t=this._suppressInterrupt(e);return(t||e===void 0)&&(this.output=oM(this.channels,this.outputKeys)),t&&(this.tasks!==void 0&&this.checkpointPendingWrites.length>0&&Object.values(this.tasks).some(e=>e.writes.length>0)&&(this.updatedChannels=OM(this.checkpoint,this.channels,Object.values(this.tasks),this.checkpointerGetNextVersion,this.triggerToNodes),this._emit(ZA(YA(lM(this.outputKeys,Object.values(this.tasks).flatMap(e=>e.writes),this.channels),`values`)))),Hb(e)&&!e.interrupts.length&&this._emit([[`updates`,{[lb]:[]}],[`values`,{[lb]:[]}]])),t}async acceptPush(e,t,n){if(this.interruptAfter?.length>0&&wM(this.checkpoint,this.interruptAfter,[e])){this.toInterrupt.push(e);return}let r=jM([_b,e.path??[],t,e.id,n],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(!r)return;if(this.interruptBefore?.length>0&&wM(this.checkpoint,this.interruptBefore,[r])){this.toInterrupt.push(r);return}this._emit(ZA(YA(LM([r]),`tasks`))),this.debug&&WM(this.step,[r]),this.tasks[r.id]=r,this.skipDoneTasks&&this._matchWrites({[r.id]:r});let i=await this._matchCachedWrites();for(let{task:e}of i)this._outputWrites(e.id,e.writes,!0);return r}_suppressInterrupt(e){return Hb(e)&&!this.isNested}async _first(e){let{configurable:t}=this.config,n=t?.[tb];if(n&&n.nullResume!==void 0&&this.putWrites(yb,[[ub,n.nullResume]]),jb(this.input)){let e=this.input.resume!=null;if(this.input.resume!=null&&typeof this.input.resume==`object`&&Object.keys(this.input.resume).every(iM)&&(this.config.configurable??={},this.config.configurable[eb]=this.input.resume),e&&this.checkpointer==null)throw Error(`Cannot use Command(resume=...) without checkpointer`);let t={};for(let[e,n,r]of sM(this.input,this.checkpointPendingWrites))t[e]??=[],t[e].push([n,r]);if(Object.keys(t).length===0)throw new Ub(`Received empty Command input`);for(let[e,n]of Object.entries(t))this.putWrites(e,n)}let r=(this.checkpointPendingWrites??[]).filter(e=>e[0]===yb).map(e=>e.slice(1));r.length>0&&OM(this.checkpoint,this.channels,[{name:Uy,writes:r,triggers:[]}],this.checkpointerGetNextVersion,this.triggerToNodes);let i=jb(this.input)&&r.length>0;if(this.isResuming||i){for(let e in this.channels)if(Object.prototype.hasOwnProperty.call(this.channels,e)&&this.checkpoint.channel_versions[e]!==void 0){let t=this.checkpoint.channel_versions[e];this.checkpoint.versions_seen[lb]={...this.checkpoint.versions_seen[lb],[e]:t}}let e=await XA(YA(lM(this.outputKeys,!0,this.channels),`values`));this._emit(e)}if(this.isResuming)this.input=rN;else if(i)await this._putCheckpoint({source:`input`}),this.input=nN;else{let t=await XA(cM(e,this.input));if(t.length>0){let e=AM(this.checkpoint,this.checkpointPendingWrites,this.nodes,this.channels,this.config,!0,{step:this.step});this.updatedChannels=OM(this.checkpoint,this.channels,Object.values(e).concat([{name:Uy,writes:t,triggers:[]}]),this.checkpointerGetNextVersion,this.triggerToNodes),await this._putCheckpoint({source:`input`}),this.input=nN}else if(`__pregel_resuming`in(this.config.configurable??{}))this.input=nN;else throw new Ub(`Received no input writes for ${JSON.stringify(e,null,2)}`)}this.isNested||(this.config=mM(this.config,{[Xy]:this.isResuming}))}_emit(e){for(let[t,n]of e)if(this.stream.modes.has(t)&&this.stream.push([this.checkpointNamespace,t,n]),(t===`checkpoints`||t===`tasks`)&&this.stream.modes.has(`debug`)){let e=t===`checkpoints`?this.step-1:this.step,r=new Date().toISOString(),i=t===`checkpoints`?`checkpoint`:typeof n==`object`&&n&&`result`in n?`task_result`:`task`;this.stream.push([this.checkpointNamespace,`debug`,{step:e,type:i,timestamp:r,payload:n}])}}_putCheckpoint(e){let t=this.checkpointMetadata===e,n=this.checkpointer!=null&&(this.durability!==`exit`||t),r=e=>{this.prevCheckpointConfig=this.checkpointConfig?.configurable?.checkpoint_id?this.checkpointConfig:void 0,this.checkpointConfig=mM(this.checkpointConfig,{[ab]:this.config.configurable?.checkpoint_ns??``});let t={...this.checkpoint.channel_versions},n=fM(this.checkpointPreviousVersions,t);this.checkpointPreviousVersions=t,this._checkpointerPutAfterPrevious({config:{...this.checkpointConfig},checkpoint:gA(e),metadata:{...this.checkpointMetadata},newVersions:n}),this.checkpointConfig={...this.checkpointConfig,configurable:{...this.checkpointConfig.configurable,checkpoint_id:this.checkpoint.id}}};t||(this.checkpointMetadata={...e,step:this.step,parents:this.config.configurable?.checkpoint_map??{}}),this.checkpoint=jA(this.checkpoint,n?this.channels:void 0,this.step,t?{id:this.checkpoint.id}:void 0),n&&r(this.checkpoint),t||(this.step+=1)}_flushPendingWrites(){if(this.checkpointer==null||this.checkpointPendingWrites.length===0)return;let e=mM(this.checkpointConfig,{[ab]:this.config.configurable?.checkpoint_ns??``,[ib]:this.checkpoint.id}),t={};for(let[e,n,r]of this.checkpointPendingWrites)t[e]??=[],t[e].push([n,r]);for(let[n,r]of Object.entries(t))this._trackCheckpointerPromise(this.checkpointer.putWrites(e,r,n))}_matchWrites(e){for(let[t,n,r]of this.checkpointPendingWrites){if(n===`__error__`||n===`__interrupt__`||n===`__resume__`)continue;let i=Object.values(e).find(e=>e.id===t);i&&i.writes.push([n,r])}for(let t of Object.values(e))t.writes.length>0&&this._outputWrites(t.id,t.writes,!0)}};function cN(e){return pt(e?.message)}function lN(e,t,n){if(!e)return;let r=e.langgraph_checkpoint_ns,i=e.checkpoint_ns,a=r??i;if(a)return[a.split(`|`),{tags:t,name:n,...e}]}var uN=class extends vr{name=`StreamMessagesHandler`;streamFn;metadatas={};seen={};emittedChatModelRunIds={};stableMessageIdMap={};lc_prefer_streaming=!0;constructor(e){super(),this.streamFn=e}_emit(e,t,n,r=!1){if(r&&t.id!==void 0&&this.seen[t.id]!==void 0)return;let i=t.id;n!=null&&(bt(t)?i??=`run-${n}-tool-${t.tool_call_id}`:((i==null||i===`run-${n}`)&&(i=this.stableMessageIdMap[n]??i??`run-${n}`),this.stableMessageIdMap[n]??=i)),i!==t.id&&(t.id=i,t.lc_kwargs.id=i),t.id!=null&&(this.seen[t.id]=t),this.streamFn([e[0],`messages`,[t,e[1]]])}handleChatModelStart(e,t,n,r,i,a,o,s){o&&(!a||!a.includes(`langsmith:nostream`)&&!a.includes(`nostream`))&&(this.metadatas[n]=lN(o,a,s))}handleLLMNewToken(e,t,n,r,i,a){let o=a?.chunk;this.emittedChatModelRunIds[n]=!0,this.metadatas[n]!==void 0&&(cN(o)?this._emit(this.metadatas[n],o.message,n):this._emit(this.metadatas[n],new Xt({content:e}),n))}handleLLMEnd(e,t){if(this.metadatas[t]!==void 0){if(!this.emittedChatModelRunIds[t]){let n=e.generations?.[0]?.[0];pt(n?.message)&&this._emit(this.metadatas[t],n?.message,t,!0),delete this.emittedChatModelRunIds[t]}delete this.metadatas[t],delete this.stableMessageIdMap[t]}}handleLLMError(e,t){delete this.metadatas[t]}handleChainStart(e,t,n,r,i,a,o,s){if(a!==void 0&&s===a.langgraph_node&&(i===void 0||!i.includes(`langsmith:hidden`))&&(this.metadatas[n]=lN(a,i,s),typeof t==`object`)){for(let e of Object.values(t))if((pt(e)||mt(e))&&e.id!==void 0)this.seen[e.id]=e;else if(Array.isArray(e))for(let t of e)(pt(t)||mt(t))&&t.id!==void 0&&(this.seen[t.id]=t)}}handleChainEnd(e,t){let n=this.metadatas[t];if(delete this.metadatas[t],n!==void 0){if(pt(e))this._emit(n,e,t,!0);else if(Array.isArray(e))for(let r of e)pt(r)&&this._emit(n,r,t,!0);else if(typeof e==`object`&&e){for(let r of Object.values(e))if(pt(r))this._emit(n,r,t,!0);else if(Array.isArray(r))for(let e of r)pt(e)&&this._emit(n,e,t,!0)}}}handleChainError(e,t){delete this.metadatas[t]}},dN=[400,401,402,403,404,405,406,407,409],fN=e=>{if(e.message.startsWith(`Cancel`)||e.message.startsWith(`AbortError`)||e.name===`AbortError`||e.name===`GraphValueError`||e?.code===`ECONNABORTED`)return!1;let t=e?.response?.status??e?.status;return!(t&&dN.includes(+t)||e?.error?.code===`insufficient_quota`)};async function pN(e,t,n,r){let i=e.retry_policy??t,a=i===void 0?0:i.initialInterval??500,o=0,s,c,l=e.config??{};n&&(l=mM(l,n)),l={...l,signal:r};let u=Date.now();for(l.executionInfo!=null&&(l.executionInfo={...l.executionInfo,nodeFirstAttemptTime:u});!r?.aborted;){e.writes.splice(0,e.writes.length),s=void 0;try{c=await e.proc.invoke(e.input,l);break}catch(t){if(s=t,s.pregelTaskId=e.id,Bb(s)){let t=l?.configurable?.checkpoint_ns,n=s.command;if(n.graph===t){for(let t of e.writers)await t.invoke(n,l);s=void 0;break}else if(n.graph===Ab.PARENT){let e=qA(t);s.command=new Ab({...s.command,graph:e})}}if(Vb(s)||i===void 0||(o+=1,o>=(i.maxAttempts??3))||!(i.retryOn??fN)(s))break;a=Math.min(i.maxInterval??128e3,a*(i.backoffFactor??2));let n=i.jitter?Math.floor(a+Math.random()*1e3):a;await new Promise(e=>setTimeout(e,n));let r=s.name??s.constructor.unminifiable_name??s.constructor.name;(i?.logWarning??!0)&&console.log(`Retrying task "${String(e.name)}" after ${a.toFixed(2)}ms (attempt ${o}) after ${r}: ${s}`),l=mM(l,{[Xy]:!0}),l.executionInfo!=null&&(l.executionInfo={...l.executionInfo,nodeAttempt:o+1,nodeFirstAttemptTime:u})}}return{task:e,result:c,error:s,signalAborted:r?.aborted}}var mN=Symbol.for(`promiseAdded`);function hN(){let e={next:()=>void 0,wait:Promise.resolve(mN)};function t(n){e.next=()=>{e.wait=new Promise(t),n(mN)}}return e.wait=new Promise(t),e}var gN=class{nodeFinished;loop;constructor({loop:e,nodeFinished:t}){this.loop=e,this.nodeFinished=t}async tick(e={}){let{timeout:t,retryPolicy:n,onStepWrite:r,maxConcurrency:i}=e,a=new Set,o,s=new AbortController,c=s.signal,l=t?AbortSignal.timeout(t):void 0,u=Object.values(this.loop.tasks).filter(e=>e.writes.length===0),{signals:d,disposeCombinedSignal:f}=this._initializeAbortSignals({exceptionSignal:c,stepTimeoutSignal:l,signal:e.signal}),p=this._executeTasksWithRetry(u,{signals:d,retryPolicy:n,maxConcurrency:i});for await(let{task:e,error:t,signalAborted:n}of p)this._commit(e,t),Hb(t)||Vb(t)&&!Hb(o)?o=t:t&&(a.size===0||!n)&&(s.abort(),a.add(t));if(f?.(),r?.(this.loop.step,Object.values(this.loop.tasks).map(e=>e.writes).flat()),a.size===1)throw Array.from(a)[0];if(a.size>1)throw AggregateError(Array.from(a),`Multiple errors occurred during superstep ${this.loop.step}. See the "errors" field of this exception for more details.`);if(Hb(o)||Vb(o)&&this.loop.isNested)throw o}_initializeAbortSignals({exceptionSignal:e,stepTimeoutSignal:t,signal:n}){let r=this.loop.config.configurable?.__pregel_abort_signals??{},i=r.externalAbortSignal??n,a=t??r.timeoutAbortSignal,{signal:o,dispose:s}=gM(i,a,e),c={externalAbortSignal:i,timeoutAbortSignal:a,composedAbortSignal:o};return this.loop.config=mM(this.loop.config,{[cb]:c}),{signals:c,disposeCombinedSignal:s}}async*_executeTasksWithRetry(e,t){let{retryPolicy:n,maxConcurrency:r,signals:i}=t??{},a=hN(),o={},s={executingTasksMap:o,barrier:a,retryPolicy:n,scheduleTask:async(e,t,n)=>this.loop.acceptPush(e,t,n)};if(i?.composedAbortSignal?.aborted)throw Error(`Abort`);let c=0,l,u=gM(i?.externalAbortSignal,i?.timeoutAbortSignal),d=u.signal?new Promise((e,t)=>{l=()=>t(Error(`Abort`)),u.signal?.addEventListener(`abort`,l,{once:!0})}):void 0;for(;(c===0||Object.keys(o).length>0)&&e.length;){for(;Object.values(o).length<(r??e.length)&&c<e.length;c+=1){let t=e[c];o[t.id]=pN(t,n,{[qy]:_N?.bind(s,this,t)},i?.composedAbortSignal).catch(e=>({task:t,error:e,signalAborted:i?.composedAbortSignal?.aborted}))}let t=await Promise.race([...Object.values(o),...d?[d]:[],a.wait]);t!==mN&&(yield t,l!=null&&(u.signal?.removeEventListener(`abort`,l),u.dispose?.()),delete o[t.task.id])}}_commit(e,t){if(t!==void 0)if(Hb(t)){if(t.interrupts.length){let n=t.interrupts.map(e=>[lb,e]),r=e.writes.filter(e=>e[0]===ub);r.length&&n.push(...r),this.loop.putWrites(e.id,n)}}else Vb(t)&&e.writes.length?this.loop.putWrites(e.id,e.writes):this.loop.putWrites(e.id,[[Wy,{message:t.message,name:t.name}]]);else this.nodeFinished&&(e.config?.tags==null||!e.config.tags.includes(`langsmith:hidden`))&&this.nodeFinished(String(e.name)),e.writes.length===0&&e.writes.push([db,null]),this.loop.putWrites(e.id,e.writes)}};async function _N(e,t,n,r,i,a={}){let o=t.config?.configurable?.[tb];if(!o)throw Error(`BUG: No scratchpad found on task ${t.name}__${t.id}`);let s=o.callCounter;o.callCounter+=1;let c=new vM({func:n,name:r,input:i,cache:a.cache,retry:a.retry,callbacks:a.callbacks}),l=await this.scheduleTask(t,s,c);if(!l)return;let u=this.executingTasksMap[l.id];if(u!==void 0)return u;if(l.writes.length>0){let e=l.writes.filter(([e])=>e===fb),t=l.writes.filter(([e])=>e===Wy);if(e.length>0){if(e.length===1)return Promise.resolve(e[0][1]);throw Error(`BUG: multiple returns found for task ${l.name}__${l.id}`)}if(t.length>0){if(t.length===1){let e=t[0][1],n=e instanceof Error?e:Error(String(e));return Promise.reject(n)}throw Error(`BUG: multiple errors found for task ${l.name}__${l.id}`)}return}else{let t=pN(l,a.retry,{[qy]:_N.bind(this,e,l)});return this.executingTasksMap[l.id]=t,this.barrier.next(),t.then(({result:e,error:t})=>t?Promise.reject(t):e)}}var vN=class extends Error{constructor(e){super(e),this.name=`GraphValidationError`}};function yN({nodes:e,channels:t,inputChannels:n,outputChannels:r,streamChannels:i,interruptAfterNodes:a,interruptBeforeNodes:o}){if(!t)throw new vN(`Channels not provided`);let s=new Set,c=new Set;for(let[t,n]of Object.entries(e)){if(t===`__interrupt__`)throw new vN(`"Node name ${lb} is reserved"`);if(n.constructor===cj)n.triggers.forEach(e=>s.add(e));else throw new vN(`Invalid node type ${typeof n}, expected PregelNode`)}for(let e of s)if(!(e in t))throw new vN(`Subscribed channel '${String(e)}' not in channels`);if(!Array.isArray(n)){if(!s.has(n))throw new vN(`Input channel ${String(n)} is not subscribed to by any node`)}else if(n.every(e=>!s.has(e)))throw new vN(`None of the input channels ${n} are subscribed to by any node`);Array.isArray(r)?r.forEach(e=>c.add(e)):c.add(r),i&&!Array.isArray(i)?c.add(i):Array.isArray(i)&&i.forEach(e=>c.add(e));for(let e of c)if(!(e in t))throw new vN(`Output channel '${String(e)}' not in channels`);if(a&&a!==`*`){for(let t of a)if(!(t in e))throw new vN(`Node ${String(t)} not in nodes`)}if(o&&o!==`*`){for(let t of o)if(!(t in e))throw new vN(`Node ${String(t)} not in nodes`)}}function bN(e,t){if(Array.isArray(e)){for(let n of e)if(!(n in t))throw Error(`Key ${String(n)} not found in channels`)}else if(!(e in t))throw Error(`Key ${String(e)} not found in channels`)}var xN=class e extends DA{lc_graph_name=`Topic`;unique=!1;accumulate=!1;seen;values;constructor(e){super(),this.unique=e?.unique??this.unique,this.accumulate=e?.accumulate??this.accumulate,this.seen=new Set,this.values=[]}fromCheckpoint(t){let n=new e({unique:this.unique,accumulate:this.accumulate});return t!==void 0&&(n.seen=new Set(t[0]),n.values=t[1]),n}update(e){let t=!1;this.accumulate||(t=this.values.length>0,this.values=[]);let n=e.flat();if(n.length>0)if(this.unique)for(let e of n)this.seen.has(e)||(t=!0,this.seen.add(e),this.values.push(e));else t=!0,this.values.push(...n);return t}get(){if(this.values.length===0)throw new Wb;return this.values}checkpoint(){return[[...this.seen],this.values]}isAvailable(){return this.values.length!==0}};function SN(e){let t=Zc.getRunnableConfig();if(!t)throw Error(`Called interrupt() outside the context of a graph.`);let n=t.configurable;if(!n)throw Error(`No configurable found in config`);if(!n.__pregel_checkpointer)throw new Ib(`No checkpointer set`,{lc_error_code:`MISSING_CHECKPOINTER`});let r=n[tb];r.interruptCounter+=1;let i=r.interruptCounter;if(r.resume.length>0&&i<r.resume.length)return n[Ky]?.([[ub,r.resume]]),r.resume[i];if(r.nullResume!==void 0){if(r.resume.length!==i)throw Error(`Resume length mismatch: ${r.resume.length} !== ${i}`);let e=r.consumeNullResume();return r.resume.push(e),n[Ky]?.([[ub,r.resume]]),e}let a=n[ab]?.split(`|`);throw new Lb([{id:a?rM(a.join(`|`)):void 0,value:e}])}var CN=class{static subscribeTo(e,t){let{key:n,tags:r}={key:void 0,tags:void 0,...t??{}};if(Array.isArray(e)&&n!==void 0)throw Error(`Can't specify a key when subscribing to multiple channels`);let i;return i=typeof e==`string`?n?{[n]:e}:[e]:Object.fromEntries(e.map(e=>[e,e])),new cj({channels:i,triggers:Array.isArray(e)?e:[e],tags:r})}static writeTo(e,t){let n=[];for(let t of e)n.push({channel:t,value:ej,skipNone:!1});for(let[e,r]of Object.entries(t??{}))ry.isRunnable(r)||typeof r==`function`?n.push({channel:e,value:ej,skipNone:!0,mapper:my(r)}):n.push({channel:e,value:r,skipNone:!1});return new rj(n)}},wN=class extends ry{lc_namespace=[`langgraph`,`pregel`];invoke(e,t){throw Error(`Not implemented`)}withConfig(e){return super.withConfig(e)}stream(e,t){return super.stream(e,t)}},TN=class extends wN{static lc_name(){return`LangGraph`}lc_namespace=[`langgraph`,`pregel`];lg_is_pregel=!0;nodes;channels;inputChannels;outputChannels;autoValidate=!0;streamMode=[`values`];streamChannels;interruptAfter;interruptBefore;stepTimeout;debug=!1;checkpointer;retryPolicy;config;store;cache;userInterrupt;triggerToNodes={};constructor(e){super(e);let{streamMode:t}=e;if(t!=null&&!Array.isArray(t)&&(t=[t]),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 Error(`Channel '${gb}' is reserved and cannot be used in the graph.`);this.channels[gb]=new xN({accumulate:!1}),this.autoValidate=e.autoValidate??this.autoValidate,this.streamMode=t??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()}withConfig(e){let t=rl(this.config,e);return new this.constructor({...this,config:t})}validate(){yN({nodes:this.nodes,channels:this.channels,outputChannels:this.outputChannels,inputChannels:this.inputChannels,streamChannels:this.streamChannels,interruptAfterNodes:this.interruptAfter,interruptBeforeNodes:this.interruptBefore});for(let[e,t]of Object.entries(this.nodes))for(let n of t.triggers)this.triggerToNodes[n]??=[],this.triggerToNodes[n].push(e);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,t){for(let[n,r]of Object.entries(this.nodes)){if(e!==void 0&&!e.startsWith(n))continue;let i=r.subgraphs?.length?r.subgraphs:[r.bound];for(let r of i){let i=dj(r);if(i!==void 0){if(n===e){yield[n,i];return}if(e===void 0&&(yield[n,i]),t){let r=e;e!==void 0&&(r=e.slice(n.length+1));for(let[e,a]of i.getSubgraphs(r,t))yield[`${n}|${e}`,a]}}}}}async*getSubgraphsAsync(e,t){yield*this.getSubgraphs(e,t)}async _prepareStateSnapshot({config:e,saved:t,subgraphCheckpointer:n,applyPendingWrites:r=!1}){if(t===void 0)return{values:{},next:[],config:e,tasks:[]};let i=AA(this.channels,t.checkpoint);if(t.pendingWrites?.length){let e=t.pendingWrites.filter(([e,t])=>e===yb).map(([e,t,n])=>[String(t),n]);e.length>0&&OM(t.checkpoint,i,[{name:Uy,writes:e,triggers:[]}],void 0,this.triggerToNodes)}let a=Object.values(AM(t.checkpoint,t.pendingWrites,this.nodes,i,t.config,!0,{step:(t.metadata?.step??-1)+1,store:this.store})),o=await XA(this.getSubgraphsAsync()),s=t.config.configurable?.checkpoint_ns??``,c={};for(let e of a){let r=o.find(([t])=>t===e.name);if(!r)continue;let i=`${String(e.name)}:${e.id}`;if(s&&(i=`${s}|${i}`),n===void 0){let n={configurable:{thread_id:t.config.configurable?.thread_id,checkpoint_ns:i}};c[e.id]=n}else{let a={configurable:{[Yy]:n,thread_id:t.config.configurable?.thread_id,checkpoint_ns:i}},o=r[1];c[e.id]=await o.getState(a,{subgraphs:!0})}}if(r&&t.pendingWrites?.length){let e=Object.fromEntries(a.map(e=>[e.id,e]));for(let[n,r,i]of t.pendingWrites)[`__error__`,`__interrupt__`,`__scheduled__`].includes(r)||n in e&&e[n].writes.push([String(r),i]);let n=a.filter(e=>e.writes.length>0);n.length>0&&OM(t.checkpoint,i,n,void 0,this.triggerToNodes)}let l=t?.metadata;l&&t?.config?.configurable?.thread_id&&(l={...l,thread_id:t.config.configurable.thread_id});let u=a.filter(e=>e.writes.length===0).map(e=>e.name);return{values:oM(i,this.streamChannelsAsIs),next:u,tasks:HM(a,t?.pendingWrites??[],c,this.streamChannelsAsIs),metadata:l,config:hM(t.config,t.metadata),createdAt:t.checkpoint.ts,parentConfig:t.parentConfig}}async getState(e,t){let n=e.configurable?.__pregel_checkpointer??this.checkpointer;if(!n)throw new Ib(`No checkpointer set`,{lc_error_code:`MISSING_CHECKPOINTER`});let r=e.configurable?.checkpoint_ns??``;if(r!==``&&e.configurable?.__pregel_checkpointer===void 0){let i=KA(r);for await(let[r,a]of this.getSubgraphsAsync(i,!0))if(r===i)return await a.getState(QA(e,{[Yy]:n}),{subgraphs:t?.subgraphs})}let i=rl(this.config,e),a=await n.getTuple(e);return await this._prepareStateSnapshot({config:i,saved:a,subgraphCheckpointer:t?.subgraphs?n:void 0,applyPendingWrites:!e.configurable?.checkpoint_id})}async*getStateHistory(e,t){let n=e.configurable?.__pregel_checkpointer??this.checkpointer;if(!n)throw new Ib(`No checkpointer set`,{lc_error_code:`MISSING_CHECKPOINTER`});let r=e.configurable?.checkpoint_ns??``;if(r!==``&&e.configurable?.__pregel_checkpointer===void 0){let i=KA(r);for await(let[r,a]of this.getSubgraphsAsync(i,!0))if(r===i){yield*a.getStateHistory(QA(e,{[Yy]:n}),t);return}}let i=rl(this.config,e,{configurable:{checkpoint_ns:r}});for await(let e of n.list(i,t))yield this._prepareStateSnapshot({config:e.config,saved:e})}async bulkUpdateState(e,t){let n=e.configurable?.__pregel_checkpointer??this.checkpointer;if(!n)throw new Ib(`No checkpointer set`,{lc_error_code:`MISSING_CHECKPOINTER`});if(t.length===0)throw Error(`No supersteps provided`);if(t.some(e=>e.updates.length===0))throw Error(`No updates provided`);let r=e.configurable?.checkpoint_ns??``;if(r!==``&&e.configurable?.__pregel_checkpointer===void 0){let i=KA(r);for await(let[,r]of this.getSubgraphsAsync(i,!0))return await r.bulkUpdateState(QA(e,{[Yy]:n}),t);throw Error(`Subgraph "${i}" not found`)}let i=async(e,t)=>{let r=this.config?rl(this.config,e):e,a=await n.getTuple(r),o=a===void 0?hA():gA(a.checkpoint),s={...a?.checkpoint.channel_versions},c=a?.metadata?.step??-1,l=QA(r,{checkpoint_ns:r.configurable?.checkpoint_ns??``}),u=r.metadata??{};a?.config.configurable&&(l=QA(r,a.config.configurable),u={...a.metadata,...u});let{values:d,asNode:f}=t[0];if(d==null&&f===void 0){if(t.length>1)throw new Gb(`Cannot create empty checkpoint with multiple updates`);return hM(await n.put(l,jA(o,void 0,c),{source:`update`,step:c+1,parents:a?.metadata?.parents??{}},{}),a?a.metadata:void 0)}let p=AA(this.channels,o);if(d===null&&f===`__end__`){if(t.length>1)throw new Gb(`Cannot apply multiple updates when clearing state`);if(a){let e=AM(o,a.pendingWrites||[],this.nodes,p,a.config,!0,{step:(a.metadata?.step??-1)+1,checkpointer:n,store:this.store}),t=(a.pendingWrites||[]).filter(e=>e[0]===yb).map(e=>e.slice(1));t.length>0&&OM(o,p,[{name:Uy,writes:t,triggers:[]}],n.getNextVersion.bind(n),this.triggerToNodes);for(let[t,n,r]of a.pendingWrites||[])[`__error__`,`__interrupt__`,`__scheduled__`].includes(n)||t in e&&e[t].writes.push([n,r]);OM(o,p,Object.values(e),n.getNextVersion.bind(n),this.triggerToNodes)}return hM(await n.put(l,jA(o,p,c),{...u,source:`update`,step:c+1,parents:a?.metadata?.parents??{}},fM(s,o.channel_versions)),a?a.metadata:void 0)}if(f===`__copy__`){if(t.length>1)throw new Gb(`Cannot copy checkpoint with multiple updates`);if(a==null)throw new Gb(`Cannot copy a non-existent checkpoint`);let e=e=>!Array.isArray(e)||e.length===0?!1:e.every(e=>Array.isArray(e)&&e.length===2),r=jA(o,void 0,c),s=await n.put(a.parentConfig??QA(a.config,{checkpoint_id:void 0}),r,{source:`fork`,step:c+1,parents:a.metadata?.parents??{}},{});if(e(d)){let e=AM(r,a.pendingWrites,this.nodes,p,s,!1,{step:c+2}),t=Object.values(e).reduce((e,{name:t,id:n})=>(e[t]??=[],e[t].push({id:n}),e),{}),n=d.reduce((e,n)=>{let[r,i]=n;e[i]??=[];let a=e[i].length,o=t[i]?.[a]?.id;return e[i].push({values:r,asNode:i,taskId:o}),e},{});return i(hM(s,a.metadata),Object.values(n).flat())}return hM(s,a.metadata)}if(f===`__input__`){if(t.length>1)throw new Gb(`Cannot apply multiple updates when updating as input`);let e=await XA(cM(this.inputChannels,d));if(e.length===0)throw new Gb(`Received no input writes for ${JSON.stringify(this.inputChannels,null,2)}`);OM(o,p,[{name:Uy,writes:e,triggers:[]}],n.getNextVersion.bind(this.checkpointer),this.triggerToNodes);let r=a?.metadata?.step==null?-1:a.metadata.step+1,i=await n.put(l,jA(o,p,r),{source:`input`,step:r,parents:a?.metadata?.parents??{}},fM(s,o.channel_versions));return await n.putWrites(i,e,Tx(Uy,o.id)),hM(i,a?a.metadata:void 0)}if(r.configurable?.checkpoint_id===void 0&&a?.pendingWrites!==void 0&&a.pendingWrites.length>0){let e=AM(o,a.pendingWrites,this.nodes,p,a.config,!0,{store:this.store,checkpointer:this.checkpointer,step:(a.metadata?.step??-1)+1}),t=(a.pendingWrites??[]).filter(e=>e[0]===yb).map(e=>e.slice(1));t.length>0&&OM(a.checkpoint,p,[{name:Uy,writes:t,triggers:[]}],void 0,this.triggerToNodes);for(let[t,n,r]of a.pendingWrites)[`__error__`,`__interrupt__`,`__scheduled__`].includes(n)||e[t]===void 0||e[t].writes.push([n,r]);let n=Object.values(e).filter(e=>e.writes.length>0);n.length>0&&OM(o,p,n,void 0,this.triggerToNodes)}let m=Object.values(o.versions_seen).map(e=>Object.values(e)).flat().find(e=>!!e),h=[];if(t.length===1){let{values:e,asNode:n,taskId:r}=t[0];if(n===void 0&&Object.keys(this.nodes).length===1)[n]=Object.keys(this.nodes);else if(n===void 0&&m===void 0)typeof this.inputChannels==`string`&&this.nodes[this.inputChannels]!==void 0&&(n=this.inputChannels);else if(n===void 0){let e=Object.entries(o.versions_seen).map(([e,t])=>Object.values(t).map(t=>[t,e])).flat().filter(([e,t])=>t!==lb).sort(([e],[t])=>_A(e,t));e&&(e.length===1?n=e[0][1]:e[e.length-1][0]!==e[e.length-2][0]&&(n=e[e.length-1][1]))}if(n===void 0)throw new Gb(`Ambiguous update, specify "asNode"`);h.push({values:e,asNode:n,taskId:r})}else for(let{asNode:e,values:n,taskId:r}of t){if(e==null)throw new Gb(`"asNode" is required when applying multiple updates`);h.push({values:n,asNode:e,taskId:r})}let g=[];for(let{asNode:e,values:t,taskId:n}of h){if(this.nodes[e]===void 0)throw new Gb(`Node "${e.toString()}" does not exist`);let r=this.nodes[e].getWriters();if(!r.length)throw new Gb(`No writers found for node "${e.toString()}"`);g.push({name:e,input:t,proc:r.length>1?sy.from(r,{omitSequenceTags:!0}):r[0],writes:[],triggers:[lb],id:n??Tx(`__interrupt__`,o.id),writers:[]})}for(let e of g)await e.proc.invoke(e.input,al({...r,store:r?.store??this.store},{runName:r.runName??`${this.getName()}UpdateState`,configurable:{[Ky]:t=>e.writes.push(...t),[Jy]:(t,n=!1)=>TM(o,p,e,t,n)}}));for(let e of g){let t=e.writes.filter(e=>e[0]!==_b);a!==void 0&&t.length>0&&await n.putWrites(l,t,e.id)}OM(o,p,g,n.getNextVersion.bind(this.checkpointer),this.triggerToNodes);let _=fM(s,o.channel_versions),v=await n.put(l,jA(o,p,c+1),{source:`update`,step:c+1,parents:a?.metadata?.parents??{}},_);for(let e of g){let t=e.writes.filter(e=>e[0]===_b);t.length>0&&await n.putWrites(v,t,e.id)}return hM(v,a?a.metadata:void 0)},a=e;for(let{updates:e}of t)a=await i(a,e);return a}async updateState(e,t,n){return this.bulkUpdateState(e,[{updates:[{values:t,asNode:n}]}])}_defaults(e){let{debug:t,streamMode:n,inputKeys:r,outputKeys:i,interruptAfter:a,interruptBefore:o,...s}=e,c=!0,l=t===void 0?this.debug:t,u=i;u===void 0?u=this.streamChannelsAsIs:bN(u,this.channels);let d=r;d===void 0?d=this.inputChannels:bN(d,this.channels);let f=o??this.interruptBefore??[],p=a??this.interruptAfter??[],m;n===void 0?(m=e.configurable?.__pregel_task_id===void 0?this.streamMode:[`values`],c=!0):(m=Array.isArray(n)?n:[n],c=typeof n==`string`);let h;if(this.checkpointer===!1)h=void 0;else if(e!==void 0&&e.configurable?.__pregel_checkpointer!==void 0)h=e.configurable[Yy];else if(this.checkpointer===!0)throw Error(`checkpointer: true cannot be used for root graphs.`);else h=this.checkpointer;let g=e.store??this.store,_=e.cache??this.cache;if(e.durability!=null&&e.checkpointDuring!=null)throw Error("Cannot use both `durability` and `checkpointDuring` at the same time.");let v=(()=>{if(e.checkpointDuring!=null)return e.checkpointDuring===!1?`exit`:`async`})(),y=e.durability??v??e?.configurable?.__pregel_durability??`async`;return[l,m,d,u,s,f,p,h,g,c,_,y]}async stream(e,t){let n=new AbortController,r={recursionLimit:this.config?.recursionLimit,...t,signal:gM(t?.signal,n.signal).signal},i=await super.stream(e,r);return new KM(t?.encoding===`text/event-stream`?tN(i):i,n)}streamEvents(e,t,n){let r=new AbortController,i={recursionLimit:this.config?.recursionLimit,...t,callbacks:_M(this.config?.callbacks,t?.callbacks),signal:gM(t?.signal,r.signal).signal};return new KM(super.streamEvents(e,i,n),r)}async _validateInput(e){return e}async _validateContext(e){return e}async*_streamIterator(e,t){let n=`version`in(t??{})?void 0:t?.encoding??void 0,r=t?.subgraphs,i=WA(this.config,t);if(i.recursionLimit===void 0||i.recursionLimit<1)throw Error(`Passed "recursionLimit" must be at least 1.`);if(this.checkpointer!==void 0&&this.checkpointer!==!1&&i.configurable===void 0)throw Error(`Checkpointer requires one or more of the following "configurable" keys: "thread_id", "checkpoint_ns", "checkpoint_id"`);let a=await this._validateInput(e),{runId:o,...s}=i,[c,l,,u,d,f,p,m,h,g,_,v]=this._defaults(s);d.metadata={ls_integration:`langgraph`,...d.metadata},d.context===void 0?d.configurable=await this._validateContext(d.configurable):d.context=await this._validateContext(d.context);let y=new qM({modes:new Set(l)});if(this.checkpointer===!0){d.configurable??={};let e=d.configurable.checkpoint_ns??``;d.configurable[ab]=e.split(`|`).map(e=>e.split(`:`)[0]).join(`|`)}if(l.includes(`messages`)){let e=new uN(e=>y.push(e)),{callbacks:t}=d;if(t===void 0)d.callbacks=[e];else if(Array.isArray(t))d.callbacks=t.concat(e);else{let n=t.copy();n.addHandler(e,!0),d.callbacks=n}}if(l.includes(`tools`)){let e=new JM(e=>y.push(e)),{callbacks:t}=d;if(t===void 0)d.callbacks=[e];else if(Array.isArray(t))d.callbacks=t.concat(e);else{let n=t.copy();n.addHandler(e,!0),d.callbacks=n}}d.writer??=e=>{if(!l.includes(`custom`))return;let t=(GA()?.configurable?.[ab])?.split(`|`).slice(0,-1);y.push([t??[],`custom`,e])},d.interrupt??=this.userInterrupt??SN,d.serverInfo??=EN(d);let b=await(await Kc._configureSync(d?.callbacks,void 0,d?.tags,void 0,d?.metadata,void 0,{tracerInheritableMetadata:kN(d)}))?.handleChainStart(this.toJSON(),pM(e,`input`),o,void 0,void 0,void 0,d?.runName??this.getName()),ee=kA(this.channels),x,te,S=(async()=>{try{x=await sN.initialize({input:a,config:d,checkpointer:m,nodes:this.nodes,channelSpecs:ee,outputKeys:u,streamKeys:this.streamChannelsAsIs,store:h,cache:_,stream:y,interruptAfter:p,interruptBefore:f,manager:b,debug:this.debug,triggerToNodes:this.triggerToNodes,durability:v});let e=new gN({loop:x,nodeFinished:d.configurable?.[ob]});t?.subgraphs&&(x.config.configurable={...x.config.configurable,[Qy]:x.stream}),await this._runLoop({loop:x,runner:e,debug:c,config:d}),v===`sync`&&await Promise.all(x?.checkpointerPromises??[])}catch(e){te=e}finally{try{x&&(await x.store?.stop(),await x.cache?.stop()),await Promise.all(x?.checkpointerPromises??[])}catch(e){te??=e}te?y.error(te):y.close()}})();try{for await(let e of y){if(e===void 0)throw Error(`Data structure error.`);let[t,i,a]=e;if(l.includes(i)){if(n===`text/event-stream`){r?yield[t,i,a]:yield[null,i,a];continue}r&&!g?yield[t,i,a]:g?r?yield[t,a]:yield a:yield[i,a]}}}catch(e){throw await b?.handleChainError(te),e}finally{await S}await b?.handleChainEnd(x?.output??{},o,void 0,void 0,void 0)}async invoke(e,t){let n=t?.streamMode??`values`,r={...t,outputKeys:t?.outputKeys??this.outputChannels,streamMode:n,encoding:void 0},i=[],a=await this.stream(e,r),o=[],s;for await(let e of a)n===`values`?kb(e)?o.push(e[lb]):s=e:i.push(e);if(n===`values`){if(o.length>0){let e=o.flat(1);if(s==null)return{[lb]:e};if(typeof s==`object`)return{...s,[lb]:e}}return s}return i}async _runLoop(e){let{loop:t,runner:n,debug:r,config:i}=e,a;try{for(;await t.tick({inputKeys:this.inputChannels});){for(let{task:e}of await t._matchCachedWrites())t._outputWrites(e.id,e.writes,!0);r&&UM(t.checkpointMetadata.step,t.channels,this.streamChannelsList),r&&WM(t.step,Object.values(t.tasks)),await n.tick({timeout:this.stepTimeout,retryPolicy:this.retryPolicy,onStepWrite:(e,t)=>{r&&GM(e,t,this.streamChannelsList)},maxConcurrency:i.maxConcurrency,signal:i.signal})}if(t.status===`out_of_steps`)throw new Fb([`Recursion limit of ${i.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(e){if(a=e,!await t.finishAndHandleError(a))throw e}finally{a===void 0&&await t.finishAndHandleError()}}async clearCache(){await this.cache?.clear([])}};function EN(e){let t=e.metadata??{},n=e.configurable??{},r=t.assistant_id,i=t.graph_id,a=n.langgraph_auth_user,o;if(typeof a==`object`&&a&&`identity`in a&&(o=a),r!=null||i!=null||o!=null)return{assistantId:r==null?``:String(r),graphId:i==null?``:String(i),user:o}}var DN=new Set([`key`,`token`,`secret`,`password`,`auth`]);function ON(e,t){let n=e.toLowerCase(),r=!1;for(let e of DN)if(n.includes(e)){r=!0;break}return e.startsWith(`__`)||!(typeof t==`string`||typeof t==`number`||typeof t==`boolean`)||r}function kN(e){let t=e.configurable;if(!t)return;let n={};for(let[e,r]of Object.entries(t))ON(e,r)||(n[e]=r);return Object.keys(n).length>0?n:void 0}var AN=/^(?:[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 jN(e){return typeof e==`string`&&AN.test(e)}for(var MN=[],NN=0;NN<256;++NN)MN.push((NN+256).toString(16).slice(1));function PN(e,t=0){return(MN[e[t+0]]+MN[e[t+1]]+MN[e[t+2]]+MN[e[t+3]]+`-`+MN[e[t+4]]+MN[e[t+5]]+`-`+MN[e[t+6]]+MN[e[t+7]]+`-`+MN[e[t+8]]+MN[e[t+9]]+`-`+MN[e[t+10]]+MN[e[t+11]]+MN[e[t+12]]+MN[e[t+13]]+MN[e[t+14]]+MN[e[t+15]]).toLowerCase()}var FN,IN=new Uint8Array(16);function LN(){if(!FN&&(FN=typeof crypto<`u`&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!FN))throw Error(`crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported`);return FN(IN)}var RN={randomUUID:typeof crypto<`u`&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function zN(e,t,n){if(RN.randomUUID&&!t&&!e)return RN.randomUUID();e||={};var r=e.random||(e.rng||LN)();if(r[6]=r[6]&15|64,r[8]=r[8]&63|128,t){n||=0;for(var i=0;i<16;++i)t[n+i]=r[i];return t}return PN(r)}var BN=class{path;ends;constructor(e){ry.isRunnable(e.path)?this.path=e.path:this.path=my(e.path),this.ends=Array.isArray(e.pathMap)?e.pathMap.reduce((e,t)=>(e[t]=t,e),{}):e.pathMap}run(e,t){return rj.registerWriter(new JA({name:`<branch_run>`,trace:!1,func:async(n,r)=>{try{return await this._route(n,r,e,t)}catch(e){throw e.name===Rb.unminifiable_name&&console.warn(`[WARN]: 'NodeInterrupt' thrown in conditional edge. This is likely a bug in your graph implementation.
151
- NodeInterrupt should only be thrown inside a node, not in edge conditions.`),e}}}))}async _route(e,t,n,r){let i=await this.path.invoke(r?r(t):e,t);Array.isArray(i)||(i=[i]);let a;if(a=this.ends?i.map(e=>Tb(e)?e:this.ends[e]):i,a.some(e=>!e))throw Error(`Branch condition returned unknown or null destination`);if(a.filter(Tb).some(e=>e.node===`__end__`))throw new Gb(`Cannot send a packet to the END node`);return await n(a,t)??e}},VN=class{nodes;edges;branches;entryPoint;compiled=!1;constructor(){this.nodes={},this.edges=new Set,this.branches={}}warnIfCompiled(e){this.compiled&&console.warn(e)}get allEdges(){return this.edges}addNode(...e){function t(e){return e.length>=1&&typeof e[0]!=`string`}let n=t(e)?Array.isArray(e[0])?e[0]:Object.entries(e[0]):[[e[0],e[1],e[2]]];if(n.length===0)throw Error("No nodes provided in `addNode`");for(let[e,t,r]of n){for(let t of[`|`,`:`])if(e.includes(t))throw Error(`"${t}" 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.`),e in this.nodes)throw Error(`Node \`${e}\` already present.`);if(e===`__end__`)throw Error(`Node \`${e}\` is reserved.`);let n=my(t);this.nodes[e]={runnable:n,metadata:r?.metadata,subgraphs:uj(n)?[n]:r?.subgraphs,ends:r?.ends}}return this}addEdge(e,t){if(this.warnIfCompiled(`Adding an edge to a graph that has already been compiled. This will not be reflected in the compiled graph.`),e===`__end__`)throw Error(`END cannot be a start node`);if(t===`__start__`)throw Error(`START cannot be an end node`);if(Array.from(this.edges).some(([t])=>t===e)&&!(`channels`in this))throw Error(`Already found path for ${e}. For multiple edges, use StateGraph.`);return this.edges.add([e,t]),this}addConditionalEdges(e,t,n){let r=typeof e==`object`?e:{source:e,path:t,pathMap:n};this.warnIfCompiled(`Adding an edge to a graph that has already been compiled. This will not be reflected in the compiled graph.`),ry.isRunnable(r.path)||(r.path=my(r.path));let i=r.path.getName()===`RunnableLambda`?`condition`:r.path.getName();if(this.branches[r.source]&&this.branches[r.source][i])throw Error(`Condition \`${i}\` already present for node \`${e}\``);return this.branches[r.source]??={},this.branches[r.source][i]=new BN(r),this}setEntryPoint(e){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(Vy,e)}setFinishPoint(e){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(e,Hy)}compile({checkpointer:e,interruptBefore:t,interruptAfter:n,name:r}={}){this.validate([...Array.isArray(t)?t:[],...Array.isArray(n)?n:[]]);let i=new HN({builder:this,checkpointer:e,interruptAfter:n,interruptBefore:t,autoValidate:!1,nodes:{},channels:{[Vy]:new fj,[Hy]:new fj},inputChannels:Vy,outputChannels:Hy,streamChannels:[],streamMode:`values`,name:r});for(let[e,t]of Object.entries(this.nodes))i.attachNode(e,t);for(let[e,t]of this.edges)i.attachEdge(e,t);for(let[e,t]of Object.entries(this.branches))for(let[n,r]of Object.entries(t))i.attachBranch(e,n,r);return i.validate()}validate(e){let t=new Set([...this.allEdges].map(([e,t])=>e));for(let[e]of Object.entries(this.branches))t.add(e);for(let e of t)if(e!==`__start__`&&!(e in this.nodes))throw Error(`Found edge starting at unknown node \`${e}\``);let n=new Set([...this.allEdges].map(([e,t])=>t));for(let[e,t]of Object.entries(this.branches))for(let r of Object.values(t))if(r.ends!=null)for(let e of Object.values(r.ends))n.add(e);else{n.add(Hy);for(let t of Object.keys(this.nodes))t!==e&&n.add(t)}for(let e of Object.values(this.nodes))for(let t of e.ends??[])n.add(t);for(let e of Object.keys(this.nodes))if(!n.has(e))throw new Kb([`Node \`${e}\` 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(`
152
- `),{lc_error_code:`UNREACHABLE_NODE`});for(let e of n)if(e!==`__end__`&&!(e in this.nodes))throw Error(`Found edge ending at unknown node \`${e}\``);if(e){for(let t of e)if(!(t in this.nodes))throw Error(`Interrupt node \`${t}\` is not present`)}this.compiled=!0}},HN=class extends TN{builder;constructor({builder:e,...t}){super(t),this.builder=e}attachNode(e,t){this.channels[e]=new fj,this.nodes[e]=new cj({channels:[],triggers:[],metadata:t.metadata,subgraphs:t.subgraphs,ends:t.ends}).pipe(t.runnable).pipe(new rj([{channel:e,value:ej}],[mb])),this.streamChannels.push(e)}attachEdge(e,t){if(t===`__end__`){if(e===`__start__`)throw Error(`Cannot have an edge from START to END`);this.nodes[e].writers.push(new rj([{channel:Hy,value:ej}],[mb]))}else this.nodes[t].triggers.push(e),this.nodes[t].channels.push(e)}attachBranch(e,t,n){e===`__start__`&&!this.nodes.__start__&&(this.nodes[Vy]=CN.subscribeTo(Vy,{tags:[mb]})),this.nodes[e].pipe(n.run(n=>new rj(n.map(n=>Tb(n)?n:{channel:n===`__end__`?Hy:`branch:${e}:${t}:${n}`,value:ej}),[mb])));let r=n.ends?Object.values(n.ends):Object.keys(this.nodes);for(let n of r)if(n!==`__end__`){let r=`branch:${e}:${t}:${n}`;this.channels[r]=new fj,this.nodes[n].triggers.push(r),this.nodes[n].channels.push(r)}}async getGraphAsync(e){let t=e?.xray,n=new Gv,r={[Vy]:n.addNode({schema:LD()},Vy)},i={},a={};t&&(a=Object.fromEntries((await XA(this.getSubgraphsAsync())).filter(e=>UN(e[1]))));function o(e,t,a,o=!1){if(t===`__end__`&&i.__end__===void 0&&(i[Hy]=n.addNode({schema:LD()},Hy)),r[e]!==void 0){if(i[t]===void 0)throw Error(`End node ${t} not found!`);return n.addEdge(r[e],i[t],a===t?void 0:a,o)}}for(let[o,s]of Object.entries(this.builder.nodes)){let c=WN(o),l=s.runnable,u=s.metadata??{};if(this.interruptBefore?.includes(o)&&this.interruptAfter?.includes(o)?u.__interrupt=`before,after`:this.interruptBefore?.includes(o)?u.__interrupt=`before`:this.interruptAfter?.includes(o)&&(u.__interrupt=`after`),t){let s=typeof t==`number`?t-1:t,d=a[o]===void 0?l.getGraph(e):await a[o].getGraphAsync({...e,xray:s});if(d.trimFirstNode(),d.trimLastNode(),Object.keys(d.nodes).length>1){let[e,t]=n.extend(d,c);if(e===void 0)throw Error(`Could not extend subgraph "${o}" due to missing entrypoint.`);function a(e){return e?e.lc_runnable:!1}function s(e,t){if(e!==void 0&&!jN(e))return e;if(a(t))try{let e=t.getName();return e=e.startsWith(`Runnable`)?e.slice(8):e,e}catch{return t.getName()}else return t.name??`UnknownSchema`}t!==void 0&&(r[c]={name:s(t.id,t.data),...t}),i[c]={name:s(e.id,e.data),...e}}else{let e=n.addNode(l,c,u);r[c]=e,i[c]=e}}else{let e=n.addNode(l,c,u);r[c]=e,i[c]=e}}let s=[...this.builder.allEdges].sort(([e],[t])=>e<t?-1:+(t>e));for(let[e,t]of s)o(WN(e),WN(t));for(let[e,t]of Object.entries(this.builder.branches)){let n={...Object.fromEntries(Object.keys(this.builder.nodes).filter(t=>t!==e).map(e=>[WN(e),WN(e)])),[Hy]:Hy};for(let r of Object.values(t)){let t;t=r.ends===void 0?n:r.ends;for(let[n,r]of Object.entries(t))o(WN(e),WN(r),n,!0)}}for(let[e,t]of Object.entries(this.builder.nodes))if(t.ends!==void 0)for(let n of t.ends)o(WN(e),WN(n),void 0,!0);return n}getGraph(e){let t=e?.xray,n=new Gv,r={[Vy]:n.addNode({schema:LD()},Vy)},i={},a={};t&&(a=Object.fromEntries(ZA(this.getSubgraphs()).filter(e=>UN(e[1]))));function o(e,t,a,o=!1){return t===`__end__`&&i.__end__===void 0&&(i[Hy]=n.addNode({schema:LD()},Hy)),n.addEdge(r[e],i[t],a===t?void 0:a,o)}for(let[o,s]of Object.entries(this.builder.nodes)){let c=WN(o),l=s.runnable,u=s.metadata??{};if(this.interruptBefore?.includes(o)&&this.interruptAfter?.includes(o)?u.__interrupt=`before,after`:this.interruptBefore?.includes(o)?u.__interrupt=`before`:this.interruptAfter?.includes(o)&&(u.__interrupt=`after`),t){let s=typeof t==`number`?t-1:t,d=a[o]===void 0?l.getGraph(e):a[o].getGraph({...e,xray:s});if(d.trimFirstNode(),d.trimLastNode(),Object.keys(d.nodes).length>1){let[e,t]=n.extend(d,c);if(e===void 0)throw Error(`Could not extend subgraph "${o}" due to missing entrypoint.`);function a(e){return e?e.lc_runnable:!1}function s(e,t){if(e!==void 0&&!jN(e))return e;if(a(t))try{let e=t.getName();return e=e.startsWith(`Runnable`)?e.slice(8):e,e}catch{return t.getName()}else return t.name??`UnknownSchema`}t!==void 0&&(r[c]={name:s(t.id,t.data),...t}),i[c]={name:s(e.id,e.data),...e}}else{let e=n.addNode(l,c,u);r[c]=e,i[c]=e}}else{let e=n.addNode(l,c,u);r[c]=e,i[c]=e}}let s=[...this.builder.allEdges].sort(([e],[t])=>e<t?-1:+(t>e));for(let[e,t]of s)o(WN(e),WN(t));for(let[e,t]of Object.entries(this.builder.branches)){let n={...Object.fromEntries(Object.keys(this.builder.nodes).filter(t=>t!==e).map(e=>[WN(e),WN(e)])),[Hy]:Hy};for(let r of Object.values(t)){let t;t=r.ends===void 0?n:r.ends;for(let[n,r]of Object.entries(t))o(WN(e),WN(r),n,!0)}}return n}};function UN(e){return typeof e.attachNode==`function`&&typeof e.attachEdge==`function`}function WN(e){return e===`subgraph`?`"${e}"`:e}var GN=(e,t)=>e.size===t.size&&[...e].every(e=>t.has(e)),KN=class e extends DA{lc_graph_name=`NamedBarrierValue`;names;seen;constructor(e){super(),this.names=e,this.seen=new Set}fromCheckpoint(t){let n=new e(this.names);return t!==void 0&&(n.seen=new Set(t)),n}update(e){let t=!1;for(let n of e)if(this.names.has(n))this.seen.has(n)||(this.seen.add(n),t=!0);else throw new Gb(`Value ${JSON.stringify(n)} not in names ${JSON.stringify(this.names)}`);return t}get(){if(!GN(this.names,this.seen))throw new Wb}checkpoint(){return[...this.seen]}consume(){return this.seen&&this.names&&GN(this.seen,this.names)?(this.seen=new Set,!0):!1}isAvailable(){return!!this.names&&GN(this.names,this.seen)}},qN=class e extends DA{lc_graph_name=`NamedBarrierValueAfterFinish`;names;seen;finished;constructor(e){super(),this.names=e,this.seen=new Set,this.finished=!1}fromCheckpoint(t){let n=new e(this.names);if(t!==void 0){let[e,r]=t;n.seen=new Set(e),n.finished=r}return n}update(e){let t=!1;for(let n of e)if(this.names.has(n)&&!this.seen.has(n))this.seen.add(n),t=!0;else if(!this.names.has(n))throw new Gb(`Value ${JSON.stringify(n)} not in names ${JSON.stringify(this.names)}`);return t}get(){if(!this.finished||!GN(this.names,this.seen))throw new Wb}checkpoint(){return[[...this.seen],this.finished]}consume(){return this.finished&&this.seen&&this.names&&GN(this.seen,this.names)?(this.seen=new Set,this.finished=!1,!0):!1}finish(){return!this.finished&&this.names&&GN(this.names,this.seen)?(this.finished=!0,!0):!1}isAvailable(){return this.finished&&!!this.names&&GN(this.names,this.seen)}};function JN(e){return typeof e==`object`&&!!e&&`~standard`in e&&typeof e[`~standard`]==`object`&&e[`~standard`]!==null&&`validate`in e[`~standard`]}function YN(e){return typeof e==`object`&&!!e&&`~standard`in e&&typeof e[`~standard`]==`object`&&e[`~standard`]!==null&&`jsonSchema`in e[`~standard`]}function XN(e){if(YN(e))try{return e[`~standard`].jsonSchema.input({target:`draft-07`})}catch{return}}function ZN(e){if(e!=null&&JN(e))try{let t=e[`~standard`].validate(void 0);if(t&&typeof t==`object`&&!(`then`in t&&typeof t.then==`function`)){let e=t;if(!e.issues){let t=e.value;return()=>t}}}catch{}}var QN=Symbol.for(`langgraph.channel.missing`),$N=class e extends DA{lc_graph_name=`UntrackedValue`;guard;_value=QN;initialValueFactory;constructor(e){super(),this.guard=e?.guard??!0,this.initialValueFactory=e?.initialValueFactory,this.initialValueFactory&&(this._value=this.initialValueFactory())}fromCheckpoint(t){return new e({guard:this.guard,initialValueFactory:this.initialValueFactory})}update(e){if(e.length===0)return!1;if(e.length!==1&&this.guard)throw new Gb(`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=e[e.length-1],!0}get(){if(this._value===QN)throw new Wb;return this._value}checkpoint(){}isAvailable(){return this._value!==QN}},eP=Symbol.for(`langgraph.state.reduced_value`),tP=class{[eP]=!0;valueSchema;inputSchema;reducer;jsonSchemaExtra;constructor(e,t){this.reducer=t.reducer,this.jsonSchemaExtra=t.jsonSchemaExtra,this.valueSchema=e,this.inputSchema=`inputSchema`in t?t.inputSchema:e,this.jsonSchemaExtra=t.jsonSchemaExtra}static isInstance(e){return typeof e==`object`&&!!e&&eP in e&&e[eP]===!0}},nP=Symbol.for(`langgraph.state.untracked_value`),rP=class{[nP]=!0;schema;guard;constructor(e,t){this.schema=e,this.guard=t?.guard??!0}static isInstance(e){return typeof e==`object`&&!!e&&nP in e}},iP=Symbol.for(`langgraph.state.state_schema`),aP=class{[iP]=!0;constructor(e){this.fields=e}getChannels(){let e={};for(let[t,n]of Object.entries(this.fields))if(tP.isInstance(n)){let r=ZN(n.valueSchema);e[t]=new FA(n.reducer,r)}else if(rP.isInstance(n)){let r=n.schema?ZN(n.schema):void 0;e[t]=new $N({guard:n.guard,initialValueFactory:r})}else if(JN(n))e[t]=new MA(ZN(n));else throw Error(`Invalid state field "${t}": must be a schema, ReducedValue, UntrackedValue, or ManagedValue`);return e}getJsonSchema(){let e={},t=[];for(let[n,r]of Object.entries(this.fields)){let i;if(tP.isInstance(r)?(i=XN(r.valueSchema),r.jsonSchemaExtra&&(i={...i??{},...r.jsonSchemaExtra})):rP.isInstance(r)?i=r.schema?XN(r.schema):void 0:JN(r)&&(i=XN(r)),i){e[n]=i;let a=!1;a=tP.isInstance(r)?ZN(r.valueSchema)!==void 0:rP.isInstance(r)?r.schema?ZN(r.schema)!==void 0:!1:ZN(r)!==void 0,a||t.push(n)}}return{type:`object`,properties:e,required:t.length>0?t:void 0}}getInputJsonSchema(){let e={};for(let[t,n]of Object.entries(this.fields)){let r;tP.isInstance(n)?(r=XN(n.inputSchema),n.jsonSchemaExtra&&(r={...r??{},...n.jsonSchemaExtra})):rP.isInstance(n)?r=n.schema?XN(n.schema):void 0:JN(n)&&(r=XN(n)),r&&(e[t]=r)}return{type:`object`,properties:e}}getChannelKeys(){return Object.entries(this.fields).map(([e])=>e)}getAllKeys(){return Object.keys(this.fields)}async validateInput(e){if(typeof e!=`object`||!e)return e;let t={};for(let[n,r]of Object.entries(e)){let e=this.fields[n];if(e===void 0){t[n]=r;continue}let i;if(tP.isInstance(e)?i=e.inputSchema:rP.isInstance(e)?i=e.schema:JN(e)&&(i=e),i){let e=await i[`~standard`].validate(r);if(e.issues)throw Error(`Validation failed for field "${n}": ${JSON.stringify(e.issues)}`);t[n]=e.value}else t[n]=r}return t}static isInstance(e){return typeof e==`object`&&!!e&&iP in e&&e[iP]===!0}};function oP(e,t){let n=Array.isArray(e)?e:[e],r=Array.isArray(t)?t:[t],i=n.map(yn),a=r.map(yn);for(let e of i)(e.id===null||e.id===void 0)&&(e.id=zN(),e.lc_kwargs.id=e.id);let o;for(let e=0;e<a.length;e+=1){let t=a[e];(t.id===null||t.id===void 0)&&(t.id=zN(),t.lc_kwargs.id=t.id),un.isInstance(t)&&t.id===`__remove_all__`&&(o=e)}if(o!=null)return a.slice(o+1);let s=[...i],c=new Map(s.map((e,t)=>[e.id,t])),l=new Set;for(let e of a){let t=c.get(e.id);if(t!==void 0)un.isInstance(e)?l.add(e.id):(l.delete(e.id),s[t]=e);else{if(un.isInstance(e))throw Error(`Attempting to delete a message with an ID that doesn't exist ('${e.id}')`);c.set(e.id,s.length),s.push(e)}}return s.filter(e=>!l.has(e.id))}new tP(TO().default(()=>[]),{inputSchema:TO(),reducer:oP,jsonSchemaExtra:{langgraph_type:`messages`,description:`A list of chat messages`}});var sP=new class{_map=new Map;_extensionCache=new Map;get(e){return this._map.get(e)}extend(e,t){let n=this.get(e);this._map.set(e,t(n))}remove(e){return this._map.delete(e),this}has(e){return this._map.has(e)}getChannelsForSchema(e){let t={},n=Ym(e);for(let[e,r]of Object.entries(n)){let n=this.get(r);n?.reducer?t[e]=new FA(n.reducer.fn,n.default):t[e]=new MA(n?.default)}return t}getExtendedChannelSchemas(e,t){if(Object.keys(t).length===0)return e;let n=Object.entries(t).filter(([,e])=>e===!0).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>`${e}:${t}`).join(`|`),r=this._extensionCache.get(n)??new Map;if(r.has(e))return r.get(e);let i=e;if(t.withReducerSchema||t.withJsonSchemaExtrasAsDescription){let n=Object.entries(Ym(e)).map(([e,n])=>{let r=this.get(n),i=t.withReducerSchema?r?.reducer?.schema??n:n;if(t.withJsonSchemaExtrasAsDescription&&r?.jsonSchemaExtra){let e=Bm(i)??Bm(n),t=JSON.stringify({...r.jsonSchemaExtra,description:e});i=i.describe(`lg:${t}`)}return[e,i]});i=Xm(e,Object.fromEntries(n)),Am(i)&&(i._def.unknownKeys=`strip`)}return t.asPartial&&(i=Zm(i)),r.set(e,i),this._extensionCache.set(n,r),i}};function cP(e){return e==null?!1:!!(aP.isInstance(e)||Jm(e)||typeof e==`object`&&`lc_graph_name`in e&&e.lc_graph_name===`AnnotationRoot`||typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length>0&&Object.values(e).every(e=>typeof e==`function`||EA(e)))}function lP(e){if(typeof e!=`object`||!e)return!1;let t=e,n=`state`in t&&cP(t.state),r=`stateSchema`in t&&cP(t.stateSchema),i=`input`in t&&cP(t.input);return!(!n&&!r&&!i||`input`in t&&t.input!=null&&!cP(t.input)||`output`in t&&t.output!=null&&!cP(t.output))}var uP=`__root__`,dP=Symbol.for(`langgraph.state.partial`),fP=class extends VN{channels={};waitingEdges=new Set;_schemaDefinition;_schemaRuntimeDefinition;_inputDefinition;_inputRuntimeDefinition;_outputDefinition;_outputRuntimeDefinition;_schemaDefinitions=new Map;_metaRegistry=sP;_configSchema;_configRuntimeSchema;_interrupt;_writer;constructor(e,t){super();let n=this._normalizeToStateGraphInit(e,t),r=n.state??n.stateSchema??n.input;if(!r)throw new qb;let i=this._getChannelsFromSchema(r);this._schemaDefinition=i,(aP.isInstance(r)||Jm(r))&&(this._schemaRuntimeDefinition=r),n.input&&(aP.isInstance(n.input)||Jm(n.input))?this._inputRuntimeDefinition=n.input:this._inputRuntimeDefinition=dP,n.output&&(aP.isInstance(n.output)||Jm(n.output))?this._outputRuntimeDefinition=n.output:this._outputRuntimeDefinition=this._schemaRuntimeDefinition;let a=n.input?this._getChannelsFromSchema(n.input):i,o=n.output?this._getChannelsFromSchema(n.output):i;this._inputDefinition=a,this._outputDefinition=o,this._addSchema(this._schemaDefinition),this._addSchema(this._inputDefinition),this._addSchema(this._outputDefinition),n.context&&Jm(n.context)&&(this._configRuntimeSchema=n.context),this._interrupt=n.interrupt,this._writer=n.writer}_normalizeToStateGraphInit(e,t){if(lP(e)){if(Jm(t)||IA.isInstance(t))return{...e,context:t};let n=t;return{...e,input:e.input??n?.input,output:e.output??n?.output,context:e.context??n?.context,interrupt:e.interrupt??n?.interrupt,writer:e.writer??n?.writer,nodes:e.nodes??n?.nodes}}if(cP(e)){if(Jm(t)||IA.isInstance(t))return{state:e,context:t};let n=t;return{state:e,input:n?.input,output:n?.output,context:n?.context,interrupt:n?.interrupt,writer:n?.writer,nodes:n?.nodes}}if(hP(e))return{state:pP(e.channels)};throw new qb}_getChannelsFromSchema(e){if(aP.isInstance(e))return e.getChannels();if(Jm(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 qb(`Invalid schema type. Expected StateSchema, Zod object, AnnotationRoot, or StateDefinition.`)}get allEdges(){return new Set([...this.edges,...Array.from(this.waitingEdges).flatMap(([e,t])=>e.map(e=>[e,t]))])}_addSchema(e){if(!this._schemaDefinitions.has(e)){this._schemaDefinitions.set(e,e);for(let[t,n]of Object.entries(e)){let e;if(e=typeof n==`function`?n():n,this.channels[t]!==void 0){if(!this.channels[t].equals(e)&&e.lc_graph_name!==`LastValue`)throw Error(`Channel "${t}" already exists with a different type.`)}else this.channels[t]=e}}}addNode(...e){function t(e){return e.length>=1&&typeof e[0]!=`string`}let n=t(e)?Array.isArray(e[0])?e[0]:Object.entries(e[0]).map(([e,t])=>[e,t]):[[e[0],e[1],e[2]]];if(n.length===0)throw Error("No nodes provided in `addNode`");for(let[e,t,r]of n){if(e in this.channels)throw Error(`${e} is already being used as a state attribute (a.k.a. a channel), cannot also be used as a node name.`);for(let t of[`|`,`:`])if(e.includes(t))throw Error(`"${t}" 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.`),e in this.nodes)throw Error(`Node \`${e}\` already present.`);if(e===`__end__`||e===`__start__`)throw Error(`Node \`${e}\` is reserved.`);let n=this._schemaDefinition;r?.input!==void 0&&(n=this._getChannelsFromSchema(r.input)),this._addSchema(n);let i;i=ry.isRunnable(t)?t:typeof t==`function`?new JA({func:t,name:e,trace:!1}):my(t);let a=r?.cachePolicy;typeof a==`boolean`&&(a=a?{}:void 0);let o={runnable:i,retryPolicy:r?.retryPolicy,cachePolicy:a,metadata:r?.metadata,input:n??this._schemaDefinition,subgraphs:uj(i)?[i]:r?.subgraphs,ends:r?.ends,defer:r?.defer};this.nodes[e]=o}return this}addEdge(e,t){if(typeof e==`string`)return super.addEdge(e,t);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(let t of e){if(t===`__end__`)throw Error(`END cannot be a start node`);if(!Object.keys(this.nodes).some(e=>e===t))throw Error(`Need to add a node named "${t}" first`)}if(t===`__end__`)throw Error(`END cannot be an end node`);if(!Object.keys(this.nodes).some(e=>e===t))throw Error(`Need to add a node named "${t}" first`);return this.waitingEdges.add([e,t]),this}addSequence(e){let t=Array.isArray(e)?e:Object.entries(e);if(t.length===0)throw Error(`Sequence requires at least one node.`);let n;for(let[e,r,i]of t){if(e in this.nodes)throw Error(`Node names must be unique: node with the name "${e}" already exists.`);let t=e;this.addNode(t,r,i),n!=null&&this.addEdge(n,t),n=t}return this}compile({checkpointer:e,store:t,cache:n,interruptBefore:r,interruptAfter:i,name:a,description:o}={}){this.validate([...Array.isArray(r)?r:[],...Array.isArray(i)?i:[]]);let s=Object.keys(this._schemaDefinitions.get(this._outputDefinition)),c=s.length===1&&s[0]===uP?uP:s,l=Object.keys(this.channels),u=l.length===1&&l[0]===uP?uP:l,d=this._interrupt,f=new mP({builder:this,checkpointer:e,interruptAfter:i,interruptBefore:r,autoValidate:!1,nodes:{},channels:{...this.channels,[Vy]:new fj},inputChannels:Vy,outputChannels:c,streamChannels:u,streamMode:`updates`,store:t,cache:n,name:a,description:o,userInterrupt:d});f.attachNode(Vy);for(let[e,t]of Object.entries(this.nodes))f.attachNode(e,t);f.attachBranch(Vy,hb,_P(),{withReader:!1});for(let[e]of Object.entries(this.nodes))f.attachBranch(e,hb,_P(),{withReader:!1});for(let[e,t]of this.edges)f.attachEdge(e,t);for(let[e,t]of this.waitingEdges)f.attachEdge(e,t);for(let[e,t]of Object.entries(this.branches))for(let[n,r]of Object.entries(t))f.attachBranch(e,n,r);return f.validate()}};function pP(e){let t={};for(let[n,r]of Object.entries(e))t[n]=RA(r);return t}var mP=class extends HN{description;_metaRegistry=sP;constructor({description:e,...t}){super(t),this.description=e}attachNode(e,t){let n;n=e===`__start__`?Object.entries(this.builder._schemaDefinitions.get(this.builder._inputDefinition)).map(([e])=>e):Object.keys(this.builder.channels);function r(e){if(jb(e))return e.graph===Ab.PARENT?null:e._updateAsTuples();if(Array.isArray(e)&&e.length>0&&e.some(e=>jb(e))){let t=[];for(let n of e)if(jb(n)){if(n.graph===Ab.PARENT)continue;t.push(...n._updateAsTuples())}else t.push([uP,n]);return t}else if(e!=null)return[[uP,e]];return null}let i=e;function a(e){if(!e)return null;if(jb(e))return e.graph===Ab.PARENT?null:e._updateAsTuples().filter(([e])=>n.includes(e));if(Array.isArray(e)&&e.length>0&&e.some(jb)){let t=[];for(let r of e)if(jb(r)){if(r.graph===Ab.PARENT)continue;t.push(...r._updateAsTuples().filter(([e])=>n.includes(e)))}else{let e=a(r);e&&t.push(...e??[])}return t}else if(typeof e==`object`&&!Array.isArray(e))return Object.entries(e).filter(([e])=>n.includes(e));else{let t=Array.isArray(e)?`array`:typeof e;throw new Gb(`Expected node "${i.toString()}" to return an object or an array containing at least one Command object, received ${t}`,{lc_error_code:`INVALID_GRAPH_NODE_RETURN_VALUE`})}}let o=[{value:ej,mapper:new JA({func:n.length&&n[0]===uP?r:a,trace:!1,recurse:!1})}];if(e===`__start__`)this.nodes[e]=new cj({tags:[mb],triggers:[Vy],channels:[Vy],writers:[new rj(o,[mb])]});else{let n=t?.input??this.builder._schemaDefinition,r=Object.fromEntries(Object.keys(this.builder._schemaDefinitions.get(n)).map(e=>[e,e])),i=Object.keys(r).length===1&&uP in r,a=`branch:to:${e}`;this.channels[a]=t?.defer?new NA:new fj(!1),this.nodes[e]=new cj({triggers:[a],channels:i?Object.keys(r):r,writers:[new rj(o,[mb])],mapper:i?void 0:e=>Object.fromEntries(Object.entries(e).filter(([e])=>e in r)),bound:t?.runnable,metadata:t?.metadata,retryPolicy:t?.retryPolicy,cachePolicy:t?.cachePolicy,subgraphs:t?.subgraphs,ends:t?.ends})}}attachEdge(e,t){if(t!==`__end__`){if(typeof e==`string`)this.nodes[e].writers.push(new rj([{channel:`branch:to:${t}`,value:null}],[mb]));else if(Array.isArray(e)){let n=`join:${e.join(`+`)}:${t}`;this.channels[n]=this.builder.nodes[t].defer?new qN(new Set(e)):new KN(new Set(e)),this.nodes[t].triggers.push(n);for(let t of e)this.nodes[t].writers.push(new rj([{channel:n,value:t}],[mb]))}}}attachBranch(e,t,n,r={withReader:!0}){this.nodes[e].writers.push(n.run(async(t,n)=>{let r=t.filter(e=>e!==Hy);if(!r.length)return;let i=r.map(t=>Tb(t)?t:{channel:t===`__end__`?t:`branch:to:${t}`,value:e});await rj.doWrite({...n,tags:(n.tags??[]).concat([mb])},i)},r.withReader?e=>oj.doRead(e,this.streamChannels??this.outputChannels,!0):void 0))}async _validateInput(e){if(e==null)return e;let t=this.builder._inputRuntimeDefinition,n=this.builder._schemaRuntimeDefinition;if(aP.isInstance(t)){if(jb(e)){let n=e;return e.update&&(n.update=await t.validateInput(Array.isArray(e.update)?Object.fromEntries(e.update):e.update)),n}return await t.validateInput(e)}if(t===dP&&aP.isInstance(n)){if(jb(e)){let t=e;return e.update&&(t.update=await n.validateInput(Array.isArray(e.update)?Object.fromEntries(e.update):e.update)),t}return await n.validateInput(e)}let r=(()=>{let e=e=>{if(e!=null)return this._metaRegistry.getExtendedChannelSchemas(e,{withReducerSchema:!0})};if(Jm(t))return e(t);if(t===dP)return Jm(n)?Zm(e(n)):void 0})();if(jb(e)){let t=e;return e.update&&r!=null&&(t.update=zm(r,e.update)),t}return r==null?e:zm(r,e)}isInterrupted(e){return kb(e)}async _validateContext(e){let t=this.builder._configRuntimeSchema;return Jm(t)&&zm(t,e),e}};function hP(e){return typeof e==`object`&&!!e&&e.channels!==void 0}function gP(e){if(Tb(e))return[e];let t=[];jb(e)?t.push(e):Array.isArray(e)&&t.push(...e.filter(jb));let n=[];for(let e of t){if(e.graph===Ab.PARENT)throw new zb(e);Tb(e.goto)||typeof e.goto==`string`?n.push(e.goto):Array.isArray(e.goto)&&n.push(...e.goto)}return n}function _P(){return new BN({path:new JA({func:gP,tags:[mb],trace:!1,recurse:!1,name:`<control_branch>`})})}var vP=e=>Array.isArray(e)&&e.every(pt),yP=e=>typeof e==`object`&&!!e&&`messages`in e&&vP(e.messages),bP=e=>typeof e==`object`&&!!e&&`lg_tool_call`in e,xP=class extends JA{tools;handleToolErrors=!0;trace=!1;constructor(e,t){let{name:n,tags:r,handleToolErrors:i}=t??{};super({name:n,tags:r,func:(e,t)=>this.run(e,t)}),this.tools=e,this.handleToolErrors=i??this.handleToolErrors}async runTool(e,t){let n=this.tools.find(t=>t.name===e.name);try{if(n===void 0)throw Error(`Tool "${e.name}" not found.`);let r=await n.invoke({...e,type:`tool_call`},t);return pt(r)&&r.getType()===`tool`||jb(r)?r:new _t({status:`success`,name:n.name,content:typeof r==`string`?r:JSON.stringify(r),tool_call_id:e.id})}catch(t){if(!this.handleToolErrors||Hb(t))throw t;return new _t({status:`error`,content:`Error: ${t.message}\n Please fix your mistakes.`,name:e.name,tool_call_id:e.id??``})}}async run(e,t){let n;if(bP(e))n=[await this.runTool(e.lg_tool_call,t)];else{let r;if(vP(e))r=e;else if(yP(e))r=e.messages;else throw Error(`ToolNode only accepts BaseMessage[] or { messages: BaseMessage[] } as input.`);let i=new Set(r.filter(e=>e.getType()===`tool`).map(e=>e.tool_call_id)),a;for(let e=r.length-1;e>=0;--e){let t=r[e];if(Jt(t)){a=t;break}}if(a==null||!Jt(a))throw Error(`ToolNode only accepts AIMessages as input.`);n=await Promise.all(a.tool_calls?.filter(e=>e.id==null||!i.has(e.id)).map(e=>this.runTool(e,t))??[])}if(!n.some(jb))return Array.isArray(e)?n:{messages:n};let r=[],i=null;for(let t of n)jb(t)?t.graph===Ab.PARENT&&Array.isArray(t.goto)&&t.goto.every(e=>Tb(e))?i?i.goto.push(...t.goto):i=new Ab({graph:Ab.PARENT,goto:t.goto}):r.push(t):r.push(Array.isArray(e)?[t]:{messages:[t]});return i&&r.push(i),r}},SP=/<name>(.*?)<\/name>/s,CP=/<content>(.*?)<\/content>/s;function wP(e){if(!(pt(e)&&(Jt(e)||mt(e)&&Yt(e)))||!e.name)return e;let{name:t}=e;if(typeof e.content==`string`)return new qt({...Object.keys(e.lc_kwargs??{}).length>0?e.lc_kwargs:e,content:`<name>${t}</name><content>${e.content}</content>`,name:void 0});let n=[],r=0;for(let i of e.content)typeof i==`string`?(r+=1,n.push(`<name>${t}</name><content>${i}</content>`)):typeof i==`object`&&`type`in i&&i.type===`text`?(r+=1,n.push({...i,text:`<name>${t}</name><content>${i.text}</content>`})):n.push(i);return r||n.unshift({type:`text`,text:`<name>${t}</name><content></content>`}),new qt({...e.lc_kwargs,content:n,name:void 0})}function TP(e){if(!Jt(e)||!e.content)return e;let t=[],n;if(Array.isArray(e.content))t=e.content.filter(e=>{if(e.type===`text`&&typeof e.text==`string`){let t=e.text.match(SP),r=e.text.match(CP);return t&&(!r||r[1]===``)?(n=t[1],!1):!0}return!0}).map(e=>{if(e.type===`text`&&typeof e.text==`string`){let t=e.text.match(SP),r=e.text.match(CP);return!t||!r?e:(n=t[1],{...e,text:r[1]})}return e});else{let r=e.content,i=r.match(SP),a=r.match(CP);if(!i||!a)return e;n=i[1],t=a[1]}return new qt({...Object.keys(e.lc_kwargs??{}).length>0?e.lc_kwargs:e,content:t,name:n})}function EP(e,t){let n,r;if(t===`inline`)n=wP,r=TP;else throw Error(`Invalid agent name mode: ${t}. Needs to be one of: "inline"`);function i(e){return e.map(n)}return sy.from([dy.from(i),e,dy.from(r)])}function DP(e){if(typeof e==`string`||pt(e)&&e._getType()===`system`)return e;if(typeof e==`function`)return async t=>e(t.messages);if(ry.isRunnable(e))return dy.from(e=>e.messages).pipe(e);throw Error(`Unexpected type for messageModifier: ${typeof e}`)}var OP=`prompt`;function kP(e){let t;if(e==null)t=dy.from(e=>e.messages).withConfig({runName:OP});else if(typeof e==`string`){let n=new dn(e);t=dy.from(e=>[n,...e.messages??[]]).withConfig({runName:OP})}else if(pt(e)&&e._getType()===`system`)t=dy.from(t=>[e,...t.messages]).withConfig({runName:OP});else if(typeof e==`function`)t=dy.from(e).withConfig({runName:OP});else if(ry.isRunnable(e))t=e;else throw Error(`Got unexpected type for 'prompt': ${typeof e}`);return t}function AP(e){return ry.isRunnable(e)}function jP(e,t,n){if([e,t,n].filter(e=>e!=null).length>1)throw Error(`Expected only one of prompt, stateModifier, or messageModifier, got multiple values`);let r=e;return t==null?n!=null&&(r=DP(n)):r=t,kP(r)}function MP(e){return`invoke`in e&&typeof e.invoke==`function`&&`_modelType`in e}function NP(e){return`_queuedMethodOperations`in e&&`_model`in e&&typeof e._model==`function`}function PP(e){return MP(e)?`bindTools`in e&&typeof e.bindTools==`function`:!1}async function FP(e,t){let n=e;if(sy.isRunnableSequence(n)&&(n=n.steps.find(e=>iy.isRunnableBinding(e)||MP(e)||NP(e))||n),NP(n)&&(n=await n._model()),!iy.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(t.length!==r.length)throw Error(`Number of tools in the model.bindTools() and tools passed to createReactAgent must match`);let i=new Set(t.flatMap(e=>AP(e)?e.name:[])),a=new Set;for(let e of r){let t;if(`type`in e&&e.type===`function`)t=e.function.name;else if(`name`in e)t=e.name;else if(`toolSpec`in e&&`name`in e.toolSpec)t=e.toolSpec.name;else continue;t&&a.add(t)}let o=[...i].filter(e=>!a.has(e));if(o.length>0)throw Error(`Missing tools '${o}' in the model.bindTools().Tools in the model.bindTools() must match the tools passed to createReactAgent.`);return!1}var IP=(e,t)=>{if(PP(e))return e.bindTools(t);if(iy.isRunnableBinding(e)&&PP(e.bound)){let n=e.bound.bindTools(t);return iy.isRunnableBinding(n)?new iy({bound:n.bound,config:{...e.config,...n.config},kwargs:{...e.kwargs,...n.kwargs},configFactories:n.configFactories??e.configFactories}):new iy({bound:n,config:e.config,kwargs:e.kwargs,configFactories:e.configFactories})}return null};async function LP(e,t){let n=IP(e,t);if(n)return n;if(NP(e)){let n=IP(await e._model(),t);if(n)return n}if(sy.isRunnableSequence(e)){let n=e.steps.findIndex(e=>iy.isRunnableBinding(e)||MP(e)||NP(e));if(n>=0){let r=IP(e.steps[n],t);if(r){let t=e.steps.slice();return t.splice(n,1,r),sy.from(t)}}}throw Error(`llm ${e} must define bindTools method.`)}async function RP(e){let t=e;if(sy.isRunnableSequence(t)&&(t=t.steps.find(e=>iy.isRunnableBinding(e)||MP(e)||NP(e))||t),NP(t)&&(t=await t._model()),iy.isRunnableBinding(t)&&(t=t.bound),!MP(t))throw Error(`Expected \`llm\` to be a ChatModel or RunnableBinding (e.g. llm.bind_tools(...)) with invoke() and generate() methods, got ${t.constructor.name}`);return t}var zP=()=>LA.Root({messages:LA({reducer:oP,default:()=>[]}),structuredResponse:LA}),BP=LA.Root({llmInputMessages:LA({reducer:(e,t)=>oP([],t),default:()=>[]})});function VP(e){let{llm:t,tools:n,messageModifier:r,stateModifier:i,prompt:a,stateSchema:o,contextSchema:s,checkpointSaver:c,checkpointer:l,interruptBefore:u,interruptAfter:d,store:f,responseFormat:p,preModelHook:m,postModelHook:h,name:g,description:_,version:v=`v1`,includeAgentName:y}=e,b,ee;Array.isArray(n)?(b=n,ee=new xP(b.filter(AP))):(b=n.tools,ee=n);let x=null,te=async e=>{if(x)return x;let t;t=await FP(e,b)?await LP(e,b):e;let n=jP(a,i,r),o=y===`inline`?EP(t,y):t;return x=n.pipe(o),x},S=async(e,t,n)=>{let o=await e(t,n);return jP(a,i,r).pipe(y===`inline`?EP(o,y):o)},ne=new Set(b.filter(AP).filter(e=>`returnDirect`in e&&e.returnDirect).map(e=>e.name));function re(e){let{messages:t,llmInputMessages:n,...r}=e;return n!=null&&n.length>0?{messages:n,...r}:{messages:t,...r}}let ie=async(e,n)=>{if(p==null)throw Error(`Attempted to generate structured output with no passed response schema. Please contact us for help.`);let r=[...e.messages],i,a=typeof t==`function`?await t(e,n):await RP(t);if(!MP(a))throw Error(`Expected \`llm\` to be a ChatModel with .withStructuredOutput() method, got ${a.constructor.name}`);if(typeof p==`object`&&`schema`in p){let{prompt:e,schema:t,...n}=p;i=a.withStructuredOutput(t,n),e!=null&&r.unshift(new dn({content:e}))}else i=a.withStructuredOutput(p);return{structuredResponse:await i.invoke(r,n)}},ae=async(e,n)=>{let r=await(typeof t==`function`?await S(t,e,n):await te(t)).invoke(re(e),n);return r.name=g,r.lc_kwargs.name=g,{messages:[r]}},oe=new fP(o??zP(),s).addNode(`tools`,ee);if(!(`messages`in oe._schemaDefinition))throw Error("Missing required `messages` key in state schema.");let se=oe,ce=e=>Object.fromEntries(Object.entries(e).filter(([e,t])=>t!=null)),C=`agent`,le;return m==null?C=`agent`:(se.addNode(`pre_model_hook`,m).addEdge(`pre_model_hook`,`agent`),C=`pre_model_hook`,le=LA.Root({...oe._schemaDefinition,...BP.spec})),se.addNode(`agent`,ae,{input:le}).addEdge(Vy,C),h!=null&&se.addNode(`post_model_hook`,h).addEdge(`agent`,`post_model_hook`).addConditionalEdges(`post_model_hook`,e=>{let{messages:t}=e,n=new Set(t.filter(bt).map(e=>e.tool_call_id)),r;for(let e=t.length-1;e>=0;--e){let n=t[e];if(Jt(n)){r=n;break}}let i=r?.tool_calls?.filter(e=>e.id==null||!n.has(e.id))??[],a=t[t.length-1];return i.length>0?v===`v2`?i.map(t=>new wb(`tools`,{...e,lg_tool_call:t})):`tools`:a&&bt(a)?C:p==null?Hy:`generate_structured_response`},ce({tools:`tools`,[C]:C,generate_structured_response:p==null?null:`generate_structured_response`,[Hy]:p==null?Hy:null})),p!==void 0&&oe.addNode(`generate_structured_response`,ie).addEdge(`generate_structured_response`,Hy),h??se.addConditionalEdges(`agent`,e=>{let{messages:t}=e,n=t[t.length-1];return!Jt(n)||!n.tool_calls?.length?p==null?Hy:`generate_structured_response`:v===`v2`?n.tool_calls.map(t=>new wb(`tools`,{...e,lg_tool_call:t})):`tools`},ce({tools:`tools`,generate_structured_response:p==null?null:`generate_structured_response`,[Hy]:p==null?Hy:null})),ne.size>0?se.addConditionalEdges(`tools`,e=>{let t=e;for(let e=t.messages.length-1;e>=0;--e){let n=t.messages[e];if(!bt(n))break;if(n.name!==void 0&&ne.has(n.name))return Hy}return C},ce({[C]:C,[Hy]:Hy})):se.addEdge(`tools`,C),se.compile({checkpointer:l??c,interruptBefore:u,interruptAfter:d,store:f,name:g,description:_})}function HP(e,t){return e.lc_error_code=t,e.message=`${e.message}\n\nTroubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${t}/\n`,e}function U(e,t,n,r,i){if(r===`m`)throw TypeError(`Private method is not writable`);if(r===`a`&&!i)throw TypeError(`Private accessor was defined without a setter`);if(typeof t==`function`?e!==t||!i:!t.has(e))throw TypeError(`Cannot write private member to an object whose class did not declare it`);return r===`a`?i.call(e,n):i?i.value=n:t.set(e,n),n}function W(e,t,n,r){if(n===`a`&&!r)throw TypeError(`Private accessor was defined without a getter`);if(typeof t==`function`?e!==t||!r:!t.has(e))throw TypeError(`Cannot read private member from an object whose class did not declare it`);return n===`m`?r:n===`a`?r.call(e):r?r.value:t.get(e)}var UP=function(){let{crypto:e}=globalThis;if(e?.randomUUID)return UP=e.randomUUID.bind(e),e.randomUUID();let t=new Uint8Array(1),n=e?()=>e.getRandomValues(t)[0]:()=>Math.random()*255&255;return`10000000-1000-4000-8000-100000000000`.replace(/[018]/g,e=>(e^n()&15>>e/4).toString(16))};function WP(e){return typeof e==`object`&&!!e&&(`name`in e&&e.name===`AbortError`||`message`in e&&String(e.message).includes(`FetchRequestCanceledException`))}var GP=e=>{if(e instanceof Error)return e;if(typeof e==`object`&&e){try{if(Object.prototype.toString.call(e)===`[object Error]`){let t=Error(e.message,e.cause?{cause:e.cause}:{});return e.stack&&(t.stack=e.stack),e.cause&&!t.cause&&(t.cause=e.cause),e.name&&(t.name=e.name),t}}catch{}try{return Error(JSON.stringify(e))}catch{}}return Error(e)},G=class extends Error{},KP=class e extends G{constructor(t,n,r,i){super(`${e.makeMessage(t,n,r)}`),this.status=t,this.headers=i,this.requestID=i?.get(`x-request-id`),this.error=n;let a=n;this.code=a?.code,this.param=a?.param,this.type=a?.type}static makeMessage(e,t,n){let r=t?.message?typeof t.message==`string`?t.message:JSON.stringify(t.message):t?JSON.stringify(t):n;return e&&r?`${e} ${r}`:e?`${e} status code (no body)`:r||`(no status code or body)`}static generate(t,n,r,i){if(!t||!i)return new JP({message:r,cause:GP(n)});let a=n?.error;return t===400?new XP(t,a,r,i):t===401?new ZP(t,a,r,i):t===403?new QP(t,a,r,i):t===404?new $P(t,a,r,i):t===409?new eF(t,a,r,i):t===422?new tF(t,a,r,i):t===429?new nF(t,a,r,i):t>=500?new rF(t,a,r,i):new e(t,a,r,i)}},qP=class extends KP{constructor({message:e}={}){super(void 0,void 0,e||`Request was aborted.`,void 0)}},JP=class extends KP{constructor({message:e,cause:t}){super(void 0,void 0,e||`Connection error.`,void 0),t&&(this.cause=t)}},YP=class extends JP{constructor({message:e}={}){super({message:e??`Request timed out.`})}},XP=class extends KP{},ZP=class extends KP{},QP=class extends KP{},$P=class extends KP{},eF=class extends KP{},tF=class extends KP{},nF=class extends KP{},rF=class extends KP{},iF=class extends G{constructor(){super(`Could not parse response content as the length limit was reached`)}},aF=class extends G{constructor(){super(`Could not parse response content as the request was rejected by the content filter`)}},oF=class extends Error{constructor(e){super(e)}},sF=class extends KP{constructor(e,t,n){let r=`OAuth2 authentication error`,i;if(t&&typeof t==`object`){let e=t;i=e.error;let n=e.error_description;n&&typeof n==`string`?r=n:i&&(r=i)}super(e,t,r,n),this.error_code=i}},cF=class extends G{constructor(e,t,n){super(e),this.provider=t,this.cause=n}},lF=/^[a-z][a-z0-9+.-]*:/i,uF=e=>lF.test(e),dF=e=>(dF=Array.isArray,dF(e)),fF=dF;function pF(e){return typeof e==`object`?e??{}:{}}function mF(e){if(!e)return!0;for(let t in e)return!1;return!0}function hF(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function gF(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var _F=(e,t)=>{if(typeof t!=`number`||!Number.isInteger(t))throw new G(`${e} must be an integer`);if(t<0)throw new G(`${e} must be a positive integer`);return t},vF=e=>{try{return JSON.parse(e)}catch{return}},yF=e=>new Promise(t=>setTimeout(t,e)),bF=`6.34.0`,xF=()=>typeof window<`u`&&window.document!==void 0&&typeof navigator<`u`;function SF(){return typeof Deno<`u`&&Deno.build!=null?`deno`:typeof EdgeRuntime<`u`?`edge`:Object.prototype.toString.call(globalThis.process===void 0?0:globalThis.process)===`[object process]`?`node`:`unknown`}var CF=()=>{let e=SF();if(e===`deno`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":bF,"X-Stainless-OS":EF(Deno.build.os),"X-Stainless-Arch":TF(Deno.build.arch),"X-Stainless-Runtime":`deno`,"X-Stainless-Runtime-Version":typeof Deno.version==`string`?Deno.version:Deno.version?.deno??`unknown`};if(typeof EdgeRuntime<`u`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":bF,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":`edge`,"X-Stainless-Runtime-Version":globalThis.process.version};if(e===`node`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":bF,"X-Stainless-OS":EF(globalThis.process.platform??`unknown`),"X-Stainless-Arch":TF(globalThis.process.arch??`unknown`),"X-Stainless-Runtime":`node`,"X-Stainless-Runtime-Version":globalThis.process.version??`unknown`};let t=wF();return t?{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":bF,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`unknown`,"X-Stainless-Runtime":`browser:${t.browser}`,"X-Stainless-Runtime-Version":t.version}:{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":bF,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`unknown`,"X-Stainless-Runtime":`unknown`,"X-Stainless-Runtime-Version":`unknown`}};function wF(){if(typeof navigator>`u`||!navigator)return null;for(let{key:e,pattern:t}of[{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/}]){let n=t.exec(navigator.userAgent);if(n)return{browser:e,version:`${n[1]||0}.${n[2]||0}.${n[3]||0}`}}return null}var TF=e=>e===`x32`?`x32`:e===`x86_64`||e===`x64`?`x64`:e===`arm`?`arm`:e===`aarch64`||e===`arm64`?`arm64`:e?`other:${e}`:`unknown`,EF=e=>(e=e.toLowerCase(),e.includes(`ios`)?`iOS`:e===`android`?`Android`:e===`darwin`?`MacOS`:e===`win32`?`Windows`:e===`freebsd`?`FreeBSD`:e===`openbsd`?`OpenBSD`:e===`linux`?`Linux`:e?`Other:${e}`:`Unknown`),DF,OF=()=>DF??=CF();function kF(){if(typeof fetch<`u`)return fetch;throw 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 AF(...e){let t=globalThis.ReadableStream;if(t===void 0)throw Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new t(...e)}function jF(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return AF({start(){},async pull(e){let{done:n,value:r}=await t.next();n?e.close():e.enqueue(r)},async cancel(){await t.return?.()}})}function MF(e){if(e[Symbol.asyncIterator])return e;let t=e.getReader();return{async next(){try{let e=await t.read();return e?.done&&t.releaseLock(),e}catch(e){throw t.releaseLock(),e}},async return(){let e=t.cancel();return t.releaseLock(),await e,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function NF(e){if(typeof e!=`object`||!e)return;if(e[Symbol.asyncIterator]){await e[Symbol.asyncIterator]().return?.();return}let t=e.getReader(),n=t.cancel();t.releaseLock(),await n}var PF=({headers:e,body:t})=>({bodyHeaders:{"content-type":`application/json`},body:JSON.stringify(t)}),FF=`RFC3986`,IF=e=>String(e),LF={RFC1738:e=>String(e).replace(/%20/g,`+`),RFC3986:IF},RF=(e,t)=>(RF=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),RF(e,t)),zF=(()=>{let e=[];for(let t=0;t<256;++t)e.push(`%`+((t<16?`0`:``)+t.toString(16)).toUpperCase());return e})(),BF=1024,VF=(e,t,n,r,i)=>{if(e.length===0)return e;let a=e;if(typeof e==`symbol`?a=Symbol.prototype.toString.call(e):typeof e!=`string`&&(a=String(e)),n===`iso-8859-1`)return escape(a).replace(/%u[0-9a-f]{4}/gi,function(e){return`%26%23`+parseInt(e.slice(2),16)+`%3B`});let o=``;for(let e=0;e<a.length;e+=BF){let t=a.length>=BF?a.slice(e,e+BF):a,n=[];for(let e=0;e<t.length;++e){let r=t.charCodeAt(e);if(r===45||r===46||r===95||r===126||r>=48&&r<=57||r>=65&&r<=90||r>=97&&r<=122||i===`RFC1738`&&(r===40||r===41)){n[n.length]=t.charAt(e);continue}if(r<128){n[n.length]=zF[r];continue}if(r<2048){n[n.length]=zF[192|r>>6]+zF[128|r&63];continue}if(r<55296||r>=57344){n[n.length]=zF[224|r>>12]+zF[128|r>>6&63]+zF[128|r&63];continue}e+=1,r=65536+((r&1023)<<10|t.charCodeAt(e)&1023),n[n.length]=zF[240|r>>18]+zF[128|r>>12&63]+zF[128|r>>6&63]+zF[128|r&63]}o+=n.join(``)}return o};function HF(e){return!e||typeof e!=`object`?!1:!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))}function UF(e,t){if(dF(e)){let n=[];for(let r=0;r<e.length;r+=1)n.push(t(e[r]));return n}return t(e)}var WF={brackets(e){return String(e)+`[]`},comma:`comma`,indices(e,t){return String(e)+`[`+t+`]`},repeat(e){return String(e)}},GF=function(e,t){Array.prototype.push.apply(e,dF(t)?t:[t])},KF,qF={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:`indices`,charset:`utf-8`,charsetSentinel:!1,delimiter:`&`,encode:!0,encodeDotInKeys:!1,encoder:VF,encodeValuesOnly:!1,format:FF,formatter:IF,indices:!1,serializeDate(e){return(KF??=Function.prototype.call.bind(Date.prototype.toISOString))(e)},skipNulls:!1,strictNullHandling:!1};function JF(e){return typeof e==`string`||typeof e==`number`||typeof e==`boolean`||typeof e==`symbol`||typeof e==`bigint`}var YF={};function XF(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h,g,_){let v=e,y=_,b=0,ee=!1;for(;(y=y.get(YF))!==void 0&&!ee;){let t=y.get(e);if(b+=1,t!==void 0){if(t===b)throw RangeError(`Cyclic object value`);ee=!0}y.get(YF)===void 0&&(b=0)}if(typeof l==`function`?v=l(t,v):v instanceof Date?v=f?.(v):n===`comma`&&dF(v)&&(v=UF(v,function(e){return e instanceof Date?f?.(e):e})),v===null){if(a)return c&&!h?c(t,qF.encoder,g,`key`,p):t;v=``}if(JF(v)||HF(v)){if(c){let e=h?t:c(t,qF.encoder,g,`key`,p);return[m?.(e)+`=`+m?.(c(v,qF.encoder,g,`value`,p))]}return[m?.(t)+`=`+m?.(String(v))]}let x=[];if(v===void 0)return x;let te;if(n===`comma`&&dF(v))h&&c&&(v=UF(v,c)),te=[{value:v.length>0?v.join(`,`)||null:void 0}];else if(dF(l))te=l;else{let e=Object.keys(v);te=u?e.sort(u):e}let S=s?String(t).replace(/\./g,`%2E`):String(t),ne=r&&dF(v)&&v.length===1?S+`[]`:S;if(i&&dF(v)&&v.length===0)return ne+`[]`;for(let t=0;t<te.length;++t){let y=te[t],ee=typeof y==`object`&&y.value!==void 0?y.value:v[y];if(o&&ee===null)continue;let S=d&&s?y.replace(/\./g,`%2E`):y,re=dF(v)?typeof n==`function`?n(ne,S):ne:ne+(d?`.`+S:`[`+S+`]`);_.set(e,b);let ie=new WeakMap;ie.set(YF,_),GF(x,XF(ee,re,n,r,i,a,o,s,n===`comma`&&h&&dF(v)?null:c,l,u,d,f,p,m,h,g,ie))}return x}function ZF(e=qF){if(e.allowEmptyArrays!==void 0&&typeof e.allowEmptyArrays!=`boolean`)throw TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(e.encodeDotInKeys!==void 0&&typeof e.encodeDotInKeys!=`boolean`)throw TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(e.encoder!==null&&e.encoder!==void 0&&typeof e.encoder!=`function`)throw TypeError(`Encoder has to be a function.`);let t=e.charset||qF.charset;if(e.charset!==void 0&&e.charset!==`utf-8`&&e.charset!==`iso-8859-1`)throw TypeError(`The charset option must be either utf-8, iso-8859-1, or undefined`);let n=FF;if(e.format!==void 0){if(!RF(LF,e.format))throw TypeError(`Unknown format option provided.`);n=e.format}let r=LF[n],i=qF.filter;(typeof e.filter==`function`||dF(e.filter))&&(i=e.filter);let a;if(a=e.arrayFormat&&e.arrayFormat in WF?e.arrayFormat:`indices`in e?e.indices?`indices`:`repeat`:qF.arrayFormat,`commaRoundTrip`in e&&typeof e.commaRoundTrip!=`boolean`)throw TypeError("`commaRoundTrip` must be a boolean, or absent");let o=e.allowDots===void 0?e.encodeDotInKeys?!0:qF.allowDots:!!e.allowDots;return{addQueryPrefix:typeof e.addQueryPrefix==`boolean`?e.addQueryPrefix:qF.addQueryPrefix,allowDots:o,allowEmptyArrays:typeof e.allowEmptyArrays==`boolean`?!!e.allowEmptyArrays:qF.allowEmptyArrays,arrayFormat:a,charset:t,charsetSentinel:typeof e.charsetSentinel==`boolean`?e.charsetSentinel:qF.charsetSentinel,commaRoundTrip:!!e.commaRoundTrip,delimiter:e.delimiter===void 0?qF.delimiter:e.delimiter,encode:typeof e.encode==`boolean`?e.encode:qF.encode,encodeDotInKeys:typeof e.encodeDotInKeys==`boolean`?e.encodeDotInKeys:qF.encodeDotInKeys,encoder:typeof e.encoder==`function`?e.encoder:qF.encoder,encodeValuesOnly:typeof e.encodeValuesOnly==`boolean`?e.encodeValuesOnly:qF.encodeValuesOnly,filter:i,format:n,formatter:r,serializeDate:typeof e.serializeDate==`function`?e.serializeDate:qF.serializeDate,skipNulls:typeof e.skipNulls==`boolean`?e.skipNulls:qF.skipNulls,sort:typeof e.sort==`function`?e.sort:null,strictNullHandling:typeof e.strictNullHandling==`boolean`?e.strictNullHandling:qF.strictNullHandling}}function QF(e,t={}){let n=e,r=ZF(t),i,a;typeof r.filter==`function`?(a=r.filter,n=a(``,n)):dF(r.filter)&&(a=r.filter,i=a);let o=[];if(typeof n!=`object`||!n)return``;let s=WF[r.arrayFormat],c=s===`comma`&&r.commaRoundTrip;i||=Object.keys(n),r.sort&&i.sort(r.sort);let l=new WeakMap;for(let e=0;e<i.length;++e){let t=i[e];r.skipNulls&&n[t]===null||GF(o,XF(n[t],t,s,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,l))}let u=o.join(r.delimiter),d=r.addQueryPrefix===!0?`?`:``;return r.charsetSentinel&&(r.charset===`iso-8859-1`?d+=`utf8=%26%2310003%3B&`:d+=`utf8=%E2%9C%93&`),u.length>0?d+u:``}function $F(e){return QF(e,{arrayFormat:`brackets`})}function eI(e){let t=0;for(let n of e)t+=n.length;let n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}var tI;function nI(e){let t;return(tI??=(t=new globalThis.TextEncoder,t.encode.bind(t)))(e)}var rI;function iI(e){let t;return(rI??=(t=new globalThis.TextDecoder,t.decode.bind(t)))(e)}var aI,oI,sI=class{constructor(){aI.set(this,void 0),oI.set(this,void 0),U(this,aI,new Uint8Array,`f`),U(this,oI,null,`f`)}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e==`string`?nI(e):e;U(this,aI,eI([W(this,aI,`f`),t]),`f`);let n=[],r;for(;(r=cI(W(this,aI,`f`),W(this,oI,`f`)))!=null;){if(r.carriage&&W(this,oI,`f`)==null){U(this,oI,r.index,`f`);continue}if(W(this,oI,`f`)!=null&&(r.index!==W(this,oI,`f`)+1||r.carriage)){n.push(iI(W(this,aI,`f`).subarray(0,W(this,oI,`f`)-1))),U(this,aI,W(this,aI,`f`).subarray(W(this,oI,`f`)),`f`),U(this,oI,null,`f`);continue}let e=W(this,oI,`f`)===null?r.preceding:r.preceding-1,t=iI(W(this,aI,`f`).subarray(0,e));n.push(t),U(this,aI,W(this,aI,`f`).subarray(r.index),`f`),U(this,oI,null,`f`)}return n}flush(){return W(this,aI,`f`).length?this.decode(`
153
- `):[]}};aI=new WeakMap,oI=new WeakMap,sI.NEWLINE_CHARS=new Set([`
154
- `,`\r`]),sI.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function cI(e,t){for(let n=t??0;n<e.length;n++){if(e[n]===10)return{preceding:n,index:n+1,carriage:!1};if(e[n]===13)return{preceding:n,index:n+1,carriage:!0}}return null}function lI(e){for(let t=0;t<e.length-1;t++){if(e[t]===10&&e[t+1]===10||e[t]===13&&e[t+1]===13)return t+2;if(e[t]===13&&e[t+1]===10&&t+3<e.length&&e[t+2]===13&&e[t+3]===10)return t+4}return-1}var uI={off:0,error:200,warn:300,info:400,debug:500},dI=(e,t,n)=>{if(e){if(hF(uI,e))return e;gI(n).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(uI))}`)}};function fI(){}function pI(e,t,n){return!t||uI[e]>uI[n]?fI:t[e].bind(t)}var mI={error:fI,warn:fI,info:fI,debug:fI},hI=new WeakMap;function gI(e){let t=e.logger,n=e.logLevel??`off`;if(!t)return mI;let r=hI.get(t);if(r&&r[0]===n)return r[1];let i={error:pI(`error`,t,n),warn:pI(`warn`,t,n),info:pI(`info`,t,n),debug:pI(`debug`,t,n)};return hI.set(t,[n,i]),i}var _I=e=>(e.options&&(e.options={...e.options},delete e.options.headers),e.headers&&=Object.fromEntries((e.headers instanceof Headers?[...e.headers]:Object.entries(e.headers)).map(([e,t])=>[e,e.toLowerCase()===`authorization`||e.toLowerCase()===`cookie`||e.toLowerCase()===`set-cookie`?`***`:t])),`retryOfRequestLogID`in e&&(e.retryOfRequestLogID&&(e.retryOf=e.retryOfRequestLogID),delete e.retryOfRequestLogID),e),vI,yI=class e{constructor(e,t,n){this.iterator=e,vI.set(this,void 0),this.controller=t,U(this,vI,n,`f`)}static fromSSEResponse(t,n,r,i){let a=!1,o=r?gI(r):console;async function*s(){if(a)throw new G("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");a=!0;let e=!1;try{for await(let r of bI(t,n))if(!e){if(r.data.startsWith(`[DONE]`)){e=!0;continue}if(r.event===null||!r.event.startsWith(`thread.`)){let e;try{e=JSON.parse(r.data)}catch(e){throw o.error(`Could not parse message into JSON:`,r.data),o.error(`From chunk:`,r.raw),e}if(e&&e.error)throw new KP(void 0,e.error,void 0,t.headers);yield i?{event:r.event,data:e}:e}else{let e;try{e=JSON.parse(r.data)}catch(e){throw console.error(`Could not parse message into JSON:`,r.data),console.error(`From chunk:`,r.raw),e}if(r.event==`error`)throw new KP(void 0,e.error,e.message,void 0);yield{event:r.event,data:e}}}e=!0}catch(e){if(WP(e))return;throw e}finally{e||n.abort()}}return new e(s,n,r)}static fromReadableStream(t,n,r){let i=!1;async function*a(){let e=new sI,n=MF(t);for await(let t of n)for(let n of e.decode(t))yield n;for(let t of e.flush())yield t}async function*o(){if(i)throw new G("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");i=!0;let e=!1;try{for await(let t of a())e||t&&(yield JSON.parse(t));e=!0}catch(e){if(WP(e))return;throw e}finally{e||n.abort()}}return new e(o,n,r)}[(vI=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let t=[],n=[],r=this.iterator(),i=e=>({next:()=>{if(e.length===0){let e=r.next();t.push(e),n.push(e)}return e.shift()}});return[new e(()=>i(t),this.controller,W(this,vI,`f`)),new e(()=>i(n),this.controller,W(this,vI,`f`))]}toReadableStream(){let e=this,t;return AF({async start(){t=e[Symbol.asyncIterator]()},async pull(e){try{let{value:n,done:r}=await t.next();if(r)return e.close();let i=nI(JSON.stringify(n)+`
155
- `);e.enqueue(i)}catch(t){e.error(t)}},async cancel(){await t.return?.()}})}};async function*bI(e,t){if(!e.body)throw t.abort(),globalThis.navigator!==void 0&&globalThis.navigator.product===`ReactNative`?new G(`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 G(`Attempted to iterate over a response with no body`);let n=new SI,r=new sI,i=MF(e.body);for await(let e of xI(i))for(let t of r.decode(e)){let e=n.decode(t);e&&(yield e)}for(let e of r.flush()){let t=n.decode(e);t&&(yield t)}}async function*xI(e){let t=new Uint8Array;for await(let n of e){if(n==null)continue;let e=n instanceof ArrayBuffer?new Uint8Array(n):typeof n==`string`?nI(n):n,r=new Uint8Array(t.length+e.length);r.set(t),r.set(e,t.length),t=r;let i;for(;(i=lI(t))!==-1;)yield t.slice(0,i),t=t.slice(i)}t.length>0&&(yield t)}var SI=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;let e={event:this.event,data:this.data.join(`
156
- `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],e}if(this.chunks.push(e),e.startsWith(`:`))return null;let[t,n,r]=CI(e,`:`);return r.startsWith(` `)&&(r=r.substring(1)),t===`event`?this.event=r:t===`data`&&this.data.push(r),null}};function CI(e,t){let n=e.indexOf(t);return n===-1?[e,``,``]:[e.substring(0,n),t,e.substring(n+t.length)]}async function wI(e,t){let{response:n,requestLogID:r,retryOfRequestLogID:i,startTime:a}=t,o=await(async()=>{if(t.options.stream)return gI(e).debug(`response`,n.status,n.url,n.headers,n.body),t.options.__streamClass?t.options.__streamClass.fromSSEResponse(n,t.controller,e,t.options.__synthesizeEventData):yI.fromSSEResponse(n,t.controller,e,t.options.__synthesizeEventData);if(n.status===204)return null;if(t.options.__binaryResponse)return n;let r=n.headers.get(`content-type`)?.split(`;`)[0]?.trim();return r?.includes(`application/json`)||r?.endsWith(`+json`)?n.headers.get(`content-length`)===`0`?void 0:TI(await n.json(),n):await n.text()})();return gI(e).debug(`[${r}] response parsed`,_I({retryOfRequestLogID:i,url:n.url,status:n.status,body:o,durationMs:Date.now()-a})),o}function TI(e,t){return!e||typeof e!=`object`||Array.isArray(e)?e:Object.defineProperty(e,`_request_id`,{value:t.headers.get(`x-request-id`),enumerable:!1})}var EI,DI=class e extends Promise{constructor(e,t,n=wI){super(e=>{e(null)}),this.responsePromise=t,this.parseResponse=n,EI.set(this,void 0),U(this,EI,e,`f`)}_thenUnwrap(t){return new e(W(this,EI,`f`),this.responsePromise,async(e,n)=>TI(t(await this.parseResponse(e,n),n),n.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t,request_id:t.headers.get(`x-request-id`)}}parse(){return this.parsedPromise||=this.responsePromise.then(e=>this.parseResponse(W(this,EI,`f`),e)),this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}};EI=new WeakMap;var OI,kI=class{constructor(e,t,n,r){OI.set(this,void 0),U(this,OI,e,`f`),this.options=r,this.response=t,this.body=n}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new G("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await W(this,OI,`f`).requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(OI=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}},AI=class extends DI{constructor(e,t,n){super(e,t,async(e,t)=>new n(e,t.response,await wI(e,t),t.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}},jI=class extends kI{constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.object=n.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}},MI=class extends kI{constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.has_more=n.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.getPaginatedItems(),t=e[e.length-1]?.id;return t?{...this.options,query:{...pF(this.options.query),after:t}}:null}},NI=class extends kI{constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.has_more=n.has_more||!1,this.last_id=n.last_id||``}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.last_id;return e?{...this.options,query:{...pF(this.options.query),after:e}}:null}},PI={jwt:`urn:ietf:params:oauth:token-type:jwt`,id:`urn:ietf:params:oauth:token-type:id_token`},FI=`urn:ietf:params:oauth:grant-type:token-exchange`,II=class{constructor(e,t){this.cachedToken=null,this.refreshPromise=null,this.tokenExchangeUrl=`https://auth.openai.com/oauth/token`,this.config=e,this.fetch=t??kF()}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(){let e=await this.config.provider.getToken(),t=await this.fetch(this.tokenExchangeUrl,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({grant_type:FI,client_id:this.config.clientId,subject_token:e,subject_token_type:PI[this.config.provider.tokenType],identity_provider_id:this.config.identityProviderId,service_account_id:this.config.serviceAccountId})});if(!t.ok){let e=await t.text(),n;try{n=JSON.parse(e)}catch{}throw t.status===400||t.status===401||t.status===403?new sF(t.status,n,t.headers):KP.generate(t.status,n,`Token exchange failed with status ${t.status}`,t.headers)}let n=await t.json(),r=n.expires_in||3600,i=Date.now()+r*1e3;return this.cachedToken={token:n.access_token,expiresAt:i},n.access_token}isTokenExpired(e){return Date.now()>=e.expiresAt}needsRefresh(e){let t=(this.config.refreshBufferSeconds??1200)*1e3;return Date.now()>=e.expiresAt-t}invalidateToken(){this.cachedToken=null,this.refreshPromise=null}},LI=()=>{if(typeof File>`u`){let{process:e}=globalThis,t=typeof e?.versions?.node==`string`&&parseInt(e.versions.node.split(`.`))<20;throw Error("`File` is not defined as a global, which is required for file uploads."+(t?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":``))}};function RI(e,t,n){return LI(),new File(e,t??`unknown_file`,n)}function zI(e){return(typeof e==`object`&&!!e&&(`name`in e&&e.name&&String(e.name)||`url`in e&&e.url&&String(e.url)||`filename`in e&&e.filename&&String(e.filename)||`path`in e&&e.path&&String(e.path))||``).split(/[\\/]/).pop()||void 0}var BI=e=>typeof e==`object`&&!!e&&typeof e[Symbol.asyncIterator]==`function`,VI=async(e,t)=>JI(e.body)?{...e,body:await GI(e.body,t)}:e,HI=async(e,t)=>({...e,body:await GI(e.body,t)}),UI=new WeakMap;function WI(e){let t=typeof e==`function`?e:e.fetch,n=UI.get(t);if(n)return n;let r=(async()=>{try{let e=`Response`in t?t.Response:(await t(`data:,`)).constructor,n=new FormData;return n.toString()!==await new e(n).text()}catch{return!0}})();return UI.set(t,r),r}var GI=async(e,t)=>{if(!await WI(t))throw TypeError(`The provided fetch function does not support file uploads with the current global FormData class.`);let n=new FormData;return await Promise.all(Object.entries(e||{}).map(([e,t])=>YI(n,e,t))),n},KI=e=>e instanceof Blob&&`name`in e,qI=e=>typeof e==`object`&&!!e&&(e instanceof Response||BI(e)||KI(e)),JI=e=>{if(qI(e))return!0;if(Array.isArray(e))return e.some(JI);if(e&&typeof e==`object`){for(let t in e)if(JI(e[t]))return!0}return!1},YI=async(e,t,n)=>{if(n!==void 0){if(n==null)throw TypeError(`Received null for "${t}"; to pass null in FormData, you must use the string 'null'`);if(typeof n==`string`||typeof n==`number`||typeof n==`boolean`)e.append(t,String(n));else if(n instanceof Response)e.append(t,RI([await n.blob()],zI(n)));else if(BI(n))e.append(t,RI([await new Response(jF(n)).blob()],zI(n)));else if(KI(n))e.append(t,n,zI(n));else if(Array.isArray(n))await Promise.all(n.map(n=>YI(e,t+`[]`,n)));else if(typeof n==`object`)await Promise.all(Object.entries(n).map(([n,r])=>YI(e,`${t}[${n}]`,r)));else throw TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${n} instead`)}},XI=e=>typeof e==`object`&&!!e&&typeof e.size==`number`&&typeof e.type==`string`&&typeof e.text==`function`&&typeof e.slice==`function`&&typeof e.arrayBuffer==`function`,ZI=e=>typeof e==`object`&&!!e&&typeof e.name==`string`&&typeof e.lastModified==`number`&&XI(e),QI=e=>typeof e==`object`&&!!e&&typeof e.url==`string`&&typeof e.blob==`function`;async function $I(e,t,n){if(LI(),e=await e,ZI(e))return e instanceof File?e:RI([await e.arrayBuffer()],e.name);if(QI(e)){let r=await e.blob();return t||=new URL(e.url).pathname.split(/[\\/]/).pop(),RI(await eL(r),t,n)}let r=await eL(e);if(t||=zI(e),!n?.type){let e=r.find(e=>typeof e==`object`&&`type`in e&&e.type);typeof e==`string`&&(n={...n,type:e})}return RI(r,t,n)}async function eL(e){let t=[];if(typeof e==`string`||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(XI(e))t.push(e instanceof Blob?e:await e.arrayBuffer());else if(BI(e))for await(let n of e)t.push(...await eL(n));else{let t=e?.constructor?.name;throw Error(`Unexpected data type: ${typeof e}${t?`; constructor: ${t}`:``}${tL(e)}`)}return t}function tL(e){return typeof e!=`object`||!e?``:`; props: [${Object.getOwnPropertyNames(e).map(e=>`"${e}"`).join(`, `)}]`}var K=class{constructor(e){this._client=e}};function nL(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var rL=Object.freeze(Object.create(null)),q=((e=nL)=>function(t,...n){if(t.length===1)return t[0];let r=!1,i=[],a=t.reduce((t,a,o)=>{/[?#]/.test(a)&&(r=!0);let s=n[o],c=(r?encodeURIComponent:e)(``+s);return o!==n.length&&(s==null||typeof s==`object`&&s.toString===Object.getPrototypeOf(Object.getPrototypeOf(s.hasOwnProperty??rL)??rL)?.toString)&&(c=s+``,i.push({start:t.length+a.length,length:c.length,error:`Value of type ${Object.prototype.toString.call(s).slice(8,-1)} is not a valid path parameter`})),t+a+(o===n.length?``:c)},``),o=a.split(/[?#]/,1)[0],s=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,c;for(;(c=s.exec(o))!==null;)i.push({start:c.index,length:c[0].length,error:`Value "${c[0]}" can\'t be safely passed as a path parameter`});if(i.sort((e,t)=>e.start-t.start),i.length>0){let e=0,t=i.reduce((t,n)=>{let r=` `.repeat(n.start-e),i=`^`.repeat(n.length);return e=n.start+n.length,t+r+i},``);throw new G(`Path parameters result in path with invalid segments:\n${i.map(e=>e.error).join(`
157
- `)}\n${a}\n${t}`)}return a})(nL),iL=class extends K{list(e,t={},n){return this._client.getAPIList(q`/chat/completions/${e}/messages`,MI,{query:t,...n})}};function aL(e){return e!==void 0&&`function`in e&&e.function!==void 0}function oL(e,t){let n={...e};return Object.defineProperties(n,{$brand:{value:`auto-parseable-response-format`,enumerable:!1},$parseRaw:{value:t,enumerable:!1}}),n}function sL(e){return e?.$brand===`auto-parseable-response-format`}function cL(e){return e?.$brand===`auto-parseable-tool`}function lL(e,t){return!t||!mL(t)?{...e,choices:e.choices.map(e=>(hL(e.message.tool_calls),{...e,message:{...e.message,parsed:null,...e.message.tool_calls?{tool_calls:e.message.tool_calls}:void 0}}))}:uL(e,t)}function uL(e,t){let n=e.choices.map(e=>{if(e.finish_reason===`length`)throw new iF;if(e.finish_reason===`content_filter`)throw new aF;return hL(e.message.tool_calls),{...e,message:{...e.message,...e.message.tool_calls?{tool_calls:e.message.tool_calls?.map(e=>fL(t,e))??void 0}:void 0,parsed:e.message.content&&!e.message.refusal?dL(t,e.message.content):null}}});return{...e,choices:n}}function dL(e,t){return e.response_format?.type===`json_schema`&&e.response_format?.type===`json_schema`?`$parseRaw`in e.response_format?e.response_format.$parseRaw(t):JSON.parse(t):null}function fL(e,t){let n=e.tools?.find(e=>aL(e)&&e.function?.name===t.function.name);return{...t,function:{...t.function,parsed_arguments:cL(n)?n.$parseRaw(t.function.arguments):n?.function.strict?JSON.parse(t.function.arguments):null}}}function pL(e,t){if(!e||!(`tools`in e)||!e.tools)return!1;let n=e.tools?.find(e=>aL(e)&&e.function?.name===t.function.name);return aL(n)&&(cL(n)||n?.function.strict||!1)}function mL(e){return sL(e.response_format)?!0:e.tools?.some(e=>cL(e)||e.type===`function`&&e.function.strict===!0)??!1}function hL(e){for(let t of e||[])if(t.type!==`function`)throw new G(`Currently only \`function\` tool calls are supported; Received \`${t.type}\``)}function gL(e){for(let t of e??[]){if(t.type!==`function`)throw new G(`Currently only \`function\` tool types support auto-parsing; Received \`${t.type}\``);if(t.function.strict!==!0)throw new G(`The \`${t.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var _L=e=>e?.role===`assistant`,vL=e=>e?.role===`tool`,yL,bL,xL,SL,CL,wL,TL,EL,DL,OL,kL,AL,jL,ML=class{constructor(){yL.add(this),this.controller=new AbortController,bL.set(this,void 0),xL.set(this,()=>{}),SL.set(this,()=>{}),CL.set(this,void 0),wL.set(this,()=>{}),TL.set(this,()=>{}),EL.set(this,{}),DL.set(this,!1),OL.set(this,!1),kL.set(this,!1),AL.set(this,!1),U(this,bL,new Promise((e,t)=>{U(this,xL,e,`f`),U(this,SL,t,`f`)}),`f`),U(this,CL,new Promise((e,t)=>{U(this,wL,e,`f`),U(this,TL,t,`f`)}),`f`),W(this,bL,`f`).catch(()=>{}),W(this,CL,`f`).catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit(`end`)},W(this,yL,`m`,jL).bind(this))},0)}_connected(){this.ended||(W(this,xL,`f`).call(this),this._emit(`connect`))}get ended(){return W(this,DL,`f`)}get errored(){return W(this,OL,`f`)}get aborted(){return W(this,kL,`f`)}abort(){this.controller.abort()}on(e,t){return(W(this,EL,`f`)[e]||(W(this,EL,`f`)[e]=[])).push({listener:t}),this}off(e,t){let n=W(this,EL,`f`)[e];if(!n)return this;let r=n.findIndex(e=>e.listener===t);return r>=0&&n.splice(r,1),this}once(e,t){return(W(this,EL,`f`)[e]||(W(this,EL,`f`)[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,n)=>{U(this,AL,!0,`f`),e!==`error`&&this.once(`error`,n),this.once(e,t)})}async done(){U(this,AL,!0,`f`),await W(this,CL,`f`)}_emit(e,...t){if(W(this,DL,`f`))return;e===`end`&&(U(this,DL,!0,`f`),W(this,wL,`f`).call(this));let n=W(this,EL,`f`)[e];if(n&&(W(this,EL,`f`)[e]=n.filter(e=>!e.once),n.forEach(({listener:e})=>e(...t))),e===`abort`){let e=t[0];!W(this,AL,`f`)&&!n?.length&&Promise.reject(e),W(this,SL,`f`).call(this,e),W(this,TL,`f`).call(this,e),this._emit(`end`);return}if(e===`error`){let e=t[0];!W(this,AL,`f`)&&!n?.length&&Promise.reject(e),W(this,SL,`f`).call(this,e),W(this,TL,`f`).call(this,e),this._emit(`end`)}}_emitFinal(){}};bL=new WeakMap,xL=new WeakMap,SL=new WeakMap,CL=new WeakMap,wL=new WeakMap,TL=new WeakMap,EL=new WeakMap,DL=new WeakMap,OL=new WeakMap,kL=new WeakMap,AL=new WeakMap,yL=new WeakSet,jL=function(e){if(U(this,OL,!0,`f`),e instanceof Error&&e.name===`AbortError`&&(e=new qP),e instanceof qP)return U(this,kL,!0,`f`),this._emit(`abort`,e);if(e instanceof G)return this._emit(`error`,e);if(e instanceof Error){let t=new G(e.message);return t.cause=e,this._emit(`error`,t)}return this._emit(`error`,new G(String(e)))};function NL(e){return typeof e.parse==`function`}var PL,FL,IL,LL,RL,zL,BL,VL,HL=10,UL=class extends ML{constructor(){super(...arguments),PL.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){this._chatCompletions.push(e),this._emit(`chatCompletion`,e);let t=e.choices[0]?.message;return t&&this._addMessage(t),e}_addMessage(e,t=!0){if(`content`in e||(e.content=null),this.messages.push(e),t){if(this._emit(`message`,e),vL(e)&&e.content)this._emit(`functionToolCallResult`,e.content);else if(_L(e)&&e.tool_calls)for(let t of e.tool_calls)t.type===`function`&&this._emit(`functionToolCall`,t.function)}}async finalChatCompletion(){await this.done();let e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new G(`stream ended without producing a ChatCompletion`);return e}async finalContent(){return await this.done(),W(this,PL,`m`,FL).call(this)}async finalMessage(){return await this.done(),W(this,PL,`m`,IL).call(this)}async finalFunctionToolCall(){return await this.done(),W(this,PL,`m`,LL).call(this)}async finalFunctionToolCallResult(){return await this.done(),W(this,PL,`m`,RL).call(this)}async totalUsage(){return await this.done(),W(this,PL,`m`,zL).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit(`finalChatCompletion`,e);let t=W(this,PL,`m`,IL).call(this);t&&this._emit(`finalMessage`,t);let n=W(this,PL,`m`,FL).call(this);n&&this._emit(`finalContent`,n);let r=W(this,PL,`m`,LL).call(this);r&&this._emit(`finalFunctionToolCall`,r);let i=W(this,PL,`m`,RL).call(this);i!=null&&this._emit(`finalFunctionToolCallResult`,i),this._chatCompletions.some(e=>e.usage)&&this._emit(`totalUsage`,W(this,PL,`m`,zL).call(this))}async _createChatCompletion(e,t,n){let r=n?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener(`abort`,()=>this.controller.abort())),W(this,PL,`m`,BL).call(this,t);let i=await e.chat.completions.create({...t,stream:!1},{...n,signal:this.controller.signal});return this._connected(),this._addChatCompletion(uL(i,t))}async _runChatCompletion(e,t,n){for(let e of t.messages)this._addMessage(e,!1);return await this._createChatCompletion(e,t,n)}async _runTools(e,t,n){let r=`tool`,{tool_choice:i=`auto`,stream:a,...o}=t,s=typeof i!=`string`&&i.type===`function`&&i?.function?.name,{maxChatCompletions:c=HL}=n||{},l=t.tools.map(e=>{if(cL(e)){if(!e.$callback)throw new G("Tool given to `.runTools()` that does not have an associated function");return{type:`function`,function:{function:e.$callback,name:e.function.name,description:e.function.description||``,parameters:e.function.parameters,parse:e.$parseRaw,strict:!0}}}return e}),u={};for(let e of l)e.type===`function`&&(u[e.function.name||e.function.function.name]=e.function);let d=`tools`in t?l.map(e=>e.type===`function`?{type:`function`,function:{name:e.function.name||e.function.function.name,parameters:e.function.parameters,description:e.function.description,strict:e.function.strict}}:e):void 0;for(let e of t.messages)this._addMessage(e,!1);for(let t=0;t<c;++t){let t=(await this._createChatCompletion(e,{...o,tool_choice:i,tools:d,messages:[...this.messages]},n)).choices[0]?.message;if(!t)throw new G(`missing message in ChatCompletion response`);if(!t.tool_calls?.length)return;for(let e of t.tool_calls){if(e.type!==`function`)continue;let t=e.id,{name:n,arguments:i}=e.function,a=u[n];if(!a){let e=`Invalid tool_call: ${JSON.stringify(n)}. Available options are: ${Object.keys(u).map(e=>JSON.stringify(e)).join(`, `)}. Please try again`;this._addMessage({role:r,tool_call_id:t,content:e});continue}else if(s&&s!==n){let e=`Invalid tool_call: ${JSON.stringify(n)}. ${JSON.stringify(s)} requested. Please try again`;this._addMessage({role:r,tool_call_id:t,content:e});continue}let o;try{o=NL(a)?await a.parse(i):i}catch(e){let n=e instanceof Error?e.message:String(e);this._addMessage({role:r,tool_call_id:t,content:n});continue}let c=await a.function(o,this),l=W(this,PL,`m`,VL).call(this,c);if(this._addMessage({role:r,tool_call_id:t,content:l}),s)return}}}};PL=new WeakSet,FL=function(){return W(this,PL,`m`,IL).call(this).content??null},IL=function(){let e=this.messages.length;for(;e-- >0;){let t=this.messages[e];if(_L(t))return{...t,content:t.content??null,refusal:t.refusal??null}}throw new G(`stream ended without producing a ChatCompletionMessage with role=assistant`)},LL=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(_L(t)&&t?.tool_calls?.length)return t.tool_calls.filter(e=>e.type===`function`).at(-1)?.function}},RL=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(vL(t)&&t.content!=null&&typeof t.content==`string`&&this.messages.some(e=>e.role===`assistant`&&e.tool_calls?.some(e=>e.type===`function`&&e.id===t.tool_call_id)))return t.content}},zL=function(){let e={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(let{usage:t}of this._chatCompletions)t&&(e.completion_tokens+=t.completion_tokens,e.prompt_tokens+=t.prompt_tokens,e.total_tokens+=t.total_tokens);return e},BL=function(e){if(e.n!=null&&e.n>1)throw new G(`ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.`)},VL=function(e){return typeof e==`string`?e:e===void 0?`undefined`:JSON.stringify(e)};var WL=class e extends UL{static runTools(t,n,r){let i=new e,a={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`runTools`}};return i._run(()=>i._runTools(t,n,a)),i}_addMessage(e,t=!0){super._addMessage(e,t),_L(e)&&e.content&&this._emit(`content`,e.content)}},GL=1,KL=2,qL=4,JL=8,YL=16,XL=32,ZL=64,QL=128,$L=256,eR=QL|$L,tR=496,nR=KL|497,rR=qL|JL,iR={STR:GL,NUM:KL,ARR:qL,OBJ:JL,NULL:YL,BOOL:XL,NAN:ZL,INFINITY:QL,MINUS_INFINITY:$L,INF:eR,SPECIAL:tR,ATOM:nR,COLLECTION:rR,ALL:nR|rR},aR=class extends Error{},oR=class extends Error{};function sR(e,t=iR.ALL){if(typeof e!=`string`)throw TypeError(`expecting str, got ${typeof e}`);if(!e.trim())throw Error(`${e} is empty`);return cR(e.trim(),t)}var cR=(e,t)=>{let n=e.length,r=0,i=e=>{throw new aR(`${e} at position ${r}`)},a=e=>{throw new oR(`${e} at position ${r}`)},o=()=>(d(),r>=n&&i(`Unexpected end of input`),e[r]===`"`?s():e[r]===`{`?c():e[r]===`[`?l():e.substring(r,r+4)===`null`||iR.NULL&t&&n-r<4&&`null`.startsWith(e.substring(r))?(r+=4,null):e.substring(r,r+4)===`true`||iR.BOOL&t&&n-r<4&&`true`.startsWith(e.substring(r))?(r+=4,!0):e.substring(r,r+5)===`false`||iR.BOOL&t&&n-r<5&&`false`.startsWith(e.substring(r))?(r+=5,!1):e.substring(r,r+8)===`Infinity`||iR.INFINITY&t&&n-r<8&&`Infinity`.startsWith(e.substring(r))?(r+=8,1/0):e.substring(r,r+9)===`-Infinity`||iR.MINUS_INFINITY&t&&1<n-r&&n-r<9&&`-Infinity`.startsWith(e.substring(r))?(r+=9,-1/0):e.substring(r,r+3)===`NaN`||iR.NAN&t&&n-r<3&&`NaN`.startsWith(e.substring(r))?(r+=3,NaN):u()),s=()=>{let o=r,s=!1;for(r++;r<n&&(e[r]!==`"`||s&&e[r-1]===`\\`);)s=e[r]===`\\`?!s:!1,r++;if(e.charAt(r)==`"`)try{return JSON.parse(e.substring(o,++r-Number(s)))}catch(e){a(String(e))}else if(iR.STR&t)try{return JSON.parse(e.substring(o,r-Number(s))+`"`)}catch{return JSON.parse(e.substring(o,e.lastIndexOf(`\\`))+`"`)}i(`Unterminated string literal`)},c=()=>{r++,d();let a={};try{for(;e[r]!==`}`;){if(d(),r>=n&&iR.OBJ&t)return a;let i=s();d(),r++;try{let e=o();Object.defineProperty(a,i,{value:e,writable:!0,enumerable:!0,configurable:!0})}catch(e){if(iR.OBJ&t)return a;throw e}d(),e[r]===`,`&&r++}}catch{if(iR.OBJ&t)return a;i(`Expected '}' at end of object`)}return r++,a},l=()=>{r++;let n=[];try{for(;e[r]!==`]`;)n.push(o()),d(),e[r]===`,`&&r++}catch{if(iR.ARR&t)return n;i(`Expected ']' at end of array`)}return r++,n},u=()=>{if(r===0){e===`-`&&iR.NUM&t&&i(`Not sure what '-' is`);try{return JSON.parse(e)}catch(n){if(iR.NUM&t)try{return e[e.length-1]===`.`?JSON.parse(e.substring(0,e.lastIndexOf(`.`))):JSON.parse(e.substring(0,e.lastIndexOf(`e`)))}catch{}a(String(n))}}let o=r;for(e[r]===`-`&&r++;e[r]&&!`,]}`.includes(e[r]);)r++;r==n&&!(iR.NUM&t)&&i(`Unterminated number literal`);try{return JSON.parse(e.substring(o,r))}catch{e.substring(o,r)===`-`&&iR.NUM&t&&i(`Not sure what '-' is`);try{return JSON.parse(e.substring(o,e.lastIndexOf(`e`)))}catch(e){a(String(e))}}},d=()=>{for(;r<n&&`
158
- \r `.includes(e[r]);)r++};return o()},lR=e=>sR(e,iR.ALL^iR.NUM),uR,dR,fR,pR,mR,hR,gR,_R,vR,yR,bR,xR,SR=class e extends UL{constructor(e){super(),uR.add(this),dR.set(this,void 0),fR.set(this,void 0),pR.set(this,void 0),U(this,dR,e,`f`),U(this,fR,[],`f`)}get currentChatCompletionSnapshot(){return W(this,pR,`f`)}static fromReadableStream(t){let n=new e(null);return n._run(()=>n._fromReadableStream(t)),n}static createChatCompletion(t,n,r){let i=new e(n);return i._run(()=>i._runChatCompletion(t,{...n,stream:!0},{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`stream`}})),i}async _createChatCompletion(e,t,n){super._createChatCompletion;let r=n?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener(`abort`,()=>this.controller.abort())),W(this,uR,`m`,mR).call(this);let i=await e.chat.completions.create({...t,stream:!0},{...n,signal:this.controller.signal});this._connected();for await(let e of i)W(this,uR,`m`,gR).call(this,e);if(i.controller.signal?.aborted)throw new qP;return this._addChatCompletion(W(this,uR,`m`,yR).call(this))}async _fromReadableStream(e,t){let n=t?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener(`abort`,()=>this.controller.abort())),W(this,uR,`m`,mR).call(this),this._connected();let r=yI.fromReadableStream(e,this.controller),i;for await(let e of r)i&&i!==e.id&&this._addChatCompletion(W(this,uR,`m`,yR).call(this)),W(this,uR,`m`,gR).call(this,e),i=e.id;if(r.controller.signal?.aborted)throw new qP;return this._addChatCompletion(W(this,uR,`m`,yR).call(this))}[(dR=new WeakMap,fR=new WeakMap,pR=new WeakMap,uR=new WeakSet,mR=function(){this.ended||U(this,pR,void 0,`f`)},hR=function(e){let t=W(this,fR,`f`)[e.index];return t||(t={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},W(this,fR,`f`)[e.index]=t,t)},gR=function(e){if(this.ended)return;let t=W(this,uR,`m`,xR).call(this,e);this._emit(`chunk`,e,t);for(let n of e.choices){let e=t.choices[n.index];n.delta.content!=null&&e.message?.role===`assistant`&&e.message?.content&&(this._emit(`content`,n.delta.content,e.message.content),this._emit(`content.delta`,{delta:n.delta.content,snapshot:e.message.content,parsed:e.message.parsed})),n.delta.refusal!=null&&e.message?.role===`assistant`&&e.message?.refusal&&this._emit(`refusal.delta`,{delta:n.delta.refusal,snapshot:e.message.refusal}),n.logprobs?.content!=null&&e.message?.role===`assistant`&&this._emit(`logprobs.content.delta`,{content:n.logprobs?.content,snapshot:e.logprobs?.content??[]}),n.logprobs?.refusal!=null&&e.message?.role===`assistant`&&this._emit(`logprobs.refusal.delta`,{refusal:n.logprobs?.refusal,snapshot:e.logprobs?.refusal??[]});let r=W(this,uR,`m`,hR).call(this,e);e.finish_reason&&(W(this,uR,`m`,vR).call(this,e),r.current_tool_call_index!=null&&W(this,uR,`m`,_R).call(this,e,r.current_tool_call_index));for(let t of n.delta.tool_calls??[])r.current_tool_call_index!==t.index&&(W(this,uR,`m`,vR).call(this,e),r.current_tool_call_index!=null&&W(this,uR,`m`,_R).call(this,e,r.current_tool_call_index)),r.current_tool_call_index=t.index;for(let t of n.delta.tool_calls??[]){let n=e.message.tool_calls?.[t.index];n?.type&&(n?.type===`function`?this._emit(`tool_calls.function.arguments.delta`,{name:n.function?.name,index:t.index,arguments:n.function.arguments,parsed_arguments:n.function.parsed_arguments,arguments_delta:t.function?.arguments??``}):n?.type)}}},_R=function(e,t){if(W(this,uR,`m`,hR).call(this,e).done_tool_calls.has(t))return;let n=e.message.tool_calls?.[t];if(!n)throw Error(`no tool call snapshot`);if(!n.type)throw Error("tool call snapshot missing `type`");if(n.type===`function`){let e=W(this,dR,`f`)?.tools?.find(e=>aL(e)&&e.function.name===n.function.name);this._emit(`tool_calls.function.arguments.done`,{name:n.function.name,index:t,arguments:n.function.arguments,parsed_arguments:cL(e)?e.$parseRaw(n.function.arguments):e?.function.strict?JSON.parse(n.function.arguments):null})}else n.type},vR=function(e){let t=W(this,uR,`m`,hR).call(this,e);if(e.message.content&&!t.content_done){t.content_done=!0;let n=W(this,uR,`m`,bR).call(this);this._emit(`content.done`,{content:e.message.content,parsed:n?n.$parseRaw(e.message.content):null})}e.message.refusal&&!t.refusal_done&&(t.refusal_done=!0,this._emit(`refusal.done`,{refusal:e.message.refusal})),e.logprobs?.content&&!t.logprobs_content_done&&(t.logprobs_content_done=!0,this._emit(`logprobs.content.done`,{content:e.logprobs.content})),e.logprobs?.refusal&&!t.logprobs_refusal_done&&(t.logprobs_refusal_done=!0,this._emit(`logprobs.refusal.done`,{refusal:e.logprobs.refusal}))},yR=function(){if(this.ended)throw new G(`stream has ended, this shouldn't happen`);let e=W(this,pR,`f`);if(!e)throw new G(`request ended without sending any chunks`);return U(this,pR,void 0,`f`),U(this,fR,[],`f`),CR(e,W(this,dR,`f`))},bR=function(){let e=W(this,dR,`f`)?.response_format;return sL(e)?e:null},xR=function(e){var t,n,r,i;let a=W(this,pR,`f`),{choices:o,...s}=e;a?Object.assign(a,s):a=U(this,pR,{...s,choices:[]},`f`);for(let{delta:o,finish_reason:s,index:c,logprobs:l=null,...u}of e.choices){let e=a.choices[c];if(e||=a.choices[c]={finish_reason:s,index:c,message:{},logprobs:l,...u},l)if(!e.logprobs)e.logprobs=Object.assign({},l);else{let{content:r,refusal:i,...a}=l;Object.assign(e.logprobs,a),r&&((t=e.logprobs).content??(t.content=[]),e.logprobs.content.push(...r)),i&&((n=e.logprobs).refusal??(n.refusal=[]),e.logprobs.refusal.push(...i))}if(s&&(e.finish_reason=s,W(this,dR,`f`)&&mL(W(this,dR,`f`)))){if(s===`length`)throw new iF;if(s===`content_filter`)throw new aF}if(Object.assign(e,u),!o)continue;let{content:d,refusal:f,function_call:p,role:m,tool_calls:h,...g}=o;if(Object.assign(e.message,g),f&&(e.message.refusal=(e.message.refusal||``)+f),m&&(e.message.role=m),p&&(e.message.function_call?(p.name&&(e.message.function_call.name=p.name),p.arguments&&((r=e.message.function_call).arguments??(r.arguments=``),e.message.function_call.arguments+=p.arguments)):e.message.function_call=p),d&&(e.message.content=(e.message.content||``)+d,!e.message.refusal&&W(this,uR,`m`,bR).call(this)&&(e.message.parsed=lR(e.message.content))),h){e.message.tool_calls||(e.message.tool_calls=[]);for(let{index:t,id:n,type:r,function:a,...o}of h){let s=(i=e.message.tool_calls)[t]??(i[t]={});Object.assign(s,o),n&&(s.id=n),r&&(s.type=r),a&&(s.function??={name:a.name??``,arguments:``}),a?.name&&(s.function.name=a.name),a?.arguments&&(s.function.arguments+=a.arguments,pL(W(this,dR,`f`),s)&&(s.function.parsed_arguments=lR(s.function.arguments)))}}}return a},Symbol.asyncIterator)](){let e=[],t=[],n=!1;return this.on(`chunk`,n=>{let r=t.shift();r?r.resolve(n):e.push(n)}),this.on(`end`,()=>{n=!0;for(let e of t)e.resolve(void 0);t.length=0}),this.on(`abort`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),this.on(`error`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((e,n)=>t.push({resolve:e,reject:n})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new yI(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};function CR(e,t){let{id:n,choices:r,created:i,model:a,system_fingerprint:o,...s}=e;return lL({...s,id:n,choices:r.map(({message:t,finish_reason:n,index:r,logprobs:i,...a})=>{if(!n)throw new G(`missing finish_reason for choice ${r}`);let{content:o=null,function_call:s,tool_calls:c,...l}=t,u=t.role;if(!u)throw new G(`missing role for choice ${r}`);if(s){let{arguments:e,name:c}=s;if(e==null)throw new G(`missing function_call.arguments for choice ${r}`);if(!c)throw new G(`missing function_call.name for choice ${r}`);return{...a,message:{content:o,function_call:{arguments:e,name:c},role:u,refusal:t.refusal??null},finish_reason:n,index:r,logprobs:i}}return c?{...a,index:r,finish_reason:n,logprobs:i,message:{...l,role:u,content:o,refusal:t.refusal??null,tool_calls:c.map((t,n)=>{let{function:i,type:a,id:o,...s}=t,{arguments:c,name:l,...u}=i||{};if(o==null)throw new G(`missing choices[${r}].tool_calls[${n}].id\n${wR(e)}`);if(a==null)throw new G(`missing choices[${r}].tool_calls[${n}].type\n${wR(e)}`);if(l==null)throw new G(`missing choices[${r}].tool_calls[${n}].function.name\n${wR(e)}`);if(c==null)throw new G(`missing choices[${r}].tool_calls[${n}].function.arguments\n${wR(e)}`);return{...s,id:o,type:a,function:{...u,name:l,arguments:c}}})}}:{...a,message:{...l,content:o,role:u,refusal:t.refusal??null},finish_reason:n,index:r,logprobs:i}}),created:i,model:a,object:`chat.completion`,...o?{system_fingerprint:o}:{}},t)}function wR(e){return JSON.stringify(e)}var TR=class e extends SR{static fromReadableStream(t){let n=new e(null);return n._run(()=>n._fromReadableStream(t)),n}static runTools(t,n,r){let i=new e(n),a={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`runTools`}};return i._run(()=>i._runTools(t,n,a)),i}},ER=class extends K{constructor(){super(...arguments),this.messages=new iL(this._client)}create(e,t){return this._client.post(`/chat/completions`,{body:e,...t,stream:e.stream??!1})}retrieve(e,t){return this._client.get(q`/chat/completions/${e}`,t)}update(e,t,n){return this._client.post(q`/chat/completions/${e}`,{body:t,...n})}list(e={},t){return this._client.getAPIList(`/chat/completions`,MI,{query:e,...t})}delete(e,t){return this._client.delete(q`/chat/completions/${e}`,t)}parse(e,t){return gL(e.tools),this._client.chat.completions.create(e,{...t,headers:{...t?.headers,"X-Stainless-Helper-Method":`chat.completions.parse`}})._thenUnwrap(t=>uL(t,e))}runTools(e,t){return e.stream?TR.runTools(this._client,e,t):WL.runTools(this._client,e,t)}stream(e,t){return SR.createChatCompletion(this._client,e,t)}};ER.Messages=iL;var DR=class extends K{constructor(){super(...arguments),this.completions=new ER(this._client)}};DR.Completions=ER;var OR=Symbol(`brand.privateNullableHeaders`);function*kR(e){if(!e)return;if(OR in e){let{values:t,nulls:n}=e;yield*t.entries();for(let e of n)yield[e,null];return}let t=!1,n;e instanceof Headers?n=e.entries():fF(e)?n=e:(t=!0,n=Object.entries(e??{}));for(let e of n){let n=e[0];if(typeof n!=`string`)throw TypeError(`expected header name to be a string`);let r=fF(e[1])?e[1]:[e[1]],i=!1;for(let e of r)e!==void 0&&(t&&!i&&(i=!0,yield[n,null]),yield[n,e])}}var J=e=>{let t=new Headers,n=new Set;for(let r of e){let e=new Set;for(let[i,a]of kR(r)){let r=i.toLowerCase();e.has(r)||(t.delete(i),e.add(r)),a===null?(t.delete(i),n.add(r)):(t.append(i,a),n.delete(r))}}return{[OR]:!0,values:t,nulls:n}},AR=class extends K{create(e,t){return this._client.post(`/audio/speech`,{body:e,...t,headers:J([{Accept:`application/octet-stream`},t?.headers]),__binaryResponse:!0})}},jR=class extends K{create(e,t){return this._client.post(`/audio/transcriptions`,HI({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model}},this._client))}},MR=class extends K{create(e,t){return this._client.post(`/audio/translations`,HI({body:e,...t,__metadata:{model:e.model}},this._client))}},NR=class extends K{constructor(){super(...arguments),this.transcriptions=new jR(this._client),this.translations=new MR(this._client),this.speech=new AR(this._client)}};NR.Transcriptions=jR,NR.Translations=MR,NR.Speech=AR;var PR=class extends K{create(e,t){return this._client.post(`/batches`,{body:e,...t})}retrieve(e,t){return this._client.get(q`/batches/${e}`,t)}list(e={},t){return this._client.getAPIList(`/batches`,MI,{query:e,...t})}cancel(e,t){return this._client.post(q`/batches/${e}/cancel`,t)}},FR=class extends K{create(e,t){return this._client.post(`/assistants`,{body:e,...t,headers:J([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}retrieve(e,t){return this._client.get(q`/assistants/${e}`,{...t,headers:J([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}update(e,t,n){return this._client.post(q`/assistants/${e}`,{body:t,...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}list(e={},t){return this._client.getAPIList(`/assistants`,MI,{query:e,...t,headers:J([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}delete(e,t){return this._client.delete(q`/assistants/${e}`,{...t,headers:J([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}},IR=class extends K{create(e,t){return this._client.post(`/realtime/sessions`,{body:e,...t,headers:J([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}},LR=class extends K{create(e,t){return this._client.post(`/realtime/transcription_sessions`,{body:e,...t,headers:J([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}},RR=class extends K{constructor(){super(...arguments),this.sessions=new IR(this._client),this.transcriptionSessions=new LR(this._client)}};RR.Sessions=IR,RR.TranscriptionSessions=LR;var zR=class extends K{create(e,t){return this._client.post(`/chatkit/sessions`,{body:e,...t,headers:J([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers])})}cancel(e,t){return this._client.post(q`/chatkit/sessions/${e}/cancel`,{...t,headers:J([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers])})}},BR=class extends K{retrieve(e,t){return this._client.get(q`/chatkit/threads/${e}`,{...t,headers:J([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers])})}list(e={},t){return this._client.getAPIList(`/chatkit/threads`,NI,{query:e,...t,headers:J([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers])})}delete(e,t){return this._client.delete(q`/chatkit/threads/${e}`,{...t,headers:J([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers])})}listItems(e,t={},n){return this._client.getAPIList(q`/chatkit/threads/${e}/items`,NI,{query:t,...n,headers:J([{"OpenAI-Beta":`chatkit_beta=v1`},n?.headers])})}},VR=class extends K{constructor(){super(...arguments),this.sessions=new zR(this._client),this.threads=new BR(this._client)}};VR.Sessions=zR,VR.Threads=BR;var HR=class extends K{create(e,t,n){return this._client.post(q`/threads/${e}/messages`,{body:t,...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}retrieve(e,t,n){let{thread_id:r}=t;return this._client.get(q`/threads/${r}/messages/${e}`,{...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}update(e,t,n){let{thread_id:r,...i}=t;return this._client.post(q`/threads/${r}/messages/${e}`,{body:i,...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}list(e,t={},n){return this._client.getAPIList(q`/threads/${e}/messages`,MI,{query:t,...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}delete(e,t,n){let{thread_id:r}=t;return this._client.delete(q`/threads/${r}/messages/${e}`,{...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}},UR=class extends K{retrieve(e,t,n){let{thread_id:r,run_id:i,...a}=t;return this._client.get(q`/threads/${r}/runs/${i}/steps/${e}`,{query:a,...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}list(e,t,n){let{thread_id:r,...i}=t;return this._client.getAPIList(q`/threads/${r}/runs/${e}/steps`,MI,{query:i,...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}},WR=e=>{if(typeof Buffer<`u`){let t=Buffer.from(e,`base64`);return Array.from(new Float32Array(t.buffer,t.byteOffset,t.length/Float32Array.BYTES_PER_ELEMENT))}else{let t=atob(e),n=t.length,r=new Uint8Array(n);for(let e=0;e<n;e++)r[e]=t.charCodeAt(e);return Array.from(new Float32Array(r.buffer))}},GR=e=>{if(globalThis.process!==void 0)return{}?.[e]?.trim()??void 0;if(globalThis.Deno!==void 0)return globalThis.Deno.env?.get?.(e)?.trim()},KR,qR,JR,YR,XR,ZR,QR,$R,ez,tz,nz,rz,iz,az,oz,sz,cz,lz,uz,dz,fz,pz,mz,hz=class extends ML{constructor(){super(...arguments),KR.add(this),JR.set(this,[]),YR.set(this,{}),XR.set(this,{}),ZR.set(this,void 0),QR.set(this,void 0),$R.set(this,void 0),ez.set(this,void 0),tz.set(this,void 0),nz.set(this,void 0),rz.set(this,void 0),iz.set(this,void 0),az.set(this,void 0)}[(JR=new WeakMap,YR=new WeakMap,XR=new WeakMap,ZR=new WeakMap,QR=new WeakMap,$R=new WeakMap,ez=new WeakMap,tz=new WeakMap,nz=new WeakMap,rz=new WeakMap,iz=new WeakMap,az=new WeakMap,KR=new WeakSet,Symbol.asyncIterator)](){let e=[],t=[],n=!1;return this.on(`event`,n=>{let r=t.shift();r?r.resolve(n):e.push(n)}),this.on(`end`,()=>{n=!0;for(let e of t)e.resolve(void 0);t.length=0}),this.on(`abort`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),this.on(`error`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((e,n)=>t.push({resolve:e,reject:n})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){let t=new qR;return t._run(()=>t._fromReadableStream(e)),t}async _fromReadableStream(e,t){let n=t?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener(`abort`,()=>this.controller.abort())),this._connected();let r=yI.fromReadableStream(e,this.controller);for await(let e of r)W(this,KR,`m`,oz).call(this,e);if(r.controller.signal?.aborted)throw new qP;return this._addRun(W(this,KR,`m`,sz).call(this))}toReadableStream(){return new yI(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,n,r){let i=new qR;return i._run(()=>i._runToolAssistantStream(e,t,n,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`stream`}})),i}async _createToolAssistantStream(e,t,n,r){let i=r?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener(`abort`,()=>this.controller.abort()));let a={...n,stream:!0},o=await e.submitToolOutputs(t,a,{...r,signal:this.controller.signal});this._connected();for await(let e of o)W(this,KR,`m`,oz).call(this,e);if(o.controller.signal?.aborted)throw new qP;return this._addRun(W(this,KR,`m`,sz).call(this))}static createThreadAssistantStream(e,t,n){let r=new qR;return r._run(()=>r._threadAssistantStream(e,t,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":`stream`}})),r}static createAssistantStream(e,t,n,r){let i=new qR;return i._run(()=>i._runAssistantStream(e,t,n,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`stream`}})),i}currentEvent(){return W(this,rz,`f`)}currentRun(){return W(this,iz,`f`)}currentMessageSnapshot(){return W(this,ZR,`f`)}currentRunStepSnapshot(){return W(this,az,`f`)}async finalRunSteps(){return await this.done(),Object.values(W(this,YR,`f`))}async finalMessages(){return await this.done(),Object.values(W(this,XR,`f`))}async finalRun(){if(await this.done(),!W(this,QR,`f`))throw Error(`Final run was not received.`);return W(this,QR,`f`)}async _createThreadAssistantStream(e,t,n){let r=n?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener(`abort`,()=>this.controller.abort()));let i={...t,stream:!0},a=await e.createAndRun(i,{...n,signal:this.controller.signal});this._connected();for await(let e of a)W(this,KR,`m`,oz).call(this,e);if(a.controller.signal?.aborted)throw new qP;return this._addRun(W(this,KR,`m`,sz).call(this))}async _createAssistantStream(e,t,n,r){let i=r?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener(`abort`,()=>this.controller.abort()));let a={...n,stream:!0},o=await e.create(t,a,{...r,signal:this.controller.signal});this._connected();for await(let e of o)W(this,KR,`m`,oz).call(this,e);if(o.controller.signal?.aborted)throw new qP;return this._addRun(W(this,KR,`m`,sz).call(this))}static accumulateDelta(e,t){for(let[n,r]of Object.entries(t)){if(!e.hasOwnProperty(n)){e[n]=r;continue}let t=e[n];if(t==null){e[n]=r;continue}if(n===`index`||n===`type`){e[n]=r;continue}if(typeof t==`string`&&typeof r==`string`)t+=r;else if(typeof t==`number`&&typeof r==`number`)t+=r;else if(gF(t)&&gF(r))t=this.accumulateDelta(t,r);else if(Array.isArray(t)&&Array.isArray(r)){if(t.every(e=>typeof e==`string`||typeof e==`number`)){t.push(...r);continue}for(let e of r){if(!gF(e))throw Error(`Expected array delta entry to be an object but got: ${e}`);let n=e.index;if(n==null)throw console.error(e),Error("Expected array delta entry to have an `index` property");if(typeof n!=`number`)throw Error(`Expected array delta entry \`index\` property to be a number but got ${n}`);let r=t[n];r==null?t.push(e):t[n]=this.accumulateDelta(r,e)}continue}else throw Error(`Unhandled record type: ${n}, deltaValue: ${r}, accValue: ${t}`);e[n]=t}return e}_addRun(e){return e}async _threadAssistantStream(e,t,n){return await this._createThreadAssistantStream(t,e,n)}async _runAssistantStream(e,t,n,r){return await this._createAssistantStream(t,e,n,r)}async _runToolAssistantStream(e,t,n,r){return await this._createToolAssistantStream(t,e,n,r)}};qR=hz,oz=function(e){if(!this.ended)switch(U(this,rz,e,`f`),W(this,KR,`m`,uz).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`:W(this,KR,`m`,mz).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`:W(this,KR,`m`,lz).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`:W(this,KR,`m`,cz).call(this,e);break;case`error`:throw Error(`Encountered an error event in event processing - errors should be processed earlier`);default:}},sz=function(){if(this.ended)throw new G(`stream has ended, this shouldn't happen`);if(!W(this,QR,`f`))throw Error(`Final run has not been received`);return W(this,QR,`f`)},cz=function(e){let[t,n]=W(this,KR,`m`,fz).call(this,e,W(this,ZR,`f`));U(this,ZR,t,`f`),W(this,XR,`f`)[t.id]=t;for(let e of n){let n=t.content[e.index];n?.type==`text`&&this._emit(`textCreated`,n.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,t),e.data.delta.content)for(let n of e.data.delta.content){if(n.type==`text`&&n.text){let e=n.text,r=t.content[n.index];if(r&&r.type==`text`)this._emit(`textDelta`,e,r.text);else throw Error(`The snapshot associated with this text delta is not text or missing`)}if(n.index!=W(this,$R,`f`)){if(W(this,ez,`f`))switch(W(this,ez,`f`).type){case`text`:this._emit(`textDone`,W(this,ez,`f`).text,W(this,ZR,`f`));break;case`image_file`:this._emit(`imageFileDone`,W(this,ez,`f`).image_file,W(this,ZR,`f`));break}U(this,$R,n.index,`f`)}U(this,ez,t.content[n.index],`f`)}break;case`thread.message.completed`:case`thread.message.incomplete`:if(W(this,$R,`f`)!==void 0){let t=e.data.content[W(this,$R,`f`)];if(t)switch(t.type){case`image_file`:this._emit(`imageFileDone`,t.image_file,W(this,ZR,`f`));break;case`text`:this._emit(`textDone`,t.text,W(this,ZR,`f`));break}}W(this,ZR,`f`)&&this._emit(`messageDone`,e.data),U(this,ZR,void 0,`f`)}},lz=function(e){let t=W(this,KR,`m`,dz).call(this,e);switch(U(this,az,t,`f`),e.event){case`thread.run.step.created`:this._emit(`runStepCreated`,e.data);break;case`thread.run.step.delta`:let n=e.data.delta;if(n.step_details&&n.step_details.type==`tool_calls`&&n.step_details.tool_calls&&t.step_details.type==`tool_calls`)for(let e of n.step_details.tool_calls)e.index==W(this,tz,`f`)?this._emit(`toolCallDelta`,e,t.step_details.tool_calls[e.index]):(W(this,nz,`f`)&&this._emit(`toolCallDone`,W(this,nz,`f`)),U(this,tz,e.index,`f`),U(this,nz,t.step_details.tool_calls[e.index],`f`),W(this,nz,`f`)&&this._emit(`toolCallCreated`,W(this,nz,`f`)));this._emit(`runStepDelta`,e.data.delta,t);break;case`thread.run.step.completed`:case`thread.run.step.failed`:case`thread.run.step.cancelled`:case`thread.run.step.expired`:U(this,az,void 0,`f`),e.data.step_details.type==`tool_calls`&&W(this,nz,`f`)&&(this._emit(`toolCallDone`,W(this,nz,`f`)),U(this,nz,void 0,`f`)),this._emit(`runStepDone`,e.data,t);break;case`thread.run.step.in_progress`:break}},uz=function(e){W(this,JR,`f`).push(e),this._emit(`event`,e)},dz=function(e){switch(e.event){case`thread.run.step.created`:return W(this,YR,`f`)[e.data.id]=e.data,e.data;case`thread.run.step.delta`:let t=W(this,YR,`f`)[e.data.id];if(!t)throw Error(`Received a RunStepDelta before creation of a snapshot`);let n=e.data;if(n.delta){let r=qR.accumulateDelta(t,n.delta);W(this,YR,`f`)[e.data.id]=r}return W(this,YR,`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`:W(this,YR,`f`)[e.data.id]=e.data;break}if(W(this,YR,`f`)[e.data.id])return W(this,YR,`f`)[e.data.id];throw Error(`No snapshot available`)},fz=function(e,t){let n=[];switch(e.event){case`thread.message.created`:return[e.data,n];case`thread.message.delta`:if(!t)throw Error(`Received a delta with no existing snapshot (there should be one from message creation)`);let r=e.data;if(r.delta.content)for(let e of r.delta.content)if(e.index in t.content){let n=t.content[e.index];t.content[e.index]=W(this,KR,`m`,pz).call(this,e,n)}else t.content[e.index]=e,n.push(e);return[t,n];case`thread.message.in_progress`:case`thread.message.completed`:case`thread.message.incomplete`:if(t)return[t,n];throw Error(`Received thread message event with no existing snapshot`)}throw Error(`Tried to accumulate a non-message event`)},pz=function(e,t){return qR.accumulateDelta(t,e)},mz=function(e){switch(U(this,iz,e.data,`f`),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`:U(this,QR,e.data,`f`),W(this,nz,`f`)&&(this._emit(`toolCallDone`,W(this,nz,`f`)),U(this,nz,void 0,`f`));break;case`thread.run.cancelling`:break}};var gz=class extends K{constructor(){super(...arguments),this.steps=new UR(this._client)}create(e,t,n){let{include:r,...i}=t;return this._client.post(q`/threads/${e}/runs`,{query:{include:r},body:i,...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),stream:t.stream??!1,__synthesizeEventData:!0})}retrieve(e,t,n){let{thread_id:r}=t;return this._client.get(q`/threads/${r}/runs/${e}`,{...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}update(e,t,n){let{thread_id:r,...i}=t;return this._client.post(q`/threads/${r}/runs/${e}`,{body:i,...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}list(e,t={},n){return this._client.getAPIList(q`/threads/${e}/runs`,MI,{query:t,...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}cancel(e,t,n){let{thread_id:r}=t;return this._client.post(q`/threads/${r}/runs/${e}/cancel`,{...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}async createAndPoll(e,t,n){let r=await this.create(e,t,n);return await this.poll(r.id,{thread_id:e},n)}createAndStream(e,t,n){return hz.createAssistantStream(e,this._client.beta.threads.runs,t,n)}async poll(e,t,n){let r=J([n?.headers,{"X-Stainless-Poll-Helper":`true`,"X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:i,response:a}=await this.retrieve(e,t,{...n,headers:{...n?.headers,...r}}).withResponse();switch(i.status){case`queued`:case`in_progress`:case`cancelling`:let e=5e3;if(n?.pollIntervalMs)e=n.pollIntervalMs;else{let t=a.headers.get(`openai-poll-after-ms`);if(t){let n=parseInt(t);isNaN(n)||(e=n)}}await yF(e);break;case`requires_action`:case`incomplete`:case`cancelled`:case`completed`:case`failed`:case`expired`:return i}}}stream(e,t,n){return hz.createAssistantStream(e,this._client.beta.threads.runs,t,n)}submitToolOutputs(e,t,n){let{thread_id:r,...i}=t;return this._client.post(q`/threads/${r}/runs/${e}/submit_tool_outputs`,{body:i,...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),stream:t.stream??!1,__synthesizeEventData:!0})}async submitToolOutputsAndPoll(e,t,n){let r=await this.submitToolOutputs(e,t,n);return await this.poll(r.id,t,n)}submitToolOutputsStream(e,t,n){return hz.createToolAssistantStream(e,this._client.beta.threads.runs,t,n)}};gz.Steps=UR;var _z=class extends K{constructor(){super(...arguments),this.runs=new gz(this._client),this.messages=new HR(this._client)}create(e={},t){return this._client.post(`/threads`,{body:e,...t,headers:J([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}retrieve(e,t){return this._client.get(q`/threads/${e}`,{...t,headers:J([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}update(e,t,n){return this._client.post(q`/threads/${e}`,{body:t,...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}delete(e,t){return this._client.delete(q`/threads/${e}`,{...t,headers:J([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}createAndRun(e,t){return this._client.post(`/threads/runs`,{body:e,...t,headers:J([{"OpenAI-Beta":`assistants=v2`},t?.headers]),stream:e.stream??!1,__synthesizeEventData:!0})}async createAndRunPoll(e,t){let n=await this.createAndRun(e,t);return await this.runs.poll(n.id,{thread_id:n.thread_id},t)}createAndRunStream(e,t){return hz.createThreadAssistantStream(e,this._client.beta.threads,t)}};_z.Runs=gz,_z.Messages=HR;var vz=class extends K{constructor(){super(...arguments),this.realtime=new RR(this._client),this.chatkit=new VR(this._client),this.assistants=new FR(this._client),this.threads=new _z(this._client)}};vz.Realtime=RR,vz.ChatKit=VR,vz.Assistants=FR,vz.Threads=_z;var yz=class extends K{create(e,t){return this._client.post(`/completions`,{body:e,...t,stream:e.stream??!1})}},bz=class extends K{retrieve(e,t,n){let{container_id:r}=t;return this._client.get(q`/containers/${r}/files/${e}/content`,{...n,headers:J([{Accept:`application/binary`},n?.headers]),__binaryResponse:!0})}},xz=class extends K{constructor(){super(...arguments),this.content=new bz(this._client)}create(e,t,n){return this._client.post(q`/containers/${e}/files`,VI({body:t,...n},this._client))}retrieve(e,t,n){let{container_id:r}=t;return this._client.get(q`/containers/${r}/files/${e}`,n)}list(e,t={},n){return this._client.getAPIList(q`/containers/${e}/files`,MI,{query:t,...n})}delete(e,t,n){let{container_id:r}=t;return this._client.delete(q`/containers/${r}/files/${e}`,{...n,headers:J([{Accept:`*/*`},n?.headers])})}};xz.Content=bz;var Sz=class extends K{constructor(){super(...arguments),this.files=new xz(this._client)}create(e,t){return this._client.post(`/containers`,{body:e,...t})}retrieve(e,t){return this._client.get(q`/containers/${e}`,t)}list(e={},t){return this._client.getAPIList(`/containers`,MI,{query:e,...t})}delete(e,t){return this._client.delete(q`/containers/${e}`,{...t,headers:J([{Accept:`*/*`},t?.headers])})}};Sz.Files=xz;var Cz=class extends K{create(e,t,n){let{include:r,...i}=t;return this._client.post(q`/conversations/${e}/items`,{query:{include:r},body:i,...n})}retrieve(e,t,n){let{conversation_id:r,...i}=t;return this._client.get(q`/conversations/${r}/items/${e}`,{query:i,...n})}list(e,t={},n){return this._client.getAPIList(q`/conversations/${e}/items`,NI,{query:t,...n})}delete(e,t,n){let{conversation_id:r}=t;return this._client.delete(q`/conversations/${r}/items/${e}`,n)}},wz=class extends K{constructor(){super(...arguments),this.items=new Cz(this._client)}create(e={},t){return this._client.post(`/conversations`,{body:e,...t})}retrieve(e,t){return this._client.get(q`/conversations/${e}`,t)}update(e,t,n){return this._client.post(q`/conversations/${e}`,{body:t,...n})}delete(e,t){return this._client.delete(q`/conversations/${e}`,t)}};wz.Items=Cz;var Tz=class extends K{create(e,t){let n=!!e.encoding_format,r=n?e.encoding_format:`base64`;n&&gI(this._client).debug(`embeddings/user defined encoding_format:`,e.encoding_format);let i=this._client.post(`/embeddings`,{body:{...e,encoding_format:r},...t});return n?i:(gI(this._client).debug(`embeddings/decoding base64 embeddings from base64`),i._thenUnwrap(e=>(e&&e.data&&e.data.forEach(e=>{let t=e.embedding;e.embedding=WR(t)}),e)))}},Ez=class extends K{retrieve(e,t,n){let{eval_id:r,run_id:i}=t;return this._client.get(q`/evals/${r}/runs/${i}/output_items/${e}`,n)}list(e,t,n){let{eval_id:r,...i}=t;return this._client.getAPIList(q`/evals/${r}/runs/${e}/output_items`,MI,{query:i,...n})}},Dz=class extends K{constructor(){super(...arguments),this.outputItems=new Ez(this._client)}create(e,t,n){return this._client.post(q`/evals/${e}/runs`,{body:t,...n})}retrieve(e,t,n){let{eval_id:r}=t;return this._client.get(q`/evals/${r}/runs/${e}`,n)}list(e,t={},n){return this._client.getAPIList(q`/evals/${e}/runs`,MI,{query:t,...n})}delete(e,t,n){let{eval_id:r}=t;return this._client.delete(q`/evals/${r}/runs/${e}`,n)}cancel(e,t,n){let{eval_id:r}=t;return this._client.post(q`/evals/${r}/runs/${e}`,n)}};Dz.OutputItems=Ez;var Oz=class extends K{constructor(){super(...arguments),this.runs=new Dz(this._client)}create(e,t){return this._client.post(`/evals`,{body:e,...t})}retrieve(e,t){return this._client.get(q`/evals/${e}`,t)}update(e,t,n){return this._client.post(q`/evals/${e}`,{body:t,...n})}list(e={},t){return this._client.getAPIList(`/evals`,MI,{query:e,...t})}delete(e,t){return this._client.delete(q`/evals/${e}`,t)}};Oz.Runs=Dz;var kz=class extends K{create(e,t){return this._client.post(`/files`,HI({body:e,...t},this._client))}retrieve(e,t){return this._client.get(q`/files/${e}`,t)}list(e={},t){return this._client.getAPIList(`/files`,MI,{query:e,...t})}delete(e,t){return this._client.delete(q`/files/${e}`,t)}content(e,t){return this._client.get(q`/files/${e}/content`,{...t,headers:J([{Accept:`application/binary`},t?.headers]),__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:t=5e3,maxWait:n=1800*1e3}={}){let r=new Set([`processed`,`error`,`deleted`]),i=Date.now(),a=await this.retrieve(e);for(;!a.status||!r.has(a.status);)if(await yF(t),a=await this.retrieve(e),Date.now()-i>n)throw new YP({message:`Giving up on waiting for file ${e} to finish processing after ${n} milliseconds.`});return a}},Az=class extends K{},jz=class extends K{run(e,t){return this._client.post(`/fine_tuning/alpha/graders/run`,{body:e,...t})}validate(e,t){return this._client.post(`/fine_tuning/alpha/graders/validate`,{body:e,...t})}},Mz=class extends K{constructor(){super(...arguments),this.graders=new jz(this._client)}};Mz.Graders=jz;var Nz=class extends K{create(e,t,n){return this._client.getAPIList(q`/fine_tuning/checkpoints/${e}/permissions`,jI,{body:t,method:`post`,...n})}retrieve(e,t={},n){return this._client.get(q`/fine_tuning/checkpoints/${e}/permissions`,{query:t,...n})}list(e,t={},n){return this._client.getAPIList(q`/fine_tuning/checkpoints/${e}/permissions`,NI,{query:t,...n})}delete(e,t,n){let{fine_tuned_model_checkpoint:r}=t;return this._client.delete(q`/fine_tuning/checkpoints/${r}/permissions/${e}`,n)}},Pz=class extends K{constructor(){super(...arguments),this.permissions=new Nz(this._client)}};Pz.Permissions=Nz;var Fz=class extends K{list(e,t={},n){return this._client.getAPIList(q`/fine_tuning/jobs/${e}/checkpoints`,MI,{query:t,...n})}},Iz=class extends K{constructor(){super(...arguments),this.checkpoints=new Fz(this._client)}create(e,t){return this._client.post(`/fine_tuning/jobs`,{body:e,...t})}retrieve(e,t){return this._client.get(q`/fine_tuning/jobs/${e}`,t)}list(e={},t){return this._client.getAPIList(`/fine_tuning/jobs`,MI,{query:e,...t})}cancel(e,t){return this._client.post(q`/fine_tuning/jobs/${e}/cancel`,t)}listEvents(e,t={},n){return this._client.getAPIList(q`/fine_tuning/jobs/${e}/events`,MI,{query:t,...n})}pause(e,t){return this._client.post(q`/fine_tuning/jobs/${e}/pause`,t)}resume(e,t){return this._client.post(q`/fine_tuning/jobs/${e}/resume`,t)}};Iz.Checkpoints=Fz;var Lz=class extends K{constructor(){super(...arguments),this.methods=new Az(this._client),this.jobs=new Iz(this._client),this.checkpoints=new Pz(this._client),this.alpha=new Mz(this._client)}};Lz.Methods=Az,Lz.Jobs=Iz,Lz.Checkpoints=Pz,Lz.Alpha=Mz;var Rz=class extends K{},zz=class extends K{constructor(){super(...arguments),this.graderModels=new Rz(this._client)}};zz.GraderModels=Rz;var Bz=class extends K{createVariation(e,t){return this._client.post(`/images/variations`,HI({body:e,...t},this._client))}edit(e,t){return this._client.post(`/images/edits`,HI({body:e,...t,stream:e.stream??!1},this._client))}generate(e,t){return this._client.post(`/images/generations`,{body:e,...t,stream:e.stream??!1})}},Vz=class extends K{retrieve(e,t){return this._client.get(q`/models/${e}`,t)}list(e){return this._client.getAPIList(`/models`,jI,e)}delete(e,t){return this._client.delete(q`/models/${e}`,t)}},Hz=class extends K{create(e,t){return this._client.post(`/moderations`,{body:e,...t})}},Uz=class extends K{accept(e,t,n){return this._client.post(q`/realtime/calls/${e}/accept`,{body:t,...n,headers:J([{Accept:`*/*`},n?.headers])})}hangup(e,t){return this._client.post(q`/realtime/calls/${e}/hangup`,{...t,headers:J([{Accept:`*/*`},t?.headers])})}refer(e,t,n){return this._client.post(q`/realtime/calls/${e}/refer`,{body:t,...n,headers:J([{Accept:`*/*`},n?.headers])})}reject(e,t={},n){return this._client.post(q`/realtime/calls/${e}/reject`,{body:t,...n,headers:J([{Accept:`*/*`},n?.headers])})}},Wz=class extends K{create(e,t){return this._client.post(`/realtime/client_secrets`,{body:e,...t})}},Gz=class extends K{constructor(){super(...arguments),this.clientSecrets=new Wz(this._client),this.calls=new Uz(this._client)}};Gz.ClientSecrets=Wz,Gz.Calls=Uz;function Kz(e,t){return!t||!Yz(t)?{...e,output_parsed:null,output:e.output.map(e=>e.type===`function_call`?{...e,parsed_arguments:null}:e.type===`message`?{...e,content:e.content.map(e=>({...e,parsed:null}))}:e)}:qz(e,t)}function qz(e,t){let n=e.output.map(e=>{if(e.type===`function_call`)return{...e,parsed_arguments:Qz(t,e)};if(e.type===`message`){let n=e.content.map(e=>e.type===`output_text`?{...e,parsed:Jz(t,e.text)}:e);return{...e,content:n}}return e}),r=Object.assign({},e,{output:n});return Object.getOwnPropertyDescriptor(e,`output_text`)||$z(r),Object.defineProperty(r,`output_parsed`,{enumerable:!0,get(){for(let e of r.output)if(e.type===`message`){for(let t of e.content)if(t.type===`output_text`&&t.parsed!==null)return t.parsed}return null}}),r}function Jz(e,t){return e.text?.format?.type===`json_schema`?`$parseRaw`in e.text?.format?(e.text?.format).$parseRaw(t):JSON.parse(t):null}function Yz(e){return!!sL(e.text?.format)}function Xz(e){return e?.$brand===`auto-parseable-tool`}function Zz(e,t){return e.find(e=>e.type===`function`&&e.name===t)}function Qz(e,t){let n=Zz(e.tools??[],t.name);return{...t,...t,parsed_arguments:Xz(n)?n.$parseRaw(t.arguments):n?.strict?JSON.parse(t.arguments):null}}function $z(e){let t=[];for(let n of e.output)if(n.type===`message`)for(let e of n.content)e.type===`output_text`&&t.push(e.text);e.output_text=t.join(``)}var eB,tB,nB,rB,iB,aB,oB,sB,cB=class e extends ML{constructor(e){super(),eB.add(this),tB.set(this,void 0),nB.set(this,void 0),rB.set(this,void 0),U(this,tB,e,`f`)}static createResponse(t,n,r){let i=new e(n);return i._run(()=>i._createOrRetrieveResponse(t,n,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`stream`}})),i}async _createOrRetrieveResponse(e,t,n){let r=n?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener(`abort`,()=>this.controller.abort())),W(this,eB,`m`,iB).call(this);let i,a=null;`response_id`in t?(i=await e.responses.retrieve(t.response_id,{stream:!0},{...n,signal:this.controller.signal,stream:!0}),a=t.starting_after??null):i=await e.responses.create({...t,stream:!0},{...n,signal:this.controller.signal}),this._connected();for await(let e of i)W(this,eB,`m`,aB).call(this,e,a);if(i.controller.signal?.aborted)throw new qP;return W(this,eB,`m`,oB).call(this)}[(tB=new WeakMap,nB=new WeakMap,rB=new WeakMap,eB=new WeakSet,iB=function(){this.ended||U(this,nB,void 0,`f`)},aB=function(e,t){if(this.ended)return;let n=(e,n)=>{(t==null||n.sequence_number>t)&&this._emit(e,n)},r=W(this,eB,`m`,sB).call(this,e);switch(n(`event`,e),e.type){case`response.output_text.delta`:{let t=r.output[e.output_index];if(!t)throw new G(`missing output at index ${e.output_index}`);if(t.type===`message`){let r=t.content[e.content_index];if(!r)throw new G(`missing content at index ${e.content_index}`);if(r.type!==`output_text`)throw new G(`expected content to be 'output_text', got ${r.type}`);n(`response.output_text.delta`,{...e,snapshot:r.text})}break}case`response.function_call_arguments.delta`:{let t=r.output[e.output_index];if(!t)throw new G(`missing output at index ${e.output_index}`);t.type===`function_call`&&n(`response.function_call_arguments.delta`,{...e,snapshot:t.arguments});break}default:n(e.type,e);break}},oB=function(){if(this.ended)throw new G(`stream has ended, this shouldn't happen`);let e=W(this,nB,`f`);if(!e)throw new G(`request ended without sending any events`);U(this,nB,void 0,`f`);let t=lB(e,W(this,tB,`f`));return U(this,rB,t,`f`),t},sB=function(e){let t=W(this,nB,`f`);if(!t){if(e.type!==`response.created`)throw new G(`When snapshot hasn't been set yet, expected 'response.created' event, got ${e.type}`);return t=U(this,nB,e.response,`f`),t}switch(e.type){case`response.output_item.added`:t.output.push(e.item);break;case`response.content_part.added`:{let n=t.output[e.output_index];if(!n)throw new G(`missing output at index ${e.output_index}`);let r=n.type,i=e.part;r===`message`&&i.type!==`reasoning_text`?n.content.push(i):r===`reasoning`&&i.type===`reasoning_text`&&(n.content||=[],n.content.push(i));break}case`response.output_text.delta`:{let n=t.output[e.output_index];if(!n)throw new G(`missing output at index ${e.output_index}`);if(n.type===`message`){let t=n.content[e.content_index];if(!t)throw new G(`missing content at index ${e.content_index}`);if(t.type!==`output_text`)throw new G(`expected content to be 'output_text', got ${t.type}`);t.text+=e.delta}break}case`response.function_call_arguments.delta`:{let n=t.output[e.output_index];if(!n)throw new G(`missing output at index ${e.output_index}`);n.type===`function_call`&&(n.arguments+=e.delta);break}case`response.reasoning_text.delta`:{let n=t.output[e.output_index];if(!n)throw new G(`missing output at index ${e.output_index}`);if(n.type===`reasoning`){let t=n.content?.[e.content_index];if(!t)throw new G(`missing content at index ${e.content_index}`);if(t.type!==`reasoning_text`)throw new G(`expected content to be 'reasoning_text', got ${t.type}`);t.text+=e.delta}break}case`response.completed`:U(this,nB,e.response,`f`);break}return t},Symbol.asyncIterator)](){let e=[],t=[],n=!1;return this.on(`event`,n=>{let r=t.shift();r?r.resolve(n):e.push(n)}),this.on(`end`,()=>{n=!0;for(let e of t)e.resolve(void 0);t.length=0}),this.on(`abort`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),this.on(`error`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((e,n)=>t.push({resolve:e,reject:n})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();let e=W(this,rB,`f`);if(!e)throw new G(`stream ended without producing a ChatCompletion`);return e}};function lB(e,t){return Kz(e,t)}var uB=class extends K{list(e,t={},n){return this._client.getAPIList(q`/responses/${e}/input_items`,MI,{query:t,...n})}},dB=class extends K{count(e={},t){return this._client.post(`/responses/input_tokens`,{body:e,...t})}},fB=class extends K{constructor(){super(...arguments),this.inputItems=new uB(this._client),this.inputTokens=new dB(this._client)}create(e,t){return this._client.post(`/responses`,{body:e,...t,stream:e.stream??!1})._thenUnwrap(e=>(`object`in e&&e.object===`response`&&$z(e),e))}retrieve(e,t={},n){return this._client.get(q`/responses/${e}`,{query:t,...n,stream:t?.stream??!1})._thenUnwrap(e=>(`object`in e&&e.object===`response`&&$z(e),e))}delete(e,t){return this._client.delete(q`/responses/${e}`,{...t,headers:J([{Accept:`*/*`},t?.headers])})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap(t=>qz(t,e))}stream(e,t){return cB.createResponse(this._client,e,t)}cancel(e,t){return this._client.post(q`/responses/${e}/cancel`,t)}compact(e,t){return this._client.post(`/responses/compact`,{body:e,...t})}};fB.InputItems=uB,fB.InputTokens=dB;var pB=class extends K{retrieve(e,t){return this._client.get(q`/skills/${e}/content`,{...t,headers:J([{Accept:`application/binary`},t?.headers]),__binaryResponse:!0})}},mB=class extends K{retrieve(e,t,n){let{skill_id:r}=t;return this._client.get(q`/skills/${r}/versions/${e}/content`,{...n,headers:J([{Accept:`application/binary`},n?.headers]),__binaryResponse:!0})}},hB=class extends K{constructor(){super(...arguments),this.content=new mB(this._client)}create(e,t={},n){return this._client.post(q`/skills/${e}/versions`,VI({body:t,...n},this._client))}retrieve(e,t,n){let{skill_id:r}=t;return this._client.get(q`/skills/${r}/versions/${e}`,n)}list(e,t={},n){return this._client.getAPIList(q`/skills/${e}/versions`,MI,{query:t,...n})}delete(e,t,n){let{skill_id:r}=t;return this._client.delete(q`/skills/${r}/versions/${e}`,n)}};hB.Content=mB;var gB=class extends K{constructor(){super(...arguments),this.content=new pB(this._client),this.versions=new hB(this._client)}create(e={},t){return this._client.post(`/skills`,VI({body:e,...t},this._client))}retrieve(e,t){return this._client.get(q`/skills/${e}`,t)}update(e,t,n){return this._client.post(q`/skills/${e}`,{body:t,...n})}list(e={},t){return this._client.getAPIList(`/skills`,MI,{query:e,...t})}delete(e,t){return this._client.delete(q`/skills/${e}`,t)}};gB.Content=pB,gB.Versions=hB;var _B=class extends K{create(e,t,n){return this._client.post(q`/uploads/${e}/parts`,HI({body:t,...n},this._client))}},vB=class extends K{constructor(){super(...arguments),this.parts=new _B(this._client)}create(e,t){return this._client.post(`/uploads`,{body:e,...t})}cancel(e,t){return this._client.post(q`/uploads/${e}/cancel`,t)}complete(e,t,n){return this._client.post(q`/uploads/${e}/complete`,{body:t,...n})}};vB.Parts=_B;var yB=async e=>{let t=await Promise.allSettled(e),n=t.filter(e=>e.status===`rejected`);if(n.length){for(let e of n)console.error(e.reason);throw Error(`${n.length} promise(s) failed - see the above errors`)}let r=[];for(let e of t)e.status===`fulfilled`&&r.push(e.value);return r},bB=class extends K{create(e,t,n){return this._client.post(q`/vector_stores/${e}/file_batches`,{body:t,...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}retrieve(e,t,n){let{vector_store_id:r}=t;return this._client.get(q`/vector_stores/${r}/file_batches/${e}`,{...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}cancel(e,t,n){let{vector_store_id:r}=t;return this._client.post(q`/vector_stores/${r}/file_batches/${e}/cancel`,{...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}async createAndPoll(e,t,n){let r=await this.create(e,t);return await this.poll(e,r.id,n)}listFiles(e,t,n){let{vector_store_id:r,...i}=t;return this._client.getAPIList(q`/vector_stores/${r}/file_batches/${e}/files`,MI,{query:i,...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}async poll(e,t,n){let r=J([n?.headers,{"X-Stainless-Poll-Helper":`true`,"X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:i,response:a}=await this.retrieve(t,{vector_store_id:e},{...n,headers:r}).withResponse();switch(i.status){case`in_progress`:let e=5e3;if(n?.pollIntervalMs)e=n.pollIntervalMs;else{let t=a.headers.get(`openai-poll-after-ms`);if(t){let n=parseInt(t);isNaN(n)||(e=n)}}await yF(e);break;case`failed`:case`cancelled`:case`completed`:return i}}}async uploadAndPoll(e,{files:t,fileIds:n=[]},r){if(t==null||t.length==0)throw Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");let i=r?.maxConcurrency??5,a=Math.min(i,t.length),o=this._client,s=t.values(),c=[...n];async function l(e){for(let t of e){let e=await o.files.create({file:t,purpose:`assistants`},r);c.push(e.id)}}return await yB(Array(a).fill(s).map(l)),await this.createAndPoll(e,{file_ids:c})}},xB=class extends K{create(e,t,n){return this._client.post(q`/vector_stores/${e}/files`,{body:t,...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}retrieve(e,t,n){let{vector_store_id:r}=t;return this._client.get(q`/vector_stores/${r}/files/${e}`,{...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}update(e,t,n){let{vector_store_id:r,...i}=t;return this._client.post(q`/vector_stores/${r}/files/${e}`,{body:i,...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}list(e,t={},n){return this._client.getAPIList(q`/vector_stores/${e}/files`,MI,{query:t,...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}delete(e,t,n){let{vector_store_id:r}=t;return this._client.delete(q`/vector_stores/${r}/files/${e}`,{...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}async createAndPoll(e,t,n){let r=await this.create(e,t,n);return await this.poll(e,r.id,n)}async poll(e,t,n){let r=J([n?.headers,{"X-Stainless-Poll-Helper":`true`,"X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let i=await this.retrieve(t,{vector_store_id:e},{...n,headers:r}).withResponse(),a=i.data;switch(a.status){case`in_progress`:let e=5e3;if(n?.pollIntervalMs)e=n.pollIntervalMs;else{let t=i.response.headers.get(`openai-poll-after-ms`);if(t){let n=parseInt(t);isNaN(n)||(e=n)}}await yF(e);break;case`failed`:case`completed`:return a}}}async upload(e,t,n){let r=await this._client.files.create({file:t,purpose:`assistants`},n);return this.create(e,{file_id:r.id},n)}async uploadAndPoll(e,t,n){let r=await this.upload(e,t,n);return await this.poll(e,r.id,n)}content(e,t,n){let{vector_store_id:r}=t;return this._client.getAPIList(q`/vector_stores/${r}/files/${e}/content`,jI,{...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}},SB=class extends K{constructor(){super(...arguments),this.files=new xB(this._client),this.fileBatches=new bB(this._client)}create(e,t){return this._client.post(`/vector_stores`,{body:e,...t,headers:J([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}retrieve(e,t){return this._client.get(q`/vector_stores/${e}`,{...t,headers:J([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}update(e,t,n){return this._client.post(q`/vector_stores/${e}`,{body:t,...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}list(e={},t){return this._client.getAPIList(`/vector_stores`,MI,{query:e,...t,headers:J([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}delete(e,t){return this._client.delete(q`/vector_stores/${e}`,{...t,headers:J([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}search(e,t,n){return this._client.getAPIList(q`/vector_stores/${e}/search`,jI,{body:t,method:`post`,...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}};SB.Files=xB,SB.FileBatches=bB;var CB=class extends K{create(e,t){return this._client.post(`/videos`,HI({body:e,...t},this._client))}retrieve(e,t){return this._client.get(q`/videos/${e}`,t)}list(e={},t){return this._client.getAPIList(`/videos`,NI,{query:e,...t})}delete(e,t){return this._client.delete(q`/videos/${e}`,t)}createCharacter(e,t){return this._client.post(`/videos/characters`,HI({body:e,...t},this._client))}downloadContent(e,t={},n){return this._client.get(q`/videos/${e}/content`,{query:t,...n,headers:J([{Accept:`application/binary`},n?.headers]),__binaryResponse:!0})}edit(e,t){return this._client.post(`/videos/edits`,HI({body:e,...t},this._client))}extend(e,t){return this._client.post(`/videos/extensions`,HI({body:e,...t},this._client))}getCharacter(e,t){return this._client.get(q`/videos/characters/${e}`,t)}remix(e,t,n){return this._client.post(q`/videos/${e}/remix`,VI({body:t,...n},this._client))}},wB,TB,EB,DB=class extends K{constructor(){super(...arguments),wB.add(this)}async unwrap(e,t,n=this._client.webhookSecret,r=300){return await this.verifySignature(e,t,n,r),JSON.parse(e)}async verifySignature(e,t,n=this._client.webhookSecret,r=300){if(typeof crypto>`u`||typeof crypto.subtle.importKey!=`function`||typeof crypto.subtle.verify!=`function`)throw Error("Webhook signature verification is only supported when the `crypto` global is defined");W(this,wB,`m`,TB).call(this,n);let i=J([t]).values,a=W(this,wB,`m`,EB).call(this,i,`webhook-signature`),o=W(this,wB,`m`,EB).call(this,i,`webhook-timestamp`),s=W(this,wB,`m`,EB).call(this,i,`webhook-id`),c=parseInt(o,10);if(isNaN(c))throw new oF(`Invalid webhook timestamp format`);let l=Math.floor(Date.now()/1e3);if(l-c>r)throw new oF(`Webhook timestamp is too old`);if(c>l+r)throw new oF(`Webhook timestamp is too new`);let u=a.split(` `).map(e=>e.startsWith(`v1,`)?e.substring(3):e),d=n.startsWith(`whsec_`)?Buffer.from(n.replace(`whsec_`,``),`base64`):Buffer.from(n,`utf-8`),f=s?`${s}.${o}.${e}`:`${o}.${e}`,p=await crypto.subtle.importKey(`raw`,d,{name:`HMAC`,hash:`SHA-256`},!1,[`verify`]);for(let e of u)try{let t=Buffer.from(e,`base64`);if(await crypto.subtle.verify(`HMAC`,p,t,new TextEncoder().encode(f)))return}catch{continue}throw new oF(`The given webhook signature does not match the expected signature`)}};wB=new WeakSet,TB=function(e){if(typeof e!=`string`||e.length===0)throw 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`)},EB=function(e,t){if(!e)throw Error(`Headers are required`);let n=e.get(t);if(n==null)throw Error(`Missing required header: ${t}`);return n};var OB,kB,AB,jB,MB=`workload-identity-auth`,NB=class{constructor({baseURL:e=GR(`OPENAI_BASE_URL`),apiKey:t=GR(`OPENAI_API_KEY`),organization:n=GR(`OPENAI_ORG_ID`)??null,project:r=GR(`OPENAI_PROJECT_ID`)??null,webhookSecret:i=GR(`OPENAI_WEBHOOK_SECRET`)??null,workloadIdentity:a,...o}={}){if(OB.add(this),AB.set(this,void 0),this.completions=new yz(this),this.chat=new DR(this),this.embeddings=new Tz(this),this.files=new kz(this),this.images=new Bz(this),this.audio=new NR(this),this.moderations=new Hz(this),this.models=new Vz(this),this.fineTuning=new Lz(this),this.graders=new zz(this),this.vectorStores=new SB(this),this.webhooks=new DB(this),this.beta=new vz(this),this.batches=new PR(this),this.uploads=new vB(this),this.responses=new fB(this),this.realtime=new Gz(this),this.conversations=new wz(this),this.evals=new Oz(this),this.containers=new Sz(this),this.skills=new gB(this),this.videos=new CB(this),a){if(t&&t!==MB)throw new G("The `apiKey` and `workloadIdentity` arguments are mutually exclusive; only one can be passed at a time.");t=MB}else if(t===void 0)throw new G("Missing credentials. Please pass an `apiKey`, `workloadIdentity`, or set the `OPENAI_API_KEY` environment variable.");let s={apiKey:t,organization:n,project:r,webhookSecret:i,workloadIdentity:a,...o,baseURL:e||`https://api.openai.com/v1`};if(!s.dangerouslyAllowBrowser&&xF())throw new G(`It looks like you're running in a browser-like environment.
159
-
160
- This is disabled by default, as it risks exposing your secret API credentials to attackers.
161
- If you understand the risks and have appropriate mitigations in place,
162
- you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
163
-
164
- new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
165
-
166
- https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
167
- `);this.baseURL=s.baseURL,this.timeout=s.timeout??kB.DEFAULT_TIMEOUT,this.logger=s.logger??console;let c=`warn`;this.logLevel=c,this.logLevel=dI(s.logLevel,`ClientOptions.logLevel`,this)??dI(GR(`OPENAI_LOG`),`process.env['OPENAI_LOG']`,this)??c,this.fetchOptions=s.fetchOptions,this.maxRetries=s.maxRetries??2,this.fetch=s.fetch??kF(),U(this,AB,PF,`f`),this._options=s,a&&(this._workloadIdentityAuth=new II(a,this.fetch)),this.apiKey=typeof t==`string`?t:`Missing Key`,this.organization=n,this.project=r,this.webhookSecret=i}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:t}){}async authHeaders(e){return J([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(e){return $F(e)}getUserAgent(){return`${this.constructor.name}/JS ${bF}`}defaultIdempotencyKey(){return`stainless-node-retry-${UP()}`}makeStatusError(e,t,n,r){return KP.generate(e,t,n,r)}async _callApiKey(){let e=this._options.apiKey;if(typeof e!=`function`)return!1;let t;try{t=await e()}catch(e){throw e instanceof G?e:new G(`Failed to get token from 'apiKey' function: ${e.message}`,{cause:e})}if(typeof t!=`string`||!t)throw new G(`Expected 'apiKey' function argument to return a string but it returned ${t}`);return this.apiKey=t,!0}buildURL(e,t,n){let r=!W(this,OB,`m`,jB).call(this)&&n||this.baseURL,i=uF(e)?new URL(e):new URL(r+(r.endsWith(`/`)&&e.startsWith(`/`)?e.slice(1):e)),a=this.defaultQuery(),o=Object.fromEntries(i.searchParams);return(!mF(a)||!mF(o))&&(t={...o,...a,...t}),typeof t==`object`&&t&&!Array.isArray(t)&&(i.search=this.stringifyQuery(t)),i.toString()}async prepareOptions(e){await this._callApiKey()}async prepareRequest(e,{url:t,options:n}){}get(e,t){return this.methodRequest(`get`,e,t)}post(e,t){return this.methodRequest(`post`,e,t)}patch(e,t){return this.methodRequest(`patch`,e,t)}put(e,t){return this.methodRequest(`put`,e,t)}delete(e,t){return this.methodRequest(`delete`,e,t)}methodRequest(e,t,n){return this.request(Promise.resolve(n).then(n=>({method:e,path:t,...n})))}request(e,t=null){return new DI(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,n){let r=await e,i=r.maxRetries??this.maxRetries;t??=i,await this.prepareOptions(r);let{req:a,url:o,timeout:s}=await this.buildRequest(r,{retryCount:i-t});await this.prepareRequest(a,{url:o,options:r});let c=`log_`+(Math.random()*(1<<24)|0).toString(16).padStart(6,`0`),l=n===void 0?``:`, retryOf: ${n}`,u=Date.now();if(gI(this).debug(`[${c}] sending request`,_I({retryOfRequestLogID:n,method:r.method,url:o,options:r,headers:a.headers})),r.signal?.aborted)throw new qP;let d=new AbortController,f=await this.fetchWithAuth(o,a,s,d).catch(GP),p=Date.now();if(f instanceof globalThis.Error){let e=`retrying, ${t} attempts remaining`;if(r.signal?.aborted)throw new qP;let i=WP(f)||/timed? ?out/i.test(String(f)+(`cause`in f?String(f.cause):``));if(t)return gI(this).info(`[${c}] connection ${i?`timed out`:`failed`} - ${e}`),gI(this).debug(`[${c}] connection ${i?`timed out`:`failed`} (${e})`,_I({retryOfRequestLogID:n,url:o,durationMs:p-u,message:f.message})),this.retryRequest(r,t,n??c);throw gI(this).info(`[${c}] connection ${i?`timed out`:`failed`} - error; no more retries left`),gI(this).debug(`[${c}] connection ${i?`timed out`:`failed`} (error; no more retries left)`,_I({retryOfRequestLogID:n,url:o,durationMs:p-u,message:f.message})),f instanceof sF||f instanceof cF?f:i?new YP:new JP({cause:f})}let m=`[${c}${l}${[...f.headers.entries()].filter(([e])=>e===`x-request-id`).map(([e,t])=>`, `+e+`: `+JSON.stringify(t)).join(``)}] ${a.method} ${o} ${f.ok?`succeeded`:`failed`} with status ${f.status} in ${p-u}ms`;if(!f.ok){if(f.status===401&&this._workloadIdentityAuth&&!r.__metadata?.hasStreamingBody&&!r.__metadata?.workloadIdentityTokenRefreshed)return await NF(f.body),this._workloadIdentityAuth.invalidateToken(),this.makeRequest({...r,__metadata:{...r.__metadata,workloadIdentityTokenRefreshed:!0}},t,n??c);let e=await this.shouldRetry(f);if(t&&e){let e=`retrying, ${t} attempts remaining`;return await NF(f.body),gI(this).info(`${m} - ${e}`),gI(this).debug(`[${c}] response error (${e})`,_I({retryOfRequestLogID:n,url:f.url,status:f.status,headers:f.headers,durationMs:p-u})),this.retryRequest(r,t,n??c,f.headers)}let i=e?`error; no more retries left`:`error; not retryable`;gI(this).info(`${m} - ${i}`);let a=await f.text().catch(e=>GP(e).message),o=vF(a),s=o?void 0:a;throw gI(this).debug(`[${c}] response error (${i})`,_I({retryOfRequestLogID:n,url:f.url,status:f.status,headers:f.headers,message:s,durationMs:Date.now()-u})),this.makeStatusError(f.status,o,s,f.headers)}return gI(this).info(m),gI(this).debug(`[${c}] response start`,_I({retryOfRequestLogID:n,url:f.url,status:f.status,headers:f.headers,durationMs:p-u})),{response:f,options:r,controller:d,requestLogID:c,retryOfRequestLogID:n,startTime:u}}getAPIList(e,t,n){return this.requestAPIList(t,n&&`then`in n?n.then(t=>({method:`get`,path:e,...t})):{method:`get`,path:e,...n})}requestAPIList(e,t){let n=this.makeRequest(t,null,void 0);return new AI(this,n,e)}async fetchWithAuth(e,t,n,r){if(this._workloadIdentityAuth){let e=t.headers,n=e.get(`Authorization`);if(!n||n===`Bearer ${MB}`){let t=await this._workloadIdentityAuth.getToken();e.set(`Authorization`,`Bearer ${t}`)}}return await this.fetchWithTimeout(e,t,n,r)}async fetchWithTimeout(e,t,n,r){let{signal:i,method:a,...o}=t||{},s=this._makeAbort(r);i&&i.addEventListener(`abort`,s,{once:!0});let c=setTimeout(s,n),l=globalThis.ReadableStream&&o.body instanceof globalThis.ReadableStream||typeof o.body==`object`&&o.body!==null&&Symbol.asyncIterator in o.body,u={signal:r.signal,...l?{duplex:`half`}:{},method:`GET`,...o};a&&(u.method=a.toUpperCase());try{return await this.fetch.call(void 0,e,u)}finally{clearTimeout(c)}}async shouldRetry(e){let t=e.headers.get(`x-should-retry`);return t===`true`?!0:t===`false`?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,t,n,r){let i,a=r?.get(`retry-after-ms`);if(a){let e=parseFloat(a);Number.isNaN(e)||(i=e)}let o=r?.get(`retry-after`);if(o&&!i){let e=parseFloat(o);i=Number.isNaN(e)?Date.parse(o)-Date.now():e*1e3}if(i===void 0){let n=e.maxRetries??this.maxRetries;i=this.calculateDefaultRetryTimeoutMillis(t,n)}return await yF(i),this.makeRequest(e,t-1,n)}calculateDefaultRetryTimeoutMillis(e,t){let n=t-e;return Math.min(.5*2**n,8)*(1-Math.random()*.25)*1e3}async buildRequest(e,{retryCount:t=0}={}){let n={...e},{method:r,path:i,query:a,defaultBaseURL:o}=n,s=this.buildURL(i,a,o);`timeout`in n&&_F(`timeout`,n.timeout),n.timeout=n.timeout??this.timeout;let{bodyHeaders:c,body:l,isStreamingBody:u}=this.buildBody({options:n});return u&&(e.__metadata={...e.__metadata,hasStreamingBody:!0}),{req:{method:r,headers:await this.buildHeaders({options:e,method:r,bodyHeaders:c,retryCount:t}),...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&l instanceof globalThis.ReadableStream&&{duplex:`half`},...l&&{body:l},...this.fetchOptions??{},...n.fetchOptions??{}},url:s,timeout:n.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:n,retryCount:r}){let i={};this.idempotencyHeader&&t!==`get`&&(e.idempotencyKey||=this.defaultIdempotencyKey(),i[this.idempotencyHeader]=e.idempotencyKey);let a=J([i,{Accept:`application/json`,"User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(r),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...OF(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders(e),this._options.defaultHeaders,n,e.headers]);return this.validateHeaders(a),a.values}_makeAbort(e){return()=>e.abort()}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0,isStreamingBody:!1};let n=J([t]),r=globalThis.ReadableStream!==void 0&&e instanceof globalThis.ReadableStream,i=!r&&(typeof e==`string`||e instanceof ArrayBuffer||ArrayBuffer.isView(e)||globalThis.Blob!==void 0&&e instanceof globalThis.Blob||e instanceof URLSearchParams||e instanceof FormData);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e==`string`&&n.values.has(`content-type`)||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||r?{bodyHeaders:void 0,body:e,isStreamingBody:!i}:typeof e==`object`&&(Symbol.asyncIterator in e||Symbol.iterator in e&&`next`in e&&typeof e.next==`function`)?{bodyHeaders:void 0,body:jF(e),isStreamingBody:!0}:typeof e==`object`&&n.values.get(`content-type`)===`application/x-www-form-urlencoded`?{bodyHeaders:{"content-type":`application/x-www-form-urlencoded`},body:this.stringifyQuery(e),isStreamingBody:!1}:{...W(this,AB,`f`).call(this,{body:e,headers:n}),isStreamingBody:!1}}};kB=NB,AB=new WeakMap,OB=new WeakSet,jB=function(){return this.baseURL!==`https://api.openai.com/v1`},NB.OpenAI=kB,NB.DEFAULT_TIMEOUT=6e5,NB.OpenAIError=G,NB.APIError=KP,NB.APIConnectionError=JP,NB.APIConnectionTimeoutError=YP,NB.APIUserAbortError=qP,NB.NotFoundError=$P,NB.ConflictError=eF,NB.RateLimitError=nF,NB.BadRequestError=XP,NB.AuthenticationError=ZP,NB.InternalServerError=rF,NB.PermissionDeniedError=QP,NB.UnprocessableEntityError=tF,NB.InvalidWebhookSignatureError=oF,NB.toFile=$I,NB.Completions=yz,NB.Chat=DR,NB.Embeddings=Tz,NB.Files=kz,NB.Images=Bz,NB.Audio=NR,NB.Moderations=Hz,NB.Models=Vz,NB.FineTuning=Lz,NB.Graders=zz,NB.VectorStores=SB,NB.Webhooks=DB,NB.Beta=vz,NB.Batches=PR,NB.Uploads=vB,NB.Responses=fB,NB.Realtime=Gz,NB.Conversations=wz,NB.Evals=Oz,NB.Containers=Sz,NB.Skills=gB,NB.Videos=CB;var PB=class extends NB{constructor({baseURL:e=GR(`OPENAI_BASE_URL`),apiKey:t=GR(`AZURE_OPENAI_API_KEY`),apiVersion:n=GR(`OPENAI_API_VERSION`),endpoint:r,deployment:i,azureADTokenProvider:a,dangerouslyAllowBrowser:o,...s}={}){if(!n)throw new G(`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 a==`function`&&(o=!0),!a&&!t)throw new G("Missing credentials. Please pass one of `apiKey` and `azureADTokenProvider`, or set the `AZURE_OPENAI_API_KEY` environment variable.");if(a&&t)throw new G("The `apiKey` and `azureADTokenProvider` arguments are mutually exclusive; only one can be passed at a time.");if(s.defaultQuery={...s.defaultQuery,"api-version":n},!e){if(r||={}.AZURE_OPENAI_ENDPOINT,!r)throw new G("Must provide one of the `baseURL` or `endpoint` arguments, or the `AZURE_OPENAI_ENDPOINT` environment variable");e=`${r}/openai`}else if(r)throw new G(`baseURL and endpoint are mutually exclusive`);super({apiKey:a??t,baseURL:e,...s,...o===void 0?{}:{dangerouslyAllowBrowser:o}}),this.apiVersion=``,this.apiVersion=n,this.deploymentName=i}async buildRequest(e,t={}){if(FB.has(e.path)&&e.method===`post`&&e.body!==void 0){if(!gF(e.body))throw Error(`Expected request body to be an object`);let t=this.deploymentName||e.body.model||e.__metadata?.model;t!==void 0&&!this.baseURL.includes(`/deployments`)&&(e.path=`/deployments/${t}${e.path}`)}return super.buildRequest(e,t)}async authHeaders(e){return typeof this._options.apiKey==`string`?J([{"api-key":this.apiKey}]):super.authHeaders(e)}},FB=new Set([`/completions`,`/chat/completions`,`/embeddings`,`/audio/transcriptions`,`/audio/translations`,`/audio/speech`,`/images/generations`,`/batches`,`/images/edits`]);function IB(e){return!!(String(e).includes(`context_length_exceeded`)||`message`in e&&typeof e.message==`string`&&(e.message.includes(`Input tokens exceed the configured limit`)||e.message.includes(`exceeds the context window`)||e.message.includes(`maximum context length`)))}function LB(e){if(!e||typeof e!=`object`)return e;let t;return e.constructor.name===YP.name&&`message`in e&&typeof e.message==`string`?(t=Error(e.message),t.name=`TimeoutError`):e.constructor.name===qP.name&&`message`in e&&typeof e.message==`string`?(t=Error(e.message),t.name=`AbortError`):t=IB(e)?m.fromError(e):`status`in e&&e.status===400&&`message`in e&&typeof e.message==`string`&&e.message.includes(`tool_calls`)?HP(e,`INVALID_TOOL_RESULTS`):`status`in e&&e.status===401?HP(e,`MODEL_AUTHENTICATION`):`status`in e&&e.status===429?HP(e,`MODEL_RATE_LIMIT`):`status`in e&&e.status===404?HP(e,`MODEL_NOT_FOUND`):e,t}var RB=e=>e();function zB(e){return e?!!(/^o\d/.test(e??``)||e.startsWith(`gpt-5`)&&!e.startsWith(`gpt-5-chat`)):!1}function BB(e){return e.role!==`system`&&e.role!==`developer`&&e.role!==`assistant`&&e.role!==`user`&&e.role!==`function`&&e.role!==`tool`&&console.warn(`Unknown message role: ${e.role}`),e.role}function VB(e){return e.metadata?.filename??e.metadata?.name??e.metadata?.title}var HB=`LC_AUTOGENERATED`;function UB(e){return(e.metadata?.filename??e.metadata?.name??e.metadata?.title)||(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'.`),HB)}function WB(e){let t=e._getType();switch(t){case`system`:return`system`;case`ai`:return`assistant`;case`human`:return`user`;case`function`:return`function`;case`tool`:return`tool`;case`generic`:if(!Zt.isInstance(e))throw Error(`Invalid generic chat message`);return BB(e);default:throw Error(`Unknown message type: ${t}`)}}function GB(e){return!!(e.includes(`gpt-5.2-pro`)||e.includes(`gpt-5.4-pro`)||e.includes(`gpt-5.5-pro`)||e.includes(`codex`))}function KB(e){let{azureOpenAIApiDeploymentName:t,azureOpenAIApiInstanceName:n,azureOpenAIApiKey:r,azureOpenAIBasePath:i,baseURL:a,azureADTokenProvider:o,azureOpenAIEndpoint:s}=e;if((r||o)&&i&&t)return`${i}/${t}`;if((r||o)&&s&&t)return`${s}/openai/deployments/${t}`;if(r||o){if(!n)throw Error(`azureOpenAIApiInstanceName is required when using azureOpenAIApiKey`);if(!t)throw Error(`azureOpenAIApiDeploymentName is a required parameter when using azureOpenAIApiKey`);return`https://${n}.openai.azure.com/openai/deployments/${t}`}return a}function qB(e){return typeof Headers<`u`&&typeof e==`object`&&!!e&&Object.prototype.toString.call(e)===`[object Headers]`}function JB(e){let t=RB(()=>{if(qB(e))return e;if(Array.isArray(e))return new Headers(e);if(typeof e==`object`&&e&&`values`in e&&qB(e.values))return e.values;if(typeof e==`object`&&e){let t=Object.entries(e).filter(([,e])=>typeof e==`string`).map(([e,t])=>[e,t]);return new Headers(t)}return new Headers});return Object.fromEntries(t.entries())}function YB(){let e=ur();return(e===`node`||e===`deno`)&&(e=`(${e}/${process.version}; ${process.platform}; ${process.arch})`),e}function XB(e,t=!1,n=`1.0.0`){let r=JB(e),i=YB(),a=`langchainjs${t?`-azure`:``}-openai`;return{...r,"User-Agent":r[`User-Agent`]?`${a}/${n} (${i})${r[`User-Agent`]}`:`${a}/${n} (${i})`}}function ZB(e,t){let n;return n=GE(e)?ik(e):e,t?.strict!==void 0&&(n.function.strict=t.strict),n}function QB(e){return e.anyOf!==void 0&&Array.isArray(e.anyOf)}function $B(e){let t=[`namespace functions {`,``];for(let n of e)n.description&&t.push(`// ${n.description}`),Object.keys(n.parameters.properties??{}).length>0?(t.push(`type ${n.name} = (_: {`),t.push(eV(n.parameters,0)),t.push(`}) => any;`)):t.push(`type ${n.name} = () => any;`),t.push(``);return t.push(`} // namespace functions`),t.join(`
168
- `)}function eV(e,t){let n=[];for(let[r,i]of Object.entries(e.properties??{}))i.description&&t<2&&n.push(`// ${i.description}`),e.required?.includes(r)?n.push(`${r}: ${tV(i,t)},`):n.push(`${r}?: ${tV(i,t)},`);return n.map(e=>` `.repeat(t)+e).join(`
169
- `)}function tV(e,t){if(QB(e))return e.anyOf.map(e=>tV(e,t)).join(` | `);switch(e.type){case`string`:return e.enum?e.enum.map(e=>`"${e}"`).join(` | `):`string`;case`number`:return e.enum?e.enum.map(e=>`${e}`).join(` | `):`number`;case`integer`:return e.enum?e.enum.map(e=>`${e}`).join(` | `):`number`;case`boolean`:return`boolean`;case`null`:return`null`;case`object`:return[`{`,eV(e,t+2),`}`].join(`
170
- `);case`array`:return e.items?`${tV(e.items,t)}[]`:`any[]`;default:return``}}function nV(e){if(e)return e===`any`||e===`required`?`required`:e===`auto`?`auto`:e===`none`?`none`:typeof e==`string`?{type:`function`,function:{name:e}}:e}function rV(e){return`type`in e&&e.type!==`function`}function iV(e){return typeof e==`object`&&!!e&&`extras`in e&&typeof e.extras==`object`&&e.extras!==null&&`providerToolDefinition`in e.extras&&typeof e.extras.providerToolDefinition==`object`&&e.extras.providerToolDefinition!==null}function aV(e){return typeof e==`object`&&!!e&&`type`in e&&e.type!==`function`}function oV(e){return typeof e==`object`&&!!e&&`metadata`in e&&typeof e.metadata==`object`&&e.metadata!==null&&`customTool`in e.metadata&&typeof e.metadata.customTool==`object`&&e.metadata.customTool!==null}function sV(e){return`type`in e&&e.type===`custom`&&`custom`in e&&typeof e.custom==`object`&&e.custom!==null}function cV(e){if(e.type===`custom_tool_call`)return{...e,type:`tool_call`,call_id:e.id,id:e.call_id,name:e.name,isCustomTool:!0,args:{input:e.input}}}function lV(e){if(e.type===`computer_call`)return{...e,type:`tool_call`,call_id:e.id,id:e.call_id,name:`computer_use`,isComputerTool:!0,args:{action:e.action}}}function uV(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`tool_call`&&`isComputerTool`in e&&e.isComputerTool===!0}function dV(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`tool_call`&&`isCustomTool`in e&&e.isCustomTool===!0}function fV(e){return{type:`custom`,name:e.custom.name,description:e.custom.description,format:(()=>{if(e.custom.format){if(e.custom.format.type===`grammar`)return{type:`grammar`,definition:e.custom.format.grammar.definition,syntax:e.custom.format.grammar.syntax};if(e.custom.format.type===`text`)return{type:`text`}}})()}}function pV(e){return{type:`custom`,custom:{name:e.name,description:e.description,format:(()=>{if(e.format){if(e.format.type===`grammar`)return{type:`grammar`,grammar:{definition:e.format.definition,syntax:e.format.syntax}};if(e.format.type===`text`)return{type:`text`}}})()}}}var mV=Symbol(`Let zodToJsonSchema decide on which parser to use`),hV={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`},gV=e=>typeof e==`string`?{...hV,basePath:[`#`],definitions:{},name:e}:{...hV,basePath:[`#`],definitions:{},...e},_V=e=>`_def`in e?e._def:e;function vV(e){if(!e)return!0;for(let t in e)return!1;return!0}var yV=e=>{let t=gV(e),n=t.name===void 0?t.basePath:[...t.basePath,t.definitionPath,t.name];return{...t,currentPath:n,propertyPath:void 0,seenRefs:new Set,seen:new Map(Object.entries(t.definitions).map(([e,n])=>[_V(n),{def:_V(n),path:[...t.basePath,t.definitionPath,e],jsonSchema:void 0}]))}};function bV(e,t,n,r){r?.errorMessages&&n&&(e.errorMessage={...e.errorMessage,[t]:n})}function xV(e,t,n,r,i){e[t]=n,bV(e,t,r,i)}function SV(){return{}}function CV(e,t){let n={type:`array`};return e.type?._def?.typeName!==z.ZodAny&&(n.items=lH(e.type._def,{...t,currentPath:[...t.currentPath,`items`]})),e.minLength&&xV(n,`minItems`,e.minLength.value,e.minLength.message,t),e.maxLength&&xV(n,`maxItems`,e.maxLength.value,e.maxLength.message,t),e.exactLength&&(xV(n,`minItems`,e.exactLength.value,e.exactLength.message,t),xV(n,`maxItems`,e.exactLength.value,e.exactLength.message,t)),n}function wV(e,t){let n={type:`integer`,format:`int64`};if(!e.checks)return n;for(let r of e.checks)switch(r.kind){case`min`:t.target===`jsonSchema7`?r.inclusive?xV(n,`minimum`,r.value,r.message,t):xV(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),xV(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?xV(n,`maximum`,r.value,r.message,t):xV(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),xV(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:xV(n,`multipleOf`,r.value,r.message,t);break}return n}function TV(){return{type:`boolean`}}function EV(e,t){return lH(e.type._def,t)}var DV=(e,t)=>lH(e.innerType._def,t);function OV(e,t,n){let r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((n,r)=>OV(e,t,n))};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 kV(e,t)}}var kV=(e,t)=>{let n={type:`integer`,format:`unix-time`};if(t.target===`openApi3`)return n;for(let r of e.checks)switch(r.kind){case`min`:xV(n,`minimum`,r.value,r.message,t);break;case`max`:xV(n,`maximum`,r.value,r.message,t);break}return n};function AV(e,t){return{...lH(e.innerType._def,t),default:e.defaultValue()}}function jV(e,t,n){return t.effectStrategy===`input`?lH(e.schema._def,t,n):{}}function MV(e){return{type:`string`,enum:[...e.values]}}var NV=e=>`type`in e&&e.type===`string`?!1:`allOf`in e;function PV(e,t){let n=[lH(e.left._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]}),lH(e.right._def,{...t,currentPath:[...t.currentPath,`allOf`,`1`]})].filter(e=>!!e),r=t.target===`jsonSchema2019-09`?{unevaluatedProperties:!1}:void 0,i=[];return n.forEach(e=>{if(NV(e))i.push(...e.allOf),e.unevaluatedProperties===void 0&&(r=void 0);else{let t=e;if(`additionalProperties`in e&&e.additionalProperties===!1){let{additionalProperties:n,...r}=e;t=r}else r=void 0;i.push(t)}}),i.length?{allOf:i,...r}:void 0}function FV(e,t){let n=typeof e.value;return n!==`bigint`&&n!==`number`&&n!==`boolean`&&n!==`string`?{type:Array.isArray(e.value)?`array`:`object`}:t.target===`openApi3`?{type:n===`bigint`?`integer`:n,enum:[e.value]}:{type:n===`bigint`?`integer`:n,const:e.value}}var IV,LV={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:()=>(IV===void 0&&(IV=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)),IV),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])$/,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})))$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/};function RV(e,t){let n={type:`string`};function r(e){return t.patternStrategy===`escape`?zV(e):e}if(e.checks)for(let i of e.checks)switch(i.kind){case`min`:xV(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,i.value):i.value,i.message,t);break;case`max`:xV(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,i.value):i.value,i.message,t);break;case`email`:switch(t.emailStrategy){case`format:email`:BV(n,`email`,i.message,t);break;case`format:idn-email`:BV(n,`idn-email`,i.message,t);break;case`pattern:zod`:VV(n,LV.email,i.message,t);break}break;case`url`:BV(n,`uri`,i.message,t);break;case`uuid`:BV(n,`uuid`,i.message,t);break;case`regex`:VV(n,i.regex,i.message,t);break;case`cuid`:VV(n,LV.cuid,i.message,t);break;case`cuid2`:VV(n,LV.cuid2,i.message,t);break;case`startsWith`:VV(n,RegExp(`^${r(i.value)}`),i.message,t);break;case`endsWith`:VV(n,RegExp(`${r(i.value)}$`),i.message,t);break;case`datetime`:BV(n,`date-time`,i.message,t);break;case`date`:BV(n,`date`,i.message,t);break;case`time`:BV(n,`time`,i.message,t);break;case`duration`:BV(n,`duration`,i.message,t);break;case`length`:xV(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,i.value):i.value,i.message,t),xV(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,i.value):i.value,i.message,t);break;case`includes`:VV(n,RegExp(r(i.value)),i.message,t);break;case`ip`:i.version!==`v6`&&BV(n,`ipv4`,i.message,t),i.version!==`v4`&&BV(n,`ipv6`,i.message,t);break;case`emoji`:VV(n,LV.emoji,i.message,t);break;case`ulid`:VV(n,LV.ulid,i.message,t);break;case`base64`:switch(t.base64Strategy){case`format:binary`:BV(n,`binary`,i.message,t);break;case`contentEncoding:base64`:xV(n,`contentEncoding`,`base64`,i.message,t);break;case`pattern:zod`:VV(n,LV.base64,i.message,t);break}break;case`nanoid`:VV(n,LV.nanoid,i.message,t);case`toLowerCase`:case`toUpperCase`:case`trim`:break;default:(e=>{})(i)}return n}var zV=e=>Array.from(e).map(e=>/[a-zA-Z0-9]/.test(e)?e:`\\${e}`).join(``),BV=(e,t,n,r)=>{e.format||e.anyOf?.some(e=>e.format)?(e.anyOf||=[],e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&r.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.anyOf.push({format:t,...n&&r.errorMessages&&{errorMessage:{format:n}}})):xV(e,`format`,t,n,r)},VV=(e,t,n,r)=>{e.pattern||e.allOf?.some(e=>e.pattern)?(e.allOf||=[],e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&r.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.allOf.push({pattern:HV(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):xV(e,`pattern`,HV(t,r),n,r)},HV=(e,t)=>{let n=typeof e==`function`?e():e;if(!t.applyRegexFlags||!n.flags)return n.source;let r={i:n.flags.includes(`i`),m:n.flags.includes(`m`),s:n.flags.includes(`s`)},i=r.i?n.source.toLowerCase():n.source,a=``,o=!1,s=!1,c=!1;for(let e=0;e<i.length;e++){if(o){a+=i[e],o=!1;continue}if(r.i){if(s){if(i[e].match(/[a-z]/)){c?(a+=i[e],a+=`${i[e-2]}-${i[e]}`.toUpperCase(),c=!1):i[e+1]===`-`&&i[e+2]?.match(/[a-z]/)?(a+=i[e],c=!0):a+=`${i[e]}${i[e].toUpperCase()}`;continue}}else if(i[e].match(/[a-z]/)){a+=`[${i[e]}${i[e].toUpperCase()}]`;continue}}if(r.m){if(i[e]===`^`){a+=`(^|(?<=[\r
171
- ]))`;continue}else if(i[e]===`$`){a+=`($|(?=[\r
172
- ]))`;continue}}if(r.s&&i[e]===`.`){a+=s?`${i[e]}\r\n`:`[${i[e]}\r\n]`;continue}a+=i[e],i[e]===`\\`?o=!0:s&&i[e]===`]`?s=!1:!s&&i[e]===`[`&&(s=!0)}try{new RegExp(a)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join(`/`)} to a flag-independent form! Falling back to the flag-ignorant source`),n.source}return a};function UV(e,t){if(t.target===`openApi3`&&e.keyType?._def.typeName===z.ZodEnum)return{type:`object`,required:e.keyType._def.values,properties:e.keyType._def.values.reduce((n,r)=>({...n,[r]:lH(e.valueType._def,{...t,currentPath:[...t.currentPath,`properties`,r]})??{}}),{}),additionalProperties:!1};let n={type:`object`,additionalProperties:lH(e.valueType._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]})??{}};if(t.target===`openApi3`)return n;if(e.keyType?._def.typeName===z.ZodString&&e.keyType._def.checks?.length){let r=Object.entries(RV(e.keyType._def,t)).reduce((e,[t,n])=>t===`type`?e:{...e,[t]:n},{});return{...n,propertyNames:r}}else if(e.keyType?._def.typeName===z.ZodEnum)return{...n,propertyNames:{enum:e.keyType._def.values}};return n}function WV(e,t){return t.mapStrategy===`record`?UV(e,t):{type:`array`,maxItems:125,items:{type:`array`,items:[lH(e.keyType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`0`]})||{},lH(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`1`]})||{}],minItems:2,maxItems:2}}}function GV(e){let t=e.values,n=Object.keys(e.values).filter(e=>typeof t[t[e]]!=`number`).map(e=>t[e]),r=Array.from(new Set(n.map(e=>typeof e)));return{type:r.length===1?r[0]===`string`?`string`:`number`:[`string`,`number`],enum:n}}function KV(){return{not:{}}}function qV(e){return e.target===`openApi3`?{enum:[`null`],nullable:!0}:{type:`null`}}var JV={ZodString:`string`,ZodNumber:`number`,ZodBigInt:`integer`,ZodBoolean:`boolean`,ZodNull:`null`};function YV(e,t){if(t.target===`openApi3`)return XV(e,t);let n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(e=>e._def.typeName in JV&&(!e._def.checks||!e._def.checks.length))){let e=n.reduce((e,t)=>{let n=JV[t._def.typeName];return n&&!e.includes(n)?[...e,n]:e},[]);return{type:e.length>1?e:e[0]}}else if(n.every(e=>e._def.typeName===`ZodLiteral`&&!e.description)){let e=n.reduce((e,t)=>{let n=typeof t._def.value;switch(n){case`string`:case`number`:case`boolean`:return[...e,n];case`bigint`:return[...e,`integer`];case`object`:if(t._def.value===null)return[...e,`null`];default:return e}},[]);if(e.length===n.length){let t=e.filter((e,t,n)=>n.indexOf(e)===t);return{type:t.length>1?t:t[0],enum:n.reduce((e,t)=>e.includes(t._def.value)?e:[...e,t._def.value],[])}}}else if(n.every(e=>e._def.typeName===`ZodEnum`))return{type:`string`,enum:n.reduce((e,t)=>[...e,...t._def.values.filter(t=>!e.includes(t))],[])};return XV(e,t)}var XV=(e,t)=>{let n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((e,n)=>lH(e._def,{...t,currentPath:[...t.currentPath,`anyOf`,`${n}`]})).filter(e=>!!e&&(!t.strictUnions||typeof e==`object`&&Object.keys(e).length>0));return n.length?{anyOf:n}:void 0};function ZV(e,t){if([`ZodString`,`ZodNumber`,`ZodBigInt`,`ZodBoolean`,`ZodNull`].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return t.target===`openApi3`||t.nullableStrategy===`property`?{type:JV[e.innerType._def.typeName],nullable:!0}:{type:[JV[e.innerType._def.typeName],`null`]};if(t.target===`openApi3`){let n=lH(e.innerType._def,{...t,currentPath:[...t.currentPath]});return n&&`$ref`in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let n=lH(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`0`]});return n&&{anyOf:[n,{type:`null`}]}}function QV(e,t){let n={type:`number`};if(!e.checks)return n;for(let r of e.checks)switch(r.kind){case`int`:n.type=`integer`,bV(n,`type`,r.message,t);break;case`min`:t.target===`jsonSchema7`?r.inclusive?xV(n,`minimum`,r.value,r.message,t):xV(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),xV(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?xV(n,`maximum`,r.value,r.message,t):xV(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),xV(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:xV(n,`multipleOf`,r.value,r.message,t);break}return n}function $V(e,t){return t.removeAdditionalStrategy===`strict`?e.catchall._def.typeName===`ZodNever`?e.unknownKeys!==`strict`:lH(e.catchall._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]})??!0:e.catchall._def.typeName===`ZodNever`?e.unknownKeys===`passthrough`:lH(e.catchall._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]})??!0}function eH(e,t){let n={type:`object`,...Object.entries(e.shape()).reduce((e,[n,r])=>{if(r===void 0||r._def===void 0)return e;let i=[...t.currentPath,`properties`,n],a=lH(r._def,{...t,currentPath:i,propertyPath:i});if(a===void 0)return e;if(t.openaiStrictMode&&r.isOptional()&&!r.isNullable()&&r._def?.defaultValue===void 0)throw 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:{...e.properties,[n]:a},required:r.isOptional()&&!t.openaiStrictMode?e.required:[...e.required,n]}},{properties:{},required:[]}),additionalProperties:$V(e,t)};return n.required.length||delete n.required,n}var tH=(e,t)=>{if(t.propertyPath&&t.currentPath.slice(0,t.propertyPath.length).toString()===t.propertyPath.toString())return lH(e.innerType._def,{...t,currentPath:t.currentPath});let n=lH(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`1`]});return n?{anyOf:[{not:{}},n]}:{}},nH=(e,t)=>{if(t.pipeStrategy===`input`)return lH(e.in._def,t);if(t.pipeStrategy===`output`)return lH(e.out._def,t);let n=lH(e.in._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]});return{allOf:[n,lH(e.out._def,{...t,currentPath:[...t.currentPath,`allOf`,n?`1`:`0`]})].filter(e=>e!==void 0)}};function rH(e,t){return lH(e.type._def,t)}function iH(e,t){let n={type:`array`,uniqueItems:!0,items:lH(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`]})};return e.minSize&&xV(n,`minItems`,e.minSize.value,e.minSize.message,t),e.maxSize&&xV(n,`maxItems`,e.maxSize.value,e.maxSize.message,t),n}function aH(e,t){return e.rest?{type:`array`,minItems:e.items.length,items:e.items.map((e,n)=>lH(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[]),additionalItems:lH(e.rest._def,{...t,currentPath:[...t.currentPath,`additionalItems`]})}:{type:`array`,minItems:e.items.length,maxItems:e.items.length,items:e.items.map((e,n)=>lH(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[])}}function oH(){return{not:{}}}function sH(){return{}}var cH=(e,t)=>lH(e.innerType._def,t);function lH(e,t,n=!1){let r=t.seen.get(e);if(t.override){let i=t.override?.(e,t,r,n);if(i!==mV)return i}if(r&&!n){let e=uH(r,t);if(e!==void 0)return`$ref`in e&&t.seenRefs.add(e.$ref),e}let i={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,i);let a=fH(e,e.typeName,t,n);return a&&pH(e,t,a),i.jsonSchema=a,a}var uH=(e,t)=>{switch(t.$refStrategy){case`root`:return{$ref:e.path.join(`/`)};case`extract-to-root`:let n=e.path.slice(t.basePath.length+1).join(`_`);return n!==t.name&&t.nameStrategy===`duplicate-ref`&&(t.definitions[n]=e.def),{$ref:[...t.basePath,t.definitionPath,n].join(`/`)};case`relative`:return{$ref:dH(t.currentPath,e.path)};case`none`:case`seen`:return e.path.length<t.currentPath.length&&e.path.every((e,n)=>t.currentPath[n]===e)?(console.warn(`Recursive reference detected at ${t.currentPath.join(`/`)}! Defaulting to any`),{}):t.$refStrategy===`seen`?{}:void 0}},dH=(e,t)=>{let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];n++);return[(e.length-n).toString(),...t.slice(n)].join(`/`)},fH=(e,t,n,r)=>{switch(t){case z.ZodString:return RV(e,n);case z.ZodNumber:return QV(e,n);case z.ZodObject:return eH(e,n);case z.ZodBigInt:return wV(e,n);case z.ZodBoolean:return TV();case z.ZodDate:return OV(e,n);case z.ZodUndefined:return oH();case z.ZodNull:return qV(n);case z.ZodArray:return CV(e,n);case z.ZodUnion:case z.ZodDiscriminatedUnion:return YV(e,n);case z.ZodIntersection:return PV(e,n);case z.ZodTuple:return aH(e,n);case z.ZodRecord:return UV(e,n);case z.ZodLiteral:return FV(e,n);case z.ZodEnum:return MV(e);case z.ZodNativeEnum:return GV(e);case z.ZodNullable:return ZV(e,n);case z.ZodOptional:return tH(e,n);case z.ZodMap:return WV(e,n);case z.ZodSet:return iH(e,n);case z.ZodLazy:return lH(e.getter()._def,n);case z.ZodPromise:return rH(e,n);case z.ZodNaN:case z.ZodNever:return KV();case z.ZodEffects:return jV(e,n,r);case z.ZodAny:return SV();case z.ZodUnknown:return sH();case z.ZodDefault:return AV(e,n);case z.ZodBranded:return EV(e,n);case z.ZodReadonly:return cH(e,n);case z.ZodCatch:return DV(e,n);case z.ZodPipeline:return nH(e,n);case z.ZodFunction:case z.ZodVoid:case z.ZodSymbol:return;default:return(e=>void 0)(t)}},pH=(e,t,n)=>(e.description&&(n.description=e.description,t.markdownDescription&&(n.markdownDescription=e.description)),n),mH=(e,t)=>{let n=yV(t),r=typeof t==`string`?t:t?.nameStrategy===`title`?void 0:t?.name,i=lH(e._def,r===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,r]},!1)??{},a=typeof t==`object`&&t.name!==void 0&&t.nameStrategy===`title`?t.name:void 0;a!==void 0&&(i.title=a);let o=(()=>{if(vV(n.definitions))return;let e={},t=new Set;for(let r=0;r<500;r++){let r=Object.entries(n.definitions).filter(([e])=>!t.has(e));if(r.length===0)break;for(let[i,a]of r)e[i]=lH(_V(a),{...n,currentPath:[...n.basePath,n.definitionPath,i]},!0)??{},t.add(i)}return e})(),s=r===void 0?o?{...i,[n.definitionPath]:o}:i:n.nameStrategy===`duplicate-ref`?{...i,...o||n.seenRefs.size?{[n.definitionPath]:{...o,...n.seenRefs.size?{[r]:i}:void 0}}:void 0}:{$ref:[...n.$refStrategy===`relative`?[]:n.basePath,n.definitionPath,r].join(`/`),[n.definitionPath]:{...o,[r]:i}};return n.target===`jsonSchema7`?s.$schema=`http://json-schema.org/draft-07/schema#`:n.target===`jsonSchema2019-09`&&(s.$schema=`https://json-schema.org/draft/2019-09/schema#`),s};function hH(e){if(e.type!==`object`)throw Error(`Root schema must have type: 'object' but got type: ${e.type?`'${e.type}'`:`undefined`}`);let t=structuredClone(e);return _H(t,[],t)}function gH(e){if(typeof e==`boolean`)return!1;if(e.type===`null`)return!0;for(let t of e.oneOf??[])if(gH(t))return!0;for(let t of e.anyOf??[])if(gH(t))return!0;return!1}function _H(e,t,n){if(typeof e==`boolean`)throw TypeError(`Expected object schema but got boolean; path=${t.join(`/`)}`);if(!yH(e))throw TypeError(`Expected ${JSON.stringify(e)} to be an object; path=${t.join(`/`)}`);let r=e.$defs;if(yH(r))for(let[e,i]of Object.entries(r))_H(i,[...t,`$defs`,e],n);let i=e.definitions;if(yH(i))for(let[e,r]of Object.entries(i))_H(r,[...t,`definitions`,e],n);e.type===`object`&&!(`additionalProperties`in e)&&(e.additionalProperties=!1);let a=e.required??[],o=e.properties;if(yH(o)){for(let[e,n]of Object.entries(o))if(!gH(n)&&!a.includes(e))throw Error(`Zod field at \`${[...t,`properties`,e].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`);e.required=Object.keys(o),e.properties=Object.fromEntries(Object.entries(o).map(([e,r])=>[e,_H(r,[...t,`properties`,e],n)]))}let s=e.items;yH(s)&&(e.items=_H(s,[...t,`items`],n));let c=e.anyOf;Array.isArray(c)&&(e.anyOf=c.map((e,r)=>_H(e,[...t,`anyOf`,String(r)],n)));let l=e.allOf;if(Array.isArray(l))if(l.length===1){let r=_H(l[0],[...t,`allOf`,`0`],n);Object.assign(e,r),delete e.allOf}else e.allOf=l.map((e,r)=>_H(e,[...t,`allOf`,String(r)],n));e.default===null&&delete e.default;let u=e.$ref;if(u&&bH(e,1)){if(typeof u!=`string`)throw TypeError(`Received non-string $ref - ${u}; path=${t.join(`/`)}`);let r=vH(n,u);if(typeof r==`boolean`)throw Error(`Expected \`$ref: ${u}\` to resolve to an object schema but got boolean`);if(!yH(r))throw Error(`Expected \`$ref: ${u}\` to resolve to an object but got ${JSON.stringify(r)}`);return Object.assign(e,{...r,...e}),delete e.$ref,_H(e,t,n)}return e}function vH(e,t){if(!t.startsWith(`#/`))throw Error(`Unexpected $ref format ${JSON.stringify(t)}; Does not start with #/`);let n=t.slice(2).split(`/`),r=e;for(let e of n){if(!yH(r))throw Error(`encountered non-object entry while resolving ${t} - ${JSON.stringify(r)}`);let n=r[e];if(n===void 0)throw Error(`Key ${e} not found while resolving ${t}`);r=n}return r}function yH(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function bH(e,t){let n=0;for(let r in e)if(n++,n>t)return!0;return!1}function xH(e,t){return mH(e,{openaiStrictMode:!0,name:t.name,nameStrategy:`duplicate-ref`,$refStrategy:`extract-to-root`,nullableStrategy:`property`})}function SH(e){return hH(Dm(e,{target:`draft-7`}))}function CH(e){return`_zod`in e}function wH(e,t,n){return oL({type:`json_schema`,json_schema:{...n,name:t,strict:!0,schema:CH(e)?SH(e):xH(e,{name:t})}},t=>e.parse(JSON.parse(t)))}var TH=[`jsonSchema`,`functionCalling`,`jsonMode`];function EH(e,t){if(t!==void 0&&!TH.includes(t))throw Error(`Invalid method: ${t}. Supported methods are: ${TH.join(`, `)}`);let n=!e.startsWith(`gpt-3`)&&!e.startsWith(`gpt-4-`)&&e!==`gpt-4`;if(n&&!t)return`jsonSchema`;if(!n&&t===`jsonSchema`)throw Error(`JSON Schema is not supported for model "${e}". Please use a different method, e.g. "functionCalling" or "jsonMode".`);return t??`functionCalling`}function DH(e,t){let n={...e};return Object.defineProperties(n,{$brand:{value:`auto-parseable-response-format`,enumerable:!1},$parseRaw:{value:t,enumerable:!1}}),n}function OH(e,t,n){if(Am(e))return wH(e,t,n);if(km(e))return DH({type:`json_schema`,json_schema:{...n,name:t,strict:!0,schema:Bv(e,{cycles:`ref`,reused:`ref`,override(e){e.jsonSchema.title=t}})}},t=>od(e,JSON.parse(t)));throw Error(`Unsupported schema response format`)}function kH(e,t){if(t&&typeof t==`object`&&`images`in t&&Array.isArray(t.images)){let n=t.images.filter(e=>typeof e?.image_url?.url==`string`).map(e=>({type:`image`,url:e.image_url.url}));return[{type:`text`,text:e},...n]}return e}var AH={"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 jH(e,t){return typeof e==`string`?{model:e,...t??{}}:e??t}var MH=class extends xw{temperature;topP;frequencyPenalty;presencePenalty;n;logitBias;model=`gpt-3.5-turbo`;modelKwargs;stop;stopSequences;user;timeout;streaming=!1;streamUsage=!0;maxTokens;logprobs;topLogprobs;apiKey;organization;__includeRawResponse;client;clientConfig;supportsStrictToolCalling;audio;modalities;reasoning;zdrEnabled;service_tier;promptCacheKey;promptCacheRetention;verbosity;defaultOptions;_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`]}lc_serializable=!0;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`.split(`.`)}getLsParams(e){let t=this.invocationParams(e);return{ls_provider:`openai`,ls_model_name:this.model,ls_model_type:`chat`,ls_temperature:t.temperature??void 0,ls_max_tokens:t.max_tokens??void 0,ls_stop:e.stop}}_identifyingParams(){return{model_name:this.model,...this.invocationParams(),...this.clientConfig}}identifyingParams(){return this._identifyingParams()}constructor(e){super(e??{});let t=typeof e?.configuration?.apiKey==`string`||typeof e?.configuration?.apiKey==`function`?e?.configuration?.apiKey:void 0;this.apiKey=e?.apiKey??t??pr(`OPENAI_API_KEY`),this.organization=e?.configuration?.organization??pr(`OPENAI_ORGANIZATION`),this.model=e?.model??e?.modelName??this.model,this.modelKwargs=e?.modelKwargs??{},this.timeout=e?.timeout,this.temperature=e?.temperature??this.temperature,this.topP=e?.topP??this.topP,this.frequencyPenalty=e?.frequencyPenalty??this.frequencyPenalty,this.presencePenalty=e?.presencePenalty??this.presencePenalty,this.logprobs=e?.logprobs,this.topLogprobs=e?.topLogprobs,this.n=e?.n??this.n,this.logitBias=e?.logitBias,this.stop=e?.stopSequences??e?.stop,this.stopSequences=this.stop,this.user=e?.user,this.__includeRawResponse=e?.__includeRawResponse,this.audio=e?.audio,this.modalities=e?.modalities,this.reasoning=e?.reasoning,this.maxTokens=e?.maxCompletionTokens??e?.maxTokens,this.promptCacheKey=e?.promptCacheKey??this.promptCacheKey,this.promptCacheRetention=e?.promptCacheRetention??this.promptCacheRetention,this.verbosity=e?.verbosity??this.verbosity,this.disableStreaming=e?.disableStreaming===!0,this.streaming=e?.streaming===!0,this.disableStreaming&&(this.streaming=!1),e?.streaming===!1&&(this.disableStreaming=!0),this.streamUsage=e?.streamUsage??this.streamUsage,this.disableStreaming&&(this.streamUsage=!1),this.clientConfig={apiKey:this.apiKey,organization:this.organization,dangerouslyAllowBrowser:!0,...e?.configuration},e?.supportsStrictToolCalling!==void 0&&(this.supportsStrictToolCalling=e.supportsStrictToolCalling),e?.service_tier!==void 0&&(this.service_tier=e.service_tier),this.zdrEnabled=e?.zdrEnabled??!1,this._addVersion(`@langchain/openai`,`1.4.5`)}_getReasoningParams(e){if(!zB(this.model))return;let t;return this.reasoning!==void 0&&(t={...t,...this.reasoning}),e?.reasoning!==void 0&&(t={...t,...e.reasoning}),e?.reasoningEffort!==void 0&&t?.effort===void 0&&(t={...t,effort:e.reasoningEffort}),t}_getResponseFormat(e){return e&&e.type===`json_schema`&&e.json_schema.schema&&Mm(e.json_schema.schema)?OH(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){let e=KB({baseURL:this.clientConfig.baseURL}),t={...this.clientConfig,baseURL:e,timeout:this.timeout,maxRetries:0};t.baseURL||delete t.baseURL,t.defaultHeaders=XB(t.defaultHeaders),this.client=new NB(t)}return{...this.clientConfig,...e}}_convertChatOpenAIToolToCompletionsTool(e,t){return oV(e)?pV(e.metadata.customTool):oC(e)?t?.strict===void 0?e:{...e,function:{...e.function,strict:t.strict}}:ZB(e,t)}bindTools(e,t){let n;return t?.strict===void 0?this.supportsStrictToolCalling!==void 0&&(n=this.supportsStrictToolCalling):n=t.strict,this.withConfig({tools:e.map(e=>{if(rV(e)||oV(e))return e;if(iV(e))return e.extras.providerToolDefinition;let t=this._convertChatOpenAIToolToCompletionsTool(e,{strict:n});return GE(e)&&e.extras?.defer_loading===!0?{...t,defer_loading:!0}:t}),...t})}async stream(e,t){return super.stream(e,this._combineCallOptions(t))}async invoke(e,t){return super.invoke(e,this._combineCallOptions(t))}_combineLLMOutput(...e){return e.reduce((e,t)=>(t&&t.tokenUsage&&(e.tokenUsage.completionTokens+=t.tokenUsage.completionTokens??0,e.tokenUsage.promptTokens+=t.tokenUsage.promptTokens??0,e.tokenUsage.totalTokens+=t.tokenUsage.totalTokens??0),e),{tokenUsage:{completionTokens:0,promptTokens:0,totalTokens:0}})}async getNumTokensFromMessages(e){let t=0,n=0,r=0;this.model===`gpt-3.5-turbo-0301`?(n=4,r=-1):(n=3,r=1);let i=await Promise.all(e.map(async e=>{let[i,a]=await Promise.all([this.getNumTokens(e.content),this.getNumTokens(WB(e))]),o=e.name===void 0?0:r+await this.getNumTokens(e.name),s=i+n+a+o,c=e;if(c._getType()===`function`&&(s-=2),c.additional_kwargs?.function_call&&(s+=3),c?.additional_kwargs.function_call?.name&&(s+=await this.getNumTokens(c.additional_kwargs.function_call?.name)),c.additional_kwargs.function_call?.arguments)try{s+=await this.getNumTokens(JSON.stringify(JSON.parse(c.additional_kwargs.function_call?.arguments)))}catch(e){console.error(`Error parsing function arguments`,e,JSON.stringify(c.additional_kwargs.function_call)),s+=await this.getNumTokens(c.additional_kwargs.function_call?.arguments)}return t+=s,s}));return t+=3,{totalCount:t,countPerMessage:i}}async _getNumTokensFromGenerations(e){return(await Promise.all(e.map(async e=>e.message.additional_kwargs?.function_call?(await this.getNumTokensFromMessages([e.message])).countPerMessage[0]:await this.getNumTokens(e.message.content)))).reduce((e,t)=>e+t,0)}async _getEstimatedTokenCountFromPrompt(e,t,n){let r=(await this.getNumTokensFromMessages(e)).totalCount;if(t&&n!==`auto`){let e=$B(t);r+=await this.getNumTokens(e),r+=9}return t&&e.find(e=>e._getType()===`system`)&&(r-=4),n===`none`?r+=1:typeof n==`object`&&(r+=await this.getNumTokens(n.name)+4),r}async moderateContent(e,t){let n=this._getClientOptions(t?.options),r={input:e,model:t?.model??`omni-moderation-latest`};return this.caller.call(async()=>{try{return await this.client.moderations.create(r,n)}catch(e){throw LB(e)}})}get profile(){return AH[this.model]??{}}_getStructuredOutputMethod(e){let t={...e};if(!this.model.startsWith(`gpt-3`)&&!this.model.startsWith(`gpt-4-`)&&this.model!==`gpt-4`){if(t?.method===void 0)return`jsonSchema`}else t.method===`jsonSchema`&&console.warn(`[WARNING]: JSON Schema is not supported for model "${this.model}". Falling back to tool calling.`);return t.method}withStructuredOutput(e,t){let n,r,{schema:i,name:a,includeRaw:o}={...t,schema:e};if(t?.strict!==void 0&&t.method===`jsonMode`)throw Error("Argument `strict` is only supported for `method` = 'function_calling'");let s=EH(this.model,t?.method);if(s===`jsonMode`){r=UC(i);let e=Bv(i);n=this.withConfig({outputVersion:`v0`,response_format:{type:`json_object`},ls_structured_output_format:{kwargs:{method:`json_mode`},schema:{title:a??`extract`,...e}}})}else if(s===`jsonSchema`){let e=Bv(i),o={name:a??`extract`,description:Bm(e),schema:Mm(i)?i:e,strict:t?.strict};if(n=this.withConfig({outputVersion:`v0`,response_format:{type:`json_schema`,json_schema:o},ls_structured_output_format:{kwargs:{method:`json_schema`},schema:{title:o.name,description:o.description,...e}}}),Mm(i)||$_(i)){let e=UC(i);r=dy.from(async t=>`parsed`in t.additional_kwargs?t.additional_kwargs.parsed:e.invoke(t.content))}else r=new wC}else{let e=a??`extract`,o=Bv(i),s;Mm(i)||$_(i)?s={name:e,description:o.description,parameters:o}:typeof i.name==`string`&&typeof i.parameters==`object`&&i.parameters!=null?(s=i,e=i.name):(e=i.title??e,s={name:e,description:i.description??``,parameters:i}),n=this.withConfig({outputVersion:`v0`,tools:[{type:`function`,function:s}],tool_choice:{type:`function`,function:{name:e}},ls_structured_output_format:{kwargs:{method:`function_calling`},schema:{title:e,...o}},...t?.strict===void 0?{}:{strict:t.strict}}),r=WC(i,e)}return GC(n,r,o)}},NH={providerName:`ChatOpenAI`,fromStandardTextBlock(e){return{type:`text`,text:e.text}},fromStandardImageBlock(e){if(e.source_type===`url`)return{type:`image_url`,image_url:{url:e.url,...e.metadata?.detail?{detail:e.metadata.detail}:{}}};if(e.source_type===`base64`)return{type:`image_url`,image_url:{url:`data:${e.mime_type??``};base64,${e.data}`,...e.metadata?.detail?{detail:e.metadata.detail}:{}}};throw Error(`Image content blocks with source_type ${e.source_type} are not supported for ChatOpenAI`)},fromStandardAudioBlock(e){if(e.source_type===`url`){let t=we({dataUrl:e.url});if(!t)throw Error(`URL audio blocks with source_type ${e.source_type} must be formatted as a data URL for ChatOpenAI`);let n=t.mime_type||e.mime_type||``,r;try{r=Ce(n)}catch{throw Error(`Audio blocks with source_type ${e.source_type} must have mime type of audio/wav or audio/mp3`)}if(r.type!==`audio`||r.subtype!==`wav`&&r.subtype!==`mp3`)throw Error(`Audio blocks with source_type ${e.source_type} must have mime type of audio/wav or audio/mp3`);return{type:`input_audio`,input_audio:{format:r.subtype,data:t.data}}}if(e.source_type===`base64`){let t;try{t=Ce(e.mime_type??``)}catch{throw Error(`Audio blocks with source_type ${e.source_type} must have mime type of audio/wav or audio/mp3`)}if(t.type!==`audio`||t.subtype!==`wav`&&t.subtype!==`mp3`)throw Error(`Audio blocks with source_type ${e.source_type} must have mime type of audio/wav or audio/mp3`);return{type:`input_audio`,input_audio:{format:t.subtype,data:e.data}}}throw Error(`Audio content blocks with source_type ${e.source_type} are not supported for ChatOpenAI`)},fromStandardFileBlock(e){if(e.source_type===`url`){let t=we({dataUrl:e.url}),n=UB(e);if(!t)throw Error(`URL file blocks with source_type ${e.source_type} must be formatted as a data URL for ChatOpenAI`);return{type:`file`,file:{file_data:e.url,filename:n}}}if(e.source_type===`base64`){let t=UB(e);return{type:`file`,file:{file_data:`data:${e.mime_type??``};base64,${e.data}`,filename:t}}}if(e.source_type===`id`)return{type:`file`,file:{file_id:e.id}};throw Error(`File content blocks with source_type ${e.source_type} are not supported for ChatOpenAI`)}},PH=({message:e,rawResponse:t,includeRawResponse:n})=>{let r=e.tool_calls,i=e.reasoning_content;switch(e.role){case`assistant`:{let a=[],o=[];for(let e of r??[])try{a.push(LC(e,{returnId:!0}))}catch(t){o.push(zC(e,t.message))}let s={function_call:e.function_call,tool_calls:r};n!==void 0&&(s.__raw_response=t),i!==void 0&&(s.reasoning_content=i);let c={model_provider:`openai`,model_name:t.model,...t.system_fingerprint?{usage:{...t.usage},system_fingerprint:t.system_fingerprint}:{}};return e.audio&&(s.audio=e.audio),new qt({content:kH(e.content||``,t.choices?.[0]?.message),tool_calls:a,invalid_tool_calls:o,additional_kwargs:s,response_metadata:c,id:t.id})}default:return new Zt(e.content||``,e.role??`unknown`)}},FH=({delta:e,rawResponse:t,includeRawResponse:n,defaultRole:r})=>{let i=e.role??r,a=e.content??``,o;o=e.function_call?{function_call:e.function_call}:e.tool_calls?{tool_calls:e.tool_calls}:{},n&&(o.__raw_response=t),e.reasoning_content!==void 0&&(o.reasoning_content=e.reasoning_content),e.audio&&(o.audio={...e.audio,index:t.choices[0].index});let s={model_provider:`openai`,usage:{...t.usage}};if(i===`user`)return new sn({content:a,response_metadata:s});if(i===`assistant`){let n=[];if(Array.isArray(e.tool_calls))for(let t of e.tool_calls)n.push({name:t.function?.name,args:t.function?.arguments,id:t.id,index:t.index,type:`tool_call_chunk`});return new Xt({content:a,tool_call_chunks:n,additional_kwargs:o,id:t.id,response_metadata:s})}else if(i===`system`)return new fn({content:a,response_metadata:s});else if(i===`developer`)return new fn({content:a,response_metadata:s,additional_kwargs:{__openai_role__:`developer`}});else if(i===`function`)return new nn({content:a,additional_kwargs:o,name:e.name,response_metadata:s});else if(i===`tool`)return new vt({content:a,additional_kwargs:o,tool_call_id:e.tool_call_id,response_metadata:s});else return new Qt({content:a,role:i,response_metadata:s})},IH=e=>{if(e.type===`image`){if(e.url)return{type:`image_url`,image_url:{url:e.url}};if(e.data)return{type:`image_url`,image_url:{url:`data:${e.mimeType};base64,${e.data}`}}}if(e.type===`audio`&&e.data){let t=hn(()=>{let[,t]=e.mimeType.split(`/`);return t===`wav`||t===`mp3`?t:`wav`});return{type:`input_audio`,input_audio:{data:e.data.toString(),format:t}}}if(e.type===`file`){if(e.data){let t=UB(e);return{type:`file`,file:{file_data:`data:${e.mimeType};base64,${e.data}`,filename:t}}}if(e.fileId)return{type:`file`,file:{file_id:e.fileId}}}},LH=({message:e,model:t})=>{let n=WB(e);if(n===`system`&&zB(t)&&(n=`developer`),n===`developer`)return{role:`developer`,content:e.contentBlocks.filter(e=>e.type===`text`)};if(n===`system`)return{role:`system`,content:e.contentBlocks.filter(e=>e.type===`text`)};if(n===`assistant`)return{role:`assistant`,content:e.contentBlocks.filter(e=>e.type===`text`)};if(n===`tool`&&_t.isInstance(e))return{role:`tool`,tool_call_id:e.tool_call_id,content:e.contentBlocks.filter(e=>e.type===`text`)};if(n===`function`)return{role:`function`,name:e.name??``,content:e.contentBlocks.filter(e=>e.type===`text`).join(``)};function*r(e){for(let t of e){t.type===`text`&&(yield{type:`text`,text:t.text});let e=IH(t);e&&(yield e)}}return{role:`user`,content:Array.from(r(e.contentBlocks))}},RH=({messages:e,model:t})=>e.flatMap(e=>{if(`output_version`in e.response_metadata&&e.response_metadata?.output_version===`v1`)return LH({message:e});let n=WB(e);n===`system`&&zB(t)&&(n=`developer`);let r=typeof e.content==`string`?e.content:e.content.flatMap(e=>_e(e)?Te(e,NH):typeof e==`object`&&e&&`type`in e&&e.type===`tool_use`?[]:e),i={role:n,content:r};return e.name!=null&&(i.name=e.name),e.additional_kwargs.function_call!=null&&(i.function_call=e.additional_kwargs.function_call),qt.isInstance(e)&&e.tool_calls?.length?i.tool_calls=e.tool_calls.map(RC):(e.additional_kwargs.tool_calls!=null&&(i.tool_calls=e.additional_kwargs.tool_calls),_t.isInstance(e)&&e.tool_call_id!=null&&(i.tool_call_id=e.tool_call_id)),e.additional_kwargs.audio&&typeof e.additional_kwargs.audio==`object`&&`id`in e.additional_kwargs.audio?[i,{role:`assistant`,audio:{id:e.additional_kwargs.audio.id}}]:i}),zH=class extends MH{constructor(e,t){super(jH(e,t))}invocationParams(e,t){let n;e?.strict===void 0?this.supportsStrictToolCalling!==void 0&&(n=this.supportsStrictToolCalling):n=e.strict;let r={};e?.stream_options===void 0?this.streamUsage&&(this.streaming||t?.streaming)&&(r={stream_options:{include_usage:!0}}):r={stream_options:e.stream_options};let i={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:e?.stop??this.stopSequences,user:this.user,stream:this.streaming,functions:e?.functions,function_call:e?.function_call,tools:e?.tools?.length?e.tools.map(e=>this._convertChatOpenAIToolToCompletionsTool(e,{strict:n})):void 0,tool_choice:nV(e?.tool_choice),response_format:this._getResponseFormat(e?.response_format),seed:e?.seed,...r,parallel_tool_calls:e?.parallel_tool_calls,...this.audio||e?.audio?{audio:this.audio||e?.audio}:{},...this.modalities||e?.modalities?{modalities:this.modalities||e?.modalities}:{},...this.modelKwargs,prompt_cache_key:e?.promptCacheKey??this.promptCacheKey,prompt_cache_retention:e?.promptCacheRetention??this.promptCacheRetention,verbosity:e?.verbosity??this.verbosity};e?.prediction!==void 0&&(i.prediction=e.prediction),this.service_tier!==void 0&&(i.service_tier=this.service_tier),e?.service_tier!==void 0&&(i.service_tier=e.service_tier);let a=this._getReasoningParams(e);return a!==void 0&&a.effort!==void 0&&(i.reasoning_effort=a.effort),zB(i.model)?i.max_completion_tokens=this.maxTokens===-1?void 0:this.maxTokens:i.max_tokens=this.maxTokens===-1?void 0:this.maxTokens,i}async _generate(e,t,n){t.signal?.throwIfAborted();let r={},i=this.invocationParams(t),a=RH({messages:e,model:this.model});if(i.stream){let i=this._streamResponseChunks(e,t,n),a={};for await(let e of i){e.message.response_metadata={...e.generationInfo,...e.message.response_metadata};let t=e.generationInfo?.completion??0;a[t]===void 0?a[t]=e:a[t]=a[t].concat(e)}let o=Object.entries(a).sort(([e],[t])=>parseInt(e,10)-parseInt(t,10)).map(([e,t])=>t),{functions:s,function_call:c}=this.invocationParams(t),l=await this._getEstimatedTokenCountFromPrompt(e,s,c),u=await this._getNumTokensFromGenerations(o);return r.input_tokens=l,r.output_tokens=u,r.total_tokens=l+u,{generations:o,llmOutput:{estimatedTokenUsage:{promptTokens:r.input_tokens,completionTokens:r.output_tokens,totalTokens:r.total_tokens}}}}else{let e=await this.completionWithRetry({...i,stream:!1,messages:a},{signal:t?.signal,...t?.options}),{completion_tokens:n,prompt_tokens:o,total_tokens:s,prompt_tokens_details:c,completion_tokens_details:l}=e?.usage??{};n&&(r.output_tokens=(r.output_tokens??0)+n),o&&(r.input_tokens=(r.input_tokens??0)+o),s&&(r.total_tokens=(r.total_tokens??0)+s),(c?.audio_tokens!==null||c?.cached_tokens!==null)&&(r.input_token_details={...c?.audio_tokens!==null&&{audio:c?.audio_tokens},...c?.cached_tokens!==null&&{cache_read:c?.cached_tokens}}),(l?.audio_tokens!==null||l?.reasoning_tokens!==null)&&(r.output_token_details={...l?.audio_tokens!==null&&{audio:l?.audio_tokens},...l?.reasoning_tokens!==null&&{reasoning:l?.reasoning_tokens}});let u=[];for(let t of e?.choices??[]){let n={text:t.message?.content??``,message:this._convertCompletionsMessageToBaseMessage(t.message??{role:`assistant`},e)};n.generationInfo={...t.finish_reason?{finish_reason:t.finish_reason}:{},...t.logprobs?{logprobs:t.logprobs}:{}},Jt(n.message)&&(n.message.usage_metadata=r),n.message=new qt(Object.fromEntries(Object.entries(n.message).filter(([e])=>!e.startsWith(`lc_`)))),u.push(n)}return{generations:u,llmOutput:{tokenUsage:{promptTokens:r.input_tokens,completionTokens:r.output_tokens,totalTokens:r.total_tokens}}}}}async*_streamResponseChunks(e,t,n){let r=RH({messages:e,model:this.model}),i={...this.invocationParams(t,{streaming:!0}),messages:r,stream:!0},a,o=await this.completionWithRetry(i,t),s;for await(let e of o){if(t.signal?.aborted)return;let r=e?.choices?.[0];if(e.usage&&(s=e.usage),!r)continue;let{delta:i}=r;if(!i)continue;let o=this._convertCompletionsDeltaToBaseMessageChunk(i,e,a);a=i.role??a;let c={prompt:t.promptIndex??0,completion:r.index??0};if(typeof o.content!=`string`){console.log(`[WARNING]: Received non-string content from OpenAI. This is currently not supported.`);continue}let l={...c};r.finish_reason!=null&&(l.finish_reason=r.finish_reason,l.system_fingerprint=e.system_fingerprint,l.model_name=e.model,l.service_tier=e.service_tier),this.logprobs&&(l.logprobs=r.logprobs);let u=new Xl({message:o,text:o.content,generationInfo:l});yield u,await n?.handleLLMNewToken(u.text??``,c,void 0,void 0,void 0,{chunk:u})}if(s){let e={...s.prompt_tokens_details?.audio_tokens!==null&&{audio:s.prompt_tokens_details?.audio_tokens},...s.prompt_tokens_details?.cached_tokens!==null&&{cache_read:s.prompt_tokens_details?.cached_tokens}},t={...s.completion_tokens_details?.audio_tokens!==null&&{audio:s.completion_tokens_details?.audio_tokens},...s.completion_tokens_details?.reasoning_tokens!==null&&{reasoning:s.completion_tokens_details?.reasoning_tokens}},r=new Xl({message:new Xt({content:``,response_metadata:{usage:{...s}},usage_metadata:{input_tokens:s.prompt_tokens,output_tokens:s.completion_tokens,total_tokens:s.total_tokens,...Object.keys(e).length>0&&{input_token_details:e},...Object.keys(t).length>0&&{output_token_details:t}}}),text:``});yield r,await n?.handleLLMNewToken(r.text??``,{prompt:0,completion:0},void 0,void 0,void 0,{chunk:r})}if(t.signal?.aborted)throw Error(`AbortError`)}async completionWithRetry(e,t){let n=this._getClientOptions(t),r=e.response_format&&e.response_format.type===`json_schema`;return this.caller.call(async()=>{try{return r&&!e.stream?await this.client.chat.completions.parse(e,n):await this.client.chat.completions.create(e,n)}catch(e){throw LB(e)}})}_convertCompletionsDeltaToBaseMessageChunk(e,t,n){return FH({delta:e,rawResponse:t,includeRawResponse:this.__includeRawResponse,defaultRole:n})}_convertCompletionsMessageToBaseMessage(e,t){return PH({message:e,rawResponse:t,includeRawResponse:this.__includeRawResponse})}},BH={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`},VH={azureOpenAIApiKey:`AZURE_OPENAI_API_KEY`},HH=[`azureOpenAIApiKey`,`azureOpenAIApiVersion`,`azureOpenAIBasePath`,`azureOpenAIEndpoint`,`azureOpenAIApiInstanceName`,`azureOpenAIApiDeploymentName`,`deploymentName`,`openAIApiKey`,`openAIApiVersion`];function UH(e,t){return typeof e==`string`?{model:e,deploymentName:e,azureOpenAIApiDeploymentName:e,...t??{}}:e??t}function WH(e){if(this.azureOpenAIApiKey=e?.azureOpenAIApiKey??(typeof e?.openAIApiKey==`string`?e?.openAIApiKey:void 0)??(typeof e?.apiKey==`string`?e?.apiKey:void 0)??pr(`AZURE_OPENAI_API_KEY`),this.azureOpenAIApiInstanceName=e?.azureOpenAIApiInstanceName??pr(`AZURE_OPENAI_API_INSTANCE_NAME`),this.azureOpenAIApiDeploymentName=e?.azureOpenAIApiDeploymentName??e?.deploymentName??pr(`AZURE_OPENAI_API_DEPLOYMENT_NAME`),this.azureOpenAIApiVersion=e?.azureOpenAIApiVersion??e?.openAIApiVersion??pr(`AZURE_OPENAI_API_VERSION`),this.azureOpenAIBasePath=e?.azureOpenAIBasePath??pr(`AZURE_OPENAI_BASE_PATH`),this.azureOpenAIEndpoint=e?.azureOpenAIEndpoint??pr(`AZURE_OPENAI_ENDPOINT`),this.azureADTokenProvider=e?.azureADTokenProvider,!this.azureOpenAIApiKey&&!this.apiKey&&!this.azureADTokenProvider)throw Error(`Azure OpenAI API key or Token Provider not found`)}function GH(e){if(!this.client){let e={azureOpenAIApiDeploymentName:this.azureOpenAIApiDeploymentName,azureOpenAIApiInstanceName:this.azureOpenAIApiInstanceName,azureOpenAIApiKey:this.azureOpenAIApiKey,azureOpenAIBasePath:this.azureOpenAIBasePath,azureADTokenProvider:this.azureADTokenProvider,baseURL:this.clientConfig.baseURL,azureOpenAIEndpoint:this.azureOpenAIEndpoint},t=KB(e),{apiKey:n,...r}=this.clientConfig,i={...r,baseURL:t,timeout:this.timeout,maxRetries:0};this.azureADTokenProvider||(i.apiKey=e.azureOpenAIApiKey),i.baseURL||delete i.baseURL,i.defaultHeaders=XB(i.defaultHeaders,!0,`2.0.0`),this.client=new PB({apiVersion:this.azureOpenAIApiVersion,azureADTokenProvider:this.azureADTokenProvider,deployment:this.azureOpenAIApiDeploymentName,...i})}let t={...this.clientConfig,...e};return this.azureOpenAIApiKey&&(t.headers={"api-key":this.azureOpenAIApiKey,...t.headers},t.query={"api-version":this.azureOpenAIApiVersion,...t.query}),t}function KH(e){let t=e;function n(e){return typeof e==`object`&&!!e}if(n(t)&&n(t.kwargs)){if(delete t.kwargs.azure_openai_base_path,delete t.kwargs.azure_openai_api_deployment_name,delete t.kwargs.azure_openai_api_key,delete t.kwargs.azure_openai_api_version,delete t.kwargs.azure_open_ai_base_path,!t.kwargs.azure_endpoint&&this.azureOpenAIEndpoint&&(t.kwargs.azure_endpoint=this.azureOpenAIEndpoint),!t.kwargs.azure_endpoint&&this.azureOpenAIBasePath){let e=this.azureOpenAIBasePath.split(`/openai/deployments/`);if(e.length===2&&e[0].startsWith(`http`)){let[n]=e;t.kwargs.azure_endpoint=n}}if(!t.kwargs.azure_endpoint&&this.azureOpenAIApiInstanceName&&(t.kwargs.azure_endpoint=`https://${this.azureOpenAIApiInstanceName}.openai.azure.com/`),!t.kwargs.deployment_name&&this.azureOpenAIApiDeploymentName&&(t.kwargs.deployment_name=this.azureOpenAIApiDeploymentName),!t.kwargs.deployment_name&&this.azureOpenAIBasePath){let e=this.azureOpenAIBasePath.split(`/openai/deployments/`);if(e.length===2){let[,n]=e;t.kwargs.deployment_name=n}}t.kwargs.azure_endpoint&&t.kwargs.deployment_name&&t.kwargs.openai_api_base&&delete t.kwargs.openai_api_base,t.kwargs.azure_openai_api_instance_name&&t.kwargs.azure_endpoint&&delete t.kwargs.azure_openai_api_instance_name}return t}var qH=class extends zH{azureOpenAIApiVersion;azureOpenAIApiKey;azureADTokenProvider;azureOpenAIApiInstanceName;azureOpenAIApiDeploymentName;azureOpenAIBasePath;azureOpenAIEndpoint;_llmType(){return`azure_openai`}get lc_aliases(){return{...super.lc_aliases,...BH}}get lc_secrets(){return{...super.lc_secrets,...VH}}get lc_serializable_keys(){return[...super.lc_serializable_keys,...HH]}getLsParams(e){let t=super.getLsParams(e);return t.ls_provider=`azure`,t}constructor(e,t){let n=UH(e,t);super(n),WH.call(this,n)}_getClientOptions(e){return GH.call(this,e)}toJSON(){return KH.call(this,super.toJSON())}},JH=`__openai_function_call_ids__`;function YH(e){return e.type===`url_citation`?{type:`citation`,source:`url_citation`,url:e.url,title:e.title,startIndex:e.start_index,endIndex:e.end_index}:e.type===`file_citation`?{type:`citation`,source:`file_citation`,title:e.filename,startIndex:e.index,file_id:e.file_id}:e.type===`container_file_citation`?{type:`citation`,source:`container_file_citation`,title:e.filename,startIndex:e.start_index,endIndex:e.end_index,file_id:e.file_id,container_id:e.container_id}:e.type===`file_path`?{type:`citation`,source:`file_path`,startIndex:e.index,file_id:e.file_id}:{type:`non_standard`,value:e}}function XH(e){if(e.type===`url_citation`||e.type===`file_citation`||e.type===`container_file_citation`||e.type===`file_path`)return e;if(e.type===`citation`){let t=e;if(t.source===`url_citation`)return{type:`url_citation`,url:t.url??``,title:t.title??``,start_index:t.startIndex??0,end_index:t.endIndex??0};if(t.source===`file_citation`)return{type:`file_citation`,file_id:t.file_id??``,filename:t.title??``,index:t.startIndex??0};if(t.source===`container_file_citation`)return{type:`container_file_citation`,file_id:t.file_id??``,filename:t.title??``,container_id:t.container_id??``,start_index:t.startIndex??0,end_index:t.endIndex??0};if(t.source===`file_path`)return{type:`file_path`,file_id:t.file_id??``,index:t.startIndex??0}}return e.type===`non_standard`?e.value:e}var ZH=e=>{let t={...e?.input_tokens_details?.cached_tokens!=null&&{cache_read:e?.input_tokens_details?.cached_tokens}},n={...e?.output_tokens_details?.reasoning_tokens!=null&&{reasoning:e?.output_tokens_details?.reasoning_tokens}};return{input_tokens:e?.input_tokens??0,output_tokens:e?.output_tokens??0,total_tokens:e?.total_tokens??0,input_token_details:t,output_token_details:n}},QH=e=>{if(e.error){let t=Error(e.error.message);throw t.name=e.error.code,t}let t,n=[],r=[],i=[],a=e.output.map(e=>{if(e.type===`function_call`&&`parsed_arguments`in e){let t={...e};return delete t.parsed_arguments,t}return e}),o={model_provider:`openai`,model:e.model,created_at:e.created_at,id:e.id,incomplete_details:e.incomplete_details,metadata:e.metadata,object:e.object,output:a,status:e.status,user:e.user,service_tier:e.service_tier,model_name:e.model},s={};for(let a of e.output)if(a.type===`message`)t=a.id,n.push(...a.content.flatMap(e=>e.type===`output_text`?(`parsed`in e&&e.parsed!=null&&(s.parsed=e.parsed),{type:`text`,text:e.text,annotations:e.annotations.map(YH),...a.phase===null?{}:{phase:a.phase}}):e.type===`refusal`?(s.refusal=e.refusal,[]):e));else if(a.type===`function_call`){let e={function:{name:a.name,arguments:a.arguments},id:a.call_id};try{r.push(LC(e,{returnId:!0}))}catch(t){let n;typeof t==`object`&&t&&`message`in t&&typeof t.message==`string`&&(n=t.message),i.push(zC(e,n))}s[JH]??={},a.id&&(s[JH][a.call_id]=a.id)}else if(a.type===`reasoning`){s.reasoning=a;let e=a.summary?.map(e=>e.text).filter(Boolean).join(``);e&&n.push({type:`reasoning`,reasoning:e})}else if(a.type===`custom_tool_call`){let e=cV(a);e?r.push(e):i.push(zC(a,`Malformed custom tool call`))}else if(a.type===`computer_call`){let e=lV(a);e?r.push(e):i.push(zC(a,`Malformed computer call`))}else a.type===`image_generation_call`?(a.result&&n.push({type:`image`,mimeType:`image/png`,data:a.result,id:a.id,metadata:{status:a.status}}),s.tool_outputs??=[],s.tool_outputs.push(a)):(s.tool_outputs??=[],s.tool_outputs.push(a));return new qt({id:t,content:n,tool_calls:r,invalid_tool_calls:i,usage_metadata:ZH(e.usage),additional_kwargs:s,response_metadata:o})},$H=e=>{let t=(e.summary.length>1?e.summary.reduce((e,t)=>{let n=e[e.length-1];return n.index===t.index?n.text+=t.text:e.push(t),e},[{...e.summary[0]}]):e.summary).map(e=>Object.fromEntries(Object.entries(e).filter(([e])=>e!==`index`)));return{...e,summary:t}},eU=e=>{let t=[],n={},r,i=[],a={model_provider:`openai`},o={},s;if(e.type===`response.output_text.delta`)t.push({type:`text`,text:e.delta,index:e.content_index});else if(e.type===`response.output_text.annotation.added`)t.push({type:`text`,text:``,annotations:[YH(e.annotation)],index:e.content_index});else if(e.type===`response.output_item.added`&&e.item.type===`message`){s=e.item.id;let n=`phase`in e.item?e.item.phase:void 0;n&&t.push({type:`text`,text:``,phase:n,index:0})}else if(e.type===`response.output_item.added`&&e.item.type===`function_call`)i.push({type:`tool_call_chunk`,name:e.item.name,args:e.item.arguments,id:e.item.call_id,index:e.output_index}),o[JH]={[e.item.call_id]:e.item.id};else if(e.type===`response.output_item.done`&&e.item.type===`computer_call`)i.push({type:`tool_call_chunk`,name:`computer_use`,args:JSON.stringify({action:e.item.action}),id:e.item.call_id,index:e.output_index}),o.tool_outputs=[e.item];else if(e.type===`response.output_item.done`&&e.item.type===`image_generation_call`)e.item.result&&t.push({type:`image`,mimeType:`image/png`,data:e.item.result,id:e.item.id,metadata:{status:e.item.status}}),o.tool_outputs=[e.item];else if(e.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(e.item.type))o.tool_outputs=[e.item];else if(e.type===`response.created`)a.id=e.response.id,a.model_name=e.response.model,a.model=e.response.model;else if(e.type===`response.completed`){let t=QH(e.response);r=ZH(e.response.usage),e.response.text?.format?.type===`json_schema`&&t.text&&(o.parsed??=JSON.parse(t.text));for(let[n,r]of Object.entries(e.response))n!==`id`&&(n===`output`?a[n]=t.response_metadata.output:a[n]=r)}else if(e.type===`response.function_call_arguments.delta`||e.type===`response.custom_tool_call_input.delta`)i.push({type:`tool_call_chunk`,args:e.delta,index:e.output_index});else if(e.type===`response.web_search_call.completed`||e.type===`response.file_search_call.completed`)n={tool_outputs:{id:e.item_id,type:e.type.replace(`response.`,``).replace(`.completed`,``),status:`completed`}};else if(e.type===`response.refusal.done`)o.refusal=e.refusal;else if(e.type===`response.output_item.added`&&`item`in e&&e.item.type===`reasoning`){let n=e.item.summary?e.item.summary.map((e,t)=>({...e,index:t})):void 0;o.reasoning={id:e.item.id,type:e.item.type,...n?{summary:n}:{}};let r=e.item.summary?.map(e=>e.text).filter(Boolean).join(``);r&&t.push({type:`reasoning`,reasoning:r})}else if(e.type===`response.reasoning_summary_part.added`)o.reasoning={type:`reasoning`,summary:[{...e.part,index:e.summary_index}]},e.part.text&&t.push({type:`reasoning`,reasoning:e.part.text,index:e.summary_index});else if(e.type===`response.reasoning_summary_text.delta`)o.reasoning={type:`reasoning`,summary:[{text:e.delta,type:`summary_text`,index:e.summary_index}]},e.delta&&t.push({type:`reasoning`,reasoning:e.delta,index:e.summary_index});else if(e.type===`response.image_generation_call.partial_image`)return null;else return null;return new Xl({text:t.map(e=>e.text).join(``),message:new Xt({id:s,content:t,tool_call_chunks:i,usage_metadata:r,additional_kwargs:o,response_metadata:a}),generationInfo:n})},tU=e=>{let t=qt.isInstance(e)&&e.response_metadata?.model_provider===`openai`;function*n(){let n=RB(()=>{try{let t=WB(e);return t===`system`||t===`developer`||t===`assistant`||t===`user`?t:`assistant`}catch{return`assistant`}}),r,i=new Set,a=new Set,o=new Map,s=new Map;function*c(){if(!r)return;let e=r.content;(typeof e==`string`&&e.length>0||Array.isArray(e)&&e.length>0)&&(yield r),r=void 0}let l=(e,t)=>{r||={type:`message`,role:n,content:[],...t?{phase:t}:{}},typeof r.content==`string`?r.content=r.content.length>0?[{type:`input_text`,text:r.content},...e]:[...e]:r.content.push(...e)},u=e=>{if(typeof e==`string`)return e;try{return JSON.stringify(e??{})}catch{return`{}`}},d=e=>{let t=RB(()=>{let t=e.metadata?.detail;return t===`low`||t===`high`||t===`auto`?t:`auto`});if(e.fileId)return{type:`input_image`,detail:t,file_id:e.fileId};if(e.url)return{type:`input_image`,detail:t,image_url:e.url};if(e.data){let n=typeof e.data==`string`?e.data:Buffer.from(e.data).toString(`base64`);return{type:`input_image`,detail:t,image_url:`data:${e.mimeType??`image/png`};base64,${n}`}}},f=e=>{if(e.fileId){let t=VB(e);return{type:`input_file`,file_id:e.fileId,...t?{filename:t}:{}}}if(e.url){let t=VB(e);return{...t?{filename:t}:{},type:`input_file`,file_url:e.url}}if(e.data){let t=UB(e),n=typeof e.data==`string`?e.data:Buffer.from(e.data).toString(`base64`);return{type:`input_file`,file_data:`data:${e.mimeType??`application/octet-stream`};base64,${n}`,filename:t}}},p=e=>{let t=RB(()=>{if(Array.isArray(e.summary)){let t=e.summary?.map(e=>e?.text).filter(e=>typeof e==`string`)??[];if(t.length>0)return t}return e.reasoning?[e.reasoning]:[]}),n=t.length>0?t.map(e=>({type:`summary_text`,text:e})):[{type:`summary_text`,text:``}],r={type:`reasoning`,id:e.id??``,summary:n};return e.reasoning&&(r.content=[{type:`reasoning_text`,text:e.reasoning}]),r},m=e=>({type:`function_call`,name:e.name??``,call_id:e.id??``,arguments:u(e.args)}),h=e=>{let t=u(e.output),n=e.status===`success`?`completed`:e.status===`error`?`incomplete`:void 0;return{type:`function_call_output`,call_id:e.toolCallId??``,output:t,...n?{status:n}:{}}};for(let n of e.contentBlocks)if(n.type===`text`){let e=RB(()=>{if(`extras`in n&&typeof n.extras==`object`&&n.extras!==null&&`phase`in n.extras)return n.extras.phase});l([{type:`input_text`,text:n.text}],e)}else if(n.type!==`invalid_tool_call`){if(n.type===`reasoning`)yield*c(),yield p(n);else if(n.type===`tool_call`){yield*c();let e=n.id??``;e&&(i.add(e),o.delete(e)),yield m(n)}else if(n.type===`tool_call_chunk`){if(n.id){let e=o.get(n.id)??{name:n.name,args:[]};n.name&&(e.name=n.name),n.args&&e.args.push(n.args),o.set(n.id,e)}}else if(n.type===`server_tool_call`){yield*c();let e=n.id??``;e&&(a.add(e),s.delete(e)),yield m(n)}else if(n.type===`server_tool_call_chunk`){if(n.id){let e=s.get(n.id)??{name:n.name,args:[]};n.name&&(e.name=n.name),n.args&&e.args.push(n.args),s.set(n.id,e)}}else if(n.type===`server_tool_call_result`)yield*c(),yield h(n);else if(n.type!==`audio`)if(n.type===`file`){let e=f(n);e&&l([e])}else if(n.type===`image`){let e=d(n);e&&l([e])}else if(n.type===`video`){let e=f(n);e&&l([e])}else n.type===`text-plain`?n.text&&l([{type:`input_text`,text:n.text}]):n.type===`non_standard`&&t&&(yield*c(),yield n.value)}yield*c();for(let[e,t]of o){if(!e||i.has(e))continue;let n=t.args.join(``);!t.name&&!n||(yield{type:`function_call`,call_id:e,name:t.name??``,arguments:n})}for(let[e,t]of s){if(!e||a.has(e))continue;let n=t.args.join(``);!t.name&&!n||(yield{type:`function_call`,call_id:e,name:t.name??``,arguments:n})}}return Array.from(n())},nU=({messages:e,zdrEnabled:t,model:n})=>e.flatMap(e=>{let r=e.response_metadata;if(r?.output_version===`v1`)return tU(e);let i=e.additional_kwargs,a=WB(e);if(a===`system`&&zB(n)&&(a=`developer`),a===`function`)throw Error(`Function messages are not supported in Responses API`);if(a===`tool`){let t=e;if(i?.type===`computer_call_output`)return{type:`computer_call_output`,output:(()=>{if(typeof t.content==`string`)return{type:`input_image`,image_url:t.content};if(Array.isArray(t.content)){let e=t.content.find(e=>e.type===`input_image`);if(e)return e;let n=t.content.find(e=>e.type===`computer_screenshot`);if(n)return n;let r=t.content.find(e=>e.type===`image_url`);if(r)return{type:`input_image`,image_url:typeof r.image_url==`string`?r.image_url:r.image_url.url}}throw Error(`Invalid computer call output`)})(),call_id:t.tool_call_id};if(t.additional_kwargs?.customTool)return{type:`custom_tool_call_output`,call_id:t.tool_call_id,output:t.content};let n=Array.isArray(t.content)&&t.content.every(e=>typeof e==`object`&&!!e&&`type`in e&&(e.type===`input_file`||e.type===`input_image`||e.type===`input_text`));return{type:`function_call_output`,call_id:t.tool_call_id,id:t.id?.startsWith(`fc_`)?t.id:void 0,output:n||typeof t.content==`string`?t.content:JSON.stringify(t.content)}}if(a===`assistant`){if(!t&&r?.output!=null&&Array.isArray(r?.output)&&r?.output.length>0&&r?.output.every(e=>`type`in e))return r?.output;let n=[],a=i?.reasoning,o=!!a?.encrypted_content;if(a&&(!t||o)){let e=$H(a);n.push(e)}let{content:s}=e;if(i?.refusal&&(typeof s==`string`&&(s=[{type:`output_text`,text:s,annotations:[]}]),s=[...s,{type:`refusal`,refusal:i.refusal}]),typeof s==`string`||s.length>0){let r={type:`message`,role:`assistant`,...e.id&&!t&&e.id.startsWith(`msg_`)?{id:e.id}:{},content:RB(()=>typeof s==`string`?s:s.flatMap(e=>{if(e.type===`text`){let t=e;return{type:`output_text`,text:t.text,annotations:(t.annotations??[]).map(XH)}}return e.type===`output_text`||e.type===`refusal`?e:[]})),phase:RB(()=>{if(Array.isArray(s))return s.find(e=>`phase`in e&&typeof e.phase==`string`)?.phase})};n.push(r)}let c=i?.[JH];qt.isInstance(e)&&e.tool_calls?.length?n.push(...e.tool_calls.map(e=>dV(e)?{type:`custom_tool_call`,id:e.call_id,call_id:e.id??``,input:e.args.input,name:e.name}:uV(e)?{type:`computer_call`,id:e.call_id,call_id:e.id??``,action:e.args.action}:{type:`function_call`,name:e.name,arguments:JSON.stringify(e.args),call_id:e.id,...t?{}:{id:c?.[e.id]}})):i?.tool_calls&&n.push(...i.tool_calls.map(e=>({type:`function_call`,name:e.function.name,call_id:e.id,arguments:e.function.arguments,...t?{}:{id:c?.[e.id]}})));let l=r?.output?.length?r?.output:i.tool_outputs,u=[`computer_call`,`mcp_call`,`code_interpreter_call`,`image_generation_call`,`shell_call`,`local_shell_call`];if(l!=null){let e=l?.filter(e=>u.includes(e.type));e.length>0&&n.push(...e)}return n}if(a===`user`||a===`system`||a===`developer`){if(typeof e.content==`string`)return{type:`message`,role:a,content:e.content};let t=[],n=e.content.flatMap(e=>(e.type===`mcp_approval_response`&&t.push({type:`mcp_approval_response`,approval_request_id:e.approval_request_id,approve:e.approve}),_e(e)?Te(e,NH):e.type===`text`?{type:`input_text`,text:e.text}:e.type===`image_url`?{type:`input_image`,image_url:RB(()=>{if(typeof e.image_url==`string`)return e.image_url;if(typeof e.image_url==`object`&&e.image_url!==null&&`url`in e.image_url)return e.image_url.url}),detail:RB(()=>{if(typeof e.image_url==`string`)return`auto`;if(typeof e.image_url==`object`&&e.image_url!==null&&`detail`in e.image_url)return e.image_url.detail})}:e.type===`input_text`||e.type===`input_image`||e.type===`input_file`?e:[]));return n.length>0&&t.push({type:`message`,role:a,content:n}),t}return console.warn(`Unsupported role found when converting to OpenAI Responses API: ${a}`),[]}),rU=class extends MH{constructor(e,t){super(jH(e,t))}invocationParams(e){let t;e?.strict!==void 0&&(t=e.strict),t===void 0&&this.supportsStrictToolCalling!==void 0&&(t=this.supportsStrictToolCalling);let 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:e?.previous_response_id,truncation:e?.truncation,include:e?.include,tools:e?.tools?.length?this._reduceChatOpenAITools(e.tools,{stream:this.streaming,strict:t}):void 0,tool_choice:aV(e?.tool_choice)?e?.tool_choice:(()=>{let t=nV(e?.tool_choice);if(typeof t==`object`&&`type`in t){if(t.type===`function`)return{type:`function`,name:t.function.name};if(t.type===`allowed_tools`)return{type:`allowed_tools`,mode:t.allowed_tools.mode,tools:t.allowed_tools.tools};if(t.type===`custom`)return{type:`custom`,name:t.custom.name}}})(),text:(()=>{if(e?.text)return e.text;let t=this._getResponseFormat(e?.response_format);return t?.type===`json_schema`?t.json_schema.schema==null?void 0:{format:{type:`json_schema`,schema:t.json_schema.schema,description:t.json_schema.description,name:t.json_schema.name,strict:t.json_schema.strict},verbosity:e?.verbosity}:{format:t,verbosity:e?.verbosity}})(),parallel_tool_calls:e?.parallel_tool_calls,max_output_tokens:this.maxTokens===-1?void 0:this.maxTokens,prompt_cache_key:e?.promptCacheKey??this.promptCacheKey,prompt_cache_retention:e?.promptCacheRetention??this.promptCacheRetention,...this.zdrEnabled?{store:!1}:{},...this.modelKwargs},r=this._getReasoningParams(e);return r!==void 0&&(n.reasoning=r),n}async _generate(e,t,n){t.signal?.throwIfAborted();let r=this.invocationParams(t);if(r.stream){let r=this._streamResponseChunks(e,t,n),i;for await(let e of r)e.message.response_metadata={...e.generationInfo,...e.message.response_metadata},i=i?.concat(e)??e;return{generations:i?[i]:[],llmOutput:{estimatedTokenUsage:i?.message?.usage_metadata}}}else{let n=await this.completionWithRetry({input:nU({messages:e,zdrEnabled:this.zdrEnabled??!1,model:this.model}),...r,stream:!1},{signal:t?.signal,...t?.options});return{generations:[{text:n.output_text,message:QH(n)}],llmOutput:{id:n.id,estimatedTokenUsage:n.usage?{promptTokens:n.usage.input_tokens,completionTokens:n.usage.output_tokens,totalTokens:n.usage.total_tokens}:void 0}}}}async*_streamResponseChunks(e,t,n){let r=await this.completionWithRetry({...this.invocationParams(t),input:nU({messages:e,zdrEnabled:this.zdrEnabled??!1,model:this.model}),stream:!0},t);for await(let e of r){if(t.signal?.aborted)return;let r=eU(e);r!=null&&(yield r,await n?.handleLLMNewToken(r.text||``,{prompt:t.promptIndex??0,completion:0},void 0,void 0,void 0,{chunk:r}))}}async completionWithRetry(e,t){return this.caller.call(async()=>{let n=this._getClientOptions(t);try{return e.text?.format?.type===`json_schema`&&!e.stream?await this.client.responses.parse(e,n):await this.client.responses.create(e,n)}catch(e){throw LB(e)}})}_reduceChatOpenAITools(e,t){let n=[];for(let r of e)if(rV(r))r.type===`image_generation`&&t?.stream&&(r.partial_images=1),n.push(r);else if(oV(r)){let e=r.metadata.customTool;n.push({type:`custom`,name:e.name,description:e.description,format:e.format})}else if(oC(r)){let e={};for(let[t,n]of Object.entries(r))t!==`type`&&t!==`function`&&(e[t]=n);n.push({type:`function`,name:r.function.name,parameters:r.function.parameters,description:r.function.description,strict:t?.strict??null,...e})}else sV(r)&&n.push(fV(r));return n}},iU=class extends rU{azureOpenAIApiVersion;azureOpenAIApiKey;azureADTokenProvider;azureOpenAIApiInstanceName;azureOpenAIApiDeploymentName;azureOpenAIBasePath;azureOpenAIEndpoint;_llmType(){return`azure_openai`}get lc_aliases(){return{...super.lc_aliases,...BH}}get lc_secrets(){return{...super.lc_secrets,...VH}}get lc_serializable_keys(){return[...super.lc_serializable_keys,...HH]}getLsParams(e){let t=super.getLsParams(e);return t.ls_provider=`azure`,t}constructor(e,t){let n=UH(e,t);super(n),WH.call(this,n)}_getClientOptions(e){return GH.call(this,e)}toJSON(){return KH.call(this,super.toJSON())}},aU=class e extends MH{useResponsesApi=!1;responses;completions;get lc_serializable_keys(){return[...super.lc_serializable_keys,`useResponsesApi`]}get callKeys(){return[...super.callKeys,`useResponsesApi`]}fields;constructor(e,t){let n=jH(e,t);super(n),this.fields=n,this.useResponsesApi=n?.useResponsesApi??!1,this.responses=n?.responses??new rU(n),this.completions=n?.completions??new zH(n)}_useResponsesApi(e){let t=e?.tools?.some(rV),n=e?.previous_response_id!=null||e?.text!=null||e?.truncation!=null||e?.include!=null||e?.reasoning?.summary!=null||this.reasoning?.summary!=null,r=e?.tools?.some(sV)||e?.tools?.some(oV);return this.useResponsesApi||t||n||r||GB(this.model)}getLsParams(e){let t=this._combineCallOptions(e);return this._useResponsesApi(e)?this.responses.getLsParams(t):this.completions.getLsParams(t)}invocationParams(e){let t=this._combineCallOptions(e);return this._useResponsesApi(e)?this.responses.invocationParams(t):this.completions.invocationParams(t)}async _generate(e,t,n){return this._useResponsesApi(t)?this.responses._generate(e,t,n):this.completions._generate(e,t,n)}async*_streamResponseChunks(e,t,n){if(this._useResponsesApi(t)){yield*this.responses._streamResponseChunks(e,this._combineCallOptions(t),n);return}yield*this.completions._streamResponseChunks(e,this._combineCallOptions(t),n)}withConfig(t){let n=new e(this.fields);return n.defaultOptions={...this.defaultOptions,...t},n}},oU=class extends aU{azureOpenAIApiVersion;azureOpenAIApiKey;azureADTokenProvider;azureOpenAIApiInstanceName;azureOpenAIApiDeploymentName;azureOpenAIBasePath;azureOpenAIEndpoint;_llmType(){return`azure_openai`}get lc_aliases(){return{...super.lc_aliases,...BH}}get lc_secrets(){return{...super.lc_secrets,...VH}}get lc_serializable_keys(){return[...super.lc_serializable_keys,...HH]}getLsParams(e){let t=super.getLsParams(e);return t.ls_provider=`azure`,t}constructor(e,t){let n=UH(e,t);super({...n,completions:new qH(n),responses:new iU(n)}),WH.call(this,n)}_getStructuredOutputMethod(e){let t={...e};return this.model.startsWith(`gpt-4o`)&&t?.method===void 0?`functionCalling`:super._getStructuredOutputMethod(t)}toJSON(){return KH.call(this,super.toJSON())}};V({action:KD([V({type:iO(`screenshot`)}),V({type:iO(`click`),x:jD(),y:jD(),button:nO([`left`,`right`,`wheel`,`back`,`forward`]).default(`left`)}),V({type:iO(`double_click`),x:jD(),y:jD(),button:nO([`left`,`right`,`wheel`,`back`,`forward`]).default(`left`)}),V({type:iO(`drag`),path:UD(V({x:jD(),y:jD()}))}),V({type:iO(`keypress`),keys:UD(lD())}),V({type:iO(`move`),x:jD(),y:jD()}),V({type:iO(`scroll`),x:jD(),y:jD(),scroll_x:jD(),scroll_y:jD()}),V({type:iO(`type`),text:lD()}),V({type:iO(`wait`),duration:jD().optional()})])}),KD([V({type:iO(`exec`),command:UD(lD()),env:eO(lD(),lD()).optional(),working_directory:lD().optional(),timeout_ms:jD().optional(),user:lD().optional()})]),V({commands:UD(lD()).describe(`Array of shell commands to execute`),timeout_ms:jD().optional().describe(`Optional timeout in milliseconds for the commands`),max_output_length:jD().optional().describe(`Optional maximum number of characters to return from each command`)}),KD([V({type:iO(`create_file`),path:lD(),diff:lD()}),V({type:iO(`update_file`),path:lD(),diff:lD()}),V({type:iO(`delete_file`),path:lD()})]);function sU(e){if(typeof e==`object`&&e){let t={...e};`additionalProperties`in t&&delete t.additionalProperties,`$schema`in t&&delete t.$schema,`strict`in t&&delete t.strict;for(let e in t)e in t&&(Array.isArray(t[e])?t[e]=t[e].map(sU):typeof t[e]==`object`&&t[e]!==null&&(t[e]=sU(t[e])));return t}return e}function cU(e){let{$schema:t,...n}=sU(Mm(e)||$_(e)?Bv(e):e);return n}function lU(e){let{$schema:t,...n}=sU(e);return n}function uU(e,t,n=[]){if(typeof e!=`object`||!e)return;let r=e;if(Array.isArray(r.enum)&&r.enum.some(e=>e===``)){let e=n.length?` at path "${n.join(`.`)}"`:``,r=t?` in tool "${t}"`:``;throw Error(`Invalid enum: empty string not allowed${r}${e}. Gemini API rejects empty strings in enums.`)}if(r.type===`object`&&r.properties&&typeof r.properties==`object`)for(let[e,i]of Object.entries(r.properties))uU(i,t,[...n,e]);r.items&&uU(r.items,t,[...n,`[]`]);for(let e of[`anyOf`,`oneOf`,`allOf`]){let i=r[e];Array.isArray(i)&&i.forEach((r,i)=>uU(r,t,[...n,`${e}[${i}]`]))}r.additionalProperties&&typeof r.additionalProperties==`object`&&uU(r.additionalProperties,t,[...n,`additionalProperties`])}var dU=`__gemini_function_call_thought_signatures__`,fU=`ErYCCrMCAdHtim9kOoOkrPiCNVsmlpMIKd7ZMxgiFbVQOkgp7nlLcDMzVsZwIzvuT7nQROivoXA72ccC2lSDvR0Gh7dkWaGuj7ctv6t7ZceHnecx0QYa+ix8tYpRfjhyWozQ49lWiws6+YGjCt10KRTyWsZ2h6O7iHTYJwKIRwGUHRKy/qK/6kFxJm5ML00gLq4D8s5Z6DBpp2ZlR+uF4G8jJgeWQgyHWVdx2wGYElaceVAc66tZdPQRdOHpWtgYSI1YdaXgVI8KHY3/EfNc2YqqMIulvkDBAnuMhkAjV9xmBa54Tq+ih3Im4+r3DzqhGqYdsSkhS0kZMwte4Hjs65dZzCw9lANxIqYi1DJ639WNPYihp/DCJCos7o+/EeSPJaio5sgWDyUnMGkY1atsJZ+m7pj7DD5tvQ==`,pU=e=>e();function mU(e){return Zt.isInstance(e)?e.role:e.type}function hU(e){switch(e){case`supervisor`:case`ai`:case`model`:return`model`;case`system`:return`system`;case`human`:return`user`;case`tool`:case`function`:return`function`;default:throw Error(`Unknown / unsupported author: ${e}`)}}function gU(e){if(`mimeType`in e&&`data`in e)return{inlineData:{mimeType:e.mimeType,data:e.data}};if(`mimeType`in e&&`fileUri`in e)return{fileData:{mimeType:e.mimeType,fileUri:e.fileUri}};throw Error(`Invalid media content`)}function _U(e,t){return t.map(e=>Jt(e)?e.tool_calls??[]:[]).flat().find(t=>t.id===e.tool_call_id)?.name}function vU(e,t){if(`data`in e&&e.data!==void 0){let n=e.data instanceof Uint8Array?btoa(String.fromCharCode(...e.data)):e.data;return{inlineData:{mimeType:e.mimeType||t,data:n}}}if(`url`in e&&e.url!==void 0){let n=we({dataUrl:e.url});return n?{inlineData:{mimeType:n.mime_type,data:n.data}}:{fileData:{mimeType:e.mimeType||t,fileUri:e.url}}}throw`fileId`in e&&e.fileId!==void 0?Error(`ContentBlock.Multimodal fileId is not supported by Google Generative AI. Use a URL or base64 data instead.`):Error(`Invalid multimodal content block: must have "data", "url", or "fileId" property. Received: ${JSON.stringify(e)}`)}function yU(e){return{providerName:`Google Gemini`,fromStandardTextBlock(e){return{text:e.text}},fromStandardImageBlock(t){if(!e)throw Error(`This model does not support images`);if(t.source_type===`url`){let e=we({dataUrl:t.url});return e?{inlineData:{mimeType:e.mime_type,data:e.data}}:{fileData:{mimeType:t.mime_type??``,fileUri:t.url}}}if(t.source_type===`base64`)return{inlineData:{mimeType:t.mime_type??``,data:t.data}};throw Error(`Unsupported source type: ${t.source_type}`)},fromStandardAudioBlock(t){if(!e)throw Error(`This model does not support audio`);if(t.source_type===`url`){let e=we({dataUrl:t.url});return e?{inlineData:{mimeType:e.mime_type,data:e.data}}:{fileData:{mimeType:t.mime_type??``,fileUri:t.url}}}if(t.source_type===`base64`)return{inlineData:{mimeType:t.mime_type??``,data:t.data}};throw Error(`Unsupported source type: ${t.source_type}`)},fromStandardFileBlock(t){if(!e)throw Error(`This model does not support files`);if(t.source_type===`text`)return{text:t.text};if(t.source_type===`url`){let e=we({dataUrl:t.url});return e?{inlineData:{mimeType:e.mime_type,data:e.data}}:{fileData:{mimeType:t.mime_type??``,fileUri:t.url}}}if(t.source_type===`base64`)return{inlineData:{mimeType:t.mime_type??``,data:t.data}};throw Error(`Unsupported source type: ${t.source_type}`)}}}function bU(e,t){if(_e(e))return Te(e,yU(t));if(e.type===`text`)return{text:e.text};if(e.type===`executableCode`)return{executableCode:e.executableCode};if(e.type===`codeExecutionResult`)return{codeExecutionResult:e.codeExecutionResult};if(e.type===`image_url`){if(!t)throw Error(`This model does not support images`);let n;if(typeof e.image_url==`string`)n=e.image_url;else if(typeof e.image_url==`object`&&`url`in e.image_url)n=e.image_url.url;else throw Error(`Please provide image as base64 encoded data URL`);let[r,i]=n.split(`,`);if(!r.startsWith(`data:`))throw Error(`Please provide image as base64 encoded data URL`);let[a,o]=r.replace(/^data:/,``).split(`;`);if(o!==`base64`)throw Error(`Please provide image as base64 encoded data URL`);return{inlineData:{data:i,mimeType:a}}}else if(e.type===`media`)return gU(e);else if(e.type===`image`)return vU(e,`image/png`);else if(e.type===`video`)return vU(e,`video/mp4`);else if(e.type===`audio`)return vU(e,`audio/mpeg`);else if(e.type===`file`)return vU(e,`application/octet-stream`);else if(e.type===`text-plain`)return`text`in e&&typeof e.text==`string`?{text:e.text}:vU(e,`text/plain`);else if(e.type===`tool_use`)return{functionCall:{name:e.name,args:e.input}};else if(e.type===`tool_call`)return{functionCall:{name:e.name,args:e.args}};else if(e.type?.includes(`/`)&&e.type.split(`/`).length===2&&`data`in e&&typeof e.data==`string`)return{inlineData:{mimeType:e.type,data:e.data}};else if(e.type===`thinking`){let t=e;return{text:t.thinking,thought:!0,...t.signature?{thoughtSignature:t.signature}:{}}}else if(`functionCall`in e)return;else if(`type`in e)throw Error(`Unknown content type ${e.type}`);else throw Error(`Unknown content ${JSON.stringify(e)}`)}function xU(e,t,n,r){if(bt(e)){let r=e.name??_U(e,n);if(r===void 0)throw Error(`Google requires a tool name for each tool call response, and we could not infer a called tool name for ToolMessage "${e.id}" from your passed messages. Please populate a "name" field on that ToolMessage explicitly.`);let i=Array.isArray(e.content)?e.content.map(e=>bU(e,t)).filter(e=>e!==void 0):e.content;return e.status===`error`?[{functionResponse:{name:r,response:{error:{details:i}}}}]:[{functionResponse:{name:r,response:{result:i}}}]}let i=[],a=[];typeof e.content==`string`&&e.content&&a.push({text:e.content}),Array.isArray(e.content)&&a.push(...e.content.map(e=>bU(e,t)).filter(e=>e!==void 0));let o=e.additional_kwargs?.[dU];return Jt(e)&&e.tool_calls?.length&&(i=e.tool_calls.map(e=>{let t=pU(()=>{if(e.id){let t=o?.[e.id];if(t)return t}return r?.includes(`gemini-3`)?fU:``});return{functionCall:{name:e.name,args:e.args},...t?{thoughtSignature:t}:{}}})),[...a,...i]}function SU(e,t,n=!1,r){return e.reduce((i,a,o)=>{if(!pt(a))throw Error(`Unsupported message input`);let s=mU(a);if(s===`system`&&o!==0)throw Error(`System message should be the first one`);let c=hU(s),l=i.content[i.content.length];if(!i.mergeWithPreviousContent&&l&&l.role===c)throw Error(`Google Generative AI requires alternate messages between authors`);let u=xU(a,t,e.slice(0,o),r);if(i.mergeWithPreviousContent){let e=i.content[i.content.length-1];if(!e)throw Error(`There was a problem parsing your system message. Please try a prompt without one.`);return e.parts.push(...u),{mergeWithPreviousContent:!1,content:i.content}}let d=c;(d===`function`||d===`system`&&!n)&&(d=`user`);let f={role:d,parts:u};return{mergeWithPreviousContent:s===`system`&&!n,content:[...i.content,f]}},{content:[],mergeWithPreviousContent:!1}).content}function CU(e,t){if(!e.candidates||e.candidates.length===0||!e.candidates[0])return{generations:[],llmOutput:{filters:e.promptFeedback}};let[n]=e.candidates,{content:r,...i}=n,a=r?.parts?.reduce((e,t)=>(`functionCall`in t&&t.functionCall&&e.push({...t,id:`id`in t.functionCall&&typeof t.functionCall.id==`string`?t.functionCall.id:Kn()}),e),[]),o,s=r?.parts;o=Array.isArray(s)&&s.length===1&&`text`in s[0]&&s[0].text&&!s[0].thought?s[0].text:Array.isArray(s)&&s.length>0?s.map(e=>e.thought&&`text`in e&&e.text?{type:`thinking`,thinking:e.text,...e.thoughtSignature?{signature:e.thoughtSignature}:{}}:`text`in e?{type:`text`,text:e.text}:`inlineData`in e?{type:`inlineData`,inlineData:e.inlineData}:`functionCall`in e?{type:`functionCall`,functionCall:e.functionCall}:`functionResponse`in e?{type:`functionResponse`,functionResponse:e.functionResponse}:`fileData`in e?{type:`fileData`,fileData:e.fileData}:`executableCode`in e?{type:`executableCode`,executableCode:e.executableCode}:`codeExecutionResult`in e?{type:`codeExecutionResult`,codeExecutionResult:e.codeExecutionResult}:e):[];let c=a?.reduce((e,t)=>(`thoughtSignature`in t&&typeof t.thoughtSignature==`string`&&(e[t.id]=t.thoughtSignature),e),{}),l=``;return typeof o==`string`?l=o:Array.isArray(o)&&o.length>0&&(l=o.find(e=>`text`in e)?.text??l),{generations:[{text:l,message:new qt({content:o??``,tool_calls:a?.map(e=>({type:`tool_call`,id:e.id,name:e.functionCall.name,args:e.functionCall.args})),additional_kwargs:{...i,[dU]:c},usage_metadata:t?.usageMetadata}),generationInfo:i}],llmOutput:{tokenUsage:{promptTokens:t?.usageMetadata?.input_tokens,completionTokens:t?.usageMetadata?.output_tokens,totalTokens:t?.usageMetadata?.total_tokens}}}}function wU(e,t){if(!e.candidates||e.candidates.length===0)return null;let[n]=e.candidates,{content:r,...i}=n,a=r.parts?.reduce((e,t)=>(`functionCall`in t&&t.functionCall&&e.push({...t,id:`id`in t.functionCall&&typeof t.functionCall.id==`string`?t.functionCall.id:Kn()}),e),[]),o,s=r?.parts;o=Array.isArray(s)&&s.every(e=>`text`in e&&!e.thought)?s.map(e=>e.text).join(``):Array.isArray(s)?s.map(e=>e.thought&&`text`in e&&e.text?{type:`thinking`,thinking:e.text,...e.thoughtSignature?{signature:e.thoughtSignature}:{}}:`text`in e?{type:`text`,text:e.text}:`inlineData`in e?{type:`inlineData`,inlineData:e.inlineData}:`functionCall`in e?{type:`functionCall`,functionCall:e.functionCall}:`functionResponse`in e?{type:`functionResponse`,functionResponse:e.functionResponse}:`fileData`in e?{type:`fileData`,fileData:e.fileData}:`executableCode`in e?{type:`executableCode`,executableCode:e.executableCode}:`codeExecutionResult`in e?{type:`codeExecutionResult`,codeExecutionResult:e.codeExecutionResult}:e):[];let c=``;o&&typeof o==`string`?c=o:Array.isArray(o)&&(c=o.find(e=>`text`in e)?.text??``);let l=[];a&&l.push(...a.map(e=>({type:`tool_call_chunk`,id:e.id,name:e.functionCall.name,args:JSON.stringify(e.functionCall.args)})));let u=a?.reduce((e,t)=>(`thoughtSignature`in t&&typeof t.thoughtSignature==`string`&&(e[t.id]=t.thoughtSignature),e),{});return new Xl({text:c,message:new Xt({content:o||``,name:r?r.role:void 0,tool_call_chunks:l,additional_kwargs:{[dU]:u},response_metadata:{model_provider:`google-genai`},usage_metadata:t.usageMetadata}),generationInfo:i})}function TU(e){return e.every(e=>`functionDeclarations`in e&&Array.isArray(e.functionDeclarations))?e:[{functionDeclarations:e.map(e=>{if(GE(e)){let t=cU(e.schema);return t.type===`object`&&`properties`in t&&Object.keys(t.properties).length===0?{name:e.name,description:e.description}:(uU(t,e.name),{name:e.name,description:e.description,parameters:t})}if(oC(e)){let t=lU(e.function.parameters);return uU(t,e.function.name),{name:e.function.name,description:e.function.description??`A function available to call.`,parameters:t}}return e})}]}function EU(e,t){let n={input_tokens:e?.promptTokenCount??0,output_tokens:e?.candidatesTokenCount??0,total_tokens:e?.totalTokenCount??0};if(e?.cachedContentTokenCount&&(n.input_token_details??={},n.input_token_details.cache_read=e.cachedContentTokenCount),t===`gemini-3-pro-preview`){let t=Math.max(0,e?.promptTokenCount??-2e5),r=Math.max(0,e?.cachedContentTokenCount??-2e5);t&&(n.input_token_details={...n.input_token_details,over_200k:t}),r&&(n.input_token_details={...n.input_token_details,cache_read_over_200k:r})}return n}var DU=class extends fC{static lc_name(){return`GoogleGenerativeAIToolsOutputParser`}lc_namespace=[`langchain`,`google_genai`,`output_parsers`];returnId=!1;keyName;returnSingle=!1;zodSchema;serializableSchema;constructor(e){super(e),this.keyName=e.keyName,this.returnSingle=e.returnSingle??this.returnSingle,this.zodSchema=e.zodSchema,this.serializableSchema=e.serializableSchema}async _validateResult(e){if(this.serializableSchema!==void 0){let t=await this.serializableSchema[`~standard`].validate(e);if(t.issues)throw new mC(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(t.issues)}`,JSON.stringify(e,null,2));return t.value}if(this.zodSchema===void 0)return e;let t=await Im(this.zodSchema,e);if(t.success)return t.data;throw new mC(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(t.error.issues)}`,JSON.stringify(e,null,2))}async parseResult(e){let t=e.flatMap(e=>{let{message:t}=e;return!(`tool_calls`in t)||!Array.isArray(t.tool_calls)?[]:t.tool_calls});if(t[0]===void 0)throw Error(`No parseable tool calls provided to GoogleGenerativeAIToolsOutputParser.`);let[n]=t;return await this._validateResult(n.args)}},OU;(function(e){e.STRING=`string`,e.NUMBER=`number`,e.INTEGER=`integer`,e.BOOLEAN=`boolean`,e.ARRAY=`array`,e.OBJECT=`object`})(OU||={});var kU;(function(e){e.LANGUAGE_UNSPECIFIED=`language_unspecified`,e.PYTHON=`python`})(kU||={});var AU;(function(e){e.OUTCOME_UNSPECIFIED=`outcome_unspecified`,e.OUTCOME_OK=`outcome_ok`,e.OUTCOME_FAILED=`outcome_failed`,e.OUTCOME_DEADLINE_EXCEEDED=`outcome_deadline_exceeded`})(AU||={});var jU=[`user`,`model`,`function`,`system`],MU;(function(e){e.HARM_CATEGORY_UNSPECIFIED=`HARM_CATEGORY_UNSPECIFIED`,e.HARM_CATEGORY_HATE_SPEECH=`HARM_CATEGORY_HATE_SPEECH`,e.HARM_CATEGORY_SEXUALLY_EXPLICIT=`HARM_CATEGORY_SEXUALLY_EXPLICIT`,e.HARM_CATEGORY_HARASSMENT=`HARM_CATEGORY_HARASSMENT`,e.HARM_CATEGORY_DANGEROUS_CONTENT=`HARM_CATEGORY_DANGEROUS_CONTENT`,e.HARM_CATEGORY_CIVIC_INTEGRITY=`HARM_CATEGORY_CIVIC_INTEGRITY`})(MU||={});var NU;(function(e){e.HARM_BLOCK_THRESHOLD_UNSPECIFIED=`HARM_BLOCK_THRESHOLD_UNSPECIFIED`,e.BLOCK_LOW_AND_ABOVE=`BLOCK_LOW_AND_ABOVE`,e.BLOCK_MEDIUM_AND_ABOVE=`BLOCK_MEDIUM_AND_ABOVE`,e.BLOCK_ONLY_HIGH=`BLOCK_ONLY_HIGH`,e.BLOCK_NONE=`BLOCK_NONE`})(NU||={});var PU;(function(e){e.HARM_PROBABILITY_UNSPECIFIED=`HARM_PROBABILITY_UNSPECIFIED`,e.NEGLIGIBLE=`NEGLIGIBLE`,e.LOW=`LOW`,e.MEDIUM=`MEDIUM`,e.HIGH=`HIGH`})(PU||={});var FU;(function(e){e.BLOCKED_REASON_UNSPECIFIED=`BLOCKED_REASON_UNSPECIFIED`,e.SAFETY=`SAFETY`,e.OTHER=`OTHER`})(FU||={});var IU;(function(e){e.FINISH_REASON_UNSPECIFIED=`FINISH_REASON_UNSPECIFIED`,e.STOP=`STOP`,e.MAX_TOKENS=`MAX_TOKENS`,e.SAFETY=`SAFETY`,e.RECITATION=`RECITATION`,e.LANGUAGE=`LANGUAGE`,e.BLOCKLIST=`BLOCKLIST`,e.PROHIBITED_CONTENT=`PROHIBITED_CONTENT`,e.SPII=`SPII`,e.MALFORMED_FUNCTION_CALL=`MALFORMED_FUNCTION_CALL`,e.OTHER=`OTHER`})(IU||={});var LU;(function(e){e.TASK_TYPE_UNSPECIFIED=`TASK_TYPE_UNSPECIFIED`,e.RETRIEVAL_QUERY=`RETRIEVAL_QUERY`,e.RETRIEVAL_DOCUMENT=`RETRIEVAL_DOCUMENT`,e.SEMANTIC_SIMILARITY=`SEMANTIC_SIMILARITY`,e.CLASSIFICATION=`CLASSIFICATION`,e.CLUSTERING=`CLUSTERING`})(LU||={});var RU;(function(e){e.MODE_UNSPECIFIED=`MODE_UNSPECIFIED`,e.AUTO=`AUTO`,e.ANY=`ANY`,e.NONE=`NONE`})(RU||={});var zU;(function(e){e.MODE_UNSPECIFIED=`MODE_UNSPECIFIED`,e.MODE_DYNAMIC=`MODE_DYNAMIC`})(zU||={});var BU=class extends Error{constructor(e){super(`[GoogleGenerativeAI Error]: ${e}`)}},VU=class extends BU{constructor(e,t){super(e),this.response=t}},HU=class extends BU{constructor(e,t,n,r){super(e),this.status=t,this.statusText=n,this.errorDetails=r}},UU=class extends BU{},WU=class extends BU{},GU=`https://generativelanguage.googleapis.com`,KU=`v1beta`,qU=`0.24.1`,JU=`genai-js`,YU;(function(e){e.GENERATE_CONTENT=`generateContent`,e.STREAM_GENERATE_CONTENT=`streamGenerateContent`,e.COUNT_TOKENS=`countTokens`,e.EMBED_CONTENT=`embedContent`,e.BATCH_EMBED_CONTENTS=`batchEmbedContents`})(YU||={});var XU=class{constructor(e,t,n,r,i){this.model=e,this.task=t,this.apiKey=n,this.stream=r,this.requestOptions=i}toString(){let e=this.requestOptions?.apiVersion||KU,t=`${this.requestOptions?.baseUrl||GU}/${e}/${this.model}:${this.task}`;return this.stream&&(t+=`?alt=sse`),t}};function ZU(e){let t=[];return e?.apiClient&&t.push(e.apiClient),t.push(`${JU}/${qU}`),t.join(` `)}async function QU(e){let t=new Headers;t.append(`Content-Type`,`application/json`),t.append(`x-goog-api-client`,ZU(e.requestOptions)),t.append(`x-goog-api-key`,e.apiKey);let n=e.requestOptions?.customHeaders;if(n){if(!(n instanceof Headers))try{n=new Headers(n)}catch(e){throw new UU(`unable to convert customHeaders value ${JSON.stringify(n)} to Headers: ${e.message}`)}for(let[e,r]of n.entries()){if(e===`x-goog-api-key`)throw new UU(`Cannot set reserved header name ${e}`);if(e===`x-goog-api-client`)throw new UU(`Header name ${e} can only be set using the apiClient field`);t.append(e,r)}}return t}async function $U(e,t,n,r,i,a){let o=new XU(e,t,n,r,a);return{url:o.toString(),fetchOptions:Object.assign(Object.assign({},iW(a)),{method:`POST`,headers:await QU(o),body:i})}}async function eW(e,t,n,r,i,a={},o=fetch){let{url:s,fetchOptions:c}=await $U(e,t,n,r,i,a);return tW(s,c,o)}async function tW(e,t,n=fetch){let r;try{r=await n(e,t)}catch(t){nW(t,e)}return r.ok||await rW(r,e),r}function nW(e,t){let n=e;throw n.name===`AbortError`?(n=new WU(`Request aborted when fetching ${t.toString()}: ${e.message}`),n.stack=e.stack):e instanceof HU||e instanceof UU||(n=new BU(`Error fetching from ${t.toString()}: ${e.message}`),n.stack=e.stack),n}async function rW(e,t){let n=``,r;try{let t=await e.json();n=t.error.message,t.error.details&&(n+=` ${JSON.stringify(t.error.details)}`,r=t.error.details)}catch{}throw new HU(`Error fetching from ${t.toString()}: [${e.status} ${e.statusText}] ${n}`,e.status,e.statusText,r)}function iW(e){let t={};if(e?.signal!==void 0||e?.timeout>=0){let n=new AbortController;e?.timeout>=0&&setTimeout(()=>n.abort(),e.timeout),e?.signal&&e.signal.addEventListener(`abort`,()=>{n.abort()}),t.signal=n.signal}return t}function aW(e){return e.text=()=>{if(e.candidates&&e.candidates.length>0){if(e.candidates.length>1&&console.warn(`This response had ${e.candidates.length} candidates. Returning text from the first candidate only. Access response.candidates directly to use the other candidates.`),lW(e.candidates[0]))throw new VU(`${uW(e)}`,e);return oW(e)}else if(e.promptFeedback)throw new VU(`Text not available. ${uW(e)}`,e);return``},e.functionCall=()=>{if(e.candidates&&e.candidates.length>0){if(e.candidates.length>1&&console.warn(`This response had ${e.candidates.length} candidates. Returning function calls from the first candidate only. Access response.candidates directly to use the other candidates.`),lW(e.candidates[0]))throw new VU(`${uW(e)}`,e);return console.warn(`response.functionCall() is deprecated. Use response.functionCalls() instead.`),sW(e)[0]}else if(e.promptFeedback)throw new VU(`Function call not available. ${uW(e)}`,e)},e.functionCalls=()=>{if(e.candidates&&e.candidates.length>0){if(e.candidates.length>1&&console.warn(`This response had ${e.candidates.length} candidates. Returning function calls from the first candidate only. Access response.candidates directly to use the other candidates.`),lW(e.candidates[0]))throw new VU(`${uW(e)}`,e);return sW(e)}else if(e.promptFeedback)throw new VU(`Function call not available. ${uW(e)}`,e)},e}function oW(e){let t=[];if(e.candidates?.[0].content?.parts)for(let n of e.candidates?.[0].content?.parts)n.text&&t.push(n.text),n.executableCode&&t.push("\n```"+n.executableCode.language+`
173
- `+n.executableCode.code+"\n```\n"),n.codeExecutionResult&&t.push("\n```\n"+n.codeExecutionResult.output+"\n```\n");return t.length>0?t.join(``):``}function sW(e){let t=[];if(e.candidates?.[0].content?.parts)for(let n of e.candidates?.[0].content?.parts)n.functionCall&&t.push(n.functionCall);if(t.length>0)return t}var cW=[IU.RECITATION,IU.SAFETY,IU.LANGUAGE];function lW(e){return!!e.finishReason&&cW.includes(e.finishReason)}function uW(e){let t=``;if((!e.candidates||e.candidates.length===0)&&e.promptFeedback)t+=`Response was blocked`,e.promptFeedback?.blockReason&&(t+=` due to ${e.promptFeedback.blockReason}`),e.promptFeedback?.blockReasonMessage&&(t+=`: ${e.promptFeedback.blockReasonMessage}`);else if(e.candidates?.[0]){let n=e.candidates[0];lW(n)&&(t+=`Candidate was blocked due to ${n.finishReason}`,n.finishMessage&&(t+=`: ${n.finishMessage}`))}return t}function dW(e){return this instanceof dW?(this.v=e,this):new dW(e)}function fW(e,t,n){if(!Symbol.asyncIterator)throw TypeError(`Symbol.asyncIterator is not defined.`);var r=n.apply(e,t||[]),i,a=[];return i={},o(`next`),o(`throw`),o(`return`),i[Symbol.asyncIterator]=function(){return this},i;function o(e){r[e]&&(i[e]=function(t){return new Promise(function(n,r){a.push([e,t,n,r])>1||s(e,t)})})}function s(e,t){try{c(r[e](t))}catch(e){d(a[0][3],e)}}function c(e){e.value instanceof dW?Promise.resolve(e.value.v).then(l,u):d(a[0][2],e)}function l(e){s(`next`,e)}function u(e){s(`throw`,e)}function d(e,t){e(t),a.shift(),a.length&&s(a[0][0],a[0][1])}}var pW=/^data\: (.*)(?:\n\n|\r\r|\r\n\r\n)/;function mW(e){let[t,n]=_W(e.body.pipeThrough(new TextDecoderStream(`utf8`,{fatal:!0}))).tee();return{stream:gW(t),response:hW(n)}}async function hW(e){let t=[],n=e.getReader();for(;;){let{done:e,value:r}=await n.read();if(e)return aW(vW(t));t.push(r)}}function gW(e){return fW(this,arguments,function*(){let t=e.getReader();for(;;){let{value:e,done:n}=yield dW(t.read());if(n)break;yield yield dW(aW(e))}})}function _W(e){let t=e.getReader();return new ReadableStream({start(e){let n=``;return r();function r(){return t.read().then(({value:t,done:i})=>{if(i){if(n.trim()){e.error(new BU(`Failed to parse stream`));return}e.close();return}n+=t;let a=n.match(pW),o;for(;a;){try{o=JSON.parse(a[1])}catch{e.error(new BU(`Error parsing JSON response: "${a[1]}"`));return}e.enqueue(o),n=n.substring(a[0].length),a=n.match(pW)}return r()}).catch(e=>{let t=e;throw t.stack=e.stack,t=t.name===`AbortError`?new WU(`Request aborted when reading from the stream`):new BU(`Error reading from the stream`),t})}}})}function vW(e){let t={promptFeedback:e[e.length-1]?.promptFeedback};for(let n of e){if(n.candidates){let e=0;for(let r of n.candidates)if(t.candidates||=[],t.candidates[e]||(t.candidates[e]={index:e}),t.candidates[e].citationMetadata=r.citationMetadata,t.candidates[e].groundingMetadata=r.groundingMetadata,t.candidates[e].finishReason=r.finishReason,t.candidates[e].finishMessage=r.finishMessage,t.candidates[e].safetyRatings=r.safetyRatings,r.content&&r.content.parts){t.candidates[e].content||(t.candidates[e].content={role:r.content.role||`user`,parts:[]});let n={};for(let i of r.content.parts)i.text&&(n.text=i.text),i.functionCall&&(n.functionCall=i.functionCall),i.executableCode&&(n.executableCode=i.executableCode),i.codeExecutionResult&&(n.codeExecutionResult=i.codeExecutionResult),Object.keys(n).length===0&&(n.text=``),t.candidates[e].content.parts.push(n)}e++}n.usageMetadata&&(t.usageMetadata=n.usageMetadata)}return t}async function yW(e,t,n,r){return mW(await eW(t,YU.STREAM_GENERATE_CONTENT,e,!0,JSON.stringify(n),r))}async function bW(e,t,n,r){return{response:aW(await(await eW(t,YU.GENERATE_CONTENT,e,!1,JSON.stringify(n),r)).json())}}function xW(e){if(e!=null){if(typeof e==`string`)return{role:`system`,parts:[{text:e}]};if(e.text)return{role:`system`,parts:[e]};if(e.parts)return e.role?e:{role:`system`,parts:e.parts}}}function SW(e){let t=[];if(typeof e==`string`)t=[{text:e}];else for(let n of e)typeof n==`string`?t.push({text:n}):t.push(n);return CW(t)}function CW(e){let t={role:`user`,parts:[]},n={role:`function`,parts:[]},r=!1,i=!1;for(let a of e)`functionResponse`in a?(n.parts.push(a),i=!0):(t.parts.push(a),r=!0);if(r&&i)throw new BU(`Within a single message, FunctionResponse cannot be mixed with other type of part in the request for sending chat message.`);if(!r&&!i)throw new BU(`No content is provided for sending chat message.`);return r?t:n}function wW(e,t){let n={model:t?.model,generationConfig:t?.generationConfig,safetySettings:t?.safetySettings,tools:t?.tools,toolConfig:t?.toolConfig,systemInstruction:t?.systemInstruction,cachedContent:t?.cachedContent?.name,contents:[]},r=e.generateContentRequest!=null;if(e.contents){if(r)throw new UU(`CountTokensRequest must have one of contents or generateContentRequest, not both.`);n.contents=e.contents}else if(r)n=Object.assign(Object.assign({},n),e.generateContentRequest);else{let t=SW(e);n.contents=[t]}return{generateContentRequest:n}}function TW(e){let t;return t=e.contents?e:{contents:[SW(e)]},e.systemInstruction&&(t.systemInstruction=xW(e.systemInstruction)),t}function EW(e){return typeof e==`string`||Array.isArray(e)?{content:SW(e)}:e}var DW=[`text`,`inlineData`,`functionCall`,`functionResponse`,`executableCode`,`codeExecutionResult`],OW={user:[`text`,`inlineData`],function:[`functionResponse`],model:[`text`,`functionCall`,`executableCode`,`codeExecutionResult`],system:[`text`]};function kW(e){let t=!1;for(let n of e){let{role:e,parts:r}=n;if(!t&&e!==`user`)throw new BU(`First content should be with role 'user', got ${e}`);if(!jU.includes(e))throw new BU(`Each item should include role field. Got ${e} but valid roles are: ${JSON.stringify(jU)}`);if(!Array.isArray(r))throw new BU(`Content should have 'parts' property with an array of Parts`);if(r.length===0)throw new BU(`Each Content should have at least one part`);let i={text:0,inlineData:0,functionCall:0,functionResponse:0,fileData:0,executableCode:0,codeExecutionResult:0};for(let e of r)for(let t of DW)t in e&&(i[t]+=1);let a=OW[e];for(let t of DW)if(!a.includes(t)&&i[t]>0)throw new BU(`Content with role '${e}' can't contain '${t}' part`);t=!0}}function AW(e){if(e.candidates===void 0||e.candidates.length===0)return!1;let t=e.candidates[0]?.content;if(t===void 0||t.parts===void 0||t.parts.length===0)return!1;for(let e of t.parts)if(e===void 0||Object.keys(e).length===0||e.text!==void 0&&e.text===``)return!1;return!0}var jW=`SILENT_ERROR`,MW=class{constructor(e,t,n,r={}){this.model=t,this.params=n,this._requestOptions=r,this._history=[],this._sendPromise=Promise.resolve(),this._apiKey=e,n?.history&&(kW(n.history),this._history=n.history)}async getHistory(){return await this._sendPromise,this._history}async sendMessage(e,t={}){await this._sendPromise;let n=SW(e),r={safetySettings:this.params?.safetySettings,generationConfig:this.params?.generationConfig,tools:this.params?.tools,toolConfig:this.params?.toolConfig,systemInstruction:this.params?.systemInstruction,cachedContent:this.params?.cachedContent,contents:[...this._history,n]},i=Object.assign(Object.assign({},this._requestOptions),t),a;return this._sendPromise=this._sendPromise.then(()=>bW(this._apiKey,this.model,r,i)).then(e=>{if(AW(e.response)){this._history.push(n);let t=Object.assign({parts:[],role:`model`},e.response.candidates?.[0].content);this._history.push(t)}else{let t=uW(e.response);t&&console.warn(`sendMessage() was unsuccessful. ${t}. Inspect response object for details.`)}a=e}).catch(e=>{throw this._sendPromise=Promise.resolve(),e}),await this._sendPromise,a}async sendMessageStream(e,t={}){await this._sendPromise;let n=SW(e),r={safetySettings:this.params?.safetySettings,generationConfig:this.params?.generationConfig,tools:this.params?.tools,toolConfig:this.params?.toolConfig,systemInstruction:this.params?.systemInstruction,cachedContent:this.params?.cachedContent,contents:[...this._history,n]},i=Object.assign(Object.assign({},this._requestOptions),t),a=yW(this._apiKey,this.model,r,i);return this._sendPromise=this._sendPromise.then(()=>a).catch(e=>{throw Error(jW)}).then(e=>e.response).then(e=>{if(AW(e)){this._history.push(n);let t=Object.assign({},e.candidates[0].content);t.role||=`model`,this._history.push(t)}else{let t=uW(e);t&&console.warn(`sendMessageStream() was unsuccessful. ${t}. Inspect response object for details.`)}}).catch(e=>{e.message!==jW&&console.error(e)}),a}};async function NW(e,t,n,r){return(await eW(t,YU.COUNT_TOKENS,e,!1,JSON.stringify(n),r)).json()}async function PW(e,t,n,r){return(await eW(t,YU.EMBED_CONTENT,e,!1,JSON.stringify(n),r)).json()}async function FW(e,t,n,r){let i=n.requests.map(e=>Object.assign(Object.assign({},e),{model:t}));return(await eW(t,YU.BATCH_EMBED_CONTENTS,e,!1,JSON.stringify({requests:i}),r)).json()}var IW=class{constructor(e,t,n={}){this.apiKey=e,this._requestOptions=n,t.model.includes(`/`)?this.model=t.model:this.model=`models/${t.model}`,this.generationConfig=t.generationConfig||{},this.safetySettings=t.safetySettings||[],this.tools=t.tools,this.toolConfig=t.toolConfig,this.systemInstruction=xW(t.systemInstruction),this.cachedContent=t.cachedContent}async generateContent(e,t={}){let n=TW(e),r=Object.assign(Object.assign({},this._requestOptions),t);return bW(this.apiKey,this.model,Object.assign({generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:this.cachedContent?.name},n),r)}async generateContentStream(e,t={}){let n=TW(e),r=Object.assign(Object.assign({},this._requestOptions),t);return yW(this.apiKey,this.model,Object.assign({generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:this.cachedContent?.name},n),r)}startChat(e){return new MW(this.apiKey,this.model,Object.assign({generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:this.cachedContent?.name},e),this._requestOptions)}async countTokens(e,t={}){let n=wW(e,{model:this.model,generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:this.cachedContent}),r=Object.assign(Object.assign({},this._requestOptions),t);return NW(this.apiKey,this.model,n,r)}async embedContent(e,t={}){let n=EW(e),r=Object.assign(Object.assign({},this._requestOptions),t);return PW(this.apiKey,this.model,n,r)}async batchEmbedContents(e,t={}){let n=Object.assign(Object.assign({},this._requestOptions),t);return FW(this.apiKey,this.model,e,n)}},LW=class{constructor(e){this.apiKey=e}getGenerativeModel(e,t){if(!e.model)throw new BU(`Must provide a model name. Example: genai.getGenerativeModel({ model: 'my-model-name' })`);return new IW(this.apiKey,e,t)}getGenerativeModelFromCachedContent(e,t,n){if(!e.name)throw new UU("Cached content must contain a `name` field.");if(!e.model)throw new UU("Cached content must contain a `model` field.");for(let n of[`model`,`systemInstruction`])if(t?.[n]&&e[n]&&t?.[n]!==e[n]){if(n===`model`&&(t.model.startsWith(`models/`)?t.model.replace(`models/`,``):t.model)===(e.model.startsWith(`models/`)?e.model.replace(`models/`,``):e.model))continue;throw new UU(`Different value for "${n}" specified in modelParams (${t[n]}) and cachedContent (${e[n]})`)}let r=Object.assign(Object.assign({},t),{model:e.model,tools:e.tools,toolConfig:e.toolConfig,systemInstruction:e.systemInstruction,cachedContent:e});return new IW(this.apiKey,r,n)}};function RW(e,t){let n=zW(e);return{tools:n,toolConfig:VW(n,t)}}function zW(e){let t=[],n=[];return e.forEach(e=>{if(GE(e)){let[n]=TU([e]);n.functionDeclarations&&t.push(...n.functionDeclarations)}else if(oC(e)){let{functionDeclarations:n}=BW(e);if(n)t.push(...n);else throw Error(`Failed to convert OpenAI structured tool to GenerativeAI tool`)}else n.push(e)}),n.find(e=>`functionDeclarations`in e)?n.map(e=>{if(t?.length>0&&`functionDeclarations`in e){let n={functionDeclarations:[...e.functionDeclarations||[],...t]};return t=[],n}return e}):[...n,...t.length>0?[{functionDeclarations:t}]:[]]}function BW(e){return{functionDeclarations:[{name:e.function.name,description:e.function.description,parameters:sU(e.function.parameters)}]}}function VW(e,t){if(!e.length||!t)return;let{toolChoice:n,allowedFunctionNames:r}=t,i={any:RU.ANY,auto:RU.AUTO,none:RU.NONE};if(n&&[`any`,`auto`,`none`].includes(n))return{functionCallingConfig:{mode:i[n]??`MODE_UNSPECIFIED`,allowedFunctionNames:r}};if(typeof n==`string`||r)return{functionCallingConfig:{mode:RU.ANY,allowedFunctionNames:[...r??[],...n&&typeof n==`string`?[n]:[]]}}}var HW={"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}},UW=class extends xw{static lc_name(){return`ChatGoogleGenerativeAI`}lc_serializable=!0;get lc_secrets(){return{apiKey:`GOOGLE_API_KEY`}}lc_namespace=[`langchain`,`chat_models`,`google_genai`];get lc_aliases(){return{apiKey:`google_api_key`}}model;temperature;maxOutputTokens;topP;topK;stopSequences=[];safetySettings;apiKey;streaming=!1;json;streamUsage=!0;convertSystemMessageToHumanContent;thinkingConfig;client;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`)}constructor(e,t){let n=typeof e==`string`?{...t??{},model:e}:e;if(super(n),this._addVersion(`@langchain/google-genai`,`2.1.30`),this.model=n.model.replace(/^models\//,``),this.maxOutputTokens=n.maxOutputTokens??this.maxOutputTokens,this.maxOutputTokens&&this.maxOutputTokens<0)throw Error("`maxOutputTokens` must be a positive integer");if(this.temperature=n.temperature??this.temperature,this.temperature&&(this.temperature<0||this.temperature>2))throw Error("`temperature` must be in the range of [0.0,2.0]");if(this.topP=n.topP??this.topP,this.topP&&this.topP<0)throw Error("`topP` must be a positive integer");if(this.topP&&this.topP>1)throw Error("`topP` must be below 1.");if(this.topK=n.topK??this.topK,this.topK&&this.topK<0)throw Error("`topK` must be a positive integer");if(this.stopSequences=n.stopSequences??this.stopSequences,this.apiKey=n.apiKey??pr(`GOOGLE_API_KEY`),!this.apiKey)throw 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=n.safetySettings??this.safetySettings,this.safetySettings&&this.safetySettings.length>0&&new Set(this.safetySettings.map(e=>e.category)).size!==this.safetySettings.length)throw Error("The categories in `safetySettings` array must be unique");this.streaming=n.streaming??this.streaming,this.json=n.json,this.thinkingConfig=n.thinkingConfig??this.thinkingConfig,this.client=new LW(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:n.apiVersion,baseUrl:n.baseUrl,customHeaders:n.customHeaders}),this.streamUsage=n.streamUsage??this.streamUsage}useCachedContent(e,t,n){this.apiKey&&(this.client=new LW(this.apiKey).getGenerativeModelFromCachedContent(e,t,n))}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,t){return this.withConfig({tools:RW(e)?.tools,...t})}invocationParams(e){let t=e?.tools?.length?RW(e.tools,{toolChoice:e.tool_choice,allowedFunctionNames:e.allowedFunctionNames}):void 0;return 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),{...t?.tools?{tools:t.tools}:{},...t?.toolConfig?{toolConfig:t.toolConfig}:{}}}async _generate(e,t,n){t.signal?.throwIfAborted();let r=SU(e,this._isMultimodalModel,this.useSystemInstruction,this.model),i=r;if(r[0].role===`system`){let[e]=r;this.client.systemInstruction=e,i=r.slice(1)}let a=this.invocationParams(t);if(this.streaming){let r={},i=this._streamResponseChunks(e,t,n),a=[];for await(let e of i){let t=e.generationInfo?.completion??0;a[t]===void 0?a[t]=e:a[t]=a[t].concat(e)}return{generations:a.filter(e=>e!==void 0),llmOutput:{estimatedTokenUsage:r}}}let o=await this.completionWithRetry({...a,contents:i}),s;`usageMetadata`in o.response&&(s=EU(o.response.usageMetadata,this.model));let c=CU(o.response,{usageMetadata:s});return c.generations?.length>0&&await n?.handleLLMNewToken(c.generations[0]?.text??``),c}async*_streamResponseChunks(e,t,n){let r=SU(e,this._isMultimodalModel,this.useSystemInstruction,this.model),i=r;if(r[0].role===`system`){let[e]=r;this.client.systemInstruction=e,i=r.slice(1)}let a={...this.invocationParams(t),contents:i},o=await this.caller.callWithOptions({signal:t?.signal},async()=>{let{stream:e}=await this.client.generateContentStream(a,{signal:t?.signal});return e}),s,c=0,l=0,u=0,d=0;for await(let e of o){if(t.signal?.aborted)return;if(`usageMetadata`in e&&e.usageMetadata!==void 0&&this.streamUsage!==!1&&t.streamUsage!==!1){s=EU(e.usageMetadata,this.model);let t=e.usageMetadata.promptTokenCount??0;s.input_tokens=Math.max(0,t-c),c=t;let n=e.usageMetadata.candidatesTokenCount??0;s.output_tokens=Math.max(0,n-l),l=n;let r=e.usageMetadata.totalTokenCount??0;s.total_tokens=Math.max(0,r-u),u=r}let r=wU(e,{usageMetadata:s,index:d});d+=1,r&&(yield r,await n?.handleLLMNewToken(r.text??``))}}async completionWithRetry(e,t){return this.caller.callWithOptions({signal:t?.signal},async()=>{try{return await this.client.generateContent(e,{signal:t?.signal})}catch(e){throw e.message?.includes(`400 Bad Request`)&&(e.status=400),e}})}get profile(){return HW[this.model]??{}}withStructuredOutput(e,t){let n=e,r=t?.name,i=t?.method,a=t?.includeRaw;if(i===`jsonMode`)throw Error(`ChatGoogleGenerativeAI only supports "jsonSchema" or "functionCalling" as a method.`);let o,s;if(i===`functionCalling`){let e=r??`extract`,t;if(Mm(n)||$_(n)){let r=cU(n);t={name:e,description:r.description??`A function available to call.`,parameters:r}}else typeof n.name==`string`&&typeof n.parameters==`object`&&n.parameters!=null?(t=n,t.parameters=sU(n.parameters),e=n.name):t={name:e,description:n.description??``,parameters:sU(n)};let i=[{functionDeclarations:[t]}];o=this.bindTools(i).withConfig({allowedFunctionNames:[e]}),s=WC(n,e,DU)}else{let e=cU(n);o=this.withConfig({responseSchema:e}),s=UC(n)}return GC(o,s,a,a?`StructuredOutputRunnable`:`ChatGoogleGenerativeAIStructuredOutput`)}},WW=class extends fC{static lc_name(){return`AnthropicToolsOutputParser`}lc_namespace=[`langchain`,`anthropic`,`output_parsers`];returnId=!1;keyName;returnSingle=!1;zodSchema;serializableSchema;constructor(e){super(e),this.keyName=e.keyName,this.returnSingle=e.returnSingle??this.returnSingle,this.zodSchema=e.zodSchema,this.serializableSchema=e.serializableSchema}async _validateResult(e){let t=e;if(typeof e==`string`)try{t=JSON.parse(e)}catch(t){throw new mC(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(t.message)}`,e)}else t=e;if(this.serializableSchema!==void 0){let e=await this.serializableSchema[`~standard`].validate(t);if(e.issues)throw new mC(`Failed to parse. Text: "${JSON.stringify(t,null,2)}". Error: ${JSON.stringify(e.issues)}`,JSON.stringify(t,null,2));return e.value}if(this.zodSchema===void 0)return t;let n=await Im(this.zodSchema,t);if(n.success)return n.data;throw new mC(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(n.error.issues)}`,JSON.stringify(t,null,2))}async parseResult(e){let t=e.flatMap(e=>{let{message:t}=e;return Array.isArray(t.content)?GW(t.content)[0]:[]});if(t[0]===void 0)throw Error(`No parseable tool calls provided to AnthropicToolsOutputParser.`);let[n]=t;return await this._validateResult(n.args)}};function GW(e){let t=[];for(let n of e)n.type===`tool_use`&&t.push({name:n.name,args:n.input,id:n.id,type:`tool_call`});return t}function KW(e){if(e)return e===`any`||e===`required`?{type:`any`}:e===`auto`?{type:`auto`}:e===`none`?{type:`none`}:typeof e==`string`?{type:`tool`,name:e}:e}var qW=V({cache_control:TO().optional().nullable(),defer_loading:FD().optional(),input_examples:UD(zD()).optional(),allowed_callers:UD(zD()).optional()}),JW={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 YW(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`thinking`}function XW(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`redacted_thinking`}function ZW(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`compaction`}function QW(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`search_result`}function $W(e){return typeof e!=`object`||!e||!(`type`in e)||e.type!==`image`||!(`source`in e)||typeof e.source!=`object`||e.source==null||!(`type`in e.source)?!1:e.source.type===`base64`?!(!(`media_type`in e.source)||typeof e.source.media_type!=`string`||!(`data`in e.source)||typeof e.source.data!=`string`):e.source.type===`url`?!(!(`url`in e.source)||typeof e.source.url!=`string`):!1}var eG={providerName:`anthropic`,fromStandardTextBlock(e){return{type:`text`,text:e.text,...`citations`in(e.metadata??{})?{citations:e.metadata.citations}:{},...`cache_control`in(e.metadata??{})?{cache_control:e.metadata.cache_control}:{}}},fromStandardImageBlock(e){if(e.source_type===`url`){let t=we({dataUrl:e.url,asTypedArray:!1});return t?{type:`image`,source:{type:`base64`,data:t.data,media_type:t.mime_type},...`cache_control`in(e.metadata??{})?{cache_control:e.metadata.cache_control}:{}}:{type:`image`,source:{type:`url`,url:e.url},...`cache_control`in(e.metadata??{})?{cache_control:e.metadata.cache_control}:{}}}else if(e.source_type===`base64`)return{type:`image`,source:{type:`base64`,data:e.data,media_type:e.mime_type??``},...`cache_control`in(e.metadata??{})?{cache_control:e.metadata.cache_control}:{}};else throw Error(`Unsupported image source type: ${e.source_type}`)},fromStandardFileBlock(e){let t=(e.mime_type??``).split(`;`)[0];if(e.source_type===`url`){if(t===`application/pdf`||t===``)return{type:`document`,source:{type:`url`,url:e.url},...`cache_control`in(e.metadata??{})?{cache_control:e.metadata.cache_control}:{},...`citations`in(e.metadata??{})?{citations:e.metadata.citations}:{},...`context`in(e.metadata??{})?{context:e.metadata.context}:{},...`title`in(e.metadata??{})?{title:e.metadata.title}:{}};throw Error(`Unsupported file mime type for file url source: ${e.mime_type}`)}else if(e.source_type===`text`){if(t===`text/plain`||t===``)return{type:`document`,source:{type:`text`,data:e.text,media_type:e.mime_type??``},...`cache_control`in(e.metadata??{})?{cache_control:e.metadata.cache_control}:{},...`citations`in(e.metadata??{})?{citations:e.metadata.citations}:{},...`context`in(e.metadata??{})?{context:e.metadata.context}:{},...`title`in(e.metadata??{})?{title:e.metadata.title}:{}};throw Error(`Unsupported file mime type for file text source: ${e.mime_type}`)}else if(e.source_type===`base64`){if(t===`application/pdf`||t===``)return{type:`document`,source:{type:`base64`,data:e.data,media_type:`application/pdf`},...`cache_control`in(e.metadata??{})?{cache_control:e.metadata.cache_control}:{},...`citations`in(e.metadata??{})?{citations:e.metadata.citations}:{},...`context`in(e.metadata??{})?{context:e.metadata.context}:{},...`title`in(e.metadata??{})?{title:e.metadata.title}:{}};if([`image/jpeg`,`image/png`,`image/gif`,`image/webp`].includes(t))return{type:`document`,source:{type:`content`,content:[{type:`image`,source:{type:`base64`,data:e.data,media_type:t}}]},...`cache_control`in(e.metadata??{})?{cache_control:e.metadata.cache_control}:{},...`citations`in(e.metadata??{})?{citations:e.metadata.citations}:{},...`context`in(e.metadata??{})?{context:e.metadata.context}:{},...`title`in(e.metadata??{})?{title:e.metadata.title}:{}};throw Error(`Unsupported file mime type for file base64 source: ${e.mime_type}`)}else throw Error(`Unsupported file source type: ${e.source_type}`)}},tG=e=>e();function nG(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`citation`}function rG(e){function*t(){for(let t of e)nG(t)&&(t.source===`char`?yield{type:`char_location`,file_id:t.url??``,start_char_index:t.startIndex??0,end_char_index:t.endIndex??0,document_title:t.title??null,document_index:0,cited_text:t.citedText??``}:t.source===`page`?yield{type:`page_location`,file_id:t.url??``,start_page_number:t.startIndex??0,end_page_number:t.endIndex??0,document_title:t.title??null,document_index:0,cited_text:t.citedText??``}:t.source===`block`?yield{type:`content_block_location`,file_id:t.url??``,start_block_index:t.startIndex??0,end_block_index:t.endIndex??0,document_title:t.title??null,document_index:0,cited_text:t.citedText??``}:t.source===`url`?yield{type:`web_search_result_location`,url:t.url??``,title:t.title??null,encrypted_index:String(t.startIndex??0),cited_text:t.citedText??``}:t.source===`search`&&(yield{type:`search_result_location`,title:t.title??null,start_block_index:t.startIndex??0,end_block_index:t.endIndex??0,search_result_index:0,source:t.source??``,cited_text:t.citedText??``}))}return Array.from(t())}function iG(e){return typeof e==`string`?e:aG(e)}function aG(e){let t=[];for(let n=0,{length:r}=e;n<r;n++)t.push(String.fromCharCode(e[n]));return btoa(t.join(``))}function oG(e){return(e??``).split(`;`)[0].toLowerCase()}function sG(e,t){if(typeof e==`object`&&e&&t in e)return e[t]}function cG(e,t){let n=sG(t,`cache_control`);n!==void 0&&(e.cache_control=n);let r=sG(t,`citations`);r!==void 0&&(e.citations=r);let i=sG(t,`context`);i!==void 0&&(e.context=i);let a=sG(t,`title`);return a!==void 0&&(e.title=a),e}function lG(e,t){let n=sG(t,`cache_control`);return n!==void 0&&(e.cache_control=n),e}function uG(e){return new Set([`image/jpeg`,`image/png`,`image/gif`,`image/webp`]).has(e)}function dG(e){let t=[],n=e.response_metadata,r=`model_provider`in n&&n?.model_provider===`anthropic`;for(let n of e.contentBlocks)if(n.type===`text`)n.annotations?t.push({type:`text`,text:n.text,citations:rG(n.annotations)}):t.push({type:`text`,text:n.text});else if(n.type===`tool_call`)t.push({type:`tool_use`,id:n.id??``,name:n.name,input:n.args});else if(n.type===`tool_call_chunk`){let e=tG(()=>{if(typeof n.args!=`string`)return n.args;try{return JSON.parse(n.args)}catch{return{}}});t.push({type:`tool_use`,id:n.id??``,name:n.name??``,input:e})}else if(n.type===`reasoning`&&r)t.push({type:`thinking`,thinking:n.reasoning,signature:String(n.signature)});else if(n.type===`server_tool_call`&&r)(n.name===`web_search`||n.name===`code_execution`)&&t.push({type:`server_tool_use`,name:n.name,id:n.id??``,input:n.args});else if(n.type===`server_tool_call_result`&&r)if(n.name===`web_search`&&Array.isArray(n.output.urls)){let e=n.output.urls.map(e=>({type:`web_search_result`,title:``,encrypted_content:``,url:e}));t.push({type:`web_search_tool_result`,tool_use_id:n.toolCallId??``,content:e})}else n.name===`code_execution`?t.push({type:`code_execution_tool_result`,tool_use_id:n.toolCallId??``,content:n.output}):n.name===`mcp_tool_result`&&t.push({type:`mcp_tool_result`,tool_use_id:n.toolCallId??``,content:n.output});else if(n.type===`audio`)throw Error(`Anthropic does not support audio content blocks.`);else if(n.type===`file`){let e=n.metadata;if(n.fileId){t.push(cG({type:`document`,source:{type:`file`,file_id:n.fileId}},e));continue}if(n.url){let r=oG(n.mimeType);if(r===`application/pdf`||r===``){t.push(cG({type:`document`,source:{type:`url`,url:n.url}},e));continue}}if(n.data){let r=oG(n.mimeType);if(r===``||r===`application/pdf`)t.push(cG({type:`document`,source:{type:`base64`,data:iG(n.data),media_type:`application/pdf`}},e));else if(r===`text/plain`)t.push(cG({type:`document`,source:{type:`text`,data:iG(n.data),media_type:`text/plain`}},e));else if(uG(r))t.push(cG({type:`document`,source:{type:`content`,content:[{type:`image`,source:{type:`base64`,data:iG(n.data),media_type:r}}]}},e));else throw Error(`Unsupported file mime type for Anthropic base64 source: ${r}`);continue}throw Error(`File content block must include a fileId, url, or data property.`)}else if(n.type===`image`){let e=n.metadata;if(n.fileId){t.push(lG({type:`image`,source:{type:`file`,file_id:n.fileId}},e));continue}if(n.url){t.push(lG({type:`image`,source:{type:`url`,url:n.url}},e));continue}if(n.data){let r=oG(n.mimeType)||`image/png`;uG(r)&&t.push(lG({type:`image`,source:{type:`base64`,data:iG(n.data),media_type:r}},e));continue}throw Error(`Image content block must include a fileId, url, or data property.`)}else n.type===`video`||(n.type===`text-plain`?n.data&&t.push(cG({type:`document`,source:{type:`text`,data:iG(n.data),media_type:`text/plain`}},n.metadata)):n.type===`non_standard`&&r&&t.push(n.value));return t}function fG(e){let t=we({dataUrl:e});if(t)return{type:`base64`,media_type:t.mime_type,data:t.data};let n;try{n=new URL(e)}catch{throw Error([`Malformed image URL: ${JSON.stringify(e)}. 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(`
174
-
175
- `))}if(n.protocol===`http:`||n.protocol===`https:`)return{type:`url`,url:e};throw 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(`
176
-
177
- `))}function pG(e){let t=[];for(let n of e)if(n._getType()===`tool`)if(typeof n.content==`string`){let e=t[t.length-1];e?._getType()===`human`&&Array.isArray(e.content)&&`type`in e.content[0]&&e.content[0].type===`tool_result`?e.content.push({type:`tool_result`,content:n.content,tool_use_id:n.tool_call_id}):t.push(new on({content:[{type:`tool_result`,content:n.content,tool_use_id:n.tool_call_id}]}))}else t.push(new on({content:[{type:`tool_result`,...n.content==null?{}:{content:gG(n)},tool_use_id:n.tool_call_id}]}));else t.push(n);return t}function mG(e){if(e.id===void 0)throw Error(`Anthropic requires all tool calls to have an "id".`);return{type:`tool_use`,id:e.id,name:e.name,input:e.args}}function*hG(e,t){let 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(let i of e){_e(i)&&(yield Te(i,eG));let a=`cache_control`in i?i.cache_control:void 0;if(i.type===`image_url`){let e;typeof i.image_url==`string`?e=fG(i.image_url):typeof i.image_url==`object`&&i.image_url!==null&&`url`in i.image_url&&typeof i.image_url.url==`string`&&(e=fG(i.image_url.url)),e&&(yield{type:`image`,source:e,...a?{cache_control:a}:{}})}else if($W(i))yield i;else if(i.type===`image`){let e;`url`in i&&typeof i.url==`string`?e=fG(i.url):`data`in i&&(typeof i.data==`string`||i.data instanceof Uint8Array)?e={type:`base64`,media_type:`mimeType`in i&&typeof i.mimeType==`string`?i.mimeType:`image/jpeg`,data:typeof i.data==`string`?i.data:Buffer.from(i.data).toString(`base64`)}:`fileId`in i&&typeof i.fileId==`string`&&(e={type:`file`,file_id:i.fileId}),e&&(yield{type:`image`,source:e,...a?{cache_control:a}:{}})}else if(i.type===`file`){let e;`url`in i&&typeof i.url==`string`?e={type:`url`,url:i.url}:`data`in i&&(typeof i.data==`string`||i.data instanceof Uint8Array)?e={type:`base64`,media_type:`mimeType`in i&&typeof i.mimeType==`string`?i.mimeType:`application/pdf`,data:typeof i.data==`string`?i.data:Buffer.from(i.data).toString(`base64`)}:`fileId`in i&&typeof i.fileId==`string`&&(e={type:`file`,file_id:i.fileId}),e&&(yield{type:`document`,source:e,...a?{cache_control:a}:{}})}else if(i.type===`document`)yield{...i,...a?{cache_control:a}:{}};else if(YW(i))yield{type:`thinking`,thinking:i.thinking,signature:i.signature,...a?{cache_control:a}:{}};else if(XW(i))yield{type:`redacted_thinking`,data:i.data,...a?{cache_control:a}:{}};else if(ZW(i))yield{type:`compaction`,content:i.content,...a?{cache_control:a}:{}};else if(QW(i))yield{type:`search_result`,title:i.title,source:i.source,...`cache_control`in i&&i.cache_control?{cache_control:i.cache_control}:{},...`citations`in i&&i.citations?{citations:i.citations}:{},content:i.content};else if(r.find(e=>e===i.type)&&`text`in i)yield{type:`text`,text:i.text,...a?{cache_control:a}:{},...`citations`in i&&i.citations?{citations:i.citations}:{}};else if(n.find(e=>e===i.type)){let n={...i};if(n.type===`input_json_delta`)continue;if(n.type===`tool_use`&&typeof n.input==`string`){let r=t?.find(e=>e.id===n.id);r?n.input=r.args:n.input=e.filter(e=>e.index===n.index&&e.type===`input_json_delta`&&typeof e.input==`string`).reduce((e,t)=>e+t.input,n.input)}if(`index`in n&&delete n.index,`input`in n&&typeof n.input==`string`)try{n.input=JSON.parse(n.input)}catch{n.input={}}yield{...n,...a?{cache_control:a}:{}}}else i.type===`container_upload`&&(yield{...i,...a?{cache_control:a}:{}})}}function gG(e,t){let{content:n}=e;return typeof n==`string`?n:Array.from(hG(n,t))}function _G(e){let t=pG(e),n;return t.length>0&&t[0]._getType()===`system`&&(n=e[0].content),{messages:vG((n===void 0?t:t.slice(1)).map(e=>{let t;if(e._getType()===`human`)t=`user`;else if(e._getType()===`ai`)t=`assistant`;else if(e._getType()===`tool`)t=`user`;else if(e._getType()===`system`)throw Error(`System messages are only permitted as the first passed message.`);else throw Error(`Message type "${e.type}" is not supported.`);if(qt.isInstance(e)&&e.response_metadata?.output_version===`v1`)return{role:t,content:dG(e)};if(qt.isInstance(e)&&e.tool_calls?.length){if(typeof e.content==`string`)return e.content===``?{role:t,content:e.tool_calls.map(mG)}:{role:t,content:[{type:`text`,text:e.content},...e.tool_calls.map(mG)]};{let{content:n}=e,r=gG(e,e.tool_calls),i=Array.isArray(r)?r:[{type:`text`,text:r}],a=e.tool_calls.filter(e=>!n.find(t=>(t.type===`tool_use`||t.type===`input_json_delta`||t.type===`server_tool_use`)&&t.id===e.id));return{role:t,content:[...i,...a.map(mG)]}}}else return{role:t,content:gG(e,qt.isInstance(e)?e.tool_calls:void 0)}})),system:n}}function vG(e){if(!e||e.length<=1)return e;let t=[],n=e[0],r=e=>typeof e==`string`?[{type:`text`,text:e}]:e,i=e=>e.role!==`user`||typeof e.content==`string`?!1:Array.isArray(e.content)&&e.content.every(e=>e.type===`tool_result`);for(let a=1;a<e.length;a+=1){let o=e[a];i(n)&&i(o)?n={...n,content:[...r(n.content),...r(o.content)]}:(t.push(n),n=o)}return t.push(n),t}function yG(e){return e.type===`enabled`||e.type===`adaptive`}function bG(e){return e?.startsWith(`claude-opus-4-7`)??!1}function xG(e,t){let n=t&&typeof t==`object`&&`task_budget`in t&&t.task_budget!=null;return bG(e)&&n?[`task-budgets-2026-03-13`]:[]}function SG(e){let{model:t,thinking:n,topK:r,topP:i,temperature:a}=e,o=bG(t);if(o&&n.type===`enabled`)throw Error(`thinking.type="enabled" is not supported for claude-opus-4-7; use thinking.type="adaptive" instead`);if(o&&typeof n==`object`&&n&&`budget_tokens`in n)throw Error(`thinking.budget_tokens is not supported for claude-opus-4-7; use outputConfig.effort instead`);if(o){if(r!==void 0)throw Error(`topK is not supported for claude-opus-4-7; omit topK/topP/temperature or use model prompting instead`);if(i!==void 0&&i!==1)throw Error(`topP is not supported for claude-opus-4-7 when set to non-default values`);if(a!==void 0&&a!==1)throw Error(`temperature is not supported for claude-opus-4-7 when set to non-default values`)}if(yG(n)){if(r!==void 0)throw Error(`topK is not supported when thinking is enabled`);if(i!==void 0)throw Error(`topP is not supported when thinking is enabled`);if(a!==void 0&&a!==1)throw Error(`temperature is not supported when thinking is enabled`)}}function CG(e){let{model:t,thinking:n,topK:r,topP:i,temperature:a}=e,o={};return yG(n)||bG(t)?o:(a!==void 0&&(o.temperature=a),r!==void 0&&(o.top_k=r),i!==void 0&&(o.top_p=i),o)}function wG(e,t){let n={model_provider:`anthropic`};if(e.type===`message_start`){let{content:r,usage:i,...a}=e.message,o={};for(let[e,t]of Object.entries(a))t!=null&&(o[e]=t);let{input_tokens:s,output_tokens:c,...l}=i??{},u=EG(i);return{chunk:new Xt({content:t.coerceContentToString?``:[],additional_kwargs:o,usage_metadata:t.streamUsage?u:void 0,response_metadata:{...n,usage:{...l}},id:e.message.id})}}else if(e.type===`message_delta`){let n={input_tokens:0,output_tokens:e.usage.output_tokens,total_tokens:e.usage.output_tokens},r=`context_management`in e.delta?{context_management:e.delta.context_management}:void 0;return{chunk:new Xt({content:t.coerceContentToString?``:[],response_metadata:r,additional_kwargs:{...e.delta},usage_metadata:t.streamUsage?n:void 0})}}else if(e.type===`content_block_start`&&[`tool_use`,`document`,`server_tool_use`,`web_search_tool_result`].includes(e.content_block.type)){let r=e.content_block,i;return i=r.type===`tool_use`?[{id:r.id,index:e.index,name:r.name,args:``}]:[],{chunk:new Xt({content:t.coerceContentToString?``:[{index:e.index,...e.content_block,input:r.type===`server_tool_use`||r.type===`tool_use`?``:void 0}],response_metadata:n,additional_kwargs:{},tool_call_chunks:i})}}else if(e.type===`content_block_delta`&&[`text_delta`,`citations_delta`,`thinking_delta`,`signature_delta`].includes(e.delta.type)){if(t.coerceContentToString&&`text`in e.delta)return{chunk:new Xt({content:e.delta.text})};{let t=e.delta;return`citation`in t&&(t.citations=[t.citation],delete t.citation),t.type===`thinking_delta`||t.type===`signature_delta`?{chunk:new Xt({content:[{index:e.index,...t,type:`thinking`}],response_metadata:n})}:{chunk:new Xt({content:[{index:e.index,...t,type:`text`}],response_metadata:n})}}}else if(e.type===`content_block_delta`&&e.delta.type===`input_json_delta`)return{chunk:new Xt({content:t.coerceContentToString?``:[{index:e.index,input:e.delta.partial_json,type:e.delta.type}],response_metadata:n,additional_kwargs:{},tool_call_chunks:[{index:e.index,args:e.delta.partial_json}]})};else if(e.type===`content_block_start`&&e.content_block.type===`text`){let r=e.content_block?.text;if(r!==void 0)return{chunk:new Xt({content:t.coerceContentToString?r:[{index:e.index,...e.content_block}],response_metadata:n,additional_kwargs:{}})}}else if(e.type===`content_block_start`&&e.content_block.type===`redacted_thinking`)return{chunk:new Xt({content:t.coerceContentToString?``:[{index:e.index,...e.content_block}],response_metadata:n})};else if(e.type===`content_block_start`&&e.content_block.type===`thinking`){let r=e.content_block.thinking;return{chunk:new Xt({content:t.coerceContentToString?r:[{index:e.index,...e.content_block}],response_metadata:n})}}else if(e.type===`content_block_start`&&ZW(e.content_block))return{chunk:new Xt({content:t.coerceContentToString?``:[{index:e.index,...e.content_block}],response_metadata:n})};else if(e.type===`content_block_delta`&&e.delta.type===`compaction_delta`)return{chunk:new Xt({content:t.coerceContentToString?``:[{index:e.index,...e.delta,type:`compaction`}],response_metadata:n})};return null}function TG(e,t){let n={...t,model_provider:`anthropic`},r=t.usage,i=r==null?void 0:EG(r);return e.length===1&&e[0].type===`text`?[{text:e[0].text,message:new qt({content:e[0].text,additional_kwargs:t,usage_metadata:i,response_metadata:n,id:t.id})}]:[{text:``,message:new qt({content:e,additional_kwargs:t,tool_calls:GW(e),usage_metadata:i,response_metadata:n,id:t.id})}]}function EG(e){let t=e.cache_creation_input_tokens??0,n=e.cache_read_input_tokens??0,r=e.input_tokens+t+n;return{input_tokens:r,output_tokens:e.output_tokens,total_tokens:r+e.output_tokens,input_token_details:{cache_creation:t,cache_read:n}}}function DG(e,t){return e.lc_error_code=t,e.message=`${e.message}\n\nTroubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${t}/\n`,e}function OG(e){let t;return t=e.status===400&&typeof e.message==`string`&&e.message.includes(`prompt is too long`)?DG(m.fromError(e),`CONTEXT_OVERFLOW`):e.status===400&&e.message.includes(`tool`)?DG(e,`INVALID_TOOL_RESULTS`):e.status===401?DG(e,`MODEL_AUTHENTICATION`):e.status===404?DG(e,`MODEL_NOT_FOUND`):e.status===429?DG(e,`MODEL_RATE_LIMIT`):e,t}var kG={"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}};async function*AG(e,t={}){let n=t.streamUsage??!0,r=new Map,i,a=null;for await(let t of e)switch(t.type){case`message_start`:{let{usage:e,id:r,model:a}=t.message;e&&n&&(i=MG(e)),yield{event:`message-start`,id:r,...i?{usage:i}:{}},yield{event:`provider`,provider:`anthropic`,name:`message_start`,payload:{model:a,id:r}};break}case`message_delta`:a=t.delta.stop_reason,n&&t.usage&&(i=i?{...i,output_tokens:i.output_tokens+t.usage.output_tokens,total_tokens:i.input_tokens+i.output_tokens+t.usage.output_tokens}:{input_tokens:0,output_tokens:t.usage.output_tokens,total_tokens:t.usage.output_tokens},yield{event:`usage`,usage:i}),`context_management`in t.delta&&t.delta.context_management&&(yield{event:`provider`,provider:`anthropic`,name:`context_management`,payload:t.delta.context_management});break;case`message_stop`:yield{event:`message-finish`,reason:jG(a),...i?{usage:i}:{},metadata:{model_provider:`anthropic`}};break;case`content_block_start`:{let{index:e,content_block:n}=t,i=NG(n,e);r.set(e,{...i}),yield{event:`content-block-start`,index:e,content:i};break}case`content_block_delta`:{let{index:e,delta:n}=t,i=r.get(e);if(!i)break;let{contentDelta:a,accumulated:o}=PG(i,n);r.set(e,o),yield{event:`content-block-delta`,index:e,delta:a};break}case`content_block_stop`:{let{index:e}=t,n=r.get(e);if(!n)break;yield{event:`content-block-finish`,index:e,content:FG(n)},r.delete(e);break}default:yield{event:`provider`,provider:`anthropic`,name:t.type,payload:t};break}}function jG(e){switch(e){case`end_turn`:case`stop_sequence`:return`stop`;case`tool_use`:return`tool_use`;case`max_tokens`:return`length`;default:return`stop`}}function MG(e){let t=e.cache_creation_input_tokens??0,n=e.cache_read_input_tokens??0,r=e.input_tokens+t+n;return{input_tokens:r,output_tokens:e.output_tokens,total_tokens:r+e.output_tokens,input_token_details:{cache_creation:t,cache_read:n}}}function NG(e,t){switch(e.type){case`text`:return{type:`text`,text:e.text??``,index:t};case`thinking`:return{type:`reasoning`,reasoning:e.thinking??``,index:t};case`redacted_thinking`:return{type:`non_standard`,value:{...e},index:t};case`tool_use`:return{type:`tool_call_chunk`,id:e.id,name:e.name,args:``,index:t};case`server_tool_use`:return{type:`server_tool_call_chunk`,id:e.id,name:e.name,args:``,index:t};default:return{type:`non_standard`,value:{...e},index:t}}}function PG(e,t){switch(t.type){case`text_delta`:return{contentDelta:{type:`text-delta`,text:t.text},accumulated:{...e,text:(e.text??``)+t.text}};case`thinking_delta`:return{contentDelta:{type:`reasoning-delta`,reasoning:t.thinking},accumulated:{...e,reasoning:(e.reasoning??``)+t.thinking}};case`input_json_delta`:{let n=(e.args??``)+t.partial_json;return{contentDelta:{type:`block-delta`,fields:{type:e.type,args:n}},accumulated:{...e,args:n}}}case`citations_delta`:{let n=[...e.annotations??[],t.citation];return{contentDelta:{type:`block-delta`,fields:{type:e.type,annotations:n}},accumulated:{...e,annotations:n}}}case`signature_delta`:return{contentDelta:{type:`block-delta`,fields:{type:e.type,signature:t.signature}},accumulated:{...e,signature:t.signature}};case`compaction_delta`:return{contentDelta:{type:`block-delta`,fields:{type:`non_standard`,value:{...e.value??{},compaction:t}}},accumulated:{...e,value:{...e.value??{},compaction:t}}};default:return{contentDelta:{type:`block-delta`,fields:{type:e.type,...t}},accumulated:e}}}function FG(e){if(e.type===`tool_call_chunk`||e.type===`server_tool_call_chunk`){let t=e.type===`tool_call_chunk`?`tool_call`:`server_tool_call`,n;try{n=JSON.parse(e.args||`{}`)}catch{return{type:`invalid_tool_call`,id:e.id,name:e.name,args:e.args,error:`Failed to parse tool call arguments as JSON`}}return{type:t,id:e.id,name:e.name,args:n}}let{index:t,...n}=e;return n}function Y(e,t,n,r,i){if(r===`m`)throw TypeError(`Private method is not writable`);if(r===`a`&&!i)throw TypeError(`Private accessor was defined without a setter`);if(typeof t==`function`?e!==t||!i:!t.has(e))throw TypeError(`Cannot write private member to an object whose class did not declare it`);return r===`a`?i.call(e,n):i?i.value=n:t.set(e,n),n}function X(e,t,n,r){if(n===`a`&&!r)throw TypeError(`Private accessor was defined without a getter`);if(typeof t==`function`?e!==t||!r:!t.has(e))throw TypeError(`Cannot read private member from an object whose class did not declare it`);return n===`m`?r:n===`a`?r.call(e):r?r.value:t.get(e)}var IG=function(){let{crypto:e}=globalThis;if(e?.randomUUID)return IG=e.randomUUID.bind(e),e.randomUUID();let t=new Uint8Array(1),n=e?()=>e.getRandomValues(t)[0]:()=>Math.random()*255&255;return`10000000-1000-4000-8000-100000000000`.replace(/[018]/g,e=>(e^n()&15>>e/4).toString(16))};function LG(e){return typeof e==`object`&&!!e&&(`name`in e&&e.name===`AbortError`||`message`in e&&String(e.message).includes(`FetchRequestCanceledException`))}var RG=e=>{if(e instanceof Error)return e;if(typeof e==`object`&&e){try{if(Object.prototype.toString.call(e)===`[object Error]`){let t=Error(e.message,e.cause?{cause:e.cause}:{});return e.stack&&(t.stack=e.stack),e.cause&&!t.cause&&(t.cause=e.cause),e.name&&(t.name=e.name),t}}catch{}try{return Error(JSON.stringify(e))}catch{}}return Error(e)},Z=class extends Error{},zG=class e extends Z{constructor(t,n,r,i,a){super(`${e.makeMessage(t,n,r)}`),this.status=t,this.headers=i,this.requestID=i?.get(`request-id`),this.error=n,this.type=a??null}static makeMessage(e,t,n){let r=t?.message?typeof t.message==`string`?t.message:JSON.stringify(t.message):t?JSON.stringify(t):n;return e&&r?`${e} ${r}`:e?`${e} status code (no body)`:r||`(no status code or body)`}static generate(t,n,r,i){if(!t||!i)return new VG({message:r,cause:RG(n)});let a=n,o=a?.error?.type;return t===400?new UG(t,a,r,i,o):t===401?new WG(t,a,r,i,o):t===403?new GG(t,a,r,i,o):t===404?new KG(t,a,r,i,o):t===409?new qG(t,a,r,i,o):t===422?new JG(t,a,r,i,o):t===429?new YG(t,a,r,i,o):t>=500?new XG(t,a,r,i,o):new e(t,a,r,i,o)}},BG=class extends zG{constructor({message:e}={}){super(void 0,void 0,e||`Request was aborted.`,void 0)}},VG=class extends zG{constructor({message:e,cause:t}){super(void 0,void 0,e||`Connection error.`,void 0),t&&(this.cause=t)}},HG=class extends VG{constructor({message:e}={}){super({message:e??`Request timed out.`})}},UG=class extends zG{},WG=class extends zG{},GG=class extends zG{},KG=class extends zG{},qG=class extends zG{},JG=class extends zG{},YG=class extends zG{},XG=class extends zG{},ZG=/^[a-z][a-z0-9+.-]*:/i,QG=e=>ZG.test(e),$G=e=>($G=Array.isArray,$G(e)),eK=$G;function tK(e){return typeof e==`object`?e??{}:{}}function nK(e){if(!e)return!0;for(let t in e)return!1;return!0}function rK(e,t){return Object.prototype.hasOwnProperty.call(e,t)}var iK=(e,t)=>{if(typeof t!=`number`||!Number.isInteger(t))throw new Z(`${e} must be an integer`);if(t<0)throw new Z(`${e} must be a positive integer`);return t},aK=e=>{try{return JSON.parse(e)}catch{return}},oK=(e,t)=>{let n=e[t];return delete e[t],n},sK=e=>new Promise(t=>setTimeout(t,e)),cK=`0.91.1`,lK=()=>typeof window<`u`&&window.document!==void 0&&typeof navigator<`u`;function uK(){return typeof Deno<`u`&&Deno.build!=null?`deno`:typeof EdgeRuntime<`u`?`edge`:Object.prototype.toString.call(globalThis.process===void 0?0:globalThis.process)===`[object process]`?`node`:`unknown`}var dK=()=>{let e=uK();if(e===`deno`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":cK,"X-Stainless-OS":mK(Deno.build.os),"X-Stainless-Arch":pK(Deno.build.arch),"X-Stainless-Runtime":`deno`,"X-Stainless-Runtime-Version":typeof Deno.version==`string`?Deno.version:Deno.version?.deno??`unknown`};if(typeof EdgeRuntime<`u`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":cK,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":`edge`,"X-Stainless-Runtime-Version":globalThis.process.version};if(e===`node`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":cK,"X-Stainless-OS":mK(globalThis.process.platform??`unknown`),"X-Stainless-Arch":pK(globalThis.process.arch??`unknown`),"X-Stainless-Runtime":`node`,"X-Stainless-Runtime-Version":globalThis.process.version??`unknown`};let t=fK();return t?{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":cK,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`unknown`,"X-Stainless-Runtime":`browser:${t.browser}`,"X-Stainless-Runtime-Version":t.version}:{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":cK,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`unknown`,"X-Stainless-Runtime":`unknown`,"X-Stainless-Runtime-Version":`unknown`}};function fK(){if(typeof navigator>`u`||!navigator)return null;for(let{key:e,pattern:t}of[{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/}]){let n=t.exec(navigator.userAgent);if(n)return{browser:e,version:`${n[1]||0}.${n[2]||0}.${n[3]||0}`}}return null}var pK=e=>e===`x32`?`x32`:e===`x86_64`||e===`x64`?`x64`:e===`arm`?`arm`:e===`aarch64`||e===`arm64`?`arm64`:e?`other:${e}`:`unknown`,mK=e=>(e=e.toLowerCase(),e.includes(`ios`)?`iOS`:e===`android`?`Android`:e===`darwin`?`MacOS`:e===`win32`?`Windows`:e===`freebsd`?`FreeBSD`:e===`openbsd`?`OpenBSD`:e===`linux`?`Linux`:e?`Other:${e}`:`Unknown`),hK,gK=()=>hK??=dK();function _K(){if(typeof fetch<`u`)return fetch;throw 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 vK(...e){let t=globalThis.ReadableStream;if(t===void 0)throw Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new t(...e)}function yK(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return vK({start(){},async pull(e){let{done:n,value:r}=await t.next();n?e.close():e.enqueue(r)},async cancel(){await t.return?.()}})}function bK(e){if(e[Symbol.asyncIterator])return e;let t=e.getReader();return{async next(){try{let e=await t.read();return e?.done&&t.releaseLock(),e}catch(e){throw t.releaseLock(),e}},async return(){let e=t.cancel();return t.releaseLock(),await e,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function xK(e){if(typeof e!=`object`||!e)return;if(e[Symbol.asyncIterator]){await e[Symbol.asyncIterator]().return?.();return}let t=e.getReader(),n=t.cancel();t.releaseLock(),await n}var SK=({headers:e,body:t})=>({bodyHeaders:{"content-type":`application/json`},body:JSON.stringify(t)});function CK(e){return Object.entries(e).filter(([e,t])=>t!==void 0).map(([e,t])=>{if(typeof t==`string`||typeof t==`number`||typeof t==`boolean`)return`${encodeURIComponent(e)}=${encodeURIComponent(t)}`;if(t===null)return`${encodeURIComponent(e)}=`;throw new Z(`Cannot stringify type ${typeof t}; 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 wK(e){let t=0;for(let n of e)t+=n.length;let n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}var TK;function EK(e){let t;return(TK??=(t=new globalThis.TextEncoder,t.encode.bind(t)))(e)}var DK;function OK(e){let t;return(DK??=(t=new globalThis.TextDecoder,t.decode.bind(t)))(e)}var kK,AK,jK=class{constructor(){kK.set(this,void 0),AK.set(this,void 0),Y(this,kK,new Uint8Array,`f`),Y(this,AK,null,`f`)}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e==`string`?EK(e):e;Y(this,kK,wK([X(this,kK,`f`),t]),`f`);let n=[],r;for(;(r=MK(X(this,kK,`f`),X(this,AK,`f`)))!=null;){if(r.carriage&&X(this,AK,`f`)==null){Y(this,AK,r.index,`f`);continue}if(X(this,AK,`f`)!=null&&(r.index!==X(this,AK,`f`)+1||r.carriage)){n.push(OK(X(this,kK,`f`).subarray(0,X(this,AK,`f`)-1))),Y(this,kK,X(this,kK,`f`).subarray(X(this,AK,`f`)),`f`),Y(this,AK,null,`f`);continue}let e=X(this,AK,`f`)===null?r.preceding:r.preceding-1,t=OK(X(this,kK,`f`).subarray(0,e));n.push(t),Y(this,kK,X(this,kK,`f`).subarray(r.index),`f`),Y(this,AK,null,`f`)}return n}flush(){return X(this,kK,`f`).length?this.decode(`
178
- `):[]}};kK=new WeakMap,AK=new WeakMap,jK.NEWLINE_CHARS=new Set([`
179
- `,`\r`]),jK.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function MK(e,t){for(let n=t??0;n<e.length;n++){if(e[n]===10)return{preceding:n,index:n+1,carriage:!1};if(e[n]===13)return{preceding:n,index:n+1,carriage:!0}}return null}function NK(e){for(let t=0;t<e.length-1;t++){if(e[t]===10&&e[t+1]===10||e[t]===13&&e[t+1]===13)return t+2;if(e[t]===13&&e[t+1]===10&&t+3<e.length&&e[t+2]===13&&e[t+3]===10)return t+4}return-1}var PK={off:0,error:200,warn:300,info:400,debug:500},FK=(e,t,n)=>{if(e){if(rK(PK,e))return e;BK(n).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(PK))}`)}};function IK(){}function LK(e,t,n){return!t||PK[e]>PK[n]?IK:t[e].bind(t)}var RK={error:IK,warn:IK,info:IK,debug:IK},zK=new WeakMap;function BK(e){let t=e.logger,n=e.logLevel??`off`;if(!t)return RK;let r=zK.get(t);if(r&&r[0]===n)return r[1];let i={error:LK(`error`,t,n),warn:LK(`warn`,t,n),info:LK(`info`,t,n),debug:LK(`debug`,t,n)};return zK.set(t,[n,i]),i}var VK=e=>(e.options&&(e.options={...e.options},delete e.options.headers),e.headers&&=Object.fromEntries((e.headers instanceof Headers?[...e.headers]:Object.entries(e.headers)).map(([e,t])=>[e,e.toLowerCase()===`x-api-key`||e.toLowerCase()===`authorization`||e.toLowerCase()===`cookie`||e.toLowerCase()===`set-cookie`?`***`:t])),`retryOfRequestLogID`in e&&(e.retryOfRequestLogID&&(e.retryOf=e.retryOfRequestLogID),delete e.retryOfRequestLogID),e),HK,UK=class e{constructor(e,t,n){this.iterator=e,HK.set(this,void 0),this.controller=t,Y(this,HK,n,`f`)}static fromSSEResponse(t,n,r){let i=!1,a=r?BK(r):console;async function*o(){if(i)throw new Z("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");i=!0;let e=!1;try{for await(let e of WK(t,n)){if(e.event===`completion`)try{yield JSON.parse(e.data)}catch(t){throw a.error(`Could not parse message into JSON:`,e.data),a.error(`From chunk:`,e.raw),t}if(e.event===`message_start`||e.event===`message_delta`||e.event===`message_stop`||e.event===`content_block_start`||e.event===`content_block_delta`||e.event===`content_block_stop`||e.event===`message`||e.event===`user.message`||e.event===`user.interrupt`||e.event===`user.tool_confirmation`||e.event===`user.custom_tool_result`||e.event===`agent.message`||e.event===`agent.thinking`||e.event===`agent.tool_use`||e.event===`agent.tool_result`||e.event===`agent.mcp_tool_use`||e.event===`agent.mcp_tool_result`||e.event===`agent.custom_tool_use`||e.event===`agent.thread_context_compacted`||e.event===`session.status_running`||e.event===`session.status_idle`||e.event===`session.status_rescheduled`||e.event===`session.status_terminated`||e.event===`session.error`||e.event===`session.deleted`||e.event===`span.model_request_start`||e.event===`span.model_request_end`)try{yield JSON.parse(e.data)}catch(t){throw a.error(`Could not parse message into JSON:`,e.data),a.error(`From chunk:`,e.raw),t}if(e.event!==`ping`&&e.event===`error`){let n=aK(e.data)??e.data,r=n?.error?.type;throw new zG(void 0,n,void 0,t.headers,r)}}e=!0}catch(e){if(LG(e))return;throw e}finally{e||n.abort()}}return new e(o,n,r)}static fromReadableStream(t,n,r){let i=!1;async function*a(){let e=new jK,n=bK(t);for await(let t of n)for(let n of e.decode(t))yield n;for(let t of e.flush())yield t}async function*o(){if(i)throw new Z("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");i=!0;let e=!1;try{for await(let t of a())e||t&&(yield JSON.parse(t));e=!0}catch(e){if(LG(e))return;throw e}finally{e||n.abort()}}return new e(o,n,r)}[(HK=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let t=[],n=[],r=this.iterator(),i=e=>({next:()=>{if(e.length===0){let e=r.next();t.push(e),n.push(e)}return e.shift()}});return[new e(()=>i(t),this.controller,X(this,HK,`f`)),new e(()=>i(n),this.controller,X(this,HK,`f`))]}toReadableStream(){let e=this,t;return vK({async start(){t=e[Symbol.asyncIterator]()},async pull(e){try{let{value:n,done:r}=await t.next();if(r)return e.close();let i=EK(JSON.stringify(n)+`
180
- `);e.enqueue(i)}catch(t){e.error(t)}},async cancel(){await t.return?.()}})}};async function*WK(e,t){if(!e.body)throw t.abort(),globalThis.navigator!==void 0&&globalThis.navigator.product===`ReactNative`?new Z(`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 Z(`Attempted to iterate over a response with no body`);let n=new KK,r=new jK,i=bK(e.body);for await(let e of GK(i))for(let t of r.decode(e)){let e=n.decode(t);e&&(yield e)}for(let e of r.flush()){let t=n.decode(e);t&&(yield t)}}async function*GK(e){let t=new Uint8Array;for await(let n of e){if(n==null)continue;let e=n instanceof ArrayBuffer?new Uint8Array(n):typeof n==`string`?EK(n):n,r=new Uint8Array(t.length+e.length);r.set(t),r.set(e,t.length),t=r;let i;for(;(i=NK(t))!==-1;)yield t.slice(0,i),t=t.slice(i)}t.length>0&&(yield t)}var KK=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;let e={event:this.event,data:this.data.join(`
181
- `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],e}if(this.chunks.push(e),e.startsWith(`:`))return null;let[t,n,r]=qK(e,`:`);return r.startsWith(` `)&&(r=r.substring(1)),t===`event`?this.event=r:t===`data`&&this.data.push(r),null}};function qK(e,t){let n=e.indexOf(t);return n===-1?[e,``,``]:[e.substring(0,n),t,e.substring(n+t.length)]}async function JK(e,t){let{response:n,requestLogID:r,retryOfRequestLogID:i,startTime:a}=t,o=await(async()=>{if(t.options.stream)return BK(e).debug(`response`,n.status,n.url,n.headers,n.body),t.options.__streamClass?t.options.__streamClass.fromSSEResponse(n,t.controller):UK.fromSSEResponse(n,t.controller);if(n.status===204)return null;if(t.options.__binaryResponse)return n;let r=n.headers.get(`content-type`)?.split(`;`)[0]?.trim();return r?.includes(`application/json`)||r?.endsWith(`+json`)?n.headers.get(`content-length`)===`0`?void 0:YK(await n.json(),n):await n.text()})();return BK(e).debug(`[${r}] response parsed`,VK({retryOfRequestLogID:i,url:n.url,status:n.status,body:o,durationMs:Date.now()-a})),o}function YK(e,t){return!e||typeof e!=`object`||Array.isArray(e)?e:Object.defineProperty(e,`_request_id`,{value:t.headers.get(`request-id`),enumerable:!1})}var XK,ZK=class e extends Promise{constructor(e,t,n=JK){super(e=>{e(null)}),this.responsePromise=t,this.parseResponse=n,XK.set(this,void 0),Y(this,XK,e,`f`)}_thenUnwrap(t){return new e(X(this,XK,`f`),this.responsePromise,async(e,n)=>YK(t(await this.parseResponse(e,n),n),n.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t,request_id:t.headers.get(`request-id`)}}parse(){return this.parsedPromise||=this.responsePromise.then(e=>this.parseResponse(X(this,XK,`f`),e)),this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}};XK=new WeakMap;var QK,$K=class{constructor(e,t,n,r){QK.set(this,void 0),Y(this,QK,e,`f`),this.options=r,this.response=t,this.body=n}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new Z("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await X(this,QK,`f`).requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(QK=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}},eq=class extends ZK{constructor(e,t,n){super(e,t,async(e,t)=>new n(e,t.response,await JK(e,t),t.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}},tq=class extends $K{constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.has_more=n.has_more||!1,this.first_id=n.first_id||null,this.last_id=n.last_id||null}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){if(this.options.query?.before_id){let e=this.first_id;return e?{...this.options,query:{...tK(this.options.query),before_id:e}}:null}let e=this.last_id;return e?{...this.options,query:{...tK(this.options.query),after_id:e}}:null}},nq=class extends $K{constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.next_page=n.next_page||null}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){let e=this.next_page;return e?{...this.options,query:{...tK(this.options.query),page:e}}:null}},rq=()=>{if(typeof File>`u`){let{process:e}=globalThis,t=typeof e?.versions?.node==`string`&&parseInt(e.versions.node.split(`.`))<20;throw Error("`File` is not defined as a global, which is required for file uploads."+(t?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":``))}};function iq(e,t,n){return rq(),new File(e,t??`unknown_file`,n)}function aq(e,t){let n=typeof e==`object`&&!!e&&(`name`in e&&e.name&&String(e.name)||`url`in e&&e.url&&String(e.url)||`filename`in e&&e.filename&&String(e.filename)||`path`in e&&e.path&&String(e.path))||``;return t?n.split(/[\\/]/).pop()||void 0:n}var oq=e=>typeof e==`object`&&!!e&&typeof e[Symbol.asyncIterator]==`function`,sq=async(e,t,n=!0)=>({...e,body:await uq(e.body,t,n)}),cq=new WeakMap;function lq(e){let t=typeof e==`function`?e:e.fetch,n=cq.get(t);if(n)return n;let r=(async()=>{try{let e=`Response`in t?t.Response:(await t(`data:,`)).constructor,n=new FormData;return n.toString()!==await new e(n).text()}catch{return!0}})();return cq.set(t,r),r}var uq=async(e,t,n=!0)=>{if(!await lq(t))throw TypeError(`The provided fetch function does not support file uploads with the current global FormData class.`);let r=new FormData;return await Promise.all(Object.entries(e||{}).map(([e,t])=>fq(r,e,t,n))),r},dq=e=>e instanceof Blob&&`name`in e,fq=async(e,t,n,r)=>{if(n!==void 0){if(n==null)throw TypeError(`Received null for "${t}"; to pass null in FormData, you must use the string 'null'`);if(typeof n==`string`||typeof n==`number`||typeof n==`boolean`)e.append(t,String(n));else if(n instanceof Response){let i={},a=n.headers.get(`Content-Type`);a&&(i={type:a}),e.append(t,iq([await n.blob()],aq(n,r),i))}else if(oq(n))e.append(t,iq([await new Response(yK(n)).blob()],aq(n,r)));else if(dq(n))e.append(t,iq([n],aq(n,r),{type:n.type}));else if(Array.isArray(n))await Promise.all(n.map(n=>fq(e,t+`[]`,n,r)));else if(typeof n==`object`)await Promise.all(Object.entries(n).map(([n,i])=>fq(e,`${t}[${n}]`,i,r)));else throw TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${n} instead`)}},pq=e=>typeof e==`object`&&!!e&&typeof e.size==`number`&&typeof e.type==`string`&&typeof e.text==`function`&&typeof e.slice==`function`&&typeof e.arrayBuffer==`function`,mq=e=>typeof e==`object`&&!!e&&typeof e.name==`string`&&typeof e.lastModified==`number`&&pq(e),hq=e=>typeof e==`object`&&!!e&&typeof e.url==`string`&&typeof e.blob==`function`;async function gq(e,t,n){if(rq(),e=await e,t||=aq(e,!0),mq(e))return e instanceof File&&t==null&&n==null?e:iq([await e.arrayBuffer()],t??e.name,{type:e.type,lastModified:e.lastModified,...n});if(hq(e)){let r=await e.blob();return t||=new URL(e.url).pathname.split(/[\\/]/).pop(),iq(await _q(r),t,n)}let r=await _q(e);if(!n?.type){let e=r.find(e=>typeof e==`object`&&`type`in e&&e.type);typeof e==`string`&&(n={...n,type:e})}return iq(r,t,n)}async function _q(e){let t=[];if(typeof e==`string`||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(pq(e))t.push(e instanceof Blob?e:await e.arrayBuffer());else if(oq(e))for await(let n of e)t.push(...await _q(n));else{let t=e?.constructor?.name;throw Error(`Unexpected data type: ${typeof e}${t?`; constructor: ${t}`:``}${vq(e)}`)}return t}function vq(e){return typeof e!=`object`||!e?``:`; props: [${Object.getOwnPropertyNames(e).map(e=>`"${e}"`).join(`, `)}]`}var yq=class{constructor(e){this._client=e}},bq=Symbol.for(`brand.privateNullableHeaders`);function*xq(e){if(!e)return;if(bq in e){let{values:t,nulls:n}=e;yield*t.entries();for(let e of n)yield[e,null];return}let t=!1,n;e instanceof Headers?n=e.entries():eK(e)?n=e:(t=!0,n=Object.entries(e??{}));for(let e of n){let n=e[0];if(typeof n!=`string`)throw TypeError(`expected header name to be a string`);let r=eK(e[1])?e[1]:[e[1]],i=!1;for(let e of r)e!==void 0&&(t&&!i&&(i=!0,yield[n,null]),yield[n,e])}}var Q=e=>{let t=new Headers,n=new Set;for(let r of e){let e=new Set;for(let[i,a]of xq(r)){let r=i.toLowerCase();e.has(r)||(t.delete(i),e.add(r)),a===null?(t.delete(i),n.add(r)):(t.append(i,a),n.delete(r))}}return{[bq]:!0,values:t,nulls:n}};function Sq(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var Cq=Object.freeze(Object.create(null)),$=((e=Sq)=>function(t,...n){if(t.length===1)return t[0];let r=!1,i=[],a=t.reduce((t,a,o)=>{/[?#]/.test(a)&&(r=!0);let s=n[o],c=(r?encodeURIComponent:e)(``+s);return o!==n.length&&(s==null||typeof s==`object`&&s.toString===Object.getPrototypeOf(Object.getPrototypeOf(s.hasOwnProperty??Cq)??Cq)?.toString)&&(c=s+``,i.push({start:t.length+a.length,length:c.length,error:`Value of type ${Object.prototype.toString.call(s).slice(8,-1)} is not a valid path parameter`})),t+a+(o===n.length?``:c)},``),o=a.split(/[?#]/,1)[0],s=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,c;for(;(c=s.exec(o))!==null;)i.push({start:c.index,length:c[0].length,error:`Value "${c[0]}" can\'t be safely passed as a path parameter`});if(i.sort((e,t)=>e.start-t.start),i.length>0){let e=0,t=i.reduce((t,n)=>{let r=` `.repeat(n.start-e),i=`^`.repeat(n.length);return e=n.start+n.length,t+r+i},``);throw new Z(`Path parameters result in path with invalid segments:\n${i.map(e=>e.error).join(`
182
- `)}\n${a}\n${t}`)}return a})(Sq),wq=class extends yq{create(e,t){let{betas:n,...r}=e;return this._client.post(`/v1/environments?beta=true`,{body:r,...t,headers:Q([{"anthropic-beta":[...n??[],`managed-agents-2026-04-01`].toString()},t?.headers])})}retrieve(e,t={},n){let{betas:r}=t??{};return this._client.get($`/v1/environments/${e}?beta=true`,{...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}update(e,t,n){let{betas:r,...i}=t;return this._client.post($`/v1/environments/${e}?beta=true`,{body:i,...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}list(e={},t){let{betas:n,...r}=e??{};return this._client.getAPIList(`/v1/environments?beta=true`,nq,{query:r,...t,headers:Q([{"anthropic-beta":[...n??[],`managed-agents-2026-04-01`].toString()},t?.headers])})}delete(e,t={},n){let{betas:r}=t??{};return this._client.delete($`/v1/environments/${e}?beta=true`,{...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}archive(e,t={},n){let{betas:r}=t??{};return this._client.post($`/v1/environments/${e}/archive?beta=true`,{...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}},Tq=Symbol(`anthropic.sdk.stainlessHelper`);function Eq(e){return typeof e==`object`&&!!e&&Tq in e}function Dq(e,t){let n=new Set;if(e)for(let t of e)Eq(t)&&n.add(t[Tq]);if(t){for(let e of t)if(Eq(e)&&n.add(e[Tq]),Array.isArray(e.content))for(let t of e.content)Eq(t)&&n.add(t[Tq])}return Array.from(n)}function Oq(e,t){let n=Dq(e,t);return n.length===0?{}:{"x-stainless-helper":n.join(`, `)}}function kq(e){return Eq(e)?{"x-stainless-helper":e[Tq]}:{}}var Aq=class extends yq{list(e={},t){let{betas:n,...r}=e??{};return this._client.getAPIList(`/v1/files?beta=true`,tq,{query:r,...t,headers:Q([{"anthropic-beta":[...n??[],`files-api-2025-04-14`].toString()},t?.headers])})}delete(e,t={},n){let{betas:r}=t??{};return this._client.delete($`/v1/files/${e}?beta=true`,{...n,headers:Q([{"anthropic-beta":[...r??[],`files-api-2025-04-14`].toString()},n?.headers])})}download(e,t={},n){let{betas:r}=t??{};return this._client.get($`/v1/files/${e}/content?beta=true`,{...n,headers:Q([{"anthropic-beta":[...r??[],`files-api-2025-04-14`].toString(),Accept:`application/binary`},n?.headers]),__binaryResponse:!0})}retrieveMetadata(e,t={},n){let{betas:r}=t??{};return this._client.get($`/v1/files/${e}?beta=true`,{...n,headers:Q([{"anthropic-beta":[...r??[],`files-api-2025-04-14`].toString()},n?.headers])})}upload(e,t){let{betas:n,...r}=e;return this._client.post(`/v1/files?beta=true`,sq({body:r,...t,headers:Q([{"anthropic-beta":[...n??[],`files-api-2025-04-14`].toString()},kq(r.file),t?.headers])},this._client))}},jq=class extends yq{retrieve(e,t={},n){let{betas:r}=t??{};return this._client.get($`/v1/models/${e}?beta=true`,{...n,headers:Q([{...r?.toString()==null?void 0:{"anthropic-beta":r?.toString()}},n?.headers])})}list(e={},t){let{betas:n,...r}=e??{};return this._client.getAPIList(`/v1/models?beta=true`,tq,{query:r,...t,headers:Q([{...n?.toString()==null?void 0:{"anthropic-beta":n?.toString()}},t?.headers])})}},Mq=class extends yq{create(e,t){let{betas:n,...r}=e;return this._client.post(`/v1/user_profiles?beta=true`,{body:r,...t,headers:Q([{"anthropic-beta":[...n??[],`user-profiles-2026-03-24`].toString()},t?.headers])})}retrieve(e,t={},n){let{betas:r}=t??{};return this._client.get($`/v1/user_profiles/${e}?beta=true`,{...n,headers:Q([{"anthropic-beta":[...r??[],`user-profiles-2026-03-24`].toString()},n?.headers])})}update(e,t,n){let{betas:r,...i}=t;return this._client.post($`/v1/user_profiles/${e}?beta=true`,{body:i,...n,headers:Q([{"anthropic-beta":[...r??[],`user-profiles-2026-03-24`].toString()},n?.headers])})}list(e={},t){let{betas:n,...r}=e??{};return this._client.getAPIList(`/v1/user_profiles?beta=true`,nq,{query:r,...t,headers:Q([{"anthropic-beta":[...n??[],`user-profiles-2026-03-24`].toString()},t?.headers])})}createEnrollmentURL(e,t={},n){let{betas:r}=t??{};return this._client.post($`/v1/user_profiles/${e}/enrollment_url?beta=true`,{...n,headers:Q([{"anthropic-beta":[...r??[],`user-profiles-2026-03-24`].toString()},n?.headers])})}},Nq=class extends yq{list(e,t={},n){let{betas:r,...i}=t??{};return this._client.getAPIList($`/v1/agents/${e}/versions?beta=true`,nq,{query:i,...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}},Pq=class extends yq{constructor(){super(...arguments),this.versions=new Nq(this._client)}create(e,t){let{betas:n,...r}=e;return this._client.post(`/v1/agents?beta=true`,{body:r,...t,headers:Q([{"anthropic-beta":[...n??[],`managed-agents-2026-04-01`].toString()},t?.headers])})}retrieve(e,t={},n){let{betas:r,...i}=t??{};return this._client.get($`/v1/agents/${e}?beta=true`,{query:i,...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}update(e,t,n){let{betas:r,...i}=t;return this._client.post($`/v1/agents/${e}?beta=true`,{body:i,...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}list(e={},t){let{betas:n,...r}=e??{};return this._client.getAPIList(`/v1/agents?beta=true`,nq,{query:r,...t,headers:Q([{"anthropic-beta":[...n??[],`managed-agents-2026-04-01`].toString()},t?.headers])})}archive(e,t={},n){let{betas:r}=t??{};return this._client.post($`/v1/agents/${e}/archive?beta=true`,{...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}};Pq.Versions=Nq;var Fq=class extends yq{create(e,t,n){let{view:r,betas:i,...a}=t;return this._client.post($`/v1/memory_stores/${e}/memories?beta=true`,{query:{view:r},body:a,...n,headers:Q([{"anthropic-beta":[...i??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}retrieve(e,t,n){let{memory_store_id:r,betas:i,...a}=t;return this._client.get($`/v1/memory_stores/${r}/memories/${e}?beta=true`,{query:a,...n,headers:Q([{"anthropic-beta":[...i??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}update(e,t,n){let{memory_store_id:r,view:i,betas:a,...o}=t;return this._client.post($`/v1/memory_stores/${r}/memories/${e}?beta=true`,{query:{view:i},body:o,...n,headers:Q([{"anthropic-beta":[...a??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}list(e,t={},n){let{betas:r,...i}=t??{};return this._client.getAPIList($`/v1/memory_stores/${e}/memories?beta=true`,nq,{query:i,...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}delete(e,t,n){let{memory_store_id:r,expected_content_sha256:i,betas:a}=t;return this._client.delete($`/v1/memory_stores/${r}/memories/${e}?beta=true`,{query:{expected_content_sha256:i},...n,headers:Q([{"anthropic-beta":[...a??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}},Iq=class extends yq{retrieve(e,t,n){let{memory_store_id:r,betas:i,...a}=t;return this._client.get($`/v1/memory_stores/${r}/memory_versions/${e}?beta=true`,{query:a,...n,headers:Q([{"anthropic-beta":[...i??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}list(e,t={},n){let{betas:r,...i}=t??{};return this._client.getAPIList($`/v1/memory_stores/${e}/memory_versions?beta=true`,nq,{query:i,...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}redact(e,t,n){let{memory_store_id:r,betas:i}=t;return this._client.post($`/v1/memory_stores/${r}/memory_versions/${e}/redact?beta=true`,{...n,headers:Q([{"anthropic-beta":[...i??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}},Lq=class extends yq{constructor(){super(...arguments),this.memories=new Fq(this._client),this.memoryVersions=new Iq(this._client)}create(e,t){let{betas:n,...r}=e;return this._client.post(`/v1/memory_stores?beta=true`,{body:r,...t,headers:Q([{"anthropic-beta":[...n??[],`managed-agents-2026-04-01`].toString()},t?.headers])})}retrieve(e,t={},n){let{betas:r}=t??{};return this._client.get($`/v1/memory_stores/${e}?beta=true`,{...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}update(e,t,n){let{betas:r,...i}=t;return this._client.post($`/v1/memory_stores/${e}?beta=true`,{body:i,...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}list(e={},t){let{betas:n,...r}=e??{};return this._client.getAPIList(`/v1/memory_stores?beta=true`,nq,{query:r,...t,headers:Q([{"anthropic-beta":[...n??[],`managed-agents-2026-04-01`].toString()},t?.headers])})}delete(e,t={},n){let{betas:r}=t??{};return this._client.delete($`/v1/memory_stores/${e}?beta=true`,{...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}archive(e,t={},n){let{betas:r}=t??{};return this._client.post($`/v1/memory_stores/${e}/archive?beta=true`,{...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}};Lq.Memories=Fq,Lq.MemoryVersions=Iq;var Rq={"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 zq(e){return e?.output_format??e?.output_config?.format}function Bq(e,t,n){let r=zq(t);return!t||!(`parse`in(r??{}))?{...e,content:e.content.map(e=>{if(e.type===`text`){let t=Object.defineProperty({...e},`parsed_output`,{value:null,enumerable:!1});return Object.defineProperty(t,`parsed`,{get(){return n.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),null},enumerable:!1})}return e}),parsed_output:null}:Vq(e,t,n)}function Vq(e,t,n){let r=null,i=e.content.map(e=>{if(e.type===`text`){let i=Hq(t,e.text);r===null&&(r=i);let a=Object.defineProperty({...e},`parsed_output`,{value:i,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."),i},enumerable:!1})}return e});return{...e,content:i,parsed_output:r}}function Hq(e,t){let n=zq(e);if(n?.type!==`json_schema`)return null;try{return`parse`in n?n.parse(t):JSON.parse(t)}catch(e){throw new Z(`Failed to parse structured output: ${e}`)}}var Uq=e=>{let t=0,n=[];for(;t<e.length;){let r=e[t];if(r===`\\`){t++;continue}if(r===`{`){n.push({type:`brace`,value:`{`}),t++;continue}if(r===`}`){n.push({type:`brace`,value:`}`}),t++;continue}if(r===`[`){n.push({type:`paren`,value:`[`}),t++;continue}if(r===`]`){n.push({type:`paren`,value:`]`}),t++;continue}if(r===`:`){n.push({type:`separator`,value:`:`}),t++;continue}if(r===`,`){n.push({type:`delimiter`,value:`,`}),t++;continue}if(r===`"`){let i=``,a=!1;for(r=e[++t];r!==`"`;){if(t===e.length){a=!0;break}if(r===`\\`){if(t++,t===e.length){a=!0;break}i+=r+e[t],r=e[++t]}else i+=r,r=e[++t]}r=e[++t],a||n.push({type:`string`,value:i});continue}if(r&&/\s/.test(r)){t++;continue}let i=/[0-9]/;if(r&&i.test(r)||r===`-`||r===`.`){let a=``;for(r===`-`&&(a+=r,r=e[++t]);r&&i.test(r)||r===`.`;)a+=r,r=e[++t];n.push({type:`number`,value:a});continue}let a=/[a-z]/i;if(r&&a.test(r)){let i=``;for(;r&&a.test(r)&&t!==e.length;)i+=r,r=e[++t];if(i==`true`||i==`false`||i===`null`)n.push({type:`name`,value:i});else{t++;continue}continue}t++}return n},Wq=e=>{if(e.length===0)return e;let t=e[e.length-1];switch(t.type){case`separator`:return e=e.slice(0,e.length-1),Wq(e);case`number`:let n=t.value[t.value.length-1];if(n===`.`||n===`-`)return e=e.slice(0,e.length-1),Wq(e);case`string`:let r=e[e.length-2];if(r?.type===`delimiter`||r?.type===`brace`&&r.value===`{`)return e=e.slice(0,e.length-1),Wq(e);break;case`delimiter`:return e=e.slice(0,e.length-1),Wq(e)}return e},Gq=e=>{let t=[];return e.map(e=>{e.type===`brace`&&(e.value===`{`?t.push(`}`):t.splice(t.lastIndexOf(`}`),1)),e.type===`paren`&&(e.value===`[`?t.push(`]`):t.splice(t.lastIndexOf(`]`),1))}),t.length>0&&t.reverse().map(t=>{t===`}`?e.push({type:`brace`,value:`}`}):t===`]`&&e.push({type:`paren`,value:`]`})}),e},Kq=e=>{let t=``;return e.map(e=>{switch(e.type){case`string`:t+=`"`+e.value+`"`;break;default:t+=e.value;break}}),t},qq=e=>JSON.parse(Kq(Gq(Wq(Uq(e))))),Jq,Yq,Xq,Zq,Qq,$q,eJ,tJ,nJ,rJ,iJ,aJ,oJ,sJ,cJ,lJ,uJ,dJ,fJ,pJ,mJ,hJ,gJ,_J,vJ=`__json_buf`;function yJ(e){return e.type===`tool_use`||e.type===`server_tool_use`||e.type===`mcp_tool_use`}var bJ=class e{constructor(e,t){Jq.add(this),this.messages=[],this.receivedMessages=[],Yq.set(this,void 0),Xq.set(this,null),this.controller=new AbortController,Zq.set(this,void 0),Qq.set(this,()=>{}),$q.set(this,()=>{}),eJ.set(this,void 0),tJ.set(this,()=>{}),nJ.set(this,()=>{}),rJ.set(this,{}),iJ.set(this,!1),aJ.set(this,!1),oJ.set(this,!1),sJ.set(this,!1),cJ.set(this,void 0),lJ.set(this,void 0),uJ.set(this,void 0),pJ.set(this,e=>{if(Y(this,aJ,!0,`f`),LG(e)&&(e=new BG),e instanceof BG)return Y(this,oJ,!0,`f`),this._emit(`abort`,e);if(e instanceof Z)return this._emit(`error`,e);if(e instanceof Error){let t=new Z(e.message);return t.cause=e,this._emit(`error`,t)}return this._emit(`error`,new Z(String(e)))}),Y(this,Zq,new Promise((e,t)=>{Y(this,Qq,e,`f`),Y(this,$q,t,`f`)}),`f`),Y(this,eJ,new Promise((e,t)=>{Y(this,tJ,e,`f`),Y(this,nJ,t,`f`)}),`f`),X(this,Zq,`f`).catch(()=>{}),X(this,eJ,`f`).catch(()=>{}),Y(this,Xq,e,`f`),Y(this,uJ,t?.logger??console,`f`)}get response(){return X(this,cJ,`f`)}get request_id(){return X(this,lJ,`f`)}async withResponse(){Y(this,sJ,!0,`f`);let e=await X(this,Zq,`f`);if(!e)throw Error("Could not resolve a `Response` object");return{data:this,response:e,request_id:e.headers.get(`request-id`)}}static fromReadableStream(t){let n=new e(null);return n._run(()=>n._fromReadableStream(t)),n}static createMessage(t,n,r,{logger:i}={}){let a=new e(n,{logger:i});for(let e of n.messages)a._addMessageParam(e);return Y(a,Xq,{...n,stream:!0},`f`),a._run(()=>a._createMessage(t,{...n,stream:!0},{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`stream`}})),a}_run(e){e().then(()=>{this._emitFinal(),this._emit(`end`)},X(this,pJ,`f`))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,t=!0){this.receivedMessages.push(e),t&&this._emit(`message`,e)}async _createMessage(e,t,n){let r=n?.signal,i;r&&(r.aborted&&this.controller.abort(),i=this.controller.abort.bind(this.controller),r.addEventListener(`abort`,i));try{X(this,Jq,`m`,mJ).call(this);let{response:r,data:i}=await e.create({...t,stream:!0},{...n,signal:this.controller.signal}).withResponse();this._connected(r);for await(let e of i)X(this,Jq,`m`,hJ).call(this,e);if(i.controller.signal?.aborted)throw new BG;X(this,Jq,`m`,gJ).call(this)}finally{r&&i&&r.removeEventListener(`abort`,i)}}_connected(e){this.ended||(Y(this,cJ,e,`f`),Y(this,lJ,e?.headers.get(`request-id`),`f`),X(this,Qq,`f`).call(this,e),this._emit(`connect`))}get ended(){return X(this,iJ,`f`)}get errored(){return X(this,aJ,`f`)}get aborted(){return X(this,oJ,`f`)}abort(){this.controller.abort()}on(e,t){return(X(this,rJ,`f`)[e]||(X(this,rJ,`f`)[e]=[])).push({listener:t}),this}off(e,t){let n=X(this,rJ,`f`)[e];if(!n)return this;let r=n.findIndex(e=>e.listener===t);return r>=0&&n.splice(r,1),this}once(e,t){return(X(this,rJ,`f`)[e]||(X(this,rJ,`f`)[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,n)=>{Y(this,sJ,!0,`f`),e!==`error`&&this.once(`error`,n),this.once(e,t)})}async done(){Y(this,sJ,!0,`f`),await X(this,eJ,`f`)}get currentMessage(){return X(this,Yq,`f`)}async finalMessage(){return await this.done(),X(this,Jq,`m`,dJ).call(this)}async finalText(){return await this.done(),X(this,Jq,`m`,fJ).call(this)}_emit(e,...t){if(X(this,iJ,`f`))return;e===`end`&&(Y(this,iJ,!0,`f`),X(this,tJ,`f`).call(this));let n=X(this,rJ,`f`)[e];if(n&&(X(this,rJ,`f`)[e]=n.filter(e=>!e.once),n.forEach(({listener:e})=>e(...t))),e===`abort`){let e=t[0];!X(this,sJ,`f`)&&!n?.length&&Promise.reject(e),X(this,$q,`f`).call(this,e),X(this,nJ,`f`).call(this,e),this._emit(`end`);return}if(e===`error`){let e=t[0];!X(this,sJ,`f`)&&!n?.length&&Promise.reject(e),X(this,$q,`f`).call(this,e),X(this,nJ,`f`).call(this,e),this._emit(`end`)}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit(`finalMessage`,X(this,Jq,`m`,dJ).call(this))}async _fromReadableStream(e,t){let n=t?.signal,r;n&&(n.aborted&&this.controller.abort(),r=this.controller.abort.bind(this.controller),n.addEventListener(`abort`,r));try{X(this,Jq,`m`,mJ).call(this),this._connected(null);let t=UK.fromReadableStream(e,this.controller);for await(let e of t)X(this,Jq,`m`,hJ).call(this,e);if(t.controller.signal?.aborted)throw new BG;X(this,Jq,`m`,gJ).call(this)}finally{n&&r&&n.removeEventListener(`abort`,r)}}[(Yq=new WeakMap,Xq=new WeakMap,Zq=new WeakMap,Qq=new WeakMap,$q=new WeakMap,eJ=new WeakMap,tJ=new WeakMap,nJ=new WeakMap,rJ=new WeakMap,iJ=new WeakMap,aJ=new WeakMap,oJ=new WeakMap,sJ=new WeakMap,cJ=new WeakMap,lJ=new WeakMap,uJ=new WeakMap,pJ=new WeakMap,Jq=new WeakSet,dJ=function(){if(this.receivedMessages.length===0)throw new Z(`stream ended without producing a Message with role=assistant`);return this.receivedMessages.at(-1)},fJ=function(){if(this.receivedMessages.length===0)throw new Z(`stream ended without producing a Message with role=assistant`);let e=this.receivedMessages.at(-1).content.filter(e=>e.type===`text`).map(e=>e.text);if(e.length===0)throw new Z(`stream ended without producing a content block with type=text`);return e.join(` `)},mJ=function(){this.ended||Y(this,Yq,void 0,`f`)},hJ=function(e){if(this.ended)return;let t=X(this,Jq,`m`,_J).call(this,e);switch(this._emit(`streamEvent`,e,t),e.type){case`content_block_delta`:{let n=t.content.at(-1);switch(e.delta.type){case`text_delta`:n.type===`text`&&this._emit(`text`,e.delta.text,n.text||``);break;case`citations_delta`:n.type===`text`&&this._emit(`citation`,e.delta.citation,n.citations??[]);break;case`input_json_delta`:yJ(n)&&n.input&&this._emit(`inputJson`,e.delta.partial_json,n.input);break;case`thinking_delta`:n.type===`thinking`&&this._emit(`thinking`,e.delta.thinking,n.thinking);break;case`signature_delta`:n.type===`thinking`&&this._emit(`signature`,n.signature);break;case`compaction_delta`:n.type===`compaction`&&n.content&&this._emit(`compaction`,n.content);break;default:e.delta}break}case`message_stop`:this._addMessageParam(t),this._addMessage(Bq(t,X(this,Xq,`f`),{logger:X(this,uJ,`f`)}),!0);break;case`content_block_stop`:this._emit(`contentBlock`,t.content.at(-1));break;case`message_start`:Y(this,Yq,t,`f`);break;case`content_block_start`:case`message_delta`:break}},gJ=function(){if(this.ended)throw new Z(`stream has ended, this shouldn't happen`);let e=X(this,Yq,`f`);if(!e)throw new Z(`request ended without sending any chunks`);return Y(this,Yq,void 0,`f`),Bq(e,X(this,Xq,`f`),{logger:X(this,uJ,`f`)})},_J=function(e){let t=X(this,Yq,`f`);if(e.type===`message_start`){if(t)throw new Z(`Unexpected event order, got ${e.type} before receiving "message_stop"`);return e.message}if(!t)throw new Z(`Unexpected event order, got ${e.type} before "message_start"`);switch(e.type){case`message_stop`:return t;case`message_delta`:return t.container=e.delta.container,t.stop_reason=e.delta.stop_reason,t.stop_sequence=e.delta.stop_sequence,t.usage.output_tokens=e.usage.output_tokens,t.context_management=e.context_management,e.usage.input_tokens!=null&&(t.usage.input_tokens=e.usage.input_tokens),e.usage.cache_creation_input_tokens!=null&&(t.usage.cache_creation_input_tokens=e.usage.cache_creation_input_tokens),e.usage.cache_read_input_tokens!=null&&(t.usage.cache_read_input_tokens=e.usage.cache_read_input_tokens),e.usage.server_tool_use!=null&&(t.usage.server_tool_use=e.usage.server_tool_use),e.usage.iterations!=null&&(t.usage.iterations=e.usage.iterations),t;case`content_block_start`:return t.content.push(e.content_block),t;case`content_block_delta`:{let n=t.content.at(e.index);switch(e.delta.type){case`text_delta`:n?.type===`text`&&(t.content[e.index]={...n,text:(n.text||``)+e.delta.text});break;case`citations_delta`:n?.type===`text`&&(t.content[e.index]={...n,citations:[...n.citations??[],e.delta.citation]});break;case`input_json_delta`:if(n&&yJ(n)){let r=n[vJ]||``;r+=e.delta.partial_json;let i={...n};if(Object.defineProperty(i,vJ,{value:r,enumerable:!1,writable:!0}),r)try{i.input=qq(r)}catch(e){let t=new Z(`Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: ${e}. JSON: ${r}`);X(this,pJ,`f`).call(this,t)}t.content[e.index]=i}break;case`thinking_delta`:n?.type===`thinking`&&(t.content[e.index]={...n,thinking:n.thinking+e.delta.thinking});break;case`signature_delta`:n?.type===`thinking`&&(t.content[e.index]={...n,signature:e.delta.signature});break;case`compaction_delta`:n?.type===`compaction`&&(t.content[e.index]={...n,content:(n.content||``)+e.delta.content});break;default:e.delta}return t}case`content_block_stop`:return t}},Symbol.asyncIterator)](){let e=[],t=[],n=!1;return this.on(`streamEvent`,n=>{let r=t.shift();r?r.resolve(n):e.push(n)}),this.on(`end`,()=>{n=!0;for(let e of t)e.resolve(void 0);t.length=0}),this.on(`abort`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),this.on(`error`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((e,n)=>t.push({resolve:e,reject:n})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new UK(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}},xJ=class extends Error{constructor(e){let t=typeof e==`string`?e:e.map(e=>e.type===`text`?e.text:`[${e.type}]`).join(` `);super(t),this.name=`ToolError`,this.content=e}},SJ=`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:
183
- 1. Task Overview
184
- The user's core request and success criteria
185
- Any clarifications or constraints they specified
186
- 2. Current State
187
- What has been completed so far
188
- Files created, modified, or analyzed (with paths if relevant)
189
- Key outputs or artifacts produced
190
- 3. Important Discoveries
191
- Technical constraints or requirements uncovered
192
- Decisions made and their rationale
193
- Errors encountered and how they were resolved
194
- What approaches were tried that didn't work (and why)
195
- 4. Next Steps
196
- Specific actions needed to complete the task
197
- Any blockers or open questions to resolve
198
- Priority order if multiple steps remain
199
- 5. Context to Preserve
200
- User preferences or style requirements
201
- Domain-specific details that aren't obvious
202
- Any promises made to the user
203
- 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.
204
- Wrap your summary in <summary></summary> tags.`,CJ,wJ,TJ,EJ,DJ,OJ,kJ,AJ,jJ,MJ,NJ;function PJ(){let e,t;return{promise:new Promise((n,r)=>{e=n,t=r}),resolve:e,reject:t}}var FJ=class{constructor(e,t,n){CJ.add(this),this.client=e,wJ.set(this,!1),TJ.set(this,!1),EJ.set(this,void 0),DJ.set(this,void 0),OJ.set(this,void 0),kJ.set(this,void 0),AJ.set(this,void 0),jJ.set(this,0),Y(this,EJ,{params:{...t,messages:structuredClone(t.messages)}},`f`);let r=[`BetaToolRunner`,...Dq(t.tools,t.messages)].join(`, `);Y(this,DJ,{...n,headers:Q([{"x-stainless-helper":r},n?.headers])},`f`),Y(this,AJ,PJ(),`f`),t.compactionControl?.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*[(wJ=new WeakMap,TJ=new WeakMap,EJ=new WeakMap,DJ=new WeakMap,OJ=new WeakMap,kJ=new WeakMap,AJ=new WeakMap,jJ=new WeakMap,CJ=new WeakSet,MJ=async function(){let e=X(this,EJ,`f`).params.compactionControl;if(!e||!e.enabled)return!1;let t=0;if(X(this,OJ,`f`)!==void 0)try{let e=await X(this,OJ,`f`);t=e.usage.input_tokens+(e.usage.cache_creation_input_tokens??0)+(e.usage.cache_read_input_tokens??0)+e.usage.output_tokens}catch{return!1}let n=e.contextTokenThreshold??1e5;if(t<n)return!1;let r=e.model??X(this,EJ,`f`).params.model,i=e.summaryPrompt??SJ,a=X(this,EJ,`f`).params.messages;if(a[a.length-1].role===`assistant`){let e=a[a.length-1];if(Array.isArray(e.content)){let t=e.content.filter(e=>e.type!==`tool_use`);t.length===0?a.pop():e.content=t}}let o=await this.client.beta.messages.create({model:r,messages:[...a,{role:`user`,content:[{type:`text`,text:i}]}],max_tokens:X(this,EJ,`f`).params.max_tokens},{signal:X(this,DJ,`f`).signal,headers:Q([X(this,DJ,`f`).headers,{"x-stainless-helper":`compaction`}])});if(o.content[0]?.type!==`text`)throw new Z(`Expected text response for compaction`);return X(this,EJ,`f`).params.messages=[{role:`user`,content:o.content}],!0},Symbol.asyncIterator)](){var e;if(X(this,wJ,`f`))throw new Z(`Cannot iterate over a consumed stream`);Y(this,wJ,!0,`f`),Y(this,TJ,!0,`f`),Y(this,kJ,void 0,`f`);try{for(;;){let t;try{if(X(this,EJ,`f`).params.max_iterations&&X(this,jJ,`f`)>=X(this,EJ,`f`).params.max_iterations)break;Y(this,TJ,!1,`f`),Y(this,kJ,void 0,`f`),Y(this,jJ,(e=X(this,jJ,`f`),e++,e),`f`),Y(this,OJ,void 0,`f`);let{max_iterations:n,compactionControl:r,...i}=X(this,EJ,`f`).params;if(i.stream?(t=this.client.beta.messages.stream({...i},X(this,DJ,`f`)),Y(this,OJ,t.finalMessage(),`f`),X(this,OJ,`f`).catch(()=>{}),yield t):(Y(this,OJ,this.client.beta.messages.create({...i,stream:!1},X(this,DJ,`f`)),`f`),yield X(this,OJ,`f`)),!await X(this,CJ,`m`,MJ).call(this)){if(!X(this,TJ,`f`)){let{role:e,content:t}=await X(this,OJ,`f`);X(this,EJ,`f`).params.messages.push({role:e,content:t})}let e=await X(this,CJ,`m`,NJ).call(this,X(this,EJ,`f`).params.messages.at(-1));if(e)X(this,EJ,`f`).params.messages.push(e);else if(!X(this,TJ,`f`))break}}finally{t&&t.abort()}}if(!X(this,OJ,`f`))throw new Z(`ToolRunner concluded without a message from the server`);X(this,AJ,`f`).resolve(await X(this,OJ,`f`))}catch(e){throw Y(this,wJ,!1,`f`),X(this,AJ,`f`).promise.catch(()=>{}),X(this,AJ,`f`).reject(e),Y(this,AJ,PJ(),`f`),e}}setMessagesParams(e){typeof e==`function`?X(this,EJ,`f`).params=e(X(this,EJ,`f`).params):X(this,EJ,`f`).params=e,Y(this,TJ,!0,`f`),Y(this,kJ,void 0,`f`)}setRequestOptions(e){typeof e==`function`?Y(this,DJ,e(X(this,DJ,`f`)),`f`):Y(this,DJ,{...X(this,DJ,`f`),...e},`f`)}async generateToolResponse(e=X(this,DJ,`f`).signal){let t=await X(this,OJ,`f`)??this.params.messages.at(-1);return t?X(this,CJ,`m`,NJ).call(this,t,e):null}done(){return X(this,AJ,`f`).promise}async runUntilDone(){if(!X(this,wJ,`f`))for await(let e of this);return this.done()}get params(){return X(this,EJ,`f`).params}pushMessages(...e){this.setMessagesParams(t=>({...t,messages:[...t.messages,...e]}))}then(e,t){return this.runUntilDone().then(e,t)}};NJ=async function(e,t=X(this,DJ,`f`).signal){return X(this,kJ,`f`)===void 0&&Y(this,kJ,IJ(X(this,EJ,`f`).params,e,{...X(this,DJ,`f`),signal:t}),`f`),X(this,kJ,`f`)};async function IJ(e,t=e.messages.at(-1),n){if(!t||t.role!==`assistant`||!t.content||typeof t.content==`string`)return null;let r=t.content.filter(e=>e.type===`tool_use`);return r.length===0?null:{role:`user`,content:await Promise.all(r.map(async t=>{let r=e.tools.find(e=>(`name`in e?e.name:e.mcp_server_name)===t.name);if(!r||!(`run`in r))return{type:`tool_result`,tool_use_id:t.id,content:`Error: Tool '${t.name}' not found`,is_error:!0};try{let e=t.input;`parse`in r&&r.parse&&(e=r.parse(e));let i=await r.run(e,{toolUseBlock:t,signal:n?.signal});return{type:`tool_result`,tool_use_id:t.id,content:i}}catch(e){return{type:`tool_result`,tool_use_id:t.id,content:e instanceof xJ?e.content:`Error: ${e instanceof Error?e.message:String(e)}`,is_error:!0}}}))}}var LJ=class e{constructor(e,t){this.iterator=e,this.controller=t}async*decoder(){let e=new jK;for await(let t of this.iterator)for(let n of e.decode(t))yield JSON.parse(n);for(let t of e.flush())yield JSON.parse(t)}[Symbol.asyncIterator](){return this.decoder()}static fromResponse(t,n){if(!t.body)throw n.abort(),globalThis.navigator!==void 0&&globalThis.navigator.product===`ReactNative`?new Z(`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 Z(`Attempted to iterate over a response with no body`);return new e(bK(t.body),n)}},RJ=class extends yq{create(e,t){let{betas:n,...r}=e;return this._client.post(`/v1/messages/batches?beta=true`,{body:r,...t,headers:Q([{"anthropic-beta":[...n??[],`message-batches-2024-09-24`].toString()},t?.headers])})}retrieve(e,t={},n){let{betas:r}=t??{};return this._client.get($`/v1/messages/batches/${e}?beta=true`,{...n,headers:Q([{"anthropic-beta":[...r??[],`message-batches-2024-09-24`].toString()},n?.headers])})}list(e={},t){let{betas:n,...r}=e??{};return this._client.getAPIList(`/v1/messages/batches?beta=true`,tq,{query:r,...t,headers:Q([{"anthropic-beta":[...n??[],`message-batches-2024-09-24`].toString()},t?.headers])})}delete(e,t={},n){let{betas:r}=t??{};return this._client.delete($`/v1/messages/batches/${e}?beta=true`,{...n,headers:Q([{"anthropic-beta":[...r??[],`message-batches-2024-09-24`].toString()},n?.headers])})}cancel(e,t={},n){let{betas:r}=t??{};return this._client.post($`/v1/messages/batches/${e}/cancel?beta=true`,{...n,headers:Q([{"anthropic-beta":[...r??[],`message-batches-2024-09-24`].toString()},n?.headers])})}async results(e,t={},n){let r=await this.retrieve(e);if(!r.results_url)throw new Z(`No batch \`results_url\`; Has it finished processing? ${r.processing_status} - ${r.id}`);let{betas:i}=t??{};return this._client.get(r.results_url,{...n,headers:Q([{"anthropic-beta":[...i??[],`message-batches-2024-09-24`].toString(),Accept:`application/binary`},n?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((e,t)=>LJ.fromResponse(t.response,t.controller))}},zJ={"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`},BJ=[`claude-mythos-preview`,`claude-opus-4-6`],VJ=class extends yq{constructor(){super(...arguments),this.batches=new RJ(this._client)}create(e,t){let n=HJ(e),{betas:r,...i}=n;i.model in zJ&&console.warn(`The model '${i.model}' is deprecated and will reach end-of-life on ${zJ[i.model]}\nPlease migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),BJ.includes(i.model)&&i.thinking&&i.thinking.type===`enabled`&&console.warn(`Using Claude with ${i.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 a=this._client._options.timeout;if(!i.stream&&a==null){let e=Rq[i.model]??void 0;a=this._client.calculateNonstreamingTimeout(i.max_tokens,e)}let o=Oq(i.tools,i.messages);return this._client.post(`/v1/messages?beta=true`,{body:i,timeout:a??6e5,...t,headers:Q([{...r?.toString()==null?void 0:{"anthropic-beta":r?.toString()}},o,t?.headers]),stream:n.stream??!1})}parse(e,t){return t={...t,headers:Q([{"anthropic-beta":[...e.betas??[],`structured-outputs-2025-12-15`].toString()},t?.headers])},this.create(e,t).then(t=>Vq(t,e,{logger:this._client.logger??console}))}stream(e,t){return bJ.createMessage(this,e,t)}countTokens(e,t){let{betas:n,...r}=HJ(e);return this._client.post(`/v1/messages/count_tokens?beta=true`,{body:r,...t,headers:Q([{"anthropic-beta":[...n??[],`token-counting-2024-11-01`].toString()},t?.headers])})}toolRunner(e,t){return new FJ(this._client,e,t)}};function HJ(e){if(!e.output_format)return e;if(e.output_config?.format)throw new Z(`Both output_format and output_config.format were provided. Please use only output_config.format (output_format is deprecated).`);let{output_format:t,...n}=e;return{...n,output_config:{...e.output_config,format:t}}}VJ.Batches=RJ,VJ.BetaToolRunner=FJ,VJ.ToolError=xJ;var UJ=class extends yq{list(e,t={},n){let{betas:r,...i}=t??{};return this._client.getAPIList($`/v1/sessions/${e}/events?beta=true`,nq,{query:i,...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}send(e,t,n){let{betas:r,...i}=t;return this._client.post($`/v1/sessions/${e}/events?beta=true`,{body:i,...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}stream(e,t={},n){let{betas:r}=t??{};return this._client.get($`/v1/sessions/${e}/events/stream?beta=true`,{...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers]),stream:!0})}},WJ=class extends yq{retrieve(e,t,n){let{session_id:r,betas:i}=t;return this._client.get($`/v1/sessions/${r}/resources/${e}?beta=true`,{...n,headers:Q([{"anthropic-beta":[...i??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}update(e,t,n){let{session_id:r,betas:i,...a}=t;return this._client.post($`/v1/sessions/${r}/resources/${e}?beta=true`,{body:a,...n,headers:Q([{"anthropic-beta":[...i??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}list(e,t={},n){let{betas:r,...i}=t??{};return this._client.getAPIList($`/v1/sessions/${e}/resources?beta=true`,nq,{query:i,...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}delete(e,t,n){let{session_id:r,betas:i}=t;return this._client.delete($`/v1/sessions/${r}/resources/${e}?beta=true`,{...n,headers:Q([{"anthropic-beta":[...i??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}add(e,t,n){let{betas:r,...i}=t;return this._client.post($`/v1/sessions/${e}/resources?beta=true`,{body:i,...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}},GJ=class extends yq{constructor(){super(...arguments),this.events=new UJ(this._client),this.resources=new WJ(this._client)}create(e,t){let{betas:n,...r}=e;return this._client.post(`/v1/sessions?beta=true`,{body:r,...t,headers:Q([{"anthropic-beta":[...n??[],`managed-agents-2026-04-01`].toString()},t?.headers])})}retrieve(e,t={},n){let{betas:r}=t??{};return this._client.get($`/v1/sessions/${e}?beta=true`,{...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}update(e,t,n){let{betas:r,...i}=t;return this._client.post($`/v1/sessions/${e}?beta=true`,{body:i,...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}list(e={},t){let{betas:n,...r}=e??{};return this._client.getAPIList(`/v1/sessions?beta=true`,nq,{query:r,...t,headers:Q([{"anthropic-beta":[...n??[],`managed-agents-2026-04-01`].toString()},t?.headers])})}delete(e,t={},n){let{betas:r}=t??{};return this._client.delete($`/v1/sessions/${e}?beta=true`,{...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}archive(e,t={},n){let{betas:r}=t??{};return this._client.post($`/v1/sessions/${e}/archive?beta=true`,{...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}};GJ.Events=UJ,GJ.Resources=WJ;var KJ=class extends yq{create(e,t={},n){let{betas:r,...i}=t??{};return this._client.post($`/v1/skills/${e}/versions?beta=true`,sq({body:i,...n,headers:Q([{"anthropic-beta":[...r??[],`skills-2025-10-02`].toString()},n?.headers])},this._client))}retrieve(e,t,n){let{skill_id:r,betas:i}=t;return this._client.get($`/v1/skills/${r}/versions/${e}?beta=true`,{...n,headers:Q([{"anthropic-beta":[...i??[],`skills-2025-10-02`].toString()},n?.headers])})}list(e,t={},n){let{betas:r,...i}=t??{};return this._client.getAPIList($`/v1/skills/${e}/versions?beta=true`,nq,{query:i,...n,headers:Q([{"anthropic-beta":[...r??[],`skills-2025-10-02`].toString()},n?.headers])})}delete(e,t,n){let{skill_id:r,betas:i}=t;return this._client.delete($`/v1/skills/${r}/versions/${e}?beta=true`,{...n,headers:Q([{"anthropic-beta":[...i??[],`skills-2025-10-02`].toString()},n?.headers])})}},qJ=class extends yq{constructor(){super(...arguments),this.versions=new KJ(this._client)}create(e={},t){let{betas:n,...r}=e??{};return this._client.post(`/v1/skills?beta=true`,sq({body:r,...t,headers:Q([{"anthropic-beta":[...n??[],`skills-2025-10-02`].toString()},t?.headers])},this._client,!1))}retrieve(e,t={},n){let{betas:r}=t??{};return this._client.get($`/v1/skills/${e}?beta=true`,{...n,headers:Q([{"anthropic-beta":[...r??[],`skills-2025-10-02`].toString()},n?.headers])})}list(e={},t){let{betas:n,...r}=e??{};return this._client.getAPIList(`/v1/skills?beta=true`,nq,{query:r,...t,headers:Q([{"anthropic-beta":[...n??[],`skills-2025-10-02`].toString()},t?.headers])})}delete(e,t={},n){let{betas:r}=t??{};return this._client.delete($`/v1/skills/${e}?beta=true`,{...n,headers:Q([{"anthropic-beta":[...r??[],`skills-2025-10-02`].toString()},n?.headers])})}};qJ.Versions=KJ;var JJ=class extends yq{create(e,t,n){let{betas:r,...i}=t;return this._client.post($`/v1/vaults/${e}/credentials?beta=true`,{body:i,...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}retrieve(e,t,n){let{vault_id:r,betas:i}=t;return this._client.get($`/v1/vaults/${r}/credentials/${e}?beta=true`,{...n,headers:Q([{"anthropic-beta":[...i??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}update(e,t,n){let{vault_id:r,betas:i,...a}=t;return this._client.post($`/v1/vaults/${r}/credentials/${e}?beta=true`,{body:a,...n,headers:Q([{"anthropic-beta":[...i??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}list(e,t={},n){let{betas:r,...i}=t??{};return this._client.getAPIList($`/v1/vaults/${e}/credentials?beta=true`,nq,{query:i,...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}delete(e,t,n){let{vault_id:r,betas:i}=t;return this._client.delete($`/v1/vaults/${r}/credentials/${e}?beta=true`,{...n,headers:Q([{"anthropic-beta":[...i??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}archive(e,t,n){let{vault_id:r,betas:i}=t;return this._client.post($`/v1/vaults/${r}/credentials/${e}/archive?beta=true`,{...n,headers:Q([{"anthropic-beta":[...i??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}},YJ=class extends yq{constructor(){super(...arguments),this.credentials=new JJ(this._client)}create(e,t){let{betas:n,...r}=e;return this._client.post(`/v1/vaults?beta=true`,{body:r,...t,headers:Q([{"anthropic-beta":[...n??[],`managed-agents-2026-04-01`].toString()},t?.headers])})}retrieve(e,t={},n){let{betas:r}=t??{};return this._client.get($`/v1/vaults/${e}?beta=true`,{...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}update(e,t,n){let{betas:r,...i}=t;return this._client.post($`/v1/vaults/${e}?beta=true`,{body:i,...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}list(e={},t){let{betas:n,...r}=e??{};return this._client.getAPIList(`/v1/vaults?beta=true`,nq,{query:r,...t,headers:Q([{"anthropic-beta":[...n??[],`managed-agents-2026-04-01`].toString()},t?.headers])})}delete(e,t={},n){let{betas:r}=t??{};return this._client.delete($`/v1/vaults/${e}?beta=true`,{...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}archive(e,t={},n){let{betas:r}=t??{};return this._client.post($`/v1/vaults/${e}/archive?beta=true`,{...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}};YJ.Credentials=JJ;var XJ=class extends yq{constructor(){super(...arguments),this.models=new jq(this._client),this.messages=new VJ(this._client),this.agents=new Pq(this._client),this.environments=new wq(this._client),this.sessions=new GJ(this._client),this.vaults=new YJ(this._client),this.memoryStores=new Lq(this._client),this.files=new Aq(this._client),this.skills=new qJ(this._client),this.userProfiles=new Mq(this._client)}};XJ.Models=jq,XJ.Messages=VJ,XJ.Agents=Pq,XJ.Environments=wq,XJ.Sessions=GJ,XJ.Vaults=YJ,XJ.MemoryStores=Lq,XJ.Files=Aq,XJ.Skills=qJ,XJ.UserProfiles=Mq;var ZJ=class extends yq{create(e,t){let{betas:n,...r}=e;return this._client.post(`/v1/complete`,{body:r,timeout:this._client._options.timeout??6e5,...t,headers:Q([{...n?.toString()==null?void 0:{"anthropic-beta":n?.toString()}},t?.headers]),stream:e.stream??!1})}};function QJ(e){return e?.output_config?.format}function $J(e,t,n){let r=QJ(t);return!t||!(`parse`in(r??{}))?{...e,content:e.content.map(e=>e.type===`text`?Object.defineProperty({...e},`parsed_output`,{value:null,enumerable:!1}):e),parsed_output:null}:eY(e,t,n)}function eY(e,t,n){let r=null,i=e.content.map(e=>{if(e.type===`text`){let n=tY(t,e.text);return r===null&&(r=n),Object.defineProperty({...e},`parsed_output`,{value:n,enumerable:!1})}return e});return{...e,content:i,parsed_output:r}}function tY(e,t){let n=QJ(e);if(n?.type!==`json_schema`)return null;try{return`parse`in n?n.parse(t):JSON.parse(t)}catch(e){throw new Z(`Failed to parse structured output: ${e}`)}}var nY,rY,iY,aY,oY,sY,cY,lY,uY,dY,fY,pY,mY,hY,gY,_Y,vY,yY,bY,xY,SY,CY,wY,TY,EY=`__json_buf`;function DY(e){return e.type===`tool_use`||e.type===`server_tool_use`}var OY=class e{constructor(e,t){nY.add(this),this.messages=[],this.receivedMessages=[],rY.set(this,void 0),iY.set(this,null),this.controller=new AbortController,aY.set(this,void 0),oY.set(this,()=>{}),sY.set(this,()=>{}),cY.set(this,void 0),lY.set(this,()=>{}),uY.set(this,()=>{}),dY.set(this,{}),fY.set(this,!1),pY.set(this,!1),mY.set(this,!1),hY.set(this,!1),gY.set(this,void 0),_Y.set(this,void 0),vY.set(this,void 0),xY.set(this,e=>{if(Y(this,pY,!0,`f`),LG(e)&&(e=new BG),e instanceof BG)return Y(this,mY,!0,`f`),this._emit(`abort`,e);if(e instanceof Z)return this._emit(`error`,e);if(e instanceof Error){let t=new Z(e.message);return t.cause=e,this._emit(`error`,t)}return this._emit(`error`,new Z(String(e)))}),Y(this,aY,new Promise((e,t)=>{Y(this,oY,e,`f`),Y(this,sY,t,`f`)}),`f`),Y(this,cY,new Promise((e,t)=>{Y(this,lY,e,`f`),Y(this,uY,t,`f`)}),`f`),X(this,aY,`f`).catch(()=>{}),X(this,cY,`f`).catch(()=>{}),Y(this,iY,e,`f`),Y(this,vY,t?.logger??console,`f`)}get response(){return X(this,gY,`f`)}get request_id(){return X(this,_Y,`f`)}async withResponse(){Y(this,hY,!0,`f`);let e=await X(this,aY,`f`);if(!e)throw Error("Could not resolve a `Response` object");return{data:this,response:e,request_id:e.headers.get(`request-id`)}}static fromReadableStream(t){let n=new e(null);return n._run(()=>n._fromReadableStream(t)),n}static createMessage(t,n,r,{logger:i}={}){let a=new e(n,{logger:i});for(let e of n.messages)a._addMessageParam(e);return Y(a,iY,{...n,stream:!0},`f`),a._run(()=>a._createMessage(t,{...n,stream:!0},{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`stream`}})),a}_run(e){e().then(()=>{this._emitFinal(),this._emit(`end`)},X(this,xY,`f`))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,t=!0){this.receivedMessages.push(e),t&&this._emit(`message`,e)}async _createMessage(e,t,n){let r=n?.signal,i;r&&(r.aborted&&this.controller.abort(),i=this.controller.abort.bind(this.controller),r.addEventListener(`abort`,i));try{X(this,nY,`m`,SY).call(this);let{response:r,data:i}=await e.create({...t,stream:!0},{...n,signal:this.controller.signal}).withResponse();this._connected(r);for await(let e of i)X(this,nY,`m`,CY).call(this,e);if(i.controller.signal?.aborted)throw new BG;X(this,nY,`m`,wY).call(this)}finally{r&&i&&r.removeEventListener(`abort`,i)}}_connected(e){this.ended||(Y(this,gY,e,`f`),Y(this,_Y,e?.headers.get(`request-id`),`f`),X(this,oY,`f`).call(this,e),this._emit(`connect`))}get ended(){return X(this,fY,`f`)}get errored(){return X(this,pY,`f`)}get aborted(){return X(this,mY,`f`)}abort(){this.controller.abort()}on(e,t){return(X(this,dY,`f`)[e]||(X(this,dY,`f`)[e]=[])).push({listener:t}),this}off(e,t){let n=X(this,dY,`f`)[e];if(!n)return this;let r=n.findIndex(e=>e.listener===t);return r>=0&&n.splice(r,1),this}once(e,t){return(X(this,dY,`f`)[e]||(X(this,dY,`f`)[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,n)=>{Y(this,hY,!0,`f`),e!==`error`&&this.once(`error`,n),this.once(e,t)})}async done(){Y(this,hY,!0,`f`),await X(this,cY,`f`)}get currentMessage(){return X(this,rY,`f`)}async finalMessage(){return await this.done(),X(this,nY,`m`,yY).call(this)}async finalText(){return await this.done(),X(this,nY,`m`,bY).call(this)}_emit(e,...t){if(X(this,fY,`f`))return;e===`end`&&(Y(this,fY,!0,`f`),X(this,lY,`f`).call(this));let n=X(this,dY,`f`)[e];if(n&&(X(this,dY,`f`)[e]=n.filter(e=>!e.once),n.forEach(({listener:e})=>e(...t))),e===`abort`){let e=t[0];!X(this,hY,`f`)&&!n?.length&&Promise.reject(e),X(this,sY,`f`).call(this,e),X(this,uY,`f`).call(this,e),this._emit(`end`);return}if(e===`error`){let e=t[0];!X(this,hY,`f`)&&!n?.length&&Promise.reject(e),X(this,sY,`f`).call(this,e),X(this,uY,`f`).call(this,e),this._emit(`end`)}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit(`finalMessage`,X(this,nY,`m`,yY).call(this))}async _fromReadableStream(e,t){let n=t?.signal,r;n&&(n.aborted&&this.controller.abort(),r=this.controller.abort.bind(this.controller),n.addEventListener(`abort`,r));try{X(this,nY,`m`,SY).call(this),this._connected(null);let t=UK.fromReadableStream(e,this.controller);for await(let e of t)X(this,nY,`m`,CY).call(this,e);if(t.controller.signal?.aborted)throw new BG;X(this,nY,`m`,wY).call(this)}finally{n&&r&&n.removeEventListener(`abort`,r)}}[(rY=new WeakMap,iY=new WeakMap,aY=new WeakMap,oY=new WeakMap,sY=new WeakMap,cY=new WeakMap,lY=new WeakMap,uY=new WeakMap,dY=new WeakMap,fY=new WeakMap,pY=new WeakMap,mY=new WeakMap,hY=new WeakMap,gY=new WeakMap,_Y=new WeakMap,vY=new WeakMap,xY=new WeakMap,nY=new WeakSet,yY=function(){if(this.receivedMessages.length===0)throw new Z(`stream ended without producing a Message with role=assistant`);return this.receivedMessages.at(-1)},bY=function(){if(this.receivedMessages.length===0)throw new Z(`stream ended without producing a Message with role=assistant`);let e=this.receivedMessages.at(-1).content.filter(e=>e.type===`text`).map(e=>e.text);if(e.length===0)throw new Z(`stream ended without producing a content block with type=text`);return e.join(` `)},SY=function(){this.ended||Y(this,rY,void 0,`f`)},CY=function(e){if(this.ended)return;let t=X(this,nY,`m`,TY).call(this,e);switch(this._emit(`streamEvent`,e,t),e.type){case`content_block_delta`:{let n=t.content.at(-1);switch(e.delta.type){case`text_delta`:n.type===`text`&&this._emit(`text`,e.delta.text,n.text||``);break;case`citations_delta`:n.type===`text`&&this._emit(`citation`,e.delta.citation,n.citations??[]);break;case`input_json_delta`:DY(n)&&n.input&&this._emit(`inputJson`,e.delta.partial_json,n.input);break;case`thinking_delta`:n.type===`thinking`&&this._emit(`thinking`,e.delta.thinking,n.thinking);break;case`signature_delta`:n.type===`thinking`&&this._emit(`signature`,n.signature);break;default:e.delta}break}case`message_stop`:this._addMessageParam(t),this._addMessage($J(t,X(this,iY,`f`),{logger:X(this,vY,`f`)}),!0);break;case`content_block_stop`:this._emit(`contentBlock`,t.content.at(-1));break;case`message_start`:Y(this,rY,t,`f`);break;case`content_block_start`:case`message_delta`:break}},wY=function(){if(this.ended)throw new Z(`stream has ended, this shouldn't happen`);let e=X(this,rY,`f`);if(!e)throw new Z(`request ended without sending any chunks`);return Y(this,rY,void 0,`f`),$J(e,X(this,iY,`f`),{logger:X(this,vY,`f`)})},TY=function(e){let t=X(this,rY,`f`);if(e.type===`message_start`){if(t)throw new Z(`Unexpected event order, got ${e.type} before receiving "message_stop"`);return e.message}if(!t)throw new Z(`Unexpected event order, got ${e.type} before "message_start"`);switch(e.type){case`message_stop`:return t;case`message_delta`:return t.stop_reason=e.delta.stop_reason,t.stop_sequence=e.delta.stop_sequence,t.usage.output_tokens=e.usage.output_tokens,e.usage.input_tokens!=null&&(t.usage.input_tokens=e.usage.input_tokens),e.usage.cache_creation_input_tokens!=null&&(t.usage.cache_creation_input_tokens=e.usage.cache_creation_input_tokens),e.usage.cache_read_input_tokens!=null&&(t.usage.cache_read_input_tokens=e.usage.cache_read_input_tokens),e.usage.server_tool_use!=null&&(t.usage.server_tool_use=e.usage.server_tool_use),t;case`content_block_start`:return t.content.push({...e.content_block}),t;case`content_block_delta`:{let n=t.content.at(e.index);switch(e.delta.type){case`text_delta`:n?.type===`text`&&(t.content[e.index]={...n,text:(n.text||``)+e.delta.text});break;case`citations_delta`:n?.type===`text`&&(t.content[e.index]={...n,citations:[...n.citations??[],e.delta.citation]});break;case`input_json_delta`:if(n&&DY(n)){let r=n[EY]||``;r+=e.delta.partial_json;let i={...n};Object.defineProperty(i,EY,{value:r,enumerable:!1,writable:!0}),r&&(i.input=qq(r)),t.content[e.index]=i}break;case`thinking_delta`:n?.type===`thinking`&&(t.content[e.index]={...n,thinking:n.thinking+e.delta.thinking});break;case`signature_delta`:n?.type===`thinking`&&(t.content[e.index]={...n,signature:e.delta.signature});break;default:e.delta}return t}case`content_block_stop`:return t}},Symbol.asyncIterator)](){let e=[],t=[],n=!1;return this.on(`streamEvent`,n=>{let r=t.shift();r?r.resolve(n):e.push(n)}),this.on(`end`,()=>{n=!0;for(let e of t)e.resolve(void 0);t.length=0}),this.on(`abort`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),this.on(`error`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((e,n)=>t.push({resolve:e,reject:n})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new UK(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}},kY=class extends yq{create(e,t){return this._client.post(`/v1/messages/batches`,{body:e,...t})}retrieve(e,t){return this._client.get($`/v1/messages/batches/${e}`,t)}list(e={},t){return this._client.getAPIList(`/v1/messages/batches`,tq,{query:e,...t})}delete(e,t){return this._client.delete($`/v1/messages/batches/${e}`,t)}cancel(e,t){return this._client.post($`/v1/messages/batches/${e}/cancel`,t)}async results(e,t){let n=await this.retrieve(e);if(!n.results_url)throw new Z(`No batch \`results_url\`; Has it finished processing? ${n.processing_status} - ${n.id}`);return this._client.get(n.results_url,{...t,headers:Q([{Accept:`application/binary`},t?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((e,t)=>LJ.fromResponse(t.response,t.controller))}},AY=class extends yq{constructor(){super(...arguments),this.batches=new kY(this._client)}create(e,t){e.model in jY&&console.warn(`The model '${e.model}' is deprecated and will reach end-of-life on ${jY[e.model]}\nPlease migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),MY.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 n=this._client._options.timeout;if(!e.stream&&n==null){let t=Rq[e.model]??void 0;n=this._client.calculateNonstreamingTimeout(e.max_tokens,t)}let r=Oq(e.tools,e.messages);return this._client.post(`/v1/messages`,{body:e,timeout:n??6e5,...t,headers:Q([r,t?.headers]),stream:e.stream??!1})}parse(e,t){return this.create(e,t).then(t=>eY(t,e,{logger:this._client.logger??console}))}stream(e,t){return OY.createMessage(this,e,t,{logger:this._client.logger??console})}countTokens(e,t){return this._client.post(`/v1/messages/count_tokens`,{body:e,...t})}},jY={"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`},MY=[`claude-mythos-preview`,`claude-opus-4-6`];AY.Batches=kY;var NY=class extends yq{retrieve(e,t={},n){let{betas:r}=t??{};return this._client.get($`/v1/models/${e}`,{...n,headers:Q([{...r?.toString()==null?void 0:{"anthropic-beta":r?.toString()}},n?.headers])})}list(e={},t){let{betas:n,...r}=e??{};return this._client.getAPIList(`/v1/models`,tq,{query:r,...t,headers:Q([{...n?.toString()==null?void 0:{"anthropic-beta":n?.toString()}},t?.headers])})}},PY=e=>{if(globalThis.process!==void 0)return{}?.[e]?.trim()||void 0;if(globalThis.Deno!==void 0)return globalThis.Deno.env?.get?.(e)?.trim()||void 0},FY,IY,LY,RY,zY=`\\n\\nHuman:`,BY=`\\n\\nAssistant:`,VY=class{constructor({baseURL:e=PY(`ANTHROPIC_BASE_URL`),apiKey:t=PY(`ANTHROPIC_API_KEY`)??null,authToken:n=PY(`ANTHROPIC_AUTH_TOKEN`)??null,...r}={}){FY.add(this),LY.set(this,void 0);let i={apiKey:t,authToken:n,...r,baseURL:e||`https://api.anthropic.com`};if(!i.dangerouslyAllowBrowser&&lK())throw new Z(`It looks like you're running in a browser-like environment.
205
-
206
- This is disabled by default, as it risks exposing your secret API credentials to attackers.
207
- If you understand the risks and have appropriate mitigations in place,
208
- you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
209
-
210
- new Anthropic({ apiKey, dangerouslyAllowBrowser: true });
211
- `);this.baseURL=i.baseURL,this.timeout=i.timeout??IY.DEFAULT_TIMEOUT,this.logger=i.logger??console;let a=`warn`;this.logLevel=a,this.logLevel=FK(i.logLevel,`ClientOptions.logLevel`,this)??FK(PY(`ANTHROPIC_LOG`),`process.env['ANTHROPIC_LOG']`,this)??a,this.fetchOptions=i.fetchOptions,this.maxRetries=i.maxRetries??2,this.fetch=i.fetch??_K(),Y(this,LY,SK,`f`),this._options=i,this.apiKey=typeof t==`string`?t:null,this.authToken=n}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:t}){if(!(e.get(`x-api-key`)||e.get(`authorization`))&&!(this.apiKey&&e.get(`x-api-key`))&&!t.has(`x-api-key`)&&!(this.authToken&&e.get(`authorization`))&&!t.has(`authorization`))throw 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 Q([await this.apiKeyAuth(e),await this.bearerAuth(e)])}async apiKeyAuth(e){if(this.apiKey!=null)return Q([{"X-Api-Key":this.apiKey}])}async bearerAuth(e){if(this.authToken!=null)return Q([{Authorization:`Bearer ${this.authToken}`}])}stringifyQuery(e){return CK(e)}getUserAgent(){return`${this.constructor.name}/JS ${cK}`}defaultIdempotencyKey(){return`stainless-node-retry-${IG()}`}makeStatusError(e,t,n,r){return zG.generate(e,t,n,r)}buildURL(e,t,n){let r=!X(this,FY,`m`,RY).call(this)&&n||this.baseURL,i=QG(e)?new URL(e):new URL(r+(r.endsWith(`/`)&&e.startsWith(`/`)?e.slice(1):e)),a=this.defaultQuery(),o=Object.fromEntries(i.searchParams);return(!nK(a)||!nK(o))&&(t={...o,...a,...t}),typeof t==`object`&&t&&!Array.isArray(t)&&(i.search=this.stringifyQuery(t)),i.toString()}_calculateNonstreamingTimeout(e){if(3600*e/128e3>600)throw new Z(`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:t,options:n}){}get(e,t){return this.methodRequest(`get`,e,t)}post(e,t){return this.methodRequest(`post`,e,t)}patch(e,t){return this.methodRequest(`patch`,e,t)}put(e,t){return this.methodRequest(`put`,e,t)}delete(e,t){return this.methodRequest(`delete`,e,t)}methodRequest(e,t,n){return this.request(Promise.resolve(n).then(n=>({method:e,path:t,...n})))}request(e,t=null){return new ZK(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,n){let r=await e,i=r.maxRetries??this.maxRetries;t??=i,await this.prepareOptions(r);let{req:a,url:o,timeout:s}=await this.buildRequest(r,{retryCount:i-t});await this.prepareRequest(a,{url:o,options:r});let c=`log_`+(Math.random()*(1<<24)|0).toString(16).padStart(6,`0`),l=n===void 0?``:`, retryOf: ${n}`,u=Date.now();if(BK(this).debug(`[${c}] sending request`,VK({retryOfRequestLogID:n,method:r.method,url:o,options:r,headers:a.headers})),r.signal?.aborted)throw new BG;let d=new AbortController,f=await this.fetchWithTimeout(o,a,s,d).catch(RG),p=Date.now();if(f instanceof globalThis.Error){let e=`retrying, ${t} attempts remaining`;if(r.signal?.aborted)throw new BG;let i=LG(f)||/timed? ?out/i.test(String(f)+(`cause`in f?String(f.cause):``));if(t)return BK(this).info(`[${c}] connection ${i?`timed out`:`failed`} - ${e}`),BK(this).debug(`[${c}] connection ${i?`timed out`:`failed`} (${e})`,VK({retryOfRequestLogID:n,url:o,durationMs:p-u,message:f.message})),this.retryRequest(r,t,n??c);throw BK(this).info(`[${c}] connection ${i?`timed out`:`failed`} - error; no more retries left`),BK(this).debug(`[${c}] connection ${i?`timed out`:`failed`} (error; no more retries left)`,VK({retryOfRequestLogID:n,url:o,durationMs:p-u,message:f.message})),i?new HG:new VG({cause:f})}let m=`[${c}${l}${[...f.headers.entries()].filter(([e])=>e===`request-id`).map(([e,t])=>`, `+e+`: `+JSON.stringify(t)).join(``)}] ${a.method} ${o} ${f.ok?`succeeded`:`failed`} with status ${f.status} in ${p-u}ms`;if(!f.ok){let e=await this.shouldRetry(f);if(t&&e){let e=`retrying, ${t} attempts remaining`;return await xK(f.body),BK(this).info(`${m} - ${e}`),BK(this).debug(`[${c}] response error (${e})`,VK({retryOfRequestLogID:n,url:f.url,status:f.status,headers:f.headers,durationMs:p-u})),this.retryRequest(r,t,n??c,f.headers)}let i=e?`error; no more retries left`:`error; not retryable`;BK(this).info(`${m} - ${i}`);let a=await f.text().catch(e=>RG(e).message),o=aK(a),s=o?void 0:a;throw BK(this).debug(`[${c}] response error (${i})`,VK({retryOfRequestLogID:n,url:f.url,status:f.status,headers:f.headers,message:s,durationMs:Date.now()-u})),this.makeStatusError(f.status,o,s,f.headers)}return BK(this).info(m),BK(this).debug(`[${c}] response start`,VK({retryOfRequestLogID:n,url:f.url,status:f.status,headers:f.headers,durationMs:p-u})),{response:f,options:r,controller:d,requestLogID:c,retryOfRequestLogID:n,startTime:u}}getAPIList(e,t,n){return this.requestAPIList(t,n&&`then`in n?n.then(t=>({method:`get`,path:e,...t})):{method:`get`,path:e,...n})}requestAPIList(e,t){let n=this.makeRequest(t,null,void 0);return new eq(this,n,e)}async fetchWithTimeout(e,t,n,r){let{signal:i,method:a,...o}=t||{},s=this._makeAbort(r);i&&i.addEventListener(`abort`,s,{once:!0});let c=setTimeout(s,n),l=globalThis.ReadableStream&&o.body instanceof globalThis.ReadableStream||typeof o.body==`object`&&o.body!==null&&Symbol.asyncIterator in o.body,u={signal:r.signal,...l?{duplex:`half`}:{},method:`GET`,...o};a&&(u.method=a.toUpperCase());try{return await this.fetch.call(void 0,e,u)}finally{clearTimeout(c)}}async shouldRetry(e){let t=e.headers.get(`x-should-retry`);return t===`true`?!0:t===`false`?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,t,n,r){let i,a=r?.get(`retry-after-ms`);if(a){let e=parseFloat(a);Number.isNaN(e)||(i=e)}let o=r?.get(`retry-after`);if(o&&!i){let e=parseFloat(o);i=Number.isNaN(e)?Date.parse(o)-Date.now():e*1e3}if(i===void 0){let n=e.maxRetries??this.maxRetries;i=this.calculateDefaultRetryTimeoutMillis(t,n)}return await sK(i),this.makeRequest(e,t-1,n)}calculateDefaultRetryTimeoutMillis(e,t){let n=t-e;return Math.min(.5*2**n,8)*(1-Math.random()*.25)*1e3}calculateNonstreamingTimeout(e,t){let n=600*1e3;if(36e5*e/128e3>n||t!=null&&e>t)throw new Z(`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 n}async buildRequest(e,{retryCount:t=0}={}){let n={...e},{method:r,path:i,query:a,defaultBaseURL:o}=n,s=this.buildURL(i,a,o);`timeout`in n&&iK(`timeout`,n.timeout),n.timeout=n.timeout??this.timeout;let{bodyHeaders:c,body:l}=this.buildBody({options:n});return{req:{method:r,headers:await this.buildHeaders({options:e,method:r,bodyHeaders:c,retryCount:t}),...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&l instanceof globalThis.ReadableStream&&{duplex:`half`},...l&&{body:l},...this.fetchOptions??{},...n.fetchOptions??{}},url:s,timeout:n.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:n,retryCount:r}){let i={};this.idempotencyHeader&&t!==`get`&&(e.idempotencyKey||=this.defaultIdempotencyKey(),i[this.idempotencyHeader]=e.idempotencyKey);let a=Q([i,{Accept:`application/json`,"User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(r),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...gK(),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":`true`}:void 0,"anthropic-version":`2023-06-01`},await this.authHeaders(e),this._options.defaultHeaders,n,e.headers]);return this.validateHeaders(a),a.values}_makeAbort(e){return()=>e.abort()}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0};let n=Q([t]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e==`string`&&n.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:yK(e)}:typeof e==`object`&&n.values.get(`content-type`)===`application/x-www-form-urlencoded`?{bodyHeaders:{"content-type":`application/x-www-form-urlencoded`},body:this.stringifyQuery(e)}:X(this,LY,`f`).call(this,{body:e,headers:n})}};IY=VY,LY=new WeakMap,FY=new WeakSet,RY=function(){return this.baseURL!==`https://api.anthropic.com`},VY.Anthropic=IY,VY.HUMAN_PROMPT=zY,VY.AI_PROMPT=BY,VY.DEFAULT_TIMEOUT=6e5,VY.AnthropicError=Z,VY.APIError=zG,VY.APIConnectionError=VG,VY.APIConnectionTimeoutError=HG,VY.APIUserAbortError=BG,VY.NotFoundError=KG,VY.ConflictError=qG,VY.RateLimitError=YG,VY.BadRequestError=UG,VY.AuthenticationError=WG,VY.InternalServerError=XG,VY.PermissionDeniedError=GG,VY.UnprocessableEntityError=JG,VY.toFile=gq;var HY=class extends VY{constructor(){super(...arguments),this.completions=new ZJ(this),this.messages=new AY(this),this.models=new NY(this),this.beta=new XJ(this)}};HY.Completions=ZJ,HY.Messages=AY,HY.Models=NY,HY.Beta=XJ;var UY=new Set([`date-time`,`time`,`date`,`duration`,`email`,`hostname`,`uri`,`ipv4`,`ipv6`,`uuid`]);function WY(e){return JSON.parse(JSON.stringify(e))}function GY(e){return KY(WY(e))}function KY(e){let t={},n=oK(e,`$ref`);if(n!==void 0)return t.$ref=n,t;let r=oK(e,`$defs`);if(r!==void 0){let e={};t.$defs=e;for(let[t,n]of Object.entries(r))e[t]=KY(n)}let i=oK(e,`type`),a=oK(e,`anyOf`),o=oK(e,`oneOf`),s=oK(e,`allOf`);if(Array.isArray(a))t.anyOf=a.map(e=>KY(e));else if(Array.isArray(o))t.anyOf=o.map(e=>KY(e));else if(Array.isArray(s))t.allOf=s.map(e=>KY(e));else{if(i===void 0)throw Error(`JSON schema must have a type defined if anyOf/oneOf/allOf are not used`);t.type=i}let c=oK(e,`description`);c!==void 0&&(t.description=c);let l=oK(e,`title`);if(l!==void 0&&(t.title=l),i===`object`){let n=oK(e,`properties`)||{};t.properties=Object.fromEntries(Object.entries(n).map(([e,t])=>[e,KY(t)])),oK(e,`additionalProperties`),t.additionalProperties=!1;let r=oK(e,`required`);r!==void 0&&(t.required=r)}else if(i===`string`){let n=oK(e,`format`);n!==void 0&&UY.has(n)?t.format=n:n!==void 0&&(e.format=n)}else if(i===`array`){let n=oK(e,`items`);n!==void 0&&(t.items=KY(n));let r=oK(e,`minItems`);r!==void 0&&(r===0||r===1)?t.minItems=r:r!==void 0&&(e.minItems=r)}if(Object.keys(e).length>0){let n=t.description;t.description=(n?n+`
212
-
213
- `:``)+`{`+Object.entries(e).map(([e,t])=>`${e}: ${JSON.stringify(t)}`).join(`, `)+`}`}return t}var qY={"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},JY=4096;function YY(e){return e?Object.entries(qY).find(([t])=>e.startsWith(t))?.[1]??JY:JY}function XY(e){return!!(e.tools&&e.tools.length>0)}function ZY(e){for(let t of e.messages??[])if(typeof t.content!=`string`){for(let e of t.content??[])if(typeof e==`object`&&e&&e.type===`document`&&typeof e.citations==`object`&&e.citations?.enabled)return!0}return!1}function QY(e){return!!(e.thinking&&(e.thinking.type===`enabled`||e.thinking.type===`adaptive`))}function $Y(e){return!!e.context_management?.edits?.some(e=>e.type===`compact_20260112`)}function eX(e){return`input_schema`in e}function tX(e){return typeof e==`object`&&!!e&&`type`in e&&(`name`in e||`mcp_server_name`in e)&&typeof e.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(t=>typeof e.type==`string`&&e.type.startsWith(t))}function nX(e,t,...n){return Array.from(new Set([...e??[],...t??[],...n.flatMap(e=>Array.from(e))]))}function rX(e){if(typeof e.content==`string`)return e.content;if(Array.isArray(e.content)&&e.content.length>=1&&`input`in e.content[0])return typeof e.content[0].input==`string`?e.content[0].input:JSON.stringify(e.content[0].input);if(Array.isArray(e.content)&&e.content.length>=1&&`text`in e.content[0]&&typeof e.content[0].text==`string`)return e.content[0].text}var iX=class extends xw{static lc_name(){return`ChatAnthropic`}get lc_secrets(){return{anthropicApiKey:`ANTHROPIC_API_KEY`,apiKey:`ANTHROPIC_API_KEY`}}get lc_aliases(){return{modelName:`model`}}lc_serializable=!0;anthropicApiKey;apiKey;apiUrl;temperature;topK;topP;maxTokens;modelName=`claude-sonnet-4-5-20250929`;model=`claude-sonnet-4-5-20250929`;invocationKwargs;stopSequences;streaming=!1;clientOptions;thinking={type:`disabled`};contextManagement;outputConfig;inferenceGeo;batchClient;streamingClient;streamUsage=!0;betas;createClient;constructor(e,t){let n=typeof e==`string`?{...t??{},model:e}:e??{};if(super(n??{}),this._addVersion(`@langchain/anthropic`,`1.3.29`),this.anthropicApiKey=n?.apiKey??n?.anthropicApiKey??pr(`ANTHROPIC_API_KEY`),!this.anthropicApiKey&&!n?.createClient)throw Error(`Anthropic API key not found`);this.clientOptions=n?.clientOptions??{},this.apiKey=this.anthropicApiKey,this.apiUrl=n?.anthropicApiUrl,this.modelName=n?.model??n?.modelName??this.model,this.model=this.modelName,this.invocationKwargs=n?.invocationKwargs??{},this.topP=n?.topP??this.topP,this.temperature=n?.temperature??this.temperature,this.topK=n?.topK??this.topK,this.maxTokens=n?.maxTokens??YY(this.model),this.stopSequences=n?.stopSequences??this.stopSequences,this.streaming=n?.streaming??!1,this.streamUsage=n?.streamUsage??this.streamUsage,this.thinking=n?.thinking??this.thinking,this.contextManagement=n?.contextManagement??this.contextManagement,this.outputConfig=n?.outputConfig??this.outputConfig,this.inferenceGeo=n?.inferenceGeo??this.inferenceGeo,this.betas=n?.betas??this.betas,this.createClient=n?.createClient??(e=>new HY(e))}getLsParams(e){let t=this.invocationParams(e);return{ls_provider:`anthropic`,ls_model_name:this.model,ls_model_type:`chat`,ls_temperature:t.temperature??void 0,ls_max_tokens:t.max_tokens??void 0,ls_stop:e.stop}}formatStructuredToolToAnthropic(e){if(e)return e.map(e=>{if(GE(e)&&e.extras?.providerToolDefinition)return e.extras.providerToolDefinition;if(tX(e)||eX(e))return e;if(oC(e))return{name:e.function.name,description:e.function.description,input_schema:e.function.parameters};if(GE(e))return{name:e.name,description:e.description,input_schema:Mm(e.schema)?Bv(e.schema):e.schema,...e.extras?qW.parse(e.extras):{}};throw Error(`Unknown tool type passed to ChatAnthropic: ${JSON.stringify(e,null,2)}`)})}bindTools(e,t){return this.withConfig({tools:this.formatStructuredToolToAnthropic(e),...t})}invocationParams(e){let t=KW(e?.tool_choice),n=e?.tools?.reduce((e,t)=>{if(typeof t==`object`&&`type`in t&&t.type in JW){let n=JW[t.type];if(!e.includes(n))return[...e,n]}return e},[]),r=(()=>{let t={...this.outputConfig,...e?.outputConfig};return e?.outputFormat&&!t.format&&(t.format=e.outputFormat),Object.keys(t).length>0?t:void 0})(),i=this.contextManagement?.edits?.some(e=>e.type===`compact_20260112`)?[`compact-2026-01-12`]:[],a=xG(this.model,r),o={model:this.model,stop_sequences:e?.stop??this.stopSequences,stream:this.streaming,max_tokens:this.maxTokens,tools:this.formatStructuredToolToAnthropic(e?.tools),tool_choice:t,thinking:this.thinking,context_management:this.contextManagement,...this.invocationKwargs,container:e?.container,betas:nX(this.betas,e?.betas,n??[],i,a),output_config:r,inference_geo:e?.inferenceGeo??this.inferenceGeo,mcp_servers:e?.mcp_servers,cache_control:e?.cache_control};return SG({model:this.model,thinking:this.thinking,topK:this.topK,topP:this.topP,temperature:this.temperature}),Object.assign(o,CG({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,t,n){let r=this.invocationParams(t),i=_G(e),a={...r,...i,stream:!0},o=!XY(a)&&!ZY(a)&&!QY(a)&&!$Y(a),s=await this.createStreamWithRetry(a,{headers:t.headers,signal:t.signal});for await(let e of s){if(t.signal?.aborted){s.controller.abort();return}let r=this.streamUsage??t.streamUsage,i=wG(e,{streamUsage:r,coerceContentToString:o});if(!i)continue;let{chunk:a}=i,c=rX(a),l=new Xl({message:new Xt({content:a.content,additional_kwargs:a.additional_kwargs,tool_call_chunks:a.tool_call_chunks,usage_metadata:r?a.usage_metadata:void 0,response_metadata:a.response_metadata,id:a.id}),text:c??``});yield l,await n?.handleLLMNewToken(c??``,void 0,void 0,void 0,void 0,{chunk:l})}}async*_streamChatModelEvents(e,t,n){let r=this.invocationParams(t),i=_G(e),a={...r,...i,stream:!0},o=await this.createStreamWithRetry(a,{headers:t.headers,signal:t.signal}),s=this.streamUsage??t.streamUsage;yield*AG(async function*(e,t){for await(let n of e){if(t?.aborted){e.controller?.abort();return}yield n}}(o,t.signal),{streamUsage:s??!0})}async _generateNonStreaming(e,t,n){let r=_G(e),{content:i,...a}=await this.completionWithRetry({...t,stream:!1,...r},n),o=TG(i,a),{role:s,type:c,...l}=a;return{generations:o,llmOutput:l}}async _generate(e,t,n){if(t.signal?.throwIfAborted(),this.stopSequences&&t.stop)throw Error(`"stopSequence" parameter found in input and default params`);let r=this.invocationParams(t);if(r.stream){let r,i=this._streamResponseChunks(e,t,n);for await(let e of i)r=r===void 0?e:r.concat(e);if(r===void 0)throw Error(`No chunks returned from Anthropic API.`);return{generations:[{text:r.text,message:r.message}]}}else return this._generateNonStreaming(e,r,{signal:t.signal,headers:t.headers})}async createStreamWithRetry(e,t){if(!this.streamingClient){let e=this.apiUrl?{baseURL:this.apiUrl}:void 0;this.streamingClient=this.createClient({dangerouslyAllowBrowser:!0,...this.clientOptions,...e,apiKey:this.apiKey,maxRetries:0})}let{betas:n,...r}=e;return this.caller.call(async()=>{try{return e?.betas?.length?await this.streamingClient.beta.messages.create({...r,betas:n,...this.invocationKwargs,stream:!0},t):await this.streamingClient.messages.create({...r,...this.invocationKwargs,stream:!0},t)}catch(e){throw OG(e)}})}async completionWithRetry(e,t){if(!this.batchClient){let e=this.apiUrl?{baseURL:this.apiUrl}:void 0;this.batchClient=this.createClient({dangerouslyAllowBrowser:!0,...this.clientOptions,...e,apiKey:this.apiKey,maxRetries:0})}let{betas:n,...r}=e;return this.caller.callWithOptions({signal:t.signal??void 0},async()=>{try{return e?.betas?.length?await this.batchClient.beta.messages.create({...r,...this.invocationKwargs,betas:n},t):await this.batchClient.messages.create({...r,...this.invocationKwargs},t)}catch(e){throw OG(e)}})}_llmType(){return`anthropic`}get profile(){return kG[this.model]??{}}withStructuredOutput(e,t){let n,r,{schema:i,name:a,includeRaw:o}={...t,schema:e},s=t?.method??`functionCalling`;if(s===`jsonMode`&&(console.warn(`"jsonMode" is not supported for Anthropic models. Falling back to "jsonSchema".`),s=`jsonSchema`),s===`jsonSchema`){r=UC(i);let e=GY(Bv(i));n=this.withConfig({outputVersion:`v0`,outputConfig:{format:{type:`json_schema`,schema:e}},ls_structured_output_format:{kwargs:{method:`json_schema`},schema:e}})}else if(s===`functionCalling`){let e=a??`extract`,t;if(Mm(i)||$_(i)){let n=Bv(i);t=[{name:e,description:n.description??`A function available to call.`,input_schema:n}]}else typeof i.name==`string`&&typeof i.description==`string`&&typeof i.input_schema==`object`&&i.input_schema!=null?(t=[i],e=i.name):t=[{name:e,description:i.description??``,input_schema:i}];if(r=WC(i,e,WW),this.thinking?.type===`enabled`||this.thinking?.type===`adaptive`){let e="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(e),n=this.withConfig({outputVersion:`v0`,tools:t,ls_structured_output_format:{kwargs:{method:`functionCalling`},schema:Bv(i)}}),n=n.pipe(t=>{if(!t.tool_calls||t.tool_calls.length===0)throw Error(e);return t})}else n=this.withConfig({outputVersion:`v0`,tools:t,tool_choice:{type:`tool`,name:e},ls_structured_output_format:{kwargs:{method:`functionCalling`},schema:Bv(i)}})}else throw TypeError(`Unrecognized structured output method '${s}'. Expected 'functionCalling' or 'jsonSchema'`);return GC(n,r,o,o?`StructuredOutputRunnable`:`ChatAnthropicStructuredOutput`)}},aX=class extends iX{};JD(`command`,[V({command:iO(`view`),path:lD()}),V({command:iO(`create`),path:lD(),file_text:lD()}),V({command:iO(`str_replace`),path:lD(),old_str:lD(),new_str:lD()}),V({command:iO(`insert`),path:lD(),insert_line:jD(),insert_text:lD()}),V({command:iO(`delete`),path:lD()}),V({command:iO(`rename`),old_path:lD(),new_path:lD()})]),JD(`command`,[V({command:iO(`view`),path:lD(),view_range:QD([jD(),jD()]).optional()}),V({command:iO(`str_replace`),path:lD(),old_str:lD(),new_str:lD()}),V({command:iO(`create`),path:lD(),file_text:lD()}),V({command:iO(`insert`),path:lD(),insert_line:jD(),new_str:lD()})]);var oX=QD([jD(),jD()]),sX=V({action:iO(`screenshot`)}),cX=V({action:iO(`left_click`),coordinate:oX}),lX=V({action:iO(`right_click`),coordinate:oX}),uX=V({action:iO(`middle_click`),coordinate:oX}),dX=V({action:iO(`double_click`),coordinate:oX}),fX=V({action:iO(`triple_click`),coordinate:oX}),pX=V({action:iO(`left_click_drag`),start_coordinate:oX,end_coordinate:oX}),mX=V({action:iO(`left_mouse_down`),coordinate:oX}),hX=V({action:iO(`left_mouse_up`),coordinate:oX}),gX=V({action:iO(`scroll`),coordinate:oX,scroll_direction:nO([`up`,`down`,`left`,`right`]),scroll_amount:jD()}),_X=V({action:iO(`type`),text:lD()}),vX=V({action:iO(`key`),key:lD()}),yX=V({action:iO(`mouse_move`),coordinate:oX}),bX=V({action:iO(`hold_key`),key:lD()}),xX=V({action:iO(`wait`),duration:jD().optional()}),SX=V({action:iO(`zoom`),region:QD([jD(),jD(),jD(),jD()])});JD(`action`,[sX,cX,lX,uX,dX,fX,pX,mX,hX,gX,_X,vX,yX,bX,xX]),JD(`action`,[sX,cX,lX,uX,dX,fX,pX,mX,hX,gX,_X,vX,yX,bX,xX,SX]),KD([V({command:lD().describe(`The bash command to run`)}),V({restart:iO(!0).describe(`Set to true to restart the bash session`)})]);for(var CX=[],wX=0;wX<256;++wX)CX.push((wX+256).toString(16).slice(1));function TX(e,t=0){return(CX[e[t+0]]+CX[e[t+1]]+CX[e[t+2]]+CX[e[t+3]]+`-`+CX[e[t+4]]+CX[e[t+5]]+`-`+CX[e[t+6]]+CX[e[t+7]]+`-`+CX[e[t+8]]+CX[e[t+9]]+`-`+CX[e[t+10]]+CX[e[t+11]]+CX[e[t+12]]+CX[e[t+13]]+CX[e[t+14]]+CX[e[t+15]]).toLowerCase()}var EX,DX=new Uint8Array(16);function OX(){if(!EX&&(EX=typeof crypto<`u`&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!EX))throw Error(`crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported`);return EX(DX)}var kX={randomUUID:typeof crypto<`u`&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function AX(e,t,n){if(kX.randomUUID&&!t&&!e)return kX.randomUUID();e||={};var r=e.random||(e.rng||OX)();if(r[6]=r[6]&15|64,r[8]=r[8]&63|128,t){n||=0;for(var i=0;i<16;++i)t[n+i]=r[i];return t}return TX(r)}function jX(e,t){return new Xt({content:e.content??``,additional_kwargs:e.thinking&&e.thinking!==``?{reasoning_content:e.thinking}:{},tool_call_chunks:e.tool_calls?.map(e=>({name:e.function.name,args:JSON.stringify(e.function.arguments),type:`tool_call_chunk`,index:0,id:AX()})),response_metadata:{...t?.responseMetadata,model_provider:`ollama`},usage_metadata:t?.usageMetadata})}function MX(e){let t=e.match(/^data:.*?;base64,(.*)$/);return t?t[1]:``}function NX(e){if(typeof e.content==`string`){if(e.tool_calls?.length){let t=e.tool_calls.map(e=>({id:e.id,type:`function`,function:{name:e.name,arguments:e.args}}));return[{role:`assistant`,content:e.content,tool_calls:t}]}return[{role:`assistant`,content:e.content}]}let t=e.content.filter(e=>e.type===`text`&&typeof e.text==`string`).map(e=>({role:`assistant`,content:e.text})),n;if(e.content.find(e=>e.type===`tool_use`)&&e.tool_calls?.length){let t=e.tool_calls?.map(e=>({id:e.id,type:`function`,function:{name:e.name,arguments:e.args}}));t&&(n={role:`assistant`,tool_calls:t,content:``})}else if(e.content.find(e=>e.type===`tool_use`)&&!e.tool_calls?.length)throw Error(`'tool_use' content type is not supported without tool calls.`);return[...t,...n?[n]:[]]}function PX(e){return typeof e.content==`string`?[{role:`user`,content:e.content}]:e.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:[MX(e.image_url)]};if(e.image_url.url&&typeof e.image_url.url==`string`)return{role:`user`,content:``,images:[MX(e.image_url.url)]}}throw Error(`Unsupported content type: ${e.type}`)})}function FX(e){if(typeof e.content==`string`)return[{role:`system`,content:e.content}];if(e.content.every(e=>e.type===`text`&&typeof e.text==`string`))return e.content.map(e=>({role:`system`,content:e.text}));throw Error(`Unsupported content type(s): ${e.content.map(e=>e.type).join(`, `)}`)}function IX(e){if(typeof e.content!=`string`)throw Error(`Non string tool message content is not supported`);return[{role:`tool`,content:e.content}]}function LX(e){return e.flatMap(e=>{if([`human`,`generic`].includes(e._getType()))return PX(e);if(e._getType()===`ai`)return NX(e);if(e._getType()===`system`)return FX(e);if(e._getType()===`tool`)return IX(e);throw Error(`Unsupported message type: ${e._getType()}`)})}var RX=typeof globalThis<`u`&&globalThis||typeof self<`u`&&self||typeof global<`u`&&global||{},zX={searchParams:`URLSearchParams`in RX,iterable:`Symbol`in RX&&`iterator`in Symbol,blob:`FileReader`in RX&&`Blob`in RX&&(function(){try{return new Blob,!0}catch{return!1}})(),formData:`FormData`in RX,arrayBuffer:`ArrayBuffer`in RX};function BX(e){return e&&DataView.prototype.isPrototypeOf(e)}if(zX.arrayBuffer)var VX=[`[object Int8Array]`,`[object Uint8Array]`,`[object Uint8ClampedArray]`,`[object Int16Array]`,`[object Uint16Array]`,`[object Int32Array]`,`[object Uint32Array]`,`[object Float32Array]`,`[object Float64Array]`],HX=ArrayBuffer.isView||function(e){return e&&VX.indexOf(Object.prototype.toString.call(e))>-1};function UX(e){if(typeof e!=`string`&&(e=String(e)),/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(e)||e===``)throw TypeError(`Invalid character in header field name: "`+e+`"`);return e.toLowerCase()}function WX(e){return typeof e!=`string`&&(e=String(e)),e}function GX(e){var t={next:function(){var t=e.shift();return{done:t===void 0,value:t}}};return zX.iterable&&(t[Symbol.iterator]=function(){return t}),t}function KX(e){this.map={},e instanceof KX?e.forEach(function(e,t){this.append(t,e)},this):Array.isArray(e)?e.forEach(function(e){if(e.length!=2)throw TypeError(`Headers constructor: expected name/value pair to be length 2, found`+e.length);this.append(e[0],e[1])},this):e&&Object.getOwnPropertyNames(e).forEach(function(t){this.append(t,e[t])},this)}KX.prototype.append=function(e,t){e=UX(e),t=WX(t);var n=this.map[e];this.map[e]=n?n+`, `+t:t},KX.prototype.delete=function(e){delete this.map[UX(e)]},KX.prototype.get=function(e){return e=UX(e),this.has(e)?this.map[e]:null},KX.prototype.has=function(e){return this.map.hasOwnProperty(UX(e))},KX.prototype.set=function(e,t){this.map[UX(e)]=WX(t)},KX.prototype.forEach=function(e,t){for(var n in this.map)this.map.hasOwnProperty(n)&&e.call(t,this.map[n],n,this)},KX.prototype.keys=function(){var e=[];return this.forEach(function(t,n){e.push(n)}),GX(e)},KX.prototype.values=function(){var e=[];return this.forEach(function(t){e.push(t)}),GX(e)},KX.prototype.entries=function(){var e=[];return this.forEach(function(t,n){e.push([n,t])}),GX(e)},zX.iterable&&(KX.prototype[Symbol.iterator]=KX.prototype.entries);function qX(e){if(!e._noBody){if(e.bodyUsed)return Promise.reject(TypeError(`Already read`));e.bodyUsed=!0}}function JX(e){return new Promise(function(t,n){e.onload=function(){t(e.result)},e.onerror=function(){n(e.error)}})}function YX(e){var t=new FileReader,n=JX(t);return t.readAsArrayBuffer(e),n}function XX(e){var t=new FileReader,n=JX(t),r=/charset=([A-Za-z0-9_-]+)/.exec(e.type),i=r?r[1]:`utf-8`;return t.readAsText(e,i),n}function ZX(e){for(var t=new Uint8Array(e),n=Array(t.length),r=0;r<t.length;r++)n[r]=String.fromCharCode(t[r]);return n.join(``)}function QX(e){if(e.slice)return e.slice(0);var t=new Uint8Array(e.byteLength);return t.set(new Uint8Array(e)),t.buffer}function $X(){return this.bodyUsed=!1,this._initBody=function(e){this.bodyUsed=this.bodyUsed,this._bodyInit=e,e?typeof e==`string`?this._bodyText=e:zX.blob&&Blob.prototype.isPrototypeOf(e)?this._bodyBlob=e:zX.formData&&FormData.prototype.isPrototypeOf(e)?this._bodyFormData=e:zX.searchParams&&URLSearchParams.prototype.isPrototypeOf(e)?this._bodyText=e.toString():zX.arrayBuffer&&zX.blob&&BX(e)?(this._bodyArrayBuffer=QX(e.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):zX.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(e)||HX(e))?this._bodyArrayBuffer=QX(e):this._bodyText=e=Object.prototype.toString.call(e):(this._noBody=!0,this._bodyText=``),this.headers.get(`content-type`)||(typeof e==`string`?this.headers.set(`content-type`,`text/plain;charset=UTF-8`):this._bodyBlob&&this._bodyBlob.type?this.headers.set(`content-type`,this._bodyBlob.type):zX.searchParams&&URLSearchParams.prototype.isPrototypeOf(e)&&this.headers.set(`content-type`,`application/x-www-form-urlencoded;charset=UTF-8`))},zX.blob&&(this.blob=function(){var e=qX(this);if(e)return e;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw Error(`could not read FormData body as blob`);return Promise.resolve(new Blob([this._bodyText]))}),this.arrayBuffer=function(){if(this._bodyArrayBuffer)return qX(this)||(ArrayBuffer.isView(this._bodyArrayBuffer)?Promise.resolve(this._bodyArrayBuffer.buffer.slice(this._bodyArrayBuffer.byteOffset,this._bodyArrayBuffer.byteOffset+this._bodyArrayBuffer.byteLength)):Promise.resolve(this._bodyArrayBuffer));if(zX.blob)return this.blob().then(YX);throw Error(`could not read as ArrayBuffer`)},this.text=function(){var e=qX(this);if(e)return e;if(this._bodyBlob)return XX(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(ZX(this._bodyArrayBuffer));if(this._bodyFormData)throw Error(`could not read FormData body as text`);return Promise.resolve(this._bodyText)},zX.formData&&(this.formData=function(){return this.text().then(rZ)}),this.json=function(){return this.text().then(JSON.parse)},this}var eZ=[`CONNECT`,`DELETE`,`GET`,`HEAD`,`OPTIONS`,`PATCH`,`POST`,`PUT`,`TRACE`];function tZ(e){var t=e.toUpperCase();return eZ.indexOf(t)>-1?t:e}function nZ(e,t){if(!(this instanceof nZ))throw TypeError(`Please use the "new" operator, this DOM object constructor cannot be called as a function.`);t||={};var n=t.body;if(e instanceof nZ){if(e.bodyUsed)throw TypeError(`Already read`);this.url=e.url,this.credentials=e.credentials,t.headers||(this.headers=new KX(e.headers)),this.method=e.method,this.mode=e.mode,this.signal=e.signal,!n&&e._bodyInit!=null&&(n=e._bodyInit,e.bodyUsed=!0)}else this.url=String(e);if(this.credentials=t.credentials||this.credentials||`same-origin`,(t.headers||!this.headers)&&(this.headers=new KX(t.headers)),this.method=tZ(t.method||this.method||`GET`),this.mode=t.mode||this.mode||null,this.signal=t.signal||this.signal||function(){if(`AbortController`in RX)return new AbortController().signal}(),this.referrer=null,(this.method===`GET`||this.method===`HEAD`)&&n)throw TypeError(`Body not allowed for GET or HEAD requests`);if(this._initBody(n),(this.method===`GET`||this.method===`HEAD`)&&(t.cache===`no-store`||t.cache===`no-cache`)){var r=/([?&])_=[^&]*/;if(r.test(this.url))this.url=this.url.replace(r,`$1_=`+new Date().getTime());else{var i=/\?/;this.url+=(i.test(this.url)?`&`:`?`)+`_=`+new Date().getTime()}}}nZ.prototype.clone=function(){return new nZ(this,{body:this._bodyInit})};function rZ(e){var t=new FormData;return e.trim().split(`&`).forEach(function(e){if(e){var n=e.split(`=`),r=n.shift().replace(/\+/g,` `),i=n.join(`=`).replace(/\+/g,` `);t.append(decodeURIComponent(r),decodeURIComponent(i))}}),t}function iZ(e){var t=new KX;return e.replace(/\r?\n[\t ]+/g,` `).split(`\r`).map(function(e){return e.indexOf(`
214
- `)===0?e.substr(1,e.length):e}).forEach(function(e){var n=e.split(`:`),r=n.shift().trim();if(r){var i=n.join(`:`).trim();try{t.append(r,i)}catch(e){console.warn(`Response `+e.message)}}}),t}$X.call(nZ.prototype);function aZ(e,t){if(!(this instanceof aZ))throw TypeError(`Please use the "new" operator, this DOM object constructor cannot be called as a function.`);if(t||={},this.type=`default`,this.status=t.status===void 0?200:t.status,this.status<200||this.status>599)throw 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=t.statusText===void 0?``:``+t.statusText,this.headers=new KX(t.headers),this.url=t.url||``,this._initBody(e)}$X.call(aZ.prototype),aZ.prototype.clone=function(){return new aZ(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new KX(this.headers),url:this.url})},aZ.error=function(){var e=new aZ(null,{status:200,statusText:``});return e.ok=!1,e.status=0,e.type=`error`,e};var oZ=[301,302,303,307,308];aZ.redirect=function(e,t){if(oZ.indexOf(t)===-1)throw RangeError(`Invalid status code`);return new aZ(null,{status:t,headers:{location:e}})};var sZ=RX.DOMException;try{new sZ}catch{sZ=function(e,t){this.message=e,this.name=t;var n=Error(e);this.stack=n.stack},sZ.prototype=Object.create(Error.prototype),sZ.prototype.constructor=sZ}function cZ(e,t){return new Promise(function(n,r){var i=new nZ(e,t);if(i.signal&&i.signal.aborted)return r(new sZ(`Aborted`,`AbortError`));var a=new XMLHttpRequest;function o(){a.abort()}a.onload=function(){var e={statusText:a.statusText,headers:iZ(a.getAllResponseHeaders()||``)};i.url.indexOf(`file://`)===0&&(a.status<200||a.status>599)?e.status=200:e.status=a.status,e.url=`responseURL`in a?a.responseURL:e.headers.get(`X-Request-URL`);var t=`response`in a?a.response:a.responseText;setTimeout(function(){n(new aZ(t,e))},0)},a.onerror=function(){setTimeout(function(){r(TypeError(`Network request failed`))},0)},a.ontimeout=function(){setTimeout(function(){r(TypeError(`Network request timed out`))},0)},a.onabort=function(){setTimeout(function(){r(new sZ(`Aborted`,`AbortError`))},0)};function s(e){try{return e===``&&RX.location.href?RX.location.href:e}catch{return e}}if(a.open(i.method,s(i.url),!0),i.credentials===`include`?a.withCredentials=!0:i.credentials===`omit`&&(a.withCredentials=!1),`responseType`in a&&(zX.blob?a.responseType=`blob`:zX.arrayBuffer&&(a.responseType=`arraybuffer`)),t&&typeof t.headers==`object`&&!(t.headers instanceof KX||RX.Headers&&t.headers instanceof RX.Headers)){var c=[];Object.getOwnPropertyNames(t.headers).forEach(function(e){c.push(UX(e)),a.setRequestHeader(e,WX(t.headers[e]))}),i.headers.forEach(function(e,t){c.indexOf(t)===-1&&a.setRequestHeader(t,e)})}else i.headers.forEach(function(e,t){a.setRequestHeader(t,e)});i.signal&&(i.signal.addEventListener(`abort`,o),a.onreadystatechange=function(){a.readyState===4&&i.signal.removeEventListener(`abort`,o)}),a.send(i._bodyInit===void 0?null:i._bodyInit)})}cZ.polyfill=!0,RX.fetch||(RX.fetch=cZ,RX.Headers=KX,RX.Request=nZ,RX.Response=aZ);var lZ=`11434`,uZ=`http://127.0.0.1:${lZ}`,dZ=`0.6.3`,fZ=Object.defineProperty,pZ=(e,t,n)=>t in e?fZ(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,mZ=(e,t,n)=>(pZ(e,typeof t==`symbol`?t:t+``,n),n),hZ=class e extends Error{constructor(t,n){super(t),this.error=t,this.status_code=n,this.name=`ResponseError`,Error.captureStackTrace&&Error.captureStackTrace(this,e)}},gZ=class{constructor(e,t,n){mZ(this,`abortController`),mZ(this,`itr`),mZ(this,`doneCallback`),this.abortController=e,this.itr=t,this.doneCallback=n}abort(){this.abortController.abort()}async*[Symbol.asyncIterator](){for await(let e of this.itr){if(`error`in e)throw Error(e.error);if(yield e,e.done||e.status===`success`){this.doneCallback();return}}throw Error(`Did not receive done or success response in stream.`)}},_Z=async e=>{if(e.ok)return;let t=`Error ${e.status}: ${e.statusText}`,n=null;if(e.headers.get(`content-type`)?.includes(`application/json`))try{n=await e.json(),t=n.error||t}catch{console.log(`Failed to parse error response as JSON`)}else try{console.log(`Getting text from response`),t=await e.text()||t}catch{console.log(`Failed to get text from error response`)}throw new hZ(t,e.status)};function vZ(){if(typeof window<`u`&&window.navigator){let e=navigator;return`userAgentData`in e&&e.userAgentData?.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 yZ(e){if(e instanceof Headers){let t={};return e.forEach((e,n)=>{t[n]=e}),t}else if(Array.isArray(e))return Object.fromEntries(e);else return e||{}}var bZ=(e,t)=>e[t],xZ=async(e,t,n={})=>{let r={"Content-Type":`application/json`,Accept:`application/json`,"User-Agent":`ollama-js/${dZ} (${vZ()})`};n.headers=yZ(n.headers);try{let e=new URL(t);if(e.protocol===`https:`&&e.hostname===`ollama.com`){let e=typeof process==`object`&&process!==null?bZ({},`OLLAMA_API_KEY`):void 0;!(n.headers.authorization||n.headers.Authorization)&&e&&(n.headers.Authorization=`Bearer ${e}`)}}catch(e){console.error(`error parsing url`,e)}let i=Object.fromEntries(Object.entries(n.headers).filter(([e])=>!Object.keys(r).some(t=>t.toLowerCase()===e.toLowerCase())));return n.headers={...r,...i},e(t,n)},SZ=async(e,t,n)=>{let r=await xZ(e,t,{headers:n?.headers});return await _Z(r),r},CZ=async(e,t,n,r)=>{let i=await xZ(e,t,{method:`POST`,body:(e=>typeof e==`object`&&!!e&&!Array.isArray(e))(n)?JSON.stringify(n):n,signal:r?.signal,headers:r?.headers});return await _Z(i),i},wZ=async(e,t,n,r)=>{let i=await xZ(e,t,{method:`DELETE`,body:JSON.stringify(n),headers:r?.headers});return await _Z(i),i},TZ=async function*(e){let t=new TextDecoder(`utf-8`),n=``,r=e.getReader();for(;;){let{done:e,value:i}=await r.read();if(e)break;n+=t.decode(i,{stream:!0});let a=n.split(`
215
- `);n=a.pop()??``;for(let e of a)try{yield JSON.parse(e)}catch{console.warn(`invalid json: `,e)}}n+=t.decode();for(let e of n.split(`
216
- `).filter(e=>e!==``))try{yield JSON.parse(e)}catch{console.warn(`invalid json: `,e)}},EZ=e=>{if(!e)return uZ;let t=e.includes(`://`);e.startsWith(`:`)&&(e=`http://127.0.0.1${e}`,t=!0),t||(e=`http://${e}`);let n=new URL(e),r=n.port;r||=t?n.protocol===`https:`?`443`:`80`:lZ;let i=``;n.username&&(i=n.username,n.password&&(i+=`:${n.password}`),i+=`@`);let a=`${n.protocol}//${i}${n.hostname}:${r}${n.pathname}`;return a.endsWith(`/`)&&(a=a.slice(0,-1)),a},DZ=Object.defineProperty,OZ=(e,t,n)=>t in e?DZ(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,kZ=(e,t,n)=>(OZ(e,typeof t==`symbol`?t:t+``,n),n),AZ=class{constructor(e){kZ(this,`config`),kZ(this,`fetch`),kZ(this,`ongoingStreamedRequests`,[]),this.config={host:``,headers:e?.headers},e?.proxy||(this.config.host=EZ(e?.host??uZ)),this.fetch=e?.fetch??fetch}abort(){for(let e of this.ongoingStreamedRequests)e.abort();this.ongoingStreamedRequests.length=0}async processStreamableRequest(e,t){t.stream=t.stream??!1;let n=`${this.config.host}/api/${e}`;if(t.stream){let e=new AbortController,r=await CZ(this.fetch,n,t,{signal:e.signal,headers:this.config.headers});if(!r.body)throw Error(`Missing body`);let i=new gZ(e,TZ(r.body),()=>{let e=this.ongoingStreamedRequests.indexOf(i);e>-1&&this.ongoingStreamedRequests.splice(e,1)});return this.ongoingStreamedRequests.push(i),i}return await(await CZ(this.fetch,n,t,{headers:this.config.headers})).json()}async encodeImage(e){if(typeof e!=`string`){let t=new Uint8Array(e),n=``,r=t.byteLength;for(let e=0;e<r;e++)n+=String.fromCharCode(t[e]);return btoa(n)}return e}async generate(e){return e.images&&=await Promise.all(e.images.map(this.encodeImage.bind(this))),this.processStreamableRequest(`generate`,e)}async chat(e){if(e.messages)for(let t of e.messages)t.images&&=await Promise.all(t.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 wZ(this.fetch,`${this.config.host}/api/delete`,{name:e.model},{headers:this.config.headers}),{status:`success`}}async copy(e){return await CZ(this.fetch,`${this.config.host}/api/copy`,{...e},{headers:this.config.headers}),{status:`success`}}async list(){return await(await SZ(this.fetch,`${this.config.host}/api/tags`,{headers:this.config.headers})).json()}async show(e){return await(await CZ(this.fetch,`${this.config.host}/api/show`,{...e},{headers:this.config.headers})).json()}async embed(e){return await(await CZ(this.fetch,`${this.config.host}/api/embed`,{...e},{headers:this.config.headers})).json()}async embeddings(e){return await(await CZ(this.fetch,`${this.config.host}/api/embeddings`,{...e},{headers:this.config.headers})).json()}async ps(){return await(await SZ(this.fetch,`${this.config.host}/api/ps`,{headers:this.config.headers})).json()}async version(){return await(await SZ(this.fetch,`${this.config.host}/api/version`,{headers:this.config.headers})).json()}async webSearch(e){if(!e.query||e.query.length===0)throw Error(`Query is required`);return await(await CZ(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 Error(`URL is required`);return await(await CZ(this.fetch,`https://ollama.com/api/web_fetch`,{...e},{headers:this.config.headers})).json()}};new AZ;var jZ=class extends xw{static lc_name(){return`ChatOllama`}model=`llama3`;numa;numCtx;numBatch;numGpu;mainGpu;lowVram;f16Kv;logitsAll;vocabOnly;useMmap;useMlock;embeddingOnly;numThread;numKeep;seed;numPredict;topK;topP;tfsZ;typicalP;repeatLastN;temperature;repeatPenalty;presencePenalty;frequencyPenalty;mirostat;mirostatTau;mirostatEta;penalizeNewline;streaming;format;keepAlive;client;checkOrPullModel=!1;baseUrl=`http://127.0.0.1:11434`;think;constructor(e,t){let n=typeof e==`string`?{...t??{},model:e}:e??{};super(n),this._addVersion(`@langchain/ollama`,`1.2.6`),this.baseUrl=n.baseUrl??pr(`OLLAMA_BASE_URL`)??this.baseUrl,this.client=new AZ({fetch:n.fetch,host:this.baseUrl,headers:n.headers}),this.model=n.model??this.model,this.numa=n.numa,this.numCtx=n.numCtx,this.numBatch=n.numBatch,this.numGpu=n.numGpu,this.mainGpu=n.mainGpu,this.lowVram=n.lowVram,this.f16Kv=n.f16Kv,this.logitsAll=n.logitsAll,this.vocabOnly=n.vocabOnly,this.useMmap=n.useMmap,this.useMlock=n.useMlock,this.embeddingOnly=n.embeddingOnly,this.numThread=n.numThread,this.numKeep=n.numKeep,this.seed=n.seed,this.numPredict=n.numPredict,this.topK=n.topK,this.topP=n.topP,this.tfsZ=n.tfsZ,this.typicalP=n.typicalP,this.repeatLastN=n.repeatLastN,this.temperature=n.temperature,this.repeatPenalty=n.repeatPenalty,this.presencePenalty=n.presencePenalty,this.frequencyPenalty=n.frequencyPenalty,this.mirostat=n.mirostat,this.mirostatTau=n.mirostatTau,this.mirostatEta=n.mirostatEta,this.penalizeNewline=n.penalizeNewline,this.streaming=n.streaming,this.format=n.format,this.keepAlive=n.keepAlive,this.think=n.think,this.checkOrPullModel=n.checkOrPullModel??this.checkOrPullModel}_llmType(){return`ollama`}async pull(e,t){let{stream:n,insecure:r,logProgress:i}={stream:!0,...t};if(n)for await(let t of await this.client.pull({model:e,insecure:r,stream:n}))i&&console.log(t);else{let t=await this.client.pull({model:e,insecure:r});i&&console.log(t)}}bindTools(e,t){return this.withConfig({tools:e.map(e=>ik(e)),...t})}getLsParams(e){let t=this.invocationParams(e);return{ls_provider:`ollama`,ls_model_name:this.model,ls_model_type:`chat`,ls_temperature:t.options?.temperature??void 0,ls_max_tokens:t.options?.num_predict??void 0,ls_stop:e.stop}}invocationParams(e){return{model:this.model,format: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?.stop},tools:e?.tools?.length?e.tools.map(e=>ik(e)):void 0}}async checkModelExistsOnMachine(e){let{models:t}=await this.client.list();return!!t.find(t=>t.name===e||t.name===`${e}:latest`)}async _generate(e,t,n){t.signal?.throwIfAborted(),this.checkOrPullModel&&(await this.checkModelExistsOnMachine(this.model)||await this.pull(this.model,{logProgress:!0}));let r;for await(let i of this._streamResponseChunks(e,t,n))r=r?fl(r,i.message):i.message;let i=new qt({id:r?.id,content:r?.content??``,additional_kwargs:r?.additional_kwargs,tool_calls:r?.tool_calls,response_metadata:r?.response_metadata,usage_metadata:r?.usage_metadata});return{generations:[{text:typeof i.content==`string`?i.content:``,message:i}]}}async*_streamResponseChunks(e,t,n){this.checkOrPullModel&&(await this.checkModelExistsOnMachine(this.model)||await this.pull(this.model,{logProgress:!0}));let r=this.invocationParams(t),i=LX(e),a={input_tokens:0,output_tokens:0,total_tokens:0},o=await this.client.chat({...r,messages:i,stream:!0}),s;for await(let e of o){if(t.signal?.aborted){this.client.abort();return}let{message:r,...i}=e;a.input_tokens+=i.prompt_eval_count??0,a.output_tokens+=i.eval_count??0,a.total_tokens=a.input_tokens+a.output_tokens,s=i;let o=this.think?r.thinking??r.content??``:r.content??``,c=new Xl({text:o,message:jX(r)});yield c,await n?.handleLLMNewToken(o,void 0,void 0,void 0,void 0,{chunk:c})}yield new Xl({text:``,message:new Xt({content:``,response_metadata:{...s,model_provider:`ollama`},usage_metadata:a})})}withStructuredOutput(e,t){let n,r,{schema:i,name:a,includeRaw:o}={...t,schema:e},s=t?.method??`jsonSchema`;if(s===`functionCalling`){let e=a??`extract`,t,o=Bv(i);Mm(i)||$_(i)?t={name:e,description:o.description,parameters:o}:typeof i.name==`string`&&typeof i.parameters==`object`&&i.parameters!=null?(t=i,e=i.name):t={name:e,description:i.description??``,parameters:i},n=this.bindTools([{type:`function`,function:t}]).withConfig({ls_structured_output_format:{kwargs:{method:s},schema:Mm(i)||$_(i)?o:i}}),r=WC(i,e)}else if(s===`jsonMode`||s===`jsonSchema`){r=UC(i);let e=Bv(i);n=this.withConfig({format:s===`jsonMode`?`json`:e,ls_structured_output_format:{kwargs:{method:s},schema:e}})}else throw TypeError(`Unrecognized structured output method '${s}'. Expected one of 'functionCalling', 'jsonMode', or 'jsonSchema'`);return GC(n,r,o,o?`StructuredOutputRunnable`:`ChatOllamaStructuredOutput`)}},MZ=e=>n.includes(e),NZ=e=>r.includes(e),PZ=e=>{let{executeQuery:t,search:n,grep:i,readFile:a}=e;return[PO(async({query:e,limit:t,groupByProcess:r})=>{let i=t??10,a=r??!0,o;try{o=await n(e,{limit:i,enrich:!0})}catch{return`Search is not available. Please load a repository first.`}if(o.length===0)return`No code found matching "${e}". Try different terms or use grep for exact patterns.`;let s=o.slice(0,i).map((e,t)=>{let n=e.nodeId||``,r=e.name||e.filePath?.split(`/`).pop()||`Unknown`,i=e.label||`File`,a=e.filePath||``,o=e.startLine?` (lines ${e.startLine}-${e.endLine})`:``,s=e.sources?.join(`+`)||`hybrid`,c=e.score?` [score: ${e.score.toFixed(2)}]`:``,l=``;if(e.connections){let t=(e.connections.outgoing||[]).filter(e=>e?.name).slice(0,3),n=(e.connections.incoming||[]).filter(e=>e?.name).slice(0,3),r=(e,t)=>{let n=e.confidence?Math.round(e.confidence*100):100;return t===`out`?`-[${e.type} ${n}%]-> ${e.name}`:`<-[${e.type} ${n}%]- ${e.name}`},i=t.map(e=>r(e,`out`)),a=n.map(e=>r(e,`in`));(i.length||a.length)&&(l=`\n Connections: ${[...i,...a].join(`, `)}`)}let u=e.cluster||`Unclustered`,d=(e.processes||[]).filter(e=>e.id&&e.label);return{idx:t+1,nodeId:n,name:r,label:i,filePath:a,location:o,sources:s,score:c,connections:l,clusterLabel:u,processes:d}}),c=(e,t)=>{let n=t?.step?` (step ${t.step}/${t.stepCount??`?`})`:``;return`[${e.idx}] ${e.label}: ${e.name}${e.score}${n}\n ID: ${e.nodeId}\n File: ${e.filePath}${e.location}\n Cluster: ${e.clusterLabel}\n Found by: ${e.sources}${e.connections}`};if(!a)return`Found ${o.length} matches:\n\n${s.map(e=>c(e)).join(`
217
-
218
- `)}`;let l=new Map,u=`__no_process__`;for(let e of s){if(e.processes.length===0){l.has(u)||l.set(u,{label:`No process`,entries:[]}),l.get(u).entries.push({result:e});continue}for(let t of e.processes)l.has(t.id)||l.set(t.id,{label:t.label,stepCount:t.stepCount,entries:[]}),l.get(t.id).entries.push({result:e,step:t.step,stepCount:t.stepCount})}let d=Array.from(l.entries()).sort((e,t)=>{let n=e[1].entries.length;return t[1].entries.length-n}),f=[];f.push(`Found ${o.length} matches grouped by process:`),f.push(``);for(let[e,t]of d){let n=t.stepCount?`, ${t.stepCount} steps`:``,r=e===u?`NO PROCESS (${t.entries.length} matches)`:`PROCESS: ${t.label} (${t.entries.length} matches${n})`;f.push(r),t.entries.forEach(n=>{let r=n.step?{id:e,label:t.label,step:n.step,stepCount:n.stepCount}:void 0;f.push(c(n.result,r))}),f.push(``)}return f.join(`
219
- `).trim()},{name:`search`,description:`Search for code by keywords or concepts. Combines keyword matching and semantic understanding. Groups results by process with cluster context.`,schema:e_({query:Yg().describe(`What you are looking for (e.g., "authentication middleware", "database connection")`),groupByProcess:Zg().optional().nullable().describe(`Group results by process (default: true)`),limit:Xg().optional().nullable().describe(`Max results to return (default: 10)`)})}),PO(async({query:e,cypher:r})=>{try{if(r.includes(`{{QUERY_VECTOR}}`)){if(!e)return`Error: Your Cypher contains {{QUERY_VECTOR}} but you didn't provide a 'query' to embed. Add a natural language query.`;try{let t=await n(e,{limit:10,mode:`semantic`});if(t.length===0)return`Semantic search returned no results. Embeddings may not be generated yet.`;let r=t.map((e,t)=>`[${t+1}] ${e.label||`File`}: ${e.name||e.filePath?.split(`/`).pop()||`?`} (score: ${(e.score??0).toFixed(3)})\n File: ${e.filePath||`n/a`}`).join(`
220
- `);return`Semantic search for "${e}" (${t.length} results):\n\n${r}`}catch{return`Semantic search not available. Embeddings may not be generated. Use a non-vector Cypher query instead.`}}let i=await t(r);if(i.length===0)return`Query returned no results.`;let a=i[0],o=typeof a==`object`&&!Array.isArray(a)?Object.keys(a):[];if(o.length>0){let e=`| ${o.join(` | `)} |`,t=`|${o.map(()=>`---`).join(`|`)}|`,n=i.slice(0,50).map(e=>`| ${o.map(t=>{let n=e[t];if(n==null)return``;if(typeof n==`object`)return JSON.stringify(n);let r=String(n).replace(/\\/g,`\\\\`).replace(/\|/g,`\\|`);return r.length>60?r.slice(0,57)+`...`:r}).join(` | `)} |`).join(`
221
- `),r=i.length>50?`\n\n_(${i.length-50} more rows)_`:``;return`**${i.length} results:**\n\n${e}\n${t}\n${n}${r}`}let s=i.slice(0,50).map((e,t)=>`[${t+1}] ${JSON.stringify(e)}`),c=i.length>50?`\n... (${i.length-50} more)`:``;return`${i.length} results:\n${s.join(`
222
- `)}${c}`}catch(e){return`Cypher error: ${e instanceof Error?e.message:String(e)}\n\nCheck your query syntax. Node tables: File, Folder, Function, Class, Interface, Method, CodeElement. Relation: CodeRelation with type property (CONTAINS, DEFINES, IMPORTS, CALLS). Example: MATCH (f:File)-[:CodeRelation {type: 'IMPORTS'}]->(g:File) RETURN f, g`}},{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.
223
-
224
- Node tables: File, Folder, Function, Class, Interface, Method, CodeElement
225
- Relation: CodeRelation (single table with 'type' property: CONTAINS, DEFINES, IMPORTS, CALLS, EXTENDS, IMPLEMENTS)
226
-
227
- Example queries:
228
- - Functions calling a function: MATCH (caller:Function)-[:CodeRelation {type: 'CALLS'}]->(fn:Function {name: 'validate'}) RETURN caller.name, caller.filePath
229
- - Class inheritance: MATCH (child:Class)-[:CodeRelation {type: 'EXTENDS'}]->(parent:Class) RETURN child.name, parent.name
230
- - Classes implementing interface: MATCH (c:Class)-[:CodeRelation {type: 'IMPLEMENTS'}]->(i:Interface) RETURN c.name, i.name
231
- - Files importing a file: MATCH (f:File)-[:CodeRelation {type: 'IMPORTS'}]->(target:File) WHERE target.name = 'utils.ts' RETURN f.name
232
- - 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
233
- - Find fuzzy matches: MATCH (n)-[r:CodeRelation]-(m) WHERE r.confidence < 0.8 RETURN n.name, r.reason
234
-
235
- For semantic+graph queries, include {{QUERY_VECTOR}} placeholder and provide a 'query' parameter:
236
- CALL QUERY_VECTOR_INDEX('CodeEmbedding', 'code_embedding_idx', {{QUERY_VECTOR}}, 10) YIELD node AS emb, distance
237
- WITH emb, distance WHERE distance < 0.5
238
- MATCH (n:Function {id: emb.nodeId}) RETURN n`,schema:e_({cypher:Yg().describe(`The Cypher query to execute`),query:Yg().optional().nullable().describe(`Natural language query to embed (required if cypher contains {{QUERY_VECTOR}})`)})}),PO(async({pattern:e,fileFilter:t,caseSensitive:n,maxResults:r})=>{try{try{new RegExp(e,n?`g`:`gi`)}catch(t){return`Invalid regex: ${e}. Error: ${t instanceof Error?t.message:String(t)}`}let a=r??100,o=await i(t?`(?=.*${t.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}).*${e}`:e,a);if(o.length===0)return`No matches for "${e}"${t?` in files matching "${t}"`:``}`;let s=o.map(e=>`${e.filePath}:${e.line}: ${e.text}`).join(`
239
- `),c=o.length>=a?`\n\n(Showing first ${a} results)`:``;return`Found ${o.length} matches:\n\n${s}${c}`}catch(e){return`Grep error: ${e instanceof Error?e.message:String(e)}`}},{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:e_({pattern:Yg().describe(`Regex pattern to search for (e.g., "TODO", "console\\.log", "API_KEY")`),fileFilter:Yg().optional().nullable().describe(`Only search files containing this string (e.g., ".ts", "src/api")`),caseSensitive:Zg().optional().nullable().describe(`Case-sensitive search (default: false)`),maxResults:Xg().optional().nullable().describe(`Max results (default: 100)`)})}),PO(async({filePath:e})=>{try{let t=await a(e),n=5e4;return t.length>n?`File: ${e} (${t.split(`
240
- `).length} lines, truncated)\n\n${t.slice(0,n)}\n\n... [truncated]`:`File: ${e} (${t.split(`
241
- `).length} lines)\n\n${t}`}catch(t){let n=t instanceof Error?t.message:String(t);return n.includes(`not found`)||n.includes(`404`)?`File not found: "${e}". Use grep to search for the correct path.`:`Error reading file: ${n}`}},{name:`read`,description:`Read the full content of a file. Use to see source code after finding files via search or grep.`,schema:e_({filePath:Yg().describe(`File path to read (can be partial like "src/utils.ts")`)})}),PO(async()=>{try{let[e,n,r,i]=await Promise.all([t(`
242
- MATCH (c:Community)
243
- RETURN c.id AS id, c.label AS label, c.cohesion AS cohesion, c.symbolCount AS symbolCount, c.description AS description
244
- ORDER BY c.symbolCount DESC
245
- LIMIT 200
246
- `),t(`
247
- MATCH (p:Process)
248
- RETURN p.id AS id, p.label AS label, p.processType AS type, p.stepCount AS stepCount, p.communities AS communities
249
- ORDER BY p.stepCount DESC
250
- LIMIT 200
251
- `),t(`
252
- MATCH (a)-[:CodeRelation {type: 'CALLS'}]->(b)
253
- MATCH (a)-[:CodeRelation {type: 'MEMBER_OF'}]->(c1:Community)
254
- MATCH (b)-[:CodeRelation {type: 'MEMBER_OF'}]->(c2:Community)
255
- WHERE c1.id <> c2.id
256
- RETURN c1.label AS \`from\`, c2.label AS \`to\`, COUNT(*) AS calls
257
- ORDER BY calls DESC
258
- LIMIT 15
259
- `),t(`
260
- MATCH (s)-[r:CodeRelation {type: 'STEP_IN_PROCESS'}]->(p:Process)
261
- RETURN p.label AS label, COUNT(r) AS steps
262
- ORDER BY steps DESC
263
- LIMIT 10
264
- `)]),a=e.map(e=>{let t=Array.isArray(e)?e[1]:e.label,n=Array.isArray(e)?e[3]:e.symbolCount,r=Array.isArray(e)?e[2]:e.cohesion,i=Array.isArray(e)?e[4]:e.description,a=r==null?``:Number(r).toFixed(2);return`| ${t||``} | ${n??``} | ${a} | ${i??``} |`}),o=n.map(e=>{let t=Array.isArray(e)?e[1]:e.label,n=Array.isArray(e)?e[3]:e.stepCount,r=Array.isArray(e)?e[2]:e.type,i=Array.isArray(e)?e[4]:e.communities,a=Array.isArray(i)?i.length:+!!i;return`| ${t||``} | ${n??``} | ${r??``} | ${a} |`}),s=r.map(e=>`- ${Array.isArray(e)?e[0]:e.from} -> ${Array.isArray(e)?e[1]:e.to} (${Array.isArray(e)?e[2]:e.calls} calls)`),c=i.map(e=>`- ${Array.isArray(e)?e[0]:e.label} (${Array.isArray(e)?e[1]:e.steps} steps)`);return[`CLUSTERS (${e.length} total):`,`| Cluster | Symbols | Cohesion | Description |`,`| --- | --- | --- | --- |`,...a,``,`PROCESSES (${n.length} total):`,`| Process | Steps | Type | Clusters |`,`| --- | --- | --- | --- |`,...o,``,`CLUSTER DEPENDENCIES:`,...s.length>0?s:[`- None found`],``,`CRITICAL PATHS:`,...c.length>0?c:[`- None found`]].join(`
265
- `)}catch(e){return`Overview error: ${e instanceof Error?e.message:String(e)}`}},{name:`overview`,description:`Codebase map showing all clusters and processes, plus cross-cluster dependencies.`,schema:e_({})}),PO(async({target:e,type:n})=>{let r=e.replace(/'/g,`''`),i=n??null,a=null,o=null,s=null,c=(e,t,n)=>Array.isArray(e)?e[t]:e[n];if(!i||i===`process`){let e=await t(`
266
- MATCH (p:Process)
267
- WHERE p.id = '${r}' OR p.label = '${r}'
268
- RETURN p.id AS id, p.label AS label, p.processType AS type, p.stepCount AS stepCount
269
- LIMIT 1
270
- `);e.length>0&&(a=e[0],i=`process`)}if(!i||i===`cluster`){let e=await t(`
271
- MATCH (c:Community)
272
- WHERE c.id = '${r}' OR c.label = '${r}' OR c.heuristicLabel = '${r}'
273
- RETURN c.id AS id, c.label AS label, c.cohesion AS cohesion, c.symbolCount AS symbolCount, c.description AS description
274
- LIMIT 1
275
- `);e.length>0&&(o=e[0],i=`cluster`)}if(!i||i===`symbol`){let e=await t(`
276
- MATCH (n)
277
- WHERE n.name = '${r}' OR n.id = '${r}' OR n.filePath = '${r}'
278
- RETURN n.id AS id, n.name AS name, n.filePath AS filePath, label(n) AS nodeType
279
- LIMIT 5
280
- `);e.length>0&&(s=e[0],i=`symbol`)}if(!i)return`Could not find "${e}" as a symbol, cluster, or process. Try search first.`;if(i===`process`){let e=c(a,0,`id`),n=c(a,1,`label`),r=c(a,2,`type`),i=c(a,3,`stepCount`),o=`
281
- MATCH (s)-[r:CodeRelation {type: 'STEP_IN_PROCESS'}]->(p:Process {id: '${e.replace(/'/g,`''`)}'})
282
- RETURN s.name AS name, s.filePath AS filePath, r.step AS step
283
- ORDER BY r.step
284
- `,s=`
285
- MATCH (c:Community)<-[:CodeRelation {type: 'MEMBER_OF'}]-(s)
286
- MATCH (s)-[:CodeRelation {type: 'STEP_IN_PROCESS'}]->(p:Process {id: '${e.replace(/'/g,`''`)}'})
287
- RETURN DISTINCT c.id AS id, c.label AS label, c.description AS description
288
- ORDER BY c.label
289
- LIMIT 20
290
- `,[l,u]=await Promise.all([t(o),t(s)]),d=l.map(e=>{let t=c(e,0,`name`),n=c(e,1,`filePath`);return`- ${c(e,2,`step`)}. ${t} (${n||`n/a`})`}),f=u.map(e=>{let t=c(e,1,`label`),n=c(e,2,`description`);return`- ${t}${n?` β€” ${n}`:``}`});return[`PROCESS: ${n}`,`Type: ${r||`n/a`}`,`Steps: ${i??l.length}`,``,`STEPS:`,...d.length>0?d:[`- None found`],``,`CLUSTERS TOUCHED:`,...f.length>0?f:[`- None found`]].join(`
291
- `)}if(i===`cluster`){let e=c(o,0,`id`),n=c(o,1,`label`),r=c(o,2,`cohesion`),i=c(o,3,`symbolCount`),a=c(o,4,`description`),s=`
292
- MATCH (c:Community {id: '${e.replace(/'/g,`''`)}'})<-[:CodeRelation {type: 'MEMBER_OF'}]-(m)
293
- RETURN m.name AS name, m.filePath AS filePath, label(m) AS nodeType
294
- LIMIT 50
295
- `,l=`
296
- MATCH (c:Community {id: '${e.replace(/'/g,`''`)}'})<-[:CodeRelation {type: 'MEMBER_OF'}]-(s)
297
- MATCH (s)-[:CodeRelation {type: 'STEP_IN_PROCESS'}]->(p:Process)
298
- RETURN DISTINCT p.id AS id, p.label AS label, p.stepCount AS stepCount
299
- ORDER BY p.stepCount DESC
300
- LIMIT 20
301
- `,[u,d]=await Promise.all([t(s),t(l)]),f=u.map(e=>{let t=c(e,0,`name`),n=c(e,1,`filePath`);return`- ${c(e,2,`nodeType`)}: ${t} (${n||`n/a`})`}),p=d.map(e=>`- ${c(e,1,`label`)} (${c(e,2,`stepCount`)} steps)`);return[`CLUSTER: ${n}`,`Symbols: ${i??u.length}`,`Cohesion: ${r==null?`n/a`:Number(r).toFixed(2)}`,`Description: ${a||`n/a`}`,``,`TOP MEMBERS:`,...f.length>0?f:[`- None found`],``,`PROCESSES TOUCHING THIS CLUSTER:`,...p.length>0?p:[`- None found`]].join(`
302
- `)}if(i===`symbol`){let n=c(s,0,`id`),r=c(s,1,`name`),i=c(s,2,`filePath`),a=c(s,3,`nodeType`);if(!MZ(a))return`Unknown node type "${a}" for symbol "${e}".`;let o=`
303
- MATCH (n:${a} {id: '${String(n).replace(/'/g,`''`)}'})
304
- MATCH (n)-[:CodeRelation {type: 'MEMBER_OF'}]->(c:Community)
305
- RETURN c.label AS label, c.description AS description
306
- LIMIT 1
307
- `,l=`
308
- MATCH (n:${a} {id: '${String(n).replace(/'/g,`''`)}'})
309
- MATCH (n)-[r:CodeRelation {type: 'STEP_IN_PROCESS'}]->(p:Process)
310
- RETURN p.label AS label, r.step AS step, p.stepCount AS stepCount
311
- ORDER BY r.step
312
- `,u=`
313
- MATCH (n:${a} {id: '${String(n).replace(/'/g,`''`)}'})
314
- OPTIONAL MATCH (n)-[r1:CodeRelation]->(dst)
315
- OPTIONAL MATCH (src)-[r2:CodeRelation]->(n)
316
- RETURN
317
- collect(DISTINCT {name: dst.name, type: r1.type, confidence: r1.confidence}) AS outgoing,
318
- collect(DISTINCT {name: src.name, type: r2.type, confidence: r2.confidence}) AS incoming
319
- LIMIT 1
320
- `,[d,f,p]=await Promise.all([t(o),t(l),t(u)]),m=d.length>0?c(d[0],0,`label`):`Unclustered`,h=d.length>0?c(d[0],1,`description`):``,g=f.map(e=>`- ${c(e,0,`label`)} (step ${c(e,1,`step`)}/${c(e,2,`stepCount`)??`?`})`),_=`None`;if(p.length>0){let e=p[0],t=Array.isArray(e)?e[0]:e.outgoing||[],n=Array.isArray(e)?e[1]:e.incoming||[],r=(t||[]).filter(e=>e&&e.name).slice(0,5),i=(n||[]).filter(e=>e&&e.name).slice(0,5),a=(e,t)=>{let n=e.confidence?Math.round(e.confidence*100):100;return t===`out`?`-[${e.type} ${n}%]-> ${e.name}`:`<-[${e.type} ${n}%]- ${e.name}`},o=r.map(e=>a(e,`out`)),s=i.map(e=>a(e,`in`));(o.length||s.length)&&(_=[...o,...s].join(`, `))}return[`SYMBOL: ${a} ${r}`,`ID: ${n}`,`File: ${i||`n/a`}`,`Cluster: ${m}${h?` β€” ${h}`:``}`,``,`PROCESSES:`,...g.length>0?g:[`- None found`],``,`CONNECTIONS:`,_].join(`
321
- `)}return`Unable to explore "${e}".`},{name:`explore`,description:`Deep dive on a symbol, cluster, or process. Shows membership, participation, and connections.`,schema:e_({target:Yg().describe(`Name or ID of a symbol, cluster, or process`),type:t_([`symbol`,`cluster`,`process`]).optional().nullable().describe(`Optional target type (auto-detected if omitted)`)})}),PO(async({target:e,direction:n,maxDepth:o,relationTypes:s,includeTests:c,minConfidence:l})=>{let u=Math.min(o??3,10),d=c??!1,f=l??.7,p=e=>{if(!e)return!1;let t=e.toLowerCase();return t.includes(`.test.`)||t.includes(`.spec.`)||t.includes(`__tests__`)||t.includes(`__mocks__`)||t.endsWith(`.test.ts`)||t.endsWith(`.test.tsx`)||t.endsWith(`.spec.ts`)||t.endsWith(`.spec.tsx`)},m=s&&s.length>0?s.filter(e=>NZ(e)):[`CALLS`,`IMPORTS`,`EXTENDS`,`IMPLEMENTS`];if(m.length===0)return`No valid relation types provided. Valid types: ${r.join(`, `)}`;let h=m.map(e=>`'${e.replace(/'/g,`''`)}'`).join(`, `),g=e.includes(`/`),_=e.replace(/'/g,`''`),v=g?`
322
- MATCH (n)
323
- WHERE n.filePath IS NOT NULL AND n.filePath CONTAINS '${_}'
324
- RETURN n.id AS id, label(n) AS nodeType, n.filePath AS filePath
325
- LIMIT 10
326
- `:`
327
- MATCH (n)
328
- WHERE n.name = '${_}'
329
- RETURN n.id AS id, label(n) AS nodeType, n.filePath AS filePath
330
- LIMIT 10
331
- `,y;try{y=await t(v)}catch(t){return`Error finding target "${e}": ${t}`}if(!y||y.length===0)return`Could not find "${e}" in the codebase. Try using the search tool first to find the exact name.`;let b=y.map(e=>Array.isArray(e)?e[2]:e.filePath).filter(Boolean);if(y.length>1&&!e.includes(`/`))return`⚠️ AMBIGUOUS TARGET: Multiple files named "${e}" found:\n\n${b.map((e,t)=>`${t+1}. ${e}`).join(`
332
- `)}\n\nPlease specify which file you mean by using a more specific path, e.g.:\n- impact("${b[0].split(`/`).slice(-3).join(`/`)}")\n- impact("${b[1]?.split(`/`).slice(-3).join(`/`)||b[0]}")`;let ee=y[0];if(e.includes(`/`)&&y.length>1){let t=y.find(t=>{let n=Array.isArray(t)?t[2]:t.filePath;return n&&n.toLowerCase().includes(e.toLowerCase())});if(t)ee=t;else return`⚠️ AMBIGUOUS TARGET: Could not uniquely match "${e}". Found:\n\n${b.map((e,t)=>`${t+1}. ${e}`).join(`
333
- `)}\n\nPlease use a more specific path.`}let x=Array.isArray(ee)?ee[0]:ee.id,te=Array.isArray(ee)?ee[1]:ee.nodeType,S=Array.isArray(ee)?ee[2]:ee.filePath,ne=te===`File`,re=[],ie=n===`upstream`?ne?`
334
- MATCH (affected)-[r:CodeRelation]->(callee)
335
- WHERE callee.filePath = '${(S||e).replace(/'/g,`''`)}'
336
- AND r.type IN [${h}]
337
- AND affected.filePath <> callee.filePath
338
- AND (r.confidence IS NULL OR r.confidence >= ${f})
339
- RETURN DISTINCT
340
- affected.id AS id,
341
- affected.name AS name,
342
- label(affected) AS nodeType,
343
- affected.filePath AS filePath,
344
- affected.startLine AS startLine,
345
- 1 AS depth,
346
- r.type AS edgeType,
347
- r.confidence AS confidence,
348
- r.reason AS reason
349
- LIMIT 300
350
- `:`
351
- MATCH (target {id: '${x.replace(/'/g,`''`)}'})
352
- MATCH (affected)-[r:CodeRelation]->(target)
353
- WHERE r.type IN [${h}]
354
- AND (r.confidence IS NULL OR r.confidence >= ${f})
355
- RETURN DISTINCT
356
- affected.id AS id,
357
- affected.name AS name,
358
- label(affected) AS nodeType,
359
- affected.filePath AS filePath,
360
- affected.startLine AS startLine,
361
- 1 AS depth,
362
- r.type AS edgeType,
363
- r.confidence AS confidence,
364
- r.reason AS reason
365
- LIMIT 300
366
- `:ne?`
367
- MATCH (caller)-[r:CodeRelation]->(affected)
368
- WHERE caller.filePath = '${(S||e).replace(/'/g,`''`)}'
369
- AND r.type IN [${h}]
370
- AND caller.filePath <> affected.filePath
371
- AND (r.confidence IS NULL OR r.confidence >= ${f})
372
- RETURN DISTINCT
373
- affected.id AS id,
374
- affected.name AS name,
375
- label(affected) AS nodeType,
376
- affected.filePath AS filePath,
377
- affected.startLine AS startLine,
378
- 1 AS depth,
379
- r.type AS edgeType,
380
- r.confidence AS confidence,
381
- r.reason AS reason
382
- LIMIT 300
383
- `:`
384
- MATCH (target {id: '${x.replace(/'/g,`''`)}'})
385
- MATCH (target)-[r:CodeRelation]->(affected)
386
- WHERE r.type IN [${h}]
387
- AND (r.confidence IS NULL OR r.confidence >= ${f})
388
- RETURN DISTINCT
389
- affected.id AS id,
390
- affected.name AS name,
391
- label(affected) AS nodeType,
392
- affected.filePath AS filePath,
393
- affected.startLine AS startLine,
394
- 1 AS depth,
395
- r.type AS edgeType,
396
- r.confidence AS confidence,
397
- r.reason AS reason
398
- LIMIT 300
399
- `;if(re.push(t(ie).then(e=>e).catch(e=>[])),u>=2){let e=n===`upstream`?`
400
- MATCH (target {id: '${x.replace(/'/g,`''`)}'})
401
- MATCH (a)-[r1:CodeRelation]->(target)
402
- MATCH (affected)-[r2:CodeRelation]->(a)
403
- WHERE r1.type IN [${h}] AND r2.type IN [${h}]
404
- AND affected.id <> target.id
405
- AND (r1.confidence IS NULL OR r1.confidence >= ${f})
406
- AND (r2.confidence IS NULL OR r2.confidence >= ${f})
407
- RETURN DISTINCT
408
- affected.id AS id,
409
- affected.name AS name,
410
- label(affected) AS nodeType,
411
- affected.filePath AS filePath,
412
- affected.startLine AS startLine,
413
- 2 AS depth,
414
- r2.type AS edgeType,
415
- r2.confidence AS confidence,
416
- r2.reason AS reason
417
- LIMIT 200
418
- `:`
419
- MATCH (target {id: '${x.replace(/'/g,`''`)}'})
420
- MATCH (target)-[r1:CodeRelation]->(a)
421
- MATCH (a)-[r2:CodeRelation]->(affected)
422
- WHERE r1.type IN [${h}] AND r2.type IN [${h}]
423
- AND affected.id <> target.id
424
- AND (r1.confidence IS NULL OR r1.confidence >= ${f})
425
- AND (r2.confidence IS NULL OR r2.confidence >= ${f})
426
- RETURN DISTINCT
427
- affected.id AS id,
428
- affected.name AS name,
429
- label(affected) AS nodeType,
430
- affected.filePath AS filePath,
431
- affected.startLine AS startLine,
432
- 2 AS depth,
433
- r2.type AS edgeType,
434
- r2.confidence AS confidence,
435
- r2.reason AS reason
436
- LIMIT 200
437
- `;re.push(t(e).catch(e=>[]))}if(u>=3){let e=n===`upstream`?`
438
- MATCH (target {id: '${x.replace(/'/g,`''`)}'})
439
- MATCH (a)-[r1:CodeRelation]->(target)
440
- MATCH (b)-[r2:CodeRelation]->(a)
441
- MATCH (affected)-[r3:CodeRelation]->(b)
442
- WHERE r1.type IN [${h}] AND r2.type IN [${h}] AND r3.type IN [${h}]
443
- AND affected.id <> target.id AND affected.id <> a.id
444
- AND (r1.confidence IS NULL OR r1.confidence >= ${f})
445
- AND (r2.confidence IS NULL OR r2.confidence >= ${f})
446
- AND (r3.confidence IS NULL OR r3.confidence >= ${f})
447
- RETURN DISTINCT
448
- affected.id AS id,
449
- affected.name AS name,
450
- label(affected) AS nodeType,
451
- affected.filePath AS filePath,
452
- affected.startLine AS startLine,
453
- 3 AS depth,
454
- r3.type AS edgeType,
455
- r3.confidence AS confidence,
456
- r3.reason AS reason
457
- LIMIT 100
458
- `:`
459
- MATCH (target {id: '${x.replace(/'/g,`''`)}'})
460
- MATCH (target)-[r1:CodeRelation]->(a)
461
- MATCH (a)-[r2:CodeRelation]->(b)
462
- MATCH (b)-[r3:CodeRelation]->(affected)
463
- WHERE r1.type IN [${h}] AND r2.type IN [${h}] AND r3.type IN [${h}]
464
- AND affected.id <> target.id AND affected.id <> a.id
465
- AND (r1.confidence IS NULL OR r1.confidence >= ${f})
466
- AND (r2.confidence IS NULL OR r2.confidence >= ${f})
467
- AND (r3.confidence IS NULL OR r3.confidence >= ${f})
468
- RETURN DISTINCT
469
- affected.id AS id,
470
- affected.name AS name,
471
- label(affected) AS nodeType,
472
- affected.filePath AS filePath,
473
- affected.startLine AS startLine,
474
- 3 AS depth,
475
- r3.type AS edgeType,
476
- r3.confidence AS confidence,
477
- r3.reason AS reason
478
- LIMIT 100
479
- `;re.push(t(e).catch(e=>[]))}let ae=await Promise.all(re),oe=new Map,se=[],ce=new Set;ae.forEach((e,t)=>{let n=t+1;e.forEach(e=>{let t=Array.isArray(e)?e[0]:e.id,r=Array.isArray(e)?e[3]:e.filePath;if(!(!d&&p(r))&&t&&!ce.has(t)){ce.add(t),oe.has(n)||oe.set(n,[]);let i={id:t,name:Array.isArray(e)?e[1]:e.name,nodeType:Array.isArray(e)?e[2]:e.nodeType,filePath:r,startLine:Array.isArray(e)?e[4]:e.startLine,edgeType:Array.isArray(e)?e[5]:e.edgeType||`CALLS`,confidence:Array.isArray(e)?e[6]:e.confidence??1,reason:Array.isArray(e)?e[7]:e.reason||``};oe.get(n).push(i),se.push(t)}})});let C=se.length;if(C===0){if(ne){let t=e=>e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`),r=((S||e).split(`/`).pop()||e).replace(/\.[^/.]+$/,``);try{let a=(await i(`\\b${t(r)}\\b`,15)).filter(e=>e.filePath!==S);if(a.length>0){let t=a.map(e=>`${e.filePath}:${e.line}: ${e.text}`).join(`
480
- `);return`No ${n} dependencies found for "${e}" (types: ${m.join(`, `)}), but textual references were detected (graph may be incomplete):\n\n${t}`}}catch{}}return`No ${n} dependencies found for "${e}" (types: ${m.join(`, `)}). This code appears to be ${n===`upstream`?`unused (not called by anything)`:`self-contained (no outgoing dependencies)`}.`}let le=oe.get(1)||[],ue=oe.get(2)||[],de=oe.get(3)||[],fe={high:0,medium:0,low:0};for(let e of oe.values())for(let t of e){let e=t.confidence??1;e>=.9?fe.high+=1:e>=.8?fe.medium+=1:fe.low+=1}let pe=se.slice(0,500),me=pe.map(e=>`'${e.replace(/'/g,`''`)}'`).join(`, `),he=[],ge=[];if(pe.length>0){let e=`
481
- MATCH (s)-[r:CodeRelation {type: 'STEP_IN_PROCESS'}]->(p:Process)
482
- WHERE s.id IN [${me}]
483
- RETURN p.label AS label, COUNT(DISTINCT s.id) AS hits, MIN(r.step) AS minStep, p.stepCount AS stepCount
484
- ORDER BY hits DESC
485
- LIMIT 20
486
- `,n=`
487
- MATCH (s)-[:CodeRelation {type: 'MEMBER_OF'}]->(c:Community)
488
- WHERE s.id IN [${me}]
489
- RETURN c.label AS label, COUNT(DISTINCT s.id) AS hits
490
- ORDER BY hits DESC
491
- LIMIT 20
492
- `,r=le.map(e=>`'${e.id.replace(/'/g,`''`)}'`).join(`, `),i=le.length>0?`
493
- MATCH (s)-[:CodeRelation {type: 'MEMBER_OF'}]->(c:Community)
494
- WHERE s.id IN [${r}]
495
- RETURN DISTINCT c.label AS label
496
- `:``,[a,o,s]=await Promise.all([t(e),t(n),i?t(i):Promise.resolve([])]),c=new Set;s.forEach(e=>{let t=Array.isArray(e)?e[0]:e.label;t&&c.add(t)}),he=a.map(e=>({label:Array.isArray(e)?e[0]:e.label,hits:Array.isArray(e)?e[1]:e.hits,minStep:Array.isArray(e)?e[2]:e.minStep,stepCount:Array.isArray(e)?e[3]:e.stepCount})),ge=o.map(e=>{let t=Array.isArray(e)?e[0]:e.label;return{label:t,hits:Array.isArray(e)?e[1]:e.hits,impact:c.has(t)?`direct`:`indirect`}})}let _e=le.length,ve=he.length,ye=ge.length,be=`LOW`;_e>=30||ve>=5||ye>=5||C>=200?be=`CRITICAL`:_e>=15||ve>=3||ye>=3||C>=100?be=`HIGH`:(_e>=5||C>=30)&&(be=`MEDIUM`);let xe=[`πŸ”΄ IMPACT: ${e} | ${n} | ${C} affected`,`Confidence: High ${fe.high} | Medium ${fe.medium} | Low ${fe.low}`,``,`AFFECTED PROCESSES:`,...he.length>0?he.map(e=>`- ${e.label} - BROKEN at step ${e.minStep??`?`} (${e.hits} symbols, ${e.stepCount??`?`} steps)`):[`- None found`],``,`AFFECTED CLUSTERS:`,...ge.length>0?ge.map(e=>`- ${e.label} (${e.impact}, ${e.hits} symbols)`):[`- None found`],``,`RISK: ${be}`,`- Direct callers: ${_e}`,`- Processes affected: ${ve}`,`- Clusters affected: ${ye}`,``],Se=e=>{let t=e.filePath?.split(`/`).pop()||``,n=e.startLine?`${t}:${e.startLine}`:t,r=Math.round((e.confidence??1)*100),i=r<80?`[fuzzy]`:``;return` ${e.nodeType}|${e.name}|${n}|${e.edgeType}|${r}%${i}`},Ce=async e=>{if(!e.filePath||!e.startLine)return null;try{let t=(await a(e.filePath)).split(`
497
- `),n=e.startLine-1;if(n<0||n>=t.length)return null;let r=t[n].trim();return r.length>80&&(r=r.slice(0,77)+`...`),r}catch{return null}};if(le.length>0){let t=n===`upstream`?`d=1 (Directly DEPEND ON ${e}):`:`d=1 (${e} USES these):`;xe.push(t);for(let e of le.slice(0,15)){xe.push(Se(e));let t=await Ce(e);t&&xe.push(` ↳ "${t}"`)}le.length>15&&xe.push(` ... +${le.length-15} more`),xe.push(``)}if(ue.length>0){let t=n===`upstream`?`d=2 (Indirectly DEPEND ON ${e}):`:`d=2 (${e} USES these indirectly):`;xe.push(t),ue.slice(0,15).forEach(e=>xe.push(Se(e))),ue.length>15&&xe.push(` ... +${ue.length-15} more`),xe.push(``)}return de.length>0&&(xe.push(`d=3 (Deep impact/dependency):`),de.slice(0,5).forEach(e=>xe.push(Se(e))),de.length>5&&xe.push(` ... +${de.length-5} more`),xe.push(``)),xe.push(`βœ… GRAPH ANALYSIS COMPLETE (trusted)`),xe.push(`⚠️ Optional: grep("${e}") for dynamic patterns`),xe.push(``),xe.join(`
498
- `)},{name:`impact`,description:`Analyze the impact of changing a function, class, or file.
499
-
500
- Use when users ask:
501
- - "What would break if I changed X?"
502
- - "What depends on X?"
503
- - "Impact analysis for X"
504
-
505
- Direction:
506
- - upstream: Find what CALLS/IMPORTS/EXTENDS this target (what would break)
507
- - downstream: Find what this target CALLS/IMPORTS/EXTENDS (dependencies)
508
-
509
- Output format (compact tabular):
510
- Type|Name|File:Line|EdgeType|Confidence%
511
-
512
- EdgeType: CALLS, IMPORTS, EXTENDS, IMPLEMENTS
513
- Confidence: 100% = certain, <80% = fuzzy match (may be false positive)
514
-
515
- relationTypes filter (optional):
516
- - Default: CALLS, IMPORTS, EXTENDS, IMPLEMENTS (usage-based)
517
- - Can add CONTAINS, DEFINES for structural analysis
518
-
519
- Additional output sections:
520
- - Affected processes (with step impact)
521
- - Affected clusters (direct/indirect)
522
- - Risk summary (based on direct callers, processes, clusters)`,schema:e_({target:Yg().describe(`Name of the function, class, or file to analyze`),direction:t_([`upstream`,`downstream`]).describe(`upstream = what depends on this; downstream = what this depends on`),maxDepth:Xg().optional().nullable().describe(`Max traversal depth (default: 3, max: 10)`),relationTypes:$g(Yg()).optional().nullable().describe(`Filter by relation types: CALLS, IMPORTS, EXTENDS, IMPLEMENTS, CONTAINS, DEFINES (default: usage-based)`),includeTests:Zg().optional().nullable().describe(`Include test files in results (default: false, excludes .test.ts, .spec.ts, __tests__)`),minConfidence:Xg().optional().nullable().describe(`Minimum edge confidence 0-1 (default: 0.7, excludes fuzzy/inferred matches)`)})})]},FZ=`You are Nexus, a Code Analysis Agent with access to a Knowledge Graph. Your responses MUST be grounded.
523
-
524
- ## ⚠️ MANDATORY: GROUNDING
525
- Every factual claim MUST include a citation.
526
- - File refs: [[src/auth.ts:45-60]] (line range with hyphen)
527
- - NO citation = NO claim. Say "I didn't find evidence" instead of guessing.
528
-
529
- ## ⚠️ MANDATORY: VALIDATION
530
- Every output MUST be validated.
531
- - Use cypher to validate the results and confirm completeness of context before final output.
532
- - NO validation = NO claim. Say "I didn't find evidence" instead of guessing.
533
- - Do not blindly trust readme or single source of truth. Always validate and cross-reference. Never be lazy.
534
-
535
- ## 🧠 CORE PROTOCOL
536
- You are an investigator. For each question:
537
- 1. **Search** β†’ Use cypher, search or grep to find relevant code
538
- 2. **Read** β†’ Use read to see the actual source
539
- 3. **Trace** β†’ Use cypher to follow connections in the graph
540
- 4. **Cite** β†’ Ground every finding with [[file:line]] or [[Type:Name]]
541
- 5. **Validate** β†’ Use cypher to validate the results and confirm completeness of context before final output. ( MUST DO )
542
-
543
- ## πŸ› οΈ TOOLS
544
- - **\`search\`** β€” Hybrid search. Results grouped by process with cluster context.
545
- - **\`cypher\`** β€” Cypher queries against the graph. Use \`{{QUERY_VECTOR}}\` for vector search.
546
- - **\`grep\`** β€” Regex search. Best for exact strings, TODOs, error codes.
547
- - **\`read\`** β€” Read file content. Always use after search/grep to see full code.
548
- - **\`explore\`** β€” Deep dive on a symbol, cluster, or process. Shows membership, participation, connections.
549
- - **\`overview\`** β€” Codebase map showing all clusters and processes.
550
- - **\`impact\`** β€” Impact analysis. Shows affected processes, clusters, and risk level.
551
-
552
- ## πŸ“Š GRAPH SCHEMA
553
- Nodes: File, Folder, Function, Class, Interface, Method, Community, Process
554
- Relations: \`CodeRelation\` with \`type\` property: CONTAINS, DEFINES, IMPORTS, CALLS, EXTENDS, IMPLEMENTS, MEMBER_OF, STEP_IN_PROCESS
555
-
556
- ## πŸ“ GRAPH SEMANTICS (Important!)
557
- **Edge Types:**
558
- - \`CALLS\`: Method invocation OR constructor injection. If A receives B as parameter and uses it, A→B is CALLS. This is intentional simplification.
559
- - \`IMPORTS\`: File-level import/include statement.
560
- - \`EXTENDS/IMPLEMENTS\`: Class inheritance.
561
-
562
- **Process Nodes:**
563
- - Process labels use format: "EntryPoint β†’ Terminal" (e.g., "onCreate β†’ showToast")
564
- - These are heuristic names from tracing execution flow, NOT application-defined names
565
- - Entry points are detected via export status, naming patterns, and framework conventions
566
-
567
- Cypher examples:
568
- - \`MATCH (f:Function) RETURN f.name LIMIT 10\`
569
- - \`MATCH (f:File)-[:CodeRelation {type: 'IMPORTS'}]->(g:File) RETURN f.name, g.name\`
570
-
571
- ## πŸ“CRITICAL RULES
572
- - **impact output is trusted.** Do NOT re-validate with cypher. Optionally run the suggested grep commands for dynamic patterns.
573
- - **Cite or retract.** Never state something you can't ground.
574
- - **Read before concluding.** Don't guess from names alone.
575
- - **Retry on failure.** If a tool fails, fix the input and try again.
576
- - **Cyfer tool validation** prefer using cyfer tool in anything that requires graph connections.
577
- - **OUTPUT STYLE** Prefer using tables and mermaid diagrams instead of long explanations.
578
- - ALWAYS USE MERMAID FOR VISUALIZATION AND STRUCTURING THE OUTPUT.
579
-
580
- ## 🎯 OUTPUT STYLE
581
- Think like a senior architect. Be conciseβ€”no fluff, short, precise and to the point.
582
- - Use tables for comparisons/rankings
583
- - Use mermaid diagrams for flows/dependencies
584
- - Surface deep insights: patterns, coupling, design decisions
585
- - End with **TL;DR** (short summary of the response, summing up the response and the most critical parts)
586
-
587
- ## MERMAID RULES
588
- When generating diagrams:
589
- - NO special characters in node labels: quotes, (), /, &, <, >
590
- - Wrap labels with spaces in quotes: A["My Label"]
591
- - Use simple IDs: A, B, C or auth, db, api
592
- - Flowchart: graph TD or graph LR (not flowchart)
593
- - Always test mentally: would this parse?
594
-
595
- BAD: A[User's Data] --> B(Process & Save)
596
- GOOD: A["User Data"] --> B["Process and Save"]
597
- `,IZ=e=>{switch(e.provider){case`openai`:{let t=e;if(!t.apiKey||t.apiKey.trim()===``)throw Error(`OpenAI API key is required but was not provided`);return new aU({apiKey:t.apiKey,modelName:t.model,temperature:t.temperature??.1,maxTokens:t.maxTokens,configuration:{apiKey:t.apiKey,...t.baseUrl?{baseURL:t.baseUrl}:{}},streaming:!0})}case`azure-openai`:{let t=e;return new oU({azureOpenAIApiKey:t.apiKey,azureOpenAIApiInstanceName:LZ(t.endpoint),azureOpenAIApiDeploymentName:t.deploymentName,azureOpenAIApiVersion:t.apiVersion??`2024-12-01-preview`,streaming:!0})}case`gemini`:{let t=e;return new UW({apiKey:t.apiKey,model:t.model,temperature:t.temperature??.1,maxOutputTokens:t.maxTokens,streaming:!0})}case`anthropic`:{let t=e;return new aX({anthropicApiKey:t.apiKey,model:t.model,temperature:t.temperature??.1,maxTokens:t.maxTokens??8192,streaming:!0})}case`ollama`:{let t=e;return new jZ({baseUrl:t.baseUrl??`http://localhost:11434`,model:t.model,temperature:t.temperature??.1,streaming:!0,numPredict:3e4,numCtx:32768})}case`openrouter`:{let t=e;if(!t.apiKey||t.apiKey.trim()===``)throw Error(`OpenRouter API key is required but was not provided`);return new aU({openAIApiKey:t.apiKey,apiKey:t.apiKey,modelName:t.model,temperature:t.temperature??.1,maxTokens:t.maxTokens,configuration:{apiKey:t.apiKey,baseURL:t.baseUrl??`https://openrouter.ai/api/v1`},streaming:!0})}case`minimax`:{let t=e;if(!t.apiKey||t.apiKey.trim()===``)throw Error(`MiniMax API key is required but was not provided`);return new aX({anthropicApiKey:t.apiKey,model:t.model,temperature:t.temperature??.1,maxTokens:t.maxTokens??8192,streaming:!0,clientOptions:{baseURL:`https://api.minimax.io/anthropic`}})}case`glm`:{let t=e;if(!t.apiKey||t.apiKey.trim()===``)throw Error(`GLM API key is required but was not provided`);return new aU({apiKey:t.apiKey,modelName:t.model,temperature:t.temperature??.1,maxTokens:t.maxTokens,configuration:{apiKey:t.apiKey,baseURL:t.baseUrl??`https://api.z.ai/api/coding/paas/v4`},streaming:!0})}default:throw Error(`Unsupported provider: ${e.provider}`)}},LZ=e=>{try{let t=new URL(e).hostname,n=t.match(/^([^.]+)\.openai\.azure\.com$/);return n?n[1]:t.split(`.`)[0]}catch{return e}},RZ=(e,t,n)=>VP({llm:IZ(e),tools:PZ(t),messageModifier:new dn(n?i(FZ,n):FZ)});async function*zZ(e,t){try{let n=t.map(e=>({role:e.role,content:e.content})),r=await e.stream({messages:n},{streamMode:[`values`,`messages`],recursionLimit:50}),i=new Set,a=new Set,o=n.length,s=0,c=!1;for await(let e of r){let t,n;if(Array.isArray(e)&&e.length===2&&typeof e[0]==`string`?[t,n]=e:Array.isArray(e)&&e[0]?._getType?(t=`messages`,n=e):(t=`values`,n=e),t===`messages`){let[e]=Array.isArray(n)?n:[n];if(!e)continue;let t=e._getType?.()||e.type||e.constructor?.name||`unknown`;if(t===`ai`||t===`AIMessage`||t===`AIMessageChunk`){let t=e.content,n=e.tool_calls||[],r=``;if(typeof t==`string`?r=t:Array.isArray(t)&&(r=t.filter(e=>e.type===`text`||typeof e==`string`).map(e=>typeof e==`string`?e:e.text||``).join(``)),r&&r.length>0){let e=!c||n.length>0||s>0;yield{type:e?`reasoning`:`content`,[e?`reasoning`:`content`]:r}}if(n.length>0){c=!0,s+=n.length;for(let e of n){let t=e.id||`tool-${Date.now()}-${Math.random().toString(36).slice(2)}`;if(!i.has(t)){i.add(t);let n;try{n=e.function?.arguments?JSON.parse(e.function.arguments):{}}catch{n={}}yield{type:`tool_call`,toolCall:{id:t,name:e.name||e.function?.name||`unknown`,args:e.args||n,status:`running`}}}}}}if(t===`tool`||t===`ToolMessage`){let t=e.tool_call_id||``;if(t&&!a.has(t)){a.add(t);let n=typeof e.content==`string`?e.content:JSON.stringify(e.content);yield{type:`tool_result`,toolCall:{id:t,name:e.name||`tool`,args:{},result:n,status:`completed`}},s=Math.max(0,s-1)}}}if(t===`values`&&n?.messages){let e=n.messages||[];for(let t=o;t<e.length;t++){let n=e[t],r=n._getType?.()||n.type||`unknown`;if((r===`ai`||r===`AIMessage`)&&!i.size){let e=n.tool_calls||[];for(let t of e){let e=t.id||`tool-${Date.now()}`;i.has(e)||(s++,i.add(e),yield{type:`tool_call`,toolCall:{id:e,name:t.name||`unknown`,args:t.args||{},status:`running`}})}}if(r===`tool`||r===`ToolMessage`){let e=n.tool_call_id||``;if(e&&!a.has(e)){a.add(e);let t=typeof n.content==`string`?n.content:JSON.stringify(n.content);yield{type:`tool_result`,toolCall:{id:e,name:n.name||`tool`,args:{},result:t,status:`completed`}},s=Math.max(0,s-1)}}}o=e.length}}yield{type:`done`}}catch(e){yield{type:`error`,error:e instanceof Error?e.message:String(e)}}}export{RZ as createGraphRAGAgent,zZ as streamAgentResponse};