gitnexus 1.6.6-rc.76 → 1.6.6-rc.78

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 (42) hide show
  1. package/dist/core/ingestion/languages/python/captures.js +3 -0
  2. package/dist/core/ingestion/languages/python/depends-references.d.ts +19 -0
  3. package/dist/core/ingestion/languages/python/depends-references.js +65 -0
  4. package/dist/core/ingestion/parsing-processor.d.ts +2 -1
  5. package/dist/core/ingestion/parsing-processor.js +5 -0
  6. package/dist/core/ingestion/pipeline-phases/parse-impl.d.ts +2 -1
  7. package/dist/core/ingestion/pipeline-phases/parse-impl.js +6 -0
  8. package/dist/core/ingestion/pipeline-phases/parse.d.ts +2 -1
  9. package/dist/core/ingestion/pipeline-phases/routes.js +29 -1
  10. package/dist/core/ingestion/tree-sitter-queries.d.ts +2 -2
  11. package/dist/core/ingestion/tree-sitter-queries.js +12 -0
  12. package/dist/core/ingestion/workers/parse-worker.d.ts +5 -0
  13. package/dist/core/ingestion/workers/parse-worker.js +35 -0
  14. package/dist/storage/parse-cache.js +1 -1
  15. package/package.json +1 -1
  16. package/web/assets/{agent-ztCmSzAP.js → agent-BRX-afm3.js} +68 -67
  17. package/web/assets/{architectureDiagram-UL44E2DR-UbBGKtKc.js → architectureDiagram-UL44E2DR-B1oYB8-c.js} +1 -1
  18. package/web/assets/{chunk-LCXTWHL2-CNag8uwS.js → chunk-LCXTWHL2-SPC6pgWI.js} +1 -1
  19. package/web/assets/{chunk-RG4AUYOV-BsPxAzSB.js → chunk-RG4AUYOV-DZXr4Yv3.js} +1 -1
  20. package/web/assets/{classDiagram-KGZ6W3CR-hyXalbgI.js → classDiagram-KGZ6W3CR-BqpOj8L9.js} +1 -1
  21. package/web/assets/{classDiagram-v2-72OJOZXJ-BZvBt1Jw.js → classDiagram-v2-72OJOZXJ-FmElywK2.js} +1 -1
  22. package/web/assets/{diagram-3NCE3AQN-BPy1qvxM.js → diagram-3NCE3AQN-BWtJXMDq.js} +1 -1
  23. package/web/assets/{diagram-GF46GFSD-DHZvmDr6.js → diagram-GF46GFSD-Hh-fChxU.js} +1 -1
  24. package/web/assets/{diagram-QXG6HAR7-h2JaRLwM.js → diagram-QXG6HAR7-DYeQHxGU.js} +1 -1
  25. package/web/assets/{diagram-WEQXMOUZ-BQasYj8c.js → diagram-WEQXMOUZ-DYGU4T0y.js} +1 -1
  26. package/web/assets/{erDiagram-L5TCEMPS-CKNmoGli.js → erDiagram-L5TCEMPS-bN3wlP2A.js} +1 -1
  27. package/web/assets/{flowDiagram-H6V6AXG4-BUtBrFuB.js → flowDiagram-H6V6AXG4-YACVtF3-.js} +1 -1
  28. package/web/assets/{index-BTynj0rU.js → index-BhnAdWTt.js} +5 -5
  29. package/web/assets/{infoDiagram-3YFTVSEB-FmBeKKHR.js → infoDiagram-3YFTVSEB-BWBzD28-.js} +1 -1
  30. package/web/assets/{ishikawaDiagram-BNXS4ZKH-CBIehaQ8.js → ishikawaDiagram-BNXS4ZKH-B8qYT-j9.js} +1 -1
  31. package/web/assets/{kanban-definition-75IXJCU3-BkQHGPDZ.js → kanban-definition-75IXJCU3-BeoPr5Tl.js} +1 -1
  32. package/web/assets/{mindmap-definition-2TDM6QVE-CtjovahQ.js → mindmap-definition-2TDM6QVE-CdLLN_so.js} +1 -1
  33. package/web/assets/{pieDiagram-CU6KROY3-DJ7mL2OO.js → pieDiagram-CU6KROY3-DEd2a_k_.js} +1 -1
  34. package/web/assets/{requirementDiagram-JXO7QTGE-BQ-a2UHa.js → requirementDiagram-JXO7QTGE-QNeTo5C_.js} +1 -1
  35. package/web/assets/{sequenceDiagram-VS2MUI6T-Dq-E41TD.js → sequenceDiagram-VS2MUI6T-BHC7q7yJ.js} +1 -1
  36. package/web/assets/{stateDiagram-7D4R322I-DyXkAThk.js → stateDiagram-7D4R322I-KONnc2Px.js} +1 -1
  37. package/web/assets/{stateDiagram-v2-36443NZ5-x6kVl63Y.js → stateDiagram-v2-36443NZ5-C2QfuMlu.js} +1 -1
  38. package/web/assets/{timeline-definition-O6YCAMPW-CnIsqFeF.js → timeline-definition-O6YCAMPW-D4t4NJx1.js} +1 -1
  39. package/web/assets/{vennDiagram-MWXL3ELB-Ce24QI5i.js → vennDiagram-MWXL3ELB-6bctC9Yg.js} +1 -1
  40. package/web/assets/{wardleyDiagram-CUQ6CDDI-BFmc79Jd.js → wardleyDiagram-CUQ6CDDI-BPZYNTvC.js} +1 -1
  41. package/web/assets/{xychartDiagram-N2JHSOCM-CIcd2MDJ.js → xychartDiagram-N2JHSOCM-lBI9O6DW.js} +1 -1
  42. package/web/index.html +1 -1
@@ -1,4 +1,4 @@
1
- import{r as e,t}from"./chunk-CilyBKbf.js";import{o as n,s as r}from"./index-BTynj0rU.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
1
+ import{r as e,t}from"./chunk-CilyBKbf.js";import{o as n,s as r}from"./index-BhnAdWTt.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
2
  `)?r=r.substring(5):r.startsWith(`json`)?r=r.substring(4):r.startsWith(`
3
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
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()}})),te=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})),ne=e(ee(),1),x=e(te(),1);function re(e,t){return t?.[e]||(0,ne.default)(e)}function ie(e,t){return t?.[e]||(0,x.default)(e)}function ae(e,t,n){let r={};for(let i in e)Object.hasOwn(e,i)&&(r[t(i,n)]=e[i]);return r}var oe=`__lc_escaped__`;function se(e){return`lc`in e||Object.keys(e).length===1&&`__lc_escaped__`in e}function ce(e){return{[oe]:e}}function le(e){return Object.keys(e).length===1&&`__lc_escaped__`in e}function S(e){return typeof e==`object`&&!!e&&`lc_serializable`in e&&typeof e.toJSON==`function`}function ue(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 de(e,t=new WeakSet){if(typeof e==`object`&&e&&!Array.isArray(e)){if(t.has(e))return ue(e);if(S(e))return e;t.add(e);let n=e;if(se(n))return t.delete(e),ce(n);let r={};for(let[e,i]of Object.entries(n))r[e]=de(i,t);return t.delete(e),r}return Array.isArray(e)?e.map(e=>de(e,t)):e}function fe(e){if(typeof e==`object`&&e&&!Array.isArray(e)){let t=e;if(le(t))return t[oe];let n={};for(let[e,r]of Object.entries(t))n[e]=fe(r);return n}return Array.isArray(e)?e.map(e=>fe(e)):e}var pe=o({Serializable:()=>_e,get_lc_unique_name:()=>ge});function me(e){return Array.isArray(e)?[...e]:{...e}}function he(e,t){let n=me(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]=me(a[e]),a=a[e]}a[t]!==void 0&&(a[t]={lc:1,type:`secret`,id:[r]})}return n}function ge(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 _e=class e{lc_serializable=!1;lc_kwargs;static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,ge(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]=de(t,a);let o=ae(Object.keys(n).length?he(i,n):i,re,t);return{lc:1,type:`constructor`,id:this.lc_id,kwargs:o}}toJSONNotImplemented(){return{lc:1,type:`not_implemented`,id:this.lc_id}}};function ve(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 ye(e){return ve(e)&&e.source_type===`url`&&`url`in e&&typeof e.url==`string`}function be(e){return ve(e)&&e.source_type===`base64`&&`data`in e&&typeof e.data==`string`}function xe(e){return ve(e)&&e.source_type===`text`&&`text`in e&&typeof e.text==`string`}function Se(e){return ve(e)&&e.source_type===`id`&&`id`in e&&typeof e.id==`string`}function Ce(e){if(ve(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 we(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 Te({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 Ee(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 C(e,t){return w(e)&&e.type===t}function w(e){return typeof e==`object`&&!!e}function De(e){return Array.isArray(e)}function T(e){return typeof e==`string`}function Oe(e){return typeof e==`number`}function ke(e){return e instanceof Uint8Array}function E(e){try{return JSON.parse(e)}catch{return}}var Ae=e=>e();function je(e){if(e.type===`char_location`&&T(e.document_title)&&Oe(e.start_char_index)&&Oe(e.end_char_index)&&T(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`&&T(e.document_title)&&Oe(e.start_page_number)&&Oe(e.end_page_number)&&T(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`&&T(e.document_title)&&Oe(e.start_block_index)&&Oe(e.end_block_index)&&T(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`&&T(e.url)&&T(e.title)&&T(e.encrypted_index)&&T(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`&&T(e.source)&&T(e.title)&&Oe(e.start_block_index)&&Oe(e.end_block_index)&&T(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 Me(e){if(C(e,`document`)&&w(e.source)&&`type`in e.source){if(e.source.type===`base64`&&T(e.source.media_type)&&T(e.source.data))return{type:`file`,mimeType:e.source.media_type,data:e.source.data};if(e.source.type===`url`&&T(e.source.url))return{type:`file`,url:e.source.url};if(e.source.type===`file`&&T(e.source.file_id))return{type:`file`,fileId:e.source.file_id};if(e.source.type===`text`&&T(e.source.data))return{type:`file`,mimeType:String(e.source.media_type??`text/plain`),data:e.source.data}}else if(C(e,`image`)&&w(e.source)&&`type`in e.source){if(e.source.type===`base64`&&T(e.source.media_type)&&T(e.source.data))return{type:`image`,mimeType:e.source.media_type,data:e.source.data};if(e.source.type===`url`&&T(e.source.url))return{type:`image`,url:e.source.url};if(e.source.type===`file`&&T(e.source.file_id))return{type:`image`,fileId:e.source.file_id}}}function Ne(e){function*t(){for(let t of e){let e=Me(t);e?yield e:yield t}}return Array.from(t())}function Pe(e){function*t(){let t=typeof e.content==`string`?[{type:`text`,text:e.content}]:e.content;for(let n of t){if(C(n,`text`)&&T(n.text)){let{text:e,citations:t,...r}=n;if(De(t)&&t.length){let n=t.reduce((e,t)=>{let n=je(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(C(n,`thinking`)&&T(n.thinking)){let{thinking:e,signature:t,...r}=n;yield{...r,type:`reasoning`,reasoning:e,signature:t};continue}else if(C(n,`redacted_thinking`)){yield{type:`non_standard`,value:n};continue}else if(C(n,`tool_use`)&&T(n.name)&&T(n.id)){yield{type:`tool_call`,id:n.id,name:n.name,args:n.input};continue}else if(C(n,`input_json_delta`)){if(Ie(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(C(n,`server_tool_use`)&&T(n.name)&&T(n.id)){let{name:e,id:t}=n;if(e===`web_search`){yield{id:t,type:`server_tool_call`,name:`web_search`,args:{query:Ae(()=>{if(typeof n.input==`string`)return n.input;if(w(n.input)&&T(n.input.query))return n.input.query;if(T(n.partial_json)){let e=E(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:Ae(()=>{if(typeof n.input==`string`)return n.input;if(w(n.input)&&T(n.input.code))return n.input.code;if(T(n.partial_json)){let e=E(n.partial_json);if(e?.code)return e.code}return``})}};continue}}else if(C(n,`web_search_tool_result`)&&T(n.tool_use_id)&&De(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)=>C(t,`web_search_result`)?[...e,t.url]:e,[])}};continue}else if(C(n,`code_execution_tool_result`)&&T(n.tool_use_id)&&w(n.content)){yield{type:`server_tool_call_result`,name:`code_execution`,toolCallId:n.tool_use_id,status:`success`,output:n.content};continue}else if(C(n,`mcp_tool_use`)){yield{id:n.id,type:`server_tool_call`,name:`mcp_tool_use`,args:n.input};continue}else if(C(n,`mcp_tool_result`)&&T(n.tool_use_id)&&w(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(C(n,`container_upload`)){yield{type:`server_tool_call`,name:`container_upload`,args:n.input};continue}else if(C(n,`search_result`)){yield{id:n.id,type:`non_standard`,value:n};continue}else if(C(n,`tool_result`)){yield{id:n.id,type:`non_standard`,value:n};continue}else{let e=Me(n);if(e){yield e;continue}}yield{type:`non_standard`,value:n}}}return Array.from(t())}var Fe={translateContent:Pe,translateContentChunk:Pe};function Ie(e){return typeof e?._getType==`function`&&typeof e.concat==`function`&&e._getType()===`ai`}function Le(e){return ye(e)?{type:e.type,mimeType:e.mime_type,url:e.url,metadata:e.metadata}:be(e)?{type:e.type,mimeType:e.mime_type??`application/octet-stream`,data:e.data,metadata:e.metadata}:Se(e)?{type:e.type,mimeType:e.mime_type,fileId:e.id,metadata:e.metadata}:e}function Re(e){return e.map(Le)}function ze(e){return!!(C(e,`image_url`)&&w(e.image_url)||C(e,`input_audio`)&&w(e.input_audio)||C(e,`file`)&&w(e.file))}function Be(e){if(C(e,`image_url`)&&w(e.image_url)&&T(e.image_url.url)){let t=Te({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(C(e,`input_audio`)&&w(e.input_audio)&&T(e.input_audio.data)&&T(e.input_audio.format))return{type:`audio`,data:e.input_audio.data,mimeType:`audio/${e.input_audio.format}`};else if(C(e,`file`)&&w(e.file)&&T(e.file.data)){let t=Te({dataUrl:e.file.data});if(t)return{type:`file`,data:t.data,mimeType:t.mime_type};if(T(e.file.file_id))return{type:`file`,fileId:e.file.file_id}}return e}function Ve(e){let t=[];typeof e.content==`string`?e.content.length>0&&t.push({type:`text`,text:e.content}):t.push(...Ue(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=[];typeof e.content==`string`?e.content.length>0&&t.push({type:`text`,text:e.content}):t.push(...Ue(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 Ue(e){let t=[];for(let n of e)ze(n)?t.push(Be(n)):t.push(n);return t}function We(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 Ge(e){function*t(){w(e.additional_kwargs?.reasoning)&&De(e.additional_kwargs.reasoning.summary)&&(yield{type:`reasoning`,reasoning:e.additional_kwargs.reasoning.summary.reduce((e,t)=>w(t)&&T(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(C(e,`text`)){let{text:t,annotations:n,phase:r,extras:i,...a}=e,o=w(i)?{...i}:{};T(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(We)}: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(w(e.additional_kwargs)&&De(e.additional_kwargs.tool_outputs))for(let t of e.additional_kwargs.tool_outputs){if(C(t,`web_search_call`)){let e={};if(w(t.action)&&T(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={};w(t.action)&&(e.action=t.action),yield{type:`server_tool_call_result`,toolCallId:T(t.id)?t.id:``,status:t.status===`completed`?`success`:`error`,output:e}}continue}else if(C(t,`file_search_call`)){yield{id:t.id,type:`server_tool_call`,name:`file_search`,args:{queries:De(t.queries)?t.queries:[]}},(t.status===`completed`||t.status===`failed`)&&(yield{type:`server_tool_call_result`,toolCallId:T(t.id)?t.id:``,status:t.status===`completed`?`success`:`error`,output:De(t.results)?{results:t.results}:{}});continue}else if(C(t,`computer_call`)){yield{type:`non_standard`,value:t};continue}else if(C(t,`code_interpreter_call`)){if(T(t.code)&&(yield{id:t.id,type:`server_tool_call`,name:`code_interpreter`,args:{code:t.code}}),De(t.outputs)){let e=Ae(()=>{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(C(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(C(t,`mcp_call`)){yield{id:t.id,type:`server_tool_call`,name:`mcp_call`,args:t.input};continue}else if(C(t,`mcp_list_tools`)){yield{id:t.id,type:`server_tool_call`,name:`mcp_list_tools`,args:t.input};continue}else if(C(t,`mcp_approval_request`)){yield{type:`non_standard`,value:t};continue}else if(C(t,`tool_search_call`)){let e={};w(t.arguments)&&Object.assign(e,t.arguments);let n={};T(t.execution)&&(n.execution=t.execution),T(t.status)&&(n.status=t.status),T(t.call_id)&&(n.call_id=t.call_id),yield{id:T(t.id)?t.id:``,type:`server_tool_call`,name:`tool_search`,args:e,...Object.keys(n).length>0?{extras:n}:{}};continue}else if(C(t,`tool_search_output`)){let e={name:`tool_search`};T(t.execution)&&(e.execution=t.execution),yield{type:`server_tool_call_result`,toolCallId:T(t.id)?t.id:``,status:t.status===`completed`?`success`:t.status===`failed`?`error`:`success`,output:{tools:De(t.tools)?t.tools:[]},extras:e};continue}else if(C(t,`image_generation_call`)){T(t.result)&&(yield{type:`image`,mimeType:`image/png`,data:t.result,id:T(t.id)?t.id:void 0,metadata:{status:T(t.status)?t.status:void 0}}),yield{type:`non_standard`,value:t};continue}w(t)&&(yield{type:`non_standard`,value:t})}}return Array.from(t())}function Ke(e){function*t(){yield*Ge(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 qe={translateContent:e=>typeof e.content==`string`?Ve(e):Ge(e),translateContentChunk:e=>typeof e.content==`string`?He(e):Ke(e)};function Je(e){return typeof e==`object`&&!!e&&`type`in e&&`content`in e&&(typeof e.content==`string`||Array.isArray(e.content))}function Ye(e,t=`pretty`){return t===`pretty`?Xe(e):JSON.stringify(e)}function Xe(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(`
@@ -90,27 +90,27 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
90
90
  `;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=Qg.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(`
91
91
  `)}</em></small>`);let o=(n[r]??n[t]).replace(`{0}`,Zg(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${Zg(e)}${a}${Zg(n)};\n`}t&&!n&&(l+=` end
92
92
  `)}p(u[``]??[],``);for(let e in u)!e.includes(`:`)&&e!==``&&p(u[e],e);return o&&(l+=$g(a??{})),l}async function t_(e,t){let n=t?.backgroundColor??`white`,r=t?.imageType??`png`,i=Gu(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(`
93
- `));return await o.blob()}var n_=Symbol(`Let zodToJsonSchema decide on which parser to use`),r_={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`},i_=e=>typeof e==`string`?{...r_,name:e}:{...r_,...e},a_=e=>{let t=i_(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}]))}},o_=(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 s_(e){if(e.target!==`openAi`)return{};let t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy===`relative`?o_(t,e.currentPath):t.join(`/`)}}function c_(e,t,n,r){r?.errorMessages&&n&&(e.errorMessage={...e.errorMessage,[t]:n})}function l_(e,t,n,r,i){e[t]=n,c_(e,t,r,i)}var u_;(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})(u_||={});var d_;(function(e){e.mergeShapes=(e,t)=>({...e,...t})})(d_||={});var M=u_.arrayToEnum([`string`,`nan`,`number`,`integer`,`float`,`boolean`,`date`,`bigint`,`symbol`,`function`,`undefined`,`null`,`array`,`object`,`unknown`,`promise`,`void`,`never`,`map`,`set`]),f_=e=>{switch(typeof e){case`undefined`:return M.undefined;case`string`:return M.string;case`number`:return Number.isNaN(e)?M.nan:M.number;case`boolean`:return M.boolean;case`function`:return M.function;case`bigint`:return M.bigint;case`symbol`:return M.symbol;case`object`:return Array.isArray(e)?M.array:e===null?M.null:e.then&&typeof e.then==`function`&&e.catch&&typeof e.catch==`function`?M.promise:typeof Map<`u`&&e instanceof Map?M.map:typeof Set<`u`&&e instanceof Set?M.set:typeof Date<`u`&&e instanceof Date?M.date:M.object;default:return M.unknown}},N=u_.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`]),p_=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,u_.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=e=>e.message){let t=Object.create(null),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()}};p_.create=e=>new p_(e);var m_=(e,t)=>{let n;switch(e.code){case N.invalid_type:n=e.received===M.undefined?`Required`:`Expected ${e.expected}, received ${e.received}`;break;case N.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,u_.jsonStringifyReplacer)}`;break;case N.unrecognized_keys:n=`Unrecognized key(s) in object: ${u_.joinValues(e.keys,`, `)}`;break;case N.invalid_union:n=`Invalid input`;break;case N.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${u_.joinValues(e.options)}`;break;case N.invalid_enum_value:n=`Invalid enum value. Expected ${u_.joinValues(e.options)}, received '${e.received}'`;break;case N.invalid_arguments:n=`Invalid function arguments`;break;case N.invalid_return_type:n=`Invalid function return type`;break;case N.invalid_date:n=`Invalid date`;break;case N.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}"`:u_.assertNever(e.validation):n=e.validation===`regex`?`Invalid`:`Invalid ${e.validation}`;break;case N.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 N.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 N.custom:n=`Invalid input`;break;case N.invalid_intersection_types:n=`Intersection results could not be merged`;break;case N.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case N.not_finite:n=`Number must be finite`;break;default:n=t.defaultError,u_.assertNever(e)}return{message:n}},h_=m_;function g_(){return h_}var __=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 P(e,t){let n=g_(),r=__({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===m_?void 0:m_].filter(e=>!!e)});e.common.issues.push(r)}var v_=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 F;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 F;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}}},F=Object.freeze({status:`aborted`}),y_=e=>({status:`dirty`,value:e}),b_=e=>({status:`valid`,value:e}),x_=e=>e.status===`aborted`,S_=e=>e.status===`dirty`,C_=e=>e.status===`valid`,w_=e=>typeof Promise<`u`&&e instanceof Promise,I;(function(e){e.errToObj=e=>typeof e==`string`?{message:e}:e||{},e.toString=e=>typeof e==`string`?e:e?.message})(I||={});var T_=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}},E_=(e,t)=>{if(C_(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 p_(e.common.issues);return this._error=t,this._error}}};function D_(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 O_=class{get description(){return this._def.description}_getType(e){return f_(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:f_(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new v_,ctx:{common:e.parent.common,data:e.data,parsedType:f_(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(w_(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:f_(e)};return E_(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:f_(e)};if(!this[`~standard`].async)try{let n=this._parseSync({data:e,path:[],parent:t});return C_(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=>C_(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:f_(e)},r=this._parse({data:e,path:n.path,parent:n});return E_(n,await(w_(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:N.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 jv({schema:this,typeName:L.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 Mv.create(this,this._def)}nullable(){return Nv.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return fv.create(this)}promise(){return Av.create(this,this._def)}or(e){return hv.create([this,e],this._def)}and(e){return yv.create(this,e,this._def)}transform(e){return new jv({...D_(this._def),schema:this,typeName:L.ZodEffects,effect:{type:`transform`,transform:e}})}default(e){let t=typeof e==`function`?e:()=>e;return new Pv({...D_(this._def),innerType:this,defaultValue:t,typeName:L.ZodDefault})}brand(){return new Lv({typeName:L.ZodBranded,type:this,...D_(this._def)})}catch(e){let t=typeof e==`function`?e:()=>e;return new Fv({...D_(this._def),innerType:this,catchValue:t,typeName:L.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return Rv.create(this,e)}readonly(){return zv.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},k_=/^c[^\s-]{8,}$/i,A_=/^[0-9a-z]+$/,j_=/^[0-9A-HJKMNP-TV-Z]{26}$/i,M_=/^[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,N_=/^[a-z0-9_-]{21}$/i,P_=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,F_=/^[-+]?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)?)??$/,I_=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,L_=`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,R_,z_=/^(?:(?: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])$/,B_=/^(?:(?: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])$/,V_=/^(([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]))$/,H_=/^(([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])$/,U_=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,W_=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,G_=`((\\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])))`,K_=RegExp(`^${G_}$`);function q_(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 J_(e){return RegExp(`^${q_(e)}$`)}function Y_(e){let t=`${G_}T${q_(e)}`,n=[];return n.push(e.local?`Z?`:`Z`),e.offset&&n.push(`([+-]\\d{2}:?\\d{2})`),t=`${t}(${n.join(`|`)})`,RegExp(`^${t}$`)}function X_(e,t){return!!((t===`v4`||!t)&&z_.test(e)||(t===`v6`||!t)&&V_.test(e))}function Z_(e,t){if(!P_.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 Q_(e,t){return!!((t===`v4`||!t)&&B_.test(e)||(t===`v6`||!t)&&H_.test(e))}var $_=class e extends O_{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==M.string){let t=this._getOrReturnCtx(e);return P(t,{code:N.invalid_type,expected:M.string,received:t.parsedType}),F}let t=new v_,n;for(let r of this._def.checks)if(r.kind===`min`)e.data.length<r.value&&(n=this._getOrReturnCtx(e,n),P(n,{code:N.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),P(n,{code:N.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?P(n,{code:N.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}):a&&P(n,{code:N.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}),t.dirty())}else if(r.kind===`email`)I_.test(e.data)||(n=this._getOrReturnCtx(e,n),P(n,{validation:`email`,code:N.invalid_string,message:r.message}),t.dirty());else if(r.kind===`emoji`)R_||=new RegExp(L_,`u`),R_.test(e.data)||(n=this._getOrReturnCtx(e,n),P(n,{validation:`emoji`,code:N.invalid_string,message:r.message}),t.dirty());else if(r.kind===`uuid`)M_.test(e.data)||(n=this._getOrReturnCtx(e,n),P(n,{validation:`uuid`,code:N.invalid_string,message:r.message}),t.dirty());else if(r.kind===`nanoid`)N_.test(e.data)||(n=this._getOrReturnCtx(e,n),P(n,{validation:`nanoid`,code:N.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid`)k_.test(e.data)||(n=this._getOrReturnCtx(e,n),P(n,{validation:`cuid`,code:N.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid2`)A_.test(e.data)||(n=this._getOrReturnCtx(e,n),P(n,{validation:`cuid2`,code:N.invalid_string,message:r.message}),t.dirty());else if(r.kind===`ulid`)j_.test(e.data)||(n=this._getOrReturnCtx(e,n),P(n,{validation:`ulid`,code:N.invalid_string,message:r.message}),t.dirty());else if(r.kind===`url`)try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),P(n,{validation:`url`,code:N.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),P(n,{validation:`regex`,code:N.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),P(n,{code:N.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),P(n,{code:N.invalid_string,validation:{startsWith:r.value},message:r.message}),t.dirty()):r.kind===`endsWith`?e.data.endsWith(r.value)||(n=this._getOrReturnCtx(e,n),P(n,{code:N.invalid_string,validation:{endsWith:r.value},message:r.message}),t.dirty()):r.kind===`datetime`?Y_(r).test(e.data)||(n=this._getOrReturnCtx(e,n),P(n,{code:N.invalid_string,validation:`datetime`,message:r.message}),t.dirty()):r.kind===`date`?K_.test(e.data)||(n=this._getOrReturnCtx(e,n),P(n,{code:N.invalid_string,validation:`date`,message:r.message}),t.dirty()):r.kind===`time`?J_(r).test(e.data)||(n=this._getOrReturnCtx(e,n),P(n,{code:N.invalid_string,validation:`time`,message:r.message}),t.dirty()):r.kind===`duration`?F_.test(e.data)||(n=this._getOrReturnCtx(e,n),P(n,{validation:`duration`,code:N.invalid_string,message:r.message}),t.dirty()):r.kind===`ip`?X_(e.data,r.version)||(n=this._getOrReturnCtx(e,n),P(n,{validation:`ip`,code:N.invalid_string,message:r.message}),t.dirty()):r.kind===`jwt`?Z_(e.data,r.alg)||(n=this._getOrReturnCtx(e,n),P(n,{validation:`jwt`,code:N.invalid_string,message:r.message}),t.dirty()):r.kind===`cidr`?Q_(e.data,r.version)||(n=this._getOrReturnCtx(e,n),P(n,{validation:`cidr`,code:N.invalid_string,message:r.message}),t.dirty()):r.kind===`base64`?U_.test(e.data)||(n=this._getOrReturnCtx(e,n),P(n,{validation:`base64`,code:N.invalid_string,message:r.message}),t.dirty()):r.kind===`base64url`?W_.test(e.data)||(n=this._getOrReturnCtx(e,n),P(n,{validation:`base64url`,code:N.invalid_string,message:r.message}),t.dirty()):u_.assertNever(r);return{status:t.value,value:e.data}}_regex(e,t,n){return this.refinement(t=>e.test(t),{validation:t,code:N.invalid_string,...I.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(e){return this._addCheck({kind:`email`,...I.errToObj(e)})}url(e){return this._addCheck({kind:`url`,...I.errToObj(e)})}emoji(e){return this._addCheck({kind:`emoji`,...I.errToObj(e)})}uuid(e){return this._addCheck({kind:`uuid`,...I.errToObj(e)})}nanoid(e){return this._addCheck({kind:`nanoid`,...I.errToObj(e)})}cuid(e){return this._addCheck({kind:`cuid`,...I.errToObj(e)})}cuid2(e){return this._addCheck({kind:`cuid2`,...I.errToObj(e)})}ulid(e){return this._addCheck({kind:`ulid`,...I.errToObj(e)})}base64(e){return this._addCheck({kind:`base64`,...I.errToObj(e)})}base64url(e){return this._addCheck({kind:`base64url`,...I.errToObj(e)})}jwt(e){return this._addCheck({kind:`jwt`,...I.errToObj(e)})}ip(e){return this._addCheck({kind:`ip`,...I.errToObj(e)})}cidr(e){return this._addCheck({kind:`cidr`,...I.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,...I.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,...I.errToObj(e?.message)})}duration(e){return this._addCheck({kind:`duration`,...I.errToObj(e)})}regex(e,t){return this._addCheck({kind:`regex`,regex:e,...I.errToObj(t)})}includes(e,t){return this._addCheck({kind:`includes`,value:e,position:t?.position,...I.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:`startsWith`,value:e,...I.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:`endsWith`,value:e,...I.errToObj(t)})}min(e,t){return this._addCheck({kind:`min`,value:e,...I.errToObj(t)})}max(e,t){return this._addCheck({kind:`max`,value:e,...I.errToObj(t)})}length(e,t){return this._addCheck({kind:`length`,value:e,...I.errToObj(t)})}nonempty(e){return this.min(1,I.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}};$_.create=e=>new $_({checks:[],typeName:L.ZodString,coerce:e?.coerce??!1,...D_(e)});function ev(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 tv=class e extends O_{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)!==M.number){let t=this._getOrReturnCtx(e);return P(t,{code:N.invalid_type,expected:M.number,received:t.parsedType}),F}let t,n=new v_;for(let r of this._def.checks)r.kind===`int`?u_.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),P(t,{code:N.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),P(t,{code:N.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),P(t,{code:N.too_big,maximum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`multipleOf`?ev(e.data,r.value)!==0&&(t=this._getOrReturnCtx(e,t),P(t,{code:N.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):r.kind===`finite`?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),P(t,{code:N.not_finite,message:r.message}),n.dirty()):u_.assertNever(r);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit(`min`,e,!0,I.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,I.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,I.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,I.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:I.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(e){return this._addCheck({kind:`int`,message:I.toString(e)})}positive(e){return this._addCheck({kind:`min`,value:0,inclusive:!1,message:I.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:0,inclusive:!1,message:I.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:0,inclusive:!0,message:I.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:0,inclusive:!0,message:I.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:I.toString(t)})}finite(e){return this._addCheck({kind:`finite`,message:I.toString(e)})}safe(e){return this._addCheck({kind:`min`,inclusive:!0,value:-(2**53-1),message:I.toString(e)})._addCheck({kind:`max`,inclusive:!0,value:2**53-1,message:I.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`&&u_.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)}};tv.create=e=>new tv({checks:[],typeName:L.ZodNumber,coerce:e?.coerce||!1,...D_(e)});var nv=class e extends O_{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)!==M.bigint)return this._getInvalidInput(e);let t,n=new v_;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),P(t,{code:N.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),P(t,{code:N.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),P(t,{code:N.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):u_.assertNever(r);return{status:n.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return P(t,{code:N.invalid_type,expected:M.bigint,received:t.parsedType}),F}gte(e,t){return this.setLimit(`min`,e,!0,I.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,I.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,I.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,I.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:I.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:I.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!1,message:I.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!0,message:I.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!0,message:I.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:I.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}};nv.create=e=>new nv({checks:[],typeName:L.ZodBigInt,coerce:e?.coerce??!1,...D_(e)});var rv=class extends O_{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==M.boolean){let t=this._getOrReturnCtx(e);return P(t,{code:N.invalid_type,expected:M.boolean,received:t.parsedType}),F}return b_(e.data)}};rv.create=e=>new rv({typeName:L.ZodBoolean,coerce:e?.coerce||!1,...D_(e)});var iv=class e extends O_{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==M.date){let t=this._getOrReturnCtx(e);return P(t,{code:N.invalid_type,expected:M.date,received:t.parsedType}),F}if(Number.isNaN(e.data.getTime()))return P(this._getOrReturnCtx(e),{code:N.invalid_date}),F;let t=new v_,n;for(let r of this._def.checks)r.kind===`min`?e.data.getTime()<r.value&&(n=this._getOrReturnCtx(e,n),P(n,{code:N.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),P(n,{code:N.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:`date`}),t.dirty()):u_.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:I.toString(t)})}max(e,t){return this._addCheck({kind:`max`,value:e.getTime(),message:I.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)}};iv.create=e=>new iv({checks:[],coerce:e?.coerce||!1,typeName:L.ZodDate,...D_(e)});var av=class extends O_{_parse(e){if(this._getType(e)!==M.symbol){let t=this._getOrReturnCtx(e);return P(t,{code:N.invalid_type,expected:M.symbol,received:t.parsedType}),F}return b_(e.data)}};av.create=e=>new av({typeName:L.ZodSymbol,...D_(e)});var ov=class extends O_{_parse(e){if(this._getType(e)!==M.undefined){let t=this._getOrReturnCtx(e);return P(t,{code:N.invalid_type,expected:M.undefined,received:t.parsedType}),F}return b_(e.data)}};ov.create=e=>new ov({typeName:L.ZodUndefined,...D_(e)});var sv=class extends O_{_parse(e){if(this._getType(e)!==M.null){let t=this._getOrReturnCtx(e);return P(t,{code:N.invalid_type,expected:M.null,received:t.parsedType}),F}return b_(e.data)}};sv.create=e=>new sv({typeName:L.ZodNull,...D_(e)});var cv=class extends O_{constructor(){super(...arguments),this._any=!0}_parse(e){return b_(e.data)}};cv.create=e=>new cv({typeName:L.ZodAny,...D_(e)});var lv=class extends O_{constructor(){super(...arguments),this._unknown=!0}_parse(e){return b_(e.data)}};lv.create=e=>new lv({typeName:L.ZodUnknown,...D_(e)});var uv=class extends O_{_parse(e){let t=this._getOrReturnCtx(e);return P(t,{code:N.invalid_type,expected:M.never,received:t.parsedType}),F}};uv.create=e=>new uv({typeName:L.ZodNever,...D_(e)});var dv=class extends O_{_parse(e){if(this._getType(e)!==M.undefined){let t=this._getOrReturnCtx(e);return P(t,{code:N.invalid_type,expected:M.void,received:t.parsedType}),F}return b_(e.data)}};dv.create=e=>new dv({typeName:L.ZodVoid,...D_(e)});var fv=class e extends O_{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),r=this._def;if(t.parsedType!==M.array)return P(t,{code:N.invalid_type,expected:M.array,received:t.parsedType}),F;if(r.exactLength!==null){let e=t.data.length>r.exactLength.value,i=t.data.length<r.exactLength.value;(e||i)&&(P(t,{code:e?N.too_big:N.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&&(P(t,{code:N.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&&(P(t,{code:N.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 T_(t,e,t.path,n)))).then(e=>v_.mergeArray(n,e));let i=[...t.data].map((e,n)=>r.type._parseSync(new T_(t,e,t.path,n)));return v_.mergeArray(n,i)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:I.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:I.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:I.toString(n)}})}nonempty(e){return this.min(1,e)}};fv.create=(e,t)=>new fv({type:e,minLength:null,maxLength:null,exactLength:null,typeName:L.ZodArray,...D_(t)});function pv(e){if(e instanceof mv){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=Mv.create(pv(r))}return new mv({...e._def,shape:()=>t})}else if(e instanceof fv)return new fv({...e._def,type:pv(e.element)});else if(e instanceof Mv)return Mv.create(pv(e.unwrap()));else if(e instanceof Nv)return Nv.create(pv(e.unwrap()));else if(e instanceof bv)return bv.create(e.items.map(e=>pv(e)));else return e}var mv=class e extends O_{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=u_.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==M.object){let t=this._getOrReturnCtx(e);return P(t,{code:N.invalid_type,expected:M.object,received:t.parsedType}),F}let{status:t,ctx:n}=this._processInputParams(e),{shape:r,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof uv&&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 T_(n,i,n.path,e)),alwaysSet:e in n.data})}if(this._def.catchall instanceof uv){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&&(P(n,{code:N.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 T_(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=>v_.mergeObjectSync(t,e)):v_.mergeObjectSync(t,o)}get shape(){return this._def.shape()}strict(t){return I.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:I.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:L.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 u_.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 u_.objectKeys(this.shape))t[e]||(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}deepPartial(){return pv(this)}partial(t){let n={};for(let e of u_.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 u_.objectKeys(this.shape))if(t&&!t[e])n[e]=this.shape[e];else{let t=this.shape[e];for(;t instanceof Mv;)t=t._def.innerType;n[e]=t}return new e({...this._def,shape:()=>n})}keyof(){return Dv(u_.objectKeys(this.shape))}};mv.create=(e,t)=>new mv({shape:()=>e,unknownKeys:`strip`,catchall:uv.create(),typeName:L.ZodObject,...D_(t)}),mv.strictCreate=(e,t)=>new mv({shape:()=>e,unknownKeys:`strict`,catchall:uv.create(),typeName:L.ZodObject,...D_(t)}),mv.lazycreate=(e,t)=>new mv({shape:e,unknownKeys:`strip`,catchall:uv.create(),typeName:L.ZodObject,...D_(t)});var hv=class extends O_{_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 p_(e.ctx.common.issues));return P(t,{code:N.invalid_union,unionErrors:n}),F}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 p_(e));return P(t,{code:N.invalid_union,unionErrors:i}),F}}get options(){return this._def.options}};hv.create=(e,t)=>new hv({options:e,typeName:L.ZodUnion,...D_(t)});var gv=e=>e instanceof Tv?gv(e.schema):e instanceof jv?gv(e.innerType()):e instanceof Ev?[e.value]:e instanceof Ov?e.options:e instanceof kv?u_.objectValues(e.enum):e instanceof Pv?gv(e._def.innerType):e instanceof ov?[void 0]:e instanceof sv?[null]:e instanceof Mv?[void 0,...gv(e.unwrap())]:e instanceof Nv?[null,...gv(e.unwrap())]:e instanceof Lv||e instanceof zv?gv(e.unwrap()):e instanceof Fv?gv(e._def.innerType):[],_v=class e extends O_{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==M.object)return P(t,{code:N.invalid_type,expected:M.object,received:t.parsedType}),F;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}):(P(t,{code:N.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),F)}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=gv(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:L.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:i,...D_(r)})}};function vv(e,t){let n=f_(e),r=f_(t);if(e===t)return{valid:!0,data:e};if(n===M.object&&r===M.object){let n=u_.objectKeys(t),r=u_.objectKeys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=vv(e[n],t[n]);if(!r.valid)return{valid:!1};i[n]=r.data}return{valid:!0,data:i}}else if(n===M.array&&r===M.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=vv(i,a);if(!o.valid)return{valid:!1};n.push(o.data)}return{valid:!0,data:n}}else if(n===M.date&&r===M.date&&+e==+t)return{valid:!0,data:e};else return{valid:!1}}var yv=class extends O_{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=(e,r)=>{if(x_(e)||x_(r))return F;let i=vv(e.value,r.value);return i.valid?((S_(e)||S_(r))&&t.dirty(),{status:t.value,value:i.data}):(P(n,{code:N.invalid_intersection_types}),F)};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}))}};yv.create=(e,t,n)=>new yv({left:e,right:t,typeName:L.ZodIntersection,...D_(n)});var bv=class e extends O_{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==M.array)return P(n,{code:N.invalid_type,expected:M.array,received:n.parsedType}),F;if(n.data.length<this._def.items.length)return P(n,{code:N.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),F;!this._def.rest&&n.data.length>this._def.items.length&&(P(n,{code:N.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 T_(n,e,n.path,t)):null}).filter(e=>!!e);return n.common.async?Promise.all(r).then(e=>v_.mergeArray(t,e)):v_.mergeArray(t,r)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};bv.create=(e,t)=>{if(!Array.isArray(e))throw Error(`You must pass an array of schemas to z.tuple([ ... ])`);return new bv({items:e,typeName:L.ZodTuple,rest:null,...D_(t)})};var xv=class e extends O_{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!==M.object)return P(n,{code:N.invalid_type,expected:M.object,received:n.parsedType}),F;let r=[],i=this._def.keyType,a=this._def.valueType;for(let e in n.data)r.push({key:i._parse(new T_(n,e,n.path,e)),value:a._parse(new T_(n,n.data[e],n.path,e)),alwaysSet:e in n.data});return n.common.async?v_.mergeObjectAsync(t,r):v_.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof O_?new e({keyType:t,valueType:n,typeName:L.ZodRecord,...D_(r)}):new e({keyType:$_.create(),valueType:t,typeName:L.ZodRecord,...D_(n)})}},Sv=class extends O_{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!==M.map)return P(n,{code:N.invalid_type,expected:M.map,received:n.parsedType}),F;let r=this._def.keyType,i=this._def.valueType,a=[...n.data.entries()].map(([e,t],a)=>({key:r._parse(new T_(n,e,n.path,[a,`key`])),value:i._parse(new T_(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 F;(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 F;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}}}};Sv.create=(e,t,n)=>new Sv({valueType:t,keyType:e,typeName:L.ZodMap,...D_(n)});var Cv=class e extends O_{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==M.set)return P(n,{code:N.invalid_type,expected:M.set,received:n.parsedType}),F;let r=this._def;r.minSize!==null&&n.data.size<r.minSize.value&&(P(n,{code:N.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&&(P(n,{code:N.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 F;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 T_(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:I.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:I.toString(n)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};Cv.create=(e,t)=>new Cv({valueType:e,minSize:null,maxSize:null,typeName:L.ZodSet,...D_(t)});var wv=class e extends O_{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==M.function)return P(t,{code:N.invalid_type,expected:M.function,received:t.parsedType}),F;function n(e,n){return __({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,g_(),m_].filter(e=>!!e),issueData:{code:N.invalid_arguments,argumentsError:n}})}function r(e,n){return __({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,g_(),m_].filter(e=>!!e),issueData:{code:N.invalid_return_type,returnTypeError:n}})}let i={errorMap:t.common.contextualErrorMap},a=t.data;if(this._def.returns instanceof Av){let e=this;return b_(async function(...t){let o=new p_([]),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 b_(function(...t){let o=e._def.args.safeParse(t,i);if(!o.success)throw new p_([n(t,o.error)]);let s=Reflect.apply(a,this,o.data),c=e._def.returns.safeParse(s,i);if(!c.success)throw new p_([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:bv.create(t).rest(lv.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||bv.create([]).rest(lv.create()),returns:n||lv.create(),typeName:L.ZodFunction,...D_(r)})}},Tv=class extends O_{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})}};Tv.create=(e,t)=>new Tv({getter:e,typeName:L.ZodLazy,...D_(t)});var Ev=class extends O_{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return P(t,{received:t.data,code:N.invalid_literal,expected:this._def.value}),F}return{status:`valid`,value:e.data}}get value(){return this._def.value}};Ev.create=(e,t)=>new Ev({value:e,typeName:L.ZodLiteral,...D_(t)});function Dv(e,t){return new Ov({values:e,typeName:L.ZodEnum,...D_(t)})}var Ov=class e extends O_{_parse(e){if(typeof e.data!=`string`){let t=this._getOrReturnCtx(e),n=this._def.values;return P(t,{expected:u_.joinValues(n),received:t.parsedType,code:N.invalid_type}),F}if(this._cache||=new Set(this._def.values),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return P(t,{received:t.data,code:N.invalid_enum_value,options:n}),F}return b_(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})}};Ov.create=Dv;var kv=class extends O_{_parse(e){let t=u_.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==M.string&&n.parsedType!==M.number){let e=u_.objectValues(t);return P(n,{expected:u_.joinValues(e),received:n.parsedType,code:N.invalid_type}),F}if(this._cache||=new Set(u_.getValidEnumValues(this._def.values)),!this._cache.has(e.data)){let e=u_.objectValues(t);return P(n,{received:n.data,code:N.invalid_enum_value,options:e}),F}return b_(e.data)}get enum(){return this._def.values}};kv.create=(e,t)=>new kv({values:e,typeName:L.ZodNativeEnum,...D_(t)});var Av=class extends O_{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);return t.parsedType!==M.promise&&t.common.async===!1?(P(t,{code:N.invalid_type,expected:M.promise,received:t.parsedType}),F):b_((t.parsedType===M.promise?t.data:Promise.resolve(t.data)).then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}};Av.create=(e,t)=>new Av({type:e,typeName:L.ZodPromise,...D_(t)});var jv=class extends O_{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===L.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=>{P(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 F;let r=await this._def.schema._parseAsync({data:e,path:n.path,parent:n});return r.status===`aborted`?F:r.status===`dirty`||t.value===`dirty`?y_(r.value):r});{if(t.value===`aborted`)return F;let r=this._def.schema._parseSync({data:e,path:n.path,parent:n});return r.status===`aborted`?F:r.status===`dirty`||t.value===`dirty`?y_(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`?F:(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`?F:(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(!C_(e))return F;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=>C_(e)?Promise.resolve(r.transform(e.value,i)).then(e=>({status:t.value,value:e})):F);u_.assertNever(r)}};jv.create=(e,t,n)=>new jv({schema:e,typeName:L.ZodEffects,effect:t,...D_(n)}),jv.createWithPreprocess=(e,t,n)=>new jv({schema:t,effect:{type:`preprocess`,transform:e},typeName:L.ZodEffects,...D_(n)});var Mv=class extends O_{_parse(e){return this._getType(e)===M.undefined?b_(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Mv.create=(e,t)=>new Mv({innerType:e,typeName:L.ZodOptional,...D_(t)});var Nv=class extends O_{_parse(e){return this._getType(e)===M.null?b_(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Nv.create=(e,t)=>new Nv({innerType:e,typeName:L.ZodNullable,...D_(t)});var Pv=class extends O_{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===M.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};Pv.create=(e,t)=>new Pv({innerType:e,typeName:L.ZodDefault,defaultValue:typeof t.default==`function`?t.default:()=>t.default,...D_(t)});var Fv=class extends O_{_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 w_(r)?r.then(e=>({status:`valid`,value:e.status===`valid`?e.value:this._def.catchValue({get error(){return new p_(n.common.issues)},input:n.data})})):{status:`valid`,value:r.status===`valid`?r.value:this._def.catchValue({get error(){return new p_(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Fv.create=(e,t)=>new Fv({innerType:e,typeName:L.ZodCatch,catchValue:typeof t.catch==`function`?t.catch:()=>t.catch,...D_(t)});var Iv=class extends O_{_parse(e){if(this._getType(e)!==M.nan){let t=this._getOrReturnCtx(e);return P(t,{code:N.invalid_type,expected:M.nan,received:t.parsedType}),F}return{status:`valid`,value:e.data}}};Iv.create=e=>new Iv({typeName:L.ZodNaN,...D_(e)});var Lv=class extends O_{_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}},Rv=class e extends O_{_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`?F:e.status===`dirty`?(t.dirty(),y_(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`?F: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:L.ZodPipeline})}},zv=class extends O_{_parse(e){let t=this._def.innerType._parse(e),n=e=>(C_(e)&&(e.value=Object.freeze(e.value)),e);return w_(t)?t.then(e=>n(e)):n(t)}unwrap(){return this._def.innerType}};zv.create=(e,t)=>new zv({innerType:e,typeName:L.ZodReadonly,...D_(t)}),mv.lazycreate;var L;(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`})(L||={});var Bv=$_.create;tv.create,Iv.create,nv.create,rv.create,iv.create,av.create,ov.create,sv.create;var Vv=cv.create;lv.create,uv.create,dv.create,fv.create;var Hv=mv.create;mv.strictCreate,hv.create,_v.create,yv.create,bv.create,xv.create,Sv.create,Cv.create,wv.create,Tv.create,Ev.create,Ov.create,kv.create,Av.create,jv.create,Mv.create,Nv.create,jv.createWithPreprocess,Rv.create;function Uv(e,t){let n={type:`array`};return e.type?._def&&e.type?._def?.typeName!==L.ZodAny&&(n.items=Ny(e.type._def,{...t,currentPath:[...t.currentPath,`items`]})),e.minLength&&l_(n,`minItems`,e.minLength.value,e.minLength.message,t),e.maxLength&&l_(n,`maxItems`,e.maxLength.value,e.maxLength.message,t),e.exactLength&&(l_(n,`minItems`,e.exactLength.value,e.exactLength.message,t),l_(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?l_(n,`minimum`,r.value,r.message,t):l_(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),l_(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?l_(n,`maximum`,r.value,r.message,t):l_(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),l_(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:l_(n,`multipleOf`,r.value,r.message,t);break}return n}function Gv(){return{type:`boolean`}}function Kv(e,t){return Ny(e.type._def,t)}var qv=(e,t)=>Ny(e.innerType._def,t);function Jv(e,t,n){let r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map(n=>Jv(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 Yv(e,t)}}var Yv=(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`:l_(n,`minimum`,r.value,r.message,t);break;case`max`:l_(n,`maximum`,r.value,r.message,t);break}return n};function Xv(e,t){return{...Ny(e.innerType._def,t),default:e.defaultValue()}}function Zv(e,t){return t.effectStrategy===`input`?Ny(e.schema._def,t):s_(t)}function Qv(e){return{type:`string`,enum:Array.from(e.values)}}var $v=e=>`type`in e&&e.type===`string`?!1:`allOf`in e;function ey(e,t){let n=[Ny(e.left._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]}),Ny(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($v(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 ty(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 ny=void 0,ry={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:()=>(ny===void 0&&(ny=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)),ny),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 iy(e,t){let n={type:`string`};if(e.checks)for(let r of e.checks)switch(r.kind){case`min`:l_(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t);break;case`max`:l_(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`:cy(n,`email`,r.message,t);break;case`format:idn-email`:cy(n,`idn-email`,r.message,t);break;case`pattern:zod`:ly(n,ry.email,r.message,t);break}break;case`url`:cy(n,`uri`,r.message,t);break;case`uuid`:cy(n,`uuid`,r.message,t);break;case`regex`:ly(n,r.regex,r.message,t);break;case`cuid`:ly(n,ry.cuid,r.message,t);break;case`cuid2`:ly(n,ry.cuid2,r.message,t);break;case`startsWith`:ly(n,RegExp(`^${ay(r.value,t)}`),r.message,t);break;case`endsWith`:ly(n,RegExp(`${ay(r.value,t)}$`),r.message,t);break;case`datetime`:cy(n,`date-time`,r.message,t);break;case`date`:cy(n,`date`,r.message,t);break;case`time`:cy(n,`time`,r.message,t);break;case`duration`:cy(n,`duration`,r.message,t);break;case`length`:l_(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t),l_(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case`includes`:ly(n,RegExp(ay(r.value,t)),r.message,t);break;case`ip`:r.version!==`v6`&&cy(n,`ipv4`,r.message,t),r.version!==`v4`&&cy(n,`ipv6`,r.message,t);break;case`base64url`:ly(n,ry.base64url,r.message,t);break;case`jwt`:ly(n,ry.jwt,r.message,t);break;case`cidr`:r.version!==`v6`&&ly(n,ry.ipv4Cidr,r.message,t),r.version!==`v4`&&ly(n,ry.ipv6Cidr,r.message,t);break;case`emoji`:ly(n,ry.emoji(),r.message,t);break;case`ulid`:ly(n,ry.ulid,r.message,t);break;case`base64`:switch(t.base64Strategy){case`format:binary`:cy(n,`binary`,r.message,t);break;case`contentEncoding:base64`:l_(n,`contentEncoding`,`base64`,r.message,t);break;case`pattern:zod`:ly(n,ry.base64,r.message,t);break}break;case`nanoid`:ly(n,ry.nanoid,r.message,t);break;case`toLowerCase`:case`toUpperCase`:case`trim`:break;default:(e=>{})(r)}return n}function ay(e,t){return t.patternStrategy===`escape`?sy(e):e}var oy=new Set(`ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789`);function sy(e){let t=``;for(let n=0;n<e.length;n++)oy.has(e[n])||(t+=`\\`),t+=e[n];return t}function cy(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}}})):l_(e,`format`,t,n,r)}function ly(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:uy(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):l_(e,`pattern`,uy(t,r),n,r)}function uy(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
93
+ `));return await o.blob()}var n_=Symbol(`Let zodToJsonSchema decide on which parser to use`),r_={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`},i_=e=>typeof e==`string`?{...r_,name:e}:{...r_,...e},a_=e=>{let t=i_(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}]))}},o_=(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 s_(e){if(e.target!==`openAi`)return{};let t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy===`relative`?o_(t,e.currentPath):t.join(`/`)}}function c_(e,t,n,r){r?.errorMessages&&n&&(e.errorMessage={...e.errorMessage,[t]:n})}function l_(e,t,n,r,i){e[t]=n,c_(e,t,r,i)}var u_;(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})(u_||={});var d_;(function(e){e.mergeShapes=(e,t)=>({...e,...t})})(d_||={});var M=u_.arrayToEnum([`string`,`nan`,`number`,`integer`,`float`,`boolean`,`date`,`bigint`,`symbol`,`function`,`undefined`,`null`,`array`,`object`,`unknown`,`promise`,`void`,`never`,`map`,`set`]),f_=e=>{switch(typeof e){case`undefined`:return M.undefined;case`string`:return M.string;case`number`:return Number.isNaN(e)?M.nan:M.number;case`boolean`:return M.boolean;case`function`:return M.function;case`bigint`:return M.bigint;case`symbol`:return M.symbol;case`object`:return Array.isArray(e)?M.array:e===null?M.null:e.then&&typeof e.then==`function`&&e.catch&&typeof e.catch==`function`?M.promise:typeof Map<`u`&&e instanceof Map?M.map:typeof Set<`u`&&e instanceof Set?M.set:typeof Date<`u`&&e instanceof Date?M.date:M.object;default:return M.unknown}},N=u_.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`]),p_=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,u_.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=e=>e.message){let t=Object.create(null),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()}};p_.create=e=>new p_(e);var m_=(e,t)=>{let n;switch(e.code){case N.invalid_type:n=e.received===M.undefined?`Required`:`Expected ${e.expected}, received ${e.received}`;break;case N.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,u_.jsonStringifyReplacer)}`;break;case N.unrecognized_keys:n=`Unrecognized key(s) in object: ${u_.joinValues(e.keys,`, `)}`;break;case N.invalid_union:n=`Invalid input`;break;case N.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${u_.joinValues(e.options)}`;break;case N.invalid_enum_value:n=`Invalid enum value. Expected ${u_.joinValues(e.options)}, received '${e.received}'`;break;case N.invalid_arguments:n=`Invalid function arguments`;break;case N.invalid_return_type:n=`Invalid function return type`;break;case N.invalid_date:n=`Invalid date`;break;case N.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}"`:u_.assertNever(e.validation):n=e.validation===`regex`?`Invalid`:`Invalid ${e.validation}`;break;case N.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 N.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 N.custom:n=`Invalid input`;break;case N.invalid_intersection_types:n=`Intersection results could not be merged`;break;case N.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case N.not_finite:n=`Number must be finite`;break;default:n=t.defaultError,u_.assertNever(e)}return{message:n}},h_=m_;function g_(){return h_}var __=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 P(e,t){let n=g_(),r=__({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===m_?void 0:m_].filter(e=>!!e)});e.common.issues.push(r)}var v_=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 F;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 F;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}}},F=Object.freeze({status:`aborted`}),y_=e=>({status:`dirty`,value:e}),b_=e=>({status:`valid`,value:e}),x_=e=>e.status===`aborted`,S_=e=>e.status===`dirty`,C_=e=>e.status===`valid`,w_=e=>typeof Promise<`u`&&e instanceof Promise,I;(function(e){e.errToObj=e=>typeof e==`string`?{message:e}:e||{},e.toString=e=>typeof e==`string`?e:e?.message})(I||={});var T_=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}},E_=(e,t)=>{if(C_(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 p_(e.common.issues);return this._error=t,this._error}}};function L(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 D_=class{get description(){return this._def.description}_getType(e){return f_(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:f_(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new v_,ctx:{common:e.parent.common,data:e.data,parsedType:f_(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(w_(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:f_(e)};return E_(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:f_(e)};if(!this[`~standard`].async)try{let n=this._parseSync({data:e,path:[],parent:t});return C_(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=>C_(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:f_(e)},r=this._parse({data:e,path:n.path,parent:n});return E_(n,await(w_(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:N.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 Av({schema:this,typeName:R.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 jv.create(this,this._def)}nullable(){return Mv.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return dv.create(this)}promise(){return kv.create(this,this._def)}or(e){return mv.create([this,e],this._def)}and(e){return vv.create(this,e,this._def)}transform(e){return new Av({...L(this._def),schema:this,typeName:R.ZodEffects,effect:{type:`transform`,transform:e}})}default(e){let t=typeof e==`function`?e:()=>e;return new Nv({...L(this._def),innerType:this,defaultValue:t,typeName:R.ZodDefault})}brand(){return new Iv({typeName:R.ZodBranded,type:this,...L(this._def)})}catch(e){let t=typeof e==`function`?e:()=>e;return new Pv({...L(this._def),innerType:this,catchValue:t,typeName:R.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return Lv.create(this,e)}readonly(){return Rv.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},O_=/^c[^\s-]{8,}$/i,k_=/^[0-9a-z]+$/,A_=/^[0-9A-HJKMNP-TV-Z]{26}$/i,j_=/^[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,M_=/^[a-z0-9_-]{21}$/i,N_=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,P_=/^[-+]?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)?)??$/,F_=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,I_=`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,L_,R_=/^(?:(?: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])$/,z_=/^(?:(?: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])$/,B_=/^(([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]))$/,V_=/^(([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])$/,H_=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,U_=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,W_=`((\\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])))`,G_=RegExp(`^${W_}$`);function K_(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 q_(e){return RegExp(`^${K_(e)}$`)}function J_(e){let t=`${W_}T${K_(e)}`,n=[];return n.push(e.local?`Z?`:`Z`),e.offset&&n.push(`([+-]\\d{2}:?\\d{2})`),t=`${t}(${n.join(`|`)})`,RegExp(`^${t}$`)}function Y_(e,t){return!!((t===`v4`||!t)&&R_.test(e)||(t===`v6`||!t)&&B_.test(e))}function X_(e,t){if(!N_.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 Z_(e,t){return!!((t===`v4`||!t)&&z_.test(e)||(t===`v6`||!t)&&V_.test(e))}var Q_=class e extends D_{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==M.string){let t=this._getOrReturnCtx(e);return P(t,{code:N.invalid_type,expected:M.string,received:t.parsedType}),F}let t=new v_,n;for(let r of this._def.checks)if(r.kind===`min`)e.data.length<r.value&&(n=this._getOrReturnCtx(e,n),P(n,{code:N.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),P(n,{code:N.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?P(n,{code:N.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}):a&&P(n,{code:N.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}),t.dirty())}else if(r.kind===`email`)F_.test(e.data)||(n=this._getOrReturnCtx(e,n),P(n,{validation:`email`,code:N.invalid_string,message:r.message}),t.dirty());else if(r.kind===`emoji`)L_||=new RegExp(I_,`u`),L_.test(e.data)||(n=this._getOrReturnCtx(e,n),P(n,{validation:`emoji`,code:N.invalid_string,message:r.message}),t.dirty());else if(r.kind===`uuid`)j_.test(e.data)||(n=this._getOrReturnCtx(e,n),P(n,{validation:`uuid`,code:N.invalid_string,message:r.message}),t.dirty());else if(r.kind===`nanoid`)M_.test(e.data)||(n=this._getOrReturnCtx(e,n),P(n,{validation:`nanoid`,code:N.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid`)O_.test(e.data)||(n=this._getOrReturnCtx(e,n),P(n,{validation:`cuid`,code:N.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid2`)k_.test(e.data)||(n=this._getOrReturnCtx(e,n),P(n,{validation:`cuid2`,code:N.invalid_string,message:r.message}),t.dirty());else if(r.kind===`ulid`)A_.test(e.data)||(n=this._getOrReturnCtx(e,n),P(n,{validation:`ulid`,code:N.invalid_string,message:r.message}),t.dirty());else if(r.kind===`url`)try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),P(n,{validation:`url`,code:N.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),P(n,{validation:`regex`,code:N.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),P(n,{code:N.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),P(n,{code:N.invalid_string,validation:{startsWith:r.value},message:r.message}),t.dirty()):r.kind===`endsWith`?e.data.endsWith(r.value)||(n=this._getOrReturnCtx(e,n),P(n,{code:N.invalid_string,validation:{endsWith:r.value},message:r.message}),t.dirty()):r.kind===`datetime`?J_(r).test(e.data)||(n=this._getOrReturnCtx(e,n),P(n,{code:N.invalid_string,validation:`datetime`,message:r.message}),t.dirty()):r.kind===`date`?G_.test(e.data)||(n=this._getOrReturnCtx(e,n),P(n,{code:N.invalid_string,validation:`date`,message:r.message}),t.dirty()):r.kind===`time`?q_(r).test(e.data)||(n=this._getOrReturnCtx(e,n),P(n,{code:N.invalid_string,validation:`time`,message:r.message}),t.dirty()):r.kind===`duration`?P_.test(e.data)||(n=this._getOrReturnCtx(e,n),P(n,{validation:`duration`,code:N.invalid_string,message:r.message}),t.dirty()):r.kind===`ip`?Y_(e.data,r.version)||(n=this._getOrReturnCtx(e,n),P(n,{validation:`ip`,code:N.invalid_string,message:r.message}),t.dirty()):r.kind===`jwt`?X_(e.data,r.alg)||(n=this._getOrReturnCtx(e,n),P(n,{validation:`jwt`,code:N.invalid_string,message:r.message}),t.dirty()):r.kind===`cidr`?Z_(e.data,r.version)||(n=this._getOrReturnCtx(e,n),P(n,{validation:`cidr`,code:N.invalid_string,message:r.message}),t.dirty()):r.kind===`base64`?H_.test(e.data)||(n=this._getOrReturnCtx(e,n),P(n,{validation:`base64`,code:N.invalid_string,message:r.message}),t.dirty()):r.kind===`base64url`?U_.test(e.data)||(n=this._getOrReturnCtx(e,n),P(n,{validation:`base64url`,code:N.invalid_string,message:r.message}),t.dirty()):u_.assertNever(r);return{status:t.value,value:e.data}}_regex(e,t,n){return this.refinement(t=>e.test(t),{validation:t,code:N.invalid_string,...I.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(e){return this._addCheck({kind:`email`,...I.errToObj(e)})}url(e){return this._addCheck({kind:`url`,...I.errToObj(e)})}emoji(e){return this._addCheck({kind:`emoji`,...I.errToObj(e)})}uuid(e){return this._addCheck({kind:`uuid`,...I.errToObj(e)})}nanoid(e){return this._addCheck({kind:`nanoid`,...I.errToObj(e)})}cuid(e){return this._addCheck({kind:`cuid`,...I.errToObj(e)})}cuid2(e){return this._addCheck({kind:`cuid2`,...I.errToObj(e)})}ulid(e){return this._addCheck({kind:`ulid`,...I.errToObj(e)})}base64(e){return this._addCheck({kind:`base64`,...I.errToObj(e)})}base64url(e){return this._addCheck({kind:`base64url`,...I.errToObj(e)})}jwt(e){return this._addCheck({kind:`jwt`,...I.errToObj(e)})}ip(e){return this._addCheck({kind:`ip`,...I.errToObj(e)})}cidr(e){return this._addCheck({kind:`cidr`,...I.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,...I.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,...I.errToObj(e?.message)})}duration(e){return this._addCheck({kind:`duration`,...I.errToObj(e)})}regex(e,t){return this._addCheck({kind:`regex`,regex:e,...I.errToObj(t)})}includes(e,t){return this._addCheck({kind:`includes`,value:e,position:t?.position,...I.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:`startsWith`,value:e,...I.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:`endsWith`,value:e,...I.errToObj(t)})}min(e,t){return this._addCheck({kind:`min`,value:e,...I.errToObj(t)})}max(e,t){return this._addCheck({kind:`max`,value:e,...I.errToObj(t)})}length(e,t){return this._addCheck({kind:`length`,value:e,...I.errToObj(t)})}nonempty(e){return this.min(1,I.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}};Q_.create=e=>new Q_({checks:[],typeName:R.ZodString,coerce:e?.coerce??!1,...L(e)});function $_(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 ev=class e extends D_{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)!==M.number){let t=this._getOrReturnCtx(e);return P(t,{code:N.invalid_type,expected:M.number,received:t.parsedType}),F}let t,n=new v_;for(let r of this._def.checks)r.kind===`int`?u_.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),P(t,{code:N.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),P(t,{code:N.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),P(t,{code:N.too_big,maximum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`multipleOf`?$_(e.data,r.value)!==0&&(t=this._getOrReturnCtx(e,t),P(t,{code:N.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):r.kind===`finite`?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),P(t,{code:N.not_finite,message:r.message}),n.dirty()):u_.assertNever(r);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit(`min`,e,!0,I.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,I.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,I.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,I.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:I.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(e){return this._addCheck({kind:`int`,message:I.toString(e)})}positive(e){return this._addCheck({kind:`min`,value:0,inclusive:!1,message:I.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:0,inclusive:!1,message:I.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:0,inclusive:!0,message:I.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:0,inclusive:!0,message:I.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:I.toString(t)})}finite(e){return this._addCheck({kind:`finite`,message:I.toString(e)})}safe(e){return this._addCheck({kind:`min`,inclusive:!0,value:-(2**53-1),message:I.toString(e)})._addCheck({kind:`max`,inclusive:!0,value:2**53-1,message:I.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`&&u_.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)}};ev.create=e=>new ev({checks:[],typeName:R.ZodNumber,coerce:e?.coerce||!1,...L(e)});var tv=class e extends D_{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)!==M.bigint)return this._getInvalidInput(e);let t,n=new v_;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),P(t,{code:N.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),P(t,{code:N.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),P(t,{code:N.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):u_.assertNever(r);return{status:n.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return P(t,{code:N.invalid_type,expected:M.bigint,received:t.parsedType}),F}gte(e,t){return this.setLimit(`min`,e,!0,I.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,I.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,I.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,I.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:I.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:I.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!1,message:I.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!0,message:I.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!0,message:I.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:I.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}};tv.create=e=>new tv({checks:[],typeName:R.ZodBigInt,coerce:e?.coerce??!1,...L(e)});var nv=class extends D_{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==M.boolean){let t=this._getOrReturnCtx(e);return P(t,{code:N.invalid_type,expected:M.boolean,received:t.parsedType}),F}return b_(e.data)}};nv.create=e=>new nv({typeName:R.ZodBoolean,coerce:e?.coerce||!1,...L(e)});var rv=class e extends D_{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==M.date){let t=this._getOrReturnCtx(e);return P(t,{code:N.invalid_type,expected:M.date,received:t.parsedType}),F}if(Number.isNaN(e.data.getTime()))return P(this._getOrReturnCtx(e),{code:N.invalid_date}),F;let t=new v_,n;for(let r of this._def.checks)r.kind===`min`?e.data.getTime()<r.value&&(n=this._getOrReturnCtx(e,n),P(n,{code:N.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),P(n,{code:N.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:`date`}),t.dirty()):u_.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:I.toString(t)})}max(e,t){return this._addCheck({kind:`max`,value:e.getTime(),message:I.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)}};rv.create=e=>new rv({checks:[],coerce:e?.coerce||!1,typeName:R.ZodDate,...L(e)});var iv=class extends D_{_parse(e){if(this._getType(e)!==M.symbol){let t=this._getOrReturnCtx(e);return P(t,{code:N.invalid_type,expected:M.symbol,received:t.parsedType}),F}return b_(e.data)}};iv.create=e=>new iv({typeName:R.ZodSymbol,...L(e)});var av=class extends D_{_parse(e){if(this._getType(e)!==M.undefined){let t=this._getOrReturnCtx(e);return P(t,{code:N.invalid_type,expected:M.undefined,received:t.parsedType}),F}return b_(e.data)}};av.create=e=>new av({typeName:R.ZodUndefined,...L(e)});var ov=class extends D_{_parse(e){if(this._getType(e)!==M.null){let t=this._getOrReturnCtx(e);return P(t,{code:N.invalid_type,expected:M.null,received:t.parsedType}),F}return b_(e.data)}};ov.create=e=>new ov({typeName:R.ZodNull,...L(e)});var sv=class extends D_{constructor(){super(...arguments),this._any=!0}_parse(e){return b_(e.data)}};sv.create=e=>new sv({typeName:R.ZodAny,...L(e)});var cv=class extends D_{constructor(){super(...arguments),this._unknown=!0}_parse(e){return b_(e.data)}};cv.create=e=>new cv({typeName:R.ZodUnknown,...L(e)});var lv=class extends D_{_parse(e){let t=this._getOrReturnCtx(e);return P(t,{code:N.invalid_type,expected:M.never,received:t.parsedType}),F}};lv.create=e=>new lv({typeName:R.ZodNever,...L(e)});var uv=class extends D_{_parse(e){if(this._getType(e)!==M.undefined){let t=this._getOrReturnCtx(e);return P(t,{code:N.invalid_type,expected:M.void,received:t.parsedType}),F}return b_(e.data)}};uv.create=e=>new uv({typeName:R.ZodVoid,...L(e)});var dv=class e extends D_{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),r=this._def;if(t.parsedType!==M.array)return P(t,{code:N.invalid_type,expected:M.array,received:t.parsedType}),F;if(r.exactLength!==null){let e=t.data.length>r.exactLength.value,i=t.data.length<r.exactLength.value;(e||i)&&(P(t,{code:e?N.too_big:N.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&&(P(t,{code:N.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&&(P(t,{code:N.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 T_(t,e,t.path,n)))).then(e=>v_.mergeArray(n,e));let i=[...t.data].map((e,n)=>r.type._parseSync(new T_(t,e,t.path,n)));return v_.mergeArray(n,i)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:I.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:I.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:I.toString(n)}})}nonempty(e){return this.min(1,e)}};dv.create=(e,t)=>new dv({type:e,minLength:null,maxLength:null,exactLength:null,typeName:R.ZodArray,...L(t)});function fv(e){if(e instanceof pv){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=jv.create(fv(r))}return new pv({...e._def,shape:()=>t})}else if(e instanceof dv)return new dv({...e._def,type:fv(e.element)});else if(e instanceof jv)return jv.create(fv(e.unwrap()));else if(e instanceof Mv)return Mv.create(fv(e.unwrap()));else if(e instanceof yv)return yv.create(e.items.map(e=>fv(e)));else return e}var pv=class e extends D_{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=u_.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==M.object){let t=this._getOrReturnCtx(e);return P(t,{code:N.invalid_type,expected:M.object,received:t.parsedType}),F}let{status:t,ctx:n}=this._processInputParams(e),{shape:r,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof lv&&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 T_(n,i,n.path,e)),alwaysSet:e in n.data})}if(this._def.catchall instanceof lv){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&&(P(n,{code:N.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 T_(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=>v_.mergeObjectSync(t,e)):v_.mergeObjectSync(t,o)}get shape(){return this._def.shape()}strict(t){return I.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:I.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:R.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 u_.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 u_.objectKeys(this.shape))t[e]||(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}deepPartial(){return fv(this)}partial(t){let n={};for(let e of u_.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 u_.objectKeys(this.shape))if(t&&!t[e])n[e]=this.shape[e];else{let t=this.shape[e];for(;t instanceof jv;)t=t._def.innerType;n[e]=t}return new e({...this._def,shape:()=>n})}keyof(){return Ev(u_.objectKeys(this.shape))}};pv.create=(e,t)=>new pv({shape:()=>e,unknownKeys:`strip`,catchall:lv.create(),typeName:R.ZodObject,...L(t)}),pv.strictCreate=(e,t)=>new pv({shape:()=>e,unknownKeys:`strict`,catchall:lv.create(),typeName:R.ZodObject,...L(t)}),pv.lazycreate=(e,t)=>new pv({shape:e,unknownKeys:`strip`,catchall:lv.create(),typeName:R.ZodObject,...L(t)});var mv=class extends D_{_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 p_(e.ctx.common.issues));return P(t,{code:N.invalid_union,unionErrors:n}),F}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 p_(e));return P(t,{code:N.invalid_union,unionErrors:i}),F}}get options(){return this._def.options}};mv.create=(e,t)=>new mv({options:e,typeName:R.ZodUnion,...L(t)});var hv=e=>e instanceof wv?hv(e.schema):e instanceof Av?hv(e.innerType()):e instanceof Tv?[e.value]:e instanceof Dv?e.options:e instanceof Ov?u_.objectValues(e.enum):e instanceof Nv?hv(e._def.innerType):e instanceof av?[void 0]:e instanceof ov?[null]:e instanceof jv?[void 0,...hv(e.unwrap())]:e instanceof Mv?[null,...hv(e.unwrap())]:e instanceof Iv||e instanceof Rv?hv(e.unwrap()):e instanceof Pv?hv(e._def.innerType):[],gv=class e extends D_{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==M.object)return P(t,{code:N.invalid_type,expected:M.object,received:t.parsedType}),F;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}):(P(t,{code:N.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),F)}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=hv(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:R.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:i,...L(r)})}};function _v(e,t){let n=f_(e),r=f_(t);if(e===t)return{valid:!0,data:e};if(n===M.object&&r===M.object){let n=u_.objectKeys(t),r=u_.objectKeys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=_v(e[n],t[n]);if(!r.valid)return{valid:!1};i[n]=r.data}return{valid:!0,data:i}}else if(n===M.array&&r===M.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=_v(i,a);if(!o.valid)return{valid:!1};n.push(o.data)}return{valid:!0,data:n}}else if(n===M.date&&r===M.date&&+e==+t)return{valid:!0,data:e};else return{valid:!1}}var vv=class extends D_{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=(e,r)=>{if(x_(e)||x_(r))return F;let i=_v(e.value,r.value);return i.valid?((S_(e)||S_(r))&&t.dirty(),{status:t.value,value:i.data}):(P(n,{code:N.invalid_intersection_types}),F)};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}))}};vv.create=(e,t,n)=>new vv({left:e,right:t,typeName:R.ZodIntersection,...L(n)});var yv=class e extends D_{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==M.array)return P(n,{code:N.invalid_type,expected:M.array,received:n.parsedType}),F;if(n.data.length<this._def.items.length)return P(n,{code:N.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),F;!this._def.rest&&n.data.length>this._def.items.length&&(P(n,{code:N.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 T_(n,e,n.path,t)):null}).filter(e=>!!e);return n.common.async?Promise.all(r).then(e=>v_.mergeArray(t,e)):v_.mergeArray(t,r)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};yv.create=(e,t)=>{if(!Array.isArray(e))throw Error(`You must pass an array of schemas to z.tuple([ ... ])`);return new yv({items:e,typeName:R.ZodTuple,rest:null,...L(t)})};var bv=class e extends D_{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!==M.object)return P(n,{code:N.invalid_type,expected:M.object,received:n.parsedType}),F;let r=[],i=this._def.keyType,a=this._def.valueType;for(let e in n.data)r.push({key:i._parse(new T_(n,e,n.path,e)),value:a._parse(new T_(n,n.data[e],n.path,e)),alwaysSet:e in n.data});return n.common.async?v_.mergeObjectAsync(t,r):v_.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof D_?new e({keyType:t,valueType:n,typeName:R.ZodRecord,...L(r)}):new e({keyType:Q_.create(),valueType:t,typeName:R.ZodRecord,...L(n)})}},xv=class extends D_{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!==M.map)return P(n,{code:N.invalid_type,expected:M.map,received:n.parsedType}),F;let r=this._def.keyType,i=this._def.valueType,a=[...n.data.entries()].map(([e,t],a)=>({key:r._parse(new T_(n,e,n.path,[a,`key`])),value:i._parse(new T_(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 F;(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 F;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}}}};xv.create=(e,t,n)=>new xv({valueType:t,keyType:e,typeName:R.ZodMap,...L(n)});var Sv=class e extends D_{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==M.set)return P(n,{code:N.invalid_type,expected:M.set,received:n.parsedType}),F;let r=this._def;r.minSize!==null&&n.data.size<r.minSize.value&&(P(n,{code:N.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&&(P(n,{code:N.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 F;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 T_(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:I.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:I.toString(n)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};Sv.create=(e,t)=>new Sv({valueType:e,minSize:null,maxSize:null,typeName:R.ZodSet,...L(t)});var Cv=class e extends D_{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==M.function)return P(t,{code:N.invalid_type,expected:M.function,received:t.parsedType}),F;function n(e,n){return __({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,g_(),m_].filter(e=>!!e),issueData:{code:N.invalid_arguments,argumentsError:n}})}function r(e,n){return __({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,g_(),m_].filter(e=>!!e),issueData:{code:N.invalid_return_type,returnTypeError:n}})}let i={errorMap:t.common.contextualErrorMap},a=t.data;if(this._def.returns instanceof kv){let e=this;return b_(async function(...t){let o=new p_([]),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 b_(function(...t){let o=e._def.args.safeParse(t,i);if(!o.success)throw new p_([n(t,o.error)]);let s=Reflect.apply(a,this,o.data),c=e._def.returns.safeParse(s,i);if(!c.success)throw new p_([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:yv.create(t).rest(cv.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||yv.create([]).rest(cv.create()),returns:n||cv.create(),typeName:R.ZodFunction,...L(r)})}},wv=class extends D_{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})}};wv.create=(e,t)=>new wv({getter:e,typeName:R.ZodLazy,...L(t)});var Tv=class extends D_{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return P(t,{received:t.data,code:N.invalid_literal,expected:this._def.value}),F}return{status:`valid`,value:e.data}}get value(){return this._def.value}};Tv.create=(e,t)=>new Tv({value:e,typeName:R.ZodLiteral,...L(t)});function Ev(e,t){return new Dv({values:e,typeName:R.ZodEnum,...L(t)})}var Dv=class e extends D_{_parse(e){if(typeof e.data!=`string`){let t=this._getOrReturnCtx(e),n=this._def.values;return P(t,{expected:u_.joinValues(n),received:t.parsedType,code:N.invalid_type}),F}if(this._cache||=new Set(this._def.values),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return P(t,{received:t.data,code:N.invalid_enum_value,options:n}),F}return b_(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})}};Dv.create=Ev;var Ov=class extends D_{_parse(e){let t=u_.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==M.string&&n.parsedType!==M.number){let e=u_.objectValues(t);return P(n,{expected:u_.joinValues(e),received:n.parsedType,code:N.invalid_type}),F}if(this._cache||=new Set(u_.getValidEnumValues(this._def.values)),!this._cache.has(e.data)){let e=u_.objectValues(t);return P(n,{received:n.data,code:N.invalid_enum_value,options:e}),F}return b_(e.data)}get enum(){return this._def.values}};Ov.create=(e,t)=>new Ov({values:e,typeName:R.ZodNativeEnum,...L(t)});var kv=class extends D_{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);return t.parsedType!==M.promise&&t.common.async===!1?(P(t,{code:N.invalid_type,expected:M.promise,received:t.parsedType}),F):b_((t.parsedType===M.promise?t.data:Promise.resolve(t.data)).then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}};kv.create=(e,t)=>new kv({type:e,typeName:R.ZodPromise,...L(t)});var Av=class extends D_{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===R.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=>{P(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 F;let r=await this._def.schema._parseAsync({data:e,path:n.path,parent:n});return r.status===`aborted`?F:r.status===`dirty`||t.value===`dirty`?y_(r.value):r});{if(t.value===`aborted`)return F;let r=this._def.schema._parseSync({data:e,path:n.path,parent:n});return r.status===`aborted`?F:r.status===`dirty`||t.value===`dirty`?y_(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`?F:(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`?F:(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(!C_(e))return F;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=>C_(e)?Promise.resolve(r.transform(e.value,i)).then(e=>({status:t.value,value:e})):F);u_.assertNever(r)}};Av.create=(e,t,n)=>new Av({schema:e,typeName:R.ZodEffects,effect:t,...L(n)}),Av.createWithPreprocess=(e,t,n)=>new Av({schema:t,effect:{type:`preprocess`,transform:e},typeName:R.ZodEffects,...L(n)});var jv=class extends D_{_parse(e){return this._getType(e)===M.undefined?b_(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};jv.create=(e,t)=>new jv({innerType:e,typeName:R.ZodOptional,...L(t)});var Mv=class extends D_{_parse(e){return this._getType(e)===M.null?b_(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Mv.create=(e,t)=>new Mv({innerType:e,typeName:R.ZodNullable,...L(t)});var Nv=class extends D_{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===M.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};Nv.create=(e,t)=>new Nv({innerType:e,typeName:R.ZodDefault,defaultValue:typeof t.default==`function`?t.default:()=>t.default,...L(t)});var Pv=class extends D_{_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 w_(r)?r.then(e=>({status:`valid`,value:e.status===`valid`?e.value:this._def.catchValue({get error(){return new p_(n.common.issues)},input:n.data})})):{status:`valid`,value:r.status===`valid`?r.value:this._def.catchValue({get error(){return new p_(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Pv.create=(e,t)=>new Pv({innerType:e,typeName:R.ZodCatch,catchValue:typeof t.catch==`function`?t.catch:()=>t.catch,...L(t)});var Fv=class extends D_{_parse(e){if(this._getType(e)!==M.nan){let t=this._getOrReturnCtx(e);return P(t,{code:N.invalid_type,expected:M.nan,received:t.parsedType}),F}return{status:`valid`,value:e.data}}};Fv.create=e=>new Fv({typeName:R.ZodNaN,...L(e)});var Iv=class extends D_{_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}},Lv=class e extends D_{_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`?F:e.status===`dirty`?(t.dirty(),y_(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`?F: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:R.ZodPipeline})}},Rv=class extends D_{_parse(e){let t=this._def.innerType._parse(e),n=e=>(C_(e)&&(e.value=Object.freeze(e.value)),e);return w_(t)?t.then(e=>n(e)):n(t)}unwrap(){return this._def.innerType}};Rv.create=(e,t)=>new Rv({innerType:e,typeName:R.ZodReadonly,...L(t)}),pv.lazycreate;var R;(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`})(R||={});var zv=Q_.create;ev.create,Fv.create,tv.create,nv.create,rv.create,iv.create,av.create,ov.create;var Bv=sv.create;cv.create,lv.create,uv.create,dv.create;var Vv=pv.create;pv.strictCreate,mv.create,gv.create,vv.create,yv.create,bv.create,xv.create,Sv.create,Cv.create,wv.create,Tv.create,Dv.create,Ov.create,kv.create,Av.create,jv.create,Mv.create,Av.createWithPreprocess,Lv.create;function Hv(e,t){let n={type:`array`};return e.type?._def&&e.type?._def?.typeName!==R.ZodAny&&(n.items=My(e.type._def,{...t,currentPath:[...t.currentPath,`items`]})),e.minLength&&l_(n,`minItems`,e.minLength.value,e.minLength.message,t),e.maxLength&&l_(n,`maxItems`,e.maxLength.value,e.maxLength.message,t),e.exactLength&&(l_(n,`minItems`,e.exactLength.value,e.exactLength.message,t),l_(n,`maxItems`,e.exactLength.value,e.exactLength.message,t)),n}function Uv(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?l_(n,`minimum`,r.value,r.message,t):l_(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),l_(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?l_(n,`maximum`,r.value,r.message,t):l_(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),l_(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:l_(n,`multipleOf`,r.value,r.message,t);break}return n}function Wv(){return{type:`boolean`}}function Gv(e,t){return My(e.type._def,t)}var Kv=(e,t)=>My(e.innerType._def,t);function qv(e,t,n){let r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map(n=>qv(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 Jv(e,t)}}var Jv=(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`:l_(n,`minimum`,r.value,r.message,t);break;case`max`:l_(n,`maximum`,r.value,r.message,t);break}return n};function Yv(e,t){return{...My(e.innerType._def,t),default:e.defaultValue()}}function Xv(e,t){return t.effectStrategy===`input`?My(e.schema._def,t):s_(t)}function Zv(e){return{type:`string`,enum:Array.from(e.values)}}var Qv=e=>`type`in e&&e.type===`string`?!1:`allOf`in e;function $v(e,t){let n=[My(e.left._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]}),My(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(Qv(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 ey(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 ty=void 0,ny={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:()=>(ty===void 0&&(ty=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)),ty),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 ry(e,t){let n={type:`string`};if(e.checks)for(let r of e.checks)switch(r.kind){case`min`:l_(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t);break;case`max`:l_(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`:sy(n,`email`,r.message,t);break;case`format:idn-email`:sy(n,`idn-email`,r.message,t);break;case`pattern:zod`:cy(n,ny.email,r.message,t);break}break;case`url`:sy(n,`uri`,r.message,t);break;case`uuid`:sy(n,`uuid`,r.message,t);break;case`regex`:cy(n,r.regex,r.message,t);break;case`cuid`:cy(n,ny.cuid,r.message,t);break;case`cuid2`:cy(n,ny.cuid2,r.message,t);break;case`startsWith`:cy(n,RegExp(`^${iy(r.value,t)}`),r.message,t);break;case`endsWith`:cy(n,RegExp(`${iy(r.value,t)}$`),r.message,t);break;case`datetime`:sy(n,`date-time`,r.message,t);break;case`date`:sy(n,`date`,r.message,t);break;case`time`:sy(n,`time`,r.message,t);break;case`duration`:sy(n,`duration`,r.message,t);break;case`length`:l_(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t),l_(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case`includes`:cy(n,RegExp(iy(r.value,t)),r.message,t);break;case`ip`:r.version!==`v6`&&sy(n,`ipv4`,r.message,t),r.version!==`v4`&&sy(n,`ipv6`,r.message,t);break;case`base64url`:cy(n,ny.base64url,r.message,t);break;case`jwt`:cy(n,ny.jwt,r.message,t);break;case`cidr`:r.version!==`v6`&&cy(n,ny.ipv4Cidr,r.message,t),r.version!==`v4`&&cy(n,ny.ipv6Cidr,r.message,t);break;case`emoji`:cy(n,ny.emoji(),r.message,t);break;case`ulid`:cy(n,ny.ulid,r.message,t);break;case`base64`:switch(t.base64Strategy){case`format:binary`:sy(n,`binary`,r.message,t);break;case`contentEncoding:base64`:l_(n,`contentEncoding`,`base64`,r.message,t);break;case`pattern:zod`:cy(n,ny.base64,r.message,t);break}break;case`nanoid`:cy(n,ny.nanoid,r.message,t);break;case`toLowerCase`:case`toUpperCase`:case`trim`:break;default:(e=>{})(r)}return n}function iy(e,t){return t.patternStrategy===`escape`?oy(e):e}var ay=new Set(`ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789`);function oy(e){let t=``;for(let n=0;n<e.length;n++)ay.has(e[n])||(t+=`\\`),t+=e[n];return t}function sy(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}}})):l_(e,`format`,t,n,r)}function cy(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:ly(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):l_(e,`pattern`,ly(t,r),n,r)}function ly(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
94
94
  ]))`;continue}else if(r[e]===`$`){i+=`($|(?=[\r
95
- ]))`;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 dy(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===L.ZodEnum)return{type:`object`,required:e.keyType._def.values,properties:e.keyType._def.values.reduce((n,r)=>({...n,[r]:Ny(e.valueType._def,{...t,currentPath:[...t.currentPath,`properties`,r]})??s_(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};let n={type:`object`,additionalProperties:Ny(e.valueType._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]})??t.allowedAdditionalProperties};if(t.target===`openApi3`)return n;if(e.keyType?._def.typeName===L.ZodString&&e.keyType._def.checks?.length){let{type:r,...i}=iy(e.keyType._def,t);return{...n,propertyNames:i}}else if(e.keyType?._def.typeName===L.ZodEnum)return{...n,propertyNames:{enum:e.keyType._def.values}};else if(e.keyType?._def.typeName===L.ZodBranded&&e.keyType._def.type._def.typeName===L.ZodString&&e.keyType._def.type._def.checks?.length){let{type:r,...i}=Kv(e.keyType._def,t);return{...n,propertyNames:i}}return n}function fy(e,t){return t.mapStrategy===`record`?dy(e,t):{type:`array`,maxItems:125,items:{type:`array`,items:[Ny(e.keyType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`0`]})||s_(t),Ny(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`1`]})||s_(t)],minItems:2,maxItems:2}}}function py(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 my(e){return e.target===`openAi`?void 0:{not:s_({...e,currentPath:[...e.currentPath,`not`]})}}function hy(e){return e.target===`openApi3`?{enum:[`null`],nullable:!0}:{type:`null`}}var gy={ZodString:`string`,ZodNumber:`number`,ZodBigInt:`integer`,ZodBoolean:`boolean`,ZodNull:`null`};function _y(e,t){if(t.target===`openApi3`)return vy(e,t);let n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(e=>e._def.typeName in gy&&(!e._def.checks||!e._def.checks.length))){let e=n.reduce((e,t)=>{let n=gy[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 vy(e,t)}var vy=(e,t)=>{let n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((e,n)=>Ny(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 yy(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:gy[e.innerType._def.typeName],nullable:!0}:{type:[gy[e.innerType._def.typeName],`null`]};if(t.target===`openApi3`){let n=Ny(e.innerType._def,{...t,currentPath:[...t.currentPath]});return n&&`$ref`in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let n=Ny(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`0`]});return n&&{anyOf:[n,{type:`null`}]}}function by(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`,c_(n,`type`,r.message,t);break;case`min`:t.target===`jsonSchema7`?r.inclusive?l_(n,`minimum`,r.value,r.message,t):l_(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),l_(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?l_(n,`maximum`,r.value,r.message,t):l_(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),l_(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:l_(n,`multipleOf`,r.value,r.message,t);break}return n}function xy(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=Cy(o);s&&n&&(o._def.typeName===`ZodOptional`&&(o=o._def.innerType),o.isNullable()||(o=o.nullable()),s=!1);let c=Ny(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=Sy(e,t);return o!==void 0&&(r.additionalProperties=o),r}function Sy(e,t){if(e.catchall._def.typeName!==`ZodNever`)return Ny(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 Cy(e){try{return e.isOptional()}catch{return!0}}var wy=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return Ny(e.innerType._def,t);let n=Ny(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`1`]});return n?{anyOf:[{not:s_(t)},n]}:s_(t)},Ty=(e,t)=>{if(t.pipeStrategy===`input`)return Ny(e.in._def,t);if(t.pipeStrategy===`output`)return Ny(e.out._def,t);let n=Ny(e.in._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]});return{allOf:[n,Ny(e.out._def,{...t,currentPath:[...t.currentPath,`allOf`,n?`1`:`0`]})].filter(e=>e!==void 0)}};function Ey(e,t){return Ny(e.type._def,t)}function Dy(e,t){let n={type:`array`,uniqueItems:!0,items:Ny(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`]})};return e.minSize&&l_(n,`minItems`,e.minSize.value,e.minSize.message,t),e.maxSize&&l_(n,`maxItems`,e.maxSize.value,e.maxSize.message,t),n}function Oy(e,t){return e.rest?{type:`array`,minItems:e.items.length,items:e.items.map((e,n)=>Ny(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[]),additionalItems:Ny(e.rest._def,{...t,currentPath:[...t.currentPath,`additionalItems`]})}:{type:`array`,minItems:e.items.length,maxItems:e.items.length,items:e.items.map((e,n)=>Ny(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[])}}function ky(e){return{not:s_(e)}}function Ay(e){return s_(e)}var jy=(e,t)=>Ny(e.innerType._def,t),My=(e,t,n)=>{switch(t){case L.ZodString:return iy(e,n);case L.ZodNumber:return by(e,n);case L.ZodObject:return xy(e,n);case L.ZodBigInt:return Wv(e,n);case L.ZodBoolean:return Gv();case L.ZodDate:return Jv(e,n);case L.ZodUndefined:return ky(n);case L.ZodNull:return hy(n);case L.ZodArray:return Uv(e,n);case L.ZodUnion:case L.ZodDiscriminatedUnion:return _y(e,n);case L.ZodIntersection:return ey(e,n);case L.ZodTuple:return Oy(e,n);case L.ZodRecord:return dy(e,n);case L.ZodLiteral:return ty(e,n);case L.ZodEnum:return Qv(e);case L.ZodNativeEnum:return py(e);case L.ZodNullable:return yy(e,n);case L.ZodOptional:return wy(e,n);case L.ZodMap:return fy(e,n);case L.ZodSet:return Dy(e,n);case L.ZodLazy:return()=>e.getter()._def;case L.ZodPromise:return Ey(e,n);case L.ZodNaN:case L.ZodNever:return my(n);case L.ZodEffects:return Zv(e,n);case L.ZodAny:return s_(n);case L.ZodUnknown:return Ay(n);case L.ZodDefault:return Xv(e,n);case L.ZodBranded:return Kv(e,n);case L.ZodReadonly:return jy(e,n);case L.ZodCatch:return qv(e,n);case L.ZodPipeline:return Ty(e,n);case L.ZodFunction:case L.ZodVoid:case L.ZodSymbol:return;default:return(e=>void 0)(t)}};function Ny(e,t,n=!1){let r=t.seen.get(e);if(t.override){let i=t.override?.(e,t,r,n);if(i!==n_)return i}if(r&&!n){let e=Py(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=My(e,e.typeName,t),o=typeof a==`function`?Ny(a(),t):a;if(o&&Fy(e,t,o),t.postProcess){let n=t.postProcess(o,e,t);return i.jsonSchema=o,n}return i.jsonSchema=o,o}var Py=(e,t)=>{switch(t.$refStrategy){case`root`:return{$ref:e.path.join(`/`)};case`relative`:return{$ref:o_(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`),s_(t)):t.$refStrategy===`seen`?s_(t):void 0}},Fy=(e,t,n)=>(e.description&&(n.description=e.description,t.markdownDescription&&(n.markdownDescription=e.description)),n),Iy=(e,t)=>{let n=a_(t),r=typeof t==`object`&&t.definitions?Object.entries(t.definitions).reduce((e,[t,r])=>({...e,[t]:Ny(r._def,{...n,currentPath:[...n.basePath,n.definitionPath,t]},!0)??s_(n)}),{}):void 0,i=typeof t==`string`?t:t?.nameStrategy===`title`?void 0:t?.name,a=Ny(e._def,i===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,i]},!1)??s_(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},Ly=o({isSerializableSchema:()=>By,isStandardJsonSchema:()=>zy,isStandardSchema:()=>Ry});function Ry(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 zy(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 By(e){return Ry(e)&&zy(e)}function Vy(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(!Vy(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(!Vy(e[r],t[r]))return!1;return!0}return e===t}function Hy(e){return encodeURI(Uy(e))}function Uy(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}var Wy={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},Gy={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},Ky={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},qy=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 Jy(e,t=Object.create(null),n=qy,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:Jy(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(Ky[i])continue;let a=`${r}/${Hy(i)}`,o=e[i];if(Array.isArray(o)){if(Wy[i]){let e=o.length;for(let r=0;r<e;r++)Jy(o[r],t,n,`${a}/${r}`)}}else if(Gy[i])for(let e in o)Jy(o[e],t,n,`${a}/${Hy(e)}`);else Jy(o,t,n,a)}return t}var Yy=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,Xy=[0,31,28,31,30,31,30,31,31,30,31,30,31],Zy=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,Qy=/^(?=.{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,$y=/^(?:[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,eb=/^(?:(?:[^\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,tb=/^(?:(?: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,nb=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,rb=/^(?:\/(?:[^~/]|~0|~1)*)*$/,ib=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,ab=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,ob=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))},sb=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,cb=/^((([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,lb=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 ub(e){return e.test.bind(e)}var db={date:pb,time:mb.bind(void 0,!1),"date-time":gb,duration:lb,uri:yb,"uri-reference":ub($y),"uri-template":ub(eb),url:ub(tb),email:ob,hostname:ub(Qy),ipv4:ub(sb),ipv6:ub(cb),regex:xb,uuid:ub(nb),"json-pointer":ub(rb),"json-pointer-uri-fragment":ub(ib),"relative-json-pointer":ub(ab)};function fb(e){return e%4==0&&(e%100!=0||e%400==0)}function pb(e){let t=e.match(Yy);if(!t)return!1;let n=+t[1],r=+t[2],i=+t[3];return r>=1&&r<=12&&i>=1&&i<=(r==2&&fb(n)?29:Xy[r])}function mb(e,t){let n=t.match(Zy);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 hb=/t|\s/i;function gb(e){let t=e.split(hb);return t.length==2&&pb(t[0])&&mb(!0,t[1])}var _b=/\/|:/,vb=/^(?:[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 yb(e){return _b.test(e)&&vb.test(e)}var bb=/[^\\]\\Z/;function xb(e){if(bb.test(e))return!1;try{return new RegExp(e,`u`),!0}catch{return!1}}function Sb(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 Cb(e,t,n=`2019-09`,r=Jy(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:te,then:ne,else:x,format:re,properties:ie,patternProperties:ae,additionalProperties:oe,unevaluatedProperties:se,minProperties:ce,maxProperties:le,propertyNames:S,dependentRequired:ue,dependentSchemas:de,dependencies:fe,prefixItems:pe,items:me,additionalItems:he,unevaluatedItems:ge,contains:_e,minContains:ve,maxContains:ye,minItems:be,maxItems:xe,uniqueItems:Se,minimum:Ce,maximum:we,exclusiveMinimum:Te,exclusiveMaximum:Ee,multipleOf:C,minLength:w,maxLength:De,pattern:T,__absolute_ref__:Oe,__absolute_recursive_ref__:ke}=t,E=[];if(p===!0&&a===null&&(a=t),f===`#`){let l=a===null?r[ke]:a,u=`${s}/$recursiveRef`,d=Cb(e,a===null?t:a,n,r,i,l,o,u,c);d.valid||E.push({instanceLocation:o,keyword:`$recursiveRef`,keywordLocation:u,error:`A subschema had errors.`},...d.errors)}if(d!==void 0){let t=r[Oe||d];if(t===void 0){let e=`Unresolved $ref "${d}".`;throw Oe&&Oe!==d&&(e+=` Absolute URI "${Oe}".`),e+=`\nKnown schemas:\n- ${Object.keys(r).join(`
96
- - `)}`,Error(e)}let l=`${s}/$ref`,u=Cb(e,t,n,r,i,a,o,l,c);if(u.valid||E.push({instanceLocation:o,keyword:`$ref`,keywordLocation:l,error:`A subschema had errors.`},...u.errors),n===`4`||n===`7`)return{valid:E.length===0,errors:E}}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||E.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)&&E.push({instanceLocation:o,keyword:`type`,keywordLocation:`${s}/type`,error:`Instance type "${u}" is invalid. Expected "${m}".`}):m!==void 0&&u!==m&&E.push({instanceLocation:o,keyword:`type`,keywordLocation:`${s}/type`,error:`Instance type "${u}" is invalid. Expected "${m}".`});if(h!==void 0&&(u===`object`||u===`array`?Vy(e,h)||E.push({instanceLocation:o,keyword:`const`,keywordLocation:`${s}/const`,error:`Instance does not match ${JSON.stringify(h)}.`}):e!==h&&E.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=>Vy(e,t))||E.push({instanceLocation:o,keyword:`enum`,keywordLocation:`${s}/enum`,error:`Instance does not match any of ${JSON.stringify(g)}.`}):g.some(t=>e===t)||E.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`;Cb(e,v,n,r,i,a,o,t).valid&&E.push({instanceLocation:o,keyword:`not`,keywordLocation:t,error:`Instance matched "not" schema.`})}let Ae=[];if(y!==void 0){let t=`${s}/anyOf`,l=E.length,u=!1;for(let s=0;s<y.length;s++){let l=y[s],d=Object.create(c),f=Cb(e,l,n,r,i,p===!0?a:null,o,`${t}/${s}`,d);E.push(...f.errors),u||=f.valid,f.valid&&Ae.push(d)}u?E.length=l:E.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=E.length,u=!0;for(let s=0;s<b.length;s++){let l=b[s],d=Object.create(c),f=Cb(e,l,n,r,i,p===!0?a:null,o,`${t}/${s}`,d);E.push(...f.errors),u&&=f.valid,f.valid&&Ae.push(d)}u?E.length=l:E.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=E.length,u=ee.filter((s,l)=>{let u=Object.create(c),d=Cb(e,s,n,r,i,p===!0?a:null,o,`${t}/${l}`,u);return E.push(...d.errors),d.valid&&Ae.push(u),d.valid}).length;u===1?E.length=l:E.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,...Ae),te!==void 0){let t=`${s}/if`;if(Cb(e,te,n,r,i,a,o,t,c).valid){if(ne!==void 0){let l=Cb(e,ne,n,r,i,a,o,`${s}/then`,c);l.valid||E.push({instanceLocation:o,keyword:`if`,keywordLocation:t,error:`Instance does not match "then" schema.`},...l.errors)}}else if(x!==void 0){let l=Cb(e,x,n,r,i,a,o,`${s}/else`,c);l.valid||E.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||E.push({instanceLocation:o,keyword:`required`,keywordLocation:`${s}/required`,error:`Instance does not have required property "${t}".`});let t=Object.keys(e);if(ce!==void 0&&t.length<ce&&E.push({instanceLocation:o,keyword:`minProperties`,keywordLocation:`${s}/minProperties`,error:`Instance does not have at least ${ce} properties.`}),le!==void 0&&t.length>le&&E.push({instanceLocation:o,keyword:`maxProperties`,keywordLocation:`${s}/maxProperties`,error:`Instance does not have at least ${le} properties.`}),S!==void 0){let t=`${s}/propertyNames`;for(let s in e){let e=`${o}/${Hy(s)}`,c=Cb(s,S,n,r,i,a,e,t);c.valid||E.push({instanceLocation:o,keyword:`propertyNames`,keywordLocation:t,error:`Property name "${s}" does not match schema.`},...c.errors)}}if(ue!==void 0){let t=`${s}/dependantRequired`;for(let n in ue)if(n in e){let r=ue[n];for(let i of r)i in e||E.push({instanceLocation:o,keyword:`dependentRequired`,keywordLocation:t,error:`Instance has "${n}" but does not have "${i}".`})}}if(de!==void 0)for(let t in de){let l=`${s}/dependentSchemas`;if(t in e){let s=Cb(e,de[t],n,r,i,a,o,`${l}/${Hy(t)}`,c);s.valid||E.push({instanceLocation:o,keyword:`dependentSchemas`,keywordLocation:l,error:`Instance has "${t}" but does not match dependant schema.`},...s.errors)}}if(fe!==void 0){let t=`${s}/dependencies`;for(let s in fe)if(s in e){let c=fe[s];if(Array.isArray(c))for(let n of c)n in e||E.push({instanceLocation:o,keyword:`dependencies`,keywordLocation:t,error:`Instance has "${s}" but does not have "${n}".`});else{let l=Cb(e,c,n,r,i,a,o,`${t}/${Hy(s)}`);l.valid||E.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(ie!==void 0){let t=`${s}/properties`;for(let s in ie){if(!(s in e))continue;let d=`${o}/${Hy(s)}`,f=Cb(e[s],ie[s],n,r,i,a,d,`${t}/${Hy(s)}`);if(f.valid)c[s]=l[s]=!0;else if(u=i,E.push({instanceLocation:o,keyword:`properties`,keywordLocation:t,error:`Property "${s}" does not match schema.`},...f.errors),u)break}}if(!u&&ae!==void 0){let t=`${s}/patternProperties`;for(let s in ae){let d=new RegExp(s,`u`),f=ae[s];for(let p in e){if(!d.test(p))continue;let m=`${o}/${Hy(p)}`,h=Cb(e[p],f,n,r,i,a,m,`${t}/${Hy(s)}`);h.valid?c[p]=l[p]=!0:(u=i,E.push({instanceLocation:o,keyword:`patternProperties`,keywordLocation:t,error:`Property "${p}" matches pattern "${s}" but does not match associated schema.`},...h.errors))}}}if(!u&&oe!==void 0){let t=`${s}/additionalProperties`;for(let s in e){if(l[s])continue;let d=`${o}/${Hy(s)}`,f=Cb(e[s],oe,n,r,i,a,d,t);f.valid?c[s]=!0:(u=i,E.push({instanceLocation:o,keyword:`additionalProperties`,keywordLocation:t,error:`Property "${s}" does not match additional properties schema.`},...f.errors))}}else if(!u&&se!==void 0){let t=`${s}/unevaluatedProperties`;for(let s in e)if(!c[s]){let l=`${o}/${Hy(s)}`,u=Cb(e[s],se,n,r,i,a,l,t);u.valid?c[s]=!0:E.push({instanceLocation:o,keyword:`unevaluatedProperties`,keywordLocation:t,error:`Property "${s}" does not match unevaluated properties schema.`},...u.errors)}}}else if(u===`array`){xe!==void 0&&e.length>xe&&E.push({instanceLocation:o,keyword:`maxItems`,keywordLocation:`${s}/maxItems`,error:`Array has too many items (${e.length} > ${xe}).`}),be!==void 0&&e.length<be&&E.push({instanceLocation:o,keyword:`minItems`,keywordLocation:`${s}/minItems`,error:`Array has too few items (${e.length} < ${be}).`});let t=e.length,l=0,u=!1;if(pe!==void 0){let d=`${s}/prefixItems`,f=Math.min(pe.length,t);for(;l<f;l++){let t=Cb(e[l],pe[l],n,r,i,a,`${o}/${l}`,`${d}/${l}`);if(c[l]=!0,!t.valid&&(u=i,E.push({instanceLocation:o,keyword:`prefixItems`,keywordLocation:d,error:`Items did not match schema.`},...t.errors),u))break}}if(me!==void 0){let d=`${s}/items`;if(Array.isArray(me)){let s=Math.min(me.length,t);for(;l<s;l++){let t=Cb(e[l],me[l],n,r,i,a,`${o}/${l}`,`${d}/${l}`);if(c[l]=!0,!t.valid&&(u=i,E.push({instanceLocation:o,keyword:`items`,keywordLocation:d,error:`Items did not match schema.`},...t.errors),u))break}}else for(;l<t;l++){let t=Cb(e[l],me,n,r,i,a,`${o}/${l}`,d);if(c[l]=!0,!t.valid&&(u=i,E.push({instanceLocation:o,keyword:`items`,keywordLocation:d,error:`Items did not match schema.`},...t.errors),u))break}if(!u&&he!==void 0){let d=`${s}/additionalItems`;for(;l<t;l++){let t=Cb(e[l],he,n,r,i,a,`${o}/${l}`,d);c[l]=!0,t.valid||(u=i,E.push({instanceLocation:o,keyword:`additionalItems`,keywordLocation:d,error:`Items did not match additional items schema.`},...t.errors))}}}if(_e!==void 0)if(t===0&&ve===void 0)E.push({instanceLocation:o,keyword:`contains`,keywordLocation:`${s}/contains`,error:`Array is empty. It must contain at least one item matching the schema.`});else if(ve!==void 0&&t<ve)E.push({instanceLocation:o,keyword:`minContains`,keywordLocation:`${s}/minContains`,error:`Array has less items (${t}) than minContains (${ve}).`});else{let l=`${s}/contains`,u=E.length,d=0;for(let s=0;s<t;s++){let t=Cb(e[s],_e,n,r,i,a,`${o}/${s}`,l);t.valid?(c[s]=!0,d++):E.push(...t.errors)}d>=(ve||0)&&(E.length=u),ve===void 0&&ye===void 0&&d===0?E.splice(u,0,{instanceLocation:o,keyword:`contains`,keywordLocation:l,error:`Array does not contain item matching schema.`}):ve!==void 0&&d<ve?E.push({instanceLocation:o,keyword:`minContains`,keywordLocation:`${s}/minContains`,error:`Array must contain at least ${ve} items matching schema. Only ${d} items were found.`}):ye!==void 0&&d>ye&&E.push({instanceLocation:o,keyword:`maxContains`,keywordLocation:`${s}/maxContains`,error:`Array may contain at most ${ye} items matching schema. ${d} items were found.`})}if(!u&&ge!==void 0){let u=`${s}/unevaluatedItems`;for(;l<t;l++){if(c[l])continue;let t=Cb(e[l],ge,n,r,i,a,`${o}/${l}`,u);c[l]=!0,t.valid||E.push({instanceLocation:o,keyword:`unevaluatedItems`,keywordLocation:u,error:`Items did not match unevaluated items schema.`},...t.errors)}}if(Se)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&&Vy(r,t))&&(E.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`?(Ce!==void 0&&(Te===!0&&e<=Ce||e<Ce)&&E.push({instanceLocation:o,keyword:`minimum`,keywordLocation:`${s}/minimum`,error:`${e} is less than ${Te?`or equal to `:``} ${Ce}.`}),we!==void 0&&(Ee===!0&&e>=we||e>we)&&E.push({instanceLocation:o,keyword:`maximum`,keywordLocation:`${s}/maximum`,error:`${e} is greater than ${Ee?`or equal to `:``} ${we}.`})):(Ce!==void 0&&e<Ce&&E.push({instanceLocation:o,keyword:`minimum`,keywordLocation:`${s}/minimum`,error:`${e} is less than ${Ce}.`}),we!==void 0&&e>we&&E.push({instanceLocation:o,keyword:`maximum`,keywordLocation:`${s}/maximum`,error:`${e} is greater than ${we}.`}),Te!==void 0&&e<=Te&&E.push({instanceLocation:o,keyword:`exclusiveMinimum`,keywordLocation:`${s}/exclusiveMinimum`,error:`${e} is less than ${Te}.`}),Ee!==void 0&&e>=Ee&&E.push({instanceLocation:o,keyword:`exclusiveMaximum`,keywordLocation:`${s}/exclusiveMaximum`,error:`${e} is greater than or equal to ${Ee}.`})),C!==void 0){let t=e%C;Math.abs(0-t)>=1.1920929e-7&&Math.abs(C-t)>=1.1920929e-7&&E.push({instanceLocation:o,keyword:`multipleOf`,keywordLocation:`${s}/multipleOf`,error:`${e} is not a multiple of ${C}.`})}}else if(u===`string`){let t=w===void 0&&De===void 0?0:Sb(e);w!==void 0&&t<w&&E.push({instanceLocation:o,keyword:`minLength`,keywordLocation:`${s}/minLength`,error:`String is too short (${t} < ${w}).`}),De!==void 0&&t>De&&E.push({instanceLocation:o,keyword:`maxLength`,keywordLocation:`${s}/maxLength`,error:`String is too long (${t} > ${De}).`}),T!==void 0&&!new RegExp(T,`u`).test(e)&&E.push({instanceLocation:o,keyword:`pattern`,keywordLocation:`${s}/pattern`,error:`String does not match pattern.`}),re!==void 0&&db[re]&&!db[re](e)&&E.push({instanceLocation:o,keyword:`format`,keywordLocation:`${s}/format`,error:`String does not match format "${re}".`})}return{valid:E.length===0,errors:E}}var wb=class{schema;draft;shortCircuit;lookup;constructor(e,t=`2019-09`,n=!0){this.schema=e,this.draft=t,this.shortCircuit=n,this.lookup=Jy(e)}validate(e){return Cb(e,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(e,t){t&&(e={...e,$id:t}),Jy(e,this.lookup)}},Tb=o({Validator:()=>wb,deepCompareStrict:()=>Vy,toJsonSchema:()=>Db,validatesOnlyStrings:()=>Ob}),Eb=new WeakMap;function Db(e,t){let n=!t&&typeof e==`object`&&!!e;if(n){let t=Eb.get(e);if(t)return t}let r;if(zy(e)&&!yg(e))r=e[`~standard`].jsonSchema.input({target:`draft-07`});else if(yg(e)){let n=Jg(e,!0);r=Pg(n)?vg(Hg(n,!0),t):vg(e,t)}else r=bg(e)?Iy(e):e;return n&&typeof r==`object`&&r&&Eb.set(e,r),r}function Ob(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=>Ob(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=>Ob(e))}if(`not`in e)return!1;if(`$ref`in e&&typeof e.$ref==`string`){let t=e.$ref,n=Jy(e);return n[t]?Ob(n[t]):!1}return!1}var kb=o({Graph:()=>Mb});function Ab(e,t){if(e!==void 0&&!An(e))return e;if(Uu(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 jb(e){return Uu(e.data)?{type:`runnable`,data:{id:e.data.lc_id,name:e.data.getName()}}:{type:`schema`,data:{...Db(e.data.schema),title:e.data.name}}}var Mb=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]=An(t.id)?n:t.id}),{nodes:Object.values(this.nodes).map(t=>({id:e[t.id],...jb(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??qn(),i={id:r,data:e,name:Ab(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 Nb(this)}lastNode(){return Pb(this)}extend(e,t=``){let n=t;Object.values(e.nodes).map(e=>e.id).every(An)&&(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&&Nb(this,[e.id])&&this.removeNode(e)}trimLastNode(){let e=this.lastNode();e&&Pb(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 An(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 e_(a.nodes,a.edges,{firstNode:o?.id,lastNode:s?.id,withStyles:t,curveStyle:n,nodeColors:r,wrapLabelNWords:i})}async drawMermaidPng(e){return t_(this.drawMermaid(e),{backgroundColor:e?.backgroundColor})}};function Nb(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 Pb(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 Fb(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
95
+ ]))`;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 uy(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===R.ZodEnum)return{type:`object`,required:e.keyType._def.values,properties:e.keyType._def.values.reduce((n,r)=>({...n,[r]:My(e.valueType._def,{...t,currentPath:[...t.currentPath,`properties`,r]})??s_(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};let n={type:`object`,additionalProperties:My(e.valueType._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]})??t.allowedAdditionalProperties};if(t.target===`openApi3`)return n;if(e.keyType?._def.typeName===R.ZodString&&e.keyType._def.checks?.length){let{type:r,...i}=ry(e.keyType._def,t);return{...n,propertyNames:i}}else if(e.keyType?._def.typeName===R.ZodEnum)return{...n,propertyNames:{enum:e.keyType._def.values}};else if(e.keyType?._def.typeName===R.ZodBranded&&e.keyType._def.type._def.typeName===R.ZodString&&e.keyType._def.type._def.checks?.length){let{type:r,...i}=Gv(e.keyType._def,t);return{...n,propertyNames:i}}return n}function dy(e,t){return t.mapStrategy===`record`?uy(e,t):{type:`array`,maxItems:125,items:{type:`array`,items:[My(e.keyType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`0`]})||s_(t),My(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`1`]})||s_(t)],minItems:2,maxItems:2}}}function fy(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 py(e){return e.target===`openAi`?void 0:{not:s_({...e,currentPath:[...e.currentPath,`not`]})}}function my(e){return e.target===`openApi3`?{enum:[`null`],nullable:!0}:{type:`null`}}var hy={ZodString:`string`,ZodNumber:`number`,ZodBigInt:`integer`,ZodBoolean:`boolean`,ZodNull:`null`};function gy(e,t){if(t.target===`openApi3`)return _y(e,t);let n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(e=>e._def.typeName in hy&&(!e._def.checks||!e._def.checks.length))){let e=n.reduce((e,t)=>{let n=hy[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 _y(e,t)}var _y=(e,t)=>{let n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((e,n)=>My(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 vy(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:hy[e.innerType._def.typeName],nullable:!0}:{type:[hy[e.innerType._def.typeName],`null`]};if(t.target===`openApi3`){let n=My(e.innerType._def,{...t,currentPath:[...t.currentPath]});return n&&`$ref`in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let n=My(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`0`]});return n&&{anyOf:[n,{type:`null`}]}}function yy(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`,c_(n,`type`,r.message,t);break;case`min`:t.target===`jsonSchema7`?r.inclusive?l_(n,`minimum`,r.value,r.message,t):l_(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),l_(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?l_(n,`maximum`,r.value,r.message,t):l_(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),l_(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:l_(n,`multipleOf`,r.value,r.message,t);break}return n}function by(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=Sy(o);s&&n&&(o._def.typeName===`ZodOptional`&&(o=o._def.innerType),o.isNullable()||(o=o.nullable()),s=!1);let c=My(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=xy(e,t);return o!==void 0&&(r.additionalProperties=o),r}function xy(e,t){if(e.catchall._def.typeName!==`ZodNever`)return My(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 Sy(e){try{return e.isOptional()}catch{return!0}}var Cy=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return My(e.innerType._def,t);let n=My(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`1`]});return n?{anyOf:[{not:s_(t)},n]}:s_(t)},wy=(e,t)=>{if(t.pipeStrategy===`input`)return My(e.in._def,t);if(t.pipeStrategy===`output`)return My(e.out._def,t);let n=My(e.in._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]});return{allOf:[n,My(e.out._def,{...t,currentPath:[...t.currentPath,`allOf`,n?`1`:`0`]})].filter(e=>e!==void 0)}};function Ty(e,t){return My(e.type._def,t)}function Ey(e,t){let n={type:`array`,uniqueItems:!0,items:My(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`]})};return e.minSize&&l_(n,`minItems`,e.minSize.value,e.minSize.message,t),e.maxSize&&l_(n,`maxItems`,e.maxSize.value,e.maxSize.message,t),n}function Dy(e,t){return e.rest?{type:`array`,minItems:e.items.length,items:e.items.map((e,n)=>My(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[]),additionalItems:My(e.rest._def,{...t,currentPath:[...t.currentPath,`additionalItems`]})}:{type:`array`,minItems:e.items.length,maxItems:e.items.length,items:e.items.map((e,n)=>My(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[])}}function Oy(e){return{not:s_(e)}}function ky(e){return s_(e)}var Ay=(e,t)=>My(e.innerType._def,t),jy=(e,t,n)=>{switch(t){case R.ZodString:return ry(e,n);case R.ZodNumber:return yy(e,n);case R.ZodObject:return by(e,n);case R.ZodBigInt:return Uv(e,n);case R.ZodBoolean:return Wv();case R.ZodDate:return qv(e,n);case R.ZodUndefined:return Oy(n);case R.ZodNull:return my(n);case R.ZodArray:return Hv(e,n);case R.ZodUnion:case R.ZodDiscriminatedUnion:return gy(e,n);case R.ZodIntersection:return $v(e,n);case R.ZodTuple:return Dy(e,n);case R.ZodRecord:return uy(e,n);case R.ZodLiteral:return ey(e,n);case R.ZodEnum:return Zv(e);case R.ZodNativeEnum:return fy(e);case R.ZodNullable:return vy(e,n);case R.ZodOptional:return Cy(e,n);case R.ZodMap:return dy(e,n);case R.ZodSet:return Ey(e,n);case R.ZodLazy:return()=>e.getter()._def;case R.ZodPromise:return Ty(e,n);case R.ZodNaN:case R.ZodNever:return py(n);case R.ZodEffects:return Xv(e,n);case R.ZodAny:return s_(n);case R.ZodUnknown:return ky(n);case R.ZodDefault:return Yv(e,n);case R.ZodBranded:return Gv(e,n);case R.ZodReadonly:return Ay(e,n);case R.ZodCatch:return Kv(e,n);case R.ZodPipeline:return wy(e,n);case R.ZodFunction:case R.ZodVoid:case R.ZodSymbol:return;default:return(e=>void 0)(t)}};function My(e,t,n=!1){let r=t.seen.get(e);if(t.override){let i=t.override?.(e,t,r,n);if(i!==n_)return i}if(r&&!n){let e=Ny(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=jy(e,e.typeName,t),o=typeof a==`function`?My(a(),t):a;if(o&&Py(e,t,o),t.postProcess){let n=t.postProcess(o,e,t);return i.jsonSchema=o,n}return i.jsonSchema=o,o}var Ny=(e,t)=>{switch(t.$refStrategy){case`root`:return{$ref:e.path.join(`/`)};case`relative`:return{$ref:o_(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`),s_(t)):t.$refStrategy===`seen`?s_(t):void 0}},Py=(e,t,n)=>(e.description&&(n.description=e.description,t.markdownDescription&&(n.markdownDescription=e.description)),n),Fy=(e,t)=>{let n=a_(t),r=typeof t==`object`&&t.definitions?Object.entries(t.definitions).reduce((e,[t,r])=>({...e,[t]:My(r._def,{...n,currentPath:[...n.basePath,n.definitionPath,t]},!0)??s_(n)}),{}):void 0,i=typeof t==`string`?t:t?.nameStrategy===`title`?void 0:t?.name,a=My(e._def,i===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,i]},!1)??s_(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},Iy=o({isSerializableSchema:()=>zy,isStandardJsonSchema:()=>Ry,isStandardSchema:()=>Ly});function Ly(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 Ry(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 zy(e){return Ly(e)&&Ry(e)}function By(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(!By(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(!By(e[r],t[r]))return!1;return!0}return e===t}function Vy(e){return encodeURI(Hy(e))}function Hy(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}var Uy={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},Wy={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},Gy={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},Ky=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 qy(e,t=Object.create(null),n=Ky,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:qy(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(Gy[i])continue;let a=`${r}/${Vy(i)}`,o=e[i];if(Array.isArray(o)){if(Uy[i]){let e=o.length;for(let r=0;r<e;r++)qy(o[r],t,n,`${a}/${r}`)}}else if(Wy[i])for(let e in o)qy(o[e],t,n,`${a}/${Vy(e)}`);else qy(o,t,n,a)}return t}var Jy=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,Yy=[0,31,28,31,30,31,30,31,31,30,31,30,31],Xy=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,Zy=/^(?=.{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,Qy=/^(?:[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,$y=/^(?:(?:[^\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,eb=/^(?:(?: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,tb=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,nb=/^(?:\/(?:[^~/]|~0|~1)*)*$/,rb=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,ib=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,ab=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))},ob=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,sb=/^((([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,cb=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 lb(e){return e.test.bind(e)}var ub={date:fb,time:pb.bind(void 0,!1),"date-time":hb,duration:cb,uri:vb,"uri-reference":lb(Qy),"uri-template":lb($y),url:lb(eb),email:ab,hostname:lb(Zy),ipv4:lb(ob),ipv6:lb(sb),regex:bb,uuid:lb(tb),"json-pointer":lb(nb),"json-pointer-uri-fragment":lb(rb),"relative-json-pointer":lb(ib)};function db(e){return e%4==0&&(e%100!=0||e%400==0)}function fb(e){let t=e.match(Jy);if(!t)return!1;let n=+t[1],r=+t[2],i=+t[3];return r>=1&&r<=12&&i>=1&&i<=(r==2&&db(n)?29:Yy[r])}function pb(e,t){let n=t.match(Xy);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 mb=/t|\s/i;function hb(e){let t=e.split(mb);return t.length==2&&fb(t[0])&&pb(!0,t[1])}var gb=/\/|:/,_b=/^(?:[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 vb(e){return gb.test(e)&&_b.test(e)}var yb=/[^\\]\\Z/;function bb(e){if(yb.test(e))return!1;try{return new RegExp(e,`u`),!0}catch{return!1}}function xb(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 Sb(e,t,n=`2019-09`,r=qy(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:te,then:ne,else:x,format:re,properties:ie,patternProperties:ae,additionalProperties:oe,unevaluatedProperties:se,minProperties:ce,maxProperties:le,propertyNames:S,dependentRequired:ue,dependentSchemas:de,dependencies:fe,prefixItems:pe,items:me,additionalItems:he,unevaluatedItems:ge,contains:_e,minContains:ve,maxContains:ye,minItems:be,maxItems:xe,uniqueItems:Se,minimum:Ce,maximum:we,exclusiveMinimum:Te,exclusiveMaximum:Ee,multipleOf:C,minLength:w,maxLength:De,pattern:T,__absolute_ref__:Oe,__absolute_recursive_ref__:ke}=t,E=[];if(p===!0&&a===null&&(a=t),f===`#`){let l=a===null?r[ke]:a,u=`${s}/$recursiveRef`,d=Sb(e,a===null?t:a,n,r,i,l,o,u,c);d.valid||E.push({instanceLocation:o,keyword:`$recursiveRef`,keywordLocation:u,error:`A subschema had errors.`},...d.errors)}if(d!==void 0){let t=r[Oe||d];if(t===void 0){let e=`Unresolved $ref "${d}".`;throw Oe&&Oe!==d&&(e+=` Absolute URI "${Oe}".`),e+=`\nKnown schemas:\n- ${Object.keys(r).join(`
96
+ - `)}`,Error(e)}let l=`${s}/$ref`,u=Sb(e,t,n,r,i,a,o,l,c);if(u.valid||E.push({instanceLocation:o,keyword:`$ref`,keywordLocation:l,error:`A subschema had errors.`},...u.errors),n===`4`||n===`7`)return{valid:E.length===0,errors:E}}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||E.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)&&E.push({instanceLocation:o,keyword:`type`,keywordLocation:`${s}/type`,error:`Instance type "${u}" is invalid. Expected "${m}".`}):m!==void 0&&u!==m&&E.push({instanceLocation:o,keyword:`type`,keywordLocation:`${s}/type`,error:`Instance type "${u}" is invalid. Expected "${m}".`});if(h!==void 0&&(u===`object`||u===`array`?By(e,h)||E.push({instanceLocation:o,keyword:`const`,keywordLocation:`${s}/const`,error:`Instance does not match ${JSON.stringify(h)}.`}):e!==h&&E.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=>By(e,t))||E.push({instanceLocation:o,keyword:`enum`,keywordLocation:`${s}/enum`,error:`Instance does not match any of ${JSON.stringify(g)}.`}):g.some(t=>e===t)||E.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`;Sb(e,v,n,r,i,a,o,t).valid&&E.push({instanceLocation:o,keyword:`not`,keywordLocation:t,error:`Instance matched "not" schema.`})}let Ae=[];if(y!==void 0){let t=`${s}/anyOf`,l=E.length,u=!1;for(let s=0;s<y.length;s++){let l=y[s],d=Object.create(c),f=Sb(e,l,n,r,i,p===!0?a:null,o,`${t}/${s}`,d);E.push(...f.errors),u||=f.valid,f.valid&&Ae.push(d)}u?E.length=l:E.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=E.length,u=!0;for(let s=0;s<b.length;s++){let l=b[s],d=Object.create(c),f=Sb(e,l,n,r,i,p===!0?a:null,o,`${t}/${s}`,d);E.push(...f.errors),u&&=f.valid,f.valid&&Ae.push(d)}u?E.length=l:E.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=E.length,u=ee.filter((s,l)=>{let u=Object.create(c),d=Sb(e,s,n,r,i,p===!0?a:null,o,`${t}/${l}`,u);return E.push(...d.errors),d.valid&&Ae.push(u),d.valid}).length;u===1?E.length=l:E.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,...Ae),te!==void 0){let t=`${s}/if`;if(Sb(e,te,n,r,i,a,o,t,c).valid){if(ne!==void 0){let l=Sb(e,ne,n,r,i,a,o,`${s}/then`,c);l.valid||E.push({instanceLocation:o,keyword:`if`,keywordLocation:t,error:`Instance does not match "then" schema.`},...l.errors)}}else if(x!==void 0){let l=Sb(e,x,n,r,i,a,o,`${s}/else`,c);l.valid||E.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||E.push({instanceLocation:o,keyword:`required`,keywordLocation:`${s}/required`,error:`Instance does not have required property "${t}".`});let t=Object.keys(e);if(ce!==void 0&&t.length<ce&&E.push({instanceLocation:o,keyword:`minProperties`,keywordLocation:`${s}/minProperties`,error:`Instance does not have at least ${ce} properties.`}),le!==void 0&&t.length>le&&E.push({instanceLocation:o,keyword:`maxProperties`,keywordLocation:`${s}/maxProperties`,error:`Instance does not have at least ${le} properties.`}),S!==void 0){let t=`${s}/propertyNames`;for(let s in e){let e=`${o}/${Vy(s)}`,c=Sb(s,S,n,r,i,a,e,t);c.valid||E.push({instanceLocation:o,keyword:`propertyNames`,keywordLocation:t,error:`Property name "${s}" does not match schema.`},...c.errors)}}if(ue!==void 0){let t=`${s}/dependantRequired`;for(let n in ue)if(n in e){let r=ue[n];for(let i of r)i in e||E.push({instanceLocation:o,keyword:`dependentRequired`,keywordLocation:t,error:`Instance has "${n}" but does not have "${i}".`})}}if(de!==void 0)for(let t in de){let l=`${s}/dependentSchemas`;if(t in e){let s=Sb(e,de[t],n,r,i,a,o,`${l}/${Vy(t)}`,c);s.valid||E.push({instanceLocation:o,keyword:`dependentSchemas`,keywordLocation:l,error:`Instance has "${t}" but does not match dependant schema.`},...s.errors)}}if(fe!==void 0){let t=`${s}/dependencies`;for(let s in fe)if(s in e){let c=fe[s];if(Array.isArray(c))for(let n of c)n in e||E.push({instanceLocation:o,keyword:`dependencies`,keywordLocation:t,error:`Instance has "${s}" but does not have "${n}".`});else{let l=Sb(e,c,n,r,i,a,o,`${t}/${Vy(s)}`);l.valid||E.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(ie!==void 0){let t=`${s}/properties`;for(let s in ie){if(!(s in e))continue;let d=`${o}/${Vy(s)}`,f=Sb(e[s],ie[s],n,r,i,a,d,`${t}/${Vy(s)}`);if(f.valid)c[s]=l[s]=!0;else if(u=i,E.push({instanceLocation:o,keyword:`properties`,keywordLocation:t,error:`Property "${s}" does not match schema.`},...f.errors),u)break}}if(!u&&ae!==void 0){let t=`${s}/patternProperties`;for(let s in ae){let d=new RegExp(s,`u`),f=ae[s];for(let p in e){if(!d.test(p))continue;let m=`${o}/${Vy(p)}`,h=Sb(e[p],f,n,r,i,a,m,`${t}/${Vy(s)}`);h.valid?c[p]=l[p]=!0:(u=i,E.push({instanceLocation:o,keyword:`patternProperties`,keywordLocation:t,error:`Property "${p}" matches pattern "${s}" but does not match associated schema.`},...h.errors))}}}if(!u&&oe!==void 0){let t=`${s}/additionalProperties`;for(let s in e){if(l[s])continue;let d=`${o}/${Vy(s)}`,f=Sb(e[s],oe,n,r,i,a,d,t);f.valid?c[s]=!0:(u=i,E.push({instanceLocation:o,keyword:`additionalProperties`,keywordLocation:t,error:`Property "${s}" does not match additional properties schema.`},...f.errors))}}else if(!u&&se!==void 0){let t=`${s}/unevaluatedProperties`;for(let s in e)if(!c[s]){let l=`${o}/${Vy(s)}`,u=Sb(e[s],se,n,r,i,a,l,t);u.valid?c[s]=!0:E.push({instanceLocation:o,keyword:`unevaluatedProperties`,keywordLocation:t,error:`Property "${s}" does not match unevaluated properties schema.`},...u.errors)}}}else if(u===`array`){xe!==void 0&&e.length>xe&&E.push({instanceLocation:o,keyword:`maxItems`,keywordLocation:`${s}/maxItems`,error:`Array has too many items (${e.length} > ${xe}).`}),be!==void 0&&e.length<be&&E.push({instanceLocation:o,keyword:`minItems`,keywordLocation:`${s}/minItems`,error:`Array has too few items (${e.length} < ${be}).`});let t=e.length,l=0,u=!1;if(pe!==void 0){let d=`${s}/prefixItems`,f=Math.min(pe.length,t);for(;l<f;l++){let t=Sb(e[l],pe[l],n,r,i,a,`${o}/${l}`,`${d}/${l}`);if(c[l]=!0,!t.valid&&(u=i,E.push({instanceLocation:o,keyword:`prefixItems`,keywordLocation:d,error:`Items did not match schema.`},...t.errors),u))break}}if(me!==void 0){let d=`${s}/items`;if(Array.isArray(me)){let s=Math.min(me.length,t);for(;l<s;l++){let t=Sb(e[l],me[l],n,r,i,a,`${o}/${l}`,`${d}/${l}`);if(c[l]=!0,!t.valid&&(u=i,E.push({instanceLocation:o,keyword:`items`,keywordLocation:d,error:`Items did not match schema.`},...t.errors),u))break}}else for(;l<t;l++){let t=Sb(e[l],me,n,r,i,a,`${o}/${l}`,d);if(c[l]=!0,!t.valid&&(u=i,E.push({instanceLocation:o,keyword:`items`,keywordLocation:d,error:`Items did not match schema.`},...t.errors),u))break}if(!u&&he!==void 0){let d=`${s}/additionalItems`;for(;l<t;l++){let t=Sb(e[l],he,n,r,i,a,`${o}/${l}`,d);c[l]=!0,t.valid||(u=i,E.push({instanceLocation:o,keyword:`additionalItems`,keywordLocation:d,error:`Items did not match additional items schema.`},...t.errors))}}}if(_e!==void 0)if(t===0&&ve===void 0)E.push({instanceLocation:o,keyword:`contains`,keywordLocation:`${s}/contains`,error:`Array is empty. It must contain at least one item matching the schema.`});else if(ve!==void 0&&t<ve)E.push({instanceLocation:o,keyword:`minContains`,keywordLocation:`${s}/minContains`,error:`Array has less items (${t}) than minContains (${ve}).`});else{let l=`${s}/contains`,u=E.length,d=0;for(let s=0;s<t;s++){let t=Sb(e[s],_e,n,r,i,a,`${o}/${s}`,l);t.valid?(c[s]=!0,d++):E.push(...t.errors)}d>=(ve||0)&&(E.length=u),ve===void 0&&ye===void 0&&d===0?E.splice(u,0,{instanceLocation:o,keyword:`contains`,keywordLocation:l,error:`Array does not contain item matching schema.`}):ve!==void 0&&d<ve?E.push({instanceLocation:o,keyword:`minContains`,keywordLocation:`${s}/minContains`,error:`Array must contain at least ${ve} items matching schema. Only ${d} items were found.`}):ye!==void 0&&d>ye&&E.push({instanceLocation:o,keyword:`maxContains`,keywordLocation:`${s}/maxContains`,error:`Array may contain at most ${ye} items matching schema. ${d} items were found.`})}if(!u&&ge!==void 0){let u=`${s}/unevaluatedItems`;for(;l<t;l++){if(c[l])continue;let t=Sb(e[l],ge,n,r,i,a,`${o}/${l}`,u);c[l]=!0,t.valid||E.push({instanceLocation:o,keyword:`unevaluatedItems`,keywordLocation:u,error:`Items did not match unevaluated items schema.`},...t.errors)}}if(Se)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&&By(r,t))&&(E.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`?(Ce!==void 0&&(Te===!0&&e<=Ce||e<Ce)&&E.push({instanceLocation:o,keyword:`minimum`,keywordLocation:`${s}/minimum`,error:`${e} is less than ${Te?`or equal to `:``} ${Ce}.`}),we!==void 0&&(Ee===!0&&e>=we||e>we)&&E.push({instanceLocation:o,keyword:`maximum`,keywordLocation:`${s}/maximum`,error:`${e} is greater than ${Ee?`or equal to `:``} ${we}.`})):(Ce!==void 0&&e<Ce&&E.push({instanceLocation:o,keyword:`minimum`,keywordLocation:`${s}/minimum`,error:`${e} is less than ${Ce}.`}),we!==void 0&&e>we&&E.push({instanceLocation:o,keyword:`maximum`,keywordLocation:`${s}/maximum`,error:`${e} is greater than ${we}.`}),Te!==void 0&&e<=Te&&E.push({instanceLocation:o,keyword:`exclusiveMinimum`,keywordLocation:`${s}/exclusiveMinimum`,error:`${e} is less than ${Te}.`}),Ee!==void 0&&e>=Ee&&E.push({instanceLocation:o,keyword:`exclusiveMaximum`,keywordLocation:`${s}/exclusiveMaximum`,error:`${e} is greater than or equal to ${Ee}.`})),C!==void 0){let t=e%C;Math.abs(0-t)>=1.1920929e-7&&Math.abs(C-t)>=1.1920929e-7&&E.push({instanceLocation:o,keyword:`multipleOf`,keywordLocation:`${s}/multipleOf`,error:`${e} is not a multiple of ${C}.`})}}else if(u===`string`){let t=w===void 0&&De===void 0?0:xb(e);w!==void 0&&t<w&&E.push({instanceLocation:o,keyword:`minLength`,keywordLocation:`${s}/minLength`,error:`String is too short (${t} < ${w}).`}),De!==void 0&&t>De&&E.push({instanceLocation:o,keyword:`maxLength`,keywordLocation:`${s}/maxLength`,error:`String is too long (${t} > ${De}).`}),T!==void 0&&!new RegExp(T,`u`).test(e)&&E.push({instanceLocation:o,keyword:`pattern`,keywordLocation:`${s}/pattern`,error:`String does not match pattern.`}),re!==void 0&&ub[re]&&!ub[re](e)&&E.push({instanceLocation:o,keyword:`format`,keywordLocation:`${s}/format`,error:`String does not match format "${re}".`})}return{valid:E.length===0,errors:E}}var Cb=class{schema;draft;shortCircuit;lookup;constructor(e,t=`2019-09`,n=!0){this.schema=e,this.draft=t,this.shortCircuit=n,this.lookup=qy(e)}validate(e){return Sb(e,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(e,t){t&&(e={...e,$id:t}),qy(e,this.lookup)}},wb=o({Validator:()=>Cb,deepCompareStrict:()=>By,toJsonSchema:()=>Eb,validatesOnlyStrings:()=>Db}),Tb=new WeakMap;function Eb(e,t){let n=!t&&typeof e==`object`&&!!e;if(n){let t=Tb.get(e);if(t)return t}let r;if(Ry(e)&&!yg(e))r=e[`~standard`].jsonSchema.input({target:`draft-07`});else if(yg(e)){let n=Jg(e,!0);r=Pg(n)?vg(Hg(n,!0),t):vg(e,t)}else r=bg(e)?Fy(e):e;return n&&typeof r==`object`&&r&&Tb.set(e,r),r}function Db(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=>Db(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=>Db(e))}if(`not`in e)return!1;if(`$ref`in e&&typeof e.$ref==`string`){let t=e.$ref,n=qy(e);return n[t]?Db(n[t]):!1}return!1}var Ob=o({Graph:()=>jb});function kb(e,t){if(e!==void 0&&!An(e))return e;if(Uu(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 Ab(e){return Uu(e.data)?{type:`runnable`,data:{id:e.data.lc_id,name:e.data.getName()}}:{type:`schema`,data:{...Eb(e.data.schema),title:e.data.name}}}var jb=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]=An(t.id)?n:t.id}),{nodes:Object.values(this.nodes).map(t=>({id:e[t.id],...Ab(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??qn(),i={id:r,data:e,name:kb(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 Mb(this)}lastNode(){return Nb(this)}extend(e,t=``){let n=t;Object.values(e.nodes).map(e=>e.id).every(An)&&(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&&Mb(this,[e.id])&&this.removeNode(e)}trimLastNode(){let e=this.lastNode();e&&Nb(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 An(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 e_(a.nodes,a.edges,{firstNode:o?.id,lastNode:s?.id,withStyles:t,curveStyle:n,nodeColors:r,wrapLabelNWords:i})}async drawMermaidPng(e){return t_(this.drawMermaid(e),{backgroundColor:e?.backgroundColor})}};function Mb(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 Nb(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 Pb(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
97
97
 
98
- `)),n.close()}});return Ll.fromReadableStream(n)}function Ib(e){return typeof e==`object`&&!!e&&typeof e[Symbol.iterator]==`function`&&typeof e.next==`function`}var Lb=e=>typeof e==`object`&&!!e&&`next`in e&&typeof e.next==`function`;function Rb(e){return typeof e==`object`&&!!e&&typeof e[Symbol.asyncIterator]==`function`}function zb(e){return typeof e==`object`&&!!e&&typeof e.next==`function`}async function Bb(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*Vb(e,t){for(;;){let{value:n,done:r}=wl.runWithConfig(Nl(e),t.next.bind(t),!0);if(r)break;yield n}}async function*Hb(e,t){let n=t[Symbol.asyncIterator]();for(;;){let{value:r,done:i}=await wl.runWithConfig(Nl(e),n.next.bind(t),!0);if(i)break;yield r}}function Ub(e,t){return e&&!Array.isArray(e)&&!(e instanceof Date)&&typeof e==`object`?e:{[t]:e}}var Wb=class extends _e{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 qb({bound:this,kwargs:{},config:{},maxAttemptNumber:e?.stopAfterAttempt,...e})}withConfig(e){return new Gb({bound:this,config:e,kwargs:{}})}withFallbacks(e){let t=Array.isArray(e)?e:e.fallbacks;return new ex({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(jl);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)=>jl(r===0?e:n))}return Array.from({length:t},()=>jl(e))}async batch(e,t,n){let r=this._getOptionsList(t??{},e.length),i=new Vu({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=jl(t),r=new Bl({generator:this._streamIterator(e,n),config:n});return await r.setup,Ll.fromAsyncGenerator(r)}_separateRunnableConfigFromCallOptions(e){let t;t=jl(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=jl(n),i=await(await kl(r))?.handleChainStart(this.toJSON(),Ub(t,`input`),r.runId,r?.runType,void 0,void 0,r?.runName??this.getName());delete r.runId;let a;try{a=await Pl(e.call(this,t,r,i),r.signal)}catch(e){throw await i?.handleChainError(e),e}return await i?.handleChainEnd(Ub(a,`output`)),a}async _batchWithConfig(e,t,n,r){let i=this._getOptionsList(n??{},t.length),a=await Promise.all(i.map(kl)),o=await Promise.all(a.map(async(e,n)=>{let r=await e?.handleChainStart(this.toJSON(),Ub(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 Pl(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(Ub(s,`output`)))),s}_concatOutputChunks(e,t){return zl(e,t)}async*_transformStreamWithConfig(e,t,n){let r,i=!0,a,o=!0,s=jl(n),c=await kl(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 Vl(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(Tu),r=e.output;n!==void 0&&d!==void 0&&(r=n.tapOutputIterable(d.runId,r));let i=d?.handlers.find(hu);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:Ub(r,`input`)}),e}await d?.handleChainEnd(a??{},void 0,void 0,void 0,{inputs:Ub(r,`input`)})}getGraph(e){let t=new Mb,n=t.addNode({name:`${this.getName()}Input`,schema:Vv()}),r=t.addNode(this),i=t.addNode({name:`${this.getName()}Output`,schema:Vv()});return t.addEdge(n,r),t.addEdge(r,i),t}pipe(e){return new Jb({first:this,last:tx(e)})}pick(e){return this.pipe(new rx(e))}assign(e){return this.pipe(new nx(new Yb({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,jl(t))}async*streamLog(e,t,n){let r=new yu({...n,autoClose:!1,_schemaFormat:`original`}),i=jl(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 pu({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`?Fb(r):Ll.fromAsyncGenerator(r)}async*_streamEventsV2(e,t,n){let r=new Eu({...n,autoClose:!1}),i=jl(t),a=i.runId??Ln();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=jl(t),o=a.tags??[],s=a.metadata??{},c=a.runName??this.getName(),l=new yu({...n,autoClose:!1,_schemaFormat:`streaming_events`}),u=new Wu({...n}),d=this._streamLog(e,l,a);for await(let t of d){if(r=r?r.concat(t):mu.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 Uu(e)}withListeners({onStart:e,onEnd:t,onError:n}){return new Gb({bound:this,config:{},configFactories:[r=>({callbacks:[new Hu({config:r,onStart:e,onEnd:t,onError:n})]})]})}asTool(e){return ax(this,e)}},Gb=class e extends Wb{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=Al(this.config,...e);return Al(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 qb({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(jl(e),this.kwargs))):await this._mergeConfig(jl(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(jl(t),this.kwargs))}async stream(e,t){return this.bound.stream(e,await this._mergeConfig(jl(t),this.kwargs))}async*transform(e,t){yield*this.bound.transform(e,await this._mergeConfig(jl(t),this.kwargs))}streamEvents(e,t,n){let r=this;return Ll.fromAsyncGenerator(async function*(){yield*r.bound.streamEvents(e,{...await r._mergeConfig(jl(t),r.kwargs),version:t.version},n)}())}static isRunnableBinding(e){return e.bound&&Wb.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})]})]})}},Kb=class e extends Wb{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,Ml(t,{callbacks:n?.getChild()}))}withListeners({onStart:t,onEnd:n,onError:r}){return new e({bound:this.bound.withListeners({onStart:t,onEnd:n,onError:r})})}},qb=class extends Gb{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 Ml(t,{callbacks:n?.getChild(r)})}async _invoke(e,t,n){return Lu(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 Lu(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)}},Jb=class e extends Wb{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=jl(t),r=await(await kl(n))?.handleChainStart(this.toJSON(),Ub(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 Pl(e[t].invoke(i,Ml(n,{callbacks:r?.getChild(this.omitSequenceTags?void 0:`seq:step:${t+1}`)})),n.signal);if(n.signal?.aborted)throw Fl(n.signal);a=await this.last.invoke(i,Ml(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(Ub(a,`output`)),a}async batch(e,t,n){let r=this._getOptionsList(t??{},e.length),i=await Promise.all(r.map(kl)),a=await Promise.all(i.map(async(t,n)=>{let i=await t?.handleChainStart(this.toJSON(),Ub(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 Pl(this.steps[e].batch(o,a.map((t,n)=>{let i=t?.getChild(this.omitSequenceTags?void 0:`seq:step:${e+1}`);return Ml(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(Ub(o,`output`)))),o}_concatOutputChunks(e,t){return this.last._concatOutputChunks(e,t)}async*_streamIterator(e,t){let n=await kl(t),{runId:r,...i}=t??{},a=await n?.handleChainStart(this.toJSON(),Ub(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(),Ml(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,Ml(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(Ub(c,`output`))}getGraph(e){let t=new Mb,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:tx(t),name:this.name})}static isRunnableSequence(e){return Array.isArray(e.middle)&&Wb.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:tx(t),middle:n.slice(0,-1).map(tx),last:tx(n[n.length-1])})}},Yb=class e extends Wb{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]=tx(n)}static from(t){return new e({steps:t})}async invoke(e,t){let n=jl(t),r=await(await kl(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,Ml(n,{callbacks:r?.getChild(`map:key:${t}`)}))});await Pl(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=Rl(e,Object.keys(r).length),a=new Map(Object.entries(r).map(([e,r],a)=>{let o=r.transform(i[a],Ml(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 Pl(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=jl(t),i=new Bl({generator:this.transform(n(),r),config:r});return await i.setup,Ll.fromAsyncGenerator(i)}},Xb=class e extends Wb{lc_serializable=!1;lc_namespace=[`langchain_core`,`runnables`];func;constructor(e){if(super(e),!Gc(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 kl(n);return Pl(this.func(Ml(n,{callbacks:r}),e),n?.signal)}async*_streamIterator(e,t){let[n]=this._getOptionsList(t??{},1),r=await this.invoke(e,t);if(Rb(r)){for await(let e of r)n?.signal?.throwIfAborted(),yield e;return}if(Lb(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 Zb(e){if(Gc(e))throw Error(`RunnableLambda requires a function that is not wrapped in traceable higher-order function. This shouldn't happen.`)}var Qb=class e extends Wb{static lc_name(){return`RunnableLambda`}lc_namespace=[`langchain_core`,`runnables`];func;constructor(e){if(Gc(e.func))return Xb.from(e.func);super(e),Zb(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=Ml(t,{callbacks:n?.getChild(),recursionLimit:(t?.recursionLimit??25)-1});wl.runWithConfig(Nl(a),async()=>{try{let n=await this.func(e,{...a});if(n&&Wb.isRunnable(n)){if(t?.recursionLimit===0)throw Error(`Recursion limit reached.`);n=await n.invoke(e,{...a,recursionLimit:(a.recursionLimit??25)-1})}else if(Rb(n)){let e;for await(let r of Hb(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(Ib(n)){let e;for(let r of Vb(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=Ml(n,{callbacks:t?.getChild(),recursionLimit:(n?.recursionLimit??25)-1}),a=await new Promise((e,t)=>{wl.runWithConfig(Nl(i),async()=>{try{e(await this.func(r,{...i,config:i}))}catch(e){t(e)}})});if(a&&Wb.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(Rb(a))for await(let e of Hb(i,a))n?.signal?.throwIfAborted(),yield e;else if(Ib(a))for(let e of Vb(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=jl(t),i=new Bl({generator:this.transform(n(),r),config:r});return await i.setup,Ll.fromAsyncGenerator(i)}},$b=class extends Yb{},ex=class extends Wb{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=jl(t),r=await kl(n),{runId:i,...a}=n,o=await r?.handleChainStart(this.toJSON(),Ub(e,`input`),i,void 0,void 0,void 0,a?.runName),s=Ml(a,{callbacks:o?.getChild()});return await wl.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(Ub(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=jl(t),r=await kl(n),{runId:i,...a}=n,o=await r?.handleChainStart(this.toJSON(),Ub(e,`input`),i,void 0,void 0,void 0,a?.runName),s,c;for(let t of this.runnables()){n?.signal?.throwIfAborted();let r=Ml(a,{callbacks:o?.getChild()});try{c=Hb(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(Ub(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=>kl(e))),a=await Promise.all(i.map(async(t,n)=>{let i=await t?.handleChainStart(this.toJSON(),Ub(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)=>Ml(r[t],{callbacks:e?.getChild()})),n);return await Promise.all(a.map((e,t)=>e?.handleChainEnd(Ub(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 tx(e){if(typeof e==`function`)return new Qb({func:e});if(Wb.isRunnable(e))return e;if(!Array.isArray(e)&&typeof e==`object`){let t={};for(let[n,r]of Object.entries(e))t[n]=tx(r);return new Yb({steps:t})}else throw Error(`Expected a Runnable, function or object.
99
- Instead got an unsupported type.`)}var nx=class extends Wb{static lc_name(){return`RunnableAssign`}lc_namespace=[`langchain_core`,`runnables`];lc_serializable=!0;mapper;constructor(e){e instanceof Yb&&(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]=Rl(e),o=this.mapper.transform(a,Ml(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=jl(t),i=new Bl({generator:this.transform(n(),r),config:r});return await i.setup,Ll.fromAsyncGenerator(i)}},rx=class extends Wb{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=jl(t),i=new Bl({generator:this.transform(n(),r),config:r});return await i.setup,Ll.fromAsyncGenerator(i)}},ix=class extends Gb{name;description;schema;constructor(e){let t=Jb.from([Qb.from(async e=>{let t;if(h(e))try{t=await Dg(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 ax(e,t){let n=t.name??e.getName(),r=t.description??Ag(t.schema);return Mg(t.schema)?new ix({name:n,description:r,schema:Hv({input:Bv()}).transform(e=>e.input),bound:e}):new ix({name:n,description:r,schema:t.schema,bound:e})}var ox=class extends Wb{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=jl(t);return this.func&&await this.func(e,n),this._callWithConfig(e=>Promise.resolve(e),e,n)}async*transform(e,t){let n=jl(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=zl(r,t)}catch{r=void 0,i=!1}this.func&&r!==void 0&&await this.func(r,n)}static assign(e){return new nx(new Yb({steps:e}))}},sx=class extends Wb{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,jl(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)}},cx=class extends Wb{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])=>[tx(e),tx(t)]),n=tx(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,Ml(t,{callbacks:n?.getChild(`condition:${i+1}`)}))){r=await o.invoke(e,Ml(t,{callbacks:n?.getChild(`branch:${i+1}`)}));break}}return r||=await this.default.invoke(e,Ml(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 kl(t))?.handleChainStart(this.toJSON(),Ub(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,Ml(t,{callbacks:n?.getChild(`condition:${o+1}`)}))){a=await c.stream(e,Ml(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=zl(r,e)}catch{r=void 0,i=!1}break}}if(a===void 0){a=await this.default.stream(e,Ml(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=zl(r,e)}catch{r=void 0,i=!1}}}catch(e){throw await n?.handleChainError(e),e}await n?.handleChainEnd(r??{})}},lx=(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 ux(e,t){return Array.isArray(e)?dx(e,t):Qb.from(t=>dx(t,e))}function dx(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&&lx(t,a)||s&&t.id&&s.includes(t.id)||(i||o||n?(n&&t.name&&n.some(e=>e===t.name)||i&&lx(t,i)||o&&t.id&&o.some(e=>e===t.id))&&c.push(t):c.push(t));return c}function fx(e){return Array.isArray(e)?px(e):Qb.from(px)}function px(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=Dn(r),i=Dn(e),a=n.concat(i);typeof n.content==`string`&&typeof i.content==`string`&&(a.content=`${n.content}\n${i.content}`),t.push(bx(a))}}return t}function mx(e,t){if(Array.isArray(e)){let n=e;if(!t)throw Error(`Options parameter is required when providing messages.`);return hx(n,t)}else{let t=e;return Qb.from(e=>hx(e,t)).withConfig({runName:`trim_messages`})}}async function hx(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=xx;if(l&&(d=`splitText`in l?l.splitText:async e=>l(e)),i===`first`)return gx(e,{maxTokens:n,tokenCounter:u,textSplitter:d,partialStrategy:a?`first`:void 0,endOn:o});if(i===`last`)return _x(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 gx(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=yx(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&&!lx(s[c-1],e);)--c}return s.slice(0,c)}async function _x(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 yx(e.getType(),t,ht(e))});if(i){let e=Array.isArray(i)?i:[i];for(;s.length>0&&!lx(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 gx(l,{...o,partialStrategy:n?`last`:void 0,endOn:a}),c?[l[0],...l.slice(1).reverse()]:l.reverse()}var vx={human:{message:sn,messageChunk:cn},ai:{message:Jt,messageChunk:Zt},system:{message:fn,messageChunk:pn},developer:{message:fn,messageChunk:pn},tool:{message:vt,messageChunk:yt},function:{message:nn,messageChunk:rn},generic:{message:Qt,messageChunk:$t},remove:{message:dn,messageChunk:dn}};function yx(e,t,n){let r,i;switch(e){case`human`:n?r=new cn(t):i=new sn(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 Zt(e)}else i=new Jt(t);break;case`system`:n?r=new pn(t):i=new fn(t);break;case`developer`:n?r=new pn({...t,additional_kwargs:{...t.additional_kwargs,__openai_role__:`developer`}}):i=new fn({...t,additional_kwargs:{...t.additional_kwargs,__openai_role__:`developer`}});break;case`tool`:if(`tool_call_id`in t)n?r=new yt(t):i=new vt(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 rn(t);else{if(!t.name)throw Error(`FunctionMessage must have a 'name' field`);i=new nn(t)}break;case`generic`:if(`role`in t)n?r=new $t(t):i=new Qt(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 bx(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 vx&&(n=yx(t,r)),!n)throw Error(`Unrecognized message chunk class ${t}. Supported classes are ${Object.keys(vx)}`);return n}function xx(e){let t=e.split(`
100
- `);return Promise.resolve([...t.slice(0,-1).map(e=>`${e}\n`),t[t.length-1]])}var Sx=[`tool_call`,`tool_call_chunk`,`invalid_tool_call`,`server_tool_call`,`server_tool_call_chunk`,`server_tool_call_result`],Cx=[`image`,`video`,`audio`,`text-plain`,`file`],wx=[`text`,`reasoning`,...Sx,...Cx],Tx=o({AIMessage:()=>Jt,AIMessageChunk:()=>Zt,BaseMessage:()=>nt,BaseMessageChunk:()=>ft,ChatMessage:()=>Qt,ChatMessageChunk:()=>$t,DEFAULT_MERGE_IGNORE_KEYS:()=>it,FunctionMessage:()=>nn,FunctionMessageChunk:()=>rn,HumanMessage:()=>sn,HumanMessageChunk:()=>cn,KNOWN_BLOCK_TYPES:()=>wx,RemoveMessage:()=>dn,SystemMessage:()=>fn,SystemMessageChunk:()=>pn,ToolMessage:()=>vt,ToolMessageChunk:()=>yt,_isMessageFieldWithRole:()=>pt,_mergeDicts:()=>at,_mergeLists:()=>ut,_mergeObj:()=>dt,_mergeStatus:()=>et,coerceMessageLikeToMessage:()=>bn,collapseToolCallChunks:()=>On,convertToChunk:()=>Dn,convertToOpenAIImageBlock:()=>Ce,convertToProviderContentBlock:()=>Ee,defaultTextSplitter:()=>xx,defaultToolCallParser:()=>bt,filterMessages:()=>ux,getBufferString:()=>Sn,iife:()=>gn,isAIMessage:()=>Yt,isAIMessageChunk:()=>Xt,isBase64ContentBlock:()=>be,isBaseMessage:()=>mt,isBaseMessageChunk:()=>ht,isChatMessage:()=>en,isChatMessageChunk:()=>tn,isDataContentBlock:()=>ve,isDirectToolOutput:()=>_t,isFunctionMessage:()=>an,isFunctionMessageChunk:()=>on,isHumanMessage:()=>ln,isHumanMessageChunk:()=>un,isIDContentBlock:()=>Se,isMessage:()=>Je,isOpenAIToolCallArray:()=>rt,isPlainTextContentBlock:()=>xe,isSystemMessage:()=>mn,isSystemMessageChunk:()=>hn,isToolMessage:()=>xt,isToolMessageChunk:()=>St,isURLContentBlock:()=>ye,mapChatMessagesToStoredMessages:()=>En,mapStoredMessageToChatMessage:()=>wn,mapStoredMessagesToChatMessages:()=>Tn,mergeContent:()=>$e,mergeMessageRuns:()=>fx,mergeResponseMetadata:()=>Ut,mergeUsageMetadata:()=>qt,parseBase64DataUrl:()=>Te,parseMimeType:()=>we,trimMessages:()=>mx}),Ex=class extends Gb{runnable;inputMessagesKey;outputMessagesKey;historyMessagesKey;getMessageHistory;constructor(e){let t=Qb.from((e,t)=>this._enterHistory(e,t??{})).withConfig({runName:`loadHistory`}),n=e.historyMessagesKey??e.inputMessagesKey;n&&(t=ox.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)&&!mt(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 sn(t)];if(Array.isArray(t))return t;if(mt(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)&&!mt(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 Jt(t)];if(Array.isArray(t))return t;if(mt(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}},Dx=o({RouterRunnable:()=>sx,Runnable:()=>Wb,RunnableAssign:()=>nx,RunnableBinding:()=>Gb,RunnableBranch:()=>cx,RunnableEach:()=>Kb,RunnableLambda:()=>Qb,RunnableMap:()=>Yb,RunnableParallel:()=>$b,RunnablePassthrough:()=>ox,RunnablePick:()=>rx,RunnableRetry:()=>qb,RunnableSequence:()=>Jb,RunnableToolLike:()=>ix,RunnableWithFallbacks:()=>ex,RunnableWithMessageHistory:()=>Ex,_coerceToRunnable:()=>tx,ensureConfig:()=>jl,getCallbackManagerForConfig:()=>kl,mergeConfigs:()=>Al,patchConfig:()=>Ml,pickRunnableConfigKeys:()=>Nl,raceWithSignal:()=>Pl}),Ox=`__start__`,kx=`__end__`,Ax=`__input__`,jx=`__error__`,Mx=`__pregel_ns_writes`,Nx=`__pregel_send`,Px=`__pregel_call`,Fx=`__pregel_read`,Ix=`__pregel_checkpointer`,Lx=`__pregel_resuming`,Rx=`__pregel_task_id`,zx=`__pregel_stream`,Bx=`__pregel_resume_value`,Vx=`__pregel_resume_map`,Hx=`__pregel_scratchpad`,Ux=`__pregel_previous`,Wx=`__pregel_durability`,Gx=`checkpoint_id`,Kx=`checkpoint_ns`,qx=`__pregel_node_finished`,Jx=`checkpoint_map`,Yx=`__pregel_abort_signals`,Xx=`__interrupt__`,Zx=`__resume__`,Qx=`__no_writes__`,$x=`__return__`,eS=`__previous__`,tS=`langsmith:hidden`,nS=`__self__`,rS=`__pregel_tasks`,iS=`__pregel_push`,aS=`__pregel_pull`,oS=`00000000-0000-0000-0000-000000000000`,sS=[tS,Ax,Xx,Zx,jx,Qx,Nx,Fx,Ix,Wx,zx,Lx,Rx,Px,Bx,Hx,Ux,Jx,Kx,Gx],cS=Symbol.for(`langgraph.command`),lS=class{[cS];constructor(e){this[cS]=e}};function uS(e){let t=e;return t!=null&&typeof t.node==`string`&&t.args!==void 0}var dS=class{lg_name=`Send`;node;args;constructor(e,t){this.node=e,this.args=yS(t)}toJSON(){return{lg_name:this.lg_name,node:this.node,args:this.args}}};function fS(e){return e instanceof dS}var pS=`__overwrite__`;function mS(e){return typeof e==`object`&&e&&`__overwrite__`in e?[!0,e[pS]]:[!1,void 0]}function hS(e){return mS(e)[0]}function gS(e){return!e||typeof e!=`object`||!(`__interrupt__`in e)?!1:Array.isArray(e[Xx])}var _S=class extends lS{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)?yS(e.goto):[yS(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:fS(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 vS(e){return typeof e!=`object`||!e?!1:`lg_name`in e&&e.lg_name===`Command`}function yS(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]=yS(e,t)});else if(vS(e)&&!(e instanceof _S))n=new _S(e),t.set(e,n);else if(uS(e)&&!(e instanceof dS))n=new dS(e.node,e.args),t.set(e,n);else if(vS(e)||fS(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]=yS(i,t)}return n}return e}var bS=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}},xS=class extends bS{get is_bubble_up(){return!0}},SS=class extends bS{constructor(e,t){super(e,t),this.name=`GraphRecursionError`}static get unminifiable_name(){return`GraphRecursionError`}},CS=class extends bS{constructor(e,t){super(e,t),this.name=`GraphValueError`}static get unminifiable_name(){return`GraphValueError`}},wS=class extends xS{interrupts;constructor(e,t){super(JSON.stringify(e,null,2),t),this.name=`GraphInterrupt`,this.interrupts=e??[]}static get unminifiable_name(){return`GraphInterrupt`}},TS=class extends wS{constructor(e,t){super([{value:e}],t),this.name=`NodeInterrupt`}static get unminifiable_name(){return`NodeInterrupt`}},ES=class extends xS{command;constructor(e){super(),this.name=`ParentCommand`,this.command=e}static get unminifiable_name(){return`ParentCommand`}};function DS(e){return e!==void 0&&e.name===ES.unminifiable_name}function OS(e){return e!==void 0&&e.is_bubble_up===!0}function kS(e){return e!==void 0&&[wS.unminifiable_name,TS.unminifiable_name].includes(e.name)}var AS=class extends bS{constructor(e,t){super(e,t),this.name=`EmptyInputError`}static get unminifiable_name(){return`EmptyInputError`}},jS=class extends bS{constructor(e,t){super(e,t),this.name=`EmptyChannelError`}static get unminifiable_name(){return`EmptyChannelError`}},MS=class extends bS{constructor(e,t){super(e,t),this.name=`InvalidUpdateError`}static get unminifiable_name(){return`InvalidUpdateError`}},NS=class extends bS{constructor(e,t){super(e,t),this.name=`UnreachableNodeError`}static get unminifiable_name(){return`UnreachableNodeError`}},PS=class extends bS{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`}},FS=/^(?:[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 IS(e){return typeof e==`string`&&FS.test(e)}function LS(e){if(!IS(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 RS=[],zS=0;zS<256;++zS)RS.push((zS+256).toString(16).slice(1));function BS(e,t=0){return(RS[e[t+0]]+RS[e[t+1]]+RS[e[t+2]]+RS[e[t+3]]+`-`+RS[e[t+4]]+RS[e[t+5]]+`-`+RS[e[t+6]]+RS[e[t+7]]+`-`+RS[e[t+8]]+RS[e[t+9]]+`-`+RS[e[t+10]]+RS[e[t+11]]+RS[e[t+12]]+RS[e[t+13]]+RS[e[t+14]]+RS[e[t+15]]).toLowerCase()}var VS,HS=new Uint8Array(16);function US(){if(!VS&&(VS=typeof crypto<`u`&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!VS))throw Error(`crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported`);return VS(HS)}var WS,GS,KS=0,qS=0;function JS(e,t,n){var r=t&&n||0,i=t||Array(16);e||={};var a=e.node,o=e.clockseq;if(e._v6||(a||=WS,o??=GS),a==null||o==null){var s=e.random||(e.rng||US)();a??(a=[s[0],s[1],s[2],s[3],s[4],s[5]],!WS&&!e._v6&&(a[0]|=1,WS=a)),o??(o=(s[6]<<8|s[7])&16383,GS===void 0&&!e._v6&&(GS=o))}var c=e.msecs===void 0?Date.now():e.msecs,l=e.nsecs===void 0?qS+1:e.nsecs,u=c-KS+(l-qS)/1e4;if(u<0&&e.clockseq===void 0&&(o=o+1&16383),(u<0||c>KS)&&e.nsecs===void 0&&(l=0),l>=1e4)throw Error(`uuid.v1(): Can't create more than 10M uuids/sec`);KS=c,qS=l,GS=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||BS(i)}function YS(e){var t=XS(typeof e==`string`?LS(e):e);return typeof e==`string`?BS(t):t}function XS(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 ZS(e){e=unescape(encodeURIComponent(e));for(var t=[],n=0;n<e.length;++n)t.push(e.charCodeAt(n));return t}var QS=`6ba7b810-9dad-11d1-80b4-00c04fd430c8`,$S=`6ba7b811-9dad-11d1-80b4-00c04fd430c8`;function eC(e,t,n){function r(e,r,i,a){if(typeof e==`string`&&(e=ZS(e)),typeof r==`string`&&(r=LS(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 BS(o)}try{r.name=e}catch{}return r.DNS=QS,r.URL=$S,r}function tC(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 nC(e,t){return e<<t|e>>>32-t}function rC(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]=nC(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),te=nC(h,5)+tC(ee,g,_,v)+y+t[ee]+f[b]>>>0;y=v,v=_,_=nC(g,30)>>>0,g=h,h=te}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 iC=eC(`v5`,80,rC);function aC(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 oC(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?aC(Object(n),!0).forEach(function(t){sC(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):aC(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function sC(e,t,n){return(t=cC(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function cC(e){var t=lC(e,`string`);return typeof t==`symbol`?t:t+``}function lC(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 uC(e={},t,n=0){var r=JS(oC(oC({},e),{},{_v6:!0}),new Uint8Array(16));if(r=YS(r),t){for(var i=0;i<16;i++)t[n+i]=r[i];return t}return BS(r)}function dC(e){return uC({clockseq:e})}function fC(e,t){let n=t.replace(/-/g,``).match(/.{2}/g).map(e=>parseInt(e,16));return iC(e,new Uint8Array(n))}var pC=`__error__`,mC=`__scheduled__`,hC=`__interrupt__`,gC=`__resume__`,_C=`[...]`,vC=`[Circular]`,yC=[],bC=[];function xC(){return{depthLimit:2**53-1,edgesLimit:2**53-1}}function SC(e,t,n,r){r===void 0&&(r=xC()),wC(e,``,0,[],void 0,0,r);var i;try{i=bC.length===0?JSON.stringify(e,t,n):JSON.stringify(e,TC(t),n)}catch{return JSON.stringify(`[unable to serialize, circular reference is too complex to analyze]`)}finally{for(;yC.length!==0;){var a=yC.pop();a.length===4?Object.defineProperty(a[0],a[1],a[3]):a[0][a[1]]=a[2]}}return i}function CC(e,t,n,r){var i=Object.getOwnPropertyDescriptor(r,n);i.get===void 0?(r[n]=e,yC.push([r,n,t])):i.configurable?(Object.defineProperty(r,n,{value:e}),yC.push([r,n,t,i])):bC.push([t,n,e])}function wC(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){CC(vC,e,t,i);return}if(o.depthLimit!==void 0&&a>o.depthLimit){CC(_C,e,t,i);return}if(o.edgesLimit!==void 0&&n+1>o.edgesLimit){CC(_C,e,t,i);return}if(r.push(e),Array.isArray(e))for(s=0;s<e.length;s++)wC(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];wC(e[l],l,s,r,e,a,o)}}r.pop()}}function TC(e){return e=e===void 0?function(e,t){return t}:e,function(t,n){if(bC.length>0)for(var r=0;r<bC.length;r++){var i=bC[r];if(i[1]===t&&i[0]===n){n=i[2],bC.splice(r,1);break}}return e.call(this,t,n)}}var EC=[],DC=o({}),OC=o({}),R=`0123456789abcdef`.split(``),kC=[-2147483648,8388608,32768,128],AC=[24,16,8,0],jC=[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],MC=[];function NC(e,t){t?(MC[0]=MC[16]=MC[1]=MC[2]=MC[3]=MC[4]=MC[5]=MC[6]=MC[7]=MC[8]=MC[9]=MC[10]=MC[11]=MC[12]=MC[13]=MC[14]=MC[15]=0,this.blocks=MC):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}NC.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]<<AC[a++&3];else for(a=this.start;i<o&&a<64;++i)r=e.charCodeAt(i),r<128?s[a>>>2]|=r<<AC[a++&3]:r<2048?(s[a>>>2]|=(192|r>>>6)<<AC[a++&3],s[a>>>2]|=(128|r&63)<<AC[a++&3]):r<55296||r>=57344?(s[a>>>2]|=(224|r>>>12)<<AC[a++&3],s[a>>>2]|=(128|r>>>6&63)<<AC[a++&3],s[a>>>2]|=(128|r&63)<<AC[a++&3]):(r=65536+((r&1023)<<10|e.charCodeAt(++i)&1023),s[a>>>2]|=(240|r>>>18)<<AC[a++&3],s[a>>>2]|=(128|r>>>12&63)<<AC[a++&3],s[a>>>2]|=(128|r>>>6&63)<<AC[a++&3],s[a>>>2]|=(128|r&63)<<AC[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}},NC.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var e=this.blocks,t=this.lastByteIndex;e[16]=this.block,e[t>>>2]|=kC[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()}},NC.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+jC[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+jC[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+jC[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+jC[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},NC.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=R[e>>>28&15]+R[e>>>24&15]+R[e>>>20&15]+R[e>>>16&15]+R[e>>>12&15]+R[e>>>8&15]+R[e>>>4&15]+R[e&15]+R[t>>>28&15]+R[t>>>24&15]+R[t>>>20&15]+R[t>>>16&15]+R[t>>>12&15]+R[t>>>8&15]+R[t>>>4&15]+R[t&15]+R[n>>>28&15]+R[n>>>24&15]+R[n>>>20&15]+R[n>>>16&15]+R[n>>>12&15]+R[n>>>8&15]+R[n>>>4&15]+R[n&15]+R[r>>>28&15]+R[r>>>24&15]+R[r>>>20&15]+R[r>>>16&15]+R[r>>>12&15]+R[r>>>8&15]+R[r>>>4&15]+R[r&15]+R[i>>>28&15]+R[i>>>24&15]+R[i>>>20&15]+R[i>>>16&15]+R[i>>>12&15]+R[i>>>8&15]+R[i>>>4&15]+R[i&15]+R[a>>>28&15]+R[a>>>24&15]+R[a>>>20&15]+R[a>>>16&15]+R[a>>>12&15]+R[a>>>8&15]+R[a>>>4&15]+R[a&15]+R[o>>>28&15]+R[o>>>24&15]+R[o>>>20&15]+R[o>>>16&15]+R[o>>>12&15]+R[o>>>8&15]+R[o>>>4&15]+R[o&15];return this.is224||(c+=R[s>>>28&15]+R[s>>>24&15]+R[s>>>20&15]+R[s>>>16&15]+R[s>>>12&15]+R[s>>>8&15]+R[s>>>4&15]+R[s&15]),c},NC.prototype.toString=NC.prototype.hex,NC.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},NC.prototype.array=NC.prototype.digest,NC.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 PC=(...e)=>new NC(!1,!0).update(e.join(``)).hex(),FC=o({sha256:()=>PC}),IC=o({BaseCache:()=>BC,InMemoryCache:()=>HC,defaultHashKeyEncoder:()=>LC,deserializeStoredGeneration:()=>RC,serializeGeneration:()=>zC}),LC=(...e)=>PC(e.join(`_`));function RC(e){return e.message===void 0?{text:e.text}:{text:e.text,message:wn(e.message)}}function zC(e){let t={text:e.text};return e.message!==void 0&&(t.message=e.message.toDict()),t}var BC=class{keyEncoder=LC;makeDefaultKeyEncoder(e){this.keyEncoder=e}},VC=new Map,HC=class e extends BC{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(VC)}},UC=o({BaseChatMessageHistory:()=>WC,BaseListChatMessageHistory:()=>GC,InMemoryChatMessageHistory:()=>KC}),WC=class extends _e{async addMessages(e){for(let t of e)await this.addMessage(t)}},GC=class extends _e{addUserMessage(e){return this.addMessage(new sn(e))}addAIMessage(e){return this.addMessage(new Jt(e))}async addMessages(e){for(let t of e)await this.addMessage(t)}clear(){throw Error(`Not implemented.`)}},KC=class extends GC{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=[]}},qC=class{pageContent;metadata;id;constructor(e){this.pageContent=e.pageContent===void 0?``:e.pageContent.toString(),this.metadata=e.metadata??{},this.id=e.id}},JC=class extends Wb{lc_namespace=[`langchain_core`,`documents`,`transformers`];invoke(e,t){return this.transformDocuments(e)}},YC=class extends JC{async transformDocuments(e){let t=[];for(let n of e){let e=await this._transformDocument(n);t.push(e)}return t}},XC=o({BaseDocumentTransformer:()=>JC,Document:()=>qC,MappingDocumentTransformer:()=>YC}),ZC=o({BaseDocumentLoader:()=>QC}),QC=class{},$C=o({LangSmithLoader:()=>ew}),ew=class extends QC{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 $s(e?.clientConfig),this.contentKey=e.contentKey?e.contentKey.split(`.`):[],this.formatContent=e.formatContent??tw,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 tw(e){if(typeof e==`string`)return e;try{return JSON.stringify(e,null,2)}catch{return String(e)}}var nw=o({Embeddings:()=>rw}),rw=class{caller;constructor(e){this.caller=new Vu(e??{})}},iw=class extends _e{lc_namespace=[`langchain_core`,`example_selectors`,`base`]},aw=class{async getPromptAsync(e,t){return this.getPrompt(e).partial(t?.partialVariables??{})}},ow=class extends aw{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 sw(e){return e._modelType()===`base_llm`}function cw(e){return e._modelType()===`base_chat_model`}function lw(e){return e.split(/\n| /).length}var uw=class e extends iw{examples=[];examplePrompt;getTextLength=lw;maxLength=2048;exampleTextLengths=[];constructor(e){super(e),this.examplePrompt=e.examplePrompt,this.maxLength=e.maxLength??2048,this.getTextLength=e.getTextLength??lw}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 dw(e){return Object.keys(e).sort().map(t=>e[t])}var fw=class e extends iw{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=dw((this.inputKeys??Object.keys(e)).reduce((t,n)=>({...t,[n]:e[n]}),{})).join(` `);await this.vectorStoreRetriever.addDocuments([new qC({pageContent:t,metadata:e})])}async selectExamples(e){let t=dw((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=>dw(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})}},pw=o({BaseExampleSelector:()=>iw,BasePromptSelector:()=>aw,ConditionalPromptSelector:()=>ow,LengthBasedExampleSelector:()=>uw,SemanticSimilarityExampleSelector:()=>fw,isChatModel:()=>cw,isLLM:()=>sw}),mw=`10f90ea3-90a4-4962-bf75-83a0f3c1c62a`,hw=class extends _e{lc_namespace=[`langchain`,`recordmanagers`]},gw=class{uid;hash_;contentHash;metadataHash;pageContent;metadata;keyEncoder=PC;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 qC({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 nr(this.keyEncoder(e),mw)}_hashNestedDictToUUID(e){let t=JSON.stringify(e,Object.keys(e).sort());return nr(this.keyEncoder(t),mw)}};function _w(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 vw(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 yw(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 bw=e=>`load`in e&&typeof e.load==`function`&&`loadAndSplit`in e&&typeof e.loadAndSplit==`function`;async function xw(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=bw(t)?await t.load():t,d=yw(s??null),f=await n.getTime(),p=0,m=0,h=0,g=0,_=_w(a??100,u);for(let e of _){let t=vw(e.map(e=>gw.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 Sw=o({RecordManager:()=>hw,UUIDV5_NAMESPACE:()=>mw,_HashedDocument:()=>gw,_batch:()=>_w,_deduplicateInOrder:()=>vw,_getSourceIdAssigner:()=>yw,_isBaseDocumentLoader:()=>bw,index:()=>xw}),Cw=o({BasePromptValue:()=>ww,ChatPromptValue:()=>Ew,ImagePromptValue:()=>Dw,StringPromptValue:()=>Tw}),ww=class extends _e{},Tw=class extends ww{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 sn(this.value)]}},Ew=class extends ww{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 Sn(this.messages)}toChatMessages(){return this.messages}},Dw=class extends ww{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 sn({content:[{type:`image_url`,image_url:{detail:this.imageUrl.detail,url:this.imageUrl.url}}]})]}},Ow=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),kw=Object.defineProperty,Aw=(e,t,n)=>t in e?kw(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,jw=(e,t,n)=>(Aw(e,typeof t==`symbol`?t:t+``,n),n);function Mw(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 Nw(e,t){return e.length===1?[t.get(e.join(`,`))]:Mw(e,t).map(n=>t.get(e.slice(n.start,n.end).join(`,`))).filter(e=>e!=null)}function Pw(e){return e.replace(/[\\^$*+?.()|[\]{}]/g,`\\$&`)}var Fw=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(`
101
- `).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=Ow.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=Fw.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=Fw.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(...Nw(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)}},Iw=Fw;jw(Iw,`specialTokenRegex`,e=>new RegExp(e.map(e=>Pw(e)).join(`|`),`g`));function Lw(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 Rw=o({encodingForModel:()=>Hw,getEncoding:()=>Vw}),zw={},Bw=new Vu({});async function Vw(e){return e in zw||(zw[e]=Bw.fetch(`https://tiktoken.pages.dev/js/${e}.json`).then(e=>e.json()).then(e=>new Iw(e)).catch(t=>{throw delete zw[e],t})),await zw[e]}async function Hw(e){return Vw(Lw(e))}var Uw=o({BaseLangChain:()=>Xw,BaseLanguageModel:()=>Zw,calculateMaxTokens:()=>Jw,getEmbeddingContextSize:()=>Gw,getModelContextSize:()=>Kw,getModelNameForTiktoken:()=>Ww,isOpenAITool:()=>qw}),Ww=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,Gw=e=>{switch(e){case`text-embedding-ada-002`:return 8191;default:return 2046}},Kw=e=>{switch(Ww(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 qw(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 Jw=async({prompt:e,modelName:t})=>{let n;try{n=(await Hw(Ww(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 Kw(t)-n},Yw=()=>!1,Xw=class extends Wb{verbose;callbacks;tags;metadata;get lc_attributes(){return{callbacks:void 0,verbose:void 0}}constructor(e){super(e),this.verbose=e.verbose??Yw(),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}}}},Zw=class extends Xw{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=HC.global():this.cache=void 0,this.caller=new Vu(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 Hw(`modelName`in this?Ww(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 Tw(e):Array.isArray(e)?new Ew(e.map(bn)):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}},Qw=o({applyPatch:()=>au,compare:()=>du}),$w=class extends Wb{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`})}},eT=class extends $w{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`)}},tT=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`)}},nT=class extends eT{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`})}},rT=class extends nT{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(ht(r)){if(typeof r.content!=`string`)throw Error(`Cannot handle non-string message output.`);e=new Cu({message:r,text:r.content})}else if(mt(r)){if(typeof r.content!=`string`)throw Error(`Cannot handle non-string message output.`);e=new Cu({message:Dn(r),text:r.content})}else e=new Su({text:r});n=n===void 0?e:n.concat(e);let i=await this.parsePartialResult([n]);i!=null&&!Vy(i,t)&&(this.diff?yield this._diff(t,i):yield i,t=i)}}getFormatInstructions(){return``}},iT=class extends nT{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``}},aT=class extends nT{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]}},oT=class extends aT{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 tT(`Could not parse output: ${e}`,e)}}getFormatInstructions(){return"Your response should be a list of comma separated values, eg: `foo, bar, baz`"}},sT=class extends aT{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 tT(`Incorrect number of items. Expected ${this.length}, got ${t.length}.`);return t}catch(t){throw Object.getPrototypeOf(t)===tT.prototype?t:new tT(`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\`)`}},cT=class extends aT{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:
98
+ `)),n.close()}});return Ll.fromReadableStream(n)}function Fb(e){return typeof e==`object`&&!!e&&typeof e[Symbol.iterator]==`function`&&typeof e.next==`function`}var Ib=e=>typeof e==`object`&&!!e&&`next`in e&&typeof e.next==`function`;function Lb(e){return typeof e==`object`&&!!e&&typeof e[Symbol.asyncIterator]==`function`}function Rb(e){return typeof e==`object`&&!!e&&typeof e.next==`function`}async function zb(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*Bb(e,t){for(;;){let{value:n,done:r}=wl.runWithConfig(Nl(e),t.next.bind(t),!0);if(r)break;yield n}}async function*Vb(e,t){let n=t[Symbol.asyncIterator]();for(;;){let{value:r,done:i}=await wl.runWithConfig(Nl(e),n.next.bind(t),!0);if(i)break;yield r}}function Hb(e,t){return e&&!Array.isArray(e)&&!(e instanceof Date)&&typeof e==`object`?e:{[t]:e}}var Ub=class extends _e{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 Kb({bound:this,kwargs:{},config:{},maxAttemptNumber:e?.stopAfterAttempt,...e})}withConfig(e){return new Wb({bound:this,config:e,kwargs:{}})}withFallbacks(e){let t=Array.isArray(e)?e:e.fallbacks;return new $b({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(jl);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)=>jl(r===0?e:n))}return Array.from({length:t},()=>jl(e))}async batch(e,t,n){let r=this._getOptionsList(t??{},e.length),i=new Vu({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=jl(t),r=new Bl({generator:this._streamIterator(e,n),config:n});return await r.setup,Ll.fromAsyncGenerator(r)}_separateRunnableConfigFromCallOptions(e){let t;t=jl(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=jl(n),i=await(await kl(r))?.handleChainStart(this.toJSON(),Hb(t,`input`),r.runId,r?.runType,void 0,void 0,r?.runName??this.getName());delete r.runId;let a;try{a=await Pl(e.call(this,t,r,i),r.signal)}catch(e){throw await i?.handleChainError(e),e}return await i?.handleChainEnd(Hb(a,`output`)),a}async _batchWithConfig(e,t,n,r){let i=this._getOptionsList(n??{},t.length),a=await Promise.all(i.map(kl)),o=await Promise.all(a.map(async(e,n)=>{let r=await e?.handleChainStart(this.toJSON(),Hb(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 Pl(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(Hb(s,`output`)))),s}_concatOutputChunks(e,t){return zl(e,t)}async*_transformStreamWithConfig(e,t,n){let r,i=!0,a,o=!0,s=jl(n),c=await kl(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 Vl(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(Tu),r=e.output;n!==void 0&&d!==void 0&&(r=n.tapOutputIterable(d.runId,r));let i=d?.handlers.find(hu);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:Hb(r,`input`)}),e}await d?.handleChainEnd(a??{},void 0,void 0,void 0,{inputs:Hb(r,`input`)})}getGraph(e){let t=new jb,n=t.addNode({name:`${this.getName()}Input`,schema:Bv()}),r=t.addNode(this),i=t.addNode({name:`${this.getName()}Output`,schema:Bv()});return t.addEdge(n,r),t.addEdge(r,i),t}pipe(e){return new qb({first:this,last:ex(e)})}pick(e){return this.pipe(new nx(e))}assign(e){return this.pipe(new tx(new Jb({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,jl(t))}async*streamLog(e,t,n){let r=new yu({...n,autoClose:!1,_schemaFormat:`original`}),i=jl(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 pu({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`?Pb(r):Ll.fromAsyncGenerator(r)}async*_streamEventsV2(e,t,n){let r=new Eu({...n,autoClose:!1}),i=jl(t),a=i.runId??Ln();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=jl(t),o=a.tags??[],s=a.metadata??{},c=a.runName??this.getName(),l=new yu({...n,autoClose:!1,_schemaFormat:`streaming_events`}),u=new Wu({...n}),d=this._streamLog(e,l,a);for await(let t of d){if(r=r?r.concat(t):mu.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 Uu(e)}withListeners({onStart:e,onEnd:t,onError:n}){return new Wb({bound:this,config:{},configFactories:[r=>({callbacks:[new Hu({config:r,onStart:e,onEnd:t,onError:n})]})]})}asTool(e){return ix(this,e)}},Wb=class e extends Ub{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=Al(this.config,...e);return Al(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 Kb({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(jl(e),this.kwargs))):await this._mergeConfig(jl(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(jl(t),this.kwargs))}async stream(e,t){return this.bound.stream(e,await this._mergeConfig(jl(t),this.kwargs))}async*transform(e,t){yield*this.bound.transform(e,await this._mergeConfig(jl(t),this.kwargs))}streamEvents(e,t,n){let r=this;return Ll.fromAsyncGenerator(async function*(){yield*r.bound.streamEvents(e,{...await r._mergeConfig(jl(t),r.kwargs),version:t.version},n)}())}static isRunnableBinding(e){return e.bound&&Ub.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})]})]})}},Gb=class e extends Ub{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,Ml(t,{callbacks:n?.getChild()}))}withListeners({onStart:t,onEnd:n,onError:r}){return new e({bound:this.bound.withListeners({onStart:t,onEnd:n,onError:r})})}},Kb=class extends Wb{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 Ml(t,{callbacks:n?.getChild(r)})}async _invoke(e,t,n){return Lu(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 Lu(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)}},qb=class e extends Ub{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=jl(t),r=await(await kl(n))?.handleChainStart(this.toJSON(),Hb(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 Pl(e[t].invoke(i,Ml(n,{callbacks:r?.getChild(this.omitSequenceTags?void 0:`seq:step:${t+1}`)})),n.signal);if(n.signal?.aborted)throw Fl(n.signal);a=await this.last.invoke(i,Ml(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(Hb(a,`output`)),a}async batch(e,t,n){let r=this._getOptionsList(t??{},e.length),i=await Promise.all(r.map(kl)),a=await Promise.all(i.map(async(t,n)=>{let i=await t?.handleChainStart(this.toJSON(),Hb(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 Pl(this.steps[e].batch(o,a.map((t,n)=>{let i=t?.getChild(this.omitSequenceTags?void 0:`seq:step:${e+1}`);return Ml(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(Hb(o,`output`)))),o}_concatOutputChunks(e,t){return this.last._concatOutputChunks(e,t)}async*_streamIterator(e,t){let n=await kl(t),{runId:r,...i}=t??{},a=await n?.handleChainStart(this.toJSON(),Hb(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(),Ml(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,Ml(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(Hb(c,`output`))}getGraph(e){let t=new jb,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:ex(t),name:this.name})}static isRunnableSequence(e){return Array.isArray(e.middle)&&Ub.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:ex(t),middle:n.slice(0,-1).map(ex),last:ex(n[n.length-1])})}},Jb=class e extends Ub{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]=ex(n)}static from(t){return new e({steps:t})}async invoke(e,t){let n=jl(t),r=await(await kl(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,Ml(n,{callbacks:r?.getChild(`map:key:${t}`)}))});await Pl(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=Rl(e,Object.keys(r).length),a=new Map(Object.entries(r).map(([e,r],a)=>{let o=r.transform(i[a],Ml(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 Pl(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=jl(t),i=new Bl({generator:this.transform(n(),r),config:r});return await i.setup,Ll.fromAsyncGenerator(i)}},Yb=class e extends Ub{lc_serializable=!1;lc_namespace=[`langchain_core`,`runnables`];func;constructor(e){if(super(e),!Gc(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 kl(n);return Pl(this.func(Ml(n,{callbacks:r}),e),n?.signal)}async*_streamIterator(e,t){let[n]=this._getOptionsList(t??{},1),r=await this.invoke(e,t);if(Lb(r)){for await(let e of r)n?.signal?.throwIfAborted(),yield e;return}if(Ib(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 Xb(e){if(Gc(e))throw Error(`RunnableLambda requires a function that is not wrapped in traceable higher-order function. This shouldn't happen.`)}var Zb=class e extends Ub{static lc_name(){return`RunnableLambda`}lc_namespace=[`langchain_core`,`runnables`];func;constructor(e){if(Gc(e.func))return Yb.from(e.func);super(e),Xb(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=Ml(t,{callbacks:n?.getChild(),recursionLimit:(t?.recursionLimit??25)-1});wl.runWithConfig(Nl(a),async()=>{try{let n=await this.func(e,{...a});if(n&&Ub.isRunnable(n)){if(t?.recursionLimit===0)throw Error(`Recursion limit reached.`);n=await n.invoke(e,{...a,recursionLimit:(a.recursionLimit??25)-1})}else if(Lb(n)){let e;for await(let r of Vb(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(Fb(n)){let e;for(let r of Bb(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=Ml(n,{callbacks:t?.getChild(),recursionLimit:(n?.recursionLimit??25)-1}),a=await new Promise((e,t)=>{wl.runWithConfig(Nl(i),async()=>{try{e(await this.func(r,{...i,config:i}))}catch(e){t(e)}})});if(a&&Ub.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(Lb(a))for await(let e of Vb(i,a))n?.signal?.throwIfAborted(),yield e;else if(Fb(a))for(let e of Bb(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=jl(t),i=new Bl({generator:this.transform(n(),r),config:r});return await i.setup,Ll.fromAsyncGenerator(i)}},Qb=class extends Jb{},$b=class extends Ub{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=jl(t),r=await kl(n),{runId:i,...a}=n,o=await r?.handleChainStart(this.toJSON(),Hb(e,`input`),i,void 0,void 0,void 0,a?.runName),s=Ml(a,{callbacks:o?.getChild()});return await wl.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(Hb(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=jl(t),r=await kl(n),{runId:i,...a}=n,o=await r?.handleChainStart(this.toJSON(),Hb(e,`input`),i,void 0,void 0,void 0,a?.runName),s,c;for(let t of this.runnables()){n?.signal?.throwIfAborted();let r=Ml(a,{callbacks:o?.getChild()});try{c=Vb(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(Hb(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=>kl(e))),a=await Promise.all(i.map(async(t,n)=>{let i=await t?.handleChainStart(this.toJSON(),Hb(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)=>Ml(r[t],{callbacks:e?.getChild()})),n);return await Promise.all(a.map((e,t)=>e?.handleChainEnd(Hb(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 ex(e){if(typeof e==`function`)return new Zb({func:e});if(Ub.isRunnable(e))return e;if(!Array.isArray(e)&&typeof e==`object`){let t={};for(let[n,r]of Object.entries(e))t[n]=ex(r);return new Jb({steps:t})}else throw Error(`Expected a Runnable, function or object.
99
+ Instead got an unsupported type.`)}var tx=class extends Ub{static lc_name(){return`RunnableAssign`}lc_namespace=[`langchain_core`,`runnables`];lc_serializable=!0;mapper;constructor(e){e instanceof Jb&&(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]=Rl(e),o=this.mapper.transform(a,Ml(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=jl(t),i=new Bl({generator:this.transform(n(),r),config:r});return await i.setup,Ll.fromAsyncGenerator(i)}},nx=class extends Ub{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=jl(t),i=new Bl({generator:this.transform(n(),r),config:r});return await i.setup,Ll.fromAsyncGenerator(i)}},rx=class extends Wb{name;description;schema;constructor(e){let t=qb.from([Zb.from(async e=>{let t;if(h(e))try{t=await Dg(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 ix(e,t){let n=t.name??e.getName(),r=t.description??Ag(t.schema);return Mg(t.schema)?new rx({name:n,description:r,schema:Vv({input:zv()}).transform(e=>e.input),bound:e}):new rx({name:n,description:r,schema:t.schema,bound:e})}var ax=class extends Ub{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=jl(t);return this.func&&await this.func(e,n),this._callWithConfig(e=>Promise.resolve(e),e,n)}async*transform(e,t){let n=jl(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=zl(r,t)}catch{r=void 0,i=!1}this.func&&r!==void 0&&await this.func(r,n)}static assign(e){return new tx(new Jb({steps:e}))}},ox=class extends Ub{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,jl(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)}},sx=class extends Ub{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])=>[ex(e),ex(t)]),n=ex(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,Ml(t,{callbacks:n?.getChild(`condition:${i+1}`)}))){r=await o.invoke(e,Ml(t,{callbacks:n?.getChild(`branch:${i+1}`)}));break}}return r||=await this.default.invoke(e,Ml(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 kl(t))?.handleChainStart(this.toJSON(),Hb(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,Ml(t,{callbacks:n?.getChild(`condition:${o+1}`)}))){a=await c.stream(e,Ml(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=zl(r,e)}catch{r=void 0,i=!1}break}}if(a===void 0){a=await this.default.stream(e,Ml(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=zl(r,e)}catch{r=void 0,i=!1}}}catch(e){throw await n?.handleChainError(e),e}await n?.handleChainEnd(r??{})}},cx=(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 lx(e,t){return Array.isArray(e)?ux(e,t):Zb.from(t=>ux(t,e))}function ux(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&&cx(t,a)||s&&t.id&&s.includes(t.id)||(i||o||n?(n&&t.name&&n.some(e=>e===t.name)||i&&cx(t,i)||o&&t.id&&o.some(e=>e===t.id))&&c.push(t):c.push(t));return c}function dx(e){return Array.isArray(e)?fx(e):Zb.from(fx)}function fx(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=Dn(r),i=Dn(e),a=n.concat(i);typeof n.content==`string`&&typeof i.content==`string`&&(a.content=`${n.content}\n${i.content}`),t.push(yx(a))}}return t}function px(e,t){if(Array.isArray(e)){let n=e;if(!t)throw Error(`Options parameter is required when providing messages.`);return mx(n,t)}else{let t=e;return Zb.from(e=>mx(e,t)).withConfig({runName:`trim_messages`})}}async function mx(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=bx;if(l&&(d=`splitText`in l?l.splitText:async e=>l(e)),i===`first`)return hx(e,{maxTokens:n,tokenCounter:u,textSplitter:d,partialStrategy:a?`first`:void 0,endOn:o});if(i===`last`)return gx(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 hx(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=vx(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&&!cx(s[c-1],e);)--c}return s.slice(0,c)}async function gx(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 vx(e.getType(),t,ht(e))});if(i){let e=Array.isArray(i)?i:[i];for(;s.length>0&&!cx(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 hx(l,{...o,partialStrategy:n?`last`:void 0,endOn:a}),c?[l[0],...l.slice(1).reverse()]:l.reverse()}var _x={human:{message:sn,messageChunk:cn},ai:{message:Jt,messageChunk:Zt},system:{message:fn,messageChunk:pn},developer:{message:fn,messageChunk:pn},tool:{message:vt,messageChunk:yt},function:{message:nn,messageChunk:rn},generic:{message:Qt,messageChunk:$t},remove:{message:dn,messageChunk:dn}};function vx(e,t,n){let r,i;switch(e){case`human`:n?r=new cn(t):i=new sn(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 Zt(e)}else i=new Jt(t);break;case`system`:n?r=new pn(t):i=new fn(t);break;case`developer`:n?r=new pn({...t,additional_kwargs:{...t.additional_kwargs,__openai_role__:`developer`}}):i=new fn({...t,additional_kwargs:{...t.additional_kwargs,__openai_role__:`developer`}});break;case`tool`:if(`tool_call_id`in t)n?r=new yt(t):i=new vt(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 rn(t);else{if(!t.name)throw Error(`FunctionMessage must have a 'name' field`);i=new nn(t)}break;case`generic`:if(`role`in t)n?r=new $t(t):i=new Qt(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 yx(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 _x&&(n=vx(t,r)),!n)throw Error(`Unrecognized message chunk class ${t}. Supported classes are ${Object.keys(_x)}`);return n}function bx(e){let t=e.split(`
100
+ `);return Promise.resolve([...t.slice(0,-1).map(e=>`${e}\n`),t[t.length-1]])}var xx=[`tool_call`,`tool_call_chunk`,`invalid_tool_call`,`server_tool_call`,`server_tool_call_chunk`,`server_tool_call_result`],Sx=[`image`,`video`,`audio`,`text-plain`,`file`],Cx=[`text`,`reasoning`,...xx,...Sx],wx=o({AIMessage:()=>Jt,AIMessageChunk:()=>Zt,BaseMessage:()=>nt,BaseMessageChunk:()=>ft,ChatMessage:()=>Qt,ChatMessageChunk:()=>$t,DEFAULT_MERGE_IGNORE_KEYS:()=>it,FunctionMessage:()=>nn,FunctionMessageChunk:()=>rn,HumanMessage:()=>sn,HumanMessageChunk:()=>cn,KNOWN_BLOCK_TYPES:()=>Cx,RemoveMessage:()=>dn,SystemMessage:()=>fn,SystemMessageChunk:()=>pn,ToolMessage:()=>vt,ToolMessageChunk:()=>yt,_isMessageFieldWithRole:()=>pt,_mergeDicts:()=>at,_mergeLists:()=>ut,_mergeObj:()=>dt,_mergeStatus:()=>et,coerceMessageLikeToMessage:()=>bn,collapseToolCallChunks:()=>On,convertToChunk:()=>Dn,convertToOpenAIImageBlock:()=>Ce,convertToProviderContentBlock:()=>Ee,defaultTextSplitter:()=>bx,defaultToolCallParser:()=>bt,filterMessages:()=>lx,getBufferString:()=>Sn,iife:()=>gn,isAIMessage:()=>Yt,isAIMessageChunk:()=>Xt,isBase64ContentBlock:()=>be,isBaseMessage:()=>mt,isBaseMessageChunk:()=>ht,isChatMessage:()=>en,isChatMessageChunk:()=>tn,isDataContentBlock:()=>ve,isDirectToolOutput:()=>_t,isFunctionMessage:()=>an,isFunctionMessageChunk:()=>on,isHumanMessage:()=>ln,isHumanMessageChunk:()=>un,isIDContentBlock:()=>Se,isMessage:()=>Je,isOpenAIToolCallArray:()=>rt,isPlainTextContentBlock:()=>xe,isSystemMessage:()=>mn,isSystemMessageChunk:()=>hn,isToolMessage:()=>xt,isToolMessageChunk:()=>St,isURLContentBlock:()=>ye,mapChatMessagesToStoredMessages:()=>En,mapStoredMessageToChatMessage:()=>wn,mapStoredMessagesToChatMessages:()=>Tn,mergeContent:()=>$e,mergeMessageRuns:()=>dx,mergeResponseMetadata:()=>Ut,mergeUsageMetadata:()=>qt,parseBase64DataUrl:()=>Te,parseMimeType:()=>we,trimMessages:()=>px}),Tx=class extends Wb{runnable;inputMessagesKey;outputMessagesKey;historyMessagesKey;getMessageHistory;constructor(e){let t=Zb.from((e,t)=>this._enterHistory(e,t??{})).withConfig({runName:`loadHistory`}),n=e.historyMessagesKey??e.inputMessagesKey;n&&(t=ax.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)&&!mt(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 sn(t)];if(Array.isArray(t))return t;if(mt(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)&&!mt(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 Jt(t)];if(Array.isArray(t))return t;if(mt(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}},Ex=o({RouterRunnable:()=>ox,Runnable:()=>Ub,RunnableAssign:()=>tx,RunnableBinding:()=>Wb,RunnableBranch:()=>sx,RunnableEach:()=>Gb,RunnableLambda:()=>Zb,RunnableMap:()=>Jb,RunnableParallel:()=>Qb,RunnablePassthrough:()=>ax,RunnablePick:()=>nx,RunnableRetry:()=>Kb,RunnableSequence:()=>qb,RunnableToolLike:()=>rx,RunnableWithFallbacks:()=>$b,RunnableWithMessageHistory:()=>Tx,_coerceToRunnable:()=>ex,ensureConfig:()=>jl,getCallbackManagerForConfig:()=>kl,mergeConfigs:()=>Al,patchConfig:()=>Ml,pickRunnableConfigKeys:()=>Nl,raceWithSignal:()=>Pl}),Dx=`__start__`,Ox=`__end__`,kx=`__input__`,Ax=`__error__`,jx=`__pregel_ns_writes`,Mx=`__pregel_send`,Nx=`__pregel_call`,Px=`__pregel_read`,Fx=`__pregel_checkpointer`,Ix=`__pregel_resuming`,Lx=`__pregel_task_id`,Rx=`__pregel_stream`,zx=`__pregel_resume_value`,Bx=`__pregel_resume_map`,Vx=`__pregel_scratchpad`,Hx=`__pregel_previous`,Ux=`__pregel_durability`,Wx=`checkpoint_id`,Gx=`checkpoint_ns`,Kx=`__pregel_node_finished`,qx=`checkpoint_map`,Jx=`__pregel_abort_signals`,Yx=`__interrupt__`,Xx=`__resume__`,Zx=`__no_writes__`,Qx=`__return__`,$x=`__previous__`,eS=`langsmith:hidden`,tS=`__self__`,nS=`__pregel_tasks`,rS=`__pregel_push`,iS=`__pregel_pull`,aS=`00000000-0000-0000-0000-000000000000`,oS=[eS,kx,Yx,Xx,Ax,Zx,Mx,Px,Fx,Ux,Rx,Ix,Lx,Nx,zx,Vx,Hx,qx,Gx,Wx],sS=Symbol.for(`langgraph.command`),cS=class{[sS];constructor(e){this[sS]=e}};function lS(e){let t=e;return t!=null&&typeof t.node==`string`&&t.args!==void 0}var uS=class{lg_name=`Send`;node;args;constructor(e,t){this.node=e,this.args=vS(t)}toJSON(){return{lg_name:this.lg_name,node:this.node,args:this.args}}};function dS(e){return e instanceof uS}var fS=`__overwrite__`;function pS(e){return typeof e==`object`&&e&&`__overwrite__`in e?[!0,e[fS]]:[!1,void 0]}function mS(e){return pS(e)[0]}function hS(e){return!e||typeof e!=`object`||!(`__interrupt__`in e)?!1:Array.isArray(e[Yx])}var gS=class extends cS{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)?vS(e.goto):[vS(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:dS(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 _S(e){return typeof e!=`object`||!e?!1:`lg_name`in e&&e.lg_name===`Command`}function vS(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]=vS(e,t)});else if(_S(e)&&!(e instanceof gS))n=new gS(e),t.set(e,n);else if(lS(e)&&!(e instanceof uS))n=new uS(e.node,e.args),t.set(e,n);else if(_S(e)||dS(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]=vS(i,t)}return n}return e}var yS=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}},bS=class extends yS{get is_bubble_up(){return!0}},xS=class extends yS{constructor(e,t){super(e,t),this.name=`GraphRecursionError`}static get unminifiable_name(){return`GraphRecursionError`}},SS=class extends yS{constructor(e,t){super(e,t),this.name=`GraphValueError`}static get unminifiable_name(){return`GraphValueError`}},CS=class extends bS{interrupts;constructor(e,t){super(JSON.stringify(e,null,2),t),this.name=`GraphInterrupt`,this.interrupts=e??[]}static get unminifiable_name(){return`GraphInterrupt`}},wS=class extends CS{constructor(e,t){super([{value:e}],t),this.name=`NodeInterrupt`}static get unminifiable_name(){return`NodeInterrupt`}},TS=class extends bS{command;constructor(e){super(),this.name=`ParentCommand`,this.command=e}static get unminifiable_name(){return`ParentCommand`}};function ES(e){return e!==void 0&&e.name===TS.unminifiable_name}function DS(e){return e!==void 0&&e.is_bubble_up===!0}function OS(e){return e!==void 0&&[CS.unminifiable_name,wS.unminifiable_name].includes(e.name)}var kS=class extends yS{constructor(e,t){super(e,t),this.name=`EmptyInputError`}static get unminifiable_name(){return`EmptyInputError`}},AS=class extends yS{constructor(e,t){super(e,t),this.name=`EmptyChannelError`}static get unminifiable_name(){return`EmptyChannelError`}},jS=class extends yS{constructor(e,t){super(e,t),this.name=`InvalidUpdateError`}static get unminifiable_name(){return`InvalidUpdateError`}},MS=class extends yS{constructor(e,t){super(e,t),this.name=`UnreachableNodeError`}static get unminifiable_name(){return`UnreachableNodeError`}},NS=class extends yS{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`}},PS=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;function FS(e){return typeof e==`string`&&PS.test(e)}function IS(e){if(!FS(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 LS=[],RS=0;RS<256;++RS)LS.push((RS+256).toString(16).slice(1));function zS(e,t=0){return(LS[e[t+0]]+LS[e[t+1]]+LS[e[t+2]]+LS[e[t+3]]+`-`+LS[e[t+4]]+LS[e[t+5]]+`-`+LS[e[t+6]]+LS[e[t+7]]+`-`+LS[e[t+8]]+LS[e[t+9]]+`-`+LS[e[t+10]]+LS[e[t+11]]+LS[e[t+12]]+LS[e[t+13]]+LS[e[t+14]]+LS[e[t+15]]).toLowerCase()}var BS,VS=new Uint8Array(16);function HS(){if(!BS&&(BS=typeof crypto<`u`&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!BS))throw Error(`crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported`);return BS(VS)}var US,WS,GS=0,KS=0;function qS(e,t,n){var r=t&&n||0,i=t||Array(16);e||={};var a=e.node,o=e.clockseq;if(e._v6||(a||=US,o??=WS),a==null||o==null){var s=e.random||(e.rng||HS)();a??(a=[s[0],s[1],s[2],s[3],s[4],s[5]],!US&&!e._v6&&(a[0]|=1,US=a)),o??(o=(s[6]<<8|s[7])&16383,WS===void 0&&!e._v6&&(WS=o))}var c=e.msecs===void 0?Date.now():e.msecs,l=e.nsecs===void 0?KS+1:e.nsecs,u=c-GS+(l-KS)/1e4;if(u<0&&e.clockseq===void 0&&(o=o+1&16383),(u<0||c>GS)&&e.nsecs===void 0&&(l=0),l>=1e4)throw Error(`uuid.v1(): Can't create more than 10M uuids/sec`);GS=c,KS=l,WS=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||zS(i)}function JS(e){var t=YS(typeof e==`string`?IS(e):e);return typeof e==`string`?zS(t):t}function YS(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 XS(e){e=unescape(encodeURIComponent(e));for(var t=[],n=0;n<e.length;++n)t.push(e.charCodeAt(n));return t}var ZS=`6ba7b810-9dad-11d1-80b4-00c04fd430c8`,QS=`6ba7b811-9dad-11d1-80b4-00c04fd430c8`;function $S(e,t,n){function r(e,r,i,a){if(typeof e==`string`&&(e=XS(e)),typeof r==`string`&&(r=IS(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 zS(o)}try{r.name=e}catch{}return r.DNS=ZS,r.URL=QS,r}function eC(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 tC(e,t){return e<<t|e>>>32-t}function nC(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]=tC(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),te=tC(h,5)+eC(ee,g,_,v)+y+t[ee]+f[b]>>>0;y=v,v=_,_=tC(g,30)>>>0,g=h,h=te}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 rC=$S(`v5`,80,nC);function iC(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 aC(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?iC(Object(n),!0).forEach(function(t){oC(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):iC(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function oC(e,t,n){return(t=sC(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function sC(e){var t=cC(e,`string`);return typeof t==`symbol`?t:t+``}function cC(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 lC(e={},t,n=0){var r=qS(aC(aC({},e),{},{_v6:!0}),new Uint8Array(16));if(r=JS(r),t){for(var i=0;i<16;i++)t[n+i]=r[i];return t}return zS(r)}function uC(e){return lC({clockseq:e})}function dC(e,t){let n=t.replace(/-/g,``).match(/.{2}/g).map(e=>parseInt(e,16));return rC(e,new Uint8Array(n))}var fC=`__error__`,pC=`__scheduled__`,mC=`__interrupt__`,hC=`__resume__`,gC=`[...]`,_C=`[Circular]`,vC=[],yC=[];function bC(){return{depthLimit:2**53-1,edgesLimit:2**53-1}}function xC(e,t,n,r){r===void 0&&(r=bC()),CC(e,``,0,[],void 0,0,r);var i;try{i=yC.length===0?JSON.stringify(e,t,n):JSON.stringify(e,wC(t),n)}catch{return JSON.stringify(`[unable to serialize, circular reference is too complex to analyze]`)}finally{for(;vC.length!==0;){var a=vC.pop();a.length===4?Object.defineProperty(a[0],a[1],a[3]):a[0][a[1]]=a[2]}}return i}function SC(e,t,n,r){var i=Object.getOwnPropertyDescriptor(r,n);i.get===void 0?(r[n]=e,vC.push([r,n,t])):i.configurable?(Object.defineProperty(r,n,{value:e}),vC.push([r,n,t,i])):yC.push([t,n,e])}function CC(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){SC(_C,e,t,i);return}if(o.depthLimit!==void 0&&a>o.depthLimit){SC(gC,e,t,i);return}if(o.edgesLimit!==void 0&&n+1>o.edgesLimit){SC(gC,e,t,i);return}if(r.push(e),Array.isArray(e))for(s=0;s<e.length;s++)CC(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];CC(e[l],l,s,r,e,a,o)}}r.pop()}}function wC(e){return e=e===void 0?function(e,t){return t}:e,function(t,n){if(yC.length>0)for(var r=0;r<yC.length;r++){var i=yC[r];if(i[1]===t&&i[0]===n){n=i[2],yC.splice(r,1);break}}return e.call(this,t,n)}}var TC=[],EC=o({}),DC=o({}),z=`0123456789abcdef`.split(``),OC=[-2147483648,8388608,32768,128],kC=[24,16,8,0],AC=[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],jC=[];function MC(e,t){t?(jC[0]=jC[16]=jC[1]=jC[2]=jC[3]=jC[4]=jC[5]=jC[6]=jC[7]=jC[8]=jC[9]=jC[10]=jC[11]=jC[12]=jC[13]=jC[14]=jC[15]=0,this.blocks=jC):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}MC.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]<<kC[a++&3];else for(a=this.start;i<o&&a<64;++i)r=e.charCodeAt(i),r<128?s[a>>>2]|=r<<kC[a++&3]:r<2048?(s[a>>>2]|=(192|r>>>6)<<kC[a++&3],s[a>>>2]|=(128|r&63)<<kC[a++&3]):r<55296||r>=57344?(s[a>>>2]|=(224|r>>>12)<<kC[a++&3],s[a>>>2]|=(128|r>>>6&63)<<kC[a++&3],s[a>>>2]|=(128|r&63)<<kC[a++&3]):(r=65536+((r&1023)<<10|e.charCodeAt(++i)&1023),s[a>>>2]|=(240|r>>>18)<<kC[a++&3],s[a>>>2]|=(128|r>>>12&63)<<kC[a++&3],s[a>>>2]|=(128|r>>>6&63)<<kC[a++&3],s[a>>>2]|=(128|r&63)<<kC[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}},MC.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var e=this.blocks,t=this.lastByteIndex;e[16]=this.block,e[t>>>2]|=OC[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()}},MC.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+AC[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+AC[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+AC[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+AC[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},MC.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=z[e>>>28&15]+z[e>>>24&15]+z[e>>>20&15]+z[e>>>16&15]+z[e>>>12&15]+z[e>>>8&15]+z[e>>>4&15]+z[e&15]+z[t>>>28&15]+z[t>>>24&15]+z[t>>>20&15]+z[t>>>16&15]+z[t>>>12&15]+z[t>>>8&15]+z[t>>>4&15]+z[t&15]+z[n>>>28&15]+z[n>>>24&15]+z[n>>>20&15]+z[n>>>16&15]+z[n>>>12&15]+z[n>>>8&15]+z[n>>>4&15]+z[n&15]+z[r>>>28&15]+z[r>>>24&15]+z[r>>>20&15]+z[r>>>16&15]+z[r>>>12&15]+z[r>>>8&15]+z[r>>>4&15]+z[r&15]+z[i>>>28&15]+z[i>>>24&15]+z[i>>>20&15]+z[i>>>16&15]+z[i>>>12&15]+z[i>>>8&15]+z[i>>>4&15]+z[i&15]+z[a>>>28&15]+z[a>>>24&15]+z[a>>>20&15]+z[a>>>16&15]+z[a>>>12&15]+z[a>>>8&15]+z[a>>>4&15]+z[a&15]+z[o>>>28&15]+z[o>>>24&15]+z[o>>>20&15]+z[o>>>16&15]+z[o>>>12&15]+z[o>>>8&15]+z[o>>>4&15]+z[o&15];return this.is224||(c+=z[s>>>28&15]+z[s>>>24&15]+z[s>>>20&15]+z[s>>>16&15]+z[s>>>12&15]+z[s>>>8&15]+z[s>>>4&15]+z[s&15]),c},MC.prototype.toString=MC.prototype.hex,MC.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},MC.prototype.array=MC.prototype.digest,MC.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 NC=(...e)=>new MC(!1,!0).update(e.join(``)).hex(),PC=o({sha256:()=>NC}),FC=o({BaseCache:()=>zC,InMemoryCache:()=>VC,defaultHashKeyEncoder:()=>IC,deserializeStoredGeneration:()=>LC,serializeGeneration:()=>RC}),IC=(...e)=>NC(e.join(`_`));function LC(e){return e.message===void 0?{text:e.text}:{text:e.text,message:wn(e.message)}}function RC(e){let t={text:e.text};return e.message!==void 0&&(t.message=e.message.toDict()),t}var zC=class{keyEncoder=IC;makeDefaultKeyEncoder(e){this.keyEncoder=e}},BC=new Map,VC=class e extends zC{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(BC)}},HC=o({BaseChatMessageHistory:()=>UC,BaseListChatMessageHistory:()=>WC,InMemoryChatMessageHistory:()=>GC}),UC=class extends _e{async addMessages(e){for(let t of e)await this.addMessage(t)}},WC=class extends _e{addUserMessage(e){return this.addMessage(new sn(e))}addAIMessage(e){return this.addMessage(new Jt(e))}async addMessages(e){for(let t of e)await this.addMessage(t)}clear(){throw Error(`Not implemented.`)}},GC=class extends WC{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=[]}},KC=class{pageContent;metadata;id;constructor(e){this.pageContent=e.pageContent===void 0?``:e.pageContent.toString(),this.metadata=e.metadata??{},this.id=e.id}},qC=class extends Ub{lc_namespace=[`langchain_core`,`documents`,`transformers`];invoke(e,t){return this.transformDocuments(e)}},JC=class extends qC{async transformDocuments(e){let t=[];for(let n of e){let e=await this._transformDocument(n);t.push(e)}return t}},YC=o({BaseDocumentTransformer:()=>qC,Document:()=>KC,MappingDocumentTransformer:()=>JC}),XC=o({BaseDocumentLoader:()=>ZC}),ZC=class{},QC=o({LangSmithLoader:()=>$C}),$C=class extends ZC{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 $s(e?.clientConfig),this.contentKey=e.contentKey?e.contentKey.split(`.`):[],this.formatContent=e.formatContent??ew,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 ew(e){if(typeof e==`string`)return e;try{return JSON.stringify(e,null,2)}catch{return String(e)}}var tw=o({Embeddings:()=>nw}),nw=class{caller;constructor(e){this.caller=new Vu(e??{})}},rw=class extends _e{lc_namespace=[`langchain_core`,`example_selectors`,`base`]},iw=class{async getPromptAsync(e,t){return this.getPrompt(e).partial(t?.partialVariables??{})}},aw=class extends iw{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 ow(e){return e._modelType()===`base_llm`}function sw(e){return e._modelType()===`base_chat_model`}function cw(e){return e.split(/\n| /).length}var lw=class e extends rw{examples=[];examplePrompt;getTextLength=cw;maxLength=2048;exampleTextLengths=[];constructor(e){super(e),this.examplePrompt=e.examplePrompt,this.maxLength=e.maxLength??2048,this.getTextLength=e.getTextLength??cw}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 uw(e){return Object.keys(e).sort().map(t=>e[t])}var dw=class e extends rw{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=uw((this.inputKeys??Object.keys(e)).reduce((t,n)=>({...t,[n]:e[n]}),{})).join(` `);await this.vectorStoreRetriever.addDocuments([new KC({pageContent:t,metadata:e})])}async selectExamples(e){let t=uw((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=>uw(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})}},fw=o({BaseExampleSelector:()=>rw,BasePromptSelector:()=>iw,ConditionalPromptSelector:()=>aw,LengthBasedExampleSelector:()=>lw,SemanticSimilarityExampleSelector:()=>dw,isChatModel:()=>sw,isLLM:()=>ow}),pw=`10f90ea3-90a4-4962-bf75-83a0f3c1c62a`,mw=class extends _e{lc_namespace=[`langchain`,`recordmanagers`]},hw=class{uid;hash_;contentHash;metadataHash;pageContent;metadata;keyEncoder=NC;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 KC({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 nr(this.keyEncoder(e),pw)}_hashNestedDictToUUID(e){let t=JSON.stringify(e,Object.keys(e).sort());return nr(this.keyEncoder(t),pw)}};function gw(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 _w(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 vw(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 yw=e=>`load`in e&&typeof e.load==`function`&&`loadAndSplit`in e&&typeof e.loadAndSplit==`function`;async function bw(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=yw(t)?await t.load():t,d=vw(s??null),f=await n.getTime(),p=0,m=0,h=0,g=0,_=gw(a??100,u);for(let e of _){let t=_w(e.map(e=>hw.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 xw=o({RecordManager:()=>mw,UUIDV5_NAMESPACE:()=>pw,_HashedDocument:()=>hw,_batch:()=>gw,_deduplicateInOrder:()=>_w,_getSourceIdAssigner:()=>vw,_isBaseDocumentLoader:()=>yw,index:()=>bw}),Sw=o({BasePromptValue:()=>Cw,ChatPromptValue:()=>Tw,ImagePromptValue:()=>Ew,StringPromptValue:()=>ww}),Cw=class extends _e{},ww=class extends Cw{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 sn(this.value)]}},Tw=class extends Cw{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 Sn(this.messages)}toChatMessages(){return this.messages}},Ew=class extends Cw{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 sn({content:[{type:`image_url`,image_url:{detail:this.imageUrl.detail,url:this.imageUrl.url}}]})]}},Dw=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),Ow=Object.defineProperty,kw=(e,t,n)=>t in e?Ow(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Aw=(e,t,n)=>(kw(e,typeof t==`symbol`?t:t+``,n),n);function jw(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 Mw(e,t){return e.length===1?[t.get(e.join(`,`))]:jw(e,t).map(n=>t.get(e.slice(n.start,n.end).join(`,`))).filter(e=>e!=null)}function Nw(e){return e.replace(/[\\^$*+?.()|[\]{}]/g,`\\$&`)}var Pw=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(`
101
+ `).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=Dw.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=Pw.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=Pw.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(...Mw(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)}},Fw=Pw;Aw(Fw,`specialTokenRegex`,e=>new RegExp(e.map(e=>Nw(e)).join(`|`),`g`));function Iw(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 Lw=o({encodingForModel:()=>Vw,getEncoding:()=>Bw}),Rw={},zw=new Vu({});async function Bw(e){return e in Rw||(Rw[e]=zw.fetch(`https://tiktoken.pages.dev/js/${e}.json`).then(e=>e.json()).then(e=>new Fw(e)).catch(t=>{throw delete Rw[e],t})),await Rw[e]}async function Vw(e){return Bw(Iw(e))}var Hw=o({BaseLangChain:()=>Yw,BaseLanguageModel:()=>Xw,calculateMaxTokens:()=>qw,getEmbeddingContextSize:()=>Ww,getModelContextSize:()=>Gw,getModelNameForTiktoken:()=>Uw,isOpenAITool:()=>Kw}),Uw=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,Ww=e=>{switch(e){case`text-embedding-ada-002`:return 8191;default:return 2046}},Gw=e=>{switch(Uw(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 Kw(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 qw=async({prompt:e,modelName:t})=>{let n;try{n=(await Vw(Uw(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 Gw(t)-n},Jw=()=>!1,Yw=class extends Ub{verbose;callbacks;tags;metadata;get lc_attributes(){return{callbacks:void 0,verbose:void 0}}constructor(e){super(e),this.verbose=e.verbose??Jw(),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}}}},Xw=class extends Yw{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=VC.global():this.cache=void 0,this.caller=new Vu(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 Vw(`modelName`in this?Uw(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 ww(e):Array.isArray(e)?new Tw(e.map(bn)):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}},Zw=o({applyPatch:()=>au,compare:()=>du}),Qw=class extends Ub{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`})}},$w=class extends Qw{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`)}},eT=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`)}},tT=class extends $w{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`})}},nT=class extends tT{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(ht(r)){if(typeof r.content!=`string`)throw Error(`Cannot handle non-string message output.`);e=new Cu({message:r,text:r.content})}else if(mt(r)){if(typeof r.content!=`string`)throw Error(`Cannot handle non-string message output.`);e=new Cu({message:Dn(r),text:r.content})}else e=new Su({text:r});n=n===void 0?e:n.concat(e);let i=await this.parsePartialResult([n]);i!=null&&!By(i,t)&&(this.diff?yield this._diff(t,i):yield i,t=i)}}getFormatInstructions(){return``}},rT=class extends tT{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``}},iT=class extends tT{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]}},aT=class extends iT{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 eT(`Could not parse output: ${e}`,e)}}getFormatInstructions(){return"Your response should be a list of comma separated values, eg: `foo, bar, baz`"}},oT=class extends iT{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 eT(`Incorrect number of items. Expected ${this.length}, got ${t.length}.`);return t}catch(t){throw Object.getPrototypeOf(t)===eT.prototype?t:new eT(`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\`)`}},sT=class extends iT{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:
102
102
 
103
103
  1. foo
104
104
 
105
105
  2. bar
106
106
 
107
- 3. baz`}re=/\d+\.\s([^\n]+)/g;async parse(e){return[...e.matchAll(this.re)??[]].map(e=>e[1])}},lT=class extends aT{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:
107
+ 3. baz`}re=/\d+\.\s([^\n]+)/g;async parse(e){return[...e.matchAll(this.re)??[]].map(e=>e[1])}},cT=class extends iT{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:
108
108
 
109
109
  1. foo
110
110
 
111
111
  2. bar
112
112
 
113
- 3. baz`}re=/^\s*[-*]\s([^\n]+)$/gm;async parse(e){return[...e.matchAll(this.re)??[]].map(e=>e[1])}},uT=class extends nT{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),``)}},dT=class extends rT{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?du(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}},fT=class extends eT{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 tT(`Failed to parse. Text: "${e}". Error: ${t}`,e)}}_baseMessageToString(e){return e.text}getFormatInstructions(){return``}},pT=class extends eT{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=Hv(Object.fromEntries(Object.entries(e).map(([e,t])=>[e,Bv().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.
113
+ 3. baz`}re=/^\s*[-*]\s([^\n]+)$/gm;async parse(e){return[...e.matchAll(this.re)??[]].map(e=>e[1])}},lT=class extends tT{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),``)}},uT=class extends nT{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?du(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}},dT=class extends $w{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 eT(`Failed to parse. Text: "${e}". Error: ${t}`,e)}}_baseMessageToString(e){return e.text}getFormatInstructions(){return``}},fT=class extends $w{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=Vv(Object.fromEntries(Object.entries(e).map(([e,t])=>[e,zv().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.
114
114
 
115
115
  "JSON Schema" is a declarative language that allows you to annotate and validate JSON documents.
116
116
 
@@ -122,10 +122,10 @@ Your output will be parsed and type-checked according to the provided schema ins
122
122
 
123
123
  Here is the JSON Schema instance your output must adhere to. Include the enclosing markdown codeblock:
124
124
  \`\`\`json
125
- ${JSON.stringify(Db(this.schema))}
125
+ ${JSON.stringify(Eb(this.schema))}
126
126
  \`\`\`
127
- `}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 Dg(this.schema,JSON.parse(n))}catch(t){throw new tT(`Failed to parse. Text: "${e}". Error: ${t}`,e)}}_baseMessageToString(e){return e.text}},mT=class extends pT{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(Db(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(`
128
- `)}\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=Hv(Object.fromEntries(Object.entries(e).map(([e,t])=>[e,Bv().describe(t)])));return new this(t)}},hT=class extends eT{structuredInputParser;constructor({inputSchema:e}){super(...arguments),this.structuredInputParser=new mT(e)}async parse(e){let t;try{t=await this.structuredInputParser.parse(e)}catch(t){throw new tT(`Failed to parse. Text: "${e}". Error: ${t}`,e)}return this.outputProcessor(t)}getFormatInstructions(){return this.structuredInputParser.getFormatInstructions()}},gT=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=x.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),ie(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`:oe(n);break;case`cdata`:ae(n,`oncdata`,n.cdata),n.cdata=``;break;case`script`:ae(n,`onscript`,n.script),n.script=``;break;default:ce(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){oe(e),e.cdata!==``&&(ae(e,`oncdata`,e.cdata),e.cdata=``),e.script!==``&&(ae(e,`onscript`,e.script),e.script=``)}n.prototype={end:function(){le(this)},write:ve,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===`
127
+ `}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 Dg(this.schema,JSON.parse(n))}catch(t){throw new eT(`Failed to parse. Text: "${e}". Error: ${t}`,e)}}_baseMessageToString(e){return e.text}},pT=class extends fT{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(Eb(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(`
128
+ `)}\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=Vv(Object.fromEntries(Object.entries(e).map(([e,t])=>[e,zv().describe(t)])));return new this(t)}},mT=class extends $w{structuredInputParser;constructor({inputSchema:e}){super(...arguments),this.structuredInputParser=new pT(e)}async parse(e){let t;try{t=await this.structuredInputParser.parse(e)}catch(t){throw new eT(`Failed to parse. Text: "${e}". Error: ${t}`,e)}return this.outputProcessor(t)}getFormatInstructions(){return this.structuredInputParser.getFormatInstructions()}},hT=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=x.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),ie(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`:oe(n);break;case`cdata`:ae(n,`oncdata`,n.cdata),n.cdata=``;break;case`script`:ae(n,`onscript`,n.script),n.script=``;break;default:ce(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){oe(e),e.cdata!==``&&(ae(e,`oncdata`,e.cdata),e.cdata=``),e.script!==``&&(ae(e,`onscript`,e.script),e.script=``)}n.prototype={end:function(){le(this)},write:ve,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===`
129
129
  `||e===`\r`||e===` `}function b(e){return e===`"`||e===`'`}function ee(e){return e===`>`||y(e)}function te(e,t){return e.test(t)}function ne(e,t){return!te(e,t)}var x=0;for(var re in e.STATE={BEGIN:x++,BEGIN_WHITESPACE:x++,TEXT:x++,TEXT_ENTITY:x++,OPEN_WAKA:x++,SGML_DECL:x++,SGML_DECL_QUOTED:x++,DOCTYPE:x++,DOCTYPE_QUOTED:x++,DOCTYPE_DTD:x++,DOCTYPE_DTD_QUOTED:x++,COMMENT_STARTING:x++,COMMENT:x++,COMMENT_ENDING:x++,COMMENT_ENDED:x++,CDATA:x++,CDATA_ENDING:x++,CDATA_ENDING_2:x++,PROC_INST:x++,PROC_INST_BODY:x++,PROC_INST_ENDING:x++,OPEN_TAG:x++,OPEN_TAG_SLASH:x++,ATTRIB:x++,ATTRIB_NAME:x++,ATTRIB_NAME_SAW_WHITE:x++,ATTRIB_VALUE:x++,ATTRIB_VALUE_QUOTED:x++,ATTRIB_VALUE_CLOSED:x++,ATTRIB_VALUE_UNQUOTED:x++,ATTRIB_VALUE_ENTITY_Q:x++,ATTRIB_VALUE_ENTITY_U:x++,CLOSE_TAG:x++,CLOSE_TAG_SAW_WHITE:x++,SCRIPT:x++,SCRIPT_ENDING:x++},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[re]]=re;x=e.STATE;function ie(e,t,n){e[t]&&e[t](n)}function ae(e,t,n){e.textNode&&oe(e),ie(e,t,n)}function oe(e){e.textNode=se(e.opt,e.textNode),e.textNode&&ie(e,`ontext`,e.textNode),e.textNode=``}function se(e,t){return e.trim&&(t=t.trim()),e.normalize&&(t=t.replace(/\s+/g,` `)),t}function ce(e,t){return oe(e),e.trackPosition&&(t+=`
130
130
  Line: `+e.line+`
131
131
  Column: `+e.column+`
@@ -133,7 +133,7 @@ Char: `+e.c),t=Error(t),e.error=t,ie(e,`onerror`,t),e}function le(e){return e.sa
133
133
  Actual: `+e.attribValue);else if(r===`xmlns`&&e.attribValue!==p)S(e,`xmlns: prefix must be bound to `+p+`
134
134
  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,ae(e,`onattribute`,{name:e.attribName,value:e.attribValue});e.attribName=e.attribValue=``}function pe(e,t){if(e.opt.xmlns){var n=e.tag,r=de(e.tagName);n.prefix=r.prefix,n.local=r.local,n.uri=n.ns[r.prefix]||``,n.prefix&&!n.uri&&(S(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){ae(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=de(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&&(S(e,`Unbound namespace prefix: `+JSON.stringify(d)),m.uri=d),e.tag.attributes[c]=m,ae(e,`onattribute`,m)}e.attribList.length=0}e.tag.isSelfClosing=!!t,e.sawRoot=!0,e.tags.push(e.tag),ae(e,`onopentag`,e.tag),t||(!e.noscript&&e.tagName.toLowerCase()===`script`?e.state=x.SCRIPT:e.state=x.TEXT,e.tag=null,e.tagName=``),e.attribName=e.attribValue=``,e.attribList.length=0}function me(e){if(!e.tagName){S(e,`Weird empty close tag.`),e.textNode+=`</>`,e.state=x.TEXT;return}if(e.script){if(e.tagName!==`script`){e.script+=`</`+e.tagName+`>`,e.tagName=``,e.state=x.SCRIPT;return}ae(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;)S(e,`Unexpected close tag`);if(t<0){S(e,`Unmatched closing tag: `+e.tagName),e.textNode+=`</`+e.tagName+`>`,e.state=x.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,ae(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];ae(e,`onclosenamespace`,{prefix:t,uri:n})})}t===0&&(e.closedRoot=!0),e.tagName=e.attribValue=e.attribName=``,e.attribList.length=0,e.state=x.TEXT}function he(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?(S(e,`Invalid character entity`),`&`+e.entity+`;`):String.fromCodePoint(r))}function ge(e,t){t===`<`?(e.state=x.OPEN_WAKA,e.startTagPosition=e.position):y(t)||(S(e,`Non-whitespace before first tag.`),e.textNode=t,e.state=x.TEXT)}function _e(e,t){var n=``;return t<e.length&&(n=e.charAt(t)),n}function ve(e){var t=this;if(this.error)throw this.error;if(t.closed)return ce(t,`Cannot write after close. Assign an onready handler.`);if(e===null)return le(t);typeof e==`object`&&(e=e.toString());for(var n=0,i=``;i=_e(e,n++),t.c=i,i;)switch(t.trackPosition&&(t.position++,i===`
135
135
  `?(t.line++,t.column=0):t.column++),t.state){case x.BEGIN:if(t.state=x.BEGIN_WHITESPACE,i===``)continue;ge(t,i);continue;case x.BEGIN_WHITESPACE:ge(t,i);continue;case x.TEXT:if(t.sawRoot&&!t.closedRoot){for(var a=n-1;i&&i!==`<`&&i!==`&`;)i=_e(e,n++),i&&t.trackPosition&&(t.position++,i===`
136
- `?(t.line++,t.column=0):t.column++);t.textNode+=e.substring(a,n-1)}i===`<`&&!(t.sawRoot&&t.closedRoot&&!t.strict)?(t.state=x.OPEN_WAKA,t.startTagPosition=t.position):(!y(i)&&(!t.sawRoot||t.closedRoot)&&S(t,`Text data outside of root node.`),i===`&`?t.state=x.TEXT_ENTITY:t.textNode+=i);continue;case x.SCRIPT:i===`<`?t.state=x.SCRIPT_ENDING:t.script+=i;continue;case x.SCRIPT_ENDING:i===`/`?t.state=x.CLOSE_TAG:(t.script+=`<`+i,t.state=x.SCRIPT);continue;case x.OPEN_WAKA:if(i===`!`)t.state=x.SGML_DECL,t.sgmlDecl=``;else if(!y(i))if(te(h,i))t.state=x.OPEN_TAG,t.tagName=i;else if(i===`/`)t.state=x.CLOSE_TAG,t.tagName=``;else if(i===`?`)t.state=x.PROC_INST,t.procInstName=t.procInstBody=``;else{if(S(t,`Unencoded <`),t.startTagPosition+1<t.position){var o=t.position-t.startTagPosition;i=Array(o).join(` `)+i}t.textNode+=`<`+i,t.state=x.TEXT}continue;case x.SGML_DECL:(t.sgmlDecl+i).toUpperCase()===u?(ae(t,`onopencdata`),t.state=x.CDATA,t.sgmlDecl=``,t.cdata=``):t.sgmlDecl+i===`--`?(t.state=x.COMMENT,t.comment=``,t.sgmlDecl=``):(t.sgmlDecl+i).toUpperCase()===d?(t.state=x.DOCTYPE,(t.doctype||t.sawRoot)&&S(t,`Inappropriately located doctype declaration`),t.doctype=``,t.sgmlDecl=``):i===`>`?(ae(t,`onsgmldeclaration`,t.sgmlDecl),t.sgmlDecl=``,t.state=x.TEXT):(b(i)&&(t.state=x.SGML_DECL_QUOTED),t.sgmlDecl+=i);continue;case x.SGML_DECL_QUOTED:i===t.q&&(t.state=x.SGML_DECL,t.q=``),t.sgmlDecl+=i;continue;case x.DOCTYPE:i===`>`?(t.state=x.TEXT,ae(t,`ondoctype`,t.doctype),t.doctype=!0):(t.doctype+=i,i===`[`?t.state=x.DOCTYPE_DTD:b(i)&&(t.state=x.DOCTYPE_QUOTED,t.q=i));continue;case x.DOCTYPE_QUOTED:t.doctype+=i,i===t.q&&(t.q=``,t.state=x.DOCTYPE);continue;case x.DOCTYPE_DTD:t.doctype+=i,i===`]`?t.state=x.DOCTYPE:b(i)&&(t.state=x.DOCTYPE_DTD_QUOTED,t.q=i);continue;case x.DOCTYPE_DTD_QUOTED:t.doctype+=i,i===t.q&&(t.state=x.DOCTYPE_DTD,t.q=``);continue;case x.COMMENT:i===`-`?t.state=x.COMMENT_ENDING:t.comment+=i;continue;case x.COMMENT_ENDING:i===`-`?(t.state=x.COMMENT_ENDED,t.comment=se(t.opt,t.comment),t.comment&&ae(t,`oncomment`,t.comment),t.comment=``):(t.comment+=`-`+i,t.state=x.COMMENT);continue;case x.COMMENT_ENDED:i===`>`?t.state=x.TEXT:(S(t,`Malformed comment`),t.comment+=`--`+i,t.state=x.COMMENT);continue;case x.CDATA:i===`]`?t.state=x.CDATA_ENDING:t.cdata+=i;continue;case x.CDATA_ENDING:i===`]`?t.state=x.CDATA_ENDING_2:(t.cdata+=`]`+i,t.state=x.CDATA);continue;case x.CDATA_ENDING_2:i===`>`?(t.cdata&&ae(t,`oncdata`,t.cdata),ae(t,`onclosecdata`),t.cdata=``,t.state=x.TEXT):i===`]`?t.cdata+=`]`:(t.cdata+=`]]`+i,t.state=x.CDATA);continue;case x.PROC_INST:i===`?`?t.state=x.PROC_INST_ENDING:y(i)?t.state=x.PROC_INST_BODY:t.procInstName+=i;continue;case x.PROC_INST_BODY:if(!t.procInstBody&&y(i))continue;i===`?`?t.state=x.PROC_INST_ENDING:t.procInstBody+=i;continue;case x.PROC_INST_ENDING:i===`>`?(ae(t,`onprocessinginstruction`,{name:t.procInstName,body:t.procInstBody}),t.procInstName=t.procInstBody=``,t.state=x.TEXT):(t.procInstBody+=`?`+i,t.state=x.PROC_INST_BODY);continue;case x.OPEN_TAG:te(g,i)?t.tagName+=i:(ue(t),i===`>`?pe(t):i===`/`?t.state=x.OPEN_TAG_SLASH:(y(i)||S(t,`Invalid character in tag name`),t.state=x.ATTRIB));continue;case x.OPEN_TAG_SLASH:i===`>`?(pe(t,!0),me(t)):(S(t,`Forward-slash in opening tag not followed by >`),t.state=x.ATTRIB);continue;case x.ATTRIB:if(y(i))continue;i===`>`?pe(t):i===`/`?t.state=x.OPEN_TAG_SLASH:te(h,i)?(t.attribName=i,t.attribValue=``,t.state=x.ATTRIB_NAME):S(t,`Invalid attribute name`);continue;case x.ATTRIB_NAME:i===`=`?t.state=x.ATTRIB_VALUE:i===`>`?(S(t,`Attribute without value`),t.attribValue=t.attribName,fe(t),pe(t)):y(i)?t.state=x.ATTRIB_NAME_SAW_WHITE:te(g,i)?t.attribName+=i:S(t,`Invalid attribute name`);continue;case x.ATTRIB_NAME_SAW_WHITE:if(i===`=`)t.state=x.ATTRIB_VALUE;else if(y(i))continue;else S(t,`Attribute without value`),t.tag.attributes[t.attribName]=``,t.attribValue=``,ae(t,`onattribute`,{name:t.attribName,value:``}),t.attribName=``,i===`>`?pe(t):te(h,i)?(t.attribName=i,t.state=x.ATTRIB_NAME):(S(t,`Invalid attribute name`),t.state=x.ATTRIB);continue;case x.ATTRIB_VALUE:if(y(i))continue;b(i)?(t.q=i,t.state=x.ATTRIB_VALUE_QUOTED):(S(t,`Unquoted attribute value`),t.state=x.ATTRIB_VALUE_UNQUOTED,t.attribValue=i);continue;case x.ATTRIB_VALUE_QUOTED:if(i!==t.q){i===`&`?t.state=x.ATTRIB_VALUE_ENTITY_Q:t.attribValue+=i;continue}fe(t),t.q=``,t.state=x.ATTRIB_VALUE_CLOSED;continue;case x.ATTRIB_VALUE_CLOSED:y(i)?t.state=x.ATTRIB:i===`>`?pe(t):i===`/`?t.state=x.OPEN_TAG_SLASH:te(h,i)?(S(t,`No whitespace between attributes`),t.attribName=i,t.attribValue=``,t.state=x.ATTRIB_NAME):S(t,`Invalid attribute name`);continue;case x.ATTRIB_VALUE_UNQUOTED:if(!ee(i)){i===`&`?t.state=x.ATTRIB_VALUE_ENTITY_U:t.attribValue+=i;continue}fe(t),i===`>`?pe(t):t.state=x.ATTRIB;continue;case x.CLOSE_TAG:if(t.tagName)i===`>`?me(t):te(g,i)?t.tagName+=i:t.script?(t.script+=`</`+t.tagName,t.tagName=``,t.state=x.SCRIPT):(y(i)||S(t,`Invalid tagname in closing tag`),t.state=x.CLOSE_TAG_SAW_WHITE);else{if(y(i))continue;ne(h,i)?t.script?(t.script+=`</`+i,t.state=x.SCRIPT):S(t,`Invalid tagname in closing tag.`):t.tagName=i}continue;case x.CLOSE_TAG_SAW_WHITE:if(y(i))continue;i===`>`?me(t):S(t,`Invalid characters in closing tag`);continue;case x.TEXT_ENTITY:case x.ATTRIB_VALUE_ENTITY_Q:case x.ATTRIB_VALUE_ENTITY_U:var s,c;switch(t.state){case x.TEXT_ENTITY:s=x.TEXT,c=`textNode`;break;case x.ATTRIB_VALUE_ENTITY_Q:s=x.ATTRIB_VALUE_QUOTED,c=`attribValue`;break;case x.ATTRIB_VALUE_ENTITY_U:s=x.ATTRIB_VALUE_UNQUOTED,c=`attribValue`;break}if(i===`;`)if(t.opt.unparsedEntities){var l=he(t);t.entity=``,t.state=s,t.write(l)}else t[c]+=he(t),t.entity=``,t.state=s;else te(t.entity.length?v:_,i)?t.entity+=i:(S(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}(),_T=`The output should be formatted as a XML file.
136
+ `?(t.line++,t.column=0):t.column++);t.textNode+=e.substring(a,n-1)}i===`<`&&!(t.sawRoot&&t.closedRoot&&!t.strict)?(t.state=x.OPEN_WAKA,t.startTagPosition=t.position):(!y(i)&&(!t.sawRoot||t.closedRoot)&&S(t,`Text data outside of root node.`),i===`&`?t.state=x.TEXT_ENTITY:t.textNode+=i);continue;case x.SCRIPT:i===`<`?t.state=x.SCRIPT_ENDING:t.script+=i;continue;case x.SCRIPT_ENDING:i===`/`?t.state=x.CLOSE_TAG:(t.script+=`<`+i,t.state=x.SCRIPT);continue;case x.OPEN_WAKA:if(i===`!`)t.state=x.SGML_DECL,t.sgmlDecl=``;else if(!y(i))if(te(h,i))t.state=x.OPEN_TAG,t.tagName=i;else if(i===`/`)t.state=x.CLOSE_TAG,t.tagName=``;else if(i===`?`)t.state=x.PROC_INST,t.procInstName=t.procInstBody=``;else{if(S(t,`Unencoded <`),t.startTagPosition+1<t.position){var o=t.position-t.startTagPosition;i=Array(o).join(` `)+i}t.textNode+=`<`+i,t.state=x.TEXT}continue;case x.SGML_DECL:(t.sgmlDecl+i).toUpperCase()===u?(ae(t,`onopencdata`),t.state=x.CDATA,t.sgmlDecl=``,t.cdata=``):t.sgmlDecl+i===`--`?(t.state=x.COMMENT,t.comment=``,t.sgmlDecl=``):(t.sgmlDecl+i).toUpperCase()===d?(t.state=x.DOCTYPE,(t.doctype||t.sawRoot)&&S(t,`Inappropriately located doctype declaration`),t.doctype=``,t.sgmlDecl=``):i===`>`?(ae(t,`onsgmldeclaration`,t.sgmlDecl),t.sgmlDecl=``,t.state=x.TEXT):(b(i)&&(t.state=x.SGML_DECL_QUOTED),t.sgmlDecl+=i);continue;case x.SGML_DECL_QUOTED:i===t.q&&(t.state=x.SGML_DECL,t.q=``),t.sgmlDecl+=i;continue;case x.DOCTYPE:i===`>`?(t.state=x.TEXT,ae(t,`ondoctype`,t.doctype),t.doctype=!0):(t.doctype+=i,i===`[`?t.state=x.DOCTYPE_DTD:b(i)&&(t.state=x.DOCTYPE_QUOTED,t.q=i));continue;case x.DOCTYPE_QUOTED:t.doctype+=i,i===t.q&&(t.q=``,t.state=x.DOCTYPE);continue;case x.DOCTYPE_DTD:t.doctype+=i,i===`]`?t.state=x.DOCTYPE:b(i)&&(t.state=x.DOCTYPE_DTD_QUOTED,t.q=i);continue;case x.DOCTYPE_DTD_QUOTED:t.doctype+=i,i===t.q&&(t.state=x.DOCTYPE_DTD,t.q=``);continue;case x.COMMENT:i===`-`?t.state=x.COMMENT_ENDING:t.comment+=i;continue;case x.COMMENT_ENDING:i===`-`?(t.state=x.COMMENT_ENDED,t.comment=se(t.opt,t.comment),t.comment&&ae(t,`oncomment`,t.comment),t.comment=``):(t.comment+=`-`+i,t.state=x.COMMENT);continue;case x.COMMENT_ENDED:i===`>`?t.state=x.TEXT:(S(t,`Malformed comment`),t.comment+=`--`+i,t.state=x.COMMENT);continue;case x.CDATA:i===`]`?t.state=x.CDATA_ENDING:t.cdata+=i;continue;case x.CDATA_ENDING:i===`]`?t.state=x.CDATA_ENDING_2:(t.cdata+=`]`+i,t.state=x.CDATA);continue;case x.CDATA_ENDING_2:i===`>`?(t.cdata&&ae(t,`oncdata`,t.cdata),ae(t,`onclosecdata`),t.cdata=``,t.state=x.TEXT):i===`]`?t.cdata+=`]`:(t.cdata+=`]]`+i,t.state=x.CDATA);continue;case x.PROC_INST:i===`?`?t.state=x.PROC_INST_ENDING:y(i)?t.state=x.PROC_INST_BODY:t.procInstName+=i;continue;case x.PROC_INST_BODY:if(!t.procInstBody&&y(i))continue;i===`?`?t.state=x.PROC_INST_ENDING:t.procInstBody+=i;continue;case x.PROC_INST_ENDING:i===`>`?(ae(t,`onprocessinginstruction`,{name:t.procInstName,body:t.procInstBody}),t.procInstName=t.procInstBody=``,t.state=x.TEXT):(t.procInstBody+=`?`+i,t.state=x.PROC_INST_BODY);continue;case x.OPEN_TAG:te(g,i)?t.tagName+=i:(ue(t),i===`>`?pe(t):i===`/`?t.state=x.OPEN_TAG_SLASH:(y(i)||S(t,`Invalid character in tag name`),t.state=x.ATTRIB));continue;case x.OPEN_TAG_SLASH:i===`>`?(pe(t,!0),me(t)):(S(t,`Forward-slash in opening tag not followed by >`),t.state=x.ATTRIB);continue;case x.ATTRIB:if(y(i))continue;i===`>`?pe(t):i===`/`?t.state=x.OPEN_TAG_SLASH:te(h,i)?(t.attribName=i,t.attribValue=``,t.state=x.ATTRIB_NAME):S(t,`Invalid attribute name`);continue;case x.ATTRIB_NAME:i===`=`?t.state=x.ATTRIB_VALUE:i===`>`?(S(t,`Attribute without value`),t.attribValue=t.attribName,fe(t),pe(t)):y(i)?t.state=x.ATTRIB_NAME_SAW_WHITE:te(g,i)?t.attribName+=i:S(t,`Invalid attribute name`);continue;case x.ATTRIB_NAME_SAW_WHITE:if(i===`=`)t.state=x.ATTRIB_VALUE;else if(y(i))continue;else S(t,`Attribute without value`),t.tag.attributes[t.attribName]=``,t.attribValue=``,ae(t,`onattribute`,{name:t.attribName,value:``}),t.attribName=``,i===`>`?pe(t):te(h,i)?(t.attribName=i,t.state=x.ATTRIB_NAME):(S(t,`Invalid attribute name`),t.state=x.ATTRIB);continue;case x.ATTRIB_VALUE:if(y(i))continue;b(i)?(t.q=i,t.state=x.ATTRIB_VALUE_QUOTED):(S(t,`Unquoted attribute value`),t.state=x.ATTRIB_VALUE_UNQUOTED,t.attribValue=i);continue;case x.ATTRIB_VALUE_QUOTED:if(i!==t.q){i===`&`?t.state=x.ATTRIB_VALUE_ENTITY_Q:t.attribValue+=i;continue}fe(t),t.q=``,t.state=x.ATTRIB_VALUE_CLOSED;continue;case x.ATTRIB_VALUE_CLOSED:y(i)?t.state=x.ATTRIB:i===`>`?pe(t):i===`/`?t.state=x.OPEN_TAG_SLASH:te(h,i)?(S(t,`No whitespace between attributes`),t.attribName=i,t.attribValue=``,t.state=x.ATTRIB_NAME):S(t,`Invalid attribute name`);continue;case x.ATTRIB_VALUE_UNQUOTED:if(!ee(i)){i===`&`?t.state=x.ATTRIB_VALUE_ENTITY_U:t.attribValue+=i;continue}fe(t),i===`>`?pe(t):t.state=x.ATTRIB;continue;case x.CLOSE_TAG:if(t.tagName)i===`>`?me(t):te(g,i)?t.tagName+=i:t.script?(t.script+=`</`+t.tagName,t.tagName=``,t.state=x.SCRIPT):(y(i)||S(t,`Invalid tagname in closing tag`),t.state=x.CLOSE_TAG_SAW_WHITE);else{if(y(i))continue;ne(h,i)?t.script?(t.script+=`</`+i,t.state=x.SCRIPT):S(t,`Invalid tagname in closing tag.`):t.tagName=i}continue;case x.CLOSE_TAG_SAW_WHITE:if(y(i))continue;i===`>`?me(t):S(t,`Invalid characters in closing tag`);continue;case x.TEXT_ENTITY:case x.ATTRIB_VALUE_ENTITY_Q:case x.ATTRIB_VALUE_ENTITY_U:var s,c;switch(t.state){case x.TEXT_ENTITY:s=x.TEXT,c=`textNode`;break;case x.ATTRIB_VALUE_ENTITY_Q:s=x.ATTRIB_VALUE_QUOTED,c=`attribValue`;break;case x.ATTRIB_VALUE_ENTITY_U:s=x.ATTRIB_VALUE_UNQUOTED,c=`attribValue`;break}if(i===`;`)if(t.opt.unparsedEntities){var l=he(t);t.entity=``,t.state=s,t.write(l)}else t[c]+=he(t),t.entity=``,t.state=s;else te(t.entity.length?v:_,i)?t.entity+=i:(S(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}(),gT=`The output should be formatted as a XML file.
137
137
  1. Output should conform to the tags below.
138
138
  2. If tags are not given, make them on your own.
139
139
  3. Remember to always open and close all the tags.
@@ -155,43 +155,44 @@ As an example, for the tags ["foo", "bar", "baz"]:
155
155
  Here are the output tags:
156
156
  \`\`\`
157
157
  {tags}
158
- \`\`\``,vT=class extends rT{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?du(e,t):[{op:`replace`,path:``,value:t}]}async parsePartialResult(e){return xT(e[0].text)}async parse(e){return xT(e)}getFormatInstructions(){return this.tags&&this.tags.length>0?_T.replace(`{tags}`,this.tags?.join(`, `)??``):_T}},yT=e=>e.split(`
158
+ \`\`\``,_T=class extends nT{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?du(e,t):[{op:`replace`,path:``,value:t}]}async parsePartialResult(e){return bT(e[0].text)}async parse(e){return bT(e)}getFormatInstructions(){return this.tags&&this.tags.length>0?gT.replace(`{tags}`,this.tags?.join(`, `)??``):gT}},vT=e=>e.split(`
159
159
  `).map(e=>e.replace(/^\s+/,``)).join(`
160
- `).trim(),bT=e=>{if(Object.keys(e).length===0)return{};let t={};return e.children.length>0?(t[e.name]=e.children.map(bT),t):(t[e.name]=e.text??void 0,t)};function xT(e){let t=yT(e),n=gT.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]),bT(r)}var ST=o({AsymmetricStructuredOutputParser:()=>hT,BaseCumulativeTransformOutputParser:()=>rT,BaseLLMOutputParser:()=>$w,BaseOutputParser:()=>eT,BaseTransformOutputParser:()=>nT,BytesOutputParser:()=>iT,CommaSeparatedListOutputParser:()=>oT,CustomListOutputParser:()=>sT,JsonMarkdownStructuredOutputParser:()=>mT,JsonOutputParser:()=>dT,ListOutputParser:()=>aT,MarkdownListOutputParser:()=>lT,NumberedListOutputParser:()=>cT,OutputParserException:()=>tT,StandardSchemaOutputParser:()=>fT,StringOutputParser:()=>uT,StructuredOutputParser:()=>pT,XMLOutputParser:()=>vT,XML_FORMAT_INSTRUCTIONS:()=>_T,parseJsonMarkdown:()=>v,parsePartialJson:()=>b,parseXMLMarkdown:()=>xT}),CT=o({extendInteropZodObject:()=>Bg,getInteropZodDefaultGetter:()=>Wg,getInteropZodObjectShape:()=>zg,getSchemaDescription:()=>Ag,interopParse:()=>kg,interopParseAsync:()=>Dg,interopSafeParse:()=>Og,interopSafeParseAsync:()=>Eg,interopZodObjectMakeFieldsOptional:()=>Yg,interopZodObjectPartial:()=>Vg,interopZodObjectPassthrough:()=>Ug,interopZodObjectStrict:()=>Hg,interopZodTransformInputSchema:()=>Jg,isInteropZodError:()=>Xg,isInteropZodLiteral:()=>Tg,isInteropZodObject:()=>Rg,isInteropZodSchema:()=>Sg,isShapelessZodSchema:()=>jg,isSimpleStringZodSchema:()=>Mg,isZodArrayV4:()=>Fg,isZodLiteralV3:()=>Cg,isZodLiteralV4:()=>wg,isZodNullableV4:()=>Lg,isZodObjectV3:()=>Ng,isZodObjectV4:()=>Pg,isZodOptionalV4:()=>Ig,isZodSchema:()=>xg,isZodSchemaV3:()=>bg,isZodSchemaV4:()=>yg});function wT(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 tT([`Function "${e.function.name}" arguments:`,``,e.function.arguments,``,`are not valid JSON.`,`Error: ${t.message}`].join(`
161
- `))}let r={name:e.function.name,args:n,type:`tool_call`};return t?.returnId&&(r.id=e.id),r}function TT(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 ET(e,t){return{name:e.function?.name,args:e.function?.arguments,id:e.id,error:t,type:`invalid_tool_call`}}var DT=class extends rT{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(Yt(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=>wT(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}},OT=class extends DT{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 tT(`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 Eg(this.zodSchema,e);if(t.success)return t.data;throw new tT(`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)))}},kT=o({assembleStructuredOutputPipeline:()=>MT,createContentParser:()=>AT,createFunctionCallingParser:()=>jT});function AT(e){return Sg(e)?pT.fromZodSchema(e):By(e)?fT.fromSerializableSchema(e):new dT}function jT(e,t,n){let r=n??OT;return Sg(e)?new r({returnSingle:!0,keyName:t,zodSchema:e}):By(e)?new r({returnSingle:!0,keyName:t,serializableSchema:e}):new r({returnSingle:!0,keyName:t})}function MT(e,t,n,r){if(!n){let n=e.pipe(t);return r?n.withConfig({runName:r}):n}let i=ox.assign({parsed:(e,n)=>t.invoke(e.raw,n)}),a=ox.assign({parsed:()=>null}),o=i.withFallbacks({fallbacks:[a]}),s=Jb.from([{raw:e},o]);return r?s.withConfig({runName:r}):s}var NT=o({ChatModelStream:()=>KT,ReasoningContentStream:()=>WT,TextContentStream:()=>HT,ToolCallsStream:()=>UT,UsageMetadataStream:()=>GT}),PT=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 FT(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 IT(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 LT(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 RT(e){if(typeof e!=`object`||!e)return!1;let t=e.type;return t===`reasoning`||t===`thinking`}function zT(e){if(e)return{...e,input_tokens:e.input_tokens??0,output_tokens:e.output_tokens??0,total_tokens:e.total_tokens??0}}function BT(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 VT(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:BT(r)}}var HT=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=IT(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=IT(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)}},UT=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)}},WT=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(!RT(r.content)){if(n)return;continue}n=!0;let e=LT(r.content);if(e==null||e.length===0)continue;t+=e,yield t}else if(r.event===`content-block-delta`){let e=IT(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`&&RT(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(!RT(n.content)){if(t)return;continue}t=!0;let e=LT(n.content);e!=null&&e.length>0&&(yield e)}else if(n.event===`content-block-delta`){let e=IT(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`&&RT(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)}},GT=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=zT(t.usage);e&&(yield e)}else if(t.event===`message-start`&&t.usage){let e=zT(t.usage);e&&(yield e)}else if(t.event===`message-finish`&&t.usage){let e=zT(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)}},KT=class{_buffer;constructor(e){this._buffer=new PT,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 HT(this._buffer)}get toolCalls(){return new UT(this._buffer)}get reasoning(){return new WT(this._buffer)}get usage(){return new GT(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=zT(a.usage));break;case`content-block-start`:e[a.index]=a.content;break;case`content-block-delta`:{let t=e[a.index],n=IT(a);t&&n&&(e[a.index]=FT(t,n));break}case`content-block-finish`:e[a.index]=a.content;break;case`usage`:n=zT(a.usage);break;case`message-finish`:i=a.reason,a.usage&&(n=zT(a.usage)),a.responseMetadata&&(r={...r,...a.responseMetadata});break;default:break}let a=e.filter(e=>e!=null).map(VT);return new Jt({id:t,content:a,usage_metadata:n,response_metadata:{...r,...i?{finish_reason:i}:{},output_version:`v1`}})}},qT=o({convertChunksToEvents:()=>eE,finalizeContentBlock:()=>rE}),JT={wav:`audio/wav`,mp3:`audio/mpeg`,flac:`audio/flac`,opus:`audio/opus`,aac:`audio/aac`,pcm16:`audio/pcm`},YT={png:`image/png`,jpeg:`image/jpeg`,jpg:`image/jpeg`,webp:`image/webp`,gif:`image/gif`};function XT(e){let t=0;for(let n of e.keys())n>=t&&(t=n+1);return t}function ZT(e){let t=e.additional_kwargs;return typeof t==`object`&&t?t:{}}function QT(e){let t=ZT(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:YT[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 $T(e){let t=ZT(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:JT[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*eE(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};Zt.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=nE(e);r.accumulated=tE(r.accumulated,i),yield{event:`content-block-delta`,index:t,delta:i}}}if(Zt.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=$T(e);if(u!=null){if(a==null){let e=XT(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 QT(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=XT(n);n.set(i,{type:`image`,accumulated:t}),yield{event:`content-block-start`,index:i,content:t}}if(!c&&Zt.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:rE(t.accumulated)};yield{event:`message-finish`,reason:`stop`,...i?{usage:i}:{}}}function tE(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 nE(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 rE(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 iE=e=>e();function aE(e){let t=e.constructor;return new t({...e,content:e.contentBlocks,response_metadata:{...e.response_metadata,output_version:`v1`}})}var oE=o({BaseChatModel:()=>cE,SimpleChatModel:()=>lE});function sE(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];(ye(r)||be(r))&&e===n&&(e=new n.constructor({...e,content:[...n.content.slice(0,t),Ce(r),...n.content.slice(t+1)]}))}t.push(e)}return t}var cE=class e extends Zw{lc_namespace=[`langchain`,`chat_models`,this._llmType()];disableStreaming=!1;outputVersion;get callKeys(){return[...super.callKeys,`outputVersion`]}constructor(e){super(e),this.outputVersion=iE(()=>{let t=e.outputVersion??mr(`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*eE(this._streamResponseChunks(e,t,n),{signal:t.signal})}streamV2(t,n){let r=e._convertInputToPromptValue(t).toChatMessages(),[,i]=this._separateRunnableConfigFromCallOptionsCompat(n);return new KT(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 yl.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(),[sE(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 aE(e.message):yield e.message,f=f?f.concat(e):e,Xt(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(bn)),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 yl.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(sE),r.runId,void 0,s,void 0,void 0,r.runName)}let s=n.outputVersion??this.outputVersion,c=[],l=[],u=!!o?.[0].handlers.find(vr),d=!!o?.[0].handlers.find(_r);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 KT({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:zl(t,i),Xt(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=aE(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,xu,{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(bn)),s={...a.metadata,...this.getLsParamsWithDefaults(i)},c=this.invocationParams(i),l=await yl.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(sE),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&&mt(e.message)&&Yt(e.message)&&(e.message.usage_metadata={input_tokens:0,output_tokens:0,total_tokens:0},m===`v1`&&(e.message=aE(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,xu,{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(bn)),[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=Ag(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`;!Sg(n)&&!By(n)&&`name`in n&&(s=n.name);let c=Sg(n)||By(n)?Db(n):n,l=[{type:`function`,function:{name:s,description:i,parameters:c}}];return MT(this.bindTools(l),Qb.from(e=>{if(!Zt.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`)}},lE=class extends cE{async _generate(e,t,n){let r=new Jt(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}]}}},uE=o({}),dE=o({BaseLLM:()=>fE,LLM:()=>pE}),fE=class e extends Zw{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 yl.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 Su({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 yl.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(_r),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:zl(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,xu,{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 yl.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,xu,{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`}},pE=class extends fE{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}])))}}},mE=o({}),hE=o({BaseMemory:()=>gE,getInputValue:()=>vE,getOutputValue:()=>yE,getPromptInputKey:()=>bE}),gE=class{},_E=(e,t)=>{if(t!==void 0)return e[t];let n=Object.keys(e);if(n.length===1)return e[n[0]]},vE=(e,t)=>{let n=_E(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},yE=(e,t)=>{let n=_E(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 bE(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 xE=class extends $w{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)}`)}},SE=class extends rT{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 xE(e)}_diff(e,t){if(t)return du(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``}},CE=class extends $w{static lc_name(){return`JsonKeyOutputFunctionsParser`}lc_namespace=[`langchain`,`output_parsers`,`openai_functions`];lc_serializable=!0;outputParser=new SE;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]}},wE=o({JsonKeyOutputFunctionsParser:()=>CE,JsonOutputFunctionsParser:()=>SE,OutputFunctionsParser:()=>xE}),TE=o({JsonOutputKeyToolsParser:()=>OT,JsonOutputToolsParser:()=>DT,convertLangChainToolCallToOpenAI:()=>TT,makeInvalidToolCall:()=>ET,parseToolCall:()=>wT}),EE=class extends Wb{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`})}},DE=class extends EE{async formatPromptValue(e){return new Tw(await this.format(e))}},OE=Object.prototype.toString,kE=Array.isArray||function(e){return OE.call(e)===`[object Array]`};function AE(e){return typeof e==`function`}function jE(e){return kE(e)?`array`:typeof e}function ME(e){return e.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,`\\$&`)}function NE(e,t){return typeof e==`object`&&!!e&&t in e}function PE(e,t){return e!=null&&typeof e!=`object`&&e.hasOwnProperty&&e.hasOwnProperty(t)}var FE=RegExp.prototype.test;function IE(e,t){return FE.call(e,t)}var LE=/\S/;function RE(e){return!IE(LE,e)}var zE={"&":`&amp;`,"<":`&lt;`,">":`&gt;`,'"':`&quot;`,"'":`&#39;`,"/":`&#x2F;`,"`":`&#x60;`,"=":`&#x3D;`};function BE(e){return String(e).replace(/[&<>"'`=\/]/g,function(e){return zE[e]})}var VE=/\s*/,HE=/\s+/,UE=/\s*=/,WE=/\s*\}/,GE=/#|\^|\/|>|\{|&|=|!/;function KE(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(HE,2)),!kE(e)||e.length!==2)throw Error(`Invalid tags: `+e);d=RegExp(ME(e[0])+`\\s*`),f=RegExp(`\\s*`+ME(e[1])),p=RegExp(`\\s*`+ME(`}`+e[1]))}m(t||QE.tags);for(var h=new YE(e),g,_,v,y,b,ee;!h.eos();){if(g=h.pos,v=h.scanUntil(d),v)for(var te=0,ne=v.length;te<ne;++te)y=v.charAt(te),RE(y)?(a.push(i.length),c+=y):(s=!0,n=!0,c+=` `),i.push([`text`,y,g,g+1]),g+=1,y===`
162
- `&&(u(),c=``,l=0,n=!1);if(!h.scan(d))break;if(o=!0,_=h.scan(GE)||`name`,h.scan(VE),_===`=`?(v=h.scanUntil(UE),h.scan(UE),h.scanUntil(f)):_===`{`?(v=h.scanUntil(p),h.scan(WE),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 JE(qE(i))}function qE(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 JE(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 YE(e){this.string=e,this.tail=e,this.pos=0}YE.prototype.eos=function(){return this.tail===``},YE.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},YE.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 XE(e,t){this.view=e,this.cache={".":this.view},this.parent=t}XE.prototype.push=function(e){return new XE(e,this)},XE.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=NE(i,a[o])||PE(i,a[o])),i=i[a[o++]];else i=r.view[e],s=NE(r.view,e);if(s){n=i;break}r=r.parent}t[e]=n}return AE(n)&&(n=n.call(this.view)),n};function ZE(){this.templateCache={_cache:{},set:function(e,t){this._cache[e]=t},get:function(e){return this._cache[e]},clear:function(){this._cache={}}}}ZE.prototype.clearCache=function(){this.templateCache!==void 0&&this.templateCache.clear()},ZE.prototype.parse=function(e,t){var n=this.templateCache,r=e+`:`+(t||QE.tags).join(`:`),i=n!==void 0,a=i?n.get(r):void 0;return a??(a=KE(e,t),i&&n.set(r,a)),a},ZE.prototype.render=function(e,t,n,r){var i=this.getConfigTags(r),a=this.parse(e,i),o=t instanceof XE?t:new XE(t,void 0);return this.renderTokens(a,o,n,e,r)},ZE.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},ZE.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(kE(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(AE(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}},ZE.prototype.renderInverted=function(e,t,n,r,i){var a=t.lookup(e[1]);if(!a||kE(a)&&a.length===0)return this.renderTokens(e[4],t,n,r,i)},ZE.prototype.indentPartial=function(e,t,n){for(var r=t.replace(/[^ \t]/g,``),i=e.split(`
160
+ `).trim(),yT=e=>{if(Object.keys(e).length===0)return{};let t={};return e.children.length>0?(t[e.name]=e.children.map(yT),t):(t[e.name]=e.text??void 0,t)};function bT(e){let t=vT(e),n=hT.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]),yT(r)}var xT=o({AsymmetricStructuredOutputParser:()=>mT,BaseCumulativeTransformOutputParser:()=>nT,BaseLLMOutputParser:()=>Qw,BaseOutputParser:()=>$w,BaseTransformOutputParser:()=>tT,BytesOutputParser:()=>rT,CommaSeparatedListOutputParser:()=>aT,CustomListOutputParser:()=>oT,JsonMarkdownStructuredOutputParser:()=>pT,JsonOutputParser:()=>uT,ListOutputParser:()=>iT,MarkdownListOutputParser:()=>cT,NumberedListOutputParser:()=>sT,OutputParserException:()=>eT,StandardSchemaOutputParser:()=>dT,StringOutputParser:()=>lT,StructuredOutputParser:()=>fT,XMLOutputParser:()=>_T,XML_FORMAT_INSTRUCTIONS:()=>gT,parseJsonMarkdown:()=>v,parsePartialJson:()=>b,parseXMLMarkdown:()=>bT}),ST=o({extendInteropZodObject:()=>Bg,getInteropZodDefaultGetter:()=>Wg,getInteropZodObjectShape:()=>zg,getSchemaDescription:()=>Ag,interopParse:()=>kg,interopParseAsync:()=>Dg,interopSafeParse:()=>Og,interopSafeParseAsync:()=>Eg,interopZodObjectMakeFieldsOptional:()=>Yg,interopZodObjectPartial:()=>Vg,interopZodObjectPassthrough:()=>Ug,interopZodObjectStrict:()=>Hg,interopZodTransformInputSchema:()=>Jg,isInteropZodError:()=>Xg,isInteropZodLiteral:()=>Tg,isInteropZodObject:()=>Rg,isInteropZodSchema:()=>Sg,isShapelessZodSchema:()=>jg,isSimpleStringZodSchema:()=>Mg,isZodArrayV4:()=>Fg,isZodLiteralV3:()=>Cg,isZodLiteralV4:()=>wg,isZodNullableV4:()=>Lg,isZodObjectV3:()=>Ng,isZodObjectV4:()=>Pg,isZodOptionalV4:()=>Ig,isZodSchema:()=>xg,isZodSchemaV3:()=>bg,isZodSchemaV4:()=>yg});function CT(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 eT([`Function "${e.function.name}" arguments:`,``,e.function.arguments,``,`are not valid JSON.`,`Error: ${t.message}`].join(`
161
+ `))}let r={name:e.function.name,args:n,type:`tool_call`};return t?.returnId&&(r.id=e.id),r}function wT(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 TT(e,t){return{name:e.function?.name,args:e.function?.arguments,id:e.id,error:t,type:`invalid_tool_call`}}var ET=class extends nT{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(Yt(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=>CT(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}},DT=class extends ET{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 eT(`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 Eg(this.zodSchema,e);if(t.success)return t.data;throw new eT(`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)))}},OT=o({assembleStructuredOutputPipeline:()=>jT,createContentParser:()=>kT,createFunctionCallingParser:()=>AT});function kT(e){return Sg(e)?fT.fromZodSchema(e):zy(e)?dT.fromSerializableSchema(e):new uT}function AT(e,t,n){let r=n??DT;return Sg(e)?new r({returnSingle:!0,keyName:t,zodSchema:e}):zy(e)?new r({returnSingle:!0,keyName:t,serializableSchema:e}):new r({returnSingle:!0,keyName:t})}function jT(e,t,n,r){if(!n){let n=e.pipe(t);return r?n.withConfig({runName:r}):n}let i=ax.assign({parsed:(e,n)=>t.invoke(e.raw,n)}),a=ax.assign({parsed:()=>null}),o=i.withFallbacks({fallbacks:[a]}),s=qb.from([{raw:e},o]);return r?s.withConfig({runName:r}):s}var MT=o({ChatModelStream:()=>GT,ReasoningContentStream:()=>UT,TextContentStream:()=>VT,ToolCallsStream:()=>HT,UsageMetadataStream:()=>WT}),NT=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 PT(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 FT(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 IT(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 LT(e){if(typeof e!=`object`||!e)return!1;let t=e.type;return t===`reasoning`||t===`thinking`}function RT(e){if(e)return{...e,input_tokens:e.input_tokens??0,output_tokens:e.output_tokens??0,total_tokens:e.total_tokens??0}}function zT(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 BT(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:zT(r)}}var VT=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=FT(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=FT(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)}},HT=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)}},UT=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(!LT(r.content)){if(n)return;continue}n=!0;let e=IT(r.content);if(e==null||e.length===0)continue;t+=e,yield t}else if(r.event===`content-block-delta`){let e=FT(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`&&LT(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(!LT(n.content)){if(t)return;continue}t=!0;let e=IT(n.content);e!=null&&e.length>0&&(yield e)}else if(n.event===`content-block-delta`){let e=FT(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`&&LT(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)}},WT=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=RT(t.usage);e&&(yield e)}else if(t.event===`message-start`&&t.usage){let e=RT(t.usage);e&&(yield e)}else if(t.event===`message-finish`&&t.usage){let e=RT(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)}},GT=class{_buffer;constructor(e){this._buffer=new NT,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 VT(this._buffer)}get toolCalls(){return new HT(this._buffer)}get reasoning(){return new UT(this._buffer)}get usage(){return new WT(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=RT(a.usage));break;case`content-block-start`:e[a.index]=a.content;break;case`content-block-delta`:{let t=e[a.index],n=FT(a);t&&n&&(e[a.index]=PT(t,n));break}case`content-block-finish`:e[a.index]=a.content;break;case`usage`:n=RT(a.usage);break;case`message-finish`:i=a.reason,a.usage&&(n=RT(a.usage)),a.responseMetadata&&(r={...r,...a.responseMetadata});break;default:break}let a=e.filter(e=>e!=null).map(BT);return new Jt({id:t,content:a,usage_metadata:n,response_metadata:{...r,...i?{finish_reason:i}:{},output_version:`v1`}})}},KT=o({convertChunksToEvents:()=>$T,finalizeContentBlock:()=>nE}),qT={wav:`audio/wav`,mp3:`audio/mpeg`,flac:`audio/flac`,opus:`audio/opus`,aac:`audio/aac`,pcm16:`audio/pcm`},JT={png:`image/png`,jpeg:`image/jpeg`,jpg:`image/jpeg`,webp:`image/webp`,gif:`image/gif`};function YT(e){let t=0;for(let n of e.keys())n>=t&&(t=n+1);return t}function XT(e){let t=e.additional_kwargs;return typeof t==`object`&&t?t:{}}function ZT(e){let t=XT(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:JT[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 QT(e){let t=XT(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:qT[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*$T(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};Zt.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=tE(e);r.accumulated=eE(r.accumulated,i),yield{event:`content-block-delta`,index:t,delta:i}}}if(Zt.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=QT(e);if(u!=null){if(a==null){let e=YT(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 ZT(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=YT(n);n.set(i,{type:`image`,accumulated:t}),yield{event:`content-block-start`,index:i,content:t}}if(!c&&Zt.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:nE(t.accumulated)};yield{event:`message-finish`,reason:`stop`,...i?{usage:i}:{}}}function eE(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 tE(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 nE(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 rE=e=>e();function iE(e){let t=e.constructor;return new t({...e,content:e.contentBlocks,response_metadata:{...e.response_metadata,output_version:`v1`}})}var aE=o({BaseChatModel:()=>sE,SimpleChatModel:()=>cE});function oE(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];(ye(r)||be(r))&&e===n&&(e=new n.constructor({...e,content:[...n.content.slice(0,t),Ce(r),...n.content.slice(t+1)]}))}t.push(e)}return t}var sE=class e extends Xw{lc_namespace=[`langchain`,`chat_models`,this._llmType()];disableStreaming=!1;outputVersion;get callKeys(){return[...super.callKeys,`outputVersion`]}constructor(e){super(e),this.outputVersion=rE(()=>{let t=e.outputVersion??mr(`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*$T(this._streamResponseChunks(e,t,n),{signal:t.signal})}streamV2(t,n){let r=e._convertInputToPromptValue(t).toChatMessages(),[,i]=this._separateRunnableConfigFromCallOptionsCompat(n);return new GT(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 yl.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(),[oE(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 iE(e.message):yield e.message,f=f?f.concat(e):e,Xt(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(bn)),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 yl.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(oE),r.runId,void 0,s,void 0,void 0,r.runName)}let s=n.outputVersion??this.outputVersion,c=[],l=[],u=!!o?.[0].handlers.find(vr),d=!!o?.[0].handlers.find(_r);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 GT({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:zl(t,i),Xt(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=iE(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,xu,{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(bn)),s={...a.metadata,...this.getLsParamsWithDefaults(i)},c=this.invocationParams(i),l=await yl.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(oE),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&&mt(e.message)&&Yt(e.message)&&(e.message.usage_metadata={input_tokens:0,output_tokens:0,total_tokens:0},m===`v1`&&(e.message=iE(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,xu,{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(bn)),[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=Ag(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`;!Sg(n)&&!zy(n)&&`name`in n&&(s=n.name);let c=Sg(n)||zy(n)?Eb(n):n,l=[{type:`function`,function:{name:s,description:i,parameters:c}}];return jT(this.bindTools(l),Zb.from(e=>{if(!Zt.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`)}},cE=class extends sE{async _generate(e,t,n){let r=new Jt(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}]}}},lE=o({}),uE=o({BaseLLM:()=>dE,LLM:()=>fE}),dE=class e extends Xw{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 yl.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 Su({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 yl.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(_r),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:zl(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,xu,{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 yl.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,xu,{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`}},fE=class extends dE{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}])))}}},pE=o({}),mE=o({BaseMemory:()=>hE,getInputValue:()=>_E,getOutputValue:()=>vE,getPromptInputKey:()=>yE}),hE=class{},gE=(e,t)=>{if(t!==void 0)return e[t];let n=Object.keys(e);if(n.length===1)return e[n[0]]},_E=(e,t)=>{let n=gE(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},vE=(e,t)=>{let n=gE(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 yE(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 bE=class extends Qw{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)}`)}},xE=class extends nT{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 bE(e)}_diff(e,t){if(t)return du(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``}},SE=class extends Qw{static lc_name(){return`JsonKeyOutputFunctionsParser`}lc_namespace=[`langchain`,`output_parsers`,`openai_functions`];lc_serializable=!0;outputParser=new xE;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]}},CE=o({JsonKeyOutputFunctionsParser:()=>SE,JsonOutputFunctionsParser:()=>xE,OutputFunctionsParser:()=>bE}),wE=o({JsonOutputKeyToolsParser:()=>DT,JsonOutputToolsParser:()=>ET,convertLangChainToolCallToOpenAI:()=>wT,makeInvalidToolCall:()=>TT,parseToolCall:()=>CT}),TE=class extends Ub{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`})}},EE=class extends TE{async formatPromptValue(e){return new ww(await this.format(e))}},DE=Object.prototype.toString,OE=Array.isArray||function(e){return DE.call(e)===`[object Array]`};function kE(e){return typeof e==`function`}function AE(e){return OE(e)?`array`:typeof e}function jE(e){return e.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,`\\$&`)}function ME(e,t){return typeof e==`object`&&!!e&&t in e}function NE(e,t){return e!=null&&typeof e!=`object`&&e.hasOwnProperty&&e.hasOwnProperty(t)}var PE=RegExp.prototype.test;function FE(e,t){return PE.call(e,t)}var IE=/\S/;function LE(e){return!FE(IE,e)}var RE={"&":`&amp;`,"<":`&lt;`,">":`&gt;`,'"':`&quot;`,"'":`&#39;`,"/":`&#x2F;`,"`":`&#x60;`,"=":`&#x3D;`};function zE(e){return String(e).replace(/[&<>"'`=\/]/g,function(e){return RE[e]})}var BE=/\s*/,VE=/\s+/,HE=/\s*=/,UE=/\s*\}/,WE=/#|\^|\/|>|\{|&|=|!/;function GE(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(VE,2)),!OE(e)||e.length!==2)throw Error(`Invalid tags: `+e);d=RegExp(jE(e[0])+`\\s*`),f=RegExp(`\\s*`+jE(e[1])),p=RegExp(`\\s*`+jE(`}`+e[1]))}m(t||ZE.tags);for(var h=new JE(e),g,_,v,y,b,ee;!h.eos();){if(g=h.pos,v=h.scanUntil(d),v)for(var te=0,ne=v.length;te<ne;++te)y=v.charAt(te),LE(y)?(a.push(i.length),c+=y):(s=!0,n=!0,c+=` `),i.push([`text`,y,g,g+1]),g+=1,y===`
162
+ `&&(u(),c=``,l=0,n=!1);if(!h.scan(d))break;if(o=!0,_=h.scan(WE)||`name`,h.scan(BE),_===`=`?(v=h.scanUntil(HE),h.scan(HE),h.scanUntil(f)):_===`{`?(v=h.scanUntil(p),h.scan(UE),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 qE(KE(i))}function KE(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 qE(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 JE(e){this.string=e,this.tail=e,this.pos=0}JE.prototype.eos=function(){return this.tail===``},JE.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},JE.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 YE(e,t){this.view=e,this.cache={".":this.view},this.parent=t}YE.prototype.push=function(e){return new YE(e,this)},YE.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=ME(i,a[o])||NE(i,a[o])),i=i[a[o++]];else i=r.view[e],s=ME(r.view,e);if(s){n=i;break}r=r.parent}t[e]=n}return kE(n)&&(n=n.call(this.view)),n};function XE(){this.templateCache={_cache:{},set:function(e,t){this._cache[e]=t},get:function(e){return this._cache[e]},clear:function(){this._cache={}}}}XE.prototype.clearCache=function(){this.templateCache!==void 0&&this.templateCache.clear()},XE.prototype.parse=function(e,t){var n=this.templateCache,r=e+`:`+(t||ZE.tags).join(`:`),i=n!==void 0,a=i?n.get(r):void 0;return a??(a=GE(e,t),i&&n.set(r,a)),a},XE.prototype.render=function(e,t,n,r){var i=this.getConfigTags(r),a=this.parse(e,i),o=t instanceof YE?t:new YE(t,void 0);return this.renderTokens(a,o,n,e,r)},XE.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},XE.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(OE(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(kE(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}},XE.prototype.renderInverted=function(e,t,n,r,i){var a=t.lookup(e[1]);if(!a||OE(a)&&a.length===0)return this.renderTokens(e[4],t,n,r,i)},XE.prototype.indentPartial=function(e,t,n){for(var r=t.replace(/[^ \t]/g,``),i=e.split(`
163
163
  `),a=0;a<i.length;a++)i[a].length&&(a>0||!n)&&(i[a]=r+i[a]);return i.join(`
164
- `)},ZE.prototype.renderPartial=function(e,t,n,r){if(n){var i=this.getConfigTags(r),a=AE(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)}}},ZE.prototype.unescapedValue=function(e,t){var n=t.lookup(e[1]);if(n!=null)return n},ZE.prototype.escapedValue=function(e,t,n){var r=this.getConfigEscape(n)||QE.escape,i=t.lookup(e[1]);if(i!=null)return typeof i==`number`&&r===QE.escape?String(i):r(i)},ZE.prototype.rawValue=function(e){return e[1]},ZE.prototype.getConfigTags=function(e){if(kE(e))return e;if(e&&typeof e==`object`)return e.tags},ZE.prototype.getConfigEscape=function(e){if(e&&typeof e==`object`&&!kE(e))return e.escape};var QE={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){$E.templateCache=e},get templateCache(){return $E.templateCache}},$E=new ZE;QE.clearCache=function(){return $E.clearCache()},QE.parse=function(e,t){return $E.parse(e,t)},QE.render=function(e,t,n,r){if(typeof e!=`string`)throw TypeError(`Invalid template! Template should be a "string" but "`+jE(e)+`" was given as the first argument for mustache#render(template, view, partials)`);return $E.render(e,t,n,r)},QE.escape=BE,QE.Scanner=YE,QE.Context=XE,QE.Writer=ZE;function eD(){QE.escape=e=>e}var tD=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},nD=(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=nD(r[4],e);n.push(...i)}}else n.push({type:`literal`,text:r[1]});return n},rD=e=>(eD(),nD(QE.parse(e))),iD=(e,t)=>tD(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},``),aD=(e,t)=>(eD(),QE.render(e,t)),oD={"f-string":iD,mustache:aD},sD={"f-string":tD,mustache:rD},cD=(e,t,n)=>{try{return oD[t](e,n)}catch(e){throw u(e,`INVALID_PROMPT_INPUT`)}},lD=(e,t)=>sD[t](e),uD=(e,t,n)=>{if(!(t in oD))throw Error(`Invalid template format. Got \`${t}\`;
165
- should be one of ${Object.keys(oD)}`);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`)cD(e.text,t,r);else if(e.type===`image_url`){if(typeof e.image_url==`string`)cD(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;cD(n,t,r)}}else throw Error(`Invalid message template received. ${JSON.stringify(e,null,2)}`)}):cD(e,t,r)}catch(e){throw Error(`Invalid prompt schema: ${e.message}`)}},dD=class e extends DE{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))),uD(this.template,this.templateFormat,e)}}_getPromptType(){return`prompt`}async format(e){let t=await this.mergePartialAndUserVariables(e);return cD(this.template,this.templateFormat,t)}static fromExamples(t,n,r,i=`
164
+ `)},XE.prototype.renderPartial=function(e,t,n,r){if(n){var i=this.getConfigTags(r),a=kE(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)}}},XE.prototype.unescapedValue=function(e,t){var n=t.lookup(e[1]);if(n!=null)return n},XE.prototype.escapedValue=function(e,t,n){var r=this.getConfigEscape(n)||ZE.escape,i=t.lookup(e[1]);if(i!=null)return typeof i==`number`&&r===ZE.escape?String(i):r(i)},XE.prototype.rawValue=function(e){return e[1]},XE.prototype.getConfigTags=function(e){if(OE(e))return e;if(e&&typeof e==`object`)return e.tags},XE.prototype.getConfigEscape=function(e){if(e&&typeof e==`object`&&!OE(e))return e.escape};var ZE={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){QE.templateCache=e},get templateCache(){return QE.templateCache}},QE=new XE;ZE.clearCache=function(){return QE.clearCache()},ZE.parse=function(e,t){return QE.parse(e,t)},ZE.render=function(e,t,n,r){if(typeof e!=`string`)throw TypeError(`Invalid template! Template should be a "string" but "`+AE(e)+`" was given as the first argument for mustache#render(template, view, partials)`);return QE.render(e,t,n,r)},ZE.escape=zE,ZE.Scanner=JE,ZE.Context=YE,ZE.Writer=XE;function $E(){ZE.escape=e=>e}var eD=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},tD=(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=tD(r[4],e);n.push(...i)}}else n.push({type:`literal`,text:r[1]});return n},nD=e=>($E(),tD(ZE.parse(e))),rD=(e,t)=>eD(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},``),iD=(e,t)=>($E(),ZE.render(e,t)),aD={"f-string":rD,mustache:iD},oD={"f-string":eD,mustache:nD},sD=(e,t,n)=>{try{return aD[t](e,n)}catch(e){throw u(e,`INVALID_PROMPT_INPUT`)}},cD=(e,t)=>oD[t](e),lD=(e,t,n)=>{if(!(t in aD))throw Error(`Invalid template format. Got \`${t}\`;
165
+ should be one of ${Object.keys(aD)}`);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`)sD(e.text,t,r);else if(e.type===`image_url`){if(typeof e.image_url==`string`)sD(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;sD(n,t,r)}}else throw Error(`Invalid message template received. ${JSON.stringify(e,null,2)}`)}):sD(e,t,r)}catch(e){throw Error(`Invalid prompt schema: ${e.message}`)}},uD=class e extends EE{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))),lD(this.template,this.templateFormat,e)}}_getPromptType(){return`prompt`}async format(e){let t=await this.mergePartialAndUserVariables(e);return sD(this.template,this.templateFormat,t)}static fromExamples(t,n,r,i=`
166
166
 
167
- `,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 lD(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})}},fD=class e extends EE{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))),uD([{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]=cD(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 Dw(await this.format(e))}},pD=class extends Wb{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=mD(e.template,t);super({inputVariables:n,...e}),this.template=e.template,this.templateFormat=t,this.inputVariables=n}async format(e){return hD(this.template,e,this.templateFormat)}async invoke(e){return await this._callWithConfig(this.format.bind(this),e,{runType:`prompt`})}};function mD(e,t){let n=[];for(let r of Object.values(e))if(typeof r==`string`)lD(r,t).forEach(e=>{e.type===`variable`&&n.push(e.name)});else if(Array.isArray(r))for(let e of r)typeof e==`string`?lD(e,t).forEach(e=>{e.type===`variable`&&n.push(e.name)}):typeof e==`object`&&n.push(...mD(e,t));else typeof r==`object`&&r&&n.push(...mD(r,t));return Array.from(new Set(n))}function hD(e,t,n){let r={};for(let[i,a]of Object.entries(e))if(typeof a==`string`)r[i]=cD(a,n,t);else if(Array.isArray(a)){let e=[];for(let r of a)typeof r==`string`?e.push(cD(r,n,t)):typeof r==`object`&&e.push(hD(r,t,n));r[i]=e}else typeof a==`object`&&a?r[i]=hD(a,t,n):r[i]=a;return r}var gD=class extends Wb{lc_namespace=[`langchain_core`,`prompts`,`chat`];lc_serializable=!0;async invoke(e,t){return this._callWithConfig(e=>this.formatMessages(e),e,{...t,runType:`prompt`})}},_D=class extends gD{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(bn):[bn(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(`
167
+ `,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 cD(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})}},dD=class e extends TE{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))),lD([{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]=sD(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 Ew(await this.format(e))}},fD=class extends Ub{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=pD(e.template,t);super({inputVariables:n,...e}),this.template=e.template,this.templateFormat=t,this.inputVariables=n}async format(e){return mD(this.template,e,this.templateFormat)}async invoke(e){return await this._callWithConfig(this.format.bind(this),e,{runType:`prompt`})}};function pD(e,t){let n=[];for(let r of Object.values(e))if(typeof r==`string`)cD(r,t).forEach(e=>{e.type===`variable`&&n.push(e.name)});else if(Array.isArray(r))for(let e of r)typeof e==`string`?cD(e,t).forEach(e=>{e.type===`variable`&&n.push(e.name)}):typeof e==`object`&&n.push(...pD(e,t));else typeof r==`object`&&r&&n.push(...pD(r,t));return Array.from(new Set(n))}function mD(e,t,n){let r={};for(let[i,a]of Object.entries(e))if(typeof a==`string`)r[i]=sD(a,n,t);else if(Array.isArray(a)){let e=[];for(let r of a)typeof r==`string`?e.push(sD(r,n,t)):typeof r==`object`&&e.push(mD(r,t,n));r[i]=e}else typeof a==`object`&&a?r[i]=mD(a,t,n):r[i]=a;return r}var hD=class extends Ub{lc_namespace=[`langchain_core`,`prompts`,`chat`];lc_serializable=!0;async invoke(e,t){return this._callWithConfig(e=>this.formatMessages(e),e,{...t,runType:`prompt`})}},gD=class extends hD{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(bn):[bn(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(`
168
168
 
169
- `));throw r.name=`InputFormatError`,r.lc_error_code=e.lc_error_code,r}return n}},vD=class extends gD{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)]}},yD=class extends EE{constructor(e){super(e)}async format(e){return(await this.formatPromptValue(e)).toString()}async formatPromptValue(e){return new Ew(await this.formatMessages(e))}},bD=class extends vD{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 Qt(await this.prompt.format(e),this.role)}static fromTemplate(e,t,n){return new this(dD.fromTemplate(e,{templateFormat:n?.templateFormat}),t)}};function xD(e){return typeof e!=`object`||!e||Array.isArray(e)?!1:Object.keys(e).length===1&&`text`in e&&typeof e.text==`string`}function SD(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 CD=class extends gD{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(dD.fromTemplate(e,t));let n=[];for(let r of e)if(typeof r==`string`)n.push(dD.fromTemplate(r,t));else if(r!==null)if(xD(r)){let e=``;typeof r.text==`string`&&(e=r.text??``);let i={...t,additionalContentFields:r};n.push(dD.fromTemplate(e,i))}else if(SD(r)){let e=r.image_url??``,i,a=[];if(typeof e==`string`){let n;n=t?.templateFormat===`mustache`?rD(e):tD(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 fD({template:e,inputVariables:a,templateFormat:t?.templateFormat,additionalContentFields:r})}else if(typeof e==`object`){if(`url`in e){let n;n=t?.templateFormat===`mustache`?rD(e.url):tD(e.url),a=n.flatMap(e=>e.type===`variable`?[e.name]:[])}else a=[];i=new fD({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 pD({template:r,templateFormat:t?.templateFormat}));return new this({prompt:n,additionalOptions:t})}async format(e){if(this.prompt instanceof DE){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 DE){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 fD){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 pD){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)]}},wD=class extends CD{static _messageClass(){return sn}static lc_name(){return`HumanMessagePromptTemplate`}},TD=class extends CD{static _messageClass(){return Jt}static lc_name(){return`AIMessagePromptTemplate`}},ED=class extends CD{static _messageClass(){return fn}static lc_name(){return`SystemMessagePromptTemplate`}};function DD(e){return typeof e.formatMessages==`function`}function OD(e,t){if(DD(e)||mt(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 _D({variableName:n.slice(2,-2),optional:!0});if(typeof n==`string`&&n[0]===`{`&&n[n.length-1]===`}`)return new _D({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=bn(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 wD.fromTemplate(r,t);if(n._getType()===`ai`)return TD.fromTemplate(r,t);if(n._getType()===`system`)return ED.fromTemplate(r,t);if(Qt.isInstance(n))return bD.fromTemplate(n.content,n.role,t);throw Error(`Could not coerce message prompt template from input. Received message type: "${n._getType()}".`)}function kD(e){return e.constructor.lc_name()===`MessagesPlaceholder`}var AD=class e extends yD{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 nt))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 dD.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 nt)n.push(await this._parseImagePrompts(e,t));else{let r;r=this.templateFormat===`mustache`?{...t}:e.inputVariables.reduce((n,r)=>{if(!(r in t)&&!(kD(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 wD({prompt:dD.fromTemplate(e,t)});return this.fromMessages([n])}static fromMessages(t,n){let r=t.reduce((t,r)=>t.concat(r instanceof e?r.promptMessages:[OD(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 nt))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})}},jD=class e extends DE{lc_serializable=!1;examples;exampleSelector;examplePrompt;suffix=``;exampleSeparator=`
169
+ `));throw r.name=`InputFormatError`,r.lc_error_code=e.lc_error_code,r}return n}},_D=class extends hD{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)]}},vD=class extends TE{constructor(e){super(e)}async format(e){return(await this.formatPromptValue(e)).toString()}async formatPromptValue(e){return new Tw(await this.formatMessages(e))}},yD=class extends _D{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 Qt(await this.prompt.format(e),this.role)}static fromTemplate(e,t,n){return new this(uD.fromTemplate(e,{templateFormat:n?.templateFormat}),t)}};function bD(e){return typeof e!=`object`||!e||Array.isArray(e)?!1:Object.keys(e).length===1&&`text`in e&&typeof e.text==`string`}function xD(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 SD=class extends hD{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(uD.fromTemplate(e,t));let n=[];for(let r of e)if(typeof r==`string`)n.push(uD.fromTemplate(r,t));else if(r!==null)if(bD(r)){let e=``;typeof r.text==`string`&&(e=r.text??``);let i={...t,additionalContentFields:r};n.push(uD.fromTemplate(e,i))}else if(xD(r)){let e=r.image_url??``,i,a=[];if(typeof e==`string`){let n;n=t?.templateFormat===`mustache`?nD(e):eD(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 dD({template:e,inputVariables:a,templateFormat:t?.templateFormat,additionalContentFields:r})}else if(typeof e==`object`){if(`url`in e){let n;n=t?.templateFormat===`mustache`?nD(e.url):eD(e.url),a=n.flatMap(e=>e.type===`variable`?[e.name]:[])}else a=[];i=new dD({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 fD({template:r,templateFormat:t?.templateFormat}));return new this({prompt:n,additionalOptions:t})}async format(e){if(this.prompt instanceof EE){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 EE){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 dD){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 fD){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)]}},CD=class extends SD{static _messageClass(){return sn}static lc_name(){return`HumanMessagePromptTemplate`}},wD=class extends SD{static _messageClass(){return Jt}static lc_name(){return`AIMessagePromptTemplate`}},TD=class extends SD{static _messageClass(){return fn}static lc_name(){return`SystemMessagePromptTemplate`}};function ED(e){return typeof e.formatMessages==`function`}function DD(e,t){if(ED(e)||mt(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 gD({variableName:n.slice(2,-2),optional:!0});if(typeof n==`string`&&n[0]===`{`&&n[n.length-1]===`}`)return new gD({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=bn(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 CD.fromTemplate(r,t);if(n._getType()===`ai`)return wD.fromTemplate(r,t);if(n._getType()===`system`)return TD.fromTemplate(r,t);if(Qt.isInstance(n))return yD.fromTemplate(n.content,n.role,t);throw Error(`Could not coerce message prompt template from input. Received message type: "${n._getType()}".`)}function OD(e){return e.constructor.lc_name()===`MessagesPlaceholder`}var kD=class e extends vD{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 nt))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 uD.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 nt)n.push(await this._parseImagePrompts(e,t));else{let r;r=this.templateFormat===`mustache`?{...t}:e.inputVariables.reduce((n,r)=>{if(!(r in t)&&!(OD(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 CD({prompt:uD.fromTemplate(e,t)});return this.fromMessages([n])}static fromMessages(t,n){let r=t.reduce((t,r)=>t.concat(r instanceof e?r.promptMessages:[DD(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 nt))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})}},AD=class e extends EE{lc_serializable=!1;examples;exampleSelector;examplePrompt;suffix=``;exampleSeparator=`
170
170
 
171
- `;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))),uD(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 cD([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 dD.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})}},MD=class e extends yD{lc_serializable=!0;examples;exampleSelector;examplePrompt;suffix=``;exampleSeparator=`
171
+ `;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))),lD(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 sD([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 uD.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})}},jD=class e extends vD{lc_serializable=!0;examples;exampleSelector;examplePrompt;suffix=``;exampleSeparator=`
172
172
 
173
173
  `;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??`
174
174
 
175
- `,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))),uD(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 cD([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})}},ND=class e extends EE{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 AD?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 PD(e){return typeof e==`object`&&!!e&&`withStructuredOutput`in e&&typeof e.withStructuredOutput==`function`}function FD(e){return typeof e==`object`&&!!e&&`lc_id`in e&&Array.isArray(e.lc_id)&&e.lc_id.join(`/`)===`langchain_core/runnables/RunnableBinding`}var ID=class e extends AD{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(PD(e))return super.pipe(e.withStructuredOutput(this.schema));if(FD(e)&&PD(e.bound))return super.pipe(new Gb({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})}},LD=o({AIMessagePromptTemplate:()=>TD,BaseChatPromptTemplate:()=>yD,BaseMessagePromptTemplate:()=>gD,BaseMessageStringPromptTemplate:()=>vD,BasePromptTemplate:()=>EE,BaseStringPromptTemplate:()=>DE,ChatMessagePromptTemplate:()=>bD,ChatPromptTemplate:()=>AD,DEFAULT_FORMATTER_MAPPING:()=>oD,DEFAULT_PARSER_MAPPING:()=>sD,DictPromptTemplate:()=>pD,FewShotChatMessagePromptTemplate:()=>MD,FewShotPromptTemplate:()=>jD,HumanMessagePromptTemplate:()=>wD,ImagePromptTemplate:()=>fD,MessagesPlaceholder:()=>_D,PipelinePromptTemplate:()=>ND,PromptTemplate:()=>dD,StructuredPrompt:()=>ID,SystemMessagePromptTemplate:()=>ED,checkValidTemplate:()=>uD,interpolateFString:()=>iD,interpolateMustache:()=>aD,parseFString:()=>tD,parseMustache:()=>rD,parseTemplate:()=>lD,renderTemplate:()=>cD}),RD=o({BaseDocumentCompressor:()=>zD}),zD=class{static isBaseDocumentCompressor(e){return e?.compressDocuments!==void 0}},BD=o({BaseRetriever:()=>VD}),VD=class extends Wb{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=jl(fl(t)),r=await(await yl.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}}},HD=o({BaseStore:()=>UD,InMemoryStore:()=>WD}),UD=class extends _e{},WD=class extends UD{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)}},GD={and:`and`,or:`or`,not:`not`},KD={eq:`eq`,ne:`ne`,lt:`lt`,gt:`gt`,lte:`lte`,gte:`gte`},qD=class{},JD=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`)}},YD=class extends JD{},XD=class extends YD{exprName=`Comparison`;constructor(e,t,n){super(),this.comparator=e,this.attribute=t,this.value=n}},ZD=class extends YD{exprName=`Operation`;constructor(e,t){super(),this.operator=e,this.args=t}},QD=class extends JD{exprName=`StructuredQuery`;constructor(e,t){super(),this.query=e,this.filter=t}};function $D(e){return e&&typeof e==`object`&&!Array.isArray(e)}function eO(e){return e?typeof e==`string`&&e.length>0||typeof e==`function`?!1:$D(e)&&Object.keys(e).length===0:!0}function tO(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 nO(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 rO(e){return typeof e==`string`&&(Number.isNaN(parseFloat(e))||parseFloat(e).toString()!==e)}function iO(e){return typeof e==`boolean`}function aO(e){let t;if(rO(e))t=e;else if(tO(e))t=parseInt(e,10);else if(nO(e))t=parseFloat(e);else if(iO(e))t=!!e;else throw Error(`Unsupported value type`);return t}var oO=class extends qD{},sO=class extends oO{allowedOperators;allowedComparators;constructor(e){super(),this.allowedOperators=e?.allowedOperators??[GD.and,GD.or],this.allowedComparators=e?.allowedComparators??[KD.eq,KD.ne,KD.gt,KD.gte,KD.lt,KD.lte]}formatFunction(e){if(e in KD){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 GD){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)]:aO(e.value)}}}visitStructuredQuery(e){let t={};return e.filter&&(t={filter:e.filter.accept(this)}),t}mergeFilters(e,t,n=`and`,r=!1){if(!(eO(e)&&eO(t))){if(eO(e)||n===`replace`)return eO(t)?void 0:t;if(eO(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`)}}},cO=class extends oO{allowedOperators=[GD.and,GD.or];allowedComparators=[KD.eq,KD.ne,KD.gt,KD.gte,KD.lt,KD.lte];formatFunction(){throw Error(`Not implemented`)}getAllowedComparatorsForType(e){switch(e){case`string`:return[KD.eq,KD.ne,KD.gt,KD.gte,KD.lt,KD.lte];case`number`:return[KD.eq,KD.ne,KD.gt,KD.gte,KD.lt,KD.lte];case`boolean`:return[KD.eq,KD.ne];default:throw Error(`Unsupported data type: ${e}`)}}getComparatorFunction(e){switch(e){case KD.eq:return(e,t)=>e===t;case KD.ne:return(e,t)=>e!==t;case KD.gt:return(e,t)=>e>t;case KD.gte:return(e,t)=>e>=t;case KD.lt:return(e,t)=>e<t;case KD.lte:return(e,t)=>e<=t;default:throw Error(`Unknown comparator`)}}getOperatorFunction(e){switch(e){case GD.and:return(e,t)=>e&&t;case GD.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=[KD.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,aO(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(!(eO(e)&&eO(t))){if(eO(e)||n===`replace`)return eO(t)?void 0:t;if(eO(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`)}}},lO=o({BaseTranslator:()=>oO,BasicTranslator:()=>sO,Comparators:()=>KD,Comparison:()=>XD,Expression:()=>JD,FilterDirective:()=>YD,FunctionalTranslator:()=>cO,Operation:()=>ZD,Operators:()=>GD,StructuredQuery:()=>QD,Visitor:()=>qD,castValue:()=>aO,isBoolean:()=>iO,isFilterEmpty:()=>eO,isFloat:()=>nO,isInt:()=>tO,isObject:()=>$D,isString:()=>rO});function uO(e){return nt.isInstance(e)?e.constructor.name||e.type:typeof e}function dO(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: ${uO(n)}`,actual:uO(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 fO=dO(`HumanMessage`,sn.isInstance),pO=dO(`AIMessage`,Jt.isInstance),mO=dO(`SystemMessage`,fn.isInstance),hO=dO(`ToolMessage`,vt.isInstance);function gO(e,t){let{isNot:n,utils:r}=this;if(!Jt.isInstance(e))return{pass:!1,message:()=>`${r.matcherHint(`toHaveToolCalls`)}\n\nExpected: AIMessage\nReceived: ${uO(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 _O(e,t){let{isNot:n,utils:r}=this;if(!Jt.isInstance(e))return{pass:!1,message:()=>`${r.matcherHint(`toHaveToolCallCount`)}\n\nExpected: AIMessage\nReceived: ${uO(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 vO(e,t){let{isNot:n,utils:r}=this;if(!Jt.isInstance(e))return{pass:!1,message:()=>`${r.matcherHint(`toContainToolCall`)}\n\nExpected: AIMessage\nReceived: ${uO(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 yO(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(vt.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 bO(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 xO(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 SO={toBeHumanMessage:fO,toBeAIMessage:pO,toBeSystemMessage:mO,toBeToolMessage:hO,toHaveToolCalls:gO,toHaveToolCallCount:_O,toContainToolCall:vO,toHaveToolMessages:yO,toHaveBeenInterrupted:bO,toHaveStructuredResponse:xO};function CO(e){return e.map(e=>e.text).filter(Boolean).join(`-`)}var wO=0;function TO(){return wO+=1,`fake_tc_${wO}`}var EO=class e extends cE{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}):nt.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??TO(),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 Qb.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(!nt.isInstance(t))throw t;return{generations:[{text:``,message:t}]}}if(i.kind===`message`)return{generations:[{text:``,message:i.message}]};let a=CO(e);return{generations:[{text:a,message:new Jt({content:a,id:r.toString(),tool_calls:i.toolCalls.length>0?i.toolCalls.map(e=>({...e,type:`tool_call`})):void 0})}],llmOutput:{}}}};function DO(){return new EO}var OO=o({FakeBuiltModel:()=>EO,fakeModel:()=>DO,langchainMatchers:()=>SO,toBeAIMessage:()=>pO,toBeHumanMessage:()=>fO,toBeSystemMessage:()=>mO,toBeToolMessage:()=>hO,toContainToolCall:()=>vO,toHaveBeenInterrupted:()=>bO,toHaveStructuredResponse:()=>xO,toHaveToolCallCount:()=>_O,toHaveToolCalls:()=>gO,toHaveToolMessages:()=>yO});function kO(e){return e!==void 0&&Array.isArray(e.lc_namespace)}function AO(e){return e!==void 0&&Wb.isRunnable(e)&&`lc_name`in e.constructor&&typeof e.constructor.lc_name==`function`&&e.constructor.lc_name()===`RunnableToolLike`}function jO(e){return!!e&&typeof e==`object`&&`name`in e&&`schema`in e&&(Sg(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 MO(e){return jO(e)||AO(e)||kO(e)}var NO=A(`ZodISODateTime`,(e,t)=>{pp.init(e,t),ak.init(e,t)});function PO(e){return Wm(NO,e)}var FO=A(`ZodISODate`,(e,t)=>{mp.init(e,t),ak.init(e,t)});function IO(e){return Gm(FO,e)}var LO=A(`ZodISOTime`,(e,t)=>{hp.init(e,t),ak.init(e,t)});function RO(e){return Km(LO,e)}var zO=A(`ZodISODuration`,(e,t)=>{gp.init(e,t),ak.init(e,t)});function BO(e){return qm(zO,e)}var VO=A(`ZodError`,(e,t)=>{Pd.init(e,t),e.name=`ZodError`,Object.defineProperties(e,{format:{value:t=>Ld(e,t)},flatten:{value:t=>Id(e,t)},addIssue:{value:t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,Qu,2)}},addIssues:{value:t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,Qu,2)}},isEmpty:{get(){return e.issues.length===0}}})},{Parent:Error}),HO=Bd(VO),UO=Hd(VO),WO=Wd(VO),GO=Kd(VO),KO=Jd(VO),qO=Yd(VO),JO=Xd(VO),YO=Zd(VO),XO=Qd(VO),ZO=$d(VO),QO=ef(VO),$O=tf(VO),ek=new WeakMap;function tk(e,t,n){let r=Object.getPrototypeOf(e),i=ek.get(r);if(i||(i=new Set,ek.set(r,i)),!i.has(t)){i.add(t);for(let e in n){let t=n[e];Object.defineProperty(r,e,{configurable:!0,enumerable:!1,get(){let n=t.bind(this);return Object.defineProperty(this,e,{configurable:!0,writable:!0,enumerable:!0,value:n}),n},set(t){Object.defineProperty(this,e,{configurable:!0,writable:!0,enumerable:!0,value:t})}})}}}var nk=A(`ZodType`,(e,t)=>($f.init(e,t),Object.assign(e[`~standard`],{jsonSchema:{input:jh(e,`input`),output:jh(e,`output`)}}),e.toJSONSchema=Ah(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,`_def`,{value:t}),e.parse=(t,n)=>HO(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>WO(e,t,n),e.parseAsync=async(t,n)=>UO(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>GO(e,t,n),e.spa=e.safeParseAsync,e.encode=(t,n)=>KO(e,t,n),e.decode=(t,n)=>qO(e,t,n),e.encodeAsync=async(t,n)=>JO(e,t,n),e.decodeAsync=async(t,n)=>YO(e,t,n),e.safeEncode=(t,n)=>XO(e,t,n),e.safeDecode=(t,n)=>ZO(e,t,n),e.safeEncodeAsync=async(t,n)=>QO(e,t,n),e.safeDecodeAsync=async(t,n)=>$O(e,t,n),tk(e,`ZodType`,{check(...e){let t=this.def;return this.clone(od(t,{checks:[...t.checks??[],...e.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return gd(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(SA(e,t))},superRefine(e,t){return this.check(CA(e,t))},overwrite(e){return this.check(mh(e))},optional(){return rA(this)},exactOptional(){return aA(this)},nullable(){return sA(this)},nullish(){return rA(sA(this))},nonoptional(e){return pA(this,e)},array(){return Rk(this)},or(e){return Vk([this,e])},and(e){return Gk(this,e)},transform(e){return _A(this,tA(e))},default(e){return lA(this,e)},prefault(e){return dA(this,e)},catch(e){return hA(this,e)},pipe(e){return _A(this,e)},readonly(){return yA(this)},describe(e){let t=this.clone();return bm.add(t,{description:e}),t},meta(...e){if(e.length===0)return bm.get(this);let t=this.clone();return bm.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e){return e(this)}}),Object.defineProperty(e,`description`,{get(){return bm.get(e)?.description},configurable:!0}),e)),rk=A(`_ZodString`,(e,t)=>{ep.init(e,t),nk.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Nh(e,t,n,r);let n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,tk(e,`_ZodString`,{regex(...e){return this.check(ch(...e))},includes(...e){return this.check(dh(...e))},startsWith(...e){return this.check(fh(...e))},endsWith(...e){return this.check(ph(...e))},min(...e){return this.check(oh(...e))},max(...e){return this.check(ah(...e))},length(...e){return this.check(sh(...e))},nonempty(...e){return this.check(oh(1,...e))},lowercase(e){return this.check(lh(e))},uppercase(e){return this.check(uh(e))},trim(){return this.check(gh())},normalize(...e){return this.check(hh(...e))},toLowerCase(){return this.check(_h())},toUpperCase(){return this.check(vh())},slugify(){return this.check(yh())}})}),ik=A(`ZodString`,(e,t)=>{ep.init(e,t),rk.init(e,t),e.email=t=>e.check(Sm(ok,t)),e.url=t=>e.check(Om(lk,t)),e.jwt=t=>e.check(Um(wk,t)),e.emoji=t=>e.check(km(uk,t)),e.guid=t=>e.check(Cm(sk,t)),e.uuid=t=>e.check(wm(ck,t)),e.uuidv4=t=>e.check(Tm(ck,t)),e.uuidv6=t=>e.check(Em(ck,t)),e.uuidv7=t=>e.check(Dm(ck,t)),e.nanoid=t=>e.check(Am(dk,t)),e.guid=t=>e.check(Cm(sk,t)),e.cuid=t=>e.check(jm(fk,t)),e.cuid2=t=>e.check(Mm(pk,t)),e.ulid=t=>e.check(Nm(mk,t)),e.base64=t=>e.check(Bm(xk,t)),e.base64url=t=>e.check(Vm(Sk,t)),e.xid=t=>e.check(Pm(hk,t)),e.ksuid=t=>e.check(Fm(gk,t)),e.ipv4=t=>e.check(Im(_k,t)),e.ipv6=t=>e.check(Lm(vk,t)),e.cidrv4=t=>e.check(Rm(yk,t)),e.cidrv6=t=>e.check(zm(bk,t)),e.e164=t=>e.check(Hm(Ck,t)),e.datetime=t=>e.check(PO(t)),e.date=t=>e.check(IO(t)),e.time=t=>e.check(RO(t)),e.duration=t=>e.check(BO(t))});function z(e){return xm(ik,e)}var ak=A(`ZodStringFormat`,(e,t)=>{tp.init(e,t),rk.init(e,t)}),ok=A(`ZodEmail`,(e,t)=>{ip.init(e,t),ak.init(e,t)}),sk=A(`ZodGUID`,(e,t)=>{np.init(e,t),ak.init(e,t)}),ck=A(`ZodUUID`,(e,t)=>{rp.init(e,t),ak.init(e,t)}),lk=A(`ZodURL`,(e,t)=>{ap.init(e,t),ak.init(e,t)}),uk=A(`ZodEmoji`,(e,t)=>{op.init(e,t),ak.init(e,t)}),dk=A(`ZodNanoID`,(e,t)=>{sp.init(e,t),ak.init(e,t)}),fk=A(`ZodCUID`,(e,t)=>{cp.init(e,t),ak.init(e,t)}),pk=A(`ZodCUID2`,(e,t)=>{lp.init(e,t),ak.init(e,t)}),mk=A(`ZodULID`,(e,t)=>{up.init(e,t),ak.init(e,t)}),hk=A(`ZodXID`,(e,t)=>{dp.init(e,t),ak.init(e,t)}),gk=A(`ZodKSUID`,(e,t)=>{fp.init(e,t),ak.init(e,t)}),_k=A(`ZodIPv4`,(e,t)=>{_p.init(e,t),ak.init(e,t)}),vk=A(`ZodIPv6`,(e,t)=>{vp.init(e,t),ak.init(e,t)}),yk=A(`ZodCIDRv4`,(e,t)=>{yp.init(e,t),ak.init(e,t)}),bk=A(`ZodCIDRv6`,(e,t)=>{bp.init(e,t),ak.init(e,t)}),xk=A(`ZodBase64`,(e,t)=>{Sp.init(e,t),ak.init(e,t)}),Sk=A(`ZodBase64URL`,(e,t)=>{wp.init(e,t),ak.init(e,t)}),Ck=A(`ZodE164`,(e,t)=>{Tp.init(e,t),ak.init(e,t)}),wk=A(`ZodJWT`,(e,t)=>{Dp.init(e,t),ak.init(e,t)}),Tk=A(`ZodNumber`,(e,t)=>{Op.init(e,t),nk.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ph(e,t,n,r),tk(e,`ZodNumber`,{gt(e,t){return this.check(nh(e,t))},gte(e,t){return this.check(rh(e,t))},min(e,t){return this.check(rh(e,t))},lt(e,t){return this.check(eh(e,t))},lte(e,t){return this.check(th(e,t))},max(e,t){return this.check(th(e,t))},int(e){return this.check(Ok(e))},safe(e){return this.check(Ok(e))},positive(e){return this.check(nh(0,e))},nonnegative(e){return this.check(rh(0,e))},negative(e){return this.check(eh(0,e))},nonpositive(e){return this.check(th(0,e))},multipleOf(e,t){return this.check(ih(e,t))},step(e,t){return this.check(ih(e,t))},finite(){return this}});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 Ek(e){return Jm(Tk,e)}var Dk=A(`ZodNumberFormat`,(e,t)=>{kp.init(e,t),Tk.init(e,t)});function Ok(e){return Ym(Dk,e)}var kk=A(`ZodBoolean`,(e,t)=>{Ap.init(e,t),nk.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Fh(e,t,n,r)});function Ak(e){return Xm(kk,e)}var jk=A(`ZodAny`,(e,t)=>{jp.init(e,t),nk.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function Mk(){return Zm(jk)}var Nk=A(`ZodUnknown`,(e,t)=>{Mp.init(e,t),nk.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function Pk(){return Qm(Nk)}var Fk=A(`ZodNever`,(e,t)=>{Np.init(e,t),nk.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Vh(e,t,n,r)});function Ik(e){return $m(Fk,e)}var Lk=A(`ZodArray`,(e,t)=>{Fp.init(e,t),nk.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ng(e,t,n,r),e.element=t.element,tk(e,`ZodArray`,{min(e,t){return this.check(oh(e,t))},nonempty(e){return this.check(oh(1,e))},max(e,t){return this.check(ah(e,t))},length(e,t){return this.check(sh(e,t))},unwrap(){return this.element}})});function Rk(e,t){return bh(Lk,e,t)}var zk=A(`ZodObject`,(e,t)=>{Bp.init(e,t),nk.init(e,t),e._zod.processJSONSchema=(t,n,r)=>rg(e,t,n,r),id(e,`shape`,()=>t.shape),tk(e,`ZodObject`,{keyof(){return Zk(Object.keys(this._zod.def.shape))},catchall(e){return this.clone({...this._zod.def,catchall:e})},passthrough(){return this.clone({...this._zod.def,catchall:Pk()})},loose(){return this.clone({...this._zod.def,catchall:Pk()})},strict(){return this.clone({...this._zod.def,catchall:Ik()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(e){return xd(this,e)},safeExtend(e){return Sd(this,e)},merge(e){return Cd(this,e)},pick(e){return yd(this,e)},omit(e){return bd(this,e)},partial(...e){return wd(nA,this,e[0])},required(...e){return Td(fA,this,e[0])}})});function B(e,t){return new zk({type:`object`,shape:e??{},...j(t)})}var Bk=A(`ZodUnion`,(e,t)=>{Hp.init(e,t),nk.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ig(e,t,n,r),e.options=t.options});function Vk(e,t){return new Bk({type:`union`,options:e,...j(t)})}var Hk=A(`ZodDiscriminatedUnion`,(e,t)=>{Bk.init(e,t),Up.init(e,t)});function Uk(e,t,n){return new Hk({type:`union`,options:t,discriminator:e,...j(n)})}var Wk=A(`ZodIntersection`,(e,t)=>{Wp.init(e,t),nk.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ag(e,t,n,r)});function Gk(e,t){return new Wk({type:`intersection`,left:e,right:t})}var Kk=A(`ZodTuple`,(e,t)=>{qp.init(e,t),nk.init(e,t),e._zod.processJSONSchema=(t,n,r)=>og(e,t,n,r),e.rest=t=>e.clone({...e._zod.def,rest:t})});function qk(e,t,n){let r=t instanceof $f;return new Kk({type:`tuple`,items:e,rest:r?t:null,...j(r?n:t)})}var Jk=A(`ZodRecord`,(e,t)=>{Zp.init(e,t),nk.init(e,t),e._zod.processJSONSchema=(t,n,r)=>sg(e,t,n,r),e.keyType=t.keyType,e.valueType=t.valueType});function Yk(e,t,n){return!t||!t._zod?new Jk({type:`record`,keyType:z(),valueType:e,...j(t)}):new Jk({type:`record`,keyType:e,valueType:t,...j(n)})}var Xk=A(`ZodEnum`,(e,t)=>{Qp.init(e,t),nk.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Gh(e,t,n,r),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 Xk({...t,checks:[],...j(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 Xk({...t,checks:[],...j(r),entries:i})}});function Zk(e,t){return new Xk({type:`enum`,entries:Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e,...j(t)})}var Qk=A(`ZodLiteral`,(e,t)=>{$p.init(e,t),nk.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Kh(e,t,n,r),e.values=new Set(t.values),Object.defineProperty(e,`value`,{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function $k(e,t){return new Qk({type:`literal`,values:Array.isArray(e)?e:[e],...j(t)})}var eA=A(`ZodTransform`,(e,t)=>{em.init(e,t),nk.init(e,t),e._zod.processJSONSchema=(t,n,r)=>$h(e,t,n,r),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new Ju(e.constructor.name);n.addIssue=r=>{if(typeof r==`string`)n.issues.push(Md(r,n.value,t));else{let t=r;t.fatal&&(t.continue=!1),t.code??=`custom`,t.input??=n.value,t.inst??=e,n.issues.push(Md(t))}};let i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n.fallback=!0,n)):(n.value=i,n.fallback=!0,n)}});function tA(e){return new eA({type:`transform`,transform:e})}var nA=A(`ZodOptional`,(e,t)=>{nm.init(e,t),nk.init(e,t),e._zod.processJSONSchema=(t,n,r)=>gg(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function rA(e){return new nA({type:`optional`,innerType:e})}var iA=A(`ZodExactOptional`,(e,t)=>{rm.init(e,t),nk.init(e,t),e._zod.processJSONSchema=(t,n,r)=>gg(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function aA(e){return new iA({type:`optional`,innerType:e})}var oA=A(`ZodNullable`,(e,t)=>{im.init(e,t),nk.init(e,t),e._zod.processJSONSchema=(t,n,r)=>cg(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function sA(e){return new oA({type:`nullable`,innerType:e})}var cA=A(`ZodDefault`,(e,t)=>{am.init(e,t),nk.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ug(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function lA(e,t){return new cA({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():pd(t)}})}var uA=A(`ZodPrefault`,(e,t)=>{sm.init(e,t),nk.init(e,t),e._zod.processJSONSchema=(t,n,r)=>dg(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function dA(e,t){return new uA({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():pd(t)}})}var fA=A(`ZodNonOptional`,(e,t)=>{cm.init(e,t),nk.init(e,t),e._zod.processJSONSchema=(t,n,r)=>lg(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function pA(e,t){return new fA({type:`nonoptional`,innerType:e,...j(t)})}var mA=A(`ZodCatch`,(e,t)=>{um.init(e,t),nk.init(e,t),e._zod.processJSONSchema=(t,n,r)=>fg(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function hA(e,t){return new mA({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:()=>t})}var gA=A(`ZodPipe`,(e,t)=>{dm.init(e,t),nk.init(e,t),e._zod.processJSONSchema=(t,n,r)=>pg(e,t,n,r),e.in=t.in,e.out=t.out});function _A(e,t){return new gA({type:`pipe`,in:e,out:t})}var vA=A(`ZodReadonly`,(e,t)=>{pm.init(e,t),nk.init(e,t),e._zod.processJSONSchema=(t,n,r)=>mg(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function yA(e){return new vA({type:`readonly`,innerType:e})}var bA=A(`ZodCustom`,(e,t)=>{hm.init(e,t),nk.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Zh(e,t,n,r)});function xA(e,t){return xh(bA,e??(()=>!0),t)}function SA(e,t={}){return Sh(bA,e,t)}function CA(e,t){return Ch(e,t)}var wA=o({BaseToolkit:()=>kA,DynamicStructuredTool:()=>OA,DynamicTool:()=>DA,StructuredTool:()=>TA,Tool:()=>EA,ToolInputParsingException:()=>_,isLangChainTool:()=>MO,isRunnableToolLike:()=>AO,isStructuredTool:()=>kO,isStructuredToolParams:()=>jO,tool:()=>AA}),TA=class extends Xw{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=jl(Al(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(Sg(this.schema))try{i=await Dg(this.schema,r)}catch(t){let n=`Received tool input did not match expected schema`;throw this.verboseParsingErrors&&(n=`${n}\nDetails: ${t.message}`),Xg(t)&&(n=`${n}\n\n${zd(t)}`),new _(n,JSON.stringify(e))}else{let t=Cb(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(`
176
- `)}`),new _(n,JSON.stringify(e))}i=r}let a=fl(t),o=yl.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=zb(e)?await Bb(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=jA({content:u,artifact:d,toolCallId:s,name:this.name,metadata:this.metadata});return await c?.handleToolEnd(f),f}},EA=class extends TA{schema=Hv({input:Bv().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)}},DA=class extends EA{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=fl(t);return n.runName===void 0&&(n.runName=this.name),super.call(e,n)}_call(e,t,n){return this.func(e,t,n)}},OA=class extends TA{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=fl(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)}},kA=class{getTools(){return this.tools}};function AA(e,t){let n=Mg(t.schema),r=Ob(t.schema);if(!t.schema||n||r)return new DA({...t,description:t.description??t.schema?.description??`${t.name} tool`,func:async(t,n,r)=>new Promise((i,a)=>{let o=Ml(r,{callbacks:n?.getChild()});wl.runWithConfig(Nl(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 OA({...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(Fl(r.signal))},r.signal.addEventListener(`abort`,o,{once:!0}));let c=Ml(r,{callbacks:n?.getChild()});wl.runWithConfig(Nl(c),async()=>{try{let n=await e(t,c);if(zb(n)){i(n);return}if(r?.signal?.aborted){s();return}s(),i(n)}catch(e){s(),a(e)}})})})}function jA(e){let{content:t,artifact:n,toolCallId:r,metadata:i}=e;return r&&!_t(t)?typeof t==`string`||Array.isArray(t)&&t.every(e=>typeof e==`object`)?new vt({status:`success`,content:t,artifact:n,tool_call_id:r,name:e.name,metadata:i}):new vt({status:`success`,content:MA(t),artifact:n,tool_call_id:r,name:e.name,metadata:i}):t}function MA(e){try{return JSON.stringify(e)??``}catch{return`${e}`}}var NA=o({RunCollectorCallbackHandler:()=>PA}),PA=class extends kc{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)}},FA=o({}),IA=o({chunkArray:()=>LA}),LA=(e,t)=>e.reduce((e,n,r)=>{let i=Math.floor(r/t);return e[i]=(e[i]||[]).concat([n]),e},[]),RA=o({context:()=>zA});function zA(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=BA(t[e],r);r+=typeof n==`string`?n:JSON.stringify(n)}}return r=VA(r),r=r.trim(),r=r.replace(/\\n/g,`
177
- `),r}function BA(e,t){if(typeof e!=`string`||!e.includes(`
175
+ `,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))),lD(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 sD([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})}},MD=class e extends TE{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 kD?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 ND(e){return typeof e==`object`&&!!e&&`withStructuredOutput`in e&&typeof e.withStructuredOutput==`function`}function PD(e){return typeof e==`object`&&!!e&&`lc_id`in e&&Array.isArray(e.lc_id)&&e.lc_id.join(`/`)===`langchain_core/runnables/RunnableBinding`}var FD=class e extends kD{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(ND(e))return super.pipe(e.withStructuredOutput(this.schema));if(PD(e)&&ND(e.bound))return super.pipe(new Wb({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})}},ID=o({AIMessagePromptTemplate:()=>wD,BaseChatPromptTemplate:()=>vD,BaseMessagePromptTemplate:()=>hD,BaseMessageStringPromptTemplate:()=>_D,BasePromptTemplate:()=>TE,BaseStringPromptTemplate:()=>EE,ChatMessagePromptTemplate:()=>yD,ChatPromptTemplate:()=>kD,DEFAULT_FORMATTER_MAPPING:()=>aD,DEFAULT_PARSER_MAPPING:()=>oD,DictPromptTemplate:()=>fD,FewShotChatMessagePromptTemplate:()=>jD,FewShotPromptTemplate:()=>AD,HumanMessagePromptTemplate:()=>CD,ImagePromptTemplate:()=>dD,MessagesPlaceholder:()=>gD,PipelinePromptTemplate:()=>MD,PromptTemplate:()=>uD,StructuredPrompt:()=>FD,SystemMessagePromptTemplate:()=>TD,checkValidTemplate:()=>lD,interpolateFString:()=>rD,interpolateMustache:()=>iD,parseFString:()=>eD,parseMustache:()=>nD,parseTemplate:()=>cD,renderTemplate:()=>sD}),LD=o({BaseDocumentCompressor:()=>RD}),RD=class{static isBaseDocumentCompressor(e){return e?.compressDocuments!==void 0}},zD=o({BaseRetriever:()=>BD}),BD=class extends Ub{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=jl(fl(t)),r=await(await yl.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}}},VD=o({BaseStore:()=>HD,InMemoryStore:()=>UD}),HD=class extends _e{},UD=class extends HD{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)}},WD={and:`and`,or:`or`,not:`not`},GD={eq:`eq`,ne:`ne`,lt:`lt`,gt:`gt`,lte:`lte`,gte:`gte`},KD=class{},qD=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`)}},JD=class extends qD{},YD=class extends JD{exprName=`Comparison`;constructor(e,t,n){super(),this.comparator=e,this.attribute=t,this.value=n}},XD=class extends JD{exprName=`Operation`;constructor(e,t){super(),this.operator=e,this.args=t}},ZD=class extends qD{exprName=`StructuredQuery`;constructor(e,t){super(),this.query=e,this.filter=t}};function QD(e){return e&&typeof e==`object`&&!Array.isArray(e)}function $D(e){return e?typeof e==`string`&&e.length>0||typeof e==`function`?!1:QD(e)&&Object.keys(e).length===0:!0}function eO(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 tO(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 nO(e){return typeof e==`string`&&(Number.isNaN(parseFloat(e))||parseFloat(e).toString()!==e)}function rO(e){return typeof e==`boolean`}function iO(e){let t;if(nO(e))t=e;else if(eO(e))t=parseInt(e,10);else if(tO(e))t=parseFloat(e);else if(rO(e))t=!!e;else throw Error(`Unsupported value type`);return t}var aO=class extends KD{},oO=class extends aO{allowedOperators;allowedComparators;constructor(e){super(),this.allowedOperators=e?.allowedOperators??[WD.and,WD.or],this.allowedComparators=e?.allowedComparators??[GD.eq,GD.ne,GD.gt,GD.gte,GD.lt,GD.lte]}formatFunction(e){if(e in GD){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 WD){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)]:iO(e.value)}}}visitStructuredQuery(e){let t={};return e.filter&&(t={filter:e.filter.accept(this)}),t}mergeFilters(e,t,n=`and`,r=!1){if(!($D(e)&&$D(t))){if($D(e)||n===`replace`)return $D(t)?void 0:t;if($D(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`)}}},sO=class extends aO{allowedOperators=[WD.and,WD.or];allowedComparators=[GD.eq,GD.ne,GD.gt,GD.gte,GD.lt,GD.lte];formatFunction(){throw Error(`Not implemented`)}getAllowedComparatorsForType(e){switch(e){case`string`:return[GD.eq,GD.ne,GD.gt,GD.gte,GD.lt,GD.lte];case`number`:return[GD.eq,GD.ne,GD.gt,GD.gte,GD.lt,GD.lte];case`boolean`:return[GD.eq,GD.ne];default:throw Error(`Unsupported data type: ${e}`)}}getComparatorFunction(e){switch(e){case GD.eq:return(e,t)=>e===t;case GD.ne:return(e,t)=>e!==t;case GD.gt:return(e,t)=>e>t;case GD.gte:return(e,t)=>e>=t;case GD.lt:return(e,t)=>e<t;case GD.lte:return(e,t)=>e<=t;default:throw Error(`Unknown comparator`)}}getOperatorFunction(e){switch(e){case WD.and:return(e,t)=>e&&t;case WD.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=[GD.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,iO(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(!($D(e)&&$D(t))){if($D(e)||n===`replace`)return $D(t)?void 0:t;if($D(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`)}}},cO=o({BaseTranslator:()=>aO,BasicTranslator:()=>oO,Comparators:()=>GD,Comparison:()=>YD,Expression:()=>qD,FilterDirective:()=>JD,FunctionalTranslator:()=>sO,Operation:()=>XD,Operators:()=>WD,StructuredQuery:()=>ZD,Visitor:()=>KD,castValue:()=>iO,isBoolean:()=>rO,isFilterEmpty:()=>$D,isFloat:()=>tO,isInt:()=>eO,isObject:()=>QD,isString:()=>nO});function lO(e){return nt.isInstance(e)?e.constructor.name||e.type:typeof e}function uO(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: ${lO(n)}`,actual:lO(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 dO=uO(`HumanMessage`,sn.isInstance),fO=uO(`AIMessage`,Jt.isInstance),pO=uO(`SystemMessage`,fn.isInstance),mO=uO(`ToolMessage`,vt.isInstance);function hO(e,t){let{isNot:n,utils:r}=this;if(!Jt.isInstance(e))return{pass:!1,message:()=>`${r.matcherHint(`toHaveToolCalls`)}\n\nExpected: AIMessage\nReceived: ${lO(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 gO(e,t){let{isNot:n,utils:r}=this;if(!Jt.isInstance(e))return{pass:!1,message:()=>`${r.matcherHint(`toHaveToolCallCount`)}\n\nExpected: AIMessage\nReceived: ${lO(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 _O(e,t){let{isNot:n,utils:r}=this;if(!Jt.isInstance(e))return{pass:!1,message:()=>`${r.matcherHint(`toContainToolCall`)}\n\nExpected: AIMessage\nReceived: ${lO(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 vO(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(vt.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 yO(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 bO(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 xO={toBeHumanMessage:dO,toBeAIMessage:fO,toBeSystemMessage:pO,toBeToolMessage:mO,toHaveToolCalls:hO,toHaveToolCallCount:gO,toContainToolCall:_O,toHaveToolMessages:vO,toHaveBeenInterrupted:yO,toHaveStructuredResponse:bO};function SO(e){return e.map(e=>e.text).filter(Boolean).join(`-`)}var CO=0;function wO(){return CO+=1,`fake_tc_${CO}`}var TO=class e extends sE{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}):nt.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??wO(),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 Zb.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(!nt.isInstance(t))throw t;return{generations:[{text:``,message:t}]}}if(i.kind===`message`)return{generations:[{text:``,message:i.message}]};let a=SO(e);return{generations:[{text:a,message:new Jt({content:a,id:r.toString(),tool_calls:i.toolCalls.length>0?i.toolCalls.map(e=>({...e,type:`tool_call`})):void 0})}],llmOutput:{}}}};function EO(){return new TO}var DO=o({FakeBuiltModel:()=>TO,fakeModel:()=>EO,langchainMatchers:()=>xO,toBeAIMessage:()=>fO,toBeHumanMessage:()=>dO,toBeSystemMessage:()=>pO,toBeToolMessage:()=>mO,toContainToolCall:()=>_O,toHaveBeenInterrupted:()=>yO,toHaveStructuredResponse:()=>bO,toHaveToolCallCount:()=>gO,toHaveToolCalls:()=>hO,toHaveToolMessages:()=>vO});function OO(e){return e!==void 0&&Array.isArray(e.lc_namespace)}function kO(e){return e!==void 0&&Ub.isRunnable(e)&&`lc_name`in e.constructor&&typeof e.constructor.lc_name==`function`&&e.constructor.lc_name()===`RunnableToolLike`}function AO(e){return!!e&&typeof e==`object`&&`name`in e&&`schema`in e&&(Sg(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 jO(e){return AO(e)||kO(e)||OO(e)}var MO=A(`ZodISODateTime`,(e,t)=>{pp.init(e,t),ik.init(e,t)});function NO(e){return Wm(MO,e)}var PO=A(`ZodISODate`,(e,t)=>{mp.init(e,t),ik.init(e,t)});function FO(e){return Gm(PO,e)}var IO=A(`ZodISOTime`,(e,t)=>{hp.init(e,t),ik.init(e,t)});function LO(e){return Km(IO,e)}var RO=A(`ZodISODuration`,(e,t)=>{gp.init(e,t),ik.init(e,t)});function zO(e){return qm(RO,e)}var BO=A(`ZodError`,(e,t)=>{Pd.init(e,t),e.name=`ZodError`,Object.defineProperties(e,{format:{value:t=>Ld(e,t)},flatten:{value:t=>Id(e,t)},addIssue:{value:t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,Qu,2)}},addIssues:{value:t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,Qu,2)}},isEmpty:{get(){return e.issues.length===0}}})},{Parent:Error}),VO=Bd(BO),HO=Hd(BO),UO=Wd(BO),WO=Kd(BO),GO=Jd(BO),KO=Yd(BO),qO=Xd(BO),JO=Zd(BO),YO=Qd(BO),XO=$d(BO),ZO=ef(BO),QO=tf(BO),$O=new WeakMap;function ek(e,t,n){let r=Object.getPrototypeOf(e),i=$O.get(r);if(i||(i=new Set,$O.set(r,i)),!i.has(t)){i.add(t);for(let e in n){let t=n[e];Object.defineProperty(r,e,{configurable:!0,enumerable:!1,get(){let n=t.bind(this);return Object.defineProperty(this,e,{configurable:!0,writable:!0,enumerable:!0,value:n}),n},set(t){Object.defineProperty(this,e,{configurable:!0,writable:!0,enumerable:!0,value:t})}})}}}var tk=A(`ZodType`,(e,t)=>($f.init(e,t),Object.assign(e[`~standard`],{jsonSchema:{input:jh(e,`input`),output:jh(e,`output`)}}),e.toJSONSchema=Ah(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,`_def`,{value:t}),e.parse=(t,n)=>VO(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>UO(e,t,n),e.parseAsync=async(t,n)=>HO(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>WO(e,t,n),e.spa=e.safeParseAsync,e.encode=(t,n)=>GO(e,t,n),e.decode=(t,n)=>KO(e,t,n),e.encodeAsync=async(t,n)=>qO(e,t,n),e.decodeAsync=async(t,n)=>JO(e,t,n),e.safeEncode=(t,n)=>YO(e,t,n),e.safeDecode=(t,n)=>XO(e,t,n),e.safeEncodeAsync=async(t,n)=>ZO(e,t,n),e.safeDecodeAsync=async(t,n)=>QO(e,t,n),ek(e,`ZodType`,{check(...e){let t=this.def;return this.clone(od(t,{checks:[...t.checks??[],...e.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return gd(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(xA(e,t))},superRefine(e,t){return this.check(SA(e,t))},overwrite(e){return this.check(mh(e))},optional(){return nA(this)},exactOptional(){return iA(this)},nullable(){return oA(this)},nullish(){return nA(oA(this))},nonoptional(e){return fA(this,e)},array(){return Lk(this)},or(e){return Bk([this,e])},and(e){return Wk(this,e)},transform(e){return gA(this,eA(e))},default(e){return cA(this,e)},prefault(e){return uA(this,e)},catch(e){return mA(this,e)},pipe(e){return gA(this,e)},readonly(){return vA(this)},describe(e){let t=this.clone();return bm.add(t,{description:e}),t},meta(...e){if(e.length===0)return bm.get(this);let t=this.clone();return bm.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e){return e(this)}}),Object.defineProperty(e,`description`,{get(){return bm.get(e)?.description},configurable:!0}),e)),nk=A(`_ZodString`,(e,t)=>{ep.init(e,t),tk.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Nh(e,t,n,r);let n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,ek(e,`_ZodString`,{regex(...e){return this.check(ch(...e))},includes(...e){return this.check(dh(...e))},startsWith(...e){return this.check(fh(...e))},endsWith(...e){return this.check(ph(...e))},min(...e){return this.check(oh(...e))},max(...e){return this.check(ah(...e))},length(...e){return this.check(sh(...e))},nonempty(...e){return this.check(oh(1,...e))},lowercase(e){return this.check(lh(e))},uppercase(e){return this.check(uh(e))},trim(){return this.check(gh())},normalize(...e){return this.check(hh(...e))},toLowerCase(){return this.check(_h())},toUpperCase(){return this.check(vh())},slugify(){return this.check(yh())}})}),rk=A(`ZodString`,(e,t)=>{ep.init(e,t),nk.init(e,t),e.email=t=>e.check(Sm(ak,t)),e.url=t=>e.check(Om(ck,t)),e.jwt=t=>e.check(Um(Ck,t)),e.emoji=t=>e.check(km(lk,t)),e.guid=t=>e.check(Cm(ok,t)),e.uuid=t=>e.check(wm(sk,t)),e.uuidv4=t=>e.check(Tm(sk,t)),e.uuidv6=t=>e.check(Em(sk,t)),e.uuidv7=t=>e.check(Dm(sk,t)),e.nanoid=t=>e.check(Am(uk,t)),e.guid=t=>e.check(Cm(ok,t)),e.cuid=t=>e.check(jm(dk,t)),e.cuid2=t=>e.check(Mm(fk,t)),e.ulid=t=>e.check(Nm(pk,t)),e.base64=t=>e.check(Bm(bk,t)),e.base64url=t=>e.check(Vm(xk,t)),e.xid=t=>e.check(Pm(mk,t)),e.ksuid=t=>e.check(Fm(hk,t)),e.ipv4=t=>e.check(Im(gk,t)),e.ipv6=t=>e.check(Lm(_k,t)),e.cidrv4=t=>e.check(Rm(vk,t)),e.cidrv6=t=>e.check(zm(yk,t)),e.e164=t=>e.check(Hm(Sk,t)),e.datetime=t=>e.check(NO(t)),e.date=t=>e.check(FO(t)),e.time=t=>e.check(LO(t)),e.duration=t=>e.check(zO(t))});function B(e){return xm(rk,e)}var ik=A(`ZodStringFormat`,(e,t)=>{tp.init(e,t),nk.init(e,t)}),ak=A(`ZodEmail`,(e,t)=>{ip.init(e,t),ik.init(e,t)}),ok=A(`ZodGUID`,(e,t)=>{np.init(e,t),ik.init(e,t)}),sk=A(`ZodUUID`,(e,t)=>{rp.init(e,t),ik.init(e,t)}),ck=A(`ZodURL`,(e,t)=>{ap.init(e,t),ik.init(e,t)}),lk=A(`ZodEmoji`,(e,t)=>{op.init(e,t),ik.init(e,t)}),uk=A(`ZodNanoID`,(e,t)=>{sp.init(e,t),ik.init(e,t)}),dk=A(`ZodCUID`,(e,t)=>{cp.init(e,t),ik.init(e,t)}),fk=A(`ZodCUID2`,(e,t)=>{lp.init(e,t),ik.init(e,t)}),pk=A(`ZodULID`,(e,t)=>{up.init(e,t),ik.init(e,t)}),mk=A(`ZodXID`,(e,t)=>{dp.init(e,t),ik.init(e,t)}),hk=A(`ZodKSUID`,(e,t)=>{fp.init(e,t),ik.init(e,t)}),gk=A(`ZodIPv4`,(e,t)=>{_p.init(e,t),ik.init(e,t)}),_k=A(`ZodIPv6`,(e,t)=>{vp.init(e,t),ik.init(e,t)}),vk=A(`ZodCIDRv4`,(e,t)=>{yp.init(e,t),ik.init(e,t)}),yk=A(`ZodCIDRv6`,(e,t)=>{bp.init(e,t),ik.init(e,t)}),bk=A(`ZodBase64`,(e,t)=>{Sp.init(e,t),ik.init(e,t)}),xk=A(`ZodBase64URL`,(e,t)=>{wp.init(e,t),ik.init(e,t)}),Sk=A(`ZodE164`,(e,t)=>{Tp.init(e,t),ik.init(e,t)}),Ck=A(`ZodJWT`,(e,t)=>{Dp.init(e,t),ik.init(e,t)}),wk=A(`ZodNumber`,(e,t)=>{Op.init(e,t),tk.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ph(e,t,n,r),ek(e,`ZodNumber`,{gt(e,t){return this.check(nh(e,t))},gte(e,t){return this.check(rh(e,t))},min(e,t){return this.check(rh(e,t))},lt(e,t){return this.check(eh(e,t))},lte(e,t){return this.check(th(e,t))},max(e,t){return this.check(th(e,t))},int(e){return this.check(Dk(e))},safe(e){return this.check(Dk(e))},positive(e){return this.check(nh(0,e))},nonnegative(e){return this.check(rh(0,e))},negative(e){return this.check(eh(0,e))},nonpositive(e){return this.check(th(0,e))},multipleOf(e,t){return this.check(ih(e,t))},step(e,t){return this.check(ih(e,t))},finite(){return this}});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 Tk(e){return Jm(wk,e)}var Ek=A(`ZodNumberFormat`,(e,t)=>{kp.init(e,t),wk.init(e,t)});function Dk(e){return Ym(Ek,e)}var Ok=A(`ZodBoolean`,(e,t)=>{Ap.init(e,t),tk.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Fh(e,t,n,r)});function kk(e){return Xm(Ok,e)}var Ak=A(`ZodAny`,(e,t)=>{jp.init(e,t),tk.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function jk(){return Zm(Ak)}var Mk=A(`ZodUnknown`,(e,t)=>{Mp.init(e,t),tk.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function Nk(){return Qm(Mk)}var Pk=A(`ZodNever`,(e,t)=>{Np.init(e,t),tk.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Vh(e,t,n,r)});function Fk(e){return $m(Pk,e)}var Ik=A(`ZodArray`,(e,t)=>{Fp.init(e,t),tk.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ng(e,t,n,r),e.element=t.element,ek(e,`ZodArray`,{min(e,t){return this.check(oh(e,t))},nonempty(e){return this.check(oh(1,e))},max(e,t){return this.check(ah(e,t))},length(e,t){return this.check(sh(e,t))},unwrap(){return this.element}})});function Lk(e,t){return bh(Ik,e,t)}var Rk=A(`ZodObject`,(e,t)=>{Bp.init(e,t),tk.init(e,t),e._zod.processJSONSchema=(t,n,r)=>rg(e,t,n,r),id(e,`shape`,()=>t.shape),ek(e,`ZodObject`,{keyof(){return Xk(Object.keys(this._zod.def.shape))},catchall(e){return this.clone({...this._zod.def,catchall:e})},passthrough(){return this.clone({...this._zod.def,catchall:Nk()})},loose(){return this.clone({...this._zod.def,catchall:Nk()})},strict(){return this.clone({...this._zod.def,catchall:Fk()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(e){return xd(this,e)},safeExtend(e){return Sd(this,e)},merge(e){return Cd(this,e)},pick(e){return yd(this,e)},omit(e){return bd(this,e)},partial(...e){return wd(tA,this,e[0])},required(...e){return Td(dA,this,e[0])}})});function V(e,t){return new Rk({type:`object`,shape:e??{},...j(t)})}var zk=A(`ZodUnion`,(e,t)=>{Hp.init(e,t),tk.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ig(e,t,n,r),e.options=t.options});function Bk(e,t){return new zk({type:`union`,options:e,...j(t)})}var Vk=A(`ZodDiscriminatedUnion`,(e,t)=>{zk.init(e,t),Up.init(e,t)});function Hk(e,t,n){return new Vk({type:`union`,options:t,discriminator:e,...j(n)})}var Uk=A(`ZodIntersection`,(e,t)=>{Wp.init(e,t),tk.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ag(e,t,n,r)});function Wk(e,t){return new Uk({type:`intersection`,left:e,right:t})}var Gk=A(`ZodTuple`,(e,t)=>{qp.init(e,t),tk.init(e,t),e._zod.processJSONSchema=(t,n,r)=>og(e,t,n,r),e.rest=t=>e.clone({...e._zod.def,rest:t})});function Kk(e,t,n){let r=t instanceof $f;return new Gk({type:`tuple`,items:e,rest:r?t:null,...j(r?n:t)})}var qk=A(`ZodRecord`,(e,t)=>{Zp.init(e,t),tk.init(e,t),e._zod.processJSONSchema=(t,n,r)=>sg(e,t,n,r),e.keyType=t.keyType,e.valueType=t.valueType});function Jk(e,t,n){return!t||!t._zod?new qk({type:`record`,keyType:B(),valueType:e,...j(t)}):new qk({type:`record`,keyType:e,valueType:t,...j(n)})}var Yk=A(`ZodEnum`,(e,t)=>{Qp.init(e,t),tk.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Gh(e,t,n,r),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 Yk({...t,checks:[],...j(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 Yk({...t,checks:[],...j(r),entries:i})}});function Xk(e,t){return new Yk({type:`enum`,entries:Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e,...j(t)})}var Zk=A(`ZodLiteral`,(e,t)=>{$p.init(e,t),tk.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Kh(e,t,n,r),e.values=new Set(t.values),Object.defineProperty(e,`value`,{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function Qk(e,t){return new Zk({type:`literal`,values:Array.isArray(e)?e:[e],...j(t)})}var $k=A(`ZodTransform`,(e,t)=>{em.init(e,t),tk.init(e,t),e._zod.processJSONSchema=(t,n,r)=>$h(e,t,n,r),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new Ju(e.constructor.name);n.addIssue=r=>{if(typeof r==`string`)n.issues.push(Md(r,n.value,t));else{let t=r;t.fatal&&(t.continue=!1),t.code??=`custom`,t.input??=n.value,t.inst??=e,n.issues.push(Md(t))}};let i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n.fallback=!0,n)):(n.value=i,n.fallback=!0,n)}});function eA(e){return new $k({type:`transform`,transform:e})}var tA=A(`ZodOptional`,(e,t)=>{nm.init(e,t),tk.init(e,t),e._zod.processJSONSchema=(t,n,r)=>gg(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function nA(e){return new tA({type:`optional`,innerType:e})}var rA=A(`ZodExactOptional`,(e,t)=>{rm.init(e,t),tk.init(e,t),e._zod.processJSONSchema=(t,n,r)=>gg(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function iA(e){return new rA({type:`optional`,innerType:e})}var aA=A(`ZodNullable`,(e,t)=>{im.init(e,t),tk.init(e,t),e._zod.processJSONSchema=(t,n,r)=>cg(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function oA(e){return new aA({type:`nullable`,innerType:e})}var sA=A(`ZodDefault`,(e,t)=>{am.init(e,t),tk.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ug(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function cA(e,t){return new sA({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():pd(t)}})}var lA=A(`ZodPrefault`,(e,t)=>{sm.init(e,t),tk.init(e,t),e._zod.processJSONSchema=(t,n,r)=>dg(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function uA(e,t){return new lA({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():pd(t)}})}var dA=A(`ZodNonOptional`,(e,t)=>{cm.init(e,t),tk.init(e,t),e._zod.processJSONSchema=(t,n,r)=>lg(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function fA(e,t){return new dA({type:`nonoptional`,innerType:e,...j(t)})}var pA=A(`ZodCatch`,(e,t)=>{um.init(e,t),tk.init(e,t),e._zod.processJSONSchema=(t,n,r)=>fg(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function mA(e,t){return new pA({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:()=>t})}var hA=A(`ZodPipe`,(e,t)=>{dm.init(e,t),tk.init(e,t),e._zod.processJSONSchema=(t,n,r)=>pg(e,t,n,r),e.in=t.in,e.out=t.out});function gA(e,t){return new hA({type:`pipe`,in:e,out:t})}var _A=A(`ZodReadonly`,(e,t)=>{pm.init(e,t),tk.init(e,t),e._zod.processJSONSchema=(t,n,r)=>mg(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function vA(e){return new _A({type:`readonly`,innerType:e})}var yA=A(`ZodCustom`,(e,t)=>{hm.init(e,t),tk.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Zh(e,t,n,r)});function bA(e,t){return xh(yA,e??(()=>!0),t)}function xA(e,t={}){return Sh(yA,e,t)}function SA(e,t){return Ch(e,t)}var CA=o({BaseToolkit:()=>OA,DynamicStructuredTool:()=>DA,DynamicTool:()=>EA,StructuredTool:()=>wA,Tool:()=>TA,ToolInputParsingException:()=>_,isLangChainTool:()=>jO,isRunnableToolLike:()=>kO,isStructuredTool:()=>OO,isStructuredToolParams:()=>AO,tool:()=>kA}),wA=class extends Yw{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=jl(Al(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(Sg(this.schema))try{i=await Dg(this.schema,r)}catch(t){let n=`Received tool input did not match expected schema`;throw this.verboseParsingErrors&&(n=`${n}\nDetails: ${t.message}`),Xg(t)&&(n=`${n}\n\n${zd(t)}`),new _(n,JSON.stringify(e))}else{let t=Sb(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(`
176
+ `)}`),new _(n,JSON.stringify(e))}i=r}let a=fl(t),o=yl.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=Rb(e)?await zb(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=AA({content:u,artifact:d,toolCallId:s,name:this.name,metadata:this.metadata});return await c?.handleToolEnd(f),f}},TA=class extends wA{schema=Vv({input:zv().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)}},EA=class extends TA{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=fl(t);return n.runName===void 0&&(n.runName=this.name),super.call(e,n)}_call(e,t,n){return this.func(e,t,n)}},DA=class extends wA{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=fl(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)}},OA=class{getTools(){return this.tools}};function kA(e,t){let n=Mg(t.schema),r=Db(t.schema);if(!t.schema||n||r)return new EA({...t,description:t.description??t.schema?.description??`${t.name} tool`,func:async(t,n,r)=>new Promise((i,a)=>{let o=Ml(r,{callbacks:n?.getChild()});wl.runWithConfig(Nl(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 DA({...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(Fl(r.signal))},r.signal.addEventListener(`abort`,o,{once:!0}));let c=Ml(r,{callbacks:n?.getChild()});wl.runWithConfig(Nl(c),async()=>{try{let n=await e(t,c);if(Rb(n)){i(n);return}if(r?.signal?.aborted){s();return}s(),i(n)}catch(e){s(),a(e)}})})})}function AA(e){let{content:t,artifact:n,toolCallId:r,metadata:i}=e;return r&&!_t(t)?typeof t==`string`||Array.isArray(t)&&t.every(e=>typeof e==`object`)?new vt({status:`success`,content:t,artifact:n,tool_call_id:r,name:e.name,metadata:i}):new vt({status:`success`,content:jA(t),artifact:n,tool_call_id:r,name:e.name,metadata:i}):t}function jA(e){try{return JSON.stringify(e)??``}catch{return`${e}`}}var MA=o({RunCollectorCallbackHandler:()=>NA}),NA=class extends kc{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)}},PA=o({}),FA=o({chunkArray:()=>IA}),IA=(e,t)=>e.reduce((e,n,r)=>{let i=Math.floor(r/t);return e[i]=(e[i]||[]).concat([n]),e},[]),LA=o({context:()=>RA});function RA(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=zA(t[e],r);r+=typeof n==`string`?n:JSON.stringify(n)}}return r=BA(r),r=r.trim(),r=r.replace(/\\n/g,`
177
+ `),r}function zA(e,t){if(typeof e!=`string`||!e.includes(`
178
178
  `))return e;let n=t.slice(t.lastIndexOf(`
179
- `)+1).match(/^(\s+)/);if(n){let t=n[1];return e.replace(/\n/g,`\n${t}`)}return e}function VA(e){let t=e.split(`
179
+ `)+1).match(/^(\s+)/);if(n){let t=n[1];return e.replace(/\n/g,`\n${t}`)}return e}function BA(e){let t=e.split(`
180
180
  `),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(`
181
- `)}var HA=o({EventStreamContentType:()=>UA,convertEventStreamToIterableReadableDataStream:()=>YA,getBytes:()=>WA,getLines:()=>GA,getMessages:()=>KA}),UA=`text/event-stream`;async function WA(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(`
182
- `))}}function GA(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=qA(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 KA(e,t,n){let r=JA(),i=new TextDecoder;return function(a,o,s){if(s){XA(r)||(e?.(r),r=JA());return}if(a.length===0)e?.(r),r=JA();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+`
183
- `+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 qA(e,t){let n=new Uint8Array(e.length+t.length);return n.set(e),n.set(t,e.length),n}function JA(){return{data:``,event:``,id:``,retry:void 0}}function YA(e,t){let n=new ReadableStream({async start(n){let r=KA(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 WA(e,GA((e,t,i)=>{r(e,t,i),i&&n.close()}))}});return Ll.fromReadableStream(n)}function XA(e){return e.data===``&&e.event===``&&e.id===``&&e.retry===void 0}var ZA=o({}),QA=o({convertToOpenAIFunction:()=>$A,convertToOpenAITool:()=>ej,isLangChainTool:()=>MO,isRunnableToolLike:()=>AO,isStructuredTool:()=>kO,isStructuredToolParams:()=>jO});function $A(e,t){let n=typeof t==`number`?void 0:t;return{name:e.name,description:e.description,parameters:Db(e.schema),...n?.strict===void 0?{}:{strict:n.strict}}}function ej(e,t){let n=typeof t==`number`?void 0:t,r;return r=MO(e)?{type:`function`,function:$A(e)}:e,n?.strict!==void 0&&(r.function.strict=n.strict),r}function tj(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 nj(e,t){let n=0;for(let r=0;r<e.length;r++)n+=e[r]*t[r];return n}function rj(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 ij(e,t){return Math.sqrt(rj(e,t))}var aj=o({cosineSimilarity:()=>cj,euclideanDistance:()=>uj,innerProduct:()=>lj,matrixFunc:()=>oj,maximalMarginalRelevance:()=>dj,normalize:()=>sj});function oj(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 sj(e,t=!1){let n=pj(e);return e.map(e=>e.map(e=>t?1-e/n:e/n))}function cj(e,t){return oj(e,t,tj)}function lj(e,t){return oj(e,t,nj)}function uj(e,t){return oj(e,t,ij)}function dj(e,t,n=.5,r=4){if(Math.min(r,t.length)<=0)return[];let i=cj(Array.isArray(e[0])?e:[e],t)[0],a=fj(i).maxIndex,o=[t[a]],s=[a];for(;s.length<Math.min(r,t.length);){let e=-1/0,r=-1,a=cj(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 fj(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 pj(e){return e.reduce((e,t)=>Math.max(e,fj(t).maxValue),0)}var mj=o({isCloudMetadata:()=>Oj,isLocalhost:()=>kj,isPrivateIp:()=>Dj,isSafeUrl:()=>jj,isSameOrigin:()=>Mj,validateSafeUrl:()=>Aj}),hj=[`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`],gj=[`169.254.169.254`,`169.254.170.2`,`100.100.100.200`],_j=[`metadata.google.internal`,`metadata`,`instance-data`],vj=[`localhost`,`localhost.localdomain`],yj=/^(?:(?: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 bj(e){return yj.test(e)}function xj(e){return wj(e)!==null}function Sj(e){return bj(e)||xj(e)}function Cj(e){if(bj(e))return e.split(`.`).map(e=>parseInt(e,10));if(xj(e)){let t=wj(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 wj(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 Tj(e){let[t,n]=e.split(`/`);if(!t||!n)return null;let r=Cj(t);if(!r)return null;let i=parseInt(n,10);if(isNaN(i))return null;let a=xj(t);return a&&i>128||!a&&i>32?null:{addr:r,prefixLen:i,isIpv6:a}}function Ej(e,t){let n=Cj(e);if(!n)return!1;let r=Tj(t);if(!r)return!1;let i=xj(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 Dj(e){if(!Sj(e))return!1;for(let t of hj)if(Ej(e,t))return!0;return!1}function Oj(e,t){if(gj.includes(t||``))return!0;let n=e.toLowerCase();return!!_j.includes(n)}function kj(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!!vj.includes(n)}function Aj(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(Oj(i))throw Error(`URL points to cloud metadata endpoint: ${i}`);if(kj(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(Sj(i)){let t=i;if(kj(i,t)){if(!n)throw Error(`URL points to localhost: ${i}`);return e}if(Oj(i,t))throw Error(`URL resolves to cloud metadata IP: ${t} (${i})`);if(Dj(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 jj(e,t){try{return Aj(e,t),!0}catch{return!1}}function Mj(e,t){try{return new URL(e).origin===new URL(t).origin}catch{return!1}}var Nj=o({SaveableVectorStore:()=>Ij,VectorStore:()=>Fj,VectorStoreRetriever:()=>Pj}),Pj=class extends VD{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)}},Fj=class extends _e{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 Pj({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 Pj({...t,searchKwargs:e.searchKwargs}):new Pj({...t})}}},Ij=class extends Fj{static load(e,t){throw Error(`Not implemented`)}},Lj=class extends cE{_combineLLMOutput(){return[]}_llmType(){return`fake`}async _generate(e,t,n){if(t?.stop?.length)return{generations:[{message:new Jt(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(`
184
- `);return await n?.handleLLMNewToken(r),{generations:[{message:new Jt(r),text:r}],llmOutput:{}}}},Rj=class e extends cE{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:Db(e.schema)}};case`anthropic`:return{name:e.name,description:e.description,input_schema:Db(e.schema)};case`bedrock`:return{toolSpec:{name:e.name,description:e.description,inputSchema:Db(e.schema)}};case`google`:return{name:e.name,description:e.description,parameters:Db(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 Jt({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 Cu({message:new Zt({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 Jt(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 Cu({message:new Zt({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})}}},zj=class e extends cE{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 Jt(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 Cu({message:new Zt({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:Db(e.schema)}};case`anthropic`:return{name:e.name,description:e.description,input_schema:Db(e.schema)};case`bedrock`:return{toolSpec:{name:e.name,description:e.description,inputSchema:Db(e.schema)}};case`google`:return{name:e.name,description:e.description,parameters:Db(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 Qb.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`)})}},Bj=class extends rw{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})}},Vj=class extends rw{constructor(e){super(e??{})}embedDocuments(e){return Promise.resolve(e.map(()=>[.1,.2,.3,.4]))}embedQuery(e){return Promise.resolve([.1,.2,.3,.4])}},Hj=class extends pE{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}},Uj=class extends pE{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)}},Wj=class extends WC{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 sn(e))}async addAIMessage(e){this.messages.push(new Jt(e))}async clear(){this.messages=[]}},Gj=class extends GC{lc_namespace=[`langchain_core`,`message`,`fake`];messages=[];constructor(){super()}async addMessage(e){this.messages.push(e)}async getMessages(){return this.messages}},Kj=class extends kc{name=`fake_tracer`;runs=[];constructor(){super()}persistRun(e){return this.runs.push(e),Promise.resolve()}},qj=class extends eT{lc_namespace=[`tests`,`fake`];getFormatInstructions(){return``}async parse(e){return e.split(`,`).map(e=>e.trim())}},Jj=class extends VD{lc_namespace=[`test`,`fake`];output=[new qC({pageContent:`foo`}),new qC({pageContent:`bar`})];constructor(e){super(),this.output=e?.output??this.output}async _getRelevantDocuments(e){return this.output}},Yj=class extends Wb{lc_namespace=[`tests`,`fake`];returnOptions;constructor(e){super(e),this.returnOptions=e.returnOptions}async invoke(e,t){return this.returnOptions?t??{}:{input:e}}},Xj=class extends TA{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)}},Zj=class extends kc{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}},Qj=class e extends Fj{memoryVectors=[];similarity;_vectorstoreType(){return`memory`}constructor(e,{similarity:t,...n}={}){super(e,n),this.similarity=t??tj}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 qC({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 qC({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 qC({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)}},$j=o({FakeChatMessageHistory:()=>Wj,FakeChatModel:()=>Lj,FakeEmbeddings:()=>Vj,FakeLLM:()=>Hj,FakeListChatMessageHistory:()=>Gj,FakeListChatModel:()=>zj,FakeRetriever:()=>Jj,FakeRunnable:()=>Yj,FakeSplitIntoListParser:()=>qj,FakeStreamingChatModel:()=>Rj,FakeStreamingLLM:()=>Uj,FakeTool:()=>Xj,FakeTracer:()=>Kj,FakeVectorStore:()=>Qj,SingleRunExtractor:()=>Zj,SyntheticEmbeddings:()=>Bj}),eM=o({agents:()=>OC,caches:()=>IC,callbacks__base:()=>hr,callbacks__manager:()=>dl,callbacks__promises:()=>ol,chat_history:()=>UC,document_loaders__base:()=>ZC,document_loaders__langsmith:()=>$C,documents:()=>XC,embeddings:()=>nw,errors:()=>l,example_selectors:()=>pw,index:()=>DC,indexing:()=>Sw,language_models__base:()=>Uw,language_models__chat_models:()=>oE,language_models__compat:()=>qT,language_models__event:()=>uE,language_models__llms:()=>dE,language_models__profile:()=>mE,language_models__stream:()=>NT,language_models__structured_output:()=>kT,load__serializable:()=>pe,memory:()=>hE,messages:()=>Tx,messages__tool:()=>gt,output_parsers:()=>ST,output_parsers__openai_functions:()=>wE,output_parsers__openai_tools:()=>TE,outputs:()=>bu,prompt_values:()=>Cw,prompts:()=>LD,retrievers:()=>BD,retrievers__document_compressors:()=>RD,runnables:()=>Dx,runnables__graph:()=>kb,singletons:()=>Tl,stores:()=>HD,structured_query:()=>lO,testing:()=>OO,tools:()=>wA,tracers__base:()=>wc,tracers__console:()=>jc,tracers__log_stream:()=>fu,tracers__run_collector:()=>NA,tracers__tracer_langchain:()=>Kc,types__stream:()=>FA,utils__async_caller:()=>Ru,utils__chunk_array:()=>IA,utils__context:()=>RA,utils__env:()=>ar,utils__event_source_parse:()=>HA,utils__format:()=>ZA,utils__function_calling:()=>QA,utils__hash:()=>FC,utils__json_patch:()=>Qw,utils__json_schema:()=>Tb,utils__math:()=>aj,utils__ssrf:()=>mj,utils__standard_schema:()=>Ly,utils__stream:()=>Il,utils__testing:()=>$j,utils__tiktoken:()=>Rw,utils__types:()=>CT,utils__uuid:()=>ir,vectorstores:()=>Nj}),tM=50;function nM(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 rM(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)=>rM.call({...this,path:[...o,`${t}`],depth:s+1},e)));let u=e;if(le(u))return fe(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=mr(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:eM,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(EC.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`&&ge(e)===a);if(typeof g!=`function`)throw Error(`Invalid identifer: ${l} -> ${i}`);let _=new g(ae(await rM.call({...this,path:[...o,`kwargs`],depth:s+1},e.kwargs),ie,nM(g)));return Object.defineProperty(_.constructor,`name`,{value:a}),_}let d={};for(let[e,t]of Object.entries(u))d[e]=await rM.call({...this,path:[...o,e],depth:s+1},t);return d}async function iM(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??tM};return rM.call(r,n)}function aM(e){return e!==null&&e.lc===1&&e.type===`constructor`&&Array.isArray(e.id)}async function oM(e){if(e&&typeof e==`object`){if(Array.isArray(e))return await Promise.all(e.map(e=>oM(e)));{let t={};for(let[n,r]of Object.entries(e))t[n]=await oM(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(aM(t))return iM(JSON.stringify(t));return t}}return e}function sM(e,t,n,r){return{lc:2,type:`constructor`,id:[e.name],method:t??null,args:n??[],kwargs:r??{}}}function cM(e){return e===void 0?{lc:2,type:`undefined`}:e instanceof Set||e instanceof Map?sM(e.constructor,void 0,[Array.from(e)]):e instanceof RegExp?sM(RegExp,void 0,[e.source,e.flags]):e instanceof Error?sM(e.constructor,void 0,[e.message]):e?.lg_name===`Send`?{node:e.node,args:e.args}:e instanceof Uint8Array?sM(Uint8Array,`from`,[Array.from(e)]):e}var lM=class{_dumps(e){return new TextEncoder().encode(SC(e,(e,t)=>cM(t)))}async dumpsTyped(e){return e instanceof Uint8Array?[`bytes`,e]:[`json`,this._dumps(e)]}async _loads(e){return oM(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 uM(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]=uM(e[n]));return t}function dM(){return{v:4,id:dC(-2),ts:new Date().toISOString(),channel_values:{},channel_versions:{},versions_seen:{}}}function fM(e){return{v:e.v,id:e.id,ts:e.ts,channel_values:{...e.channel_values},channel_versions:{...e.channel_versions},versions_seen:uM(e.versions_seen)}}function pM(e,t){return typeof e==`number`&&typeof t==`number`?Math.sign(e-t):String(e).localeCompare(String(t))}function mM(...e){return e.reduce((e,t,n)=>n===0?t:pM(e,t)>=0?e:t)}var hM={[pC]:-1,[mC]:-2,[hC]:-3,[gC]:-4},gM=class extends Error{constructor(e){super(e),this.name=`InvalidNamespaceError`}};function _M(e){if(e.length===0)throw new gM(`Namespace cannot be empty.`);for(let t of e){if(typeof t!=`string`)throw new gM(`Invalid namespace label '${t}' found in ${e}. Namespace labels must be strings, but got ${typeof t}.`);if(t.includes(`.`))throw new gM(`Invalid namespace label '${t}' found in ${e}. Namespace labels cannot contain periods ('.').`);if(t===``)throw new gM(`Namespace labels cannot be empty strings. Got ${t} in ${e}`)}if(e[0]===`langgraph`)throw new gM(`Root label for namespace cannot be "langgraph". Got: ${e}`)}var vM=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){_M(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(){}},yM=e=>`lg_name`in e&&e.lg_name===`AsyncBatchedStore`?e.store:e,bM=class extends vM{lg_name=`AsyncBatchedStore`;store;queue=new Map;nextKey=0;running=!1;processingTask=null;constructor(e){super(),this.store=yM(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]`}}},xM=class{serde=new lM;constructor(e){this.serde=e||this.serde}};function SM(e){return e!=null&&e.lg_is_channel===!0}var CM=class{ValueType;UpdateType;lg_is_channel=!0;consume(){return!1}finish(){return!1}isAvailable(){try{return this.get(),!0}catch(e){if(e.name===jS.unminifiable_name)return!1;throw e}}equals(e){return this===e}},wM=Symbol.for(`LG_IS_ONLY_BASE_CHANNEL`);function TM(e){if(e[wM]===!0)return e;let t={};for(let n in e){if(!Object.prototype.hasOwnProperty.call(e,n))continue;let r=e[n];SM(r)&&(t[n]=r)}return Object.assign(t,{[wM]:!0}),t}function EM(e,t){let n=TM(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,{[wM]:!0}),r}function DM(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!==jS.unminifiable_name)throw e}}return{v:4,id:r?.id??dC(n),ts:new Date().toISOString(),channel_values:i,channel_versions:e.channel_versions,versions_seen:e.versions_seen}}var OM=class e extends CM{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 MS(`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 jS;return this.value[0]}checkpoint(){if(this.value.length===0)throw new jS;return this.value[0]}isAvailable(){return this.value.length!==0}},kM=class e extends CM{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 jS;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}},AM=e=>e!=null&&e.lc_graph_name===`BinaryOperatorAggregate`,jM=class e extends CM{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]=mS(e);n?this.value=r:this.value=e,t=t.slice(1)}let n=!1;for(let e of t)if(hS(e)){if(n)throw new MS(`Can receive only one Overwrite value per step.`);let[,t]=mS(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 jS;return this.value}checkpoint(){if(this.value===void 0)throw new jS;return this.value}isAvailable(){return this.value!==void 0}equals(e){return this===e?!0:AM(e)?this.operator===e.operator:!1}},MM=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`}},NM=function(e){return e?PM(e):new OM};NM.Root=e=>new MM(e);function PM(e){return typeof e==`object`&&e&&`reducer`in e&&e.reducer?new jM(e.reducer,e.default):typeof e==`object`&&e&&`value`in e&&e.value?new jM(e.value,e.default):new OM}var FM=[`tags`,`metadata`,`callbacks`,`configurable`],IM=[`tags`,`metadata`,`callbacks`,`runName`,`maxConcurrency`,`recursionLimit`,`configurable`,`runId`,`outputKeys`,`streamMode`,`store`,`writer`,`interrupt`,`context`,`interruptBefore`,`interruptAfter`,`checkpointDuring`,`durability`,`signal`,`executionInfo`,`serverInfo`],LM=25,RM=new Set([`thread_id`,`checkpoint_id`,`checkpoint_ns`,`task_id`,`run_id`,`assistant_id`,`graph_id`]);function zM(e,t){if(!e)return t;let n=t??{};for(let t of RM){if(t in n)continue;let r=e[t];r!==void 0&&(n[t]=r)}return n}function BM(...e){let t={tags:[],metadata:{},callbacks:void 0,recursionLimit:LM,configurable:{}},n=wl.getRunnableConfig();if(n!==void 0){for(let[e,r]of Object.entries(n))if(r!==void 0)if(FM.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&&IM.includes(e)&&(t[e]=r);return t.metadata=zM(t.configurable,t.metadata)??{},t}function VM(){return wl.getRunnableConfig()}function HM(e){return e.split(`|`).filter(e=>!e.match(/^\d+$/)).map(e=>e.split(`:`)[0]).join(`|`)}function UM(e){let t=e.split(`|`);for(;t.length>1&&t[t.length-1].match(/^\d+$/);)t.pop();return t.slice(0,-1).join(`|`)}var WM=class extends Wb{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=Ml(t,{callbacks:n?.getChild()});wl.runWithConfig(a,async()=>{try{r(await this.func(e,a))}catch(e){i(e)}})})}async invoke(e,t){let n,r=BM(t),i=Al(this.config,r);return n=this.trace?await this._callWithConfig(this._tracedInvoke,e,i):await wl.runWithConfig(i,async()=>this.func(e,i)),Wb.isRunnable(n)&&this.recurse?await wl.runWithConfig(i,async()=>n.invoke(e,i)):n}};function*GM(e,t){if(t===void 0)yield*e;else for(let n of e)yield[t,n]}async function KM(e){let t=[];for await(let n of await e)t.push(n);return t}function qM(e){let t=[];for(let n of e)t.push(n);return t}function JM(e,t){return e?`configurable`in e?{...e,configurable:{...e.configurable,...t}}:{...e,configurable:t}:{configurable:t}}function YM(e){return typeof e==`object`&&e?.[Symbol.for(`LG_SKIP_WRITE`)]!==void 0}var XM={[Symbol.for(`LG_PASSTHROUGH`)]:!0};function ZM(e){return typeof e==`object`&&e?.[Symbol.for(`LG_PASSTHROUGH`)]!==void 0}var QM=Symbol(`IS_WRITER`),$M=class e extends WM{writes;constructor(e,t){let n=`ChannelWrite<${e.map(e=>fS(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=>tN(e)&&ZM(e.value)?{mapper:e.mapper,value:t}:eN(e)&&ZM(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(eN(e)){if(e.channel===`__pregel_tasks`)throw new MS(`Cannot write to the reserved channel TASKS`);if(ZM(e.value))throw new MS(`PASSTHROUGH value must be replaced`)}if(tN(e)&&ZM(e.value))throw new MS(`PASSTHROUGH value must be replaced`)}let n=[];for(let r of t)if(fS(r))n.push([rS,r]);else if(tN(r)){let t=await r.mapper.invoke(r.value,e);t!=null&&t.length>0&&n.push(...t)}else if(eN(r)){let t=r.mapper===void 0?r.value:await r.mapper.invoke(r.value,e);if(YM(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?.[Nx];r(n)}static isWriter(t){return t instanceof e||QM in t&&!!t[QM]}static registerWriter(e){return Object.defineProperty(e,QM,{value:!0})}};function eN(e){return e!==void 0&&typeof e.channel==`string`}function tN(e){return e!==void 0&&!eN(e)&&Wb.isRunnable(e.mapper)}var nN=class e extends WM{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?.[Fx];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)}},rN=new ox,iN=class e extends Gb{lc_graph_name=`PregelNode`;channels;triggers=[];mapper;writers=[];bound=rN;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??rN,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 $M&&e[e.length-2]instanceof $M;){let t=e.slice(-2),n=t[0].writes.concat(t[1].writes);e[e.length-2]=new $M(n,t[0].config?.tags),e.pop()}return e}getNode(){let e=this.getWriters();if(!(this.bound===rN&&e.length===0))return this.bound===rN&&e.length===1?e[0]:this.bound===rN?new Jb({first:e[0],middle:e.slice(1,e.length-1),last:e[e.length-1],omitSequenceTags:!0}):e.length>0?new Jb({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 $M.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===rN?new e({channels:this.channels,triggers:this.triggers,mapper:this.mapper,writers:this.writers,bound:tx(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 aN(e){return`steps`in e&&Array.isArray(e.steps)}function oN(e){return`lg_is_pregel`in e&&e.lg_is_pregel===!0}function sN(e){let t=[e];for(let e of t)if(oN(e))return e;else aN(e)&&t.push(...e.steps)}var cN=class e extends CM{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 MS(`EphemeralValue can only receive one value per step.`);return this.value=[e[e.length-1]],!0}get(){if(this.value.length===0)throw new jS;return this.value[0]}checkpoint(){if(this.value.length===0)throw new jS;return this.value[0]}isAvailable(){return this.value.length!==0}},V=e=>BigInt(e),lN=(e,t=0)=>new DataView(e.buffer,e.byteOffset+t,e.byteLength-t),uN=V(`0x9E3779B1`),dN=V(`0x85EBCA77`),fN=V(`0xC2B2AE3D`),pN=V(`0x9E3779B185EBCA87`),mN=V(`0xC2B2AE3D27D4EB4F`),hN=V(`0x165667B19E3779F9`),gN=V(`0x85EBCA77C2B2AE63`),_N=V(`0x27D4EB2F165667C5`),vN=V(`0x165667919E3779F9`),yN=V(`0x9FB21C651E98DF25`),bN=(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 lN(r)})(`b8fe6c3923a44bbe7c01812cf721ad1cded46de9839097db7240a4a4b7b3671fcb79e64eccc0e578825ad07dccff7221b8084674f743248ee03590e6813a264c3c2852bb91c300cb88d0658b1b532ea371644897a20df94e3819ef46a9deacd8a8fa763fe39c343ff9dcbbc7c70b4f1d8a51e04bcdb45931c89f7ec9d9787364eac5ac8334d3ebc3c581a0fffa1363eb170ddd51b7f0da49d316552629d4689e2b16be587d47a1fc8ff8b8d17ad031ce45cb3a8f95160428afd7fbcabb4b407e`),xN=(V(1)<<V(128))-V(1),SN=(V(1)<<V(64))-V(1),CN=(V(1)<<V(32))-V(1),wN=64,TN=wN/8,EN=8,DN=4;function ON(e){if(!e)throw Error(`Assert failed`)}function kN(e){let t=new DataView(new ArrayBuffer(8));return t.setBigUint64(0,e,!0),t.getBigUint64(0,!1)}function AN(e){let t=e;return t=(t&V(65535))<<V(16)|(t&V(4294901760))>>V(16),t=(t&V(16711935))<<V(8)|(t&V(4278255360))>>V(8),t}function jN(e,t){return(e&CN)*(t&CN)&SN}function MN(e,t){return(e<<t|e>>V(32)-t)&CN}function NN(e,t,n){for(let r=0;r<TN;r+=1){let i=t.getBigUint64(r*8,!0),a=i^n.getBigUint64(r*8,!0);e[r^1]+=i,e[r]+=jN(a,a>>V(32))}return e}function PN(e,t,n,r){for(let i=0;i<r;i+=1)NN(e,lN(t,i*wN),lN(n,i*8));return e}function FN(e,t){for(let n=0;n<TN;n+=1){let r=t.getBigUint64(n*8,!0),i=e[n];i=KN(i,V(47)),i^=r,i*=uN,e[n]=i&SN}return e}function IN(e,t){return BN(e[0]^t.getBigUint64(0,!0),e[1]^t.getBigUint64(EN,!0))}function LN(e,t,n){let r=n;return r+=IN(e.slice(0),lN(t,0*DN)),r+=IN(e.slice(2),lN(t,4*DN)),r+=IN(e.slice(4),lN(t,8*DN)),r+=IN(e.slice(6),lN(t,12*DN)),UN(r&SN)}function RN(e,t,n,r,i){let a=e,o=Math.floor((n.byteLength-wN)/8),s=wN*o,c=Math.floor((t.byteLength-1)/s);for(let e=0;e<c;e+=1)a=PN(a,lN(t,e*s),n,o),a=i(a,lN(n,n.byteLength-wN));{let e=Math.floor((t.byteLength-1-s*c)/wN);a=PN(a,lN(t,c*s),n,e),a=r(a,lN(t,t.byteLength-wN),lN(n,n.byteLength-wN-7))}return a}function zN(e,t){let n=new BigUint64Array([fN,pN,mN,hN,gN,dN,_N,uN]);ON(e.byteLength>128),n=RN(n,e,t,NN,FN),ON(n.length*8==64);{let r=LN(n,lN(t,11),V(e.byteLength)*pN&SN);return LN(n,lN(t,t.byteLength-wN-11),~(V(e.byteLength)*mN)&SN)<<V(64)|r}}function BN(e,t){let n=e*t&xN;return n&SN^n>>V(64)}function VN(e,t,n){return BN((e.getBigUint64(0,!0)^t.getBigUint64(0,!0)+n)&SN,(e.getBigUint64(8,!0)^t.getBigUint64(8,!0)-n)&SN)}function HN(e,t,n,r,i){let a=e&SN,o=e>>V(64)&SN;return a+=VN(t,r,i),a^=n.getBigUint64(0,!0)+n.getBigUint64(8,!0),a&=SN,o+=VN(n,lN(r,16),i),o^=t.getBigUint64(0,!0)+t.getBigUint64(8,!0),o&=SN,o<<V(64)|a}function UN(e){let t=e;return t^=t>>V(37),t*=vN,t&=SN,t^=t>>V(32),t}function WN(e){let t=e;return t^=t>>V(33),t*=mN,t&=SN,t^=t>>V(29),t*=hN,t&=SN,t^=t>>V(32),t}function GN(e,t,n){let r=e.byteLength;ON(r>0&&r<=3);let i=V(e.getUint8(r-1))|V(r<<8)|V(e.getUint8(0)<<16)|V(e.getUint8(r>>1)<<24),a=(i^(V(t.getUint32(0,!0))^V(t.getUint32(4,!0)))+n)&SN,o=(V(t.getUint32(8,!0))^V(t.getUint32(12,!0)))-n;return(WN((MN(AN(i),V(13))^o)&SN)&SN)<<V(64)|WN(a)}function KN(e,t){return e^e>>t}function qN(e,t,n){let r=e.byteLength;ON(r>=4&&r<=8);{let i=e.getUint32(0,!0),a=e.getUint32(r-4,!0),o=((V(i)|V(a)<<V(32))^(t.getBigUint64(16,!0)^t.getBigUint64(24,!0))+n&SN)*(pN+(V(r)<<V(2)))&xN;return o+=(o&SN)<<V(65),o&=xN,o^=o>>V(67),KN(KN(o&SN,V(35))*yN&SN,V(28))|UN(o>>V(64))<<V(64)}}function JN(e,t,n){let r=e.byteLength;ON(r>=9&&r<=16);{let i=(t.getBigUint64(32,!0)^t.getBigUint64(40,!0))+n&SN,a=(t.getBigUint64(48,!0)^t.getBigUint64(56,!0))-n&SN,o=e.getBigUint64(0,!0),s=e.getBigUint64(r-8,!0),c=(o^s^i)*pN,l=(c&SN)+(V(r-1)<<V(54));c=c&(xN^SN)|l,s^=a,c+=s+(s&CN)*(dN-V(1))<<V(64),c&=xN,c^=kN(c>>V(64));let u=(c&SN)*mN;return u+=(c>>V(64))*mN<<V(64),u&=xN,UN(u&SN)|UN(u>>V(64))<<V(64)}}function YN(e,t){let n=e.byteLength;return ON(n<=16),n>8?JN(e,bN,t):n>=4?qN(e,bN,t):n>0?GN(e,bN,t):WN(t^bN.getBigUint64(64,!0)^bN.getBigUint64(72,!0))|WN(t^bN.getBigUint64(80,!0)^bN.getBigUint64(88,!0))<<V(64)}function XN(e){return~e+V(1)&SN}function ZN(e,t,n){let r=V(e.byteLength)*pN&SN,i=V(e.byteLength-1)/V(32);for(;i>=0;){let a=Number(i);r=HN(r,lN(e,16*a),lN(e,e.byteLength-16*(a+1)),lN(t,32*a),n),i-=V(1)}let a=r+(r>>V(64))&SN;a=UN(a);let o=(r&SN)*pN+(r>>V(64))*gN+(V(e.byteLength)-n&SN)*mN;return o&=SN,o=XN(UN(o)),a|o<<V(64)}function QN(e,t,n){let r=V(e.byteLength)*pN&SN;for(let i=32;i<160;i+=32)r=HN(r,lN(e,i-32),lN(e,i-16),lN(t,i-32),n);r=UN(r&SN)|UN(r>>V(64))<<V(64);for(let i=160;i<=e.byteLength;i+=32)r=HN(r,lN(e,i-32),lN(e,i-16),lN(t,3+i-160),n);r=HN(r,lN(e,e.byteLength-16),lN(e,e.byteLength-32),lN(t,103),XN(n));let i=r+(r>>V(64))&SN;i=UN(i);let a=(r&SN)*pN+(r>>V(64))*gN+(V(e.byteLength)-n&SN)*mN;return a&=SN,a=XN(UN(a)),i|a<<V(64)}function $N(e,t=V(0)){let n=new TextEncoder,r=lN(typeof e==`string`?n.encode(e):e),i=r.byteLength;return(e=>e.toString(16).padStart(32,`0`))(i<=16?YN(r,t):i<=128?ZN(r,bN,t):i<=240?QN(r,bN,t):zN(r,bN))}function eP(e){return/^[0-9a-f]{32}$/.test(e)}function tP(e,t,n=!0,r=!1){try{return e[t].get()}catch(e){if(e.name===jS.unminifiable_name){if(r)return e;if(n)return null}throw e}}function nP(e,t,n=!0){if(Array.isArray(t)){let r={};for(let i of t)try{r[i]=tP(e,i,!n)}catch(e){if(e.name===jS.unminifiable_name)continue}return r}else return tP(e,t)}function*rP(e,t){if(e.graph===_S.PARENT)throw new MS(`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(fS(e))yield[oS,rS,e];else if(typeof e==`string`)yield[oS,`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(eP))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,Zx,e]}else yield[oS,Zx,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[oS,t,n];else for(let[t,n]of Object.entries(e.update))yield[oS,t,n]}}function*iP(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*aP(e,t,n){Array.isArray(e)?(t===!0||t.find(([t,n])=>e.includes(t)))&&(yield nP(n,e)):(t===!0||t.some(([t,n])=>t===e))&&(yield tP(n,e))}function*oP(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===$x).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 sP(e){let t=typeof e[Ox];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 cP(e,t){if(Object.keys(e).length>0){let n=sP(t);return Object.fromEntries(Object.entries(t).filter(([t,r])=>r>(e[t]??n)))}else return t}function lP(e,t){return e&&!Array.isArray(e)&&!(e instanceof Date)&&typeof e==`object`?e:{[t]:e}}function uP(e,t){return e===null?{configurable:t}:e?.configurable===void 0?{...e,configurable:t}:{...e,configurable:{...e.configurable,...t}}}function dP(e,t){let n=t?.parents??{};return Object.keys(n).length>0?uP(e,{[Jx]:{...n,[e.configurable?.checkpoint_ns??``]:e.configurable?.checkpoint_id}}):e}function fP(...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 pP=(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},mP=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 hP(e){return typeof e==`object`&&!!e&&`__lg_type`in e&&e.__lg_type===`call`}function gP(e,t){return new Jb({name:e,first:new WM({func:e=>t(...e),name:e,trace:!1,recurse:!1}),last:new $M([{channel:$x,value:XM}],[tS])})}var _P=e=>e===void 0?1:e+1;function vP(e,t){if(t==null)return!1;for(let n of e)if(t[n])return!0;return!1}function yP(e){let t;for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t=t==null?e[n]:mM(t,e[n]));return t}function bP(e,t,n){let r=sP(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(tS):t.includes(e.name));return a&&o}function xP(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=DM(e,i,-1),c=EM(i,s);wP(fM(s),c,[n],void 0,void 0),o=nP({...t,...c},r)}else o=nP(t,r);return o}function SP(e,t,n){for(let[e,r]of n)if([`__pregel_push`,`__pregel_tasks`].includes(e)&&r!=null){if(!fS(r))throw new MS(`Invalid packet type, expected SendProtocol, got ${JSON.stringify(r)}`);if(!(r.node in t))throw new MS(`Invalid node name "${r.node}" in Send packet`)}e(n)}var CP=new Set([Qx,iS,Zx,Xx,$x,jx]);function wP(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=TM(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=yP(e.channel_versions),c=new Set(n.flatMap(e=>e.triggers).filter(e=>!sS.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)CP.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===MS.unminifiable_name){let r=new MS(`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&&!vP(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*TP(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 EP(e,t,n,r,i,a,o){let s={},c=r[rS];if(c?.isAvailable()){let l=c.get().length;for(let c=0;c<l;c+=1){let l=DP([iS,c],e,t,n,r,i,a,o);l!==void 0&&(s[l.id]=l)}}for(let c of TP(e,n,o)){let l=DP([aS,c],e,t,n,r,i,a,o);l!==void 0&&(s[l.id]=l)}return s}function DP(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`&&hP(e[e.length-1])){let p=e[e.length-1],m=gP(p.name,p.func),h=[iS],g=f===``?p.name:`${f}|${p.name}`,_=fC(JSON.stringify([g,c.toString(),p.name,iS,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:{...Ml(Al(a,{metadata:b,store:s.store??a.store}),{runName:p.name,callbacks:u?.getChild(`graph:step:${c}`),configurable:{[Rx]:_,[Nx]:t=>SP(t=>e.push(...t),r,t),[Fx]:(n,r=!1)=>xP(t,i,{name:p.name,writes:e,triggers:h,path:y},n,r),[Ix]:l??d.__pregel_checkpointer,[Jx]:{...d[Jx],[f]:t.id},[Hx]:AP({pendingWrites:n??[],taskId:_,currentTaskInput:p.input,resumeMap:a.configurable?.[Vx],namespaceHash:$N(v)}),[Ux]:t.channel_values[eS],checkpoint_id:void 0,checkpoint_ns:v}}),executionInfo:o},triggers:h,retry_policy:p.retry,cache_key:p.cache?{key:$N((p.cache.keyFunc??JSON.stringify)([p.input])),ns:[Mx,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[rS].get();if(p<0||p>=m.length)return;let h=uS(m[p])&&!fS(m[p])?new dS(m[p].node,m[p].args):m[p];if(!uS(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=[iS],_=f===``?h.node:`${f}|${h.node}`,v=fC(JSON.stringify([_,c.toString(),h.node,iS,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:{...Ml(Al(a,{metadata:b,tags:o.tags,store:s.store??a.store}),{runName:h.node,callbacks:u?.getChild(`graph:step:${c}`),configurable:{[Rx]:v,[Nx]:e=>SP(e=>m.push(...e),r,e),[Fx]:(n,r=!1)=>xP(t,i,{name:h.node,writes:m,triggers:g,path:e},n,r),[Ix]:l??d.__pregel_checkpointer,[Jx]:{...d[Jx],[f]:t.id},[Hx]:AP({pendingWrites:n??[],taskId:v,currentTaskInput:h.args,resumeMap:a.configurable?.[Vx],namespaceHash:$N(y)}),[Ux]:t.channel_values[eS],checkpoint_id:void 0,checkpoint_ns:y}}),executionInfo:_},triggers:g,retry_policy:o.retryPolicy,cache_key:o.cachePolicy?{key:$N((o.cachePolicy.keyFunc??JSON.stringify)([h.args])),ns:[Mx,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=fC(JSON.stringify([e,c.toString(),p,aS,p]),t.id);if(n.some(e=>e[0]===r&&e[1]!==`__error__`))return}let h=sP(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=OP(m,i,o);if(h===void 0)return;let g=f===``?p:`${f}|${p}`,v=fC(JSON.stringify([g,c.toString(),p,aS,[_]]),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:{...Ml(Al(a,{metadata:b,tags:m.tags,store:s.store??a.store}),{runName:p,callbacks:u?.getChild(`graph:step:${c}`),configurable:{[Rx]:v,[Nx]:e=>SP(e=>{g.push(...e)},r,e),[Fx]:(n,r=!1)=>xP(t,i,{name:p,writes:g,triggers:[_],path:e},n,r),[Ix]:l??d.__pregel_checkpointer,[Jx]:{...d[Jx],[f]:t.id},[Hx]:AP({pendingWrites:n??[],taskId:v,currentTaskInput:h,resumeMap:a.configurable?.[Vx],namespaceHash:$N(y)}),[Ux]:t.channel_values[eS],checkpoint_id:void 0,checkpoint_ns:y}}),executionInfo:ee},triggers:[_],retry_policy:m.retryPolicy,cache_key:m.cachePolicy?{key:$N((m.cachePolicy.keyFunc??JSON.stringify)([h])),ns:[Mx,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 OP(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]=tP(t,i,!1)}catch(e){if(e.name===jS.unminifiable_name)return;throw e}else if(i in t)try{r[n]=tP(t,i,!1)}catch(e){if(e.name===jS.unminifiable_name)continue;throw e}}else if(Array.isArray(e.channels)){let n=!1;for(let i of e.channels)try{r=tP(t,i,!1),n=!0;break}catch(e){if(e.name===jS.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 kP(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 dS(e.node,n)}function AP({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 jP={blue:{start:`\x1B[34m`,end:`\x1B[0m`},green:{start:`\x1B[32m`,end:`\x1B[0m`},yellow:{start:`\x1B[33;1m`,end:`\x1B[0m`}},MP=(e,t)=>`${e.start}${t}${e.end}`;function*NP(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 PP(e){return typeof e!=`object`||!e?!1:`$writes`in e&&Array.isArray(e.$writes)}function FP(e){let t={};for(let[n,r]of e){let e=String(n);if(e in t){let n=PP(t[e])?t[e].$writes:[t[e]];n.push(r),t[e]={$writes:n}}else t[e]=r}return t}function*IP(e,t){for(let[{id:n,name:r,config:i},a]of e)i?.tags?.includes(`langsmith:hidden`)||(yield{id:n,name:r,result:FP(a.filter(([e])=>Array.isArray(t)?t.includes(e):e===t)),interrupts:a.filter(e=>e[0]===Xx).map(e=>e[1])})}function*LP(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(sN))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:nP(t,n),metadata:r,next:i.map(e=>e.name),tasks:RP(i,a,u,s),parentConfig:o?c(o):void 0}}function RP(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?FP(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 zP(e,t,n){console.log([`${MP(jP.blue,`[${e}:checkpoint]`)}`,`\x1b[1m State at the end of step ${e}:\x1b[0m\n`,JSON.stringify(nP(t,n),null,2)].join(``))}function BP(e,t){let n=t.length;console.log([`${MP(jP.blue,`[${e}:tasks]`)}`,`\x1b[1m Starting step ${e} with ${n} task${n===1?``:`s`}:\x1b[0m\n`,t.map(e=>`- ${MP(jP.green,String(e.name))} -> ${JSON.stringify(e.input,null,2)}`).join(`
185
- `)].join(``))}function VP(e,t,n){let r={};for(let[e,i]of t)n.includes(e)&&(r[e]||(r[e]=[]),r[e].push(i));console.log([`${MP(jP.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])=>`- ${MP(jP.yellow,e)} -> ${t.map(e=>JSON.stringify(e)).join(`, `)}`).join(`
186
- `)].join(``))}var HP=class extends Ll{_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}},UP=class extends Ll{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)}},WP=class extends yr{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 GP(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 KP(e){return e instanceof Error?{error:e.name,message:e.message}:{error:`Error`,message:JSON.stringify(e)}}function qP(e){return typeof e!=`object`||!e?!1:`configurable`in e&&typeof e.configurable==`object`&&e.configurable!=null}function JP(e){return!qP(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 YP(e){if(qP(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 XP(e){let t={...e,checkpoint:JP(e.config),parent_checkpoint:JP(e.parentConfig),config:YP(e.config),parent_config:YP(e.parentConfig),tasks:e.tasks.map(e=>{if(qP(e.state)){let t=JP(e.state);if(t!=null){let n={...e,checkpoint:t};return delete n.state,n}}return e})};return delete t.parentConfig,t}function ZP(e){let t=new TextEncoder;return new ReadableStream({async start(n){let r=e=>{n.enqueue(t.encode(`event: ${e.event}\ndata: ${GP(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:XP(e.payload)})}n===`checkpoints`&&(a=XP(i)),r({event:e?.length?`${n}|${e.join(`|`)}`:n,data:a})}}catch(e){r({event:`error`,data:KP(e)})}n.close()}})}var QP=Symbol.for(`INPUT_DONE`),$P=Symbol.for(`INPUT_RESUMING`),eF=25;function tF(...e){return new UP({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 nF=class extends xM{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}},rF=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=vS(this.input)&&this.input.resume!=null,i=this.input===$P,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=_P: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 nF(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=tF(r,n.configurable[zx]));let i=n.configurable?!(`checkpoint_id`in n.configurable):!0,a=n.configurable?.[Hx];n.configurable&&a&&(a.subgraphCounter>0&&(n=uP(n,{[Kx]:[n.configurable[Kx],a.subgraphCounter.toString()].join(`|`)})),a.subgraphCounter+=1);let o=Fx in(n.configurable??{});!o&&n.configurable?.checkpoint_ns!==void 0&&n.configurable?.checkpoint_ns!==``&&(n=uP(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=uP(n,{checkpoint_id:n.configurable[Jx][n.configurable?.checkpoint_ns]}));let c=n.configurable?.checkpoint_ns?.split(`|`)??[],l=await t.checkpointer?.getTuple(s)??{config:n,checkpoint:dM(),metadata:{source:`input`,step:-2,parents:{}},pendingWrites:[]};s={...n,...l.config,configurable:{checkpoint_ns:``,...n.configurable,...l.config.configurable}};let u=l.parentConfig,d=fM(l.checkpoint),f={...l.metadata},p=l.pendingWrites??[],m=EM(t.channelSpecs,d),h=(f.step??0)+1,g=h+(n.recursionLimit??eF)+1,_={...d.channel_versions},v=t.store?new bM(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 hM)&&(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`&&fS(t)?[e,kP(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=uP(this.checkpointConfig,{[Kx]:this.config.configurable?.checkpoint_ns??``,[Gx]: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]===Xx).flatMap(e=>e[1]);this._emit([[`updates`,{[Xx]:e}],[`values`,{[Xx]:e}]])}else t[0][0]!==`__error__`&&this._emit(qM(GM(oP(this.outputKeys,[[r,t]],n),`updates`)));n||this._emit(qM(GM(IP([[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(![QP,$P].includes(this.input))await this._first(t);else if(this.toInterrupt.length>0)throw this.status=`interrupt_before`,new wS;else if(Object.values(this.tasks).every(e=>e.writes.length>0)){let e=Object.values(this.tasks).flatMap(e=>e.writes);this.updatedChannels=wP(this.checkpoint,this.channels,Object.values(this.tasks),this.checkpointerGetNextVersion,this.triggerToNodes);let t=await KM(GM(aP(this.outputKeys,e,this.channels),`values`));if(this._emit(t),this.checkpointPendingWrites=[],await this._putCheckpoint({source:`loop`}),bP(this.checkpoint,this.interruptAfter,Object.values(this.tasks)))throw this.status=`interrupt_after`,new wS;this.config.configurable?.__pregel_resuming!==void 0&&delete this.config.configurable?.[Lx]}else return!1;if(this.step>this.stop)return this.status=`out_of_steps`,!1;if(this.tasks=EP(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 KM(GM(LP(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(bP(this.checkpoint,this.interruptBefore,Object.values(this.tasks)))throw this.status=`interrupt_before`,new wS;let n=await KM(GM(NP(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=nP(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=wP(this.checkpoint,this.channels,Object.values(this.tasks),this.checkpointerGetNextVersion,this.triggerToNodes),this._emit(qM(GM(aP(this.outputKeys,Object.values(this.tasks).flatMap(e=>e.writes),this.channels),`values`)))),kS(e)&&!e.interrupts.length&&this._emit([[`updates`,{[Xx]:[]}],[`values`,{[Xx]:[]}]])),t}async acceptPush(e,t,n){if(this.interruptAfter?.length>0&&bP(this.checkpoint,this.interruptAfter,[e])){this.toInterrupt.push(e);return}let r=DP([iS,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&&bP(this.checkpoint,this.interruptBefore,[r])){this.toInterrupt.push(r);return}this._emit(qM(GM(NP([r]),`tasks`))),this.debug&&BP(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 kS(e)&&!this.isNested}async _first(e){let{configurable:t}=this.config,n=t?.[Hx];if(n&&n.nullResume!==void 0&&this.putWrites(oS,[[Zx,n.nullResume]]),vS(this.input)){let e=this.input.resume!=null;if(this.input.resume!=null&&typeof this.input.resume==`object`&&Object.keys(this.input.resume).every(eP)&&(this.config.configurable??={},this.config.configurable[Vx]=this.input.resume),e&&this.checkpointer==null)throw Error(`Cannot use Command(resume=...) without checkpointer`);let t={};for(let[e,n,r]of rP(this.input,this.checkpointPendingWrites))t[e]??=[],t[e].push([n,r]);if(Object.keys(t).length===0)throw new AS(`Received empty Command input`);for(let[e,n]of Object.entries(t))this.putWrites(e,n)}let r=(this.checkpointPendingWrites??[]).filter(e=>e[0]===oS).map(e=>e.slice(1));r.length>0&&wP(this.checkpoint,this.channels,[{name:Ax,writes:r,triggers:[]}],this.checkpointerGetNextVersion,this.triggerToNodes);let i=vS(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[Xx]={...this.checkpoint.versions_seen[Xx],[e]:t}}let e=await KM(GM(aP(this.outputKeys,!0,this.channels),`values`));this._emit(e)}if(this.isResuming)this.input=$P;else if(i)await this._putCheckpoint({source:`input`}),this.input=QP;else{let t=await KM(iP(e,this.input));if(t.length>0){let e=EP(this.checkpoint,this.checkpointPendingWrites,this.nodes,this.channels,this.config,!0,{step:this.step});this.updatedChannels=wP(this.checkpoint,this.channels,Object.values(e).concat([{name:Ax,writes:t,triggers:[]}]),this.checkpointerGetNextVersion,this.triggerToNodes),await this._putCheckpoint({source:`input`}),this.input=QP}else if(`__pregel_resuming`in(this.config.configurable??{}))this.input=QP;else throw new AS(`Received no input writes for ${JSON.stringify(e,null,2)}`)}this.isNested||(this.config=uP(this.config,{[Lx]: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=uP(this.checkpointConfig,{[Kx]:this.config.configurable?.checkpoint_ns??``});let t={...this.checkpoint.channel_versions},n=cP(this.checkpointPreviousVersions,t);this.checkpointPreviousVersions=t,this._checkpointerPutAfterPrevious({config:{...this.checkpointConfig},checkpoint:fM(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=DM(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=uP(this.checkpointConfig,{[Kx]:this.config.configurable?.checkpoint_ns??``,[Gx]: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 iF(e){return mt(e?.message)}function aF(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 oF=class extends yr{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&&(xt(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]=aF(o,a,s))}handleLLMNewToken(e,t,n,r,i,a){let o=a?.chunk;this.emittedChatModelRunIds[n]=!0,this.metadatas[n]!==void 0&&(iF(o)?this._emit(this.metadatas[n],o.message,n):this._emit(this.metadatas[n],new Zt({content:e}),n))}handleLLMEnd(e,t){if(this.metadatas[t]!==void 0){if(!this.emittedChatModelRunIds[t]){let n=e.generations?.[0]?.[0];mt(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]=aF(a,i,s),typeof t==`object`)){for(let e of Object.values(t))if((mt(e)||ht(e))&&e.id!==void 0)this.seen[e.id]=e;else if(Array.isArray(e))for(let t of e)(mt(t)||ht(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(mt(e))this._emit(n,e,t,!0);else if(Array.isArray(e))for(let r of e)mt(r)&&this._emit(n,r,t,!0);else if(typeof e==`object`&&e){for(let r of Object.values(e))if(mt(r))this._emit(n,r,t,!0);else if(Array.isArray(r))for(let e of r)mt(e)&&this._emit(n,e,t,!0)}}}handleChainError(e,t){delete this.metadatas[t]}},sF=[400,401,402,403,404,405,406,407,409],cF=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&&sF.includes(+t)||e?.error?.code===`insufficient_quota`)};async function lF(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=uP(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,DS(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===_S.PARENT){let e=UM(t);s.command=new _S({...s.command,graph:e})}}if(OS(s)||i===void 0||(o+=1,o>=(i.maxAttempts??3))||!(i.retryOn??cF)(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=uP(l,{[Lx]:!0}),l.executionInfo!=null&&(l.executionInfo={...l.executionInfo,nodeAttempt:o+1,nodeFirstAttemptTime:u})}}return{task:e,result:c,error:s,signalAborted:r?.aborted}}var uF=Symbol.for(`promiseAdded`);function dF(){let e={next:()=>void 0,wait:Promise.resolve(uF)};function t(n){e.next=()=>{e.wait=new Promise(t),n(uF)}}return e.wait=new Promise(t),e}var fF=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),kS(t)||OS(t)&&!kS(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(kS(o)||OS(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}=fP(i,a,e),c={externalAbortSignal:i,timeoutAbortSignal:a,composedAbortSignal:o};return this.loop.config=uP(this.loop.config,{[Yx]:c}),{signals:c,disposeCombinedSignal:s}}async*_executeTasksWithRetry(e,t){let{retryPolicy:n,maxConcurrency:r,signals:i}=t??{},a=dF(),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=fP(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]=lF(t,n,{[Px]:pF?.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!==uF&&(yield t,l!=null&&(u.signal?.removeEventListener(`abort`,l),u.dispose?.()),delete o[t.task.id])}}_commit(e,t){if(t!==void 0)if(kS(t)){if(t.interrupts.length){let n=t.interrupts.map(e=>[Xx,e]),r=e.writes.filter(e=>e[0]===Zx);r.length&&n.push(...r),this.loop.putWrites(e.id,n)}}else OS(t)&&e.writes.length?this.loop.putWrites(e.id,e.writes):this.loop.putWrites(e.id,[[jx,{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([Qx,null]),this.loop.putWrites(e.id,e.writes)}};async function pF(e,t,n,r,i,a={}){let o=t.config?.configurable?.[Hx];if(!o)throw Error(`BUG: No scratchpad found on task ${t.name}__${t.id}`);let s=o.callCounter;o.callCounter+=1;let c=new mP({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===$x),t=l.writes.filter(([e])=>e===jx);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=lF(l,a.retry,{[Px]:pF.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 mF=class extends Error{constructor(e){super(e),this.name=`GraphValidationError`}};function hF({nodes:e,channels:t,inputChannels:n,outputChannels:r,streamChannels:i,interruptAfterNodes:a,interruptBeforeNodes:o}){if(!t)throw new mF(`Channels not provided`);let s=new Set,c=new Set;for(let[t,n]of Object.entries(e)){if(t===`__interrupt__`)throw new mF(`"Node name ${Xx} is reserved"`);if(n.constructor===iN)n.triggers.forEach(e=>s.add(e));else throw new mF(`Invalid node type ${typeof n}, expected PregelNode`)}for(let e of s)if(!(e in t))throw new mF(`Subscribed channel '${String(e)}' not in channels`);if(!Array.isArray(n)){if(!s.has(n))throw new mF(`Input channel ${String(n)} is not subscribed to by any node`)}else if(n.every(e=>!s.has(e)))throw new mF(`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 mF(`Output channel '${String(e)}' not in channels`);if(a&&a!==`*`){for(let t of a)if(!(t in e))throw new mF(`Node ${String(t)} not in nodes`)}if(o&&o!==`*`){for(let t of o)if(!(t in e))throw new mF(`Node ${String(t)} not in nodes`)}}function gF(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 _F=class e extends CM{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 jS;return this.values}checkpoint(){return[[...this.seen],this.values]}isAvailable(){return this.values.length!==0}};function vF(e){let t=wl.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 CS(`No checkpointer set`,{lc_error_code:`MISSING_CHECKPOINTER`});let r=n[Hx];r.interruptCounter+=1;let i=r.interruptCounter;if(r.resume.length>0&&i<r.resume.length)return n[Nx]?.([[Zx,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[Nx]?.([[Zx,r.resume]]),e}let a=n[Kx]?.split(`|`);throw new wS([{id:a?$N(a.join(`|`)):void 0,value:e}])}var yF=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 iN({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:XM,skipNone:!1});for(let[e,r]of Object.entries(t??{}))Wb.isRunnable(r)||typeof r==`function`?n.push({channel:e,value:XM,skipNone:!0,mapper:tx(r)}):n.push({channel:e,value:r,skipNone:!1});return new $M(n)}},bF=class extends Wb{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)}},xF=class extends bF{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 '${rS}' is reserved and cannot be used in the graph.`);this.channels[rS]=new _F({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=Al(this.config,e);return new this.constructor({...this,config:t})}validate(){hF({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=sN(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=EM(this.channels,t.checkpoint);if(t.pendingWrites?.length){let e=t.pendingWrites.filter(([e,t])=>e===oS).map(([e,t,n])=>[String(t),n]);e.length>0&&wP(t.checkpoint,i,[{name:Ax,writes:e,triggers:[]}],void 0,this.triggerToNodes)}let a=Object.values(EP(t.checkpoint,t.pendingWrites,this.nodes,i,t.config,!0,{step:(t.metadata?.step??-1)+1,store:this.store})),o=await KM(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:{[Ix]: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&&wP(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:nP(i,this.streamChannelsAsIs),next:u,tasks:RP(a,t?.pendingWrites??[],c,this.streamChannelsAsIs),metadata:l,config:dP(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 CS(`No checkpointer set`,{lc_error_code:`MISSING_CHECKPOINTER`});let r=e.configurable?.checkpoint_ns??``;if(r!==``&&e.configurable?.__pregel_checkpointer===void 0){let i=HM(r);for await(let[r,a]of this.getSubgraphsAsync(i,!0))if(r===i)return await a.getState(JM(e,{[Ix]:n}),{subgraphs:t?.subgraphs})}let i=Al(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 CS(`No checkpointer set`,{lc_error_code:`MISSING_CHECKPOINTER`});let r=e.configurable?.checkpoint_ns??``;if(r!==``&&e.configurable?.__pregel_checkpointer===void 0){let i=HM(r);for await(let[r,a]of this.getSubgraphsAsync(i,!0))if(r===i){yield*a.getStateHistory(JM(e,{[Ix]:n}),t);return}}let i=Al(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 CS(`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=HM(r);for await(let[,r]of this.getSubgraphsAsync(i,!0))return await r.bulkUpdateState(JM(e,{[Ix]:n}),t);throw Error(`Subgraph "${i}" not found`)}let i=async(e,t)=>{let r=this.config?Al(this.config,e):e,a=await n.getTuple(r),o=a===void 0?dM():fM(a.checkpoint),s={...a?.checkpoint.channel_versions},c=a?.metadata?.step??-1,l=JM(r,{checkpoint_ns:r.configurable?.checkpoint_ns??``}),u=r.metadata??{};a?.config.configurable&&(l=JM(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 MS(`Cannot create empty checkpoint with multiple updates`);return dP(await n.put(l,DM(o,void 0,c),{source:`update`,step:c+1,parents:a?.metadata?.parents??{}},{}),a?a.metadata:void 0)}let p=EM(this.channels,o);if(d===null&&f===`__end__`){if(t.length>1)throw new MS(`Cannot apply multiple updates when clearing state`);if(a){let e=EP(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]===oS).map(e=>e.slice(1));t.length>0&&wP(o,p,[{name:Ax,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]);wP(o,p,Object.values(e),n.getNextVersion.bind(n),this.triggerToNodes)}return dP(await n.put(l,DM(o,p,c),{...u,source:`update`,step:c+1,parents:a?.metadata?.parents??{}},cP(s,o.channel_versions)),a?a.metadata:void 0)}if(f===`__copy__`){if(t.length>1)throw new MS(`Cannot copy checkpoint with multiple updates`);if(a==null)throw new MS(`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=DM(o,void 0,c),s=await n.put(a.parentConfig??JM(a.config,{checkpoint_id:void 0}),r,{source:`fork`,step:c+1,parents:a.metadata?.parents??{}},{});if(e(d)){let e=EP(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(dP(s,a.metadata),Object.values(n).flat())}return dP(s,a.metadata)}if(f===`__input__`){if(t.length>1)throw new MS(`Cannot apply multiple updates when updating as input`);let e=await KM(iP(this.inputChannels,d));if(e.length===0)throw new MS(`Received no input writes for ${JSON.stringify(this.inputChannels,null,2)}`);wP(o,p,[{name:Ax,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,DM(o,p,r),{source:`input`,step:r,parents:a?.metadata?.parents??{}},cP(s,o.channel_versions));return await n.putWrites(i,e,fC(Ax,o.id)),dP(i,a?a.metadata:void 0)}if(r.configurable?.checkpoint_id===void 0&&a?.pendingWrites!==void 0&&a.pendingWrites.length>0){let e=EP(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]===oS).map(e=>e.slice(1));t.length>0&&wP(a.checkpoint,p,[{name:Ax,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&&wP(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!==Xx).sort(([e],[t])=>pM(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 MS(`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 MS(`"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 MS(`Node "${e.toString()}" does not exist`);let r=this.nodes[e].getWriters();if(!r.length)throw new MS(`No writers found for node "${e.toString()}"`);g.push({name:e,input:t,proc:r.length>1?Jb.from(r,{omitSequenceTags:!0}):r[0],writes:[],triggers:[Xx],id:n??fC(`__interrupt__`,o.id),writers:[]})}for(let e of g)await e.proc.invoke(e.input,Ml({...r,store:r?.store??this.store},{runName:r.runName??`${this.getName()}UpdateState`,configurable:{[Nx]:t=>e.writes.push(...t),[Fx]:(t,n=!1)=>xP(o,p,e,t,n)}}));for(let e of g){let t=e.writes.filter(e=>e[0]!==iS);a!==void 0&&t.length>0&&await n.putWrites(l,t,e.id)}wP(o,p,g,n.getNextVersion.bind(this.checkpointer),this.triggerToNodes);let _=cP(s,o.channel_versions),v=await n.put(l,DM(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]===iS);t.length>0&&await n.putWrites(v,t,e.id)}return dP(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:gF(u,this.channels);let d=r;d===void 0?d=this.inputChannels:gF(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[Ix];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:fP(t?.signal,n.signal).signal},i=await super.stream(e,r);return new HP(t?.encoding===`text/event-stream`?ZP(i):i,n)}streamEvents(e,t,n){let r=new AbortController,i={recursionLimit:this.config?.recursionLimit,...t,callbacks:pP(this.config?.callbacks,t?.callbacks),signal:fP(t?.signal,r.signal).signal};return new HP(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=BM(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 UP({modes:new Set(l)});if(this.checkpointer===!0){d.configurable??={};let e=d.configurable.checkpoint_ns??``;d.configurable[Kx]=e.split(`|`).map(e=>e.split(`:`)[0]).join(`|`)}if(l.includes(`messages`)){let e=new oF(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 WP(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=(VM()?.configurable?.[Kx])?.split(`|`).slice(0,-1);y.push([t??[],`custom`,e])},d.interrupt??=this.userInterrupt??vF,d.serverInfo??=SF(d);let b=await(await yl._configureSync(d?.callbacks,void 0,d?.tags,void 0,d?.metadata,void 0,{tracerInheritableMetadata:TF(d)}))?.handleChainStart(this.toJSON(),lP(e,`input`),o,void 0,void 0,void 0,d?.runName??this.getName()),ee=TM(this.channels),te,ne,x=(async()=>{try{te=await rF.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 fF({loop:te,nodeFinished:d.configurable?.[qx]});t?.subgraphs&&(te.config.configurable={...te.config.configurable,[zx]:te.stream}),await this._runLoop({loop:te,runner:e,debug:c,config:d}),v===`sync`&&await Promise.all(te?.checkpointerPromises??[])}catch(e){ne=e}finally{try{te&&(await te.store?.stop(),await te.cache?.stop()),await Promise.all(te?.checkpointerPromises??[])}catch(e){ne??=e}ne?y.error(ne):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(ne),e}finally{await x}await b?.handleChainEnd(te?.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`?gS(e)?o.push(e[Xx]):s=e:i.push(e);if(n===`values`){if(o.length>0){let e=o.flat(1);if(s==null)return{[Xx]:e};if(typeof s==`object`)return{...s,[Xx]: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&&zP(t.checkpointMetadata.step,t.channels,this.streamChannelsList),r&&BP(t.step,Object.values(t.tasks)),await n.tick({timeout:this.stepTimeout,retryPolicy:this.retryPolicy,onStepWrite:(e,t)=>{r&&VP(e,t,this.streamChannelsList)},maxConcurrency:i.maxConcurrency,signal:i.signal})}if(t.status===`out_of_steps`)throw new SS([`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 SF(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 CF=new Set([`key`,`token`,`secret`,`password`,`auth`]);function wF(e,t){let n=e.toLowerCase(),r=!1;for(let e of CF)if(n.includes(e)){r=!0;break}return e.startsWith(`__`)||!(typeof t==`string`||typeof t==`number`||typeof t==`boolean`)||r}function TF(e){let t=e.configurable;if(!t)return;let n={};for(let[e,r]of Object.entries(t))wF(e,r)||(n[e]=r);return Object.keys(n).length>0?n:void 0}var EF=/^(?:[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 DF(e){return typeof e==`string`&&EF.test(e)}for(var OF=[],kF=0;kF<256;++kF)OF.push((kF+256).toString(16).slice(1));function AF(e,t=0){return(OF[e[t+0]]+OF[e[t+1]]+OF[e[t+2]]+OF[e[t+3]]+`-`+OF[e[t+4]]+OF[e[t+5]]+`-`+OF[e[t+6]]+OF[e[t+7]]+`-`+OF[e[t+8]]+OF[e[t+9]]+`-`+OF[e[t+10]]+OF[e[t+11]]+OF[e[t+12]]+OF[e[t+13]]+OF[e[t+14]]+OF[e[t+15]]).toLowerCase()}var jF,MF=new Uint8Array(16);function NF(){if(!jF&&(jF=typeof crypto<`u`&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!jF))throw Error(`crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported`);return jF(MF)}var PF={randomUUID:typeof crypto<`u`&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function FF(e,t,n){if(PF.randomUUID&&!t&&!e)return PF.randomUUID();e||={};var r=e.random||(e.rng||NF)();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 AF(r)}var IF=class{path;ends;constructor(e){Wb.isRunnable(e.path)?this.path=e.path:this.path=tx(e.path),this.ends=Array.isArray(e.pathMap)?e.pathMap.reduce((e,t)=>(e[t]=t,e),{}):e.pathMap}run(e,t){return $M.registerWriter(new WM({name:`<branch_run>`,trace:!1,func:async(n,r)=>{try{return await this._route(n,r,e,t)}catch(e){throw e.name===TS.unminifiable_name&&console.warn(`[WARN]: 'NodeInterrupt' thrown in conditional edge. This is likely a bug in your graph implementation.
187
- 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=>fS(e)?e:this.ends[e]):i,a.some(e=>!e))throw Error(`Branch condition returned unknown or null destination`);if(a.filter(fS).some(e=>e.node===`__end__`))throw new MS(`Cannot send a packet to the END node`);return await n(a,t)??e}},LF=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=tx(t);this.nodes[e]={runnable:n,metadata:r?.metadata,subgraphs:oN(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.`),Wb.isRunnable(r.path)||(r.path=tx(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 IF(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(Ox,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,kx)}compile({checkpointer:e,interruptBefore:t,interruptAfter:n,name:r}={}){this.validate([...Array.isArray(t)?t:[],...Array.isArray(n)?n:[]]);let i=new RF({builder:this,checkpointer:e,interruptAfter:n,interruptBefore:t,autoValidate:!1,nodes:{},channels:{[Ox]:new cN,[kx]:new cN},inputChannels:Ox,outputChannels:kx,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(kx);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 NS([`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(`
188
- `),{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}},RF=class extends xF{builder;constructor({builder:e,...t}){super(t),this.builder=e}attachNode(e,t){this.channels[e]=new cN,this.nodes[e]=new iN({channels:[],triggers:[],metadata:t.metadata,subgraphs:t.subgraphs,ends:t.ends}).pipe(t.runnable).pipe(new $M([{channel:e,value:XM}],[tS])),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 $M([{channel:kx,value:XM}],[tS]))}else this.nodes[t].triggers.push(e),this.nodes[t].channels.push(e)}attachBranch(e,t,n){e===`__start__`&&!this.nodes.__start__&&(this.nodes[Ox]=yF.subscribeTo(Ox,{tags:[tS]})),this.nodes[e].pipe(n.run(n=>new $M(n.map(n=>fS(n)?n:{channel:n===`__end__`?kx:`branch:${e}:${t}:${n}`,value:XM}),[tS])));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 cN,this.nodes[n].triggers.push(r),this.nodes[n].channels.push(r)}}async getGraphAsync(e){let t=e?.xray,n=new Mb,r={[Ox]:n.addNode({schema:Mk()},Ox)},i={},a={};t&&(a=Object.fromEntries((await KM(this.getSubgraphsAsync())).filter(e=>zF(e[1]))));function o(e,t,a,o=!1){if(t===`__end__`&&i.__end__===void 0&&(i[kx]=n.addNode({schema:Mk()},kx)),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=BF(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&&!DF(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(BF(e),BF(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=>[BF(e),BF(e)])),[kx]:kx};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(BF(e),BF(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(BF(e),BF(n),void 0,!0);return n}getGraph(e){let t=e?.xray,n=new Mb,r={[Ox]:n.addNode({schema:Mk()},Ox)},i={},a={};t&&(a=Object.fromEntries(qM(this.getSubgraphs()).filter(e=>zF(e[1]))));function o(e,t,a,o=!1){return t===`__end__`&&i.__end__===void 0&&(i[kx]=n.addNode({schema:Mk()},kx)),n.addEdge(r[e],i[t],a===t?void 0:a,o)}for(let[o,s]of Object.entries(this.builder.nodes)){let c=BF(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&&!DF(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(BF(e),BF(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=>[BF(e),BF(e)])),[kx]:kx};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(BF(e),BF(r),n,!0)}}return n}};function zF(e){return typeof e.attachNode==`function`&&typeof e.attachEdge==`function`}function BF(e){return e===`subgraph`?`"${e}"`:e}var VF=(e,t)=>e.size===t.size&&[...e].every(e=>t.has(e)),HF=class e extends CM{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 MS(`Value ${JSON.stringify(n)} not in names ${JSON.stringify(this.names)}`);return t}get(){if(!VF(this.names,this.seen))throw new jS}checkpoint(){return[...this.seen]}consume(){return this.seen&&this.names&&VF(this.seen,this.names)?(this.seen=new Set,!0):!1}isAvailable(){return!!this.names&&VF(this.names,this.seen)}},UF=class e extends CM{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 MS(`Value ${JSON.stringify(n)} not in names ${JSON.stringify(this.names)}`);return t}get(){if(!this.finished||!VF(this.names,this.seen))throw new jS}checkpoint(){return[[...this.seen],this.finished]}consume(){return this.finished&&this.seen&&this.names&&VF(this.seen,this.names)?(this.seen=new Set,this.finished=!1,!0):!1}finish(){return!this.finished&&this.names&&VF(this.names,this.seen)?(this.finished=!0,!0):!1}isAvailable(){return this.finished&&!!this.names&&VF(this.names,this.seen)}};function WF(e){return typeof e==`object`&&!!e&&`~standard`in e&&typeof e[`~standard`]==`object`&&e[`~standard`]!==null&&`validate`in e[`~standard`]}function GF(e){return typeof e==`object`&&!!e&&`~standard`in e&&typeof e[`~standard`]==`object`&&e[`~standard`]!==null&&`jsonSchema`in e[`~standard`]}function KF(e){if(GF(e))try{return e[`~standard`].jsonSchema.input({target:`draft-07`})}catch{return}}function qF(e){if(e!=null&&WF(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 JF=Symbol.for(`langgraph.channel.missing`),YF=class e extends CM{lc_graph_name=`UntrackedValue`;guard;_value=JF;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 MS(`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===JF)throw new jS;return this._value}checkpoint(){}isAvailable(){return this._value!==JF}},XF=Symbol.for(`langgraph.state.reduced_value`),ZF=class{[XF]=!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&&XF in e&&e[XF]===!0}},QF=Symbol.for(`langgraph.state.untracked_value`),$F=class{[QF]=!0;schema;guard;constructor(e,t){this.schema=e,this.guard=t?.guard??!0}static isInstance(e){return typeof e==`object`&&!!e&&QF in e}},eI=Symbol.for(`langgraph.state.state_schema`),tI=class{[eI]=!0;constructor(e){this.fields=e}getChannels(){let e={};for(let[t,n]of Object.entries(this.fields))if(ZF.isInstance(n)){let r=qF(n.valueSchema);e[t]=new jM(n.reducer,r)}else if($F.isInstance(n)){let r=n.schema?qF(n.schema):void 0;e[t]=new YF({guard:n.guard,initialValueFactory:r})}else if(WF(n))e[t]=new OM(qF(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(ZF.isInstance(r)?(i=KF(r.valueSchema),r.jsonSchemaExtra&&(i={...i??{},...r.jsonSchemaExtra})):$F.isInstance(r)?i=r.schema?KF(r.schema):void 0:WF(r)&&(i=KF(r)),i){e[n]=i;let a=!1;a=ZF.isInstance(r)?qF(r.valueSchema)!==void 0:$F.isInstance(r)?r.schema?qF(r.schema)!==void 0:!1:qF(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;ZF.isInstance(n)?(r=KF(n.inputSchema),n.jsonSchemaExtra&&(r={...r??{},...n.jsonSchemaExtra})):$F.isInstance(n)?r=n.schema?KF(n.schema):void 0:WF(n)&&(r=KF(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(ZF.isInstance(e)?i=e.inputSchema:$F.isInstance(e)?i=e.schema:WF(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&&eI in e&&e[eI]===!0}};function nI(e,t){let n=Array.isArray(e)?e:[e],r=Array.isArray(t)?t:[t],i=n.map(bn),a=r.map(bn);for(let e of i)(e.id===null||e.id===void 0)&&(e.id=FF(),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=FF(),t.lc_kwargs.id=t.id),dn.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)dn.isInstance(e)?l.add(e.id):(l.delete(e.id),s[t]=e);else{if(dn.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 ZF(xA().default(()=>[]),{inputSchema:xA(),reducer:nI,jsonSchemaExtra:{langgraph_type:`messages`,description:`A list of chat messages`}});var rI=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=zg(e);for(let[e,r]of Object.entries(n)){let n=this.get(r);n?.reducer?t[e]=new jM(n.reducer.fn,n.default):t[e]=new OM(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(zg(e)).map(([e,n])=>{let r=this.get(n),i=t.withReducerSchema?r?.reducer?.schema??n:n;if(t.withJsonSchemaExtrasAsDescription&&r?.jsonSchemaExtra){let e=Ag(i)??Ag(n),t=JSON.stringify({...r.jsonSchemaExtra,description:e});i=i.describe(`lg:${t}`)}return[e,i]});i=Bg(e,Object.fromEntries(n)),bg(i)&&(i._def.unknownKeys=`strip`)}return t.asPartial&&(i=Vg(i)),r.set(e,i),this._extensionCache.set(n,r),i}};function iI(e){return e==null?!1:!!(tI.isInstance(e)||Rg(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`||SM(e)))}function aI(e){if(typeof e!=`object`||!e)return!1;let t=e,n=`state`in t&&iI(t.state),r=`stateSchema`in t&&iI(t.stateSchema),i=`input`in t&&iI(t.input);return!(!n&&!r&&!i||`input`in t&&t.input!=null&&!iI(t.input)||`output`in t&&t.output!=null&&!iI(t.output))}var oI=`__root__`,sI=Symbol.for(`langgraph.state.partial`),cI=class extends LF{channels={};waitingEdges=new Set;_schemaDefinition;_schemaRuntimeDefinition;_inputDefinition;_inputRuntimeDefinition;_outputDefinition;_outputRuntimeDefinition;_schemaDefinitions=new Map;_metaRegistry=rI;_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 PS;let i=this._getChannelsFromSchema(r);this._schemaDefinition=i,(tI.isInstance(r)||Rg(r))&&(this._schemaRuntimeDefinition=r),n.input&&(tI.isInstance(n.input)||Rg(n.input))?this._inputRuntimeDefinition=n.input:this._inputRuntimeDefinition=sI,n.output&&(tI.isInstance(n.output)||Rg(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&&Rg(n.context)&&(this._configRuntimeSchema=n.context),this._interrupt=n.interrupt,this._writer=n.writer}_normalizeToStateGraphInit(e,t){if(aI(e)){if(Rg(t)||MM.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(iI(e)){if(Rg(t)||MM.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(dI(e))return{state:lI(e.channels)};throw new PS}_getChannelsFromSchema(e){if(tI.isInstance(e))return e.getChannels();if(Rg(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 PS(`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=Wb.isRunnable(t)?t:typeof t==`function`?new WM({func:t,name:e,trace:!1}):tx(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:oN(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]===oI?oI:s,l=Object.keys(this.channels),u=l.length===1&&l[0]===oI?oI:l,d=this._interrupt,f=new uI({builder:this,checkpointer:e,interruptAfter:i,interruptBefore:r,autoValidate:!1,nodes:{},channels:{...this.channels,[Ox]:new cN},inputChannels:Ox,outputChannels:c,streamChannels:u,streamMode:`updates`,store:t,cache:n,name:a,description:o,userInterrupt:d});f.attachNode(Ox);for(let[e,t]of Object.entries(this.nodes))f.attachNode(e,t);f.attachBranch(Ox,nS,pI(),{withReader:!1});for(let[e]of Object.entries(this.nodes))f.attachBranch(e,nS,pI(),{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 lI(e){let t={};for(let[n,r]of Object.entries(e))t[n]=PM(r);return t}var uI=class extends RF{description;_metaRegistry=rI;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(vS(e))return e.graph===_S.PARENT?null:e._updateAsTuples();if(Array.isArray(e)&&e.length>0&&e.some(e=>vS(e))){let t=[];for(let n of e)if(vS(n)){if(n.graph===_S.PARENT)continue;t.push(...n._updateAsTuples())}else t.push([oI,n]);return t}else if(e!=null)return[[oI,e]];return null}let i=e;function a(e){if(!e)return null;if(vS(e))return e.graph===_S.PARENT?null:e._updateAsTuples().filter(([e])=>n.includes(e));if(Array.isArray(e)&&e.length>0&&e.some(vS)){let t=[];for(let r of e)if(vS(r)){if(r.graph===_S.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 MS(`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:XM,mapper:new WM({func:n.length&&n[0]===oI?r:a,trace:!1,recurse:!1})}];if(e===`__start__`)this.nodes[e]=new iN({tags:[tS],triggers:[Ox],channels:[Ox],writers:[new $M(o,[tS])]});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&&oI in r,a=`branch:to:${e}`;this.channels[a]=t?.defer?new kM:new cN(!1),this.nodes[e]=new iN({triggers:[a],channels:i?Object.keys(r):r,writers:[new $M(o,[tS])],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 $M([{channel:`branch:to:${t}`,value:null}],[tS]));else if(Array.isArray(e)){let n=`join:${e.join(`+`)}:${t}`;this.channels[n]=this.builder.nodes[t].defer?new UF(new Set(e)):new HF(new Set(e)),this.nodes[t].triggers.push(n);for(let t of e)this.nodes[t].writers.push(new $M([{channel:n,value:t}],[tS]))}}}attachBranch(e,t,n,r={withReader:!0}){this.nodes[e].writers.push(n.run(async(t,n)=>{let r=t.filter(e=>e!==kx);if(!r.length)return;let i=r.map(t=>fS(t)?t:{channel:t===`__end__`?t:`branch:to:${t}`,value:e});await $M.doWrite({...n,tags:(n.tags??[]).concat([tS])},i)},r.withReader?e=>nN.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(tI.isInstance(t)){if(vS(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===sI&&tI.isInstance(n)){if(vS(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(Rg(t))return e(t);if(t===sI)return Rg(n)?Vg(e(n)):void 0})();if(vS(e)){let t=e;return e.update&&r!=null&&(t.update=kg(r,e.update)),t}return r==null?e:kg(r,e)}isInterrupted(e){return gS(e)}async _validateContext(e){let t=this.builder._configRuntimeSchema;return Rg(t)&&kg(t,e),e}};function dI(e){return typeof e==`object`&&!!e&&e.channels!==void 0}function fI(e){if(fS(e))return[e];let t=[];vS(e)?t.push(e):Array.isArray(e)&&t.push(...e.filter(vS));let n=[];for(let e of t){if(e.graph===_S.PARENT)throw new ES(e);fS(e.goto)||typeof e.goto==`string`?n.push(e.goto):Array.isArray(e.goto)&&n.push(...e.goto)}return n}function pI(){return new IF({path:new WM({func:fI,tags:[tS],trace:!1,recurse:!1,name:`<control_branch>`})})}var mI=e=>Array.isArray(e)&&e.every(mt),hI=e=>typeof e==`object`&&!!e&&`messages`in e&&mI(e.messages),gI=e=>typeof e==`object`&&!!e&&`lg_tool_call`in e,_I=class extends WM{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 mt(r)&&r.getType()===`tool`||vS(r)?r:new vt({status:`success`,name:n.name,content:typeof r==`string`?r:JSON.stringify(r),tool_call_id:e.id})}catch(t){if(!this.handleToolErrors||kS(t))throw t;return new vt({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(gI(e))n=[await this.runTool(e.lg_tool_call,t)];else{let r;if(mI(e))r=e;else if(hI(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(Yt(t)){a=t;break}}if(a==null||!Yt(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(vS))return Array.isArray(e)?n:{messages:n};let r=[],i=null;for(let t of n)vS(t)?t.graph===_S.PARENT&&Array.isArray(t.goto)&&t.goto.every(e=>fS(e))?i?i.goto.push(...t.goto):i=new _S({graph:_S.PARENT,goto:t.goto}):r.push(t):r.push(Array.isArray(e)?[t]:{messages:[t]});return i&&r.push(i),r}},vI=/<name>(.*?)<\/name>/s,yI=/<content>(.*?)<\/content>/s;function bI(e){if(!(mt(e)&&(Yt(e)||ht(e)&&Xt(e)))||!e.name)return e;let{name:t}=e;if(typeof e.content==`string`)return new Jt({...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 Jt({...e.lc_kwargs,content:n,name:void 0})}function xI(e){if(!Yt(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(vI),r=e.text.match(yI);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(vI),r=e.text.match(yI);return!t||!r?e:(n=t[1],{...e,text:r[1]})}return e});else{let r=e.content,i=r.match(vI),a=r.match(yI);if(!i||!a)return e;n=i[1],t=a[1]}return new Jt({...Object.keys(e.lc_kwargs??{}).length>0?e.lc_kwargs:e,content:t,name:n})}function SI(e,t){let n,r;if(t===`inline`)n=bI,r=xI;else throw Error(`Invalid agent name mode: ${t}. Needs to be one of: "inline"`);function i(e){return e.map(n)}return Jb.from([Qb.from(i),e,Qb.from(r)])}function CI(e){if(typeof e==`string`||mt(e)&&e._getType()===`system`)return e;if(typeof e==`function`)return async t=>e(t.messages);if(Wb.isRunnable(e))return Qb.from(e=>e.messages).pipe(e);throw Error(`Unexpected type for messageModifier: ${typeof e}`)}var wI=`prompt`;function TI(e){let t;if(e==null)t=Qb.from(e=>e.messages).withConfig({runName:wI});else if(typeof e==`string`){let n=new fn(e);t=Qb.from(e=>[n,...e.messages??[]]).withConfig({runName:wI})}else if(mt(e)&&e._getType()===`system`)t=Qb.from(t=>[e,...t.messages]).withConfig({runName:wI});else if(typeof e==`function`)t=Qb.from(e).withConfig({runName:wI});else if(Wb.isRunnable(e))t=e;else throw Error(`Got unexpected type for 'prompt': ${typeof e}`);return t}function EI(e){return Wb.isRunnable(e)}function DI(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=CI(n)):r=t,TI(r)}function OI(e){return`invoke`in e&&typeof e.invoke==`function`&&`_modelType`in e}function kI(e){return`_queuedMethodOperations`in e&&`_model`in e&&typeof e._model==`function`}function AI(e){return OI(e)?`bindTools`in e&&typeof e.bindTools==`function`:!1}async function jI(e,t){let n=e;if(Jb.isRunnableSequence(n)&&(n=n.steps.find(e=>Gb.isRunnableBinding(e)||OI(e)||kI(e))||n),kI(n)&&(n=await n._model()),!Gb.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=>EI(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 MI=(e,t)=>{if(AI(e))return e.bindTools(t);if(Gb.isRunnableBinding(e)&&AI(e.bound)){let n=e.bound.bindTools(t);return Gb.isRunnableBinding(n)?new Gb({bound:n.bound,config:{...e.config,...n.config},kwargs:{...e.kwargs,...n.kwargs},configFactories:n.configFactories??e.configFactories}):new Gb({bound:n,config:e.config,kwargs:e.kwargs,configFactories:e.configFactories})}return null};async function NI(e,t){let n=MI(e,t);if(n)return n;if(kI(e)){let n=MI(await e._model(),t);if(n)return n}if(Jb.isRunnableSequence(e)){let n=e.steps.findIndex(e=>Gb.isRunnableBinding(e)||OI(e)||kI(e));if(n>=0){let r=MI(e.steps[n],t);if(r){let t=e.steps.slice();return t.splice(n,1,r),Jb.from(t)}}}throw Error(`llm ${e} must define bindTools method.`)}async function PI(e){let t=e;if(Jb.isRunnableSequence(t)&&(t=t.steps.find(e=>Gb.isRunnableBinding(e)||OI(e)||kI(e))||t),kI(t)&&(t=await t._model()),Gb.isRunnableBinding(t)&&(t=t.bound),!OI(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 FI=()=>NM.Root({messages:NM({reducer:nI,default:()=>[]}),structuredResponse:NM}),II=NM.Root({llmInputMessages:NM({reducer:(e,t)=>nI([],t),default:()=>[]})});function LI(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 _I(b.filter(EI))):(b=n.tools,ee=n);let te=null,ne=async e=>{if(te)return te;let t;t=await jI(e,b)?await NI(e,b):e;let n=DI(a,i,r),o=y===`inline`?SI(t,y):t;return te=n.pipe(o),te},x=async(e,t,n)=>{let o=await e(t,n);return DI(a,i,r).pipe(y===`inline`?SI(o,y):o)},re=new Set(b.filter(EI).filter(e=>`returnDirect`in e&&e.returnDirect).map(e=>e.name));function ie(e){let{messages:t,llmInputMessages:n,...r}=e;return n!=null&&n.length>0?{messages:n,...r}:{messages:t,...r}}let ae=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 PI(t);if(!OI(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 fn({content:e}))}else i=a.withStructuredOutput(p);return{structuredResponse:await i.invoke(r,n)}},oe=async(e,n)=>{let r=await(typeof t==`function`?await x(t,e,n):await ne(t)).invoke(ie(e),n);return r.name=g,r.lc_kwargs.name=g,{messages:[r]}},se=new cI(o??FI(),s).addNode(`tools`,ee);if(!(`messages`in se._schemaDefinition))throw Error("Missing required `messages` key in state schema.");let ce=se,le=e=>Object.fromEntries(Object.entries(e).filter(([e,t])=>t!=null)),S=`agent`,ue;return m==null?S=`agent`:(ce.addNode(`pre_model_hook`,m).addEdge(`pre_model_hook`,`agent`),S=`pre_model_hook`,ue=NM.Root({...se._schemaDefinition,...II.spec})),ce.addNode(`agent`,oe,{input:ue}).addEdge(Ox,S),h!=null&&ce.addNode(`post_model_hook`,h).addEdge(`agent`,`post_model_hook`).addConditionalEdges(`post_model_hook`,e=>{let{messages:t}=e,n=new Set(t.filter(xt).map(e=>e.tool_call_id)),r;for(let e=t.length-1;e>=0;--e){let n=t[e];if(Yt(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 dS(`tools`,{...e,lg_tool_call:t})):`tools`:a&&xt(a)?S:p==null?kx:`generate_structured_response`},le({tools:`tools`,[S]:S,generate_structured_response:p==null?null:`generate_structured_response`,[kx]:p==null?kx:null})),p!==void 0&&se.addNode(`generate_structured_response`,ae).addEdge(`generate_structured_response`,kx),h??ce.addConditionalEdges(`agent`,e=>{let{messages:t}=e,n=t[t.length-1];return!Yt(n)||!n.tool_calls?.length?p==null?kx:`generate_structured_response`:v===`v2`?n.tool_calls.map(t=>new dS(`tools`,{...e,lg_tool_call:t})):`tools`},le({tools:`tools`,generate_structured_response:p==null?null:`generate_structured_response`,[kx]:p==null?kx:null})),re.size>0?ce.addConditionalEdges(`tools`,e=>{let t=e;for(let e=t.messages.length-1;e>=0;--e){let n=t.messages[e];if(!xt(n))break;if(n.name!==void 0&&re.has(n.name))return kx}return S},le({[S]:S,[kx]:kx})):ce.addEdge(`tools`,S),ce.compile({checkpointer:l??c,interruptBefore:u,interruptAfter:d,store:f,name:g,description:_})}function RI(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 H(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 U(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 zI=function(){let{crypto:e}=globalThis;if(e?.randomUUID)return zI=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 BI(e){return typeof e==`object`&&!!e&&(`name`in e&&e.name===`AbortError`||`message`in e&&String(e.message).includes(`FetchRequestCanceledException`))}var VI=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)},W=class extends Error{},HI=class e extends W{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 WI({message:r,cause:VI(n)});let a=n?.error;return t===400?new KI(t,a,r,i):t===401?new qI(t,a,r,i):t===403?new JI(t,a,r,i):t===404?new YI(t,a,r,i):t===409?new XI(t,a,r,i):t===422?new ZI(t,a,r,i):t===429?new QI(t,a,r,i):t>=500?new $I(t,a,r,i):new e(t,a,r,i)}},UI=class extends HI{constructor({message:e}={}){super(void 0,void 0,e||`Request was aborted.`,void 0)}},WI=class extends HI{constructor({message:e,cause:t}){super(void 0,void 0,e||`Connection error.`,void 0),t&&(this.cause=t)}},GI=class extends WI{constructor({message:e}={}){super({message:e??`Request timed out.`})}},KI=class extends HI{},qI=class extends HI{},JI=class extends HI{},YI=class extends HI{},XI=class extends HI{},ZI=class extends HI{},QI=class extends HI{},$I=class extends HI{},eL=class extends W{constructor(){super(`Could not parse response content as the length limit was reached`)}},tL=class extends W{constructor(){super(`Could not parse response content as the request was rejected by the content filter`)}},nL=class extends Error{constructor(e){super(e)}},rL=class extends HI{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}},iL=class extends W{constructor(e,t,n){super(e),this.provider=t,this.cause=n}},aL=/^[a-z][a-z0-9+.-]*:/i,oL=e=>aL.test(e),sL=e=>(sL=Array.isArray,sL(e)),cL=sL;function lL(e){return typeof e==`object`?e??{}:{}}function uL(e){if(!e)return!0;for(let t in e)return!1;return!0}function dL(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function fL(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var pL=(e,t)=>{if(typeof t!=`number`||!Number.isInteger(t))throw new W(`${e} must be an integer`);if(t<0)throw new W(`${e} must be a positive integer`);return t},mL=e=>{try{return JSON.parse(e)}catch{return}},hL=e=>new Promise(t=>setTimeout(t,e)),gL=`6.34.0`,_L=()=>typeof window<`u`&&window.document!==void 0&&typeof navigator<`u`;function vL(){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 yL=()=>{let e=vL();if(e===`deno`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":gL,"X-Stainless-OS":SL(Deno.build.os),"X-Stainless-Arch":xL(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":gL,"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":gL,"X-Stainless-OS":SL(globalThis.process.platform??`unknown`),"X-Stainless-Arch":xL(globalThis.process.arch??`unknown`),"X-Stainless-Runtime":`node`,"X-Stainless-Runtime-Version":globalThis.process.version??`unknown`};let t=bL();return t?{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":gL,"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":gL,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`unknown`,"X-Stainless-Runtime":`unknown`,"X-Stainless-Runtime-Version":`unknown`}};function bL(){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 xL=e=>e===`x32`?`x32`:e===`x86_64`||e===`x64`?`x64`:e===`arm`?`arm`:e===`aarch64`||e===`arm64`?`arm64`:e?`other:${e}`:`unknown`,SL=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`),CL,wL=()=>CL??=yL();function TL(){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 EL(...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 DL(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return EL({start(){},async pull(e){let{done:n,value:r}=await t.next();n?e.close():e.enqueue(r)},async cancel(){await t.return?.()}})}function OL(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 kL(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 AL=({headers:e,body:t})=>({bodyHeaders:{"content-type":`application/json`},body:JSON.stringify(t)}),jL=`RFC3986`,ML=e=>String(e),NL={RFC1738:e=>String(e).replace(/%20/g,`+`),RFC3986:ML},PL=(e,t)=>(PL=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),PL(e,t)),FL=(()=>{let e=[];for(let t=0;t<256;++t)e.push(`%`+((t<16?`0`:``)+t.toString(16)).toUpperCase());return e})(),IL=1024,LL=(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+=IL){let t=a.length>=IL?a.slice(e,e+IL):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]=FL[r];continue}if(r<2048){n[n.length]=FL[192|r>>6]+FL[128|r&63];continue}if(r<55296||r>=57344){n[n.length]=FL[224|r>>12]+FL[128|r>>6&63]+FL[128|r&63];continue}e+=1,r=65536+((r&1023)<<10|t.charCodeAt(e)&1023),n[n.length]=FL[240|r>>18]+FL[128|r>>12&63]+FL[128|r>>6&63]+FL[128|r&63]}o+=n.join(``)}return o};function RL(e){return!e||typeof e!=`object`?!1:!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))}function zL(e,t){if(sL(e)){let n=[];for(let r=0;r<e.length;r+=1)n.push(t(e[r]));return n}return t(e)}var BL={brackets(e){return String(e)+`[]`},comma:`comma`,indices(e,t){return String(e)+`[`+t+`]`},repeat(e){return String(e)}},VL=function(e,t){Array.prototype.push.apply(e,sL(t)?t:[t])},HL,UL={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:`indices`,charset:`utf-8`,charsetSentinel:!1,delimiter:`&`,encode:!0,encodeDotInKeys:!1,encoder:LL,encodeValuesOnly:!1,format:jL,formatter:ML,indices:!1,serializeDate(e){return(HL??=Function.prototype.call.bind(Date.prototype.toISOString))(e)},skipNulls:!1,strictNullHandling:!1};function WL(e){return typeof e==`string`||typeof e==`number`||typeof e==`boolean`||typeof e==`symbol`||typeof e==`bigint`}var GL={};function KL(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(GL))!==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(GL)===void 0&&(b=0)}if(typeof l==`function`?v=l(t,v):v instanceof Date?v=f?.(v):n===`comma`&&sL(v)&&(v=zL(v,function(e){return e instanceof Date?f?.(e):e})),v===null){if(a)return c&&!h?c(t,UL.encoder,g,`key`,p):t;v=``}if(WL(v)||RL(v)){if(c){let e=h?t:c(t,UL.encoder,g,`key`,p);return[m?.(e)+`=`+m?.(c(v,UL.encoder,g,`value`,p))]}return[m?.(t)+`=`+m?.(String(v))]}let te=[];if(v===void 0)return te;let ne;if(n===`comma`&&sL(v))h&&c&&(v=zL(v,c)),ne=[{value:v.length>0?v.join(`,`)||null:void 0}];else if(sL(l))ne=l;else{let e=Object.keys(v);ne=u?e.sort(u):e}let x=s?String(t).replace(/\./g,`%2E`):String(t),re=r&&sL(v)&&v.length===1?x+`[]`:x;if(i&&sL(v)&&v.length===0)return re+`[]`;for(let t=0;t<ne.length;++t){let y=ne[t],ee=typeof y==`object`&&y.value!==void 0?y.value:v[y];if(o&&ee===null)continue;let x=d&&s?y.replace(/\./g,`%2E`):y,ie=sL(v)?typeof n==`function`?n(re,x):re:re+(d?`.`+x:`[`+x+`]`);_.set(e,b);let ae=new WeakMap;ae.set(GL,_),VL(te,KL(ee,ie,n,r,i,a,o,s,n===`comma`&&h&&sL(v)?null:c,l,u,d,f,p,m,h,g,ae))}return te}function qL(e=UL){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||UL.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=jL;if(e.format!==void 0){if(!PL(NL,e.format))throw TypeError(`Unknown format option provided.`);n=e.format}let r=NL[n],i=UL.filter;(typeof e.filter==`function`||sL(e.filter))&&(i=e.filter);let a;if(a=e.arrayFormat&&e.arrayFormat in BL?e.arrayFormat:`indices`in e?e.indices?`indices`:`repeat`:UL.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:UL.allowDots:!!e.allowDots;return{addQueryPrefix:typeof e.addQueryPrefix==`boolean`?e.addQueryPrefix:UL.addQueryPrefix,allowDots:o,allowEmptyArrays:typeof e.allowEmptyArrays==`boolean`?!!e.allowEmptyArrays:UL.allowEmptyArrays,arrayFormat:a,charset:t,charsetSentinel:typeof e.charsetSentinel==`boolean`?e.charsetSentinel:UL.charsetSentinel,commaRoundTrip:!!e.commaRoundTrip,delimiter:e.delimiter===void 0?UL.delimiter:e.delimiter,encode:typeof e.encode==`boolean`?e.encode:UL.encode,encodeDotInKeys:typeof e.encodeDotInKeys==`boolean`?e.encodeDotInKeys:UL.encodeDotInKeys,encoder:typeof e.encoder==`function`?e.encoder:UL.encoder,encodeValuesOnly:typeof e.encodeValuesOnly==`boolean`?e.encodeValuesOnly:UL.encodeValuesOnly,filter:i,format:n,formatter:r,serializeDate:typeof e.serializeDate==`function`?e.serializeDate:UL.serializeDate,skipNulls:typeof e.skipNulls==`boolean`?e.skipNulls:UL.skipNulls,sort:typeof e.sort==`function`?e.sort:null,strictNullHandling:typeof e.strictNullHandling==`boolean`?e.strictNullHandling:UL.strictNullHandling}}function JL(e,t={}){let n=e,r=qL(t),i,a;typeof r.filter==`function`?(a=r.filter,n=a(``,n)):sL(r.filter)&&(a=r.filter,i=a);let o=[];if(typeof n!=`object`||!n)return``;let s=BL[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||VL(o,KL(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 YL(e){return JL(e,{arrayFormat:`brackets`})}function XL(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 ZL;function QL(e){let t;return(ZL??=(t=new globalThis.TextEncoder,t.encode.bind(t)))(e)}var $L;function eR(e){let t;return($L??=(t=new globalThis.TextDecoder,t.decode.bind(t)))(e)}var tR,nR,rR=class{constructor(){tR.set(this,void 0),nR.set(this,void 0),H(this,tR,new Uint8Array,`f`),H(this,nR,null,`f`)}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e==`string`?QL(e):e;H(this,tR,XL([U(this,tR,`f`),t]),`f`);let n=[],r;for(;(r=iR(U(this,tR,`f`),U(this,nR,`f`)))!=null;){if(r.carriage&&U(this,nR,`f`)==null){H(this,nR,r.index,`f`);continue}if(U(this,nR,`f`)!=null&&(r.index!==U(this,nR,`f`)+1||r.carriage)){n.push(eR(U(this,tR,`f`).subarray(0,U(this,nR,`f`)-1))),H(this,tR,U(this,tR,`f`).subarray(U(this,nR,`f`)),`f`),H(this,nR,null,`f`);continue}let e=U(this,nR,`f`)===null?r.preceding:r.preceding-1,t=eR(U(this,tR,`f`).subarray(0,e));n.push(t),H(this,tR,U(this,tR,`f`).subarray(r.index),`f`),H(this,nR,null,`f`)}return n}flush(){return U(this,tR,`f`).length?this.decode(`
189
- `):[]}};tR=new WeakMap,nR=new WeakMap,rR.NEWLINE_CHARS=new Set([`
190
- `,`\r`]),rR.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function iR(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 aR(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 oR={off:0,error:200,warn:300,info:400,debug:500},sR=(e,t,n)=>{if(e){if(dL(oR,e))return e;fR(n).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(oR))}`)}};function cR(){}function lR(e,t,n){return!t||oR[e]>oR[n]?cR:t[e].bind(t)}var uR={error:cR,warn:cR,info:cR,debug:cR},dR=new WeakMap;function fR(e){let t=e.logger,n=e.logLevel??`off`;if(!t)return uR;let r=dR.get(t);if(r&&r[0]===n)return r[1];let i={error:lR(`error`,t,n),warn:lR(`warn`,t,n),info:lR(`info`,t,n),debug:lR(`debug`,t,n)};return dR.set(t,[n,i]),i}var pR=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),mR,hR=class e{constructor(e,t,n){this.iterator=e,mR.set(this,void 0),this.controller=t,H(this,mR,n,`f`)}static fromSSEResponse(t,n,r,i){let a=!1,o=r?fR(r):console;async function*s(){if(a)throw new W("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");a=!0;let e=!1;try{for await(let r of gR(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 HI(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 HI(void 0,e.error,e.message,void 0);yield{event:r.event,data:e}}}e=!0}catch(e){if(BI(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 rR,n=OL(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 W("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(BI(e))return;throw e}finally{e||n.abort()}}return new e(o,n,r)}[(mR=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,U(this,mR,`f`)),new e(()=>i(n),this.controller,U(this,mR,`f`))]}toReadableStream(){let e=this,t;return EL({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=QL(JSON.stringify(n)+`
191
- `);e.enqueue(i)}catch(t){e.error(t)}},async cancel(){await t.return?.()}})}};async function*gR(e,t){if(!e.body)throw t.abort(),globalThis.navigator!==void 0&&globalThis.navigator.product===`ReactNative`?new W(`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 W(`Attempted to iterate over a response with no body`);let n=new vR,r=new rR,i=OL(e.body);for await(let e of _R(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*_R(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`?QL(n):n,r=new Uint8Array(t.length+e.length);r.set(t),r.set(e,t.length),t=r;let i;for(;(i=aR(t))!==-1;)yield t.slice(0,i),t=t.slice(i)}t.length>0&&(yield t)}var vR=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(`
192
- `),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]=yR(e,`:`);return r.startsWith(` `)&&(r=r.substring(1)),t===`event`?this.event=r:t===`data`&&this.data.push(r),null}};function yR(e,t){let n=e.indexOf(t);return n===-1?[e,``,``]:[e.substring(0,n),t,e.substring(n+t.length)]}async function bR(e,t){let{response:n,requestLogID:r,retryOfRequestLogID:i,startTime:a}=t,o=await(async()=>{if(t.options.stream)return fR(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):hR.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:xR(await n.json(),n):await n.text()})();return fR(e).debug(`[${r}] response parsed`,pR({retryOfRequestLogID:i,url:n.url,status:n.status,body:o,durationMs:Date.now()-a})),o}function xR(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 SR,CR=class e extends Promise{constructor(e,t,n=bR){super(e=>{e(null)}),this.responsePromise=t,this.parseResponse=n,SR.set(this,void 0),H(this,SR,e,`f`)}_thenUnwrap(t){return new e(U(this,SR,`f`),this.responsePromise,async(e,n)=>xR(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(U(this,SR,`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)}};SR=new WeakMap;var wR,TR=class{constructor(e,t,n,r){wR.set(this,void 0),H(this,wR,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 W("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await U(this,wR,`f`).requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(wR=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}},ER=class extends CR{constructor(e,t,n){super(e,t,async(e,t)=>new n(e,t.response,await bR(e,t),t.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}},DR=class extends TR{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}},OR=class extends TR{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:{...lL(this.options.query),after:t}}:null}},kR=class extends TR{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:{...lL(this.options.query),after:e}}:null}},AR={jwt:`urn:ietf:params:oauth:token-type:jwt`,id:`urn:ietf:params:oauth:token-type:id_token`},jR=`urn:ietf:params:oauth:grant-type:token-exchange`,MR=class{constructor(e,t){this.cachedToken=null,this.refreshPromise=null,this.tokenExchangeUrl=`https://auth.openai.com/oauth/token`,this.config=e,this.fetch=t??TL()}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:jR,client_id:this.config.clientId,subject_token:e,subject_token_type:AR[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 rL(t.status,n,t.headers):HI.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}},NR=()=>{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 PR(e,t,n){return NR(),new File(e,t??`unknown_file`,n)}function FR(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 IR=e=>typeof e==`object`&&!!e&&typeof e[Symbol.asyncIterator]==`function`,LR=async(e,t)=>WR(e.body)?{...e,body:await VR(e.body,t)}:e,RR=async(e,t)=>({...e,body:await VR(e.body,t)}),zR=new WeakMap;function BR(e){let t=typeof e==`function`?e:e.fetch,n=zR.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 zR.set(t,r),r}var VR=async(e,t)=>{if(!await BR(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])=>GR(n,e,t))),n},HR=e=>e instanceof Blob&&`name`in e,UR=e=>typeof e==`object`&&!!e&&(e instanceof Response||IR(e)||HR(e)),WR=e=>{if(UR(e))return!0;if(Array.isArray(e))return e.some(WR);if(e&&typeof e==`object`){for(let t in e)if(WR(e[t]))return!0}return!1},GR=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,PR([await n.blob()],FR(n)));else if(IR(n))e.append(t,PR([await new Response(DL(n)).blob()],FR(n)));else if(HR(n))e.append(t,n,FR(n));else if(Array.isArray(n))await Promise.all(n.map(n=>GR(e,t+`[]`,n)));else if(typeof n==`object`)await Promise.all(Object.entries(n).map(([n,r])=>GR(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`)}},KR=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`,qR=e=>typeof e==`object`&&!!e&&typeof e.name==`string`&&typeof e.lastModified==`number`&&KR(e),JR=e=>typeof e==`object`&&!!e&&typeof e.url==`string`&&typeof e.blob==`function`;async function YR(e,t,n){if(NR(),e=await e,qR(e))return e instanceof File?e:PR([await e.arrayBuffer()],e.name);if(JR(e)){let r=await e.blob();return t||=new URL(e.url).pathname.split(/[\\/]/).pop(),PR(await XR(r),t,n)}let r=await XR(e);if(t||=FR(e),!n?.type){let e=r.find(e=>typeof e==`object`&&`type`in e&&e.type);typeof e==`string`&&(n={...n,type:e})}return PR(r,t,n)}async function XR(e){let t=[];if(typeof e==`string`||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(KR(e))t.push(e instanceof Blob?e:await e.arrayBuffer());else if(IR(e))for await(let n of e)t.push(...await XR(n));else{let t=e?.constructor?.name;throw Error(`Unexpected data type: ${typeof e}${t?`; constructor: ${t}`:``}${ZR(e)}`)}return t}function ZR(e){return typeof e!=`object`||!e?``:`; props: [${Object.getOwnPropertyNames(e).map(e=>`"${e}"`).join(`, `)}]`}var G=class{constructor(e){this._client=e}};function QR(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var $R=Object.freeze(Object.create(null)),K=((e=QR)=>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??$R)??$R)?.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 W(`Path parameters result in path with invalid segments:\n${i.map(e=>e.error).join(`
193
- `)}\n${a}\n${t}`)}return a})(QR),ez=class extends G{list(e,t={},n){return this._client.getAPIList(K`/chat/completions/${e}/messages`,OR,{query:t,...n})}};function tz(e){return e!==void 0&&`function`in e&&e.function!==void 0}function nz(e,t){let n={...e};return Object.defineProperties(n,{$brand:{value:`auto-parseable-response-format`,enumerable:!1},$parseRaw:{value:t,enumerable:!1}}),n}function rz(e){return e?.$brand===`auto-parseable-response-format`}function iz(e){return e?.$brand===`auto-parseable-tool`}function az(e,t){return!t||!uz(t)?{...e,choices:e.choices.map(e=>(dz(e.message.tool_calls),{...e,message:{...e.message,parsed:null,...e.message.tool_calls?{tool_calls:e.message.tool_calls}:void 0}}))}:oz(e,t)}function oz(e,t){let n=e.choices.map(e=>{if(e.finish_reason===`length`)throw new eL;if(e.finish_reason===`content_filter`)throw new tL;return dz(e.message.tool_calls),{...e,message:{...e.message,...e.message.tool_calls?{tool_calls:e.message.tool_calls?.map(e=>cz(t,e))??void 0}:void 0,parsed:e.message.content&&!e.message.refusal?sz(t,e.message.content):null}}});return{...e,choices:n}}function sz(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 cz(e,t){let n=e.tools?.find(e=>tz(e)&&e.function?.name===t.function.name);return{...t,function:{...t.function,parsed_arguments:iz(n)?n.$parseRaw(t.function.arguments):n?.function.strict?JSON.parse(t.function.arguments):null}}}function lz(e,t){if(!e||!(`tools`in e)||!e.tools)return!1;let n=e.tools?.find(e=>tz(e)&&e.function?.name===t.function.name);return tz(n)&&(iz(n)||n?.function.strict||!1)}function uz(e){return rz(e.response_format)?!0:e.tools?.some(e=>iz(e)||e.type===`function`&&e.function.strict===!0)??!1}function dz(e){for(let t of e||[])if(t.type!==`function`)throw new W(`Currently only \`function\` tool calls are supported; Received \`${t.type}\``)}function fz(e){for(let t of e??[]){if(t.type!==`function`)throw new W(`Currently only \`function\` tool types support auto-parsing; Received \`${t.type}\``);if(t.function.strict!==!0)throw new W(`The \`${t.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var pz=e=>e?.role===`assistant`,mz=e=>e?.role===`tool`,hz,gz,_z,vz,yz,bz,xz,Sz,Cz,wz,Tz,Ez,Dz,Oz=class{constructor(){hz.add(this),this.controller=new AbortController,gz.set(this,void 0),_z.set(this,()=>{}),vz.set(this,()=>{}),yz.set(this,void 0),bz.set(this,()=>{}),xz.set(this,()=>{}),Sz.set(this,{}),Cz.set(this,!1),wz.set(this,!1),Tz.set(this,!1),Ez.set(this,!1),H(this,gz,new Promise((e,t)=>{H(this,_z,e,`f`),H(this,vz,t,`f`)}),`f`),H(this,yz,new Promise((e,t)=>{H(this,bz,e,`f`),H(this,xz,t,`f`)}),`f`),U(this,gz,`f`).catch(()=>{}),U(this,yz,`f`).catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit(`end`)},U(this,hz,`m`,Dz).bind(this))},0)}_connected(){this.ended||(U(this,_z,`f`).call(this),this._emit(`connect`))}get ended(){return U(this,Cz,`f`)}get errored(){return U(this,wz,`f`)}get aborted(){return U(this,Tz,`f`)}abort(){this.controller.abort()}on(e,t){return(U(this,Sz,`f`)[e]||(U(this,Sz,`f`)[e]=[])).push({listener:t}),this}off(e,t){let n=U(this,Sz,`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(U(this,Sz,`f`)[e]||(U(this,Sz,`f`)[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,n)=>{H(this,Ez,!0,`f`),e!==`error`&&this.once(`error`,n),this.once(e,t)})}async done(){H(this,Ez,!0,`f`),await U(this,yz,`f`)}_emit(e,...t){if(U(this,Cz,`f`))return;e===`end`&&(H(this,Cz,!0,`f`),U(this,bz,`f`).call(this));let n=U(this,Sz,`f`)[e];if(n&&(U(this,Sz,`f`)[e]=n.filter(e=>!e.once),n.forEach(({listener:e})=>e(...t))),e===`abort`){let e=t[0];!U(this,Ez,`f`)&&!n?.length&&Promise.reject(e),U(this,vz,`f`).call(this,e),U(this,xz,`f`).call(this,e),this._emit(`end`);return}if(e===`error`){let e=t[0];!U(this,Ez,`f`)&&!n?.length&&Promise.reject(e),U(this,vz,`f`).call(this,e),U(this,xz,`f`).call(this,e),this._emit(`end`)}}_emitFinal(){}};gz=new WeakMap,_z=new WeakMap,vz=new WeakMap,yz=new WeakMap,bz=new WeakMap,xz=new WeakMap,Sz=new WeakMap,Cz=new WeakMap,wz=new WeakMap,Tz=new WeakMap,Ez=new WeakMap,hz=new WeakSet,Dz=function(e){if(H(this,wz,!0,`f`),e instanceof Error&&e.name===`AbortError`&&(e=new UI),e instanceof UI)return H(this,Tz,!0,`f`),this._emit(`abort`,e);if(e instanceof W)return this._emit(`error`,e);if(e instanceof Error){let t=new W(e.message);return t.cause=e,this._emit(`error`,t)}return this._emit(`error`,new W(String(e)))};function kz(e){return typeof e.parse==`function`}var Az,jz,Mz,Nz,Pz,Fz,Iz,Lz,Rz=10,zz=class extends Oz{constructor(){super(...arguments),Az.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),mz(e)&&e.content)this._emit(`functionToolCallResult`,e.content);else if(pz(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 W(`stream ended without producing a ChatCompletion`);return e}async finalContent(){return await this.done(),U(this,Az,`m`,jz).call(this)}async finalMessage(){return await this.done(),U(this,Az,`m`,Mz).call(this)}async finalFunctionToolCall(){return await this.done(),U(this,Az,`m`,Nz).call(this)}async finalFunctionToolCallResult(){return await this.done(),U(this,Az,`m`,Pz).call(this)}async totalUsage(){return await this.done(),U(this,Az,`m`,Fz).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit(`finalChatCompletion`,e);let t=U(this,Az,`m`,Mz).call(this);t&&this._emit(`finalMessage`,t);let n=U(this,Az,`m`,jz).call(this);n&&this._emit(`finalContent`,n);let r=U(this,Az,`m`,Nz).call(this);r&&this._emit(`finalFunctionToolCall`,r);let i=U(this,Az,`m`,Pz).call(this);i!=null&&this._emit(`finalFunctionToolCallResult`,i),this._chatCompletions.some(e=>e.usage)&&this._emit(`totalUsage`,U(this,Az,`m`,Fz).call(this))}async _createChatCompletion(e,t,n){let r=n?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener(`abort`,()=>this.controller.abort())),U(this,Az,`m`,Iz).call(this,t);let i=await e.chat.completions.create({...t,stream:!1},{...n,signal:this.controller.signal});return this._connected(),this._addChatCompletion(oz(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=Rz}=n||{},l=t.tools.map(e=>{if(iz(e)){if(!e.$callback)throw new W("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 W(`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=kz(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=U(this,Az,`m`,Lz).call(this,c);if(this._addMessage({role:r,tool_call_id:t,content:l}),s)return}}}};Az=new WeakSet,jz=function(){return U(this,Az,`m`,Mz).call(this).content??null},Mz=function(){let e=this.messages.length;for(;e-- >0;){let t=this.messages[e];if(pz(t))return{...t,content:t.content??null,refusal:t.refusal??null}}throw new W(`stream ended without producing a ChatCompletionMessage with role=assistant`)},Nz=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(pz(t)&&t?.tool_calls?.length)return t.tool_calls.filter(e=>e.type===`function`).at(-1)?.function}},Pz=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(mz(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}},Fz=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},Iz=function(e){if(e.n!=null&&e.n>1)throw new W(`ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.`)},Lz=function(e){return typeof e==`string`?e:e===void 0?`undefined`:JSON.stringify(e)};var Bz=class e extends zz{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),pz(e)&&e.content&&this._emit(`content`,e.content)}},Vz=1,Hz=2,Uz=4,Wz=8,Gz=16,Kz=32,qz=64,Jz=128,Yz=256,Xz=Jz|Yz,Zz=496,Qz=Hz|497,$z=Uz|Wz,eB={STR:Vz,NUM:Hz,ARR:Uz,OBJ:Wz,NULL:Gz,BOOL:Kz,NAN:qz,INFINITY:Jz,MINUS_INFINITY:Yz,INF:Xz,SPECIAL:Zz,ATOM:Qz,COLLECTION:$z,ALL:Qz|$z},tB=class extends Error{},nB=class extends Error{};function rB(e,t=eB.ALL){if(typeof e!=`string`)throw TypeError(`expecting str, got ${typeof e}`);if(!e.trim())throw Error(`${e} is empty`);return iB(e.trim(),t)}var iB=(e,t)=>{let n=e.length,r=0,i=e=>{throw new tB(`${e} at position ${r}`)},a=e=>{throw new nB(`${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`||eB.NULL&t&&n-r<4&&`null`.startsWith(e.substring(r))?(r+=4,null):e.substring(r,r+4)===`true`||eB.BOOL&t&&n-r<4&&`true`.startsWith(e.substring(r))?(r+=4,!0):e.substring(r,r+5)===`false`||eB.BOOL&t&&n-r<5&&`false`.startsWith(e.substring(r))?(r+=5,!1):e.substring(r,r+8)===`Infinity`||eB.INFINITY&t&&n-r<8&&`Infinity`.startsWith(e.substring(r))?(r+=8,1/0):e.substring(r,r+9)===`-Infinity`||eB.MINUS_INFINITY&t&&1<n-r&&n-r<9&&`-Infinity`.startsWith(e.substring(r))?(r+=9,-1/0):e.substring(r,r+3)===`NaN`||eB.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(eB.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&&eB.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(eB.OBJ&t)return a;throw e}d(),e[r]===`,`&&r++}}catch{if(eB.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(eB.ARR&t)return n;i(`Expected ']' at end of array`)}return r++,n},u=()=>{if(r===0){e===`-`&&eB.NUM&t&&i(`Not sure what '-' is`);try{return JSON.parse(e)}catch(n){if(eB.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&&!(eB.NUM&t)&&i(`Unterminated number literal`);try{return JSON.parse(e.substring(o,r))}catch{e.substring(o,r)===`-`&&eB.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&&`
194
- \r `.includes(e[r]);)r++};return o()},aB=e=>rB(e,eB.ALL^eB.NUM),oB,sB,cB,lB,uB,dB,fB,pB,mB,hB,gB,_B,vB=class e extends zz{constructor(e){super(),oB.add(this),sB.set(this,void 0),cB.set(this,void 0),lB.set(this,void 0),H(this,sB,e,`f`),H(this,cB,[],`f`)}get currentChatCompletionSnapshot(){return U(this,lB,`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())),U(this,oB,`m`,uB).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)U(this,oB,`m`,fB).call(this,e);if(i.controller.signal?.aborted)throw new UI;return this._addChatCompletion(U(this,oB,`m`,hB).call(this))}async _fromReadableStream(e,t){let n=t?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener(`abort`,()=>this.controller.abort())),U(this,oB,`m`,uB).call(this),this._connected();let r=hR.fromReadableStream(e,this.controller),i;for await(let e of r)i&&i!==e.id&&this._addChatCompletion(U(this,oB,`m`,hB).call(this)),U(this,oB,`m`,fB).call(this,e),i=e.id;if(r.controller.signal?.aborted)throw new UI;return this._addChatCompletion(U(this,oB,`m`,hB).call(this))}[(sB=new WeakMap,cB=new WeakMap,lB=new WeakMap,oB=new WeakSet,uB=function(){this.ended||H(this,lB,void 0,`f`)},dB=function(e){let t=U(this,cB,`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},U(this,cB,`f`)[e.index]=t,t)},fB=function(e){if(this.ended)return;let t=U(this,oB,`m`,_B).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=U(this,oB,`m`,dB).call(this,e);e.finish_reason&&(U(this,oB,`m`,mB).call(this,e),r.current_tool_call_index!=null&&U(this,oB,`m`,pB).call(this,e,r.current_tool_call_index));for(let t of n.delta.tool_calls??[])r.current_tool_call_index!==t.index&&(U(this,oB,`m`,mB).call(this,e),r.current_tool_call_index!=null&&U(this,oB,`m`,pB).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)}}},pB=function(e,t){if(U(this,oB,`m`,dB).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=U(this,sB,`f`)?.tools?.find(e=>tz(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:iz(e)?e.$parseRaw(n.function.arguments):e?.function.strict?JSON.parse(n.function.arguments):null})}else n.type},mB=function(e){let t=U(this,oB,`m`,dB).call(this,e);if(e.message.content&&!t.content_done){t.content_done=!0;let n=U(this,oB,`m`,gB).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}))},hB=function(){if(this.ended)throw new W(`stream has ended, this shouldn't happen`);let e=U(this,lB,`f`);if(!e)throw new W(`request ended without sending any chunks`);return H(this,lB,void 0,`f`),H(this,cB,[],`f`),yB(e,U(this,sB,`f`))},gB=function(){let e=U(this,sB,`f`)?.response_format;return rz(e)?e:null},_B=function(e){var t,n,r,i;let a=U(this,lB,`f`),{choices:o,...s}=e;a?Object.assign(a,s):a=H(this,lB,{...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,U(this,sB,`f`)&&uz(U(this,sB,`f`)))){if(s===`length`)throw new eL;if(s===`content_filter`)throw new tL}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&&U(this,oB,`m`,gB).call(this)&&(e.message.parsed=aB(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,lz(U(this,sB,`f`),s)&&(s.function.parsed_arguments=aB(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 hR(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};function yB(e,t){let{id:n,choices:r,created:i,model:a,system_fingerprint:o,...s}=e;return az({...s,id:n,choices:r.map(({message:t,finish_reason:n,index:r,logprobs:i,...a})=>{if(!n)throw new W(`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 W(`missing role for choice ${r}`);if(s){let{arguments:e,name:c}=s;if(e==null)throw new W(`missing function_call.arguments for choice ${r}`);if(!c)throw new W(`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 W(`missing choices[${r}].tool_calls[${n}].id\n${bB(e)}`);if(a==null)throw new W(`missing choices[${r}].tool_calls[${n}].type\n${bB(e)}`);if(l==null)throw new W(`missing choices[${r}].tool_calls[${n}].function.name\n${bB(e)}`);if(c==null)throw new W(`missing choices[${r}].tool_calls[${n}].function.arguments\n${bB(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 bB(e){return JSON.stringify(e)}var xB=class e extends vB{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}},SB=class extends G{constructor(){super(...arguments),this.messages=new ez(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(K`/chat/completions/${e}`,t)}update(e,t,n){return this._client.post(K`/chat/completions/${e}`,{body:t,...n})}list(e={},t){return this._client.getAPIList(`/chat/completions`,OR,{query:e,...t})}delete(e,t){return this._client.delete(K`/chat/completions/${e}`,t)}parse(e,t){return fz(e.tools),this._client.chat.completions.create(e,{...t,headers:{...t?.headers,"X-Stainless-Helper-Method":`chat.completions.parse`}})._thenUnwrap(t=>oz(t,e))}runTools(e,t){return e.stream?xB.runTools(this._client,e,t):Bz.runTools(this._client,e,t)}stream(e,t){return vB.createChatCompletion(this._client,e,t)}};SB.Messages=ez;var CB=class extends G{constructor(){super(...arguments),this.completions=new SB(this._client)}};CB.Completions=SB;var wB=Symbol(`brand.privateNullableHeaders`);function*TB(e){if(!e)return;if(wB 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():cL(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=cL(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 TB(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{[wB]:!0,values:t,nulls:n}},EB=class extends G{create(e,t){return this._client.post(`/audio/speech`,{body:e,...t,headers:q([{Accept:`application/octet-stream`},t?.headers]),__binaryResponse:!0})}},DB=class extends G{create(e,t){return this._client.post(`/audio/transcriptions`,RR({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model}},this._client))}},OB=class extends G{create(e,t){return this._client.post(`/audio/translations`,RR({body:e,...t,__metadata:{model:e.model}},this._client))}},kB=class extends G{constructor(){super(...arguments),this.transcriptions=new DB(this._client),this.translations=new OB(this._client),this.speech=new EB(this._client)}};kB.Transcriptions=DB,kB.Translations=OB,kB.Speech=EB;var AB=class extends G{create(e,t){return this._client.post(`/batches`,{body:e,...t})}retrieve(e,t){return this._client.get(K`/batches/${e}`,t)}list(e={},t){return this._client.getAPIList(`/batches`,OR,{query:e,...t})}cancel(e,t){return this._client.post(K`/batches/${e}/cancel`,t)}},jB=class extends G{create(e,t){return this._client.post(`/assistants`,{body:e,...t,headers:q([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}retrieve(e,t){return this._client.get(K`/assistants/${e}`,{...t,headers:q([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}update(e,t,n){return this._client.post(K`/assistants/${e}`,{body:t,...n,headers:q([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}list(e={},t){return this._client.getAPIList(`/assistants`,OR,{query:e,...t,headers:q([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}delete(e,t){return this._client.delete(K`/assistants/${e}`,{...t,headers:q([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}},MB=class extends G{create(e,t){return this._client.post(`/realtime/sessions`,{body:e,...t,headers:q([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}},NB=class extends G{create(e,t){return this._client.post(`/realtime/transcription_sessions`,{body:e,...t,headers:q([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}},PB=class extends G{constructor(){super(...arguments),this.sessions=new MB(this._client),this.transcriptionSessions=new NB(this._client)}};PB.Sessions=MB,PB.TranscriptionSessions=NB;var FB=class extends G{create(e,t){return this._client.post(`/chatkit/sessions`,{body:e,...t,headers:q([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers])})}cancel(e,t){return this._client.post(K`/chatkit/sessions/${e}/cancel`,{...t,headers:q([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers])})}},IB=class extends G{retrieve(e,t){return this._client.get(K`/chatkit/threads/${e}`,{...t,headers:q([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers])})}list(e={},t){return this._client.getAPIList(`/chatkit/threads`,kR,{query:e,...t,headers:q([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers])})}delete(e,t){return this._client.delete(K`/chatkit/threads/${e}`,{...t,headers:q([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers])})}listItems(e,t={},n){return this._client.getAPIList(K`/chatkit/threads/${e}/items`,kR,{query:t,...n,headers:q([{"OpenAI-Beta":`chatkit_beta=v1`},n?.headers])})}},LB=class extends G{constructor(){super(...arguments),this.sessions=new FB(this._client),this.threads=new IB(this._client)}};LB.Sessions=FB,LB.Threads=IB;var RB=class extends G{create(e,t,n){return this._client.post(K`/threads/${e}/messages`,{body:t,...n,headers:q([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}retrieve(e,t,n){let{thread_id:r}=t;return this._client.get(K`/threads/${r}/messages/${e}`,{...n,headers:q([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}update(e,t,n){let{thread_id:r,...i}=t;return this._client.post(K`/threads/${r}/messages/${e}`,{body:i,...n,headers:q([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}list(e,t={},n){return this._client.getAPIList(K`/threads/${e}/messages`,OR,{query:t,...n,headers:q([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}delete(e,t,n){let{thread_id:r}=t;return this._client.delete(K`/threads/${r}/messages/${e}`,{...n,headers:q([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}},zB=class extends G{retrieve(e,t,n){let{thread_id:r,run_id:i,...a}=t;return this._client.get(K`/threads/${r}/runs/${i}/steps/${e}`,{query:a,...n,headers:q([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}list(e,t,n){let{thread_id:r,...i}=t;return this._client.getAPIList(K`/threads/${r}/runs/${e}/steps`,OR,{query:i,...n,headers:q([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}},BB=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))}},VB=e=>{if(globalThis.process!==void 0)return{}?.[e]?.trim()??void 0;if(globalThis.Deno!==void 0)return globalThis.Deno.env?.get?.(e)?.trim()},HB,UB,WB,GB,KB,qB,JB,YB,XB,ZB,QB,$B,eV,tV,nV,rV,iV,aV,oV,sV,cV,lV,uV,dV=class extends Oz{constructor(){super(...arguments),HB.add(this),WB.set(this,[]),GB.set(this,{}),KB.set(this,{}),qB.set(this,void 0),JB.set(this,void 0),YB.set(this,void 0),XB.set(this,void 0),ZB.set(this,void 0),QB.set(this,void 0),$B.set(this,void 0),eV.set(this,void 0),tV.set(this,void 0)}[(WB=new WeakMap,GB=new WeakMap,KB=new WeakMap,qB=new WeakMap,JB=new WeakMap,YB=new WeakMap,XB=new WeakMap,ZB=new WeakMap,QB=new WeakMap,$B=new WeakMap,eV=new WeakMap,tV=new WeakMap,HB=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 UB;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=hR.fromReadableStream(e,this.controller);for await(let e of r)U(this,HB,`m`,nV).call(this,e);if(r.controller.signal?.aborted)throw new UI;return this._addRun(U(this,HB,`m`,rV).call(this))}toReadableStream(){return new hR(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,n,r){let i=new UB;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)U(this,HB,`m`,nV).call(this,e);if(o.controller.signal?.aborted)throw new UI;return this._addRun(U(this,HB,`m`,rV).call(this))}static createThreadAssistantStream(e,t,n){let r=new UB;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 UB;return i._run(()=>i._runAssistantStream(e,t,n,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`stream`}})),i}currentEvent(){return U(this,$B,`f`)}currentRun(){return U(this,eV,`f`)}currentMessageSnapshot(){return U(this,qB,`f`)}currentRunStepSnapshot(){return U(this,tV,`f`)}async finalRunSteps(){return await this.done(),Object.values(U(this,GB,`f`))}async finalMessages(){return await this.done(),Object.values(U(this,KB,`f`))}async finalRun(){if(await this.done(),!U(this,JB,`f`))throw Error(`Final run was not received.`);return U(this,JB,`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)U(this,HB,`m`,nV).call(this,e);if(a.controller.signal?.aborted)throw new UI;return this._addRun(U(this,HB,`m`,rV).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)U(this,HB,`m`,nV).call(this,e);if(o.controller.signal?.aborted)throw new UI;return this._addRun(U(this,HB,`m`,rV).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(fL(t)&&fL(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(!fL(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)}};UB=dV,nV=function(e){if(!this.ended)switch(H(this,$B,e,`f`),U(this,HB,`m`,oV).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`:U(this,HB,`m`,uV).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`:U(this,HB,`m`,aV).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`:U(this,HB,`m`,iV).call(this,e);break;case`error`:throw Error(`Encountered an error event in event processing - errors should be processed earlier`);default:}},rV=function(){if(this.ended)throw new W(`stream has ended, this shouldn't happen`);if(!U(this,JB,`f`))throw Error(`Final run has not been received`);return U(this,JB,`f`)},iV=function(e){let[t,n]=U(this,HB,`m`,cV).call(this,e,U(this,qB,`f`));H(this,qB,t,`f`),U(this,KB,`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!=U(this,YB,`f`)){if(U(this,XB,`f`))switch(U(this,XB,`f`).type){case`text`:this._emit(`textDone`,U(this,XB,`f`).text,U(this,qB,`f`));break;case`image_file`:this._emit(`imageFileDone`,U(this,XB,`f`).image_file,U(this,qB,`f`));break}H(this,YB,n.index,`f`)}H(this,XB,t.content[n.index],`f`)}break;case`thread.message.completed`:case`thread.message.incomplete`:if(U(this,YB,`f`)!==void 0){let t=e.data.content[U(this,YB,`f`)];if(t)switch(t.type){case`image_file`:this._emit(`imageFileDone`,t.image_file,U(this,qB,`f`));break;case`text`:this._emit(`textDone`,t.text,U(this,qB,`f`));break}}U(this,qB,`f`)&&this._emit(`messageDone`,e.data),H(this,qB,void 0,`f`)}},aV=function(e){let t=U(this,HB,`m`,sV).call(this,e);switch(H(this,tV,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==U(this,ZB,`f`)?this._emit(`toolCallDelta`,e,t.step_details.tool_calls[e.index]):(U(this,QB,`f`)&&this._emit(`toolCallDone`,U(this,QB,`f`)),H(this,ZB,e.index,`f`),H(this,QB,t.step_details.tool_calls[e.index],`f`),U(this,QB,`f`)&&this._emit(`toolCallCreated`,U(this,QB,`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`:H(this,tV,void 0,`f`),e.data.step_details.type==`tool_calls`&&U(this,QB,`f`)&&(this._emit(`toolCallDone`,U(this,QB,`f`)),H(this,QB,void 0,`f`)),this._emit(`runStepDone`,e.data,t);break;case`thread.run.step.in_progress`:break}},oV=function(e){U(this,WB,`f`).push(e),this._emit(`event`,e)},sV=function(e){switch(e.event){case`thread.run.step.created`:return U(this,GB,`f`)[e.data.id]=e.data,e.data;case`thread.run.step.delta`:let t=U(this,GB,`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=UB.accumulateDelta(t,n.delta);U(this,GB,`f`)[e.data.id]=r}return U(this,GB,`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`:U(this,GB,`f`)[e.data.id]=e.data;break}if(U(this,GB,`f`)[e.data.id])return U(this,GB,`f`)[e.data.id];throw Error(`No snapshot available`)},cV=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]=U(this,HB,`m`,lV).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`)},lV=function(e,t){return UB.accumulateDelta(t,e)},uV=function(e){switch(H(this,eV,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`:H(this,JB,e.data,`f`),U(this,QB,`f`)&&(this._emit(`toolCallDone`,U(this,QB,`f`)),H(this,QB,void 0,`f`));break;case`thread.run.cancelling`:break}};var fV=class extends G{constructor(){super(...arguments),this.steps=new zB(this._client)}create(e,t,n){let{include:r,...i}=t;return this._client.post(K`/threads/${e}/runs`,{query:{include:r},body:i,...n,headers:q([{"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(K`/threads/${r}/runs/${e}`,{...n,headers:q([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}update(e,t,n){let{thread_id:r,...i}=t;return this._client.post(K`/threads/${r}/runs/${e}`,{body:i,...n,headers:q([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}list(e,t={},n){return this._client.getAPIList(K`/threads/${e}/runs`,OR,{query:t,...n,headers:q([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}cancel(e,t,n){let{thread_id:r}=t;return this._client.post(K`/threads/${r}/runs/${e}/cancel`,{...n,headers:q([{"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 dV.createAssistantStream(e,this._client.beta.threads.runs,t,n)}async poll(e,t,n){let r=q([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 hL(e);break;case`requires_action`:case`incomplete`:case`cancelled`:case`completed`:case`failed`:case`expired`:return i}}}stream(e,t,n){return dV.createAssistantStream(e,this._client.beta.threads.runs,t,n)}submitToolOutputs(e,t,n){let{thread_id:r,...i}=t;return this._client.post(K`/threads/${r}/runs/${e}/submit_tool_outputs`,{body:i,...n,headers:q([{"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 dV.createToolAssistantStream(e,this._client.beta.threads.runs,t,n)}};fV.Steps=zB;var pV=class extends G{constructor(){super(...arguments),this.runs=new fV(this._client),this.messages=new RB(this._client)}create(e={},t){return this._client.post(`/threads`,{body:e,...t,headers:q([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}retrieve(e,t){return this._client.get(K`/threads/${e}`,{...t,headers:q([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}update(e,t,n){return this._client.post(K`/threads/${e}`,{body:t,...n,headers:q([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}delete(e,t){return this._client.delete(K`/threads/${e}`,{...t,headers:q([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}createAndRun(e,t){return this._client.post(`/threads/runs`,{body:e,...t,headers:q([{"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 dV.createThreadAssistantStream(e,this._client.beta.threads,t)}};pV.Runs=fV,pV.Messages=RB;var mV=class extends G{constructor(){super(...arguments),this.realtime=new PB(this._client),this.chatkit=new LB(this._client),this.assistants=new jB(this._client),this.threads=new pV(this._client)}};mV.Realtime=PB,mV.ChatKit=LB,mV.Assistants=jB,mV.Threads=pV;var hV=class extends G{create(e,t){return this._client.post(`/completions`,{body:e,...t,stream:e.stream??!1})}},gV=class extends G{retrieve(e,t,n){let{container_id:r}=t;return this._client.get(K`/containers/${r}/files/${e}/content`,{...n,headers:q([{Accept:`application/binary`},n?.headers]),__binaryResponse:!0})}},_V=class extends G{constructor(){super(...arguments),this.content=new gV(this._client)}create(e,t,n){return this._client.post(K`/containers/${e}/files`,LR({body:t,...n},this._client))}retrieve(e,t,n){let{container_id:r}=t;return this._client.get(K`/containers/${r}/files/${e}`,n)}list(e,t={},n){return this._client.getAPIList(K`/containers/${e}/files`,OR,{query:t,...n})}delete(e,t,n){let{container_id:r}=t;return this._client.delete(K`/containers/${r}/files/${e}`,{...n,headers:q([{Accept:`*/*`},n?.headers])})}};_V.Content=gV;var vV=class extends G{constructor(){super(...arguments),this.files=new _V(this._client)}create(e,t){return this._client.post(`/containers`,{body:e,...t})}retrieve(e,t){return this._client.get(K`/containers/${e}`,t)}list(e={},t){return this._client.getAPIList(`/containers`,OR,{query:e,...t})}delete(e,t){return this._client.delete(K`/containers/${e}`,{...t,headers:q([{Accept:`*/*`},t?.headers])})}};vV.Files=_V;var yV=class extends G{create(e,t,n){let{include:r,...i}=t;return this._client.post(K`/conversations/${e}/items`,{query:{include:r},body:i,...n})}retrieve(e,t,n){let{conversation_id:r,...i}=t;return this._client.get(K`/conversations/${r}/items/${e}`,{query:i,...n})}list(e,t={},n){return this._client.getAPIList(K`/conversations/${e}/items`,kR,{query:t,...n})}delete(e,t,n){let{conversation_id:r}=t;return this._client.delete(K`/conversations/${r}/items/${e}`,n)}},bV=class extends G{constructor(){super(...arguments),this.items=new yV(this._client)}create(e={},t){return this._client.post(`/conversations`,{body:e,...t})}retrieve(e,t){return this._client.get(K`/conversations/${e}`,t)}update(e,t,n){return this._client.post(K`/conversations/${e}`,{body:t,...n})}delete(e,t){return this._client.delete(K`/conversations/${e}`,t)}};bV.Items=yV;var xV=class extends G{create(e,t){let n=!!e.encoding_format,r=n?e.encoding_format:`base64`;n&&fR(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:(fR(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=BB(t)}),e)))}},SV=class extends G{retrieve(e,t,n){let{eval_id:r,run_id:i}=t;return this._client.get(K`/evals/${r}/runs/${i}/output_items/${e}`,n)}list(e,t,n){let{eval_id:r,...i}=t;return this._client.getAPIList(K`/evals/${r}/runs/${e}/output_items`,OR,{query:i,...n})}},CV=class extends G{constructor(){super(...arguments),this.outputItems=new SV(this._client)}create(e,t,n){return this._client.post(K`/evals/${e}/runs`,{body:t,...n})}retrieve(e,t,n){let{eval_id:r}=t;return this._client.get(K`/evals/${r}/runs/${e}`,n)}list(e,t={},n){return this._client.getAPIList(K`/evals/${e}/runs`,OR,{query:t,...n})}delete(e,t,n){let{eval_id:r}=t;return this._client.delete(K`/evals/${r}/runs/${e}`,n)}cancel(e,t,n){let{eval_id:r}=t;return this._client.post(K`/evals/${r}/runs/${e}`,n)}};CV.OutputItems=SV;var wV=class extends G{constructor(){super(...arguments),this.runs=new CV(this._client)}create(e,t){return this._client.post(`/evals`,{body:e,...t})}retrieve(e,t){return this._client.get(K`/evals/${e}`,t)}update(e,t,n){return this._client.post(K`/evals/${e}`,{body:t,...n})}list(e={},t){return this._client.getAPIList(`/evals`,OR,{query:e,...t})}delete(e,t){return this._client.delete(K`/evals/${e}`,t)}};wV.Runs=CV;var TV=class extends G{create(e,t){return this._client.post(`/files`,RR({body:e,...t},this._client))}retrieve(e,t){return this._client.get(K`/files/${e}`,t)}list(e={},t){return this._client.getAPIList(`/files`,OR,{query:e,...t})}delete(e,t){return this._client.delete(K`/files/${e}`,t)}content(e,t){return this._client.get(K`/files/${e}/content`,{...t,headers:q([{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 hL(t),a=await this.retrieve(e),Date.now()-i>n)throw new GI({message:`Giving up on waiting for file ${e} to finish processing after ${n} milliseconds.`});return a}},EV=class extends G{},DV=class extends G{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})}},OV=class extends G{constructor(){super(...arguments),this.graders=new DV(this._client)}};OV.Graders=DV;var kV=class extends G{create(e,t,n){return this._client.getAPIList(K`/fine_tuning/checkpoints/${e}/permissions`,DR,{body:t,method:`post`,...n})}retrieve(e,t={},n){return this._client.get(K`/fine_tuning/checkpoints/${e}/permissions`,{query:t,...n})}list(e,t={},n){return this._client.getAPIList(K`/fine_tuning/checkpoints/${e}/permissions`,kR,{query:t,...n})}delete(e,t,n){let{fine_tuned_model_checkpoint:r}=t;return this._client.delete(K`/fine_tuning/checkpoints/${r}/permissions/${e}`,n)}},AV=class extends G{constructor(){super(...arguments),this.permissions=new kV(this._client)}};AV.Permissions=kV;var jV=class extends G{list(e,t={},n){return this._client.getAPIList(K`/fine_tuning/jobs/${e}/checkpoints`,OR,{query:t,...n})}},MV=class extends G{constructor(){super(...arguments),this.checkpoints=new jV(this._client)}create(e,t){return this._client.post(`/fine_tuning/jobs`,{body:e,...t})}retrieve(e,t){return this._client.get(K`/fine_tuning/jobs/${e}`,t)}list(e={},t){return this._client.getAPIList(`/fine_tuning/jobs`,OR,{query:e,...t})}cancel(e,t){return this._client.post(K`/fine_tuning/jobs/${e}/cancel`,t)}listEvents(e,t={},n){return this._client.getAPIList(K`/fine_tuning/jobs/${e}/events`,OR,{query:t,...n})}pause(e,t){return this._client.post(K`/fine_tuning/jobs/${e}/pause`,t)}resume(e,t){return this._client.post(K`/fine_tuning/jobs/${e}/resume`,t)}};MV.Checkpoints=jV;var NV=class extends G{constructor(){super(...arguments),this.methods=new EV(this._client),this.jobs=new MV(this._client),this.checkpoints=new AV(this._client),this.alpha=new OV(this._client)}};NV.Methods=EV,NV.Jobs=MV,NV.Checkpoints=AV,NV.Alpha=OV;var PV=class extends G{},FV=class extends G{constructor(){super(...arguments),this.graderModels=new PV(this._client)}};FV.GraderModels=PV;var IV=class extends G{createVariation(e,t){return this._client.post(`/images/variations`,RR({body:e,...t},this._client))}edit(e,t){return this._client.post(`/images/edits`,RR({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})}},LV=class extends G{retrieve(e,t){return this._client.get(K`/models/${e}`,t)}list(e){return this._client.getAPIList(`/models`,DR,e)}delete(e,t){return this._client.delete(K`/models/${e}`,t)}},RV=class extends G{create(e,t){return this._client.post(`/moderations`,{body:e,...t})}},zV=class extends G{accept(e,t,n){return this._client.post(K`/realtime/calls/${e}/accept`,{body:t,...n,headers:q([{Accept:`*/*`},n?.headers])})}hangup(e,t){return this._client.post(K`/realtime/calls/${e}/hangup`,{...t,headers:q([{Accept:`*/*`},t?.headers])})}refer(e,t,n){return this._client.post(K`/realtime/calls/${e}/refer`,{body:t,...n,headers:q([{Accept:`*/*`},n?.headers])})}reject(e,t={},n){return this._client.post(K`/realtime/calls/${e}/reject`,{body:t,...n,headers:q([{Accept:`*/*`},n?.headers])})}},BV=class extends G{create(e,t){return this._client.post(`/realtime/client_secrets`,{body:e,...t})}},VV=class extends G{constructor(){super(...arguments),this.clientSecrets=new BV(this._client),this.calls=new zV(this._client)}};VV.ClientSecrets=BV,VV.Calls=zV;function HV(e,t){return!t||!GV(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)}:UV(e,t)}function UV(e,t){let n=e.output.map(e=>{if(e.type===`function_call`)return{...e,parsed_arguments:JV(t,e)};if(e.type===`message`){let n=e.content.map(e=>e.type===`output_text`?{...e,parsed:WV(t,e.text)}:e);return{...e,content:n}}return e}),r=Object.assign({},e,{output:n});return Object.getOwnPropertyDescriptor(e,`output_text`)||YV(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 WV(e,t){return e.text?.format?.type===`json_schema`?`$parseRaw`in e.text?.format?(e.text?.format).$parseRaw(t):JSON.parse(t):null}function GV(e){return!!rz(e.text?.format)}function KV(e){return e?.$brand===`auto-parseable-tool`}function qV(e,t){return e.find(e=>e.type===`function`&&e.name===t)}function JV(e,t){let n=qV(e.tools??[],t.name);return{...t,...t,parsed_arguments:KV(n)?n.$parseRaw(t.arguments):n?.strict?JSON.parse(t.arguments):null}}function YV(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 XV,ZV,QV,$V,eH,tH,nH,rH,iH=class e extends Oz{constructor(e){super(),XV.add(this),ZV.set(this,void 0),QV.set(this,void 0),$V.set(this,void 0),H(this,ZV,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())),U(this,XV,`m`,eH).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)U(this,XV,`m`,tH).call(this,e,a);if(i.controller.signal?.aborted)throw new UI;return U(this,XV,`m`,nH).call(this)}[(ZV=new WeakMap,QV=new WeakMap,$V=new WeakMap,XV=new WeakSet,eH=function(){this.ended||H(this,QV,void 0,`f`)},tH=function(e,t){if(this.ended)return;let n=(e,n)=>{(t==null||n.sequence_number>t)&&this._emit(e,n)},r=U(this,XV,`m`,rH).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 W(`missing output at index ${e.output_index}`);if(t.type===`message`){let r=t.content[e.content_index];if(!r)throw new W(`missing content at index ${e.content_index}`);if(r.type!==`output_text`)throw new W(`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 W(`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}},nH=function(){if(this.ended)throw new W(`stream has ended, this shouldn't happen`);let e=U(this,QV,`f`);if(!e)throw new W(`request ended without sending any events`);H(this,QV,void 0,`f`);let t=aH(e,U(this,ZV,`f`));return H(this,$V,t,`f`),t},rH=function(e){let t=U(this,QV,`f`);if(!t){if(e.type!==`response.created`)throw new W(`When snapshot hasn't been set yet, expected 'response.created' event, got ${e.type}`);return t=H(this,QV,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 W(`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 W(`missing output at index ${e.output_index}`);if(n.type===`message`){let t=n.content[e.content_index];if(!t)throw new W(`missing content at index ${e.content_index}`);if(t.type!==`output_text`)throw new W(`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 W(`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 W(`missing output at index ${e.output_index}`);if(n.type===`reasoning`){let t=n.content?.[e.content_index];if(!t)throw new W(`missing content at index ${e.content_index}`);if(t.type!==`reasoning_text`)throw new W(`expected content to be 'reasoning_text', got ${t.type}`);t.text+=e.delta}break}case`response.completed`:H(this,QV,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=U(this,$V,`f`);if(!e)throw new W(`stream ended without producing a ChatCompletion`);return e}};function aH(e,t){return HV(e,t)}var oH=class extends G{list(e,t={},n){return this._client.getAPIList(K`/responses/${e}/input_items`,OR,{query:t,...n})}},sH=class extends G{count(e={},t){return this._client.post(`/responses/input_tokens`,{body:e,...t})}},cH=class extends G{constructor(){super(...arguments),this.inputItems=new oH(this._client),this.inputTokens=new sH(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`&&YV(e),e))}retrieve(e,t={},n){return this._client.get(K`/responses/${e}`,{query:t,...n,stream:t?.stream??!1})._thenUnwrap(e=>(`object`in e&&e.object===`response`&&YV(e),e))}delete(e,t){return this._client.delete(K`/responses/${e}`,{...t,headers:q([{Accept:`*/*`},t?.headers])})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap(t=>UV(t,e))}stream(e,t){return iH.createResponse(this._client,e,t)}cancel(e,t){return this._client.post(K`/responses/${e}/cancel`,t)}compact(e,t){return this._client.post(`/responses/compact`,{body:e,...t})}};cH.InputItems=oH,cH.InputTokens=sH;var lH=class extends G{retrieve(e,t){return this._client.get(K`/skills/${e}/content`,{...t,headers:q([{Accept:`application/binary`},t?.headers]),__binaryResponse:!0})}},uH=class extends G{retrieve(e,t,n){let{skill_id:r}=t;return this._client.get(K`/skills/${r}/versions/${e}/content`,{...n,headers:q([{Accept:`application/binary`},n?.headers]),__binaryResponse:!0})}},dH=class extends G{constructor(){super(...arguments),this.content=new uH(this._client)}create(e,t={},n){return this._client.post(K`/skills/${e}/versions`,LR({body:t,...n},this._client))}retrieve(e,t,n){let{skill_id:r}=t;return this._client.get(K`/skills/${r}/versions/${e}`,n)}list(e,t={},n){return this._client.getAPIList(K`/skills/${e}/versions`,OR,{query:t,...n})}delete(e,t,n){let{skill_id:r}=t;return this._client.delete(K`/skills/${r}/versions/${e}`,n)}};dH.Content=uH;var fH=class extends G{constructor(){super(...arguments),this.content=new lH(this._client),this.versions=new dH(this._client)}create(e={},t){return this._client.post(`/skills`,LR({body:e,...t},this._client))}retrieve(e,t){return this._client.get(K`/skills/${e}`,t)}update(e,t,n){return this._client.post(K`/skills/${e}`,{body:t,...n})}list(e={},t){return this._client.getAPIList(`/skills`,OR,{query:e,...t})}delete(e,t){return this._client.delete(K`/skills/${e}`,t)}};fH.Content=lH,fH.Versions=dH;var pH=class extends G{create(e,t,n){return this._client.post(K`/uploads/${e}/parts`,RR({body:t,...n},this._client))}},mH=class extends G{constructor(){super(...arguments),this.parts=new pH(this._client)}create(e,t){return this._client.post(`/uploads`,{body:e,...t})}cancel(e,t){return this._client.post(K`/uploads/${e}/cancel`,t)}complete(e,t,n){return this._client.post(K`/uploads/${e}/complete`,{body:t,...n})}};mH.Parts=pH;var hH=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},gH=class extends G{create(e,t,n){return this._client.post(K`/vector_stores/${e}/file_batches`,{body:t,...n,headers:q([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}retrieve(e,t,n){let{vector_store_id:r}=t;return this._client.get(K`/vector_stores/${r}/file_batches/${e}`,{...n,headers:q([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}cancel(e,t,n){let{vector_store_id:r}=t;return this._client.post(K`/vector_stores/${r}/file_batches/${e}/cancel`,{...n,headers:q([{"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(K`/vector_stores/${r}/file_batches/${e}/files`,OR,{query:i,...n,headers:q([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}async poll(e,t,n){let r=q([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 hL(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 hH(Array(a).fill(s).map(l)),await this.createAndPoll(e,{file_ids:c})}},_H=class extends G{create(e,t,n){return this._client.post(K`/vector_stores/${e}/files`,{body:t,...n,headers:q([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}retrieve(e,t,n){let{vector_store_id:r}=t;return this._client.get(K`/vector_stores/${r}/files/${e}`,{...n,headers:q([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}update(e,t,n){let{vector_store_id:r,...i}=t;return this._client.post(K`/vector_stores/${r}/files/${e}`,{body:i,...n,headers:q([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}list(e,t={},n){return this._client.getAPIList(K`/vector_stores/${e}/files`,OR,{query:t,...n,headers:q([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}delete(e,t,n){let{vector_store_id:r}=t;return this._client.delete(K`/vector_stores/${r}/files/${e}`,{...n,headers:q([{"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=q([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 hL(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(K`/vector_stores/${r}/files/${e}/content`,DR,{...n,headers:q([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}},vH=class extends G{constructor(){super(...arguments),this.files=new _H(this._client),this.fileBatches=new gH(this._client)}create(e,t){return this._client.post(`/vector_stores`,{body:e,...t,headers:q([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}retrieve(e,t){return this._client.get(K`/vector_stores/${e}`,{...t,headers:q([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}update(e,t,n){return this._client.post(K`/vector_stores/${e}`,{body:t,...n,headers:q([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}list(e={},t){return this._client.getAPIList(`/vector_stores`,OR,{query:e,...t,headers:q([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}delete(e,t){return this._client.delete(K`/vector_stores/${e}`,{...t,headers:q([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}search(e,t,n){return this._client.getAPIList(K`/vector_stores/${e}/search`,DR,{body:t,method:`post`,...n,headers:q([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}};vH.Files=_H,vH.FileBatches=gH;var yH=class extends G{create(e,t){return this._client.post(`/videos`,RR({body:e,...t},this._client))}retrieve(e,t){return this._client.get(K`/videos/${e}`,t)}list(e={},t){return this._client.getAPIList(`/videos`,kR,{query:e,...t})}delete(e,t){return this._client.delete(K`/videos/${e}`,t)}createCharacter(e,t){return this._client.post(`/videos/characters`,RR({body:e,...t},this._client))}downloadContent(e,t={},n){return this._client.get(K`/videos/${e}/content`,{query:t,...n,headers:q([{Accept:`application/binary`},n?.headers]),__binaryResponse:!0})}edit(e,t){return this._client.post(`/videos/edits`,RR({body:e,...t},this._client))}extend(e,t){return this._client.post(`/videos/extensions`,RR({body:e,...t},this._client))}getCharacter(e,t){return this._client.get(K`/videos/characters/${e}`,t)}remix(e,t,n){return this._client.post(K`/videos/${e}/remix`,LR({body:t,...n},this._client))}},bH,xH,SH,CH=class extends G{constructor(){super(...arguments),bH.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");U(this,bH,`m`,xH).call(this,n);let i=q([t]).values,a=U(this,bH,`m`,SH).call(this,i,`webhook-signature`),o=U(this,bH,`m`,SH).call(this,i,`webhook-timestamp`),s=U(this,bH,`m`,SH).call(this,i,`webhook-id`),c=parseInt(o,10);if(isNaN(c))throw new nL(`Invalid webhook timestamp format`);let l=Math.floor(Date.now()/1e3);if(l-c>r)throw new nL(`Webhook timestamp is too old`);if(c>l+r)throw new nL(`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 nL(`The given webhook signature does not match the expected signature`)}};bH=new WeakSet,xH=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`)},SH=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 wH,TH,EH,DH,OH=`workload-identity-auth`,J=class{constructor({baseURL:e=VB(`OPENAI_BASE_URL`),apiKey:t=VB(`OPENAI_API_KEY`),organization:n=VB(`OPENAI_ORG_ID`)??null,project:r=VB(`OPENAI_PROJECT_ID`)??null,webhookSecret:i=VB(`OPENAI_WEBHOOK_SECRET`)??null,workloadIdentity:a,...o}={}){if(wH.add(this),EH.set(this,void 0),this.completions=new hV(this),this.chat=new CB(this),this.embeddings=new xV(this),this.files=new TV(this),this.images=new IV(this),this.audio=new kB(this),this.moderations=new RV(this),this.models=new LV(this),this.fineTuning=new NV(this),this.graders=new FV(this),this.vectorStores=new vH(this),this.webhooks=new CH(this),this.beta=new mV(this),this.batches=new AB(this),this.uploads=new mH(this),this.responses=new cH(this),this.realtime=new VV(this),this.conversations=new bV(this),this.evals=new wV(this),this.containers=new vV(this),this.skills=new fH(this),this.videos=new yH(this),a){if(t&&t!==OH)throw new W("The `apiKey` and `workloadIdentity` arguments are mutually exclusive; only one can be passed at a time.");t=OH}else if(t===void 0)throw new W("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&&_L())throw new W(`It looks like you're running in a browser-like environment.
181
+ `)}var VA=o({EventStreamContentType:()=>HA,convertEventStreamToIterableReadableDataStream:()=>JA,getBytes:()=>UA,getLines:()=>WA,getMessages:()=>GA}),HA=`text/event-stream`;async function UA(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(`
182
+ `))}}function WA(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=KA(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 GA(e,t,n){let r=qA(),i=new TextDecoder;return function(a,o,s){if(s){YA(r)||(e?.(r),r=qA());return}if(a.length===0)e?.(r),r=qA();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+`
183
+ `+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 KA(e,t){let n=new Uint8Array(e.length+t.length);return n.set(e),n.set(t,e.length),n}function qA(){return{data:``,event:``,id:``,retry:void 0}}function JA(e,t){let n=new ReadableStream({async start(n){let r=GA(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 UA(e,WA((e,t,i)=>{r(e,t,i),i&&n.close()}))}});return Ll.fromReadableStream(n)}function YA(e){return e.data===``&&e.event===``&&e.id===``&&e.retry===void 0}var XA=o({}),ZA=o({convertToOpenAIFunction:()=>QA,convertToOpenAITool:()=>$A,isLangChainTool:()=>jO,isRunnableToolLike:()=>kO,isStructuredTool:()=>OO,isStructuredToolParams:()=>AO});function QA(e,t){let n=typeof t==`number`?void 0:t;return{name:e.name,description:e.description,parameters:Eb(e.schema),...n?.strict===void 0?{}:{strict:n.strict}}}function $A(e,t){let n=typeof t==`number`?void 0:t,r;return r=jO(e)?{type:`function`,function:QA(e)}:e,n?.strict!==void 0&&(r.function.strict=n.strict),r}function ej(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 tj(e,t){let n=0;for(let r=0;r<e.length;r++)n+=e[r]*t[r];return n}function nj(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 rj(e,t){return Math.sqrt(nj(e,t))}var ij=o({cosineSimilarity:()=>sj,euclideanDistance:()=>lj,innerProduct:()=>cj,matrixFunc:()=>aj,maximalMarginalRelevance:()=>uj,normalize:()=>oj});function aj(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 oj(e,t=!1){let n=fj(e);return e.map(e=>e.map(e=>t?1-e/n:e/n))}function sj(e,t){return aj(e,t,ej)}function cj(e,t){return aj(e,t,tj)}function lj(e,t){return aj(e,t,rj)}function uj(e,t,n=.5,r=4){if(Math.min(r,t.length)<=0)return[];let i=sj(Array.isArray(e[0])?e:[e],t)[0],a=dj(i).maxIndex,o=[t[a]],s=[a];for(;s.length<Math.min(r,t.length);){let e=-1/0,r=-1,a=sj(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 dj(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 fj(e){return e.reduce((e,t)=>Math.max(e,dj(t).maxValue),0)}var pj=o({isCloudMetadata:()=>Dj,isLocalhost:()=>Oj,isPrivateIp:()=>Ej,isSafeUrl:()=>Aj,isSameOrigin:()=>jj,validateSafeUrl:()=>kj}),mj=[`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`],hj=[`169.254.169.254`,`169.254.170.2`,`100.100.100.200`],gj=[`metadata.google.internal`,`metadata`,`instance-data`],_j=[`localhost`,`localhost.localdomain`],vj=/^(?:(?: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 yj(e){return vj.test(e)}function bj(e){return Cj(e)!==null}function xj(e){return yj(e)||bj(e)}function Sj(e){if(yj(e))return e.split(`.`).map(e=>parseInt(e,10));if(bj(e)){let t=Cj(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 Cj(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 wj(e){let[t,n]=e.split(`/`);if(!t||!n)return null;let r=Sj(t);if(!r)return null;let i=parseInt(n,10);if(isNaN(i))return null;let a=bj(t);return a&&i>128||!a&&i>32?null:{addr:r,prefixLen:i,isIpv6:a}}function Tj(e,t){let n=Sj(e);if(!n)return!1;let r=wj(t);if(!r)return!1;let i=bj(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 Ej(e){if(!xj(e))return!1;for(let t of mj)if(Tj(e,t))return!0;return!1}function Dj(e,t){if(hj.includes(t||``))return!0;let n=e.toLowerCase();return!!gj.includes(n)}function Oj(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!!_j.includes(n)}function kj(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(Dj(i))throw Error(`URL points to cloud metadata endpoint: ${i}`);if(Oj(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(xj(i)){let t=i;if(Oj(i,t)){if(!n)throw Error(`URL points to localhost: ${i}`);return e}if(Dj(i,t))throw Error(`URL resolves to cloud metadata IP: ${t} (${i})`);if(Ej(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 Aj(e,t){try{return kj(e,t),!0}catch{return!1}}function jj(e,t){try{return new URL(e).origin===new URL(t).origin}catch{return!1}}var Mj=o({SaveableVectorStore:()=>Fj,VectorStore:()=>Pj,VectorStoreRetriever:()=>Nj}),Nj=class extends BD{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)}},Pj=class extends _e{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 Nj({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 Nj({...t,searchKwargs:e.searchKwargs}):new Nj({...t})}}},Fj=class extends Pj{static load(e,t){throw Error(`Not implemented`)}},Ij=class extends sE{_combineLLMOutput(){return[]}_llmType(){return`fake`}async _generate(e,t,n){if(t?.stop?.length)return{generations:[{message:new Jt(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(`
184
+ `);return await n?.handleLLMNewToken(r),{generations:[{message:new Jt(r),text:r}],llmOutput:{}}}},Lj=class e extends sE{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:Eb(e.schema)}};case`anthropic`:return{name:e.name,description:e.description,input_schema:Eb(e.schema)};case`bedrock`:return{toolSpec:{name:e.name,description:e.description,inputSchema:Eb(e.schema)}};case`google`:return{name:e.name,description:e.description,parameters:Eb(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 Jt({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 Cu({message:new Zt({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 Jt(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 Cu({message:new Zt({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})}}},Rj=class e extends sE{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 Jt(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 Cu({message:new Zt({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:Eb(e.schema)}};case`anthropic`:return{name:e.name,description:e.description,input_schema:Eb(e.schema)};case`bedrock`:return{toolSpec:{name:e.name,description:e.description,inputSchema:Eb(e.schema)}};case`google`:return{name:e.name,description:e.description,parameters:Eb(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 Zb.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`)})}},zj=class extends nw{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})}},Bj=class extends nw{constructor(e){super(e??{})}embedDocuments(e){return Promise.resolve(e.map(()=>[.1,.2,.3,.4]))}embedQuery(e){return Promise.resolve([.1,.2,.3,.4])}},Vj=class extends fE{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}},Hj=class extends fE{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)}},Uj=class extends UC{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 sn(e))}async addAIMessage(e){this.messages.push(new Jt(e))}async clear(){this.messages=[]}},Wj=class extends WC{lc_namespace=[`langchain_core`,`message`,`fake`];messages=[];constructor(){super()}async addMessage(e){this.messages.push(e)}async getMessages(){return this.messages}},Gj=class extends kc{name=`fake_tracer`;runs=[];constructor(){super()}persistRun(e){return this.runs.push(e),Promise.resolve()}},Kj=class extends $w{lc_namespace=[`tests`,`fake`];getFormatInstructions(){return``}async parse(e){return e.split(`,`).map(e=>e.trim())}},qj=class extends BD{lc_namespace=[`test`,`fake`];output=[new KC({pageContent:`foo`}),new KC({pageContent:`bar`})];constructor(e){super(),this.output=e?.output??this.output}async _getRelevantDocuments(e){return this.output}},Jj=class extends Ub{lc_namespace=[`tests`,`fake`];returnOptions;constructor(e){super(e),this.returnOptions=e.returnOptions}async invoke(e,t){return this.returnOptions?t??{}:{input:e}}},Yj=class extends wA{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)}},Xj=class extends kc{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}},Zj=class e extends Pj{memoryVectors=[];similarity;_vectorstoreType(){return`memory`}constructor(e,{similarity:t,...n}={}){super(e,n),this.similarity=t??ej}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 KC({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 KC({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 KC({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)}},Qj=o({FakeChatMessageHistory:()=>Uj,FakeChatModel:()=>Ij,FakeEmbeddings:()=>Bj,FakeLLM:()=>Vj,FakeListChatMessageHistory:()=>Wj,FakeListChatModel:()=>Rj,FakeRetriever:()=>qj,FakeRunnable:()=>Jj,FakeSplitIntoListParser:()=>Kj,FakeStreamingChatModel:()=>Lj,FakeStreamingLLM:()=>Hj,FakeTool:()=>Yj,FakeTracer:()=>Gj,FakeVectorStore:()=>Zj,SingleRunExtractor:()=>Xj,SyntheticEmbeddings:()=>zj}),$j=o({agents:()=>DC,caches:()=>FC,callbacks__base:()=>hr,callbacks__manager:()=>dl,callbacks__promises:()=>ol,chat_history:()=>HC,document_loaders__base:()=>XC,document_loaders__langsmith:()=>QC,documents:()=>YC,embeddings:()=>tw,errors:()=>l,example_selectors:()=>fw,index:()=>EC,indexing:()=>xw,language_models__base:()=>Hw,language_models__chat_models:()=>aE,language_models__compat:()=>KT,language_models__event:()=>lE,language_models__llms:()=>uE,language_models__profile:()=>pE,language_models__stream:()=>MT,language_models__structured_output:()=>OT,load__serializable:()=>pe,memory:()=>mE,messages:()=>wx,messages__tool:()=>gt,output_parsers:()=>xT,output_parsers__openai_functions:()=>CE,output_parsers__openai_tools:()=>wE,outputs:()=>bu,prompt_values:()=>Sw,prompts:()=>ID,retrievers:()=>zD,retrievers__document_compressors:()=>LD,runnables:()=>Ex,runnables__graph:()=>Ob,singletons:()=>Tl,stores:()=>VD,structured_query:()=>cO,testing:()=>DO,tools:()=>CA,tracers__base:()=>wc,tracers__console:()=>jc,tracers__log_stream:()=>fu,tracers__run_collector:()=>MA,tracers__tracer_langchain:()=>Kc,types__stream:()=>PA,utils__async_caller:()=>Ru,utils__chunk_array:()=>FA,utils__context:()=>LA,utils__env:()=>ar,utils__event_source_parse:()=>VA,utils__format:()=>XA,utils__function_calling:()=>ZA,utils__hash:()=>PC,utils__json_patch:()=>Zw,utils__json_schema:()=>wb,utils__math:()=>ij,utils__ssrf:()=>pj,utils__standard_schema:()=>Iy,utils__stream:()=>Il,utils__testing:()=>Qj,utils__tiktoken:()=>Lw,utils__types:()=>ST,utils__uuid:()=>ir,vectorstores:()=>Mj}),eM=50;function tM(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 nM(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)=>nM.call({...this,path:[...o,`${t}`],depth:s+1},e)));let u=e;if(le(u))return fe(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=mr(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:$j,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(TC.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`&&ge(e)===a);if(typeof g!=`function`)throw Error(`Invalid identifer: ${l} -> ${i}`);let _=new g(ae(await nM.call({...this,path:[...o,`kwargs`],depth:s+1},e.kwargs),ie,tM(g)));return Object.defineProperty(_.constructor,`name`,{value:a}),_}let d={};for(let[e,t]of Object.entries(u))d[e]=await nM.call({...this,path:[...o,e],depth:s+1},t);return d}async function rM(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??eM};return nM.call(r,n)}function iM(e){return e!==null&&e.lc===1&&e.type===`constructor`&&Array.isArray(e.id)}async function aM(e){if(e&&typeof e==`object`){if(Array.isArray(e))return await Promise.all(e.map(e=>aM(e)));{let t={};for(let[n,r]of Object.entries(e))t[n]=await aM(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(iM(t))return rM(JSON.stringify(t));return t}}return e}function oM(e,t,n,r){return{lc:2,type:`constructor`,id:[e.name],method:t??null,args:n??[],kwargs:r??{}}}function sM(e){return e===void 0?{lc:2,type:`undefined`}:e instanceof Set||e instanceof Map?oM(e.constructor,void 0,[Array.from(e)]):e instanceof RegExp?oM(RegExp,void 0,[e.source,e.flags]):e instanceof Error?oM(e.constructor,void 0,[e.message]):e?.lg_name===`Send`?{node:e.node,args:e.args}:e instanceof Uint8Array?oM(Uint8Array,`from`,[Array.from(e)]):e}var cM=class{_dumps(e){return new TextEncoder().encode(xC(e,(e,t)=>sM(t)))}async dumpsTyped(e){return e instanceof Uint8Array?[`bytes`,e]:[`json`,this._dumps(e)]}async _loads(e){return aM(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 lM(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]=lM(e[n]));return t}function uM(){return{v:4,id:uC(-2),ts:new Date().toISOString(),channel_values:{},channel_versions:{},versions_seen:{}}}function dM(e){return{v:e.v,id:e.id,ts:e.ts,channel_values:{...e.channel_values},channel_versions:{...e.channel_versions},versions_seen:lM(e.versions_seen)}}function fM(e,t){return typeof e==`number`&&typeof t==`number`?Math.sign(e-t):String(e).localeCompare(String(t))}function pM(...e){return e.reduce((e,t,n)=>n===0?t:fM(e,t)>=0?e:t)}var mM={[fC]:-1,[pC]:-2,[mC]:-3,[hC]:-4},hM=class extends Error{constructor(e){super(e),this.name=`InvalidNamespaceError`}};function gM(e){if(e.length===0)throw new hM(`Namespace cannot be empty.`);for(let t of e){if(typeof t!=`string`)throw new hM(`Invalid namespace label '${t}' found in ${e}. Namespace labels must be strings, but got ${typeof t}.`);if(t.includes(`.`))throw new hM(`Invalid namespace label '${t}' found in ${e}. Namespace labels cannot contain periods ('.').`);if(t===``)throw new hM(`Namespace labels cannot be empty strings. Got ${t} in ${e}`)}if(e[0]===`langgraph`)throw new hM(`Root label for namespace cannot be "langgraph". Got: ${e}`)}var _M=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){gM(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(){}},vM=e=>`lg_name`in e&&e.lg_name===`AsyncBatchedStore`?e.store:e,yM=class extends _M{lg_name=`AsyncBatchedStore`;store;queue=new Map;nextKey=0;running=!1;processingTask=null;constructor(e){super(),this.store=vM(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]`}}},bM=class{serde=new cM;constructor(e){this.serde=e||this.serde}};function xM(e){return e!=null&&e.lg_is_channel===!0}var SM=class{ValueType;UpdateType;lg_is_channel=!0;consume(){return!1}finish(){return!1}isAvailable(){try{return this.get(),!0}catch(e){if(e.name===AS.unminifiable_name)return!1;throw e}}equals(e){return this===e}},CM=Symbol.for(`LG_IS_ONLY_BASE_CHANNEL`);function wM(e){if(e[CM]===!0)return e;let t={};for(let n in e){if(!Object.prototype.hasOwnProperty.call(e,n))continue;let r=e[n];xM(r)&&(t[n]=r)}return Object.assign(t,{[CM]:!0}),t}function TM(e,t){let n=wM(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,{[CM]:!0}),r}function EM(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!==AS.unminifiable_name)throw e}}return{v:4,id:r?.id??uC(n),ts:new Date().toISOString(),channel_values:i,channel_versions:e.channel_versions,versions_seen:e.versions_seen}}var DM=class e extends SM{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 jS(`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 AS;return this.value[0]}checkpoint(){if(this.value.length===0)throw new AS;return this.value[0]}isAvailable(){return this.value.length!==0}},OM=class e extends SM{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 AS;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}},kM=e=>e!=null&&e.lc_graph_name===`BinaryOperatorAggregate`,AM=class e extends SM{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]=pS(e);n?this.value=r:this.value=e,t=t.slice(1)}let n=!1;for(let e of t)if(mS(e)){if(n)throw new jS(`Can receive only one Overwrite value per step.`);let[,t]=pS(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 AS;return this.value}checkpoint(){if(this.value===void 0)throw new AS;return this.value}isAvailable(){return this.value!==void 0}equals(e){return this===e?!0:kM(e)?this.operator===e.operator:!1}},jM=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`}},MM=function(e){return e?NM(e):new DM};MM.Root=e=>new jM(e);function NM(e){return typeof e==`object`&&e&&`reducer`in e&&e.reducer?new AM(e.reducer,e.default):typeof e==`object`&&e&&`value`in e&&e.value?new AM(e.value,e.default):new DM}var PM=[`tags`,`metadata`,`callbacks`,`configurable`],FM=[`tags`,`metadata`,`callbacks`,`runName`,`maxConcurrency`,`recursionLimit`,`configurable`,`runId`,`outputKeys`,`streamMode`,`store`,`writer`,`interrupt`,`context`,`interruptBefore`,`interruptAfter`,`checkpointDuring`,`durability`,`signal`,`executionInfo`,`serverInfo`],IM=25,LM=new Set([`thread_id`,`checkpoint_id`,`checkpoint_ns`,`task_id`,`run_id`,`assistant_id`,`graph_id`]);function RM(e,t){if(!e)return t;let n=t??{};for(let t of LM){if(t in n)continue;let r=e[t];r!==void 0&&(n[t]=r)}return n}function zM(...e){let t={tags:[],metadata:{},callbacks:void 0,recursionLimit:IM,configurable:{}},n=wl.getRunnableConfig();if(n!==void 0){for(let[e,r]of Object.entries(n))if(r!==void 0)if(PM.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&&FM.includes(e)&&(t[e]=r);return t.metadata=RM(t.configurable,t.metadata)??{},t}function BM(){return wl.getRunnableConfig()}function VM(e){return e.split(`|`).filter(e=>!e.match(/^\d+$/)).map(e=>e.split(`:`)[0]).join(`|`)}function HM(e){let t=e.split(`|`);for(;t.length>1&&t[t.length-1].match(/^\d+$/);)t.pop();return t.slice(0,-1).join(`|`)}var UM=class extends Ub{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=Ml(t,{callbacks:n?.getChild()});wl.runWithConfig(a,async()=>{try{r(await this.func(e,a))}catch(e){i(e)}})})}async invoke(e,t){let n,r=zM(t),i=Al(this.config,r);return n=this.trace?await this._callWithConfig(this._tracedInvoke,e,i):await wl.runWithConfig(i,async()=>this.func(e,i)),Ub.isRunnable(n)&&this.recurse?await wl.runWithConfig(i,async()=>n.invoke(e,i)):n}};function*WM(e,t){if(t===void 0)yield*e;else for(let n of e)yield[t,n]}async function GM(e){let t=[];for await(let n of await e)t.push(n);return t}function KM(e){let t=[];for(let n of e)t.push(n);return t}function qM(e,t){return e?`configurable`in e?{...e,configurable:{...e.configurable,...t}}:{...e,configurable:t}:{configurable:t}}function JM(e){return typeof e==`object`&&e?.[Symbol.for(`LG_SKIP_WRITE`)]!==void 0}var YM={[Symbol.for(`LG_PASSTHROUGH`)]:!0};function XM(e){return typeof e==`object`&&e?.[Symbol.for(`LG_PASSTHROUGH`)]!==void 0}var ZM=Symbol(`IS_WRITER`),QM=class e extends UM{writes;constructor(e,t){let n=`ChannelWrite<${e.map(e=>dS(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=>eN(e)&&XM(e.value)?{mapper:e.mapper,value:t}:$M(e)&&XM(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($M(e)){if(e.channel===`__pregel_tasks`)throw new jS(`Cannot write to the reserved channel TASKS`);if(XM(e.value))throw new jS(`PASSTHROUGH value must be replaced`)}if(eN(e)&&XM(e.value))throw new jS(`PASSTHROUGH value must be replaced`)}let n=[];for(let r of t)if(dS(r))n.push([nS,r]);else if(eN(r)){let t=await r.mapper.invoke(r.value,e);t!=null&&t.length>0&&n.push(...t)}else if($M(r)){let t=r.mapper===void 0?r.value:await r.mapper.invoke(r.value,e);if(JM(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?.[Mx];r(n)}static isWriter(t){return t instanceof e||ZM in t&&!!t[ZM]}static registerWriter(e){return Object.defineProperty(e,ZM,{value:!0})}};function $M(e){return e!==void 0&&typeof e.channel==`string`}function eN(e){return e!==void 0&&!$M(e)&&Ub.isRunnable(e.mapper)}var tN=class e extends UM{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?.[Px];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)}},nN=new ax,rN=class e extends Wb{lc_graph_name=`PregelNode`;channels;triggers=[];mapper;writers=[];bound=nN;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??nN,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 QM&&e[e.length-2]instanceof QM;){let t=e.slice(-2),n=t[0].writes.concat(t[1].writes);e[e.length-2]=new QM(n,t[0].config?.tags),e.pop()}return e}getNode(){let e=this.getWriters();if(!(this.bound===nN&&e.length===0))return this.bound===nN&&e.length===1?e[0]:this.bound===nN?new qb({first:e[0],middle:e.slice(1,e.length-1),last:e[e.length-1],omitSequenceTags:!0}):e.length>0?new qb({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 QM.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===nN?new e({channels:this.channels,triggers:this.triggers,mapper:this.mapper,writers:this.writers,bound:ex(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 iN(e){return`steps`in e&&Array.isArray(e.steps)}function aN(e){return`lg_is_pregel`in e&&e.lg_is_pregel===!0}function oN(e){let t=[e];for(let e of t)if(aN(e))return e;else iN(e)&&t.push(...e.steps)}var sN=class e extends SM{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 jS(`EphemeralValue can only receive one value per step.`);return this.value=[e[e.length-1]],!0}get(){if(this.value.length===0)throw new AS;return this.value[0]}checkpoint(){if(this.value.length===0)throw new AS;return this.value[0]}isAvailable(){return this.value.length!==0}},H=e=>BigInt(e),cN=(e,t=0)=>new DataView(e.buffer,e.byteOffset+t,e.byteLength-t),lN=H(`0x9E3779B1`),uN=H(`0x85EBCA77`),dN=H(`0xC2B2AE3D`),fN=H(`0x9E3779B185EBCA87`),pN=H(`0xC2B2AE3D27D4EB4F`),mN=H(`0x165667B19E3779F9`),hN=H(`0x85EBCA77C2B2AE63`),gN=H(`0x27D4EB2F165667C5`),_N=H(`0x165667919E3779F9`),vN=H(`0x9FB21C651E98DF25`),yN=(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 cN(r)})(`b8fe6c3923a44bbe7c01812cf721ad1cded46de9839097db7240a4a4b7b3671fcb79e64eccc0e578825ad07dccff7221b8084674f743248ee03590e6813a264c3c2852bb91c300cb88d0658b1b532ea371644897a20df94e3819ef46a9deacd8a8fa763fe39c343ff9dcbbc7c70b4f1d8a51e04bcdb45931c89f7ec9d9787364eac5ac8334d3ebc3c581a0fffa1363eb170ddd51b7f0da49d316552629d4689e2b16be587d47a1fc8ff8b8d17ad031ce45cb3a8f95160428afd7fbcabb4b407e`),bN=(H(1)<<H(128))-H(1),xN=(H(1)<<H(64))-H(1),SN=(H(1)<<H(32))-H(1),CN=64,wN=CN/8,TN=8,EN=4;function DN(e){if(!e)throw Error(`Assert failed`)}function ON(e){let t=new DataView(new ArrayBuffer(8));return t.setBigUint64(0,e,!0),t.getBigUint64(0,!1)}function kN(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 AN(e,t){return(e&SN)*(t&SN)&xN}function jN(e,t){return(e<<t|e>>H(32)-t)&SN}function MN(e,t,n){for(let r=0;r<wN;r+=1){let i=t.getBigUint64(r*8,!0),a=i^n.getBigUint64(r*8,!0);e[r^1]+=i,e[r]+=AN(a,a>>H(32))}return e}function NN(e,t,n,r){for(let i=0;i<r;i+=1)MN(e,cN(t,i*CN),cN(n,i*8));return e}function PN(e,t){for(let n=0;n<wN;n+=1){let r=t.getBigUint64(n*8,!0),i=e[n];i=GN(i,H(47)),i^=r,i*=lN,e[n]=i&xN}return e}function FN(e,t){return zN(e[0]^t.getBigUint64(0,!0),e[1]^t.getBigUint64(TN,!0))}function IN(e,t,n){let r=n;return r+=FN(e.slice(0),cN(t,0*EN)),r+=FN(e.slice(2),cN(t,4*EN)),r+=FN(e.slice(4),cN(t,8*EN)),r+=FN(e.slice(6),cN(t,12*EN)),HN(r&xN)}function LN(e,t,n,r,i){let a=e,o=Math.floor((n.byteLength-CN)/8),s=CN*o,c=Math.floor((t.byteLength-1)/s);for(let e=0;e<c;e+=1)a=NN(a,cN(t,e*s),n,o),a=i(a,cN(n,n.byteLength-CN));{let e=Math.floor((t.byteLength-1-s*c)/CN);a=NN(a,cN(t,c*s),n,e),a=r(a,cN(t,t.byteLength-CN),cN(n,n.byteLength-CN-7))}return a}function RN(e,t){let n=new BigUint64Array([dN,fN,pN,mN,hN,uN,gN,lN]);DN(e.byteLength>128),n=LN(n,e,t,MN,PN),DN(n.length*8==64);{let r=IN(n,cN(t,11),H(e.byteLength)*fN&xN);return IN(n,cN(t,t.byteLength-CN-11),~(H(e.byteLength)*pN)&xN)<<H(64)|r}}function zN(e,t){let n=e*t&bN;return n&xN^n>>H(64)}function BN(e,t,n){return zN((e.getBigUint64(0,!0)^t.getBigUint64(0,!0)+n)&xN,(e.getBigUint64(8,!0)^t.getBigUint64(8,!0)-n)&xN)}function VN(e,t,n,r,i){let a=e&xN,o=e>>H(64)&xN;return a+=BN(t,r,i),a^=n.getBigUint64(0,!0)+n.getBigUint64(8,!0),a&=xN,o+=BN(n,cN(r,16),i),o^=t.getBigUint64(0,!0)+t.getBigUint64(8,!0),o&=xN,o<<H(64)|a}function HN(e){let t=e;return t^=t>>H(37),t*=_N,t&=xN,t^=t>>H(32),t}function UN(e){let t=e;return t^=t>>H(33),t*=pN,t&=xN,t^=t>>H(29),t*=mN,t&=xN,t^=t>>H(32),t}function WN(e,t,n){let r=e.byteLength;DN(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)&xN,o=(H(t.getUint32(8,!0))^H(t.getUint32(12,!0)))-n;return(UN((jN(kN(i),H(13))^o)&xN)&xN)<<H(64)|UN(a)}function GN(e,t){return e^e>>t}function KN(e,t,n){let r=e.byteLength;DN(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&xN)*(fN+(H(r)<<H(2)))&bN;return o+=(o&xN)<<H(65),o&=bN,o^=o>>H(67),GN(GN(o&xN,H(35))*vN&xN,H(28))|HN(o>>H(64))<<H(64)}}function qN(e,t,n){let r=e.byteLength;DN(r>=9&&r<=16);{let i=(t.getBigUint64(32,!0)^t.getBigUint64(40,!0))+n&xN,a=(t.getBigUint64(48,!0)^t.getBigUint64(56,!0))-n&xN,o=e.getBigUint64(0,!0),s=e.getBigUint64(r-8,!0),c=(o^s^i)*fN,l=(c&xN)+(H(r-1)<<H(54));c=c&(bN^xN)|l,s^=a,c+=s+(s&SN)*(uN-H(1))<<H(64),c&=bN,c^=ON(c>>H(64));let u=(c&xN)*pN;return u+=(c>>H(64))*pN<<H(64),u&=bN,HN(u&xN)|HN(u>>H(64))<<H(64)}}function JN(e,t){let n=e.byteLength;return DN(n<=16),n>8?qN(e,yN,t):n>=4?KN(e,yN,t):n>0?WN(e,yN,t):UN(t^yN.getBigUint64(64,!0)^yN.getBigUint64(72,!0))|UN(t^yN.getBigUint64(80,!0)^yN.getBigUint64(88,!0))<<H(64)}function YN(e){return~e+H(1)&xN}function XN(e,t,n){let r=H(e.byteLength)*fN&xN,i=H(e.byteLength-1)/H(32);for(;i>=0;){let a=Number(i);r=VN(r,cN(e,16*a),cN(e,e.byteLength-16*(a+1)),cN(t,32*a),n),i-=H(1)}let a=r+(r>>H(64))&xN;a=HN(a);let o=(r&xN)*fN+(r>>H(64))*hN+(H(e.byteLength)-n&xN)*pN;return o&=xN,o=YN(HN(o)),a|o<<H(64)}function ZN(e,t,n){let r=H(e.byteLength)*fN&xN;for(let i=32;i<160;i+=32)r=VN(r,cN(e,i-32),cN(e,i-16),cN(t,i-32),n);r=HN(r&xN)|HN(r>>H(64))<<H(64);for(let i=160;i<=e.byteLength;i+=32)r=VN(r,cN(e,i-32),cN(e,i-16),cN(t,3+i-160),n);r=VN(r,cN(e,e.byteLength-16),cN(e,e.byteLength-32),cN(t,103),YN(n));let i=r+(r>>H(64))&xN;i=HN(i);let a=(r&xN)*fN+(r>>H(64))*hN+(H(e.byteLength)-n&xN)*pN;return a&=xN,a=YN(HN(a)),i|a<<H(64)}function QN(e,t=H(0)){let n=new TextEncoder,r=cN(typeof e==`string`?n.encode(e):e),i=r.byteLength;return(e=>e.toString(16).padStart(32,`0`))(i<=16?JN(r,t):i<=128?XN(r,yN,t):i<=240?ZN(r,yN,t):RN(r,yN))}function $N(e){return/^[0-9a-f]{32}$/.test(e)}function eP(e,t,n=!0,r=!1){try{return e[t].get()}catch(e){if(e.name===AS.unminifiable_name){if(r)return e;if(n)return null}throw e}}function tP(e,t,n=!0){if(Array.isArray(t)){let r={};for(let i of t)try{r[i]=eP(e,i,!n)}catch(e){if(e.name===AS.unminifiable_name)continue}return r}else return eP(e,t)}function*nP(e,t){if(e.graph===gS.PARENT)throw new jS(`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(dS(e))yield[aS,nS,e];else if(typeof e==`string`)yield[aS,`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($N))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,Xx,e]}else yield[aS,Xx,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[aS,t,n];else for(let[t,n]of Object.entries(e.update))yield[aS,t,n]}}function*rP(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*iP(e,t,n){Array.isArray(e)?(t===!0||t.find(([t,n])=>e.includes(t)))&&(yield tP(n,e)):(t===!0||t.some(([t,n])=>t===e))&&(yield eP(n,e))}function*aP(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===Qx).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 oP(e){let t=typeof e[Dx];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 sP(e,t){if(Object.keys(e).length>0){let n=oP(t);return Object.fromEntries(Object.entries(t).filter(([t,r])=>r>(e[t]??n)))}else return t}function cP(e,t){return e&&!Array.isArray(e)&&!(e instanceof Date)&&typeof e==`object`?e:{[t]:e}}function lP(e,t){return e===null?{configurable:t}:e?.configurable===void 0?{...e,configurable:t}:{...e,configurable:{...e.configurable,...t}}}function uP(e,t){let n=t?.parents??{};return Object.keys(n).length>0?lP(e,{[qx]:{...n,[e.configurable?.checkpoint_ns??``]:e.configurable?.checkpoint_id}}):e}function dP(...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 fP=(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},pP=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 mP(e){return typeof e==`object`&&!!e&&`__lg_type`in e&&e.__lg_type===`call`}function hP(e,t){return new qb({name:e,first:new UM({func:e=>t(...e),name:e,trace:!1,recurse:!1}),last:new QM([{channel:Qx,value:YM}],[eS])})}var gP=e=>e===void 0?1:e+1;function _P(e,t){if(t==null)return!1;for(let n of e)if(t[n])return!0;return!1}function vP(e){let t;for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t=t==null?e[n]:pM(t,e[n]));return t}function yP(e,t,n){let r=oP(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(eS):t.includes(e.name));return a&&o}function bP(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=EM(e,i,-1),c=TM(i,s);CP(dM(s),c,[n],void 0,void 0),o=tP({...t,...c},r)}else o=tP(t,r);return o}function xP(e,t,n){for(let[e,r]of n)if([`__pregel_push`,`__pregel_tasks`].includes(e)&&r!=null){if(!dS(r))throw new jS(`Invalid packet type, expected SendProtocol, got ${JSON.stringify(r)}`);if(!(r.node in t))throw new jS(`Invalid node name "${r.node}" in Send packet`)}e(n)}var SP=new Set([Zx,rS,Xx,Yx,Qx,Ax]);function CP(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=wM(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=vP(e.channel_versions),c=new Set(n.flatMap(e=>e.triggers).filter(e=>!oS.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)SP.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===jS.unminifiable_name){let r=new jS(`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&&!_P(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*wP(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 TP(e,t,n,r,i,a,o){let s={},c=r[nS];if(c?.isAvailable()){let l=c.get().length;for(let c=0;c<l;c+=1){let l=EP([rS,c],e,t,n,r,i,a,o);l!==void 0&&(s[l.id]=l)}}for(let c of wP(e,n,o)){let l=EP([iS,c],e,t,n,r,i,a,o);l!==void 0&&(s[l.id]=l)}return s}function EP(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`&&mP(e[e.length-1])){let p=e[e.length-1],m=hP(p.name,p.func),h=[rS],g=f===``?p.name:`${f}|${p.name}`,_=dC(JSON.stringify([g,c.toString(),p.name,rS,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:{...Ml(Al(a,{metadata:b,store:s.store??a.store}),{runName:p.name,callbacks:u?.getChild(`graph:step:${c}`),configurable:{[Lx]:_,[Mx]:t=>xP(t=>e.push(...t),r,t),[Px]:(n,r=!1)=>bP(t,i,{name:p.name,writes:e,triggers:h,path:y},n,r),[Fx]:l??d.__pregel_checkpointer,[qx]:{...d[qx],[f]:t.id},[Vx]:kP({pendingWrites:n??[],taskId:_,currentTaskInput:p.input,resumeMap:a.configurable?.[Bx],namespaceHash:QN(v)}),[Hx]:t.channel_values[$x],checkpoint_id:void 0,checkpoint_ns:v}}),executionInfo:o},triggers:h,retry_policy:p.retry,cache_key:p.cache?{key:QN((p.cache.keyFunc??JSON.stringify)([p.input])),ns:[jx,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[nS].get();if(p<0||p>=m.length)return;let h=lS(m[p])&&!dS(m[p])?new uS(m[p].node,m[p].args):m[p];if(!lS(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=[rS],_=f===``?h.node:`${f}|${h.node}`,v=dC(JSON.stringify([_,c.toString(),h.node,rS,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:{...Ml(Al(a,{metadata:b,tags:o.tags,store:s.store??a.store}),{runName:h.node,callbacks:u?.getChild(`graph:step:${c}`),configurable:{[Lx]:v,[Mx]:e=>xP(e=>m.push(...e),r,e),[Px]:(n,r=!1)=>bP(t,i,{name:h.node,writes:m,triggers:g,path:e},n,r),[Fx]:l??d.__pregel_checkpointer,[qx]:{...d[qx],[f]:t.id},[Vx]:kP({pendingWrites:n??[],taskId:v,currentTaskInput:h.args,resumeMap:a.configurable?.[Bx],namespaceHash:QN(y)}),[Hx]:t.channel_values[$x],checkpoint_id:void 0,checkpoint_ns:y}}),executionInfo:_},triggers:g,retry_policy:o.retryPolicy,cache_key:o.cachePolicy?{key:QN((o.cachePolicy.keyFunc??JSON.stringify)([h.args])),ns:[jx,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=dC(JSON.stringify([e,c.toString(),p,iS,p]),t.id);if(n.some(e=>e[0]===r&&e[1]!==`__error__`))return}let h=oP(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=DP(m,i,o);if(h===void 0)return;let g=f===``?p:`${f}|${p}`,v=dC(JSON.stringify([g,c.toString(),p,iS,[_]]),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:{...Ml(Al(a,{metadata:b,tags:m.tags,store:s.store??a.store}),{runName:p,callbacks:u?.getChild(`graph:step:${c}`),configurable:{[Lx]:v,[Mx]:e=>xP(e=>{g.push(...e)},r,e),[Px]:(n,r=!1)=>bP(t,i,{name:p,writes:g,triggers:[_],path:e},n,r),[Fx]:l??d.__pregel_checkpointer,[qx]:{...d[qx],[f]:t.id},[Vx]:kP({pendingWrites:n??[],taskId:v,currentTaskInput:h,resumeMap:a.configurable?.[Bx],namespaceHash:QN(y)}),[Hx]:t.channel_values[$x],checkpoint_id:void 0,checkpoint_ns:y}}),executionInfo:ee},triggers:[_],retry_policy:m.retryPolicy,cache_key:m.cachePolicy?{key:QN((m.cachePolicy.keyFunc??JSON.stringify)([h])),ns:[jx,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 DP(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]=eP(t,i,!1)}catch(e){if(e.name===AS.unminifiable_name)return;throw e}else if(i in t)try{r[n]=eP(t,i,!1)}catch(e){if(e.name===AS.unminifiable_name)continue;throw e}}else if(Array.isArray(e.channels)){let n=!1;for(let i of e.channels)try{r=eP(t,i,!1),n=!0;break}catch(e){if(e.name===AS.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 OP(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 uS(e.node,n)}function kP({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 AP={blue:{start:`\x1B[34m`,end:`\x1B[0m`},green:{start:`\x1B[32m`,end:`\x1B[0m`},yellow:{start:`\x1B[33;1m`,end:`\x1B[0m`}},jP=(e,t)=>`${e.start}${t}${e.end}`;function*MP(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 NP(e){return typeof e!=`object`||!e?!1:`$writes`in e&&Array.isArray(e.$writes)}function PP(e){let t={};for(let[n,r]of e){let e=String(n);if(e in t){let n=NP(t[e])?t[e].$writes:[t[e]];n.push(r),t[e]={$writes:n}}else t[e]=r}return t}function*FP(e,t){for(let[{id:n,name:r,config:i},a]of e)i?.tags?.includes(`langsmith:hidden`)||(yield{id:n,name:r,result:PP(a.filter(([e])=>Array.isArray(t)?t.includes(e):e===t)),interrupts:a.filter(e=>e[0]===Yx).map(e=>e[1])})}function*IP(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(oN))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:tP(t,n),metadata:r,next:i.map(e=>e.name),tasks:LP(i,a,u,s),parentConfig:o?c(o):void 0}}function LP(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?PP(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 RP(e,t,n){console.log([`${jP(AP.blue,`[${e}:checkpoint]`)}`,`\x1b[1m State at the end of step ${e}:\x1b[0m\n`,JSON.stringify(tP(t,n),null,2)].join(``))}function zP(e,t){let n=t.length;console.log([`${jP(AP.blue,`[${e}:tasks]`)}`,`\x1b[1m Starting step ${e} with ${n} task${n===1?``:`s`}:\x1b[0m\n`,t.map(e=>`- ${jP(AP.green,String(e.name))} -> ${JSON.stringify(e.input,null,2)}`).join(`
185
+ `)].join(``))}function BP(e,t,n){let r={};for(let[e,i]of t)n.includes(e)&&(r[e]||(r[e]=[]),r[e].push(i));console.log([`${jP(AP.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])=>`- ${jP(AP.yellow,e)} -> ${t.map(e=>JSON.stringify(e)).join(`, `)}`).join(`
186
+ `)].join(``))}var VP=class extends Ll{_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}},HP=class extends Ll{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)}},UP=class extends yr{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 WP(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 GP(e){return e instanceof Error?{error:e.name,message:e.message}:{error:`Error`,message:JSON.stringify(e)}}function KP(e){return typeof e!=`object`||!e?!1:`configurable`in e&&typeof e.configurable==`object`&&e.configurable!=null}function qP(e){return!KP(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 JP(e){if(KP(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 YP(e){let t={...e,checkpoint:qP(e.config),parent_checkpoint:qP(e.parentConfig),config:JP(e.config),parent_config:JP(e.parentConfig),tasks:e.tasks.map(e=>{if(KP(e.state)){let t=qP(e.state);if(t!=null){let n={...e,checkpoint:t};return delete n.state,n}}return e})};return delete t.parentConfig,t}function XP(e){let t=new TextEncoder;return new ReadableStream({async start(n){let r=e=>{n.enqueue(t.encode(`event: ${e.event}\ndata: ${WP(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:YP(e.payload)})}n===`checkpoints`&&(a=YP(i)),r({event:e?.length?`${n}|${e.join(`|`)}`:n,data:a})}}catch(e){r({event:`error`,data:GP(e)})}n.close()}})}var ZP=Symbol.for(`INPUT_DONE`),QP=Symbol.for(`INPUT_RESUMING`),$P=25;function eF(...e){return new HP({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 tF=class extends bM{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}},nF=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=_S(this.input)&&this.input.resume!=null,i=this.input===QP,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=gP: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 tF(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=eF(r,n.configurable[Rx]));let i=n.configurable?!(`checkpoint_id`in n.configurable):!0,a=n.configurable?.[Vx];n.configurable&&a&&(a.subgraphCounter>0&&(n=lP(n,{[Gx]:[n.configurable[Gx],a.subgraphCounter.toString()].join(`|`)})),a.subgraphCounter+=1);let o=Px in(n.configurable??{});!o&&n.configurable?.checkpoint_ns!==void 0&&n.configurable?.checkpoint_ns!==``&&(n=lP(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=lP(n,{checkpoint_id:n.configurable[qx][n.configurable?.checkpoint_ns]}));let c=n.configurable?.checkpoint_ns?.split(`|`)??[],l=await t.checkpointer?.getTuple(s)??{config:n,checkpoint:uM(),metadata:{source:`input`,step:-2,parents:{}},pendingWrites:[]};s={...n,...l.config,configurable:{checkpoint_ns:``,...n.configurable,...l.config.configurable}};let u=l.parentConfig,d=dM(l.checkpoint),f={...l.metadata},p=l.pendingWrites??[],m=TM(t.channelSpecs,d),h=(f.step??0)+1,g=h+(n.recursionLimit??$P)+1,_={...d.channel_versions},v=t.store?new yM(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 mM)&&(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`&&dS(t)?[e,OP(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=lP(this.checkpointConfig,{[Gx]:this.config.configurable?.checkpoint_ns??``,[Wx]: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]===Yx).flatMap(e=>e[1]);this._emit([[`updates`,{[Yx]:e}],[`values`,{[Yx]:e}]])}else t[0][0]!==`__error__`&&this._emit(KM(WM(aP(this.outputKeys,[[r,t]],n),`updates`)));n||this._emit(KM(WM(FP([[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(![ZP,QP].includes(this.input))await this._first(t);else if(this.toInterrupt.length>0)throw this.status=`interrupt_before`,new CS;else if(Object.values(this.tasks).every(e=>e.writes.length>0)){let e=Object.values(this.tasks).flatMap(e=>e.writes);this.updatedChannels=CP(this.checkpoint,this.channels,Object.values(this.tasks),this.checkpointerGetNextVersion,this.triggerToNodes);let t=await GM(WM(iP(this.outputKeys,e,this.channels),`values`));if(this.checkpointPendingWrites=[],await this._putCheckpoint({source:`loop`}),this._emitValuesWithCheckpointMeta(t),yP(this.checkpoint,this.interruptAfter,Object.values(this.tasks)))throw this.status=`interrupt_after`,new CS;this.config.configurable?.__pregel_resuming!==void 0&&delete this.config.configurable?.[Ix]}else return!1;if(this.step>this.stop)return this.status=`out_of_steps`,!1;if(this.tasks=TP(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 GM(WM(IP(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(yP(this.checkpoint,this.interruptBefore,Object.values(this.tasks)))throw this.status=`interrupt_before`,new CS;let n=await GM(WM(MP(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=tP(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=CP(this.checkpoint,this.channels,Object.values(this.tasks),this.checkpointerGetNextVersion,this.triggerToNodes),this._emitValuesWithCheckpointMeta(KM(WM(iP(this.outputKeys,Object.values(this.tasks).flatMap(e=>e.writes),this.channels),`values`)))),OS(e)&&!e.interrupts.length&&this._emit([[`updates`,{[Yx]:[]}],[`values`,{[Yx]:[]}]])),t}async acceptPush(e,t,n){if(this.interruptAfter?.length>0&&yP(this.checkpoint,this.interruptAfter,[e])){this.toInterrupt.push(e);return}let r=EP([rS,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&&yP(this.checkpoint,this.interruptBefore,[r])){this.toInterrupt.push(r);return}this._emit(KM(WM(MP([r]),`tasks`))),this.debug&&zP(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 OS(e)&&!this.isNested}async _first(e){let{configurable:t}=this.config,n=t?.[Vx];if(n&&n.nullResume!==void 0&&this.putWrites(aS,[[Xx,n.nullResume]]),_S(this.input)){let e=this.input.resume!=null;if(this.input.resume!=null&&typeof this.input.resume==`object`&&Object.keys(this.input.resume).every($N)&&(this.config.configurable??={},this.config.configurable[Bx]=this.input.resume),e&&this.checkpointer==null)throw Error(`Cannot use Command(resume=...) without checkpointer`);let t={};for(let[e,n,r]of nP(this.input,this.checkpointPendingWrites))t[e]??=[],t[e].push([n,r]);if(Object.keys(t).length===0)throw new kS(`Received empty Command input`);for(let[e,n]of Object.entries(t))this.putWrites(e,n)}let r=(this.checkpointPendingWrites??[]).filter(e=>e[0]===aS).map(e=>e.slice(1));r.length>0&&CP(this.checkpoint,this.channels,[{name:kx,writes:r,triggers:[]}],this.checkpointerGetNextVersion,this.triggerToNodes);let i=_S(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[Yx]={...this.checkpoint.versions_seen[Yx],[e]:t}}let e=await GM(WM(iP(this.outputKeys,!0,this.channels),`values`));this.isResuming?this.input=QP:i&&(await this._putCheckpoint({source:`input`}),this.input=ZP),this._emitValuesWithCheckpointMeta(e)}else{let t=await GM(rP(e,this.input));if(t.length>0){let e=TP(this.checkpoint,this.checkpointPendingWrites,this.nodes,this.channels,this.config,!0,{step:this.step});this.updatedChannels=CP(this.checkpoint,this.channels,Object.values(e).concat([{name:kx,writes:t,triggers:[]}]),this.checkpointerGetNextVersion,this.triggerToNodes),await this._putCheckpoint({source:`input`}),this.input=ZP}else if(`__pregel_resuming`in(this.config.configurable??{}))this.input=ZP;else throw new kS(`Received no input writes for ${JSON.stringify(e,null,2)}`)}this.isNested||(this.config=lP(this.config,{[Ix]:this.isResuming}))}_emit(e){for(let t of e){let[e,n,r]=t;if(this.stream.modes.has(e)&&this.stream.push([this.checkpointNamespace,e,n,r]),(e===`checkpoints`||e===`tasks`)&&this.stream.modes.has(`debug`)){let t=e===`checkpoints`?this.step-1:this.step,r=new Date().toISOString(),i=e===`checkpoints`?`checkpoint`:typeof n==`object`&&n&&`result`in n?`task_result`:`task`;this.stream.push([this.checkpointNamespace,`debug`,{step:t,type:i,timestamp:r,payload:n}])}}}_currentCheckpointMeta(){if(!this.checkpointMetadata||!this.checkpoint?.id)return;let e=this.prevCheckpointConfig?.configurable?.checkpoint_id;return{checkpoint:{id:this.checkpoint.id,...e?{parent_id:e}:{},step:this.checkpointMetadata.step,source:this.checkpointMetadata.source}}}_emitValuesWithCheckpointMeta(e){let t=this._currentCheckpointMeta();if(!t){this._emit(e);return}this._emit(e.map(([e,n])=>e===`values`?[e,n,t]:[e,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=lP(this.checkpointConfig,{[Gx]:this.config.configurable?.checkpoint_ns??``});let t={...this.checkpoint.channel_versions},n=sP(this.checkpointPreviousVersions,t);this.checkpointPreviousVersions=t,this._checkpointerPutAfterPrevious({config:{...this.checkpointConfig},checkpoint:dM(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=EM(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=lP(this.checkpointConfig,{[Gx]:this.config.configurable?.checkpoint_ns??``,[Wx]: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 rF(e){return mt(e?.message)}function iF(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 aF=class extends yr{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&&(xt(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]=iF(o,a,s))}handleLLMNewToken(e,t,n,r,i,a){let o=a?.chunk;this.emittedChatModelRunIds[n]=!0,this.metadatas[n]!==void 0&&(rF(o)?this._emit(this.metadatas[n],o.message,n):this._emit(this.metadatas[n],new Zt({content:e}),n))}handleLLMEnd(e,t){if(this.metadatas[t]!==void 0){if(!this.emittedChatModelRunIds[t]){let n=e.generations?.[0]?.[0];mt(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]=iF(a,i,s),typeof t==`object`)){for(let e of Object.values(t))if((mt(e)||ht(e))&&e.id!==void 0)this.seen[e.id]=e;else if(Array.isArray(e))for(let t of e)(mt(t)||ht(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(mt(e))this._emit(n,e,t,!0);else if(Array.isArray(e))for(let r of e)mt(r)&&this._emit(n,r,t,!0);else if(typeof e==`object`&&e){for(let r of Object.values(e))if(mt(r))this._emit(n,r,t,!0);else if(Array.isArray(r))for(let e of r)mt(e)&&this._emit(n,e,t,!0)}}}handleChainError(e,t){delete this.metadatas[t]}};function oF(e){if(`response_metadata`in e&&typeof e.response_metadata==`object`&&e.response_metadata!=null)return e.response_metadata}function sF(e){if(`usage_metadata`in e&&typeof e.usage_metadata==`object`&&e.usage_metadata!=null)return e.usage_metadata}function cF(e){switch(e.type){case`text`:return{type:`text`,text:``};case`reasoning`:return{type:`reasoning`,reasoning:``};case`tool_call`:case`tool_call_chunk`:return{type:`tool_call_chunk`,...e.id==null?{}:{id:e.id},...e.name==null?{}:{name:e.name},args:``};default:return e}}function lF(e){switch(e.type){case`text`:{let t=typeof e.text==`string`?e.text:``;return t.length>0?{event:`content-block-delta`,index:typeof e.index==`number`?e.index:0,delta:{type:`text-delta`,text:t}}:void 0}case`reasoning`:{let t=typeof e.reasoning==`string`?e.reasoning:``;return t.length>0?{event:`content-block-delta`,index:typeof e.index==`number`?e.index:0,delta:{type:`reasoning-delta`,reasoning:t}}:void 0}case`tool_call_chunk`:return{event:`content-block-delta`,index:typeof e.index==`number`?e.index:0,delta:{type:`block-delta`,fields:{...e,type:`tool_call_chunk`}}};default:return}}var uF=class extends yr{name=`StreamProtocolMessagesHandler`;streamFn;metadatas={};seen={};streamedRunIds=new Set;stableMessageIdMap={};lc_prefer_chat_model_stream_events=!0;constructor(e){super(),this.streamFn=e}normalizeMessageId(e,t){let n=e.id;return t!=null&&(vt.isInstance(e)?n??=`run-${t}-tool-${e.tool_call_id}`:((n==null||n===`run-${t}`)&&(n=this.stableMessageIdMap[t]??n??`run-${t}`),this.stableMessageIdMap[t]??=n)),n!==e.id&&(e.id=n,e.lc_kwargs.id=n),e.id!=null&&(this.seen[e.id]=e),e.id}emit(e,t,n){let r=n==null?e[1]:{...e[1],run_id:n};this.streamFn([e[0],`messages`,[t,r]])}emitFinalMessage(e,t,n,r=!1){let i=t.id??(n==null?void 0:this.stableMessageIdMap[n]);if(r&&i!=null&&this.seen[i]!==void 0)return;let a=this.normalizeMessageId(t,n),o=t.type===`human`?`human`:t.type===`system`?`system`:t.type===`tool`?`tool`:`ai`,s=o===`tool`&&vt.isInstance(t)?t.tool_call_id:void 0;this.emit(e,{event:`message-start`,...a==null?{}:{id:a},...o===`ai`?{}:{role:o},...typeof s==`string`?{tool_call_id:s}:{}},n),(Array.isArray(t.content)?t.content:typeof t.content==`string`&&t.content.length>0?[{type:`text`,text:t.content}]:[]).forEach((t,r)=>{let i=typeof t.index==`number`?t.index:r;this.emit(e,{event:`content-block-start`,index:i,content:cF(t)},n);let a=lF({...t,index:i});a!=null&&this.emit(e,a,n),this.emit(e,{event:`content-block-finish`,index:i,content:t},n)}),this.emit(e,{event:`message-finish`,...sF(t)==null?{}:{usage:sF(t)},...oF(t)==null?{}:{responseMetadata:oF(t)}},n)}handleChatModelStart(e,t,n,r,i,a,o,s){o&&(!a||!a.includes(`langsmith:nostream`)&&!a.includes(`nostream`))&&(this.metadatas[n]=[o.langgraph_checkpoint_ns.split(`|`),{tags:a,name:s,...o}])}handleLLMNewToken(){}handleChatModelStreamEvent(e,t){let n=this.metadatas[t];if(n===void 0)return;let r=e;if(e.event===`message-start`){this.streamedRunIds.add(t);let n=e.id??`run-${t}`;this.seen[n]=!0,this.stableMessageIdMap[t]??=n,e.id??(r={...e,id:n})}this.emit(n,r,t)}handleLLMEnd(e,t){let n=this.metadatas[t];if(n===void 0)return;let r=e.generations?.[0]?.[0],i=nt.isInstance(r?.message)?r.message:void 0;if(i!=null)if(this.streamedRunIds.has(t)){let e=this.normalizeMessageId(i,t);e!=null&&(this.seen[e]=i)}else this.emitFinalMessage(n,i,t,!0);this.streamedRunIds.delete(t),delete this.metadatas[t],delete this.stableMessageIdMap[t]}handleLLMError(e,t){this.streamedRunIds.delete(t),delete this.metadatas[t],delete this.stableMessageIdMap[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]=[a.langgraph_checkpoint_ns.split(`|`),{tags:i,name:s,...a}],typeof t==`object`)){for(let e of Object.values(t))if((nt.isInstance(e)||ft.isInstance(e))&&e.id!==void 0)this.seen[e.id]=e;else if(Array.isArray(e))for(let t of e)(nt.isInstance(t)||ft.isInstance(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)return;let r=e=>{nt.isInstance(e)&&!vt.isInstance(e)&&this.emitFinalMessage(n,e,t,!0)};if(nt.isInstance(e))r(e);else if(Array.isArray(e))for(let t of e)r(t);else if(typeof e==`object`&&e)for(let t of Object.values(e))if(Array.isArray(t))for(let e of t)r(e);else r(t);delete this.stableMessageIdMap[t]}handleChainError(e,t){delete this.metadatas[t],delete this.stableMessageIdMap[t]}},dF=[400,401,402,403,404,405,406,407,409],fF=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&&dF.includes(+t)||e?.error?.code===`insufficient_quota`)};async function pF(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=lP(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,ES(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===gS.PARENT){let e=HM(t);s.command=new gS({...s.command,graph:e})}}if(DS(s)||i===void 0||(o+=1,o>=(i.maxAttempts??3))||!(i.retryOn??fF)(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=lP(l,{[Ix]:!0}),l.executionInfo!=null&&(l.executionInfo={...l.executionInfo,nodeAttempt:o+1,nodeFirstAttemptTime:u})}}return{task:e,result:c,error:s,signalAborted:r?.aborted}}var mF=Symbol.for(`promiseAdded`);function hF(){let e={next:()=>void 0,wait:Promise.resolve(mF)};function t(n){e.next=()=>{e.wait=new Promise(t),n(mF)}}return e.wait=new Promise(t),e}var gF=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),OS(t)||DS(t)&&!OS(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(OS(o)||DS(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}=dP(i,a,e),c={externalAbortSignal:i,timeoutAbortSignal:a,composedAbortSignal:o};return this.loop.config=lP(this.loop.config,{[Jx]:c}),{signals:c,disposeCombinedSignal:s}}async*_executeTasksWithRetry(e,t){let{retryPolicy:n,maxConcurrency:r,signals:i}=t??{},a=hF(),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=dP(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]=pF(t,n,{[Nx]:_F?.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!==mF&&(yield t,l!=null&&(u.signal?.removeEventListener(`abort`,l),u.dispose?.()),delete o[t.task.id])}}_commit(e,t){if(t!==void 0)if(OS(t)){if(t.interrupts.length){let n=t.interrupts.map(e=>[Yx,e]),r=e.writes.filter(e=>e[0]===Xx);r.length&&n.push(...r),this.loop.putWrites(e.id,n)}}else DS(t)&&e.writes.length?this.loop.putWrites(e.id,e.writes):this.loop.putWrites(e.id,[[Ax,{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([Zx,null]),this.loop.putWrites(e.id,e.writes)}};async function _F(e,t,n,r,i,a={}){let o=t.config?.configurable?.[Vx];if(!o)throw Error(`BUG: No scratchpad found on task ${t.name}__${t.id}`);let s=o.callCounter;o.callCounter+=1;let c=new pP({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===Qx),t=l.writes.filter(([e])=>e===Ax);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=pF(l,a.retry,{[Nx]:_F.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 vF=[`values`,`updates`,`messages`,`tools`,`custom`,`tasks`];function yF(e){if(!Array.isArray(e)||e.length!==2)return{data:e};let[t,n]=e;if(typeof n!=`object`||!n)return{data:e};let r=n,i=typeof r.langgraph_node==`string`?r.langgraph_node:void 0,a=typeof r.run_id==`string`?r.run_id:void 0;return{data:a!=null&&typeof t==`object`&&t?{...t,run_id:a}:t,node:i}}function bF({namespace:e,mode:t,payload:n,seq:r,meta:i}){let a=Date.now(),o={type:`event`};switch(t){case`messages`:{let{data:t,node:i}=yF(n);return[{...o,seq:r,method:`messages`,params:{namespace:e,timestamp:a,...i?{node:i}:{},data:t}}]}case`tools`:return[{...o,seq:r,method:`tools`,params:{namespace:e,timestamp:a,data:xF(n)}}];case`values`:{let t=[];return i?.checkpoint!=null&&t.push({...o,seq:r,method:`checkpoints`,params:{namespace:e,timestamp:a,data:i.checkpoint}}),t.push({...o,seq:i?.checkpoint==null?r:r+1,method:`values`,params:{namespace:e,timestamp:a,data:n}}),t}case`updates`:{let t=SF(n);return[{...o,seq:r,method:`updates`,params:{namespace:e,timestamp:a,...typeof t.node==`string`?{node:t.node}:{},data:t}}]}case`custom`:{let t=typeof n==`object`&&n&&!Array.isArray(n)&&`name`in n?n:{payload:n};return[{...o,seq:r,method:`custom`,params:{namespace:e,timestamp:a,data:t}}]}case`tasks`:return[{...o,seq:r,method:`tasks`,params:{namespace:e,timestamp:a,data:n}}];default:return[]}}function xF(e){if(typeof e!=`object`||!e)return{event:`tool-error`,tool_call_id:``,message:`Unexpected tools payload shape`};let t=e,n=String(t.toolCallId??``);switch(t.event){case`on_tool_start`:return{event:`tool-started`,tool_call_id:n,tool_name:String(t.name??`unknown`),input:t.input};case`on_tool_event`:return{event:`tool-output-delta`,tool_call_id:n,delta:typeof t.data==`string`?t.data:JSON.stringify(t.data??``)};case`on_tool_end`:return{event:`tool-finished`,tool_call_id:n,output:t.output};case`on_tool_error`:{let e=t.error;return{event:`tool-error`,tool_call_id:n,message:typeof e==`object`&&e&&`message`in e&&typeof e.message==`string`?e.message:String(e??`unknown error`)}}default:return{event:`tool-error`,tool_call_id:``,message:`Unknown tool event: ${String(t.event)}`}}}function SF(e){if(typeof e!=`object`||!e)return{values:{}};let t=Object.entries(e);if(t.length===0)return{values:{}};let[n,r]=t[0];return{node:n,values:typeof r==`object`&&r?r:{value:r}}}var CF=Symbol.for(`langgraph.stream_channel`),wF=class e{[CF]=!0;channelName;#e=[];#t=[];#n=!1;#r;#i;constructor(e){this.channelName=e}static local(){return new e}static remote(t){return new e(t)}static isInstance(e){return typeof e==`object`&&!!e&&CF in e&&e[CF]===!0}push(e){this.#e.push(e),this.#a(),this.#i?.(e)}iterate(e=0){let t=e;return{next:async()=>{for(;;){if(t<this.#e.length)return{value:this.#e[t++],done:!1};if(this.#n){if(this.#r)throw this.#r;return{value:void 0,done:!0}}await new Promise(e=>this.#t.push(e))}}}}toAsyncIterable(e=0){return{[Symbol.asyncIterator]:()=>this.iterate(e)}}toEventStream(e={}){let t=new TextEncoder,n=this.iterate(e.startAt),r=e.event??this.channelName,i=e.serialize??(e=>JSON.stringify(e)??`null`);return new ReadableStream({async pull(e){try{let a=await n.next();if(a.done){e.close();return}let o=[];r!=null&&o.push(`event: ${r}`);for(let e of i(a.value).split(/\r\n|\r|\n/))o.push(`data: ${e}`);e.enqueue(t.encode(`${o.join(`
187
+ `)}\n\n`))}catch(t){e.error(t)}},async cancel(){await n.return?.()}})}get(e){if(e<0||e>=this.#e.length)throw RangeError(`StreamChannel index ${e} out of bounds (size=${this.#e.length})`);return this.#e[e]}get size(){return this.#e.length}get done(){return this.#n}close(){this.#n=!0,this.#a()}fail(e){this.#r=e,this.#n=!0,this.#a()}_wire(e){this.#i=e}_close(){this.close()}_fail(e){this.fail(e)}[Symbol.asyncIterator](){return this.iterate()}#a(){let e=this.#t.splice(0);for(let t of e)t()}};function TF(e){return wF.isInstance(e)}function EF(e){return e!=null&&(typeof e==`object`||typeof e==`function`)&&typeof e.then==`function`}var DF=Symbol(`resolveValues`),OF=Symbol(`rejectValues`),kF=class{_events=wF.local();_discoveries=wF.local();#e=0;#t=!1;#n;#r=!1;#i=[];#a=[];#o=[];#s=new Map;#c=new Map;#l=[];#u=[];register(e,t){this.#s.set(jF(e),t)}addTransformer(e){let t=this._events.size;this.#a.push(e),e.onRegister&&e.onRegister({push:(e,t)=>this.push(e,t)});for(let n=0;n<t;n+=1)e.process(this._events.get(n));this.#t&&(this.#n===void 0?e.finalize?.():e.fail?.(this.#n))}wireChannels(e){for(let[t,n]of Object.entries(e)){if(TF(n)){if(this.#o.push(n),typeof n.channelName!=`string`)continue;n._wire(e=>{this._events.push({type:`event`,seq:this.#e++,method:n.channelName,params:{namespace:this.#i,timestamp:Date.now(),data:e}})});continue}EF(n)&&this.#u.push({name:t,promise:Promise.resolve(n)})}}push(e,t){t.method===`values`&&this.#c.set(jF(e),t.params.data);let n=this.#i;this.#i=e;let r=!0;for(let e of this.#a)e.process(t)||(r=!1);this.#i=n,r&&this._events.push({...t,seq:this.#e++})}close(){this.#t=!0;for(let[e,t]of this.#c.entries()){let n=e?e.split(`\0`):[];this.#s.get(jF(n))?.[DF](t)}let e=[];for(let t of this.#a){let n=t.finalize?.();n!=null&&typeof n.then==`function`&&e.push(n)}for(let e of this.#o)e._close();let t=this.#u;t.length===0&&e.length===0?(this._events.close(),this._discoveries.close()):Promise.allSettled([...e,...t.map(async({name:e,promise:t})=>{try{let n=await t;this._events.done||this._events.push({type:`event`,seq:this.#e++,method:`custom`,params:{namespace:[],timestamp:Date.now(),data:{name:e,payload:n}}})}catch{}})]).then(()=>{this._events.close(),this._discoveries.close()});for(let e of this.#s.values())e[DF](void 0)}fail(e){this.#t=!0,this.#n=e;for(let t of this.#a)t.fail?.(e);for(let t of this.#o)t._fail(e);this._events.fail(e),this._discoveries.fail(e);for(let t of this.#s.values())t[OF](e)}markInterrupted(e){this.#r=!0,this.#l.push(...e)}get interrupted(){return this.#r}get interrupts(){return this.#l}subscribeEvents(e,t=0){let n=this._events.iterate(t);return{async next(){for(;;){let t=await n.next();if(t.done||MF(t.value.params.namespace,e))return t}}}}};async function AF(e,t){let n=0;try{for await(let r of e){let[e,i,a,o]=r;if(i===`values`&&hS(a)){let e=a[Yx];t.markInterrupted(e.map(e=>({interruptId:e.id??``,payload:e.value})))}let s=bF({namespace:e,mode:i,payload:a,seq:n,meta:o});n+=s.length;for(let n of s)t.push(e,n)}}catch(e){t.fail(e);return}t.close()}function jF(e){return e.join(`\0`)}function MF(e,t){if(t.length>e.length)return!1;for(let n=0;n<t.length;n+=1)if(e[n]!==t[n])return!1;return!0}function NF(e,t,n=0){return{[Symbol.asyncIterator](){let r=e.iterate(n);return{async next(){for(;;){let e=await r.next();if(e.done)return{value:void 0,done:!0};if(MF(e.value.namespace,t))return{value:e.value,done:!1}}}}}}}var PF=`root`;function FF(e){if(e.length===0)return PF;let t=e[e.length-1],n=t.indexOf(`:`);return n===-1?t:t.slice(0,n)}function IF(e){if(e instanceof Error)return e.message;if(typeof e==`string`)return e;try{return JSON.stringify(e)}catch{return String(e)}}function LF(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function RF(e){if(!LF(e)||e.event!==`started`)return;let t=e.cause;if(LF(t)&&typeof t.type==`string`)return t}function zF(e){if(LF(e)&&`result`in e&&typeof e.name==`string`&&typeof e.id==`string`&&!e.name.startsWith(`__`))return{name:e.name,id:e.id}}function BF(e={}){let t=e.rootGraphName??PF,n=e.initialStatus??`running`,r=e.emitRootOnRegister??!0,i=e.getGraphName??FF,a=e.serializeError??IF,o=e.getTerminalStatusOverride,s=wF.local(),c=new Map,l=new Map,u=new Set,d=[],f,p=0,m=!1,h=e=>e.length===0?t:i(e),g=(e,t,n)=>{let i=jF(e),a=c.get(i),o=a?.graphName??h(e);if(a!=null&&a.status===t&&a.graphName===o&&n?.error==null)return;a==null?(a={namespace:e,graphName:o,status:t},c.set(i,a)):a.status=t;let l={event:t,graph_name:o,...n?.cause==null?{}:{cause:n.cause},...n?.error==null?{}:{error:n.error}},u=Date.now();if(s.push({namespace:e,timestamp:u,...l}),!(e.length===0&&!r)&&f!=null){p+=1;try{f.push(e,{type:`event`,seq:0,method:`lifecycle`,params:{namespace:e,timestamp:u,data:l}})}finally{--p}}},_=e=>{let t=jF(e),n=c.get(t);return n??(n={namespace:e,graphName:h(e),status:void 0},c.set(t,n)),n},v=()=>{if(d.length===0)return;let e=d.splice(0,d.length);for(let t of e){let e=jF(t.namespace),n=c.get(e);n==null||n.status!==`started`||g(t.namespace,`completed`)}},y=e=>{let t=jF(e.namespace),n=c.get(t);n==null||n.status!==`started`||d.some(e=>jF(e.namespace)===t)||d.push(e)},b=(e,t)=>{for(let n=d.length-1;n>=0;--n){let r=d[n];r.source.type===`node`&&r.source.node===t&&jF(r.source.parent)===jF(e)&&d.splice(n,1)}},ee=e=>{for(let t=1;t<=e.length;t+=1){let n=e.slice(0,t),r=jF(n);if(c.has(r))continue;_(n);let i=l.get(r);g(n,`started`,i==null?void 0:{cause:i})}},te=()=>u.size>0?`interrupted`:`completed`,ne=e=>{for(let t of c.values())t.namespace.length!==0&&t.status===`started`&&g(t.namespace,e);g([],e),s.close()},x=async()=>{if(o==null)return te();try{return await o()??te()}catch{return te()}},re=(e,t)=>{let n=`${t}:`;for(let r of c.values()){if(r.namespace.length!==e.length+1||r.status!==`started`||!MF(r.namespace,e))continue;let i=r.namespace[r.namespace.length-1];if(i===t||i.startsWith(n))return r.namespace}},ie=(e,t)=>{let n=[...e,`${t.name}:${t.id}`];return c.get(jF(n))?.status===`started`?n:void 0};return{__native:!0,init(){return{_lifecycleLog:s,lifecycle:NF(s,[],0)}},onRegister(e){f=e,_([]),r&&g([],n)},process(e){let t=e.params.namespace;if(p>0)return!0;let n=e.method===`tasks`?zF(e.params.data):void 0;if(n!=null&&b(t,n.name),v(),e.method===`lifecycle`){let n=RF(e.params.data);return n!=null&&l.set(jF(t),n),ee(t),!1}if(ee(t),e.method===`input`&&LF(e.params.data)&&e.params.data.event===`requested`){let t=e.params.data.id;typeof t==`string`&&u.add(t)}if(n!=null){let e=ie(t,n);e!=null&&y({namespace:e,source:{type:`task`}})}if(e.method===`updates`){let n=e.params.node;if(typeof n==`string`&&!n.startsWith(`__`)){let e=re(t,n);e!=null&&y({namespace:e,source:{type:`node`,parent:t,node:n}})}}return!0},finalize(){if(!m){if(m=!0,v(),o==null){ne(te());return}return x().then(ne).catch(e=>{s.fail(e)})}},fail(e){if(m)return;m=!0;let t=a(e);for(let e of c.values())e.namespace.length!==0&&e.status===`started`&&g(e.namespace,`failed`);g([],`failed`,{error:t}),s.fail(e)}}}function VF(e){let t=e;return typeof t.run_id==`string`?`run:${t.run_id}`:e.event===`message-start`&&typeof t.id==`string`?`message:${t.id}`:`__default__`}function HF(e,t){let n=wF.local(),r=new Map,i=new Set;return{init:()=>({messages:n.toAsyncIterable()}),process(a){if(a.method!==`messages`||!MF(a.params.namespace,e)||a.params.namespace.length!==e.length+1||t!==void 0&&a.params.node!==t)return!0;let o=a.params.data;switch(o.event){case`message-start`:{let e=VF(o);if(o.role===`tool`){i.add(e);break}let t=wF.local(),s=Object.assign(new GT(t.toAsyncIterable()),{namespace:a.params.namespace,node:a.params.node});r.set(e,{source:t,stream:s}),t.push(o),n.push(s);break}case`content-block-start`:case`content-block-delta`:case`content-block-finish`:if(i.has(VF(o)))break;r.get(VF(o))?.source.push(o);break;case`message-finish`:{let e=VF(o);if(i.delete(e))break;let t=r.get(e);t&&(t.source.push(o),t.source.close(),r.delete(e));break}case`error`:if(i.has(VF(o)))break;r.get(VF(o))?.source.push(o);break}return!0},finalize(){for(let[e,t]of r)t.source.push({event:`message-finish`}),t.source.close(),r.delete(e);i.clear(),n.close()},fail(e){for(let[t,n]of r)n.source.fail(e),r.delete(t);i.clear(),n.fail(e)}}}function UF(e,t,n=0){let r=t.length+1;return{[Symbol.asyncIterator](){let i=e.iterate(n);return{async next(){for(;;){let e=await i.next();if(e.done)return{value:void 0,done:!0};let{ns:n,stream:a}=e.value;if(n.length===r&&MF(n,t))return{value:a,done:!1}}}}}}}function WF(e,t){let{createStream:n}=t,r=new Set;return{__native:!0,init(){return{_discoveries:e._discoveries,subgraphs:UF(e._discoveries,[],0)}},process(t){let i=t.params.namespace;if(i.length===0)return!0;let a=i.slice(0,1),o=jF(a);if(r.has(o))return!0;r.add(o);let s=n(a,e._discoveries.size,e._events.size);return e.register(a,s),e._discoveries.push({ns:a,stream:s}),!0}}}function GF(e){let t=wF.local();return{init:()=>({_valuesLog:t}),process(n){return n.method!==`values`||n.params.namespace.length!==e.length||!MF(n.params.namespace,e)||t.push(n.params.data),!0},finalize(){t.close()},fail(e){t.fail(e)}}}function KF(e){return`__native`in e&&e.__native===!0}var qF=Symbol(`setValuesLog`),JF=Symbol(`setMessagesIterable`),YF=Symbol(`setLifecycleIterable`),XF=Symbol(`setSubgraphsIterable`),ZF={[Symbol.asyncIterator](){return{next:()=>Promise.resolve({value:void 0,done:!0})}}},QF=class{path;extensions;_mux;#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;constructor(e,t,n=0,r=0,i,a){this.path=e,this._mux=t,this.#t=n,this.#e=r,this.extensions=i??{},this.#n=a??new AbortController,this.#a=new Promise((e,t)=>{this.#r=e,this.#i=t}),this.#a.catch(()=>{})}[Symbol.asyncIterator](){return this._mux.subscribeEvents(this.path,this.#e)}get subgraphs(){return this.#l?this.#l:UF(this._mux._discoveries,this.path,this.#t)}get values(){let e=this.#o,t=this.#a,n=this._mux,r=this.#e,i=this.path,a=e?e.toAsyncIterable():{[Symbol.asyncIterator]:()=>{let e=n.subscribeEvents(i,r);return{async next(){for(;;){let t=await e.next();if(t.done)return{value:void 0,done:!0};if(t.value.method===`values`&&t.value.params.namespace.length===i.length)return{value:t.value.params.data,done:!1}}}}}};return{[Symbol.asyncIterator]:()=>a[Symbol.asyncIterator](),then:t.then.bind(t)}}get messages(){if(this.#s)return this.#s;let e=HF(this.path),t=e.init();return this._mux.addTransformer(e),this.#s=t.messages,this.#s}get lifecycle(){return this.#c??ZF}messagesFrom(e){let t=HF(this.path,e),n=t.init();return this._mux.addTransformer(t),n.messages}get output(){return this.#a}get interrupted(){return this._mux.interrupted}get interrupts(){return this._mux.interrupts}abort(e){this.#n.abort(e)}get signal(){return this.#n.signal}[DF](e){this.#r?.(e),this.#r=void 0}[OF](e){this.#i?.(e),this.#i=void 0}[qF](e){this.#o=e}[JF](e){this.#s=e}[YF](e){this.#c=e}[XF](e){this.#l=e}},$F=class extends QF{name;index;constructor(e,t,n=0,r=0,i,a){super(e,t,n,r,i,a);let o=e[e.length-1]??``,s=o.lastIndexOf(`:`);if(s>=0){this.name=o.slice(0,s);let e=o.slice(s+1);this.index=/^\d+$/.test(e)?Number(e):0}else this.name=o,this.index=0}};function eI(e,t=[],n){let{abortController:r}=n instanceof AbortController?{abortController:n}:n??{},i=new kF,a=BF(),o=a.init(),s=o._lifecycleLog,c=WF(i,{createStream:(e,t,n)=>{let r=new $F(e,i,t,n);return r[XF](UF(i._discoveries,e,t)),r[YF](NF(s,e,s.size)),r}}),l=c.init();i.addTransformer(c),i.addTransformer(a);let u=GF([]),d=HF([]);i.addTransformer(u),i.addTransformer(d);let f={},p=[];for(let e of t){let t=e();i.addTransformer(t);let n=t.init();KF(t)?p.push(n):Object.assign(f,n),typeof n==`object`&&n&&!KF(t)&&i.wireChannels(n)}let m=new QF([],i,0,0,f,r);for(let e of p)Object.assign(m,e);let h=u.init();m[qF](h._valuesLog);let g=d.init();return m[JF](g.messages),m[YF](o.lifecycle),m[XF](l.subgraphs),i.register([],m),AF(e,i).catch(e=>{}),m}var tI=class extends Error{constructor(e){super(e),this.name=`GraphValidationError`}};function nI({nodes:e,channels:t,inputChannels:n,outputChannels:r,streamChannels:i,interruptAfterNodes:a,interruptBeforeNodes:o}){if(!t)throw new tI(`Channels not provided`);let s=new Set,c=new Set;for(let[t,n]of Object.entries(e)){if(t===`__interrupt__`)throw new tI(`"Node name ${Yx} is reserved"`);if(n.constructor===rN)n.triggers.forEach(e=>s.add(e));else throw new tI(`Invalid node type ${typeof n}, expected PregelNode`)}for(let e of s)if(!(e in t))throw new tI(`Subscribed channel '${String(e)}' not in channels`);if(!Array.isArray(n)){if(!s.has(n))throw new tI(`Input channel ${String(n)} is not subscribed to by any node`)}else if(n.every(e=>!s.has(e)))throw new tI(`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 tI(`Output channel '${String(e)}' not in channels`);if(a&&a!==`*`){for(let t of a)if(!(t in e))throw new tI(`Node ${String(t)} not in nodes`)}if(o&&o!==`*`){for(let t of o)if(!(t in e))throw new tI(`Node ${String(t)} not in nodes`)}}function rI(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 iI=class e extends SM{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 AS;return this.values}checkpoint(){return[[...this.seen],this.values]}isAvailable(){return this.values.length!==0}};function aI(e){let t=wl.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 SS(`No checkpointer set`,{lc_error_code:`MISSING_CHECKPOINTER`});let r=n[Vx];r.interruptCounter+=1;let i=r.interruptCounter;if(r.resume.length>0&&i<r.resume.length)return n[Mx]?.([[Xx,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[Mx]?.([[Xx,r.resume]]),e}let a=n[Gx]?.split(`|`);throw new CS([{id:a?QN(a.join(`|`)):void 0,value:e}])}function oI(e){let t=new TextEncoder;return new ReadableStream({async start(n){try{for await(let r of e){let e=r.params.namespace,i=e.length?`${r.method}|${e.join(`|`)}`:r.method;n.enqueue(t.encode(`event: ${i}\ndata: ${JSON.stringify(r.params.data??{})}\n\n`))}}catch(e){n.enqueue(t.encode(`event: error\ndata: ${JSON.stringify({message:String(e)})}\n\n`))}finally{n.close()}}})}var sI=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 rN({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:YM,skipNone:!1});for(let[e,r]of Object.entries(t??{}))Ub.isRunnable(r)||typeof r==`function`?n.push({channel:e,value:YM,skipNone:!0,mapper:ex(r)}):n.push({channel:e,value:r,skipNone:!1});return new QM(n)}},cI=class extends Ub{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)}},lI=class extends cI{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;streamTransformers;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 '${nS}' is reserved and cannot be used in the graph.`);this.channels[nS]=new iI({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.streamTransformers=e.streamTransformers??[],this.autoValidate&&this.validate()}withConfig(e){let{streamTransformers:t,...n}=e,r=Al(this.config,n),i=[...this.streamTransformers,...t??[]];return new this.constructor({...this,config:r,streamTransformers:i})}validate(){nI({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=oN(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=TM(this.channels,t.checkpoint);if(t.pendingWrites?.length){let e=t.pendingWrites.filter(([e,t])=>e===aS).map(([e,t,n])=>[String(t),n]);e.length>0&&CP(t.checkpoint,i,[{name:kx,writes:e,triggers:[]}],void 0,this.triggerToNodes)}let a=Object.values(TP(t.checkpoint,t.pendingWrites,this.nodes,i,t.config,!0,{step:(t.metadata?.step??-1)+1,store:this.store})),o=await GM(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:{[Fx]: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&&CP(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:tP(i,this.streamChannelsAsIs),next:u,tasks:LP(a,t?.pendingWrites??[],c,this.streamChannelsAsIs),metadata:l,config:uP(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 SS(`No checkpointer set`,{lc_error_code:`MISSING_CHECKPOINTER`});let r=e.configurable?.checkpoint_ns??``;if(r!==``&&e.configurable?.__pregel_checkpointer===void 0){let i=VM(r);for await(let[r,a]of this.getSubgraphsAsync(i,!0))if(r===i)return await a.getState(qM(e,{[Fx]:n}),{subgraphs:t?.subgraphs})}let i=Al(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 SS(`No checkpointer set`,{lc_error_code:`MISSING_CHECKPOINTER`});let r=e.configurable?.checkpoint_ns??``;if(r!==``&&e.configurable?.__pregel_checkpointer===void 0){let i=VM(r);for await(let[r,a]of this.getSubgraphsAsync(i,!0))if(r===i){yield*a.getStateHistory(qM(e,{[Fx]:n}),t);return}}let i=Al(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 SS(`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=VM(r);for await(let[,r]of this.getSubgraphsAsync(i,!0))return await r.bulkUpdateState(qM(e,{[Fx]:n}),t);throw Error(`Subgraph "${i}" not found`)}let i=async(e,t)=>{let r=this.config?Al(this.config,e):e,a=await n.getTuple(r),o=a===void 0?uM():dM(a.checkpoint),s={...a?.checkpoint.channel_versions},c=a?.metadata?.step??-1,l=qM(r,{checkpoint_ns:r.configurable?.checkpoint_ns??``}),u=r.metadata??{};a?.config.configurable&&(l=qM(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 jS(`Cannot create empty checkpoint with multiple updates`);return uP(await n.put(l,EM(o,void 0,c),{source:`update`,step:c+1,parents:a?.metadata?.parents??{}},{}),a?a.metadata:void 0)}let p=TM(this.channels,o);if(d===null&&f===`__end__`){if(t.length>1)throw new jS(`Cannot apply multiple updates when clearing state`);if(a){let e=TP(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]===aS).map(e=>e.slice(1));t.length>0&&CP(o,p,[{name:kx,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]);CP(o,p,Object.values(e),n.getNextVersion.bind(n),this.triggerToNodes)}return uP(await n.put(l,EM(o,p,c),{...u,source:`update`,step:c+1,parents:a?.metadata?.parents??{}},sP(s,o.channel_versions)),a?a.metadata:void 0)}if(f===`__copy__`){if(t.length>1)throw new jS(`Cannot copy checkpoint with multiple updates`);if(a==null)throw new jS(`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=EM(o,void 0,c),s=await n.put(a.parentConfig??qM(a.config,{checkpoint_id:void 0}),r,{source:`fork`,step:c+1,parents:a.metadata?.parents??{}},{});if(e(d)){let e=TP(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(uP(s,a.metadata),Object.values(n).flat())}return uP(s,a.metadata)}if(f===`__input__`){if(t.length>1)throw new jS(`Cannot apply multiple updates when updating as input`);let e=await GM(rP(this.inputChannels,d));if(e.length===0)throw new jS(`Received no input writes for ${JSON.stringify(this.inputChannels,null,2)}`);CP(o,p,[{name:kx,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,EM(o,p,r),{source:`input`,step:r,parents:a?.metadata?.parents??{}},sP(s,o.channel_versions));return await n.putWrites(i,e,dC(kx,o.id)),uP(i,a?a.metadata:void 0)}if(r.configurable?.checkpoint_id===void 0&&a?.pendingWrites!==void 0&&a.pendingWrites.length>0){let e=TP(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]===aS).map(e=>e.slice(1));t.length>0&&CP(a.checkpoint,p,[{name:kx,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&&CP(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!==Yx).sort(([e],[t])=>fM(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 jS(`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 jS(`"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 jS(`Node "${e.toString()}" does not exist`);let r=this.nodes[e].getWriters();if(!r.length)throw new jS(`No writers found for node "${e.toString()}"`);g.push({name:e,input:t,proc:r.length>1?qb.from(r,{omitSequenceTags:!0}):r[0],writes:[],triggers:[Yx],id:n??dC(`__interrupt__`,o.id),writers:[]})}for(let e of g)await e.proc.invoke(e.input,Ml({...r,store:r?.store??this.store},{runName:r.runName??`${this.getName()}UpdateState`,configurable:{[Mx]:t=>e.writes.push(...t),[Px]:(t,n=!1)=>bP(o,p,e,t,n)}}));for(let e of g){let t=e.writes.filter(e=>e[0]!==rS);a!==void 0&&t.length>0&&await n.putWrites(l,t,e.id)}CP(o,p,g,n.getNextVersion.bind(this.checkpointer),this.triggerToNodes);let _=sP(s,o.channel_versions),v=await n.put(l,EM(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]===rS);t.length>0&&await n.putWrites(v,t,e.id)}return uP(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:rI(u,this.channels);let d=r;d===void 0?d=this.inputChannels:rI(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[Fx];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:dP(t?.signal,n.signal).signal},i=await super.stream(e,r);return new VP(t?.encoding===`text/event-stream`?XP(i):i,n)}async#e(e,t){let{version:n,encoding:r,transformers:i,...a}=t,o={recursionLimit:this.config?.recursionLimit,...a,configurable:{...this.config?.configurable,...a?.configurable},version:n,streamMode:vF,subgraphs:!0,encoding:void 0},s=this.stream(e,o),c=eI({[Symbol.asyncIterator]:async function*(){let e=await s;for await(let t of e)yield t}},[...this.streamTransformers??[],...i??[]]);if(r===`text/event-stream`){let e=new AbortController;return e.signal.addEventListener(`abort`,()=>c.abort(e.signal.reason),{once:!0}),new VP(oI(c),e)}return c}streamEvents(e,t,n){if(t.version===`v3`)return this.#e(e,t);let r=new AbortController,i={recursionLimit:this.config?.recursionLimit,...t,callbacks:fP(this.config?.callbacks,t?.callbacks),signal:dP(t?.signal,r.signal).signal};return new VP(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=zM(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 HP({modes:new Set(l)});if(this.checkpointer===!0){d.configurable??={};let e=d.configurable.checkpoint_ns??``;d.configurable[Gx]=e.split(`|`).map(e=>e.split(`:`)[0]).join(`|`)}if(l.includes(`messages`)){let e=t?.version===`v3`?new uF(e=>y.push(e)):new aF(e=>y.push(e)),{callbacks:n}=d;if(n===void 0)d.callbacks=[e];else if(Array.isArray(n))d.callbacks=n.concat(e);else{let t=n.copy();t.addHandler(e,!0),d.callbacks=t}}if(l.includes(`tools`)){let e=new UP(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=(BM()?.configurable?.[Gx])?.split(`|`).slice(0,-1);y.push([t??[],`custom`,e])},d.interrupt??=this.userInterrupt??aI,d.serverInfo??=uI(d);let b={tracerInheritableMetadata:pI(d)},ee=await(await yl._configureSync(d?.callbacks,void 0,d?.tags,void 0,d?.metadata,void 0,b))?.handleChainStart(this.toJSON(),cP(e,`input`),o,void 0,void 0,void 0,d?.runName??this.getName()),te=wM(this.channels),ne,x,re=(async()=>{try{ne=await nF.initialize({input:a,config:d,checkpointer:m,nodes:this.nodes,channelSpecs:te,outputKeys:u,streamKeys:this.streamChannelsAsIs,store:h,cache:_,stream:y,interruptAfter:p,interruptBefore:f,manager:ee,debug:this.debug,triggerToNodes:this.triggerToNodes,durability:v});let e=new gF({loop:ne,nodeFinished:d.configurable?.[Kx]});t?.subgraphs&&(ne.config.configurable={...ne.config.configurable,[Rx]:ne.stream}),await this._runLoop({loop:ne,runner:e,debug:c,config:d}),v===`sync`&&await Promise.all(ne?.checkpointerPromises??[])}catch(e){x=e}finally{try{ne&&(await ne.store?.stop(),await ne.cache?.stop()),await Promise.all(ne?.checkpointerPromises??[])}catch(e){x??=e}x?y.error(x):y.close()}})();try{for await(let e of y){if(e===void 0)throw Error(`Data structure error.`);let[t,i,a,o]=e;if(l.includes(i)){if(n===`text/event-stream`){r?yield[t,i,a]:yield[null,i,a];continue}r&&!g?yield o===void 0?[t,i,a]:[t,i,a,o]:g?r?yield[t,a]:yield a:yield[i,a]}}}catch(e){throw await ee?.handleChainError(x),e}finally{await re}await ee?.handleChainEnd(ne?.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`?hS(e)?o.push(e[Yx]):s=e:i.push(e);if(n===`values`){if(o.length>0){let e=o.flat(1);if(s==null)return{[Yx]:e};if(typeof s==`object`)return{...s,[Yx]: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&&RP(t.checkpointMetadata.step,t.channels,this.streamChannelsList),r&&zP(t.step,Object.values(t.tasks)),await n.tick({timeout:this.stepTimeout,retryPolicy:this.retryPolicy,onStepWrite:(e,t)=>{r&&BP(e,t,this.streamChannelsList)},maxConcurrency:i.maxConcurrency,signal:i.signal})}if(t.status===`out_of_steps`)throw new xS([`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 uI(e){let t=e.metadata??{},n=e.configurable??{},r=n.assistant_id??t.assistant_id,i=n.graph_id??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 dI=new Set([`key`,`token`,`secret`,`password`,`auth`]);function fI(e,t){let n=e.toLowerCase(),r=!1;for(let e of dI)if(n.includes(e)){r=!0;break}return e.startsWith(`__`)||!(typeof t==`string`||typeof t==`number`||typeof t==`boolean`)||r}function pI(e){let t=e.configurable;if(!t)return;let n={};for(let[e,r]of Object.entries(t))fI(e,r)||(n[e]=r);return Object.keys(n).length>0?n:void 0}var mI=/^(?:[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 hI(e){return typeof e==`string`&&mI.test(e)}for(var gI=[],_I=0;_I<256;++_I)gI.push((_I+256).toString(16).slice(1));function vI(e,t=0){return(gI[e[t+0]]+gI[e[t+1]]+gI[e[t+2]]+gI[e[t+3]]+`-`+gI[e[t+4]]+gI[e[t+5]]+`-`+gI[e[t+6]]+gI[e[t+7]]+`-`+gI[e[t+8]]+gI[e[t+9]]+`-`+gI[e[t+10]]+gI[e[t+11]]+gI[e[t+12]]+gI[e[t+13]]+gI[e[t+14]]+gI[e[t+15]]).toLowerCase()}var yI,bI=new Uint8Array(16);function xI(){if(!yI&&(yI=typeof crypto<`u`&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!yI))throw Error(`crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported`);return yI(bI)}var SI={randomUUID:typeof crypto<`u`&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function CI(e,t,n){if(SI.randomUUID&&!t&&!e)return SI.randomUUID();e||={};var r=e.random||(e.rng||xI)();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 vI(r)}var wI=class{path;ends;constructor(e){Ub.isRunnable(e.path)?this.path=e.path:this.path=ex(e.path),this.ends=Array.isArray(e.pathMap)?e.pathMap.reduce((e,t)=>(e[t]=t,e),{}):e.pathMap}run(e,t){return QM.registerWriter(new UM({name:`<branch_run>`,trace:!1,func:async(n,r)=>{try{return await this._route(n,r,e,t)}catch(e){throw e.name===wS.unminifiable_name&&console.warn(`[WARN]: 'NodeInterrupt' thrown in conditional edge. This is likely a bug in your graph implementation.
188
+ 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=>dS(e)?e:this.ends[e]):i,a.some(e=>!e))throw Error(`Branch condition returned unknown or null destination`);if(a.filter(dS).some(e=>e.node===`__end__`))throw new jS(`Cannot send a packet to the END node`);return await n(a,t)??e}},TI=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=ex(t);this.nodes[e]={runnable:n,metadata:r?.metadata,subgraphs:aN(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.`),Ub.isRunnable(r.path)||(r.path=ex(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 wI(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(Dx,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,Ox)}compile({checkpointer:e,interruptBefore:t,interruptAfter:n,name:r,transformers:i}={}){this.validate([...Array.isArray(t)?t:[],...Array.isArray(n)?n:[]]);let a=new EI({builder:this,checkpointer:e,interruptAfter:n,interruptBefore:t,autoValidate:!1,nodes:{},channels:{[Dx]:new sN,[Ox]:new sN},inputChannels:Dx,outputChannels:Ox,streamChannels:[],streamMode:`values`,name:r,streamTransformers:i});for(let[e,t]of Object.entries(this.nodes))a.attachNode(e,t);for(let[e,t]of this.edges)a.attachEdge(e,t);for(let[e,t]of Object.entries(this.branches))for(let[n,r]of Object.entries(t))a.attachBranch(e,n,r);return a.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(Ox);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 MS([`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(`
189
+ `),{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}},EI=class extends lI{builder;constructor({builder:e,...t}){super(t),this.builder=e}withConfig(e){return super.withConfig(e)}attachNode(e,t){this.channels[e]=new sN,this.nodes[e]=new rN({channels:[],triggers:[],metadata:t.metadata,subgraphs:t.subgraphs,ends:t.ends}).pipe(t.runnable).pipe(new QM([{channel:e,value:YM}],[eS])),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 QM([{channel:Ox,value:YM}],[eS]))}else this.nodes[t].triggers.push(e),this.nodes[t].channels.push(e)}attachBranch(e,t,n){e===`__start__`&&!this.nodes.__start__&&(this.nodes[Dx]=sI.subscribeTo(Dx,{tags:[eS]})),this.nodes[e].pipe(n.run(n=>new QM(n.map(n=>dS(n)?n:{channel:n===`__end__`?Ox:`branch:${e}:${t}:${n}`,value:YM}),[eS])));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 sN,this.nodes[n].triggers.push(r),this.nodes[n].channels.push(r)}}async getGraphAsync(e){let t=e?.xray,n=new jb,r={[Dx]:n.addNode({schema:jk()},Dx)},i={},a={};t&&(a=Object.fromEntries((await GM(this.getSubgraphsAsync())).filter(e=>DI(e[1]))));function o(e,t,a,o=!1){if(t===`__end__`&&i.__end__===void 0&&(i[Ox]=n.addNode({schema:jk()},Ox)),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=OI(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&&!hI(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(OI(e),OI(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=>[OI(e),OI(e)])),[Ox]:Ox};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(OI(e),OI(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(OI(e),OI(n),void 0,!0);return n}getGraph(e){let t=e?.xray,n=new jb,r={[Dx]:n.addNode({schema:jk()},Dx)},i={},a={};t&&(a=Object.fromEntries(KM(this.getSubgraphs()).filter(e=>DI(e[1]))));function o(e,t,a,o=!1){return t===`__end__`&&i.__end__===void 0&&(i[Ox]=n.addNode({schema:jk()},Ox)),n.addEdge(r[e],i[t],a===t?void 0:a,o)}for(let[o,s]of Object.entries(this.builder.nodes)){let c=OI(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&&!hI(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(OI(e),OI(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=>[OI(e),OI(e)])),[Ox]:Ox};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(OI(e),OI(r),n,!0)}}return n}};function DI(e){return typeof e.attachNode==`function`&&typeof e.attachEdge==`function`}function OI(e){return e===`subgraph`?`"${e}"`:e}var kI=(e,t)=>e.size===t.size&&[...e].every(e=>t.has(e)),AI=class e extends SM{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 jS(`Value ${JSON.stringify(n)} not in names ${JSON.stringify(this.names)}`);return t}get(){if(!kI(this.names,this.seen))throw new AS}checkpoint(){return[...this.seen]}consume(){return this.seen&&this.names&&kI(this.seen,this.names)?(this.seen=new Set,!0):!1}isAvailable(){return!!this.names&&kI(this.names,this.seen)}},jI=class e extends SM{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 jS(`Value ${JSON.stringify(n)} not in names ${JSON.stringify(this.names)}`);return t}get(){if(!this.finished||!kI(this.names,this.seen))throw new AS}checkpoint(){return[[...this.seen],this.finished]}consume(){return this.finished&&this.seen&&this.names&&kI(this.seen,this.names)?(this.seen=new Set,this.finished=!1,!0):!1}finish(){return!this.finished&&this.names&&kI(this.names,this.seen)?(this.finished=!0,!0):!1}isAvailable(){return this.finished&&!!this.names&&kI(this.names,this.seen)}};function MI(e){return typeof e==`object`&&!!e&&`~standard`in e&&typeof e[`~standard`]==`object`&&e[`~standard`]!==null&&`validate`in e[`~standard`]}function NI(e){return typeof e==`object`&&!!e&&`~standard`in e&&typeof e[`~standard`]==`object`&&e[`~standard`]!==null&&`jsonSchema`in e[`~standard`]}function PI(e){if(NI(e))try{return e[`~standard`].jsonSchema.input({target:`draft-07`})}catch{return}}function FI(e){if(e!=null&&MI(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 II=Symbol.for(`langgraph.channel.missing`),LI=class e extends SM{lc_graph_name=`UntrackedValue`;guard;_value=II;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 jS(`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===II)throw new AS;return this._value}checkpoint(){}isAvailable(){return this._value!==II}},RI=Symbol.for(`langgraph.state.reduced_value`),zI=class{[RI]=!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&&RI in e&&e[RI]===!0}},BI=Symbol.for(`langgraph.state.untracked_value`),VI=class{[BI]=!0;schema;guard;constructor(e,t){this.schema=e,this.guard=t?.guard??!0}static isInstance(e){return typeof e==`object`&&!!e&&BI in e}},HI=Symbol.for(`langgraph.state.state_schema`),UI=class{[HI]=!0;constructor(e){this.fields=e}getChannels(){let e={};for(let[t,n]of Object.entries(this.fields))if(zI.isInstance(n)){let r=FI(n.valueSchema);e[t]=new AM(n.reducer,r)}else if(VI.isInstance(n)){let r=n.schema?FI(n.schema):void 0;e[t]=new LI({guard:n.guard,initialValueFactory:r})}else if(MI(n))e[t]=new DM(FI(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(zI.isInstance(r)?(i=PI(r.valueSchema),r.jsonSchemaExtra&&(i={...i??{},...r.jsonSchemaExtra})):VI.isInstance(r)?i=r.schema?PI(r.schema):void 0:MI(r)&&(i=PI(r)),i){e[n]=i;let a=!1;a=zI.isInstance(r)?FI(r.valueSchema)!==void 0:VI.isInstance(r)?r.schema?FI(r.schema)!==void 0:!1:FI(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;zI.isInstance(n)?(r=PI(n.inputSchema),n.jsonSchemaExtra&&(r={...r??{},...n.jsonSchemaExtra})):VI.isInstance(n)?r=n.schema?PI(n.schema):void 0:MI(n)&&(r=PI(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(zI.isInstance(e)?i=e.inputSchema:VI.isInstance(e)?i=e.schema:MI(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&&HI in e&&e[HI]===!0}};function WI(e,t){let n=Array.isArray(e)?e:[e],r=Array.isArray(t)?t:[t],i=n.map(bn),a=r.map(bn);for(let e of i)(e.id===null||e.id===void 0)&&(e.id=CI(),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=CI(),t.lc_kwargs.id=t.id),dn.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)dn.isInstance(e)?l.add(e.id):(l.delete(e.id),s[t]=e);else{if(dn.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 zI(bA().default(()=>[]),{inputSchema:bA(),reducer:WI,jsonSchemaExtra:{langgraph_type:`messages`,description:`A list of chat messages`}});var GI=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=zg(e);for(let[e,r]of Object.entries(n)){let n=this.get(r);n?.reducer?t[e]=new AM(n.reducer.fn,n.default):t[e]=new DM(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(zg(e)).map(([e,n])=>{let r=this.get(n),i=t.withReducerSchema?r?.reducer?.schema??n:n;if(t.withJsonSchemaExtrasAsDescription&&r?.jsonSchemaExtra){let e=Ag(i)??Ag(n),t=JSON.stringify({...r.jsonSchemaExtra,description:e});i=i.describe(`lg:${t}`)}return[e,i]});i=Bg(e,Object.fromEntries(n)),bg(i)&&(i._def.unknownKeys=`strip`)}return t.asPartial&&(i=Vg(i)),r.set(e,i),this._extensionCache.set(n,r),i}};function KI(e){return e==null?!1:!!(UI.isInstance(e)||Rg(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`||xM(e)))}function qI(e){if(typeof e!=`object`||!e)return!1;let t=e,n=`state`in t&&KI(t.state),r=`stateSchema`in t&&KI(t.stateSchema),i=`input`in t&&KI(t.input);return!(!n&&!r&&!i||`input`in t&&t.input!=null&&!KI(t.input)||`output`in t&&t.output!=null&&!KI(t.output))}var JI=`__root__`,YI=Symbol.for(`langgraph.state.partial`),XI=class extends TI{channels={};waitingEdges=new Set;_schemaDefinition;_schemaRuntimeDefinition;_inputDefinition;_inputRuntimeDefinition;_outputDefinition;_outputRuntimeDefinition;_schemaDefinitions=new Map;_metaRegistry=GI;_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 NS;let i=this._getChannelsFromSchema(r);this._schemaDefinition=i,(UI.isInstance(r)||Rg(r))&&(this._schemaRuntimeDefinition=r),n.input&&(UI.isInstance(n.input)||Rg(n.input))?this._inputRuntimeDefinition=n.input:this._inputRuntimeDefinition=YI,n.output&&(UI.isInstance(n.output)||Rg(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&&Rg(n.context)&&(this._configRuntimeSchema=n.context),this._interrupt=n.interrupt,this._writer=n.writer}_normalizeToStateGraphInit(e,t){if(qI(e)){if(Rg(t)||jM.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(KI(e)){if(Rg(t)||jM.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($I(e))return{state:ZI(e.channels)};throw new NS}_getChannelsFromSchema(e){if(UI.isInstance(e))return e.getChannels();if(Rg(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 NS(`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=Ub.isRunnable(t)?t:typeof t==`function`?new UM({func:t,name:e,trace:!1}):ex(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:aN(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,transformers:s}={}){this.validate([...Array.isArray(r)?r:[],...Array.isArray(i)?i:[]]);let c=Object.keys(this._schemaDefinitions.get(this._outputDefinition)),l=c.length===1&&c[0]===JI?JI:c,u=Object.keys(this.channels),d=u.length===1&&u[0]===JI?JI:u,f=this._interrupt,p=new QI({builder:this,checkpointer:e,interruptAfter:i,interruptBefore:r,autoValidate:!1,nodes:{},channels:{...this.channels,[Dx]:new sN},inputChannels:Dx,outputChannels:l,streamChannels:d,streamMode:`updates`,store:t,cache:n,name:a,description:o,userInterrupt:f,streamTransformers:s});p.attachNode(Dx);for(let[e,t]of Object.entries(this.nodes))p.attachNode(e,t);p.attachBranch(Dx,tS,tL(),{withReader:!1});for(let[e]of Object.entries(this.nodes))p.attachBranch(e,tS,tL(),{withReader:!1});for(let[e,t]of this.edges)p.attachEdge(e,t);for(let[e,t]of this.waitingEdges)p.attachEdge(e,t);for(let[e,t]of Object.entries(this.branches))for(let[n,r]of Object.entries(t))p.attachBranch(e,n,r);return p.validate()}};function ZI(e){let t={};for(let[n,r]of Object.entries(e))t[n]=NM(r);return t}var QI=class extends EI{description;_metaRegistry=GI;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(_S(e))return e.graph===gS.PARENT?null:e._updateAsTuples();if(Array.isArray(e)&&e.length>0&&e.some(e=>_S(e))){let t=[];for(let n of e)if(_S(n)){if(n.graph===gS.PARENT)continue;t.push(...n._updateAsTuples())}else t.push([JI,n]);return t}else if(e!=null)return[[JI,e]];return null}let i=e;function a(e){if(!e)return null;if(_S(e))return e.graph===gS.PARENT?null:e._updateAsTuples().filter(([e])=>n.includes(e));if(Array.isArray(e)&&e.length>0&&e.some(_S)){let t=[];for(let r of e)if(_S(r)){if(r.graph===gS.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 jS(`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:YM,mapper:new UM({func:n.length&&n[0]===JI?r:a,trace:!1,recurse:!1})}];if(e===`__start__`)this.nodes[e]=new rN({tags:[eS],triggers:[Dx],channels:[Dx],writers:[new QM(o,[eS])]});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&&JI in r,a=`branch:to:${e}`;this.channels[a]=t?.defer?new OM:new sN(!1),this.nodes[e]=new rN({triggers:[a],channels:i?Object.keys(r):r,writers:[new QM(o,[eS])],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 QM([{channel:`branch:to:${t}`,value:null}],[eS]));else if(Array.isArray(e)){let n=`join:${e.join(`+`)}:${t}`;this.channels[n]=this.builder.nodes[t].defer?new jI(new Set(e)):new AI(new Set(e)),this.nodes[t].triggers.push(n);for(let t of e)this.nodes[t].writers.push(new QM([{channel:n,value:t}],[eS]))}}}attachBranch(e,t,n,r={withReader:!0}){this.nodes[e].writers.push(n.run(async(t,n)=>{let r=t.filter(e=>e!==Ox);if(!r.length)return;let i=r.map(t=>dS(t)?t:{channel:t===`__end__`?t:`branch:to:${t}`,value:e});await QM.doWrite({...n,tags:(n.tags??[]).concat([eS])},i)},r.withReader?e=>tN.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(UI.isInstance(t)){if(_S(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===YI&&UI.isInstance(n)){if(_S(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(Rg(t))return e(t);if(t===YI)return Rg(n)?Vg(e(n)):void 0})();if(_S(e)){let t=e;return e.update&&r!=null&&(t.update=kg(r,e.update)),t}return r==null?e:kg(r,e)}isInterrupted(e){return hS(e)}async _validateContext(e){let t=this.builder._configRuntimeSchema;return Rg(t)&&kg(t,e),e}};function $I(e){return typeof e==`object`&&!!e&&e.channels!==void 0}function eL(e){if(dS(e))return[e];let t=[];_S(e)?t.push(e):Array.isArray(e)&&t.push(...e.filter(_S));let n=[];for(let e of t){if(e.graph===gS.PARENT)throw new TS(e);dS(e.goto)||typeof e.goto==`string`?n.push(e.goto):Array.isArray(e.goto)&&n.push(...e.goto)}return n}function tL(){return new wI({path:new UM({func:eL,tags:[eS],trace:!1,recurse:!1,name:`<control_branch>`})})}var nL=e=>Array.isArray(e)&&e.every(mt),rL=e=>typeof e==`object`&&!!e&&`messages`in e&&nL(e.messages),iL=e=>typeof e==`object`&&!!e&&`lg_tool_call`in e,aL=class extends UM{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 mt(r)&&r.getType()===`tool`||_S(r)?r:new vt({status:`success`,name:n.name,content:typeof r==`string`?r:JSON.stringify(r),tool_call_id:e.id})}catch(t){if(!this.handleToolErrors||OS(t))throw t;return new vt({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(iL(e))n=[await this.runTool(e.lg_tool_call,t)];else{let r;if(nL(e))r=e;else if(rL(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(Yt(t)){a=t;break}}if(a==null||!Yt(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(_S))return Array.isArray(e)?n:{messages:n};let r=[],i=null;for(let t of n)_S(t)?t.graph===gS.PARENT&&Array.isArray(t.goto)&&t.goto.every(e=>dS(e))?i?i.goto.push(...t.goto):i=new gS({graph:gS.PARENT,goto:t.goto}):r.push(t):r.push(Array.isArray(e)?[t]:{messages:[t]});return i&&r.push(i),r}},oL=/<name>(.*?)<\/name>/s,sL=/<content>(.*?)<\/content>/s;function cL(e){if(!(mt(e)&&(Yt(e)||ht(e)&&Xt(e)))||!e.name)return e;let{name:t}=e;if(typeof e.content==`string`)return new Jt({...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 Jt({...e.lc_kwargs,content:n,name:void 0})}function lL(e){if(!Yt(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(oL),r=e.text.match(sL);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(oL),r=e.text.match(sL);return!t||!r?e:(n=t[1],{...e,text:r[1]})}return e});else{let r=e.content,i=r.match(oL),a=r.match(sL);if(!i||!a)return e;n=i[1],t=a[1]}return new Jt({...Object.keys(e.lc_kwargs??{}).length>0?e.lc_kwargs:e,content:t,name:n})}function uL(e,t){let n,r;if(t===`inline`)n=cL,r=lL;else throw Error(`Invalid agent name mode: ${t}. Needs to be one of: "inline"`);function i(e){return e.map(n)}return qb.from([Zb.from(i),e,Zb.from(r)])}function dL(e){if(typeof e==`string`||mt(e)&&e._getType()===`system`)return e;if(typeof e==`function`)return async t=>e(t.messages);if(Ub.isRunnable(e))return Zb.from(e=>e.messages).pipe(e);throw Error(`Unexpected type for messageModifier: ${typeof e}`)}var fL=`prompt`;function pL(e){let t;if(e==null)t=Zb.from(e=>e.messages).withConfig({runName:fL});else if(typeof e==`string`){let n=new fn(e);t=Zb.from(e=>[n,...e.messages??[]]).withConfig({runName:fL})}else if(mt(e)&&e._getType()===`system`)t=Zb.from(t=>[e,...t.messages]).withConfig({runName:fL});else if(typeof e==`function`)t=Zb.from(e).withConfig({runName:fL});else if(Ub.isRunnable(e))t=e;else throw Error(`Got unexpected type for 'prompt': ${typeof e}`);return t}function mL(e){return Ub.isRunnable(e)}function hL(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=dL(n)):r=t,pL(r)}function gL(e){return`invoke`in e&&typeof e.invoke==`function`&&`_modelType`in e}function _L(e){return`_queuedMethodOperations`in e&&`_model`in e&&typeof e._model==`function`}function vL(e){return gL(e)?`bindTools`in e&&typeof e.bindTools==`function`:!1}async function yL(e,t){let n=e;if(qb.isRunnableSequence(n)&&(n=n.steps.find(e=>Wb.isRunnableBinding(e)||gL(e)||_L(e))||n),_L(n)&&(n=await n._model()),!Wb.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=>mL(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 bL=(e,t)=>{if(vL(e))return e.bindTools(t);if(Wb.isRunnableBinding(e)&&vL(e.bound)){let n=e.bound.bindTools(t);return Wb.isRunnableBinding(n)?new Wb({bound:n.bound,config:{...e.config,...n.config},kwargs:{...e.kwargs,...n.kwargs},configFactories:n.configFactories??e.configFactories}):new Wb({bound:n,config:e.config,kwargs:e.kwargs,configFactories:e.configFactories})}return null};async function xL(e,t){let n=bL(e,t);if(n)return n;if(_L(e)){let n=bL(await e._model(),t);if(n)return n}if(qb.isRunnableSequence(e)){let n=e.steps.findIndex(e=>Wb.isRunnableBinding(e)||gL(e)||_L(e));if(n>=0){let r=bL(e.steps[n],t);if(r){let t=e.steps.slice();return t.splice(n,1,r),qb.from(t)}}}throw Error(`llm ${e} must define bindTools method.`)}async function SL(e){let t=e;if(qb.isRunnableSequence(t)&&(t=t.steps.find(e=>Wb.isRunnableBinding(e)||gL(e)||_L(e))||t),_L(t)&&(t=await t._model()),Wb.isRunnableBinding(t)&&(t=t.bound),!gL(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 CL=()=>MM.Root({messages:MM({reducer:WI,default:()=>[]}),structuredResponse:MM}),wL=MM.Root({llmInputMessages:MM({reducer:(e,t)=>WI([],t),default:()=>[]})});function TL(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 aL(b.filter(mL))):(b=n.tools,ee=n);let te=null,ne=async e=>{if(te)return te;let t;t=await yL(e,b)?await xL(e,b):e;let n=hL(a,i,r),o=y===`inline`?uL(t,y):t;return te=n.pipe(o),te},x=async(e,t,n)=>{let o=await e(t,n);return hL(a,i,r).pipe(y===`inline`?uL(o,y):o)},re=new Set(b.filter(mL).filter(e=>`returnDirect`in e&&e.returnDirect).map(e=>e.name));function ie(e){let{messages:t,llmInputMessages:n,...r}=e;return n!=null&&n.length>0?{messages:n,...r}:{messages:t,...r}}let ae=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 SL(t);if(!gL(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 fn({content:e}))}else i=a.withStructuredOutput(p);let o=await i.invoke(r,n);if(o==null)throw Error("Failed to parse structured response against the provided `responseFormat` schema: the structured-output parser returned null/undefined, which usually means the model output did not satisfy the schema.");return{structuredResponse:o}},oe=async(e,n)=>{let r=await(typeof t==`function`?await x(t,e,n):await ne(t)).invoke(ie(e),n);return r.name=g,r.lc_kwargs.name=g,{messages:[r]}},se=new XI(o??CL(),s).addNode(`tools`,ee);if(!(`messages`in se._schemaDefinition))throw Error("Missing required `messages` key in state schema.");let ce=se,le=e=>Object.fromEntries(Object.entries(e).filter(([e,t])=>t!=null)),S=`agent`,ue;return m==null?S=`agent`:(ce.addNode(`pre_model_hook`,m).addEdge(`pre_model_hook`,`agent`),S=`pre_model_hook`,ue=MM.Root({...se._schemaDefinition,...wL.spec})),ce.addNode(`agent`,oe,{input:ue}).addEdge(Dx,S),h!=null&&ce.addNode(`post_model_hook`,h).addEdge(`agent`,`post_model_hook`).addConditionalEdges(`post_model_hook`,e=>{let{messages:t}=e,n=new Set(t.filter(xt).map(e=>e.tool_call_id)),r;for(let e=t.length-1;e>=0;--e){let n=t[e];if(Yt(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 uS(`tools`,{...e,lg_tool_call:t})):`tools`:a&&xt(a)?S:p==null?Ox:`generate_structured_response`},le({tools:`tools`,[S]:S,generate_structured_response:p==null?null:`generate_structured_response`,[Ox]:p==null?Ox:null})),p!==void 0&&se.addNode(`generate_structured_response`,ae).addEdge(`generate_structured_response`,Ox),h??ce.addConditionalEdges(`agent`,e=>{let{messages:t}=e,n=t[t.length-1];return!Yt(n)||!n.tool_calls?.length?p==null?Ox:`generate_structured_response`:v===`v2`?n.tool_calls.map(t=>new uS(`tools`,{...e,lg_tool_call:t})):`tools`},le({tools:`tools`,generate_structured_response:p==null?null:`generate_structured_response`,[Ox]:p==null?Ox:null})),re.size>0?ce.addConditionalEdges(`tools`,e=>{let t=e;for(let e=t.messages.length-1;e>=0;--e){let n=t.messages[e];if(!xt(n))break;if(n.name!==void 0&&re.has(n.name))return Ox}return S},le({[S]:S,[Ox]:Ox})):ce.addEdge(`tools`,S),ce.compile({checkpointer:l??c,interruptBefore:u,interruptAfter:d,store:f,name:g,description:_})}function EL(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 DL=function(){let{crypto:e}=globalThis;if(e?.randomUUID)return DL=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 OL(e){return typeof e==`object`&&!!e&&(`name`in e&&e.name===`AbortError`||`message`in e&&String(e.message).includes(`FetchRequestCanceledException`))}var kL=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{},AL=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 ML({message:r,cause:kL(n)});let a=n?.error;return t===400?new PL(t,a,r,i):t===401?new FL(t,a,r,i):t===403?new IL(t,a,r,i):t===404?new LL(t,a,r,i):t===409?new RL(t,a,r,i):t===422?new zL(t,a,r,i):t===429?new BL(t,a,r,i):t>=500?new VL(t,a,r,i):new e(t,a,r,i)}},jL=class extends AL{constructor({message:e}={}){super(void 0,void 0,e||`Request was aborted.`,void 0)}},ML=class extends AL{constructor({message:e,cause:t}){super(void 0,void 0,e||`Connection error.`,void 0),t&&(this.cause=t)}},NL=class extends ML{constructor({message:e}={}){super({message:e??`Request timed out.`})}},PL=class extends AL{},FL=class extends AL{},IL=class extends AL{},LL=class extends AL{},RL=class extends AL{},zL=class extends AL{},BL=class extends AL{},VL=class extends AL{},HL=class extends G{constructor(){super(`Could not parse response content as the length limit was reached`)}},UL=class extends G{constructor(){super(`Could not parse response content as the request was rejected by the content filter`)}},WL=class extends Error{constructor(e){super(e)}},GL=class extends AL{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}},KL=class extends G{constructor(e,t,n){super(e),this.provider=t,this.cause=n}},qL=/^[a-z][a-z0-9+.-]*:/i,JL=e=>qL.test(e),YL=e=>(YL=Array.isArray,YL(e)),XL=YL;function ZL(e){return typeof e==`object`?e??{}:{}}function QL(e){if(!e)return!0;for(let t in e)return!1;return!0}function $L(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function eR(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var tR=(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},nR=e=>{try{return JSON.parse(e)}catch{return}},rR=e=>new Promise(t=>setTimeout(t,e)),iR=`6.34.0`,aR=()=>typeof window<`u`&&window.document!==void 0&&typeof navigator<`u`;function oR(){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 sR=()=>{let e=oR();if(e===`deno`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":iR,"X-Stainless-OS":uR(Deno.build.os),"X-Stainless-Arch":lR(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":iR,"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":iR,"X-Stainless-OS":uR(globalThis.process.platform??`unknown`),"X-Stainless-Arch":lR(globalThis.process.arch??`unknown`),"X-Stainless-Runtime":`node`,"X-Stainless-Runtime-Version":globalThis.process.version??`unknown`};let t=cR();return t?{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":iR,"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":iR,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`unknown`,"X-Stainless-Runtime":`unknown`,"X-Stainless-Runtime-Version":`unknown`}};function cR(){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 lR=e=>e===`x32`?`x32`:e===`x86_64`||e===`x64`?`x64`:e===`arm`?`arm`:e===`aarch64`||e===`arm64`?`arm64`:e?`other:${e}`:`unknown`,uR=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`),dR,fR=()=>dR??=sR();function pR(){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 mR(...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 hR(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return mR({start(){},async pull(e){let{done:n,value:r}=await t.next();n?e.close():e.enqueue(r)},async cancel(){await t.return?.()}})}function gR(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 _R(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 vR=({headers:e,body:t})=>({bodyHeaders:{"content-type":`application/json`},body:JSON.stringify(t)}),yR=`RFC3986`,bR=e=>String(e),xR={RFC1738:e=>String(e).replace(/%20/g,`+`),RFC3986:bR},SR=(e,t)=>(SR=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),SR(e,t)),CR=(()=>{let e=[];for(let t=0;t<256;++t)e.push(`%`+((t<16?`0`:``)+t.toString(16)).toUpperCase());return e})(),wR=1024,TR=(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+=wR){let t=a.length>=wR?a.slice(e,e+wR):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]=CR[r];continue}if(r<2048){n[n.length]=CR[192|r>>6]+CR[128|r&63];continue}if(r<55296||r>=57344){n[n.length]=CR[224|r>>12]+CR[128|r>>6&63]+CR[128|r&63];continue}e+=1,r=65536+((r&1023)<<10|t.charCodeAt(e)&1023),n[n.length]=CR[240|r>>18]+CR[128|r>>12&63]+CR[128|r>>6&63]+CR[128|r&63]}o+=n.join(``)}return o};function ER(e){return!e||typeof e!=`object`?!1:!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))}function DR(e,t){if(YL(e)){let n=[];for(let r=0;r<e.length;r+=1)n.push(t(e[r]));return n}return t(e)}var OR={brackets(e){return String(e)+`[]`},comma:`comma`,indices(e,t){return String(e)+`[`+t+`]`},repeat(e){return String(e)}},kR=function(e,t){Array.prototype.push.apply(e,YL(t)?t:[t])},AR,jR={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:`indices`,charset:`utf-8`,charsetSentinel:!1,delimiter:`&`,encode:!0,encodeDotInKeys:!1,encoder:TR,encodeValuesOnly:!1,format:yR,formatter:bR,indices:!1,serializeDate(e){return(AR??=Function.prototype.call.bind(Date.prototype.toISOString))(e)},skipNulls:!1,strictNullHandling:!1};function MR(e){return typeof e==`string`||typeof e==`number`||typeof e==`boolean`||typeof e==`symbol`||typeof e==`bigint`}var NR={};function PR(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(NR))!==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(NR)===void 0&&(b=0)}if(typeof l==`function`?v=l(t,v):v instanceof Date?v=f?.(v):n===`comma`&&YL(v)&&(v=DR(v,function(e){return e instanceof Date?f?.(e):e})),v===null){if(a)return c&&!h?c(t,jR.encoder,g,`key`,p):t;v=``}if(MR(v)||ER(v)){if(c){let e=h?t:c(t,jR.encoder,g,`key`,p);return[m?.(e)+`=`+m?.(c(v,jR.encoder,g,`value`,p))]}return[m?.(t)+`=`+m?.(String(v))]}let te=[];if(v===void 0)return te;let ne;if(n===`comma`&&YL(v))h&&c&&(v=DR(v,c)),ne=[{value:v.length>0?v.join(`,`)||null:void 0}];else if(YL(l))ne=l;else{let e=Object.keys(v);ne=u?e.sort(u):e}let x=s?String(t).replace(/\./g,`%2E`):String(t),re=r&&YL(v)&&v.length===1?x+`[]`:x;if(i&&YL(v)&&v.length===0)return re+`[]`;for(let t=0;t<ne.length;++t){let y=ne[t],ee=typeof y==`object`&&y.value!==void 0?y.value:v[y];if(o&&ee===null)continue;let x=d&&s?y.replace(/\./g,`%2E`):y,ie=YL(v)?typeof n==`function`?n(re,x):re:re+(d?`.`+x:`[`+x+`]`);_.set(e,b);let ae=new WeakMap;ae.set(NR,_),kR(te,PR(ee,ie,n,r,i,a,o,s,n===`comma`&&h&&YL(v)?null:c,l,u,d,f,p,m,h,g,ae))}return te}function FR(e=jR){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||jR.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=yR;if(e.format!==void 0){if(!SR(xR,e.format))throw TypeError(`Unknown format option provided.`);n=e.format}let r=xR[n],i=jR.filter;(typeof e.filter==`function`||YL(e.filter))&&(i=e.filter);let a;if(a=e.arrayFormat&&e.arrayFormat in OR?e.arrayFormat:`indices`in e?e.indices?`indices`:`repeat`:jR.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:jR.allowDots:!!e.allowDots;return{addQueryPrefix:typeof e.addQueryPrefix==`boolean`?e.addQueryPrefix:jR.addQueryPrefix,allowDots:o,allowEmptyArrays:typeof e.allowEmptyArrays==`boolean`?!!e.allowEmptyArrays:jR.allowEmptyArrays,arrayFormat:a,charset:t,charsetSentinel:typeof e.charsetSentinel==`boolean`?e.charsetSentinel:jR.charsetSentinel,commaRoundTrip:!!e.commaRoundTrip,delimiter:e.delimiter===void 0?jR.delimiter:e.delimiter,encode:typeof e.encode==`boolean`?e.encode:jR.encode,encodeDotInKeys:typeof e.encodeDotInKeys==`boolean`?e.encodeDotInKeys:jR.encodeDotInKeys,encoder:typeof e.encoder==`function`?e.encoder:jR.encoder,encodeValuesOnly:typeof e.encodeValuesOnly==`boolean`?e.encodeValuesOnly:jR.encodeValuesOnly,filter:i,format:n,formatter:r,serializeDate:typeof e.serializeDate==`function`?e.serializeDate:jR.serializeDate,skipNulls:typeof e.skipNulls==`boolean`?e.skipNulls:jR.skipNulls,sort:typeof e.sort==`function`?e.sort:null,strictNullHandling:typeof e.strictNullHandling==`boolean`?e.strictNullHandling:jR.strictNullHandling}}function IR(e,t={}){let n=e,r=FR(t),i,a;typeof r.filter==`function`?(a=r.filter,n=a(``,n)):YL(r.filter)&&(a=r.filter,i=a);let o=[];if(typeof n!=`object`||!n)return``;let s=OR[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||kR(o,PR(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 LR(e){return IR(e,{arrayFormat:`brackets`})}function RR(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 zR;function BR(e){let t;return(zR??=(t=new globalThis.TextEncoder,t.encode.bind(t)))(e)}var VR;function HR(e){let t;return(VR??=(t=new globalThis.TextDecoder,t.decode.bind(t)))(e)}var UR,WR,GR=class{constructor(){UR.set(this,void 0),WR.set(this,void 0),U(this,UR,new Uint8Array,`f`),U(this,WR,null,`f`)}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e==`string`?BR(e):e;U(this,UR,RR([W(this,UR,`f`),t]),`f`);let n=[],r;for(;(r=KR(W(this,UR,`f`),W(this,WR,`f`)))!=null;){if(r.carriage&&W(this,WR,`f`)==null){U(this,WR,r.index,`f`);continue}if(W(this,WR,`f`)!=null&&(r.index!==W(this,WR,`f`)+1||r.carriage)){n.push(HR(W(this,UR,`f`).subarray(0,W(this,WR,`f`)-1))),U(this,UR,W(this,UR,`f`).subarray(W(this,WR,`f`)),`f`),U(this,WR,null,`f`);continue}let e=W(this,WR,`f`)===null?r.preceding:r.preceding-1,t=HR(W(this,UR,`f`).subarray(0,e));n.push(t),U(this,UR,W(this,UR,`f`).subarray(r.index),`f`),U(this,WR,null,`f`)}return n}flush(){return W(this,UR,`f`).length?this.decode(`
190
+ `):[]}};UR=new WeakMap,WR=new WeakMap,GR.NEWLINE_CHARS=new Set([`
191
+ `,`\r`]),GR.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function KR(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 qR(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 JR={off:0,error:200,warn:300,info:400,debug:500},YR=(e,t,n)=>{if(e){if($L(JR,e))return e;ez(n).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(JR))}`)}};function XR(){}function ZR(e,t,n){return!t||JR[e]>JR[n]?XR:t[e].bind(t)}var QR={error:XR,warn:XR,info:XR,debug:XR},$R=new WeakMap;function ez(e){let t=e.logger,n=e.logLevel??`off`;if(!t)return QR;let r=$R.get(t);if(r&&r[0]===n)return r[1];let i={error:ZR(`error`,t,n),warn:ZR(`warn`,t,n),info:ZR(`info`,t,n),debug:ZR(`debug`,t,n)};return $R.set(t,[n,i]),i}var tz=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),nz,rz=class e{constructor(e,t,n){this.iterator=e,nz.set(this,void 0),this.controller=t,U(this,nz,n,`f`)}static fromSSEResponse(t,n,r,i){let a=!1,o=r?ez(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 iz(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 AL(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 AL(void 0,e.error,e.message,void 0);yield{event:r.event,data:e}}}e=!0}catch(e){if(OL(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 GR,n=gR(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(OL(e))return;throw e}finally{e||n.abort()}}return new e(o,n,r)}[(nz=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,nz,`f`)),new e(()=>i(n),this.controller,W(this,nz,`f`))]}toReadableStream(){let e=this,t;return mR({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=BR(JSON.stringify(n)+`
192
+ `);e.enqueue(i)}catch(t){e.error(t)}},async cancel(){await t.return?.()}})}};async function*iz(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 oz,r=new GR,i=gR(e.body);for await(let e of az(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*az(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`?BR(n):n,r=new Uint8Array(t.length+e.length);r.set(t),r.set(e,t.length),t=r;let i;for(;(i=qR(t))!==-1;)yield t.slice(0,i),t=t.slice(i)}t.length>0&&(yield t)}var oz=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(`
193
+ `),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]=sz(e,`:`);return r.startsWith(` `)&&(r=r.substring(1)),t===`event`?this.event=r:t===`data`&&this.data.push(r),null}};function sz(e,t){let n=e.indexOf(t);return n===-1?[e,``,``]:[e.substring(0,n),t,e.substring(n+t.length)]}async function cz(e,t){let{response:n,requestLogID:r,retryOfRequestLogID:i,startTime:a}=t,o=await(async()=>{if(t.options.stream)return ez(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):rz.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:lz(await n.json(),n):await n.text()})();return ez(e).debug(`[${r}] response parsed`,tz({retryOfRequestLogID:i,url:n.url,status:n.status,body:o,durationMs:Date.now()-a})),o}function lz(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 uz,dz=class e extends Promise{constructor(e,t,n=cz){super(e=>{e(null)}),this.responsePromise=t,this.parseResponse=n,uz.set(this,void 0),U(this,uz,e,`f`)}_thenUnwrap(t){return new e(W(this,uz,`f`),this.responsePromise,async(e,n)=>lz(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,uz,`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)}};uz=new WeakMap;var fz,pz=class{constructor(e,t,n,r){fz.set(this,void 0),U(this,fz,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,fz,`f`).requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(fz=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}},mz=class extends dz{constructor(e,t,n){super(e,t,async(e,t)=>new n(e,t.response,await cz(e,t),t.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}},hz=class extends pz{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}},gz=class extends pz{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:{...ZL(this.options.query),after:t}}:null}},_z=class extends pz{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:{...ZL(this.options.query),after:e}}:null}},vz={jwt:`urn:ietf:params:oauth:token-type:jwt`,id:`urn:ietf:params:oauth:token-type:id_token`},yz=`urn:ietf:params:oauth:grant-type:token-exchange`,bz=class{constructor(e,t){this.cachedToken=null,this.refreshPromise=null,this.tokenExchangeUrl=`https://auth.openai.com/oauth/token`,this.config=e,this.fetch=t??pR()}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:yz,client_id:this.config.clientId,subject_token:e,subject_token_type:vz[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 GL(t.status,n,t.headers):AL.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}},xz=()=>{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 Sz(e,t,n){return xz(),new File(e,t??`unknown_file`,n)}function Cz(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 wz=e=>typeof e==`object`&&!!e&&typeof e[Symbol.asyncIterator]==`function`,Tz=async(e,t)=>Mz(e.body)?{...e,body:await kz(e.body,t)}:e,Ez=async(e,t)=>({...e,body:await kz(e.body,t)}),Dz=new WeakMap;function Oz(e){let t=typeof e==`function`?e:e.fetch,n=Dz.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 Dz.set(t,r),r}var kz=async(e,t)=>{if(!await Oz(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])=>Nz(n,e,t))),n},Az=e=>e instanceof Blob&&`name`in e,jz=e=>typeof e==`object`&&!!e&&(e instanceof Response||wz(e)||Az(e)),Mz=e=>{if(jz(e))return!0;if(Array.isArray(e))return e.some(Mz);if(e&&typeof e==`object`){for(let t in e)if(Mz(e[t]))return!0}return!1},Nz=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,Sz([await n.blob()],Cz(n)));else if(wz(n))e.append(t,Sz([await new Response(hR(n)).blob()],Cz(n)));else if(Az(n))e.append(t,n,Cz(n));else if(Array.isArray(n))await Promise.all(n.map(n=>Nz(e,t+`[]`,n)));else if(typeof n==`object`)await Promise.all(Object.entries(n).map(([n,r])=>Nz(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`)}},Pz=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`,Fz=e=>typeof e==`object`&&!!e&&typeof e.name==`string`&&typeof e.lastModified==`number`&&Pz(e),Iz=e=>typeof e==`object`&&!!e&&typeof e.url==`string`&&typeof e.blob==`function`;async function Lz(e,t,n){if(xz(),e=await e,Fz(e))return e instanceof File?e:Sz([await e.arrayBuffer()],e.name);if(Iz(e)){let r=await e.blob();return t||=new URL(e.url).pathname.split(/[\\/]/).pop(),Sz(await Rz(r),t,n)}let r=await Rz(e);if(t||=Cz(e),!n?.type){let e=r.find(e=>typeof e==`object`&&`type`in e&&e.type);typeof e==`string`&&(n={...n,type:e})}return Sz(r,t,n)}async function Rz(e){let t=[];if(typeof e==`string`||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(Pz(e))t.push(e instanceof Blob?e:await e.arrayBuffer());else if(wz(e))for await(let n of e)t.push(...await Rz(n));else{let t=e?.constructor?.name;throw Error(`Unexpected data type: ${typeof e}${t?`; constructor: ${t}`:``}${zz(e)}`)}return t}function zz(e){return typeof e!=`object`||!e?``:`; props: [${Object.getOwnPropertyNames(e).map(e=>`"${e}"`).join(`, `)}]`}var K=class{constructor(e){this._client=e}};function Bz(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var Vz=Object.freeze(Object.create(null)),q=((e=Bz)=>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??Vz)??Vz)?.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(`
194
+ `)}\n${a}\n${t}`)}return a})(Bz),Hz=class extends K{list(e,t={},n){return this._client.getAPIList(q`/chat/completions/${e}/messages`,gz,{query:t,...n})}};function Uz(e){return e!==void 0&&`function`in e&&e.function!==void 0}function Wz(e,t){let n={...e};return Object.defineProperties(n,{$brand:{value:`auto-parseable-response-format`,enumerable:!1},$parseRaw:{value:t,enumerable:!1}}),n}function Gz(e){return e?.$brand===`auto-parseable-response-format`}function Kz(e){return e?.$brand===`auto-parseable-tool`}function qz(e,t){return!t||!Qz(t)?{...e,choices:e.choices.map(e=>($z(e.message.tool_calls),{...e,message:{...e.message,parsed:null,...e.message.tool_calls?{tool_calls:e.message.tool_calls}:void 0}}))}:Jz(e,t)}function Jz(e,t){let n=e.choices.map(e=>{if(e.finish_reason===`length`)throw new HL;if(e.finish_reason===`content_filter`)throw new UL;return $z(e.message.tool_calls),{...e,message:{...e.message,...e.message.tool_calls?{tool_calls:e.message.tool_calls?.map(e=>Xz(t,e))??void 0}:void 0,parsed:e.message.content&&!e.message.refusal?Yz(t,e.message.content):null}}});return{...e,choices:n}}function Yz(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 Xz(e,t){let n=e.tools?.find(e=>Uz(e)&&e.function?.name===t.function.name);return{...t,function:{...t.function,parsed_arguments:Kz(n)?n.$parseRaw(t.function.arguments):n?.function.strict?JSON.parse(t.function.arguments):null}}}function Zz(e,t){if(!e||!(`tools`in e)||!e.tools)return!1;let n=e.tools?.find(e=>Uz(e)&&e.function?.name===t.function.name);return Uz(n)&&(Kz(n)||n?.function.strict||!1)}function Qz(e){return Gz(e.response_format)?!0:e.tools?.some(e=>Kz(e)||e.type===`function`&&e.function.strict===!0)??!1}function $z(e){for(let t of e||[])if(t.type!==`function`)throw new G(`Currently only \`function\` tool calls are supported; Received \`${t.type}\``)}function eB(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 tB=e=>e?.role===`assistant`,nB=e=>e?.role===`tool`,rB,iB,aB,oB,sB,cB,lB,uB,dB,fB,pB,mB,hB,gB=class{constructor(){rB.add(this),this.controller=new AbortController,iB.set(this,void 0),aB.set(this,()=>{}),oB.set(this,()=>{}),sB.set(this,void 0),cB.set(this,()=>{}),lB.set(this,()=>{}),uB.set(this,{}),dB.set(this,!1),fB.set(this,!1),pB.set(this,!1),mB.set(this,!1),U(this,iB,new Promise((e,t)=>{U(this,aB,e,`f`),U(this,oB,t,`f`)}),`f`),U(this,sB,new Promise((e,t)=>{U(this,cB,e,`f`),U(this,lB,t,`f`)}),`f`),W(this,iB,`f`).catch(()=>{}),W(this,sB,`f`).catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit(`end`)},W(this,rB,`m`,hB).bind(this))},0)}_connected(){this.ended||(W(this,aB,`f`).call(this),this._emit(`connect`))}get ended(){return W(this,dB,`f`)}get errored(){return W(this,fB,`f`)}get aborted(){return W(this,pB,`f`)}abort(){this.controller.abort()}on(e,t){return(W(this,uB,`f`)[e]||(W(this,uB,`f`)[e]=[])).push({listener:t}),this}off(e,t){let n=W(this,uB,`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,uB,`f`)[e]||(W(this,uB,`f`)[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,n)=>{U(this,mB,!0,`f`),e!==`error`&&this.once(`error`,n),this.once(e,t)})}async done(){U(this,mB,!0,`f`),await W(this,sB,`f`)}_emit(e,...t){if(W(this,dB,`f`))return;e===`end`&&(U(this,dB,!0,`f`),W(this,cB,`f`).call(this));let n=W(this,uB,`f`)[e];if(n&&(W(this,uB,`f`)[e]=n.filter(e=>!e.once),n.forEach(({listener:e})=>e(...t))),e===`abort`){let e=t[0];!W(this,mB,`f`)&&!n?.length&&Promise.reject(e),W(this,oB,`f`).call(this,e),W(this,lB,`f`).call(this,e),this._emit(`end`);return}if(e===`error`){let e=t[0];!W(this,mB,`f`)&&!n?.length&&Promise.reject(e),W(this,oB,`f`).call(this,e),W(this,lB,`f`).call(this,e),this._emit(`end`)}}_emitFinal(){}};iB=new WeakMap,aB=new WeakMap,oB=new WeakMap,sB=new WeakMap,cB=new WeakMap,lB=new WeakMap,uB=new WeakMap,dB=new WeakMap,fB=new WeakMap,pB=new WeakMap,mB=new WeakMap,rB=new WeakSet,hB=function(e){if(U(this,fB,!0,`f`),e instanceof Error&&e.name===`AbortError`&&(e=new jL),e instanceof jL)return U(this,pB,!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 _B(e){return typeof e.parse==`function`}var vB,yB,bB,xB,SB,CB,wB,TB,EB=10,DB=class extends gB{constructor(){super(...arguments),vB.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),nB(e)&&e.content)this._emit(`functionToolCallResult`,e.content);else if(tB(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,vB,`m`,yB).call(this)}async finalMessage(){return await this.done(),W(this,vB,`m`,bB).call(this)}async finalFunctionToolCall(){return await this.done(),W(this,vB,`m`,xB).call(this)}async finalFunctionToolCallResult(){return await this.done(),W(this,vB,`m`,SB).call(this)}async totalUsage(){return await this.done(),W(this,vB,`m`,CB).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit(`finalChatCompletion`,e);let t=W(this,vB,`m`,bB).call(this);t&&this._emit(`finalMessage`,t);let n=W(this,vB,`m`,yB).call(this);n&&this._emit(`finalContent`,n);let r=W(this,vB,`m`,xB).call(this);r&&this._emit(`finalFunctionToolCall`,r);let i=W(this,vB,`m`,SB).call(this);i!=null&&this._emit(`finalFunctionToolCallResult`,i),this._chatCompletions.some(e=>e.usage)&&this._emit(`totalUsage`,W(this,vB,`m`,CB).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,vB,`m`,wB).call(this,t);let i=await e.chat.completions.create({...t,stream:!1},{...n,signal:this.controller.signal});return this._connected(),this._addChatCompletion(Jz(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=EB}=n||{},l=t.tools.map(e=>{if(Kz(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=_B(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,vB,`m`,TB).call(this,c);if(this._addMessage({role:r,tool_call_id:t,content:l}),s)return}}}};vB=new WeakSet,yB=function(){return W(this,vB,`m`,bB).call(this).content??null},bB=function(){let e=this.messages.length;for(;e-- >0;){let t=this.messages[e];if(tB(t))return{...t,content:t.content??null,refusal:t.refusal??null}}throw new G(`stream ended without producing a ChatCompletionMessage with role=assistant`)},xB=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(tB(t)&&t?.tool_calls?.length)return t.tool_calls.filter(e=>e.type===`function`).at(-1)?.function}},SB=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(nB(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}},CB=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},wB=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.`)},TB=function(e){return typeof e==`string`?e:e===void 0?`undefined`:JSON.stringify(e)};var OB=class e extends DB{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),tB(e)&&e.content&&this._emit(`content`,e.content)}},kB=1,AB=2,jB=4,MB=8,NB=16,PB=32,FB=64,IB=128,LB=256,RB=IB|LB,zB=496,BB=AB|497,VB=jB|MB,HB={STR:kB,NUM:AB,ARR:jB,OBJ:MB,NULL:NB,BOOL:PB,NAN:FB,INFINITY:IB,MINUS_INFINITY:LB,INF:RB,SPECIAL:zB,ATOM:BB,COLLECTION:VB,ALL:BB|VB},UB=class extends Error{},WB=class extends Error{};function GB(e,t=HB.ALL){if(typeof e!=`string`)throw TypeError(`expecting str, got ${typeof e}`);if(!e.trim())throw Error(`${e} is empty`);return KB(e.trim(),t)}var KB=(e,t)=>{let n=e.length,r=0,i=e=>{throw new UB(`${e} at position ${r}`)},a=e=>{throw new WB(`${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`||HB.NULL&t&&n-r<4&&`null`.startsWith(e.substring(r))?(r+=4,null):e.substring(r,r+4)===`true`||HB.BOOL&t&&n-r<4&&`true`.startsWith(e.substring(r))?(r+=4,!0):e.substring(r,r+5)===`false`||HB.BOOL&t&&n-r<5&&`false`.startsWith(e.substring(r))?(r+=5,!1):e.substring(r,r+8)===`Infinity`||HB.INFINITY&t&&n-r<8&&`Infinity`.startsWith(e.substring(r))?(r+=8,1/0):e.substring(r,r+9)===`-Infinity`||HB.MINUS_INFINITY&t&&1<n-r&&n-r<9&&`-Infinity`.startsWith(e.substring(r))?(r+=9,-1/0):e.substring(r,r+3)===`NaN`||HB.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(HB.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&&HB.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(HB.OBJ&t)return a;throw e}d(),e[r]===`,`&&r++}}catch{if(HB.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(HB.ARR&t)return n;i(`Expected ']' at end of array`)}return r++,n},u=()=>{if(r===0){e===`-`&&HB.NUM&t&&i(`Not sure what '-' is`);try{return JSON.parse(e)}catch(n){if(HB.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&&!(HB.NUM&t)&&i(`Unterminated number literal`);try{return JSON.parse(e.substring(o,r))}catch{e.substring(o,r)===`-`&&HB.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&&`
195
+ \r `.includes(e[r]);)r++};return o()},qB=e=>GB(e,HB.ALL^HB.NUM),JB,YB,XB,ZB,QB,$B,eV,tV,nV,rV,iV,aV,oV=class e extends DB{constructor(e){super(),JB.add(this),YB.set(this,void 0),XB.set(this,void 0),ZB.set(this,void 0),U(this,YB,e,`f`),U(this,XB,[],`f`)}get currentChatCompletionSnapshot(){return W(this,ZB,`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,JB,`m`,QB).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,JB,`m`,eV).call(this,e);if(i.controller.signal?.aborted)throw new jL;return this._addChatCompletion(W(this,JB,`m`,rV).call(this))}async _fromReadableStream(e,t){let n=t?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener(`abort`,()=>this.controller.abort())),W(this,JB,`m`,QB).call(this),this._connected();let r=rz.fromReadableStream(e,this.controller),i;for await(let e of r)i&&i!==e.id&&this._addChatCompletion(W(this,JB,`m`,rV).call(this)),W(this,JB,`m`,eV).call(this,e),i=e.id;if(r.controller.signal?.aborted)throw new jL;return this._addChatCompletion(W(this,JB,`m`,rV).call(this))}[(YB=new WeakMap,XB=new WeakMap,ZB=new WeakMap,JB=new WeakSet,QB=function(){this.ended||U(this,ZB,void 0,`f`)},$B=function(e){let t=W(this,XB,`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,XB,`f`)[e.index]=t,t)},eV=function(e){if(this.ended)return;let t=W(this,JB,`m`,aV).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,JB,`m`,$B).call(this,e);e.finish_reason&&(W(this,JB,`m`,nV).call(this,e),r.current_tool_call_index!=null&&W(this,JB,`m`,tV).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,JB,`m`,nV).call(this,e),r.current_tool_call_index!=null&&W(this,JB,`m`,tV).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)}}},tV=function(e,t){if(W(this,JB,`m`,$B).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,YB,`f`)?.tools?.find(e=>Uz(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:Kz(e)?e.$parseRaw(n.function.arguments):e?.function.strict?JSON.parse(n.function.arguments):null})}else n.type},nV=function(e){let t=W(this,JB,`m`,$B).call(this,e);if(e.message.content&&!t.content_done){t.content_done=!0;let n=W(this,JB,`m`,iV).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}))},rV=function(){if(this.ended)throw new G(`stream has ended, this shouldn't happen`);let e=W(this,ZB,`f`);if(!e)throw new G(`request ended without sending any chunks`);return U(this,ZB,void 0,`f`),U(this,XB,[],`f`),sV(e,W(this,YB,`f`))},iV=function(){let e=W(this,YB,`f`)?.response_format;return Gz(e)?e:null},aV=function(e){var t,n,r,i;let a=W(this,ZB,`f`),{choices:o,...s}=e;a?Object.assign(a,s):a=U(this,ZB,{...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,YB,`f`)&&Qz(W(this,YB,`f`)))){if(s===`length`)throw new HL;if(s===`content_filter`)throw new UL}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,JB,`m`,iV).call(this)&&(e.message.parsed=qB(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,Zz(W(this,YB,`f`),s)&&(s.function.parsed_arguments=qB(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 rz(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};function sV(e,t){let{id:n,choices:r,created:i,model:a,system_fingerprint:o,...s}=e;return qz({...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${cV(e)}`);if(a==null)throw new G(`missing choices[${r}].tool_calls[${n}].type\n${cV(e)}`);if(l==null)throw new G(`missing choices[${r}].tool_calls[${n}].function.name\n${cV(e)}`);if(c==null)throw new G(`missing choices[${r}].tool_calls[${n}].function.arguments\n${cV(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 cV(e){return JSON.stringify(e)}var lV=class e extends oV{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}},uV=class extends K{constructor(){super(...arguments),this.messages=new Hz(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`,gz,{query:e,...t})}delete(e,t){return this._client.delete(q`/chat/completions/${e}`,t)}parse(e,t){return eB(e.tools),this._client.chat.completions.create(e,{...t,headers:{...t?.headers,"X-Stainless-Helper-Method":`chat.completions.parse`}})._thenUnwrap(t=>Jz(t,e))}runTools(e,t){return e.stream?lV.runTools(this._client,e,t):OB.runTools(this._client,e,t)}stream(e,t){return oV.createChatCompletion(this._client,e,t)}};uV.Messages=Hz;var dV=class extends K{constructor(){super(...arguments),this.completions=new uV(this._client)}};dV.Completions=uV;var fV=Symbol(`brand.privateNullableHeaders`);function*pV(e){if(!e)return;if(fV 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():XL(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=XL(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 pV(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{[fV]:!0,values:t,nulls:n}},mV=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})}},hV=class extends K{create(e,t){return this._client.post(`/audio/transcriptions`,Ez({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model}},this._client))}},gV=class extends K{create(e,t){return this._client.post(`/audio/translations`,Ez({body:e,...t,__metadata:{model:e.model}},this._client))}},_V=class extends K{constructor(){super(...arguments),this.transcriptions=new hV(this._client),this.translations=new gV(this._client),this.speech=new mV(this._client)}};_V.Transcriptions=hV,_V.Translations=gV,_V.Speech=mV;var vV=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`,gz,{query:e,...t})}cancel(e,t){return this._client.post(q`/batches/${e}/cancel`,t)}},yV=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`,gz,{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])})}},bV=class extends K{create(e,t){return this._client.post(`/realtime/sessions`,{body:e,...t,headers:J([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}},xV=class extends K{create(e,t){return this._client.post(`/realtime/transcription_sessions`,{body:e,...t,headers:J([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}},SV=class extends K{constructor(){super(...arguments),this.sessions=new bV(this._client),this.transcriptionSessions=new xV(this._client)}};SV.Sessions=bV,SV.TranscriptionSessions=xV;var CV=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])})}},wV=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`,_z,{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`,_z,{query:t,...n,headers:J([{"OpenAI-Beta":`chatkit_beta=v1`},n?.headers])})}},TV=class extends K{constructor(){super(...arguments),this.sessions=new CV(this._client),this.threads=new wV(this._client)}};TV.Sessions=CV,TV.Threads=wV;var EV=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`,gz,{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])})}},DV=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`,gz,{query:i,...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}},OV=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))}},kV=e=>{if(globalThis.process!==void 0)return{}?.[e]?.trim()??void 0;if(globalThis.Deno!==void 0)return globalThis.Deno.env?.get?.(e)?.trim()},AV,jV,MV,NV,PV,FV,IV,LV,RV,zV,BV,VV,HV,UV,WV,GV,KV,qV,JV,YV,XV,ZV,QV,$V=class extends gB{constructor(){super(...arguments),AV.add(this),MV.set(this,[]),NV.set(this,{}),PV.set(this,{}),FV.set(this,void 0),IV.set(this,void 0),LV.set(this,void 0),RV.set(this,void 0),zV.set(this,void 0),BV.set(this,void 0),VV.set(this,void 0),HV.set(this,void 0),UV.set(this,void 0)}[(MV=new WeakMap,NV=new WeakMap,PV=new WeakMap,FV=new WeakMap,IV=new WeakMap,LV=new WeakMap,RV=new WeakMap,zV=new WeakMap,BV=new WeakMap,VV=new WeakMap,HV=new WeakMap,UV=new WeakMap,AV=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 jV;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=rz.fromReadableStream(e,this.controller);for await(let e of r)W(this,AV,`m`,WV).call(this,e);if(r.controller.signal?.aborted)throw new jL;return this._addRun(W(this,AV,`m`,GV).call(this))}toReadableStream(){return new rz(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,n,r){let i=new jV;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,AV,`m`,WV).call(this,e);if(o.controller.signal?.aborted)throw new jL;return this._addRun(W(this,AV,`m`,GV).call(this))}static createThreadAssistantStream(e,t,n){let r=new jV;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 jV;return i._run(()=>i._runAssistantStream(e,t,n,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`stream`}})),i}currentEvent(){return W(this,VV,`f`)}currentRun(){return W(this,HV,`f`)}currentMessageSnapshot(){return W(this,FV,`f`)}currentRunStepSnapshot(){return W(this,UV,`f`)}async finalRunSteps(){return await this.done(),Object.values(W(this,NV,`f`))}async finalMessages(){return await this.done(),Object.values(W(this,PV,`f`))}async finalRun(){if(await this.done(),!W(this,IV,`f`))throw Error(`Final run was not received.`);return W(this,IV,`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,AV,`m`,WV).call(this,e);if(a.controller.signal?.aborted)throw new jL;return this._addRun(W(this,AV,`m`,GV).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,AV,`m`,WV).call(this,e);if(o.controller.signal?.aborted)throw new jL;return this._addRun(W(this,AV,`m`,GV).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(eR(t)&&eR(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(!eR(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)}};jV=$V,WV=function(e){if(!this.ended)switch(U(this,VV,e,`f`),W(this,AV,`m`,JV).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,AV,`m`,QV).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,AV,`m`,qV).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,AV,`m`,KV).call(this,e);break;case`error`:throw Error(`Encountered an error event in event processing - errors should be processed earlier`);default:}},GV=function(){if(this.ended)throw new G(`stream has ended, this shouldn't happen`);if(!W(this,IV,`f`))throw Error(`Final run has not been received`);return W(this,IV,`f`)},KV=function(e){let[t,n]=W(this,AV,`m`,XV).call(this,e,W(this,FV,`f`));U(this,FV,t,`f`),W(this,PV,`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,LV,`f`)){if(W(this,RV,`f`))switch(W(this,RV,`f`).type){case`text`:this._emit(`textDone`,W(this,RV,`f`).text,W(this,FV,`f`));break;case`image_file`:this._emit(`imageFileDone`,W(this,RV,`f`).image_file,W(this,FV,`f`));break}U(this,LV,n.index,`f`)}U(this,RV,t.content[n.index],`f`)}break;case`thread.message.completed`:case`thread.message.incomplete`:if(W(this,LV,`f`)!==void 0){let t=e.data.content[W(this,LV,`f`)];if(t)switch(t.type){case`image_file`:this._emit(`imageFileDone`,t.image_file,W(this,FV,`f`));break;case`text`:this._emit(`textDone`,t.text,W(this,FV,`f`));break}}W(this,FV,`f`)&&this._emit(`messageDone`,e.data),U(this,FV,void 0,`f`)}},qV=function(e){let t=W(this,AV,`m`,YV).call(this,e);switch(U(this,UV,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,zV,`f`)?this._emit(`toolCallDelta`,e,t.step_details.tool_calls[e.index]):(W(this,BV,`f`)&&this._emit(`toolCallDone`,W(this,BV,`f`)),U(this,zV,e.index,`f`),U(this,BV,t.step_details.tool_calls[e.index],`f`),W(this,BV,`f`)&&this._emit(`toolCallCreated`,W(this,BV,`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,UV,void 0,`f`),e.data.step_details.type==`tool_calls`&&W(this,BV,`f`)&&(this._emit(`toolCallDone`,W(this,BV,`f`)),U(this,BV,void 0,`f`)),this._emit(`runStepDone`,e.data,t);break;case`thread.run.step.in_progress`:break}},JV=function(e){W(this,MV,`f`).push(e),this._emit(`event`,e)},YV=function(e){switch(e.event){case`thread.run.step.created`:return W(this,NV,`f`)[e.data.id]=e.data,e.data;case`thread.run.step.delta`:let t=W(this,NV,`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=jV.accumulateDelta(t,n.delta);W(this,NV,`f`)[e.data.id]=r}return W(this,NV,`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,NV,`f`)[e.data.id]=e.data;break}if(W(this,NV,`f`)[e.data.id])return W(this,NV,`f`)[e.data.id];throw Error(`No snapshot available`)},XV=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,AV,`m`,ZV).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`)},ZV=function(e,t){return jV.accumulateDelta(t,e)},QV=function(e){switch(U(this,HV,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,IV,e.data,`f`),W(this,BV,`f`)&&(this._emit(`toolCallDone`,W(this,BV,`f`)),U(this,BV,void 0,`f`));break;case`thread.run.cancelling`:break}};var eH=class extends K{constructor(){super(...arguments),this.steps=new DV(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`,gz,{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 $V.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 rR(e);break;case`requires_action`:case`incomplete`:case`cancelled`:case`completed`:case`failed`:case`expired`:return i}}}stream(e,t,n){return $V.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 $V.createToolAssistantStream(e,this._client.beta.threads.runs,t,n)}};eH.Steps=DV;var tH=class extends K{constructor(){super(...arguments),this.runs=new eH(this._client),this.messages=new EV(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 $V.createThreadAssistantStream(e,this._client.beta.threads,t)}};tH.Runs=eH,tH.Messages=EV;var nH=class extends K{constructor(){super(...arguments),this.realtime=new SV(this._client),this.chatkit=new TV(this._client),this.assistants=new yV(this._client),this.threads=new tH(this._client)}};nH.Realtime=SV,nH.ChatKit=TV,nH.Assistants=yV,nH.Threads=tH;var rH=class extends K{create(e,t){return this._client.post(`/completions`,{body:e,...t,stream:e.stream??!1})}},iH=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})}},aH=class extends K{constructor(){super(...arguments),this.content=new iH(this._client)}create(e,t,n){return this._client.post(q`/containers/${e}/files`,Tz({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`,gz,{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])})}};aH.Content=iH;var oH=class extends K{constructor(){super(...arguments),this.files=new aH(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`,gz,{query:e,...t})}delete(e,t){return this._client.delete(q`/containers/${e}`,{...t,headers:J([{Accept:`*/*`},t?.headers])})}};oH.Files=aH;var sH=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`,_z,{query:t,...n})}delete(e,t,n){let{conversation_id:r}=t;return this._client.delete(q`/conversations/${r}/items/${e}`,n)}},cH=class extends K{constructor(){super(...arguments),this.items=new sH(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)}};cH.Items=sH;var lH=class extends K{create(e,t){let n=!!e.encoding_format,r=n?e.encoding_format:`base64`;n&&ez(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:(ez(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=OV(t)}),e)))}},uH=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`,gz,{query:i,...n})}},dH=class extends K{constructor(){super(...arguments),this.outputItems=new uH(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`,gz,{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)}};dH.OutputItems=uH;var fH=class extends K{constructor(){super(...arguments),this.runs=new dH(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`,gz,{query:e,...t})}delete(e,t){return this._client.delete(q`/evals/${e}`,t)}};fH.Runs=dH;var pH=class extends K{create(e,t){return this._client.post(`/files`,Ez({body:e,...t},this._client))}retrieve(e,t){return this._client.get(q`/files/${e}`,t)}list(e={},t){return this._client.getAPIList(`/files`,gz,{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 rR(t),a=await this.retrieve(e),Date.now()-i>n)throw new NL({message:`Giving up on waiting for file ${e} to finish processing after ${n} milliseconds.`});return a}},mH=class extends K{},hH=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})}},gH=class extends K{constructor(){super(...arguments),this.graders=new hH(this._client)}};gH.Graders=hH;var _H=class extends K{create(e,t,n){return this._client.getAPIList(q`/fine_tuning/checkpoints/${e}/permissions`,hz,{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`,_z,{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)}},vH=class extends K{constructor(){super(...arguments),this.permissions=new _H(this._client)}};vH.Permissions=_H;var yH=class extends K{list(e,t={},n){return this._client.getAPIList(q`/fine_tuning/jobs/${e}/checkpoints`,gz,{query:t,...n})}},bH=class extends K{constructor(){super(...arguments),this.checkpoints=new yH(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`,gz,{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`,gz,{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)}};bH.Checkpoints=yH;var xH=class extends K{constructor(){super(...arguments),this.methods=new mH(this._client),this.jobs=new bH(this._client),this.checkpoints=new vH(this._client),this.alpha=new gH(this._client)}};xH.Methods=mH,xH.Jobs=bH,xH.Checkpoints=vH,xH.Alpha=gH;var SH=class extends K{},CH=class extends K{constructor(){super(...arguments),this.graderModels=new SH(this._client)}};CH.GraderModels=SH;var wH=class extends K{createVariation(e,t){return this._client.post(`/images/variations`,Ez({body:e,...t},this._client))}edit(e,t){return this._client.post(`/images/edits`,Ez({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})}},TH=class extends K{retrieve(e,t){return this._client.get(q`/models/${e}`,t)}list(e){return this._client.getAPIList(`/models`,hz,e)}delete(e,t){return this._client.delete(q`/models/${e}`,t)}},EH=class extends K{create(e,t){return this._client.post(`/moderations`,{body:e,...t})}},DH=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])})}},OH=class extends K{create(e,t){return this._client.post(`/realtime/client_secrets`,{body:e,...t})}},kH=class extends K{constructor(){super(...arguments),this.clientSecrets=new OH(this._client),this.calls=new DH(this._client)}};kH.ClientSecrets=OH,kH.Calls=DH;function AH(e,t){return!t||!NH(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)}:jH(e,t)}function jH(e,t){let n=e.output.map(e=>{if(e.type===`function_call`)return{...e,parsed_arguments:IH(t,e)};if(e.type===`message`){let n=e.content.map(e=>e.type===`output_text`?{...e,parsed:MH(t,e.text)}:e);return{...e,content:n}}return e}),r=Object.assign({},e,{output:n});return Object.getOwnPropertyDescriptor(e,`output_text`)||LH(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 MH(e,t){return e.text?.format?.type===`json_schema`?`$parseRaw`in e.text?.format?(e.text?.format).$parseRaw(t):JSON.parse(t):null}function NH(e){return!!Gz(e.text?.format)}function PH(e){return e?.$brand===`auto-parseable-tool`}function FH(e,t){return e.find(e=>e.type===`function`&&e.name===t)}function IH(e,t){let n=FH(e.tools??[],t.name);return{...t,...t,parsed_arguments:PH(n)?n.$parseRaw(t.arguments):n?.strict?JSON.parse(t.arguments):null}}function LH(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 RH,zH,BH,VH,HH,UH,WH,GH,KH=class e extends gB{constructor(e){super(),RH.add(this),zH.set(this,void 0),BH.set(this,void 0),VH.set(this,void 0),U(this,zH,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,RH,`m`,HH).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,RH,`m`,UH).call(this,e,a);if(i.controller.signal?.aborted)throw new jL;return W(this,RH,`m`,WH).call(this)}[(zH=new WeakMap,BH=new WeakMap,VH=new WeakMap,RH=new WeakSet,HH=function(){this.ended||U(this,BH,void 0,`f`)},UH=function(e,t){if(this.ended)return;let n=(e,n)=>{(t==null||n.sequence_number>t)&&this._emit(e,n)},r=W(this,RH,`m`,GH).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}},WH=function(){if(this.ended)throw new G(`stream has ended, this shouldn't happen`);let e=W(this,BH,`f`);if(!e)throw new G(`request ended without sending any events`);U(this,BH,void 0,`f`);let t=qH(e,W(this,zH,`f`));return U(this,VH,t,`f`),t},GH=function(e){let t=W(this,BH,`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,BH,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,BH,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,VH,`f`);if(!e)throw new G(`stream ended without producing a ChatCompletion`);return e}};function qH(e,t){return AH(e,t)}var JH=class extends K{list(e,t={},n){return this._client.getAPIList(q`/responses/${e}/input_items`,gz,{query:t,...n})}},YH=class extends K{count(e={},t){return this._client.post(`/responses/input_tokens`,{body:e,...t})}},XH=class extends K{constructor(){super(...arguments),this.inputItems=new JH(this._client),this.inputTokens=new YH(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`&&LH(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`&&LH(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=>jH(t,e))}stream(e,t){return KH.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})}};XH.InputItems=JH,XH.InputTokens=YH;var ZH=class extends K{retrieve(e,t){return this._client.get(q`/skills/${e}/content`,{...t,headers:J([{Accept:`application/binary`},t?.headers]),__binaryResponse:!0})}},QH=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})}},$H=class extends K{constructor(){super(...arguments),this.content=new QH(this._client)}create(e,t={},n){return this._client.post(q`/skills/${e}/versions`,Tz({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`,gz,{query:t,...n})}delete(e,t,n){let{skill_id:r}=t;return this._client.delete(q`/skills/${r}/versions/${e}`,n)}};$H.Content=QH;var eU=class extends K{constructor(){super(...arguments),this.content=new ZH(this._client),this.versions=new $H(this._client)}create(e={},t){return this._client.post(`/skills`,Tz({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`,gz,{query:e,...t})}delete(e,t){return this._client.delete(q`/skills/${e}`,t)}};eU.Content=ZH,eU.Versions=$H;var tU=class extends K{create(e,t,n){return this._client.post(q`/uploads/${e}/parts`,Ez({body:t,...n},this._client))}},nU=class extends K{constructor(){super(...arguments),this.parts=new tU(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})}};nU.Parts=tU;var rU=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},iU=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`,gz,{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 rR(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 rU(Array(a).fill(s).map(l)),await this.createAndPoll(e,{file_ids:c})}},aU=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`,gz,{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 rR(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`,hz,{...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}},oU=class extends K{constructor(){super(...arguments),this.files=new aU(this._client),this.fileBatches=new iU(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`,gz,{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`,hz,{body:t,method:`post`,...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}};oU.Files=aU,oU.FileBatches=iU;var sU=class extends K{create(e,t){return this._client.post(`/videos`,Ez({body:e,...t},this._client))}retrieve(e,t){return this._client.get(q`/videos/${e}`,t)}list(e={},t){return this._client.getAPIList(`/videos`,_z,{query:e,...t})}delete(e,t){return this._client.delete(q`/videos/${e}`,t)}createCharacter(e,t){return this._client.post(`/videos/characters`,Ez({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`,Ez({body:e,...t},this._client))}extend(e,t){return this._client.post(`/videos/extensions`,Ez({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`,Tz({body:t,...n},this._client))}},cU,lU,uU,dU=class extends K{constructor(){super(...arguments),cU.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,cU,`m`,lU).call(this,n);let i=J([t]).values,a=W(this,cU,`m`,uU).call(this,i,`webhook-signature`),o=W(this,cU,`m`,uU).call(this,i,`webhook-timestamp`),s=W(this,cU,`m`,uU).call(this,i,`webhook-id`),c=parseInt(o,10);if(isNaN(c))throw new WL(`Invalid webhook timestamp format`);let l=Math.floor(Date.now()/1e3);if(l-c>r)throw new WL(`Webhook timestamp is too old`);if(c>l+r)throw new WL(`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 WL(`The given webhook signature does not match the expected signature`)}};cU=new WeakSet,lU=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`)},uU=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 fU,pU,mU,hU,gU=`workload-identity-auth`,_U=class{constructor({baseURL:e=kV(`OPENAI_BASE_URL`),apiKey:t=kV(`OPENAI_API_KEY`),organization:n=kV(`OPENAI_ORG_ID`)??null,project:r=kV(`OPENAI_PROJECT_ID`)??null,webhookSecret:i=kV(`OPENAI_WEBHOOK_SECRET`)??null,workloadIdentity:a,...o}={}){if(fU.add(this),mU.set(this,void 0),this.completions=new rH(this),this.chat=new dV(this),this.embeddings=new lH(this),this.files=new pH(this),this.images=new wH(this),this.audio=new _V(this),this.moderations=new EH(this),this.models=new TH(this),this.fineTuning=new xH(this),this.graders=new CH(this),this.vectorStores=new oU(this),this.webhooks=new dU(this),this.beta=new nH(this),this.batches=new vV(this),this.uploads=new nU(this),this.responses=new XH(this),this.realtime=new kH(this),this.conversations=new cH(this),this.evals=new fH(this),this.containers=new oH(this),this.skills=new eU(this),this.videos=new sU(this),a){if(t&&t!==gU)throw new G("The `apiKey` and `workloadIdentity` arguments are mutually exclusive; only one can be passed at a time.");t=gU}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&&aR())throw new G(`It looks like you're running in a browser-like environment.
195
196
 
196
197
  This is disabled by default, as it risks exposing your secret API credentials to attackers.
197
198
  If you understand the risks and have appropriate mitigations in place,
@@ -200,22 +201,22 @@ you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
200
201
  new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
201
202
 
202
203
  https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
203
- `);this.baseURL=s.baseURL,this.timeout=s.timeout??TH.DEFAULT_TIMEOUT,this.logger=s.logger??console;let c=`warn`;this.logLevel=c,this.logLevel=sR(s.logLevel,`ClientOptions.logLevel`,this)??sR(VB(`OPENAI_LOG`),`process.env['OPENAI_LOG']`,this)??c,this.fetchOptions=s.fetchOptions,this.maxRetries=s.maxRetries??2,this.fetch=s.fetch??TL(),H(this,EH,AL,`f`),this._options=s,a&&(this._workloadIdentityAuth=new MR(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 q([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(e){return YL(e)}getUserAgent(){return`${this.constructor.name}/JS ${gL}`}defaultIdempotencyKey(){return`stainless-node-retry-${zI()}`}makeStatusError(e,t,n,r){return HI.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 W?e:new W(`Failed to get token from 'apiKey' function: ${e.message}`,{cause:e})}if(typeof t!=`string`||!t)throw new W(`Expected 'apiKey' function argument to return a string but it returned ${t}`);return this.apiKey=t,!0}buildURL(e,t,n){let r=!U(this,wH,`m`,DH).call(this)&&n||this.baseURL,i=oL(e)?new URL(e):new URL(r+(r.endsWith(`/`)&&e.startsWith(`/`)?e.slice(1):e)),a=this.defaultQuery(),o=Object.fromEntries(i.searchParams);return(!uL(a)||!uL(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 CR(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(fR(this).debug(`[${c}] sending request`,pR({retryOfRequestLogID:n,method:r.method,url:o,options:r,headers:a.headers})),r.signal?.aborted)throw new UI;let d=new AbortController,f=await this.fetchWithAuth(o,a,s,d).catch(VI),p=Date.now();if(f instanceof globalThis.Error){let e=`retrying, ${t} attempts remaining`;if(r.signal?.aborted)throw new UI;let i=BI(f)||/timed? ?out/i.test(String(f)+(`cause`in f?String(f.cause):``));if(t)return fR(this).info(`[${c}] connection ${i?`timed out`:`failed`} - ${e}`),fR(this).debug(`[${c}] connection ${i?`timed out`:`failed`} (${e})`,pR({retryOfRequestLogID:n,url:o,durationMs:p-u,message:f.message})),this.retryRequest(r,t,n??c);throw fR(this).info(`[${c}] connection ${i?`timed out`:`failed`} - error; no more retries left`),fR(this).debug(`[${c}] connection ${i?`timed out`:`failed`} (error; no more retries left)`,pR({retryOfRequestLogID:n,url:o,durationMs:p-u,message:f.message})),f instanceof rL||f instanceof iL?f:i?new GI:new WI({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 kL(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 kL(f.body),fR(this).info(`${m} - ${e}`),fR(this).debug(`[${c}] response error (${e})`,pR({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`;fR(this).info(`${m} - ${i}`);let a=await f.text().catch(e=>VI(e).message),o=mL(a),s=o?void 0:a;throw fR(this).debug(`[${c}] response error (${i})`,pR({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 fR(this).info(m),fR(this).debug(`[${c}] response start`,pR({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 ER(this,n,e)}async fetchWithAuth(e,t,n,r){if(this._workloadIdentityAuth){let e=t.headers,n=e.get(`Authorization`);if(!n||n===`Bearer ${OH}`){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 hL(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&&pL(`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=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))}:{},...wL(),"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=q([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:DL(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}:{...U(this,EH,`f`).call(this,{body:e,headers:n}),isStreamingBody:!1}}};TH=J,EH=new WeakMap,wH=new WeakSet,DH=function(){return this.baseURL!==`https://api.openai.com/v1`},J.OpenAI=TH,J.DEFAULT_TIMEOUT=6e5,J.OpenAIError=W,J.APIError=HI,J.APIConnectionError=WI,J.APIConnectionTimeoutError=GI,J.APIUserAbortError=UI,J.NotFoundError=YI,J.ConflictError=XI,J.RateLimitError=QI,J.BadRequestError=KI,J.AuthenticationError=qI,J.InternalServerError=$I,J.PermissionDeniedError=JI,J.UnprocessableEntityError=ZI,J.InvalidWebhookSignatureError=nL,J.toFile=YR,J.Completions=hV,J.Chat=CB,J.Embeddings=xV,J.Files=TV,J.Images=IV,J.Audio=kB,J.Moderations=RV,J.Models=LV,J.FineTuning=NV,J.Graders=FV,J.VectorStores=vH,J.Webhooks=CH,J.Beta=mV,J.Batches=AB,J.Uploads=mH,J.Responses=cH,J.Realtime=VV,J.Conversations=bV,J.Evals=wV,J.Containers=vV,J.Skills=fH,J.Videos=yH;var kH=class extends J{constructor({baseURL:e=VB(`OPENAI_BASE_URL`),apiKey:t=VB(`AZURE_OPENAI_API_KEY`),apiVersion:n=VB(`OPENAI_API_VERSION`),endpoint:r,deployment:i,azureADTokenProvider:a,dangerouslyAllowBrowser:o,...s}={}){if(!n)throw new W(`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 W("Missing credentials. Please pass one of `apiKey` and `azureADTokenProvider`, or set the `AZURE_OPENAI_API_KEY` environment variable.");if(a&&t)throw new W("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 W("Must provide one of the `baseURL` or `endpoint` arguments, or the `AZURE_OPENAI_ENDPOINT` environment variable");e=`${r}/openai`}else if(r)throw new W(`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(AH.has(e.path)&&e.method===`post`&&e.body!==void 0){if(!fL(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`?q([{"api-key":this.apiKey}]):super.authHeaders(e)}},AH=new Set([`/completions`,`/chat/completions`,`/embeddings`,`/audio/transcriptions`,`/audio/translations`,`/audio/speech`,`/images/generations`,`/batches`,`/images/edits`]);function jH(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 MH(e){if(!e||typeof e!=`object`)return e;let t;return e.constructor.name===GI.name&&`message`in e&&typeof e.message==`string`?(t=Error(e.message),t.name=`TimeoutError`):e.constructor.name===UI.name&&`message`in e&&typeof e.message==`string`?(t=Error(e.message),t.name=`AbortError`):t=jH(e)?m.fromError(e):`status`in e&&e.status===400&&`message`in e&&typeof e.message==`string`&&e.message.includes(`tool_calls`)?RI(e,`INVALID_TOOL_RESULTS`):`status`in e&&e.status===401?RI(e,`MODEL_AUTHENTICATION`):`status`in e&&e.status===429?RI(e,`MODEL_RATE_LIMIT`):`status`in e&&e.status===404?RI(e,`MODEL_NOT_FOUND`):e,t}var NH=e=>e();function PH(e){return e?!!(/^o\d/.test(e??``)||e.startsWith(`gpt-5`)&&!e.startsWith(`gpt-5-chat`)):!1}function FH(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 IH(e){return e.metadata?.filename??e.metadata?.name??e.metadata?.title}var LH=`LC_AUTOGENERATED`;function RH(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'.`),LH)}function zH(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(!Qt.isInstance(e))throw Error(`Invalid generic chat message`);return FH(e);default:throw Error(`Unknown message type: ${t}`)}}function BH(e){return!!(e.includes(`gpt-5.2-pro`)||e.includes(`gpt-5.4-pro`)||e.includes(`gpt-5.5-pro`)||e.includes(`codex`))}function VH(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 HH(e){return typeof Headers<`u`&&typeof e==`object`&&!!e&&Object.prototype.toString.call(e)===`[object Headers]`}function UH(e){let t=NH(()=>{if(HH(e))return e;if(Array.isArray(e))return new Headers(e);if(typeof e==`object`&&e&&`values`in e&&HH(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 WH(){let e=dr();return(e===`node`||e===`deno`)&&(e=`(${e}/${process.version}; ${process.platform}; ${process.arch})`),e}function GH(e,t=!1,n=`1.0.0`){let r=UH(e),i=WH(),a=`langchainjs${t?`-azure`:``}-openai`;return{...r,"User-Agent":r[`User-Agent`]?`${a}/${n} (${i})${r[`User-Agent`]}`:`${a}/${n} (${i})`}}function KH(e,t){let n;return n=MO(e)?ej(e):e,t?.strict!==void 0&&(n.function.strict=t.strict),n}function qH(e){return e.anyOf!==void 0&&Array.isArray(e.anyOf)}function JH(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(YH(n.parameters,0)),t.push(`}) => any;`)):t.push(`type ${n.name} = () => any;`),t.push(``);return t.push(`} // namespace functions`),t.join(`
204
- `)}function YH(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}: ${XH(i,t)},`):n.push(`${r}?: ${XH(i,t)},`);return n.map(e=>` `.repeat(t)+e).join(`
205
- `)}function XH(e,t){if(qH(e))return e.anyOf.map(e=>XH(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[`{`,YH(e,t+2),`}`].join(`
206
- `);case`array`:return e.items?`${XH(e.items,t)}[]`:`any[]`;default:return``}}function ZH(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 QH(e){return`type`in e&&e.type!==`function`}function $H(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 eU(e){return typeof e==`object`&&!!e&&`type`in e&&e.type!==`function`}function tU(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 nU(e){return`type`in e&&e.type===`custom`&&`custom`in e&&typeof e.custom==`object`&&e.custom!==null}function rU(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 iU(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 aU(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`tool_call`&&`isComputerTool`in e&&e.isComputerTool===!0}function oU(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`tool_call`&&`isCustomTool`in e&&e.isCustomTool===!0}function sU(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 cU(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 lU=Symbol(`Let zodToJsonSchema decide on which parser to use`),uU={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`},dU=e=>typeof e==`string`?{...uU,basePath:[`#`],definitions:{},name:e}:{...uU,basePath:[`#`],definitions:{},...e},fU=e=>`_def`in e?e._def:e;function pU(e){if(!e)return!0;for(let t in e)return!1;return!0}var mU=e=>{let t=dU(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])=>[fU(n),{def:fU(n),path:[...t.basePath,t.definitionPath,e],jsonSchema:void 0}]))}};function hU(e,t,n,r){r?.errorMessages&&n&&(e.errorMessage={...e.errorMessage,[t]:n})}function gU(e,t,n,r,i){e[t]=n,hU(e,t,r,i)}function _U(){return{}}function vU(e,t){let n={type:`array`};return e.type?._def?.typeName!==L.ZodAny&&(n.items=iW(e.type._def,{...t,currentPath:[...t.currentPath,`items`]})),e.minLength&&gU(n,`minItems`,e.minLength.value,e.minLength.message,t),e.maxLength&&gU(n,`maxItems`,e.maxLength.value,e.maxLength.message,t),e.exactLength&&(gU(n,`minItems`,e.exactLength.value,e.exactLength.message,t),gU(n,`maxItems`,e.exactLength.value,e.exactLength.message,t)),n}function yU(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?gU(n,`minimum`,r.value,r.message,t):gU(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),gU(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?gU(n,`maximum`,r.value,r.message,t):gU(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),gU(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:gU(n,`multipleOf`,r.value,r.message,t);break}return n}function bU(){return{type:`boolean`}}function xU(e,t){return iW(e.type._def,t)}var SU=(e,t)=>iW(e.innerType._def,t);function CU(e,t,n){let r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((n,r)=>CU(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 wU(e,t)}}var wU=(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`:gU(n,`minimum`,r.value,r.message,t);break;case`max`:gU(n,`maximum`,r.value,r.message,t);break}return n};function TU(e,t){return{...iW(e.innerType._def,t),default:e.defaultValue()}}function EU(e,t,n){return t.effectStrategy===`input`?iW(e.schema._def,t,n):{}}function DU(e){return{type:`string`,enum:[...e.values]}}var OU=e=>`type`in e&&e.type===`string`?!1:`allOf`in e;function kU(e,t){let n=[iW(e.left._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]}),iW(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(OU(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 AU(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 jU,MU={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:()=>(jU===void 0&&(jU=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)),jU),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 NU(e,t){let n={type:`string`};function r(e){return t.patternStrategy===`escape`?PU(e):e}if(e.checks)for(let i of e.checks)switch(i.kind){case`min`:gU(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,i.value):i.value,i.message,t);break;case`max`:gU(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`:FU(n,`email`,i.message,t);break;case`format:idn-email`:FU(n,`idn-email`,i.message,t);break;case`pattern:zod`:IU(n,MU.email,i.message,t);break}break;case`url`:FU(n,`uri`,i.message,t);break;case`uuid`:FU(n,`uuid`,i.message,t);break;case`regex`:IU(n,i.regex,i.message,t);break;case`cuid`:IU(n,MU.cuid,i.message,t);break;case`cuid2`:IU(n,MU.cuid2,i.message,t);break;case`startsWith`:IU(n,RegExp(`^${r(i.value)}`),i.message,t);break;case`endsWith`:IU(n,RegExp(`${r(i.value)}$`),i.message,t);break;case`datetime`:FU(n,`date-time`,i.message,t);break;case`date`:FU(n,`date`,i.message,t);break;case`time`:FU(n,`time`,i.message,t);break;case`duration`:FU(n,`duration`,i.message,t);break;case`length`:gU(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,i.value):i.value,i.message,t),gU(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,i.value):i.value,i.message,t);break;case`includes`:IU(n,RegExp(r(i.value)),i.message,t);break;case`ip`:i.version!==`v6`&&FU(n,`ipv4`,i.message,t),i.version!==`v4`&&FU(n,`ipv6`,i.message,t);break;case`emoji`:IU(n,MU.emoji,i.message,t);break;case`ulid`:IU(n,MU.ulid,i.message,t);break;case`base64`:switch(t.base64Strategy){case`format:binary`:FU(n,`binary`,i.message,t);break;case`contentEncoding:base64`:gU(n,`contentEncoding`,`base64`,i.message,t);break;case`pattern:zod`:IU(n,MU.base64,i.message,t);break}break;case`nanoid`:IU(n,MU.nanoid,i.message,t);case`toLowerCase`:case`toUpperCase`:case`trim`:break;default:(e=>{})(i)}return n}var PU=e=>Array.from(e).map(e=>/[a-zA-Z0-9]/.test(e)?e:`\\${e}`).join(``),FU=(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}}})):gU(e,`format`,t,n,r)},IU=(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:LU(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):gU(e,`pattern`,LU(t,r),n,r)},LU=(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
204
+ `);this.baseURL=s.baseURL,this.timeout=s.timeout??pU.DEFAULT_TIMEOUT,this.logger=s.logger??console;let c=`warn`;this.logLevel=c,this.logLevel=YR(s.logLevel,`ClientOptions.logLevel`,this)??YR(kV(`OPENAI_LOG`),`process.env['OPENAI_LOG']`,this)??c,this.fetchOptions=s.fetchOptions,this.maxRetries=s.maxRetries??2,this.fetch=s.fetch??pR(),U(this,mU,vR,`f`),this._options=s,a&&(this._workloadIdentityAuth=new bz(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 LR(e)}getUserAgent(){return`${this.constructor.name}/JS ${iR}`}defaultIdempotencyKey(){return`stainless-node-retry-${DL()}`}makeStatusError(e,t,n,r){return AL.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,fU,`m`,hU).call(this)&&n||this.baseURL,i=JL(e)?new URL(e):new URL(r+(r.endsWith(`/`)&&e.startsWith(`/`)?e.slice(1):e)),a=this.defaultQuery(),o=Object.fromEntries(i.searchParams);return(!QL(a)||!QL(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 dz(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(ez(this).debug(`[${c}] sending request`,tz({retryOfRequestLogID:n,method:r.method,url:o,options:r,headers:a.headers})),r.signal?.aborted)throw new jL;let d=new AbortController,f=await this.fetchWithAuth(o,a,s,d).catch(kL),p=Date.now();if(f instanceof globalThis.Error){let e=`retrying, ${t} attempts remaining`;if(r.signal?.aborted)throw new jL;let i=OL(f)||/timed? ?out/i.test(String(f)+(`cause`in f?String(f.cause):``));if(t)return ez(this).info(`[${c}] connection ${i?`timed out`:`failed`} - ${e}`),ez(this).debug(`[${c}] connection ${i?`timed out`:`failed`} (${e})`,tz({retryOfRequestLogID:n,url:o,durationMs:p-u,message:f.message})),this.retryRequest(r,t,n??c);throw ez(this).info(`[${c}] connection ${i?`timed out`:`failed`} - error; no more retries left`),ez(this).debug(`[${c}] connection ${i?`timed out`:`failed`} (error; no more retries left)`,tz({retryOfRequestLogID:n,url:o,durationMs:p-u,message:f.message})),f instanceof GL||f instanceof KL?f:i?new NL:new ML({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 _R(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 _R(f.body),ez(this).info(`${m} - ${e}`),ez(this).debug(`[${c}] response error (${e})`,tz({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`;ez(this).info(`${m} - ${i}`);let a=await f.text().catch(e=>kL(e).message),o=nR(a),s=o?void 0:a;throw ez(this).debug(`[${c}] response error (${i})`,tz({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 ez(this).info(m),ez(this).debug(`[${c}] response start`,tz({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 mz(this,n,e)}async fetchWithAuth(e,t,n,r){if(this._workloadIdentityAuth){let e=t.headers,n=e.get(`Authorization`);if(!n||n===`Bearer ${gU}`){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 rR(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&&tR(`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))}:{},...fR(),"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:hR(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,mU,`f`).call(this,{body:e,headers:n}),isStreamingBody:!1}}};pU=_U,mU=new WeakMap,fU=new WeakSet,hU=function(){return this.baseURL!==`https://api.openai.com/v1`},_U.OpenAI=pU,_U.DEFAULT_TIMEOUT=6e5,_U.OpenAIError=G,_U.APIError=AL,_U.APIConnectionError=ML,_U.APIConnectionTimeoutError=NL,_U.APIUserAbortError=jL,_U.NotFoundError=LL,_U.ConflictError=RL,_U.RateLimitError=BL,_U.BadRequestError=PL,_U.AuthenticationError=FL,_U.InternalServerError=VL,_U.PermissionDeniedError=IL,_U.UnprocessableEntityError=zL,_U.InvalidWebhookSignatureError=WL,_U.toFile=Lz,_U.Completions=rH,_U.Chat=dV,_U.Embeddings=lH,_U.Files=pH,_U.Images=wH,_U.Audio=_V,_U.Moderations=EH,_U.Models=TH,_U.FineTuning=xH,_U.Graders=CH,_U.VectorStores=oU,_U.Webhooks=dU,_U.Beta=nH,_U.Batches=vV,_U.Uploads=nU,_U.Responses=XH,_U.Realtime=kH,_U.Conversations=cH,_U.Evals=fH,_U.Containers=oH,_U.Skills=eU,_U.Videos=sU;var vU=class extends _U{constructor({baseURL:e=kV(`OPENAI_BASE_URL`),apiKey:t=kV(`AZURE_OPENAI_API_KEY`),apiVersion:n=kV(`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(yU.has(e.path)&&e.method===`post`&&e.body!==void 0){if(!eR(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)}},yU=new Set([`/completions`,`/chat/completions`,`/embeddings`,`/audio/transcriptions`,`/audio/translations`,`/audio/speech`,`/images/generations`,`/batches`,`/images/edits`]);function bU(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 xU(e){if(!e||typeof e!=`object`)return e;let t;return e.constructor.name===NL.name&&`message`in e&&typeof e.message==`string`?(t=Error(e.message),t.name=`TimeoutError`):e.constructor.name===jL.name&&`message`in e&&typeof e.message==`string`?(t=Error(e.message),t.name=`AbortError`):t=bU(e)?m.fromError(e):`status`in e&&e.status===400&&`message`in e&&typeof e.message==`string`&&e.message.includes(`tool_calls`)?EL(e,`INVALID_TOOL_RESULTS`):`status`in e&&e.status===401?EL(e,`MODEL_AUTHENTICATION`):`status`in e&&e.status===429?EL(e,`MODEL_RATE_LIMIT`):`status`in e&&e.status===404?EL(e,`MODEL_NOT_FOUND`):e,t}var SU=e=>e();function CU(e){return e?!!(/^o\d/.test(e??``)||e.startsWith(`gpt-5`)&&!e.startsWith(`gpt-5-chat`)):!1}function wU(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 TU(e){return e.metadata?.filename??e.metadata?.name??e.metadata?.title}var EU=`LC_AUTOGENERATED`;function DU(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'.`),EU)}function OU(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(!Qt.isInstance(e))throw Error(`Invalid generic chat message`);return wU(e);default:throw Error(`Unknown message type: ${t}`)}}function kU(e){return!!(e.includes(`gpt-5.2-pro`)||e.includes(`gpt-5.4-pro`)||e.includes(`gpt-5.5-pro`)||e.includes(`codex`))}function AU(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 jU(e){return typeof Headers<`u`&&typeof e==`object`&&!!e&&Object.prototype.toString.call(e)===`[object Headers]`}function MU(e){let t=SU(()=>{if(jU(e))return e;if(Array.isArray(e))return new Headers(e);if(typeof e==`object`&&e&&`values`in e&&jU(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 NU(){let e=dr();return(e===`node`||e===`deno`)&&(e=`(${e}/${process.version}; ${process.platform}; ${process.arch})`),e}function PU(e,t=!1,n=`1.0.0`){let r=MU(e),i=NU(),a=`langchainjs${t?`-azure`:``}-openai`;return{...r,"User-Agent":r[`User-Agent`]?`${a}/${n} (${i})${r[`User-Agent`]}`:`${a}/${n} (${i})`}}function FU(e,t){let n;return n=jO(e)?$A(e):e,t?.strict!==void 0&&(n.function.strict=t.strict),n}function IU(e){return e.anyOf!==void 0&&Array.isArray(e.anyOf)}function LU(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(RU(n.parameters,0)),t.push(`}) => any;`)):t.push(`type ${n.name} = () => any;`),t.push(``);return t.push(`} // namespace functions`),t.join(`
205
+ `)}function RU(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}: ${zU(i,t)},`):n.push(`${r}?: ${zU(i,t)},`);return n.map(e=>` `.repeat(t)+e).join(`
206
+ `)}function zU(e,t){if(IU(e))return e.anyOf.map(e=>zU(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[`{`,RU(e,t+2),`}`].join(`
207
+ `);case`array`:return e.items?`${zU(e.items,t)}[]`:`any[]`;default:return``}}function BU(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 VU(e){return`type`in e&&e.type!==`function`}function HU(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 UU(e){return typeof e==`object`&&!!e&&`type`in e&&e.type!==`function`}function WU(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 GU(e){return`type`in e&&e.type===`custom`&&`custom`in e&&typeof e.custom==`object`&&e.custom!==null}function KU(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 qU(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 JU(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`tool_call`&&`isComputerTool`in e&&e.isComputerTool===!0}function YU(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`tool_call`&&`isCustomTool`in e&&e.isCustomTool===!0}function XU(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 ZU(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 QU=Symbol(`Let zodToJsonSchema decide on which parser to use`),$U={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`},eW=e=>typeof e==`string`?{...$U,basePath:[`#`],definitions:{},name:e}:{...$U,basePath:[`#`],definitions:{},...e},tW=e=>`_def`in e?e._def:e;function nW(e){if(!e)return!0;for(let t in e)return!1;return!0}var rW=e=>{let t=eW(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])=>[tW(n),{def:tW(n),path:[...t.basePath,t.definitionPath,e],jsonSchema:void 0}]))}};function iW(e,t,n,r){r?.errorMessages&&n&&(e.errorMessage={...e.errorMessage,[t]:n})}function aW(e,t,n,r,i){e[t]=n,iW(e,t,r,i)}function oW(){return{}}function sW(e,t){let n={type:`array`};return e.type?._def?.typeName!==R.ZodAny&&(n.items=qW(e.type._def,{...t,currentPath:[...t.currentPath,`items`]})),e.minLength&&aW(n,`minItems`,e.minLength.value,e.minLength.message,t),e.maxLength&&aW(n,`maxItems`,e.maxLength.value,e.maxLength.message,t),e.exactLength&&(aW(n,`minItems`,e.exactLength.value,e.exactLength.message,t),aW(n,`maxItems`,e.exactLength.value,e.exactLength.message,t)),n}function cW(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?aW(n,`minimum`,r.value,r.message,t):aW(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),aW(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?aW(n,`maximum`,r.value,r.message,t):aW(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),aW(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:aW(n,`multipleOf`,r.value,r.message,t);break}return n}function lW(){return{type:`boolean`}}function uW(e,t){return qW(e.type._def,t)}var dW=(e,t)=>qW(e.innerType._def,t);function fW(e,t,n){let r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((n,r)=>fW(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 pW(e,t)}}var pW=(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`:aW(n,`minimum`,r.value,r.message,t);break;case`max`:aW(n,`maximum`,r.value,r.message,t);break}return n};function mW(e,t){return{...qW(e.innerType._def,t),default:e.defaultValue()}}function hW(e,t,n){return t.effectStrategy===`input`?qW(e.schema._def,t,n):{}}function gW(e){return{type:`string`,enum:[...e.values]}}var _W=e=>`type`in e&&e.type===`string`?!1:`allOf`in e;function vW(e,t){let n=[qW(e.left._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]}),qW(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(_W(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 yW(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 bW,xW={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:()=>(bW===void 0&&(bW=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)),bW),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 SW(e,t){let n={type:`string`};function r(e){return t.patternStrategy===`escape`?CW(e):e}if(e.checks)for(let i of e.checks)switch(i.kind){case`min`:aW(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,i.value):i.value,i.message,t);break;case`max`:aW(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`:wW(n,`email`,i.message,t);break;case`format:idn-email`:wW(n,`idn-email`,i.message,t);break;case`pattern:zod`:TW(n,xW.email,i.message,t);break}break;case`url`:wW(n,`uri`,i.message,t);break;case`uuid`:wW(n,`uuid`,i.message,t);break;case`regex`:TW(n,i.regex,i.message,t);break;case`cuid`:TW(n,xW.cuid,i.message,t);break;case`cuid2`:TW(n,xW.cuid2,i.message,t);break;case`startsWith`:TW(n,RegExp(`^${r(i.value)}`),i.message,t);break;case`endsWith`:TW(n,RegExp(`${r(i.value)}$`),i.message,t);break;case`datetime`:wW(n,`date-time`,i.message,t);break;case`date`:wW(n,`date`,i.message,t);break;case`time`:wW(n,`time`,i.message,t);break;case`duration`:wW(n,`duration`,i.message,t);break;case`length`:aW(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,i.value):i.value,i.message,t),aW(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,i.value):i.value,i.message,t);break;case`includes`:TW(n,RegExp(r(i.value)),i.message,t);break;case`ip`:i.version!==`v6`&&wW(n,`ipv4`,i.message,t),i.version!==`v4`&&wW(n,`ipv6`,i.message,t);break;case`emoji`:TW(n,xW.emoji,i.message,t);break;case`ulid`:TW(n,xW.ulid,i.message,t);break;case`base64`:switch(t.base64Strategy){case`format:binary`:wW(n,`binary`,i.message,t);break;case`contentEncoding:base64`:aW(n,`contentEncoding`,`base64`,i.message,t);break;case`pattern:zod`:TW(n,xW.base64,i.message,t);break}break;case`nanoid`:TW(n,xW.nanoid,i.message,t);case`toLowerCase`:case`toUpperCase`:case`trim`:break;default:(e=>{})(i)}return n}var CW=e=>Array.from(e).map(e=>/[a-zA-Z0-9]/.test(e)?e:`\\${e}`).join(``),wW=(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}}})):aW(e,`format`,t,n,r)},TW=(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:EW(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):aW(e,`pattern`,EW(t,r),n,r)},EW=(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
207
208
  ]))`;continue}else if(i[e]===`$`){a+=`($|(?=[\r
208
- ]))`;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 RU(e,t){if(t.target===`openApi3`&&e.keyType?._def.typeName===L.ZodEnum)return{type:`object`,required:e.keyType._def.values,properties:e.keyType._def.values.reduce((n,r)=>({...n,[r]:iW(e.valueType._def,{...t,currentPath:[...t.currentPath,`properties`,r]})??{}}),{}),additionalProperties:!1};let n={type:`object`,additionalProperties:iW(e.valueType._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]})??{}};if(t.target===`openApi3`)return n;if(e.keyType?._def.typeName===L.ZodString&&e.keyType._def.checks?.length){let r=Object.entries(NU(e.keyType._def,t)).reduce((e,[t,n])=>t===`type`?e:{...e,[t]:n},{});return{...n,propertyNames:r}}else if(e.keyType?._def.typeName===L.ZodEnum)return{...n,propertyNames:{enum:e.keyType._def.values}};return n}function zU(e,t){return t.mapStrategy===`record`?RU(e,t):{type:`array`,maxItems:125,items:{type:`array`,items:[iW(e.keyType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`0`]})||{},iW(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`1`]})||{}],minItems:2,maxItems:2}}}function BU(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 VU(){return{not:{}}}function HU(e){return e.target===`openApi3`?{enum:[`null`],nullable:!0}:{type:`null`}}var UU={ZodString:`string`,ZodNumber:`number`,ZodBigInt:`integer`,ZodBoolean:`boolean`,ZodNull:`null`};function WU(e,t){if(t.target===`openApi3`)return GU(e,t);let n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(e=>e._def.typeName in UU&&(!e._def.checks||!e._def.checks.length))){let e=n.reduce((e,t)=>{let n=UU[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 GU(e,t)}var GU=(e,t)=>{let n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((e,n)=>iW(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 KU(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:UU[e.innerType._def.typeName],nullable:!0}:{type:[UU[e.innerType._def.typeName],`null`]};if(t.target===`openApi3`){let n=iW(e.innerType._def,{...t,currentPath:[...t.currentPath]});return n&&`$ref`in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let n=iW(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`0`]});return n&&{anyOf:[n,{type:`null`}]}}function qU(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`,hU(n,`type`,r.message,t);break;case`min`:t.target===`jsonSchema7`?r.inclusive?gU(n,`minimum`,r.value,r.message,t):gU(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),gU(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?gU(n,`maximum`,r.value,r.message,t):gU(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),gU(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:gU(n,`multipleOf`,r.value,r.message,t);break}return n}function JU(e,t){return t.removeAdditionalStrategy===`strict`?e.catchall._def.typeName===`ZodNever`?e.unknownKeys!==`strict`:iW(e.catchall._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]})??!0:e.catchall._def.typeName===`ZodNever`?e.unknownKeys===`passthrough`:iW(e.catchall._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]})??!0}function YU(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=iW(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:JU(e,t)};return n.required.length||delete n.required,n}var XU=(e,t)=>{if(t.propertyPath&&t.currentPath.slice(0,t.propertyPath.length).toString()===t.propertyPath.toString())return iW(e.innerType._def,{...t,currentPath:t.currentPath});let n=iW(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`1`]});return n?{anyOf:[{not:{}},n]}:{}},ZU=(e,t)=>{if(t.pipeStrategy===`input`)return iW(e.in._def,t);if(t.pipeStrategy===`output`)return iW(e.out._def,t);let n=iW(e.in._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]});return{allOf:[n,iW(e.out._def,{...t,currentPath:[...t.currentPath,`allOf`,n?`1`:`0`]})].filter(e=>e!==void 0)}};function QU(e,t){return iW(e.type._def,t)}function $U(e,t){let n={type:`array`,uniqueItems:!0,items:iW(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`]})};return e.minSize&&gU(n,`minItems`,e.minSize.value,e.minSize.message,t),e.maxSize&&gU(n,`maxItems`,e.maxSize.value,e.maxSize.message,t),n}function eW(e,t){return e.rest?{type:`array`,minItems:e.items.length,items:e.items.map((e,n)=>iW(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[]),additionalItems:iW(e.rest._def,{...t,currentPath:[...t.currentPath,`additionalItems`]})}:{type:`array`,minItems:e.items.length,maxItems:e.items.length,items:e.items.map((e,n)=>iW(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[])}}function tW(){return{not:{}}}function nW(){return{}}var rW=(e,t)=>iW(e.innerType._def,t);function iW(e,t,n=!1){let r=t.seen.get(e);if(t.override){let i=t.override?.(e,t,r,n);if(i!==lU)return i}if(r&&!n){let e=aW(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=sW(e,e.typeName,t,n);return a&&cW(e,t,a),i.jsonSchema=a,a}var aW=(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:oW(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}},oW=(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(`/`)},sW=(e,t,n,r)=>{switch(t){case L.ZodString:return NU(e,n);case L.ZodNumber:return qU(e,n);case L.ZodObject:return YU(e,n);case L.ZodBigInt:return yU(e,n);case L.ZodBoolean:return bU();case L.ZodDate:return CU(e,n);case L.ZodUndefined:return tW();case L.ZodNull:return HU(n);case L.ZodArray:return vU(e,n);case L.ZodUnion:case L.ZodDiscriminatedUnion:return WU(e,n);case L.ZodIntersection:return kU(e,n);case L.ZodTuple:return eW(e,n);case L.ZodRecord:return RU(e,n);case L.ZodLiteral:return AU(e,n);case L.ZodEnum:return DU(e);case L.ZodNativeEnum:return BU(e);case L.ZodNullable:return KU(e,n);case L.ZodOptional:return XU(e,n);case L.ZodMap:return zU(e,n);case L.ZodSet:return $U(e,n);case L.ZodLazy:return iW(e.getter()._def,n);case L.ZodPromise:return QU(e,n);case L.ZodNaN:case L.ZodNever:return VU();case L.ZodEffects:return EU(e,n,r);case L.ZodAny:return _U();case L.ZodUnknown:return nW();case L.ZodDefault:return TU(e,n);case L.ZodBranded:return xU(e,n);case L.ZodReadonly:return rW(e,n);case L.ZodCatch:return SU(e,n);case L.ZodPipeline:return ZU(e,n);case L.ZodFunction:case L.ZodVoid:case L.ZodSymbol:return;default:return(e=>void 0)(t)}},cW=(e,t,n)=>(e.description&&(n.description=e.description,t.markdownDescription&&(n.markdownDescription=e.description)),n),lW=(e,t)=>{let n=mU(t),r=typeof t==`string`?t:t?.nameStrategy===`title`?void 0:t?.name,i=iW(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(pU(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]=iW(fU(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 uW(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 fW(t,[],t)}function dW(e){if(typeof e==`boolean`)return!1;if(e.type===`null`)return!0;for(let t of e.oneOf??[])if(dW(t))return!0;for(let t of e.anyOf??[])if(dW(t))return!0;return!1}function fW(e,t,n){if(typeof e==`boolean`)throw TypeError(`Expected object schema but got boolean; path=${t.join(`/`)}`);if(!mW(e))throw TypeError(`Expected ${JSON.stringify(e)} to be an object; path=${t.join(`/`)}`);let r=e.$defs;if(mW(r))for(let[e,i]of Object.entries(r))fW(i,[...t,`$defs`,e],n);let i=e.definitions;if(mW(i))for(let[e,r]of Object.entries(i))fW(r,[...t,`definitions`,e],n);e.type===`object`&&!(`additionalProperties`in e)&&(e.additionalProperties=!1);let a=e.required??[],o=e.properties;if(mW(o)){for(let[e,n]of Object.entries(o))if(!dW(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,fW(r,[...t,`properties`,e],n)]))}let s=e.items;mW(s)&&(e.items=fW(s,[...t,`items`],n));let c=e.anyOf;Array.isArray(c)&&(e.anyOf=c.map((e,r)=>fW(e,[...t,`anyOf`,String(r)],n)));let l=e.allOf;if(Array.isArray(l))if(l.length===1){let r=fW(l[0],[...t,`allOf`,`0`],n);Object.assign(e,r),delete e.allOf}else e.allOf=l.map((e,r)=>fW(e,[...t,`allOf`,String(r)],n));e.default===null&&delete e.default;let u=e.$ref;if(u&&hW(e,1)){if(typeof u!=`string`)throw TypeError(`Received non-string $ref - ${u}; path=${t.join(`/`)}`);let r=pW(n,u);if(typeof r==`boolean`)throw Error(`Expected \`$ref: ${u}\` to resolve to an object schema but got boolean`);if(!mW(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,fW(e,t,n)}return e}function pW(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(!mW(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 mW(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function hW(e,t){let n=0;for(let r in e)if(n++,n>t)return!0;return!1}function gW(e,t){return lW(e,{openaiStrictMode:!0,name:t.name,nameStrategy:`duplicate-ref`,$refStrategy:`extract-to-root`,nullableStrategy:`property`})}function _W(e){return uW(vg(e,{target:`draft-7`}))}function vW(e){return`_zod`in e}function yW(e,t,n){return nz({type:`json_schema`,json_schema:{...n,name:t,strict:!0,schema:vW(e)?_W(e):gW(e,{name:t})}},t=>e.parse(JSON.parse(t)))}var bW=[`jsonSchema`,`functionCalling`,`jsonMode`];function xW(e,t){if(t!==void 0&&!bW.includes(t))throw Error(`Invalid method: ${t}. Supported methods are: ${bW.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 SW(e,t){let n={...e};return Object.defineProperties(n,{$brand:{value:`auto-parseable-response-format`,enumerable:!1},$parseRaw:{value:t,enumerable:!1}}),n}function CW(e,t,n){if(bg(e))return yW(e,t,n);if(yg(e))return SW({type:`json_schema`,json_schema:{...n,name:t,strict:!0,schema:Db(e,{cycles:`ref`,reused:`ref`,override(e){e.jsonSchema.title=t}})}},t=>Vd(e,JSON.parse(t)));throw Error(`Unsupported schema response format`)}function wW(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 TW={"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 EW(e,t){return typeof e==`string`?{model:e,...t??{}}:e??t}var DW=class extends cE{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??mr(`OPENAI_API_KEY`),this.organization=e?.configuration?.organization??mr(`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(!PH(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&&Sg(e.json_schema.schema)?CW(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=VH({baseURL:this.clientConfig.baseURL}),t={...this.clientConfig,baseURL:e,timeout:this.timeout,maxRetries:0};t.baseURL||delete t.baseURL,t.defaultHeaders=GH(t.defaultHeaders),this.client=new J(t)}return{...this.clientConfig,...e}}_convertChatOpenAIToolToCompletionsTool(e,t){return tU(e)?cU(e.metadata.customTool):qw(e)?t?.strict===void 0?e:{...e,function:{...e.function,strict:t.strict}}:KH(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(QH(e)||tU(e))return e;if($H(e))return e.extras.providerToolDefinition;let t=this._convertChatOpenAIToolToCompletionsTool(e,{strict:n});return MO(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(zH(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=JH(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 MH(e)}})}get profile(){return TW[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=xW(this.model,t?.method);if(s===`jsonMode`){r=AT(i);let e=Db(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=Db(i),o={name:a??`extract`,description:Ag(e),schema:Sg(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}}}),Sg(i)||By(i)){let e=AT(i);r=Qb.from(async t=>`parsed`in t.additional_kwargs?t.additional_kwargs.parsed:e.invoke(t.content))}else r=new dT}else{let e=a??`extract`,o=Db(i),s;Sg(i)||By(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=jT(i,e)}return MT(n,r,o)}},OW={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=Te({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=we(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=we(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=Te({dataUrl:e.url}),n=RH(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=RH(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`)}},kW=({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(wT(e,{returnId:!0}))}catch(t){o.push(ET(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 Jt({content:wW(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 Qt(e.content||``,e.role??`unknown`)}},AW=({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 cn({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 Zt({content:a,tool_call_chunks:n,additional_kwargs:o,id:t.id,response_metadata:s})}else if(i===`system`)return new pn({content:a,response_metadata:s});else if(i===`developer`)return new pn({content:a,response_metadata:s,additional_kwargs:{__openai_role__:`developer`}});else if(i===`function`)return new rn({content:a,additional_kwargs:o,name:e.name,response_metadata:s});else if(i===`tool`)return new yt({content:a,additional_kwargs:o,tool_call_id:e.tool_call_id,response_metadata:s});else return new $t({content:a,role:i,response_metadata:s})},jW=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=gn(()=>{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=RH(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}}}},MW=({message:e,model:t})=>{let n=zH(e);if(n===`system`&&PH(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`&&vt.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=jW(t);e&&(yield e)}}return{role:`user`,content:Array.from(r(e.contentBlocks))}},NW=({messages:e,model:t})=>e.flatMap(e=>{if(`output_version`in e.response_metadata&&e.response_metadata?.output_version===`v1`)return MW({message:e});let n=zH(e);n===`system`&&PH(t)&&(n=`developer`);let r=typeof e.content==`string`?e.content:e.content.flatMap(e=>ve(e)?Ee(e,OW):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),Jt.isInstance(e)&&e.tool_calls?.length?i.tool_calls=e.tool_calls.map(TT):(e.additional_kwargs.tool_calls!=null&&(i.tool_calls=e.additional_kwargs.tool_calls),vt.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}),PW=class extends DW{constructor(e,t){super(EW(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:ZH(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),PH(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=NW({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}:{}},Yt(n.message)&&(n.message.usage_metadata=r),n.message=new Jt(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=NW({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 Cu({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 Cu({message:new Zt({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 MH(e)}})}_convertCompletionsDeltaToBaseMessageChunk(e,t,n){return AW({delta:e,rawResponse:t,includeRawResponse:this.__includeRawResponse,defaultRole:n})}_convertCompletionsMessageToBaseMessage(e,t){return kW({message:e,rawResponse:t,includeRawResponse:this.__includeRawResponse})}},FW={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`},IW={azureOpenAIApiKey:`AZURE_OPENAI_API_KEY`},LW=[`azureOpenAIApiKey`,`azureOpenAIApiVersion`,`azureOpenAIBasePath`,`azureOpenAIEndpoint`,`azureOpenAIApiInstanceName`,`azureOpenAIApiDeploymentName`,`deploymentName`,`openAIApiKey`,`openAIApiVersion`];function RW(e,t){return typeof e==`string`?{model:e,deploymentName:e,azureOpenAIApiDeploymentName:e,...t??{}}:e??t}function zW(e){if(this.azureOpenAIApiKey=e?.azureOpenAIApiKey??(typeof e?.openAIApiKey==`string`?e?.openAIApiKey:void 0)??(typeof e?.apiKey==`string`?e?.apiKey:void 0)??mr(`AZURE_OPENAI_API_KEY`),this.azureOpenAIApiInstanceName=e?.azureOpenAIApiInstanceName??mr(`AZURE_OPENAI_API_INSTANCE_NAME`),this.azureOpenAIApiDeploymentName=e?.azureOpenAIApiDeploymentName??e?.deploymentName??mr(`AZURE_OPENAI_API_DEPLOYMENT_NAME`),this.azureOpenAIApiVersion=e?.azureOpenAIApiVersion??e?.openAIApiVersion??mr(`AZURE_OPENAI_API_VERSION`),this.azureOpenAIBasePath=e?.azureOpenAIBasePath??mr(`AZURE_OPENAI_BASE_PATH`),this.azureOpenAIEndpoint=e?.azureOpenAIEndpoint??mr(`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 BW(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=VH(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=GH(i.defaultHeaders,!0,`2.0.0`),this.client=new kH({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 VW(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 HW=class extends PW{azureOpenAIApiVersion;azureOpenAIApiKey;azureADTokenProvider;azureOpenAIApiInstanceName;azureOpenAIApiDeploymentName;azureOpenAIBasePath;azureOpenAIEndpoint;_llmType(){return`azure_openai`}get lc_aliases(){return{...super.lc_aliases,...FW}}get lc_secrets(){return{...super.lc_secrets,...IW}}get lc_serializable_keys(){return[...super.lc_serializable_keys,...LW]}getLsParams(e){let t=super.getLsParams(e);return t.ls_provider=`azure`,t}constructor(e,t){let n=RW(e,t);super(n),zW.call(this,n)}_getClientOptions(e){return BW.call(this,e)}toJSON(){return VW.call(this,super.toJSON())}},UW=`__openai_function_call_ids__`;function WW(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 GW(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 KW=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}},qW=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(WW),...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(wT(e,{returnId:!0}))}catch(t){let n;typeof t==`object`&&t&&`message`in t&&typeof t.message==`string`&&(n=t.message),i.push(ET(e,n))}s[UW]??={},a.id&&(s[UW][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=rU(a);e?r.push(e):i.push(ET(a,`Malformed custom tool call`))}else if(a.type===`computer_call`){let e=iU(a);e?r.push(e):i.push(ET(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 Jt({id:t,content:n,tool_calls:r,invalid_tool_calls:i,usage_metadata:KW(e.usage),additional_kwargs:s,response_metadata:o})},JW=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}},YW=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:[WW(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[UW]={[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=qW(e.response);r=KW(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 Cu({text:t.map(e=>e.text).join(``),message:new Zt({id:s,content:t,tool_call_chunks:i,usage_metadata:r,additional_kwargs:o,response_metadata:a}),generationInfo:n})},XW=e=>{let t=Jt.isInstance(e)&&e.response_metadata?.model_provider===`openai`;function*n(){let n=NH(()=>{try{let t=zH(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=NH(()=>{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=IH(e);return{type:`input_file`,file_id:e.fileId,...t?{filename:t}:{}}}if(e.url){let t=IH(e);return{...t?{filename:t}:{},type:`input_file`,file_url:e.url}}if(e.data){let t=RH(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=NH(()=>{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=NH(()=>{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())},ZW=({messages:e,zdrEnabled:t,model:n})=>e.flatMap(e=>{let r=e.response_metadata;if(r?.output_version===`v1`)return XW(e);let i=e.additional_kwargs,a=zH(e);if(a===`system`&&PH(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=JW(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:NH(()=>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(GW)}}return e.type===`output_text`||e.type===`refusal`?e:[]})),phase:NH(()=>{if(Array.isArray(s))return s.find(e=>`phase`in e&&typeof e.phase==`string`)?.phase})};n.push(r)}let c=i?.[UW];Jt.isInstance(e)&&e.tool_calls?.length?n.push(...e.tool_calls.map(e=>oU(e)?{type:`custom_tool_call`,id:e.call_id,call_id:e.id??``,input:e.args.input,name:e.name}:aU(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}),ve(e)?Ee(e,OW):e.type===`text`?{type:`input_text`,text:e.text}:e.type===`image_url`?{type:`input_image`,image_url:NH(()=>{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:NH(()=>{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}`),[]}),QW=class extends DW{constructor(e,t){super(EW(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:eU(e?.tool_choice)?e?.tool_choice:(()=>{let t=ZH(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:ZW({messages:e,zdrEnabled:this.zdrEnabled??!1,model:this.model}),...r,stream:!1},{signal:t?.signal,...t?.options});return{generations:[{text:n.output_text,message:qW(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:ZW({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=YW(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 MH(e)}})}_reduceChatOpenAITools(e,t){let n=[];for(let r of e)if(QH(r))r.type===`image_generation`&&t?.stream&&(r.partial_images=1),n.push(r);else if(tU(r)){let e=r.metadata.customTool;n.push({type:`custom`,name:e.name,description:e.description,format:e.format})}else if(qw(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 nU(r)&&n.push(sU(r));return n}},$W=class extends QW{azureOpenAIApiVersion;azureOpenAIApiKey;azureADTokenProvider;azureOpenAIApiInstanceName;azureOpenAIApiDeploymentName;azureOpenAIBasePath;azureOpenAIEndpoint;_llmType(){return`azure_openai`}get lc_aliases(){return{...super.lc_aliases,...FW}}get lc_secrets(){return{...super.lc_secrets,...IW}}get lc_serializable_keys(){return[...super.lc_serializable_keys,...LW]}getLsParams(e){let t=super.getLsParams(e);return t.ls_provider=`azure`,t}constructor(e,t){let n=RW(e,t);super(n),zW.call(this,n)}_getClientOptions(e){return BW.call(this,e)}toJSON(){return VW.call(this,super.toJSON())}},eG=class e extends DW{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=EW(e,t);super(n),this.fields=n,this.useResponsesApi=n?.useResponsesApi??!1,this.responses=n?.responses??new QW(n),this.completions=n?.completions??new PW(n)}_useResponsesApi(e){let t=e?.tools?.some(QH),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(nU)||e?.tools?.some(tU);return this.useResponsesApi||t||n||r||BH(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}},tG=class extends eG{azureOpenAIApiVersion;azureOpenAIApiKey;azureADTokenProvider;azureOpenAIApiInstanceName;azureOpenAIApiDeploymentName;azureOpenAIBasePath;azureOpenAIEndpoint;_llmType(){return`azure_openai`}get lc_aliases(){return{...super.lc_aliases,...FW}}get lc_secrets(){return{...super.lc_secrets,...IW}}get lc_serializable_keys(){return[...super.lc_serializable_keys,...LW]}getLsParams(e){let t=super.getLsParams(e);return t.ls_provider=`azure`,t}constructor(e,t){let n=RW(e,t);super({...n,completions:new HW(n),responses:new $W(n)}),zW.call(this,n)}_getStructuredOutputMethod(e){let t={...e};return this.model.startsWith(`gpt-4o`)&&t?.method===void 0?`functionCalling`:super._getStructuredOutputMethod(t)}toJSON(){return VW.call(this,super.toJSON())}};B({action:Vk([B({type:$k(`screenshot`)}),B({type:$k(`click`),x:Ek(),y:Ek(),button:Zk([`left`,`right`,`wheel`,`back`,`forward`]).default(`left`)}),B({type:$k(`double_click`),x:Ek(),y:Ek(),button:Zk([`left`,`right`,`wheel`,`back`,`forward`]).default(`left`)}),B({type:$k(`drag`),path:Rk(B({x:Ek(),y:Ek()}))}),B({type:$k(`keypress`),keys:Rk(z())}),B({type:$k(`move`),x:Ek(),y:Ek()}),B({type:$k(`scroll`),x:Ek(),y:Ek(),scroll_x:Ek(),scroll_y:Ek()}),B({type:$k(`type`),text:z()}),B({type:$k(`wait`),duration:Ek().optional()})])}),Vk([B({type:$k(`exec`),command:Rk(z()),env:Yk(z(),z()).optional(),working_directory:z().optional(),timeout_ms:Ek().optional(),user:z().optional()})]),B({commands:Rk(z()).describe(`Array of shell commands to execute`),timeout_ms:Ek().optional().describe(`Optional timeout in milliseconds for the commands`),max_output_length:Ek().optional().describe(`Optional maximum number of characters to return from each command`)}),Vk([B({type:$k(`create_file`),path:z(),diff:z()}),B({type:$k(`update_file`),path:z(),diff:z()}),B({type:$k(`delete_file`),path:z()})]);function nG(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(nG):typeof t[e]==`object`&&t[e]!==null&&(t[e]=nG(t[e])));return t}return e}function rG(e){let{$schema:t,...n}=nG(Sg(e)||By(e)?Db(e):e);return n}function iG(e){let{$schema:t,...n}=nG(e);return n}function aG(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))aG(i,t,[...n,e]);r.items&&aG(r.items,t,[...n,`[]`]);for(let e of[`anyOf`,`oneOf`,`allOf`]){let i=r[e];Array.isArray(i)&&i.forEach((r,i)=>aG(r,t,[...n,`${e}[${i}]`]))}r.additionalProperties&&typeof r.additionalProperties==`object`&&aG(r.additionalProperties,t,[...n,`additionalProperties`])}var oG=`__gemini_function_call_thought_signatures__`,sG=`ErYCCrMCAdHtim9kOoOkrPiCNVsmlpMIKd7ZMxgiFbVQOkgp7nlLcDMzVsZwIzvuT7nQROivoXA72ccC2lSDvR0Gh7dkWaGuj7ctv6t7ZceHnecx0QYa+ix8tYpRfjhyWozQ49lWiws6+YGjCt10KRTyWsZ2h6O7iHTYJwKIRwGUHRKy/qK/6kFxJm5ML00gLq4D8s5Z6DBpp2ZlR+uF4G8jJgeWQgyHWVdx2wGYElaceVAc66tZdPQRdOHpWtgYSI1YdaXgVI8KHY3/EfNc2YqqMIulvkDBAnuMhkAjV9xmBa54Tq+ih3Im4+r3DzqhGqYdsSkhS0kZMwte4Hjs65dZzCw9lANxIqYi1DJ639WNPYihp/DCJCos7o+/EeSPJaio5sgWDyUnMGkY1atsJZ+m7pj7DD5tvQ==`,cG=e=>e();function lG(e){return Qt.isInstance(e)?e.role:e.type}function uG(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 dG(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 fG(e,t){return t.map(e=>Yt(e)?e.tool_calls??[]:[]).flat().find(t=>t.id===e.tool_call_id)?.name}function pG(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=Te({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 mG(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=Te({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=Te({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=Te({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 hG(e,t){if(ve(e))return Ee(e,mG(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 dG(e);else if(e.type===`image`)return pG(e,`image/png`);else if(e.type===`video`)return pG(e,`video/mp4`);else if(e.type===`audio`)return pG(e,`audio/mpeg`);else if(e.type===`file`)return pG(e,`application/octet-stream`);else if(e.type===`text-plain`)return`text`in e&&typeof e.text==`string`?{text:e.text}:pG(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 gG(e,t,n,r){if(xt(e)){let r=e.name??fG(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=>hG(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=>hG(e,t)).filter(e=>e!==void 0));let o=e.additional_kwargs?.[oG];return Yt(e)&&e.tool_calls?.length&&(i=e.tool_calls.map(e=>{let t=cG(()=>{if(e.id){let t=o?.[e.id];if(t)return t}return r?.includes(`gemini-3`)?sG:``});return{functionCall:{name:e.name,args:e.args},...t?{thoughtSignature:t}:{}}})),[...a,...i]}function _G(e,t,n=!1,r){return e.reduce((i,a,o)=>{if(!mt(a))throw Error(`Unsupported message input`);let s=lG(a);if(s===`system`&&o!==0)throw Error(`System message should be the first one`);let c=uG(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=gG(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 vG(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:qn()}),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 Jt({content:o??``,tool_calls:a?.map(e=>({type:`tool_call`,id:e.id,name:e.functionCall.name,args:e.functionCall.args})),additional_kwargs:{...i,[oG]: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 yG(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:qn()}),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 Cu({text:c,message:new Zt({content:o||``,name:r?r.role:void 0,tool_call_chunks:l,additional_kwargs:{[oG]:u},response_metadata:{model_provider:`google-genai`},usage_metadata:t.usageMetadata}),generationInfo:i})}function bG(e){return e.every(e=>`functionDeclarations`in e&&Array.isArray(e.functionDeclarations))?e:[{functionDeclarations:e.map(e=>{if(MO(e)){let t=rG(e.schema);return t.type===`object`&&`properties`in t&&Object.keys(t.properties).length===0?{name:e.name,description:e.description}:(aG(t,e.name),{name:e.name,description:e.description,parameters:t})}if(qw(e)){let t=iG(e.function.parameters);return aG(t,e.function.name),{name:e.function.name,description:e.function.description??`A function available to call.`,parameters:t}}return e})}]}function xG(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 SG=class extends $w{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 tT(`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 Eg(this.zodSchema,e);if(t.success)return t.data;throw new tT(`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)}},CG;(function(e){e.STRING=`string`,e.NUMBER=`number`,e.INTEGER=`integer`,e.BOOLEAN=`boolean`,e.ARRAY=`array`,e.OBJECT=`object`})(CG||={});var wG;(function(e){e.LANGUAGE_UNSPECIFIED=`language_unspecified`,e.PYTHON=`python`})(wG||={});var TG;(function(e){e.OUTCOME_UNSPECIFIED=`outcome_unspecified`,e.OUTCOME_OK=`outcome_ok`,e.OUTCOME_FAILED=`outcome_failed`,e.OUTCOME_DEADLINE_EXCEEDED=`outcome_deadline_exceeded`})(TG||={});var EG=[`user`,`model`,`function`,`system`],DG;(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`})(DG||={});var OG;(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`})(OG||={});var kG;(function(e){e.HARM_PROBABILITY_UNSPECIFIED=`HARM_PROBABILITY_UNSPECIFIED`,e.NEGLIGIBLE=`NEGLIGIBLE`,e.LOW=`LOW`,e.MEDIUM=`MEDIUM`,e.HIGH=`HIGH`})(kG||={});var AG;(function(e){e.BLOCKED_REASON_UNSPECIFIED=`BLOCKED_REASON_UNSPECIFIED`,e.SAFETY=`SAFETY`,e.OTHER=`OTHER`})(AG||={});var jG;(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`})(jG||={});var MG;(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`})(MG||={});var NG;(function(e){e.MODE_UNSPECIFIED=`MODE_UNSPECIFIED`,e.AUTO=`AUTO`,e.ANY=`ANY`,e.NONE=`NONE`})(NG||={});var PG;(function(e){e.MODE_UNSPECIFIED=`MODE_UNSPECIFIED`,e.MODE_DYNAMIC=`MODE_DYNAMIC`})(PG||={});var FG=class extends Error{constructor(e){super(`[GoogleGenerativeAI Error]: ${e}`)}},IG=class extends FG{constructor(e,t){super(e),this.response=t}},LG=class extends FG{constructor(e,t,n,r){super(e),this.status=t,this.statusText=n,this.errorDetails=r}},RG=class extends FG{},zG=class extends FG{},BG=`https://generativelanguage.googleapis.com`,VG=`v1beta`,HG=`0.24.1`,UG=`genai-js`,WG;(function(e){e.GENERATE_CONTENT=`generateContent`,e.STREAM_GENERATE_CONTENT=`streamGenerateContent`,e.COUNT_TOKENS=`countTokens`,e.EMBED_CONTENT=`embedContent`,e.BATCH_EMBED_CONTENTS=`batchEmbedContents`})(WG||={});var GG=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||VG,t=`${this.requestOptions?.baseUrl||BG}/${e}/${this.model}:${this.task}`;return this.stream&&(t+=`?alt=sse`),t}};function KG(e){let t=[];return e?.apiClient&&t.push(e.apiClient),t.push(`${UG}/${HG}`),t.join(` `)}async function qG(e){let t=new Headers;t.append(`Content-Type`,`application/json`),t.append(`x-goog-api-client`,KG(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 RG(`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 RG(`Cannot set reserved header name ${e}`);if(e===`x-goog-api-client`)throw new RG(`Header name ${e} can only be set using the apiClient field`);t.append(e,r)}}return t}async function JG(e,t,n,r,i,a){let o=new GG(e,t,n,r,a);return{url:o.toString(),fetchOptions:Object.assign(Object.assign({},$G(a)),{method:`POST`,headers:await qG(o),body:i})}}async function YG(e,t,n,r,i,a={},o=fetch){let{url:s,fetchOptions:c}=await JG(e,t,n,r,i,a);return XG(s,c,o)}async function XG(e,t,n=fetch){let r;try{r=await n(e,t)}catch(t){ZG(t,e)}return r.ok||await QG(r,e),r}function ZG(e,t){let n=e;throw n.name===`AbortError`?(n=new zG(`Request aborted when fetching ${t.toString()}: ${e.message}`),n.stack=e.stack):e instanceof LG||e instanceof RG||(n=new FG(`Error fetching from ${t.toString()}: ${e.message}`),n.stack=e.stack),n}async function QG(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 LG(`Error fetching from ${t.toString()}: [${e.status} ${e.statusText}] ${n}`,e.status,e.statusText,r)}function $G(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 eK(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.`),iK(e.candidates[0]))throw new IG(`${aK(e)}`,e);return tK(e)}else if(e.promptFeedback)throw new IG(`Text not available. ${aK(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.`),iK(e.candidates[0]))throw new IG(`${aK(e)}`,e);return console.warn(`response.functionCall() is deprecated. Use response.functionCalls() instead.`),nK(e)[0]}else if(e.promptFeedback)throw new IG(`Function call not available. ${aK(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.`),iK(e.candidates[0]))throw new IG(`${aK(e)}`,e);return nK(e)}else if(e.promptFeedback)throw new IG(`Function call not available. ${aK(e)}`,e)},e}function tK(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+`
209
- `+n.executableCode.code+"\n```\n"),n.codeExecutionResult&&t.push("\n```\n"+n.codeExecutionResult.output+"\n```\n");return t.length>0?t.join(``):``}function nK(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 rK=[jG.RECITATION,jG.SAFETY,jG.LANGUAGE];function iK(e){return!!e.finishReason&&rK.includes(e.finishReason)}function aK(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];iK(n)&&(t+=`Candidate was blocked due to ${n.finishReason}`,n.finishMessage&&(t+=`: ${n.finishMessage}`))}return t}function oK(e){return this instanceof oK?(this.v=e,this):new oK(e)}function sK(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 oK?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 cK=/^data\: (.*)(?:\n\n|\r\r|\r\n\r\n)/;function lK(e){let[t,n]=fK(e.body.pipeThrough(new TextDecoderStream(`utf8`,{fatal:!0}))).tee();return{stream:dK(t),response:uK(n)}}async function uK(e){let t=[],n=e.getReader();for(;;){let{done:e,value:r}=await n.read();if(e)return eK(pK(t));t.push(r)}}function dK(e){return sK(this,arguments,function*(){let t=e.getReader();for(;;){let{value:e,done:n}=yield oK(t.read());if(n)break;yield yield oK(eK(e))}})}function fK(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 FG(`Failed to parse stream`));return}e.close();return}n+=t;let a=n.match(cK),o;for(;a;){try{o=JSON.parse(a[1])}catch{e.error(new FG(`Error parsing JSON response: "${a[1]}"`));return}e.enqueue(o),n=n.substring(a[0].length),a=n.match(cK)}return r()}).catch(e=>{let t=e;throw t.stack=e.stack,t=t.name===`AbortError`?new zG(`Request aborted when reading from the stream`):new FG(`Error reading from the stream`),t})}}})}function pK(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 mK(e,t,n,r){return lK(await YG(t,WG.STREAM_GENERATE_CONTENT,e,!0,JSON.stringify(n),r))}async function hK(e,t,n,r){return{response:eK(await(await YG(t,WG.GENERATE_CONTENT,e,!1,JSON.stringify(n),r)).json())}}function gK(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 _K(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 vK(t)}function vK(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 FG(`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 FG(`No content is provided for sending chat message.`);return r?t:n}function yK(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 RG(`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=_K(e);n.contents=[t]}return{generateContentRequest:n}}function bK(e){let t;return t=e.contents?e:{contents:[_K(e)]},e.systemInstruction&&(t.systemInstruction=gK(e.systemInstruction)),t}function xK(e){return typeof e==`string`||Array.isArray(e)?{content:_K(e)}:e}var SK=[`text`,`inlineData`,`functionCall`,`functionResponse`,`executableCode`,`codeExecutionResult`],CK={user:[`text`,`inlineData`],function:[`functionResponse`],model:[`text`,`functionCall`,`executableCode`,`codeExecutionResult`],system:[`text`]};function wK(e){let t=!1;for(let n of e){let{role:e,parts:r}=n;if(!t&&e!==`user`)throw new FG(`First content should be with role 'user', got ${e}`);if(!EG.includes(e))throw new FG(`Each item should include role field. Got ${e} but valid roles are: ${JSON.stringify(EG)}`);if(!Array.isArray(r))throw new FG(`Content should have 'parts' property with an array of Parts`);if(r.length===0)throw new FG(`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 SK)t in e&&(i[t]+=1);let a=CK[e];for(let t of SK)if(!a.includes(t)&&i[t]>0)throw new FG(`Content with role '${e}' can't contain '${t}' part`);t=!0}}function TK(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 EK=`SILENT_ERROR`,DK=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&&(wK(n.history),this._history=n.history)}async getHistory(){return await this._sendPromise,this._history}async sendMessage(e,t={}){await this._sendPromise;let n=_K(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(()=>hK(this._apiKey,this.model,r,i)).then(e=>{if(TK(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=aK(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=_K(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=mK(this._apiKey,this.model,r,i);return this._sendPromise=this._sendPromise.then(()=>a).catch(e=>{throw Error(EK)}).then(e=>e.response).then(e=>{if(TK(e)){this._history.push(n);let t=Object.assign({},e.candidates[0].content);t.role||=`model`,this._history.push(t)}else{let t=aK(e);t&&console.warn(`sendMessageStream() was unsuccessful. ${t}. Inspect response object for details.`)}}).catch(e=>{e.message!==EK&&console.error(e)}),a}};async function OK(e,t,n,r){return(await YG(t,WG.COUNT_TOKENS,e,!1,JSON.stringify(n),r)).json()}async function kK(e,t,n,r){return(await YG(t,WG.EMBED_CONTENT,e,!1,JSON.stringify(n),r)).json()}async function AK(e,t,n,r){let i=n.requests.map(e=>Object.assign(Object.assign({},e),{model:t}));return(await YG(t,WG.BATCH_EMBED_CONTENTS,e,!1,JSON.stringify({requests:i}),r)).json()}var jK=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=gK(t.systemInstruction),this.cachedContent=t.cachedContent}async generateContent(e,t={}){let n=bK(e),r=Object.assign(Object.assign({},this._requestOptions),t);return hK(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=bK(e),r=Object.assign(Object.assign({},this._requestOptions),t);return mK(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 DK(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=yK(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 OK(this.apiKey,this.model,n,r)}async embedContent(e,t={}){let n=xK(e),r=Object.assign(Object.assign({},this._requestOptions),t);return kK(this.apiKey,this.model,n,r)}async batchEmbedContents(e,t={}){let n=Object.assign(Object.assign({},this._requestOptions),t);return AK(this.apiKey,this.model,e,n)}},MK=class{constructor(e){this.apiKey=e}getGenerativeModel(e,t){if(!e.model)throw new FG(`Must provide a model name. Example: genai.getGenerativeModel({ model: 'my-model-name' })`);return new jK(this.apiKey,e,t)}getGenerativeModelFromCachedContent(e,t,n){if(!e.name)throw new RG("Cached content must contain a `name` field.");if(!e.model)throw new RG("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 RG(`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 jK(this.apiKey,r,n)}};function NK(e,t){let n=PK(e);return{tools:n,toolConfig:IK(n,t)}}function PK(e){let t=[],n=[];return e.forEach(e=>{if(MO(e)){let[n]=bG([e]);n.functionDeclarations&&t.push(...n.functionDeclarations)}else if(qw(e)){let{functionDeclarations:n}=FK(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 FK(e){return{functionDeclarations:[{name:e.function.name,description:e.function.description,parameters:nG(e.function.parameters)}]}}function IK(e,t){if(!e.length||!t)return;let{toolChoice:n,allowedFunctionNames:r}=t,i={any:NG.ANY,auto:NG.AUTO,none:NG.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:NG.ANY,allowedFunctionNames:[...r??[],...n&&typeof n==`string`?[n]:[]]}}}var LK={"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}},RK=class extends cE{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??mr(`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 MK(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 MK(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:NK(e)?.tools,...t})}invocationParams(e){let t=e?.tools?.length?NK(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=_G(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=xG(o.response.usageMetadata,this.model));let c=vG(o.response,{usageMetadata:s});return c.generations?.length>0&&await n?.handleLLMNewToken(c.generations[0]?.text??``),c}async*_streamResponseChunks(e,t,n){let r=_G(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=xG(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=yG(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 LK[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(Sg(n)||By(n)){let r=rG(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=nG(n.parameters),e=n.name):t={name:e,description:n.description??``,parameters:nG(n)};let i=[{functionDeclarations:[t]}];o=this.bindTools(i).withConfig({allowedFunctionNames:[e]}),s=jT(n,e,SG)}else{let e=rG(n);o=this.withConfig({responseSchema:e}),s=AT(n)}return MT(o,s,a,a?`StructuredOutputRunnable`:`ChatGoogleGenerativeAIStructuredOutput`)}},zK=class extends $w{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 tT(`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 tT(`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 Eg(this.zodSchema,t);if(n.success)return n.data;throw new tT(`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)?BK(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 BK(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 VK(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 HK=B({cache_control:xA().optional().nullable(),defer_loading:Ak().optional(),input_examples:Rk(Pk()).optional(),allowed_callers:Rk(Pk()).optional()}),UK={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 WK(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`thinking`}function GK(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`redacted_thinking`}function KK(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`compaction`}function qK(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`search_result`}function JK(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 YK={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=Te({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}`)}},XK=e=>e();function ZK(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`citation`}function QK(e){function*t(){for(let t of e)ZK(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 $K(e){return typeof e==`string`?e:eq(e)}function eq(e){let t=[];for(let n=0,{length:r}=e;n<r;n++)t.push(String.fromCharCode(e[n]));return btoa(t.join(``))}function tq(e){return(e??``).split(`;`)[0].toLowerCase()}function nq(e,t){if(typeof e==`object`&&e&&t in e)return e[t]}function rq(e,t){let n=nq(t,`cache_control`);n!==void 0&&(e.cache_control=n);let r=nq(t,`citations`);r!==void 0&&(e.citations=r);let i=nq(t,`context`);i!==void 0&&(e.context=i);let a=nq(t,`title`);return a!==void 0&&(e.title=a),e}function iq(e,t){let n=nq(t,`cache_control`);return n!==void 0&&(e.cache_control=n),e}function aq(e){return new Set([`image/jpeg`,`image/png`,`image/gif`,`image/webp`]).has(e)}function oq(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:QK(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=XK(()=>{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(rq({type:`document`,source:{type:`file`,file_id:n.fileId}},e));continue}if(n.url){let r=tq(n.mimeType);if(r===`application/pdf`||r===``){t.push(rq({type:`document`,source:{type:`url`,url:n.url}},e));continue}}if(n.data){let r=tq(n.mimeType);if(r===``||r===`application/pdf`)t.push(rq({type:`document`,source:{type:`base64`,data:$K(n.data),media_type:`application/pdf`}},e));else if(r===`text/plain`)t.push(rq({type:`document`,source:{type:`text`,data:$K(n.data),media_type:`text/plain`}},e));else if(aq(r))t.push(rq({type:`document`,source:{type:`content`,content:[{type:`image`,source:{type:`base64`,data:$K(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(iq({type:`image`,source:{type:`file`,file_id:n.fileId}},e));continue}if(n.url){t.push(iq({type:`image`,source:{type:`url`,url:n.url}},e));continue}if(n.data){let r=tq(n.mimeType)||`image/png`;aq(r)&&t.push(iq({type:`image`,source:{type:`base64`,data:$K(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(rq({type:`document`,source:{type:`text`,data:$K(n.data),media_type:`text/plain`}},n.metadata)):n.type===`non_standard`&&r&&t.push(n.value));return t}function sq(e){let t=Te({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(`
209
+ ]))`;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 DW(e,t){if(t.target===`openApi3`&&e.keyType?._def.typeName===R.ZodEnum)return{type:`object`,required:e.keyType._def.values,properties:e.keyType._def.values.reduce((n,r)=>({...n,[r]:qW(e.valueType._def,{...t,currentPath:[...t.currentPath,`properties`,r]})??{}}),{}),additionalProperties:!1};let n={type:`object`,additionalProperties:qW(e.valueType._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]})??{}};if(t.target===`openApi3`)return n;if(e.keyType?._def.typeName===R.ZodString&&e.keyType._def.checks?.length){let r=Object.entries(SW(e.keyType._def,t)).reduce((e,[t,n])=>t===`type`?e:{...e,[t]:n},{});return{...n,propertyNames:r}}else if(e.keyType?._def.typeName===R.ZodEnum)return{...n,propertyNames:{enum:e.keyType._def.values}};return n}function OW(e,t){return t.mapStrategy===`record`?DW(e,t):{type:`array`,maxItems:125,items:{type:`array`,items:[qW(e.keyType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`0`]})||{},qW(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`1`]})||{}],minItems:2,maxItems:2}}}function kW(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 AW(){return{not:{}}}function jW(e){return e.target===`openApi3`?{enum:[`null`],nullable:!0}:{type:`null`}}var MW={ZodString:`string`,ZodNumber:`number`,ZodBigInt:`integer`,ZodBoolean:`boolean`,ZodNull:`null`};function NW(e,t){if(t.target===`openApi3`)return PW(e,t);let n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(e=>e._def.typeName in MW&&(!e._def.checks||!e._def.checks.length))){let e=n.reduce((e,t)=>{let n=MW[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 PW(e,t)}var PW=(e,t)=>{let n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((e,n)=>qW(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 FW(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:MW[e.innerType._def.typeName],nullable:!0}:{type:[MW[e.innerType._def.typeName],`null`]};if(t.target===`openApi3`){let n=qW(e.innerType._def,{...t,currentPath:[...t.currentPath]});return n&&`$ref`in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let n=qW(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`0`]});return n&&{anyOf:[n,{type:`null`}]}}function IW(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`,iW(n,`type`,r.message,t);break;case`min`:t.target===`jsonSchema7`?r.inclusive?aW(n,`minimum`,r.value,r.message,t):aW(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),aW(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?aW(n,`maximum`,r.value,r.message,t):aW(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),aW(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:aW(n,`multipleOf`,r.value,r.message,t);break}return n}function LW(e,t){return t.removeAdditionalStrategy===`strict`?e.catchall._def.typeName===`ZodNever`?e.unknownKeys!==`strict`:qW(e.catchall._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]})??!0:e.catchall._def.typeName===`ZodNever`?e.unknownKeys===`passthrough`:qW(e.catchall._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]})??!0}function RW(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=qW(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:LW(e,t)};return n.required.length||delete n.required,n}var zW=(e,t)=>{if(t.propertyPath&&t.currentPath.slice(0,t.propertyPath.length).toString()===t.propertyPath.toString())return qW(e.innerType._def,{...t,currentPath:t.currentPath});let n=qW(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`1`]});return n?{anyOf:[{not:{}},n]}:{}},BW=(e,t)=>{if(t.pipeStrategy===`input`)return qW(e.in._def,t);if(t.pipeStrategy===`output`)return qW(e.out._def,t);let n=qW(e.in._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]});return{allOf:[n,qW(e.out._def,{...t,currentPath:[...t.currentPath,`allOf`,n?`1`:`0`]})].filter(e=>e!==void 0)}};function VW(e,t){return qW(e.type._def,t)}function HW(e,t){let n={type:`array`,uniqueItems:!0,items:qW(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`]})};return e.minSize&&aW(n,`minItems`,e.minSize.value,e.minSize.message,t),e.maxSize&&aW(n,`maxItems`,e.maxSize.value,e.maxSize.message,t),n}function UW(e,t){return e.rest?{type:`array`,minItems:e.items.length,items:e.items.map((e,n)=>qW(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[]),additionalItems:qW(e.rest._def,{...t,currentPath:[...t.currentPath,`additionalItems`]})}:{type:`array`,minItems:e.items.length,maxItems:e.items.length,items:e.items.map((e,n)=>qW(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[])}}function WW(){return{not:{}}}function GW(){return{}}var KW=(e,t)=>qW(e.innerType._def,t);function qW(e,t,n=!1){let r=t.seen.get(e);if(t.override){let i=t.override?.(e,t,r,n);if(i!==QU)return i}if(r&&!n){let e=JW(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=XW(e,e.typeName,t,n);return a&&ZW(e,t,a),i.jsonSchema=a,a}var JW=(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:YW(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}},YW=(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(`/`)},XW=(e,t,n,r)=>{switch(t){case R.ZodString:return SW(e,n);case R.ZodNumber:return IW(e,n);case R.ZodObject:return RW(e,n);case R.ZodBigInt:return cW(e,n);case R.ZodBoolean:return lW();case R.ZodDate:return fW(e,n);case R.ZodUndefined:return WW();case R.ZodNull:return jW(n);case R.ZodArray:return sW(e,n);case R.ZodUnion:case R.ZodDiscriminatedUnion:return NW(e,n);case R.ZodIntersection:return vW(e,n);case R.ZodTuple:return UW(e,n);case R.ZodRecord:return DW(e,n);case R.ZodLiteral:return yW(e,n);case R.ZodEnum:return gW(e);case R.ZodNativeEnum:return kW(e);case R.ZodNullable:return FW(e,n);case R.ZodOptional:return zW(e,n);case R.ZodMap:return OW(e,n);case R.ZodSet:return HW(e,n);case R.ZodLazy:return qW(e.getter()._def,n);case R.ZodPromise:return VW(e,n);case R.ZodNaN:case R.ZodNever:return AW();case R.ZodEffects:return hW(e,n,r);case R.ZodAny:return oW();case R.ZodUnknown:return GW();case R.ZodDefault:return mW(e,n);case R.ZodBranded:return uW(e,n);case R.ZodReadonly:return KW(e,n);case R.ZodCatch:return dW(e,n);case R.ZodPipeline:return BW(e,n);case R.ZodFunction:case R.ZodVoid:case R.ZodSymbol:return;default:return(e=>void 0)(t)}},ZW=(e,t,n)=>(e.description&&(n.description=e.description,t.markdownDescription&&(n.markdownDescription=e.description)),n),QW=(e,t)=>{let n=rW(t),r=typeof t==`string`?t:t?.nameStrategy===`title`?void 0:t?.name,i=qW(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(nW(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]=qW(tW(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 $W(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 tG(t,[],t)}function eG(e){if(typeof e==`boolean`)return!1;if(e.type===`null`)return!0;for(let t of e.oneOf??[])if(eG(t))return!0;for(let t of e.anyOf??[])if(eG(t))return!0;return!1}function tG(e,t,n){if(typeof e==`boolean`)throw TypeError(`Expected object schema but got boolean; path=${t.join(`/`)}`);if(!rG(e))throw TypeError(`Expected ${JSON.stringify(e)} to be an object; path=${t.join(`/`)}`);let r=e.$defs;if(rG(r))for(let[e,i]of Object.entries(r))tG(i,[...t,`$defs`,e],n);let i=e.definitions;if(rG(i))for(let[e,r]of Object.entries(i))tG(r,[...t,`definitions`,e],n);e.type===`object`&&!(`additionalProperties`in e)&&(e.additionalProperties=!1);let a=e.required??[],o=e.properties;if(rG(o)){for(let[e,n]of Object.entries(o))if(!eG(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,tG(r,[...t,`properties`,e],n)]))}let s=e.items;rG(s)&&(e.items=tG(s,[...t,`items`],n));let c=e.anyOf;Array.isArray(c)&&(e.anyOf=c.map((e,r)=>tG(e,[...t,`anyOf`,String(r)],n)));let l=e.allOf;if(Array.isArray(l))if(l.length===1){let r=tG(l[0],[...t,`allOf`,`0`],n);Object.assign(e,r),delete e.allOf}else e.allOf=l.map((e,r)=>tG(e,[...t,`allOf`,String(r)],n));e.default===null&&delete e.default;let u=e.$ref;if(u&&iG(e,1)){if(typeof u!=`string`)throw TypeError(`Received non-string $ref - ${u}; path=${t.join(`/`)}`);let r=nG(n,u);if(typeof r==`boolean`)throw Error(`Expected \`$ref: ${u}\` to resolve to an object schema but got boolean`);if(!rG(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,tG(e,t,n)}return e}function nG(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(!rG(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 rG(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function iG(e,t){let n=0;for(let r in e)if(n++,n>t)return!0;return!1}function aG(e,t){return QW(e,{openaiStrictMode:!0,name:t.name,nameStrategy:`duplicate-ref`,$refStrategy:`extract-to-root`,nullableStrategy:`property`})}function oG(e){return $W(vg(e,{target:`draft-7`}))}function sG(e){return`_zod`in e}function cG(e,t,n){return Wz({type:`json_schema`,json_schema:{...n,name:t,strict:!0,schema:sG(e)?oG(e):aG(e,{name:t})}},t=>e.parse(JSON.parse(t)))}var lG=[`jsonSchema`,`functionCalling`,`jsonMode`];function uG(e,t){if(t!==void 0&&!lG.includes(t))throw Error(`Invalid method: ${t}. Supported methods are: ${lG.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 dG(e,t){let n={...e};return Object.defineProperties(n,{$brand:{value:`auto-parseable-response-format`,enumerable:!1},$parseRaw:{value:t,enumerable:!1}}),n}function fG(e,t,n){if(bg(e))return cG(e,t,n);if(yg(e))return dG({type:`json_schema`,json_schema:{...n,name:t,strict:!0,schema:Eb(e,{cycles:`ref`,reused:`ref`,override(e){e.jsonSchema.title=t}})}},t=>Vd(e,JSON.parse(t)));throw Error(`Unsupported schema response format`)}function pG(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 mG={"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 hG(e,t){return typeof e==`string`?{model:e,...t??{}}:e??t}var gG=class extends sE{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??mr(`OPENAI_API_KEY`),this.organization=e?.configuration?.organization??mr(`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(!CU(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&&Sg(e.json_schema.schema)?fG(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=AU({baseURL:this.clientConfig.baseURL}),t={...this.clientConfig,baseURL:e,timeout:this.timeout,maxRetries:0};t.baseURL||delete t.baseURL,t.defaultHeaders=PU(t.defaultHeaders),this.client=new _U(t)}return{...this.clientConfig,...e}}_convertChatOpenAIToolToCompletionsTool(e,t){return WU(e)?ZU(e.metadata.customTool):Kw(e)?t?.strict===void 0?e:{...e,function:{...e.function,strict:t.strict}}:FU(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(VU(e)||WU(e))return e;if(HU(e))return e.extras.providerToolDefinition;let t=this._convertChatOpenAIToolToCompletionsTool(e,{strict:n});return jO(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(OU(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=LU(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 xU(e)}})}get profile(){return mG[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=uG(this.model,t?.method);if(s===`jsonMode`){r=kT(i);let e=Eb(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=Eb(i),o={name:a??`extract`,description:Ag(e),schema:Sg(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}}}),Sg(i)||zy(i)){let e=kT(i);r=Zb.from(async t=>`parsed`in t.additional_kwargs?t.additional_kwargs.parsed:e.invoke(t.content))}else r=new uT}else{let e=a??`extract`,o=Eb(i),s;Sg(i)||zy(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=AT(i,e)}return jT(n,r,o)}},_G={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=Te({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=we(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=we(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=Te({dataUrl:e.url}),n=DU(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=DU(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`)}},vG=({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(CT(e,{returnId:!0}))}catch(t){o.push(TT(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 Jt({content:pG(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 Qt(e.content||``,e.role??`unknown`)}},yG=({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 cn({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 Zt({content:a,tool_call_chunks:n,additional_kwargs:o,id:t.id,response_metadata:s})}else if(i===`system`)return new pn({content:a,response_metadata:s});else if(i===`developer`)return new pn({content:a,response_metadata:s,additional_kwargs:{__openai_role__:`developer`}});else if(i===`function`)return new rn({content:a,additional_kwargs:o,name:e.name,response_metadata:s});else if(i===`tool`)return new yt({content:a,additional_kwargs:o,tool_call_id:e.tool_call_id,response_metadata:s});else return new $t({content:a,role:i,response_metadata:s})},bG=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=gn(()=>{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=DU(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}}}},xG=({message:e,model:t})=>{let n=OU(e);if(n===`system`&&CU(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`&&vt.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=bG(t);e&&(yield e)}}return{role:`user`,content:Array.from(r(e.contentBlocks))}},SG=({messages:e,model:t})=>e.flatMap(e=>{if(`output_version`in e.response_metadata&&e.response_metadata?.output_version===`v1`)return xG({message:e});let n=OU(e);n===`system`&&CU(t)&&(n=`developer`);let r=typeof e.content==`string`?e.content:e.content.flatMap(e=>ve(e)?Ee(e,_G):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),Jt.isInstance(e)&&e.tool_calls?.length?i.tool_calls=e.tool_calls.map(wT):(e.additional_kwargs.tool_calls!=null&&(i.tool_calls=e.additional_kwargs.tool_calls),vt.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}),CG=class extends gG{constructor(e,t){super(hG(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:BU(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),CU(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=SG({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}:{}},Yt(n.message)&&(n.message.usage_metadata=r),n.message=new Jt(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=SG({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 Cu({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 Cu({message:new Zt({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 xU(e)}})}_convertCompletionsDeltaToBaseMessageChunk(e,t,n){return yG({delta:e,rawResponse:t,includeRawResponse:this.__includeRawResponse,defaultRole:n})}_convertCompletionsMessageToBaseMessage(e,t){return vG({message:e,rawResponse:t,includeRawResponse:this.__includeRawResponse})}},wG={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`},TG={azureOpenAIApiKey:`AZURE_OPENAI_API_KEY`},EG=[`azureOpenAIApiKey`,`azureOpenAIApiVersion`,`azureOpenAIBasePath`,`azureOpenAIEndpoint`,`azureOpenAIApiInstanceName`,`azureOpenAIApiDeploymentName`,`deploymentName`,`openAIApiKey`,`openAIApiVersion`];function DG(e,t){return typeof e==`string`?{model:e,deploymentName:e,azureOpenAIApiDeploymentName:e,...t??{}}:e??t}function OG(e){if(this.azureOpenAIApiKey=e?.azureOpenAIApiKey??(typeof e?.openAIApiKey==`string`?e?.openAIApiKey:void 0)??(typeof e?.apiKey==`string`?e?.apiKey:void 0)??mr(`AZURE_OPENAI_API_KEY`),this.azureOpenAIApiInstanceName=e?.azureOpenAIApiInstanceName??mr(`AZURE_OPENAI_API_INSTANCE_NAME`),this.azureOpenAIApiDeploymentName=e?.azureOpenAIApiDeploymentName??e?.deploymentName??mr(`AZURE_OPENAI_API_DEPLOYMENT_NAME`),this.azureOpenAIApiVersion=e?.azureOpenAIApiVersion??e?.openAIApiVersion??mr(`AZURE_OPENAI_API_VERSION`),this.azureOpenAIBasePath=e?.azureOpenAIBasePath??mr(`AZURE_OPENAI_BASE_PATH`),this.azureOpenAIEndpoint=e?.azureOpenAIEndpoint??mr(`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 kG(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=AU(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=PU(i.defaultHeaders,!0,`2.0.0`),this.client=new vU({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 AG(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 jG=class extends CG{azureOpenAIApiVersion;azureOpenAIApiKey;azureADTokenProvider;azureOpenAIApiInstanceName;azureOpenAIApiDeploymentName;azureOpenAIBasePath;azureOpenAIEndpoint;_llmType(){return`azure_openai`}get lc_aliases(){return{...super.lc_aliases,...wG}}get lc_secrets(){return{...super.lc_secrets,...TG}}get lc_serializable_keys(){return[...super.lc_serializable_keys,...EG]}getLsParams(e){let t=super.getLsParams(e);return t.ls_provider=`azure`,t}constructor(e,t){let n=DG(e,t);super(n),OG.call(this,n)}_getClientOptions(e){return kG.call(this,e)}toJSON(){return AG.call(this,super.toJSON())}},MG=`__openai_function_call_ids__`;function NG(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 PG(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 FG=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}},IG=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(NG),...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(CT(e,{returnId:!0}))}catch(t){let n;typeof t==`object`&&t&&`message`in t&&typeof t.message==`string`&&(n=t.message),i.push(TT(e,n))}s[MG]??={},a.id&&(s[MG][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=KU(a);e?r.push(e):i.push(TT(a,`Malformed custom tool call`))}else if(a.type===`computer_call`){let e=qU(a);e?r.push(e):i.push(TT(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 Jt({id:t,content:n,tool_calls:r,invalid_tool_calls:i,usage_metadata:FG(e.usage),additional_kwargs:s,response_metadata:o})},LG=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}},RG=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:[NG(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[MG]={[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=IG(e.response);r=FG(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 Cu({text:t.map(e=>e.text).join(``),message:new Zt({id:s,content:t,tool_call_chunks:i,usage_metadata:r,additional_kwargs:o,response_metadata:a}),generationInfo:n})},zG=e=>{let t=Jt.isInstance(e)&&e.response_metadata?.model_provider===`openai`;function*n(){let n=SU(()=>{try{let t=OU(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=SU(()=>{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=TU(e);return{type:`input_file`,file_id:e.fileId,...t?{filename:t}:{}}}if(e.url){let t=TU(e);return{...t?{filename:t}:{},type:`input_file`,file_url:e.url}}if(e.data){let t=DU(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=SU(()=>{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=SU(()=>{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())},BG=({messages:e,zdrEnabled:t,model:n})=>e.flatMap(e=>{let r=e.response_metadata;if(r?.output_version===`v1`)return zG(e);let i=e.additional_kwargs,a=OU(e);if(a===`system`&&CU(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=LG(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:SU(()=>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(PG)}}return e.type===`output_text`||e.type===`refusal`?e:[]})),phase:SU(()=>{if(Array.isArray(s))return s.find(e=>`phase`in e&&typeof e.phase==`string`)?.phase})};n.push(r)}let c=i?.[MG];Jt.isInstance(e)&&e.tool_calls?.length?n.push(...e.tool_calls.map(e=>YU(e)?{type:`custom_tool_call`,id:e.call_id,call_id:e.id??``,input:e.args.input,name:e.name}:JU(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}),ve(e)?Ee(e,_G):e.type===`text`?{type:`input_text`,text:e.text}:e.type===`image_url`?{type:`input_image`,image_url:SU(()=>{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:SU(()=>{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}`),[]}),VG=class extends gG{constructor(e,t){super(hG(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:UU(e?.tool_choice)?e?.tool_choice:(()=>{let t=BU(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:BG({messages:e,zdrEnabled:this.zdrEnabled??!1,model:this.model}),...r,stream:!1},{signal:t?.signal,...t?.options});return{generations:[{text:n.output_text,message:IG(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:BG({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=RG(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 xU(e)}})}_reduceChatOpenAITools(e,t){let n=[];for(let r of e)if(VU(r))r.type===`image_generation`&&t?.stream&&(r.partial_images=1),n.push(r);else if(WU(r)){let e=r.metadata.customTool;n.push({type:`custom`,name:e.name,description:e.description,format:e.format})}else if(Kw(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 GU(r)&&n.push(XU(r));return n}},HG=class extends VG{azureOpenAIApiVersion;azureOpenAIApiKey;azureADTokenProvider;azureOpenAIApiInstanceName;azureOpenAIApiDeploymentName;azureOpenAIBasePath;azureOpenAIEndpoint;_llmType(){return`azure_openai`}get lc_aliases(){return{...super.lc_aliases,...wG}}get lc_secrets(){return{...super.lc_secrets,...TG}}get lc_serializable_keys(){return[...super.lc_serializable_keys,...EG]}getLsParams(e){let t=super.getLsParams(e);return t.ls_provider=`azure`,t}constructor(e,t){let n=DG(e,t);super(n),OG.call(this,n)}_getClientOptions(e){return kG.call(this,e)}toJSON(){return AG.call(this,super.toJSON())}},UG=class e extends gG{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=hG(e,t);super(n),this.fields=n,this.useResponsesApi=n?.useResponsesApi??!1,this.responses=n?.responses??new VG(n),this.completions=n?.completions??new CG(n)}_useResponsesApi(e){let t=e?.tools?.some(VU),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(GU)||e?.tools?.some(WU);return this.useResponsesApi||t||n||r||kU(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}},WG=class extends UG{azureOpenAIApiVersion;azureOpenAIApiKey;azureADTokenProvider;azureOpenAIApiInstanceName;azureOpenAIApiDeploymentName;azureOpenAIBasePath;azureOpenAIEndpoint;_llmType(){return`azure_openai`}get lc_aliases(){return{...super.lc_aliases,...wG}}get lc_secrets(){return{...super.lc_secrets,...TG}}get lc_serializable_keys(){return[...super.lc_serializable_keys,...EG]}getLsParams(e){let t=super.getLsParams(e);return t.ls_provider=`azure`,t}constructor(e,t){let n=DG(e,t);super({...n,completions:new jG(n),responses:new HG(n)}),OG.call(this,n)}_getStructuredOutputMethod(e){let t={...e};return this.model.startsWith(`gpt-4o`)&&t?.method===void 0?`functionCalling`:super._getStructuredOutputMethod(t)}toJSON(){return AG.call(this,super.toJSON())}};V({action:Bk([V({type:Qk(`screenshot`)}),V({type:Qk(`click`),x:Tk(),y:Tk(),button:Xk([`left`,`right`,`wheel`,`back`,`forward`]).default(`left`)}),V({type:Qk(`double_click`),x:Tk(),y:Tk(),button:Xk([`left`,`right`,`wheel`,`back`,`forward`]).default(`left`)}),V({type:Qk(`drag`),path:Lk(V({x:Tk(),y:Tk()}))}),V({type:Qk(`keypress`),keys:Lk(B())}),V({type:Qk(`move`),x:Tk(),y:Tk()}),V({type:Qk(`scroll`),x:Tk(),y:Tk(),scroll_x:Tk(),scroll_y:Tk()}),V({type:Qk(`type`),text:B()}),V({type:Qk(`wait`),duration:Tk().optional()})])}),Bk([V({type:Qk(`exec`),command:Lk(B()),env:Jk(B(),B()).optional(),working_directory:B().optional(),timeout_ms:Tk().optional(),user:B().optional()})]),V({commands:Lk(B()).describe(`Array of shell commands to execute`),timeout_ms:Tk().optional().describe(`Optional timeout in milliseconds for the commands`),max_output_length:Tk().optional().describe(`Optional maximum number of characters to return from each command`)}),Bk([V({type:Qk(`create_file`),path:B(),diff:B()}),V({type:Qk(`update_file`),path:B(),diff:B()}),V({type:Qk(`delete_file`),path:B()})]);function GG(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(GG):typeof t[e]==`object`&&t[e]!==null&&(t[e]=GG(t[e])));return t}return e}function KG(e){let{$schema:t,...n}=GG(Sg(e)||zy(e)?Eb(e):e);return n}function qG(e){let{$schema:t,...n}=GG(e);return n}function JG(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))JG(i,t,[...n,e]);r.items&&JG(r.items,t,[...n,`[]`]);for(let e of[`anyOf`,`oneOf`,`allOf`]){let i=r[e];Array.isArray(i)&&i.forEach((r,i)=>JG(r,t,[...n,`${e}[${i}]`]))}r.additionalProperties&&typeof r.additionalProperties==`object`&&JG(r.additionalProperties,t,[...n,`additionalProperties`])}var YG=`__gemini_function_call_thought_signatures__`,XG=`ErYCCrMCAdHtim9kOoOkrPiCNVsmlpMIKd7ZMxgiFbVQOkgp7nlLcDMzVsZwIzvuT7nQROivoXA72ccC2lSDvR0Gh7dkWaGuj7ctv6t7ZceHnecx0QYa+ix8tYpRfjhyWozQ49lWiws6+YGjCt10KRTyWsZ2h6O7iHTYJwKIRwGUHRKy/qK/6kFxJm5ML00gLq4D8s5Z6DBpp2ZlR+uF4G8jJgeWQgyHWVdx2wGYElaceVAc66tZdPQRdOHpWtgYSI1YdaXgVI8KHY3/EfNc2YqqMIulvkDBAnuMhkAjV9xmBa54Tq+ih3Im4+r3DzqhGqYdsSkhS0kZMwte4Hjs65dZzCw9lANxIqYi1DJ639WNPYihp/DCJCos7o+/EeSPJaio5sgWDyUnMGkY1atsJZ+m7pj7DD5tvQ==`,ZG=e=>e();function QG(e){return Qt.isInstance(e)?e.role:e.type}function $G(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 eK(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 tK(e,t){return t.map(e=>Yt(e)?e.tool_calls??[]:[]).flat().find(t=>t.id===e.tool_call_id)?.name}function nK(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=Te({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 rK(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=Te({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=Te({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=Te({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 iK(e,t){if(ve(e))return Ee(e,rK(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 eK(e);else if(e.type===`image`)return nK(e,`image/png`);else if(e.type===`video`)return nK(e,`video/mp4`);else if(e.type===`audio`)return nK(e,`audio/mpeg`);else if(e.type===`file`)return nK(e,`application/octet-stream`);else if(e.type===`text-plain`)return`text`in e&&typeof e.text==`string`?{text:e.text}:nK(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 aK(e,t,n,r){if(xt(e)){let r=e.name??tK(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=>iK(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=>iK(e,t)).filter(e=>e!==void 0));let o=e.additional_kwargs?.[YG];return Yt(e)&&e.tool_calls?.length&&(i=e.tool_calls.map(e=>{let t=ZG(()=>{if(e.id){let t=o?.[e.id];if(t)return t}return r?.includes(`gemini-3`)?XG:``});return{functionCall:{name:e.name,args:e.args},...t?{thoughtSignature:t}:{}}})),[...a,...i]}function oK(e,t,n=!1,r){return e.reduce((i,a,o)=>{if(!mt(a))throw Error(`Unsupported message input`);let s=QG(a);if(s===`system`&&o!==0)throw Error(`System message should be the first one`);let c=$G(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=aK(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 sK(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:qn()}),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 Jt({content:o??``,tool_calls:a?.map(e=>({type:`tool_call`,id:e.id,name:e.functionCall.name,args:e.functionCall.args})),additional_kwargs:{...i,[YG]: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 cK(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:qn()}),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 Cu({text:c,message:new Zt({content:o||``,name:r?r.role:void 0,tool_call_chunks:l,additional_kwargs:{[YG]:u},response_metadata:{model_provider:`google-genai`},usage_metadata:t.usageMetadata}),generationInfo:i})}function lK(e){return e.every(e=>`functionDeclarations`in e&&Array.isArray(e.functionDeclarations))?e:[{functionDeclarations:e.map(e=>{if(jO(e)){let t=KG(e.schema);return t.type===`object`&&`properties`in t&&Object.keys(t.properties).length===0?{name:e.name,description:e.description}:(JG(t,e.name),{name:e.name,description:e.description,parameters:t})}if(Kw(e)){let t=qG(e.function.parameters);return JG(t,e.function.name),{name:e.function.name,description:e.function.description??`A function available to call.`,parameters:t}}return e})}]}function uK(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 dK=class extends Qw{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 eT(`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 Eg(this.zodSchema,e);if(t.success)return t.data;throw new eT(`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)}},fK;(function(e){e.STRING=`string`,e.NUMBER=`number`,e.INTEGER=`integer`,e.BOOLEAN=`boolean`,e.ARRAY=`array`,e.OBJECT=`object`})(fK||={});var pK;(function(e){e.LANGUAGE_UNSPECIFIED=`language_unspecified`,e.PYTHON=`python`})(pK||={});var mK;(function(e){e.OUTCOME_UNSPECIFIED=`outcome_unspecified`,e.OUTCOME_OK=`outcome_ok`,e.OUTCOME_FAILED=`outcome_failed`,e.OUTCOME_DEADLINE_EXCEEDED=`outcome_deadline_exceeded`})(mK||={});var hK=[`user`,`model`,`function`,`system`],gK;(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`})(gK||={});var _K;(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`})(_K||={});var vK;(function(e){e.HARM_PROBABILITY_UNSPECIFIED=`HARM_PROBABILITY_UNSPECIFIED`,e.NEGLIGIBLE=`NEGLIGIBLE`,e.LOW=`LOW`,e.MEDIUM=`MEDIUM`,e.HIGH=`HIGH`})(vK||={});var yK;(function(e){e.BLOCKED_REASON_UNSPECIFIED=`BLOCKED_REASON_UNSPECIFIED`,e.SAFETY=`SAFETY`,e.OTHER=`OTHER`})(yK||={});var bK;(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`})(bK||={});var xK;(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`})(xK||={});var SK;(function(e){e.MODE_UNSPECIFIED=`MODE_UNSPECIFIED`,e.AUTO=`AUTO`,e.ANY=`ANY`,e.NONE=`NONE`})(SK||={});var CK;(function(e){e.MODE_UNSPECIFIED=`MODE_UNSPECIFIED`,e.MODE_DYNAMIC=`MODE_DYNAMIC`})(CK||={});var wK=class extends Error{constructor(e){super(`[GoogleGenerativeAI Error]: ${e}`)}},TK=class extends wK{constructor(e,t){super(e),this.response=t}},EK=class extends wK{constructor(e,t,n,r){super(e),this.status=t,this.statusText=n,this.errorDetails=r}},DK=class extends wK{},OK=class extends wK{},kK=`https://generativelanguage.googleapis.com`,AK=`v1beta`,jK=`0.24.1`,MK=`genai-js`,NK;(function(e){e.GENERATE_CONTENT=`generateContent`,e.STREAM_GENERATE_CONTENT=`streamGenerateContent`,e.COUNT_TOKENS=`countTokens`,e.EMBED_CONTENT=`embedContent`,e.BATCH_EMBED_CONTENTS=`batchEmbedContents`})(NK||={});var PK=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||AK,t=`${this.requestOptions?.baseUrl||kK}/${e}/${this.model}:${this.task}`;return this.stream&&(t+=`?alt=sse`),t}};function FK(e){let t=[];return e?.apiClient&&t.push(e.apiClient),t.push(`${MK}/${jK}`),t.join(` `)}async function IK(e){let t=new Headers;t.append(`Content-Type`,`application/json`),t.append(`x-goog-api-client`,FK(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 DK(`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 DK(`Cannot set reserved header name ${e}`);if(e===`x-goog-api-client`)throw new DK(`Header name ${e} can only be set using the apiClient field`);t.append(e,r)}}return t}async function LK(e,t,n,r,i,a){let o=new PK(e,t,n,r,a);return{url:o.toString(),fetchOptions:Object.assign(Object.assign({},HK(a)),{method:`POST`,headers:await IK(o),body:i})}}async function RK(e,t,n,r,i,a={},o=fetch){let{url:s,fetchOptions:c}=await LK(e,t,n,r,i,a);return zK(s,c,o)}async function zK(e,t,n=fetch){let r;try{r=await n(e,t)}catch(t){BK(t,e)}return r.ok||await VK(r,e),r}function BK(e,t){let n=e;throw n.name===`AbortError`?(n=new OK(`Request aborted when fetching ${t.toString()}: ${e.message}`),n.stack=e.stack):e instanceof EK||e instanceof DK||(n=new wK(`Error fetching from ${t.toString()}: ${e.message}`),n.stack=e.stack),n}async function VK(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 EK(`Error fetching from ${t.toString()}: [${e.status} ${e.statusText}] ${n}`,e.status,e.statusText,r)}function HK(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 UK(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.`),qK(e.candidates[0]))throw new TK(`${JK(e)}`,e);return WK(e)}else if(e.promptFeedback)throw new TK(`Text not available. ${JK(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.`),qK(e.candidates[0]))throw new TK(`${JK(e)}`,e);return console.warn(`response.functionCall() is deprecated. Use response.functionCalls() instead.`),GK(e)[0]}else if(e.promptFeedback)throw new TK(`Function call not available. ${JK(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.`),qK(e.candidates[0]))throw new TK(`${JK(e)}`,e);return GK(e)}else if(e.promptFeedback)throw new TK(`Function call not available. ${JK(e)}`,e)},e}function WK(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+`
210
+ `+n.executableCode.code+"\n```\n"),n.codeExecutionResult&&t.push("\n```\n"+n.codeExecutionResult.output+"\n```\n");return t.length>0?t.join(``):``}function GK(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 KK=[bK.RECITATION,bK.SAFETY,bK.LANGUAGE];function qK(e){return!!e.finishReason&&KK.includes(e.finishReason)}function JK(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];qK(n)&&(t+=`Candidate was blocked due to ${n.finishReason}`,n.finishMessage&&(t+=`: ${n.finishMessage}`))}return t}function YK(e){return this instanceof YK?(this.v=e,this):new YK(e)}function XK(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 YK?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 ZK=/^data\: (.*)(?:\n\n|\r\r|\r\n\r\n)/;function QK(e){let[t,n]=tq(e.body.pipeThrough(new TextDecoderStream(`utf8`,{fatal:!0}))).tee();return{stream:eq(t),response:$K(n)}}async function $K(e){let t=[],n=e.getReader();for(;;){let{done:e,value:r}=await n.read();if(e)return UK(nq(t));t.push(r)}}function eq(e){return XK(this,arguments,function*(){let t=e.getReader();for(;;){let{value:e,done:n}=yield YK(t.read());if(n)break;yield yield YK(UK(e))}})}function tq(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 wK(`Failed to parse stream`));return}e.close();return}n+=t;let a=n.match(ZK),o;for(;a;){try{o=JSON.parse(a[1])}catch{e.error(new wK(`Error parsing JSON response: "${a[1]}"`));return}e.enqueue(o),n=n.substring(a[0].length),a=n.match(ZK)}return r()}).catch(e=>{let t=e;throw t.stack=e.stack,t=t.name===`AbortError`?new OK(`Request aborted when reading from the stream`):new wK(`Error reading from the stream`),t})}}})}function nq(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 rq(e,t,n,r){return QK(await RK(t,NK.STREAM_GENERATE_CONTENT,e,!0,JSON.stringify(n),r))}async function iq(e,t,n,r){return{response:UK(await(await RK(t,NK.GENERATE_CONTENT,e,!1,JSON.stringify(n),r)).json())}}function aq(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 oq(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 sq(t)}function sq(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 wK(`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 wK(`No content is provided for sending chat message.`);return r?t:n}function cq(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 DK(`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=oq(e);n.contents=[t]}return{generateContentRequest:n}}function lq(e){let t;return t=e.contents?e:{contents:[oq(e)]},e.systemInstruction&&(t.systemInstruction=aq(e.systemInstruction)),t}function uq(e){return typeof e==`string`||Array.isArray(e)?{content:oq(e)}:e}var dq=[`text`,`inlineData`,`functionCall`,`functionResponse`,`executableCode`,`codeExecutionResult`],fq={user:[`text`,`inlineData`],function:[`functionResponse`],model:[`text`,`functionCall`,`executableCode`,`codeExecutionResult`],system:[`text`]};function pq(e){let t=!1;for(let n of e){let{role:e,parts:r}=n;if(!t&&e!==`user`)throw new wK(`First content should be with role 'user', got ${e}`);if(!hK.includes(e))throw new wK(`Each item should include role field. Got ${e} but valid roles are: ${JSON.stringify(hK)}`);if(!Array.isArray(r))throw new wK(`Content should have 'parts' property with an array of Parts`);if(r.length===0)throw new wK(`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 dq)t in e&&(i[t]+=1);let a=fq[e];for(let t of dq)if(!a.includes(t)&&i[t]>0)throw new wK(`Content with role '${e}' can't contain '${t}' part`);t=!0}}function mq(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 hq=`SILENT_ERROR`,gq=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&&(pq(n.history),this._history=n.history)}async getHistory(){return await this._sendPromise,this._history}async sendMessage(e,t={}){await this._sendPromise;let n=oq(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(()=>iq(this._apiKey,this.model,r,i)).then(e=>{if(mq(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=JK(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=oq(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=rq(this._apiKey,this.model,r,i);return this._sendPromise=this._sendPromise.then(()=>a).catch(e=>{throw Error(hq)}).then(e=>e.response).then(e=>{if(mq(e)){this._history.push(n);let t=Object.assign({},e.candidates[0].content);t.role||=`model`,this._history.push(t)}else{let t=JK(e);t&&console.warn(`sendMessageStream() was unsuccessful. ${t}. Inspect response object for details.`)}}).catch(e=>{e.message!==hq&&console.error(e)}),a}};async function _q(e,t,n,r){return(await RK(t,NK.COUNT_TOKENS,e,!1,JSON.stringify(n),r)).json()}async function vq(e,t,n,r){return(await RK(t,NK.EMBED_CONTENT,e,!1,JSON.stringify(n),r)).json()}async function yq(e,t,n,r){let i=n.requests.map(e=>Object.assign(Object.assign({},e),{model:t}));return(await RK(t,NK.BATCH_EMBED_CONTENTS,e,!1,JSON.stringify({requests:i}),r)).json()}var bq=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=aq(t.systemInstruction),this.cachedContent=t.cachedContent}async generateContent(e,t={}){let n=lq(e),r=Object.assign(Object.assign({},this._requestOptions),t);return iq(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=lq(e),r=Object.assign(Object.assign({},this._requestOptions),t);return rq(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 gq(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=cq(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 _q(this.apiKey,this.model,n,r)}async embedContent(e,t={}){let n=uq(e),r=Object.assign(Object.assign({},this._requestOptions),t);return vq(this.apiKey,this.model,n,r)}async batchEmbedContents(e,t={}){let n=Object.assign(Object.assign({},this._requestOptions),t);return yq(this.apiKey,this.model,e,n)}},xq=class{constructor(e){this.apiKey=e}getGenerativeModel(e,t){if(!e.model)throw new wK(`Must provide a model name. Example: genai.getGenerativeModel({ model: 'my-model-name' })`);return new bq(this.apiKey,e,t)}getGenerativeModelFromCachedContent(e,t,n){if(!e.name)throw new DK("Cached content must contain a `name` field.");if(!e.model)throw new DK("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 DK(`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 bq(this.apiKey,r,n)}};function Sq(e,t){let n=Cq(e);return{tools:n,toolConfig:Tq(n,t)}}function Cq(e){let t=[],n=[];return e.forEach(e=>{if(jO(e)){let[n]=lK([e]);n.functionDeclarations&&t.push(...n.functionDeclarations)}else if(Kw(e)){let{functionDeclarations:n}=wq(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 wq(e){return{functionDeclarations:[{name:e.function.name,description:e.function.description,parameters:GG(e.function.parameters)}]}}function Tq(e,t){if(!e.length||!t)return;let{toolChoice:n,allowedFunctionNames:r}=t,i={any:SK.ANY,auto:SK.AUTO,none:SK.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:SK.ANY,allowedFunctionNames:[...r??[],...n&&typeof n==`string`?[n]:[]]}}}var Eq={"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}},Dq=class extends sE{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??mr(`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 xq(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 xq(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:Sq(e)?.tools,...t})}invocationParams(e){let t=e?.tools?.length?Sq(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=oK(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=uK(o.response.usageMetadata,this.model));let c=sK(o.response,{usageMetadata:s});return c.generations?.length>0&&await n?.handleLLMNewToken(c.generations[0]?.text??``),c}async*_streamResponseChunks(e,t,n){let r=oK(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=uK(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=cK(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 Eq[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(Sg(n)||zy(n)){let r=KG(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=GG(n.parameters),e=n.name):t={name:e,description:n.description??``,parameters:GG(n)};let i=[{functionDeclarations:[t]}];o=this.bindTools(i).withConfig({allowedFunctionNames:[e]}),s=AT(n,e,dK)}else{let e=KG(n);o=this.withConfig({responseSchema:e}),s=kT(n)}return jT(o,s,a,a?`StructuredOutputRunnable`:`ChatGoogleGenerativeAIStructuredOutput`)}},Oq=class extends Qw{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 eT(`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 eT(`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 Eg(this.zodSchema,t);if(n.success)return n.data;throw new eT(`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)?kq(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 kq(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 Aq(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 jq=V({cache_control:bA().optional().nullable(),defer_loading:kk().optional(),input_examples:Lk(Nk()).optional(),allowed_callers:Lk(Nk()).optional()}),Mq={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 Nq(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`thinking`}function Pq(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`redacted_thinking`}function Fq(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`compaction`}function Iq(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`search_result`}function Lq(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 Rq={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=Te({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}`)}},zq=e=>e();function Bq(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`citation`}function Vq(e){function*t(){for(let t of e)Bq(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 Hq(e){return typeof e==`string`?e:Uq(e)}function Uq(e){let t=[];for(let n=0,{length:r}=e;n<r;n++)t.push(String.fromCharCode(e[n]));return btoa(t.join(``))}function Wq(e){return(e??``).split(`;`)[0].toLowerCase()}function Gq(e,t){if(typeof e==`object`&&e&&t in e)return e[t]}function Kq(e,t){let n=Gq(t,`cache_control`);n!==void 0&&(e.cache_control=n);let r=Gq(t,`citations`);r!==void 0&&(e.citations=r);let i=Gq(t,`context`);i!==void 0&&(e.context=i);let a=Gq(t,`title`);return a!==void 0&&(e.title=a),e}function qq(e,t){let n=Gq(t,`cache_control`);return n!==void 0&&(e.cache_control=n),e}function Jq(e){return new Set([`image/jpeg`,`image/png`,`image/gif`,`image/webp`]).has(e)}function Yq(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:Vq(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=zq(()=>{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(Kq({type:`document`,source:{type:`file`,file_id:n.fileId}},e));continue}if(n.url){let r=Wq(n.mimeType);if(r===`application/pdf`||r===``){t.push(Kq({type:`document`,source:{type:`url`,url:n.url}},e));continue}}if(n.data){let r=Wq(n.mimeType);if(r===``||r===`application/pdf`)t.push(Kq({type:`document`,source:{type:`base64`,data:Hq(n.data),media_type:`application/pdf`}},e));else if(r===`text/plain`)t.push(Kq({type:`document`,source:{type:`text`,data:Hq(n.data),media_type:`text/plain`}},e));else if(Jq(r))t.push(Kq({type:`document`,source:{type:`content`,content:[{type:`image`,source:{type:`base64`,data:Hq(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(qq({type:`image`,source:{type:`file`,file_id:n.fileId}},e));continue}if(n.url){t.push(qq({type:`image`,source:{type:`url`,url:n.url}},e));continue}if(n.data){let r=Wq(n.mimeType)||`image/png`;Jq(r)&&t.push(qq({type:`image`,source:{type:`base64`,data:Hq(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(Kq({type:`document`,source:{type:`text`,data:Hq(n.data),media_type:`text/plain`}},n.metadata)):n.type===`non_standard`&&r&&t.push(n.value));return t}function Xq(e){let t=Te({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(`
210
211
 
211
212
  `))}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(`
212
213
 
213
- `))}function cq(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 sn({content:[{type:`tool_result`,content:n.content,tool_use_id:n.tool_call_id}]}))}else t.push(new sn({content:[{type:`tool_result`,...n.content==null?{}:{content:dq(n)},tool_use_id:n.tool_call_id}]}));else t.push(n);return t}function lq(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*uq(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){ve(i)&&(yield Ee(i,YK));let a=`cache_control`in i?i.cache_control:void 0;if(i.type===`image_url`){let e;typeof i.image_url==`string`?e=sq(i.image_url):typeof i.image_url==`object`&&i.image_url!==null&&`url`in i.image_url&&typeof i.image_url.url==`string`&&(e=sq(i.image_url.url)),e&&(yield{type:`image`,source:e,...a?{cache_control:a}:{}})}else if(JK(i))yield i;else if(i.type===`image`){let e;`url`in i&&typeof i.url==`string`?e=sq(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(WK(i))yield{type:`thinking`,thinking:i.thinking,signature:i.signature,...a?{cache_control:a}:{}};else if(GK(i))yield{type:`redacted_thinking`,data:i.data,...a?{cache_control:a}:{}};else if(KK(i))yield{type:`compaction`,content:i.content,...a?{cache_control:a}:{}};else if(qK(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 dq(e,t){let{content:n}=e;return typeof n==`string`?n:Array.from(uq(n,t))}function fq(e){let t=cq(e),n;return t.length>0&&t[0]._getType()===`system`&&(n=e[0].content),{messages:pq((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(Jt.isInstance(e)&&e.response_metadata?.output_version===`v1`)return{role:t,content:oq(e)};if(Jt.isInstance(e)&&e.tool_calls?.length){if(typeof e.content==`string`)return e.content===``?{role:t,content:e.tool_calls.map(lq)}:{role:t,content:[{type:`text`,text:e.content},...e.tool_calls.map(lq)]};{let{content:n}=e,r=dq(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(lq)]}}}else return{role:t,content:dq(e,Jt.isInstance(e)?e.tool_calls:void 0)}})),system:n}}function pq(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 mq(e){return e.type===`enabled`||e.type===`adaptive`}function hq(e){return e?.startsWith(`claude-opus-4-7`)??!1}function gq(e,t){let n=t&&typeof t==`object`&&`task_budget`in t&&t.task_budget!=null;return hq(e)&&n?[`task-budgets-2026-03-13`]:[]}function _q(e){let{model:t,thinking:n,topK:r,topP:i,temperature:a}=e,o=hq(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(mq(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 vq(e){let{model:t,thinking:n,topK:r,topP:i,temperature:a}=e,o={};return mq(n)||hq(t)?o:(a!==void 0&&(o.temperature=a),r!==void 0&&(o.top_k=r),i!==void 0&&(o.top_p=i),o)}function yq(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=xq(i);return{chunk:new Zt({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 Zt({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 Zt({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 Zt({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 Zt({content:[{index:e.index,...t,type:`thinking`}],response_metadata:n})}:{chunk:new Zt({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 Zt({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 Zt({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 Zt({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 Zt({content:t.coerceContentToString?r:[{index:e.index,...e.content_block}],response_metadata:n})}}else if(e.type===`content_block_start`&&KK(e.content_block))return{chunk:new Zt({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 Zt({content:t.coerceContentToString?``:[{index:e.index,...e.delta,type:`compaction`}],response_metadata:n})};return null}function bq(e,t){let n={...t,model_provider:`anthropic`},r=t.usage,i=r==null?void 0:xq(r);return e.length===1&&e[0].type===`text`?[{text:e[0].text,message:new Jt({content:e[0].text,additional_kwargs:t,usage_metadata:i,response_metadata:n,id:t.id})}]:[{text:``,message:new Jt({content:e,additional_kwargs:t,tool_calls:BK(e),usage_metadata:i,response_metadata:n,id:t.id})}]}function xq(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 Sq(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 Cq(e){let t;return t=e.status===400&&typeof e.message==`string`&&e.message.includes(`prompt is too long`)?Sq(m.fromError(e),`CONTEXT_OVERFLOW`):e.status===400&&e.message.includes(`tool`)?Sq(e,`INVALID_TOOL_RESULTS`):e.status===401?Sq(e,`MODEL_AUTHENTICATION`):e.status===404?Sq(e,`MODEL_NOT_FOUND`):e.status===429?Sq(e,`MODEL_RATE_LIMIT`):e,t}var wq={"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*Tq(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=Dq(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:Eq(a),...i?{usage:i}:{},metadata:{model_provider:`anthropic`}};break;case`content_block_start`:{let{index:e,content_block:n}=t,i=Oq(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}=kq(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:Aq(n)},r.delete(e);break}default:yield{event:`provider`,provider:`anthropic`,name:t.type,payload:t};break}}function Eq(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 Dq(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 Oq(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 kq(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 Aq(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 jq=function(){let{crypto:e}=globalThis;if(e?.randomUUID)return jq=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 Mq(e){return typeof e==`object`&&!!e&&(`name`in e&&e.name===`AbortError`||`message`in e&&String(e.message).includes(`FetchRequestCanceledException`))}var Nq=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{},Pq=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 Iq({message:r,cause:Nq(n)});let a=n,o=a?.error?.type;return t===400?new Rq(t,a,r,i,o):t===401?new zq(t,a,r,i,o):t===403?new Bq(t,a,r,i,o):t===404?new Vq(t,a,r,i,o):t===409?new Hq(t,a,r,i,o):t===422?new Uq(t,a,r,i,o):t===429?new Wq(t,a,r,i,o):t>=500?new Gq(t,a,r,i,o):new e(t,a,r,i,o)}},Fq=class extends Pq{constructor({message:e}={}){super(void 0,void 0,e||`Request was aborted.`,void 0)}},Iq=class extends Pq{constructor({message:e,cause:t}){super(void 0,void 0,e||`Connection error.`,void 0),t&&(this.cause=t)}},Lq=class extends Iq{constructor({message:e}={}){super({message:e??`Request timed out.`})}},Rq=class extends Pq{},zq=class extends Pq{},Bq=class extends Pq{},Vq=class extends Pq{},Hq=class extends Pq{},Uq=class extends Pq{},Wq=class extends Pq{},Gq=class extends Pq{},Kq=/^[a-z][a-z0-9+.-]*:/i,qq=e=>Kq.test(e),Jq=e=>(Jq=Array.isArray,Jq(e)),Yq=Jq;function Xq(e){return typeof e==`object`?e??{}:{}}function Zq(e){if(!e)return!0;for(let t in e)return!1;return!0}function Qq(e,t){return Object.prototype.hasOwnProperty.call(e,t)}var $q=(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},eJ=e=>{try{return JSON.parse(e)}catch{return}},tJ=(e,t)=>{let n=e[t];return delete e[t],n},nJ=e=>new Promise(t=>setTimeout(t,e)),rJ=`0.91.1`,iJ=()=>typeof window<`u`&&window.document!==void 0&&typeof navigator<`u`;function aJ(){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 oJ=()=>{let e=aJ();if(e===`deno`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":rJ,"X-Stainless-OS":lJ(Deno.build.os),"X-Stainless-Arch":cJ(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":rJ,"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":rJ,"X-Stainless-OS":lJ(globalThis.process.platform??`unknown`),"X-Stainless-Arch":cJ(globalThis.process.arch??`unknown`),"X-Stainless-Runtime":`node`,"X-Stainless-Runtime-Version":globalThis.process.version??`unknown`};let t=sJ();return t?{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":rJ,"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":rJ,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`unknown`,"X-Stainless-Runtime":`unknown`,"X-Stainless-Runtime-Version":`unknown`}};function sJ(){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 cJ=e=>e===`x32`?`x32`:e===`x86_64`||e===`x64`?`x64`:e===`arm`?`arm`:e===`aarch64`||e===`arm64`?`arm64`:e?`other:${e}`:`unknown`,lJ=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`),uJ,dJ=()=>uJ??=oJ();function fJ(){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 pJ(...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 mJ(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return pJ({start(){},async pull(e){let{done:n,value:r}=await t.next();n?e.close():e.enqueue(r)},async cancel(){await t.return?.()}})}function hJ(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 gJ(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 _J=({headers:e,body:t})=>({bodyHeaders:{"content-type":`application/json`},body:JSON.stringify(t)});function vJ(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 yJ(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 bJ;function xJ(e){let t;return(bJ??=(t=new globalThis.TextEncoder,t.encode.bind(t)))(e)}var SJ;function CJ(e){let t;return(SJ??=(t=new globalThis.TextDecoder,t.decode.bind(t)))(e)}var wJ,TJ,EJ=class{constructor(){wJ.set(this,void 0),TJ.set(this,void 0),Y(this,wJ,new Uint8Array,`f`),Y(this,TJ,null,`f`)}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e==`string`?xJ(e):e;Y(this,wJ,yJ([X(this,wJ,`f`),t]),`f`);let n=[],r;for(;(r=DJ(X(this,wJ,`f`),X(this,TJ,`f`)))!=null;){if(r.carriage&&X(this,TJ,`f`)==null){Y(this,TJ,r.index,`f`);continue}if(X(this,TJ,`f`)!=null&&(r.index!==X(this,TJ,`f`)+1||r.carriage)){n.push(CJ(X(this,wJ,`f`).subarray(0,X(this,TJ,`f`)-1))),Y(this,wJ,X(this,wJ,`f`).subarray(X(this,TJ,`f`)),`f`),Y(this,TJ,null,`f`);continue}let e=X(this,TJ,`f`)===null?r.preceding:r.preceding-1,t=CJ(X(this,wJ,`f`).subarray(0,e));n.push(t),Y(this,wJ,X(this,wJ,`f`).subarray(r.index),`f`),Y(this,TJ,null,`f`)}return n}flush(){return X(this,wJ,`f`).length?this.decode(`
214
- `):[]}};wJ=new WeakMap,TJ=new WeakMap,EJ.NEWLINE_CHARS=new Set([`
215
- `,`\r`]),EJ.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function DJ(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 OJ(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 kJ={off:0,error:200,warn:300,info:400,debug:500},AJ=(e,t,n)=>{if(e){if(Qq(kJ,e))return e;FJ(n).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(kJ))}`)}};function jJ(){}function MJ(e,t,n){return!t||kJ[e]>kJ[n]?jJ:t[e].bind(t)}var NJ={error:jJ,warn:jJ,info:jJ,debug:jJ},PJ=new WeakMap;function FJ(e){let t=e.logger,n=e.logLevel??`off`;if(!t)return NJ;let r=PJ.get(t);if(r&&r[0]===n)return r[1];let i={error:MJ(`error`,t,n),warn:MJ(`warn`,t,n),info:MJ(`info`,t,n),debug:MJ(`debug`,t,n)};return PJ.set(t,[n,i]),i}var IJ=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),LJ,RJ=class e{constructor(e,t,n){this.iterator=e,LJ.set(this,void 0),this.controller=t,Y(this,LJ,n,`f`)}static fromSSEResponse(t,n,r){let i=!1,a=r?FJ(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 zJ(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=eJ(e.data)??e.data,r=n?.error?.type;throw new Pq(void 0,n,void 0,t.headers,r)}}e=!0}catch(e){if(Mq(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 EJ,n=hJ(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(Mq(e))return;throw e}finally{e||n.abort()}}return new e(o,n,r)}[(LJ=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,LJ,`f`)),new e(()=>i(n),this.controller,X(this,LJ,`f`))]}toReadableStream(){let e=this,t;return pJ({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=xJ(JSON.stringify(n)+`
216
- `);e.enqueue(i)}catch(t){e.error(t)}},async cancel(){await t.return?.()}})}};async function*zJ(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 VJ,r=new EJ,i=hJ(e.body);for await(let e of BJ(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*BJ(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`?xJ(n):n,r=new Uint8Array(t.length+e.length);r.set(t),r.set(e,t.length),t=r;let i;for(;(i=OJ(t))!==-1;)yield t.slice(0,i),t=t.slice(i)}t.length>0&&(yield t)}var VJ=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(`
217
- `),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]=HJ(e,`:`);return r.startsWith(` `)&&(r=r.substring(1)),t===`event`?this.event=r:t===`data`&&this.data.push(r),null}};function HJ(e,t){let n=e.indexOf(t);return n===-1?[e,``,``]:[e.substring(0,n),t,e.substring(n+t.length)]}async function UJ(e,t){let{response:n,requestLogID:r,retryOfRequestLogID:i,startTime:a}=t,o=await(async()=>{if(t.options.stream)return FJ(e).debug(`response`,n.status,n.url,n.headers,n.body),t.options.__streamClass?t.options.__streamClass.fromSSEResponse(n,t.controller):RJ.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:WJ(await n.json(),n):await n.text()})();return FJ(e).debug(`[${r}] response parsed`,IJ({retryOfRequestLogID:i,url:n.url,status:n.status,body:o,durationMs:Date.now()-a})),o}function WJ(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 GJ,KJ=class e extends Promise{constructor(e,t,n=UJ){super(e=>{e(null)}),this.responsePromise=t,this.parseResponse=n,GJ.set(this,void 0),Y(this,GJ,e,`f`)}_thenUnwrap(t){return new e(X(this,GJ,`f`),this.responsePromise,async(e,n)=>WJ(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,GJ,`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)}};GJ=new WeakMap;var qJ,JJ=class{constructor(e,t,n,r){qJ.set(this,void 0),Y(this,qJ,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,qJ,`f`).requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(qJ=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}},YJ=class extends KJ{constructor(e,t,n){super(e,t,async(e,t)=>new n(e,t.response,await UJ(e,t),t.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}},XJ=class extends JJ{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:{...Xq(this.options.query),before_id:e}}:null}let e=this.last_id;return e?{...this.options,query:{...Xq(this.options.query),after_id:e}}:null}},ZJ=class extends JJ{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:{...Xq(this.options.query),page:e}}:null}},QJ=()=>{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 $J(e,t,n){return QJ(),new File(e,t??`unknown_file`,n)}function eY(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 tY=e=>typeof e==`object`&&!!e&&typeof e[Symbol.asyncIterator]==`function`,nY=async(e,t,n=!0)=>({...e,body:await aY(e.body,t,n)}),rY=new WeakMap;function iY(e){let t=typeof e==`function`?e:e.fetch,n=rY.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 rY.set(t,r),r}var aY=async(e,t,n=!0)=>{if(!await iY(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])=>sY(r,e,t,n))),r},oY=e=>e instanceof Blob&&`name`in e,sY=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,$J([await n.blob()],eY(n,r),i))}else if(tY(n))e.append(t,$J([await new Response(mJ(n)).blob()],eY(n,r)));else if(oY(n))e.append(t,$J([n],eY(n,r),{type:n.type}));else if(Array.isArray(n))await Promise.all(n.map(n=>sY(e,t+`[]`,n,r)));else if(typeof n==`object`)await Promise.all(Object.entries(n).map(([n,i])=>sY(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`)}},cY=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`,lY=e=>typeof e==`object`&&!!e&&typeof e.name==`string`&&typeof e.lastModified==`number`&&cY(e),uY=e=>typeof e==`object`&&!!e&&typeof e.url==`string`&&typeof e.blob==`function`;async function dY(e,t,n){if(QJ(),e=await e,t||=eY(e,!0),lY(e))return e instanceof File&&t==null&&n==null?e:$J([await e.arrayBuffer()],t??e.name,{type:e.type,lastModified:e.lastModified,...n});if(uY(e)){let r=await e.blob();return t||=new URL(e.url).pathname.split(/[\\/]/).pop(),$J(await fY(r),t,n)}let r=await fY(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 $J(r,t,n)}async function fY(e){let t=[];if(typeof e==`string`||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(cY(e))t.push(e instanceof Blob?e:await e.arrayBuffer());else if(tY(e))for await(let n of e)t.push(...await fY(n));else{let t=e?.constructor?.name;throw Error(`Unexpected data type: ${typeof e}${t?`; constructor: ${t}`:``}${pY(e)}`)}return t}function pY(e){return typeof e!=`object`||!e?``:`; props: [${Object.getOwnPropertyNames(e).map(e=>`"${e}"`).join(`, `)}]`}var mY=class{constructor(e){this._client=e}},hY=Symbol.for(`brand.privateNullableHeaders`);function*gY(e){if(!e)return;if(hY 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():Yq(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=Yq(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 gY(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{[hY]:!0,values:t,nulls:n}};function _Y(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var vY=Object.freeze(Object.create(null)),$=((e=_Y)=>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??vY)??vY)?.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(`
218
- `)}\n${a}\n${t}`)}return a})(_Y),yY=class extends mY{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`,ZJ,{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])})}},bY=Symbol(`anthropic.sdk.stainlessHelper`);function xY(e){return typeof e==`object`&&!!e&&bY in e}function SY(e,t){let n=new Set;if(e)for(let t of e)xY(t)&&n.add(t[bY]);if(t){for(let e of t)if(xY(e)&&n.add(e[bY]),Array.isArray(e.content))for(let t of e.content)xY(t)&&n.add(t[bY])}return Array.from(n)}function CY(e,t){let n=SY(e,t);return n.length===0?{}:{"x-stainless-helper":n.join(`, `)}}function wY(e){return xY(e)?{"x-stainless-helper":e[bY]}:{}}var TY=class extends mY{list(e={},t){let{betas:n,...r}=e??{};return this._client.getAPIList(`/v1/files?beta=true`,XJ,{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`,nY({body:r,...t,headers:Q([{"anthropic-beta":[...n??[],`files-api-2025-04-14`].toString()},wY(r.file),t?.headers])},this._client))}},EY=class extends mY{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`,XJ,{query:r,...t,headers:Q([{...n?.toString()==null?void 0:{"anthropic-beta":n?.toString()}},t?.headers])})}},DY=class extends mY{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`,ZJ,{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])})}},OY=class extends mY{list(e,t={},n){let{betas:r,...i}=t??{};return this._client.getAPIList($`/v1/agents/${e}/versions?beta=true`,ZJ,{query:i,...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}},kY=class extends mY{constructor(){super(...arguments),this.versions=new OY(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`,ZJ,{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])})}};kY.Versions=OY;var AY=class extends mY{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`,ZJ,{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])})}},jY=class extends mY{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`,ZJ,{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])})}},MY=class extends mY{constructor(){super(...arguments),this.memories=new AY(this._client),this.memoryVersions=new jY(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`,ZJ,{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])})}};MY.Memories=AY,MY.MemoryVersions=jY;var NY={"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 PY(e){return e?.output_format??e?.output_config?.format}function FY(e,t,n){let r=PY(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}:IY(e,t,n)}function IY(e,t,n){let r=null,i=e.content.map(e=>{if(e.type===`text`){let i=LY(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 LY(e,t){let n=PY(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 RY=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},zY=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),zY(e);case`number`:let n=t.value[t.value.length-1];if(n===`.`||n===`-`)return e=e.slice(0,e.length-1),zY(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),zY(e);break;case`delimiter`:return e=e.slice(0,e.length-1),zY(e)}return e},BY=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},VY=e=>{let t=``;return e.map(e=>{switch(e.type){case`string`:t+=`"`+e.value+`"`;break;default:t+=e.value;break}}),t},HY=e=>JSON.parse(VY(BY(zY(RY(e))))),UY,WY,GY,KY,qY,JY,YY,XY,ZY,QY,$Y,eX,tX,nX,rX,iX,aX,oX,sX,cX,lX,uX,dX,fX,pX=`__json_buf`;function mX(e){return e.type===`tool_use`||e.type===`server_tool_use`||e.type===`mcp_tool_use`}var hX=class e{constructor(e,t){UY.add(this),this.messages=[],this.receivedMessages=[],WY.set(this,void 0),GY.set(this,null),this.controller=new AbortController,KY.set(this,void 0),qY.set(this,()=>{}),JY.set(this,()=>{}),YY.set(this,void 0),XY.set(this,()=>{}),ZY.set(this,()=>{}),QY.set(this,{}),$Y.set(this,!1),eX.set(this,!1),tX.set(this,!1),nX.set(this,!1),rX.set(this,void 0),iX.set(this,void 0),aX.set(this,void 0),cX.set(this,e=>{if(Y(this,eX,!0,`f`),Mq(e)&&(e=new Fq),e instanceof Fq)return Y(this,tX,!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,KY,new Promise((e,t)=>{Y(this,qY,e,`f`),Y(this,JY,t,`f`)}),`f`),Y(this,YY,new Promise((e,t)=>{Y(this,XY,e,`f`),Y(this,ZY,t,`f`)}),`f`),X(this,KY,`f`).catch(()=>{}),X(this,YY,`f`).catch(()=>{}),Y(this,GY,e,`f`),Y(this,aX,t?.logger??console,`f`)}get response(){return X(this,rX,`f`)}get request_id(){return X(this,iX,`f`)}async withResponse(){Y(this,nX,!0,`f`);let e=await X(this,KY,`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,GY,{...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,cX,`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,UY,`m`,lX).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,UY,`m`,uX).call(this,e);if(i.controller.signal?.aborted)throw new Fq;X(this,UY,`m`,dX).call(this)}finally{r&&i&&r.removeEventListener(`abort`,i)}}_connected(e){this.ended||(Y(this,rX,e,`f`),Y(this,iX,e?.headers.get(`request-id`),`f`),X(this,qY,`f`).call(this,e),this._emit(`connect`))}get ended(){return X(this,$Y,`f`)}get errored(){return X(this,eX,`f`)}get aborted(){return X(this,tX,`f`)}abort(){this.controller.abort()}on(e,t){return(X(this,QY,`f`)[e]||(X(this,QY,`f`)[e]=[])).push({listener:t}),this}off(e,t){let n=X(this,QY,`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,QY,`f`)[e]||(X(this,QY,`f`)[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,n)=>{Y(this,nX,!0,`f`),e!==`error`&&this.once(`error`,n),this.once(e,t)})}async done(){Y(this,nX,!0,`f`),await X(this,YY,`f`)}get currentMessage(){return X(this,WY,`f`)}async finalMessage(){return await this.done(),X(this,UY,`m`,oX).call(this)}async finalText(){return await this.done(),X(this,UY,`m`,sX).call(this)}_emit(e,...t){if(X(this,$Y,`f`))return;e===`end`&&(Y(this,$Y,!0,`f`),X(this,XY,`f`).call(this));let n=X(this,QY,`f`)[e];if(n&&(X(this,QY,`f`)[e]=n.filter(e=>!e.once),n.forEach(({listener:e})=>e(...t))),e===`abort`){let e=t[0];!X(this,nX,`f`)&&!n?.length&&Promise.reject(e),X(this,JY,`f`).call(this,e),X(this,ZY,`f`).call(this,e),this._emit(`end`);return}if(e===`error`){let e=t[0];!X(this,nX,`f`)&&!n?.length&&Promise.reject(e),X(this,JY,`f`).call(this,e),X(this,ZY,`f`).call(this,e),this._emit(`end`)}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit(`finalMessage`,X(this,UY,`m`,oX).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,UY,`m`,lX).call(this),this._connected(null);let t=RJ.fromReadableStream(e,this.controller);for await(let e of t)X(this,UY,`m`,uX).call(this,e);if(t.controller.signal?.aborted)throw new Fq;X(this,UY,`m`,dX).call(this)}finally{n&&r&&n.removeEventListener(`abort`,r)}}[(WY=new WeakMap,GY=new WeakMap,KY=new WeakMap,qY=new WeakMap,JY=new WeakMap,YY=new WeakMap,XY=new WeakMap,ZY=new WeakMap,QY=new WeakMap,$Y=new WeakMap,eX=new WeakMap,tX=new WeakMap,nX=new WeakMap,rX=new WeakMap,iX=new WeakMap,aX=new WeakMap,cX=new WeakMap,UY=new WeakSet,oX=function(){if(this.receivedMessages.length===0)throw new Z(`stream ended without producing a Message with role=assistant`);return this.receivedMessages.at(-1)},sX=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(` `)},lX=function(){this.ended||Y(this,WY,void 0,`f`)},uX=function(e){if(this.ended)return;let t=X(this,UY,`m`,fX).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`:mX(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(FY(t,X(this,GY,`f`),{logger:X(this,aX,`f`)}),!0);break;case`content_block_stop`:this._emit(`contentBlock`,t.content.at(-1));break;case`message_start`:Y(this,WY,t,`f`);break;case`content_block_start`:case`message_delta`:break}},dX=function(){if(this.ended)throw new Z(`stream has ended, this shouldn't happen`);let e=X(this,WY,`f`);if(!e)throw new Z(`request ended without sending any chunks`);return Y(this,WY,void 0,`f`),FY(e,X(this,GY,`f`),{logger:X(this,aX,`f`)})},fX=function(e){let t=X(this,WY,`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&&mX(n)){let r=n[pX]||``;r+=e.delta.partial_json;let i={...n};if(Object.defineProperty(i,pX,{value:r,enumerable:!1,writable:!0}),r)try{i.input=HY(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,cX,`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 RJ(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}},gX=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}},_X=`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:
214
+ `))}function Zq(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 sn({content:[{type:`tool_result`,content:n.content,tool_use_id:n.tool_call_id}]}))}else t.push(new sn({content:[{type:`tool_result`,...n.content==null?{}:{content:eJ(n)},tool_use_id:n.tool_call_id}]}));else t.push(n);return t}function Qq(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*$q(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){ve(i)&&(yield Ee(i,Rq));let a=`cache_control`in i?i.cache_control:void 0;if(i.type===`image_url`){let e;typeof i.image_url==`string`?e=Xq(i.image_url):typeof i.image_url==`object`&&i.image_url!==null&&`url`in i.image_url&&typeof i.image_url.url==`string`&&(e=Xq(i.image_url.url)),e&&(yield{type:`image`,source:e,...a?{cache_control:a}:{}})}else if(Lq(i))yield i;else if(i.type===`image`){let e;`url`in i&&typeof i.url==`string`?e=Xq(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(Nq(i))yield{type:`thinking`,thinking:i.thinking,signature:i.signature,...a?{cache_control:a}:{}};else if(Pq(i))yield{type:`redacted_thinking`,data:i.data,...a?{cache_control:a}:{}};else if(Fq(i))yield{type:`compaction`,content:i.content,...a?{cache_control:a}:{}};else if(Iq(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 eJ(e,t){let{content:n}=e;return typeof n==`string`?n:Array.from($q(n,t))}function tJ(e){let t=Zq(e),n;return t.length>0&&t[0]._getType()===`system`&&(n=e[0].content),{messages:nJ((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(Jt.isInstance(e)&&e.response_metadata?.output_version===`v1`)return{role:t,content:Yq(e)};if(Jt.isInstance(e)&&e.tool_calls?.length){if(typeof e.content==`string`)return e.content===``?{role:t,content:e.tool_calls.map(Qq)}:{role:t,content:[{type:`text`,text:e.content},...e.tool_calls.map(Qq)]};{let{content:n}=e,r=eJ(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(Qq)]}}}else return{role:t,content:eJ(e,Jt.isInstance(e)?e.tool_calls:void 0)}})),system:n}}function nJ(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 rJ(e){return e.type===`enabled`||e.type===`adaptive`}function iJ(e){return e?.startsWith(`claude-opus-4-7`)??!1}function aJ(e,t){let n=t&&typeof t==`object`&&`task_budget`in t&&t.task_budget!=null;return iJ(e)&&n?[`task-budgets-2026-03-13`]:[]}function oJ(e){let{model:t,thinking:n,topK:r,topP:i,temperature:a}=e,o=iJ(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(rJ(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 sJ(e){let{model:t,thinking:n,topK:r,topP:i,temperature:a}=e,o={};return rJ(n)||iJ(t)?o:(a!==void 0&&(o.temperature=a),r!==void 0&&(o.top_k=r),i!==void 0&&(o.top_p=i),o)}function cJ(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=uJ(i);return{chunk:new Zt({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 Zt({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 Zt({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 Zt({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 Zt({content:[{index:e.index,...t,type:`thinking`}],response_metadata:n})}:{chunk:new Zt({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 Zt({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 Zt({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 Zt({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 Zt({content:t.coerceContentToString?r:[{index:e.index,...e.content_block}],response_metadata:n})}}else if(e.type===`content_block_start`&&Fq(e.content_block))return{chunk:new Zt({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 Zt({content:t.coerceContentToString?``:[{index:e.index,...e.delta,type:`compaction`}],response_metadata:n})};return null}function lJ(e,t){let n={...t,model_provider:`anthropic`},r=t.usage,i=r==null?void 0:uJ(r);return e.length===1&&e[0].type===`text`?[{text:e[0].text,message:new Jt({content:e[0].text,additional_kwargs:t,usage_metadata:i,response_metadata:n,id:t.id})}]:[{text:``,message:new Jt({content:e,additional_kwargs:t,tool_calls:kq(e),usage_metadata:i,response_metadata:n,id:t.id})}]}function uJ(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 dJ(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 fJ(e){let t;return t=e.status===400&&typeof e.message==`string`&&e.message.includes(`prompt is too long`)?dJ(m.fromError(e),`CONTEXT_OVERFLOW`):e.status===400&&e.message.includes(`tool`)?dJ(e,`INVALID_TOOL_RESULTS`):e.status===401?dJ(e,`MODEL_AUTHENTICATION`):e.status===404?dJ(e,`MODEL_NOT_FOUND`):e.status===429?dJ(e,`MODEL_RATE_LIMIT`):e,t}var pJ={"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*mJ(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=gJ(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:hJ(a),...i?{usage:i}:{},metadata:{model_provider:`anthropic`}};break;case`content_block_start`:{let{index:e,content_block:n}=t,i=_J(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}=vJ(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:yJ(n)},r.delete(e);break}default:yield{event:`provider`,provider:`anthropic`,name:t.type,payload:t};break}}function hJ(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 gJ(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 _J(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 vJ(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 yJ(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 bJ=function(){let{crypto:e}=globalThis;if(e?.randomUUID)return bJ=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 xJ(e){return typeof e==`object`&&!!e&&(`name`in e&&e.name===`AbortError`||`message`in e&&String(e.message).includes(`FetchRequestCanceledException`))}var SJ=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{},CJ=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 TJ({message:r,cause:SJ(n)});let a=n,o=a?.error?.type;return t===400?new DJ(t,a,r,i,o):t===401?new OJ(t,a,r,i,o):t===403?new kJ(t,a,r,i,o):t===404?new AJ(t,a,r,i,o):t===409?new jJ(t,a,r,i,o):t===422?new MJ(t,a,r,i,o):t===429?new NJ(t,a,r,i,o):t>=500?new PJ(t,a,r,i,o):new e(t,a,r,i,o)}},wJ=class extends CJ{constructor({message:e}={}){super(void 0,void 0,e||`Request was aborted.`,void 0)}},TJ=class extends CJ{constructor({message:e,cause:t}){super(void 0,void 0,e||`Connection error.`,void 0),t&&(this.cause=t)}},EJ=class extends TJ{constructor({message:e}={}){super({message:e??`Request timed out.`})}},DJ=class extends CJ{},OJ=class extends CJ{},kJ=class extends CJ{},AJ=class extends CJ{},jJ=class extends CJ{},MJ=class extends CJ{},NJ=class extends CJ{},PJ=class extends CJ{},FJ=/^[a-z][a-z0-9+.-]*:/i,IJ=e=>FJ.test(e),LJ=e=>(LJ=Array.isArray,LJ(e)),RJ=LJ;function zJ(e){return typeof e==`object`?e??{}:{}}function BJ(e){if(!e)return!0;for(let t in e)return!1;return!0}function VJ(e,t){return Object.prototype.hasOwnProperty.call(e,t)}var HJ=(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},UJ=e=>{try{return JSON.parse(e)}catch{return}},WJ=(e,t)=>{let n=e[t];return delete e[t],n},GJ=e=>new Promise(t=>setTimeout(t,e)),KJ=`0.91.1`,qJ=()=>typeof window<`u`&&window.document!==void 0&&typeof navigator<`u`;function JJ(){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 YJ=()=>{let e=JJ();if(e===`deno`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":KJ,"X-Stainless-OS":QJ(Deno.build.os),"X-Stainless-Arch":ZJ(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":KJ,"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":KJ,"X-Stainless-OS":QJ(globalThis.process.platform??`unknown`),"X-Stainless-Arch":ZJ(globalThis.process.arch??`unknown`),"X-Stainless-Runtime":`node`,"X-Stainless-Runtime-Version":globalThis.process.version??`unknown`};let t=XJ();return t?{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":KJ,"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":KJ,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`unknown`,"X-Stainless-Runtime":`unknown`,"X-Stainless-Runtime-Version":`unknown`}};function XJ(){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 ZJ=e=>e===`x32`?`x32`:e===`x86_64`||e===`x64`?`x64`:e===`arm`?`arm`:e===`aarch64`||e===`arm64`?`arm64`:e?`other:${e}`:`unknown`,QJ=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`),$J,eY=()=>$J??=YJ();function tY(){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 nY(...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 rY(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return nY({start(){},async pull(e){let{done:n,value:r}=await t.next();n?e.close():e.enqueue(r)},async cancel(){await t.return?.()}})}function iY(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 aY(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 oY=({headers:e,body:t})=>({bodyHeaders:{"content-type":`application/json`},body:JSON.stringify(t)});function sY(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 cY(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 lY;function uY(e){let t;return(lY??=(t=new globalThis.TextEncoder,t.encode.bind(t)))(e)}var dY;function fY(e){let t;return(dY??=(t=new globalThis.TextDecoder,t.decode.bind(t)))(e)}var pY,mY,hY=class{constructor(){pY.set(this,void 0),mY.set(this,void 0),Y(this,pY,new Uint8Array,`f`),Y(this,mY,null,`f`)}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e==`string`?uY(e):e;Y(this,pY,cY([X(this,pY,`f`),t]),`f`);let n=[],r;for(;(r=gY(X(this,pY,`f`),X(this,mY,`f`)))!=null;){if(r.carriage&&X(this,mY,`f`)==null){Y(this,mY,r.index,`f`);continue}if(X(this,mY,`f`)!=null&&(r.index!==X(this,mY,`f`)+1||r.carriage)){n.push(fY(X(this,pY,`f`).subarray(0,X(this,mY,`f`)-1))),Y(this,pY,X(this,pY,`f`).subarray(X(this,mY,`f`)),`f`),Y(this,mY,null,`f`);continue}let e=X(this,mY,`f`)===null?r.preceding:r.preceding-1,t=fY(X(this,pY,`f`).subarray(0,e));n.push(t),Y(this,pY,X(this,pY,`f`).subarray(r.index),`f`),Y(this,mY,null,`f`)}return n}flush(){return X(this,pY,`f`).length?this.decode(`
215
+ `):[]}};pY=new WeakMap,mY=new WeakMap,hY.NEWLINE_CHARS=new Set([`
216
+ `,`\r`]),hY.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function gY(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 _Y(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 vY={off:0,error:200,warn:300,info:400,debug:500},yY=(e,t,n)=>{if(e){if(VJ(vY,e))return e;wY(n).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(vY))}`)}};function bY(){}function xY(e,t,n){return!t||vY[e]>vY[n]?bY:t[e].bind(t)}var SY={error:bY,warn:bY,info:bY,debug:bY},CY=new WeakMap;function wY(e){let t=e.logger,n=e.logLevel??`off`;if(!t)return SY;let r=CY.get(t);if(r&&r[0]===n)return r[1];let i={error:xY(`error`,t,n),warn:xY(`warn`,t,n),info:xY(`info`,t,n),debug:xY(`debug`,t,n)};return CY.set(t,[n,i]),i}var TY=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),EY,DY=class e{constructor(e,t,n){this.iterator=e,EY.set(this,void 0),this.controller=t,Y(this,EY,n,`f`)}static fromSSEResponse(t,n,r){let i=!1,a=r?wY(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 OY(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=UJ(e.data)??e.data,r=n?.error?.type;throw new CJ(void 0,n,void 0,t.headers,r)}}e=!0}catch(e){if(xJ(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 hY,n=iY(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(xJ(e))return;throw e}finally{e||n.abort()}}return new e(o,n,r)}[(EY=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,EY,`f`)),new e(()=>i(n),this.controller,X(this,EY,`f`))]}toReadableStream(){let e=this,t;return nY({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=uY(JSON.stringify(n)+`
217
+ `);e.enqueue(i)}catch(t){e.error(t)}},async cancel(){await t.return?.()}})}};async function*OY(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 AY,r=new hY,i=iY(e.body);for await(let e of kY(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*kY(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`?uY(n):n,r=new Uint8Array(t.length+e.length);r.set(t),r.set(e,t.length),t=r;let i;for(;(i=_Y(t))!==-1;)yield t.slice(0,i),t=t.slice(i)}t.length>0&&(yield t)}var AY=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(`
218
+ `),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]=jY(e,`:`);return r.startsWith(` `)&&(r=r.substring(1)),t===`event`?this.event=r:t===`data`&&this.data.push(r),null}};function jY(e,t){let n=e.indexOf(t);return n===-1?[e,``,``]:[e.substring(0,n),t,e.substring(n+t.length)]}async function MY(e,t){let{response:n,requestLogID:r,retryOfRequestLogID:i,startTime:a}=t,o=await(async()=>{if(t.options.stream)return wY(e).debug(`response`,n.status,n.url,n.headers,n.body),t.options.__streamClass?t.options.__streamClass.fromSSEResponse(n,t.controller):DY.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:NY(await n.json(),n):await n.text()})();return wY(e).debug(`[${r}] response parsed`,TY({retryOfRequestLogID:i,url:n.url,status:n.status,body:o,durationMs:Date.now()-a})),o}function NY(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 PY,FY=class e extends Promise{constructor(e,t,n=MY){super(e=>{e(null)}),this.responsePromise=t,this.parseResponse=n,PY.set(this,void 0),Y(this,PY,e,`f`)}_thenUnwrap(t){return new e(X(this,PY,`f`),this.responsePromise,async(e,n)=>NY(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,PY,`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)}};PY=new WeakMap;var IY,LY=class{constructor(e,t,n,r){IY.set(this,void 0),Y(this,IY,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,IY,`f`).requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(IY=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}},RY=class extends FY{constructor(e,t,n){super(e,t,async(e,t)=>new n(e,t.response,await MY(e,t),t.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}},zY=class extends LY{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:{...zJ(this.options.query),before_id:e}}:null}let e=this.last_id;return e?{...this.options,query:{...zJ(this.options.query),after_id:e}}:null}},BY=class extends LY{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:{...zJ(this.options.query),page:e}}:null}},VY=()=>{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 HY(e,t,n){return VY(),new File(e,t??`unknown_file`,n)}function UY(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 WY=e=>typeof e==`object`&&!!e&&typeof e[Symbol.asyncIterator]==`function`,GY=async(e,t,n=!0)=>({...e,body:await JY(e.body,t,n)}),KY=new WeakMap;function qY(e){let t=typeof e==`function`?e:e.fetch,n=KY.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 KY.set(t,r),r}var JY=async(e,t,n=!0)=>{if(!await qY(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])=>XY(r,e,t,n))),r},YY=e=>e instanceof Blob&&`name`in e,XY=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,HY([await n.blob()],UY(n,r),i))}else if(WY(n))e.append(t,HY([await new Response(rY(n)).blob()],UY(n,r)));else if(YY(n))e.append(t,HY([n],UY(n,r),{type:n.type}));else if(Array.isArray(n))await Promise.all(n.map(n=>XY(e,t+`[]`,n,r)));else if(typeof n==`object`)await Promise.all(Object.entries(n).map(([n,i])=>XY(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`)}},ZY=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`,QY=e=>typeof e==`object`&&!!e&&typeof e.name==`string`&&typeof e.lastModified==`number`&&ZY(e),$Y=e=>typeof e==`object`&&!!e&&typeof e.url==`string`&&typeof e.blob==`function`;async function eX(e,t,n){if(VY(),e=await e,t||=UY(e,!0),QY(e))return e instanceof File&&t==null&&n==null?e:HY([await e.arrayBuffer()],t??e.name,{type:e.type,lastModified:e.lastModified,...n});if($Y(e)){let r=await e.blob();return t||=new URL(e.url).pathname.split(/[\\/]/).pop(),HY(await tX(r),t,n)}let r=await tX(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 HY(r,t,n)}async function tX(e){let t=[];if(typeof e==`string`||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(ZY(e))t.push(e instanceof Blob?e:await e.arrayBuffer());else if(WY(e))for await(let n of e)t.push(...await tX(n));else{let t=e?.constructor?.name;throw Error(`Unexpected data type: ${typeof e}${t?`; constructor: ${t}`:``}${nX(e)}`)}return t}function nX(e){return typeof e!=`object`||!e?``:`; props: [${Object.getOwnPropertyNames(e).map(e=>`"${e}"`).join(`, `)}]`}var rX=class{constructor(e){this._client=e}},iX=Symbol.for(`brand.privateNullableHeaders`);function*aX(e){if(!e)return;if(iX 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():RJ(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=RJ(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 aX(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{[iX]:!0,values:t,nulls:n}};function oX(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var sX=Object.freeze(Object.create(null)),$=((e=oX)=>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??sX)??sX)?.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(`
219
+ `)}\n${a}\n${t}`)}return a})(oX),cX=class extends rX{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`,BY,{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])})}},lX=Symbol(`anthropic.sdk.stainlessHelper`);function uX(e){return typeof e==`object`&&!!e&&lX in e}function dX(e,t){let n=new Set;if(e)for(let t of e)uX(t)&&n.add(t[lX]);if(t){for(let e of t)if(uX(e)&&n.add(e[lX]),Array.isArray(e.content))for(let t of e.content)uX(t)&&n.add(t[lX])}return Array.from(n)}function fX(e,t){let n=dX(e,t);return n.length===0?{}:{"x-stainless-helper":n.join(`, `)}}function pX(e){return uX(e)?{"x-stainless-helper":e[lX]}:{}}var mX=class extends rX{list(e={},t){let{betas:n,...r}=e??{};return this._client.getAPIList(`/v1/files?beta=true`,zY,{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`,GY({body:r,...t,headers:Q([{"anthropic-beta":[...n??[],`files-api-2025-04-14`].toString()},pX(r.file),t?.headers])},this._client))}},hX=class extends rX{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`,zY,{query:r,...t,headers:Q([{...n?.toString()==null?void 0:{"anthropic-beta":n?.toString()}},t?.headers])})}},gX=class extends rX{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`,BY,{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])})}},_X=class extends rX{list(e,t={},n){let{betas:r,...i}=t??{};return this._client.getAPIList($`/v1/agents/${e}/versions?beta=true`,BY,{query:i,...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}},vX=class extends rX{constructor(){super(...arguments),this.versions=new _X(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`,BY,{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])})}};vX.Versions=_X;var yX=class extends rX{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`,BY,{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])})}},bX=class extends rX{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`,BY,{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])})}},xX=class extends rX{constructor(){super(...arguments),this.memories=new yX(this._client),this.memoryVersions=new bX(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`,BY,{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])})}};xX.Memories=yX,xX.MemoryVersions=bX;var SX={"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 CX(e){return e?.output_format??e?.output_config?.format}function wX(e,t,n){let r=CX(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}:TX(e,t,n)}function TX(e,t,n){let r=null,i=e.content.map(e=>{if(e.type===`text`){let i=EX(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 EX(e,t){let n=CX(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 DX=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},OX=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),OX(e);case`number`:let n=t.value[t.value.length-1];if(n===`.`||n===`-`)return e=e.slice(0,e.length-1),OX(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),OX(e);break;case`delimiter`:return e=e.slice(0,e.length-1),OX(e)}return e},kX=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},AX=e=>{let t=``;return e.map(e=>{switch(e.type){case`string`:t+=`"`+e.value+`"`;break;default:t+=e.value;break}}),t},jX=e=>JSON.parse(AX(kX(OX(DX(e))))),MX,NX,PX,FX,IX,LX,RX,zX,BX,VX,HX,UX,WX,GX,KX,qX,JX,YX,XX,ZX,QX,$X,eZ,tZ,nZ=`__json_buf`;function rZ(e){return e.type===`tool_use`||e.type===`server_tool_use`||e.type===`mcp_tool_use`}var iZ=class e{constructor(e,t){MX.add(this),this.messages=[],this.receivedMessages=[],NX.set(this,void 0),PX.set(this,null),this.controller=new AbortController,FX.set(this,void 0),IX.set(this,()=>{}),LX.set(this,()=>{}),RX.set(this,void 0),zX.set(this,()=>{}),BX.set(this,()=>{}),VX.set(this,{}),HX.set(this,!1),UX.set(this,!1),WX.set(this,!1),GX.set(this,!1),KX.set(this,void 0),qX.set(this,void 0),JX.set(this,void 0),ZX.set(this,e=>{if(Y(this,UX,!0,`f`),xJ(e)&&(e=new wJ),e instanceof wJ)return Y(this,WX,!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,FX,new Promise((e,t)=>{Y(this,IX,e,`f`),Y(this,LX,t,`f`)}),`f`),Y(this,RX,new Promise((e,t)=>{Y(this,zX,e,`f`),Y(this,BX,t,`f`)}),`f`),X(this,FX,`f`).catch(()=>{}),X(this,RX,`f`).catch(()=>{}),Y(this,PX,e,`f`),Y(this,JX,t?.logger??console,`f`)}get response(){return X(this,KX,`f`)}get request_id(){return X(this,qX,`f`)}async withResponse(){Y(this,GX,!0,`f`);let e=await X(this,FX,`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,PX,{...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,ZX,`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,MX,`m`,QX).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,MX,`m`,$X).call(this,e);if(i.controller.signal?.aborted)throw new wJ;X(this,MX,`m`,eZ).call(this)}finally{r&&i&&r.removeEventListener(`abort`,i)}}_connected(e){this.ended||(Y(this,KX,e,`f`),Y(this,qX,e?.headers.get(`request-id`),`f`),X(this,IX,`f`).call(this,e),this._emit(`connect`))}get ended(){return X(this,HX,`f`)}get errored(){return X(this,UX,`f`)}get aborted(){return X(this,WX,`f`)}abort(){this.controller.abort()}on(e,t){return(X(this,VX,`f`)[e]||(X(this,VX,`f`)[e]=[])).push({listener:t}),this}off(e,t){let n=X(this,VX,`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,VX,`f`)[e]||(X(this,VX,`f`)[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,n)=>{Y(this,GX,!0,`f`),e!==`error`&&this.once(`error`,n),this.once(e,t)})}async done(){Y(this,GX,!0,`f`),await X(this,RX,`f`)}get currentMessage(){return X(this,NX,`f`)}async finalMessage(){return await this.done(),X(this,MX,`m`,YX).call(this)}async finalText(){return await this.done(),X(this,MX,`m`,XX).call(this)}_emit(e,...t){if(X(this,HX,`f`))return;e===`end`&&(Y(this,HX,!0,`f`),X(this,zX,`f`).call(this));let n=X(this,VX,`f`)[e];if(n&&(X(this,VX,`f`)[e]=n.filter(e=>!e.once),n.forEach(({listener:e})=>e(...t))),e===`abort`){let e=t[0];!X(this,GX,`f`)&&!n?.length&&Promise.reject(e),X(this,LX,`f`).call(this,e),X(this,BX,`f`).call(this,e),this._emit(`end`);return}if(e===`error`){let e=t[0];!X(this,GX,`f`)&&!n?.length&&Promise.reject(e),X(this,LX,`f`).call(this,e),X(this,BX,`f`).call(this,e),this._emit(`end`)}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit(`finalMessage`,X(this,MX,`m`,YX).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,MX,`m`,QX).call(this),this._connected(null);let t=DY.fromReadableStream(e,this.controller);for await(let e of t)X(this,MX,`m`,$X).call(this,e);if(t.controller.signal?.aborted)throw new wJ;X(this,MX,`m`,eZ).call(this)}finally{n&&r&&n.removeEventListener(`abort`,r)}}[(NX=new WeakMap,PX=new WeakMap,FX=new WeakMap,IX=new WeakMap,LX=new WeakMap,RX=new WeakMap,zX=new WeakMap,BX=new WeakMap,VX=new WeakMap,HX=new WeakMap,UX=new WeakMap,WX=new WeakMap,GX=new WeakMap,KX=new WeakMap,qX=new WeakMap,JX=new WeakMap,ZX=new WeakMap,MX=new WeakSet,YX=function(){if(this.receivedMessages.length===0)throw new Z(`stream ended without producing a Message with role=assistant`);return this.receivedMessages.at(-1)},XX=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(` `)},QX=function(){this.ended||Y(this,NX,void 0,`f`)},$X=function(e){if(this.ended)return;let t=X(this,MX,`m`,tZ).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`:rZ(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(wX(t,X(this,PX,`f`),{logger:X(this,JX,`f`)}),!0);break;case`content_block_stop`:this._emit(`contentBlock`,t.content.at(-1));break;case`message_start`:Y(this,NX,t,`f`);break;case`content_block_start`:case`message_delta`:break}},eZ=function(){if(this.ended)throw new Z(`stream has ended, this shouldn't happen`);let e=X(this,NX,`f`);if(!e)throw new Z(`request ended without sending any chunks`);return Y(this,NX,void 0,`f`),wX(e,X(this,PX,`f`),{logger:X(this,JX,`f`)})},tZ=function(e){let t=X(this,NX,`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&&rZ(n)){let r=n[nZ]||``;r+=e.delta.partial_json;let i={...n};if(Object.defineProperty(i,nZ,{value:r,enumerable:!1,writable:!0}),r)try{i.input=jX(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,ZX,`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 DY(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}},aZ=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}},oZ=`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:
219
220
  1. Task Overview
220
221
  The user's core request and success criteria
221
222
  Any clarifications or constraints they specified
@@ -237,22 +238,22 @@ User preferences or style requirements
237
238
  Domain-specific details that aren't obvious
238
239
  Any promises made to the user
239
240
  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.
240
- Wrap your summary in <summary></summary> tags.`,vX,yX,bX,xX,SX,CX,wX,TX,EX,DX,OX;function kX(){let e,t;return{promise:new Promise((n,r)=>{e=n,t=r}),resolve:e,reject:t}}var AX=class{constructor(e,t,n){vX.add(this),this.client=e,yX.set(this,!1),bX.set(this,!1),xX.set(this,void 0),SX.set(this,void 0),CX.set(this,void 0),wX.set(this,void 0),TX.set(this,void 0),EX.set(this,0),Y(this,xX,{params:{...t,messages:structuredClone(t.messages)}},`f`);let r=[`BetaToolRunner`,...SY(t.tools,t.messages)].join(`, `);Y(this,SX,{...n,headers:Q([{"x-stainless-helper":r},n?.headers])},`f`),Y(this,TX,kX(),`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*[(yX=new WeakMap,bX=new WeakMap,xX=new WeakMap,SX=new WeakMap,CX=new WeakMap,wX=new WeakMap,TX=new WeakMap,EX=new WeakMap,vX=new WeakSet,DX=async function(){let e=X(this,xX,`f`).params.compactionControl;if(!e||!e.enabled)return!1;let t=0;if(X(this,CX,`f`)!==void 0)try{let e=await X(this,CX,`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,xX,`f`).params.model,i=e.summaryPrompt??_X,a=X(this,xX,`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,xX,`f`).params.max_tokens},{signal:X(this,SX,`f`).signal,headers:Q([X(this,SX,`f`).headers,{"x-stainless-helper":`compaction`}])});if(o.content[0]?.type!==`text`)throw new Z(`Expected text response for compaction`);return X(this,xX,`f`).params.messages=[{role:`user`,content:o.content}],!0},Symbol.asyncIterator)](){var e;if(X(this,yX,`f`))throw new Z(`Cannot iterate over a consumed stream`);Y(this,yX,!0,`f`),Y(this,bX,!0,`f`),Y(this,wX,void 0,`f`);try{for(;;){let t;try{if(X(this,xX,`f`).params.max_iterations&&X(this,EX,`f`)>=X(this,xX,`f`).params.max_iterations)break;Y(this,bX,!1,`f`),Y(this,wX,void 0,`f`),Y(this,EX,(e=X(this,EX,`f`),e++,e),`f`),Y(this,CX,void 0,`f`);let{max_iterations:n,compactionControl:r,...i}=X(this,xX,`f`).params;if(i.stream?(t=this.client.beta.messages.stream({...i},X(this,SX,`f`)),Y(this,CX,t.finalMessage(),`f`),X(this,CX,`f`).catch(()=>{}),yield t):(Y(this,CX,this.client.beta.messages.create({...i,stream:!1},X(this,SX,`f`)),`f`),yield X(this,CX,`f`)),!await X(this,vX,`m`,DX).call(this)){if(!X(this,bX,`f`)){let{role:e,content:t}=await X(this,CX,`f`);X(this,xX,`f`).params.messages.push({role:e,content:t})}let e=await X(this,vX,`m`,OX).call(this,X(this,xX,`f`).params.messages.at(-1));if(e)X(this,xX,`f`).params.messages.push(e);else if(!X(this,bX,`f`))break}}finally{t&&t.abort()}}if(!X(this,CX,`f`))throw new Z(`ToolRunner concluded without a message from the server`);X(this,TX,`f`).resolve(await X(this,CX,`f`))}catch(e){throw Y(this,yX,!1,`f`),X(this,TX,`f`).promise.catch(()=>{}),X(this,TX,`f`).reject(e),Y(this,TX,kX(),`f`),e}}setMessagesParams(e){typeof e==`function`?X(this,xX,`f`).params=e(X(this,xX,`f`).params):X(this,xX,`f`).params=e,Y(this,bX,!0,`f`),Y(this,wX,void 0,`f`)}setRequestOptions(e){typeof e==`function`?Y(this,SX,e(X(this,SX,`f`)),`f`):Y(this,SX,{...X(this,SX,`f`),...e},`f`)}async generateToolResponse(e=X(this,SX,`f`).signal){let t=await X(this,CX,`f`)??this.params.messages.at(-1);return t?X(this,vX,`m`,OX).call(this,t,e):null}done(){return X(this,TX,`f`).promise}async runUntilDone(){if(!X(this,yX,`f`))for await(let e of this);return this.done()}get params(){return X(this,xX,`f`).params}pushMessages(...e){this.setMessagesParams(t=>({...t,messages:[...t.messages,...e]}))}then(e,t){return this.runUntilDone().then(e,t)}};OX=async function(e,t=X(this,SX,`f`).signal){return X(this,wX,`f`)===void 0&&Y(this,wX,jX(X(this,xX,`f`).params,e,{...X(this,SX,`f`),signal:t}),`f`),X(this,wX,`f`)};async function jX(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 gX?e.content:`Error: ${e instanceof Error?e.message:String(e)}`,is_error:!0}}}))}}var MX=class e{constructor(e,t){this.iterator=e,this.controller=t}async*decoder(){let e=new EJ;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(hJ(t.body),n)}},NX=class extends mY{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`,XJ,{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)=>MX.fromResponse(t.response,t.controller))}},PX={"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`},FX=[`claude-mythos-preview`,`claude-opus-4-6`],IX=class extends mY{constructor(){super(...arguments),this.batches=new NX(this._client)}create(e,t){let n=LX(e),{betas:r,...i}=n;i.model in PX&&console.warn(`The model '${i.model}' is deprecated and will reach end-of-life on ${PX[i.model]}\nPlease migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),FX.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=NY[i.model]??void 0;a=this._client.calculateNonstreamingTimeout(i.max_tokens,e)}let o=CY(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=>IY(t,e,{logger:this._client.logger??console}))}stream(e,t){return hX.createMessage(this,e,t)}countTokens(e,t){let{betas:n,...r}=LX(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 AX(this._client,e,t)}};function LX(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}}}IX.Batches=NX,IX.BetaToolRunner=AX,IX.ToolError=gX;var RX=class extends mY{list(e,t={},n){let{betas:r,...i}=t??{};return this._client.getAPIList($`/v1/sessions/${e}/events?beta=true`,ZJ,{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})}},zX=class extends mY{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`,ZJ,{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])})}},BX=class extends mY{constructor(){super(...arguments),this.events=new RX(this._client),this.resources=new zX(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`,ZJ,{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])})}};BX.Events=RX,BX.Resources=zX;var VX=class extends mY{create(e,t={},n){let{betas:r,...i}=t??{};return this._client.post($`/v1/skills/${e}/versions?beta=true`,nY({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`,ZJ,{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])})}},HX=class extends mY{constructor(){super(...arguments),this.versions=new VX(this._client)}create(e={},t){let{betas:n,...r}=e??{};return this._client.post(`/v1/skills?beta=true`,nY({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`,ZJ,{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])})}};HX.Versions=VX;var UX=class extends mY{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`,ZJ,{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])})}},WX=class extends mY{constructor(){super(...arguments),this.credentials=new UX(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`,ZJ,{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])})}};WX.Credentials=UX;var GX=class extends mY{constructor(){super(...arguments),this.models=new EY(this._client),this.messages=new IX(this._client),this.agents=new kY(this._client),this.environments=new yY(this._client),this.sessions=new BX(this._client),this.vaults=new WX(this._client),this.memoryStores=new MY(this._client),this.files=new TY(this._client),this.skills=new HX(this._client),this.userProfiles=new DY(this._client)}};GX.Models=EY,GX.Messages=IX,GX.Agents=kY,GX.Environments=yY,GX.Sessions=BX,GX.Vaults=WX,GX.MemoryStores=MY,GX.Files=TY,GX.Skills=HX,GX.UserProfiles=DY;var KX=class extends mY{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 qX(e){return e?.output_config?.format}function JX(e,t,n){let r=qX(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}:YX(e,t,n)}function YX(e,t,n){let r=null,i=e.content.map(e=>{if(e.type===`text`){let n=XX(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 XX(e,t){let n=qX(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 ZX,QX,$X,eZ,tZ,nZ,rZ,iZ,aZ,oZ,sZ,cZ,lZ,uZ,dZ,fZ,pZ,mZ,hZ,gZ,_Z,vZ,yZ,bZ,xZ=`__json_buf`;function SZ(e){return e.type===`tool_use`||e.type===`server_tool_use`}var CZ=class e{constructor(e,t){ZX.add(this),this.messages=[],this.receivedMessages=[],QX.set(this,void 0),$X.set(this,null),this.controller=new AbortController,eZ.set(this,void 0),tZ.set(this,()=>{}),nZ.set(this,()=>{}),rZ.set(this,void 0),iZ.set(this,()=>{}),aZ.set(this,()=>{}),oZ.set(this,{}),sZ.set(this,!1),cZ.set(this,!1),lZ.set(this,!1),uZ.set(this,!1),dZ.set(this,void 0),fZ.set(this,void 0),pZ.set(this,void 0),gZ.set(this,e=>{if(Y(this,cZ,!0,`f`),Mq(e)&&(e=new Fq),e instanceof Fq)return Y(this,lZ,!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,eZ,new Promise((e,t)=>{Y(this,tZ,e,`f`),Y(this,nZ,t,`f`)}),`f`),Y(this,rZ,new Promise((e,t)=>{Y(this,iZ,e,`f`),Y(this,aZ,t,`f`)}),`f`),X(this,eZ,`f`).catch(()=>{}),X(this,rZ,`f`).catch(()=>{}),Y(this,$X,e,`f`),Y(this,pZ,t?.logger??console,`f`)}get response(){return X(this,dZ,`f`)}get request_id(){return X(this,fZ,`f`)}async withResponse(){Y(this,uZ,!0,`f`);let e=await X(this,eZ,`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,$X,{...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,gZ,`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,ZX,`m`,_Z).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,ZX,`m`,vZ).call(this,e);if(i.controller.signal?.aborted)throw new Fq;X(this,ZX,`m`,yZ).call(this)}finally{r&&i&&r.removeEventListener(`abort`,i)}}_connected(e){this.ended||(Y(this,dZ,e,`f`),Y(this,fZ,e?.headers.get(`request-id`),`f`),X(this,tZ,`f`).call(this,e),this._emit(`connect`))}get ended(){return X(this,sZ,`f`)}get errored(){return X(this,cZ,`f`)}get aborted(){return X(this,lZ,`f`)}abort(){this.controller.abort()}on(e,t){return(X(this,oZ,`f`)[e]||(X(this,oZ,`f`)[e]=[])).push({listener:t}),this}off(e,t){let n=X(this,oZ,`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,oZ,`f`)[e]||(X(this,oZ,`f`)[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,n)=>{Y(this,uZ,!0,`f`),e!==`error`&&this.once(`error`,n),this.once(e,t)})}async done(){Y(this,uZ,!0,`f`),await X(this,rZ,`f`)}get currentMessage(){return X(this,QX,`f`)}async finalMessage(){return await this.done(),X(this,ZX,`m`,mZ).call(this)}async finalText(){return await this.done(),X(this,ZX,`m`,hZ).call(this)}_emit(e,...t){if(X(this,sZ,`f`))return;e===`end`&&(Y(this,sZ,!0,`f`),X(this,iZ,`f`).call(this));let n=X(this,oZ,`f`)[e];if(n&&(X(this,oZ,`f`)[e]=n.filter(e=>!e.once),n.forEach(({listener:e})=>e(...t))),e===`abort`){let e=t[0];!X(this,uZ,`f`)&&!n?.length&&Promise.reject(e),X(this,nZ,`f`).call(this,e),X(this,aZ,`f`).call(this,e),this._emit(`end`);return}if(e===`error`){let e=t[0];!X(this,uZ,`f`)&&!n?.length&&Promise.reject(e),X(this,nZ,`f`).call(this,e),X(this,aZ,`f`).call(this,e),this._emit(`end`)}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit(`finalMessage`,X(this,ZX,`m`,mZ).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,ZX,`m`,_Z).call(this),this._connected(null);let t=RJ.fromReadableStream(e,this.controller);for await(let e of t)X(this,ZX,`m`,vZ).call(this,e);if(t.controller.signal?.aborted)throw new Fq;X(this,ZX,`m`,yZ).call(this)}finally{n&&r&&n.removeEventListener(`abort`,r)}}[(QX=new WeakMap,$X=new WeakMap,eZ=new WeakMap,tZ=new WeakMap,nZ=new WeakMap,rZ=new WeakMap,iZ=new WeakMap,aZ=new WeakMap,oZ=new WeakMap,sZ=new WeakMap,cZ=new WeakMap,lZ=new WeakMap,uZ=new WeakMap,dZ=new WeakMap,fZ=new WeakMap,pZ=new WeakMap,gZ=new WeakMap,ZX=new WeakSet,mZ=function(){if(this.receivedMessages.length===0)throw new Z(`stream ended without producing a Message with role=assistant`);return this.receivedMessages.at(-1)},hZ=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(` `)},_Z=function(){this.ended||Y(this,QX,void 0,`f`)},vZ=function(e){if(this.ended)return;let t=X(this,ZX,`m`,bZ).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`:SZ(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(JX(t,X(this,$X,`f`),{logger:X(this,pZ,`f`)}),!0);break;case`content_block_stop`:this._emit(`contentBlock`,t.content.at(-1));break;case`message_start`:Y(this,QX,t,`f`);break;case`content_block_start`:case`message_delta`:break}},yZ=function(){if(this.ended)throw new Z(`stream has ended, this shouldn't happen`);let e=X(this,QX,`f`);if(!e)throw new Z(`request ended without sending any chunks`);return Y(this,QX,void 0,`f`),JX(e,X(this,$X,`f`),{logger:X(this,pZ,`f`)})},bZ=function(e){let t=X(this,QX,`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&&SZ(n)){let r=n[xZ]||``;r+=e.delta.partial_json;let i={...n};Object.defineProperty(i,xZ,{value:r,enumerable:!1,writable:!0}),r&&(i.input=HY(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 RJ(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}},wZ=class extends mY{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`,XJ,{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)=>MX.fromResponse(t.response,t.controller))}},TZ=class extends mY{constructor(){super(...arguments),this.batches=new wZ(this._client)}create(e,t){e.model in EZ&&console.warn(`The model '${e.model}' is deprecated and will reach end-of-life on ${EZ[e.model]}\nPlease migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),DZ.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=NY[e.model]??void 0;n=this._client.calculateNonstreamingTimeout(e.max_tokens,t)}let r=CY(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=>YX(t,e,{logger:this._client.logger??console}))}stream(e,t){return CZ.createMessage(this,e,t,{logger:this._client.logger??console})}countTokens(e,t){return this._client.post(`/v1/messages/count_tokens`,{body:e,...t})}},EZ={"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`},DZ=[`claude-mythos-preview`,`claude-opus-4-6`];TZ.Batches=wZ;var OZ=class extends mY{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`,XJ,{query:r,...t,headers:Q([{...n?.toString()==null?void 0:{"anthropic-beta":n?.toString()}},t?.headers])})}},kZ=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},AZ,jZ,MZ,NZ,PZ=`\\n\\nHuman:`,FZ=`\\n\\nAssistant:`,IZ=class{constructor({baseURL:e=kZ(`ANTHROPIC_BASE_URL`),apiKey:t=kZ(`ANTHROPIC_API_KEY`)??null,authToken:n=kZ(`ANTHROPIC_AUTH_TOKEN`)??null,...r}={}){AZ.add(this),MZ.set(this,void 0);let i={apiKey:t,authToken:n,...r,baseURL:e||`https://api.anthropic.com`};if(!i.dangerouslyAllowBrowser&&iJ())throw new Z(`It looks like you're running in a browser-like environment.
241
+ Wrap your summary in <summary></summary> tags.`,sZ,cZ,lZ,uZ,dZ,fZ,pZ,mZ,hZ,gZ,_Z;function vZ(){let e,t;return{promise:new Promise((n,r)=>{e=n,t=r}),resolve:e,reject:t}}var yZ=class{constructor(e,t,n){sZ.add(this),this.client=e,cZ.set(this,!1),lZ.set(this,!1),uZ.set(this,void 0),dZ.set(this,void 0),fZ.set(this,void 0),pZ.set(this,void 0),mZ.set(this,void 0),hZ.set(this,0),Y(this,uZ,{params:{...t,messages:structuredClone(t.messages)}},`f`);let r=[`BetaToolRunner`,...dX(t.tools,t.messages)].join(`, `);Y(this,dZ,{...n,headers:Q([{"x-stainless-helper":r},n?.headers])},`f`),Y(this,mZ,vZ(),`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*[(cZ=new WeakMap,lZ=new WeakMap,uZ=new WeakMap,dZ=new WeakMap,fZ=new WeakMap,pZ=new WeakMap,mZ=new WeakMap,hZ=new WeakMap,sZ=new WeakSet,gZ=async function(){let e=X(this,uZ,`f`).params.compactionControl;if(!e||!e.enabled)return!1;let t=0;if(X(this,fZ,`f`)!==void 0)try{let e=await X(this,fZ,`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,uZ,`f`).params.model,i=e.summaryPrompt??oZ,a=X(this,uZ,`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,uZ,`f`).params.max_tokens},{signal:X(this,dZ,`f`).signal,headers:Q([X(this,dZ,`f`).headers,{"x-stainless-helper":`compaction`}])});if(o.content[0]?.type!==`text`)throw new Z(`Expected text response for compaction`);return X(this,uZ,`f`).params.messages=[{role:`user`,content:o.content}],!0},Symbol.asyncIterator)](){var e;if(X(this,cZ,`f`))throw new Z(`Cannot iterate over a consumed stream`);Y(this,cZ,!0,`f`),Y(this,lZ,!0,`f`),Y(this,pZ,void 0,`f`);try{for(;;){let t;try{if(X(this,uZ,`f`).params.max_iterations&&X(this,hZ,`f`)>=X(this,uZ,`f`).params.max_iterations)break;Y(this,lZ,!1,`f`),Y(this,pZ,void 0,`f`),Y(this,hZ,(e=X(this,hZ,`f`),e++,e),`f`),Y(this,fZ,void 0,`f`);let{max_iterations:n,compactionControl:r,...i}=X(this,uZ,`f`).params;if(i.stream?(t=this.client.beta.messages.stream({...i},X(this,dZ,`f`)),Y(this,fZ,t.finalMessage(),`f`),X(this,fZ,`f`).catch(()=>{}),yield t):(Y(this,fZ,this.client.beta.messages.create({...i,stream:!1},X(this,dZ,`f`)),`f`),yield X(this,fZ,`f`)),!await X(this,sZ,`m`,gZ).call(this)){if(!X(this,lZ,`f`)){let{role:e,content:t}=await X(this,fZ,`f`);X(this,uZ,`f`).params.messages.push({role:e,content:t})}let e=await X(this,sZ,`m`,_Z).call(this,X(this,uZ,`f`).params.messages.at(-1));if(e)X(this,uZ,`f`).params.messages.push(e);else if(!X(this,lZ,`f`))break}}finally{t&&t.abort()}}if(!X(this,fZ,`f`))throw new Z(`ToolRunner concluded without a message from the server`);X(this,mZ,`f`).resolve(await X(this,fZ,`f`))}catch(e){throw Y(this,cZ,!1,`f`),X(this,mZ,`f`).promise.catch(()=>{}),X(this,mZ,`f`).reject(e),Y(this,mZ,vZ(),`f`),e}}setMessagesParams(e){typeof e==`function`?X(this,uZ,`f`).params=e(X(this,uZ,`f`).params):X(this,uZ,`f`).params=e,Y(this,lZ,!0,`f`),Y(this,pZ,void 0,`f`)}setRequestOptions(e){typeof e==`function`?Y(this,dZ,e(X(this,dZ,`f`)),`f`):Y(this,dZ,{...X(this,dZ,`f`),...e},`f`)}async generateToolResponse(e=X(this,dZ,`f`).signal){let t=await X(this,fZ,`f`)??this.params.messages.at(-1);return t?X(this,sZ,`m`,_Z).call(this,t,e):null}done(){return X(this,mZ,`f`).promise}async runUntilDone(){if(!X(this,cZ,`f`))for await(let e of this);return this.done()}get params(){return X(this,uZ,`f`).params}pushMessages(...e){this.setMessagesParams(t=>({...t,messages:[...t.messages,...e]}))}then(e,t){return this.runUntilDone().then(e,t)}};_Z=async function(e,t=X(this,dZ,`f`).signal){return X(this,pZ,`f`)===void 0&&Y(this,pZ,bZ(X(this,uZ,`f`).params,e,{...X(this,dZ,`f`),signal:t}),`f`),X(this,pZ,`f`)};async function bZ(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 aZ?e.content:`Error: ${e instanceof Error?e.message:String(e)}`,is_error:!0}}}))}}var xZ=class e{constructor(e,t){this.iterator=e,this.controller=t}async*decoder(){let e=new hY;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(iY(t.body),n)}},SZ=class extends rX{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`,zY,{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)=>xZ.fromResponse(t.response,t.controller))}},CZ={"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`},wZ=[`claude-mythos-preview`,`claude-opus-4-6`],TZ=class extends rX{constructor(){super(...arguments),this.batches=new SZ(this._client)}create(e,t){let n=EZ(e),{betas:r,...i}=n;i.model in CZ&&console.warn(`The model '${i.model}' is deprecated and will reach end-of-life on ${CZ[i.model]}\nPlease migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),wZ.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=SX[i.model]??void 0;a=this._client.calculateNonstreamingTimeout(i.max_tokens,e)}let o=fX(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=>TX(t,e,{logger:this._client.logger??console}))}stream(e,t){return iZ.createMessage(this,e,t)}countTokens(e,t){let{betas:n,...r}=EZ(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 yZ(this._client,e,t)}};function EZ(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}}}TZ.Batches=SZ,TZ.BetaToolRunner=yZ,TZ.ToolError=aZ;var DZ=class extends rX{list(e,t={},n){let{betas:r,...i}=t??{};return this._client.getAPIList($`/v1/sessions/${e}/events?beta=true`,BY,{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})}},OZ=class extends rX{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`,BY,{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])})}},kZ=class extends rX{constructor(){super(...arguments),this.events=new DZ(this._client),this.resources=new OZ(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`,BY,{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])})}};kZ.Events=DZ,kZ.Resources=OZ;var AZ=class extends rX{create(e,t={},n){let{betas:r,...i}=t??{};return this._client.post($`/v1/skills/${e}/versions?beta=true`,GY({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`,BY,{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])})}},jZ=class extends rX{constructor(){super(...arguments),this.versions=new AZ(this._client)}create(e={},t){let{betas:n,...r}=e??{};return this._client.post(`/v1/skills?beta=true`,GY({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`,BY,{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])})}};jZ.Versions=AZ;var MZ=class extends rX{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`,BY,{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])})}},NZ=class extends rX{constructor(){super(...arguments),this.credentials=new MZ(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`,BY,{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])})}};NZ.Credentials=MZ;var PZ=class extends rX{constructor(){super(...arguments),this.models=new hX(this._client),this.messages=new TZ(this._client),this.agents=new vX(this._client),this.environments=new cX(this._client),this.sessions=new kZ(this._client),this.vaults=new NZ(this._client),this.memoryStores=new xX(this._client),this.files=new mX(this._client),this.skills=new jZ(this._client),this.userProfiles=new gX(this._client)}};PZ.Models=hX,PZ.Messages=TZ,PZ.Agents=vX,PZ.Environments=cX,PZ.Sessions=kZ,PZ.Vaults=NZ,PZ.MemoryStores=xX,PZ.Files=mX,PZ.Skills=jZ,PZ.UserProfiles=gX;var FZ=class extends rX{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 IZ(e){return e?.output_config?.format}function LZ(e,t,n){let r=IZ(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}:RZ(e,t,n)}function RZ(e,t,n){let r=null,i=e.content.map(e=>{if(e.type===`text`){let n=zZ(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 zZ(e,t){let n=IZ(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 BZ,VZ,HZ,UZ,WZ,GZ,KZ,qZ,JZ,YZ,XZ,ZZ,QZ,$Z,eQ,tQ,nQ,rQ,iQ,aQ,oQ,sQ,cQ,lQ,uQ=`__json_buf`;function dQ(e){return e.type===`tool_use`||e.type===`server_tool_use`}var fQ=class e{constructor(e,t){BZ.add(this),this.messages=[],this.receivedMessages=[],VZ.set(this,void 0),HZ.set(this,null),this.controller=new AbortController,UZ.set(this,void 0),WZ.set(this,()=>{}),GZ.set(this,()=>{}),KZ.set(this,void 0),qZ.set(this,()=>{}),JZ.set(this,()=>{}),YZ.set(this,{}),XZ.set(this,!1),ZZ.set(this,!1),QZ.set(this,!1),$Z.set(this,!1),eQ.set(this,void 0),tQ.set(this,void 0),nQ.set(this,void 0),aQ.set(this,e=>{if(Y(this,ZZ,!0,`f`),xJ(e)&&(e=new wJ),e instanceof wJ)return Y(this,QZ,!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,UZ,new Promise((e,t)=>{Y(this,WZ,e,`f`),Y(this,GZ,t,`f`)}),`f`),Y(this,KZ,new Promise((e,t)=>{Y(this,qZ,e,`f`),Y(this,JZ,t,`f`)}),`f`),X(this,UZ,`f`).catch(()=>{}),X(this,KZ,`f`).catch(()=>{}),Y(this,HZ,e,`f`),Y(this,nQ,t?.logger??console,`f`)}get response(){return X(this,eQ,`f`)}get request_id(){return X(this,tQ,`f`)}async withResponse(){Y(this,$Z,!0,`f`);let e=await X(this,UZ,`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,HZ,{...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,aQ,`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,BZ,`m`,oQ).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,BZ,`m`,sQ).call(this,e);if(i.controller.signal?.aborted)throw new wJ;X(this,BZ,`m`,cQ).call(this)}finally{r&&i&&r.removeEventListener(`abort`,i)}}_connected(e){this.ended||(Y(this,eQ,e,`f`),Y(this,tQ,e?.headers.get(`request-id`),`f`),X(this,WZ,`f`).call(this,e),this._emit(`connect`))}get ended(){return X(this,XZ,`f`)}get errored(){return X(this,ZZ,`f`)}get aborted(){return X(this,QZ,`f`)}abort(){this.controller.abort()}on(e,t){return(X(this,YZ,`f`)[e]||(X(this,YZ,`f`)[e]=[])).push({listener:t}),this}off(e,t){let n=X(this,YZ,`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,YZ,`f`)[e]||(X(this,YZ,`f`)[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,n)=>{Y(this,$Z,!0,`f`),e!==`error`&&this.once(`error`,n),this.once(e,t)})}async done(){Y(this,$Z,!0,`f`),await X(this,KZ,`f`)}get currentMessage(){return X(this,VZ,`f`)}async finalMessage(){return await this.done(),X(this,BZ,`m`,rQ).call(this)}async finalText(){return await this.done(),X(this,BZ,`m`,iQ).call(this)}_emit(e,...t){if(X(this,XZ,`f`))return;e===`end`&&(Y(this,XZ,!0,`f`),X(this,qZ,`f`).call(this));let n=X(this,YZ,`f`)[e];if(n&&(X(this,YZ,`f`)[e]=n.filter(e=>!e.once),n.forEach(({listener:e})=>e(...t))),e===`abort`){let e=t[0];!X(this,$Z,`f`)&&!n?.length&&Promise.reject(e),X(this,GZ,`f`).call(this,e),X(this,JZ,`f`).call(this,e),this._emit(`end`);return}if(e===`error`){let e=t[0];!X(this,$Z,`f`)&&!n?.length&&Promise.reject(e),X(this,GZ,`f`).call(this,e),X(this,JZ,`f`).call(this,e),this._emit(`end`)}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit(`finalMessage`,X(this,BZ,`m`,rQ).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,BZ,`m`,oQ).call(this),this._connected(null);let t=DY.fromReadableStream(e,this.controller);for await(let e of t)X(this,BZ,`m`,sQ).call(this,e);if(t.controller.signal?.aborted)throw new wJ;X(this,BZ,`m`,cQ).call(this)}finally{n&&r&&n.removeEventListener(`abort`,r)}}[(VZ=new WeakMap,HZ=new WeakMap,UZ=new WeakMap,WZ=new WeakMap,GZ=new WeakMap,KZ=new WeakMap,qZ=new WeakMap,JZ=new WeakMap,YZ=new WeakMap,XZ=new WeakMap,ZZ=new WeakMap,QZ=new WeakMap,$Z=new WeakMap,eQ=new WeakMap,tQ=new WeakMap,nQ=new WeakMap,aQ=new WeakMap,BZ=new WeakSet,rQ=function(){if(this.receivedMessages.length===0)throw new Z(`stream ended without producing a Message with role=assistant`);return this.receivedMessages.at(-1)},iQ=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(` `)},oQ=function(){this.ended||Y(this,VZ,void 0,`f`)},sQ=function(e){if(this.ended)return;let t=X(this,BZ,`m`,lQ).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`:dQ(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(LZ(t,X(this,HZ,`f`),{logger:X(this,nQ,`f`)}),!0);break;case`content_block_stop`:this._emit(`contentBlock`,t.content.at(-1));break;case`message_start`:Y(this,VZ,t,`f`);break;case`content_block_start`:case`message_delta`:break}},cQ=function(){if(this.ended)throw new Z(`stream has ended, this shouldn't happen`);let e=X(this,VZ,`f`);if(!e)throw new Z(`request ended without sending any chunks`);return Y(this,VZ,void 0,`f`),LZ(e,X(this,HZ,`f`),{logger:X(this,nQ,`f`)})},lQ=function(e){let t=X(this,VZ,`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&&dQ(n)){let r=n[uQ]||``;r+=e.delta.partial_json;let i={...n};Object.defineProperty(i,uQ,{value:r,enumerable:!1,writable:!0}),r&&(i.input=jX(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 DY(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}},pQ=class extends rX{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`,zY,{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)=>xZ.fromResponse(t.response,t.controller))}},mQ=class extends rX{constructor(){super(...arguments),this.batches=new pQ(this._client)}create(e,t){e.model in hQ&&console.warn(`The model '${e.model}' is deprecated and will reach end-of-life on ${hQ[e.model]}\nPlease migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),gQ.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=SX[e.model]??void 0;n=this._client.calculateNonstreamingTimeout(e.max_tokens,t)}let r=fX(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=>RZ(t,e,{logger:this._client.logger??console}))}stream(e,t){return fQ.createMessage(this,e,t,{logger:this._client.logger??console})}countTokens(e,t){return this._client.post(`/v1/messages/count_tokens`,{body:e,...t})}},hQ={"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`},gQ=[`claude-mythos-preview`,`claude-opus-4-6`];mQ.Batches=pQ;var _Q=class extends rX{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`,zY,{query:r,...t,headers:Q([{...n?.toString()==null?void 0:{"anthropic-beta":n?.toString()}},t?.headers])})}},vQ=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},yQ,bQ,xQ,SQ,CQ=`\\n\\nHuman:`,wQ=`\\n\\nAssistant:`,TQ=class{constructor({baseURL:e=vQ(`ANTHROPIC_BASE_URL`),apiKey:t=vQ(`ANTHROPIC_API_KEY`)??null,authToken:n=vQ(`ANTHROPIC_AUTH_TOKEN`)??null,...r}={}){yQ.add(this),xQ.set(this,void 0);let i={apiKey:t,authToken:n,...r,baseURL:e||`https://api.anthropic.com`};if(!i.dangerouslyAllowBrowser&&qJ())throw new Z(`It looks like you're running in a browser-like environment.
241
242
 
242
243
  This is disabled by default, as it risks exposing your secret API credentials to attackers.
243
244
  If you understand the risks and have appropriate mitigations in place,
244
245
  you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
245
246
 
246
247
  new Anthropic({ apiKey, dangerouslyAllowBrowser: true });
247
- `);this.baseURL=i.baseURL,this.timeout=i.timeout??jZ.DEFAULT_TIMEOUT,this.logger=i.logger??console;let a=`warn`;this.logLevel=a,this.logLevel=AJ(i.logLevel,`ClientOptions.logLevel`,this)??AJ(kZ(`ANTHROPIC_LOG`),`process.env['ANTHROPIC_LOG']`,this)??a,this.fetchOptions=i.fetchOptions,this.maxRetries=i.maxRetries??2,this.fetch=i.fetch??fJ(),Y(this,MZ,_J,`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 vJ(e)}getUserAgent(){return`${this.constructor.name}/JS ${rJ}`}defaultIdempotencyKey(){return`stainless-node-retry-${jq()}`}makeStatusError(e,t,n,r){return Pq.generate(e,t,n,r)}buildURL(e,t,n){let r=!X(this,AZ,`m`,NZ).call(this)&&n||this.baseURL,i=qq(e)?new URL(e):new URL(r+(r.endsWith(`/`)&&e.startsWith(`/`)?e.slice(1):e)),a=this.defaultQuery(),o=Object.fromEntries(i.searchParams);return(!Zq(a)||!Zq(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 KJ(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(FJ(this).debug(`[${c}] sending request`,IJ({retryOfRequestLogID:n,method:r.method,url:o,options:r,headers:a.headers})),r.signal?.aborted)throw new Fq;let d=new AbortController,f=await this.fetchWithTimeout(o,a,s,d).catch(Nq),p=Date.now();if(f instanceof globalThis.Error){let e=`retrying, ${t} attempts remaining`;if(r.signal?.aborted)throw new Fq;let i=Mq(f)||/timed? ?out/i.test(String(f)+(`cause`in f?String(f.cause):``));if(t)return FJ(this).info(`[${c}] connection ${i?`timed out`:`failed`} - ${e}`),FJ(this).debug(`[${c}] connection ${i?`timed out`:`failed`} (${e})`,IJ({retryOfRequestLogID:n,url:o,durationMs:p-u,message:f.message})),this.retryRequest(r,t,n??c);throw FJ(this).info(`[${c}] connection ${i?`timed out`:`failed`} - error; no more retries left`),FJ(this).debug(`[${c}] connection ${i?`timed out`:`failed`} (error; no more retries left)`,IJ({retryOfRequestLogID:n,url:o,durationMs:p-u,message:f.message})),i?new Lq:new Iq({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 gJ(f.body),FJ(this).info(`${m} - ${e}`),FJ(this).debug(`[${c}] response error (${e})`,IJ({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`;FJ(this).info(`${m} - ${i}`);let a=await f.text().catch(e=>Nq(e).message),o=eJ(a),s=o?void 0:a;throw FJ(this).debug(`[${c}] response error (${i})`,IJ({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 FJ(this).info(m),FJ(this).debug(`[${c}] response start`,IJ({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 YJ(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 nJ(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&&$q(`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))}:{},...dJ(),...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:mJ(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,MZ,`f`).call(this,{body:e,headers:n})}};jZ=IZ,MZ=new WeakMap,AZ=new WeakSet,NZ=function(){return this.baseURL!==`https://api.anthropic.com`},IZ.Anthropic=jZ,IZ.HUMAN_PROMPT=PZ,IZ.AI_PROMPT=FZ,IZ.DEFAULT_TIMEOUT=6e5,IZ.AnthropicError=Z,IZ.APIError=Pq,IZ.APIConnectionError=Iq,IZ.APIConnectionTimeoutError=Lq,IZ.APIUserAbortError=Fq,IZ.NotFoundError=Vq,IZ.ConflictError=Hq,IZ.RateLimitError=Wq,IZ.BadRequestError=Rq,IZ.AuthenticationError=zq,IZ.InternalServerError=Gq,IZ.PermissionDeniedError=Bq,IZ.UnprocessableEntityError=Uq,IZ.toFile=dY;var LZ=class extends IZ{constructor(){super(...arguments),this.completions=new KX(this),this.messages=new TZ(this),this.models=new OZ(this),this.beta=new GX(this)}};LZ.Completions=KX,LZ.Messages=TZ,LZ.Models=OZ,LZ.Beta=GX;var RZ=new Set([`date-time`,`time`,`date`,`duration`,`email`,`hostname`,`uri`,`ipv4`,`ipv6`,`uuid`]);function zZ(e){return JSON.parse(JSON.stringify(e))}function BZ(e){return VZ(zZ(e))}function VZ(e){let t={},n=tJ(e,`$ref`);if(n!==void 0)return t.$ref=n,t;let r=tJ(e,`$defs`);if(r!==void 0){let e={};t.$defs=e;for(let[t,n]of Object.entries(r))e[t]=VZ(n)}let i=tJ(e,`type`),a=tJ(e,`anyOf`),o=tJ(e,`oneOf`),s=tJ(e,`allOf`);if(Array.isArray(a))t.anyOf=a.map(e=>VZ(e));else if(Array.isArray(o))t.anyOf=o.map(e=>VZ(e));else if(Array.isArray(s))t.allOf=s.map(e=>VZ(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=tJ(e,`description`);c!==void 0&&(t.description=c);let l=tJ(e,`title`);if(l!==void 0&&(t.title=l),i===`object`){let n=tJ(e,`properties`)||{};t.properties=Object.fromEntries(Object.entries(n).map(([e,t])=>[e,VZ(t)])),tJ(e,`additionalProperties`),t.additionalProperties=!1;let r=tJ(e,`required`);r!==void 0&&(t.required=r)}else if(i===`string`){let n=tJ(e,`format`);n!==void 0&&RZ.has(n)?t.format=n:n!==void 0&&(e.format=n)}else if(i===`array`){let n=tJ(e,`items`);n!==void 0&&(t.items=VZ(n));let r=tJ(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+`
248
+ `);this.baseURL=i.baseURL,this.timeout=i.timeout??bQ.DEFAULT_TIMEOUT,this.logger=i.logger??console;let a=`warn`;this.logLevel=a,this.logLevel=yY(i.logLevel,`ClientOptions.logLevel`,this)??yY(vQ(`ANTHROPIC_LOG`),`process.env['ANTHROPIC_LOG']`,this)??a,this.fetchOptions=i.fetchOptions,this.maxRetries=i.maxRetries??2,this.fetch=i.fetch??tY(),Y(this,xQ,oY,`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 sY(e)}getUserAgent(){return`${this.constructor.name}/JS ${KJ}`}defaultIdempotencyKey(){return`stainless-node-retry-${bJ()}`}makeStatusError(e,t,n,r){return CJ.generate(e,t,n,r)}buildURL(e,t,n){let r=!X(this,yQ,`m`,SQ).call(this)&&n||this.baseURL,i=IJ(e)?new URL(e):new URL(r+(r.endsWith(`/`)&&e.startsWith(`/`)?e.slice(1):e)),a=this.defaultQuery(),o=Object.fromEntries(i.searchParams);return(!BJ(a)||!BJ(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 FY(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(wY(this).debug(`[${c}] sending request`,TY({retryOfRequestLogID:n,method:r.method,url:o,options:r,headers:a.headers})),r.signal?.aborted)throw new wJ;let d=new AbortController,f=await this.fetchWithTimeout(o,a,s,d).catch(SJ),p=Date.now();if(f instanceof globalThis.Error){let e=`retrying, ${t} attempts remaining`;if(r.signal?.aborted)throw new wJ;let i=xJ(f)||/timed? ?out/i.test(String(f)+(`cause`in f?String(f.cause):``));if(t)return wY(this).info(`[${c}] connection ${i?`timed out`:`failed`} - ${e}`),wY(this).debug(`[${c}] connection ${i?`timed out`:`failed`} (${e})`,TY({retryOfRequestLogID:n,url:o,durationMs:p-u,message:f.message})),this.retryRequest(r,t,n??c);throw wY(this).info(`[${c}] connection ${i?`timed out`:`failed`} - error; no more retries left`),wY(this).debug(`[${c}] connection ${i?`timed out`:`failed`} (error; no more retries left)`,TY({retryOfRequestLogID:n,url:o,durationMs:p-u,message:f.message})),i?new EJ:new TJ({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 aY(f.body),wY(this).info(`${m} - ${e}`),wY(this).debug(`[${c}] response error (${e})`,TY({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`;wY(this).info(`${m} - ${i}`);let a=await f.text().catch(e=>SJ(e).message),o=UJ(a),s=o?void 0:a;throw wY(this).debug(`[${c}] response error (${i})`,TY({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 wY(this).info(m),wY(this).debug(`[${c}] response start`,TY({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 RY(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 GJ(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&&HJ(`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))}:{},...eY(),...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:rY(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,xQ,`f`).call(this,{body:e,headers:n})}};bQ=TQ,xQ=new WeakMap,yQ=new WeakSet,SQ=function(){return this.baseURL!==`https://api.anthropic.com`},TQ.Anthropic=bQ,TQ.HUMAN_PROMPT=CQ,TQ.AI_PROMPT=wQ,TQ.DEFAULT_TIMEOUT=6e5,TQ.AnthropicError=Z,TQ.APIError=CJ,TQ.APIConnectionError=TJ,TQ.APIConnectionTimeoutError=EJ,TQ.APIUserAbortError=wJ,TQ.NotFoundError=AJ,TQ.ConflictError=jJ,TQ.RateLimitError=NJ,TQ.BadRequestError=DJ,TQ.AuthenticationError=OJ,TQ.InternalServerError=PJ,TQ.PermissionDeniedError=kJ,TQ.UnprocessableEntityError=MJ,TQ.toFile=eX;var EQ=class extends TQ{constructor(){super(...arguments),this.completions=new FZ(this),this.messages=new mQ(this),this.models=new _Q(this),this.beta=new PZ(this)}};EQ.Completions=FZ,EQ.Messages=mQ,EQ.Models=_Q,EQ.Beta=PZ;var DQ=new Set([`date-time`,`time`,`date`,`duration`,`email`,`hostname`,`uri`,`ipv4`,`ipv6`,`uuid`]);function OQ(e){return JSON.parse(JSON.stringify(e))}function kQ(e){return AQ(OQ(e))}function AQ(e){let t={},n=WJ(e,`$ref`);if(n!==void 0)return t.$ref=n,t;let r=WJ(e,`$defs`);if(r!==void 0){let e={};t.$defs=e;for(let[t,n]of Object.entries(r))e[t]=AQ(n)}let i=WJ(e,`type`),a=WJ(e,`anyOf`),o=WJ(e,`oneOf`),s=WJ(e,`allOf`);if(Array.isArray(a))t.anyOf=a.map(e=>AQ(e));else if(Array.isArray(o))t.anyOf=o.map(e=>AQ(e));else if(Array.isArray(s))t.allOf=s.map(e=>AQ(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=WJ(e,`description`);c!==void 0&&(t.description=c);let l=WJ(e,`title`);if(l!==void 0&&(t.title=l),i===`object`){let n=WJ(e,`properties`)||{};t.properties=Object.fromEntries(Object.entries(n).map(([e,t])=>[e,AQ(t)])),WJ(e,`additionalProperties`),t.additionalProperties=!1;let r=WJ(e,`required`);r!==void 0&&(t.required=r)}else if(i===`string`){let n=WJ(e,`format`);n!==void 0&&DQ.has(n)?t.format=n:n!==void 0&&(e.format=n)}else if(i===`array`){let n=WJ(e,`items`);n!==void 0&&(t.items=AQ(n));let r=WJ(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+`
248
249
 
249
- `:``)+`{`+Object.entries(e).map(([e,t])=>`${e}: ${JSON.stringify(t)}`).join(`, `)+`}`}return t}var HZ={"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},UZ=4096;function WZ(e){return e?Object.entries(HZ).find(([t])=>e.startsWith(t))?.[1]??UZ:UZ}function GZ(e){return!!(e.tools&&e.tools.length>0)}function KZ(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 qZ(e){return!!(e.thinking&&(e.thinking.type===`enabled`||e.thinking.type===`adaptive`))}function JZ(e){return!!e.context_management?.edits?.some(e=>e.type===`compact_20260112`)}function YZ(e){return`input_schema`in e}function XZ(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 ZZ(e,t,...n){return Array.from(new Set([...e??[],...t??[],...n.flatMap(e=>Array.from(e))]))}function QZ(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 $Z=class extends cE{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??mr(`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??WZ(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 LZ(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(MO(e)&&e.extras?.providerToolDefinition)return e.extras.providerToolDefinition;if(XZ(e)||YZ(e))return e;if(qw(e))return{name:e.function.name,description:e.function.description,input_schema:e.function.parameters};if(MO(e))return{name:e.name,description:e.description,input_schema:Sg(e.schema)?Db(e.schema):e.schema,...e.extras?HK.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=VK(e?.tool_choice),n=e?.tools?.reduce((e,t)=>{if(typeof t==`object`&&`type`in t&&t.type in UK){let n=UK[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=gq(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:ZZ(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 _q({model:this.model,thinking:this.thinking,topK:this.topK,topP:this.topP,temperature:this.temperature}),Object.assign(o,vq({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=fq(e),a={...r,...i,stream:!0},o=!GZ(a)&&!KZ(a)&&!qZ(a)&&!JZ(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=yq(e,{streamUsage:r,coerceContentToString:o});if(!i)continue;let{chunk:a}=i,c=QZ(a),l=new Cu({message:new Zt({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=fq(e),a={...r,...i,stream:!0},o=await this.createStreamWithRetry(a,{headers:t.headers,signal:t.signal}),s=this.streamUsage??t.streamUsage;yield*Tq(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=fq(e),{content:i,...a}=await this.completionWithRetry({...t,stream:!1,...r},n),o=bq(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 Cq(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 Cq(e)}})}_llmType(){return`anthropic`}get profile(){return wq[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=AT(i);let e=BZ(Db(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(Sg(i)||By(i)){let n=Db(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=jT(i,e,zK),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:Db(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:Db(i)}})}else throw TypeError(`Unrecognized structured output method '${s}'. Expected 'functionCalling' or 'jsonSchema'`);return MT(n,r,o,o?`StructuredOutputRunnable`:`ChatAnthropicStructuredOutput`)}},eQ=class extends $Z{};Uk(`command`,[B({command:$k(`view`),path:z()}),B({command:$k(`create`),path:z(),file_text:z()}),B({command:$k(`str_replace`),path:z(),old_str:z(),new_str:z()}),B({command:$k(`insert`),path:z(),insert_line:Ek(),insert_text:z()}),B({command:$k(`delete`),path:z()}),B({command:$k(`rename`),old_path:z(),new_path:z()})]),Uk(`command`,[B({command:$k(`view`),path:z(),view_range:qk([Ek(),Ek()]).optional()}),B({command:$k(`str_replace`),path:z(),old_str:z(),new_str:z()}),B({command:$k(`create`),path:z(),file_text:z()}),B({command:$k(`insert`),path:z(),insert_line:Ek(),new_str:z()})]);var tQ=qk([Ek(),Ek()]),nQ=B({action:$k(`screenshot`)}),rQ=B({action:$k(`left_click`),coordinate:tQ}),iQ=B({action:$k(`right_click`),coordinate:tQ}),aQ=B({action:$k(`middle_click`),coordinate:tQ}),oQ=B({action:$k(`double_click`),coordinate:tQ}),sQ=B({action:$k(`triple_click`),coordinate:tQ}),cQ=B({action:$k(`left_click_drag`),start_coordinate:tQ,end_coordinate:tQ}),lQ=B({action:$k(`left_mouse_down`),coordinate:tQ}),uQ=B({action:$k(`left_mouse_up`),coordinate:tQ}),dQ=B({action:$k(`scroll`),coordinate:tQ,scroll_direction:Zk([`up`,`down`,`left`,`right`]),scroll_amount:Ek()}),fQ=B({action:$k(`type`),text:z()}),pQ=B({action:$k(`key`),key:z()}),mQ=B({action:$k(`mouse_move`),coordinate:tQ}),hQ=B({action:$k(`hold_key`),key:z()}),gQ=B({action:$k(`wait`),duration:Ek().optional()}),_Q=B({action:$k(`zoom`),region:qk([Ek(),Ek(),Ek(),Ek()])});Uk(`action`,[nQ,rQ,iQ,aQ,oQ,sQ,cQ,lQ,uQ,dQ,fQ,pQ,mQ,hQ,gQ]),Uk(`action`,[nQ,rQ,iQ,aQ,oQ,sQ,cQ,lQ,uQ,dQ,fQ,pQ,mQ,hQ,gQ,_Q]),Vk([B({command:z().describe(`The bash command to run`)}),B({restart:$k(!0).describe(`Set to true to restart the bash session`)})]);for(var vQ=[],yQ=0;yQ<256;++yQ)vQ.push((yQ+256).toString(16).slice(1));function bQ(e,t=0){return(vQ[e[t+0]]+vQ[e[t+1]]+vQ[e[t+2]]+vQ[e[t+3]]+`-`+vQ[e[t+4]]+vQ[e[t+5]]+`-`+vQ[e[t+6]]+vQ[e[t+7]]+`-`+vQ[e[t+8]]+vQ[e[t+9]]+`-`+vQ[e[t+10]]+vQ[e[t+11]]+vQ[e[t+12]]+vQ[e[t+13]]+vQ[e[t+14]]+vQ[e[t+15]]).toLowerCase()}var xQ,SQ=new Uint8Array(16);function CQ(){if(!xQ&&(xQ=typeof crypto<`u`&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!xQ))throw Error(`crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported`);return xQ(SQ)}var wQ={randomUUID:typeof crypto<`u`&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function TQ(e,t,n){if(wQ.randomUUID&&!t&&!e)return wQ.randomUUID();e||={};var r=e.random||(e.rng||CQ)();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 bQ(r)}function EQ(e,t){return new Zt({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:TQ()})),response_metadata:{...t?.responseMetadata,model_provider:`ollama`},usage_metadata:t?.usageMetadata})}function DQ(e){let t=e.match(/^data:.*?;base64,(.*)$/);return t?t[1]:``}function OQ(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 kQ(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:[DQ(e.image_url)]};if(e.image_url.url&&typeof e.image_url.url==`string`)return{role:`user`,content:``,images:[DQ(e.image_url.url)]}}throw Error(`Unsupported content type: ${e.type}`)})}function AQ(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 jQ(e){if(typeof e.content!=`string`)throw Error(`Non string tool message content is not supported`);return[{role:`tool`,content:e.content}]}function MQ(e){return e.flatMap(e=>{if([`human`,`generic`].includes(e._getType()))return kQ(e);if(e._getType()===`ai`)return OQ(e);if(e._getType()===`system`)return AQ(e);if(e._getType()===`tool`)return jQ(e);throw Error(`Unsupported message type: ${e._getType()}`)})}var NQ=typeof globalThis<`u`&&globalThis||typeof self<`u`&&self||typeof global<`u`&&global||{},PQ={searchParams:`URLSearchParams`in NQ,iterable:`Symbol`in NQ&&`iterator`in Symbol,blob:`FileReader`in NQ&&`Blob`in NQ&&(function(){try{return new Blob,!0}catch{return!1}})(),formData:`FormData`in NQ,arrayBuffer:`ArrayBuffer`in NQ};function FQ(e){return e&&DataView.prototype.isPrototypeOf(e)}if(PQ.arrayBuffer)var IQ=[`[object Int8Array]`,`[object Uint8Array]`,`[object Uint8ClampedArray]`,`[object Int16Array]`,`[object Uint16Array]`,`[object Int32Array]`,`[object Uint32Array]`,`[object Float32Array]`,`[object Float64Array]`],LQ=ArrayBuffer.isView||function(e){return e&&IQ.indexOf(Object.prototype.toString.call(e))>-1};function RQ(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 zQ(e){return typeof e!=`string`&&(e=String(e)),e}function BQ(e){var t={next:function(){var t=e.shift();return{done:t===void 0,value:t}}};return PQ.iterable&&(t[Symbol.iterator]=function(){return t}),t}function VQ(e){this.map={},e instanceof VQ?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)}VQ.prototype.append=function(e,t){e=RQ(e),t=zQ(t);var n=this.map[e];this.map[e]=n?n+`, `+t:t},VQ.prototype.delete=function(e){delete this.map[RQ(e)]},VQ.prototype.get=function(e){return e=RQ(e),this.has(e)?this.map[e]:null},VQ.prototype.has=function(e){return this.map.hasOwnProperty(RQ(e))},VQ.prototype.set=function(e,t){this.map[RQ(e)]=zQ(t)},VQ.prototype.forEach=function(e,t){for(var n in this.map)this.map.hasOwnProperty(n)&&e.call(t,this.map[n],n,this)},VQ.prototype.keys=function(){var e=[];return this.forEach(function(t,n){e.push(n)}),BQ(e)},VQ.prototype.values=function(){var e=[];return this.forEach(function(t){e.push(t)}),BQ(e)},VQ.prototype.entries=function(){var e=[];return this.forEach(function(t,n){e.push([n,t])}),BQ(e)},PQ.iterable&&(VQ.prototype[Symbol.iterator]=VQ.prototype.entries);function HQ(e){if(!e._noBody){if(e.bodyUsed)return Promise.reject(TypeError(`Already read`));e.bodyUsed=!0}}function UQ(e){return new Promise(function(t,n){e.onload=function(){t(e.result)},e.onerror=function(){n(e.error)}})}function WQ(e){var t=new FileReader,n=UQ(t);return t.readAsArrayBuffer(e),n}function GQ(e){var t=new FileReader,n=UQ(t),r=/charset=([A-Za-z0-9_-]+)/.exec(e.type),i=r?r[1]:`utf-8`;return t.readAsText(e,i),n}function KQ(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 qQ(e){if(e.slice)return e.slice(0);var t=new Uint8Array(e.byteLength);return t.set(new Uint8Array(e)),t.buffer}function JQ(){return this.bodyUsed=!1,this._initBody=function(e){this.bodyUsed=this.bodyUsed,this._bodyInit=e,e?typeof e==`string`?this._bodyText=e:PQ.blob&&Blob.prototype.isPrototypeOf(e)?this._bodyBlob=e:PQ.formData&&FormData.prototype.isPrototypeOf(e)?this._bodyFormData=e:PQ.searchParams&&URLSearchParams.prototype.isPrototypeOf(e)?this._bodyText=e.toString():PQ.arrayBuffer&&PQ.blob&&FQ(e)?(this._bodyArrayBuffer=qQ(e.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):PQ.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(e)||LQ(e))?this._bodyArrayBuffer=qQ(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):PQ.searchParams&&URLSearchParams.prototype.isPrototypeOf(e)&&this.headers.set(`content-type`,`application/x-www-form-urlencoded;charset=UTF-8`))},PQ.blob&&(this.blob=function(){var e=HQ(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 HQ(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(PQ.blob)return this.blob().then(WQ);throw Error(`could not read as ArrayBuffer`)},this.text=function(){var e=HQ(this);if(e)return e;if(this._bodyBlob)return GQ(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(KQ(this._bodyArrayBuffer));if(this._bodyFormData)throw Error(`could not read FormData body as text`);return Promise.resolve(this._bodyText)},PQ.formData&&(this.formData=function(){return this.text().then(QQ)}),this.json=function(){return this.text().then(JSON.parse)},this}var YQ=[`CONNECT`,`DELETE`,`GET`,`HEAD`,`OPTIONS`,`PATCH`,`POST`,`PUT`,`TRACE`];function XQ(e){var t=e.toUpperCase();return YQ.indexOf(t)>-1?t:e}function ZQ(e,t){if(!(this instanceof ZQ))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 ZQ){if(e.bodyUsed)throw TypeError(`Already read`);this.url=e.url,this.credentials=e.credentials,t.headers||(this.headers=new VQ(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 VQ(t.headers)),this.method=XQ(t.method||this.method||`GET`),this.mode=t.mode||this.mode||null,this.signal=t.signal||this.signal||function(){if(`AbortController`in NQ)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()}}}ZQ.prototype.clone=function(){return new ZQ(this,{body:this._bodyInit})};function QQ(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 $Q(e){var t=new VQ;return e.replace(/\r?\n[\t ]+/g,` `).split(`\r`).map(function(e){return e.indexOf(`
250
- `)===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}JQ.call(ZQ.prototype);function e$(e,t){if(!(this instanceof e$))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 VQ(t.headers),this.url=t.url||``,this._initBody(e)}JQ.call(e$.prototype),e$.prototype.clone=function(){return new e$(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new VQ(this.headers),url:this.url})},e$.error=function(){var e=new e$(null,{status:200,statusText:``});return e.ok=!1,e.status=0,e.type=`error`,e};var t$=[301,302,303,307,308];e$.redirect=function(e,t){if(t$.indexOf(t)===-1)throw RangeError(`Invalid status code`);return new e$(null,{status:t,headers:{location:e}})};var n$=NQ.DOMException;try{new n$}catch{n$=function(e,t){this.message=e,this.name=t;var n=Error(e);this.stack=n.stack},n$.prototype=Object.create(Error.prototype),n$.prototype.constructor=n$}function r$(e,t){return new Promise(function(n,r){var i=new ZQ(e,t);if(i.signal&&i.signal.aborted)return r(new n$(`Aborted`,`AbortError`));var a=new XMLHttpRequest;function o(){a.abort()}a.onload=function(){var e={statusText:a.statusText,headers:$Q(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 e$(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 n$(`Aborted`,`AbortError`))},0)};function s(e){try{return e===``&&NQ.location.href?NQ.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&&(PQ.blob?a.responseType=`blob`:PQ.arrayBuffer&&(a.responseType=`arraybuffer`)),t&&typeof t.headers==`object`&&!(t.headers instanceof VQ||NQ.Headers&&t.headers instanceof NQ.Headers)){var c=[];Object.getOwnPropertyNames(t.headers).forEach(function(e){c.push(RQ(e)),a.setRequestHeader(e,zQ(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)})}r$.polyfill=!0,NQ.fetch||(NQ.fetch=r$,NQ.Headers=VQ,NQ.Request=ZQ,NQ.Response=e$);var i$=`11434`,a$=`http://127.0.0.1:${i$}`,o$=`0.6.3`,s$=Object.defineProperty,c$=(e,t,n)=>t in e?s$(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,l$=(e,t,n)=>(c$(e,typeof t==`symbol`?t:t+``,n),n),u$=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)}},d$=class{constructor(e,t,n){l$(this,`abortController`),l$(this,`itr`),l$(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.`)}},f$=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 u$(t,e.status)};function p$(){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 m$(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 h$=(e,t)=>e[t],g$=async(e,t,n={})=>{let r={"Content-Type":`application/json`,Accept:`application/json`,"User-Agent":`ollama-js/${o$} (${p$()})`};n.headers=m$(n.headers);try{let e=new URL(t);if(e.protocol===`https:`&&e.hostname===`ollama.com`){let e=typeof process==`object`&&process!==null?h$({},`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)},_$=async(e,t,n)=>{let r=await g$(e,t,{headers:n?.headers});return await f$(r),r},v$=async(e,t,n,r)=>{let i=await g$(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 f$(i),i},y$=async(e,t,n,r)=>{let i=await g$(e,t,{method:`DELETE`,body:JSON.stringify(n),headers:r?.headers});return await f$(i),i},b$=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(`
250
+ `:``)+`{`+Object.entries(e).map(([e,t])=>`${e}: ${JSON.stringify(t)}`).join(`, `)+`}`}return t}var jQ={"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},MQ=4096;function NQ(e){return e?Object.entries(jQ).find(([t])=>e.startsWith(t))?.[1]??MQ:MQ}function PQ(e){return!!(e.tools&&e.tools.length>0)}function FQ(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 IQ(e){return!!(e.thinking&&(e.thinking.type===`enabled`||e.thinking.type===`adaptive`))}function LQ(e){return!!e.context_management?.edits?.some(e=>e.type===`compact_20260112`)}function RQ(e){return`input_schema`in e}function zQ(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 BQ(e,t,...n){return Array.from(new Set([...e??[],...t??[],...n.flatMap(e=>Array.from(e))]))}function VQ(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 HQ=class extends sE{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??mr(`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??NQ(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 EQ(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(jO(e)&&e.extras?.providerToolDefinition)return e.extras.providerToolDefinition;if(zQ(e)||RQ(e))return e;if(Kw(e))return{name:e.function.name,description:e.function.description,input_schema:e.function.parameters};if(jO(e))return{name:e.name,description:e.description,input_schema:Sg(e.schema)?Eb(e.schema):e.schema,...e.extras?jq.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=Aq(e?.tool_choice),n=e?.tools?.reduce((e,t)=>{if(typeof t==`object`&&`type`in t&&t.type in Mq){let n=Mq[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=aJ(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:BQ(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 oJ({model:this.model,thinking:this.thinking,topK:this.topK,topP:this.topP,temperature:this.temperature}),Object.assign(o,sJ({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=tJ(e),a={...r,...i,stream:!0},o=!PQ(a)&&!FQ(a)&&!IQ(a)&&!LQ(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=cJ(e,{streamUsage:r,coerceContentToString:o});if(!i)continue;let{chunk:a}=i,c=VQ(a),l=new Cu({message:new Zt({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=tJ(e),a={...r,...i,stream:!0},o=await this.createStreamWithRetry(a,{headers:t.headers,signal:t.signal}),s=this.streamUsage??t.streamUsage;yield*mJ(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=tJ(e),{content:i,...a}=await this.completionWithRetry({...t,stream:!1,...r},n),o=lJ(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 fJ(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 fJ(e)}})}_llmType(){return`anthropic`}get profile(){return pJ[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=kT(i);let e=kQ(Eb(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(Sg(i)||zy(i)){let n=Eb(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=AT(i,e,Oq),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:Eb(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:Eb(i)}})}else throw TypeError(`Unrecognized structured output method '${s}'. Expected 'functionCalling' or 'jsonSchema'`);return jT(n,r,o,o?`StructuredOutputRunnable`:`ChatAnthropicStructuredOutput`)}},UQ=class extends HQ{};Hk(`command`,[V({command:Qk(`view`),path:B()}),V({command:Qk(`create`),path:B(),file_text:B()}),V({command:Qk(`str_replace`),path:B(),old_str:B(),new_str:B()}),V({command:Qk(`insert`),path:B(),insert_line:Tk(),insert_text:B()}),V({command:Qk(`delete`),path:B()}),V({command:Qk(`rename`),old_path:B(),new_path:B()})]),Hk(`command`,[V({command:Qk(`view`),path:B(),view_range:Kk([Tk(),Tk()]).optional()}),V({command:Qk(`str_replace`),path:B(),old_str:B(),new_str:B()}),V({command:Qk(`create`),path:B(),file_text:B()}),V({command:Qk(`insert`),path:B(),insert_line:Tk(),new_str:B()})]);var WQ=Kk([Tk(),Tk()]),GQ=V({action:Qk(`screenshot`)}),KQ=V({action:Qk(`left_click`),coordinate:WQ}),qQ=V({action:Qk(`right_click`),coordinate:WQ}),JQ=V({action:Qk(`middle_click`),coordinate:WQ}),YQ=V({action:Qk(`double_click`),coordinate:WQ}),XQ=V({action:Qk(`triple_click`),coordinate:WQ}),ZQ=V({action:Qk(`left_click_drag`),start_coordinate:WQ,end_coordinate:WQ}),QQ=V({action:Qk(`left_mouse_down`),coordinate:WQ}),$Q=V({action:Qk(`left_mouse_up`),coordinate:WQ}),e$=V({action:Qk(`scroll`),coordinate:WQ,scroll_direction:Xk([`up`,`down`,`left`,`right`]),scroll_amount:Tk()}),t$=V({action:Qk(`type`),text:B()}),n$=V({action:Qk(`key`),key:B()}),r$=V({action:Qk(`mouse_move`),coordinate:WQ}),i$=V({action:Qk(`hold_key`),key:B()}),a$=V({action:Qk(`wait`),duration:Tk().optional()}),o$=V({action:Qk(`zoom`),region:Kk([Tk(),Tk(),Tk(),Tk()])});Hk(`action`,[GQ,KQ,qQ,JQ,YQ,XQ,ZQ,QQ,$Q,e$,t$,n$,r$,i$,a$]),Hk(`action`,[GQ,KQ,qQ,JQ,YQ,XQ,ZQ,QQ,$Q,e$,t$,n$,r$,i$,a$,o$]),Bk([V({command:B().describe(`The bash command to run`)}),V({restart:Qk(!0).describe(`Set to true to restart the bash session`)})]);for(var s$=[],c$=0;c$<256;++c$)s$.push((c$+256).toString(16).slice(1));function l$(e,t=0){return(s$[e[t+0]]+s$[e[t+1]]+s$[e[t+2]]+s$[e[t+3]]+`-`+s$[e[t+4]]+s$[e[t+5]]+`-`+s$[e[t+6]]+s$[e[t+7]]+`-`+s$[e[t+8]]+s$[e[t+9]]+`-`+s$[e[t+10]]+s$[e[t+11]]+s$[e[t+12]]+s$[e[t+13]]+s$[e[t+14]]+s$[e[t+15]]).toLowerCase()}var u$,d$=new Uint8Array(16);function f$(){if(!u$&&(u$=typeof crypto<`u`&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!u$))throw Error(`crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported`);return u$(d$)}var p$={randomUUID:typeof crypto<`u`&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function m$(e,t,n){if(p$.randomUUID&&!t&&!e)return p$.randomUUID();e||={};var r=e.random||(e.rng||f$)();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 l$(r)}function h$(e,t){return new Zt({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:m$()})),response_metadata:{...t?.responseMetadata,model_provider:`ollama`},usage_metadata:t?.usageMetadata})}function g$(e){let t=e.match(/^data:.*?;base64,(.*)$/);return t?t[1]:``}function _$(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 v$(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:[g$(e.image_url)]};if(e.image_url.url&&typeof e.image_url.url==`string`)return{role:`user`,content:``,images:[g$(e.image_url.url)]}}throw Error(`Unsupported content type: ${e.type}`)})}function y$(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 b$(e){if(typeof e.content!=`string`)throw Error(`Non string tool message content is not supported`);return[{role:`tool`,content:e.content}]}function x$(e){return e.flatMap(e=>{if([`human`,`generic`].includes(e._getType()))return v$(e);if(e._getType()===`ai`)return _$(e);if(e._getType()===`system`)return y$(e);if(e._getType()===`tool`)return b$(e);throw Error(`Unsupported message type: ${e._getType()}`)})}var S$=typeof globalThis<`u`&&globalThis||typeof self<`u`&&self||typeof global<`u`&&global||{},C$={searchParams:`URLSearchParams`in S$,iterable:`Symbol`in S$&&`iterator`in Symbol,blob:`FileReader`in S$&&`Blob`in S$&&(function(){try{return new Blob,!0}catch{return!1}})(),formData:`FormData`in S$,arrayBuffer:`ArrayBuffer`in S$};function w$(e){return e&&DataView.prototype.isPrototypeOf(e)}if(C$.arrayBuffer)var T$=[`[object Int8Array]`,`[object Uint8Array]`,`[object Uint8ClampedArray]`,`[object Int16Array]`,`[object Uint16Array]`,`[object Int32Array]`,`[object Uint32Array]`,`[object Float32Array]`,`[object Float64Array]`],E$=ArrayBuffer.isView||function(e){return e&&T$.indexOf(Object.prototype.toString.call(e))>-1};function D$(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 O$(e){return typeof e!=`string`&&(e=String(e)),e}function k$(e){var t={next:function(){var t=e.shift();return{done:t===void 0,value:t}}};return C$.iterable&&(t[Symbol.iterator]=function(){return t}),t}function A$(e){this.map={},e instanceof A$?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)}A$.prototype.append=function(e,t){e=D$(e),t=O$(t);var n=this.map[e];this.map[e]=n?n+`, `+t:t},A$.prototype.delete=function(e){delete this.map[D$(e)]},A$.prototype.get=function(e){return e=D$(e),this.has(e)?this.map[e]:null},A$.prototype.has=function(e){return this.map.hasOwnProperty(D$(e))},A$.prototype.set=function(e,t){this.map[D$(e)]=O$(t)},A$.prototype.forEach=function(e,t){for(var n in this.map)this.map.hasOwnProperty(n)&&e.call(t,this.map[n],n,this)},A$.prototype.keys=function(){var e=[];return this.forEach(function(t,n){e.push(n)}),k$(e)},A$.prototype.values=function(){var e=[];return this.forEach(function(t){e.push(t)}),k$(e)},A$.prototype.entries=function(){var e=[];return this.forEach(function(t,n){e.push([n,t])}),k$(e)},C$.iterable&&(A$.prototype[Symbol.iterator]=A$.prototype.entries);function j$(e){if(!e._noBody){if(e.bodyUsed)return Promise.reject(TypeError(`Already read`));e.bodyUsed=!0}}function M$(e){return new Promise(function(t,n){e.onload=function(){t(e.result)},e.onerror=function(){n(e.error)}})}function N$(e){var t=new FileReader,n=M$(t);return t.readAsArrayBuffer(e),n}function P$(e){var t=new FileReader,n=M$(t),r=/charset=([A-Za-z0-9_-]+)/.exec(e.type),i=r?r[1]:`utf-8`;return t.readAsText(e,i),n}function F$(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 I$(e){if(e.slice)return e.slice(0);var t=new Uint8Array(e.byteLength);return t.set(new Uint8Array(e)),t.buffer}function L$(){return this.bodyUsed=!1,this._initBody=function(e){this.bodyUsed=this.bodyUsed,this._bodyInit=e,e?typeof e==`string`?this._bodyText=e:C$.blob&&Blob.prototype.isPrototypeOf(e)?this._bodyBlob=e:C$.formData&&FormData.prototype.isPrototypeOf(e)?this._bodyFormData=e:C$.searchParams&&URLSearchParams.prototype.isPrototypeOf(e)?this._bodyText=e.toString():C$.arrayBuffer&&C$.blob&&w$(e)?(this._bodyArrayBuffer=I$(e.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):C$.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(e)||E$(e))?this._bodyArrayBuffer=I$(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):C$.searchParams&&URLSearchParams.prototype.isPrototypeOf(e)&&this.headers.set(`content-type`,`application/x-www-form-urlencoded;charset=UTF-8`))},C$.blob&&(this.blob=function(){var e=j$(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 j$(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(C$.blob)return this.blob().then(N$);throw Error(`could not read as ArrayBuffer`)},this.text=function(){var e=j$(this);if(e)return e;if(this._bodyBlob)return P$(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(F$(this._bodyArrayBuffer));if(this._bodyFormData)throw Error(`could not read FormData body as text`);return Promise.resolve(this._bodyText)},C$.formData&&(this.formData=function(){return this.text().then(V$)}),this.json=function(){return this.text().then(JSON.parse)},this}var R$=[`CONNECT`,`DELETE`,`GET`,`HEAD`,`OPTIONS`,`PATCH`,`POST`,`PUT`,`TRACE`];function z$(e){var t=e.toUpperCase();return R$.indexOf(t)>-1?t:e}function B$(e,t){if(!(this instanceof B$))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 B$){if(e.bodyUsed)throw TypeError(`Already read`);this.url=e.url,this.credentials=e.credentials,t.headers||(this.headers=new A$(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 A$(t.headers)),this.method=z$(t.method||this.method||`GET`),this.mode=t.mode||this.mode||null,this.signal=t.signal||this.signal||function(){if(`AbortController`in S$)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()}}}B$.prototype.clone=function(){return new B$(this,{body:this._bodyInit})};function V$(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 H$(e){var t=new A$;return e.replace(/\r?\n[\t ]+/g,` `).split(`\r`).map(function(e){return e.indexOf(`
251
+ `)===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}L$.call(B$.prototype);function U$(e,t){if(!(this instanceof U$))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 A$(t.headers),this.url=t.url||``,this._initBody(e)}L$.call(U$.prototype),U$.prototype.clone=function(){return new U$(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new A$(this.headers),url:this.url})},U$.error=function(){var e=new U$(null,{status:200,statusText:``});return e.ok=!1,e.status=0,e.type=`error`,e};var W$=[301,302,303,307,308];U$.redirect=function(e,t){if(W$.indexOf(t)===-1)throw RangeError(`Invalid status code`);return new U$(null,{status:t,headers:{location:e}})};var G$=S$.DOMException;try{new G$}catch{G$=function(e,t){this.message=e,this.name=t;var n=Error(e);this.stack=n.stack},G$.prototype=Object.create(Error.prototype),G$.prototype.constructor=G$}function K$(e,t){return new Promise(function(n,r){var i=new B$(e,t);if(i.signal&&i.signal.aborted)return r(new G$(`Aborted`,`AbortError`));var a=new XMLHttpRequest;function o(){a.abort()}a.onload=function(){var e={statusText:a.statusText,headers:H$(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 U$(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 G$(`Aborted`,`AbortError`))},0)};function s(e){try{return e===``&&S$.location.href?S$.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&&(C$.blob?a.responseType=`blob`:C$.arrayBuffer&&(a.responseType=`arraybuffer`)),t&&typeof t.headers==`object`&&!(t.headers instanceof A$||S$.Headers&&t.headers instanceof S$.Headers)){var c=[];Object.getOwnPropertyNames(t.headers).forEach(function(e){c.push(D$(e)),a.setRequestHeader(e,O$(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)})}K$.polyfill=!0,S$.fetch||(S$.fetch=K$,S$.Headers=A$,S$.Request=B$,S$.Response=U$);var q$=`11434`,J$=`http://127.0.0.1:${q$}`,Y$=`0.6.3`,X$=Object.defineProperty,Z$=(e,t,n)=>t in e?X$(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Q$=(e,t,n)=>(Z$(e,typeof t==`symbol`?t:t+``,n),n),$$=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)}},e1=class{constructor(e,t,n){Q$(this,`abortController`),Q$(this,`itr`),Q$(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.`)}},t1=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 $$(t,e.status)};function n1(){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 r1(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 i1=(e,t)=>e[t],a1=async(e,t,n={})=>{let r={"Content-Type":`application/json`,Accept:`application/json`,"User-Agent":`ollama-js/${Y$} (${n1()})`};n.headers=r1(n.headers);try{let e=new URL(t);if(e.protocol===`https:`&&e.hostname===`ollama.com`){let e=typeof process==`object`&&process!==null?i1({},`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)},o1=async(e,t,n)=>{let r=await a1(e,t,{headers:n?.headers});return await t1(r),r},s1=async(e,t,n,r)=>{let i=await a1(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 t1(i),i},c1=async(e,t,n,r)=>{let i=await a1(e,t,{method:`DELETE`,body:JSON.stringify(n),headers:r?.headers});return await t1(i),i},l1=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(`
251
252
  `);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(`
252
- `).filter(e=>e!==``))try{yield JSON.parse(e)}catch{console.warn(`invalid json: `,e)}},x$=e=>{if(!e)return a$;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`:i$;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},S$=Object.defineProperty,C$=(e,t,n)=>t in e?S$(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,w$=(e,t,n)=>(C$(e,typeof t==`symbol`?t:t+``,n),n),T$=class{constructor(e){w$(this,`config`),w$(this,`fetch`),w$(this,`ongoingStreamedRequests`,[]),this.config={host:``,headers:e?.headers},e?.proxy||(this.config.host=x$(e?.host??a$)),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 v$(this.fetch,n,t,{signal:e.signal,headers:this.config.headers});if(!r.body)throw Error(`Missing body`);let i=new d$(e,b$(r.body),()=>{let e=this.ongoingStreamedRequests.indexOf(i);e>-1&&this.ongoingStreamedRequests.splice(e,1)});return this.ongoingStreamedRequests.push(i),i}return await(await v$(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 y$(this.fetch,`${this.config.host}/api/delete`,{name:e.model},{headers:this.config.headers}),{status:`success`}}async copy(e){return await v$(this.fetch,`${this.config.host}/api/copy`,{...e},{headers:this.config.headers}),{status:`success`}}async list(){return await(await _$(this.fetch,`${this.config.host}/api/tags`,{headers:this.config.headers})).json()}async show(e){return await(await v$(this.fetch,`${this.config.host}/api/show`,{...e},{headers:this.config.headers})).json()}async embed(e){return await(await v$(this.fetch,`${this.config.host}/api/embed`,{...e},{headers:this.config.headers})).json()}async embeddings(e){return await(await v$(this.fetch,`${this.config.host}/api/embeddings`,{...e},{headers:this.config.headers})).json()}async ps(){return await(await _$(this.fetch,`${this.config.host}/api/ps`,{headers:this.config.headers})).json()}async version(){return await(await _$(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 v$(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 v$(this.fetch,`https://ollama.com/api/web_fetch`,{...e},{headers:this.config.headers})).json()}};new T$;var E$=class extends cE{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??mr(`OLLAMA_BASE_URL`)??this.baseUrl,this.client=new T$({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=>ej(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=>ej(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?zl(r,i.message):i.message;let i=new Jt({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=MQ(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 Cu({text:o,message:EQ(r)});yield c,await n?.handleLLMNewToken(o,void 0,void 0,void 0,void 0,{chunk:c})}yield new Cu({text:``,message:new Zt({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=Db(i);Sg(i)||By(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:Sg(i)||By(i)?o:i}}),r=jT(i,e)}else if(s===`jsonMode`||s===`jsonSchema`){r=AT(i);let e=Db(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 MT(n,r,o,o?`StructuredOutputRunnable`:`ChatOllamaStructuredOutput`)}},D$=e=>n.includes(e),O$=e=>r.includes(e),k$=e=>{let{executeQuery:t,search:n,grep:i,readFile:a}=e;return[AA(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(`
253
+ `).filter(e=>e!==``))try{yield JSON.parse(e)}catch{console.warn(`invalid json: `,e)}},u1=e=>{if(!e)return J$;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`:q$;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},d1=Object.defineProperty,f1=(e,t,n)=>t in e?d1(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,p1=(e,t,n)=>(f1(e,typeof t==`symbol`?t:t+``,n),n),m1=class{constructor(e){p1(this,`config`),p1(this,`fetch`),p1(this,`ongoingStreamedRequests`,[]),this.config={host:``,headers:e?.headers},e?.proxy||(this.config.host=u1(e?.host??J$)),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 s1(this.fetch,n,t,{signal:e.signal,headers:this.config.headers});if(!r.body)throw Error(`Missing body`);let i=new e1(e,l1(r.body),()=>{let e=this.ongoingStreamedRequests.indexOf(i);e>-1&&this.ongoingStreamedRequests.splice(e,1)});return this.ongoingStreamedRequests.push(i),i}return await(await s1(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 c1(this.fetch,`${this.config.host}/api/delete`,{name:e.model},{headers:this.config.headers}),{status:`success`}}async copy(e){return await s1(this.fetch,`${this.config.host}/api/copy`,{...e},{headers:this.config.headers}),{status:`success`}}async list(){return await(await o1(this.fetch,`${this.config.host}/api/tags`,{headers:this.config.headers})).json()}async show(e){return await(await s1(this.fetch,`${this.config.host}/api/show`,{...e},{headers:this.config.headers})).json()}async embed(e){return await(await s1(this.fetch,`${this.config.host}/api/embed`,{...e},{headers:this.config.headers})).json()}async embeddings(e){return await(await s1(this.fetch,`${this.config.host}/api/embeddings`,{...e},{headers:this.config.headers})).json()}async ps(){return await(await o1(this.fetch,`${this.config.host}/api/ps`,{headers:this.config.headers})).json()}async version(){return await(await o1(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 s1(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 s1(this.fetch,`https://ollama.com/api/web_fetch`,{...e},{headers:this.config.headers})).json()}};new m1;var h1=class extends sE{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??mr(`OLLAMA_BASE_URL`)??this.baseUrl,this.client=new m1({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=>$A(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=>$A(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?zl(r,i.message):i.message;let i=new Jt({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=x$(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 Cu({text:o,message:h$(r)});yield c,await n?.handleLLMNewToken(o,void 0,void 0,void 0,void 0,{chunk:c})}yield new Cu({text:``,message:new Zt({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=Eb(i);Sg(i)||zy(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:Sg(i)||zy(i)?o:i}}),r=AT(i,e)}else if(s===`jsonMode`||s===`jsonSchema`){r=kT(i);let e=Eb(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 jT(n,r,o,o?`StructuredOutputRunnable`:`ChatOllamaStructuredOutput`)}},g1=e=>n.includes(e),_1=e=>r.includes(e),v1=e=>{let{executeQuery:t,search:n,grep:i,readFile:a}=e;return[kA(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(`
253
254
 
254
255
  `)}`;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(`
255
- `).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:B({query:z().describe(`What you are looking for (e.g., "authentication middleware", "database connection")`),groupByProcess:Ak().optional().nullable().describe(`Group results by process (default: true)`),limit:Ek().optional().nullable().describe(`Max results to return (default: 10)`)})}),AA(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(`
256
+ `).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:V({query:B().describe(`What you are looking for (e.g., "authentication middleware", "database connection")`),groupByProcess:kk().optional().nullable().describe(`Group results by process (default: true)`),limit:Tk().optional().nullable().describe(`Max results to return (default: 10)`)})}),kA(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(`
256
257
  `);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(`
257
258
  `),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(`
258
259
  `)}${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.
@@ -271,10 +272,10 @@ Example queries:
271
272
  For semantic+graph queries, include {{QUERY_VECTOR}} placeholder and provide a 'query' parameter:
272
273
  CALL QUERY_VECTOR_INDEX('CodeEmbedding', 'code_embedding_idx', {{QUERY_VECTOR}}, 10) YIELD node AS emb, distance
273
274
  WITH emb, distance WHERE distance < 0.5
274
- MATCH (n:Function {id: emb.nodeId}) RETURN n`,schema:B({cypher:z().describe(`The Cypher query to execute`),query:z().optional().nullable().describe(`Natural language query to embed (required if cypher contains {{QUERY_VECTOR}})`)})}),AA(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(`
275
- `),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:B({pattern:z().describe(`Regex pattern to search for (e.g., "TODO", "console\\.log", "API_KEY")`),fileFilter:z().optional().nullable().describe(`Only search files containing this string (e.g., ".ts", "src/api")`),caseSensitive:Ak().optional().nullable().describe(`Case-sensitive search (default: false)`),maxResults:Ek().optional().nullable().describe(`Max results (default: 100)`)})}),AA(async({filePath:e})=>{try{let t=await a(e),n=5e4;return t.length>n?`File: ${e} (${t.split(`
275
+ MATCH (n:Function {id: emb.nodeId}) RETURN n`,schema:V({cypher:B().describe(`The Cypher query to execute`),query:B().optional().nullable().describe(`Natural language query to embed (required if cypher contains {{QUERY_VECTOR}})`)})}),kA(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(`
276
+ `),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:V({pattern:B().describe(`Regex pattern to search for (e.g., "TODO", "console\\.log", "API_KEY")`),fileFilter:B().optional().nullable().describe(`Only search files containing this string (e.g., ".ts", "src/api")`),caseSensitive:kk().optional().nullable().describe(`Case-sensitive search (default: false)`),maxResults:Tk().optional().nullable().describe(`Max results (default: 100)`)})}),kA(async({filePath:e})=>{try{let t=await a(e),n=5e4;return t.length>n?`File: ${e} (${t.split(`
276
277
  `).length} lines, truncated)\n\n${t.slice(0,n)}\n\n... [truncated]`:`File: ${e} (${t.split(`
277
- `).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:B({filePath:z().describe(`File path to read (can be partial like "src/utils.ts")`)})}),AA(async()=>{try{let[e,n,r,i]=await Promise.all([t(`
278
+ `).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:V({filePath:B().describe(`File path to read (can be partial like "src/utils.ts")`)})}),kA(async()=>{try{let[e,n,r,i]=await Promise.all([t(`
278
279
  MATCH (c:Community)
279
280
  RETURN c.id AS id, c.label AS label, c.cohesion AS cohesion, c.symbolCount AS symbolCount, c.description AS description
280
281
  ORDER BY c.symbolCount DESC
@@ -298,7 +299,7 @@ MATCH (n:Function {id: emb.nodeId}) RETURN n`,schema:B({cypher:z().describe(`The
298
299
  ORDER BY steps DESC
299
300
  LIMIT 10
300
301
  `)]),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(`
301
- `)}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:B({})}),AA(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(`
302
+ `)}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:V({})}),kA(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(`
302
303
  MATCH (p:Process)
303
304
  WHERE p.id = '${r}' OR p.label = '${r}'
304
305
  RETURN p.id AS id, p.label AS label, p.processType AS type, p.stepCount AS stepCount
@@ -335,7 +336,7 @@ MATCH (n:Function {id: emb.nodeId}) RETURN n`,schema:B({cypher:z().describe(`The
335
336
  ORDER BY p.stepCount DESC
336
337
  LIMIT 20
337
338
  `,[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(`
338
- `)}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(!D$(a))return`Unknown node type "${a}" for symbol "${e}".`;let o=`
339
+ `)}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(!g1(a))return`Unknown node type "${a}" for symbol "${e}".`;let o=`
339
340
  MATCH (n:${a} {id: '${String(n).replace(/'/g,`''`)}'})
340
341
  MATCH (n)-[:CodeRelation {type: 'MEMBER_OF'}]->(c:Community)
341
342
  RETURN c.label AS label, c.description AS description
@@ -354,7 +355,7 @@ MATCH (n:Function {id: emb.nodeId}) RETURN n`,schema:B({cypher:z().describe(`The
354
355
  collect(DISTINCT {name: src.name, type: r2.type, confidence: r2.confidence}) AS incoming
355
356
  LIMIT 1
356
357
  `,[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(`
357
- `)}return`Unable to explore "${e}".`},{name:`explore`,description:`Deep dive on a symbol, cluster, or process. Shows membership, participation, and connections.`,schema:B({target:z().describe(`Name or ID of a symbol, cluster, or process`),type:Zk([`symbol`,`cluster`,`process`]).optional().nullable().describe(`Optional target type (auto-detected if omitted)`)})}),AA(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=>O$(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?`
358
+ `)}return`Unable to explore "${e}".`},{name:`explore`,description:`Deep dive on a symbol, cluster, or process. Shows membership, participation, and connections.`,schema:V({target:B().describe(`Name or ID of a symbol, cluster, or process`),type:Xk([`symbol`,`cluster`,`process`]).optional().nullable().describe(`Optional target type (auto-detected if omitted)`)})}),kA(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=>_1(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?`
358
359
  MATCH (n)
359
360
  WHERE n.filePath IS NOT NULL AND n.filePath CONTAINS '${_}'
360
361
  RETURN n.id AS id, label(n) AS nodeType, n.filePath AS filePath
@@ -555,7 +556,7 @@ relationTypes filter (optional):
555
556
  Additional output sections:
556
557
  - Affected processes (with step impact)
557
558
  - Affected clusters (direct/indirect)
558
- - Risk summary (based on direct callers, processes, clusters)`,schema:B({target:z().describe(`Name of the function, class, or file to analyze`),direction:Zk([`upstream`,`downstream`]).describe(`upstream = what depends on this; downstream = what this depends on`),maxDepth:Ek().optional().nullable().describe(`Max traversal depth (default: 3, max: 10)`),relationTypes:Rk(z()).optional().nullable().describe(`Filter by relation types: CALLS, IMPORTS, EXTENDS, IMPLEMENTS, CONTAINS, DEFINES (default: usage-based)`),includeTests:Ak().optional().nullable().describe(`Include test files in results (default: false, excludes .test.ts, .spec.ts, __tests__)`),minConfidence:Ek().optional().nullable().describe(`Minimum edge confidence 0-1 (default: 0.7, excludes fuzzy/inferred matches)`)})})]},A$=class extends PW{activeMessages=null;setActiveMessages(e){if(this.activeMessages!==null)throw Error(`DeepSeekChatOpenAICompletions does not support overlapping requests`);this.activeMessages=e}async _generate(e,t,n){this.setActiveMessages(e);try{return await super._generate(e,t,n)}finally{this.activeMessages=null}}async*_streamResponseChunks(e,t,n){this.setActiveMessages(e);try{yield*super._streamResponseChunks(e,t,n)}finally{this.activeMessages=null}}async completionWithRetry(e,t){let n=this.activeMessages?R$(this.activeMessages):e.messages;return super.completionWithRetry({...e,messages:n},t)}},j$=class e extends eG{deepSeekFields;constructor(e){let t={...e,completions:new A$(e)};super(t),this.deepSeekFields=t}withConfig(t){let n=new e(this.deepSeekFields);return n.defaultOptions={...this.defaultOptions,...t},n}},M$=e=>typeof e==`string`?e:Array.isArray(e)?e.filter(e=>e?.type===`text`||typeof e==`string`).map(e=>typeof e==`string`?e:e.text||``).join(``):e==null?``:String(e),N$=e=>{if(e?.args&&typeof e.args==`object`)return e.args;try{return e?.function?.arguments?JSON.parse(e.function.arguments):{}}catch{return{}}},P$=e=>{if(!(!Array.isArray(e)||e.length===0))return e.map(e=>({id:typeof e?.id==`string`?e.id:void 0,name:e?.name||e?.function?.name||`unknown`,args:N$(e),type:typeof e?.type==`string`?e.type:`tool_call`}))},F$=e=>{if(typeof e==`string`)return e;try{return JSON.stringify(e??{})}catch{return`{}`}},I$=e=>{if(typeof e==`string`)return e;if(!Array.isArray(e))return M$(e);let t=e.flatMap(e=>typeof e==`string`?[{type:`text`,text:e}]:e?.type===`text`&&typeof e.text==`string`?[{type:`text`,text:e.text}]:[]);return t.length===0?``:t.length===1?t[0].text:t},L$=e=>{let t=e?._getType?.()||e?.type||e?.constructor?.name||`unknown`;if((e.additional_kwargs||{}).__openai_role__===`developer`)return`developer`;switch(t){case`human`:case`HumanMessage`:return`user`;case`ai`:case`AIMessage`:return`assistant`;case`system`:case`SystemMessage`:return`system`;case`tool`:case`ToolMessage`:return`tool`;case`function`:case`FunctionMessage`:return`function`;default:return typeof e.role==`string`?e.role:`user`}},R$=e=>e.map(e=>{let t=L$(e),n=e.additional_kwargs&&typeof e.additional_kwargs==`object`?e.additional_kwargs:{},r={role:t,content:I$(e.content)};if(typeof e.name==`string`&&e.name.length>0&&(r.name=e.name),t===`assistant`){let t=Array.isArray(e.tool_calls)?e.tool_calls:Array.isArray(n.tool_calls)?n.tool_calls:void 0;return t?.length&&(r.tool_calls=t.map(e=>e?.function?{id:e.id,type:e.type??`function`,function:{name:e.function.name,arguments:F$(e.function.arguments)}}:{id:e?.id,type:`function`,function:{name:e?.name??`unknown`,arguments:F$(e?.args)}})),n.function_call!=null&&(r.function_call=n.function_call),t?.length&&typeof n.reasoning_content==`string`&&(r.reasoning_content=n.reasoning_content),r}return t===`tool`&&typeof e.tool_call_id==`string`&&(r.tool_call_id=e.tool_call_id),t===`function`&&typeof e.name==`string`&&(r.name=e.name),r}),z$=`You are Nexus, a Code Analysis Agent with access to a Knowledge Graph. Your responses MUST be grounded.
559
+ - Risk summary (based on direct callers, processes, clusters)`,schema:V({target:B().describe(`Name of the function, class, or file to analyze`),direction:Xk([`upstream`,`downstream`]).describe(`upstream = what depends on this; downstream = what this depends on`),maxDepth:Tk().optional().nullable().describe(`Max traversal depth (default: 3, max: 10)`),relationTypes:Lk(B()).optional().nullable().describe(`Filter by relation types: CALLS, IMPORTS, EXTENDS, IMPLEMENTS, CONTAINS, DEFINES (default: usage-based)`),includeTests:kk().optional().nullable().describe(`Include test files in results (default: false, excludes .test.ts, .spec.ts, __tests__)`),minConfidence:Tk().optional().nullable().describe(`Minimum edge confidence 0-1 (default: 0.7, excludes fuzzy/inferred matches)`)})})]},y1=class extends CG{activeMessages=null;setActiveMessages(e){if(this.activeMessages!==null)throw Error(`DeepSeekChatOpenAICompletions does not support overlapping requests`);this.activeMessages=e}async _generate(e,t,n){this.setActiveMessages(e);try{return await super._generate(e,t,n)}finally{this.activeMessages=null}}async*_streamResponseChunks(e,t,n){this.setActiveMessages(e);try{yield*super._streamResponseChunks(e,t,n)}finally{this.activeMessages=null}}async completionWithRetry(e,t){let n=this.activeMessages?D1(this.activeMessages):e.messages;return super.completionWithRetry({...e,messages:n},t)}},b1=class e extends UG{deepSeekFields;constructor(e){let t={...e,completions:new y1(e)};super(t),this.deepSeekFields=t}withConfig(t){let n=new e(this.deepSeekFields);return n.defaultOptions={...this.defaultOptions,...t},n}},x1=e=>typeof e==`string`?e:Array.isArray(e)?e.filter(e=>e?.type===`text`||typeof e==`string`).map(e=>typeof e==`string`?e:e.text||``).join(``):e==null?``:String(e),S1=e=>{if(e?.args&&typeof e.args==`object`)return e.args;try{return e?.function?.arguments?JSON.parse(e.function.arguments):{}}catch{return{}}},C1=e=>{if(!(!Array.isArray(e)||e.length===0))return e.map(e=>({id:typeof e?.id==`string`?e.id:void 0,name:e?.name||e?.function?.name||`unknown`,args:S1(e),type:typeof e?.type==`string`?e.type:`tool_call`}))},w1=e=>{if(typeof e==`string`)return e;try{return JSON.stringify(e??{})}catch{return`{}`}},T1=e=>{if(typeof e==`string`)return e;if(!Array.isArray(e))return x1(e);let t=e.flatMap(e=>typeof e==`string`?[{type:`text`,text:e}]:e?.type===`text`&&typeof e.text==`string`?[{type:`text`,text:e.text}]:[]);return t.length===0?``:t.length===1?t[0].text:t},E1=e=>{let t=e?._getType?.()||e?.type||e?.constructor?.name||`unknown`;if((e.additional_kwargs||{}).__openai_role__===`developer`)return`developer`;switch(t){case`human`:case`HumanMessage`:return`user`;case`ai`:case`AIMessage`:return`assistant`;case`system`:case`SystemMessage`:return`system`;case`tool`:case`ToolMessage`:return`tool`;case`function`:case`FunctionMessage`:return`function`;default:return typeof e.role==`string`?e.role:`user`}},D1=e=>e.map(e=>{let t=E1(e),n=e.additional_kwargs&&typeof e.additional_kwargs==`object`?e.additional_kwargs:{},r={role:t,content:T1(e.content)};if(typeof e.name==`string`&&e.name.length>0&&(r.name=e.name),t===`assistant`){let t=Array.isArray(e.tool_calls)?e.tool_calls:Array.isArray(n.tool_calls)?n.tool_calls:void 0;return t?.length&&(r.tool_calls=t.map(e=>e?.function?{id:e.id,type:e.type??`function`,function:{name:e.function.name,arguments:w1(e.function.arguments)}}:{id:e?.id,type:`function`,function:{name:e?.name??`unknown`,arguments:w1(e?.args)}})),n.function_call!=null&&(r.function_call=n.function_call),t?.length&&typeof n.reasoning_content==`string`&&(r.reasoning_content=n.reasoning_content),r}return t===`tool`&&typeof e.tool_call_id==`string`&&(r.tool_call_id=e.tool_call_id),t===`function`&&typeof e.name==`string`&&(r.name=e.name),r}),O1=`You are Nexus, a Code Analysis Agent with access to a Knowledge Graph. Your responses MUST be grounded.
559
560
 
560
561
  ## ⚠️ MANDATORY: GROUNDING
561
562
  Every factual claim MUST include a citation.
@@ -630,4 +631,4 @@ When generating diagrams:
630
631
 
631
632
  BAD: A[User's Data] --> B(Process & Save)
632
633
  GOOD: A["User Data"] --> B["Process and Save"]
633
- `,B$=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 eG({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 tG({azureOpenAIApiKey:t.apiKey,azureOpenAIApiInstanceName:V$(t.endpoint),azureOpenAIApiDeploymentName:t.deploymentName,azureOpenAIApiVersion:t.apiVersion??`2024-12-01-preview`,streaming:!0})}case`gemini`:{let t=e;return new RK({apiKey:t.apiKey,model:t.model,temperature:t.temperature??.1,maxOutputTokens:t.maxTokens,streaming:!0})}case`anthropic`:{let t=e;return new eQ({anthropicApiKey:t.apiKey,model:t.model,temperature:t.temperature??.1,maxTokens:t.maxTokens??8192,streaming:!0})}case`ollama`:{let t=e;return new E$({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 eG({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 eQ({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 eG({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})}case`deepseek`:{let t=e;if(!t.apiKey||t.apiKey.trim()===``)throw Error(`DeepSeek API key is required but was not provided`);return new j$({apiKey:t.apiKey,modelName:t.model,temperature:t.temperature??.1,maxTokens:t.maxTokens,configuration:{apiKey:t.apiKey,baseURL:`https://api.deepseek.com`},streaming:!0})}default:throw Error(`Unsupported provider: ${e.provider}`)}},V$=e=>{try{let t=new URL(e).hostname,n=t.match(/^([^.]+)\.openai\.azure\.com$/);return n?n[1]:t.split(`.`)[0]}catch{return e}},H$=(e,t,n)=>LI({llm:B$(e),tools:k$(t),messageModifier:new fn(n?i(z$,n):z$)}),U$=(e,t)=>!!(e instanceof DOMException&&e.name===`AbortError`||e instanceof Error&&e.name===`AbortError`||t?.aborted),W$=e=>e.map(e=>e.role===`user`?new sn(e.content):e.role===`tool`?new vt({content:e.content,tool_call_id:e.toolCallId,...e.name?{name:e.name}:{}}):new Jt({content:e.content,...typeof e.reasoningContent==`string`?{additional_kwargs:{reasoning_content:e.reasoningContent}}:{},...e.toolCalls?.length?{tool_calls:e.toolCalls}:{}})),G$=(e,t=0)=>{let n=[];for(let r of e.slice(t)){let e=r,t=e?._getType?.()||e?.type||e?.constructor?.name||`unknown`;if(t===`ai`||t===`AIMessage`){let t=(e.additional_kwargs||e.kwargs)?.reasoning_content,r=P$(e.tool_calls);n.push({role:`assistant`,content:M$(e.content),...r?.length&&typeof t==`string`?{reasoningContent:t}:{},...r?.length?{toolCalls:r}:{}});continue}(t===`tool`||t===`ToolMessage`)&&n.push({role:`tool`,content:M$(e.content),toolCallId:String(e.tool_call_id??``),...typeof e.name==`string`?{name:e.name}:{}})}return n};async function*K$(e,t,n={}){try{let r=W$(t),i=await e.stream({messages:r},{streamMode:[`values`,`messages`],recursionLimit:50,signal:n.signal}),a=new Set,o=new Set,s=r.length,c=0,l=!1,u=null;for await(let e of i){if(n.signal?.aborted)break;let t,r;if(Array.isArray(e)&&e.length===2&&typeof e[0]==`string`?[t,r]=e:Array.isArray(e)&&e[0]?._getType?(t=`messages`,r=e):(t=`values`,r=e),t===`messages`){let[e]=Array.isArray(r)?r:[r];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&&(!l||n.length>0||c>0?yield{type:`reasoning`,reasoning:r}:yield{type:`content`,content:r}),n.length>0){l=!0,c+=n.length;for(let e of n){let t=e.id||`tool-${Date.now()}-${Math.random().toString(36).slice(2)}`;if(!a.has(t)){a.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&&!o.has(t)){o.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`}},c=Math.max(0,c-1)}}}if(t===`values`&&r?.messages){let e=r.messages||[];n.captureHistory&&(u=e);for(let t=s;t<e.length;t++){let n=e[t],r=n._getType?.()||n.type||`unknown`;if((r===`ai`||r===`AIMessage`)&&!a.size){let e=n.tool_calls||[];for(let t of e){let e=t.id||`tool-${Date.now()}`;a.has(e)||(c++,a.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&&!o.has(e)){o.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`}},c=Math.max(0,c-1)}}}s=e.length}}if(n.signal?.aborted){yield{type:`cancelled`};return}yield{type:`done`,historyMessages:n.captureHistory&&u?G$(u,r.length):void 0}}catch(e){if(U$(e,n.signal)){yield{type:`cancelled`};return}yield{type:`error`,error:e instanceof Error?e.message:String(e)}}}export{H$ as createGraphRAGAgent,K$ as streamAgentResponse};
634
+ `,k1=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 UG({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 WG({azureOpenAIApiKey:t.apiKey,azureOpenAIApiInstanceName:A1(t.endpoint),azureOpenAIApiDeploymentName:t.deploymentName,azureOpenAIApiVersion:t.apiVersion??`2024-12-01-preview`,streaming:!0})}case`gemini`:{let t=e;return new Dq({apiKey:t.apiKey,model:t.model,temperature:t.temperature??.1,maxOutputTokens:t.maxTokens,streaming:!0})}case`anthropic`:{let t=e;return new UQ({anthropicApiKey:t.apiKey,model:t.model,temperature:t.temperature??.1,maxTokens:t.maxTokens??8192,streaming:!0})}case`ollama`:{let t=e;return new h1({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 UG({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 UQ({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 UG({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})}case`deepseek`:{let t=e;if(!t.apiKey||t.apiKey.trim()===``)throw Error(`DeepSeek API key is required but was not provided`);return new b1({apiKey:t.apiKey,modelName:t.model,temperature:t.temperature??.1,maxTokens:t.maxTokens,configuration:{apiKey:t.apiKey,baseURL:`https://api.deepseek.com`},streaming:!0})}default:throw Error(`Unsupported provider: ${e.provider}`)}},A1=e=>{try{let t=new URL(e).hostname,n=t.match(/^([^.]+)\.openai\.azure\.com$/);return n?n[1]:t.split(`.`)[0]}catch{return e}},j1=(e,t,n)=>TL({llm:k1(e),tools:v1(t),messageModifier:new fn(n?i(O1,n):O1)}),M1=(e,t)=>!!(e instanceof DOMException&&e.name===`AbortError`||e instanceof Error&&e.name===`AbortError`||t?.aborted),N1=e=>e.map(e=>e.role===`user`?new sn(e.content):e.role===`tool`?new vt({content:e.content,tool_call_id:e.toolCallId,...e.name?{name:e.name}:{}}):new Jt({content:e.content,...typeof e.reasoningContent==`string`?{additional_kwargs:{reasoning_content:e.reasoningContent}}:{},...e.toolCalls?.length?{tool_calls:e.toolCalls}:{}})),P1=(e,t=0)=>{let n=[];for(let r of e.slice(t)){let e=r,t=e?._getType?.()||e?.type||e?.constructor?.name||`unknown`;if(t===`ai`||t===`AIMessage`){let t=(e.additional_kwargs||e.kwargs)?.reasoning_content,r=C1(e.tool_calls);n.push({role:`assistant`,content:x1(e.content),...r?.length&&typeof t==`string`?{reasoningContent:t}:{},...r?.length?{toolCalls:r}:{}});continue}(t===`tool`||t===`ToolMessage`)&&n.push({role:`tool`,content:x1(e.content),toolCallId:String(e.tool_call_id??``),...typeof e.name==`string`?{name:e.name}:{}})}return n};async function*F1(e,t,n={}){try{let r=N1(t),i=await e.stream({messages:r},{streamMode:[`values`,`messages`],recursionLimit:50,signal:n.signal}),a=new Set,o=new Set,s=r.length,c=0,l=!1,u=null;for await(let e of i){if(n.signal?.aborted)break;let t,r;if(Array.isArray(e)&&e.length===2&&typeof e[0]==`string`?[t,r]=e:Array.isArray(e)&&e[0]?._getType?(t=`messages`,r=e):(t=`values`,r=e),t===`messages`){let[e]=Array.isArray(r)?r:[r];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&&(!l||n.length>0||c>0?yield{type:`reasoning`,reasoning:r}:yield{type:`content`,content:r}),n.length>0){l=!0,c+=n.length;for(let e of n){let t=e.id||`tool-${Date.now()}-${Math.random().toString(36).slice(2)}`;if(!a.has(t)){a.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&&!o.has(t)){o.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`}},c=Math.max(0,c-1)}}}if(t===`values`&&r?.messages){let e=r.messages||[];n.captureHistory&&(u=e);for(let t=s;t<e.length;t++){let n=e[t],r=n._getType?.()||n.type||`unknown`;if((r===`ai`||r===`AIMessage`)&&!a.size){let e=n.tool_calls||[];for(let t of e){let e=t.id||`tool-${Date.now()}`;a.has(e)||(c++,a.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&&!o.has(e)){o.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`}},c=Math.max(0,c-1)}}}s=e.length}}if(n.signal?.aborted){yield{type:`cancelled`};return}yield{type:`done`,historyMessages:n.captureHistory&&u?P1(u,r.length):void 0}}catch(e){if(M1(e,n.signal)){yield{type:`cancelled`};return}yield{type:`error`,error:e instanceof Error?e.message:String(e)}}}export{j1 as createGraphRAGAgent,F1 as streamAgentResponse};