@codragraph/cli 2.1.6 → 2.2.0-rc.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +7 -7
- package/dist/cli/graphpack.d.ts +48 -0
- package/dist/cli/graphpack.js +217 -0
- package/dist/cli/index.js +72 -0
- package/dist/cli/tool.d.ts +1 -0
- package/dist/cli/tool.js +111 -2
- package/dist/core/graphpack/index.d.ts +14 -0
- package/dist/core/graphpack/index.js +474 -0
- package/dist/core/graphpack/types.d.ts +129 -0
- package/dist/core/graphpack/types.js +4 -0
- package/dist/core/semantic/relationships.d.ts +36 -0
- package/dist/core/semantic/relationships.js +261 -0
- package/dist/mcp/local/local-backend.js +42 -0
- package/dist/mcp/resources.js +125 -0
- package/dist/mcp/tools.js +105 -0
- package/dist/server/api.js +112 -0
- package/dist/web/assets/agent-CQNZQ-hg.js +1139 -0
- package/dist/web/assets/{architectureDiagram-UL44E2DR-DFSpa3Hb.js → architectureDiagram-UL44E2DR-B5_goS_i.js} +1 -1
- package/dist/web/assets/{blockDiagram-7IZFK4PR-DlFaxH1b.js → blockDiagram-7IZFK4PR-D7ZAlDyv.js} +1 -1
- package/dist/web/assets/{c4Diagram-Y2BXMSZH-BjJ_Yrim.js → c4Diagram-Y2BXMSZH-Djcgm_54.js} +1 -1
- package/dist/web/assets/{chunk-3SSMPTDK-KGZSzG3Y.js → chunk-3SSMPTDK-Cv2Zy2FO.js} +1 -1
- package/dist/web/assets/{chunk-6764PJDD-p1sGJgVm.js → chunk-6764PJDD-Cppb-jH-.js} +1 -1
- package/dist/web/assets/{chunk-AZZRMDJM-DIDkQA4V.js → chunk-AZZRMDJM-BHlLC7p3.js} +1 -1
- package/dist/web/assets/{chunk-JQRUD6KW-DAwg-yCU.js → chunk-JQRUD6KW-3F8Zg-1N.js} +1 -1
- package/dist/web/assets/{chunk-KRXBNO2N-ChVO_XdS.js → chunk-KRXBNO2N-C0mbN9a7.js} +1 -1
- package/dist/web/assets/{chunk-LCXTWHL2-DGYdb_Eh.js → chunk-LCXTWHL2-BoiuJpIF.js} +1 -1
- package/dist/web/assets/{chunk-LII3EMHJ-Bzh9SNgD.js → chunk-LII3EMHJ-Dqq0Qguw.js} +1 -1
- package/dist/web/assets/{chunk-RG4AUYOV-Bcl7U_IV.js → chunk-RG4AUYOV-Bl5F_gDs.js} +1 -1
- package/dist/web/assets/{chunk-T5OCTHI4-CZYMg5sc.js → chunk-T5OCTHI4-B2tIcggA.js} +1 -1
- package/dist/web/assets/{chunk-W44A43WB-REOI67PN.js → chunk-W44A43WB-BHe37iN7.js} +1 -1
- package/dist/web/assets/{chunk-ZXARS5L4-BfFdV1tf.js → chunk-ZXARS5L4-wcrIaQvY.js} +1 -1
- package/dist/web/assets/classDiagram-KGZ6W3CR-IbI6v_24.js +1 -0
- package/dist/web/assets/classDiagram-v2-72OJOZXJ-IbI6v_24.js +1 -0
- package/dist/web/assets/{cose-bilkent-UX7MHV2Q-D6vANJGG.js → cose-bilkent-UX7MHV2Q-BWr7v0Wr.js} +1 -1
- package/dist/web/assets/{dagre-ND4H6XIP-BiHe5Lal.js → dagre-ND4H6XIP-De5LIh1B.js} +1 -1
- package/dist/web/assets/{diagram-3NCE3AQN-CEutBCOW.js → diagram-3NCE3AQN-Dd22FSHy.js} +1 -1
- package/dist/web/assets/{diagram-GF46GFSD-CZns6HPQ.js → diagram-GF46GFSD-Cev3THY8.js} +1 -1
- package/dist/web/assets/{diagram-HNR7UZ2L-Vz8fE5of.js → diagram-HNR7UZ2L-D8Z8RQGs.js} +1 -1
- package/dist/web/assets/{diagram-QXG6HAR7-D60HKZ_y.js → diagram-QXG6HAR7-B8VOJOiE.js} +1 -1
- package/dist/web/assets/{diagram-WEQXMOUZ-vGAf1p3E.js → diagram-WEQXMOUZ-va1bLoMD.js} +1 -1
- package/dist/web/assets/{erDiagram-L5TCEMPS-DZaplJA6.js → erDiagram-L5TCEMPS-B3_9uAoP.js} +1 -1
- package/dist/web/assets/{flowDiagram-H6V6AXG4-BqUqeAsI.js → flowDiagram-H6V6AXG4-98m6maI1.js} +1 -1
- package/dist/web/assets/{ganttDiagram-JCBTUEKG-XEB6H-0G.js → ganttDiagram-JCBTUEKG-vE2nzETb.js} +1 -1
- package/dist/web/assets/{gitGraphDiagram-S2ZK5IYY-7G50u1Cd.js → gitGraphDiagram-S2ZK5IYY-DKc8uUg_.js} +1 -1
- package/dist/web/assets/index-BAhe1HSk.css +1 -0
- package/dist/web/assets/{index-B5WxtMpv.js → index-VTKdaklA.js} +230 -230
- package/dist/web/assets/{infoDiagram-3YFTVSEB-Cut_rzaf.js → infoDiagram-3YFTVSEB-DYP-Srzx.js} +1 -1
- package/dist/web/assets/{ishikawaDiagram-BNXS4ZKH-B4DGfGi3.js → ishikawaDiagram-BNXS4ZKH-QZnkpmmb.js} +1 -1
- package/dist/web/assets/{journeyDiagram-M6C3CM3L-BBFhsL3E.js → journeyDiagram-M6C3CM3L-B5ojIuqu.js} +1 -1
- package/dist/web/assets/{kanban-definition-75IXJCU3-DarGRyn3.js → kanban-definition-75IXJCU3-BJA8liRR.js} +1 -1
- package/dist/web/assets/{katex-K3KEBU37-W5XTYMhr.js → katex-K3KEBU37-DUqZiCRL.js} +1 -1
- package/dist/web/assets/{mindmap-definition-2TDM6QVE-BgeczIJM.js → mindmap-definition-2TDM6QVE-BQj5yylD.js} +1 -1
- package/dist/web/assets/{pieDiagram-CU6KROY3-Kkoo-Noq.js → pieDiagram-CU6KROY3-4eSrPiQz.js} +1 -1
- package/dist/web/assets/{quadrantDiagram-VICAPDV7-CDQFeRWN.js → quadrantDiagram-VICAPDV7-PzxN8j55.js} +1 -1
- package/dist/web/assets/{requirementDiagram-JXO7QTGE-Cz9-XnkA.js → requirementDiagram-JXO7QTGE-CtplTc5y.js} +1 -1
- package/dist/web/assets/{sankeyDiagram-URQDO5SZ-CU26z0n7.js → sankeyDiagram-URQDO5SZ-CoSgvkxv.js} +1 -1
- package/dist/web/assets/{sequenceDiagram-VS2MUI6T-OGK1FLOt.js → sequenceDiagram-VS2MUI6T-D7ygyXvJ.js} +1 -1
- package/dist/web/assets/{stateDiagram-7D4R322I-DJ9brq0U.js → stateDiagram-7D4R322I-v01gvwji.js} +1 -1
- package/dist/web/assets/stateDiagram-v2-36443NZ5-DFD2b8_x.js +1 -0
- package/dist/web/assets/{timeline-definition-O6YCAMPW-XZvnjqTT.js → timeline-definition-O6YCAMPW-CTI3M65J.js} +1 -1
- package/dist/web/assets/{vennDiagram-MWXL3ELB-CJUssEjA.js → vennDiagram-MWXL3ELB-RnB0XMP7.js} +1 -1
- package/dist/web/assets/{wardley-L42UT6IY-5TKZOOLJ-DZr11zBG.js → wardley-L42UT6IY-5TKZOOLJ-C-ZcgEBb.js} +1 -1
- package/dist/web/assets/{wardleyDiagram-CUQ6CDDI-C276iqrN.js → wardleyDiagram-CUQ6CDDI-EwRi4kwo.js} +1 -1
- package/dist/web/assets/{xychartDiagram-N2JHSOCM-B9-uCZyP.js → xychartDiagram-N2JHSOCM-DA38II6y.js} +1 -1
- package/dist/web/index.html +2 -2
- package/package.json +2 -2
- package/dist/web/assets/__vite-browser-external-BIHI7g3E.js +0 -1
- package/dist/web/assets/agent-DcdaQnmu.js +0 -1104
- package/dist/web/assets/classDiagram-KGZ6W3CR-B-qkKMYi.js +0 -1
- package/dist/web/assets/classDiagram-v2-72OJOZXJ-B-qkKMYi.js +0 -1
- package/dist/web/assets/index-CT0GtFLZ.css +0 -1
- package/dist/web/assets/stateDiagram-v2-36443NZ5-DhJ4Ky-7.js +0 -1
|
@@ -1,1104 +0,0 @@
|
|
|
1
|
-
var LR=Object.defineProperty;var Ob=t=>{throw TypeError(t)};var jR=(t,e,n)=>e in t?LR(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var m=(t,e,n)=>jR(t,typeof e!="symbol"?e+"":e,n),fp=(t,e,n)=>e.has(t)||Ob("Cannot "+n);var ne=(t,e,n)=>(fp(t,e,"read from private field"),n?n.call(t):e.get(t)),Ze=(t,e,n)=>e.has(t)?Ob("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,n),ct=(t,e,n,r)=>(fp(t,e,"write to private field"),r?r.call(t,n):e.set(t,n),n),ji=(t,e,n)=>(fp(t,e,"access private method"),n);var Bl=(t,e,n,r)=>({set _(s){ct(t,e,s,n)},get _(){return ne(t,e,r)}});import{b0 as Ir,b1 as Zm,b2 as DR,b3 as UR}from"./index-B5WxtMpv.js";import{buildDynamicSystemPrompt as FR}from"./context-builder-22jU3V56.js";const BR=["File","Folder","Function","Class","Interface","Method","CodeElement","Community","Process","FeatureCluster","Section","Struct","Enum","Macro","Typedef","Union","Namespace","Trait","Impl","TypeAlias","Const","Static","Variable","Property","Record","Delegate","Annotation","Constructor","Template","Module","Route","Tool"],pT=["CONTAINS","DEFINES","IMPORTS","CALLS","EXTENDS","IMPLEMENTS","HAS_METHOD","HAS_PROPERTY","ACCESSES","METHOD_OVERRIDES","OVERRIDES","METHOD_IMPLEMENTS","MEMBER_OF","STEP_IN_PROCESS","HANDLES_ROUTE","FETCHES","HANDLES_TOOL","ENTRY_POINT_OF","WRAPS","QUERIES","FEATURE_MEMBER_OF","FEATURE_DEPENDS_ON"];var $b=Object.defineProperty,de=(t,e)=>{let n={};for(var r in t)$b(n,r,{get:t[r],enumerable:!0});return $b(n,Symbol.toStringTag,{value:"Module"}),n};function mT(t){const e=Symbol.for(t);return{brand(n,r){var a,o;const s=r?Symbol.for(`${t}.${r}`):e;class i extends(o=n,a=s,o){constructor(...l){super(...l);m(this,a,!0)}static isInstance(l){return typeof l=="object"&&l!==null&&s in l&&l[s]===!0}}return Object.defineProperty(i,"name",{value:n.name}),i},sub(n){return mT(`${t}.${n}`)},isInstance(n){return typeof n=="object"&&n!==null&&e in n&&n[e]===!0}}}const zR=mT("langchain");var HR=de({ContextOverflowError:()=>Z_,LangChainError:()=>W_,ModelAbortError:()=>qm,addLangChainErrorFields:()=>cl,ns:()=>_f});function cl(t,e){return t.lc_error_code=e,t.message=`${t.message}
|
|
2
|
-
|
|
3
|
-
Troubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${e}/
|
|
4
|
-
`,t}const _f=zR.sub("error");var W_=class extends _f.brand(Error){constructor(e){super(e);m(this,"name","LangChainError");Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}},qm=class extends _f.brand(W_,"model-abort"){constructor(e,n){super(e);m(this,"name","ModelAbortError");m(this,"partialOutput");this.partialOutput=n}},Z_=class gT extends _f.brand(W_,"context-overflow"){constructor(n){super(n??"Input exceeded the model's context window.");m(this,"name","ContextOverflowError");m(this,"cause")}static fromError(n){const r=new gT(n.message);return r.cause=n,r}};function nu(t){return!!(t&&typeof t=="object"&&"type"in t&&t.type==="tool_call")}function VR(t){return!!(t&&typeof t=="object"&&"toolCall"in t&&t.toolCall!=null&&typeof t.toolCall=="object"&&"id"in t.toolCall&&typeof t.toolCall.id=="string")}var gh=class extends Error{constructor(e,n){super(e);m(this,"output");this.output=n}};function _h(t,e=$o){t=t.trim();const n=t.indexOf("```");if(n===-1)return e(t);let r=t.substring(n+3);r.startsWith(`json
|
|
5
|
-
`)?r=r.substring(5):r.startsWith("json")?r=r.substring(4):r.startsWith(`
|
|
6
|
-
`)&&(r=r.substring(1));const s=r.indexOf("```");let i=r;return s!==-1&&(i=r.substring(0,s)),e(i.trim())}function KR(t){try{return JSON.parse(t)}catch{}const e=t.trim();if(e.length===0)throw new Error("Unexpected end of JSON input");let n=0;function r(){for(;n<e.length&&/\s/.test(e[n]);)n+=1}function s(){if(e[n]!=='"')throw new Error(`Expected '"' at position ${n}, got '${e[n]}'`);n+=1;let l="",d=!1;for(;n<e.length;){const f=e[n];if(d){if(f==="n")l+=`
|
|
7
|
-
`;else if(f==="t")l+=" ";else if(f==="r")l+="\r";else if(f==="\\")l+="\\";else if(f==='"')l+='"';else if(f==="b")l+="\b";else if(f==="f")l+="\f";else if(f==="/")l+="/";else if(f==="u"){const h=e.substring(n+1,n+5);if(/^[0-9A-Fa-f]{0,4}$/.test(h))h.length===4?l+=String.fromCharCode(Number.parseInt(h,16)):l+=`u${h}`,n+=h.length;else throw new Error(`Invalid unicode escape sequence '\\u${h}' at position ${n}`)}else throw new Error(`Invalid escape sequence '\\${f}' at position ${n}`);d=!1}else if(f==="\\")d=!0;else{if(f==='"')return n+=1,l;l+=f}n+=1}return d&&(l+="\\"),l}function i(){const l=n;let d="";if(e[n]==="-"&&(d+="-",n+=1),n<e.length&&e[n]==="0"&&(d+="0",n+=1,e[n]>="0"&&e[n]<="9"))throw new Error(`Invalid number at position ${l}`);if(n<e.length&&e[n]>="1"&&e[n]<="9")for(;n<e.length&&e[n]>="0"&&e[n]<="9";)d+=e[n],n+=1;if(n<e.length&&e[n]===".")for(d+=".",n+=1;n<e.length&&e[n]>="0"&&e[n]<="9";)d+=e[n],n+=1;if(n<e.length&&(e[n]==="e"||e[n]==="E"))for(d+=e[n],n+=1,n<e.length&&(e[n]==="+"||e[n]==="-")&&(d+=e[n],n+=1);n<e.length&&e[n]>="0"&&e[n]<="9";)d+=e[n],n+=1;if(d==="-")return-0;const f=Number.parseFloat(d);if(Number.isNaN(f))throw n=l,new Error(`Invalid number '${d}' at position ${l}`);return f}function a(){if(r(),n>=e.length)throw new Error(`Unexpected end of input at position ${n}`);const l=e[n];if(l==="{")return c();if(l==="[")return o();if(l==='"')return s();if("null".startsWith(e.substring(n,n+4)))return n+=Math.min(4,e.length-n),null;if("true".startsWith(e.substring(n,n+4)))return n+=Math.min(4,e.length-n),!0;if("false".startsWith(e.substring(n,n+5)))return n+=Math.min(5,e.length-n),!1;if(l==="-"||l>="0"&&l<="9")return i();throw new Error(`Unexpected character '${l}' at position ${n}`)}function o(){if(e[n]!=="[")throw new Error(`Expected '[' at position ${n}, got '${e[n]}'`);const l=[];if(n+=1,r(),n>=e.length)return l;if(e[n]==="]")return n+=1,l;for(;n<e.length;){if(r(),n>=e.length||(l.push(a()),r(),n>=e.length))return l;if(e[n]==="]")return n+=1,l;if(e[n]===","){n+=1;continue}throw new Error(`Expected ',' or ']' at position ${n}, got '${e[n]}'`)}return l}function c(){if(e[n]!=="{")throw new Error(`Expected '{' at position ${n}, got '${e[n]}'`);const l={};if(n+=1,r(),n>=e.length)return l;if(e[n]==="}")return n+=1,l;for(;n<e.length;){if(r(),n>=e.length)return l;const d=s();if(r(),n>=e.length)return l;if(e[n]!==":")throw new Error(`Expected ':' at position ${n}, got '${e[n]}'`);if(n+=1,r(),n>=e.length||(l[d]=a(),r(),n>=e.length))return l;if(e[n]==="}")return n+=1,l;if(e[n]===","){n+=1;continue}throw new Error(`Expected ',' or '}' at position ${n}, got '${e[n]}'`)}return l}const u=a();if(r(),n<e.length)throw new Error(`Unexpected character '${e[n]}' at position ${n}`);return u}function $o(t){try{return typeof t>"u"?null:KR(t)}catch{return null}}const WR=/([A-Z]+)([A-Z][a-z0-9]+)/g,ZR=/([a-z0-9])([A-Z])/g,_T=/[-_\s]+/g;function qR(t){return t.replace(WR,"$1_$2").replace(ZR,"$1_$2").replace(_T,"_").toLowerCase()}function GR(t){const e=t.trim();return/[-_\s]/.test(e)?e.replace(_T,"_").toLowerCase().replace(/_+([a-z0-9])/g,(n,r)=>r.toUpperCase()):e}function JR(t,e){return(e==null?void 0:e[t])||qR(t)}function YR(t,e){return(e==null?void 0:e[t])||GR(t)}function yT(t,e,n){const r={};for(const s in t)Object.hasOwn(t,s)&&(r[e(s,n)]=t[s]);return r}const wT="__lc_escaped__";function XR(t){return"lc"in t||Object.keys(t).length===1&&"__lc_escaped__"in t}function QR(t){return{[wT]:t}}function bT(t){return Object.keys(t).length===1&&"__lc_escaped__"in t}function eP(t){return t!==null&&typeof t=="object"&&"lc_serializable"in t&&typeof t.toJSON=="function"}function tP(t){var n;let e;return t!==null&&typeof t=="object"?"lc_id"in t&&Array.isArray(t.lc_id)?e=t.lc_id:e=[((n=t.constructor)==null?void 0:n.name)??"Object"]:e=[typeof t],{lc:1,type:"not_implemented",id:e}}function Gm(t,e=new WeakSet){if(t!==null&&typeof t=="object"&&!Array.isArray(t)){if(e.has(t))return tP(t);if(eP(t))return t;e.add(t);const n=t;if(XR(n))return e.delete(t),QR(n);const r={};for(const[s,i]of Object.entries(n))r[s]=Gm(i,e);return e.delete(t),r}return Array.isArray(t)?t.map(n=>Gm(n,e)):t}function Jm(t){if(t!==null&&typeof t=="object"&&!Array.isArray(t)){const e=t;if(bT(e))return e[wT];const n={};for(const[r,s]of Object.entries(e))n[r]=Jm(s);return n}return Array.isArray(t)?t.map(e=>Jm(e)):t}var nP=de({Serializable:()=>xr,get_lc_unique_name:()=>yf});function Rb(t){return Array.isArray(t)?[...t]:{...t}}function rP(t,e){const n=Rb(t);for(const[r,s]of Object.entries(e)){const[i,...a]=r.split(".").reverse();let o=n;for(const c of a.reverse()){if(o[c]===void 0)break;o[c]=Rb(o[c]),o=o[c]}o[i]!==void 0&&(o[i]={lc:1,type:"secret",id:[s]})}return n}function yf(t){const e=Object.getPrototypeOf(t);return typeof t.lc_name=="function"&&(typeof e.lc_name!="function"||t.lc_name()!==e.lc_name())?t.lc_name():t.name}var xr=class vT{constructor(e,...n){m(this,"lc_serializable",!1);m(this,"lc_kwargs");this.lc_serializable_keys!==void 0?this.lc_kwargs=Object.fromEntries(Object.entries(e||{}).filter(([r])=>{var s;return(s=this.lc_serializable_keys)==null?void 0:s.includes(r)})):this.lc_kwargs=e??{}}static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,yf(this.constructor)]}get lc_secrets(){}get lc_attributes(){}get lc_aliases(){}get lc_serializable_keys(){}toJSON(){if(!this.lc_serializable)return this.toJSONNotImplemented();if(this.lc_kwargs instanceof vT||typeof this.lc_kwargs!="object"||Array.isArray(this.lc_kwargs))return this.toJSONNotImplemented();const e={},n={},r=Object.keys(this.lc_kwargs).reduce((o,c)=>(o[c]=c in this?this[c]:this.lc_kwargs[c],o),{});for(let o=Object.getPrototypeOf(this);o;o=Object.getPrototypeOf(o))Object.assign(e,Reflect.get(o,"lc_aliases",this)),Object.assign(n,Reflect.get(o,"lc_secrets",this)),Object.assign(r,Reflect.get(o,"lc_attributes",this));Object.keys(n).forEach(o=>{let c=this,u=r;const[l,...d]=o.split(".").reverse();for(const f of d.reverse()){if(!(f in c)||c[f]===void 0)return;(!(f in u)||u[f]===void 0)&&(typeof c[f]=="object"&&c[f]!=null?u[f]={}:Array.isArray(c[f])&&(u[f]=[])),c=c[f],u=u[f]}l in c&&c[l]!==void 0&&(u[l]=u[l]||c[l])});const s={},i=new WeakSet;i.add(this);for(const[o,c]of Object.entries(r))s[o]=Gm(c,i);const a=yT(Object.keys(n).length?rP(s,n):s,JR,e);return{lc:1,type:"constructor",id:this.lc_id,kwargs:a}}toJSONNotImplemented(){return{lc:1,type:"not_implemented",id:this.lc_id}}};function kr(t){return typeof t=="object"&&t!==null&&"type"in t&&typeof t.type=="string"&&"source_type"in t&&(t.source_type==="url"||t.source_type==="base64"||t.source_type==="text"||t.source_type==="id")}function q_(t){return kr(t)&&t.source_type==="url"&&"url"in t&&typeof t.url=="string"}function G_(t){return kr(t)&&t.source_type==="base64"&&"data"in t&&typeof t.data=="string"}function sP(t){return kr(t)&&t.source_type==="text"&&"text"in t&&typeof t.text=="string"}function ST(t){return kr(t)&&t.source_type==="id"&&"id"in t&&typeof t.id=="string"}function AT(t){if(kr(t)){if(t.source_type==="url")return{type:"image_url",image_url:{url:t.url}};if(t.source_type==="base64"){if(!t.mime_type)throw new Error("mime_type key is required for base64 data.");return{type:"image_url",image_url:{url:`data:${t.mime_type};base64,${t.data}`}}}}throw new Error("Unsupported source type. Only 'url' and 'base64' are supported.")}function Ym(t){const e=t.split(";")[0].split("/");if(e.length!==2)throw new Error(`Invalid mime type: "${t}" - does not match type/subtype format.`);const n=e[0].trim(),r=e[1].trim();if(n===""||r==="")throw new Error(`Invalid mime type: "${t}" - type or subtype is empty.`);const s={};for(const i of t.split(";").slice(1)){const a=i.split("=");if(a.length!==2)throw new Error(`Invalid parameter syntax in mime type: "${t}".`);const o=a[0].trim(),c=a[1].trim();if(o==="")throw new Error(`Invalid parameter syntax in mime type: "${t}".`);s[o]=c}return{type:n,subtype:r,parameters:s}}function Gr({dataUrl:t,asTypedArray:e=!1}){const n=t.match(/^data:(\w+\/\w+);base64,([A-Za-z0-9+/]+=*)$/);let r;if(n){r=n[1].toLowerCase();const s=e?Uint8Array.from(atob(n[2]),i=>i.charCodeAt(0)):n[2];return{mime_type:r,data:s}}}function ul(t,e){if(t.type==="text"){if(!e.fromStandardTextBlock)throw new Error(`Converter for ${e.providerName} does not implement \`fromStandardTextBlock\` method.`);return e.fromStandardTextBlock(t)}if(t.type==="image"){if(!e.fromStandardImageBlock)throw new Error(`Converter for ${e.providerName} does not implement \`fromStandardImageBlock\` method.`);return e.fromStandardImageBlock(t)}if(t.type==="audio"){if(!e.fromStandardAudioBlock)throw new Error(`Converter for ${e.providerName} does not implement \`fromStandardAudioBlock\` method.`);return e.fromStandardAudioBlock(t)}if(t.type==="file"){if(!e.fromStandardFileBlock)throw new Error(`Converter for ${e.providerName} does not implement \`fromStandardFileBlock\` method.`);return e.fromStandardFileBlock(t)}throw new Error(`Unable to convert content block type '${t.type}' to provider-specific format: not recognized.`)}function fe(t,e){return Te(t)&&t.type===e}function Te(t){return typeof t=="object"&&t!==null}function zn(t){return Array.isArray(t)}function V(t){return typeof t=="string"}function Br(t){return typeof t=="number"}function J_(t){return t instanceof Uint8Array}function Pb(t){try{return JSON.parse(t)}catch{return}}const wi=t=>t();function iP(t){if(t.type==="char_location"&&V(t.document_title)&&Br(t.start_char_index)&&Br(t.end_char_index)&&V(t.cited_text)){const{document_title:e,start_char_index:n,end_char_index:r,cited_text:s,...i}=t;return{...i,type:"citation",source:"char",title:e??void 0,startIndex:n,endIndex:r,citedText:s}}if(t.type==="page_location"&&V(t.document_title)&&Br(t.start_page_number)&&Br(t.end_page_number)&&V(t.cited_text)){const{document_title:e,start_page_number:n,end_page_number:r,cited_text:s,...i}=t;return{...i,type:"citation",source:"page",title:e??void 0,startIndex:n,endIndex:r,citedText:s}}if(t.type==="content_block_location"&&V(t.document_title)&&Br(t.start_block_index)&&Br(t.end_block_index)&&V(t.cited_text)){const{document_title:e,start_block_index:n,end_block_index:r,cited_text:s,...i}=t;return{...i,type:"citation",source:"block",title:e??void 0,startIndex:n,endIndex:r,citedText:s}}if(t.type==="web_search_result_location"&&V(t.url)&&V(t.title)&&V(t.encrypted_index)&&V(t.cited_text)){const{url:e,title:n,encrypted_index:r,cited_text:s,...i}=t;return{...i,type:"citation",source:"url",url:e,title:n,startIndex:Number(r),endIndex:Number(r),citedText:s}}if(t.type==="search_result_location"&&V(t.source)&&V(t.title)&&Br(t.start_block_index)&&Br(t.end_block_index)&&V(t.cited_text)){const{source:e,title:n,start_block_index:r,end_block_index:s,cited_text:i,...a}=t;return{...a,type:"citation",source:"search",url:e,title:n??void 0,startIndex:r,endIndex:s,citedText:i}}}function TT(t){if(fe(t,"document")&&Te(t.source)&&"type"in t.source){if(t.source.type==="base64"&&V(t.source.media_type)&&V(t.source.data))return{type:"file",mimeType:t.source.media_type,data:t.source.data};if(t.source.type==="url"&&V(t.source.url))return{type:"file",url:t.source.url};if(t.source.type==="file"&&V(t.source.file_id))return{type:"file",fileId:t.source.file_id};if(t.source.type==="text"&&V(t.source.data))return{type:"file",mimeType:String(t.source.media_type??"text/plain"),data:t.source.data}}else if(fe(t,"image")&&Te(t.source)&&"type"in t.source){if(t.source.type==="base64"&&V(t.source.media_type)&&V(t.source.data))return{type:"image",mimeType:t.source.media_type,data:t.source.data};if(t.source.type==="url"&&V(t.source.url))return{type:"image",url:t.source.url};if(t.source.type==="file"&&V(t.source.file_id))return{type:"image",fileId:t.source.file_id}}}function aP(t){function*e(){for(const n of t){const r=TT(n);r?yield r:yield n}}return Array.from(e())}function Nb(t){function*e(){var r;const n=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;for(const s of n){if(fe(s,"text")&&V(s.text)){const{text:i,citations:a,...o}=s;if(zn(a)&&a.length){const c=a.reduce((u,l)=>{const d=iP(l);return d?[...u,d]:u},[]);yield{...o,type:"text",text:i,annotations:c};continue}else{yield{...o,type:"text",text:i};continue}}else if(fe(s,"thinking")&&V(s.thinking)){const{thinking:i,signature:a,...o}=s;yield{...o,type:"reasoning",reasoning:i,signature:a};continue}else if(fe(s,"redacted_thinking")){yield{type:"non_standard",value:s};continue}else if(fe(s,"tool_use")&&V(s.name)&&V(s.id)){yield{type:"tool_call",id:s.id,name:s.name,args:s.input};continue}else if(fe(s,"input_json_delta")){if(cP(t)&&((r=t.tool_call_chunks)!=null&&r.length)){const i=t.tool_call_chunks[0];yield{type:"tool_call_chunk",id:i.id,name:i.name,args:i.args,index:i.index};continue}}else if(fe(s,"server_tool_use")&&V(s.name)&&V(s.id)){const{name:i,id:a}=s;if(i==="web_search"){yield{id:a,type:"server_tool_call",name:"web_search",args:{query:wi(()=>{if(typeof s.input=="string")return s.input;if(Te(s.input)&&V(s.input.query))return s.input.query;if(V(s.partial_json)){const o=Pb(s.partial_json);if(o!=null&&o.query)return o.query}return""})}};continue}else if(s.name==="code_execution"){yield{id:a,type:"server_tool_call",name:"code_execution",args:{code:wi(()=>{if(typeof s.input=="string")return s.input;if(Te(s.input)&&V(s.input.code))return s.input.code;if(V(s.partial_json)){const o=Pb(s.partial_json);if(o!=null&&o.code)return o.code}return""})}};continue}}else if(fe(s,"web_search_tool_result")&&V(s.tool_use_id)&&zn(s.content)){const{content:i,tool_use_id:a}=s;yield{type:"server_tool_call_result",name:"web_search",toolCallId:a,status:"success",output:{urls:i.reduce((o,c)=>fe(c,"web_search_result")?[...o,c.url]:o,[])}};continue}else if(fe(s,"code_execution_tool_result")&&V(s.tool_use_id)&&Te(s.content)){yield{type:"server_tool_call_result",name:"code_execution",toolCallId:s.tool_use_id,status:"success",output:s.content};continue}else if(fe(s,"mcp_tool_use")){yield{id:s.id,type:"server_tool_call",name:"mcp_tool_use",args:s.input};continue}else if(fe(s,"mcp_tool_result")&&V(s.tool_use_id)&&Te(s.content)){yield{type:"server_tool_call_result",name:"mcp_tool_use",toolCallId:s.tool_use_id,status:"success",output:s.content};continue}else if(fe(s,"container_upload")){yield{type:"server_tool_call",name:"container_upload",args:s.input};continue}else if(fe(s,"search_result")){yield{id:s.id,type:"non_standard",value:s};continue}else if(fe(s,"tool_result")){yield{id:s.id,type:"non_standard",value:s};continue}else{const i=TT(s);if(i){yield i;continue}}yield{type:"non_standard",value:s}}}return Array.from(e())}const oP={translateContent:Nb,translateContentChunk:Nb};function cP(t){return typeof(t==null?void 0:t._getType)=="function"&&typeof t.concat=="function"&&t._getType()==="ai"}function uP(t){return q_(t)?{type:t.type,mimeType:t.mime_type,url:t.url,metadata:t.metadata}:G_(t)?{type:t.type,mimeType:t.mime_type??"application/octet-stream",data:t.data,metadata:t.metadata}:ST(t)?{type:t.type,mimeType:t.mime_type,fileId:t.id,metadata:t.metadata}:t}function lP(t){return t.map(uP)}function dP(t){return!!(fe(t,"image_url")&&Te(t.image_url)||fe(t,"input_audio")&&Te(t.input_audio)||fe(t,"file")&&Te(t.file))}function hP(t){if(fe(t,"image_url")&&Te(t.image_url)&&V(t.image_url.url)){const e=Gr({dataUrl:t.image_url.url});return e?{type:"image",mimeType:e.mime_type,data:e.data}:{type:"image",url:t.image_url.url}}else{if(fe(t,"input_audio")&&Te(t.input_audio)&&V(t.input_audio.data)&&V(t.input_audio.format))return{type:"audio",data:t.input_audio.data,mimeType:`audio/${t.input_audio.format}`};if(fe(t,"file")&&Te(t.file)&&V(t.file.data)){const e=Gr({dataUrl:t.file.data});if(e)return{type:"file",data:e.data,mimeType:e.mime_type};if(V(t.file.file_id))return{type:"file",fileId:t.file.file_id}}}return t}function fP(t){const e=[];typeof t.content=="string"?t.content.length>0&&e.push({type:"text",text:t.content}):e.push(...Y_(t.content));for(const n of t.tool_calls??[])e.push({type:"tool_call",id:n.id,name:n.name,args:n.args});return e}function pP(t){const e=[];typeof t.content=="string"?t.content.length>0&&e.push({type:"text",text:t.content}):e.push(...Y_(t.content));for(const n of t.tool_calls??[])e.push({type:"tool_call",id:n.id,name:n.name,args:n.args});return e}function Y_(t){const e=[];for(const n of t)dP(n)?e.push(hP(n)):e.push(n);return e}function mP(t){if(t.type==="url_citation"){const{url:e,title:n,start_index:r,end_index:s}=t;return{type:"citation",url:e,title:n,startIndex:r,endIndex:s}}if(t.type==="file_citation"){const{file_id:e,filename:n,index:r}=t;return{type:"citation",title:n,startIndex:r,endIndex:r,fileId:e}}return t}function ET(t){function*e(){var r;Te((r=t.additional_kwargs)==null?void 0:r.reasoning)&&zn(t.additional_kwargs.reasoning.summary)&&(yield{type:"reasoning",reasoning:t.additional_kwargs.reasoning.summary.reduce((s,i)=>Te(i)&&V(i.text)?`${s}${i.text}`:s,"")});const n=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;for(const s of n)if(fe(s,"text")){const{text:i,annotations:a,phase:o,extras:c,...u}=s,l=Te(c)?{...c}:{};V(o)&&(l.phase=o);const d=Object.keys(l).length>0?{extras:l}:{};Array.isArray(a)?yield{...u,...d,type:"text",text:String(i),annotations:a.map(mP)}:yield{...u,...d,type:"text",text:String(i)}}for(const s of t.tool_calls??[])yield{type:"tool_call",id:s.id,name:s.name,args:s.args};if(Te(t.additional_kwargs)&&zn(t.additional_kwargs.tool_outputs))for(const s of t.additional_kwargs.tool_outputs){if(fe(s,"web_search_call")){const i={};if(Te(s.action)&&V(s.action.query)&&(i.query=s.action.query),yield{id:s.id,type:"server_tool_call",name:"web_search",args:i},s.status==="completed"||s.status==="failed"){const a={};Te(s.action)&&(a.action=s.action),yield{type:"server_tool_call_result",toolCallId:V(s.id)?s.id:"",status:s.status==="completed"?"success":"error",output:a}}continue}else if(fe(s,"file_search_call")){yield{id:s.id,type:"server_tool_call",name:"file_search",args:{queries:zn(s.queries)?s.queries:[]}},(s.status==="completed"||s.status==="failed")&&(yield{type:"server_tool_call_result",toolCallId:V(s.id)?s.id:"",status:s.status==="completed"?"success":"error",output:zn(s.results)?{results:s.results}:{}});continue}else if(fe(s,"computer_call")){yield{type:"non_standard",value:s};continue}else if(fe(s,"code_interpreter_call")){if(V(s.code)&&(yield{id:s.id,type:"server_tool_call",name:"code_interpreter",args:{code:s.code}}),zn(s.outputs)){const i=wi(()=>{if(s.status!=="in_progress"){if(s.status==="completed")return 0;if(s.status==="incomplete")return 127;if(s.status!=="interpreting"&&s.status==="failed")return 1}});for(const a of s.outputs)if(fe(a,"logs")){yield{type:"server_tool_call_result",toolCallId:s.id??"",status:"success",output:{type:"code_interpreter_output",returnCode:i??0,stderr:[0,void 0].includes(i)?void 0:String(a.logs),stdout:[0,void 0].includes(i)?String(a.logs):void 0}};continue}}continue}else if(fe(s,"mcp_call")){yield{id:s.id,type:"server_tool_call",name:"mcp_call",args:s.input};continue}else if(fe(s,"mcp_list_tools")){yield{id:s.id,type:"server_tool_call",name:"mcp_list_tools",args:s.input};continue}else if(fe(s,"mcp_approval_request")){yield{type:"non_standard",value:s};continue}else if(fe(s,"tool_search_call")){const i={};Te(s.arguments)&&Object.assign(i,s.arguments);const a={};V(s.execution)&&(a.execution=s.execution),V(s.status)&&(a.status=s.status),V(s.call_id)&&(a.call_id=s.call_id),yield{id:V(s.id)?s.id:"",type:"server_tool_call",name:"tool_search",args:i,...Object.keys(a).length>0?{extras:a}:{}};continue}else if(fe(s,"tool_search_output")){const i={name:"tool_search"};V(s.execution)&&(i.execution=s.execution),yield{type:"server_tool_call_result",toolCallId:V(s.id)?s.id:"",status:s.status==="completed"?"success":s.status==="failed"?"error":"success",output:{tools:zn(s.tools)?s.tools:[]},extras:i};continue}else if(fe(s,"image_generation_call")){V(s.result)&&(yield{type:"image",mimeType:"image/png",data:s.result,id:V(s.id)?s.id:void 0,metadata:{status:V(s.status)?s.status:void 0}}),yield{type:"non_standard",value:s};continue}Te(s)&&(yield{type:"non_standard",value:s})}}return Array.from(e())}function gP(t){function*e(){yield*ET(t);for(const n of t.tool_call_chunks??[])yield{type:"tool_call_chunk",id:n.id,name:n.name,args:n.args}}return Array.from(e())}const _P={translateContent:t=>typeof t.content=="string"?fP(t):ET(t),translateContentChunk:t=>typeof t.content=="string"?pP(t):gP(t)};function IT(t){return typeof t=="object"&&t!==null&&"type"in t&&"content"in t&&(typeof t.content=="string"||Array.isArray(t.content))}function yP(t,e="pretty"){return e==="pretty"?wP(t):JSON.stringify(t)}function wP(t){const e=[],n=` ${t.type.charAt(0).toUpperCase()+t.type.slice(1)} Message `,r=Math.floor((80-n.length)/2),s="=".repeat(r),i=n.length%2===0?s:`${s}=`;if(e.push(`${s}${n}${i}`),t.type==="ai"){const a=t;if(a.tool_calls&&a.tool_calls.length>0){e.push("Tool Calls:");for(const o of a.tool_calls){e.push(` ${o.name} (${o.id})`),e.push(` Call ID: ${o.id}`),e.push(" Args:");for(const[c,u]of Object.entries(o.args))e.push(` ${c}: ${typeof u=="object"?JSON.stringify(u):u}`)}}}if(t.type==="tool"){const a=t;a.name&&e.push(`Name: ${a.name}`)}return typeof t.content=="string"&&t.content.trim()&&(e.length>1&&e.push(""),e.push(t.content)),e.join(`
|
|
8
|
-
`)}const pp=Symbol.for("langchain.message");function Mb(t){return Array.isArray(t)?t:typeof t=="string"?t===""?[]:[{type:"text",text:t}]:t==null?[]:[t]}function zs(t,e){if(typeof t=="string")return t===""?e:typeof e=="string"?t+e:Array.isArray(e)&&e.length===0?t:Array.isArray(e)&&e.some(n=>kr(n))?[{type:"text",source_type:"text",text:t},...e]:[{type:"text",text:t},...e];if(Array.isArray(e)){const n=Mb(t);return Ro(n,e)??[...n,...e]}else return e===""?t:Array.isArray(t)&&t.some(n=>kr(n))?[...t,{type:"file",source_type:"text",text:e}]:[...Mb(t),{type:"text",text:e}]}function xT(t,e){return t==="error"||e==="error"?"error":"success"}function bP(t,e){function n(r,s){if(typeof r!="object"||r===null||r===void 0)return r;if(s>=e)return Array.isArray(r)?"[Array]":"[Object]";if(Array.isArray(r))return r.map(a=>n(a,s+1));const i={};for(const a of Object.keys(r))i[a]=n(r[a],s+1);return i}return JSON.stringify(n(t,0),null,2)}var nT,Ot=class extends xr{constructor(e){const n=typeof e=="string"||Array.isArray(e)?{content:e}:e;n.additional_kwargs||(n.additional_kwargs={}),n.response_metadata||(n.response_metadata={});super(n);m(this,"lc_namespace",["langchain_core","messages"]);m(this,"lc_serializable",!0);m(this,nT,!0);m(this,"id");m(this,"name");m(this,"content");m(this,"additional_kwargs");m(this,"response_metadata");this.name=n.name,n.content===void 0&&n.contentBlocks!==void 0?(this.content=n.contentBlocks,this.response_metadata={output_version:"v1",...n.response_metadata}):n.content!==void 0?(this.content=n.content??[],this.response_metadata=n.response_metadata):(this.content=[],this.response_metadata=n.response_metadata),this.additional_kwargs=n.additional_kwargs,this.id=n.id}get lc_aliases(){return{additional_kwargs:"additional_kwargs",response_metadata:"response_metadata"}}_getType(){return this.type}getType(){return this._getType()}get text(){return typeof this.content=="string"?this.content:Array.isArray(this.content)?this.content.map(e=>typeof e=="string"?e:e.type==="text"?e.text:"").join(""):""}get contentBlocks(){const e=typeof this.content=="string"?[{type:"text",text:this.content}]:this.content;return[lP,Y_,aP].reduce((n,r)=>r(n),e)}toDict(){return{type:this.getType(),data:this.toJSON().kwargs}}static lc_name(){return"BaseMessage"}get _printableFields(){return{id:this.id,content:this.content,name:this.name,additional_kwargs:this.additional_kwargs,response_metadata:this.response_metadata}}static isInstance(e){return typeof e=="object"&&e!==null&&pp in e&&e[pp]===!0&&IT(e)}_updateId(e){this.id=e,this.lc_kwargs.id=e}get[(nT=pp,Symbol.toStringTag)](){return this.constructor.lc_name()}[Symbol.for("nodejs.util.inspect.custom")](e){if(e===null)return this;const n=bP(this._printableFields,Math.max(4,e));return`${this.constructor.lc_name()} ${n}`}toFormattedString(e="pretty"){return yP(this,e)}};function vP(t){return Array.isArray(t)&&t.every(e=>typeof e.index=="number")}const kT=["index","created","timestamp"];function Sn(t,e,n){const r=(n==null?void 0:n.ignoreKeys)??kT;if(t==null&&e==null)return;if(t==null||e==null)return t??e;const s={...t};for(const[i,a]of Object.entries(e))if(s[i]==null)s[i]=a;else{if(a==null)continue;if(typeof s[i]!=typeof a||Array.isArray(s[i])!==Array.isArray(a))throw new Error(`field[${i}] already exists in the message chunk, but with a different type.`);if(typeof s[i]=="string"){if(i==="type")continue;if(["id","name","output_version","model_provider"].includes(i))a&&(s[i]=a);else{if(r.includes(i))continue;s[i]+=a}}else if(typeof s[i]=="number"){if(r.includes(i))continue;s[i]=s[i]+a}else if(typeof s[i]=="object"&&!Array.isArray(s[i]))s[i]=Sn(s[i],a,n);else if(Array.isArray(s[i]))s[i]=Ro(s[i],a,n);else{if(s[i]===a)continue;console.warn(`field[${i}] already exists in this message chunk and value has unsupported type.`)}}return s}function SP(t){return typeof t=="number"||typeof t=="string"}function Lb(t){return typeof t!="object"||t===null||!("index"in t)?!1:SP(t.index)}function jb(t){if(typeof t!="object"||t===null||!("id"in t))return!1;const e=t.id;return e!=null&&e!==""}function Db(t){return t.endsWith("_delta")?t.slice(0,-6):t}function AP(t,e){return typeof t!="object"||t===null||typeof e!="object"||e===null||!("type"in t)||!("type"in e)?!1:typeof t.type=="string"&&typeof e.type=="string"&&Db(t.type)!==Db(e.type)}function TP(t,e){const n=Lb(e),r=jb(e);return!n&&!r?-1:t.findIndex(s=>{const i=Lb(s),a=jb(s);return n&&i?s.index!==e.index||AP(s,e)?!1:a&&r?s.id===e.id:!0:!n&&!i&&r&&a?s.id===e.id:!1})}function Ro(t,e,n){if(!(t==null&&e==null)){if(t==null||e==null)return t||e;{const r=[...t];for(const s of e){const i=TP(r,s);if(i!==-1)r[i]=Sn(r[i],s,n);else{if(typeof s=="object"&&s!==null&&"text"in s&&s.text==="")continue;r.push(s)}}return r}}}function CT(t,e,n){if(!(t==null&&e==null)){if(t==null||e==null)return t??e;if(typeof t!=typeof e)throw new Error(`Cannot merge objects of different types.
|
|
9
|
-
Left ${typeof t}
|
|
10
|
-
Right ${typeof e}`);if(typeof t=="string"&&typeof e=="string")return t+e;if(Array.isArray(t)&&Array.isArray(e))return Ro(t,e,n);if(typeof t=="object"&&typeof e=="object")return Sn(t,e,n);if(t===e)return t;throw new Error(`Can not merge objects of different types.
|
|
11
|
-
Left ${t}
|
|
12
|
-
Right ${e}`)}}var vs=class OT extends Ot{static isInstance(e){if(!super.isInstance(e))return!1;let n=Object.getPrototypeOf(e);for(;n!==null;){if(n===OT.prototype)return!0;n=Object.getPrototypeOf(n)}return!1}};function $T(t){return typeof t.role=="string"}function Et(t){return typeof(t==null?void 0:t._getType)=="function"}function Po(t){return vs.isInstance(t)}var EP=de({ToolMessage:()=>fn,ToolMessageChunk:()=>ll,defaultToolCallParser:()=>Q_,isDirectToolOutput:()=>X_,isToolMessage:()=>ca,isToolMessageChunk:()=>RT});function X_(t){return t!=null&&typeof t=="object"&&"lc_direct_tool_output"in t&&t.lc_direct_tool_output===!0}var fn=class extends Ot{constructor(e,n,r){const s=typeof e=="string"||Array.isArray(e)?{content:e,name:r,tool_call_id:n}:e;super(s);m(this,"lc_direct_tool_output",!0);m(this,"type","tool");m(this,"status");m(this,"tool_call_id");m(this,"metadata");m(this,"artifact");this.tool_call_id=s.tool_call_id,this.artifact=s.artifact,this.status=s.status,this.metadata=s.metadata}static lc_name(){return"ToolMessage"}get lc_aliases(){return{tool_call_id:"tool_call_id"}}static isInstance(e){return super.isInstance(e)&&e.type==="tool"}get _printableFields(){return{...super._printableFields,tool_call_id:this.tool_call_id,artifact:this.artifact}}},ll=class extends vs{constructor(e){super(e);m(this,"type","tool");m(this,"tool_call_id");m(this,"status");m(this,"artifact");this.tool_call_id=e.tool_call_id,this.artifact=e.artifact,this.status=e.status}static lc_name(){return"ToolMessageChunk"}concat(e){const n=this.constructor;return new n({content:zs(this.content,e.content),additional_kwargs:Sn(this.additional_kwargs,e.additional_kwargs),response_metadata:Sn(this.response_metadata,e.response_metadata),artifact:CT(this.artifact,e.artifact),tool_call_id:this.tool_call_id,id:this.id??e.id,status:xT(this.status,e.status)})}get _printableFields(){return{...super._printableFields,tool_call_id:this.tool_call_id,artifact:this.artifact}}};function Q_(t){const e=[],n=[];for(const r of t)if(r.function){const s=r.function.name;try{const i=JSON.parse(r.function.arguments);e.push({name:s||"",args:i||{},id:r.id})}catch{n.push({name:s,args:r.function.arguments,id:r.id,error:"Malformed args."})}}else continue;return[e,n]}function ca(t){return typeof t=="object"&&t!==null&&"getType"in t&&typeof t.getType=="function"&&t.getType()==="tool"}function RT(t){return t._getType()==="tool"}function ey(t){switch(t){case"csv":return"text/csv";case"doc":return"application/vnd.openxmlformats-officedocument.wordprocessingml.document";case"docx":return"application/vnd.openxmlformats-officedocument.wordprocessingml.document";case"html":return"text/html";case"md":return"text/markdown";case"pdf":return"application/pdf";case"txt":return"text/plain";case"xls":return"application/vnd.ms-excel";case"xlsx":return"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";case"gif":return"image/gif";case"jpeg":return"image/jpeg";case"jpg":return"image/jpeg";case"png":return"image/png";case"webp":return"image/webp";case"flv":return"video/flv";case"mkv":return"video/mkv";case"mov":return"video/mov";case"mp4":return"video/mp4";case"mpeg":return"video/mpeg";case"mpg":return"video/mpg";case"three_gp":return"video/three_gp";case"webm":return"video/webm";case"wmv":return"video/wmv";default:return"application/octet-stream"}}function IP(t){if(Te(t.document)&&Te(t.document.source)){const e=ey(Te(t.document)&&V(t.document.format)?t.document.format:"");if(Te(t.document.source)){if(Te(t.document.source.s3Location)&&V(t.document.source.s3Location.uri))return{type:"file",mimeType:e,fileId:t.document.source.s3Location.uri};if(J_(t.document.source.bytes))return{type:"file",mimeType:e,data:t.document.source.bytes};if(V(t.document.source.text))return{type:"file",mimeType:e,data:Buffer.from(t.document.source.text).toString("base64")};if(zn(t.document.source.content))return{type:"file",mimeType:e,data:t.document.source.content.reduce((n,r)=>Te(r)&&V(r.text)?n+r.text:n,"")}}}return{type:"non_standard",value:t}}function xP(t){if(fe(t,"image")&&Te(t.image)){const e=ey(Te(t.image)&&V(t.image.format)?t.image.format:"");if(Te(t.image.source)){if(Te(t.image.source.s3Location)&&V(t.image.source.s3Location.uri))return{type:"image",mimeType:e,fileId:t.image.source.s3Location.uri};if(J_(t.image.source.bytes))return{type:"image",mimeType:e,data:t.image.source.bytes}}}return{type:"non_standard",value:t}}function kP(t){if(fe(t,"video")&&Te(t.video)){const e=ey(Te(t.video)&&V(t.video.format)?t.video.format:"");if(Te(t.video.source)){if(Te(t.video.source.s3Location)&&V(t.video.source.s3Location.uri))return{type:"video",mimeType:e,fileId:t.video.source.s3Location.uri};if(J_(t.video.source.bytes))return{type:"video",mimeType:e,data:t.video.source.bytes}}}return{type:"non_standard",value:t}}function Ub(t){function*e(){const n=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;for(const r of n){if(fe(r,"cache_point")){yield{type:"non_standard",value:r};continue}else if(fe(r,"citations_content")&&Te(r.citationsContent)){yield{type:"text",text:zn(r.citationsContent.content)?r.citationsContent.content.reduce((s,i)=>Te(i)&&V(i.text)?s+i.text:s,""):"",annotations:zn(r.citationsContent.citations)?r.citationsContent.citations.reduce((s,i)=>{if(Te(i)){const a=zn(i.sourceContent)?i.sourceContent.reduce((c,u)=>Te(u)&&V(u.text)?c+u.text:c,""):"",o=wi(()=>{if(Te(i.location)){const c=i.location.documentChar||i.location.documentPage||i.location.documentChunk;if(Te(c))return{source:Br(c.documentIndex)?c.documentIndex.toString():void 0,startIndex:Br(c.start)?c.start:void 0,endIndex:Br(c.end)?c.end:void 0}}return{}});s.push({type:"citation",citedText:a,...o})}return s},[]):[]};continue}else if(fe(r,"document")&&Te(r.document)){yield IP(r);continue}else if(fe(r,"guard_content")){yield{type:"non_standard",value:r};continue}else if(fe(r,"image")&&Te(r.image)){yield xP(r);continue}else if(fe(r,"reasoning_content")&&V(r.reasoningText)){yield{type:"reasoning",reasoning:r.reasoningText};continue}else if(fe(r,"text")&&V(r.text)){yield{type:"text",text:r.text};continue}else if(fe(r,"tool_result")){yield{type:"non_standard",value:r};continue}else{if(fe(r,"tool_call"))continue;if(fe(r,"video")&&Te(r.video)){yield kP(r);continue}}yield{type:"non_standard",value:r}}}return Array.from(e())}const CP={translateContent:Ub,translateContentChunk:Ub};function Fb(t){var r;const e=[],n=(r=t.additional_kwargs)==null?void 0:r.reasoning_content;if(V(n)&&n.length>0&&e.push({type:"reasoning",reasoning:n}),typeof t.content=="string")t.content.length>0&&e.push({type:"text",text:t.content});else for(const s of t.content)typeof s=="object"&&"type"in s&&s.type==="text"&&"text"in s&&V(s.text)&&e.push({type:"text",text:s.text});for(const s of t.tool_calls??[])e.push({type:"tool_call",id:s.id,name:s.name,args:s.args});return e}const OP={translateContent:Fb,translateContentChunk:Fb};function Bb(t){function*e(){const n=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;for(const r of n){if(fe(r,"text")&&V(r.text)){yield{type:"text",text:r.text};continue}else if(fe(r,"thinking")&&V(r.thinking)){yield{type:"reasoning",reasoning:r.thinking,...r.signature?{signature:r.signature}:{}};continue}else if(fe(r,"inlineData")&&Te(r.inlineData)&&V(r.inlineData.mimeType)&&V(r.inlineData.data)){yield{type:"file",mimeType:r.inlineData.mimeType,data:r.inlineData.data};continue}else if(fe(r,"functionCall")&&Te(r.functionCall)&&V(r.functionCall.name)&&Te(r.functionCall.args)){yield{type:"tool_call",id:t.id,name:r.functionCall.name,args:r.functionCall.args};continue}else if(fe(r,"functionResponse")){yield{type:"non_standard",value:r};continue}else if(fe(r,"fileData")&&Te(r.fileData)&&V(r.fileData.mimeType)&&V(r.fileData.fileUri)){yield{type:"file",mimeType:r.fileData.mimeType,fileId:r.fileData.fileUri};continue}else if(fe(r,"executableCode")){yield{type:"non_standard",value:r};continue}else if(fe(r,"codeExecutionResult")){yield{type:"non_standard",value:r};continue}yield{type:"non_standard",value:r}}}return Array.from(e())}const $P={translateContent:Bb,translateContentChunk:Bb};function zb(t){function*e(){const n=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;for(const r of n){if(fe(r,"reasoning")&&V(r.reasoning)){const s=wi(()=>{var a;const i=n.indexOf(r);if(zn((a=t.additional_kwargs)==null?void 0:a.signatures)&&i>=0)return t.additional_kwargs.signatures.at(i)});V(s)?yield{type:"reasoning",reasoning:r.reasoning,signature:s}:yield{type:"reasoning",reasoning:r.reasoning};continue}else if(fe(r,"thinking")&&V(r.thinking)){yield{type:"reasoning",reasoning:r.thinking,...r.signature?{signature:r.signature}:{}};continue}else if(fe(r,"text")&&V(r.text)){yield{type:"text",text:r.text};continue}else if(fe(r,"image_url")){if(V(r.image_url))if(r.image_url.startsWith("data:")){const s=r.image_url.match(/^data:([^;]+);base64,(.+)$/);s?yield{type:"image",data:s[2],mimeType:s[1]}:yield{type:"image",url:r.image_url}}else yield{type:"image",url:r.image_url};continue}else if(fe(r,"media")&&V(r.mimeType)&&V(r.data)){yield{type:"file",mimeType:r.mimeType,data:r.data};continue}yield{type:"non_standard",value:r}}}return Array.from(e())}const RP={translateContent:zb,translateContentChunk:zb};function Hb(t){var r;const e=[],n=(r=t.additional_kwargs)==null?void 0:r.reasoning;if(V(n)&&n.length>0&&e.push({type:"reasoning",reasoning:n}),typeof t.content=="string"){let s=t.content;const i=s.match(/<think>([\s\S]*?)<\/think>/);if(i){const a=i[1].trim();a.length>0&&e.push({type:"reasoning",reasoning:a}),s=s.replace(/<think>[\s\S]*?<\/think>/,"").trim()}s.length>0&&e.push({type:"text",text:s})}else for(const s of t.content)if(typeof s=="object"&&"type"in s&&s.type==="text"&&"text"in s&&V(s.text)){let i=s.text;const a=i.match(/<think>([\s\S]*?)<\/think>/);if(a){const o=a[1].trim();o.length>0&&e.push({type:"reasoning",reasoning:o}),i=i.replace(/<think>[\s\S]*?<\/think>/,"").trim()}i.length>0&&e.push({type:"text",text:i})}for(const s of t.tool_calls??[])e.push({type:"tool_call",id:s.id,name:s.name,args:s.args});return e}const PP={translateContent:Hb,translateContentChunk:Hb};function Vb(t){var r;const e=[],n=(r=t.additional_kwargs)==null?void 0:r.reasoning_content;if(V(n)&&n.length>0&&e.push({type:"reasoning",reasoning:n}),typeof t.content=="string")t.content.length>0&&e.push({type:"text",text:t.content});else for(const s of t.content)typeof s=="object"&&"type"in s&&s.type==="text"&&"text"in s&&V(s.text)&&e.push({type:"text",text:s.text});for(const s of t.tool_calls??[])e.push({type:"tool_call",id:s.id,name:s.name,args:s.args});return e}const NP={translateContent:Vb,translateContentChunk:Vb};function Kb(t){var s,i;const e=[],n=(s=t.additional_kwargs)==null?void 0:s.reasoning_details;let r=!1;if(Array.isArray(n)&&n.length>0)for(const a of n){if(a==null||typeof a!="object")continue;const o=a.type;if(o==="reasoning.summary"){const c=a.summary;V(c)&&c.length>0&&(e.push({type:"reasoning",reasoning:c}),r=!0)}else if(o==="reasoning.text"){const c=a.text;V(c)&&c.length>0&&(e.push({type:"reasoning",reasoning:c}),r=!0)}}if(!r){const a=(i=t.additional_kwargs)==null?void 0:i.reasoning_content;V(a)&&a.length>0&&e.push({type:"reasoning",reasoning:a})}if(typeof t.content=="string")t.content.length>0&&e.push({type:"text",text:t.content});else for(const a of t.content)typeof a=="object"&&"type"in a&&a.type==="text"&&"text"in a&&V(a.text)&&e.push({type:"text",text:a.text});for(const a of t.tool_calls??[])e.push({type:"tool_call",id:a.id,name:a.name,args:a.args});return e}const MP={translateContent:Kb,translateContentChunk:Kb};function Wb(t){var r,s;const e=[];if(Te((r=t.additional_kwargs)==null?void 0:r.reasoning)){const i=t.additional_kwargs.reasoning;if(zn(i.summary)){const a=i.summary.reduce((o,c)=>Te(c)&&V(c.text)?`${o}${c.text}`:o,"");a.length>0&&e.push({type:"reasoning",reasoning:a})}}const n=(s=t.additional_kwargs)==null?void 0:s.reasoning_content;if(V(n)&&n.length>0&&e.push({type:"reasoning",reasoning:n}),typeof t.content=="string")t.content.length>0&&e.push({type:"text",text:t.content});else for(const i of t.content)typeof i=="object"&&"type"in i&&i.type==="text"&&"text"in i&&V(i.text)&&e.push({type:"text",text:i.text});for(const i of t.tool_calls??[])e.push({type:"tool_call",id:i.id,name:i.name,args:i.args});return e}const LP={translateContent:Wb,translateContentChunk:Wb};function Zb(t){function*e(){const n=wi(()=>{var r;if(typeof t.content=="string")return t.additional_kwargs.originalTextContentBlock?[{...t.additional_kwargs.originalTextContentBlock,type:"text"}]:[{type:"text",text:t.content}];{const s=(r=t.additional_kwargs)==null?void 0:r.originalTextContentBlock;if(s!=null&&s.thoughtSignature&&!t.content.some(i=>"thoughtSignature"in i)){const i=[...t.content];for(let a=i.length-1;a>=0;a--){const o=i[a];if(o.type==="text"&&!o.thought)return o.thoughtSignature=s.thoughtSignature,i}}return t.content}});for(const r of n){const s=wi(()=>fe(r,"text")&&V(r.text)?{type:"text",text:r.text}:fe(r,"inlineData")&&Te(r.inlineData)&&V(r.inlineData.mimeType)&&V(r.inlineData.data)?{type:"file",mimeType:r.inlineData.mimeType,data:r.inlineData.data}:fe(r,"functionCall")&&Te(r.functionCall)&&V(r.functionCall.name)&&Te(r.functionCall.args)?{type:"tool_call",id:t.id,name:r.functionCall.name,args:r.functionCall.args}:fe(r,"functionResponse")?{type:"non_standard",value:r}:fe(r,"fileData")&&Te(r.fileData)&&V(r.fileData.mimeType)&&V(r.fileData.fileUri)?{type:"file",mimeType:r.fileData.mimeType,fileId:r.fileData.fileUri}:fe(r,"executableCode")?{type:"non_standard",value:r}:fe(r,"codeExecutionResult")?{type:"non_standard",value:r}:{type:"non_standard",value:r}),i=wi(()=>"thought"in r&&r.thought?{type:"reasoning",reasoning:s.type==="text"?s.text:"",reasoningContentBlock:s}:s),a={thought:r.thought,thoughtSignature:r.thoughtSignature,partMetadata:r.partMetadata,...i};for(const o in a)a[o]===void 0&&delete a[o];yield a}}return Array.from(e())}const jP={translateContent:Zb,translateContentChunk:Zb};globalThis.lc_block_translators_registry??(globalThis.lc_block_translators_registry=new Map([["anthropic",oP],["bedrock-converse",CP],["deepseek",OP],["google",jP],["google-genai",$P],["google-vertexai",RP],["groq",PP],["ollama",NP],["openai",_P],["openrouter",MP],["xai",LP]]));function PT(t){return globalThis.lc_block_translators_registry.get(t)}function NT(t,e){return Sn(t,e)??{}}function MT(t,e){const n={};return((t==null?void 0:t.audio)!==void 0||(e==null?void 0:e.audio)!==void 0)&&(n.audio=((t==null?void 0:t.audio)??0)+((e==null?void 0:e.audio)??0)),((t==null?void 0:t.image)!==void 0||(e==null?void 0:e.image)!==void 0)&&(n.image=((t==null?void 0:t.image)??0)+((e==null?void 0:e.image)??0)),((t==null?void 0:t.video)!==void 0||(e==null?void 0:e.video)!==void 0)&&(n.video=((t==null?void 0:t.video)??0)+((e==null?void 0:e.video)??0)),((t==null?void 0:t.document)!==void 0||(e==null?void 0:e.document)!==void 0)&&(n.document=((t==null?void 0:t.document)??0)+((e==null?void 0:e.document)??0)),((t==null?void 0:t.text)!==void 0||(e==null?void 0:e.text)!==void 0)&&(n.text=((t==null?void 0:t.text)??0)+((e==null?void 0:e.text)??0)),n}function DP(t,e){const n={...MT(t,e)};return((t==null?void 0:t.cache_read)!==void 0||(e==null?void 0:e.cache_read)!==void 0)&&(n.cache_read=((t==null?void 0:t.cache_read)??0)+((e==null?void 0:e.cache_read)??0)),((t==null?void 0:t.cache_creation)!==void 0||(e==null?void 0:e.cache_creation)!==void 0)&&(n.cache_creation=((t==null?void 0:t.cache_creation)??0)+((e==null?void 0:e.cache_creation)??0)),n}function UP(t,e){const n={...MT(t,e)};return((t==null?void 0:t.reasoning)!==void 0||(e==null?void 0:e.reasoning)!==void 0)&&(n.reasoning=((t==null?void 0:t.reasoning)??0)+((e==null?void 0:e.reasoning)??0)),n}function ty(t,e){return{input_tokens:((t==null?void 0:t.input_tokens)??0)+((e==null?void 0:e.input_tokens)??0),output_tokens:((t==null?void 0:t.output_tokens)??0)+((e==null?void 0:e.output_tokens)??0),total_tokens:((t==null?void 0:t.total_tokens)??0)+((e==null?void 0:e.total_tokens)??0),input_token_details:DP(t==null?void 0:t.input_token_details,e==null?void 0:e.input_token_details),output_token_details:UP(t==null?void 0:t.output_token_details,e==null?void 0:e.output_token_details)}}var De=class extends Ot{constructor(e){var r;let n;if(typeof e=="string"||Array.isArray(e))n={content:e,tool_calls:[],invalid_tool_calls:[],additional_kwargs:{}};else{n=e;const s=(r=n.additional_kwargs)==null?void 0:r.tool_calls,i=n.tool_calls;s!=null&&s.length>0&&(i===void 0||i.length===0)&&console.warn(["New LangChain packages are available that more efficiently handle",`tool calling.
|
|
13
|
-
|
|
14
|
-
Please upgrade your packages to versions that set`,"message tool calls. e.g., `pnpm install @langchain/anthropic`,","pnpm install @langchain/openai`, etc."].join(" "));try{if(s!=null&&i===void 0){const[a,o]=Q_(s);n.tool_calls=a??[],n.invalid_tool_calls=o??[]}else n.tool_calls=n.tool_calls??[],n.invalid_tool_calls=n.invalid_tool_calls??[]}catch{n.tool_calls=[],n.invalid_tool_calls=[]}if(n.response_metadata!==void 0&&"output_version"in n.response_metadata&&n.response_metadata.output_version==="v1"&&(n.contentBlocks=n.content,n.content=void 0),n.contentBlocks!==void 0){if(n.tool_calls){const o=n.tool_calls.filter(c=>{var u;return!((u=n.contentBlocks)!=null&&u.some(l=>l.type==="tool_call"&&l.id===c.id&&l.name===c.name))});n.contentBlocks.push(...o.map(c=>({type:"tool_call",id:c.id,name:c.name,args:c.args})))}const a=n.contentBlocks.filter(o=>o.type==="tool_call").filter(o=>{var c;return!((c=n.tool_calls)!=null&&c.some(u=>u.id===o.id&&u.name===o.name))});a.length>0&&(n.tool_calls=[...n.tool_calls??[],...a.map(o=>({type:"tool_call",id:o.id,name:o.name,args:o.args}))])}}super(n);m(this,"type","ai");m(this,"tool_calls",[]);m(this,"invalid_tool_calls",[]);m(this,"usage_metadata");typeof n!="string"&&(this.tool_calls=n.tool_calls??this.tool_calls,this.invalid_tool_calls=n.invalid_tool_calls??this.invalid_tool_calls),this.usage_metadata=n.usage_metadata}get lc_aliases(){return{...super.lc_aliases,tool_calls:"tool_calls",invalid_tool_calls:"invalid_tool_calls",usage_metadata:"usage_metadata"}}static lc_name(){return"AIMessage"}get contentBlocks(){if(this.response_metadata&&"output_version"in this.response_metadata&&this.response_metadata.output_version==="v1")return this.content;if(this.response_metadata&&"model_provider"in this.response_metadata&&typeof this.response_metadata.model_provider=="string"){const n=PT(this.response_metadata.model_provider);if(n)return n.translateContent(this)}const e=super.contentBlocks;if(this.tool_calls){const n=this.tool_calls.filter(r=>!e.some(s=>s.id===r.id&&s.name===r.name));e.push(...n.map(r=>({type:"tool_call",id:r.id,name:r.name,args:r.args})))}return e}get _printableFields(){return{...super._printableFields,tool_calls:this.tool_calls,invalid_tool_calls:this.invalid_tool_calls,usage_metadata:this.usage_metadata}}static isInstance(e){return super.isInstance(e)&&e.type==="ai"}};function Cr(t){return t._getType()==="ai"}function yh(t){return t._getType()==="ai"}var Ge=class extends vs{constructor(e){let n;if(typeof e=="string"||Array.isArray(e))n={content:e,tool_calls:[],invalid_tool_calls:[],tool_call_chunks:[]};else if(e.tool_call_chunks===void 0||e.tool_call_chunks.length===0)n={...e,tool_calls:e.tool_calls??[],invalid_tool_calls:[],tool_call_chunks:[],usage_metadata:e.usage_metadata!==void 0?e.usage_metadata:void 0};else{const r=DT(e.tool_call_chunks??[]);n={...e,tool_call_chunks:r.tool_call_chunks,tool_calls:r.tool_calls,invalid_tool_calls:r.invalid_tool_calls,usage_metadata:e.usage_metadata!==void 0?e.usage_metadata:void 0}}super(n);m(this,"type","ai");m(this,"tool_calls",[]);m(this,"invalid_tool_calls",[]);m(this,"tool_call_chunks",[]);m(this,"usage_metadata");this.tool_call_chunks=n.tool_call_chunks??this.tool_call_chunks,this.tool_calls=n.tool_calls??this.tool_calls,this.invalid_tool_calls=n.invalid_tool_calls??this.invalid_tool_calls,this.usage_metadata=n.usage_metadata}get lc_aliases(){return{...super.lc_aliases,tool_calls:"tool_calls",invalid_tool_calls:"invalid_tool_calls",tool_call_chunks:"tool_call_chunks",usage_metadata:"usage_metadata"}}static lc_name(){return"AIMessageChunk"}get contentBlocks(){if(this.response_metadata&&"output_version"in this.response_metadata&&this.response_metadata.output_version==="v1")return this.content;if(this.response_metadata&&"model_provider"in this.response_metadata&&typeof this.response_metadata.model_provider=="string"){const n=PT(this.response_metadata.model_provider);if(n)return n.translateContent(this)}const e=super.contentBlocks;if(this.tool_calls&&typeof this.content!="string"){const n=this.content.filter(r=>r.type==="tool_call").map(r=>r.id);for(const r of this.tool_calls)r.id&&!n.includes(r.id)&&e.push({...r,type:"tool_call",id:r.id,name:r.name,args:r.args})}return e}get _printableFields(){return{...super._printableFields,tool_calls:this.tool_calls,tool_call_chunks:this.tool_call_chunks,invalid_tool_calls:this.invalid_tool_calls,usage_metadata:this.usage_metadata}}concat(e){const n={content:zs(this.content,e.content),additional_kwargs:Sn(this.additional_kwargs,e.additional_kwargs),response_metadata:NT(this.response_metadata,e.response_metadata),tool_call_chunks:[],tool_calls:[],id:this.id??e.id};if(this.tool_call_chunks!==void 0||e.tool_call_chunks!==void 0){const s=Ro(this.tool_call_chunks,e.tool_call_chunks);s!==void 0&&s.length>0&&(n.tool_call_chunks=s)}if(this.tool_calls!==void 0||e.tool_calls!==void 0){const s=Ro(this.tool_calls,e.tool_calls);s!==void 0&&s.length>0&&(n.tool_calls=s)}(this.usage_metadata!==void 0||e.usage_metadata!==void 0)&&(n.usage_metadata=ty(this.usage_metadata,e.usage_metadata));const r=this.constructor;return new r(n)}static isInstance(e){return super.isInstance(e)&&e.type==="ai"}},Ts=class LT extends Ot{constructor(n,r){(typeof n=="string"||Array.isArray(n))&&(n={content:n,role:r});super(n);m(this,"type","generic");m(this,"role");this.role=n.role}static lc_name(){return"ChatMessage"}static _chatMessageClass(){return LT}static isInstance(n){return super.isInstance(n)&&n.type==="generic"}get _printableFields(){return{...super._printableFields,role:this.role}}},dl=class extends vs{constructor(e,n){(typeof e=="string"||Array.isArray(e))&&(e={content:e,role:n});super(e);m(this,"type","generic");m(this,"role");this.role=e.role}static lc_name(){return"ChatMessageChunk"}concat(e){const n=this.constructor;return new n({content:zs(this.content,e.content),additional_kwargs:Sn(this.additional_kwargs,e.additional_kwargs),response_metadata:Sn(this.response_metadata,e.response_metadata),role:this.role,id:this.id??e.id})}static isInstance(e){return super.isInstance(e)&&e.type==="generic"}get _printableFields(){return{...super._printableFields,role:this.role}}};function FP(t){return t._getType()==="generic"}function BP(t){return t._getType()==="generic"}var wf=class extends Ot{constructor(e){super(e);m(this,"type","function");m(this,"name");this.name=e.name}static lc_name(){return"FunctionMessage"}},hl=class extends vs{constructor(){super(...arguments);m(this,"type","function")}static lc_name(){return"FunctionMessageChunk"}concat(e){const n=this.constructor;return new n({content:zs(this.content,e.content),additional_kwargs:Sn(this.additional_kwargs,e.additional_kwargs),response_metadata:Sn(this.response_metadata,e.response_metadata),name:this.name??"",id:this.id??e.id})}};function zP(t){return t._getType()==="function"}function HP(t){return t._getType()==="function"}var Nn=class extends Ot{constructor(e){super(e);m(this,"type","human")}static lc_name(){return"HumanMessage"}static isInstance(e){return super.isInstance(e)&&e.type==="human"}},fl=class extends vs{constructor(e){super(e);m(this,"type","human")}static lc_name(){return"HumanMessageChunk"}concat(e){const n=this.constructor;return new n({content:zs(this.content,e.content),additional_kwargs:Sn(this.additional_kwargs,e.additional_kwargs),response_metadata:Sn(this.response_metadata,e.response_metadata),id:this.id??e.id})}static isInstance(e){return super.isInstance(e)&&e.type==="human"}};function VP(t){return t.getType()==="human"}function KP(t){return t.getType()==="human"}var ua=class extends Ot{constructor(e){super({...e,content:[]});m(this,"type","remove");m(this,"id");this.id=e.id}get _printableFields(){return{...super._printableFields,id:this.id}}static isInstance(e){return super.isInstance(e)&&e.type==="remove"}},lr=class jd extends Ot{constructor(n){super(n);m(this,"type","system")}static lc_name(){return"SystemMessage"}concat(n){if(typeof n=="string")return new jd({content:zs(this.content,n),additional_kwargs:this.additional_kwargs,response_metadata:this.response_metadata,id:this.id,name:this.name});if(jd.isInstance(n))return new jd({content:zs(this.content,n.content),additional_kwargs:{...this.additional_kwargs,...n.additional_kwargs},response_metadata:{...this.response_metadata,...n.response_metadata},id:this.id??n.id,name:this.name??n.name});throw new Error("Unexpected chunk type for system message")}static isInstance(n){return super.isInstance(n)&&n.type==="system"}},xi=class extends vs{constructor(e){super(e);m(this,"type","system")}static lc_name(){return"SystemMessageChunk"}concat(e){const n=this.constructor;return new n({content:zs(this.content,e.content),additional_kwargs:Sn(this.additional_kwargs,e.additional_kwargs),response_metadata:Sn(this.response_metadata,e.response_metadata),id:this.id??e.id})}static isInstance(e){return super.isInstance(e)&&e.type==="system"}};function WP(t){return t._getType()==="system"}function ZP(t){return t._getType()==="system"}function qP(t){return t.isCustomTool===!0}const jT=t=>t();function GP(t){return nu(t)?t:typeof t.id=="string"&&t.type==="function"&&typeof t.function=="object"&&t.function!==null&&"arguments"in t.function&&typeof t.function.arguments=="string"&&"name"in t.function&&typeof t.function.name=="string"?{id:t.id,args:JSON.parse(t.function.arguments),name:t.function.name,type:"tool_call"}:t}function JP(t){return typeof t=="object"&&t!=null&&t.lc===1&&Array.isArray(t.id)&&t.kwargs!=null&&typeof t.kwargs=="object"}function mp(t){let e,n;if(JP(t)){const r=t.id.at(-1);r==="HumanMessage"||r==="HumanMessageChunk"?e="user":r==="AIMessage"||r==="AIMessageChunk"?e="assistant":r==="SystemMessage"||r==="SystemMessageChunk"?e="system":r==="FunctionMessage"||r==="FunctionMessageChunk"?e="function":r==="ToolMessage"||r==="ToolMessageChunk"?e="tool":e="unknown",n=t.kwargs}else{const{type:r,...s}=t;e=r,n=s}if(e==="human"||e==="user")return new Nn(n);if(e==="ai"||e==="assistant"){const{tool_calls:r,...s}=n;if(!Array.isArray(r))return new De(n);const i=r.map(GP);return new De({...s,tool_calls:i})}else{if(e==="system")return new lr(n);if(e==="developer")return new lr({...n,additional_kwargs:{...n.additional_kwargs,__openai_role__:"developer"}});if(e==="tool"&&"tool_call_id"in n)return new fn({...n,content:n.content,tool_call_id:n.tool_call_id,name:n.name});if(e==="remove"&&"id"in n&&typeof n.id=="string")return new ua({...n,id:n.id});throw cl(new Error(`Unable to coerce message from array: only human, AI, system, developer, or tool message coercion is currently supported.
|
|
15
|
-
|
|
16
|
-
Received: ${JSON.stringify(t,null,2)}`),"MESSAGE_COERCION_FAILURE")}}function _s(t){if(typeof t=="string")return new Nn(t);if(Et(t))return t;if(Array.isArray(t)){const[e,n]=t;return mp({type:e,content:n})}else if($T(t)){const{role:e,...n}=t;return mp({...n,type:e})}else return mp(t)}function YP(t){if(typeof t=="string")return t;switch(t.type){case"text":return t.text??"";case"text-plain":return t.text??"[text-plain file]";case"image":case"image_url":return"[image]";case"audio":case"input_audio":return"[audio]";case"video":return"[video]";case"file":return"[file]";case"reasoning":case"tool_call":case"tool_call_chunk":case"invalid_tool_call":case"server_tool_call":case"server_tool_call_chunk":case"server_tool_call_result":case"non_standard":return"";default:return t.type?`[${t.type}]`:""}}function ny(t,e="Human",n="AI"){const r=[];for(const s of t){let i;if(s.type==="human")i=e;else if(s.type==="ai")i=n;else if(s.type==="system")i="System";else if(s.type==="tool")i="Tool";else if(s.type==="generic")i=s.role;else throw new Error(`Got unsupported message type: ${s.type}`);const a=s.name?`${s.name}, `:"",o=typeof s.content=="string"?s.content:Array.isArray(s.content)?s.content.map(YP).filter(Boolean).join(""):"";let c=`${i}: ${a}${o}`;if(s.type==="ai"){const u=s;u.tool_calls&&u.tool_calls.length>0?c+=JSON.stringify(u.tool_calls):u.additional_kwargs&&"function_call"in u.additional_kwargs&&(c+=JSON.stringify(u.additional_kwargs.function_call))}r.push(c)}return r.join(`
|
|
17
|
-
`)}function XP(t){if(t.data!==void 0)return t;{const e=t;return{type:e.type,data:{content:e.text,role:e.role,name:void 0,tool_call_id:void 0}}}}function ry(t){const e=XP(t);switch(e.type){case"human":return new Nn(e.data);case"ai":return new De(e.data);case"system":return new lr(e.data);case"function":if(e.data.name===void 0)throw new Error("Name must be defined for function messages");return new wf(e.data);case"tool":if(e.data.tool_call_id===void 0)throw new Error("Tool call ID must be defined for tool messages");return new fn(e.data);case"generic":if(e.data.role===void 0)throw new Error("Role must be defined for chat messages");return new Ts(e.data);default:throw new Error(`Got unexpected type: ${e.type}`)}}function QP(t){return t.map(ry)}function eN(t){return t.map(e=>e.toDict())}function wh(t){var n;const e=t._getType();if(e==="human")return new fl({...t});if(e==="ai"){let r={...t};return"tool_calls"in r&&(r={...r,tool_call_chunks:(n=r.tool_calls)==null?void 0:n.map(s=>({...s,type:"tool_call_chunk",index:void 0,args:JSON.stringify(s.args)}))}),new Ge({...r})}else{if(e==="system")return new xi({...t});if(e==="function")return new hl({...t});if(Ts.isInstance(t))return new dl({...t});throw new Error("Unknown message type.")}}function DT(t){var s,i,a;const e=t.reduce((o,c)=>{const u=o.findIndex(([l])=>"id"in c&&c.id&&"index"in c&&c.index!==void 0?c.id===l.id&&c.index===l.index:"id"in c&&c.id?c.id===l.id:"index"in c&&c.index!==void 0?c.index===l.index:!1);return u!==-1?o[u].push(c):o.push([c]),o},[]),n=[],r=[];for(const o of e){let c=null;const u=o.some(qP),l=((s=o[0])==null?void 0:s.name)??"",d=o.map(g=>g.args||"").join(""),f=u?d:d.trim(),h=f.length?f:"{}",p=((i=o.find(g=>g.id))==null?void 0:i.id)??((a=o[0])==null?void 0:a.id);if(u&&p){n.push({name:l,args:{input:f},id:p,type:"tool_call"});continue}try{if(c=$o(h),!p||c===null||typeof c!="object"||Array.isArray(c))throw new Error("Malformed tool call chunk args.");n.push({name:l,args:c,id:p,type:"tool_call"})}catch{r.push({name:l,args:h,id:p,error:"Malformed args.",type:"invalid_tool_call"})}}return{tool_call_chunks:t,tool_calls:n,invalid_tool_calls:r}}var tN="ffffffff-ffff-ffff-ffff-ffffffffffff",nN="00000000-0000-0000-0000-000000000000",rN=/^(?:[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 bf(t){return typeof t=="string"&&rN.test(t)}function bh(t){if(!bf(t))throw TypeError("Invalid UUID");let e;return Uint8Array.of((e=parseInt(t.slice(0,8),16))>>>24,e>>>16&255,e>>>8&255,e&255,(e=parseInt(t.slice(9,13),16))>>>8,e&255,(e=parseInt(t.slice(14,18),16))>>>8,e&255,(e=parseInt(t.slice(19,23),16))>>>8,e&255,(e=parseInt(t.slice(24,36),16))/1099511627776&255,e/4294967296&255,e>>>24&255,e>>>16&255,e>>>8&255,e&255)}const nn=[];for(let t=0;t<256;++t)nn.push((t+256).toString(16).slice(1));function xa(t,e=0){return(nn[t[e+0]]+nn[t[e+1]]+nn[t[e+2]]+nn[t[e+3]]+"-"+nn[t[e+4]]+nn[t[e+5]]+"-"+nn[t[e+6]]+nn[t[e+7]]+"-"+nn[t[e+8]]+nn[t[e+9]]+"-"+nn[t[e+10]]+nn[t[e+11]]+nn[t[e+12]]+nn[t[e+13]]+nn[t[e+14]]+nn[t[e+15]]).toLowerCase()}function sN(t,e=0){const n=xa(t,e);if(!bf(n))throw TypeError("Stringified UUID is invalid");return n}const iN=new Uint8Array(16);function bu(){return crypto.getRandomValues(iN)}const oc={};function UT(t,e,n){var i;let r;const s=(t==null?void 0:t._v6)??!1;if(t){const a=Object.keys(t);a.length===1&&a[0]==="_v6"&&(t=void 0)}if(t)r=qb(t.random??((i=t.rng)==null?void 0:i.call(t))??bu(),t.msecs,t.nsecs,t.clockseq,t.node,e,n);else{const a=Date.now(),o=bu();aN(oc,a,o),r=qb(o,oc.msecs,oc.nsecs,s?void 0:oc.clockseq,s?void 0:oc.node,e,n)}return e??xa(r)}function aN(t,e,n){return t.msecs??(t.msecs=-1/0),t.nsecs??(t.nsecs=0),e===t.msecs?(t.nsecs++,t.nsecs>=1e4&&(t.node=void 0,t.nsecs=0)):e>t.msecs?t.nsecs=0:e<t.msecs&&(t.node=void 0),t.node||(t.node=n.slice(10,16),t.node[0]|=1,t.clockseq=(n[8]<<8|n[9])&16383),t.msecs=e,t}function qb(t,e,n,r,s,i,a=0){if(t.length<16)throw new Error("Random bytes length must be >= 16");if(!i)i=new Uint8Array(16),a=0;else if(a<0||a+16>i.length)throw new RangeError(`UUID byte range ${a}:${a+15} is out of buffer bounds`);e??(e=Date.now()),n??(n=0),r??(r=(t[8]<<8|t[9])&16383),s??(s=t.slice(10,16)),e+=122192928e5;const o=((e&268435455)*1e4+n)%4294967296;i[a++]=o>>>24&255,i[a++]=o>>>16&255,i[a++]=o>>>8&255,i[a++]=o&255;const c=e/4294967296*1e4&268435455;i[a++]=c>>>8&255,i[a++]=c&255,i[a++]=c>>>24&15|16,i[a++]=c>>>16&255,i[a++]=r>>>8|128,i[a++]=r&255;for(let u=0;u<6;++u)i[a++]=s[u];return i}function oN(t,e,n){return!e&&!t&&crypto.randomUUID?crypto.randomUUID():cN(t,e,n)}function cN(t,e,n){var s;t=t||{};const r=t.random??((s=t.rng)==null?void 0:s.call(t))??bu();if(r.length<16)throw new Error("Random bytes length must be >= 16");if(r[6]=r[6]&15|64,r[8]=r[8]&63|128,e){if(n=n||0,n<0||n+16>e.length)throw new RangeError(`UUID byte range ${n}:${n+15} is out of buffer bounds`);for(let i=0;i<16;++i)e[n+i]=r[i];return e}return xa(r)}function uN(t,e,n,r){switch(t){case 0:return e&n^~e&r;case 1:return e^n^r;case 2:return e&n^e&r^n&r;case 3:return e^n^r}}function gp(t,e){return t<<e|t>>>32-e}function lN(t){const e=[1518500249,1859775393,2400959708,3395469782],n=[1732584193,4023233417,2562383102,271733878,3285377520],r=new Uint8Array(t.length+1);r.set(t),r[t.length]=128,t=r;const s=t.length/4+2,i=Math.ceil(s/16),a=new Array(i);for(let o=0;o<i;++o){const c=new Uint32Array(16);for(let u=0;u<16;++u)c[u]=t[o*64+u*4]<<24|t[o*64+u*4+1]<<16|t[o*64+u*4+2]<<8|t[o*64+u*4+3];a[o]=c}a[i-1][14]=(t.length-1)*8/2**32,a[i-1][14]=Math.floor(a[i-1][14]),a[i-1][15]=(t.length-1)*8&4294967295;for(let o=0;o<i;++o){const c=new Uint32Array(80);for(let p=0;p<16;++p)c[p]=a[o][p];for(let p=16;p<80;++p)c[p]=gp(c[p-3]^c[p-8]^c[p-14]^c[p-16],1);let u=n[0],l=n[1],d=n[2],f=n[3],h=n[4];for(let p=0;p<80;++p){const g=Math.floor(p/20),y=gp(u,5)+uN(g,l,d,f)+h+e[g]+c[p]>>>0;h=f,f=d,d=gp(l,30)>>>0,l=u,u=y}n[0]=n[0]+u>>>0,n[1]=n[1]+l>>>0,n[2]=n[2]+d>>>0,n[3]=n[3]+f>>>0,n[4]=n[4]+h>>>0}return Uint8Array.of(n[0]>>24,n[0]>>16,n[0]>>8,n[0],n[1]>>24,n[1]>>16,n[1]>>8,n[1],n[2]>>24,n[2]>>16,n[2]>>8,n[2],n[3]>>24,n[3]>>16,n[3]>>8,n[3],n[4]>>24,n[4]>>16,n[4]>>8,n[4])}function dN(t){t=unescape(encodeURIComponent(t));const e=new Uint8Array(t.length);for(let n=0;n<t.length;++n)e[n]=t.charCodeAt(n);return e}const hN="6ba7b810-9dad-11d1-80b4-00c04fd430c8",fN="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function pN(t,e,n,r,s,i){const a=typeof n=="string"?dN(n):n,o=typeof r=="string"?bh(r):r;if(typeof r=="string"&&(r=bh(r)),(r==null?void 0:r.length)!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let c=new Uint8Array(16+a.length);if(c.set(o),c.set(a,o.length),c=e(c),c[6]=c[6]&15|t,c[8]=c[8]&63|128,s){if(i??(i=0),i<0||i+16>s.length)throw new RangeError(`UUID byte range ${i}:${i+15} is out of buffer bounds`);for(let u=0;u<16;++u)s[i+u]=c[u];return s}return xa(c)}function sy(t,e,n,r){return pN(80,lN,t,e,n,r)}sy.DNS=hN;sy.URL=fN;function mN(t){const e=gN(typeof t=="string"?bh(t):t);return typeof t=="string"?xa(e):e}function gN(t){return Uint8Array.of((t[6]&15)<<4|t[7]>>4&15,(t[7]&15)<<4|(t[4]&240)>>4,(t[4]&15)<<4|(t[5]&240)>>4,(t[5]&15)<<4|(t[0]&240)>>4,(t[0]&15)<<4|(t[1]&240)>>4,(t[1]&15)<<4|(t[2]&240)>>4,96|t[2]&15,t[3],t[8],t[9],t[10],t[11],t[12],t[13],t[14],t[15])}function _N(t,e,n){t??(t={}),n??(n=0);let r=UT({...t,_v6:!0},new Uint8Array(16));if(r=mN(r),e){if(n<0||n+16>e.length)throw new RangeError(`UUID byte range ${n}:${n+15} is out of buffer bounds`);for(let s=0;s<16;s++)e[n+s]=r[s];return e}return xa(r)}const _p={};function yN(t,e,n){var s;let r;if(t)r=Gb(t.random??((s=t.rng)==null?void 0:s.call(t))??bu(),t.msecs,t.seq,e,n);else{const i=Date.now(),a=bu();wN(_p,i,a),r=Gb(a,_p.msecs,_p.seq,e,n)}return e??xa(r)}function wN(t,e,n){return t.msecs??(t.msecs=-1/0),t.seq??(t.seq=0),e>t.msecs?(t.seq=n[6]<<23|n[7]<<16|n[8]<<8|n[9],t.msecs=e):(t.seq=t.seq+1|0,t.seq===0&&t.msecs++),t}function Gb(t,e,n,r,s=0){if(t.length<16)throw new Error("Random bytes length must be >= 16");if(!r)r=new Uint8Array(16),s=0;else if(s<0||s+16>r.length)throw new RangeError(`UUID byte range ${s}:${s+15} is out of buffer bounds`);return e??(e=Date.now()),n??(n=t[6]*127<<24|t[7]<<16|t[8]<<8|t[9]),r[s++]=e/1099511627776&255,r[s++]=e/4294967296&255,r[s++]=e/16777216&255,r[s++]=e/65536&255,r[s++]=e/256&255,r[s++]=e&255,r[s++]=112|n>>>28&15,r[s++]=n>>>20&255,r[s++]=128|n>>>14&63,r[s++]=n>>>6&255,r[s++]=n<<2&255|t[10]&3,r[s++]=t[11],r[s++]=t[12],r[s++]=t[13],r[s++]=t[14],r[s++]=t[15],r}function bN(t){if(!bf(t))throw TypeError("Invalid UUID");return parseInt(t.slice(14,15),16)}var vN=de({MAX:()=>SN,NIL:()=>AN,parse:()=>TN,stringify:()=>EN,v1:()=>IN,v4:()=>pl,v5:()=>Xm,v6:()=>xN,v7:()=>Ps,validate:()=>ru,version:()=>kN});const SN=tN,AN=nN,TN=bh,EN=sN,IN=UT,pl=oN,Xm=sy,xN=_N,Ps=yN,ru=bf,kN=bN;var yp={},CN=de({getEnv:()=>iy,getEnvironmentVariable:()=>Mt,getRuntimeEnvironment:()=>VT,isBrowser:()=>FT,isDeno:()=>vf,isJsDom:()=>zT,isNode:()=>HT,isWebWorker:()=>BT});const FT=()=>typeof window<"u"&&typeof window.document<"u",BT=()=>typeof globalThis=="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope",zT=()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&navigator.userAgent.includes("jsdom"),vf=()=>typeof Deno<"u",HT=()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!vf(),iy=()=>{let t;return FT()?t="browser":HT()?t="node":BT()?t="webworker":zT()?t="jsdom":vf()?t="deno":t="other",t};let wp;function VT(){return wp===void 0&&(wp={library:"langchain-js",runtime:iy()}),wp}function Mt(t){try{return typeof process<"u"?yp==null?void 0:yp[t]:vf()?Deno==null?void 0:Deno.env.get(t):void 0}catch{return}}var ON=de({BaseCallbackHandler:()=>qs,callbackHandlerPrefersChatModelStreamEvents:()=>KT,callbackHandlerPrefersStreaming:()=>ay,isBaseCallbackHandler:()=>WT}),$N=class{};function ay(t){return"lc_prefer_streaming"in t&&t.lc_prefer_streaming}function KT(t){return"lc_prefer_chat_model_stream_events"in t&&t.lc_prefer_chat_model_stream_events}var qs=class extends $N{constructor(e){super();m(this,"lc_serializable",!1);m(this,"lc_kwargs");m(this,"ignoreLLM",!1);m(this,"ignoreChain",!1);m(this,"ignoreAgent",!1);m(this,"ignoreRetriever",!1);m(this,"ignoreCustomEvent",!1);m(this,"raiseError",!1);m(this,"awaitHandlers",Mt("LANGCHAIN_CALLBACKS_BACKGROUND")==="false");this.lc_kwargs=e||{},e&&(this.ignoreLLM=e.ignoreLLM??this.ignoreLLM,this.ignoreChain=e.ignoreChain??this.ignoreChain,this.ignoreAgent=e.ignoreAgent??this.ignoreAgent,this.ignoreRetriever=e.ignoreRetriever??this.ignoreRetriever,this.ignoreCustomEvent=e.ignoreCustomEvent??this.ignoreCustomEvent,this.raiseError=e.raiseError??this.raiseError,this.awaitHandlers=this.raiseError||(e._awaitHandler??this.awaitHandlers))}get lc_namespace(){return["langchain_core","callbacks",this.name]}get lc_secrets(){}get lc_attributes(){}get lc_aliases(){}get lc_serializable_keys(){}static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,yf(this.constructor)]}copy(){return new this.constructor(this)}toJSON(){return xr.prototype.toJSON.call(this)}toJSONNotImplemented(){return xr.prototype.toJSONNotImplemented.call(this)}static fromMethods(e){class n extends qs{constructor(){super();m(this,"name",Ps());Object.assign(this,e)}}return new n}};const WT=t=>{const e=t;return e!==void 0&&typeof e.copy=="function"&&typeof e.name=="string"&&typeof e.awaitHandlers=="boolean"},RN=/^(?:[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 PN(t){return typeof t=="string"&&RN.test(t)}function Jb(t){if(!PN(t))throw TypeError("Invalid UUID");let e;return Uint8Array.of((e=parseInt(t.slice(0,8),16))>>>24,e>>>16&255,e>>>8&255,e&255,(e=parseInt(t.slice(9,13),16))>>>8,e&255,(e=parseInt(t.slice(14,18),16))>>>8,e&255,(e=parseInt(t.slice(19,23),16))>>>8,e&255,(e=parseInt(t.slice(24,36),16))/1099511627776&255,e/4294967296&255,e>>>24&255,e>>>16&255,e>>>8&255,e&255)}const rn=[];for(let t=0;t<256;++t)rn.push((t+256).toString(16).slice(1));function oy(t,e=0){return(rn[t[e+0]]+rn[t[e+1]]+rn[t[e+2]]+rn[t[e+3]]+"-"+rn[t[e+4]]+rn[t[e+5]]+"-"+rn[t[e+6]]+rn[t[e+7]]+"-"+rn[t[e+8]]+rn[t[e+9]]+"-"+rn[t[e+10]]+rn[t[e+11]]+rn[t[e+12]]+rn[t[e+13]]+rn[t[e+14]]+rn[t[e+15]]).toLowerCase()}const NN=new Uint8Array(16);function Qm(){return crypto.getRandomValues(NN)}function cc(t,e,n){return crypto.randomUUID?crypto.randomUUID():MN(t)}function MN(t,e,n){var s;t=t||{};const r=t.random??((s=t.rng)==null?void 0:s.call(t))??Qm();if(r.length<16)throw new Error("Random bytes length must be >= 16");return r[6]=r[6]&15|64,r[8]=r[8]&63|128,oy(r)}function LN(t,e,n,r){switch(t){case 0:return e&n^~e&r;case 1:return e^n^r;case 2:return e&n^e&r^n&r;case 3:return e^n^r}}function bp(t,e){return t<<e|t>>>32-e}function jN(t){const e=[1518500249,1859775393,2400959708,3395469782],n=[1732584193,4023233417,2562383102,271733878,3285377520],r=new Uint8Array(t.length+1);r.set(t),r[t.length]=128,t=r;const s=t.length/4+2,i=Math.ceil(s/16),a=new Array(i);for(let o=0;o<i;++o){const c=new Uint32Array(16);for(let u=0;u<16;++u)c[u]=t[o*64+u*4]<<24|t[o*64+u*4+1]<<16|t[o*64+u*4+2]<<8|t[o*64+u*4+3];a[o]=c}a[i-1][14]=(t.length-1)*8/2**32,a[i-1][14]=Math.floor(a[i-1][14]),a[i-1][15]=(t.length-1)*8&4294967295;for(let o=0;o<i;++o){const c=new Uint32Array(80);for(let p=0;p<16;++p)c[p]=a[o][p];for(let p=16;p<80;++p)c[p]=bp(c[p-3]^c[p-8]^c[p-14]^c[p-16],1);let u=n[0],l=n[1],d=n[2],f=n[3],h=n[4];for(let p=0;p<80;++p){const g=Math.floor(p/20),y=bp(u,5)+LN(g,l,d,f)+h+e[g]+c[p]>>>0;h=f,f=d,d=bp(l,30)>>>0,l=u,u=y}n[0]=n[0]+u>>>0,n[1]=n[1]+l>>>0,n[2]=n[2]+d>>>0,n[3]=n[3]+f>>>0,n[4]=n[4]+h>>>0}return Uint8Array.of(n[0]>>24,n[0]>>16,n[0]>>8,n[0],n[1]>>24,n[1]>>16,n[1]>>8,n[1],n[2]>>24,n[2]>>16,n[2]>>8,n[2],n[3]>>24,n[3]>>16,n[3]>>8,n[3],n[4]>>24,n[4]>>16,n[4]>>8,n[4])}function DN(t){t=unescape(encodeURIComponent(t));const e=new Uint8Array(t.length);for(let n=0;n<t.length;++n)e[n]=t.charCodeAt(n);return e}const UN="6ba7b810-9dad-11d1-80b4-00c04fd430c8",FN="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function BN(t,e,n,r,s,i){const a=typeof n=="string"?DN(n):n,o=typeof r=="string"?Jb(r):r;if(typeof r=="string"&&(r=Jb(r)),(r==null?void 0:r.length)!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let c=new Uint8Array(16+a.length);if(c.set(o),c.set(a,o.length),c=e(c),c[6]=c[6]&15|t,c[8]=c[8]&63|128,s){if(i??(i=0),i<0||i+16>s.length)throw new RangeError(`UUID byte range ${i}:${i+15} is out of buffer bounds`);for(let u=0;u<16;++u)s[i+u]=c[u];return s}return oy(c)}function cy(t,e,n,r){return BN(80,jN,t,e,n,r)}cy.DNS=UN;cy.URL=FN;const vp={};function ZT(t,e,n){var s;let r;if(t)r=Yb(t.random??((s=t.rng)==null?void 0:s.call(t))??Qm(),t.msecs,t.seq,e,n);else{const i=Date.now(),a=Qm();zN(vp,i,a),r=Yb(a,vp.msecs,vp.seq,e,n)}return e??oy(r)}function zN(t,e,n){return t.msecs??(t.msecs=-1/0),t.seq??(t.seq=0),e>t.msecs?(t.seq=n[6]<<23|n[7]<<16|n[8]<<8|n[9],t.msecs=e):(t.seq=t.seq+1|0,t.seq===0&&t.msecs++),t}function Yb(t,e,n,r,s=0){if(t.length<16)throw new Error("Random bytes length must be >= 16");if(!r)r=new Uint8Array(16),s=0;else if(s<0||s+16>r.length)throw new RangeError(`UUID byte range ${s}:${s+15} is out of buffer bounds`);return e??(e=Date.now()),n??(n=t[6]*127<<24|t[7]<<16|t[8]<<8|t[9]),r[s++]=e/1099511627776&255,r[s++]=e/4294967296&255,r[s++]=e/16777216&255,r[s++]=e/65536&255,r[s++]=e/256&255,r[s++]=e&255,r[s++]=112|n>>>28&15,r[s++]=n>>>20&255,r[s++]=128|n>>>14&63,r[s++]=n>>>6&255,r[s++]=n<<2&255|t[10]&3,r[s++]=t[11],r[s++]=t[12],r[s++]=t[13],r[s++]=t[14],r[s++]=t[15],r}const HN="gen_ai.operation.name",VN="gen_ai.system",Xb="gen_ai.request.model",KN="gen_ai.response.model",Qb="gen_ai.usage.input_tokens",e0="gen_ai.usage.output_tokens",t0="gen_ai.usage.total_tokens",WN="gen_ai.request.max_tokens",ZN="gen_ai.request.temperature",qN="gen_ai.request.top_p",GN="gen_ai.request.frequency_penalty",JN="gen_ai.request.presence_penalty",YN="gen_ai.response.finish_reasons",XN="gen_ai.prompt",QN="gen_ai.completion",e2="gen_ai.request.extra_query",t2="gen_ai.request.extra_body",n2="gen_ai.serialized.name",r2="gen_ai.serialized.signature",s2="gen_ai.serialized.doc",i2="gen_ai.response.id",a2="gen_ai.response.service_tier",o2="gen_ai.response.system_fingerprint",c2="gen_ai.usage.input_token_details",u2="gen_ai.usage.output_token_details",l2="langsmith.trace.session_id",d2="langsmith.trace.session_name",h2="langsmith.span.kind",f2="langsmith.trace.name",p2="langsmith.metadata",n0="langsmith.span.tags",m2="langsmith.request.streaming",g2="langsmith.request.headers",r0="langsmith.usage_metadata",_2=(...t)=>fetch(...t),qT=Symbol.for("ls:fetch_implementation"),y2=()=>globalThis[qT]===void 0,w2=t=>async(...e)=>{if(t||Pt("DEBUG")==="true"){const[r,s]=e;console.log(`→ ${(s==null?void 0:s.method)||"GET"} ${r}`)}const n=await(globalThis[qT]??_2)(...e);return(t||Pt("DEBUG")==="true")&&console.log(`← ${n.status} ${n.statusText} ${n.url}`),n},GT=()=>Pt("PROJECT")??cr("LANGCHAIN_SESSION")??"default",s0={};function Dd(t){s0[t]||(console.warn(t),s0[t]=!0)}const H=t=>BigInt(t),JT=H("0x9E3779B1"),YT=H("0x85EBCA77"),b2=H("0xC2B2AE3D"),ki=H("0x9E3779B185EBCA87"),_a=H("0xC2B2AE3D27D4EB4F"),XT=H("0x165667B19E3779F9"),uy=H("0x85EBCA77C2B2AE63"),v2=H("0x27D4EB2F165667C5"),S2=H("0x165667919E3779F9"),A2=H("0x9FB21C651E98DF25");function T2(t){const e=new Uint8Array(t.length/2);for(let n=0;n<t.length;n+=2)e[n/2]=parseInt(t.substring(n,n+2),16);return e}const is=T2("b8fe6c3923a44bbe7c01812cf721ad1cded46de9839097db7240a4a4b7b3671fcb79e64eccc0e578825ad07dccff7221b8084674f743248ee03590e6813a264c3c2852bb91c300cb88d0658b1b532ea371644897a20df94e3819ef46a9deacd8a8fa763fe39c343ff9dcbbc7c70b4f1d8a51e04bcdb45931c89f7ec9d9787364eac5ac8334d3ebc3c581a0fffa1363eb170ddd51b7f0da49d316552629d4689e2b16be587d47a1fc8ff8b8d17ad031ce45cb3a8f95160428afd7fbcabb4b407e"),ho=(H(1)<<H(128))-H(1),Le=(H(1)<<H(64))-H(1),vh=(H(1)<<H(32))-H(1),Ns=64,QT=Ns/8,E2=8,zl=4;function pt(t,e=0){return new Uint8Array(t.buffer,t.byteOffset+e,t.length-e)}function yt(t,e=0){return new DataView(t.buffer,t.byteOffset+e).getBigUint64(0,!0)}function to(t,e=0){return new DataView(t.buffer,t.byteOffset+e).getUint32(0,!0)}function Sp(t,e=0){return t[e]}const I2=t=>(t&H(255))<<H(56)|(t&H(65280))<<H(40)|(t&H(16711680))<<H(24)|(t&H(4278190080))<<H(8)|(t&H(0xff00000000))>>H(8)|(t&H(0xff0000000000))>>H(24)|(t&H(0xff000000000000))>>H(40)|(t&H(0xff00000000000000))>>H(56),x2=t=>(t=(t&H(65535))<<H(16)|(t&H(4294901760))>>H(16),t=(t&H(16711935))<<H(8)|(t&H(4278255360))>>H(8),t),k2=(t,e)=>(t&vh)*(e&vh)&Le,No=t=>{if(!t)throw new Error("Assert failed")};function C2(t,e){return(t<<e|t>>H(32)-e)&vh}function eE(t,e,n){for(let r=0;r<QT;r++){const s=yt(e,r*8),i=s^yt(n,r*8);t[r^1]+=s,t[r]+=k2(i,i>>H(32))}return t}function i0(t,e,n,r){for(let s=0;s<r;s++)eE(t,pt(e,s*Ns),pt(n,s*8));return t}function O2(t,e){for(let n=0;n<QT;n++){const r=yt(e,n*8);let s=t[n];s=eg(s,H(47)),s^=r,s*=JT,t[n]=s&Le}return t}function Hl(t,e){return tE(t[0]^yt(e,0),t[1]^yt(e,E2))}function a0(t,e,n){let r=n;return r+=Hl(t.slice(0),pt(e,0*zl)),r+=Hl(t.slice(2),pt(e,4*zl)),r+=Hl(t.slice(4),pt(e,8*zl)),r+=Hl(t.slice(6),pt(e,12*zl)),fs(r&Le)}function $2(t,e,n,r,s){const i=Math.floor((n.byteLength-Ns)/8),a=Ns*i,o=Math.floor((e.byteLength-1)/a);for(let c=0;c<o;c++)t=i0(t,pt(e,c*a),n,i),t=s(t,pt(n,n.byteLength-Ns));{const c=Math.floor((e.byteLength-1-a*o)/Ns);t=i0(t,pt(e,o*a),n,c),t=r(t,pt(e,e.byteLength-Ns),pt(n,n.byteLength-Ns-7))}return t}function R2(t,e,n){let r=new BigUint64Array([b2,ki,_a,XT,uy,YT,v2,JT]);No(t.length>128),r=$2(r,t,e,eE,O2),No(r.length*8==64);{const s=a0(r,pt(e,11),H(t.byteLength)*ki&Le);return a0(r,pt(e,e.byteLength-Ns-11),~(H(t.byteLength)*_a)&Le)<<H(64)|s}}function tE(t,e){const n=t*e&ho;return n&Le^n>>H(64)}function o0(t,e,n){return tE((yt(t,0)^yt(e,0)+n)&Le,(yt(t,8)^yt(e,8)-n)&Le)}function Ud(t,e,n,r,s){let i=t&Le,a=t>>H(64)&Le;return i+=o0(e,r,s),i^=yt(n,0)+yt(n,8),i&=Le,a+=o0(n,pt(r,16),s),a^=yt(e,0)+yt(e,8),a&=Le,a<<H(64)|i}function fs(t){return t^=t>>H(37),t*=S2,t&=Le,t^=t>>H(32),t}function Sh(t){return t^=t>>H(33),t*=_a,t&=Le,t^=t>>H(29),t*=XT,t&=Le,t^=t>>H(32),t}function P2(t,e,n){const r=t.byteLength;No(r>0&&r<=3);const s=H(Sp(t,r-1))|H(r<<8)|H(Sp(t,0)<<16)|H(Sp(t,r>>1)<<24),i=(H(to(e,0))^H(to(e,4)))+n,a=(s^i)&Le,o=(H(to(e,8))^H(to(e,12)))-n,c=(C2(x2(s),H(13))^o)&Le;return(Sh(c)&Le)<<H(64)|Sh(a)}function eg(t,e){return t^t>>e}function N2(t,e,n){const r=t.byteLength;No(r>=4&&r<=8);{const s=to(t,0),i=to(t,r-4),a=H(s)|H(i)<<H(32),o=(yt(e,16)^yt(e,24))+n&Le;let u=(a^o)*(ki+(H(r)<<H(2)))&ho;return u+=(u&Le)<<H(65),u&=ho,u^=u>>H(67),eg(eg(u&Le,H(35))*A2&Le,H(28))|fs(u>>H(64))<<H(64)}}function M2(t,e,n){const r=t.byteLength;No(r>=9&&r<=16);{const s=(yt(e,32)^yt(e,40))+n&Le,i=(yt(e,48)^yt(e,56))-n&Le,a=yt(t);let o=yt(t,r-8),c=(a^o^s)*ki;const u=(c&Le)+(H(r-1)<<H(54));c=c&(ho^Le)|u,o^=i,c+=o+(o&vh)*(YT-H(1))<<H(64),c&=ho,c^=I2(c>>H(64));let l=(c&Le)*_a;return l+=(c>>H(64))*_a<<H(64),l&=ho,fs(l&Le)|fs(l>>H(64))<<H(64)}}function L2(t,e){const n=t.byteLength;return No(n<=16),n>8?M2(t,is,e):n>=4?N2(t,is,e):n>0?P2(t,is,e):Sh(e^yt(is,64)^yt(is,72))|Sh(e^yt(is,80)^yt(is,88))<<H(64)}function tg(t){return~t+H(1)&Le}function j2(t,e,n){let r=H(t.byteLength)*ki&Le,s=H(t.byteLength-1)/H(32);for(;s>=0;){const o=Number(s);r=Ud(r,pt(t,16*o),pt(t,t.byteLength-16*(o+1)),pt(e,32*o),n),s--}let i=r+(r>>H(64))&Le;i=fs(i);let a=(r&Le)*ki+(r>>H(64))*uy+(H(t.byteLength)-n&Le)*_a;return a&=Le,a=tg(fs(a)),i|a<<H(64)}function D2(t,e,n){let r=H(t.byteLength)*ki&Le;for(let a=32;a<160;a+=32)r=Ud(r,pt(t,a-32),pt(t,a-16),pt(e,a-32),n);r=fs(r&Le)|fs(r>>H(64))<<H(64);for(let a=160;a<=t.byteLength;a+=32)r=Ud(r,pt(t,a-32),pt(t,a-16),pt(e,3+a-160),n);r=Ud(r,pt(t,t.byteLength-16),pt(t,t.byteLength-32),pt(e,103),tg(n));let s=r+(r>>H(64))&Le;s=fs(s);let i=(r&Le)*ki+(r>>H(64))*uy+(H(t.byteLength)-n&Le)*_a;return i&=Le,i=tg(fs(i)),s|i<<H(64)}function U2(t,e=H(0)){const n=t.byteLength;return n<=16?L2(t,e):n<=128?j2(t,is,e):n<=240?D2(t,is,e):R2(t,is)}function F2(t){const e=new Uint8Array(16),n=new DataView(e.buffer),r=t&Le,s=t>>H(64);return n.setBigUint64(0,s,!1),n.setBigUint64(8,r,!1),e}const nE=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Ne(t,e){if(!nE.test(t)){const n=e!==void 0?`Invalid UUID for ${e}: ${t}`:`Invalid UUID: ${t}`;throw new Error(n)}return t}function B2(t){const e=typeof t=="string"?Date.parse(t):t;return ZT({msecs:e,seq:0})}function z2(t){if(!nE.test(t))return null;const e=t[14];return parseInt(e,16)}function H2(t){const e=t.replace(/-/g,""),n=new Uint8Array(16);for(let r=0;r<16;r++)n[r]=parseInt(e.slice(r*2,r*2+2),16);return n}function V2(t){const e=Array.from(t).map(n=>n.toString(16).padStart(2,"0")).join("");return`${e.slice(0,8)}-${e.slice(8,12)}-${e.slice(12,16)}-${e.slice(16,20)}-${e.slice(20)}`}const K2=new TextEncoder;function W2(t){const e=K2.encode(t),n=U2(e);return F2(n)}function Vl(t,e){const n=`${t}:${e}`,r=W2(n),s=new Uint8Array(16);if(z2(t)===7){const a=H2(t);s.set(a.slice(0,6),0)}else{const a=Date.now();s[0]=a/1099511627776&255,s[1]=a/4294967296&255,s[2]=a/16777216&255,s[3]=a/65536&255,s[4]=a/256&255,s[5]=a&255}return s[6]=112|r[0]&15,s[7]=r[1],s[8]=128|r[2]&63,s.set(r.slice(3,10),9),V2(s)}const ya={join:(...t)=>t.join("/"),dirname:t=>t.split("/").slice(0,-1).join("/")};async function rE(t){}async function ly(t,e){}async function Z2(t){return[]}async function q2(t){return{size:0}}function sE(t){return""}async function G2(t){}async function ng(t){}function J2(t,e){return e===null?!1:Date.now()-t.createdAt>e*1e3}class Y2{constructor(e={}){Object.defineProperty(this,"cache",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"ttlSeconds",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"refreshIntervalSeconds",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"refreshTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_metrics",{enumerable:!0,configurable:!0,writable:!0,value:{hits:0,misses:0,refreshes:0,refreshErrors:0}}),this.configure(e)}get metrics(){return{...this._metrics}}get totalRequests(){return this._metrics.hits+this._metrics.misses}get hitRate(){const e=this.totalRequests;return e>0?this._metrics.hits/e:0}resetMetrics(){this._metrics={hits:0,misses:0,refreshes:0,refreshErrors:0}}get(e,n){if(this.maxSize===0)return;const r=this.cache.get(e);if(!r){this._metrics.misses+=1;return}return this.cache.delete(e),this.cache.set(e,{...r,refreshFunc:n}),this._metrics.hits+=1,r.value}set(e,n,r){if(this.maxSize===0)return;if(this.refreshTimer===void 0&&this.startRefreshLoop(),!this.cache.has(e)&&this.cache.size>=this.maxSize){const i=this.cache.keys().next().value;i!==void 0&&this.cache.delete(i)}const s={value:n,createdAt:Date.now(),refreshFunc:r};this.cache.delete(e),this.cache.set(e,s)}invalidate(e){this.cache.delete(e)}clear(){this.cache.clear()}get size(){return this.cache.size}stop(){this.refreshTimer&&(clearInterval(this.refreshTimer),this.refreshTimer=void 0)}dump(e){const n={};for(const[s,i]of this.cache.entries())n[s]=i.value;ya.dirname(e);const r=`${e}.tmp`;try{JSON.stringify({entries:n},null,2)}catch(s){throw s}}load(e){return 0}startRefreshLoop(){this.stop(),this.ttlSeconds!==null&&(this.refreshTimer=setInterval(()=>{this.refreshStaleEntries().catch(e=>{console.warn("Unexpected error in cache refresh loop:",e)})},this.refreshIntervalSeconds*1e3),this.refreshTimer.unref&&this.refreshTimer.unref())}getStaleEntries(){const e=[];for(const[n,r]of this.cache.entries())J2(r,this.ttlSeconds)&&e.push([n,r]);return e}async refreshStaleEntries(){const e=this.getStaleEntries();if(e.length!==0){for(const[n,r]of e)if(r.refreshFunc!==void 0)try{const s=await r.refreshFunc();this.set(n,s,r.refreshFunc),this._metrics.refreshes+=1}catch(s){this._metrics.refreshErrors+=1,console.warn(`Failed to refresh cache entry ${n}:`,s)}}}configure(e){this.stop(),this.refreshIntervalSeconds=e.refreshIntervalSeconds??60,this.maxSize=e.maxSize??100,this.ttlSeconds=e.ttlSeconds??5*60}}const c0=new Y2,iE="0.7.6";var su={};let es;const X2=()=>typeof window<"u"&&typeof window.document<"u",Q2=()=>typeof globalThis=="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope",eM=()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&navigator.userAgent.includes("jsdom"),aE=()=>typeof Deno<"u",tM=()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!aE(),dy=()=>es||(typeof Bun<"u"?es="bun":X2()?es="browser":tM()?es="node":Q2()?es="webworker":eM()?es="jsdom":aE()?es="deno":es="other",es);let Ap;function oE(){if(Ap===void 0){const t=dy(),e=rM();Ap={library:"langsmith",runtime:t,sdk:"langsmith-js",sdk_version:iE,...e}}return Ap}function cE(){const t=nM(),e={},n=["LANGCHAIN_API_KEY","LANGCHAIN_ENDPOINT","LANGCHAIN_TRACING_V2","LANGCHAIN_PROJECT","LANGCHAIN_SESSION","LANGSMITH_API_KEY","LANGSMITH_ENDPOINT","LANGSMITH_TRACING_V2","LANGSMITH_CONFIG_FILE","LANGSMITH_PROJECT","LANGSMITH_SESSION"];for(const[r,s]of Object.entries(t))typeof s=="string"&&!n.includes(r)&&!r.toLowerCase().includes("key")&&!r.toLowerCase().includes("secret")&&!r.toLowerCase().includes("token")&&(r==="LANGCHAIN_REVISION_ID"?e.revision_id=s:e[r]=s);return e}function nM(){const t={};try{if(typeof process<"u"&&su)for(const[e,n]of Object.entries(su))(e.startsWith("LANGCHAIN_")||e.startsWith("LANGSMITH_"))&&n!=null&&((e.toLowerCase().includes("key")||e.toLowerCase().includes("secret")||e.toLowerCase().includes("token"))&&typeof n=="string"?t[e]=n.slice(0,2)+"*".repeat(n.length-4)+n.slice(-2):t[e]=n)}catch{}return t}function cr(t){try{return typeof process<"u"?su==null?void 0:su[t]:void 0}catch{return}}function Pt(t){return cr(`LANGSMITH_${t}`)||cr(`LANGCHAIN_${t}`)}let Tp;function rM(){if(Tp!==void 0)return Tp;const t=["VERCEL_GIT_COMMIT_SHA","NEXT_PUBLIC_VERCEL_GIT_COMMIT_SHA","COMMIT_REF","RENDER_GIT_COMMIT","CI_COMMIT_SHA","CIRCLE_SHA1","CF_PAGES_COMMIT_SHA","REACT_APP_GIT_SHA","SOURCE_VERSION","GITHUB_SHA","TRAVIS_COMMIT","GIT_COMMIT","BUILD_VCS_NUMBER","bamboo_planRepository_revision","Build.SourceVersion","BITBUCKET_COMMIT","DRONE_COMMIT_SHA","SEMAPHORE_GIT_SHA","BUILDKITE_COMMIT"],e={};for(const n of t){const r=cr(n);r!==void 0&&(e[n]=r)}return Tp=e,e}function u0(){return cr("OTEL_ENABLED")==="true"||Pt("OTEL_ENABLED")==="true"}const l0=new Set(["langsmith","otel"]);function uE(t){if(t!==void 0)return t;const e=Pt("TRACING_MODE");if(e!==void 0&&e!==""){const n=e.toLowerCase();if(!l0.has(n))throw new Error(`Invalid LANGSMITH_TRACING_MODE=${JSON.stringify(e)}. Must be one of: ${[...l0].sort().join(", ")}`);return u0()&&console.warn("Both LANGSMITH_TRACING_MODE and the legacy OTEL_ENABLED / LANGSMITH_OTEL_ENABLED env vars are set. LANGSMITH_TRACING_MODE takes precedence."),n}return u0()?"otel":"langsmith"}class sM{constructor(){Object.defineProperty(this,"hasWarned",{enumerable:!0,configurable:!0,writable:!0,value:!1})}startActiveSpan(e,...n){!this.hasWarned&&uE()==="otel"&&(console.warn('OTel tracing mode is active (via LANGSMITH_TRACING_MODE, OTEL_ENABLED, or LANGSMITH_OTEL_ENABLED), but the required OTEL instances have not been initialized. Please add:\n```\nimport { initializeOTEL } from "langsmith/experimental/otel/setup";\ninitializeOTEL();\n```\nat the beginning of your code.'),this.hasWarned=!0);let r;if(n.length===1&&typeof n[0]=="function"?r=n[0]:n.length===2&&typeof n[1]=="function"?r=n[1]:n.length===3&&typeof n[2]=="function"&&(r=n[2]),typeof r=="function")return r()}}class iM{constructor(){Object.defineProperty(this,"mockTracer",{enumerable:!0,configurable:!0,writable:!0,value:new sM})}getTracer(e,n){return this.mockTracer}getActiveSpan(){}setSpan(e,n){return e}getSpan(e){}setSpanContext(e,n){return e}getTracerProvider(){}setGlobalTracerProvider(e){return!1}}class aM{active(){return{}}with(e,n){return n()}}const Ep=Symbol.for("ls:otel_trace"),Ip=Symbol.for("ls:otel_context"),d0=Symbol.for("ls:otel_get_default_otlp_tracer_provider"),oM=new iM,cM=new aM;class uM{getTraceInstance(){return globalThis[Ep]??oM}getContextInstance(){return globalThis[Ip]??cM}initializeGlobalInstances(e){globalThis[Ep]===void 0&&(globalThis[Ep]=e.trace),globalThis[Ip]===void 0&&(globalThis[Ip]=e.context)}setDefaultOTLPTracerComponents(e){globalThis[d0]=e}getDefaultOTLPTracerComponents(){return globalThis[d0]??void 0}}const hy=new uM;function lE(){return hy.getTraceInstance()}function lM(){return hy.getContextInstance()}function dM(){return hy.getDefaultOTLPTracerComponents()}const hM={llm:"chat",tool:"execute_tool",retriever:"embeddings",embedding:"embeddings",prompt:"chat"};function fM(t){return hM[t]||t}function pM(t){return typeof t=="string"||typeof t=="number"||typeof t=="boolean"}class mM{constructor(){Object.defineProperty(this,"spans",{enumerable:!0,configurable:!0,writable:!0,value:new Map})}exportBatch(e,n){for(const r of e)try{if(!r.run)continue;if(r.operation==="post"){const s=this.createSpanForRun(r,r.run,n.get(r.id));s&&!r.run.end_time&&this.spans.set(r.id,s)}else this.updateSpanForRun(r,r.run)}catch(s){console.error(`Error processing operation ${r.id}:`,s)}}createSpanForRun(e,n,r){const s=r&&lE().getSpan(r);if(s)try{return this.finishSpanSetup(s,n,e)}catch(i){console.error(`Failed to create span for run ${e.id}:`,i);return}}finishSpanSetup(e,n,r){return this.setSpanAttributes(e,n,r),n.error?(e.setStatus({code:2}),e.recordException(new Error(n.error))):e.setStatus({code:1}),n.end_time&&e.end(new Date(n.end_time)),e}updateSpanForRun(e,n){try{const r=this.spans.get(e.id);if(!r){console.debug(`No span found for run ${e.id} during update`);return}this.setSpanAttributes(r,n,e),n.error?(r.setStatus({code:2}),r.recordException(new Error(n.error))):r.setStatus({code:1});const s=n.end_time;s&&(r.end(new Date(s)),this.spans.delete(e.id))}catch(r){console.error(`Failed to update span for run ${e.id}:`,r)}}extractModelName(e){var n;if((n=e.extra)!=null&&n.metadata){const r=e.extra.metadata;if(r.ls_model_name)return r.ls_model_name;if(r.invocation_params){const s=r.invocation_params;if(s.model)return s.model;if(s.model_name)return s.model_name}}}setSpanAttributes(e,n,r){var o,c,u;if("run_type"in n&&n.run_type){e.setAttribute(h2,n.run_type);const l=fM(n.run_type||"chain");e.setAttribute(HN,l)}"name"in n&&n.name&&e.setAttribute(f2,n.name),"session_id"in n&&n.session_id&&e.setAttribute(l2,n.session_id),"session_name"in n&&n.session_name&&e.setAttribute(d2,n.session_name),this.setGenAiSystem(e,n);const s=this.extractModelName(n);s&&e.setAttribute(Xb,s),(c=(o=n.extra)==null?void 0:o.metadata)!=null&&c.usage_metadata&&typeof n.extra.metadata.usage_metadata=="object"&&e.setAttribute(r0,JSON.stringify(n.extra.metadata.usage_metadata)),"prompt_tokens"in n&&typeof n.prompt_tokens=="number"&&e.setAttribute(Qb,n.prompt_tokens),"completion_tokens"in n&&typeof n.completion_tokens=="number"&&e.setAttribute(e0,n.completion_tokens),"total_tokens"in n&&typeof n.total_tokens=="number"&&e.setAttribute(t0,n.total_tokens),this.setInvocationParameters(e,n);const i=((u=n.extra)==null?void 0:u.metadata)||{};for(const[l,d]of Object.entries(i))d!=null&&e.setAttribute(`${p2}.${l}`,pM(d)?String(d):JSON.stringify(d));const a=n.tags;if(a&&Array.isArray(a)?e.setAttribute(n0,a.join(", ")):a&&e.setAttribute(n0,String(a)),"serialized"in n&&typeof n.serialized=="object"){const l=n.serialized;l.name&&e.setAttribute(n2,String(l.name)),l.signature&&e.setAttribute(r2,String(l.signature)),l.doc&&e.setAttribute(s2,String(l.doc))}this.setIOAttributes(e,r)}setGenAiSystem(e,n){let r="langchain";const s=this.extractModelName(n);if(s){const i=s.toLowerCase();i.includes("anthropic")||i.startsWith("claude")?r="anthropic":i.includes("bedrock")?r="aws.bedrock":i.includes("azure")&&i.includes("openai")?r="az.ai.openai":i.includes("azure")&&i.includes("inference")?r="az.ai.inference":i.includes("cohere")?r="cohere":i.includes("deepseek")?r="deepseek":i.includes("gemini")?r="gemini":i.includes("groq")?r="groq":i.includes("watson")||i.includes("ibm")?r="ibm.watsonx.ai":i.includes("mistral")?r="mistral_ai":i.includes("gpt")||i.includes("openai")?r="openai":i.includes("perplexity")||i.includes("sonar")?r="perplexity":i.includes("vertex")?r="vertex_ai":(i.includes("xai")||i.includes("grok"))&&(r="xai")}e.setAttribute(VN,r)}setInvocationParameters(e,n){var s,i;if(!((i=(s=n.extra)==null?void 0:s.metadata)!=null&&i.invocation_params))return;const r=n.extra.metadata.invocation_params;r.max_tokens!==void 0&&e.setAttribute(WN,r.max_tokens),r.temperature!==void 0&&e.setAttribute(ZN,r.temperature),r.top_p!==void 0&&e.setAttribute(qN,r.top_p),r.frequency_penalty!==void 0&&e.setAttribute(GN,r.frequency_penalty),r.presence_penalty!==void 0&&e.setAttribute(JN,r.presence_penalty)}setIOAttributes(e,n){if(n.run.inputs)try{const r=n.run.inputs;typeof r=="object"&&r!==null&&(r.model&&Array.isArray(r.messages)&&e.setAttribute(Xb,r.model),r.stream!==void 0&&e.setAttribute(m2,r.stream),r.extra_headers&&e.setAttribute(g2,JSON.stringify(r.extra_headers)),r.extra_query&&e.setAttribute(e2,JSON.stringify(r.extra_query)),r.extra_body&&e.setAttribute(t2,JSON.stringify(r.extra_body))),e.setAttribute(XN,JSON.stringify(r))}catch(r){console.debug(`Failed to process inputs for run ${n.id}`,r)}if(n.run.outputs)try{const r=n.run.outputs,s=this.getUnifiedRunTokens(r);if(s&&(e.setAttribute(Qb,s[0]),e.setAttribute(e0,s[1]),e.setAttribute(t0,s[0]+s[1])),r&&typeof r=="object"){if(r.model&&e.setAttribute(KN,String(r.model)),r.id&&e.setAttribute(i2,r.id),r.choices&&Array.isArray(r.choices)){const i=r.choices.map(a=>a.finish_reason).filter(a=>a).map(String);i.length>0&&e.setAttribute(YN,i.join(", "))}if(r.service_tier&&e.setAttribute(a2,r.service_tier),r.system_fingerprint&&e.setAttribute(o2,r.system_fingerprint),r.usage_metadata&&typeof r.usage_metadata=="object"){const i=r.usage_metadata;e.setAttribute(r0,JSON.stringify(i)),i.input_token_details&&e.setAttribute(c2,JSON.stringify(i.input_token_details)),i.output_token_details&&e.setAttribute(u2,JSON.stringify(i.output_token_details))}}e.setAttribute(QN,JSON.stringify(r))}catch(r){console.debug(`Failed to process outputs for run ${n.id}`,r)}}getUnifiedRunTokens(e){if(!e)return null;let n=this.extractUnifiedRunTokens(e.usage_metadata);if(n)return n;const r=Object.keys(e);for(const a of r){const o=e[a];if(!(!o||typeof o!="object")&&(n=this.extractUnifiedRunTokens(o.usage_metadata),n||o.lc===1&&o.kwargs&&typeof o.kwargs=="object"&&(n=this.extractUnifiedRunTokens(o.kwargs.usage_metadata),n)))return n}const s=e.generations||[];if(!Array.isArray(s))return null;const i=Array.isArray(s[0])?s.flat():s;for(const a of i)if(typeof a=="object"&&a.message&&typeof a.message=="object"&&a.message.kwargs&&typeof a.message.kwargs=="object"&&(n=this.extractUnifiedRunTokens(a.message.kwargs.usage_metadata),n))return n;return null}extractUnifiedRunTokens(e){return!e||typeof e!="object"||typeof e.input_tokens!="number"||typeof e.output_tokens!="number"?null:[e.input_tokens,e.output_tokens]}}const gM=Object.prototype.toString,_M=t=>gM.call(t)==="[object Error]",yM=new Set(["network error","Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed","fetch failed","terminated"," A network error occurred.","Network connection lost"]);function wM(t){if(!(t&&_M(t)&&t.name==="TypeError"&&typeof t.message=="string"))return!1;const{message:n,stack:r}=t;return n==="Load failed"?r===void 0||"__sentry_captured__"in t:n.startsWith("error sending request for url")?!0:yM.has(n)}function bM(t){if(typeof t=="number"){if(t<0)throw new TypeError("Expected `retries` to be a non-negative number.");if(Number.isNaN(t))throw new TypeError("Expected `retries` to be a valid number or Infinity, got NaN.")}else if(t!==void 0)throw new TypeError("Expected `retries` to be a number or Infinity.")}function Kl(t,e,{min:n=0,allowInfinity:r=!1}={}){if(e!==void 0){if(typeof e!="number"||Number.isNaN(e))throw new TypeError(`Expected \`${t}\` to be a number${r?" or Infinity":""}.`);if(!r&&!Number.isFinite(e))throw new TypeError(`Expected \`${t}\` to be a finite number.`);if(e<n)throw new TypeError(`Expected \`${t}\` to be ≥ ${n}.`)}}let vM=class extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,{message:e}=e):(this.originalError=new Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}};function SM(t,e){const n=Math.max(1,t+1),r=e.randomize?Math.random()+1:1;let s=Math.round(r*e.minTimeout*e.factor**(n-1));return s=Math.min(s,e.maxTimeout),s}function h0(t,e){return Number.isFinite(e)?e-(performance.now()-t):e}async function AM({error:t,attemptNumber:e,retriesConsumed:n,startTime:r,options:s}){var h,p,g;const i=t instanceof Error?t:new TypeError(`Non-error was thrown: "${t}". You should only throw errors.`);if(i instanceof vM)throw i.originalError;const a=Number.isFinite(s.retries)?Math.max(0,s.retries-n):s.retries,o=s.maxRetryTime??Number.POSITIVE_INFINITY,c=Object.freeze({error:i,attemptNumber:e,retriesLeft:a,retriesConsumed:n});if(await s.onFailedAttempt(c),h0(r,o)<=0)throw i;const u=await s.shouldConsumeRetry(c),l=h0(r,o);if(l<=0||a<=0)throw i;if(i instanceof TypeError&&!wM(i)){if(u)throw i;return(h=s.signal)==null||h.throwIfAborted(),!1}if(!await s.shouldRetry(c))throw i;if(!u)return(p=s.signal)==null||p.throwIfAborted(),!1;const d=SM(n,s),f=Math.min(d,l);return f>0&&await new Promise((y,b)=>{var v,A;const _=()=>{var S;clearTimeout(w),(S=s.signal)==null||S.removeEventListener("abort",_),b(s.signal.reason)},w=setTimeout(()=>{var S;(S=s.signal)==null||S.removeEventListener("abort",_),y()},f);s.unref&&((v=w.unref)==null||v.call(w)),(A=s.signal)==null||A.addEventListener("abort",_,{once:!0})}),(g=s.signal)==null||g.throwIfAborted(),!0}async function TM(t,e={}){var i,a,o;if(e={...e},bM(e.retries),Object.hasOwn(e,"forever"))throw new Error("The `forever` option is no longer supported. For many use-cases, you can set `retries: Infinity` instead.");e.retries??(e.retries=10),e.factor??(e.factor=2),e.minTimeout??(e.minTimeout=1e3),e.maxTimeout??(e.maxTimeout=Number.POSITIVE_INFINITY),e.maxRetryTime??(e.maxRetryTime=Number.POSITIVE_INFINITY),e.randomize??(e.randomize=!1),e.onFailedAttempt??(e.onFailedAttempt=()=>{}),e.shouldRetry??(e.shouldRetry=()=>!0),e.shouldConsumeRetry??(e.shouldConsumeRetry=()=>!0),Kl("factor",e.factor,{min:0,allowInfinity:!1}),Kl("minTimeout",e.minTimeout,{min:0,allowInfinity:!1}),Kl("maxTimeout",e.maxTimeout,{min:0,allowInfinity:!0}),Kl("maxRetryTime",e.maxRetryTime,{min:0,allowInfinity:!0}),e.factor>0||(e.factor=1),(i=e.signal)==null||i.throwIfAborted();let n=0,r=0;const s=performance.now();for(;!Number.isFinite(e.retries)||r<=e.retries;){n++;try{(a=e.signal)==null||a.throwIfAborted();const c=await t(n);return(o=e.signal)==null||o.throwIfAborted(),c}catch(c){await AM({error:c,attemptNumber:n,retriesConsumed:r,startTime:s,options:e})&&r++}}throw new Error("Retry attempts exhausted without throwing an error.")}var dE={},hE={exports:{}};(function(t){var e=Object.prototype.hasOwnProperty,n="~";function r(){}Object.create&&(r.prototype=Object.create(null),new r().__proto__||(n=!1));function s(c,u,l){this.fn=c,this.context=u,this.once=l||!1}function i(c,u,l,d,f){if(typeof l!="function")throw new TypeError("The listener must be a function");var h=new s(l,d||c,f),p=n?n+u:u;return c._events[p]?c._events[p].fn?c._events[p]=[c._events[p],h]:c._events[p].push(h):(c._events[p]=h,c._eventsCount++),c}function a(c,u){--c._eventsCount===0?c._events=new r:delete c._events[u]}function o(){this._events=new r,this._eventsCount=0}o.prototype.eventNames=function(){var u=[],l,d;if(this._eventsCount===0)return u;for(d in l=this._events)e.call(l,d)&&u.push(n?d.slice(1):d);return Object.getOwnPropertySymbols?u.concat(Object.getOwnPropertySymbols(l)):u},o.prototype.listeners=function(u){var l=n?n+u:u,d=this._events[l];if(!d)return[];if(d.fn)return[d.fn];for(var f=0,h=d.length,p=new Array(h);f<h;f++)p[f]=d[f].fn;return p},o.prototype.listenerCount=function(u){var l=n?n+u:u,d=this._events[l];return d?d.fn?1:d.length:0},o.prototype.emit=function(u,l,d,f,h,p){var g=n?n+u:u;if(!this._events[g])return!1;var y=this._events[g],b=arguments.length,_,w;if(y.fn){switch(y.once&&this.removeListener(u,y.fn,void 0,!0),b){case 1:return y.fn.call(y.context),!0;case 2:return y.fn.call(y.context,l),!0;case 3:return y.fn.call(y.context,l,d),!0;case 4:return y.fn.call(y.context,l,d,f),!0;case 5:return y.fn.call(y.context,l,d,f,h),!0;case 6:return y.fn.call(y.context,l,d,f,h,p),!0}for(w=1,_=new Array(b-1);w<b;w++)_[w-1]=arguments[w];y.fn.apply(y.context,_)}else{var v=y.length,A;for(w=0;w<v;w++)switch(y[w].once&&this.removeListener(u,y[w].fn,void 0,!0),b){case 1:y[w].fn.call(y[w].context);break;case 2:y[w].fn.call(y[w].context,l);break;case 3:y[w].fn.call(y[w].context,l,d);break;case 4:y[w].fn.call(y[w].context,l,d,f);break;default:if(!_)for(A=1,_=new Array(b-1);A<b;A++)_[A-1]=arguments[A];y[w].fn.apply(y[w].context,_)}}return!0},o.prototype.on=function(u,l,d){return i(this,u,l,d,!1)},o.prototype.once=function(u,l,d){return i(this,u,l,d,!0)},o.prototype.removeListener=function(u,l,d,f){var h=n?n+u:u;if(!this._events[h])return this;if(!l)return a(this,h),this;var p=this._events[h];if(p.fn)p.fn===l&&(!f||p.once)&&(!d||p.context===d)&&a(this,h);else{for(var g=0,y=[],b=p.length;g<b;g++)(p[g].fn!==l||f&&!p[g].once||d&&p[g].context!==d)&&y.push(p[g]);y.length?this._events[h]=y.length===1?y[0]:y:a(this,h)}return this},o.prototype.removeAllListeners=function(u){var l;return u?(l=n?n+u:u,this._events[l]&&a(this,l)):(this._events=new r,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=n,o.EventEmitter=o,t.exports=o})(hE);var EM=hE.exports,Sf={exports:{}},IM=(t,e)=>(e=e||(()=>{}),t.then(n=>new Promise(r=>{r(e())}).then(()=>n),n=>new Promise(r=>{r(e())}).then(()=>{throw n})));const xM=IM;class fE extends Error{constructor(e){super(e),this.name="TimeoutError"}}const pE=(t,e,n)=>new Promise((r,s)=>{if(typeof e!="number"||e<0)throw new TypeError("Expected `milliseconds` to be a positive number");if(e===1/0){r(t);return}const i=setTimeout(()=>{if(typeof n=="function"){try{r(n())}catch(c){s(c)}return}const a=typeof n=="string"?n:`Promise timed out after ${e} milliseconds`,o=n instanceof Error?n:new fE(a);typeof t.cancel=="function"&&t.cancel(),s(o)},e);xM(t.then(r,s),()=>{clearTimeout(i)})});Sf.exports=pE;Sf.exports.default=pE;Sf.exports.TimeoutError=fE;var kM=Sf.exports,fy={},py={};Object.defineProperty(py,"__esModule",{value:!0});function CM(t,e,n){let r=0,s=t.length;for(;s>0;){const i=s/2|0;let a=r+i;n(t[a],e)<=0?(r=++a,s-=i+1):s=i}return r}py.default=CM;Object.defineProperty(fy,"__esModule",{value:!0});const OM=py;class $M{constructor(){this._queue=[]}enqueue(e,n){n=Object.assign({priority:0},n);const r={priority:n.priority,run:e};if(this.size&&this._queue[this.size-1].priority>=n.priority){this._queue.push(r);return}const s=OM.default(this._queue,r,(i,a)=>a.priority-i.priority);this._queue.splice(s,0,r)}dequeue(){const e=this._queue.shift();return e==null?void 0:e.run}filter(e){return this._queue.filter(n=>n.priority===e.priority).map(n=>n.run)}get size(){return this._queue.length}}fy.default=$M;Object.defineProperty(dE,"__esModule",{value:!0});const RM=EM,mE=kM,PM=fy,Wl=()=>{},NM=new mE.TimeoutError;let MM=class extends RM{constructor(e){var n,r,s,i;if(super(),this._intervalCount=0,this._intervalEnd=0,this._pendingCount=0,this._resolveEmpty=Wl,this._resolveIdle=Wl,e=Object.assign({carryoverConcurrencyCount:!1,intervalCap:1/0,interval:0,concurrency:1/0,autoStart:!0,queueClass:PM.default},e),!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${(r=(n=e.intervalCap)===null||n===void 0?void 0:n.toString())!==null&&r!==void 0?r:""}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${(i=(s=e.interval)===null||s===void 0?void 0:s.toString())!==null&&i!==void 0?i:""}\` (${typeof e.interval})`);this._carryoverConcurrencyCount=e.carryoverConcurrencyCount,this._isIntervalIgnored=e.intervalCap===1/0||e.interval===0,this._intervalCap=e.intervalCap,this._interval=e.interval,this._queue=new e.queueClass,this._queueClass=e.queueClass,this.concurrency=e.concurrency,this._timeout=e.timeout,this._throwOnTimeout=e.throwOnTimeout===!0,this._isPaused=e.autoStart===!1}get _doesIntervalAllowAnother(){return this._isIntervalIgnored||this._intervalCount<this._intervalCap}get _doesConcurrentAllowAnother(){return this._pendingCount<this._concurrency}_next(){this._pendingCount--,this._tryToStartAnother(),this.emit("next")}_resolvePromises(){this._resolveEmpty(),this._resolveEmpty=Wl,this._pendingCount===0&&(this._resolveIdle(),this._resolveIdle=Wl,this.emit("idle"))}_onResumeInterval(){this._onInterval(),this._initializeIntervalIfNeeded(),this._timeoutId=void 0}_isIntervalPaused(){const e=Date.now();if(this._intervalId===void 0){const n=this._intervalEnd-e;if(n<0)this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0;else return this._timeoutId===void 0&&(this._timeoutId=setTimeout(()=>{this._onResumeInterval()},n)),!0}return!1}_tryToStartAnother(){if(this._queue.size===0)return this._intervalId&&clearInterval(this._intervalId),this._intervalId=void 0,this._resolvePromises(),!1;if(!this._isPaused){const e=!this._isIntervalPaused();if(this._doesIntervalAllowAnother&&this._doesConcurrentAllowAnother){const n=this._queue.dequeue();return n?(this.emit("active"),n(),e&&this._initializeIntervalIfNeeded(),!0):!1}}return!1}_initializeIntervalIfNeeded(){this._isIntervalIgnored||this._intervalId!==void 0||(this._intervalId=setInterval(()=>{this._onInterval()},this._interval),this._intervalEnd=Date.now()+this._interval)}_onInterval(){this._intervalCount===0&&this._pendingCount===0&&this._intervalId&&(clearInterval(this._intervalId),this._intervalId=void 0),this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0,this._processQueue()}_processQueue(){for(;this._tryToStartAnother(););}get concurrency(){return this._concurrency}set concurrency(e){if(!(typeof e=="number"&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);this._concurrency=e,this._processQueue()}async add(e,n={}){return new Promise((r,s)=>{const i=async()=>{this._pendingCount++,this._intervalCount++;try{const a=this._timeout===void 0&&n.timeout===void 0?e():mE.default(Promise.resolve(e()),n.timeout===void 0?this._timeout:n.timeout,()=>{(n.throwOnTimeout===void 0?this._throwOnTimeout:n.throwOnTimeout)&&s(NM)});r(await a)}catch(a){s(a)}this._next()};this._queue.enqueue(i,n),this._tryToStartAnother(),this.emit("add")})}async addAll(e,n){return Promise.all(e.map(async r=>this.add(r,n)))}start(){return this._isPaused?(this._isPaused=!1,this._processQueue(),this):this}pause(){this._isPaused=!0}clear(){this._queue=new this._queueClass}async onEmpty(){if(this._queue.size!==0)return new Promise(e=>{const n=this._resolveEmpty;this._resolveEmpty=()=>{n(),e()}})}async onIdle(){if(!(this._pendingCount===0&&this._queue.size===0))return new Promise(e=>{const n=this._resolveIdle;this._resolveIdle=()=>{n(),e()}})}get size(){return this._queue.size}sizeBy(e){return this._queue.filter(e).length}get pending(){return this._pendingCount}get isPaused(){return this._isPaused}get timeout(){return this._timeout}set timeout(e){this._timeout=e}};var Fs=dE.default=MM;const LM="default"in Fs?Fs.default:Fs,jM=[408,425,429,500,502,503,504];let f0=class{constructor(e){Object.defineProperty(this,"maxConcurrency",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"maxRetries",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"maxQueueSizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"queue",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onFailedResponseHook",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"queueSizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:0}),this.maxConcurrency=e.maxConcurrency??1/0,this.maxRetries=e.maxRetries??6,this.maxQueueSizeBytes=e.maxQueueSizeBytes,this.queue=new LM({concurrency:this.maxConcurrency}),this.onFailedResponseHook=e==null?void 0:e.onFailedResponseHook}call(e,...n){return this.callWithOptions({},e,...n)}callWithOptions(e,n,...r){const s=e.sizeBytes??0;if(this.maxQueueSizeBytes!==void 0&&s>0&&this.queueSizeBytes+s>this.maxQueueSizeBytes)return Promise.reject(new Error(`Queue size limit (${this.maxQueueSizeBytes} bytes) exceeded. Current queue size: ${this.queueSizeBytes} bytes, attempted addition: ${s} bytes.`));s>0&&(this.queueSizeBytes+=s);const i=this.onFailedResponseHook;let a=this.queue.add(()=>TM(()=>n(...r).catch(o=>{throw o instanceof Error?o:new Error(o)}),{async onFailedAttempt({error:o}){if(typeof o!="object"||o==null)throw o;const c="message"in o&&typeof o.message=="string"?o.message:void 0;if(c!=null&&c.startsWith("Cancel")||c!=null&&c.startsWith("TimeoutError")||c!=null&&c.startsWith("AbortError")||"name"in o&&o.name==="TimeoutError"||"code"in o&&o.code==="ECONNABORTED")throw o;const u="response"in o?o.response:void 0;if(i&&await i(u))return;const l=(u==null?void 0:u.status)??("status"in o?o.status:void 0);if(l!=null&&(typeof l=="number"||typeof l=="string")&&!jM.includes(+l))throw o},retries:this.maxRetries,randomize:!0}),{throwOnTimeout:!0});return s>0&&(a=a.finally(()=>{this.queueSizeBytes-=s})),e.signal?Promise.race([a,new Promise((o,c)=>{var u;(u=e.signal)==null||u.addEventListener("abort",()=>{c(new Error("AbortError"))})})]):a}};function p0(t){return typeof(t==null?void 0:t._getType)=="function"}function m0(t){const e={type:t._getType(),data:{content:t.content}};return t!=null&&t.additional_kwargs&&Object.keys(t.additional_kwargs).length>0&&(e.data.additional_kwargs={...t.additional_kwargs}),e}function xp(t){return`Invalid prompt identifier format: "${t}". Expected one of:
|
|
18
|
-
- "prompt-name" (for private prompts)
|
|
19
|
-
- "owner/prompt-name" (for prompts with explicit owner)
|
|
20
|
-
- "prompt-name:commit-hash" (with commit reference)
|
|
21
|
-
- "owner/prompt-name:commit-hash" (with owner and commit)`}class DM extends Error{constructor(e){super(e),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="LangSmithConflictError",this.status=409}}class UM extends Error{constructor(e){super(e),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="LangSmithNotFoundError",this.status=404}}function kp(t){return t!=null&&typeof t=="object"&&"name"in t&&(t==null?void 0:t.name)==="LangSmithNotFoundError"}function FM(t){return t!=null&&typeof t=="object"&&"name"in t&&(t==null?void 0:t.name)==="LangSmithConflictError"}async function he(t,e,n){let r;if(t.ok){n&&(r=await t.text());return}if(t.status===403)try{const a=await t.json();(a==null?void 0:a.error)==="org_scoped_key_requires_workspace"&&(r="This API key is org-scoped and requires workspace specification. Please provide 'workspaceId' parameter, or set LANGSMITH_WORKSPACE_ID environment variable.")}catch{const o=new Error(`${t.status} ${t.statusText}`);throw o.status=t==null?void 0:t.status,o}if(r===void 0)try{r=await t.text()}catch{r=""}const s=`Failed to ${e}. Received status [${t.status}]: ${t.statusText}. Message: ${r}`;if(t.status===404)throw new UM(s);if(t.status===409)throw new DM(s);const i=new Error(s);throw i.status=t.status,i}const gE="ERR_CONFLICTING_ENDPOINTS";class BM extends Error{constructor(){super("You cannot provide both LANGSMITH_ENDPOINT / LANGCHAIN_ENDPOINT and LANGSMITH_RUNS_ENDPOINTS."),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:gE}),this.name="ConflictingEndpointsError"}}function zM(t){return typeof t=="object"&&t!==null&&t.code===gE}function kn(t){if(!t||t.split("/").length>2||t.startsWith("/")||t.endsWith("/")||t.split(":").length>2)throw new Error(xp(t));const[e,n]=t.split(":"),r=n||"latest";if(e.includes("/")){const[s,i]=e.split("/",2);if(!s||!i)throw new Error(xp(t));return[s,i,r]}else{if(!e)throw new Error(xp(t));return["-",e,r]}}const HM=10,VM=1e4,_E="created_at";function KM(t){return new Promise(e=>setTimeout(e,t))}function WM(t){return typeof t=="object"&&t!==null&&t.code==="EEXIST"}function yE(t){try{return sE(ya.join(t,_E)).split(`
|
|
22
|
-
`)}catch{return}}function ZM(t){const e=yE(t);if(e&&e[0]&&e[0].trim()){const n=Date.parse(e[0].trim());if(!Number.isNaN(n))return n}return void 0}function qM(t){const e=yE(t);if(e&&e.length>=2&&e[1].trim())return e[1].trim()}async function GM(t){const e=ZM(t);return e===void 0||Date.now()-e<=VM?!1:(await ng(),!0)}async function JM(t,e){const n=`${t}.oauth.lock.lock`;ya.dirname(n)&&await rE();const s=globalThis.crypto.randomUUID();for(;;){try{await G2(n)}catch(i){if(!WM(i))throw i;if(!await GM(n)){if(Date.now()>=e)throw new Error("timed out acquiring OAuth refresh lock");await KM(Math.min(HM,Math.max(0,e-Date.now())))}continue}try{await ly(ya.join(n,_E),`${new Date().toISOString()}
|
|
23
|
-
${s}
|
|
24
|
-
`)}catch(i){throw await ng(),i}break}return{async release(){qM(n)===s&&await ng()}}}const rg="https://api.smith.langchain.com",YM="langsmith-cli",XM=6e4,QM=1e4;function eL(){const t=dy();return t==="browser"||t==="webworker"}function tL(){const t=cr("LANGSMITH_CONFIG_FILE");if(t)return t;const e=cr("HOME")??cr("USERPROFILE");if(e)return ya.join(e,".langsmith","config.json")}function nL(){eL()||tL()}function Pr(t){return t!=null&&t.trim()!==""}function bi(t){return t==null?void 0:t.trim().replace(/^["']|["']$/g,"")}function g0(t){const e=t.oauth;if(!(e!=null&&e.refresh_token))return!1;if(!e.access_token)return!0;if(!e.expires_at)return!1;const n=Date.parse(e.expires_at);return Number.isNaN(n)?!1:n<=Date.now()+XM}function rL(t){let e=t;for(;e.endsWith("/");)e=e.slice(0,-1);const n="/api/v1";return e.endsWith(n)?e.slice(0,-n.length):e}function sL(t,e){t.oauth??(t.oauth={}),e.access_token&&(t.oauth.access_token=e.access_token),e.refresh_token&&(t.oauth.refresh_token=e.refresh_token),typeof e.expires_in=="number"&&e.expires_in>0&&(t.oauth.expires_at=new Date(Date.now()+e.expires_in*1e3).toISOString())}function _0(t){return t.reason??new Error("The operation was aborted.")}async function iL(t,e){if(!e)return t;if(e.aborted)throw _0(e);let n;const r=new Promise((s,i)=>{const a=()=>{i(_0(e))};e.addEventListener("abort",a,{once:!0}),n=()=>{e.removeEventListener("abort",a)}});try{return await Promise.race([t,r])}finally{n==null||n()}}function aL(){var i,a;const t=nL(),e=t==null?void 0:t.profile;if(!t||!e)return{};const n=bi(e.api_key),r=bi((i=e.oauth)==null?void 0:i.access_token),s=bi((a=e.oauth)==null?void 0:a.refresh_token);return{apiUrl:e.api_url,apiKey:n,workspaceId:e.workspace_id,oauthAccessToken:r,oauthRefreshToken:s,profileAuth:n||r||s?new oL(t):void 0}}class oL{constructor(e){Object.defineProperty(this,"state",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"refreshPromise",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"managedAuthorizationValue",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.rememberProfileAuthHeader(this.currentAuthHeader())}currentAuthHeader(){const e=cL(this.state.profile);return this.rememberProfileAuthHeader(e),e}async getAuthHeader(e,n){g0(this.state.profile)&&(this.refreshPromise||(this.refreshPromise=this.refreshOAuthToken(e).finally(()=>{this.refreshPromise=void 0})),await iL(this.refreshPromise,n));const r=wE(this.state.profile);return this.rememberProfileAuthHeader(r),r}isProfileAuthorizationHeader(e){return e===this.managedAuthorizationValue}reloadProfile(){var e;try{const n=JSON.parse(sE(this.state.configPath)),r=(e=n.profiles)==null?void 0:e[this.state.profileName];return r?(this.state.config=n,this.state.profile=r,r):void 0}catch{return}}async refreshOAuthToken(e){var a,o,c;const n=(a=this.state.profile.oauth)==null?void 0:a.refresh_token;if(!n)return;const r=bi(this.state.profile.api_url)??rg,s=Date.now()+QM;let i;try{if(i=await JM(this.state.configPath,s),this.reloadProfile()&&!g0(this.state.profile))return;const l=new URLSearchParams({grant_type:"refresh_token",client_id:YM,refresh_token:((o=this.state.profile.oauth)==null?void 0:o.refresh_token)??n}),d=await e(`${rL(r)}/oauth/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:l.toString(),signal:AbortSignal.timeout(Math.max(0,s-Date.now()))});if(!d.ok)return;const f=await d.json();if(!f.access_token)return;sL(this.state.profile,f),(c=this.state.config).profiles??(c.profiles={}),this.state.config.profiles[this.state.profileName]=this.state.profile,await ly(this.state.configPath,`${JSON.stringify(this.state.config,null,2)}
|
|
25
|
-
`)}catch{return}finally{await(i==null?void 0:i.release())}}rememberProfileAuthHeader(e){this.managedAuthorizationValue=(e==null?void 0:e.name)==="Authorization"?e.value:void 0}}function cL(t){var n,r;const e=bi((n=t.oauth)==null?void 0:n.access_token);if(e)return{name:"Authorization",value:`Bearer ${e}`};if(!bi((r=t.oauth)==null?void 0:r.refresh_token))return wE(t)}function wE(t){var r;const e=bi((r=t.oauth)==null?void 0:r.access_token);if(e)return{name:"Authorization",value:`Bearer ${e}`};const n=bi(t.api_key);if(n)return{name:"x-api-key",value:n}}var y0="[...]",uL={result:"[Circular]"},Ah=[],no=[];const lL=new TextEncoder;function dL(){return{depthLimit:Number.MAX_SAFE_INTEGER,edgesLimit:Number.MAX_SAFE_INTEGER}}function Zl(t){return lL.encode(t)}function bE(t){if(t&&typeof t=="object"&&t!==null){if(t instanceof Map)return Object.fromEntries(t);if(t instanceof Set)return Array.from(t);if(t instanceof Date)return t.toISOString();if(t instanceof RegExp)return t.toString();if(t instanceof Error)return{name:t.name,message:t.message}}else if(typeof t=="bigint")return t.toString();return t}function hL(t){return function(e,n){return bE(n)}}function fL(t){try{let s=function(l){const d=r(l);return d>n&&(n=d),d+2},i=function(l){return l===0?2:2+l*4},a=function(l){return l===void 0||typeof l=="function"||typeof l=="symbol"},o=function(l){return l===void 0||typeof l=="function"||typeof l=="symbol"?4:c(l)},c=function(l){if(l===null)return 4;if(l===void 0)return 0;const d=typeof l;if(d==="boolean")return 5;if(d==="number")return Number.isFinite(l)?l.toString().length:4;if(d==="bigint")return l.toString().length+2;if(d==="string")return s(l);if(d==="function"||d==="symbol")return 0;const f=l;if(f instanceof Date)return 26;if(f instanceof RegExp)return r(f.toString())+2;if(f instanceof Error){const p=f.name??"",g=f.message??"";return 22+r(p)+r(g)}if(typeof Buffer<"u"&&f instanceof Buffer)return 28+i(f.byteLength);if(ArrayBuffer.isView(f)){if(f instanceof DataView)return 2;const p=f.length??0,y=f instanceof Float32Array||f instanceof Float64Array?30:12;return 2+p*y}if(f instanceof ArrayBuffer)return 2;if(e.has(f))return 24;if(typeof f.toJSON=="function"){let p;try{p=f.toJSON("")}catch{return 16}e.add(f);const g=c(p);return e.delete(f),g}e.add(f);let h;if(Array.isArray(f)){h=2;const p=f.length;for(let g=0;g<p;g++)h+=o(f[g]),g<p-1&&(h+=1)}else if(f instanceof Map){h=2;let p=0;for(const[g,y]of f){if(a(y))continue;p>0&&(h+=1);const b=typeof g=="string"?g:String(g);h+=r(b)+3,h+=c(y),p++}}else if(f instanceof Set){h=2;let p=0;for(const g of f)p>0&&(h+=1),h+=o(g),p++}else{h=2;let p=0;const g=Object.keys(f);for(let y=0;y<g.length;y++){const b=g[y],_=f[b];a(_)||(p>0&&(h+=1),h+=r(b)+3,h+=c(_),p++)}}return e.delete(f),h};const e=new Set;let n=0;const r=typeof Buffer<"u"&&typeof Buffer.byteLength=="function"?l=>Buffer.byteLength(l,"utf8"):l=>l.length;return{size:c(t),maxStringLen:n}}catch{return{size:Cn(t).length,maxStringLen:0}}}function Cn(t,e,n,r,s){var i;try{const a=JSON.stringify(t,hL(n),r);return Zl(a)}catch(a){if(!((i=a.message)!=null&&i.includes("Converting circular structure to JSON")))return console.warn(`[WARNING]: LangSmith received unserializable value.${e?`
|
|
26
|
-
Context: ${e}`:""}`),Zl("[Unserializable]");Pt("SUPPRESS_CIRCULAR_JSON_WARNINGS")!=="true"&&console.warn(`[WARNING]: LangSmith received circular JSON. This will decrease tracer performance. ${e?`
|
|
27
|
-
Context: ${e}`:""}`),typeof s>"u"&&(s=dL()),sg(t,"",0,[],void 0,0,s);let o;try{no.length===0?o=JSON.stringify(t,n,r):o=JSON.stringify(t,pL(n),r)}catch{return Zl("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;Ah.length!==0;){const c=Ah.pop();c.length===4?Object.defineProperty(c[0],c[1],c[3]):c[0][c[1]]=c[2]}}return Zl(o)}}function Cp(t,e,n,r){var s=Object.getOwnPropertyDescriptor(r,n);s.get!==void 0?s.configurable?(Object.defineProperty(r,n,{value:t}),Ah.push([r,n,e,s])):no.push([e,n,t]):(r[n]=t,Ah.push([r,n,e]))}function sg(t,e,n,r,s,i,a){i+=1;var o;if(typeof t=="object"&&t!==null){for(o=0;o<r.length;o++)if(r[o]===t){Cp(uL,t,e,s);return}if(typeof a.depthLimit<"u"&&i>a.depthLimit){Cp(y0,t,e,s);return}if(typeof a.edgesLimit<"u"&&n+1>a.edgesLimit){Cp(y0,t,e,s);return}if(r.push(t),Array.isArray(t))for(o=0;o<t.length;o++)sg(t[o],o,o,r,t,i,a);else{t=bE(t);var c=Object.keys(t);for(o=0;o<c.length;o++){var u=c[o];sg(t[u],u,o,r,t,i,a)}}r.pop()}}function pL(t){return t=typeof t<"u"?t:function(e,n){return n},function(e,n){if(no.length>0)for(var r=0;r<no.length;r++){var s=no[r];if(s[1]===e&&s[0]===n){n=s[2],no.splice(r,1);break}}return t.call(this,e,n)}}class mL{constructor(){Object.defineProperty(this,"worker",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"nextId",{enumerable:!0,configurable:!0,writable:!0,value:1}),Object.defineProperty(this,"pending",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"disabled",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"startPromise",{enumerable:!0,configurable:!0,writable:!0,value:null})}async ensureStarted(){if(this.disabled)return!1;if(this.worker!==null)return!0;if(this.startPromise!==null)return this.startPromise;this.startPromise=this._start();try{return await this.startPromise}finally{this.startPromise=null}}async _start(){return this.disabled=!0,!1}async serialize(e){if(!await this.ensureStarted())return null;const r=this.nextId++;return new Promise((s,i)=>{this.pending.set(r,{resolve:s,reject:i});try{this.worker.postMessage({id:r,op:"serialize",payload:e})}catch(a){this.pending.delete(r),i(a)}})}async terminate(){this.worker&&(await this.worker.terminate(),this.worker=null);for(const[,e]of this.pending)e.reject(new Error("worker terminated"));this.pending.clear()}}let Op=null;function gL(){return Op===null&&(Op=new mL),Op}const _L=64*1024,yL=2048;function wL(t,e=_L,n=yL){if(t===null||typeof t!="object")return typeof t=="string"&&t.length>=e;const r=[t],s=new Set;let i=0;for(;r.length>0;){if(i++>=n)return!1;const a=r.pop();if(a==null)continue;const o=typeof a;if(o==="string"){if(a.length>=e)return!0;continue}if(o!=="object")continue;const c=a;if(s.has(c)||(s.add(c),c instanceof Date||c instanceof RegExp||c instanceof Error||c instanceof ArrayBuffer||ArrayBuffer.isView(c)))continue;if(Array.isArray(c)){for(let l=c.length-1;l>=0;l--)r.push(c[l]);continue}if(c instanceof Map){for(const[,l]of c)r.push(l);continue}if(c instanceof Set){for(const l of c)r.push(l);continue}const u=Object.keys(c);for(let l=u.length-1;l>=0;l--)r.push(c[u[l]])}return!1}function bL(t,e){const[n]=kn(t);if(n!=="-"&&!e)throw new Error("Pulling a public prompt by owner/name is disabled by default because prompts may contain untrusted serialized LangChain objects. If you trust this prompt, set `dangerouslyPullPublicPrompt: true` to acknowledge the risk.")}function w0(t){return typeof t=="string"&&t.length>0&&!t.includes("Z")&&!t.includes("+")&&!t.includes("-",10)?t+"Z":t}function Ca(t){return{...t,start_time:w0(t.start_time),end_time:w0(t.end_time)}}function b0(t,e,n){if(n)return t;const r=oE(),s=e??cE(),i=t.extra??{},a=i.metadata;return t.extra={...i,runtime:{...r,...i==null?void 0:i.runtime},metadata:{...s,...s.revision_id||"revision_id"in t&&t.revision_id?{revision_id:("revision_id"in t?t.revision_id:void 0)??s.revision_id}:{},...a}},t}const vL=t=>{const e=(t==null?void 0:t.toString())??Pt("TRACING_SAMPLING_RATE");if(e===void 0)return;const n=parseFloat(e);if(n<0||n>1)throw new Error(`LANGSMITH_TRACING_SAMPLING_RATE must be between 0 and 1 if set. Got: ${n}`);return n},SL=t=>{const n=t.replace("http://","").replace("https://","").split("/")[0].split(":")[0];return n==="localhost"||n==="127.0.0.1"||n==="::1"};async function AL(t){const e=[];for await(const n of t)e.push(n);return e}function ql(t){if(t!==void 0)return t.trim().replace(/^"(.*)"$/,"$1").replace(/^'(.*)'$/,"$1")}const TL=async t=>{if((t==null?void 0:t.status)===429){const e=parseInt(t.headers.get("retry-after")??"10",10)*1e3;if(e>0)return await new Promise(n=>setTimeout(n,e)),!0}return!1};function v0(t){return typeof t=="number"?Number(t.toFixed(4)):t}const EL=24*1024*1024,vE=1024*1024*1024,IL=1e4,xL=100;class kL{constructor(e){Object.defineProperty(this,"items",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"sizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"maxSizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSizeBytes=e??vE}peek(){return this.items[0]}push(e){let n;const r=new Promise(i=>{n=i}),s=fL(e.item).size;return this.sizeBytes+s>this.maxSizeBytes&&this.items.length>0?(console.warn(`AutoBatchQueue size limit (${this.maxSizeBytes} bytes) exceeded. Dropping run with id: ${e.item.id}. Current queue size: ${this.sizeBytes} bytes, attempted addition: ${s} bytes.`),n(),r):(this.items.push({action:e.action,payload:e.item,otelContext:e.otelContext,apiKey:e.apiKey,apiUrl:e.apiUrl,itemPromiseResolve:n,itemPromise:r,size:s}),this.sizeBytes+=s,r)}pop({upToSizeBytes:e,upToSize:n}){var i;if(e<1)throw new Error("Number of bytes to pop off may not be less than 1.");const r=[];let s=0;for(;s+(((i=this.peek())==null?void 0:i.size)??0)<e&&this.items.length>0&&r.length<n;){const a=this.items.shift();a&&(r.push(a),s+=a.size,this.sizeBytes-=a.size)}if(r.length===0&&this.items.length>0){const a=this.items.shift();r.push(a),s+=a.size,this.sizeBytes-=a.size}return[r.map(a=>({action:a.action,item:a.payload,otelContext:a.otelContext,apiKey:a.apiKey,apiUrl:a.apiUrl,size:a.size})),()=>r.forEach(a=>a.itemPromiseResolve())]}}class ls{get tracingMode(){return this._tracingMode}get _fetch(){const e=this.fetchImplementation||w2(this.debug);return async(n,r)=>{var a;let s;const i=this.getProfileManagedAuthorizationHeader(r);return this.apiKey!==void 0?s={name:"x-api-key",value:`${this.apiKey}`}:this.hasExplicitAuthHeader(r,i)||(s=await((a=this.profileAuth)==null?void 0:a.getAuthHeader(e,r==null?void 0:r.signal))),e(n,this.applyCurrentAuthHeaders(r,s,i))}}getProfileManagedAuthorizationHeader(e){if(!(e!=null&&e.headers)||!this.profileAuth)return;const n=new Headers(e.headers).get("Authorization");if(Pr(n))return this.profileAuth.isProfileAuthorizationHeader(n??"")?n??void 0:void 0}isProfileManagedAuthorizationHeader(e,n){var r;return e===n||((r=this.profileAuth)==null?void 0:r.isProfileAuthorizationHeader(e))===!0}hasExplicitAuthHeader(e,n){if(!(e!=null&&e.headers))return!1;const r=new Headers(e.headers);if(Pr(r.get("x-api-key")))return!0;const s=r.get("Authorization");return Pr(s)?!this.isProfileManagedAuthorizationHeader(s??"",n):!1}applyCurrentAuthHeaders(e,n,r){if(!n)return e;const s=d=>{if(this.apiKey!==void 0&&n.name==="x-api-key")return d.delete("Authorization"),d.has("x-api-key")||d.set("x-api-key",n.value),d;if(n.name==="Authorization"){if(Pr(d.get("x-api-key")))return d;const h=d.get("Authorization");return Pr(h)&&!this.isProfileManagedAuthorizationHeader(h??"",r)||d.set("Authorization",n.value),d}const f=d.get("Authorization");return Pr(f)&&!this.isProfileManagedAuthorizationHeader(f??"",r)||(Pr(f)&&d.delete("Authorization"),d.has("x-api-key")||d.set("x-api-key",n.value)),d};if(!e)return{headers:{[n.name]:n.value}};if(e.headers instanceof Headers)return{...e,headers:s(new Headers(e.headers))};if(Array.isArray(e.headers))return{...e,headers:s(new Headers(e.headers))};const i={...e.headers??{}},a=d=>Object.keys(i).find(f=>f.toLowerCase()===d),o=d=>{const f=a(d);return f?i[f]:void 0},c=Pr(o("x-api-key")),u=o("authorization"),l=Pr(u)&&!this.isProfileManagedAuthorizationHeader(u??"",r);if(this.apiKey!==void 0&&n.name==="x-api-key"){const d=a("authorization");return d&&delete i[d],c||(i["x-api-key"]=n.value),{...e,headers:i}}if(n.name==="Authorization"){if(!c&&!l){const d=a("authorization");d&&d!=="Authorization"&&delete i[d],i.Authorization=n.value}return{...e,headers:i}}if(!l){const d=a("authorization");d&&delete i[d],c||(i["x-api-key"]=n.value)}return{...e,headers:i}}_trackDrain(e){this._pendingDrains.add(e),e.finally(()=>{this._pendingDrains.delete(e)})}async _serializeBody(e,n){if(this.manualFlushMode||!wL(e)||(this._serializeWorker===void 0&&(this._serializeWorker=gL()),this._serializeWorker===null))return Cn(e,n);try{const r=await this._serializeWorker.serialize(e);return r===null?(this._serializeWorker=null,Cn(e,n)):r}catch{return Cn(e,n)}}constructor(e={}){var a;Object.defineProperty(this,"apiKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"apiUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"webUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"workspaceId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"caller",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"batchIngestCaller",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"timeout_ms",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_tenantId",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"hideInputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"hideOutputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"hideMetadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"omitTracedRuntimeInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tracingSampleRate",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"filteredPostUuids",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"autoBatchTracing",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"autoBatchQueue",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"autoBatchTimeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"autoBatchAggregationDelayMs",{enumerable:!0,configurable:!0,writable:!0,value:250}),Object.defineProperty(this,"batchSizeBytesLimit",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"batchSizeLimit",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"fetchOptions",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"settings",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"blockOnRootRunFinalization",{enumerable:!0,configurable:!0,writable:!0,value:cr("LANGSMITH_TRACING_BACKGROUND")==="false"}),Object.defineProperty(this,"traceBatchConcurrency",{enumerable:!0,configurable:!0,writable:!0,value:5}),Object.defineProperty(this,"_serverInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_getServerInfoPromise",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"manualFlushMode",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_serializeWorker",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_pendingDrains",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"langSmithToOTELTranslator",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_tracingMode",{enumerable:!0,configurable:!0,writable:!0,value:"langsmith"}),Object.defineProperty(this,"fetchImplementation",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cachedLSEnvVarsForMetadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_promptCache",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"profileAuth",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"multipartStreamingDisabled",{enumerable:!0,configurable:!0,writable:!0,value:Pt("DISABLE_MULTIPART_STREAMING")==="true"}),Object.defineProperty(this,"_multipartDisabled",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_runCompressionDisabled",{enumerable:!0,configurable:!0,writable:!0,value:Pt("DISABLE_RUN_COMPRESSION")==="true"}),Object.defineProperty(this,"failedTracesDir",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"failedTracesMaxBytes",{enumerable:!0,configurable:!0,writable:!0,value:100*1024*1024}),Object.defineProperty(this,"_customHeaders",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"debug",{enumerable:!0,configurable:!0,writable:!0,value:cr("LANGSMITH_DEBUG")==="true"});const n=ls.getDefaultClientConfig();this.tracingSampleRate=vL(e.tracingSamplingRate),this.apiUrl=ql(e.apiUrl??n.apiUrl)??"",this.apiUrl.endsWith("/")&&(this.apiUrl=this.apiUrl.slice(0,-1));const r=ql(e.apiKey??n.apiKey);if(this.apiKey=Pr(r)?r:void 0,this.profileAuth=this.apiKey!==void 0?void 0:n.profileAuth,this.webUrl=ql(e.webUrl??n.webUrl),(a=this.webUrl)!=null&&a.endsWith("/")&&(this.webUrl=this.webUrl.slice(0,-1)),this.workspaceId=ql(e.workspaceId??n.workspaceId),this.timeout_ms=e.timeout_ms??9e4,this.caller=new f0({...e.callerOptions??{},maxRetries:4,debug:e.debug??this.debug}),this.traceBatchConcurrency=e.traceBatchConcurrency??this.traceBatchConcurrency,this.traceBatchConcurrency<1)throw new Error("Trace batch concurrency must be positive.");this.debug=e.debug??this.debug,this.fetchImplementation=e.fetchImplementation,this.failedTracesDir=Pt("FAILED_TRACES_DIR")||void 0;const s=Pt("FAILED_TRACES_MAX_MB");if(s){const o=parseInt(s,10);Number.isFinite(o)&&o>0&&(this.failedTracesMaxBytes=o*1024*1024)}const i=e.maxIngestMemoryBytes??vE;this.batchIngestCaller=new f0({maxRetries:4,maxConcurrency:this.traceBatchConcurrency,maxQueueSizeBytes:i,...e.callerOptions??{},onFailedResponseHook:TL,debug:e.debug??this.debug}),this.hideInputs=e.hideInputs??e.anonymizer??n.hideInputs,this.hideOutputs=e.hideOutputs??e.anonymizer??n.hideOutputs,this.hideMetadata=e.hideMetadata??n.hideMetadata,this.omitTracedRuntimeInfo=e.omitTracedRuntimeInfo??!1,this.autoBatchTracing=e.autoBatchTracing??this.autoBatchTracing,this.autoBatchQueue=new kL(i),this.blockOnRootRunFinalization=e.blockOnRootRunFinalization??this.blockOnRootRunFinalization,this.batchSizeBytesLimit=e.batchSizeBytesLimit,this.batchSizeLimit=e.batchSizeLimit,this.fetchOptions=e.fetchOptions||{},this.manualFlushMode=e.manualFlushMode??this.manualFlushMode,this._tracingMode=uE(e.tracingMode),this._tracingMode==="otel"&&(this.langSmithToOTELTranslator=new mM),this.cachedLSEnvVarsForMetadata=cE(),e.cache!==void 0&&e.disablePromptCache&&Dd("Both 'cache' and 'disablePromptCache' were provided. The 'cache' parameter is deprecated and will be removed in a future version. Using 'cache' parameter value."),e.cache!==void 0?(Dd("The 'cache' parameter is deprecated and will be removed in a future version. Use 'configureGlobalPromptCache()' to configure the global cache, or 'disablePromptCache: true' to disable caching for this client."),e.cache===!1?this._promptCache=void 0:e.cache===!0?this._promptCache=c0:this._promptCache=e.cache):e.disablePromptCache||(this._promptCache=c0),this._customHeaders=e.headers??{}}static getDefaultClientConfig(){const e=aL(),n=Pt("API_KEY"),r=Pt("ENDPOINT"),s=Pt("WORKSPACE_ID"),i=Pr(n),a=r??e.apiUrl??rg,o=s??e.workspaceId,c=Pt("HIDE_INPUTS")==="true",u=Pt("HIDE_OUTPUTS")==="true",l=Pt("HIDE_METADATA")==="true";return{apiUrl:a,apiKey:n,webUrl:void 0,hideInputs:c,hideOutputs:u,hideMetadata:l,workspaceId:o,oauthAccessToken:i?void 0:e.oauthAccessToken,oauthRefreshToken:i?void 0:e.oauthRefreshToken,profileAuth:i?void 0:e.profileAuth}}getHostUrl(){return this.webUrl?this.webUrl:SL(this.apiUrl)?(this.webUrl="http://localhost:3000",this.webUrl):this.apiUrl.endsWith("/api/v1")?(this.webUrl=this.apiUrl.replace("/api/v1",""),this.webUrl):this.apiUrl.includes("/api")&&!this.apiUrl.split(".",1)[0].endsWith("api")?(this.webUrl=this.apiUrl.replace("/api",""),this.webUrl):this.apiUrl.split(".",1)[0].includes("dev")?(this.webUrl="https://dev.smith.langchain.com",this.webUrl):this.apiUrl.split(".",1)[0].includes("eu")?(this.webUrl="https://eu.smith.langchain.com",this.webUrl):this.apiUrl.split(".",1)[0].includes("aws")?(this.webUrl="https://aws.smith.langchain.com",this.webUrl):this.apiUrl.split(".",1)[0].includes("apac")?(this.webUrl="https://apac.smith.langchain.com",this.webUrl):this.apiUrl.split(".",1)[0].includes("beta")?(this.webUrl="https://beta.smith.langchain.com",this.webUrl):(this.webUrl="https://smith.langchain.com",this.webUrl)}get _mergedHeaders(){var n;const e={"User-Agent":`langsmith-js/${iE}`,...this._customHeaders};if(this.apiKey!==void 0)e["x-api-key"]=`${this.apiKey}`;else{const r=(n=this.profileAuth)==null?void 0:n.currentAuthHeader();r&&(e[r.name]=r.value)}return this.workspaceId&&(e["x-tenant-id"]=this.workspaceId),e}get headers(){return this._customHeaders}set headers(e){this._customHeaders=e??{}}_getPlatformEndpointPath(e){return this.apiUrl.slice(-3)!=="/v1"&&this.apiUrl.slice(-4)!=="/v1/"?`/v1/platform/${e}`:`/platform/${e}`}async processInputs(e){return this.hideInputs===!1?e:this.hideInputs===!0?{}:typeof this.hideInputs=="function"?this.hideInputs(e):e}async processOutputs(e){return this.hideOutputs===!1?e:this.hideOutputs===!0?{}:typeof this.hideOutputs=="function"?this.hideOutputs(e):e}async processMetadata(e){return this.hideMetadata===!1?e:this.hideMetadata===!0?{}:typeof this.hideMetadata=="function"?this.hideMetadata(e):e}_filterNewTokenEvents(e){return!e||e.length===0?e:e.map(n=>{if(n.name==="new_token"){const{kwargs:r,...s}=n;return s}return n})}async prepareRunCreateOrUpdateInputs(e){const n={...e};return n.inputs!==void 0&&(n.inputs=await this.processInputs(n.inputs)),n.outputs!==void 0&&(n.outputs=await this.processOutputs(n.outputs)),n.extra!=null&&"metadata"in n.extra&&(n.extra={...n.extra,metadata:await this.processMetadata(n.extra.metadata)}),n.events!==void 0&&(n.events=this._filterNewTokenEvents(n.events)),n}async _getResponse(e,n){const r=(n==null?void 0:n.toString())??"",s=`${this.apiUrl}${e}?${r}`;return await this.caller.call(async()=>{const a=await this._fetch(s,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await he(a,`fetch ${e}`),a})}async _get(e,n){return(await this._getResponse(e,n)).json()}async*_getPaginated(e,n=new URLSearchParams,r){let s=Number(n.get("offset"))||0;const i=Number(n.get("limit"))||100;for(;;){n.set("offset",String(s)),n.set("limit",String(i));const a=`${this.apiUrl}${e}?${n}`,o=await this.caller.call(async()=>{const u=await this._fetch(a,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await he(u,`fetch ${e}`),u}),c=r?r(await o.json()):await o.json();if(c.length===0||(yield c,c.length<i))break;s+=c.length}}async*_getCursorPaginatedList(e,n=null,r="POST",s="runs"){const i=n?{...n}:{};for(;;){const a=JSON.stringify(i),c=await(await this.caller.call(async()=>{const l=await this._fetch(`${this.apiUrl}${e}`,{method:r,headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await he(l,`fetch ${e}`),l})).json();if(!c||!c[s])break;yield c[s];const u=c.cursors;if(!u||!u.next)break;i.cursor=u.next}}_shouldSample(){return this.tracingSampleRate===void 0?!0:Math.random()<this.tracingSampleRate}_filterForSampling(e,n=!1){if(this.tracingSampleRate===void 0)return e;if(n){const r=[];for(const s of e)this.filteredPostUuids.has(s.trace_id)?s.id===s.trace_id&&this.filteredPostUuids.delete(s.trace_id):r.push(s);return r}else{const r=[];for(const s of e){const i=s.trace_id??s.id;this.filteredPostUuids.has(i)||(s.id===i?this._shouldSample()?r.push(s):this.filteredPostUuids.add(i):r.push(s))}return r}}async _getBatchSizeLimitBytes(){var n;const e=await this._ensureServerInfo();return this.batchSizeBytesLimit??((n=e==null?void 0:e.batch_ingest_config)==null?void 0:n.size_limit_bytes)??EL}async _getBatchSizeLimit(){var n;const e=await this._ensureServerInfo();return this.batchSizeLimit??((n=e==null?void 0:e.batch_ingest_config)==null?void 0:n.size_limit)??xL}async _getDatasetExamplesMultiPartSupport(){var n;return((n=(await this._ensureServerInfo()).instance_flags)==null?void 0:n.dataset_examples_multipart_enabled)??!1}drainAutoBatchQueue({batchSizeLimitBytes:e,batchSizeLimit:n}){const r=[];for(;this.autoBatchQueue.items.length>0;){const[s,i]=this.autoBatchQueue.pop({upToSizeBytes:e,upToSize:n});if(!s.length){i();break}const a=s.reduce((u,l)=>{const d=l.apiUrl??this.apiUrl,f=l.apiKey??this.apiKey,p=l.apiKey===this.apiKey&&l.apiUrl===this.apiUrl?"default":`${d}|${f}`;return u[p]||(u[p]=[]),u[p].push(l),u},{}),o=[];for(const[u,l]of Object.entries(a)){const d=this._processBatch(l,{apiUrl:u==="default"?void 0:u.split("|")[0],apiKey:u==="default"?void 0:u.split("|")[1]});o.push(d)}const c=Promise.all(o).finally(i);r.push(c)}return Promise.all(r)}static async _writeTraceToFallbackDir(e,n,r,s,i){try{const a=typeof n=="string"?Buffer.from(n,"utf8"):Buffer.from(n),o=JSON.stringify({version:1,endpoint:s,headers:r,body_base64:a.toString("base64")}),c=`trace_${Date.now()}_${cc().slice(0,8)}.json`,u=ya.join(e,c);if(ls._fallbackDirsCreated.has(e)||(await rE(e),ls._fallbackDirsCreated.add(e)),i!==void 0&&i>0)try{const d=(await Z2(e)).filter(h=>h.startsWith("trace_")&&h.endsWith(".json"));let f=0;for(const h of d){const{size:p}=await q2(ya.join(e,h));f+=p}if(f>=i){console.warn(`Could not write trace to fallback dir ${e} as it's already over size limit (${f} bytes >= ${i} bytes). Increase LANGSMITH_FAILED_TRACES_MAX_MB if possible.`);return}}catch{}await ly(u,o),console.warn(`LangSmith trace upload failed; data saved to ${u} for later replay.`)}catch(a){console.error(`LangSmith tracing error: could not write trace to fallback dir ${e}:`,a)}}async _processBatch(e,n){var s,i;if(!e.length)return;const r=e.reduce((a,o)=>a+(o.size??0),0);try{if(this.langSmithToOTELTranslator!==void 0)this._sendBatchToOTELTranslator(e);else{const a={runCreates:e.filter(u=>u.action==="create").map(u=>u.item),runUpdates:e.filter(u=>u.action==="update").map(u=>u.item)},o=await this._ensureServerInfo();if(!this._multipartDisabled&&(((s=o==null?void 0:o.batch_ingest_config)==null?void 0:s.use_multipart_endpoint)??!0)){const u=!this._runCompressionDisabled&&((i=o==null?void 0:o.instance_flags)==null?void 0:i.gzip_body_enabled);try{await this.multipartIngestRuns(a,{...n,useGzip:u,sizeBytes:r})}catch(l){if(kp(l))this._multipartDisabled=!0,await this.batchIngestRuns(a,{...n,sizeBytes:r});else throw l}}else await this.batchIngestRuns(a,{...n,sizeBytes:r})}}catch(a){console.error("Error exporting batch:",a)}}_sendBatchToOTELTranslator(e){if(this.langSmithToOTELTranslator!==void 0){const n=new Map,r=[];for(const s of e)s.item.id&&s.otelContext&&(n.set(s.item.id,s.otelContext),s.action==="create"?r.push({operation:"post",id:s.item.id,trace_id:s.item.trace_id??s.item.id,run:s.item}):r.push({operation:"patch",id:s.item.id,trace_id:s.item.trace_id??s.item.id,run:s.item}));this.langSmithToOTELTranslator.exportBatch(r,n)}}async processRunOperation(e){clearTimeout(this.autoBatchTimeout),this.autoBatchTimeout=void 0,e.item=b0(e.item,this.cachedLSEnvVarsForMetadata,this.omitTracedRuntimeInfo);const n=this.autoBatchQueue.push(e);if(this.manualFlushMode)return n;const r=await this._getBatchSizeLimitBytes(),s=await this._getBatchSizeLimit();return(this.autoBatchQueue.sizeBytes>r||this.autoBatchQueue.items.length>s)&&this._trackDrain(this.drainAutoBatchQueue({batchSizeLimitBytes:r,batchSizeLimit:s})),this.autoBatchQueue.items.length>0&&(this.autoBatchTimeout=setTimeout(()=>{this.autoBatchTimeout=void 0,this._trackDrain(this.drainAutoBatchQueue({batchSizeLimitBytes:r,batchSizeLimit:s}))},this.autoBatchAggregationDelayMs)),n}async _getServerInfo(){const n=await(await this.caller.call(async()=>{const r=await this._fetch(`${this.apiUrl}/info`,{method:"GET",headers:{...this._mergedHeaders,Accept:"application/json"},signal:AbortSignal.timeout(IL),...this.fetchOptions});return await he(r,"get server info"),r})).json();return this.debug&&console.log(`
|
|
28
|
-
=== LangSmith Server Configuration ===
|
|
29
|
-
`+JSON.stringify(n,null,2)+`
|
|
30
|
-
`),n}async _ensureServerInfo(){return this._getServerInfoPromise===void 0&&(this._getServerInfoPromise=(async()=>{if(this._serverInfo===void 0)try{this._serverInfo=await this._getServerInfo()}catch(e){console.warn(`[LANGSMITH]: Failed to fetch info on supported operations. Falling back to batch operations and default limits. Info: ${e.status??"Unspecified status code"} ${e.message}`)}return this._serverInfo??{}})()),this._getServerInfoPromise.then(e=>(this._serverInfo===void 0&&(this._getServerInfoPromise=void 0),e))}async _getSettings(){return this.settings||(this.settings=this._get("/settings")),await this.settings}async flush(){const e=await this._getBatchSizeLimitBytes(),n=await this._getBatchSizeLimit();await this.drainAutoBatchQueue({batchSizeLimitBytes:e,batchSizeLimit:n})}_cloneCurrentOTELContext(){const e=lE(),n=lM();if(this.langSmithToOTELTranslator!==void 0){const r=e.getActiveSpan();if(r)return e.setSpan(n.active(),r)}}async createRun(e,n){if(!this._filterForSampling([e]).length)return;const r={...this._mergedHeaders,"Content-Type":"application/json"},s=e.project_name;delete e.project_name;const i=await this.prepareRunCreateOrUpdateInputs({session_name:s,...e,start_time:e.start_time??Date.now()});if(this.autoBatchTracing&&i.trace_id!==void 0&&i.dotted_order!==void 0){const c=this._cloneCurrentOTELContext();this.processRunOperation({action:"create",item:i,otelContext:c,apiKey:n==null?void 0:n.apiKey,apiUrl:n==null?void 0:n.apiUrl}).catch(console.error);return}const a=b0(i,this.cachedLSEnvVarsForMetadata,this.omitTracedRuntimeInfo);(n==null?void 0:n.apiKey)!==void 0&&(r["x-api-key"]=n.apiKey),(n==null?void 0:n.workspaceId)!==void 0&&(r["x-tenant-id"]=n.workspaceId);const o=Cn(a,`Creating run with id: ${a.id}`);await this.caller.call(async()=>{const c=await this._fetch(`${(n==null?void 0:n.apiUrl)??this.apiUrl}/runs`,{method:"POST",headers:r,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await he(c,"create run",!0),c})}async batchIngestRuns({runCreates:e,runUpdates:n},r){if(e===void 0&&n===void 0)return;let s=await Promise.all((e==null?void 0:e.map(c=>this.prepareRunCreateOrUpdateInputs(c)))??[]),i=await Promise.all((n==null?void 0:n.map(c=>this.prepareRunCreateOrUpdateInputs(c)))??[]);if(s.length>0&&i.length>0){const c=s.reduce((l,d)=>(d.id&&(l[d.id]=d),l),{}),u=[];for(const l of i)l.id!==void 0&&c[l.id]?c[l.id]={...c[l.id],...l}:u.push(l);s=Object.values(c),i=u}const a={post:s,patch:i};if(!a.post.length&&!a.patch.length)return;const o={post:[],patch:[]};for(const c of["post","patch"]){const u=c,l=a[u].reverse();let d=l.pop();for(;d!==void 0;)o[u].push(d),d=l.pop()}if(o.post.length>0||o.patch.length>0){const c=o.post.map(u=>u.id).concat(o.patch.map(u=>u.id)).join(",");await this._postBatchIngestRuns(await this._serializeBody(o,`Ingesting runs with ids: ${c}`),r)}}async _postBatchIngestRuns(e,n){const r={...this._mergedHeaders,"Content-Type":"application/json",Accept:"application/json"};(n==null?void 0:n.apiKey)!==void 0&&(r["x-api-key"]=n.apiKey),await this.batchIngestCaller.callWithOptions({sizeBytes:n==null?void 0:n.sizeBytes},async()=>{const s=await this._fetch(`${(n==null?void 0:n.apiUrl)??this.apiUrl}/runs/batch`,{method:"POST",headers:r,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:e});return await he(s,"batch create run",!0),s})}async multipartIngestRuns({runCreates:e,runUpdates:n},r){if(e===void 0&&n===void 0)return;const s={};let i=[];for(const d of e??[]){const f=await this.prepareRunCreateOrUpdateInputs(d);f.id!==void 0&&f.attachments!==void 0&&(s[f.id]=f.attachments),delete f.attachments,i.push(f)}let a=[];for(const d of n??[])a.push(await this.prepareRunCreateOrUpdateInputs(d));if(i.find(d=>d.trace_id===void 0||d.dotted_order===void 0)!==void 0)throw new Error('Multipart ingest requires "trace_id" and "dotted_order" to be set when creating a run');if(a.find(d=>d.trace_id===void 0||d.dotted_order===void 0)!==void 0)throw new Error('Multipart ingest requires "trace_id" and "dotted_order" to be set when updating a run');if(i.length>0&&a.length>0){const d=i.reduce((h,p)=>(p.id&&(h[p.id]=p),h),{}),f=[];for(const h of a)h.id!==void 0&&d[h.id]?d[h.id]={...d[h.id],...h}:f.push(h);i=Object.values(d),a=f}if(i.length===0&&a.length===0)return;const u=[],l=[];for(const[d,f]of[["post",i],["patch",a]])for(const h of f){const{inputs:p,outputs:g,events:y,extra:b,error:_,serialized:w,attachments:v,...A}=h,S={inputs:p,outputs:g,events:y,extra:b,error:_,serialized:w},x=await this._serializeBody(A,`Serializing for multipart ingestion of run with id: ${A.id}`);l.push({name:`${d}.${A.id}`,payload:new Blob([x],{type:`application/json; length=${x.length}`})});for(const[E,$]of Object.entries(S)){if($===void 0)continue;const k=await this._serializeBody($,`Serializing ${E} for multipart ingestion of run with id: ${A.id}`);l.push({name:`${d}.${A.id}.${E}`,payload:new Blob([k],{type:`application/json; length=${k.length}`})})}if(A.id!==void 0){const E=s[A.id];if(E){delete s[A.id];for(const[$,k]of Object.entries(E)){let C,D;if(Array.isArray(k)?[C,D]=k:(C=k.mimeType,D=k.data),$.includes(".")){console.warn(`Skipping attachment '${$}' for run ${A.id}: Invalid attachment name. Attachment names must not contain periods ('.'). Please rename the attachment and try again.`);continue}l.push({name:`attachment.${A.id}.${$}`,payload:new Blob([D],{type:`${C}; length=${D.byteLength}`})})}}}u.push(`trace=${A.trace_id},id=${A.id}`)}await this._sendMultipartRequest(l,u.join("; "),r)}async _createNodeFetchBody(e,n){const r=[];for(const a of e)r.push(new Blob([`--${n}\r
|
|
31
|
-
`])),r.push(new Blob([`Content-Disposition: form-data; name="${a.name}"\r
|
|
32
|
-
`,`Content-Type: ${a.payload.type}\r
|
|
33
|
-
\r
|
|
34
|
-
`])),r.push(a.payload),r.push(new Blob([`\r
|
|
35
|
-
`]));return r.push(new Blob([`--${n}--\r
|
|
36
|
-
`])),await new Blob(r).arrayBuffer()}async _createMultipartStream(e,n){const r=new TextEncoder;return new ReadableStream({async start(i){const a=async o=>{typeof o=="string"?i.enqueue(r.encode(o)):i.enqueue(o)};for(const o of e){await a(`--${n}\r
|
|
37
|
-
`),await a(`Content-Disposition: form-data; name="${o.name}"\r
|
|
38
|
-
`),await a(`Content-Type: ${o.payload.type}\r
|
|
39
|
-
\r
|
|
40
|
-
`);const u=o.payload.stream().getReader();try{let l;for(;!(l=await u.read()).done;)i.enqueue(l.value)}finally{u.releaseLock()}await a(`\r
|
|
41
|
-
`)}await a(`--${n}--\r
|
|
42
|
-
`),i.close()}})}async _sendMultipartRequest(e,n,r){const s="----LangSmithFormBoundary"+Math.random().toString(36).slice(2),i=()=>this._createNodeFetchBody(e,s),a=()=>this._createMultipartStream(e,s),o=async c=>this.batchIngestCaller.callWithOptions({sizeBytes:r==null?void 0:r.sizeBytes},async()=>{const u=await c(),l={...this._mergedHeaders,"Content-Type":`multipart/form-data; boundary=${s}`};(r==null?void 0:r.apiKey)!==void 0&&(l["x-api-key"]=r.apiKey);let d=u;r!=null&&r.useGzip&&typeof u=="object"&&"pipeThrough"in u&&(d=u.pipeThrough(new CompressionStream("gzip")),l["Content-Encoding"]="gzip");const f=await this._fetch(`${(r==null?void 0:r.apiUrl)??this.apiUrl}/runs/multipart`,{method:"POST",headers:l,body:d,duplex:"half",signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await he(f,"Failed to send multipart request",!0),f});try{let c,u=!1;y2()&&!this.multipartStreamingDisabled&&dy()!=="bun"?(u=!0,c=await o(a)):c=await o(i),(!this.multipartStreamingDisabled||u)&&c.status===422&&((r==null?void 0:r.apiUrl)??this.apiUrl)!==rg&&(console.warn(`Streaming multipart upload to ${(r==null?void 0:r.apiUrl)??this.apiUrl}/runs/multipart failed. This usually means the host does not support chunked uploads. Retrying with a buffered upload for operation "${n}".`),this.multipartStreamingDisabled=!0,c=await o(i))}catch(c){if(kp(c))throw c;if(console.warn(`${c.message.trim()}
|
|
43
|
-
|
|
44
|
-
Context: ${n}`),this.failedTracesDir){const u=await this._createNodeFetchBody(e,s).catch(()=>null);u&&await ls._writeTraceToFallbackDir(this.failedTracesDir,u,{"Content-Type":`multipart/form-data; boundary=${s}`},"runs/multipart",this.failedTracesMaxBytes)}}}async updateRun(e,n,r){Ne(e),n.inputs&&(n.inputs=await this.processInputs(n.inputs)),n.outputs&&(n.outputs=await this.processOutputs(n.outputs)),n.extra!=null&&"metadata"in n.extra&&(n.extra={...n.extra,metadata:await this.processMetadata(n.extra.metadata)}),n.events&&(n.events=this._filterNewTokenEvents(n.events));const s={...n,id:e};if(!this._filterForSampling([s],!0).length)return;if(this.autoBatchTracing&&s.trace_id!==void 0&&s.dotted_order!==void 0){const o=this._cloneCurrentOTELContext();if(n.end_time!==void 0&&s.parent_run_id===void 0&&this.blockOnRootRunFinalization&&!this.manualFlushMode){await this.processRunOperation({action:"update",item:s,otelContext:o,apiKey:r==null?void 0:r.apiKey,apiUrl:r==null?void 0:r.apiUrl}).catch(console.error);return}else this.processRunOperation({action:"update",item:s,otelContext:o,apiKey:r==null?void 0:r.apiKey,apiUrl:r==null?void 0:r.apiUrl}).catch(console.error);return}const i={...this._mergedHeaders,"Content-Type":"application/json"};(r==null?void 0:r.apiKey)!==void 0&&(i["x-api-key"]=r.apiKey),(r==null?void 0:r.workspaceId)!==void 0&&(i["x-tenant-id"]=r.workspaceId);const a=Cn(n,`Serializing payload to update run with id: ${e}`);await this.caller.call(async()=>{const o=await this._fetch(`${(r==null?void 0:r.apiUrl)??this.apiUrl}/runs/${e}`,{method:"PATCH",headers:i,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await he(o,"update run",!0),o})}async readRun(e,{loadChildRuns:n}={loadChildRuns:!1}){Ne(e);let r=Ca(await this._get(`/runs/${e}`));return n&&(r=await this._loadChildRuns(r)),r}async getRunUrl({runId:e,run:n,projectOpts:r}){if(n!==void 0){let s;n.session_id?s=n.session_id:r!=null&&r.projectName?s=(await this.readProject({projectName:r==null?void 0:r.projectName})).id:r!=null&&r.projectId?s=r==null?void 0:r.projectId:s=(await this.readProject({projectName:Pt("PROJECT")||"default"})).id;const i=await this._getTenantId();return`${this.getHostUrl()}/o/${i}/projects/p/${s}/r/${n.id}?poll=true`}else if(e!==void 0){const s=await this.readRun(e);if(!s.app_path)throw new Error(`Run ${e} has no app_path`);return`${this.getHostUrl()}${s.app_path}`}else throw new Error("Must provide either runId or run")}async _loadChildRuns(e){var i;const n=await AL(this.listRuns({isRoot:!1,projectId:e.session_id,traceId:e.trace_id})),r={},s={};n.sort((a,o)=>((a==null?void 0:a.dotted_order)??"").localeCompare((o==null?void 0:o.dotted_order)??""));for(const a of n){if(a.parent_run_id===null||a.parent_run_id===void 0)throw new Error(`Child run ${a.id} has no parent`);(i=a.dotted_order)!=null&&i.startsWith(e.dotted_order??"")&&a.id!==e.id&&(a.parent_run_id in r||(r[a.parent_run_id]=[]),r[a.parent_run_id].push(a),s[a.id]=a)}e.child_runs=r[e.id]||[];for(const a in r)a!==e.id&&(s[a].child_runs=r[a]);return e}async*listRuns(e){const{projectId:n,projectName:r,parentRunId:s,traceId:i,referenceExampleId:a,startTime:o,executionOrder:c,isRoot:u,runType:l,error:d,id:f,query:h,filter:p,traceFilter:g,treeFilter:y,limit:b,select:_,order:w}=e;let v=[];if(n&&(v=Array.isArray(n)?n:[n]),r){const E=Array.isArray(r)?r:[r],$=await Promise.all(E.map(k=>this.readProject({projectName:k}).then(C=>C.id)));v.push(...$)}const A=["app_path","completion_cost","completion_tokens","dotted_order","end_time","error","events","extra","feedback_stats","first_token_time","id","inputs","name","outputs","parent_run_id","parent_run_ids","prompt_cost","prompt_tokens","reference_example_id","run_type","session_id","start_time","status","tags","total_cost","total_tokens","trace_id"],S={session:v.length?v:null,run_type:l,reference_example:a,query:h,filter:p,trace_filter:g,tree_filter:y,execution_order:c,parent_run:s,start_time:o?o.toISOString():null,error:d,id:f,limit:b,trace:i,select:_||A,is_root:u,order:w};S.select.includes("child_run_ids")&&Dd("Deprecated: 'child_run_ids' in the listRuns select parameter is deprecated and will be removed in a future version.");let x=0;for await(const E of this._getCursorPaginatedList("/runs/query",S)){const $=E.map(Ca);if(b){if(x>=b)break;if($.length+x>b){yield*$.slice(0,b-x);break}x+=$.length,yield*$}else yield*$}}async*listGroupRuns(e){const{projectId:n,projectName:r,groupBy:s,filter:i,startTime:a,endTime:o,limit:c,offset:u}=e,d={session_id:n||(await this.readProject({projectName:r})).id,group_by:s,filter:i,start_time:a?a.toISOString():null,end_time:o?o.toISOString():null,limit:Number(c)||100};let f=Number(u)||0;const h="/runs/group",p=`${this.apiUrl}${h}`;for(;;){const g={...d,offset:f},y=Object.fromEntries(Object.entries(g).filter(([S,x])=>x!==void 0)),b=JSON.stringify(y),w=await(await this.caller.call(async()=>{const S=await this._fetch(p,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:b});return await he(S,`Failed to fetch ${h}`),S})).json(),{groups:v,total:A}=w;if(v.length===0)break;for(const S of v)yield S;if(f+=v.length,f>=A)break}}async*readThread(e){const{threadId:n,projectId:r,projectName:s,isRoot:i=!0,limit:a,filter:o,order:c="asc"}=e;if(!r&&!s)throw new Error("threadId requires projectId or projectName");const u=`eq(thread_id, ${JSON.stringify(n)})`,l=o?`and(${u}, ${o})`:u;yield*this.listRuns({projectId:r??void 0,projectName:s??void 0,isRoot:i,limit:a,filter:l,order:c})}async listThreads(e){const{projectId:n,projectName:r,limit:s,offset:i=0,filter:a,startTime:o,isRoot:c=!0}=e;if(!n&&!r)throw new Error("Either projectId or projectName must be provided");if(n&&r)throw new Error("Provide exactly one of projectId or projectName");const u=n??(await this.readProject({projectName:r})).id,l=o??new Date(Date.now()-1*24*60*60*1e3),f={session:[u],is_root:c,limit:100,order:"desc",select:["id","name","status","start_time","end_time","thread_id","trace_id","run_type","error","tags","session_id","parent_run_id","total_tokens","total_cost","dotted_order","reference_example_id","feedback_stats","app_path","completion_cost","completion_tokens","prompt_cost","prompt_tokens","first_token_time"],start_time:l.toISOString()};a!=null&&(f.filter=a);const h=new Map;for await(const b of this._getCursorPaginatedList("/runs/query",f))for(const _ of b){const w=Ca(_),v=w.thread_id;if(v){const A=h.get(v)??[];A.push(w),h.set(v,A)}}const p=[];for(const[b,_]of h.entries()){_.sort((x,E)=>{const $=x,k=E,C=$.start_time??"",D=k.start_time??"";if(C!==D)return C.localeCompare(D);const B=$.dotted_order??"",z=k.dotted_order??"";return B.localeCompare(z)});const v=[..._.map(x=>x.start_time).filter(Boolean)].sort(),A=v.length?v[0]:"",S=v.length?v[v.length-1]:"";p.push({thread_id:b,runs:_,count:_.length,filter:"",total_tokens:0,total_cost:null,min_start_time:A,max_start_time:S,latency_p50:0,latency_p99:0,feedback_stats:null,first_inputs:"",last_outputs:"",last_error:null})}p.sort((b,_)=>{const w=b.max_start_time??"";return(_.max_start_time??"").localeCompare(w)});const g=i>0?p.slice(i):p;return s!==void 0?g.slice(0,s):g}async getRunStats({id:e,trace:n,parentRun:r,runType:s,projectNames:i,projectIds:a,referenceExampleIds:o,startTime:c,endTime:u,error:l,query:d,filter:f,traceFilter:h,treeFilter:p,isRoot:g,dataSourceType:y}){let b=a||[];i&&(b=[...a||[],...await Promise.all(i.map(x=>this.readProject({projectName:x}).then(E=>E.id)))]);const w=Object.fromEntries(Object.entries({id:e,trace:n,parent_run:r,run_type:s,session:b,reference_example:o,start_time:c,end_time:u,error:l,query:d,filter:f,trace_filter:h,tree_filter:p,is_root:g,data_source_type:y}).filter(([x,E])=>E!==void 0)),v=JSON.stringify(w);return await(await this.caller.call(async()=>{const x=await this._fetch(`${this.apiUrl}/runs/stats`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:v});return await he(x,"get run stats"),x})).json()}async shareRun(e,{shareId:n}={}){const r={run_id:e,share_token:n||cc()};Ne(e);const s=JSON.stringify(r),a=await(await this.caller.call(async()=>{const o=await this._fetch(`${this.apiUrl}/runs/${e}/share`,{method:"PUT",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await he(o,"share run"),o})).json();if(a===null||!("share_token"in a))throw new Error("Invalid response from server");return`${this.getHostUrl()}/public/${a.share_token}/r`}async unshareRun(e){Ne(e),await this.caller.call(async()=>{const n=await this._fetch(`${this.apiUrl}/runs/${e}/share`,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await he(n,"unshare run",!0),n})}async readRunSharedLink(e){Ne(e);const r=await(await this.caller.call(async()=>{const s=await this._fetch(`${this.apiUrl}/runs/${e}/share`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await he(s,"read run shared link"),s})).json();if(!(r===null||!("share_token"in r)))return`${this.getHostUrl()}/public/${r.share_token}/r`}async listSharedRuns(e,{runIds:n}={}){const r=new URLSearchParams({share_token:e});if(n!==void 0)for(const a of n)r.append("id",a);return Ne(e),(await(await this.caller.call(async()=>{const a=await this._fetch(`${this.apiUrl}/public/${e}/runs${r}`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await he(a,"list shared runs"),a})).json()).map(Ca)}async readDatasetSharedSchema(e,n){if(!e&&!n)throw new Error("Either datasetId or datasetName must be given");e||(e=(await this.readDataset({datasetName:n})).id),Ne(e);const s=await(await this.caller.call(async()=>{const i=await this._fetch(`${this.apiUrl}/datasets/${e}/share`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await he(i,"read dataset shared schema"),i})).json();return s.url=`${this.getHostUrl()}/public/${s.share_token}/d`,s}async shareDataset(e,n){if(!e&&!n)throw new Error("Either datasetId or datasetName must be given");e||(e=(await this.readDataset({datasetName:n})).id);const r={dataset_id:e};Ne(e);const s=JSON.stringify(r),a=await(await this.caller.call(async()=>{const o=await this._fetch(`${this.apiUrl}/datasets/${e}/share`,{method:"PUT",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await he(o,"share dataset"),o})).json();return a.url=`${this.getHostUrl()}/public/${a.share_token}/d`,a}async unshareDataset(e){Ne(e),await this.caller.call(async()=>{const n=await this._fetch(`${this.apiUrl}/datasets/${e}/share`,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await he(n,"unshare dataset",!0),n})}async readSharedDataset(e){return Ne(e),await(await this.caller.call(async()=>{const s=await this._fetch(`${this.apiUrl}/public/${e}/datasets`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await he(s,"read shared dataset"),s})).json()}async listSharedExamples(e,n){const r={};n!=null&&n.exampleIds&&(r.id=n.exampleIds);const s=new URLSearchParams;Object.entries(r).forEach(([o,c])=>{Array.isArray(c)?c.forEach(u=>s.append(o,u)):s.append(o,c)});const i=await this.caller.call(async()=>{const o=await this._fetch(`${this.apiUrl}/public/${e}/examples?${s.toString()}`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await he(o,"list shared examples"),o}),a=await i.json();if(!i.ok)throw"detail"in a?new Error(`Failed to list shared examples.
|
|
45
|
-
Status: ${i.status}
|
|
46
|
-
Message: ${Array.isArray(a.detail)?a.detail.join(`
|
|
47
|
-
`):"Unspecified error"}`):new Error(`Failed to list shared examples: ${i.status} ${i.statusText}`);return a.map(o=>({...o,_hostUrl:this.getHostUrl()}))}async createProject({projectName:e,description:n=null,metadata:r=null,upsert:s=!1,projectExtra:i=null,referenceDatasetId:a=null,numExamples:o=null,numRepetitions:c=null,evaluatorKeys:u=null}){const l=s?"?upsert=true":"",d=`${this.apiUrl}/sessions${l}`,f=i||{};r&&(f.metadata=r);const h={name:e,extra:f,description:n};a!==null&&(h.reference_dataset_id=a),o!=null&&(h.num_examples=o),c!=null&&(h.num_repetitions=c),u!=null&&u.length>0&&(h.evaluator_keys=u);const p=JSON.stringify(h);return await(await this.caller.call(async()=>{const b=await this._fetch(d,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:p});return await he(b,"create project"),b})).json()}async updateProject(e,{name:n=null,description:r=null,metadata:s=null,projectExtra:i=null,endTime:a=null}){const o=`${this.apiUrl}/sessions/${e}`;let c=i;s&&(c={...c||{},metadata:s});const u=JSON.stringify({name:n,extra:c,description:r,end_time:a?new Date(a).toISOString():null});return await(await this.caller.call(async()=>{const f=await this._fetch(o,{method:"PATCH",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:u});return await he(f,"update project"),f})).json()}async hasProject({projectId:e,projectName:n}){let r="/sessions";const s=new URLSearchParams;if(e!==void 0&&n!==void 0)throw new Error("Must provide either projectName or projectId, not both");if(e!==void 0)Ne(e),r+=`/${e}`;else if(n!==void 0)s.append("name",n);else throw new Error("Must provide projectName or projectId");const i=await this.caller.call(async()=>{const a=await this._fetch(`${this.apiUrl}${r}?${s}`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await he(a,"has project"),a});try{const a=await i.json();return i.ok?Array.isArray(a)?a.length>0:!0:!1}catch{return!1}}async readProject({projectId:e,projectName:n,includeStats:r}){let s="/sessions";const i=new URLSearchParams;if(e!==void 0&&n!==void 0)throw new Error("Must provide either projectName or projectId, not both");if(e!==void 0)Ne(e),s+=`/${e}`;else if(n!==void 0)i.append("name",n);else throw new Error("Must provide projectName or projectId");r!==void 0&&i.append("include_stats",r.toString());const a=await this._get(s,i);let o;if(Array.isArray(a)){if(a.length===0)throw new Error(`Project[id=${e}, name=${n}] not found`);o=a[0]}else o=a;return o}async getProjectUrl({projectId:e,projectName:n}){if(e===void 0&&n===void 0)throw new Error("Must provide either projectName or projectId");const r=await this.readProject({projectId:e,projectName:n}),s=await this._getTenantId();return`${this.getHostUrl()}/o/${s}/projects/p/${r.id}`}async getDatasetUrl({datasetId:e,datasetName:n}){if(e===void 0&&n===void 0)throw new Error("Must provide either datasetName or datasetId");const r=await this.readDataset({datasetId:e,datasetName:n}),s=await this._getTenantId();return`${this.getHostUrl()}/o/${s}/datasets/${r.id}`}async _getTenantId(){if(this._tenantId!==null)return this._tenantId;const e=new URLSearchParams({limit:"1"});for await(const n of this._getPaginated("/sessions",e))return this._tenantId=n[0].tenant_id,n[0].tenant_id;throw new Error("No projects found to resolve tenant.")}async*listProjects({projectIds:e,name:n,nameContains:r,referenceDatasetId:s,referenceDatasetName:i,includeStats:a,datasetVersion:o,referenceFree:c,metadata:u}={}){const l=new URLSearchParams;if(e!==void 0)for(const d of e)l.append("id",d);if(n!==void 0&&l.append("name",n),r!==void 0&&l.append("name_contains",r),s!==void 0)l.append("reference_dataset",s);else if(i!==void 0){const d=await this.readDataset({datasetName:i});l.append("reference_dataset",d.id)}a!==void 0&&l.append("include_stats",a.toString()),o!==void 0&&l.append("dataset_version",o),c!==void 0&&l.append("reference_free",c.toString()),u!==void 0&&l.append("metadata",JSON.stringify(u));for await(const d of this._getPaginated("/sessions",l))yield*d}async deleteProject({projectId:e,projectName:n}){let r;if(e===void 0&&n===void 0)throw new Error("Must provide projectName or projectId");if(e!==void 0&&n!==void 0)throw new Error("Must provide either projectName or projectId, not both");e===void 0?r=(await this.readProject({projectName:n})).id:r=e,Ne(r),await this.caller.call(async()=>{const s=await this._fetch(`${this.apiUrl}/sessions/${r}`,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await he(s,`delete session ${r} (${n})`,!0),s})}async uploadCsv({csvFile:e,fileName:n,inputKeys:r,outputKeys:s,description:i,dataType:a,name:o}){const c=`${this.apiUrl}/datasets/upload`,u=new FormData,l=new Blob([e],{type:"text/csv"});return u.append("file",l,n),r.forEach(h=>{u.append("input_keys",h)}),s.forEach(h=>{u.append("output_keys",h)}),i&&u.append("description",i),a&&u.append("data_type",a),o&&u.append("name",o),await(await this.caller.call(async()=>{const h=await this._fetch(c,{method:"POST",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:u});return await he(h,"upload CSV"),h})).json()}async createDataset(e,{description:n,dataType:r,inputsSchema:s,outputsSchema:i,metadata:a}={}){const o={name:e,description:n,extra:{source:"sdk",...a?{metadata:a}:{}}};r&&(o.data_type=r),s&&(o.inputs_schema_definition=s),i&&(o.outputs_schema_definition=i);const c=JSON.stringify(o);return await(await this.caller.call(async()=>{const d=await this._fetch(`${this.apiUrl}/datasets`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await he(d,"create dataset"),d})).json()}async readDataset({datasetId:e,datasetName:n}){let r="/datasets";const s=new URLSearchParams({limit:"1"});if(e&&n)throw new Error("Must provide either datasetName or datasetId, not both");if(e)Ne(e),r+=`/${e}`;else if(n)s.append("name",n);else throw new Error("Must provide datasetName or datasetId");const i=await this._get(r,s);let a;if(Array.isArray(i)){if(i.length===0)throw new Error(`Dataset[id=${e}, name=${n}] not found`);a=i[0]}else a=i;return a}async hasDataset({datasetId:e,datasetName:n}){try{return await this.readDataset({datasetId:e,datasetName:n}),!0}catch(r){if(r instanceof Error&&r.message.toLocaleLowerCase().includes("not found"))return!1;throw r}}async diffDatasetVersions({datasetId:e,datasetName:n,fromVersion:r,toVersion:s}){let i=e;if(i===void 0&&n===void 0)throw new Error("Must provide either datasetName or datasetId");if(i!==void 0&&n!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");i===void 0&&(i=(await this.readDataset({datasetName:n})).id);const a=new URLSearchParams({from_version:typeof r=="string"?r:r.toISOString(),to_version:typeof s=="string"?s:s.toISOString()});return await this._get(`/datasets/${i}/versions/diff`,a)}async readDatasetOpenaiFinetuning({datasetId:e,datasetName:n}){const r="/datasets";if(e===void 0)if(n!==void 0)e=(await this.readDataset({datasetName:n})).id;else throw new Error("Must provide either datasetName or datasetId");return(await(await this._getResponse(`${r}/${e}/openai_ft`)).text()).trim().split(`
|
|
48
|
-
`).map(o=>JSON.parse(o))}async*listDatasets({limit:e=100,offset:n=0,datasetIds:r,datasetName:s,datasetNameContains:i,metadata:a}={}){const o="/datasets",c=new URLSearchParams({limit:e.toString(),offset:n.toString()});if(r!==void 0)for(const u of r)c.append("id",u);s!==void 0&&c.append("name",s),i!==void 0&&c.append("name_contains",i),a!==void 0&&c.append("metadata",JSON.stringify(a));for await(const u of this._getPaginated(o,c))yield*u}async updateDataset(e){const{datasetId:n,datasetName:r,...s}=e;if(!n&&!r)throw new Error("Must provide either datasetName or datasetId");const i=n??(await this.readDataset({datasetName:r})).id;Ne(i);const a=JSON.stringify(s);return await(await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/datasets/${i}`,{method:"PATCH",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await he(c,"update dataset"),c})).json()}async updateDatasetTag(e){const{datasetId:n,datasetName:r,asOf:s,tag:i}=e;if(!n&&!r)throw new Error("Must provide either datasetName or datasetId");const a=n??(await this.readDataset({datasetName:r})).id;Ne(a);const o=JSON.stringify({as_of:typeof s=="string"?s:s.toISOString(),tag:i});await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/datasets/${a}/tags`,{method:"PUT",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await he(c,"update dataset tags",!0),c})}async deleteDataset({datasetId:e,datasetName:n}){let r="/datasets",s=e;if(e!==void 0&&n!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");if(n!==void 0&&(s=(await this.readDataset({datasetName:n})).id),s!==void 0)Ne(s),r+=`/${s}`;else throw new Error("Must provide datasetName or datasetId");await this.caller.call(async()=>{const i=await this._fetch(this.apiUrl+r,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await he(i,`delete ${r}`,!0),i})}async createExample(e,n,r){var l;if(S0(e)&&(n!==void 0||r!==void 0))throw new Error("Cannot provide outputs or options when using ExampleCreate object");let s=n?r==null?void 0:r.datasetId:e.dataset_id;const i=n?r==null?void 0:r.datasetName:e.dataset_name;if(s===void 0&&i===void 0)throw new Error("Must provide either datasetName or datasetId");if(s!==void 0&&i!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");s===void 0&&(s=(await this.readDataset({datasetName:i})).id);const a=(n?r==null?void 0:r.createdAt:e.created_at)||new Date;let o;S0(e)?o=e:o={inputs:e,outputs:n,created_at:a==null?void 0:a.toISOString(),id:r==null?void 0:r.exampleId,metadata:r==null?void 0:r.metadata,split:r==null?void 0:r.split,source_run_id:r==null?void 0:r.sourceRunId,use_source_run_io:r==null?void 0:r.useSourceRunIO,use_source_run_attachments:r==null?void 0:r.useSourceRunAttachments,attachments:r==null?void 0:r.attachments};const c=await this._uploadExamplesMultipart(s,[o]);return await this.readExample(((l=c.example_ids)==null?void 0:l[0])??cc())}async createExamples(e){if(Array.isArray(e)){if(e.length===0)return[];const _=e;let w=_[0].dataset_id;const v=_[0].dataset_name;if(w===void 0&&v===void 0)throw new Error("Must provide either datasetName or datasetId");if(w!==void 0&&v!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");w===void 0&&(w=(await this.readDataset({datasetName:v})).id);const A=await this._uploadExamplesMultipart(w,_);return await Promise.all(A.example_ids.map(x=>this.readExample(x)))}const{inputs:n,outputs:r,metadata:s,splits:i,sourceRunIds:a,useSourceRunIOs:o,useSourceRunAttachments:c,attachments:u,exampleIds:l,datasetId:d,datasetName:f}=e;if(n===void 0)throw new Error("Must provide inputs when using legacy parameters");let h=d;const p=f;if(h===void 0&&p===void 0)throw new Error("Must provide either datasetName or datasetId");if(h!==void 0&&p!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");h===void 0&&(h=(await this.readDataset({datasetName:p})).id);const g=n.map((_,w)=>({dataset_id:h,inputs:_,outputs:r==null?void 0:r[w],metadata:s==null?void 0:s[w],split:i==null?void 0:i[w],id:l==null?void 0:l[w],attachments:u==null?void 0:u[w],source_run_id:a==null?void 0:a[w],use_source_run_io:o==null?void 0:o[w],use_source_run_attachments:c==null?void 0:c[w]})),y=await this._uploadExamplesMultipart(h,g);return await Promise.all(y.example_ids.map(_=>this.readExample(_)))}async createLLMExample(e,n,r){return this.createExample({input:e},{output:n},r)}async createChatExample(e,n,r){const s=e.map(a=>p0(a)?m0(a):a),i=p0(n)?m0(n):n;return this.createExample({input:s},{output:i},r)}async readExample(e){Ne(e);const n=`/examples/${e}`,r=await this._get(n),{attachment_urls:s,...i}=r,a=i;return s&&(a.attachments=Object.entries(s).reduce((o,[c,u])=>(o[c.slice(11)]={presigned_url:u.presigned_url,mime_type:u.mime_type},o),{})),a}async*listExamples({datasetId:e,datasetName:n,exampleIds:r,asOf:s,splits:i,inlineS3Urls:a,metadata:o,limit:c,offset:u,filter:l,includeAttachments:d}={}){let f;if(e!==void 0&&n!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");if(e!==void 0)f=e;else if(n!==void 0)f=(await this.readDataset({datasetName:n})).id;else throw new Error("Must provide a datasetName or datasetId");const h=new URLSearchParams({dataset:f}),p=s?typeof s=="string"?s:s==null?void 0:s.toISOString():void 0;p&&h.append("as_of",p);const g=a??!0;if(h.append("inline_s3_urls",g.toString()),r!==void 0)for(const b of r)h.append("id",b);if(i!==void 0)for(const b of i)h.append("splits",b);if(o!==void 0){const b=JSON.stringify(o);h.append("metadata",b)}c!==void 0&&h.append("limit",c.toString()),u!==void 0&&h.append("offset",u.toString()),l!==void 0&&h.append("filter",l),d===!0&&["attachment_urls","outputs","metadata"].forEach(b=>h.append("select",b));let y=0;for await(const b of this._getPaginated("/examples",h)){for(const _ of b){const{attachment_urls:w,...v}=_,A=v;w&&(A.attachments=Object.entries(w).reduce((S,[x,E])=>(S[x.slice(11)]={presigned_url:E.presigned_url,mime_type:E.mime_type||void 0},S),{})),yield A,y++}if(c!==void 0&&y>=c)break}}async deleteExample(e){Ne(e);const n=`/examples/${e}`;await this.caller.call(async()=>{const r=await this._fetch(this.apiUrl+n,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await he(r,`delete ${n}`,!0),r})}async deleteExamples(e,n){if(e.forEach(r=>Ne(r)),n!=null&&n.hardDelete){const r=this._getPlatformEndpointPath("datasets/examples/delete");await this.caller.call(async()=>{const s=await this._fetch(`${this.apiUrl}${r}`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},body:JSON.stringify({example_ids:e,hard_delete:!0}),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await he(s,"hard delete examples",!0),s})}else{const r=new URLSearchParams;e.forEach(s=>r.append("example_ids",s)),await this.caller.call(async()=>{const s=await this._fetch(`${this.apiUrl}/examples?${r.toString()}`,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await he(s,"delete examples",!0),s})}}async updateExample(e,n){let r;n?r=e:r=e.id,Ne(r);let s;n?s={id:r,...n}:s=e;let i;return s.dataset_id!==void 0?i=s.dataset_id:i=(await this.readExample(r)).dataset_id,this._updateExamplesMultipart(i,[s])}async updateExamples(e){let n;return e[0].dataset_id===void 0?n=(await this.readExample(e[0].id)).dataset_id:n=e[0].dataset_id,this._updateExamplesMultipart(n,e)}async readDatasetVersion({datasetId:e,datasetName:n,asOf:r,tag:s}){let i;if(e?i=e:i=(await this.readDataset({datasetName:n})).id,Ne(i),r&&s||!r&&!s)throw new Error("Exactly one of asOf and tag must be specified.");const a=new URLSearchParams;return r!==void 0&&a.append("as_of",typeof r=="string"?r:r.toISOString()),s!==void 0&&a.append("tag",s),await(await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/datasets/${i}/version?${a.toString()}`,{method:"GET",headers:{...this._mergedHeaders},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await he(c,"read dataset version"),c})).json()}async listDatasetSplits({datasetId:e,datasetName:n,asOf:r}){let s;if(e===void 0&&n===void 0)throw new Error("Must provide dataset name or ID");if(e!==void 0&&n!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");e===void 0?s=(await this.readDataset({datasetName:n})).id:s=e,Ne(s);const i=new URLSearchParams,a=r?typeof r=="string"?r:r==null?void 0:r.toISOString():void 0;return a&&i.append("as_of",a),await this._get(`/datasets/${s}/splits`,i)}async updateDatasetSplits({datasetId:e,datasetName:n,splitName:r,exampleIds:s,remove:i=!1}){let a;if(e===void 0&&n===void 0)throw new Error("Must provide dataset name or ID");if(e!==void 0&&n!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");e===void 0?a=(await this.readDataset({datasetName:n})).id:a=e,Ne(a);const o={split_name:r,examples:s.map(u=>(Ne(u),u)),remove:i},c=JSON.stringify(o);await this.caller.call(async()=>{const u=await this._fetch(`${this.apiUrl}/datasets/${a}/splits`,{method:"PUT",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await he(u,"update dataset splits",!0),u})}async createFeedback(e,n,{score:r,value:s,correction:i,comment:a,sourceInfo:o,feedbackSourceType:c="api",sourceRunId:u,feedbackId:l,feedbackConfig:d,projectId:f,comparativeExperimentId:h,sessionId:p,startTime:g}){var v;if(!e&&!f)throw new Error("One of runId or projectId must be provided");if(e&&f)throw new Error("Only one of runId or projectId can be provided");const y={type:c??"api",metadata:o??{}};u!==void 0&&(y==null?void 0:y.metadata)!==void 0&&!y.metadata.__run&&(y.metadata.__run={run_id:u}),(y==null?void 0:y.metadata)!==void 0&&((v=y.metadata.__run)==null?void 0:v.run_id)!==void 0&&Ne(y.metadata.__run.run_id);const b={id:l??ZT(),run_id:e,key:n,score:v0(r),value:s,correction:i,comment:a,feedback_source:y,comparative_experiment_id:h,feedbackConfig:d,session_id:p??f,start_time:g},_=JSON.stringify(b),w=`${this.apiUrl}/feedback`;return await this.caller.call(async()=>{const A=await this._fetch(w,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:_});return await he(A,"create feedback",!0),A}),b}async updateFeedback(e,{score:n,value:r,correction:s,comment:i}){const a={};n!=null&&(a.score=v0(n)),r!=null&&(a.value=r),s!=null&&(a.correction=s),i!=null&&(a.comment=i),Ne(e);const o=JSON.stringify(a);await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/feedback/${e}`,{method:"PATCH",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await he(c,"update feedback",!0),c})}async readFeedback(e){Ne(e);const n=`/feedback/${e}`;return await this._get(n)}async deleteFeedback(e){Ne(e);const n=`/feedback/${e}`;await this.caller.call(async()=>{const r=await this._fetch(this.apiUrl+n,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await he(r,`delete ${n}`,!0),r})}async*listFeedback({runIds:e,feedbackKeys:n,feedbackSourceTypes:r}={}){const s=new URLSearchParams;if(e)for(const i of e)Ne(i),s.append("run",i);if(n)for(const i of n)s.append("key",i);if(r)for(const i of r)s.append("source",i);for await(const i of this._getPaginated("/feedback",s))yield*i}async createPresignedFeedbackToken(e,n,{expiration:r,feedbackConfig:s}={}){const i={run_id:e,feedback_key:n,feedback_config:s};r?typeof r=="string"?i.expires_at=r:(r!=null&&r.hours||r!=null&&r.minutes||r!=null&&r.days)&&(i.expires_in=r):i.expires_in={hours:3};const a=JSON.stringify(i);return await(await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/feedback/tokens`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await he(c,"create presigned feedback token"),c})).json()}async createComparativeExperiment({name:e,experimentIds:n,referenceDatasetId:r,createdAt:s,description:i,metadata:a,id:o}){var d;if(n.length===0)throw new Error("At least one experiment is required");if(r||(r=(await this.readProject({projectId:n[0]})).reference_dataset_id),!r==null)throw new Error("A reference dataset is required");const c={id:o,name:e,experiment_ids:n,reference_dataset_id:r,description:i,created_at:(d=s??new Date)==null?void 0:d.toISOString(),extra:{}};a&&(c.extra.metadata=a);const u=JSON.stringify(c);return(await this.caller.call(async()=>{const f=await this._fetch(`${this.apiUrl}/datasets/comparative`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:u});return await he(f,"create comparative experiment"),f})).json()}async*listPresignedFeedbackTokens(e){Ne(e);const n=new URLSearchParams({run_id:e});for await(const r of this._getPaginated("/feedback/tokens",n))yield*r}_selectEvalResults(e){let n;return"results"in e?n=e.results:Array.isArray(e)?n=e:n=[e],n}async _logEvaluationFeedback(e,n,r){const s=this._selectEvalResults(e),i=[];for(const a of s){let o=r||{};a.evaluatorInfo&&(o={...a.evaluatorInfo,...o});let c=null;a.targetRunId?c=a.targetRunId:n&&(c=n.id),i.push(await this.createFeedback(c,a.key,{score:a.score,value:a.value,comment:a.comment,correction:a.correction,sourceInfo:o,sourceRunId:a.sourceRunId,feedbackConfig:a.feedbackConfig,feedbackSourceType:"model",sessionId:n==null?void 0:n.session_id,startTime:n==null?void 0:n.start_time}))}return[s,i]}async logEvaluationFeedback(e,n,r){const[s]=await this._logEvaluationFeedback(e,n,r);return s}async createFeedbackConfig(e){const{feedbackKey:n,feedbackConfig:r,isLowerScoreBetter:s=!1}=e,i={feedback_key:n,feedback_config:r,is_lower_score_better:s};return(await this.caller.call(async()=>{const o=await this._fetch(`${this.apiUrl}/feedback-configs`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:JSON.stringify(i)});return await he(o,"create feedback config"),o})).json()}async*listFeedbackConfigs(e={}){const{feedbackKeys:n,nameContains:r,limit:s}=e,i=new URLSearchParams;n&&n.forEach(o=>{i.append("key",o)}),r&&i.append("name_contains",r),i.append("limit",(s!==void 0?Math.min(s,100):100).toString());let a=0;for await(const o of this._getPaginated("/feedback-configs",i))if(yield*o,a+=o.length,s!==void 0&&a>=s)break}async updateFeedbackConfig(e,n={}){const{feedbackConfig:r,isLowerScoreBetter:s}=n,i={feedback_key:e};return r!==void 0&&(i.feedback_config=r),s!==void 0&&(i.is_lower_score_better=s),(await this.caller.call(async()=>{const o=await this._fetch(`${this.apiUrl}/feedback-configs`,{method:"PATCH",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:JSON.stringify(i)});return await he(o,"update feedback config"),o})).json()}async deleteFeedbackConfig(e){const n=new URLSearchParams({feedback_key:e});await this.caller.call(async()=>{const r=await this._fetch(`${this.apiUrl}/feedback-configs?${n}`,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await he(r,"delete feedback config",!0),r})}async*listAnnotationQueues(e={}){const{queueIds:n,name:r,nameContains:s,limit:i}=e,a=new URLSearchParams;n&&n.forEach((c,u)=>{Ne(c,`queueIds[${u}]`),a.append("ids",c)}),r&&a.append("name",r),s&&a.append("name_contains",s),a.append("limit",(i!==void 0?Math.min(i,100):100).toString());let o=0;for await(const c of this._getPaginated("/annotation-queues",a))if(yield*c,o++,i!==void 0&&o>=i)break}async createAnnotationQueue(e){const{name:n,description:r,queueId:s,rubricInstructions:i,rubricItems:a}=e,o={name:n,description:r,id:s||cc(),rubric_instructions:i,rubric_items:a},c=JSON.stringify(Object.fromEntries(Object.entries(o).filter(([l,d])=>d!==void 0)));return(await this.caller.call(async()=>{const l=await this._fetch(`${this.apiUrl}/annotation-queues`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await he(l,"create annotation queue"),l})).json()}async readAnnotationQueue(e){return(await this.caller.call(async()=>{const r=await this._fetch(`${this.apiUrl}/annotation-queues/${Ne(e,"queueId")}`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await he(r,"read annotation queue"),r})).json()}async updateAnnotationQueue(e,n){const{name:r,description:s,rubricInstructions:i,rubricItems:a}=n,o={};r!==void 0&&(o.name=r),s!==void 0&&(o.description=s),i!==void 0&&(o.rubric_instructions=i),a!==void 0&&(o.rubric_items=a);const c=JSON.stringify(o);await this.caller.call(async()=>{const u=await this._fetch(`${this.apiUrl}/annotation-queues/${Ne(e,"queueId")}`,{method:"PATCH",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await he(u,"update annotation queue",!0),u})}async deleteAnnotationQueue(e){await this.caller.call(async()=>{const n=await this._fetch(`${this.apiUrl}/annotation-queues/${Ne(e,"queueId")}`,{method:"DELETE",headers:{...this._mergedHeaders,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await he(n,"delete annotation queue",!0),n})}async addRunsToAnnotationQueue(e,n){const r=JSON.stringify(n.map((s,i)=>Ne(s,`runIds[${i}]`).toString()));await this.caller.call(async()=>{const s=await this._fetch(`${this.apiUrl}/annotation-queues/${Ne(e,"queueId")}/runs`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:r});return await he(s,"add runs to annotation queue",!0),s})}async getRunFromAnnotationQueue(e,n){const r=`/annotation-queues/${Ne(e,"queueId")}/run`,i=await(await this.caller.call(async()=>{const a=await this._fetch(`${this.apiUrl}${r}/${n}`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await he(a,"get run from annotation queue"),a})).json();return Ca(i)}async*listRunsFromAnnotationQueue(e,n={}){const{status:r,limit:s}=n,i=new URLSearchParams,a=s!==void 0&&Number.isFinite(s)?Math.min(s,100):100;r&&i.append("status",r),i.append("limit",a.toString());let o=0;const c=`/annotation-queues/${Ne(e,"queueId")}/runs`;for await(const u of this._getPaginated(c,i))for(const l of u)if(yield Ca(l),o++,o>=a)return}async deleteRunFromAnnotationQueue(e,n){await this.caller.call(async()=>{const r=await this._fetch(`${this.apiUrl}/annotation-queues/${Ne(e,"queueId")}/runs/${Ne(n,"queueRunId")}`,{method:"DELETE",headers:{...this._mergedHeaders,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await he(r,"delete run from annotation queue",!0),r})}async getSizeFromAnnotationQueue(e){return(await this.caller.call(async()=>{const r=await this._fetch(`${this.apiUrl}/annotation-queues/${Ne(e,"queueId")}/size`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await he(r,"get size from annotation queue"),r})).json()}async _currentTenantIsOwner(e){const n=await this._getSettings();return e=="-"||n.tenant_handle===e}async _ownerConflictError(e,n){const r=await this._getSettings();return new Error(`Cannot ${e} for another tenant.
|
|
49
|
-
|
|
50
|
-
Current tenant: ${r.tenant_handle}
|
|
51
|
-
|
|
52
|
-
Requested tenant: ${n}`)}async _getLatestCommitHash(e){const r=await(await this.caller.call(async()=>{const s=await this._fetch(`${this.apiUrl}/commits/${e}/?limit=1&offset=0`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await he(s,"get latest commit hash"),s})).json();if(r.commits.length!==0)return r.commits[0].commit_hash}async _createCommitTags(e,n,r){const s=typeof r=="string"?[r]:r;await Promise.all(s.map(async i=>this.caller.call(async()=>{const a=await this._fetch(`${this.apiUrl}/repos/${e}/tags`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:JSON.stringify({tag_name:i,commit_id:n})});return await he(a,"create commit tag"),a})))}async _likeOrUnlikePrompt(e,n){const[r,s,i]=kn(e),a=JSON.stringify({like:n});return(await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/likes/${r}/${s}`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await he(c,`${n?"like":"unlike"} prompt`),c})).json()}async _getPromptUrl(e){const[n,r,s]=kn(e);if(await this._currentTenantIsOwner(n)){const i=await this._getSettings();return s!=="latest"?`${this.getHostUrl()}/prompts/${r}/${s.substring(0,8)}?organizationId=${i.id}`:`${this.getHostUrl()}/prompts/${r}?organizationId=${i.id}`}else return s!=="latest"?`${this.getHostUrl()}/hub/${n}/${r}/${s.substring(0,8)}`:`${this.getHostUrl()}/hub/${n}/${r}`}async promptExists(e){return!!await this.getPrompt(e)}async likePrompt(e){return this._likeOrUnlikePrompt(e,!0)}async unlikePrompt(e){return this._likeOrUnlikePrompt(e,!1)}async*listCommits(e){const[n,r,s]=kn(e);for await(const i of this._getPaginated(`/commits/${n}/${r}/`,new URLSearchParams,a=>a.commits))yield*i}async*listPrompts(e){const n=new URLSearchParams;n.append("sort_field",(e==null?void 0:e.sortField)??"updated_at"),n.append("sort_direction","desc"),n.append("is_archived",(!!(e!=null&&e.isArchived)).toString()),(e==null?void 0:e.isPublic)!==void 0&&n.append("is_public",e.isPublic.toString()),e!=null&&e.query&&n.append("query",e.query);for await(const r of this._getPaginated("/repos",n,s=>s.repos))yield*r}async getPrompt(e){const[n,r,s]=kn(e),i=await this.caller.call(async()=>{const o=await this._fetch(`${this.apiUrl}/repos/${n}/${r}`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return(o==null?void 0:o.status)===404?null:(await he(o,"get prompt"),o)}),a=await(i==null?void 0:i.json());return a!=null&&a.repo?a.repo:null}async createPrompt(e,n){const r=await this._getSettings();if(n!=null&&n.isPublic&&!r.tenant_handle)throw new Error(`Cannot create a public prompt without first
|
|
53
|
-
|
|
54
|
-
creating a LangChain Hub handle.
|
|
55
|
-
You can add a handle by creating a public prompt at:
|
|
56
|
-
|
|
57
|
-
https://smith.langchain.com/prompts`);const[s,i,a]=kn(e);if(!await this._currentTenantIsOwner(s))throw await this._ownerConflictError("create a prompt",s);const o={repo_handle:i,...(n==null?void 0:n.description)&&{description:n.description},...(n==null?void 0:n.readme)&&{readme:n.readme},...(n==null?void 0:n.tags)&&{tags:n.tags},is_public:!!(n!=null&&n.isPublic)},c=JSON.stringify(o),u=await this.caller.call(async()=>{const d=await this._fetch(`${this.apiUrl}/repos/`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await he(d,"create prompt"),d}),{repo:l}=await u.json();return l}async createCommit(e,n,r){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");const[s,i,a]=kn(e),o=(r==null?void 0:r.parentCommitHash)==="latest"||!(r!=null&&r.parentCommitHash)?await this._getLatestCommitHash(`${s}/${i}`):r==null?void 0:r.parentCommitHash,c={manifest:JSON.parse(JSON.stringify(n)),parent_commit:o,...(r==null?void 0:r.description)!==void 0&&{description:r.description}},u=JSON.stringify(c),d=await(await this.caller.call(async()=>{const h=await this._fetch(`${this.apiUrl}/commits/${s}/${i}`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:u});return await he(h,"create commit"),h})).json(),f=d.commit??d;return r!=null&&r.tags&&await this._createCommitTags(`${s}/${i}`,f.id,r.tags),this._getPromptUrl(`${s}/${i}${f.commit_hash?`:${f.commit_hash}`:""}`)}async updateExamplesMultipart(e,n=[]){return this._updateExamplesMultipart(e,n)}async _updateExamplesMultipart(e,n=[]){var a;if(!await this._getDatasetExamplesMultiPartSupport())throw new Error("Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version.");const r=new FormData;for(const o of n){const c=o.id,u={...o.metadata&&{metadata:o.metadata},...o.split&&{split:o.split}},l=Cn(u,`Serializing body for example with id: ${c}`),d=new Blob([l],{type:"application/json"});if(r.append(c,d),o.inputs){const f=Cn(o.inputs,`Serializing inputs for example with id: ${c}`),h=new Blob([f],{type:"application/json"});r.append(`${c}.inputs`,h)}if(o.outputs){const f=Cn(o.outputs,`Serializing outputs whle updating example with id: ${c}`),h=new Blob([f],{type:"application/json"});r.append(`${c}.outputs`,h)}if(o.attachments)for(const[f,h]of Object.entries(o.attachments)){let p,g;Array.isArray(h)?[p,g]=h:(p=h.mimeType,g=h.data);const y=new Blob([g],{type:`${p}; length=${g.byteLength}`});r.append(`${c}.attachment.${f}`,y)}if(o.attachments_operations){const f=Cn(o.attachments_operations,`Serializing attachments while updating example with id: ${c}`),h=new Blob([f],{type:"application/json"});r.append(`${c}.attachments_operations`,h)}}const s=e??((a=n[0])==null?void 0:a.dataset_id);return(await this.caller.call(async()=>{const o=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${s}/examples`)}`,{method:"PATCH",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:r});return await he(o,"update examples"),o})).json()}async uploadExamplesMultipart(e,n=[]){return this._uploadExamplesMultipart(e,n)}async _uploadExamplesMultipart(e,n=[]){if(!await this._getDatasetExamplesMultiPartSupport())throw new Error("Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version.");const r=new FormData;for(const i of n){const a=(i.id??cc()).toString(),o={created_at:i.created_at,...i.metadata&&{metadata:i.metadata},...i.split&&{split:i.split},...i.source_run_id&&{source_run_id:i.source_run_id},...i.use_source_run_io&&{use_source_run_io:i.use_source_run_io},...i.use_source_run_attachments&&{use_source_run_attachments:i.use_source_run_attachments}},c=Cn(o,`Serializing body for uploaded example with id: ${a}`),u=new Blob([c],{type:"application/json"});if(r.append(a,u),i.inputs){const l=Cn(i.inputs,`Serializing inputs for uploaded example with id: ${a}`),d=new Blob([l],{type:"application/json"});r.append(`${a}.inputs`,d)}if(i.outputs){const l=Cn(i.outputs,`Serializing outputs for uploaded example with id: ${a}`),d=new Blob([l],{type:"application/json"});r.append(`${a}.outputs`,d)}if(i.attachments)for(const[l,d]of Object.entries(i.attachments)){let f,h;Array.isArray(d)?[f,h]=d:(f=d.mimeType,h=d.data);const p=new Blob([h],{type:`${f}; length=${h.byteLength}`});r.append(`${a}.attachment.${l}`,p)}}return(await this.caller.call(async()=>{const i=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${e}/examples`)}`,{method:"POST",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:r});return await he(i,"upload examples"),i})).json()}async updatePrompt(e,n){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");const[r,s]=kn(e);if(!await this._currentTenantIsOwner(r))throw await this._ownerConflictError("update a prompt",r);const i={};if((n==null?void 0:n.description)!==void 0&&(i.description=n.description),(n==null?void 0:n.readme)!==void 0&&(i.readme=n.readme),(n==null?void 0:n.tags)!==void 0&&(i.tags=n.tags),(n==null?void 0:n.isPublic)!==void 0&&(i.is_public=n.isPublic),(n==null?void 0:n.isArchived)!==void 0&&(i.is_archived=n.isArchived),Object.keys(i).length===0)throw new Error("No valid update options provided");const a=JSON.stringify(i);return(await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/repos/${r}/${s}`,{method:"PATCH",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await he(c,"update prompt"),c})).json()}async deletePrompt(e){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");const[n,r,s]=kn(e);if(!await this._currentTenantIsOwner(n))throw await this._ownerConflictError("delete a prompt",n);return(await this.caller.call(async()=>{const a=await this._fetch(`${this.apiUrl}/repos/${n}/${r}`,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await he(a,"delete prompt"),a})).json()}_getPromptCacheKey(e,n){return`${e}${n?":with_model":""}`}async _fetchPromptFromApi(e,n){const[r,s,i]=kn(e),o=await(await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/commits/${r}/${s}/${i}${n!=null&&n.includeModel?"?include_model=true":""}`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await he(c,"pull prompt commit"),c})).json();return{owner:r,repo:s,commit_hash:o.commit_hash,manifest:o.manifest,examples:o.examples,hub_model_config:o.model_config,hub_model_provider:o.model_provider}}async pullPromptCommit(e,n){bL(e,n==null?void 0:n.dangerouslyPullPublicPrompt);const r=this._fetchPromptFromApi.bind(this,e,n);if(!(n!=null&&n.skipCache)&&this._promptCache){const s=this._getPromptCacheKey(e,n==null?void 0:n.includeModel),i=this._promptCache.get(s,r);if(i)return i;const a=await r();return this._promptCache.set(s,a,r),a}return this._fetchPromptFromApi(e,n)}async _pullPrompt(e,n){const r=await this.pullPromptCommit(e,{includeModel:n==null?void 0:n.includeModel,skipCache:n==null?void 0:n.skipCache,dangerouslyPullPublicPrompt:n==null?void 0:n.dangerouslyPullPublicPrompt});return JSON.stringify(r.manifest)}async pushPrompt(e,n){return await this.promptExists(e)?n&&["description","readme","tags","isPublic"].some(s=>n[s]!==void 0)&&await this.updatePrompt(e,{description:n==null?void 0:n.description,readme:n==null?void 0:n.readme,tags:n==null?void 0:n.tags,isPublic:n==null?void 0:n.isPublic}):await this.createPrompt(e,{description:n==null?void 0:n.description,readme:n==null?void 0:n.readme,tags:n==null?void 0:n.tags,isPublic:n==null?void 0:n.isPublic}),n!=null&&n.object?await this.createCommit(e,n==null?void 0:n.object,{parentCommitHash:n==null?void 0:n.parentCommitHash,tags:n==null?void 0:n.commitTags,description:n==null?void 0:n.commitDescription}):await this._getPromptUrl(e)}async agentExists(e){const[n,r]=kn(e);return this._repoExists(n,r)}async skillExists(e){const[n,r]=kn(e);return this._repoExists(n,r)}async pullAgent(e,n){return await this._pullDirectory(e,"agent",n==null?void 0:n.version)}async pullSkill(e,n){return await this._pullDirectory(e,"skill",n==null?void 0:n.version)}async pushAgent(e,n){return this._pushDirectory(e,"agent",n)}async pushSkill(e,n){return this._pushDirectory(e,"skill",n)}async deleteAgent(e){return this._deleteDirectory(e)}async deleteSkill(e){return this._deleteDirectory(e)}async*listAgents(e){yield*this._listReposByType("agent",e)}async*listSkills(e){yield*this._listReposByType("skill",e)}async*_listReposByType(e,n){const r=new URLSearchParams;r.append("repo_type",e),r.append("is_archived",(!!(n!=null&&n.isArchived)).toString()),(n==null?void 0:n.isPublic)!==void 0&&r.append("is_public",n.isPublic.toString()),n!=null&&n.query&&r.append("query",n.query);for await(const s of this._getPaginated("/repos",r,i=>i.repos))yield*s}async _pullDirectory(e,n,r){const[s,i,a]=kn(e),o=r??(a!=="latest"?a:void 0),c=new URL(`${this.apiUrl}${this._getPlatformEndpointPath(`hub/repos/${s}/${i}/directories`)}`);return c.searchParams.set("repo_type",n),o&&c.searchParams.set("commit",o),await(await this.caller.call(async()=>{const l=await this._fetch(c.toString(),{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await he(l,"pull directory"),l})).json()}async _pushDirectory(e,n,r){if(r.parentCommit!==void 0&&(r.parentCommit.length<8||r.parentCommit.length>64))throw new Error("parent_commit must be 8-64 characters");const[s,i]=kn(e);if(!await this._currentTenantIsOwner(s))throw await this._ownerConflictError(`push ${n}`,s);if(await this._repoExists(s,i))(r.description!==void 0||r.readme!==void 0||r.tags!==void 0||r.isPublic!==void 0)&&await this._updateRepoMetadata(s,i,r);else{const f=/^[a-z][a-z0-9-_]*$/;if(!f.test(i))throw new Error(`Invalid repo_handle ${JSON.stringify(i)}: must match ${f}`);await this._createRepo(i,n,r)}const a={files:r.files};r.parentCommit&&(a.parent_commit=r.parentCommit);const u=(await(await this.caller.call(async()=>{const f=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`hub/repos/${s}/${i}/directories/commits`)}`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:JSON.stringify(a)});return await he(f,`push ${n}`),f})).json()).commit.commit_hash,l=await this._getSettings(),d=new URLSearchParams({organizationId:l.id});return`${this.getHostUrl()}/context/${i}/${u.slice(0,8)}?${d.toString()}`}async _deleteDirectory(e){const[n,r]=kn(e);if(!await this._currentTenantIsOwner(n))throw await this._ownerConflictError("delete",n);await this.caller.call(async()=>{const s=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`hub/repos/${n}/${r}/directories`)}`,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await he(s,"delete directory"),s})}async _repoExists(e,n){try{return await this.caller.call(async()=>{const r=await this._fetch(`${this.apiUrl}/repos/${e}/${n}`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await he(r,"check repo exists"),r}),!0}catch(r){if(kp(r))return!1;throw r}}async _createRepo(e,n,r){const s={repo_handle:e,repo_type:n,is_public:!!r.isPublic};r.description!==void 0&&(s.description=r.description),r.readme!==void 0&&(s.readme=r.readme),r.tags!==void 0&&(s.tags=r.tags);try{await this.caller.call(async()=>{const i=await this._fetch(`${this.apiUrl}/repos/`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:JSON.stringify(s)});return await he(i,`create ${n}`),i})}catch(i){if(FM(i))return;throw i}}async _updateRepoMetadata(e,n,r){const s={};r.description!==void 0&&(s.description=r.description),r.readme!==void 0&&(s.readme=r.readme),r.tags!==void 0&&(s.tags=r.tags),r.isPublic!==void 0&&(s.is_public=r.isPublic),Object.keys(s).length!==0&&await this.caller.call(async()=>{const i=await this._fetch(`${this.apiUrl}/repos/${e}/${n}`,{method:"PATCH",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:JSON.stringify(s)});return await he(i,"update repo metadata"),i})}async clonePublicDataset(e,n={}){const{sourceApiUrl:r=this.apiUrl,datasetName:s}=n,[i,a]=this.parseTokenOrUrl(e,r),o=new ls({apiUrl:i,apiKey:"placeholder"}),c=await o.readSharedDataset(a),u=s||c.name;try{if(await this.hasDataset({datasetId:u})){console.log(`Dataset ${u} already exists in your tenant. Skipping.`);return}}catch{}const l=await o.listSharedExamples(a),d=await this.createDataset(u,{description:c.description,dataType:c.data_type||"kv",inputsSchema:c.inputs_schema_definition??void 0,outputsSchema:c.outputs_schema_definition??void 0});try{await this.createExamples({inputs:l.map(f=>f.inputs),outputs:l.flatMap(f=>f.outputs?[f.outputs]:[]),datasetId:d.id})}catch(f){throw console.error(`An error occurred while creating dataset ${u}. You should delete it manually.`),f}}parseTokenOrUrl(e,n,r=2,s="dataset"){try{return Ne(e),[n,e]}catch{}try{const a=new URL(e).pathname.split("/").filter(o=>o!=="");if(a.length>=r){const o=a[a.length-r];return[n,o]}else throw new Error(`Invalid public ${s} URL: ${e}`)}catch{throw new Error(`Invalid public ${s} URL or token: ${e}`)}}cleanup(){this._promptCache&&this._promptCache.stop()}async awaitPendingTraceBatches(){var e,n;if(this.manualFlushMode)return console.warn("[WARNING]: When tracing in manual flush mode, you must call `await client.flush()` manually to submit trace batches."),Promise.resolve();for(await new Promise(r=>setTimeout(r,1));this._pendingDrains.size>0;)await Promise.all([...this._pendingDrains]);await Promise.all([...this.autoBatchQueue.items.map(({itemPromise:r})=>r),this.batchIngestCaller.queue.onIdle()]),this.langSmithToOTELTranslator!==void 0&&await((n=(e=dM())==null?void 0:e.DEFAULT_LANGSMITH_SPAN_PROCESSOR)==null?void 0:n.forceFlush())}toString(){const e=[`apiUrl=${JSON.stringify(this.apiUrl)}`];return this.webUrl!==void 0&&e.push(`webUrl=${JSON.stringify(this.webUrl)}`),this.workspaceId!==void 0&&e.push(`workspaceId=${JSON.stringify(this.workspaceId)}`),`[LangSmithClient ${e.join(" ")}]`}[Symbol.for("nodejs.util.inspect.custom")](){return this.toString()}}Object.defineProperty(ls,"_fallbackDirsCreated",{enumerable:!0,configurable:!0,writable:!0,value:new Set});function S0(t){return"dataset_id"in t||"dataset_name"in t}const CL=t=>!!["TRACING_V2","TRACING"].find(n=>Pt(n)==="true"),vi=Symbol.for("lc:context_variables"),$p=Symbol.for("langsmith:replica_trace_roots");function A0(t,e){if(vi in t)return t[vi][e]}function OL(t,e,n){const r=vi in t?t[vi]:{};r[e]=n,t[vi]=r}const $L="6ba7b810-9dad-11d1-80b4-00c04fd430c8";function T0(t){const n=Object.keys(t).sort().map(r=>`${r}:${t[r]??""}`).join("|");return cy(n,$L)}function RL(t){return t.replace(/[-:.]/g,"")}function SE(t,e=1){const n=e.toFixed(0).slice(0,3).padStart(3,"0");return`${new Date(t).toISOString().slice(0,-1)}${n}Z`}function AE(t,e,n=1){const r=SE(t,n);return{dottedOrder:RL(r)+e,microsecondPrecisionDatestring:r}}const PL=new Set(["projectName","updates","reroot"]);function NL(t){const e={};for(const n of Object.keys(t))PL.has(n)&&(e[n]=t[n]);return e}class Th{constructor(e,n,r,s){Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"project_name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"replicas",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.metadata=e,this.tags=n,this.project_name=r,this.replicas=s}static fromHeader(e){const n=e.split(",");let r={},s=[],i,a;for(const o of n){const[c,u]=o.split("="),l=decodeURIComponent(u);c==="langsmith-metadata"?r=JSON.parse(l):c==="langsmith-tags"?s=l.split(","):c==="langsmith-project"?i=l:c==="langsmith-replicas"&&(a=JSON.parse(l).map(f=>Array.isArray(f)?f:NL(f)))}return new Th(r,s,i,a)}toHeader(){const e=[];return this.metadata&&Object.keys(this.metadata).length>0&&e.push(`langsmith-metadata=${encodeURIComponent(JSON.stringify(this.metadata))}`),this.tags&&this.tags.length>0&&e.push(`langsmith-tags=${encodeURIComponent(this.tags.join(","))}`),this.project_name&&e.push(`langsmith-project=${encodeURIComponent(this.project_name)}`),e.join(",")}}class Un{constructor(e){var o;if(Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"run_type",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"project_name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"parent_run",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"parent_run_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"child_runs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"start_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"end_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"extra",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"error",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"serialized",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"inputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"outputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"reference_example_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"client",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"events",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"trace_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"dotted_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tracingEnabled",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"execution_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"child_execution_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"attachments",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"replicas",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"distributedParentId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_serialized_start_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_awaitInputsOnPost",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),ML(e)){Object.assign(this,{...e});return}const n=Un.getDefaultConfig(),{metadata:r,...s}=e,i=s.client??Un.getSharedClient(),a={...r,...(o=s==null?void 0:s.extra)==null?void 0:o.metadata};if(s.extra={...s.extra,metadata:a},"id"in s&&s.id==null&&delete s.id,Object.assign(this,{...n,...s,client:i}),this.execution_order??(this.execution_order=1),this.child_execution_order??(this.child_execution_order=1),this.dotted_order||(this._serialized_start_time=SE(this.start_time,this.execution_order)),this.id||(this.id=B2(this._serialized_start_time??this.start_time)),this.trace_id||(this.parent_run?this.trace_id=this.parent_run.trace_id??this.id:this.trace_id=this.id),this.replicas=UL(this.replicas),!this.dotted_order){const{dottedOrder:c}=AE(this.start_time,this.id,this.execution_order);this.parent_run?this.dotted_order=this.parent_run.dotted_order+"."+c:this.dotted_order=c}}set metadata(e){var n;this.extra={...this.extra,metadata:{...(n=this.extra)==null?void 0:n.metadata,...e}}}get metadata(){var e;return(e=this.extra)==null?void 0:e.metadata}static getDefaultConfig(){const e=Date.now();return{run_type:"chain",project_name:GT(),child_runs:[],api_url:cr("LANGCHAIN_ENDPOINT")??"http://localhost:1984",api_key:cr("LANGCHAIN_API_KEY"),caller_options:{},start_time:e,serialized:{},inputs:{},extra:{}}}static getSharedClient(){return Un.sharedClient||(Un.sharedClient=new ls),Un.sharedClient}createChild(e){var f,h,p,g,y,b,_,w,v;const n=this.child_execution_order+1,r=(f=this.replicas)==null?void 0:f.map(A=>{const{reroot:S,...x}=A;return x}),s=e.replicas??r,i=new Un({...e,parent_run:this,project_name:this.project_name,replicas:s,client:this.client,tracingEnabled:this.tracingEnabled,execution_order:n,child_execution_order:n}),a=((h=this.extra)==null?void 0:h.metadata)??{},o=((p=i.extra)==null?void 0:p.metadata)??{};Object.keys(a).length>0&&(i.extra={...i.extra,metadata:{...a,...o}}),vi in this&&(i[vi]=this[vi]);const c=Symbol.for("lc:child_config"),u=((g=e.extra)==null?void 0:g[c])??this.extra[c];if(jL(u)){const A={...u},S=LL(A.callbacks)?(b=(y=A.callbacks).copy)==null?void 0:b.call(y):void 0;S&&(Object.assign(S,{_parentRunId:i.id}),(v=(w=(_=S.handlers)==null?void 0:_.find(TE))==null?void 0:w.updateFromRunTree)==null||v.call(w,i),A.callbacks=S),i.extra[c]=A}const l=new Set;let d=this;for(;d!=null&&!l.has(d.id);)l.add(d.id),d.child_execution_order=Math.max(d.child_execution_order,n),d=d.parent_run;return this.child_runs.push(i),i}async end(e,n,r=Date.now(),s){this.outputs=this.outputs??e,this.error=this.error??n,this.end_time=this.end_time??r,s&&Object.keys(s).length>0&&(this.extra=this.extra?{...this.extra,metadata:{...this.extra.metadata,...s}}:{metadata:s})}_convertToCreate(e,n,r=!0){var o,c;const s=e.extra??{};if(((o=s==null?void 0:s.runtime)==null?void 0:o.library)===void 0&&(s.runtime||(s.runtime={}),n))for(const[u,l]of Object.entries(n))s.runtime[u]||(s.runtime[u]=l);const i=((c=e.parent_run)==null?void 0:c.id)??e.parent_run_id;let a;return r?a=[]:a=e.child_runs.map(u=>this._convertToCreate(u,n,r)),{id:e.id,name:e.name,start_time:e._serialized_start_time??e.start_time,end_time:e.end_time,run_type:e.run_type,reference_example_id:e.reference_example_id,extra:s,serialized:e.serialized,error:e.error,inputs:e.inputs,outputs:e.outputs,session_name:e.project_name,child_runs:a,parent_run_id:i,trace_id:e.trace_id,dotted_order:e.dotted_order,tags:e.tags,attachments:e.attachments,events:e.events}}_sliceParentId(e,n){if(n.dotted_order){const r=n.dotted_order.split(".");let s=null;for(let i=0;i<r.length;i++)if(r[i].slice(-36)===e){s=i;break}if(s!==null){const i=r.slice(s+1);n.dotted_order=i.join("."),i.length>0?n.trace_id=i[0].slice(-36):n.trace_id=n.id}}n.parent_run_id===e&&(n.parent_run_id=void 0)}_setReplicaTraceRoot(e,n){const r=A0(this,$p)??{};r[e]=n,OL(this,$p,r);for(const s of this.child_runs)s._setReplicaTraceRoot(e,n)}_remapForProject(e){const{projectName:n,runtimeEnv:r,excludeChildRuns:s=!0,reroot:i=!1,distributedParentId:a,apiUrl:o,apiKey:c,workspaceId:u}=e,l=this._convertToCreate(this,r,s);if(n===this.project_name)return{...l,session_name:n};if(i){if(a)this._sliceParentId(a,l);else if(l.parent_run_id=void 0,l.dotted_order){const _=l.dotted_order.split(".");_.length>0&&(l.dotted_order=_[_.length-1],l.trace_id=l.id)}const b=T0({projectName:n,apiUrl:o,apiKey:c,workspaceId:u});this._setReplicaTraceRoot(b,l.id)}let d;if(!i){const b=A0(this,$p)??{},_=T0({projectName:n,apiUrl:o,apiKey:c,workspaceId:u});if(d=b[_],d&&(l.trace_id=d,l.dotted_order)){const w=l.dotted_order.split(".");let v=null;for(let A=0;A<w.length;A++)if(w[A].slice(-36)===d){v=A;break}if(v!==null){const A=w.slice(v);l.dotted_order=A.join(".")}}}const f=l.id,h=Vl(f,n);let p;l.trace_id?p=Vl(l.trace_id,n):p=h;let g;l.parent_run_id&&(g=Vl(l.parent_run_id,n));let y;return l.dotted_order&&(y=l.dotted_order.split(".").map(w=>{const v=w.slice(-36),A=Vl(v,n);return w.slice(0,-36)+A}).join(".")),{...l,id:h,trace_id:p,parent_run_id:g,dotted_order:y,session_name:n}}async postRun(e=!0){this._awaitInputsOnPost&&(this.inputs=await this.inputs);try{const n=oE();if(this.replicas&&this.replicas.length>0)for(const{projectName:r,apiKey:s,apiUrl:i,workspaceId:a,reroot:o,client:c}of this.replicas){const u=this._remapForProject({projectName:r??this.project_name,runtimeEnv:n,excludeChildRuns:!0,reroot:o,distributedParentId:this.distributedParentId,apiUrl:i,apiKey:s,workspaceId:a});await(c??this.client).createRun(u,{apiKey:s,apiUrl:i,workspaceId:a})}else{const r=this._convertToCreate(this,n,e);await this.client.createRun(r)}if(!e){Dd("Posting with excludeChildRuns=false is deprecated and will be removed in a future version.");for(const r of this.child_runs)await r.postRun(!1)}this.child_runs=[]}catch(n){console.error(`Error in postRun for run ${this.id}:`,n)}}async patchRun(e){var n;if(this.replicas&&this.replicas.length>0)for(const{projectName:r,apiKey:s,apiUrl:i,workspaceId:a,updates:o,reroot:c,client:u}of this.replicas){const l=this._remapForProject({projectName:r??this.project_name,runtimeEnv:void 0,excludeChildRuns:!0,reroot:c,distributedParentId:this.distributedParentId,apiUrl:i,apiKey:s,workspaceId:a}),d={id:l.id,name:l.name,run_type:l.run_type,start_time:l.start_time,outputs:l.outputs,error:l.error,parent_run_id:l.parent_run_id,session_name:l.session_name,reference_example_id:l.reference_example_id,end_time:l.end_time,dotted_order:l.dotted_order,trace_id:l.trace_id,events:l.events,tags:l.tags,extra:l.extra,attachments:this.attachments,...o};e!=null&&e.excludeInputs||(d.inputs=l.inputs),await(u??this.client).updateRun(l.id,d,{apiKey:s,apiUrl:i,workspaceId:a})}else try{const r={name:this.name,run_type:this.run_type,start_time:this._serialized_start_time??this.start_time,end_time:this.end_time,error:this.error,outputs:this.outputs,parent_run_id:((n=this.parent_run)==null?void 0:n.id)??this.parent_run_id,reference_example_id:this.reference_example_id,extra:this.extra,events:this.events,dotted_order:this.dotted_order,trace_id:this.trace_id,tags:this.tags,attachments:this.attachments,session_name:this.project_name};e!=null&&e.excludeInputs||(r.inputs=this.inputs),await this.client.updateRun(this.id,r)}catch(r){console.error(`Error in patchRun for run ${this.id}`,r)}this.child_runs=[]}toJSON(){return this._convertToCreate(this,void 0,!1)}addEvent(e){this.events||(this.events=[]),typeof e=="string"?this.events.push({name:"event",time:new Date().toISOString(),message:e}):this.events.push({...e,time:e.time??new Date().toISOString()})}static fromRunnableConfig(e,n){var u,l,d,f;const r=e==null?void 0:e.callbacks;let s,i,a,o=CL();if(r){const h=((u=r==null?void 0:r.getParentRunId)==null?void 0:u.call(r))??"",p=(l=r==null?void 0:r.handlers)==null?void 0:l.find(g=>(g==null?void 0:g.name)=="langchain_tracer");s=(d=p==null?void 0:p.getRun)==null?void 0:d.call(p,h),i=p==null?void 0:p.projectName,a=p==null?void 0:p.client,o=o||!!p}return s?new Un({name:s.name,id:s.id,trace_id:s.trace_id,dotted_order:s.dotted_order,client:a,tracingEnabled:o,project_name:i,tags:[...new Set(((s==null?void 0:s.tags)??[]).concat((e==null?void 0:e.tags)??[]))],extra:{metadata:{...(f=s==null?void 0:s.extra)==null?void 0:f.metadata,...e==null?void 0:e.metadata}}}).createChild(n):new Un({...n,client:a,tracingEnabled:o,project_name:i})}static fromDottedOrder(e){return this.fromHeaders({"langsmith-trace":e})}static fromHeaders(e,n){var l;const r="get"in e&&typeof e.get=="function"?{"langsmith-trace":e.get("langsmith-trace"),baggage:e.get("baggage")}:e,s=r["langsmith-trace"];if(!s||typeof s!="string")return;const i=s.trim(),a=i.split(".").map(d=>{const[f,h]=d.split("Z");return{strTime:f,time:Date.parse(f+"Z"),uuid:h}}),o=a[0].uuid,c={...n,name:(n==null?void 0:n.name)??"parent",run_type:(n==null?void 0:n.run_type)??"chain",start_time:(n==null?void 0:n.start_time)??Date.now(),id:(l=a.at(-1))==null?void 0:l.uuid,trace_id:o,dotted_order:i};if(r.baggage&&typeof r.baggage=="string"){const d=Th.fromHeader(r.baggage);c.metadata=d.metadata,c.tags=d.tags,c.project_name=d.project_name,c.replicas=d.replicas}const u=new Un(c);return u.distributedParentId=u.id,u}toHeaders(e){var r;const n={"langsmith-trace":this.dotted_order,baggage:new Th((r=this.extra)==null?void 0:r.metadata,this.tags,this.project_name,this.replicas).toHeader()};if(e)for(const[s,i]of Object.entries(n))e.set(s,i);return n}}Object.defineProperty(Un,"sharedClient",{enumerable:!0,configurable:!0,writable:!0,value:null});function ML(t){return t!=null&&typeof t.createChild=="function"&&typeof t.postRun=="function"}function TE(t){return typeof t=="object"&&t!=null&&typeof t.name=="string"&&t.name==="langchain_tracer"}function E0(t){return Array.isArray(t)&&t.some(e=>TE(e))}function LL(t){return typeof t=="object"&&t!=null&&Array.isArray(t.handlers)}function jL(t){const e=t==null?void 0:t.callbacks;return t!=null&&typeof e=="object"&&(E0(e==null?void 0:e.handlers)||E0(e))}function DL(){const t=cr("LANGSMITH_RUNS_ENDPOINTS");if(!t)return[];try{const e=JSON.parse(t);if(Array.isArray(e)){const n=[];for(const r of e){if(typeof r!="object"||r===null){console.warn(`Invalid item type in LANGSMITH_RUNS_ENDPOINTS: expected object, got ${typeof r}`);continue}if(typeof r.api_url!="string"){console.warn(`Invalid api_url type in LANGSMITH_RUNS_ENDPOINTS: expected string, got ${typeof r.api_url}`);continue}if(typeof r.api_key!="string"){console.warn(`Invalid api_key type in LANGSMITH_RUNS_ENDPOINTS: expected string, got ${typeof r.api_key}`);continue}n.push({apiUrl:r.api_url.replace(/\/$/,""),apiKey:r.api_key})}return n}else if(typeof e=="object"&&e!==null){FL(e);const n=[];for(const[r,s]of Object.entries(e)){const i=r.replace(/\/$/,"");if(typeof s=="string")n.push({apiUrl:i,apiKey:s});else{console.warn(`Invalid value type in LANGSMITH_RUNS_ENDPOINTS for URL ${r}: expected string, got ${typeof s}`);continue}}return n}else return console.warn(`Invalid LANGSMITH_RUNS_ENDPOINTS – must be valid JSON array of objects with api_url and api_key properties, or object mapping url->apiKey, got ${typeof e}`),[]}catch(e){if(zM(e))throw e;return console.warn("Invalid LANGSMITH_RUNS_ENDPOINTS – must be valid JSON array of objects with api_url and api_key properties, or object mapping url->apiKey"),[]}}function UL(t){return t?t.map(e=>Array.isArray(e)?{projectName:e[0],updates:e[1]}:e):DL()}function FL(t){if(Object.keys(t).length>0&&Pt("ENDPOINT"))throw new BM}var BL=de({BaseTracer:()=>Gs,isBaseTracer:()=>Ka});const zL=t=>{if(t)return t.events=t.events??[],t.child_runs=t.child_runs??[],t};function ig(t,e){if(t)return new Un({...t,start_time:t._serialized_start_time??t.start_time,parent_run:ig(e),child_runs:t.child_runs.map(n=>ig(n)).filter(n=>n!==void 0),extra:{...t.extra,runtime:VT()},tracingEnabled:!1})}function Rp(t,e){return t&&!Array.isArray(t)&&typeof t=="object"?t:{[e]:t}}function Ka(t){return typeof t._addRunToRunMap=="function"}var Gs=class extends qs{constructor(e){super(...arguments);m(this,"runMap",new Map);m(this,"runTreeMap",new Map);m(this,"usesRunTreeMap",!1)}copy(){return this}getRunById(e){if(e!==void 0)return this.usesRunTreeMap?zL(this.runTreeMap.get(e)):this.runMap.get(e)}stringifyError(e){return e instanceof Error?e.message+(e!=null&&e.stack?`
|
|
58
|
-
|
|
59
|
-
${e.stack}`:""):typeof e=="string"?e:`${e}`}_addChildRun(e,n){e.child_runs.push(n)}_addRunToRunMap(e){const{dottedOrder:n,microsecondPrecisionDatestring:r}=AE(new Date(e.start_time).getTime(),e.id,e.execution_order),s={...e},i=this.getRunById(s.parent_run_id);if(s.parent_run_id!==void 0?i?(this._addChildRun(i,s),i.child_execution_order=Math.max(i.child_execution_order,s.child_execution_order),s.trace_id=i.trace_id,i.dotted_order!==void 0&&(s.dotted_order=[i.dotted_order,n].join("."),s._serialized_start_time=r)):s.parent_run_id=void 0:(s.trace_id=s.id,s.dotted_order=n,s._serialized_start_time=r),this.usesRunTreeMap){const a=ig(s,i);a!==void 0&&this.runTreeMap.set(s.id,a)}else this.runMap.set(s.id,s);return s}async _endTrace(e){var r;const n=e.parent_run_id!==void 0&&this.getRunById(e.parent_run_id);n?n.child_execution_order=Math.max(n.child_execution_order,e.child_execution_order):await this.persistRun(e),await((r=this.onRunUpdate)==null?void 0:r.call(this,e)),this.usesRunTreeMap?this.runTreeMap.delete(e.id):this.runMap.delete(e.id)}_getExecutionOrder(e){const n=e!==void 0&&this.getRunById(e);return n?n.child_execution_order+1:1}_createRunForLLMStart(e,n,r,s,i,a,o,c){const u=this._getExecutionOrder(s),l=Date.now(),d=o?{...i,metadata:o}:i,f={id:r,name:c??e.id[e.id.length-1],parent_run_id:s,start_time:l,serialized:e,events:[{name:"start",time:new Date(l).toISOString()}],inputs:{prompts:n},execution_order:u,child_runs:[],child_execution_order:u,run_type:"llm",extra:d??{},tags:a||[]};return this._addRunToRunMap(f)}async handleLLMStart(e,n,r,s,i,a,o,c){var l,d;const u=this.getRunById(r)??this._createRunForLLMStart(e,n,r,s,i,a,o,c);return await((l=this.onRunCreate)==null?void 0:l.call(this,u)),await((d=this.onLLMStart)==null?void 0:d.call(this,u)),u}_createRunForChatModelStart(e,n,r,s,i,a,o,c){const u=this._getExecutionOrder(s),l=Date.now(),d=o?{...i,metadata:o}:i,f={id:r,name:c??e.id[e.id.length-1],parent_run_id:s,start_time:l,serialized:e,events:[{name:"start",time:new Date(l).toISOString()}],inputs:{messages:n},execution_order:u,child_runs:[],child_execution_order:u,run_type:"llm",extra:d??{},tags:a||[]};return this._addRunToRunMap(f)}async handleChatModelStart(e,n,r,s,i,a,o,c){var l,d;const u=this.getRunById(r)??this._createRunForChatModelStart(e,n,r,s,i,a,o,c);return await((l=this.onRunCreate)==null?void 0:l.call(this,u)),await((d=this.onLLMStart)==null?void 0:d.call(this,u)),u}async handleLLMEnd(e,n,r,s,i){var o;const a=this.getRunById(n);if(!a||(a==null?void 0:a.run_type)!=="llm")throw new Error("No LLM run to end.");return a.end_time=Date.now(),a.outputs=e,a.events.push({name:"end",time:new Date(a.end_time).toISOString()}),a.extra={...a.extra,...i},await((o=this.onLLMEnd)==null?void 0:o.call(this,a)),await this._endTrace(a),a}async handleLLMError(e,n,r,s,i){var o;const a=this.getRunById(n);if(!a||(a==null?void 0:a.run_type)!=="llm")throw new Error("No LLM run to end.");return a.end_time=Date.now(),a.error=this.stringifyError(e),a.events.push({name:"error",time:new Date(a.end_time).toISOString()}),a.extra={...a.extra,...i},await((o=this.onLLMError)==null?void 0:o.call(this,a)),await this._endTrace(a),a}_createRunForChainStart(e,n,r,s,i,a,o,c,u){const l=this._getExecutionOrder(s),d=Date.now(),f={id:r,name:c??e.id[e.id.length-1],parent_run_id:s,start_time:d,serialized:e,events:[{name:"start",time:new Date(d).toISOString()}],inputs:n,execution_order:l,child_execution_order:l,run_type:o??"chain",child_runs:[],extra:a?{...u,metadata:a}:{...u},tags:i||[]};return this._addRunToRunMap(f)}async handleChainStart(e,n,r,s,i,a,o,c){var l,d;const u=this.getRunById(r)??this._createRunForChainStart(e,n,r,s,i,a,o,c);return await((l=this.onRunCreate)==null?void 0:l.call(this,u)),await((d=this.onChainStart)==null?void 0:d.call(this,u)),u}async handleChainEnd(e,n,r,s,i){var o;const a=this.getRunById(n);if(!a)throw new Error("No chain run to end.");return a.end_time=Date.now(),a.outputs=Rp(e,"output"),a.events.push({name:"end",time:new Date(a.end_time).toISOString()}),(i==null?void 0:i.inputs)!==void 0&&(a.inputs=Rp(i.inputs,"input")),await((o=this.onChainEnd)==null?void 0:o.call(this,a)),await this._endTrace(a),a}async handleChainError(e,n,r,s,i){var o;const a=this.getRunById(n);if(!a)throw new Error("No chain run to end.");return a.end_time=Date.now(),a.error=this.stringifyError(e),a.events.push({name:"error",time:new Date(a.end_time).toISOString()}),(i==null?void 0:i.inputs)!==void 0&&(a.inputs=Rp(i.inputs,"input")),await((o=this.onChainError)==null?void 0:o.call(this,a)),await this._endTrace(a),a}_createRunForToolStart(e,n,r,s,i,a,o){const c=this._getExecutionOrder(s),u=Date.now(),l={id:r,name:o??e.id[e.id.length-1],parent_run_id:s,start_time:u,serialized:e,events:[{name:"start",time:new Date(u).toISOString()}],inputs:{input:n},execution_order:c,child_execution_order:c,run_type:"tool",child_runs:[],extra:a?{metadata:a}:{},tags:i||[]};return this._addRunToRunMap(l)}async handleToolStart(e,n,r,s,i,a,o){var u,l;const c=this.getRunById(r)??this._createRunForToolStart(e,n,r,s,i,a,o);return await((u=this.onRunCreate)==null?void 0:u.call(this,c)),await((l=this.onToolStart)==null?void 0:l.call(this,c)),c}async handleToolEnd(e,n){var s;const r=this.getRunById(n);if(!r||(r==null?void 0:r.run_type)!=="tool")throw new Error("No tool run to end");return r.end_time=Date.now(),r.outputs={output:e},r.events.push({name:"end",time:new Date(r.end_time).toISOString()}),await((s=this.onToolEnd)==null?void 0:s.call(this,r)),await this._endTrace(r),r}async handleToolError(e,n){var s;const r=this.getRunById(n);if(!r||(r==null?void 0:r.run_type)!=="tool")throw new Error("No tool run to end");return r.end_time=Date.now(),r.error=this.stringifyError(e),r.events.push({name:"error",time:new Date(r.end_time).toISOString()}),await((s=this.onToolError)==null?void 0:s.call(this,r)),await this._endTrace(r),r}async handleAgentAction(e,n){var i;const r=this.getRunById(n);if(!r||(r==null?void 0:r.run_type)!=="chain")return;const s=r;s.actions=s.actions||[],s.actions.push(e),s.events.push({name:"agent_action",time:new Date().toISOString(),kwargs:{action:e}}),await((i=this.onAgentAction)==null?void 0:i.call(this,r))}async handleAgentEnd(e,n){var s;const r=this.getRunById(n);!r||(r==null?void 0:r.run_type)!=="chain"||(r.events.push({name:"agent_end",time:new Date().toISOString(),kwargs:{action:e}}),await((s=this.onAgentEnd)==null?void 0:s.call(this,r)))}_createRunForRetrieverStart(e,n,r,s,i,a,o){const c=this._getExecutionOrder(s),u=Date.now(),l={id:r,name:o??e.id[e.id.length-1],parent_run_id:s,start_time:u,serialized:e,events:[{name:"start",time:new Date(u).toISOString()}],inputs:{query:n},execution_order:c,child_execution_order:c,run_type:"retriever",child_runs:[],extra:a?{metadata:a}:{},tags:i||[]};return this._addRunToRunMap(l)}async handleRetrieverStart(e,n,r,s,i,a,o){var u,l;const c=this.getRunById(r)??this._createRunForRetrieverStart(e,n,r,s,i,a,o);return await((u=this.onRunCreate)==null?void 0:u.call(this,c)),await((l=this.onRetrieverStart)==null?void 0:l.call(this,c)),c}async handleRetrieverEnd(e,n){var s;const r=this.getRunById(n);if(!r||(r==null?void 0:r.run_type)!=="retriever")throw new Error("No retriever run to end");return r.end_time=Date.now(),r.outputs={documents:e},r.events.push({name:"end",time:new Date(r.end_time).toISOString()}),await((s=this.onRetrieverEnd)==null?void 0:s.call(this,r)),await this._endTrace(r),r}async handleRetrieverError(e,n){var s;const r=this.getRunById(n);if(!r||(r==null?void 0:r.run_type)!=="retriever")throw new Error("No retriever run to end");return r.end_time=Date.now(),r.error=this.stringifyError(e),r.events.push({name:"error",time:new Date(r.end_time).toISOString()}),await((s=this.onRetrieverError)==null?void 0:s.call(this,r)),await this._endTrace(r),r}async handleText(e,n){var s;const r=this.getRunById(n);!r||(r==null?void 0:r.run_type)!=="chain"||(r.events.push({name:"text",time:new Date().toISOString(),kwargs:{text:e}}),await((s=this.onText)==null?void 0:s.call(this,r)))}async handleLLMNewToken(e,n,r,s,i,a){var c;const o=this.getRunById(r);if(!o||(o==null?void 0:o.run_type)!=="llm")throw new Error('Invalid "runId" provided to "handleLLMNewToken" callback.');return o.events.push({name:"new_token",time:new Date().toISOString(),kwargs:{token:e,idx:n,chunk:a==null?void 0:a.chunk}}),await((c=this.onLLMNewToken)==null?void 0:c.call(this,o,e,{chunk:a==null?void 0:a.chunk})),o}},HL=de({ConsoleCallbackHandler:()=>ag});const EE={bold:{open:"\x1B[1m",close:"\x1B[22m"},color:{grey:{open:"\x1B[90m",close:"\x1B[39m"},green:{open:"\x1B[32m",close:"\x1B[39m"},cyan:{open:"\x1B[36m",close:"\x1B[39m"},red:{open:"\x1B[31m",close:"\x1B[39m"},blue:{open:"\x1B[34m",close:"\x1B[39m"}}};function In(t,e){return`${t.open}${e}${t.close}`}function vr(t,e){try{return JSON.stringify(t,null,2)}catch{return e}}function I0(t){return typeof t=="string"?t.trim():t==null?t:vr(t,t.toString())}function Xs(t){if(!t.end_time)return"";const e=t.end_time-t.start_time;return e<1e3?`${e}ms`:`${(e/1e3).toFixed(2)}s`}const{color:Ln}=EE;var ag=class extends Gs{constructor(){super(...arguments);m(this,"name","console_callback_handler")}persistRun(e){return Promise.resolve()}getParents(e){const n=[];let r=e;for(;r.parent_run_id;){const s=this.runMap.get(r.parent_run_id);if(s)n.push(s),r=s;else break}return n}getBreadcrumbs(e){const n=[...this.getParents(e).reverse(),e].map((r,s,i)=>{const a=`${r.execution_order}:${r.run_type}:${r.name}`;return s===i.length-1?In(EE.bold,a):a}).join(" > ");return In(Ln.grey,n)}onChainStart(e){const n=this.getBreadcrumbs(e);console.log(`${In(Ln.green,"[chain/start]")} [${n}] Entering Chain run with input: ${vr(e.inputs,"[inputs]")}`)}onChainEnd(e){const n=this.getBreadcrumbs(e);console.log(`${In(Ln.cyan,"[chain/end]")} [${n}] [${Xs(e)}] Exiting Chain run with output: ${vr(e.outputs,"[outputs]")}`)}onChainError(e){const n=this.getBreadcrumbs(e);console.log(`${In(Ln.red,"[chain/error]")} [${n}] [${Xs(e)}] Chain run errored with error: ${vr(e.error,"[error]")}`)}onLLMStart(e){const n=this.getBreadcrumbs(e),r="prompts"in e.inputs?{prompts:e.inputs.prompts.map(s=>s.trim())}:e.inputs;console.log(`${In(Ln.green,"[llm/start]")} [${n}] Entering LLM run with input: ${vr(r,"[inputs]")}`)}onLLMEnd(e){const n=this.getBreadcrumbs(e);console.log(`${In(Ln.cyan,"[llm/end]")} [${n}] [${Xs(e)}] Exiting LLM run with output: ${vr(e.outputs,"[response]")}`)}onLLMError(e){const n=this.getBreadcrumbs(e);console.log(`${In(Ln.red,"[llm/error]")} [${n}] [${Xs(e)}] LLM run errored with error: ${vr(e.error,"[error]")}`)}onToolStart(e){const n=this.getBreadcrumbs(e);console.log(`${In(Ln.green,"[tool/start]")} [${n}] Entering Tool run with input: "${I0(e.inputs.input)}"`)}onToolEnd(e){var r;const n=this.getBreadcrumbs(e);console.log(`${In(Ln.cyan,"[tool/end]")} [${n}] [${Xs(e)}] Exiting Tool run with output: "${I0((r=e.outputs)==null?void 0:r.output)}"`)}onToolError(e){const n=this.getBreadcrumbs(e);console.log(`${In(Ln.red,"[tool/error]")} [${n}] [${Xs(e)}] Tool run errored with error: ${vr(e.error,"[error]")}`)}onRetrieverStart(e){const n=this.getBreadcrumbs(e);console.log(`${In(Ln.green,"[retriever/start]")} [${n}] Entering Retriever run with input: ${vr(e.inputs,"[inputs]")}`)}onRetrieverEnd(e){const n=this.getBreadcrumbs(e);console.log(`${In(Ln.cyan,"[retriever/end]")} [${n}] [${Xs(e)}] Exiting Retriever run with output: ${vr(e.outputs,"[outputs]")}`)}onRetrieverError(e){const n=this.getBreadcrumbs(e);console.log(`${In(Ln.red,"[retriever/error]")} [${n}] [${Xs(e)}] Retriever run errored with error: ${vr(e.error,"[error]")}`)}onAgentAction(e){const n=e,r=this.getBreadcrumbs(e);console.log(`${In(Ln.blue,"[agent/action]")} [${r}] Agent selected action: ${vr(n.actions[n.actions.length-1],"[action]")}`)}};let Pp;const IE=()=>(Pp===void 0&&(Pp=new ls(Mt("LANGCHAIN_CALLBACKS_BACKGROUND")==="false"?{blockOnRootRunFinalization:!0}:{})),Pp);let VL=class{getStore(){}run(e,n){return n()}};const Np=Symbol.for("ls:tracing_async_local_storage"),KL=new VL;let WL=class{getInstance(){return globalThis[Np]??KL}initializeGlobalInstance(e){globalThis[Np]===void 0&&(globalThis[Np]=e)}};const ZL=new WL;function qL(t=!1){const e=ZL.getInstance().getStore();if(!t&&e===void 0)throw new Error(`Could not get the current run tree.
|
|
60
|
-
|
|
61
|
-
Please make sure you are calling this method within a traceable function and that tracing is enabled.`);return e}function my(t){return typeof t=="function"&&"langsmith:traceable"in t}var GL=de({LangChainTracer:()=>Pc,OVERRIDABLE_LANGSMITH_INHERITABLE_METADATA_KEYS:()=>gy});const gy=new Set(["ls_agent_type"]);function JL(t){let e;for(const n of t)for(const r of n)De.isInstance(r.message)&&r.message.usage_metadata!==void 0&&(e=ty(e,r.message.usage_metadata));return e}var Pc=class og extends Gs{constructor(n={}){super(n);m(this,"name","langchain_tracer");m(this,"projectName");m(this,"exampleId");m(this,"client");m(this,"replicas");m(this,"usesRunTreeMap",!0);m(this,"tracingMetadata");m(this,"tracingTags",[]);this.fields=n;const{exampleId:r,projectName:s,client:i,replicas:a,metadata:o,tags:c}=n;this.projectName=s??GT(),this.replicas=a,this.exampleId=r,this.client=i??IE(),this.tracingMetadata=o?{...o}:void 0,this.tracingTags=c??[];const u=og.getTraceableRunTree();u&&this.updateFromRunTree(u)}async persistRun(n){}async onRunCreate(n){var r,s;x0(this,n),(r=n.extra)!=null&&r.lc_defers_inputs||await((s=this.getRunTreeWithTracingConfig(n.id))==null?void 0:s.postRun())}async onRunUpdate(n){var s;x0(this,n);const r=this.getRunTreeWithTracingConfig(n.id);(s=n.extra)!=null&&s.lc_defers_inputs?await(r==null?void 0:r.postRun()):await(r==null?void 0:r.patchRun())}onLLMEnd(n){const r=n.outputs;if(r!=null&&r.generations){const s=JL(r.generations);if(s!==void 0){n.extra=n.extra??{};const i=n.extra.metadata??{};i.usage_metadata=s,n.extra.metadata=i}}}copyWithTracingConfig({metadata:n,tags:r}){let s;if(n===void 0)s=this.tracingMetadata?{...this.tracingMetadata}:void 0;else if(this.tracingMetadata===void 0)s={...n};else{s={...this.tracingMetadata};for(const[o,c]of Object.entries(n))(!Object.prototype.hasOwnProperty.call(s,o)||gy.has(o))&&(s[o]=c)}const i=r?Array.from(new Set([...this.tracingTags,...r])):[...this.tracingTags],a=new og({...this.fields,metadata:s,tags:i});return a.runMap=this.runMap,a.runTreeMap=this.runTreeMap,a}getRun(n){return this.runTreeMap.get(n)}updateFromRunTree(n){this.runTreeMap.set(n.id,n);let r=n;const s=new Set;for(;r.parent_run&&!(s.has(r.id)||(s.add(r.id),!r.parent_run));)r=r.parent_run;s.clear();const i=[r];for(;i.length>0;){const a=i.shift();!a||s.has(a.id)||(s.add(a.id),this.runTreeMap.set(a.id,a),a.child_runs&&i.push(...a.child_runs))}this.client=n.client??this.client,this.replicas=n.replicas??this.replicas,this.projectName=n.project_name??this.projectName,this.exampleId=n.reference_example_id??this.exampleId,this.fields={...this.fields,client:this.client,replicas:this.replicas,projectName:this.projectName,exampleId:this.exampleId}}getRunTreeWithTracingConfig(n){const r=this.runTreeMap.get(n);if(r)return new Un({...r,client:this.client,project_name:this.projectName,replicas:this.replicas,reference_example_id:this.exampleId,tracingEnabled:!0})}static getTraceableRunTree(){try{return qL(!0)}catch{return}}static[Symbol.hasInstance](n){if(typeof n!="object"||n===null)return!1;const r=n;return"name"in r&&r.name==="langchain_tracer"&&"copyWithTracingConfig"in r&&typeof r.copyWithTracingConfig=="function"&&"getRunTreeWithTracingConfig"in r&&typeof r.getRunTreeWithTracingConfig=="function"}};function x0(t,e){if(t.tracingMetadata){e.extra??(e.extra={});const n=e.extra.metadata??{};let r=!1;for(const[s,i]of Object.entries(t.tracingMetadata))(!Object.prototype.hasOwnProperty.call(n,s)||gy.has(s))&&n[s]!==i&&(n[s]=i,r=!0);r&&(e.extra.metadata=n)}t.tracingTags.length>0&&(e.tags=Array.from(new Set([...e.tags??[],...t.tracingTags])))}const xE=Symbol.for("ls:tracing_async_local_storage"),iu=Symbol.for("lc:context_variables"),YL=t=>{globalThis[xE]=t},vu=()=>globalThis[xE];let la;function XL(){return new("default"in Fs?Fs.default:Fs)({autoStart:!0,concurrency:1})}function QL(){return typeof la>"u"&&(la=XL()),la}async function Ct(t,e){if(e===!0){const n=vu();n!==void 0?await n.run(void 0,async()=>t()):await t()}else la=QL(),la.add(async()=>{const n=vu();n!==void 0?await n.run(void 0,async()=>t()):await t()})}async function ej(){const t=IE();await Promise.allSettled([typeof la<"u"?la.onIdle():Promise.resolve(),t.awaitPendingTraceBatches()])}var tj=de({awaitAllCallbacks:()=>ej,consumeCallback:()=>Ct});const nj=t=>!!["LANGSMITH_TRACING_V2","LANGCHAIN_TRACING_V2","LANGSMITH_TRACING","LANGCHAIN_TRACING"].find(e=>Mt(e)==="true");function kE(t){var n,r;const e=vu();if(e!==void 0)return(r=(n=e.getStore())==null?void 0:n[iu])==null?void 0:r[t]}const rj=Symbol("lc:configure_hooks"),sj=()=>kE(rj)||[];var ij=de({BaseCallbackManager:()=>CE,BaseRunManager:()=>gl,CallbackManager:()=>bn,CallbackManagerForChainRun:()=>$E,CallbackManagerForLLMRun:()=>cg,CallbackManagerForRetrieverRun:()=>OE,CallbackManagerForToolRun:()=>RE,ensureHandler:()=>Su,parseCallbackConfigArg:()=>ml});function ml(t){return t?Array.isArray(t)||"name"in t?{callbacks:t}:t:{}}var CE=class{setHandler(t){return this.setHandlers([t])}},gl=class{constructor(t,e,n,r,s,i,a,o){this.runId=t,this.handlers=e,this.inheritableHandlers=n,this.tags=r,this.inheritableTags=s,this.metadata=i,this.inheritableMetadata=a,this._parentRunId=o}get parentRunId(){return this._parentRunId}async handleText(t){await Promise.all(this.handlers.map(e=>Ct(async()=>{var n;try{await((n=e.handleText)==null?void 0:n.call(e,t,this.runId,this._parentRunId,this.tags))}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleText: ${r}`),e.raiseError)throw r}},e.awaitHandlers)))}async handleCustomEvent(t,e,n,r,s){await Promise.all(this.handlers.map(i=>Ct(async()=>{var a;try{await((a=i.handleCustomEvent)==null?void 0:a.call(i,t,e,this.runId,this.tags,this.metadata))}catch(o){if((i.raiseError?console.error:console.warn)(`Error in handler ${i.constructor.name}, handleCustomEvent: ${o}`),i.raiseError)throw o}},i.awaitHandlers)))}},OE=class extends gl{getChild(t){const e=new bn(this.runId);return e.setHandlers(this.inheritableHandlers),e.addTags(this.inheritableTags),e.addMetadata(this.inheritableMetadata),t&&e.addTags([t],!1),e}async handleRetrieverEnd(t){await Promise.all(this.handlers.map(e=>Ct(async()=>{var n;if(!e.ignoreRetriever)try{await((n=e.handleRetrieverEnd)==null?void 0:n.call(e,t,this.runId,this._parentRunId,this.tags))}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleRetriever`),e.raiseError)throw r}},e.awaitHandlers)))}async handleRetrieverError(t){await Promise.all(this.handlers.map(e=>Ct(async()=>{var n;if(!e.ignoreRetriever)try{await((n=e.handleRetrieverError)==null?void 0:n.call(e,t,this.runId,this._parentRunId,this.tags))}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleRetrieverError: ${r}`),e.raiseError)throw t}},e.awaitHandlers)))}},cg=class extends gl{async handleLLMNewToken(t,e,n,r,s,i){await Promise.all(this.handlers.map(a=>Ct(async()=>{var o;if(!a.ignoreLLM)try{await((o=a.handleLLMNewToken)==null?void 0:o.call(a,t,e??{prompt:0,completion:0},this.runId,this._parentRunId,this.tags,i))}catch(c){if((a.raiseError?console.error:console.warn)(`Error in handler ${a.constructor.name}, handleLLMNewToken: ${c}`),a.raiseError)throw c}},a.awaitHandlers)))}async handleChatModelStreamEvent(t){await Promise.all(this.handlers.map(e=>Ct(async()=>{var n;if(!e.ignoreLLM)try{await((n=e.handleChatModelStreamEvent)==null?void 0:n.call(e,t,this.runId,this._parentRunId,this.tags))}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleChatModelStreamEvent: ${r}`),e.raiseError)throw r}},e.awaitHandlers)))}async handleLLMError(t,e,n,r,s){await Promise.all(this.handlers.map(i=>Ct(async()=>{var a;if(!i.ignoreLLM)try{await((a=i.handleLLMError)==null?void 0:a.call(i,t,this.runId,this._parentRunId,this.tags,s))}catch(o){if((i.raiseError?console.error:console.warn)(`Error in handler ${i.constructor.name}, handleLLMError: ${o}`),i.raiseError)throw o}},i.awaitHandlers)))}async handleLLMEnd(t,e,n,r,s){await Promise.all(this.handlers.map(i=>Ct(async()=>{var a;if(!i.ignoreLLM)try{await((a=i.handleLLMEnd)==null?void 0:a.call(i,t,this.runId,this._parentRunId,this.tags,s))}catch(o){if((i.raiseError?console.error:console.warn)(`Error in handler ${i.constructor.name}, handleLLMEnd: ${o}`),i.raiseError)throw o}},i.awaitHandlers)))}},$E=class extends gl{getChild(t){const e=new bn(this.runId);return e.setHandlers(this.inheritableHandlers),e.addTags(this.inheritableTags),e.addMetadata(this.inheritableMetadata),t&&e.addTags([t],!1),e}async handleChainError(t,e,n,r,s){await Promise.all(this.handlers.map(i=>Ct(async()=>{var a;if(!i.ignoreChain)try{await((a=i.handleChainError)==null?void 0:a.call(i,t,this.runId,this._parentRunId,this.tags,s))}catch(o){if((i.raiseError?console.error:console.warn)(`Error in handler ${i.constructor.name}, handleChainError: ${o}`),i.raiseError)throw o}},i.awaitHandlers)))}async handleChainEnd(t,e,n,r,s){await Promise.all(this.handlers.map(i=>Ct(async()=>{var a;if(!i.ignoreChain)try{await((a=i.handleChainEnd)==null?void 0:a.call(i,t,this.runId,this._parentRunId,this.tags,s))}catch(o){if((i.raiseError?console.error:console.warn)(`Error in handler ${i.constructor.name}, handleChainEnd: ${o}`),i.raiseError)throw o}},i.awaitHandlers)))}async handleAgentAction(t){await Promise.all(this.handlers.map(e=>Ct(async()=>{var n;if(!e.ignoreAgent)try{await((n=e.handleAgentAction)==null?void 0:n.call(e,t,this.runId,this._parentRunId,this.tags))}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleAgentAction: ${r}`),e.raiseError)throw r}},e.awaitHandlers)))}async handleAgentEnd(t){await Promise.all(this.handlers.map(e=>Ct(async()=>{var n;if(!e.ignoreAgent)try{await((n=e.handleAgentEnd)==null?void 0:n.call(e,t,this.runId,this._parentRunId,this.tags))}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleAgentEnd: ${r}`),e.raiseError)throw r}},e.awaitHandlers)))}},RE=class extends gl{getChild(t){const e=new bn(this.runId);return e.setHandlers(this.inheritableHandlers),e.addTags(this.inheritableTags),e.addMetadata(this.inheritableMetadata),t&&e.addTags([t],!1),e}async handleToolError(t){await Promise.all(this.handlers.map(e=>Ct(async()=>{var n;if(!e.ignoreAgent)try{await((n=e.handleToolError)==null?void 0:n.call(e,t,this.runId,this._parentRunId,this.tags))}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleToolError: ${r}`),e.raiseError)throw r}},e.awaitHandlers)))}async handleToolEvent(t){await Promise.all(this.handlers.map(e=>Ct(async()=>{var n;if(!e.ignoreAgent)try{await((n=e.handleToolEvent)==null?void 0:n.call(e,t,this.runId,this._parentRunId,this.tags))}catch(r){if(e.raiseError)throw r}},e.awaitHandlers)))}async handleToolEnd(t){await Promise.all(this.handlers.map(e=>Ct(async()=>{var n;if(!e.ignoreAgent)try{await((n=e.handleToolEnd)==null?void 0:n.call(e,t,this.runId,this._parentRunId,this.tags))}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleToolEnd: ${r}`),e.raiseError)throw r}},e.awaitHandlers)))}},bn=class Nc extends CE{constructor(n,r){super();m(this,"handlers",[]);m(this,"inheritableHandlers",[]);m(this,"tags",[]);m(this,"inheritableTags",[]);m(this,"metadata",{});m(this,"inheritableMetadata",{});m(this,"name","callback_manager");m(this,"_parentRunId");this.handlers=(r==null?void 0:r.handlers)??this.handlers,this.inheritableHandlers=(r==null?void 0:r.inheritableHandlers)??this.inheritableHandlers,this.tags=(r==null?void 0:r.tags)??this.tags,this.inheritableTags=(r==null?void 0:r.inheritableTags)??this.inheritableTags,this.metadata=(r==null?void 0:r.metadata)??this.metadata,this.inheritableMetadata=(r==null?void 0:r.inheritableMetadata)??this.inheritableMetadata,this._parentRunId=n}getParentRunId(){return this._parentRunId}async handleLLMStart(n,r,s=void 0,i=void 0,a=void 0,o=void 0,c=void 0,u=void 0){return Promise.all(r.map(async(l,d)=>{const f=d===0&&s?s:Ps();return await Promise.all(this.handlers.map(h=>{if(!h.ignoreLLM)return Ka(h)&&h._createRunForLLMStart(n,[l],f,this._parentRunId,a,this.tags,this.metadata,u),Ct(async()=>{var p;try{await((p=h.handleLLMStart)==null?void 0:p.call(h,n,[l],f,this._parentRunId,a,this.tags,this.metadata,u))}catch(g){if((h.raiseError?console.error:console.warn)(`Error in handler ${h.constructor.name}, handleLLMStart: ${g}`),h.raiseError)throw g}},h.awaitHandlers)})),new cg(f,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChatModelStart(n,r,s=void 0,i=void 0,a=void 0,o=void 0,c=void 0,u=void 0){return Promise.all(r.map(async(l,d)=>{const f=d===0&&s?s:Ps();return await Promise.all(this.handlers.map(h=>{if(!h.ignoreLLM)return Ka(h)&&h._createRunForChatModelStart(n,[l],f,this._parentRunId,a,this.tags,this.metadata,u),Ct(async()=>{var p,g;try{if(h.handleChatModelStart)await((p=h.handleChatModelStart)==null?void 0:p.call(h,n,[l],f,this._parentRunId,a,this.tags,this.metadata,u));else if(h.handleLLMStart){const y=ny(l);await((g=h.handleLLMStart)==null?void 0:g.call(h,n,[y],f,this._parentRunId,a,this.tags,this.metadata,u))}}catch(y){if((h.raiseError?console.error:console.warn)(`Error in handler ${h.constructor.name}, handleLLMStart: ${y}`),h.raiseError)throw y}},h.awaitHandlers)})),new cg(f,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChainStart(n,r,s=Ps(),i=void 0,a=void 0,o=void 0,c=void 0,u=void 0,l=void 0){return await Promise.all(this.handlers.map(d=>{if(!d.ignoreChain)return Ka(d)&&d._createRunForChainStart(n,r,s,this._parentRunId,this.tags,this.metadata,i,c,l),Ct(async()=>{var f;try{await((f=d.handleChainStart)==null?void 0:f.call(d,n,r,s,this._parentRunId,this.tags,this.metadata,i,c,l))}catch(h){if((d.raiseError?console.error:console.warn)(`Error in handler ${d.constructor.name}, handleChainStart: ${h}`),d.raiseError)throw h}},d.awaitHandlers)})),new $E(s,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleToolStart(n,r,s=Ps(),i=void 0,a=void 0,o=void 0,c=void 0,u=void 0){return await Promise.all(this.handlers.map(l=>{if(!l.ignoreAgent)return Ka(l)&&l._createRunForToolStart(n,r,s,this._parentRunId,this.tags,this.metadata,c),Ct(async()=>{var d;try{await((d=l.handleToolStart)==null?void 0:d.call(l,n,r,s,this._parentRunId,this.tags,this.metadata,c,u))}catch(f){if((l.raiseError?console.error:console.warn)(`Error in handler ${l.constructor.name}, handleToolStart: ${f}`),l.raiseError)throw f}},l.awaitHandlers)})),new RE(s,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleRetrieverStart(n,r,s=Ps(),i=void 0,a=void 0,o=void 0,c=void 0){return await Promise.all(this.handlers.map(u=>{if(!u.ignoreRetriever)return Ka(u)&&u._createRunForRetrieverStart(n,r,s,this._parentRunId,this.tags,this.metadata,c),Ct(async()=>{var l;try{await((l=u.handleRetrieverStart)==null?void 0:l.call(u,n,r,s,this._parentRunId,this.tags,this.metadata,c))}catch(d){if((u.raiseError?console.error:console.warn)(`Error in handler ${u.constructor.name}, handleRetrieverStart: ${d}`),u.raiseError)throw d}},u.awaitHandlers)})),new OE(s,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleCustomEvent(n,r,s,i,a){await Promise.all(this.handlers.map(o=>Ct(async()=>{var c;if(!o.ignoreCustomEvent)try{await((c=o.handleCustomEvent)==null?void 0:c.call(o,n,r,s,this.tags,this.metadata))}catch(u){if((o.raiseError?console.error:console.warn)(`Error in handler ${o.constructor.name}, handleCustomEvent: ${u}`),o.raiseError)throw u}},o.awaitHandlers)))}addHandler(n,r=!0){this.handlers.push(n),r&&this.inheritableHandlers.push(n)}removeHandler(n){this.handlers=this.handlers.filter(r=>r!==n),this.inheritableHandlers=this.inheritableHandlers.filter(r=>r!==n)}setHandlers(n,r=!0){this.handlers=[],this.inheritableHandlers=[];for(const s of n)this.addHandler(s,r)}addTags(n,r=!0){this.removeTags(n),this.tags.push(...n),r&&this.inheritableTags.push(...n)}removeTags(n){this.tags=this.tags.filter(r=>!n.includes(r)),this.inheritableTags=this.inheritableTags.filter(r=>!n.includes(r))}addMetadata(n,r=!0){this.metadata={...this.metadata,...n},r&&(this.inheritableMetadata={...this.inheritableMetadata,...n})}removeMetadata(n){for(const r of Object.keys(n))delete this.metadata[r],delete this.inheritableMetadata[r]}copy(n=[],r=!0){const s=new Nc(this._parentRunId);for(const i of this.handlers){const a=this.inheritableHandlers.includes(i);s.addHandler(i,a)}for(const i of this.tags){const a=this.inheritableTags.includes(i);s.addTags([i],a)}for(const i of Object.keys(this.metadata)){const a=Object.keys(this.inheritableMetadata).includes(i);s.addMetadata({[i]:this.metadata[i]},a)}for(const i of n)s.handlers.filter(a=>a.name==="console_callback_handler").some(a=>a.name===i.name)||s.addHandler(i,r);return s}static fromHandlers(n){class r extends qs{constructor(){super();m(this,"name",Ps());Object.assign(this,n)}}const s=new this;return s.addHandler(new r),s}static configure(n,r,s,i,a,o,c){return this._configureSync(n,r,s,i,a,o,c)}static _configureSync(n,r,s,i,a,o,c){var y;let u;(n||r)&&(Array.isArray(n)||!n?(u=new Nc,u.setHandlers((n==null?void 0:n.map(Su))??[],!0)):u=n,u=u.copy(Array.isArray(r)?r.map(Su):r==null?void 0:r.handlers,!1));const l=Mt("LANGCHAIN_VERBOSE")==="true"||(c==null?void 0:c.verbose),d=Pc.getTraceableRunTree(),f=(d==null?void 0:d.tracingEnabled)??nj();if((d==null?void 0:d.tracingEnabled)===!1&&u){const b=u.handlers.filter(_=>_.name==="langchain_tracer");for(const _ of b)u.removeHandler(_)}const h=f||(Mt("LANGCHAIN_TRACING")??!1);if(l||h){if(u||(u=new Nc),l&&!u.handlers.some(b=>b.name===ag.prototype.name)){const b=new ag;u.addHandler(b,!0)}if(h&&!u.handlers.some(b=>b.name==="langchain_tracer")&&f){const b=new Pc;u.addHandler(b,!0)}f&&d&&u._parentRunId===void 0&&(u._parentRunId=d.id,(y=u.handlers.find(b=>b.name==="langchain_tracer"))==null||y.updateFromRunTree(d))}for(const{contextVar:b,inheritable:_=!0,handlerClass:w,envVar:v}of sj()){const A=v&&Mt(v)==="true"&&w;let S;const x=b!==void 0?kE(b):void 0;x&&WT(x)?S=x:A&&(S=new w({})),S!==void 0&&(u||(u=new Nc),u.handlers.some(E=>E.name===S.name)||u.addHandler(S,_))}(s||i)&&u&&(u.addTags(s??[]),u.addTags(i??[],!1)),(a||o)&&u&&(u.addMetadata(a??{}),u.addMetadata(o??{},!1));const p=c==null?void 0:c.tracerInheritableMetadata,g=c==null?void 0:c.tracerInheritableTags;return u&&(p||g)&&(u.handlers=u.handlers.map(b=>b instanceof Pc?b.copyWithTracingConfig({metadata:p,tags:g}):b),u.inheritableHandlers=u.inheritableHandlers.map(b=>b instanceof Pc?b.copyWithTracingConfig({metadata:p,tags:g}):b)),u}};function Su(t){return"name"in t?t:qs.fromMethods(t)}var PE=class{getStore(){}run(t,e){return e()}enterWith(t){}};const aj=new PE,k0=Symbol.for("lc:child_config");var oj=class{getInstance(){return vu()??aj}getRunnableConfig(){var t,e;return(e=(t=this.getInstance().getStore())==null?void 0:t.extra)==null?void 0:e[k0]}runWithConfig(t,e,n){var u;const r=bn._configureSync(t==null?void 0:t.callbacks,void 0,t==null?void 0:t.tags,void 0,t==null?void 0:t.metadata),s=this.getInstance(),i=s.getStore(),a=r==null?void 0:r.getParentRunId(),o=(u=r==null?void 0:r.handlers)==null?void 0:u.find(l=>(l==null?void 0:l.name)==="langchain_tracer");let c;return o&&a?c=o.getRunTreeWithTracingConfig(a):n||(c=new Un({name:"<runnable_lambda>",tracingEnabled:!1})),c&&(c.extra={...c.extra,[k0]:t}),i!==void 0&&i[iu]!==void 0&&(c===void 0&&(c={}),c[iu]=i[iu]),s.run(c,e)}initializeGlobalInstance(t){vu()===void 0&&YL(t)}};const pn=new oj;var cj=de({AsyncLocalStorageProviderSingleton:()=>pn,MockAsyncLocalStorage:()=>PE,_CONTEXT_VARIABLES_KEY:()=>iu});const uj=new Set(["api_key"]),lj=new Set(["string","number","boolean"]);function dj(t){const e=t.configurable??{},n=t.metadata??{},r={};for(const[s,i]of Object.entries(e))!s.startsWith("__")&&!Object.prototype.hasOwnProperty.call(n,s)&&!uj.has(s)&&lj.has(typeof i)&&(r[s]=i);return Object.keys(r).length>0?r:void 0}async function ur(t){return bn._configureSync(t==null?void 0:t.callbacks,void 0,t==null?void 0:t.tags,void 0,t==null?void 0:t.metadata,void 0,{tracerInheritableMetadata:t?dj(t):void 0})}function ir(...t){const e={};for(const n of t.filter(r=>!!r))for(const r of Object.keys(n))if(r==="metadata")e[r]={...e[r],...n[r]};else if(r==="tags"){const s=e[r]??[];e[r]=[...new Set(s.concat(n[r]??[]))]}else if(r==="configurable")e[r]={...e[r],...n[r]};else if(r==="timeout")e.timeout===void 0?e.timeout=n.timeout:n.timeout!==void 0&&(e.timeout=Math.min(e.timeout,n.timeout));else if(r==="signal")e.signal===void 0?e.signal=n.signal:n.signal!==void 0&&("any"in AbortSignal?e.signal=AbortSignal.any([e.signal,n.signal]):e.signal=n.signal);else if(r==="callbacks"){const s=e.callbacks,i=n.callbacks;if(Array.isArray(i))if(!s)e.callbacks=i;else if(Array.isArray(s))e.callbacks=s.concat(i);else{const a=s.copy();for(const o of i)a.addHandler(Su(o),!0);e.callbacks=a}else if(i)if(!s)e.callbacks=i;else if(Array.isArray(s)){const a=i.copy();for(const o of s)a.addHandler(Su(o),!0);e.callbacks=a}else e.callbacks=new bn(i._parentRunId,{handlers:s.handlers.concat(i.handlers),inheritableHandlers:s.inheritableHandlers.concat(i.inheritableHandlers),tags:Array.from(new Set(s.tags.concat(i.tags))),inheritableTags:Array.from(new Set(s.inheritableTags.concat(i.inheritableTags))),metadata:{...s.metadata,...i.metadata}})}else{const s=r;e[s]=n[s]??e[s]}return e}function Je(t){var r;const e=pn.getRunnableConfig();let n={tags:[],metadata:{},recursionLimit:25,runId:void 0};if(e){const{runId:s,runName:i,...a}=e;n=Object.entries(a).reduce((o,[c,u])=>(u!==void 0&&(o[c]=u),o),n)}if(t&&(n=Object.entries(t).reduce((s,[i,a])=>(a!==void 0&&(s[i]=a),s),n)),n!=null&&n.configurable&&typeof n.configurable.model=="string"&&((r=n.metadata)==null?void 0:r.model)===void 0&&(n.metadata||(n.metadata={}),n.metadata.model=n.configurable.model),n.timeout!==void 0){if(n.timeout<=0)throw new Error("Timeout must be a positive number");const s=n.timeout,i=AbortSignal.timeout(s);n.metadata||(n.metadata={}),n.metadata.timeoutMs===void 0&&(n.metadata.timeoutMs=s),n.signal!==void 0?"any"in AbortSignal&&(n.signal=AbortSignal.any([n.signal,i])):n.signal=i,delete n.timeout}return n}function et(t={},{callbacks:e,maxConcurrency:n,recursionLimit:r,runName:s,configurable:i,runId:a}={}){const o=Je(t);return e!==void 0&&(delete o.runName,o.callbacks=e),r!==void 0&&(o.recursionLimit=r),n!==void 0&&(o.maxConcurrency=n),s!==void 0&&(o.runName=s),i!==void 0&&(o.configurable={...o.configurable,...i}),a!==void 0&&delete o.runId,o}function Hs(t){if(t)return{configurable:t.configurable,recursionLimit:t.recursionLimit,callbacks:t.callbacks,tags:t.tags,metadata:t.metadata,maxConcurrency:t.maxConcurrency,timeout:t.timeout,signal:t.signal,store:t.store}}async function Ss(t,e){if(e===void 0)return t;let n;return Promise.race([t.catch(r=>{if(!(e!=null&&e.aborted))throw r}),new Promise((r,s)=>{n=()=>{s(Au(e))},e.addEventListener("abort",n,{once:!0}),e.aborted&&s(Au(e))})]).finally(()=>e.removeEventListener("abort",n))}function Au(t){return(t==null?void 0:t.reason)instanceof Error?t.reason:typeof(t==null?void 0:t.reason)=="string"?new Error(t.reason):new Error("Aborted")}var hj=de({AsyncGeneratorWithSetup:()=>ka,IterableReadableStream:()=>Vn,atee:()=>_y,concat:()=>Vs,pipeGeneratorWithSetup:()=>NE}),Vn=class ug extends ReadableStream{constructor(){super(...arguments);m(this,"reader")}ensureReader(){this.reader||(this.reader=this.getReader())}async next(){this.ensureReader();try{const n=await this.reader.read();return n.done?(this.reader.releaseLock(),{done:!0,value:void 0}):{done:!1,value:n.value}}catch(n){throw this.reader.releaseLock(),n}}async return(){if(this.ensureReader(),this.locked){const n=this.reader.cancel();this.reader.releaseLock(),await n}return{done:!0,value:void 0}}async throw(n){if(this.ensureReader(),this.locked){const r=this.reader.cancel();this.reader.releaseLock(),await r}throw n}[Symbol.asyncIterator](){return this}async[Symbol.asyncDispose](){await this.return()}static fromReadableStream(n){const r=n.getReader();return new ug({start(s){return i();function i(){return r.read().then(({done:a,value:o})=>{if(a){s.close();return}return s.enqueue(o),i()})}},cancel(){r.releaseLock()}})}static fromAsyncGenerator(n){return new ug({async pull(r){const{value:s,done:i}=await n.next();i&&r.close(),r.enqueue(s)},async cancel(r){await n.return(r)}})}};function _y(t,e=2){const n=Array.from({length:e},()=>[]);return n.map(async function*(s){for(;;)if(s.length===0){const i=await t.next();for(const a of n)a.push(i)}else{if(s[0].done)return;yield s.shift().value}})}function Vs(t,e){if(Array.isArray(t)&&Array.isArray(e))return t.concat(e);if(typeof t=="string"&&typeof e=="string")return t+e;if(typeof t=="number"&&typeof e=="number")return t+e;if("concat"in t&&typeof t.concat=="function")return t.concat(e);if(typeof t=="object"&&typeof e=="object"){const n={...t};for(const[r,s]of Object.entries(e))r in n&&!Array.isArray(n[r])?n[r]=Vs(n[r],s):n[r]=s;return n}else throw new Error(`Cannot concat ${typeof t} and ${typeof e}`)}var ka=class{constructor(t){m(this,"generator");m(this,"setup");m(this,"config");m(this,"signal");m(this,"firstResult");m(this,"firstResultUsed",!1);var e;this.generator=t.generator,this.config=t.config,this.signal=t.signal??((e=this.config)==null?void 0:e.signal),this.setup=new Promise((n,r)=>{pn.runWithConfig(Hs(t.config),async()=>{this.firstResult=this.signal?Ss(t.generator.next(),this.signal):t.generator.next(),t.startSetup?this.firstResult.then(t.startSetup).then(n,r):this.firstResult.then(s=>n(void 0),r)},!0)})}async next(...t){var e;return(e=this.signal)==null||e.throwIfAborted(),this.firstResultUsed?pn.runWithConfig(Hs(this.config),this.signal?async()=>Ss(this.generator.next(...t),this.signal):async()=>this.generator.next(...t),!0):(this.firstResultUsed=!0,this.firstResult)}async return(t){return this.generator.return(t)}async throw(t){return this.generator.throw(t)}[Symbol.asyncIterator](){return this}async[Symbol.asyncDispose](){await this.return()}};async function NE(t,e,n,r,...s){const i=new ka({generator:e,startSetup:n,signal:r}),a=await i.setup;return{output:t(i,a,...s),setup:a}}/*!
|
|
62
|
-
* https://github.com/Starcounter-Jack/JSON-Patch
|
|
63
|
-
* (c) 2017-2022 Joachim Wester
|
|
64
|
-
* MIT licensed
|
|
65
|
-
*/const fj=Object.prototype.hasOwnProperty;function lg(t,e){return fj.call(t,e)}function dg(t){if(Array.isArray(t)){const n=new Array(t.length);for(let r=0;r<n.length;r++)n[r]=""+r;return n}if(Object.keys)return Object.keys(t);let e=[];for(let n in t)lg(t,n)&&e.push(n);return e}function Wr(t){switch(typeof t){case"object":return JSON.parse(JSON.stringify(t));case"undefined":return null;default:return t}}function hg(t){let e=0;const n=t.length;let r;for(;e<n;){if(r=t.charCodeAt(e),r>=48&&r<=57){e++;continue}return!1}return!0}function Oa(t){return t.indexOf("/")===-1&&t.indexOf("~")===-1?t:t.replace(/~/g,"~0").replace(/\//g,"~1")}function pj(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}function fg(t){if(t===void 0)return!0;if(t){if(Array.isArray(t)){for(let n=0,r=t.length;n<r;n++)if(fg(t[n]))return!0}else if(typeof t=="object"){const n=dg(t),r=n.length;for(var e=0;e<r;e++)if(fg(t[n[e]]))return!0}}return!1}function C0(t,e){const n=[t];for(const r in e){const s=typeof e[r]=="object"?JSON.stringify(e[r],null,2):e[r];typeof s<"u"&&n.push(`${r}: ${s}`)}return n.join(`
|
|
66
|
-
`)}var mj=class extends Error{constructor(t,e,n,r,s){super(C0(t,{name:e,index:n,operation:r,tree:s})),this.name=e,this.index=n,this.operation=r,this.tree=s,Object.setPrototypeOf(this,new.target.prototype),this.message=C0(t,{name:e,index:n,operation:r,tree:s})}},gj=de({JsonPatchError:()=>kt,_areEquals:()=>Tu,applyOperation:()=>da,applyPatch:()=>Mo,applyReducer:()=>wj,deepClone:()=>_j,getValueByPointer:()=>Eh,validate:()=>ME,validator:()=>Ih});const kt=mj,_j=Wr,ro={add:function(t,e,n){if(e==="__proto__"||e==="constructor")throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor` prop is banned for security reasons");return t[e]=this.value,{newDocument:n}},remove:function(t,e,n){if(e==="__proto__"||e==="constructor")throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor` prop is banned for security reasons");var r=t[e];return delete t[e],{newDocument:n,removed:r}},replace:function(t,e,n){if(e==="__proto__"||e==="constructor")throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor` prop is banned for security reasons");var r=t[e];return t[e]=this.value,{newDocument:n,removed:r}},move:function(t,e,n){let r=Eh(n,this.path);r&&(r=Wr(r));const s=da(n,{op:"remove",path:this.from}).removed;return da(n,{op:"add",path:this.path,value:s}),{newDocument:n,removed:r}},copy:function(t,e,n){const r=Eh(n,this.from);return da(n,{op:"add",path:this.path,value:Wr(r)}),{newDocument:n}},test:function(t,e,n){return{newDocument:n,test:Tu(t[e],this.value)}},_get:function(t,e,n){return this.value=t[e],{newDocument:n}}};var yj={add:function(t,e,n){return hg(e)?t.splice(e,0,this.value):t[e]=this.value,{newDocument:n,index:e}},remove:function(t,e,n){return{newDocument:n,removed:t.splice(e,1)[0]}},replace:function(t,e,n){var r=t[e];return t[e]=this.value,{newDocument:n,removed:r}},move:ro.move,copy:ro.copy,test:ro.test,_get:ro._get};function Eh(t,e){if(e=="")return t;var n={op:"_get",path:e};return da(t,n),n.value}function da(t,e,n=!1,r=!0,s=!0,i=0){if(n&&(typeof n=="function"?n(e,0,t,e.path):Ih(e,0)),e.path===""){let a={newDocument:t};if(e.op==="add")return a.newDocument=e.value,a;if(e.op==="replace")return a.newDocument=e.value,a.removed=t,a;if(e.op==="move"||e.op==="copy")return a.newDocument=Eh(t,e.from),e.op==="move"&&(a.removed=t),a;if(e.op==="test"){if(a.test=Tu(t,e.value),a.test===!1)throw new kt("Test operation failed","TEST_OPERATION_FAILED",i,e,t);return a.newDocument=t,a}else{if(e.op==="remove")return a.removed=t,a.newDocument=null,a;if(e.op==="_get")return e.value=t,a;if(n)throw new kt("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",i,e,t);return a}}else{r||(t=Wr(t));const a=(e.path||"").split("/");let o=t,c=1,u=a.length,l,d,f;for(typeof n=="function"?f=n:f=Ih;;){if(d=a[c],d&&d.indexOf("~")!=-1&&(d=pj(d)),s&&(d=="__proto__"||d=="prototype"&&c>0&&a[c-1]=="constructor"))throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(n&&l===void 0&&(o[d]===void 0?l=a.slice(0,c).join("/"):c==u-1&&(l=e.path),l!==void 0&&f(e,0,t,l)),c++,Array.isArray(o)){if(d==="-")d=o.length;else{if(n&&!hg(d))throw new kt("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",i,e,t);hg(d)&&(d=~~d)}if(c>=u){if(n&&e.op==="add"&&d>o.length)throw new kt("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",i,e,t);const h=yj[e.op].call(e,o,d,t);if(h.test===!1)throw new kt("Test operation failed","TEST_OPERATION_FAILED",i,e,t);return h}}else if(c>=u){const h=ro[e.op].call(e,o,d,t);if(h.test===!1)throw new kt("Test operation failed","TEST_OPERATION_FAILED",i,e,t);return h}if(o=o[d],n&&c<u&&(!o||typeof o!="object"))throw new kt("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",i,e,t)}}}function Mo(t,e,n,r=!0,s=!0){if(n&&!Array.isArray(e))throw new kt("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");r||(t=Wr(t));const i=new Array(e.length);for(let a=0,o=e.length;a<o;a++)i[a]=da(t,e[a],n,!0,s,a),t=i[a].newDocument;return i.newDocument=t,i}function wj(t,e,n){const r=da(t,e);if(r.test===!1)throw new kt("Test operation failed","TEST_OPERATION_FAILED",n,e,t);return r.newDocument}function Ih(t,e,n,r){if(typeof t!="object"||t===null||Array.isArray(t))throw new kt("Operation is not an object","OPERATION_NOT_AN_OBJECT",e,t,n);if(ro[t.op]){if(typeof t.path!="string")throw new kt("Operation `path` property is not a string","OPERATION_PATH_INVALID",e,t,n);if(t.path.indexOf("/")!==0&&t.path.length>0)throw new kt('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",e,t,n);if((t.op==="move"||t.op==="copy")&&typeof t.from!="string")throw new kt("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",e,t,n);if((t.op==="add"||t.op==="replace"||t.op==="test")&&t.value===void 0)throw new kt("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",e,t,n);if((t.op==="add"||t.op==="replace"||t.op==="test")&&fg(t.value))throw new kt("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",e,t,n);if(n){if(t.op=="add"){var s=t.path.split("/").length,i=r.split("/").length;if(s!==i+1&&s!==i)throw new kt("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",e,t,n)}else if(t.op==="replace"||t.op==="remove"||t.op==="_get"){if(t.path!==r)throw new kt("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",e,t,n)}else if(t.op==="move"||t.op==="copy"){var a=ME([{op:"_get",path:t.from,value:void 0}],n);if(a&&a.name==="OPERATION_PATH_UNRESOLVABLE")throw new kt("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",e,t,n)}}}else throw new kt("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",e,t,n)}function ME(t,e,n){try{if(!Array.isArray(t))throw new kt("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(e)Mo(Wr(e),Wr(t),n||!0);else{n=n||Ih;for(var r=0;r<t.length;r++)n(t[r],r,e,void 0)}}catch(s){if(s instanceof kt)return s;throw s}}function Tu(t,e){if(t===e)return!0;if(t&&e&&typeof t=="object"&&typeof e=="object"){var n=Array.isArray(t),r=Array.isArray(e),s,i,a;if(n&&r){if(i=t.length,i!=e.length)return!1;for(s=i;s--!==0;)if(!Tu(t[s],e[s]))return!1;return!0}if(n!=r)return!1;var o=Object.keys(t);if(i=o.length,i!==Object.keys(e).length)return!1;for(s=i;s--!==0;)if(!e.hasOwnProperty(o[s]))return!1;for(s=i;s--!==0;)if(a=o[s],!Tu(t[a],e[a]))return!1;return!0}return t!==t&&e!==e}/*!
|
|
67
|
-
* https://github.com/Starcounter-Jack/JSON-Patch
|
|
68
|
-
* (c) 2013-2021 Joachim Wester
|
|
69
|
-
* MIT license
|
|
70
|
-
*/function LE(t,e,n,r,s){if(e!==t){typeof e.toJSON=="function"&&(e=e.toJSON());for(var i=dg(e),a=dg(t),o=!1,c=a.length-1;c>=0;c--){var u=a[c],l=t[u];if(lg(e,u)&&!(e[u]===void 0&&l!==void 0&&Array.isArray(e)===!1)){var d=e[u];typeof l=="object"&&l!=null&&typeof d=="object"&&d!=null&&Array.isArray(l)===Array.isArray(d)?LE(l,d,n,r+"/"+Oa(u),s):l!==d&&(s&&n.push({op:"test",path:r+"/"+Oa(u),value:Wr(l)}),n.push({op:"replace",path:r+"/"+Oa(u),value:Wr(d)}))}else Array.isArray(t)===Array.isArray(e)?(s&&n.push({op:"test",path:r+"/"+Oa(u),value:Wr(l)}),n.push({op:"remove",path:r+"/"+Oa(u)}),o=!0):(s&&n.push({op:"test",path:r,value:t}),n.push({op:"replace",path:r,value:e}))}if(!(!o&&i.length==a.length))for(var c=0;c<i.length;c++){var u=i[c];!lg(t,u)&&e[u]!==void 0&&n.push({op:"add",path:r+"/"+Oa(u),value:Wr(e[u])})}}}function Af(t,e,n=!1){var r=[];return LE(t,e,r,"",n),r}({...gj});var bj=de({LogStreamCallbackHandler:()=>mg,RunLog:()=>yy,RunLogPatch:()=>Ms,isLogStreamHandler:()=>jE}),Ms=class{constructor(t){m(this,"ops");this.ops=t.ops??[]}concat(t){const e=this.ops.concat(t.ops),n=Mo({},e);return new yy({ops:e,state:n[n.length-1].newDocument})}},yy=class pg extends Ms{constructor(n){super(n);m(this,"state");this.state=n.state}concat(n){const r=this.ops.concat(n.ops),s=Mo(this.state,n.ops);return new pg({ops:r,state:s[s.length-1].newDocument})}static fromRunLogPatch(n){const r=Mo({},n.ops);return new pg({ops:n.ops,state:r[r.length-1].newDocument})}};const jE=t=>t.name==="log_stream_tracer";async function O0(t,e){if(e==="original")throw new Error("Do not assign inputs with original schema drop the key for now. When inputs are added to streamLog they should be added with standardized schema for streaming events.");const{inputs:n}=t;if(["retriever","llm","prompt"].includes(t.run_type))return n;if(!(Object.keys(n).length===1&&(n==null?void 0:n.input)===""))return n.input}async function $0(t,e){const{outputs:n}=t;return e==="original"||["retriever","llm","prompt"].includes(t.run_type)?n:n!==void 0&&Object.keys(n).length===1&&(n==null?void 0:n.output)!==void 0?n.output:n}function vj(t){return t!==void 0&&t.message!==void 0}var mg=class extends Gs{constructor(e){super({_awaitHandler:!0,...e});m(this,"autoClose",!0);m(this,"includeNames");m(this,"includeTypes");m(this,"includeTags");m(this,"excludeNames");m(this,"excludeTypes");m(this,"excludeTags");m(this,"_schemaFormat","original");m(this,"rootId");m(this,"keyMapByRunId",{});m(this,"counterMapByRunName",{});m(this,"transformStream");m(this,"writer");m(this,"receiveStream");m(this,"name","log_stream_tracer");m(this,"lc_prefer_streaming",!0);this.autoClose=(e==null?void 0:e.autoClose)??!0,this.includeNames=e==null?void 0:e.includeNames,this.includeTypes=e==null?void 0:e.includeTypes,this.includeTags=e==null?void 0:e.includeTags,this.excludeNames=e==null?void 0:e.excludeNames,this.excludeTypes=e==null?void 0:e.excludeTypes,this.excludeTags=e==null?void 0:e.excludeTags,this._schemaFormat=(e==null?void 0:e._schemaFormat)??this._schemaFormat,this.transformStream=new TransformStream,this.writer=this.transformStream.writable.getWriter(),this.receiveStream=Vn.fromReadableStream(this.transformStream.readable)}[Symbol.asyncIterator](){return this.receiveStream}async persistRun(e){}_includeRun(e){if(e.id===this.rootId)return!1;const n=e.tags??[];let r=this.includeNames===void 0&&this.includeTags===void 0&&this.includeTypes===void 0;return this.includeNames!==void 0&&(r=r||this.includeNames.includes(e.name)),this.includeTypes!==void 0&&(r=r||this.includeTypes.includes(e.run_type)),this.includeTags!==void 0&&(r=r||n.find(s=>{var i;return(i=this.includeTags)==null?void 0:i.includes(s)})!==void 0),this.excludeNames!==void 0&&(r=r&&!this.excludeNames.includes(e.name)),this.excludeTypes!==void 0&&(r=r&&!this.excludeTypes.includes(e.run_type)),this.excludeTags!==void 0&&(r=r&&n.every(s=>{var i;return!((i=this.excludeTags)!=null&&i.includes(s))})),r}async*tapOutputIterable(e,n){for await(const r of n){if(e!==this.rootId){const s=this.keyMapByRunId[e];s&&await this.writer.write(new Ms({ops:[{op:"add",path:`/logs/${s}/streamed_output/-`,value:r}]}))}yield r}}async onRunCreate(e){var s;if(this.rootId===void 0&&(this.rootId=e.id,await this.writer.write(new Ms({ops:[{op:"replace",path:"",value:{id:e.id,name:e.name,type:e.run_type,streamed_output:[],final_output:void 0,logs:{}}}]}))),!this._includeRun(e))return;this.counterMapByRunName[e.name]===void 0&&(this.counterMapByRunName[e.name]=0),this.counterMapByRunName[e.name]+=1;const n=this.counterMapByRunName[e.name];this.keyMapByRunId[e.id]=n===1?e.name:`${e.name}:${n}`;const r={id:e.id,name:e.name,type:e.run_type,tags:e.tags??[],metadata:((s=e.extra)==null?void 0:s.metadata)??{},start_time:new Date(e.start_time).toISOString(),streamed_output:[],streamed_output_str:[],final_output:void 0,end_time:void 0};this._schemaFormat==="streaming_events"&&(r.inputs=await O0(e,this._schemaFormat)),await this.writer.write(new Ms({ops:[{op:"add",path:`/logs/${this.keyMapByRunId[e.id]}`,value:r}]}))}async onRunUpdate(e){try{const n=this.keyMapByRunId[e.id];if(n===void 0)return;const r=[];this._schemaFormat==="streaming_events"&&r.push({op:"replace",path:`/logs/${n}/inputs`,value:await O0(e,this._schemaFormat)}),r.push({op:"add",path:`/logs/${n}/final_output`,value:await $0(e,this._schemaFormat)}),e.end_time!==void 0&&r.push({op:"add",path:`/logs/${n}/end_time`,value:new Date(e.end_time).toISOString()});const s=new Ms({ops:r});await this.writer.write(s)}finally{if(e.id===this.rootId){const n=new Ms({ops:[{op:"replace",path:"/final_output",value:await $0(e,this._schemaFormat)}]});await this.writer.write(n),this.autoClose&&await this.writer.close()}}}async onLLMNewToken(e,n,r){const s=this.keyMapByRunId[e.id];if(s===void 0)return;const i=e.inputs.messages!==void 0;let a;i?vj(r==null?void 0:r.chunk)?a=r==null?void 0:r.chunk:a=new Ge({id:`run-${e.id}`,content:n}):a=n;const o=new Ms({ops:[{op:"add",path:`/logs/${s}/streamed_output_str/-`,value:n},{op:"add",path:`/logs/${s}/streamed_output/-`,value:a}]});await this.writer.write(o)}},Sj=de({ChatGenerationChunk:()=>dr,GenerationChunk:()=>Lo,RUN_KEY:()=>Eu});const Eu="__run";var Lo=class DE{constructor(e){m(this,"text");m(this,"generationInfo");this.text=e.text,this.generationInfo=e.generationInfo}concat(e){return new DE({text:this.text+e.text,generationInfo:{...this.generationInfo,...e.generationInfo}})}},dr=class UE extends Lo{constructor(n){super(n);m(this,"message");this.message=n.message}concat(n){return new UE({text:this.text+n.text,generationInfo:{...this.generationInfo,...n.generationInfo},message:this.message.concat(n.message)})}};function Gl({name:t,serialized:e}){return t!==void 0?t:(e==null?void 0:e.name)!==void 0?e.name:(e==null?void 0:e.id)!==void 0&&Array.isArray(e==null?void 0:e.id)?e.id[e.id.length-1]:"Unnamed"}const Aj=t=>t.name==="event_stream_tracer";var Tj=class extends Gs{constructor(e){super({_awaitHandler:!0,...e});m(this,"autoClose",!0);m(this,"includeNames");m(this,"includeTypes");m(this,"includeTags");m(this,"excludeNames");m(this,"excludeTypes");m(this,"excludeTags");m(this,"runInfoMap",new Map);m(this,"tappedPromises",new Map);m(this,"transformStream");m(this,"writer");m(this,"receiveStream");m(this,"readableStreamClosed",!1);m(this,"name","event_stream_tracer");m(this,"lc_prefer_streaming",!0);this.autoClose=(e==null?void 0:e.autoClose)??!0,this.includeNames=e==null?void 0:e.includeNames,this.includeTypes=e==null?void 0:e.includeTypes,this.includeTags=e==null?void 0:e.includeTags,this.excludeNames=e==null?void 0:e.excludeNames,this.excludeTypes=e==null?void 0:e.excludeTypes,this.excludeTags=e==null?void 0:e.excludeTags,this.transformStream=new TransformStream({flush:()=>{this.readableStreamClosed=!0}}),this.writer=this.transformStream.writable.getWriter(),this.receiveStream=Vn.fromReadableStream(this.transformStream.readable)}[Symbol.asyncIterator](){return this.receiveStream}async persistRun(e){}_includeRun(e){const n=e.tags??[];let r=this.includeNames===void 0&&this.includeTags===void 0&&this.includeTypes===void 0;return this.includeNames!==void 0&&(r=r||this.includeNames.includes(e.name)),this.includeTypes!==void 0&&(r=r||this.includeTypes.includes(e.runType)),this.includeTags!==void 0&&(r=r||n.find(s=>{var i;return(i=this.includeTags)==null?void 0:i.includes(s)})!==void 0),this.excludeNames!==void 0&&(r=r&&!this.excludeNames.includes(e.name)),this.excludeTypes!==void 0&&(r=r&&!this.excludeTypes.includes(e.runType)),this.excludeTags!==void 0&&(r=r&&n.every(s=>{var i;return!((i=this.excludeTags)!=null&&i.includes(s))})),r}async*tapOutputIterable(e,n){const r=await n.next();if(r.done)return;const s=this.runInfoMap.get(e);if(s===void 0){yield r.value;return}function i(o,c){return o==="llm"&&typeof c=="string"?new Lo({text:c}):c}let a=this.tappedPromises.get(e);if(a===void 0){let o;a=new Promise(c=>{o=c}),this.tappedPromises.set(e,a);try{const c={event:`on_${s.runType}_stream`,run_id:e,name:s.name,tags:s.tags,metadata:s.metadata,data:{}};await this.send({...c,data:{chunk:i(s.runType,r.value)}},s),yield r.value;for await(const u of n)s.runType!=="tool"&&s.runType!=="retriever"&&await this.send({...c,data:{chunk:i(s.runType,u)}},s),yield u}finally{o==null||o()}}else{yield r.value;for await(const o of n)yield o}}async send(e,n){this.readableStreamClosed||this._includeRun(n)&&await this.writer.write(e)}async sendEndEvent(e,n){const r=this.tappedPromises.get(e.run_id);r!==void 0?r.then(()=>{this.send(e,n)}):await this.send(e,n)}async onLLMStart(e){var a,o;const n=Gl(e),r=e.inputs.messages!==void 0?"chat_model":"llm",s={tags:e.tags??[],metadata:((a=e.extra)==null?void 0:a.metadata)??{},name:n,runType:r,inputs:e.inputs};this.runInfoMap.set(e.id,s);const i=`on_${r}_start`;await this.send({event:i,data:{input:e.inputs},name:n,tags:e.tags??[],run_id:e.id,metadata:((o=e.extra)==null?void 0:o.metadata)??{}},s)}async onLLMNewToken(e,n,r){const s=this.runInfoMap.get(e.id);let i,a;if(s===void 0)throw new Error(`onLLMNewToken: Run ID ${e.id} not found in run map.`);if(this.runInfoMap.size!==1){if(s.runType==="chat_model")a="on_chat_model_stream",(r==null?void 0:r.chunk)===void 0?i=new Ge({content:n,id:`run-${e.id}`}):i=r.chunk.message;else if(s.runType==="llm")a="on_llm_stream",(r==null?void 0:r.chunk)===void 0?i=new Lo({text:n}):i=r.chunk;else throw new Error(`Unexpected run type ${s.runType}`);await this.send({event:a,data:{chunk:i},run_id:e.id,name:s.name,tags:s.tags,metadata:s.metadata},s)}}async onLLMEnd(e){var a,o,c;const n=this.runInfoMap.get(e.id);this.runInfoMap.delete(e.id);let r;if(n===void 0)throw new Error(`onLLMEnd: Run ID ${e.id} not found in run map.`);const s=(a=e.outputs)==null?void 0:a.generations;let i;if(n.runType==="chat_model"){for(const u of s??[]){if(i!==void 0)break;i=(o=u[0])==null?void 0:o.message}r="on_chat_model_end"}else if(n.runType==="llm")i={generations:s==null?void 0:s.map(u=>u.map(l=>({text:l.text,generationInfo:l.generationInfo}))),llmOutput:((c=e.outputs)==null?void 0:c.llmOutput)??{}},r="on_llm_end";else throw new Error(`onLLMEnd: Unexpected run type: ${n.runType}`);await this.sendEndEvent({event:r,data:{output:i,input:n.inputs},run_id:e.id,name:n.name,tags:n.tags,metadata:n.metadata},n)}async onChainStart(e){var a,o;const n=Gl(e),r=e.run_type??"chain",s={tags:e.tags??[],metadata:((a=e.extra)==null?void 0:a.metadata)??{},name:n,runType:e.run_type};let i={};e.inputs.input===""&&Object.keys(e.inputs).length===1?(i={},s.inputs={}):e.inputs.input!==void 0?(i.input=e.inputs.input,s.inputs=e.inputs.input):(i.input=e.inputs,s.inputs=e.inputs),this.runInfoMap.set(e.id,s),await this.send({event:`on_${r}_start`,data:i,name:n,tags:e.tags??[],run_id:e.id,metadata:((o=e.extra)==null?void 0:o.metadata)??{}},s)}async onChainEnd(e){var a;const n=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),n===void 0)throw new Error(`onChainEnd: Run ID ${e.id} not found in run map.`);const r=`on_${e.run_type}_end`,s=e.inputs??n.inputs??{},i={output:((a=e.outputs)==null?void 0:a.output)??e.outputs,input:s};s.input&&Object.keys(s).length===1&&(i.input=s.input,n.inputs=s.input),await this.sendEndEvent({event:r,data:i,run_id:e.id,name:n.name,tags:n.tags,metadata:n.metadata??{}},n)}async onToolStart(e){var s,i;const n=Gl(e),r={tags:e.tags??[],metadata:((s=e.extra)==null?void 0:s.metadata)??{},name:n,runType:"tool",inputs:e.inputs??{}};this.runInfoMap.set(e.id,r),await this.send({event:"on_tool_start",data:{input:e.inputs??{}},name:n,run_id:e.id,tags:e.tags??[],metadata:((i=e.extra)==null?void 0:i.metadata)??{}},r)}async onToolEnd(e){var s;const n=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),n===void 0)throw new Error(`onToolEnd: Run ID ${e.id} not found in run map.`);if(n.inputs===void 0)throw new Error(`onToolEnd: Run ID ${e.id} is a tool call, and is expected to have traced inputs.`);const r=((s=e.outputs)==null?void 0:s.output)===void 0?e.outputs:e.outputs.output;await this.sendEndEvent({event:"on_tool_end",data:{output:r,input:n.inputs},run_id:e.id,name:n.name,tags:n.tags,metadata:n.metadata},n)}async onToolError(e){const n=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),n===void 0)throw new Error(`onToolEnd: Run ID ${e.id} not found in run map.`);if(n.inputs===void 0)throw new Error(`onToolEnd: Run ID ${e.id} is a tool call, and is expected to have traced inputs.`);await this.sendEndEvent({event:"on_tool_error",data:{input:n.inputs,error:e.error},run_id:e.id,name:n.name,tags:n.tags,metadata:n.metadata},n)}async onRetrieverStart(e){var s,i;const n=Gl(e),r={tags:e.tags??[],metadata:((s=e.extra)==null?void 0:s.metadata)??{},name:n,runType:"retriever",inputs:{query:e.inputs.query}};this.runInfoMap.set(e.id,r),await this.send({event:"on_retriever_start",data:{input:{query:e.inputs.query}},name:n,tags:e.tags??[],run_id:e.id,metadata:((i=e.extra)==null?void 0:i.metadata)??{}},r)}async onRetrieverEnd(e){var r;const n=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),n===void 0)throw new Error(`onRetrieverEnd: Run ID ${e.id} not found in run map.`);await this.sendEndEvent({event:"on_retriever_end",data:{output:((r=e.outputs)==null?void 0:r.documents)??e.outputs,input:n.inputs},run_id:e.id,name:n.name,tags:n.tags,metadata:n.metadata},n)}async handleCustomEvent(e,n,r){const s=this.runInfoMap.get(r);if(s===void 0)throw new Error(`handleCustomEvent: Run ID ${r} not found in run map.`);await this.send({event:"on_custom_event",run_id:r,name:e,tags:s.tags,metadata:s.metadata,data:n},s)}async finish(){const e=[...this.tappedPromises.values()];Promise.all(e).finally(()=>{this.writer.close()})}};const Ej=Object.prototype.toString,Ij=t=>Ej.call(t)==="[object Error]",xj=new Set(["network error","Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed","fetch failed","terminated"," A network error occurred.","Network connection lost"]);function kj(t){if(!(t&&Ij(t)&&t.name==="TypeError"&&typeof t.message=="string"))return!1;const{message:e,stack:n}=t;return e==="Load failed"?n===void 0||"__sentry_captured__"in t:e.startsWith("error sending request for url")?!0:xj.has(e)}function Cj(t){if(typeof t=="number"){if(t<0)throw new TypeError("Expected `retries` to be a non-negative number.");if(Number.isNaN(t))throw new TypeError("Expected `retries` to be a valid number or Infinity, got NaN.")}else if(t!==void 0)throw new TypeError("Expected `retries` to be a number or Infinity.")}function Jl(t,e,{min:n=0,allowInfinity:r=!1}={}){if(e!==void 0){if(typeof e!="number"||Number.isNaN(e))throw new TypeError(`Expected \`${t}\` to be a number${r?" or Infinity":""}.`);if(!r&&!Number.isFinite(e))throw new TypeError(`Expected \`${t}\` to be a finite number.`);if(e<n)throw new TypeError(`Expected \`${t}\` to be ≥ ${n}.`)}}var Oj=class extends Error{constructor(t){super(),t instanceof Error?(this.originalError=t,{message:t}=t):(this.originalError=new Error(t),this.originalError.stack=this.stack),this.name="AbortError",this.message=t}};function $j(t,e){const n=Math.max(1,t+1),r=e.randomize?Math.random()+1:1;let s=Math.round(r*e.minTimeout*e.factor**(n-1));return s=Math.min(s,e.maxTimeout),s}function R0(t,e){return Number.isFinite(e)?e-(performance.now()-t):e}async function Rj({error:t,attemptNumber:e,retriesConsumed:n,startTime:r,options:s}){var h,p,g;const i=t instanceof Error?t:new TypeError(`Non-error was thrown: "${t}". You should only throw errors.`);if(i instanceof Oj)throw i.originalError;const a=Number.isFinite(s.retries)?Math.max(0,s.retries-n):s.retries,o=s.maxRetryTime??Number.POSITIVE_INFINITY,c=Object.freeze({error:i,attemptNumber:e,retriesLeft:a,retriesConsumed:n});if(await s.onFailedAttempt(c),R0(r,o)<=0)throw i;const u=await s.shouldConsumeRetry(c),l=R0(r,o);if(l<=0||a<=0)throw i;if(i instanceof TypeError&&!kj(i)){if(u)throw i;return(h=s.signal)==null||h.throwIfAborted(),!1}if(!await s.shouldRetry(c))throw i;if(!u)return(p=s.signal)==null||p.throwIfAborted(),!1;const d=$j(n,s),f=Math.min(d,l);return f>0&&await new Promise((y,b)=>{var v,A;const _=()=>{var S;clearTimeout(w),(S=s.signal)==null||S.removeEventListener("abort",_),b(s.signal.reason)},w=setTimeout(()=>{var S;(S=s.signal)==null||S.removeEventListener("abort",_),y()},f);s.unref&&((v=w.unref)==null||v.call(w)),(A=s.signal)==null||A.addEventListener("abort",_,{once:!0})}),(g=s.signal)==null||g.throwIfAborted(),!0}async function gg(t,e={}){var i,a,o;if(e={...e},Cj(e.retries),Object.hasOwn(e,"forever"))throw new Error("The `forever` option is no longer supported. For many use-cases, you can set `retries: Infinity` instead.");e.retries??(e.retries=10),e.factor??(e.factor=2),e.minTimeout??(e.minTimeout=1e3),e.maxTimeout??(e.maxTimeout=Number.POSITIVE_INFINITY),e.maxRetryTime??(e.maxRetryTime=Number.POSITIVE_INFINITY),e.randomize??(e.randomize=!1),e.onFailedAttempt??(e.onFailedAttempt=()=>{}),e.shouldRetry??(e.shouldRetry=()=>!0),e.shouldConsumeRetry??(e.shouldConsumeRetry=()=>!0),Jl("factor",e.factor,{min:0,allowInfinity:!1}),Jl("minTimeout",e.minTimeout,{min:0,allowInfinity:!1}),Jl("maxTimeout",e.maxTimeout,{min:0,allowInfinity:!0}),Jl("maxRetryTime",e.maxRetryTime,{min:0,allowInfinity:!0}),e.factor>0||(e.factor=1),(i=e.signal)==null||i.throwIfAborted();let n=0,r=0;const s=performance.now();for(;!Number.isFinite(e.retries)||r<=e.retries;){n++;try{(a=e.signal)==null||a.throwIfAborted();const c=await t(n);return(o=e.signal)==null||o.throwIfAborted(),c}catch(c){await Rj({error:c,attemptNumber:n,retriesConsumed:r,startTime:s,options:e})&&r++}}throw new Error("Retry attempts exhausted without throwing an error.")}var Pj=de({AsyncCaller:()=>_l});const Nj=[400,401,402,403,404,405,406,407,409],Mj=t=>{if(typeof t!="object"||t===null)return;if("message"in t&&typeof t.message=="string"&&(t.message.startsWith("Cancel")||t.message.startsWith("AbortError"))||"name"in t&&typeof t.name=="string"&&t.name==="AbortError"||"code"in t&&typeof t.code=="string"&&t.code==="ECONNABORTED")throw t;const e="response"in t&&typeof t.response=="object"&&t.response!==null&&"status"in t.response&&typeof t.response.status=="number"?t.response.status:void 0,n="status"in t&&typeof t.status=="number"?t.status:void 0,r=e??n;if(r&&Nj.includes(+r))throw t;if(("error"in t&&typeof t.error=="object"&&t.error!==null&&"code"in t.error&&typeof t.error.code=="string"?t.error.code:void 0)==="insufficient_quota"){const s=new Error("message"in t&&typeof t.message=="string"?t.message:"Insufficient quota");throw s.name="InsufficientQuotaError",s}};var _l=class{constructor(t){m(this,"maxConcurrency");m(this,"maxRetries");m(this,"onFailedAttempt");m(this,"queue");this.maxConcurrency=t.maxConcurrency??1/0,this.maxRetries=t.maxRetries??6,this.onFailedAttempt=t.onFailedAttempt??Mj;const e="default"in Fs?Fs.default:Fs;this.queue=new e({concurrency:this.maxConcurrency})}async call(t,...e){return this.queue.add(()=>gg(()=>t(...e).catch(n=>{throw n instanceof Error?n:new Error(n)}),{onFailedAttempt:({error:n})=>{var r;return(r=this.onFailedAttempt)==null?void 0:r.call(this,n)},retries:this.maxRetries,randomize:!0}),{throwOnTimeout:!0})}callWithOptions(t,e,...n){if(t.signal){let r;return Promise.race([this.call(e,...n),new Promise((s,i)=>{var a;r=()=>{i(Au(t.signal))},(a=t.signal)==null||a.addEventListener("abort",r,{once:!0})})]).finally(()=>{t.signal&&r&&t.signal.removeEventListener("abort",r)})}return this.call(e,...n)}fetch(...t){return this.call(()=>fetch(...t).then(e=>e.ok?e:Promise.reject(e)))}},FE=class extends Gs{constructor({config:e,onStart:n,onEnd:r,onError:s}){super({_awaitHandler:!0});m(this,"name","RootListenersTracer");m(this,"rootId");m(this,"config");m(this,"argOnStart");m(this,"argOnEnd");m(this,"argOnError");this.config=e,this.argOnStart=n,this.argOnEnd=r,this.argOnError=s}persistRun(e){return Promise.resolve()}async onRunCreate(e){this.rootId||(this.rootId=e.id,this.argOnStart&&await this.argOnStart(e,this.config))}async onRunUpdate(e){e.id===this.rootId&&(e.error?this.argOnError&&await this.argOnError(e,this.config):this.argOnEnd&&await this.argOnEnd(e,this.config))}};function wy(t){return t?t.lc_runnable:!1}var Lj=class{constructor(t){m(this,"includeNames");m(this,"includeTypes");m(this,"includeTags");m(this,"excludeNames");m(this,"excludeTypes");m(this,"excludeTags");this.includeNames=t.includeNames,this.includeTypes=t.includeTypes,this.includeTags=t.includeTags,this.excludeNames=t.excludeNames,this.excludeTypes=t.excludeTypes,this.excludeTags=t.excludeTags}includeEvent(t,e){let n=this.includeNames===void 0&&this.includeTypes===void 0&&this.includeTags===void 0;const r=t.tags??[];return this.includeNames!==void 0&&(n=n||this.includeNames.includes(t.name)),this.includeTypes!==void 0&&(n=n||this.includeTypes.includes(e)),this.includeTags!==void 0&&(n=n||r.some(s=>{var i;return(i=this.includeTags)==null?void 0:i.includes(s)})),this.excludeNames!==void 0&&(n=n&&!this.excludeNames.includes(t.name)),this.excludeTypes!==void 0&&(n=n&&!this.excludeTypes.includes(e)),this.excludeTags!==void 0&&(n=n&&r.every(s=>{var i;return!((i=this.excludeTags)!=null&&i.includes(s))})),n}};const jj=t=>btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"");function F(t,e,n){function r(o,c){var u;Object.defineProperty(o,"_zod",{value:o._zod??{},enumerable:!1}),(u=o._zod).traits??(u.traits=new Set),o._zod.traits.add(t),e(o,c);for(const l in a.prototype)l in o||Object.defineProperty(o,l,{value:a.prototype[l].bind(o)});o._zod.constr=a,o._zod.def=c}const s=(n==null?void 0:n.Parent)??Object;class i extends s{}Object.defineProperty(i,"name",{value:t});function a(o){var c;const u=n!=null&&n.Parent?new i:this;r(u,o),(c=u._zod).deferred??(c.deferred=[]);for(const l of u._zod.deferred)l();return u}return Object.defineProperty(a,"init",{value:r}),Object.defineProperty(a,Symbol.hasInstance,{value:o=>{var c,u;return n!=null&&n.Parent&&o instanceof n.Parent?!0:(u=(c=o==null?void 0:o._zod)==null?void 0:c.traits)==null?void 0:u.has(t)}}),Object.defineProperty(a,"name",{value:t}),a}class Iu extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}const BE={};function Ci(t){return BE}function zE(t){const e=Object.values(t).filter(r=>typeof r=="number");return Object.entries(t).filter(([r,s])=>e.indexOf(+r)===-1).map(([r,s])=>s)}function Dj(t,e){return typeof e=="bigint"?e.toString():e}function by(t){return{get value(){{const e=t();return Object.defineProperty(this,"value",{value:e}),e}}}}function vy(t){return t==null}function Sy(t){const e=t.startsWith("^")?1:0,n=t.endsWith("$")?t.length-1:t.length;return t.slice(e,n)}function Uj(t,e){const n=(t.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,s=n>r?n:r,i=Number.parseInt(t.toFixed(s).replace(".","")),a=Number.parseInt(e.toFixed(s).replace(".",""));return i%a/10**s}function wt(t,e,n){Object.defineProperty(t,e,{get(){{const r=n();return t[e]=r,r}},set(r){Object.defineProperty(t,e,{value:r})},configurable:!0})}function Ay(t,e,n){Object.defineProperty(t,e,{value:n,writable:!0,enumerable:!0,configurable:!0})}function uc(t){return JSON.stringify(t)}const HE=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};function xh(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}const Fj=by(()=>{var t;if(typeof navigator<"u"&&((t=navigator==null?void 0:navigator.userAgent)!=null&&t.includes("Cloudflare")))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function kh(t){if(xh(t)===!1)return!1;const e=t.constructor;if(e===void 0)return!0;const n=e.prototype;return!(xh(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}const Bj=new Set(["string","number","symbol"]);function yl(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function wn(t,e,n){const r=new t._zod.constr(e??t._zod.def);return(!e||n!=null&&n.parent)&&(r._zod.parent=t),r}function ve(t){const e=t;if(!e)return{};if(typeof e=="string")return{error:()=>e};if((e==null?void 0:e.message)!==void 0){if((e==null?void 0:e.error)!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function zj(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}const Hj={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function Vj(t,e){const n={},r=t._zod.def;for(const s in e){if(!(s in r.shape))throw new Error(`Unrecognized key: "${s}"`);e[s]&&(n[s]=r.shape[s])}return wn(t,{...t._zod.def,shape:n,checks:[]})}function Kj(t,e){const n={...t._zod.def.shape},r=t._zod.def;for(const s in e){if(!(s in r.shape))throw new Error(`Unrecognized key: "${s}"`);e[s]&&delete n[s]}return wn(t,{...t._zod.def,shape:n,checks:[]})}function VE(t,e){if(!kh(e))throw new Error("Invalid input to extend: expected a plain object");const n={...t._zod.def,get shape(){const r={...t._zod.def.shape,...e};return Ay(this,"shape",r),r},checks:[]};return wn(t,n)}function Wj(t,e){return wn(t,{...t._zod.def,get shape(){const n={...t._zod.def.shape,...e._zod.def.shape};return Ay(this,"shape",n),n},catchall:e._zod.def.catchall,checks:[]})}function KE(t,e,n){const r=e._zod.def.shape,s={...r};if(n)for(const i in n){if(!(i in r))throw new Error(`Unrecognized key: "${i}"`);n[i]&&(s[i]=t?new t({type:"optional",innerType:r[i]}):r[i])}else for(const i in r)s[i]=t?new t({type:"optional",innerType:r[i]}):r[i];return wn(e,{...e._zod.def,shape:s,checks:[]})}function Zj(t,e,n){const r=e._zod.def.shape,s={...r};if(n)for(const i in n){if(!(i in s))throw new Error(`Unrecognized key: "${i}"`);n[i]&&(s[i]=new t({type:"nonoptional",innerType:r[i]}))}else for(const i in r)s[i]=new t({type:"nonoptional",innerType:r[i]});return wn(e,{...e._zod.def,shape:s,checks:[]})}function au(t,e=0){var n;for(let r=e;r<t.issues.length;r++)if(((n=t.issues[r])==null?void 0:n.continue)!==!0)return!0;return!1}function pi(t,e){return e.map(n=>{var r;return(r=n).path??(r.path=[]),n.path.unshift(t),n})}function Yl(t){return typeof t=="string"?t:t==null?void 0:t.message}function Oi(t,e,n){var s,i,a,o,c,u;const r={...t,path:t.path??[]};if(!t.message){const l=Yl((a=(i=(s=t.inst)==null?void 0:s._zod.def)==null?void 0:i.error)==null?void 0:a.call(i,t))??Yl((o=e==null?void 0:e.error)==null?void 0:o.call(e,t))??Yl((c=n.customError)==null?void 0:c.call(n,t))??Yl((u=n.localeError)==null?void 0:u.call(n,t))??"Invalid input";r.message=l}return delete r.inst,delete r.continue,e!=null&&e.reportInput||delete r.input,r}function Ty(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function xu(...t){const[e,n,r]=t;return typeof e=="string"?{message:e,code:"custom",input:n,inst:r}:{...e}}const WE=(t,e)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:e,enumerable:!1}),Object.defineProperty(t,"message",{get(){return JSON.stringify(e,Dj,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},ZE=F("$ZodError",WE),Tf=F("$ZodError",WE,{Parent:Error});function qj(t,e=n=>n.message){const n={},r=[];for(const s of t.issues)s.path.length>0?(n[s.path[0]]=n[s.path[0]]||[],n[s.path[0]].push(e(s))):r.push(e(s));return{formErrors:r,fieldErrors:n}}function Gj(t,e){const n=e||function(i){return i.message},r={_errors:[]},s=i=>{for(const a of i.issues)if(a.code==="invalid_union"&&a.errors.length)a.errors.map(o=>s({issues:o}));else if(a.code==="invalid_key")s({issues:a.issues});else if(a.code==="invalid_element")s({issues:a.issues});else if(a.path.length===0)r._errors.push(n(a));else{let o=r,c=0;for(;c<a.path.length;){const u=a.path[c];c===a.path.length-1?(o[u]=o[u]||{_errors:[]},o[u]._errors.push(n(a))):o[u]=o[u]||{_errors:[]},o=o[u],c++}}};return s(t),r}function Jj(t){const e=[];for(const n of t)typeof n=="number"?e.push(`[${n}]`):typeof n=="symbol"?e.push(`[${JSON.stringify(String(n))}]`):/[^\w$]/.test(n)?e.push(`[${JSON.stringify(n)}]`):(e.length&&e.push("."),e.push(n));return e.join("")}function Yj(t){var r;const e=[],n=[...t.issues].sort((s,i)=>s.path.length-i.path.length);for(const s of n)e.push(`✖ ${s.message}`),(r=s.path)!=null&&r.length&&e.push(` → at ${Jj(s.path)}`);return e.join(`
|
|
71
|
-
`)}const qE=t=>(e,n,r,s)=>{const i=r?Object.assign(r,{async:!1}):{async:!1},a=e._zod.run({value:n,issues:[]},i);if(a instanceof Promise)throw new Iu;if(a.issues.length){const o=new((s==null?void 0:s.Err)??t)(a.issues.map(c=>Oi(c,i,Ci())));throw HE(o,s==null?void 0:s.callee),o}return a.value},Ef=qE(Tf),GE=t=>async(e,n,r,s)=>{const i=r?Object.assign(r,{async:!0}):{async:!0};let a=e._zod.run({value:n,issues:[]},i);if(a instanceof Promise&&(a=await a),a.issues.length){const o=new((s==null?void 0:s.Err)??t)(a.issues.map(c=>Oi(c,i,Ci())));throw HE(o,s==null?void 0:s.callee),o}return a.value},JE=GE(Tf),YE=t=>(e,n,r)=>{const s=r?{...r,async:!1}:{async:!1},i=e._zod.run({value:n,issues:[]},s);if(i instanceof Promise)throw new Iu;return i.issues.length?{success:!1,error:new(t??ZE)(i.issues.map(a=>Oi(a,s,Ci())))}:{success:!0,data:i.value}},Xj=YE(Tf),XE=t=>async(e,n,r)=>{const s=r?Object.assign(r,{async:!0}):{async:!0};let i=e._zod.run({value:n,issues:[]},s);return i instanceof Promise&&(i=await i),i.issues.length?{success:!1,error:new t(i.issues.map(a=>Oi(a,s,Ci())))}:{success:!0,data:i.value}},Qj=XE(Tf),eD=/^[cC][^\s-]{8,}$/,tD=/^[0-9a-z]+$/,nD=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,rD=/^[0-9a-vA-V]{20}$/,sD=/^[A-Za-z0-9]{27}$/,iD=/^[a-zA-Z0-9_-]{21}$/,aD=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,oD=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,P0=t=>t?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/,cD=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,uD="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function lD(){return new RegExp(uD,"u")}const dD=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,hD=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,fD=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,pD=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,mD=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,QE=/^[A-Za-z0-9_-]*$/,gD=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,_D=/^\+(?:[0-9]){6,14}[0-9]$/,eI="(?:(?:\\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])))",yD=new RegExp(`^${eI}$`);function tI(t){const e="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof t.precision=="number"?t.precision===-1?`${e}`:t.precision===0?`${e}:[0-5]\\d`:`${e}:[0-5]\\d\\.\\d{${t.precision}}`:`${e}(?::[0-5]\\d(?:\\.\\d+)?)?`}function wD(t){return new RegExp(`^${tI(t)}$`)}function bD(t){const e=tI({precision:t.precision}),n=["Z"];t.local&&n.push(""),t.offset&&n.push("([+-]\\d{2}:\\d{2})");const r=`${e}(?:${n.join("|")})`;return new RegExp(`^${eI}T(?:${r})$`)}const vD=t=>{const e=t?`[\\s\\S]{${(t==null?void 0:t.minimum)??0},${(t==null?void 0:t.maximum)??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},SD=/^\d+$/,AD=/^-?\d+(?:\.\d+)?/i,TD=/true|false/i,ED=/^[^A-Z]*$/,ID=/^[^a-z]*$/,qn=F("$ZodCheck",(t,e)=>{var n;t._zod??(t._zod={}),t._zod.def=e,(n=t._zod).onattach??(n.onattach=[])}),nI={number:"number",bigint:"bigint",object:"date"},rI=F("$ZodCheckLessThan",(t,e)=>{qn.init(t,e);const n=nI[typeof e.value];t._zod.onattach.push(r=>{const s=r._zod.bag,i=(e.inclusive?s.maximum:s.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value<i&&(e.inclusive?s.maximum=e.value:s.exclusiveMaximum=e.value)}),t._zod.check=r=>{(e.inclusive?r.value<=e.value:r.value<e.value)||r.issues.push({origin:n,code:"too_big",maximum:e.value,input:r.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),sI=F("$ZodCheckGreaterThan",(t,e)=>{qn.init(t,e);const n=nI[typeof e.value];t._zod.onattach.push(r=>{const s=r._zod.bag,i=(e.inclusive?s.minimum:s.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>i&&(e.inclusive?s.minimum=e.value:s.exclusiveMinimum=e.value)}),t._zod.check=r=>{(e.inclusive?r.value>=e.value:r.value>e.value)||r.issues.push({origin:n,code:"too_small",minimum:e.value,input:r.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),xD=F("$ZodCheckMultipleOf",(t,e)=>{qn.init(t,e),t._zod.onattach.push(n=>{var r;(r=n._zod.bag).multipleOf??(r.multipleOf=e.value)}),t._zod.check=n=>{if(typeof n.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof n.value=="bigint"?n.value%e.value===BigInt(0):Uj(n.value,e.value)===0)||n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:e.value,input:n.value,inst:t,continue:!e.abort})}}),kD=F("$ZodCheckNumberFormat",(t,e)=>{var a;qn.init(t,e),e.format=e.format||"float64";const n=(a=e.format)==null?void 0:a.includes("int"),r=n?"int":"number",[s,i]=Hj[e.format];t._zod.onattach.push(o=>{const c=o._zod.bag;c.format=e.format,c.minimum=s,c.maximum=i,n&&(c.pattern=SD)}),t._zod.check=o=>{const c=o.value;if(n){if(!Number.isInteger(c)){o.issues.push({expected:r,format:e.format,code:"invalid_type",input:c,inst:t});return}if(!Number.isSafeInteger(c)){c>0?o.issues.push({input:c,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:r,continue:!e.abort}):o.issues.push({input:c,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:r,continue:!e.abort});return}}c<s&&o.issues.push({origin:"number",input:c,code:"too_small",minimum:s,inclusive:!0,inst:t,continue:!e.abort}),c>i&&o.issues.push({origin:"number",input:c,code:"too_big",maximum:i,inst:t})}}),CD=F("$ZodCheckMaxLength",(t,e)=>{var n;qn.init(t,e),(n=t._zod.def).when??(n.when=r=>{const s=r.value;return!vy(s)&&s.length!==void 0}),t._zod.onattach.push(r=>{const s=r._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<s&&(r._zod.bag.maximum=e.maximum)}),t._zod.check=r=>{const s=r.value;if(s.length<=e.maximum)return;const a=Ty(s);r.issues.push({origin:a,code:"too_big",maximum:e.maximum,inclusive:!0,input:s,inst:t,continue:!e.abort})}}),OD=F("$ZodCheckMinLength",(t,e)=>{var n;qn.init(t,e),(n=t._zod.def).when??(n.when=r=>{const s=r.value;return!vy(s)&&s.length!==void 0}),t._zod.onattach.push(r=>{const s=r._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>s&&(r._zod.bag.minimum=e.minimum)}),t._zod.check=r=>{const s=r.value;if(s.length>=e.minimum)return;const a=Ty(s);r.issues.push({origin:a,code:"too_small",minimum:e.minimum,inclusive:!0,input:s,inst:t,continue:!e.abort})}}),$D=F("$ZodCheckLengthEquals",(t,e)=>{var n;qn.init(t,e),(n=t._zod.def).when??(n.when=r=>{const s=r.value;return!vy(s)&&s.length!==void 0}),t._zod.onattach.push(r=>{const s=r._zod.bag;s.minimum=e.length,s.maximum=e.length,s.length=e.length}),t._zod.check=r=>{const s=r.value,i=s.length;if(i===e.length)return;const a=Ty(s),o=i>e.length;r.issues.push({origin:a,...o?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:r.value,inst:t,continue:!e.abort})}}),If=F("$ZodCheckStringFormat",(t,e)=>{var n,r;qn.init(t,e),t._zod.onattach.push(s=>{const i=s._zod.bag;i.format=e.format,e.pattern&&(i.patterns??(i.patterns=new Set),i.patterns.add(e.pattern))}),e.pattern?(n=t._zod).check??(n.check=s=>{e.pattern.lastIndex=0,!e.pattern.test(s.value)&&s.issues.push({origin:"string",code:"invalid_format",format:e.format,input:s.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(r=t._zod).check??(r.check=()=>{})}),RD=F("$ZodCheckRegex",(t,e)=>{If.init(t,e),t._zod.check=n=>{e.pattern.lastIndex=0,!e.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),PD=F("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=ED),If.init(t,e)}),ND=F("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=ID),If.init(t,e)}),MD=F("$ZodCheckIncludes",(t,e)=>{qn.init(t,e);const n=yl(e.includes),r=new RegExp(typeof e.position=="number"?`^.{${e.position}}${n}`:n);e.pattern=r,t._zod.onattach.push(s=>{const i=s._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(r)}),t._zod.check=s=>{s.value.includes(e.includes,e.position)||s.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:s.value,inst:t,continue:!e.abort})}}),LD=F("$ZodCheckStartsWith",(t,e)=>{qn.init(t,e);const n=new RegExp(`^${yl(e.prefix)}.*`);e.pattern??(e.pattern=n),t._zod.onattach.push(r=>{const s=r._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(n)}),t._zod.check=r=>{r.value.startsWith(e.prefix)||r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:r.value,inst:t,continue:!e.abort})}}),jD=F("$ZodCheckEndsWith",(t,e)=>{qn.init(t,e);const n=new RegExp(`.*${yl(e.suffix)}$`);e.pattern??(e.pattern=n),t._zod.onattach.push(r=>{const s=r._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(n)}),t._zod.check=r=>{r.value.endsWith(e.suffix)||r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:r.value,inst:t,continue:!e.abort})}}),DD=F("$ZodCheckOverwrite",(t,e)=>{qn.init(t,e),t._zod.check=n=>{n.value=e.tx(n.value)}});class UD{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}const r=e.split(`
|
|
72
|
-
`).filter(a=>a),s=Math.min(...r.map(a=>a.length-a.trimStart().length)),i=r.map(a=>a.slice(s)).map(a=>" ".repeat(this.indent*2)+a);for(const a of i)this.content.push(a)}compile(){const e=Function,n=this==null?void 0:this.args,s=[...((this==null?void 0:this.content)??[""]).map(i=>` ${i}`)];return new e(...n,s.join(`
|
|
73
|
-
`))}}const FD={major:4,minor:0,patch:0},ut=F("$ZodType",(t,e)=>{var s;var n;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=FD;const r=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&r.unshift(t);for(const i of r)for(const a of i._zod.onattach)a(t);if(r.length===0)(n=t._zod).deferred??(n.deferred=[]),(s=t._zod.deferred)==null||s.push(()=>{t._zod.run=t._zod.parse});else{const i=(a,o,c)=>{let u=au(a),l;for(const d of o){if(d._zod.def.when){if(!d._zod.def.when(a))continue}else if(u)continue;const f=a.issues.length,h=d._zod.check(a);if(h instanceof Promise&&(c==null?void 0:c.async)===!1)throw new Iu;if(l||h instanceof Promise)l=(l??Promise.resolve()).then(async()=>{await h,a.issues.length!==f&&(u||(u=au(a,f)))});else{if(a.issues.length===f)continue;u||(u=au(a,f))}}return l?l.then(()=>a):a};t._zod.run=(a,o)=>{const c=t._zod.parse(a,o);if(c instanceof Promise){if(o.async===!1)throw new Iu;return c.then(u=>i(u,r,o))}return i(c,r,o)}}t["~standard"]={validate:i=>{var a;try{const o=Xj(t,i);return o.success?{value:o.data}:{issues:(a=o.error)==null?void 0:a.issues}}catch{return Qj(t,i).then(c=>{var u;return c.success?{value:c.data}:{issues:(u=c.error)==null?void 0:u.issues}})}},vendor:"zod",version:1}}),Ey=F("$ZodString",(t,e)=>{var n;ut.init(t,e),t._zod.pattern=[...((n=t==null?void 0:t._zod.bag)==null?void 0:n.patterns)??[]].pop()??vD(t._zod.bag),t._zod.parse=(r,s)=>{if(e.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:t}),r}}),At=F("$ZodStringFormat",(t,e)=>{If.init(t,e),Ey.init(t,e)}),BD=F("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=oD),At.init(t,e)}),zD=F("$ZodUUID",(t,e)=>{if(e.version){const r={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(r===void 0)throw new Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=P0(r))}else e.pattern??(e.pattern=P0());At.init(t,e)}),HD=F("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=cD),At.init(t,e)}),VD=F("$ZodURL",(t,e)=>{At.init(t,e),t._zod.check=n=>{try{const r=n.value,s=new URL(r),i=s.href;e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(s.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:gD.source,input:n.value,inst:t,continue:!e.abort})),e.protocol&&(e.protocol.lastIndex=0,e.protocol.test(s.protocol.endsWith(":")?s.protocol.slice(0,-1):s.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:n.value,inst:t,continue:!e.abort})),!r.endsWith("/")&&i.endsWith("/")?n.value=i.slice(0,-1):n.value=i;return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:t,continue:!e.abort})}}}),KD=F("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=lD()),At.init(t,e)}),WD=F("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=iD),At.init(t,e)}),ZD=F("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=eD),At.init(t,e)}),qD=F("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=tD),At.init(t,e)}),GD=F("$ZodULID",(t,e)=>{e.pattern??(e.pattern=nD),At.init(t,e)}),JD=F("$ZodXID",(t,e)=>{e.pattern??(e.pattern=rD),At.init(t,e)}),YD=F("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=sD),At.init(t,e)}),XD=F("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=bD(e)),At.init(t,e)}),QD=F("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=yD),At.init(t,e)}),e4=F("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=wD(e)),At.init(t,e)}),t4=F("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=aD),At.init(t,e)}),n4=F("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=dD),At.init(t,e),t._zod.onattach.push(n=>{const r=n._zod.bag;r.format="ipv4"})}),r4=F("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=hD),At.init(t,e),t._zod.onattach.push(n=>{const r=n._zod.bag;r.format="ipv6"}),t._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:t,continue:!e.abort})}}}),s4=F("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=fD),At.init(t,e)}),i4=F("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=pD),At.init(t,e),t._zod.check=n=>{const[r,s]=n.value.split("/");try{if(!s)throw new Error;const i=Number(s);if(`${i}`!==s)throw new Error;if(i<0||i>128)throw new Error;new URL(`http://[${r}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:t,continue:!e.abort})}}});function iI(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}const a4=F("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=mD),At.init(t,e),t._zod.onattach.push(n=>{n._zod.bag.contentEncoding="base64"}),t._zod.check=n=>{iI(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:t,continue:!e.abort})}});function o4(t){if(!QE.test(t))return!1;const e=t.replace(/[-_]/g,r=>r==="-"?"+":"/"),n=e.padEnd(Math.ceil(e.length/4)*4,"=");return iI(n)}const c4=F("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=QE),At.init(t,e),t._zod.onattach.push(n=>{n._zod.bag.contentEncoding="base64url"}),t._zod.check=n=>{o4(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:t,continue:!e.abort})}}),u4=F("$ZodE164",(t,e)=>{e.pattern??(e.pattern=_D),At.init(t,e)});function l4(t,e=null){try{const n=t.split(".");if(n.length!==3)return!1;const[r]=n;if(!r)return!1;const s=JSON.parse(atob(r));return!("typ"in s&&(s==null?void 0:s.typ)!=="JWT"||!s.alg||e&&(!("alg"in s)||s.alg!==e))}catch{return!1}}const d4=F("$ZodJWT",(t,e)=>{At.init(t,e),t._zod.check=n=>{l4(n.value,e.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:t,continue:!e.abort})}}),aI=F("$ZodNumber",(t,e)=>{ut.init(t,e),t._zod.pattern=t._zod.bag.pattern??AD,t._zod.parse=(n,r)=>{if(e.coerce)try{n.value=Number(n.value)}catch{}const s=n.value;if(typeof s=="number"&&!Number.isNaN(s)&&Number.isFinite(s))return n;const i=typeof s=="number"?Number.isNaN(s)?"NaN":Number.isFinite(s)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:s,inst:t,...i?{received:i}:{}}),n}}),h4=F("$ZodNumber",(t,e)=>{kD.init(t,e),aI.init(t,e)}),f4=F("$ZodBoolean",(t,e)=>{ut.init(t,e),t._zod.pattern=TD,t._zod.parse=(n,r)=>{if(e.coerce)try{n.value=!!n.value}catch{}const s=n.value;return typeof s=="boolean"||n.issues.push({expected:"boolean",code:"invalid_type",input:s,inst:t}),n}}),p4=F("$ZodAny",(t,e)=>{ut.init(t,e),t._zod.parse=n=>n}),oI=F("$ZodUnknown",(t,e)=>{ut.init(t,e),t._zod.parse=n=>n}),cI=F("$ZodNever",(t,e)=>{ut.init(t,e),t._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:t}),n)});function N0(t,e,n){t.issues.length&&e.issues.push(...pi(n,t.issues)),e.value[n]=t.value}const m4=F("$ZodArray",(t,e)=>{ut.init(t,e),t._zod.parse=(n,r)=>{const s=n.value;if(!Array.isArray(s))return n.issues.push({expected:"array",code:"invalid_type",input:s,inst:t}),n;n.value=Array(s.length);const i=[];for(let a=0;a<s.length;a++){const o=s[a],c=e.element._zod.run({value:o,issues:[]},r);c instanceof Promise?i.push(c.then(u=>N0(u,n,a))):N0(c,n,a)}return i.length?Promise.all(i).then(()=>n):n}});function Xl(t,e,n){t.issues.length&&e.issues.push(...pi(n,t.issues)),e.value[n]=t.value}function M0(t,e,n,r){t.issues.length?r[n]===void 0?n in r?e.value[n]=void 0:e.value[n]=t.value:e.issues.push(...pi(n,t.issues)):t.value===void 0?n in r&&(e.value[n]=void 0):e.value[n]=t.value}const g4=F("$ZodObject",(t,e)=>{ut.init(t,e);const n=by(()=>{const d=Object.keys(e.shape);for(const h of d)if(!(e.shape[h]instanceof ut))throw new Error(`Invalid element at key "${h}": expected a Zod schema`);const f=zj(e.shape);return{shape:e.shape,keys:d,keySet:new Set(d),numKeys:d.length,optionalKeys:new Set(f)}});wt(t._zod,"propValues",()=>{const d=e.shape,f={};for(const h in d){const p=d[h]._zod;if(p.values){f[h]??(f[h]=new Set);for(const g of p.values)f[h].add(g)}}return f});const r=d=>{const f=new UD(["shape","payload","ctx"]),h=n.value,p=_=>{const w=uc(_);return`shape[${w}]._zod.run({ value: input[${w}], issues: [] }, ctx)`};f.write("const input = payload.value;");const g=Object.create(null);let y=0;for(const _ of h.keys)g[_]=`key_${y++}`;f.write("const newResult = {}");for(const _ of h.keys)if(h.optionalKeys.has(_)){const w=g[_];f.write(`const ${w} = ${p(_)};`);const v=uc(_);f.write(`
|
|
74
|
-
if (${w}.issues.length) {
|
|
75
|
-
if (input[${v}] === undefined) {
|
|
76
|
-
if (${v} in input) {
|
|
77
|
-
newResult[${v}] = undefined;
|
|
78
|
-
}
|
|
79
|
-
} else {
|
|
80
|
-
payload.issues = payload.issues.concat(
|
|
81
|
-
${w}.issues.map((iss) => ({
|
|
82
|
-
...iss,
|
|
83
|
-
path: iss.path ? [${v}, ...iss.path] : [${v}],
|
|
84
|
-
}))
|
|
85
|
-
);
|
|
86
|
-
}
|
|
87
|
-
} else if (${w}.value === undefined) {
|
|
88
|
-
if (${v} in input) newResult[${v}] = undefined;
|
|
89
|
-
} else {
|
|
90
|
-
newResult[${v}] = ${w}.value;
|
|
91
|
-
}
|
|
92
|
-
`)}else{const w=g[_];f.write(`const ${w} = ${p(_)};`),f.write(`
|
|
93
|
-
if (${w}.issues.length) payload.issues = payload.issues.concat(${w}.issues.map(iss => ({
|
|
94
|
-
...iss,
|
|
95
|
-
path: iss.path ? [${uc(_)}, ...iss.path] : [${uc(_)}]
|
|
96
|
-
})));`),f.write(`newResult[${uc(_)}] = ${w}.value`)}f.write("payload.value = newResult;"),f.write("return payload;");const b=f.compile();return(_,w)=>b(d,_,w)};let s;const i=xh,a=!BE.jitless,c=a&&Fj.value,u=e.catchall;let l;t._zod.parse=(d,f)=>{l??(l=n.value);const h=d.value;if(!i(h))return d.issues.push({expected:"object",code:"invalid_type",input:h,inst:t}),d;const p=[];if(a&&c&&(f==null?void 0:f.async)===!1&&f.jitless!==!0)s||(s=r(e.shape)),d=s(d,f);else{d.value={};const w=l.shape;for(const v of l.keys){const A=w[v],S=A._zod.run({value:h[v],issues:[]},f),x=A._zod.optin==="optional"&&A._zod.optout==="optional";S instanceof Promise?p.push(S.then(E=>x?M0(E,d,v,h):Xl(E,d,v))):x?M0(S,d,v,h):Xl(S,d,v)}}if(!u)return p.length?Promise.all(p).then(()=>d):d;const g=[],y=l.keySet,b=u._zod,_=b.def.type;for(const w of Object.keys(h)){if(y.has(w))continue;if(_==="never"){g.push(w);continue}const v=b.run({value:h[w],issues:[]},f);v instanceof Promise?p.push(v.then(A=>Xl(A,d,w))):Xl(v,d,w)}return g.length&&d.issues.push({code:"unrecognized_keys",keys:g,input:h,inst:t}),p.length?Promise.all(p).then(()=>d):d}});function L0(t,e,n,r){for(const s of t)if(s.issues.length===0)return e.value=s.value,e;return e.issues.push({code:"invalid_union",input:e.value,inst:n,errors:t.map(s=>s.issues.map(i=>Oi(i,r,Ci())))}),e}const uI=F("$ZodUnion",(t,e)=>{ut.init(t,e),wt(t._zod,"optin",()=>e.options.some(n=>n._zod.optin==="optional")?"optional":void 0),wt(t._zod,"optout",()=>e.options.some(n=>n._zod.optout==="optional")?"optional":void 0),wt(t._zod,"values",()=>{if(e.options.every(n=>n._zod.values))return new Set(e.options.flatMap(n=>Array.from(n._zod.values)))}),wt(t._zod,"pattern",()=>{if(e.options.every(n=>n._zod.pattern)){const n=e.options.map(r=>r._zod.pattern);return new RegExp(`^(${n.map(r=>Sy(r.source)).join("|")})$`)}}),t._zod.parse=(n,r)=>{let s=!1;const i=[];for(const a of e.options){const o=a._zod.run({value:n.value,issues:[]},r);if(o instanceof Promise)i.push(o),s=!0;else{if(o.issues.length===0)return o;i.push(o)}}return s?Promise.all(i).then(a=>L0(a,n,t,r)):L0(i,n,t,r)}}),_4=F("$ZodDiscriminatedUnion",(t,e)=>{uI.init(t,e);const n=t._zod.parse;wt(t._zod,"propValues",()=>{const s={};for(const i of e.options){const a=i._zod.propValues;if(!a||Object.keys(a).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(i)}"`);for(const[o,c]of Object.entries(a)){s[o]||(s[o]=new Set);for(const u of c)s[o].add(u)}}return s});const r=by(()=>{const s=e.options,i=new Map;for(const a of s){const o=a._zod.propValues[e.discriminator];if(!o||o.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(a)}"`);for(const c of o){if(i.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);i.set(c,a)}}return i});t._zod.parse=(s,i)=>{const a=s.value;if(!xh(a))return s.issues.push({code:"invalid_type",expected:"object",input:a,inst:t}),s;const o=r.value.get(a==null?void 0:a[e.discriminator]);return o?o._zod.run(s,i):e.unionFallback?n(s,i):(s.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:a,path:[e.discriminator],inst:t}),s)}}),y4=F("$ZodIntersection",(t,e)=>{ut.init(t,e),t._zod.parse=(n,r)=>{const s=n.value,i=e.left._zod.run({value:s,issues:[]},r),a=e.right._zod.run({value:s,issues:[]},r);return i instanceof Promise||a instanceof Promise?Promise.all([i,a]).then(([c,u])=>j0(n,c,u)):j0(n,i,a)}});function _g(t,e){if(t===e)return{valid:!0,data:t};if(t instanceof Date&&e instanceof Date&&+t==+e)return{valid:!0,data:t};if(kh(t)&&kh(e)){const n=Object.keys(e),r=Object.keys(t).filter(i=>n.indexOf(i)!==-1),s={...t,...e};for(const i of r){const a=_g(t[i],e[i]);if(!a.valid)return{valid:!1,mergeErrorPath:[i,...a.mergeErrorPath]};s[i]=a.data}return{valid:!0,data:s}}if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return{valid:!1,mergeErrorPath:[]};const n=[];for(let r=0;r<t.length;r++){const s=t[r],i=e[r],a=_g(s,i);if(!a.valid)return{valid:!1,mergeErrorPath:[r,...a.mergeErrorPath]};n.push(a.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function j0(t,e,n){if(e.issues.length&&t.issues.push(...e.issues),n.issues.length&&t.issues.push(...n.issues),au(t))return t;const r=_g(e.value,n.value);if(!r.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(r.mergeErrorPath)}`);return t.value=r.data,t}const w4=F("$ZodTuple",(t,e)=>{ut.init(t,e);const n=e.items,r=n.length-[...n].reverse().findIndex(s=>s._zod.optin!=="optional");t._zod.parse=(s,i)=>{const a=s.value;if(!Array.isArray(a))return s.issues.push({input:a,inst:t,expected:"tuple",code:"invalid_type"}),s;s.value=[];const o=[];if(!e.rest){const u=a.length>n.length,l=a.length<r-1;if(u||l)return s.issues.push({input:a,inst:t,origin:"array",...u?{code:"too_big",maximum:n.length}:{code:"too_small",minimum:n.length}}),s}let c=-1;for(const u of n){if(c++,c>=a.length&&c>=r)continue;const l=u._zod.run({value:a[c],issues:[]},i);l instanceof Promise?o.push(l.then(d=>Ql(d,s,c))):Ql(l,s,c)}if(e.rest){const u=a.slice(n.length);for(const l of u){c++;const d=e.rest._zod.run({value:l,issues:[]},i);d instanceof Promise?o.push(d.then(f=>Ql(f,s,c))):Ql(d,s,c)}}return o.length?Promise.all(o).then(()=>s):s}});function Ql(t,e,n){t.issues.length&&e.issues.push(...pi(n,t.issues)),e.value[n]=t.value}const b4=F("$ZodRecord",(t,e)=>{ut.init(t,e),t._zod.parse=(n,r)=>{const s=n.value;if(!kh(s))return n.issues.push({expected:"record",code:"invalid_type",input:s,inst:t}),n;const i=[];if(e.keyType._zod.values){const a=e.keyType._zod.values;n.value={};for(const c of a)if(typeof c=="string"||typeof c=="number"||typeof c=="symbol"){const u=e.valueType._zod.run({value:s[c],issues:[]},r);u instanceof Promise?i.push(u.then(l=>{l.issues.length&&n.issues.push(...pi(c,l.issues)),n.value[c]=l.value})):(u.issues.length&&n.issues.push(...pi(c,u.issues)),n.value[c]=u.value)}let o;for(const c in s)a.has(c)||(o=o??[],o.push(c));o&&o.length>0&&n.issues.push({code:"unrecognized_keys",input:s,inst:t,keys:o})}else{n.value={};for(const a of Reflect.ownKeys(s)){if(a==="__proto__")continue;const o=e.keyType._zod.run({value:a,issues:[]},r);if(o instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(o.issues.length){n.issues.push({origin:"record",code:"invalid_key",issues:o.issues.map(u=>Oi(u,r,Ci())),input:a,path:[a],inst:t}),n.value[o.value]=o.value;continue}const c=e.valueType._zod.run({value:s[a],issues:[]},r);c instanceof Promise?i.push(c.then(u=>{u.issues.length&&n.issues.push(...pi(a,u.issues)),n.value[o.value]=u.value})):(c.issues.length&&n.issues.push(...pi(a,c.issues)),n.value[o.value]=c.value)}}return i.length?Promise.all(i).then(()=>n):n}}),v4=F("$ZodEnum",(t,e)=>{ut.init(t,e);const n=zE(e.entries);t._zod.values=new Set(n),t._zod.pattern=new RegExp(`^(${n.filter(r=>Bj.has(typeof r)).map(r=>typeof r=="string"?yl(r):r.toString()).join("|")})$`),t._zod.parse=(r,s)=>{const i=r.value;return t._zod.values.has(i)||r.issues.push({code:"invalid_value",values:n,input:i,inst:t}),r}}),S4=F("$ZodLiteral",(t,e)=>{ut.init(t,e),t._zod.values=new Set(e.values),t._zod.pattern=new RegExp(`^(${e.values.map(n=>typeof n=="string"?yl(n):n?n.toString():String(n)).join("|")})$`),t._zod.parse=(n,r)=>{const s=n.value;return t._zod.values.has(s)||n.issues.push({code:"invalid_value",values:e.values,input:s,inst:t}),n}}),A4=F("$ZodTransform",(t,e)=>{ut.init(t,e),t._zod.parse=(n,r)=>{const s=e.transform(n.value,n);if(r.async)return(s instanceof Promise?s:Promise.resolve(s)).then(a=>(n.value=a,n));if(s instanceof Promise)throw new Iu;return n.value=s,n}}),Iy=F("$ZodOptional",(t,e)=>{ut.init(t,e),t._zod.optin="optional",t._zod.optout="optional",wt(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),wt(t._zod,"pattern",()=>{const n=e.innerType._zod.pattern;return n?new RegExp(`^(${Sy(n.source)})?$`):void 0}),t._zod.parse=(n,r)=>e.innerType._zod.optin==="optional"?e.innerType._zod.run(n,r):n.value===void 0?n:e.innerType._zod.run(n,r)}),T4=F("$ZodNullable",(t,e)=>{ut.init(t,e),wt(t._zod,"optin",()=>e.innerType._zod.optin),wt(t._zod,"optout",()=>e.innerType._zod.optout),wt(t._zod,"pattern",()=>{const n=e.innerType._zod.pattern;return n?new RegExp(`^(${Sy(n.source)}|null)$`):void 0}),wt(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(n,r)=>n.value===null?n:e.innerType._zod.run(n,r)}),E4=F("$ZodDefault",(t,e)=>{ut.init(t,e),t._zod.optin="optional",wt(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,r)=>{if(n.value===void 0)return n.value=e.defaultValue,n;const s=e.innerType._zod.run(n,r);return s instanceof Promise?s.then(i=>D0(i,e)):D0(s,e)}});function D0(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}const I4=F("$ZodPrefault",(t,e)=>{ut.init(t,e),t._zod.optin="optional",wt(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,r)=>(n.value===void 0&&(n.value=e.defaultValue),e.innerType._zod.run(n,r))}),x4=F("$ZodNonOptional",(t,e)=>{ut.init(t,e),wt(t._zod,"values",()=>{const n=e.innerType._zod.values;return n?new Set([...n].filter(r=>r!==void 0)):void 0}),t._zod.parse=(n,r)=>{const s=e.innerType._zod.run(n,r);return s instanceof Promise?s.then(i=>U0(i,t)):U0(s,t)}});function U0(t,e){return!t.issues.length&&t.value===void 0&&t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:e}),t}const k4=F("$ZodCatch",(t,e)=>{ut.init(t,e),t._zod.optin="optional",wt(t._zod,"optout",()=>e.innerType._zod.optout),wt(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,r)=>{const s=e.innerType._zod.run(n,r);return s instanceof Promise?s.then(i=>(n.value=i.value,i.issues.length&&(n.value=e.catchValue({...n,error:{issues:i.issues.map(a=>Oi(a,r,Ci()))},input:n.value}),n.issues=[]),n)):(n.value=s.value,s.issues.length&&(n.value=e.catchValue({...n,error:{issues:s.issues.map(i=>Oi(i,r,Ci()))},input:n.value}),n.issues=[]),n)}}),C4=F("$ZodPipe",(t,e)=>{ut.init(t,e),wt(t._zod,"values",()=>e.in._zod.values),wt(t._zod,"optin",()=>e.in._zod.optin),wt(t._zod,"optout",()=>e.out._zod.optout),t._zod.parse=(n,r)=>{const s=e.in._zod.run(n,r);return s instanceof Promise?s.then(i=>F0(i,e,r)):F0(s,e,r)}});function F0(t,e,n){return au(t)?t:e.out._zod.run({value:t.value,issues:t.issues},n)}const O4=F("$ZodReadonly",(t,e)=>{ut.init(t,e),wt(t._zod,"propValues",()=>e.innerType._zod.propValues),wt(t._zod,"values",()=>e.innerType._zod.values),wt(t._zod,"optin",()=>e.innerType._zod.optin),wt(t._zod,"optout",()=>e.innerType._zod.optout),t._zod.parse=(n,r)=>{const s=e.innerType._zod.run(n,r);return s instanceof Promise?s.then(B0):B0(s)}});function B0(t){return t.value=Object.freeze(t.value),t}const $4=F("$ZodCustom",(t,e)=>{qn.init(t,e),ut.init(t,e),t._zod.parse=(n,r)=>n,t._zod.check=n=>{const r=n.value,s=e.fn(r);if(s instanceof Promise)return s.then(i=>z0(i,n,r,t));z0(s,n,r,t)}});function z0(t,e,n,r){if(!t){const s={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(s.params=r._zod.def.params),e.issues.push(xu(s))}}class lI{constructor(){this._map=new Map,this._idmap=new Map}add(e,...n){const r=n[0];if(this._map.set(e,r),r&&typeof r=="object"&&"id"in r){if(this._idmap.has(r.id))throw new Error(`ID ${r.id} already exists in the registry`);this._idmap.set(r.id,e)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(e){const n=this._map.get(e);return n&&typeof n=="object"&&"id"in n&&this._idmap.delete(n.id),this._map.delete(e),this}get(e){const n=e._zod.parent;if(n){const r={...this.get(n)??{}};return delete r.id,{...r,...this._map.get(e)}}return this._map.get(e)}has(e){return this._map.has(e)}}function R4(){return new lI}const Qt=R4();function P4(t,e){return new t({type:"string",...ve(e)})}function N4(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...ve(e)})}function H0(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...ve(e)})}function M4(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...ve(e)})}function L4(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...ve(e)})}function j4(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...ve(e)})}function D4(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...ve(e)})}function U4(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...ve(e)})}function F4(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...ve(e)})}function B4(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...ve(e)})}function z4(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...ve(e)})}function H4(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...ve(e)})}function V4(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...ve(e)})}function K4(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...ve(e)})}function W4(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...ve(e)})}function Z4(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...ve(e)})}function q4(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...ve(e)})}function G4(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...ve(e)})}function J4(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...ve(e)})}function Y4(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...ve(e)})}function X4(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...ve(e)})}function Q4(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...ve(e)})}function eU(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...ve(e)})}function tU(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...ve(e)})}function nU(t,e){return new t({type:"string",format:"date",check:"string_format",...ve(e)})}function rU(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...ve(e)})}function sU(t,e){return new t({type:"string",format:"duration",check:"string_format",...ve(e)})}function iU(t,e){return new t({type:"number",checks:[],...ve(e)})}function aU(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...ve(e)})}function oU(t,e){return new t({type:"boolean",...ve(e)})}function cU(t){return new t({type:"any"})}function dI(t){return new t({type:"unknown"})}function hI(t,e){return new t({type:"never",...ve(e)})}function V0(t,e){return new rI({check:"less_than",...ve(e),value:t,inclusive:!1})}function Mp(t,e){return new rI({check:"less_than",...ve(e),value:t,inclusive:!0})}function K0(t,e){return new sI({check:"greater_than",...ve(e),value:t,inclusive:!1})}function Lp(t,e){return new sI({check:"greater_than",...ve(e),value:t,inclusive:!0})}function W0(t,e){return new xD({check:"multiple_of",...ve(e),value:t})}function fI(t,e){return new CD({check:"max_length",...ve(e),maximum:t})}function Ch(t,e){return new OD({check:"min_length",...ve(e),minimum:t})}function pI(t,e){return new $D({check:"length_equals",...ve(e),length:t})}function uU(t,e){return new RD({check:"string_format",format:"regex",...ve(e),pattern:t})}function lU(t){return new PD({check:"string_format",format:"lowercase",...ve(t)})}function dU(t){return new ND({check:"string_format",format:"uppercase",...ve(t)})}function hU(t,e){return new MD({check:"string_format",format:"includes",...ve(e),includes:t})}function fU(t,e){return new LD({check:"string_format",format:"starts_with",...ve(e),prefix:t})}function pU(t,e){return new jD({check:"string_format",format:"ends_with",...ve(e),suffix:t})}function wl(t){return new DD({check:"overwrite",tx:t})}function mU(t){return wl(e=>e.normalize(t))}function gU(){return wl(t=>t.trim())}function _U(){return wl(t=>t.toLowerCase())}function yU(){return wl(t=>t.toUpperCase())}function wU(t,e,n){return new t({type:"array",element:e,...ve(n)})}function bU(t,e,n){const r=ve(n);return r.abort??(r.abort=!0),new t({type:"custom",check:"custom",fn:e,...r})}function vU(t,e,n){return new t({type:"custom",check:"custom",fn:e,...ve(n)})}class Z0{constructor(e){this.counter=0,this.metadataRegistry=(e==null?void 0:e.metadata)??Qt,this.target=(e==null?void 0:e.target)??"draft-2020-12",this.unrepresentable=(e==null?void 0:e.unrepresentable)??"throw",this.override=(e==null?void 0:e.override)??(()=>{}),this.io=(e==null?void 0:e.io)??"output",this.seen=new Map}process(e,n={path:[],schemaPath:[]}){var d,f,h;var r;const s=e._zod.def,i={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},a=this.seen.get(e);if(a)return a.count++,n.schemaPath.includes(e)&&(a.cycle=n.path),a.schema;const o={schema:{},count:1,cycle:void 0,path:n.path};this.seen.set(e,o);const c=(f=(d=e._zod).toJSONSchema)==null?void 0:f.call(d);if(c)o.schema=c;else{const p={...n,schemaPath:[...n.schemaPath,e],path:n.path},g=e._zod.parent;if(g)o.ref=g,this.process(g,p),this.seen.get(g).isParent=!0;else{const y=o.schema;switch(s.type){case"string":{const b=y;b.type="string";const{minimum:_,maximum:w,format:v,patterns:A,contentEncoding:S}=e._zod.bag;if(typeof _=="number"&&(b.minLength=_),typeof w=="number"&&(b.maxLength=w),v&&(b.format=i[v]??v,b.format===""&&delete b.format),S&&(b.contentEncoding=S),A&&A.size>0){const x=[...A];x.length===1?b.pattern=x[0].source:x.length>1&&(o.schema.allOf=[...x.map(E=>({...this.target==="draft-7"?{type:"string"}:{},pattern:E.source}))])}break}case"number":{const b=y,{minimum:_,maximum:w,format:v,multipleOf:A,exclusiveMaximum:S,exclusiveMinimum:x}=e._zod.bag;typeof v=="string"&&v.includes("int")?b.type="integer":b.type="number",typeof x=="number"&&(b.exclusiveMinimum=x),typeof _=="number"&&(b.minimum=_,typeof x=="number"&&(x>=_?delete b.minimum:delete b.exclusiveMinimum)),typeof S=="number"&&(b.exclusiveMaximum=S),typeof w=="number"&&(b.maximum=w,typeof S=="number"&&(S<=w?delete b.maximum:delete b.exclusiveMaximum)),typeof A=="number"&&(b.multipleOf=A);break}case"boolean":{const b=y;b.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema");break}case"null":{y.type="null";break}case"any":break;case"unknown":break;case"undefined":{if(this.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema");break}case"void":{if(this.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema");break}case"never":{y.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{const b=y,{minimum:_,maximum:w}=e._zod.bag;typeof _=="number"&&(b.minItems=_),typeof w=="number"&&(b.maxItems=w),b.type="array",b.items=this.process(s.element,{...p,path:[...p.path,"items"]});break}case"object":{const b=y;b.type="object",b.properties={};const _=s.shape;for(const A in _)b.properties[A]=this.process(_[A],{...p,path:[...p.path,"properties",A]});const w=new Set(Object.keys(_)),v=new Set([...w].filter(A=>{const S=s.shape[A]._zod;return this.io==="input"?S.optin===void 0:S.optout===void 0}));v.size>0&&(b.required=Array.from(v)),((h=s.catchall)==null?void 0:h._zod.def.type)==="never"?b.additionalProperties=!1:s.catchall?s.catchall&&(b.additionalProperties=this.process(s.catchall,{...p,path:[...p.path,"additionalProperties"]})):this.io==="output"&&(b.additionalProperties=!1);break}case"union":{const b=y;b.anyOf=s.options.map((_,w)=>this.process(_,{...p,path:[...p.path,"anyOf",w]}));break}case"intersection":{const b=y,_=this.process(s.left,{...p,path:[...p.path,"allOf",0]}),w=this.process(s.right,{...p,path:[...p.path,"allOf",1]}),v=S=>"allOf"in S&&Object.keys(S).length===1,A=[...v(_)?_.allOf:[_],...v(w)?w.allOf:[w]];b.allOf=A;break}case"tuple":{const b=y;b.type="array";const _=s.items.map((A,S)=>this.process(A,{...p,path:[...p.path,"prefixItems",S]}));if(this.target==="draft-2020-12"?b.prefixItems=_:b.items=_,s.rest){const A=this.process(s.rest,{...p,path:[...p.path,"items"]});this.target==="draft-2020-12"?b.items=A:b.additionalItems=A}s.rest&&(b.items=this.process(s.rest,{...p,path:[...p.path,"items"]}));const{minimum:w,maximum:v}=e._zod.bag;typeof w=="number"&&(b.minItems=w),typeof v=="number"&&(b.maxItems=v);break}case"record":{const b=y;b.type="object",b.propertyNames=this.process(s.keyType,{...p,path:[...p.path,"propertyNames"]}),b.additionalProperties=this.process(s.valueType,{...p,path:[...p.path,"additionalProperties"]});break}case"map":{if(this.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema");break}case"set":{if(this.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema");break}case"enum":{const b=y,_=zE(s.entries);_.every(w=>typeof w=="number")&&(b.type="number"),_.every(w=>typeof w=="string")&&(b.type="string"),b.enum=_;break}case"literal":{const b=y,_=[];for(const w of s.values)if(w===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof w=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");_.push(Number(w))}else _.push(w);if(_.length!==0)if(_.length===1){const w=_[0];b.type=w===null?"null":typeof w,b.const=w}else _.every(w=>typeof w=="number")&&(b.type="number"),_.every(w=>typeof w=="string")&&(b.type="string"),_.every(w=>typeof w=="boolean")&&(b.type="string"),_.every(w=>w===null)&&(b.type="null"),b.enum=_;break}case"file":{const b=y,_={type:"string",format:"binary",contentEncoding:"binary"},{minimum:w,maximum:v,mime:A}=e._zod.bag;w!==void 0&&(_.minLength=w),v!==void 0&&(_.maxLength=v),A?A.length===1?(_.contentMediaType=A[0],Object.assign(b,_)):b.anyOf=A.map(S=>({..._,contentMediaType:S})):Object.assign(b,_);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{const b=this.process(s.innerType,p);y.anyOf=[b,{type:"null"}];break}case"nonoptional":{this.process(s.innerType,p),o.ref=s.innerType;break}case"success":{const b=y;b.type="boolean";break}case"default":{this.process(s.innerType,p),o.ref=s.innerType,y.default=JSON.parse(JSON.stringify(s.defaultValue));break}case"prefault":{this.process(s.innerType,p),o.ref=s.innerType,this.io==="input"&&(y._prefault=JSON.parse(JSON.stringify(s.defaultValue)));break}case"catch":{this.process(s.innerType,p),o.ref=s.innerType;let b;try{b=s.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}y.default=b;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{const b=y,_=e._zod.pattern;if(!_)throw new Error("Pattern not found in template literal");b.type="string",b.pattern=_.source;break}case"pipe":{const b=this.io==="input"?s.in._zod.def.type==="transform"?s.out:s.in:s.out;this.process(b,p),o.ref=b;break}case"readonly":{this.process(s.innerType,p),o.ref=s.innerType,y.readOnly=!0;break}case"promise":{this.process(s.innerType,p),o.ref=s.innerType;break}case"optional":{this.process(s.innerType,p),o.ref=s.innerType;break}case"lazy":{const b=e._zod.innerType;this.process(b,p),o.ref=b;break}case"custom":{if(this.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema");break}}}}const u=this.metadataRegistry.get(e);return u&&Object.assign(o.schema,u),this.io==="input"&&Ut(e)&&(delete o.schema.examples,delete o.schema.default),this.io==="input"&&o.schema._prefault&&((r=o.schema).default??(r.default=o.schema._prefault)),delete o.schema._prefault,this.seen.get(e).schema}emit(e,n){var l,d,f,h,p,g;const r={cycles:(n==null?void 0:n.cycles)??"ref",reused:(n==null?void 0:n.reused)??"inline",external:(n==null?void 0:n.external)??void 0},s=this.seen.get(e);if(!s)throw new Error("Unprocessed schema. This is a bug in Zod.");const i=y=>{var A;const b=this.target==="draft-2020-12"?"$defs":"definitions";if(r.external){const S=(A=r.external.registry.get(y[0]))==null?void 0:A.id,x=r.external.uri??($=>$);if(S)return{ref:x(S)};const E=y[1].defId??y[1].schema.id??`schema${this.counter++}`;return y[1].defId=E,{defId:E,ref:`${x("__shared")}#/${b}/${E}`}}if(y[1]===s)return{ref:"#"};const w=`#/${b}/`,v=y[1].schema.id??`__schema${this.counter++}`;return{defId:v,ref:w+v}},a=y=>{if(y[1].schema.$ref)return;const b=y[1],{ref:_,defId:w}=i(y);b.def={...b.schema},w&&(b.defId=w);const v=b.schema;for(const A in v)delete v[A];v.$ref=_};if(r.cycles==="throw")for(const y of this.seen.entries()){const b=y[1];if(b.cycle)throw new Error(`Cycle detected: #/${(l=b.cycle)==null?void 0:l.join("/")}/<root>
|
|
97
|
-
|
|
98
|
-
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const y of this.seen.entries()){const b=y[1];if(e===y[0]){a(y);continue}if(r.external){const w=(d=r.external.registry.get(y[0]))==null?void 0:d.id;if(e!==y[0]&&w){a(y);continue}}if((f=this.metadataRegistry.get(y[0]))==null?void 0:f.id){a(y);continue}if(b.cycle){a(y);continue}if(b.count>1&&r.reused==="ref"){a(y);continue}}const o=(y,b)=>{const _=this.seen.get(y),w=_.def??_.schema,v={...w};if(_.ref===null)return;const A=_.ref;if(_.ref=null,A){o(A,b);const S=this.seen.get(A).schema;S.$ref&&b.target==="draft-7"?(w.allOf=w.allOf??[],w.allOf.push(S)):(Object.assign(w,S),Object.assign(w,v))}_.isParent||this.override({zodSchema:y,jsonSchema:w,path:_.path??[]})};for(const y of[...this.seen.entries()].reverse())o(y[0],{target:this.target});const c={};if(this.target==="draft-2020-12"?c.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?c.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),(h=r.external)!=null&&h.uri){const y=(p=r.external.registry.get(e))==null?void 0:p.id;if(!y)throw new Error("Schema is missing an `id` property");c.$id=r.external.uri(y)}Object.assign(c,s.def);const u=((g=r.external)==null?void 0:g.defs)??{};for(const y of this.seen.entries()){const b=y[1];b.def&&b.defId&&(u[b.defId]=b.def)}r.external||Object.keys(u).length>0&&(this.target==="draft-2020-12"?c.$defs=u:c.definitions=u);try{return JSON.parse(JSON.stringify(c))}catch{throw new Error("Error converting schema to JSON.")}}}function yg(t,e){if(t instanceof lI){const r=new Z0(e),s={};for(const o of t._idmap.entries()){const[c,u]=o;r.process(u)}const i={},a={registry:t,uri:e==null?void 0:e.uri,defs:s};for(const o of t._idmap.entries()){const[c,u]=o;i[c]=r.emit(u,{...e,external:a})}if(Object.keys(s).length>0){const o=r.target==="draft-2020-12"?"$defs":"definitions";i.__shared={[o]:s}}return{schemas:i}}const n=new Z0(e);return n.process(t),n.emit(t,e)}function Ut(t,e){const n=e??{seen:new Set};if(n.seen.has(t))return!1;n.seen.add(t);const s=t._zod.def;switch(s.type){case"string":case"number":case"bigint":case"boolean":case"date":case"symbol":case"undefined":case"null":case"any":case"unknown":case"never":case"void":case"literal":case"enum":case"nan":case"file":case"template_literal":return!1;case"array":return Ut(s.element,n);case"object":{for(const i in s.shape)if(Ut(s.shape[i],n))return!0;return!1}case"union":{for(const i of s.options)if(Ut(i,n))return!0;return!1}case"intersection":return Ut(s.left,n)||Ut(s.right,n);case"tuple":{for(const i of s.items)if(Ut(i,n))return!0;return!!(s.rest&&Ut(s.rest,n))}case"record":return Ut(s.keyType,n)||Ut(s.valueType,n);case"map":return Ut(s.keyType,n)||Ut(s.valueType,n);case"set":return Ut(s.valueType,n);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return Ut(s.innerType,n);case"lazy":return Ut(s.getter(),n);case"default":return Ut(s.innerType,n);case"prefault":return Ut(s.innerType,n);case"custom":return!1;case"transform":return!0;case"pipe":return Ut(s.in,n)||Ut(s.out,n);case"success":return!1;case"catch":return!1}throw new Error(`Unknown schema type: ${s.type}`)}function bt(t){if(typeof t!="object"||t===null)return!1;const e=t;if(!("_zod"in e))return!1;const n=e._zod;return typeof n=="object"&&n!==null&&"def"in n}function Lt(t){if(typeof t!="object"||t===null)return!1;const e=t;if(!("_def"in e)||"_zod"in e)return!1;const n=e._def;return typeof n=="object"&&n!=null&&"typeName"in n}function SU(t){return bt(t)&&console.warn("[WARNING] Attempting to use Zod 4 schema in a context where Zod 3 schema is expected. This may cause unexpected behavior."),Lt(t)}function Wt(t){return!t||typeof t!="object"||Array.isArray(t)?!1:!!(bt(t)||Lt(t))}function mI(t){return typeof t=="object"&&t!==null&&"_def"in t&&typeof t._def=="object"&&t._def!==null&&"typeName"in t._def&&t._def.typeName==="ZodLiteral"}function gI(t){return bt(t)?typeof t=="object"&&t!==null&&"_zod"in t&&typeof t._zod=="object"&&t._zod!==null&&"def"in t._zod&&typeof t._zod.def=="object"&&t._zod.def!==null&&"type"in t._zod.def&&t._zod.def.type==="literal":!1}function AU(t){return!!(mI(t)||gI(t))}async function xf(t,e){if(bt(t))try{return{success:!0,data:await JE(t,e)}}catch(n){return{success:!1,error:n}}if(Lt(t))return await t.safeParseAsync(e);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}async function kf(t,e){if(bt(t))return await JE(t,e);if(Lt(t))return await t.parseAsync(e);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function TU(t,e){if(bt(t))try{return{success:!0,data:Ef(t,e)}}catch(n){return{success:!1,error:n}}if(Lt(t))return t.safeParse(e);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function Wa(t,e){if(bt(t))return Ef(t,e);if(Lt(t))return t.parse(e);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function jo(t){var e;if(bt(t))return(e=Qt.get(t))==null?void 0:e.description;if(Lt(t)||"description"in t&&typeof t.description=="string")return t.description}function EU(t){if(!Wt(t))return!1;if(Lt(t)){const e=t._def;if(e.typeName==="ZodObject"){const n=t;return!n.shape||Object.keys(n.shape).length===0}if(e.typeName==="ZodRecord")return!0}if(bt(t)){const e=t._zod.def;if(e.type==="object"){const n=t;return!n.shape||Object.keys(n.shape).length===0}if(e.type==="record")return!0}return typeof t=="object"&&t!==null&&!("shape"in t)}function xy(t){return Wt(t)?Lt(t)?t._def.typeName==="ZodString":bt(t)?t._zod.def.type==="string":!1:!1}function Cf(t){return typeof t=="object"&&t!==null&&"_def"in t&&typeof t._def=="object"&&t._def!==null&&"typeName"in t._def&&t._def.typeName==="ZodObject"}function ys(t){return bt(t)?typeof t=="object"&&t!==null&&"_zod"in t&&typeof t._zod=="object"&&t._zod!==null&&"def"in t._zod&&typeof t._zod.def=="object"&&t._zod.def!==null&&"type"in t._zod.def&&t._zod.def.type==="object":!1}function Of(t){return bt(t)?typeof t=="object"&&t!==null&&"_zod"in t&&typeof t._zod=="object"&&t._zod!==null&&"def"in t._zod&&typeof t._zod.def=="object"&&t._zod.def!==null&&"type"in t._zod.def&&t._zod.def.type==="array":!1}function _I(t){return bt(t)?typeof t=="object"&&t!==null&&"_zod"in t&&typeof t._zod=="object"&&t._zod!==null&&"def"in t._zod&&typeof t._zod.def=="object"&&t._zod.def!==null&&"type"in t._zod.def&&t._zod.def.type==="optional":!1}function yI(t){return bt(t)?typeof t=="object"&&t!==null&&"_zod"in t&&typeof t._zod=="object"&&t._zod!==null&&"def"in t._zod&&typeof t._zod.def=="object"&&t._zod.def!==null&&"type"in t._zod.def&&t._zod.def.type==="nullable":!1}function rr(t){return!!(Cf(t)||ys(t))}function Do(t){if(Lt(t))return t.shape;if(bt(t))return t._zod.def.shape;throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function wI(t,e){if(Lt(t))return t.extend(e);if(bt(t))return VE(t,e);throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function ou(t){if(Lt(t))return t.partial();if(bt(t))return KE(Iy,t,void 0);throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function Oh(t,e=!1){if(Cf(t))return t.strict();if(ys(t)){const n=t._zod.def.shape;if(e)for(const[i,a]of Object.entries(t._zod.def.shape)){if(ys(a))n[i]=Oh(a,e);else if(Of(a)){let c=a._zod.def.element;ys(c)&&(c=Oh(c,e)),n[i]=wn(a,{...a._zod.def,element:c})}else n[i]=a;const o=Qt.get(a);o&&Qt.add(n[i],o)}const r=wn(t,{...t._zod.def,shape:n,catchall:hI(cI)}),s=Qt.get(t);return s&&Qt.add(r,s),r}throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function wg(t,e=!1){if(Cf(t))return t.passthrough();if(ys(t)){const n=t._zod.def.shape;if(e)for(const[i,a]of Object.entries(t._zod.def.shape)){if(ys(a))n[i]=wg(a,e);else if(Of(a)){let c=a._zod.def.element;ys(c)&&(c=wg(c,e)),n[i]=wn(a,{...a._zod.def,element:c})}else n[i]=a;const o=Qt.get(a);o&&Qt.add(n[i],o)}const r=wn(t,{...t._zod.def,shape:n,catchall:dI(oI)}),s=Qt.get(t);return s&&Qt.add(r,s),r}throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function IU(t){if(Lt(t))try{const e=t.parse(void 0);return()=>e}catch{return}if(bt(t))try{const e=Ef(t,void 0);return()=>e}catch{return}}function xU(t){return Lt(t)&&"typeName"in t._def&&t._def.typeName==="ZodEffects"}function kU(t){return bt(t)&&t._zod.def.type==="pipe"}function Hi(t,e,n){const r=n.get(t);if(r!==void 0)return r;if(Lt(t))return xU(t)?Hi(t._def.schema,e,n):t;if(bt(t)){let s=t;if(kU(t)&&(s=Hi(t._zod.def.in,e,n)),e){if(ys(s)){const a={};for(const[o,c]of Object.entries(s._zod.def.shape))a[o]=Hi(c,e,n);s=wn(s,{...s._zod.def,shape:a})}else if(Of(s)){const a=Hi(s._zod.def.element,e,n);s=wn(s,{...s._zod.def,element:a})}else if(_I(s)){const a=Hi(s._zod.def.innerType,e,n);s=wn(s,{...s._zod.def,innerType:a})}else if(yI(s)){const a=Hi(s._zod.def.innerType,e,n);s=wn(s,{...s._zod.def,innerType:a})}}const i=Qt.get(t);return i&&Qt.add(s,i),n.set(t,s),s}throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function bI(t,e=!1){return Hi(t,e,new WeakMap)}function CU(t,e){if(Lt(t)){const n=Do(t),r={};for(const[s,i]of Object.entries(n))e(s,i)?r[s]=i.optional():r[s]=i;return t.extend(r)}if(bt(t)){const n=Do(t),r={...t._zod.def.shape};for(const[a,o]of Object.entries(n))e(a,o)&&(r[a]=new Iy({type:"optional",innerType:o}));const s=wn(t,{...t._zod.def,shape:r}),i=Qt.get(t);return i&&Qt.add(s,i),s}throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function vI(t){return t instanceof Error&&(t.constructor.name==="ZodError"||t.constructor.name==="$ZodError")}function jp(t){return t.replace(/[^a-zA-Z-_0-9]/g,"_")}const OU=["*","_","`"];function $U(t){let e="";for(const[n,r]of Object.entries(t))e+=` classDef ${n} ${r};
|
|
99
|
-
`;return e}function RU(t,e,n){const{firstNode:r,lastNode:s,nodeColors:i,withStyles:a=!0,curveStyle:o="linear",wrapLabelNWords:c=9}=n??{};let u=a?`%%{init: {'flowchart': {'curve': '${o}'}}}%%
|
|
100
|
-
graph TD;
|
|
101
|
-
`:`graph TD;
|
|
102
|
-
`;if(a){const p="default",g={[p]:"{0}({1})"};r!==void 0&&(g[r]="{0}([{1}]):::first"),s!==void 0&&(g[s]="{0}([{1}]):::last");for(const[y,b]of Object.entries(t)){const _=b.name.split(":").pop()??"";let w=OU.some(A=>_.startsWith(A)&&_.endsWith(A))?`<p>${_}</p>`:_;Object.keys(b.metadata??{}).length&&(w+=`<hr/><small><em>${Object.entries(b.metadata??{}).map(([A,S])=>`${A} = ${S}`).join(`
|
|
103
|
-
`)}</em></small>`);const v=(g[y]??g[p]).replace("{0}",jp(y)).replace("{1}",w);u+=` ${v}
|
|
104
|
-
`}}const l={};for(const p of e){const g=p.source.split(":"),y=p.target.split(":"),b=g.filter((_,w)=>_===y[w]).join(":");l[b]||(l[b]=[]),l[b].push(p)}const d=new Set;function f(p){return[...p].sort((g,y)=>g.split(":").length-y.split(":").length)}function h(p,g){const y=p.length===1&&p[0].source===p[0].target;if(g&&!y){const _=g.split(":").pop();if(d.has(g))throw new Error(`Found duplicate subgraph '${_}' at '${g} -- 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(g),u+=` subgraph ${_}
|
|
105
|
-
`}const b=f(Object.keys(l).filter(_=>_.startsWith(`${g}:`)&&_!==g&&_.split(":").length===g.split(":").length+1));for(const _ of b)h(l[_],_);for(const _ of p){const{source:w,target:v,data:A,conditional:S}=_;let x="";if(A!==void 0){let E=A;const $=E.split(" ");$.length>c&&(E=Array.from({length:Math.ceil($.length/c)},(k,C)=>$.slice(C*c,(C+1)*c).join(" ")).join(" <br> ")),x=S?` -. ${E} .-> `:` -- ${E} --> `}else x=S?" -.-> ":" --> ";u+=` ${jp(w)}${x}${jp(v)};
|
|
106
|
-
`}g&&!y&&(u+=` end
|
|
107
|
-
`)}h(l[""]??[],"");for(const p in l)!p.includes(":")&&p!==""&&h(l[p],p);return a&&(u+=$U(i??{})),u}async function PU(t,e){let n=(e==null?void 0:e.backgroundColor)??"white";const r=(e==null?void 0:e.imageType)??"png",s=jj(t);n!==void 0&&(/^#(?:[0-9a-fA-F]{3}){1,2}$/.test(n)||(n=`!${n}`));const i=`https://mermaid.ink/img/${s}?bgColor=${n}&type=${r}`,a=await fetch(i);if(!a.ok)throw new Error(["Failed to render the graph using the Mermaid.INK API.",`Status code: ${a.status}`,`Status text: ${a.statusText}`].join(`
|
|
108
|
-
`));return await a.blob()}const NU=Symbol("Let zodToJsonSchema decide on which parser to use"),MU={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"},LU=t=>({...MU,...t}),jU=t=>{const e=LU(t),n=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([r,s])=>[s._def,{def:s._def,path:[...e.basePath,e.definitionPath,r],jsonSchema:void 0}]))}},SI=(t,e)=>{let n=0;for(;n<t.length&&n<e.length&&t[n]===e[n];n++);return[(t.length-n).toString(),...e.slice(n)].join("/")};function Kn(t){if(t.target!=="openAi")return{};const e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?SI(e,t.currentPath):e.join("/")}}function AI(t,e,n,r){r!=null&&r.errorMessages&&n&&(t.errorMessage={...t.errorMessage,[e]:n})}function rt(t,e,n,r,s){t[e]=n,AI(t,e,r,s)}var Xe;(function(t){t.assertEqual=s=>{};function e(s){}t.assertIs=e;function n(s){throw new Error}t.assertNever=n,t.arrayToEnum=s=>{const i={};for(const a of s)i[a]=a;return i},t.getValidEnumValues=s=>{const i=t.objectKeys(s).filter(o=>typeof s[s[o]]!="number"),a={};for(const o of i)a[o]=s[o];return t.objectValues(a)},t.objectValues=s=>t.objectKeys(s).map(function(i){return s[i]}),t.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{const i=[];for(const a in s)Object.prototype.hasOwnProperty.call(s,a)&&i.push(a);return i},t.find=(s,i)=>{for(const a of s)if(i(a))return a},t.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function r(s,i=" | "){return s.map(a=>typeof a=="string"?`'${a}'`:a).join(i)}t.joinValues=r,t.jsonStringifyReplacer=(s,i)=>typeof i=="bigint"?i.toString():i})(Xe||(Xe={}));var q0;(function(t){t.mergeShapes=(e,n)=>({...e,...n})})(q0||(q0={}));const _e=Xe.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ai=t=>{switch(typeof t){case"undefined":return _e.undefined;case"string":return _e.string;case"number":return Number.isNaN(t)?_e.nan:_e.number;case"boolean":return _e.boolean;case"function":return _e.function;case"bigint":return _e.bigint;case"symbol":return _e.symbol;case"object":return Array.isArray(t)?_e.array:t===null?_e.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?_e.promise:typeof Map<"u"&&t instanceof Map?_e.map:typeof Set<"u"&&t instanceof Set?_e.set:typeof Date<"u"&&t instanceof Date?_e.date:_e.object;default:return _e.unknown}},Y=Xe.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class Ks extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};const n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=e}format(e){const n=e||function(i){return i.message},r={_errors:[]},s=i=>{for(const a of i.issues)if(a.code==="invalid_union")a.unionErrors.map(s);else if(a.code==="invalid_return_type")s(a.returnTypeError);else if(a.code==="invalid_arguments")s(a.argumentsError);else if(a.path.length===0)r._errors.push(n(a));else{let o=r,c=0;for(;c<a.path.length;){const u=a.path[c];c===a.path.length-1?(o[u]=o[u]||{_errors:[]},o[u]._errors.push(n(a))):o[u]=o[u]||{_errors:[]},o=o[u],c++}}};return s(this),r}static assert(e){if(!(e instanceof Ks))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Xe.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=n=>n.message){const n={},r=[];for(const s of this.issues)if(s.path.length>0){const i=s.path[0];n[i]=n[i]||[],n[i].push(e(s))}else r.push(e(s));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}}Ks.create=t=>new Ks(t);const bg=(t,e)=>{let n;switch(t.code){case Y.invalid_type:t.received===_e.undefined?n="Required":n=`Expected ${t.expected}, received ${t.received}`;break;case Y.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(t.expected,Xe.jsonStringifyReplacer)}`;break;case Y.unrecognized_keys:n=`Unrecognized key(s) in object: ${Xe.joinValues(t.keys,", ")}`;break;case Y.invalid_union:n="Invalid input";break;case Y.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${Xe.joinValues(t.options)}`;break;case Y.invalid_enum_value:n=`Invalid enum value. Expected ${Xe.joinValues(t.options)}, received '${t.received}'`;break;case Y.invalid_arguments:n="Invalid function arguments";break;case Y.invalid_return_type:n="Invalid function return type";break;case Y.invalid_date:n="Invalid date";break;case Y.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(n=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?n=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?n=`Invalid input: must end with "${t.validation.endsWith}"`:Xe.assertNever(t.validation):t.validation!=="regex"?n=`Invalid ${t.validation}`:n="Invalid";break;case Y.too_small:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:n="Invalid input";break;case Y.too_big:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?n=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:n="Invalid input";break;case Y.custom:n="Invalid input";break;case Y.invalid_intersection_types:n="Intersection results could not be merged";break;case Y.not_multiple_of:n=`Number must be a multiple of ${t.multipleOf}`;break;case Y.not_finite:n="Number must be finite";break;default:n=e.defaultError,Xe.assertNever(t)}return{message:n}};let DU=bg;function UU(){return DU}const FU=t=>{const{data:e,path:n,errorMaps:r,issueData:s}=t,i=[...n,...s.path||[]],a={...s,path:i};if(s.message!==void 0)return{...s,path:i,message:s.message};let o="";const c=r.filter(u=>!!u).slice().reverse();for(const u of c)o=u(a,{data:e,defaultError:o}).message;return{...s,path:i,message:o}};function ce(t,e){const n=UU(),r=FU({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n,n===bg?void 0:bg].filter(s=>!!s)});t.common.issues.push(r)}class hr{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,n){const r=[];for(const s of n){if(s.status==="aborted")return Re;s.status==="dirty"&&e.dirty(),r.push(s.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,n){const r=[];for(const s of n){const i=await s.key,a=await s.value;r.push({key:i,value:a})}return hr.mergeObjectSync(e,r)}static mergeObjectSync(e,n){const r={};for(const s of n){const{key:i,value:a}=s;if(i.status==="aborted"||a.status==="aborted")return Re;i.status==="dirty"&&e.dirty(),a.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof a.value<"u"||s.alwaysSet)&&(r[i.value]=a.value)}return{status:e.value,value:r}}}const Re=Object.freeze({status:"aborted"}),Mc=t=>({status:"dirty",value:t}),$r=t=>({status:"valid",value:t}),G0=t=>t.status==="aborted",J0=t=>t.status==="dirty",Uo=t=>t.status==="valid",$h=t=>typeof Promise<"u"&&t instanceof Promise;var we;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e==null?void 0:e.message})(we||(we={}));class $i{constructor(e,n,r,s){this._cachedPath=[],this.parent=e,this.data=n,this._path=r,this._key=s}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const Y0=(t,e)=>{if(Uo(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const n=new Ks(t.common.issues);return this._error=n,this._error}}};function Be(t){if(!t)return{};const{errorMap:e,invalid_type_error:n,required_error:r,description:s}=t;if(e&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(a,o)=>{const{message:c}=t;return a.code==="invalid_enum_value"?{message:c??o.defaultError}:typeof o.data>"u"?{message:c??r??o.defaultError}:a.code!=="invalid_type"?{message:o.defaultError}:{message:c??n??o.defaultError}},description:s}}let Ye=class{get description(){return this._def.description}_getType(e){return ai(e.data)}_getOrReturnCtx(e,n){return n||{common:e.parent.common,data:e.data,parsedType:ai(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new hr,ctx:{common:e.parent.common,data:e.data,parsedType:ai(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const n=this._parse(e);if($h(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(e){const n=this._parse(e);return Promise.resolve(n)}parse(e,n){const r=this.safeParse(e,n);if(r.success)return r.data;throw r.error}safeParse(e,n){const r={common:{issues:[],async:(n==null?void 0:n.async)??!1,contextualErrorMap:n==null?void 0:n.errorMap},path:(n==null?void 0:n.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ai(e)},s=this._parseSync({data:e,path:r.path,parent:r});return Y0(r,s)}"~validate"(e){var r,s;const n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ai(e)};if(!this["~standard"].async)try{const i=this._parseSync({data:e,path:[],parent:n});return Uo(i)?{value:i.value}:{issues:n.common.issues}}catch(i){(s=(r=i==null?void 0:i.message)==null?void 0:r.toLowerCase())!=null&&s.includes("encountered")&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:n}).then(i=>Uo(i)?{value:i.value}:{issues:n.common.issues})}async parseAsync(e,n){const r=await this.safeParseAsync(e,n);if(r.success)return r.data;throw r.error}async safeParseAsync(e,n){const r={common:{issues:[],contextualErrorMap:n==null?void 0:n.errorMap,async:!0},path:(n==null?void 0:n.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ai(e)},s=this._parse({data:e,path:r.path,parent:r}),i=await($h(s)?s:Promise.resolve(s));return Y0(r,i)}refine(e,n){const r=s=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(s):n;return this._refinement((s,i)=>{const a=e(s),o=()=>i.addIssue({code:Y.custom,...r(s)});return typeof Promise<"u"&&a instanceof Promise?a.then(c=>c?!0:(o(),!1)):a?!0:(o(),!1)})}refinement(e,n){return this._refinement((r,s)=>e(r)?!0:(s.addIssue(typeof n=="function"?n(r,s):n),!1))}_refinement(e){return new Bo({schema:this,typeName:U.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:n=>this["~validate"](n)}}optional(){return Si.create(this,this._def)}nullable(){return zo.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Fo.create(this)}promise(){return Mh.create(this,this._def)}or(e){return Ph.create([this,e],this._def)}and(e){return Nh.create(this,e,this._def)}transform(e){return new Bo({...Be(this._def),schema:this,typeName:U.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const n=typeof e=="function"?e:()=>e;return new kg({...Be(this._def),innerType:this,defaultValue:n,typeName:U.ZodDefault})}brand(){return new uF({typeName:U.ZodBranded,type:this,...Be(this._def)})}catch(e){const n=typeof e=="function"?e:()=>e;return new Cg({...Be(this._def),innerType:this,catchValue:n,typeName:U.ZodCatch})}describe(e){const n=this.constructor;return new n({...this._def,description:e})}pipe(e){return Cy.create(this,e)}readonly(){return Og.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};const BU=/^c[^\s-]{8,}$/i,zU=/^[0-9a-z]+$/,HU=/^[0-9A-HJKMNP-TV-Z]{26}$/i,VU=/^[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,KU=/^[a-z0-9_-]{21}$/i,WU=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,ZU=/^[-+]?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)?)??$/,qU=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,GU="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let Dp;const JU=/^(?:(?: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])$/,YU=/^(?:(?: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])$/,XU=/^(([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]))$/,QU=/^(([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])$/,eF=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,tF=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,TI="((\\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])))",nF=new RegExp(`^${TI}$`);function EI(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);const n=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${n}`}function rF(t){return new RegExp(`^${EI(t)}$`)}function sF(t){let e=`${TI}T${EI(t)}`;const n=[];return n.push(t.local?"Z?":"Z"),t.offset&&n.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${n.join("|")})`,new RegExp(`^${e}$`)}function iF(t,e){return!!((e==="v4"||!e)&&JU.test(t)||(e==="v6"||!e)&&XU.test(t))}function aF(t,e){if(!WU.test(t))return!1;try{const[n]=t.split(".");if(!n)return!1;const r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),s=JSON.parse(atob(r));return!(typeof s!="object"||s===null||"typ"in s&&(s==null?void 0:s.typ)!=="JWT"||!s.alg||e&&s.alg!==e)}catch{return!1}}function oF(t,e){return!!((e==="v4"||!e)&&YU.test(t)||(e==="v6"||!e)&&QU.test(t))}let vg=class Lc extends Ye{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==_e.string){const i=this._getOrReturnCtx(e);return ce(i,{code:Y.invalid_type,expected:_e.string,received:i.parsedType}),Re}const r=new hr;let s;for(const i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(s=this._getOrReturnCtx(e,s),ce(s,{code:Y.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="max")e.data.length>i.value&&(s=this._getOrReturnCtx(e,s),ce(s,{code:Y.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="length"){const a=e.data.length>i.value,o=e.data.length<i.value;(a||o)&&(s=this._getOrReturnCtx(e,s),a?ce(s,{code:Y.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):o&&ce(s,{code:Y.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),r.dirty())}else if(i.kind==="email")qU.test(e.data)||(s=this._getOrReturnCtx(e,s),ce(s,{validation:"email",code:Y.invalid_string,message:i.message}),r.dirty());else if(i.kind==="emoji")Dp||(Dp=new RegExp(GU,"u")),Dp.test(e.data)||(s=this._getOrReturnCtx(e,s),ce(s,{validation:"emoji",code:Y.invalid_string,message:i.message}),r.dirty());else if(i.kind==="uuid")VU.test(e.data)||(s=this._getOrReturnCtx(e,s),ce(s,{validation:"uuid",code:Y.invalid_string,message:i.message}),r.dirty());else if(i.kind==="nanoid")KU.test(e.data)||(s=this._getOrReturnCtx(e,s),ce(s,{validation:"nanoid",code:Y.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid")BU.test(e.data)||(s=this._getOrReturnCtx(e,s),ce(s,{validation:"cuid",code:Y.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid2")zU.test(e.data)||(s=this._getOrReturnCtx(e,s),ce(s,{validation:"cuid2",code:Y.invalid_string,message:i.message}),r.dirty());else if(i.kind==="ulid")HU.test(e.data)||(s=this._getOrReturnCtx(e,s),ce(s,{validation:"ulid",code:Y.invalid_string,message:i.message}),r.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),ce(s,{validation:"url",code:Y.invalid_string,message:i.message}),r.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),ce(s,{validation:"regex",code:Y.invalid_string,message:i.message}),r.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(s=this._getOrReturnCtx(e,s),ce(s,{code:Y.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),r.dirty()):i.kind==="toLowerCase"?e.data=e.data.toLowerCase():i.kind==="toUpperCase"?e.data=e.data.toUpperCase():i.kind==="startsWith"?e.data.startsWith(i.value)||(s=this._getOrReturnCtx(e,s),ce(s,{code:Y.invalid_string,validation:{startsWith:i.value},message:i.message}),r.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(s=this._getOrReturnCtx(e,s),ce(s,{code:Y.invalid_string,validation:{endsWith:i.value},message:i.message}),r.dirty()):i.kind==="datetime"?sF(i).test(e.data)||(s=this._getOrReturnCtx(e,s),ce(s,{code:Y.invalid_string,validation:"datetime",message:i.message}),r.dirty()):i.kind==="date"?nF.test(e.data)||(s=this._getOrReturnCtx(e,s),ce(s,{code:Y.invalid_string,validation:"date",message:i.message}),r.dirty()):i.kind==="time"?rF(i).test(e.data)||(s=this._getOrReturnCtx(e,s),ce(s,{code:Y.invalid_string,validation:"time",message:i.message}),r.dirty()):i.kind==="duration"?ZU.test(e.data)||(s=this._getOrReturnCtx(e,s),ce(s,{validation:"duration",code:Y.invalid_string,message:i.message}),r.dirty()):i.kind==="ip"?iF(e.data,i.version)||(s=this._getOrReturnCtx(e,s),ce(s,{validation:"ip",code:Y.invalid_string,message:i.message}),r.dirty()):i.kind==="jwt"?aF(e.data,i.alg)||(s=this._getOrReturnCtx(e,s),ce(s,{validation:"jwt",code:Y.invalid_string,message:i.message}),r.dirty()):i.kind==="cidr"?oF(e.data,i.version)||(s=this._getOrReturnCtx(e,s),ce(s,{validation:"cidr",code:Y.invalid_string,message:i.message}),r.dirty()):i.kind==="base64"?eF.test(e.data)||(s=this._getOrReturnCtx(e,s),ce(s,{validation:"base64",code:Y.invalid_string,message:i.message}),r.dirty()):i.kind==="base64url"?tF.test(e.data)||(s=this._getOrReturnCtx(e,s),ce(s,{validation:"base64url",code:Y.invalid_string,message:i.message}),r.dirty()):Xe.assertNever(i);return{status:r.value,value:e.data}}_regex(e,n,r){return this.refinement(s=>e.test(s),{validation:n,code:Y.invalid_string,...we.errToObj(r)})}_addCheck(e){return new Lc({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...we.errToObj(e)})}url(e){return this._addCheck({kind:"url",...we.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...we.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...we.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...we.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...we.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...we.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...we.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...we.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...we.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...we.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...we.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...we.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof(e==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,offset:(e==null?void 0:e.offset)??!1,local:(e==null?void 0:e.local)??!1,...we.errToObj(e==null?void 0:e.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof(e==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,...we.errToObj(e==null?void 0:e.message)})}duration(e){return this._addCheck({kind:"duration",...we.errToObj(e)})}regex(e,n){return this._addCheck({kind:"regex",regex:e,...we.errToObj(n)})}includes(e,n){return this._addCheck({kind:"includes",value:e,position:n==null?void 0:n.position,...we.errToObj(n==null?void 0:n.message)})}startsWith(e,n){return this._addCheck({kind:"startsWith",value:e,...we.errToObj(n)})}endsWith(e,n){return this._addCheck({kind:"endsWith",value:e,...we.errToObj(n)})}min(e,n){return this._addCheck({kind:"min",value:e,...we.errToObj(n)})}max(e,n){return this._addCheck({kind:"max",value:e,...we.errToObj(n)})}length(e,n){return this._addCheck({kind:"length",value:e,...we.errToObj(n)})}nonempty(e){return this.min(1,we.errToObj(e))}trim(){return new Lc({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Lc({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Lc({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(const n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxLength(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}};vg.create=t=>new vg({checks:[],typeName:U.ZodString,coerce:(t==null?void 0:t.coerce)??!1,...Be(t)});function cF(t,e){const n=(t.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,s=n>r?n:r,i=Number.parseInt(t.toFixed(s).replace(".","")),a=Number.parseInt(e.toFixed(s).replace(".",""));return i%a/10**s}let Sg=class Ag extends Ye{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)!==_e.number){const i=this._getOrReturnCtx(e);return ce(i,{code:Y.invalid_type,expected:_e.number,received:i.parsedType}),Re}let r;const s=new hr;for(const i of this._def.checks)i.kind==="int"?Xe.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),ce(r,{code:Y.invalid_type,expected:"integer",received:"float",message:i.message}),s.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(r=this._getOrReturnCtx(e,r),ce(r,{code:Y.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(r=this._getOrReturnCtx(e,r),ce(r,{code:Y.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="multipleOf"?cF(e.data,i.value)!==0&&(r=this._getOrReturnCtx(e,r),ce(r,{code:Y.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),ce(r,{code:Y.not_finite,message:i.message}),s.dirty()):Xe.assertNever(i);return{status:s.value,value:e.data}}gte(e,n){return this.setLimit("min",e,!0,we.toString(n))}gt(e,n){return this.setLimit("min",e,!1,we.toString(n))}lte(e,n){return this.setLimit("max",e,!0,we.toString(n))}lt(e,n){return this.setLimit("max",e,!1,we.toString(n))}setLimit(e,n,r,s){return new Ag({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:we.toString(s)}]})}_addCheck(e){return new Ag({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:we.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:we.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:we.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:we.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:we.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:we.toString(n)})}finite(e){return this._addCheck({kind:"finite",message:we.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:we.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:we.toString(e)})}get minValue(){let e=null;for(const n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&Xe.isInteger(e.value))}get isFinite(){let e=null,n=null;for(const r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(e===null||r.value<e)&&(e=r.value)}return Number.isFinite(n)&&Number.isFinite(e)}};Sg.create=t=>new Sg({checks:[],typeName:U.ZodNumber,coerce:(t==null?void 0:t.coerce)||!1,...Be(t)});class ku extends Ye{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)!==_e.bigint)return this._getInvalidInput(e);let r;const s=new hr;for(const i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(r=this._getOrReturnCtx(e,r),ce(r,{code:Y.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(r=this._getOrReturnCtx(e,r),ce(r,{code:Y.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(r=this._getOrReturnCtx(e,r),ce(r,{code:Y.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):Xe.assertNever(i);return{status:s.value,value:e.data}}_getInvalidInput(e){const n=this._getOrReturnCtx(e);return ce(n,{code:Y.invalid_type,expected:_e.bigint,received:n.parsedType}),Re}gte(e,n){return this.setLimit("min",e,!0,we.toString(n))}gt(e,n){return this.setLimit("min",e,!1,we.toString(n))}lte(e,n){return this.setLimit("max",e,!0,we.toString(n))}lt(e,n){return this.setLimit("max",e,!1,we.toString(n))}setLimit(e,n,r,s){return new ku({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:we.toString(s)}]})}_addCheck(e){return new ku({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:we.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:we.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:we.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:we.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:we.toString(n)})}get minValue(){let e=null;for(const n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}}ku.create=t=>new ku({checks:[],typeName:U.ZodBigInt,coerce:(t==null?void 0:t.coerce)??!1,...Be(t)});let Tg=class extends Ye{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==_e.boolean){const r=this._getOrReturnCtx(e);return ce(r,{code:Y.invalid_type,expected:_e.boolean,received:r.parsedType}),Re}return $r(e.data)}};Tg.create=t=>new Tg({typeName:U.ZodBoolean,coerce:(t==null?void 0:t.coerce)||!1,...Be(t)});class Rh extends Ye{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==_e.date){const i=this._getOrReturnCtx(e);return ce(i,{code:Y.invalid_type,expected:_e.date,received:i.parsedType}),Re}if(Number.isNaN(e.data.getTime())){const i=this._getOrReturnCtx(e);return ce(i,{code:Y.invalid_date}),Re}const r=new hr;let s;for(const i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(s=this._getOrReturnCtx(e,s),ce(s,{code:Y.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),r.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(s=this._getOrReturnCtx(e,s),ce(s,{code:Y.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):Xe.assertNever(i);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new Rh({...this._def,checks:[...this._def.checks,e]})}min(e,n){return this._addCheck({kind:"min",value:e.getTime(),message:we.toString(n)})}max(e,n){return this._addCheck({kind:"max",value:e.getTime(),message:we.toString(n)})}get minDate(){let e=null;for(const n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e!=null?new Date(e):null}}Rh.create=t=>new Rh({checks:[],coerce:(t==null?void 0:t.coerce)||!1,typeName:U.ZodDate,...Be(t)});class X0 extends Ye{_parse(e){if(this._getType(e)!==_e.symbol){const r=this._getOrReturnCtx(e);return ce(r,{code:Y.invalid_type,expected:_e.symbol,received:r.parsedType}),Re}return $r(e.data)}}X0.create=t=>new X0({typeName:U.ZodSymbol,...Be(t)});class Q0 extends Ye{_parse(e){if(this._getType(e)!==_e.undefined){const r=this._getOrReturnCtx(e);return ce(r,{code:Y.invalid_type,expected:_e.undefined,received:r.parsedType}),Re}return $r(e.data)}}Q0.create=t=>new Q0({typeName:U.ZodUndefined,...Be(t)});class ev extends Ye{_parse(e){if(this._getType(e)!==_e.null){const r=this._getOrReturnCtx(e);return ce(r,{code:Y.invalid_type,expected:_e.null,received:r.parsedType}),Re}return $r(e.data)}}ev.create=t=>new ev({typeName:U.ZodNull,...Be(t)});let Eg=class extends Ye{constructor(){super(...arguments),this._any=!0}_parse(e){return $r(e.data)}};Eg.create=t=>new Eg({typeName:U.ZodAny,...Be(t)});let tv=class extends Ye{constructor(){super(...arguments),this._unknown=!0}_parse(e){return $r(e.data)}};tv.create=t=>new tv({typeName:U.ZodUnknown,...Be(t)});let Ri=class extends Ye{_parse(e){const n=this._getOrReturnCtx(e);return ce(n,{code:Y.invalid_type,expected:_e.never,received:n.parsedType}),Re}};Ri.create=t=>new Ri({typeName:U.ZodNever,...Be(t)});class nv extends Ye{_parse(e){if(this._getType(e)!==_e.undefined){const r=this._getOrReturnCtx(e);return ce(r,{code:Y.invalid_type,expected:_e.void,received:r.parsedType}),Re}return $r(e.data)}}nv.create=t=>new nv({typeName:U.ZodVoid,...Be(t)});let Fo=class Fd extends Ye{_parse(e){const{ctx:n,status:r}=this._processInputParams(e),s=this._def;if(n.parsedType!==_e.array)return ce(n,{code:Y.invalid_type,expected:_e.array,received:n.parsedType}),Re;if(s.exactLength!==null){const a=n.data.length>s.exactLength.value,o=n.data.length<s.exactLength.value;(a||o)&&(ce(n,{code:a?Y.too_big:Y.too_small,minimum:o?s.exactLength.value:void 0,maximum:a?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),r.dirty())}if(s.minLength!==null&&n.data.length<s.minLength.value&&(ce(n,{code:Y.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),r.dirty()),s.maxLength!==null&&n.data.length>s.maxLength.value&&(ce(n,{code:Y.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((a,o)=>s.type._parseAsync(new $i(n,a,n.path,o)))).then(a=>hr.mergeArray(r,a));const i=[...n.data].map((a,o)=>s.type._parseSync(new $i(n,a,n.path,o)));return hr.mergeArray(r,i)}get element(){return this._def.type}min(e,n){return new Fd({...this._def,minLength:{value:e,message:we.toString(n)}})}max(e,n){return new Fd({...this._def,maxLength:{value:e,message:we.toString(n)}})}length(e,n){return new Fd({...this._def,exactLength:{value:e,message:we.toString(n)}})}nonempty(e){return this.min(1,e)}};Fo.create=(t,e)=>new Fo({type:t,minLength:null,maxLength:null,exactLength:null,typeName:U.ZodArray,...Be(e)});function Za(t){if(t instanceof Ws){const e={};for(const n in t.shape){const r=t.shape[n];e[n]=Si.create(Za(r))}return new Ws({...t._def,shape:()=>e})}else return t instanceof Fo?new Fo({...t._def,type:Za(t.element)}):t instanceof Si?Si.create(Za(t.unwrap())):t instanceof zo?zo.create(Za(t.unwrap())):t instanceof Cu?Cu.create(t.items.map(e=>Za(e))):t}let Ws=class Ur extends Ye{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape(),n=Xe.objectKeys(e);return this._cached={shape:e,keys:n},this._cached}_parse(e){if(this._getType(e)!==_e.object){const u=this._getOrReturnCtx(e);return ce(u,{code:Y.invalid_type,expected:_e.object,received:u.parsedType}),Re}const{status:r,ctx:s}=this._processInputParams(e),{shape:i,keys:a}=this._getCached(),o=[];if(!(this._def.catchall instanceof Ri&&this._def.unknownKeys==="strip"))for(const u in s.data)a.includes(u)||o.push(u);const c=[];for(const u of a){const l=i[u],d=s.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new $i(s,d,s.path,u)),alwaysSet:u in s.data})}if(this._def.catchall instanceof Ri){const u=this._def.unknownKeys;if(u==="passthrough")for(const l of o)c.push({key:{status:"valid",value:l},value:{status:"valid",value:s.data[l]}});else if(u==="strict")o.length>0&&(ce(s,{code:Y.unrecognized_keys,keys:o}),r.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const u=this._def.catchall;for(const l of o){const d=s.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new $i(s,d,s.path,l)),alwaysSet:l in s.data})}}return s.common.async?Promise.resolve().then(async()=>{const u=[];for(const l of c){const d=await l.key,f=await l.value;u.push({key:d,value:f,alwaysSet:l.alwaysSet})}return u}).then(u=>hr.mergeObjectSync(r,u)):hr.mergeObjectSync(r,c)}get shape(){return this._def.shape()}strict(e){return we.errToObj,new Ur({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(n,r)=>{var i,a;const s=((a=(i=this._def).errorMap)==null?void 0:a.call(i,n,r).message)??r.defaultError;return n.code==="unrecognized_keys"?{message:we.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new Ur({...this._def,unknownKeys:"strip"})}passthrough(){return new Ur({...this._def,unknownKeys:"passthrough"})}extend(e){return new Ur({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new Ur({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:U.ZodObject})}setKey(e,n){return this.augment({[e]:n})}catchall(e){return new Ur({...this._def,catchall:e})}pick(e){const n={};for(const r of Xe.objectKeys(e))e[r]&&this.shape[r]&&(n[r]=this.shape[r]);return new Ur({...this._def,shape:()=>n})}omit(e){const n={};for(const r of Xe.objectKeys(this.shape))e[r]||(n[r]=this.shape[r]);return new Ur({...this._def,shape:()=>n})}deepPartial(){return Za(this)}partial(e){const n={};for(const r of Xe.objectKeys(this.shape)){const s=this.shape[r];e&&!e[r]?n[r]=s:n[r]=s.optional()}return new Ur({...this._def,shape:()=>n})}required(e){const n={};for(const r of Xe.objectKeys(this.shape))if(e&&!e[r])n[r]=this.shape[r];else{let i=this.shape[r];for(;i instanceof Si;)i=i._def.innerType;n[r]=i}return new Ur({...this._def,shape:()=>n})}keyof(){return xI(Xe.objectKeys(this.shape))}};Ws.create=(t,e)=>new Ws({shape:()=>t,unknownKeys:"strip",catchall:Ri.create(),typeName:U.ZodObject,...Be(e)});Ws.strictCreate=(t,e)=>new Ws({shape:()=>t,unknownKeys:"strict",catchall:Ri.create(),typeName:U.ZodObject,...Be(e)});Ws.lazycreate=(t,e)=>new Ws({shape:t,unknownKeys:"strip",catchall:Ri.create(),typeName:U.ZodObject,...Be(e)});let Ph=class extends Ye{_parse(e){const{ctx:n}=this._processInputParams(e),r=this._def.options;function s(i){for(const o of i)if(o.result.status==="valid")return o.result;for(const o of i)if(o.result.status==="dirty")return n.common.issues.push(...o.ctx.common.issues),o.result;const a=i.map(o=>new Ks(o.ctx.common.issues));return ce(n,{code:Y.invalid_union,unionErrors:a}),Re}if(n.common.async)return Promise.all(r.map(async i=>{const a={...n,common:{...n.common,issues:[]},parent:null};return{result:await i._parseAsync({data:n.data,path:n.path,parent:a}),ctx:a}})).then(s);{let i;const a=[];for(const c of r){const u={...n,common:{...n.common,issues:[]},parent:null},l=c._parseSync({data:n.data,path:n.path,parent:u});if(l.status==="valid")return l;l.status==="dirty"&&!i&&(i={result:l,ctx:u}),u.common.issues.length&&a.push(u.common.issues)}if(i)return n.common.issues.push(...i.ctx.common.issues),i.result;const o=a.map(c=>new Ks(c));return ce(n,{code:Y.invalid_union,unionErrors:o}),Re}}get options(){return this._def.options}};Ph.create=(t,e)=>new Ph({options:t,typeName:U.ZodUnion,...Be(e)});function Ig(t,e){const n=ai(t),r=ai(e);if(t===e)return{valid:!0,data:t};if(n===_e.object&&r===_e.object){const s=Xe.objectKeys(e),i=Xe.objectKeys(t).filter(o=>s.indexOf(o)!==-1),a={...t,...e};for(const o of i){const c=Ig(t[o],e[o]);if(!c.valid)return{valid:!1};a[o]=c.data}return{valid:!0,data:a}}else if(n===_e.array&&r===_e.array){if(t.length!==e.length)return{valid:!1};const s=[];for(let i=0;i<t.length;i++){const a=t[i],o=e[i],c=Ig(a,o);if(!c.valid)return{valid:!1};s.push(c.data)}return{valid:!0,data:s}}else return n===_e.date&&r===_e.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}let Nh=class extends Ye{_parse(e){const{status:n,ctx:r}=this._processInputParams(e),s=(i,a)=>{if(G0(i)||G0(a))return Re;const o=Ig(i.value,a.value);return o.valid?((J0(i)||J0(a))&&n.dirty(),{status:n.value,value:o.data}):(ce(r,{code:Y.invalid_intersection_types}),Re)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([i,a])=>s(i,a)):s(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};Nh.create=(t,e,n)=>new Nh({left:t,right:e,typeName:U.ZodIntersection,...Be(n)});let Cu=class II extends Ye{_parse(e){const{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==_e.array)return ce(r,{code:Y.invalid_type,expected:_e.array,received:r.parsedType}),Re;if(r.data.length<this._def.items.length)return ce(r,{code:Y.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),Re;!this._def.rest&&r.data.length>this._def.items.length&&(ce(r,{code:Y.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());const i=[...r.data].map((a,o)=>{const c=this._def.items[o]||this._def.rest;return c?c._parse(new $i(r,a,r.path,o)):null}).filter(a=>!!a);return r.common.async?Promise.all(i).then(a=>hr.mergeArray(n,a)):hr.mergeArray(n,i)}get items(){return this._def.items}rest(e){return new II({...this._def,rest:e})}};Cu.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Cu({items:t,typeName:U.ZodTuple,rest:null,...Be(e)})};class rv extends Ye{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==_e.map)return ce(r,{code:Y.invalid_type,expected:_e.map,received:r.parsedType}),Re;const s=this._def.keyType,i=this._def.valueType,a=[...r.data.entries()].map(([o,c],u)=>({key:s._parse(new $i(r,o,r.path,[u,"key"])),value:i._parse(new $i(r,c,r.path,[u,"value"]))}));if(r.common.async){const o=new Map;return Promise.resolve().then(async()=>{for(const c of a){const u=await c.key,l=await c.value;if(u.status==="aborted"||l.status==="aborted")return Re;(u.status==="dirty"||l.status==="dirty")&&n.dirty(),o.set(u.value,l.value)}return{status:n.value,value:o}})}else{const o=new Map;for(const c of a){const u=c.key,l=c.value;if(u.status==="aborted"||l.status==="aborted")return Re;(u.status==="dirty"||l.status==="dirty")&&n.dirty(),o.set(u.value,l.value)}return{status:n.value,value:o}}}}rv.create=(t,e,n)=>new rv({valueType:e,keyType:t,typeName:U.ZodMap,...Be(n)});class Ou extends Ye{_parse(e){const{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==_e.set)return ce(r,{code:Y.invalid_type,expected:_e.set,received:r.parsedType}),Re;const s=this._def;s.minSize!==null&&r.data.size<s.minSize.value&&(ce(r,{code:Y.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),n.dirty()),s.maxSize!==null&&r.data.size>s.maxSize.value&&(ce(r,{code:Y.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),n.dirty());const i=this._def.valueType;function a(c){const u=new Set;for(const l of c){if(l.status==="aborted")return Re;l.status==="dirty"&&n.dirty(),u.add(l.value)}return{status:n.value,value:u}}const o=[...r.data.values()].map((c,u)=>i._parse(new $i(r,c,r.path,u)));return r.common.async?Promise.all(o).then(c=>a(c)):a(o)}min(e,n){return new Ou({...this._def,minSize:{value:e,message:we.toString(n)}})}max(e,n){return new Ou({...this._def,maxSize:{value:e,message:we.toString(n)}})}size(e,n){return this.min(e,n).max(e,n)}nonempty(e){return this.min(1,e)}}Ou.create=(t,e)=>new Ou({valueType:t,minSize:null,maxSize:null,typeName:U.ZodSet,...Be(e)});class sv extends Ye{get schema(){return this._def.getter()}_parse(e){const{ctx:n}=this._processInputParams(e);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}}sv.create=(t,e)=>new sv({getter:t,typeName:U.ZodLazy,...Be(e)});let iv=class extends Ye{_parse(e){if(e.data!==this._def.value){const n=this._getOrReturnCtx(e);return ce(n,{received:n.data,code:Y.invalid_literal,expected:this._def.value}),Re}return{status:"valid",value:e.data}}get value(){return this._def.value}};iv.create=(t,e)=>new iv({value:t,typeName:U.ZodLiteral,...Be(e)});function xI(t,e){return new ky({values:t,typeName:U.ZodEnum,...Be(e)})}let ky=class xg extends Ye{_parse(e){if(typeof e.data!="string"){const n=this._getOrReturnCtx(e),r=this._def.values;return ce(n,{expected:Xe.joinValues(r),received:n.parsedType,code:Y.invalid_type}),Re}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const n=this._getOrReturnCtx(e),r=this._def.values;return ce(n,{received:n.data,code:Y.invalid_enum_value,options:r}),Re}return $r(e.data)}get options(){return this._def.values}get enum(){const e={};for(const n of this._def.values)e[n]=n;return e}get Values(){const e={};for(const n of this._def.values)e[n]=n;return e}get Enum(){const e={};for(const n of this._def.values)e[n]=n;return e}extract(e,n=this._def){return xg.create(e,{...this._def,...n})}exclude(e,n=this._def){return xg.create(this.options.filter(r=>!e.includes(r)),{...this._def,...n})}};ky.create=xI;class av extends Ye{_parse(e){const n=Xe.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==_e.string&&r.parsedType!==_e.number){const s=Xe.objectValues(n);return ce(r,{expected:Xe.joinValues(s),received:r.parsedType,code:Y.invalid_type}),Re}if(this._cache||(this._cache=new Set(Xe.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const s=Xe.objectValues(n);return ce(r,{received:r.data,code:Y.invalid_enum_value,options:s}),Re}return $r(e.data)}get enum(){return this._def.values}}av.create=(t,e)=>new av({values:t,typeName:U.ZodNativeEnum,...Be(e)});class Mh extends Ye{unwrap(){return this._def.type}_parse(e){const{ctx:n}=this._processInputParams(e);if(n.parsedType!==_e.promise&&n.common.async===!1)return ce(n,{code:Y.invalid_type,expected:_e.promise,received:n.parsedType}),Re;const r=n.parsedType===_e.promise?n.data:Promise.resolve(n.data);return $r(r.then(s=>this._def.type.parseAsync(s,{path:n.path,errorMap:n.common.contextualErrorMap})))}}Mh.create=(t,e)=>new Mh({type:t,typeName:U.ZodPromise,...Be(e)});class Bo extends Ye{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===U.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:n,ctx:r}=this._processInputParams(e),s=this._def.effect||null,i={addIssue:a=>{ce(r,a),a.fatal?n.abort():n.dirty()},get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),s.type==="preprocess"){const a=s.transform(r.data,i);if(r.common.async)return Promise.resolve(a).then(async o=>{if(n.value==="aborted")return Re;const c=await this._def.schema._parseAsync({data:o,path:r.path,parent:r});return c.status==="aborted"?Re:c.status==="dirty"||n.value==="dirty"?Mc(c.value):c});{if(n.value==="aborted")return Re;const o=this._def.schema._parseSync({data:a,path:r.path,parent:r});return o.status==="aborted"?Re:o.status==="dirty"||n.value==="dirty"?Mc(o.value):o}}if(s.type==="refinement"){const a=o=>{const c=s.refinement(o,i);if(r.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return o};if(r.common.async===!1){const o=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?Re:(o.status==="dirty"&&n.dirty(),a(o.value),{status:n.value,value:o.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(o=>o.status==="aborted"?Re:(o.status==="dirty"&&n.dirty(),a(o.value).then(()=>({status:n.value,value:o.value}))))}if(s.type==="transform")if(r.common.async===!1){const a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!Uo(a))return Re;const o=s.transform(a.value,i);if(o instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:o}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(a=>Uo(a)?Promise.resolve(s.transform(a.value,i)).then(o=>({status:n.value,value:o})):Re);Xe.assertNever(s)}}Bo.create=(t,e,n)=>new Bo({schema:t,typeName:U.ZodEffects,effect:e,...Be(n)});Bo.createWithPreprocess=(t,e,n)=>new Bo({schema:e,effect:{type:"preprocess",transform:t},typeName:U.ZodEffects,...Be(n)});let Si=class extends Ye{_parse(e){return this._getType(e)===_e.undefined?$r(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Si.create=(t,e)=>new Si({innerType:t,typeName:U.ZodOptional,...Be(e)});let zo=class extends Ye{_parse(e){return this._getType(e)===_e.null?$r(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};zo.create=(t,e)=>new zo({innerType:t,typeName:U.ZodNullable,...Be(e)});let kg=class extends Ye{_parse(e){const{ctx:n}=this._processInputParams(e);let r=n.data;return n.parsedType===_e.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};kg.create=(t,e)=>new kg({innerType:t,typeName:U.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...Be(e)});let Cg=class extends Ye{_parse(e){const{ctx:n}=this._processInputParams(e),r={...n,common:{...n.common,issues:[]}},s=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return $h(s)?s.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Ks(r.common.issues)},input:r.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Ks(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};Cg.create=(t,e)=>new Cg({innerType:t,typeName:U.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...Be(e)});class ov extends Ye{_parse(e){if(this._getType(e)!==_e.nan){const r=this._getOrReturnCtx(e);return ce(r,{code:Y.invalid_type,expected:_e.nan,received:r.parsedType}),Re}return{status:"valid",value:e.data}}}ov.create=t=>new ov({typeName:U.ZodNaN,...Be(t)});class uF extends Ye{_parse(e){const{ctx:n}=this._processInputParams(e),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}}class Cy extends Ye{_parse(e){const{status:n,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{const i=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?Re:i.status==="dirty"?(n.dirty(),Mc(i.value)):this._def.out._parseAsync({data:i.value,path:r.path,parent:r})})();{const s=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?Re:s.status==="dirty"?(n.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:r.path,parent:r})}}static create(e,n){return new Cy({in:e,out:n,typeName:U.ZodPipeline})}}let Og=class extends Ye{_parse(e){const n=this._def.innerType._parse(e),r=s=>(Uo(s)&&(s.value=Object.freeze(s.value)),s);return $h(n)?n.then(s=>r(s)):r(n)}unwrap(){return this._def.innerType}};Og.create=(t,e)=>new Og({innerType:t,typeName:U.ZodReadonly,...Be(e)});var U;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(U||(U={}));const tr=vg.create,ed=Sg.create,Up=Tg.create,cv=Eg.create;Ri.create;const lF=Fo.create,Vr=Ws.create;Ph.create;Nh.create;Cu.create;const uv=ky.create;Mh.create;Si.create;zo.create;function dF(t,e){var r,s,i;const n={type:"array"};return(r=t.type)!=null&&r._def&&((i=(s=t.type)==null?void 0:s._def)==null?void 0:i.typeName)!==U.ZodAny&&(n.items=tt(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&rt(n,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&rt(n,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(rt(n,"minItems",t.exactLength.value,t.exactLength.message,e),rt(n,"maxItems",t.exactLength.value,t.exactLength.message,e)),n}function hF(t,e){const n={type:"integer",format:"int64"};if(!t.checks)return n;for(const r of t.checks)switch(r.kind){case"min":e.target==="jsonSchema7"?r.inclusive?rt(n,"minimum",r.value,r.message,e):rt(n,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(n.exclusiveMinimum=!0),rt(n,"minimum",r.value,r.message,e));break;case"max":e.target==="jsonSchema7"?r.inclusive?rt(n,"maximum",r.value,r.message,e):rt(n,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(n.exclusiveMaximum=!0),rt(n,"maximum",r.value,r.message,e));break;case"multipleOf":rt(n,"multipleOf",r.value,r.message,e);break}return n}function fF(){return{type:"boolean"}}function kI(t,e){return tt(t.type._def,e)}const pF=(t,e)=>tt(t.innerType._def,e);function CI(t,e,n){const r=n??e.dateStrategy;if(Array.isArray(r))return{anyOf:r.map(s=>CI(t,e,s))};switch(r){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return mF(t,e)}}const mF=(t,e)=>{const n={type:"integer",format:"unix-time"};if(e.target==="openApi3")return n;for(const r of t.checks)switch(r.kind){case"min":rt(n,"minimum",r.value,r.message,e);break;case"max":rt(n,"maximum",r.value,r.message,e);break}return n};function gF(t,e){return{...tt(t.innerType._def,e),default:t.defaultValue()}}function _F(t,e){return e.effectStrategy==="input"?tt(t.schema._def,e):Kn(e)}function yF(t){return{type:"string",enum:Array.from(t.values)}}const wF=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function bF(t,e){const n=[tt(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),tt(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(i=>!!i);let r=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0;const s=[];return n.forEach(i=>{if(wF(i))s.push(...i.allOf),i.unevaluatedProperties===void 0&&(r=void 0);else{let a=i;if("additionalProperties"in i&&i.additionalProperties===!1){const{additionalProperties:o,...c}=i;a=c}else r=void 0;s.push(a)}}),s.length?{allOf:s,...r}:void 0}function vF(t,e){const n=typeof t.value;return n!=="bigint"&&n!=="number"&&n!=="boolean"&&n!=="string"?{type:Array.isArray(t.value)?"array":"object"}:e.target==="openApi3"?{type:n==="bigint"?"integer":n,enum:[t.value]}:{type:n==="bigint"?"integer":n,const:t.value}}let Fp;const Nr={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:()=>(Fp===void 0&&(Fp=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Fp),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 OI(t,e){const n={type:"string"};if(t.checks)for(const r of t.checks)switch(r.kind){case"min":rt(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value,r.message,e);break;case"max":rt(n,"maxLength",typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value,r.message,e);break;case"email":switch(e.emailStrategy){case"format:email":Mr(n,"email",r.message,e);break;case"format:idn-email":Mr(n,"idn-email",r.message,e);break;case"pattern:zod":xn(n,Nr.email,r.message,e);break}break;case"url":Mr(n,"uri",r.message,e);break;case"uuid":Mr(n,"uuid",r.message,e);break;case"regex":xn(n,r.regex,r.message,e);break;case"cuid":xn(n,Nr.cuid,r.message,e);break;case"cuid2":xn(n,Nr.cuid2,r.message,e);break;case"startsWith":xn(n,RegExp(`^${Bp(r.value,e)}`),r.message,e);break;case"endsWith":xn(n,RegExp(`${Bp(r.value,e)}$`),r.message,e);break;case"datetime":Mr(n,"date-time",r.message,e);break;case"date":Mr(n,"date",r.message,e);break;case"time":Mr(n,"time",r.message,e);break;case"duration":Mr(n,"duration",r.message,e);break;case"length":rt(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value,r.message,e),rt(n,"maxLength",typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value,r.message,e);break;case"includes":xn(n,RegExp(Bp(r.value,e)),r.message,e);break;case"ip":r.version!=="v6"&&Mr(n,"ipv4",r.message,e),r.version!=="v4"&&Mr(n,"ipv6",r.message,e);break;case"base64url":xn(n,Nr.base64url,r.message,e);break;case"jwt":xn(n,Nr.jwt,r.message,e);break;case"cidr":r.version!=="v6"&&xn(n,Nr.ipv4Cidr,r.message,e),r.version!=="v4"&&xn(n,Nr.ipv6Cidr,r.message,e);break;case"emoji":xn(n,Nr.emoji(),r.message,e);break;case"ulid":xn(n,Nr.ulid,r.message,e);break;case"base64":switch(e.base64Strategy){case"format:binary":Mr(n,"binary",r.message,e);break;case"contentEncoding:base64":rt(n,"contentEncoding","base64",r.message,e);break;case"pattern:zod":xn(n,Nr.base64,r.message,e);break}break;case"nanoid":xn(n,Nr.nanoid,r.message,e);break}return n}function Bp(t,e){return e.patternStrategy==="escape"?AF(t):t}const SF=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function AF(t){let e="";for(let n=0;n<t.length;n++)SF.has(t[n])||(e+="\\"),e+=t[n];return e}function Mr(t,e,n,r){var s;t.format||(s=t.anyOf)!=null&&s.some(i=>i.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&r.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...n&&r.errorMessages&&{errorMessage:{format:n}}})):rt(t,"format",e,n,r)}function xn(t,e,n,r){var s;t.pattern||(s=t.allOf)!=null&&s.some(i=>i.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&r.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:lv(e,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):rt(t,"pattern",lv(e,r),n,r)}function lv(t,e){var c;if(!e.applyRegexFlags||!t.flags)return t.source;const n={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},r=n.i?t.source.toLowerCase():t.source;let s="",i=!1,a=!1,o=!1;for(let u=0;u<r.length;u++){if(i){s+=r[u],i=!1;continue}if(n.i){if(a){if(r[u].match(/[a-z]/)){o?(s+=r[u],s+=`${r[u-2]}-${r[u]}`.toUpperCase(),o=!1):r[u+1]==="-"&&((c=r[u+2])!=null&&c.match(/[a-z]/))?(s+=r[u],o=!0):s+=`${r[u]}${r[u].toUpperCase()}`;continue}}else if(r[u].match(/[a-z]/)){s+=`[${r[u]}${r[u].toUpperCase()}]`;continue}}if(n.m){if(r[u]==="^"){s+=`(^|(?<=[\r
|
|
109
|
-
]))`;continue}else if(r[u]==="$"){s+=`($|(?=[\r
|
|
110
|
-
]))`;continue}}if(n.s&&r[u]==="."){s+=a?`${r[u]}\r
|
|
111
|
-
`:`[${r[u]}\r
|
|
112
|
-
]`;continue}s+=r[u],r[u]==="\\"?i=!0:a&&r[u]==="]"?a=!1:!a&&r[u]==="["&&(a=!0)}try{new RegExp(s)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return s}function $I(t,e){var r,s,i,a,o,c;if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&((r=t.keyType)==null?void 0:r._def.typeName)===U.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((u,l)=>({...u,[l]:tt(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",l]})??Kn(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};const n={type:"object",additionalProperties:tt(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return n;if(((s=t.keyType)==null?void 0:s._def.typeName)===U.ZodString&&((i=t.keyType._def.checks)!=null&&i.length)){const{type:u,...l}=OI(t.keyType._def,e);return{...n,propertyNames:l}}else{if(((a=t.keyType)==null?void 0:a._def.typeName)===U.ZodEnum)return{...n,propertyNames:{enum:t.keyType._def.values}};if(((o=t.keyType)==null?void 0:o._def.typeName)===U.ZodBranded&&t.keyType._def.type._def.typeName===U.ZodString&&((c=t.keyType._def.type._def.checks)!=null&&c.length)){const{type:u,...l}=kI(t.keyType._def,e);return{...n,propertyNames:l}}}return n}function TF(t,e){return e.mapStrategy==="record"?$I(t,e):{type:"array",maxItems:125,items:{type:"array",items:[tt(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||Kn(e),tt(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||Kn(e)],minItems:2,maxItems:2}}}function EF(t){const e=t.values,n=Object.keys(t.values).filter(s=>typeof e[e[s]]!="number").map(s=>e[s]),r=Array.from(new Set(n.map(s=>typeof s)));return{type:r.length===1?r[0]==="string"?"string":"number":["string","number"],enum:n}}function IF(t){return t.target==="openAi"?void 0:{not:Kn({...t,currentPath:[...t.currentPath,"not"]})}}function xF(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}const Lh={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function kF(t,e){if(e.target==="openApi3")return dv(t,e);const n=t.options instanceof Map?Array.from(t.options.values()):t.options;if(n.every(r=>r._def.typeName in Lh&&(!r._def.checks||!r._def.checks.length))){const r=n.reduce((s,i)=>{const a=Lh[i._def.typeName];return a&&!s.includes(a)?[...s,a]:s},[]);return{type:r.length>1?r:r[0]}}else if(n.every(r=>r._def.typeName==="ZodLiteral"&&!r.description)){const r=n.reduce((s,i)=>{const a=typeof i._def.value;switch(a){case"string":case"number":case"boolean":return[...s,a];case"bigint":return[...s,"integer"];case"object":return i._def.value===null?[...s,"null"]:s;default:return s}},[]);if(r.length===n.length){const s=r.filter((i,a,o)=>o.indexOf(i)===a);return{type:s.length>1?s:s[0],enum:n.reduce((i,a)=>i.includes(a._def.value)?i:[...i,a._def.value],[])}}}else if(n.every(r=>r._def.typeName==="ZodEnum"))return{type:"string",enum:n.reduce((r,s)=>[...r,...s._def.values.filter(i=>!r.includes(i))],[])};return dv(t,e)}const dv=(t,e)=>{const n=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((r,s)=>tt(r._def,{...e,currentPath:[...e.currentPath,"anyOf",`${s}`]})).filter(r=>!!r&&(!e.strictUnions||typeof r=="object"&&Object.keys(r).length>0));return n.length?{anyOf:n}:void 0};function CF(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"?{type:Lh[t.innerType._def.typeName],nullable:!0}:{type:[Lh[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){const r=tt(t.innerType._def,{...e,currentPath:[...e.currentPath]});return r&&"$ref"in r?{allOf:[r],nullable:!0}:r&&{...r,nullable:!0}}const n=tt(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}function OF(t,e){const n={type:"number"};if(!t.checks)return n;for(const r of t.checks)switch(r.kind){case"int":n.type="integer",AI(n,"type",r.message,e);break;case"min":e.target==="jsonSchema7"?r.inclusive?rt(n,"minimum",r.value,r.message,e):rt(n,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(n.exclusiveMinimum=!0),rt(n,"minimum",r.value,r.message,e));break;case"max":e.target==="jsonSchema7"?r.inclusive?rt(n,"maximum",r.value,r.message,e):rt(n,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(n.exclusiveMaximum=!0),rt(n,"maximum",r.value,r.message,e));break;case"multipleOf":rt(n,"multipleOf",r.value,r.message,e);break}return n}function $F(t,e){const n=e.target==="openAi",r={type:"object",properties:{}},s=[],i=t.shape();for(const o in i){let c=i[o];if(c===void 0||c._def===void 0)continue;let u=PF(c);u&&n&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),u=!1);const l=tt(c._def,{...e,currentPath:[...e.currentPath,"properties",o],propertyPath:[...e.currentPath,"properties",o]});l!==void 0&&(r.properties[o]=l,u||s.push(o))}s.length&&(r.required=s);const a=RF(t,e);return a!==void 0&&(r.additionalProperties=a),r}function RF(t,e){if(t.catchall._def.typeName!=="ZodNever")return tt(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function PF(t){try{return t.isOptional()}catch{return!0}}const NF=(t,e)=>{var r;if(e.currentPath.toString()===((r=e.propertyPath)==null?void 0:r.toString()))return tt(t.innerType._def,e);const n=tt(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return n?{anyOf:[{not:Kn(e)},n]}:Kn(e)},MF=(t,e)=>{if(e.pipeStrategy==="input")return tt(t.in._def,e);if(e.pipeStrategy==="output")return tt(t.out._def,e);const n=tt(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]});return{allOf:[n,tt(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",n?"1":"0"]})].filter(r=>r!==void 0)}};function LF(t,e){return tt(t.type._def,e)}function jF(t,e){const n={type:"array",uniqueItems:!0,items:tt(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&rt(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&rt(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}function DF(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((n,r)=>tt(n._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[]),additionalItems:tt(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((n,r)=>tt(n._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[])}}function UF(t){return{not:Kn(t)}}function FF(t){return Kn(t)}const BF=(t,e)=>tt(t.innerType._def,e),zF=(t,e,n)=>{switch(e){case U.ZodString:return OI(t,n);case U.ZodNumber:return OF(t,n);case U.ZodObject:return $F(t,n);case U.ZodBigInt:return hF(t,n);case U.ZodBoolean:return fF();case U.ZodDate:return CI(t,n);case U.ZodUndefined:return UF(n);case U.ZodNull:return xF(n);case U.ZodArray:return dF(t,n);case U.ZodUnion:case U.ZodDiscriminatedUnion:return kF(t,n);case U.ZodIntersection:return bF(t,n);case U.ZodTuple:return DF(t,n);case U.ZodRecord:return $I(t,n);case U.ZodLiteral:return vF(t,n);case U.ZodEnum:return yF(t);case U.ZodNativeEnum:return EF(t);case U.ZodNullable:return CF(t,n);case U.ZodOptional:return NF(t,n);case U.ZodMap:return TF(t,n);case U.ZodSet:return jF(t,n);case U.ZodLazy:return()=>t.getter()._def;case U.ZodPromise:return LF(t,n);case U.ZodNaN:case U.ZodNever:return IF(n);case U.ZodEffects:return _F(t,n);case U.ZodAny:return Kn(n);case U.ZodUnknown:return FF(n);case U.ZodDefault:return gF(t,n);case U.ZodBranded:return kI(t,n);case U.ZodReadonly:return BF(t,n);case U.ZodCatch:return pF(t,n);case U.ZodPipeline:return MF(t,n);case U.ZodFunction:case U.ZodVoid:case U.ZodSymbol:return;default:return(r=>{})()}};function tt(t,e,n=!1){var o;const r=e.seen.get(t);if(e.override){const c=(o=e.override)==null?void 0:o.call(e,t,e,r,n);if(c!==NU)return c}if(r&&!n){const c=HF(r,e);if(c!==void 0)return c}const s={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,s);const i=zF(t,t.typeName,e),a=typeof i=="function"?tt(i(),e):i;if(a&&VF(t,e,a),e.postProcess){const c=e.postProcess(a,t,e);return s.jsonSchema=a,c}return s.jsonSchema=a,a}const HF=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:SI(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((n,r)=>e.currentPath[r]===n)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),Kn(e)):e.$refStrategy==="seen"?Kn(e):void 0}},VF=(t,e,n)=>(t.description&&(n.description=t.description,e.markdownDescription&&(n.markdownDescription=t.description)),n),KF=(t,e)=>{const n=jU(e);let r=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((o,[c,u])=>({...o,[c]:tt(u._def,{...n,currentPath:[...n.basePath,n.definitionPath,c]},!0)??Kn(n)}),{}):void 0;const s=typeof e=="string"?e:e==null?void 0:e.name,i=tt(t._def,n,!1)??Kn(n);n.flags.hasReferencedOpenAiAnyType&&(r||(r={}),r[n.openAiAnyTypeName]||(r[n.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:n.$refStrategy==="relative"?"1":[...n.basePath,n.definitionPath,n.openAiAnyTypeName].join("/")}}));const a=s===void 0?r?{...i,[n.definitionPath]:r}:i:{$ref:[...n.$refStrategy==="relative"?[]:n.basePath,n.definitionPath,s].join("/"),[n.definitionPath]:{...r,[s]:i}};return n.target==="jsonSchema7"?a.$schema="http://json-schema.org/draft-07/schema#":(n.target==="jsonSchema2019-09"||n.target==="openAi")&&(a.$schema="https://json-schema.org/draft/2019-09/schema#"),n.target==="openAi"&&("anyOf"in a||"oneOf"in a||"allOf"in a||"type"in a&&Array.isArray(a.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),a};var WF=de({isSerializableSchema:()=>Or,isStandardJsonSchema:()=>Oy,isStandardSchema:()=>RI});function RI(t){return(typeof t=="object"||typeof t=="function")&&t!==null&&"~standard"in t&&typeof t["~standard"]=="object"&&t["~standard"]!==null&&"validate"in t["~standard"]}function Oy(t){return(typeof t=="object"||typeof t=="function")&&t!==null&&"~standard"in t&&typeof t["~standard"]=="object"&&t["~standard"]!==null&&"jsonSchema"in t["~standard"]}function Or(t){return RI(t)&&Oy(t)}function ha(t,e){const n=typeof t;if(n!==typeof e)return!1;if(Array.isArray(t)){if(!Array.isArray(e))return!1;const r=t.length;if(r!==e.length)return!1;for(let s=0;s<r;s++)if(!ha(t[s],e[s]))return!1;return!0}if(n==="object"){if(!t||!e)return t===e;const r=Object.keys(t),s=Object.keys(e);if(r.length!==s.length)return!1;for(const a of r)if(!ha(t[a],e[a]))return!1;return!0}return t===e}function Fr(t){return encodeURI(ZF(t))}function ZF(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}const qF={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},GF={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},JF={id:!0,$id:!0,$ref:!0,$schema:!0,$anchor:!0,$vocabulary:!0,$comment:!0,default:!0,enum:!0,const:!0,required:!0,type:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};let YF=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 mi(t,e=Object.create(null),n=YF,r=""){if(t&&typeof t=="object"&&!Array.isArray(t)){const i=t.$id||t.id;if(i){const a=new URL(i,n.href);a.hash.length>1?e[a.href]=t:(a.hash="",r===""?n=a:mi(t,e,n))}}else if(t!==!0&&t!==!1)return e;const s=n.href+(r?"#"+r:"");if(e[s]!==void 0)throw new Error(`Duplicate schema URI "${s}".`);if(e[s]=t,t===!0||t===!1)return e;if(t.__absolute_uri__===void 0&&Object.defineProperty(t,"__absolute_uri__",{enumerable:!1,value:s}),t.$ref&&t.__absolute_ref__===void 0){const i=new URL(t.$ref,n.href);i.hash=i.hash,Object.defineProperty(t,"__absolute_ref__",{enumerable:!1,value:i.href})}if(t.$recursiveRef&&t.__absolute_recursive_ref__===void 0){const i=new URL(t.$recursiveRef,n.href);i.hash=i.hash,Object.defineProperty(t,"__absolute_recursive_ref__",{enumerable:!1,value:i.href})}if(t.$anchor){const i=new URL("#"+t.$anchor,n.href);e[i.href]=t}for(let i in t){if(JF[i])continue;const a=`${r}/${Fr(i)}`,o=t[i];if(Array.isArray(o)){if(qF[i]){const c=o.length;for(let u=0;u<c;u++)mi(o[u],e,n,`${a}/${u}`)}}else if(GF[i])for(let c in o)mi(o[c],e,n,`${a}/${Fr(c)}`);else mi(o,e,n,a)}return e}const XF=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,QF=[0,31,28,31,30,31,30,31,31,30,31,30,31],e6=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,t6=/^(?=.{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,n6=/^(?:[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,r6=/^(?:(?:[^\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,s6=/^(?:(?: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,i6=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,a6=/^(?:\/(?:[^~/]|~0|~1)*)*$/,o6=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,c6=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,u6=t=>{if(t[0]==='"')return!1;const[e,n,...r]=t.split("@");return!e||!n||r.length!==0||e.length>64||n.length>253||e[0]==="."||e.endsWith(".")||e.includes("..")||!/^[a-z0-9.-]+$/i.test(n)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(e)?!1:n.split(".").every(s=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(s))},l6=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,d6=/^((([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,h6=t=>t.length>1&&t.length<80&&(/^P\d+([.,]\d+)?W$/.test(t)||/^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(t)&&/^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(t));function ts(t){return t.test.bind(t)}const hv={date:PI,time:NI.bind(void 0,!1),"date-time":m6,duration:h6,uri:y6,"uri-reference":ts(n6),"uri-template":ts(r6),url:ts(s6),email:u6,hostname:ts(t6),ipv4:ts(l6),ipv6:ts(d6),regex:b6,uuid:ts(i6),"json-pointer":ts(a6),"json-pointer-uri-fragment":ts(o6),"relative-json-pointer":ts(c6)};function f6(t){return t%4===0&&(t%100!==0||t%400===0)}function PI(t){const e=t.match(XF);if(!e)return!1;const n=+e[1],r=+e[2],s=+e[3];return r>=1&&r<=12&&s>=1&&s<=(r==2&&f6(n)?29:QF[r])}function NI(t,e){const n=e.match(e6);if(!n)return!1;const r=+n[1],s=+n[2],i=+n[3],a=!!n[5];return(r<=23&&s<=59&&i<=59||r==23&&s==59&&i==60)&&(!t||a)}const p6=/t|\s/i;function m6(t){const e=t.split(p6);return e.length==2&&PI(e[0])&&NI(!0,e[1])}const g6=/\/|:/,_6=/^(?:[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 y6(t){return g6.test(t)&&_6.test(t)}const w6=/[^\\]\\Z/;function b6(t){if(w6.test(t))return!1;try{return new RegExp(t,"u"),!0}catch{return!1}}function v6(t){let e=0,n=t.length,r=0,s;for(;r<n;)e++,s=t.charCodeAt(r++),s>=55296&&s<=56319&&r<n&&(s=t.charCodeAt(r),(s&64512)==56320&&r++);return e}function St(t,e,n="2019-09",r=mi(e),s=!0,i=null,a="#",o="#",c=Object.create(null)){if(e===!0)return{valid:!0,errors:[]};if(e===!1)return{valid:!1,errors:[{instanceLocation:a,keyword:"false",keywordLocation:a,error:"False boolean schema."}]};const u=typeof t;let l;switch(u){case"boolean":case"number":case"string":l=u;break;case"object":t===null?l="null":Array.isArray(t)?l="array":l="object";break;default:throw new Error(`Instances of "${u}" type are not supported.`)}const{$ref:d,$recursiveRef:f,$recursiveAnchor:h,type:p,const:g,enum:y,required:b,not:_,anyOf:w,allOf:v,oneOf:A,if:S,then:x,else:E,format:$,properties:k,patternProperties:C,additionalProperties:D,unevaluatedProperties:B,minProperties:z,maxProperties:q,propertyNames:W,dependentRequired:me,dependentSchemas:M,dependencies:Z,prefixItems:re,items:ae,additionalItems:X,unevaluatedItems:se,contains:Se,minContains:ue,maxContains:I,minItems:T,maxItems:L,uniqueItems:O,minimum:ge,maximum:Ee,exclusiveMinimum:nt,exclusiveMaximum:We,multipleOf:lt,minLength:vt,maxLength:Pe,pattern:$t,__absolute_ref__:gn,__absolute_recursive_ref__:_r}=e,j=[];if(h===!0&&i===null&&(i=e),f==="#"){const Ae=i===null?r[_r]:i,be=`${o}/$recursiveRef`,Ie=St(t,i===null?e:i,n,r,s,Ae,a,be,c);Ie.valid||j.push({instanceLocation:a,keyword:"$recursiveRef",keywordLocation:be,error:"A subschema had errors."},...Ie.errors)}if(d!==void 0){const be=r[gn||d];if(be===void 0){let te=`Unresolved $ref "${d}".`;throw gn&&gn!==d&&(te+=` Absolute URI "${gn}".`),te+=`
|
|
113
|
-
Known schemas:
|
|
114
|
-
- ${Object.keys(r).join(`
|
|
115
|
-
- `)}`,new Error(te)}const Ie=`${o}/$ref`,ee=St(t,be,n,r,s,i,a,Ie,c);if(ee.valid||j.push({instanceLocation:a,keyword:"$ref",keywordLocation:Ie,error:"A subschema had errors."},...ee.errors),n==="4"||n==="7")return{valid:j.length===0,errors:j}}if(Array.isArray(p)){let Ae=p.length,be=!1;for(let Ie=0;Ie<Ae;Ie++)if(l===p[Ie]||p[Ie]==="integer"&&l==="number"&&t%1===0&&t===t){be=!0;break}be||j.push({instanceLocation:a,keyword:"type",keywordLocation:`${o}/type`,error:`Instance type "${l}" is invalid. Expected "${p.join('", "')}".`})}else p==="integer"?(l!=="number"||t%1||t!==t)&&j.push({instanceLocation:a,keyword:"type",keywordLocation:`${o}/type`,error:`Instance type "${l}" is invalid. Expected "${p}".`}):p!==void 0&&l!==p&&j.push({instanceLocation:a,keyword:"type",keywordLocation:`${o}/type`,error:`Instance type "${l}" is invalid. Expected "${p}".`});if(g!==void 0&&(l==="object"||l==="array"?ha(t,g)||j.push({instanceLocation:a,keyword:"const",keywordLocation:`${o}/const`,error:`Instance does not match ${JSON.stringify(g)}.`}):t!==g&&j.push({instanceLocation:a,keyword:"const",keywordLocation:`${o}/const`,error:`Instance does not match ${JSON.stringify(g)}.`})),y!==void 0&&(l==="object"||l==="array"?y.some(Ae=>ha(t,Ae))||j.push({instanceLocation:a,keyword:"enum",keywordLocation:`${o}/enum`,error:`Instance does not match any of ${JSON.stringify(y)}.`}):y.some(Ae=>t===Ae)||j.push({instanceLocation:a,keyword:"enum",keywordLocation:`${o}/enum`,error:`Instance does not match any of ${JSON.stringify(y)}.`})),_!==void 0){const Ae=`${o}/not`;St(t,_,n,r,s,i,a,Ae).valid&&j.push({instanceLocation:a,keyword:"not",keywordLocation:Ae,error:'Instance matched "not" schema.'})}let _n=[];if(w!==void 0){const Ae=`${o}/anyOf`,be=j.length;let Ie=!1;for(let ee=0;ee<w.length;ee++){const te=w[ee],Ce=Object.create(c),xe=St(t,te,n,r,s,h===!0?i:null,a,`${Ae}/${ee}`,Ce);j.push(...xe.errors),Ie=Ie||xe.valid,xe.valid&&_n.push(Ce)}Ie?j.length=be:j.splice(be,0,{instanceLocation:a,keyword:"anyOf",keywordLocation:Ae,error:"Instance does not match any subschemas."})}if(v!==void 0){const Ae=`${o}/allOf`,be=j.length;let Ie=!0;for(let ee=0;ee<v.length;ee++){const te=v[ee],Ce=Object.create(c),xe=St(t,te,n,r,s,h===!0?i:null,a,`${Ae}/${ee}`,Ce);j.push(...xe.errors),Ie=Ie&&xe.valid,xe.valid&&_n.push(Ce)}Ie?j.length=be:j.splice(be,0,{instanceLocation:a,keyword:"allOf",keywordLocation:Ae,error:"Instance does not match every subschema."})}if(A!==void 0){const Ae=`${o}/oneOf`,be=j.length,Ie=A.filter((ee,te)=>{const Ce=Object.create(c),xe=St(t,ee,n,r,s,h===!0?i:null,a,`${Ae}/${te}`,Ce);return j.push(...xe.errors),xe.valid&&_n.push(Ce),xe.valid}).length;Ie===1?j.length=be:j.splice(be,0,{instanceLocation:a,keyword:"oneOf",keywordLocation:Ae,error:`Instance does not match exactly one subschema (${Ie} matches).`})}if((l==="object"||l==="array")&&Object.assign(c,..._n),S!==void 0){const Ae=`${o}/if`;if(St(t,S,n,r,s,i,a,Ae,c).valid){if(x!==void 0){const Ie=St(t,x,n,r,s,i,a,`${o}/then`,c);Ie.valid||j.push({instanceLocation:a,keyword:"if",keywordLocation:Ae,error:'Instance does not match "then" schema.'},...Ie.errors)}}else if(E!==void 0){const Ie=St(t,E,n,r,s,i,a,`${o}/else`,c);Ie.valid||j.push({instanceLocation:a,keyword:"if",keywordLocation:Ae,error:'Instance does not match "else" schema.'},...Ie.errors)}}if(l==="object"){if(b!==void 0)for(const ee of b)ee in t||j.push({instanceLocation:a,keyword:"required",keywordLocation:`${o}/required`,error:`Instance does not have required property "${ee}".`});const Ae=Object.keys(t);if(z!==void 0&&Ae.length<z&&j.push({instanceLocation:a,keyword:"minProperties",keywordLocation:`${o}/minProperties`,error:`Instance does not have at least ${z} properties.`}),q!==void 0&&Ae.length>q&&j.push({instanceLocation:a,keyword:"maxProperties",keywordLocation:`${o}/maxProperties`,error:`Instance does not have at least ${q} properties.`}),W!==void 0){const ee=`${o}/propertyNames`;for(const te in t){const Ce=`${a}/${Fr(te)}`,xe=St(te,W,n,r,s,i,Ce,ee);xe.valid||j.push({instanceLocation:a,keyword:"propertyNames",keywordLocation:ee,error:`Property name "${te}" does not match schema.`},...xe.errors)}}if(me!==void 0){const ee=`${o}/dependantRequired`;for(const te in me)if(te in t){const Ce=me[te];for(const xe of Ce)xe in t||j.push({instanceLocation:a,keyword:"dependentRequired",keywordLocation:ee,error:`Instance has "${te}" but does not have "${xe}".`})}}if(M!==void 0)for(const ee in M){const te=`${o}/dependentSchemas`;if(ee in t){const Ce=St(t,M[ee],n,r,s,i,a,`${te}/${Fr(ee)}`,c);Ce.valid||j.push({instanceLocation:a,keyword:"dependentSchemas",keywordLocation:te,error:`Instance has "${ee}" but does not match dependant schema.`},...Ce.errors)}}if(Z!==void 0){const ee=`${o}/dependencies`;for(const te in Z)if(te in t){const Ce=Z[te];if(Array.isArray(Ce))for(const xe of Ce)xe in t||j.push({instanceLocation:a,keyword:"dependencies",keywordLocation:ee,error:`Instance has "${te}" but does not have "${xe}".`});else{const xe=St(t,Ce,n,r,s,i,a,`${ee}/${Fr(te)}`);xe.valid||j.push({instanceLocation:a,keyword:"dependencies",keywordLocation:ee,error:`Instance has "${te}" but does not match dependant schema.`},...xe.errors)}}}const be=Object.create(null);let Ie=!1;if(k!==void 0){const ee=`${o}/properties`;for(const te in k){if(!(te in t))continue;const Ce=`${a}/${Fr(te)}`,xe=St(t[te],k[te],n,r,s,i,Ce,`${ee}/${Fr(te)}`);if(xe.valid)c[te]=be[te]=!0;else if(Ie=s,j.push({instanceLocation:a,keyword:"properties",keywordLocation:ee,error:`Property "${te}" does not match schema.`},...xe.errors),Ie)break}}if(!Ie&&C!==void 0){const ee=`${o}/patternProperties`;for(const te in C){const Ce=new RegExp(te,"u"),xe=C[te];for(const Q in t){if(!Ce.test(Q))continue;const He=`${a}/${Fr(Q)}`,dt=St(t[Q],xe,n,r,s,i,He,`${ee}/${Fr(te)}`);dt.valid?c[Q]=be[Q]=!0:(Ie=s,j.push({instanceLocation:a,keyword:"patternProperties",keywordLocation:ee,error:`Property "${Q}" matches pattern "${te}" but does not match associated schema.`},...dt.errors))}}}if(!Ie&&D!==void 0){const ee=`${o}/additionalProperties`;for(const te in t){if(be[te])continue;const Ce=`${a}/${Fr(te)}`,xe=St(t[te],D,n,r,s,i,Ce,ee);xe.valid?c[te]=!0:(Ie=s,j.push({instanceLocation:a,keyword:"additionalProperties",keywordLocation:ee,error:`Property "${te}" does not match additional properties schema.`},...xe.errors))}}else if(!Ie&&B!==void 0){const ee=`${o}/unevaluatedProperties`;for(const te in t)if(!c[te]){const Ce=`${a}/${Fr(te)}`,xe=St(t[te],B,n,r,s,i,Ce,ee);xe.valid?c[te]=!0:j.push({instanceLocation:a,keyword:"unevaluatedProperties",keywordLocation:ee,error:`Property "${te}" does not match unevaluated properties schema.`},...xe.errors)}}}else if(l==="array"){L!==void 0&&t.length>L&&j.push({instanceLocation:a,keyword:"maxItems",keywordLocation:`${o}/maxItems`,error:`Array has too many items (${t.length} > ${L}).`}),T!==void 0&&t.length<T&&j.push({instanceLocation:a,keyword:"minItems",keywordLocation:`${o}/minItems`,error:`Array has too few items (${t.length} < ${T}).`});const Ae=t.length;let be=0,Ie=!1;if(re!==void 0){const ee=`${o}/prefixItems`,te=Math.min(re.length,Ae);for(;be<te;be++){const Ce=St(t[be],re[be],n,r,s,i,`${a}/${be}`,`${ee}/${be}`);if(c[be]=!0,!Ce.valid&&(Ie=s,j.push({instanceLocation:a,keyword:"prefixItems",keywordLocation:ee,error:"Items did not match schema."},...Ce.errors),Ie))break}}if(ae!==void 0){const ee=`${o}/items`;if(Array.isArray(ae)){const te=Math.min(ae.length,Ae);for(;be<te;be++){const Ce=St(t[be],ae[be],n,r,s,i,`${a}/${be}`,`${ee}/${be}`);if(c[be]=!0,!Ce.valid&&(Ie=s,j.push({instanceLocation:a,keyword:"items",keywordLocation:ee,error:"Items did not match schema."},...Ce.errors),Ie))break}}else for(;be<Ae;be++){const te=St(t[be],ae,n,r,s,i,`${a}/${be}`,ee);if(c[be]=!0,!te.valid&&(Ie=s,j.push({instanceLocation:a,keyword:"items",keywordLocation:ee,error:"Items did not match schema."},...te.errors),Ie))break}if(!Ie&&X!==void 0){const te=`${o}/additionalItems`;for(;be<Ae;be++){const Ce=St(t[be],X,n,r,s,i,`${a}/${be}`,te);c[be]=!0,Ce.valid||(Ie=s,j.push({instanceLocation:a,keyword:"additionalItems",keywordLocation:te,error:"Items did not match additional items schema."},...Ce.errors))}}}if(Se!==void 0)if(Ae===0&&ue===void 0)j.push({instanceLocation:a,keyword:"contains",keywordLocation:`${o}/contains`,error:"Array is empty. It must contain at least one item matching the schema."});else if(ue!==void 0&&Ae<ue)j.push({instanceLocation:a,keyword:"minContains",keywordLocation:`${o}/minContains`,error:`Array has less items (${Ae}) than minContains (${ue}).`});else{const ee=`${o}/contains`,te=j.length;let Ce=0;for(let xe=0;xe<Ae;xe++){const Q=St(t[xe],Se,n,r,s,i,`${a}/${xe}`,ee);Q.valid?(c[xe]=!0,Ce++):j.push(...Q.errors)}Ce>=(ue||0)&&(j.length=te),ue===void 0&&I===void 0&&Ce===0?j.splice(te,0,{instanceLocation:a,keyword:"contains",keywordLocation:ee,error:"Array does not contain item matching schema."}):ue!==void 0&&Ce<ue?j.push({instanceLocation:a,keyword:"minContains",keywordLocation:`${o}/minContains`,error:`Array must contain at least ${ue} items matching schema. Only ${Ce} items were found.`}):I!==void 0&&Ce>I&&j.push({instanceLocation:a,keyword:"maxContains",keywordLocation:`${o}/maxContains`,error:`Array may contain at most ${I} items matching schema. ${Ce} items were found.`})}if(!Ie&&se!==void 0){const ee=`${o}/unevaluatedItems`;for(be;be<Ae;be++){if(c[be])continue;const te=St(t[be],se,n,r,s,i,`${a}/${be}`,ee);c[be]=!0,te.valid||j.push({instanceLocation:a,keyword:"unevaluatedItems",keywordLocation:ee,error:"Items did not match unevaluated items schema."},...te.errors)}}if(O)for(let ee=0;ee<Ae;ee++){const te=t[ee],Ce=typeof te=="object"&&te!==null;for(let xe=0;xe<Ae;xe++){if(ee===xe)continue;const Q=t[xe];(te===Q||Ce&&(typeof Q=="object"&&Q!==null)&&ha(te,Q))&&(j.push({instanceLocation:a,keyword:"uniqueItems",keywordLocation:`${o}/uniqueItems`,error:`Duplicate items at indexes ${ee} and ${xe}.`}),ee=Number.MAX_SAFE_INTEGER,xe=Number.MAX_SAFE_INTEGER)}}}else if(l==="number"){if(n==="4"?(ge!==void 0&&(nt===!0&&t<=ge||t<ge)&&j.push({instanceLocation:a,keyword:"minimum",keywordLocation:`${o}/minimum`,error:`${t} is less than ${nt?"or equal to ":""} ${ge}.`}),Ee!==void 0&&(We===!0&&t>=Ee||t>Ee)&&j.push({instanceLocation:a,keyword:"maximum",keywordLocation:`${o}/maximum`,error:`${t} is greater than ${We?"or equal to ":""} ${Ee}.`})):(ge!==void 0&&t<ge&&j.push({instanceLocation:a,keyword:"minimum",keywordLocation:`${o}/minimum`,error:`${t} is less than ${ge}.`}),Ee!==void 0&&t>Ee&&j.push({instanceLocation:a,keyword:"maximum",keywordLocation:`${o}/maximum`,error:`${t} is greater than ${Ee}.`}),nt!==void 0&&t<=nt&&j.push({instanceLocation:a,keyword:"exclusiveMinimum",keywordLocation:`${o}/exclusiveMinimum`,error:`${t} is less than ${nt}.`}),We!==void 0&&t>=We&&j.push({instanceLocation:a,keyword:"exclusiveMaximum",keywordLocation:`${o}/exclusiveMaximum`,error:`${t} is greater than or equal to ${We}.`})),lt!==void 0){const Ae=t%lt;Math.abs(0-Ae)>=11920929e-14&&Math.abs(lt-Ae)>=11920929e-14&&j.push({instanceLocation:a,keyword:"multipleOf",keywordLocation:`${o}/multipleOf`,error:`${t} is not a multiple of ${lt}.`})}}else if(l==="string"){const Ae=vt===void 0&&Pe===void 0?0:v6(t);vt!==void 0&&Ae<vt&&j.push({instanceLocation:a,keyword:"minLength",keywordLocation:`${o}/minLength`,error:`String is too short (${Ae} < ${vt}).`}),Pe!==void 0&&Ae>Pe&&j.push({instanceLocation:a,keyword:"maxLength",keywordLocation:`${o}/maxLength`,error:`String is too long (${Ae} > ${Pe}).`}),$t!==void 0&&!new RegExp($t,"u").test(t)&&j.push({instanceLocation:a,keyword:"pattern",keywordLocation:`${o}/pattern`,error:"String does not match pattern."}),$!==void 0&&hv[$]&&!hv[$](t)&&j.push({instanceLocation:a,keyword:"format",keywordLocation:`${o}/format`,error:`String does not match format "${$}".`})}return{valid:j.length===0,errors:j}}class S6{constructor(e,n="2019-09",r=!0){m(this,"schema");m(this,"draft");m(this,"shortCircuit");m(this,"lookup");this.schema=e,this.draft=n,this.shortCircuit=r,this.lookup=mi(e)}validate(e){return St(e,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(e,n){n&&(e={...e,$id:n}),mi(e,this.lookup)}}var A6=de({Validator:()=>S6,deepCompareStrict:()=>ha,toJsonSchema:()=>mt,validatesOnlyStrings:()=>cu});const fv=new WeakMap;function mt(t,e){const n=!e&&t!=null&&typeof t=="object";if(n){const s=fv.get(t);if(s)return s}let r;if(Oy(t)&&!bt(t))r=t["~standard"].jsonSchema.input({target:"draft-07"});else if(bt(t)){const s=bI(t,!0);ys(s)?r=yg(Oh(s,!0),e):r=yg(t,e)}else Lt(t)?r=KF(t):r=t;return n&&r!=null&&typeof r=="object"&&fv.set(t,r),r}function cu(t){if(!t||typeof t!="object"||Object.keys(t).length===0||Array.isArray(t))return!1;if("type"in t)return typeof t.type=="string"?t.type==="string":Array.isArray(t.type)?t.type.every(e=>e==="string"):!1;if("enum"in t)return Array.isArray(t.enum)&&t.enum.length>0&&t.enum.every(e=>typeof e=="string");if("const"in t)return typeof t.const=="string";if("allOf"in t&&Array.isArray(t.allOf))return t.allOf.some(e=>cu(e));if("anyOf"in t&&Array.isArray(t.anyOf)||"oneOf"in t&&Array.isArray(t.oneOf)){const e="anyOf"in t?t.anyOf:t.oneOf;return e.length>0&&e.every(n=>cu(n))}if("not"in t)return!1;if("$ref"in t&&typeof t.$ref=="string"){const e=t.$ref,n=mi(t);return n[e]?cu(n[e]):!1}return!1}var T6=de({Graph:()=>$u});function E6(t,e){if(t!==void 0&&!ru(t))return t;if(wy(e))try{let n=e.getName();return n=n.startsWith("Runnable")?n.slice(8):n,n}catch{return e.getName()}else return e.name??"UnknownSchema"}function I6(t){return wy(t.data)?{type:"runnable",data:{id:t.data.lc_id,name:t.data.getName()}}:{type:"schema",data:{...mt(t.data.schema),title:t.data.name}}}var $u=class MI{constructor(e){m(this,"nodes",{});m(this,"edges",[]);this.nodes=(e==null?void 0:e.nodes)??this.nodes,this.edges=(e==null?void 0:e.edges)??this.edges}toJSON(){const e={};return Object.values(this.nodes).forEach((n,r)=>{e[n.id]=ru(n.id)?r:n.id}),{nodes:Object.values(this.nodes).map(n=>({id:e[n.id],...I6(n)})),edges:this.edges.map(n=>{const r={source:e[n.source],target:e[n.target]};return typeof n.data<"u"&&(r.data=n.data),typeof n.conditional<"u"&&(r.conditional=n.conditional),r})}}addNode(e,n,r){if(n!==void 0&&this.nodes[n]!==void 0)throw new Error(`Node with id ${n} already exists`);const s=n??pl(),i={id:s,data:e,name:E6(n,e),metadata:r};return this.nodes[s]=i,i}removeNode(e){delete this.nodes[e.id],this.edges=this.edges.filter(n=>n.source!==e.id&&n.target!==e.id)}addEdge(e,n,r,s){if(this.nodes[e.id]===void 0)throw new Error(`Source node ${e.id} not in graph`);if(this.nodes[n.id]===void 0)throw new Error(`Target node ${n.id} not in graph`);const i={source:e.id,target:n.id,data:r,conditional:s};return this.edges.push(i),i}firstNode(){return pv(this)}lastNode(){return mv(this)}extend(e,n=""){let r=n;Object.values(e.nodes).map(c=>c.id).every(ru)&&(r="");const s=c=>r?`${r}:${c}`:c;Object.entries(e.nodes).forEach(([c,u])=>{this.nodes[s(c)]={...u,id:s(c)}});const i=e.edges.map(c=>({...c,source:s(c.source),target:s(c.target)}));this.edges=[...this.edges,...i];const a=e.firstNode(),o=e.lastNode();return[a?{id:s(a.id),data:a.data}:void 0,o?{id:s(o.id),data:o.data}:void 0]}trimFirstNode(){const e=this.firstNode();e&&pv(this,[e.id])&&this.removeNode(e)}trimLastNode(){const e=this.lastNode();e&&mv(this,[e.id])&&this.removeNode(e)}reid(){const e=Object.fromEntries(Object.values(this.nodes).map(s=>[s.id,s.name])),n=new Map;Object.values(e).forEach(s=>{n.set(s,(n.get(s)||0)+1)});const r=s=>{const i=e[s];return ru(s)&&n.get(i)===1?i:s};return new MI({nodes:Object.fromEntries(Object.entries(this.nodes).map(([s,i])=>[r(s),{...i,id:r(s)}])),edges:this.edges.map(s=>({...s,source:r(s.source),target:r(s.target)}))})}drawMermaid(e){const{withStyles:n,curveStyle:r,nodeColors:s={default:"fill:#f2f0ff,line-height:1.2",first:"fill-opacity:0",last:"fill:#bfb6fc"},wrapLabelNWords:i}=e??{},a=this.reid(),o=a.firstNode(),c=a.lastNode();return RU(a.nodes,a.edges,{firstNode:o==null?void 0:o.id,lastNode:c==null?void 0:c.id,withStyles:n,curveStyle:r,nodeColors:s,wrapLabelNWords:i})}async drawMermaidPng(e){return PU(this.drawMermaid(e),{backgroundColor:e==null?void 0:e.backgroundColor})}};function pv(t,e=[]){const n=new Set(t.edges.filter(s=>!e.includes(s.source)).map(s=>s.target)),r=[];for(const s of Object.values(t.nodes))!e.includes(s.id)&&!n.has(s.id)&&r.push(s);return r.length===1?r[0]:void 0}function mv(t,e=[]){const n=new Set(t.edges.filter(s=>!e.includes(s.target)).map(s=>s.source)),r=[];for(const s of Object.values(t.nodes))!e.includes(s.id)&&!n.has(s.id)&&r.push(s);return r.length===1?r[0]:void 0}function x6(t){const e=new TextEncoder,n=new ReadableStream({async start(r){for await(const s of t)r.enqueue(e.encode(`event: data
|
|
116
|
-
data: ${JSON.stringify(s)}
|
|
117
|
-
|
|
118
|
-
`));r.enqueue(e.encode(`event: end
|
|
119
|
-
|
|
120
|
-
`)),r.close()}});return Vn.fromReadableStream(n)}function gv(t){return typeof t=="object"&&t!==null&&typeof t[Symbol.iterator]=="function"&&typeof t.next=="function"}const k6=t=>t!=null&&typeof t=="object"&&"next"in t&&typeof t.next=="function";function $g(t){return typeof t=="object"&&t!==null&&typeof t[Symbol.asyncIterator]=="function"}function LI(t){return t!=null&&typeof t=="object"&&typeof t.next=="function"}async function C6(t,e){var n;try{let r=await t.next();for(;!r.done;)await(e==null?void 0:e(r.value)),r=await t.next();return r.value}finally{await((n=t.return)==null?void 0:n.call(t,void 0))}}function*_v(t,e){for(;;){const{value:n,done:r}=pn.runWithConfig(Hs(t),e.next.bind(e),!0);if(r)break;yield n}}async function*Rg(t,e){const n=e[Symbol.asyncIterator]();for(;;){const{value:r,done:s}=await pn.runWithConfig(Hs(t),n.next.bind(e),!0);if(s)break;yield r}}function Kt(t,e){return t&&!Array.isArray(t)&&!(t instanceof Date)&&typeof t=="object"?t:{[e]:t}}var ze=class extends xr{constructor(){super(...arguments);m(this,"lc_runnable",!0);m(this,"name")}getName(e){const n=this.name??this.constructor.lc_name()??this.constructor.name;return e?`${n}${e}`:n}withRetry(e){return new $y({bound:this,kwargs:{},config:{},maxAttemptNumber:e==null?void 0:e.stopAfterAttempt,...e})}withConfig(e){return new dn({bound:this,config:e,kwargs:{}})}withFallbacks(e){const n=Array.isArray(e)?e:e.fallbacks;return new zI({runnable:this,fallbacks:n})}_getOptionsList(e,n=0){if(Array.isArray(e)&&e.length!==n)throw new Error(`Passed "options" must be an array with the same length as the inputs, but got ${e.length} options for ${n} inputs`);if(Array.isArray(e))return e.map(Je);if(n>1&&!Array.isArray(e)&&e.runId){console.warn("Provided runId will be used only for the first element of the batch.");const r=Object.fromEntries(Object.entries(e).filter(([s])=>s!=="runId"));return Array.from({length:n},(s,i)=>Je(i===0?e:r))}return Array.from({length:n},()=>Je(e))}async batch(e,n,r){var o;const s=this._getOptionsList(n??{},e.length),i=new _l({maxConcurrency:((o=s[0])==null?void 0:o.maxConcurrency)??(r==null?void 0:r.maxConcurrency),onFailedAttempt:c=>{throw c}}),a=e.map((c,u)=>i.call(async()=>{try{return await this.invoke(c,s[u])}catch(l){if(r!=null&&r.returnExceptions)return l;throw l}}));return Promise.all(a)}async*_streamIterator(e,n){yield this.invoke(e,n)}async stream(e,n){const r=Je(n),s=new ka({generator:this._streamIterator(e,r),config:r});return await s.setup,Vn.fromAsyncGenerator(s)}_separateRunnableConfigFromCallOptions(e){let n;e===void 0?n=Je(e):n=Je({callbacks:e.callbacks,tags:e.tags,metadata:e.metadata,runName:e.runName,configurable:e.configurable,recursionLimit:e.recursionLimit,maxConcurrency:e.maxConcurrency,runId:e.runId,timeout:e.timeout,signal:e.signal});const r={...e};return delete r.callbacks,delete r.tags,delete r.metadata,delete r.runName,delete r.configurable,delete r.recursionLimit,delete r.maxConcurrency,delete r.runId,delete r.timeout,delete r.signal,[n,r]}async _callWithConfig(e,n,r){var o;const s=Je(r),i=await((o=await ur(s))==null?void 0:o.handleChainStart(this.toJSON(),Kt(n,"input"),s.runId,s==null?void 0:s.runType,void 0,void 0,(s==null?void 0:s.runName)??this.getName()));delete s.runId;let a;try{a=await Ss(e.call(this,n,s,i),s.signal)}catch(c){throw await(i==null?void 0:i.handleChainError(c)),c}return await(i==null?void 0:i.handleChainEnd(Kt(a,"output"))),a}async _batchWithConfig(e,n,r,s){var u;const i=this._getOptionsList(r??{},n.length),a=await Promise.all(i.map(ur)),o=await Promise.all(a.map(async(l,d)=>{const f=await(l==null?void 0:l.handleChainStart(this.toJSON(),Kt(n[d],"input"),i[d].runId,i[d].runType,void 0,void 0,i[d].runName??this.getName()));return delete i[d].runId,f}));let c;try{c=await Ss(e.call(this,n,i,o,s),(u=i==null?void 0:i[0])==null?void 0:u.signal)}catch(l){throw await Promise.all(o.map(d=>d==null?void 0:d.handleChainError(l))),l}return await Promise.all(o.map(l=>l==null?void 0:l.handleChainEnd(Kt(c,"output")))),c}_concatOutputChunks(e,n){return Vs(e,n)}async*_transformStreamWithConfig(e,n,r){let s,i=!0,a,o=!0;const c=Je(r),u=await ur(c),l=this;async function*d(){for await(const h of e){if(i)if(s===void 0)s=h;else try{s=l._concatOutputChunks(s,h)}catch{s=void 0,i=!1}yield h}}let f;try{const h=await NE(n.bind(this),d(),async()=>u==null?void 0:u.handleChainStart(this.toJSON(),{input:""},c.runId,c.runType,void 0,void 0,c.runName??this.getName(),void 0,{lc_defers_inputs:!0}),c.signal,c);delete c.runId,f=h.setup;const p=f==null?void 0:f.handlers.find(Aj);let g=h.output;p!==void 0&&f!==void 0&&(g=p.tapOutputIterable(f.runId,g));const y=f==null?void 0:f.handlers.find(jE);y!==void 0&&f!==void 0&&(g=y.tapOutputIterable(f.runId,g));for await(const b of g)if(yield b,o)if(a===void 0)a=b;else try{a=this._concatOutputChunks(a,b)}catch{a=void 0,o=!1}}catch(h){throw await(f==null?void 0:f.handleChainError(h,void 0,void 0,void 0,{inputs:Kt(s,"input")})),h}await(f==null?void 0:f.handleChainEnd(a??{},void 0,void 0,void 0,{inputs:Kt(s,"input")}))}getGraph(e){const n=new $u,r=n.addNode({name:`${this.getName()}Input`,schema:cv()}),s=n.addNode(this),i=n.addNode({name:`${this.getName()}Output`,schema:cv()});return n.addEdge(r,s),n.addEdge(s,i),n}pipe(e){return new fr({first:this,last:hn(e)})}pick(e){return this.pipe(new HI(e))}assign(e){return this.pipe(new Ry(new Yo({steps:e})))}async*transform(e,n){let r;for await(const s of e)r===void 0?r=s:r=this._concatOutputChunks(r,s);yield*this._streamIterator(r,Je(n))}async*streamLog(e,n,r){const s=new mg({...r,autoClose:!1,_schemaFormat:"original"}),i=Je(n);yield*this._streamLog(e,s,i)}async*_streamLog(e,n,r){const{callbacks:s}=r;if(s===void 0)r.callbacks=[n];else if(Array.isArray(s))r.callbacks=s.concat([n]);else{const c=s.copy();c.addHandler(n,!0),r.callbacks=c}const i=this.stream(e,r);async function a(){try{const c=await i;for await(const u of c){const l=new Ms({ops:[{op:"add",path:"/streamed_output/-",value:u}]});await n.writer.write(l)}}finally{await n.writer.close()}}const o=a();try{for await(const c of n)yield c}finally{await o}}streamEvents(e,n,r){let s;if(n.version==="v1")s=this._streamEventsV1(e,n,r);else if(n.version==="v2")s=this._streamEventsV2(e,n,r);else throw new Error('Only versions "v1" and "v2" of the schema are currently supported.');return n.encoding==="text/event-stream"?x6(s):Vn.fromAsyncGenerator(s)}async*_streamEventsV2(e,n,r){var p;const s=new Tj({...r,autoClose:!1}),i=Je(n),a=i.runId??Ps();i.runId=a;const o=i.callbacks;if(o===void 0)i.callbacks=[s];else if(Array.isArray(o))i.callbacks=o.concat(s);else{const g=o.copy();g.addHandler(s,!0),i.callbacks=g}const c=new AbortController,u=this;async function l(){let g;try{if(i.signal)if("any"in AbortSignal)g=AbortSignal.any([c.signal,i.signal]);else{const _=new AbortController;i.signal.addEventListener("abort",()=>_.abort(),{once:!0}),c.signal.addEventListener("abort",()=>_.abort(),{once:!0}),g=_.signal}else g=c.signal;const y=await u.stream(e,{...i,signal:g}),b=s.tapOutputIterable(a,y);for await(const _ of b)if(c.signal.aborted)break}finally{await s.finish()}}const d=l();let f=!1,h;try{for await(const g of s){if(!f){g.data.input=e,f=!0,h=g.run_id,yield g;continue}g.run_id===h&&g.event.endsWith("_end")&&(p=g.data)!=null&&p.input&&delete g.data.input,yield g}}finally{c.abort(),await d}}async*_streamEventsV1(e,n,r){let s,i=!1;const a=Je(n),o=a.tags??[],c=a.metadata??{},u=a.runName??this.getName(),l=new mg({...r,autoClose:!1,_schemaFormat:"streaming_events"}),d=new Lj({...r}),f=this._streamLog(e,l,a);for await(const p of f){if(s?s=s.concat(p):s=yy.fromRunLogPatch(p),s.state===void 0)throw new Error('Internal error: "streamEvents" state is missing. Please open a bug report.');if(!i){i=!0;const _={...s.state},w={run_id:_.id,event:`on_${_.type}_start`,name:u,tags:o,metadata:c,data:{input:e}};d.includeEvent(w,_.type)&&(yield w)}const g=p.ops.filter(_=>_.path.startsWith("/logs/")).map(_=>_.path.split("/")[2]),y=[...new Set(g)];for(const _ of y){let w,v={};const A=s.state.logs[_];if(A.end_time===void 0?A.streamed_output.length>0?w="stream":w="start":w="end",w==="start")A.inputs!==void 0&&(v.input=A.inputs);else if(w==="end")A.inputs!==void 0&&(v.input=A.inputs),v.output=A.final_output;else if(w==="stream"){const S=A.streamed_output.length;if(S!==1)throw new Error(`Expected exactly one chunk of streamed output, got ${S} instead. Encountered in: "${A.name}"`);v={chunk:A.streamed_output[0]},A.streamed_output=[]}yield{event:`on_${A.type}_${w}`,name:A.name,run_id:A.id,tags:A.tags,metadata:A.metadata,data:v}}const{state:b}=s;if(b.streamed_output.length>0){const _=b.streamed_output.length;if(_!==1)throw new Error(`Expected exactly one chunk of streamed output, got ${_} instead. Encountered in: "${b.name}"`);const w={chunk:b.streamed_output[0]};b.streamed_output=[];const v={event:`on_${b.type}_stream`,run_id:b.id,tags:o,metadata:c,name:u,data:w};d.includeEvent(v,b.type)&&(yield v)}}const h=s==null?void 0:s.state;if(h!==void 0){const p={event:`on_${h.type}_end`,name:u,run_id:h.id,tags:o,metadata:c,data:{output:h.final_output}};d.includeEvent(p,h.type)&&(yield p)}}static isRunnable(e){return wy(e)}withListeners({onStart:e,onEnd:n,onError:r}){return new dn({bound:this,config:{},configFactories:[s=>({callbacks:[new FE({config:s,onStart:e,onEnd:n,onError:r})]})]})}asTool(e){return N6(this,e)}},dn=class jI extends ze{constructor(n){super(n);m(this,"lc_namespace",["langchain_core","runnables"]);m(this,"lc_serializable",!0);m(this,"bound");m(this,"config");m(this,"kwargs");m(this,"configFactories");this.bound=n.bound,this.kwargs=n.kwargs,this.config=n.config,this.configFactories=n.configFactories}static lc_name(){return"RunnableBinding"}getName(n){return this.bound.getName(n)}async _mergeConfig(...n){const r=ir(this.config,...n);return ir(r,...this.configFactories?await Promise.all(this.configFactories.map(async s=>await s(r))):[])}withConfig(n){return new this.constructor({bound:this.bound,kwargs:this.kwargs,config:{...this.config,...n}})}withRetry(n){return new $y({bound:this.bound,kwargs:this.kwargs,config:this.config,maxAttemptNumber:n==null?void 0:n.stopAfterAttempt,...n})}async invoke(n,r){return this.bound.invoke(n,await this._mergeConfig(r,this.kwargs))}async batch(n,r,s){const i=Array.isArray(r)?await Promise.all(r.map(async a=>this._mergeConfig(Je(a),this.kwargs))):await this._mergeConfig(Je(r),this.kwargs);return this.bound.batch(n,i,s)}_concatOutputChunks(n,r){return this.bound._concatOutputChunks(n,r)}async*_streamIterator(n,r){yield*this.bound._streamIterator(n,await this._mergeConfig(Je(r),this.kwargs))}async stream(n,r){return this.bound.stream(n,await this._mergeConfig(Je(r),this.kwargs))}async*transform(n,r){yield*this.bound.transform(n,await this._mergeConfig(Je(r),this.kwargs))}streamEvents(n,r,s){const i=this,a=async function*(){yield*i.bound.streamEvents(n,{...await i._mergeConfig(Je(r),i.kwargs),version:r.version},s)};return Vn.fromAsyncGenerator(a())}static isRunnableBinding(n){return n.bound&&ze.isRunnable(n.bound)}withListeners({onStart:n,onEnd:r,onError:s}){return new jI({bound:this.bound,kwargs:this.kwargs,config:this.config,configFactories:[i=>({callbacks:[new FE({config:i,onStart:n,onEnd:r,onError:s})]})]})}},O6=class DI extends ze{constructor(n){super(n);m(this,"lc_serializable",!0);m(this,"lc_namespace",["langchain_core","runnables"]);m(this,"bound");this.bound=n.bound}static lc_name(){return"RunnableEach"}async invoke(n,r){return this._callWithConfig(this._invoke.bind(this),n,r)}async _invoke(n,r,s){return this.bound.batch(n,et(r,{callbacks:s==null?void 0:s.getChild()}))}withListeners({onStart:n,onEnd:r,onError:s}){return new DI({bound:this.bound.withListeners({onStart:n,onEnd:r,onError:s})})}},$y=class extends dn{constructor(e){super(e);m(this,"lc_namespace",["langchain_core","runnables"]);m(this,"maxAttemptNumber",3);m(this,"onFailedAttempt",()=>{});this.maxAttemptNumber=e.maxAttemptNumber??this.maxAttemptNumber,this.onFailedAttempt=e.onFailedAttempt??this.onFailedAttempt}static lc_name(){return"RunnableRetry"}_patchConfigForRetry(e,n,r){const s=e>1?`retry:attempt:${e}`:void 0;return et(n,{callbacks:r==null?void 0:r.getChild(s)})}async _invoke(e,n,r){return gg(s=>super.invoke(e,this._patchConfigForRetry(s,n,r)),{onFailedAttempt:({error:s})=>this.onFailedAttempt(s,e),retries:Math.max(this.maxAttemptNumber-1,0),randomize:!0})}async invoke(e,n){return this._callWithConfig(this._invoke.bind(this),e,n)}async _batch(e,n,r,s){const i={};try{await gg(async a=>{const o=e.map((f,h)=>h).filter(f=>i[f.toString()]===void 0||i[f.toString()]instanceof Error),c=o.map(f=>e[f]),u=o.map(f=>this._patchConfigForRetry(a,n==null?void 0:n[f],r==null?void 0:r[f])),l=await super.batch(c,u,{...s,returnExceptions:!0});let d;for(let f=0;f<l.length;f+=1){const h=l[f],p=o[f];h instanceof Error&&d===void 0&&(d=h,d.input=c[f]),i[p.toString()]=h}if(d)throw d;return l},{onFailedAttempt:({error:a})=>this.onFailedAttempt(a,a.input),retries:Math.max(this.maxAttemptNumber-1,0),randomize:!0})}catch(a){if((s==null?void 0:s.returnExceptions)!==!0)throw a}return Object.keys(i).sort((a,o)=>parseInt(a,10)-parseInt(o,10)).map(a=>i[parseInt(a,10)])}async batch(e,n,r){return this._batchWithConfig(this._batch.bind(this),e,n,r)}},fr=class jc extends ze{constructor(n){super(n);m(this,"first");m(this,"middle",[]);m(this,"last");m(this,"omitSequenceTags",!1);m(this,"lc_serializable",!0);m(this,"lc_namespace",["langchain_core","runnables"]);this.first=n.first,this.middle=n.middle??this.middle,this.last=n.last,this.name=n.name,this.omitSequenceTags=n.omitSequenceTags??this.omitSequenceTags}static lc_name(){return"RunnableSequence"}get steps(){return[this.first,...this.middle,this.last]}async invoke(n,r){var c,u;const s=Je(r),i=await((c=await ur(s))==null?void 0:c.handleChainStart(this.toJSON(),Kt(n,"input"),s.runId,void 0,void 0,void 0,s==null?void 0:s.runName));delete s.runId;let a=n,o;try{const l=[this.first,...this.middle];for(let d=0;d<l.length;d+=1)a=await Ss(l[d].invoke(a,et(s,{callbacks:i==null?void 0:i.getChild(this.omitSequenceTags?void 0:`seq:step:${d+1}`)})),s.signal);if((u=s.signal)!=null&&u.aborted)throw Au(s.signal);o=await this.last.invoke(a,et(s,{callbacks:i==null?void 0:i.getChild(this.omitSequenceTags?void 0:`seq:step:${this.steps.length}`)}))}catch(l){throw await(i==null?void 0:i.handleChainError(l)),l}return await(i==null?void 0:i.handleChainEnd(Kt(o,"output"))),o}async batch(n,r,s){var u;const i=this._getOptionsList(r??{},n.length),a=await Promise.all(i.map(ur)),o=await Promise.all(a.map(async(l,d)=>{const f=await(l==null?void 0:l.handleChainStart(this.toJSON(),Kt(n[d],"input"),i[d].runId,void 0,void 0,void 0,i[d].runName));return delete i[d].runId,f}));let c=n;try{for(let l=0;l<this.steps.length;l+=1)c=await Ss(this.steps[l].batch(c,o.map((d,f)=>{const h=d==null?void 0:d.getChild(this.omitSequenceTags?void 0:`seq:step:${l+1}`);return et(i[f],{callbacks:h})}),s),(u=i[0])==null?void 0:u.signal)}catch(l){throw await Promise.all(o.map(d=>d==null?void 0:d.handleChainError(l))),l}return await Promise.all(o.map(l=>l==null?void 0:l.handleChainEnd(Kt(c,"output")))),c}_concatOutputChunks(n,r){return this.last._concatOutputChunks(n,r)}async*_streamIterator(n,r){var f;const s=await ur(r),{runId:i,...a}=r??{},o=await(s==null?void 0:s.handleChainStart(this.toJSON(),Kt(n,"input"),i,void 0,void 0,void 0,a==null?void 0:a.runName)),c=[this.first,...this.middle,this.last];let u=!0,l;async function*d(){yield n}try{let h=c[0].transform(d(),et(a,{callbacks:o==null?void 0:o.getChild(this.omitSequenceTags?void 0:"seq:step:1")}));for(let p=1;p<c.length;p+=1)h=await c[p].transform(h,et(a,{callbacks:o==null?void 0:o.getChild(this.omitSequenceTags?void 0:`seq:step:${p+1}`)}));for await(const p of h)if((f=r==null?void 0:r.signal)==null||f.throwIfAborted(),yield p,u)if(l===void 0)l=p;else try{l=this._concatOutputChunks(l,p)}catch{l=void 0,u=!1}}catch(h){throw await(o==null?void 0:o.handleChainError(h)),h}await(o==null?void 0:o.handleChainEnd(Kt(l,"output")))}getGraph(n){const r=new $u;let s=null;return this.steps.forEach((i,a)=>{const o=i.getGraph(n);a!==0&&o.trimFirstNode(),a!==this.steps.length-1&&o.trimLastNode(),r.extend(o);const c=o.firstNode();if(!c)throw new Error(`Runnable ${i} has no first node`);s&&r.addEdge(s,c),s=o.lastNode()}),r}pipe(n){return jc.isRunnableSequence(n)?new jc({first:this.first,middle:this.middle.concat([this.last,n.first,...n.middle]),last:n.last,name:this.name??n.name}):new jc({first:this.first,middle:[...this.middle,this.last],last:hn(n),name:this.name})}static isRunnableSequence(n){return Array.isArray(n.middle)&&ze.isRunnable(n)}static from([n,...r],s){let i={};return typeof s=="string"?i.name=s:s!==void 0&&(i=s),new jc({...i,first:hn(n),middle:r.slice(0,-1).map(hn),last:hn(r[r.length-1])})}},Yo=class UI extends ze{constructor(n){super(n);m(this,"lc_namespace",["langchain_core","runnables"]);m(this,"lc_serializable",!0);m(this,"steps");this.steps={};for(const[r,s]of Object.entries(n.steps))this.steps[r]=hn(s)}static lc_name(){return"RunnableMap"}getStepsKeys(){return Object.keys(this.steps)}static from(n){return new UI({steps:n})}async invoke(n,r){var o;const s=Je(r),i=await((o=await ur(s))==null?void 0:o.handleChainStart(this.toJSON(),{input:n},s.runId,void 0,void 0,void 0,s==null?void 0:s.runName));delete s.runId;const a={};try{const c=Object.entries(this.steps).map(async([u,l])=>{a[u]=await l.invoke(n,et(s,{callbacks:i==null?void 0:i.getChild(`map:key:${u}`)}))});await Ss(Promise.all(c),s.signal)}catch(c){throw await(i==null?void 0:i.handleChainError(c)),c}return await(i==null?void 0:i.handleChainEnd(a)),a}async*_transform(n,r,s){const i={...this.steps},a=_y(n,Object.keys(i).length),o=new Map(Object.entries(i).map(([c,u],l)=>{const d=u.transform(a[l],et(s,{callbacks:r==null?void 0:r.getChild(`map:key:${c}`)}));return[c,d.next().then(f=>({key:c,gen:d,result:f}))]}));for(;o.size;){const{key:c,result:u,gen:l}=await Ss(Promise.race(o.values()),s==null?void 0:s.signal);o.delete(c),u.done||(yield{[c]:u.value},o.set(c,l.next().then(d=>({key:c,gen:l,result:d}))))}}transform(n,r){return this._transformStreamWithConfig(n,this._transform.bind(this),r)}async stream(n,r){async function*s(){yield n}const i=Je(r),a=new ka({generator:this.transform(s(),i),config:i});return await a.setup,Vn.fromAsyncGenerator(a)}},$6=class FI extends ze{constructor(n){super(n);m(this,"lc_serializable",!1);m(this,"lc_namespace",["langchain_core","runnables"]);m(this,"func");if(!my(n.func))throw new Error("RunnableTraceable requires a function that is wrapped in traceable higher-order function");this.func=n.func}async invoke(n,r){const[s]=this._getOptionsList(r??{},1),i=await ur(s);return Ss(this.func(et(s,{callbacks:i}),n),s==null?void 0:s.signal)}async*_streamIterator(n,r){var a,o;const[s]=this._getOptionsList(r??{},1),i=await this.invoke(n,r);if($g(i)){for await(const c of i)(a=s==null?void 0:s.signal)==null||a.throwIfAborted(),yield c;return}if(k6(i)){for(;;){(o=s==null?void 0:s.signal)==null||o.throwIfAborted();const c=i.next();if(c.done)break;yield c.value}return}yield i}static from(n){return new FI({func:n})}};function R6(t){if(my(t))throw new Error("RunnableLambda requires a function that is not wrapped in traceable higher-order function. This shouldn't happen.")}var en=class BI extends ze{constructor(n){if(my(n.func))return $6.from(n.func);super(n);m(this,"lc_namespace",["langchain_core","runnables"]);m(this,"func");R6(n.func),this.func=n.func}static lc_name(){return"RunnableLambda"}static from(n){return new BI({func:n})}async _invoke(n,r,s){return new Promise((i,a)=>{const o=et(r,{callbacks:s==null?void 0:s.getChild(),recursionLimit:((r==null?void 0:r.recursionLimit)??25)-1});pn.runWithConfig(Hs(o),async()=>{var c,u;try{let l=await this.func(n,{...o});if(l&&ze.isRunnable(l)){if((r==null?void 0:r.recursionLimit)===0)throw new Error("Recursion limit reached.");l=await l.invoke(n,{...o,recursionLimit:(o.recursionLimit??25)-1})}else if($g(l)){let d;for await(const f of Rg(o,l))if((c=r==null?void 0:r.signal)==null||c.throwIfAborted(),d===void 0)d=f;else try{d=this._concatOutputChunks(d,f)}catch{d=f}l=d}else if(gv(l)){let d;for(const f of _v(o,l))if((u=r==null?void 0:r.signal)==null||u.throwIfAborted(),d===void 0)d=f;else try{d=this._concatOutputChunks(d,f)}catch{d=f}l=d}i(l)}catch(l){a(l)}})})}async invoke(n,r){return this._callWithConfig(this._invoke.bind(this),n,r)}async*_transform(n,r,s){var c,u;let i;for await(const l of n)if(i===void 0)i=l;else try{i=this._concatOutputChunks(i,l)}catch{i=l}const a=et(s,{callbacks:r==null?void 0:r.getChild(),recursionLimit:((s==null?void 0:s.recursionLimit)??25)-1}),o=await new Promise((l,d)=>{pn.runWithConfig(Hs(a),async()=>{try{l(await this.func(i,{...a,config:a}))}catch(f){d(f)}})});if(o&&ze.isRunnable(o)){if((s==null?void 0:s.recursionLimit)===0)throw new Error("Recursion limit reached.");const l=await o.stream(i,a);for await(const d of l)yield d}else if($g(o))for await(const l of Rg(a,o))(c=s==null?void 0:s.signal)==null||c.throwIfAborted(),yield l;else if(gv(o))for(const l of _v(a,o))(u=s==null?void 0:s.signal)==null||u.throwIfAborted(),yield l;else yield o}transform(n,r){return this._transformStreamWithConfig(n,this._transform.bind(this),r)}async stream(n,r){async function*s(){yield n}const i=Je(r),a=new ka({generator:this.transform(s(),i),config:i});return await a.setup,Vn.fromAsyncGenerator(a)}},P6=class extends Yo{},zI=class extends ze{constructor(e){super(e);m(this,"lc_namespace",["langchain_core","runnables"]);m(this,"lc_serializable",!0);m(this,"runnable");m(this,"fallbacks");this.runnable=e.runnable,this.fallbacks=e.fallbacks}static lc_name(){return"RunnableWithFallbacks"}*runnables(){yield this.runnable;for(const e of this.fallbacks)yield e}async invoke(e,n){const r=Je(n),s=await ur(r),{runId:i,...a}=r,o=await(s==null?void 0:s.handleChainStart(this.toJSON(),Kt(e,"input"),i,void 0,void 0,void 0,a==null?void 0:a.runName)),c=et(a,{callbacks:o==null?void 0:o.getChild()});return await pn.runWithConfig(c,async()=>{var l;let u;for(const d of this.runnables()){(l=r==null?void 0:r.signal)==null||l.throwIfAborted();try{const f=await d.invoke(e,c);return await(o==null?void 0:o.handleChainEnd(Kt(f,"output"))),f}catch(f){u===void 0&&(u=f)}}throw u===void 0?new Error("No error stored at end of fallback."):(await(o==null?void 0:o.handleChainError(u)),u)})}async*_streamIterator(e,n){var d;const r=Je(n),s=await ur(r),{runId:i,...a}=r,o=await(s==null?void 0:s.handleChainStart(this.toJSON(),Kt(e,"input"),i,void 0,void 0,void 0,a==null?void 0:a.runName));let c,u;for(const f of this.runnables()){(d=r==null?void 0:r.signal)==null||d.throwIfAborted();const h=et(a,{callbacks:o==null?void 0:o.getChild()});try{u=Rg(h,await f.stream(e,h));break}catch(p){c===void 0&&(c=p)}}if(u===void 0){const f=c??new Error("No error stored at end of fallback.");throw await(o==null?void 0:o.handleChainError(f)),f}let l;try{for await(const f of u){yield f;try{l=l===void 0?l:this._concatOutputChunks(l,f)}catch{l=void 0}}}catch(f){throw await(o==null?void 0:o.handleChainError(f)),f}await(o==null?void 0:o.handleChainEnd(Kt(l,"output")))}async batch(e,n,r){var c;if(r!=null&&r.returnExceptions)throw new Error("Not implemented.");const s=this._getOptionsList(n??{},e.length),i=await Promise.all(s.map(u=>ur(u))),a=await Promise.all(i.map(async(u,l)=>{const d=await(u==null?void 0:u.handleChainStart(this.toJSON(),Kt(e[l],"input"),s[l].runId,void 0,void 0,void 0,s[l].runName));return delete s[l].runId,d}));let o;for(const u of this.runnables()){(c=s[0].signal)==null||c.throwIfAborted();try{const l=await u.batch(e,a.map((d,f)=>et(s[f],{callbacks:d==null?void 0:d.getChild()})),r);return await Promise.all(a.map((d,f)=>d==null?void 0:d.handleChainEnd(Kt(l[f],"output")))),l}catch(l){o===void 0&&(o=l)}}throw o?(await Promise.all(a.map(u=>u==null?void 0:u.handleChainError(o))),o):new Error("No error stored at end of fallbacks.")}};function hn(t){if(typeof t=="function")return new en({func:t});if(ze.isRunnable(t))return t;if(!Array.isArray(t)&&typeof t=="object"){const e={};for(const[n,r]of Object.entries(t))e[n]=hn(r);return new Yo({steps:e})}else throw new Error(`Expected a Runnable, function or object.
|
|
121
|
-
Instead got an unsupported type.`)}var Ry=class extends ze{constructor(e){e instanceof Yo&&(e={mapper:e});super(e);m(this,"lc_namespace",["langchain_core","runnables"]);m(this,"lc_serializable",!0);m(this,"mapper");this.mapper=e.mapper}static lc_name(){return"RunnableAssign"}async invoke(e,n){const r=await this.mapper.invoke(e,n);return{...e,...r}}async*_transform(e,n,r){const s=this.mapper.getStepsKeys(),[i,a]=_y(e),o=this.mapper.transform(a,et(r,{callbacks:n==null?void 0:n.getChild()})),c=o.next();for await(const u of i){if(typeof u!="object"||Array.isArray(u))throw new Error(`RunnableAssign can only be used with objects as input, got ${typeof u}`);const l=Object.fromEntries(Object.entries(u).filter(([d])=>!s.includes(d)));Object.keys(l).length>0&&(yield l)}yield(await c).value;for await(const u of o)yield u}transform(e,n){return this._transformStreamWithConfig(e,this._transform.bind(this),n)}async stream(e,n){async function*r(){yield e}const s=Je(n),i=new ka({generator:this.transform(r(),s),config:s});return await i.setup,Vn.fromAsyncGenerator(i)}},HI=class extends ze{constructor(e){(typeof e=="string"||Array.isArray(e))&&(e={keys:e});super(e);m(this,"lc_namespace",["langchain_core","runnables"]);m(this,"lc_serializable",!0);m(this,"keys");this.keys=e.keys}static lc_name(){return"RunnablePick"}async _pick(e){if(typeof this.keys=="string")return e[this.keys];{const n=this.keys.map(r=>[r,e[r]]).filter(r=>r[1]!==void 0);return n.length===0?void 0:Object.fromEntries(n)}}async invoke(e,n){return this._callWithConfig(this._pick.bind(this),e,n)}async*_transform(e){for await(const n of e){const r=await this._pick(n);r!==void 0&&(yield r)}}transform(e,n){return this._transformStreamWithConfig(e,this._transform.bind(this),n)}async stream(e,n){async function*r(){yield e}const s=Je(n),i=new ka({generator:this.transform(r(),s),config:s});return await i.setup,Vn.fromAsyncGenerator(i)}},Pg=class extends dn{constructor(e){const n=fr.from([en.from(async r=>{let s;if(nu(r))try{s=await kf(this.schema,r.args)}catch{throw new gh("Received tool input did not match expected schema",JSON.stringify(r.args))}else s=r;return s}).withConfig({runName:`${e.name}:parse_input`}),e.bound]).withConfig({runName:e.name});super({bound:n,config:e.config??{}});m(this,"name");m(this,"description");m(this,"schema");this.name=e.name,this.description=e.description,this.schema=e.schema}static lc_name(){return"RunnableToolLike"}};function N6(t,e){const n=e.name??t.getName(),r=e.description??jo(e.schema);return xy(e.schema)?new Pg({name:n,description:r,schema:Vr({input:tr()}).transform(s=>s.input),bound:t}):new Pg({name:n,description:r,schema:e.schema,bound:t})}var Ru=class extends ze{constructor(e){super(e);m(this,"lc_namespace",["langchain_core","runnables"]);m(this,"lc_serializable",!0);m(this,"func");e&&(this.func=e.func)}static lc_name(){return"RunnablePassthrough"}async invoke(e,n){const r=Je(n);return this.func&&await this.func(e,r),this._callWithConfig(s=>Promise.resolve(s),e,r)}async*transform(e,n){const r=Je(n);let s,i=!0;for await(const a of this._transformStreamWithConfig(e,o=>o,r))if(yield a,i)if(s===void 0)s=a;else try{s=Vs(s,a)}catch{s=void 0,i=!1}this.func&&s!==void 0&&await this.func(s,r)}static assign(e){return new Ry(new Yo({steps:e}))}},M6=class extends ze{constructor(e){super(e);m(this,"lc_namespace",["langchain_core","runnables"]);m(this,"lc_serializable",!0);m(this,"runnables");this.runnables=e.runnables}static lc_name(){return"RouterRunnable"}async invoke(e,n){const{key:r,input:s}=e,i=this.runnables[r];if(i===void 0)throw new Error(`No runnable associated with key "${r}".`);return i.invoke(s,Je(n))}async batch(e,n,r){var d;const s=e.map(f=>f.key),i=e.map(f=>f.input);if(s.find(f=>this.runnables[f]===void 0)!==void 0)throw new Error("One or more keys do not have a corresponding runnable.");const a=s.map(f=>this.runnables[f]),o=this._getOptionsList(n??{},e.length),c=((d=o[0])==null?void 0:d.maxConcurrency)??(r==null?void 0:r.maxConcurrency),u=c&&c>0?c:e.length,l=[];for(let f=0;f<i.length;f+=u){const h=i.slice(f,f+u).map((g,y)=>a[y].invoke(g,o[y])),p=await Promise.all(h);l.push(p)}return l.flat()}async stream(e,n){const{key:r,input:s}=e,i=this.runnables[r];if(i===void 0)throw new Error(`No runnable associated with key "${r}".`);return i.stream(s,n)}},L6=class extends ze{constructor(e){super(e);m(this,"lc_namespace",["langchain_core","runnables"]);m(this,"lc_serializable",!0);m(this,"default");m(this,"branches");this.branches=e.branches,this.default=e.default}static lc_name(){return"RunnableBranch"}static from(e){if(e.length<1)throw new Error("RunnableBranch requires at least one branch");const n=e.slice(0,-1).map(([s,i])=>[hn(s),hn(i)]),r=hn(e[e.length-1]);return new this({branches:n,default:r})}async _invoke(e,n,r){let s;for(let i=0;i<this.branches.length;i+=1){const[a,o]=this.branches[i];if(await a.invoke(e,et(n,{callbacks:r==null?void 0:r.getChild(`condition:${i+1}`)}))){s=await o.invoke(e,et(n,{callbacks:r==null?void 0:r.getChild(`branch:${i+1}`)}));break}}return s||(s=await this.default.invoke(e,et(n,{callbacks:r==null?void 0:r.getChild("branch:default")}))),s}async invoke(e,n={}){return this._callWithConfig(this._invoke,e,n)}async*_streamIterator(e,n){var o;const r=await((o=await ur(n))==null?void 0:o.handleChainStart(this.toJSON(),Kt(e,"input"),n==null?void 0:n.runId,void 0,void 0,void 0,n==null?void 0:n.runName));let s,i=!0,a;try{for(let c=0;c<this.branches.length;c+=1){const[u,l]=this.branches[c];if(await u.invoke(e,et(n,{callbacks:r==null?void 0:r.getChild(`condition:${c+1}`)}))){a=await l.stream(e,et(n,{callbacks:r==null?void 0:r.getChild(`branch:${c+1}`)}));for await(const d of a)if(yield d,i)if(s===void 0)s=d;else try{s=Vs(s,d)}catch{s=void 0,i=!1}break}}if(a===void 0){a=await this.default.stream(e,et(n,{callbacks:r==null?void 0:r.getChild("branch:default")}));for await(const c of a)if(yield c,i)if(s===void 0)s=c;else try{s=Vs(s,c)}catch{s=void 0,i=!1}}}catch(c){throw await(r==null?void 0:r.handleChainError(c)),c}await(r==null?void 0:r.handleChainEnd(s??{}))}};const jh=(t,e)=>{const n=[...new Set(e==null?void 0:e.map(s=>{if(typeof s=="string")return s;const i=new s({});if(!("getType"in i)||typeof i.getType!="function")throw new Error("Invalid type provided.");return i.getType()}))],r=t.getType();return n.some(s=>s===r)};function j6(t,e){return Array.isArray(t)?yv(t,e):en.from(n=>yv(n,t))}function yv(t,e={}){const{includeNames:n,excludeNames:r,includeTypes:s,excludeTypes:i,includeIds:a,excludeIds:o}=e,c=[];for(const u of t)if(!(r&&u.name&&r.includes(u.name))){{if(i&&jh(u,i))continue;if(o&&u.id&&o.includes(u.id))continue}s||a||n?(n&&u.name&&n.some(l=>l===u.name)||s&&jh(u,s)||a&&u.id&&a.some(l=>l===u.id))&&c.push(u):c.push(u)}return c}function D6(t){return Array.isArray(t)?wv(t):en.from(wv)}function wv(t){if(!t.length)return[];const e=[];for(const n of t){const r=n,s=e.pop();if(!s)e.push(r);else if(r.getType()==="tool"||r.getType()!==s.getType())e.push(s,r);else{const i=wh(s),a=wh(r),o=i.concat(a);typeof i.content=="string"&&typeof a.content=="string"&&(o.content=`${i.content}
|
|
122
|
-
${a.content}`),e.push(B6(o))}}return e}function U6(t,e){if(Array.isArray(t)){const n=t;if(!e)throw new Error("Options parameter is required when providing messages.");return bv(n,e)}else{const n=t;return en.from(r=>bv(r,n)).withConfig({runName:"trim_messages"})}}async function bv(t,e){const{maxTokens:n,tokenCounter:r,strategy:s="last",allowPartial:i=!1,endOn:a,startOn:o,includeSystem:c=!1,textSplitter:u}=e;if(o&&s==="first")throw new Error("`startOn` should only be specified if `strategy` is 'last'.");if(c&&s==="first")throw new Error("`includeSystem` should only be specified if `strategy` is 'last'.");let l;"getNumTokens"in r?l=async f=>(await Promise.all(f.map(h=>r.getNumTokens(h.content)))).reduce((h,p)=>h+p,0):l=async f=>r(f);let d=KI;if(u&&("splitText"in u?d=u.splitText:d=async f=>u(f)),s==="first")return VI(t,{maxTokens:n,tokenCounter:l,textSplitter:d,partialStrategy:i?"first":void 0,endOn:a});if(s==="last")return F6(t,{maxTokens:n,tokenCounter:l,textSplitter:d,allowPartial:i,includeSystem:c,startOn:o,endOn:a});throw new Error(`Unrecognized strategy: '${s}'. Must be one of 'first' or 'last'.`)}async function VI(t,e){var u;const{maxTokens:n,tokenCounter:r,textSplitter:s,partialStrategy:i,endOn:a}=e;let o=[...t],c=0;for(let l=0;l<o.length;l+=1)if(await r(l>0?o.slice(0,-l):o)<=n){c=o.length-l;break}if(c<o.length&&i){let l=!1;if(Array.isArray(o[c].content)){const d=o[c];if(typeof d.content=="string")throw new Error("Expected content to be an array.");const f=d.content.length,h=i==="last"?[...d.content].reverse():d.content;for(let p=1;p<=f;p+=1){const g=i==="first"?h.slice(0,p):h.slice(-p),y=Object.fromEntries(Object.entries(d).filter(([w])=>w!=="type"&&!w.startsWith("lc_"))),b=Py(d.getType(),{...y,content:g}),_=[...o.slice(0,c),b];if(await r(_)<=n)o=_,c+=1,l=!0;else break}l&&i==="last"&&(d.content=[...h].reverse())}if(!l){const d=o[c];let f;if(Array.isArray(d.content)&&d.content.some(h=>typeof h=="string"||h.type==="text")?f=(u=d.content.find(h=>h.type==="text"&&h.text))==null?void 0:u.text:typeof d.content=="string"&&(f=d.content),f){const h=await s(f),p=h.length;i==="last"&&h.reverse();for(let g=0;g<p-1;g+=1)if(h.pop(),d.content=h.join(""),await r([...o.slice(0,c),d])<=n){i==="last"&&(d.content=[...h].reverse().join("")),o=[...o.slice(0,c),d],c+=1;break}}}}if(a){const l=Array.isArray(a)?a:[a];for(;c>0&&!jh(o[c-1],l);)c-=1}return o.slice(0,c)}async function F6(t,e){var l;const{allowPartial:n=!1,includeSystem:r=!1,endOn:s,startOn:i,...a}=e;let o=t.map(d=>{const f=Object.fromEntries(Object.entries(d).filter(([h])=>h!=="type"&&!h.startsWith("lc_")));return Py(d.getType(),f,Po(d))});if(s){const d=Array.isArray(s)?s:[s];for(;o.length>0&&!jh(o[o.length-1],d);)o=o.slice(0,-1)}const c=r&&((l=o[0])==null?void 0:l.getType())==="system";let u=c?o.slice(0,1).concat(o.slice(1).reverse()):o.reverse();return u=await VI(u,{...a,partialStrategy:n?"last":void 0,endOn:i}),c?[u[0],...u.slice(1).reverse()]:u.reverse()}const vv={human:{message:Nn,messageChunk:fl},ai:{message:De,messageChunk:Ge},system:{message:lr,messageChunk:xi},developer:{message:lr,messageChunk:xi},tool:{message:fn,messageChunk:ll},function:{message:wf,messageChunk:hl},generic:{message:Ts,messageChunk:dl},remove:{message:ua,messageChunk:ua}};function Py(t,e,n){var i;let r,s;switch(t){case"human":n?r=new fl(e):s=new Nn(e);break;case"ai":if(n){let a={...e};"tool_calls"in a&&(a={...a,tool_call_chunks:(i=a.tool_calls)==null?void 0:i.map(o=>({...o,type:"tool_call_chunk",index:void 0,args:JSON.stringify(o.args)}))}),r=new Ge(a)}else s=new De(e);break;case"system":n?r=new xi(e):s=new lr(e);break;case"developer":n?r=new xi({...e,additional_kwargs:{...e.additional_kwargs,__openai_role__:"developer"}}):s=new lr({...e,additional_kwargs:{...e.additional_kwargs,__openai_role__:"developer"}});break;case"tool":if("tool_call_id"in e)n?r=new ll(e):s=new fn(e);else throw new Error("Can not convert ToolMessage to ToolMessageChunk if 'tool_call_id' field is not defined.");break;case"function":if(n)r=new hl(e);else{if(!e.name)throw new Error("FunctionMessage must have a 'name' field");s=new wf(e)}break;case"generic":if("role"in e)n?r=new dl(e):s=new Ts(e);else throw new Error("Can not convert ChatMessage to ChatMessageChunk if 'role' field is not defined.");break;default:throw new Error(`Unrecognized message type ${t}`)}if(n&&r)return r;if(s)return s;throw new Error(`Unrecognized message type ${t}`)}function B6(t){const e=t.getType();let n;const r=Object.fromEntries(Object.entries(t).filter(([s])=>!["type","tool_call_chunks"].includes(s)&&!s.startsWith("lc_")));if(e in vv&&(n=Py(e,r)),!n)throw new Error(`Unrecognized message chunk class ${e}. Supported classes are ${Object.keys(vv)}`);return n}function KI(t){const e=t.split(`
|
|
123
|
-
`);return Promise.resolve([...e.slice(0,-1).map(n=>`${n}
|
|
124
|
-
`),e[e.length-1]])}const z6=["tool_call","tool_call_chunk","invalid_tool_call","server_tool_call","server_tool_call_chunk","server_tool_call_result"],H6=["image","video","audio","text-plain","file"],V6=["text","reasoning",...z6,...H6];var K6=de({AIMessage:()=>De,AIMessageChunk:()=>Ge,BaseMessage:()=>Ot,BaseMessageChunk:()=>vs,ChatMessage:()=>Ts,ChatMessageChunk:()=>dl,DEFAULT_MERGE_IGNORE_KEYS:()=>kT,FunctionMessage:()=>wf,FunctionMessageChunk:()=>hl,HumanMessage:()=>Nn,HumanMessageChunk:()=>fl,KNOWN_BLOCK_TYPES:()=>V6,RemoveMessage:()=>ua,SystemMessage:()=>lr,SystemMessageChunk:()=>xi,ToolMessage:()=>fn,ToolMessageChunk:()=>ll,_isMessageFieldWithRole:()=>$T,_mergeDicts:()=>Sn,_mergeLists:()=>Ro,_mergeObj:()=>CT,_mergeStatus:()=>xT,coerceMessageLikeToMessage:()=>_s,collapseToolCallChunks:()=>DT,convertToChunk:()=>wh,convertToOpenAIImageBlock:()=>AT,convertToProviderContentBlock:()=>ul,defaultTextSplitter:()=>KI,defaultToolCallParser:()=>Q_,filterMessages:()=>j6,getBufferString:()=>ny,iife:()=>jT,isAIMessage:()=>Cr,isAIMessageChunk:()=>yh,isBase64ContentBlock:()=>G_,isBaseMessage:()=>Et,isBaseMessageChunk:()=>Po,isChatMessage:()=>FP,isChatMessageChunk:()=>BP,isDataContentBlock:()=>kr,isDirectToolOutput:()=>X_,isFunctionMessage:()=>zP,isFunctionMessageChunk:()=>HP,isHumanMessage:()=>VP,isHumanMessageChunk:()=>KP,isIDContentBlock:()=>ST,isMessage:()=>IT,isOpenAIToolCallArray:()=>vP,isPlainTextContentBlock:()=>sP,isSystemMessage:()=>WP,isSystemMessageChunk:()=>ZP,isToolMessage:()=>ca,isToolMessageChunk:()=>RT,isURLContentBlock:()=>q_,mapChatMessagesToStoredMessages:()=>eN,mapStoredMessageToChatMessage:()=>ry,mapStoredMessagesToChatMessages:()=>QP,mergeContent:()=>zs,mergeMessageRuns:()=>D6,mergeResponseMetadata:()=>NT,mergeUsageMetadata:()=>ty,parseBase64DataUrl:()=>Gr,parseMimeType:()=>Ym,trimMessages:()=>U6}),W6=class extends dn{constructor(e){let n=en.from((a,o)=>this._enterHistory(a,o??{})).withConfig({runName:"loadHistory"});const r=e.historyMessagesKey??e.inputMessagesKey;r&&(n=Ru.assign({[r]:n}).withConfig({runName:"insertHistory"}));const s=n.pipe(e.runnable.withListeners({onEnd:(a,o)=>this._exitHistory(a,o??{})})).withConfig({runName:"RunnableWithMessageHistory"}),i=e.config??{};super({...e,config:i,bound:s});m(this,"runnable");m(this,"inputMessagesKey");m(this,"outputMessagesKey");m(this,"historyMessagesKey");m(this,"getMessageHistory");this.runnable=e.runnable,this.getMessageHistory=e.getMessageHistory,this.inputMessagesKey=e.inputMessagesKey,this.outputMessagesKey=e.outputMessagesKey,this.historyMessagesKey=e.historyMessagesKey}_getInputMessages(e){let n;if(typeof e=="object"&&!Array.isArray(e)&&!Et(e)){let r;this.inputMessagesKey?r=this.inputMessagesKey:Object.keys(e).length===1?r=Object.keys(e)[0]:r="input",Array.isArray(e[r])&&Array.isArray(e[r][0])?n=e[r][0]:n=e[r]}else n=e;if(typeof n=="string")return[new Nn(n)];if(Array.isArray(n))return n;if(Et(n))return[n];throw new Error(`Expected a string, BaseMessage, or array of BaseMessages.
|
|
125
|
-
Got ${JSON.stringify(n,null,2)}`)}_getOutputMessages(e){let n;if(!Array.isArray(e)&&!Et(e)&&typeof e!="string"){let r;this.outputMessagesKey!==void 0?r=this.outputMessagesKey:Object.keys(e).length===1?r=Object.keys(e)[0]:r="output",e.generations!==void 0?n=e.generations[0][0].message:n=e[r]}else n=e;if(typeof n=="string")return[new De(n)];if(Array.isArray(n))return n;if(Et(n))return[n];throw new Error(`Expected a string, BaseMessage, or array of BaseMessages. Received: ${JSON.stringify(n,null,2)}`)}async _enterHistory(e,n){var s;const r=await((s=n==null?void 0:n.configurable)==null?void 0:s.messageHistory).getMessages();return this.historyMessagesKey===void 0?r.concat(this._getInputMessages(e)):r}async _exitHistory(e,n){var c;const r=(c=n.configurable)==null?void 0:c.messageHistory;let s;Array.isArray(e.inputs)&&Array.isArray(e.inputs[0])?s=e.inputs[0]:s=e.inputs;let i=this._getInputMessages(s);if(this.historyMessagesKey===void 0){const u=await r.getMessages();i=i.slice(u.length)}const a=e.outputs;if(!a)throw new Error(`Output values from 'Run' undefined. Run: ${JSON.stringify(e,null,2)}`);const o=this._getOutputMessages(a);await r.addMessages([...i,...o])}async _mergeConfig(...e){const n=await super._mergeConfig(...e);if(!n.configurable||!n.configurable.sessionId){const s={[this.inputMessagesKey??"input"]:"foo"};throw new Error(`sessionId is required. Pass it in as part of the config argument to .invoke() or .stream()
|
|
126
|
-
eg. chain.invoke(${JSON.stringify(s)}, ${JSON.stringify({configurable:{sessionId:"123"}})})`)}const{sessionId:r}=n.configurable;return n.configurable.messageHistory=await this.getMessageHistory(r),n}},Z6=de({RouterRunnable:()=>M6,Runnable:()=>ze,RunnableAssign:()=>Ry,RunnableBinding:()=>dn,RunnableBranch:()=>L6,RunnableEach:()=>O6,RunnableLambda:()=>en,RunnableMap:()=>Yo,RunnableParallel:()=>P6,RunnablePassthrough:()=>Ru,RunnablePick:()=>HI,RunnableRetry:()=>$y,RunnableSequence:()=>fr,RunnableToolLike:()=>Pg,RunnableWithFallbacks:()=>zI,RunnableWithMessageHistory:()=>W6,_coerceToRunnable:()=>hn,ensureConfig:()=>Je,getCallbackManagerForConfig:()=>ur,mergeConfigs:()=>ir,patchConfig:()=>et,pickRunnableConfigKeys:()=>Hs,raceWithSignal:()=>Ss});function Sv(t,e){if(t!=null){if(typeof t!="number"||Number.isNaN(t)||t<=0)throw new Error(`${e} must be greater than 0`);return t}}function Ng(t){if(t==null)return;const e=typeof t=="number"?{runTimeout:t}:t,n=e.refreshOn??"auto";if(n!=="auto"&&n!=="heartbeat")throw new Error('refreshOn must be "auto" or "heartbeat"');const r=Sv(e.runTimeout,"runTimeout"),s=Sv(e.idleTimeout,"idleTimeout");if(!(r===void 0&&s===void 0))return{runTimeout:r,idleTimeout:s,refreshOn:n}}var zp={};const un="__start__",ht="__end__",ui="__input__",bl="__error__",Ny="__error_source_node__",Hp="__pregel_ns_writes";function q6(){const t=typeof process<"u"?zp==null?void 0:zp.LANGGRAPH_DELTA_MAX_SUPERSTEPS_SINCE_SNAPSHOT:void 0;if(t!==void 0&&t!==""){const e=Number.parseInt(t,10);if(Number.isFinite(e)&&e>0)return e}return 5e3}const Jr="__pregel_send",Ho="__pregel_call",Ai="__pregel_read",ds="__pregel_checkpointer",uu="__pregel_resuming",lu="__pregel_task_id",My="__pregel_stream",G6="__pregel_resume_value",du="__pregel_resume_map",Bs="__pregel_scratchpad",hu="__pregel_previous",J6="__pregel_durability",Vi="checkpoint_id",us="checkpoint_ns",Y6="__pregel_node_finished",Mg="__pregel_node_error",sr="checkpoint_map",Lg="__pregel_replay_state",X6="__pregel_abort_signals",Nt="__interrupt__",ws="__resume__",Ly="__no_writes__",$f="__return__",Bd="__previous__",Hn="langsmith:hidden",Av="__self__",Vo="__pregel_tasks",Tr="__pregel_push",jg="__pregel_pull",Ar="00000000-0000-0000-0000-000000000000",Q6=[Hn,ui,Nt,ws,bl,Ny,Ly,Jr,Ai,ds,J6,My,uu,lu,Ho,G6,Bs,hu,sr,us,Vi,Lg],Tv=Symbol.for("langgraph.command");var rT,eB=(rT=Tv,class{constructor(t){m(this,rT);this[Tv]=t}});function Dg(t){const e=t;return e!=null&&typeof e.node=="string"&&e.args!==void 0}var wa=class{constructor(t,e,n){m(this,"lg_name","Send");m(this,"node");m(this,"args");m(this,"timeout");this.node=t,this.args=Nu(e),this.timeout=Ng(n==null?void 0:n.timeout)}toJSON(){return{lg_name:this.lg_name,node:this.node,args:this.args,timeout:this.timeout}}};function Wn(t){return t instanceof wa}const jy="__overwrite__";function Pu(t){return typeof t=="object"&&t!==null&&"__overwrite__"in t?[!0,t[jy]]:[!1,void 0]}function tB(t){return Pu(t)[0]}function Dy(t){return!t||typeof t!="object"||!("__interrupt__"in t)?!1:Array.isArray(t[Nt])}var Wm,ar=(Wm=class extends eB{constructor(e){super(e);m(this,"lg_name","Command");m(this,"lc_direct_tool_output",!0);m(this,"graph");m(this,"update");m(this,"resume");m(this,"goto",[]);this.resume=e.resume,this.graph=e.graph,this.update=e.update,e.goto&&(this.goto=Array.isArray(e.goto)?Nu(e.goto):[Nu(e.goto)])}_updateAsTuples(){return this.update&&typeof this.update=="object"&&!Array.isArray(this.update)?Object.entries(this.update):Array.isArray(this.update)&&this.update.every(e=>Array.isArray(e)&&e.length===2&&typeof e[0]=="string")?this.update:[["__root__",this.update]]}toJSON(){var n;let e;return typeof this.goto=="string"?e=this.goto:Wn(this.goto)?e=this.goto.toJSON():e=(n=this.goto)==null?void 0:n.map(r=>typeof r=="string"?r:r.toJSON()),{lg_name:this.lg_name,update:this.update,resume:this.resume,goto:e}}},m(Wm,"PARENT","__parent__"),Wm);function Xt(t){return typeof t!="object"||t==null?!1:"lg_name"in t&&t.lg_name==="Command"}function nB(t){const e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function Nu(t,e=new Map){if(t!=null&&typeof t=="object"){if(e.has(t))return e.get(t);let n;if(Array.isArray(t))n=[],e.set(t,n),t.forEach((r,s)=>{n[s]=Nu(r,e)});else if(t instanceof ar||t instanceof wa||!nB(t))n=t,e.set(t,n);else if(Xt(t))n=new ar(t),e.set(t,n);else if(Dg(t))n=new wa(t.node,t.args,t.timeout!==void 0?{timeout:t.timeout}:void 0),e.set(t,n);else if("lc_serializable"in t&&t.lc_serializable)n=t,e.set(t,n);else{n={},e.set(t,n);for(const[r,s]of Object.entries(t))n[r]=Nu(s,e)}return n}return t}var Js=class extends Error{constructor(e,n){let r=e??"";n!=null&&n.lc_error_code&&(r=`${r}
|
|
127
|
-
|
|
128
|
-
Troubleshooting URL: https://docs.langchain.com/oss/javascript/langgraph/${n.lc_error_code}/
|
|
129
|
-
`);super(r);m(this,"lc_error_code");this.lc_error_code=n==null?void 0:n.lc_error_code}},Uy=class extends Js{get is_bubble_up(){return!0}},rB=class extends Js{constructor(t,e){super(t,e),this.name="GraphRecursionError"}static get unminifiable_name(){return"GraphRecursionError"}},zd=class extends Js{constructor(t,e){super(t,e),this.name="GraphValueError"}static get unminifiable_name(){return"GraphValueError"}},WI=class extends Uy{constructor(e="shutdown",n){super(`Graph drained: ${e}`,n);m(this,"reason");this.name="GraphDrained",this.reason=e}static get unminifiable_name(){return"GraphDrained"}};function Ev(t){return t!==void 0&&t.name===WI.unminifiable_name}var fo=class extends Uy{constructor(e,n){super(JSON.stringify(e,null,2),n);m(this,"interrupts");this.name="GraphInterrupt",this.interrupts=e??[]}static get unminifiable_name(){return"GraphInterrupt"}},ZI=class extends fo{constructor(t,e){super([{value:t}],e),this.name="NodeInterrupt"}static get unminifiable_name(){return"NodeInterrupt"}},sB=class{constructor(t,e){m(this,"node");m(this,"error");this.node=t,this.error=e}static get unminifiable_name(){return"NodeError"}},qI=class extends Uy{constructor(e){super();m(this,"command");this.name="ParentCommand",this.command=e}static get unminifiable_name(){return"ParentCommand"}};function iB(t){return t!==void 0&&t.name===qI.unminifiable_name}function Dc(t){return t!==void 0&&t.is_bubble_up===!0}function Xi(t){return t!==void 0&&[fo.unminifiable_name,ZI.unminifiable_name].includes(t.name)}var aB=class extends Js{constructor(e,n){const{node:r,elapsed:s,kind:i,runTimeout:a,idleTimeout:o}=e;let c,u;if(i==="idle"){if(o===void 0)throw new Error("idleTimeout is required when kind='idle'");u=o,c=`Node "${r}" exceeded its idle timeout of ${o}ms without making progress (elapsed: ${s}ms).`}else{if(a===void 0)throw new Error("runTimeout is required when kind='run'");u=a,c=`Node "${r}" exceeded its run timeout of ${a}ms (elapsed: ${s}ms).`}super(c,n);m(this,"node");m(this,"kind");m(this,"timeout");m(this,"elapsed");m(this,"runTimeout");m(this,"idleTimeout");this.name="NodeTimeoutError",this.node=r,this.kind=i,this.timeout=u,this.elapsed=s,this.runTimeout=a,this.idleTimeout=o}static get unminifiable_name(){return"NodeTimeoutError"}},Iv=class extends Js{constructor(t,e){super(t,e),this.name="EmptyInputError"}static get unminifiable_name(){return"EmptyInputError"}},tn=class extends Js{constructor(t,e){const n=Error.stackTraceLimit;Error.stackTraceLimit=0,super(t,e),Error.stackTraceLimit=n,this.name="EmptyChannelError"}static get unminifiable_name(){return"EmptyChannelError"}},ft=class extends Js{constructor(t,e){super(t,e),this.name="InvalidUpdateError"}static get unminifiable_name(){return"InvalidUpdateError"}},oB=class extends Js{constructor(t,e){super(t,e),this.name="UnreachableNodeError"}static get unminifiable_name(){return"UnreachableNodeError"}},Vp=class extends Js{constructor(t,e){super(t,e),this.name="StateGraphInputError",this.message="Invalid StateGraph input. Make sure to pass a valid StateDefinition, Annotation.Root, or Zod schema."}static get unminifiable_name(){return"StateGraphInputError"}};const cB=/^(?:[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 uB(t){return typeof t=="string"&&cB.test(t)}function Ug(t){if(!uB(t))throw TypeError("Invalid UUID");let e;return Uint8Array.of((e=parseInt(t.slice(0,8),16))>>>24,e>>>16&255,e>>>8&255,e&255,(e=parseInt(t.slice(9,13),16))>>>8,e&255,(e=parseInt(t.slice(14,18),16))>>>8,e&255,(e=parseInt(t.slice(19,23),16))>>>8,e&255,(e=parseInt(t.slice(24,36),16))/1099511627776&255,e/4294967296&255,e>>>24&255,e>>>16&255,e>>>8&255,e&255)}const sn=[];for(let t=0;t<256;++t)sn.push((t+256).toString(16).slice(1));function Rf(t,e=0){return(sn[t[e+0]]+sn[t[e+1]]+sn[t[e+2]]+sn[t[e+3]]+"-"+sn[t[e+4]]+sn[t[e+5]]+"-"+sn[t[e+6]]+sn[t[e+7]]+"-"+sn[t[e+8]]+sn[t[e+9]]+"-"+sn[t[e+10]]+sn[t[e+11]]+sn[t[e+12]]+sn[t[e+13]]+sn[t[e+14]]+sn[t[e+15]]).toLowerCase()}const lB=new Uint8Array(16);function xv(){return crypto.getRandomValues(lB)}const lc={};function dB(t,e,n){var i;let r;const s=(t==null?void 0:t._v6)??!1;if(t){const a=Object.keys(t);a.length===1&&a[0]==="_v6"&&(t=void 0)}if(t)r=kv(t.random??((i=t.rng)==null?void 0:i.call(t))??xv(),t.msecs,t.nsecs,t.clockseq,t.node,e,n);else{const a=Date.now(),o=xv();hB(lc,a,o),r=kv(o,lc.msecs,lc.nsecs,s?void 0:lc.clockseq,s?void 0:lc.node,e,n)}return e??Rf(r)}function hB(t,e,n){return t.msecs??(t.msecs=-1/0),t.nsecs??(t.nsecs=0),e===t.msecs?(t.nsecs++,t.nsecs>=1e4&&(t.node=void 0,t.nsecs=0)):e>t.msecs?t.nsecs=0:e<t.msecs&&(t.node=void 0),t.node||(t.node=n.slice(10,16),t.node[0]|=1,t.clockseq=(n[8]<<8|n[9])&16383),t.msecs=e,t}function kv(t,e,n,r,s,i,a=0){if(t.length<16)throw new Error("Random bytes length must be >= 16");if(!i)i=new Uint8Array(16),a=0;else if(a<0||a+16>i.length)throw new RangeError(`UUID byte range ${a}:${a+15} is out of buffer bounds`);e??(e=Date.now()),n??(n=0),r??(r=(t[8]<<8|t[9])&16383),s??(s=t.slice(10,16)),e+=122192928e5;const o=((e&268435455)*1e4+n)%4294967296;i[a++]=o>>>24&255,i[a++]=o>>>16&255,i[a++]=o>>>8&255,i[a++]=o&255;const c=e/4294967296*1e4&268435455;i[a++]=c>>>8&255,i[a++]=c&255,i[a++]=c>>>24&15|16,i[a++]=c>>>16&255,i[a++]=r>>>8|128,i[a++]=r&255;for(let u=0;u<6;++u)i[a++]=s[u];return i}function fB(t){const e=typeof t=="string"?Ug(t):t,n=pB(e);return typeof t=="string"?Rf(n):n}function pB(t){return Uint8Array.of((t[6]&15)<<4|t[7]>>4&15,(t[7]&15)<<4|(t[4]&240)>>4,(t[4]&15)<<4|(t[5]&240)>>4,(t[5]&15)<<4|(t[0]&240)>>4,(t[0]&15)<<4|(t[1]&240)>>4,(t[1]&15)<<4|(t[2]&240)>>4,96|t[2]&15,t[3],t[8],t[9],t[10],t[11],t[12],t[13],t[14],t[15])}function mB(t){t=unescape(encodeURIComponent(t));const e=new Uint8Array(t.length);for(let n=0;n<t.length;++n)e[n]=t.charCodeAt(n);return e}const gB="6ba7b810-9dad-11d1-80b4-00c04fd430c8",_B="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function yB(t,e,n,r,s,i){const a=typeof n=="string"?mB(n):n,o=typeof r=="string"?Ug(r):r;if(typeof r=="string"&&(r=Ug(r)),(r==null?void 0:r.length)!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let c=new Uint8Array(16+a.length);if(c.set(o),c.set(a,o.length),c=e(c),c[6]=c[6]&15|t,c[8]=c[8]&63|128,s){if(i??(i=0),i<0||i+16>s.length)throw new RangeError(`UUID byte range ${i}:${i+15} is out of buffer bounds`);for(let u=0;u<16;++u)s[i+u]=c[u];return s}return Rf(c)}function wB(t,e,n,r){switch(t){case 0:return e&n^~e&r;case 1:return e^n^r;case 2:return e&n^e&r^n&r;case 3:return e^n^r}}function Kp(t,e){return t<<e|t>>>32-e}function bB(t){const e=[1518500249,1859775393,2400959708,3395469782],n=[1732584193,4023233417,2562383102,271733878,3285377520],r=new Uint8Array(t.length+1);r.set(t),r[t.length]=128,t=r;const s=t.length/4+2,i=Math.ceil(s/16),a=new Array(i);for(let o=0;o<i;++o){const c=new Uint32Array(16);for(let u=0;u<16;++u)c[u]=t[o*64+u*4]<<24|t[o*64+u*4+1]<<16|t[o*64+u*4+2]<<8|t[o*64+u*4+3];a[o]=c}a[i-1][14]=(t.length-1)*8/2**32,a[i-1][14]=Math.floor(a[i-1][14]),a[i-1][15]=(t.length-1)*8&4294967295;for(let o=0;o<i;++o){const c=new Uint32Array(80);for(let p=0;p<16;++p)c[p]=a[o][p];for(let p=16;p<80;++p)c[p]=Kp(c[p-3]^c[p-8]^c[p-14]^c[p-16],1);let u=n[0],l=n[1],d=n[2],f=n[3],h=n[4];for(let p=0;p<80;++p){const g=Math.floor(p/20),y=Kp(u,5)+wB(g,l,d,f)+h+e[g]+c[p]>>>0;h=f,f=d,d=Kp(l,30)>>>0,l=u,u=y}n[0]=n[0]+u>>>0,n[1]=n[1]+l>>>0,n[2]=n[2]+d>>>0,n[3]=n[3]+f>>>0,n[4]=n[4]+h>>>0}return Uint8Array.of(n[0]>>24,n[0]>>16,n[0]>>8,n[0],n[1]>>24,n[1]>>16,n[1]>>8,n[1],n[2]>>24,n[2]>>16,n[2]>>8,n[2],n[3]>>24,n[3]>>16,n[3]>>8,n[3],n[4]>>24,n[4]>>16,n[4]>>8,n[4])}function Fy(t,e,n,r){return yB(80,bB,t,e,n,r)}Fy.DNS=gB;Fy.URL=_B;function vB(t,e,n){t??(t={});let r=dB({...t,_v6:!0},new Uint8Array(16));return r=fB(r),Rf(r)}let Wp=0,dc=0;function GI(t){let e=Date.now();return e<=Wp?(dc+=1,dc>=1e4&&(dc=0,e=Wp+1)):dc=0,Wp=e,vB({clockseq:t,msecs:e,nsecs:dc})}function Qi(t,e){const n=e.replace(/-/g,"").match(/.{2}/g).map(r=>parseInt(r,16));return Fy(t,new Uint8Array(n))}const SB="__error__",Hd="__scheduled__",AB="__interrupt__",TB="__resume__";var By=class{constructor(t){m(this,"lg_name","DeltaSnapshot");m(this,"value");this.value=t}},Cv="[...]",EB="[Circular]",Dh=[],so=[];function IB(){return{depthLimit:Number.MAX_SAFE_INTEGER,edgesLimit:Number.MAX_SAFE_INTEGER}}function xB(t,e,n,r){typeof r>"u"&&(r=IB()),Fg(t,"",0,[],void 0,0,r);var s;try{so.length===0?s=JSON.stringify(t,e,n):s=JSON.stringify(t,kB(e),n)}catch{return JSON.stringify("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;Dh.length!==0;){var i=Dh.pop();i.length===4?Object.defineProperty(i[0],i[1],i[3]):i[0][i[1]]=i[2]}}return s}function Zp(t,e,n,r){var s=Object.getOwnPropertyDescriptor(r,n);s.get!==void 0?s.configurable?(Object.defineProperty(r,n,{value:t}),Dh.push([r,n,e,s])):so.push([e,n,t]):(r[n]=t,Dh.push([r,n,e]))}function Fg(t,e,n,r,s,i,a){i+=1;var o;if(typeof t=="object"&&t!==null){for(o=0;o<r.length;o++)if(r[o]===t){Zp(EB,t,e,s);return}if(typeof a.depthLimit<"u"&&i>a.depthLimit){Zp(Cv,t,e,s);return}if(typeof a.edgesLimit<"u"&&n+1>a.edgesLimit){Zp(Cv,t,e,s);return}if(r.push(t),Array.isArray(t))for(o=0;o<t.length;o++)Fg(t[o],o,o,r,t,i,a);else{var c=Object.keys(t);for(o=0;o<c.length;o++){var u=c[o];Fg(t[u],u,o,r,t,i,a)}}r.pop()}}function kB(t){return t=typeof t<"u"?t:function(e,n){return n},function(e,n){if(so.length>0)for(var r=0;r<so.length;r++){var s=so[r];if(s[1]===e&&s[0]===n){n=s[2],so.splice(r,1);break}}return t.call(this,e,n)}}const CB=[];var OB=de({}),$B=de({});/**
|
|
130
|
-
* [js-sha256]{@link https://github.com/emn178/js-sha256}
|
|
131
|
-
*
|
|
132
|
-
* @version 0.11.1
|
|
133
|
-
* @author Chen, Yi-Cyuan [emn178@gmail.com]
|
|
134
|
-
* @copyright Chen, Yi-Cyuan 2014-2025
|
|
135
|
-
* @license MIT
|
|
136
|
-
*/var pe="0123456789abcdef".split(""),RB=[-2147483648,8388608,32768,128],Lr=[24,16,8,0],td=[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],Gt=[];function Yr(t,e){e?(Gt[0]=Gt[16]=Gt[1]=Gt[2]=Gt[3]=Gt[4]=Gt[5]=Gt[6]=Gt[7]=Gt[8]=Gt[9]=Gt[10]=Gt[11]=Gt[12]=Gt[13]=Gt[14]=Gt[15]=0,this.blocks=Gt):this.blocks=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],t?(this.h0=3238371032,this.h1=914150663,this.h2=812702999,this.h3=4144912697,this.h4=4290775857,this.h5=1750603025,this.h6=1694076839,this.h7=3204075428):(this.h0=1779033703,this.h1=3144134277,this.h2=1013904242,this.h3=2773480762,this.h4=1359893119,this.h5=2600822924,this.h6=528734635,this.h7=1541459225),this.block=this.start=this.bytes=this.hBytes=0,this.finalized=this.hashed=!1,this.first=!0,this.is224=t}Yr.prototype.update=function(t){if(!this.finalized){var e,n=typeof t;if(n!=="string"){if(n==="object"){if(t===null)throw new Error(ERROR);if(ARRAY_BUFFER&&t.constructor===ArrayBuffer)t=new Uint8Array(t);else if(!Array.isArray(t)&&(!ARRAY_BUFFER||!ArrayBuffer.isView(t)))throw new Error(ERROR)}else throw new Error(ERROR);e=!0}for(var r,s=0,i,a=t.length,o=this.blocks;s<a;){if(this.hashed&&(this.hashed=!1,o[0]=this.block,this.block=o[16]=o[1]=o[2]=o[3]=o[4]=o[5]=o[6]=o[7]=o[8]=o[9]=o[10]=o[11]=o[12]=o[13]=o[14]=o[15]=0),e)for(i=this.start;s<a&&i<64;++s)o[i>>>2]|=t[s]<<Lr[i++&3];else for(i=this.start;s<a&&i<64;++s)r=t.charCodeAt(s),r<128?o[i>>>2]|=r<<Lr[i++&3]:r<2048?(o[i>>>2]|=(192|r>>>6)<<Lr[i++&3],o[i>>>2]|=(128|r&63)<<Lr[i++&3]):r<55296||r>=57344?(o[i>>>2]|=(224|r>>>12)<<Lr[i++&3],o[i>>>2]|=(128|r>>>6&63)<<Lr[i++&3],o[i>>>2]|=(128|r&63)<<Lr[i++&3]):(r=65536+((r&1023)<<10|t.charCodeAt(++s)&1023),o[i>>>2]|=(240|r>>>18)<<Lr[i++&3],o[i>>>2]|=(128|r>>>12&63)<<Lr[i++&3],o[i>>>2]|=(128|r>>>6&63)<<Lr[i++&3],o[i>>>2]|=(128|r&63)<<Lr[i++&3]);this.lastByteIndex=i,this.bytes+=i-this.start,i>=64?(this.block=o[16],this.start=i-64,this.hash(),this.hashed=!0):this.start=i}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296<<0,this.bytes=this.bytes%4294967296),this}};Yr.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var t=this.blocks,e=this.lastByteIndex;t[16]=this.block,t[e>>>2]|=RB[e&3],this.block=t[16],e>=56&&(this.hashed||this.hash(),t[0]=this.block,t[16]=t[1]=t[2]=t[3]=t[4]=t[5]=t[6]=t[7]=t[8]=t[9]=t[10]=t[11]=t[12]=t[13]=t[14]=t[15]=0),t[14]=this.hBytes<<3|this.bytes>>>29,t[15]=this.bytes<<3,this.hash()}};Yr.prototype.hash=function(){var t=this.h0,e=this.h1,n=this.h2,r=this.h3,s=this.h4,i=this.h5,a=this.h6,o=this.h7,c=this.blocks,u,l,d,f,h,p,g,y,b,_,w;for(u=16;u<64;++u)h=c[u-15],l=(h>>>7|h<<25)^(h>>>18|h<<14)^h>>>3,h=c[u-2],d=(h>>>17|h<<15)^(h>>>19|h<<13)^h>>>10,c[u]=c[u-16]+l+c[u-7]+d<<0;for(w=e&n,u=0;u<64;u+=4)this.first?(this.is224?(y=300032,h=c[0]-1413257819,o=h-150054599<<0,r=h+24177077<<0):(y=704751109,h=c[0]-210244248,o=h-1521486534<<0,r=h+143694565<<0),this.first=!1):(l=(t>>>2|t<<30)^(t>>>13|t<<19)^(t>>>22|t<<10),d=(s>>>6|s<<26)^(s>>>11|s<<21)^(s>>>25|s<<7),y=t&e,f=y^t&n^w,g=s&i^~s&a,h=o+d+g+td[u]+c[u],p=l+f,o=r+h<<0,r=h+p<<0),l=(r>>>2|r<<30)^(r>>>13|r<<19)^(r>>>22|r<<10),d=(o>>>6|o<<26)^(o>>>11|o<<21)^(o>>>25|o<<7),b=r&t,f=b^r&e^y,g=a&o^~a&s,h=i+d+g+td[u+1]+c[u+1],p=l+f,a=n+h<<0,n=h+p<<0,l=(n>>>2|n<<30)^(n>>>13|n<<19)^(n>>>22|n<<10),d=(a>>>6|a<<26)^(a>>>11|a<<21)^(a>>>25|a<<7),_=n&r,f=_^n&t^b,g=i&a^~i&o,h=s+d+g+td[u+2]+c[u+2],p=l+f,i=e+h<<0,e=h+p<<0,l=(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),w=e&n,f=w^e&r^_,g=i&a^~i&o,h=s+d+g+td[u+3]+c[u+3],p=l+f,s=t+h<<0,t=h+p<<0,this.chromeBugWorkAround=!0;this.h0=this.h0+t<<0,this.h1=this.h1+e<<0,this.h2=this.h2+n<<0,this.h3=this.h3+r<<0,this.h4=this.h4+s<<0,this.h5=this.h5+i<<0,this.h6=this.h6+a<<0,this.h7=this.h7+o<<0};Yr.prototype.hex=function(){this.finalize();var t=this.h0,e=this.h1,n=this.h2,r=this.h3,s=this.h4,i=this.h5,a=this.h6,o=this.h7,c=pe[t>>>28&15]+pe[t>>>24&15]+pe[t>>>20&15]+pe[t>>>16&15]+pe[t>>>12&15]+pe[t>>>8&15]+pe[t>>>4&15]+pe[t&15]+pe[e>>>28&15]+pe[e>>>24&15]+pe[e>>>20&15]+pe[e>>>16&15]+pe[e>>>12&15]+pe[e>>>8&15]+pe[e>>>4&15]+pe[e&15]+pe[n>>>28&15]+pe[n>>>24&15]+pe[n>>>20&15]+pe[n>>>16&15]+pe[n>>>12&15]+pe[n>>>8&15]+pe[n>>>4&15]+pe[n&15]+pe[r>>>28&15]+pe[r>>>24&15]+pe[r>>>20&15]+pe[r>>>16&15]+pe[r>>>12&15]+pe[r>>>8&15]+pe[r>>>4&15]+pe[r&15]+pe[s>>>28&15]+pe[s>>>24&15]+pe[s>>>20&15]+pe[s>>>16&15]+pe[s>>>12&15]+pe[s>>>8&15]+pe[s>>>4&15]+pe[s&15]+pe[i>>>28&15]+pe[i>>>24&15]+pe[i>>>20&15]+pe[i>>>16&15]+pe[i>>>12&15]+pe[i>>>8&15]+pe[i>>>4&15]+pe[i&15]+pe[a>>>28&15]+pe[a>>>24&15]+pe[a>>>20&15]+pe[a>>>16&15]+pe[a>>>12&15]+pe[a>>>8&15]+pe[a>>>4&15]+pe[a&15];return this.is224||(c+=pe[o>>>28&15]+pe[o>>>24&15]+pe[o>>>20&15]+pe[o>>>16&15]+pe[o>>>12&15]+pe[o>>>8&15]+pe[o>>>4&15]+pe[o&15]),c};Yr.prototype.toString=Yr.prototype.hex;Yr.prototype.digest=function(){this.finalize();var t=this.h0,e=this.h1,n=this.h2,r=this.h3,s=this.h4,i=this.h5,a=this.h6,o=this.h7,c=[t>>>24&255,t>>>16&255,t>>>8&255,t&255,e>>>24&255,e>>>16&255,e>>>8&255,e&255,n>>>24&255,n>>>16&255,n>>>8&255,n&255,r>>>24&255,r>>>16&255,r>>>8&255,r&255,s>>>24&255,s>>>16&255,s>>>8&255,s&255,i>>>24&255,i>>>16&255,i>>>8&255,i&255,a>>>24&255,a>>>16&255,a>>>8&255,a&255];return this.is224||c.push(o>>>24&255,o>>>16&255,o>>>8&255,o&255),c};Yr.prototype.array=Yr.prototype.digest;Yr.prototype.arrayBuffer=function(){this.finalize();var t=new ArrayBuffer(this.is224?28:32),e=new DataView(t);return e.setUint32(0,this.h0),e.setUint32(4,this.h1),e.setUint32(8,this.h2),e.setUint32(12,this.h3),e.setUint32(16,this.h4),e.setUint32(20,this.h5),e.setUint32(24,this.h6),this.is224||e.setUint32(28,this.h7),t};const zy=(...t)=>new Yr(!1,!0).update(t.join("")).hex();var PB=de({sha256:()=>zy}),NB=de({BaseCache:()=>YI,InMemoryCache:()=>XI,defaultHashKeyEncoder:()=>JI,deserializeStoredGeneration:()=>MB,serializeGeneration:()=>LB});const JI=(...t)=>zy(t.join("_"));function MB(t){return t.message!==void 0?{text:t.text,message:ry(t.message)}:{text:t.text}}function LB(t){const e={text:t.text};return t.message!==void 0&&(e.message=t.message.toDict()),e}var YI=class{constructor(){m(this,"keyEncoder",JI)}makeDefaultKeyEncoder(e){this.keyEncoder=e}};const jB=new Map;var XI=class QI extends YI{constructor(n){super();m(this,"cache");this.cache=n??new Map}lookup(n,r){return Promise.resolve(this.cache.get(this.keyEncoder(n,r))??null)}async update(n,r,s){this.cache.set(this.keyEncoder(n,r),s)}static global(){return new QI(jB)}},DB=de({BaseChatMessageHistory:()=>ex,BaseListChatMessageHistory:()=>Hy,InMemoryChatMessageHistory:()=>UB}),ex=class extends xr{async addMessages(t){for(const e of t)await this.addMessage(e)}},Hy=class extends xr{addUserMessage(t){return this.addMessage(new Nn(t))}addAIMessage(t){return this.addMessage(new De(t))}async addMessages(t){for(const e of t)await this.addMessage(e)}clear(){throw new Error("Not implemented.")}},UB=class extends Hy{constructor(e){super(...arguments);m(this,"lc_namespace",["langchain","stores","message","in_memory"]);m(this,"messages",[]);this.messages=e??[]}async getMessages(){return this.messages}async addMessage(e){this.messages.push(e)}async clear(){this.messages=[]}},Ti=class{constructor(t){m(this,"pageContent");m(this,"metadata");m(this,"id");this.pageContent=t.pageContent!==void 0?t.pageContent.toString():"",this.metadata=t.metadata??{},this.id=t.id}},tx=class extends ze{constructor(){super(...arguments);m(this,"lc_namespace",["langchain_core","documents","transformers"])}invoke(e,n){return this.transformDocuments(e)}},FB=class extends tx{async transformDocuments(t){const e=[];for(const n of t){const r=await this._transformDocument(n);e.push(r)}return e}},BB=de({BaseDocumentTransformer:()=>tx,Document:()=>Ti,MappingDocumentTransformer:()=>FB}),zB=de({BaseDocumentLoader:()=>nx}),nx=class{},HB=de({LangSmithLoader:()=>VB}),VB=class extends nx{constructor(e){super();m(this,"datasetId");m(this,"datasetName");m(this,"exampleIds");m(this,"asOf");m(this,"splits");m(this,"inlineS3Urls");m(this,"offset");m(this,"limit");m(this,"metadata");m(this,"filter");m(this,"contentKey");m(this,"formatContent");m(this,"client");if(e.client&&e.clientConfig)throw new Error("client and clientConfig cannot both be provided.");this.client=e.client??new ls(e==null?void 0:e.clientConfig),this.contentKey=e.contentKey?e.contentKey.split("."):[],this.formatContent=e.formatContent??KB,this.datasetId=e.datasetId,this.datasetName=e.datasetName,this.exampleIds=e.exampleIds,this.asOf=e.asOf,this.splits=e.splits,this.inlineS3Urls=e.inlineS3Urls,this.offset=e.offset,this.limit=e.limit,this.metadata=e.metadata,this.filter=e.filter}async load(){const e=[];for await(const n of this.client.listExamples({datasetId:this.datasetId,datasetName:this.datasetName,exampleIds:this.exampleIds,asOf:this.asOf,splits:this.splits,inlineS3Urls:this.inlineS3Urls,offset:this.offset,limit:this.limit,metadata:this.metadata,filter:this.filter})){let r=n.inputs;for(const a of this.contentKey)r=r[a];const s=this.formatContent(r),i=n;["created_at","modified_at"].forEach(a=>{a in i&&typeof i[a]=="object"&&(i[a]=i[a].toString())}),e.push({pageContent:s,metadata:i})}return e}};function KB(t){if(typeof t=="string")return t;try{return JSON.stringify(t,null,2)}catch{return String(t)}}var WB=de({Embeddings:()=>Vy}),Vy=class{constructor(e){m(this,"caller");this.caller=new _l(e??{})}},Ky=class extends xr{constructor(){super(...arguments);m(this,"lc_namespace",["langchain_core","example_selectors","base"])}},rx=class{async getPromptAsync(t,e){return this.getPrompt(t).partial((e==null?void 0:e.partialVariables)??{})}},ZB=class extends rx{constructor(e,n=[]){super();m(this,"defaultPrompt");m(this,"conditionals");this.defaultPrompt=e,this.conditionals=n}getPrompt(e){for(const[n,r]of this.conditionals)if(n(e))return r;return this.defaultPrompt}};function qB(t){return t._modelType()==="base_llm"}function GB(t){return t._modelType()==="base_chat_model"}function Ov(t){return t.split(/\n| /).length}var JB=class sx extends Ky{constructor(n){super(n);m(this,"examples",[]);m(this,"examplePrompt");m(this,"getTextLength",Ov);m(this,"maxLength",2048);m(this,"exampleTextLengths",[]);this.examplePrompt=n.examplePrompt,this.maxLength=n.maxLength??2048,this.getTextLength=n.getTextLength??Ov}async addExample(n){this.examples.push(n);const r=await this.examplePrompt.format(n);this.exampleTextLengths.push(this.getTextLength(r))}async calculateExampleTextLengths(n,r){if(n.length>0)return n;const{examples:s,examplePrompt:i}=r;return(await Promise.all(s.map(a=>i.format(a)))).map(a=>this.getTextLength(a))}async selectExamples(n){const r=Object.values(n).join(" ");let s=this.maxLength-this.getTextLength(r),i=0;const a=[];for(;s>0&&i<this.examples.length;){const o=s-this.exampleTextLengths[i];if(o<0)break;a.push(this.examples[i]),s=o,i+=1}return a}static async fromExamples(n,r){const s=new sx(r);return await Promise.all(n.map(i=>s.addExample(i))),s}};function qp(t){return Object.keys(t).sort().map(e=>t[e])}var YB=class ix extends Ky{constructor(n){super(n);m(this,"vectorStoreRetriever");m(this,"exampleKeys");m(this,"inputKeys");if(this.exampleKeys=n.exampleKeys,this.inputKeys=n.inputKeys,n.vectorStore!==void 0)this.vectorStoreRetriever=n.vectorStore.asRetriever({k:n.k??4,filter:n.filter});else if(n.vectorStoreRetriever)this.vectorStoreRetriever=n.vectorStoreRetriever;else throw new Error('You must specify one of "vectorStore" and "vectorStoreRetriever".')}async addExample(n){const r=qp((this.inputKeys??Object.keys(n)).reduce((s,i)=>({...s,[i]:n[i]}),{})).join(" ");await this.vectorStoreRetriever.addDocuments([new Ti({pageContent:r,metadata:n})])}async selectExamples(n){const r=qp((this.inputKeys??Object.keys(n)).reduce((i,a)=>({...i,[a]:n[a]}),{})).join(" "),s=(await this.vectorStoreRetriever.invoke(r)).map(i=>i.metadata);return this.exampleKeys?s.map(i=>this.exampleKeys.reduce((a,o)=>({...a,[o]:i[o]}),{})):s}static async fromExamples(n,r,s,i={}){const a=i.inputKeys??null,o=n.map(c=>qp(a?a.reduce((u,l)=>({...u,[l]:c[l]}),{}):c).join(" "));return new ix({vectorStore:await s.fromTexts(o,n,r,i),k:i.k??4,exampleKeys:i.exampleKeys,inputKeys:i.inputKeys})}},XB=de({BaseExampleSelector:()=>Ky,BasePromptSelector:()=>rx,ConditionalPromptSelector:()=>ZB,LengthBasedExampleSelector:()=>JB,SemanticSimilarityExampleSelector:()=>YB,isChatModel:()=>GB,isLLM:()=>qB});const Bg="10f90ea3-90a4-4962-bf75-83a0f3c1c62a";var QB=class extends xr{constructor(){super(...arguments);m(this,"lc_namespace",["langchain","recordmanagers"])}},ax=class{constructor(t){m(this,"uid");m(this,"hash_");m(this,"contentHash");m(this,"metadataHash");m(this,"pageContent");m(this,"metadata");m(this,"keyEncoder",zy);this.uid=t.uid,this.pageContent=t.pageContent,this.metadata=t.metadata}makeDefaultKeyEncoder(t){this.keyEncoder=t}calculateHashes(){const t=["hash_","content_hash","metadata_hash"];for(const n of t)if(n in this.metadata)throw new Error(`Metadata cannot contain key ${n} as it is reserved for internal use. Restricted keys: [${t.join(", ")}]`);const e=this._hashStringToUUID(this.pageContent);try{const n=this._hashNestedDictToUUID(this.metadata);this.contentHash=e,this.metadataHash=n}catch(n){throw new Error(`Failed to hash metadata: ${n}. Please use a dict that can be serialized using json.`)}this.hash_=this._hashStringToUUID(this.contentHash+this.metadataHash),this.uid||(this.uid=this.hash_)}toDocument(){return new Ti({pageContent:this.pageContent,metadata:this.metadata})}static fromDocument(t,e){const n=new this({pageContent:t.pageContent,metadata:t.metadata,uid:e||t.uid});return n.calculateHashes(),n}_hashStringToUUID(t){return Xm(this.keyEncoder(t),Bg)}_hashNestedDictToUUID(t){const e=JSON.stringify(t,Object.keys(t).sort());return Xm(this.keyEncoder(e),Bg)}};function ox(t,e){const n=[];let r=[];return e.forEach(s=>{r.push(s),r.length>=t&&(n.push(r),r=[])}),r.length>0&&n.push(r),n}function cx(t){const e=new Set,n=[];for(const r of t){if(!r.hash_)throw new Error("Hashed document does not have a hash");e.has(r.hash_)||(e.add(r.hash_),n.push(r))}return n}function ux(t){if(t===null)return e=>null;if(typeof t=="string")return e=>e.metadata[t];if(typeof t=="function")return t;throw new Error(`sourceIdKey should be null, a string or a function, got ${typeof t}`)}const lx=t=>"load"in t&&typeof t.load=="function"&&"loadAndSplit"in t&&typeof t.loadAndSplit=="function";async function ez(t){const{docsSource:e,recordManager:n,vectorStore:r,options:s}=t,{batchSize:i=100,cleanup:a,sourceIdKey:o,cleanupBatchSize:c=1e3,forceUpdate:u=!1}=s??{};if(a==="incremental"&&!o)throw new Error("sourceIdKey is required when cleanup mode is incremental. Please provide through 'options.sourceIdKey'.");const l=lx(e)?await e.load():e,d=ux(o??null),f=await n.getTime();let h=0,p=0,g=0,y=0;const b=ox(i??100,l);for(const _ of b){const w=cx(_.map(k=>ax.fromDocument(k))),v=w.map(k=>d(k));a==="incremental"&&w.forEach((k,C)=>{if(v[C]===null)throw new Error("sourceIdKey must be provided when cleanup is incremental")});const A=await n.exists(w.map(k=>k.uid)),S=[],x=[],E=[],$=new Set;if(w.forEach((k,C)=>{if(A[C])if(u)$.add(k.uid);else{E.push(k.uid);return}S.push(k.uid),x.push(k.toDocument())}),E.length>0&&(await n.update(E,{timeAtLeast:f}),y+=E.length),x.length>0&&(await r.addDocuments(x,{ids:S}),h+=x.length-$.size,g+=$.size),await n.update(w.map(k=>k.uid),{timeAtLeast:f,groupIds:v}),a==="incremental"){v.forEach(C=>{if(!C)throw new Error("Source id cannot be null")});const k=await n.listKeys({before:f,groupIds:v});k.length>0&&(await r.delete({ids:k}),await n.deleteKeys(k),p+=k.length)}}if(a==="full"){let _=await n.listKeys({before:f,limit:c});for(;_.length>0;)await r.delete({ids:_}),await n.deleteKeys(_),p+=_.length,_=await n.listKeys({before:f,limit:c})}return{numAdded:h,numDeleted:p,numUpdated:g,numSkipped:y}}var tz=de({RecordManager:()=>QB,UUIDV5_NAMESPACE:()=>Bg,_HashedDocument:()=>ax,_batch:()=>ox,_deduplicateInOrder:()=>cx,_getSourceIdAssigner:()=>ux,_isBaseDocumentLoader:()=>lx,index:()=>ez}),nz=de({BasePromptValue:()=>Pf,ChatPromptValue:()=>Zy,ImagePromptValue:()=>dx,StringPromptValue:()=>Wy}),Pf=class extends xr{},Wy=class extends Pf{constructor(e){super({value:e});m(this,"lc_namespace",["langchain_core","prompt_values"]);m(this,"lc_serializable",!0);m(this,"value");this.value=e}static lc_name(){return"StringPromptValue"}toString(){return this.value}toChatMessages(){return[new Nn(this.value)]}},Zy=class extends Pf{constructor(e){Array.isArray(e)&&(e={messages:e});super(e);m(this,"lc_namespace",["langchain_core","prompt_values"]);m(this,"lc_serializable",!0);m(this,"messages");this.messages=e.messages}static lc_name(){return"ChatPromptValue"}toString(){return ny(this.messages)}toChatMessages(){return this.messages}},dx=class extends Pf{constructor(e){"imageUrl"in e||(e={imageUrl:e});super(e);m(this,"lc_namespace",["langchain_core","prompt_values"]);m(this,"lc_serializable",!0);m(this,"imageUrl");m(this,"value");this.imageUrl=e.imageUrl}static lc_name(){return"ImagePromptValue"}toString(){return this.imageUrl.url}toChatMessages(){return[new Nn({content:[{type:"image_url",image_url:{detail:this.imageUrl.detail,url:this.imageUrl.url}}]})]}},Nf={};Nf.byteLength=iz;Nf.toByteArray=oz;Nf.fromByteArray=lz;var hs=[],Sr=[],rz=typeof Uint8Array<"u"?Uint8Array:Array,Gp="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(var $a=0,sz=Gp.length;$a<sz;++$a)hs[$a]=Gp[$a],Sr[Gp.charCodeAt($a)]=$a;Sr[45]=62;Sr[95]=63;function hx(t){var e=t.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var n=t.indexOf("=");n===-1&&(n=e);var r=n===e?0:4-n%4;return[n,r]}function iz(t){var e=hx(t),n=e[0],r=e[1];return(n+r)*3/4-r}function az(t,e,n){return(e+n)*3/4-n}function oz(t){var e,n=hx(t),r=n[0],s=n[1],i=new rz(az(t,r,s)),a=0,o=s>0?r-4:r,c;for(c=0;c<o;c+=4)e=Sr[t.charCodeAt(c)]<<18|Sr[t.charCodeAt(c+1)]<<12|Sr[t.charCodeAt(c+2)]<<6|Sr[t.charCodeAt(c+3)],i[a++]=e>>16&255,i[a++]=e>>8&255,i[a++]=e&255;return s===2&&(e=Sr[t.charCodeAt(c)]<<2|Sr[t.charCodeAt(c+1)]>>4,i[a++]=e&255),s===1&&(e=Sr[t.charCodeAt(c)]<<10|Sr[t.charCodeAt(c+1)]<<4|Sr[t.charCodeAt(c+2)]>>2,i[a++]=e>>8&255,i[a++]=e&255),i}function cz(t){return hs[t>>18&63]+hs[t>>12&63]+hs[t>>6&63]+hs[t&63]}function uz(t,e,n){for(var r,s=[],i=e;i<n;i+=3)r=(t[i]<<16&16711680)+(t[i+1]<<8&65280)+(t[i+2]&255),s.push(cz(r));return s.join("")}function lz(t){for(var e,n=t.length,r=n%3,s=[],i=16383,a=0,o=n-r;a<o;a+=i)s.push(uz(t,a,a+i>o?o:a+i));return r===1?(e=t[n-1],s.push(hs[e>>2]+hs[e<<4&63]+"==")):r===2&&(e=(t[n-2]<<8)+t[n-1],s.push(hs[e>>10]+hs[e>>4&63]+hs[e<<2&63]+"=")),s.join("")}var dz=Object.defineProperty,hz=(t,e,n)=>e in t?dz(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,fz=(t,e,n)=>(hz(t,e+"",n),n);function pz(t,e){let n=Array.from({length:t.length},(r,s)=>({start:s,end:s+1}));for(;n.length>1;){let r=null;for(let s=0;s<n.length-1;s++){const i=t.slice(n[s].start,n[s+1].end),a=e.get(i.join(","));a!=null&&(r==null||a<r[0])&&(r=[a,s])}if(r!=null){const s=r[1];n[s]={start:n[s].start,end:n[s+1].end},n.splice(s+1,1)}else break}return n}function mz(t,e){return t.length===1?[e.get(t.join(","))]:pz(t,e).map(n=>e.get(t.slice(n.start,n.end).join(","))).filter(n=>n!=null)}function gz(t){return t.replace(/[\\^$*+?.()|[\]{}]/g,"\\$&")}var zg=class{constructor(t,e){m(this,"specialTokens");m(this,"inverseSpecialTokens");m(this,"patStr");m(this,"textEncoder",new TextEncoder);m(this,"textDecoder",new TextDecoder("utf-8"));m(this,"rankMap",new Map);m(this,"textMap",new Map);this.patStr=t.pat_str;const n=t.bpe_ranks.split(`
|
|
137
|
-
`).filter(Boolean).reduce((r,s)=>{const[i,a,...o]=s.split(" "),c=Number.parseInt(a,10);return o.forEach((u,l)=>r[u]=c+l),r},{});for(const[r,s]of Object.entries(n)){const i=Nf.toByteArray(r);this.rankMap.set(i.join(","),s),this.textMap.set(s,i)}this.specialTokens={...t.special_tokens,...e},this.inverseSpecialTokens=Object.entries(this.specialTokens).reduce((r,[s,i])=>(r[i]=this.textEncoder.encode(s),r),{})}encode(t,e=[],n="all"){const r=new RegExp(this.patStr,"ug"),s=zg.specialTokenRegex(Object.keys(this.specialTokens)),i=[],a=new Set(e==="all"?Object.keys(this.specialTokens):e),o=new Set(n==="all"?Object.keys(this.specialTokens).filter(u=>!a.has(u)):n);if(o.size>0){const u=zg.specialTokenRegex([...o]),l=t.match(u);if(l!=null)throw new Error(`The text contains a special token that is not allowed: ${l[0]}`)}let c=0;for(;;){let u=null,l=c;for(;s.lastIndex=l,u=s.exec(t),!(u==null||a.has(u[0]));)l=u.index+1;const d=(u==null?void 0:u.index)??t.length;for(const h of t.substring(c,d).matchAll(r)){const p=this.textEncoder.encode(h[0]),g=this.rankMap.get(p.join(","));if(g!=null){i.push(g);continue}i.push(...mz(p,this.rankMap))}if(u==null)break;let f=this.specialTokens[u[0]];i.push(f),c=u.index+u[0].length}return i}decode(t){const e=[];let n=0;for(let i=0;i<t.length;++i){const a=t[i],o=this.textMap.get(a)??this.inverseSpecialTokens[a];o!=null&&(e.push(o),n+=o.length)}const r=new Uint8Array(n);let s=0;for(const i of e)r.set(i,s),s+=i.length;return this.textDecoder.decode(r)}},fx=zg;fz(fx,"specialTokenRegex",t=>new RegExp(t.map(e=>gz(e)).join("|"),"g"));function _z(t){switch(t){case"gpt2":return"gpt2";case"code-cushman-001":case"code-cushman-002":case"code-davinci-001":case"code-davinci-002":case"cushman-codex":case"davinci-codex":case"davinci-002":case"text-davinci-002":case"text-davinci-003":return"p50k_base";case"code-davinci-edit-001":case"text-davinci-edit-001":return"p50k_edit";case"ada":case"babbage":case"babbage-002":case"code-search-ada-code-001":case"code-search-babbage-code-001":case"curie":case"davinci":case"text-ada-001":case"text-babbage-001":case"text-curie-001":case"text-davinci-001":case"text-search-ada-doc-001":case"text-search-babbage-doc-001":case"text-search-curie-doc-001":case"text-search-davinci-doc-001":case"text-similarity-ada-001":case"text-similarity-babbage-001":case"text-similarity-curie-001":case"text-similarity-davinci-001":return"r50k_base";case"gpt-3.5-turbo-instruct-0914":case"gpt-3.5-turbo-instruct":case"gpt-3.5-turbo-16k-0613":case"gpt-3.5-turbo-16k":case"gpt-3.5-turbo-0613":case"gpt-3.5-turbo-0301":case"gpt-3.5-turbo":case"gpt-4-32k-0613":case"gpt-4-32k-0314":case"gpt-4-32k":case"gpt-4-0613":case"gpt-4-0314":case"gpt-4":case"gpt-3.5-turbo-1106":case"gpt-35-turbo":case"gpt-4-1106-preview":case"gpt-4-vision-preview":case"gpt-3.5-turbo-0125":case"gpt-4-turbo":case"gpt-4-turbo-2024-04-09":case"gpt-4-turbo-preview":case"gpt-4-0125-preview":case"text-embedding-ada-002":case"text-embedding-3-small":case"text-embedding-3-large":return"cl100k_base";case"gpt-4o":case"gpt-4o-2024-05-13":case"gpt-4o-2024-08-06":case"gpt-4o-2024-11-20":case"gpt-4o-mini-2024-07-18":case"gpt-4o-mini":case"gpt-4o-search-preview":case"gpt-4o-search-preview-2025-03-11":case"gpt-4o-mini-search-preview":case"gpt-4o-mini-search-preview-2025-03-11":case"gpt-4o-audio-preview":case"gpt-4o-audio-preview-2024-12-17":case"gpt-4o-audio-preview-2024-10-01":case"gpt-4o-mini-audio-preview":case"gpt-4o-mini-audio-preview-2024-12-17":case"o1":case"o1-2024-12-17":case"o1-mini":case"o1-mini-2024-09-12":case"o1-preview":case"o1-preview-2024-09-12":case"o1-pro":case"o1-pro-2025-03-19":case"o3":case"o3-2025-04-16":case"o3-mini":case"o3-mini-2025-01-31":case"o4-mini":case"o4-mini-2025-04-16":case"chatgpt-4o-latest":case"gpt-4o-realtime":case"gpt-4o-realtime-preview-2024-10-01":case"gpt-4o-realtime-preview-2024-12-17":case"gpt-4o-mini-realtime-preview":case"gpt-4o-mini-realtime-preview-2024-12-17":case"gpt-4.1":case"gpt-4.1-2025-04-14":case"gpt-4.1-mini":case"gpt-4.1-mini-2025-04-14":case"gpt-4.1-nano":case"gpt-4.1-nano-2025-04-14":case"gpt-4.5-preview":case"gpt-4.5-preview-2025-02-27":case"gpt-5":case"gpt-5-2025-08-07":case"gpt-5-nano":case"gpt-5-nano-2025-08-07":case"gpt-5-mini":case"gpt-5-mini-2025-08-07":case"gpt-5-chat-latest":return"o200k_base";default:throw new Error("Unknown model")}}var yz=de({encodingForModel:()=>qy,getEncoding:()=>px});const nd={},wz=new _l({});async function px(t){return t in nd||(nd[t]=wz.fetch(`https://tiktoken.pages.dev/js/${t}.json`).then(e=>e.json()).then(e=>new fx(e)).catch(e=>{throw delete nd[t],e})),await nd[t]}async function qy(t){return px(_z(t))}var bz=de({BaseLangChain:()=>Gy,BaseLanguageModel:()=>Jy,calculateMaxTokens:()=>Sz,getEmbeddingContextSize:()=>vz,getModelContextSize:()=>mx,getModelNameForTiktoken:()=>Mf,isOpenAITool:()=>Xo});const Mf=t=>t.startsWith("gpt-5")?"gpt-5":t.startsWith("gpt-3.5-turbo-16k")?"gpt-3.5-turbo-16k":t.startsWith("gpt-3.5-turbo-")?"gpt-3.5-turbo":t.startsWith("gpt-4-32k")?"gpt-4-32k":t.startsWith("gpt-4-")?"gpt-4":t.startsWith("gpt-4o")?"gpt-4o":t,vz=t=>{switch(t){case"text-embedding-ada-002":return 8191;default:return 2046}},mx=t=>{switch(Mf(t)){case"gpt-5":case"gpt-5-turbo":case"gpt-5-turbo-preview":return 4e5;case"gpt-4o":case"gpt-4o-mini":case"gpt-4o-2024-05-13":case"gpt-4o-2024-08-06":return 128e3;case"gpt-4-turbo":case"gpt-4-turbo-preview":case"gpt-4-turbo-2024-04-09":case"gpt-4-0125-preview":case"gpt-4-1106-preview":return 128e3;case"gpt-4-32k":case"gpt-4-32k-0314":case"gpt-4-32k-0613":return 32768;case"gpt-4":case"gpt-4-0314":case"gpt-4-0613":return 8192;case"gpt-3.5-turbo-16k":case"gpt-3.5-turbo-16k-0613":return 16384;case"gpt-3.5-turbo":case"gpt-3.5-turbo-0301":case"gpt-3.5-turbo-0613":case"gpt-3.5-turbo-1106":case"gpt-3.5-turbo-0125":return 4096;case"text-davinci-003":case"text-davinci-002":return 4097;case"text-davinci-001":return 2049;case"text-curie-001":case"text-babbage-001":case"text-ada-001":return 2048;case"code-davinci-002":case"code-davinci-001":return 8e3;case"code-cushman-001":return 2048;case"claude-3-5-sonnet-20241022":case"claude-3-5-sonnet-20240620":case"claude-3-opus-20240229":case"claude-3-sonnet-20240229":case"claude-3-haiku-20240307":case"claude-2.1":return 2e5;case"claude-2.0":case"claude-instant-1.2":return 1e5;case"gemini-1.5-pro":case"gemini-1.5-pro-latest":case"gemini-1.5-flash":case"gemini-1.5-flash-latest":return 1e6;case"gemini-pro":case"gemini-pro-vision":return 32768;default:return 4097}};function Xo(t){return typeof t!="object"||!t?!1:!!("type"in t&&t.type==="function"&&"function"in t&&typeof t.function=="object"&&t.function&&"name"in t.function&&"parameters"in t.function)}const Sz=async({prompt:t,modelName:e})=>{let n;try{n=(await qy(Mf(e))).encode(t).length}catch{console.warn("Failed to calculate number of tokens, falling back to approximate count"),n=Math.ceil(t.length/4)}return mx(e)-n},Az=()=>!1;var Gy=class extends ze{constructor(e){super(e);m(this,"verbose");m(this,"callbacks");m(this,"tags");m(this,"metadata");this.verbose=e.verbose??Az(),this.callbacks=e.callbacks,this.tags=e.tags??[],this.metadata=e.metadata??{},this._addVersion("@langchain/core","1.1.48")}get lc_attributes(){return{callbacks:void 0,verbose:void 0}}_addVersion(e,n){var s;const r=(s=this.metadata)==null?void 0:s.versions;this.metadata={...this.metadata,versions:{...typeof r=="object"&&r!==null?r:{},[e]:n}}}},Jy=class extends Gy{constructor({callbacks:e,callbackManager:n,...r}){const{cache:s,...i}=r;super({callbacks:e??n,...i});m(this,"caller");m(this,"cache");m(this,"_encoding");typeof s=="object"?this.cache=s:s?this.cache=XI.global():this.cache=void 0,this.caller=new _l(r??{})}get callKeys(){return["stop","timeout","signal","tags","metadata","callbacks"]}async getNumTokens(e){let n;typeof e=="string"?n=e:n=e.map(s=>typeof s=="string"?s:s.type==="text"&&"text"in s?s.text:"").join("");let r=Math.ceil(n.length/4);if(!this._encoding)try{this._encoding=await qy("modelName"in this?Mf(this.modelName):"gpt2")}catch(s){console.warn("Failed to calculate number of tokens, falling back to approximate count",s)}if(this._encoding)try{r=this._encoding.encode(n).length}catch(s){console.warn("Failed to calculate number of tokens, falling back to approximate count",s)}return r}static _convertInputToPromptValue(e){return typeof e=="string"?new Wy(e):Array.isArray(e)?new Zy(e.map(_s)):e}_identifyingParams(){return{}}_getSerializedCacheKeyParametersForCall({config:e,...n}){const r={...this._identifyingParams(),...n,_type:this._llmType(),_model:this._modelType()};return Object.entries(r).filter(([s,i])=>i!==void 0).map(([s,i])=>`${s}:${JSON.stringify(i)}`).sort().join(",")}serialize(){return{...this._identifyingParams(),_type:this._llmType(),_model:this._modelType()}}static async deserialize(e){throw new Error("Use .toJSON() instead")}get profile(){return{}}_filterInvocationParamsForTracing(e){const{tools:n,functions:r,messages:s,response_format:i,...a}=e;return a}},Tz=de({applyPatch:()=>Mo,compare:()=>Af}),Qo=class extends ze{parseResultWithPrompt(t,e,n){return this.parseResult(t,n)}_baseMessageToString(t){return typeof t.content=="string"?t.content:this._baseMessageContentToString(t.content)}_baseMessageContentToString(t){return JSON.stringify(t)}async invoke(t,e){return typeof t=="string"?this._callWithConfig(async(n,r)=>this.parseResult([{text:n}],r==null?void 0:r.callbacks),t,{...e,runType:"parser"}):this._callWithConfig(async(n,r)=>this.parseResult([{message:n,text:this._baseMessageToString(n)}],r==null?void 0:r.callbacks),t,{...e,runType:"parser"})}},ec=class extends Qo{parseResult(t,e){return this.parse(t[0].text,e)}async parseWithPrompt(t,e,n){return this.parse(t,n)}_type(){throw new Error("_type not implemented")}},vn=class extends Error{constructor(e,n,r,s=!1){super(e);m(this,"llmOutput");m(this,"observation");m(this,"sendToLLM");if(this.llmOutput=n,this.observation=r,this.sendToLLM=s,s&&(r===void 0||n===void 0))throw new Error("Arguments 'observation' & 'llmOutput' are required if 'sendToLlm' is true");cl(this,"OUTPUT_PARSING_FAILURE")}},vl=class extends ec{async*_transform(t){for await(const e of t)typeof e=="string"?yield this.parseResult([{text:e}]):yield this.parseResult([{message:e,text:this._baseMessageToString(e)}])}async*transform(t,e){yield*this._transformStreamWithConfig(t,this._transform.bind(this),{...e,runType:"parser"})}},Sl=class extends vl{constructor(e){super(e);m(this,"diff",!1);this.diff=(e==null?void 0:e.diff)??this.diff}async*_transform(e){let n,r;for await(const s of e){if(typeof s!="string"&&typeof s.content!="string")throw new Error("Cannot handle non-string output.");let i;if(Po(s)){if(typeof s.content!="string")throw new Error("Cannot handle non-string message output.");i=new dr({message:s,text:s.content})}else if(Et(s)){if(typeof s.content!="string")throw new Error("Cannot handle non-string message output.");i=new dr({message:wh(s),text:s.content})}else i=new Lo({text:s});r===void 0?r=i:r=r.concat(i);const a=await this.parsePartialResult([r]);a!=null&&!ha(a,n)&&(this.diff?yield this._diff(n,a):yield a,n=a)}}getFormatInstructions(){return""}},Ez=class extends vl{constructor(){super(...arguments);m(this,"lc_namespace",["langchain_core","output_parsers","bytes"]);m(this,"lc_serializable",!0);m(this,"textEncoder",new TextEncoder)}static lc_name(){return"BytesOutputParser"}parse(e){return Promise.resolve(this.textEncoder.encode(e))}getFormatInstructions(){return""}},Al=class extends vl{constructor(){super(...arguments);m(this,"re")}async*_transform(e){let n="";for await(const r of e)if(typeof r=="string"?n+=r:n+=r.content,this.re){const s=[...n.matchAll(this.re)];if(s.length>1){let i=0;for(const a of s.slice(0,-1))yield[a[1]],i+=(a.index??0)+a[0].length;n=n.slice(i)}}else{const s=await this.parse(n);if(s.length>1){for(const i of s.slice(0,-1))yield[i];n=s[s.length-1]}}for(const r of await this.parse(n))yield[r]}},Iz=class extends Al{constructor(){super(...arguments);m(this,"lc_namespace",["langchain_core","output_parsers","list"]);m(this,"lc_serializable",!0)}static lc_name(){return"CommaSeparatedListOutputParser"}async parse(e){try{return e.trim().split(",").map(n=>n.trim())}catch{throw new vn(`Could not parse output: ${e}`,e)}}getFormatInstructions(){return"Your response should be a list of comma separated values, eg: `foo, bar, baz`"}},xz=class extends Al{constructor({length:e,separator:n}){super(...arguments);m(this,"lc_namespace",["langchain_core","output_parsers","list"]);m(this,"length");m(this,"separator");this.length=e,this.separator=n||","}async parse(e){try{const n=e.trim().split(this.separator).map(r=>r.trim());if(this.length!==void 0&&n.length!==this.length)throw new vn(`Incorrect number of items. Expected ${this.length}, got ${n.length}.`);return n}catch(n){throw Object.getPrototypeOf(n)===vn.prototype?n:new vn(`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\`)`}},kz=class extends Al{constructor(){super(...arguments);m(this,"lc_namespace",["langchain_core","output_parsers","list"]);m(this,"lc_serializable",!0);m(this,"re",/\d+\.\s([^\n]+)/g)}static lc_name(){return"NumberedListOutputParser"}getFormatInstructions(){return`Your response should be a numbered list with each item on a new line. For example:
|
|
138
|
-
|
|
139
|
-
1. foo
|
|
140
|
-
|
|
141
|
-
2. bar
|
|
142
|
-
|
|
143
|
-
3. baz`}async parse(e){return[...e.matchAll(this.re)??[]].map(n=>n[1])}},Cz=class extends Al{constructor(){super(...arguments);m(this,"lc_namespace",["langchain_core","output_parsers","list"]);m(this,"lc_serializable",!0);m(this,"re",/^\s*[-*]\s([^\n]+)$/gm)}static lc_name(){return"NumberedListOutputParser"}getFormatInstructions(){return`Your response should be a numbered list with each item on a new line. For example:
|
|
144
|
-
|
|
145
|
-
1. foo
|
|
146
|
-
|
|
147
|
-
2. bar
|
|
148
|
-
|
|
149
|
-
3. baz`}async parse(e){return[...e.matchAll(this.re)??[]].map(n=>n[1])}},Oz=class extends vl{constructor(){super(...arguments);m(this,"lc_namespace",["langchain_core","output_parsers","string"]);m(this,"lc_serializable",!0)}static lc_name(){return"StrOutputParser"}parse(e){return Promise.resolve(e)}getFormatInstructions(){return""}_textContentToString(e){return e.text}_imageUrlContentToString(e){throw new Error('Cannot coerce a multimodal "image_url" message part into a string.')}_messageContentToString(e){switch(e.type){case"text":case"text_delta":if("text"in e)return this._textContentToString(e);break;case"image_url":if("image_url"in e)return this._imageUrlContentToString(e);break;case"reasoning":case"thinking":case"redacted_thinking":return"";default:throw new Error(`Cannot coerce "${e.type}" message part into a string.`)}throw new Error(`Invalid content type: ${e.type}`)}_baseMessageContentToString(e){return e.reduce((n,r)=>n+this._messageContentToString(r),"")}},Yy=class extends Sl{constructor(){super(...arguments);m(this,"lc_namespace",["langchain_core","output_parsers"]);m(this,"lc_serializable",!0)}static lc_name(){return"JsonOutputParser"}_concatOutputChunks(e,n){return this.diff?super._concatOutputChunks(e,n):n}_diff(e,n){if(n)return e?Af(e,n):[{op:"replace",path:"",value:n}]}async parsePartialResult(e){return _h(e[0].text)}async parse(e){return _h(e,JSON.parse)}getFormatInstructions(){return""}_baseMessageToString(e){return e.text}},gx=class extends ec{constructor(e){super();m(this,"lc_namespace",["langchain","output_parsers","standard_schema"]);m(this,"schema");this.schema=e}static lc_name(){return"StandardSchemaOutputParser"}static fromSerializableSchema(e){return new this(e)}async parse(e){try{const n=_h(e,JSON.parse),r=await this.schema["~standard"].validate(n);if(r.issues)throw new Error(`Validation failed: ${JSON.stringify(r.issues)}`);return r.value}catch(n){throw new vn(`Failed to parse. Text: "${e}". Error: ${n}`,e)}}_baseMessageToString(e){return e.text}getFormatInstructions(){return""}},Xy=class extends ec{constructor(e){super(e);m(this,"lc_namespace",["langchain","output_parsers","structured"]);this.schema=e}static lc_name(){return"StructuredOutputParser"}toJSON(){return this.toJSONNotImplemented()}static fromZodSchema(e){return new this(e)}static fromNamesAndDescriptions(e){const n=Vr(Object.fromEntries(Object.entries(e).map(([r,s])=>[r,tr().describe(s)])));return new this(n)}getFormatInstructions(){return`You must format your output as a JSON value that adheres to a given "JSON Schema" instance.
|
|
150
|
-
|
|
151
|
-
"JSON Schema" is a declarative language that allows you to annotate and validate JSON documents.
|
|
152
|
-
|
|
153
|
-
For example, the example "JSON Schema" instance {{"properties": {{"foo": {{"description": "a list of test words", "type": "array", "items": {{"type": "string"}}}}}}, "required": ["foo"]}}
|
|
154
|
-
would match an object with one required property, "foo". The "type" property specifies "foo" must be an "array", and the "description" property semantically describes it as "a list of test words". The items within "foo" must be strings.
|
|
155
|
-
Thus, the object {{"foo": ["bar", "baz"]}} is a well-formatted instance of this example "JSON Schema". The object {{"properties": {{"foo": ["bar", "baz"]}}}} is not well-formatted.
|
|
156
|
-
|
|
157
|
-
Your output will be parsed and type-checked according to the provided schema instance, so make sure all fields in your output match the schema exactly and there are no trailing commas!
|
|
158
|
-
|
|
159
|
-
Here is the JSON Schema instance your output must adhere to. Include the enclosing markdown codeblock:
|
|
160
|
-
\`\`\`json
|
|
161
|
-
${JSON.stringify(mt(this.schema))}
|
|
162
|
-
\`\`\`
|
|
163
|
-
`}async parse(e){var n,r;try{const s=e.trim(),i=(((n=s.match(/^```(?:json)?\s*([\s\S]*?)```/))==null?void 0:n[1])||((r=s.match(/```json\s*([\s\S]*?)```/))==null?void 0:r[1])||s).replace(/"([^"\\]*(\\.[^"\\]*)*)"/g,(a,o)=>`"${o.replace(/\n/g,"\\n")}"`).replace(/\n/g,"");return await kf(this.schema,JSON.parse(i))}catch(s){throw new vn(`Failed to parse. Text: "${e}". Error: ${s}`,e)}}_baseMessageToString(e){return e.text}},_x=class extends Xy{static lc_name(){return"JsonMarkdownStructuredOutputParser"}getFormatInstructions(t){const e=(t==null?void 0:t.interpolationDepth)??1;if(e<1)throw new Error("f string interpolation depth must be at least 1");return`Return a markdown code snippet with a JSON object formatted to look like:
|
|
164
|
-
\`\`\`json
|
|
165
|
-
${this._schemaToInstruction(mt(this.schema)).replaceAll("{","{".repeat(e)).replaceAll("}","}".repeat(e))}
|
|
166
|
-
\`\`\``}_schemaToInstruction(t,e=2){const n=t;if("type"in n){let r=!1,s;if(Array.isArray(n.type)){const o=n.type.findIndex(c=>c==="null");o!==-1&&(r=!0,n.type.splice(o,1)),s=n.type.join(" | ")}else s=n.type;if(n.type==="object"&&n.properties){const o=n.description?` // ${n.description}`:"";return`{
|
|
167
|
-
${Object.entries(n.properties).map(([c,u])=>{var d;const l=(d=n.required)!=null&&d.includes(c)?"":" (optional)";return`${" ".repeat(e)}"${c}": ${this._schemaToInstruction(u,e+2)}${l}`}).join(`
|
|
168
|
-
`)}
|
|
169
|
-
${" ".repeat(e-2)}}${o}`}if(n.type==="array"&&n.items){const o=n.description?` // ${n.description}`:"";return`array[
|
|
170
|
-
${" ".repeat(e)}${this._schemaToInstruction(n.items,e+2)}
|
|
171
|
-
${" ".repeat(e-2)}] ${o}`}const i=r?" (nullable)":"",a=n.description?` // ${n.description}`:"";return`${s}${a}${i}`}if("anyOf"in n)return n.anyOf.map(r=>this._schemaToInstruction(r,e)).join(`
|
|
172
|
-
${" ".repeat(e-2)}`);throw new Error("unsupported schema type")}static fromZodSchema(t){return new this(t)}static fromNamesAndDescriptions(t){const e=Vr(Object.fromEntries(Object.entries(t).map(([n,r])=>[n,tr().describe(r)])));return new this(e)}},$z=class extends ec{constructor({inputSchema:e}){super(...arguments);m(this,"structuredInputParser");this.structuredInputParser=new _x(e)}async parse(e){let n;try{n=await this.structuredInputParser.parse(e)}catch(r){throw new vn(`Failed to parse. Text: "${e}". Error: ${r}`,e)}return this.outputProcessor(n)}getFormatInstructions(){return this.structuredInputParser.getFormatInstructions()}};const Rz=function(){const t={};t.parser=function(I,T){return new n(I,T)},t.SAXParser=n,t.SAXStream=u,t.createStream=c,t.MAX_BUFFER_LENGTH=64*1024;const e=["comment","sgmlDecl","textNode","tagName","doctype","procInstName","procInstBody","entity","attribName","attribValue","cdata","script"];t.EVENTS=["text","processinginstruction","sgmldeclaration","doctype","comment","opentagstart","attribute","opentag","closetag","opencdata","cdata","closecdata","error","end","ready","script","opennamespace","closenamespace"];function n(I,T){if(!(this instanceof n))return new n(I,T);var L=this;s(L),L.q=L.c="",L.bufferCheckPosition=t.MAX_BUFFER_LENGTH,L.opt=T||{},L.opt.lowercase=L.opt.lowercase||L.opt.lowercasetags,L.looseCase=L.opt.lowercase?"toLowerCase":"toUpperCase",L.tags=[],L.closed=L.closedRoot=L.sawRoot=!1,L.tag=L.error=null,L.strict=!!I,L.noscript=!!(I||L.opt.noscript),L.state=E.BEGIN,L.strictEntities=L.opt.strictEntities,L.ENTITIES=L.strictEntities?Object.create(t.XML_ENTITIES):Object.create(t.ENTITIES),L.attribList=[],L.opt.xmlns&&(L.ns=Object.create(p)),L.trackPosition=L.opt.position!==!1,L.trackPosition&&(L.position=L.line=L.column=0),k(L,"onready")}Object.create||(Object.create=function(I){function T(){}return T.prototype=I,new T}),Object.keys||(Object.keys=function(I){var T=[];for(var L in I)I.hasOwnProperty(L)&&T.push(L);return T});function r(I){for(var T=Math.max(t.MAX_BUFFER_LENGTH,10),L=0,O=0,ge=e.length;O<ge;O++){var Ee=I[e[O]].length;if(Ee>T)switch(e[O]){case"textNode":D(I);break;case"cdata":C(I,"oncdata",I.cdata),I.cdata="";break;case"script":C(I,"onscript",I.script),I.script="";break;default:z(I,"Max buffer length exceeded: "+e[O])}L=Math.max(L,Ee)}I.bufferCheckPosition=t.MAX_BUFFER_LENGTH-L+I.position}function s(I){for(var T=0,L=e.length;T<L;T++)I[e[T]]=""}function i(I){D(I),I.cdata!==""&&(C(I,"oncdata",I.cdata),I.cdata=""),I.script!==""&&(C(I,"onscript",I.script),I.script="")}n.prototype={end:function(){q(this)},write:ue,resume:function(){return this.error=null,this},close:function(){return this.write(null)},flush:function(){i(this)}};var a=ReadableStream;a||(a=function(){});var o=t.EVENTS.filter(function(I){return I!=="error"&&I!=="end"});function c(I,T){return new u(I,T)}function u(I,T){if(!(this instanceof u))return new u(I,T);a.apply(this),this._parser=new n(I,T),this.writable=!0,this.readable=!0;var L=this;this._parser.onend=function(){L.emit("end")},this._parser.onerror=function(O){L.emit("error",O),L._parser.error=null},this._decoder=null,o.forEach(function(O){Object.defineProperty(L,"on"+O,{get:function(){return L._parser["on"+O]},set:function(ge){if(!ge)return L.removeAllListeners(O),L._parser["on"+O]=ge,ge;L.on(O,ge)},enumerable:!0,configurable:!1})})}u.prototype=Object.create(a.prototype,{constructor:{value:u}}),u.prototype.write=function(I){return this._parser.write(I.toString()),this.emit("data",I),!0},u.prototype.end=function(I){return I&&I.length&&this.write(I),this._parser.end(),!0},u.prototype.on=function(I,T){var L=this;return!L._parser["on"+I]&&o.indexOf(I)!==-1&&(L._parser["on"+I]=function(){var O=arguments.length===1?[arguments[0]]:Array.apply(null,arguments);O.splice(0,0,I),L.emit.apply(L,O)}),a.prototype.on.call(L,I,T)};var l="[CDATA[",d="DOCTYPE",f="http://www.w3.org/XML/1998/namespace",h="http://www.w3.org/2000/xmlns/",p={xml:f,xmlns:h},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]/,y=/[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040.\d-]/,b=/[#:_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]/,_=/[#:_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 w(I){return I===" "||I===`
|
|
173
|
-
`||I==="\r"||I===" "}function v(I){return I==='"'||I==="'"}function A(I){return I===">"||w(I)}function S(I,T){return I.test(T)}function x(I,T){return!S(I,T)}var E=0;t.STATE={BEGIN:E++,BEGIN_WHITESPACE:E++,TEXT:E++,TEXT_ENTITY:E++,OPEN_WAKA:E++,SGML_DECL:E++,SGML_DECL_QUOTED:E++,DOCTYPE:E++,DOCTYPE_QUOTED:E++,DOCTYPE_DTD:E++,DOCTYPE_DTD_QUOTED:E++,COMMENT_STARTING:E++,COMMENT:E++,COMMENT_ENDING:E++,COMMENT_ENDED:E++,CDATA:E++,CDATA_ENDING:E++,CDATA_ENDING_2:E++,PROC_INST:E++,PROC_INST_BODY:E++,PROC_INST_ENDING:E++,OPEN_TAG:E++,OPEN_TAG_SLASH:E++,ATTRIB:E++,ATTRIB_NAME:E++,ATTRIB_NAME_SAW_WHITE:E++,ATTRIB_VALUE:E++,ATTRIB_VALUE_QUOTED:E++,ATTRIB_VALUE_CLOSED:E++,ATTRIB_VALUE_UNQUOTED:E++,ATTRIB_VALUE_ENTITY_Q:E++,ATTRIB_VALUE_ENTITY_U:E++,CLOSE_TAG:E++,CLOSE_TAG_SAW_WHITE:E++,SCRIPT:E++,SCRIPT_ENDING:E++},t.XML_ENTITIES={amp:"&",gt:">",lt:"<",quot:'"',apos:"'"},t.ENTITIES={amp:"&",gt:">",lt:"<",quot:'"',apos:"'",AElig:198,Aacute:193,Acirc:194,Agrave:192,Aring:197,Atilde:195,Auml:196,Ccedil:199,ETH:208,Eacute:201,Ecirc:202,Egrave:200,Euml:203,Iacute:205,Icirc:206,Igrave:204,Iuml:207,Ntilde:209,Oacute:211,Ocirc:212,Ograve:210,Oslash:216,Otilde:213,Ouml:214,THORN:222,Uacute:218,Ucirc:219,Ugrave:217,Uuml:220,Yacute:221,aacute:225,acirc:226,aelig:230,agrave:224,aring:229,atilde:227,auml:228,ccedil:231,eacute:233,ecirc:234,egrave:232,eth:240,euml:235,iacute:237,icirc:238,igrave:236,iuml:239,ntilde:241,oacute:243,ocirc:244,ograve:242,oslash:248,otilde:245,ouml:246,szlig:223,thorn:254,uacute:250,ucirc:251,ugrave:249,uuml:252,yacute:253,yuml:255,copy:169,reg:174,nbsp:160,iexcl:161,cent:162,pound:163,curren:164,yen:165,brvbar:166,sect:167,uml:168,ordf:170,laquo:171,not:172,shy:173,macr:175,deg:176,plusmn:177,sup1:185,sup2:178,sup3:179,acute:180,micro:181,para:182,middot:183,cedil:184,ordm:186,raquo:187,frac14:188,frac12:189,frac34:190,iquest:191,times:215,divide:247,OElig:338,oelig:339,Scaron:352,scaron:353,Yuml:376,fnof:402,circ:710,tilde:732,Alpha:913,Beta:914,Gamma:915,Delta:916,Epsilon:917,Zeta:918,Eta:919,Theta:920,Iota:921,Kappa:922,Lambda:923,Mu:924,Nu:925,Xi:926,Omicron:927,Pi:928,Rho:929,Sigma:931,Tau:932,Upsilon:933,Phi:934,Chi:935,Psi:936,Omega:937,alpha:945,beta:946,gamma:947,delta:948,epsilon:949,zeta:950,eta:951,theta:952,iota:953,kappa:954,lambda:955,mu:956,nu:957,xi:958,omicron:959,pi:960,rho:961,sigmaf:962,sigma:963,tau:964,upsilon:965,phi:966,chi:967,psi:968,omega:969,thetasym:977,upsih:978,piv:982,ensp:8194,emsp:8195,thinsp:8201,zwnj:8204,zwj:8205,lrm:8206,rlm:8207,ndash:8211,mdash:8212,lsquo:8216,rsquo:8217,sbquo:8218,ldquo:8220,rdquo:8221,bdquo:8222,dagger:8224,Dagger:8225,bull:8226,hellip:8230,permil:8240,prime:8242,Prime:8243,lsaquo:8249,rsaquo:8250,oline:8254,frasl:8260,euro:8364,image:8465,weierp:8472,real:8476,trade:8482,alefsym:8501,larr:8592,uarr:8593,rarr:8594,darr:8595,harr:8596,crarr:8629,lArr:8656,uArr:8657,rArr:8658,dArr:8659,hArr:8660,forall:8704,part:8706,exist:8707,empty:8709,nabla:8711,isin:8712,notin:8713,ni:8715,prod:8719,sum:8721,minus:8722,lowast:8727,radic:8730,prop:8733,infin:8734,ang:8736,and:8743,or:8744,cap:8745,cup:8746,int:8747,there4:8756,sim:8764,cong:8773,asymp:8776,ne:8800,equiv:8801,le:8804,ge:8805,sub:8834,sup:8835,nsub:8836,sube:8838,supe:8839,oplus:8853,otimes:8855,perp:8869,sdot:8901,lceil:8968,rceil:8969,lfloor:8970,rfloor:8971,lang:9001,rang:9002,loz:9674,spades:9824,clubs:9827,hearts:9829,diams:9830},Object.keys(t.ENTITIES).forEach(function(I){var T=t.ENTITIES[I],L=typeof T=="number"?String.fromCharCode(T):T;t.ENTITIES[I]=L});for(var $ in t.STATE)t.STATE[t.STATE[$]]=$;E=t.STATE;function k(I,T,L){I[T]&&I[T](L)}function C(I,T,L){I.textNode&&D(I),k(I,T,L)}function D(I){I.textNode=B(I.opt,I.textNode),I.textNode&&k(I,"ontext",I.textNode),I.textNode=""}function B(I,T){return I.trim&&(T=T.trim()),I.normalize&&(T=T.replace(/\s+/g," ")),T}function z(I,T){return D(I),I.trackPosition&&(T+=`
|
|
174
|
-
Line: `+I.line+`
|
|
175
|
-
Column: `+I.column+`
|
|
176
|
-
Char: `+I.c),T=new Error(T),I.error=T,k(I,"onerror",T),I}function q(I){return I.sawRoot&&!I.closedRoot&&W(I,"Unclosed root tag"),I.state!==E.BEGIN&&I.state!==E.BEGIN_WHITESPACE&&I.state!==E.TEXT&&z(I,"Unexpected end"),D(I),I.c="",I.closed=!0,k(I,"onend"),n.call(I,I.strict,I.opt),I}function W(I,T){if(typeof I!="object"||!(I instanceof n))throw new Error("bad call to strictFail");I.strict&&z(I,T)}function me(I){I.strict||(I.tagName=I.tagName[I.looseCase]());var T=I.tags[I.tags.length-1]||I,L=I.tag={name:I.tagName,attributes:{}};I.opt.xmlns&&(L.ns=T.ns),I.attribList.length=0,C(I,"onopentagstart",L)}function M(I,T){var L=I.indexOf(":")<0?["",I]:I.split(":"),O=L[0],ge=L[1];return T&&I==="xmlns"&&(O="xmlns",ge=""),{prefix:O,local:ge}}function Z(I){if(I.strict||(I.attribName=I.attribName[I.looseCase]()),I.attribList.indexOf(I.attribName)!==-1||I.tag.attributes.hasOwnProperty(I.attribName)){I.attribName=I.attribValue="";return}if(I.opt.xmlns){var T=M(I.attribName,!0),L=T.prefix,O=T.local;if(L==="xmlns")if(O==="xml"&&I.attribValue!==f)W(I,"xml: prefix must be bound to "+f+`
|
|
177
|
-
Actual: `+I.attribValue);else if(O==="xmlns"&&I.attribValue!==h)W(I,"xmlns: prefix must be bound to "+h+`
|
|
178
|
-
Actual: `+I.attribValue);else{var ge=I.tag,Ee=I.tags[I.tags.length-1]||I;ge.ns===Ee.ns&&(ge.ns=Object.create(Ee.ns)),ge.ns[O]=I.attribValue}I.attribList.push([I.attribName,I.attribValue])}else I.tag.attributes[I.attribName]=I.attribValue,C(I,"onattribute",{name:I.attribName,value:I.attribValue});I.attribName=I.attribValue=""}function re(I,T){if(I.opt.xmlns){var L=I.tag,O=M(I.tagName);L.prefix=O.prefix,L.local=O.local,L.uri=L.ns[O.prefix]||"",L.prefix&&!L.uri&&(W(I,"Unbound namespace prefix: "+JSON.stringify(I.tagName)),L.uri=O.prefix);var ge=I.tags[I.tags.length-1]||I;L.ns&&ge.ns!==L.ns&&Object.keys(L.ns).forEach(function(_n){C(I,"onopennamespace",{prefix:_n,uri:L.ns[_n]})});for(var Ee=0,nt=I.attribList.length;Ee<nt;Ee++){var We=I.attribList[Ee],lt=We[0],vt=We[1],Pe=M(lt,!0),$t=Pe.prefix,gn=Pe.local,_r=$t===""?"":L.ns[$t]||"",j={name:lt,value:vt,prefix:$t,local:gn,uri:_r};$t&&$t!=="xmlns"&&!_r&&(W(I,"Unbound namespace prefix: "+JSON.stringify($t)),j.uri=$t),I.tag.attributes[lt]=j,C(I,"onattribute",j)}I.attribList.length=0}I.tag.isSelfClosing=!!T,I.sawRoot=!0,I.tags.push(I.tag),C(I,"onopentag",I.tag),T||(!I.noscript&&I.tagName.toLowerCase()==="script"?I.state=E.SCRIPT:I.state=E.TEXT,I.tag=null,I.tagName=""),I.attribName=I.attribValue="",I.attribList.length=0}function ae(I){if(!I.tagName){W(I,"Weird empty close tag."),I.textNode+="</>",I.state=E.TEXT;return}if(I.script){if(I.tagName!=="script"){I.script+="</"+I.tagName+">",I.tagName="",I.state=E.SCRIPT;return}C(I,"onscript",I.script),I.script=""}var T=I.tags.length,L=I.tagName;I.strict||(L=L[I.looseCase]());for(var O=L;T--&&I.tags[T].name!==O;)W(I,"Unexpected close tag");if(T<0){W(I,"Unmatched closing tag: "+I.tagName),I.textNode+="</"+I.tagName+">",I.state=E.TEXT;return}I.tagName=L;for(var ge=I.tags.length;ge-- >T;){var Ee=I.tag=I.tags.pop();I.tagName=I.tag.name,C(I,"onclosetag",I.tagName);var nt={};for(var We in Ee.ns)nt[We]=Ee.ns[We];var lt=I.tags[I.tags.length-1]||I;I.opt.xmlns&&Ee.ns!==lt.ns&&Object.keys(Ee.ns).forEach(function(vt){var Pe=Ee.ns[vt];C(I,"onclosenamespace",{prefix:vt,uri:Pe})})}T===0&&(I.closedRoot=!0),I.tagName=I.attribValue=I.attribName="",I.attribList.length=0,I.state=E.TEXT}function X(I){var T=I.entity,L=T.toLowerCase(),O,ge="";return I.ENTITIES[T]?I.ENTITIES[T]:I.ENTITIES[L]?I.ENTITIES[L]:(T=L,T.charAt(0)==="#"&&(T.charAt(1)==="x"?(T=T.slice(2),O=parseInt(T,16),ge=O.toString(16)):(T=T.slice(1),O=parseInt(T,10),ge=O.toString(10))),T=T.replace(/^0+/,""),isNaN(O)||ge.toLowerCase()!==T?(W(I,"Invalid character entity"),"&"+I.entity+";"):String.fromCodePoint(O))}function se(I,T){T==="<"?(I.state=E.OPEN_WAKA,I.startTagPosition=I.position):w(T)||(W(I,"Non-whitespace before first tag."),I.textNode=T,I.state=E.TEXT)}function Se(I,T){var L="";return T<I.length&&(L=I.charAt(T)),L}function ue(I){var T=this;if(this.error)throw this.error;if(T.closed)return z(T,"Cannot write after close. Assign an onready handler.");if(I===null)return q(T);typeof I=="object"&&(I=I.toString());for(var L=0,O="";O=Se(I,L++),T.c=O,!!O;)switch(T.trackPosition&&(T.position++,O===`
|
|
179
|
-
`?(T.line++,T.column=0):T.column++),T.state){case E.BEGIN:if(T.state=E.BEGIN_WHITESPACE,O==="\uFEFF")continue;se(T,O);continue;case E.BEGIN_WHITESPACE:se(T,O);continue;case E.TEXT:if(T.sawRoot&&!T.closedRoot){for(var ge=L-1;O&&O!=="<"&&O!=="&";)O=Se(I,L++),O&&T.trackPosition&&(T.position++,O===`
|
|
180
|
-
`?(T.line++,T.column=0):T.column++);T.textNode+=I.substring(ge,L-1)}O==="<"&&!(T.sawRoot&&T.closedRoot&&!T.strict)?(T.state=E.OPEN_WAKA,T.startTagPosition=T.position):(!w(O)&&(!T.sawRoot||T.closedRoot)&&W(T,"Text data outside of root node."),O==="&"?T.state=E.TEXT_ENTITY:T.textNode+=O);continue;case E.SCRIPT:O==="<"?T.state=E.SCRIPT_ENDING:T.script+=O;continue;case E.SCRIPT_ENDING:O==="/"?T.state=E.CLOSE_TAG:(T.script+="<"+O,T.state=E.SCRIPT);continue;case E.OPEN_WAKA:if(O==="!")T.state=E.SGML_DECL,T.sgmlDecl="";else if(!w(O))if(S(g,O))T.state=E.OPEN_TAG,T.tagName=O;else if(O==="/")T.state=E.CLOSE_TAG,T.tagName="";else if(O==="?")T.state=E.PROC_INST,T.procInstName=T.procInstBody="";else{if(W(T,"Unencoded <"),T.startTagPosition+1<T.position){var Ee=T.position-T.startTagPosition;O=new Array(Ee).join(" ")+O}T.textNode+="<"+O,T.state=E.TEXT}continue;case E.SGML_DECL:(T.sgmlDecl+O).toUpperCase()===l?(C(T,"onopencdata"),T.state=E.CDATA,T.sgmlDecl="",T.cdata=""):T.sgmlDecl+O==="--"?(T.state=E.COMMENT,T.comment="",T.sgmlDecl=""):(T.sgmlDecl+O).toUpperCase()===d?(T.state=E.DOCTYPE,(T.doctype||T.sawRoot)&&W(T,"Inappropriately located doctype declaration"),T.doctype="",T.sgmlDecl=""):O===">"?(C(T,"onsgmldeclaration",T.sgmlDecl),T.sgmlDecl="",T.state=E.TEXT):(v(O)&&(T.state=E.SGML_DECL_QUOTED),T.sgmlDecl+=O);continue;case E.SGML_DECL_QUOTED:O===T.q&&(T.state=E.SGML_DECL,T.q=""),T.sgmlDecl+=O;continue;case E.DOCTYPE:O===">"?(T.state=E.TEXT,C(T,"ondoctype",T.doctype),T.doctype=!0):(T.doctype+=O,O==="["?T.state=E.DOCTYPE_DTD:v(O)&&(T.state=E.DOCTYPE_QUOTED,T.q=O));continue;case E.DOCTYPE_QUOTED:T.doctype+=O,O===T.q&&(T.q="",T.state=E.DOCTYPE);continue;case E.DOCTYPE_DTD:T.doctype+=O,O==="]"?T.state=E.DOCTYPE:v(O)&&(T.state=E.DOCTYPE_DTD_QUOTED,T.q=O);continue;case E.DOCTYPE_DTD_QUOTED:T.doctype+=O,O===T.q&&(T.state=E.DOCTYPE_DTD,T.q="");continue;case E.COMMENT:O==="-"?T.state=E.COMMENT_ENDING:T.comment+=O;continue;case E.COMMENT_ENDING:O==="-"?(T.state=E.COMMENT_ENDED,T.comment=B(T.opt,T.comment),T.comment&&C(T,"oncomment",T.comment),T.comment=""):(T.comment+="-"+O,T.state=E.COMMENT);continue;case E.COMMENT_ENDED:O!==">"?(W(T,"Malformed comment"),T.comment+="--"+O,T.state=E.COMMENT):T.state=E.TEXT;continue;case E.CDATA:O==="]"?T.state=E.CDATA_ENDING:T.cdata+=O;continue;case E.CDATA_ENDING:O==="]"?T.state=E.CDATA_ENDING_2:(T.cdata+="]"+O,T.state=E.CDATA);continue;case E.CDATA_ENDING_2:O===">"?(T.cdata&&C(T,"oncdata",T.cdata),C(T,"onclosecdata"),T.cdata="",T.state=E.TEXT):O==="]"?T.cdata+="]":(T.cdata+="]]"+O,T.state=E.CDATA);continue;case E.PROC_INST:O==="?"?T.state=E.PROC_INST_ENDING:w(O)?T.state=E.PROC_INST_BODY:T.procInstName+=O;continue;case E.PROC_INST_BODY:if(!T.procInstBody&&w(O))continue;O==="?"?T.state=E.PROC_INST_ENDING:T.procInstBody+=O;continue;case E.PROC_INST_ENDING:O===">"?(C(T,"onprocessinginstruction",{name:T.procInstName,body:T.procInstBody}),T.procInstName=T.procInstBody="",T.state=E.TEXT):(T.procInstBody+="?"+O,T.state=E.PROC_INST_BODY);continue;case E.OPEN_TAG:S(y,O)?T.tagName+=O:(me(T),O===">"?re(T):O==="/"?T.state=E.OPEN_TAG_SLASH:(w(O)||W(T,"Invalid character in tag name"),T.state=E.ATTRIB));continue;case E.OPEN_TAG_SLASH:O===">"?(re(T,!0),ae(T)):(W(T,"Forward-slash in opening tag not followed by >"),T.state=E.ATTRIB);continue;case E.ATTRIB:if(w(O))continue;O===">"?re(T):O==="/"?T.state=E.OPEN_TAG_SLASH:S(g,O)?(T.attribName=O,T.attribValue="",T.state=E.ATTRIB_NAME):W(T,"Invalid attribute name");continue;case E.ATTRIB_NAME:O==="="?T.state=E.ATTRIB_VALUE:O===">"?(W(T,"Attribute without value"),T.attribValue=T.attribName,Z(T),re(T)):w(O)?T.state=E.ATTRIB_NAME_SAW_WHITE:S(y,O)?T.attribName+=O:W(T,"Invalid attribute name");continue;case E.ATTRIB_NAME_SAW_WHITE:if(O==="=")T.state=E.ATTRIB_VALUE;else{if(w(O))continue;W(T,"Attribute without value"),T.tag.attributes[T.attribName]="",T.attribValue="",C(T,"onattribute",{name:T.attribName,value:""}),T.attribName="",O===">"?re(T):S(g,O)?(T.attribName=O,T.state=E.ATTRIB_NAME):(W(T,"Invalid attribute name"),T.state=E.ATTRIB)}continue;case E.ATTRIB_VALUE:if(w(O))continue;v(O)?(T.q=O,T.state=E.ATTRIB_VALUE_QUOTED):(W(T,"Unquoted attribute value"),T.state=E.ATTRIB_VALUE_UNQUOTED,T.attribValue=O);continue;case E.ATTRIB_VALUE_QUOTED:if(O!==T.q){O==="&"?T.state=E.ATTRIB_VALUE_ENTITY_Q:T.attribValue+=O;continue}Z(T),T.q="",T.state=E.ATTRIB_VALUE_CLOSED;continue;case E.ATTRIB_VALUE_CLOSED:w(O)?T.state=E.ATTRIB:O===">"?re(T):O==="/"?T.state=E.OPEN_TAG_SLASH:S(g,O)?(W(T,"No whitespace between attributes"),T.attribName=O,T.attribValue="",T.state=E.ATTRIB_NAME):W(T,"Invalid attribute name");continue;case E.ATTRIB_VALUE_UNQUOTED:if(!A(O)){O==="&"?T.state=E.ATTRIB_VALUE_ENTITY_U:T.attribValue+=O;continue}Z(T),O===">"?re(T):T.state=E.ATTRIB;continue;case E.CLOSE_TAG:if(T.tagName)O===">"?ae(T):S(y,O)?T.tagName+=O:T.script?(T.script+="</"+T.tagName,T.tagName="",T.state=E.SCRIPT):(w(O)||W(T,"Invalid tagname in closing tag"),T.state=E.CLOSE_TAG_SAW_WHITE);else{if(w(O))continue;x(g,O)?T.script?(T.script+="</"+O,T.state=E.SCRIPT):W(T,"Invalid tagname in closing tag."):T.tagName=O}continue;case E.CLOSE_TAG_SAW_WHITE:if(w(O))continue;O===">"?ae(T):W(T,"Invalid characters in closing tag");continue;case E.TEXT_ENTITY:case E.ATTRIB_VALUE_ENTITY_Q:case E.ATTRIB_VALUE_ENTITY_U:var nt,We;switch(T.state){case E.TEXT_ENTITY:nt=E.TEXT,We="textNode";break;case E.ATTRIB_VALUE_ENTITY_Q:nt=E.ATTRIB_VALUE_QUOTED,We="attribValue";break;case E.ATTRIB_VALUE_ENTITY_U:nt=E.ATTRIB_VALUE_UNQUOTED,We="attribValue";break}if(O===";")if(T.opt.unparsedEntities){var lt=X(T);T.entity="",T.state=nt,T.write(lt)}else T[We]+=X(T),T.entity="",T.state=nt;else S(T.entity.length?_:b,O)?T.entity+=O:(W(T,"Invalid character in entity name"),T[We]+="&"+T.entity+O,T.entity="",T.state=nt);continue;default:throw new Error(T,"Unknown state: "+T.state)}return T.position>=T.bufferCheckPosition&&r(T),T}/*! http://mths.be/fromcodepoint v0.1.0 by @mathias */return String.fromCodePoint||function(){var I=String.fromCharCode,T=Math.floor,L=function(){var O=16384,ge=[],Ee,nt,We=-1,lt=arguments.length;if(!lt)return"";for(var vt="";++We<lt;){var Pe=Number(arguments[We]);if(!isFinite(Pe)||Pe<0||Pe>1114111||T(Pe)!==Pe)throw RangeError("Invalid code point: "+Pe);Pe<=65535?ge.push(Pe):(Pe-=65536,Ee=(Pe>>10)+55296,nt=Pe%1024+56320,ge.push(Ee,nt)),(We+1===lt||ge.length>O)&&(vt+=I.apply(null,ge),ge.length=0)}return vt};Object.defineProperty?Object.defineProperty(String,"fromCodePoint",{value:L,configurable:!0,writable:!0}):String.fromCodePoint=L}(),t},Pz=Rz(),Hg=`The output should be formatted as a XML file.
|
|
181
|
-
1. Output should conform to the tags below.
|
|
182
|
-
2. If tags are not given, make them on your own.
|
|
183
|
-
3. Remember to always open and close all the tags.
|
|
184
|
-
|
|
185
|
-
As an example, for the tags ["foo", "bar", "baz"]:
|
|
186
|
-
1. String "<foo>
|
|
187
|
-
<bar>
|
|
188
|
-
<baz></baz>
|
|
189
|
-
</bar>
|
|
190
|
-
</foo>" is a well-formatted instance of the schema.
|
|
191
|
-
2. String "<foo>
|
|
192
|
-
<bar>
|
|
193
|
-
</foo>" is a badly-formatted instance.
|
|
194
|
-
3. String "<foo>
|
|
195
|
-
<tag>
|
|
196
|
-
</tag>
|
|
197
|
-
</foo>" is a badly-formatted instance.
|
|
198
|
-
|
|
199
|
-
Here are the output tags:
|
|
200
|
-
\`\`\`
|
|
201
|
-
{tags}
|
|
202
|
-
\`\`\``;var Nz=class extends Sl{constructor(e){super(e);m(this,"tags");m(this,"lc_namespace",["langchain_core","output_parsers"]);m(this,"lc_serializable",!0);this.tags=e==null?void 0:e.tags}static lc_name(){return"XMLOutputParser"}_diff(e,n){if(n)return e?Af(e,n):[{op:"replace",path:"",value:n}]}async parsePartialResult(e){return Vg(e[0].text)}async parse(e){return Vg(e)}getFormatInstructions(){var e;return this.tags&&this.tags.length>0?Hg.replace("{tags}",((e=this.tags)==null?void 0:e.join(", "))??""):Hg}};const Mz=t=>t.split(`
|
|
203
|
-
`).map(e=>e.replace(/^\s+/,"")).join(`
|
|
204
|
-
`).trim(),yx=t=>{if(Object.keys(t).length===0)return{};const e={};return t.children.length>0?(e[t.name]=t.children.map(yx),e):(e[t.name]=t.text??void 0,e)};function Vg(t){const e=Mz(t),n=Pz.parser(!0);let r={};const s=[];n.onopentag=o=>{const c={name:o.name,attributes:o.attributes,children:[],text:"",isSelfClosing:o.isSelfClosing};s.length>0?s[s.length-1].children.push(c):r=c,o.isSelfClosing||s.push(c)},n.onclosetag=()=>{if(s.length>0){const o=s.pop();s.length===0&&o&&(r=o)}},n.ontext=o=>{if(s.length>0){const c=s[s.length-1];c.text+=o}},n.onattribute=o=>{if(s.length>0){const c=s[s.length-1];c.attributes[o.name]=o.value}};const i=/```(xml)?(.*)```/s.exec(e),a=i?i[2]:e;return n.write(a).close(),r&&r.name==="?xml"&&(r=r.children[0]),yx(r)}var Lz=de({AsymmetricStructuredOutputParser:()=>$z,BaseCumulativeTransformOutputParser:()=>Sl,BaseLLMOutputParser:()=>Qo,BaseOutputParser:()=>ec,BaseTransformOutputParser:()=>vl,BytesOutputParser:()=>Ez,CommaSeparatedListOutputParser:()=>Iz,CustomListOutputParser:()=>xz,JsonMarkdownStructuredOutputParser:()=>_x,JsonOutputParser:()=>Yy,ListOutputParser:()=>Al,MarkdownListOutputParser:()=>Cz,NumberedListOutputParser:()=>kz,OutputParserException:()=>vn,StandardSchemaOutputParser:()=>gx,StringOutputParser:()=>Oz,StructuredOutputParser:()=>Xy,XMLOutputParser:()=>Nz,XML_FORMAT_INSTRUCTIONS:()=>Hg,parseJsonMarkdown:()=>_h,parsePartialJson:()=>$o,parseXMLMarkdown:()=>Vg}),jz=de({extendInteropZodObject:()=>wI,getInteropZodDefaultGetter:()=>IU,getInteropZodObjectShape:()=>Do,getSchemaDescription:()=>jo,interopParse:()=>Wa,interopParseAsync:()=>kf,interopSafeParse:()=>TU,interopSafeParseAsync:()=>xf,interopZodObjectMakeFieldsOptional:()=>CU,interopZodObjectPartial:()=>ou,interopZodObjectPassthrough:()=>wg,interopZodObjectStrict:()=>Oh,interopZodTransformInputSchema:()=>bI,isInteropZodError:()=>vI,isInteropZodLiteral:()=>AU,isInteropZodObject:()=>rr,isInteropZodSchema:()=>Wt,isShapelessZodSchema:()=>EU,isSimpleStringZodSchema:()=>xy,isZodArrayV4:()=>Of,isZodLiteralV3:()=>mI,isZodLiteralV4:()=>gI,isZodNullableV4:()=>yI,isZodObjectV3:()=>Cf,isZodObjectV4:()=>ys,isZodOptionalV4:()=>_I,isZodSchema:()=>SU,isZodSchemaV3:()=>Lt,isZodSchemaV4:()=>bt});function Lf(t,e){if(t.function===void 0)return;let n;if(e!=null&&e.partial)try{n=$o(t.function.arguments??"{}")}catch{return}else try{n=JSON.parse(t.function.arguments)}catch(s){throw new vn([`Function "${t.function.name}" arguments:`,"",t.function.arguments,"","are not valid JSON.",`Error: ${s.message}`].join(`
|
|
205
|
-
`))}const r={name:t.function.name,args:n,type:"tool_call"};return e!=null&&e.returnId&&(r.id=t.id),r}function Qy(t){if(t.id===void 0)throw new Error('All OpenAI tool calls must have an "id" field.');return{id:t.id,type:"function",function:{name:t.name,arguments:JSON.stringify(t.args)}}}function fu(t,e){var n,r;return{name:(n=t.function)==null?void 0:n.name,args:(r=t.function)==null?void 0:r.arguments,id:t.id,error:e,type:"invalid_tool_call"}}var wx=class extends Sl{constructor(e){super(e);m(this,"returnId",!1);m(this,"lc_namespace",["langchain","output_parsers","openai_tools"]);m(this,"lc_serializable",!0);this.returnId=(e==null?void 0:e.returnId)??this.returnId}static lc_name(){return"JsonOutputToolsParser"}_diff(){throw new Error("Not supported.")}async parse(){throw new Error("Not implemented.")}async parseResult(e){return await this.parsePartialResult(e,!1)}async parsePartialResult(e,n=!0){var a;const r=e[0].message;let s;if(Cr(r)&&((a=r.tool_calls)!=null&&a.length)?s=r.tool_calls.map(o=>{const{id:c,...u}=o;return this.returnId?{id:c,...u}:u}):r.additional_kwargs.tool_calls!==void 0&&(s=JSON.parse(JSON.stringify(r.additional_kwargs.tool_calls)).map(o=>Lf(o,{returnId:this.returnId,partial:n}))),!s)return[];const i=[];for(const o of s)if(o!==void 0){const c={type:o.name,args:o.args,id:o.id};i.push(c)}return i}},bx=class extends wx{constructor(e){super(e);m(this,"lc_namespace",["langchain","output_parsers","openai_tools"]);m(this,"lc_serializable",!0);m(this,"returnId",!1);m(this,"keyName");m(this,"returnSingle",!1);m(this,"zodSchema");m(this,"serializableSchema");this.keyName=e.keyName,this.returnSingle=e.returnSingle??this.returnSingle,"zodSchema"in e&&(this.zodSchema=e.zodSchema),"serializableSchema"in e&&(this.serializableSchema=e.serializableSchema)}static lc_name(){return"JsonOutputKeyToolsParser"}async _validateResult(e){var r;if(this.serializableSchema!==void 0){const s=await this.serializableSchema["~standard"].validate(e);if(s.issues)throw new vn(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(s.issues)}`,JSON.stringify(e,null,2));return s.value}if(this.zodSchema===void 0)return e;const n=await xf(this.zodSchema,e);if(n.success)return n.data;throw new vn(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify((r=n.error)==null?void 0:r.issues)}`,JSON.stringify(e,null,2))}async parsePartialResult(e){const n=(await super.parsePartialResult(e)).filter(s=>s.type===this.keyName);let r=n;if(n.length)return this.returnId||(r=n.map(s=>s.args)),this.returnSingle?r[0]:r}async parseResult(e){const n=(await super.parsePartialResult(e,!1)).filter(s=>s.type===this.keyName);let r=n;if(n.length)return this.returnId||(r=n.map(s=>s.args)),this.returnSingle?this._validateResult(r[0]):await Promise.all(r.map(s=>this._validateResult(s)))}},Dz=de({assembleStructuredOutputPipeline:()=>tc,createContentParser:()=>Ko,createFunctionCallingParser:()=>Tl});function Ko(t){return Wt(t)?Xy.fromZodSchema(t):Or(t)?gx.fromSerializableSchema(t):new Yy}function Tl(t,e,n){const r=n??bx;return Wt(t)?new r({returnSingle:!0,keyName:e,zodSchema:t}):Or(t)?new r({returnSingle:!0,keyName:e,serializableSchema:t}):new r({returnSingle:!0,keyName:e})}function tc(t,e,n,r){if(!n){const c=t.pipe(e);return r?c.withConfig({runName:r}):c}const s=Ru.assign({parsed:(c,u)=>e.invoke(c.raw,u)}),i=Ru.assign({parsed:()=>null}),a=s.withFallbacks({fallbacks:[i]}),o=fr.from([{raw:t},a]);return r?o.withConfig({runName:r}):o}var Uz=de({ChatModelStream:()=>Uh,ReasoningContentStream:()=>Ax,TextContentStream:()=>vx,ToolCallsStream:()=>Sx,UsageMetadataStream:()=>Tx}),Fz=class{constructor(){m(this,"events",[]);m(this,"finished",!1);m(this,"waiters",[]);m(this,"error",null)}push(t){this.events.push(t);const e=this.waiters.splice(0);for(const n of e)n()}finish(){this.finished=!0;const t=this.waiters.splice(0);for(const e of t)e()}setError(t){this.error=t,this.finished=!0;const e=this.waiters.splice(0);for(const n of e)n()}async*iterate(){if(this.finished){if(this.error)throw this.error;yield*this.events;return}let t=0;for(;;){for(;t<this.events.length;)yield this.events[t],t++;if(this.finished){if(this.error)throw this.error;return}await new Promise(e=>{if(t<this.events.length||this.finished){e();return}this.waiters.push(e)})}}};function Bz(t,e){switch(e.type){case"text-delta":return t.type==="text"?{...t,text:(t.text??"")+e.text}:t;case"reasoning-delta":return t.type==="thinking"?{...t,thinking:(t.thinking??"")+e.reasoning}:t.type==="reasoning"?{...t,reasoning:(t.reasoning??"")+e.reasoning}:t;case"data-delta":return{...t,data:(t.data??"")+e.data};case"block-delta":return{...t,...e.fields};default:throw new Error(`Unknown delta type: ${JSON.stringify(e)}`)}}function Mu(t){if(t.event!=="content-block-delta")return;if("delta"in t&&t.delta)return t.delta;const e=t.content;if(e==null||typeof e!="object")return;const n=e;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 $v(t){if(t==null||typeof t!="object")return;const e=t;if(e.type==="reasoning"&&typeof e.reasoning=="string")return e.reasoning;if(e.type==="thinking"&&typeof e.thinking=="string")return e.thinking}function rd(t){if(t==null||typeof t!="object")return!1;const e=t.type;return e==="reasoning"||e==="thinking"}function po(t){if(t)return{...t,input_tokens:t.input_tokens??0,output_tokens:t.output_tokens??0,total_tokens:t.total_tokens??0}}function zz(t){if(t!=null&&typeof t=="object"&&!Array.isArray(t))return t;if(typeof t!="string"||t.length===0)return{};try{const e=JSON.parse(t);return e!=null&&typeof e=="object"&&!Array.isArray(e)?e:{}}catch{return{}}}function Hz(t){const e=t;if(t.type==="tool_call"||t.type!=="tool_call_chunk"&&t.type!=="tool_use"&&t.type!=="input_json_delta")return t;const n=typeof e.name=="string"?e.name:void 0;if(n==null)return t;const r=e.args??e.input;return{...e,type:"tool_call",name:n,args:zz(r)}}var vx=class{constructor(t){m(this,"_buffer");this._buffer=t}get full(){const t=this._buffer;return{async*[Symbol.asyncIterator](){let e="";for await(const n of t.iterate()){const r=Mu(n);(r==null?void 0:r.type)==="text-delta"&&(e+=r.text,yield e)}}}}[Symbol.asyncIterator](){const t=this._buffer;async function*e(){for await(const n of t.iterate()){const r=Mu(n);(r==null?void 0:r.type)==="text-delta"&&(yield r.text)}}return e()}then(t,e){return(async()=>{let n="";for await(const r of this)n+=r;return n})().then(t,e)}},Sx=class{constructor(t){m(this,"_buffer");this._buffer=t}get full(){const t=this._buffer;return{async*[Symbol.asyncIterator](){const e=[];for await(const n of t.iterate())n.event==="content-block-finish"&&n.content.type==="tool_call"&&(e.push(n.content),yield[...e])}}}[Symbol.asyncIterator](){const t=this._buffer;async function*e(){for await(const n of t.iterate())n.event==="content-block-finish"&&n.content.type==="tool_call"&&(yield n.content)}return e()}then(t,e){return(async()=>{const n=[];for await(const r of this)n.push(r);return n})().then(t,e)}},Ax=class{constructor(t){m(this,"_buffer");this._buffer=t}get full(){const t=this._buffer;return{async*[Symbol.asyncIterator](){let e="",n=!1;for await(const r of t.iterate())if(r.event==="content-block-start"){if(!rd(r.content)){if(n)return;continue}n=!0;const s=$v(r.content);if(s==null||s.length===0)continue;e+=s,yield e}else if(r.event==="content-block-delta"){const s=Mu(r);if((s==null?void 0:s.type)!=="reasoning-delta")continue;n=!0;const i=s.reasoning;if(i==null||i.length===0)continue;e+=i,yield e}else{if(r.event==="content-block-finish"&&rd(r.content))return;if(r.event==="message-finish")return}}}}[Symbol.asyncIterator](){const t=this._buffer;async function*e(){let n=!1;for await(const r of t.iterate())if(r.event==="content-block-start"){if(!rd(r.content)){if(n)return;continue}n=!0;const s=$v(r.content);s!=null&&s.length>0&&(yield s)}else if(r.event==="content-block-delta"){const s=Mu(r);if((s==null?void 0:s.type)!=="reasoning-delta")continue;n=!0;const i=s.reasoning;i!=null&&i.length>0&&(yield i)}else{if(r.event==="content-block-finish"&&rd(r.content))return;if(r.event==="message-finish")return}}return e()}then(t,e){return(async()=>{let n="";for await(const r of this)n+=r;return n})().then(t,e)}},Tx=class{constructor(t){m(this,"_buffer");this._buffer=t}[Symbol.asyncIterator](){const t=this._buffer;async function*e(){for await(const n of t.iterate())if(n.event==="usage"){const r=po(n.usage);r&&(yield r)}else if(n.event==="message-start"&&n.usage){const r=po(n.usage);r&&(yield r)}else if(n.event==="message-finish"&&n.usage){const r=po(n.usage);r&&(yield r)}}return e()}then(t,e){return(async()=>{let n;for await(const r of this)n=r;return n})().then(t,e)}},Uh=class{constructor(t){m(this,"_buffer");this._buffer=new Fz,this._consume(t)}async _consume(t){try{for await(const e of t)this._buffer.push(e);this._buffer.finish()}catch(e){this._buffer.setError(e instanceof Error?e:new Error(String(e)))}}[Symbol.asyncIterator](){return this._buffer.iterate()}get text(){return new vx(this._buffer)}get toolCalls(){return new Sx(this._buffer)}get reasoning(){return new Ax(this._buffer)}get usage(){return new Tx(this._buffer)}get output(){return this._assembleMessage()}then(t,e){return this._assembleMessage().then(t,e)}async _assembleMessage(){const t=[];let e,n,r={},s;for await(const a of this._buffer.iterate())switch(a.event){case"message-start":e=a.id??e,a.usage&&(n=po(a.usage));break;case"content-block-start":t[a.index]=a.content;break;case"content-block-delta":{const o=t[a.index],c=Mu(a);o&&c&&(t[a.index]=Bz(o,c));break}case"content-block-finish":t[a.index]=a.content;break;case"usage":n=po(a.usage);break;case"message-finish":s=a.reason,a.usage&&(n=po(a.usage)),a.responseMetadata&&(r={...r,...a.responseMetadata});break}const i=t.filter(a=>a!=null).map(Hz);return new De({id:e,content:i,usage_metadata:n,response_metadata:{...r,...s?{finish_reason:s}:{},output_version:"v1"}})}},Vz=de({convertChunksToEvents:()=>Ix,finalizeContentBlock:()=>xx});const Kz={wav:"audio/wav",mp3:"audio/mpeg",flac:"audio/flac",opus:"audio/opus",aac:"audio/aac",pcm16:"audio/pcm"},Wz={png:"image/png",jpeg:"image/jpeg",jpg:"image/jpeg",webp:"image/webp",gif:"image/gif"};function Rv(t){let e=0;for(const n of t.keys())n>=e&&(e=n+1);return e}function Ex(t){const e=t.additional_kwargs;return e!=null&&typeof e=="object"?e:{}}function Zz(t){const e=Ex(t).tool_outputs;if(!Array.isArray(e))return[];const n=[];for(const r of e){if(r==null||typeof r!="object")continue;const s=r;if(s.type!=="image_generation_call")continue;const i=typeof s.result=="string"?s.result:void 0,a=typeof s.url=="string"?s.url:void 0;if(i==null&&a==null)continue;const o=typeof s.output_format=="string"?s.output_format.toLowerCase():void 0,c=(o!=null?Wz[o]:void 0)??"image/png";n.push({type:"image",...typeof s.id=="string"?{id:s.id}:{},...a!=null?{url:a}:{},...i!=null?{data:i}:{},mimeType:c})}return n}function qz(t){const e=Ex(t).audio;if(e==null||typeof e!="object")return;const n=e,r=typeof n.data=="string"?n.data:void 0,s=typeof n.url=="string"?n.url:void 0,i=typeof n.transcript=="string"?n.transcript:void 0;if(r==null&&s==null&&i==null)return;const a=typeof n.mime_type=="string"?n.mime_type:typeof n.mimeType=="string"?n.mimeType:void 0,o=typeof n.format=="string"?n.format.toLowerCase():void 0,c=a??(o!=null?Kz[o]:void 0)??(r!=null?"audio/wav":"audio/pcm");return{...typeof n.id=="string"?{id:n.id}:{},...r!=null?{data:r}:{},...s!=null?{url:s}:{},...i!=null?{transcript:i}:{},mimeType:c}}async function*Ix(t,e){var o;const n=new Map;let r=!1,s,i;const a=new Set;for await(const c of t){(o=e==null?void 0:e.signal)==null||o.throwIfAborted();const u=c.message;let l=!1;if(!r){r=!0;const h={event:"message-start",id:u.id??void 0};Ge.isInstance(u)&&u.usage_metadata&&(h.usage=u.usage_metadata,s={...u.usage_metadata},l=!0),yield h}const d=u.content;if(typeof d=="string"){if(d!==""){if(!n.has(0)){const g={type:"text",text:""};n.set(0,{type:"text",accumulated:g}),yield{event:"content-block-start",index:0,content:g}}const p=n.get(0);p.accumulated={...p.accumulated,text:(p.accumulated.text??"")+d},yield{event:"content-block-delta",index:0,delta:{type:"text-delta",text:d}}}}else if(Array.isArray(d))for(const h of d){const p=typeof h.index=="number"?h.index:n.size;if(!n.has(p))n.set(p,{type:h.type,accumulated:{...h}}),yield{event:"content-block-start",index:p,content:{...h}};else{const g=n.get(p),y=Jz(h);g.accumulated=Gz(g.accumulated,y),yield{event:"content-block-delta",index:p,delta:y}}}if(Ge.isInstance(u)&&u.tool_call_chunks&&u.tool_call_chunks.length>0)for(const h of u.tool_call_chunks){const p=typeof h.index=="number"?h.index:n.size;if(!n.has(p)){const y={type:"tool_call_chunk",id:h.id,name:h.name,args:"",index:p};n.set(p,{type:"tool_call_chunk",accumulated:y}),yield{event:"content-block-start",index:p,content:y}}const g=n.get(p).accumulated;h.id!=null&&(g.id=h.id),h.name!=null&&(g.name=h.name),g.args=(g.args??"")+(h.args??""),yield{event:"content-block-delta",index:p,delta:{type:"block-delta",fields:{type:"tool_call_chunk",..."id"in g&&g.id!=null?{id:g.id}:{},..."name"in g&&g.name!=null?{name:g.name}:{},args:g.args}}}}const f=qz(u);if(f!=null){if(i==null){const p=Rv(n);i={index:p,id:f.id,mimeType:f.mimeType,transcript:""};const g={type:"audio",...f.id!=null?{id:f.id}:{},...f.url!=null?{url:f.url}:{},data:"",mimeType:f.mimeType};n.set(p,{type:"audio",accumulated:g}),yield{event:"content-block-start",index:p,content:g}}const h=n.get(i.index);if(h!=null){const p=h.accumulated;f.id!=null&&i.id==null&&(i.id=f.id,p.id=f.id),f.transcript!=null&&(i.transcript+=f.transcript,p.transcript=i.transcript,yield{event:"content-block-delta",index:i.index,delta:{type:"block-delta",fields:{type:"audio",transcript:i.transcript}}}),f.data!=null&&f.data.length>0&&(p.data=(p.data??"")+f.data,yield{event:"content-block-delta",index:i.index,delta:{type:"data-delta",data:f.data,encoding:"base64"}})}}for(const h of Zz(u)){const p=h,g=p.id??p.url??(p.data!=null?`${p.data.length}:${p.data.slice(0,32)}`:void 0);if(g!=null&&a.has(g))continue;g!=null&&a.add(g);const y=Rv(n);n.set(y,{type:"image",accumulated:h}),yield{event:"content-block-start",index:y,content:h}}if(!l&&Ge.isInstance(u)&&u.usage_metadata){const h=u.usage_metadata;s?s={input_tokens:s.input_tokens+h.input_tokens,output_tokens:s.output_tokens+h.output_tokens,total_tokens:s.total_tokens+h.total_tokens}:s={...h},yield{event:"usage",usage:{...s}}}}for(const[c,u]of n)yield{event:"content-block-finish",index:c,content:xx(u.accumulated)};yield{event:"message-finish",reason:"stop",...s?{usage:s}:{}}}function Gz(t,e){switch(e.type){case"text-delta":return t.type==="text"?{...t,text:(t.text??"")+e.text}:t;case"reasoning-delta":return t.type==="thinking"?{...t,thinking:(t.thinking??"")+e.reasoning}:t.type==="reasoning"?{...t,reasoning:(t.reasoning??"")+e.reasoning}:t;case"data-delta":return{...t,data:(t.data??"")+e.data};case"block-delta":return{...t,...e.fields};default:throw new Error(`Unknown delta type: ${JSON.stringify(e)}`)}}function Jz(t){if(t.type==="text")return{type:"text-delta",text:t.text};if(t.type==="reasoning")return{type:"reasoning-delta",reasoning:t.reasoning};if(t.type==="thinking"&&typeof t.thinking=="string")return{type:"reasoning-delta",reasoning:t.thinking};if(typeof t.data=="string")return{type:"data-delta",data:t.data,encoding:"base64"};if(typeof t.type=="string")return{type:"block-delta",fields:{...t}};throw new Error(`Unsupported content block delta: ${JSON.stringify(t)}`)}function xx(t){if(t.type==="tool_call_chunk"){const e=t;let 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:"tool_call",id:e.id,name:e.name,args:n}}return t}const Yz=t=>t();function sd(t){const e=t.constructor;return new e({...t,content:t.contentBlocks,response_metadata:{...t.response_metadata,output_version:"v1"}})}var Xz=de({BaseChatModel:()=>Es,SimpleChatModel:()=>Qz});function Jp(t){const e=[];for(const n of t){let r=n;if(Array.isArray(n.content))for(let s=0;s<n.content.length;s++){const i=n.content[s];(q_(i)||G_(i))&&r===n&&(r=new n.constructor({...r,content:[...n.content.slice(0,s),AT(i),...n.content.slice(s+1)]}))}e.push(r)}return e}var Es=class ss extends Jy{constructor(n){super(n);m(this,"lc_namespace",["langchain","chat_models",this._llmType()]);m(this,"disableStreaming",!1);m(this,"outputVersion");this.outputVersion=Yz(()=>{const r=n.outputVersion??Mt("LC_OUTPUT_VERSION");return r&&["v0","v1"].includes(r)?r:"v0"})}get callKeys(){return[...super.callKeys,"outputVersion"]}_separateRunnableConfigFromCallOptionsCompat(n){const[r,s]=super._separateRunnableConfigFromCallOptions(n);return s.signal=r.signal,[r,s]}async invoke(n,r){const s=ss._convertInputToPromptValue(n);return(await this.generatePrompt([s],r,r==null?void 0:r.callbacks)).generations[0][0].message}async*_streamResponseChunks(n,r,s){throw new Error("Not implemented.")}async*_streamChatModelEvents(n,r,s){yield*Ix(this._streamResponseChunks(n,r,s),{signal:r.signal})}streamV2(n,r){const s=ss._convertInputToPromptValue(n).toChatMessages(),[,i]=this._separateRunnableConfigFromCallOptionsCompat(r);return new Uh(this._streamChatModelEvents(s,i))}async*_streamIterator(n,r){var s,i,a;if(this._streamResponseChunks===ss.prototype._streamResponseChunks||this.disableStreaming)yield this.invoke(n,r);else{const o=ss._convertInputToPromptValue(n).toChatMessages(),[c,u]=this._separateRunnableConfigFromCallOptionsCompat(r),l={...c.metadata,...this.getLsParamsWithDefaults(u)},d=this.invocationParams(u),f=await bn.configure(c.callbacks,this.callbacks,c.tags,this.tags,l,this.metadata,{verbose:this.verbose,tracerInheritableMetadata:this._filterInvocationParamsForTracing(d)}),h={options:u,invocation_params:d,batch_size:1},p=u.outputVersion??this.outputVersion,g=await(f==null?void 0:f.handleChatModelStart(this.toJSON(),[Jp(o)],c.runId,void 0,h,void 0,void 0,c.runName));let y,b;try{for await(const _ of this._streamResponseChunks(o,u,g==null?void 0:g[0])){if((s=u.signal)==null||s.throwIfAborted(),_.message.id==null){const w=(i=g==null?void 0:g.at(0))==null?void 0:i.runId;w!=null&&_.message._updateId(`run-${w}`)}_.message.response_metadata={..._.generationInfo,..._.message.response_metadata},p==="v1"?yield sd(_.message):yield _.message,y?y=y.concat(_):y=_,yh(_.message)&&_.message.usage_metadata!==void 0&&(b={tokenUsage:{promptTokens:_.message.usage_metadata.input_tokens,completionTokens:_.message.usage_metadata.output_tokens,totalTokens:_.message.usage_metadata.total_tokens}})}(a=u.signal)==null||a.throwIfAborted()}catch(_){throw await Promise.all((g??[]).map(w=>w==null?void 0:w.handleLLMError(_))),_}await Promise.all((g??[]).map(_=>_==null?void 0:_.handleLLMEnd({generations:[[y]],llmOutput:b})))}}getLsParams(n){const r=this.getName().startsWith("Chat")?this.getName().replace("Chat",""):this.getName();return{ls_model_type:"chat",ls_stop:n.stop,ls_provider:r}}getLsParamsWithDefaults(n){return{...this.getLsParams(n),ls_integration:"langchain_chat_model"}}async _generateUncached(n,r,s,i){var p,g,y,b,_,w;const a=n.map(v=>v.map(_s));let o;if(i!==void 0&&i.length===a.length)o=i;else{const v={...s.metadata,...this.getLsParamsWithDefaults(r)},A=this.invocationParams(r),S=await bn.configure(s.callbacks,this.callbacks,s.tags,this.tags,v,this.metadata,{verbose:this.verbose,tracerInheritableMetadata:this._filterInvocationParamsForTracing(A)}),x={options:r,invocation_params:A,batch_size:1};o=await(S==null?void 0:S.handleChatModelStart(this.toJSON(),a.map(Jp),s.runId,void 0,x,void 0,void 0,s.runName))}const c=r.outputVersion??this.outputVersion,u=[],l=[],d=!!(o!=null&&o[0].handlers.find(KT)),f=!!(o!=null&&o[0].handlers.find(ay));if(d&&!this.disableStreaming&&a.length===1&&(this._streamChatModelEvents!==ss.prototype._streamChatModelEvents||this._streamResponseChunks!==ss.prototype._streamResponseChunks))try{let v=!1;const A=o==null?void 0:o[0],S=this._streamChatModelEvents(a[0],r),x=await new Uh({async*[Symbol.asyncIterator](){var k;for await(const C of S){(k=r.signal)==null||k.throwIfAborted(),v=!0;const D=C.event==="message-start"&&C.id==null&&(A==null?void 0:A.runId)!=null?{...C,id:`run-${A.runId}`}:C;await(A==null?void 0:A.handleChatModelStreamEvent(D)),yield D}}});if((p=r.signal)==null||p.throwIfAborted(),!v)throw new Error("Received empty response from chat model call.");if(x.id==null){const k=(g=o==null?void 0:o.at(0))==null?void 0:g.runId;k!=null&&x._updateId(`run-${k}`)}const E={text:x.text,message:x};u.push([E]);const $=x.usage_metadata!==void 0?{tokenUsage:{promptTokens:x.usage_metadata.input_tokens,completionTokens:x.usage_metadata.output_tokens,totalTokens:x.usage_metadata.total_tokens}}:void 0;await(o==null?void 0:o[0].handleLLMEnd({generations:u,llmOutput:$}))}catch(v){throw await(o==null?void 0:o[0].handleLLMError(v)),v}else if(f&&!this.disableStreaming&&a.length===1&&this._streamResponseChunks!==ss.prototype._streamResponseChunks)try{const v=await this._streamResponseChunks(a[0],r,o==null?void 0:o[0]);let A,S;for await(const x of v){if((y=r.signal)!=null&&y.aborted){const E=A==null?void 0:A.message;throw new qm("Model invocation was aborted.",E)}if(x.message.id==null){const E=(b=o==null?void 0:o.at(0))==null?void 0:b.runId;E!=null&&x.message._updateId(`run-${E}`)}A===void 0?A=x:A=Vs(A,x),yh(x.message)&&x.message.usage_metadata!==void 0&&(S={tokenUsage:{promptTokens:x.message.usage_metadata.input_tokens,completionTokens:x.message.usage_metadata.output_tokens,totalTokens:x.message.usage_metadata.total_tokens}})}if((_=r.signal)!=null&&_.aborted){const x=A==null?void 0:A.message;throw new qm("Model invocation was aborted.",x)}if(A===void 0)throw new Error("Received empty response from chat model call.");c==="v1"&&(A.message=sd(A.message)),u.push([A]),await(o==null?void 0:o[0].handleLLMEnd({generations:u,llmOutput:S}))}catch(v){throw await(o==null?void 0:o[0].handleLLMError(v)),v}else{const v=await Promise.allSettled(a.map(async(A,S)=>{const x=await this._generate(A,{...r,promptIndex:S},o==null?void 0:o[S]);if(c==="v1")for(const E of x.generations)E.message=sd(E.message);return x}));await Promise.all(v.map(async(A,S)=>{var x,E,$;if(A.status==="fulfilled"){const k=A.value;for(const C of k.generations){if(C.message.id==null){const D=(x=o==null?void 0:o.at(0))==null?void 0:x.runId;D!=null&&C.message._updateId(`run-${D}`)}C.message.response_metadata={...C.generationInfo,...C.message.response_metadata}}return k.generations.length===1&&(k.generations[0].message.response_metadata={...k.llmOutput,...k.generations[0].message.response_metadata}),u[S]=k.generations,l[S]=k.llmOutput,(E=o==null?void 0:o[S])==null?void 0:E.handleLLMEnd({generations:[k.generations],llmOutput:k.llmOutput})}else return await(($=o==null?void 0:o[S])==null?void 0:$.handleLLMError(A.reason)),Promise.reject(A.reason)}))}const h={generations:u,llmOutput:l.length?(w=this._combineLLMOutput)==null?void 0:w.call(this,...l):void 0};return Object.defineProperty(h,Eu,{value:o?{runIds:o==null?void 0:o.map(v=>v.runId)}:void 0,configurable:!0}),h}async _generateCached({messages:n,cache:r,llmStringKey:s,parsedOptions:i,handledOptions:a}){const o=n.map(_=>_.map(_s)),c={...a.metadata,...this.getLsParamsWithDefaults(i)},u=this.invocationParams(i),l=await bn.configure(a.callbacks,this.callbacks,a.tags,this.tags,c,this.metadata,{verbose:this.verbose,tracerInheritableMetadata:this._filterInvocationParamsForTracing(u)}),d={options:i,invocation_params:u,batch_size:1},f=await(l==null?void 0:l.handleChatModelStart(this.toJSON(),o.map(Jp),a.runId,void 0,d,void 0,void 0,a.runName)),h=[],p=(await Promise.allSettled(o.map(async(_,w)=>{const v=ss._convertInputToPromptValue(_).toString(),A=await r.lookup(v,s);return A==null&&h.push(w),A}))).map((_,w)=>({result:_,runManager:f==null?void 0:f[w]})).filter(({result:_})=>_.status==="fulfilled"&&_.value!=null||_.status==="rejected"),g=i.outputVersion??this.outputVersion,y=[];await Promise.all(p.map(async({result:_,runManager:w},v)=>{if(_.status==="fulfilled"){const A=_.value;return y[v]=A.map(S=>("message"in S&&Et(S.message)&&Cr(S.message)&&(S.message.usage_metadata={input_tokens:0,output_tokens:0,total_tokens:0},g==="v1"&&(S.message=sd(S.message))),S.generationInfo={...S.generationInfo,tokenUsage:{}},S)),A.length&&await(w==null?void 0:w.handleLLMNewToken(A[0].text)),w==null?void 0:w.handleLLMEnd({generations:[A]},void 0,void 0,void 0,{cached:!0})}else return await(w==null?void 0:w.handleLLMError(_.reason,void 0,void 0,void 0,{cached:!0})),Promise.reject(_.reason)}));const b={generations:y,missingPromptIndices:h,startedRunManagers:f};return Object.defineProperty(b,Eu,{value:f?{runIds:f==null?void 0:f.map(_=>_.runId)}:void 0,configurable:!0}),b}async generate(n,r,s){let i;Array.isArray(r)?i={stop:r}:i=r;const a=n.map(g=>g.map(_s)),[o,c]=this._separateRunnableConfigFromCallOptionsCompat(i);if(o.callbacks=o.callbacks??s,!this.cache)return this._generateUncached(a,c,o);const{cache:u}=this,l=this._getSerializedCacheKeyParametersForCall(c),{generations:d,missingPromptIndices:f,startedRunManagers:h}=await this._generateCached({messages:a,cache:u,llmStringKey:l,parsedOptions:c,handledOptions:o});let p={};if(f.length>0){const g=await this._generateUncached(f.map(y=>a[y]),c,o,h!==void 0?f.map(y=>h==null?void 0:h[y]):void 0);await Promise.all(g.generations.map(async(y,b)=>{const _=f[b];d[_]=y;const w=ss._convertInputToPromptValue(a[_]).toString();return u.update(w,l,y)})),p=g.llmOutput??{}}return{generations:d,llmOutput:p}}invocationParams(n){return{}}_modelType(){return"base_chat_model"}async generatePrompt(n,r,s){const i=n.map(a=>a.toChatMessages());return this.generate(i,r,s)}withStructuredOutput(n,r){if(typeof this.bindTools!="function")throw new Error('Chat model must implement ".bindTools()" to use withStructuredOutput.');if(r!=null&&r.strict)throw new Error('"strict" mode is not supported for this model by default.');const s=n,i=r==null?void 0:r.name,a=jo(s)??"A function available to call.",o=r==null?void 0:r.method,c=r==null?void 0:r.includeRaw;if(o==="jsonMode")throw new Error('Base withStructuredOutput implementation only supports "functionCalling" as a method.');let u=i??"extract";!Wt(s)&&!Or(s)&&"name"in s&&(u=s.name);const l=Wt(s)||Or(s)?mt(s):s,d=[{type:"function",function:{name:u,description:a,parameters:l}}];return tc(this.bindTools(d),en.from(f=>{if(!Ge.isInstance(f))throw new Error("Input is not an AIMessageChunk.");if(!f.tool_calls||f.tool_calls.length===0)throw new Error("No tool calls found in the response.");const h=f.tool_calls.find(p=>p.name===u);if(!h)throw new Error(`No tool call found with name ${u}.`);return h.args}),c,c?"StructuredOutputRunnable":"StructuredOutput")}},Qz=class extends Es{async _generate(t,e,n){const r=new De(await this._call(t,e,n));if(typeof r.content!="string")throw new Error("Cannot generate with a simple chat model when output is not a string.");return{generations:[{text:r.content,message:r}]}}},e3=de({}),t3=de({BaseLLM:()=>kx,LLM:()=>ew}),kx=class Uc extends Jy{constructor(){super(...arguments);m(this,"lc_namespace",["langchain","llms",this._llmType()])}async invoke(n,r){const s=Uc._convertInputToPromptValue(n);return(await this.generatePrompt([s],r,r==null?void 0:r.callbacks)).generations[0][0].text}async*_streamResponseChunks(n,r,s){throw new Error("Not implemented.")}_separateRunnableConfigFromCallOptionsCompat(n){const[r,s]=super._separateRunnableConfigFromCallOptions(n);return s.signal=r.signal,[r,s]}async*_streamIterator(n,r){if(this._streamResponseChunks===Uc.prototype._streamResponseChunks)yield this.invoke(n,r);else{const s=Uc._convertInputToPromptValue(n),[i,a]=this._separateRunnableConfigFromCallOptionsCompat(r),o=this.invocationParams(a),c=await bn.configure(i.callbacks,this.callbacks,i.tags,this.tags,i.metadata,this.metadata,{verbose:this.verbose,tracerInheritableMetadata:this._filterInvocationParamsForTracing(o)}),u={options:a,invocation_params:o,batch_size:1},l=await(c==null?void 0:c.handleLLMStart(this.toJSON(),[s.toString()],i.runId,void 0,u,void 0,void 0,i.runName));let d=new Lo({text:""});try{for await(const f of this._streamResponseChunks(s.toString(),a,l==null?void 0:l[0]))d?d=d.concat(f):d=f,typeof f.text=="string"&&(yield f.text)}catch(f){throw await Promise.all((l??[]).map(h=>h==null?void 0:h.handleLLMError(f))),f}await Promise.all((l??[]).map(f=>f==null?void 0:f.handleLLMEnd({generations:[[d]]})))}}async generatePrompt(n,r,s){const i=n.map(a=>a.toString());return this.generate(i,r,s)}invocationParams(n){return{}}_flattenLLMResult(n){const r=[];for(let s=0;s<n.generations.length;s+=1){const i=n.generations[s];if(s===0)r.push({generations:[i],llmOutput:n.llmOutput});else{const a=n.llmOutput?{...n.llmOutput,tokenUsage:{}}:void 0;r.push({generations:[i],llmOutput:a})}}return r}async _generateUncached(n,r,s,i){let a;if(i!==void 0&&i.length===n.length)a=i;else{const l=this.invocationParams(r),d=await bn.configure(s.callbacks,this.callbacks,s.tags,this.tags,s.metadata,this.metadata,{verbose:this.verbose,tracerInheritableMetadata:this._filterInvocationParamsForTracing(l)}),f={options:r,invocation_params:l,batch_size:n.length};a=await(d==null?void 0:d.handleLLMStart(this.toJSON(),n,s.runId,void 0,f,void 0,void 0,s==null?void 0:s.runName))}const o=!!(a!=null&&a[0].handlers.find(ay));let c;if(o&&n.length===1&&this._streamResponseChunks!==Uc.prototype._streamResponseChunks)try{const l=await this._streamResponseChunks(n[0],r,a==null?void 0:a[0]);let d;for await(const f of l)d===void 0?d=f:d=Vs(d,f);if(d===void 0)throw new Error("Received empty response from chat model call.");c={generations:[[d]],llmOutput:{}},await(a==null?void 0:a[0].handleLLMEnd(c))}catch(l){throw await(a==null?void 0:a[0].handleLLMError(l)),l}else{try{c=await this._generate(n,r,a==null?void 0:a[0])}catch(d){throw await Promise.all((a??[]).map(f=>f==null?void 0:f.handleLLMError(d))),d}const l=this._flattenLLMResult(c);await Promise.all((a??[]).map((d,f)=>d==null?void 0:d.handleLLMEnd(l[f])))}const u=(a==null?void 0:a.map(l=>l.runId))||void 0;return Object.defineProperty(c,Eu,{value:u?{runIds:u}:void 0,configurable:!0}),c}async _generateCached({prompts:n,cache:r,llmStringKey:s,parsedOptions:i,handledOptions:a,runId:o}){const c=this.invocationParams(i),u=await bn.configure(a.callbacks,this.callbacks,a.tags,this.tags,a.metadata,this.metadata,{verbose:this.verbose,tracerInheritableMetadata:this._filterInvocationParamsForTracing(c)}),l={options:i,invocation_params:c,batch_size:n.length},d=await(u==null?void 0:u.handleLLMStart(this.toJSON(),n,o,void 0,l,void 0,void 0,a==null?void 0:a.runName)),f=[],h=(await Promise.allSettled(n.map(async(y,b)=>{const _=await r.lookup(y,s);return _==null&&f.push(b),_}))).map((y,b)=>({result:y,runManager:d==null?void 0:d[b]})).filter(({result:y})=>y.status==="fulfilled"&&y.value!=null||y.status==="rejected"),p=[];await Promise.all(h.map(async({result:y,runManager:b},_)=>{if(y.status==="fulfilled"){const w=y.value;return p[_]=w.map(v=>(v.generationInfo={...v.generationInfo,tokenUsage:{}},v)),w.length&&await(b==null?void 0:b.handleLLMNewToken(w[0].text)),b==null?void 0:b.handleLLMEnd({generations:[w]},void 0,void 0,void 0,{cached:!0})}else return await(b==null?void 0:b.handleLLMError(y.reason,void 0,void 0,void 0,{cached:!0})),Promise.reject(y.reason)}));const g={generations:p,missingPromptIndices:f,startedRunManagers:d};return Object.defineProperty(g,Eu,{value:d?{runIds:d==null?void 0:d.map(y=>y.runId)}:void 0,configurable:!0}),g}async generate(n,r,s){if(!Array.isArray(n))throw new Error("Argument 'prompts' is expected to be a string[]");let i;Array.isArray(r)?i={stop:r}:i=r;const[a,o]=this._separateRunnableConfigFromCallOptionsCompat(i);if(a.callbacks=a.callbacks??s,!this.cache)return this._generateUncached(n,o,a);const{cache:c}=this,u=this._getSerializedCacheKeyParametersForCall(o),{generations:l,missingPromptIndices:d,startedRunManagers:f}=await this._generateCached({prompts:n,cache:c,llmStringKey:u,parsedOptions:o,handledOptions:a,runId:a.runId});let h={};if(d.length>0){const p=await this._generateUncached(d.map(g=>n[g]),o,a,f!==void 0?d.map(g=>f==null?void 0:f[g]):void 0);await Promise.all(p.generations.map(async(g,y)=>{const b=d[y];return l[b]=g,c.update(n[b],u,g)})),h=p.llmOutput??{}}return{generations:l,llmOutput:h}}_identifyingParams(){return{}}_modelType(){return"base_llm"}},ew=class extends kx{async _generate(t,e,n){return{generations:await Promise.all(t.map((r,s)=>this._call(r,{...e,promptIndex:s},n).then(i=>[{text:i}])))}}},n3=de({}),r3=de({BaseMemory:()=>s3,getInputValue:()=>i3,getOutputValue:()=>a3,getPromptInputKey:()=>o3}),s3=class{};const Cx=(t,e)=>{if(e!==void 0)return t[e];const n=Object.keys(t);if(n.length===1)return t[n[0]]},i3=(t,e)=>{const n=Cx(t,e);if(!n)throw new Error(`input values have ${Object.keys(t).length} keys, you must specify an input key or pass only 1 key as input`);return n},a3=(t,e)=>{const n=Cx(t,e);if(!n&&n!=="")throw new Error(`output values have ${Object.keys(t).length} keys, you must specify an output key or pass only 1 key as output`);return n};function o3(t,e){const n=Object.keys(t).filter(r=>!e.includes(r)&&r!=="stop");if(n.length!==1)throw new Error(`One input key expected, but got ${n.length}`);return n[0]}var Ox=class extends Qo{constructor(e){super();m(this,"lc_namespace",["langchain","output_parsers","openai_functions"]);m(this,"lc_serializable",!0);m(this,"argsOnly",!0);this.argsOnly=(e==null?void 0:e.argsOnly)??this.argsOnly}static lc_name(){return"OutputFunctionsParser"}async parseResult(e){if("message"in e[0]){const n=e[0].message.additional_kwargs.function_call;if(!n)throw new Error(`No function_call in message ${JSON.stringify(e)}`);if(!n.arguments)throw new Error(`No arguments in function_call ${JSON.stringify(e)}`);return this.argsOnly?n.arguments:JSON.stringify(n)}else throw new Error(`No message in generations ${JSON.stringify(e)}`)}},$x=class extends Sl{constructor(e){super(e);m(this,"lc_namespace",["langchain","output_parsers","openai_functions"]);m(this,"lc_serializable",!0);m(this,"outputParser");m(this,"argsOnly",!0);this.argsOnly=(e==null?void 0:e.argsOnly)??this.argsOnly,this.outputParser=new Ox(e)}static lc_name(){return"JsonOutputFunctionsParser"}_diff(e,n){if(n)return Af(e??{},n)}async parsePartialResult(e){const n=e[0];if(!n.message)return;const{message:r}=n,s=r.additional_kwargs.function_call;if(s)return this.argsOnly?$o(s.arguments):{...s,arguments:$o(s.arguments)}}async parseResult(e){const n=await this.outputParser.parseResult(e);if(!n)throw new Error(`No result from "OutputFunctionsParser" ${JSON.stringify(e)}`);return this.parse(n)}async parse(e){const n=JSON.parse(e);return this.argsOnly||(n.arguments=JSON.parse(n.arguments)),n}getFormatInstructions(){return""}},c3=class extends Qo{constructor(e){super(e);m(this,"lc_namespace",["langchain","output_parsers","openai_functions"]);m(this,"lc_serializable",!0);m(this,"outputParser",new $x);m(this,"attrName");this.attrName=e.attrName}static lc_name(){return"JsonKeyOutputFunctionsParser"}get lc_aliases(){return{attrName:"key_name"}}async parseResult(e){return(await this.outputParser.parseResult(e))[this.attrName]}},u3=de({JsonKeyOutputFunctionsParser:()=>c3,JsonOutputFunctionsParser:()=>$x,OutputFunctionsParser:()=>Ox}),l3=de({JsonOutputKeyToolsParser:()=>bx,JsonOutputToolsParser:()=>wx,convertLangChainToolCallToOpenAI:()=>Qy,makeInvalidToolCall:()=>fu,parseToolCall:()=>Lf}),El=class extends ze{constructor(e){super(e);m(this,"lc_serializable",!0);m(this,"lc_namespace",["langchain_core","prompts",this._getPromptType()]);m(this,"inputVariables");m(this,"outputParser");m(this,"partialVariables");m(this,"metadata");m(this,"tags");const{inputVariables:n}=e;if(n.includes("stop"))throw new Error("Cannot have an input variable named 'stop', as it is used internally, please rename.");Object.assign(this,e)}get lc_attributes(){return{partialVariables:void 0}}async mergePartialAndUserVariables(e){const n=this.partialVariables??{},r={};for(const[s,i]of Object.entries(n))typeof i=="string"?r[s]=i:r[s]=await i();return{...r,...e}}async invoke(e,n){const r={...this.metadata,...n==null?void 0:n.metadata},s=[...this.tags??[],...(n==null?void 0:n.tags)??[]];return this._callWithConfig(i=>this.formatPromptValue(i),e,{...n,tags:s,metadata:r,runType:"prompt"})}},Lu=class extends El{async formatPromptValue(t){return new Wy(await this.format(t))}};/*!
|
|
206
|
-
* mustache.js - Logic-less {{mustache}} templates with JavaScript
|
|
207
|
-
* http://github.com/janl/mustache.js
|
|
208
|
-
*/var d3=Object.prototype.toString,nc=Array.isArray||function(e){return d3.call(e)==="[object Array]"};function tw(t){return typeof t=="function"}function h3(t){return nc(t)?"array":typeof t}function Yp(t){return t.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function Pv(t,e){return t!=null&&typeof t=="object"&&e in t}function f3(t,e){return t!=null&&typeof t!="object"&&t.hasOwnProperty&&t.hasOwnProperty(e)}var p3=RegExp.prototype.test;function m3(t,e){return p3.call(t,e)}var g3=/\S/;function _3(t){return!m3(g3,t)}var y3={"&":"&","<":"<",">":">",'"':""","'":"'","/":"/","`":"`","=":"="};function w3(t){return String(t).replace(/[&<>"'`=\/]/g,function(n){return y3[n]})}var b3=/\s*/,v3=/\s+/,Nv=/\s*=/,S3=/\s*\}/,A3=/#|\^|\/|>|\{|&|=|!/;function T3(t,e){if(!t)return[];var n=!1,r=[],s=[],i=[],a=!1,o=!1,c="",u=0;function l(){if(a&&!o)for(;i.length;)delete s[i.pop()];else i=[];a=!1,o=!1}var d,f,h;function p(E){if(typeof E=="string"&&(E=E.split(v3,2)),!nc(E)||E.length!==2)throw new Error("Invalid tags: "+E);d=new RegExp(Yp(E[0])+"\\s*"),f=new RegExp("\\s*"+Yp(E[1])),h=new RegExp("\\s*"+Yp("}"+E[1]))}p(e||Zn.tags);for(var g=new Il(t),y,b,_,w,v,A;!g.eos();){if(y=g.pos,_=g.scanUntil(d),_)for(var S=0,x=_.length;S<x;++S)w=_.charAt(S),_3(w)?(i.push(s.length),c+=w):(o=!0,n=!0,c+=" "),s.push(["text",w,y,y+1]),y+=1,w===`
|
|
209
|
-
`&&(l(),c="",u=0,n=!1);if(!g.scan(d))break;if(a=!0,b=g.scan(A3)||"name",g.scan(b3),b==="="?(_=g.scanUntil(Nv),g.scan(Nv),g.scanUntil(f)):b==="{"?(_=g.scanUntil(h),g.scan(S3),g.scanUntil(f),b="&"):_=g.scanUntil(f),!g.scan(f))throw new Error("Unclosed tag at "+g.pos);if(b==">"?v=[b,_,y,g.pos,c,u,n]:v=[b,_,y,g.pos],u++,s.push(v),b==="#"||b==="^")r.push(v);else if(b==="/"){if(A=r.pop(),!A)throw new Error('Unopened section "'+_+'" at '+y);if(A[1]!==_)throw new Error('Unclosed section "'+A[1]+'" at '+y)}else b==="name"||b==="{"||b==="&"?o=!0:b==="="&&p(_)}if(l(),A=r.pop(),A)throw new Error('Unclosed section "'+A[1]+'" at '+g.pos);return I3(E3(s))}function E3(t){for(var e=[],n,r,s=0,i=t.length;s<i;++s)n=t[s],n&&(n[0]==="text"&&r&&r[0]==="text"?(r[1]+=n[1],r[3]=n[3]):(e.push(n),r=n));return e}function I3(t){for(var e=[],n=e,r=[],s,i,a=0,o=t.length;a<o;++a)switch(s=t[a],s[0]){case"#":case"^":n.push(s),r.push(s),n=s[4]=[];break;case"/":i=r.pop(),i[5]=s[2],n=r.length>0?r[r.length-1][4]:e;break;default:n.push(s)}return e}function Il(t){this.string=t,this.tail=t,this.pos=0}Il.prototype.eos=function(){return this.tail===""};Il.prototype.scan=function(e){var n=this.tail.match(e);if(!n||n.index!==0)return"";var r=n[0];return this.tail=this.tail.substring(r.length),this.pos+=r.length,r};Il.prototype.scanUntil=function(e){var n=this.tail.search(e),r;switch(n){case-1:r=this.tail,this.tail="";break;case 0:r="";break;default:r=this.tail.substring(0,n),this.tail=this.tail.substring(n)}return this.pos+=r.length,r};function Wo(t,e){this.view=t,this.cache={".":this.view},this.parent=e}Wo.prototype.push=function(e){return new Wo(e,this)};Wo.prototype.lookup=function(e){var n=this.cache,r;if(n.hasOwnProperty(e))r=n[e];else{for(var s=this,i,a,o,c=!1;s;){if(e.indexOf(".")>0)for(i=s.view,a=e.split("."),o=0;i!=null&&o<a.length;)o===a.length-1&&(c=Pv(i,a[o])||f3(i,a[o])),i=i[a[o++]];else i=s.view[e],c=Pv(s.view,e);if(c){r=i;break}s=s.parent}n[e]=r}return tw(r)&&(r=r.call(this.view)),r};function Mn(){this.templateCache={_cache:{},set:function(e,n){this._cache[e]=n},get:function(e){return this._cache[e]},clear:function(){this._cache={}}}}Mn.prototype.clearCache=function(){typeof this.templateCache<"u"&&this.templateCache.clear()};Mn.prototype.parse=function(e,n){var r=this.templateCache,s=e+":"+(n||Zn.tags).join(":"),i=typeof r<"u",a=i?r.get(s):void 0;return a==null&&(a=T3(e,n),i&&r.set(s,a)),a};Mn.prototype.render=function(e,n,r,s){var i=this.getConfigTags(s),a=this.parse(e,i),o=n instanceof Wo?n:new Wo(n,void 0);return this.renderTokens(a,o,r,e,s)};Mn.prototype.renderTokens=function(e,n,r,s,i){for(var a="",o,c,u,l=0,d=e.length;l<d;++l)u=void 0,o=e[l],c=o[0],c==="#"?u=this.renderSection(o,n,r,s,i):c==="^"?u=this.renderInverted(o,n,r,s,i):c===">"?u=this.renderPartial(o,n,r,i):c==="&"?u=this.unescapedValue(o,n):c==="name"?u=this.escapedValue(o,n,i):c==="text"&&(u=this.rawValue(o)),u!==void 0&&(a+=u);return a};Mn.prototype.renderSection=function(e,n,r,s,i){var a=this,o="",c=n.lookup(e[1]);function u(f){return a.render(f,n,r,i)}if(c){if(nc(c))for(var l=0,d=c.length;l<d;++l)o+=this.renderTokens(e[4],n.push(c[l]),r,s,i);else if(typeof c=="object"||typeof c=="string"||typeof c=="number")o+=this.renderTokens(e[4],n.push(c),r,s,i);else if(tw(c)){if(typeof s!="string")throw new Error("Cannot use higher-order sections without the original template");c=c.call(n.view,s.slice(e[3],e[5]),u),c!=null&&(o+=c)}else o+=this.renderTokens(e[4],n,r,s,i);return o}};Mn.prototype.renderInverted=function(e,n,r,s,i){var a=n.lookup(e[1]);if(!a||nc(a)&&a.length===0)return this.renderTokens(e[4],n,r,s,i)};Mn.prototype.indentPartial=function(e,n,r){for(var s=n.replace(/[^ \t]/g,""),i=e.split(`
|
|
210
|
-
`),a=0;a<i.length;a++)i[a].length&&(a>0||!r)&&(i[a]=s+i[a]);return i.join(`
|
|
211
|
-
`)};Mn.prototype.renderPartial=function(e,n,r,s){if(r){var i=this.getConfigTags(s),a=tw(r)?r(e[1]):r[e[1]];if(a!=null){var o=e[6],c=e[5],u=e[4],l=a;c==0&&u&&(l=this.indentPartial(a,u,o));var d=this.parse(l,i);return this.renderTokens(d,n,r,l,s)}}};Mn.prototype.unescapedValue=function(e,n){var r=n.lookup(e[1]);if(r!=null)return r};Mn.prototype.escapedValue=function(e,n,r){var s=this.getConfigEscape(r)||Zn.escape,i=n.lookup(e[1]);if(i!=null)return typeof i=="number"&&s===Zn.escape?String(i):s(i)};Mn.prototype.rawValue=function(e){return e[1]};Mn.prototype.getConfigTags=function(e){return nc(e)?e:e&&typeof e=="object"?e.tags:void 0};Mn.prototype.getConfigEscape=function(e){if(e&&typeof e=="object"&&!nc(e))return e.escape};var Zn={name:"mustache.js",version:"4.2.0",tags:["{{","}}"],clearCache:void 0,escape:void 0,parse:void 0,render:void 0,Scanner:void 0,Context:void 0,Writer:void 0,set templateCache(t){ju.templateCache=t},get templateCache(){return ju.templateCache}},ju=new Mn;Zn.clearCache=function(){return ju.clearCache()};Zn.parse=function(e,n){return ju.parse(e,n)};Zn.render=function(e,n,r,s){if(typeof e!="string")throw new TypeError('Invalid template! Template should be a "string" but "'+h3(e)+'" was given as the first argument for mustache#render(template, view, partials)');return ju.render(e,n,r,s)};Zn.escape=w3;Zn.Scanner=Il;Zn.Context=Wo;Zn.Writer=Mn;function Rx(){Zn.escape=t=>t}const Du=t=>{const e=t.split(""),n=[],r=(i,a)=>{for(let o=a;o<e.length;o+=1)if(i.includes(e[o]))return o;return-1};let s=0;for(;s<e.length;)if(e[s]==="{"&&s+1<e.length&&e[s+1]==="{")n.push({type:"literal",text:"{"}),s+=2;else if(e[s]==="}"&&s+1<e.length&&e[s+1]==="}")n.push({type:"literal",text:"}"}),s+=2;else if(e[s]==="{"){const i=r("}",s);if(i<0)throw new Error("Unclosed '{' in template.");n.push({type:"variable",name:e.slice(s+1,i).join("")}),s=i+1}else{if(e[s]==="}")throw new Error("Single '}' in template.");{const i=r("{}",s),a=(i<0?e.slice(s):e.slice(s,i)).join("");n.push({type:"literal",text:a}),s=i<0?e.length:i}}return n},Px=(t,e=[])=>{const n=[];for(const r of t)if(r[0]==="name"){const s=r[1].includes(".")?r[1].split(".")[0]:r[1];n.push({type:"variable",name:s})}else if(["#","&","^",">"].includes(r[0])){if(n.push({type:"variable",name:r[1]}),r[0]==="#"&&r.length>4&&Array.isArray(r[4])){const s=[...e,r[1]],i=Px(r[4],s);n.push(...i)}}else n.push({type:"literal",text:r[1]});return n},Fh=t=>(Rx(),Px(Zn.parse(t))),Nx=(t,e)=>Du(t).reduce((n,r)=>{if(r.type==="variable"){if(r.name in e)return n+(typeof e[r.name]=="string"?e[r.name]:JSON.stringify(e[r.name]));throw new Error(`(f-string) Missing value for input ${r.name}`)}return n+r.text},""),Mx=(t,e)=>(Rx(),Zn.render(t,e)),Bh={"f-string":Nx,mustache:Mx},Lx={"f-string":Du,mustache:Fh},Zr=(t,e,n)=>{try{return Bh[e](t,n)}catch(r){throw cl(r,"INVALID_PROMPT_INPUT")}},zh=(t,e)=>Lx[e](t),xl=(t,e,n)=>{if(!(e in Bh))throw new Error(`Invalid template format. Got \`${e}\`;
|
|
212
|
-
should be one of ${Object.keys(Bh)}`);try{const r=Object.fromEntries(n.map(s=>[s,"foo"]));Array.isArray(t)?t.forEach(s=>{if(s.type==="text"&&"text"in s&&typeof s.text=="string")Zr(s.text,e,r);else if(s.type==="image_url"){if(typeof s.image_url=="string")Zr(s.image_url,e,r);else if(typeof s.image_url=="object"&&s.image_url!==null&&"url"in s.image_url&&typeof s.image_url.url=="string"){const i=s.image_url.url;Zr(i,e,r)}}else throw new Error(`Invalid message template received. ${JSON.stringify(s,null,2)}`)}):Zr(t,e,r)}catch(r){throw new Error(`Invalid prompt schema: ${r.message}`)}};var Ei=class Fc extends Lu{constructor(n){super(n);m(this,"template");m(this,"templateFormat","f-string");m(this,"validateTemplate",!0);m(this,"additionalContentFields");if(n.templateFormat==="mustache"&&n.validateTemplate===void 0&&(this.validateTemplate=!1),Object.assign(this,n),this.validateTemplate){if(this.templateFormat==="mustache")throw new Error("Mustache templates cannot be validated.");let r=this.inputVariables;this.partialVariables&&(r=r.concat(Object.keys(this.partialVariables))),xl(this.template,this.templateFormat,r)}}static lc_name(){return"PromptTemplate"}_getPromptType(){return"prompt"}async format(n){const r=await this.mergePartialAndUserVariables(n);return Zr(this.template,this.templateFormat,r)}static fromExamples(n,r,s,i=`
|
|
213
|
-
|
|
214
|
-
`,a=""){return new Fc({inputVariables:s,template:[a,...n,r].join(i)})}static fromTemplate(n,r){const{templateFormat:s="f-string",...i}=r??{},a=new Set;return zh(n,s).forEach(o=>{o.type==="variable"&&a.add(o.name)}),new Fc({inputVariables:[...a],templateFormat:s,template:n,...i})}async partial(n){const r=this.inputVariables.filter(i=>!(i in n)),s={...this.partialVariables??{},...n};return new Fc({...this,inputVariables:r,partialVariables:s})}serialize(){if(this.outputParser!==void 0)throw new Error("Cannot serialize a prompt template with an output parser");return{_type:this._getPromptType(),input_variables:this.inputVariables,template:this.template,template_format:this.templateFormat}}static async deserialize(n){if(!n.template)throw new Error("Prompt template must have a template");return new Fc({inputVariables:n.input_variables,template:n.template,templateFormat:n.template_format})}},Vd=class jx extends El{constructor(n){super(n);m(this,"lc_namespace",["langchain_core","prompts","image"]);m(this,"template");m(this,"templateFormat","f-string");m(this,"validateTemplate",!0);m(this,"additionalContentFields");if(this.template=n.template,this.templateFormat=n.templateFormat??this.templateFormat,this.validateTemplate=n.validateTemplate??this.validateTemplate,this.additionalContentFields=n.additionalContentFields,this.validateTemplate){let r=this.inputVariables;this.partialVariables&&(r=r.concat(Object.keys(this.partialVariables))),xl([{type:"image_url",image_url:this.template}],this.templateFormat,r)}}static lc_name(){return"ImagePromptTemplate"}_getPromptType(){return"prompt"}async partial(n){const r=this.inputVariables.filter(i=>!(i in n)),s={...this.partialVariables??{},...n};return new jx({...this,inputVariables:r,partialVariables:s})}async format(n){const r={};for(const[o,c]of Object.entries(this.template))typeof c=="string"?r[o]=Zr(c,this.templateFormat,n):r[o]=c;const s=n.url||r.url,i=n.detail||r.detail;if(!s)throw new Error("Must provide either an image URL.");if(typeof s!="string")throw new Error("url must be a string.");const a={url:s};return i&&(a.detail=i),a}async formatPromptValue(n){return new dx(await this.format(n))}},Kg=class extends ze{constructor(e){const n=e.templateFormat??"f-string",r=Wg(e.template,n);super({inputVariables:r,...e});m(this,"lc_namespace",["langchain_core","prompts","dict"]);m(this,"lc_serializable",!0);m(this,"template");m(this,"templateFormat");m(this,"inputVariables");this.template=e.template,this.templateFormat=n,this.inputVariables=r}static lc_name(){return"DictPromptTemplate"}async format(e){return Zg(this.template,e,this.templateFormat)}async invoke(e){return await this._callWithConfig(this.format.bind(this),e,{runType:"prompt"})}};function Wg(t,e){const n=[];for(const r of Object.values(t))if(typeof r=="string")zh(r,e).forEach(s=>{s.type==="variable"&&n.push(s.name)});else if(Array.isArray(r))for(const s of r)typeof s=="string"?zh(s,e).forEach(i=>{i.type==="variable"&&n.push(i.name)}):typeof s=="object"&&n.push(...Wg(s,e));else typeof r=="object"&&r!==null&&n.push(...Wg(r,e));return Array.from(new Set(n))}function Zg(t,e,n){const r={};for(const[s,i]of Object.entries(t))if(typeof i=="string")r[s]=Zr(i,n,e);else if(Array.isArray(i)){const a=[];for(const o of i)typeof o=="string"?a.push(Zr(o,n,e)):typeof o=="object"&&a.push(Zg(o,e,n));r[s]=a}else typeof i=="object"&&i!==null?r[s]=Zg(i,e,n):r[s]=i;return r}var jf=class extends ze{constructor(){super(...arguments);m(this,"lc_namespace",["langchain_core","prompts","chat"]);m(this,"lc_serializable",!0)}async invoke(e,n){return this._callWithConfig(r=>this.formatMessages(r),e,{...n,runType:"prompt"})}},qg=class extends jf{constructor(e){typeof e=="string"&&(e={variableName:e});super(e);m(this,"variableName");m(this,"optional");this.variableName=e.variableName,this.optional=e.optional??!1}static lc_name(){return"MessagesPlaceholder"}get inputVariables(){return[this.variableName]}async formatMessages(e){const n=e[this.variableName];if(this.optional&&!n)return[];if(!n){const s=new Error(`Field "${this.variableName}" in prompt uses a MessagesPlaceholder, which expects an array of BaseMessages as an input value. Received: undefined`);throw s.name="InputFormatError",s}let r;try{Array.isArray(n)?r=n.map(_s):r=[_s(n)]}catch(s){const i=typeof n=="string"?n:JSON.stringify(n,null,2),a=new Error([`Field "${this.variableName}" in prompt uses a MessagesPlaceholder, which expects an array of BaseMessages or coerceable values as input.`,`Received value: ${i}`,`Additional message: ${s.message}`].join(`
|
|
215
|
-
|
|
216
|
-
`));throw a.name="InputFormatError",a.lc_error_code=s.lc_error_code,a}return r}},Dx=class extends jf{constructor(e){"prompt"in e||(e={prompt:e});super(e);m(this,"prompt");this.prompt=e.prompt}get inputVariables(){return this.prompt.inputVariables}async formatMessages(e){return[await this.format(e)]}},nw=class extends El{constructor(t){super(t)}async format(t){return(await this.formatPromptValue(t)).toString()}async formatPromptValue(t){return new Zy(await this.formatMessages(t))}},Ux=class extends Dx{constructor(e,n){"prompt"in e||(e={prompt:e,role:n});super(e);m(this,"role");this.role=e.role}static lc_name(){return"ChatMessagePromptTemplate"}async format(e){return new Ts(await this.prompt.format(e),this.role)}static fromTemplate(e,n,r){return new this(Ei.fromTemplate(e,{templateFormat:r==null?void 0:r.templateFormat}),n)}};function x3(t){return t===null||typeof t!="object"||Array.isArray(t)?!1:Object.keys(t).length===1&&"text"in t&&typeof t.text=="string"}function k3(t){return t===null||typeof t!="object"||Array.isArray(t)?!1:"image_url"in t&&(typeof t.image_url=="string"||typeof t.image_url=="object"&&t.image_url!==null&&"url"in t.image_url&&typeof t.image_url.url=="string")}var rw=class extends jf{constructor(e,n){"prompt"in e||(e={prompt:e});super(e);m(this,"lc_namespace",["langchain_core","prompts","chat"]);m(this,"lc_serializable",!0);m(this,"inputVariables",[]);m(this,"additionalOptions",{});m(this,"prompt");m(this,"messageClass");m(this,"chatMessageClass");if(this.prompt=e.prompt,Array.isArray(this.prompt)){let r=[];this.prompt.forEach(s=>{"inputVariables"in s&&(r=r.concat(s.inputVariables))}),this.inputVariables=r}else this.inputVariables=this.prompt.inputVariables;this.additionalOptions=n??this.additionalOptions}static _messageClass(){throw new Error("Can not invoke _messageClass from inside _StringImageMessagePromptTemplate")}createMessage(e){const n=this.constructor;if(n._messageClass())return new(n._messageClass())({content:e});if(n.chatMessageClass){const r=n.chatMessageClass();return new r({content:e,role:this.getRoleFromMessageClass(r.lc_name())})}else throw new Error("No message class defined")}getRoleFromMessageClass(e){switch(e){case"HumanMessage":return"human";case"AIMessage":return"ai";case"SystemMessage":return"system";case"ChatMessage":return"chat";default:throw new Error("Invalid message class name")}}static fromTemplate(e,n){if(typeof e=="string")return new this(Ei.fromTemplate(e,n));const r=[];for(const s of e)if(typeof s=="string")r.push(Ei.fromTemplate(s,n));else if(s!==null)if(x3(s)){let i="";typeof s.text=="string"&&(i=s.text??"");const a={...n,additionalContentFields:s};r.push(Ei.fromTemplate(i,a))}else if(k3(s)){let i=s.image_url??"",a,o=[];if(typeof i=="string"){let c;(n==null?void 0:n.templateFormat)==="mustache"?c=Fh(i):c=Du(i);const u=c.flatMap(l=>l.type==="variable"?[l.name]:[]);if(((u==null?void 0:u.length)??0)>0){if(u.length>1)throw new Error(`Only one format variable allowed per image template.
|
|
217
|
-
Got: ${u}
|
|
218
|
-
From: ${i}`);o=[u[0]]}else o=[];i={url:i},a=new Vd({template:i,inputVariables:o,templateFormat:n==null?void 0:n.templateFormat,additionalContentFields:s})}else if(typeof i=="object"){if("url"in i){let c;(n==null?void 0:n.templateFormat)==="mustache"?c=Fh(i.url):c=Du(i.url),o=c.flatMap(u=>u.type==="variable"?[u.name]:[])}else o=[];a=new Vd({template:i,inputVariables:o,templateFormat:n==null?void 0:n.templateFormat,additionalContentFields:s})}else throw new Error("Invalid image template");r.push(a)}else typeof s=="object"&&r.push(new Kg({template:s,templateFormat:n==null?void 0:n.templateFormat}));return new this({prompt:r,additionalOptions:n})}async format(e){if(this.prompt instanceof Lu){const n=await this.prompt.format(e);return this.createMessage(n)}else{const n=[];for(const r of this.prompt){let s={};if(!("inputVariables"in r))throw new Error(`Prompt ${r} does not have inputVariables defined.`);for(const i of r.inputVariables)s||(s={[i]:e[i]}),s={...s,[i]:e[i]};if(r instanceof Lu){const i=await r.format(s);let a;"additionalContentFields"in r&&(a=r.additionalContentFields),i!==""&&n.push({...a,type:"text",text:i})}else if(r instanceof Vd){const i=await r.format(s);let a;"additionalContentFields"in r&&(a=r.additionalContentFields),n.push({...a,type:"image_url",image_url:i})}else if(r instanceof Kg){const i=await r.format(s);let a;"additionalContentFields"in r&&(a=r.additionalContentFields),n.push({...a,...i})}}return this.createMessage(n)}}async formatMessages(e){return[await this.format(e)]}},sw=class extends rw{static _messageClass(){return Nn}static lc_name(){return"HumanMessagePromptTemplate"}},Fx=class extends rw{static _messageClass(){return De}static lc_name(){return"AIMessagePromptTemplate"}},Bx=class extends rw{static _messageClass(){return lr}static lc_name(){return"SystemMessagePromptTemplate"}};function C3(t){return typeof t.formatMessages=="function"}function O3(t,e){if(C3(t)||Et(t))return t;if(Array.isArray(t)&&t[0]==="placeholder"){const s=t[1];if((e==null?void 0:e.templateFormat)==="mustache"&&typeof s=="string"&&s.slice(0,2)==="{{"&&s.slice(-2)==="}}")return new qg({variableName:s.slice(2,-2),optional:!0});if(typeof s=="string"&&s[0]==="{"&&s[s.length-1]==="}")return new qg({variableName:s.slice(1,-1),optional:!0});throw new Error(`Invalid placeholder template for format ${(e==null?void 0:e.templateFormat)??'"f-string"'}: "${t[1]}". Expected a variable name surrounded by ${(e==null?void 0:e.templateFormat)==="mustache"?"double":"single"} curly braces.`)}const n=_s(t);let r;if(typeof n.content=="string"?r=n.content:r=n.content.map(s=>"text"in s?{...s,text:s.text}:"image_url"in s?{...s,image_url:s.image_url}:s),n._getType()==="human")return sw.fromTemplate(r,e);if(n._getType()==="ai")return Fx.fromTemplate(r,e);if(n._getType()==="system")return Bx.fromTemplate(r,e);if(Ts.isInstance(n))return Ux.fromTemplate(n.content,n.role,e);throw new Error(`Could not coerce message prompt template from input. Received message type: "${n._getType()}".`)}function $3(t){return t.constructor.lc_name()==="MessagesPlaceholder"}var iw=class Kd extends nw{constructor(n){super(n);m(this,"promptMessages");m(this,"validateTemplate",!0);m(this,"templateFormat","f-string");if(n.templateFormat==="mustache"&&n.validateTemplate===void 0&&(this.validateTemplate=!1),Object.assign(this,n),this.validateTemplate){const r=new Set;for(const c of this.promptMessages)if(!(c instanceof Ot))for(const u of c.inputVariables)r.add(u);const s=this.inputVariables,i=new Set(this.partialVariables?s.concat(Object.keys(this.partialVariables)):s),a=new Set([...i].filter(c=>!r.has(c)));if(a.size>0)throw new Error(`Input variables \`${[...a]}\` are not used in any of the prompt messages.`);const o=new Set([...r].filter(c=>!i.has(c)));if(o.size>0)throw new Error(`Input variables \`${[...o]}\` are used in prompt messages but not in the prompt template.`)}}static lc_name(){return"ChatPromptTemplate"}get lc_aliases(){return{promptMessages:"messages"}}_getPromptType(){return"chat"}async _parseImagePrompts(n,r){return typeof n.content=="string"||(n.content=await Promise.all(n.content.map(async s=>{if(s.type!=="image_url")return s;let i="";typeof s.image_url=="string"?i=s.image_url:typeof s.image_url=="object"&&s.image_url!==null&&"url"in s.image_url&&typeof s.image_url.url=="string"&&(i=s.image_url.url);const a=await Ei.fromTemplate(i,{templateFormat:this.templateFormat}).format(r);return typeof s.image_url=="object"&&s.image_url!==null&&"url"in s.image_url?s.image_url.url=a:s.image_url=a,s}))),n}async formatMessages(n){const r=await this.mergePartialAndUserVariables(n);let s=[];for(const i of this.promptMessages)if(i instanceof Ot)s.push(await this._parseImagePrompts(i,r));else{let a;this.templateFormat==="mustache"?a={...r}:a=i.inputVariables.reduce((c,u)=>{if(!(u in r)&&!($3(i)&&i.optional))throw cl(new Error(`Missing value for input variable \`${u.toString()}\``),"INVALID_PROMPT_INPUT");return c[u]=r[u],c},{});const o=await i.formatMessages(a);s=s.concat(o)}return s}async partial(n){const r=this.inputVariables.filter(i=>!(i in n)),s={...this.partialVariables??{},...n};return new Kd({...this,inputVariables:r,partialVariables:s})}static fromTemplate(n,r){const s=new sw({prompt:Ei.fromTemplate(n,r)});return this.fromMessages([s])}static fromMessages(n,r){const s=n.reduce((o,c)=>o.concat(c instanceof Kd?c.promptMessages:[O3(c,r)]),[]),i=n.reduce((o,c)=>c instanceof Kd?Object.assign(o,c.partialVariables):o,Object.create(null)),a=new Set;for(const o of s)if(!(o instanceof Ot))for(const c of o.inputVariables)c in i||a.add(c);return new this({...r,inputVariables:[...a],promptMessages:s,partialVariables:i,templateFormat:r==null?void 0:r.templateFormat})}},R3=class Gg extends Lu{constructor(n){super(n);m(this,"lc_serializable",!1);m(this,"examples");m(this,"exampleSelector");m(this,"examplePrompt");m(this,"suffix","");m(this,"exampleSeparator",`
|
|
219
|
-
|
|
220
|
-
`);m(this,"prefix","");m(this,"templateFormat","f-string");m(this,"validateTemplate",!0);if(Object.assign(this,n),this.examples!==void 0&&this.exampleSelector!==void 0)throw new Error("Only one of 'examples' and 'example_selector' should be provided");if(this.examples===void 0&&this.exampleSelector===void 0)throw new Error("One of 'examples' and 'example_selector' should be provided");if(this.validateTemplate){let r=this.inputVariables;this.partialVariables&&(r=r.concat(Object.keys(this.partialVariables))),xl(this.prefix+this.suffix,this.templateFormat,r)}}_getPromptType(){return"few_shot"}static lc_name(){return"FewShotPromptTemplate"}async getExamples(n){if(this.examples!==void 0)return this.examples;if(this.exampleSelector!==void 0)return this.exampleSelector.selectExamples(n);throw new Error("One of 'examples' and 'example_selector' should be provided")}async partial(n){const r=this.inputVariables.filter(i=>!(i in n)),s={...this.partialVariables??{},...n};return new Gg({...this,inputVariables:r,partialVariables:s})}async format(n){const r=await this.mergePartialAndUserVariables(n),s=await this.getExamples(r),i=await Promise.all(s.map(a=>this.examplePrompt.format(a)));return Zr([this.prefix,...i,this.suffix].join(this.exampleSeparator),this.templateFormat,r)}serialize(){if(this.exampleSelector||!this.examples)throw new Error("Serializing an example selector is not currently supported");if(this.outputParser!==void 0)throw new Error("Serializing an output parser is not currently supported");return{_type:this._getPromptType(),input_variables:this.inputVariables,example_prompt:this.examplePrompt.serialize(),example_separator:this.exampleSeparator,suffix:this.suffix,prefix:this.prefix,template_format:this.templateFormat,examples:this.examples}}static async deserialize(n){const{example_prompt:r}=n;if(!r)throw new Error("Missing example prompt");const s=await Ei.deserialize(r);let i;if(Array.isArray(n.examples))i=n.examples;else throw new Error("Invalid examples format. Only list or string are supported.");return new Gg({inputVariables:n.input_variables,examplePrompt:s,examples:i,exampleSeparator:n.example_separator,prefix:n.prefix,suffix:n.suffix,templateFormat:n.template_format})}},P3=class zx extends nw{constructor(n){super(n);m(this,"lc_serializable",!0);m(this,"examples");m(this,"exampleSelector");m(this,"examplePrompt");m(this,"suffix","");m(this,"exampleSeparator",`
|
|
221
|
-
|
|
222
|
-
`);m(this,"prefix","");m(this,"templateFormat","f-string");m(this,"validateTemplate",!0);if(this.examples=n.examples,this.examplePrompt=n.examplePrompt,this.exampleSeparator=n.exampleSeparator??`
|
|
223
|
-
|
|
224
|
-
`,this.exampleSelector=n.exampleSelector,this.prefix=n.prefix??"",this.suffix=n.suffix??"",this.templateFormat=n.templateFormat??"f-string",this.validateTemplate=n.validateTemplate??!0,this.examples!==void 0&&this.exampleSelector!==void 0)throw new Error("Only one of 'examples' and 'example_selector' should be provided");if(this.examples===void 0&&this.exampleSelector===void 0)throw new Error("One of 'examples' and 'example_selector' should be provided");if(this.validateTemplate){let r=this.inputVariables;this.partialVariables&&(r=r.concat(Object.keys(this.partialVariables))),xl(this.prefix+this.suffix,this.templateFormat,r)}}_getPromptType(){return"few_shot_chat"}static lc_name(){return"FewShotChatMessagePromptTemplate"}async getExamples(n){if(this.examples!==void 0)return this.examples;if(this.exampleSelector!==void 0)return this.exampleSelector.selectExamples(n);throw new Error("One of 'examples' and 'example_selector' should be provided")}async formatMessages(n){const r=await this.mergePartialAndUserVariables(n);let s=await this.getExamples(r);s=s.map(a=>{const o={};return this.examplePrompt.inputVariables.forEach(c=>{o[c]=a[c]}),o});const i=[];for(const a of s){const o=await this.examplePrompt.formatMessages(a);i.push(...o)}return i}async format(n){const r=await this.mergePartialAndUserVariables(n),s=await this.getExamples(r),i=(await Promise.all(s.map(a=>this.examplePrompt.formatMessages(a)))).flat().map(a=>a.content);return Zr([this.prefix,...i,this.suffix].join(this.exampleSeparator),this.templateFormat,r)}async partial(n){const r=this.inputVariables.filter(i=>!(i in n)),s={...this.partialVariables??{},...n};return new zx({...this,inputVariables:r,partialVariables:s})}},N3=class Wd extends El{constructor(n){super({...n,inputVariables:[]});m(this,"pipelinePrompts");m(this,"finalPrompt");this.pipelinePrompts=n.pipelinePrompts,this.finalPrompt=n.finalPrompt,this.inputVariables=this.computeInputValues()}static lc_name(){return"PipelinePromptTemplate"}computeInputValues(){const n=this.pipelinePrompts.map(s=>s.name),r=this.pipelinePrompts.map(s=>s.prompt.inputVariables.filter(i=>!n.includes(i))).flat();return[...new Set(r)]}static extractRequiredInputValues(n,r){return r.reduce((s,i)=>(s[i]=n[i],s),{})}async formatPipelinePrompts(n){const r=await this.mergePartialAndUserVariables(n);for(const{name:s,prompt:i}of this.pipelinePrompts){const a=Wd.extractRequiredInputValues(r,i.inputVariables);i instanceof iw?r[s]=await i.formatMessages(a):r[s]=await i.format(a)}return Wd.extractRequiredInputValues(r,this.finalPrompt.inputVariables)}async formatPromptValue(n){return this.finalPrompt.formatPromptValue(await this.formatPipelinePrompts(n))}async format(n){return this.finalPrompt.format(await this.formatPipelinePrompts(n))}async partial(n){const r={...this};return r.inputVariables=this.inputVariables.filter(s=>!(s in n)),r.partialVariables={...this.partialVariables??{},...n},new Wd(r)}serialize(){throw new Error("Not implemented.")}_getPromptType(){return"pipeline"}};function Mv(t){return typeof t=="object"&&t!=null&&"withStructuredOutput"in t&&typeof t.withStructuredOutput=="function"}function M3(t){return typeof t=="object"&&t!=null&&"lc_id"in t&&Array.isArray(t.lc_id)&&t.lc_id.join("/")==="langchain_core/runnables/RunnableBinding"}var L3=class Hx extends iw{constructor(n){super(n);m(this,"schema");m(this,"method");m(this,"lc_namespace",["langchain_core","prompts","structured"]);this.schema=n.schema,this.method=n.method}get lc_aliases(){return{...super.lc_aliases,schema:"schema_"}}pipe(n){if(Mv(n))return super.pipe(n.withStructuredOutput(this.schema));if(M3(n)&&Mv(n.bound))return super.pipe(new dn({bound:n.bound.withStructuredOutput(this.schema,...this.method?[{method:this.method}]:[]),kwargs:n.kwargs??{},config:n.config,configFactories:n.configFactories}));throw new Error('Structured prompts need to be piped to a language model that supports the "withStructuredOutput()" method.')}static fromMessagesAndSchema(n,r,s){return Hx.fromMessages(n,{schema:r,method:s})}},j3=de({AIMessagePromptTemplate:()=>Fx,BaseChatPromptTemplate:()=>nw,BaseMessagePromptTemplate:()=>jf,BaseMessageStringPromptTemplate:()=>Dx,BasePromptTemplate:()=>El,BaseStringPromptTemplate:()=>Lu,ChatMessagePromptTemplate:()=>Ux,ChatPromptTemplate:()=>iw,DEFAULT_FORMATTER_MAPPING:()=>Bh,DEFAULT_PARSER_MAPPING:()=>Lx,DictPromptTemplate:()=>Kg,FewShotChatMessagePromptTemplate:()=>P3,FewShotPromptTemplate:()=>R3,HumanMessagePromptTemplate:()=>sw,ImagePromptTemplate:()=>Vd,MessagesPlaceholder:()=>qg,PipelinePromptTemplate:()=>N3,PromptTemplate:()=>Ei,StructuredPrompt:()=>L3,SystemMessagePromptTemplate:()=>Bx,checkValidTemplate:()=>xl,interpolateFString:()=>Nx,interpolateMustache:()=>Mx,parseFString:()=>Du,parseMustache:()=>Fh,parseTemplate:()=>zh,renderTemplate:()=>Zr}),D3=de({BaseDocumentCompressor:()=>U3}),U3=class{static isBaseDocumentCompressor(t){return(t==null?void 0:t.compressDocuments)!==void 0}},F3=de({BaseRetriever:()=>aw}),aw=class extends ze{constructor(e){super(e);m(this,"callbacks");m(this,"tags");m(this,"metadata");m(this,"verbose");this.callbacks=e==null?void 0:e.callbacks,this.tags=(e==null?void 0:e.tags)??[],this.metadata=(e==null?void 0:e.metadata)??{},this.verbose=(e==null?void 0:e.verbose)??!1}_getRelevantDocuments(e,n){throw new Error("Not implemented!")}async invoke(e,n){var i;const r=Je(ml(n)),s=await((i=await bn.configure(r.callbacks,this.callbacks,r.tags,this.tags,r.metadata,this.metadata,{verbose:this.verbose}))==null?void 0:i.handleRetrieverStart(this.toJSON(),e,r.runId,void 0,void 0,void 0,r.runName));try{const a=await this._getRelevantDocuments(e,s);return await(s==null?void 0:s.handleRetrieverEnd(a)),a}catch(a){throw await(s==null?void 0:s.handleRetrieverError(a)),a}}},B3=de({BaseStore:()=>Vx,InMemoryStore:()=>z3}),Vx=class extends xr{},z3=class extends Vx{constructor(){super(...arguments);m(this,"lc_namespace",["langchain","storage"]);m(this,"store",{})}async mget(e){return e.map(n=>this.store[n])}async mset(e){for(const[n,r]of e)this.store[n]=r}async mdelete(e){for(const n of e)delete this.store[n]}async*yieldKeys(e){const n=Object.keys(this.store);for(const r of n)(e===void 0||r.startsWith(e))&&(yield r)}};const gi={and:"and",or:"or",not:"not"},qe={eq:"eq",ne:"ne",lt:"lt",gt:"gt",lte:"lte",gte:"gte"};var Kx=class{},ow=class{accept(t){if(this.exprName==="Operation")return t.visitOperation(this);if(this.exprName==="Comparison")return t.visitComparison(this);if(this.exprName==="StructuredQuery")return t.visitStructuredQuery(this);throw new Error("Unknown Expression type")}},cw=class extends ow{},H3=class extends cw{constructor(e,n,r){super();m(this,"exprName","Comparison");this.comparator=e,this.attribute=n,this.value=r}},V3=class extends cw{constructor(e,n){super();m(this,"exprName","Operation");this.operator=e,this.args=n}},K3=class extends ow{constructor(e,n){super();m(this,"exprName","StructuredQuery");this.query=e,this.filter=n}};function Wx(t){return t&&typeof t=="object"&&!Array.isArray(t)}function Kr(t){return t?typeof t=="string"&&t.length>0||typeof t=="function"?!1:Wx(t)&&Object.keys(t).length===0:!0}function Zx(t){if(typeof t=="number")return t%1===0;if(typeof t=="string"){const e=parseInt(t,10);return!Number.isNaN(e)&&e%1===0&&e.toString()===t}return!1}function qx(t){if(typeof t=="number")return t%1!==0;if(typeof t=="string"){const e=parseFloat(t);return!Number.isNaN(e)&&e%1!==0&&e.toString()===t}return!1}function Gx(t){return typeof t=="string"&&(Number.isNaN(parseFloat(t))||parseFloat(t).toString()!==t)}function Jx(t){return typeof t=="boolean"}function uw(t){let e;if(Gx(t))e=t;else if(Zx(t))e=parseInt(t,10);else if(qx(t))e=parseFloat(t);else if(Jx(t))e=!!t;else throw new Error("Unsupported value type");return e}var lw=class extends Kx{},W3=class extends lw{constructor(e){super();m(this,"allowedOperators");m(this,"allowedComparators");this.allowedOperators=(e==null?void 0:e.allowedOperators)??[gi.and,gi.or],this.allowedComparators=(e==null?void 0:e.allowedComparators)??[qe.eq,qe.ne,qe.gt,qe.gte,qe.lt,qe.lte]}formatFunction(e){if(e in qe){if(this.allowedComparators.length>0&&this.allowedComparators.indexOf(e)===-1)throw new Error(`Comparator ${e} not allowed. Allowed comparators: ${this.allowedComparators.join(", ")}`)}else if(e in gi){if(this.allowedOperators.length>0&&this.allowedOperators.indexOf(e)===-1)throw new Error(`Operator ${e} not allowed. Allowed operators: ${this.allowedOperators.join(", ")}`)}else throw new Error("Unknown comparator or operator");return`$${e}`}visitOperation(e){var r;const n=(r=e.args)==null?void 0:r.map(s=>s.accept(this));return{[this.formatFunction(e.operator)]:n}}visitComparison(e){return{[e.attribute]:{[this.formatFunction(e.comparator)]:uw(e.value)}}}visitStructuredQuery(e){let n={};return e.filter&&(n={filter:e.filter.accept(this)}),n}mergeFilters(e,n,r="and",s=!1){if(!(Kr(e)&&Kr(n))){if(Kr(e)||r==="replace")return Kr(n)?void 0:n;if(Kr(n))return s?e:r==="and"?void 0:e;if(r==="and")return{$and:[e,n]};if(r==="or")return{$or:[e,n]};throw new Error("Unknown merge type")}}},Z3=class extends lw{constructor(){super(...arguments);m(this,"allowedOperators",[gi.and,gi.or]);m(this,"allowedComparators",[qe.eq,qe.ne,qe.gt,qe.gte,qe.lt,qe.lte])}formatFunction(){throw new Error("Not implemented")}getAllowedComparatorsForType(e){switch(e){case"string":return[qe.eq,qe.ne,qe.gt,qe.gte,qe.lt,qe.lte];case"number":return[qe.eq,qe.ne,qe.gt,qe.gte,qe.lt,qe.lte];case"boolean":return[qe.eq,qe.ne];default:throw new Error(`Unsupported data type: ${e}`)}}getComparatorFunction(e){switch(e){case qe.eq:return(n,r)=>n===r;case qe.ne:return(n,r)=>n!==r;case qe.gt:return(n,r)=>n>r;case qe.gte:return(n,r)=>n>=r;case qe.lt:return(n,r)=>n<r;case qe.lte:return(n,r)=>n<=r;default:throw new Error("Unknown comparator")}}getOperatorFunction(e){switch(e){case gi.and:return(n,r)=>n&&r;case gi.or:return(n,r)=>n||r;default:throw new Error("Unknown operator")}}visitOperation(e){const{operator:n,args:r}=e;if(this.allowedOperators.includes(n)){const s=this.getOperatorFunction(n);return i=>r?r.reduce((a,o)=>{const c=o.accept(this);if(typeof c=="function")return s(a,c(i));throw new Error("Filter is not a function")},!0):!0}else throw new Error("Operator not allowed")}visitComparison(e){const{comparator:n,attribute:r,value:s}=e,i=[qe.ne];if(this.allowedComparators.includes(n)){if(!this.getAllowedComparatorsForType(typeof s).includes(n))throw new Error(`'${n}' comparator not allowed to be used with ${typeof s}`);const a=this.getComparatorFunction(n);return o=>{const c=o.metadata[r];return c===void 0?!!i.includes(n):a(c,uw(s))}}else throw new Error("Comparator not allowed")}visitStructuredQuery(e){var r;if(!e.filter)return{};const n=(r=e.filter)==null?void 0:r.accept(this);if(typeof n!="function")throw new Error("Structured query filter is not a function");return{filter:n}}mergeFilters(e,n,r="and"){if(!(Kr(e)&&Kr(n))){if(Kr(e)||r==="replace")return Kr(n)?void 0:n;if(Kr(n))return r==="and"?void 0:e;if(r==="and")return s=>e(s)&&n(s);if(r==="or")return s=>e(s)||n(s);throw new Error("Unknown merge type")}}},q3=de({BaseTranslator:()=>lw,BasicTranslator:()=>W3,Comparators:()=>qe,Comparison:()=>H3,Expression:()=>ow,FilterDirective:()=>cw,FunctionalTranslator:()=>Z3,Operation:()=>V3,Operators:()=>gi,StructuredQuery:()=>K3,Visitor:()=>Kx,castValue:()=>uw,isBoolean:()=>Jx,isFilterEmpty:()=>Kr,isFloat:()=>qx,isInt:()=>Zx,isObject:()=>Wx,isString:()=>Gx});function Uu(t){return Ot.isInstance(t)?t.constructor.name||t.type:typeof t}function Df(t,e){return function(n,r){const{isNot:s,utils:i}=this;if(!e(n))return{pass:!1,message:()=>`${i.matcherHint(`toBe${t}`,void 0,void 0)}
|
|
225
|
-
|
|
226
|
-
Expected: ${s?"not ":""}${t}
|
|
227
|
-
Received: ${Uu(n)}`,actual:Uu(n),expected:t};if(r===void 0)return{pass:!0,message:()=>`${i.matcherHint(`toBe${t}`,void 0,void 0)}
|
|
228
|
-
|
|
229
|
-
Expected: not ${t}
|
|
230
|
-
Received: ${t}`};const a=n;return typeof r=="string"?{pass:a.content===r,message:()=>`${i.matcherHint(`toBe${t}`,void 0,void 0)}
|
|
231
|
-
|
|
232
|
-
Expected: ${t} with content ${i.printExpected(r)}
|
|
233
|
-
Received: ${t} with content ${i.printReceived(a.content)}`,actual:a.content,expected:r}:{pass:Object.entries(r).every(([o,c])=>this.equals(a[o],c)),message:()=>{const o={};for(const c of Object.keys(r))o[c]=a[c];return`${i.matcherHint(`toBe${t}`,void 0,void 0)}
|
|
234
|
-
|
|
235
|
-
Expected: ${t} matching ${i.printExpected(r)}
|
|
236
|
-
Received: ${t} with ${i.printReceived(o)}`},actual:(()=>{const o={};for(const c of Object.keys(r))o[c]=a[c];return o})(),expected:r}}}const Yx=Df("HumanMessage",Nn.isInstance),Xx=Df("AIMessage",De.isInstance),Qx=Df("SystemMessage",lr.isInstance),ek=Df("ToolMessage",fn.isInstance);function tk(t,e){const{isNot:n,utils:r}=this;if(!De.isInstance(t))return{pass:!1,message:()=>`${r.matcherHint("toHaveToolCalls")}
|
|
237
|
-
|
|
238
|
-
Expected: AIMessage
|
|
239
|
-
Received: ${Uu(t)}`};const s=t.tool_calls??[];if(s.length!==e.length)return{pass:!1,message:()=>`${r.matcherHint("toHaveToolCalls")}
|
|
240
|
-
|
|
241
|
-
Expected ${n?"not ":""}${e.length} tool call(s), received ${s.length}`,actual:s.length,expected:e.length};const i=e.filter(a=>!s.some(o=>Object.entries(a).every(([c,u])=>this.equals(o[c],u))));return i.length>0?{pass:!1,message:()=>`${r.matcherHint("toHaveToolCalls")}
|
|
242
|
-
|
|
243
|
-
Could not find matching tool call(s) for:
|
|
244
|
-
${r.printExpected(i)}
|
|
245
|
-
Received tool calls: ${r.printReceived(s.map(a=>({name:a.name,id:a.id,args:a.args})))}`,actual:s.map(a=>({name:a.name,id:a.id,args:a.args})),expected:e}:{pass:!0,message:()=>`${r.matcherHint("toHaveToolCalls")}
|
|
246
|
-
|
|
247
|
-
Expected AIMessage not to have matching tool calls`}}function nk(t,e){var i;const{isNot:n,utils:r}=this;if(!De.isInstance(t))return{pass:!1,message:()=>`${r.matcherHint("toHaveToolCallCount")}
|
|
248
|
-
|
|
249
|
-
Expected: AIMessage
|
|
250
|
-
Received: ${Uu(t)}`};const s=((i=t.tool_calls)==null?void 0:i.length)??0;return{pass:s===e,message:()=>`${r.matcherHint("toHaveToolCallCount")}
|
|
251
|
-
|
|
252
|
-
Expected ${n?"not ":""}${e} tool call(s)
|
|
253
|
-
Received: ${s}`,actual:s,expected:e}}function rk(t,e){const{isNot:n,utils:r}=this;if(!De.isInstance(t))return{pass:!1,message:()=>`${r.matcherHint("toContainToolCall")}
|
|
254
|
-
|
|
255
|
-
Expected: AIMessage
|
|
256
|
-
Received: ${Uu(t)}`};const s=t.tool_calls??[];return{pass:s.some(i=>Object.entries(e).every(([a,o])=>this.equals(i[a],o))),message:()=>`${r.matcherHint("toContainToolCall")}
|
|
257
|
-
|
|
258
|
-
Expected AIMessage ${n?"not ":""}to contain a tool call matching ${r.printExpected(e)}
|
|
259
|
-
Received tool calls: ${r.printReceived(s.map(i=>({name:i.name,id:i.id})))}`,actual:s.map(i=>({name:i.name,id:i.id})),expected:e}}function sk(t,e){const{isNot:n,utils:r}=this;if(!Array.isArray(t))return{pass:!1,message:()=>`${r.matcherHint("toHaveToolMessages")}
|
|
260
|
-
|
|
261
|
-
Expected an array of messages
|
|
262
|
-
Received: ${typeof t}`};const s=t.filter(fn.isInstance);if(s.length!==e.length)return{pass:!1,message:()=>`${r.matcherHint("toHaveToolMessages")}
|
|
263
|
-
|
|
264
|
-
Expected ${n?"not ":""}${e.length} tool message(s), found ${s.length}`,actual:s.length,expected:e.length};for(let i=0;i<e.length;i++)if(!Object.entries(e[i]).every(([a,o])=>this.equals(s[i][a],o)))return{pass:!1,message:()=>{const a={};for(const o of Object.keys(e[i]))a[o]=s[i][o];return`${r.matcherHint("toHaveToolMessages")}
|
|
265
|
-
|
|
266
|
-
Tool message at index ${i} did not match:
|
|
267
|
-
Expected: ${r.printExpected(e[i])}
|
|
268
|
-
Received: ${r.printReceived(a)}`},actual:s[i],expected:e[i]};return{pass:!0,message:()=>`${r.matcherHint("toHaveToolMessages")}
|
|
269
|
-
|
|
270
|
-
Expected messages not to contain matching tool messages`}}function ik(t,e){var a;const{isNot:n,utils:r}=this,s=t==null?void 0:t.__interrupt__;if(!(Array.isArray(s)&&s.length>0))return{pass:!1,message:()=>`${r.matcherHint("toHaveBeenInterrupted")}
|
|
271
|
-
|
|
272
|
-
Expected result ${n?"not ":""}to have been interrupted
|
|
273
|
-
Received __interrupt__: ${r.printReceived(s)}`};if(e===void 0)return{pass:!0,message:()=>`${r.matcherHint("toHaveBeenInterrupted")}
|
|
274
|
-
|
|
275
|
-
Expected result not to have been interrupted
|
|
276
|
-
Received ${s.length} interrupt(s)`};const i=(a=s[0])==null?void 0:a.value;return{pass:this.equals(i,e),message:()=>`${r.matcherHint("toHaveBeenInterrupted")}
|
|
277
|
-
|
|
278
|
-
Expected interrupt value: ${r.printExpected(e)}
|
|
279
|
-
Received interrupt value: ${r.printReceived(i)}`,actual:i,expected:e}}function ak(t,e){const{isNot:n,utils:r}=this,s=t==null?void 0:t.structuredResponse;return s===void 0?{pass:!1,message:()=>`${r.matcherHint("toHaveStructuredResponse")}
|
|
280
|
-
|
|
281
|
-
Expected result ${n?"not ":""}to have a structured response
|
|
282
|
-
Received structuredResponse: undefined`}:e===void 0?{pass:!0,message:()=>`${r.matcherHint("toHaveStructuredResponse")}
|
|
283
|
-
|
|
284
|
-
Expected result not to have a structured response`}:{pass:Object.entries(e).every(([i,a])=>this.equals(s[i],a)),message:()=>`${r.matcherHint("toHaveStructuredResponse")}
|
|
285
|
-
|
|
286
|
-
Expected structured response: ${r.printExpected(e)}
|
|
287
|
-
Received structured response: ${r.printReceived(s)}`,actual:s,expected:e}}const G3={toBeHumanMessage:Yx,toBeAIMessage:Xx,toBeSystemMessage:Qx,toBeToolMessage:ek,toHaveToolCalls:tk,toHaveToolCallCount:nk,toContainToolCall:rk,toHaveToolMessages:sk,toHaveBeenInterrupted:ik,toHaveStructuredResponse:ak};function J3(t){return t.map(e=>e.text).filter(Boolean).join("-")}let Lv=0;function Y3(){return Lv+=1,`fake_tc_${Lv}`}var ok=class ck extends Es{constructor(){super({});m(this,"queue",[]);m(this,"_alwaysThrowError");m(this,"_structuredResponseValue");m(this,"_tools",[]);m(this,"_state",{callIndex:0,calls:[]})}get calls(){return this._state.calls}get callCount(){return this._state.calls.length}_llmType(){return"fake-model-builder"}_combineLLMOutput(){return[]}respond(n){return typeof n=="function"?this.queue.push({kind:"factory",factory:n}):Ot.isInstance(n)?this.queue.push({kind:"message",message:n}):this.queue.push({kind:"error",error:n}),this}respondWithTools(n){return this.queue.push({kind:"toolCalls",toolCalls:n.map(r=>({name:r.name,args:r.args,id:r.id??Y3(),type:"tool_call"}))}),this}alwaysThrow(n){return this._alwaysThrowError=n,this}structuredResponse(n){return this._structuredResponseValue=n,this}bindTools(n){const r=[...this._tools,...n],s=new ck;return s.queue=this.queue,s._alwaysThrowError=this._alwaysThrowError,s._structuredResponseValue=this._structuredResponseValue,s._tools=r,s._state=this._state,s.withConfig({})}withStructuredOutput(n,r){const{_structuredResponseValue:s}=this;return en.from(async()=>s)}async _generate(n,r,s){this._state.calls.push({messages:[...n],options:r});const i=this._state.callIndex;if(this._state.callIndex+=1,this._alwaysThrowError)throw this._alwaysThrowError;const a=this.queue[i];if(!a)throw new Error(`FakeModel: no response queued for invocation ${i} (${this.queue.length} total queued).`);if(a.kind==="error")throw a.error;if(a.kind==="factory"){const c=a.factory(n);if(!Ot.isInstance(c))throw c;return{generations:[{text:"",message:c}]}}if(a.kind==="message")return{generations:[{text:"",message:a.message}]};const o=J3(n);return{generations:[{text:o,message:new De({content:o,id:i.toString(),tool_calls:a.toolCalls.length>0?a.toolCalls.map(c=>({...c,type:"tool_call"})):void 0})}],llmOutput:{}}}};function X3(){return new ok}var Q3=de({FakeBuiltModel:()=>ok,fakeModel:()=>X3,langchainMatchers:()=>G3,toBeAIMessage:()=>Xx,toBeHumanMessage:()=>Yx,toBeSystemMessage:()=>Qx,toBeToolMessage:()=>ek,toContainToolCall:()=>rk,toHaveBeenInterrupted:()=>ik,toHaveStructuredResponse:()=>ak,toHaveToolCallCount:()=>nk,toHaveToolCalls:()=>tk,toHaveToolMessages:()=>sk});function dw(t){return t!==void 0&&Array.isArray(t.lc_namespace)}function hw(t){return t!==void 0&&ze.isRunnable(t)&&"lc_name"in t.constructor&&typeof t.constructor.lc_name=="function"&&t.constructor.lc_name()==="RunnableToolLike"}function fw(t){return!!t&&typeof t=="object"&&"name"in t&&"schema"in t&&(Wt(t.schema)||t.schema!=null&&typeof t.schema=="object"&&"type"in t.schema&&typeof t.schema.type=="string"&&["null","boolean","object","array","number","string"].includes(t.schema.type))}function Zs(t){return fw(t)||hw(t)||dw(t)}const e5=F("ZodISODateTime",(t,e)=>{XD.init(t,e),xt.init(t,e)});function t5(t){return tU(e5,t)}const n5=F("ZodISODate",(t,e)=>{QD.init(t,e),xt.init(t,e)});function r5(t){return nU(n5,t)}const s5=F("ZodISOTime",(t,e)=>{e4.init(t,e),xt.init(t,e)});function i5(t){return rU(s5,t)}const a5=F("ZodISODuration",(t,e)=>{t4.init(t,e),xt.init(t,e)});function o5(t){return sU(a5,t)}const c5=(t,e)=>{ZE.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:n=>Gj(t,n)},flatten:{value:n=>qj(t,n)},addIssue:{value:n=>t.issues.push(n)},addIssues:{value:n=>t.issues.push(...n)},isEmpty:{get(){return t.issues.length===0}}})},Uf=F("ZodError",c5,{Parent:Error}),u5=qE(Uf),l5=GE(Uf),d5=YE(Uf),h5=XE(Uf),Tt=F("ZodType",(t,e)=>(ut.init(t,e),t.def=e,Object.defineProperty(t,"_def",{value:e}),t.check=(...n)=>t.clone({...e,checks:[...e.checks??[],...n.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),t.clone=(n,r)=>wn(t,n,r),t.brand=()=>t,t.register=(n,r)=>(n.add(t,r),t),t.parse=(n,r)=>u5(t,n,r,{callee:t.parse}),t.safeParse=(n,r)=>d5(t,n,r),t.parseAsync=async(n,r)=>l5(t,n,r,{callee:t.parseAsync}),t.safeParseAsync=async(n,r)=>h5(t,n,r),t.spa=t.safeParseAsync,t.refine=(n,r)=>t.check(a8(n,r)),t.superRefine=n=>t.check(o8(n)),t.overwrite=n=>t.check(wl(n)),t.optional=()=>Fv(t),t.nullable=()=>Bv(t),t.nullish=()=>Fv(Bv(t)),t.nonoptional=n=>Q5(t,n),t.array=()=>ba(t),t.or=n=>kl([t,n]),t.and=n=>B5(t,n),t.transform=n=>zv(t,Z5(n)),t.default=n=>J5(t,n),t.prefault=n=>X5(t,n),t.catch=n=>t8(t,n),t.pipe=n=>zv(t,n),t.readonly=()=>s8(t),t.describe=n=>{const r=t.clone();return Qt.add(r,{description:n}),r},Object.defineProperty(t,"description",{get(){var n;return(n=Qt.get(t))==null?void 0:n.description},configurable:!0}),t.meta=(...n)=>{if(n.length===0)return Qt.get(t);const r=t.clone();return Qt.add(r,n[0]),r},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),uk=F("_ZodString",(t,e)=>{Ey.init(t,e),Tt.init(t,e);const n=t._zod.bag;t.format=n.format??null,t.minLength=n.minimum??null,t.maxLength=n.maximum??null,t.regex=(...r)=>t.check(uU(...r)),t.includes=(...r)=>t.check(hU(...r)),t.startsWith=(...r)=>t.check(fU(...r)),t.endsWith=(...r)=>t.check(pU(...r)),t.min=(...r)=>t.check(Ch(...r)),t.max=(...r)=>t.check(fI(...r)),t.length=(...r)=>t.check(pI(...r)),t.nonempty=(...r)=>t.check(Ch(1,...r)),t.lowercase=r=>t.check(lU(r)),t.uppercase=r=>t.check(dU(r)),t.trim=()=>t.check(gU()),t.normalize=(...r)=>t.check(mU(...r)),t.toLowerCase=()=>t.check(_U()),t.toUpperCase=()=>t.check(yU())}),f5=F("ZodString",(t,e)=>{Ey.init(t,e),uk.init(t,e),t.email=n=>t.check(N4(p5,n)),t.url=n=>t.check(U4(m5,n)),t.jwt=n=>t.check(eU(O5,n)),t.emoji=n=>t.check(F4(g5,n)),t.guid=n=>t.check(H0(jv,n)),t.uuid=n=>t.check(M4(id,n)),t.uuidv4=n=>t.check(L4(id,n)),t.uuidv6=n=>t.check(j4(id,n)),t.uuidv7=n=>t.check(D4(id,n)),t.nanoid=n=>t.check(B4(_5,n)),t.guid=n=>t.check(H0(jv,n)),t.cuid=n=>t.check(z4(y5,n)),t.cuid2=n=>t.check(H4(w5,n)),t.ulid=n=>t.check(V4(b5,n)),t.base64=n=>t.check(Y4(x5,n)),t.base64url=n=>t.check(X4(k5,n)),t.xid=n=>t.check(K4(v5,n)),t.ksuid=n=>t.check(W4(S5,n)),t.ipv4=n=>t.check(Z4(A5,n)),t.ipv6=n=>t.check(q4(T5,n)),t.cidrv4=n=>t.check(G4(E5,n)),t.cidrv6=n=>t.check(J4(I5,n)),t.e164=n=>t.check(Q4(C5,n)),t.datetime=n=>t.check(t5(n)),t.date=n=>t.check(r5(n)),t.time=n=>t.check(i5(n)),t.duration=n=>t.check(o5(n))});function Ke(t){return P4(f5,t)}const xt=F("ZodStringFormat",(t,e)=>{At.init(t,e),uk.init(t,e)}),p5=F("ZodEmail",(t,e)=>{HD.init(t,e),xt.init(t,e)}),jv=F("ZodGUID",(t,e)=>{BD.init(t,e),xt.init(t,e)}),id=F("ZodUUID",(t,e)=>{zD.init(t,e),xt.init(t,e)}),m5=F("ZodURL",(t,e)=>{VD.init(t,e),xt.init(t,e)}),g5=F("ZodEmoji",(t,e)=>{KD.init(t,e),xt.init(t,e)}),_5=F("ZodNanoID",(t,e)=>{WD.init(t,e),xt.init(t,e)}),y5=F("ZodCUID",(t,e)=>{ZD.init(t,e),xt.init(t,e)}),w5=F("ZodCUID2",(t,e)=>{qD.init(t,e),xt.init(t,e)}),b5=F("ZodULID",(t,e)=>{GD.init(t,e),xt.init(t,e)}),v5=F("ZodXID",(t,e)=>{JD.init(t,e),xt.init(t,e)}),S5=F("ZodKSUID",(t,e)=>{YD.init(t,e),xt.init(t,e)}),A5=F("ZodIPv4",(t,e)=>{n4.init(t,e),xt.init(t,e)}),T5=F("ZodIPv6",(t,e)=>{r4.init(t,e),xt.init(t,e)}),E5=F("ZodCIDRv4",(t,e)=>{s4.init(t,e),xt.init(t,e)}),I5=F("ZodCIDRv6",(t,e)=>{i4.init(t,e),xt.init(t,e)}),x5=F("ZodBase64",(t,e)=>{a4.init(t,e),xt.init(t,e)}),k5=F("ZodBase64URL",(t,e)=>{c4.init(t,e),xt.init(t,e)}),C5=F("ZodE164",(t,e)=>{u4.init(t,e),xt.init(t,e)}),O5=F("ZodJWT",(t,e)=>{d4.init(t,e),xt.init(t,e)}),lk=F("ZodNumber",(t,e)=>{aI.init(t,e),Tt.init(t,e),t.gt=(r,s)=>t.check(K0(r,s)),t.gte=(r,s)=>t.check(Lp(r,s)),t.min=(r,s)=>t.check(Lp(r,s)),t.lt=(r,s)=>t.check(V0(r,s)),t.lte=(r,s)=>t.check(Mp(r,s)),t.max=(r,s)=>t.check(Mp(r,s)),t.int=r=>t.check(Dv(r)),t.safe=r=>t.check(Dv(r)),t.positive=r=>t.check(K0(0,r)),t.nonnegative=r=>t.check(Lp(0,r)),t.negative=r=>t.check(V0(0,r)),t.nonpositive=r=>t.check(Mp(0,r)),t.multipleOf=(r,s)=>t.check(W0(r,s)),t.step=(r,s)=>t.check(W0(r,s)),t.finite=()=>t;const n=t._zod.bag;t.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),t.isFinite=!0,t.format=n.format??null});function ot(t){return iU(lk,t)}const $5=F("ZodNumberFormat",(t,e)=>{h4.init(t,e),lk.init(t,e)});function Dv(t){return aU($5,t)}const R5=F("ZodBoolean",(t,e)=>{f4.init(t,e),Tt.init(t,e)});function Uv(t){return oU(R5,t)}const P5=F("ZodAny",(t,e)=>{p4.init(t,e),Tt.init(t,e)});function ad(){return cU(P5)}const N5=F("ZodUnknown",(t,e)=>{oI.init(t,e),Tt.init(t,e)});function Hh(){return dI(N5)}const M5=F("ZodNever",(t,e)=>{cI.init(t,e),Tt.init(t,e)});function L5(t){return hI(M5,t)}const j5=F("ZodArray",(t,e)=>{m4.init(t,e),Tt.init(t,e),t.element=e.element,t.min=(n,r)=>t.check(Ch(n,r)),t.nonempty=n=>t.check(Ch(1,n)),t.max=(n,r)=>t.check(fI(n,r)),t.length=(n,r)=>t.check(pI(n,r)),t.unwrap=()=>t.element});function ba(t,e){return wU(j5,t,e)}const D5=F("ZodObject",(t,e)=>{g4.init(t,e),Tt.init(t,e),wt(t,"shape",()=>e.shape),t.keyof=()=>Bf(Object.keys(t._zod.def.shape)),t.catchall=n=>t.clone({...t._zod.def,catchall:n}),t.passthrough=()=>t.clone({...t._zod.def,catchall:Hh()}),t.loose=()=>t.clone({...t._zod.def,catchall:Hh()}),t.strict=()=>t.clone({...t._zod.def,catchall:L5()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=n=>VE(t,n),t.merge=n=>Wj(t,n),t.pick=n=>Vj(t,n),t.omit=n=>Kj(t,n),t.partial=(...n)=>KE(hk,t,n[0]),t.required=(...n)=>Zj(fk,t,n[0])});function $e(t,e){const n={type:"object",get shape(){return Ay(this,"shape",{...t}),this.shape},...ve(e)};return new D5(n)}const dk=F("ZodUnion",(t,e)=>{uI.init(t,e),Tt.init(t,e),t.options=e.options});function kl(t,e){return new dk({type:"union",options:t,...ve(e)})}const U5=F("ZodDiscriminatedUnion",(t,e)=>{dk.init(t,e),_4.init(t,e)});function Ff(t,e,n){return new U5({type:"union",options:e,discriminator:t,...ve(n)})}const F5=F("ZodIntersection",(t,e)=>{y4.init(t,e),Tt.init(t,e)});function B5(t,e){return new F5({type:"intersection",left:t,right:e})}const z5=F("ZodTuple",(t,e)=>{w4.init(t,e),Tt.init(t,e),t.rest=n=>t.clone({...t._zod.def,rest:n})});function pw(t,e,n){const r=e instanceof ut,s=r?n:e,i=r?e:null;return new z5({type:"tuple",items:t,rest:i,...ve(s)})}const H5=F("ZodRecord",(t,e)=>{b4.init(t,e),Tt.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});function V5(t,e,n){return new H5({type:"record",keyType:t,valueType:e,...ve(n)})}const Jg=F("ZodEnum",(t,e)=>{v4.init(t,e),Tt.init(t,e),t.enum=e.entries,t.options=Object.values(e.entries);const n=new Set(Object.keys(e.entries));t.extract=(r,s)=>{const i={};for(const a of r)if(n.has(a))i[a]=e.entries[a];else throw new Error(`Key ${a} not found in enum`);return new Jg({...e,checks:[],...ve(s),entries:i})},t.exclude=(r,s)=>{const i={...e.entries};for(const a of r)if(n.has(a))delete i[a];else throw new Error(`Key ${a} not found in enum`);return new Jg({...e,checks:[],...ve(s),entries:i})}});function Bf(t,e){const n=Array.isArray(t)?Object.fromEntries(t.map(r=>[r,r])):t;return new Jg({type:"enum",entries:n,...ve(e)})}const K5=F("ZodLiteral",(t,e)=>{S4.init(t,e),Tt.init(t,e),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});function Ue(t,e){return new K5({type:"literal",values:Array.isArray(t)?t:[t],...ve(e)})}const W5=F("ZodTransform",(t,e)=>{A4.init(t,e),Tt.init(t,e),t._zod.parse=(n,r)=>{n.addIssue=i=>{if(typeof i=="string")n.issues.push(xu(i,n.value,e));else{const a=i;a.fatal&&(a.continue=!1),a.code??(a.code="custom"),a.input??(a.input=n.value),a.inst??(a.inst=t),a.continue??(a.continue=!0),n.issues.push(xu(a))}};const s=e.transform(n.value,n);return s instanceof Promise?s.then(i=>(n.value=i,n)):(n.value=s,n)}});function Z5(t){return new W5({type:"transform",transform:t})}const hk=F("ZodOptional",(t,e)=>{Iy.init(t,e),Tt.init(t,e),t.unwrap=()=>t._zod.def.innerType});function Fv(t){return new hk({type:"optional",innerType:t})}const q5=F("ZodNullable",(t,e)=>{T4.init(t,e),Tt.init(t,e),t.unwrap=()=>t._zod.def.innerType});function Bv(t){return new q5({type:"nullable",innerType:t})}const G5=F("ZodDefault",(t,e)=>{E4.init(t,e),Tt.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function J5(t,e){return new G5({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}const Y5=F("ZodPrefault",(t,e)=>{I4.init(t,e),Tt.init(t,e),t.unwrap=()=>t._zod.def.innerType});function X5(t,e){return new Y5({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}const fk=F("ZodNonOptional",(t,e)=>{x4.init(t,e),Tt.init(t,e),t.unwrap=()=>t._zod.def.innerType});function Q5(t,e){return new fk({type:"nonoptional",innerType:t,...ve(e)})}const e8=F("ZodCatch",(t,e)=>{k4.init(t,e),Tt.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function t8(t,e){return new e8({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}const n8=F("ZodPipe",(t,e)=>{C4.init(t,e),Tt.init(t,e),t.in=e.in,t.out=e.out});function zv(t,e){return new n8({type:"pipe",in:t,out:e})}const r8=F("ZodReadonly",(t,e)=>{O4.init(t,e),Tt.init(t,e)});function s8(t){return new r8({type:"readonly",innerType:t})}const pk=F("ZodCustom",(t,e)=>{$4.init(t,e),Tt.init(t,e)});function i8(t){const e=new qn({check:"custom"});return e._zod.check=t,e}function Yg(t,e){return bU(pk,()=>!0,e)}function a8(t,e={}){return vU(pk,t,e)}function o8(t){const e=i8(n=>(n.addIssue=r=>{if(typeof r=="string")n.issues.push(xu(r,n.value,e._zod.def));else{const s=r;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=n.value),s.inst??(s.inst=e),s.continue??(s.continue=!e._zod.def.abort),n.issues.push(xu(s))}},t(n.value,n)));return e}var c8=de({BaseToolkit:()=>u8,DynamicStructuredTool:()=>_k,DynamicTool:()=>gk,StructuredTool:()=>zf,Tool:()=>mk,ToolInputParsingException:()=>gh,isLangChainTool:()=>Zs,isRunnableToolLike:()=>hw,isStructuredTool:()=>dw,isStructuredToolParams:()=>fw,tool:()=>ii}),zf=class extends Gy{constructor(e){super(e??{});m(this,"extras");m(this,"returnDirect",!1);m(this,"verboseParsingErrors",!1);m(this,"responseFormat","content");m(this,"defaultConfig");this.verboseParsingErrors=(e==null?void 0:e.verboseParsingErrors)??this.verboseParsingErrors,this.responseFormat=(e==null?void 0:e.responseFormat)??this.responseFormat,this.defaultConfig=(e==null?void 0:e.defaultConfig)??this.defaultConfig,this.metadata=(e==null?void 0:e.metadata)??this.metadata,this.extras=(e==null?void 0:e.extras)??this.extras}get lc_namespace(){return["langchain","tools"]}async invoke(e,n){let r,s=Je(ir(this.defaultConfig,n));return nu(e)?(r=e.args,s={...s,toolCall:e}):r=e,this.call(r,s)}async call(e,n,r){const s=nu(e)?e.args:e;let i;if(Wt(this.schema))try{i=await kf(this.schema,s)}catch(p){let g="Received tool input did not match expected schema";throw this.verboseParsingErrors&&(g=`${g}
|
|
288
|
-
Details: ${p.message}`),vI(p)&&(g=`${g}
|
|
289
|
-
|
|
290
|
-
${Yj(p)}`),new gh(g,JSON.stringify(e))}else{const p=St(s,this.schema);if(!p.valid){let g="Received tool input did not match expected schema";throw this.verboseParsingErrors&&(g=`${g}
|
|
291
|
-
Details: ${p.errors.map(y=>`${y.keywordLocation}: ${y.error}`).join(`
|
|
292
|
-
`)}`),new gh(g,JSON.stringify(e))}i=s}const a=ml(n),o=bn.configure(a.callbacks,this.callbacks,a.tags||r,this.tags,a.metadata,this.metadata,{verbose:this.verbose});let c;nu(e)&&(c=e.id),!c&&VR(a)&&(c=a.toolCall.id);const u=await(o==null?void 0:o.handleToolStart(this.toJSON(),typeof e=="string"?e:JSON.stringify(e),a.runId,void 0,void 0,void 0,a.runName,c));delete a.runId;let l;try{const p=await this._call(i,u,a);l=LI(p)?await C6(p,async g=>{try{await(u==null?void 0:u.handleToolEvent(g))}catch(y){await(u==null?void 0:u.handleToolError(y))}}):p}catch(p){throw await(u==null?void 0:u.handleToolError(p)),p}let d,f;if(this.responseFormat==="content_and_artifact")if(Array.isArray(l)&&l.length===2)[d,f]=l;else throw new Error(`Tool response format is "content_and_artifact" but the output was not a two-tuple.
|
|
293
|
-
Result: ${JSON.stringify(l)}`);else d=l;const h=l8({content:d,artifact:f,toolCallId:c,name:this.name,metadata:this.metadata});return await(u==null?void 0:u.handleToolEnd(h)),h}},mk=class extends zf{constructor(e){super(e);m(this,"schema",Vr({input:tr().optional()}).transform(e=>e.input))}call(e,n){const r=typeof e=="string"||e==null?{input:e}:e;return super.call(r,n)}},gk=class extends mk{constructor(e){super(e);m(this,"name");m(this,"description");m(this,"func");this.name=e.name,this.description=e.description,this.func=e.func,this.returnDirect=e.returnDirect??this.returnDirect}static lc_name(){return"DynamicTool"}async call(e,n){const r=ml(n);return r.runName===void 0&&(r.runName=this.name),super.call(e,r)}_call(e,n,r){return this.func(e,n,r)}},_k=class extends zf{constructor(e){super(e);m(this,"description");m(this,"func");m(this,"schema");this.name=e.name,this.description=e.description,this.func=e.func,this.returnDirect=e.returnDirect??this.returnDirect,this.schema=e.schema}static lc_name(){return"DynamicStructuredTool"}async call(e,n,r){const s=ml(n);return s.runName===void 0&&(s.runName=this.name),super.call(e,s,r)}_call(e,n,r){return this.func(e,n,r)}},u8=class{getTools(){return this.tools}};function ii(t,e){var a;const n=xy(e.schema),r=cu(e.schema);if(!e.schema||n||r)return new gk({...e,description:e.description??((a=e.schema)==null?void 0:a.description)??`${e.name} tool`,func:async(o,c,u)=>new Promise((l,d)=>{const f=et(u,{callbacks:c==null?void 0:c.getChild()});pn.runWithConfig(Hs(f),async()=>{try{l(t(o,f))}catch(h){d(h)}})})});const s=e.schema,i=e.description??e.schema.description??`${e.name} tool`;return new _k({...e,description:i,schema:s,func:async(o,c,u)=>new Promise((l,d)=>{let f;const h=()=>{u!=null&&u.signal&&f&&u.signal.removeEventListener("abort",f)};u!=null&&u.signal&&(f=()=>{h(),d(Au(u.signal))},u.signal.addEventListener("abort",f,{once:!0}));const p=et(u,{callbacks:c==null?void 0:c.getChild()});pn.runWithConfig(Hs(p),async()=>{var g;try{const y=await t(o,p);if(LI(y)){l(y);return}if((g=u==null?void 0:u.signal)!=null&&g.aborted){h();return}h(),l(y)}catch(y){h(),d(y)}})})})}function l8(t){const{content:e,artifact:n,toolCallId:r,metadata:s}=t;return r&&!X_(e)?typeof e=="string"||Array.isArray(e)&&e.every(i=>typeof i=="object")?new fn({status:"success",content:e,artifact:n,tool_call_id:r,name:t.name,metadata:s}):new fn({status:"success",content:d8(e),artifact:n,tool_call_id:r,name:t.name,metadata:s}):e}function d8(t){try{return JSON.stringify(t)??""}catch{return`${t}`}}var h8=de({RunCollectorCallbackHandler:()=>f8}),f8=class extends Gs{constructor({exampleId:e}={}){super({_awaitHandler:!0});m(this,"name","run_collector");m(this,"exampleId");m(this,"tracedRuns");this.exampleId=e,this.tracedRuns=[]}async persistRun(e){const n={...e};n.reference_example_id=this.exampleId,this.tracedRuns.push(n)}},p8=de({}),m8=de({chunkArray:()=>g8});const g8=(t,e)=>t.reduce((n,r,s)=>{const i=Math.floor(s/e);return n[i]=(n[i]||[]).concat([r]),n},[]);var _8=de({context:()=>y8});function y8(t,...e){const n=t.raw;let r="";for(let s=0;s<n.length;s++){const i=n[s].replace(/\\\n[ \t]*/g,"").replace(/\\`/g,"`").replace(/\\\$/g,"$").replace(/\\\{/g,"{");if(r+=i,s<e.length){const a=w8(e[s],r);r+=typeof a=="string"?a:JSON.stringify(a)}}return r=b8(r),r=r.trim(),r=r.replace(/\\n/g,`
|
|
294
|
-
`),r}function w8(t,e){if(typeof t!="string"||!t.includes(`
|
|
295
|
-
`))return t;const n=e.slice(e.lastIndexOf(`
|
|
296
|
-
`)+1).match(/^(\s+)/);if(n){const r=n[1];return t.replace(/\n/g,`
|
|
297
|
-
${r}`)}return t}function b8(t){const e=t.split(`
|
|
298
|
-
`);let n=null;for(const r of e){const s=r.match(/^(\s+)\S+/);if(s){const i=s[1].length;n===null?n=i:n=Math.min(n,i)}}return n===null?t:e.map(r=>r[0]===" "||r[0]===" "?r.slice(n):r).join(`
|
|
299
|
-
`)}var v8=de({EventStreamContentType:()=>S8,convertEventStreamToIterableReadableDataStream:()=>T8,getBytes:()=>yk,getLines:()=>wk,getMessages:()=>bk});const S8="text/event-stream";async function yk(t,e){if(t instanceof ReadableStream){const n=t.getReader();for(;;){const r=await n.read();if(r.done){e(new Uint8Array,!0);break}e(r.value)}}else try{for await(const n of t)e(new Uint8Array(n));e(new Uint8Array,!0)}catch(n){throw new Error(["Parsing event source stream failed.","Ensure your implementation of fetch returns a web or Node readable stream.",`Error: ${n.message}`].join(`
|
|
300
|
-
`))}}function wk(t){let e,n,r,s=!1;return function(a,o){if(o){t(a,0,!0);return}e===void 0?(e=a,n=0,r=-1):e=A8(e,a);const c=e.length;let u=0;for(;n<c;){s&&(e[n]===10&&(u=++n),s=!1);let l=-1;for(;n<c&&l===-1;++n)switch(e[n]){case 58:r===-1&&(r=n-u);break;case 13:s=!0;case 10:l=n;break}if(l===-1)break;t(e.subarray(u,l),r),u=n,r=-1}u===c?e=void 0:u!==0&&(e=e.subarray(u),n-=u)}}function bk(t,e,n){let r=Xp();const s=new TextDecoder;return function(a,o,c){if(c){E8(r)||(t==null||t(r),r=Xp());return}if(a.length===0)t==null||t(r),r=Xp();else if(o>0){const u=s.decode(a.subarray(0,o)),l=o+(a[o+1]===32?2:1),d=s.decode(a.subarray(l));switch(u){case"data":r.data=r.data?r.data+`
|
|
301
|
-
`+d:d;break;case"event":r.event=d;break;case"id":e==null||e(r.id=d);break;case"retry":{const f=parseInt(d,10);Number.isNaN(f)||n==null||n(r.retry=f);break}}}}}function A8(t,e){const n=new Uint8Array(t.length+e.length);return n.set(t),n.set(e,t.length),n}function Xp(){return{data:"",event:"",id:"",retry:void 0}}function T8(t,e){const n=new ReadableStream({async start(r){const s=bk(a=>{if(a.event==="error")throw new Error(a.data??"Unspecified event streaming error.");a.event==="metadata"?e==null||e(a):a.data&&r.enqueue(a.data)});await yk(t,wk((a,o,c)=>{s(a,o,c),c&&r.close()}))}});return Vn.fromReadableStream(n)}function E8(t){return t.data===""&&t.event===""&&t.id===""&&t.retry===void 0}var I8=de({}),x8=de({convertToOpenAIFunction:()=>vk,convertToOpenAITool:()=>Vh,isLangChainTool:()=>Zs,isRunnableToolLike:()=>hw,isStructuredTool:()=>dw,isStructuredToolParams:()=>fw});function vk(t,e){const n=typeof e=="number"?void 0:e;return{name:t.name,description:t.description,parameters:mt(t.schema),...(n==null?void 0:n.strict)!==void 0?{strict:n.strict}:{}}}function Vh(t,e){const n=typeof e=="number"?void 0:e;let r;return Zs(t)?r={type:"function",function:vk(t)}:r=t,(n==null?void 0:n.strict)!==void 0&&(r.function.strict=n.strict),r}function Sk(t,e){let n=0,r=0,s=0;for(let i=0;i<t.length;i++)n+=t[i]*e[i],r+=t[i]*t[i],s+=e[i]*e[i];return n/(Math.sqrt(r)*Math.sqrt(s))}function k8(t,e){let n=0;for(let r=0;r<t.length;r++)n+=t[r]*e[r];return n}function C8(t,e){let n=0;for(let r=0;r<t.length;r++)n+=(t[r]-e[r])*(t[r]-e[r]);return n}function O8(t,e){return Math.sqrt(C8(t,e))}var $8=de({cosineSimilarity:()=>Xg,euclideanDistance:()=>N8,innerProduct:()=>P8,matrixFunc:()=>Hf,maximalMarginalRelevance:()=>M8,normalize:()=>R8});function Hf(t,e,n){if(t.length===0||t[0].length===0||e.length===0||e[0].length===0)return[[]];if(t[0].length!==e[0].length)throw new Error(`Number of columns in X and Y must be the same. X has shape ${[t.length,t[0].length]} and Y has shape ${[e.length,e[0].length]}.`);return t.map(r=>e.map(s=>n(r,s)).map(s=>Number.isNaN(s)?0:s))}function R8(t,e=!1){const n=L8(t);return t.map(r=>r.map(s=>e?1-s/n:s/n))}function Xg(t,e){return Hf(t,e,Sk)}function P8(t,e){return Hf(t,e,k8)}function N8(t,e){return Hf(t,e,O8)}function M8(t,e,n=.5,r=4){if(Math.min(r,e.length)<=0)return[];const s=Xg(Array.isArray(t[0])?t:[t],e)[0],i=Ak(s).maxIndex,a=[e[i]],o=[i];for(;o.length<Math.min(r,e.length);){let c=-1/0,u=-1;const l=Xg(e,a);s.forEach((d,f)=>{if(o.includes(f))return;const h=Math.max(...l[f]),p=n*d-(1-n)*h;p>c&&(c=p,u=f)}),a.push(e[u]),o.push(u)}return o}function Ak(t){if(t.length===0)return{maxIndex:-1,maxValue:NaN};let e=t[0],n=0;for(let r=1;r<t.length;r+=1)t[r]>e&&(n=r,e=t[r]);return{maxIndex:n,maxValue:e}}function L8(t){return t.reduce((e,n)=>Math.max(e,Ak(n).maxValue),0)}var j8=de({isCloudMetadata:()=>Qg,isLocalhost:()=>e_,isPrivateIp:()=>kk,isSafeUrl:()=>K8,isSameOrigin:()=>W8,validateSafeUrl:()=>Ck});const D8=["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"],U8=["169.254.169.254","169.254.170.2","100.100.100.200"],F8=["metadata.google.internal","metadata","instance-data"],B8=["localhost","localhost.localdomain"],z8=/^(?:(?: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 Tk(t){return z8.test(t)}function Vf(t){return xk(t)!==null}function Ek(t){return Tk(t)||Vf(t)}function Ik(t){if(Tk(t))return t.split(".").map(e=>parseInt(e,10));if(Vf(t)){const e=xk(t);if(!e)return null;const n=e.split(":"),r=[];for(const s of n)r.push(parseInt(s,16));return r}return null}function xk(t){if(!t||typeof t!="string"||!t.includes(":")||!/^[0-9a-fA-F:]+$/.test(t))return null;let e=t;if(e.includes("::")){const r=e.split("::");if(r.length>2)return null;const[s,i]=r,a=s?s.split(":"):[],o=i?i.split(":"):[],c=8-(a.length+o.length);if(c<0)return null;const u=Array(c).fill("0");e=[...a,...u,...o].filter(l=>l!=="").join(":")}const n=e.split(":");if(n.length!==8)return null;for(const r of n)if(r.length===0||r.length>4||!/^[0-9a-fA-F]+$/.test(r))return null;return n.map(r=>r.padStart(4,"0").toLowerCase()).join(":")}function H8(t){const[e,n]=t.split("/");if(!e||!n)return null;const r=Ik(e);if(!r)return null;const s=parseInt(n,10);if(isNaN(s))return null;const i=Vf(e);return i&&s>128||!i&&s>32?null:{addr:r,prefixLen:s,isIpv6:i}}function V8(t,e){const n=Ik(t);if(!n)return!1;const r=H8(e);if(!r)return!1;const s=Vf(t);if(s!==r.isIpv6)return!1;const{addr:i,prefixLen:a}=r;if(s)for(let o=0;o<Math.ceil(a/16);o++){const c=65535<<16-Math.min(16,a-o*16)&65535;if((n[o]&c)!==(i[o]&c))return!1}else for(let o=0;o<Math.ceil(a/8);o++){const c=255<<8-Math.min(8,a-o*8)&255;if((n[o]&c)!==(i[o]&c))return!1}return!0}function kk(t){if(!Ek(t))return!1;for(const e of D8)if(V8(t,e))return!0;return!1}function Qg(t,e){if(U8.includes(e||""))return!0;const n=t.toLowerCase();return!!F8.includes(n)}function e_(t,e){if(e&&(e==="127.0.0.1"||e==="::1"||e==="0.0.0.0"||e.startsWith("127.")))return!0;const n=t.toLowerCase();return!!B8.includes(n)}function Ck(t,e){const n=(e==null?void 0:e.allowPrivate)??!1,r=(e==null?void 0:e.allowHttp)??!1;try{let s;try{s=new URL(t)}catch{throw new Error(`Invalid URL: ${t}`)}const i=s.hostname;if(!i)throw new Error("URL missing hostname.");if(Qg(i))throw new Error(`URL points to cloud metadata endpoint: ${i}`);if(e_(i)){if(!n)throw new Error(`URL points to localhost: ${i}`);return t}const a=s.protocol;if(a!=="http:"&&a!=="https:")throw new Error(`Invalid URL scheme: ${a}. Only http and https are allowed.`);if(a==="http:"&&!r)throw new Error("HTTP scheme not allowed. Use HTTPS or set allowHttp: true.");if(Ek(i)){const o=i;if(e_(i,o)){if(!n)throw new Error(`URL points to localhost: ${i}`);return t}if(Qg(i,o))throw new Error(`URL resolves to cloud metadata IP: ${o} (${i})`);if(kk(o)&&!n)throw new Error(`URL resolves to private IP: ${o} (${i}). Set allowPrivate: true to allow.`);return t}return t}catch(s){throw s&&typeof s=="object"&&"message"in s?s:new Error(`URL validation failed: ${s}`)}}function K8(t,e){try{return Ck(t,e),!0}catch{return!1}}function W8(t,e){try{return new URL(t).origin===new URL(e).origin}catch{return!1}}var Z8=de({SaveableVectorStore:()=>q8,VectorStore:()=>mw,VectorStoreRetriever:()=>Zd}),Zd=class extends aw{constructor(e){super(e);m(this,"vectorStore");m(this,"k",4);m(this,"searchType","similarity");m(this,"searchKwargs");m(this,"filter");this.vectorStore=e.vectorStore,this.k=e.k??this.k,this.searchType=e.searchType??this.searchType,this.filter=e.filter,e.searchType==="mmr"&&(this.searchKwargs=e.searchKwargs)}static lc_name(){return"VectorStoreRetriever"}get lc_namespace(){return["langchain_core","vectorstores"]}_vectorstoreType(){return this.vectorStore._vectorstoreType()}async _getRelevantDocuments(e,n){if(this.searchType==="mmr"){if(typeof this.vectorStore.maxMarginalRelevanceSearch!="function")throw new Error(`The vector store backing this retriever, ${this._vectorstoreType()} does not support max marginal relevance search.`);return this.vectorStore.maxMarginalRelevanceSearch(e,{k:this.k,filter:this.filter,...this.searchKwargs},n==null?void 0:n.getChild("vectorstore"))}return this.vectorStore.similaritySearch(e,this.k,this.filter,n==null?void 0:n.getChild("vectorstore"))}async addDocuments(e,n){return this.vectorStore.addDocuments(e,n)}},mw=class extends xr{constructor(e,n){super(n);m(this,"lc_namespace",["langchain","vectorstores",this._vectorstoreType()]);m(this,"embeddings");this.embeddings=e}async delete(e){throw new Error("Not implemented.")}async similaritySearch(e,n=4,r=void 0,s=void 0){return(await this.similaritySearchVectorWithScore(await this.embeddings.embedQuery(e),n,r)).map(i=>i[0])}async similaritySearchWithScore(e,n=4,r=void 0,s=void 0){return this.similaritySearchVectorWithScore(await this.embeddings.embedQuery(e),n,r)}static fromTexts(e,n,r,s){throw new Error("the Langchain vectorstore implementation you are using forgot to override this, please report a bug")}static fromDocuments(e,n,r){throw new Error("the Langchain vectorstore implementation you are using forgot to override this, please report a bug")}asRetriever(e,n,r,s,i,a){if(typeof e=="number")return new Zd({vectorStore:this,k:e,filter:n,tags:[...s??[],this._vectorstoreType()],metadata:i,verbose:a,callbacks:r});{const o={vectorStore:this,k:e==null?void 0:e.k,filter:e==null?void 0:e.filter,tags:[...(e==null?void 0:e.tags)??[],this._vectorstoreType()],metadata:e==null?void 0:e.metadata,verbose:e==null?void 0:e.verbose,callbacks:e==null?void 0:e.callbacks,searchType:e==null?void 0:e.searchType};return(e==null?void 0:e.searchType)==="mmr"?new Zd({...o,searchKwargs:e.searchKwargs}):new Zd({...o})}}},q8=class extends mw{static load(t,e){throw new Error("Not implemented")}},G8=class extends Es{_combineLLMOutput(){return[]}_llmType(){return"fake"}async _generate(t,e,n){var s;if((s=e==null?void 0:e.stop)!=null&&s.length)return{generations:[{message:new De(e.stop[0]),text:e.stop[0]}]};const r=t.map(i=>typeof i.content=="string"?i.content:JSON.stringify(i.content,null,2)).join(`
|
|
302
|
-
`);return await(n==null?void 0:n.handleLLMNewToken(r)),{generations:[{message:new De(r),text:r}],llmOutput:{}}}},J8=class Ok extends Es{constructor({sleep:n=50,responses:r=[],chunks:s=[],toolStyle:i="openai",thrownErrorString:a,...o}){super(o);m(this,"sleep",50);m(this,"responses",[]);m(this,"chunks",[]);m(this,"toolStyle","openai");m(this,"thrownErrorString");m(this,"tools",[]);this.sleep=n,this.responses=r,this.chunks=s,this.toolStyle=i,this.thrownErrorString=a}_llmType(){return"fake"}bindTools(n){const r=[...this.tools,...n],s=r.map(o=>{switch(this.toolStyle){case"openai":return{type:"function",function:{name:o.name,description:o.description,parameters:mt(o.schema)}};case"anthropic":return{name:o.name,description:o.description,input_schema:mt(o.schema)};case"bedrock":return{toolSpec:{name:o.name,description:o.description,inputSchema:mt(o.schema)}};case"google":return{name:o.name,description:o.description,parameters:mt(o.schema)};default:throw new Error(`Unsupported tool style: ${this.toolStyle}`)}}),i=this.toolStyle==="google"?[{functionDeclarations:s}]:s,a=new Ok({sleep:this.sleep,responses:this.responses,chunks:this.chunks,toolStyle:this.toolStyle,thrownErrorString:this.thrownErrorString});return a.tools=r,a.withConfig({tools:i})}async _generate(n,r,s){var i,a,o,c;if(this.thrownErrorString)throw new Error(this.thrownErrorString);return{generations:[{text:"",message:new De({content:((a=(i=this.responses)==null?void 0:i[0])==null?void 0:a.content)??n[0].content??"",tool_calls:(c=(o=this.chunks)==null?void 0:o[0])==null?void 0:c.tool_calls})}]}}async*_streamResponseChunks(n,r,s){var o,c,u,l,d;if(this.thrownErrorString)throw new Error(this.thrownErrorString);if((o=this.chunks)!=null&&o.length){for(const f of this.chunks){const h=new dr({message:new Ge({content:f.content,tool_calls:f.tool_calls,additional_kwargs:f.additional_kwargs??{}}),text:((c=f.content)==null?void 0:c.toString())??""});if((u=r.signal)!=null&&u.aborted)break;yield h,await(s==null?void 0:s.handleLLMNewToken(f.content,void 0,void 0,void 0,void 0,{chunk:h}))}return}const i=((l=this.responses)==null?void 0:l[0])??new De(typeof n[0].content=="string"?n[0].content:""),a=typeof i.content=="string"?i.content:"";for(const f of a){await new Promise(p=>setTimeout(p,this.sleep));const h=new dr({message:new Ge({content:f}),text:f});if((d=r.signal)!=null&&d.aborted)break;yield h,await(s==null?void 0:s.handleLLMNewToken(f,void 0,void 0,void 0,void 0,{chunk:h}))}}},Y8=class $k extends Es{constructor(n){super(n);m(this,"lc_serializable",!0);m(this,"responses");m(this,"i",0);m(this,"sleep");m(this,"emitCustomEvent",!1);m(this,"generationInfo");m(this,"tools",[]);m(this,"toolStyle","openai");const{responses:r,sleep:s,emitCustomEvent:i,generationInfo:a}=n;this.responses=r,this.sleep=s,this.emitCustomEvent=i??this.emitCustomEvent,this.generationInfo=a}static lc_name(){return"FakeListChatModel"}_combineLLMOutput(){return[]}_llmType(){return"fake-list"}async _generate(n,r,s){var i;if(await this._sleepIfRequested(),r!=null&&r.thrownErrorString)throw new Error(r.thrownErrorString);if(this.emitCustomEvent&&await(s==null?void 0:s.handleCustomEvent("some_test_event",{someval:!0})),(i=r==null?void 0:r.stop)!=null&&i.length)return{generations:[this._formatGeneration(r.stop[0])]};{const a=this._currentResponse();return this._incrementResponse(),{generations:[this._formatGeneration(a)],llmOutput:{}}}}_formatGeneration(n){return{message:new De(n),text:n}}async*_streamResponseChunks(n,r,s){var o;const i=this._currentResponse();this._incrementResponse(),this.emitCustomEvent&&await(s==null?void 0:s.handleCustomEvent("some_test_event",{someval:!0}));const a=[...i];for(let c=0;c<a.length;c++){const u=a[c],l=c===a.length-1;if(await this._sleepIfRequested(),r!=null&&r.thrownErrorString)throw new Error(r.thrownErrorString);const d=this._createResponseChunk(u,l?this.generationInfo:void 0);if((o=r.signal)!=null&&o.aborted)break;yield d,s==null||s.handleLLMNewToken(u)}}async _sleepIfRequested(){this.sleep!==void 0&&await this._sleep()}async _sleep(){return new Promise(n=>{setTimeout(()=>n(),this.sleep)})}_createResponseChunk(n,r){return new dr({message:new Ge({content:n}),text:n,generationInfo:r})}_currentResponse(){return this.responses[this.i]}_incrementResponse(){this.i<this.responses.length-1?this.i+=1:this.i=0}bindTools(n){const r=[...this.tools,...n],s=r.map(o=>{switch(this.toolStyle){case"openai":return{type:"function",function:{name:o.name,description:o.description,parameters:mt(o.schema)}};case"anthropic":return{name:o.name,description:o.description,input_schema:mt(o.schema)};case"bedrock":return{toolSpec:{name:o.name,description:o.description,inputSchema:mt(o.schema)}};case"google":return{name:o.name,description:o.description,parameters:mt(o.schema)};default:throw new Error(`Unsupported tool style: ${this.toolStyle}`)}}),i=this.toolStyle==="google"?[{functionDeclarations:s}]:s,a=new $k({responses:this.responses,sleep:this.sleep,emitCustomEvent:this.emitCustomEvent,generationInfo:this.generationInfo});return a.tools=r,a.toolStyle=this.toolStyle,a.i=this.i,a.withConfig({tools:i})}withStructuredOutput(n,r){return en.from(async s=>{var a,o;const i=await this.invoke(s);if((o=(a=i.tool_calls)==null?void 0:a[0])!=null&&o.args)return i.tool_calls[0].args;if(typeof i.content=="string")return JSON.parse(i.content);throw new Error("No structured output found")})}},X8=class extends Vy{constructor(e){super(e??{});m(this,"vectorSize");this.vectorSize=(e==null?void 0:e.vectorSize)??4}async embedDocuments(e){return Promise.all(e.map(n=>this.embedQuery(n)))}async embedQuery(e){let n=e;n=n.toLowerCase().replaceAll(/[^a-z ]/g,"");const r=n.length%this.vectorSize,s=r===0?0:this.vectorSize-r,i=n.length+s;n=n.padEnd(i," ");const a=n.length/this.vectorSize,o=[];for(let c=0;c<n.length;c+=a)o.push(n.slice(c,c+a));return o.map(c=>{let u=0;for(let l=0;l<c.length;l+=1)u+=c===" "?0:c.charCodeAt(l);return u%26/26})}},Q8=class extends Vy{constructor(t){super(t??{})}embedDocuments(t){return Promise.resolve(t.map(()=>[.1,.2,.3,.4]))}embedQuery(t){return Promise.resolve([.1,.2,.3,.4])}},e9=class extends ew{constructor(e){super(e);m(this,"response");m(this,"thrownErrorString");this.response=e.response,this.thrownErrorString=e.thrownErrorString}_llmType(){return"fake"}async _call(e,n,r){if(this.thrownErrorString)throw new Error(this.thrownErrorString);const s=this.response??e;return await(r==null?void 0:r.handleLLMNewToken(s)),s}},t9=class extends ew{constructor(e){super(e);m(this,"sleep",50);m(this,"responses");m(this,"thrownErrorString");this.sleep=e.sleep??this.sleep,this.responses=e.responses,this.thrownErrorString=e.thrownErrorString}_llmType(){return"fake"}async _call(e){var r,s;if(this.thrownErrorString)throw new Error(this.thrownErrorString);const n=(r=this.responses)==null?void 0:r[0];return this.responses=(s=this.responses)==null?void 0:s.slice(1),n??e}async*_streamResponseChunks(e,n,r){var i,a;if(this.thrownErrorString)throw new Error(this.thrownErrorString);const s=(i=this.responses)==null?void 0:i[0];this.responses=(a=this.responses)==null?void 0:a.slice(1);for(const o of s??e)await new Promise(c=>setTimeout(c,this.sleep)),yield{text:o,generationInfo:{}},await(r==null?void 0:r.handleLLMNewToken(o))}},n9=class extends ex{constructor(){super();m(this,"lc_namespace",["langchain_core","message","fake"]);m(this,"messages",[])}async getMessages(){return this.messages}async addMessage(e){this.messages.push(e)}async addUserMessage(e){this.messages.push(new Nn(e))}async addAIMessage(e){this.messages.push(new De(e))}async clear(){this.messages=[]}},r9=class extends Hy{constructor(){super();m(this,"lc_namespace",["langchain_core","message","fake"]);m(this,"messages",[])}async addMessage(e){this.messages.push(e)}async getMessages(){return this.messages}},s9=class extends Gs{constructor(){super();m(this,"name","fake_tracer");m(this,"runs",[])}persistRun(e){return this.runs.push(e),Promise.resolve()}},i9=class extends ec{constructor(){super(...arguments);m(this,"lc_namespace",["tests","fake"])}getFormatInstructions(){return""}async parse(e){return e.split(",").map(n=>n.trim())}},a9=class extends aw{constructor(e){super();m(this,"lc_namespace",["test","fake"]);m(this,"output",[new Ti({pageContent:"foo"}),new Ti({pageContent:"bar"})]);this.output=(e==null?void 0:e.output)??this.output}async _getRelevantDocuments(e){return this.output}},o9=class extends ze{constructor(e){super(e);m(this,"lc_namespace",["tests","fake"]);m(this,"returnOptions");this.returnOptions=e.returnOptions}async invoke(e,n){return this.returnOptions?n??{}:{input:e}}},c9=class extends zf{constructor(e){super(e);m(this,"name");m(this,"description");m(this,"schema");this.name=e.name,this.description=e.description,this.schema=e.schema}async _call(e,n){return JSON.stringify(e)}},u9=class extends Gs{constructor(){super();m(this,"runPromiseResolver");m(this,"runPromise");m(this,"name","single_run_extractor");this.runPromise=new Promise(e=>{this.runPromiseResolver=e})}async persistRun(e){this.runPromiseResolver(e)}async extract(){return this.runPromise}},l9=class Rk extends mw{constructor(n,{similarity:r,...s}={}){super(n,s);m(this,"memoryVectors",[]);m(this,"similarity");this.similarity=r??Sk}_vectorstoreType(){return"memory"}async addDocuments(n){const r=n.map(({pageContent:s})=>s);return this.addVectors(await this.embeddings.embedDocuments(r),n)}async addVectors(n,r){const s=n.map((i,a)=>({content:r[a].pageContent,embedding:i,metadata:r[a].metadata}));this.memoryVectors=this.memoryVectors.concat(s)}async similaritySearchVectorWithScore(n,r,s){const i=o=>s?s(new Ti({metadata:o.metadata,pageContent:o.content})):!0,a=this.memoryVectors.filter(i);return a.map((o,c)=>({similarity:this.similarity(n,o.embedding),index:c})).sort((o,c)=>o.similarity>c.similarity?-1:0).slice(0,r).map(o=>[new Ti({metadata:a[o.index].metadata,pageContent:a[o.index].content}),o.similarity])}static async fromTexts(n,r,s,i){const a=[];for(let o=0;o<n.length;o+=1){const c=Array.isArray(r)?r[o]:r,u=new Ti({pageContent:n[o],metadata:c});a.push(u)}return Rk.fromDocuments(a,s,i)}static async fromDocuments(n,r,s){const i=new this(r,s);return await i.addDocuments(n),i}static async fromExistingIndex(n,r){return new this(n,r)}},d9=de({FakeChatMessageHistory:()=>n9,FakeChatModel:()=>G8,FakeEmbeddings:()=>Q8,FakeLLM:()=>e9,FakeListChatMessageHistory:()=>r9,FakeListChatModel:()=>Y8,FakeRetriever:()=>a9,FakeRunnable:()=>o9,FakeSplitIntoListParser:()=>i9,FakeStreamingChatModel:()=>J8,FakeStreamingLLM:()=>t9,FakeTool:()=>c9,FakeTracer:()=>s9,FakeVectorStore:()=>l9,SingleRunExtractor:()=>u9,SyntheticEmbeddings:()=>X8}),h9=de({agents:()=>$B,caches:()=>NB,callbacks__base:()=>ON,callbacks__manager:()=>ij,callbacks__promises:()=>tj,chat_history:()=>DB,document_loaders__base:()=>zB,document_loaders__langsmith:()=>HB,documents:()=>BB,embeddings:()=>WB,errors:()=>HR,example_selectors:()=>XB,index:()=>OB,indexing:()=>tz,language_models__base:()=>bz,language_models__chat_models:()=>Xz,language_models__compat:()=>Vz,language_models__event:()=>e3,language_models__llms:()=>t3,language_models__profile:()=>n3,language_models__stream:()=>Uz,language_models__structured_output:()=>Dz,load__serializable:()=>nP,memory:()=>r3,messages:()=>K6,messages__tool:()=>EP,output_parsers:()=>Lz,output_parsers__openai_functions:()=>u3,output_parsers__openai_tools:()=>l3,outputs:()=>Sj,prompt_values:()=>nz,prompts:()=>j3,retrievers:()=>F3,retrievers__document_compressors:()=>D3,runnables:()=>Z6,runnables__graph:()=>T6,singletons:()=>cj,stores:()=>B3,structured_query:()=>q3,testing:()=>Q3,tools:()=>c8,tracers__base:()=>BL,tracers__console:()=>HL,tracers__log_stream:()=>bj,tracers__run_collector:()=>h8,tracers__tracer_langchain:()=>GL,types__stream:()=>p8,utils__async_caller:()=>Pj,utils__chunk_array:()=>m8,utils__context:()=>_8,utils__env:()=>CN,utils__event_source_parse:()=>v8,utils__format:()=>I8,utils__function_calling:()=>x8,utils__hash:()=>PB,utils__json_patch:()=>Tz,utils__json_schema:()=>A6,utils__math:()=>$8,utils__ssrf:()=>j8,utils__standard_schema:()=>WF,utils__stream:()=>hj,utils__testing:()=>d9,utils__tiktoken:()=>yz,utils__types:()=>jz,utils__uuid:()=>vN,vectorstores:()=>Z8});const f9=50;function p9(t){const e={};for(let n=t;n&&n.prototype;n=Object.getPrototypeOf(n))Object.assign(e,Reflect.get(n.prototype,"lc_aliases"));return Object.entries(e).reduce((n,[r,s])=>(n[s]=r,n),{})}async function qd(t){const{optionalImportsMap:e,optionalImportEntrypoints:n,importMap:r,secretsMap:s,secretsFromEnv:i,path:a,depth:o,maxDepth:c}=this,u=a.join(".");if(o>c)throw new Error(`Maximum recursion depth (${c}) exceeded during deserialization. This may indicate a malicious payload or you may need to increase maxDepth.`);if(typeof t!="object"||t==null)return t;if(Array.isArray(t))return Promise.all(t.map((f,h)=>qd.call({...this,path:[...a,`${h}`],depth:o+1},f)));const l=t;if(bT(l))return Jm(l);if("lc"in l&&"type"in l&&"id"in l&&l.lc===1&&l.type==="secret"){const[f]=l.id;if(f in s)return s[f];if(i){const h=Mt(f);if(h)return h}throw new Error(`Missing secret "${f}" at ${u}`)}if("lc"in l&&"type"in l&&"id"in l&&l.lc===1&&l.type==="not_implemented"){const f=JSON.stringify(l);throw new Error(`Trying to load an object that doesn't implement serialization: ${u} -> ${f}`)}if("lc"in l&&"type"in l&&"id"in l&&"kwargs"in l&&l.lc===1&&l.type==="constructor"){const f=l,h=JSON.stringify(f),[p,...g]=f.id.slice().reverse(),y=g.reverse(),b={langchain_core:h9,langchain:r};let _=null;const w=[y.join("/")];y[0]==="langchain_community"&&w.push(["langchain",...y.slice(1)].join("/"));const v=w.find(x=>x in e);if(CB.concat(n).includes(y.join("/"))||v)if(v!==void 0)_=await e[v];else throw new Error(`Missing key "${y.join("/")}" for ${u} in load(optionalImportsMap={})`);else{let x;if(y[0]==="langchain"||y[0]==="langchain_core")x=b[y[0]],y.shift();else throw new Error(`Invalid namespace: ${u} -> ${h}`);if(y.length===0)throw new Error(`Invalid namespace: ${u} -> ${h}`);let E;do{if(E=y.join("__"),E in x)break;y.pop()}while(y.length>0);E in x&&(_=x[E])}if(typeof _!="object"||_===null)throw new Error(`Invalid namespace: ${u} -> ${h}`);const A=_[p]??Object.values(_).find(x=>typeof x=="function"&&yf(x)===p);if(typeof A!="function")throw new Error(`Invalid identifer: ${u} -> ${h}`);const S=new A(yT(await qd.call({...this,path:[...a,"kwargs"],depth:o+1},f.kwargs),YR,p9(A)));return Object.defineProperty(S.constructor,"name",{value:p}),S}const d={};for(const[f,h]of Object.entries(l))d[f]=await qd.call({...this,path:[...a,f],depth:o+1},h);return d}async function m9(t,e){const n=JSON.parse(t),r={optionalImportsMap:{},optionalImportEntrypoints:[],secretsMap:{},secretsFromEnv:!1,importMap:{},path:["$"],depth:0,maxDepth:f9};return qd.call(r,n)}function g9(t){return t!==null&&t.lc===1&&t.type==="constructor"&&Array.isArray(t.id)}async function t_(t){if(t&&typeof t=="object"){if(Array.isArray(t))return await Promise.all(t.map(e=>t_(e)));{const e={};for(const[n,r]of Object.entries(t))e[n]=await t_(r);if(e.lc===2&&e.type==="undefined")return;if(e.lc===2&&e.type==="delta_snapshot")return new By(e.value);if(e.lc===2&&e.type==="constructor"&&Array.isArray(e.id))try{const n=e.id[e.id.length-1];let r;switch(n){case"Set":r=Set;break;case"Map":r=Map;break;case"RegExp":r=RegExp;break;case"Error":r=Error;break;case"Uint8Array":r=Uint8Array;break;default:return e}return e.method?r[e.method](...e.args||[]):new r(...e.args||[])}catch{return e}else if(g9(e))return m9(JSON.stringify(e));return e}}return t}function od(t,e,n,r){return{lc:2,type:"constructor",id:[t.name],method:e??null,args:n??[],kwargs:r??{}}}function _9(t){return t===void 0?{lc:2,type:"undefined"}:t instanceof By?{lc:2,type:"delta_snapshot",value:t.value}:t instanceof Set||t instanceof Map?od(t.constructor,void 0,[Array.from(t)]):t instanceof RegExp?od(RegExp,void 0,[t.source,t.flags]):t instanceof Error?od(t.constructor,void 0,[t.message]):(t==null?void 0:t.lg_name)==="Send"?{node:t.node,args:t.args,...t.timeout!==void 0?{timeout:t.timeout}:{}}:t instanceof Uint8Array?od(Uint8Array,"from",[Array.from(t)]):t}var y9=class{_dumps(t){return new TextEncoder().encode(xB(t,(e,n)=>_9(n)))}async dumpsTyped(t){return t instanceof Uint8Array?["bytes",t]:["json",this._dumps(t)]}async _loads(t){return t_(JSON.parse(t))}async loadsTyped(t,e){if(t==="bytes")return typeof e=="string"?new TextEncoder().encode(e):e;if(t==="json")return this._loads(typeof e=="string"?e:new TextDecoder().decode(e));throw new Error(`Unknown serialization type: ${t}`)}};function Pk(t){if(typeof t!="object"||t===null)return t;const e=Array.isArray(t)?[]:{};for(const n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=Pk(t[n]));return e}function n_(){return{v:4,id:GI(0),ts:new Date().toISOString(),channel_values:{},channel_versions:{},versions_seen:{}}}function Kh(t){return{v:t.v,id:t.id,ts:t.ts,channel_values:{...t.channel_values},channel_versions:{...t.channel_versions},versions_seen:Pk(t.versions_seen)}}function Nk(t,e){return typeof t=="number"&&typeof e=="number"?Math.sign(t-e):String(t).localeCompare(String(e))}function w9(...t){return t.reduce((e,n,r)=>r===0?n:Nk(e,n)>=0?e:n)}const b9={[SB]:-1,[Hd]:-2,[AB]:-3,[TB]:-4};var hc=class extends Error{constructor(t){super(t),this.name="InvalidNamespaceError"}};function v9(t){if(t.length===0)throw new hc("Namespace cannot be empty.");for(const e of t){if(typeof e!="string")throw new hc(`Invalid namespace label '${e}' found in ${t}. Namespace labels must be strings, but got ${typeof e}.`);if(e.includes("."))throw new hc(`Invalid namespace label '${e}' found in ${t}. Namespace labels cannot contain periods ('.').`);if(e==="")throw new hc(`Namespace labels cannot be empty strings. Got ${e} in ${t}`)}if(t[0]==="langgraph")throw new hc(`Root label for namespace cannot be "langgraph". Got: ${t}`)}var S9=class{async get(t,e){return(await this.batch([{namespace:t,key:e}]))[0]}async search(t,e={}){const{filter:n,limit:r=10,offset:s=0,query:i}=e;return(await this.batch([{namespacePrefix:t,filter:n,limit:r,offset:s,query:i}]))[0]}async put(t,e,n,r){v9(t),await this.batch([{namespace:t,key:e,value:n,index:r}])}async delete(t,e){await this.batch([{namespace:t,key:e,value:null}])}async listNamespaces(t={}){const{prefix:e,suffix:n,maxDepth:r,limit:s=100,offset:i=0}=t,a=[];return e&&a.push({matchType:"prefix",path:e}),n&&a.push({matchType:"suffix",path:n}),(await this.batch([{matchConditions:a.length?a:void 0,maxDepth:r,limit:s,offset:i}]))[0]}start(){}stop(){}};const A9=t=>"lg_name"in t&&t.lg_name==="AsyncBatchedStore"?t.store:t;var T9=class extends S9{constructor(e){super();m(this,"lg_name","AsyncBatchedStore");m(this,"store");m(this,"queue",new Map);m(this,"nextKey",0);m(this,"running",!1);m(this,"processingTask",null);this.store=A9(e)}get isRunning(){return this.running}async batch(e){throw new Error("The `batch` method is not implemented on `AsyncBatchedStore`.\n Instead, it calls the `batch` method on the wrapped store.\n If you are seeing this error, something is wrong.")}async get(e,n){return this.enqueueOperation({namespace:e,key:n})}async search(e,n){const{filter:r,limit:s=10,offset:i=0,query:a}=n||{};return this.enqueueOperation({namespacePrefix:e,filter:r,limit:s,offset:i,query:a})}async put(e,n,r){return this.enqueueOperation({namespace:e,key:n,value:r})}async delete(e,n){return this.enqueueOperation({namespace:e,key:n,value:null})}start(){this.running||(this.running=!0,this.processingTask=this.processBatchQueue())}async stop(){this.running=!1,this.processingTask&&await this.processingTask}enqueueOperation(e){return new Promise((n,r)=>{const s=this.nextKey;this.nextKey+=1,this.queue.set(s,{operation:e,resolve:n,reject:r})})}async processBatchQueue(){for(;this.running;){if(await new Promise(n=>{setTimeout(n,0)}),this.queue.size===0)continue;const e=new Map(this.queue);this.queue.clear();try{const n=Array.from(e.values()).map(({operation:s})=>s),r=await this.store.batch(n);e.forEach(({resolve:s},i)=>{s(r[Array.from(e.keys()).indexOf(i)])})}catch(n){e.forEach(({reject:r})=>{r(n)})}}}toJSON(){return{queue:this.queue,nextKey:this.nextKey,running:this.running,store:"[LangGraphStore]"}}},E9=class{constructor(t){m(this,"serde",new y9);this.serde=t||this.serde}};function _i(t){return t!=null&&t.lc_graph_name==="DeltaChannel"}function Mk(t){return t!=null&&t.lg_is_channel===!0}var Mi=class{constructor(){m(this,"ValueType");m(this,"UpdateType");m(this,"lg_is_channel",!0)}consume(){return!1}finish(){return!1}isAvailable(){try{return this.get(),!0}catch(t){if(t.name===tn.unminifiable_name)return!1;throw t}}equals(t){return this===t}};const r_=Symbol.for("LG_IS_ONLY_BASE_CHANNEL");function Kf(t){if(t[r_]===!0)return t;const e={};for(const n in t){if(!Object.prototype.hasOwnProperty.call(t,n))continue;const r=t[n];Mk(r)&&(e[n]=r)}return Object.assign(e,{[r_]:!0}),e}function Lk(t,e){const n=Kf(t),r={};for(const s in n){if(!Object.prototype.hasOwnProperty.call(n,s))continue;const i=e.channel_values[s];r[s]=n[s].fromCheckpoint(i)}return Object.assign(r,{[r_]:!0}),r}function Hv(t,e){const n=new Set,r=q6();for(const s in t){if(!Object.prototype.hasOwnProperty.call(t,s))continue;const i=t[s];if(!_i(i)||!i.isAvailable())continue;const[a,o]=e[s]??[0,0];(a>=i.snapshotFrequency||o>=r)&&n.add(s)}return n}function Gi(t,e,n,r){const s=(r==null?void 0:r.channelsToSnapshot)??new Set,{updatedChannels:i,getNextVersion:a}=r??{};let o,c=t.channel_versions;if(e===void 0)o=t.channel_values;else{o={},c={...t.channel_versions};for(const u in e){if(!Object.prototype.hasOwnProperty.call(e,u))continue;const l=e[u];if(s.has(u)){a!==void 0&&(i===void 0||!i.has(u))&&(c[u]=a(c[u])),o[u]=new By(l.get());continue}if(!_i(l))try{o[u]=l.checkpoint()}catch(d){if(d.name!==tn.unminifiable_name)throw d}}}return{v:4,id:(r==null?void 0:r.id)??GI(n),ts:new Date().toISOString(),channel_values:o,channel_versions:c,versions_seen:t.versions_seen}}async function s_(t,e,n){const r=Lk(t,e),{saver:s,config:i}=n??{},a=Kf(t),o=[];for(const u in a)Object.prototype.hasOwnProperty.call(a,u)&&_i(a[u])&&!Object.prototype.hasOwnProperty.call(e.channel_values,u)&&o.push(u);if(o.length===0||s===void 0||i===void 0)return r;const c=await s.getDeltaChannelHistory({config:i,channels:o});for(const u of o){const l=c[u];if(l===void 0)continue;const d=a[u].fromCheckpoint(l.seed);d.replayWrites(l.writes),r[u]=d}return r}var Wf=class jk extends Mi{constructor(n){super();m(this,"lc_graph_name","LastValue");m(this,"value",[]);this.initialValueFactory=n,n&&(this.value=[n()])}fromCheckpoint(n){const r=new jk(this.initialValueFactory);return typeof n<"u"&&(r.value=[n]),r}update(n){if(n.length===0)return!1;if(n.length!==1)throw new ft("LastValue can only receive one value per step.",{lc_error_code:"INVALID_CONCURRENT_GRAPH_UPDATE"});return this.value=[n[n.length-1]],!0}get(){if(this.value.length===0)throw new tn;return this.value[0]}checkpoint(){if(this.value.length===0)throw new tn;return this.value[0]}isAvailable(){return this.value.length!==0}},I9=class Dk extends Mi{constructor(){super(...arguments);m(this,"lc_graph_name","LastValueAfterFinish");m(this,"value",[]);m(this,"finished",!1)}fromCheckpoint(n){const r=new Dk;if(typeof n<"u"){const[s,i]=n;r.value=[s],r.finished=i}return r}update(n){return n.length===0?!1:(this.finished=!1,this.value=[n[n.length-1]],!0)}get(){if(this.value.length===0||!this.finished)throw new tn;return this.value[0]}checkpoint(){if(this.value.length!==0)return[this.value[0],this.finished]}consume(){return this.finished?(this.finished=!1,this.value=[],!0):!1}finish(){return!this.finished&&this.value.length>0?(this.finished=!0,!0):!1}isAvailable(){return this.value.length!==0&&this.finished}};const x9=t=>t!=null&&t.lc_graph_name==="BinaryOperatorAggregate";var Wh=class Uk extends Mi{constructor(n,r){super();m(this,"lc_graph_name","BinaryOperatorAggregate");m(this,"value");m(this,"operator");m(this,"initialValueFactory");this.operator=n,this.initialValueFactory=r,this.value=r==null?void 0:r()}fromCheckpoint(n){const r=new Uk(this.operator,this.initialValueFactory);return typeof n<"u"&&(r.value=n),r}update(n){let r=n;if(!r.length)return!1;if(this.value===void 0){const i=r[0],[a,o]=Pu(i);a?this.value=o:this.value=i,r=r.slice(1)}let s=!1;for(const i of r)if(tB(i)){if(s)throw new ft("Can receive only one Overwrite value per step.");const[,a]=Pu(i);this.value=a,s=!0;continue}else!s&&this.value!==void 0&&(this.value=this.operator(this.value,i));return!0}get(){if(this.value===void 0)throw new tn;return this.value}checkpoint(){if(this.value===void 0)throw new tn;return this.value}isAvailable(){return this.value!==void 0}equals(n){return this===n?!0:x9(n)?this.operator===n.operator:!1}},i_=class{constructor(t){m(this,"lc_graph_name","AnnotationRoot");m(this,"spec");this.spec=t}static isInstance(t){return typeof t=="object"&&t!==null&&"lc_graph_name"in t&&t.lc_graph_name==="AnnotationRoot"}};const fa=function(t){return t?a_(t):new Wf};fa.Root=t=>new i_(t);function a_(t){return typeof t=="object"&&t&&"reducer"in t&&t.reducer?new Wh(t.reducer,t.default):typeof t=="object"&&t&&"value"in t&&t.value?new Wh(t.value,t.default):new Wf}const k9=["tags","metadata","callbacks","configurable"],C9=["tags","metadata","callbacks","runName","maxConcurrency","recursionLimit","configurable","runId","outputKeys","streamMode","store","writer","interrupt","context","interruptBefore","interruptAfter","checkpointDuring","durability","signal","heartbeat","executionInfo","serverInfo","control"],O9=25,$9=new Set(["thread_id","checkpoint_id","checkpoint_ns","task_id","run_id","assistant_id","graph_id"]);function R9(t,e){if(!t)return e;const n=e??{};for(const r of $9){if(r in n)continue;const s=t[r];s!==void 0&&(n[r]=s)}return n}function Fk(...t){const e={tags:[],metadata:{},callbacks:void 0,recursionLimit:O9,configurable:{}},n=pn.getRunnableConfig();if(n!==void 0){for(const[r,s]of Object.entries(n))if(s!==void 0)if(k9.includes(r)){let i;Array.isArray(s)?i=[...s]:typeof s=="object"?r==="callbacks"&&"copy"in s&&typeof s.copy=="function"?i=s.copy():i={...s}:i=s,e[r]=i}else e[r]=s}for(const r of t)if(r!==void 0)for(const[s,i]of Object.entries(r))i!==void 0&&C9.includes(s)&&(e[s]=i);return e.metadata=R9(e.configurable,e.metadata)??{},e}function P9(){return pn.getRunnableConfig()}function Qp(t){return t.split("|").filter(e=>!e.match(/^\d+$/)).map(e=>e.split(":")[0]).join("|")}function N9(t){const e=t.split("|");for(;e.length>1&&e[e.length-1].match(/^\d+$/);)e.pop();return e.slice(0,-1).join("|")}var bs=class extends ze{constructor(e){super();m(this,"lc_namespace",["langgraph"]);m(this,"func");m(this,"tags");m(this,"config");m(this,"trace",!0);m(this,"recurse",!0);this.name=e.name??e.func.name,this.func=e.func,this.config=e.tags?{tags:e.tags}:void 0,this.trace=e.trace??this.trace,this.recurse=e.recurse??this.recurse}async _tracedInvoke(e,n,r){return new Promise((s,i)=>{const a=et(n,{callbacks:r==null?void 0:r.getChild()});pn.runWithConfig(a,async()=>{try{s(await this.func(e,a))}catch(o){i(o)}})})}async invoke(e,n){let r;const s=Fk(n),i=ir(this.config,s);return this.trace?r=await this._callWithConfig(this._tracedInvoke,e,i):r=await pn.runWithConfig(i,async()=>this.func(e,i)),ze.isRunnable(r)&&this.recurse?await pn.runWithConfig(i,async()=>r.invoke(e,i)):r}};function*Is(t,e){if(e===void 0)yield*t;else for(const n of t)yield[e,n]}async function li(t){const e=[];for await(const n of await t)e.push(n);return e}function qa(t){const e=[];for(const n of t)e.push(n);return e}function Ra(t,e){return t?"configurable"in t?{...t,configurable:{...t.configurable,...e}}:{...t,configurable:e}:{configurable:e}}function M9(t){return typeof t=="object"&&(t==null?void 0:t[Symbol.for("LG_SKIP_WRITE")])!==void 0}const pa={[Symbol.for("LG_PASSTHROUGH")]:!0};function cd(t){return typeof t=="object"&&(t==null?void 0:t[Symbol.for("LG_PASSTHROUGH")])!==void 0}const em=Symbol("IS_WRITER");var Pn=class o_ extends bs{constructor(n,r){const s=`ChannelWrite<${n.map(i=>Wn(i)?i.node:"channel"in i?i.channel:"...").join(",")}>`;super({writes:n,name:s,tags:r,trace:!1,func:async(i,a)=>this._write(i,a??{})});m(this,"writes");this.writes=n}async _write(n,r){const s=this.writes.map(i=>tm(i)&&cd(i.value)?{mapper:i.mapper,value:n}:Gd(i)&&cd(i.value)?{channel:i.channel,value:n,skipNone:i.skipNone,mapper:i.mapper}:i);return await o_.doWrite(r,s),n}static async doWrite(n,r){var a;for(const o of r){if(Gd(o)){if(o.channel==="__pregel_tasks")throw new ft("Cannot write to the reserved channel TASKS");if(cd(o.value))throw new ft("PASSTHROUGH value must be replaced")}if(tm(o)&&cd(o.value))throw new ft("PASSTHROUGH value must be replaced")}const s=[];for(const o of r)if(Wn(o))s.push([Vo,o]);else if(tm(o)){const c=await o.mapper.invoke(o.value,n);c!=null&&c.length>0&&s.push(...c)}else if(Gd(o)){const c=o.mapper!==void 0?await o.mapper.invoke(o.value,n):o.value;if(M9(c)||o.skipNone&&c===void 0)continue;s.push([o.channel,c])}else throw new Error(`Invalid write entry: ${JSON.stringify(o)}`);((a=n.configurable)==null?void 0:a[Jr])(s)}static isWriter(n){return n instanceof o_||em in n&&!!n[em]}static registerWriter(n){return Object.defineProperty(n,em,{value:!0})}};function Gd(t){return t!==void 0&&typeof t.channel=="string"}function tm(t){return t!==void 0&&!Gd(t)&&ze.isRunnable(t.mapper)}var L9=class Bk extends bs{constructor(n,r,s=!1){super({trace:!1,func:(i,a)=>Bk.doRead(a,this.channel,this.fresh,this.mapper)});m(this,"lc_graph_name","ChannelRead");m(this,"channel");m(this,"fresh",!1);m(this,"mapper");this.fresh=s,this.mapper=r,this.channel=n,this.name=Array.isArray(n)?`ChannelRead<${n.join(",")}>`:`ChannelRead<${n}>`}static doRead(n,r,s,i){var o;const a=(o=n.configurable)==null?void 0:o[Ai];if(!a)throw new Error("Runnable is not configured with a read function. Make sure to call in the context of a Pregel process");return i?i(a(r,s)):a(r,s)}};const Pa=new Ru;var Fu=class Bc extends dn{constructor(n){var w;const{channels:r,triggers:s,mapper:i,writers:a,bound:o,kwargs:c,metadata:u,retryPolicy:l,cachePolicy:d,timeout:f,tags:h,subgraphs:p,ends:g,isErrorHandler:y,errorHandlerNode:b}=n,_=[...(w=n.config)!=null&&w.tags?n.config.tags:[],...h??[]];super({...n,bound:n.bound??Pa,config:{...n.config?n.config:{},tags:_}});m(this,"lc_graph_name","PregelNode");m(this,"channels");m(this,"triggers",[]);m(this,"mapper");m(this,"writers",[]);m(this,"bound",Pa);m(this,"kwargs",{});m(this,"metadata",{});m(this,"tags",[]);m(this,"retryPolicy");m(this,"cachePolicy");m(this,"timeout");m(this,"subgraphs");m(this,"ends");m(this,"isErrorHandler");m(this,"errorHandlerNode");this.channels=r,this.triggers=s,this.mapper=i,this.writers=a??this.writers,this.bound=o??this.bound,this.kwargs=c??this.kwargs,this.metadata=u??this.metadata,this.tags=_,this.retryPolicy=l,this.cachePolicy=d,this.timeout=f,this.subgraphs=p,this.ends=g,this.isErrorHandler=y,this.errorHandlerNode=b}getWriters(){var r;const n=[...this.writers];for(;n.length>1&&n[n.length-1]instanceof Pn&&n[n.length-2]instanceof Pn;){const s=n.slice(-2),i=s[0].writes.concat(s[1].writes);n[n.length-2]=new Pn(i,(r=s[0].config)==null?void 0:r.tags),n.pop()}return n}getNode(){const n=this.getWriters();if(!(this.bound===Pa&&n.length===0))return this.bound===Pa&&n.length===1?n[0]:this.bound===Pa?new fr({first:n[0],middle:n.slice(1,n.length-1),last:n[n.length-1],omitSequenceTags:!0}):n.length>0?new fr({first:this.bound,middle:n.slice(0,n.length-1),last:n[n.length-1],omitSequenceTags:!0}):this.bound}join(n){if(!Array.isArray(n))throw new Error("channels must be a list");if(typeof this.channels!="object")throw new Error("all channels must be named when using .join()");return new Bc({channels:{...this.channels,...Object.fromEntries(n.map(r=>[r,r]))},triggers:this.triggers,mapper:this.mapper,writers:this.writers,bound:this.bound,kwargs:this.kwargs,config:this.config,retryPolicy:this.retryPolicy,cachePolicy:this.cachePolicy,timeout:this.timeout})}pipe(n){return Pn.isWriter(n)?new Bc({channels:this.channels,triggers:this.triggers,mapper:this.mapper,writers:[...this.writers,n],bound:this.bound,config:this.config,kwargs:this.kwargs,retryPolicy:this.retryPolicy,cachePolicy:this.cachePolicy,timeout:this.timeout}):this.bound===Pa?new Bc({channels:this.channels,triggers:this.triggers,mapper:this.mapper,writers:this.writers,bound:hn(n),config:this.config,kwargs:this.kwargs,retryPolicy:this.retryPolicy,cachePolicy:this.cachePolicy,timeout:this.timeout}):new Bc({channels:this.channels,triggers:this.triggers,mapper:this.mapper,writers:this.writers,bound:this.bound.pipe(n),config:this.config,kwargs:this.kwargs,retryPolicy:this.retryPolicy,cachePolicy:this.cachePolicy,timeout:this.timeout})}};function gw(t){const e=typeof t[un];if(e==="number")return 0;if(e==="string")return"";for(const n in t){if(!Object.prototype.hasOwnProperty.call(t,n))continue;const r=typeof t[n];if(r==="number")return 0;if(r==="string")return"";break}}function Jd(t,e){if(Object.keys(t).length>0){const n=gw(e);return Object.fromEntries(Object.entries(e).filter(([r,s])=>s>(t[r]??n)))}else return e}function j9(t,e){return t&&!Array.isArray(t)&&!(t instanceof Date)&&typeof t=="object"?t:{[e]:t}}function $n(t,e){return t===null?{configurable:e}:(t==null?void 0:t.configurable)===void 0?{...t,configurable:e}:{...t,configurable:{...t.configurable,...e}}}function Di(t,e){var r,s;const n=(e==null?void 0:e.parents)??{};return Object.keys(n).length>0?$n(t,{[sr]:{...n,[((r=t.configurable)==null?void 0:r.checkpoint_ns)??""]:(s=t.configurable)==null?void 0:s.checkpoint_id}}):t}function Bu(...t){const e=[...new Set(t.filter(Boolean))];if(e.length===0)return{signal:void 0,dispose:void 0};if(e.length===1)return{signal:e[0],dispose:void 0};const n=new AbortController,r=()=>{var a;const i=(a=e.find(o=>o.aborted))==null?void 0:a.reason;n.abort(i),e.forEach(o=>o.removeEventListener("abort",r))};e.forEach(i=>i.addEventListener("abort",r,{once:!0}));const s=e.find(i=>i.aborted);return s&&n.abort(s.reason),{signal:n.signal,dispose:()=>{e.forEach(i=>i.removeEventListener("abort",r))}}}const D9=(t,e)=>{if(!(!t&&!e))return t?e?Array.isArray(t)&&Array.isArray(e)?[...t,...e]:Array.isArray(t)?[...t,e]:Array.isArray(e)?[t,...e]:[t,e]:t:e};function U9(t){return"steps"in t&&Array.isArray(t.steps)}function _w(t){return"lg_is_pregel"in t&&t.lg_is_pregel===!0}function zk(t){const e=[t];for(const n of e){if(_w(n))return n;U9(n)&&e.push(...n.steps)}}var Zo=class Hk extends Mi{constructor(n=!0){super();m(this,"lc_graph_name","EphemeralValue");m(this,"guard");m(this,"value",[]);this.guard=n}fromCheckpoint(n){const r=new Hk(this.guard);return typeof n<"u"&&(r.value=[n]),r}update(n){if(n.length===0){const r=this.value.length>0;return this.value=[],r}if(n.length!==1&&this.guard)throw new ft("EphemeralValue can only receive one value per step.");return this.value=[n[n.length-1]],!0}get(){if(this.value.length===0)throw new tn;return this.value[0]}checkpoint(){if(this.value.length===0)throw new tn;return this.value[0]}isAvailable(){return this.value.length!==0}},yo,sT,F9=(sT=class{constructor(){Ze(this,yo)}requestDrain(t="shutdown"){ct(this,yo,t)}get drainRequested(){return ne(this,yo)!==void 0}get drainReason(){return ne(this,yo)}},yo=new WeakMap,sT);const J=t=>BigInt(t),at=(t,e=0)=>new DataView(t.buffer,t.byteOffset+e,t.byteLength-e),Vk=J("0x9E3779B1"),Kk=J("0x85EBCA77"),B9=J("0xC2B2AE3D"),Pi=J("0x9E3779B185EBCA87"),va=J("0xC2B2AE3D27D4EB4F"),Wk=J("0x165667B19E3779F9"),yw=J("0x85EBCA77C2B2AE63"),z9=J("0x27D4EB2F165667C5"),H9=J("0x165667919E3779F9"),V9=J("0x9FB21C651E98DF25"),K9=t=>{const e=t.length;if(e%2!==0)throw new Error("String should have an even number of characters");const n=e/2,r=new Uint8Array(n);let s=0,i=0;for(;i<n;){const a=t.slice(s,s+=2);r[i]=Number.parseInt(a,16),i+=1}return at(r)},as=K9("b8fe6c3923a44bbe7c01812cf721ad1cded46de9839097db7240a4a4b7b3671fcb79e64eccc0e578825ad07dccff7221b8084674f743248ee03590e6813a264c3c2852bb91c300cb88d0658b1b532ea371644897a20df94e3819ef46a9deacd8a8fa763fe39c343ff9dcbbc7c70b4f1d8a51e04bcdb45931c89f7ec9d9787364eac5ac8334d3ebc3c581a0fffa1363eb170ddd51b7f0da49d316552629d4689e2b16be587d47a1fc8ff8b8d17ad031ce45cb3a8f95160428afd7fbcabb4b407e"),mo=(J(1)<<J(128))-J(1),je=(J(1)<<J(64))-J(1),Zh=(J(1)<<J(32))-J(1),Ls=64,Zk=Ls/8,W9=8,ud=4;function qo(t){if(!t)throw new Error("Assert failed")}function Z9(t){const e=new DataView(new ArrayBuffer(8));return e.setBigUint64(0,t,!0),e.getBigUint64(0,!1)}function q9(t){let e=t;return e=(e&J(65535))<<J(16)|(e&J(4294901760))>>J(16),e=(e&J(16711935))<<J(8)|(e&J(4278255360))>>J(8),e}function G9(t,e){return(t&Zh)*(e&Zh)&je}function J9(t,e){return(t<<e|t>>J(32)-e)&Zh}function qk(t,e,n){for(let r=0;r<Zk;r+=1){const s=e.getBigUint64(r*8,!0),i=s^n.getBigUint64(r*8,!0);t[r^1]+=s,t[r]+=G9(i,i>>J(32))}return t}function Vv(t,e,n,r){for(let s=0;s<r;s+=1)qk(t,at(e,s*Ls),at(n,s*8));return t}function Y9(t,e){for(let n=0;n<Zk;n+=1){const r=e.getBigUint64(n*8,!0);let s=t[n];s=c_(s,J(47)),s^=r,s*=Vk,t[n]=s&je}return t}function ld(t,e){return Gk(t[0]^e.getBigUint64(0,!0),t[1]^e.getBigUint64(W9,!0))}function Kv(t,e,n){let r=n;return r+=ld(t.slice(0),at(e,0*ud)),r+=ld(t.slice(2),at(e,4*ud)),r+=ld(t.slice(4),at(e,8*ud)),r+=ld(t.slice(6),at(e,12*ud)),ps(r&je)}function X9(t,e,n,r,s){let i=t;const a=Math.floor((n.byteLength-Ls)/8),o=Ls*a,c=Math.floor((e.byteLength-1)/o);for(let u=0;u<c;u+=1)i=Vv(i,at(e,u*o),n,a),i=s(i,at(n,n.byteLength-Ls));{const u=Math.floor((e.byteLength-1-o*c)/Ls);i=Vv(i,at(e,c*o),n,u),i=r(i,at(e,e.byteLength-Ls),at(n,n.byteLength-Ls-7))}return i}function Q9(t,e){let n=new BigUint64Array([B9,Pi,va,Wk,yw,Kk,z9,Vk]);qo(t.byteLength>128),n=X9(n,t,e,qk,Y9),qo(n.length*8===64);{const r=Kv(n,at(e,11),J(t.byteLength)*Pi&je);return Kv(n,at(e,e.byteLength-Ls-11),~(J(t.byteLength)*va)&je)<<J(64)|r}}function Gk(t,e){const n=t*e&mo;return n&je^n>>J(64)}function Wv(t,e,n){return Gk((t.getBigUint64(0,!0)^e.getBigUint64(0,!0)+n)&je,(t.getBigUint64(8,!0)^e.getBigUint64(8,!0)-n)&je)}function Yd(t,e,n,r,s){let i=t&je,a=t>>J(64)&je;return i+=Wv(e,r,s),i^=n.getBigUint64(0,!0)+n.getBigUint64(8,!0),i&=je,a+=Wv(n,at(r,16),s),a^=e.getBigUint64(0,!0)+e.getBigUint64(8,!0),a&=je,a<<J(64)|i}function ps(t){let e=t;return e^=e>>J(37),e*=H9,e&=je,e^=e>>J(32),e}function qh(t){let e=t;return e^=e>>J(33),e*=va,e&=je,e^=e>>J(29),e*=Wk,e&=je,e^=e>>J(32),e}function eH(t,e,n){const r=t.byteLength;qo(r>0&&r<=3);const s=J(t.getUint8(r-1))|J(r<<8)|J(t.getUint8(0)<<16)|J(t.getUint8(r>>1)<<24),i=(s^(J(e.getUint32(0,!0))^J(e.getUint32(4,!0)))+n)&je,a=(J(e.getUint32(8,!0))^J(e.getUint32(12,!0)))-n;return(qh((J9(q9(s),J(13))^a)&je)&je)<<J(64)|qh(i)}function c_(t,e){return t^t>>e}function tH(t,e,n){const r=t.byteLength;qo(r>=4&&r<=8);{const s=t.getUint32(0,!0),i=t.getUint32(r-4,!0);let a=((J(s)|J(i)<<J(32))^(e.getBigUint64(16,!0)^e.getBigUint64(24,!0))+n&je)*(Pi+(J(r)<<J(2)))&mo;return a+=(a&je)<<J(65),a&=mo,a^=a>>J(67),c_(c_(a&je,J(35))*V9&je,J(28))|ps(a>>J(64))<<J(64)}}function nH(t,e,n){const r=t.byteLength;qo(r>=9&&r<=16);{const s=(e.getBigUint64(32,!0)^e.getBigUint64(40,!0))+n&je,i=(e.getBigUint64(48,!0)^e.getBigUint64(56,!0))-n&je,a=t.getBigUint64(0,!0);let o=t.getBigUint64(r-8,!0),c=(a^o^s)*Pi;const u=(c&je)+(J(r-1)<<J(54));c=c&(mo^je)|u,o^=i,c+=o+(o&Zh)*(Kk-J(1))<<J(64),c&=mo,c^=Z9(c>>J(64));let l=(c&je)*va;return l+=(c>>J(64))*va<<J(64),l&=mo,ps(l&je)|ps(l>>J(64))<<J(64)}}function rH(t,e){const n=t.byteLength;return qo(n<=16),n>8?nH(t,as,e):n>=4?tH(t,as,e):n>0?eH(t,as,e):qh(e^as.getBigUint64(64,!0)^as.getBigUint64(72,!0))|qh(e^as.getBigUint64(80,!0)^as.getBigUint64(88,!0))<<J(64)}function u_(t){return~t+J(1)&je}function sH(t,e,n){let r=J(t.byteLength)*Pi&je,s=J(t.byteLength-1)/J(32);for(;s>=0;){const o=Number(s);r=Yd(r,at(t,16*o),at(t,t.byteLength-16*(o+1)),at(e,32*o),n),s-=J(1)}let i=r+(r>>J(64))&je;i=ps(i);let a=(r&je)*Pi+(r>>J(64))*yw+(J(t.byteLength)-n&je)*va;return a&=je,a=u_(ps(a)),i|a<<J(64)}function iH(t,e,n){let r=J(t.byteLength)*Pi&je;for(let a=32;a<160;a+=32)r=Yd(r,at(t,a-32),at(t,a-16),at(e,a-32),n);r=ps(r&je)|ps(r>>J(64))<<J(64);for(let a=160;a<=t.byteLength;a+=32)r=Yd(r,at(t,a-32),at(t,a-16),at(e,3+a-160),n);r=Yd(r,at(t,t.byteLength-16),at(t,t.byteLength-32),at(e,103),u_(n));let s=r+(r>>J(64))&je;s=ps(s);let i=(r&je)*Pi+(r>>J(64))*yw+(J(t.byteLength)-n&je)*va;return i&=je,i=u_(ps(i)),s|i<<J(64)}function oi(t,e=J(0)){const n=new TextEncoder,r=at(typeof t=="string"?n.encode(t):t),s=r.byteLength,i=a=>a.toString(16).padStart(32,"0");return s<=16?i(rH(r,e)):s<=128?i(sH(r,as,e)):s<=240?i(iH(r,as,e)):i(Q9(r,as))}function Jk(t){return/^[0-9a-f]{32}$/.test(t)}function go(t,e,n=!0,r=!1){try{return t[e].get()}catch(s){if(s.name===tn.unminifiable_name){if(r)return s;if(n)return null}throw s}}function Sa(t,e,n=!0){if(Array.isArray(e)){const r={};for(const s of e)try{r[s]=go(t,s,!n)}catch(i){if(i.name===tn.unminifiable_name)continue}return r}else return go(t,e)}function*aH(t,e){if(t.graph===ar.PARENT)throw new ft("There is no parent graph.");if(t.goto){let n;Array.isArray(t.goto)?n=t.goto:n=[t.goto];for(const r of n)if(Wn(r))yield[Ar,Vo,r];else if(typeof r=="string")yield[Ar,`branch:to:${r}`,"__start__"];else throw new Error(`In Command.send, expected Send or string, got ${typeof r}`)}if(t.resume)if(typeof t.resume=="object"&&Object.keys(t.resume).length&&Object.keys(t.resume).every(Jk))for(const[n,r]of Object.entries(t.resume)){const s=e.filter(i=>i[0]===n&&i[1]==="__resume__").map(i=>i[2]).slice(0,1)??[];s.push(r),yield[n,ws,s]}else yield[Ar,ws,t.resume];if(t.update){if(typeof t.update!="object"||!t.update)throw new Error("Expected cmd.update to be a dict mapping channel names to update values");if(Array.isArray(t.update))for(const[n,r]of t.update)yield[Ar,n,r];else for(const[n,r]of Object.entries(t.update))yield[Ar,n,r]}}function*Yk(t,e){if(e!=null)if(Array.isArray(t)&&typeof e=="object"&&!Array.isArray(e))for(const n in e)t.includes(n)&&(yield[n,e[n]]);else{if(Array.isArray(t))throw new Error('Input chunk must be an object when "inputChannels" is an array');yield[t,e]}}function*nm(t,e,n){Array.isArray(t)?(e===!0||e.find(([r,s])=>t.includes(r)))&&(yield Sa(n,t)):(e===!0||e.some(([r,s])=>r===t))&&(yield go(n,t))}function*oH(t,e,n){const r=e.filter(([o,c])=>{var u;return(o.config===void 0||!((u=o.config.tags)!=null&&u.includes("langsmith:hidden")))&&c[0][0]!=="__error__"&&c[0][0]!=="__interrupt__"});if(!r.length)return;let s;r.some(([o])=>o.writes.some(([c,u])=>c==="__return__"))?s=r.flatMap(([o])=>o.writes.filter(([c,u])=>c===$f).map(([c,u])=>[o.name,u])):Array.isArray(t)?s=r.flatMap(([o])=>{const{writes:c}=o,u={};for(const[l]of c)t.includes(l)&&(u[l]=(u[l]||0)+1);return Object.values(u).some(l=>l>1)?c.filter(([l])=>t.includes(l)).map(([l,d])=>[o.name,{[l]:d}]):[[o.name,Object.fromEntries(c.filter(([l])=>t.includes(l)))]]}):s=r.flatMap(([o])=>o.writes.filter(([c,u])=>c===t).map(([c,u])=>[o.name,u]));const i={};for(const[o,c]of s)o in i||(i[o]=[]),i[o].push(c);const a={};for(const o in i)if(i[o].length===1){const[c]=i[o];a[o]=c}else a[o]=i[o];n&&(a.__metadata__={cached:n}),yield a}var cH=class{constructor({func:t,name:e,input:n,retry:r,cache:s,timeout:i,callbacks:a}){m(this,"func");m(this,"name");m(this,"input");m(this,"retry");m(this,"cache");m(this,"timeout");m(this,"callbacks");m(this,"__lg_type","call");this.func=t,this.name=e,this.input=n,this.retry=r,this.cache=s,this.timeout=i,this.callbacks=a}};function uH(t){return typeof t=="object"&&t!==null&&"__lg_type"in t&&t.__lg_type==="call"}function lH(t,e){return new fr({name:t,first:new bs({func:n=>e(...n),name:t,trace:!1,recurse:!1}),last:new Pn([{channel:$f,value:pa}],[Hn])})}const dH=t=>t!==void 0?t+1:1;function hH(t,e){if(e==null)return!1;for(const n of t)if(e[n])return!0;return!1}function fH(t){let e;for(const n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e==null?e=t[n]:e=w9(e,t[n]));return e}function dd(t,e,n){const r=gw(t.channel_versions),s=t.versions_seen.__interrupt__??{};let i=!1;if((t.channel_versions.__start__??r)>(s.__start__??r))i=!0;else for(const o in t.channel_versions)if(Object.prototype.hasOwnProperty.call(t.channel_versions,o)&&t.channel_versions[o]>(s[o]??r)){i=!0;break}const a=n.some(o=>{var c,u;return e==="*"?!((u=(c=o.config)==null?void 0:c.tags)!=null&&u.includes(Hn)):e.includes(o.name)});return i&&a}function pu(t,e,n,r,s=!1){let i=new Set;if(Array.isArray(r))i=new Set(r.filter(o=>n.writes.some(([c,u])=>c===o)));else{for(const[o]of n.writes)if(o===r){i=new Set([o]);break}i=i||new Set}let a;if(s&&i.size>0){const o=Object.fromEntries(Object.entries(e).filter(([d,f])=>i.has(d))),c=new Set;for(const d in o){if(!Object.prototype.hasOwnProperty.call(o,d))continue;const f=o[d];_i(f)&&f.isAvailable()&&c.add(d)}const u=Gi(t,o,-1,{channelsToSnapshot:c}),l=Lk(o,u);nr(Kh(u),l,[n],void 0,void 0),a=Sa({...e,...l},r)}else a=Sa(e,r);return a}function Xd(t,e,n){for(const[r,s]of n)if(["__pregel_push","__pregel_tasks"].includes(r)&&s!=null){if(!Wn(s))throw new ft(`Invalid packet type, expected SendProtocol, got ${JSON.stringify(s)}`);if(!(s.node in e))throw new ft(`Invalid node name "${s.node}" in Send packet`)}t(n)}const pH=new Set([Ly,Tr,ws,Nt,$f,bl,Ny]),mH=new Set(Q6);function nr(t,e,n,r,s){var h,p,g;const i=new Map;for(const y of n)i.set(y,((h=y.path)==null?void 0:h.slice(0,3))||[]);n.sort((y,b)=>{const _=i.get(y),w=i.get(b);for(let v=0;v<Math.min(_.length,w.length);v+=1){if(_[v]<w[v])return-1;if(_[v]>w[v])return 1}return _.length-w.length});const a=Kf(e);let o=!1;const c=new Set;for(const y of n){y.triggers.length>0&&(o=!0),(p=t.versions_seen)[g=y.name]??(p[g]={});for(const b of y.triggers)b in t.channel_versions&&(t.versions_seen[y.name][b]=t.channel_versions[b]),mH.has(b)||c.add(b)}let u=fH(t.channel_versions),l=!1;for(const y of c)y in a&&a[y].consume()&&r!==void 0&&(t.channel_versions[y]=r(u),l=!0);const d={};for(const y of n)for(const[b,_]of y.writes)pH.has(b)||b in a&&(d[b]??(d[b]=[]),d[b].push(_));u!=null&&r!=null&&(u=l?r(u):u);const f=new Set;for(const[y,b]of Object.entries(d))if(y in a){const _=a[y];let w;try{w=_.update(b)}catch(v){if(v.name===ft.unminifiable_name){const A=new ft(`Invalid update for channel "${y}" with values ${JSON.stringify(b)}: ${v.message}`);throw A.lc_error_code=v.lc_error_code,A}else throw v}w&&r!==void 0&&(t.channel_versions[y]=r(u),_.isAvailable()&&f.add(y))}if(o)for(const y in a){if(!Object.prototype.hasOwnProperty.call(a,y))continue;const b=a[y];b.isAvailable()&&!f.has(y)&&b.update([])&&r!==void 0&&(t.channel_versions[y]=r(u),b.isAvailable()&&f.add(y))}if(o&&!hH(f,s))for(const y in a){if(!Object.prototype.hasOwnProperty.call(a,y))continue;const b=a[y];b.finish()&&r!==void 0&&(t.channel_versions[y]=r(u),b.isAvailable()&&f.add(y))}return f}function*gH(t,e,n){if(n.updatedChannels!=null&&n.triggerToNodes!=null){const r=new Set;for(const s of n.updatedChannels){const i=n.triggerToNodes[s];for(const a of i??[])r.add(a)}yield*[...r].sort();return}if(!(()=>{for(const r in t.channel_versions)if(t.channel_versions[r]!==null)return!1;return!0})())for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&(yield r)}function _H(t){let e;const n=new Map,r=new Set;if(t)for(const[s,i,a]of t){if(s==="00000000-0000-0000-0000-000000000000"&&i==="__resume__"&&e===void 0&&(e=a),i==="__resume__"&&s!=="00000000-0000-0000-0000-000000000000"){let o=n.get(s);o||(o=[],n.set(s,o)),o.push(a)}i!=="__error__"&&r.add(s)}return{nullResume:e,resumeByTaskId:n,successfulWriteTaskIds:r}}function io(t,e,n,r,s,i,a){const o={},c=a.pendingWritesIndex?a:{...a,pendingWritesIndex:_H(e)},u=r[Vo];if(u!=null&&u.isAvailable()){const l=u.get().length;for(let d=0;d<l;d+=1){const f=l_([Tr,d],t,e,n,r,s,i,c);f!==void 0&&(o[f.id]=f)}}for(const l of gH(t,n,c)){const d=l_([jg,l],t,e,n,r,s,i,c);d!==void 0&&(o[d.id]=d)}return o}function l_(t,e,n,r,s,i,a,o){var h,p,g,y;const{step:c,checkpointer:u,manager:l}=o,d=i.configurable??{},f=d.checkpoint_ns??"";if(t[0]==="__pregel_push"&&uH(t[t.length-1])){const b=t[t.length-1],_=lH(b.name,b.func),w=[Tr],v=f===""?b.name:`${f}|${b.name}`,A=Qi(JSON.stringify([v,c.toString(),b.name,Tr,t[1],t[2]]),e.id),S=`${v}:${A}`,x=[...t.slice(0,3),!0],E={langgraph_step:c,langgraph_node:b.name,langgraph_triggers:w,langgraph_path:x,langgraph_checkpoint_ns:S,checkpoint_ns:S};if(a){const $=[],k={checkpointId:e.id,checkpointNs:S,taskId:A,threadId:d.thread_id,runId:i.runId!=null?String(i.runId):void 0,nodeAttempt:1};return{name:b.name,input:b.input,proc:_,writes:$,config:{...et(ir(i,{metadata:E,store:o.store??i.store}),{runName:b.name,callbacks:l==null?void 0:l.getChild(`graph:step:${c}`),configurable:{[lu]:A,[Jr]:C=>Xd(D=>$.push(...D),r,C),[Ai]:(C,D=!1)=>pu(e,s,{name:b.name,writes:$,triggers:w,path:x},C,D),[ds]:u??d.__pregel_checkpointer,[sr]:{...d[sr],[f]:e.id},[Bs]:Qd({pendingWrites:n??[],taskId:A,currentTaskInput:b.input,resumeMap:(h=i.configurable)==null?void 0:h[du],namespaceHash:oi(S),pendingWritesIndex:o.pendingWritesIndex}),[hu]:e.channel_values[Bd],checkpoint_id:void 0,checkpoint_ns:S}}),executionInfo:k},triggers:w,retry_policy:b.retry,cache_key:b.cache?{key:oi((b.cache.keyFunc??JSON.stringify)([b.input])),ns:[Hp,b.name??"__dynamic__"],ttl:b.cache.ttl}:void 0,id:A,path:x,writers:[],timeout:b.timeout}}else return{id:A,name:b.name,interrupts:[],path:x}}else if(t[0]==="__pregel_push"){const b=typeof t[1]=="number"?t[1]:parseInt(t[1],10);if(!((p=s.__pregel_tasks)!=null&&p.isAvailable()))return;const _=s[Vo].get();if(b<0||b>=_.length)return;const w=Dg(_[b])&&!Wn(_[b])?new wa(_[b].node,_[b].args,_[b].timeout!==void 0?{timeout:_[b].timeout}:void 0):_[b];if(!Dg(w)){console.warn(`Ignoring invalid packet ${JSON.stringify(w)} in pending sends.`);return}if(!(w.node in r)){console.warn(`Ignoring unknown node name ${w.node} in pending sends.`);return}const v=[Tr],A=f===""?w.node:`${f}|${w.node}`,S=Qi(JSON.stringify([A,c.toString(),w.node,Tr,b.toString()]),e.id),x=`${A}:${S}`;let E={langgraph_step:c,langgraph_node:w.node,langgraph_triggers:v,langgraph_path:t.slice(0,3),langgraph_checkpoint_ns:x,checkpoint_ns:x};if(a){const $=r[w.node],k=$.getNode();if(k!==void 0){$.metadata!==void 0&&(E={...E,...$.metadata});const C=[],D={checkpointId:e.id,checkpointNs:x,taskId:S,threadId:d.thread_id,runId:i.runId!=null?String(i.runId):void 0,nodeAttempt:1};return{name:w.node,input:w.args,proc:k,subgraphs:$.subgraphs,writes:C,config:{...et(ir(i,{metadata:E,tags:$.tags,store:o.store??i.store}),{runName:w.node,callbacks:l==null?void 0:l.getChild(`graph:step:${c}`),configurable:{[lu]:S,[Jr]:B=>Xd(z=>C.push(...z),r,B),[Ai]:(B,z=!1)=>pu(e,s,{name:w.node,writes:C,triggers:v,path:t},B,z),[ds]:u??d.__pregel_checkpointer,[sr]:{...d[sr],[f]:e.id},[Bs]:Qd({pendingWrites:n??[],taskId:S,currentTaskInput:w.args,resumeMap:(g=i.configurable)==null?void 0:g[du],namespaceHash:oi(x),pendingWritesIndex:o.pendingWritesIndex}),[hu]:e.channel_values[Bd],checkpoint_id:void 0,checkpoint_ns:x}}),executionInfo:D},triggers:v,retry_policy:$.retryPolicy,cache_key:$.cachePolicy?{key:oi(($.cachePolicy.keyFunc??JSON.stringify)([w.args])),ns:[Hp,$.name??"__dynamic__",w.node],ttl:$.cachePolicy.ttl}:void 0,id:S,path:t,writers:$.getWriters(),timeout:w.timeout??$.timeout}}}else return{id:S,name:w.node,interrupts:[],path:t}}else if(t[0]==="__pregel_pull"){const b=t[1].toString(),_=r[b];if(_===void 0)return;if(n!=null&&n.length){const S=f===""?b:`${f}|${b}`,x=Qi(JSON.stringify([S,c.toString(),b,jg,b]),e.id);if(o.pendingWritesIndex?o.pendingWritesIndex.successfulWriteTaskIds.has(x):n.some(E=>E[0]===x&&E[1]!=="__error__"))return}const w=gw(e.channel_versions);if(w===void 0)return;const v=e.versions_seen[b]??{},A=_.triggers.find(S=>s[S].isAvailable()?(e.channel_versions[S]??w)>(v[S]??w):!1);if(A!==void 0){const S=wH(_,s,a);if(S===void 0)return;const x=f===""?b:`${f}|${b}`,E=Qi(JSON.stringify([x,c.toString(),b,jg,[A]]),e.id),$=`${x}:${E}`;let k={langgraph_step:c,langgraph_node:b,langgraph_triggers:[A],langgraph_path:t,langgraph_checkpoint_ns:$,checkpoint_ns:$};if(a){const C=_.getNode();if(C!==void 0){_.metadata!==void 0&&(k={...k,..._.metadata});const D=[],B={checkpointId:e.id,checkpointNs:$,taskId:E,threadId:d.thread_id,runId:i.runId!=null?String(i.runId):void 0,nodeAttempt:1};return{name:b,input:S,proc:C,subgraphs:_.subgraphs,writes:D,config:{...et(ir(i,{metadata:k,tags:_.tags,store:o.store??i.store}),{runName:b,callbacks:l==null?void 0:l.getChild(`graph:step:${c}`),configurable:{[lu]:E,[Jr]:z=>Xd(q=>{D.push(...q)},r,z),[Ai]:(z,q=!1)=>pu(e,s,{name:b,writes:D,triggers:[A],path:t},z,q),[ds]:u??d.__pregel_checkpointer,[sr]:{...d[sr],[f]:e.id},[Bs]:Qd({pendingWrites:n??[],taskId:E,currentTaskInput:S,resumeMap:(y=i.configurable)==null?void 0:y[du],namespaceHash:oi($),pendingWritesIndex:o.pendingWritesIndex}),[hu]:e.channel_values[Bd],checkpoint_id:void 0,checkpoint_ns:$}}),executionInfo:B},triggers:[A],retry_policy:_.retryPolicy,cache_key:_.cachePolicy?{key:oi((_.cachePolicy.keyFunc??JSON.stringify)([S])),ns:[Hp,_.name??"__dynamic__",b],ttl:_.cachePolicy.ttl}:void 0,id:E,path:t,writers:_.getWriters(),timeout:_.timeout}}}else return{id:E,name:b,interrupts:[],path:t}}}}function yH(t,e,n,r,s,i,a,o,c){var E;const{step:u,checkpointer:l,manager:d}=c,f=i[e];if(f===void 0)return;const h=f.getNode();if(h===void 0)return;const p=o.configurable??{},g=p.checkpoint_ns??"",y=[Tr],b=g===""?e:`${g}|${e}`,_=Qi(JSON.stringify([b,u.toString(),e,Tr,"node_error_handler",t.id]),r.id),w=`${b}:${_}`,v=[Tr,String(t.name),e,!1];let A={langgraph_step:u,langgraph_node:e,langgraph_triggers:y,langgraph_path:v,langgraph_checkpoint_ns:w,checkpoint_ns:w};f.metadata!==void 0&&(A={...A,...f.metadata});const S=[],x={checkpointId:r.id,checkpointNs:w,taskId:_,threadId:p.thread_id,runId:o.runId!=null?String(o.runId):void 0,nodeAttempt:1};return{name:e,input:t.input,proc:h,subgraphs:f.subgraphs,writes:S,config:{...et(ir(o,{metadata:A,tags:f.tags,store:c.store??o.store}),{runName:e,callbacks:d==null?void 0:d.getChild(`graph:step:${u}`),configurable:{[lu]:_,[Jr]:$=>Xd(k=>S.push(...k),i,$),[Ai]:($,k=!1)=>pu(r,a,{name:e,writes:S,triggers:y,path:v},$,k),[ds]:l??p.__pregel_checkpointer,[sr]:{...p[sr],[g]:r.id},[Bs]:Qd({pendingWrites:s??[],taskId:_,currentTaskInput:t.input,resumeMap:(E=o.configurable)==null?void 0:E[du],namespaceHash:oi(w)}),[hu]:r.channel_values[Bd],[Mg]:new sB(String(t.name),n),checkpoint_id:void 0,checkpoint_ns:w}}),executionInfo:x},triggers:y,retry_policy:f.retryPolicy,cache_key:void 0,id:_,path:v,writers:f.getWriters()}}function wH(t,e,n){let r;if(typeof t.channels=="object"&&!Array.isArray(t.channels)){r={};for(const[s,i]of Object.entries(t.channels))if(t.triggers.includes(i))try{r[s]=go(e,i,!1)}catch(a){if(a.name===tn.unminifiable_name)return;throw a}else if(i in e)try{r[s]=go(e,i,!1)}catch(a){if(a.name===tn.unminifiable_name)continue;throw a}}else if(Array.isArray(t.channels)){let s=!1;for(const i of t.channels)try{r=go(e,i,!1),s=!0;break}catch(a){if(a.name===tn.unminifiable_name)continue;throw a}if(!s)return}else throw new Error(`Invalid channels type, expected list or dict, got ${t.channels}`);return n&&t.mapper!==void 0&&(r=t.mapper(r)),r}function bH(t,e){if(typeof t.args!="object"||t.args===null)return t;const n={};for(const[r,s]of Object.entries(t.args)){const i=e[r];(!i||i.lc_graph_name!=="UntrackedValue")&&(n[r]=s)}return new wa(t.node,n)}function Qd({pendingWrites:t,taskId:e,currentTaskInput:n,resumeMap:r,namespaceHash:s,pendingWritesIndex:i}){var c;const a=i?i.nullResume:(c=t.find(([u,l])=>u==="00000000-0000-0000-0000-000000000000"&&l==="__resume__"))==null?void 0:c[2],o={callCounter:0,interruptCounter:-1,resume:(()=>{const u=i?(i.resumeByTaskId.get(e)??[]).flat():t.filter(([l,d])=>l===e&&d==="__resume__").flatMap(([l,d,f])=>f);if(r!=null&&s in r){const l=r[s];u.push(l)}return u})(),nullResume:a,subgraphCounter:0,currentTaskInput:n,consumeNullResume:()=>{if(o.nullResume)return delete o.nullResume,t.splice(t.findIndex(([u,l])=>u==="00000000-0000-0000-0000-000000000000"&&l==="__resume__"),1),a}};return o}const zu={blue:{start:"\x1B[34m",end:"\x1B[0m"},green:{start:"\x1B[32m",end:"\x1B[0m"},yellow:{start:"\x1B[33;1m",end:"\x1B[0m"}},Hu=(t,e)=>`${t.start}${e}${t.end}`;function*rm(t){var e;for(const{id:n,name:r,input:s,config:i,triggers:a,writes:o}of t)(e=i==null?void 0:i.tags)!=null&&e.includes("langsmith:hidden")||(yield{id:n,name:r,input:s,triggers:a,interrupts:o.filter(([c,u])=>c===n&&u==="__interrupt__").map(([,c])=>c)})}function vH(t){return typeof t!="object"||t===null?!1:"$writes"in t&&Array.isArray(t.$writes)}function Xk(t){const e={};for(const[n,r]of t){const s=String(n);if(s in e){const i=vH(e[s])?e[s].$writes:[e[s]];i.push(r),e[s]={$writes:i}}else e[s]=r}return e}function*SH(t,e){var n;for(const[{id:r,name:s,config:i},a]of t)(n=i==null?void 0:i.tags)!=null&&n.includes("langsmith:hidden")||(yield{id:r,name:s,result:Xk(a.filter(([o])=>Array.isArray(e)?e.includes(o):o===e)),interrupts:a.filter(o=>o[0]===Nt).map(o=>o[1])})}function*AH(t,e,n,r,s,i,a,o){var d,f,h;function c(p){const g={};return p.callbacks!=null&&(g.callbacks=p.callbacks),p.configurable!=null&&(g.configurable=p.configurable),p.maxConcurrency!=null&&(g.max_concurrency=p.maxConcurrency),p.metadata!=null&&(g.metadata=p.metadata),p.recursionLimit!=null&&(g.recursion_limit=p.recursionLimit),p.runId!=null&&(g.run_id=p.runId),p.runName!=null&&(g.run_name=p.runName),p.tags!=null&&(g.tags=p.tags),g}const u=(d=t.configurable)==null?void 0:d.checkpoint_ns,l={};for(const p of s){if(!((f=p.subgraphs)!=null&&f.length?p.subgraphs:[p.proc]).find(zk))continue;let g=`${p.name}:${p.id}`;u&&(g=`${u}|${g}`),l[p.id]={configurable:{thread_id:(h=t.configurable)==null?void 0:h.thread_id,checkpoint_ns:g}}}yield{config:c(t),values:Sa(e,n),metadata:r,next:s.map(p=>p.name),tasks:Qk(s,i,l,o),parentConfig:a?c(a):void 0}}function Qk(t,e,n,r){return t.map(s=>{var u;const i=(u=e.find(([l,d])=>l===s.id&&d==="__error__"))==null?void 0:u[2],a=e.filter(([l,d])=>l===s.id&&d==="__interrupt__").map(([,,l])=>l),o=(()=>{var d;if(i||a.length||!e.length)return;const l=e.findIndex(([f,h])=>f===s.id&&h==="__return__");if(l>=0)return e[l][2];if(typeof r=="string")return(d=e.find(([f,h])=>f===s.id&&h===r))==null?void 0:d[2];if(Array.isArray(r)){const f=e.filter(([h,p])=>h===s.id&&r.includes(p)).map(([,h,p])=>[h,p]);return f.length?Xk(f):void 0}})();if(i)return{id:s.id,name:s.name,path:s.path,error:i,interrupts:a,result:o};const c=n==null?void 0:n[s.id];return{id:s.id,name:s.name,path:s.path,interrupts:a,...c!==void 0?{state:c}:{},result:o}})}function TH(t,e,n){console.log([`${Hu(zu.blue,`[${t}:checkpoint]`)}`,`\x1B[1m State at the end of step ${t}:\x1B[0m
|
|
303
|
-
`,JSON.stringify(Sa(e,n),null,2)].join(""))}function d_(t,e){const n=e.length;console.log([`${Hu(zu.blue,`[${t}:tasks]`)}`,`\x1B[1m Starting step ${t} with ${n} task${n===1?"":"s"}:\x1B[0m
|
|
304
|
-
`,e.map(r=>`- ${Hu(zu.green,String(r.name))} -> ${JSON.stringify(r.input,null,2)}`).join(`
|
|
305
|
-
`)].join(""))}function EH(t,e,n){const r={};for(const[s,i]of e)n.includes(s)&&(r[s]||(r[s]=[]),r[s].push(i));console.log([`${Hu(zu.blue,`[${t}:writes]`)}`,`\x1B[1m Finished step ${t} with writes to ${Object.keys(r).length} channel${Object.keys(r).length!==1?"s":""}:\x1B[0m
|
|
306
|
-
`,Object.entries(r).map(([s,i])=>`- ${Hu(zu.yellow,s)} -> ${i.map(a=>JSON.stringify(a)).join(", ")}`).join(`
|
|
307
|
-
`)].join(""))}const IH=["values","updates","messages","tools","custom","tasks"];function ww(t){if(t==null||typeof t!="object")return!1;const e=t;return typeof e.id=="string"&&("source"in e||typeof e.step=="number")&&!("values"in e)&&!("config"in e)}function xH(t){if(!Array.isArray(t)||t.length!==2)return{data:t};const[e,n]=t;if(n==null||typeof n!="object")return{data:t};const r=n,s=typeof r.langgraph_node=="string"?r.langgraph_node:void 0,i=typeof r.run_id=="string"?r.run_id:void 0;return{data:i!=null&&e!=null&&typeof e=="object"?{...e,run_id:i}:e,node:s}}function kH({namespace:t,mode:e,payload:n,seq:r}){const s=Date.now(),i={type:"event"};switch(e){case"messages":{const{data:a,node:o}=xH(n);return[{...i,seq:r,method:"messages",params:{namespace:t,timestamp:s,...o?{node:o}:{},data:a}}]}case"tools":return[{...i,seq:r,method:"tools",params:{namespace:t,timestamp:s,data:CH(n)}}];case"checkpoints":return ww(n)?[{...i,seq:r,method:"checkpoints",params:{namespace:t,timestamp:s,data:n}}]:[];case"values":return[{...i,seq:r,method:"values",params:{namespace:t,timestamp:s,data:n}}];case"updates":{const a=OH(n);return[{...i,seq:r,method:"updates",params:{namespace:t,timestamp:s,...typeof a.node=="string"?{node:a.node}:{},data:a}}]}case"custom":{const a=typeof n=="object"&&n!==null&&!Array.isArray(n)&&"name"in n?n:{payload:n};return[{...i,seq:r,method:"custom",params:{namespace:t,timestamp:s,data:a}}]}case"tasks":return[{...i,seq:r,method:"tasks",params:{namespace:t,timestamp:s,data:n}}];default:return[]}}function CH(t){if(typeof t!="object"||t===null)return{event:"tool-error",tool_call_id:"",message:"Unexpected tools payload shape"};const e=t,n=String(e.toolCallId??"");switch(e.event){case"on_tool_start":return{event:"tool-started",tool_call_id:n,tool_name:String(e.name??"unknown"),input:e.input};case"on_tool_event":return{event:"tool-output-delta",tool_call_id:n,delta:typeof e.data=="string"?e.data:JSON.stringify(e.data??"")};case"on_tool_end":return{event:"tool-finished",tool_call_id:n,output:e.output};case"on_tool_error":{const r=e.error;return{event:"tool-error",tool_call_id:n,message:typeof r=="object"&&r!==null&&"message"in r&&typeof r.message=="string"?r.message:String(r??"unknown error")}}default:return{event:"tool-error",tool_call_id:"",message:`Unknown tool event: ${String(e.event)}`}}}function OH(t){if(typeof t!="object"||t===null)return{values:{}};const e=Object.entries(t);if(e.length===0)return{values:{}};const[n,r]=e[0];return{node:n,values:typeof r=="object"&&r!==null?r:{value:r}}}var sm=class extends Vn{constructor(e,n){const r=e.getReader(),s=n??new AbortController;super({start(i){return a();function a(){return r.read().then(({done:o,value:c})=>{if(o){i.close();return}return i.enqueue(c),a()})}}});m(this,"_abortController");m(this,"_innerReader");this._abortController=s,this._innerReader=r}async cancel(e){this._abortController.abort(e),this._innerReader.releaseLock()}get signal(){return this._abortController.signal}},eC=class extends Vn{constructor(e){let n;const r=new Promise(s=>{n=s});super({start:s=>{n(s)}});m(this,"modes");m(this,"controller");m(this,"passthroughFn");m(this,"_closed",!1);r.then(s=>{this.controller=s}),this.passthroughFn=e.passthroughFn,this.modes=e.modes}get closed(){return this._closed}push(e){var n;this._closed||!this.controller||((n=this.passthroughFn)==null||n.call(this,e),this.controller.enqueue(e))}close(){try{this.controller.close()}catch{}finally{this._closed=!0}}error(e){var n;try{(n=this.controller)==null||n.error(e)}finally{this._closed=!0}}},$H=class extends qs{constructor(e){super();m(this,"name","StreamToolsHandler");m(this,"awaitHandlers",!0);m(this,"streamFn");m(this,"runs",{});this.streamFn=e}handleToolStart(e,n,r,s,i,a,o,c){var d;if(!a||i&&i.includes("langsmith:hidden"))return;const u=((d=a.langgraph_checkpoint_ns)==null?void 0:d.split("|"))??[],l={ns:u,toolCallId:c,toolName:o??"unknown",input:n};this.runs[r]=l,this.streamFn([u,"tools",{event:"on_tool_start",toolCallId:l.toolCallId,name:l.toolName,input:n}])}handleToolEvent(e,n){const r=this.runs[n];r&&this.streamFn([r.ns,"tools",{event:"on_tool_event",toolCallId:r.toolCallId,name:r.toolName,data:e}])}handleToolEnd(e,n){const r=this.runs[n];delete this.runs[n],r&&this.streamFn([r.ns,"tools",{event:"on_tool_end",toolCallId:r.toolCallId,name:r.toolName,output:e}])}handleToolError(e,n){const r=this.runs[n];delete this.runs[n],r&&this.streamFn([r.ns,"tools",{event:"on_tool_error",toolCallId:r.toolCallId,name:r.toolName,error:e}])}};function RH(t){return JSON.stringify(t,function(e,n){const r=this[e];if(r!=null&&typeof r=="object"&&"toDict"in r&&typeof r.toDict=="function"){const{type:s,data:i}=r.toDict();return{...i,type:s}}return n})}function PH(t){return t instanceof Error?{error:t.name,message:t.message}:{error:"Error",message:JSON.stringify(t)}}function bw(t){return typeof t!="object"||t==null?!1:"configurable"in t&&typeof t.configurable=="object"&&t.configurable!=null}function im(t){return!bw(t)||!t.configurable.thread_id?null:{thread_id:t.configurable.thread_id,checkpoint_ns:t.configurable.checkpoint_ns||"",checkpoint_id:t.configurable.checkpoint_id||null,checkpoint_map:t.configurable.checkpoint_map||null}}function Zv(t){if(bw(t)){const e=Object.fromEntries(Object.entries(t.configurable).filter(([r])=>!r.startsWith("__"))),n={...t,configurable:e};return delete n.callbacks,n}return t}function qv(t){const e={...t,checkpoint:im(t.config),parent_checkpoint:im(t.parentConfig),config:Zv(t.config),parent_config:Zv(t.parentConfig),tasks:t.tasks.map(n=>{if(bw(n.state)){const r=im(n.state);if(r!=null){const s={...n,checkpoint:r};return delete s.state,s}}return n})};return delete e.parentConfig,e}function NH(t){const e=new TextEncoder;return new ReadableStream({async start(n){const r=s=>{n.enqueue(e.encode(`event: ${s.event}
|
|
308
|
-
data: ${RH(s.data)}
|
|
309
|
-
|
|
310
|
-
`))};try{for await(const s of t){const[i,a,o]=s;let c=o;if(a==="debug"){const u=o;u.type==="checkpoint"&&(c={...u,payload:qv(u.payload)})}a==="checkpoints"&&(c=qv(o)),r({event:i!=null&&i.length?`${a}|${i.join("|")}`:a,data:c})}}catch(s){r({event:"error",data:PH(s)})}n.close()}})}function MH(...t){return new eC({passthroughFn:e=>{const n=e[1]==="checkpoints"&&ww(e[2]);for(const r of t)(r.modes.has(e[1])||n)&&r.push(e)},modes:new Set(t.flatMap(e=>Array.from(e.modes)))})}var Yu,pf,tC,iT,LH=(iT=class{constructor(t){Ze(this,pf);m(this,"checkpointId");Ze(this,Yu,new Set);this.checkpointId=t}async getCheckpoint(t,e,n){if(ji(this,pf,tC).call(this,t)){const r=[];for await(const s of e.list(n,{before:{configurable:{checkpoint_id:this.checkpointId}},limit:1}))r.push(s);return r.length>0?r[0]:void 0}return await e.getTuple(n)??void 0}},Yu=new WeakMap,pf=new WeakSet,tC=function(t){const e=t.includes(":")?t.slice(0,t.lastIndexOf(":")):t;return ne(this,Yu).has(e)?!1:(ne(this,Yu).add(e),!0)},iT);const jH=/^(?:[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 Gv(t){return typeof t=="string"&&jH.test(t)}const an=[];for(let t=0;t<256;++t)an.push((t+256).toString(16).slice(1));function DH(t,e=0){return(an[t[e+0]]+an[t[e+1]]+an[t[e+2]]+an[t[e+3]]+"-"+an[t[e+4]]+an[t[e+5]]+"-"+an[t[e+6]]+an[t[e+7]]+"-"+an[t[e+8]]+an[t[e+9]]+"-"+an[t[e+10]]+an[t[e+11]]+an[t[e+12]]+an[t[e+13]]+an[t[e+14]]+an[t[e+15]]).toLowerCase()}const UH=new Uint8Array(16);function FH(){return crypto.getRandomValues(UH)}function h_(t,e,n){return crypto.randomUUID?crypto.randomUUID():BH(t)}function BH(t,e,n){var s;t=t||{};const r=t.random??((s=t.rng)==null?void 0:s.call(t))??FH();if(r.length<16)throw new Error("Random bytes length must be >= 16");return r[6]=r[6]&15|64,r[8]=r[8]&63|128,DH(r)}const hd=Symbol.for("INPUT_DONE"),am=Symbol.for("INPUT_RESUMING"),zH=25;function nC(t){if(!(t==null||typeof t!="object")){if(Ot.isInstance(t)){const e=t;e.id==null&&(e.id=h_(),e.lc_kwargs!=null&&(e.lc_kwargs.id=e.id));return}if(Array.isArray(t)){for(const e of t)nC(e);return}}}function rC(t){return t===void 0||t===""?[]:t.split("|")}function HH(t){if(!t)return[];let e="";for(const n of Object.keys(t))n!==""&&n.length>e.length&&(e=n);return rC(e)}var VH=class extends E9{constructor(e){super();m(this,"cache");m(this,"queue",Promise.resolve());this.cache=e}async get(e){return this.enqueueOperation("get",e)}async set(e){return this.enqueueOperation("set",e)}async clear(e){return this.enqueueOperation("clear",e)}async stop(){await this.queue}enqueueOperation(e,...n){const r=this.queue.then(()=>this.cache[e](...n));return this.queue=r.then(()=>{},()=>{}),r}},mf,sC,wo,KH=(wo=class{constructor(e){Ze(this,mf);m(this,"input");m(this,"output");m(this,"config");m(this,"checkpointer");m(this,"checkpointerGetNextVersion");m(this,"channels");m(this,"checkpoint");m(this,"checkpointIdSaved");m(this,"_exitDeltaWrites");m(this,"_hasPersistedParent",!1);m(this,"_initialCheckpointConfig");m(this,"checkpointConfig");m(this,"checkpointMetadata");m(this,"checkpointNamespace");m(this,"checkpointPendingWrites",[]);m(this,"checkpointPreviousVersions");m(this,"step");m(this,"stop");m(this,"durability");m(this,"outputKeys");m(this,"streamKeys");m(this,"nodes");m(this,"skipDoneTasks");m(this,"prevCheckpointConfig");m(this,"updatedChannels");m(this,"status","pending");m(this,"control");m(this,"tasks",{});m(this,"stream");m(this,"checkpointerPromises",new Set);m(this,"isNested");m(this,"resumeAtHead");m(this,"_checkpointerChainedPromise",Promise.resolve());m(this,"store");m(this,"cache");m(this,"manager");m(this,"interruptAfter");m(this,"interruptBefore");m(this,"toInterrupt",[]);m(this,"debug",!1);m(this,"triggerToNodes");this.input=e.input,this.checkpointer=e.checkpointer,this.checkpointer!==void 0?this.checkpointerGetNextVersion=this.checkpointer.getNextVersion.bind(this.checkpointer):this.checkpointerGetNextVersion=dH,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.resumeAtHead=e.resumeAtHead,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 VH(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,this.control=this.config.control,this._exitDeltaWrites=this.durability==="exit"&&this.checkpointer!=null?[]:void 0,this._hasPersistedParent=e.hasPersistedParent??!1,this._initialCheckpointConfig=e.checkpointConfig,this.checkpointIdSaved=e.checkpoint.id}_trackCheckpointerPromise(e){const n=e.then(r=>(this.checkpointerPromises.delete(n),r),r=>{throw r});this.checkpointerPromises.add(n)}get isResuming(){var o,c,u,l,d;let e=!1;if("__start__"in this.checkpoint.channel_versions)e=!0;else for(const f in this.checkpoint.channel_versions)if(Object.prototype.hasOwnProperty.call(this.checkpoint.channel_versions,f)){e=!0;break}const n=((o=this.config.configurable)==null?void 0:o.__pregel_resuming)!==void 0&&((c=this.config.configurable)==null?void 0:c.__pregel_resuming),r=this.input===null||this.input===void 0,s=Xt(this.input)&&this.input.resume!=null,i=this.input===am,a=!this.isNested&&((u=this.config.metadata)==null?void 0:u.run_id)!==void 0&&((l=this.checkpointMetadata)==null?void 0:l.run_id)!==void 0&&this.config.metadata.run_id===((d=this.checkpointMetadata)==null?void 0:d.run_id);return e&&(n||r||s||i||a)}get isReplaying(){return!this.skipDoneTasks}static async initialize(e){var k,C,D,B,z,q,W,me,M,Z,re,ae,X,se,Se,ue,I,T,L,O,ge;let{config:n,stream:r}=e;r!==void 0&&((k=n.configurable)==null?void 0:k.__pregel_stream)!==void 0&&(r=MH(r,n.configurable[My]));const s=n.configurable?!("checkpoint_id"in n.configurable):!0,i=(C=n.configurable)==null?void 0:C[Bs];n.configurable&&i&&(i.subgraphCounter>0&&(n=$n(n,{[us]:[n.configurable[us],i.subgraphCounter.toString()].join("|")})),i.subgraphCounter+=1);const a=(D=n.configurable)==null?void 0:D.checkpoint_id,o=Ai in(n.configurable??{});!o&&((B=n.configurable)==null?void 0:B.checkpoint_ns)!==void 0&&((z=n.configurable)==null?void 0:z.checkpoint_ns)!==""&&(n=$n(n,{checkpoint_ns:"",checkpoint_id:void 0}));let c=n;((q=n.configurable)==null?void 0:q.checkpoint_id)===void 0&&((W=n.configurable)==null?void 0:W.checkpoint_map)!==void 0&&((Z=(me=n.configurable)==null?void 0:me.checkpoint_map)!=null&&Z[(M=n.configurable)==null?void 0:M.checkpoint_ns])&&(c=$n(n,{checkpoint_id:n.configurable[sr][(re=n.configurable)==null?void 0:re.checkpoint_ns]}));const u=rC((ae=n.configurable)==null?void 0:ae.checkpoint_ns);let l;e.checkpointer?(X=c.configurable)!=null&&X.checkpoint_id?l=await e.checkpointer.getTuple(c):(se=n.configurable)!=null&&se.__pregel_replay_state?(l=await n.configurable[Lg].getCheckpoint(((Se=n.configurable)==null?void 0:Se.checkpoint_ns)??"",e.checkpointer,c),n.configurable&&delete n.configurable[uu]):l=await e.checkpointer.getTuple(c):l=void 0;const d=l!==void 0;l||(l={config:n,checkpoint:n_(),metadata:{source:"input",step:-2,parents:{}},pendingWrites:[]}),c={...n,...l.config,configurable:{checkpoint_ns:"",...n.configurable,...l.config.configurable}};const f=l.parentConfig,h=Kh(l.checkpoint),p={...l.metadata};let g=l.pendingWrites??[];const y=(ue=n.configurable)==null?void 0:ue.checkpoint_ns,b=(I=n.configurable)==null?void 0:I[sr];typeof y=="string"&&y!==""&&typeof b=="object"&&b!==null&&y in b&&g.length>0&&(g=g.filter(([,Ee])=>Ee!==ws));let _=!1;const w=(T=c.configurable)==null?void 0:T.thread_id,v=((L=c.configurable)==null?void 0:L.checkpoint_ns)??"";e.checkpointer&&a&&typeof w=="string"&&(_=((ge=(O=await e.checkpointer.getTuple({configurable:{thread_id:w,checkpoint_ns:v}}))==null?void 0:O.config.configurable)==null?void 0:ge.checkpoint_id)===a&&p.source!=="update"&&p.source!=="fork");const A=await s_(e.channelSpecs,h,{saver:e.checkpointer,config:c}),S=(p.step??0)+1,x=S+(n.recursionLimit??zH)+1,E={...h.channel_versions},$=e.store?new T9(e.store):void 0;return $&&await $.start(),new wo({input:e.input,config:n,checkpointer:e.checkpointer,checkpoint:h,checkpointMetadata:p,checkpointConfig:c,prevCheckpointConfig:f,checkpointNamespace:u,channels:A,isNested:o,resumeAtHead:_,manager:e.manager,skipDoneTasks:s,step:S,stop:x,checkpointPreviousVersions:E,checkpointPendingWrites:g,outputKeys:e.outputKeys??[],streamKeys:e.streamKeys??[],nodes:e.nodes,stream:r,store:$,cache:e.cache,interruptAfter:e.interruptAfter,interruptBefore:e.interruptBefore,durability:e.durability,debug:e.debug,triggerToNodes:e.triggerToNodes,hasPersistedParent:d})}_checkpointerPutAfterPrevious(e){this._checkpointerChainedPromise=this._checkpointerChainedPromise.then(()=>{var n;return(n=this.checkpointer)==null?void 0:n.put(e.config,e.checkpoint,e.metadata,e.newVersions)}),this._trackCheckpointerPromise(this._checkpointerChainedPromise)}putWrites(e,n){var c;let r=n;if(r.length===0)return;r.every(([u])=>u in b9)&&(r=Array.from(new Map(r.map(u=>[u[0],u])).values()));let s=!1;for(const u in this.channels)if(Object.prototype.hasOwnProperty.call(this.channels,u)&&this.channels[u].lc_graph_name==="UntrackedValue"){s=!0;break}let i=r;s&&(i=r.filter(([u])=>{const l=this.channels[u];return!l||l.lc_graph_name!=="UntrackedValue"}).map(([u,l])=>u==="__pregel_tasks"&&Wn(l)?[u,bH(l,this.channels)]:[u,l])),this.checkpointPendingWrites=this.checkpointPendingWrites.filter(u=>u[0]!==e);for(const[u,l]of i)this.checkpointPendingWrites.push([e,u,l]);for(const[u,l]of i){const d=this.channels[u];d!=null&&_i(d)&&nC(l)}const a=$n(this.checkpointConfig,{[us]:((c=this.config.configurable)==null?void 0:c.checkpoint_ns)??"",[Vi]:this.checkpoint.id});if(this.durability!=="exit"&&this.checkpointer!=null&&this._trackCheckpointerPromise(this.checkpointer.putWrites(a,i,e)),this.tasks&&this._outputWrites(e,r),!n.length||!this.cache||!this.tasks)return;const o=this.tasks[e];o==null||o.cache_key==null||n[0][0]==="__error__"||n[0][0]==="__interrupt__"||this.cache.set([{key:[o.cache_key.ns,o.cache_key.key],value:o.writes,ttl:o.cache_key.ttl}])}_outputWrites(e,n,r=!1){var i,a;const s=this.tasks[e];if(s!==void 0){if(s.config!==void 0&&(s.config.tags??[]).includes("langsmith:hidden"))return;if(n.length>0)if(n[0][0]==="__interrupt__"){if(((i=s.path)==null?void 0:i[0])==="__pregel_push"&&((a=s.path)==null?void 0:a[s.path.length-1])===!0)return;const o=n.filter(c=>c[0]===Nt).flatMap(c=>c[1]);this._emit([["updates",{[Nt]:o}],["values",{[Nt]:o}]])}else n[0][0]!=="__error__"&&this._emit(qa(Is(oH(this.outputKeys,[[s,n]],r),"updates")));r||this._emit(qa(Is(SH([[s,n]],this.streamKeys),"tasks")))}}async _matchCachedWrites(){if(!this.cache)return[];const e=[],n=([a,o])=>`ns:${a.join(",")}|key:${o}`,r=[],s={};for(const a of Object.values(this.tasks))a.cache_key!=null&&!a.writes.length&&(r.push([a.cache_key.ns,a.cache_key.key]),s[n([a.cache_key.ns,a.cache_key.key])]=a);if(r.length===0)return[];const i=await this.cache.get(r);for(const{key:a,value:o}of i){const c=s[n(a)];c!=null&&(c.writes.push(...o),e.push({task:c,result:o}))}return e}async tick(e){var s,i,a;this.store&&!this.store.isRunning&&await((s=this.store)==null?void 0:s.start());const{inputKeys:n=[]}=e;if(this.status!=="pending")throw new Error(`Cannot tick when status is no longer "pending". Current status: "${this.status}"`);if(![hd,am].includes(this.input))await this._first(n);else{if(this.toInterrupt.length>0)throw this.status="interrupt_before",new fo;if(Object.values(this.tasks).every(o=>o.writes.length>0)){const o=Object.values(this.tasks),c=o.flatMap(l=>l.writes);this.updatedChannels=nr(this.checkpoint,this.channels,o,this.checkpointerGetNextVersion,this.triggerToNodes);const u=await li(Is(nm(this.outputKeys,c,this.channels),"values"));if(this._exitDeltaWrites!==void 0)for(const[l,d,f]of this.checkpointPendingWrites){const h=this.channels[d];h!=null&&_i(h)&&this._exitDeltaWrites.push([this.step,l,d,f])}if(this.checkpointPendingWrites=[],await this._putCheckpoint({source:"loop"}),this._emitValuesWithCheckpointMeta(u),dd(this.checkpoint,this.interruptAfter,o))throw this.status="interrupt_after",new fo;((i=this.config.configurable)==null?void 0:i.__pregel_resuming)!==void 0&&((a=this.config.configurable)==null||delete a[uu])}else return!1}if(this.step>this.stop)return this.status="out_of_steps",!1;this.tasks=io(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});let r=Object.values(this.tasks);if(this.checkpointer&&(this.stream.modes.has("checkpoints")||this.stream.modes.has("debug"))&&this._emit(await li(Is(AH(this.checkpointConfig,this.channels,this.streamKeys,this.checkpointMetadata,r,this.checkpointPendingWrites,this.prevCheckpointConfig,this.outputKeys),"checkpoints"))),r.length===0)return this.status="done",!1;if(this.control!=null&&this.control.drainRequested)return this.status="draining",!1;if(this.skipDoneTasks&&this.checkpointPendingWrites.length>0){for(const[o,c,u]of this.checkpointPendingWrites){if(c==="__error__"||c==="__error_source_node__"||c==="__interrupt__"||c==="__resume__")continue;const l=r.find(d=>d.id===o);l&&l.writes.push([c,u])}this._resumeErrorHandlersIfApplicable(),r=Object.values(this.tasks);for(const o of r)o.writes.length>0&&this._outputWrites(o.id,o.writes,!0)}if(r.every(o=>o.writes.length>0))return this.tick({inputKeys:n});if(dd(this.checkpoint,this.interruptBefore,r))throw this.status="interrupt_before",new fo;if(this.stream.modes.has("tasks")||this.stream.modes.has("debug")){const o=await li(Is(rm(r),"tasks"));this._emit(o)}return!0}async finishAndHandleError(e){this.durability==="exit"&&(!this.isNested||typeof e<"u"||this.checkpointNamespace.every(r=>!r.includes(":")))&&(await this._putExitDeltaWrites(),this._putCheckpoint(this.checkpointMetadata),this._flushPendingWrites());const n=this._suppressInterrupt(e);return(n||e===void 0)&&(this.output=Sa(this.channels,this.outputKeys)),n&&(this.tasks!==void 0&&this.checkpointPendingWrites.length>0&&Object.values(this.tasks).some(r=>r.writes.length>0)&&(this.updatedChannels=nr(this.checkpoint,this.channels,Object.values(this.tasks),this.checkpointerGetNextVersion,this.triggerToNodes),this._emitValuesWithCheckpointMeta(qa(Is(nm(this.outputKeys,Object.values(this.tasks).flatMap(r=>r.writes),this.channels),"values")))),Xi(e)&&!e.interrupts.length&&this._emit([["updates",{[Nt]:[]}],["values",{[Nt]:[]}]],ji(this,mf,sC).call(this))),n}async acceptPush(e,n,r){var a,o;if(((a=this.interruptAfter)==null?void 0:a.length)>0&&dd(this.checkpoint,this.interruptAfter,[e])){this.toInterrupt.push(e);return}const s=l_([Tr,e.path??[],n,e.id,r],this.checkpoint,this.checkpointPendingWrites,this.nodes,this.channels,e.config??{},!0,{step:this.step,checkpointer:this.checkpointer,manager:this.manager,store:this.store,stream:this.stream});if(!s)return;if(((o=this.interruptBefore)==null?void 0:o.length)>0&&dd(this.checkpoint,this.interruptBefore,[s])){this.toInterrupt.push(s);return}(this.stream.modes.has("tasks")||this.stream.modes.has("debug"))&&this._emit(qa(Is(rm([s]),"tasks"))),this.debug&&d_(this.step,[s]),this.tasks[s.id]=s,this.skipDoneTasks&&this._matchWrites({[s.id]:s});const i=await this._matchCachedWrites();for(const{task:c}of i)this._outputWrites(c.id,c.writes,!0);return s}getErrorHandlerNode(e){var n;return(n=this.nodes[e])==null?void 0:n.errorHandlerNode}isErrorHandlerNode(e){var n;return((n=this.nodes[e])==null?void 0:n.isErrorHandler)===!0}scheduleErrorHandler(e,n){const r=this.getErrorHandlerNode(String(e.name));if(!r)return;const s=yH(e,r,n,this.checkpoint,this.checkpointPendingWrites,this.nodes,this.channels,e.config??this.config,{step:this.step,checkpointer:this.checkpointer,manager:this.manager,store:this.store,stream:this.stream});if(s!==void 0)return this.tasks[s.id]=s,this._emit(qa(Is(rm([s]),"tasks"))),this.debug&&d_(this.step,[s]),s}_resumeErrorHandlersIfApplicable(){const e=new Map;for(const[n,r]of this.checkpointPendingWrites){if(r!=="__error_source_node__")continue;const s=this.checkpointPendingWrites.find(([o,c])=>o===n&&c==="__error__");if(s===void 0)continue;const i=s[2],a=new Error((i==null?void 0:i.message)??String(i));i!=null&&i.name&&(a.name=i.name),e.set(n,a)}for(const[n,r]of e){const s=this.tasks[n];s!==void 0&&this.getErrorHandlerNode(String(s.name))&&(s.writes.length===0&&s.writes.push([bl,{message:r.message,name:r.name}]),this.scheduleErrorHandler(s,r))}}_suppressInterrupt(e){return Xi(e)&&!this.isNested}async _first(e){var u,l;const{configurable:n}=this.config,r=n==null?void 0:n[Bs];if(r&&r.nullResume!==void 0&&this.putWrites(Ar,[[ws,r.nullResume]]),Xt(this.input)){const d=this.input.resume!=null;if(this.input.resume!=null&&typeof this.input.resume=="object"&&Object.keys(this.input.resume).every(Jk)&&((u=this.config).configurable??(u.configurable={}),this.config.configurable[du]=this.input.resume),d&&this.checkpointer==null)throw new Error("Cannot use Command(resume=...) without checkpointer");const f={};for(const[h,p,g]of aH(this.input,this.checkpointPendingWrites))f[h]??(f[h]=[]),f[h].push([p,g]);if(Object.keys(f).length===0)throw new Iv("Received empty Command input");for(const[h,p]of Object.entries(f))this.putWrites(h,p)}const s=(this.checkpointPendingWrites??[]).filter(d=>d[0]===Ar).map(d=>d.slice(1));s.length>0&&nr(this.checkpoint,this.channels,[{name:ui,writes:s,triggers:[]}],this.checkpointerGetNextVersion,this.triggerToNodes);const i=Xt(this.input),a=i&&s.length>0,o=this.isReplaying&&(this.isNested&&(n==null?void 0:n.checkpoint_ns)!==void 0&&(n==null?void 0:n.checkpoint_ns)!==""&&(n==null?void 0:n.checkpoint_map)!==void 0&&n.checkpoint_ns in n.checkpoint_map||!(i&&this.input.resume!=null||(n==null?void 0:n.__pregel_resuming)===!0||this.resumeAtHead));o&&(this.checkpointPendingWrites=this.checkpointPendingWrites.filter(d=>d[1]!==ws));const c=this.isResuming;if(c||a){const d={...this.checkpoint.versions_seen[Nt]};for(const h in this.channels)Object.prototype.hasOwnProperty.call(this.channels,h)&&this.checkpoint.channel_versions[h]!==void 0&&(d[h]=this.checkpoint.channel_versions[h]);this.checkpoint.versions_seen[Nt]=d,o&&this.checkpointMetadata.source!=="update"&&this.checkpointMetadata.source!=="fork"&&(this.checkpointPendingWrites=this.checkpointPendingWrites.filter(h=>h[1]!==Nt),await this._putCheckpoint({source:"fork"}));const f=await li(Is(nm(this.outputKeys,!0,this.channels),"values"));c?this.input=am:a&&(await this._putCheckpoint({source:"input"}),this.input=hd),this._emitValuesWithCheckpointMeta(f)}else{const d=await li(Yk(e,this.input));if(d.length>0){const f=io(this.checkpoint,this.checkpointPendingWrites,this.nodes,this.channels,this.config,!0,{step:this.step});this.updatedChannels=nr(this.checkpoint,this.channels,Object.values(f).concat([{name:ui,writes:d,triggers:[]}]),this.checkpointerGetNextVersion,this.triggerToNodes);const h=d.filter(([p])=>{const g=this.channels[p];return g!=null&&_i(g)});if(h.length>0)if(this._exitDeltaWrites!==void 0)for(const[p,g]of h)this._exitDeltaWrites.push([this.step,Ar,p,g]);else this.checkpointer!=null&&this.putWrites(Ar,h);await this._putCheckpoint({source:"input"}),this.input=hd}else if("__pregel_resuming"in(this.config.configurable??{}))this.input=hd;else throw new Iv(`Received no input writes for ${JSON.stringify(e,null,2)}`)}if(!this.isNested){let d;if(o){let f=this.checkpoint.id;(this.checkpointMetadata.source==="update"||this.checkpointMetadata.source==="fork")&&this.prevCheckpointConfig&&(f=((l=this.prevCheckpointConfig.configurable)==null?void 0:l.checkpoint_id)??f),d=new LH(f)}this.config=$n(this.config,{[uu]:this.isResuming,[Lg]:d})}}_emit(e,n=this.checkpointNamespace){for(const[r,s]of e)if(this.stream.modes.has(r)&&this.stream.push([n,r,s]),(r==="checkpoints"||r==="tasks")&&this.stream.modes.has("debug")){const i=r==="checkpoints"?this.step-1:this.step,a=new Date().toISOString(),o=r==="checkpoints"?"checkpoint":typeof s=="object"&&s!=null&&"result"in s?"task_result":"task";this.stream.push([n,"debug",{step:i,type:o,timestamp:a,payload:s}])}}_currentCheckpointMeta(){var n,r,s;if(!this.checkpointMetadata||!((n=this.checkpoint)!=null&&n.id))return;const e=(s=(r=this.prevCheckpointConfig)==null?void 0:r.configurable)==null?void 0:s.checkpoint_id;return{checkpoint:{id:this.checkpoint.id,...e?{parent_id:e}:{},step:this.checkpointMetadata.step,source:this.checkpointMetadata.source}}}_emitValuesWithCheckpointMeta(e){const n=this._currentCheckpointMeta();for(const[r,s]of e)r==="values"&&(n==null?void 0:n.checkpoint)!=null&&!this.stream.modes.has("checkpoints")&&this.stream.push([this.checkpointNamespace,"checkpoints",n.checkpoint]),this.stream.modes.has(r)&&this.stream.push([this.checkpointNamespace,r,s])}_putCheckpoint(e){var c;const n=this.checkpointMetadata===e,r=this.checkpointer!=null&&(this.durability!=="exit"||n),s=u=>{var f,h,p;this.prevCheckpointConfig=(h=(f=this.checkpointConfig)==null?void 0:f.configurable)!=null&&h.checkpoint_id?this.checkpointConfig:void 0,this.checkpointConfig=$n(this.checkpointConfig,{[us]:((p=this.config.configurable)==null?void 0:p.checkpoint_ns)??""});const l={...this.checkpoint.channel_versions},d=Jd(this.checkpointPreviousVersions,l);this.checkpointPreviousVersions=l,this._checkpointerPutAfterPrevious({config:{...this.checkpointConfig},checkpoint:Kh(u),metadata:{...this.checkpointMetadata},newVersions:d}),this.checkpointConfig={...this.checkpointConfig,configurable:{...this.checkpointConfig.configurable,checkpoint_id:this.checkpoint.id}}};let i;if(n)i={...this.checkpointMetadata.counters_since_delta_snapshot??{}};else{const u=this.checkpointMetadata.counters_since_delta_snapshot??{};i={};const l=this.updatedChannels??new Set;for(const d in this.channels){if(!Object.prototype.hasOwnProperty.call(this.channels,d)||!_i(this.channels[d]))continue;const[f,h]=u[d]??[0,0];i[d]=[l.has(d)?f+1:f,h+1]}this.checkpointMetadata={...e,step:this.step,parents:((c=this.config.configurable)==null?void 0:c.checkpoint_map)??{}}}const a=r?Hv(this.channels,i):new Set;this.checkpoint=Gi(this.checkpoint,r?this.channels:void 0,this.step,{id:n?this.checkpoint.id:void 0,channelsToSnapshot:a,updatedChannels:this.updatedChannels,getNextVersion:r?u=>this.checkpointerGetNextVersion(u):void 0});for(const u of a)i[u]=[0,0];const o={};for(const u in i){if(!Object.prototype.hasOwnProperty.call(i,u))continue;const[l,d]=i[u];(l!==0||d!==0)&&(o[u]=[l,d])}Object.keys(o).length>0?this.checkpointMetadata.counters_since_delta_snapshot=o:delete this.checkpointMetadata.counters_since_delta_snapshot,r&&s(this.checkpoint),n||(this.step+=1)}async _putExitDeltaWrites(){var c,u;if(this._exitDeltaWrites===void 0||this._exitDeltaWrites.length===0||this.checkpointer==null||this._initialCheckpointConfig===void 0)return;const e=this.checkpointMetadata.counters_since_delta_snapshot??{},n=Hv(this.channels,e),r=this._exitDeltaWrites.filter(([,,l])=>!n.has(l));if(r.length===0)return;let s;if(this._hasPersistedParent)s=this._initialCheckpointConfig;else{const l=n_();l.id=this.checkpointIdSaved??l.id,l.ts=new Date().toISOString();const d=$n(this._initialCheckpointConfig,{[Vi]:void 0});s=$n(this._initialCheckpointConfig,{[Vi]:l.id}),this._trackCheckpointerPromise(this.checkpointer.put(d,l,{source:"loop",step:-2,parents:{}},{})),this.checkpointConfig=s}const i=$n(s,{[us]:((c=this.config.configurable)==null?void 0:c.checkpoint_ns)??"",[Vi]:(u=s.configurable)==null?void 0:u[Vi]}),a=new Map,o=[];for(const[l,d,f,h]of r){const p=`${l}\0${d}`;let g=a.get(p);g===void 0&&(g=[],a.set(p,g),o.push({key:p,step:l,tid:d})),g.push([f,h])}for(const{key:l,step:d,tid:f}of o){const h=`${String(d).padStart(8,"0")}-${f}`;this._trackCheckpointerPromise(this.checkpointer.putWrites(i,a.get(l),h))}}_flushPendingWrites(){var r;if(this.checkpointer==null||this.checkpointPendingWrites.length===0)return;const e=$n(this.checkpointConfig,{[us]:((r=this.config.configurable)==null?void 0:r.checkpoint_ns)??"",[Vi]:this.checkpoint.id}),n={};for(const[s,i,a]of this.checkpointPendingWrites)n[s]??(n[s]=[]),n[s].push([i,a]);for(const[s,i]of Object.entries(n))this._trackCheckpointerPromise(this.checkpointer.putWrites(e,i,s))}_matchWrites(e){for(const[n,r,s]of this.checkpointPendingWrites){if(r==="__error__"||r==="__interrupt__"||r==="__resume__")continue;const i=Object.values(e).find(a=>a.id===n);i&&i.writes.push([r,s])}for(const n of Object.values(e))n.writes.length>0&&this._outputWrites(n.id,n.writes,!0)}},mf=new WeakSet,sC=function(){var r,s;const e=this.checkpointNamespace;if(!(e.length===0||e.length===1&&e[0]==="")||((r=this.config.configurable)==null?void 0:r.__pregel_stream)===void 0)return e;const n=HH((s=this.config.configurable)==null?void 0:s[sr]);return n.length>0?n:e},wo);function WH(t){return Et(t==null?void 0:t.message)}function Jv(t,e,n){if(!t)return;const r=t.langgraph_checkpoint_ns,s=t.checkpoint_ns,i=r??s;if(i)return[i.split("|"),{tags:e,name:n,...t}]}var ZH=class extends qs{constructor(e){super();m(this,"name","StreamMessagesHandler");m(this,"streamFn");m(this,"metadatas",{});m(this,"seen",{});m(this,"emittedChatModelRunIds",{});m(this,"stableMessageIdMap",{});m(this,"lc_prefer_streaming",!0);this.streamFn=e}_emit(e,n,r,s=!1){var a;if(s&&n.id!==void 0&&this.seen[n.id]!==void 0)return;let i=n.id;r!=null&&(ca(n)?i??(i=`run-${r}-tool-${n.tool_call_id}`):((i==null||i===`run-${r}`)&&(i=this.stableMessageIdMap[r]??i??`run-${r}`),(a=this.stableMessageIdMap)[r]??(a[r]=i))),i!==n.id&&(n.id=i,n.lc_kwargs.id=i),n.id!=null&&(this.seen[n.id]=n),this.streamFn([e[0],"messages",[n,e[1]]])}handleChatModelStart(e,n,r,s,i,a,o,c){o&&(!a||!a.includes("langsmith:nostream")&&!a.includes("nostream"))&&(this.metadatas[r]=Jv(o,a,c))}handleLLMNewToken(e,n,r,s,i,a){const o=a==null?void 0:a.chunk;this.emittedChatModelRunIds[r]=!0,this.metadatas[r]!==void 0&&(WH(o)?this._emit(this.metadatas[r],o.message,r):this._emit(this.metadatas[r],new Ge({content:e}),r))}handleLLMEnd(e,n){var r,s;if(this.metadatas[n]!==void 0){if(!this.emittedChatModelRunIds[n]){const i=(s=(r=e.generations)==null?void 0:r[0])==null?void 0:s[0];Et(i==null?void 0:i.message)&&this._emit(this.metadatas[n],i==null?void 0:i.message,n,!0),delete this.emittedChatModelRunIds[n]}delete this.metadatas[n],delete this.stableMessageIdMap[n]}}handleLLMError(e,n){delete this.metadatas[n]}handleChainStart(e,n,r,s,i,a,o,c){if(a!==void 0&&c===a.langgraph_node&&(i===void 0||!i.includes("langsmith:hidden"))&&(this.metadatas[r]=Jv(a,i,c),typeof n=="object")){for(const u of Object.values(n))if((Et(u)||Po(u))&&u.id!==void 0)this.seen[u.id]=u;else if(Array.isArray(u))for(const l of u)(Et(l)||Po(l))&&l.id!==void 0&&(this.seen[l.id]=l)}}handleChainEnd(e,n){const r=this.metadatas[n];if(delete this.metadatas[n],r!==void 0){if(Et(e))this._emit(r,e,n,!0);else if(Array.isArray(e))for(const s of e)Et(s)&&this._emit(r,s,n,!0);else if(e!=null&&typeof e=="object"){for(const s of Object.values(e))if(Et(s))this._emit(r,s,n,!0);else if(Array.isArray(s))for(const i of s)Et(i)&&this._emit(r,i,n,!0)}}}handleChainError(e,n){delete this.metadatas[n]}};function Yv(t){if("response_metadata"in t&&typeof t.response_metadata=="object"&&t.response_metadata!=null)return t.response_metadata}function Xv(t){if("usage_metadata"in t&&typeof t.usage_metadata=="object"&&t.usage_metadata!=null)return t.usage_metadata}function qH(t){switch(t.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",...t.id!=null?{id:t.id}:{},...t.name!=null?{name:t.name}:{},args:""};default:return t}}function GH(t){switch(t.type){case"text":{const e=typeof t.text=="string"?t.text:"";return e.length>0?{event:"content-block-delta",index:typeof t.index=="number"?t.index:0,delta:{type:"text-delta",text:e}}:void 0}case"reasoning":{const e=typeof t.reasoning=="string"?t.reasoning:"";return e.length>0?{event:"content-block-delta",index:typeof t.index=="number"?t.index:0,delta:{type:"reasoning-delta",reasoning:e}}:void 0}case"tool_call_chunk":return{event:"content-block-delta",index:typeof t.index=="number"?t.index:0,delta:{type:"block-delta",fields:{...t,type:"tool_call_chunk"}}};default:return}}var JH=class extends qs{constructor(e){super();m(this,"name","StreamProtocolMessagesHandler");m(this,"streamFn");m(this,"metadatas",{});m(this,"seen",{});m(this,"streamedRunIds",new Set);m(this,"stableMessageIdMap",{});m(this,"lc_prefer_chat_model_stream_events",!0);this.streamFn=e}normalizeMessageId(e,n){var s;let r=e.id;return n!=null&&(fn.isInstance(e)?r??(r=`run-${n}-tool-${e.tool_call_id}`):((r==null||r===`run-${n}`)&&(r=this.stableMessageIdMap[n]??r??`run-${n}`),(s=this.stableMessageIdMap)[n]??(s[n]=r))),r!==e.id&&(e.id=r,e.lc_kwargs.id=r),e.id!=null&&(this.seen[e.id]=e),e.id}emit(e,n,r){const s=r!=null?{...e[1],run_id:r}:e[1];this.streamFn([e[0],"messages",[n,s]])}emitFinalMessage(e,n,r,s=!1){const i=n.id??(r!=null?this.stableMessageIdMap[r]:void 0);if(s&&i!=null&&this.seen[i]!==void 0)return;const a=this.normalizeMessageId(n,r),o=n.type==="human"?"human":n.type==="system"?"system":n.type==="tool"?"tool":"ai",c=o==="tool"&&fn.isInstance(n)?n.tool_call_id:void 0;this.emit(e,{event:"message-start",...a!=null?{id:a}:{},...o!=="ai"?{role:o}:{},...typeof c=="string"?{tool_call_id:c}:{}},r),(Array.isArray(n.content)?n.content:typeof n.content=="string"&&n.content.length>0?[{type:"text",text:n.content}]:[]).forEach((u,l)=>{const d=typeof u.index=="number"?u.index:l;this.emit(e,{event:"content-block-start",index:d,content:qH(u)},r);const f=GH({...u,index:d});f!=null&&this.emit(e,f,r),this.emit(e,{event:"content-block-finish",index:d,content:u},r)}),this.emit(e,{event:"message-finish",...Xv(n)!=null?{usage:Xv(n)}:{},...Yv(n)!=null?{responseMetadata:Yv(n)}:{}},r)}handleChatModelStart(e,n,r,s,i,a,o,c){o&&(!a||!a.includes("langsmith:nostream")&&!a.includes("nostream"))&&(this.metadatas[r]=[o.langgraph_checkpoint_ns.split("|"),{tags:a,name:c,...o}])}handleLLMNewToken(){}handleChatModelStreamEvent(e,n){var i;const r=this.metadatas[n];if(r===void 0)return;let s=e;if(e.event==="message-start"){this.streamedRunIds.add(n);const a=e.id??`run-${n}`;this.seen[a]=!0,(i=this.stableMessageIdMap)[n]??(i[n]=a),e.id==null&&(s={...e,id:a})}this.emit(r,s,n)}handleLLMEnd(e,n){var a,o;const r=this.metadatas[n];if(r===void 0)return;const s=(o=(a=e.generations)==null?void 0:a[0])==null?void 0:o[0],i=Ot.isInstance(s==null?void 0:s.message)?s.message:void 0;if(i!=null)if(this.streamedRunIds.has(n)){const c=this.normalizeMessageId(i,n);c!=null&&(this.seen[c]=i)}else this.emitFinalMessage(r,i,n,!0);this.streamedRunIds.delete(n),delete this.metadatas[n],delete this.stableMessageIdMap[n]}handleLLMError(e,n){this.streamedRunIds.delete(n),delete this.metadatas[n],delete this.stableMessageIdMap[n]}handleChainStart(e,n,r,s,i,a,o,c){if(a!==void 0&&c===a.langgraph_node&&(i===void 0||!i.includes("langsmith:hidden"))&&(this.metadatas[r]=[a.langgraph_checkpoint_ns.split("|"),{tags:i,name:c,...a}],typeof n=="object")){for(const u of Object.values(n))if((Ot.isInstance(u)||vs.isInstance(u))&&u.id!==void 0)this.seen[u.id]=u;else if(Array.isArray(u))for(const l of u)(Ot.isInstance(l)||vs.isInstance(l))&&l.id!==void 0&&(this.seen[l.id]=l)}}handleChainEnd(e,n){const r=this.metadatas[n];if(delete this.metadatas[n],r===void 0)return;const s=i=>{Ot.isInstance(i)&&!fn.isInstance(i)&&this.emitFinalMessage(r,i,n,!0)};if(Ot.isInstance(e))s(e);else if(Array.isArray(e))for(const i of e)s(i);else if(e!=null&&typeof e=="object")for(const i of Object.values(e))if(Array.isArray(i))for(const a of i)s(a);else s(i);delete this.stableMessageIdMap[n]}handleChainError(e,n){delete this.metadatas[n],delete this.stableMessageIdMap[n]}},YH=class{constructor(t){m(this,"active",!0);m(this,"lastProgress",Date.now());m(this,"refreshOn");this.refreshOn=t}touch(){this.lastProgress=Date.now()}autoTouch(){this.refreshOn==="auto"&&(this.lastProgress=Date.now())}close(){this.active=!1}},Xu,Vt,aT,XH=(aT=class extends qs{constructor(e){super();m(this,"name","IdleProgressCallbackHandler");m(this,"awaitHandlers",!1);Ze(this,Xu);Ze(this,Vt,()=>{ne(this,Xu).autoTouch()});m(this,"handleLLMStart",ne(this,Vt));m(this,"handleChatModelStart",ne(this,Vt));m(this,"handleLLMNewToken",ne(this,Vt));m(this,"handleLLMEnd",ne(this,Vt));m(this,"handleLLMError",ne(this,Vt));m(this,"handleChainStart",ne(this,Vt));m(this,"handleChainEnd",ne(this,Vt));m(this,"handleChainError",ne(this,Vt));m(this,"handleToolStart",ne(this,Vt));m(this,"handleToolEnd",ne(this,Vt));m(this,"handleToolError",ne(this,Vt));m(this,"handleText",ne(this,Vt));m(this,"handleRetrieverStart",ne(this,Vt));m(this,"handleRetrieverEnd",ne(this,Vt));m(this,"handleRetrieverError",ne(this,Vt));m(this,"handleCustomEvent",ne(this,Vt));ct(this,Xu,e)}},Xu=new WeakMap,Vt=new WeakMap,aT);function QH(t,e,n,r){const s=t.configurable??{},i={},a=s[Jr];typeof a=="function"&&(i[Jr]=u=>{if(e.active)return u&&u.length&&e.autoTouch(),a(u)});const o=s[Ho];typeof o=="function"&&(i[Ho]=(...u)=>{if(!e.active)throw new Error(`Node "${r}" attempt was cancelled after its timeout fired`);return e.autoTouch(),o(...u)});const c={...Object.keys(i).length>0?$n(t,i):t};if(c.heartbeat=()=>{n.idleTimeout!==void 0&&e.touch()},typeof c.writer=="function"){const u=c.writer;c.writer=l=>{if(e.active)return e.autoTouch(),u(l)}}if((n.refreshOn??"auto")==="auto"&&n.idleTimeout!==void 0){const u=new XH(e),l=c.callbacks;if(l===void 0)c.callbacks=[u];else if(Array.isArray(l))c.callbacks=[...l,u];else{const d=l.copy();d.addHandler(u,!0),c.callbacks=d}}return c}async function eV(t,e,n,r){const s=new YH(n.refreshOn??"auto"),i=new AbortController,{signal:a,dispose:o}=Bu(e.signal,i.signal),c=QH({...e,signal:a},s,n,String(t.name)),u=Date.now(),l=r(c).then(b=>({type:"ok",value:b}),b=>({type:"err",error:b}));let d,f;const h=()=>{d!==void 0&&clearTimeout(d),f!==void 0&&clearTimeout(f)},p=new Promise(b=>{if(n.runTimeout!==void 0&&(d=setTimeout(()=>b({type:"timeout",kind:"run"}),n.runTimeout)),n.idleTimeout!==void 0){const _=n.idleTimeout,w=()=>{const v=s.lastProgress+_-Date.now();v<=0?b({type:"timeout",kind:"idle"}):f=setTimeout(w,v)};f=setTimeout(w,_)}});let g;try{g=await Promise.race([l,p])}finally{h()}if(g.type!=="timeout"){const b=Date.now();n.runTimeout!==void 0&&b-u>=n.runTimeout?g={type:"timeout",kind:"run"}:n.idleTimeout!==void 0&&b-s.lastProgress>=n.idleTimeout&&(g={type:"timeout",kind:"idle"})}if(g.type==="ok")return o==null||o(),g.value;if(g.type==="err")throw o==null||o(),g.error;const y=Date.now()-u;throw s.close(),t.writes.splice(0,t.writes.length),i.abort(),o==null||o(),new aB({node:String(t.name),elapsed:y,kind:g.kind,runTimeout:n.runTimeout,idleTimeout:n.idleTimeout})}const tV=[400,401,402,403,404,405,406,407,409],nV=t=>{var n,r;if(t.message.startsWith("Cancel")||t.message.startsWith("AbortError")||t.name==="AbortError"||t.name==="GraphValueError"||(t==null?void 0:t.code)==="ECONNABORTED")return!1;const e=((n=t==null?void 0:t.response)==null?void 0:n.status)??(t==null?void 0:t.status);return!(e&&tV.includes(+e)||((r=t==null?void 0:t.error)==null?void 0:r.code)==="insufficient_quota")};async function f_(t,e,n,r){var l;const s=t.retry_policy??e;let i=0,a,o,c=t.config??{};n&&(c=$n(c,n)),c={...c,signal:r};const u=Date.now();for(c.executionInfo!=null&&(c.executionInfo={...c.executionInfo,nodeFirstAttemptTime:u});!(r!=null&&r.aborted);){t.writes.splice(0,t.writes.length),a=void 0;try{t.timeout!==void 0?o=await eV(t,c,t.timeout,d=>t.proc.invoke(t.input,d)):o=await t.proc.invoke(t.input,c);break}catch(d){if(a=d,a.pregelTaskId=t.id,iB(a)){const y=(l=c==null?void 0:c.configurable)==null?void 0:l.checkpoint_ns,b=a.command;if(b.graph===y){for(const _ of t.writers)await _.invoke(b,c);a=void 0;break}else if(b.graph===ar.PARENT){const _=N9(y);a.command=new ar({...a.command,graph:_})}}if(Dc(a)||s===void 0||(i+=1,i>=(s.maxAttempts??3))||!(s.retryOn??nV)(a))break;const f=s.initialInterval??500,h=Math.min(s.maxInterval??128e3,f*(s.backoffFactor??2)**(i-1)),p=s.jitter??!0?h+Math.random()*1e3:h;await new Promise(y=>setTimeout(y,p));const g=a.name??a.constructor.unminifiable_name??a.constructor.name;((s==null?void 0:s.logWarning)??!0)&&console.log(`Retrying task "${String(t.name)}" after ${p.toFixed(2)}ms (attempt ${i}) after ${g}: ${a}`),c=$n(c,{[uu]:!0}),c.executionInfo!=null&&(c.executionInfo={...c.executionInfo,nodeAttempt:i+1,nodeFirstAttemptTime:u})}}return{task:t,result:o,error:a,signalAborted:r==null?void 0:r.aborted}}const p_=Symbol.for("promiseAdded");function rV(){const t={next:()=>{},wait:Promise.resolve(p_)};function e(n){t.next=()=>{t.wait=new Promise(e),n(p_)}}return t.wait=new Promise(e),t}var sV=class{constructor({loop:t,nodeFinished:e}){m(this,"nodeFinished");m(this,"loop");m(this,"handledExceptions",new WeakSet);this.loop=t,this.nodeFinished=e}async tick(t={}){const{timeout:e,retryPolicy:n,onStepWrite:r,maxConcurrency:s}=t,i=new Set;let a;const o=new AbortController,c=o.signal,u=e?AbortSignal.timeout(e):void 0,l=Object.values(this.loop.tasks),d=l.filter(g=>g.writes.length===0),{signals:f,disposeCombinedSignal:h}=this._initializeAbortSignals({exceptionSignal:c,stepTimeoutSignal:u,signal:t.signal}),p=this._executeTasksWithRetry(d,{signals:f,retryPolicy:n,maxConcurrency:s});for await(const{task:g,error:y,signalAborted:b}of p)this._commit(g,y),!(y!==void 0&&this.handledExceptions.has(y))&&(Xi(y)||Dc(y)&&!Xi(a)?a=y:y&&(i.size===0||!b)&&(o.abort(),i.add(y)));if(h==null||h(),r==null||r(this.loop.step,l.map(g=>g.writes).flat()),i.size===1)throw Array.from(i)[0];if(i.size>1)throw new AggregateError(Array.from(i),`Multiple errors occurred during superstep ${this.loop.step}. See the "errors" field of this exception for more details.`);if(Xi(a)||Ev(a)||Dc(a)&&this.loop.isNested)throw a}_initializeAbortSignals({exceptionSignal:t,stepTimeoutSignal:e,signal:n}){var u;const r=((u=this.loop.config.configurable)==null?void 0:u.__pregel_abort_signals)??{},s=r.externalAbortSignal??n,i=e??r.timeoutAbortSignal,{signal:a,dispose:o}=Bu(s,i,t),c={externalAbortSignal:s,timeoutAbortSignal:i,composedAbortSignal:a};return this.loop.config=$n(this.loop.config,{[X6]:c}),{signals:c,disposeCombinedSignal:o}}async*_executeTasksWithRetry(t,e){var f,h,p;const{retryPolicy:n,maxConcurrency:r,signals:s}=e??{},i=rV(),a={},o={executingTasksMap:a,barrier:i,retryPolicy:n,scheduleTask:async(g,y,b)=>this.loop.acceptPush(g,y,b)};if((f=s==null?void 0:s.composedAbortSignal)!=null&&f.aborted)throw new Error("Abort");let c=0,u;const l=Bu(s==null?void 0:s.externalAbortSignal,s==null?void 0:s.timeoutAbortSignal),d=l.signal?new Promise((g,y)=>{var b;u=()=>y(new Error("Abort")),(b=l.signal)==null||b.addEventListener("abort",u,{once:!0})}):void 0;for(;(c===0||Object.keys(a).length>0)&&t.length;){for(;Object.values(a).length<(r??t.length)&&c<t.length;c+=1){const w=t[c];a[w.id]=f_(w,n,{[Ho]:Ki==null?void 0:Ki.bind(o,this,w)},s==null?void 0:s.composedAbortSignal).catch(v=>{var A;return{task:w,error:v,signalAborted:(A=s==null?void 0:s.composedAbortSignal)==null?void 0:A.aborted}})}const g=await Promise.race([...Object.values(a),...d?[d]:[],i.wait]);if(g===p_)continue;const y=g,{task:b,error:_}=y;if(_!==void 0&&!Dc(_)&&!this.loop.isErrorHandlerNode(String(b.name))&&this.loop.getErrorHandlerNode(String(b.name))!==void 0){const w=this.loop.scheduleErrorHandler(b,_);w!==void 0&&(a[w.id]=f_(w,n,{[Ho]:Ki==null?void 0:Ki.bind(o,this,w)},s==null?void 0:s.composedAbortSignal).catch(v=>{var A;return{task:w,error:v,signalAborted:(A=s==null?void 0:s.composedAbortSignal)==null?void 0:A.aborted}}),i.next())}yield y,u!=null&&((h=l.signal)==null||h.removeEventListener("abort",u),(p=l.dispose)==null||p.call(l)),delete a[g.task.id]}}_shouldRouteToErrorHandler(t){const e=String(t.name);return this.loop.isErrorHandlerNode(e)?!1:this.loop.getErrorHandlerNode(e)!==void 0}_commit(t,e){var n;if(e!==void 0)if(Xi(e)){if(e.interrupts.length){const r=e.interrupts.map(i=>[Nt,i]),s=t.writes.filter(i=>i[0]===ws);s.length&&r.push(...s),this.loop.putWrites(t.id,r)}}else Ev(e)?t.writes.length&&this.loop.putWrites(t.id,t.writes):Dc(e)&&t.writes.length?this.loop.putWrites(t.id,t.writes):(t.writes.push([bl,{message:e.message,name:e.name}]),this._shouldRouteToErrorHandler(t)&&(t.writes.push([Ny,String(t.name)]),this.handledExceptions.add(e)),this.loop.putWrites(t.id,t.writes));else this.nodeFinished&&(((n=t.config)==null?void 0:n.tags)==null||!t.config.tags.includes("langsmith:hidden"))&&this.nodeFinished(String(t.name)),t.writes.length===0&&t.writes.push([Ly,null]),this.loop.putWrites(t.id,t.writes)}};async function Ki(t,e,n,r,s,i={}){var d,f;const a=(f=(d=e.config)==null?void 0:d.configurable)==null?void 0:f[Bs];if(!a)throw new Error(`BUG: No scratchpad found on task ${e.name}__${e.id}`);const o=a.callCounter;a.callCounter+=1;const c=new cH({func:n,name:r,input:s,cache:i.cache,retry:i.retry,timeout:i.timeout,callbacks:i.callbacks}),u=await this.scheduleTask(e,o,c);if(!u)return;const l=this.executingTasksMap[u.id];if(l!==void 0)return l;if(u.writes.length>0){const h=u.writes.filter(([g])=>g===$f),p=u.writes.filter(([g])=>g===bl);if(h.length>0){if(h.length===1)return Promise.resolve(h[0][1]);throw new Error(`BUG: multiple returns found for task ${u.name}__${u.id}`)}if(p.length>0){if(p.length===1){const g=p[0][1],y=g instanceof Error?g:new Error(String(g));return Promise.reject(y)}throw new Error(`BUG: multiple errors found for task ${u.name}__${u.id}`)}return}else{const h=f_(u,i.retry,{[Ho]:Ki.bind(this,t,u)});return this.executingTasksMap[u.id]=h,this.barrier.next(),h.then(({result:p,error:g})=>g?Promise.reject(g):p)}}const om=Symbol.for("langgraph.stream_channel");var oT,cs,Qu,ra,bo,el,vo,eh,ga,Aa=(ga=class{constructor(e){Ze(this,vo);m(this,oT,!0);m(this,"channelName");Ze(this,cs,[]);Ze(this,Qu,[]);Ze(this,ra,!1);Ze(this,bo);Ze(this,el);this.channelName=e}static local(){return new ga}static remote(e){return new ga(e)}static isInstance(e){return typeof e=="object"&&e!==null&&om in e&&e[om]===!0}push(e){var n;ne(this,cs).push(e),ji(this,vo,eh).call(this),(n=ne(this,el))==null||n.call(this,e)}iterate(e=0){let n=e;return{next:async()=>{for(;;){if(n<ne(this,cs).length)return{value:ne(this,cs)[n++],done:!1};if(ne(this,ra)){if(ne(this,bo))throw ne(this,bo);return{value:void 0,done:!0}}await new Promise(r=>ne(this,Qu).push(r))}}}}toAsyncIterable(e=0){return{[Symbol.asyncIterator]:()=>this.iterate(e)}}toEventStream(e={}){const n=new TextEncoder,r=this.iterate(e.startAt),s=e.event??this.channelName,i=e.serialize??(a=>JSON.stringify(a)??"null");return new ReadableStream({async pull(a){try{const o=await r.next();if(o.done){a.close();return}const c=[];s!=null&&c.push(`event: ${s}`);for(const u of i(o.value).split(/\r\n|\r|\n/))c.push(`data: ${u}`);a.enqueue(n.encode(`${c.join(`
|
|
311
|
-
`)}
|
|
312
|
-
|
|
313
|
-
`))}catch(o){a.error(o)}},async cancel(){var a;await((a=r.return)==null?void 0:a.call(r))}})}get(e){if(e<0||e>=ne(this,cs).length)throw new RangeError(`StreamChannel index ${e} out of bounds (size=${ne(this,cs).length})`);return ne(this,cs)[e]}get size(){return ne(this,cs).length}get done(){return ne(this,ra)}close(){ct(this,ra,!0),ji(this,vo,eh).call(this)}fail(e){ct(this,bo,e),ct(this,ra,!0),ji(this,vo,eh).call(this)}_wire(e){ct(this,el,e)}_close(){this.close()}_fail(e){this.fail(e)}[(oT=om,Symbol.asyncIterator)](){return this.iterate()}},cs=new WeakMap,Qu=new WeakMap,ra=new WeakMap,bo=new WeakMap,el=new WeakMap,vo=new WeakSet,eh=function(){const e=ne(this,Qu).splice(0);for(const n of e)n()},ga);function iV(t){return Aa.isInstance(t)}const aV="custom:";function oV(t){return`${aV}${t}`}function cV(t){return t!=null&&(typeof t=="object"||typeof t=="function")&&typeof t.then=="function"}const m_=Symbol("resolveValues"),iC=Symbol("rejectValues");var So,Ao,To,tl,sa,ia,Eo,aa,nl,rl,sl,cT,uV=(cT=class{constructor(){m(this,"_events",Aa.local());m(this,"_discoveries",Aa.local());Ze(this,So,0);Ze(this,Ao,!1);Ze(this,To);Ze(this,tl,!1);Ze(this,sa,[]);Ze(this,ia,[]);Ze(this,Eo,[]);Ze(this,aa,new Map);Ze(this,nl,new Map);Ze(this,rl,[]);Ze(this,sl,[])}register(t,e){ne(this,aa).set(Dn(t),e)}addTransformer(t){var n,r;const e=this._events.size;ne(this,ia).push(t),t.onRegister&&t.onRegister({push:(s,i)=>this.push(s,i)});for(let s=0;s<e;s+=1)t.process(this._events.get(s));ne(this,Ao)&&(ne(this,To)!==void 0?(n=t.fail)==null||n.call(t,ne(this,To)):(r=t.finalize)==null||r.call(t))}wireChannels(t){for(const[e,n]of Object.entries(t)){if(iV(n)){if(ne(this,Eo).push(n),typeof n.channelName!="string")continue;const r=oV(n.channelName);n._wire(s=>{this._events.push({type:"event",seq:Bl(this,So)._++,method:r,params:{namespace:ne(this,sa),timestamp:Date.now(),data:s}})});continue}cV(n)&&ne(this,sl).push({name:e,promise:Promise.resolve(n)})}}push(t,e){e.method==="values"&&ne(this,nl).set(Dn(t),e.params.data);const n=ne(this,sa);ct(this,sa,t);let r=!0;for(const s of ne(this,ia))s.process(e)||(r=!1);ct(this,sa,n),r&&this._events.push({...e,seq:Bl(this,So)._++})}close(){var n,r;ct(this,Ao,!0);for(const[s,i]of ne(this,nl).entries()){const a=s?s.split("\0"):[];(n=ne(this,aa).get(Dn(a)))==null||n[m_](i)}const t=[];for(const s of ne(this,ia)){const i=(r=s.finalize)==null?void 0:r.call(s);i!=null&&typeof i.then=="function"&&t.push(i)}for(const s of ne(this,Eo))s._close();const e=ne(this,sl);e.length===0&&t.length===0?(this._events.close(),this._discoveries.close()):Promise.allSettled([...t,...e.map(async({name:s,promise:i})=>{try{const a=await i;this._events.done||this._events.push({type:"event",seq:Bl(this,So)._++,method:"custom",params:{namespace:[],timestamp:Date.now(),data:{name:s,payload:a}}})}catch{}})]).then(()=>{this._events.close(),this._discoveries.close()});for(const s of ne(this,aa).values())s[m_](void 0)}fail(t){var e;ct(this,Ao,!0),ct(this,To,t);for(const n of ne(this,ia))(e=n.fail)==null||e.call(n,t);for(const n of ne(this,Eo))n._fail(t);this._events.fail(t),this._discoveries.fail(t);for(const n of ne(this,aa).values())n[iC](t)}markInterrupted(t){ct(this,tl,!0),ne(this,rl).push(...t)}get interrupted(){return ne(this,tl)}get interrupts(){return ne(this,rl)}subscribeEvents(t,e=0){const n=this._events.iterate(e);return{async next(){for(;;){const r=await n.next();if(r.done||rc(r.value.params.namespace,t))return r}}}}},So=new WeakMap,Ao=new WeakMap,To=new WeakMap,tl=new WeakMap,sa=new WeakMap,ia=new WeakMap,Eo=new WeakMap,aa=new WeakMap,nl=new WeakMap,rl=new WeakMap,sl=new WeakMap,cT);async function lV(t,e){let n=0;try{for await(const r of t){const[s,i,a]=r;if(i==="values"&&Dy(a)){const c=a[Nt];e.markInterrupted(c.map(u=>({interruptId:u.id??"",payload:u.value})))}const o=kH({namespace:s,mode:i,payload:a,seq:n});n+=o.length;for(const c of o)e.push(s,c)}}catch(r){e.fail(r);return}e.close()}function Dn(t){return t.join("\0")}function rc(t,e){if(e.length>t.length)return!1;for(let n=0;n<e.length;n+=1)if(t[n]!==e[n])return!1;return!0}function aC(t,e,n=0){return{[Symbol.asyncIterator](){const r=t.iterate(n);return{async next(){for(;;){const s=await r.next();if(s.done)return{value:void 0,done:!0};if(rc(s.value.namespace,e))return{value:s.value,done:!1}}}}}}}const oC="root";function dV(t){if(t.length===0)return oC;const e=t[t.length-1],n=e.indexOf(":");return n===-1?e:e.slice(0,n)}function hV(t){if(t instanceof Error)return t.message;if(typeof t=="string")return t;try{return JSON.stringify(t)}catch{return String(t)}}function Gh(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function fV(t){if(!Gh(t)||t.event!=="started")return;const e=t.cause;if(Gh(e)&&typeof e.type=="string")return e}function pV(t){if(Gh(t)&&"result"in t&&typeof t.name=="string"&&typeof t.id=="string"&&!t.name.startsWith("__"))return{name:t.name,id:t.id}}function mV(t={}){const e=t.rootGraphName??oC,n=t.initialStatus??"running",r=t.emitRootOnRegister??!0,s=t.getGraphName??dV,i=t.serializeError??hV,a=t.getTerminalStatusOverride,o=Aa.local(),c=new Map,u=new Map,l=new Set,d=[];let f,h=0,p=!1;const g=C=>C.length===0?e:s(C),y=(C,D,B)=>{const z=Dn(C);let q=c.get(z);const W=(q==null?void 0:q.graphName)??g(C);if(q!=null&&q.status===D&&q.graphName===W&&(B==null?void 0:B.error)==null)return;q==null?(q={namespace:C,graphName:W,status:D},c.set(z,q)):q.status=D;const me={event:D,graph_name:W,...(B==null?void 0:B.cause)!=null?{cause:B.cause}:{},...(B==null?void 0:B.error)!=null?{error:B.error}:{}},M=Date.now();if(o.push({namespace:C,timestamp:M,...me}),!(C.length===0&&!r)&&f!=null){h+=1;try{f.push(C,{type:"event",seq:0,method:"lifecycle",params:{namespace:C,timestamp:M,data:me}})}finally{h-=1}}},b=C=>{const D=Dn(C);let B=c.get(D);return B==null&&(B={namespace:C,graphName:g(C),status:void 0},c.set(D,B)),B},_=()=>{if(d.length===0)return;const C=d.splice(0,d.length);for(const D of C){const B=Dn(D.namespace),z=c.get(B);z==null||z.status!=="started"||y(D.namespace,"completed")}},w=C=>{const D=Dn(C.namespace),B=c.get(D);B==null||B.status!=="started"||d.some(z=>Dn(z.namespace)===D)||d.push(C)},v=(C,D)=>{for(let B=d.length-1;B>=0;B-=1){const z=d[B];z.source.type==="node"&&z.source.node===D&&Dn(z.source.parent)===Dn(C)&&d.splice(B,1)}},A=C=>{for(let D=1;D<=C.length;D+=1){const B=C.slice(0,D),z=Dn(B);if(c.has(z))continue;b(B);const q=u.get(z);y(B,"started",q!=null?{cause:q}:void 0)}},S=()=>l.size>0?"interrupted":"completed",x=C=>{for(const D of c.values())D.namespace.length!==0&&D.status==="started"&&y(D.namespace,C);y([],C),o.close()},E=async()=>{if(a==null)return S();try{return await a()??S()}catch{return S()}},$=(C,D)=>{const B=`${D}:`;for(const z of c.values()){if(z.namespace.length!==C.length+1||z.status!=="started"||!rc(z.namespace,C))continue;const q=z.namespace[z.namespace.length-1];if(q===D||q.startsWith(B))return z.namespace}},k=(C,D)=>{var z;const B=[...C,`${D.name}:${D.id}`];return((z=c.get(Dn(B)))==null?void 0:z.status)==="started"?B:void 0};return{__native:!0,init(){return{_lifecycleLog:o,lifecycle:aC(o,[],0)}},onRegister(C){f=C,b([]),r&&y([],n)},process(C){const D=C.params.namespace;if(h>0)return!0;const B=C.method==="tasks"?pV(C.params.data):void 0;if(B!=null&&v(D,B.name),_(),C.method==="lifecycle"){const z=fV(C.params.data);return z!=null&&u.set(Dn(D),z),A(D),!1}if(A(D),C.method==="input"&&Gh(C.params.data)&&C.params.data.event==="requested"){const z=C.params.data.id;typeof z=="string"&&l.add(z)}if(B!=null){const z=k(D,B);z!=null&&w({namespace:z,source:{type:"task"}})}if(C.method==="updates"){const z=C.params.node;if(typeof z=="string"&&!z.startsWith("__")){const q=$(D,z);q!=null&&w({namespace:q,source:{type:"node",parent:D,node:z}})}}return!0},finalize(){if(!p){if(p=!0,_(),a==null){x(S());return}return E().then(x).catch(C=>{o.fail(C)})}},fail(C){if(p)return;p=!0;const D=i(C);for(const B of c.values())B.namespace.length!==0&&B.status==="started"&&y(B.namespace,"failed");y([],"failed",{error:D}),o.fail(C)}}}function Na(t){const e=t;return typeof e.run_id=="string"?`run:${e.run_id}`:t.event==="message-start"&&typeof e.id=="string"?`message:${e.id}`:"__default__"}function g_(t,e){const n=Aa.local(),r=new Map,s=new Set;return{init:()=>({messages:n.toAsyncIterable()}),process(i){var o,c;if(i.method!=="messages"||!rc(i.params.namespace,t)||i.params.namespace.length!==t.length+1||e!==void 0&&i.params.node!==e)return!0;const a=i.params.data;switch(a.event){case"message-start":{const u=Na(a);if(a.role==="tool"){s.add(u);break}const l=Aa.local(),d=Object.assign(new Uh(l.toAsyncIterable()),{namespace:i.params.namespace,node:i.params.node});r.set(u,{source:l,stream:d}),l.push(a),n.push(d);break}case"content-block-start":case"content-block-delta":case"content-block-finish":if(s.has(Na(a)))break;(o=r.get(Na(a)))==null||o.source.push(a);break;case"message-finish":{const u=Na(a);if(s.delete(u))break;const l=r.get(u);l&&(l.source.push(a),l.source.close(),r.delete(u));break}case"error":if(s.has(Na(a)))break;(c=r.get(Na(a)))==null||c.source.push(a);break}return!0},finalize(){for(const[i,a]of r)a.source.push({event:"message-finish"}),a.source.close(),r.delete(i);s.clear(),n.close()},fail(i){for(const[a,o]of r)o.source.fail(i),r.delete(a);s.clear(),n.fail(i)}}}function vw(t,e,n=0){const r=e.length+1;return{[Symbol.asyncIterator](){const s=t.iterate(n);return{async next(){for(;;){const i=await s.next();if(i.done)return{value:void 0,done:!0};const{ns:a,stream:o}=i.value;if(a.length===r&&rc(a,e))return{value:o,done:!1}}}}}}}function gV(t,e){const{createStream:n}=e,r=new Set;return{__native:!0,init(){return{_discoveries:t._discoveries,subgraphs:vw(t._discoveries,[],0)}},process(s){const i=s.params.namespace;if(i.length===0)return!0;const a=i.slice(0,1),o=Dn(a);if(r.has(o))return!0;r.add(o);const c=n(a,t._discoveries.size,t._events.size);return t.register(a,c),t._discoveries.push({ns:a,stream:c}),!0}}}function _V(t){const e=Aa.local();return{init:()=>({_valuesLog:e}),process(n){return n.method!=="values"||n.params.namespace.length!==t.length||!rc(n.params.namespace,t)||e.push(n.params.data),!0},finalize(){e.close()},fail(n){e.fail(n)}}}function Qv(t){return"__native"in t&&t.__native===!0}const cC=Symbol("setValuesLog"),uC=Symbol("setMessagesIterable"),__=Symbol("setLifecycleIterable"),y_=Symbol("setSubgraphsIterable"),yV={[Symbol.asyncIterator](){return{next:()=>Promise.resolve({value:void 0,done:!0})}}};var Io,il,xo,ko,Co,oa,al,fi,ol,Oo,uT,lC=(uT=class{constructor(t,e,n=0,r=0,s,i){m(this,"path");m(this,"extensions");m(this,"_mux");Ze(this,Io);Ze(this,il);Ze(this,xo);Ze(this,ko);Ze(this,Co);Ze(this,oa);Ze(this,al);Ze(this,fi);Ze(this,ol);Ze(this,Oo);this.path=t,this._mux=e,ct(this,il,n),ct(this,Io,r),this.extensions=s??{},ct(this,xo,i??new AbortController),ct(this,oa,new Promise((a,o)=>{ct(this,ko,a),ct(this,Co,o)})),ne(this,oa).catch(()=>{})}[Symbol.asyncIterator](){return this._mux.subscribeEvents(this.path,ne(this,Io))}get subgraphs(){return ne(this,Oo)?ne(this,Oo):vw(this._mux._discoveries,this.path,ne(this,il))}get values(){const t=ne(this,al),e=ne(this,oa),n=this._mux,r=ne(this,Io),s=this.path,i=t?t.toAsyncIterable():{[Symbol.asyncIterator]:()=>{const a=n.subscribeEvents(s,r);return{async next(){for(;;){const o=await a.next();if(o.done)return{value:void 0,done:!0};if(o.value.method==="values"&&o.value.params.namespace.length===s.length)return{value:o.value.params.data,done:!1}}}}}};return{[Symbol.asyncIterator]:()=>i[Symbol.asyncIterator](),then:e.then.bind(e)}}get messages(){if(ne(this,fi))return ne(this,fi);const t=g_(this.path),e=t.init();return this._mux.addTransformer(t),ct(this,fi,e.messages),ne(this,fi)}get lifecycle(){return ne(this,ol)??yV}messagesFrom(t){const e=g_(this.path,t),n=e.init();return this._mux.addTransformer(e),n.messages}get output(){return ne(this,oa)}get interrupted(){return this._mux.interrupted}get interrupts(){return this._mux.interrupts}abort(t){ne(this,xo).abort(t)}get signal(){return ne(this,xo).signal}[m_](t){var e;(e=ne(this,ko))==null||e.call(this,t),ct(this,ko,void 0)}[iC](t){var e;(e=ne(this,Co))==null||e.call(this,t),ct(this,Co,void 0)}[cC](t){ct(this,al,t)}[uC](t){ct(this,fi,t)}[__](t){ct(this,ol,t)}[y_](t){ct(this,Oo,t)}},Io=new WeakMap,il=new WeakMap,xo=new WeakMap,ko=new WeakMap,Co=new WeakMap,oa=new WeakMap,al=new WeakMap,fi=new WeakMap,ol=new WeakMap,Oo=new WeakMap,uT),wV=class extends lC{constructor(e,n,r=0,s=0,i,a){super(e,n,r,s,i,a);m(this,"name");m(this,"index");const o=e[e.length-1]??"",c=o.lastIndexOf(":");if(c>=0){this.name=o.slice(0,c);const u=o.slice(c+1);this.index=/^\d+$/.test(u)?Number(u):0}else this.name=o,this.index=0}};function bV(t,e=[],n){const{abortController:r}=n instanceof AbortController?{abortController:n}:{},s=new uV,i=mV(),a=i.init(),o=a._lifecycleLog,c=gV(s,{createStream:(b,_,w)=>{const v=new wV(b,s,_,w);return v[y_](vw(s._discoveries,b,_)),v[__](aC(o,b,o.size)),v}}),u=c.init();s.addTransformer(c),s.addTransformer(i);const l=_V([]),d=g_([]);s.addTransformer(l),s.addTransformer(d);const f={},h=[];for(const b of e){const _=b();s.addTransformer(_);const w=_.init();Qv(_)?h.push(w):Object.assign(f,w),typeof w=="object"&&w!==null&&!Qv(_)&&s.wireChannels(w)}const p=new lC([],s,0,0,f,r);for(const b of h)Object.assign(p,b);const g=l.init();p[cC](g._valuesLog);const y=d.init();return p[uC](y.messages),p[__](a.lifecycle),p[y_](u.subgraphs),s.register([],p),lV(t,s).catch(b=>{}),p}var xs=class extends Error{constructor(t){super(t),this.name="GraphValidationError"}};function vV({nodes:t,channels:e,inputChannels:n,outputChannels:r,streamChannels:s,interruptAfterNodes:i,interruptBeforeNodes:a}){if(!e)throw new xs("Channels not provided");const o=new Set,c=new Set;for(const[u,l]of Object.entries(t)){if(u==="__interrupt__")throw new xs(`"Node name ${Nt} is reserved"`);if(l.constructor===Fu)l.triggers.forEach(d=>o.add(d));else throw new xs(`Invalid node type ${typeof l}, expected PregelNode`)}for(const u of o)if(!(u in e))throw new xs(`Subscribed channel '${String(u)}' not in channels`);if(Array.isArray(n)){if(n.every(u=>!o.has(u)))throw new xs(`None of the input channels ${n} are subscribed to by any node`)}else if(!o.has(n))throw new xs(`Input channel ${String(n)} is not subscribed to by any node`);Array.isArray(r)?r.forEach(u=>c.add(u)):c.add(r),s&&!Array.isArray(s)?c.add(s):Array.isArray(s)&&s.forEach(u=>c.add(u));for(const u of c)if(!(u in e))throw new xs(`Output channel '${String(u)}' not in channels`);if(i&&i!=="*"){for(const u of i)if(!(u in t))throw new xs(`Node ${String(u)} not in nodes`)}if(a&&a!=="*"){for(const u of a)if(!(u in t))throw new xs(`Node ${String(u)} not in nodes`)}}function eS(t,e){if(Array.isArray(t)){for(const n of t)if(!(n in e))throw new Error(`Key ${String(n)} not found in channels`)}else if(!(t in e))throw new Error(`Key ${String(t)} not found in channels`)}var SV=class dC extends Mi{constructor(n){super();m(this,"lc_graph_name","Topic");m(this,"unique",!1);m(this,"accumulate",!1);m(this,"seen");m(this,"values");this.unique=(n==null?void 0:n.unique)??this.unique,this.accumulate=(n==null?void 0:n.accumulate)??this.accumulate,this.seen=new Set,this.values=[]}fromCheckpoint(n){const r=new dC({unique:this.unique,accumulate:this.accumulate});return typeof n<"u"&&(r.seen=new Set(n[0]),r.values=n[1]),r}update(n){let r=!1;this.accumulate||(r=this.values.length>0,this.values=[]);const s=n.flat();if(s.length>0)if(this.unique)for(const i of s)this.seen.has(i)||(r=!0,this.seen.add(i),this.values.push(i));else r=!0,this.values.push(...s);return r}get(){if(this.values.length===0)throw new tn;return this.values}checkpoint(){return[[...this.seen],this.values]}isAvailable(){return this.values.length!==0}};function AV(t){var a,o,c;const e=pn.getRunnableConfig();if(!e)throw new Error("Called interrupt() outside the context of a graph.");const n=e.configurable;if(!n)throw new Error("No configurable found in config");if(!n.__pregel_checkpointer)throw new zd("No checkpointer set",{lc_error_code:"MISSING_CHECKPOINTER"});const r=n[Bs];r.interruptCounter+=1;const s=r.interruptCounter;if(r.resume.length>0&&s<r.resume.length)return(a=n[Jr])==null||a.call(n,[[ws,r.resume]]),r.resume[s];if(r.nullResume!==void 0){if(r.resume.length!==s)throw new Error(`Resume length mismatch: ${r.resume.length} !== ${s}`);const u=r.consumeNullResume();return r.resume.push(u),(o=n[Jr])==null||o.call(n,[[ws,r.resume]]),u}const i=(c=n[us])==null?void 0:c.split("|");throw new fo([{id:i?oi(i.join("|")):void 0,value:t}])}function TV(t){const e=new TextEncoder;return new ReadableStream({async start(n){try{for await(const r of t){const s=r.params.namespace,i=s.length?`${r.method}|${s.join("|")}`:r.method;n.enqueue(e.encode(`event: ${i}
|
|
314
|
-
data: ${JSON.stringify(r.params.data??{})}
|
|
315
|
-
|
|
316
|
-
`))}}catch(r){n.enqueue(e.encode(`event: error
|
|
317
|
-
data: ${JSON.stringify({message:String(r)})}
|
|
318
|
-
|
|
319
|
-
`))}finally{n.close()}}})}var EV=class{static subscribeTo(t,e){const{key:n,tags:r}={key:void 0,tags:void 0,...e??{}};if(Array.isArray(t)&&n!==void 0)throw new Error("Can't specify a key when subscribing to multiple channels");let s;return typeof t=="string"?n?s={[n]:t}:s=[t]:s=Object.fromEntries(t.map(i=>[i,i])),new Fu({channels:s,triggers:Array.isArray(t)?t:[t],tags:r})}static writeTo(t,e){const n=[];for(const r of t)n.push({channel:r,value:pa,skipNone:!1});for(const[r,s]of Object.entries(e??{}))ze.isRunnable(s)||typeof s=="function"?n.push({channel:r,value:pa,skipNone:!0,mapper:hn(s)}):n.push({channel:r,value:s,skipNone:!1});return new Pn(n)}},IV=class extends ze{constructor(){super(...arguments);m(this,"lc_namespace",["langgraph","pregel"])}invoke(e,n){throw new Error("Not implemented")}withConfig(e){return super.withConfig(e)}stream(e,n){return super.stream(e,n)}},gf,hC,lT,xV=(lT=class extends IV{constructor(e){super(e);Ze(this,gf);m(this,"lc_namespace",["langgraph","pregel"]);m(this,"lg_is_pregel",!0);m(this,"nodes");m(this,"channels");m(this,"inputChannels");m(this,"outputChannels");m(this,"autoValidate",!0);m(this,"streamMode",["values"]);m(this,"streamChannels");m(this,"interruptAfter");m(this,"interruptBefore");m(this,"stepTimeout");m(this,"debug",!1);m(this,"checkpointer");m(this,"retryPolicy");m(this,"config");m(this,"store");m(this,"cache");m(this,"userInterrupt");m(this,"streamTransformers");m(this,"triggerToNodes",{});let{streamMode:n}=e;if(n!=null&&!Array.isArray(n)&&(n=[n]),this.nodes=e.nodes,this.channels=e.channels,"__pregel_tasks"in this.channels&&"lc_graph_name"in this.channels.__pregel_tasks&&this.channels.__pregel_tasks.lc_graph_name!=="Topic")throw new Error(`Channel '${Vo}' is reserved and cannot be used in the graph.`);this.channels[Vo]=new SV({accumulate:!1}),this.autoValidate=e.autoValidate??this.autoValidate,this.streamMode=n??this.streamMode,this.inputChannels=e.inputChannels,this.outputChannels=e.outputChannels,this.streamChannels=e.streamChannels??this.streamChannels,this.interruptAfter=e.interruptAfter,this.interruptBefore=e.interruptBefore,this.stepTimeout=e.stepTimeout??this.stepTimeout,this.debug=e.debug??this.debug,this.checkpointer=e.checkpointer,this.retryPolicy=e.retryPolicy,this.config=e.config,this.store=e.store,this.cache=e.cache,this.name=e.name,this.triggerToNodes=e.triggerToNodes??this.triggerToNodes,this.userInterrupt=e.userInterrupt,this.streamTransformers=e.streamTransformers??[],this.autoValidate&&this.validate()}static lc_name(){return"LangGraph"}withConfig(e){const{streamTransformers:n,...r}=e,s=ir(this.config,r),i=[...this.streamTransformers,...n??[]];return new this.constructor({...this,config:s,streamTransformers:i})}validate(){var e;vV({nodes:this.nodes,channels:this.channels,outputChannels:this.outputChannels,inputChannels:this.inputChannels,streamChannels:this.streamChannels,interruptAfterNodes:this.interruptAfter,interruptBeforeNodes:this.interruptBefore});for(const[n,r]of Object.entries(this.nodes))for(const s of r.triggers)(e=this.triggerToNodes)[s]??(e[s]=[]),this.triggerToNodes[s].push(n);return this}get streamChannelsList(){return Array.isArray(this.streamChannels)?this.streamChannels:this.streamChannels?[this.streamChannels]:Object.keys(this.channels)}get streamChannelsAsIs(){return this.streamChannels?this.streamChannels:Object.keys(this.channels)}async getGraphAsync(e){return this.getGraph(e)}*getSubgraphs(e,n){var r;for(const[s,i]of Object.entries(this.nodes)){if(e!==void 0&&!e.startsWith(s))continue;const a=(r=i.subgraphs)!=null&&r.length?i.subgraphs:[i.bound];for(const o of a){const c=zk(o);if(c!==void 0){if(s===e){yield[s,c];return}if(e===void 0&&(yield[s,c]),n){let u=e;e!==void 0&&(u=e.slice(s.length+1));for(const[l,d]of c.getSubgraphs(u,n))yield[`${s}|${l}`,d]}}}}}async*getSubgraphsAsync(e,n){yield*this.getSubgraphs(e,n)}async _prepareStateSnapshot({config:e,saved:n,subgraphCheckpointer:r,applyPendingWrites:s=!1}){var f,h,p,g,y,b,_,w;if(n===void 0)return{values:{},next:[],config:e,tasks:[]};const i=await s_(this.channels,n.checkpoint,{saver:typeof this.checkpointer=="object"?this.checkpointer:void 0,config:n.config??e});if((f=n.pendingWrites)!=null&&f.length){const v=n.pendingWrites.filter(([A,S])=>A===Ar).map(([A,S,x])=>[String(S),x]);v.length>0&&nr(n.checkpoint,i,[{name:ui,writes:v,triggers:[]}],void 0,this.triggerToNodes)}const a=Object.values(io(n.checkpoint,n.pendingWrites,this.nodes,i,n.config,!0,{step:(((h=n.metadata)==null?void 0:h.step)??-1)+1,store:this.store})),o=await li(this.getSubgraphsAsync()),c=((p=n.config.configurable)==null?void 0:p.checkpoint_ns)??"",u={};for(const v of a){const A=o.find(([x])=>x===v.name);if(!A)continue;let S=`${String(v.name)}:${v.id}`;if(c&&(S=`${c}|${S}`),r===void 0){const x={configurable:{thread_id:(g=n.config.configurable)==null?void 0:g.thread_id,checkpoint_ns:S}};u[v.id]=x}else{const x={configurable:{[ds]:r,thread_id:(y=n.config.configurable)==null?void 0:y.thread_id,checkpoint_ns:S}},E=A[1];u[v.id]=await E.getState(x,{subgraphs:!0})}}if(s&&((b=n.pendingWrites)!=null&&b.length)){const v=Object.fromEntries(a.map(S=>[S.id,S]));for(const[S,x,E]of n.pendingWrites)["__error__","__interrupt__",Hd].includes(x)||S in v&&v[S].writes.push([String(x),E]);const A=a.filter(S=>S.writes.length>0);A.length>0&&nr(n.checkpoint,i,A,void 0,this.triggerToNodes)}let l=n==null?void 0:n.metadata;l&&((w=(_=n==null?void 0:n.config)==null?void 0:_.configurable)!=null&&w.thread_id)&&(l={...l,thread_id:n.config.configurable.thread_id});const d=a.filter(v=>v.writes.length===0).map(v=>v.name);return{values:Sa(i,this.streamChannelsAsIs),next:d,tasks:Qk(a,(n==null?void 0:n.pendingWrites)??[],u,this.streamChannelsAsIs),metadata:l,config:Di(n.config,n.metadata),createdAt:n.checkpoint.ts,parentConfig:n.parentConfig}}async getState(e,n){var o,c,u,l,d;const r=((o=e.configurable)==null?void 0:o.__pregel_checkpointer)??this.checkpointer;if(!r)throw new zd("No checkpointer set",{lc_error_code:"MISSING_CHECKPOINTER"});const s=((c=e.configurable)==null?void 0:c.checkpoint_ns)??"";if(s!==""&&((u=e.configurable)==null?void 0:u.__pregel_read)===void 0&&((l=e.configurable)==null?void 0:l.__pregel_checkpointer)===void 0){const f=Qp(s);for await(const[h,p]of this.getSubgraphsAsync(f,!0))if(h===f)return await p.getState(Ra(e,{[ds]:r}),{subgraphs:n==null?void 0:n.subgraphs})}const i=ir(this.config,e),a=await r.getTuple(e);return await this._prepareStateSnapshot({config:i,saved:a,subgraphCheckpointer:n!=null&&n.subgraphs?r:void 0,applyPendingWrites:!((d=e.configurable)!=null&&d.checkpoint_id)})}async*getStateHistory(e,n){var a,o,c;const r=((a=e.configurable)==null?void 0:a.__pregel_checkpointer)??this.checkpointer;if(!r)throw new zd("No checkpointer set",{lc_error_code:"MISSING_CHECKPOINTER"});const s=((o=e.configurable)==null?void 0:o.checkpoint_ns)??"";if(s!==""&&((c=e.configurable)==null?void 0:c.__pregel_checkpointer)===void 0){const u=Qp(s);for await(const[l,d]of this.getSubgraphsAsync(u,!0))if(l===u){yield*d.getStateHistory(Ra(e,{[ds]:r}),n);return}}const i=ir(this.config,e,{configurable:{checkpoint_ns:s}});for await(const u of r.list(i,n))yield this._prepareStateSnapshot({config:u.config,saved:u})}async bulkUpdateState(e,n){var o,c,u;const r=((o=e.configurable)==null?void 0:o.__pregel_checkpointer)??this.checkpointer;if(!r)throw new zd("No checkpointer set",{lc_error_code:"MISSING_CHECKPOINTER"});if(n.length===0)throw new Error("No supersteps provided");if(n.some(l=>l.updates.length===0))throw new Error("No updates provided");const s=((c=e.configurable)==null?void 0:c.checkpoint_ns)??"";if(s!==""&&((u=e.configurable)==null?void 0:u.__pregel_checkpointer)===void 0){const l=Qp(s);for await(const[,d]of this.getSubgraphsAsync(l,!0))return await d.bulkUpdateState(Ra(e,{[ds]:r}),n);throw new Error(`Subgraph "${l}" not found`)}const i=async(l,d)=>{var C,D,B,z,q,W,me,M,Z,re,ae;const f=this.config?ir(this.config,l):l,h=await r.getTuple(f),p=h!==void 0?Kh(h.checkpoint):n_(),g={...h==null?void 0:h.checkpoint.channel_versions},y=((C=h==null?void 0:h.metadata)==null?void 0:C.step)??-1;let b=Ra(f,{checkpoint_ns:((D=f.configurable)==null?void 0:D.checkpoint_ns)??""}),_=f.metadata??{};h!=null&&h.config.configurable&&(b=Ra(f,h.config.configurable),_={...h.metadata,..._});const{values:w,asNode:v}=d[0];if(w==null&&v===void 0){if(d.length>1)throw new ft("Cannot create empty checkpoint with multiple updates");return Di(await r.put(b,Gi(p,void 0,y),{source:"update",step:y+1,parents:((B=h==null?void 0:h.metadata)==null?void 0:B.parents)??{}},{}),h?h.metadata:void 0)}const A=await s_(this.channels,p,{saver:r,config:(h==null?void 0:h.config)??b});if(w===null&&v==="__end__"){if(d.length>1)throw new ft("Cannot apply multiple updates when clearing state");if(h){const X=io(p,h.pendingWrites||[],this.nodes,A,h.config,!0,{step:(((z=h.metadata)==null?void 0:z.step)??-1)+1,checkpointer:r,store:this.store}),se=(h.pendingWrites||[]).filter(Se=>Se[0]===Ar).map(Se=>Se.slice(1));se.length>0&&nr(p,A,[{name:ui,writes:se,triggers:[]}],r.getNextVersion.bind(r),this.triggerToNodes);for(const[Se,ue,I]of h.pendingWrites||[])["__error__","__interrupt__",Hd].includes(ue)||Se in X&&X[Se].writes.push([ue,I]);nr(p,A,Object.values(X),r.getNextVersion.bind(r),this.triggerToNodes)}return Di(await r.put(b,Gi(p,A,y),{..._,source:"update",step:y+1,parents:((q=h==null?void 0:h.metadata)==null?void 0:q.parents)??{}},Jd(g,p.channel_versions)),h?h.metadata:void 0)}if(v==="__copy__"){if(d.length>1)throw new ft("Cannot copy checkpoint with multiple updates");if(h==null)throw new ft("Cannot copy a non-existent checkpoint");const X=ue=>!Array.isArray(ue)||ue.length===0?!1:ue.every(I=>Array.isArray(I)&&I.length===2),se=Gi(p,void 0,y),Se=await r.put(h.parentConfig??Ra(h.config,{checkpoint_id:void 0}),se,{source:"fork",step:y+1,parents:((W=h.metadata)==null?void 0:W.parents)??{}},{});if(X(w)){const ue=io(se,h.pendingWrites,this.nodes,A,Se,!1,{step:y+2}),I=Object.values(ue).reduce((L,{name:O,id:ge})=>(L[O]??(L[O]=[]),L[O].push({id:ge}),L),{}),T=w.reduce((L,O)=>{var lt,vt;const[ge,Ee]=O;L[Ee]??(L[Ee]=[]);const nt=L[Ee].length,We=(vt=(lt=I[Ee])==null?void 0:lt[nt])==null?void 0:vt.id;return L[Ee].push({values:ge,asNode:Ee,taskId:We}),L},{});return i(Di(Se,h.metadata),Object.values(T).flat())}return Di(Se,h.metadata)}if(v==="__input__"){if(d.length>1)throw new ft("Cannot apply multiple updates when updating as input");const X=await li(Yk(this.inputChannels,w));if(X.length===0)throw new ft(`Received no input writes for ${JSON.stringify(this.inputChannels,null,2)}`);nr(p,A,[{name:ui,writes:X,triggers:[]}],r.getNextVersion.bind(this.checkpointer),this.triggerToNodes);const se=((me=h==null?void 0:h.metadata)==null?void 0:me.step)!=null?h.metadata.step+1:-1,Se=await r.put(b,Gi(p,A,se),{source:"input",step:se,parents:((M=h==null?void 0:h.metadata)==null?void 0:M.parents)??{}},Jd(g,p.channel_versions));return await r.putWrites(Se,X,Qi(ui,p.id)),Di(Se,h?h.metadata:void 0)}if(((Z=f.configurable)==null?void 0:Z.checkpoint_id)===void 0&&(h==null?void 0:h.pendingWrites)!==void 0&&h.pendingWrites.length>0){const X=io(p,h.pendingWrites,this.nodes,A,h.config,!0,{store:this.store,checkpointer:this.checkpointer,step:(((re=h.metadata)==null?void 0:re.step)??-1)+1}),se=(h.pendingWrites??[]).filter(ue=>ue[0]===Ar).map(ue=>ue.slice(1));se.length>0&&nr(h.checkpoint,A,[{name:ui,writes:se,triggers:[]}],void 0,this.triggerToNodes);for(const[ue,I,T]of h.pendingWrites)["__error__","__interrupt__",Hd].includes(I)||X[ue]===void 0||X[ue].writes.push([I,T]);const Se=Object.values(X).filter(ue=>ue.writes.length>0);Se.length>0&&nr(p,A,Se,void 0,this.triggerToNodes)}const S=Object.values(p.versions_seen).map(X=>Object.values(X)).flat().find(X=>!!X),x=[];if(d.length===1){let{values:X,asNode:se,taskId:Se}=d[0];if(se===void 0&&Object.keys(this.nodes).length===1)[se]=Object.keys(this.nodes);else if(se===void 0&&S===void 0)typeof this.inputChannels=="string"&&this.nodes[this.inputChannels]!==void 0&&(se=this.inputChannels);else if(se===void 0){const ue=Object.entries(p.versions_seen).map(([I,T])=>Object.values(T).map(L=>[L,I])).flat().filter(([I,T])=>T!==Nt).sort(([I],[T])=>Nk(I,T));ue&&(ue.length===1?se=ue[0][1]:ue[ue.length-1][0]!==ue[ue.length-2][0]&&(se=ue[ue.length-1][1]))}if(se===void 0)throw new ft('Ambiguous update, specify "asNode"');x.push({values:X,asNode:se,taskId:Se})}else for(const{asNode:X,values:se,taskId:Se}of d){if(X==null)throw new ft('"asNode" is required when applying multiple updates');x.push({values:se,asNode:X,taskId:Se})}const E=[];for(const{asNode:X,values:se,taskId:Se}of x){if(this.nodes[X]===void 0)throw new ft(`Node "${X.toString()}" does not exist`);const ue=this.nodes[X].getWriters();if(!ue.length)throw new ft(`No writers found for node "${X.toString()}"`);E.push({name:X,input:se,proc:ue.length>1?fr.from(ue,{omitSequenceTags:!0}):ue[0],writes:[],triggers:[Nt],id:Se??Qi("__interrupt__",p.id),writers:[]})}for(const X of E)await X.proc.invoke(X.input,et({...f,store:(f==null?void 0:f.store)??this.store},{runName:f.runName??`${this.getName()}UpdateState`,configurable:{[Jr]:se=>X.writes.push(...se),[Ai]:(se,Se=!1)=>pu(p,A,X,se,Se)}}));for(const X of E){const se=X.writes.filter(Se=>Se[0]!==Tr);h!==void 0&&se.length>0&&await r.putWrites(b,se,X.id)}nr(p,A,E,r.getNextVersion.bind(this.checkpointer),this.triggerToNodes);const $=Jd(g,p.channel_versions),k=await r.put(b,Gi(p,A,y+1),{source:"update",step:y+1,parents:((ae=h==null?void 0:h.metadata)==null?void 0:ae.parents)??{}},$);for(const X of E){const se=X.writes.filter(Se=>Se[0]===Tr);se.length>0&&await r.putWrites(k,se,X.id)}return Di(k,h?h.metadata:void 0)};let a=e;for(const{updates:l}of n)a=await i(a,l);return a}async updateState(e,n,r){return this.bulkUpdateState(e,[{updates:[{values:n,asNode:r}]}])}_defaults(e){var A,S,x;const{debug:n,streamMode:r,inputKeys:s,outputKeys:i,interruptAfter:a,interruptBefore:o,...c}=e;let u=!0;const l=n!==void 0?n:this.debug;let d=i;d===void 0?d=this.streamChannelsAsIs:eS(d,this.channels);let f=s;f===void 0?f=this.inputChannels:eS(f,this.channels);const h=o??this.interruptBefore??[],p=a??this.interruptAfter??[];let g;r!==void 0?(g=Array.isArray(r)?r:[r],u=typeof r=="string"):(((A=e.configurable)==null?void 0:A.__pregel_task_id)!==void 0?g=["values"]:g=this.streamMode,u=!0);let y;if(this.checkpointer===!1)y=void 0;else if(e!==void 0&&((S=e.configurable)==null?void 0:S.__pregel_checkpointer)!==void 0)y=e.configurable[ds];else{if(this.checkpointer===!0)throw new Error("checkpointer: true cannot be used for root graphs.");y=this.checkpointer}const b=e.store??this.store,_=e.cache??this.cache;if(e.durability!=null&&e.checkpointDuring!=null)throw new Error("Cannot use both `durability` and `checkpointDuring` at the same time.");const w=(()=>{if(e.checkpointDuring!=null)return e.checkpointDuring===!1?"exit":"async"})(),v=e.durability??w??((x=e==null?void 0:e.configurable)==null?void 0:x.__pregel_durability)??"async";return[l,g,f,d,c,h,p,y,b,u,_,v]}async stream(e,n){var a;const r=new AbortController,s={recursionLimit:(a=this.config)==null?void 0:a.recursionLimit,...n,signal:Bu(n==null?void 0:n.signal,r.signal).signal},i=await super.stream(e,s);return new sm((n==null?void 0:n.encoding)==="text/event-stream"?NH(i):i,r)}streamEvents(e,n,r){var a,o;if(n.version==="v3")return ji(this,gf,hC).call(this,e,n);const s=new AbortController,i={recursionLimit:(a=this.config)==null?void 0:a.recursionLimit,...n,callbacks:D9((o=this.config)==null?void 0:o.callbacks,n==null?void 0:n.callbacks),signal:Bu(n==null?void 0:n.signal,s.signal).signal};return new sm(super.streamEvents(e,i,r),s)}async _validateInput(e){return e}async _validateContext(e){return e}async*_streamIterator(e,n){var B;const r="version"in(n??{})?void 0:(n==null?void 0:n.encoding)??void 0,s=n==null?void 0:n.subgraphs,i=(n==null?void 0:n.version)==="v3",a=Fk(this.config,n);if(a.recursionLimit===void 0||a.recursionLimit<1)throw new Error('Passed "recursionLimit" must be at least 1.');if(this.checkpointer!==void 0&&this.checkpointer!==!1&&a.configurable===void 0)throw new Error('Checkpointer requires one or more of the following "configurable" keys: "thread_id", "checkpoint_ns", "checkpoint_id"');const o=await this._validateInput(e),{runId:c,...u}=a,[l,d,,f,h,p,g,y,b,_,w,v]=this._defaults(u);h.metadata={ls_integration:"langgraph",...h.metadata},typeof h.context<"u"?h.context=await this._validateContext(h.context):h.configurable=await this._validateContext(h.configurable);const A=new eC({modes:new Set(d)});if(this.checkpointer===!0){h.configurable??(h.configurable={});const z=h.configurable.checkpoint_ns??"";h.configurable[us]=z.split("|").map(q=>q.split(":")[0]).join("|")}if(d.includes("messages")){const z=i?new JH(W=>A.push(W)):new ZH(W=>A.push(W)),{callbacks:q}=h;if(q===void 0)h.callbacks=[z];else if(Array.isArray(q))h.callbacks=q.concat(z);else{const W=q.copy();W.addHandler(z,!0),h.callbacks=W}}if(d.includes("tools")){const z=new $H(W=>A.push(W)),{callbacks:q}=h;if(q===void 0)h.callbacks=[z];else if(Array.isArray(q))h.callbacks=q.concat(z);else{const W=q.copy();W.addHandler(z,!0),h.callbacks=W}}h.writer??(h.writer=z=>{var W,me,M;if(!d.includes("custom"))return;const q=(M=(me=(W=P9())==null?void 0:W.configurable)==null?void 0:me[us])==null?void 0:M.split("|").slice(0,-1);A.push([q??[],"custom",z])}),h.interrupt??(h.interrupt=this.userInterrupt??AV),h.serverInfo==null&&(h.serverInfo=kV(h)),h.control??(h.control=new F9);const S={tracerInheritableMetadata:$V(h)},x=await((B=await bn._configureSync(h==null?void 0:h.callbacks,void 0,h==null?void 0:h.tags,void 0,h==null?void 0:h.metadata,void 0,S))==null?void 0:B.handleChainStart(this.toJSON(),j9(e,"input"),c,void 0,void 0,void 0,(h==null?void 0:h.runName)??this.getName())),E=Kf(this.channels);let $,k;const D=(async()=>{var z,q,W;try{$=await KH.initialize({input:o,config:h,checkpointer:y,nodes:this.nodes,channelSpecs:E,outputKeys:f,streamKeys:this.streamChannelsAsIs,store:b,cache:w,stream:A,interruptAfter:g,interruptBefore:p,manager:x,debug:this.debug,triggerToNodes:this.triggerToNodes,durability:v});const me=new sV({loop:$,nodeFinished:(z=h.configurable)==null?void 0:z[Y6]});n!=null&&n.subgraphs&&($.config.configurable={...$.config.configurable,[My]:$.stream}),await this._runLoop({loop:$,runner:me,debug:l,config:h}),v==="sync"&&await Promise.all(($==null?void 0:$.checkpointerPromises)??[])}catch(me){k=me}finally{try{$&&(await((q=$.store)==null?void 0:q.stop()),await((W=$.cache)==null?void 0:W.stop())),await Promise.all(($==null?void 0:$.checkpointerPromises)??[])}catch(me){k=k??me}k?(await new Promise(me=>{queueMicrotask(me)}),A.error(k)):A.close()}})();try{for await(const z of A){if(z===void 0)throw new Error("Data structure error.");const[q,W,me]=z,M="version"in(n??{});if(d.includes(W)||W==="checkpoints"&&ww(me)&&(i||M&&s&&d.includes("values"))){if(r==="text/event-stream"){s?yield[q,W,me]:yield[null,W,me];continue}s&&!_?yield[q,W,me]:_?s?yield[q,me]:yield me:yield[W,me]}}}catch(z){throw await(x==null?void 0:x.handleChainError(k)),z}finally{await D}await(x==null?void 0:x.handleChainEnd(($==null?void 0:$.output)??{},c,void 0,void 0,void 0))}async invoke(e,n){const r=(n==null?void 0:n.streamMode)??"values",s={...n,outputKeys:(n==null?void 0:n.outputKeys)??this.outputChannels,streamMode:r,encoding:void 0},i=[],a=await this.stream(e,s),o=[];let c;for await(const u of a)r==="values"?Dy(u)?o.push(u[Nt]):c=u:i.push(u);if(r==="values"){if(o.length>0){const u=o.flat(1);if(c==null)return{[Nt]:u};if(typeof c=="object")return{...c,[Nt]:u}}return c}return i}async _runLoop(e){const{loop:n,runner:r,debug:s,config:i}=e;let a;try{for(;await n.tick({inputKeys:this.inputChannels});){for(const{task:o}of await n._matchCachedWrites())n._outputWrites(o.id,o.writes,!0);s&&TH(n.checkpointMetadata.step,n.channels,this.streamChannelsList),s&&d_(n.step,Object.values(n.tasks)),await r.tick({timeout:this.stepTimeout,retryPolicy:this.retryPolicy,onStepWrite:(o,c)=>{s&&EH(o,c,this.streamChannelsList)},maxConcurrency:i.maxConcurrency,signal:i.signal})}if(n.status==="draining")throw n.control==null?new Error("Draining status requires run control"):new WI(n.control.drainReason??"shutdown");if(n.status==="out_of_steps")throw new rB([`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(o){if(a=o,!await n.finishAndHandleError(a))throw o}finally{a===void 0&&await n.finishAndHandleError()}}async clearCache(){var e;await((e=this.cache)==null?void 0:e.clear([]))}},gf=new WeakSet,hC=async function(e,n){var l,d;const{version:r,encoding:s,transformers:i,...a}=n,o={recursionLimit:(l=this.config)==null?void 0:l.recursionLimit,...a,configurable:{...(d=this.config)==null?void 0:d.configurable,...a==null?void 0:a.configurable},version:r,streamMode:IH,subgraphs:!0,encoding:void 0},c=this.stream(e,o),u=bV({[Symbol.asyncIterator]:async function*(){const f=await c;for await(const h of f)yield h}},[...this.streamTransformers??[],...i??[]]);if(s==="text/event-stream"){const f=new AbortController;return f.signal.addEventListener("abort",()=>u.abort(f.signal.reason),{once:!0}),new sm(TV(u),f)}return u},lT);function kV(t){const e=t.metadata??{},n=t.configurable??{},r=n.assistant_id??e.assistant_id,s=n.graph_id??e.graph_id,i=n.langgraph_auth_user;let a;if(i!=null&&typeof i=="object"&&"identity"in i&&(a=i),r!=null||s!=null||a!=null)return{assistantId:r!=null?String(r):"",graphId:s!=null?String(s):"",user:a}}const CV=new Set(["key","token","secret","password","auth"]);function OV(t,e){const n=t.toLowerCase();let r=!1;for(const s of CV)if(n.includes(s)){r=!0;break}return t.startsWith("__")||!(typeof e=="string"||typeof e=="number"||typeof e=="boolean")||r}function $V(t){const e=t.configurable;if(!e)return;const n={};for(const[r,s]of Object.entries(e))OV(r,s)||(n[r]=s);return Object.keys(n).length>0?n:void 0}var fC=class{constructor(t){m(this,"path");m(this,"ends");ze.isRunnable(t.path)?this.path=t.path:this.path=hn(t.path),this.ends=Array.isArray(t.pathMap)?t.pathMap.reduce((e,n)=>(e[n]=n,e),{}):t.pathMap}run(t,e){return Pn.registerWriter(new bs({name:"<branch_run>",trace:!1,func:async(n,r)=>{try{return await this._route(n,r,t,e)}catch(s){throw s.name===ZI.unminifiable_name&&console.warn(`[WARN]: 'NodeInterrupt' thrown in conditional edge. This is likely a bug in your graph implementation.
|
|
320
|
-
NodeInterrupt should only be thrown inside a node, not in edge conditions.`),s}}}))}async _route(t,e,n,r){let s=await this.path.invoke(r?r(e):t,e);Array.isArray(s)||(s=[s]);let i;if(this.ends?i=s.map(a=>Wn(a)?a:this.ends[a]):i=s,i.some(a=>!a))throw new Error("Branch condition returned unknown or null destination");if(i.filter(Wn).some(a=>a.node==="__end__"))throw new ft("Cannot send a packet to the END node");return await n(i,e)??t}},RV=class{constructor(){m(this,"nodes");m(this,"edges");m(this,"branches");m(this,"entryPoint");m(this,"compiled",!1);this.nodes={},this.edges=new Set,this.branches={}}warnIfCompiled(t){this.compiled&&console.warn(t)}get allEdges(){return this.edges}addNode(...t){function e(r){return r.length>=1&&typeof r[0]!="string"}const n=e(t)?Array.isArray(t[0])?t[0]:Object.entries(t[0]):[[t[0],t[1],t[2]]];if(n.length===0)throw new Error("No nodes provided in `addNode`");for(const[r,s,i]of n){for(const o of["|",":"])if(r.includes(o))throw new Error(`"${o}" is a reserved character and is not allowed in node names.`);if(this.warnIfCompiled("Adding a node to a graph that has already been compiled. This will not be reflected in the compiled graph."),r in this.nodes)throw new Error(`Node \`${r}\` already present.`);if(r==="__end__")throw new Error(`Node \`${r}\` is reserved.`);const a=hn(s);this.nodes[r]={runnable:a,metadata:i==null?void 0:i.metadata,subgraphs:_w(a)?[a]:i==null?void 0:i.subgraphs,ends:i==null?void 0:i.ends}}return this}addEdge(t,e){if(this.warnIfCompiled("Adding an edge to a graph that has already been compiled. This will not be reflected in the compiled graph."),t==="__end__")throw new Error("END cannot be a start node");if(e==="__start__")throw new Error("START cannot be an end node");if(Array.from(this.edges).some(([n])=>n===t)&&!("channels"in this))throw new Error(`Already found path for ${t}. For multiple edges, use StateGraph.`);return this.edges.add([t,e]),this}addConditionalEdges(t,e,n){var i,a;const r=typeof t=="object"?t:{source:t,path:e,pathMap:n};this.warnIfCompiled("Adding an edge to a graph that has already been compiled. This will not be reflected in the compiled graph."),ze.isRunnable(r.path)||(r.path=hn(r.path));const s=r.path.getName()==="RunnableLambda"?"condition":r.path.getName();if(this.branches[r.source]&&this.branches[r.source][s])throw new Error(`Condition \`${s}\` already present for node \`${t}\``);return(i=this.branches)[a=r.source]??(i[a]={}),this.branches[r.source][s]=new fC(r),this}setEntryPoint(t){return this.warnIfCompiled("Setting the entry point of a graph that has already been compiled. This will not be reflected in the compiled graph."),this.addEdge(un,t)}setFinishPoint(t){return this.warnIfCompiled("Setting a finish point of a graph that has already been compiled. This will not be reflected in the compiled graph."),this.addEdge(t,ht)}compile({checkpointer:t,interruptBefore:e,interruptAfter:n,name:r,transformers:s}={}){this.validate([...Array.isArray(e)?e:[],...Array.isArray(n)?n:[]]);const i=new pC({builder:this,checkpointer:t,interruptAfter:n,interruptBefore:e,autoValidate:!1,nodes:{},channels:{[un]:new Zo,[ht]:new Zo},inputChannels:un,outputChannels:ht,streamChannels:[],streamMode:"values",name:r,streamTransformers:s});for(const[a,o]of Object.entries(this.nodes))i.attachNode(a,o);for(const[a,o]of this.edges)i.attachEdge(a,o);for(const[a,o]of Object.entries(this.branches))for(const[c,u]of Object.entries(o))i.attachBranch(a,c,u);return i.validate()}validate(t){const e=new Set([...this.allEdges].map(([r,s])=>r));for(const[r]of Object.entries(this.branches))e.add(r);for(const r of e)if(r!=="__start__"&&!(r in this.nodes))throw new Error(`Found edge starting at unknown node \`${r}\``);const n=new Set([...this.allEdges].map(([r,s])=>s));for(const[r,s]of Object.entries(this.branches))for(const i of Object.values(s))if(i.ends!=null)for(const a of Object.values(i.ends))n.add(a);else{n.add(ht);for(const a of Object.keys(this.nodes))a!==r&&n.add(a)}for(const r of Object.values(this.nodes))for(const s of r.ends??[])n.add(s);if(Object.values(this.nodes).some(r=>r.isErrorHandler))for(const r of Object.keys(this.nodes))n.add(r);for(const r of Object.keys(this.nodes))if(!this.nodes[r].isErrorHandler&&!n.has(r))throw new oB([`Node \`${r}\` is not reachable.`,"","If you are returning Command objects from your node,",'make sure you are passing names of potential destination nodes as an "ends" array','into ".addNode(..., { ends: ["node1", "node2"] })".'].join(`
|
|
321
|
-
`),{lc_error_code:"UNREACHABLE_NODE"});for(const r of n)if(r!=="__end__"&&!(r in this.nodes))throw new Error(`Found edge ending at unknown node \`${r}\``);if(t){for(const r of t)if(!(r in this.nodes))throw new Error(`Interrupt node \`${r}\` is not present`)}this.compiled=!0}},pC=class extends xV{constructor({builder:e,...n}){super(n);m(this,"builder");this.builder=e}withConfig(e){return super.withConfig(e)}attachNode(e,n){this.channels[e]=new Zo,this.nodes[e]=new Fu({channels:[],triggers:[],metadata:n.metadata,subgraphs:n.subgraphs,ends:n.ends}).pipe(n.runnable).pipe(new Pn([{channel:e,value:pa}],[Hn])),this.streamChannels.push(e)}attachEdge(e,n){if(n==="__end__"){if(e==="__start__")throw new Error("Cannot have an edge from START to END");this.nodes[e].writers.push(new Pn([{channel:ht,value:pa}],[Hn]))}else this.nodes[n].triggers.push(e),this.nodes[n].channels.push(e)}attachBranch(e,n,r){e==="__start__"&&!this.nodes.__start__&&(this.nodes[un]=EV.subscribeTo(un,{tags:[Hn]})),this.nodes[e].pipe(r.run(i=>new Pn(i.map(a=>Wn(a)?a:{channel:a==="__end__"?ht:`branch:${e}:${n}:${a}`,value:pa}),[Hn])));const s=r.ends?Object.values(r.ends):Object.keys(this.nodes);for(const i of s)if(i!=="__end__"){const a=`branch:${e}:${n}:${i}`;this.channels[a]=new Zo,this.nodes[i].triggers.push(a),this.nodes[i].channels.push(a)}}async getGraphAsync(e){var l,d,f,h;const n=e==null?void 0:e.xray,r=new $u,s={[un]:r.addNode({schema:ad()},un)},i={};let a={};n&&(a=Object.fromEntries((await li(this.getSubgraphsAsync())).filter(p=>tS(p[1]))));const o=[];function c(p,g,y,b=!1){if(g==="__end__"&&i.__end__===void 0&&(i[ht]=r.addNode({schema:ad()},ht)),s[p]!==void 0){if(i[g]===void 0)throw new Error(`End node ${g} not found!`);return o.push({src:p,dest:g,conditional:b}),r.addEdge(s[p],i[g],y!==g?y:void 0,b)}}for(const[p,g]of Object.entries(this.builder.nodes)){const y=Ft(p),b=g.runnable,_=g.metadata??{};if((l=this.interruptBefore)!=null&&l.includes(p)&&((d=this.interruptAfter)!=null&&d.includes(p))?_.__interrupt="before,after":(f=this.interruptBefore)!=null&&f.includes(p)?_.__interrupt="before":(h=this.interruptAfter)!=null&&h.includes(p)&&(_.__interrupt="after"),n){const w=typeof n=="number"?n-1:n,v=a[p]!==void 0?await a[p].getGraphAsync({...e,xray:w}):b.getGraph(e);if(v.trimFirstNode(),v.trimLastNode(),Object.keys(v.nodes).length>1){let x=function($){return $?$.lc_runnable:!1},E=function($,k){if($!==void 0&&!Gv($))return $;if(x(k))try{let C=k.getName();return C=C.startsWith("Runnable")?C.slice(8):C,C}catch{return k.getName()}else return k.name??"UnknownSchema"};const[A,S]=r.extend(v,y);if(A===void 0)throw new Error(`Could not extend subgraph "${p}" due to missing entrypoint.`);S!==void 0&&(s[y]={name:E(S.id,S.data),...S}),i[y]={name:E(A.id,A.data),...A}}else{const A=r.addNode(b,y,_);s[y]=A,i[y]=A}}else{const w=r.addNode(b,y,_);s[y]=w,i[y]=w}}const u=[...this.builder.allEdges].sort(([p],[g])=>p<g?-1:g>p?1:0);for(const[p,g]of u)c(Ft(p),Ft(g));for(const[p,g]of Object.entries(this.builder.branches)){const y={...Object.fromEntries(Object.keys(this.builder.nodes).filter(b=>b!==p).map(b=>[Ft(b),Ft(b)])),[ht]:ht};for(const b of Object.values(g)){let _;b.ends!==void 0?_=b.ends:_=y;for(const[w,v]of Object.entries(_))c(Ft(p),Ft(v),w,!0)}}for(const[p,g]of Object.entries(this.builder.nodes))if(g.ends!==void 0)for(const y of g.ends)c(Ft(p),Ft(y),void 0,!0);return nS(this.builder.nodes,o,c),r}getGraph(e){var l,d,f,h;const n=e==null?void 0:e.xray,r=new $u,s={[un]:r.addNode({schema:ad()},un)},i={};let a={};n&&(a=Object.fromEntries(qa(this.getSubgraphs()).filter(p=>tS(p[1]))));const o=[];function c(p,g,y,b=!1){if(g==="__end__"&&i.__end__===void 0&&(i[ht]=r.addNode({schema:ad()},ht)),s[p]!==void 0){if(i[g]===void 0)throw new Error(`End node ${g} not found!`);return o.push({src:p,dest:g,conditional:b}),r.addEdge(s[p],i[g],y!==g?y:void 0,b)}}for(const[p,g]of Object.entries(this.builder.nodes)){const y=Ft(p),b=g.runnable,_=g.metadata??{};if((l=this.interruptBefore)!=null&&l.includes(p)&&((d=this.interruptAfter)!=null&&d.includes(p))?_.__interrupt="before,after":(f=this.interruptBefore)!=null&&f.includes(p)?_.__interrupt="before":(h=this.interruptAfter)!=null&&h.includes(p)&&(_.__interrupt="after"),n){const w=typeof n=="number"?n-1:n,v=a[p]!==void 0?a[p].getGraph({...e,xray:w}):b.getGraph(e);if(v.trimFirstNode(),v.trimLastNode(),Object.keys(v.nodes).length>1){let x=function($){return $?$.lc_runnable:!1},E=function($,k){if($!==void 0&&!Gv($))return $;if(x(k))try{let C=k.getName();return C=C.startsWith("Runnable")?C.slice(8):C,C}catch{return k.getName()}else return k.name??"UnknownSchema"};const[A,S]=r.extend(v,y);if(A===void 0)throw new Error(`Could not extend subgraph "${p}" due to missing entrypoint.`);S!==void 0&&(s[y]={name:E(S.id,S.data),...S}),i[y]={name:E(A.id,A.data),...A}}else{const A=r.addNode(b,y,_);s[y]=A,i[y]=A}}else{const w=r.addNode(b,y,_);s[y]=w,i[y]=w}}const u=[...this.builder.allEdges].sort(([p],[g])=>p<g?-1:g>p?1:0);for(const[p,g]of u)c(Ft(p),Ft(g));for(const[p,g]of Object.entries(this.builder.branches)){const y={...Object.fromEntries(Object.keys(this.builder.nodes).filter(b=>b!==p).map(b=>[Ft(b),Ft(b)])),[ht]:ht};for(const b of Object.values(g)){let _;b.ends!==void 0?_=b.ends:_=y;for(const[w,v]of Object.entries(_))c(Ft(p),Ft(v),w,!0)}}for(const[p,g]of Object.entries(this.builder.nodes))if(g.ends!==void 0)for(const y of g.ends)c(Ft(p),Ft(y),void 0,!0);return nS(this.builder.nodes,o,c),r}};function tS(t){return typeof t.attachNode=="function"&&typeof t.attachEdge=="function"}function Ft(t){return t==="subgraph"?`"${t}"`:t}function nS(t,e,n){var i;const r=new Set(e.map(a=>a.src)),s=[...new Set(e.filter(a=>!a.conditional&&a.dest!=="__end__").map(a=>a.dest))].sort();for(const a of s){if(r.has(a))continue;const o=Object.keys(t).find(c=>Ft(c)===a);o!==void 0&&((i=t[o])!=null&&i.isErrorHandler)||n(a,ht)}}const ea=(t,e)=>t.size===e.size&&[...t].every(n=>e.has(n));var PV=class mC extends Mi{constructor(n){super();m(this,"lc_graph_name","NamedBarrierValue");m(this,"names");m(this,"seen");this.names=n,this.seen=new Set}fromCheckpoint(n){const r=new mC(this.names);return typeof n<"u"&&(r.seen=new Set(n)),r}update(n){let r=!1;for(const s of n)if(this.names.has(s))this.seen.has(s)||(this.seen.add(s),r=!0);else throw new ft(`Value ${JSON.stringify(s)} not in names ${JSON.stringify(this.names)}`);return r}get(){if(!ea(this.names,this.seen))throw new tn}checkpoint(){return[...this.seen]}consume(){return this.seen&&this.names&&ea(this.seen,this.names)?(this.seen=new Set,!0):!1}isAvailable(){return!!this.names&&ea(this.names,this.seen)}},NV=class gC extends Mi{constructor(n){super();m(this,"lc_graph_name","NamedBarrierValueAfterFinish");m(this,"names");m(this,"seen");m(this,"finished");this.names=n,this.seen=new Set,this.finished=!1}fromCheckpoint(n){const r=new gC(this.names);if(typeof n<"u"){const[s,i]=n;r.seen=new Set(s),r.finished=i}return r}update(n){let r=!1;for(const s of n)if(this.names.has(s)&&!this.seen.has(s))this.seen.add(s),r=!0;else if(!this.names.has(s))throw new ft(`Value ${JSON.stringify(s)} not in names ${JSON.stringify(this.names)}`);return r}get(){if(!this.finished||!ea(this.names,this.seen))throw new tn}checkpoint(){return[[...this.seen],this.finished]}consume(){return this.finished&&this.seen&&this.names&&ea(this.seen,this.names)?(this.seen=new Set,this.finished=!1,!0):!1}finish(){return!this.finished&&this.names&&ea(this.names,this.seen)?(this.finished=!0,!0):!1}isAvailable(){return this.finished&&!!this.names&&ea(this.names,this.seen)}};function zc(t){return typeof t=="object"&&t!==null&&"~standard"in t&&typeof t["~standard"]=="object"&&t["~standard"]!==null&&"validate"in t["~standard"]}function MV(t){return typeof t=="object"&&t!==null&&"~standard"in t&&typeof t["~standard"]=="object"&&t["~standard"]!==null&&"jsonSchema"in t["~standard"]}function Ma(t){if(MV(t))try{return t["~standard"].jsonSchema.input({target:"draft-07"})}catch{return}}function La(t){if(t!=null&&zc(t))try{const e=t["~standard"].validate(void 0);if(e&&typeof e=="object"&&!("then"in e&&typeof e.then=="function")){const n=e;if(!n.issues){const r=n.value;return()=>r}}}catch{}}const cm=Symbol.for("langgraph.channel.missing");var LV=class _C extends Mi{constructor(n){super();m(this,"lc_graph_name","UntrackedValue");m(this,"guard");m(this,"_value",cm);m(this,"initialValueFactory");this.guard=(n==null?void 0:n.guard)??!0,this.initialValueFactory=n==null?void 0:n.initialValueFactory,this.initialValueFactory&&(this._value=this.initialValueFactory())}fromCheckpoint(n){return new _C({guard:this.guard,initialValueFactory:this.initialValueFactory})}update(n){if(n.length===0)return!1;if(n.length!==1&&this.guard)throw new ft("UntrackedValue(guard=true) can receive only one value per step. Use guard=false if you want to store any one of multiple values.",{lc_error_code:"INVALID_CONCURRENT_GRAPH_UPDATE"});return this._value=n[n.length-1],!0}get(){if(this._value===cm)throw new tn;return this._value}checkpoint(){}isAvailable(){return this._value!==cm}};const um=Symbol.for("langgraph.state.reduced_value");var dT,Ga=(dT=um,class{constructor(t,e){m(this,dT,!0);m(this,"valueSchema");m(this,"inputSchema");m(this,"reducer");m(this,"jsonSchemaExtra");this.reducer=e.reducer,this.jsonSchemaExtra=e.jsonSchemaExtra,this.valueSchema=t,this.inputSchema="inputSchema"in e?e.inputSchema:t,this.jsonSchemaExtra=e.jsonSchemaExtra}static isInstance(t){return typeof t=="object"&&t!==null&&um in t&&t[um]===!0}});const rS=Symbol.for("langgraph.state.untracked_value");var hT,fc=(hT=rS,class{constructor(t,e){m(this,hT,!0);m(this,"schema");m(this,"guard");this.schema=t,this.guard=(e==null?void 0:e.guard)??!0}static isInstance(t){return typeof t=="object"&&t!==null&&rS in t}});const lm=Symbol.for("langgraph.state.state_schema");var fT,yi=(fT=lm,class{constructor(t){m(this,fT,!0);this.fields=t}getChannels(){const t={};for(const[e,n]of Object.entries(this.fields))if(Ga.isInstance(n)){const r=La(n.valueSchema);t[e]=new Wh(n.reducer,r)}else if(fc.isInstance(n)){const r=n.schema?La(n.schema):void 0;t[e]=new LV({guard:n.guard,initialValueFactory:r})}else if(zc(n))t[e]=new Wf(La(n));else throw new Error(`Invalid state field "${e}": must be a schema, ReducedValue, UntrackedValue, or ManagedValue`);return t}getJsonSchema(){const t={},e=[];for(const[n,r]of Object.entries(this.fields)){let s;if(Ga.isInstance(r)?(s=Ma(r.valueSchema),r.jsonSchemaExtra&&(s={...s??{},...r.jsonSchemaExtra})):fc.isInstance(r)?s=r.schema?Ma(r.schema):void 0:zc(r)&&(s=Ma(r)),s){t[n]=s;let i=!1;Ga.isInstance(r)?i=La(r.valueSchema)!==void 0:fc.isInstance(r)?i=r.schema?La(r.schema)!==void 0:!1:i=La(r)!==void 0,i||e.push(n)}}return{type:"object",properties:t,required:e.length>0?e:void 0}}getInputJsonSchema(){const t={};for(const[e,n]of Object.entries(this.fields)){let r;Ga.isInstance(n)?(r=Ma(n.inputSchema),n.jsonSchemaExtra&&(r={...r??{},...n.jsonSchemaExtra})):fc.isInstance(n)?r=n.schema?Ma(n.schema):void 0:zc(n)&&(r=Ma(n)),r&&(t[e]=r)}return{type:"object",properties:t}}getChannelKeys(){return Object.entries(this.fields).map(([t])=>t)}getAllKeys(){return Object.keys(this.fields)}async validateInput(t){if(t==null||typeof t!="object")return t;const e={};for(const[n,r]of Object.entries(t)){const s=this.fields[n];if(s===void 0){e[n]=r;continue}let i;if(Ga.isInstance(s)){const[a,o]=Pu(r);if(a){i=s.valueSchema;const c=await i["~standard"].validate(o);if(c.issues)throw new Error(`Validation failed for field "${n}": ${JSON.stringify(c.issues)}`);e[n]={[jy]:c.value};continue}i=s.inputSchema}else fc.isInstance(s)?i=s.schema:zc(s)&&(i=s);if(i){const a=await i["~standard"].validate(r);if(a.issues)throw new Error(`Validation failed for field "${n}": ${JSON.stringify(a.issues)}`);e[n]=a.value}else e[n]=r}return e}static isInstance(t){return typeof t=="object"&&t!==null&&lm in t&&t[lm]===!0}});function Sw(t,e){const n=Array.isArray(t)?t:[t],r=Array.isArray(e)?e:[e],s=n.map(_s),i=r.map(_s);for(const l of s)(l.id===null||l.id===void 0)&&(l.id=h_(),l.lc_kwargs.id=l.id);let a;for(let l=0;l<i.length;l+=1){const d=i[l];(d.id===null||d.id===void 0)&&(d.id=h_(),d.lc_kwargs.id=d.id),ua.isInstance(d)&&d.id==="__remove_all__"&&(a=l)}if(a!=null)return i.slice(a+1);const o=[...s],c=new Map(o.map((l,d)=>[l.id,d])),u=new Set;for(const l of i){const d=c.get(l.id);if(d!==void 0)ua.isInstance(l)?u.add(l.id):(u.delete(l.id),o[d]=l);else{if(ua.isInstance(l))throw new Error(`Attempting to delete a message with an ID that doesn't exist ('${l.id}')`);c.set(l.id,o.length),o.push(l)}}return o.filter(l=>!u.has(l.id))}new Ga(Yg().default(()=>[]),{inputSchema:Yg(),reducer:Sw,jsonSchemaExtra:{langgraph_type:"messages",description:"A list of chat messages"}});var jV=class{constructor(){m(this,"_map",new Map);m(this,"_extensionCache",new Map)}get(t){return this._map.get(t)}extend(t,e){const n=this.get(t);this._map.set(t,e(n))}remove(t){return this._map.delete(t),this}has(t){return this._map.has(t)}getChannelsForSchema(t){const e={},n=Do(t);for(const[r,s]of Object.entries(n)){const i=this.get(s);i!=null&&i.reducer?e[r]=new Wh(i.reducer.fn,i.default):e[r]=new Wf(i==null?void 0:i.default)}return e}getExtendedChannelSchemas(t,e){if(Object.keys(e).length===0)return t;const n=Object.entries(e).filter(([,i])=>i===!0).sort(([i],[a])=>i.localeCompare(a)).map(([i,a])=>`${i}:${a}`).join("|"),r=this._extensionCache.get(n)??new Map;if(r.has(t))return r.get(t);let s=t;if(e.withReducerSchema||e.withJsonSchemaExtrasAsDescription){const i=Object.entries(Do(t)).map(([a,o])=>{var l;const c=this.get(o);let u=e.withReducerSchema?((l=c==null?void 0:c.reducer)==null?void 0:l.schema)??o:o;if(e.withJsonSchemaExtrasAsDescription&&(c!=null&&c.jsonSchemaExtra)){const d=jo(u)??jo(o),f=JSON.stringify({...c.jsonSchemaExtra,description:d});u=u.describe(`lg:${f}`)}return[a,u]});s=wI(t,Object.fromEntries(i)),Lt(s)&&(s._def.unknownKeys="strip")}return e.asPartial&&(s=ou(s)),r.set(t,s),this._extensionCache.set(n,r),s}};const yC=new jV;function Ja(t){return t==null?!1:!!(yi.isInstance(t)||rr(t)||typeof t=="object"&&"lc_graph_name"in t&&t.lc_graph_name==="AnnotationRoot"||typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length>0&&Object.values(t).every(e=>typeof e=="function"||Mk(e)))}function DV(t){if(typeof t!="object"||t==null)return!1;const e=t,n="state"in e&&Ja(e.state),r="stateSchema"in e&&Ja(e.stateSchema),s="input"in e&&Ja(e.input);return!(!n&&!r&&!s||"input"in e&&e.input!=null&&!Ja(e.input)||"output"in e&&e.output!=null&&!Ja(e.output))}const Ds="__root__",ja="__default_error_handler__",Jh=Symbol.for("langgraph.state.partial");var UV=class extends RV{constructor(e,n){super();m(this,"channels",{});m(this,"waitingEdges",new Set);m(this,"_schemaDefinition");m(this,"_schemaRuntimeDefinition");m(this,"_inputDefinition");m(this,"_inputRuntimeDefinition");m(this,"_outputDefinition");m(this,"_outputRuntimeDefinition");m(this,"_schemaDefinitions",new Map);m(this,"_metaRegistry",yC);m(this,"_configSchema");m(this,"_configRuntimeSchema");m(this,"_interrupt");m(this,"_writer");m(this,"_nodeDefaults",{});const r=this._normalizeToStateGraphInit(e,n),s=r.state??r.stateSchema??r.input;if(!s)throw new Vp;const i=this._getChannelsFromSchema(s);this._schemaDefinition=i,yi.isInstance(s)?this._schemaRuntimeDefinition=s:rr(s)&&(this._schemaRuntimeDefinition=s),r.input?yi.isInstance(r.input)?this._inputRuntimeDefinition=r.input:rr(r.input)?this._inputRuntimeDefinition=r.input:this._inputRuntimeDefinition=Jh:this._inputRuntimeDefinition=Jh,r.output?yi.isInstance(r.output)?this._outputRuntimeDefinition=r.output:rr(r.output)?this._outputRuntimeDefinition=r.output:this._outputRuntimeDefinition=this._schemaRuntimeDefinition:this._outputRuntimeDefinition=this._schemaRuntimeDefinition;const a=r.input?this._getChannelsFromSchema(r.input):i,o=r.output?this._getChannelsFromSchema(r.output):i;this._inputDefinition=a,this._outputDefinition=o,this._addSchema(this._schemaDefinition),this._addSchema(this._inputDefinition),this._addSchema(this._outputDefinition),r.context&&rr(r.context)&&(this._configRuntimeSchema=r.context),this._interrupt=r.interrupt,this._writer=r.writer}setNodeDefaults(e){return e.retryPolicy!==void 0&&(this._nodeDefaults.retryPolicy=e.retryPolicy),e.cachePolicy!==void 0&&(this._nodeDefaults.cachePolicy=typeof e.cachePolicy=="boolean"?e.cachePolicy?{}:void 0:e.cachePolicy),e.timeout!==void 0&&(this._nodeDefaults.timeout=Ng(e.timeout)),e.errorHandler!==void 0&&(this._nodeDefaults.errorHandler=e.errorHandler),this}_createDefaultErrorHandlerSpec(){const e=this._nodeDefaults.errorHandler;if(e!==void 0)return{runnable:new bs({func:(n,r)=>{var i;const s=(i=r==null?void 0:r.configurable)==null?void 0:i[Mg];return e(n,s,r)},name:ja,trace:!1}),metadata:void 0,input:this._schemaDefinition,retryPolicy:void 0,cachePolicy:void 0,isErrorHandler:!0}}_normalizeToStateGraphInit(e,n){if(DV(e)){if(rr(n)||i_.isInstance(n))return{...e,context:n};const r=n;return{...e,input:e.input??(r==null?void 0:r.input),output:e.output??(r==null?void 0:r.output),context:e.context??(r==null?void 0:r.context),interrupt:e.interrupt??(r==null?void 0:r.interrupt),writer:e.writer??(r==null?void 0:r.writer),nodes:e.nodes??(r==null?void 0:r.nodes)}}if(Ja(e)){if(rr(n)||i_.isInstance(n))return{state:e,context:n};const r=n;return{state:e,input:r==null?void 0:r.input,output:r==null?void 0:r.output,context:r==null?void 0:r.context,interrupt:r==null?void 0:r.interrupt,writer:r==null?void 0:r.writer,nodes:r==null?void 0:r.nodes}}if(zV(e))return{state:FV(e.channels)};throw new Vp}_getChannelsFromSchema(e){if(yi.isInstance(e))return e.getChannels();if(rr(e))return this._metaRegistry.getChannelsForSchema(e);if(typeof e=="object"&&"lc_graph_name"in e&&e.lc_graph_name==="AnnotationRoot")return e.spec;if(typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length>0)return e;throw new Vp("Invalid schema type. Expected StateSchema, Zod object, AnnotationRoot, or StateDefinition.")}get allEdges(){return new Set([...this.edges,...Array.from(this.waitingEdges).flatMap(([e,n])=>e.map(r=>[r,n]))])}_addSchema(e){if(!this._schemaDefinitions.has(e)){this._schemaDefinitions.set(e,e);for(const[n,r]of Object.entries(e)){let s;if(typeof r=="function"?s=r():s=r,this.channels[n]!==void 0){if(!this.channels[n].equals(s)&&s.lc_graph_name!=="LastValue")throw new Error(`Channel "${n}" already exists with a different type.`)}else this.channels[n]=s}}}addNode(...e){function n(s){return s.length>=1&&typeof s[0]!="string"}const r=n(e)?Array.isArray(e[0])?e[0]:Object.entries(e[0]).map(([s,i])=>[s,i]):[[e[0],e[1],e[2]]];if(r.length===0)throw new Error("No nodes provided in `addNode`");for(const[s,i,a]of r){if(s in this.channels)throw new Error(`${s} is already being used as a state attribute (a.k.a. a channel), cannot also be used as a node name.`);for(const h of["|",":"])if(s.includes(h))throw new Error(`"${h}" is a reserved character and is not allowed in node names.`);if(this.warnIfCompiled("Adding a node to a graph that has already been compiled. This will not be reflected in the compiled graph."),s in this.nodes)throw new Error(`Node \`${s}\` already present.`);if(s==="__end__"||s==="__start__")throw new Error(`Node \`${s}\` is reserved.`);let o=this._schemaDefinition;(a==null?void 0:a.input)!==void 0&&(o=this._getChannelsFromSchema(a.input)),this._addSchema(o);let c;ze.isRunnable(i)?c=i:typeof i=="function"?c=new bs({func:i,name:s,trace:!1}):c=hn(i);const u=a==null?void 0:a.cachePolicy;let l;u!==void 0&&(l=typeof u=="boolean"?u?{}:!1:u);let d;if((a==null?void 0:a.errorHandler)!==void 0){if(d=`__error_handler__${s}`,d in this.nodes)throw new Error(`Cannot add error handler to node \`${s}\`: the reserved name \`${d}\` is already in use. StateGraph registers \`__error_handler__<nodeName>\` when you pass \`errorHandler\` in addNode options. Remove or rename the existing node with that name (for example, you may have added it manually).`);const h=a.errorHandler,p={runnable:new bs({func:(g,y)=>{var _;const b=(_=y==null?void 0:y.configurable)==null?void 0:_[Mg];return h(g,b,y)},name:d,trace:!1}),metadata:void 0,input:o??this._schemaDefinition,retryPolicy:void 0,cachePolicy:void 0,isErrorHandler:!0};this.nodes[d]=p}const f={runnable:c,retryPolicy:a==null?void 0:a.retryPolicy,cachePolicy:l,timeout:Ng(a==null?void 0:a.timeout),metadata:a==null?void 0:a.metadata,input:o??this._schemaDefinition,subgraphs:_w(c)?[c]:a==null?void 0:a.subgraphs,ends:a==null?void 0:a.ends,defer:a==null?void 0:a.defer,errorHandlerNode:d};this.nodes[s]=f}return this}addEdge(e,n){if(typeof e=="string")return super.addEdge(e,n);this.compiled&&console.warn("Adding an edge to a graph that has already been compiled. This will not be reflected in the compiled graph.");for(const r of e){if(r==="__end__")throw new Error("END cannot be a start node");if(!Object.keys(this.nodes).some(s=>s===r))throw new Error(`Need to add a node named "${r}" first`)}if(n==="__end__")throw new Error("END cannot be an end node");if(!Object.keys(this.nodes).some(r=>r===n))throw new Error(`Need to add a node named "${n}" first`);return this.waitingEdges.add([e,n]),this}addSequence(e){const n=Array.isArray(e)?e:Object.entries(e);if(n.length===0)throw new Error("Sequence requires at least one node.");let r;for(const[s,i,a]of n){if(s in this.nodes)throw new Error(`Node names must be unique: node with the name "${s}" already exists.`);const o=s;this.addNode(s,i,a),r!=null&&this.addEdge(r,o),r=o}return this}compile({checkpointer:e,store:n,cache:r,interruptBefore:s,interruptAfter:i,name:a,description:o,transformers:c}={}){const u=this._createDefaultErrorHandlerSpec();if(u!==void 0){if(ja in this.nodes)throw new Error(`Cannot apply a default error handler: the reserved node name \`${ja}\` is already in use. setNodeDefaults({ errorHandler }) registers a node with that name; rename the conflicting node.`);this.nodes[ja]=u}try{return this._compileResolved({checkpointer:e,store:n,cache:r,interruptBefore:s,interruptAfter:i,name:a,description:o,transformers:c,defaultErrorHandlerNode:u!==void 0?ja:void 0})}finally{u!==void 0&&delete this.nodes[ja]}}_compileResolved({checkpointer:e,store:n,cache:r,interruptBefore:s,interruptAfter:i,name:a,description:o,transformers:c,defaultErrorHandlerNode:u}){this.validate([...Array.isArray(s)?s:[],...Array.isArray(i)?i:[]]);const l=Object.keys(this._schemaDefinitions.get(this._outputDefinition)),d=l.length===1&&l[0]===Ds?Ds:l,f=Object.keys(this.channels),h=f.length===1&&f[0]===Ds?Ds:f,p=this._interrupt,g=new BV({builder:this,checkpointer:e,interruptAfter:i,interruptBefore:s,autoValidate:!1,nodes:{},channels:{...this.channels,[un]:new Zo},inputChannels:un,outputChannels:d,streamChannels:h,streamMode:"updates",store:n,cache:r,name:a,description:o,userInterrupt:p,streamTransformers:c});g.attachNode(un);const y=this._nodeDefaults,b=y.retryPolicy!==void 0||y.cachePolicy!==void 0||y.timeout!==void 0||u!==void 0;for(const[_,w]of Object.entries(this.nodes)){const v=w.isErrorHandler===!0,A=b?{...w,retryPolicy:w.retryPolicy??y.retryPolicy,cachePolicy:v||w.cachePolicy===!1?void 0:w.cachePolicy??y.cachePolicy,timeout:w.timeout??y.timeout,errorHandlerNode:!v&&u!==void 0&&w.errorHandlerNode===void 0?u:w.errorHandlerNode}:w;g.attachNode(_,A)}g.attachBranch(un,Av,sS(),{withReader:!1});for(const[_]of Object.entries(this.nodes))g.attachBranch(_,Av,sS(),{withReader:!1});for(const[_,w]of this.edges)g.attachEdge(_,w);for(const[_,w]of this.waitingEdges)g.attachEdge(_,w);for(const[_,w]of Object.entries(this.branches))for(const[v,A]of Object.entries(w))g.attachBranch(_,v,A);return g.validate()}};function FV(t){const e={};for(const[n,r]of Object.entries(t))e[n]=a_(r);return e}var BV=class extends pC{constructor({description:e,...n}){super(n);m(this,"description");m(this,"_metaRegistry",yC);this.description=e}attachNode(e,n){let r;e==="__start__"?r=Object.entries(this.builder._schemaDefinitions.get(this.builder._inputDefinition)).map(([u])=>u):r=Object.keys(this.builder.channels);function s(u){if(Xt(u))return u.graph===ar.PARENT?null:u._updateAsTuples();if(Array.isArray(u)&&u.length>0&&u.some(l=>Xt(l))){const l=[];for(const d of u)if(Xt(d)){if(d.graph===ar.PARENT)continue;l.push(...d._updateAsTuples())}else l.push([Ds,d]);return l}else if(u!=null)return[[Ds,u]];return null}const i=e,a=async u=>{if(u==null||u.length===0)return u;const l=this.builder._schemaRuntimeDefinition;if(yi.isInstance(l)){const d=new Set(l.getChannelKeys());return Promise.all(u.map(async([f,h])=>{if(!d.has(f))return[f,h];const p=await l.validateInput({[f]:h});return[f,Object.prototype.hasOwnProperty.call(p,f)?p[f]:h]}))}if(rr(l)){const d=new Set(Object.keys(Do(l)));if(u.filter(([p])=>d.has(p)).length===0)return u;const f=ou(this._metaRegistry.getExtendedChannelSchemas(l,{withReducerSchema:!0})),h=ou(l);return u.map(([p,g])=>{if(!d.has(p))return[p,g];const[y,b]=Pu(g);if(y){const w=Wa(h,{[p]:b});return[p,Object.prototype.hasOwnProperty.call(w,p)?{[jy]:w[p]}:g]}const _=Wa(f,{[p]:g});return[p,Object.prototype.hasOwnProperty.call(_,p)?_[p]:g]})}return u};async function o(u){if(u){if(Xt(u))return u.graph===ar.PARENT?null:a(u._updateAsTuples().filter(([l])=>r.includes(l)));if(Array.isArray(u)&&u.length>0&&u.some(Xt)){const l=[];for(const d of u)if(Xt(d)){if(d.graph===ar.PARENT)continue;l.push(...d._updateAsTuples().filter(([f])=>r.includes(f)))}else{const f=await o(d);f&&l.push(...f??[])}return a(l)}else{if(typeof u=="object"&&!Array.isArray(u))return a(Object.entries(u).filter(([l])=>r.includes(l)));{const l=Array.isArray(u)?"array":typeof u;throw new ft(`Expected node "${i.toString()}" to return an object or an array containing at least one Command object, received ${l}`,{lc_error_code:"INVALID_GRAPH_NODE_RETURN_VALUE"})}}}else return null}const c=[{value:pa,mapper:new bs({func:r.length&&r[0]===Ds?s:o,trace:!1,recurse:!1})}];if(e==="__start__")this.nodes[e]=new Fu({tags:[Hn],triggers:[un],channels:[un],writers:[new Pn(c,[Hn])]});else{const u=(n==null?void 0:n.input)??this.builder._schemaDefinition,l=Object.fromEntries(Object.keys(this.builder._schemaDefinitions.get(u)).map(g=>[g,g])),d=Object.keys(l).length===1&&Ds in l,f=`branch:to:${e}`;this.channels[f]=n!=null&&n.defer?new I9:new Zo(!1);const h=n==null?void 0:n.cachePolicy,p=h===!1?void 0:h;this.nodes[e]=new Fu({triggers:[f],channels:d?Object.keys(l):l,writers:[new Pn(c,[Hn])],mapper:d?void 0:g=>Object.fromEntries(Object.entries(g).filter(([y])=>y in l)),bound:n==null?void 0:n.runnable,metadata:n==null?void 0:n.metadata,retryPolicy:n==null?void 0:n.retryPolicy,cachePolicy:p,timeout:n==null?void 0:n.timeout,subgraphs:n==null?void 0:n.subgraphs,ends:n==null?void 0:n.ends,isErrorHandler:n==null?void 0:n.isErrorHandler,errorHandlerNode:n==null?void 0:n.errorHandlerNode})}}attachEdge(e,n){if(n!=="__end__"){if(typeof e=="string")this.nodes[e].writers.push(new Pn([{channel:`branch:to:${n}`,value:null}],[Hn]));else if(Array.isArray(e)){const r=`join:${e.join("+")}:${n}`;this.channels[r]=this.builder.nodes[n].defer?new NV(new Set(e)):new PV(new Set(e)),this.nodes[n].triggers.push(r);for(const s of e)this.nodes[s].writers.push(new Pn([{channel:r,value:s}],[Hn]))}}}attachBranch(e,n,r,s={withReader:!0}){const i=async(a,o)=>{const c=a.filter(l=>l!==ht);if(!c.length)return;const u=c.map(l=>Wn(l)?l:{channel:l==="__end__"?l:`branch:to:${l}`,value:e});await Pn.doWrite({...o,tags:(o.tags??[]).concat([Hn])},u)};this.nodes[e].writers.push(r.run(i,s.withReader?a=>L9.doRead(a,this.streamChannels??this.outputChannels,!0):void 0))}async _validateInput(e){if(e==null)return e;const n=this.builder._inputRuntimeDefinition,r=this.builder._schemaRuntimeDefinition;if(yi.isInstance(n)){if(Xt(e)){const i=e;return e.update&&(i.update=await n.validateInput(Array.isArray(e.update)?Object.fromEntries(e.update):e.update)),i}return await n.validateInput(e)}if(n===Jh&&yi.isInstance(r)){if(Xt(e)){const i=e;return e.update&&(i.update=await r.validateInput(Array.isArray(e.update)?Object.fromEntries(e.update):e.update)),i}return await r.validateInput(e)}const s=(()=>{const i=a=>{if(a!=null)return this._metaRegistry.getExtendedChannelSchemas(a,{withReducerSchema:!0})};if(rr(n))return i(n);if(n===Jh)return rr(r)?ou(i(r)):void 0})();if(Xt(e)){const i=e;if(e.update&&s!=null){const a=Array.isArray(e.update)?Object.fromEntries(e.update):e.update,o=Wa(s,a);i.update=Object.fromEntries(Object.keys(a).map(c=>[c,o[c]]))}return i}return s!=null?Wa(s,e):e}isInterrupted(e){return Dy(e)}async _validateContext(e){const n=this.builder._configRuntimeSchema;return rr(n)&&Wa(n,e),e}};function zV(t){return typeof t=="object"&&t!==null&&t.channels!==void 0}function HV(t){if(Wn(t))return[t];const e=[];Xt(t)?e.push(t):Array.isArray(t)&&e.push(...t.filter(Xt));const n=[];for(const r of e){if(r.graph===ar.PARENT)throw new qI(r);Wn(r.goto)||typeof r.goto=="string"?n.push(r.goto):Array.isArray(r.goto)&&n.push(...r.goto)}return n}function sS(){return new fC({path:new bs({func:HV,tags:[Hn],trace:!1,recurse:!1,name:"<control_branch>"})})}const wC=t=>Array.isArray(t)&&t.every(Et),VV=t=>typeof t=="object"&&t!=null&&"messages"in t&&wC(t.messages),KV=t=>typeof t=="object"&&t!=null&&"lg_tool_call"in t;var WV=class extends bs{constructor(e,n){const{name:r,tags:s,handleToolErrors:i}=n??{};super({name:r,tags:s,func:(a,o)=>this.run(a,o)});m(this,"tools");m(this,"handleToolErrors",!0);m(this,"trace",!1);this.tools=e,this.handleToolErrors=i??this.handleToolErrors}async runTool(e,n,r){var i;const s=this.tools.find(a=>a.name===e.name);try{if(s===void 0)throw new Error(`Tool "${e.name}" not found.`);const a={...e,type:"tool_call"},o={...n,state:r,toolCallId:e.id??"",config:n,context:n.context,store:n.store??null,writer:n.writer??((i=n.configurable)==null?void 0:i.writer)??null},c=await s.invoke(a,o);return Et(c)&&c.getType()==="tool"||Xt(c)?c:new fn({status:"success",name:s.name,content:typeof c=="string"?c:JSON.stringify(c),tool_call_id:e.id})}catch(a){if(!this.handleToolErrors||Xi(a))throw a;return new fn({status:"error",content:`Error: ${a.message}
|
|
322
|
-
Please fix your mistakes.`,name:e.name,tool_call_id:e.id??""})}}async run(e,n){var a;let r;if(KV(e)){const{lg_tool_call:o,...c}=e;r=[await this.runTool(o,n,c)]}else{let o;if(wC(e))o=e;else if(VV(e))o=e.messages;else throw new Error("ToolNode only accepts BaseMessage[] or { messages: BaseMessage[] } as input.");const c=new Set(o.filter(l=>l.getType()==="tool").map(l=>l.tool_call_id));let u;for(let l=o.length-1;l>=0;l-=1){const d=o[l];if(Cr(d)){u=d;break}}if(u==null||!Cr(u))throw new Error("ToolNode only accepts AIMessages as input.");r=await Promise.all(((a=u.tool_calls)==null?void 0:a.filter(l=>l.id==null||!c.has(l.id)).map(l=>this.runTool(l,n,e)))??[])}if(!r.some(Xt))return Array.isArray(e)?r:{messages:r};const s=[];let i=null;for(const o of r)Xt(o)?o.graph===ar.PARENT&&Array.isArray(o.goto)&&o.goto.every(c=>Wn(c))?i?i.goto.push(...o.goto):i=new ar({graph:ar.PARENT,goto:o.goto}):s.push(o):s.push(Array.isArray(e)?[o]:{messages:[o]});return i&&s.push(i),s}};const dm=/<name>(.*?)<\/name>/s,hm=/<content>(.*?)<\/content>/s;function ZV(t){if(!(Et(t)&&(Cr(t)||Po(t)&&yh(t)))||!t.name)return t;const{name:e}=t;if(typeof t.content=="string")return new De({...Object.keys(t.lc_kwargs??{}).length>0?t.lc_kwargs:t,content:`<name>${e}</name><content>${t.content}</content>`,name:void 0});const n=[];let r=0;for(const s of t.content)typeof s=="string"?(r+=1,n.push(`<name>${e}</name><content>${s}</content>`)):typeof s=="object"&&"type"in s&&s.type==="text"?(r+=1,n.push({...s,text:`<name>${e}</name><content>${s.text}</content>`})):n.push(s);return r||n.unshift({type:"text",text:`<name>${e}</name><content></content>`}),new De({...t.lc_kwargs,content:n,name:void 0})}function qV(t){if(!Cr(t)||!t.content)return t;let e=[],n;if(Array.isArray(t.content))e=t.content.filter(r=>{if(r.type==="text"&&typeof r.text=="string"){const s=r.text.match(dm),i=r.text.match(hm);return s&&(!i||i[1]==="")?(n=s[1],!1):!0}return!0}).map(r=>{if(r.type==="text"&&typeof r.text=="string"){const s=r.text.match(dm),i=r.text.match(hm);return!s||!i?r:(n=s[1],{...r,text:i[1]})}return r});else{const r=t.content,s=r.match(dm),i=r.match(hm);if(!s||!i)return t;n=s[1],e=i[1]}return new De({...Object.keys(t.lc_kwargs??{}).length>0?t.lc_kwargs:t,content:e,name:n})}function iS(t,e){let n,r;if(e==="inline")n=ZV,r=qV;else throw new Error(`Invalid agent name mode: ${e}. Needs to be one of: "inline"`);function s(i){return i.map(n)}return fr.from([en.from(s),t,en.from(r)])}function GV(t){if(typeof t=="string"||Et(t)&&t._getType()==="system")return t;if(typeof t=="function")return async e=>t(e.messages);if(ze.isRunnable(t))return en.from(e=>e.messages).pipe(t);throw new Error(`Unexpected type for messageModifier: ${typeof t}`)}const fd="prompt";function JV(t){let e;if(t==null)e=en.from(n=>n.messages).withConfig({runName:fd});else if(typeof t=="string"){const n=new lr(t);e=en.from(r=>[n,...r.messages??[]]).withConfig({runName:fd})}else if(Et(t)&&t._getType()==="system")e=en.from(n=>[t,...n.messages]).withConfig({runName:fd});else if(typeof t=="function")e=en.from(t).withConfig({runName:fd});else if(ze.isRunnable(t))e=t;else throw new Error(`Got unexpected type for 'prompt': ${typeof t}`);return e}function w_(t){return ze.isRunnable(t)}function aS(t,e,n){if([t,e,n].filter(s=>s!=null).length>1)throw new Error("Expected only one of prompt, stateModifier, or messageModifier, got multiple values");let r=t;return e!=null?r=e:n!=null&&(r=GV(n)),JV(r)}function Go(t){return"invoke"in t&&typeof t.invoke=="function"&&"_modelType"in t}function Jo(t){return"_queuedMethodOperations"in t&&"_model"in t&&typeof t._model=="function"}function oS(t){return Go(t)?"bindTools"in t&&typeof t.bindTools=="function":!1}async function YV(t,e){let n=t;if(fr.isRunnableSequence(n)&&(n=n.steps.find(o=>dn.isRunnableBinding(o)||Go(o)||Jo(o))||n),Jo(n)&&(n=await n._model()),!dn.isRunnableBinding(n))return!0;let r=n.kwargs!=null&&typeof n.kwargs=="object"&&"tools"in n.kwargs&&Array.isArray(n.kwargs.tools)?n.kwargs.tools??null:n.config!=null&&typeof n.config=="object"&&"tools"in n.config&&Array.isArray(n.config.tools)?n.config.tools??null:null;if(r!=null&&r.length===1&&"functionDeclarations"in r[0]&&(r=r[0].functionDeclarations),r==null)return!0;if(e.length!==r.length)throw new Error("Number of tools in the model.bindTools() and tools passed to createReactAgent must match");const s=new Set(e.flatMap(o=>w_(o)?o.name:[])),i=new Set;for(const o of r){let c;if("type"in o&&o.type==="function")c=o.function.name;else if("name"in o)c=o.name;else if("toolSpec"in o&&"name"in o.toolSpec)c=o.toolSpec.name;else continue;c&&i.add(c)}const a=[...s].filter(o=>!i.has(o));if(a.length>0)throw new Error(`Missing tools '${a}' in the model.bindTools().Tools in the model.bindTools() must match the tools passed to createReactAgent.`);return!1}const fm=(t,e)=>{if(oS(t))return t.bindTools(e);if(dn.isRunnableBinding(t)&&oS(t.bound)){const n=t.bound.bindTools(e);return dn.isRunnableBinding(n)?new dn({bound:n.bound,config:{...t.config,...n.config},kwargs:{...t.kwargs,...n.kwargs},configFactories:n.configFactories??t.configFactories}):new dn({bound:n,config:t.config,kwargs:t.kwargs,configFactories:t.configFactories})}return null};async function XV(t,e){const n=fm(t,e);if(n)return n;if(Jo(t)){const r=fm(await t._model(),e);if(r)return r}if(fr.isRunnableSequence(t)){const r=t.steps.findIndex(s=>dn.isRunnableBinding(s)||Go(s)||Jo(s));if(r>=0){const s=fm(t.steps[r],e);if(s){const i=t.steps.slice();return i.splice(r,1,s),fr.from(i)}}}throw new Error(`llm ${t} must define bindTools method.`)}async function QV(t){let e=t;if(fr.isRunnableSequence(e)&&(e=e.steps.find(n=>dn.isRunnableBinding(n)||Go(n)||Jo(n))||e),Jo(e)&&(e=await e._model()),dn.isRunnableBinding(e)&&(e=e.bound),!Go(e))throw new Error(`Expected \`llm\` to be a ChatModel or RunnableBinding (e.g. llm.bind_tools(...)) with invoke() and generate() methods, got ${e.constructor.name}`);return e}const eK=()=>fa.Root({messages:fa({reducer:Sw,default:()=>[]}),structuredResponse:fa}),tK=fa.Root({llmInputMessages:fa({reducer:(t,e)=>Sw([],e),default:()=>[]})});function nK(t){const{llm:e,tools:n,messageModifier:r,stateModifier:s,prompt:i,stateSchema:a,contextSchema:o,checkpointSaver:c,checkpointer:u,interruptBefore:l,interruptAfter:d,store:f,responseFormat:h,preModelHook:p,postModelHook:g,name:y,description:b,version:_="v1",includeAgentName:w}=t;let v,A;Array.isArray(n)?(v=n,A=new WV(v.filter(w_))):(v=n.tools,A=n);let S=null;const x=async M=>{if(S)return S;let Z;await YV(M,v)?Z=await XV(M,v):Z=M;const re=aS(i,s,r),ae=w==="inline"?iS(Z,w):Z;return S=re.pipe(ae),S},E=async(M,Z,re)=>{const ae=await M(Z,re);return aS(i,s,r).pipe(w==="inline"?iS(ae,w):ae)},$=new Set(v.filter(w_).filter(M=>"returnDirect"in M&&M.returnDirect).map(M=>M.name));function k(M){const{messages:Z,llmInputMessages:re,...ae}=M;return re!=null&&re.length>0?{messages:re,...ae}:{messages:Z,...ae}}const C=async(M,Z)=>{if(h==null)throw new Error("Attempted to generate structured output with no passed response schema. Please contact us for help.");const re=[...M.messages];let ae;const X=typeof e=="function"?await e(M,Z):await QV(e);if(!Go(X))throw new Error(`Expected \`llm\` to be a ChatModel with .withStructuredOutput() method, got ${X.constructor.name}`);if(typeof h=="object"&&"schema"in h){const{prompt:Se,schema:ue,...I}=h;ae=X.withStructuredOutput(ue,I),Se!=null&&re.unshift(new lr({content:Se}))}else ae=X.withStructuredOutput(h);const se=await ae.invoke(re,Z);if(se==null)throw new 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:se}},D=async(M,Z)=>{const re=await(typeof e=="function"?await E(e,M,Z):await x(e)).invoke(k(M),Z);return re.name=y,re.lc_kwargs.name=y,{messages:[re]}},B=new UV(a??eK(),o).addNode("tools",A);if(!("messages"in B._schemaDefinition))throw new Error("Missing required `messages` key in state schema.");const z=B,q=M=>Object.fromEntries(Object.entries(M).filter(([Z,re])=>re!=null));let W="agent",me;return p!=null?(z.addNode("pre_model_hook",p).addEdge("pre_model_hook","agent"),W="pre_model_hook",me=fa.Root({...B._schemaDefinition,...tK.spec})):W="agent",z.addNode("agent",D,{input:me}).addEdge(un,W),g!=null&&z.addNode("post_model_hook",g).addEdge("agent","post_model_hook").addConditionalEdges("post_model_hook",M=>{var Se;const{messages:Z}=M,re=new Set(Z.filter(ca).map(ue=>ue.tool_call_id));let ae;for(let ue=Z.length-1;ue>=0;ue-=1){const I=Z[ue];if(Cr(I)){ae=I;break}}const X=((Se=ae==null?void 0:ae.tool_calls)==null?void 0:Se.filter(ue=>ue.id==null||!re.has(ue.id)))??[],se=Z[Z.length-1];return X.length>0?_==="v2"?X.map(ue=>new wa("tools",{...M,lg_tool_call:ue})):"tools":se&&ca(se)?W:h!=null?"generate_structured_response":ht},q({tools:"tools",[W]:W,generate_structured_response:h!=null?"generate_structured_response":null,[ht]:h!=null?null:ht})),h!==void 0&&B.addNode("generate_structured_response",C).addEdge("generate_structured_response",ht),g==null&&z.addConditionalEdges("agent",M=>{var ae;const{messages:Z}=M,re=Z[Z.length-1];return!Cr(re)||!((ae=re.tool_calls)!=null&&ae.length)?h!=null?"generate_structured_response":ht:_==="v2"?re.tool_calls.map(X=>new wa("tools",{...M,lg_tool_call:X})):"tools"},q({tools:"tools",generate_structured_response:h!=null?"generate_structured_response":null,[ht]:h!=null?null:ht})),$.size>0?z.addConditionalEdges("tools",M=>{const Z=M;for(let re=Z.messages.length-1;re>=0;re-=1){const ae=Z.messages[re];if(!ca(ae))break;if(ae.name!==void 0&&$.has(ae.name))return ht}return W},q({[W]:W,[ht]:ht})):z.addEdge("tools",W),z.compile({checkpointer:u??c,interruptBefore:l,interruptAfter:d,store:f,name:y,description:b})}function pd(t,e){return t.lc_error_code=e,t.message=`${t.message}
|
|
323
|
-
|
|
324
|
-
Troubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${e}/
|
|
325
|
-
`,t}function Oe(t,e,n,r,s){if(typeof e=="function"?t!==e||!0:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return e.set(t,n),n}function N(t,e,n,r){if(n==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!r:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return n==="m"?r:n==="a"?r.call(t):r?r.value:e.get(t)}let bC=function(){const{crypto:t}=globalThis;if(t!=null&&t.randomUUID)return bC=t.randomUUID.bind(t),t.randomUUID();const e=new Uint8Array(1),n=t?()=>t.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,r=>(+r^n()&15>>+r/4).toString(16))};function b_(t){return typeof t=="object"&&t!==null&&("name"in t&&t.name==="AbortError"||"message"in t&&String(t.message).includes("FetchRequestCanceledException"))}const v_=t=>{if(t instanceof Error)return t;if(typeof t=="object"&&t!==null){try{if(Object.prototype.toString.call(t)==="[object Error]"){const e=new Error(t.message,t.cause?{cause:t.cause}:{});return t.stack&&(e.stack=t.stack),t.cause&&!e.cause&&(e.cause=t.cause),t.name&&(e.name=t.name),e}}catch{}try{return new Error(JSON.stringify(t))}catch{}}return new Error(t)};class ye extends Error{}let An=class S_ extends ye{constructor(e,n,r,s){super(`${S_.makeMessage(e,n,r)}`),this.status=e,this.headers=s,this.requestID=s==null?void 0:s.get("x-request-id"),this.error=n;const i=n;this.code=i==null?void 0:i.code,this.param=i==null?void 0:i.param,this.type=i==null?void 0:i.type}static makeMessage(e,n,r){const s=n!=null&&n.message?typeof n.message=="string"?n.message:JSON.stringify(n.message):n?JSON.stringify(n):r;return e&&s?`${e} ${s}`:e?`${e} status code (no body)`:s||"(no status code or body)"}static generate(e,n,r,s){if(!e||!s)return new Zf({message:r,cause:v_(n)});const i=n==null?void 0:n.error;return e===400?new vC(e,i,r,s):e===401?new SC(e,i,r,s):e===403?new AC(e,i,r,s):e===404?new TC(e,i,r,s):e===409?new EC(e,i,r,s):e===422?new IC(e,i,r,s):e===429?new xC(e,i,r,s):e>=500?new kC(e,i,r,s):new S_(e,i,r,s)}},or=class extends An{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},Zf=class extends An{constructor({message:e,cause:n}){super(void 0,void 0,e||"Connection error.",void 0),n&&(this.cause=n)}},qf=class extends Zf{constructor({message:e}={}){super({message:e??"Request timed out."})}},vC=class extends An{},SC=class extends An{},AC=class extends An{},TC=class extends An{},EC=class extends An{},IC=class extends An{},xC=class extends An{},kC=class extends An{};class CC extends ye{constructor(){super("Could not parse response content as the length limit was reached")}}class OC extends ye{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}class Hc extends Error{constructor(e){super(e)}}class $C extends An{constructor(e,n,r){let s="OAuth2 authentication error",i;if(n&&typeof n=="object"){const a=n;i=a.error;const o=a.error_description;o&&typeof o=="string"?s=o:i&&(s=i)}super(e,n,s,r),this.error_code=i}}class rK extends ye{constructor(e,n,r){super(e),this.provider=n,this.cause=r}}const sK=/^[a-z][a-z0-9+.-]*:/i,iK=t=>sK.test(t);let Fn=t=>(Fn=Array.isArray,Fn(t)),cS=Fn;function Aw(t){return typeof t!="object"?{}:t??{}}function uS(t){if(!t)return!0;for(const e in t)return!1;return!0}function aK(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function th(t){return t!=null&&typeof t=="object"&&!Array.isArray(t)}const oK=(t,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new ye(`${t} must be an integer`);if(e<0)throw new ye(`${t} must be a positive integer`);return e},cK=t=>{try{return JSON.parse(t)}catch{return}},Cl=t=>new Promise(e=>setTimeout(e,t)),Ya="6.42.0",uK=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function lK(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}const dK=()=>{var n;const t=lK();if(t==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ya,"X-Stainless-OS":dS(Deno.build.os),"X-Stainless-Arch":lS(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:((n=Deno.version)==null?void 0:n.deno)??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ya,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(t==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ya,"X-Stainless-OS":dS(globalThis.process.platform??"unknown"),"X-Stainless-Arch":lS(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};const e=hK();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ya,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ya,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function hK(){if(typeof navigator>"u"||!navigator)return null;const t=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(const{key:e,pattern:n}of t){const r=n.exec(navigator.userAgent);if(r){const s=r[1]||0,i=r[2]||0,a=r[3]||0;return{browser:e,version:`${s}.${i}.${a}`}}}return null}const lS=t=>t==="x32"?"x32":t==="x86_64"||t==="x64"?"x64":t==="arm"?"arm":t==="aarch64"||t==="arm64"?"arm64":t?`other:${t}`:"unknown",dS=t=>(t=t.toLowerCase(),t.includes("ios")?"iOS":t==="android"?"Android":t==="darwin"?"MacOS":t==="win32"?"Windows":t==="freebsd"?"FreeBSD":t==="openbsd"?"OpenBSD":t==="linux"?"Linux":t?`Other:${t}`:"Unknown");let hS;const fK=()=>hS??(hS=dK());function RC(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function PC(...t){const e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...t)}function NC(t){let e=Symbol.asyncIterator in t?t[Symbol.asyncIterator]():t[Symbol.iterator]();return PC({start(){},async pull(n){const{done:r,value:s}=await e.next();r?n.close():n.enqueue(s)},async cancel(){var n;await((n=e.return)==null?void 0:n.call(e))}})}function MC(t){if(t[Symbol.asyncIterator])return t;const e=t.getReader();return{async next(){try{const n=await e.read();return n!=null&&n.done&&e.releaseLock(),n}catch(n){throw e.releaseLock(),n}},async return(){const n=e.cancel();return e.releaseLock(),await n,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function fS(t){var r,s;if(t===null||typeof t!="object")return;if(t[Symbol.asyncIterator]){await((s=(r=t[Symbol.asyncIterator]()).return)==null?void 0:s.call(r));return}const e=t.getReader(),n=e.cancel();e.releaseLock(),await n}const pK=({headers:t,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)}),LC="RFC3986",jC=t=>String(t),pS={RFC1738:t=>String(t).replace(/%20/g,"+"),RFC3986:jC},mK="RFC1738";let A_=(t,e)=>(A_=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),A_(t,e));const ns=(()=>{const t=[];for(let e=0;e<256;++e)t.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return t})(),pm=1024,gK=(t,e,n,r,s)=>{if(t.length===0)return t;let i=t;if(typeof t=="symbol"?i=Symbol.prototype.toString.call(t):typeof t!="string"&&(i=String(t)),n==="iso-8859-1")return escape(i).replace(/%u[0-9a-f]{4}/gi,function(o){return"%26%23"+parseInt(o.slice(2),16)+"%3B"});let a="";for(let o=0;o<i.length;o+=pm){const c=i.length>=pm?i.slice(o,o+pm):i,u=[];for(let l=0;l<c.length;++l){let d=c.charCodeAt(l);if(d===45||d===46||d===95||d===126||d>=48&&d<=57||d>=65&&d<=90||d>=97&&d<=122||s===mK&&(d===40||d===41)){u[u.length]=c.charAt(l);continue}if(d<128){u[u.length]=ns[d];continue}if(d<2048){u[u.length]=ns[192|d>>6]+ns[128|d&63];continue}if(d<55296||d>=57344){u[u.length]=ns[224|d>>12]+ns[128|d>>6&63]+ns[128|d&63];continue}l+=1,d=65536+((d&1023)<<10|c.charCodeAt(l)&1023),u[u.length]=ns[240|d>>18]+ns[128|d>>12&63]+ns[128|d>>6&63]+ns[128|d&63]}a+=u.join("")}return a};function _K(t){return!t||typeof t!="object"?!1:!!(t.constructor&&t.constructor.isBuffer&&t.constructor.isBuffer(t))}function mS(t,e){if(Fn(t)){const n=[];for(let r=0;r<t.length;r+=1)n.push(e(t[r]));return n}return e(t)}const DC={brackets(t){return String(t)+"[]"},comma:"comma",indices(t,e){return String(t)+"["+e+"]"},repeat(t){return String(t)}},UC=function(t,e){Array.prototype.push.apply(t,Fn(e)?e:[e])};let gS;const zt={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:gK,encodeValuesOnly:!1,format:LC,formatter:jC,indices:!1,serializeDate(t){return(gS??(gS=Function.prototype.call.bind(Date.prototype.toISOString)))(t)},skipNulls:!1,strictNullHandling:!1};function yK(t){return typeof t=="string"||typeof t=="number"||typeof t=="boolean"||typeof t=="symbol"||typeof t=="bigint"}const mm={};function FC(t,e,n,r,s,i,a,o,c,u,l,d,f,h,p,g,y,b){let _=t,w=b,v=0,A=!1;for(;(w=w.get(mm))!==void 0&&!A;){const k=w.get(t);if(v+=1,typeof k<"u"){if(k===v)throw new RangeError("Cyclic object value");A=!0}typeof w.get(mm)>"u"&&(v=0)}if(typeof u=="function"?_=u(e,_):_ instanceof Date?_=f==null?void 0:f(_):n==="comma"&&Fn(_)&&(_=mS(_,function(k){return k instanceof Date?f==null?void 0:f(k):k})),_===null){if(i)return c&&!g?c(e,zt.encoder,y,"key",h):e;_=""}if(yK(_)||_K(_)){if(c){const k=g?e:c(e,zt.encoder,y,"key",h);return[(p==null?void 0:p(k))+"="+(p==null?void 0:p(c(_,zt.encoder,y,"value",h)))]}return[(p==null?void 0:p(e))+"="+(p==null?void 0:p(String(_)))]}const S=[];if(typeof _>"u")return S;let x;if(n==="comma"&&Fn(_))g&&c&&(_=mS(_,c)),x=[{value:_.length>0?_.join(",")||null:void 0}];else if(Fn(u))x=u;else{const k=Object.keys(_);x=l?k.sort(l):k}const E=o?String(e).replace(/\./g,"%2E"):String(e),$=r&&Fn(_)&&_.length===1?E+"[]":E;if(s&&Fn(_)&&_.length===0)return $+"[]";for(let k=0;k<x.length;++k){const C=x[k],D=typeof C=="object"&&typeof C.value<"u"?C.value:_[C];if(a&&D===null)continue;const B=d&&o?C.replace(/\./g,"%2E"):C,z=Fn(_)?typeof n=="function"?n($,B):$:$+(d?"."+B:"["+B+"]");b.set(t,v);const q=new WeakMap;q.set(mm,b),UC(S,FC(D,z,n,r,s,i,a,o,n==="comma"&&g&&Fn(_)?null:c,u,l,d,f,h,p,g,y,q))}return S}function wK(t=zt){if(typeof t.allowEmptyArrays<"u"&&typeof t.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof t.encodeDotInKeys<"u"&&typeof t.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(t.encoder!==null&&typeof t.encoder<"u"&&typeof t.encoder!="function")throw new TypeError("Encoder has to be a function.");const e=t.charset||zt.charset;if(typeof t.charset<"u"&&t.charset!=="utf-8"&&t.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let n=LC;if(typeof t.format<"u"){if(!A_(pS,t.format))throw new TypeError("Unknown format option provided.");n=t.format}const r=pS[n];let s=zt.filter;(typeof t.filter=="function"||Fn(t.filter))&&(s=t.filter);let i;if(t.arrayFormat&&t.arrayFormat in DC?i=t.arrayFormat:"indices"in t?i=t.indices?"indices":"repeat":i=zt.arrayFormat,"commaRoundTrip"in t&&typeof t.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");const a=typeof t.allowDots>"u"?t.encodeDotInKeys?!0:zt.allowDots:!!t.allowDots;return{addQueryPrefix:typeof t.addQueryPrefix=="boolean"?t.addQueryPrefix:zt.addQueryPrefix,allowDots:a,allowEmptyArrays:typeof t.allowEmptyArrays=="boolean"?!!t.allowEmptyArrays:zt.allowEmptyArrays,arrayFormat:i,charset:e,charsetSentinel:typeof t.charsetSentinel=="boolean"?t.charsetSentinel:zt.charsetSentinel,commaRoundTrip:!!t.commaRoundTrip,delimiter:typeof t.delimiter>"u"?zt.delimiter:t.delimiter,encode:typeof t.encode=="boolean"?t.encode:zt.encode,encodeDotInKeys:typeof t.encodeDotInKeys=="boolean"?t.encodeDotInKeys:zt.encodeDotInKeys,encoder:typeof t.encoder=="function"?t.encoder:zt.encoder,encodeValuesOnly:typeof t.encodeValuesOnly=="boolean"?t.encodeValuesOnly:zt.encodeValuesOnly,filter:s,format:n,formatter:r,serializeDate:typeof t.serializeDate=="function"?t.serializeDate:zt.serializeDate,skipNulls:typeof t.skipNulls=="boolean"?t.skipNulls:zt.skipNulls,sort:typeof t.sort=="function"?t.sort:null,strictNullHandling:typeof t.strictNullHandling=="boolean"?t.strictNullHandling:zt.strictNullHandling}}function bK(t,e={}){let n=t;const r=wK(e);let s,i;typeof r.filter=="function"?(i=r.filter,n=i("",n)):Fn(r.filter)&&(i=r.filter,s=i);const a=[];if(typeof n!="object"||n===null)return"";const o=DC[r.arrayFormat],c=o==="comma"&&r.commaRoundTrip;s||(s=Object.keys(n)),r.sort&&s.sort(r.sort);const u=new WeakMap;for(let f=0;f<s.length;++f){const h=s[f];r.skipNulls&&n[h]===null||UC(a,FC(n[h],h,o,c,r.allowEmptyArrays,r.strictNullHandling,r.skipNulls,r.encodeDotInKeys,r.encode?r.encoder:null,r.filter,r.sort,r.allowDots,r.serializeDate,r.format,r.formatter,r.encodeValuesOnly,r.charset,u))}const l=a.join(r.delimiter);let d=r.addQueryPrefix===!0?"?":"";return r.charsetSentinel&&(r.charset==="iso-8859-1"?d+="utf8=%26%2310003%3B&":d+="utf8=%E2%9C%93&"),l.length>0?d+l:""}function vK(t){return bK(t,{arrayFormat:"brackets"})}function SK(t){let e=0;for(const s of t)e+=s.length;const n=new Uint8Array(e);let r=0;for(const s of t)n.set(s,r),r+=s.length;return n}let _S;function Tw(t){let e;return(_S??(e=new globalThis.TextEncoder,_S=e.encode.bind(e)))(t)}let yS;function wS(t){let e;return(yS??(e=new globalThis.TextDecoder,yS=e.decode.bind(e)))(t)}var Jn,Yn;let Gf=class{constructor(){Jn.set(this,void 0),Yn.set(this,void 0),Oe(this,Jn,new Uint8Array),Oe(this,Yn,null)}decode(e){if(e==null)return[];const n=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?Tw(e):e;Oe(this,Jn,SK([N(this,Jn,"f"),n]));const r=[];let s;for(;(s=AK(N(this,Jn,"f"),N(this,Yn,"f")))!=null;){if(s.carriage&&N(this,Yn,"f")==null){Oe(this,Yn,s.index);continue}if(N(this,Yn,"f")!=null&&(s.index!==N(this,Yn,"f")+1||s.carriage)){r.push(wS(N(this,Jn,"f").subarray(0,N(this,Yn,"f")-1))),Oe(this,Jn,N(this,Jn,"f").subarray(N(this,Yn,"f"))),Oe(this,Yn,null);continue}const i=N(this,Yn,"f")!==null?s.preceding-1:s.preceding,a=wS(N(this,Jn,"f").subarray(0,i));r.push(a),Oe(this,Jn,N(this,Jn,"f").subarray(s.index)),Oe(this,Yn,null)}return r}flush(){return N(this,Jn,"f").length?this.decode(`
|
|
326
|
-
`):[]}};Jn=new WeakMap,Yn=new WeakMap;Gf.NEWLINE_CHARS=new Set([`
|
|
327
|
-
`,"\r"]);Gf.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function AK(t,e){for(let s=e??0;s<t.length;s++){if(t[s]===10)return{preceding:s,index:s+1,carriage:!1};if(t[s]===13)return{preceding:s,index:s+1,carriage:!0}}return null}function TK(t){for(let r=0;r<t.length-1;r++){if(t[r]===10&&t[r+1]===10||t[r]===13&&t[r+1]===13)return r+2;if(t[r]===13&&t[r+1]===10&&r+3<t.length&&t[r+2]===13&&t[r+3]===10)return r+4}return-1}const Yh={off:0,error:200,warn:300,info:400,debug:500},bS=(t,e,n)=>{if(t){if(aK(Yh,t))return t;on(n).warn(`${e} was set to ${JSON.stringify(t)}, expected one of ${JSON.stringify(Object.keys(Yh))}`)}};function Vc(){}function md(t,e,n){return!e||Yh[t]>Yh[n]?Vc:e[t].bind(e)}const EK={error:Vc,warn:Vc,info:Vc,debug:Vc};let vS=new WeakMap;function on(t){const e=t.logger,n=t.logLevel??"off";if(!e)return EK;const r=vS.get(e);if(r&&r[0]===n)return r[1];const s={error:md("error",e,n),warn:md("warn",e,n),info:md("info",e,n),debug:md("debug",e,n)};return vS.set(e,[n,s]),s}const Wi=t=>(t.options&&(t.options={...t.options},delete t.options.headers),t.headers&&(t.headers=Object.fromEntries((t.headers instanceof Headers?[...t.headers]:Object.entries(t.headers)).map(([e,n])=>[e,e.toLowerCase()==="authorization"||e.toLowerCase()==="api-key"||e.toLowerCase()==="x-api-key"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":n]))),"retryOfRequestLogID"in t&&(t.retryOfRequestLogID&&(t.retryOf=t.retryOfRequestLogID),delete t.retryOfRequestLogID),t);var pc;let Vu=class Kc{constructor(e,n,r){this.iterator=e,pc.set(this,void 0),this.controller=n,Oe(this,pc,r)}static fromSSEResponse(e,n,r,s){let i=!1;const a=r?on(r):console;async function*o(){if(i)throw new ye("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");i=!0;let c=!1;try{for await(const u of IK(e,n))if(!c){if(u.data.startsWith("[DONE]")){c=!0;continue}if(u.event===null||!u.event.startsWith("thread.")){let l;try{l=JSON.parse(u.data)}catch(d){throw a.error("Could not parse message into JSON:",u.data),a.error("From chunk:",u.raw),d}if(l&&l.error)throw new An(void 0,l.error,void 0,e.headers);yield s?{event:u.event,data:l}:l}else{let l;try{l=JSON.parse(u.data)}catch(d){throw console.error("Could not parse message into JSON:",u.data),console.error("From chunk:",u.raw),d}if(u.event=="error")throw new An(void 0,l.error,l.message,void 0);yield{event:u.event,data:l}}}c=!0}catch(u){if(b_(u))return;throw u}finally{c||n.abort()}}return new Kc(o,n,r)}static fromReadableStream(e,n,r){let s=!1;async function*i(){const o=new Gf,c=MC(e);for await(const u of c)for(const l of o.decode(u))yield l;for(const u of o.flush())yield u}async function*a(){if(s)throw new ye("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let o=!1;try{for await(const c of i())o||c&&(yield JSON.parse(c));o=!0}catch(c){if(b_(c))return;throw c}finally{o||n.abort()}}return new Kc(a,n,r)}[(pc=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){const e=[],n=[],r=this.iterator(),s=i=>({next:()=>{if(i.length===0){const a=r.next();e.push(a),n.push(a)}return i.shift()}});return[new Kc(()=>s(e),this.controller,N(this,pc,"f")),new Kc(()=>s(n),this.controller,N(this,pc,"f"))]}toReadableStream(){const e=this;let n;return PC({async start(){n=e[Symbol.asyncIterator]()},async pull(r){try{const{value:s,done:i}=await n.next();if(i)return r.close();const a=Tw(JSON.stringify(s)+`
|
|
328
|
-
`);r.enqueue(a)}catch(s){r.error(s)}},async cancel(){var r;await((r=n.return)==null?void 0:r.call(n))}})}};async function*IK(t,e){if(!t.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new ye("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 ye("Attempted to iterate over a response with no body");const n=new kK,r=new Gf,s=MC(t.body);for await(const i of xK(s))for(const a of r.decode(i)){const o=n.decode(a);o&&(yield o)}for(const i of r.flush()){const a=n.decode(i);a&&(yield a)}}async function*xK(t){let e=new Uint8Array;for await(const n of t){if(n==null)continue;const r=n instanceof ArrayBuffer?new Uint8Array(n):typeof n=="string"?Tw(n):n;let s=new Uint8Array(e.length+r.length);s.set(e),s.set(r,e.length),e=s;let i;for(;(i=TK(e))!==-1;)yield e.slice(0,i),e=e.slice(i)}e.length>0&&(yield e)}let kK=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;const i={event:this.event,data:this.data.join(`
|
|
329
|
-
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],i}if(this.chunks.push(e),e.startsWith(":"))return null;let[n,r,s]=CK(e,":");return s.startsWith(" ")&&(s=s.substring(1)),n==="event"?this.event=s:n==="data"&&this.data.push(s),null}};function CK(t,e){const n=t.indexOf(e);return n!==-1?[t.substring(0,n),e,t.substring(n+e.length)]:[t,"",""]}async function BC(t,e){const{response:n,requestLogID:r,retryOfRequestLogID:s,startTime:i}=e,a=await(async()=>{var d;if(e.options.stream)return on(t).debug("response",n.status,n.url,n.headers,n.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(n,e.controller,t,e.options.__synthesizeEventData):Vu.fromSSEResponse(n,e.controller,t,e.options.__synthesizeEventData);if(n.status===204)return null;if(e.options.__binaryResponse)return n;const o=n.headers.get("content-type"),c=(d=o==null?void 0:o.split(";")[0])==null?void 0:d.trim();if((c==null?void 0:c.includes("application/json"))||(c==null?void 0:c.endsWith("+json"))){if(n.headers.get("content-length")==="0")return;const h=await n.json();return zC(h,n)}return await n.text()})();return on(t).debug(`[${r}] response parsed`,Wi({retryOfRequestLogID:s,url:n.url,status:n.status,body:a,durationMs:Date.now()-i})),a}function zC(t,e){return!t||typeof t!="object"||Array.isArray(t)?t:Object.defineProperty(t,"_request_id",{value:e.headers.get("x-request-id"),enumerable:!1})}var Wc;let HC=class VC extends Promise{constructor(e,n,r=BC){super(s=>{s(null)}),this.responsePromise=n,this.parseResponse=r,Wc.set(this,void 0),Oe(this,Wc,e)}_thenUnwrap(e){return new VC(N(this,Wc,"f"),this.responsePromise,async(n,r)=>zC(e(await this.parseResponse(n,r),r),r.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){const[e,n]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:n,request_id:n.headers.get("x-request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(N(this,Wc,"f"),e))),this.parsedPromise}then(e,n){return this.parse().then(e,n)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}};Wc=new WeakMap;var gd;let Jf=class{constructor(e,n,r,s){gd.set(this,void 0),Oe(this,gd,e),this.options=s,this.response=n,this.body=r}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){const e=this.nextPageRequestOptions();if(!e)throw new ye("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await N(this,gd,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(gd=new WeakMap,Symbol.asyncIterator)](){for await(const e of this.iterPages())for(const n of e.getPaginatedItems())yield n}},OK=class extends HC{constructor(e,n,r){super(e,n,async(s,i)=>new r(s,i.response,await BC(s,i),i.options))}async*[Symbol.asyncIterator](){const e=await this;for await(const n of e)yield n}},Ni=class extends Jf{constructor(e,n,r,s){super(e,n,r,s),this.data=r.data||[],this.object=r.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}};class It extends Jf{constructor(e,n,r,s){super(e,n,r,s),this.data=r.data||[],this.has_more=r.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){var r;const e=this.getPaginatedItems(),n=(r=e[e.length-1])==null?void 0:r.id;return n?{...this.options,query:{...Aw(this.options.query),after:n}}:null}}class mn extends Jf{constructor(e,n,r,s){super(e,n,r,s),this.data=r.data||[],this.has_more=r.has_more||!1,this.last_id=r.last_id||""}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){const e=this.last_id;return e?{...this.options,query:{...Aw(this.options.query),after:e}}:null}}class Ys extends Jf{constructor(e,n,r,s){super(e,n,r,s),this.data=r.data||[],this.has_more=r.has_more||!1,this.next=r.next||null}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){const e=this.next;return e?{...this.options,query:{...Aw(this.options.query),after:e}}:null}}const $K={jwt:"urn:ietf:params:oauth:token-type:jwt",id:"urn:ietf:params:oauth:token-type:id_token"},RK="urn:ietf:params:oauth:grant-type:token-exchange";class PK{constructor(e,n){this.cachedToken=null,this.refreshPromise=null,this.tokenExchangeUrl="https://auth.openai.com/oauth/token",this.config=e,this.fetch=n??RC()}async getToken(){if(!this.cachedToken||this.isTokenExpired(this.cachedToken)){if(this.refreshPromise)return await this.refreshPromise;this.refreshPromise=this.refreshToken();try{return await this.refreshPromise}finally{this.refreshPromise=null}}return this.needsRefresh(this.cachedToken)&&!this.refreshPromise&&(this.refreshPromise=this.refreshToken().finally(()=>{this.refreshPromise=null})),this.cachedToken.token}async refreshToken(){const e=await this.config.provider.getToken(),n={grant_type:RK,subject_token:e,subject_token_type:$K[this.config.provider.tokenType],identity_provider_id:this.config.identityProviderId,service_account_id:this.config.serviceAccountId};this.config.clientId&&(n.client_id=this.config.clientId);const r=await this.fetch(this.tokenExchangeUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!r.ok){const o=await r.text();let c;try{c=JSON.parse(o)}catch{}throw r.status===400||r.status===401||r.status===403?new $C(r.status,c,r.headers):An.generate(r.status,c,`Token exchange failed with status ${r.status}`,r.headers)}const s=await r.json(),i=s.expires_in||3600,a=Date.now()+i*1e3;return this.cachedToken={token:s.access_token,expiresAt:a},s.access_token}isTokenExpired(e){return Date.now()>=e.expiresAt}needsRefresh(e){const r=(this.config.refreshBufferSeconds??1200)*1e3;return Date.now()>=e.expiresAt-r}invalidateToken(){this.cachedToken=null,this.refreshPromise=null}}const KC=()=>{var t;if(typeof File>"u"){const{process:e}=globalThis,n=typeof((t=e==null?void 0:e.versions)==null?void 0:t.node)=="string"&&parseInt(e.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(n?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function mu(t,e,n){return KC(),new File(t,e??"unknown_file",n)}function nh(t){return(typeof t=="object"&&t!==null&&("name"in t&&t.name&&String(t.name)||"url"in t&&t.url&&String(t.url)||"filename"in t&&t.filename&&String(t.filename)||"path"in t&&t.path&&String(t.path))||"").split(/[\\/]/).pop()||void 0}const Ew=t=>t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function",Yf=async(t,e)=>T_(t.body)?{...t,body:await WC(t.body,e)}:t,ms=async(t,e)=>({...t,body:await WC(t.body,e)}),SS=new WeakMap;function NK(t){const e=typeof t=="function"?t:t.fetch,n=SS.get(e);if(n)return n;const r=(async()=>{try{const s="Response"in e?e.Response:(await e("data:,")).constructor,i=new FormData;return i.toString()!==await new s(i).text()}catch{return!0}})();return SS.set(e,r),r}const WC=async(t,e)=>{if(!await NK(e))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");const n=new FormData;return await Promise.all(Object.entries(t||{}).map(([r,s])=>E_(n,r,s))),n},ZC=t=>t instanceof Blob&&"name"in t,MK=t=>typeof t=="object"&&t!==null&&(t instanceof Response||Ew(t)||ZC(t)),T_=t=>{if(MK(t))return!0;if(Array.isArray(t))return t.some(T_);if(t&&typeof t=="object"){for(const e in t)if(T_(t[e]))return!0}return!1},E_=async(t,e,n)=>{if(n!==void 0){if(n==null)throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")t.append(e,String(n));else if(n instanceof Response)t.append(e,mu([await n.blob()],nh(n)));else if(Ew(n))t.append(e,mu([await new Response(NC(n)).blob()],nh(n)));else if(ZC(n))t.append(e,n,nh(n));else if(Array.isArray(n))await Promise.all(n.map(r=>E_(t,e+"[]",r)));else if(typeof n=="object")await Promise.all(Object.entries(n).map(([r,s])=>E_(t,`${e}[${r}]`,s)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${n} instead`)}},qC=t=>t!=null&&typeof t=="object"&&typeof t.size=="number"&&typeof t.type=="string"&&typeof t.text=="function"&&typeof t.slice=="function"&&typeof t.arrayBuffer=="function",LK=t=>t!=null&&typeof t=="object"&&typeof t.name=="string"&&typeof t.lastModified=="number"&&qC(t),jK=t=>t!=null&&typeof t=="object"&&typeof t.url=="string"&&typeof t.blob=="function";async function DK(t,e,n){if(KC(),t=await t,LK(t))return t instanceof File?t:mu([await t.arrayBuffer()],t.name);if(jK(t)){const s=await t.blob();return e||(e=new URL(t.url).pathname.split(/[\\/]/).pop()),mu(await I_(s),e,n)}const r=await I_(t);if(e||(e=nh(t)),!(n!=null&&n.type)){const s=r.find(i=>typeof i=="object"&&"type"in i&&i.type);typeof s=="string"&&(n={...n,type:s})}return mu(r,e,n)}async function I_(t){var n;let e=[];if(typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer)e.push(t);else if(qC(t))e.push(t instanceof Blob?t:await t.arrayBuffer());else if(Ew(t))for await(const r of t)e.push(...await I_(r));else{const r=(n=t==null?void 0:t.constructor)==null?void 0:n.name;throw new Error(`Unexpected data type: ${typeof t}${r?`; constructor: ${r}`:""}${UK(t)}`)}return e}function UK(t){return typeof t!="object"||t===null?"":`; props: [${Object.getOwnPropertyNames(t).map(n=>`"${n}"`).join(", ")}]`}let G=class{constructor(e){this._client=e}};function GC(t){return t.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}const AS=Object.freeze(Object.create(null)),FK=(t=GC)=>function(n,...r){if(n.length===1)return n[0];let s=!1;const i=[],a=n.reduce((l,d,f)=>{var g;/[?#]/.test(d)&&(s=!0);const h=r[f];let p=(s?encodeURIComponent:t)(""+h);return f!==r.length&&(h==null||typeof h=="object"&&h.toString===((g=Object.getPrototypeOf(Object.getPrototypeOf(h.hasOwnProperty??AS)??AS))==null?void 0:g.toString))&&(p=h+"",i.push({start:l.length+d.length,length:p.length,error:`Value of type ${Object.prototype.toString.call(h).slice(8,-1)} is not a valid path parameter`})),l+d+(f===r.length?"":p)},""),o=a.split(/[?#]/,1)[0],c=new RegExp("(?<=^|\\/)(?:\\.|%2e){1,2}(?=\\/|$)","gi");let u;for(;(u=c.exec(o))!==null;)i.push({start:u.index,length:u[0].length,error:`Value "${u[0]}" can't be safely passed as a path parameter`});if(i.sort((l,d)=>l.start-d.start),i.length>0){let l=0;const d=i.reduce((f,h)=>{const p=" ".repeat(h.start-l),g="^".repeat(h.length);return l=h.start+h.length,f+p+g},"");throw new ye(`Path parameters result in path with invalid segments:
|
|
330
|
-
${i.map(f=>f.error).join(`
|
|
331
|
-
`)}
|
|
332
|
-
${a}
|
|
333
|
-
${d}`)}return a},R=FK(GC);let JC=class extends G{list(e,n={},r){return this._client.getAPIList(R`/chat/completions/${e}/messages`,It,{query:n,...r,__security:{bearerAuth:!0}})}};function Xh(t){return t!==void 0&&"function"in t&&t.function!==void 0}function BK(t,e){const n={...t};return Object.defineProperties(n,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:e,enumerable:!1}}),n}function Iw(t){return(t==null?void 0:t.$brand)==="auto-parseable-response-format"}function Ol(t){return(t==null?void 0:t.$brand)==="auto-parseable-tool"}function zK(t,e){return!e||!YC(e)?{...t,choices:t.choices.map(n=>(XC(n.message.tool_calls),{...n,message:{...n.message,parsed:null,...n.message.tool_calls?{tool_calls:n.message.tool_calls}:void 0}}))}:xw(t,e)}function xw(t,e){const n=t.choices.map(r=>{var s;if(r.finish_reason==="length")throw new CC;if(r.finish_reason==="content_filter")throw new OC;return XC(r.message.tool_calls),{...r,message:{...r.message,...r.message.tool_calls?{tool_calls:((s=r.message.tool_calls)==null?void 0:s.map(i=>VK(e,i)))??void 0}:void 0,parsed:r.message.content&&!r.message.refusal?HK(e,r.message.content):null}}});return{...t,choices:n}}function HK(t,e){var n,r;return((n=t.response_format)==null?void 0:n.type)!=="json_schema"?null:((r=t.response_format)==null?void 0:r.type)==="json_schema"?"$parseRaw"in t.response_format?t.response_format.$parseRaw(e):JSON.parse(e):null}function VK(t,e){var r;const n=(r=t.tools)==null?void 0:r.find(s=>{var i;return Xh(s)&&((i=s.function)==null?void 0:i.name)===e.function.name});return{...e,function:{...e.function,parsed_arguments:Ol(n)?n.$parseRaw(e.function.arguments):n!=null&&n.function.strict?JSON.parse(e.function.arguments):null}}}function KK(t,e){var r;if(!t||!("tools"in t)||!t.tools)return!1;const n=(r=t.tools)==null?void 0:r.find(s=>{var i;return Xh(s)&&((i=s.function)==null?void 0:i.name)===e.function.name});return Xh(n)&&(Ol(n)||(n==null?void 0:n.function.strict)||!1)}function YC(t){var e;return Iw(t.response_format)?!0:((e=t.tools)==null?void 0:e.some(n=>Ol(n)||n.type==="function"&&n.function.strict===!0))??!1}function XC(t){for(const e of t||[])if(e.type!=="function")throw new ye(`Currently only \`function\` tool calls are supported; Received \`${e.type}\``)}function WK(t){for(const e of t??[]){if(e.type!=="function")throw new ye(`Currently only \`function\` tool types support auto-parsing; Received \`${e.type}\``);if(e.function.strict!==!0)throw new ye(`The \`${e.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}const Qh=t=>(t==null?void 0:t.role)==="assistant",QC=t=>(t==null?void 0:t.role)==="tool";var x_,rh,sh,Zc,qc,ih,Gc,$s,Jc,ef,tf,Xa,eO;class kw{constructor(){x_.add(this),this.controller=new AbortController,rh.set(this,void 0),sh.set(this,()=>{}),Zc.set(this,()=>{}),qc.set(this,void 0),ih.set(this,()=>{}),Gc.set(this,()=>{}),$s.set(this,{}),Jc.set(this,!1),ef.set(this,!1),tf.set(this,!1),Xa.set(this,!1),Oe(this,rh,new Promise((e,n)=>{Oe(this,sh,e,"f"),Oe(this,Zc,n,"f")})),Oe(this,qc,new Promise((e,n)=>{Oe(this,ih,e,"f"),Oe(this,Gc,n,"f")})),N(this,rh,"f").catch(()=>{}),N(this,qc,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},N(this,x_,"m",eO).bind(this))},0)}_connected(){this.ended||(N(this,sh,"f").call(this),this._emit("connect"))}get ended(){return N(this,Jc,"f")}get errored(){return N(this,ef,"f")}get aborted(){return N(this,tf,"f")}abort(){this.controller.abort()}on(e,n){return(N(this,$s,"f")[e]||(N(this,$s,"f")[e]=[])).push({listener:n}),this}off(e,n){const r=N(this,$s,"f")[e];if(!r)return this;const s=r.findIndex(i=>i.listener===n);return s>=0&&r.splice(s,1),this}once(e,n){return(N(this,$s,"f")[e]||(N(this,$s,"f")[e]=[])).push({listener:n,once:!0}),this}emitted(e){return new Promise((n,r)=>{Oe(this,Xa,!0),e!=="error"&&this.once("error",r),this.once(e,n)})}async done(){Oe(this,Xa,!0),await N(this,qc,"f")}_emit(e,...n){if(N(this,Jc,"f"))return;e==="end"&&(Oe(this,Jc,!0),N(this,ih,"f").call(this));const r=N(this,$s,"f")[e];if(r&&(N(this,$s,"f")[e]=r.filter(s=>!s.once),r.forEach(({listener:s})=>s(...n))),e==="abort"){const s=n[0];!N(this,Xa,"f")&&!(r!=null&&r.length)&&Promise.reject(s),N(this,Zc,"f").call(this,s),N(this,Gc,"f").call(this,s),this._emit("end");return}if(e==="error"){const s=n[0];!N(this,Xa,"f")&&!(r!=null&&r.length)&&Promise.reject(s),N(this,Zc,"f").call(this,s),N(this,Gc,"f").call(this,s),this._emit("end")}}_emitFinal(){}}rh=new WeakMap,sh=new WeakMap,Zc=new WeakMap,qc=new WeakMap,ih=new WeakMap,Gc=new WeakMap,$s=new WeakMap,Jc=new WeakMap,ef=new WeakMap,tf=new WeakMap,Xa=new WeakMap,x_=new WeakSet,eO=function(e){if(Oe(this,ef,!0),e instanceof Error&&e.name==="AbortError"&&(e=new or),e instanceof or)return Oe(this,tf,!0),this._emit("abort",e);if(e instanceof ye)return this._emit("error",e);if(e instanceof Error){const n=new ye(e.message);return n.cause=e,this._emit("error",n)}return this._emit("error",new ye(String(e)))};function ZK(t){return typeof t.parse=="function"}var On,k_,nf,C_,O_,$_,tO,nO;const qK=10;class rO extends kw{constructor(){super(...arguments),On.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){var r;this._chatCompletions.push(e),this._emit("chatCompletion",e);const n=(r=e.choices[0])==null?void 0:r.message;return n&&this._addMessage(n),e}_addMessage(e,n=!0){if("content"in e||(e.content=null),this.messages.push(e),n){if(this._emit("message",e),QC(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(Qh(e)&&e.tool_calls)for(const r of e.tool_calls)r.type==="function"&&this._emit("functionToolCall",r.function)}}async finalChatCompletion(){await this.done();const e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new ye("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),N(this,On,"m",k_).call(this)}async finalMessage(){return await this.done(),N(this,On,"m",nf).call(this)}async finalFunctionToolCall(){return await this.done(),N(this,On,"m",C_).call(this)}async finalFunctionToolCallResult(){return await this.done(),N(this,On,"m",O_).call(this)}async totalUsage(){return await this.done(),N(this,On,"m",$_).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){const e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);const n=N(this,On,"m",nf).call(this);n&&this._emit("finalMessage",n);const r=N(this,On,"m",k_).call(this);r&&this._emit("finalContent",r);const s=N(this,On,"m",C_).call(this);s&&this._emit("finalFunctionToolCall",s);const i=N(this,On,"m",O_).call(this);i!=null&&this._emit("finalFunctionToolCallResult",i),this._chatCompletions.some(a=>a.usage)&&this._emit("totalUsage",N(this,On,"m",$_).call(this))}async _createChatCompletion(e,n,r){const s=r==null?void 0:r.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),N(this,On,"m",tO).call(this,n);const i=await e.chat.completions.create({...n,stream:!1},{...r,signal:this.controller.signal});return this._connected(),this._addChatCompletion(xw(i,n))}async _runChatCompletion(e,n,r){for(const s of n.messages)this._addMessage(s,!1);return await this._createChatCompletion(e,n,r)}async _runTools(e,n,r){var h,p,g;const s="tool",{tool_choice:i="auto",stream:a,...o}=n,c=typeof i!="string"&&i.type==="function"&&((h=i==null?void 0:i.function)==null?void 0:h.name),{maxChatCompletions:u=qK}=r||{},l=n.tools.map(y=>{if(Ol(y)){if(!y.$callback)throw new ye("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:y.$callback,name:y.function.name,description:y.function.description||"",parameters:y.function.parameters,parse:y.$parseRaw,strict:!0}}}return y}),d={};for(const y of l)y.type==="function"&&(d[y.function.name||y.function.function.name]=y.function);const f="tools"in n?l.map(y=>y.type==="function"?{type:"function",function:{name:y.function.name||y.function.function.name,parameters:y.function.parameters,description:y.function.description,strict:y.function.strict}}:y):void 0;for(const y of n.messages)this._addMessage(y,!1);for(let y=0;y<u;++y){const _=(p=(await this._createChatCompletion(e,{...o,tool_choice:i,tools:f,messages:[...this.messages]},r)).choices[0])==null?void 0:p.message;if(!_)throw new ye("missing message in ChatCompletion response");if(!((g=_.tool_calls)!=null&&g.length))return;for(const w of _.tool_calls){if(w.type!=="function")continue;const v=w.id,{name:A,arguments:S}=w.function,x=d[A];if(x){if(c&&c!==A){const C=`Invalid tool_call: ${JSON.stringify(A)}. ${JSON.stringify(c)} requested. Please try again`;this._addMessage({role:s,tool_call_id:v,content:C});continue}}else{const C=`Invalid tool_call: ${JSON.stringify(A)}. Available options are: ${Object.keys(d).map(D=>JSON.stringify(D)).join(", ")}. Please try again`;this._addMessage({role:s,tool_call_id:v,content:C});continue}let E;try{E=ZK(x)?await x.parse(S):S}catch(C){const D=C instanceof Error?C.message:String(C);this._addMessage({role:s,tool_call_id:v,content:D});continue}const $=await x.function(E,this),k=N(this,On,"m",nO).call(this,$);if(this._addMessage({role:s,tool_call_id:v,content:k}),c)return}}}}On=new WeakSet,k_=function(){return N(this,On,"m",nf).call(this).content??null},nf=function(){let e=this.messages.length;for(;e-- >0;){const n=this.messages[e];if(Qh(n))return{...n,content:n.content??null,refusal:n.refusal??null}}throw new ye("stream ended without producing a ChatCompletionMessage with role=assistant")},C_=function(){var e,n;for(let r=this.messages.length-1;r>=0;r--){const s=this.messages[r];if(Qh(s)&&((e=s==null?void 0:s.tool_calls)!=null&&e.length))return(n=s.tool_calls.filter(i=>i.type==="function").at(-1))==null?void 0:n.function}},O_=function(){for(let e=this.messages.length-1;e>=0;e--){const n=this.messages[e];if(QC(n)&&n.content!=null&&typeof n.content=="string"&&this.messages.some(r=>{var s;return r.role==="assistant"&&((s=r.tool_calls)==null?void 0:s.some(i=>i.type==="function"&&i.id===n.tool_call_id))}))return n.content}},$_=function(){const e={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(const{usage:n}of this._chatCompletions)n&&(e.completion_tokens+=n.completion_tokens,e.prompt_tokens+=n.prompt_tokens,e.total_tokens+=n.total_tokens);return e},tO=function(e){if(e.n!=null&&e.n>1)throw new ye("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},nO=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)};class Cw extends rO{static runTools(e,n,r){const s=new Cw,i={...r,headers:{...r==null?void 0:r.headers,"X-Stainless-Helper-Method":"runTools"}};return s._run(()=>s._runTools(e,n,i)),s}_addMessage(e,n=!0){super._addMessage(e,n),Qh(e)&&e.content&&this._emit("content",e.content)}}const sO=1,iO=2,aO=4,oO=8,cO=16,uO=32,lO=64,dO=128,hO=256,fO=dO|hO,pO=cO|uO|fO|lO,mO=sO|iO|pO,gO=aO|oO,GK=mO|gO,Jt={STR:sO,NUM:iO,ARR:aO,OBJ:oO,NULL:cO,BOOL:uO,NAN:lO,INFINITY:dO,MINUS_INFINITY:hO,INF:fO,SPECIAL:pO,ATOM:mO,COLLECTION:gO,ALL:GK};class JK extends Error{}class YK extends Error{}function XK(t,e=Jt.ALL){if(typeof t!="string")throw new TypeError(`expecting str, got ${typeof t}`);if(!t.trim())throw new Error(`${t} is empty`);return QK(t.trim(),e)}const QK=(t,e)=>{const n=t.length;let r=0;const s=f=>{throw new JK(`${f} at position ${r}`)},i=f=>{throw new YK(`${f} at position ${r}`)},a=()=>(d(),r>=n&&s("Unexpected end of input"),t[r]==='"'?o():t[r]==="{"?c():t[r]==="["?u():t.substring(r,r+4)==="null"||Jt.NULL&e&&n-r<4&&"null".startsWith(t.substring(r))?(r+=4,null):t.substring(r,r+4)==="true"||Jt.BOOL&e&&n-r<4&&"true".startsWith(t.substring(r))?(r+=4,!0):t.substring(r,r+5)==="false"||Jt.BOOL&e&&n-r<5&&"false".startsWith(t.substring(r))?(r+=5,!1):t.substring(r,r+8)==="Infinity"||Jt.INFINITY&e&&n-r<8&&"Infinity".startsWith(t.substring(r))?(r+=8,1/0):t.substring(r,r+9)==="-Infinity"||Jt.MINUS_INFINITY&e&&1<n-r&&n-r<9&&"-Infinity".startsWith(t.substring(r))?(r+=9,-1/0):t.substring(r,r+3)==="NaN"||Jt.NAN&e&&n-r<3&&"NaN".startsWith(t.substring(r))?(r+=3,NaN):l()),o=()=>{const f=r;let h=!1;for(r++;r<n&&(t[r]!=='"'||h&&t[r-1]==="\\");)h=t[r]==="\\"?!h:!1,r++;if(t.charAt(r)=='"')try{return JSON.parse(t.substring(f,++r-Number(h)))}catch(p){i(String(p))}else if(Jt.STR&e)try{return JSON.parse(t.substring(f,r-Number(h))+'"')}catch{return JSON.parse(t.substring(f,t.lastIndexOf("\\"))+'"')}s("Unterminated string literal")},c=()=>{r++,d();const f={};try{for(;t[r]!=="}";){if(d(),r>=n&&Jt.OBJ&e)return f;const h=o();d(),r++;try{const p=a();Object.defineProperty(f,h,{value:p,writable:!0,enumerable:!0,configurable:!0})}catch(p){if(Jt.OBJ&e)return f;throw p}d(),t[r]===","&&r++}}catch{if(Jt.OBJ&e)return f;s("Expected '}' at end of object")}return r++,f},u=()=>{r++;const f=[];try{for(;t[r]!=="]";)f.push(a()),d(),t[r]===","&&r++}catch{if(Jt.ARR&e)return f;s("Expected ']' at end of array")}return r++,f},l=()=>{if(r===0){t==="-"&&Jt.NUM&e&&s("Not sure what '-' is");try{return JSON.parse(t)}catch(h){if(Jt.NUM&e)try{return t[t.length-1]==="."?JSON.parse(t.substring(0,t.lastIndexOf("."))):JSON.parse(t.substring(0,t.lastIndexOf("e")))}catch{}i(String(h))}}const f=r;for(t[r]==="-"&&r++;t[r]&&!",]}".includes(t[r]);)r++;r==n&&!(Jt.NUM&e)&&s("Unterminated number literal");try{return JSON.parse(t.substring(f,r))}catch{t.substring(f,r)==="-"&&Jt.NUM&e&&s("Not sure what '-' is");try{return JSON.parse(t.substring(f,t.lastIndexOf("e")))}catch(p){i(String(p))}}},d=()=>{for(;r<n&&`
|
|
334
|
-
\r `.includes(t[r]);)r++};return a()},TS=t=>XK(t,Jt.ALL^Jt.NUM);var Dt,ks,Da,Qs,gm,_d,_m,ym,wm,yd,bm,ES;class Ku extends rO{constructor(e){super(),Dt.add(this),ks.set(this,void 0),Da.set(this,void 0),Qs.set(this,void 0),Oe(this,ks,e),Oe(this,Da,[])}get currentChatCompletionSnapshot(){return N(this,Qs,"f")}static fromReadableStream(e){const n=new Ku(null);return n._run(()=>n._fromReadableStream(e)),n}static createChatCompletion(e,n,r){const s=new Ku(n);return s._run(()=>s._runChatCompletion(e,{...n,stream:!0},{...r,headers:{...r==null?void 0:r.headers,"X-Stainless-Helper-Method":"stream"}})),s}async _createChatCompletion(e,n,r){var a;super._createChatCompletion;const s=r==null?void 0:r.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),N(this,Dt,"m",gm).call(this);const i=await e.chat.completions.create({...n,stream:!0},{...r,signal:this.controller.signal});this._connected();for await(const o of i)N(this,Dt,"m",_m).call(this,o);if((a=i.controller.signal)!=null&&a.aborted)throw new or;return this._addChatCompletion(N(this,Dt,"m",yd).call(this))}async _fromReadableStream(e,n){var a;const r=n==null?void 0:n.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),N(this,Dt,"m",gm).call(this),this._connected();const s=Vu.fromReadableStream(e,this.controller);let i;for await(const o of s)i&&i!==o.id&&this._addChatCompletion(N(this,Dt,"m",yd).call(this)),N(this,Dt,"m",_m).call(this,o),i=o.id;if((a=s.controller.signal)!=null&&a.aborted)throw new or;return this._addChatCompletion(N(this,Dt,"m",yd).call(this))}[(ks=new WeakMap,Da=new WeakMap,Qs=new WeakMap,Dt=new WeakSet,gm=function(){this.ended||Oe(this,Qs,void 0)},_d=function(n){let r=N(this,Da,"f")[n.index];return r||(r={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},N(this,Da,"f")[n.index]=r,r)},_m=function(n){var s,i,a,o,c,u,l,d,f,h,p,g,y,b,_;if(this.ended)return;const r=N(this,Dt,"m",ES).call(this,n);this._emit("chunk",n,r);for(const w of n.choices){const v=r.choices[w.index];w.delta.content!=null&&((s=v.message)==null?void 0:s.role)==="assistant"&&((i=v.message)!=null&&i.content)&&(this._emit("content",w.delta.content,v.message.content),this._emit("content.delta",{delta:w.delta.content,snapshot:v.message.content,parsed:v.message.parsed})),w.delta.refusal!=null&&((a=v.message)==null?void 0:a.role)==="assistant"&&((o=v.message)!=null&&o.refusal)&&this._emit("refusal.delta",{delta:w.delta.refusal,snapshot:v.message.refusal}),((c=w.logprobs)==null?void 0:c.content)!=null&&((u=v.message)==null?void 0:u.role)==="assistant"&&this._emit("logprobs.content.delta",{content:(l=w.logprobs)==null?void 0:l.content,snapshot:((d=v.logprobs)==null?void 0:d.content)??[]}),((f=w.logprobs)==null?void 0:f.refusal)!=null&&((h=v.message)==null?void 0:h.role)==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:(p=w.logprobs)==null?void 0:p.refusal,snapshot:((g=v.logprobs)==null?void 0:g.refusal)??[]});const A=N(this,Dt,"m",_d).call(this,v);v.finish_reason&&(N(this,Dt,"m",wm).call(this,v),A.current_tool_call_index!=null&&N(this,Dt,"m",ym).call(this,v,A.current_tool_call_index));for(const S of w.delta.tool_calls??[])A.current_tool_call_index!==S.index&&(N(this,Dt,"m",wm).call(this,v),A.current_tool_call_index!=null&&N(this,Dt,"m",ym).call(this,v,A.current_tool_call_index)),A.current_tool_call_index=S.index;for(const S of w.delta.tool_calls??[]){const x=(y=v.message.tool_calls)==null?void 0:y[S.index];x!=null&&x.type&&((x==null?void 0:x.type)==="function"?this._emit("tool_calls.function.arguments.delta",{name:(b=x.function)==null?void 0:b.name,index:S.index,arguments:x.function.arguments,parsed_arguments:x.function.parsed_arguments,arguments_delta:((_=S.function)==null?void 0:_.arguments)??""}):(x==null||x.type,void 0))}}},ym=function(n,r){var a,o,c;if(N(this,Dt,"m",_d).call(this,n).done_tool_calls.has(r))return;const i=(a=n.message.tool_calls)==null?void 0:a[r];if(!i)throw new Error("no tool call snapshot");if(!i.type)throw new Error("tool call snapshot missing `type`");if(i.type==="function"){const u=(c=(o=N(this,ks,"f"))==null?void 0:o.tools)==null?void 0:c.find(l=>Xh(l)&&l.function.name===i.function.name);this._emit("tool_calls.function.arguments.done",{name:i.function.name,index:r,arguments:i.function.arguments,parsed_arguments:Ol(u)?u.$parseRaw(i.function.arguments):u!=null&&u.function.strict?JSON.parse(i.function.arguments):null})}else i.type},wm=function(n){var s,i;const r=N(this,Dt,"m",_d).call(this,n);if(n.message.content&&!r.content_done){r.content_done=!0;const a=N(this,Dt,"m",bm).call(this);this._emit("content.done",{content:n.message.content,parsed:a?a.$parseRaw(n.message.content):null})}n.message.refusal&&!r.refusal_done&&(r.refusal_done=!0,this._emit("refusal.done",{refusal:n.message.refusal})),(s=n.logprobs)!=null&&s.content&&!r.logprobs_content_done&&(r.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:n.logprobs.content})),(i=n.logprobs)!=null&&i.refusal&&!r.logprobs_refusal_done&&(r.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:n.logprobs.refusal}))},yd=function(){if(this.ended)throw new ye("stream has ended, this shouldn't happen");const n=N(this,Qs,"f");if(!n)throw new ye("request ended without sending any chunks");return Oe(this,Qs,void 0),Oe(this,Da,[]),eW(n,N(this,ks,"f"))},bm=function(){var r;const n=(r=N(this,ks,"f"))==null?void 0:r.response_format;return Iw(n)?n:null},ES=function(n){var r,s,i,a;let o=N(this,Qs,"f");const{choices:c,...u}=n;o?Object.assign(o,u):o=Oe(this,Qs,{...u,choices:[]});for(const{delta:l,finish_reason:d,index:f,logprobs:h=null,...p}of n.choices){let g=o.choices[f];if(g||(g=o.choices[f]={finish_reason:d,index:f,message:{},logprobs:h,...p}),h)if(!g.logprobs)g.logprobs=Object.assign({},h);else{const{content:S,refusal:x,...E}=h;Object.assign(g.logprobs,E),S&&((r=g.logprobs).content??(r.content=[]),g.logprobs.content.push(...S)),x&&((s=g.logprobs).refusal??(s.refusal=[]),g.logprobs.refusal.push(...x))}if(d&&(g.finish_reason=d,N(this,ks,"f")&&YC(N(this,ks,"f")))){if(d==="length")throw new CC;if(d==="content_filter")throw new OC}if(Object.assign(g,p),!l)continue;const{content:y,refusal:b,function_call:_,role:w,tool_calls:v,...A}=l;if(Object.assign(g.message,A),b&&(g.message.refusal=(g.message.refusal||"")+b),w&&(g.message.role=w),_&&(g.message.function_call?(_.name&&(g.message.function_call.name=_.name),_.arguments&&((i=g.message.function_call).arguments??(i.arguments=""),g.message.function_call.arguments+=_.arguments)):g.message.function_call=_),y&&(g.message.content=(g.message.content||"")+y,!g.message.refusal&&N(this,Dt,"m",bm).call(this)&&(g.message.parsed=TS(g.message.content))),v){g.message.tool_calls||(g.message.tool_calls=[]);for(const{index:S,id:x,type:E,function:$,...k}of v){const C=(a=g.message.tool_calls)[S]??(a[S]={});Object.assign(C,k),x&&(C.id=x),E&&(C.type=E),$&&(C.function??(C.function={name:$.name??"",arguments:""})),$!=null&&$.name&&(C.function.name=$.name),$!=null&&$.arguments&&(C.function.arguments+=$.arguments,KK(N(this,ks,"f"),C)&&(C.function.parsed_arguments=TS(C.function.arguments)))}}}return o},Symbol.asyncIterator)](){const e=[],n=[];let r=!1;return this.on("chunk",s=>{const i=n.shift();i?i.resolve(s):e.push(s)}),this.on("end",()=>{r=!0;for(const s of n)s.resolve(void 0);n.length=0}),this.on("abort",s=>{r=!0;for(const i of n)i.reject(s);n.length=0}),this.on("error",s=>{r=!0;for(const i of n)i.reject(s);n.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((i,a)=>n.push({resolve:i,reject:a})).then(i=>i?{value:i,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new Vu(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function eW(t,e){const{id:n,choices:r,created:s,model:i,system_fingerprint:a,...o}=t,c={...o,id:n,choices:r.map(({message:u,finish_reason:l,index:d,logprobs:f,...h})=>{if(!l)throw new ye(`missing finish_reason for choice ${d}`);const{content:p=null,function_call:g,tool_calls:y,...b}=u,_=u.role;if(!_)throw new ye(`missing role for choice ${d}`);if(g){const{arguments:w,name:v}=g;if(w==null)throw new ye(`missing function_call.arguments for choice ${d}`);if(!v)throw new ye(`missing function_call.name for choice ${d}`);return{...h,message:{content:p,function_call:{arguments:w,name:v},role:_,refusal:u.refusal??null},finish_reason:l,index:d,logprobs:f}}return y?{...h,index:d,finish_reason:l,logprobs:f,message:{...b,role:_,content:p,refusal:u.refusal??null,tool_calls:y.map((w,v)=>{const{function:A,type:S,id:x,...E}=w,{arguments:$,name:k,...C}=A||{};if(x==null)throw new ye(`missing choices[${d}].tool_calls[${v}].id
|
|
335
|
-
${wd(t)}`);if(S==null)throw new ye(`missing choices[${d}].tool_calls[${v}].type
|
|
336
|
-
${wd(t)}`);if(k==null)throw new ye(`missing choices[${d}].tool_calls[${v}].function.name
|
|
337
|
-
${wd(t)}`);if($==null)throw new ye(`missing choices[${d}].tool_calls[${v}].function.arguments
|
|
338
|
-
${wd(t)}`);return{...E,id:x,type:S,function:{...C,name:k,arguments:$}}})}}:{...h,message:{...b,content:p,role:_,refusal:u.refusal??null},finish_reason:l,index:d,logprobs:f}}),created:s,model:i,object:"chat.completion",...a?{system_fingerprint:a}:{}};return zK(c,e)}function wd(t){return JSON.stringify(t)}class rf extends Ku{static fromReadableStream(e){const n=new rf(null);return n._run(()=>n._fromReadableStream(e)),n}static runTools(e,n,r){const s=new rf(n),i={...r,headers:{...r==null?void 0:r.headers,"X-Stainless-Helper-Method":"runTools"}};return s._run(()=>s._runTools(e,n,i)),s}}let Ow=class extends G{constructor(){super(...arguments),this.messages=new JC(this._client)}create(e,n){return this._client.post("/chat/completions",{body:e,...n,stream:e.stream??!1,__security:{bearerAuth:!0}})}retrieve(e,n){return this._client.get(R`/chat/completions/${e}`,{...n,__security:{bearerAuth:!0}})}update(e,n,r){return this._client.post(R`/chat/completions/${e}`,{body:n,...r,__security:{bearerAuth:!0}})}list(e={},n){return this._client.getAPIList("/chat/completions",It,{query:e,...n,__security:{bearerAuth:!0}})}delete(e,n){return this._client.delete(R`/chat/completions/${e}`,{...n,__security:{bearerAuth:!0}})}parse(e,n){return WK(e.tools),this._client.chat.completions.create(e,{...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap(r=>xw(r,e))}runTools(e,n){return e.stream?rf.runTools(this._client,e,n):Cw.runTools(this._client,e,n)}stream(e,n){return Ku.createChatCompletion(this._client,e,n)}};Ow.Messages=JC;class $w extends G{constructor(){super(...arguments),this.completions=new Ow(this._client)}}$w.Completions=Ow;class _O extends G{create(e,n){return this._client.post("/organization/admin_api_keys",{body:e,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,n){return this._client.get(R`/organization/admin_api_keys/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e={},n){return this._client.getAPIList("/organization/admin_api_keys",It,{query:e,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,n){return this._client.delete(R`/organization/admin_api_keys/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}}class yO extends G{list(e={},n){return this._client.getAPIList("/organization/audit_logs",mn,{query:e,...n,__security:{adminAPIKeyAuth:!0}})}}let wO=class extends G{create(e,n){return this._client.post("/organization/certificates",{body:e,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,n={},r){return this._client.get(R`/organization/certificates/${e}`,{query:n,...r,__security:{adminAPIKeyAuth:!0}})}update(e,n,r){return this._client.post(R`/organization/certificates/${e}`,{body:n,...r,__security:{adminAPIKeyAuth:!0}})}list(e={},n){return this._client.getAPIList("/organization/certificates",mn,{query:e,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,n){return this._client.delete(R`/organization/certificates/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}activate(e,n){return this._client.getAPIList("/organization/certificates/activate",Ni,{body:e,method:"post",...n,__security:{adminAPIKeyAuth:!0}})}deactivate(e,n){return this._client.getAPIList("/organization/certificates/deactivate",Ni,{body:e,method:"post",...n,__security:{adminAPIKeyAuth:!0}})}},bO=class extends G{retrieve(e){return this._client.get("/organization/data_retention",{...e,__security:{adminAPIKeyAuth:!0}})}update(e,n){return this._client.post("/organization/data_retention",{body:e,...n,__security:{adminAPIKeyAuth:!0}})}};class vO extends G{create(e,n){return this._client.post("/organization/invites",{body:e,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,n){return this._client.get(R`/organization/invites/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e={},n){return this._client.getAPIList("/organization/invites",mn,{query:e,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,n){return this._client.delete(R`/organization/invites/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}}let SO=class extends G{create(e,n){return this._client.post("/organization/roles",{body:e,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,n){return this._client.get(R`/organization/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,n,r){return this._client.post(R`/organization/roles/${e}`,{body:n,...r,__security:{adminAPIKeyAuth:!0}})}list(e={},n){return this._client.getAPIList("/organization/roles",Ys,{query:e,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,n){return this._client.delete(R`/organization/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},AO=class extends G{create(e,n){return this._client.post("/organization/spend_alerts",{body:e,...n,__security:{adminAPIKeyAuth:!0}})}update(e,n,r){return this._client.post(R`/organization/spend_alerts/${e}`,{body:n,...r,__security:{adminAPIKeyAuth:!0}})}list(e={},n){return this._client.getAPIList("/organization/spend_alerts",mn,{query:e,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,n){return this._client.delete(R`/organization/spend_alerts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};class TO extends G{audioSpeeches(e,n){return this._client.get("/organization/usage/audio_speeches",{query:e,...n,__security:{adminAPIKeyAuth:!0}})}audioTranscriptions(e,n){return this._client.get("/organization/usage/audio_transcriptions",{query:e,...n,__security:{adminAPIKeyAuth:!0}})}codeInterpreterSessions(e,n){return this._client.get("/organization/usage/code_interpreter_sessions",{query:e,...n,__security:{adminAPIKeyAuth:!0}})}completions(e,n){return this._client.get("/organization/usage/completions",{query:e,...n,__security:{adminAPIKeyAuth:!0}})}costs(e,n){return this._client.get("/organization/costs",{query:e,...n,__security:{adminAPIKeyAuth:!0}})}embeddings(e,n){return this._client.get("/organization/usage/embeddings",{query:e,...n,__security:{adminAPIKeyAuth:!0}})}fileSearchCalls(e,n){return this._client.get("/organization/usage/file_search_calls",{query:e,...n,__security:{adminAPIKeyAuth:!0}})}images(e,n){return this._client.get("/organization/usage/images",{query:e,...n,__security:{adminAPIKeyAuth:!0}})}moderations(e,n){return this._client.get("/organization/usage/moderations",{query:e,...n,__security:{adminAPIKeyAuth:!0}})}vectorStores(e,n){return this._client.get("/organization/usage/vector_stores",{query:e,...n,__security:{adminAPIKeyAuth:!0}})}webSearchCalls(e,n){return this._client.get("/organization/usage/web_search_calls",{query:e,...n,__security:{adminAPIKeyAuth:!0}})}}let EO=class extends G{create(e,n,r){return this._client.post(R`/organization/groups/${e}/roles`,{body:n,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,n,r){const{group_id:s}=n;return this._client.get(R`/organization/groups/${s}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e,n={},r){return this._client.getAPIList(R`/organization/groups/${e}/roles`,Ys,{query:n,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,n,r){const{group_id:s}=n;return this._client.delete(R`/organization/groups/${s}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}},IO=class extends G{create(e,n,r){return this._client.post(R`/organization/groups/${e}/users`,{body:n,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,n,r){const{group_id:s}=n;return this._client.get(R`/organization/groups/${s}/users/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e,n={},r){return this._client.getAPIList(R`/organization/groups/${e}/users`,Ys,{query:n,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,n,r){const{group_id:s}=n;return this._client.delete(R`/organization/groups/${s}/users/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}},Xf=class extends G{constructor(){super(...arguments),this.users=new IO(this._client),this.roles=new EO(this._client)}create(e,n){return this._client.post("/organization/groups",{body:e,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,n){return this._client.get(R`/organization/groups/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,n,r){return this._client.post(R`/organization/groups/${e}`,{body:n,...r,__security:{adminAPIKeyAuth:!0}})}list(e={},n){return this._client.getAPIList("/organization/groups",Ys,{query:e,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,n){return this._client.delete(R`/organization/groups/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};Xf.Users=IO;Xf.Roles=EO;class xO extends G{retrieve(e,n,r){const{project_id:s}=n;return this._client.get(R`/organization/projects/${s}/api_keys/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e,n={},r){return this._client.getAPIList(R`/organization/projects/${e}/api_keys`,mn,{query:n,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,n,r){const{project_id:s}=n;return this._client.delete(R`/organization/projects/${s}/api_keys/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}}class kO extends G{list(e,n={},r){return this._client.getAPIList(R`/organization/projects/${e}/certificates`,mn,{query:n,...r,__security:{adminAPIKeyAuth:!0}})}activate(e,n,r){return this._client.getAPIList(R`/organization/projects/${e}/certificates/activate`,Ni,{body:n,method:"post",...r,__security:{adminAPIKeyAuth:!0}})}deactivate(e,n,r){return this._client.getAPIList(R`/organization/projects/${e}/certificates/deactivate`,Ni,{body:n,method:"post",...r,__security:{adminAPIKeyAuth:!0}})}}class CO extends G{retrieve(e,n){return this._client.get(R`/organization/projects/${e}/data_retention`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,n,r){return this._client.post(R`/organization/projects/${e}/data_retention`,{body:n,...r,__security:{adminAPIKeyAuth:!0}})}}class OO extends G{retrieve(e,n){return this._client.get(R`/organization/projects/${e}/hosted_tool_permissions`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,n,r){return this._client.post(R`/organization/projects/${e}/hosted_tool_permissions`,{body:n,...r,__security:{adminAPIKeyAuth:!0}})}}class $O extends G{retrieve(e,n){return this._client.get(R`/organization/projects/${e}/model_permissions`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,n,r){return this._client.post(R`/organization/projects/${e}/model_permissions`,{body:n,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,n){return this._client.delete(R`/organization/projects/${e}/model_permissions`,{...n,__security:{adminAPIKeyAuth:!0}})}}class RO extends G{listRateLimits(e,n={},r){return this._client.getAPIList(R`/organization/projects/${e}/rate_limits`,mn,{query:n,...r,__security:{adminAPIKeyAuth:!0}})}updateRateLimit(e,n,r){const{project_id:s,...i}=n;return this._client.post(R`/organization/projects/${s}/rate_limits/${e}`,{body:i,...r,__security:{adminAPIKeyAuth:!0}})}}let PO=class extends G{create(e,n,r){return this._client.post(R`/projects/${e}/roles`,{body:n,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,n,r){const{project_id:s}=n;return this._client.get(R`/projects/${s}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,n,r){const{project_id:s,...i}=n;return this._client.post(R`/projects/${s}/roles/${e}`,{body:i,...r,__security:{adminAPIKeyAuth:!0}})}list(e,n={},r){return this._client.getAPIList(R`/projects/${e}/roles`,Ys,{query:n,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,n,r){const{project_id:s}=n;return this._client.delete(R`/projects/${s}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};class NO extends G{create(e,n,r){return this._client.post(R`/organization/projects/${e}/service_accounts`,{body:n,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,n,r){const{project_id:s}=n;return this._client.get(R`/organization/projects/${s}/service_accounts/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,n,r){const{project_id:s,...i}=n;return this._client.post(R`/organization/projects/${s}/service_accounts/${e}`,{body:i,...r,__security:{adminAPIKeyAuth:!0}})}list(e,n={},r){return this._client.getAPIList(R`/organization/projects/${e}/service_accounts`,mn,{query:n,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,n,r){const{project_id:s}=n;return this._client.delete(R`/organization/projects/${s}/service_accounts/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}}class MO extends G{create(e,n,r){return this._client.post(R`/organization/projects/${e}/spend_alerts`,{body:n,...r,__security:{adminAPIKeyAuth:!0}})}update(e,n,r){const{project_id:s,...i}=n;return this._client.post(R`/organization/projects/${s}/spend_alerts/${e}`,{body:i,...r,__security:{adminAPIKeyAuth:!0}})}list(e,n={},r){return this._client.getAPIList(R`/organization/projects/${e}/spend_alerts`,mn,{query:n,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,n,r){const{project_id:s}=n;return this._client.delete(R`/organization/projects/${s}/spend_alerts/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}}let LO=class extends G{create(e,n,r){const{project_id:s,...i}=n;return this._client.post(R`/projects/${s}/groups/${e}/roles`,{body:i,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,n,r){const{project_id:s,group_id:i}=n;return this._client.get(R`/projects/${s}/groups/${i}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e,n,r){const{project_id:s,...i}=n;return this._client.getAPIList(R`/projects/${s}/groups/${e}/roles`,Ys,{query:i,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,n,r){const{project_id:s,group_id:i}=n;return this._client.delete(R`/projects/${s}/groups/${i}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};class Rw extends G{constructor(){super(...arguments),this.roles=new LO(this._client)}create(e,n,r){return this._client.post(R`/organization/projects/${e}/groups`,{body:n,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,n,r){const{project_id:s,...i}=n;return this._client.get(R`/organization/projects/${s}/groups/${e}`,{query:i,...r,__security:{adminAPIKeyAuth:!0}})}list(e,n={},r){return this._client.getAPIList(R`/organization/projects/${e}/groups`,Ys,{query:n,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,n,r){const{project_id:s}=n;return this._client.delete(R`/organization/projects/${s}/groups/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}}Rw.Roles=LO;let jO=class extends G{create(e,n,r){const{project_id:s,...i}=n;return this._client.post(R`/projects/${s}/users/${e}/roles`,{body:i,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,n,r){const{project_id:s,user_id:i}=n;return this._client.get(R`/projects/${s}/users/${i}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e,n,r){const{project_id:s,...i}=n;return this._client.getAPIList(R`/projects/${s}/users/${e}/roles`,Ys,{query:i,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,n,r){const{project_id:s,user_id:i}=n;return this._client.delete(R`/projects/${s}/users/${i}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}},Pw=class extends G{constructor(){super(...arguments),this.roles=new jO(this._client)}create(e,n,r){return this._client.post(R`/organization/projects/${e}/users`,{body:n,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,n,r){const{project_id:s}=n;return this._client.get(R`/organization/projects/${s}/users/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,n,r){const{project_id:s,...i}=n;return this._client.post(R`/organization/projects/${s}/users/${e}`,{body:i,...r,__security:{adminAPIKeyAuth:!0}})}list(e,n={},r){return this._client.getAPIList(R`/organization/projects/${e}/users`,mn,{query:n,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,n,r){const{project_id:s}=n;return this._client.delete(R`/organization/projects/${s}/users/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};Pw.Roles=jO;class pr extends G{constructor(){super(...arguments),this.users=new Pw(this._client),this.serviceAccounts=new NO(this._client),this.apiKeys=new xO(this._client),this.rateLimits=new RO(this._client),this.modelPermissions=new $O(this._client),this.hostedToolPermissions=new OO(this._client),this.groups=new Rw(this._client),this.roles=new PO(this._client),this.dataRetention=new CO(this._client),this.spendAlerts=new MO(this._client),this.certificates=new kO(this._client)}create(e,n){return this._client.post("/organization/projects",{body:e,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,n){return this._client.get(R`/organization/projects/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,n,r){return this._client.post(R`/organization/projects/${e}`,{body:n,...r,__security:{adminAPIKeyAuth:!0}})}list(e={},n){return this._client.getAPIList("/organization/projects",mn,{query:e,...n,__security:{adminAPIKeyAuth:!0}})}archive(e,n){return this._client.post(R`/organization/projects/${e}/archive`,{...n,__security:{adminAPIKeyAuth:!0}})}}pr.Users=Pw;pr.ServiceAccounts=NO;pr.APIKeys=xO;pr.RateLimits=RO;pr.ModelPermissions=$O;pr.HostedToolPermissions=OO;pr.Groups=Rw;pr.Roles=PO;pr.DataRetention=CO;pr.SpendAlerts=MO;pr.Certificates=kO;class DO extends G{create(e,n,r){return this._client.post(R`/organization/users/${e}/roles`,{body:n,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,n,r){const{user_id:s}=n;return this._client.get(R`/organization/users/${s}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e,n={},r){return this._client.getAPIList(R`/organization/users/${e}/roles`,Ys,{query:n,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,n,r){const{user_id:s}=n;return this._client.delete(R`/organization/users/${s}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}}class Nw extends G{constructor(){super(...arguments),this.roles=new DO(this._client)}retrieve(e,n){return this._client.get(R`/organization/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,n,r){return this._client.post(R`/organization/users/${e}`,{body:n,...r,__security:{adminAPIKeyAuth:!0}})}list(e={},n){return this._client.getAPIList("/organization/users",mn,{query:e,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,n){return this._client.delete(R`/organization/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}}Nw.Roles=DO;class mr extends G{constructor(){super(...arguments),this.auditLogs=new yO(this._client),this.adminAPIKeys=new _O(this._client),this.usage=new TO(this._client),this.invites=new vO(this._client),this.users=new Nw(this._client),this.groups=new Xf(this._client),this.roles=new SO(this._client),this.dataRetention=new bO(this._client),this.spendAlerts=new AO(this._client),this.certificates=new wO(this._client),this.projects=new pr(this._client)}}mr.AuditLogs=yO;mr.AdminAPIKeys=_O;mr.Usage=TO;mr.Invites=vO;mr.Users=Nw;mr.Groups=Xf;mr.Roles=SO;mr.DataRetention=bO;mr.SpendAlerts=AO;mr.Certificates=wO;mr.Projects=pr;class Mw extends G{constructor(){super(...arguments),this.organization=new mr(this._client)}}Mw.Organization=mr;const UO=Symbol("brand.privateNullableHeaders");function*tW(t){if(!t)return;if(UO in t){const{values:r,nulls:s}=t;yield*r.entries();for(const i of s)yield[i,null];return}let e=!1,n;t instanceof Headers?n=t.entries():cS(t)?n=t:(e=!0,n=Object.entries(t??{}));for(let r of n){const s=r[0];if(typeof s!="string")throw new TypeError("expected header name to be a string");const i=cS(r[1])?r[1]:[r[1]];let a=!1;for(const o of i)o!==void 0&&(e&&!a&&(a=!0,yield[s,null]),yield[s,o])}}const ie=t=>{const e=new Headers,n=new Set;for(const r of t){const s=new Set;for(const[i,a]of tW(r)){const o=i.toLowerCase();s.has(o)||(e.delete(i),s.add(o)),a===null?(e.delete(i),n.add(o)):(e.append(i,a),n.delete(o))}}return{[UO]:!0,values:e,nulls:n}};class FO extends G{create(e,n){return this._client.post("/audio/speech",{body:e,...n,headers:ie([{Accept:"application/octet-stream"},n==null?void 0:n.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}}class BO extends G{create(e,n){return this._client.post("/audio/transcriptions",ms({body:e,...n,stream:e.stream??!1,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}}class zO extends G{create(e,n){return this._client.post("/audio/translations",ms({body:e,...n,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}}class $l extends G{constructor(){super(...arguments),this.transcriptions=new BO(this._client),this.translations=new zO(this._client),this.speech=new FO(this._client)}}$l.Transcriptions=BO;$l.Translations=zO;$l.Speech=FO;let HO=class extends G{create(e,n){return this._client.post("/batches",{body:e,...n,__security:{bearerAuth:!0}})}retrieve(e,n){return this._client.get(R`/batches/${e}`,{...n,__security:{bearerAuth:!0}})}list(e={},n){return this._client.getAPIList("/batches",It,{query:e,...n,__security:{bearerAuth:!0}})}cancel(e,n){return this._client.post(R`/batches/${e}/cancel`,{...n,__security:{bearerAuth:!0}})}};class VO extends G{create(e,n){return this._client.post("/assistants",{body:e,...n,headers:ie([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers]),__security:{bearerAuth:!0}})}retrieve(e,n){return this._client.get(R`/assistants/${e}`,{...n,headers:ie([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers]),__security:{bearerAuth:!0}})}update(e,n,r){return this._client.post(R`/assistants/${e}`,{body:n,...r,headers:ie([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers]),__security:{bearerAuth:!0}})}list(e={},n){return this._client.getAPIList("/assistants",It,{query:e,...n,headers:ie([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers]),__security:{bearerAuth:!0}})}delete(e,n){return this._client.delete(R`/assistants/${e}`,{...n,headers:ie([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers]),__security:{bearerAuth:!0}})}}let KO=class extends G{create(e,n){return this._client.post("/realtime/sessions",{body:e,...n,headers:ie([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers]),__security:{bearerAuth:!0}})}};class WO extends G{create(e,n){return this._client.post("/realtime/transcription_sessions",{body:e,...n,headers:ie([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers]),__security:{bearerAuth:!0}})}}let Qf=class extends G{constructor(){super(...arguments),this.sessions=new KO(this._client),this.transcriptionSessions=new WO(this._client)}};Qf.Sessions=KO;Qf.TranscriptionSessions=WO;let ZO=class extends G{create(e,n){return this._client.post("/chatkit/sessions",{body:e,...n,headers:ie([{"OpenAI-Beta":"chatkit_beta=v1"},n==null?void 0:n.headers]),__security:{bearerAuth:!0}})}cancel(e,n){return this._client.post(R`/chatkit/sessions/${e}/cancel`,{...n,headers:ie([{"OpenAI-Beta":"chatkit_beta=v1"},n==null?void 0:n.headers]),__security:{bearerAuth:!0}})}},qO=class extends G{retrieve(e,n){return this._client.get(R`/chatkit/threads/${e}`,{...n,headers:ie([{"OpenAI-Beta":"chatkit_beta=v1"},n==null?void 0:n.headers]),__security:{bearerAuth:!0}})}list(e={},n){return this._client.getAPIList("/chatkit/threads",mn,{query:e,...n,headers:ie([{"OpenAI-Beta":"chatkit_beta=v1"},n==null?void 0:n.headers]),__security:{bearerAuth:!0}})}delete(e,n){return this._client.delete(R`/chatkit/threads/${e}`,{...n,headers:ie([{"OpenAI-Beta":"chatkit_beta=v1"},n==null?void 0:n.headers]),__security:{bearerAuth:!0}})}listItems(e,n={},r){return this._client.getAPIList(R`/chatkit/threads/${e}/items`,mn,{query:n,...r,headers:ie([{"OpenAI-Beta":"chatkit_beta=v1"},r==null?void 0:r.headers]),__security:{bearerAuth:!0}})}};class ep extends G{constructor(){super(...arguments),this.sessions=new ZO(this._client),this.threads=new qO(this._client)}}ep.Sessions=ZO;ep.Threads=qO;let GO=class extends G{create(e,n,r){return this._client.post(R`/threads/${e}/messages`,{body:n,...r,headers:ie([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers]),__security:{bearerAuth:!0}})}retrieve(e,n,r){const{thread_id:s}=n;return this._client.get(R`/threads/${s}/messages/${e}`,{...r,headers:ie([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers]),__security:{bearerAuth:!0}})}update(e,n,r){const{thread_id:s,...i}=n;return this._client.post(R`/threads/${s}/messages/${e}`,{body:i,...r,headers:ie([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers]),__security:{bearerAuth:!0}})}list(e,n={},r){return this._client.getAPIList(R`/threads/${e}/messages`,It,{query:n,...r,headers:ie([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers]),__security:{bearerAuth:!0}})}delete(e,n,r){const{thread_id:s}=n;return this._client.delete(R`/threads/${s}/messages/${e}`,{...r,headers:ie([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers]),__security:{bearerAuth:!0}})}};class JO extends G{retrieve(e,n,r){const{thread_id:s,run_id:i,...a}=n;return this._client.get(R`/threads/${s}/runs/${i}/steps/${e}`,{query:a,...r,headers:ie([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers]),__security:{bearerAuth:!0}})}list(e,n,r){const{thread_id:s,...i}=n;return this._client.getAPIList(R`/threads/${s}/runs/${e}/steps`,It,{query:i,...r,headers:ie([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers]),__security:{bearerAuth:!0}})}}const nW=t=>{if(typeof Buffer<"u"){const e=Buffer.from(t,"base64");return Array.from(new Float32Array(e.buffer,e.byteOffset,e.length/Float32Array.BYTES_PER_ELEMENT))}else{const e=atob(t),n=e.length,r=new Uint8Array(n);for(let s=0;s<n;s++)r[s]=e.charCodeAt(s);return Array.from(new Float32Array(r.buffer))}};var vm={};const zr=t=>{var e,n,r,s;if(typeof globalThis.process<"u")return((e=vm==null?void 0:vm[t])==null?void 0:e.trim())||void 0;if(typeof globalThis.Deno<"u")return((s=(r=(n=globalThis.Deno.env)==null?void 0:n.get)==null?void 0:r.call(n,t))==null?void 0:s.trim())||void 0};var cn,ta,R_,os,ah,Hr,na,ao,Ji,sf,er,oh,ch,gu,Yc,Xc,IS,xS,kS,CS,OS,$S,RS;class _u extends kw{constructor(){super(...arguments),cn.add(this),R_.set(this,[]),os.set(this,{}),ah.set(this,{}),Hr.set(this,void 0),na.set(this,void 0),ao.set(this,void 0),Ji.set(this,void 0),sf.set(this,void 0),er.set(this,void 0),oh.set(this,void 0),ch.set(this,void 0),gu.set(this,void 0)}[(R_=new WeakMap,os=new WeakMap,ah=new WeakMap,Hr=new WeakMap,na=new WeakMap,ao=new WeakMap,Ji=new WeakMap,sf=new WeakMap,er=new WeakMap,oh=new WeakMap,ch=new WeakMap,gu=new WeakMap,cn=new WeakSet,Symbol.asyncIterator)](){const e=[],n=[];let r=!1;return this.on("event",s=>{const i=n.shift();i?i.resolve(s):e.push(s)}),this.on("end",()=>{r=!0;for(const s of n)s.resolve(void 0);n.length=0}),this.on("abort",s=>{r=!0;for(const i of n)i.reject(s);n.length=0}),this.on("error",s=>{r=!0;for(const i of n)i.reject(s);n.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((i,a)=>n.push({resolve:i,reject:a})).then(i=>i?{value:i,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){const n=new ta;return n._run(()=>n._fromReadableStream(e)),n}async _fromReadableStream(e,n){var i;const r=n==null?void 0:n.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),this._connected();const s=Vu.fromReadableStream(e,this.controller);for await(const a of s)N(this,cn,"m",Yc).call(this,a);if((i=s.controller.signal)!=null&&i.aborted)throw new or;return this._addRun(N(this,cn,"m",Xc).call(this))}toReadableStream(){return new Vu(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,n,r,s){const i=new ta;return i._run(()=>i._runToolAssistantStream(e,n,r,{...s,headers:{...s==null?void 0:s.headers,"X-Stainless-Helper-Method":"stream"}})),i}async _createToolAssistantStream(e,n,r,s){var c;const i=s==null?void 0:s.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener("abort",()=>this.controller.abort()));const a={...r,stream:!0},o=await e.submitToolOutputs(n,a,{...s,signal:this.controller.signal});this._connected();for await(const u of o)N(this,cn,"m",Yc).call(this,u);if((c=o.controller.signal)!=null&&c.aborted)throw new or;return this._addRun(N(this,cn,"m",Xc).call(this))}static createThreadAssistantStream(e,n,r){const s=new ta;return s._run(()=>s._threadAssistantStream(e,n,{...r,headers:{...r==null?void 0:r.headers,"X-Stainless-Helper-Method":"stream"}})),s}static createAssistantStream(e,n,r,s){const i=new ta;return i._run(()=>i._runAssistantStream(e,n,r,{...s,headers:{...s==null?void 0:s.headers,"X-Stainless-Helper-Method":"stream"}})),i}currentEvent(){return N(this,oh,"f")}currentRun(){return N(this,ch,"f")}currentMessageSnapshot(){return N(this,Hr,"f")}currentRunStepSnapshot(){return N(this,gu,"f")}async finalRunSteps(){return await this.done(),Object.values(N(this,os,"f"))}async finalMessages(){return await this.done(),Object.values(N(this,ah,"f"))}async finalRun(){if(await this.done(),!N(this,na,"f"))throw Error("Final run was not received.");return N(this,na,"f")}async _createThreadAssistantStream(e,n,r){var o;const s=r==null?void 0:r.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort()));const i={...n,stream:!0},a=await e.createAndRun(i,{...r,signal:this.controller.signal});this._connected();for await(const c of a)N(this,cn,"m",Yc).call(this,c);if((o=a.controller.signal)!=null&&o.aborted)throw new or;return this._addRun(N(this,cn,"m",Xc).call(this))}async _createAssistantStream(e,n,r,s){var c;const i=s==null?void 0:s.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener("abort",()=>this.controller.abort()));const a={...r,stream:!0},o=await e.create(n,a,{...s,signal:this.controller.signal});this._connected();for await(const u of o)N(this,cn,"m",Yc).call(this,u);if((c=o.controller.signal)!=null&&c.aborted)throw new or;return this._addRun(N(this,cn,"m",Xc).call(this))}static accumulateDelta(e,n){for(const[r,s]of Object.entries(n)){if(!e.hasOwnProperty(r)){e[r]=s;continue}let i=e[r];if(i==null){e[r]=s;continue}if(r==="index"||r==="type"){e[r]=s;continue}if(typeof i=="string"&&typeof s=="string")i+=s;else if(typeof i=="number"&&typeof s=="number")i+=s;else if(th(i)&&th(s))i=this.accumulateDelta(i,s);else if(Array.isArray(i)&&Array.isArray(s)){if(i.every(a=>typeof a=="string"||typeof a=="number")){i.push(...s);continue}for(const a of s){if(!th(a))throw new Error(`Expected array delta entry to be an object but got: ${a}`);const o=a.index;if(o==null)throw console.error(a),new Error("Expected array delta entry to have an `index` property");if(typeof o!="number")throw new Error(`Expected array delta entry \`index\` property to be a number but got ${o}`);const c=i[o];c==null?i.push(a):i[o]=this.accumulateDelta(c,a)}continue}else throw Error(`Unhandled record type: ${r}, deltaValue: ${s}, accValue: ${i}`);e[r]=i}return e}_addRun(e){return e}async _threadAssistantStream(e,n,r){return await this._createThreadAssistantStream(n,e,r)}async _runAssistantStream(e,n,r,s){return await this._createAssistantStream(n,e,r,s)}async _runToolAssistantStream(e,n,r,s){return await this._createToolAssistantStream(n,e,r,s)}}ta=_u,Yc=function(e){if(!this.ended)switch(Oe(this,oh,e),N(this,cn,"m",kS).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":N(this,cn,"m",RS).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":N(this,cn,"m",xS).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":N(this,cn,"m",IS).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier")}},Xc=function(){if(this.ended)throw new ye("stream has ended, this shouldn't happen");if(!N(this,na,"f"))throw Error("Final run has not been received");return N(this,na,"f")},IS=function(e){const[n,r]=N(this,cn,"m",OS).call(this,e,N(this,Hr,"f"));Oe(this,Hr,n),N(this,ah,"f")[n.id]=n;for(const s of r){const i=n.content[s.index];(i==null?void 0:i.type)=="text"&&this._emit("textCreated",i.text)}switch(e.event){case"thread.message.created":this._emit("messageCreated",e.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",e.data.delta,n),e.data.delta.content)for(const s of e.data.delta.content){if(s.type=="text"&&s.text){let i=s.text,a=n.content[s.index];if(a&&a.type=="text")this._emit("textDelta",i,a.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(s.index!=N(this,ao,"f")){if(N(this,Ji,"f"))switch(N(this,Ji,"f").type){case"text":this._emit("textDone",N(this,Ji,"f").text,N(this,Hr,"f"));break;case"image_file":this._emit("imageFileDone",N(this,Ji,"f").image_file,N(this,Hr,"f"));break}Oe(this,ao,s.index)}Oe(this,Ji,n.content[s.index])}break;case"thread.message.completed":case"thread.message.incomplete":if(N(this,ao,"f")!==void 0){const s=e.data.content[N(this,ao,"f")];if(s)switch(s.type){case"image_file":this._emit("imageFileDone",s.image_file,N(this,Hr,"f"));break;case"text":this._emit("textDone",s.text,N(this,Hr,"f"));break}}N(this,Hr,"f")&&this._emit("messageDone",e.data),Oe(this,Hr,void 0)}},xS=function(e){const n=N(this,cn,"m",CS).call(this,e);switch(Oe(this,gu,n),e.event){case"thread.run.step.created":this._emit("runStepCreated",e.data);break;case"thread.run.step.delta":const r=e.data.delta;if(r.step_details&&r.step_details.type=="tool_calls"&&r.step_details.tool_calls&&n.step_details.type=="tool_calls")for(const i of r.step_details.tool_calls)i.index==N(this,sf,"f")?this._emit("toolCallDelta",i,n.step_details.tool_calls[i.index]):(N(this,er,"f")&&this._emit("toolCallDone",N(this,er,"f")),Oe(this,sf,i.index),Oe(this,er,n.step_details.tool_calls[i.index]),N(this,er,"f")&&this._emit("toolCallCreated",N(this,er,"f")));this._emit("runStepDelta",e.data.delta,n);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":Oe(this,gu,void 0),e.data.step_details.type=="tool_calls"&&N(this,er,"f")&&(this._emit("toolCallDone",N(this,er,"f")),Oe(this,er,void 0)),this._emit("runStepDone",e.data,n);break}},kS=function(e){N(this,R_,"f").push(e),this._emit("event",e)},CS=function(e){switch(e.event){case"thread.run.step.created":return N(this,os,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let n=N(this,os,"f")[e.data.id];if(!n)throw Error("Received a RunStepDelta before creation of a snapshot");let r=e.data;if(r.delta){const s=ta.accumulateDelta(n,r.delta);N(this,os,"f")[e.data.id]=s}return N(this,os,"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":N(this,os,"f")[e.data.id]=e.data;break}if(N(this,os,"f")[e.data.id])return N(this,os,"f")[e.data.id];throw new Error("No snapshot available")},OS=function(e,n){let r=[];switch(e.event){case"thread.message.created":return[e.data,r];case"thread.message.delta":if(!n)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let s=e.data;if(s.delta.content)for(const i of s.delta.content)if(i.index in n.content){let a=n.content[i.index];n.content[i.index]=N(this,cn,"m",$S).call(this,i,a)}else n.content[i.index]=i,r.push(i);return[n,r];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(n)return[n,r];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},$S=function(e,n){return ta.accumulateDelta(n,e)},RS=function(e){switch(Oe(this,ch,e.data),e.event){case"thread.run.created":break;case"thread.run.queued":break;case"thread.run.in_progress":break;case"thread.run.requires_action":case"thread.run.cancelled":case"thread.run.failed":case"thread.run.completed":case"thread.run.expired":case"thread.run.incomplete":Oe(this,na,e.data),N(this,er,"f")&&(this._emit("toolCallDone",N(this,er,"f")),Oe(this,er,void 0));break}};let Lw=class extends G{constructor(){super(...arguments),this.steps=new JO(this._client)}create(e,n,r){const{include:s,...i}=n;return this._client.post(R`/threads/${e}/runs`,{query:{include:s},body:i,...r,headers:ie([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers]),stream:n.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}retrieve(e,n,r){const{thread_id:s}=n;return this._client.get(R`/threads/${s}/runs/${e}`,{...r,headers:ie([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers]),__security:{bearerAuth:!0}})}update(e,n,r){const{thread_id:s,...i}=n;return this._client.post(R`/threads/${s}/runs/${e}`,{body:i,...r,headers:ie([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers]),__security:{bearerAuth:!0}})}list(e,n={},r){return this._client.getAPIList(R`/threads/${e}/runs`,It,{query:n,...r,headers:ie([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers]),__security:{bearerAuth:!0}})}cancel(e,n,r){const{thread_id:s}=n;return this._client.post(R`/threads/${s}/runs/${e}/cancel`,{...r,headers:ie([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,n,r){const s=await this.create(e,n,r);return await this.poll(s.id,{thread_id:e},r)}createAndStream(e,n,r){return _u.createAssistantStream(e,this._client.beta.threads.runs,n,r)}async poll(e,n,r){var i;const s=ie([r==null?void 0:r.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":((i=r==null?void 0:r.pollIntervalMs)==null?void 0:i.toString())??void 0}]);for(;;){const{data:a,response:o}=await this.retrieve(e,n,{...r,headers:{...r==null?void 0:r.headers,...s}}).withResponse();switch(a.status){case"queued":case"in_progress":case"cancelling":let c=5e3;if(r!=null&&r.pollIntervalMs)c=r.pollIntervalMs;else{const u=o.headers.get("openai-poll-after-ms");if(u){const l=parseInt(u);isNaN(l)||(c=l)}}await Cl(c);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return a}}}stream(e,n,r){return _u.createAssistantStream(e,this._client.beta.threads.runs,n,r)}submitToolOutputs(e,n,r){const{thread_id:s,...i}=n;return this._client.post(R`/threads/${s}/runs/${e}/submit_tool_outputs`,{body:i,...r,headers:ie([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers]),stream:n.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}async submitToolOutputsAndPoll(e,n,r){const s=await this.submitToolOutputs(e,n,r);return await this.poll(s.id,n,r)}submitToolOutputsStream(e,n,r){return _u.createToolAssistantStream(e,this._client.beta.threads.runs,n,r)}};Lw.Steps=JO;let tp=class extends G{constructor(){super(...arguments),this.runs=new Lw(this._client),this.messages=new GO(this._client)}create(e={},n){return this._client.post("/threads",{body:e,...n,headers:ie([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers]),__security:{bearerAuth:!0}})}retrieve(e,n){return this._client.get(R`/threads/${e}`,{...n,headers:ie([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers]),__security:{bearerAuth:!0}})}update(e,n,r){return this._client.post(R`/threads/${e}`,{body:n,...r,headers:ie([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers]),__security:{bearerAuth:!0}})}delete(e,n){return this._client.delete(R`/threads/${e}`,{...n,headers:ie([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers]),__security:{bearerAuth:!0}})}createAndRun(e,n){return this._client.post("/threads/runs",{body:e,...n,headers:ie([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers]),stream:e.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}async createAndRunPoll(e,n){const r=await this.createAndRun(e,n);return await this.runs.poll(r.id,{thread_id:r.thread_id},n)}createAndRunStream(e,n){return _u.createThreadAssistantStream(e,this._client.beta.threads,n)}};tp.Runs=Lw;tp.Messages=GO;let sc=class extends G{constructor(){super(...arguments),this.realtime=new Qf(this._client),this.chatkit=new ep(this._client),this.assistants=new VO(this._client),this.threads=new tp(this._client)}};sc.Realtime=Qf;sc.ChatKit=ep;sc.Assistants=VO;sc.Threads=tp;let YO=class extends G{create(e,n){return this._client.post("/completions",{body:e,...n,stream:e.stream??!1,__security:{bearerAuth:!0}})}},XO=class extends G{retrieve(e,n,r){const{container_id:s}=n;return this._client.get(R`/containers/${s}/files/${e}/content`,{...r,headers:ie([{Accept:"application/binary"},r==null?void 0:r.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}},jw=class extends G{constructor(){super(...arguments),this.content=new XO(this._client)}create(e,n,r){return this._client.post(R`/containers/${e}/files`,Yf({body:n,...r,__security:{bearerAuth:!0}},this._client))}retrieve(e,n,r){const{container_id:s}=n;return this._client.get(R`/containers/${s}/files/${e}`,{...r,__security:{bearerAuth:!0}})}list(e,n={},r){return this._client.getAPIList(R`/containers/${e}/files`,It,{query:n,...r,__security:{bearerAuth:!0}})}delete(e,n,r){const{container_id:s}=n;return this._client.delete(R`/containers/${s}/files/${e}`,{...r,headers:ie([{Accept:"*/*"},r==null?void 0:r.headers]),__security:{bearerAuth:!0}})}};jw.Content=XO;class Dw extends G{constructor(){super(...arguments),this.files=new jw(this._client)}create(e,n){return this._client.post("/containers",{body:e,...n,__security:{bearerAuth:!0}})}retrieve(e,n){return this._client.get(R`/containers/${e}`,{...n,__security:{bearerAuth:!0}})}list(e={},n){return this._client.getAPIList("/containers",It,{query:e,...n,__security:{bearerAuth:!0}})}delete(e,n){return this._client.delete(R`/containers/${e}`,{...n,headers:ie([{Accept:"*/*"},n==null?void 0:n.headers]),__security:{bearerAuth:!0}})}}Dw.Files=jw;class QO extends G{create(e,n,r){const{include:s,...i}=n;return this._client.post(R`/conversations/${e}/items`,{query:{include:s},body:i,...r,__security:{bearerAuth:!0}})}retrieve(e,n,r){const{conversation_id:s,...i}=n;return this._client.get(R`/conversations/${s}/items/${e}`,{query:i,...r,__security:{bearerAuth:!0}})}list(e,n={},r){return this._client.getAPIList(R`/conversations/${e}/items`,mn,{query:n,...r,__security:{bearerAuth:!0}})}delete(e,n,r){const{conversation_id:s}=n;return this._client.delete(R`/conversations/${s}/items/${e}`,{...r,__security:{bearerAuth:!0}})}}class Uw extends G{constructor(){super(...arguments),this.items=new QO(this._client)}create(e={},n){return this._client.post("/conversations",{body:e,...n,__security:{bearerAuth:!0}})}retrieve(e,n){return this._client.get(R`/conversations/${e}`,{...n,__security:{bearerAuth:!0}})}update(e,n,r){return this._client.post(R`/conversations/${e}`,{body:n,...r,__security:{bearerAuth:!0}})}delete(e,n){return this._client.delete(R`/conversations/${e}`,{...n,__security:{bearerAuth:!0}})}}Uw.Items=QO;class e1 extends G{create(e,n){const r=!!e.encoding_format;let s=r?e.encoding_format:"base64";r&&on(this._client).debug("embeddings/user defined encoding_format:",e.encoding_format);const i=this._client.post("/embeddings",{body:{...e,encoding_format:s},...n,__security:{bearerAuth:!0}});return r?i:(on(this._client).debug("embeddings/decoding base64 embeddings from base64"),i._thenUnwrap(a=>(a&&a.data&&a.data.forEach(o=>{const c=o.embedding;o.embedding=nW(c)}),a)))}}class t1 extends G{retrieve(e,n,r){const{eval_id:s,run_id:i}=n;return this._client.get(R`/evals/${s}/runs/${i}/output_items/${e}`,{...r,__security:{bearerAuth:!0}})}list(e,n,r){const{eval_id:s,...i}=n;return this._client.getAPIList(R`/evals/${s}/runs/${e}/output_items`,It,{query:i,...r,__security:{bearerAuth:!0}})}}class Fw extends G{constructor(){super(...arguments),this.outputItems=new t1(this._client)}create(e,n,r){return this._client.post(R`/evals/${e}/runs`,{body:n,...r,__security:{bearerAuth:!0}})}retrieve(e,n,r){const{eval_id:s}=n;return this._client.get(R`/evals/${s}/runs/${e}`,{...r,__security:{bearerAuth:!0}})}list(e,n={},r){return this._client.getAPIList(R`/evals/${e}/runs`,It,{query:n,...r,__security:{bearerAuth:!0}})}delete(e,n,r){const{eval_id:s}=n;return this._client.delete(R`/evals/${s}/runs/${e}`,{...r,__security:{bearerAuth:!0}})}cancel(e,n,r){const{eval_id:s}=n;return this._client.post(R`/evals/${s}/runs/${e}`,{...r,__security:{bearerAuth:!0}})}}Fw.OutputItems=t1;class Bw extends G{constructor(){super(...arguments),this.runs=new Fw(this._client)}create(e,n){return this._client.post("/evals",{body:e,...n,__security:{bearerAuth:!0}})}retrieve(e,n){return this._client.get(R`/evals/${e}`,{...n,__security:{bearerAuth:!0}})}update(e,n,r){return this._client.post(R`/evals/${e}`,{body:n,...r,__security:{bearerAuth:!0}})}list(e={},n){return this._client.getAPIList("/evals",It,{query:e,...n,__security:{bearerAuth:!0}})}delete(e,n){return this._client.delete(R`/evals/${e}`,{...n,__security:{bearerAuth:!0}})}}Bw.Runs=Fw;let n1=class extends G{create(e,n){return this._client.post("/files",ms({body:e,...n,__security:{bearerAuth:!0}},this._client))}retrieve(e,n){return this._client.get(R`/files/${e}`,{...n,__security:{bearerAuth:!0}})}list(e={},n){return this._client.getAPIList("/files",It,{query:e,...n,__security:{bearerAuth:!0}})}delete(e,n){return this._client.delete(R`/files/${e}`,{...n,__security:{bearerAuth:!0}})}content(e,n){return this._client.get(R`/files/${e}/content`,{...n,headers:ie([{Accept:"application/binary"},n==null?void 0:n.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:n=5e3,maxWait:r=30*60*1e3}={}){const s=new Set(["processed","error","deleted"]),i=Date.now();let a=await this.retrieve(e);for(;!a.status||!s.has(a.status);)if(await Cl(n),a=await this.retrieve(e),Date.now()-i>r)throw new qf({message:`Giving up on waiting for file ${e} to finish processing after ${r} milliseconds.`});return a}};class r1 extends G{}let s1=class extends G{run(e,n){return this._client.post("/fine_tuning/alpha/graders/run",{body:e,...n,__security:{bearerAuth:!0}})}validate(e,n){return this._client.post("/fine_tuning/alpha/graders/validate",{body:e,...n,__security:{bearerAuth:!0}})}};class zw extends G{constructor(){super(...arguments),this.graders=new s1(this._client)}}zw.Graders=s1;class i1 extends G{create(e,n,r){return this._client.getAPIList(R`/fine_tuning/checkpoints/${e}/permissions`,Ni,{body:n,method:"post",...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,n={},r){return this._client.get(R`/fine_tuning/checkpoints/${e}/permissions`,{query:n,...r,__security:{adminAPIKeyAuth:!0}})}list(e,n={},r){return this._client.getAPIList(R`/fine_tuning/checkpoints/${e}/permissions`,mn,{query:n,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,n,r){const{fine_tuned_model_checkpoint:s}=n;return this._client.delete(R`/fine_tuning/checkpoints/${s}/permissions/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}}let Hw=class extends G{constructor(){super(...arguments),this.permissions=new i1(this._client)}};Hw.Permissions=i1;class a1 extends G{list(e,n={},r){return this._client.getAPIList(R`/fine_tuning/jobs/${e}/checkpoints`,It,{query:n,...r,__security:{bearerAuth:!0}})}}class Vw extends G{constructor(){super(...arguments),this.checkpoints=new a1(this._client)}create(e,n){return this._client.post("/fine_tuning/jobs",{body:e,...n,__security:{bearerAuth:!0}})}retrieve(e,n){return this._client.get(R`/fine_tuning/jobs/${e}`,{...n,__security:{bearerAuth:!0}})}list(e={},n){return this._client.getAPIList("/fine_tuning/jobs",It,{query:e,...n,__security:{bearerAuth:!0}})}cancel(e,n){return this._client.post(R`/fine_tuning/jobs/${e}/cancel`,{...n,__security:{bearerAuth:!0}})}listEvents(e,n={},r){return this._client.getAPIList(R`/fine_tuning/jobs/${e}/events`,It,{query:n,...r,__security:{bearerAuth:!0}})}pause(e,n){return this._client.post(R`/fine_tuning/jobs/${e}/pause`,{...n,__security:{bearerAuth:!0}})}resume(e,n){return this._client.post(R`/fine_tuning/jobs/${e}/resume`,{...n,__security:{bearerAuth:!0}})}}Vw.Checkpoints=a1;class ic extends G{constructor(){super(...arguments),this.methods=new r1(this._client),this.jobs=new Vw(this._client),this.checkpoints=new Hw(this._client),this.alpha=new zw(this._client)}}ic.Methods=r1;ic.Jobs=Vw;ic.Checkpoints=Hw;ic.Alpha=zw;class o1 extends G{}class Kw extends G{constructor(){super(...arguments),this.graderModels=new o1(this._client)}}Kw.GraderModels=o1;class c1 extends G{createVariation(e,n){return this._client.post("/images/variations",ms({body:e,...n,__security:{bearerAuth:!0}},this._client))}edit(e,n){return this._client.post("/images/edits",ms({body:e,...n,stream:e.stream??!1,__security:{bearerAuth:!0}},this._client))}generate(e,n){return this._client.post("/images/generations",{body:e,...n,stream:e.stream??!1,__security:{bearerAuth:!0}})}}let u1=class extends G{retrieve(e,n){return this._client.get(R`/models/${e}`,{...n,__security:{bearerAuth:!0}})}list(e){return this._client.getAPIList("/models",Ni,{...e,__security:{bearerAuth:!0}})}delete(e,n){return this._client.delete(R`/models/${e}`,{...n,__security:{bearerAuth:!0}})}};class l1 extends G{create(e,n){return this._client.post("/moderations",{body:e,...n,__security:{bearerAuth:!0}})}}class d1 extends G{accept(e,n,r){return this._client.post(R`/realtime/calls/${e}/accept`,{body:n,...r,headers:ie([{Accept:"*/*"},r==null?void 0:r.headers]),__security:{bearerAuth:!0}})}hangup(e,n){return this._client.post(R`/realtime/calls/${e}/hangup`,{...n,headers:ie([{Accept:"*/*"},n==null?void 0:n.headers]),__security:{bearerAuth:!0}})}refer(e,n,r){return this._client.post(R`/realtime/calls/${e}/refer`,{body:n,...r,headers:ie([{Accept:"*/*"},r==null?void 0:r.headers]),__security:{bearerAuth:!0}})}reject(e,n={},r){return this._client.post(R`/realtime/calls/${e}/reject`,{body:n,...r,headers:ie([{Accept:"*/*"},r==null?void 0:r.headers]),__security:{bearerAuth:!0}})}}class h1 extends G{create(e,n){return this._client.post("/realtime/client_secrets",{body:e,...n,__security:{bearerAuth:!0}})}}class np extends G{constructor(){super(...arguments),this.clientSecrets=new h1(this._client),this.calls=new d1(this._client)}}np.ClientSecrets=h1;np.Calls=d1;function rW(t,e){return!e||!iW(e)?{...t,output_parsed:null,output:t.output.map(n=>n.type==="function_call"?{...n,parsed_arguments:null}:n.type==="message"?{...n,content:n.content.map(r=>({...r,parsed:null}))}:n)}:f1(t,e)}function f1(t,e){const n=t.output.map(s=>{if(s.type==="function_call")return{...s,parsed_arguments:cW(e,s)};if(s.type==="message"){const i=s.content.map(a=>a.type==="output_text"?{...a,parsed:sW(e,a.text)}:a);return{...s,content:i}}return s}),r=Object.assign({},t,{output:n});return Object.getOwnPropertyDescriptor(t,"output_text")||P_(r),Object.defineProperty(r,"output_parsed",{enumerable:!0,get(){for(const s of r.output)if(s.type==="message"){for(const i of s.content)if(i.type==="output_text"&&i.parsed!==null)return i.parsed}return null}}),r}function sW(t,e){var n,r,s,i;return((r=(n=t.text)==null?void 0:n.format)==null?void 0:r.type)!=="json_schema"?null:"$parseRaw"in((s=t.text)==null?void 0:s.format)?((i=t.text)==null?void 0:i.format).$parseRaw(e):JSON.parse(e)}function iW(t){var e;return!!Iw((e=t.text)==null?void 0:e.format)}function aW(t){return(t==null?void 0:t.$brand)==="auto-parseable-tool"}function oW(t,e){return t.find(n=>n.type==="function"&&n.name===e)}function cW(t,e){const n=oW(t.tools??[],e.name);return{...e,...e,parsed_arguments:aW(n)?n.$parseRaw(e.arguments):n!=null&&n.strict?JSON.parse(e.arguments):null}}function P_(t){const e=[];for(const n of t.output)if(n.type==="message")for(const r of n.content)r.type==="output_text"&&e.push(r.text);t.output_text=e.join("")}var Ua,bd,ei,vd,PS,NS,MS,LS;class Ww extends kw{constructor(e){super(),Ua.add(this),bd.set(this,void 0),ei.set(this,void 0),vd.set(this,void 0),Oe(this,bd,e)}static createResponse(e,n,r){const s=new Ww(n);return s._run(()=>s._createOrRetrieveResponse(e,n,{...r,headers:{...r==null?void 0:r.headers,"X-Stainless-Helper-Method":"stream"}})),s}async _createOrRetrieveResponse(e,n,r){var o;const s=r==null?void 0:r.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),N(this,Ua,"m",PS).call(this);let i,a=null;"response_id"in n?(i=await e.responses.retrieve(n.response_id,{stream:!0},{...r,signal:this.controller.signal,stream:!0}),a=n.starting_after??null):i=await e.responses.create({...n,stream:!0},{...r,signal:this.controller.signal}),this._connected();for await(const c of i)N(this,Ua,"m",NS).call(this,c,a);if((o=i.controller.signal)!=null&&o.aborted)throw new or;return N(this,Ua,"m",MS).call(this)}[(bd=new WeakMap,ei=new WeakMap,vd=new WeakMap,Ua=new WeakSet,PS=function(){this.ended||Oe(this,ei,void 0)},NS=function(n,r){if(this.ended)return;const s=(a,o)=>{(r==null||o.sequence_number>r)&&this._emit(a,o)},i=N(this,Ua,"m",LS).call(this,n);switch(s("event",n),n.type){case"response.output_text.delta":{const a=i.output[n.output_index];if(!a)throw new ye(`missing output at index ${n.output_index}`);if(a.type==="message"){const o=a.content[n.content_index];if(!o)throw new ye(`missing content at index ${n.content_index}`);if(o.type!=="output_text")throw new ye(`expected content to be 'output_text', got ${o.type}`);s("response.output_text.delta",{...n,snapshot:o.text})}break}case"response.function_call_arguments.delta":{const a=i.output[n.output_index];if(!a)throw new ye(`missing output at index ${n.output_index}`);a.type==="function_call"&&s("response.function_call_arguments.delta",{...n,snapshot:a.arguments});break}default:s(n.type,n);break}},MS=function(){if(this.ended)throw new ye("stream has ended, this shouldn't happen");const n=N(this,ei,"f");if(!n)throw new ye("request ended without sending any events");Oe(this,ei,void 0);const r=uW(n,N(this,bd,"f"));return Oe(this,vd,r),r},LS=function(n){var s;let r=N(this,ei,"f");if(!r){if(n.type!=="response.created")throw new ye(`When snapshot hasn't been set yet, expected 'response.created' event, got ${n.type}`);return r=Oe(this,ei,n.response),r}switch(n.type){case"response.output_item.added":{r.output.push(n.item);break}case"response.content_part.added":{const i=r.output[n.output_index];if(!i)throw new ye(`missing output at index ${n.output_index}`);const a=i.type,o=n.part;a==="message"&&o.type!=="reasoning_text"?i.content.push(o):a==="reasoning"&&o.type==="reasoning_text"&&(i.content||(i.content=[]),i.content.push(o));break}case"response.output_text.delta":{const i=r.output[n.output_index];if(!i)throw new ye(`missing output at index ${n.output_index}`);if(i.type==="message"){const a=i.content[n.content_index];if(!a)throw new ye(`missing content at index ${n.content_index}`);if(a.type!=="output_text")throw new ye(`expected content to be 'output_text', got ${a.type}`);a.text+=n.delta}break}case"response.function_call_arguments.delta":{const i=r.output[n.output_index];if(!i)throw new ye(`missing output at index ${n.output_index}`);i.type==="function_call"&&(i.arguments+=n.delta);break}case"response.reasoning_text.delta":{const i=r.output[n.output_index];if(!i)throw new ye(`missing output at index ${n.output_index}`);if(i.type==="reasoning"){const a=(s=i.content)==null?void 0:s[n.content_index];if(!a)throw new ye(`missing content at index ${n.content_index}`);if(a.type!=="reasoning_text")throw new ye(`expected content to be 'reasoning_text', got ${a.type}`);a.text+=n.delta}break}case"response.completed":{Oe(this,ei,n.response);break}}return r},Symbol.asyncIterator)](){const e=[],n=[];let r=!1;return this.on("event",s=>{const i=n.shift();i?i.resolve(s):e.push(s)}),this.on("end",()=>{r=!0;for(const s of n)s.resolve(void 0);n.length=0}),this.on("abort",s=>{r=!0;for(const i of n)i.reject(s);n.length=0}),this.on("error",s=>{r=!0;for(const i of n)i.reject(s);n.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((i,a)=>n.push({resolve:i,reject:a})).then(i=>i?{value:i,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();const e=N(this,vd,"f");if(!e)throw new ye("stream ended without producing a ChatCompletion");return e}}function uW(t,e){return rW(t,e)}class p1 extends G{list(e,n={},r){return this._client.getAPIList(R`/responses/${e}/input_items`,It,{query:n,...r,__security:{bearerAuth:!0}})}}class m1 extends G{count(e={},n){return this._client.post("/responses/input_tokens",{body:e,...n,__security:{bearerAuth:!0}})}}class rp extends G{constructor(){super(...arguments),this.inputItems=new p1(this._client),this.inputTokens=new m1(this._client)}create(e,n){return this._client.post("/responses",{body:e,...n,stream:e.stream??!1,__security:{bearerAuth:!0}})._thenUnwrap(r=>("object"in r&&r.object==="response"&&P_(r),r))}retrieve(e,n={},r){return this._client.get(R`/responses/${e}`,{query:n,...r,stream:(n==null?void 0:n.stream)??!1,__security:{bearerAuth:!0}})._thenUnwrap(s=>("object"in s&&s.object==="response"&&P_(s),s))}delete(e,n){return this._client.delete(R`/responses/${e}`,{...n,headers:ie([{Accept:"*/*"},n==null?void 0:n.headers]),__security:{bearerAuth:!0}})}parse(e,n){return this._client.responses.create(e,n)._thenUnwrap(r=>f1(r,e))}stream(e,n){return Ww.createResponse(this._client,e,n)}cancel(e,n){return this._client.post(R`/responses/${e}/cancel`,{...n,__security:{bearerAuth:!0}})}compact(e,n){return this._client.post("/responses/compact",{body:e,...n,__security:{bearerAuth:!0}})}}rp.InputItems=p1;rp.InputTokens=m1;let g1=class extends G{retrieve(e,n){return this._client.get(R`/skills/${e}/content`,{...n,headers:ie([{Accept:"application/binary"},n==null?void 0:n.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};class _1 extends G{retrieve(e,n,r){const{skill_id:s}=n;return this._client.get(R`/skills/${s}/versions/${e}/content`,{...r,headers:ie([{Accept:"application/binary"},r==null?void 0:r.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}}let Zw=class extends G{constructor(){super(...arguments),this.content=new _1(this._client)}create(e,n={},r){return this._client.post(R`/skills/${e}/versions`,Yf({body:n,...r,__security:{bearerAuth:!0}},this._client))}retrieve(e,n,r){const{skill_id:s}=n;return this._client.get(R`/skills/${s}/versions/${e}`,{...r,__security:{bearerAuth:!0}})}list(e,n={},r){return this._client.getAPIList(R`/skills/${e}/versions`,It,{query:n,...r,__security:{bearerAuth:!0}})}delete(e,n,r){const{skill_id:s}=n;return this._client.delete(R`/skills/${s}/versions/${e}`,{...r,__security:{bearerAuth:!0}})}};Zw.Content=_1;let sp=class extends G{constructor(){super(...arguments),this.content=new g1(this._client),this.versions=new Zw(this._client)}create(e={},n){return this._client.post("/skills",Yf({body:e,...n,__security:{bearerAuth:!0}},this._client))}retrieve(e,n){return this._client.get(R`/skills/${e}`,{...n,__security:{bearerAuth:!0}})}update(e,n,r){return this._client.post(R`/skills/${e}`,{body:n,...r,__security:{bearerAuth:!0}})}list(e={},n){return this._client.getAPIList("/skills",It,{query:e,...n,__security:{bearerAuth:!0}})}delete(e,n){return this._client.delete(R`/skills/${e}`,{...n,__security:{bearerAuth:!0}})}};sp.Content=g1;sp.Versions=Zw;class y1 extends G{create(e,n,r){return this._client.post(R`/uploads/${e}/parts`,ms({body:n,...r,__security:{bearerAuth:!0}},this._client))}}class qw extends G{constructor(){super(...arguments),this.parts=new y1(this._client)}create(e,n){return this._client.post("/uploads",{body:e,...n,__security:{bearerAuth:!0}})}cancel(e,n){return this._client.post(R`/uploads/${e}/cancel`,{...n,__security:{bearerAuth:!0}})}complete(e,n,r){return this._client.post(R`/uploads/${e}/complete`,{body:n,...r,__security:{bearerAuth:!0}})}}qw.Parts=y1;const lW=async t=>{const e=await Promise.allSettled(t),n=e.filter(s=>s.status==="rejected");if(n.length){for(const s of n)console.error(s.reason);throw new Error(`${n.length} promise(s) failed - see the above errors`)}const r=[];for(const s of e)s.status==="fulfilled"&&r.push(s.value);return r};class w1 extends G{create(e,n,r){return this._client.post(R`/vector_stores/${e}/file_batches`,{body:n,...r,headers:ie([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers]),__security:{bearerAuth:!0}})}retrieve(e,n,r){const{vector_store_id:s}=n;return this._client.get(R`/vector_stores/${s}/file_batches/${e}`,{...r,headers:ie([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers]),__security:{bearerAuth:!0}})}cancel(e,n,r){const{vector_store_id:s}=n;return this._client.post(R`/vector_stores/${s}/file_batches/${e}/cancel`,{...r,headers:ie([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,n,r){const s=await this.create(e,n);return await this.poll(e,s.id,r)}listFiles(e,n,r){const{vector_store_id:s,...i}=n;return this._client.getAPIList(R`/vector_stores/${s}/file_batches/${e}/files`,It,{query:i,...r,headers:ie([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers]),__security:{bearerAuth:!0}})}async poll(e,n,r){var i;const s=ie([r==null?void 0:r.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":((i=r==null?void 0:r.pollIntervalMs)==null?void 0:i.toString())??void 0}]);for(;;){const{data:a,response:o}=await this.retrieve(n,{vector_store_id:e},{...r,headers:s}).withResponse();switch(a.status){case"in_progress":let c=5e3;if(r!=null&&r.pollIntervalMs)c=r.pollIntervalMs;else{const u=o.headers.get("openai-poll-after-ms");if(u){const l=parseInt(u);isNaN(l)||(c=l)}}await Cl(c);break;case"failed":case"cancelled":case"completed":return a}}}async uploadAndPoll(e,{files:n,fileIds:r=[]},s){if(n==null||n.length==0)throw new Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");const i=(s==null?void 0:s.maxConcurrency)??5,a=Math.min(i,n.length),o=this._client,c=n.values(),u=[...r];async function l(f){for(let h of f){const p=await o.files.create({file:h,purpose:"assistants"},s);u.push(p.id)}}const d=Array(a).fill(c).map(l);return await lW(d),await this.createAndPoll(e,{file_ids:u})}}let b1=class extends G{create(e,n,r){return this._client.post(R`/vector_stores/${e}/files`,{body:n,...r,headers:ie([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers]),__security:{bearerAuth:!0}})}retrieve(e,n,r){const{vector_store_id:s}=n;return this._client.get(R`/vector_stores/${s}/files/${e}`,{...r,headers:ie([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers]),__security:{bearerAuth:!0}})}update(e,n,r){const{vector_store_id:s,...i}=n;return this._client.post(R`/vector_stores/${s}/files/${e}`,{body:i,...r,headers:ie([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers]),__security:{bearerAuth:!0}})}list(e,n={},r){return this._client.getAPIList(R`/vector_stores/${e}/files`,It,{query:n,...r,headers:ie([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers]),__security:{bearerAuth:!0}})}delete(e,n,r){const{vector_store_id:s}=n;return this._client.delete(R`/vector_stores/${s}/files/${e}`,{...r,headers:ie([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,n,r){const s=await this.create(e,n,r);return await this.poll(e,s.id,r)}async poll(e,n,r){var i;const s=ie([r==null?void 0:r.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":((i=r==null?void 0:r.pollIntervalMs)==null?void 0:i.toString())??void 0}]);for(;;){const a=await this.retrieve(n,{vector_store_id:e},{...r,headers:s}).withResponse(),o=a.data;switch(o.status){case"in_progress":let c=5e3;if(r!=null&&r.pollIntervalMs)c=r.pollIntervalMs;else{const u=a.response.headers.get("openai-poll-after-ms");if(u){const l=parseInt(u);isNaN(l)||(c=l)}}await Cl(c);break;case"failed":case"completed":return o}}}async upload(e,n,r){const s=await this._client.files.create({file:n,purpose:"assistants"},r);return this.create(e,{file_id:s.id},r)}async uploadAndPoll(e,n,r){const s=await this.upload(e,n,r);return await this.poll(e,s.id,r)}content(e,n,r){const{vector_store_id:s}=n;return this._client.getAPIList(R`/vector_stores/${s}/files/${e}/content`,Ni,{...r,headers:ie([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers]),__security:{bearerAuth:!0}})}};class ip extends G{constructor(){super(...arguments),this.files=new b1(this._client),this.fileBatches=new w1(this._client)}create(e,n){return this._client.post("/vector_stores",{body:e,...n,headers:ie([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers]),__security:{bearerAuth:!0}})}retrieve(e,n){return this._client.get(R`/vector_stores/${e}`,{...n,headers:ie([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers]),__security:{bearerAuth:!0}})}update(e,n,r){return this._client.post(R`/vector_stores/${e}`,{body:n,...r,headers:ie([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers]),__security:{bearerAuth:!0}})}list(e={},n){return this._client.getAPIList("/vector_stores",It,{query:e,...n,headers:ie([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers]),__security:{bearerAuth:!0}})}delete(e,n){return this._client.delete(R`/vector_stores/${e}`,{...n,headers:ie([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers]),__security:{bearerAuth:!0}})}search(e,n,r){return this._client.getAPIList(R`/vector_stores/${e}/search`,Ni,{body:n,method:"post",...r,headers:ie([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers]),__security:{bearerAuth:!0}})}}ip.Files=b1;ip.FileBatches=w1;class v1 extends G{create(e,n){return this._client.post("/videos",ms({body:e,...n,__security:{bearerAuth:!0}},this._client))}retrieve(e,n){return this._client.get(R`/videos/${e}`,{...n,__security:{bearerAuth:!0}})}list(e={},n){return this._client.getAPIList("/videos",mn,{query:e,...n,__security:{bearerAuth:!0}})}delete(e,n){return this._client.delete(R`/videos/${e}`,{...n,__security:{bearerAuth:!0}})}createCharacter(e,n){return this._client.post("/videos/characters",ms({body:e,...n,__security:{bearerAuth:!0}},this._client))}downloadContent(e,n={},r){return this._client.get(R`/videos/${e}/content`,{query:n,...r,headers:ie([{Accept:"application/binary"},r==null?void 0:r.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}edit(e,n){return this._client.post("/videos/edits",ms({body:e,...n,__security:{bearerAuth:!0}},this._client))}extend(e,n){return this._client.post("/videos/extensions",ms({body:e,...n,__security:{bearerAuth:!0}},this._client))}getCharacter(e,n){return this._client.get(R`/videos/characters/${e}`,{...n,__security:{bearerAuth:!0}})}remix(e,n,r){return this._client.post(R`/videos/${e}/remix`,Yf({body:n,...r,__security:{bearerAuth:!0}},this._client))}}var Qa,S1,uh;let A1=class extends G{constructor(){super(...arguments),Qa.add(this)}async unwrap(e,n,r=this._client.webhookSecret,s=300){return await this.verifySignature(e,n,r,s),JSON.parse(e)}async verifySignature(e,n,r=this._client.webhookSecret,s=300){if(typeof crypto>"u"||typeof crypto.subtle.importKey!="function"||typeof crypto.subtle.verify!="function")throw new Error("Webhook signature verification is only supported when the `crypto` global is defined");N(this,Qa,"m",S1).call(this,r);const i=ie([n]).values,a=N(this,Qa,"m",uh).call(this,i,"webhook-signature"),o=N(this,Qa,"m",uh).call(this,i,"webhook-timestamp"),c=N(this,Qa,"m",uh).call(this,i,"webhook-id"),u=parseInt(o,10);if(isNaN(u))throw new Hc("Invalid webhook timestamp format");const l=Math.floor(Date.now()/1e3);if(l-u>s)throw new Hc("Webhook timestamp is too old");if(u>l+s)throw new Hc("Webhook timestamp is too new");const d=a.split(" ").map(g=>g.startsWith("v1,")?g.substring(3):g),f=r.startsWith("whsec_")?Buffer.from(r.replace("whsec_",""),"base64"):Buffer.from(r,"utf-8"),h=c?`${c}.${o}.${e}`:`${o}.${e}`,p=await crypto.subtle.importKey("raw",f,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(const g of d)try{const y=Buffer.from(g,"base64");if(await crypto.subtle.verify("HMAC",p,y,new TextEncoder().encode(h)))return}catch{continue}throw new Hc("The given webhook signature does not match the expected signature")}};Qa=new WeakSet,S1=function(e){if(typeof e!="string"||e.length===0)throw new Error("The webhook secret must either be set using the env var, OPENAI_WEBHOOK_SECRET, on the client class, OpenAI({ webhookSecret: '123' }), or passed to this function")},uh=function(e,n){if(!e)throw new Error("Headers are required");const r=e.get(n);if(r==null)throw new Error(`Missing required header: ${n}`);return r};var N_,Gw,lh,T1;const dW="workload-identity-auth";class Me{constructor({baseURL:e=zr("OPENAI_BASE_URL"),apiKey:n=zr("OPENAI_API_KEY")??null,adminAPIKey:r=zr("OPENAI_ADMIN_KEY")??null,organization:s=zr("OPENAI_ORG_ID")??null,project:i=zr("OPENAI_PROJECT_ID")??null,webhookSecret:a=zr("OPENAI_WEBHOOK_SECRET")??null,workloadIdentity:o,...c}={}){N_.add(this),lh.set(this,void 0),this.completions=new YO(this),this.chat=new $w(this),this.embeddings=new e1(this),this.files=new n1(this),this.images=new c1(this),this.audio=new $l(this),this.moderations=new l1(this),this.models=new u1(this),this.fineTuning=new ic(this),this.graders=new Kw(this),this.vectorStores=new ip(this),this.webhooks=new A1(this),this.beta=new sc(this),this.batches=new HO(this),this.uploads=new qw(this),this.admin=new Mw(this),this.responses=new rp(this),this.realtime=new np(this),this.conversations=new Uw(this),this.evals=new Bw(this),this.containers=new Dw(this),this.skills=new sp(this),this.videos=new v1(this);const u={apiKey:n,adminAPIKey:r,organization:s,project:i,webhookSecret:a,workloadIdentity:o,...c,baseURL:e||"https://api.openai.com/v1"};if(n&&o)throw new ye("The `apiKey` and `workloadIdentity` options are mutually exclusive");if(!n&&!r&&!o)throw new ye("Missing credentials. Please pass an `apiKey`, `workloadIdentity`, `adminAPIKey`, or set the `OPENAI_API_KEY` or `OPENAI_ADMIN_KEY` environment variable.");if(!u.dangerouslyAllowBrowser&&uK())throw new ye(`It looks like you're running in a browser-like environment.
|
|
339
|
-
|
|
340
|
-
This is disabled by default, as it risks exposing your secret API credentials to attackers.
|
|
341
|
-
If you understand the risks and have appropriate mitigations in place,
|
|
342
|
-
you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
|
|
343
|
-
|
|
344
|
-
new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
|
|
345
|
-
|
|
346
|
-
https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
|
|
347
|
-
`);this.baseURL=u.baseURL,this.timeout=u.timeout??Gw.DEFAULT_TIMEOUT,this.logger=u.logger??console;const l="warn";this.logLevel=l,this.logLevel=bS(u.logLevel,"ClientOptions.logLevel",this)??bS(zr("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??l,this.fetchOptions=u.fetchOptions,this.maxRetries=u.maxRetries??2,this.fetch=u.fetch??RC(),Oe(this,lh,pK);const d=zr("OPENAI_CUSTOM_HEADERS");if(d){const f={};for(const h of d.split(`
|
|
348
|
-
`)){const p=h.indexOf(":");p>=0&&(f[h.substring(0,p).trim()]=h.substring(p+1).trim())}u.defaultHeaders=ie([f,u.defaultHeaders])}this._options=u,o&&(this._workloadIdentityAuth=new PK(o,this.fetch)),this.apiKey=typeof n=="string"?n:null,this.adminAPIKey=r,this.organization=s,this.project=i,this.webhookSecret=a}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this._options.apiKey,adminAPIKey:this.adminAPIKey,workloadIdentity:this._options.workloadIdentity,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:n},r={bearerAuth:!0,adminAPIKeyAuth:!0}){if(!(e.get("authorization")||e.get("api-key"))&&!(n.has("authorization")||n.has("api-key"))&&!(this._workloadIdentityAuth&&r.bearerAuth))throw new Error('Could not resolve authentication method. Expected either apiKey or adminAPIKey to be set. Or for one of the "Authorization" or "api-key" headers to be explicitly omitted')}async authHeaders(e,n={bearerAuth:!0,adminAPIKeyAuth:!0}){return ie([n.bearerAuth?await this.bearerAuth(e):null,n.adminAPIKeyAuth?await this.adminAPIKeyAuth(e):null])}async bearerAuth(e){if(this._workloadIdentityAuth)return ie([{Authorization:`Bearer ${await this._workloadIdentityAuth.getToken()}`}]);if(this.apiKey!=null)return ie([{Authorization:`Bearer ${this.apiKey}`}])}async adminAPIKeyAuth(e){if(this.adminAPIKey!=null)return ie([{Authorization:`Bearer ${this.adminAPIKey}`}])}stringifyQuery(e){return vK(e)}getUserAgent(){return`${this.constructor.name}/JS ${Ya}`}defaultIdempotencyKey(){return`stainless-node-retry-${bC()}`}makeStatusError(e,n,r,s){return An.generate(e,n,r,s)}async _callApiKey(){const e=this._options.apiKey;if(typeof e!="function")return!1;let n;try{n=await e()}catch(r){throw r instanceof ye?r:new ye(`Failed to get token from 'apiKey' function: ${r.message}`,{cause:r})}if(typeof n!="string"||!n)throw new ye(`Expected 'apiKey' function argument to return a string but it returned ${n}`);return this.apiKey=n,!0}buildURL(e,n,r){const s=!N(this,N_,"m",T1).call(this)&&r||this.baseURL,i=iK(e)?new URL(e):new URL(s+(s.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),a=this.defaultQuery(),o=Object.fromEntries(i.searchParams);return(!uS(a)||!uS(o))&&(n={...o,...a,...n}),typeof n=="object"&&n&&!Array.isArray(n)&&(i.search=this.stringifyQuery(n)),i.toString()}async prepareOptions(e){(e.__security??{bearerAuth:!0}).bearerAuth&&await this._callApiKey()}async prepareRequest(e,{url:n,options:r}){}get(e,n){return this.methodRequest("get",e,n)}post(e,n){return this.methodRequest("post",e,n)}patch(e,n){return this.methodRequest("patch",e,n)}put(e,n){return this.methodRequest("put",e,n)}delete(e,n){return this.methodRequest("delete",e,n)}methodRequest(e,n,r){return this.request(Promise.resolve(r).then(s=>({method:e,path:n,...s})))}request(e,n=null){return new HC(this,this.makeRequest(e,n,void 0))}async makeRequest(e,n,r){var _,w,v,A;const s=await e,i=s.maxRetries??this.maxRetries;n==null&&(n=i),await this.prepareOptions(s);const{req:a,url:o,timeout:c}=await this.buildRequest(s,{retryCount:i-n});await this.prepareRequest(a,{url:o,options:s});const u="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),l=r===void 0?"":`, retryOf: ${r}`,d=Date.now();if(on(this).debug(`[${u}] sending request`,Wi({retryOfRequestLogID:r,method:s.method,url:o,options:s,headers:a.headers})),(_=s.signal)!=null&&_.aborted)throw new or;const f=s.__security??{bearerAuth:!0},h=new AbortController,p=await this.fetchWithAuth(o,a,c,h,f).catch(v_),g=Date.now();if(p instanceof globalThis.Error){const S=`retrying, ${n} attempts remaining`;if((w=s.signal)!=null&&w.aborted)throw new or;const x=b_(p)||/timed? ?out/i.test(String(p)+("cause"in p?String(p.cause):""));if(n)return on(this).info(`[${u}] connection ${x?"timed out":"failed"} - ${S}`),on(this).debug(`[${u}] connection ${x?"timed out":"failed"} (${S})`,Wi({retryOfRequestLogID:r,url:o,durationMs:g-d,message:p.message})),this.retryRequest(s,n,r??u);throw on(this).info(`[${u}] connection ${x?"timed out":"failed"} - error; no more retries left`),on(this).debug(`[${u}] connection ${x?"timed out":"failed"} (error; no more retries left)`,Wi({retryOfRequestLogID:r,url:o,durationMs:g-d,message:p.message})),p instanceof $C||p instanceof rK?p:x?new qf:new Zf({message:hW(p),cause:p})}const y=[...p.headers.entries()].filter(([S])=>S==="x-request-id").map(([S,x])=>", "+S+": "+JSON.stringify(x)).join(""),b=`[${u}${l}${y}] ${a.method} ${o} ${p.ok?"succeeded":"failed"} with status ${p.status} in ${g-d}ms`;if(!p.ok){if(p.status===401&&this._workloadIdentityAuth&&f.bearerAuth&&!((v=s.__metadata)!=null&&v.hasStreamingBody)&&!((A=s.__metadata)!=null&&A.workloadIdentityTokenRefreshed))return await fS(p.body),this._workloadIdentityAuth.invalidateToken(),this.makeRequest({...s,__metadata:{...s.__metadata,workloadIdentityTokenRefreshed:!0}},n,r??u);const S=await this.shouldRetry(p);if(n&&S){const D=`retrying, ${n} attempts remaining`;return await fS(p.body),on(this).info(`${b} - ${D}`),on(this).debug(`[${u}] response error (${D})`,Wi({retryOfRequestLogID:r,url:p.url,status:p.status,headers:p.headers,durationMs:g-d})),this.retryRequest(s,n,r??u,p.headers)}const x=S?"error; no more retries left":"error; not retryable";on(this).info(`${b} - ${x}`);const E=await p.text().catch(D=>v_(D).message),$=cK(E),k=$?void 0:E;throw on(this).debug(`[${u}] response error (${x})`,Wi({retryOfRequestLogID:r,url:p.url,status:p.status,headers:p.headers,message:k,durationMs:Date.now()-d})),this.makeStatusError(p.status,$,k,p.headers)}return on(this).info(b),on(this).debug(`[${u}] response start`,Wi({retryOfRequestLogID:r,url:p.url,status:p.status,headers:p.headers,durationMs:g-d})),{response:p,options:s,controller:h,requestLogID:u,retryOfRequestLogID:r,startTime:d}}getAPIList(e,n,r){return this.requestAPIList(n,r&&"then"in r?r.then(s=>({method:"get",path:e,...s})):{method:"get",path:e,...r})}requestAPIList(e,n){const r=this.makeRequest(n,null,void 0);return new OK(this,r,e)}async fetchWithAuth(e,n,r,s,i={bearerAuth:!0,adminAPIKeyAuth:!0}){if(this._workloadIdentityAuth&&i.bearerAuth){const o=n.headers,c=o.get("Authorization");if(!c||c===`Bearer ${dW}`){const u=await this._workloadIdentityAuth.getToken();o.set("Authorization",`Bearer ${u}`)}}return await this.fetchWithTimeout(e,n,r,s)}async fetchWithTimeout(e,n,r,s){const{signal:i,method:a,...o}=n||{},c=this._makeAbort(s);i&&i.addEventListener("abort",c,{once:!0});const u=setTimeout(c,r),l=globalThis.ReadableStream&&o.body instanceof globalThis.ReadableStream||typeof o.body=="object"&&o.body!==null&&Symbol.asyncIterator in o.body,d={signal:s.signal,...l?{duplex:"half"}:{},method:"GET",...o};a&&(d.method=a.toUpperCase());try{return await this.fetch.call(void 0,e,d)}finally{clearTimeout(u)}}async shouldRetry(e){const n=e.headers.get("x-should-retry");return n==="true"?!0:n==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,n,r,s){let i;const a=s==null?void 0:s.get("retry-after-ms");if(a){const c=parseFloat(a);Number.isNaN(c)||(i=c)}const o=s==null?void 0:s.get("retry-after");if(o&&!i){const c=parseFloat(o);Number.isNaN(c)?i=Date.parse(o)-Date.now():i=c*1e3}if(i===void 0){const c=e.maxRetries??this.maxRetries;i=this.calculateDefaultRetryTimeoutMillis(n,c)}return await Cl(i),this.makeRequest(e,n-1,r)}calculateDefaultRetryTimeoutMillis(e,n){const i=n-e,a=Math.min(.5*Math.pow(2,i),8),o=1-Math.random()*.25;return a*o*1e3}async buildRequest(e,{retryCount:n=0}={}){const r={...e},{method:s,path:i,query:a,defaultBaseURL:o}=r,c=this.buildURL(i,a,o);"timeout"in r&&oK("timeout",r.timeout),r.timeout=r.timeout??this.timeout;const{bodyHeaders:u,body:l,isStreamingBody:d}=this.buildBody({options:r});d&&(e.__metadata={...e.__metadata,hasStreamingBody:!0});const f=await this.buildHeaders({options:e,method:s,bodyHeaders:u,retryCount:n});return{req:{method:s,headers:f,...r.signal&&{signal:r.signal},...globalThis.ReadableStream&&l instanceof globalThis.ReadableStream&&{duplex:"half"},...l&&{body:l},...this.fetchOptions??{},...r.fetchOptions??{}},url:c,timeout:r.timeout}}async buildHeaders({options:e,method:n,bodyHeaders:r,retryCount:s}){let i={};this.idempotencyHeader&&n!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),i[this.idempotencyHeader]=e.idempotencyKey);const a=ie([i,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(s),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...fK(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders(e,e.__security??{bearerAuth:!0}),this._options.defaultHeaders,r,e.headers]);return this.validateHeaders(a,e.__security??{bearerAuth:!0}),a.values}_makeAbort(e){return()=>e.abort()}buildBody({options:{body:e,headers:n}}){if(!e)return{bodyHeaders:void 0,body:void 0,isStreamingBody:!1};const r=ie([n]),s=typeof globalThis.ReadableStream<"u"&&e instanceof globalThis.ReadableStream,i=!s&&(typeof e=="string"||e instanceof ArrayBuffer||ArrayBuffer.isView(e)||typeof globalThis.Blob<"u"&&e instanceof globalThis.Blob||e instanceof URLSearchParams||e instanceof FormData);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&r.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||s?{bodyHeaders:void 0,body:e,isStreamingBody:!i}:typeof e=="object"&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")?{bodyHeaders:void 0,body:NC(e),isStreamingBody:!0}:typeof e=="object"&&r.values.get("content-type")==="application/x-www-form-urlencoded"?{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(e),isStreamingBody:!1}:{...N(this,lh,"f").call(this,{body:e,headers:r}),isStreamingBody:!1}}}Gw=Me,lh=new WeakMap,N_=new WeakSet,T1=function(){return this.baseURL!=="https://api.openai.com/v1"};Me.OpenAI=Gw;Me.DEFAULT_TIMEOUT=6e5;Me.OpenAIError=ye;Me.APIError=An;Me.APIConnectionError=Zf;Me.APIConnectionTimeoutError=qf;Me.APIUserAbortError=or;Me.NotFoundError=TC;Me.ConflictError=EC;Me.RateLimitError=xC;Me.BadRequestError=vC;Me.AuthenticationError=SC;Me.InternalServerError=kC;Me.PermissionDeniedError=AC;Me.UnprocessableEntityError=IC;Me.InvalidWebhookSignatureError=Hc;Me.toFile=DK;Me.Completions=YO;Me.Chat=$w;Me.Embeddings=e1;Me.Files=n1;Me.Images=c1;Me.Audio=$l;Me.Moderations=l1;Me.Models=u1;Me.FineTuning=ic;Me.Graders=Kw;Me.VectorStores=ip;Me.Webhooks=A1;Me.Beta=sc;Me.Batches=HO;Me.Uploads=qw;Me.Admin=Mw;Me.Responses=rp;Me.Realtime=np;Me.Conversations=Uw;Me.Evals=Bw;Me.Containers=Dw;Me.Skills=sp;Me.Videos=v1;function hW(t){if(fW(t))return"Connection error. This may be caused by passing an undici dispatcher, such as ProxyAgent, that is incompatible with the fetch implementation. If you are using undici's ProxyAgent, pass the fetch implementation from the same undici package: import { fetch, ProxyAgent } from 'undici'; new OpenAI({ fetch, fetchOptions: { dispatcher: new ProxyAgent(...) } });"}function fW(t){let e=t;for(let n=0;n<8&&e&&typeof e=="object";n++){const r=e;if(r.code==="UND_ERR_INVALID_ARG"&&typeof r.message=="string"&&r.message.includes("invalid onRequestStart method"))return!0;e=r.cause}return!1}var pW={};class mW extends Me{constructor({baseURL:e=zr("OPENAI_BASE_URL"),apiKey:n=zr("AZURE_OPENAI_API_KEY"),apiVersion:r=zr("OPENAI_API_VERSION"),endpoint:s,deployment:i,azureADTokenProvider:a,dangerouslyAllowBrowser:o,...c}={}){if(!r)throw new ye("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&&!n)throw new ye("Missing credentials. Please pass one of `apiKey` and `azureADTokenProvider`, or set the `AZURE_OPENAI_API_KEY` environment variable.");if(a&&n)throw new ye("The `apiKey` and `azureADTokenProvider` arguments are mutually exclusive; only one can be passed at a time.");if(c.defaultQuery={...c.defaultQuery,"api-version":r},e){if(s)throw new ye("baseURL and endpoint are mutually exclusive")}else{if(s||(s=pW.AZURE_OPENAI_ENDPOINT),!s)throw new ye("Must provide one of the `baseURL` or `endpoint` arguments, or the `AZURE_OPENAI_ENDPOINT` environment variable");e=`${s}/openai`}super({apiKey:a??n,baseURL:e,...c,...o!==void 0?{dangerouslyAllowBrowser:o}:{}}),this.apiVersion="",this.apiVersion=r,this.deploymentName=i}async buildRequest(e,n={}){var r;if(gW.has(e.path)&&e.method==="post"&&e.body!==void 0){if(!th(e.body))throw new Error("Expected request body to be an object");const s=this.deploymentName||e.body.model||((r=e.__metadata)==null?void 0:r.model);s!==void 0&&!this.baseURL.includes("/deployments")&&(e.path=`/deployments/${s}${e.path}`)}return super.buildRequest(e,n)}async authHeaders(e,n){const r=n??{bearerAuth:!0,adminAPIKeyAuth:!0};return r.bearerAuth&&typeof this._options.apiKey=="string"?ie([{"api-key":this.apiKey}]):super.authHeaders(e,r)}}const gW=new Set(["/completions","/chat/completions","/embeddings","/audio/transcriptions","/audio/translations","/audio/speech","/images/generations","/batches","/images/edits"]);function _W(t){return!!(String(t).includes("context_length_exceeded")||"message"in t&&typeof t.message=="string"&&(t.message.includes("Input tokens exceed the configured limit")||t.message.includes("exceeds the context window")||t.message.includes("maximum context length")))}function Jw(t){if(!t||typeof t!="object")return t;let e;return t.constructor.name===qf.name&&"message"in t&&typeof t.message=="string"?(e=new Error(t.message),e.name="TimeoutError"):t.constructor.name===or.name&&"message"in t&&typeof t.message=="string"?(e=new Error(t.message),e.name="AbortError"):_W(t)?e=Z_.fromError(t):"status"in t&&t.status===400&&"message"in t&&typeof t.message=="string"&&t.message.includes("tool_calls")?e=pd(t,"INVALID_TOOL_RESULTS"):"status"in t&&t.status===401?e=pd(t,"MODEL_AUTHENTICATION"):"status"in t&&t.status===429?e=pd(t,"MODEL_RATE_LIMIT"):"status"in t&&t.status===404?e=pd(t,"MODEL_NOT_FOUND"):e=t,e}const Us=t=>t();function Rl(t){return t?!!(/^o\d/.test(t??"")||t.startsWith("gpt-5")&&!t.startsWith("gpt-5-chat")):!1}function yW(t){return t.role!=="system"&&t.role!=="developer"&&t.role!=="assistant"&&t.role!=="user"&&t.role!=="function"&&t.role!=="tool"&&console.warn(`Unknown message role: ${t.role}`),t.role}function jS(t){var e,n,r;return((e=t.metadata)==null?void 0:e.filename)??((n=t.metadata)==null?void 0:n.name)??((r=t.metadata)==null?void 0:r.title)}const wW="LC_AUTOGENERATED";function af(t){var n,r,s;const e=((n=t.metadata)==null?void 0:n.filename)??((r=t.metadata)==null?void 0:r.name)??((s=t.metadata)==null?void 0:s.title);return e||(console.warn("OpenAI may require a filename for file uploads. Specify a filename in the content block metadata, e.g.: { type: 'file', mimeType: '...', data: '...', metadata: { filename: 'my-file.pdf' } }. Using placeholder filename 'LC_AUTOGENERATED'."),wW)}function Pl(t){const e=t._getType();switch(e){case"system":return"system";case"ai":return"assistant";case"human":return"user";case"function":return"function";case"tool":return"tool";case"generic":if(!Ts.isInstance(t))throw new Error("Invalid generic chat message");return yW(t);default:throw new Error(`Unknown message type: ${e}`)}}function bW(t){return!!(t.includes("gpt-5.2-pro")||t.includes("gpt-5.4-pro")||t.includes("gpt-5.5-pro")||t.includes("codex"))}function E1(t){const{azureOpenAIApiDeploymentName:e,azureOpenAIApiInstanceName:n,azureOpenAIApiKey:r,azureOpenAIBasePath:s,baseURL:i,azureADTokenProvider:a,azureOpenAIEndpoint:o}=t;if((r||a)&&s&&e)return`${s}/${e}`;if((r||a)&&o&&e)return`${o}/openai/deployments/${e}`;if(r||a){if(!n)throw new Error("azureOpenAIApiInstanceName is required when using azureOpenAIApiKey");if(!e)throw new Error("azureOpenAIApiDeploymentName is a required parameter when using azureOpenAIApiKey");return`https://${n}.openai.azure.com/openai/deployments/${e}`}return i}function DS(t){return typeof Headers<"u"&&t!==null&&typeof t=="object"&&Object.prototype.toString.call(t)==="[object Headers]"}function vW(t){const e=Us(()=>{if(DS(t))return t;if(Array.isArray(t))return new Headers(t);if(typeof t=="object"&&t!==null&&"values"in t&&DS(t.values))return t.values;if(typeof t=="object"&&t!==null){const n=Object.entries(t).filter(([,r])=>typeof r=="string").map(([r,s])=>[r,s]);return new Headers(n)}return new Headers});return Object.fromEntries(e.entries())}function SW(){let t=iy();return(t==="node"||t==="deno")&&(t=`(${t}/${process.version}; ${process.platform}; ${process.arch})`),t}function I1(t,e=!1,n="1.0.0"){const r=vW(t),s=SW(),i=`langchainjs${e?"-azure":""}-openai`;return{...r,"User-Agent":r["User-Agent"]?`${i}/${n} (${s})${r["User-Agent"]}`:`${i}/${n} (${s})`}}function AW(t,e){let n;return Zs(t)?n=Vh(t):n=t,(e==null?void 0:e.strict)!==void 0&&(n.function.strict=e.strict),n}function TW(t){return t.anyOf!==void 0&&Array.isArray(t.anyOf)}function EW(t){const e=["namespace functions {",""];for(const n of t)n.description&&e.push(`// ${n.description}`),Object.keys(n.parameters.properties??{}).length>0?(e.push(`type ${n.name} = (_: {`),e.push(x1(n.parameters,0)),e.push("}) => any;")):e.push(`type ${n.name} = () => any;`),e.push("");return e.push("} // namespace functions"),e.join(`
|
|
349
|
-
`)}function x1(t,e){var r;const n=[];for(const[s,i]of Object.entries(t.properties??{}))i.description&&e<2&&n.push(`// ${i.description}`),(r=t.required)!=null&&r.includes(s)?n.push(`${s}: ${of(i,e)},`):n.push(`${s}?: ${of(i,e)},`);return n.map(s=>" ".repeat(e)+s).join(`
|
|
350
|
-
`)}function of(t,e){if(TW(t))return t.anyOf.map(n=>of(n,e)).join(" | ");switch(t.type){case"string":return t.enum?t.enum.map(n=>`"${n}"`).join(" | "):"string";case"number":return t.enum?t.enum.map(n=>`${n}`).join(" | "):"number";case"integer":return t.enum?t.enum.map(n=>`${n}`).join(" | "):"number";case"boolean":return"boolean";case"null":return"null";case"object":return["{",x1(t,e+2),"}"].join(`
|
|
351
|
-
`);case"array":return t.items?`${of(t.items,e)}[]`:"any[]";default:return""}}function k1(t){if(t)return t==="any"||t==="required"?"required":t==="auto"?"auto":t==="none"?"none":typeof t=="string"?{type:"function",function:{name:t}}:t}function Yw(t){return"type"in t&&t.type!=="function"}function IW(t){return typeof t=="object"&&t!==null&&"extras"in t&&typeof t.extras=="object"&&t.extras!==null&&"providerToolDefinition"in t.extras&&typeof t.extras.providerToolDefinition=="object"&&t.extras.providerToolDefinition!==null}function xW(t){return t!=null&&typeof t=="object"&&"type"in t&&t.type!=="function"}function cf(t){return typeof t=="object"&&t!==null&&"metadata"in t&&typeof t.metadata=="object"&&t.metadata!==null&&"customTool"in t.metadata&&typeof t.metadata.customTool=="object"&&t.metadata.customTool!==null}function C1(t){return"type"in t&&t.type==="custom"&&"custom"in t&&typeof t.custom=="object"&&t.custom!==null}function kW(t){if(t.type==="custom_tool_call")return{...t,type:"tool_call",call_id:t.id,id:t.call_id,name:t.name,isCustomTool:!0,args:{input:t.input}}}function CW(t){if(t.type==="computer_call")return{...t,type:"tool_call",call_id:t.id,id:t.call_id,name:"computer_use",isComputerTool:!0,args:{action:t.action}}}function OW(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="tool_call"&&"isComputerTool"in t&&t.isComputerTool===!0}function $W(t,e){return typeof t!="object"||t===null||!("type"in t)||t.type!=="tool_call"?!1:!!("isCustomTool"in t&&t.isCustomTool===!0||e&&"id"in t&&typeof t.id=="string"&&t.id in e)}function RW(t){const e=()=>{if(t.custom.format){if(t.custom.format.type==="grammar")return{type:"grammar",definition:t.custom.format.grammar.definition,syntax:t.custom.format.grammar.syntax};if(t.custom.format.type==="text")return{type:"text"}}};return{type:"custom",name:t.custom.name,description:t.custom.description,format:e()}}function PW(t){const e=()=>{if(t.format){if(t.format.type==="grammar")return{type:"grammar",grammar:{definition:t.format.definition,syntax:t.format.syntax}};if(t.format.type==="text")return{type:"text"}}};return{type:"custom",custom:{name:t.name,description:t.description,format:e()}}}const NW=Symbol("Let zodToJsonSchema decide on which parser to use"),US={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"},MW=t=>typeof t=="string"?{...US,basePath:["#"],definitions:{},name:t}:{...US,basePath:["#"],definitions:{},...t},M_=t=>"_def"in t?t._def:t;function LW(t){if(!t)return!0;for(const e in t)return!1;return!0}const jW=t=>{const e=MW(t),n=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,currentPath:n,propertyPath:void 0,seenRefs:new Set,seen:new Map(Object.entries(e.definitions).map(([r,s])=>[M_(s),{def:M_(s),path:[...e.basePath,e.definitionPath,r],jsonSchema:void 0}]))}};function O1(t,e,n,r){r!=null&&r.errorMessages&&n&&(t.errorMessage={...t.errorMessage,[e]:n})}function st(t,e,n,r,s){t[e]=n,O1(t,e,r,s)}function DW(){return{}}function UW(t,e){var r,s;const n={type:"array"};return((s=(r=t.type)==null?void 0:r._def)==null?void 0:s.typeName)!==U.ZodAny&&(n.items=Qe(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&st(n,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&st(n,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(st(n,"minItems",t.exactLength.value,t.exactLength.message,e),st(n,"maxItems",t.exactLength.value,t.exactLength.message,e)),n}function FW(t,e){const n={type:"integer",format:"int64"};if(!t.checks)return n;for(const r of t.checks)switch(r.kind){case"min":e.target==="jsonSchema7"?r.inclusive?st(n,"minimum",r.value,r.message,e):st(n,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(n.exclusiveMinimum=!0),st(n,"minimum",r.value,r.message,e));break;case"max":e.target==="jsonSchema7"?r.inclusive?st(n,"maximum",r.value,r.message,e):st(n,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(n.exclusiveMaximum=!0),st(n,"maximum",r.value,r.message,e));break;case"multipleOf":st(n,"multipleOf",r.value,r.message,e);break}return n}function BW(){return{type:"boolean"}}function zW(t,e){return Qe(t.type._def,e)}const HW=(t,e)=>Qe(t.innerType._def,e);function $1(t,e,n){const r=n??e.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((s,i)=>$1(t,e,s))};switch(r){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return VW(t,e)}}const VW=(t,e)=>{const n={type:"integer",format:"unix-time"};if(e.target==="openApi3")return n;for(const r of t.checks)switch(r.kind){case"min":st(n,"minimum",r.value,r.message,e);break;case"max":st(n,"maximum",r.value,r.message,e);break}return n};function KW(t,e){return{...Qe(t.innerType._def,e),default:t.defaultValue()}}function WW(t,e,n){return e.effectStrategy==="input"?Qe(t.schema._def,e,n):{}}function ZW(t){return{type:"string",enum:[...t.values]}}const qW=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function GW(t,e){const n=[Qe(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),Qe(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(i=>!!i);let r=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0;const s=[];return n.forEach(i=>{if(qW(i))s.push(...i.allOf),i.unevaluatedProperties===void 0&&(r=void 0);else{let a=i;if("additionalProperties"in i&&i.additionalProperties===!1){const{additionalProperties:o,...c}=i;a=c}else r=void 0;s.push(a)}}),s.length?{allOf:s,...r}:void 0}function JW(t,e){const n=typeof t.value;return n!=="bigint"&&n!=="number"&&n!=="boolean"&&n!=="string"?{type:Array.isArray(t.value)?"array":"object"}:e.target==="openApi3"?{type:n==="bigint"?"integer":n,enum:[t.value]}:{type:n==="bigint"?"integer":n,const:t.value}}let Sm;const Ui={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:()=>(Sm===void 0&&(Sm=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Sm),base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/};function R1(t,e){const n={type:"string"};function r(s){return e.patternStrategy==="escape"?YW(s):s}if(t.checks)for(const s of t.checks)switch(s.kind){case"min":st(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,s.value):s.value,s.message,e);break;case"max":st(n,"maxLength",typeof n.maxLength=="number"?Math.min(n.maxLength,s.value):s.value,s.message,e);break;case"email":switch(e.emailStrategy){case"format:email":jr(n,"email",s.message,e);break;case"format:idn-email":jr(n,"idn-email",s.message,e);break;case"pattern:zod":Dr(n,Ui.email,s.message,e);break}break;case"url":jr(n,"uri",s.message,e);break;case"uuid":jr(n,"uuid",s.message,e);break;case"regex":Dr(n,s.regex,s.message,e);break;case"cuid":Dr(n,Ui.cuid,s.message,e);break;case"cuid2":Dr(n,Ui.cuid2,s.message,e);break;case"startsWith":Dr(n,RegExp(`^${r(s.value)}`),s.message,e);break;case"endsWith":Dr(n,RegExp(`${r(s.value)}$`),s.message,e);break;case"datetime":jr(n,"date-time",s.message,e);break;case"date":jr(n,"date",s.message,e);break;case"time":jr(n,"time",s.message,e);break;case"duration":jr(n,"duration",s.message,e);break;case"length":st(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,s.value):s.value,s.message,e),st(n,"maxLength",typeof n.maxLength=="number"?Math.min(n.maxLength,s.value):s.value,s.message,e);break;case"includes":{Dr(n,RegExp(r(s.value)),s.message,e);break}case"ip":{s.version!=="v6"&&jr(n,"ipv4",s.message,e),s.version!=="v4"&&jr(n,"ipv6",s.message,e);break}case"emoji":Dr(n,Ui.emoji,s.message,e);break;case"ulid":{Dr(n,Ui.ulid,s.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{jr(n,"binary",s.message,e);break}case"contentEncoding:base64":{st(n,"contentEncoding","base64",s.message,e);break}case"pattern:zod":{Dr(n,Ui.base64,s.message,e);break}}break}case"nanoid":Dr(n,Ui.nanoid,s.message,e)}return n}const YW=t=>Array.from(t).map(e=>/[a-zA-Z0-9]/.test(e)?e:`\\${e}`).join(""),jr=(t,e,n,r)=>{var s;t.format||(s=t.anyOf)!=null&&s.some(i=>i.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&r.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...n&&r.errorMessages&&{errorMessage:{format:n}}})):st(t,"format",e,n,r)},Dr=(t,e,n,r)=>{var s;t.pattern||(s=t.allOf)!=null&&s.some(i=>i.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&r.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:FS(e,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):st(t,"pattern",FS(e,r),n,r)},FS=(t,e)=>{var u;const n=typeof t=="function"?t():t;if(!e.applyRegexFlags||!n.flags)return n.source;const r={i:n.flags.includes("i"),m:n.flags.includes("m"),s:n.flags.includes("s")},s=r.i?n.source.toLowerCase():n.source;let i="",a=!1,o=!1,c=!1;for(let l=0;l<s.length;l++){if(a){i+=s[l],a=!1;continue}if(r.i){if(o){if(s[l].match(/[a-z]/)){c?(i+=s[l],i+=`${s[l-2]}-${s[l]}`.toUpperCase(),c=!1):s[l+1]==="-"&&((u=s[l+2])!=null&&u.match(/[a-z]/))?(i+=s[l],c=!0):i+=`${s[l]}${s[l].toUpperCase()}`;continue}}else if(s[l].match(/[a-z]/)){i+=`[${s[l]}${s[l].toUpperCase()}]`;continue}}if(r.m){if(s[l]==="^"){i+=`(^|(?<=[\r
|
|
352
|
-
]))`;continue}else if(s[l]==="$"){i+=`($|(?=[\r
|
|
353
|
-
]))`;continue}}if(r.s&&s[l]==="."){i+=o?`${s[l]}\r
|
|
354
|
-
`:`[${s[l]}\r
|
|
355
|
-
]`;continue}i+=s[l],s[l]==="\\"?a=!0:o&&s[l]==="]"?o=!1:!o&&s[l]==="["&&(o=!0)}try{const l=new RegExp(i)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),n.source}return i};function P1(t,e){var r,s,i,a;if(e.target==="openApi3"&&((r=t.keyType)==null?void 0:r._def.typeName)===U.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((o,c)=>({...o,[c]:Qe(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",c]})??{}}),{}),additionalProperties:!1};const n={type:"object",additionalProperties:Qe(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??{}};if(e.target==="openApi3")return n;if(((s=t.keyType)==null?void 0:s._def.typeName)===U.ZodString&&((i=t.keyType._def.checks)!=null&&i.length)){const o=Object.entries(R1(t.keyType._def,e)).reduce((c,[u,l])=>u==="type"?c:{...c,[u]:l},{});return{...n,propertyNames:o}}else if(((a=t.keyType)==null?void 0:a._def.typeName)===U.ZodEnum)return{...n,propertyNames:{enum:t.keyType._def.values}};return n}function XW(t,e){if(e.mapStrategy==="record")return P1(t,e);const n=Qe(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||{},r=Qe(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||{};return{type:"array",maxItems:125,items:{type:"array",items:[n,r],minItems:2,maxItems:2}}}function QW(t){const e=t.values,r=Object.keys(t.values).filter(i=>typeof e[e[i]]!="number").map(i=>e[i]),s=Array.from(new Set(r.map(i=>typeof i)));return{type:s.length===1?s[0]==="string"?"string":"number":["string","number"],enum:r}}function eZ(){return{not:{}}}function tZ(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}const uf={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function nZ(t,e){if(e.target==="openApi3")return BS(t,e);const n=t.options instanceof Map?Array.from(t.options.values()):t.options;if(n.every(r=>r._def.typeName in uf&&(!r._def.checks||!r._def.checks.length))){const r=n.reduce((s,i)=>{const a=uf[i._def.typeName];return a&&!s.includes(a)?[...s,a]:s},[]);return{type:r.length>1?r:r[0]}}else if(n.every(r=>r._def.typeName==="ZodLiteral"&&!r.description)){const r=n.reduce((s,i)=>{const a=typeof i._def.value;switch(a){case"string":case"number":case"boolean":return[...s,a];case"bigint":return[...s,"integer"];case"object":if(i._def.value===null)return[...s,"null"];case"symbol":case"undefined":case"function":default:return s}},[]);if(r.length===n.length){const s=r.filter((i,a,o)=>o.indexOf(i)===a);return{type:s.length>1?s:s[0],enum:n.reduce((i,a)=>i.includes(a._def.value)?i:[...i,a._def.value],[])}}}else if(n.every(r=>r._def.typeName==="ZodEnum"))return{type:"string",enum:n.reduce((r,s)=>[...r,...s._def.values.filter(i=>!r.includes(i))],[])};return BS(t,e)}const BS=(t,e)=>{const n=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((r,s)=>Qe(r._def,{...e,currentPath:[...e.currentPath,"anyOf",`${s}`]})).filter(r=>!!r&&(!e.strictUnions||typeof r=="object"&&Object.keys(r).length>0));return n.length?{anyOf:n}:void 0};function rZ(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"||e.nullableStrategy==="property"?{type:uf[t.innerType._def.typeName],nullable:!0}:{type:[uf[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){const r=Qe(t.innerType._def,{...e,currentPath:[...e.currentPath]});return r&&"$ref"in r?{allOf:[r],nullable:!0}:r&&{...r,nullable:!0}}const n=Qe(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}function sZ(t,e){const n={type:"number"};if(!t.checks)return n;for(const r of t.checks)switch(r.kind){case"int":n.type="integer",O1(n,"type",r.message,e);break;case"min":e.target==="jsonSchema7"?r.inclusive?st(n,"minimum",r.value,r.message,e):st(n,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(n.exclusiveMinimum=!0),st(n,"minimum",r.value,r.message,e));break;case"max":e.target==="jsonSchema7"?r.inclusive?st(n,"maximum",r.value,r.message,e):st(n,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(n.exclusiveMaximum=!0),st(n,"maximum",r.value,r.message,e));break;case"multipleOf":st(n,"multipleOf",r.value,r.message,e);break}return n}function iZ(t,e){return e.removeAdditionalStrategy==="strict"?t.catchall._def.typeName==="ZodNever"?t.unknownKeys!=="strict":Qe(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0:t.catchall._def.typeName==="ZodNever"?t.unknownKeys==="passthrough":Qe(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0}function aZ(t,e){const n={type:"object",...Object.entries(t.shape()).reduce((r,[s,i])=>{var c;if(i===void 0||i._def===void 0)return r;const a=[...e.currentPath,"properties",s],o=Qe(i._def,{...e,currentPath:a,propertyPath:a});if(o===void 0)return r;if(e.openaiStrictMode&&i.isOptional()&&!i.isNullable()&&typeof((c=i._def)==null?void 0:c.defaultValue)>"u")throw new Error(`Zod field at \`${a.join("/")}\` uses \`.optional()\` without \`.nullable()\` which is not supported by the API. See: https://platform.openai.com/docs/guides/structured-outputs?api-mode=responses#all-fields-must-be-required`);return{properties:{...r.properties,[s]:o},required:i.isOptional()&&!e.openaiStrictMode?r.required:[...r.required,s]}},{properties:{},required:[]}),additionalProperties:iZ(t,e)};return n.required.length||delete n.required,n}const oZ=(t,e)=>{if(e.propertyPath&&e.currentPath.slice(0,e.propertyPath.length).toString()===e.propertyPath.toString())return Qe(t.innerType._def,{...e,currentPath:e.currentPath});const n=Qe(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return n?{anyOf:[{not:{}},n]}:{}},cZ=(t,e)=>{if(e.pipeStrategy==="input")return Qe(t.in._def,e);if(e.pipeStrategy==="output")return Qe(t.out._def,e);const n=Qe(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),r=Qe(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",n?"1":"0"]});return{allOf:[n,r].filter(s=>s!==void 0)}};function uZ(t,e){return Qe(t.type._def,e)}function lZ(t,e){const r={type:"array",uniqueItems:!0,items:Qe(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&st(r,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&st(r,"maxItems",t.maxSize.value,t.maxSize.message,e),r}function dZ(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((n,r)=>Qe(n._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[]),additionalItems:Qe(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((n,r)=>Qe(n._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[])}}function hZ(){return{not:{}}}function fZ(){return{}}const pZ=(t,e)=>Qe(t.innerType._def,e);function Qe(t,e,n=!1){var a;const r=e.seen.get(t);if(e.override){const o=(a=e.override)==null?void 0:a.call(e,t,e,r,n);if(o!==NW)return o}if(r&&!n){const o=mZ(r,e);if(o!==void 0)return"$ref"in o&&e.seenRefs.add(o.$ref),o}const s={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,s);const i=_Z(t,t.typeName,e,n);return i&&yZ(t,e,i),s.jsonSchema=i,i}const mZ=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"extract-to-root":const n=t.path.slice(e.basePath.length+1).join("_");return n!==e.name&&e.nameStrategy==="duplicate-ref"&&(e.definitions[n]=t.def),{$ref:[...e.basePath,e.definitionPath,n].join("/")};case"relative":return{$ref:gZ(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((r,s)=>e.currentPath[s]===r)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),{}):e.$refStrategy==="seen"?{}:void 0}},gZ=(t,e)=>{let n=0;for(;n<t.length&&n<e.length&&t[n]===e[n];n++);return[(t.length-n).toString(),...e.slice(n)].join("/")},_Z=(t,e,n,r)=>{switch(e){case U.ZodString:return R1(t,n);case U.ZodNumber:return sZ(t,n);case U.ZodObject:return aZ(t,n);case U.ZodBigInt:return FW(t,n);case U.ZodBoolean:return BW();case U.ZodDate:return $1(t,n);case U.ZodUndefined:return hZ();case U.ZodNull:return tZ(n);case U.ZodArray:return UW(t,n);case U.ZodUnion:case U.ZodDiscriminatedUnion:return nZ(t,n);case U.ZodIntersection:return GW(t,n);case U.ZodTuple:return dZ(t,n);case U.ZodRecord:return P1(t,n);case U.ZodLiteral:return JW(t,n);case U.ZodEnum:return ZW(t);case U.ZodNativeEnum:return QW(t);case U.ZodNullable:return rZ(t,n);case U.ZodOptional:return oZ(t,n);case U.ZodMap:return XW(t,n);case U.ZodSet:return lZ(t,n);case U.ZodLazy:return Qe(t.getter()._def,n);case U.ZodPromise:return uZ(t,n);case U.ZodNaN:case U.ZodNever:return eZ();case U.ZodEffects:return WW(t,n,r);case U.ZodAny:return DW();case U.ZodUnknown:return fZ();case U.ZodDefault:return KW(t,n);case U.ZodBranded:return zW(t,n);case U.ZodReadonly:return pZ(t,n);case U.ZodCatch:return HW(t,n);case U.ZodPipeline:return cZ(t,n);case U.ZodFunction:case U.ZodVoid:case U.ZodSymbol:return;default:return(s=>{})()}},yZ=(t,e,n)=>(t.description&&(n.description=t.description,e.markdownDescription&&(n.markdownDescription=t.description)),n),wZ=(t,e)=>{const n=jW(e),r=typeof e=="string"?e:(e==null?void 0:e.nameStrategy)==="title"||e==null?void 0:e.name,s=Qe(t._def,r===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,r]},!1)??{},i=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;i!==void 0&&(s.title=i);const a=(()=>{if(LW(n.definitions))return;const c={},u=new Set;for(let l=0;l<500;l++){const d=Object.entries(n.definitions).filter(([f])=>!u.has(f));if(d.length===0)break;for(const[f,h]of d)c[f]=Qe(M_(h),{...n,currentPath:[...n.basePath,n.definitionPath,f]},!0)??{},u.add(f)}return c})(),o=r===void 0?a?{...s,[n.definitionPath]:a}:s:n.nameStrategy==="duplicate-ref"?{...s,...a||n.seenRefs.size?{[n.definitionPath]:{...a,...n.seenRefs.size?{[r]:s}:void 0}}:void 0}:{$ref:[...n.$refStrategy==="relative"?[]:n.basePath,n.definitionPath,r].join("/"),[n.definitionPath]:{...a,[r]:s}};return n.target==="jsonSchema7"?o.$schema="http://json-schema.org/draft-07/schema#":n.target==="jsonSchema2019-09"&&(o.$schema="https://json-schema.org/draft/2019-09/schema#"),o};function bZ(t){if(t.type!=="object")throw new Error(`Root schema must have type: 'object' but got type: ${t.type?`'${t.type}'`:"undefined"}`);const e=structuredClone(t);return Rs(e,[],e)}function L_(t){if(typeof t=="boolean")return!1;if(t.type==="null")return!0;for(const e of t.oneOf??[])if(L_(e))return!0;for(const e of t.anyOf??[])if(L_(e))return!0;return!1}function Rs(t,e,n){if(typeof t=="boolean")throw new TypeError(`Expected object schema but got boolean; path=${e.join("/")}`);if(!Zi(t))throw new TypeError(`Expected ${JSON.stringify(t)} to be an object; path=${e.join("/")}`);const r=t.$defs;if(Zi(r))for(const[f,h]of Object.entries(r))Rs(h,[...e,"$defs",f],n);const s=t.definitions;if(Zi(s))for(const[f,h]of Object.entries(s))Rs(h,[...e,"definitions",f],n);t.type==="object"&&!("additionalProperties"in t)&&(t.additionalProperties=!1);const a=t.required??[],o=t.properties;if(Zi(o)){for(const[f,h]of Object.entries(o))if(!L_(h)&&!a.includes(f))throw new Error(`Zod field at \`${[...e,"properties",f].join("/")}\` uses \`.optional()\` without \`.nullable()\` which is not supported by the API. See: https://platform.openai.com/docs/guides/structured-outputs?api-mode=responses#all-fields-must-be-required`);t.required=Object.keys(o),t.properties=Object.fromEntries(Object.entries(o).map(([f,h])=>[f,Rs(h,[...e,"properties",f],n)]))}const c=t.items;Zi(c)&&(t.items=Rs(c,[...e,"items"],n));const u=t.anyOf;Array.isArray(u)&&(t.anyOf=u.map((f,h)=>Rs(f,[...e,"anyOf",String(h)],n)));const l=t.allOf;if(Array.isArray(l))if(l.length===1){const f=Rs(l[0],[...e,"allOf","0"],n);Object.assign(t,f),delete t.allOf}else t.allOf=l.map((f,h)=>Rs(f,[...e,"allOf",String(h)],n));t.default===null&&delete t.default;const d=t.$ref;if(d&&SZ(t,1)){if(typeof d!="string")throw new TypeError(`Received non-string $ref - ${d}; path=${e.join("/")}`);const f=vZ(n,d);if(typeof f=="boolean")throw new Error(`Expected \`$ref: ${d}\` to resolve to an object schema but got boolean`);if(!Zi(f))throw new Error(`Expected \`$ref: ${d}\` to resolve to an object but got ${JSON.stringify(f)}`);return Object.assign(t,{...f,...t}),delete t.$ref,Rs(t,e,n)}return t}function vZ(t,e){if(!e.startsWith("#/"))throw new Error(`Unexpected $ref format ${JSON.stringify(e)}; Does not start with #/`);const n=e.slice(2).split("/");let r=t;for(const s of n){if(!Zi(r))throw new Error(`encountered non-object entry while resolving ${e} - ${JSON.stringify(r)}`);const i=r[s];if(i===void 0)throw new Error(`Key ${s} not found while resolving ${e}`);r=i}return r}function Zi(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function SZ(t,e){let n=0;for(const r in t)if(n++,n>e)return!0;return!1}function AZ(t,e){return wZ(t,{openaiStrictMode:!0,name:e.name,nameStrategy:"duplicate-ref",$refStrategy:"extract-to-root",nullableStrategy:"property"})}function TZ(t){return bZ(yg(t,{target:"draft-7"}))}function EZ(t){return"_zod"in t}function IZ(t,e,n){return BK({type:"json_schema",json_schema:{...n,name:e,strict:!0,schema:EZ(t)?TZ(t):AZ(t,{name:e})}},r=>t.parse(JSON.parse(r)))}const zS=["jsonSchema","functionCalling","jsonMode"];function xZ(t,e){if(typeof e<"u"&&!zS.includes(e))throw new Error(`Invalid method: ${e}. Supported methods are: ${zS.join(", ")}`);const n=!t.startsWith("gpt-3")&&!t.startsWith("gpt-4-")&&t!=="gpt-4";if(n&&!e)return"jsonSchema";if(!n&&e==="jsonSchema")throw new Error(`JSON Schema is not supported for model "${t}". Please use a different method, e.g. "functionCalling" or "jsonMode".`);return e??"functionCalling"}function kZ(t,e){const n={...t};return Object.defineProperties(n,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:e,enumerable:!1}}),n}function CZ(t,e,n){if(Lt(t))return IZ(t,e,n);if(bt(t))return kZ({type:"json_schema",json_schema:{...n,name:e,strict:!0,schema:mt(t,{cycles:"ref",reused:"ref",override(r){r.jsonSchema.title=e}})}},r=>Ef(t,JSON.parse(r)));throw new Error("Unsupported schema response format")}function OZ(t,e){if(e&&typeof e=="object"&&"images"in e&&Array.isArray(e.images)){const n=e.images.filter(r=>{var s;return typeof((s=r==null?void 0:r.image_url)==null?void 0:s.url)=="string"}).map(r=>({type:"image",url:r.image_url.url}));return[{type:"text",text:t},...n]}return t}const $Z={"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 Xw(t,e){return typeof t=="string"?{model:t,...e??{}}:t??e}var Qw=class extends Es{constructor(e){var r,s,i,a;super(e??{});m(this,"temperature");m(this,"topP");m(this,"frequencyPenalty");m(this,"presencePenalty");m(this,"n");m(this,"logitBias");m(this,"model","gpt-3.5-turbo");m(this,"modelKwargs");m(this,"stop");m(this,"stopSequences");m(this,"user");m(this,"timeout");m(this,"streaming",!1);m(this,"streamUsage",!0);m(this,"maxTokens");m(this,"logprobs");m(this,"topLogprobs");m(this,"apiKey");m(this,"organization");m(this,"__includeRawResponse");m(this,"client");m(this,"clientConfig");m(this,"supportsStrictToolCalling");m(this,"audio");m(this,"modalities");m(this,"reasoning");m(this,"zdrEnabled");m(this,"service_tier");m(this,"promptCacheKey");m(this,"promptCacheRetention");m(this,"verbosity");m(this,"defaultOptions");m(this,"lc_serializable",!0);const n=typeof((r=e==null?void 0:e.configuration)==null?void 0:r.apiKey)=="string"||typeof((s=e==null?void 0:e.configuration)==null?void 0:s.apiKey)=="function"?(i=e==null?void 0:e.configuration)==null?void 0:i.apiKey:void 0;this.apiKey=(e==null?void 0:e.apiKey)??n??Mt("OPENAI_API_KEY"),this.organization=((a=e==null?void 0:e.configuration)==null?void 0:a.organization)??Mt("OPENAI_ORGANIZATION"),this.model=(e==null?void 0:e.model)??(e==null?void 0:e.modelName)??this.model,this.modelKwargs=(e==null?void 0:e.modelKwargs)??{},this.timeout=e==null?void 0:e.timeout,this.temperature=(e==null?void 0:e.temperature)??this.temperature,this.topP=(e==null?void 0:e.topP)??this.topP,this.frequencyPenalty=(e==null?void 0:e.frequencyPenalty)??this.frequencyPenalty,this.presencePenalty=(e==null?void 0:e.presencePenalty)??this.presencePenalty,this.logprobs=e==null?void 0:e.logprobs,this.topLogprobs=e==null?void 0:e.topLogprobs,this.n=(e==null?void 0:e.n)??this.n,this.logitBias=e==null?void 0:e.logitBias,this.stop=(e==null?void 0:e.stopSequences)??(e==null?void 0:e.stop),this.stopSequences=this.stop,this.user=e==null?void 0:e.user,this.__includeRawResponse=e==null?void 0:e.__includeRawResponse,this.audio=e==null?void 0:e.audio,this.modalities=e==null?void 0:e.modalities,this.reasoning=e==null?void 0:e.reasoning,this.maxTokens=(e==null?void 0:e.maxCompletionTokens)??(e==null?void 0:e.maxTokens),this.promptCacheKey=(e==null?void 0:e.promptCacheKey)??this.promptCacheKey,this.promptCacheRetention=(e==null?void 0:e.promptCacheRetention)??this.promptCacheRetention,this.verbosity=(e==null?void 0:e.verbosity)??this.verbosity,this.disableStreaming=(e==null?void 0:e.disableStreaming)===!0,this.streaming=(e==null?void 0:e.streaming)===!0,this.disableStreaming&&(this.streaming=!1),(e==null?void 0:e.streaming)===!1&&(this.disableStreaming=!0),this.streamUsage=(e==null?void 0:e.streamUsage)??this.streamUsage,this.disableStreaming&&(this.streamUsage=!1),this.clientConfig={apiKey:this.apiKey,organization:this.organization,dangerouslyAllowBrowser:!0,...e==null?void 0:e.configuration},(e==null?void 0:e.supportsStrictToolCalling)!==void 0&&(this.supportsStrictToolCalling=e.supportsStrictToolCalling),(e==null?void 0:e.service_tier)!==void 0&&(this.service_tier=e.service_tier),this.zdrEnabled=(e==null?void 0:e.zdrEnabled)??!1,this._addVersion("@langchain/openai","1.4.7")}_llmType(){return"openai"}static lc_name(){return"ChatOpenAI"}get callKeys(){return[...super.callKeys,"options","function_call","functions","tools","tool_choice","promptIndex","response_format","seed","reasoning","reasoning_effort","service_tier"]}get lc_secrets(){return{apiKey:"OPENAI_API_KEY",organization:"OPENAI_ORGANIZATION"}}get lc_aliases(){return{apiKey:"openai_api_key",modelName:"model"}}get lc_serializable_keys(){return["configuration","logprobs","topLogprobs","prefixMessages","supportsStrictToolCalling","modalities","audio","temperature","maxTokens","topP","frequencyPenalty","presencePenalty","n","logitBias","user","streaming","streamUsage","model","modelName","modelKwargs","stop","stopSequences","timeout","apiKey","cache","maxConcurrency","maxRetries","verbose","callbacks","tags","metadata","disableStreaming","zdrEnabled","reasoning","promptCacheKey","promptCacheRetention","verbosity"]}getLsParams(e){const n=this.invocationParams(e);return{ls_provider:"openai",ls_model_name:this.model,ls_model_type:"chat",ls_temperature:n.temperature??void 0,ls_max_tokens:n.max_tokens??void 0,ls_stop:e.stop}}_identifyingParams(){return{model_name:this.model,...this.invocationParams(),...this.clientConfig}}identifyingParams(){return this._identifyingParams()}_getReasoningParams(e){if(!Rl(this.model))return;let n;return this.reasoning!==void 0&&(n={...n,...this.reasoning}),(e==null?void 0:e.reasoning)!==void 0&&(n={...n,...e.reasoning}),(e==null?void 0:e.reasoningEffort)!==void 0&&(n==null?void 0:n.effort)===void 0&&(n={...n,effort:e.reasoningEffort}),n}_getResponseFormat(e){return e&&e.type==="json_schema"&&e.json_schema.schema&&Wt(e.json_schema.schema)?CZ(e.json_schema.schema,e.json_schema.name,{description:e.json_schema.description}):e}_combineCallOptions(e){return{...this.defaultOptions,...e??{}}}_getClientOptions(e){if(!this.client){const n=E1({baseURL:this.clientConfig.baseURL}),r={...this.clientConfig,baseURL:n,timeout:this.timeout,maxRetries:0};r.baseURL||delete r.baseURL,r.defaultHeaders=I1(r.defaultHeaders),this.client=new Me(r)}return{...this.clientConfig,...e}}_convertChatOpenAIToolToCompletionsTool(e,n){return cf(e)?PW(e.metadata.customTool):Xo(e)?(n==null?void 0:n.strict)!==void 0?{...e,function:{...e.function,strict:n.strict}}:e:AW(e,n)}bindTools(e,n){let r;return(n==null?void 0:n.strict)!==void 0?r=n.strict:this.supportsStrictToolCalling!==void 0&&(r=this.supportsStrictToolCalling),this.withConfig({tools:e.map(s=>{var a;if(Yw(s)||cf(s))return s;if(IW(s))return s.extras.providerToolDefinition;const i=this._convertChatOpenAIToolToCompletionsTool(s,{strict:r});return Zs(s)&&((a=s.extras)==null?void 0:a.defer_loading)===!0?{...i,defer_loading:!0}:i}),...n})}async stream(e,n){return super.stream(e,this._combineCallOptions(n))}async invoke(e,n){return super.invoke(e,this._combineCallOptions(n))}_combineLLMOutput(...e){return e.reduce((n,r)=>(r&&r.tokenUsage&&(n.tokenUsage.completionTokens+=r.tokenUsage.completionTokens??0,n.tokenUsage.promptTokens+=r.tokenUsage.promptTokens??0,n.tokenUsage.totalTokens+=r.tokenUsage.totalTokens??0),n),{tokenUsage:{completionTokens:0,promptTokens:0,totalTokens:0}})}async getNumTokensFromMessages(e){let n=0,r=0,s=0;this.model==="gpt-3.5-turbo-0301"?(r=4,s=-1):(r=3,s=1);const i=await Promise.all(e.map(async a=>{var f,h,p,g,y,b;const[o,c]=await Promise.all([this.getNumTokens(a.content),this.getNumTokens(Pl(a))]),u=a.name!==void 0?s+await this.getNumTokens(a.name):0;let l=o+r+c+u;const d=a;if(d._getType()==="function"&&(l-=2),(f=d.additional_kwargs)!=null&&f.function_call&&(l+=3),(h=d==null?void 0:d.additional_kwargs.function_call)!=null&&h.name&&(l+=await this.getNumTokens((p=d.additional_kwargs.function_call)==null?void 0:p.name)),(g=d.additional_kwargs.function_call)!=null&&g.arguments)try{l+=await this.getNumTokens(JSON.stringify(JSON.parse((y=d.additional_kwargs.function_call)==null?void 0:y.arguments)))}catch(_){console.error("Error parsing function arguments",_,JSON.stringify(d.additional_kwargs.function_call)),l+=await this.getNumTokens((b=d.additional_kwargs.function_call)==null?void 0:b.arguments)}return n+=l,l}));return n+=3,{totalCount:n,countPerMessage:i}}async _getNumTokensFromGenerations(e){return(await Promise.all(e.map(async n=>{var r;return(r=n.message.additional_kwargs)!=null&&r.function_call?(await this.getNumTokensFromMessages([n.message])).countPerMessage[0]:await this.getNumTokens(n.message.content)}))).reduce((n,r)=>n+r,0)}async _getEstimatedTokenCountFromPrompt(e,n,r){let s=(await this.getNumTokensFromMessages(e)).totalCount;if(n&&r!=="auto"){const i=EW(n);s+=await this.getNumTokens(i),s+=9}return n&&e.find(i=>i._getType()==="system")&&(s-=4),r==="none"?s+=1:typeof r=="object"&&(s+=await this.getNumTokens(r.name)+4),s}async moderateContent(e,n){const r=this._getClientOptions(n==null?void 0:n.options),s={input:e,model:(n==null?void 0:n.model)??"omni-moderation-latest"};return this.caller.call(async()=>{try{return await this.client.moderations.create(s,r)}catch(i){throw Jw(i)}})}get profile(){return $Z[this.model]??{}}_getStructuredOutputMethod(e){const n={...e};if(!this.model.startsWith("gpt-3")&&!this.model.startsWith("gpt-4-")&&this.model!=="gpt-4"){if((n==null?void 0:n.method)===void 0)return"jsonSchema"}else n.method==="jsonSchema"&&console.warn(`[WARNING]: JSON Schema is not supported for model "${this.model}". Falling back to tool calling.`);return n.method}withStructuredOutput(e,n){let r,s;const{schema:i,name:a,includeRaw:o}={...n,schema:e};if((n==null?void 0:n.strict)!==void 0&&n.method==="jsonMode")throw new Error("Argument `strict` is only supported for `method` = 'function_calling'");const c=xZ(this.model,n==null?void 0:n.method);if(c==="jsonMode"){s=Ko(i);const u=mt(i);r=this.withConfig({outputVersion:"v0",response_format:{type:"json_object"},ls_structured_output_format:{kwargs:{method:"json_mode"},schema:{title:a??"extract",...u}}})}else if(c==="jsonSchema"){const u=mt(i),l={name:a??"extract",description:jo(u),schema:Wt(i)?i:u,strict:n==null?void 0:n.strict};if(r=this.withConfig({outputVersion:"v0",response_format:{type:"json_schema",json_schema:l},ls_structured_output_format:{kwargs:{method:"json_schema"},schema:{title:l.name,description:l.description,...u}}}),Wt(i)||Or(i)){const d=Ko(i);s=en.from(async f=>"parsed"in f.additional_kwargs?f.additional_kwargs.parsed:d.invoke(f.content))}else s=new Yy}else{let u=a??"extract";const l=mt(i);let d;Wt(i)||Or(i)?d={name:u,description:l.description,parameters:l}:typeof i.name=="string"&&typeof i.parameters=="object"&&i.parameters!=null?(d=i,u=i.name):(u=i.title??u,d={name:u,description:i.description??"",parameters:i}),r=this.withConfig({outputVersion:"v0",tools:[{type:"function",function:d}],tool_choice:{type:"function",function:{name:u}},ls_structured_output_format:{kwargs:{method:"function_calling"},schema:{title:u,...l}},...(n==null?void 0:n.strict)!==void 0?{strict:n.strict}:{}}),s=Tl(i,u)}return tc(r,s,o)}};const N1={providerName:"ChatOpenAI",fromStandardTextBlock(t){return{type:"text",text:t.text}},fromStandardImageBlock(t){var e,n;if(t.source_type==="url")return{type:"image_url",image_url:{url:t.url,...(e=t.metadata)!=null&&e.detail?{detail:t.metadata.detail}:{}}};if(t.source_type==="base64")return{type:"image_url",image_url:{url:`data:${t.mime_type??""};base64,${t.data}`,...(n=t.metadata)!=null&&n.detail?{detail:t.metadata.detail}:{}}};throw new Error(`Image content blocks with source_type ${t.source_type} are not supported for ChatOpenAI`)},fromStandardAudioBlock(t){if(t.source_type==="url"){const e=Gr({dataUrl:t.url});if(!e)throw new Error(`URL audio blocks with source_type ${t.source_type} must be formatted as a data URL for ChatOpenAI`);const n=e.mime_type||t.mime_type||"";let r;try{r=Ym(n)}catch{throw new Error(`Audio blocks with source_type ${t.source_type} must have mime type of audio/wav or audio/mp3`)}if(r.type!=="audio"||r.subtype!=="wav"&&r.subtype!=="mp3")throw new Error(`Audio blocks with source_type ${t.source_type} must have mime type of audio/wav or audio/mp3`);return{type:"input_audio",input_audio:{format:r.subtype,data:e.data}}}if(t.source_type==="base64"){let e;try{e=Ym(t.mime_type??"")}catch{throw new Error(`Audio blocks with source_type ${t.source_type} must have mime type of audio/wav or audio/mp3`)}if(e.type!=="audio"||e.subtype!=="wav"&&e.subtype!=="mp3")throw new Error(`Audio blocks with source_type ${t.source_type} must have mime type of audio/wav or audio/mp3`);return{type:"input_audio",input_audio:{format:e.subtype,data:t.data}}}throw new Error(`Audio content blocks with source_type ${t.source_type} are not supported for ChatOpenAI`)},fromStandardFileBlock(t){if(t.source_type==="url"){const e=Gr({dataUrl:t.url}),n=af(t);if(!e)throw new Error(`URL file blocks with source_type ${t.source_type} must be formatted as a data URL for ChatOpenAI`);return{type:"file",file:{file_data:t.url,filename:n}}}if(t.source_type==="base64"){const e=af(t);return{type:"file",file:{file_data:`data:${t.mime_type??""};base64,${t.data}`,filename:e}}}if(t.source_type==="id")return{type:"file",file:{file_id:t.id}};throw new Error(`File content blocks with source_type ${t.source_type} are not supported for ChatOpenAI`)}},RZ=({message:t,rawResponse:e,includeRawResponse:n})=>{var i,a;const r=t.tool_calls,s=t.reasoning_content;switch(t.role){case"assistant":{const o=[],c=[];for(const d of r??[])try{o.push(Lf(d,{returnId:!0}))}catch(f){c.push(fu(d,f.message))}const u={function_call:t.function_call,tool_calls:r};n!==void 0&&(u.__raw_response=e),s!==void 0&&(u.reasoning_content=s);const l={model_provider:"openai",model_name:e.model,...e.system_fingerprint?{usage:{...e.usage},system_fingerprint:e.system_fingerprint}:{}};return t.audio&&(u.audio=t.audio),new De({content:OZ(t.content||"",(a=(i=e.choices)==null?void 0:i[0])==null?void 0:a.message),tool_calls:o,invalid_tool_calls:c,additional_kwargs:u,response_metadata:l,id:e.id})}default:return new Ts(t.content||"",t.role??"unknown")}},PZ=({delta:t,rawResponse:e,includeRawResponse:n,defaultRole:r})=>{var c,u;const s=t.role??r,i=t.content??"";let a;t.function_call?a={function_call:t.function_call}:t.tool_calls?a={tool_calls:t.tool_calls}:a={},n&&(a.__raw_response=e),t.reasoning_content!==void 0&&(a.reasoning_content=t.reasoning_content),t.audio&&(a.audio={...t.audio,index:e.choices[0].index});const o={model_provider:"openai",usage:{...e.usage}};if(s==="user")return new fl({content:i,response_metadata:o});if(s==="assistant"){const l=[];if(Array.isArray(t.tool_calls))for(const d of t.tool_calls)l.push({name:(c=d.function)==null?void 0:c.name,args:(u=d.function)==null?void 0:u.arguments,id:d.id,index:d.index,type:"tool_call_chunk"});return new Ge({content:i,tool_call_chunks:l,additional_kwargs:a,id:e.id,response_metadata:o})}else return s==="system"?new xi({content:i,response_metadata:o}):s==="developer"?new xi({content:i,response_metadata:o,additional_kwargs:{__openai_role__:"developer"}}):s==="function"?new hl({content:i,additional_kwargs:a,name:t.name,response_metadata:o}):s==="tool"?new ll({content:i,additional_kwargs:a,tool_call_id:t.tool_call_id,response_metadata:o}):new dl({content:i,role:s,response_metadata:o})},NZ=t=>{if(t.type==="image"){if(t.url)return{type:"image_url",image_url:{url:t.url}};if(t.data)return{type:"image_url",image_url:{url:`data:${t.mimeType};base64,${t.data}`}}}if(t.type==="audio"&&t.data){const e=jT(()=>{const[,n]=t.mimeType.split("/");return n==="wav"||n==="mp3"?n:"wav"});return{type:"input_audio",input_audio:{data:t.data.toString(),format:e}}}if(t.type==="file"){if(t.data){const e=af(t);return{type:"file",file:{file_data:`data:${t.mimeType};base64,${t.data}`,filename:e}}}if(t.fileId)return{type:"file",file:{file_id:t.fileId}}}},MZ=({message:t,model:e})=>{var s;let n=Pl(t);if(n==="system"&&Rl(e)&&(n="developer"),n==="developer")return{role:"developer",content:t.contentBlocks.filter(i=>i.type==="text")};if(n==="system")return{role:"system",content:t.contentBlocks.filter(i=>i.type==="text")};if(n==="assistant"){const i={role:"assistant",content:t.contentBlocks.filter(a=>a.type==="text")};return De.isInstance(t)&&((s=t.tool_calls)!=null&&s.length)?i.tool_calls=t.tool_calls.map(Qy):t.additional_kwargs.tool_calls!=null&&(i.tool_calls=t.additional_kwargs.tool_calls),i}else{if(n==="tool"&&fn.isInstance(t))return{role:"tool",tool_call_id:t.tool_call_id,content:t.contentBlocks.filter(i=>i.type==="text")};if(n==="function")return{role:"function",name:t.name??"",content:t.contentBlocks.filter(i=>i.type==="text").join("")}}function*r(i){for(const a of i){a.type==="text"&&(yield{type:"text",text:a.text});const o=NZ(a);o&&(yield o)}}return{role:"user",content:Array.from(r(t.contentBlocks))}},HS=({messages:t,model:e})=>t.flatMap(n=>{var a,o;if("output_version"in n.response_metadata&&((a=n.response_metadata)==null?void 0:a.output_version)==="v1")return MZ({message:n});let r=Pl(n);r==="system"&&Rl(e)&&(r="developer");const s=typeof n.content=="string"?n.content:n.content.flatMap(c=>kr(c)?ul(c,N1):typeof c=="object"&&c!==null&&"type"in c&&c.type==="tool_use"?[]:c),i={role:r,content:s};return n.name!=null&&(i.name=n.name),n.additional_kwargs.function_call!=null&&(i.function_call=n.additional_kwargs.function_call),De.isInstance(n)&&((o=n.tool_calls)!=null&&o.length)?i.tool_calls=n.tool_calls.map(Qy):(n.additional_kwargs.tool_calls!=null&&(i.tool_calls=n.additional_kwargs.tool_calls),fn.isInstance(n)&&n.tool_call_id!=null&&(i.tool_call_id=n.tool_call_id)),n.additional_kwargs.audio&&typeof n.additional_kwargs.audio=="object"&&"id"in n.additional_kwargs.audio?[i,{role:"assistant",audio:{id:n.additional_kwargs.audio.id}}]:i});var M1=class extends Qw{constructor(t,e){super(Xw(t,e))}invocationParams(t,e){var a;let n;(t==null?void 0:t.strict)!==void 0?n=t.strict:this.supportsStrictToolCalling!==void 0&&(n=this.supportsStrictToolCalling);let r={};(t==null?void 0:t.stream_options)!==void 0?r={stream_options:t.stream_options}:this.streamUsage&&(this.streaming||e!=null&&e.streaming)&&(r={stream_options:{include_usage:!0}});const s={model:this.model,temperature:this.temperature,top_p:this.topP,frequency_penalty:this.frequencyPenalty,presence_penalty:this.presencePenalty,logprobs:this.logprobs,top_logprobs:this.topLogprobs,n:this.n,logit_bias:this.logitBias,stop:(t==null?void 0:t.stop)??this.stopSequences,user:this.user,stream:this.streaming,functions:t==null?void 0:t.functions,function_call:t==null?void 0:t.function_call,tools:(a=t==null?void 0:t.tools)!=null&&a.length?t.tools.map(o=>this._convertChatOpenAIToolToCompletionsTool(o,{strict:n})):void 0,tool_choice:k1(t==null?void 0:t.tool_choice),response_format:this._getResponseFormat(t==null?void 0:t.response_format),seed:t==null?void 0:t.seed,...r,parallel_tool_calls:t==null?void 0:t.parallel_tool_calls,...this.audio||t!=null&&t.audio?{audio:this.audio||(t==null?void 0:t.audio)}:{},...this.modalities||t!=null&&t.modalities?{modalities:this.modalities||(t==null?void 0:t.modalities)}:{},...this.modelKwargs,prompt_cache_key:(t==null?void 0:t.promptCacheKey)??this.promptCacheKey,prompt_cache_retention:(t==null?void 0:t.promptCacheRetention)??this.promptCacheRetention,verbosity:(t==null?void 0:t.verbosity)??this.verbosity};(t==null?void 0:t.prediction)!==void 0&&(s.prediction=t.prediction),this.service_tier!==void 0&&(s.service_tier=this.service_tier),(t==null?void 0:t.service_tier)!==void 0&&(s.service_tier=t.service_tier);const i=this._getReasoningParams(t);return i!==void 0&&i.effort!==void 0&&(s.reasoning_effort=i.effort),Rl(s.model)?s.max_completion_tokens=this.maxTokens===-1?void 0:this.maxTokens:s.max_tokens=this.maxTokens===-1?void 0:this.maxTokens,s}async _generate(t,e,n){var a,o,c;(a=e.signal)==null||a.throwIfAborted();const r={},s=this.invocationParams(e),i=HS({messages:t,model:this.model});if(s.stream){const u=this._streamResponseChunks(t,e,n),l={};for await(const y of u){y.message.response_metadata={...y.generationInfo,...y.message.response_metadata};const b=((o=y.generationInfo)==null?void 0:o.completion)??0;l[b]===void 0?l[b]=y:l[b]=l[b].concat(y)}const d=Object.entries(l).sort(([y],[b])=>parseInt(y,10)-parseInt(b,10)).map(([y,b])=>b),{functions:f,function_call:h}=this.invocationParams(e),p=await this._getEstimatedTokenCountFromPrompt(t,f,h),g=await this._getNumTokensFromGenerations(d);return r.input_tokens=p,r.output_tokens=g,r.total_tokens=p+g,{generations:d,llmOutput:{estimatedTokenUsage:{promptTokens:r.input_tokens,completionTokens:r.output_tokens,totalTokens:r.total_tokens}}}}else{const u=await this.completionWithRetry({...s,stream:!1,messages:i},{signal:e==null?void 0:e.signal,...e==null?void 0:e.options}),{completion_tokens:l,prompt_tokens:d,total_tokens:f,prompt_tokens_details:h,completion_tokens_details:p}=(u==null?void 0:u.usage)??{};l&&(r.output_tokens=(r.output_tokens??0)+l),d&&(r.input_tokens=(r.input_tokens??0)+d),f&&(r.total_tokens=(r.total_tokens??0)+f),((h==null?void 0:h.audio_tokens)!==null||(h==null?void 0:h.cached_tokens)!==null)&&(r.input_token_details={...(h==null?void 0:h.audio_tokens)!==null&&{audio:h==null?void 0:h.audio_tokens},...(h==null?void 0:h.cached_tokens)!==null&&{cache_read:h==null?void 0:h.cached_tokens}}),((p==null?void 0:p.audio_tokens)!==null||(p==null?void 0:p.reasoning_tokens)!==null)&&(r.output_token_details={...(p==null?void 0:p.audio_tokens)!==null&&{audio:p==null?void 0:p.audio_tokens},...(p==null?void 0:p.reasoning_tokens)!==null&&{reasoning:p==null?void 0:p.reasoning_tokens}});const g=[];for(const y of(u==null?void 0:u.choices)??[]){const b={text:((c=y.message)==null?void 0:c.content)??"",message:this._convertCompletionsMessageToBaseMessage(y.message??{role:"assistant"},u)};b.generationInfo={...y.finish_reason?{finish_reason:y.finish_reason}:{},...y.logprobs?{logprobs:y.logprobs}:{}},Cr(b.message)&&(b.message.usage_metadata=r),b.message=new De(Object.fromEntries(Object.entries(b.message).filter(([_])=>!_.startsWith("lc_")))),g.push(b)}return{generations:g,llmOutput:{tokenUsage:{promptTokens:r.input_tokens,completionTokens:r.output_tokens,totalTokens:r.total_tokens}}}}}async*_streamResponseChunks(t,e,n){var c,u,l,d,f,h,p,g,y,b,_;const r=HS({messages:t,model:this.model}),s={...this.invocationParams(e,{streaming:!0}),messages:r,stream:!0};let i;const a=await this.completionWithRetry(s,e);let o;for await(const w of a){if((c=e.signal)!=null&&c.aborted)return;const v=(u=w==null?void 0:w.choices)==null?void 0:u[0];if(w.usage&&(o=w.usage),!v)continue;const{delta:A}=v;if(!A)continue;const S=this._convertCompletionsDeltaToBaseMessageChunk(A,w,i);i=A.role??i;const x={prompt:e.promptIndex??0,completion:v.index??0};if(typeof S.content!="string"){console.log("[WARNING]: Received non-string content from OpenAI. This is currently not supported.");continue}const E={...x};v.finish_reason!=null&&(E.finish_reason=v.finish_reason,E.system_fingerprint=w.system_fingerprint,E.model_name=w.model,E.service_tier=w.service_tier),this.logprobs&&(E.logprobs=v.logprobs);const $=new dr({message:S,text:S.content,generationInfo:E});yield $,await(n==null?void 0:n.handleLLMNewToken($.text??"",x,void 0,void 0,void 0,{chunk:$}))}if(o){const w={...((l=o.prompt_tokens_details)==null?void 0:l.audio_tokens)!==null&&{audio:(d=o.prompt_tokens_details)==null?void 0:d.audio_tokens},...((f=o.prompt_tokens_details)==null?void 0:f.cached_tokens)!==null&&{cache_read:(h=o.prompt_tokens_details)==null?void 0:h.cached_tokens}},v={...((p=o.completion_tokens_details)==null?void 0:p.audio_tokens)!==null&&{audio:(g=o.completion_tokens_details)==null?void 0:g.audio_tokens},...((y=o.completion_tokens_details)==null?void 0:y.reasoning_tokens)!==null&&{reasoning:(b=o.completion_tokens_details)==null?void 0:b.reasoning_tokens}},A=new dr({message:new Ge({content:"",response_metadata:{usage:{...o}},usage_metadata:{input_tokens:o.prompt_tokens,output_tokens:o.completion_tokens,total_tokens:o.total_tokens,...Object.keys(w).length>0&&{input_token_details:w},...Object.keys(v).length>0&&{output_token_details:v}}}),text:""});yield A,await(n==null?void 0:n.handleLLMNewToken(A.text??"",{prompt:0,completion:0},void 0,void 0,void 0,{chunk:A}))}if((_=e.signal)!=null&&_.aborted)throw new Error("AbortError")}async completionWithRetry(t,e){const n=this._getClientOptions(e),r=t.response_format&&t.response_format.type==="json_schema";return this.caller.call(async()=>{try{return r&&!t.stream?await this.client.chat.completions.parse(t,n):await this.client.chat.completions.create(t,n)}catch(s){throw Jw(s)}})}_convertCompletionsDeltaToBaseMessageChunk(t,e,n){return PZ({delta:t,rawResponse:e,includeRawResponse:this.__includeRawResponse,defaultRole:n})}_convertCompletionsMessageToBaseMessage(t,e){return RZ({message:t,rawResponse:e,includeRawResponse:this.__includeRawResponse})}};const eb={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"},tb={azureOpenAIApiKey:"AZURE_OPENAI_API_KEY"},nb=["azureOpenAIApiKey","azureOpenAIApiVersion","azureOpenAIBasePath","azureOpenAIEndpoint","azureOpenAIApiInstanceName","azureOpenAIApiDeploymentName","deploymentName","openAIApiKey","openAIApiVersion"];function rb(t,e){return typeof t=="string"?{model:t,deploymentName:t,azureOpenAIApiDeploymentName:t,...e??{}}:t??e}function sb(t){if(this.azureOpenAIApiKey=(t==null?void 0:t.azureOpenAIApiKey)??(typeof(t==null?void 0:t.openAIApiKey)=="string"?t==null?void 0:t.openAIApiKey:void 0)??(typeof(t==null?void 0:t.apiKey)=="string"?t==null?void 0:t.apiKey:void 0)??Mt("AZURE_OPENAI_API_KEY"),this.azureOpenAIApiInstanceName=(t==null?void 0:t.azureOpenAIApiInstanceName)??Mt("AZURE_OPENAI_API_INSTANCE_NAME"),this.azureOpenAIApiDeploymentName=(t==null?void 0:t.azureOpenAIApiDeploymentName)??(t==null?void 0:t.deploymentName)??Mt("AZURE_OPENAI_API_DEPLOYMENT_NAME"),this.azureOpenAIApiVersion=(t==null?void 0:t.azureOpenAIApiVersion)??(t==null?void 0:t.openAIApiVersion)??Mt("AZURE_OPENAI_API_VERSION"),this.azureOpenAIBasePath=(t==null?void 0:t.azureOpenAIBasePath)??Mt("AZURE_OPENAI_BASE_PATH"),this.azureOpenAIEndpoint=(t==null?void 0:t.azureOpenAIEndpoint)??Mt("AZURE_OPENAI_ENDPOINT"),this.azureADTokenProvider=t==null?void 0:t.azureADTokenProvider,!this.azureOpenAIApiKey&&!this.apiKey&&!this.azureADTokenProvider)throw new Error("Azure OpenAI API key or Token Provider not found")}function L1(t){if(!this.client){const n={azureOpenAIApiDeploymentName:this.azureOpenAIApiDeploymentName,azureOpenAIApiInstanceName:this.azureOpenAIApiInstanceName,azureOpenAIApiKey:this.azureOpenAIApiKey,azureOpenAIBasePath:this.azureOpenAIBasePath,azureADTokenProvider:this.azureADTokenProvider,baseURL:this.clientConfig.baseURL,azureOpenAIEndpoint:this.azureOpenAIEndpoint},r=E1(n),{apiKey:s,...i}=this.clientConfig,a={...i,baseURL:r,timeout:this.timeout,maxRetries:0};this.azureADTokenProvider||(a.apiKey=n.azureOpenAIApiKey),a.baseURL||delete a.baseURL,a.defaultHeaders=I1(a.defaultHeaders,!0,"2.0.0"),this.client=new mW({apiVersion:this.azureOpenAIApiVersion,azureADTokenProvider:this.azureADTokenProvider,deployment:this.azureOpenAIApiDeploymentName,...a})}const e={...this.clientConfig,...t};return this.azureOpenAIApiKey&&(e.headers={"api-key":this.azureOpenAIApiKey,...e.headers},e.query={"api-version":this.azureOpenAIApiVersion,...e.query}),e}function ib(t){const e=t;function n(r){return typeof r=="object"&&r!=null}if(n(e)&&n(e.kwargs)){if(delete e.kwargs.azure_openai_base_path,delete e.kwargs.azure_openai_api_deployment_name,delete e.kwargs.azure_openai_api_key,delete e.kwargs.azure_openai_api_version,delete e.kwargs.azure_open_ai_base_path,!e.kwargs.azure_endpoint&&this.azureOpenAIEndpoint&&(e.kwargs.azure_endpoint=this.azureOpenAIEndpoint),!e.kwargs.azure_endpoint&&this.azureOpenAIBasePath){const r=this.azureOpenAIBasePath.split("/openai/deployments/");if(r.length===2&&r[0].startsWith("http")){const[s]=r;e.kwargs.azure_endpoint=s}}if(!e.kwargs.azure_endpoint&&this.azureOpenAIApiInstanceName&&(e.kwargs.azure_endpoint=`https://${this.azureOpenAIApiInstanceName}.openai.azure.com/`),!e.kwargs.deployment_name&&this.azureOpenAIApiDeploymentName&&(e.kwargs.deployment_name=this.azureOpenAIApiDeploymentName),!e.kwargs.deployment_name&&this.azureOpenAIBasePath){const r=this.azureOpenAIBasePath.split("/openai/deployments/");if(r.length===2){const[,s]=r;e.kwargs.deployment_name=s}}e.kwargs.azure_endpoint&&e.kwargs.deployment_name&&e.kwargs.openai_api_base&&delete e.kwargs.openai_api_base,e.kwargs.azure_openai_api_instance_name&&e.kwargs.azure_endpoint&&delete e.kwargs.azure_openai_api_instance_name}return e}var LZ=class extends M1{constructor(e,n){const r=rb(e,n);super(r);m(this,"azureOpenAIApiVersion");m(this,"azureOpenAIApiKey");m(this,"azureADTokenProvider");m(this,"azureOpenAIApiInstanceName");m(this,"azureOpenAIApiDeploymentName");m(this,"azureOpenAIBasePath");m(this,"azureOpenAIEndpoint");sb.call(this,r)}_llmType(){return"azure_openai"}get lc_aliases(){return{...super.lc_aliases,...eb}}get lc_secrets(){return{...super.lc_secrets,...tb}}get lc_serializable_keys(){return[...super.lc_serializable_keys,...nb]}getLsParams(e){const n=super.getLsParams(e);return n.ls_provider="azure",n}_getClientOptions(e){return L1.call(this,e)}toJSON(){return ib.call(this,super.toJSON())}};const oo="__openai_function_call_ids__",co="__openai_custom_tool_call_ids__";function j1(t){return t.type==="url_citation"?{type:"citation",source:"url_citation",url:t.url,title:t.title,startIndex:t.start_index,endIndex:t.end_index}:t.type==="file_citation"?{type:"citation",source:"file_citation",title:t.filename,startIndex:t.index,file_id:t.file_id}:t.type==="container_file_citation"?{type:"citation",source:"container_file_citation",title:t.filename,startIndex:t.start_index,endIndex:t.end_index,file_id:t.file_id,container_id:t.container_id}:t.type==="file_path"?{type:"citation",source:"file_path",startIndex:t.index,file_id:t.file_id}:{type:"non_standard",value:t}}function jZ(t){if(t.type==="url_citation"||t.type==="file_citation"||t.type==="container_file_citation"||t.type==="file_path")return t;if(t.type==="citation"){const e=t;if(e.source==="url_citation")return{type:"url_citation",url:e.url??"",title:e.title??"",start_index:e.startIndex??0,end_index:e.endIndex??0};if(e.source==="file_citation")return{type:"file_citation",file_id:e.file_id??"",filename:e.title??"",index:e.startIndex??0};if(e.source==="container_file_citation")return{type:"container_file_citation",file_id:e.file_id??"",filename:e.title??"",container_id:e.container_id??"",start_index:e.startIndex??0,end_index:e.endIndex??0};if(e.source==="file_path")return{type:"file_path",file_id:e.file_id??"",index:e.startIndex??0}}return t.type==="non_standard"?t.value:t}const D1=t=>{var r,s,i,a;const e={...((r=t==null?void 0:t.input_tokens_details)==null?void 0:r.cached_tokens)!=null&&{cache_read:(s=t==null?void 0:t.input_tokens_details)==null?void 0:s.cached_tokens}},n={...((i=t==null?void 0:t.output_tokens_details)==null?void 0:i.reasoning_tokens)!=null&&{reasoning:(a=t==null?void 0:t.output_tokens_details)==null?void 0:a.reasoning_tokens}};return{input_tokens:(t==null?void 0:t.input_tokens)??0,output_tokens:(t==null?void 0:t.output_tokens)??0,total_tokens:(t==null?void 0:t.total_tokens)??0,input_token_details:e,output_token_details:n}},U1=t=>{var o;if(t.error){const c=new Error(t.error.message);throw c.name=t.error.code,c}const e=[],n=[],r=[],s=t.output.map(c=>{if(c.type==="function_call"&&"parsed_arguments"in c){const u={...c};return delete u.parsed_arguments,u}return c}),i={model_provider:"openai",model:t.model,created_at:t.created_at,id:t.id,incomplete_details:t.incomplete_details,metadata:t.metadata,object:t.object,output:s,status:t.status,user:t.user,service_tier:t.service_tier,model_name:t.model},a={};for(const c of t.output)if(c.type==="message")e.push(...c.content.flatMap(u=>u.type==="output_text"?("parsed"in u&&u.parsed!=null&&(a.parsed=u.parsed),{type:"text",text:u.text,annotations:u.annotations.map(j1),...c.phase!==null?{phase:c.phase}:{}}):u.type==="refusal"?(a.refusal=u.refusal,[]):u));else if(c.type==="function_call"){const u={function:{name:c.name,arguments:c.arguments},id:c.call_id};try{n.push(Lf(u,{returnId:!0}))}catch(l){let d;typeof l=="object"&&l!=null&&"message"in l&&typeof l.message=="string"&&(d=l.message),r.push(fu(u,d))}a[oo]??(a[oo]={}),c.id&&(a[oo][c.call_id]=c.id)}else if(c.type==="reasoning"){a.reasoning=c;const u=(o=c.summary)==null?void 0:o.map(l=>l.text).filter(Boolean).join("");u&&e.push({type:"reasoning",reasoning:u})}else if(c.type==="custom_tool_call"){const u=kW(c);u?(n.push(u),a[co]??(a[co]={}),c.id&&c.call_id&&(a[co][c.call_id]=c.id)):r.push(fu(c,"Malformed custom tool call"))}else if(c.type==="computer_call"){const u=CW(c);u?n.push(u):r.push(fu(c,"Malformed computer call"))}else c.type==="image_generation_call"?(c.result&&e.push({type:"image",mimeType:"image/png",data:c.result,id:c.id,metadata:{status:c.status}}),a.tool_outputs??(a.tool_outputs=[]),a.tool_outputs.push(c)):(a.tool_outputs??(a.tool_outputs=[]),a.tool_outputs.push(c));return new De({id:t.id,content:e,tool_calls:n,invalid_tool_calls:r,usage_metadata:D1(t.usage),additional_kwargs:a,response_metadata:i})},DZ=t=>{const e=(t.summary.length>1?t.summary.reduce((n,r)=>{const s=n[n.length-1];return s.index===r.index?s.text+=r.text:n.push(r),n},[{...t.summary[0]}]):t.summary).map(n=>Object.fromEntries(Object.entries(n).filter(([r])=>r!=="index")));return{...t,summary:e}},UZ=t=>{var c,u,l;const e=[];let n={},r;const s=[],i={model_provider:"openai"},a={};let o;if(t.type==="response.output_text.delta")e.push({type:"text",text:t.delta,index:t.content_index});else if(t.type==="response.output_text.annotation.added")e.push({type:"text",text:"",annotations:[j1(t.annotation)],index:t.content_index});else if(t.type==="response.output_item.added"&&t.item.type==="message"){const d="phase"in t.item?t.item.phase:void 0;d&&e.push({type:"text",text:"",phase:d,index:0})}else if(t.type==="response.output_item.added"&&t.item.type==="function_call")s.push({type:"tool_call_chunk",name:t.item.name,args:t.item.arguments,id:t.item.call_id,index:t.output_index}),a[oo]={[t.item.call_id]:t.item.id};else if(t.type==="response.output_item.added"&&t.item.type==="custom_tool_call")s.push({type:"tool_call_chunk",isCustomTool:!0,name:t.item.name,args:t.item.input,id:t.item.call_id,index:t.output_index}),a[co]={[t.item.call_id]:t.item.id};else if(t.type==="response.output_item.done"&&t.item.type==="computer_call")s.push({type:"tool_call_chunk",name:"computer_use",args:JSON.stringify({action:t.item.action}),id:t.item.call_id,index:t.output_index}),a.tool_outputs=[t.item];else if(t.type==="response.output_item.done"&&t.item.type==="image_generation_call")t.item.result&&e.push({type:"image",mimeType:"image/png",data:t.item.result,id:t.item.id,metadata:{status:t.item.status}}),a.tool_outputs=[t.item];else if(t.type==="response.output_item.done"&&["web_search_call","file_search_call","code_interpreter_call","shell_call","local_shell_call","mcp_call","mcp_list_tools","mcp_approval_request","custom_tool_call","tool_search_call","tool_search_output"].includes(t.item.type))a.tool_outputs=[t.item];else if(t.type==="response.created")o=t.response.id,i.id=t.response.id,i.model_name=t.response.model,i.model=t.response.model;else if(t.type==="response.completed"||t.type==="response.incomplete"){o=t.response.id;const d=U1(t.response);if(r=D1(t.response.usage),((u=(c=t.response.text)==null?void 0:c.format)==null?void 0:u.type)==="json_schema"&&d.text)try{a.parsed??(a.parsed=JSON.parse(d.text))}catch{}for(const[f,h]of Object.entries(t.response))f!=="id"&&(f==="output"?i[f]=d.response_metadata.output:i[f]=h)}else if(t.type==="response.function_call_arguments.delta"||t.type==="response.custom_tool_call_input.delta")s.push({type:"tool_call_chunk",args:t.delta,index:t.output_index,...t.type==="response.custom_tool_call_input.delta"?{isCustomTool:!0}:{}});else if(t.type==="response.web_search_call.completed"||t.type==="response.file_search_call.completed")n={tool_outputs:{id:t.item_id,type:t.type.replace("response.","").replace(".completed",""),status:"completed"}};else if(t.type==="response.refusal.done")a.refusal=t.refusal;else if(t.type==="response.output_item.added"&&"item"in t&&t.item.type==="reasoning"){const d=t.item.summary?t.item.summary.map((h,p)=>({...h,index:p})):void 0;a.reasoning={id:t.item.id,type:t.item.type,...d?{summary:d}:{}};const f=(l=t.item.summary)==null?void 0:l.map(h=>h.text).filter(Boolean).join("");f&&e.push({type:"reasoning",reasoning:f})}else if(t.type==="response.reasoning_summary_part.added")a.reasoning={type:"reasoning",summary:[{...t.part,index:t.summary_index}]},t.part.text&&e.push({type:"reasoning",reasoning:t.part.text,index:t.summary_index});else if(t.type==="response.reasoning_summary_text.delta")a.reasoning={type:"reasoning",summary:[{text:t.delta,type:"summary_text",index:t.summary_index}]},t.delta&&e.push({type:"reasoning",reasoning:t.delta,index:t.summary_index});else return t.type==="response.image_generation_call.partial_image",null;return new dr({text:e.map(d=>d.text).join(""),message:new Ge({id:o,content:e,tool_call_chunks:s,usage_metadata:r,additional_kwargs:a,response_metadata:i}),generationInfo:n})},FZ=t=>{var r;const e=De.isInstance(t)&&((r=t.response_metadata)==null?void 0:r.model_provider)==="openai";function*n(){const s=Us(()=>{try{const _=Pl(t);return _==="system"||_==="developer"||_==="assistant"||_==="user"?_:"assistant"}catch{return"assistant"}});let i;const a=new Set,o=new Set,c=new Map,u=new Map;function*l(){if(!i)return;const _=i.content;(typeof _=="string"&&_.length>0||Array.isArray(_)&&_.length>0)&&(yield i),i=void 0}const d=(_,w)=>{i||(i={type:"message",role:s,content:[],...w?{phase:w}:{}}),typeof i.content=="string"?i.content=i.content.length>0?[{type:"input_text",text:i.content},..._]:[..._]:i.content.push(..._)},f=_=>{if(typeof _=="string")return _;try{return JSON.stringify(_??{})}catch{return"{}"}},h=_=>{const w=Us(()=>{var A;const v=(A=_.metadata)==null?void 0:A.detail;return v==="low"||v==="high"||v==="auto"?v:"auto"});if(_.fileId)return{type:"input_image",detail:w,file_id:_.fileId};if(_.url)return{type:"input_image",detail:w,image_url:_.url};if(_.data){const v=typeof _.data=="string"?_.data:Buffer.from(_.data).toString("base64");return{type:"input_image",detail:w,image_url:`data:${_.mimeType??"image/png"};base64,${v}`}}},p=_=>{if(_.fileId){const w=jS(_);return{type:"input_file",file_id:_.fileId,...w?{filename:w}:{}}}if(_.url){const w=jS(_);return{...w?{filename:w}:{},type:"input_file",file_url:_.url}}if(_.data){const w=af(_),v=typeof _.data=="string"?_.data:Buffer.from(_.data).toString("base64");return{type:"input_file",file_data:`data:${_.mimeType??"application/octet-stream"};base64,${v}`,filename:w}}},g=_=>{const w=Us(()=>{var S;if(Array.isArray(_.summary)){const x=((S=_.summary)==null?void 0:S.map(E=>E==null?void 0:E.text).filter(E=>typeof E=="string"))??[];if(x.length>0)return x}return _.reasoning?[_.reasoning]:[]}),v=w.length>0?w.map(S=>({type:"summary_text",text:S})):[{type:"summary_text",text:""}],A={type:"reasoning",id:_.id??"",summary:v};return _.reasoning&&(A.content=[{type:"reasoning_text",text:_.reasoning}]),A},y=_=>({type:"function_call",name:_.name??"",call_id:_.id??"",arguments:f(_.args)}),b=_=>{const w=f(_.output),v=_.status==="success"?"completed":_.status==="error"?"incomplete":void 0;return{type:"function_call_output",call_id:_.toolCallId??"",output:w,...v?{status:v}:{}}};for(const _ of t.contentBlocks)if(_.type==="text"){const w=Us(()=>{if("extras"in _&&typeof _.extras=="object"&&_.extras!==null&&"phase"in _.extras)return _.extras.phase});d([{type:"input_text",text:_.text}],w)}else if(_.type!=="invalid_tool_call"){if(_.type==="reasoning")yield*l(),yield g(_);else if(_.type==="tool_call"){yield*l();const w=_.id??"";w&&(a.add(w),c.delete(w)),yield y(_)}else if(_.type==="tool_call_chunk"){if(_.id){const w=c.get(_.id)??{name:_.name,args:[]};_.name&&(w.name=_.name),_.args&&w.args.push(_.args),c.set(_.id,w)}}else if(_.type==="server_tool_call"){yield*l();const w=_.id??"";w&&(o.add(w),u.delete(w)),yield y(_)}else if(_.type==="server_tool_call_chunk"){if(_.id){const w=u.get(_.id)??{name:_.name,args:[]};_.name&&(w.name=_.name),_.args&&w.args.push(_.args),u.set(_.id,w)}}else if(_.type==="server_tool_call_result")yield*l(),yield b(_);else if(_.type!=="audio")if(_.type==="file"){const w=p(_);w&&d([w])}else if(_.type==="image"){const w=h(_);w&&d([w])}else if(_.type==="video"){const w=p(_);w&&d([w])}else _.type==="text-plain"?_.text&&d([{type:"input_text",text:_.text}]):_.type==="non_standard"&&e&&(yield*l(),yield _.value)}yield*l();for(const[_,w]of c){if(!_||a.has(_))continue;const v=w.args.join("");!w.name&&!v||(yield{type:"function_call",call_id:_,name:w.name??"",arguments:v})}for(const[_,w]of u){if(!_||o.has(_))continue;const v=w.args.join("");!w.name&&!v||(yield{type:"function_call",call_id:_,name:w.name??"",arguments:v})}}return Array.from(n())},VS=({messages:t,zdrEnabled:e,model:n})=>t.flatMap(r=>{var o,c,u,l;const s=r.response_metadata;if((s==null?void 0:s.output_version)==="v1")return FZ(r);const i=r.additional_kwargs;let a=Pl(r);if(a==="system"&&Rl(n)&&(a="developer"),a==="function")throw new Error("Function messages are not supported in Responses API");if(a==="tool"){const d=r;if((i==null?void 0:i.type)==="computer_call_output")return{type:"computer_call_output",output:(()=>{if(typeof d.content=="string")return{type:"input_image",image_url:d.content};if(Array.isArray(d.content)){const h=d.content.find(y=>y.type==="input_image");if(h)return h;const p=d.content.find(y=>y.type==="computer_screenshot");if(p)return p;const g=d.content.find(y=>y.type==="image_url");if(g)return{type:"input_image",image_url:typeof g.image_url=="string"?g.image_url:g.image_url.url}}throw new Error("Invalid computer call output")})(),call_id:d.tool_call_id};if((o=d.additional_kwargs)!=null&&o.customTool)return{type:"custom_tool_call_output",call_id:d.tool_call_id,output:d.content};const f=Array.isArray(d.content)&&d.content.every(h=>typeof h=="object"&&h!==null&&"type"in h&&(h.type==="input_file"||h.type==="input_image"||h.type==="input_text"));return{type:"function_call_output",call_id:d.tool_call_id,id:(c=d.id)!=null&&c.startsWith("fc_")?d.id:void 0,output:f?d.content:typeof d.content!="string"?JSON.stringify(d.content):d.content}}if(a==="assistant"){if(!e&&(s==null?void 0:s.output)!=null&&Array.isArray(s==null?void 0:s.output)&&(s==null?void 0:s.output.length)>0&&(s!=null&&s.output.every(w=>"type"in w)))return s==null?void 0:s.output;const d=[],f=i==null?void 0:i.reasoning,h=!!(f!=null&&f.encrypted_content);if(f&&(!e||h)){const w=DZ(f);d.push(w)}let{content:p}=r;if(i!=null&&i.refusal&&(typeof p=="string"&&(p=[{type:"output_text",text:p,annotations:[]}]),p=[...p,{type:"refusal",refusal:i.refusal}]),typeof p=="string"||p.length>0){const w={type:"message",role:"assistant",...r.id&&!e&&r.id.startsWith("msg_")?{id:r.id}:{},content:Us(()=>typeof p=="string"?p:p.flatMap(v=>{if(v.type==="text"){const A=v;return{type:"output_text",text:A.text,annotations:(A.annotations??[]).map(jZ)}}return v.type==="output_text"||v.type==="refusal"?v:[]})),phase:Us(()=>{var v;if(Array.isArray(p))return(v=p.find(A=>"phase"in A&&typeof A.phase=="string"))==null?void 0:v.phase})};d.push(w)}const g=i==null?void 0:i[oo],y=i==null?void 0:i[co];De.isInstance(r)&&((u=r.tool_calls)!=null&&u.length)?d.push(...r.tool_calls.map(w=>$W(w,y)?{type:"custom_tool_call",id:"call_id"in w&&typeof w.call_id=="string"?w.call_id:(y==null?void 0:y[w.id??""])??"",call_id:w.id??"",input:w.args.input,name:w.name}:OW(w)?{type:"computer_call",id:w.call_id,call_id:w.id??"",action:w.args.action}:{type:"function_call",name:w.name,arguments:JSON.stringify(w.args),call_id:w.id,...e?{}:{id:g==null?void 0:g[w.id]}})):i!=null&&i.tool_calls&&d.push(...i.tool_calls.map(w=>({type:"function_call",name:w.function.name,call_id:w.id,arguments:w.function.arguments,...e?{}:{id:g==null?void 0:g[w.id]}})));const b=(l=s==null?void 0:s.output)!=null&&l.length?s==null?void 0:s.output:i.tool_outputs,_=["computer_call","mcp_call","code_interpreter_call","image_generation_call","shell_call","local_shell_call"];if(b!=null){const w=b==null?void 0:b.filter(v=>_.includes(v.type));w.length>0&&d.push(...w)}return d}if(a==="user"||a==="system"||a==="developer"){if(typeof r.content=="string")return{type:"message",role:a,content:r.content};const d=[],f=r.content.flatMap(h=>(h.type==="mcp_approval_response"&&d.push({type:"mcp_approval_response",approval_request_id:h.approval_request_id,approve:h.approve}),kr(h)?ul(h,N1):h.type==="text"?{type:"input_text",text:h.text}:h.type==="image_url"?{type:"input_image",image_url:Us(()=>{if(typeof h.image_url=="string")return h.image_url;if(typeof h.image_url=="object"&&h.image_url!==null&&"url"in h.image_url)return h.image_url.url}),detail:Us(()=>{if(typeof h.image_url=="string")return"auto";if(typeof h.image_url=="object"&&h.image_url!==null&&"detail"in h.image_url)return h.image_url.detail})}:h.type==="input_text"||h.type==="input_image"||h.type==="input_file"?h:[]));return f.length>0&&d.push({type:"message",role:a,content:f}),d}return console.warn(`Unsupported role found when converting to OpenAI Responses API: ${a}`),[]});var F1=class extends Qw{constructor(t,e){super(Xw(t,e))}invocationParams(t){var s;let e;(t==null?void 0:t.strict)!==void 0&&(e=t.strict),e===void 0&&this.supportsStrictToolCalling!==void 0&&(e=this.supportsStrictToolCalling);const n={model:this.model,temperature:this.temperature,top_p:this.topP,user:this.user,service_tier:this.service_tier,stream:this.streaming,previous_response_id:t==null?void 0:t.previous_response_id,truncation:t==null?void 0:t.truncation,include:t==null?void 0:t.include,tools:(s=t==null?void 0:t.tools)!=null&&s.length?this._reduceChatOpenAITools(t.tools,{stream:this.streaming,strict:e}):void 0,tool_choice:xW(t==null?void 0:t.tool_choice)?t==null?void 0:t.tool_choice:(()=>{const i=k1(t==null?void 0:t.tool_choice);if(typeof i=="object"&&"type"in i){if(i.type==="function")return{type:"function",name:i.function.name};if(i.type==="allowed_tools")return{type:"allowed_tools",mode:i.allowed_tools.mode,tools:i.allowed_tools.tools};if(i.type==="custom")return{type:"custom",name:i.custom.name}}})(),text:(()=>{if(t!=null&&t.text)return t.text;const i=this._getResponseFormat(t==null?void 0:t.response_format);return(i==null?void 0:i.type)==="json_schema"?i.json_schema.schema!=null?{format:{type:"json_schema",schema:i.json_schema.schema,description:i.json_schema.description,name:i.json_schema.name,strict:i.json_schema.strict},verbosity:t==null?void 0:t.verbosity}:void 0:{format:i,verbosity:t==null?void 0:t.verbosity}})(),parallel_tool_calls:t==null?void 0:t.parallel_tool_calls,max_output_tokens:this.maxTokens===-1?void 0:this.maxTokens,prompt_cache_key:(t==null?void 0:t.promptCacheKey)??this.promptCacheKey,prompt_cache_retention:(t==null?void 0:t.promptCacheRetention)??this.promptCacheRetention,...this.zdrEnabled?{store:!1}:{},...this.modelKwargs},r=this._getReasoningParams(t);return r!==void 0&&(n.reasoning=r),n}async _generate(t,e,n){var s,i;(s=e.signal)==null||s.throwIfAborted();const r=this.invocationParams(e);if(r.stream){const a=this._streamResponseChunks(t,e,n);let o;for await(const c of a)c.message.response_metadata={...c.generationInfo,...c.message.response_metadata},o=(o==null?void 0:o.concat(c))??c;return{generations:o?[o]:[],llmOutput:{estimatedTokenUsage:(i=o==null?void 0:o.message)==null?void 0:i.usage_metadata}}}else{const a=await this.completionWithRetry({input:VS({messages:t,zdrEnabled:this.zdrEnabled??!1,model:this.model}),...r,stream:!1},{signal:e==null?void 0:e.signal,...e==null?void 0:e.options});return{generations:[{text:a.output_text,message:U1(a)}],llmOutput:{id:a.id,estimatedTokenUsage:a.usage?{promptTokens:a.usage.input_tokens,completionTokens:a.usage.output_tokens,totalTokens:a.usage.total_tokens}:void 0}}}}async*_streamResponseChunks(t,e,n){var s;const r=await this.completionWithRetry({...this.invocationParams(e),input:VS({messages:t,zdrEnabled:this.zdrEnabled??!1,model:this.model}),stream:!0},e);for await(const i of r){if((s=e.signal)!=null&&s.aborted)return;const a=UZ(i);a!=null&&(yield a,await(n==null?void 0:n.handleLLMNewToken(a.text||"",{prompt:e.promptIndex??0,completion:0},void 0,void 0,void 0,{chunk:a})))}}async completionWithRetry(t,e){return this.caller.call(async()=>{var r,s;const n=this._getClientOptions(e);try{return((s=(r=t.text)==null?void 0:r.format)==null?void 0:s.type)==="json_schema"&&!t.stream?await this.client.responses.parse(t,n):await this.client.responses.create(t,n)}catch(i){throw Jw(i)}})}_reduceChatOpenAITools(t,e){const n=[];for(const r of t)if(Yw(r))r.type==="image_generation"&&(e!=null&&e.stream)&&(r.partial_images=1),n.push(r);else if(cf(r)){const s=r.metadata.customTool;n.push({type:"custom",name:s.name,description:s.description,format:s.format})}else if(Xo(r)){const s={};for(const[i,a]of Object.entries(r))i!=="type"&&i!=="function"&&(s[i]=a);n.push({type:"function",name:r.function.name,parameters:r.function.parameters,description:r.function.description,strict:(e==null?void 0:e.strict)??null,...s})}else C1(r)&&n.push(RW(r));return n}},BZ=class extends F1{constructor(e,n){const r=rb(e,n);super(r);m(this,"azureOpenAIApiVersion");m(this,"azureOpenAIApiKey");m(this,"azureADTokenProvider");m(this,"azureOpenAIApiInstanceName");m(this,"azureOpenAIApiDeploymentName");m(this,"azureOpenAIBasePath");m(this,"azureOpenAIEndpoint");sb.call(this,r)}_llmType(){return"azure_openai"}get lc_aliases(){return{...super.lc_aliases,...eb}}get lc_secrets(){return{...super.lc_secrets,...tb}}get lc_serializable_keys(){return[...super.lc_serializable_keys,...nb]}getLsParams(e){const n=super.getLsParams(e);return n.ls_provider="azure",n}_getClientOptions(e){return L1.call(this,e)}toJSON(){return ib.call(this,super.toJSON())}},dh=class B1 extends Qw{constructor(n,r){const s=Xw(n,r);super(s);m(this,"useResponsesApi",!1);m(this,"responses");m(this,"completions");m(this,"fields");this.fields=s,this.useResponsesApi=(s==null?void 0:s.useResponsesApi)??!1,this.responses=(s==null?void 0:s.responses)??new F1(s),this.completions=(s==null?void 0:s.completions)??new M1(s)}get lc_serializable_keys(){return[...super.lc_serializable_keys,"useResponsesApi"]}get callKeys(){return[...super.callKeys,"useResponsesApi"]}_useResponsesApi(n){var a,o,c,u,l;const r=(a=n==null?void 0:n.tools)==null?void 0:a.some(Yw),s=(n==null?void 0:n.previous_response_id)!=null||(n==null?void 0:n.text)!=null||(n==null?void 0:n.truncation)!=null||(n==null?void 0:n.include)!=null||((o=n==null?void 0:n.reasoning)==null?void 0:o.summary)!=null||((c=this.reasoning)==null?void 0:c.summary)!=null,i=((u=n==null?void 0:n.tools)==null?void 0:u.some(C1))||((l=n==null?void 0:n.tools)==null?void 0:l.some(cf));return this.useResponsesApi||r||s||i||bW(this.model)}getLsParams(n){const r=this._combineCallOptions(n);return this._useResponsesApi(n)?this.responses.getLsParams(r):this.completions.getLsParams(r)}invocationParams(n){const r=this._combineCallOptions(n);return this._useResponsesApi(n)?this.responses.invocationParams(r):this.completions.invocationParams(r)}async _generate(n,r,s){return this._useResponsesApi(r)?this.responses._generate(n,r,s):this.completions._generate(n,r,s)}async*_streamResponseChunks(n,r,s){if(this._useResponsesApi(r)){yield*this.responses._streamResponseChunks(n,this._combineCallOptions(r),s);return}yield*this.completions._streamResponseChunks(n,this._combineCallOptions(r),s)}withConfig(n){const r=new B1(this.fields);return r.defaultOptions={...this.defaultOptions,...n},r}},zZ=class extends dh{constructor(e,n){const r=rb(e,n);super({...r,completions:new LZ(r),responses:new BZ(r)});m(this,"azureOpenAIApiVersion");m(this,"azureOpenAIApiKey");m(this,"azureADTokenProvider");m(this,"azureOpenAIApiInstanceName");m(this,"azureOpenAIApiDeploymentName");m(this,"azureOpenAIBasePath");m(this,"azureOpenAIEndpoint");sb.call(this,r)}_llmType(){return"azure_openai"}get lc_aliases(){return{...super.lc_aliases,...eb}}get lc_secrets(){return{...super.lc_secrets,...tb}}get lc_serializable_keys(){return[...super.lc_serializable_keys,...nb]}getLsParams(e){const n=super.getLsParams(e);return n.ls_provider="azure",n}_getStructuredOutputMethod(e){const n={...e};return this.model.startsWith("gpt-4o")&&(n==null?void 0:n.method)===void 0?"functionCalling":super._getStructuredOutputMethod(n)}toJSON(){return ib.call(this,super.toJSON())}};const HZ=$e({type:Ue("screenshot")}),VZ=$e({type:Ue("click"),x:ot(),y:ot(),button:Bf(["left","right","wheel","back","forward"]).default("left")}),KZ=$e({type:Ue("double_click"),x:ot(),y:ot(),button:Bf(["left","right","wheel","back","forward"]).default("left")}),WZ=$e({type:Ue("drag"),path:ba($e({x:ot(),y:ot()}))}),ZZ=$e({type:Ue("keypress"),keys:ba(Ke())}),qZ=$e({type:Ue("move"),x:ot(),y:ot()}),GZ=$e({type:Ue("scroll"),x:ot(),y:ot(),scroll_x:ot(),scroll_y:ot()}),JZ=$e({type:Ue("type"),text:Ke()}),YZ=$e({type:Ue("wait"),duration:ot().optional()}),XZ=kl([HZ,VZ,KZ,WZ,ZZ,qZ,GZ,JZ,YZ]);$e({action:XZ});const QZ=$e({type:Ue("exec"),command:ba(Ke()),env:V5(Ke(),Ke()).optional(),working_directory:Ke().optional(),timeout_ms:ot().optional(),user:Ke().optional()});kl([QZ]);$e({commands:ba(Ke()).describe("Array of shell commands to execute"),timeout_ms:ot().optional().describe("Optional timeout in milliseconds for the commands"),max_output_length:ot().optional().describe("Optional maximum number of characters to return from each command")});const eq=$e({type:Ue("create_file"),path:Ke(),diff:Ke()}),tq=$e({type:Ue("update_file"),path:Ke(),diff:Ke()}),nq=$e({type:Ue("delete_file"),path:Ke()});kl([eq,tq,nq]);function Ta(t){if(typeof t=="object"&&t!==null){const e={...t};"additionalProperties"in e&&delete e.additionalProperties,"$schema"in e&&delete e.$schema,"strict"in e&&delete e.strict;for(const n in e)n in e&&(Array.isArray(e[n])?e[n]=e[n].map(Ta):typeof e[n]=="object"&&e[n]!==null&&(e[n]=Ta(e[n])));return e}return t}function j_(t){const{$schema:e,...n}=Ta(Wt(t)||Or(t)?mt(t):t);return n}function rq(t){const{$schema:e,...n}=Ta(t);return n}function uo(t,e,n=[]){if(t==null||typeof t!="object")return;const r=t;if(Array.isArray(r.enum)&&r.enum.some(s=>s==="")){const s=n.length?` at path "${n.join(".")}"`:"",i=e?` in tool "${e}"`:"";throw new Error(`Invalid enum: empty string not allowed${i}${s}. Gemini API rejects empty strings in enums.`)}if(r.type==="object"&&r.properties&&typeof r.properties=="object")for(const[s,i]of Object.entries(r.properties))uo(i,e,[...n,s]);r.items&&uo(r.items,e,[...n,"[]"]);for(const s of["anyOf","oneOf","allOf"]){const i=r[s];Array.isArray(i)&&i.forEach((a,o)=>uo(a,e,[...n,`${s}[${o}]`]))}r.additionalProperties&&typeof r.additionalProperties=="object"&&uo(r.additionalProperties,e,[...n,"additionalProperties"])}const ab="__gemini_function_call_thought_signatures__",sq="ErYCCrMCAdHtim9kOoOkrPiCNVsmlpMIKd7ZMxgiFbVQOkgp7nlLcDMzVsZwIzvuT7nQROivoXA72ccC2lSDvR0Gh7dkWaGuj7ctv6t7ZceHnecx0QYa+ix8tYpRfjhyWozQ49lWiws6+YGjCt10KRTyWsZ2h6O7iHTYJwKIRwGUHRKy/qK/6kFxJm5ML00gLq4D8s5Z6DBpp2ZlR+uF4G8jJgeWQgyHWVdx2wGYElaceVAc66tZdPQRdOHpWtgYSI1YdaXgVI8KHY3/EfNc2YqqMIulvkDBAnuMhkAjV9xmBa54Tq+ih3Im4+r3DzqhGqYdsSkhS0kZMwte4Hjs65dZzCw9lANxIqYi1DJ639WNPYihp/DCJCos7o+/EeSPJaio5sgWDyUnMGkY1atsJZ+m7pj7DD5tvQ==",iq=t=>t();function aq(t){return Ts.isInstance(t)?t.role:t.type}function oq(t){switch(t){case"supervisor":case"ai":case"model":return"model";case"system":return"system";case"human":return"user";case"tool":case"function":return"function";default:throw new Error(`Unknown / unsupported author: ${t}`)}}function cq(t){if("mimeType"in t&&"data"in t)return{inlineData:{mimeType:t.mimeType,data:t.data}};if("mimeType"in t&&"fileUri"in t)return{fileData:{mimeType:t.mimeType,fileUri:t.fileUri}};throw new Error("Invalid media content")}function uq(t,e){var n;return(n=e.map(r=>Cr(r)?r.tool_calls??[]:[]).flat().find(r=>r.id===t.tool_call_id))==null?void 0:n.name}function mc(t,e){if("data"in t&&t.data!==void 0){const n=t.data instanceof Uint8Array?btoa(String.fromCharCode(...t.data)):t.data;return{inlineData:{mimeType:t.mimeType||e,data:n}}}if("url"in t&&t.url!==void 0){const n=Gr({dataUrl:t.url});return n?{inlineData:{mimeType:n.mime_type,data:n.data}}:{fileData:{mimeType:t.mimeType||e,fileUri:t.url}}}throw"fileId"in t&&t.fileId!==void 0?new Error("ContentBlock.Multimodal fileId is not supported by Google Generative AI. Use a URL or base64 data instead."):new Error(`Invalid multimodal content block: must have "data", "url", or "fileId" property. Received: ${JSON.stringify(t)}`)}function lq(t){return{providerName:"Google Gemini",fromStandardTextBlock(e){return{text:e.text}},fromStandardImageBlock(e){if(!t)throw new Error("This model does not support images");if(e.source_type==="url"){const n=Gr({dataUrl:e.url});return n?{inlineData:{mimeType:n.mime_type,data:n.data}}:{fileData:{mimeType:e.mime_type??"",fileUri:e.url}}}if(e.source_type==="base64")return{inlineData:{mimeType:e.mime_type??"",data:e.data}};throw new Error(`Unsupported source type: ${e.source_type}`)},fromStandardAudioBlock(e){if(!t)throw new Error("This model does not support audio");if(e.source_type==="url"){const n=Gr({dataUrl:e.url});return n?{inlineData:{mimeType:n.mime_type,data:n.data}}:{fileData:{mimeType:e.mime_type??"",fileUri:e.url}}}if(e.source_type==="base64")return{inlineData:{mimeType:e.mime_type??"",data:e.data}};throw new Error(`Unsupported source type: ${e.source_type}`)},fromStandardFileBlock(e){if(!t)throw new Error("This model does not support files");if(e.source_type==="text")return{text:e.text};if(e.source_type==="url"){const n=Gr({dataUrl:e.url});return n?{inlineData:{mimeType:n.mime_type,data:n.data}}:{fileData:{mimeType:e.mime_type??"",fileUri:e.url}}}if(e.source_type==="base64")return{inlineData:{mimeType:e.mime_type??"",data:e.data}};throw new Error(`Unsupported source type: ${e.source_type}`)}}}function KS(t,e){var n;if(kr(t))return ul(t,lq(e));if(t.type==="text")return{text:t.text};if(t.type==="executableCode")return{executableCode:t.executableCode};if(t.type==="codeExecutionResult")return{codeExecutionResult:t.codeExecutionResult};if(t.type==="image_url"){if(!e)throw new Error("This model does not support images");let r;if(typeof t.image_url=="string")r=t.image_url;else if(typeof t.image_url=="object"&&"url"in t.image_url)r=t.image_url.url;else throw new Error("Please provide image as base64 encoded data URL");const[s,i]=r.split(",");if(!s.startsWith("data:"))throw new Error("Please provide image as base64 encoded data URL");const[a,o]=s.replace(/^data:/,"").split(";");if(o!=="base64")throw new Error("Please provide image as base64 encoded data URL");return{inlineData:{data:i,mimeType:a}}}else{if(t.type==="media")return cq(t);if(t.type==="image")return mc(t,"image/png");if(t.type==="video")return mc(t,"video/mp4");if(t.type==="audio")return mc(t,"audio/mpeg");if(t.type==="file")return mc(t,"application/octet-stream");if(t.type==="text-plain")return"text"in t&&typeof t.text=="string"?{text:t.text}:mc(t,"text/plain");if(t.type==="tool_use")return{functionCall:{name:t.name,args:t.input}};if(t.type==="tool_call")return{functionCall:{name:t.name,args:t.args}};if((n=t.type)!=null&&n.includes("/")&&t.type.split("/").length===2&&"data"in t&&typeof t.data=="string")return{inlineData:{mimeType:t.type,data:t.data}};if(t.type==="thinking"){const r=t;return{text:r.thinking,thought:!0,...r.signature?{thoughtSignature:r.signature}:{}}}else{if("functionCall"in t)return;throw"type"in t?new Error(`Unknown content type ${t.type}`):new Error(`Unknown content ${JSON.stringify(t)}`)}}}function dq(t,e,n,r){var o,c;if(ca(t)){const u=t.name??uq(t,n);if(u===void 0)throw new Error(`Google requires a tool name for each tool call response, and we could not infer a called tool name for ToolMessage "${t.id}" from your passed messages. Please populate a "name" field on that ToolMessage explicitly.`);const l=Array.isArray(t.content)?t.content.map(d=>KS(d,e)).filter(d=>d!==void 0):t.content;return t.status==="error"?[{functionResponse:{name:u,response:{error:{details:l}}}}]:[{functionResponse:{name:u,response:{result:l}}}]}let s=[];const i=[];typeof t.content=="string"&&t.content&&i.push({text:t.content}),Array.isArray(t.content)&&i.push(...t.content.map(u=>KS(u,e)).filter(u=>u!==void 0));const a=(o=t.additional_kwargs)==null?void 0:o[ab];return Cr(t)&&((c=t.tool_calls)!=null&&c.length)&&(s=t.tool_calls.map(u=>{const l=iq(()=>{if(u.id){const d=a==null?void 0:a[u.id];if(d)return d}return r!=null&&r.includes("gemini-3")?sq:""});return{functionCall:{name:u.name,args:u.args},...l?{thoughtSignature:l}:{}}})),[...i,...s]}function WS(t,e,n=!1,r){return t.reduce((s,i,a)=>{if(!Et(i))throw new Error("Unsupported message input");const o=aq(i);if(o==="system"&&a!==0)throw new Error("System message should be the first one");const c=oq(o),u=s.content[s.content.length];if(!s.mergeWithPreviousContent&&u&&u.role===c)throw new Error("Google Generative AI requires alternate messages between authors");const l=dq(i,e,t.slice(0,a),r);if(s.mergeWithPreviousContent){const h=s.content[s.content.length-1];if(!h)throw new Error("There was a problem parsing your system message. Please try a prompt without one.");return h.parts.push(...l),{mergeWithPreviousContent:!1,content:s.content}}let d=c;(d==="function"||d==="system"&&!n)&&(d="user");const f={role:d,parts:l};return{mergeWithPreviousContent:o==="system"&&!n,content:[...s.content,f]}},{content:[],mergeWithPreviousContent:!1}).content}function hq(t,e){var l,d,f,h,p;if(!t.candidates||t.candidates.length===0||!t.candidates[0])return{generations:[],llmOutput:{filters:t.promptFeedback}};const[n]=t.candidates,{content:r,...s}=n,i=(l=r==null?void 0:r.parts)==null?void 0:l.reduce((g,y)=>("functionCall"in y&&y.functionCall&&g.push({...y,id:"id"in y.functionCall&&typeof y.functionCall.id=="string"?y.functionCall.id:pl()}),g),[]);let a;const o=r==null?void 0:r.parts;Array.isArray(o)&&o.length===1&&"text"in o[0]&&o[0].text&&!o[0].thought?a=o[0].text:Array.isArray(o)&&o.length>0?a=o.map(g=>g.thought&&"text"in g&&g.text?{type:"thinking",thinking:g.text,...g.thoughtSignature?{signature:g.thoughtSignature}:{}}:"text"in g?{type:"text",text:g.text}:"inlineData"in g?{type:"inlineData",inlineData:g.inlineData}:"functionCall"in g?{type:"functionCall",functionCall:g.functionCall}:"functionResponse"in g?{type:"functionResponse",functionResponse:g.functionResponse}:"fileData"in g?{type:"fileData",fileData:g.fileData}:"executableCode"in g?{type:"executableCode",executableCode:g.executableCode}:"codeExecutionResult"in g?{type:"codeExecutionResult",codeExecutionResult:g.codeExecutionResult}:g):a=[];const c=i==null?void 0:i.reduce((g,y)=>("thoughtSignature"in y&&typeof y.thoughtSignature=="string"&&(g[y.id]=y.thoughtSignature),g),{});let u="";return typeof a=="string"?u=a:Array.isArray(a)&&a.length>0&&(u=((d=a.find(g=>"text"in g))==null?void 0:d.text)??u),{generations:[{text:u,message:new De({content:a??"",tool_calls:i==null?void 0:i.map(g=>({type:"tool_call",id:g.id,name:g.functionCall.name,args:g.functionCall.args})),additional_kwargs:{...s,[ab]:c},usage_metadata:e==null?void 0:e.usageMetadata}),generationInfo:s}],llmOutput:{tokenUsage:{promptTokens:(f=e==null?void 0:e.usageMetadata)==null?void 0:f.input_tokens,completionTokens:(h=e==null?void 0:e.usageMetadata)==null?void 0:h.output_tokens,totalTokens:(p=e==null?void 0:e.usageMetadata)==null?void 0:p.total_tokens}}}}function fq(t,e){var d,f;if(!t.candidates||t.candidates.length===0)return null;const[n]=t.candidates,{content:r,...s}=n,i=(d=r.parts)==null?void 0:d.reduce((h,p)=>("functionCall"in p&&p.functionCall&&h.push({...p,id:"id"in p.functionCall&&typeof p.functionCall.id=="string"?p.functionCall.id:pl()}),h),[]);let a;const o=r==null?void 0:r.parts;Array.isArray(o)&&o.every(h=>"text"in h&&!h.thought)?a=o.map(h=>h.text).join(""):Array.isArray(o)?a=o.map(h=>h.thought&&"text"in h&&h.text?{type:"thinking",thinking:h.text,...h.thoughtSignature?{signature:h.thoughtSignature}:{}}:"text"in h?{type:"text",text:h.text}:"inlineData"in h?{type:"inlineData",inlineData:h.inlineData}:"functionCall"in h?{type:"functionCall",functionCall:h.functionCall}:"functionResponse"in h?{type:"functionResponse",functionResponse:h.functionResponse}:"fileData"in h?{type:"fileData",fileData:h.fileData}:"executableCode"in h?{type:"executableCode",executableCode:h.executableCode}:"codeExecutionResult"in h?{type:"codeExecutionResult",codeExecutionResult:h.codeExecutionResult}:h):a=[];let c="";a&&typeof a=="string"?c=a:Array.isArray(a)&&(c=((f=a.find(h=>"text"in h))==null?void 0:f.text)??"");const u=[];i&&u.push(...i.map(h=>({type:"tool_call_chunk",id:h.id,name:h.functionCall.name,args:JSON.stringify(h.functionCall.args)})));const l=i==null?void 0:i.reduce((h,p)=>("thoughtSignature"in p&&typeof p.thoughtSignature=="string"&&(h[p.id]=p.thoughtSignature),h),{});return new dr({text:c,message:new Ge({content:a||"",name:r?r.role:void 0,tool_call_chunks:u,additional_kwargs:{[ab]:l},response_metadata:{model_provider:"google-genai"},usage_metadata:e.usageMetadata}),generationInfo:s})}function pq(t){return t.every(e=>"functionDeclarations"in e&&Array.isArray(e.functionDeclarations))?t:[{functionDeclarations:t.map(e=>{if(Zs(e)){const n=j_(e.schema);return n.type==="object"&&"properties"in n&&Object.keys(n.properties).length===0?{name:e.name,description:e.description}:(uo(n,e.name),{name:e.name,description:e.description,parameters:n})}if(Xo(e)){const n=rq(e.function.parameters);return uo(n,e.function.name),{name:e.function.name,description:e.function.description??"A function available to call.",parameters:n}}return e})}]}function ZS(t,e){const n={input_tokens:(t==null?void 0:t.promptTokenCount)??0,output_tokens:(t==null?void 0:t.candidatesTokenCount)??0,total_tokens:(t==null?void 0:t.totalTokenCount)??0};if(t!=null&&t.cachedContentTokenCount&&(n.input_token_details??(n.input_token_details={}),n.input_token_details.cache_read=t.cachedContentTokenCount),e==="gemini-3-pro-preview"){const r=Math.max(0,(t==null?void 0:t.promptTokenCount)??-2e5),s=Math.max(0,(t==null?void 0:t.cachedContentTokenCount)??-2e5);r&&(n.input_token_details={...n.input_token_details,over_200k:r}),s&&(n.input_token_details={...n.input_token_details,cache_read_over_200k:s})}return n}var mq=class extends Qo{constructor(e){super(e);m(this,"lc_namespace",["langchain","google_genai","output_parsers"]);m(this,"returnId",!1);m(this,"keyName");m(this,"returnSingle",!1);m(this,"zodSchema");m(this,"serializableSchema");this.keyName=e.keyName,this.returnSingle=e.returnSingle??this.returnSingle,this.zodSchema=e.zodSchema,this.serializableSchema=e.serializableSchema}static lc_name(){return"GoogleGenerativeAIToolsOutputParser"}async _validateResult(e){if(this.serializableSchema!==void 0){const r=await this.serializableSchema["~standard"].validate(e);if(r.issues)throw new vn(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(r.issues)}`,JSON.stringify(e,null,2));return r.value}if(this.zodSchema===void 0)return e;const n=await xf(this.zodSchema,e);if(n.success)return n.data;throw new vn(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(n.error.issues)}`,JSON.stringify(e,null,2))}async parseResult(e){const n=e.flatMap(s=>{const{message:i}=s;return!("tool_calls"in i)||!Array.isArray(i.tool_calls)?[]:i.tool_calls});if(n[0]===void 0)throw new Error("No parseable tool calls provided to GoogleGenerativeAIToolsOutputParser.");const[r]=n;return await this._validateResult(r.args)}},qS;(function(t){t.STRING="string",t.NUMBER="number",t.INTEGER="integer",t.BOOLEAN="boolean",t.ARRAY="array",t.OBJECT="object"})(qS||(qS={}));/**
|
|
356
|
-
* @license
|
|
357
|
-
* Copyright 2024 Google LLC
|
|
358
|
-
*
|
|
359
|
-
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
360
|
-
* you may not use this file except in compliance with the License.
|
|
361
|
-
* You may obtain a copy of the License at
|
|
362
|
-
*
|
|
363
|
-
* http://www.apache.org/licenses/LICENSE-2.0
|
|
364
|
-
*
|
|
365
|
-
* Unless required by applicable law or agreed to in writing, software
|
|
366
|
-
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
367
|
-
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
368
|
-
* See the License for the specific language governing permissions and
|
|
369
|
-
* limitations under the License.
|
|
370
|
-
*/var GS;(function(t){t.LANGUAGE_UNSPECIFIED="language_unspecified",t.PYTHON="python"})(GS||(GS={}));var JS;(function(t){t.OUTCOME_UNSPECIFIED="outcome_unspecified",t.OUTCOME_OK="outcome_ok",t.OUTCOME_FAILED="outcome_failed",t.OUTCOME_DEADLINE_EXCEEDED="outcome_deadline_exceeded"})(JS||(JS={}));/**
|
|
371
|
-
* @license
|
|
372
|
-
* Copyright 2024 Google LLC
|
|
373
|
-
*
|
|
374
|
-
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
375
|
-
* you may not use this file except in compliance with the License.
|
|
376
|
-
* You may obtain a copy of the License at
|
|
377
|
-
*
|
|
378
|
-
* http://www.apache.org/licenses/LICENSE-2.0
|
|
379
|
-
*
|
|
380
|
-
* Unless required by applicable law or agreed to in writing, software
|
|
381
|
-
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
382
|
-
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
383
|
-
* See the License for the specific language governing permissions and
|
|
384
|
-
* limitations under the License.
|
|
385
|
-
*/const YS=["user","model","function","system"];var XS;(function(t){t.HARM_CATEGORY_UNSPECIFIED="HARM_CATEGORY_UNSPECIFIED",t.HARM_CATEGORY_HATE_SPEECH="HARM_CATEGORY_HATE_SPEECH",t.HARM_CATEGORY_SEXUALLY_EXPLICIT="HARM_CATEGORY_SEXUALLY_EXPLICIT",t.HARM_CATEGORY_HARASSMENT="HARM_CATEGORY_HARASSMENT",t.HARM_CATEGORY_DANGEROUS_CONTENT="HARM_CATEGORY_DANGEROUS_CONTENT",t.HARM_CATEGORY_CIVIC_INTEGRITY="HARM_CATEGORY_CIVIC_INTEGRITY"})(XS||(XS={}));var QS;(function(t){t.HARM_BLOCK_THRESHOLD_UNSPECIFIED="HARM_BLOCK_THRESHOLD_UNSPECIFIED",t.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",t.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",t.BLOCK_ONLY_HIGH="BLOCK_ONLY_HIGH",t.BLOCK_NONE="BLOCK_NONE"})(QS||(QS={}));var eA;(function(t){t.HARM_PROBABILITY_UNSPECIFIED="HARM_PROBABILITY_UNSPECIFIED",t.NEGLIGIBLE="NEGLIGIBLE",t.LOW="LOW",t.MEDIUM="MEDIUM",t.HIGH="HIGH"})(eA||(eA={}));var tA;(function(t){t.BLOCKED_REASON_UNSPECIFIED="BLOCKED_REASON_UNSPECIFIED",t.SAFETY="SAFETY",t.OTHER="OTHER"})(tA||(tA={}));var yu;(function(t){t.FINISH_REASON_UNSPECIFIED="FINISH_REASON_UNSPECIFIED",t.STOP="STOP",t.MAX_TOKENS="MAX_TOKENS",t.SAFETY="SAFETY",t.RECITATION="RECITATION",t.LANGUAGE="LANGUAGE",t.BLOCKLIST="BLOCKLIST",t.PROHIBITED_CONTENT="PROHIBITED_CONTENT",t.SPII="SPII",t.MALFORMED_FUNCTION_CALL="MALFORMED_FUNCTION_CALL",t.OTHER="OTHER"})(yu||(yu={}));var nA;(function(t){t.TASK_TYPE_UNSPECIFIED="TASK_TYPE_UNSPECIFIED",t.RETRIEVAL_QUERY="RETRIEVAL_QUERY",t.RETRIEVAL_DOCUMENT="RETRIEVAL_DOCUMENT",t.SEMANTIC_SIMILARITY="SEMANTIC_SIMILARITY",t.CLASSIFICATION="CLASSIFICATION",t.CLUSTERING="CLUSTERING"})(nA||(nA={}));var lo;(function(t){t.MODE_UNSPECIFIED="MODE_UNSPECIFIED",t.AUTO="AUTO",t.ANY="ANY",t.NONE="NONE"})(lo||(lo={}));var rA;(function(t){t.MODE_UNSPECIFIED="MODE_UNSPECIFIED",t.MODE_DYNAMIC="MODE_DYNAMIC"})(rA||(rA={}));/**
|
|
386
|
-
* @license
|
|
387
|
-
* Copyright 2024 Google LLC
|
|
388
|
-
*
|
|
389
|
-
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
390
|
-
* you may not use this file except in compliance with the License.
|
|
391
|
-
* You may obtain a copy of the License at
|
|
392
|
-
*
|
|
393
|
-
* http://www.apache.org/licenses/LICENSE-2.0
|
|
394
|
-
*
|
|
395
|
-
* Unless required by applicable law or agreed to in writing, software
|
|
396
|
-
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
397
|
-
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
398
|
-
* See the License for the specific language governing permissions and
|
|
399
|
-
* limitations under the License.
|
|
400
|
-
*/class yn extends Error{constructor(e){super(`[GoogleGenerativeAI Error]: ${e}`)}}class Fa extends yn{constructor(e,n){super(e),this.response=n}}class z1 extends yn{constructor(e,n,r,s){super(e),this.status=n,this.statusText=r,this.errorDetails=s}}class Ii extends yn{}class H1 extends yn{}/**
|
|
401
|
-
* @license
|
|
402
|
-
* Copyright 2024 Google LLC
|
|
403
|
-
*
|
|
404
|
-
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
405
|
-
* you may not use this file except in compliance with the License.
|
|
406
|
-
* You may obtain a copy of the License at
|
|
407
|
-
*
|
|
408
|
-
* http://www.apache.org/licenses/LICENSE-2.0
|
|
409
|
-
*
|
|
410
|
-
* Unless required by applicable law or agreed to in writing, software
|
|
411
|
-
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
412
|
-
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
413
|
-
* See the License for the specific language governing permissions and
|
|
414
|
-
* limitations under the License.
|
|
415
|
-
*/const gq="https://generativelanguage.googleapis.com",_q="v1beta",yq="0.24.1",wq="genai-js";var Ea;(function(t){t.GENERATE_CONTENT="generateContent",t.STREAM_GENERATE_CONTENT="streamGenerateContent",t.COUNT_TOKENS="countTokens",t.EMBED_CONTENT="embedContent",t.BATCH_EMBED_CONTENTS="batchEmbedContents"})(Ea||(Ea={}));class bq{constructor(e,n,r,s,i){this.model=e,this.task=n,this.apiKey=r,this.stream=s,this.requestOptions=i}toString(){var e,n;const r=((e=this.requestOptions)===null||e===void 0?void 0:e.apiVersion)||_q;let i=`${((n=this.requestOptions)===null||n===void 0?void 0:n.baseUrl)||gq}/${r}/${this.model}:${this.task}`;return this.stream&&(i+="?alt=sse"),i}}function vq(t){const e=[];return t!=null&&t.apiClient&&e.push(t.apiClient),e.push(`${wq}/${yq}`),e.join(" ")}async function Sq(t){var e;const n=new Headers;n.append("Content-Type","application/json"),n.append("x-goog-api-client",vq(t.requestOptions)),n.append("x-goog-api-key",t.apiKey);let r=(e=t.requestOptions)===null||e===void 0?void 0:e.customHeaders;if(r){if(!(r instanceof Headers))try{r=new Headers(r)}catch(s){throw new Ii(`unable to convert customHeaders value ${JSON.stringify(r)} to Headers: ${s.message}`)}for(const[s,i]of r.entries()){if(s==="x-goog-api-key")throw new Ii(`Cannot set reserved header name ${s}`);if(s==="x-goog-api-client")throw new Ii(`Header name ${s} can only be set using the apiClient field`);n.append(s,i)}}return n}async function Aq(t,e,n,r,s,i){const a=new bq(t,e,n,r,i);return{url:a.toString(),fetchOptions:Object.assign(Object.assign({},xq(i)),{method:"POST",headers:await Sq(a),body:s})}}async function Nl(t,e,n,r,s,i={},a=fetch){const{url:o,fetchOptions:c}=await Aq(t,e,n,r,s,i);return Tq(o,c,a)}async function Tq(t,e,n=fetch){let r;try{r=await n(t,e)}catch(s){Eq(s,t)}return r.ok||await Iq(r,t),r}function Eq(t,e){let n=t;throw n.name==="AbortError"?(n=new H1(`Request aborted when fetching ${e.toString()}: ${t.message}`),n.stack=t.stack):t instanceof z1||t instanceof Ii||(n=new yn(`Error fetching from ${e.toString()}: ${t.message}`),n.stack=t.stack),n}async function Iq(t,e){let n="",r;try{const s=await t.json();n=s.error.message,s.error.details&&(n+=` ${JSON.stringify(s.error.details)}`,r=s.error.details)}catch{}throw new z1(`Error fetching from ${e.toString()}: [${t.status} ${t.statusText}] ${n}`,t.status,t.statusText,r)}function xq(t){const e={};if((t==null?void 0:t.signal)!==void 0||(t==null?void 0:t.timeout)>=0){const n=new AbortController;(t==null?void 0:t.timeout)>=0&&setTimeout(()=>n.abort(),t.timeout),t!=null&&t.signal&&t.signal.addEventListener("abort",()=>{n.abort()}),e.signal=n.signal}return e}/**
|
|
416
|
-
* @license
|
|
417
|
-
* Copyright 2024 Google LLC
|
|
418
|
-
*
|
|
419
|
-
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
420
|
-
* you may not use this file except in compliance with the License.
|
|
421
|
-
* You may obtain a copy of the License at
|
|
422
|
-
*
|
|
423
|
-
* http://www.apache.org/licenses/LICENSE-2.0
|
|
424
|
-
*
|
|
425
|
-
* Unless required by applicable law or agreed to in writing, software
|
|
426
|
-
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
427
|
-
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
428
|
-
* See the License for the specific language governing permissions and
|
|
429
|
-
* limitations under the License.
|
|
430
|
-
*/function ob(t){return t.text=()=>{if(t.candidates&&t.candidates.length>0){if(t.candidates.length>1&&console.warn(`This response had ${t.candidates.length} candidates. Returning text from the first candidate only. Access response.candidates directly to use the other candidates.`),hh(t.candidates[0]))throw new Fa(`${ci(t)}`,t);return kq(t)}else if(t.promptFeedback)throw new Fa(`Text not available. ${ci(t)}`,t);return""},t.functionCall=()=>{if(t.candidates&&t.candidates.length>0){if(t.candidates.length>1&&console.warn(`This response had ${t.candidates.length} candidates. Returning function calls from the first candidate only. Access response.candidates directly to use the other candidates.`),hh(t.candidates[0]))throw new Fa(`${ci(t)}`,t);return console.warn("response.functionCall() is deprecated. Use response.functionCalls() instead."),sA(t)[0]}else if(t.promptFeedback)throw new Fa(`Function call not available. ${ci(t)}`,t)},t.functionCalls=()=>{if(t.candidates&&t.candidates.length>0){if(t.candidates.length>1&&console.warn(`This response had ${t.candidates.length} candidates. Returning function calls from the first candidate only. Access response.candidates directly to use the other candidates.`),hh(t.candidates[0]))throw new Fa(`${ci(t)}`,t);return sA(t)}else if(t.promptFeedback)throw new Fa(`Function call not available. ${ci(t)}`,t)},t}function kq(t){var e,n,r,s;const i=[];if(!((n=(e=t.candidates)===null||e===void 0?void 0:e[0].content)===null||n===void 0)&&n.parts)for(const a of(s=(r=t.candidates)===null||r===void 0?void 0:r[0].content)===null||s===void 0?void 0:s.parts)a.text&&i.push(a.text),a.executableCode&&i.push("\n```"+a.executableCode.language+`
|
|
431
|
-
`+a.executableCode.code+"\n```\n"),a.codeExecutionResult&&i.push("\n```\n"+a.codeExecutionResult.output+"\n```\n");return i.length>0?i.join(""):""}function sA(t){var e,n,r,s;const i=[];if(!((n=(e=t.candidates)===null||e===void 0?void 0:e[0].content)===null||n===void 0)&&n.parts)for(const a of(s=(r=t.candidates)===null||r===void 0?void 0:r[0].content)===null||s===void 0?void 0:s.parts)a.functionCall&&i.push(a.functionCall);if(i.length>0)return i}const Cq=[yu.RECITATION,yu.SAFETY,yu.LANGUAGE];function hh(t){return!!t.finishReason&&Cq.includes(t.finishReason)}function ci(t){var e,n,r;let s="";if((!t.candidates||t.candidates.length===0)&&t.promptFeedback)s+="Response was blocked",!((e=t.promptFeedback)===null||e===void 0)&&e.blockReason&&(s+=` due to ${t.promptFeedback.blockReason}`),!((n=t.promptFeedback)===null||n===void 0)&&n.blockReasonMessage&&(s+=`: ${t.promptFeedback.blockReasonMessage}`);else if(!((r=t.candidates)===null||r===void 0)&&r[0]){const i=t.candidates[0];hh(i)&&(s+=`Candidate was blocked due to ${i.finishReason}`,i.finishMessage&&(s+=`: ${i.finishMessage}`))}return s}function Wu(t){return this instanceof Wu?(this.v=t,this):new Wu(t)}function Oq(t,e,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r=n.apply(t,e||[]),s,i=[];return s={},a("next"),a("throw"),a("return"),s[Symbol.asyncIterator]=function(){return this},s;function a(f){r[f]&&(s[f]=function(h){return new Promise(function(p,g){i.push([f,h,p,g])>1||o(f,h)})})}function o(f,h){try{c(r[f](h))}catch(p){d(i[0][3],p)}}function c(f){f.value instanceof Wu?Promise.resolve(f.value.v).then(u,l):d(i[0][2],f)}function u(f){o("next",f)}function l(f){o("throw",f)}function d(f,h){f(h),i.shift(),i.length&&o(i[0][0],i[0][1])}}/**
|
|
432
|
-
* @license
|
|
433
|
-
* Copyright 2024 Google LLC
|
|
434
|
-
*
|
|
435
|
-
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
436
|
-
* you may not use this file except in compliance with the License.
|
|
437
|
-
* You may obtain a copy of the License at
|
|
438
|
-
*
|
|
439
|
-
* http://www.apache.org/licenses/LICENSE-2.0
|
|
440
|
-
*
|
|
441
|
-
* Unless required by applicable law or agreed to in writing, software
|
|
442
|
-
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
443
|
-
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
444
|
-
* See the License for the specific language governing permissions and
|
|
445
|
-
* limitations under the License.
|
|
446
|
-
*/const iA=/^data\: (.*)(?:\n\n|\r\r|\r\n\r\n)/;function $q(t){const e=t.body.pipeThrough(new TextDecoderStream("utf8",{fatal:!0})),n=Nq(e),[r,s]=n.tee();return{stream:Pq(r),response:Rq(s)}}async function Rq(t){const e=[],n=t.getReader();for(;;){const{done:r,value:s}=await n.read();if(r)return ob(Mq(e));e.push(s)}}function Pq(t){return Oq(this,arguments,function*(){const n=t.getReader();for(;;){const{value:r,done:s}=yield Wu(n.read());if(s)break;yield yield Wu(ob(r))}})}function Nq(t){const e=t.getReader();return new ReadableStream({start(r){let s="";return i();function i(){return e.read().then(({value:a,done:o})=>{if(o){if(s.trim()){r.error(new yn("Failed to parse stream"));return}r.close();return}s+=a;let c=s.match(iA),u;for(;c;){try{u=JSON.parse(c[1])}catch{r.error(new yn(`Error parsing JSON response: "${c[1]}"`));return}r.enqueue(u),s=s.substring(c[0].length),c=s.match(iA)}return i()}).catch(a=>{let o=a;throw o.stack=a.stack,o.name==="AbortError"?o=new H1("Request aborted when reading from the stream"):o=new yn("Error reading from the stream"),o})}}})}function Mq(t){const e=t[t.length-1],n={promptFeedback:e==null?void 0:e.promptFeedback};for(const r of t){if(r.candidates){let s=0;for(const i of r.candidates)if(n.candidates||(n.candidates=[]),n.candidates[s]||(n.candidates[s]={index:s}),n.candidates[s].citationMetadata=i.citationMetadata,n.candidates[s].groundingMetadata=i.groundingMetadata,n.candidates[s].finishReason=i.finishReason,n.candidates[s].finishMessage=i.finishMessage,n.candidates[s].safetyRatings=i.safetyRatings,i.content&&i.content.parts){n.candidates[s].content||(n.candidates[s].content={role:i.content.role||"user",parts:[]});const a={};for(const o of i.content.parts)o.text&&(a.text=o.text),o.functionCall&&(a.functionCall=o.functionCall),o.executableCode&&(a.executableCode=o.executableCode),o.codeExecutionResult&&(a.codeExecutionResult=o.codeExecutionResult),Object.keys(a).length===0&&(a.text=""),n.candidates[s].content.parts.push(a)}s++}r.usageMetadata&&(n.usageMetadata=r.usageMetadata)}return n}/**
|
|
447
|
-
* @license
|
|
448
|
-
* Copyright 2024 Google LLC
|
|
449
|
-
*
|
|
450
|
-
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
451
|
-
* you may not use this file except in compliance with the License.
|
|
452
|
-
* You may obtain a copy of the License at
|
|
453
|
-
*
|
|
454
|
-
* http://www.apache.org/licenses/LICENSE-2.0
|
|
455
|
-
*
|
|
456
|
-
* Unless required by applicable law or agreed to in writing, software
|
|
457
|
-
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
458
|
-
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
459
|
-
* See the License for the specific language governing permissions and
|
|
460
|
-
* limitations under the License.
|
|
461
|
-
*/async function V1(t,e,n,r){const s=await Nl(e,Ea.STREAM_GENERATE_CONTENT,t,!0,JSON.stringify(n),r);return $q(s)}async function K1(t,e,n,r){const i=await(await Nl(e,Ea.GENERATE_CONTENT,t,!1,JSON.stringify(n),r)).json();return{response:ob(i)}}/**
|
|
462
|
-
* @license
|
|
463
|
-
* Copyright 2024 Google LLC
|
|
464
|
-
*
|
|
465
|
-
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
466
|
-
* you may not use this file except in compliance with the License.
|
|
467
|
-
* You may obtain a copy of the License at
|
|
468
|
-
*
|
|
469
|
-
* http://www.apache.org/licenses/LICENSE-2.0
|
|
470
|
-
*
|
|
471
|
-
* Unless required by applicable law or agreed to in writing, software
|
|
472
|
-
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
473
|
-
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
474
|
-
* See the License for the specific language governing permissions and
|
|
475
|
-
* limitations under the License.
|
|
476
|
-
*/function W1(t){if(t!=null){if(typeof t=="string")return{role:"system",parts:[{text:t}]};if(t.text)return{role:"system",parts:[t]};if(t.parts)return t.role?t:{role:"system",parts:t.parts}}}function Zu(t){let e=[];if(typeof t=="string")e=[{text:t}];else for(const n of t)typeof n=="string"?e.push({text:n}):e.push(n);return Lq(e)}function Lq(t){const e={role:"user",parts:[]},n={role:"function",parts:[]};let r=!1,s=!1;for(const i of t)"functionResponse"in i?(n.parts.push(i),s=!0):(e.parts.push(i),r=!0);if(r&&s)throw new yn("Within a single message, FunctionResponse cannot be mixed with other type of part in the request for sending chat message.");if(!r&&!s)throw new yn("No content is provided for sending chat message.");return r?e:n}function jq(t,e){var n;let r={model:e==null?void 0:e.model,generationConfig:e==null?void 0:e.generationConfig,safetySettings:e==null?void 0:e.safetySettings,tools:e==null?void 0:e.tools,toolConfig:e==null?void 0:e.toolConfig,systemInstruction:e==null?void 0:e.systemInstruction,cachedContent:(n=e==null?void 0:e.cachedContent)===null||n===void 0?void 0:n.name,contents:[]};const s=t.generateContentRequest!=null;if(t.contents){if(s)throw new Ii("CountTokensRequest must have one of contents or generateContentRequest, not both.");r.contents=t.contents}else if(s)r=Object.assign(Object.assign({},r),t.generateContentRequest);else{const i=Zu(t);r.contents=[i]}return{generateContentRequest:r}}function aA(t){let e;return t.contents?e=t:e={contents:[Zu(t)]},t.systemInstruction&&(e.systemInstruction=W1(t.systemInstruction)),e}function Dq(t){return typeof t=="string"||Array.isArray(t)?{content:Zu(t)}:t}/**
|
|
477
|
-
* @license
|
|
478
|
-
* Copyright 2024 Google LLC
|
|
479
|
-
*
|
|
480
|
-
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
481
|
-
* you may not use this file except in compliance with the License.
|
|
482
|
-
* You may obtain a copy of the License at
|
|
483
|
-
*
|
|
484
|
-
* http://www.apache.org/licenses/LICENSE-2.0
|
|
485
|
-
*
|
|
486
|
-
* Unless required by applicable law or agreed to in writing, software
|
|
487
|
-
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
488
|
-
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
489
|
-
* See the License for the specific language governing permissions and
|
|
490
|
-
* limitations under the License.
|
|
491
|
-
*/const oA=["text","inlineData","functionCall","functionResponse","executableCode","codeExecutionResult"],Uq={user:["text","inlineData"],function:["functionResponse"],model:["text","functionCall","executableCode","codeExecutionResult"],system:["text"]};function Fq(t){let e=!1;for(const n of t){const{role:r,parts:s}=n;if(!e&&r!=="user")throw new yn(`First content should be with role 'user', got ${r}`);if(!YS.includes(r))throw new yn(`Each item should include role field. Got ${r} but valid roles are: ${JSON.stringify(YS)}`);if(!Array.isArray(s))throw new yn("Content should have 'parts' property with an array of Parts");if(s.length===0)throw new yn("Each Content should have at least one part");const i={text:0,inlineData:0,functionCall:0,functionResponse:0,fileData:0,executableCode:0,codeExecutionResult:0};for(const o of s)for(const c of oA)c in o&&(i[c]+=1);const a=Uq[r];for(const o of oA)if(!a.includes(o)&&i[o]>0)throw new yn(`Content with role '${r}' can't contain '${o}' part`);e=!0}}function cA(t){var e;if(t.candidates===void 0||t.candidates.length===0)return!1;const n=(e=t.candidates[0])===null||e===void 0?void 0:e.content;if(n===void 0||n.parts===void 0||n.parts.length===0)return!1;for(const r of n.parts)if(r===void 0||Object.keys(r).length===0||r.text!==void 0&&r.text==="")return!1;return!0}/**
|
|
492
|
-
* @license
|
|
493
|
-
* Copyright 2024 Google LLC
|
|
494
|
-
*
|
|
495
|
-
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
496
|
-
* you may not use this file except in compliance with the License.
|
|
497
|
-
* You may obtain a copy of the License at
|
|
498
|
-
*
|
|
499
|
-
* http://www.apache.org/licenses/LICENSE-2.0
|
|
500
|
-
*
|
|
501
|
-
* Unless required by applicable law or agreed to in writing, software
|
|
502
|
-
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
503
|
-
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
504
|
-
* See the License for the specific language governing permissions and
|
|
505
|
-
* limitations under the License.
|
|
506
|
-
*/const uA="SILENT_ERROR";class Bq{constructor(e,n,r,s={}){this.model=n,this.params=r,this._requestOptions=s,this._history=[],this._sendPromise=Promise.resolve(),this._apiKey=e,r!=null&&r.history&&(Fq(r.history),this._history=r.history)}async getHistory(){return await this._sendPromise,this._history}async sendMessage(e,n={}){var r,s,i,a,o,c;await this._sendPromise;const u=Zu(e),l={safetySettings:(r=this.params)===null||r===void 0?void 0:r.safetySettings,generationConfig:(s=this.params)===null||s===void 0?void 0:s.generationConfig,tools:(i=this.params)===null||i===void 0?void 0:i.tools,toolConfig:(a=this.params)===null||a===void 0?void 0:a.toolConfig,systemInstruction:(o=this.params)===null||o===void 0?void 0:o.systemInstruction,cachedContent:(c=this.params)===null||c===void 0?void 0:c.cachedContent,contents:[...this._history,u]},d=Object.assign(Object.assign({},this._requestOptions),n);let f;return this._sendPromise=this._sendPromise.then(()=>K1(this._apiKey,this.model,l,d)).then(h=>{var p;if(cA(h.response)){this._history.push(u);const g=Object.assign({parts:[],role:"model"},(p=h.response.candidates)===null||p===void 0?void 0:p[0].content);this._history.push(g)}else{const g=ci(h.response);g&&console.warn(`sendMessage() was unsuccessful. ${g}. Inspect response object for details.`)}f=h}).catch(h=>{throw this._sendPromise=Promise.resolve(),h}),await this._sendPromise,f}async sendMessageStream(e,n={}){var r,s,i,a,o,c;await this._sendPromise;const u=Zu(e),l={safetySettings:(r=this.params)===null||r===void 0?void 0:r.safetySettings,generationConfig:(s=this.params)===null||s===void 0?void 0:s.generationConfig,tools:(i=this.params)===null||i===void 0?void 0:i.tools,toolConfig:(a=this.params)===null||a===void 0?void 0:a.toolConfig,systemInstruction:(o=this.params)===null||o===void 0?void 0:o.systemInstruction,cachedContent:(c=this.params)===null||c===void 0?void 0:c.cachedContent,contents:[...this._history,u]},d=Object.assign(Object.assign({},this._requestOptions),n),f=V1(this._apiKey,this.model,l,d);return this._sendPromise=this._sendPromise.then(()=>f).catch(h=>{throw new Error(uA)}).then(h=>h.response).then(h=>{if(cA(h)){this._history.push(u);const p=Object.assign({},h.candidates[0].content);p.role||(p.role="model"),this._history.push(p)}else{const p=ci(h);p&&console.warn(`sendMessageStream() was unsuccessful. ${p}. Inspect response object for details.`)}}).catch(h=>{h.message!==uA&&console.error(h)}),f}}/**
|
|
507
|
-
* @license
|
|
508
|
-
* Copyright 2024 Google LLC
|
|
509
|
-
*
|
|
510
|
-
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
511
|
-
* you may not use this file except in compliance with the License.
|
|
512
|
-
* You may obtain a copy of the License at
|
|
513
|
-
*
|
|
514
|
-
* http://www.apache.org/licenses/LICENSE-2.0
|
|
515
|
-
*
|
|
516
|
-
* Unless required by applicable law or agreed to in writing, software
|
|
517
|
-
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
518
|
-
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
519
|
-
* See the License for the specific language governing permissions and
|
|
520
|
-
* limitations under the License.
|
|
521
|
-
*/async function zq(t,e,n,r){return(await Nl(e,Ea.COUNT_TOKENS,t,!1,JSON.stringify(n),r)).json()}/**
|
|
522
|
-
* @license
|
|
523
|
-
* Copyright 2024 Google LLC
|
|
524
|
-
*
|
|
525
|
-
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
526
|
-
* you may not use this file except in compliance with the License.
|
|
527
|
-
* You may obtain a copy of the License at
|
|
528
|
-
*
|
|
529
|
-
* http://www.apache.org/licenses/LICENSE-2.0
|
|
530
|
-
*
|
|
531
|
-
* Unless required by applicable law or agreed to in writing, software
|
|
532
|
-
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
533
|
-
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
534
|
-
* See the License for the specific language governing permissions and
|
|
535
|
-
* limitations under the License.
|
|
536
|
-
*/async function Hq(t,e,n,r){return(await Nl(e,Ea.EMBED_CONTENT,t,!1,JSON.stringify(n),r)).json()}async function Vq(t,e,n,r){const s=n.requests.map(a=>Object.assign(Object.assign({},a),{model:e}));return(await Nl(e,Ea.BATCH_EMBED_CONTENTS,t,!1,JSON.stringify({requests:s}),r)).json()}/**
|
|
537
|
-
* @license
|
|
538
|
-
* Copyright 2024 Google LLC
|
|
539
|
-
*
|
|
540
|
-
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
541
|
-
* you may not use this file except in compliance with the License.
|
|
542
|
-
* You may obtain a copy of the License at
|
|
543
|
-
*
|
|
544
|
-
* http://www.apache.org/licenses/LICENSE-2.0
|
|
545
|
-
*
|
|
546
|
-
* Unless required by applicable law or agreed to in writing, software
|
|
547
|
-
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
548
|
-
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
549
|
-
* See the License for the specific language governing permissions and
|
|
550
|
-
* limitations under the License.
|
|
551
|
-
*/class lA{constructor(e,n,r={}){this.apiKey=e,this._requestOptions=r,n.model.includes("/")?this.model=n.model:this.model=`models/${n.model}`,this.generationConfig=n.generationConfig||{},this.safetySettings=n.safetySettings||[],this.tools=n.tools,this.toolConfig=n.toolConfig,this.systemInstruction=W1(n.systemInstruction),this.cachedContent=n.cachedContent}async generateContent(e,n={}){var r;const s=aA(e),i=Object.assign(Object.assign({},this._requestOptions),n);return K1(this.apiKey,this.model,Object.assign({generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:(r=this.cachedContent)===null||r===void 0?void 0:r.name},s),i)}async generateContentStream(e,n={}){var r;const s=aA(e),i=Object.assign(Object.assign({},this._requestOptions),n);return V1(this.apiKey,this.model,Object.assign({generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:(r=this.cachedContent)===null||r===void 0?void 0:r.name},s),i)}startChat(e){var n;return new Bq(this.apiKey,this.model,Object.assign({generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:(n=this.cachedContent)===null||n===void 0?void 0:n.name},e),this._requestOptions)}async countTokens(e,n={}){const r=jq(e,{model:this.model,generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:this.cachedContent}),s=Object.assign(Object.assign({},this._requestOptions),n);return zq(this.apiKey,this.model,r,s)}async embedContent(e,n={}){const r=Dq(e),s=Object.assign(Object.assign({},this._requestOptions),n);return Hq(this.apiKey,this.model,r,s)}async batchEmbedContents(e,n={}){const r=Object.assign(Object.assign({},this._requestOptions),n);return Vq(this.apiKey,this.model,e,r)}}/**
|
|
552
|
-
* @license
|
|
553
|
-
* Copyright 2024 Google LLC
|
|
554
|
-
*
|
|
555
|
-
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
556
|
-
* you may not use this file except in compliance with the License.
|
|
557
|
-
* You may obtain a copy of the License at
|
|
558
|
-
*
|
|
559
|
-
* http://www.apache.org/licenses/LICENSE-2.0
|
|
560
|
-
*
|
|
561
|
-
* Unless required by applicable law or agreed to in writing, software
|
|
562
|
-
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
563
|
-
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
564
|
-
* See the License for the specific language governing permissions and
|
|
565
|
-
* limitations under the License.
|
|
566
|
-
*/class dA{constructor(e){this.apiKey=e}getGenerativeModel(e,n){if(!e.model)throw new yn("Must provide a model name. Example: genai.getGenerativeModel({ model: 'my-model-name' })");return new lA(this.apiKey,e,n)}getGenerativeModelFromCachedContent(e,n,r){if(!e.name)throw new Ii("Cached content must contain a `name` field.");if(!e.model)throw new Ii("Cached content must contain a `model` field.");const s=["model","systemInstruction"];for(const a of s)if(n!=null&&n[a]&&e[a]&&(n==null?void 0:n[a])!==e[a]){if(a==="model"){const o=n.model.startsWith("models/")?n.model.replace("models/",""):n.model,c=e.model.startsWith("models/")?e.model.replace("models/",""):e.model;if(o===c)continue}throw new Ii(`Different value for "${a}" specified in modelParams (${n[a]}) and cachedContent (${e[a]})`)}const i=Object.assign(Object.assign({},n),{model:e.model,tools:e.tools,toolConfig:e.toolConfig,systemInstruction:e.systemInstruction,cachedContent:e});return new lA(this.apiKey,i,r)}}function hA(t,e){const n=Kq(t);return{tools:n,toolConfig:Zq(n,e)}}function Kq(t){let e=[];const n=[];return t.forEach(r=>{if(Zs(r)){const[s]=pq([r]);s.functionDeclarations&&e.push(...s.functionDeclarations)}else if(Xo(r)){const{functionDeclarations:s}=Wq(r);if(s)e.push(...s);else throw new Error("Failed to convert OpenAI structured tool to GenerativeAI tool")}else n.push(r)}),n.find(r=>"functionDeclarations"in r)?n.map(r=>{if((e==null?void 0:e.length)>0&&"functionDeclarations"in r){const s={functionDeclarations:[...r.functionDeclarations||[],...e]};return e=[],s}return r}):[...n,...e.length>0?[{functionDeclarations:e}]:[]]}function Wq(t){return{functionDeclarations:[{name:t.function.name,description:t.function.description,parameters:Ta(t.function.parameters)}]}}function Zq(t,e){if(!t.length||!e)return;const{toolChoice:n,allowedFunctionNames:r}=e,s={any:lo.ANY,auto:lo.AUTO,none:lo.NONE};if(n&&["any","auto","none"].includes(n))return{functionCallingConfig:{mode:s[n]??"MODE_UNSPECIFIED",allowedFunctionNames:r}};if(typeof n=="string"||r)return{functionCallingConfig:{mode:lo.ANY,allowedFunctionNames:[...r??[],...n&&typeof n=="string"?[n]:[]]}}}const qq={"gemini-embedding-001":{maxInputTokens:2048,imageInputs:!1,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:3072,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!1},"gemini-2.5-flash-lite-preview-09-2025":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-2.5-pro-preview-06-05":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-2.5-flash-preview-04-17":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1},"gemini-2.5-flash-preview-09-2025":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-2.5-pro-preview-05-06":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-2.5-flash-preview-05-20":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-2.5-flash":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-live-2.5-flash":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!0,pdfInputs:!1,videoInputs:!0,maxOutputTokens:8e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!0,videoOutputs:!1,toolCalling:!0,structuredOutput:!1},"gemini-3-flash-preview":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-live-2.5-flash-preview-native-audio":{maxInputTokens:131072,imageInputs:!1,audioInputs:!0,pdfInputs:!1,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!0,videoOutputs:!1,toolCalling:!0,structuredOutput:!1},"gemini-2.5-flash-lite":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-2.5-flash-preview-tts":{maxInputTokens:8e3,imageInputs:!1,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:16e3,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!0,videoOutputs:!1,toolCalling:!1,structuredOutput:!1},"gemini-flash-latest":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-2.5-flash-lite-preview-06-17":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1},"gemini-2.5-flash-image":{maxInputTokens:32768,imageInputs:!0,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!0,imageOutputs:!0,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!1},"gemini-2.5-pro-preview-tts":{maxInputTokens:8e3,imageInputs:!1,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:16e3,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!0,videoOutputs:!1,toolCalling:!1,structuredOutput:!1},"gemini-2.5-flash-image-preview":{maxInputTokens:32768,imageInputs:!0,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!0,imageOutputs:!0,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!1},"gemini-1.5-flash-8b":{maxInputTokens:1e6,imageInputs:!0,audioInputs:!0,pdfInputs:!1,videoInputs:!0,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1},"gemini-3-pro-preview":{maxInputTokens:1e6,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:64e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-2.0-flash-lite":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-1.5-flash":{maxInputTokens:1e6,imageInputs:!0,audioInputs:!0,pdfInputs:!1,videoInputs:!0,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1},"gemini-flash-lite-latest":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-2.5-pro":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-2.0-flash":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-1.5-pro":{maxInputTokens:1e6,imageInputs:!0,audioInputs:!0,pdfInputs:!1,videoInputs:!0,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1}};var Gq=class extends Es{constructor(e,n){const r=typeof e=="string"?{...n??{},model:e}:e;super(r);m(this,"lc_serializable",!0);m(this,"lc_namespace",["langchain","chat_models","google_genai"]);m(this,"model");m(this,"temperature");m(this,"maxOutputTokens");m(this,"topP");m(this,"topK");m(this,"stopSequences",[]);m(this,"safetySettings");m(this,"apiKey");m(this,"streaming",!1);m(this,"json");m(this,"streamUsage",!0);m(this,"convertSystemMessageToHumanContent");m(this,"thinkingConfig");m(this,"client");if(this._addVersion("@langchain/google-genai","2.1.31"),this.model=r.model.replace(/^models\//,""),this.maxOutputTokens=r.maxOutputTokens??this.maxOutputTokens,this.maxOutputTokens&&this.maxOutputTokens<0)throw new Error("`maxOutputTokens` must be a positive integer");if(this.temperature=r.temperature??this.temperature,this.temperature&&(this.temperature<0||this.temperature>2))throw new Error("`temperature` must be in the range of [0.0,2.0]");if(this.topP=r.topP??this.topP,this.topP&&this.topP<0)throw new Error("`topP` must be a positive integer");if(this.topP&&this.topP>1)throw new Error("`topP` must be below 1.");if(this.topK=r.topK??this.topK,this.topK&&this.topK<0)throw new Error("`topK` must be a positive integer");if(this.stopSequences=r.stopSequences??this.stopSequences,this.apiKey=r.apiKey??Mt("GOOGLE_API_KEY"),!this.apiKey)throw new Error("Please set an API key for Google GenerativeAI in the environment variable GOOGLE_API_KEY or in the `apiKey` field of the ChatGoogleGenerativeAI constructor");if(this.safetySettings=r.safetySettings??this.safetySettings,this.safetySettings&&this.safetySettings.length>0&&new Set(this.safetySettings.map(s=>s.category)).size!==this.safetySettings.length)throw new Error("The categories in `safetySettings` array must be unique");this.streaming=r.streaming??this.streaming,this.json=r.json,this.thinkingConfig=r.thinkingConfig??this.thinkingConfig,this.client=new dA(this.apiKey).getGenerativeModel({model:this.model,safetySettings:this.safetySettings,generationConfig:{stopSequences:this.stopSequences,maxOutputTokens:this.maxOutputTokens,temperature:this.temperature,topP:this.topP,topK:this.topK,...this.json?{responseMimeType:"application/json"}:{},...this.thinkingConfig?{thinkingConfig:this.thinkingConfig}:{}}},{apiVersion:r.apiVersion,baseUrl:r.baseUrl,customHeaders:r.customHeaders}),this.streamUsage=r.streamUsage??this.streamUsage}static lc_name(){return"ChatGoogleGenerativeAI"}get lc_secrets(){return{apiKey:"GOOGLE_API_KEY"}}get lc_aliases(){return{apiKey:"google_api_key"}}get _isMultimodalModel(){return this.model.includes("vision")||this.model.startsWith("gemini-1.5")||this.model.startsWith("gemini-2")||this.model.startsWith("gemma-3-")&&!this.model.startsWith("gemma-3-1b")||this.model.startsWith("gemini-3")}useCachedContent(e,n,r){this.apiKey&&(this.client=new dA(this.apiKey).getGenerativeModelFromCachedContent(e,n,r))}get useSystemInstruction(){return typeof this.convertSystemMessageToHumanContent=="boolean"?!this.convertSystemMessageToHumanContent:this.computeUseSystemInstruction}get computeUseSystemInstruction(){return this.model==="gemini-1.0-pro-001"||this.model.startsWith("gemini-pro-vision")||this.model.startsWith("gemini-1.0-pro-vision")?!1:this.model!=="gemini-pro"}getLsParams(e){return{ls_provider:"google_genai",ls_model_name:this.model,ls_model_type:"chat",ls_temperature:this.client.generationConfig.temperature,ls_max_tokens:this.client.generationConfig.maxOutputTokens,ls_stop:e.stop}}_combineLLMOutput(){return[]}_llmType(){return"googlegenerativeai"}bindTools(e,n){var r;return this.withConfig({tools:(r=hA(e))==null?void 0:r.tools,...n})}invocationParams(e){var r;const n=(r=e==null?void 0:e.tools)!=null&&r.length?hA(e.tools,{toolChoice:e.tool_choice,allowedFunctionNames:e.allowedFunctionNames}):void 0;return e!=null&&e.responseSchema?(this.client.generationConfig.responseSchema=e.responseSchema,this.client.generationConfig.responseMimeType="application/json"):(this.client.generationConfig.responseSchema=void 0,this.client.generationConfig.responseMimeType=this.json?"application/json":void 0),{...n!=null&&n.tools?{tools:n.tools}:{},...n!=null&&n.toolConfig?{toolConfig:n.toolConfig}:{}}}async _generate(e,n,r){var l,d,f,h;(l=n.signal)==null||l.throwIfAborted();const s=WS(e,this._isMultimodalModel,this.useSystemInstruction,this.model);let i=s;if(s[0].role==="system"){const[p]=s;this.client.systemInstruction=p,i=s.slice(1)}const a=this.invocationParams(n);if(this.streaming){const p={},g=this._streamResponseChunks(e,n,r),y=[];for await(const b of g){const _=((d=b.generationInfo)==null?void 0:d.completion)??0;y[_]===void 0?y[_]=b:y[_]=y[_].concat(b)}return{generations:y.filter(b=>b!==void 0),llmOutput:{estimatedTokenUsage:p}}}const o=await this.completionWithRetry({...a,contents:i});let c;"usageMetadata"in o.response&&(c=ZS(o.response.usageMetadata,this.model));const u=hq(o.response,{usageMetadata:c});return((f=u.generations)==null?void 0:f.length)>0&&await(r==null?void 0:r.handleLLMNewToken(((h=u.generations[0])==null?void 0:h.text)??"")),u}async*_streamResponseChunks(e,n,r){var f;const s=WS(e,this._isMultimodalModel,this.useSystemInstruction,this.model);let i=s;if(s[0].role==="system"){const[h]=s;this.client.systemInstruction=h,i=s.slice(1)}const a={...this.invocationParams(n),contents:i},o=await this.caller.callWithOptions({signal:n==null?void 0:n.signal},async()=>{const{stream:h}=await this.client.generateContentStream(a,{signal:n==null?void 0:n.signal});return h});let c,u=0,l=0,d=0;for await(const h of o){if((f=n.signal)!=null&&f.aborted)return;if("usageMetadata"in h&&h.usageMetadata!==void 0&&this.streamUsage!==!1&&n.streamUsage!==!1){c=ZS(h.usageMetadata,this.model);const g=h.usageMetadata.promptTokenCount??0;c.input_tokens=Math.max(0,g-u),u=g;const y=h.usageMetadata.candidatesTokenCount??0;c.output_tokens=Math.max(0,y-l),l=y;const b=h.usageMetadata.totalTokenCount??0;c.total_tokens=Math.max(0,b-d),d=b}const p=fq(h,{usageMetadata:c});p&&(yield p,await(r==null?void 0:r.handleLLMNewToken(p.text??"")))}}async completionWithRetry(e,n){return this.caller.callWithOptions({signal:n==null?void 0:n.signal},async()=>{var r;try{return await this.client.generateContent(e,{signal:n==null?void 0:n.signal})}catch(s){throw(r=s.message)!=null&&r.includes("400 Bad Request")&&(s.status=400),s}})}get profile(){return qq[this.model]??{}}withStructuredOutput(e,n){const r=e,s=n==null?void 0:n.name,i=n==null?void 0:n.method,a=n==null?void 0:n.includeRaw;if(i==="jsonMode")throw new Error('ChatGoogleGenerativeAI only supports "jsonSchema" or "functionCalling" as a method.');let o,c;if(i==="functionCalling"){let u=s??"extract",l;if(Wt(r)||Or(r)){const f=j_(r);l={name:u,description:f.description??"A function available to call.",parameters:f}}else typeof r.name=="string"&&typeof r.parameters=="object"&&r.parameters!=null?(l=r,l.parameters=Ta(r.parameters),u=r.name):l={name:u,description:r.description??"",parameters:Ta(r)};const d=[{functionDeclarations:[l]}];o=this.bindTools(d).withConfig({allowedFunctionNames:[u]}),c=Tl(r,u,mq)}else{const u=j_(r);o=this.withConfig({responseSchema:u}),c=Ko(r)}return tc(o,c,a,a?"StructuredOutputRunnable":"ChatGoogleGenerativeAIStructuredOutput")}},Jq=class extends Qo{constructor(e){super(e);m(this,"lc_namespace",["langchain","anthropic","output_parsers"]);m(this,"returnId",!1);m(this,"keyName");m(this,"returnSingle",!1);m(this,"zodSchema");m(this,"serializableSchema");this.keyName=e.keyName,this.returnSingle=e.returnSingle??this.returnSingle,this.zodSchema=e.zodSchema,this.serializableSchema=e.serializableSchema}static lc_name(){return"AnthropicToolsOutputParser"}async _validateResult(e){let n=e;if(typeof e=="string")try{n=JSON.parse(e)}catch(s){throw new vn(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(s.message)}`,e)}else n=e;if(this.serializableSchema!==void 0){const s=await this.serializableSchema["~standard"].validate(n);if(s.issues)throw new vn(`Failed to parse. Text: "${JSON.stringify(n,null,2)}". Error: ${JSON.stringify(s.issues)}`,JSON.stringify(n,null,2));return s.value}if(this.zodSchema===void 0)return n;const r=await xf(this.zodSchema,n);if(r.success)return r.data;throw new vn(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(r.error.issues)}`,JSON.stringify(n,null,2))}async parseResult(e){const n=e.flatMap(s=>{const{message:i}=s;return Array.isArray(i.content)?Z1(i.content)[0]:[]});if(n[0]===void 0)throw new Error("No parseable tool calls provided to AnthropicToolsOutputParser.");const[r]=n;return await this._validateResult(r.args)}};function Z1(t){const e=[];for(const n of t)n.type==="tool_use"&&e.push({name:n.name,args:n.input,id:n.id,type:"tool_call"});return e}function Yq(t){if(t)return t==="any"||t==="required"?{type:"any"}:t==="auto"?{type:"auto"}:t==="none"?{type:"none"}:typeof t=="string"?{type:"tool",name:t}:t}const Xq=$e({cache_control:Yg().optional().nullable(),defer_loading:Uv().optional(),input_examples:ba(Hh()).optional(),allowed_callers:ba(Hh()).optional(),strict:Uv().optional()}),fA={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 Qq(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="thinking"}function eG(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="redacted_thinking"}function q1(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="compaction"}function tG(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="search_result"}function nG(t){return typeof t!="object"||t==null||!("type"in t)||t.type!=="image"||!("source"in t)||typeof t.source!="object"||t.source==null||!("type"in t.source)?!1:t.source.type==="base64"?!(!("media_type"in t.source)||typeof t.source.media_type!="string"||!("data"in t.source)||typeof t.source.data!="string"):t.source.type==="url"?!(!("url"in t.source)||typeof t.source.url!="string"):!1}const rG={providerName:"anthropic",fromStandardTextBlock(t){return{type:"text",text:t.text,..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}}},fromStandardImageBlock(t){if(t.source_type==="url"){const e=Gr({dataUrl:t.url,asTypedArray:!1});return e?{type:"image",source:{type:"base64",data:e.data,media_type:e.mime_type},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}}:{type:"image",source:{type:"url",url:t.url},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}}}else{if(t.source_type==="base64")return{type:"image",source:{type:"base64",data:t.data,media_type:t.mime_type??""},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}};throw new Error(`Unsupported image source type: ${t.source_type}`)}},fromStandardFileBlock(t){const e=(t.mime_type??"").split(";")[0];if(t.source_type==="url"){if(e==="application/pdf"||e==="")return{type:"document",source:{type:"url",url:t.url},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{},..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."context"in(t.metadata??{})?{context:t.metadata.context}:{},..."title"in(t.metadata??{})?{title:t.metadata.title}:{}};throw new Error(`Unsupported file mime type for file url source: ${t.mime_type}`)}else if(t.source_type==="text"){if(e==="text/plain"||e==="")return{type:"document",source:{type:"text",data:t.text,media_type:t.mime_type??""},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{},..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."context"in(t.metadata??{})?{context:t.metadata.context}:{},..."title"in(t.metadata??{})?{title:t.metadata.title}:{}};throw new Error(`Unsupported file mime type for file text source: ${t.mime_type}`)}else if(t.source_type==="base64"){if(e==="application/pdf"||e==="")return{type:"document",source:{type:"base64",data:t.data,media_type:"application/pdf"},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{},..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."context"in(t.metadata??{})?{context:t.metadata.context}:{},..."title"in(t.metadata??{})?{title:t.metadata.title}:{}};if(["image/jpeg","image/png","image/gif","image/webp"].includes(e))return{type:"document",source:{type:"content",content:[{type:"image",source:{type:"base64",data:t.data,media_type:e}}]},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{},..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."context"in(t.metadata??{})?{context:t.metadata.context}:{},..."title"in(t.metadata??{})?{title:t.metadata.title}:{}};throw new Error(`Unsupported file mime type for file base64 source: ${t.mime_type}`)}else throw new Error(`Unsupported file source type: ${t.source_type}`)}},sG=t=>t();function iG(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="citation"}function aG(t){function*e(){for(const n of t)iG(n)&&(n.source==="char"?yield{type:"char_location",file_id:n.url??"",start_char_index:n.startIndex??0,end_char_index:n.endIndex??0,document_title:n.title??null,document_index:0,cited_text:n.citedText??""}:n.source==="page"?yield{type:"page_location",file_id:n.url??"",start_page_number:n.startIndex??0,end_page_number:n.endIndex??0,document_title:n.title??null,document_index:0,cited_text:n.citedText??""}:n.source==="block"?yield{type:"content_block_location",file_id:n.url??"",start_block_index:n.startIndex??0,end_block_index:n.endIndex??0,document_title:n.title??null,document_index:0,cited_text:n.citedText??""}:n.source==="url"?yield{type:"web_search_result_location",url:n.url??"",title:n.title??null,encrypted_index:String(n.startIndex??0),cited_text:n.citedText??""}:n.source==="search"&&(yield{type:"search_result_location",title:n.title??null,start_block_index:n.startIndex??0,end_block_index:n.endIndex??0,search_result_index:0,source:n.source??"",cited_text:n.citedText??""}))}return Array.from(e())}function gc(t){return typeof t=="string"?t:oG(t)}function oG(t){const e=[];for(let n=0,{length:r}=t;n<r;n++)e.push(String.fromCharCode(t[n]));return btoa(e.join(""))}function Am(t){return(t??"").split(";")[0].toLowerCase()}function Qc(t,e){if(t!=null&&typeof t=="object"&&e in t)return t[e]}function Ba(t,e){const n=Qc(e,"cache_control");n!==void 0&&(t.cache_control=n);const r=Qc(e,"citations");r!==void 0&&(t.citations=r);const s=Qc(e,"context");s!==void 0&&(t.context=s);const i=Qc(e,"title");return i!==void 0&&(t.title=i),t}function Tm(t,e){const n=Qc(e,"cache_control");return n!==void 0&&(t.cache_control=n),t}function pA(t){return new Set(["image/jpeg","image/png","image/gif","image/webp"]).has(t)}function cG(t){const e=[],n=t.response_metadata,r="model_provider"in n&&(n==null?void 0:n.model_provider)==="anthropic";for(const s of t.contentBlocks)if(s.type==="text")s.annotations?e.push({type:"text",text:s.text,citations:aG(s.annotations)}):e.push({type:"text",text:s.text});else if(s.type==="tool_call")e.push({type:"tool_use",id:s.id??"",name:s.name,input:s.args});else if(s.type==="tool_call_chunk"){const i=sG(()=>{if(typeof s.args!="string")return s.args;try{return JSON.parse(s.args)}catch{return{}}});e.push({type:"tool_use",id:s.id??"",name:s.name??"",input:i})}else if(s.type==="reasoning"&&r)e.push({type:"thinking",thinking:s.reasoning,signature:String(s.signature)});else if(s.type==="server_tool_call"&&r)s.name==="web_search"?e.push({type:"server_tool_use",name:s.name,id:s.id??"",input:s.args}):s.name==="code_execution"&&e.push({type:"server_tool_use",name:s.name,id:s.id??"",input:s.args});else if(s.type==="server_tool_call_result"&&r)if(s.name==="web_search"&&Array.isArray(s.output.urls)){const i=s.output.urls.map(a=>({type:"web_search_result",title:"",encrypted_content:"",url:a}));e.push({type:"web_search_tool_result",tool_use_id:s.toolCallId??"",content:i})}else s.name==="code_execution"?e.push({type:"code_execution_tool_result",tool_use_id:s.toolCallId??"",content:s.output}):s.name==="mcp_tool_result"&&e.push({type:"mcp_tool_result",tool_use_id:s.toolCallId??"",content:s.output});else{if(s.type==="audio")throw new Error("Anthropic does not support audio content blocks.");if(s.type==="file"){const i=s.metadata;if(s.fileId){e.push(Ba({type:"document",source:{type:"file",file_id:s.fileId}},i));continue}if(s.url){const a=Am(s.mimeType);if(a==="application/pdf"||a===""){e.push(Ba({type:"document",source:{type:"url",url:s.url}},i));continue}}if(s.data){const a=Am(s.mimeType);if(a===""||a==="application/pdf")e.push(Ba({type:"document",source:{type:"base64",data:gc(s.data),media_type:"application/pdf"}},i));else if(a==="text/plain")e.push(Ba({type:"document",source:{type:"text",data:gc(s.data),media_type:"text/plain"}},i));else if(pA(a))e.push(Ba({type:"document",source:{type:"content",content:[{type:"image",source:{type:"base64",data:gc(s.data),media_type:a}}]}},i));else throw new Error(`Unsupported file mime type for Anthropic base64 source: ${a}`);continue}throw new Error("File content block must include a fileId, url, or data property.")}else if(s.type==="image"){const i=s.metadata;if(s.fileId){e.push(Tm({type:"image",source:{type:"file",file_id:s.fileId}},i));continue}if(s.url){e.push(Tm({type:"image",source:{type:"url",url:s.url}},i));continue}if(s.data){const a=Am(s.mimeType)||"image/png";pA(a)&&e.push(Tm({type:"image",source:{type:"base64",data:gc(s.data),media_type:a}},i));continue}throw new Error("Image content block must include a fileId, url, or data property.")}else s.type==="video"||(s.type==="text-plain"?s.data&&e.push(Ba({type:"document",source:{type:"text",data:gc(s.data),media_type:"text/plain"}},s.metadata)):s.type==="non_standard"&&r&&e.push(s.value))}return e}function Em(t){const e=Gr({dataUrl:t});if(e)return{type:"base64",media_type:e.mime_type,data:e.data};let n;try{n=new URL(t)}catch{throw new Error([`Malformed image URL: ${JSON.stringify(t)}. Content blocks of type 'image_url' must be a valid http, https, or base64-encoded data URL.`,"Example: data:image/png;base64,/9j/4AAQSk...","Example: https://example.com/image.jpg"].join(`
|
|
567
|
-
|
|
568
|
-
`))}if(n.protocol==="http:"||n.protocol==="https:")return{type:"url",url:t};throw new Error([`Invalid image URL protocol: ${JSON.stringify(n.protocol)}. Anthropic only supports images as http, https, or base64-encoded data URLs on 'image_url' content blocks.`,"Example: data:image/png;base64,/9j/4AAQSk...","Example: https://example.com/image.jpg"].join(`
|
|
569
|
-
|
|
570
|
-
`))}function uG(t){const e=[];for(const n of t)if(n._getType()==="tool")if(typeof n.content=="string"){const r=e[e.length-1];(r==null?void 0:r._getType())==="human"&&Array.isArray(r.content)&&"type"in r.content[0]&&r.content[0].type==="tool_result"?r.content.push({type:"tool_result",content:n.content,tool_use_id:n.tool_call_id}):e.push(new Nn({content:[{type:"tool_result",content:n.content,tool_use_id:n.tool_call_id}]}))}else e.push(new Nn({content:[{type:"tool_result",...n.content!=null?{content:D_(n)}:{},tool_use_id:n.tool_call_id}]}));else e.push(n);return e}function Im(t){if(t.id===void 0)throw new Error('Anthropic requires all tool calls to have an "id".');return{type:"tool_use",id:t.id,name:t.name,input:t.args}}function*lG(t,e){const n=["bash_code_execution_tool_result","input_json_delta","server_tool_use","text_editor_code_execution_tool_result","tool_result","tool_use","web_search_result","web_search_tool_result"],r=["text","text_delta"];for(const s of t){kr(s)&&(yield ul(s,rG));const i="cache_control"in s?s.cache_control:void 0;if(s.type==="image_url"){let a;typeof s.image_url=="string"?a=Em(s.image_url):typeof s.image_url=="object"&&s.image_url!==null&&"url"in s.image_url&&typeof s.image_url.url=="string"&&(a=Em(s.image_url.url)),a&&(yield{type:"image",source:a,...i?{cache_control:i}:{}})}else if(nG(s))yield s;else if(s.type==="image"){let a;"url"in s&&typeof s.url=="string"?a=Em(s.url):"data"in s&&(typeof s.data=="string"||s.data instanceof Uint8Array)?a={type:"base64",media_type:"mimeType"in s&&typeof s.mimeType=="string"?s.mimeType:"image/jpeg",data:typeof s.data=="string"?s.data:Buffer.from(s.data).toString("base64")}:"fileId"in s&&typeof s.fileId=="string"&&(a={type:"file",file_id:s.fileId}),a&&(yield{type:"image",source:a,...i?{cache_control:i}:{}})}else if(s.type==="file"){let a;"url"in s&&typeof s.url=="string"?a={type:"url",url:s.url}:"data"in s&&(typeof s.data=="string"||s.data instanceof Uint8Array)?a={type:"base64",media_type:"mimeType"in s&&typeof s.mimeType=="string"?s.mimeType:"application/pdf",data:typeof s.data=="string"?s.data:Buffer.from(s.data).toString("base64")}:"fileId"in s&&typeof s.fileId=="string"&&(a={type:"file",file_id:s.fileId}),a&&(yield{type:"document",source:a,...i?{cache_control:i}:{}})}else if(s.type==="document")yield{...s,...i?{cache_control:i}:{}};else if(Qq(s))yield{type:"thinking",thinking:s.thinking,signature:s.signature,...i?{cache_control:i}:{}};else if(eG(s))yield{type:"redacted_thinking",data:s.data,...i?{cache_control:i}:{}};else if(q1(s))yield{type:"compaction",content:s.content,...i?{cache_control:i}:{}};else if(tG(s))yield{type:"search_result",title:s.title,source:s.source,..."cache_control"in s&&s.cache_control?{cache_control:s.cache_control}:{},..."citations"in s&&s.citations?{citations:s.citations}:{},content:s.content};else if(r.find(a=>a===s.type)&&"text"in s)yield{type:"text",text:s.text,...i?{cache_control:i}:{},..."citations"in s&&s.citations?{citations:s.citations}:{}};else if(n.find(a=>a===s.type)){const a={...s};if(a.type==="input_json_delta")continue;if(a.type==="tool_use"&&typeof a.input=="string"){const o=e==null?void 0:e.find(c=>c.id===a.id);o?a.input=o.args:a.input=t.filter(c=>c.index===a.index&&c.type==="input_json_delta"&&typeof c.input=="string").reduce((c,u)=>c+u.input,a.input)}if("index"in a&&delete a.index,"input"in a&&typeof a.input=="string")try{a.input=JSON.parse(a.input)}catch{a.input={}}yield{...a,...i?{cache_control:i}:{}}}else s.type==="container_upload"&&(yield{...s,...i?{cache_control:i}:{}})}}function D_(t,e){const{content:n}=t;return typeof n=="string"?n:Array.from(lG(n,e))}function xm(t){const e=uG(t);let n;return e.length>0&&e[0]._getType()==="system"&&(n=t[0].content),{messages:dG((n!==void 0?e.slice(1):e).map(r=>{var i,a;let s;if(r._getType()==="human")s="user";else if(r._getType()==="ai")s="assistant";else if(r._getType()==="tool")s="user";else throw r._getType()==="system"?new Error("System messages are only permitted as the first passed message."):new Error(`Message type "${r.type}" is not supported.`);if(De.isInstance(r)&&((i=r.response_metadata)==null?void 0:i.output_version)==="v1")return{role:s,content:cG(r)};if(De.isInstance(r)&&((a=r.tool_calls)!=null&&a.length)){if(typeof r.content=="string")return r.content===""?{role:s,content:r.tool_calls.map(Im)}:{role:s,content:[{type:"text",text:r.content},...r.tool_calls.map(Im)]};{const{content:o}=r,c=D_(r,r.tool_calls),u=Array.isArray(c)?c:[{type:"text",text:c}],l=r.tool_calls.filter(d=>!o.find(f=>(f.type==="tool_use"||f.type==="input_json_delta"||f.type==="server_tool_use")&&f.id===d.id));return{role:s,content:[...u,...l.map(Im)]}}}else return{role:s,content:D_(r,De.isInstance(r)?r.tool_calls:void 0)}})),system:n}}function dG(t){if(!t||t.length<=1)return t;const e=[];let n=t[0];const r=i=>typeof i=="string"?[{type:"text",text:i}]:i,s=i=>i.role!=="user"||typeof i.content=="string"?!1:Array.isArray(i.content)&&i.content.every(a=>a.type==="tool_result");for(let i=1;i<t.length;i+=1){const a=t[i];s(n)&&s(a)?n={...n,content:[...r(n.content),...r(a.content)]}:(e.push(n),n=a)}return e.push(n),e}function G1(t){return t.type==="enabled"||t.type==="adaptive"}function cb(t){return(t==null?void 0:t.startsWith("claude-opus-4-7"))??!1}function hG(t,e){const n=e&&typeof e=="object"&&"task_budget"in e&&e.task_budget!=null;return cb(t)&&n?["task-budgets-2026-03-13"]:[]}function fG(t){const{model:e,thinking:n,topK:r,topP:s,temperature:i}=t,a=cb(e);if(a&&n.type==="enabled")throw new Error('thinking.type="enabled" is not supported for claude-opus-4-7; use thinking.type="adaptive" instead');if(a&&typeof n=="object"&&n!=null&&"budget_tokens"in n)throw new Error("thinking.budget_tokens is not supported for claude-opus-4-7; use outputConfig.effort instead");if(a){if(r!==void 0)throw new Error("topK is not supported for claude-opus-4-7; omit topK/topP/temperature or use model prompting instead");if(s!==void 0&&s!==1)throw new Error("topP is not supported for claude-opus-4-7 when set to non-default values");if(i!==void 0&&i!==1)throw new Error("temperature is not supported for claude-opus-4-7 when set to non-default values")}if(G1(n)){if(r!==void 0)throw new Error("topK is not supported when thinking is enabled");if(s!==void 0)throw new Error("topP is not supported when thinking is enabled");if(i!==void 0&&i!==1)throw new Error("temperature is not supported when thinking is enabled")}}function pG(t){const{model:e,thinking:n,topK:r,topP:s,temperature:i}=t,a={};return G1(n)||cb(e)||(i!==void 0&&(a.temperature=i),r!==void 0&&(a.top_k=r),s!==void 0&&(a.top_p=s)),a}function mG(t,e){var r;const n={model_provider:"anthropic"};if(t.type==="message_start"){const{content:s,usage:i,...a}=t.message,o={};for(const[f,h]of Object.entries(a))h!=null&&(o[f]=h);const{input_tokens:c,output_tokens:u,...l}=i??{},d=J1(i);return{chunk:new Ge({content:e.coerceContentToString?"":[],additional_kwargs:o,usage_metadata:e.streamUsage?d:void 0,response_metadata:{...n,usage:{...l}},id:t.message.id})}}else if(t.type==="message_delta"){const s={input_tokens:0,output_tokens:t.usage.output_tokens,total_tokens:t.usage.output_tokens},i="context_management"in t.delta?{context_management:t.delta.context_management}:void 0;return{chunk:new Ge({content:e.coerceContentToString?"":[],response_metadata:i,additional_kwargs:{...t.delta},usage_metadata:e.streamUsage?s:void 0})}}else if(t.type==="content_block_start"&&["tool_use","document","server_tool_use","web_search_tool_result"].includes(t.content_block.type)){const s=t.content_block;let i;return s.type==="tool_use"?i=[{id:s.id,index:t.index,name:s.name,args:""}]:i=[],{chunk:new Ge({content:e.coerceContentToString?"":[{index:t.index,...t.content_block,input:s.type==="server_tool_use"||s.type==="tool_use"?"":void 0}],response_metadata:n,additional_kwargs:{},tool_call_chunks:i})}}else if(t.type==="content_block_delta"&&["text_delta","citations_delta","thinking_delta","signature_delta"].includes(t.delta.type)){if(e.coerceContentToString&&"text"in t.delta)return{chunk:new Ge({content:t.delta.text})};{const s=t.delta;return"citation"in s&&(s.citations=[s.citation],delete s.citation),s.type==="thinking_delta"||s.type==="signature_delta"?{chunk:new Ge({content:[{index:t.index,...s,type:"thinking"}],response_metadata:n})}:{chunk:new Ge({content:[{index:t.index,...s,type:"text"}],response_metadata:n})}}}else{if(t.type==="content_block_delta"&&t.delta.type==="input_json_delta")return{chunk:new Ge({content:e.coerceContentToString?"":[{index:t.index,input:t.delta.partial_json,type:t.delta.type}],response_metadata:n,additional_kwargs:{},tool_call_chunks:[{index:t.index,args:t.delta.partial_json}]})};if(t.type==="content_block_start"&&t.content_block.type==="text"){const s=(r=t.content_block)==null?void 0:r.text;if(s!==void 0)return{chunk:new Ge({content:e.coerceContentToString?s:[{index:t.index,...t.content_block}],response_metadata:n,additional_kwargs:{}})}}else{if(t.type==="content_block_start"&&t.content_block.type==="redacted_thinking")return{chunk:new Ge({content:e.coerceContentToString?"":[{index:t.index,...t.content_block}],response_metadata:n})};if(t.type==="content_block_start"&&t.content_block.type==="thinking"){const s=t.content_block.thinking;return{chunk:new Ge({content:e.coerceContentToString?s:[{index:t.index,...t.content_block}],response_metadata:n})}}else{if(t.type==="content_block_start"&&q1(t.content_block))return{chunk:new Ge({content:e.coerceContentToString?"":[{index:t.index,...t.content_block}],response_metadata:n})};if(t.type==="content_block_delta"&&t.delta.type==="compaction_delta")return{chunk:new Ge({content:e.coerceContentToString?"":[{index:t.index,...t.delta,type:"compaction"}],response_metadata:n})}}}}return null}function gG(t,e){const n={...e,model_provider:"anthropic"},r=e.usage,s=r!=null?J1(r):void 0;return t.length===1&&t[0].type==="text"?[{text:t[0].text,message:new De({content:t[0].text,additional_kwargs:e,usage_metadata:s,response_metadata:n,id:e.id})}]:[{text:"",message:new De({content:t,additional_kwargs:e,tool_calls:Z1(t),usage_metadata:s,response_metadata:n,id:e.id})}]}function J1(t){const e=t.cache_creation_input_tokens??0,n=t.cache_read_input_tokens??0,r=t.input_tokens+e+n;return{input_tokens:r,output_tokens:t.output_tokens,total_tokens:r+t.output_tokens,input_token_details:{cache_creation:e,cache_read:n}}}function _c(t,e){return t.lc_error_code=e,t.message=`${t.message}
|
|
571
|
-
|
|
572
|
-
Troubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${e}/
|
|
573
|
-
`,t}function mA(t){let e;return t.status===400&&typeof t.message=="string"&&t.message.includes("prompt is too long")?e=_c(Z_.fromError(t),"CONTEXT_OVERFLOW"):t.status===400&&t.message.includes("tool")?e=_c(t,"INVALID_TOOL_RESULTS"):t.status===401?e=_c(t,"MODEL_AUTHENTICATION"):t.status===404?e=_c(t,"MODEL_NOT_FOUND"):t.status===429?e=_c(t,"MODEL_RATE_LIMIT"):e=t,e}const _G={"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*yG(t,e={}){const n=e.streamUsage??!0,r=new Map;let s,i=null;for await(const a of t)switch(a.type){case"message_start":{const{usage:o,id:c,model:u}=a.message;o&&n&&(s=bG(o)),yield{event:"message-start",id:c,...s?{usage:s}:{}},yield{event:"provider",provider:"anthropic",name:"message_start",payload:{model:u,id:c}};break}case"message_delta":i=a.delta.stop_reason,n&&a.usage&&(s?s={...s,output_tokens:s.output_tokens+a.usage.output_tokens,total_tokens:s.input_tokens+s.output_tokens+a.usage.output_tokens}:s={input_tokens:0,output_tokens:a.usage.output_tokens,total_tokens:a.usage.output_tokens},yield{event:"usage",usage:s}),"context_management"in a.delta&&a.delta.context_management&&(yield{event:"provider",provider:"anthropic",name:"context_management",payload:a.delta.context_management});break;case"message_stop":yield{event:"message-finish",reason:wG(i),...s?{usage:s}:{},metadata:{model_provider:"anthropic"}};break;case"content_block_start":{const{index:o,content_block:c}=a,u=vG(c,o);r.set(o,{...u}),yield{event:"content-block-start",index:o,content:u};break}case"content_block_delta":{const{index:o,delta:c}=a,u=r.get(o);if(!u)break;const{contentDelta:l,accumulated:d}=SG(u,c);r.set(o,d),yield{event:"content-block-delta",index:o,delta:l};break}case"content_block_stop":{const{index:o}=a,c=r.get(o);if(!c)break;yield{event:"content-block-finish",index:o,content:AG(c)},r.delete(o);break}default:yield{event:"provider",provider:"anthropic",name:a.type,payload:a};break}}function wG(t){switch(t){case"end_turn":case"stop_sequence":return"stop";case"tool_use":return"tool_use";case"max_tokens":return"length";default:return"stop"}}function bG(t){const e=t.cache_creation_input_tokens??0,n=t.cache_read_input_tokens??0,r=t.input_tokens+e+n;return{input_tokens:r,output_tokens:t.output_tokens,total_tokens:r+t.output_tokens,input_token_details:{cache_creation:e,cache_read:n}}}function vG(t,e){switch(t.type){case"text":return{type:"text",text:t.text??"",index:e};case"thinking":return{type:"reasoning",reasoning:t.thinking??"",index:e};case"redacted_thinking":return{type:"non_standard",value:{...t},index:e};case"tool_use":return{type:"tool_call_chunk",id:t.id,name:t.name,args:"",index:e};case"server_tool_use":return{type:"server_tool_call_chunk",id:t.id,name:t.name,args:"",index:e};default:return{type:"non_standard",value:{...t},index:e}}}function SG(t,e){switch(e.type){case"text_delta":return{contentDelta:{type:"text-delta",text:e.text},accumulated:{...t,text:(t.text??"")+e.text}};case"thinking_delta":return{contentDelta:{type:"reasoning-delta",reasoning:e.thinking},accumulated:{...t,reasoning:(t.reasoning??"")+e.thinking}};case"input_json_delta":{const n=(t.args??"")+e.partial_json;return{contentDelta:{type:"block-delta",fields:{type:t.type,args:n}},accumulated:{...t,args:n}}}case"citations_delta":{const n=[...t.annotations??[],e.citation];return{contentDelta:{type:"block-delta",fields:{type:t.type,annotations:n}},accumulated:{...t,annotations:n}}}case"signature_delta":return{contentDelta:{type:"block-delta",fields:{type:t.type,signature:e.signature}},accumulated:{...t,signature:e.signature}};case"compaction_delta":return{contentDelta:{type:"block-delta",fields:{type:"non_standard",value:{...t.value??{},compaction:e}}},accumulated:{...t,value:{...t.value??{},compaction:e}}};default:return{contentDelta:{type:"block-delta",fields:{type:t.type,...e}},accumulated:t}}}function AG(t){if(t.type==="tool_call_chunk"||t.type==="server_tool_call_chunk"){const r=t.type==="tool_call_chunk"?"tool_call":"server_tool_call";let s;try{s=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:r,id:t.id,name:t.name,args:s}}const{index:e,...n}=t;return n}function oe(t,e,n,r,s){if(typeof e=="function"?t!==e||!0:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return e.set(t,n),n}function P(t,e,n,r){if(n==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!r:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return n==="m"?r:n==="a"?r.call(t):r?r.value:e.get(t)}let Y1=function(){const{crypto:t}=globalThis;if(t!=null&&t.randomUUID)return Y1=t.randomUUID.bind(t),t.randomUUID();const e=new Uint8Array(1),n=t?()=>t.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,r=>(+r^n()&15>>+r/4).toString(16))};function qu(t){return typeof t=="object"&&t!==null&&("name"in t&&t.name==="AbortError"||"message"in t&&String(t.message).includes("FetchRequestCanceledException"))}const U_=t=>{if(t instanceof Error)return t;if(typeof t=="object"&&t!==null){try{if(Object.prototype.toString.call(t)==="[object Error]"){const e=new Error(t.message,t.cause?{cause:t.cause}:{});return t.stack&&(e.stack=t.stack),t.cause&&!e.cause&&(e.cause=t.cause),t.name&&(e.name=t.name),e}}catch{}try{return new Error(JSON.stringify(t))}catch{}}return new Error(t)};class ke extends Error{}class Tn extends ke{constructor(e,n,r,s,i){super(`${Tn.makeMessage(e,n,r)}`),this.status=e,this.headers=s,this.requestID=s==null?void 0:s.get("request-id"),this.error=n,this.type=i??null}static makeMessage(e,n,r){const s=n!=null&&n.message?typeof n.message=="string"?n.message:JSON.stringify(n.message):n?JSON.stringify(n):r;return e&&s?`${e} ${s}`:e?`${e} status code (no body)`:s||"(no status code or body)"}static generate(e,n,r,s){var o;if(!e||!s)return new ap({message:r,cause:U_(n)});const i=n,a=(o=i==null?void 0:i.error)==null?void 0:o.type;return e===400?new Q1(e,i,r,s,a):e===401?new e$(e,i,r,s,a):e===403?new t$(e,i,r,s,a):e===404?new n$(e,i,r,s,a):e===409?new r$(e,i,r,s,a):e===422?new s$(e,i,r,s,a):e===429?new i$(e,i,r,s,a):e>=500?new a$(e,i,r,s,a):new Tn(e,i,r,s,a)}}class qr extends Tn{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class ap extends Tn{constructor({message:e,cause:n}){super(void 0,void 0,e||"Connection error.",void 0),n&&(this.cause=n)}}class X1 extends ap{constructor({message:e}={}){super({message:e??"Request timed out."})}}class Q1 extends Tn{}class e$ extends Tn{}class t$ extends Tn{}class n$ extends Tn{}class r$ extends Tn{}class s$ extends Tn{}class i$ extends Tn{}class a$ extends Tn{}const TG=/^[a-z][a-z0-9+.-]*:/i,EG=t=>TG.test(t);let Bn=t=>(Bn=Array.isArray,Bn(t)),gA=Bn;function F_(t){return typeof t!="object"?{}:t??{}}function _A(t){if(!t)return!0;for(const e in t)return!1;return!0}function IG(t,e){return Object.prototype.hasOwnProperty.call(t,e)}const xG=(t,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new ke(`${t} must be an integer`);if(e<0)throw new ke(`${t} must be a positive integer`);return e},o$=t=>{try{return JSON.parse(t)}catch{return}},kG=t=>new Promise(e=>setTimeout(e,t)),di="0.95.2",CG=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function OG(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}const $G=()=>{var n;const t=OG();if(t==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":di,"X-Stainless-OS":wA(Deno.build.os),"X-Stainless-Arch":yA(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:((n=Deno.version)==null?void 0:n.deno)??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":di,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(t==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":di,"X-Stainless-OS":wA(globalThis.process.platform??"unknown"),"X-Stainless-Arch":yA(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};const e=RG();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":di,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":di,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function RG(){if(typeof navigator>"u"||!navigator)return null;const t=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(const{key:e,pattern:n}of t){const r=n.exec(navigator.userAgent);if(r){const s=r[1]||0,i=r[2]||0,a=r[3]||0;return{browser:e,version:`${s}.${i}.${a}`}}}return null}const yA=t=>t==="x32"?"x32":t==="x86_64"||t==="x64"?"x64":t==="arm"?"arm":t==="aarch64"||t==="arm64"?"arm64":t?`other:${t}`:"unknown",wA=t=>(t=t.toLowerCase(),t.includes("ios")?"iOS":t==="android"?"Android":t==="darwin"?"MacOS":t==="win32"?"Windows":t==="freebsd"?"FreeBSD":t==="openbsd"?"OpenBSD":t==="linux"?"Linux":t?`Other:${t}`:"Unknown");let bA;const ub=()=>bA??(bA=$G());function PG(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new Anthropic({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function c$(...t){const e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...t)}function u$(t){let e=Symbol.asyncIterator in t?t[Symbol.asyncIterator]():t[Symbol.iterator]();return c$({start(){},async pull(n){const{done:r,value:s}=await e.next();r?n.close():n.enqueue(s)},async cancel(){var n;await((n=e.return)==null?void 0:n.call(e))}})}function lb(t){if(t[Symbol.asyncIterator])return t;const e=t.getReader();return{async next(){try{const n=await e.read();return n!=null&&n.done&&e.releaseLock(),n}catch(n){throw e.releaseLock(),n}},async return(){const n=e.cancel();return e.releaseLock(),await n,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function NG(t){var r,s;if(t===null||typeof t!="object")return;if(t[Symbol.asyncIterator]){await((s=(r=t[Symbol.asyncIterator]()).return)==null?void 0:s.call(r));return}const e=t.getReader(),n=e.cancel();e.releaseLock(),await n}const MG=({headers:t,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)}),l$="RFC3986",d$=t=>String(t),vA={RFC1738:t=>String(t).replace(/%20/g,"+"),RFC3986:d$},LG="RFC1738";let B_=(t,e)=>(B_=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),B_(t,e));const rs=(()=>{const t=[];for(let e=0;e<256;++e)t.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return t})(),km=1024,jG=(t,e,n,r,s)=>{if(t.length===0)return t;let i=t;if(typeof t=="symbol"?i=Symbol.prototype.toString.call(t):typeof t!="string"&&(i=String(t)),n==="iso-8859-1")return escape(i).replace(/%u[0-9a-f]{4}/gi,function(o){return"%26%23"+parseInt(o.slice(2),16)+"%3B"});let a="";for(let o=0;o<i.length;o+=km){const c=i.length>=km?i.slice(o,o+km):i,u=[];for(let l=0;l<c.length;++l){let d=c.charCodeAt(l);if(d===45||d===46||d===95||d===126||d>=48&&d<=57||d>=65&&d<=90||d>=97&&d<=122||s===LG&&(d===40||d===41)){u[u.length]=c.charAt(l);continue}if(d<128){u[u.length]=rs[d];continue}if(d<2048){u[u.length]=rs[192|d>>6]+rs[128|d&63];continue}if(d<55296||d>=57344){u[u.length]=rs[224|d>>12]+rs[128|d>>6&63]+rs[128|d&63];continue}l+=1,d=65536+((d&1023)<<10|c.charCodeAt(l)&1023),u[u.length]=rs[240|d>>18]+rs[128|d>>12&63]+rs[128|d>>6&63]+rs[128|d&63]}a+=u.join("")}return a};function DG(t){return!t||typeof t!="object"?!1:!!(t.constructor&&t.constructor.isBuffer&&t.constructor.isBuffer(t))}function SA(t,e){if(Bn(t)){const n=[];for(let r=0;r<t.length;r+=1)n.push(e(t[r]));return n}return e(t)}const h$={brackets(t){return String(t)+"[]"},comma:"comma",indices(t,e){return String(t)+"["+e+"]"},repeat(t){return String(t)}},f$=function(t,e){Array.prototype.push.apply(t,Bn(e)?e:[e])};let AA;const Ht={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:jG,encodeValuesOnly:!1,format:l$,formatter:d$,indices:!1,serializeDate(t){return(AA??(AA=Function.prototype.call.bind(Date.prototype.toISOString)))(t)},skipNulls:!1,strictNullHandling:!1};function UG(t){return typeof t=="string"||typeof t=="number"||typeof t=="boolean"||typeof t=="symbol"||typeof t=="bigint"}const Cm={};function p$(t,e,n,r,s,i,a,o,c,u,l,d,f,h,p,g,y,b){let _=t,w=b,v=0,A=!1;for(;(w=w.get(Cm))!==void 0&&!A;){const k=w.get(t);if(v+=1,typeof k<"u"){if(k===v)throw new RangeError("Cyclic object value");A=!0}typeof w.get(Cm)>"u"&&(v=0)}if(typeof u=="function"?_=u(e,_):_ instanceof Date?_=f==null?void 0:f(_):n==="comma"&&Bn(_)&&(_=SA(_,function(k){return k instanceof Date?f==null?void 0:f(k):k})),_===null){if(i)return c&&!g?c(e,Ht.encoder,y,"key",h):e;_=""}if(UG(_)||DG(_)){if(c){const k=g?e:c(e,Ht.encoder,y,"key",h);return[(p==null?void 0:p(k))+"="+(p==null?void 0:p(c(_,Ht.encoder,y,"value",h)))]}return[(p==null?void 0:p(e))+"="+(p==null?void 0:p(String(_)))]}const S=[];if(typeof _>"u")return S;let x;if(n==="comma"&&Bn(_))g&&c&&(_=SA(_,c)),x=[{value:_.length>0?_.join(",")||null:void 0}];else if(Bn(u))x=u;else{const k=Object.keys(_);x=l?k.sort(l):k}const E=o?String(e).replace(/\./g,"%2E"):String(e),$=r&&Bn(_)&&_.length===1?E+"[]":E;if(s&&Bn(_)&&_.length===0)return $+"[]";for(let k=0;k<x.length;++k){const C=x[k],D=typeof C=="object"&&typeof C.value<"u"?C.value:_[C];if(a&&D===null)continue;const B=d&&o?C.replace(/\./g,"%2E"):C,z=Bn(_)?typeof n=="function"?n($,B):$:$+(d?"."+B:"["+B+"]");b.set(t,v);const q=new WeakMap;q.set(Cm,b),f$(S,p$(D,z,n,r,s,i,a,o,n==="comma"&&g&&Bn(_)?null:c,u,l,d,f,h,p,g,y,q))}return S}function FG(t=Ht){if(typeof t.allowEmptyArrays<"u"&&typeof t.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof t.encodeDotInKeys<"u"&&typeof t.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(t.encoder!==null&&typeof t.encoder<"u"&&typeof t.encoder!="function")throw new TypeError("Encoder has to be a function.");const e=t.charset||Ht.charset;if(typeof t.charset<"u"&&t.charset!=="utf-8"&&t.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let n=l$;if(typeof t.format<"u"){if(!B_(vA,t.format))throw new TypeError("Unknown format option provided.");n=t.format}const r=vA[n];let s=Ht.filter;(typeof t.filter=="function"||Bn(t.filter))&&(s=t.filter);let i;if(t.arrayFormat&&t.arrayFormat in h$?i=t.arrayFormat:"indices"in t?i=t.indices?"indices":"repeat":i=Ht.arrayFormat,"commaRoundTrip"in t&&typeof t.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");const a=typeof t.allowDots>"u"?t.encodeDotInKeys?!0:Ht.allowDots:!!t.allowDots;return{addQueryPrefix:typeof t.addQueryPrefix=="boolean"?t.addQueryPrefix:Ht.addQueryPrefix,allowDots:a,allowEmptyArrays:typeof t.allowEmptyArrays=="boolean"?!!t.allowEmptyArrays:Ht.allowEmptyArrays,arrayFormat:i,charset:e,charsetSentinel:typeof t.charsetSentinel=="boolean"?t.charsetSentinel:Ht.charsetSentinel,commaRoundTrip:!!t.commaRoundTrip,delimiter:typeof t.delimiter>"u"?Ht.delimiter:t.delimiter,encode:typeof t.encode=="boolean"?t.encode:Ht.encode,encodeDotInKeys:typeof t.encodeDotInKeys=="boolean"?t.encodeDotInKeys:Ht.encodeDotInKeys,encoder:typeof t.encoder=="function"?t.encoder:Ht.encoder,encodeValuesOnly:typeof t.encodeValuesOnly=="boolean"?t.encodeValuesOnly:Ht.encodeValuesOnly,filter:s,format:n,formatter:r,serializeDate:typeof t.serializeDate=="function"?t.serializeDate:Ht.serializeDate,skipNulls:typeof t.skipNulls=="boolean"?t.skipNulls:Ht.skipNulls,sort:typeof t.sort=="function"?t.sort:null,strictNullHandling:typeof t.strictNullHandling=="boolean"?t.strictNullHandling:Ht.strictNullHandling}}function BG(t,e={}){let n=t;const r=FG(e);let s,i;typeof r.filter=="function"?(i=r.filter,n=i("",n)):Bn(r.filter)&&(i=r.filter,s=i);const a=[];if(typeof n!="object"||n===null)return"";const o=h$[r.arrayFormat],c=o==="comma"&&r.commaRoundTrip;s||(s=Object.keys(n)),r.sort&&s.sort(r.sort);const u=new WeakMap;for(let f=0;f<s.length;++f){const h=s[f];r.skipNulls&&n[h]===null||f$(a,p$(n[h],h,o,c,r.allowEmptyArrays,r.strictNullHandling,r.skipNulls,r.encodeDotInKeys,r.encode?r.encoder:null,r.filter,r.sort,r.allowDots,r.serializeDate,r.format,r.formatter,r.encodeValuesOnly,r.charset,u))}const l=a.join(r.delimiter);let d=r.addQueryPrefix===!0?"?":"";return r.charsetSentinel&&(r.charset==="iso-8859-1"?d+="utf8=%26%2310003%3B&":d+="utf8=%E2%9C%93&"),l.length>0?d+l:""}function zG(t){return BG(t,{arrayFormat:"brackets"})}const HG="urn:ietf:params:oauth:grant-type:jwt-bearer",VG="refresh_token",m$="/v1/oauth/token",lf="oauth-2025-04-20",KG="oidc-federation-2026-04-01",WG=120,db=30,ZG=5,TA=1<<20;function g$(t){if(!t)return;let e;try{e=new URL(t)}catch(r){throw new _t(`Invalid token endpoint base URL "${t}": ${r}`)}if(e.protocol==="https:")return;const n=e.hostname.toLowerCase().replace(/^\[|\]$/g,"");if(!(e.protocol==="http:"&&(n==="localhost"||n==="127.0.0.1"||n==="::1")))throw new _t(`Refusing to send credential over non-https token endpoint "${t}"`)}async function _$(t,e){const n=await GG(t);let r;try{r=JSON.parse(n)}catch{throw new _t(`Token endpoint returned non-JSON response (status ${t.status})`,t.status,Er(n),e)}if(!r.access_token)throw new _t(`Token endpoint response missing access_token: ${JSON.stringify(Er(r))}`,t.status,Er(r),e);if(r.token_type&&r.token_type.toLowerCase()!=="bearer")throw new _t(`Token endpoint response: unsupported token_type "${r.token_type}" (want Bearer)`,t.status,Er(r),e);return r}const Om=2e3,qG=new Set(["error","error_description","error_uri"]);function Er(t){if(t==null)return t;if(typeof t=="string"){let e;try{e=JSON.parse(t)}catch{return t.length<=Om?t:t.slice(0,Om)+`... <${t.length-Om} more chars>`}return JSON.stringify(Er(e))}if(typeof t=="object"&&!Array.isArray(t)){const e={};for(const[n,r]of Object.entries(t))qG.has(n)&&(e[n]=r);return e}return null}async function y$(t,e=n=>console.warn(`anthropic-sdk: ${n}`)){if(typeof process>"u"||process.platform==="win32")return;const n=await Ir(()=>import("./__vite-browser-external-BIHI7g3E.js"),[]);let r=t,s;try{r=await n.promises.realpath(t),s=await n.promises.stat(r)}catch{return}const i=s.mode&511;if(i&18)throw new _t(`Credentials file at ${r} is group/world-writable (mode 0o${i.toString(8)}); this allows other local users to plant tokens. Run \`chmod 600 ${r}\`.`);if(i&36)throw new _t(`Credentials file at ${r} is group/world-readable (mode 0o${i.toString(8)}); run \`chmod 600 ${r}\` before retrying.`);typeof process.getuid=="function"&&s.uid!==process.getuid()&&e(`credentials file at ${r} is owned by uid ${s.uid} (current process uid ${process.getuid()}); verify this is intentional.`)}async function w$(t,e){const n=await Ir(()=>import("./__vite-browser-external-BIHI7g3E.js"),[]),s=(await Ir(()=>import("./__vite-browser-external-BIHI7g3E.js"),[])).dirname(t);await n.promises.mkdir(s,{recursive:!0,mode:448});const i=`${t}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;try{const a=await n.promises.open(i,"w",384);try{await a.writeFile(JSON.stringify(e,null,2)),await a.sync()}finally{await a.close()}await n.promises.rename(i,t)}catch(a){throw await n.promises.unlink(i).catch(()=>{}),a}try{const a=await n.promises.open(s,"r");try{await a.sync()}finally{await a.close()}}catch{}}async function GG(t){if(!t.body)return"";const e=t.body.getReader(),n=[];let r=0;for(;;){const{done:i,value:a}=await e.read();if(i)break;if(r+a.length>TA){const o=TA-r;o>0&&n.push(a.subarray(0,o)),await e.cancel();break}n.push(a),r+=a.length}let s;if(n.length===1)s=n[0];else{s=new Uint8Array(n.reduce((a,o)=>a+o.length,0));let i=0;for(const a of n)s.set(a,i),i+=a.length}return new TextDecoder("utf-8").decode(s)}class _t extends ke{constructor(e,n=null,r=null,s=null){super(e),this.statusCode=n,this.body=r,this.requestId=s}}function ma(){return Math.floor(Date.now()/1e3)}class JG{constructor(e,n){this.cached=null,this.pendingRefresh=null,this.nextForce=!1,this.lastAdvisoryError=0,this.provider=e,this.onAdvisoryRefreshError=n}async getToken(){const e=this.nextForce;this.nextForce=!1;const n=this.cached;if(e||n==null)return(await this.refresh(e)).token;if(n.expiresAt==null)return n.token;const r=n.expiresAt-ma();return r>WG?n.token:r>db?(this.backgroundRefresh(),n.token):(await this.refresh()).token}invalidate(){this.cached=null,this.nextForce=!0}refresh(e=!1){return this.pendingRefresh&&!e?this.pendingRefresh:this.doRefresh(e)}backgroundRefresh(){this.pendingRefresh||ma()-this.lastAdvisoryError<ZG||this.doRefresh().catch(e=>{var n;this.lastAdvisoryError=ma(),(n=this.onAdvisoryRefreshError)==null||n.call(this,e)})}doRefresh(e=!1){return this.pendingRefresh=this.provider(e?{forceRefresh:!0}:void 0).then(n=>(this.cached=n,this.pendingRefresh=null,n),n=>{throw this.pendingRefresh=null,n}),this.pendingRefresh}}var $m={};const it=t=>{var e,n,r,s;if(typeof globalThis.process<"u")return((e=$m==null?void 0:$m[t])==null?void 0:e.trim())||void 0;if(typeof globalThis.Deno<"u")return((s=(r=(n=globalThis.Deno.env)==null?void 0:n.get)==null?void 0:r.call(n,t))==null?void 0:s.trim())||void 0};function YG(t){let e=0;for(const s of t)e+=s.length;const n=new Uint8Array(e);let r=0;for(const s of t)n.set(s,r),r+=s.length;return n}let EA;function hb(t){let e;return(EA??(e=new globalThis.TextEncoder,EA=e.encode.bind(e)))(t)}let IA;function xA(t){let e;return(IA??(e=new globalThis.TextDecoder,IA=e.decode.bind(e)))(t)}const df={off:0,error:200,warn:300,info:400,debug:500},kA=(t,e,n)=>{if(t){if(IG(df,t))return t;Yt(n).warn(`${e} was set to ${JSON.stringify(t)}, expected one of ${JSON.stringify(Object.keys(df))}`)}};function eu(){}function Sd(t,e,n){return!e||df[t]>df[n]?eu:e[t].bind(e)}const XG={error:eu,warn:eu,info:eu,debug:eu};let CA=new WeakMap;function Yt(t){const e=t.logger,n=t.logLevel??"off";if(!e)return XG;const r=CA.get(e);if(r&&r[0]===n)return r[1];const s={error:Sd("error",e,n),warn:Sd("warn",e,n),info:Sd("info",e,n),debug:Sd("debug",e,n)};return CA.set(e,[n,s]),s}const qi=t=>(t.options&&(t.options={...t.options},delete t.options.headers),t.headers&&(t.headers=Object.fromEntries((t.headers instanceof Headers?[...t.headers]:Object.entries(t.headers)).map(([e,n])=>[e,e.toLowerCase()==="authorization"||e.toLowerCase()==="api-key"||e.toLowerCase()==="x-api-key"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":n]))),"retryOfRequestLogID"in t&&(t.retryOfRequestLogID&&(t.retryOf=t.retryOfRequestLogID),delete t.retryOfRequestLogID),t),b$="1.0",QG=/^[A-Za-z0-9_.-]+$/;function v$(t){if(!t)throw new Error("profile name is empty");if(t==="."||t==="..")throw new Error(`profile name "${t}" is not allowed`);if(t.includes("/")||t.includes("\\"))throw new Error(`profile name "${t}" must not contain path separators`);if(!QG.test(t))throw new Error(`profile name "${t}" contains disallowed characters (allowed: letters, digits, '_', '.', '-')`)}const e7=async t=>{var e,n;const r=await fb();if(r===null)return null;const s=t??await S$();if(s===null)return null;v$(s);const i=await Ir(()=>import("./__vite-browser-external-BIHI7g3E.js"),[]),o=(await Ir(()=>import("./__vite-browser-external-BIHI7g3E.js"),[])).join(r,"configs",`${s}.json`);let c;try{c=await i.promises.readFile(o,"utf-8")}catch(d){if((d==null?void 0:d.code)!=="ENOENT")throw new Error(`failed to read config file ${o}: ${d}`);c=null}if(c===null){const d=it("ANTHROPIC_ORGANIZATION_ID"),f=it("ANTHROPIC_IDENTITY_TOKEN_FILE"),h=it("ANTHROPIC_FEDERATION_RULE_ID");return h&&d?{fromFile:!1,config:{organization_id:d,workspace_id:it("ANTHROPIC_WORKSPACE_ID"),base_url:it("ANTHROPIC_BASE_URL"),authentication:{type:"oidc_federation",federation_rule_id:h,service_account_id:it("ANTHROPIC_SERVICE_ACCOUNT_ID"),identity_token:f?{source:"file",path:f}:void 0,scope:it("ANTHROPIC_SCOPE")}}}:null}let u;try{u=JSON.parse(c)}catch(d){throw new Error(`failed to parse config file ${o}: ${d}`)}if(!u.authentication)throw new Error(`config file ${o} is missing "authentication"`);const l=u.authentication.type;if(l!=="oidc_federation"&&l!=="user_oauth")throw new Error(`authentication.type "${l}" is not a known authentication type`);if(u.organization_id??(u.organization_id=it("ANTHROPIC_ORGANIZATION_ID")),u.workspace_id??(u.workspace_id=it("ANTHROPIC_WORKSPACE_ID")),u.base_url??(u.base_url=it("ANTHROPIC_BASE_URL")),(e=u.authentication).scope??(e.scope=it("ANTHROPIC_SCOPE")),u.authentication.type==="oidc_federation"){if(!u.authentication.identity_token){const d=it("ANTHROPIC_IDENTITY_TOKEN_FILE");d&&(u.authentication.identity_token={source:"file",path:d})}u.authentication.federation_rule_id||(u.authentication.federation_rule_id=it("ANTHROPIC_FEDERATION_RULE_ID")??""),(n=u.authentication).service_account_id??(n.service_account_id=it("ANTHROPIC_SERVICE_ACCOUNT_ID"))}return{config:u,fromFile:!0}},t7=async(t,e)=>{if(t!=null&&t.authentication.credentials_path)return t.authentication.credentials_path;const n=await fb();if(!n)return null;const r=e??await S$();return r?(v$(r),(await Ir(()=>import("./__vite-browser-external-BIHI7g3E.js"),[])).join(n,"credentials",`${r}.json`)):null},fb=async()=>{if(!n7())return null;const t=await Ir(()=>import("./__vite-browser-external-BIHI7g3E.js"),[]),e=it("ANTHROPIC_CONFIG_DIR");if(e)return e;if(ub()["X-Stainless-OS"]==="Windows"){const i=it("APPDATA");if(i)return t.join(i,"Anthropic");const a=it("USERPROFILE");return a?t.join(a,"AppData","Roaming","Anthropic"):null}const r=it("XDG_CONFIG_HOME");if(r)return t.join(r,"anthropic");const s=it("HOME");return s?t.join(s,".config","anthropic"):null},n7=()=>{const t=ub()["X-Stainless-Runtime"];return t==="node"||t==="deno"},S$=async()=>{const t=await fb();if(!t)return null;const e=it("ANTHROPIC_PROFILE");if(e)return e;const n=await Ir(()=>import("./__vite-browser-external-BIHI7g3E.js"),[]),s=(await Ir(()=>import("./__vite-browser-external-BIHI7g3E.js"),[])).join(t,"active_config");try{return(await n.promises.readFile(s,"utf-8")).trim()||"default"}catch(i){if((i==null?void 0:i.code)!=="ENOENT")throw new Error(`failed to read ${s}: ${i}`);return"default"}};function OA(t){if(!t)throw new ke("Identity token file path is empty");return async()=>{const e=await Ir(()=>import("./__vite-browser-external-BIHI7g3E.js"),[]);let n;try{n=await e.promises.readFile(t,"utf-8")}catch(s){throw new ke(`Failed to read identity token file at ${t}: ${s}`)}const r=n.trim();if(!r)throw new ke(`Identity token file at ${t} is empty`);return r}}function r7(t){if(!t)throw new ke("Identity token value is empty");return()=>t}function s7(t){return async()=>{g$(t.baseURL);const e=await t.identityTokenProvider();if(e.length>16*1024)throw new _t(`Identity token is ${Math.ceil(e.length/1024)} KiB, exceeds the 16 KiB assertion limit`);const n={grant_type:HG,assertion:e,federation_rule_id:t.federationRuleId,organization_id:t.organizationId};t.serviceAccountId&&(n.service_account_id=t.serviceAccountId),t.workspaceId&&(n.workspace_id=t.workspaceId);const r=`${t.baseURL}${m$}`;let s;try{s=await t.fetch(r,{method:"POST",headers:{"Content-Type":"application/json","anthropic-beta":`${lf},${KG}`,"User-Agent":t.userAgent||`anthropic-sdk-typescript/${di} oidcFederationProvider`},body:JSON.stringify(n)})}catch(c){throw new _t(`Failed to reach token endpoint ${r}: ${c}`)}const i=s.headers.get("Request-Id");if(!s.ok){const c=await s.text().catch(()=>""),u=Er(c);let l="";throw s.status===401&&(l=` Ensure your federation rule matches your identity token. ${t.workspaceId?"":"If your federation rule is scoped to multiple workspaces, set the ANTHROPIC_WORKSPACE_ID environment variable, the 'workspace_id' config key, or the `workspaceId` option. "}View your authentication events in the Workload identity page of Claude Console for more details.`),new _t(`Token exchange failed with status ${s.status}${i?` (request-id ${i})`:""}: ${u}${l}`,s.status,u,i)}const a=await _$(s,i),o=Number(a.expires_in);if(!Number.isFinite(o))throw new _t(`Token endpoint response missing required fields: ${JSON.stringify(Er(a))}`,s.status,Er(a),i);return{token:a.access_token,expiresAt:ma()+o}}}function i7(t){return async e=>{const n=await Ir(()=>import("./__vite-browser-external-BIHI7g3E.js"),[]);await y$(t.credentialsPath,t.onSafetyWarning);let r;try{r=await n.promises.readFile(t.credentialsPath,"utf-8")}catch(y){throw new _t(`Credentials file not found at ${t.credentialsPath}: ${y}`)}let s;try{s=JSON.parse(r)}catch(y){throw new _t(`Credentials file at ${t.credentialsPath} is not valid JSON: ${y}`)}const i=s.access_token;if(!i)throw new _t(`Credentials file at ${t.credentialsPath} must include 'access_token'`);const a=s.expires_at;if(!(e!=null&&e.forceRefresh)&&(a==null||ma()<a-db))return{token:i,expiresAt:a??null};const o=s.refresh_token;if(!t.clientId||!o)throw new _t(`Access token at ${t.credentialsPath} has expired and no refresh is available (client_id ${t.clientId?"set":"empty"}, refresh_token ${o?"set":"empty"})`);g$(t.baseURL);const c={grant_type:VG,refresh_token:o,client_id:t.clientId},u=`${t.baseURL}${m$}`;let l;try{l=await t.fetch(u,{method:"POST",headers:{"Content-Type":"application/json","anthropic-beta":lf,"User-Agent":t.userAgent||`anthropic-sdk-typescript/${di} userOAuthProvider`},body:JSON.stringify(c)})}catch(y){throw new _t(`User OAuth refresh failed to reach token endpoint: ${y}`)}const d=l.headers.get("Request-Id");if(!l.ok){const y=await l.text().catch(()=>"");throw new _t(`User OAuth refresh failed (HTTP ${l.status}): ${Er(y)}`,l.status,Er(y),d)}const f=await _$(l,d),h=Number(f.expires_in);if(!Number.isFinite(h))throw new _t(`User OAuth refresh response missing or invalid expires_in: ${JSON.stringify(Er(f))}`,l.status,Er(f),d);const p=ma()+h,g=f.refresh_token||o;return await w$(t.credentialsPath,{...s,version:b$,type:"oauth_token",access_token:f.access_token,expires_at:p,refresh_token:g}),{token:f.access_token,expiresAt:p}}}function A$(t,e){const n=t.authentication.credentials_path??null,r=(t.base_url||e.baseURL).replace(/\/+$/,""),s=o7(t,n,r,e),i={};return t.workspace_id&&t.authentication.type==="user_oauth"&&(i["anthropic-workspace-id"]=t.workspace_id),{provider:s,extraHeaders:i,baseURL:t.base_url||void 0}}async function a7(t,e){const n=await e7(e);if(!n)return null;const{config:r,fromFile:s}=n,i=r.authentication.credentials_path||!s?r:{...r,authentication:{...r.authentication,credentials_path:await t7(r,e)??void 0}};return A$(i,t)}function o7(t,e,n,r){switch(t.authentication.type){case"oidc_federation":{const s=t.authentication,i=c7(s);if(!i)throw new _t("oidc_federation config requires an identity token (set authentication.identity_token, ANTHROPIC_IDENTITY_TOKEN_FILE, or ANTHROPIC_IDENTITY_TOKEN)");if(!s.federation_rule_id)throw new _t("oidc_federation config requires 'federation_rule_id'. Set it in authentication.federation_rule_id in your profile, or via ANTHROPIC_FEDERATION_RULE_ID (profile takes precedence).");if(!t.organization_id)throw new _t("oidc_federation config requires organization_id (set ANTHROPIC_ORGANIZATION_ID or config.organization_id)");const a=s7({identityTokenProvider:i,federationRuleId:s.federation_rule_id,organizationId:t.organization_id,serviceAccountId:s.service_account_id,workspaceId:t.workspace_id,baseURL:n,fetch:r.fetch,userAgent:r.userAgent});return e?u7(a,e,r.onCacheWriteError,r.onSafetyWarning):a}case"user_oauth":{if(!e)throw new _t("user_oauth config requires authentication.credentials_path (or load via a profile so it defaults to <config_dir>/credentials/<profile>.json)");return i7({credentialsPath:e,clientId:t.authentication.client_id,baseURL:n,fetch:r.fetch,userAgent:r.userAgent,onSafetyWarning:r.onSafetyWarning})}default:{const s=t.authentication.type;throw new _t(`authentication.type "${s}" is not a known authentication type`)}}}function c7(t){if(t.identity_token){const r=t.identity_token.source;if(r!=="file")throw new _t(`identity_token.source "${r}" is not supported by this SDK version (only "file")`);if(!t.identity_token.path)throw new _t('identity_token.source "file" requires a non-empty path');return OA(t.identity_token.path)}const e=it("ANTHROPIC_IDENTITY_TOKEN_FILE");if(e)return OA(e);const n=it("ANTHROPIC_IDENTITY_TOKEN");return n?r7(n):null}function u7(t,e,n,r){return async s=>{const i=await Ir(()=>import("./__vite-browser-external-BIHI7g3E.js"),[]);await y$(e,r);let a;try{const c=await i.promises.readFile(e,"utf-8");a=JSON.parse(c);const u=a==null?void 0:a.access_token;if(u&&!(s!=null&&s.forceRefresh)){const l=a==null?void 0:a.expires_at;if(l==null||ma()<l-db)return{token:u,expiresAt:l??null}}}catch(c){(c==null?void 0:c.code)!=="ENOENT"&&!(c instanceof SyntaxError)&&(n==null||n(c))}const o=await t(s);try{await w$(e,{...a??{},version:b$,type:"oauth_token",access_token:o.token,expires_at:o.expiresAt})}catch(c){n==null||n(c)}return o}}var Xn,Qn;class Ml{constructor(){Xn.set(this,void 0),Qn.set(this,void 0),oe(this,Xn,new Uint8Array),oe(this,Qn,null)}decode(e){if(e==null)return[];const n=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?hb(e):e;oe(this,Xn,YG([P(this,Xn,"f"),n]));const r=[];let s;for(;(s=l7(P(this,Xn,"f"),P(this,Qn,"f")))!=null;){if(s.carriage&&P(this,Qn,"f")==null){oe(this,Qn,s.index);continue}if(P(this,Qn,"f")!=null&&(s.index!==P(this,Qn,"f")+1||s.carriage)){r.push(xA(P(this,Xn,"f").subarray(0,P(this,Qn,"f")-1))),oe(this,Xn,P(this,Xn,"f").subarray(P(this,Qn,"f"))),oe(this,Qn,null);continue}const i=P(this,Qn,"f")!==null?s.preceding-1:s.preceding,a=xA(P(this,Xn,"f").subarray(0,i));r.push(a),oe(this,Xn,P(this,Xn,"f").subarray(s.index)),oe(this,Qn,null)}return r}flush(){return P(this,Xn,"f").length?this.decode(`
|
|
574
|
-
`):[]}}Xn=new WeakMap,Qn=new WeakMap;Ml.NEWLINE_CHARS=new Set([`
|
|
575
|
-
`,"\r"]);Ml.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function l7(t,e){for(let s=e??0;s<t.length;s++){if(t[s]===10)return{preceding:s,index:s+1,carriage:!1};if(t[s]===13)return{preceding:s,index:s+1,carriage:!0}}return null}function d7(t){for(let r=0;r<t.length-1;r++){if(t[r]===10&&t[r+1]===10||t[r]===13&&t[r+1]===13)return r+2;if(t[r]===13&&t[r+1]===10&&r+3<t.length&&t[r+2]===13&&t[r+3]===10)return r+4}return-1}var yc;class gs{constructor(e,n,r){this.iterator=e,yc.set(this,void 0),this.controller=n,oe(this,yc,r)}static fromSSEResponse(e,n,r){let s=!1;const i=r?Yt(r):console;async function*a(){var c;if(s)throw new ke("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let o=!1;try{for await(const u of h7(e,n)){if(u.event==="completion")try{yield JSON.parse(u.data)}catch(l){throw i.error("Could not parse message into JSON:",u.data),i.error("From chunk:",u.raw),l}if(u.event==="message_start"||u.event==="message_delta"||u.event==="message_stop"||u.event==="content_block_start"||u.event==="content_block_delta"||u.event==="content_block_stop"||u.event==="message"||u.event==="user.message"||u.event==="user.interrupt"||u.event==="user.tool_confirmation"||u.event==="user.custom_tool_result"||u.event==="agent.message"||u.event==="agent.thinking"||u.event==="agent.tool_use"||u.event==="agent.tool_result"||u.event==="agent.mcp_tool_use"||u.event==="agent.mcp_tool_result"||u.event==="agent.custom_tool_use"||u.event==="agent.thread_context_compacted"||u.event==="session.status_running"||u.event==="session.status_idle"||u.event==="session.status_rescheduled"||u.event==="session.status_terminated"||u.event==="session.error"||u.event==="session.deleted"||u.event==="span.model_request_start"||u.event==="span.model_request_end"||u.event==="span.outcome_evaluation_start"||u.event==="span.outcome_evaluation_ongoing"||u.event==="span.outcome_evaluation_end"||u.event==="user.define_outcome"||u.event==="agent.thread_message_received"||u.event==="agent.thread_message_sent"||u.event==="agent.session_thread_message_received"||u.event==="agent.session_thread_message_sent"||u.event==="session.thread_created"||u.event==="session.thread_status_created"||u.event==="session.thread_status_running"||u.event==="session.thread_status_idle"||u.event==="session.thread_status_rescheduled"||u.event==="session.thread_status_terminated")try{yield JSON.parse(u.data)}catch(l){throw i.error("Could not parse message into JSON:",u.data),i.error("From chunk:",u.raw),l}if(u.event!=="ping"&&u.event==="error"){const l=o$(u.data)??u.data,d=(c=l==null?void 0:l.error)==null?void 0:c.type;throw new Tn(void 0,l,void 0,e.headers,d)}}o=!0}catch(u){if(qu(u))return;throw u}finally{o||n.abort()}}return new gs(a,n,r)}static fromReadableStream(e,n,r){let s=!1;async function*i(){const o=new Ml,c=lb(e);for await(const u of c)for(const l of o.decode(u))yield l;for(const u of o.flush())yield u}async function*a(){if(s)throw new ke("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let o=!1;try{for await(const c of i())o||c&&(yield JSON.parse(c));o=!0}catch(c){if(qu(c))return;throw c}finally{o||n.abort()}}return new gs(a,n,r)}[(yc=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){const e=[],n=[],r=this.iterator(),s=i=>({next:()=>{if(i.length===0){const a=r.next();e.push(a),n.push(a)}return i.shift()}});return[new gs(()=>s(e),this.controller,P(this,yc,"f")),new gs(()=>s(n),this.controller,P(this,yc,"f"))]}toReadableStream(){const e=this;let n;return c$({async start(){n=e[Symbol.asyncIterator]()},async pull(r){try{const{value:s,done:i}=await n.next();if(i)return r.close();const a=hb(JSON.stringify(s)+`
|
|
576
|
-
`);r.enqueue(a)}catch(s){r.error(s)}},async cancel(){var r;await((r=n.return)==null?void 0:r.call(n))}})}}async function*h7(t,e){if(!t.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new ke("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new ke("Attempted to iterate over a response with no body");const n=new p7,r=new Ml,s=lb(t.body);for await(const i of f7(s))for(const a of r.decode(i)){const o=n.decode(a);o&&(yield o)}for(const i of r.flush()){const a=n.decode(i);a&&(yield a)}}async function*f7(t){let e=new Uint8Array;for await(const n of t){if(n==null)continue;const r=n instanceof ArrayBuffer?new Uint8Array(n):typeof n=="string"?hb(n):n;let s=new Uint8Array(e.length+r.length);s.set(e),s.set(r,e.length),e=s;let i;for(;(i=d7(e))!==-1;)yield e.slice(0,i),e=e.slice(i)}e.length>0&&(yield e)}class p7{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;const i={event:this.event,data:this.data.join(`
|
|
577
|
-
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],i}if(this.chunks.push(e),e.startsWith(":"))return null;let[n,r,s]=m7(e,":");return s.startsWith(" ")&&(s=s.substring(1)),n==="event"?this.event=s:n==="data"&&this.data.push(s),null}}function m7(t,e){const n=t.indexOf(e);return n!==-1?[t.substring(0,n),e,t.substring(n+e.length)]:[t,"",""]}async function T$(t,e){const{response:n,requestLogID:r,retryOfRequestLogID:s,startTime:i}=e,a=await(async()=>{var d;if(e.options.stream)return Yt(t).debug("response",n.status,n.url,n.headers,n.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(n,e.controller):gs.fromSSEResponse(n,e.controller);if(n.status===204)return null;if(e.options.__binaryResponse)return n;const o=n.headers.get("content-type"),c=(d=o==null?void 0:o.split(";")[0])==null?void 0:d.trim();if((c==null?void 0:c.includes("application/json"))||(c==null?void 0:c.endsWith("+json"))){if(n.headers.get("content-length")==="0")return;const h=await n.json();return E$(h,n)}return await n.text()})();return Yt(t).debug(`[${r}] response parsed`,qi({retryOfRequestLogID:s,url:n.url,status:n.status,body:a,durationMs:Date.now()-i})),a}function E$(t,e){return!t||typeof t!="object"||Array.isArray(t)?t:Object.defineProperty(t,"_request_id",{value:e.headers.get("request-id"),enumerable:!1})}var tu;class op extends Promise{constructor(e,n,r=T$){super(s=>{s(null)}),this.responsePromise=n,this.parseResponse=r,tu.set(this,void 0),oe(this,tu,e)}_thenUnwrap(e){return new op(P(this,tu,"f"),this.responsePromise,async(n,r)=>E$(e(await this.parseResponse(n,r),r),r.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){const[e,n]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:n,request_id:n.headers.get("request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(P(this,tu,"f"),e))),this.parsedPromise}then(e,n){return this.parse().then(e,n)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}}tu=new WeakMap;var Ad;class I${constructor(e,n,r,s){Ad.set(this,void 0),oe(this,Ad,e),this.options=s,this.response=n,this.body=r}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){const e=this.nextPageRequestOptions();if(!e)throw new ke("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await P(this,Ad,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(Ad=new WeakMap,Symbol.asyncIterator)](){for await(const e of this.iterPages())for(const n of e.getPaginatedItems())yield n}}class g7 extends op{constructor(e,n,r){super(e,n,async(s,i)=>new r(s,i.response,await T$(s,i),i.options))}async*[Symbol.asyncIterator](){const e=await this;for await(const n of e)yield n}}class Ll extends I${constructor(e,n,r,s){super(e,n,r,s),this.data=r.data||[],this.has_more=r.has_more||!1,this.first_id=r.first_id||null,this.last_id=r.last_id||null}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){var n;if((n=this.options.query)!=null&&n.before_id){const r=this.first_id;return r?{...this.options,query:{...F_(this.options.query),before_id:r}}:null}const e=this.last_id;return e?{...this.options,query:{...F_(this.options.query),after_id:e}}:null}}class En extends I${constructor(e,n,r,s){super(e,n,r,s),this.data=r.data||[],this.next_page=r.next_page||null}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){const e=this.next_page;return e?{...this.options,query:{...F_(this.options.query),page:e}}:null}}const x$=()=>{var t;if(typeof File>"u"){const{process:e}=globalThis,n=typeof((t=e==null?void 0:e.versions)==null?void 0:t.node)=="string"&&parseInt(e.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(n?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function _o(t,e,n){return x$(),new File(t,e??"unknown_file",n)}function fh(t,e){const n=typeof t=="object"&&t!==null&&("name"in t&&t.name&&String(t.name)||"url"in t&&t.url&&String(t.url)||"filename"in t&&t.filename&&String(t.filename)||"path"in t&&t.path&&String(t.path))||"";return e?n.split(/[\\/]/).pop()||void 0:n}const k$=t=>t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function",pb=async(t,e,n=!0)=>({...t,body:await y7(t.body,e,n)}),$A=new WeakMap;function _7(t){const e=typeof t=="function"?t:t.fetch,n=$A.get(e);if(n)return n;const r=(async()=>{try{const s="Response"in e?e.Response:(await e("data:,")).constructor,i=new FormData;return i.toString()!==await new s(i).text()}catch{return!0}})();return $A.set(e,r),r}const y7=async(t,e,n=!0)=>{if(!await _7(e))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");const r=new FormData;return await Promise.all(Object.entries(t||{}).map(([s,i])=>z_(r,s,i,n))),r},w7=t=>t instanceof Blob&&"name"in t,z_=async(t,e,n,r)=>{if(n!==void 0){if(n==null)throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")t.append(e,String(n));else if(n instanceof Response){let s={};const i=n.headers.get("Content-Type");i&&(s={type:i}),t.append(e,_o([await n.blob()],fh(n,r),s))}else if(k$(n))t.append(e,_o([await new Response(u$(n)).blob()],fh(n,r)));else if(w7(n))t.append(e,_o([n],fh(n,r),{type:n.type}));else if(Array.isArray(n))await Promise.all(n.map(s=>z_(t,e+"[]",s,r)));else if(typeof n=="object")await Promise.all(Object.entries(n).map(([s,i])=>z_(t,`${e}[${s}]`,i,r)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${n} instead`)}},C$=t=>t!=null&&typeof t=="object"&&typeof t.size=="number"&&typeof t.type=="string"&&typeof t.text=="function"&&typeof t.slice=="function"&&typeof t.arrayBuffer=="function",b7=t=>t!=null&&typeof t=="object"&&typeof t.name=="string"&&typeof t.lastModified=="number"&&C$(t),v7=t=>t!=null&&typeof t=="object"&&typeof t.url=="string"&&typeof t.blob=="function";async function S7(t,e,n){if(x$(),t=await t,e||(e=fh(t,!0)),b7(t))return t instanceof File&&e==null&&n==null?t:_o([await t.arrayBuffer()],e??t.name,{type:t.type,lastModified:t.lastModified,...n});if(v7(t)){const s=await t.blob();return e||(e=new URL(t.url).pathname.split(/[\\/]/).pop()),_o(await H_(s),e,n)}const r=await H_(t);if(!(n!=null&&n.type)){const s=r.find(i=>typeof i=="object"&&"type"in i&&i.type);typeof s=="string"&&(n={...n,type:s})}return _o(r,e,n)}async function H_(t){var n;let e=[];if(typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer)e.push(t);else if(C$(t))e.push(t instanceof Blob?t:await t.arrayBuffer());else if(k$(t))for await(const r of t)e.push(...await H_(r));else{const r=(n=t==null?void 0:t.constructor)==null?void 0:n.name;throw new Error(`Unexpected data type: ${typeof t}${r?`; constructor: ${r}`:""}${A7(t)}`)}return e}function A7(t){return typeof t!="object"||t===null?"":`; props: [${Object.getOwnPropertyNames(t).map(n=>`"${n}"`).join(", ")}]`}class gt{constructor(e){this._client=e}}const O$=Symbol.for("brand.privateNullableHeaders");function*T7(t){if(!t)return;if(O$ in t){const{values:r,nulls:s}=t;yield*r.entries();for(const i of s)yield[i,null];return}let e=!1,n;t instanceof Headers?n=t.entries():gA(t)?n=t:(e=!0,n=Object.entries(t??{}));for(let r of n){const s=r[0];if(typeof s!="string")throw new TypeError("expected header name to be a string");const i=gA(r[1])?r[1]:[r[1]];let a=!1;for(const o of i)o!==void 0&&(e&&!a&&(a=!0,yield[s,null]),yield[s,o])}}const K=t=>{const e=new Headers,n=new Set;for(const r of t){const s=new Set;for(const[i,a]of T7(r)){const o=i.toLowerCase();s.has(o)||(e.delete(i),s.add(o)),a===null?(e.delete(i),n.add(o)):(e.append(i,a),n.delete(o))}}return{[O$]:!0,values:e,nulls:n}};function $$(t){return t.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}const RA=Object.freeze(Object.create(null)),E7=(t=$$)=>function(n,...r){if(n.length===1)return n[0];let s=!1;const i=[],a=n.reduce((l,d,f)=>{var g;/[?#]/.test(d)&&(s=!0);const h=r[f];let p=(s?encodeURIComponent:t)(""+h);return f!==r.length&&(h==null||typeof h=="object"&&h.toString===((g=Object.getPrototypeOf(Object.getPrototypeOf(h.hasOwnProperty??RA)??RA))==null?void 0:g.toString))&&(p=h+"",i.push({start:l.length+d.length,length:p.length,error:`Value of type ${Object.prototype.toString.call(h).slice(8,-1)} is not a valid path parameter`})),l+d+(f===r.length?"":p)},""),o=a.split(/[?#]/,1)[0],c=new RegExp("(?<=^|\\/)(?:\\.|%2e){1,2}(?=\\/|$)","gi");let u;for(;(u=c.exec(o))!==null;)i.push({start:u.index,length:u[0].length,error:`Value "${u[0]}" can't be safely passed as a path parameter`});if(i.sort((l,d)=>l.start-d.start),i.length>0){let l=0;const d=i.reduce((f,h)=>{const p=" ".repeat(h.start-l),g="^".repeat(h.length);return l=h.start+h.length,f+p+g},"");throw new ke(`Path parameters result in path with invalid segments:
|
|
578
|
-
${i.map(f=>f.error).join(`
|
|
579
|
-
`)}
|
|
580
|
-
${a}
|
|
581
|
-
${d}`)}return a},le=E7($$);class R$ extends gt{create(e,n){const{betas:r,...s}=e;return this._client.post("/v1/environments?beta=true",{body:s,...n,headers:K([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},n==null?void 0:n.headers])})}retrieve(e,n={},r){const{betas:s}=n??{};return this._client.get(le`/v1/environments/${e}?beta=true`,{...r,headers:K([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r==null?void 0:r.headers])})}update(e,n,r){const{betas:s,...i}=n;return this._client.post(le`/v1/environments/${e}?beta=true`,{body:i,...r,headers:K([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r==null?void 0:r.headers])})}list(e={},n){const{betas:r,...s}=e??{};return this._client.getAPIList("/v1/environments?beta=true",En,{query:s,...n,headers:K([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},n==null?void 0:n.headers])})}delete(e,n={},r){const{betas:s}=n??{};return this._client.delete(le`/v1/environments/${e}?beta=true`,{...r,headers:K([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r==null?void 0:r.headers])})}archive(e,n={},r){const{betas:s}=n??{};return this._client.post(le`/v1/environments/${e}/archive?beta=true`,{...r,headers:K([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r==null?void 0:r.headers])})}}const wu=Symbol("anthropic.sdk.stainlessHelper");function ph(t){return typeof t=="object"&&t!==null&&wu in t}function P$(t,e){const n=new Set;if(t)for(const r of t)ph(r)&&n.add(r[wu]);if(e){for(const r of e)if(ph(r)&&n.add(r[wu]),Array.isArray(r.content))for(const s of r.content)ph(s)&&n.add(s[wu])}return Array.from(n)}function N$(t,e){const n=P$(t,e);return n.length===0?{}:{"x-stainless-helper":n.join(", ")}}function I7(t){return ph(t)?{"x-stainless-helper":t[wu]}:{}}class M$ extends gt{list(e={},n){const{betas:r,...s}=e??{};return this._client.getAPIList("/v1/files?beta=true",Ll,{query:s,...n,headers:K([{"anthropic-beta":[...r??[],"files-api-2025-04-14"].toString()},n==null?void 0:n.headers])})}delete(e,n={},r){const{betas:s}=n??{};return this._client.delete(le`/v1/files/${e}?beta=true`,{...r,headers:K([{"anthropic-beta":[...s??[],"files-api-2025-04-14"].toString()},r==null?void 0:r.headers])})}download(e,n={},r){const{betas:s}=n??{};return this._client.get(le`/v1/files/${e}/content?beta=true`,{...r,headers:K([{"anthropic-beta":[...s??[],"files-api-2025-04-14"].toString(),Accept:"application/binary"},r==null?void 0:r.headers]),__binaryResponse:!0})}retrieveMetadata(e,n={},r){const{betas:s}=n??{};return this._client.get(le`/v1/files/${e}?beta=true`,{...r,headers:K([{"anthropic-beta":[...s??[],"files-api-2025-04-14"].toString()},r==null?void 0:r.headers])})}upload(e,n){const{betas:r,...s}=e;return this._client.post("/v1/files?beta=true",pb({body:s,...n,headers:K([{"anthropic-beta":[...r??[],"files-api-2025-04-14"].toString()},I7(s.file),n==null?void 0:n.headers])},this._client))}}let L$=class extends gt{retrieve(e,n={},r){const{betas:s}=n??{};return this._client.get(le`/v1/models/${e}?beta=true`,{...r,headers:K([{...(s==null?void 0:s.toString())!=null?{"anthropic-beta":s==null?void 0:s.toString()}:void 0},r==null?void 0:r.headers])})}list(e={},n){const{betas:r,...s}=e??{};return this._client.getAPIList("/v1/models?beta=true",Ll,{query:s,...n,headers:K([{...(r==null?void 0:r.toString())!=null?{"anthropic-beta":r==null?void 0:r.toString()}:void 0},n==null?void 0:n.headers])})}};class j$ extends gt{create(e,n){const{betas:r,...s}=e;return this._client.post("/v1/user_profiles?beta=true",{body:s,...n,headers:K([{"anthropic-beta":[...r??[],"user-profiles-2026-03-24"].toString()},n==null?void 0:n.headers])})}retrieve(e,n={},r){const{betas:s}=n??{};return this._client.get(le`/v1/user_profiles/${e}?beta=true`,{...r,headers:K([{"anthropic-beta":[...s??[],"user-profiles-2026-03-24"].toString()},r==null?void 0:r.headers])})}update(e,n,r){const{betas:s,...i}=n;return this._client.post(le`/v1/user_profiles/${e}?beta=true`,{body:i,...r,headers:K([{"anthropic-beta":[...s??[],"user-profiles-2026-03-24"].toString()},r==null?void 0:r.headers])})}list(e={},n){const{betas:r,...s}=e??{};return this._client.getAPIList("/v1/user_profiles?beta=true",En,{query:s,...n,headers:K([{"anthropic-beta":[...r??[],"user-profiles-2026-03-24"].toString()},n==null?void 0:n.headers])})}createEnrollmentURL(e,n={},r){const{betas:s}=n??{};return this._client.post(le`/v1/user_profiles/${e}/enrollment_url?beta=true`,{...r,headers:K([{"anthropic-beta":[...s??[],"user-profiles-2026-03-24"].toString()},r==null?void 0:r.headers])})}}var Gu={},cp={};Object.defineProperty(cp,"__esModule",{value:!0});cp.timingSafeEqual=void 0;function PA(t,e=""){if(!t)throw new Error(e)}function x7(t,e){if(t.byteLength!==e.byteLength)return!1;t instanceof DataView||(t=new DataView(ArrayBuffer.isView(t)?t.buffer:t)),e instanceof DataView||(e=new DataView(ArrayBuffer.isView(e)?e.buffer:e)),PA(t instanceof DataView),PA(e instanceof DataView);const n=t.byteLength;let r=0,s=-1;for(;++s<n;)r|=t.getUint8(s)^e.getUint8(s);return r===0}cp.timingSafeEqual=x7;var Qr={},k7=Zm&&Zm.__extends||function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,s){r.__proto__=s}||function(r,s){for(var i in s)s.hasOwnProperty(i)&&(r[i]=s[i])},t(e,n)};return function(e,n){t(e,n);function r(){this.constructor=e}e.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}}();Object.defineProperty(Qr,"__esModule",{value:!0});var Rt=256,mb=function(){function t(e){e===void 0&&(e="="),this._paddingCharacter=e}return t.prototype.encodedLength=function(e){return this._paddingCharacter?(e+2)/3*4|0:(e*8+5)/6|0},t.prototype.encode=function(e){for(var n="",r=0;r<e.length-2;r+=3){var s=e[r]<<16|e[r+1]<<8|e[r+2];n+=this._encodeByte(s>>>3*6&63),n+=this._encodeByte(s>>>2*6&63),n+=this._encodeByte(s>>>1*6&63),n+=this._encodeByte(s>>>0*6&63)}var i=e.length-r;if(i>0){var s=e[r]<<16|(i===2?e[r+1]<<8:0);n+=this._encodeByte(s>>>3*6&63),n+=this._encodeByte(s>>>2*6&63),i===2?n+=this._encodeByte(s>>>1*6&63):n+=this._paddingCharacter||"",n+=this._paddingCharacter||""}return n},t.prototype.maxDecodedLength=function(e){return this._paddingCharacter?e/4*3|0:(e*6+7)/8|0},t.prototype.decodedLength=function(e){return this.maxDecodedLength(e.length-this._getPaddingLength(e))},t.prototype.decode=function(e){if(e.length===0)return new Uint8Array(0);for(var n=this._getPaddingLength(e),r=e.length-n,s=new Uint8Array(this.maxDecodedLength(r)),i=0,a=0,o=0,c=0,u=0,l=0,d=0;a<r-4;a+=4)c=this._decodeChar(e.charCodeAt(a+0)),u=this._decodeChar(e.charCodeAt(a+1)),l=this._decodeChar(e.charCodeAt(a+2)),d=this._decodeChar(e.charCodeAt(a+3)),s[i++]=c<<2|u>>>4,s[i++]=u<<4|l>>>2,s[i++]=l<<6|d,o|=c&Rt,o|=u&Rt,o|=l&Rt,o|=d&Rt;if(a<r-1&&(c=this._decodeChar(e.charCodeAt(a)),u=this._decodeChar(e.charCodeAt(a+1)),s[i++]=c<<2|u>>>4,o|=c&Rt,o|=u&Rt),a<r-2&&(l=this._decodeChar(e.charCodeAt(a+2)),s[i++]=u<<4|l>>>2,o|=l&Rt),a<r-3&&(d=this._decodeChar(e.charCodeAt(a+3)),s[i++]=l<<6|d,o|=d&Rt),o!==0)throw new Error("Base64Coder: incorrect characters for decoding");return s},t.prototype._encodeByte=function(e){var n=e;return n+=65,n+=25-e>>>8&6,n+=51-e>>>8&-75,n+=61-e>>>8&-15,n+=62-e>>>8&3,String.fromCharCode(n)},t.prototype._decodeChar=function(e){var n=Rt;return n+=(42-e&e-44)>>>8&-Rt+e-43+62,n+=(46-e&e-48)>>>8&-Rt+e-47+63,n+=(47-e&e-58)>>>8&-Rt+e-48+52,n+=(64-e&e-91)>>>8&-Rt+e-65+0,n+=(96-e&e-123)>>>8&-Rt+e-97+26,n},t.prototype._getPaddingLength=function(e){var n=0;if(this._paddingCharacter){for(var r=e.length-1;r>=0&&e[r]===this._paddingCharacter;r--)n++;if(e.length<4||n>2)throw new Error("Base64Coder: incorrect padding")}return n},t}();Qr.Coder=mb;var jl=new mb;function C7(t){return jl.encode(t)}Qr.encode=C7;function O7(t){return jl.decode(t)}Qr.decode=O7;var D$=function(t){k7(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype._encodeByte=function(n){var r=n;return r+=65,r+=25-n>>>8&6,r+=51-n>>>8&-75,r+=61-n>>>8&-13,r+=62-n>>>8&49,String.fromCharCode(r)},e.prototype._decodeChar=function(n){var r=Rt;return r+=(44-n&n-46)>>>8&-Rt+n-45+62,r+=(94-n&n-96)>>>8&-Rt+n-95+63,r+=(47-n&n-58)>>>8&-Rt+n-48+52,r+=(64-n&n-91)>>>8&-Rt+n-65+0,r+=(96-n&n-123)>>>8&-Rt+n-97+26,r},e}(mb);Qr.URLSafeCoder=D$;var U$=new D$;function $7(t){return U$.encode(t)}Qr.encodeURLSafe=$7;function R7(t){return U$.decode(t)}Qr.decodeURLSafe=R7;Qr.encodedLength=function(t){return jl.encodedLength(t)};Qr.maxDecodedLength=function(t){return jl.maxDecodedLength(t)};Qr.decodedLength=function(t){return jl.decodedLength(t)};var F$={exports:{}};(function(t){(function(e,n){var r={};n(r);var s=r.default;for(var i in r)s[i]=r[i];t.exports=s})(Zm,function(e){e.__esModule=!0,e.digestLength=32,e.blockSize=64;var n=new Uint32Array([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]);function r(f,h,p,g,y){for(var b,_,w,v,A,S,x,E,$,k,C,D,B;y>=64;){for(b=h[0],_=h[1],w=h[2],v=h[3],A=h[4],S=h[5],x=h[6],E=h[7],k=0;k<16;k++)C=g+k*4,f[k]=(p[C]&255)<<24|(p[C+1]&255)<<16|(p[C+2]&255)<<8|p[C+3]&255;for(k=16;k<64;k++)$=f[k-2],D=($>>>17|$<<15)^($>>>19|$<<13)^$>>>10,$=f[k-15],B=($>>>7|$<<25)^($>>>18|$<<14)^$>>>3,f[k]=(D+f[k-7]|0)+(B+f[k-16]|0);for(k=0;k<64;k++)D=(((A>>>6|A<<26)^(A>>>11|A<<21)^(A>>>25|A<<7))+(A&S^~A&x)|0)+(E+(n[k]+f[k]|0)|0)|0,B=((b>>>2|b<<30)^(b>>>13|b<<19)^(b>>>22|b<<10))+(b&_^b&w^_&w)|0,E=x,x=S,S=A,A=v+D|0,v=w,w=_,_=b,b=D+B|0;h[0]+=b,h[1]+=_,h[2]+=w,h[3]+=v,h[4]+=A,h[5]+=S,h[6]+=x,h[7]+=E,g+=64,y-=64}return g}var s=function(){function f(){this.digestLength=e.digestLength,this.blockSize=e.blockSize,this.state=new Int32Array(8),this.temp=new Int32Array(64),this.buffer=new Uint8Array(128),this.bufferLength=0,this.bytesHashed=0,this.finished=!1,this.reset()}return f.prototype.reset=function(){return this.state[0]=1779033703,this.state[1]=3144134277,this.state[2]=1013904242,this.state[3]=2773480762,this.state[4]=1359893119,this.state[5]=2600822924,this.state[6]=528734635,this.state[7]=1541459225,this.bufferLength=0,this.bytesHashed=0,this.finished=!1,this},f.prototype.clean=function(){for(var h=0;h<this.buffer.length;h++)this.buffer[h]=0;for(var h=0;h<this.temp.length;h++)this.temp[h]=0;this.reset()},f.prototype.update=function(h,p){if(p===void 0&&(p=h.length),this.finished)throw new Error("SHA256: can't update because hash was finished.");var g=0;if(this.bytesHashed+=p,this.bufferLength>0){for(;this.bufferLength<64&&p>0;)this.buffer[this.bufferLength++]=h[g++],p--;this.bufferLength===64&&(r(this.temp,this.state,this.buffer,0,64),this.bufferLength=0)}for(p>=64&&(g=r(this.temp,this.state,h,g,p),p%=64);p>0;)this.buffer[this.bufferLength++]=h[g++],p--;return this},f.prototype.finish=function(h){if(!this.finished){var p=this.bytesHashed,g=this.bufferLength,y=p/536870912|0,b=p<<3,_=p%64<56?64:128;this.buffer[g]=128;for(var w=g+1;w<_-8;w++)this.buffer[w]=0;this.buffer[_-8]=y>>>24&255,this.buffer[_-7]=y>>>16&255,this.buffer[_-6]=y>>>8&255,this.buffer[_-5]=y>>>0&255,this.buffer[_-4]=b>>>24&255,this.buffer[_-3]=b>>>16&255,this.buffer[_-2]=b>>>8&255,this.buffer[_-1]=b>>>0&255,r(this.temp,this.state,this.buffer,0,_),this.finished=!0}for(var w=0;w<8;w++)h[w*4+0]=this.state[w]>>>24&255,h[w*4+1]=this.state[w]>>>16&255,h[w*4+2]=this.state[w]>>>8&255,h[w*4+3]=this.state[w]>>>0&255;return this},f.prototype.digest=function(){var h=new Uint8Array(this.digestLength);return this.finish(h),h},f.prototype._saveState=function(h){for(var p=0;p<this.state.length;p++)h[p]=this.state[p]},f.prototype._restoreState=function(h,p){for(var g=0;g<this.state.length;g++)this.state[g]=h[g];this.bytesHashed=p,this.finished=!1,this.bufferLength=0},f}();e.Hash=s;var i=function(){function f(h){this.inner=new s,this.outer=new s,this.blockSize=this.inner.blockSize,this.digestLength=this.inner.digestLength;var p=new Uint8Array(this.blockSize);if(h.length>this.blockSize)new s().update(h).finish(p).clean();else for(var g=0;g<h.length;g++)p[g]=h[g];for(var g=0;g<p.length;g++)p[g]^=54;this.inner.update(p);for(var g=0;g<p.length;g++)p[g]^=106;this.outer.update(p),this.istate=new Uint32Array(8),this.ostate=new Uint32Array(8),this.inner._saveState(this.istate),this.outer._saveState(this.ostate);for(var g=0;g<p.length;g++)p[g]=0}return f.prototype.reset=function(){return this.inner._restoreState(this.istate,this.inner.blockSize),this.outer._restoreState(this.ostate,this.outer.blockSize),this},f.prototype.clean=function(){for(var h=0;h<this.istate.length;h++)this.ostate[h]=this.istate[h]=0;this.inner.clean(),this.outer.clean()},f.prototype.update=function(h){return this.inner.update(h),this},f.prototype.finish=function(h){return this.outer.finished?this.outer.finish(h):(this.inner.finish(h),this.outer.update(h,this.digestLength).finish(h)),this},f.prototype.digest=function(){var h=new Uint8Array(this.digestLength);return this.finish(h),h},f}();e.HMAC=i;function a(f){var h=new s().update(f),p=h.digest();return h.clean(),p}e.hash=a,e.default=a;function o(f,h){var p=new i(f).update(h),g=p.digest();return p.clean(),g}e.hmac=o;function c(f,h,p,g){var y=g[0];if(y===0)throw new Error("hkdf: cannot expand more");h.reset(),y>1&&h.update(f),p&&h.update(p),h.update(g),h.finish(f),g[0]++}var u=new Uint8Array(e.digestLength);function l(f,h,p,g){h===void 0&&(h=u),g===void 0&&(g=32);for(var y=new Uint8Array([1]),b=o(h,f),_=new i(b),w=new Uint8Array(_.digestLength),v=w.length,A=new Uint8Array(g),S=0;S<g;S++)v===w.length&&(c(w,_,p,y),v=0),A[S]=w[v++];return _.clean(),w.fill(0),y.fill(0),A}e.hkdf=l;function d(f,h,p,g){for(var y=new i(f),b=y.digestLength,_=new Uint8Array(4),w=new Uint8Array(b),v=new Uint8Array(b),A=new Uint8Array(g),S=0;S*b<g;S++){var x=S+1;_[0]=x>>>24&255,_[1]=x>>>16&255,_[2]=x>>>8&255,_[3]=x>>>0&255,y.reset(),y.update(h),y.update(_),y.finish(v);for(var E=0;E<b;E++)w[E]=v[E];for(var E=2;E<=p;E++){y.reset(),y.update(v).finish(v);for(var $=0;$<b;$++)w[$]^=v[$]}for(var E=0;E<b&&S*b+E<g;E++)A[S*b+E]=w[E]}for(var S=0;S<b;S++)w[S]=v[S]=0;for(var S=0;S<4;S++)_[S]=0;return y.clean(),A}e.pbkdf2=d})})(F$);var P7=F$.exports;Object.defineProperty(Gu,"__esModule",{value:!0});var B$=Gu.Webhook=Gu.WebhookVerificationError=void 0;const N7=cp,NA=Qr,M7=P7,MA=5*60;class gb extends Error{constructor(e){super(e),Object.setPrototypeOf(this,gb.prototype),this.name="ExtendableError",this.stack=new Error(e).stack}}class hi extends gb{constructor(e){super(e),Object.setPrototypeOf(this,hi.prototype),this.name="WebhookVerificationError"}}Gu.WebhookVerificationError=hi;class Ju{constructor(e,n){if(!e)throw new Error("Secret can't be empty.");if((n==null?void 0:n.format)==="raw")e instanceof Uint8Array?this.key=e:this.key=Uint8Array.from(e,r=>r.charCodeAt(0));else{if(typeof e!="string")throw new Error("Expected secret to be of type string");e.startsWith(Ju.prefix)&&(e=e.substring(Ju.prefix.length)),this.key=NA.decode(e)}}verify(e,n){const r={};for(const f of Object.keys(n))r[f.toLowerCase()]=n[f];const s=r["webhook-id"],i=r["webhook-signature"],a=r["webhook-timestamp"];if(!i||!s||!a)throw new hi("Missing required headers");const o=this.verifyTimestamp(a),u=this.sign(s,o,e).split(",")[1],l=i.split(" "),d=new globalThis.TextEncoder;for(const f of l){const[h,p]=f.split(",");if(h==="v1"&&(0,N7.timingSafeEqual)(d.encode(p),d.encode(u)))return JSON.parse(e.toString())}throw new hi("No matching signature found")}sign(e,n,r){if(typeof r!="string")if(r.constructor.name==="Buffer")r=r.toString();else throw new Error("Expected payload to be of type string or Buffer.");const s=new TextEncoder,i=Math.floor(n.getTime()/1e3),a=s.encode(`${e}.${i}.${r}`);return`v1,${NA.encode(M7.hmac(this.key,a))}`}verifyTimestamp(e){const n=Math.floor(Date.now()/1e3),r=parseInt(e,10);if(isNaN(r))throw new hi("Invalid Signature Headers");if(n-r>MA)throw new hi("Message timestamp too old");if(r>n+MA)throw new hi("Message timestamp too new");return new Date(r*1e3)}}B$=Gu.Webhook=Ju;Ju.prefix="whsec_";class z$ extends gt{unwrap(e,{headers:n,key:r}){if(n!==void 0){const s=r===void 0?this._client.webhookKey:r;if(s===null)throw new Error("Webhook key must not be null in order to unwrap");new B$(s).verify(e,n)}return JSON.parse(e)}}let H$=class extends gt{list(e,n={},r){const{betas:s,...i}=n??{};return this._client.getAPIList(le`/v1/agents/${e}/versions?beta=true`,En,{query:i,...r,headers:K([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r==null?void 0:r.headers])})}};class _b extends gt{constructor(){super(...arguments),this.versions=new H$(this._client)}create(e,n){const{betas:r,...s}=e;return this._client.post("/v1/agents?beta=true",{body:s,...n,headers:K([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},n==null?void 0:n.headers])})}retrieve(e,n={},r){const{betas:s,...i}=n??{};return this._client.get(le`/v1/agents/${e}?beta=true`,{query:i,...r,headers:K([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r==null?void 0:r.headers])})}update(e,n,r){const{betas:s,...i}=n;return this._client.post(le`/v1/agents/${e}?beta=true`,{body:i,...r,headers:K([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r==null?void 0:r.headers])})}list(e={},n){const{betas:r,...s}=e??{};return this._client.getAPIList("/v1/agents?beta=true",En,{query:s,...n,headers:K([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},n==null?void 0:n.headers])})}archive(e,n={},r){const{betas:s}=n??{};return this._client.post(le`/v1/agents/${e}/archive?beta=true`,{...r,headers:K([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r==null?void 0:r.headers])})}}_b.Versions=H$;class V$ extends gt{create(e,n,r){const{view:s,betas:i,...a}=n;return this._client.post(le`/v1/memory_stores/${e}/memories?beta=true`,{query:{view:s},body:a,...r,headers:K([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString()},r==null?void 0:r.headers])})}retrieve(e,n,r){const{memory_store_id:s,betas:i,...a}=n;return this._client.get(le`/v1/memory_stores/${s}/memories/${e}?beta=true`,{query:a,...r,headers:K([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString()},r==null?void 0:r.headers])})}update(e,n,r){const{memory_store_id:s,view:i,betas:a,...o}=n;return this._client.post(le`/v1/memory_stores/${s}/memories/${e}?beta=true`,{query:{view:i},body:o,...r,headers:K([{"anthropic-beta":[...a??[],"managed-agents-2026-04-01"].toString()},r==null?void 0:r.headers])})}list(e,n={},r){const{betas:s,...i}=n??{};return this._client.getAPIList(le`/v1/memory_stores/${e}/memories?beta=true`,En,{query:i,...r,headers:K([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r==null?void 0:r.headers])})}delete(e,n,r){const{memory_store_id:s,expected_content_sha256:i,betas:a}=n;return this._client.delete(le`/v1/memory_stores/${s}/memories/${e}?beta=true`,{query:{expected_content_sha256:i},...r,headers:K([{"anthropic-beta":[...a??[],"managed-agents-2026-04-01"].toString()},r==null?void 0:r.headers])})}}class K$ extends gt{retrieve(e,n,r){const{memory_store_id:s,betas:i,...a}=n;return this._client.get(le`/v1/memory_stores/${s}/memory_versions/${e}?beta=true`,{query:a,...r,headers:K([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString()},r==null?void 0:r.headers])})}list(e,n={},r){const{betas:s,...i}=n??{};return this._client.getAPIList(le`/v1/memory_stores/${e}/memory_versions?beta=true`,En,{query:i,...r,headers:K([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r==null?void 0:r.headers])})}redact(e,n,r){const{memory_store_id:s,betas:i}=n;return this._client.post(le`/v1/memory_stores/${s}/memory_versions/${e}/redact?beta=true`,{...r,headers:K([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString()},r==null?void 0:r.headers])})}}class up extends gt{constructor(){super(...arguments),this.memories=new V$(this._client),this.memoryVersions=new K$(this._client)}create(e,n){const{betas:r,...s}=e;return this._client.post("/v1/memory_stores?beta=true",{body:s,...n,headers:K([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},n==null?void 0:n.headers])})}retrieve(e,n={},r){const{betas:s}=n??{};return this._client.get(le`/v1/memory_stores/${e}?beta=true`,{...r,headers:K([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r==null?void 0:r.headers])})}update(e,n,r){const{betas:s,...i}=n;return this._client.post(le`/v1/memory_stores/${e}?beta=true`,{body:i,...r,headers:K([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r==null?void 0:r.headers])})}list(e={},n){const{betas:r,...s}=e??{};return this._client.getAPIList("/v1/memory_stores?beta=true",En,{query:s,...n,headers:K([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},n==null?void 0:n.headers])})}delete(e,n={},r){const{betas:s}=n??{};return this._client.delete(le`/v1/memory_stores/${e}?beta=true`,{...r,headers:K([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r==null?void 0:r.headers])})}archive(e,n={},r){const{betas:s}=n??{};return this._client.post(le`/v1/memory_stores/${e}/archive?beta=true`,{...r,headers:K([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r==null?void 0:r.headers])})}}up.Memories=V$;up.MemoryVersions=K$;class lp{constructor(e,n){this.iterator=e,this.controller=n}async*decoder(){const e=new Ml;for await(const n of this.iterator)for(const r of e.decode(n))yield JSON.parse(r);for(const n of e.flush())yield JSON.parse(n)}[Symbol.asyncIterator](){return this.decoder()}static fromResponse(e,n){if(!e.body)throw n.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new ke("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new ke("Attempted to iterate over a response with no body");return new lp(lb(e.body),n)}}let W$=class extends gt{create(e,n){const{betas:r,...s}=e;return this._client.post("/v1/messages/batches?beta=true",{body:s,...n,headers:K([{"anthropic-beta":[...r??[],"message-batches-2024-09-24"].toString()},n==null?void 0:n.headers])})}retrieve(e,n={},r){const{betas:s}=n??{};return this._client.get(le`/v1/messages/batches/${e}?beta=true`,{...r,headers:K([{"anthropic-beta":[...s??[],"message-batches-2024-09-24"].toString()},r==null?void 0:r.headers])})}list(e={},n){const{betas:r,...s}=e??{};return this._client.getAPIList("/v1/messages/batches?beta=true",Ll,{query:s,...n,headers:K([{"anthropic-beta":[...r??[],"message-batches-2024-09-24"].toString()},n==null?void 0:n.headers])})}delete(e,n={},r){const{betas:s}=n??{};return this._client.delete(le`/v1/messages/batches/${e}?beta=true`,{...r,headers:K([{"anthropic-beta":[...s??[],"message-batches-2024-09-24"].toString()},r==null?void 0:r.headers])})}cancel(e,n={},r){const{betas:s}=n??{};return this._client.post(le`/v1/messages/batches/${e}/cancel?beta=true`,{...r,headers:K([{"anthropic-beta":[...s??[],"message-batches-2024-09-24"].toString()},r==null?void 0:r.headers])})}async results(e,n={},r){const s=await this.retrieve(e);if(!s.results_url)throw new ke(`No batch \`results_url\`; Has it finished processing? ${s.processing_status} - ${s.id}`);const{betas:i}=n??{};return this._client.get(s.results_url,{...r,headers:K([{"anthropic-beta":[...i??[],"message-batches-2024-09-24"].toString(),Accept:"application/binary"},r==null?void 0:r.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((a,o)=>lp.fromResponse(o.response,o.controller))}};const Z$={"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 q$(t){var e;return(t==null?void 0:t.output_format)??((e=t==null?void 0:t.output_config)==null?void 0:e.format)}function LA(t,e,n){const r=q$(e);return!e||!("parse"in(r??{}))?{...t,content:t.content.map(s=>{if(s.type==="text"){const i=Object.defineProperty({...s},"parsed_output",{value:null,enumerable:!1});return Object.defineProperty(i,"parsed",{get(){return n.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),null},enumerable:!1})}return s}),parsed_output:null}:G$(t,e,n)}function G$(t,e,n){let r=null;const s=t.content.map(i=>{if(i.type==="text"){const a=L7(e,i.text);r===null&&(r=a);const o=Object.defineProperty({...i},"parsed_output",{value:a,enumerable:!1});return Object.defineProperty(o,"parsed",{get(){return n.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),a},enumerable:!1})}return i});return{...t,content:s,parsed_output:r}}function L7(t,e){const n=q$(t);if((n==null?void 0:n.type)!=="json_schema")return null;try{return"parse"in n?n.parse(e):JSON.parse(e)}catch(r){throw new ke(`Failed to parse structured output: ${r}`)}}const j7=t=>{let e=0,n=[];for(;e<t.length;){let r=t[e];if(r==="\\"){e++;continue}if(r==="{"){n.push({type:"brace",value:"{"}),e++;continue}if(r==="}"){n.push({type:"brace",value:"}"}),e++;continue}if(r==="["){n.push({type:"paren",value:"["}),e++;continue}if(r==="]"){n.push({type:"paren",value:"]"}),e++;continue}if(r===":"){n.push({type:"separator",value:":"}),e++;continue}if(r===","){n.push({type:"delimiter",value:","}),e++;continue}if(r==='"'){let o="",c=!1;for(r=t[++e];r!=='"';){if(e===t.length){c=!0;break}if(r==="\\"){if(e++,e===t.length){c=!0;break}o+=r+t[e],r=t[++e]}else o+=r,r=t[++e]}r=t[++e],c||n.push({type:"string",value:o});continue}if(r&&/\s/.test(r)){e++;continue}let i=/[0-9]/;if(r&&i.test(r)||r==="-"||r==="."){let o="";for(r==="-"&&(o+=r,r=t[++e]);r&&i.test(r)||r===".";)o+=r,r=t[++e];n.push({type:"number",value:o});continue}let a=/[a-z]/i;if(r&&a.test(r)){let o="";for(;r&&a.test(r)&&e!==t.length;)o+=r,r=t[++e];if(o=="true"||o=="false"||o==="null")n.push({type:"name",value:o});else{e++;continue}continue}e++}return n},eo=t=>{if(t.length===0)return t;let e=t[t.length-1];switch(e.type){case"separator":return t=t.slice(0,t.length-1),eo(t);case"number":let n=e.value[e.value.length-1];if(n==="."||n==="-")return t=t.slice(0,t.length-1),eo(t);case"string":let r=t[t.length-2];if((r==null?void 0:r.type)==="delimiter")return t=t.slice(0,t.length-1),eo(t);if((r==null?void 0:r.type)==="brace"&&r.value==="{")return t=t.slice(0,t.length-1),eo(t);break;case"delimiter":return t=t.slice(0,t.length-1),eo(t)}return t},D7=t=>{let e=[];return t.map(n=>{n.type==="brace"&&(n.value==="{"?e.push("}"):e.splice(e.lastIndexOf("}"),1)),n.type==="paren"&&(n.value==="["?e.push("]"):e.splice(e.lastIndexOf("]"),1))}),e.length>0&&e.reverse().map(n=>{n==="}"?t.push({type:"brace",value:"}"}):n==="]"&&t.push({type:"paren",value:"]"})}),t},U7=t=>{let e="";return t.map(n=>{switch(n.type){case"string":e+='"'+n.value+'"';break;default:e+=n.value;break}}),e},J$=t=>JSON.parse(U7(D7(eo(j7(t)))));var wr,ti,za,wc,Td,bc,vc,Ed,Sc,Cs,Ac,Id,xd,Fi,kd,Cd,Tc,Rm,jA,Od,Pm,Nm,Mm,DA;const UA="__json_buf";function FA(t){return t.type==="tool_use"||t.type==="server_tool_use"||t.type==="mcp_tool_use"}class hf{constructor(e,n){wr.add(this),this.messages=[],this.receivedMessages=[],ti.set(this,void 0),za.set(this,null),this.controller=new AbortController,wc.set(this,void 0),Td.set(this,()=>{}),bc.set(this,()=>{}),vc.set(this,void 0),Ed.set(this,()=>{}),Sc.set(this,()=>{}),Cs.set(this,{}),Ac.set(this,!1),Id.set(this,!1),xd.set(this,!1),Fi.set(this,!1),kd.set(this,void 0),Cd.set(this,void 0),Tc.set(this,void 0),Od.set(this,r=>{if(oe(this,Id,!0),qu(r)&&(r=new qr),r instanceof qr)return oe(this,xd,!0),this._emit("abort",r);if(r instanceof ke)return this._emit("error",r);if(r instanceof Error){const s=new ke(r.message);return s.cause=r,this._emit("error",s)}return this._emit("error",new ke(String(r)))}),oe(this,wc,new Promise((r,s)=>{oe(this,Td,r,"f"),oe(this,bc,s,"f")})),oe(this,vc,new Promise((r,s)=>{oe(this,Ed,r,"f"),oe(this,Sc,s,"f")})),P(this,wc,"f").catch(()=>{}),P(this,vc,"f").catch(()=>{}),oe(this,za,e),oe(this,Tc,(n==null?void 0:n.logger)??console)}get response(){return P(this,kd,"f")}get request_id(){return P(this,Cd,"f")}async withResponse(){oe(this,Fi,!0);const e=await P(this,wc,"f");if(!e)throw new Error("Could not resolve a `Response` object");return{data:this,response:e,request_id:e.headers.get("request-id")}}static fromReadableStream(e){const n=new hf(null);return n._run(()=>n._fromReadableStream(e)),n}static createMessage(e,n,r,{logger:s}={}){const i=new hf(n,{logger:s});for(const a of n.messages)i._addMessageParam(a);return oe(i,za,{...n,stream:!0}),i._run(()=>i._createMessage(e,{...n,stream:!0},{...r,headers:{...r==null?void 0:r.headers,"X-Stainless-Helper-Method":"stream"}})),i}_run(e){e().then(()=>{this._emitFinal(),this._emit("end")},P(this,Od,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,n=!0){this.receivedMessages.push(e),n&&this._emit("message",e)}async _createMessage(e,n,r){var a;const s=r==null?void 0:r.signal;let i;s&&(s.aborted&&this.controller.abort(),i=this.controller.abort.bind(this.controller),s.addEventListener("abort",i));try{P(this,wr,"m",Pm).call(this);const{response:o,data:c}=await e.create({...n,stream:!0},{...r,signal:this.controller.signal}).withResponse();this._connected(o);for await(const u of c)P(this,wr,"m",Nm).call(this,u);if((a=c.controller.signal)!=null&&a.aborted)throw new qr;P(this,wr,"m",Mm).call(this)}finally{s&&i&&s.removeEventListener("abort",i)}}_connected(e){this.ended||(oe(this,kd,e),oe(this,Cd,e==null?void 0:e.headers.get("request-id")),P(this,Td,"f").call(this,e),this._emit("connect"))}get ended(){return P(this,Ac,"f")}get errored(){return P(this,Id,"f")}get aborted(){return P(this,xd,"f")}abort(){this.controller.abort()}on(e,n){return(P(this,Cs,"f")[e]||(P(this,Cs,"f")[e]=[])).push({listener:n}),this}off(e,n){const r=P(this,Cs,"f")[e];if(!r)return this;const s=r.findIndex(i=>i.listener===n);return s>=0&&r.splice(s,1),this}once(e,n){return(P(this,Cs,"f")[e]||(P(this,Cs,"f")[e]=[])).push({listener:n,once:!0}),this}emitted(e){return new Promise((n,r)=>{oe(this,Fi,!0),e!=="error"&&this.once("error",r),this.once(e,n)})}async done(){oe(this,Fi,!0),await P(this,vc,"f")}get currentMessage(){return P(this,ti,"f")}async finalMessage(){return await this.done(),P(this,wr,"m",Rm).call(this)}async finalText(){return await this.done(),P(this,wr,"m",jA).call(this)}_emit(e,...n){if(P(this,Ac,"f"))return;e==="end"&&(oe(this,Ac,!0),P(this,Ed,"f").call(this));const r=P(this,Cs,"f")[e];if(r&&(P(this,Cs,"f")[e]=r.filter(s=>!s.once),r.forEach(({listener:s})=>s(...n))),e==="abort"){const s=n[0];!P(this,Fi,"f")&&!(r!=null&&r.length)&&Promise.reject(s),P(this,bc,"f").call(this,s),P(this,Sc,"f").call(this,s),this._emit("end");return}if(e==="error"){const s=n[0];!P(this,Fi,"f")&&!(r!=null&&r.length)&&Promise.reject(s),P(this,bc,"f").call(this,s),P(this,Sc,"f").call(this,s),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",P(this,wr,"m",Rm).call(this))}async _fromReadableStream(e,n){var i;const r=n==null?void 0:n.signal;let s;r&&(r.aborted&&this.controller.abort(),s=this.controller.abort.bind(this.controller),r.addEventListener("abort",s));try{P(this,wr,"m",Pm).call(this),this._connected(null);const a=gs.fromReadableStream(e,this.controller);for await(const o of a)P(this,wr,"m",Nm).call(this,o);if((i=a.controller.signal)!=null&&i.aborted)throw new qr;P(this,wr,"m",Mm).call(this)}finally{r&&s&&r.removeEventListener("abort",s)}}[(ti=new WeakMap,za=new WeakMap,wc=new WeakMap,Td=new WeakMap,bc=new WeakMap,vc=new WeakMap,Ed=new WeakMap,Sc=new WeakMap,Cs=new WeakMap,Ac=new WeakMap,Id=new WeakMap,xd=new WeakMap,Fi=new WeakMap,kd=new WeakMap,Cd=new WeakMap,Tc=new WeakMap,Od=new WeakMap,wr=new WeakSet,Rm=function(){if(this.receivedMessages.length===0)throw new ke("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},jA=function(){if(this.receivedMessages.length===0)throw new ke("stream ended without producing a Message with role=assistant");const n=this.receivedMessages.at(-1).content.filter(r=>r.type==="text").map(r=>r.text);if(n.length===0)throw new ke("stream ended without producing a content block with type=text");return n.join(" ")},Pm=function(){this.ended||oe(this,ti,void 0)},Nm=function(n){if(this.ended)return;const r=P(this,wr,"m",DA).call(this,n);switch(this._emit("streamEvent",n,r),n.type){case"content_block_delta":{const s=r.content.at(-1);switch(n.delta.type){case"text_delta":{s.type==="text"&&this._emit("text",n.delta.text,s.text||"");break}case"citations_delta":{s.type==="text"&&this._emit("citation",n.delta.citation,s.citations??[]);break}case"input_json_delta":{FA(s)&&s.input&&this._emit("inputJson",n.delta.partial_json,s.input);break}case"thinking_delta":{s.type==="thinking"&&this._emit("thinking",n.delta.thinking,s.thinking);break}case"signature_delta":{s.type==="thinking"&&this._emit("signature",s.signature);break}case"compaction_delta":{s.type==="compaction"&&s.content&&this._emit("compaction",s.content);break}default:n.delta}break}case"message_stop":{this._addMessageParam(r),this._addMessage(LA(r,P(this,za,"f"),{logger:P(this,Tc,"f")}),!0);break}case"content_block_stop":{this._emit("contentBlock",r.content.at(-1));break}case"message_start":{oe(this,ti,r);break}}},Mm=function(){if(this.ended)throw new ke("stream has ended, this shouldn't happen");const n=P(this,ti,"f");if(!n)throw new ke("request ended without sending any chunks");return oe(this,ti,void 0),LA(n,P(this,za,"f"),{logger:P(this,Tc,"f")})},DA=function(n){let r=P(this,ti,"f");if(n.type==="message_start"){if(r)throw new ke(`Unexpected event order, got ${n.type} before receiving "message_stop"`);return n.message}if(!r)throw new ke(`Unexpected event order, got ${n.type} before "message_start"`);switch(n.type){case"message_stop":return r;case"message_delta":return r.container=n.delta.container,r.stop_reason=n.delta.stop_reason,r.stop_sequence=n.delta.stop_sequence,r.usage.output_tokens=n.usage.output_tokens,r.context_management=n.context_management,n.usage.input_tokens!=null&&(r.usage.input_tokens=n.usage.input_tokens),n.usage.cache_creation_input_tokens!=null&&(r.usage.cache_creation_input_tokens=n.usage.cache_creation_input_tokens),n.usage.cache_read_input_tokens!=null&&(r.usage.cache_read_input_tokens=n.usage.cache_read_input_tokens),n.usage.server_tool_use!=null&&(r.usage.server_tool_use=n.usage.server_tool_use),n.usage.iterations!=null&&(r.usage.iterations=n.usage.iterations),r;case"content_block_start":return r.content.push(n.content_block),r;case"content_block_delta":{const s=r.content.at(n.index);switch(n.delta.type){case"text_delta":{(s==null?void 0:s.type)==="text"&&(r.content[n.index]={...s,text:(s.text||"")+n.delta.text});break}case"citations_delta":{(s==null?void 0:s.type)==="text"&&(r.content[n.index]={...s,citations:[...s.citations??[],n.delta.citation]});break}case"input_json_delta":{if(s&&FA(s)){let i=s[UA]||"";i+=n.delta.partial_json;const a={...s};if(Object.defineProperty(a,UA,{value:i,enumerable:!1,writable:!0}),i)try{a.input=J$(i)}catch(o){const c=new ke(`Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: ${o}. JSON: ${i}`);P(this,Od,"f").call(this,c)}r.content[n.index]=a}break}case"thinking_delta":{(s==null?void 0:s.type)==="thinking"&&(r.content[n.index]={...s,thinking:s.thinking+n.delta.thinking});break}case"signature_delta":{(s==null?void 0:s.type)==="thinking"&&(r.content[n.index]={...s,signature:n.delta.signature});break}case"compaction_delta":{(s==null?void 0:s.type)==="compaction"&&(r.content[n.index]={...s,content:(s.content||"")+n.delta.content});break}default:n.delta}return r}case"content_block_stop":return r}},Symbol.asyncIterator)](){const e=[],n=[];let r=!1;return this.on("streamEvent",s=>{const i=n.shift();i?i.resolve(s):e.push(s)}),this.on("end",()=>{r=!0;for(const s of n)s.resolve(void 0);n.length=0}),this.on("abort",s=>{r=!0;for(const i of n)i.reject(s);n.length=0}),this.on("error",s=>{r=!0;for(const i of n)i.reject(s);n.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((i,a)=>n.push({resolve:i,reject:a})).then(i=>i?{value:i,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new gs(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}class Y$ extends Error{constructor(e){const n=typeof e=="string"?e:e.map(r=>r.type==="text"?r.text:`[${r.type}]`).join(" ");super(n),this.name="ToolError",this.content=e}}const F7=1e5,B7=`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:
|
|
582
|
-
1. Task Overview
|
|
583
|
-
The user's core request and success criteria
|
|
584
|
-
Any clarifications or constraints they specified
|
|
585
|
-
2. Current State
|
|
586
|
-
What has been completed so far
|
|
587
|
-
Files created, modified, or analyzed (with paths if relevant)
|
|
588
|
-
Key outputs or artifacts produced
|
|
589
|
-
3. Important Discoveries
|
|
590
|
-
Technical constraints or requirements uncovered
|
|
591
|
-
Decisions made and their rationale
|
|
592
|
-
Errors encountered and how they were resolved
|
|
593
|
-
What approaches were tried that didn't work (and why)
|
|
594
|
-
4. Next Steps
|
|
595
|
-
Specific actions needed to complete the task
|
|
596
|
-
Any blockers or open questions to resolve
|
|
597
|
-
Priority order if multiple steps remain
|
|
598
|
-
5. Context to Preserve
|
|
599
|
-
User preferences or style requirements
|
|
600
|
-
Domain-specific details that aren't obvious
|
|
601
|
-
Any promises made to the user
|
|
602
|
-
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.
|
|
603
|
-
Wrap your summary in <summary></summary> tags.`;var Ec,Ha,Bi,Bt,jn,Gn,js,ni,Ic,BA,V_;function zA(){let t,e;return{promise:new Promise((r,s)=>{t=r,e=s}),resolve:t,reject:e}}class X${constructor(e,n,r){var a;Ec.add(this),this.client=e,Ha.set(this,!1),Bi.set(this,!1),Bt.set(this,void 0),jn.set(this,void 0),Gn.set(this,void 0),js.set(this,void 0),ni.set(this,void 0),Ic.set(this,0),oe(this,Bt,{params:{...n,messages:structuredClone(n.messages)}});const i=["BetaToolRunner",...P$(n.tools,n.messages)].join(", ");oe(this,jn,{...r,headers:K([{"x-stainless-helper":i},r==null?void 0:r.headers])}),oe(this,ni,zA()),(a=n.compactionControl)!=null&&a.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*[(Ha=new WeakMap,Bi=new WeakMap,Bt=new WeakMap,jn=new WeakMap,Gn=new WeakMap,js=new WeakMap,ni=new WeakMap,Ic=new WeakMap,Ec=new WeakSet,BA=async function(){var u;const n=P(this,Bt,"f").params.compactionControl;if(!n||!n.enabled)return!1;let r=0;if(P(this,Gn,"f")!==void 0)try{const l=await P(this,Gn,"f");r=l.usage.input_tokens+(l.usage.cache_creation_input_tokens??0)+(l.usage.cache_read_input_tokens??0)+l.usage.output_tokens}catch{return!1}const s=n.contextTokenThreshold??F7;if(r<s)return!1;const i=n.model??P(this,Bt,"f").params.model,a=n.summaryPrompt??B7,o=P(this,Bt,"f").params.messages;if(o[o.length-1].role==="assistant"){const l=o[o.length-1];if(Array.isArray(l.content)){const d=l.content.filter(f=>f.type!=="tool_use");d.length===0?o.pop():l.content=d}}const c=await this.client.beta.messages.create({model:i,messages:[...o,{role:"user",content:[{type:"text",text:a}]}],max_tokens:P(this,Bt,"f").params.max_tokens},{signal:P(this,jn,"f").signal,headers:K([P(this,jn,"f").headers,{"x-stainless-helper":"compaction"}])});if(((u=c.content[0])==null?void 0:u.type)!=="text")throw new ke("Expected text response for compaction");return P(this,Bt,"f").params.messages=[{role:"user",content:c.content}],!0},Symbol.asyncIterator)](){var e;if(P(this,Ha,"f"))throw new ke("Cannot iterate over a consumed stream");oe(this,Ha,!0),oe(this,Bi,!0),oe(this,js,void 0);try{for(;;){let n;try{if(P(this,Bt,"f").params.max_iterations&&P(this,Ic,"f")>=P(this,Bt,"f").params.max_iterations)break;oe(this,Bi,!1,"f"),oe(this,js,void 0,"f"),oe(this,Ic,(e=P(this,Ic,"f"),e++,e),"f"),oe(this,Gn,void 0,"f");const{max_iterations:r,compactionControl:s,...i}=P(this,Bt,"f").params;if(i.stream?(n=this.client.beta.messages.stream({...i},P(this,jn,"f")),oe(this,Gn,n.finalMessage(),"f"),P(this,Gn,"f").catch(()=>{}),yield n):(oe(this,Gn,this.client.beta.messages.create({...i,stream:!1},P(this,jn,"f")),"f"),yield P(this,Gn,"f")),!await P(this,Ec,"m",BA).call(this)){if(!P(this,Bi,"f")){const{role:c,content:u}=await P(this,Gn,"f");P(this,Bt,"f").params.messages.push({role:c,content:u})}const o=await P(this,Ec,"m",V_).call(this,P(this,Bt,"f").params.messages.at(-1));if(o)P(this,Bt,"f").params.messages.push(o);else if(!P(this,Bi,"f"))break}}finally{n&&n.abort()}}if(!P(this,Gn,"f"))throw new ke("ToolRunner concluded without a message from the server");P(this,ni,"f").resolve(await P(this,Gn,"f"))}catch(n){throw oe(this,Ha,!1),P(this,ni,"f").promise.catch(()=>{}),P(this,ni,"f").reject(n),oe(this,ni,zA()),n}}setMessagesParams(e){typeof e=="function"?P(this,Bt,"f").params=e(P(this,Bt,"f").params):P(this,Bt,"f").params=e,oe(this,Bi,!0),oe(this,js,void 0)}setRequestOptions(e){typeof e=="function"?oe(this,jn,e(P(this,jn,"f"))):oe(this,jn,{...P(this,jn,"f"),...e})}async generateToolResponse(e=P(this,jn,"f").signal){const n=await P(this,Gn,"f")??this.params.messages.at(-1);return n?P(this,Ec,"m",V_).call(this,n,e):null}done(){return P(this,ni,"f").promise}async runUntilDone(){if(!P(this,Ha,"f"))for await(const e of this);return this.done()}get params(){return P(this,Bt,"f").params}pushMessages(...e){this.setMessagesParams(n=>({...n,messages:[...n.messages,...e]}))}then(e,n){return this.runUntilDone().then(e,n)}}V_=async function(e,n=P(this,jn,"f").signal){return P(this,js,"f")!==void 0?P(this,js,"f"):(oe(this,js,z7(P(this,Bt,"f").params,e,{...P(this,jn,"f"),signal:n})),P(this,js,"f"))};async function z7(t,e=t.messages.at(-1),n){if(!e||e.role!=="assistant"||!e.content||typeof e.content=="string")return null;const r=e.content.filter(i=>i.type==="tool_use");return r.length===0?null:{role:"user",content:await Promise.all(r.map(async i=>{const a=t.tools.find(o=>("name"in o?o.name:o.mcp_server_name)===i.name);if(!a||!("run"in a))return{type:"tool_result",tool_use_id:i.id,content:`Error: Tool '${i.name}' not found`,is_error:!0};try{let o=i.input;"parse"in a&&a.parse&&(o=a.parse(o));const c=await a.run(o,{toolUseBlock:i,signal:n==null?void 0:n.signal});return{type:"tool_result",tool_use_id:i.id,content:c}}catch(o){return{type:"tool_result",tool_use_id:i.id,content:o instanceof Y$?o.content:`Error: ${o instanceof Error?o.message:String(o)}`,is_error:!0}}}))}}const HA={"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"},H7=["claude-mythos-preview","claude-opus-4-6"];let Dl=class extends gt{constructor(){super(...arguments),this.batches=new W$(this._client)}create(e,n){const r=VA(e),{betas:s,...i}=r;i.model in HA&&console.warn(`The model '${i.model}' is deprecated and will reach end-of-life on ${HA[i.model]}
|
|
604
|
-
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),H7.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){const c=Z$[i.model]??void 0;a=this._client.calculateNonstreamingTimeout(i.max_tokens,c)}const o=N$(i.tools,i.messages);return this._client.post("/v1/messages?beta=true",{body:i,timeout:a??6e5,...n,headers:K([{...(s==null?void 0:s.toString())!=null?{"anthropic-beta":s==null?void 0:s.toString()}:void 0},o,n==null?void 0:n.headers]),stream:r.stream??!1})}parse(e,n){return n={...n,headers:K([{"anthropic-beta":[...e.betas??[],"structured-outputs-2025-12-15"].toString()},n==null?void 0:n.headers])},this.create(e,n).then(r=>G$(r,e,{logger:this._client.logger??console}))}stream(e,n){return hf.createMessage(this,e,n)}countTokens(e,n){const r=VA(e),{betas:s,...i}=r;return this._client.post("/v1/messages/count_tokens?beta=true",{body:i,...n,headers:K([{"anthropic-beta":[...s??[],"token-counting-2024-11-01"].toString()},n==null?void 0:n.headers])})}toolRunner(e,n){return new X$(this._client,e,n)}};function VA(t){var r;if(!t.output_format)return t;if((r=t.output_config)!=null&&r.format)throw new ke("Both output_format and output_config.format were provided. Please use only output_config.format (output_format is deprecated).");const{output_format:e,...n}=t;return{...n,output_config:{...t.output_config,format:e}}}Dl.Batches=W$;Dl.BetaToolRunner=X$;Dl.ToolError=Y$;let Q$=class extends gt{list(e,n={},r){const{betas:s,...i}=n??{};return this._client.getAPIList(le`/v1/sessions/${e}/events?beta=true`,En,{query:i,...r,headers:K([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r==null?void 0:r.headers])})}send(e,n,r){const{betas:s,...i}=n;return this._client.post(le`/v1/sessions/${e}/events?beta=true`,{body:i,...r,headers:K([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r==null?void 0:r.headers])})}stream(e,n={},r){const{betas:s}=n??{};return this._client.get(le`/v1/sessions/${e}/events/stream?beta=true`,{...r,headers:K([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r==null?void 0:r.headers]),stream:!0})}};class eR extends gt{retrieve(e,n,r){const{session_id:s,betas:i}=n;return this._client.get(le`/v1/sessions/${s}/resources/${e}?beta=true`,{...r,headers:K([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString()},r==null?void 0:r.headers])})}update(e,n,r){const{session_id:s,betas:i,...a}=n;return this._client.post(le`/v1/sessions/${s}/resources/${e}?beta=true`,{body:a,...r,headers:K([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString()},r==null?void 0:r.headers])})}list(e,n={},r){const{betas:s,...i}=n??{};return this._client.getAPIList(le`/v1/sessions/${e}/resources?beta=true`,En,{query:i,...r,headers:K([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r==null?void 0:r.headers])})}delete(e,n,r){const{session_id:s,betas:i}=n;return this._client.delete(le`/v1/sessions/${s}/resources/${e}?beta=true`,{...r,headers:K([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString()},r==null?void 0:r.headers])})}add(e,n,r){const{betas:s,...i}=n;return this._client.post(le`/v1/sessions/${e}/resources?beta=true`,{body:i,...r,headers:K([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r==null?void 0:r.headers])})}}class tR extends gt{list(e,n,r){const{session_id:s,betas:i,...a}=n;return this._client.getAPIList(le`/v1/sessions/${s}/threads/${e}/events?beta=true`,En,{query:a,...r,headers:K([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString()},r==null?void 0:r.headers])})}stream(e,n,r){const{session_id:s,betas:i}=n;return this._client.get(le`/v1/sessions/${s}/threads/${e}/stream?beta=true`,{...r,headers:K([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString()},r==null?void 0:r.headers]),stream:!0})}}class yb extends gt{constructor(){super(...arguments),this.events=new tR(this._client)}retrieve(e,n,r){const{session_id:s,betas:i}=n;return this._client.get(le`/v1/sessions/${s}/threads/${e}?beta=true`,{...r,headers:K([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString()},r==null?void 0:r.headers])})}list(e,n={},r){const{betas:s,...i}=n??{};return this._client.getAPIList(le`/v1/sessions/${e}/threads?beta=true`,En,{query:i,...r,headers:K([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r==null?void 0:r.headers])})}archive(e,n,r){const{session_id:s,betas:i}=n;return this._client.post(le`/v1/sessions/${s}/threads/${e}/archive?beta=true`,{...r,headers:K([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString()},r==null?void 0:r.headers])})}}yb.Events=tR;class Ul extends gt{constructor(){super(...arguments),this.events=new Q$(this._client),this.resources=new eR(this._client),this.threads=new yb(this._client)}create(e,n){const{betas:r,...s}=e;return this._client.post("/v1/sessions?beta=true",{body:s,...n,headers:K([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},n==null?void 0:n.headers])})}retrieve(e,n={},r){const{betas:s}=n??{};return this._client.get(le`/v1/sessions/${e}?beta=true`,{...r,headers:K([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r==null?void 0:r.headers])})}update(e,n,r){const{betas:s,...i}=n;return this._client.post(le`/v1/sessions/${e}?beta=true`,{body:i,...r,headers:K([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r==null?void 0:r.headers])})}list(e={},n){const{betas:r,...s}=e??{};return this._client.getAPIList("/v1/sessions?beta=true",En,{query:s,...n,headers:K([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},n==null?void 0:n.headers])})}delete(e,n={},r){const{betas:s}=n??{};return this._client.delete(le`/v1/sessions/${e}?beta=true`,{...r,headers:K([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r==null?void 0:r.headers])})}archive(e,n={},r){const{betas:s}=n??{};return this._client.post(le`/v1/sessions/${e}/archive?beta=true`,{...r,headers:K([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r==null?void 0:r.headers])})}}Ul.Events=Q$;Ul.Resources=eR;Ul.Threads=yb;class nR extends gt{create(e,n={},r){const{betas:s,...i}=n??{};return this._client.post(le`/v1/skills/${e}/versions?beta=true`,pb({body:i,...r,headers:K([{"anthropic-beta":[...s??[],"skills-2025-10-02"].toString()},r==null?void 0:r.headers])},this._client))}retrieve(e,n,r){const{skill_id:s,betas:i}=n;return this._client.get(le`/v1/skills/${s}/versions/${e}?beta=true`,{...r,headers:K([{"anthropic-beta":[...i??[],"skills-2025-10-02"].toString()},r==null?void 0:r.headers])})}list(e,n={},r){const{betas:s,...i}=n??{};return this._client.getAPIList(le`/v1/skills/${e}/versions?beta=true`,En,{query:i,...r,headers:K([{"anthropic-beta":[...s??[],"skills-2025-10-02"].toString()},r==null?void 0:r.headers])})}delete(e,n,r){const{skill_id:s,betas:i}=n;return this._client.delete(le`/v1/skills/${s}/versions/${e}?beta=true`,{...r,headers:K([{"anthropic-beta":[...i??[],"skills-2025-10-02"].toString()},r==null?void 0:r.headers])})}}class wb extends gt{constructor(){super(...arguments),this.versions=new nR(this._client)}create(e={},n){const{betas:r,...s}=e??{};return this._client.post("/v1/skills?beta=true",pb({body:s,...n,headers:K([{"anthropic-beta":[...r??[],"skills-2025-10-02"].toString()},n==null?void 0:n.headers])},this._client,!1))}retrieve(e,n={},r){const{betas:s}=n??{};return this._client.get(le`/v1/skills/${e}?beta=true`,{...r,headers:K([{"anthropic-beta":[...s??[],"skills-2025-10-02"].toString()},r==null?void 0:r.headers])})}list(e={},n){const{betas:r,...s}=e??{};return this._client.getAPIList("/v1/skills?beta=true",En,{query:s,...n,headers:K([{"anthropic-beta":[...r??[],"skills-2025-10-02"].toString()},n==null?void 0:n.headers])})}delete(e,n={},r){const{betas:s}=n??{};return this._client.delete(le`/v1/skills/${e}?beta=true`,{...r,headers:K([{"anthropic-beta":[...s??[],"skills-2025-10-02"].toString()},r==null?void 0:r.headers])})}}wb.Versions=nR;class rR extends gt{create(e,n,r){const{betas:s,...i}=n;return this._client.post(le`/v1/vaults/${e}/credentials?beta=true`,{body:i,...r,headers:K([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r==null?void 0:r.headers])})}retrieve(e,n,r){const{vault_id:s,betas:i}=n;return this._client.get(le`/v1/vaults/${s}/credentials/${e}?beta=true`,{...r,headers:K([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString()},r==null?void 0:r.headers])})}update(e,n,r){const{vault_id:s,betas:i,...a}=n;return this._client.post(le`/v1/vaults/${s}/credentials/${e}?beta=true`,{body:a,...r,headers:K([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString()},r==null?void 0:r.headers])})}list(e,n={},r){const{betas:s,...i}=n??{};return this._client.getAPIList(le`/v1/vaults/${e}/credentials?beta=true`,En,{query:i,...r,headers:K([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r==null?void 0:r.headers])})}delete(e,n,r){const{vault_id:s,betas:i}=n;return this._client.delete(le`/v1/vaults/${s}/credentials/${e}?beta=true`,{...r,headers:K([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString()},r==null?void 0:r.headers])})}archive(e,n,r){const{vault_id:s,betas:i}=n;return this._client.post(le`/v1/vaults/${s}/credentials/${e}/archive?beta=true`,{...r,headers:K([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString()},r==null?void 0:r.headers])})}mcpOAuthValidate(e,n,r){const{vault_id:s,betas:i}=n;return this._client.post(le`/v1/vaults/${s}/credentials/${e}/mcp_oauth_validate?beta=true`,{...r,headers:K([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString()},r==null?void 0:r.headers])})}}class bb extends gt{constructor(){super(...arguments),this.credentials=new rR(this._client)}create(e,n){const{betas:r,...s}=e;return this._client.post("/v1/vaults?beta=true",{body:s,...n,headers:K([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},n==null?void 0:n.headers])})}retrieve(e,n={},r){const{betas:s}=n??{};return this._client.get(le`/v1/vaults/${e}?beta=true`,{...r,headers:K([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r==null?void 0:r.headers])})}update(e,n,r){const{betas:s,...i}=n;return this._client.post(le`/v1/vaults/${e}?beta=true`,{body:i,...r,headers:K([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r==null?void 0:r.headers])})}list(e={},n){const{betas:r,...s}=e??{};return this._client.getAPIList("/v1/vaults?beta=true",En,{query:s,...n,headers:K([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},n==null?void 0:n.headers])})}delete(e,n={},r){const{betas:s}=n??{};return this._client.delete(le`/v1/vaults/${e}?beta=true`,{...r,headers:K([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r==null?void 0:r.headers])})}archive(e,n={},r){const{betas:s}=n??{};return this._client.post(le`/v1/vaults/${e}/archive?beta=true`,{...r,headers:K([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r==null?void 0:r.headers])})}}bb.Credentials=rR;class gr extends gt{constructor(){super(...arguments),this.models=new L$(this._client),this.messages=new Dl(this._client),this.agents=new _b(this._client),this.environments=new R$(this._client),this.sessions=new Ul(this._client),this.vaults=new bb(this._client),this.memoryStores=new up(this._client),this.files=new M$(this._client),this.skills=new wb(this._client),this.webhooks=new z$(this._client),this.userProfiles=new j$(this._client)}}gr.Models=L$;gr.Messages=Dl;gr.Agents=_b;gr.Environments=R$;gr.Sessions=Ul;gr.Vaults=bb;gr.MemoryStores=up;gr.Files=M$;gr.Skills=wb;gr.Webhooks=z$;gr.UserProfiles=j$;class sR extends gt{create(e,n){const{betas:r,...s}=e;return this._client.post("/v1/complete",{body:s,timeout:this._client._options.timeout??6e5,...n,headers:K([{...(r==null?void 0:r.toString())!=null?{"anthropic-beta":r==null?void 0:r.toString()}:void 0},n==null?void 0:n.headers]),stream:e.stream??!1})}}function iR(t){var e;return(e=t==null?void 0:t.output_config)==null?void 0:e.format}function KA(t,e,n){const r=iR(e);return!e||!("parse"in(r??{}))?{...t,content:t.content.map(s=>s.type==="text"?Object.defineProperty({...s},"parsed_output",{value:null,enumerable:!1}):s),parsed_output:null}:aR(t,e)}function aR(t,e,n){let r=null;const s=t.content.map(i=>{if(i.type==="text"){const a=V7(e,i.text);return r===null&&(r=a),Object.defineProperty({...i},"parsed_output",{value:a,enumerable:!1})}return i});return{...t,content:s,parsed_output:r}}function V7(t,e){const n=iR(t);if((n==null?void 0:n.type)!=="json_schema")return null;try{return"parse"in n?n.parse(e):JSON.parse(e)}catch(r){throw new ke(`Failed to parse structured output: ${r}`)}}var br,ri,Va,xc,$d,kc,Cc,Rd,Oc,Os,$c,Pd,Nd,zi,Md,Ld,Rc,Lm,WA,jm,Dm,Um,Fm,ZA;const qA="__json_buf";function GA(t){return t.type==="tool_use"||t.type==="server_tool_use"}class ff{constructor(e,n){br.add(this),this.messages=[],this.receivedMessages=[],ri.set(this,void 0),Va.set(this,null),this.controller=new AbortController,xc.set(this,void 0),$d.set(this,()=>{}),kc.set(this,()=>{}),Cc.set(this,void 0),Rd.set(this,()=>{}),Oc.set(this,()=>{}),Os.set(this,{}),$c.set(this,!1),Pd.set(this,!1),Nd.set(this,!1),zi.set(this,!1),Md.set(this,void 0),Ld.set(this,void 0),Rc.set(this,void 0),jm.set(this,r=>{if(oe(this,Pd,!0),qu(r)&&(r=new qr),r instanceof qr)return oe(this,Nd,!0),this._emit("abort",r);if(r instanceof ke)return this._emit("error",r);if(r instanceof Error){const s=new ke(r.message);return s.cause=r,this._emit("error",s)}return this._emit("error",new ke(String(r)))}),oe(this,xc,new Promise((r,s)=>{oe(this,$d,r,"f"),oe(this,kc,s,"f")})),oe(this,Cc,new Promise((r,s)=>{oe(this,Rd,r,"f"),oe(this,Oc,s,"f")})),P(this,xc,"f").catch(()=>{}),P(this,Cc,"f").catch(()=>{}),oe(this,Va,e),oe(this,Rc,(n==null?void 0:n.logger)??console)}get response(){return P(this,Md,"f")}get request_id(){return P(this,Ld,"f")}async withResponse(){oe(this,zi,!0);const e=await P(this,xc,"f");if(!e)throw new Error("Could not resolve a `Response` object");return{data:this,response:e,request_id:e.headers.get("request-id")}}static fromReadableStream(e){const n=new ff(null);return n._run(()=>n._fromReadableStream(e)),n}static createMessage(e,n,r,{logger:s}={}){const i=new ff(n,{logger:s});for(const a of n.messages)i._addMessageParam(a);return oe(i,Va,{...n,stream:!0}),i._run(()=>i._createMessage(e,{...n,stream:!0},{...r,headers:{...r==null?void 0:r.headers,"X-Stainless-Helper-Method":"stream"}})),i}_run(e){e().then(()=>{this._emitFinal(),this._emit("end")},P(this,jm,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,n=!0){this.receivedMessages.push(e),n&&this._emit("message",e)}async _createMessage(e,n,r){var a;const s=r==null?void 0:r.signal;let i;s&&(s.aborted&&this.controller.abort(),i=this.controller.abort.bind(this.controller),s.addEventListener("abort",i));try{P(this,br,"m",Dm).call(this);const{response:o,data:c}=await e.create({...n,stream:!0},{...r,signal:this.controller.signal}).withResponse();this._connected(o);for await(const u of c)P(this,br,"m",Um).call(this,u);if((a=c.controller.signal)!=null&&a.aborted)throw new qr;P(this,br,"m",Fm).call(this)}finally{s&&i&&s.removeEventListener("abort",i)}}_connected(e){this.ended||(oe(this,Md,e),oe(this,Ld,e==null?void 0:e.headers.get("request-id")),P(this,$d,"f").call(this,e),this._emit("connect"))}get ended(){return P(this,$c,"f")}get errored(){return P(this,Pd,"f")}get aborted(){return P(this,Nd,"f")}abort(){this.controller.abort()}on(e,n){return(P(this,Os,"f")[e]||(P(this,Os,"f")[e]=[])).push({listener:n}),this}off(e,n){const r=P(this,Os,"f")[e];if(!r)return this;const s=r.findIndex(i=>i.listener===n);return s>=0&&r.splice(s,1),this}once(e,n){return(P(this,Os,"f")[e]||(P(this,Os,"f")[e]=[])).push({listener:n,once:!0}),this}emitted(e){return new Promise((n,r)=>{oe(this,zi,!0),e!=="error"&&this.once("error",r),this.once(e,n)})}async done(){oe(this,zi,!0),await P(this,Cc,"f")}get currentMessage(){return P(this,ri,"f")}async finalMessage(){return await this.done(),P(this,br,"m",Lm).call(this)}async finalText(){return await this.done(),P(this,br,"m",WA).call(this)}_emit(e,...n){if(P(this,$c,"f"))return;e==="end"&&(oe(this,$c,!0),P(this,Rd,"f").call(this));const r=P(this,Os,"f")[e];if(r&&(P(this,Os,"f")[e]=r.filter(s=>!s.once),r.forEach(({listener:s})=>s(...n))),e==="abort"){const s=n[0];!P(this,zi,"f")&&!(r!=null&&r.length)&&Promise.reject(s),P(this,kc,"f").call(this,s),P(this,Oc,"f").call(this,s),this._emit("end");return}if(e==="error"){const s=n[0];!P(this,zi,"f")&&!(r!=null&&r.length)&&Promise.reject(s),P(this,kc,"f").call(this,s),P(this,Oc,"f").call(this,s),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",P(this,br,"m",Lm).call(this))}async _fromReadableStream(e,n){var i;const r=n==null?void 0:n.signal;let s;r&&(r.aborted&&this.controller.abort(),s=this.controller.abort.bind(this.controller),r.addEventListener("abort",s));try{P(this,br,"m",Dm).call(this),this._connected(null);const a=gs.fromReadableStream(e,this.controller);for await(const o of a)P(this,br,"m",Um).call(this,o);if((i=a.controller.signal)!=null&&i.aborted)throw new qr;P(this,br,"m",Fm).call(this)}finally{r&&s&&r.removeEventListener("abort",s)}}[(ri=new WeakMap,Va=new WeakMap,xc=new WeakMap,$d=new WeakMap,kc=new WeakMap,Cc=new WeakMap,Rd=new WeakMap,Oc=new WeakMap,Os=new WeakMap,$c=new WeakMap,Pd=new WeakMap,Nd=new WeakMap,zi=new WeakMap,Md=new WeakMap,Ld=new WeakMap,Rc=new WeakMap,jm=new WeakMap,br=new WeakSet,Lm=function(){if(this.receivedMessages.length===0)throw new ke("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},WA=function(){if(this.receivedMessages.length===0)throw new ke("stream ended without producing a Message with role=assistant");const n=this.receivedMessages.at(-1).content.filter(r=>r.type==="text").map(r=>r.text);if(n.length===0)throw new ke("stream ended without producing a content block with type=text");return n.join(" ")},Dm=function(){this.ended||oe(this,ri,void 0)},Um=function(n){if(this.ended)return;const r=P(this,br,"m",ZA).call(this,n);switch(this._emit("streamEvent",n,r),n.type){case"content_block_delta":{const s=r.content.at(-1);switch(n.delta.type){case"text_delta":{s.type==="text"&&this._emit("text",n.delta.text,s.text||"");break}case"citations_delta":{s.type==="text"&&this._emit("citation",n.delta.citation,s.citations??[]);break}case"input_json_delta":{GA(s)&&s.input&&this._emit("inputJson",n.delta.partial_json,s.input);break}case"thinking_delta":{s.type==="thinking"&&this._emit("thinking",n.delta.thinking,s.thinking);break}case"signature_delta":{s.type==="thinking"&&this._emit("signature",s.signature);break}default:n.delta}break}case"message_stop":{this._addMessageParam(r),this._addMessage(KA(r,P(this,Va,"f"),{logger:P(this,Rc,"f")}),!0);break}case"content_block_stop":{this._emit("contentBlock",r.content.at(-1));break}case"message_start":{oe(this,ri,r);break}}},Fm=function(){if(this.ended)throw new ke("stream has ended, this shouldn't happen");const n=P(this,ri,"f");if(!n)throw new ke("request ended without sending any chunks");return oe(this,ri,void 0),KA(n,P(this,Va,"f"),{logger:P(this,Rc,"f")})},ZA=function(n){let r=P(this,ri,"f");if(n.type==="message_start"){if(r)throw new ke(`Unexpected event order, got ${n.type} before receiving "message_stop"`);return n.message}if(!r)throw new ke(`Unexpected event order, got ${n.type} before "message_start"`);switch(n.type){case"message_stop":return r;case"message_delta":return r.stop_reason=n.delta.stop_reason,r.stop_sequence=n.delta.stop_sequence,r.usage.output_tokens=n.usage.output_tokens,n.usage.input_tokens!=null&&(r.usage.input_tokens=n.usage.input_tokens),n.usage.cache_creation_input_tokens!=null&&(r.usage.cache_creation_input_tokens=n.usage.cache_creation_input_tokens),n.usage.cache_read_input_tokens!=null&&(r.usage.cache_read_input_tokens=n.usage.cache_read_input_tokens),n.usage.server_tool_use!=null&&(r.usage.server_tool_use=n.usage.server_tool_use),r;case"content_block_start":return r.content.push({...n.content_block}),r;case"content_block_delta":{const s=r.content.at(n.index);switch(n.delta.type){case"text_delta":{(s==null?void 0:s.type)==="text"&&(r.content[n.index]={...s,text:(s.text||"")+n.delta.text});break}case"citations_delta":{(s==null?void 0:s.type)==="text"&&(r.content[n.index]={...s,citations:[...s.citations??[],n.delta.citation]});break}case"input_json_delta":{if(s&&GA(s)){let i=s[qA]||"";i+=n.delta.partial_json;const a={...s};Object.defineProperty(a,qA,{value:i,enumerable:!1,writable:!0}),i&&(a.input=J$(i)),r.content[n.index]=a}break}case"thinking_delta":{(s==null?void 0:s.type)==="thinking"&&(r.content[n.index]={...s,thinking:s.thinking+n.delta.thinking});break}case"signature_delta":{(s==null?void 0:s.type)==="thinking"&&(r.content[n.index]={...s,signature:n.delta.signature});break}default:n.delta}return r}case"content_block_stop":return r}},Symbol.asyncIterator)](){const e=[],n=[];let r=!1;return this.on("streamEvent",s=>{const i=n.shift();i?i.resolve(s):e.push(s)}),this.on("end",()=>{r=!0;for(const s of n)s.resolve(void 0);n.length=0}),this.on("abort",s=>{r=!0;for(const i of n)i.reject(s);n.length=0}),this.on("error",s=>{r=!0;for(const i of n)i.reject(s);n.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((i,a)=>n.push({resolve:i,reject:a})).then(i=>i?{value:i,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new gs(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}class oR extends gt{create(e,n){return this._client.post("/v1/messages/batches",{body:e,...n})}retrieve(e,n){return this._client.get(le`/v1/messages/batches/${e}`,n)}list(e={},n){return this._client.getAPIList("/v1/messages/batches",Ll,{query:e,...n})}delete(e,n){return this._client.delete(le`/v1/messages/batches/${e}`,n)}cancel(e,n){return this._client.post(le`/v1/messages/batches/${e}/cancel`,n)}async results(e,n){const r=await this.retrieve(e);if(!r.results_url)throw new ke(`No batch \`results_url\`; Has it finished processing? ${r.processing_status} - ${r.id}`);return this._client.get(r.results_url,{...n,headers:K([{Accept:"application/binary"},n==null?void 0:n.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((s,i)=>lp.fromResponse(i.response,i.controller))}}class vb extends gt{constructor(){super(...arguments),this.batches=new oR(this._client)}create(e,n){e.model in JA&&console.warn(`The model '${e.model}' is deprecated and will reach end-of-life on ${JA[e.model]}
|
|
605
|
-
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),K7.includes(e.model)&&e.thinking&&e.thinking.type==="enabled"&&console.warn(`Using Claude with ${e.model} and 'thinking.type=enabled' is deprecated. Use 'thinking.type=adaptive' instead which results in better model performance in our testing: https://platform.claude.com/docs/en/build-with-claude/adaptive-thinking`);let r=this._client._options.timeout;if(!e.stream&&r==null){const i=Z$[e.model]??void 0;r=this._client.calculateNonstreamingTimeout(e.max_tokens,i)}const s=N$(e.tools,e.messages);return this._client.post("/v1/messages",{body:e,timeout:r??6e5,...n,headers:K([s,n==null?void 0:n.headers]),stream:e.stream??!1})}parse(e,n){return this.create(e,n).then(r=>aR(r,e,{logger:this._client.logger??console}))}stream(e,n){return ff.createMessage(this,e,n,{logger:this._client.logger??console})}countTokens(e,n){return this._client.post("/v1/messages/count_tokens",{body:e,...n})}}const JA={"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"},K7=["claude-mythos-preview","claude-opus-4-6"];vb.Batches=oR;class cR extends gt{retrieve(e,n={},r){const{betas:s}=n??{};return this._client.get(le`/v1/models/${e}`,{...r,headers:K([{...(s==null?void 0:s.toString())!=null?{"anthropic-beta":s==null?void 0:s.toString()}:void 0},r==null?void 0:r.headers])})}list(e={},n){const{betas:r,...s}=e??{};return this._client.getAPIList("/v1/models",Ll,{query:s,...n,headers:K([{...(r==null?void 0:r.toString())!=null?{"anthropic-beta":r==null?void 0:r.toString()}:void 0},n==null?void 0:n.headers])})}}var K_,Sb,mh,uR;const W7="\\n\\nHuman:",Z7="\\n\\nAssistant:";class jt{get credentials(){return this._authState.provider}constructor({baseURL:e=it("ANTHROPIC_BASE_URL"),apiKey:n,authToken:r,webhookKey:s=it("ANTHROPIC_WEBHOOK_SIGNING_KEY")??null,...i}={}){if(K_.add(this),this._requestAuthFlags=new WeakMap,mh.set(this,void 0),n===void 0&&(n=i.profile!=null?null:it("ANTHROPIC_API_KEY")??null),r===void 0&&(r=i.profile!=null?null:it("ANTHROPIC_AUTH_TOKEN")??null),i.profile!=null&&(i.credentials!=null||i.config!=null))throw new TypeError("Pass at most one of `profile`, `credentials`, or `config`.");const a={apiKey:n,authToken:r,webhookKey:s,...i,baseURL:e||"https://api.anthropic.com"};if(!a.dangerouslyAllowBrowser&&CG())throw new ke(`It looks like you're running in a browser-like environment.
|
|
606
|
-
|
|
607
|
-
This is disabled by default, as it risks exposing your secret API credentials to attackers.
|
|
608
|
-
If you understand the risks and have appropriate mitigations in place,
|
|
609
|
-
you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
|
|
610
|
-
|
|
611
|
-
new Anthropic({ apiKey, dangerouslyAllowBrowser: true });
|
|
612
|
-
`);this.baseURL=a.baseURL,this._baseURLIsExplicit=i.__baseURLIsExplicit??!!e,this.timeout=a.timeout??Sb.DEFAULT_TIMEOUT,this.logger=a.logger??console;const o="warn";this.logLevel=o,this.logLevel=kA(a.logLevel,"ClientOptions.logLevel",this)??kA(it("ANTHROPIC_LOG"),"process.env['ANTHROPIC_LOG']",this)??o,this.fetchOptions=a.fetchOptions,this.maxRetries=a.maxRetries??2,this.fetch=a.fetch??PG(),oe(this,mh,MG);const c=it("ANTHROPIC_CUSTOM_HEADERS");if(c){const l={};for(const d of c.split(`
|
|
613
|
-
`)){const f=d.indexOf(":");f>=0&&(l[d.substring(0,f).trim()]=d.substring(f+1).trim())}a.defaultHeaders={...l,...a.defaultHeaders}}const u=i.__auth;if(delete a.__auth,delete a.__baseURLIsExplicit,this._options=a,this.apiKey=typeof n=="string"?n:null,this.authToken=r,this.webhookKey=s,u)this._authState=u,!this._baseURLIsExplicit&&u.baseURL&&(this.baseURL=u.baseURL);else if(this._authState={provider:null,tokenCache:null,resolution:null,error:null,extraHeaders:{}},this.apiKey==null&&this.authToken==null){const l=a.credentials??null;if(l)this._authState.provider=l,this._authState.tokenCache=this._makeTokenCache(l);else if(a.config!=null){const d=A$(a.config,this._credentialResolverOptions());this._authState.provider=d.provider,this._authState.tokenCache=this._makeTokenCache(d.provider),this._authState.extraHeaders=d.extraHeaders,this._applyCredentialBaseURL(d.baseURL)}else a.profile!=null?this._authState.resolution=this._resolveDefaultCredentials(a.profile):this._authState.resolution=this._resolveDefaultCredentials()}}_applyCredentialBaseURL(e){if(!e)return;const n=e.replace(/\/+$/,"");this._authState.baseURL=n,this._baseURLIsExplicit||(this.baseURL=n)}_credentialResolverOptions(){return{baseURL:this.baseURL,fetch:this.fetch,userAgent:this.getUserAgent(),onCacheWriteError:e=>{Yt(this).debug("credential cache write failed (best-effort)",e)},onSafetyWarning:e=>{Yt(this).warn(e)}}}_makeTokenCache(e){return new JG(e,n=>{Yt(this).debug("advisory token refresh failed; serving cached token",n)})}withOptions(e){const n="credentials"in e||"config"in e||"profile"in e,r="apiKey"in e||"authToken"in e||n,s={...this._options,...this._baseURLIsExplicit?{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,webhookKey:this.webhookKey,credentials:this.credentials,...n?{credentials:void 0,config:void 0,profile:void 0}:{},...e,__auth:r?void 0:this._authState,__baseURLIsExplicit:"baseURL"in e?!0:this._baseURLIsExplicit};return new this.constructor(s)}async _resolveDefaultCredentials(e){try{const n=await a7(this._credentialResolverOptions(),e);if(n)this._authState.provider=n.provider,this._authState.tokenCache=this._makeTokenCache(n.provider),this._authState.extraHeaders=n.extraHeaders,this._applyCredentialBaseURL(n.baseURL);else if(e!=null)throw new ke(`Profile "${e}" could not be resolved (no <config_dir>/configs/${e}.json found).`)}catch(n){this._authState.error=n}finally{this._authState.resolution=null}}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:n}){if(!(e.get("x-api-key")||e.get("authorization"))){if(this._authState.error)throw this._authState.error;if(!(this._authState.tokenCache||this._authState.resolution)&&!(this.apiKey&&e.get("x-api-key"))&&!n.has("x-api-key")&&!(this.authToken&&e.get("authorization"))&&!n.has("authorization"))throw new Error('Could not resolve authentication method. Expected one of apiKey, authToken, credentials, config, or profile to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted')}}_authFlags(e){let n=this._requestAuthFlags.get(e);return n||(n={usedTokenCache:!1,didRefreshFor401:!1},this._requestAuthFlags.set(e,n)),n}async authHeaders(e){if(this._authState.resolution&&await this._authState.resolution,!this._authState.error){if(this._authState.tokenCache&&this.apiKey==null){const n=await this._authState.tokenCache.getToken();return this._authFlags(e).usedTokenCache=!0,K([{Authorization:`Bearer ${n}`}])}return K([await this.apiKeyAuth(e),await this.bearerAuth(e)])}}async apiKeyAuth(e){if(this.apiKey!=null)return K([{"X-Api-Key":this.apiKey}])}async bearerAuth(e){if(this.authToken!=null)return K([{Authorization:`Bearer ${this.authToken}`}])}stringifyQuery(e){return zG(e)}getUserAgent(){return`${this.constructor.name}/JS ${di}`}defaultIdempotencyKey(){return`stainless-node-retry-${Y1()}`}makeStatusError(e,n,r,s){return Tn.generate(e,n,r,s)}buildURL(e,n,r){const s=!P(this,K_,"m",uR).call(this)&&r||this.baseURL,i=EG(e)?new URL(e):new URL(s+(s.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),a=this.defaultQuery(),o=Object.fromEntries(i.searchParams);return(!_A(a)||!_A(o))&&(n={...o,...a,...n}),typeof n=="object"&&n&&!Array.isArray(n)&&(i.search=this.stringifyQuery(n)),i.toString()}_calculateNonstreamingTimeout(e){if(3600*e/128e3>600)throw new ke("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#streaming-responses for more details");return 600*1e3}async prepareOptions(e){}async prepareRequest(e,{url:n,options:r}){var s;if(this._authState.tokenCache&&this.apiKey==null){const i=e.headers instanceof Headers?e.headers:new Headers(e.headers);for(const[o,c]of Object.entries(this._authState.extraHeaders))i.has(o)||i.set(o,c);const a=(s=i.get("anthropic-beta"))==null?void 0:s.split(",").map(o=>o.trim());a!=null&&a.includes(lf)||i.append("anthropic-beta",lf),e.headers=i}}get(e,n){return this.methodRequest("get",e,n)}post(e,n){return this.methodRequest("post",e,n)}patch(e,n){return this.methodRequest("patch",e,n)}put(e,n){return this.methodRequest("put",e,n)}delete(e,n){return this.methodRequest("delete",e,n)}methodRequest(e,n,r){return this.request(Promise.resolve(r).then(s=>({method:e,path:n,...s})))}request(e,n=null){return new op(this,this.makeRequest(e,n,void 0))}async makeRequest(e,n,r){var b,_;const s=await e,i=s.maxRetries??this.maxRetries;n==null&&(n=i,this._requestAuthFlags.delete(s)),await this.prepareOptions(s);const{req:a,url:o,timeout:c}=await this.buildRequest(s,{retryCount:i-n});await this.prepareRequest(a,{url:o,options:s});const u="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),l=r===void 0?"":`, retryOf: ${r}`,d=Date.now();if(Yt(this).debug(`[${u}] sending request`,qi({retryOfRequestLogID:r,method:s.method,url:o,options:s,headers:a.headers})),(b=s.signal)!=null&&b.aborted)throw new qr;const f=new AbortController,h=await this.fetchWithTimeout(o,a,c,f).catch(U_),p=Date.now();if(h instanceof globalThis.Error){const w=`retrying, ${n} attempts remaining`;if((_=s.signal)!=null&&_.aborted)throw new qr;const v=qu(h)||/timed? ?out/i.test(String(h)+("cause"in h?String(h.cause):""));if(n)return Yt(this).info(`[${u}] connection ${v?"timed out":"failed"} - ${w}`),Yt(this).debug(`[${u}] connection ${v?"timed out":"failed"} (${w})`,qi({retryOfRequestLogID:r,url:o,durationMs:p-d,message:h.message})),this.retryRequest(s,n,r??u);throw Yt(this).info(`[${u}] connection ${v?"timed out":"failed"} - error; no more retries left`),Yt(this).debug(`[${u}] connection ${v?"timed out":"failed"} (error; no more retries left)`,qi({retryOfRequestLogID:r,url:o,durationMs:p-d,message:h.message})),v?new X1:new ap({cause:h})}const g=[...h.headers.entries()].filter(([w])=>w==="request-id").map(([w,v])=>", "+w+": "+JSON.stringify(v)).join(""),y=`[${u}${l}${g}] ${a.method} ${o} ${h.ok?"succeeded":"failed"} with status ${h.status} in ${p-d}ms`;if(!h.ok){const w=await this.shouldRetry(h,s);if(n&&w){const $=`retrying, ${n} attempts remaining`;return await NG(h.body),Yt(this).info(`${y} - ${$}`),Yt(this).debug(`[${u}] response error (${$})`,qi({retryOfRequestLogID:r,url:h.url,status:h.status,headers:h.headers,durationMs:p-d})),this.retryRequest(s,n,r??u,h.headers)}const v=w?"error; no more retries left":"error; not retryable";Yt(this).info(`${y} - ${v}`);const A=await h.text().catch($=>U_($).message),S=o$(A),x=S?void 0:A;throw Yt(this).debug(`[${u}] response error (${v})`,qi({retryOfRequestLogID:r,url:h.url,status:h.status,headers:h.headers,message:x,durationMs:Date.now()-d})),this.makeStatusError(h.status,S,x,h.headers)}return Yt(this).info(y),Yt(this).debug(`[${u}] response start`,qi({retryOfRequestLogID:r,url:h.url,status:h.status,headers:h.headers,durationMs:p-d})),{response:h,options:s,controller:f,requestLogID:u,retryOfRequestLogID:r,startTime:d}}getAPIList(e,n,r){return this.requestAPIList(n,r&&"then"in r?r.then(s=>({method:"get",path:e,...s})):{method:"get",path:e,...r})}requestAPIList(e,n){const r=this.makeRequest(n,null,void 0);return new g7(this,r,e)}async fetchWithTimeout(e,n,r,s){const{signal:i,method:a,...o}=n||{},c=this._makeAbort(s);i&&i.addEventListener("abort",c,{once:!0});const u=setTimeout(c,r),l=globalThis.ReadableStream&&o.body instanceof globalThis.ReadableStream||typeof o.body=="object"&&o.body!==null&&Symbol.asyncIterator in o.body,d={signal:s.signal,...l?{duplex:"half"}:{},method:"GET",...o};a&&(d.method=a.toUpperCase());try{return await this.fetch.call(void 0,e,d)}finally{clearTimeout(u)}}async shouldRetry(e,n){const r=this._authFlags(n);if(e.status===401&&this._authState.tokenCache&&r.usedTokenCache&&!r.didRefreshFor401)return r.didRefreshFor401=!0,this._authState.tokenCache.invalidate(),!0;const s=e.headers.get("x-should-retry");return s==="true"?!0:s==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,n,r,s){let i;const a=s==null?void 0:s.get("retry-after-ms");if(a){const c=parseFloat(a);Number.isNaN(c)||(i=c)}const o=s==null?void 0:s.get("retry-after");if(o&&!i){const c=parseFloat(o);Number.isNaN(c)?i=Date.parse(o)-Date.now():i=c*1e3}if(i===void 0){const c=e.maxRetries??this.maxRetries;i=this.calculateDefaultRetryTimeoutMillis(n,c)}return await kG(i),this.makeRequest(e,n-1,r)}calculateDefaultRetryTimeoutMillis(e,n){const i=n-e,a=Math.min(.5*Math.pow(2,i),8),o=1-Math.random()*.25;return a*o*1e3}calculateNonstreamingTimeout(e,n){if(36e5*e/128e3>6e5||n!=null&&e>n)throw new ke("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#long-requests for more details");return 6e5}async buildRequest(e,{retryCount:n=0}={}){const r={...e},{method:s,path:i,query:a,defaultBaseURL:o}=r;this._authState.resolution&&await this._authState.resolution,!this._baseURLIsExplicit&&this._authState.baseURL&&this.baseURL!==this._authState.baseURL&&(this.baseURL=this._authState.baseURL);const c=this.buildURL(i,a,o);"timeout"in r&&xG("timeout",r.timeout),r.timeout=r.timeout??this.timeout;const{bodyHeaders:u,body:l}=this.buildBody({options:r}),d=await this.buildHeaders({options:e,method:s,bodyHeaders:u,retryCount:n});return{req:{method:s,headers:d,...r.signal&&{signal:r.signal},...globalThis.ReadableStream&&l instanceof globalThis.ReadableStream&&{duplex:"half"},...l&&{body:l},...this.fetchOptions??{},...r.fetchOptions??{}},url:c,timeout:r.timeout}}async buildHeaders({options:e,method:n,bodyHeaders:r,retryCount:s}){let i={};this.idempotencyHeader&&n!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),i[this.idempotencyHeader]=e.idempotencyKey);const a=K([i,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(s),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...ub(),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":"true"}:void 0,"anthropic-version":"2023-06-01"},await this.authHeaders(e),this._options.defaultHeaders,r,e.headers]);return this.validateHeaders(a),a.values}_makeAbort(e){return()=>e.abort()}buildBody({options:{body:e,headers:n}}){if(!e)return{bodyHeaders:void 0,body:void 0};const r=K([n]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&r.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:typeof e=="object"&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")?{bodyHeaders:void 0,body:u$(e)}:typeof e=="object"&&r.values.get("content-type")==="application/x-www-form-urlencoded"?{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(e)}:P(this,mh,"f").call(this,{body:e,headers:r})}}Sb=jt,mh=new WeakMap,K_=new WeakSet,uR=function(){return this.baseURL!=="https://api.anthropic.com"};jt.Anthropic=Sb;jt.HUMAN_PROMPT=W7;jt.AI_PROMPT=Z7;jt.DEFAULT_TIMEOUT=6e5;jt.AnthropicError=ke;jt.APIError=Tn;jt.APIConnectionError=ap;jt.APIConnectionTimeoutError=X1;jt.APIUserAbortError=qr;jt.NotFoundError=n$;jt.ConflictError=r$;jt.RateLimitError=i$;jt.BadRequestError=Q1;jt.AuthenticationError=e$;jt.InternalServerError=a$;jt.PermissionDeniedError=t$;jt.UnprocessableEntityError=s$;jt.toFile=S7;class Fl extends jt{constructor(){super(...arguments),this.completions=new sR(this),this.messages=new vb(this),this.models=new cR(this),this.beta=new gr(this)}}Fl.Completions=sR;Fl.Messages=vb;Fl.Models=cR;Fl.Beta=gr;const q7=t=>t,G7={"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},YA=4096;function J7(t){var e;return t?((e=Object.entries(G7).find(([n])=>t.startsWith(n)))==null?void 0:e[1])??YA:YA}function Y7(t){return!!(t.tools&&t.tools.length>0)}function X7(t){var e;for(const n of t.messages??[])if(typeof n.content!="string"){for(const r of n.content??[])if(typeof r=="object"&&r!=null&&r.type==="document"&&typeof r.citations=="object"&&((e=r.citations)!=null&&e.enabled))return!0}return!1}function Q7(t){return!!(t.thinking&&(t.thinking.type==="enabled"||t.thinking.type==="adaptive"))}function eJ(t){var e,n;return!!((n=(e=t.context_management)==null?void 0:e.edits)!=null&&n.some(r=>r.type==="compact_20260112"))}function tJ(t){return"input_schema"in t}function nJ(t){return typeof t=="object"&&t!==null&&"type"in t&&("name"in t||"mcp_server_name"in t)&&typeof t.type=="string"&&["text_editor_","computer_","bash_","web_search_","web_fetch_","str_replace_editor_","str_replace_based_edit_tool_","code_execution_","memory_","tool_search_","mcp_toolset"].some(e=>typeof t.type=="string"&&t.type.startsWith(e))}function rJ(t,e,...n){return Array.from(new Set([...t??[],...e??[],...n.flatMap(r=>Array.from(r))]))}function sJ(t){if(typeof t.content=="string")return t.content;if(Array.isArray(t.content)&&t.content.length>=1&&"input"in t.content[0])return typeof t.content[0].input=="string"?t.content[0].input:JSON.stringify(t.content[0].input);if(Array.isArray(t.content)&&t.content.length>=1&&"text"in t.content[0]&&typeof t.content[0].text=="string")return t.content[0].text}var iJ=class extends Es{constructor(e,n){const r=typeof e=="string"?{...n??{},model:e}:e??{};super(r??{});m(this,"lc_serializable",!0);m(this,"anthropicApiKey");m(this,"apiKey");m(this,"apiUrl");m(this,"temperature");m(this,"topK");m(this,"topP");m(this,"maxTokens");m(this,"modelName","claude-sonnet-4-5-20250929");m(this,"model","claude-sonnet-4-5-20250929");m(this,"invocationKwargs");m(this,"stopSequences");m(this,"streaming",!1);m(this,"clientOptions");m(this,"thinking",{type:"disabled"});m(this,"contextManagement");m(this,"outputConfig");m(this,"inferenceGeo");m(this,"batchClient");m(this,"streamingClient");m(this,"streamUsage",!0);m(this,"betas");m(this,"createClient");if(this._addVersion("@langchain/anthropic","1.4.0"),this.anthropicApiKey=(r==null?void 0:r.apiKey)??(r==null?void 0:r.anthropicApiKey)??Mt("ANTHROPIC_API_KEY"),!this.anthropicApiKey&&!(r!=null&&r.createClient))throw new Error("Anthropic API key not found");this.clientOptions=(r==null?void 0:r.clientOptions)??{},this.apiKey=this.anthropicApiKey,this.apiUrl=r==null?void 0:r.anthropicApiUrl,this.modelName=(r==null?void 0:r.model)??(r==null?void 0:r.modelName)??this.model,this.model=this.modelName,this.invocationKwargs=(r==null?void 0:r.invocationKwargs)??{},this.topP=(r==null?void 0:r.topP)??this.topP,this.temperature=(r==null?void 0:r.temperature)??this.temperature,this.topK=(r==null?void 0:r.topK)??this.topK,this.maxTokens=(r==null?void 0:r.maxTokens)??J7(this.model),this.stopSequences=(r==null?void 0:r.stopSequences)??this.stopSequences,this.streaming=(r==null?void 0:r.streaming)??!1,this.streamUsage=(r==null?void 0:r.streamUsage)??this.streamUsage,this.thinking=(r==null?void 0:r.thinking)??this.thinking,this.contextManagement=(r==null?void 0:r.contextManagement)??this.contextManagement,this.outputConfig=(r==null?void 0:r.outputConfig)??this.outputConfig,this.inferenceGeo=(r==null?void 0:r.inferenceGeo)??this.inferenceGeo,this.betas=(r==null?void 0:r.betas)??this.betas,this.createClient=(r==null?void 0:r.createClient)??(s=>new Fl(s))}static lc_name(){return"ChatAnthropic"}get lc_secrets(){return{anthropicApiKey:"ANTHROPIC_API_KEY",apiKey:"ANTHROPIC_API_KEY"}}get lc_aliases(){return{modelName:"model"}}getLsParams(e){const n=this.invocationParams(e);return{ls_provider:"anthropic",ls_model_name:this.model,ls_model_type:"chat",ls_temperature:n.temperature??void 0,ls_max_tokens:n.max_tokens??void 0,ls_stop:e.stop}}formatStructuredToolToAnthropic(e,n){if(e)return e.map(r=>{var s;if(Zs(r)&&((s=r.extras)!=null&&s.providerToolDefinition))return r.extras.providerToolDefinition;if(nJ(r))return r;if(tJ(r))return(n==null?void 0:n.strict)!==void 0?{...r,strict:n.strict}:r;if(Xo(r)){const i="strict"in r.function&&typeof r.function.strict=="boolean"?r.function.strict:void 0,a=(n==null?void 0:n.strict)??i;return{name:r.function.name,description:r.function.description,input_schema:r.function.parameters,...a!==void 0?{strict:a}:{}}}if(Zs(r)){const{strict:i,...a}=r.extras?Xq.parse(r.extras):{},o=(n==null?void 0:n.strict)??i;return{name:r.name,description:r.description,input_schema:Wt(r.schema)?mt(r.schema):r.schema,...a,...o!==void 0?{strict:o}:{}}}throw new Error(`Unknown tool type passed to ChatAnthropic: ${JSON.stringify(r,null,2)}`)})}bindTools(e,n){return this.withConfig({tools:this.formatStructuredToolToAnthropic(e,{strict:n==null?void 0:n.strict}),...n})}invocationParams(e){var c,u,l;const n=Yq(e==null?void 0:e.tool_choice),r=(c=e==null?void 0:e.tools)==null?void 0:c.reduce((d,f)=>{if(typeof f=="object"&&"type"in f&&f.type in fA){const h=fA[f.type];if(!d.includes(h))return[...d,h]}return d},[]),s=(()=>{const d={...this.outputConfig,...e==null?void 0:e.outputConfig};return e!=null&&e.outputFormat&&!d.format&&(d.format=e.outputFormat),Object.keys(d).length>0?d:void 0})(),i=(l=(u=this.contextManagement)==null?void 0:u.edits)!=null&&l.some(d=>d.type==="compact_20260112")?["compact-2026-01-12"]:[],a=hG(this.model,s),o={model:this.model,stop_sequences:(e==null?void 0:e.stop)??this.stopSequences,stream:this.streaming,max_tokens:this.maxTokens,tools:this.formatStructuredToolToAnthropic(e==null?void 0:e.tools,{strict:e==null?void 0:e.strict}),tool_choice:n,thinking:this.thinking,context_management:this.contextManagement,...this.invocationKwargs,container:e==null?void 0:e.container,betas:rJ(this.betas,e==null?void 0:e.betas,r??[],i,a),output_config:s,inference_geo:(e==null?void 0:e.inferenceGeo)??this.inferenceGeo,mcp_servers:e==null?void 0:e.mcp_servers,cache_control:e==null?void 0:e.cache_control};return fG({model:this.model,thinking:this.thinking,topK:this.topK,topP:this.topP,temperature:this.temperature}),Object.assign(o,pG({model:this.model,thinking:this.thinking,topK:this.topK,topP:this.topP,temperature:this.temperature})),o}_identifyingParams(){return{model_name:this.model,...this.invocationParams()}}identifyingParams(){return{model_name:this.model,...this.invocationParams()}}async*_streamResponseChunks(e,n,r){var u;const s=this.invocationParams(n),i=xm(e),a={...s,...i,stream:!0},o=!Y7(a)&&!X7(a)&&!Q7(a)&&!eJ(a),c=await this.createStreamWithRetry(a,{headers:n.headers,signal:n.signal});for await(const l of c){if((u=n.signal)!=null&&u.aborted){c.controller.abort();return}const d=this.streamUsage??n.streamUsage,f=mG(l,{streamUsage:d,coerceContentToString:o});if(!f)continue;const{chunk:h}=f,p=sJ(h),g=new dr({message:new Ge({content:h.content,additional_kwargs:h.additional_kwargs,tool_call_chunks:h.tool_call_chunks,usage_metadata:d?h.usage_metadata:void 0,response_metadata:h.response_metadata,id:h.id}),text:p??""});yield g,await(r==null?void 0:r.handleLLMNewToken(p??"",void 0,void 0,void 0,void 0,{chunk:g}))}}async*_streamChatModelEvents(e,n,r){const s=this.invocationParams(n),i=xm(e),a={...s,...i,stream:!0},o=await this.createStreamWithRetry(a,{headers:n.headers,signal:n.signal}),c=this.streamUsage??n.streamUsage;yield*yG(async function*(l,d){var f;for await(const h of l){if(d!=null&&d.aborted){(f=l.controller)==null||f.abort();return}yield h}}(o,n.signal),{streamUsage:c??!0})}async _generateNonStreaming(e,n,r){const s=xm(e),{content:i,...a}=await this.completionWithRetry({...n,stream:!1,...s},r),o=gG(i,a),{role:c,type:u,...l}=a;return{generations:o,llmOutput:l}}async _generate(e,n,r){var i;if((i=n.signal)==null||i.throwIfAborted(),this.stopSequences&&n.stop)throw new Error('"stopSequence" parameter found in input and default params');const s=this.invocationParams(n);if(s.stream){let a;const o=this._streamResponseChunks(e,n,r);for await(const c of o)a===void 0?a=c:a=a.concat(c);if(a===void 0)throw new Error("No chunks returned from Anthropic API.");return{generations:[{text:a.text,message:a.message}]}}else return this._generateNonStreaming(e,s,{signal:n.signal,headers:n.headers})}async createStreamWithRetry(e,n){if(!this.streamingClient){const a=this.apiUrl?{baseURL:this.apiUrl}:void 0;this.streamingClient=this.createClient({dangerouslyAllowBrowser:!0,...this.clientOptions,...a,apiKey:this.apiKey,maxRetries:0})}const{betas:r,...s}=e,i=async()=>{var a;try{return(a=e==null?void 0:e.betas)!=null&&a.length?await this.streamingClient.beta.messages.create({...s,betas:r,...this.invocationKwargs,stream:!0},n):await this.streamingClient.messages.create({...s,...this.invocationKwargs,stream:!0},n)}catch(o){throw mA(o)}};return this.caller.call(i)}async completionWithRetry(e,n){if(!this.batchClient){const a=this.apiUrl?{baseURL:this.apiUrl}:void 0;this.batchClient=this.createClient({dangerouslyAllowBrowser:!0,...this.clientOptions,...a,apiKey:this.apiKey,maxRetries:0})}const{betas:r,...s}=e,i=async()=>{var a;try{return(a=e==null?void 0:e.betas)!=null&&a.length?await this.batchClient.beta.messages.create({...s,...this.invocationKwargs,betas:r},n):await this.batchClient.messages.create({...s,...this.invocationKwargs},n)}catch(o){throw mA(o)}};return this.caller.callWithOptions({signal:n.signal??void 0},i)}_llmType(){return"anthropic"}get profile(){return _G[this.model]??{}}withStructuredOutput(e,n){var u,l;let r,s;const{schema:i,name:a,includeRaw:o}={...n,schema:e};let c=(n==null?void 0:n.method)??"functionCalling";if((n==null?void 0:n.strict)!==void 0&&c!=="functionCalling")throw new Error(`Argument \`strict\` is only supported for \`method\` = "functionCalling" on Anthropic models. Got method = "${c}".`);if(c==="jsonMode"&&(console.warn('"jsonMode" is not supported for Anthropic models. Falling back to "jsonSchema".'),c="jsonSchema"),c==="jsonSchema"){s=Ko(i);const d=q7(mt(i));r=this.withConfig({outputVersion:"v0",outputConfig:{format:{type:"json_schema",schema:d}},ls_structured_output_format:{kwargs:{method:"json_schema"},schema:d}})}else if(c==="functionCalling"){let d=a??"extract",f;if(Wt(i)||Or(i)){const h=mt(i);f=[{name:d,description:h.description??"A function available to call.",input_schema:h}]}else typeof i.name=="string"&&typeof i.description=="string"&&typeof i.input_schema=="object"&&i.input_schema!=null?(f=[i],d=i.name):f=[{name:d,description:i.description??"",input_schema:i}];if(s=Tl(i,d,Jq),((u=this.thinking)==null?void 0:u.type)==="enabled"||((l=this.thinking)==null?void 0:l.type)==="adaptive"){const h="Anthropic structured output relies on forced tool calling, which is not supported when `thinking` is enabled. This method will raise OutputParserException if tool calls are not generated. Consider disabling `thinking` or adjust your prompt to ensure the tool is called.";console.warn(h),r=this.withConfig({outputVersion:"v0",tools:f,ls_structured_output_format:{kwargs:{method:"functionCalling"},schema:mt(i)},...(n==null?void 0:n.strict)!==void 0?{strict:n.strict}:{}});const p=g=>{if(!g.tool_calls||g.tool_calls.length===0)throw new Error(h);return g};r=r.pipe(p)}else r=this.withConfig({outputVersion:"v0",tools:f,tool_choice:{type:"tool",name:d},ls_structured_output_format:{kwargs:{method:"functionCalling"},schema:mt(i)},...(n==null?void 0:n.strict)!==void 0?{strict:n.strict}:{}})}else throw new TypeError(`Unrecognized structured output method '${c}'. Expected 'functionCalling' or 'jsonSchema'`);return tc(r,s,o,o?"StructuredOutputRunnable":"ChatAnthropicStructuredOutput")}},XA=class extends iJ{};const aJ=$e({command:Ue("view"),path:Ke()}),oJ=$e({command:Ue("create"),path:Ke(),file_text:Ke()}),cJ=$e({command:Ue("str_replace"),path:Ke(),old_str:Ke(),new_str:Ke()}),uJ=$e({command:Ue("insert"),path:Ke(),insert_line:ot(),insert_text:Ke()}),lJ=$e({command:Ue("delete"),path:Ke()}),dJ=$e({command:Ue("rename"),old_path:Ke(),new_path:Ke()});Ff("command",[aJ,oJ,cJ,uJ,lJ,dJ]);const hJ=$e({command:Ue("view"),path:Ke(),view_range:pw([ot(),ot()]).optional()}),fJ=$e({command:Ue("str_replace"),path:Ke(),old_str:Ke(),new_str:Ke()}),pJ=$e({command:Ue("create"),path:Ke(),file_text:Ke()}),mJ=$e({command:Ue("insert"),path:Ke(),insert_line:ot(),new_str:Ke()});Ff("command",[hJ,fJ,pJ,mJ]);const Xr=pw([ot(),ot()]),lR=$e({action:Ue("screenshot")}),dR=$e({action:Ue("left_click"),coordinate:Xr}),hR=$e({action:Ue("right_click"),coordinate:Xr}),fR=$e({action:Ue("middle_click"),coordinate:Xr}),pR=$e({action:Ue("double_click"),coordinate:Xr}),mR=$e({action:Ue("triple_click"),coordinate:Xr}),gR=$e({action:Ue("left_click_drag"),start_coordinate:Xr,end_coordinate:Xr}),_R=$e({action:Ue("left_mouse_down"),coordinate:Xr}),yR=$e({action:Ue("left_mouse_up"),coordinate:Xr}),wR=$e({action:Ue("scroll"),coordinate:Xr,scroll_direction:Bf(["up","down","left","right"]),scroll_amount:ot()}),bR=$e({action:Ue("type"),text:Ke()}),vR=$e({action:Ue("key"),key:Ke()}),SR=$e({action:Ue("mouse_move"),coordinate:Xr}),AR=$e({action:Ue("hold_key"),key:Ke()}),TR=$e({action:Ue("wait"),duration:ot().optional()}),gJ=$e({action:Ue("zoom"),region:pw([ot(),ot(),ot(),ot()])});Ff("action",[lR,dR,hR,fR,pR,mR,gR,_R,yR,wR,bR,vR,SR,AR,TR]);Ff("action",[lR,dR,hR,fR,pR,mR,gR,_R,yR,wR,bR,vR,SR,AR,TR,gJ]);const _J=$e({command:Ke().describe("The bash command to run")}),yJ=$e({restart:Ue(!0).describe("Set to true to restart the bash session")});kl([_J,yJ]);function wJ(t,e){var n;return new Ge({content:t.content??"",additional_kwargs:t.thinking&&t.thinking!==""?{reasoning_content:t.thinking}:{},tool_call_chunks:(n=t.tool_calls)==null?void 0:n.map(r=>({name:r.function.name,args:JSON.stringify(r.function.arguments),type:"tool_call_chunk",index:0,id:pl()})),response_metadata:{...e==null?void 0:e.responseMetadata,model_provider:"ollama"},usage_metadata:e==null?void 0:e.usageMetadata})}function QA(t){const e=t.match(/^data:.*?;base64,(.*)$/);return e?e[1]:""}function bJ(t){var r,s,i,a;if(typeof t.content=="string"){if((r=t.tool_calls)!=null&&r.length){const o=t.tool_calls.map(c=>({id:c.id,type:"function",function:{name:c.name,arguments:c.args}}));return[{role:"assistant",content:t.content,tool_calls:o}]}return[{role:"assistant",content:t.content}]}const e=t.content.filter(o=>o.type==="text"&&typeof o.text=="string").map(o=>({role:"assistant",content:o.text}));let n;if(t.content.find(o=>o.type==="tool_use")&&((s=t.tool_calls)!=null&&s.length)){const o=(i=t.tool_calls)==null?void 0:i.map(c=>({id:c.id,type:"function",function:{name:c.name,arguments:c.args}}));o&&(n={role:"assistant",tool_calls:o,content:""})}else if(t.content.find(o=>o.type==="tool_use")&&!((a=t.tool_calls)!=null&&a.length))throw new Error("'tool_use' content type is not supported without tool calls.");return[...e,...n?[n]:[]]}function vJ(t){return typeof t.content=="string"?[{role:"user",content:t.content}]:t.content.map(e=>{if(e.type==="text")return{role:"user",content:e.text};if(e.type==="image_url"){if(typeof e.image_url=="string")return{role:"user",content:"",images:[QA(e.image_url)]};if(e.image_url.url&&typeof e.image_url.url=="string")return{role:"user",content:"",images:[QA(e.image_url.url)]}}throw new Error(`Unsupported content type: ${e.type}`)})}function SJ(t){if(typeof t.content=="string")return[{role:"system",content:t.content}];if(t.content.every(e=>e.type==="text"&&typeof e.text=="string"))return t.content.map(e=>({role:"system",content:e.text}));throw new Error(`Unsupported content type(s): ${t.content.map(e=>e.type).join(", ")}`)}function AJ(t){if(typeof t.content!="string")throw new Error("Non string tool message content is not supported");return[{role:"tool",content:t.content}]}function TJ(t){return t.flatMap(e=>{if(["human","generic"].includes(e._getType()))return vJ(e);if(e._getType()==="ai")return bJ(e);if(e._getType()==="system")return SJ(e);if(e._getType()==="tool")return AJ(e);throw new Error(`Unsupported message type: ${e._getType()}`)})}var ln=typeof globalThis<"u"&&globalThis||typeof self<"u"&&self||typeof global<"u"&&global||{},Rn={searchParams:"URLSearchParams"in ln,iterable:"Symbol"in ln&&"iterator"in Symbol,blob:"FileReader"in ln&&"Blob"in ln&&function(){try{return new Blob,!0}catch{return!1}}(),formData:"FormData"in ln,arrayBuffer:"ArrayBuffer"in ln};function EJ(t){return t&&DataView.prototype.isPrototypeOf(t)}if(Rn.arrayBuffer)var IJ=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],xJ=ArrayBuffer.isView||function(t){return t&&IJ.indexOf(Object.prototype.toString.call(t))>-1};function ac(t){if(typeof t!="string"&&(t=String(t)),/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(t)||t==="")throw new TypeError('Invalid character in header field name: "'+t+'"');return t.toLowerCase()}function Ab(t){return typeof t!="string"&&(t=String(t)),t}function Tb(t){var e={next:function(){var n=t.shift();return{done:n===void 0,value:n}}};return Rn.iterable&&(e[Symbol.iterator]=function(){return e}),e}function Zt(t){this.map={},t instanceof Zt?t.forEach(function(e,n){this.append(n,e)},this):Array.isArray(t)?t.forEach(function(e){if(e.length!=2)throw new TypeError("Headers constructor: expected name/value pair to be length 2, found"+e.length);this.append(e[0],e[1])},this):t&&Object.getOwnPropertyNames(t).forEach(function(e){this.append(e,t[e])},this)}Zt.prototype.append=function(t,e){t=ac(t),e=Ab(e);var n=this.map[t];this.map[t]=n?n+", "+e:e};Zt.prototype.delete=function(t){delete this.map[ac(t)]};Zt.prototype.get=function(t){return t=ac(t),this.has(t)?this.map[t]:null};Zt.prototype.has=function(t){return this.map.hasOwnProperty(ac(t))};Zt.prototype.set=function(t,e){this.map[ac(t)]=Ab(e)};Zt.prototype.forEach=function(t,e){for(var n in this.map)this.map.hasOwnProperty(n)&&t.call(e,this.map[n],n,this)};Zt.prototype.keys=function(){var t=[];return this.forEach(function(e,n){t.push(n)}),Tb(t)};Zt.prototype.values=function(){var t=[];return this.forEach(function(e){t.push(e)}),Tb(t)};Zt.prototype.entries=function(){var t=[];return this.forEach(function(e,n){t.push([n,e])}),Tb(t)};Rn.iterable&&(Zt.prototype[Symbol.iterator]=Zt.prototype.entries);function Bm(t){if(!t._noBody){if(t.bodyUsed)return Promise.reject(new TypeError("Already read"));t.bodyUsed=!0}}function ER(t){return new Promise(function(e,n){t.onload=function(){e(t.result)},t.onerror=function(){n(t.error)}})}function kJ(t){var e=new FileReader,n=ER(e);return e.readAsArrayBuffer(t),n}function CJ(t){var e=new FileReader,n=ER(e),r=/charset=([A-Za-z0-9_-]+)/.exec(t.type),s=r?r[1]:"utf-8";return e.readAsText(t,s),n}function OJ(t){for(var e=new Uint8Array(t),n=new Array(e.length),r=0;r<e.length;r++)n[r]=String.fromCharCode(e[r]);return n.join("")}function eT(t){if(t.slice)return t.slice(0);var e=new Uint8Array(t.byteLength);return e.set(new Uint8Array(t)),e.buffer}function IR(){return this.bodyUsed=!1,this._initBody=function(t){this.bodyUsed=this.bodyUsed,this._bodyInit=t,t?typeof t=="string"?this._bodyText=t:Rn.blob&&Blob.prototype.isPrototypeOf(t)?this._bodyBlob=t:Rn.formData&&FormData.prototype.isPrototypeOf(t)?this._bodyFormData=t:Rn.searchParams&&URLSearchParams.prototype.isPrototypeOf(t)?this._bodyText=t.toString():Rn.arrayBuffer&&Rn.blob&&EJ(t)?(this._bodyArrayBuffer=eT(t.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):Rn.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(t)||xJ(t))?this._bodyArrayBuffer=eT(t):this._bodyText=t=Object.prototype.toString.call(t):(this._noBody=!0,this._bodyText=""),this.headers.get("content-type")||(typeof t=="string"?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):Rn.searchParams&&URLSearchParams.prototype.isPrototypeOf(t)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},Rn.blob&&(this.blob=function(){var t=Bm(this);if(t)return t;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))}),this.arrayBuffer=function(){if(this._bodyArrayBuffer){var t=Bm(this);return t||(ArrayBuffer.isView(this._bodyArrayBuffer)?Promise.resolve(this._bodyArrayBuffer.buffer.slice(this._bodyArrayBuffer.byteOffset,this._bodyArrayBuffer.byteOffset+this._bodyArrayBuffer.byteLength)):Promise.resolve(this._bodyArrayBuffer))}else{if(Rn.blob)return this.blob().then(kJ);throw new Error("could not read as ArrayBuffer")}},this.text=function(){var t=Bm(this);if(t)return t;if(this._bodyBlob)return CJ(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(OJ(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},Rn.formData&&(this.formData=function(){return this.text().then(PJ)}),this.json=function(){return this.text().then(JSON.parse)},this}var $J=["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"];function RJ(t){var e=t.toUpperCase();return $J.indexOf(e)>-1?e:t}function Ia(t,e){if(!(this instanceof Ia))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');e=e||{};var n=e.body;if(t instanceof Ia){if(t.bodyUsed)throw new TypeError("Already read");this.url=t.url,this.credentials=t.credentials,e.headers||(this.headers=new Zt(t.headers)),this.method=t.method,this.mode=t.mode,this.signal=t.signal,!n&&t._bodyInit!=null&&(n=t._bodyInit,t.bodyUsed=!0)}else this.url=String(t);if(this.credentials=e.credentials||this.credentials||"same-origin",(e.headers||!this.headers)&&(this.headers=new Zt(e.headers)),this.method=RJ(e.method||this.method||"GET"),this.mode=e.mode||this.mode||null,this.signal=e.signal||this.signal||function(){if("AbortController"in ln){var i=new AbortController;return i.signal}}(),this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&n)throw new TypeError("Body not allowed for GET or HEAD requests");if(this._initBody(n),(this.method==="GET"||this.method==="HEAD")&&(e.cache==="no-store"||e.cache==="no-cache")){var r=/([?&])_=[^&]*/;if(r.test(this.url))this.url=this.url.replace(r,"$1_="+new Date().getTime());else{var s=/\?/;this.url+=(s.test(this.url)?"&":"?")+"_="+new Date().getTime()}}}Ia.prototype.clone=function(){return new Ia(this,{body:this._bodyInit})};function PJ(t){var e=new FormData;return t.trim().split("&").forEach(function(n){if(n){var r=n.split("="),s=r.shift().replace(/\+/g," "),i=r.join("=").replace(/\+/g," ");e.append(decodeURIComponent(s),decodeURIComponent(i))}}),e}function NJ(t){var e=new Zt,n=t.replace(/\r?\n[\t ]+/g," ");return n.split("\r").map(function(r){return r.indexOf(`
|
|
614
|
-
`)===0?r.substr(1,r.length):r}).forEach(function(r){var s=r.split(":"),i=s.shift().trim();if(i){var a=s.join(":").trim();try{e.append(i,a)}catch(o){console.warn("Response "+o.message)}}}),e}IR.call(Ia.prototype);function As(t,e){if(!(this instanceof As))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');if(e||(e={}),this.type="default",this.status=e.status===void 0?200:e.status,this.status<200||this.status>599)throw new RangeError("Failed to construct 'Response': The status provided (0) is outside the range [200, 599].");this.ok=this.status>=200&&this.status<300,this.statusText=e.statusText===void 0?"":""+e.statusText,this.headers=new Zt(e.headers),this.url=e.url||"",this._initBody(t)}IR.call(As.prototype);As.prototype.clone=function(){return new As(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new Zt(this.headers),url:this.url})};As.error=function(){var t=new As(null,{status:200,statusText:""});return t.ok=!1,t.status=0,t.type="error",t};var MJ=[301,302,303,307,308];As.redirect=function(t,e){if(MJ.indexOf(e)===-1)throw new RangeError("Invalid status code");return new As(null,{status:e,headers:{location:t}})};var Yi=ln.DOMException;try{new Yi}catch{Yi=function(e,n){this.message=e,this.name=n;var r=Error(e);this.stack=r.stack},Yi.prototype=Object.create(Error.prototype),Yi.prototype.constructor=Yi}function xR(t,e){return new Promise(function(n,r){var s=new Ia(t,e);if(s.signal&&s.signal.aborted)return r(new Yi("Aborted","AbortError"));var i=new XMLHttpRequest;function a(){i.abort()}i.onload=function(){var u={statusText:i.statusText,headers:NJ(i.getAllResponseHeaders()||"")};s.url.indexOf("file://")===0&&(i.status<200||i.status>599)?u.status=200:u.status=i.status,u.url="responseURL"in i?i.responseURL:u.headers.get("X-Request-URL");var l="response"in i?i.response:i.responseText;setTimeout(function(){n(new As(l,u))},0)},i.onerror=function(){setTimeout(function(){r(new TypeError("Network request failed"))},0)},i.ontimeout=function(){setTimeout(function(){r(new TypeError("Network request timed out"))},0)},i.onabort=function(){setTimeout(function(){r(new Yi("Aborted","AbortError"))},0)};function o(u){try{return u===""&&ln.location.href?ln.location.href:u}catch{return u}}if(i.open(s.method,o(s.url),!0),s.credentials==="include"?i.withCredentials=!0:s.credentials==="omit"&&(i.withCredentials=!1),"responseType"in i&&(Rn.blob?i.responseType="blob":Rn.arrayBuffer&&(i.responseType="arraybuffer")),e&&typeof e.headers=="object"&&!(e.headers instanceof Zt||ln.Headers&&e.headers instanceof ln.Headers)){var c=[];Object.getOwnPropertyNames(e.headers).forEach(function(u){c.push(ac(u)),i.setRequestHeader(u,Ab(e.headers[u]))}),s.headers.forEach(function(u,l){c.indexOf(l)===-1&&i.setRequestHeader(l,u)})}else s.headers.forEach(function(u,l){i.setRequestHeader(l,u)});s.signal&&(s.signal.addEventListener("abort",a),i.onreadystatechange=function(){i.readyState===4&&s.signal.removeEventListener("abort",a)}),i.send(typeof s._bodyInit>"u"?null:s._bodyInit)})}xR.polyfill=!0;ln.fetch||(ln.fetch=xR,ln.Headers=Zt,ln.Request=Ia,ln.Response=As);var zm={};const kR="11434",CR=`http://127.0.0.1:${kR}`,LJ="0.6.3";var jJ=Object.defineProperty,DJ=(t,e,n)=>e in t?jJ(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Hm=(t,e,n)=>(DJ(t,typeof e!="symbol"?e+"":e,n),n);class Eb extends Error{constructor(e,n){super(e),this.error=e,this.status_code=n,this.name="ResponseError",Error.captureStackTrace&&Error.captureStackTrace(this,Eb)}}class UJ{constructor(e,n,r){Hm(this,"abortController"),Hm(this,"itr"),Hm(this,"doneCallback"),this.abortController=e,this.itr=n,this.doneCallback=r}abort(){this.abortController.abort()}async*[Symbol.asyncIterator](){for await(const e of this.itr){if("error"in e)throw new Error(e.error);if(yield e,e.done||e.status==="success"){this.doneCallback();return}}throw new Error("Did not receive done or success response in stream.")}}const Ib=async t=>{var r;if(t.ok)return;let e=`Error ${t.status}: ${t.statusText}`,n=null;if((r=t.headers.get("content-type"))!=null&&r.includes("application/json"))try{n=await t.json(),e=n.error||e}catch{console.log("Failed to parse error response as JSON")}else try{console.log("Getting text from response"),e=await t.text()||e}catch{console.log("Failed to get text from error response")}throw new Eb(e,t.status)};function FJ(){var t;if(typeof window<"u"&&window.navigator){const e=navigator;return"userAgentData"in e&&((t=e.userAgentData)!=null&&t.platform)?`${e.userAgentData.platform.toLowerCase()} Browser/${navigator.userAgent};`:navigator.platform?`${navigator.platform.toLowerCase()} Browser/${navigator.userAgent};`:`unknown Browser/${navigator.userAgent};`}else if(typeof process<"u")return`${process.arch} ${process.platform} Node.js/${process.version}`;return""}function BJ(t){if(t instanceof Headers){const e={};return t.forEach((n,r)=>{e[r]=n}),e}else return Array.isArray(t)?Object.fromEntries(t):t||{}}const zJ=(t,e)=>t[e],xb=async(t,e,n={})=>{const r={"Content-Type":"application/json",Accept:"application/json","User-Agent":`ollama-js/${LJ} (${FJ()})`};n.headers=BJ(n.headers);try{const i=new URL(e);if(i.protocol==="https:"&&i.hostname==="ollama.com"){const a=typeof process=="object"&&process!==null&&typeof zm=="object"&&zm!==null?zJ(zm,"OLLAMA_API_KEY"):void 0;!(n.headers.authorization||n.headers.Authorization)&&a&&(n.headers.Authorization=`Bearer ${a}`)}}catch(i){console.error("error parsing url",i)}const s=Object.fromEntries(Object.entries(n.headers).filter(([i])=>!Object.keys(r).some(a=>a.toLowerCase()===i.toLowerCase())));return n.headers={...r,...s},t(e,n)},Vm=async(t,e,n)=>{const r=await xb(t,e,{headers:n==null?void 0:n.headers});return await Ib(r),r},si=async(t,e,n,r)=>{const i=(o=>o!==null&&typeof o=="object"&&!Array.isArray(o))(n)?JSON.stringify(n):n,a=await xb(t,e,{method:"POST",body:i,signal:r==null?void 0:r.signal,headers:r==null?void 0:r.headers});return await Ib(a),a},HJ=async(t,e,n,r)=>{const s=await xb(t,e,{method:"DELETE",body:JSON.stringify(n),headers:r==null?void 0:r.headers});return await Ib(s),s},VJ=async function*(t){const e=new TextDecoder("utf-8");let n="";const r=t.getReader();for(;;){const{done:s,value:i}=await r.read();if(s)break;n+=e.decode(i,{stream:!0});const a=n.split(`
|
|
615
|
-
`);n=a.pop()??"";for(const o of a)try{yield JSON.parse(o)}catch{console.warn("invalid json: ",o)}}n+=e.decode();for(const s of n.split(`
|
|
616
|
-
`).filter(i=>i!==""))try{yield JSON.parse(s)}catch{console.warn("invalid json: ",s)}},KJ=t=>{if(!t)return CR;let e=t.includes("://");t.startsWith(":")&&(t=`http://127.0.0.1${t}`,e=!0),e||(t=`http://${t}`);const n=new URL(t);let r=n.port;r||(e?r=n.protocol==="https:"?"443":"80":r=kR);let s="";n.username&&(s=n.username,n.password&&(s+=`:${n.password}`),s+="@");let i=`${n.protocol}//${s}${n.hostname}:${r}${n.pathname}`;return i.endsWith("/")&&(i=i.slice(0,-1)),i};var WJ=Object.defineProperty,ZJ=(t,e,n)=>e in t?WJ(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Km=(t,e,n)=>(ZJ(t,typeof e!="symbol"?e+"":e,n),n);let OR=class{constructor(e){Km(this,"config"),Km(this,"fetch"),Km(this,"ongoingStreamedRequests",[]),this.config={host:"",headers:e==null?void 0:e.headers},e!=null&&e.proxy||(this.config.host=KJ((e==null?void 0:e.host)??CR)),this.fetch=(e==null?void 0:e.fetch)??fetch}abort(){for(const e of this.ongoingStreamedRequests)e.abort();this.ongoingStreamedRequests.length=0}async processStreamableRequest(e,n){n.stream=n.stream??!1;const r=`${this.config.host}/api/${e}`;if(n.stream){const i=new AbortController,a=await si(this.fetch,r,n,{signal:i.signal,headers:this.config.headers});if(!a.body)throw new Error("Missing body");const o=VJ(a.body),c=new UJ(i,o,()=>{const u=this.ongoingStreamedRequests.indexOf(c);u>-1&&this.ongoingStreamedRequests.splice(u,1)});return this.ongoingStreamedRequests.push(c),c}return await(await si(this.fetch,r,n,{headers:this.config.headers})).json()}async encodeImage(e){if(typeof e!="string"){const n=new Uint8Array(e);let r="";const s=n.byteLength;for(let i=0;i<s;i++)r+=String.fromCharCode(n[i]);return btoa(r)}return e}async generate(e){return e.images&&(e.images=await Promise.all(e.images.map(this.encodeImage.bind(this)))),this.processStreamableRequest("generate",e)}async chat(e){if(e.messages)for(const n of e.messages)n.images&&(n.images=await Promise.all(n.images.map(this.encodeImage.bind(this))));return this.processStreamableRequest("chat",e)}async create(e){return this.processStreamableRequest("create",{...e})}async pull(e){return this.processStreamableRequest("pull",{name:e.model,stream:e.stream,insecure:e.insecure})}async push(e){return this.processStreamableRequest("push",{name:e.model,stream:e.stream,insecure:e.insecure})}async delete(e){return await HJ(this.fetch,`${this.config.host}/api/delete`,{name:e.model},{headers:this.config.headers}),{status:"success"}}async copy(e){return await si(this.fetch,`${this.config.host}/api/copy`,{...e},{headers:this.config.headers}),{status:"success"}}async list(){return await(await Vm(this.fetch,`${this.config.host}/api/tags`,{headers:this.config.headers})).json()}async show(e){return await(await si(this.fetch,`${this.config.host}/api/show`,{...e},{headers:this.config.headers})).json()}async embed(e){return await(await si(this.fetch,`${this.config.host}/api/embed`,{...e},{headers:this.config.headers})).json()}async embeddings(e){return await(await si(this.fetch,`${this.config.host}/api/embeddings`,{...e},{headers:this.config.headers})).json()}async ps(){return await(await Vm(this.fetch,`${this.config.host}/api/ps`,{headers:this.config.headers})).json()}async version(){return await(await Vm(this.fetch,`${this.config.host}/api/version`,{headers:this.config.headers})).json()}async webSearch(e){if(!e.query||e.query.length===0)throw new Error("Query is required");return await(await si(this.fetch,"https://ollama.com/api/web_search",{...e},{headers:this.config.headers})).json()}async webFetch(e){if(!e.url||e.url.length===0)throw new Error("URL is required");return await(await si(this.fetch,"https://ollama.com/api/web_fetch",{...e},{headers:this.config.headers})).json()}};new OR;var qJ=class extends Es{constructor(e,n){const r=typeof e=="string"?{...n??{},model:e}:e??{};super(r);m(this,"model","llama3");m(this,"numa");m(this,"numCtx");m(this,"numBatch");m(this,"numGpu");m(this,"mainGpu");m(this,"lowVram");m(this,"f16Kv");m(this,"logitsAll");m(this,"vocabOnly");m(this,"useMmap");m(this,"useMlock");m(this,"embeddingOnly");m(this,"numThread");m(this,"numKeep");m(this,"seed");m(this,"numPredict");m(this,"topK");m(this,"topP");m(this,"tfsZ");m(this,"typicalP");m(this,"repeatLastN");m(this,"temperature");m(this,"repeatPenalty");m(this,"presencePenalty");m(this,"frequencyPenalty");m(this,"mirostat");m(this,"mirostatTau");m(this,"mirostatEta");m(this,"penalizeNewline");m(this,"streaming");m(this,"format");m(this,"keepAlive");m(this,"client");m(this,"checkOrPullModel",!1);m(this,"baseUrl","http://127.0.0.1:11434");m(this,"think");this._addVersion("@langchain/ollama","1.2.7"),this.baseUrl=r.baseUrl??Mt("OLLAMA_BASE_URL")??this.baseUrl,this.client=new OR({fetch:r.fetch,host:this.baseUrl,headers:r.headers}),this.model=r.model??this.model,this.numa=r.numa,this.numCtx=r.numCtx,this.numBatch=r.numBatch,this.numGpu=r.numGpu,this.mainGpu=r.mainGpu,this.lowVram=r.lowVram,this.f16Kv=r.f16Kv,this.logitsAll=r.logitsAll,this.vocabOnly=r.vocabOnly,this.useMmap=r.useMmap,this.useMlock=r.useMlock,this.embeddingOnly=r.embeddingOnly,this.numThread=r.numThread,this.numKeep=r.numKeep,this.seed=r.seed,this.numPredict=r.numPredict,this.topK=r.topK,this.topP=r.topP,this.tfsZ=r.tfsZ,this.typicalP=r.typicalP,this.repeatLastN=r.repeatLastN,this.temperature=r.temperature,this.repeatPenalty=r.repeatPenalty,this.presencePenalty=r.presencePenalty,this.frequencyPenalty=r.frequencyPenalty,this.mirostat=r.mirostat,this.mirostatTau=r.mirostatTau,this.mirostatEta=r.mirostatEta,this.penalizeNewline=r.penalizeNewline,this.streaming=r.streaming,this.format=r.format,this.keepAlive=r.keepAlive,this.think=r.think,this.checkOrPullModel=r.checkOrPullModel??this.checkOrPullModel}static lc_name(){return"ChatOllama"}_llmType(){return"ollama"}async pull(e,n){const{stream:r,insecure:s,logProgress:i}={stream:!0,...n};if(r)for await(const a of await this.client.pull({model:e,insecure:s,stream:r}))i&&console.log(a);else{const a=await this.client.pull({model:e,insecure:s});i&&console.log(a)}}bindTools(e,n){return this.withConfig({tools:e.map(r=>Vh(r)),...n})}getLsParams(e){var r,s;const n=this.invocationParams(e);return{ls_provider:"ollama",ls_model_name:this.model,ls_model_type:"chat",ls_temperature:((r=n.options)==null?void 0:r.temperature)??void 0,ls_max_tokens:((s=n.options)==null?void 0:s.num_predict)??void 0,ls_stop:e.stop}}invocationParams(e){var n;return{model:this.model,format:(e==null?void 0:e.format)??this.format,keep_alive:this.keepAlive,think:this.think,options:{numa:this.numa,num_ctx:this.numCtx,num_batch:this.numBatch,num_gpu:this.numGpu,main_gpu:this.mainGpu,low_vram:this.lowVram,f16_kv:this.f16Kv,logits_all:this.logitsAll,vocab_only:this.vocabOnly,use_mmap:this.useMmap,use_mlock:this.useMlock,embedding_only:this.embeddingOnly,num_thread:this.numThread,num_keep:this.numKeep,seed:this.seed,num_predict:this.numPredict,top_k:this.topK,top_p:this.topP,tfs_z:this.tfsZ,typical_p:this.typicalP,repeat_last_n:this.repeatLastN,temperature:this.temperature,repeat_penalty:this.repeatPenalty,presence_penalty:this.presencePenalty,frequency_penalty:this.frequencyPenalty,mirostat:this.mirostat,mirostat_tau:this.mirostatTau,mirostat_eta:this.mirostatEta,penalize_newline:this.penalizeNewline,stop:e==null?void 0:e.stop},tools:(n=e==null?void 0:e.tools)!=null&&n.length?e.tools.map(r=>Vh(r)):void 0}}async checkModelExistsOnMachine(e){const{models:n}=await this.client.list();return!!n.find(r=>r.name===e||r.name===`${e}:latest`)}async _generate(e,n,r){var a;(a=n.signal)==null||a.throwIfAborted(),this.checkOrPullModel&&(await this.checkModelExistsOnMachine(this.model)||await this.pull(this.model,{logProgress:!0}));let s;for await(const o of this._streamResponseChunks(e,n,r))s?s=Vs(s,o.message):s=o.message;const i=new De({id:s==null?void 0:s.id,content:(s==null?void 0:s.content)??"",additional_kwargs:s==null?void 0:s.additional_kwargs,tool_calls:s==null?void 0:s.tool_calls,response_metadata:s==null?void 0:s.response_metadata,usage_metadata:s==null?void 0:s.usage_metadata});return{generations:[{text:typeof i.content=="string"?i.content:"",message:i}]}}async*_streamResponseChunks(e,n,r){var u;this.checkOrPullModel&&(await this.checkModelExistsOnMachine(this.model)||await this.pull(this.model,{logProgress:!0}));const s=this.invocationParams(n),i=TJ(e),a={input_tokens:0,output_tokens:0,total_tokens:0},o=await this.client.chat({...s,messages:i,stream:!0});let c;for await(const l of o){if((u=n.signal)!=null&&u.aborted){this.client.abort();return}const{message:d,...f}=l;a.input_tokens+=f.prompt_eval_count??0,a.output_tokens+=f.eval_count??0,a.total_tokens=a.input_tokens+a.output_tokens,c=f;const h=this.think?d.thinking??d.content??"":d.content??"",p=new dr({text:h,message:wJ(d)});yield p,await(r==null?void 0:r.handleLLMNewToken(h,void 0,void 0,void 0,void 0,{chunk:p}))}yield new dr({text:"",message:new Ge({content:"",response_metadata:{...c,model_provider:"ollama"},usage_metadata:a})})}withStructuredOutput(e,n){let r,s;const{schema:i,name:a,includeRaw:o}={...n,schema:e},c=(n==null?void 0:n.method)??"jsonSchema";if(c==="functionCalling"){let u=a??"extract",l;const d=mt(i);Wt(i)||Or(i)?l={name:u,description:d.description,parameters:d}:typeof i.name=="string"&&typeof i.parameters=="object"&&i.parameters!=null?(l=i,u=i.name):l={name:u,description:i.description??"",parameters:i},r=this.bindTools([{type:"function",function:l}]).withConfig({ls_structured_output_format:{kwargs:{method:c},schema:Wt(i)||Or(i)?d:i}}),s=Tl(i,u)}else if(c==="jsonMode"||c==="jsonSchema"){s=Ko(i);const u=mt(i);r=this.withConfig({format:c==="jsonMode"?"json":u,ls_structured_output_format:{kwargs:{method:c},schema:u}})}else throw new TypeError(`Unrecognized structured output method '${c}'. Expected one of 'functionCalling', 'jsonMode', or 'jsonSchema'`);return tc(r,s,o,o?"StructuredOutputRunnable":"ChatOllamaStructuredOutput")}};const GJ=t=>BR.includes(t),JJ=t=>pT.includes(t),YJ=t=>{const{executeQuery:e,search:n,grep:r,readFile:s,fetchFeatureClusters:i,fetchFeatureClusterDetail:a}=t,o=ii(async({query:p,limit:g,groupByProcess:y})=>{const b=g??10,_=y??!0;let w;try{w=await n(p,{limit:b,enrich:!0})}catch{return"Search is not available. Please load a repository first."}if(w.length===0)return`No code found matching "${p}". Try different terms or use grep for exact patterns.`;const v=w.slice(0,b).map((k,C)=>{var X,se;const D=k.nodeId||"",B=k.name||((X=k.filePath)==null?void 0:X.split("/").pop())||"Unknown",z=k.label||"File",q=k.filePath||"",W=k.startLine?` (lines ${k.startLine}-${k.endLine})`:"",me=((se=k.sources)==null?void 0:se.join("+"))||"hybrid",M=k.score?` [score: ${k.score.toFixed(2)}]`:"";let Z="";if(k.connections){const Se=(k.connections.outgoing||[]).filter(O=>O==null?void 0:O.name).slice(0,3),ue=(k.connections.incoming||[]).filter(O=>O==null?void 0:O.name).slice(0,3),I=(O,ge)=>{const Ee=O.confidence?Math.round(O.confidence*100):100;return ge==="out"?`-[${O.type} ${Ee}%]-> ${O.name}`:`<-[${O.type} ${Ee}%]- ${O.name}`},T=Se.map(O=>I(O,"out")),L=ue.map(O=>I(O,"in"));(T.length||L.length)&&(Z=`
|
|
617
|
-
Connections: ${[...T,...L].join(", ")}`)}const re=k.cluster||"Unclustered",ae=(k.processes||[]).filter(Se=>Se.id&&Se.label);return{idx:C+1,nodeId:D,name:B,label:z,filePath:q,location:W,sources:me,score:M,connections:Z,clusterLabel:re,processes:ae}}),A=(k,C)=>{const D=C!=null&&C.step?` (step ${C.step}/${C.stepCount??"?"})`:"";return`[${k.idx}] ${k.label}: ${k.name}${k.score}${D}
|
|
618
|
-
ID: ${k.nodeId}
|
|
619
|
-
File: ${k.filePath}${k.location}
|
|
620
|
-
Cluster: ${k.clusterLabel}
|
|
621
|
-
Found by: ${k.sources}${k.connections}`};if(!_)return`Found ${w.length} matches:
|
|
622
|
-
|
|
623
|
-
${v.map(k=>A(k)).join(`
|
|
624
|
-
|
|
625
|
-
`)}`;const S=new Map,x="__no_process__";for(const k of v){if(k.processes.length===0){S.has(x)||S.set(x,{label:"No process",entries:[]}),S.get(x).entries.push({result:k});continue}for(const C of k.processes)S.has(C.id)||S.set(C.id,{label:C.label,stepCount:C.stepCount,entries:[]}),S.get(C.id).entries.push({result:k,step:C.step,stepCount:C.stepCount})}const E=Array.from(S.entries()).sort((k,C)=>{const D=k[1].entries.length;return C[1].entries.length-D}),$=[];$.push(`Found ${w.length} matches grouped by process:`),$.push("");for(const[k,C]of E){const D=C.stepCount?`, ${C.stepCount} steps`:"",B=k===x?`NO PROCESS (${C.entries.length} matches)`:`PROCESS: ${C.label} (${C.entries.length} matches${D})`;$.push(B),C.entries.forEach(z=>{const q=z.step?{id:k,label:C.label,step:z.step,stepCount:z.stepCount}:void 0;$.push(A(z.result,q))}),$.push("")}return $.join(`
|
|
626
|
-
`).trim()},{name:"search",description:"Search for code by keywords or concepts. Combines keyword matching and semantic understanding. Groups results by process with cluster context; use overview/explore for feature clusters.",schema:Vr({query:tr().describe('What you are looking for (e.g., "authentication middleware", "database connection")'),groupByProcess:Up().optional().nullable().describe("Group results by process (default: true)"),limit:ed().optional().nullable().describe("Max results to return (default: 10)")})}),c=ii(async({query:p,cypher:g})=>{try{if(g.includes("{{QUERY_VECTOR}}")){if(!p)return"Error: Your Cypher contains {{QUERY_VECTOR}} but you didn't provide a 'query' to embed. Add a natural language query.";try{const A=await n(p,{limit:10,mode:"semantic"});if(A.length===0)return"Semantic search returned no results. Embeddings may not be generated yet.";const S=A.map((x,E)=>{var $;return`[${E+1}] ${x.label||"File"}: ${x.name||(($=x.filePath)==null?void 0:$.split("/").pop())||"?"} (score: ${(x.score??0).toFixed(3)})
|
|
627
|
-
File: ${x.filePath||"n/a"}`}).join(`
|
|
628
|
-
`);return`Semantic search for "${p}" (${A.length} results):
|
|
629
|
-
|
|
630
|
-
${S}`}catch{return"Semantic search not available. Embeddings may not be generated. Use a non-vector Cypher query instead."}}const y=await e(g);if(y.length===0)return"Query returned no results.";const b=y[0],_=typeof b=="object"&&!Array.isArray(b)?Object.keys(b):[];if(_.length>0){const A=`| ${_.join(" | ")} |`,S=`|${_.map(()=>"---").join("|")}|`,x=y.slice(0,50).map($=>`| ${_.map(C=>{const D=$[C];if(D==null)return"";if(typeof D=="object")return JSON.stringify(D);const B=String(D).replace(/\|/g,"\\|");return B.length>60?B.slice(0,57)+"...":B}).join(" | ")} |`).join(`
|
|
631
|
-
`),E=y.length>50?`
|
|
632
|
-
|
|
633
|
-
_(${y.length-50} more rows)_`:"";return`**${y.length} results:**
|
|
634
|
-
|
|
635
|
-
${A}
|
|
636
|
-
${S}
|
|
637
|
-
${x}${E}`}const w=y.slice(0,50).map((A,S)=>`[${S+1}] ${JSON.stringify(A)}`),v=y.length>50?`
|
|
638
|
-
... (${y.length-50} more)`:"";return`${y.length} results:
|
|
639
|
-
${w.join(`
|
|
640
|
-
`)}${v}`}catch(y){return`Cypher error: ${y instanceof Error?y.message:String(y)}
|
|
641
|
-
|
|
642
|
-
Check your query syntax. Node tables include File, Folder, Function, Class, Interface, Method, CodeElement, Community, Process, FeatureCluster, Route, Tool, Section. Relation: CodeRelation with type property (CONTAINS, DEFINES, IMPORTS, CALLS, MEMBER_OF, STEP_IN_PROCESS, FEATURE_MEMBER_OF, FEATURE_DEPENDS_ON). Example: MATCH (m)-[:CodeRelation {type: 'FEATURE_MEMBER_OF'}]->(f:FeatureCluster) RETURN f.name, m.filePath`}},{name:"cypher",description:`Execute a Cypher query against the code graph. Use for structural queries like finding callers, tracing imports, class inheritance, or custom traversals.
|
|
643
|
-
|
|
644
|
-
Node tables: File, Folder, Function, Class, Interface, Method, CodeElement, Community, Process, FeatureCluster, Route, Tool, Section
|
|
645
|
-
Relation: CodeRelation (single table with 'type' property: CONTAINS, DEFINES, IMPORTS, CALLS, EXTENDS, IMPLEMENTS, MEMBER_OF, STEP_IN_PROCESS, FEATURE_MEMBER_OF, FEATURE_DEPENDS_ON)
|
|
646
|
-
|
|
647
|
-
Example queries:
|
|
648
|
-
- Functions calling a function: MATCH (caller:Function)-[:CodeRelation {type: 'CALLS'}]->(fn:Function {name: 'validate'}) RETURN caller.name, caller.filePath
|
|
649
|
-
- Feature members: MATCH (m)-[:CodeRelation {type: 'FEATURE_MEMBER_OF'}]->(f:FeatureCluster {name: 'Settings'}) RETURN m.name, m.filePath, m.startLine
|
|
650
|
-
- Feature dependencies: MATCH (a:FeatureCluster)-[:CodeRelation {type: 'FEATURE_DEPENDS_ON'}]->(b:FeatureCluster) RETURN a.name, b.name
|
|
651
|
-
- Class inheritance: MATCH (child:Class)-[:CodeRelation {type: 'EXTENDS'}]->(parent:Class) RETURN child.name, parent.name
|
|
652
|
-
- Classes implementing interface: MATCH (c:Class)-[:CodeRelation {type: 'IMPLEMENTS'}]->(i:Interface) RETURN c.name, i.name
|
|
653
|
-
- Files importing a file: MATCH (f:File)-[:CodeRelation {type: 'IMPORTS'}]->(target:File) WHERE target.name = 'utils.ts' RETURN f.name
|
|
654
|
-
- All connections (with confidence): MATCH (n)-[r:CodeRelation]-(m) WHERE n.name = 'MyClass' AND r.confidence > 0.8 RETURN m.name, r.type, r.confidence
|
|
655
|
-
- Find fuzzy matches: MATCH (n)-[r:CodeRelation]-(m) WHERE r.confidence < 0.8 RETURN n.name, r.reason
|
|
656
|
-
|
|
657
|
-
For semantic+graph queries, include {{QUERY_VECTOR}} placeholder and provide a 'query' parameter:
|
|
658
|
-
CALL QUERY_VECTOR_INDEX('CodeEmbedding', 'code_embedding_idx', {{QUERY_VECTOR}}, 10) YIELD node AS emb, distance
|
|
659
|
-
WITH emb, distance WHERE distance < 0.5
|
|
660
|
-
MATCH (n:Function {id: emb.nodeId}) RETURN n`,schema:Vr({cypher:tr().describe("The Cypher query to execute"),query:tr().optional().nullable().describe("Natural language query to embed (required if cypher contains {{QUERY_VECTOR}})")})}),u=ii(async({pattern:p,fileFilter:g,caseSensitive:y,maxResults:b})=>{try{try{new RegExp(p,y?"g":"gi")}catch(x){return`Invalid regex: ${p}. Error: ${x instanceof Error?x.message:String(x)}`}const _=b??100,w=g?`(?=.*${g.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}).*${p}`:p,v=await r(w,_);if(v.length===0)return`No matches for "${p}"${g?` in files matching "${g}"`:""}`;const A=v.map(x=>`${x.filePath}:${x.line}: ${x.text}`).join(`
|
|
661
|
-
`),S=v.length>=_?`
|
|
662
|
-
|
|
663
|
-
(Showing first ${_} results)`:"";return`Found ${v.length} matches:
|
|
664
|
-
|
|
665
|
-
${A}${S}`}catch(_){return`Grep error: ${_ instanceof Error?_.message:String(_)}`}},{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:Vr({pattern:tr().describe('Regex pattern to search for (e.g., "TODO", "console\\.log", "API_KEY")'),fileFilter:tr().optional().nullable().describe('Only search files containing this string (e.g., ".ts", "src/api")'),caseSensitive:Up().optional().nullable().describe("Case-sensitive search (default: false)"),maxResults:ed().optional().nullable().describe("Max results (default: 100)")})}),l=ii(async({filePath:p})=>{try{const g=await s(p),y=5e4;if(g.length>y){const _=g.split(`
|
|
666
|
-
`).length;return`File: ${p} (${_} lines, truncated)
|
|
667
|
-
|
|
668
|
-
${g.slice(0,y)}
|
|
669
|
-
|
|
670
|
-
... [truncated]`}const b=g.split(`
|
|
671
|
-
`).length;return`File: ${p} (${b} lines)
|
|
672
|
-
|
|
673
|
-
${g}`}catch(g){const y=g instanceof Error?g.message:String(g);return y.includes("not found")||y.includes("404")?`File not found: "${p}". Use grep to search for the correct path.`:`Error reading file: ${y}`}},{name:"read",description:"Read the full content of a file. Use to see source code after finding files via search or grep.",schema:Vr({filePath:tr().describe('File path to read (can be partial like "src/utils.ts")')})}),d=ii(async()=>{try{const p=`
|
|
674
|
-
MATCH (f:FeatureCluster)
|
|
675
|
-
RETURN f.id AS id, f.name AS name, f.slug AS slug, f.featureKind AS featureKind,
|
|
676
|
-
f.description AS description, f.signals AS signals, f.memberCount AS memberCount,
|
|
677
|
-
f.confidence AS confidence
|
|
678
|
-
ORDER BY f.memberCount DESC
|
|
679
|
-
LIMIT 200
|
|
680
|
-
`,g=`
|
|
681
|
-
MATCH (c:Community)
|
|
682
|
-
RETURN c.id AS id, c.label AS label, c.cohesion AS cohesion, c.symbolCount AS symbolCount, c.description AS description
|
|
683
|
-
ORDER BY c.symbolCount DESC
|
|
684
|
-
LIMIT 200
|
|
685
|
-
`,y=`
|
|
686
|
-
MATCH (p:Process)
|
|
687
|
-
RETURN p.id AS id, p.label AS label, p.processType AS type, p.stepCount AS stepCount, p.communities AS communities
|
|
688
|
-
ORDER BY p.stepCount DESC
|
|
689
|
-
LIMIT 200
|
|
690
|
-
`,b=`
|
|
691
|
-
MATCH (a)-[:CodeRelation {type: 'CALLS'}]->(b)
|
|
692
|
-
MATCH (a)-[:CodeRelation {type: 'MEMBER_OF'}]->(c1:Community)
|
|
693
|
-
MATCH (b)-[:CodeRelation {type: 'MEMBER_OF'}]->(c2:Community)
|
|
694
|
-
WHERE c1.id <> c2.id
|
|
695
|
-
RETURN c1.label AS \`from\`, c2.label AS \`to\`, COUNT(*) AS calls
|
|
696
|
-
ORDER BY calls DESC
|
|
697
|
-
LIMIT 15
|
|
698
|
-
`,_=`
|
|
699
|
-
MATCH (s)-[r:CodeRelation {type: 'STEP_IN_PROCESS'}]->(p:Process)
|
|
700
|
-
RETURN p.label AS label, COUNT(r) AS steps
|
|
701
|
-
ORDER BY steps DESC
|
|
702
|
-
LIMIT 10
|
|
703
|
-
`,w=`
|
|
704
|
-
MATCH (a:FeatureCluster)-[:CodeRelation {type: 'FEATURE_DEPENDS_ON'}]->(b:FeatureCluster)
|
|
705
|
-
RETURN a.name AS \`from\`, b.name AS \`to\`, COUNT(*) AS edges
|
|
706
|
-
ORDER BY edges DESC
|
|
707
|
-
LIMIT 15
|
|
708
|
-
`,v=i?i().catch(()=>({clusters:[]})):e(p).then(M=>({clusters:M.map(Z=>({id:Array.isArray(Z)?Z[0]:Z.id,name:Array.isArray(Z)?Z[1]:Z.name,slug:Array.isArray(Z)?Z[2]:Z.slug,featureKind:Array.isArray(Z)?Z[3]:Z.featureKind,description:Array.isArray(Z)?Z[4]:Z.description,signals:Array.isArray(Z)?Z[5]:Z.signals,memberCount:Array.isArray(Z)?Z[6]:Z.memberCount,confidence:Array.isArray(Z)?Z[7]:Z.confidence}))})),[A,S,x,E,$,k]=await Promise.all([v,e(g),e(y),e(b),e(_),e(w)]),C=Array.isArray(A.clusters)?A.clusters:[],D=C.map(M=>{const Z=M.confidence!==null&&M.confidence!==void 0?Number(M.confidence).toFixed(2):"";return`| ${M.name||M.slug||M.id||""} | ${M.featureKind||""} | ${M.memberCount??""} | ${Z} | ${M.description??""} |`}),B=k.map(M=>{const Z=Array.isArray(M)?M[0]:M.from,re=Array.isArray(M)?M[1]:M.to,ae=Array.isArray(M)?M[2]:M.edges;return`- ${Z} -> ${re} (${ae} edges)`}),z=S.map(M=>{const Z=Array.isArray(M)?M[1]:M.label,re=Array.isArray(M)?M[3]:M.symbolCount,ae=Array.isArray(M)?M[2]:M.cohesion,X=Array.isArray(M)?M[4]:M.description,se=ae!=null?Number(ae).toFixed(2):"";return`| ${Z||""} | ${re??""} | ${se} | ${X??""} |`}),q=x.map(M=>{const Z=Array.isArray(M)?M[1]:M.label,re=Array.isArray(M)?M[3]:M.stepCount,ae=Array.isArray(M)?M[2]:M.type,X=Array.isArray(M)?M[4]:M.communities,se=Array.isArray(X)?X.length:X?1:0;return`| ${Z||""} | ${re??""} | ${ae??""} | ${se} |`}),W=E.map(M=>{const Z=Array.isArray(M)?M[0]:M.from,re=Array.isArray(M)?M[1]:M.to,ae=Array.isArray(M)?M[2]:M.calls;return`- ${Z} -> ${re} (${ae} calls)`}),me=$.map(M=>{const Z=Array.isArray(M)?M[0]:M.label,re=Array.isArray(M)?M[1]:M.steps;return`- ${Z} (${re} steps)`});return[`FEATURE CLUSTERS (${C.length} total):`,"| Feature | Kind | Members | Confidence | Description |","| --- | --- | --- | --- | --- |",...D,"",`CLUSTERS (${S.length} total):`,"| Cluster | Symbols | Cohesion | Description |","| --- | --- | --- | --- |",...z,"",`PROCESSES (${x.length} total):`,"| Process | Steps | Type | Clusters |","| --- | --- | --- | --- |",...q,"","CLUSTER DEPENDENCIES:",...W.length>0?W:["- None found"],"","FEATURE DEPENDENCIES:",...B.length>0?B:["- None found"],"","CRITICAL PATHS:",...me.length>0?me:["- None found"]].join(`
|
|
709
|
-
`)}catch(p){return`Overview error: ${p instanceof Error?p.message:String(p)}`}},{name:"overview",description:"Codebase map showing feature clusters, structural clusters, processes, and dependencies.",schema:Vr({})}),f=ii(async({target:p,type:g})=>{var E,$;const y=p.replace(/'/g,"''");let b=g??null,_=null,w=null,v=null,A=null;const S=(k,C,D)=>Array.isArray(k)?k[C]:k[D],x=k=>(k==null?void 0:k.name)||(k==null?void 0:k.slug)||(k==null?void 0:k.id)||"Unknown feature";if(!b||b==="process"){const k=`
|
|
710
|
-
MATCH (p:Process)
|
|
711
|
-
WHERE p.id = '${y}' OR p.label = '${y}'
|
|
712
|
-
RETURN p.id AS id, p.label AS label, p.processType AS type, p.stepCount AS stepCount
|
|
713
|
-
LIMIT 1
|
|
714
|
-
`,C=await e(k);C.length>0&&(_=C[0],b="process")}if(!b||b==="feature"){const k=`
|
|
715
|
-
MATCH (f:FeatureCluster)
|
|
716
|
-
WHERE f.id = '${y}' OR f.name = '${y}' OR f.slug = '${y}'
|
|
717
|
-
RETURN f.id AS id, f.name AS name, f.slug AS slug, f.featureKind AS featureKind,
|
|
718
|
-
f.description AS description, f.memberCount AS memberCount, f.confidence AS confidence,
|
|
719
|
-
f.signals AS signals
|
|
720
|
-
LIMIT 1
|
|
721
|
-
`,C=await e(k);C.length>0&&(w=C[0],b="feature")}if(!b||b==="cluster"){const k=`
|
|
722
|
-
MATCH (c:Community)
|
|
723
|
-
WHERE c.id = '${y}' OR c.label = '${y}' OR c.heuristicLabel = '${y}'
|
|
724
|
-
RETURN c.id AS id, c.label AS label, c.cohesion AS cohesion, c.symbolCount AS symbolCount, c.description AS description
|
|
725
|
-
LIMIT 1
|
|
726
|
-
`,C=await e(k);C.length>0&&(v=C[0],b="cluster")}if(!b||b==="symbol"){const k=`
|
|
727
|
-
MATCH (n)
|
|
728
|
-
WHERE n.name = '${y}' OR n.id = '${y}' OR n.filePath = '${y}'
|
|
729
|
-
RETURN n.id AS id, n.name AS name, n.filePath AS filePath, label(n) AS nodeType
|
|
730
|
-
LIMIT 5
|
|
731
|
-
`,C=await e(k);C.length>0&&(A=C[0],b="symbol")}if(!b)return`Could not find "${p}" as a symbol, feature cluster, structural cluster, or process. Try search first.`;if(b==="process"){const k=S(_,0,"id"),C=S(_,1,"label"),D=S(_,2,"type"),B=S(_,3,"stepCount"),z=`
|
|
732
|
-
MATCH (s)-[r:CodeRelation {type: 'STEP_IN_PROCESS'}]->(p:Process {id: '${k.replace(/'/g,"''")}'})
|
|
733
|
-
RETURN s.name AS name, s.filePath AS filePath, r.step AS step
|
|
734
|
-
ORDER BY r.step
|
|
735
|
-
`,q=`
|
|
736
|
-
MATCH (c:Community)<-[:CodeRelation {type: 'MEMBER_OF'}]-(s)
|
|
737
|
-
MATCH (s)-[:CodeRelation {type: 'STEP_IN_PROCESS'}]->(p:Process {id: '${k.replace(/'/g,"''")}'})
|
|
738
|
-
RETURN DISTINCT c.id AS id, c.label AS label, c.description AS description
|
|
739
|
-
ORDER BY c.label
|
|
740
|
-
LIMIT 20
|
|
741
|
-
`,[W,me]=await Promise.all([e(z),e(q)]),M=W.map(re=>{const ae=S(re,0,"name"),X=S(re,1,"filePath");return`- ${S(re,2,"step")}. ${ae} (${X||"n/a"})`}),Z=me.map(re=>{const ae=S(re,1,"label"),X=S(re,2,"description");return`- ${ae}${X?` — ${X}`:""}`});return[`PROCESS: ${C}`,`Type: ${D||"n/a"}`,`Steps: ${B??W.length}`,"","STEPS:",...M.length>0?M:["- None found"],"","CLUSTERS TOUCHED:",...Z.length>0?Z:["- None found"]].join(`
|
|
742
|
-
`)}if(b==="feature"){const k=S(w,0,"id"),C=S(w,1,"name"),D=S(w,2,"slug"),B=S(w,3,"featureKind"),z=S(w,4,"description"),q=S(w,5,"memberCount"),W=S(w,6,"confidence"),me=S(w,7,"signals");let M=null;if(a)try{const j=await a(String(C||D||k));!j.error&&j.cluster&&(M=j)}catch{M=null}const Z=`
|
|
743
|
-
MATCH (m)-[r:CodeRelation {type: 'FEATURE_MEMBER_OF'}]->(f:FeatureCluster {id: '${String(k).replace(/'/g,"''")}'})
|
|
744
|
-
RETURN m.id AS id, m.name AS name, label(m) AS type, m.filePath AS filePath,
|
|
745
|
-
m.startLine AS startLine, m.endLine AS endLine, r.confidence AS confidence,
|
|
746
|
-
r.reason AS reason
|
|
747
|
-
ORDER BY type, filePath, startLine
|
|
748
|
-
LIMIT 80
|
|
749
|
-
`,re=`
|
|
750
|
-
MATCH (f:FeatureCluster {id: '${String(k).replace(/'/g,"''")}'})-[r:CodeRelation {type: 'FEATURE_DEPENDS_ON'}]->(d:FeatureCluster)
|
|
751
|
-
RETURN d.id AS id, d.name AS name, d.slug AS slug, r.confidence AS confidence
|
|
752
|
-
ORDER BY d.name
|
|
753
|
-
`,ae=`
|
|
754
|
-
MATCH (s:FeatureCluster)-[r:CodeRelation {type: 'FEATURE_DEPENDS_ON'}]->(f:FeatureCluster {id: '${String(k).replace(/'/g,"''")}'})
|
|
755
|
-
RETURN s.id AS id, s.name AS name, s.slug AS slug, r.confidence AS confidence
|
|
756
|
-
ORDER BY s.name
|
|
757
|
-
`,X=`
|
|
758
|
-
MATCH (m)-[:CodeRelation {type: 'FEATURE_MEMBER_OF'}]->(f:FeatureCluster {id: '${String(k).replace(/'/g,"''")}'}),
|
|
759
|
-
(m)-[:CodeRelation {type: 'STEP_IN_PROCESS'}]->(p:Process)
|
|
760
|
-
RETURN DISTINCT p.id AS id, p.label AS label, p.processType AS processType, p.stepCount AS stepCount
|
|
761
|
-
ORDER BY p.stepCount DESC
|
|
762
|
-
LIMIT 20
|
|
763
|
-
`,[se,Se,ue,I]=M?[[],[],[],[]]:await Promise.all([e(Z),e(re),e(ae),e(X)]),T=M==null?void 0:M.dependencies,L=Array.isArray(T)?[]:(T==null?void 0:T.outgoing)??[],O=Array.isArray(T)?[]:(T==null?void 0:T.incoming)??[],ge=((E=M==null?void 0:M.members)==null?void 0:E.map(j=>({name:j.name||j.id||j.nodeId||"Unknown",type:j.type||j.label||"Node",filePath:j.filePath||"n/a",startLine:j.startLine,endLine:j.endLine,confidence:j.confidence})))??se.map(j=>({name:S(j,1,"name")||S(j,0,"id"),type:S(j,2,"type"),filePath:S(j,3,"filePath")||"n/a",startLine:S(j,4,"startLine"),endLine:S(j,5,"endLine"),confidence:S(j,6,"confidence")})),Ee=ge.map(j=>{const _n=j.startLine?`:${j.startLine}${j.endLine?`-${j.endLine}`:""}`:"",Ae=j.confidence!==null&&j.confidence!==void 0?` (${Math.round(Number(j.confidence)*100)}%)`:"";return`- ${j.type}: ${j.name} (${j.filePath}${_n})${Ae}`}),nt=L.length>0?L:Se.map(j=>({id:S(j,0,"id"),name:S(j,1,"name"),slug:S(j,2,"slug"),confidence:S(j,3,"confidence")})),We=O.length>0?O:ue.map(j=>({id:S(j,0,"id"),name:S(j,1,"name"),slug:S(j,2,"slug"),confidence:S(j,3,"confidence")})),lt=nt.map(j=>`- ${x(j)}`),vt=We.map(j=>`- ${x(j)}`),$t=((M==null?void 0:M.processes)??I.map(j=>({id:S(j,0,"id"),label:S(j,1,"label"),heuristicLabel:void 0,processType:S(j,2,"processType"),stepCount:S(j,3,"stepCount")}))).map(j=>`- ${j.label||j.heuristicLabel||j.id||"Unknown process"} (${j.stepCount??"?"} steps)`),gn=W!=null?Number(W).toFixed(2):"n/a",_r=Array.isArray(me)?me.slice(0,8).join(", "):"";return[`FEATURE: ${C||D||k}`,`Kind: ${B||"feature"}`,`Members: ${q??ge.length}`,`Confidence: ${gn}`,`Description: ${z||(($=M==null?void 0:M.cluster)==null?void 0:$.description)||"n/a"}`,_r?`Signals: ${_r}`:"","","TOP MEMBERS:",...Ee.length>0?Ee:["- None found"],"","DEPENDS ON:",...lt.length>0?lt:["- None found"],"","USED BY:",...vt.length>0?vt:["- None found"],"","PROCESSES TOUCHING THIS FEATURE:",...$t.length>0?$t:["- None found"]].filter((j,_n,Ae)=>j!==""||Ae[_n-1]!=="").join(`
|
|
764
|
-
`)}if(b==="cluster"){const k=S(v,0,"id"),C=S(v,1,"label"),D=S(v,2,"cohesion"),B=S(v,3,"symbolCount"),z=S(v,4,"description"),q=`
|
|
765
|
-
MATCH (c:Community {id: '${k.replace(/'/g,"''")}'})<-[:CodeRelation {type: 'MEMBER_OF'}]-(m)
|
|
766
|
-
RETURN m.name AS name, m.filePath AS filePath, label(m) AS nodeType
|
|
767
|
-
LIMIT 50
|
|
768
|
-
`,W=`
|
|
769
|
-
MATCH (c:Community {id: '${k.replace(/'/g,"''")}'})<-[:CodeRelation {type: 'MEMBER_OF'}]-(s)
|
|
770
|
-
MATCH (s)-[:CodeRelation {type: 'STEP_IN_PROCESS'}]->(p:Process)
|
|
771
|
-
RETURN DISTINCT p.id AS id, p.label AS label, p.stepCount AS stepCount
|
|
772
|
-
ORDER BY p.stepCount DESC
|
|
773
|
-
LIMIT 20
|
|
774
|
-
`,[me,M]=await Promise.all([e(q),e(W)]),Z=me.map(ae=>{const X=S(ae,0,"name"),se=S(ae,1,"filePath");return`- ${S(ae,2,"nodeType")}: ${X} (${se||"n/a"})`}),re=M.map(ae=>{const X=S(ae,1,"label"),se=S(ae,2,"stepCount");return`- ${X} (${se} steps)`});return[`CLUSTER: ${C}`,`Symbols: ${B??me.length}`,`Cohesion: ${D!=null?Number(D).toFixed(2):"n/a"}`,`Description: ${z||"n/a"}`,"","TOP MEMBERS:",...Z.length>0?Z:["- None found"],"","PROCESSES TOUCHING THIS CLUSTER:",...re.length>0?re:["- None found"]].join(`
|
|
775
|
-
`)}if(b==="symbol"){const k=S(A,0,"id"),C=S(A,1,"name"),D=S(A,2,"filePath"),B=S(A,3,"nodeType");if(!GJ(B))return`Unknown node type "${B}" for symbol "${p}".`;const z=`
|
|
776
|
-
MATCH (n:${B} {id: '${String(k).replace(/'/g,"''")}'})
|
|
777
|
-
MATCH (n)-[:CodeRelation {type: 'MEMBER_OF'}]->(c:Community)
|
|
778
|
-
RETURN c.label AS label, c.description AS description
|
|
779
|
-
LIMIT 1
|
|
780
|
-
`,q=`
|
|
781
|
-
MATCH (n:${B} {id: '${String(k).replace(/'/g,"''")}'})
|
|
782
|
-
MATCH (n)-[:CodeRelation {type: 'FEATURE_MEMBER_OF'}]->(f:FeatureCluster)
|
|
783
|
-
RETURN f.name AS name, f.slug AS slug, f.featureKind AS kind
|
|
784
|
-
LIMIT 1
|
|
785
|
-
`,W=`
|
|
786
|
-
MATCH (n:${B} {id: '${String(k).replace(/'/g,"''")}'})
|
|
787
|
-
MATCH (n)-[r:CodeRelation {type: 'STEP_IN_PROCESS'}]->(p:Process)
|
|
788
|
-
RETURN p.label AS label, r.step AS step, p.stepCount AS stepCount
|
|
789
|
-
ORDER BY r.step
|
|
790
|
-
`,me=`
|
|
791
|
-
MATCH (n:${B} {id: '${String(k).replace(/'/g,"''")}'})
|
|
792
|
-
OPTIONAL MATCH (n)-[r1:CodeRelation]->(dst)
|
|
793
|
-
OPTIONAL MATCH (src)-[r2:CodeRelation]->(n)
|
|
794
|
-
RETURN
|
|
795
|
-
collect(DISTINCT {name: dst.name, type: r1.type, confidence: r1.confidence}) AS outgoing,
|
|
796
|
-
collect(DISTINCT {name: src.name, type: r2.type, confidence: r2.confidence}) AS incoming
|
|
797
|
-
LIMIT 1
|
|
798
|
-
`,[M,Z,re,ae]=await Promise.all([e(z),e(q),e(W),e(me)]),X=M.length>0?S(M[0],0,"label"):"Unclustered",se=M.length>0?S(M[0],1,"description"):"",Se=Z.length>0?S(Z[0],0,"name")||S(Z[0],1,"slug"):"",ue=Z.length>0?S(Z[0],2,"kind"):"",I=re.map(L=>{const O=S(L,0,"label"),ge=S(L,1,"step"),Ee=S(L,2,"stepCount");return`- ${O} (step ${ge}/${Ee??"?"})`});let T="None";if(ae.length>0){const L=ae[0],O=Array.isArray(L)?L[0]:L.outgoing||[],ge=Array.isArray(L)?L[1]:L.incoming||[],Ee=(O||[]).filter(Pe=>Pe&&Pe.name).slice(0,5),nt=(ge||[]).filter(Pe=>Pe&&Pe.name).slice(0,5),We=(Pe,$t)=>{const gn=Pe.confidence?Math.round(Pe.confidence*100):100;return $t==="out"?`-[${Pe.type} ${gn}%]-> ${Pe.name}`:`<-[${Pe.type} ${gn}%]- ${Pe.name}`},lt=Ee.map(Pe=>We(Pe,"out")),vt=nt.map(Pe=>We(Pe,"in"));(lt.length||vt.length)&&(T=[...lt,...vt].join(", "))}return[`SYMBOL: ${B} ${C}`,`ID: ${k}`,`File: ${D||"n/a"}`,`Feature: ${Se||"Unassigned"}${ue?` (${ue})`:""}`,`Cluster: ${X}${se?` — ${se}`:""}`,"","PROCESSES:",...I.length>0?I:["- None found"],"","CONNECTIONS:",T].join(`
|
|
799
|
-
`)}return`Unable to explore "${p}".`},{name:"explore",description:"Deep dive on a symbol, feature cluster, structural cluster, or process. Shows membership, participation, and connections.",schema:Vr({target:tr().describe("Name or ID of a symbol, feature cluster, cluster, or process"),type:uv(["symbol","feature","cluster","process"]).optional().nullable().describe("Optional target type (auto-detected if omitted)")})}),h=ii(async({target:p,direction:g,maxDepth:y,relationTypes:b,includeTests:_,minConfidence:w})=>{var xe;const v=Math.min(y??3,10),A=_??!1,S=w??.7,x=Q=>{if(!Q)return!1;const He=Q.toLowerCase();return He.includes(".test.")||He.includes(".spec.")||He.includes("__tests__")||He.includes("__mocks__")||He.endsWith(".test.ts")||He.endsWith(".test.tsx")||He.endsWith(".spec.ts")||He.endsWith(".spec.tsx")},E=["CALLS","IMPORTS","EXTENDS","IMPLEMENTS"],$=b&&b.length>0?b.filter(Q=>JJ(Q)):E;if($.length===0)return`No valid relation types provided. Valid types: ${pT.join(", ")}`;const k=$.map(Q=>`'${Q.replace(/'/g,"''")}'`).join(", "),C=g==="upstream"?"Files that DEPEND ON this (breakage risk)":"Dependencies this RELIES ON",D=p.includes("/"),B=p.replace(/'/g,"''"),z=D?`
|
|
800
|
-
MATCH (n)
|
|
801
|
-
WHERE n.filePath IS NOT NULL AND n.filePath CONTAINS '${B}'
|
|
802
|
-
RETURN n.id AS id, label(n) AS nodeType, n.filePath AS filePath
|
|
803
|
-
LIMIT 10
|
|
804
|
-
`:`
|
|
805
|
-
MATCH (n)
|
|
806
|
-
WHERE n.name = '${B}'
|
|
807
|
-
RETURN n.id AS id, label(n) AS nodeType, n.filePath AS filePath
|
|
808
|
-
LIMIT 10
|
|
809
|
-
`;let q;try{q=await e(z)}catch(Q){return`Error finding target "${p}": ${Q}`}if(!q||q.length===0)return`Could not find "${p}" in the codebase. Try using the search tool first to find the exact name.`;const W=q.map(Q=>Array.isArray(Q)?Q[2]:Q.filePath).filter(Boolean);if(q.length>1&&!p.includes("/"))return`⚠️ AMBIGUOUS TARGET: Multiple files named "${p}" found:
|
|
810
|
-
|
|
811
|
-
${W.map((Q,He)=>`${He+1}. ${Q}`).join(`
|
|
812
|
-
`)}
|
|
813
|
-
|
|
814
|
-
Please specify which file you mean by using a more specific path, e.g.:
|
|
815
|
-
- impact("${W[0].split("/").slice(-3).join("/")}")
|
|
816
|
-
- impact("${((xe=W[1])==null?void 0:xe.split("/").slice(-3).join("/"))||W[0]}")`;let me=q[0];if(p.includes("/")&&q.length>1){const Q=q.find(He=>{const dt=Array.isArray(He)?He[2]:He.filePath;return dt&&dt.toLowerCase().includes(p.toLowerCase())});if(Q)me=Q;else return`⚠️ AMBIGUOUS TARGET: Could not uniquely match "${p}". Found:
|
|
817
|
-
|
|
818
|
-
${W.map((He,dt)=>`${dt+1}. ${He}`).join(`
|
|
819
|
-
`)}
|
|
820
|
-
|
|
821
|
-
Please use a more specific path.`}const M=Array.isArray(me)?me[0]:me.id,Z=Array.isArray(me)?me[1]:me.nodeType,re=Array.isArray(me)?me[2]:me.filePath,ae="",X=Z==="File",se=[],Se=g==="upstream"?X?`
|
|
822
|
-
MATCH (affected)-[r:CodeRelation]->(callee)
|
|
823
|
-
WHERE callee.filePath = '${(re||p).replace(/'/g,"''")}'
|
|
824
|
-
AND r.type IN [${k}]
|
|
825
|
-
AND affected.filePath <> callee.filePath
|
|
826
|
-
AND (r.confidence IS NULL OR r.confidence >= ${S})
|
|
827
|
-
RETURN DISTINCT
|
|
828
|
-
affected.id AS id,
|
|
829
|
-
affected.name AS name,
|
|
830
|
-
label(affected) AS nodeType,
|
|
831
|
-
affected.filePath AS filePath,
|
|
832
|
-
affected.startLine AS startLine,
|
|
833
|
-
1 AS depth,
|
|
834
|
-
r.type AS edgeType,
|
|
835
|
-
r.confidence AS confidence,
|
|
836
|
-
r.reason AS reason
|
|
837
|
-
LIMIT 300
|
|
838
|
-
`:`
|
|
839
|
-
MATCH (target {id: '${M.replace(/'/g,"''")}'})
|
|
840
|
-
MATCH (affected)-[r:CodeRelation]->(target)
|
|
841
|
-
WHERE r.type IN [${k}]
|
|
842
|
-
AND (r.confidence IS NULL OR r.confidence >= ${S})
|
|
843
|
-
RETURN DISTINCT
|
|
844
|
-
affected.id AS id,
|
|
845
|
-
affected.name AS name,
|
|
846
|
-
label(affected) AS nodeType,
|
|
847
|
-
affected.filePath AS filePath,
|
|
848
|
-
affected.startLine AS startLine,
|
|
849
|
-
1 AS depth,
|
|
850
|
-
r.type AS edgeType,
|
|
851
|
-
r.confidence AS confidence,
|
|
852
|
-
r.reason AS reason
|
|
853
|
-
LIMIT 300
|
|
854
|
-
`:X?`
|
|
855
|
-
MATCH (caller)-[r:CodeRelation]->(affected)
|
|
856
|
-
WHERE caller.filePath = '${(re||p).replace(/'/g,"''")}'
|
|
857
|
-
AND r.type IN [${k}]
|
|
858
|
-
AND caller.filePath <> affected.filePath
|
|
859
|
-
AND (r.confidence IS NULL OR r.confidence >= ${S})
|
|
860
|
-
RETURN DISTINCT
|
|
861
|
-
affected.id AS id,
|
|
862
|
-
affected.name AS name,
|
|
863
|
-
label(affected) AS nodeType,
|
|
864
|
-
affected.filePath AS filePath,
|
|
865
|
-
affected.startLine AS startLine,
|
|
866
|
-
1 AS depth,
|
|
867
|
-
r.type AS edgeType,
|
|
868
|
-
r.confidence AS confidence,
|
|
869
|
-
r.reason AS reason
|
|
870
|
-
LIMIT 300
|
|
871
|
-
`:`
|
|
872
|
-
MATCH (target {id: '${M.replace(/'/g,"''")}'})
|
|
873
|
-
MATCH (target)-[r:CodeRelation]->(affected)
|
|
874
|
-
WHERE r.type IN [${k}]
|
|
875
|
-
AND (r.confidence IS NULL OR r.confidence >= ${S})
|
|
876
|
-
RETURN DISTINCT
|
|
877
|
-
affected.id AS id,
|
|
878
|
-
affected.name AS name,
|
|
879
|
-
label(affected) AS nodeType,
|
|
880
|
-
affected.filePath AS filePath,
|
|
881
|
-
affected.startLine AS startLine,
|
|
882
|
-
1 AS depth,
|
|
883
|
-
r.type AS edgeType,
|
|
884
|
-
r.confidence AS confidence,
|
|
885
|
-
r.reason AS reason
|
|
886
|
-
LIMIT 300
|
|
887
|
-
`;if(se.push(e(Se).then(Q=>Q).catch(Q=>[])),v>=2){const Q=g==="upstream"?`
|
|
888
|
-
MATCH (target {id: '${M.replace(/'/g,"''")}'})
|
|
889
|
-
MATCH (a)-[r1:CodeRelation]->(target)
|
|
890
|
-
MATCH (affected)-[r2:CodeRelation]->(a)
|
|
891
|
-
WHERE r1.type IN [${k}] AND r2.type IN [${k}]
|
|
892
|
-
AND affected.id <> target.id
|
|
893
|
-
AND (r1.confidence IS NULL OR r1.confidence >= ${S})
|
|
894
|
-
AND (r2.confidence IS NULL OR r2.confidence >= ${S})
|
|
895
|
-
RETURN DISTINCT
|
|
896
|
-
affected.id AS id,
|
|
897
|
-
affected.name AS name,
|
|
898
|
-
label(affected) AS nodeType,
|
|
899
|
-
affected.filePath AS filePath,
|
|
900
|
-
affected.startLine AS startLine,
|
|
901
|
-
2 AS depth,
|
|
902
|
-
r2.type AS edgeType,
|
|
903
|
-
r2.confidence AS confidence,
|
|
904
|
-
r2.reason AS reason
|
|
905
|
-
LIMIT 200
|
|
906
|
-
`:`
|
|
907
|
-
MATCH (target {id: '${M.replace(/'/g,"''")}'})
|
|
908
|
-
MATCH (target)-[r1:CodeRelation]->(a)
|
|
909
|
-
MATCH (a)-[r2:CodeRelation]->(affected)
|
|
910
|
-
WHERE r1.type IN [${k}] AND r2.type IN [${k}]
|
|
911
|
-
AND affected.id <> target.id
|
|
912
|
-
AND (r1.confidence IS NULL OR r1.confidence >= ${S})
|
|
913
|
-
AND (r2.confidence IS NULL OR r2.confidence >= ${S})
|
|
914
|
-
RETURN DISTINCT
|
|
915
|
-
affected.id AS id,
|
|
916
|
-
affected.name AS name,
|
|
917
|
-
label(affected) AS nodeType,
|
|
918
|
-
affected.filePath AS filePath,
|
|
919
|
-
affected.startLine AS startLine,
|
|
920
|
-
2 AS depth,
|
|
921
|
-
r2.type AS edgeType,
|
|
922
|
-
r2.confidence AS confidence,
|
|
923
|
-
r2.reason AS reason
|
|
924
|
-
LIMIT 200
|
|
925
|
-
`;se.push(e(Q).catch(He=>[]))}if(v>=3){const Q=g==="upstream"?`
|
|
926
|
-
MATCH (target {id: '${M.replace(/'/g,"''")}'})
|
|
927
|
-
MATCH (a)-[r1:CodeRelation]->(target)
|
|
928
|
-
MATCH (b)-[r2:CodeRelation]->(a)
|
|
929
|
-
MATCH (affected)-[r3:CodeRelation]->(b)
|
|
930
|
-
WHERE r1.type IN [${k}] AND r2.type IN [${k}] AND r3.type IN [${k}]
|
|
931
|
-
AND affected.id <> target.id AND affected.id <> a.id
|
|
932
|
-
AND (r1.confidence IS NULL OR r1.confidence >= ${S})
|
|
933
|
-
AND (r2.confidence IS NULL OR r2.confidence >= ${S})
|
|
934
|
-
AND (r3.confidence IS NULL OR r3.confidence >= ${S})
|
|
935
|
-
RETURN DISTINCT
|
|
936
|
-
affected.id AS id,
|
|
937
|
-
affected.name AS name,
|
|
938
|
-
label(affected) AS nodeType,
|
|
939
|
-
affected.filePath AS filePath,
|
|
940
|
-
affected.startLine AS startLine,
|
|
941
|
-
3 AS depth,
|
|
942
|
-
r3.type AS edgeType,
|
|
943
|
-
r3.confidence AS confidence,
|
|
944
|
-
r3.reason AS reason
|
|
945
|
-
LIMIT 100
|
|
946
|
-
`:`
|
|
947
|
-
MATCH (target {id: '${M.replace(/'/g,"''")}'})
|
|
948
|
-
MATCH (target)-[r1:CodeRelation]->(a)
|
|
949
|
-
MATCH (a)-[r2:CodeRelation]->(b)
|
|
950
|
-
MATCH (b)-[r3:CodeRelation]->(affected)
|
|
951
|
-
WHERE r1.type IN [${k}] AND r2.type IN [${k}] AND r3.type IN [${k}]
|
|
952
|
-
AND affected.id <> target.id AND affected.id <> a.id
|
|
953
|
-
AND (r1.confidence IS NULL OR r1.confidence >= ${S})
|
|
954
|
-
AND (r2.confidence IS NULL OR r2.confidence >= ${S})
|
|
955
|
-
AND (r3.confidence IS NULL OR r3.confidence >= ${S})
|
|
956
|
-
RETURN DISTINCT
|
|
957
|
-
affected.id AS id,
|
|
958
|
-
affected.name AS name,
|
|
959
|
-
label(affected) AS nodeType,
|
|
960
|
-
affected.filePath AS filePath,
|
|
961
|
-
affected.startLine AS startLine,
|
|
962
|
-
3 AS depth,
|
|
963
|
-
r3.type AS edgeType,
|
|
964
|
-
r3.confidence AS confidence,
|
|
965
|
-
r3.reason AS reason
|
|
966
|
-
LIMIT 100
|
|
967
|
-
`;se.push(e(Q).catch(He=>[]))}const ue=await Promise.all(se),I=new Map,T=[],L=new Set;ue.forEach((Q,He)=>{const dt=He+1;Q.forEach(Ve=>{const qt=Array.isArray(Ve)?Ve[0]:Ve.id,yr=Array.isArray(Ve)?Ve[3]:Ve.filePath;if(!(!A&&x(yr))&&qt&&!L.has(qt)){L.add(qt),I.has(dt)||I.set(dt,[]);const Li={id:qt,name:Array.isArray(Ve)?Ve[1]:Ve.name,nodeType:Array.isArray(Ve)?Ve[2]:Ve.nodeType,filePath:yr,startLine:Array.isArray(Ve)?Ve[4]:Ve.startLine,edgeType:Array.isArray(Ve)?Ve[5]:Ve.edgeType||"CALLS",confidence:Array.isArray(Ve)?Ve[6]:Ve.confidence??1,reason:Array.isArray(Ve)?Ve[7]:Ve.reason||""};I.get(dt).push(Li),T.push(qt)}})});const O=T.length;if(O===0){if(X){const Q=Ve=>Ve.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),dt=((re||p).split("/").pop()||p).replace(/\.[^/.]+$/,"");try{const qt=(await r(`\\b${Q(dt)}\\b`,15)).filter(yr=>yr.filePath!==re);if(qt.length>0){const yr=qt.map(Li=>`${Li.filePath}:${Li.line}: ${Li.text}`).join(`
|
|
968
|
-
`);return`No ${g} dependencies found for "${p}" (types: ${$.join(", ")}), but textual references were detected (graph may be incomplete):
|
|
969
|
-
|
|
970
|
-
${yr}${ae}`}}catch{}}return`No ${g} dependencies found for "${p}" (types: ${$.join(", ")}). This code appears to be ${g==="upstream"?"unused (not called by anything)":"self-contained (no outgoing dependencies)"}.${ae}`}const ge=I.get(1)||[],Ee=I.get(2)||[],nt=I.get(3)||[],We={high:0,medium:0,low:0};for(const Q of I.values())for(const He of Q){const dt=He.confidence??1;dt>=.9?We.high+=1:dt>=.8?We.medium+=1:We.low+=1}const vt=T.slice(0,500),Pe=vt.map(Q=>`'${Q.replace(/'/g,"''")}'`).join(", ");let $t=[],gn=[],_r=[];if(vt.length>0){const Q=`
|
|
971
|
-
MATCH (s)-[r:CodeRelation {type: 'STEP_IN_PROCESS'}]->(p:Process)
|
|
972
|
-
WHERE s.id IN [${Pe}]
|
|
973
|
-
RETURN p.label AS label, COUNT(DISTINCT s.id) AS hits, MIN(r.step) AS minStep, p.stepCount AS stepCount
|
|
974
|
-
ORDER BY hits DESC
|
|
975
|
-
LIMIT 20
|
|
976
|
-
`,He=`
|
|
977
|
-
MATCH (s)-[:CodeRelation {type: 'MEMBER_OF'}]->(c:Community)
|
|
978
|
-
WHERE s.id IN [${Pe}]
|
|
979
|
-
RETURN c.label AS label, COUNT(DISTINCT s.id) AS hits
|
|
980
|
-
ORDER BY hits DESC
|
|
981
|
-
LIMIT 20
|
|
982
|
-
`,dt=`
|
|
983
|
-
MATCH (s)-[:CodeRelation {type: 'FEATURE_MEMBER_OF'}]->(f:FeatureCluster)
|
|
984
|
-
WHERE s.id IN [${Pe}]
|
|
985
|
-
RETURN f.name AS label, f.featureKind AS kind, COUNT(DISTINCT s.id) AS hits
|
|
986
|
-
ORDER BY hits DESC
|
|
987
|
-
LIMIT 20
|
|
988
|
-
`,Ve=ge.map(Fe=>`'${Fe.id.replace(/'/g,"''")}'`).join(", "),qt=ge.length>0?`
|
|
989
|
-
MATCH (s)-[:CodeRelation {type: 'MEMBER_OF'}]->(c:Community)
|
|
990
|
-
WHERE s.id IN [${Ve}]
|
|
991
|
-
RETURN DISTINCT c.label AS label
|
|
992
|
-
`:"",yr=ge.length>0?`
|
|
993
|
-
MATCH (s)-[:CodeRelation {type: 'FEATURE_MEMBER_OF'}]->(f:FeatureCluster)
|
|
994
|
-
WHERE s.id IN [${Ve}]
|
|
995
|
-
RETURN DISTINCT f.name AS label
|
|
996
|
-
`:"",[Li,$R,RR,PR,NR]=await Promise.all([e(Q),e(He),qt?e(qt):Promise.resolve([]),e(dt),yr?e(yr):Promise.resolve([])]),kb=new Set;RR.forEach(Fe=>{const Rr=Array.isArray(Fe)?Fe[0]:Fe.label;Rr&&kb.add(Rr)});const Cb=new Set;NR.forEach(Fe=>{const Rr=Array.isArray(Fe)?Fe[0]:Fe.label;Rr&&Cb.add(Rr)}),$t=Li.map(Fe=>({label:Array.isArray(Fe)?Fe[0]:Fe.label,hits:Array.isArray(Fe)?Fe[1]:Fe.hits,minStep:Array.isArray(Fe)?Fe[2]:Fe.minStep,stepCount:Array.isArray(Fe)?Fe[3]:Fe.stepCount})),gn=$R.map(Fe=>{const Rr=Array.isArray(Fe)?Fe[0]:Fe.label,dp=Array.isArray(Fe)?Fe[1]:Fe.hits,hp=kb.has(Rr)?"direct":"indirect";return{label:Rr,hits:dp,impact:hp}}),_r=PR.map(Fe=>{const Rr=Array.isArray(Fe)?Fe[0]:Fe.label,dp=Array.isArray(Fe)?Fe[1]:Fe.kind,hp=Array.isArray(Fe)?Fe[2]:Fe.hits,MR=Cb.has(Rr)?"direct":"indirect";return{label:Rr,kind:dp,hits:hp,impact:MR}})}const j=ge.length,_n=$t.length,Ae=gn.length,be=_r.length;let Ie="LOW";j>=30||_n>=5||Ae>=5||be>=5||O>=200?Ie="CRITICAL":j>=15||_n>=3||Ae>=3||be>=3||O>=100?Ie="HIGH":(j>=5||O>=30)&&(Ie="MEDIUM");const ee=[`🔴 IMPACT: ${p} | ${g} | ${O} affected`,`Confidence: High ${We.high} | Medium ${We.medium} | Low ${We.low}`,"","AFFECTED PROCESSES:",...$t.length>0?$t.map(Q=>`- ${Q.label} - BROKEN at step ${Q.minStep??"?"} (${Q.hits} symbols, ${Q.stepCount??"?"} steps)`):["- None found"],"","AFFECTED FEATURE CLUSTERS:",..._r.length>0?_r.map(Q=>`- ${Q.label}${Q.kind?` (${Q.kind})`:""} - ${Q.impact}, ${Q.hits} symbols`):["- None found"],"","AFFECTED CLUSTERS:",...gn.length>0?gn.map(Q=>`- ${Q.label} (${Q.impact}, ${Q.hits} symbols)`):["- None found"],"",`RISK: ${Ie}`,`- Direct callers: ${j}`,`- Processes affected: ${_n}`,`- Feature clusters affected: ${be}`,`- Clusters affected: ${Ae}`,""],te=Q=>{var yr;const He=((yr=Q.filePath)==null?void 0:yr.split("/").pop())||"",dt=Q.startLine?`${He}:${Q.startLine}`:He,Ve=Math.round((Q.confidence??1)*100),qt=Ve<80?"[fuzzy]":"";return` ${Q.nodeType}|${Q.name}|${dt}|${Q.edgeType}|${Ve}%${qt}`},Ce=async Q=>{if(!Q.filePath||!Q.startLine)return null;try{const dt=(await s(Q.filePath)).split(`
|
|
997
|
-
`),Ve=Q.startLine-1;if(Ve<0||Ve>=dt.length)return null;let qt=dt[Ve].trim();return qt.length>80&&(qt=qt.slice(0,77)+"..."),qt}catch{return null}};if(ge.length>0){const Q=g==="upstream"?`d=1 (Directly DEPEND ON ${p}):`:`d=1 (${p} USES these):`;ee.push(Q);for(const He of ge.slice(0,15)){ee.push(te(He));const dt=await Ce(He);dt&&ee.push(` ↳ "${dt}"`)}ge.length>15&&ee.push(` ... +${ge.length-15} more`),ee.push("")}if(Ee.length>0){const Q=g==="upstream"?`d=2 (Indirectly DEPEND ON ${p}):`:`d=2 (${p} USES these indirectly):`;ee.push(Q),Ee.slice(0,15).forEach(He=>ee.push(te(He))),Ee.length>15&&ee.push(` ... +${Ee.length-15} more`),ee.push("")}return nt.length>0&&(ee.push("d=3 (Deep impact/dependency):"),nt.slice(0,5).forEach(Q=>ee.push(te(Q))),nt.length>5&&ee.push(` ... +${nt.length-5} more`),ee.push("")),ee.push("✅ GRAPH ANALYSIS COMPLETE (trusted)"),ee.push(`⚠️ Optional: grep("${p}") for dynamic patterns`),ee.push(""),ee.join(`
|
|
998
|
-
`)},{name:"impact",description:`Analyze the impact of changing a function, class, or file.
|
|
999
|
-
|
|
1000
|
-
Use when users ask:
|
|
1001
|
-
- "What would break if I changed X?"
|
|
1002
|
-
- "What depends on X?"
|
|
1003
|
-
- "Impact analysis for X"
|
|
1004
|
-
|
|
1005
|
-
Direction:
|
|
1006
|
-
- upstream: Find what CALLS/IMPORTS/EXTENDS this target (what would break)
|
|
1007
|
-
- downstream: Find what this target CALLS/IMPORTS/EXTENDS (dependencies)
|
|
1008
|
-
|
|
1009
|
-
Output format (compact tabular):
|
|
1010
|
-
Type|Name|File:Line|EdgeType|Confidence%
|
|
1011
|
-
|
|
1012
|
-
EdgeType: CALLS, IMPORTS, EXTENDS, IMPLEMENTS
|
|
1013
|
-
Confidence: 100% = certain, <80% = fuzzy match (may be false positive)
|
|
1014
|
-
|
|
1015
|
-
relationTypes filter (optional):
|
|
1016
|
-
- Default: CALLS, IMPORTS, EXTENDS, IMPLEMENTS (usage-based)
|
|
1017
|
-
- Can add CONTAINS, DEFINES for structural analysis
|
|
1018
|
-
|
|
1019
|
-
Additional output sections:
|
|
1020
|
-
- Affected processes (with step impact)
|
|
1021
|
-
- Affected feature clusters (product/domain areas)
|
|
1022
|
-
- Affected clusters (direct/indirect)
|
|
1023
|
-
- Risk summary (based on direct callers, processes, feature clusters, clusters)`,schema:Vr({target:tr().describe("Name of the function, class, or file to analyze"),direction:uv(["upstream","downstream"]).describe("upstream = what depends on this; downstream = what this depends on"),maxDepth:ed().optional().nullable().describe("Max traversal depth (default: 3, max: 10)"),relationTypes:lF(tr()).optional().nullable().describe("Filter by relation types: CALLS, IMPORTS, EXTENDS, IMPLEMENTS, CONTAINS, DEFINES (default: usage-based)"),includeTests:Up().optional().nullable().describe("Include test files in results (default: false, excludes .test.ts, .spec.ts, __tests__)"),minConfidence:ed().optional().nullable().describe("Minimum edge confidence 0-1 (default: 0.7, excludes fuzzy/inferred matches)")})});return[o,c,u,l,d,f,h]},tT=`You are CodraGraph, a Code Analysis Agent with access to a Knowledge Graph. Your responses MUST be grounded.
|
|
1024
|
-
|
|
1025
|
-
## ⚠️ MANDATORY: GROUNDING
|
|
1026
|
-
Every factual claim MUST include a citation.
|
|
1027
|
-
- File refs: [[src/auth.ts:45-60]] (line range with hyphen)
|
|
1028
|
-
- NO citation = NO claim. Say "I didn't find evidence" instead of guessing.
|
|
1029
|
-
|
|
1030
|
-
## ⚠️ MANDATORY: VALIDATION
|
|
1031
|
-
Every output MUST be validated.
|
|
1032
|
-
- Use cypher to validate the results and confirm completeness of context before final output.
|
|
1033
|
-
- NO validation = NO claim. Say "I didn't find evidence" instead of guessing.
|
|
1034
|
-
- Do not blindly trust readme or single source of truth. Always validate and cross-reference. Never be lazy.
|
|
1035
|
-
|
|
1036
|
-
## 🧠 CORE PROTOCOL
|
|
1037
|
-
You are an investigator. For each question:
|
|
1038
|
-
1. **Search** → Use cypher, search or grep to find relevant code
|
|
1039
|
-
2. **Read** → Use read to see the actual source
|
|
1040
|
-
3. **Trace** → Use cypher to follow connections in the graph
|
|
1041
|
-
4. **Cite** → Ground every finding with [[file:line]] or [[Type:Name]]
|
|
1042
|
-
5. **Validate** → Use cypher to validate the results and confirm completeness of context before final output. ( MUST DO )
|
|
1043
|
-
|
|
1044
|
-
## 🛠️ TOOLS
|
|
1045
|
-
- **\`search\`** — Hybrid search. Results grouped by process with cluster context.
|
|
1046
|
-
- **\`cypher\`** — Cypher queries against the graph. Use \`{{QUERY_VECTOR}}\` for vector search.
|
|
1047
|
-
- **\`grep\`** — Regex search. Best for exact strings, TODOs, error codes.
|
|
1048
|
-
- **\`read\`** — Read file content. Always use after search/grep to see full code.
|
|
1049
|
-
- **\`explore\`** — Deep dive on a symbol, feature cluster, structural cluster, or process.
|
|
1050
|
-
- **\`overview\`** — Codebase map showing feature clusters, structural clusters, and processes.
|
|
1051
|
-
- **\`impact\`** — Impact analysis. Shows affected processes, feature clusters, clusters, and risk level.
|
|
1052
|
-
|
|
1053
|
-
## 📊 GRAPH SCHEMA
|
|
1054
|
-
Nodes: File, Folder, Function, Class, Interface, Method, Community, Process, FeatureCluster, Route, Tool, Section
|
|
1055
|
-
Relations: \`CodeRelation\` with \`type\` property: CONTAINS, DEFINES, IMPORTS, CALLS, EXTENDS, IMPLEMENTS, MEMBER_OF, STEP_IN_PROCESS, FEATURE_MEMBER_OF, FEATURE_DEPENDS_ON
|
|
1056
|
-
|
|
1057
|
-
## 📐 GRAPH SEMANTICS (Important!)
|
|
1058
|
-
**Edge Types:**
|
|
1059
|
-
- \`CALLS\`: Method invocation OR constructor injection. If A receives B as parameter and uses it, A→B is CALLS. This is intentional simplification.
|
|
1060
|
-
- \`IMPORTS\`: File-level import/include statement.
|
|
1061
|
-
- \`EXTENDS/IMPLEMENTS\`: Class inheritance.
|
|
1062
|
-
|
|
1063
|
-
**Process Nodes:**
|
|
1064
|
-
- Process labels use format: "EntryPoint → Terminal" (e.g., "onCreate → showToast")
|
|
1065
|
-
- These are heuristic names from tracing execution flow, NOT application-defined names
|
|
1066
|
-
- Entry points are detected via export status, naming patterns, and framework conventions
|
|
1067
|
-
|
|
1068
|
-
**FeatureCluster Nodes:**
|
|
1069
|
-
- Feature clusters are human/product areas like Settings, Auth, AI, Billing, Admin, or Docs.
|
|
1070
|
-
- Use \`overview\` first to find relevant feature areas, then \`explore\` with \`type: "feature"\` to load focused files, line ranges, dependencies, and flows.
|
|
1071
|
-
- Prefer feature context before broad exploration when the user asks to refactor or understand an application area.
|
|
1072
|
-
|
|
1073
|
-
Cypher examples:
|
|
1074
|
-
- \`MATCH (f:Function) RETURN f.name LIMIT 10\`
|
|
1075
|
-
- \`MATCH (f:File)-[:CodeRelation {type: 'IMPORTS'}]->(g:File) RETURN f.name, g.name\`
|
|
1076
|
-
- \`MATCH (m)-[:CodeRelation {type: 'FEATURE_MEMBER_OF'}]->(f:FeatureCluster {name: 'Settings'}) RETURN m.name, m.filePath, m.startLine\`
|
|
1077
|
-
|
|
1078
|
-
## 📝CRITICAL RULES
|
|
1079
|
-
- **impact output is trusted.** Do NOT re-validate with cypher. Optionally run the suggested grep commands for dynamic patterns.
|
|
1080
|
-
- **Cite or retract.** Never state something you can't ground.
|
|
1081
|
-
- **Read before concluding.** Don't guess from names alone.
|
|
1082
|
-
- **Retry on failure.** If a tool fails, fix the input and try again.
|
|
1083
|
-
- **Cyfer tool validation** prefer using cyfer tool in anything that requires graph connections.
|
|
1084
|
-
- **OUTPUT STYLE** Prefer using tables and mermaid diagrams instead of long explanations.
|
|
1085
|
-
- ALWAYS USE MERMAID FOR VISUALIZATION AND STRUCTURING THE OUTPUT.
|
|
1086
|
-
|
|
1087
|
-
## 🎯 OUTPUT STYLE
|
|
1088
|
-
Think like a senior architect. Be concise—no fluff, short, precise and to the point.
|
|
1089
|
-
- Use tables for comparisons/rankings
|
|
1090
|
-
- Use mermaid diagrams for flows/dependencies
|
|
1091
|
-
- Surface deep insights: patterns, coupling, design decisions
|
|
1092
|
-
- End with **TL;DR** (short summary of the response, summing up the response and the most critical parts)
|
|
1093
|
-
|
|
1094
|
-
## MERMAID RULES
|
|
1095
|
-
When generating diagrams:
|
|
1096
|
-
- NO special characters in node labels: quotes, (), /, &, <, >
|
|
1097
|
-
- Wrap labels with spaces in quotes: A["My Label"]
|
|
1098
|
-
- Use simple IDs: A, B, C or auth, db, api
|
|
1099
|
-
- Flowchart: graph TD or graph LR (not flowchart)
|
|
1100
|
-
- Always test mentally: would this parse?
|
|
1101
|
-
|
|
1102
|
-
BAD: A[User's Data] --> B(Process & Save)
|
|
1103
|
-
GOOD: A["User Data"] --> B["Process and Save"]
|
|
1104
|
-
`,XJ=t=>{switch(t.provider){case"openai":{const e=t;if(!e.apiKey||e.apiKey.trim()==="")throw new Error("OpenAI API key is required but was not provided");return new dh({apiKey:e.apiKey,modelName:e.model,temperature:e.temperature??.1,maxTokens:e.maxTokens,configuration:{apiKey:e.apiKey,...e.baseUrl?{baseURL:e.baseUrl}:{}},streaming:!0})}case"azure-openai":{const e=t;return new zZ({azureOpenAIApiKey:e.apiKey,azureOpenAIApiInstanceName:QJ(e.endpoint),azureOpenAIApiDeploymentName:e.deploymentName,azureOpenAIApiVersion:e.apiVersion??"2024-12-01-preview",streaming:!0})}case"gemini":{const e=t;return new Gq({apiKey:e.apiKey,model:e.model,temperature:e.temperature??.1,maxOutputTokens:e.maxTokens,streaming:!0})}case"anthropic":{const e=t;return new XA({anthropicApiKey:e.apiKey,model:e.model,temperature:e.temperature??.1,maxTokens:e.maxTokens??8192,streaming:!0})}case"ollama":{const e=t;return new qJ({baseUrl:e.baseUrl??UR,model:e.model,temperature:e.temperature??.1,streaming:!0,numPredict:3e4,numCtx:32768})}case"openrouter":{const e=t;if(!e.apiKey||e.apiKey.trim()==="")throw new Error("OpenRouter API key is required but was not provided");return new dh({openAIApiKey:e.apiKey,apiKey:e.apiKey,modelName:e.model,temperature:e.temperature??.1,maxTokens:e.maxTokens,configuration:{apiKey:e.apiKey,baseURL:e.baseUrl??DR},streaming:!0})}case"minimax":{const e=t;if(!e.apiKey||e.apiKey.trim()==="")throw new Error("MiniMax API key is required but was not provided");return new XA({anthropicApiKey:e.apiKey,model:e.model,temperature:e.temperature??.1,maxTokens:e.maxTokens??8192,streaming:!0,clientOptions:{baseURL:"https://api.minimax.io/anthropic"}})}case"glm":{const e=t;if(!e.apiKey||e.apiKey.trim()==="")throw new Error("GLM API key is required but was not provided");return new dh({apiKey:e.apiKey,modelName:e.model,temperature:e.temperature??.1,maxTokens:e.maxTokens,configuration:{apiKey:e.apiKey,baseURL:e.baseUrl??"https://api.z.ai/api/coding/paas/v4"},streaming:!0})}default:throw new Error(`Unsupported provider: ${t.provider}`)}},QJ=t=>{try{const n=new URL(t).hostname,r=n.match(/^([^.]+)\.openai\.azure\.com/);return r?r[1]:n.split(".")[0]}catch{return t}},xX=(t,e,n)=>{const r=XJ(t),s=YJ(e),i=n?FR(tT,n):tT;return nK({llm:r,tools:s,messageModifier:new lr(i)})};async function*kX(t,e){var n,r,s,i,a,o;try{const c=e.map(g=>({role:g.role,content:g.content})),u=await t.stream({messages:c},{streamMode:["values","messages"],recursionLimit:50}),l=new Set,d=new Set;let f=c.length,h=0,p=!1;for await(const g of u){let y,b;if(Array.isArray(g)&&g.length===2&&typeof g[0]=="string"?[y,b]=g:Array.isArray(g)&&((n=g[0])!=null&&n._getType)?(y="messages",b=g):(y="values",b=g),y==="messages"){const[_]=Array.isArray(b)?b:[b];if(!_)continue;const w=((r=_._getType)==null?void 0:r.call(_))||_.type||((s=_.constructor)==null?void 0:s.name)||"unknown";if(w==="ai"||w==="AIMessage"||w==="AIMessageChunk"){const v=_.content,A=_.tool_calls||[];let S="";if(typeof v=="string"?S=v:Array.isArray(v)&&(S=v.filter(x=>x.type==="text"||typeof x=="string").map(x=>typeof x=="string"?x:x.text||"").join("")),S&&S.length>0){const x=!p||A.length>0||h>0;yield{type:x?"reasoning":"content",[x?"reasoning":"content"]:S}}if(A.length>0){p=!0,h+=A.length;for(const x of A){const E=x.id||`tool-${Date.now()}-${Math.random().toString(36).slice(2)}`;if(!l.has(E)){l.add(E);let $;try{$=(i=x.function)!=null&&i.arguments?JSON.parse(x.function.arguments):{}}catch{$={}}yield{type:"tool_call",toolCall:{id:E,name:x.name||((a=x.function)==null?void 0:a.name)||"unknown",args:x.args||$,status:"running"}}}}}}if(w==="tool"||w==="ToolMessage"){const v=_.tool_call_id||"";if(v&&!d.has(v)){d.add(v);const A=typeof _.content=="string"?_.content:JSON.stringify(_.content);yield{type:"tool_result",toolCall:{id:v,name:_.name||"tool",args:{},result:A,status:"completed"}},h=Math.max(0,h-1)}}}if(y==="values"&&(b!=null&&b.messages)){const _=b.messages||[];for(let w=f;w<_.length;w++){const v=_[w],A=((o=v._getType)==null?void 0:o.call(v))||v.type||"unknown";if((A==="ai"||A==="AIMessage")&&!l.size){const S=v.tool_calls||[];for(const x of S){const E=x.id||`tool-${Date.now()}`;l.has(E)||(h++,l.add(E),yield{type:"tool_call",toolCall:{id:E,name:x.name||"unknown",args:x.args||{},status:"running"}})}}if(A==="tool"||A==="ToolMessage"){const S=v.tool_call_id||"";if(S&&!d.has(S)){d.add(S);const x=typeof v.content=="string"?v.content:JSON.stringify(v.content);yield{type:"tool_result",toolCall:{id:S,name:v.name||"tool",args:{},result:x,status:"completed"}},h=Math.max(0,h-1)}}}f=_.length}}yield{type:"done"}}catch(c){yield{type:"error",error:c instanceof Error?c.message:String(c)}}}const CX=async(t,e)=>{var i;const n=e.map(a=>({role:a.role,content:a.content})),r=await t.invoke({messages:n}),s=r.messages[r.messages.length-1];return((i=s==null?void 0:s.content)==null?void 0:i.toString())??"No response generated."};export{tT as BASE_SYSTEM_PROMPT,XJ as createChatModel,xX as createGraphRAGAgent,CX as invokeAgent,kX as streamAgentResponse};
|